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
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Web.UI.WebControls.WebParts.TransformerTypeCollection.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Web.UI.WebControls.WebParts { sealed public partial class TransformerTypeCollection : System.Collections.ReadOnlyCollectionBase { #region Methods and constructors public bool Contains(Type value) { return default(bool); } public void CopyTo(Type[] array, int index) { } public int IndexOf(Type value) { return default(int); } public TransformerTypeCollection() { } public TransformerTypeCollection(System.Web.UI.WebControls.WebParts.TransformerTypeCollection existingTransformerTypes, System.Collections.ICollection transformerTypes) { } public TransformerTypeCollection(System.Collections.ICollection transformerTypes) { } #endregion #region Properties and indexers public Type this [int index] { get { return default(Type); } } #endregion #region Fields public readonly static System.Web.UI.WebControls.WebParts.TransformerTypeCollection Empty; #endregion } }
ndykman/CodeContracts
Microsoft.Research/Contracts/System.Web/Sources/System.Web.UI.WebControls.WebParts.TransformerTypeCollection.cs
C#
mit
3,050
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Umbraco.Core.Xml.XPath { /// <summary> /// Represents the type of a content that can be navigated via XPath. /// </summary> interface INavigableContentType { /// <summary> /// Gets the name of the content type. /// </summary> string Name { get; } /// <summary> /// Gets the field types of the content type. /// </summary> /// <remarks>This includes the attributes and the properties.</remarks> INavigableFieldType[] FieldTypes { get; } } }
lars-erik/Umbraco-CMS
src/Umbraco.Core/Xml/XPath/INavigableContentType.cs
C#
mit
637
package com.mozu.api.utils; public class Endpoints { public static final String AUTH_URL = "api/platform/applications/authtickets"; public static final String AUTH_REFRESH_URL = "api/platform/applications/authtickets/refresh-ticket/%s"; public static final String TENANT_END_POINT = "api/platform/tenants"; public static final String SITES_END_POINT = "api/platform/tenants/%s/sites"; public static final String ATTRIBUTE_END_POINT = "api/commerce/catalog/admin/attributedefinition/attributes"; public static final String VOCABULARY_END_POINT = "api/commerce/catalog/admin/attributedefinition/attributes/%s/VocabularyValues"; public static final String PRODUCTTYPE_END_POINT = "api/commerce/catalog/admin/attributedefinition/producttypes"; public static final String ORDER_END_POINT = "api/commerce/orders"; public static final String APPLICATIONSTATUS_END_POINT = "api/commerce/settings/applicationstatus"; public static final String MZDB_APP_DATA_ENDPOINT = "api/platform/appdata"; public static final String MZDB_SITE_DATA_ENDPOINT = "api/platform/sitedata"; public static final String MZDB_TENANT_DATA_ENDPOINT = "api/platform/tenantdata"; }
carsonreinke/mozu-java-sdk
src/main/java/com/mozu/api/utils/Endpoints.java
Java
mit
1,200
/*============================================================================= Copyright (c) 2001-2011 Joel de Guzman 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_PP_IS_ITERATING #if !defined(FUSION_MAKE_TUPLE_10032005_0843) #define FUSION_MAKE_TUPLE_10032005_0843 #include <boost/preprocessor/iterate.hpp> #include <boost/preprocessor/repetition/enum_params.hpp> #include <boost/preprocessor/repetition/enum_binary_params.hpp> #include <boost/fusion/tuple/detail/tuple.hpp> #include <boost/fusion/support/detail/as_fusion_element.hpp> namespace boost { namespace fusion { BOOST_FUSION_GPU_ENABLED inline tuple<> make_tuple() { return tuple<>(); } }} #if !defined(BOOST_FUSION_DONT_USE_PREPROCESSED_FILES) #include <boost/fusion/tuple/detail/preprocessed/make_tuple.hpp> #else #if defined(__WAVE__) && defined(BOOST_FUSION_CREATE_PREPROCESSED_FILES) #pragma wave option(preserve: 2, line: 0, output: "preprocessed/make_tuple" FUSION_MAX_VECTOR_SIZE_STR ".hpp") #endif /*============================================================================= Copyright (c) 2001-2011 Joel de Guzman 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) This is an auto-generated file. Do not edit! ==============================================================================*/ #if defined(__WAVE__) && defined(BOOST_FUSION_CREATE_PREPROCESSED_FILES) #pragma wave option(preserve: 1) #endif namespace boost { namespace fusion { #define BOOST_FUSION_AS_FUSION_ELEMENT(z, n, data) \ typename detail::as_fusion_element<BOOST_PP_CAT(T, n)>::type #define BOOST_PP_FILENAME_1 <boost/fusion/tuple/detail/make_tuple.hpp> #define BOOST_PP_ITERATION_LIMITS (1, FUSION_MAX_VECTOR_SIZE) #include BOOST_PP_ITERATE() #undef BOOST_FUSION_AS_FUSION_ELEMENT }} #if defined(__WAVE__) && defined(BOOST_FUSION_CREATE_PREPROCESSED_FILES) #pragma wave option(output: null) #endif #endif // BOOST_FUSION_DONT_USE_PREPROCESSED_FILES #endif #else // defined(BOOST_PP_IS_ITERATING) /////////////////////////////////////////////////////////////////////////////// // // Preprocessor vertical repetition code // /////////////////////////////////////////////////////////////////////////////// #define N BOOST_PP_ITERATION() template <BOOST_PP_ENUM_PARAMS(N, typename T)> BOOST_FUSION_GPU_ENABLED inline tuple<BOOST_PP_ENUM(N, BOOST_FUSION_AS_FUSION_ELEMENT, _)> make_tuple(BOOST_PP_ENUM_BINARY_PARAMS(N, T, const& arg)) { return tuple<BOOST_PP_ENUM(N, BOOST_FUSION_AS_FUSION_ELEMENT, _)>( BOOST_PP_ENUM_PARAMS(N, arg)); } #undef N #endif // defined(BOOST_PP_IS_ITERATING)
nginnever/zogminer
tests/deps/boost/fusion/tuple/detail/make_tuple.hpp
C++
mit
3,058
<?php namespace Bolt\Helpers; use Cocur\Slugify\Slugify; class Str { /** * Returns a "safe" version of the given string - basically only US-ASCII and * numbers. Needed because filenames and titles and such, can't use all characters. * * @param string $str * @param boolean $strict * @param string $extrachars * * @return string */ public static function makeSafe($str, $strict = false, $extrachars = '') { $str = str_replace('&amp;', '', $str); $delim = '/'; if ($extrachars != '') { $extrachars = preg_quote($extrachars, $delim); } if ($strict) { $slugify = Slugify::create('/[^a-z0-9_' . $extrachars . ' -]+/'); $str = $slugify->slugify($str, ''); $str = str_replace(' ', '-', $str); } else { // Allow Uppercase and don't convert spaces to dashes $slugify = Slugify::create('/[^a-zA-Z0-9_.,' . $extrachars . ' -]+/', ['lowercase' => false]); $str = $slugify->slugify($str, ''); } return $str; } /** * Replace the first occurence of a string only. Behaves like str_replace, but * replaces _only_ the _first_ occurence. * * @see http://stackoverflow.com/a/2606638 * * @param string $search * @param string $replace * @param string $subject * * @return string */ public static function replaceFirst($search, $replace, $subject) { $pos = strpos($subject, $search); if ($pos !== false) { $subject = substr_replace($subject, $replace, $pos, strlen($search)); } return $subject; } /** * Add 'soft hyphens' &shy; to a string, so that it won't break layout in HTML when * using strings without spaces or dashes. Only breaks in long (> 19 chars) words. * * @param string $str * * @return string */ public static function shyphenate($str) { $res = preg_match_all('/([a-z0-9]{19,})/i', $str, $matches); if ($res) { foreach ($matches[1] as $key => $match) { $str = str_replace($match, wordwrap($match, 10, '&shy;', true), $str); } } return $str; } }
CarsonF/bolt
src/Helpers/Str.php
PHP
mit
2,298
import Ember from 'ember-metal'; // Ember as namespace import { A as emberA, typeOf, String as StringUtils, Namespace, Object as EmberObject } from 'ember-runtime'; /** @module ember @submodule ember-extension-support */ /** The `ContainerDebugAdapter` helps the container and resolver interface with tools that debug Ember such as the [Ember Extension](https://github.com/tildeio/ember-extension) for Chrome and Firefox. This class can be extended by a custom resolver implementer to override some of the methods with library-specific code. The methods likely to be overridden are: * `canCatalogEntriesByType` * `catalogEntriesByType` The adapter will need to be registered in the application's container as `container-debug-adapter:main`. Example: ```javascript Application.initializer({ name: "containerDebugAdapter", initialize(application) { application.register('container-debug-adapter:main', require('app/container-debug-adapter')); } }); ``` @class ContainerDebugAdapter @namespace Ember @extends Ember.Object @since 1.5.0 @public */ export default EmberObject.extend({ /** The resolver instance of the application being debugged. This property will be injected on creation. @property resolver @default null @public */ resolver: null, /** Returns true if it is possible to catalog a list of available classes in the resolver for a given type. @method canCatalogEntriesByType @param {String} type The type. e.g. "model", "controller", "route". @return {boolean} whether a list is available for this type. @public */ canCatalogEntriesByType(type) { if (type === 'model' || type === 'template') { return false; } return true; }, /** Returns the available classes a given type. @method catalogEntriesByType @param {String} type The type. e.g. "model", "controller", "route". @return {Array} An array of strings. @public */ catalogEntriesByType(type) { let namespaces = emberA(Namespace.NAMESPACES); let types = emberA(); let typeSuffixRegex = new RegExp(`${StringUtils.classify(type)}$`); namespaces.forEach(namespace => { if (namespace !== Ember) { for (let key in namespace) { if (!namespace.hasOwnProperty(key)) { continue; } if (typeSuffixRegex.test(key)) { let klass = namespace[key]; if (typeOf(klass) === 'class') { types.push(StringUtils.dasherize(key.replace(typeSuffixRegex, ''))); } } } } }); return types; } });
duggiefresh/ember.js
packages/ember-extension-support/lib/container_debug_adapter.js
JavaScript
mit
2,656
* { box-sizing: border-box; -webkit-overflow-scrolling: touch; -webkit-tap-highlight-color: rgba(0, 0, 0, 0); -webkit-text-size-adjust: none; -webkit-touch-callout: none; -webkit-font-smoothing: antialiased; } .progress { background-color: #000; height: 2px; left: 0px; position: fixed; right: 0px; top: 0px; -webkit-transition: width 0.2s, opacity 0.4s; transition: width 0.2s, opacity 0.4s; width: 0%; z-index: 999999; } html, body { height: 100%; } body { -moz-osx-font-smoothing: grayscale; -webkit-font-smoothing: antialiased; font-family: 'Source Sans Pro', 'Helvetica Neue', Arial, sans-serif; font-size: 15px; letter-spacing: 0; margin: 0; overflow-x: hidden; color: #000; } img { max-width: 100%; } kbd { display: inline-block; padding: 3px 5px; margin-bottom: 3px; font-size: 12px !important; line-height: 12px; vertical-align: middle; border: solid 1px #ccc; border-radius: 3px; } /* navbar */ nav { position: absolute; right: 0; left: 0; z-index: 10; margin: 25px 60px 0 0; text-align: right; } nav p { margin: 0; } nav ul, nav li { list-style: none; display: inline-block; margin: 0; } nav a { margin: 0 1em; padding: 5px 0; font-size: 16px; text-decoration: none; color: inherit; -webkit-transition: color .3s; transition: color .3s; } nav a:hover { color: #000; } nav a.active { color: #000; border-bottom: 2px solid #000; } /* navbar dropdown */ nav li { position: relative; display: inline-block; } nav li ul { background-color: rgba(255, 255, 255, 0.6); border: 1px solid #000; opacity: 0; overflow: hidden; padding: 0; position: absolute; right: 1em; top: 26px; -webkit-transform-origin: 100% 0%; transform-origin: 100% 0%; -webkit-transform: scale(1, 0); transform: scale(1, 0); -webkit-transition: opacity .4s ease-out, -webkit-transform .2s ease; transition: opacity .4s ease-out, -webkit-transform .2s ease; transition: opacity .4s ease-out, transform .2s ease; transition: opacity .4s ease-out, transform .2s ease, -webkit-transform .2s ease; -webkit-transition-delay: .3s; transition-delay: .3s; } nav li ul li { display: block; font-size: 14px; margin: 0; padding: 4px 10px; white-space: nowrap; } nav li ul a { display: block; margin: 0; padding: 0; } nav li ul a.active { border-bottom: 0; } nav li:hover ul { opacity: 1; -webkit-transform: scale(1, 1); transform: scale(1, 1); -webkit-transition: opacity .4s ease, -webkit-transform .2s ease-out; transition: opacity .4s ease, -webkit-transform .2s ease-out; transition: opacity .4s ease, transform .2s ease-out; transition: opacity .4s ease, transform .2s ease-out, -webkit-transform .2s ease-out; -webkit-transition-delay: 0; transition-delay: 0; } nav.no-badge { margin-right: 25px; } /* github corner */ .github-corner { position: fixed; top: 0; right: 0; z-index: 1; text-decoration: none; border-bottom: 0; } .github-corner svg { color: #fff; height: 80px; width: 80px; fill: #000; } .github-corner:hover .octo-arm { -webkit-animation: octocat-wave 560ms ease-in-out; animation: octocat-wave 560ms ease-in-out; } /* main */ main { width: 100vw; height: 100%; position: relative; } .anchor { text-decoration: none; -webkit-transition: all .3s; transition: all .3s; display: inline-block; } .anchor span { color: #000; } .anchor:hover { text-decoration: underline; } /* sidebar */ .sidebar { border-right: 1px solid rgba(0, 0, 0, .07); overflow-y: auto; padding: 40px 0; top: 0; bottom: 0; left: 0; position: absolute; -webkit-transition: -webkit-transform 250ms ease-out; transition: -webkit-transform 250ms ease-out; transition: transform 250ms ease-out; transition: transform 250ms ease-out, -webkit-transform 250ms ease-out; width: 300px; z-index: 20; } .sidebar ul { margin: 0; padding: 0; } .sidebar ul, .sidebar ul li { list-style: none; } .sidebar ul li a { display: block; border-bottom: none; } .sidebar ul li ul { padding-left: 20px; } /* sidebar toggle */ .sidebar-toggle { background-color: transparent; border: 0; outline: none; bottom: 0; left: 0; position: absolute; text-align: center; -webkit-transition: opacity .3s; transition: opacity .3s; width: 30px; z-index: 30; outline: none; width: 284px; padding: 10px; background-color: rgba(255, 255, 255, 0.8); } .sidebar-toggle .sidebar-toggle-button:hover { opacity: .4; } .sidebar-toggle span { background-color: #000; display: block; width: 16px; height: 2px; margin-bottom: 4px; } body.sticky .sidebar, body.sticky .sidebar-toggle { position: fixed; } /* main content */ .content { top: 0; right: 0; bottom: 0; left: 300px; position: absolute; padding-top: 20px; -webkit-transition: left 250ms ease; transition: left 250ms ease; } /* markdown content found on pages */ .markdown-section { position: relative; margin: 0 auto; max-width: 800px; padding: 20px 15px 40px 15px; } .markdown-section > * { box-sizing: border-box; font-size: inherit; } .markdown-section >:first-child { margin-top: 0!important; } .markdown-section table { display: block; width: 100%; overflow: auto; border-spacing: 0; border-collapse: collapse; margin-bottom: 1em; } .markdown-section th { font-weight: 700; padding: 6px 13px; border: 1px solid #ddd; } .markdown-section td { padding: 6px 13px; border: 1px solid #ddd; } .markdown-section tr { border-top: 1px solid #ccc; } .markdown-section tr:nth-child(2n) { background-color: #f8f8f8; } body.close .sidebar { -webkit-transform: translateX(-300px); transform: translateX(-300px); } body.close .sidebar-toggle { width: auto; } body.close .content { left: 0; } @media (max-width: 600px) { .github-corner, .sidebar-toggle, .sidebar { position: fixed; } nav { margin-top: 16px; } nav li ul { top: 30px; } main { height: auto; overflow-x: hidden; } .sidebar { left: -300px; -webkit-transition: -webkit-transform 250ms ease-out; transition: -webkit-transform 250ms ease-out; transition: transform 250ms ease-out; transition: transform 250ms ease-out, -webkit-transform 250ms ease-out; } .content { left: 0; max-width: 100vw; position: static; -webkit-transition: -webkit-transform 250ms ease; transition: -webkit-transform 250ms ease; transition: transform 250ms ease; transition: transform 250ms ease, -webkit-transform 250ms ease; } nav, .github-corner { -webkit-transition: -webkit-transform 250ms ease-out; transition: -webkit-transform 250ms ease-out; transition: transform 250ms ease-out; transition: transform 250ms ease-out, -webkit-transform 250ms ease-out; } .sidebar-toggle { width: auto; background-color: transparent; } body.close .sidebar { -webkit-transform: translateX(300px); transform: translateX(300px); } body.close .sidebar-toggle { width: 284px; background-color: rgba(255, 255, 255, 0.8); -webkit-transition: 1s background-color; transition: 1s background-color; } body.close .content { -webkit-transform: translateX(300px); transform: translateX(300px); } body.close nav, body.close .github-corner { display: none; } .github-corner .octo-arm { -webkit-animation: octocat-wave 560ms ease-in-out; animation: octocat-wave 560ms ease-in-out; } .github-corner:hover .octo-arm { -webkit-animation: none; animation: none; } } @-webkit-keyframes octocat-wave { 0%, 100% { -webkit-transform: rotate(0); transform: rotate(0); } 20%, 60% { -webkit-transform: rotate(-25deg); transform: rotate(-25deg); } 40%, 80% { -webkit-transform: rotate(10deg); transform: rotate(10deg); } } @keyframes octocat-wave { 0%, 100% { -webkit-transform: rotate(0); transform: rotate(0); } 20%, 60% { -webkit-transform: rotate(-25deg); transform: rotate(-25deg); } 40%, 80% { -webkit-transform: rotate(10deg); transform: rotate(10deg); } }
PeterDaveHello/jsdelivr
files/docsify/1.5.2/themes/pure.css
CSS
mit
8,937
<?php use yii\helpers\Html; use yii\widgets\ActiveForm; /* @var $this yii\web\View */ /* @var $model common\models\User */ /* @var $form yii\widgets\ActiveForm */ ?> <div class="user-form"> <?php $form = ActiveForm::begin(); ?> <?= $form->field($model, 'status')->textInput() ?> <div class="form-group"> <?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?> </div> <?php ActiveForm::end(); ?> </div>
wedigitalApps/foundation
themes/wedigital/backend/user/_form.php
PHP
mit
555
<?php /** * WPSEO plugin file. * * @package WPSEO\Internals\Options */ /** * Option: wpseo_taxonomy_meta. */ class WPSEO_Taxonomy_Meta extends WPSEO_Option { /** * @var string Option name. */ public $option_name = 'wpseo_taxonomy_meta'; /** * @var bool Whether to include the option in the return for WPSEO_Options::get_all(). */ public $include_in_all = false; /** * @var array Array of defaults for the option. * Shouldn't be requested directly, use $this->get_defaults(); * * {@internal Important: in contrast to most defaults, the below array format is * very bare. The real option is in the format [taxonomy_name][term_id][...] * where [...] is any of the $defaults_per_term options shown below. * This is of course taken into account in the below methods.}} */ protected $defaults = array(); /** * @var string Option name - same as $option_name property, but now also available to static methods. * @static */ public static $name; /** * @var array Array of defaults for individual taxonomy meta entries. * @static */ public static $defaults_per_term = array( 'wpseo_title' => '', 'wpseo_desc' => '', 'wpseo_canonical' => '', 'wpseo_bctitle' => '', 'wpseo_noindex' => 'default', 'wpseo_focuskw' => '', 'wpseo_linkdex' => '', 'wpseo_content_score' => '', // Social fields. 'wpseo_opengraph-title' => '', 'wpseo_opengraph-description' => '', 'wpseo_opengraph-image' => '', 'wpseo_twitter-title' => '', 'wpseo_twitter-description' => '', 'wpseo_twitter-image' => '', ); /** * @var array Available index options. * Used for form generation and input validation. * * @static * * {@internal Labels (translation) added on admin_init via WPSEO_Taxonomy::translate_meta_options().}} */ public static $no_index_options = array( 'default' => '', 'index' => '', 'noindex' => '', ); /** * Add the actions and filters for the option. * * @todo [JRF => testers] Check if the extra actions below would run into problems if an option * is updated early on and if so, change the call to schedule these for a later action on add/update * instead of running them straight away. * * @return \WPSEO_Taxonomy_Meta */ protected function __construct() { parent::__construct(); self::$name = $this->option_name; /* On succesfull update/add of the option, flush the W3TC cache. */ add_action( 'add_option_' . $this->option_name, array( 'WPSEO_Utils', 'flush_w3tc_cache' ) ); add_action( 'update_option_' . $this->option_name, array( 'WPSEO_Utils', 'flush_w3tc_cache' ) ); } /** * Get the singleton instance of this class. * * @return object */ public static function get_instance() { if ( ! ( self::$instance instanceof self ) ) { self::$instance = new self(); self::$name = self::$instance->option_name; } return self::$instance; } /** * Add extra default options received from a filter. */ public function enrich_defaults() { $extra_defaults_per_term = apply_filters( 'wpseo_add_extra_taxmeta_term_defaults', array() ); if ( is_array( $extra_defaults_per_term ) ) { self::$defaults_per_term = array_merge( $extra_defaults_per_term, self::$defaults_per_term ); } } /** * Helper method - Combines a fixed array of default values with an options array * while filtering out any keys which are not in the defaults array. * * @static * * @param string $option_key Option name of the option we're doing the merge for. * @param array $options Optional. Current options. If not set, the option defaults for the $option_key will be returned. * * @return array Combined and filtered options array. */ /* Public function array_filter_merge( $option_key, $options = null ) { $defaults = $this->get_defaults( $option_key ); if ( ! isset( $options ) || $options === false ) { return $defaults; } / * {@internal Adding the defaults to all taxonomy terms each time the option is retrieved will be quite inefficient if there are a lot of taxonomy terms. As long as taxonomy_meta is only retrieved via methods in this class, we shouldn't need this.}} $options = (array) $options; $filtered = array(); if ( $options !== array() ) { foreach ( $options as $taxonomy => $terms ) { if ( is_array( $terms ) && $terms !== array() ) { foreach ( $terms as $id => $term_meta ) { foreach ( self::$defaults_per_term as $name => $default ) { if ( isset( $options[ $taxonomy ][ $id ][ $name ] ) ) { $filtered[ $taxonomy ][ $id ][ $name ] = $options[ $taxonomy ][ $id ][ $name ]; } else { $filtered[ $name ] = $default; } } } } } unset( $taxonomy, $terms, $id, $term_meta, $name, $default ); } // end of may be remove. return $filtered; * / return (array) $options; } */ /** * Validate the option. * * @param array $dirty New value for the option. * @param array $clean Clean value for the option, normally the defaults. * @param array $old Old value of the option. * * @return array Validated clean value for the option to be saved to the database. */ protected function validate_option( $dirty, $clean, $old ) { /* * Prevent complete validation (which can be expensive when there are lots of terms) * if only one item has changed and has already been validated. */ if ( isset( $dirty['wpseo_already_validated'] ) && $dirty['wpseo_already_validated'] === true ) { unset( $dirty['wpseo_already_validated'] ); return $dirty; } foreach ( $dirty as $taxonomy => $terms ) { /* Don't validate taxonomy - may not be registered yet and we don't want to remove valid ones. */ if ( is_array( $terms ) && $terms !== array() ) { foreach ( $terms as $term_id => $meta_data ) { /* Only validate term if the taxonomy exists. */ if ( taxonomy_exists( $taxonomy ) && get_term_by( 'id', $term_id, $taxonomy ) === false ) { /* Is this term id a special case ? */ if ( has_filter( 'wpseo_tax_meta_special_term_id_validation_' . $term_id ) !== false ) { $clean[ $taxonomy ][ $term_id ] = apply_filters( 'wpseo_tax_meta_special_term_id_validation_' . $term_id, $meta_data, $taxonomy, $term_id ); } continue; } if ( is_array( $meta_data ) && $meta_data !== array() ) { /* Validate meta data. */ $old_meta = self::get_term_meta( $term_id, $taxonomy ); $meta_data = self::validate_term_meta_data( $meta_data, $old_meta ); if ( $meta_data !== array() ) { $clean[ $taxonomy ][ $term_id ] = $meta_data; } } // Deal with special cases (for when taxonomy doesn't exist yet). if ( ! isset( $clean[ $taxonomy ][ $term_id ] ) && has_filter( 'wpseo_tax_meta_special_term_id_validation_' . $term_id ) !== false ) { $clean[ $taxonomy ][ $term_id ] = apply_filters( 'wpseo_tax_meta_special_term_id_validation_' . $term_id, $meta_data, $taxonomy, $term_id ); } } } } return $clean; } /** * Validate the meta data for one individual term and removes default values (no need to save those). * * @static * * @param array $meta_data New values. * @param array $old_meta The original values. * * @return array Validated and filtered value. */ public static function validate_term_meta_data( $meta_data, $old_meta ) { $clean = self::$defaults_per_term; $meta_data = array_map( array( 'WPSEO_Utils', 'trim_recursive' ), $meta_data ); if ( ! is_array( $meta_data ) || $meta_data === array() ) { return $clean; } foreach ( $clean as $key => $value ) { switch ( $key ) { case 'wpseo_noindex': if ( isset( $meta_data[ $key ] ) ) { if ( isset( self::$no_index_options[ $meta_data[ $key ] ] ) ) { $clean[ $key ] = $meta_data[ $key ]; } } elseif ( isset( $old_meta[ $key ] ) ) { // Retain old value if field currently not in use. $clean[ $key ] = $old_meta[ $key ]; } break; case 'wpseo_canonical': if ( isset( $meta_data[ $key ] ) && $meta_data[ $key ] !== '' ) { $url = WPSEO_Utils::sanitize_url( $meta_data[ $key ] ); if ( $url !== '' ) { $clean[ $key ] = $url; } unset( $url ); } break; case 'wpseo_bctitle': if ( isset( $meta_data[ $key ] ) ) { $clean[ $key ] = WPSEO_Utils::sanitize_text_field( stripslashes( $meta_data[ $key ] ) ); } elseif ( isset( $old_meta[ $key ] ) ) { // Retain old value if field currently not in use. $clean[ $key ] = $old_meta[ $key ]; } break; case 'wpseo_focuskw': case 'wpseo_title': case 'wpseo_desc': case 'wpseo_linkdex': default: if ( isset( $meta_data[ $key ] ) && is_string( $meta_data[ $key ] ) ) { $clean[ $key ] = WPSEO_Utils::sanitize_text_field( stripslashes( $meta_data[ $key ] ) ); } if ( 'wpseo_focuskw' === $key ) { $clean[ $key ] = str_replace( array( '&lt;', '&gt;', '&quot', '&#96', '<', '>', '"', '`', ), '', $clean[ $key ] ); } break; } $clean[ $key ] = apply_filters( 'wpseo_sanitize_tax_meta_' . $key, $clean[ $key ], ( isset( $meta_data[ $key ] ) ? $meta_data[ $key ] : null ), ( isset( $old_meta[ $key ] ) ? $old_meta[ $key ] : null ) ); } // Only save the non-default values. return array_diff_assoc( $clean, self::$defaults_per_term ); } /** * Clean a given option value. * - Convert old option values to new * - Fixes strings which were escaped (should have been sanitized - escaping is for output) * * @param array $option_value Old (not merged with defaults or filtered) option value to * clean according to the rules for this option. * @param string $current_version Optional. Version from which to upgrade, if not set, * version specific upgrades will be disregarded. * @param array $all_old_option_values Optional. Only used when importing old options to have * access to the real old values, in contrast to the saved ones. * * @return array Cleaned option. */ protected function clean_option( $option_value, $current_version = null, $all_old_option_values = null ) { /* Clean up old values and remove empty arrays. */ if ( is_array( $option_value ) && $option_value !== array() ) { foreach ( $option_value as $taxonomy => $terms ) { if ( is_array( $terms ) && $terms !== array() ) { foreach ( $terms as $term_id => $meta_data ) { if ( ! is_array( $meta_data ) || $meta_data === array() ) { // Remove empty term arrays. unset( $option_value[ $taxonomy ][ $term_id ] ); } else { foreach ( $meta_data as $key => $value ) { switch ( $key ) { case 'noindex': if ( $value === 'on' ) { // Convert 'on' to 'noindex'. $option_value[ $taxonomy ][ $term_id ][ $key ] = 'noindex'; } break; case 'canonical': case 'wpseo_bctitle': case 'wpseo_title': case 'wpseo_desc': case 'wpseo_linkdex': // @todo [JRF => whomever] needs checking, I don't have example data [JRF]. if ( $value !== '' ) { // Fix incorrectly saved (encoded) canonical urls and texts. $option_value[ $taxonomy ][ $term_id ][ $key ] = wp_specialchars_decode( stripslashes( $value ), ENT_QUOTES ); } break; default: // @todo [JRF => whomever] needs checking, I don't have example data [JRF]. if ( $value !== '' ) { // Fix incorrectly saved (escaped) text strings. $option_value[ $taxonomy ][ $term_id ][ $key ] = wp_specialchars_decode( $value, ENT_QUOTES ); } break; } } } } } else { // Remove empty taxonomy arrays. unset( $option_value[ $taxonomy ] ); } } } return $option_value; } /** * Retrieve a taxonomy term's meta value(s). * * @static * * @param mixed $term Term to get the meta value for * either (string) term name, (int) term id or (object) term. * @param string $taxonomy Name of the taxonomy to which the term is attached. * @param string $meta Optional. Meta value to get (without prefix). * * @return mixed|bool Value for the $meta if one is given, might be the default. * If no meta is given, an array of all the meta data for the term. * False if the term does not exist or the $meta provided is invalid. */ public static function get_term_meta( $term, $taxonomy, $meta = null ) { /* Figure out the term id. */ if ( is_int( $term ) ) { $term = get_term_by( 'id', $term, $taxonomy ); } elseif ( is_string( $term ) ) { $term = get_term_by( 'slug', $term, $taxonomy ); } if ( is_object( $term ) && isset( $term->term_id ) ) { $term_id = $term->term_id; } else { return false; } $tax_meta = self::get_term_tax_meta( $term_id, $taxonomy ); /* * Either return the complete array or a single value from it or false if the value does not exist * (shouldn't happen after merge with defaults, indicates typo in request). */ if ( ! isset( $meta ) ) { return $tax_meta; } if ( isset( $tax_meta[ 'wpseo_' . $meta ] ) ) { return $tax_meta[ 'wpseo_' . $meta ]; } return false; } /** * Get the current queried object and return the meta value. * * @param string $meta The meta field that is needed. * * @return bool|mixed */ public static function get_meta_without_term( $meta ) { $term = $GLOBALS['wp_query']->get_queried_object(); return self::get_term_meta( $term, $term->taxonomy, $meta ); } /** * Saving the values for the given term_id. * * @param int $term_id ID of the term to save data for. * @param string $taxonomy The taxonomy the term belongs to. * @param array $meta_values The values that will be saved. */ public static function set_values( $term_id, $taxonomy, array $meta_values ) { /* Validate the post values */ $old = self::get_term_meta( $term_id, $taxonomy ); $clean = self::validate_term_meta_data( $meta_values, $old ); self::save_clean_values( $term_id, $taxonomy, $clean ); } /** * Setting a single value to the term meta. * * @param int $term_id ID of the term to save data for. * @param string $taxonomy The taxonomy the term belongs to. * @param string $meta_key The target meta key to store the value in. * @param string $meta_value The value of the target meta key. */ public static function set_value( $term_id, $taxonomy, $meta_key, $meta_value ) { if ( substr( strtolower( $meta_key ), 0, 6 ) !== 'wpseo_' ) { $meta_key = 'wpseo_' . $meta_key; } self::set_values( $term_id, $taxonomy, array( $meta_key => $meta_value ) ); } /** * Find the keyword usages in the metas for the taxonomies/terms. * * @param string $keyword The keyword to look for. * @param string $current_term_id The current term id. * @param string $current_taxonomy The current taxonomy name. * * @return array */ public static function get_keyword_usage( $keyword, $current_term_id, $current_taxonomy ) { $tax_meta = self::get_tax_meta(); $found = array(); // @todo Check for terms of all taxonomies, not only the current taxonomy. foreach ( $tax_meta as $taxonomy_name => $terms ) { foreach ( $terms as $term_id => $meta_values ) { $is_current = ( $current_taxonomy === $taxonomy_name && (string) $current_term_id === (string) $term_id ); if ( ! $is_current && ! empty( $meta_values['wpseo_focuskw'] ) && $meta_values['wpseo_focuskw'] === $keyword ) { $found[] = $term_id; } } } return array( $keyword => $found ); } /** * Saving the values for the given term_id. * * @param int $term_id ID of the term to save data for. * @param string $taxonomy The taxonomy the term belongs to. * @param array $clean Array with clean values. */ private static function save_clean_values( $term_id, $taxonomy, array $clean ) { $tax_meta = self::get_tax_meta(); /* Add/remove the result to/from the original option value. */ if ( $clean !== array() ) { $tax_meta[ $taxonomy ][ $term_id ] = $clean; } else { unset( $tax_meta[ $taxonomy ][ $term_id ] ); if ( isset( $tax_meta[ $taxonomy ] ) && $tax_meta[ $taxonomy ] === array() ) { unset( $tax_meta[ $taxonomy ] ); } } // Prevent complete array validation. $tax_meta['wpseo_already_validated'] = true; self::save_tax_meta( $tax_meta ); } /** * Getting the meta from the options. * * @return void|array */ private static function get_tax_meta() { return get_option( self::$name ); } /** * Saving the tax meta values to the database. * * @param array $tax_meta Array with the meta values for taxonomy. */ private static function save_tax_meta( $tax_meta ) { update_option( self::$name, $tax_meta ); } /** * Getting the taxonomy meta for the given term_id and taxonomy. * * @param int $term_id The id of the term. * @param string $taxonomy Name of the taxonomy to which the term is attached. * * @return array */ private static function get_term_tax_meta( $term_id, $taxonomy ) { $tax_meta = self::get_tax_meta(); /* If we have data for the term, merge with defaults for complete array, otherwise set defaults. */ if ( isset( $tax_meta[ $taxonomy ][ $term_id ] ) ) { return array_merge( self::$defaults_per_term, $tax_meta[ $taxonomy ][ $term_id ] ); } return self::$defaults_per_term; } }
smpetrey/leahconstantine.com
web/app/plugins/wordpress-seo/inc/options/class-wpseo-taxonomy-meta.php
PHP
mit
18,076
<?php namespace Sonata\AdminBundle\Tests\Fixtures\Admin; use Sonata\AdminBundle\Admin\Admin; class PostAdmin extends Admin { protected $metadataClass = null; public function setParentAssociationMapping($associationMapping) { $this->parentAssociationMapping = $associationMapping; } public function setClassMetaData($classMetaData) { $this->classMetaData = $classMetaData; } public function getClassMetaData() { if ($this->classMetaData) { return $this->classMetaData; } return parent::getClassMetaData(); } }
evgenikozlov/test-task
vendor/sonata-project/admin-bundle/Tests/Fixtures/Admin/PostAdmin.php
PHP
mit
607
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using System.Collections; using System.Reflection; using System.Diagnostics.Contracts; //using System.Runtime.CompilerServices; namespace System.Collections.Generic { // Summary: // Represents a collection of objects that can be individually accessed by index. // // Type parameters: // T: // The type of elements in the list. [ContractClass(typeof(IListContract<>))] public interface IList<T> : ICollection<T> { // Summary: // Gets or sets the element at the specified index. // // Parameters: // index: // The zero-based index of the element to get or set. // // Returns: // The element at the specified index. // // Exceptions: // System.ArgumentOutOfRangeException: // index is not a valid index in the System.Collections.Generic.IList<T>. // // System.NotSupportedException: // The property is set and the System.Collections.Generic.IList<T> is read-only. T this[int index] { get; set; } // Summary: // Determines the index of a specific item in the System.Collections.Generic.IList<T>. // // Parameters: // item: // The object to locate in the System.Collections.Generic.IList<T>. // // Returns: // The index of item if found in the list; otherwise, -1. [Pure] int IndexOf(T item); // // Summary: // Inserts an item to the System.Collections.Generic.IList<T> at the specified // index. // // Parameters: // index: // The zero-based index at which item should be inserted. // // item: // The object to insert into the System.Collections.Generic.IList<T>. // // Exceptions: // System.ArgumentOutOfRangeException: // index is not a valid index in the System.Collections.Generic.IList<T>. // // System.NotSupportedException: // The System.Collections.Generic.IList<T> is read-only. void Insert(int index, T item); // // Summary: // Removes the System.Collections.Generic.IList<T> item at the specified index. // // Parameters: // index: // The zero-based index of the item to remove. // // Exceptions: // System.ArgumentOutOfRangeException: // index is not a valid index in the System.Collections.Generic.IList<T>. // // System.NotSupportedException: // The System.Collections.Generic.IList<T> is read-only. void RemoveAt(int index); } [ContractClassFor(typeof(IList<>))] abstract class IListContract<T> : IList<T> { #region IList<T> Members T IList<T>.this[int index] { get { Contract.Requires(index >= 0); Contract.Requires(index < this.Count); return default(T); } set { Contract.Requires(index >= 0); Contract.Requires(index < this.Count); } } [Pure] int IList<T>.IndexOf(T item) { Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(Contract.Result<int>() < this.Count); throw new NotImplementedException(); } void IList<T>.Insert(int index, T item) { Contract.Requires(index >= 0); Contract.Requires(index <= this.Count); } void IList<T>.RemoveAt(int index) { Contract.Requires(index >= 0); Contract.Requires(index < this.Count); Contract.Ensures(this.Count == Contract.OldValue(this.Count) - 1); } #endregion #region ICollection<T> Members public int Count { get { throw new NotImplementedException(); } } bool ICollection<T>.IsReadOnly { get { throw new NotImplementedException(); } } void ICollection<T>.Add(T item) { // Contract.Ensures(Count == Contract.OldValue(Count) + 1); // cannot be seen by our tools as there is no IList<T>.Add throw new NotImplementedException(); } void ICollection<T>.Clear() { throw new NotImplementedException(); } bool ICollection<T>.Contains(T item) { throw new NotImplementedException(); } void ICollection<T>.CopyTo(T[] array, int arrayIndex) { throw new NotImplementedException(); } bool ICollection<T>.Remove(T item) { throw new NotImplementedException(); } #endregion #region IEnumerable<T> Members IEnumerator<T> IEnumerable<T>.GetEnumerator() { throw new NotImplementedException(); } #endregion #region IEnumerable Members IEnumerator IEnumerable.GetEnumerator() { throw new NotImplementedException(); } #endregion #region IEnumerable Members public object[] Model { get { throw new NotImplementedException(); } } #endregion } }
ndykman/CodeContracts
Microsoft.Research/Contracts/MsCorlib/System.Collections.Generic.IList.cs
C#
mit
5,963
namespace Merchello.Web.Models.ContentEditing { using System; using System.Collections.Generic; using Merchello.Core; using Merchello.Core.Models.TypeFields; using Newtonsoft.Json; using Newtonsoft.Json.Converters; /// <summary> /// The line item display base. /// </summary> public abstract class LineItemDisplayBase { /// <summary> /// Gets or sets the key. /// </summary> public Guid Key { get; set; } /// <summary> /// Gets or sets the container key. /// </summary> public Guid ContainerKey { get; set; } /// <summary> /// Gets or sets the line item type field key. /// </summary> public Guid LineItemTfKey { get; set; } /// <summary> /// Gets or sets the SKU. /// </summary> public string Sku { get; set; } /// <summary> /// Gets or sets the name. /// </summary> public string Name { get; set; } /// <summary> /// Gets or sets the quantity. /// </summary> public int Quantity { get; set; } /// <summary> /// Gets or sets the price. /// </summary> public decimal Price { get; set; } /// <summary> /// Gets or sets a value indicating whether exported. /// </summary> public bool Exported { get; set; } /// <summary> /// Gets or sets the line item type. /// </summary> [JsonConverter(typeof(StringEnumConverter))] public LineItemType LineItemType { get; set; } /// <summary> /// Gets or sets the line item type field. /// </summary> public TypeField LineItemTypeField { get; set; } /// <summary> /// Gets or sets the extended data. /// </summary> public IEnumerable<KeyValuePair<string, string>> ExtendedData { get; set; } } }
MindfireTechnology/Merchello
src/Merchello.Web/Models/ContentEditing/LineItemDisplayBase.cs
C#
mit
1,952
(function ($) { 'use strict'; $.extend(true, $.trumbowyg, { langs: { // jshint camelcase:false en: { fontFamily: 'Font' }, es: { fontFamily: 'Fuente' }, da: { fontFamily: 'Skrifttype' }, fr: { fontFamily: 'Police' }, de: { fontFamily: 'Schriftart' }, nl: { fontFamily: 'Lettertype' }, tr: { fontFamily: 'Yazı Tipi' }, zh_tw: { fontFamily: '字體', }, pt_br: { fontFamily: 'Fonte', } } }); // jshint camelcase:true var defaultOptions = { fontList: [ {name: 'Arial', family: 'Arial, Helvetica, sans-serif'}, {name: 'Arial Black', family: '\'Arial Black\', Gadget, sans-serif'}, {name: 'Comic Sans', family: '\'Comic Sans MS\', Textile, cursive, sans-serif'}, {name: 'Courier New', family: '\'Courier New\', Courier, monospace'}, {name: 'Georgia', family: 'Georgia, serif'}, {name: 'Impact', family: 'Impact, Charcoal, sans-serif'}, {name: 'Lucida Console', family: '\'Lucida Console\', Monaco, monospace'}, {name: 'Lucida Sans', family: '\'Lucida Sans Uncide\', \'Lucida Grande\', sans-serif'}, {name: 'Palatino', family: '\'Palatino Linotype\', \'Book Antiqua\', Palatino, serif'}, {name: 'Tahoma', family: 'Tahoma, Geneva, sans-serif'}, {name: 'Times New Roman', family: '\'Times New Roman\', Times, serif'}, {name: 'Trebuchet', family: '\'Trebuchet MS\', Helvetica, sans-serif'}, {name: 'Verdana', family: 'Verdana, Geneva, sans-serif'} ] }; // Add dropdown with web safe fonts $.extend(true, $.trumbowyg, { plugins: { fontfamily: { init: function (trumbowyg) { trumbowyg.o.plugins.fontfamily = $.extend(true, {}, defaultOptions, trumbowyg.o.plugins.fontfamily || {} ); trumbowyg.addBtnDef('fontfamily', { dropdown: buildDropdown(trumbowyg), hasIcon: false, text: trumbowyg.lang.fontFamily }); } } } }); function buildDropdown(trumbowyg) { var dropdown = []; $.each(trumbowyg.o.plugins.fontfamily.fontList, function (index, font) { trumbowyg.addBtnDef('fontfamily_' + index, { title: '<span style="font-family: ' + font.family + ';">' + font.name + '</span>', hasIcon: false, fn: function () { trumbowyg.execCmd('fontName', font.family, true); } }); dropdown.push('fontfamily_' + index); }); return dropdown; } })(jQuery);
extend1994/cdnjs
ajax/libs/Trumbowyg/2.16.2/plugins/fontfamily/trumbowyg.fontfamily.js
JavaScript
mit
3,157
CKEDITOR.plugins.setLang("uicolor","ro",{title:"Interfața cu utilizatorul a Selectorului de culoare",options:"Opțiuni culoare",highlight:"Evidențiere",selected:"Culoare selectată",predefined:"Seturi de culoare predefinite",config:"Copiază această expresie în fișierul tău config.js"});
cdnjs/cdnjs
ajax/libs/ckeditor/4.17.2/plugins/uicolor/lang/ro.min.js
JavaScript
mit
294
<html> <head> <meta charset="utf-8"> <meta name=viewport content="width=device-width, initial-scale=1"> {% if dev %} {% style "css/site.css" %} {% else %} {% style "css/site.min.css" %} {% endif %} </head> <body> <div id="app"></div> <script src="js/app.js" type="text/javascript"></script> </body> </html>
firthh/thoughtmule
resources/templates/index.html
HTML
epl-1.0
355
<?php global $qode_options_proya; $blog_hide_comments = ""; if (isset($qode_options_proya['blog_hide_comments'])) { $blog_hide_comments = $qode_options_proya['blog_hide_comments']; } $blog_hide_author = ""; if (isset($qode_options_proya['blog_hide_author'])) { $blog_hide_author = $qode_options_proya['blog_hide_author']; } $qode_like = "on"; if (isset($qode_options_proya['qode_like'])) { $qode_like = $qode_options_proya['qode_like']; } ?> <?php $_post_format = get_post_format(); ?> <?php switch ($_post_format) { case "video": ?> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <div class="post_content_holder"> <div class="post_image"> <?php $_video_type = get_post_meta(get_the_ID(), "video_format_choose", true);?> <?php if($_video_type == "youtube") { ?> <iframe src="//www.youtube.com/embed/<?php echo get_post_meta(get_the_ID(), "video_format_link", true); ?>?wmode=transparent" wmode="Opaque" frameborder="0" allowfullscreen></iframe> <?php } elseif ($_video_type == "vimeo"){ ?> <iframe src="//player.vimeo.com/video/<?php echo get_post_meta(get_the_ID(), "video_format_link", true); ?>?title=0&amp;byline=0&amp;portrait=0" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe> <?php } elseif ($_video_type == "self"){ ?> <div class="video"> <div class="mobile-video-image" style="background-image: url(<?php echo get_post_meta(get_the_ID(), "video_format_image", true); ?>);"></div> <div class="video-wrap" > <video class="video" poster="<?php echo get_post_meta(get_the_ID(), "video_format_image", true); ?>" preload="auto"> <?php if(get_post_meta(get_the_ID(), "video_format_webm", true) != "") { ?> <source type="video/webm" src="<?php echo get_post_meta(get_the_ID(), "video_format_webm", true); ?>"> <?php } ?> <?php if(get_post_meta(get_the_ID(), "video_format_mp4", true) != "") { ?> <source type="video/mp4" src="<?php echo get_post_meta(get_the_ID(), "video_format_mp4", true); ?>"> <?php } ?> <?php if(get_post_meta(get_the_ID(), "video_format_ogv", true) != "") { ?> <source type="video/ogg" src="<?php echo get_post_meta(get_the_ID(), "video_format_ogv", true); ?>"> <?php } ?> <object width="320" height="240" type="application/x-shockwave-flash" data="<?php echo get_template_directory_uri(); ?>/js/flashmediaelement.swf"> <param name="movie" value="<?php echo get_template_directory_uri(); ?>/js/flashmediaelement.swf" /> <param name="flashvars" value="controls=true&file=<?php echo get_post_meta(get_the_ID(), "video_format_mp4", true); ?>" /> <img src="<?php echo get_post_meta(get_the_ID(), "video_format_image", true); ?>" width="1920" height="800" title="No video playback capabilities" alt="Video thumb" /> </object> </video> </div></div> <?php } ?> </div> <div class="post_text"> <div class="post_text_inner"> <div class="minimalist_date"><?php the_time(get_option('date_format')); ?></div> <h2><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2> <div class="separator small center"></div> <?php qode_excerpt(); ?> </div> </div> </div> </article> <?php break; case "audio": ?> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <div class="post_content_holder"> <div class="post_image"> <audio class="blog_audio" src="<?php echo get_post_meta(get_the_ID(), "audio_link", true) ?>" controls="controls"> <?php _e("Your browser don't support audio player","qode"); ?> </audio> </div> <div class="post_text"> <div class="post_text_inner"> <div class="minimalist_date"><?php the_time(get_option('date_format')); ?></div> <h2><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2> <div class="separator small center"></div> <?php qode_excerpt(); ?> </div> </div> </div> </article> <?php break; case "gallery": ?> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <div class="post_content_holder"> <div class="post_image"> <div class="flexslider"> <ul class="slides"> <?php $post_content = get_the_content(); preg_match('/\[gallery.*ids=.(.*).\]/', $post_content, $ids); $array_id = explode(",", $ids[1]); foreach($array_id as $img_id){ ?> <li><a href="<?php the_permalink(); ?>"><?php echo wp_get_attachment_image( $img_id, 'full' ); ?></a></li> <?php } ?> </ul> </div> </div> <div class="post_text"> <div class="post_text_inner"> <div class="minimalist_date"><?php the_time(get_option('date_format')); ?></div> <h2><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2> <div class="separator small center"></div> <?php qode_excerpt(); ?> </div> </div> </div> </article> <?php break; case "link": ?> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <div class="post_content_holder"> <div class="post_text"> <div class="post_text_inner"> <div class="minimalist_date"><?php the_time(get_option('date_format')); ?></div> <i class="link_mark fa fa-link pull-left"></i> <div class="post_title"> <p><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></p> </div> </div> </div> </div> </article> <?php break; case "quote": ?> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <div class="post_content_holder"> <div class="post_text"> <div class="post_text_inner"> <div class="minimalist_date"><?php the_time(get_option('date_format')); ?></div> <i class="qoute_mark fa fa-quote-right pull-left"></i> <div class="post_title"> <p><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php echo get_post_meta(get_the_ID(), "quote_format", true); ?></a></p> <span class="quote_author">&mdash; <?php the_title(); ?></span> </div> </div> </div> </div> </article> <?php break; default: ?> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <div class="post_content_holder"> <?php if ( has_post_thumbnail() ) { ?> <div class="post_image"> <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"> <?php the_post_thumbnail('full'); ?> </a> </div> <?php } ?> <div class="post_text"> <div class="post_text_inner"> <div class="minimalist_date"><?php the_time(get_option('date_format')); ?></div> <h2><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2> <div class="separator small center"></div> <?php qode_excerpt(); ?> </div> </div> </div> </article> <?php } ?>
comc49/a2f_bridge_theme
wp-content/themes_bak/bridge/templates/blog_large_image_simple-loop.php
PHP
gpl-2.0
7,098
/* * Builtin "git tag" * * Copyright (c) 2007 Kristian Høgsberg <krh@redhat.com>, * Carlos Rica <jasampler@gmail.com> * Based on git-tag.sh and mktag.c by Linus Torvalds. */ #include "cache.h" #include "builtin.h" #include "refs.h" #include "tag.h" #include "run-command.h" #include "parse-options.h" #include "diff.h" #include "revision.h" #include "gpg-interface.h" #include "sha1-array.h" #include "column.h" #include "ref-filter.h" static const char * const git_tag_usage[] = { N_("git tag [-a | -s | -u <key-id>] [-f] [-m <msg> | -F <file>] <tagname> [<head>]"), N_("git tag -d <tagname>..."), N_("git tag -l [-n[<num>]] [--contains <commit>] [--points-at <object>]" "\n\t\t[--format=<format>] [--[no-]merged [<commit>]] [<pattern>...]"), N_("git tag -v <tagname>..."), NULL }; static unsigned int colopts; static int list_tags(struct ref_filter *filter, struct ref_sorting *sorting, const char *format) { struct ref_array array; char *to_free = NULL; int i; memset(&array, 0, sizeof(array)); if (filter->lines == -1) filter->lines = 0; if (!format) { if (filter->lines) { to_free = xstrfmt("%s %%(contents:lines=%d)", "%(align:15)%(refname:strip=2)%(end)", filter->lines); format = to_free; } else format = "%(refname:strip=2)"; } verify_ref_format(format); filter->with_commit_tag_algo = 1; filter_refs(&array, filter, FILTER_REFS_TAGS); ref_array_sort(sorting, &array); for (i = 0; i < array.nr; i++) show_ref_array_item(array.items[i], format, 0); ref_array_clear(&array); free(to_free); return 0; } typedef int (*each_tag_name_fn)(const char *name, const char *ref, const unsigned char *sha1); static int for_each_tag_name(const char **argv, each_tag_name_fn fn) { const char **p; char ref[PATH_MAX]; int had_error = 0; unsigned char sha1[20]; for (p = argv; *p; p++) { if (snprintf(ref, sizeof(ref), "refs/tags/%s", *p) >= sizeof(ref)) { error(_("tag name too long: %.*s..."), 50, *p); had_error = 1; continue; } if (read_ref(ref, sha1)) { error(_("tag '%s' not found."), *p); had_error = 1; continue; } if (fn(*p, ref, sha1)) had_error = 1; } return had_error; } static int delete_tag(const char *name, const char *ref, const unsigned char *sha1) { if (delete_ref(ref, sha1, 0)) return 1; printf(_("Deleted tag '%s' (was %s)\n"), name, find_unique_abbrev(sha1, DEFAULT_ABBREV)); return 0; } static int verify_tag(const char *name, const char *ref, const unsigned char *sha1) { const char *argv_verify_tag[] = {"verify-tag", "-v", "SHA1_HEX", NULL}; argv_verify_tag[2] = sha1_to_hex(sha1); if (run_command_v_opt(argv_verify_tag, RUN_GIT_CMD)) return error(_("could not verify the tag '%s'"), name); return 0; } static int do_sign(struct strbuf *buffer) { return sign_buffer(buffer, buffer, get_signing_key()); } static const char tag_template[] = N_("\nWrite a message for tag:\n %s\n" "Lines starting with '%c' will be ignored.\n"); static const char tag_template_nocleanup[] = N_("\nWrite a message for tag:\n %s\n" "Lines starting with '%c' will be kept; you may remove them" " yourself if you want to.\n"); /* Parse arg given and add it the ref_sorting array */ static int parse_sorting_string(const char *arg, struct ref_sorting **sorting_tail) { struct ref_sorting *s; int len; s = xcalloc(1, sizeof(*s)); s->next = *sorting_tail; *sorting_tail = s; if (*arg == '-') { s->reverse = 1; arg++; } if (skip_prefix(arg, "version:", &arg) || skip_prefix(arg, "v:", &arg)) s->version = 1; len = strlen(arg); s->atom = parse_ref_filter_atom(arg, arg+len); return 0; } static int git_tag_config(const char *var, const char *value, void *cb) { int status; struct ref_sorting **sorting_tail = (struct ref_sorting **)cb; if (!strcmp(var, "tag.sort")) { if (!value) return config_error_nonbool(var); parse_sorting_string(value, sorting_tail); return 0; } status = git_gpg_config(var, value, cb); if (status) return status; if (starts_with(var, "column.")) return git_column_config(var, value, "tag", &colopts); return git_default_config(var, value, cb); } static void write_tag_body(int fd, const unsigned char *sha1) { unsigned long size; enum object_type type; char *buf, *sp; buf = read_sha1_file(sha1, &type, &size); if (!buf) return; /* skip header */ sp = strstr(buf, "\n\n"); if (!sp || !size || type != OBJ_TAG) { free(buf); return; } sp += 2; /* skip the 2 LFs */ write_or_die(fd, sp, parse_signature(sp, buf + size - sp)); free(buf); } static int build_tag_object(struct strbuf *buf, int sign, unsigned char *result) { if (sign && do_sign(buf) < 0) return error(_("unable to sign the tag")); if (write_sha1_file(buf->buf, buf->len, tag_type, result) < 0) return error(_("unable to write tag file")); return 0; } struct create_tag_options { unsigned int message_given:1; unsigned int sign; enum { CLEANUP_NONE, CLEANUP_SPACE, CLEANUP_ALL } cleanup_mode; }; static void create_tag(const unsigned char *object, const char *tag, struct strbuf *buf, struct create_tag_options *opt, unsigned char *prev, unsigned char *result) { enum object_type type; char header_buf[1024]; int header_len; char *path = NULL; type = sha1_object_info(object, NULL); if (type <= OBJ_NONE) die(_("bad object type.")); header_len = snprintf(header_buf, sizeof(header_buf), "object %s\n" "type %s\n" "tag %s\n" "tagger %s\n\n", sha1_to_hex(object), typename(type), tag, git_committer_info(IDENT_STRICT)); if (header_len > sizeof(header_buf) - 1) die(_("tag header too big.")); if (!opt->message_given) { int fd; /* write the template message before editing: */ path = git_pathdup("TAG_EDITMSG"); fd = open(path, O_CREAT | O_TRUNC | O_WRONLY, 0600); if (fd < 0) die_errno(_("could not create file '%s'"), path); if (!is_null_sha1(prev)) { write_tag_body(fd, prev); } else { struct strbuf buf = STRBUF_INIT; strbuf_addch(&buf, '\n'); if (opt->cleanup_mode == CLEANUP_ALL) strbuf_commented_addf(&buf, _(tag_template), tag, comment_line_char); else strbuf_commented_addf(&buf, _(tag_template_nocleanup), tag, comment_line_char); write_or_die(fd, buf.buf, buf.len); strbuf_release(&buf); } close(fd); if (launch_editor(path, buf, NULL)) { fprintf(stderr, _("Please supply the message using either -m or -F option.\n")); exit(1); } } if (opt->cleanup_mode != CLEANUP_NONE) strbuf_stripspace(buf, opt->cleanup_mode == CLEANUP_ALL); if (!opt->message_given && !buf->len) die(_("no tag message?")); strbuf_insert(buf, 0, header_buf, header_len); if (build_tag_object(buf, opt->sign, result) < 0) { if (path) fprintf(stderr, _("The tag message has been left in %s\n"), path); exit(128); } if (path) { unlink_or_warn(path); free(path); } } struct msg_arg { int given; struct strbuf buf; }; static int parse_msg_arg(const struct option *opt, const char *arg, int unset) { struct msg_arg *msg = opt->value; if (!arg) return -1; if (msg->buf.len) strbuf_addstr(&(msg->buf), "\n\n"); strbuf_addstr(&(msg->buf), arg); msg->given = 1; return 0; } static int strbuf_check_tag_ref(struct strbuf *sb, const char *name) { if (name[0] == '-') return -1; strbuf_reset(sb); strbuf_addf(sb, "refs/tags/%s", name); return check_refname_format(sb->buf, 0); } int cmd_tag(int argc, const char **argv, const char *prefix) { struct strbuf buf = STRBUF_INIT; struct strbuf ref = STRBUF_INIT; unsigned char object[20], prev[20]; const char *object_ref, *tag; struct create_tag_options opt; char *cleanup_arg = NULL; int create_reflog = 0; int annotate = 0, force = 0; int cmdmode = 0; const char *msgfile = NULL, *keyid = NULL; struct msg_arg msg = { 0, STRBUF_INIT }; struct ref_transaction *transaction; struct strbuf err = STRBUF_INIT; struct ref_filter filter; static struct ref_sorting *sorting = NULL, **sorting_tail = &sorting; const char *format = NULL; struct option options[] = { OPT_CMDMODE('l', "list", &cmdmode, N_("list tag names"), 'l'), { OPTION_INTEGER, 'n', NULL, &filter.lines, N_("n"), N_("print <n> lines of each tag message"), PARSE_OPT_OPTARG, NULL, 1 }, OPT_CMDMODE('d', "delete", &cmdmode, N_("delete tags"), 'd'), OPT_CMDMODE('v', "verify", &cmdmode, N_("verify tags"), 'v'), OPT_GROUP(N_("Tag creation options")), OPT_BOOL('a', "annotate", &annotate, N_("annotated tag, needs a message")), OPT_CALLBACK('m', "message", &msg, N_("message"), N_("tag message"), parse_msg_arg), OPT_FILENAME('F', "file", &msgfile, N_("read message from file")), OPT_BOOL('s', "sign", &opt.sign, N_("annotated and GPG-signed tag")), OPT_STRING(0, "cleanup", &cleanup_arg, N_("mode"), N_("how to strip spaces and #comments from message")), OPT_STRING('u', "local-user", &keyid, N_("key-id"), N_("use another key to sign the tag")), OPT__FORCE(&force, N_("replace the tag if exists")), OPT_BOOL(0, "create-reflog", &create_reflog, N_("create a reflog")), OPT_GROUP(N_("Tag listing options")), OPT_COLUMN(0, "column", &colopts, N_("show tag list in columns")), OPT_CONTAINS(&filter.with_commit, N_("print only tags that contain the commit")), OPT_WITH(&filter.with_commit, N_("print only tags that contain the commit")), OPT_MERGED(&filter, N_("print only tags that are merged")), OPT_NO_MERGED(&filter, N_("print only tags that are not merged")), OPT_CALLBACK(0 , "sort", sorting_tail, N_("key"), N_("field name to sort on"), &parse_opt_ref_sorting), { OPTION_CALLBACK, 0, "points-at", &filter.points_at, N_("object"), N_("print only tags of the object"), 0, parse_opt_object_name }, OPT_STRING( 0 , "format", &format, N_("format"), N_("format to use for the output")), OPT_END() }; git_config(git_tag_config, sorting_tail); memset(&opt, 0, sizeof(opt)); memset(&filter, 0, sizeof(filter)); filter.lines = -1; argc = parse_options(argc, argv, prefix, options, git_tag_usage, 0); if (keyid) { opt.sign = 1; set_signing_key(keyid); } if (opt.sign) annotate = 1; if (argc == 0 && !cmdmode) cmdmode = 'l'; if ((annotate || msg.given || msgfile || force) && (cmdmode != 0)) usage_with_options(git_tag_usage, options); finalize_colopts(&colopts, -1); if (cmdmode == 'l' && filter.lines != -1) { if (explicitly_enable_column(colopts)) die(_("--column and -n are incompatible")); colopts = 0; } if (!sorting) sorting = ref_default_sorting(); if (cmdmode == 'l') { int ret; if (column_active(colopts)) { struct column_options copts; memset(&copts, 0, sizeof(copts)); copts.padding = 2; run_column_filter(colopts, &copts); } filter.name_patterns = argv; ret = list_tags(&filter, sorting, format); if (column_active(colopts)) stop_column_filter(); return ret; } if (filter.lines != -1) die(_("-n option is only allowed with -l.")); if (filter.with_commit) die(_("--contains option is only allowed with -l.")); if (filter.points_at.nr) die(_("--points-at option is only allowed with -l.")); if (filter.merge_commit) die(_("--merged and --no-merged option are only allowed with -l")); if (cmdmode == 'd') return for_each_tag_name(argv, delete_tag); if (cmdmode == 'v') return for_each_tag_name(argv, verify_tag); if (msg.given || msgfile) { if (msg.given && msgfile) die(_("only one -F or -m option is allowed.")); annotate = 1; if (msg.given) strbuf_addbuf(&buf, &(msg.buf)); else { if (!strcmp(msgfile, "-")) { if (strbuf_read(&buf, 0, 1024) < 0) die_errno(_("cannot read '%s'"), msgfile); } else { if (strbuf_read_file(&buf, msgfile, 1024) < 0) die_errno(_("could not open or read '%s'"), msgfile); } } } tag = argv[0]; object_ref = argc == 2 ? argv[1] : "HEAD"; if (argc > 2) die(_("too many params")); if (get_sha1(object_ref, object)) die(_("Failed to resolve '%s' as a valid ref."), object_ref); if (strbuf_check_tag_ref(&ref, tag)) die(_("'%s' is not a valid tag name."), tag); if (read_ref(ref.buf, prev)) hashclr(prev); else if (!force) die(_("tag '%s' already exists"), tag); opt.message_given = msg.given || msgfile; if (!cleanup_arg || !strcmp(cleanup_arg, "strip")) opt.cleanup_mode = CLEANUP_ALL; else if (!strcmp(cleanup_arg, "verbatim")) opt.cleanup_mode = CLEANUP_NONE; else if (!strcmp(cleanup_arg, "whitespace")) opt.cleanup_mode = CLEANUP_SPACE; else die(_("Invalid cleanup mode %s"), cleanup_arg); if (annotate) create_tag(object, tag, &buf, &opt, prev, object); transaction = ref_transaction_begin(&err); if (!transaction || ref_transaction_update(transaction, ref.buf, object, prev, create_reflog ? REF_FORCE_CREATE_REFLOG : 0, NULL, &err) || ref_transaction_commit(transaction, &err)) die("%s", err.buf); ref_transaction_free(transaction); if (force && !is_null_sha1(prev) && hashcmp(prev, object)) printf(_("Updated tag '%s' (was %s)\n"), tag, find_unique_abbrev(prev, DEFAULT_ABBREV)); strbuf_release(&err); strbuf_release(&buf); strbuf_release(&ref); return 0; }
TigerKid001/git
builtin/tag.c
C
gpl-2.0
13,238
// SPDX-License-Identifier: GPL-2.0-or-later /* * Linux Socket Filter - Kernel level socket filtering * * Based on the design of the Berkeley Packet Filter. The new * internal format has been designed by PLUMgrid: * * Copyright (c) 2011 - 2014 PLUMgrid, http://plumgrid.com * * Authors: * * Jay Schulist <jschlst@samba.org> * Alexei Starovoitov <ast@plumgrid.com> * Daniel Borkmann <dborkman@redhat.com> * * Andi Kleen - Fix a few bad bugs and races. * Kris Katterjohn - Added many additional checks in bpf_check_classic() */ #include <linux/module.h> #include <linux/types.h> #include <linux/mm.h> #include <linux/fcntl.h> #include <linux/socket.h> #include <linux/sock_diag.h> #include <linux/in.h> #include <linux/inet.h> #include <linux/netdevice.h> #include <linux/if_packet.h> #include <linux/if_arp.h> #include <linux/gfp.h> #include <net/inet_common.h> #include <net/ip.h> #include <net/protocol.h> #include <net/netlink.h> #include <linux/skbuff.h> #include <linux/skmsg.h> #include <net/sock.h> #include <net/flow_dissector.h> #include <linux/errno.h> #include <linux/timer.h> #include <linux/uaccess.h> #include <asm/unaligned.h> #include <asm/cmpxchg.h> #include <linux/filter.h> #include <linux/ratelimit.h> #include <linux/seccomp.h> #include <linux/if_vlan.h> #include <linux/bpf.h> #include <net/sch_generic.h> #include <net/cls_cgroup.h> #include <net/dst_metadata.h> #include <net/dst.h> #include <net/sock_reuseport.h> #include <net/busy_poll.h> #include <net/tcp.h> #include <net/xfrm.h> #include <net/udp.h> #include <linux/bpf_trace.h> #include <net/xdp_sock.h> #include <linux/inetdevice.h> #include <net/inet_hashtables.h> #include <net/inet6_hashtables.h> #include <net/ip_fib.h> #include <net/flow.h> #include <net/arp.h> #include <net/ipv6.h> #include <net/net_namespace.h> #include <linux/seg6_local.h> #include <net/seg6.h> #include <net/seg6_local.h> #include <net/lwtunnel.h> #include <net/ipv6_stubs.h> #include <net/bpf_sk_storage.h> /** * sk_filter_trim_cap - run a packet through a socket filter * @sk: sock associated with &sk_buff * @skb: buffer to filter * @cap: limit on how short the eBPF program may trim the packet * * Run the eBPF program and then cut skb->data to correct size returned by * the program. If pkt_len is 0 we toss packet. If skb->len is smaller * than pkt_len we keep whole skb->data. This is the socket level * wrapper to BPF_PROG_RUN. It returns 0 if the packet should * be accepted or -EPERM if the packet should be tossed. * */ int sk_filter_trim_cap(struct sock *sk, struct sk_buff *skb, unsigned int cap) { int err; struct sk_filter *filter; /* * If the skb was allocated from pfmemalloc reserves, only * allow SOCK_MEMALLOC sockets to use it as this socket is * helping free memory */ if (skb_pfmemalloc(skb) && !sock_flag(sk, SOCK_MEMALLOC)) { NET_INC_STATS(sock_net(sk), LINUX_MIB_PFMEMALLOCDROP); return -ENOMEM; } err = BPF_CGROUP_RUN_PROG_INET_INGRESS(sk, skb); if (err) return err; err = security_sock_rcv_skb(sk, skb); if (err) return err; rcu_read_lock(); filter = rcu_dereference(sk->sk_filter); if (filter) { struct sock *save_sk = skb->sk; unsigned int pkt_len; skb->sk = sk; pkt_len = bpf_prog_run_save_cb(filter->prog, skb); skb->sk = save_sk; err = pkt_len ? pskb_trim(skb, max(cap, pkt_len)) : -EPERM; } rcu_read_unlock(); return err; } EXPORT_SYMBOL(sk_filter_trim_cap); BPF_CALL_1(bpf_skb_get_pay_offset, struct sk_buff *, skb) { return skb_get_poff(skb); } BPF_CALL_3(bpf_skb_get_nlattr, struct sk_buff *, skb, u32, a, u32, x) { struct nlattr *nla; if (skb_is_nonlinear(skb)) return 0; if (skb->len < sizeof(struct nlattr)) return 0; if (a > skb->len - sizeof(struct nlattr)) return 0; nla = nla_find((struct nlattr *) &skb->data[a], skb->len - a, x); if (nla) return (void *) nla - (void *) skb->data; return 0; } BPF_CALL_3(bpf_skb_get_nlattr_nest, struct sk_buff *, skb, u32, a, u32, x) { struct nlattr *nla; if (skb_is_nonlinear(skb)) return 0; if (skb->len < sizeof(struct nlattr)) return 0; if (a > skb->len - sizeof(struct nlattr)) return 0; nla = (struct nlattr *) &skb->data[a]; if (nla->nla_len > skb->len - a) return 0; nla = nla_find_nested(nla, x); if (nla) return (void *) nla - (void *) skb->data; return 0; } BPF_CALL_4(bpf_skb_load_helper_8, const struct sk_buff *, skb, const void *, data, int, headlen, int, offset) { u8 tmp, *ptr; const int len = sizeof(tmp); if (offset >= 0) { if (headlen - offset >= len) return *(u8 *)(data + offset); if (!skb_copy_bits(skb, offset, &tmp, sizeof(tmp))) return tmp; } else { ptr = bpf_internal_load_pointer_neg_helper(skb, offset, len); if (likely(ptr)) return *(u8 *)ptr; } return -EFAULT; } BPF_CALL_2(bpf_skb_load_helper_8_no_cache, const struct sk_buff *, skb, int, offset) { return ____bpf_skb_load_helper_8(skb, skb->data, skb->len - skb->data_len, offset); } BPF_CALL_4(bpf_skb_load_helper_16, const struct sk_buff *, skb, const void *, data, int, headlen, int, offset) { u16 tmp, *ptr; const int len = sizeof(tmp); if (offset >= 0) { if (headlen - offset >= len) return get_unaligned_be16(data + offset); if (!skb_copy_bits(skb, offset, &tmp, sizeof(tmp))) return be16_to_cpu(tmp); } else { ptr = bpf_internal_load_pointer_neg_helper(skb, offset, len); if (likely(ptr)) return get_unaligned_be16(ptr); } return -EFAULT; } BPF_CALL_2(bpf_skb_load_helper_16_no_cache, const struct sk_buff *, skb, int, offset) { return ____bpf_skb_load_helper_16(skb, skb->data, skb->len - skb->data_len, offset); } BPF_CALL_4(bpf_skb_load_helper_32, const struct sk_buff *, skb, const void *, data, int, headlen, int, offset) { u32 tmp, *ptr; const int len = sizeof(tmp); if (likely(offset >= 0)) { if (headlen - offset >= len) return get_unaligned_be32(data + offset); if (!skb_copy_bits(skb, offset, &tmp, sizeof(tmp))) return be32_to_cpu(tmp); } else { ptr = bpf_internal_load_pointer_neg_helper(skb, offset, len); if (likely(ptr)) return get_unaligned_be32(ptr); } return -EFAULT; } BPF_CALL_2(bpf_skb_load_helper_32_no_cache, const struct sk_buff *, skb, int, offset) { return ____bpf_skb_load_helper_32(skb, skb->data, skb->len - skb->data_len, offset); } BPF_CALL_0(bpf_get_raw_cpu_id) { return raw_smp_processor_id(); } static const struct bpf_func_proto bpf_get_raw_smp_processor_id_proto = { .func = bpf_get_raw_cpu_id, .gpl_only = false, .ret_type = RET_INTEGER, }; static u32 convert_skb_access(int skb_field, int dst_reg, int src_reg, struct bpf_insn *insn_buf) { struct bpf_insn *insn = insn_buf; switch (skb_field) { case SKF_AD_MARK: BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, mark) != 4); *insn++ = BPF_LDX_MEM(BPF_W, dst_reg, src_reg, offsetof(struct sk_buff, mark)); break; case SKF_AD_PKTTYPE: *insn++ = BPF_LDX_MEM(BPF_B, dst_reg, src_reg, PKT_TYPE_OFFSET()); *insn++ = BPF_ALU32_IMM(BPF_AND, dst_reg, PKT_TYPE_MAX); #ifdef __BIG_ENDIAN_BITFIELD *insn++ = BPF_ALU32_IMM(BPF_RSH, dst_reg, 5); #endif break; case SKF_AD_QUEUE: BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, queue_mapping) != 2); *insn++ = BPF_LDX_MEM(BPF_H, dst_reg, src_reg, offsetof(struct sk_buff, queue_mapping)); break; case SKF_AD_VLAN_TAG: BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, vlan_tci) != 2); /* dst_reg = *(u16 *) (src_reg + offsetof(vlan_tci)) */ *insn++ = BPF_LDX_MEM(BPF_H, dst_reg, src_reg, offsetof(struct sk_buff, vlan_tci)); break; case SKF_AD_VLAN_TAG_PRESENT: *insn++ = BPF_LDX_MEM(BPF_B, dst_reg, src_reg, PKT_VLAN_PRESENT_OFFSET()); if (PKT_VLAN_PRESENT_BIT) *insn++ = BPF_ALU32_IMM(BPF_RSH, dst_reg, PKT_VLAN_PRESENT_BIT); if (PKT_VLAN_PRESENT_BIT < 7) *insn++ = BPF_ALU32_IMM(BPF_AND, dst_reg, 1); break; } return insn - insn_buf; } static bool convert_bpf_extensions(struct sock_filter *fp, struct bpf_insn **insnp) { struct bpf_insn *insn = *insnp; u32 cnt; switch (fp->k) { case SKF_AD_OFF + SKF_AD_PROTOCOL: BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, protocol) != 2); /* A = *(u16 *) (CTX + offsetof(protocol)) */ *insn++ = BPF_LDX_MEM(BPF_H, BPF_REG_A, BPF_REG_CTX, offsetof(struct sk_buff, protocol)); /* A = ntohs(A) [emitting a nop or swap16] */ *insn = BPF_ENDIAN(BPF_FROM_BE, BPF_REG_A, 16); break; case SKF_AD_OFF + SKF_AD_PKTTYPE: cnt = convert_skb_access(SKF_AD_PKTTYPE, BPF_REG_A, BPF_REG_CTX, insn); insn += cnt - 1; break; case SKF_AD_OFF + SKF_AD_IFINDEX: case SKF_AD_OFF + SKF_AD_HATYPE: BUILD_BUG_ON(FIELD_SIZEOF(struct net_device, ifindex) != 4); BUILD_BUG_ON(FIELD_SIZEOF(struct net_device, type) != 2); *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, dev), BPF_REG_TMP, BPF_REG_CTX, offsetof(struct sk_buff, dev)); /* if (tmp != 0) goto pc + 1 */ *insn++ = BPF_JMP_IMM(BPF_JNE, BPF_REG_TMP, 0, 1); *insn++ = BPF_EXIT_INSN(); if (fp->k == SKF_AD_OFF + SKF_AD_IFINDEX) *insn = BPF_LDX_MEM(BPF_W, BPF_REG_A, BPF_REG_TMP, offsetof(struct net_device, ifindex)); else *insn = BPF_LDX_MEM(BPF_H, BPF_REG_A, BPF_REG_TMP, offsetof(struct net_device, type)); break; case SKF_AD_OFF + SKF_AD_MARK: cnt = convert_skb_access(SKF_AD_MARK, BPF_REG_A, BPF_REG_CTX, insn); insn += cnt - 1; break; case SKF_AD_OFF + SKF_AD_RXHASH: BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, hash) != 4); *insn = BPF_LDX_MEM(BPF_W, BPF_REG_A, BPF_REG_CTX, offsetof(struct sk_buff, hash)); break; case SKF_AD_OFF + SKF_AD_QUEUE: cnt = convert_skb_access(SKF_AD_QUEUE, BPF_REG_A, BPF_REG_CTX, insn); insn += cnt - 1; break; case SKF_AD_OFF + SKF_AD_VLAN_TAG: cnt = convert_skb_access(SKF_AD_VLAN_TAG, BPF_REG_A, BPF_REG_CTX, insn); insn += cnt - 1; break; case SKF_AD_OFF + SKF_AD_VLAN_TAG_PRESENT: cnt = convert_skb_access(SKF_AD_VLAN_TAG_PRESENT, BPF_REG_A, BPF_REG_CTX, insn); insn += cnt - 1; break; case SKF_AD_OFF + SKF_AD_VLAN_TPID: BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, vlan_proto) != 2); /* A = *(u16 *) (CTX + offsetof(vlan_proto)) */ *insn++ = BPF_LDX_MEM(BPF_H, BPF_REG_A, BPF_REG_CTX, offsetof(struct sk_buff, vlan_proto)); /* A = ntohs(A) [emitting a nop or swap16] */ *insn = BPF_ENDIAN(BPF_FROM_BE, BPF_REG_A, 16); break; case SKF_AD_OFF + SKF_AD_PAY_OFFSET: case SKF_AD_OFF + SKF_AD_NLATTR: case SKF_AD_OFF + SKF_AD_NLATTR_NEST: case SKF_AD_OFF + SKF_AD_CPU: case SKF_AD_OFF + SKF_AD_RANDOM: /* arg1 = CTX */ *insn++ = BPF_MOV64_REG(BPF_REG_ARG1, BPF_REG_CTX); /* arg2 = A */ *insn++ = BPF_MOV64_REG(BPF_REG_ARG2, BPF_REG_A); /* arg3 = X */ *insn++ = BPF_MOV64_REG(BPF_REG_ARG3, BPF_REG_X); /* Emit call(arg1=CTX, arg2=A, arg3=X) */ switch (fp->k) { case SKF_AD_OFF + SKF_AD_PAY_OFFSET: *insn = BPF_EMIT_CALL(bpf_skb_get_pay_offset); break; case SKF_AD_OFF + SKF_AD_NLATTR: *insn = BPF_EMIT_CALL(bpf_skb_get_nlattr); break; case SKF_AD_OFF + SKF_AD_NLATTR_NEST: *insn = BPF_EMIT_CALL(bpf_skb_get_nlattr_nest); break; case SKF_AD_OFF + SKF_AD_CPU: *insn = BPF_EMIT_CALL(bpf_get_raw_cpu_id); break; case SKF_AD_OFF + SKF_AD_RANDOM: *insn = BPF_EMIT_CALL(bpf_user_rnd_u32); bpf_user_rnd_init_once(); break; } break; case SKF_AD_OFF + SKF_AD_ALU_XOR_X: /* A ^= X */ *insn = BPF_ALU32_REG(BPF_XOR, BPF_REG_A, BPF_REG_X); break; default: /* This is just a dummy call to avoid letting the compiler * evict __bpf_call_base() as an optimization. Placed here * where no-one bothers. */ BUG_ON(__bpf_call_base(0, 0, 0, 0, 0) != 0); return false; } *insnp = insn; return true; } static bool convert_bpf_ld_abs(struct sock_filter *fp, struct bpf_insn **insnp) { const bool unaligned_ok = IS_BUILTIN(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS); int size = bpf_size_to_bytes(BPF_SIZE(fp->code)); bool endian = BPF_SIZE(fp->code) == BPF_H || BPF_SIZE(fp->code) == BPF_W; bool indirect = BPF_MODE(fp->code) == BPF_IND; const int ip_align = NET_IP_ALIGN; struct bpf_insn *insn = *insnp; int offset = fp->k; if (!indirect && ((unaligned_ok && offset >= 0) || (!unaligned_ok && offset >= 0 && offset + ip_align >= 0 && offset + ip_align % size == 0))) { bool ldx_off_ok = offset <= S16_MAX; *insn++ = BPF_MOV64_REG(BPF_REG_TMP, BPF_REG_H); if (offset) *insn++ = BPF_ALU64_IMM(BPF_SUB, BPF_REG_TMP, offset); *insn++ = BPF_JMP_IMM(BPF_JSLT, BPF_REG_TMP, size, 2 + endian + (!ldx_off_ok * 2)); if (ldx_off_ok) { *insn++ = BPF_LDX_MEM(BPF_SIZE(fp->code), BPF_REG_A, BPF_REG_D, offset); } else { *insn++ = BPF_MOV64_REG(BPF_REG_TMP, BPF_REG_D); *insn++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_TMP, offset); *insn++ = BPF_LDX_MEM(BPF_SIZE(fp->code), BPF_REG_A, BPF_REG_TMP, 0); } if (endian) *insn++ = BPF_ENDIAN(BPF_FROM_BE, BPF_REG_A, size * 8); *insn++ = BPF_JMP_A(8); } *insn++ = BPF_MOV64_REG(BPF_REG_ARG1, BPF_REG_CTX); *insn++ = BPF_MOV64_REG(BPF_REG_ARG2, BPF_REG_D); *insn++ = BPF_MOV64_REG(BPF_REG_ARG3, BPF_REG_H); if (!indirect) { *insn++ = BPF_MOV64_IMM(BPF_REG_ARG4, offset); } else { *insn++ = BPF_MOV64_REG(BPF_REG_ARG4, BPF_REG_X); if (fp->k) *insn++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_ARG4, offset); } switch (BPF_SIZE(fp->code)) { case BPF_B: *insn++ = BPF_EMIT_CALL(bpf_skb_load_helper_8); break; case BPF_H: *insn++ = BPF_EMIT_CALL(bpf_skb_load_helper_16); break; case BPF_W: *insn++ = BPF_EMIT_CALL(bpf_skb_load_helper_32); break; default: return false; } *insn++ = BPF_JMP_IMM(BPF_JSGE, BPF_REG_A, 0, 2); *insn++ = BPF_ALU32_REG(BPF_XOR, BPF_REG_A, BPF_REG_A); *insn = BPF_EXIT_INSN(); *insnp = insn; return true; } /** * bpf_convert_filter - convert filter program * @prog: the user passed filter program * @len: the length of the user passed filter program * @new_prog: allocated 'struct bpf_prog' or NULL * @new_len: pointer to store length of converted program * @seen_ld_abs: bool whether we've seen ld_abs/ind * * Remap 'sock_filter' style classic BPF (cBPF) instruction set to 'bpf_insn' * style extended BPF (eBPF). * Conversion workflow: * * 1) First pass for calculating the new program length: * bpf_convert_filter(old_prog, old_len, NULL, &new_len, &seen_ld_abs) * * 2) 2nd pass to remap in two passes: 1st pass finds new * jump offsets, 2nd pass remapping: * bpf_convert_filter(old_prog, old_len, new_prog, &new_len, &seen_ld_abs) */ static int bpf_convert_filter(struct sock_filter *prog, int len, struct bpf_prog *new_prog, int *new_len, bool *seen_ld_abs) { int new_flen = 0, pass = 0, target, i, stack_off; struct bpf_insn *new_insn, *first_insn = NULL; struct sock_filter *fp; int *addrs = NULL; u8 bpf_src; BUILD_BUG_ON(BPF_MEMWORDS * sizeof(u32) > MAX_BPF_STACK); BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG); if (len <= 0 || len > BPF_MAXINSNS) return -EINVAL; if (new_prog) { first_insn = new_prog->insnsi; addrs = kcalloc(len, sizeof(*addrs), GFP_KERNEL | __GFP_NOWARN); if (!addrs) return -ENOMEM; } do_pass: new_insn = first_insn; fp = prog; /* Classic BPF related prologue emission. */ if (new_prog) { /* Classic BPF expects A and X to be reset first. These need * to be guaranteed to be the first two instructions. */ *new_insn++ = BPF_ALU32_REG(BPF_XOR, BPF_REG_A, BPF_REG_A); *new_insn++ = BPF_ALU32_REG(BPF_XOR, BPF_REG_X, BPF_REG_X); /* All programs must keep CTX in callee saved BPF_REG_CTX. * In eBPF case it's done by the compiler, here we need to * do this ourself. Initial CTX is present in BPF_REG_ARG1. */ *new_insn++ = BPF_MOV64_REG(BPF_REG_CTX, BPF_REG_ARG1); if (*seen_ld_abs) { /* For packet access in classic BPF, cache skb->data * in callee-saved BPF R8 and skb->len - skb->data_len * (headlen) in BPF R9. Since classic BPF is read-only * on CTX, we only need to cache it once. */ *new_insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, data), BPF_REG_D, BPF_REG_CTX, offsetof(struct sk_buff, data)); *new_insn++ = BPF_LDX_MEM(BPF_W, BPF_REG_H, BPF_REG_CTX, offsetof(struct sk_buff, len)); *new_insn++ = BPF_LDX_MEM(BPF_W, BPF_REG_TMP, BPF_REG_CTX, offsetof(struct sk_buff, data_len)); *new_insn++ = BPF_ALU32_REG(BPF_SUB, BPF_REG_H, BPF_REG_TMP); } } else { new_insn += 3; } for (i = 0; i < len; fp++, i++) { struct bpf_insn tmp_insns[32] = { }; struct bpf_insn *insn = tmp_insns; if (addrs) addrs[i] = new_insn - first_insn; switch (fp->code) { /* All arithmetic insns and skb loads map as-is. */ case BPF_ALU | BPF_ADD | BPF_X: case BPF_ALU | BPF_ADD | BPF_K: case BPF_ALU | BPF_SUB | BPF_X: case BPF_ALU | BPF_SUB | BPF_K: case BPF_ALU | BPF_AND | BPF_X: case BPF_ALU | BPF_AND | BPF_K: case BPF_ALU | BPF_OR | BPF_X: case BPF_ALU | BPF_OR | BPF_K: case BPF_ALU | BPF_LSH | BPF_X: case BPF_ALU | BPF_LSH | BPF_K: case BPF_ALU | BPF_RSH | BPF_X: case BPF_ALU | BPF_RSH | BPF_K: case BPF_ALU | BPF_XOR | BPF_X: case BPF_ALU | BPF_XOR | BPF_K: case BPF_ALU | BPF_MUL | BPF_X: case BPF_ALU | BPF_MUL | BPF_K: case BPF_ALU | BPF_DIV | BPF_X: case BPF_ALU | BPF_DIV | BPF_K: case BPF_ALU | BPF_MOD | BPF_X: case BPF_ALU | BPF_MOD | BPF_K: case BPF_ALU | BPF_NEG: case BPF_LD | BPF_ABS | BPF_W: case BPF_LD | BPF_ABS | BPF_H: case BPF_LD | BPF_ABS | BPF_B: case BPF_LD | BPF_IND | BPF_W: case BPF_LD | BPF_IND | BPF_H: case BPF_LD | BPF_IND | BPF_B: /* Check for overloaded BPF extension and * directly convert it if found, otherwise * just move on with mapping. */ if (BPF_CLASS(fp->code) == BPF_LD && BPF_MODE(fp->code) == BPF_ABS && convert_bpf_extensions(fp, &insn)) break; if (BPF_CLASS(fp->code) == BPF_LD && convert_bpf_ld_abs(fp, &insn)) { *seen_ld_abs = true; break; } if (fp->code == (BPF_ALU | BPF_DIV | BPF_X) || fp->code == (BPF_ALU | BPF_MOD | BPF_X)) { *insn++ = BPF_MOV32_REG(BPF_REG_X, BPF_REG_X); /* Error with exception code on div/mod by 0. * For cBPF programs, this was always return 0. */ *insn++ = BPF_JMP_IMM(BPF_JNE, BPF_REG_X, 0, 2); *insn++ = BPF_ALU32_REG(BPF_XOR, BPF_REG_A, BPF_REG_A); *insn++ = BPF_EXIT_INSN(); } *insn = BPF_RAW_INSN(fp->code, BPF_REG_A, BPF_REG_X, 0, fp->k); break; /* Jump transformation cannot use BPF block macros * everywhere as offset calculation and target updates * require a bit more work than the rest, i.e. jump * opcodes map as-is, but offsets need adjustment. */ #define BPF_EMIT_JMP \ do { \ const s32 off_min = S16_MIN, off_max = S16_MAX; \ s32 off; \ \ if (target >= len || target < 0) \ goto err; \ off = addrs ? addrs[target] - addrs[i] - 1 : 0; \ /* Adjust pc relative offset for 2nd or 3rd insn. */ \ off -= insn - tmp_insns; \ /* Reject anything not fitting into insn->off. */ \ if (off < off_min || off > off_max) \ goto err; \ insn->off = off; \ } while (0) case BPF_JMP | BPF_JA: target = i + fp->k + 1; insn->code = fp->code; BPF_EMIT_JMP; break; case BPF_JMP | BPF_JEQ | BPF_K: case BPF_JMP | BPF_JEQ | BPF_X: case BPF_JMP | BPF_JSET | BPF_K: case BPF_JMP | BPF_JSET | BPF_X: case BPF_JMP | BPF_JGT | BPF_K: case BPF_JMP | BPF_JGT | BPF_X: case BPF_JMP | BPF_JGE | BPF_K: case BPF_JMP | BPF_JGE | BPF_X: if (BPF_SRC(fp->code) == BPF_K && (int) fp->k < 0) { /* BPF immediates are signed, zero extend * immediate into tmp register and use it * in compare insn. */ *insn++ = BPF_MOV32_IMM(BPF_REG_TMP, fp->k); insn->dst_reg = BPF_REG_A; insn->src_reg = BPF_REG_TMP; bpf_src = BPF_X; } else { insn->dst_reg = BPF_REG_A; insn->imm = fp->k; bpf_src = BPF_SRC(fp->code); insn->src_reg = bpf_src == BPF_X ? BPF_REG_X : 0; } /* Common case where 'jump_false' is next insn. */ if (fp->jf == 0) { insn->code = BPF_JMP | BPF_OP(fp->code) | bpf_src; target = i + fp->jt + 1; BPF_EMIT_JMP; break; } /* Convert some jumps when 'jump_true' is next insn. */ if (fp->jt == 0) { switch (BPF_OP(fp->code)) { case BPF_JEQ: insn->code = BPF_JMP | BPF_JNE | bpf_src; break; case BPF_JGT: insn->code = BPF_JMP | BPF_JLE | bpf_src; break; case BPF_JGE: insn->code = BPF_JMP | BPF_JLT | bpf_src; break; default: goto jmp_rest; } target = i + fp->jf + 1; BPF_EMIT_JMP; break; } jmp_rest: /* Other jumps are mapped into two insns: Jxx and JA. */ target = i + fp->jt + 1; insn->code = BPF_JMP | BPF_OP(fp->code) | bpf_src; BPF_EMIT_JMP; insn++; insn->code = BPF_JMP | BPF_JA; target = i + fp->jf + 1; BPF_EMIT_JMP; break; /* ldxb 4 * ([14] & 0xf) is remaped into 6 insns. */ case BPF_LDX | BPF_MSH | BPF_B: { struct sock_filter tmp = { .code = BPF_LD | BPF_ABS | BPF_B, .k = fp->k, }; *seen_ld_abs = true; /* X = A */ *insn++ = BPF_MOV64_REG(BPF_REG_X, BPF_REG_A); /* A = BPF_R0 = *(u8 *) (skb->data + K) */ convert_bpf_ld_abs(&tmp, &insn); insn++; /* A &= 0xf */ *insn++ = BPF_ALU32_IMM(BPF_AND, BPF_REG_A, 0xf); /* A <<= 2 */ *insn++ = BPF_ALU32_IMM(BPF_LSH, BPF_REG_A, 2); /* tmp = X */ *insn++ = BPF_MOV64_REG(BPF_REG_TMP, BPF_REG_X); /* X = A */ *insn++ = BPF_MOV64_REG(BPF_REG_X, BPF_REG_A); /* A = tmp */ *insn = BPF_MOV64_REG(BPF_REG_A, BPF_REG_TMP); break; } /* RET_K is remaped into 2 insns. RET_A case doesn't need an * extra mov as BPF_REG_0 is already mapped into BPF_REG_A. */ case BPF_RET | BPF_A: case BPF_RET | BPF_K: if (BPF_RVAL(fp->code) == BPF_K) *insn++ = BPF_MOV32_RAW(BPF_K, BPF_REG_0, 0, fp->k); *insn = BPF_EXIT_INSN(); break; /* Store to stack. */ case BPF_ST: case BPF_STX: stack_off = fp->k * 4 + 4; *insn = BPF_STX_MEM(BPF_W, BPF_REG_FP, BPF_CLASS(fp->code) == BPF_ST ? BPF_REG_A : BPF_REG_X, -stack_off); /* check_load_and_stores() verifies that classic BPF can * load from stack only after write, so tracking * stack_depth for ST|STX insns is enough */ if (new_prog && new_prog->aux->stack_depth < stack_off) new_prog->aux->stack_depth = stack_off; break; /* Load from stack. */ case BPF_LD | BPF_MEM: case BPF_LDX | BPF_MEM: stack_off = fp->k * 4 + 4; *insn = BPF_LDX_MEM(BPF_W, BPF_CLASS(fp->code) == BPF_LD ? BPF_REG_A : BPF_REG_X, BPF_REG_FP, -stack_off); break; /* A = K or X = K */ case BPF_LD | BPF_IMM: case BPF_LDX | BPF_IMM: *insn = BPF_MOV32_IMM(BPF_CLASS(fp->code) == BPF_LD ? BPF_REG_A : BPF_REG_X, fp->k); break; /* X = A */ case BPF_MISC | BPF_TAX: *insn = BPF_MOV64_REG(BPF_REG_X, BPF_REG_A); break; /* A = X */ case BPF_MISC | BPF_TXA: *insn = BPF_MOV64_REG(BPF_REG_A, BPF_REG_X); break; /* A = skb->len or X = skb->len */ case BPF_LD | BPF_W | BPF_LEN: case BPF_LDX | BPF_W | BPF_LEN: *insn = BPF_LDX_MEM(BPF_W, BPF_CLASS(fp->code) == BPF_LD ? BPF_REG_A : BPF_REG_X, BPF_REG_CTX, offsetof(struct sk_buff, len)); break; /* Access seccomp_data fields. */ case BPF_LDX | BPF_ABS | BPF_W: /* A = *(u32 *) (ctx + K) */ *insn = BPF_LDX_MEM(BPF_W, BPF_REG_A, BPF_REG_CTX, fp->k); break; /* Unknown instruction. */ default: goto err; } insn++; if (new_prog) memcpy(new_insn, tmp_insns, sizeof(*insn) * (insn - tmp_insns)); new_insn += insn - tmp_insns; } if (!new_prog) { /* Only calculating new length. */ *new_len = new_insn - first_insn; if (*seen_ld_abs) *new_len += 4; /* Prologue bits. */ return 0; } pass++; if (new_flen != new_insn - first_insn) { new_flen = new_insn - first_insn; if (pass > 2) goto err; goto do_pass; } kfree(addrs); BUG_ON(*new_len != new_flen); return 0; err: kfree(addrs); return -EINVAL; } /* Security: * * As we dont want to clear mem[] array for each packet going through * __bpf_prog_run(), we check that filter loaded by user never try to read * a cell if not previously written, and we check all branches to be sure * a malicious user doesn't try to abuse us. */ static int check_load_and_stores(const struct sock_filter *filter, int flen) { u16 *masks, memvalid = 0; /* One bit per cell, 16 cells */ int pc, ret = 0; BUILD_BUG_ON(BPF_MEMWORDS > 16); masks = kmalloc_array(flen, sizeof(*masks), GFP_KERNEL); if (!masks) return -ENOMEM; memset(masks, 0xff, flen * sizeof(*masks)); for (pc = 0; pc < flen; pc++) { memvalid &= masks[pc]; switch (filter[pc].code) { case BPF_ST: case BPF_STX: memvalid |= (1 << filter[pc].k); break; case BPF_LD | BPF_MEM: case BPF_LDX | BPF_MEM: if (!(memvalid & (1 << filter[pc].k))) { ret = -EINVAL; goto error; } break; case BPF_JMP | BPF_JA: /* A jump must set masks on target */ masks[pc + 1 + filter[pc].k] &= memvalid; memvalid = ~0; break; case BPF_JMP | BPF_JEQ | BPF_K: case BPF_JMP | BPF_JEQ | BPF_X: case BPF_JMP | BPF_JGE | BPF_K: case BPF_JMP | BPF_JGE | BPF_X: case BPF_JMP | BPF_JGT | BPF_K: case BPF_JMP | BPF_JGT | BPF_X: case BPF_JMP | BPF_JSET | BPF_K: case BPF_JMP | BPF_JSET | BPF_X: /* A jump must set masks on targets */ masks[pc + 1 + filter[pc].jt] &= memvalid; masks[pc + 1 + filter[pc].jf] &= memvalid; memvalid = ~0; break; } } error: kfree(masks); return ret; } static bool chk_code_allowed(u16 code_to_probe) { static const bool codes[] = { /* 32 bit ALU operations */ [BPF_ALU | BPF_ADD | BPF_K] = true, [BPF_ALU | BPF_ADD | BPF_X] = true, [BPF_ALU | BPF_SUB | BPF_K] = true, [BPF_ALU | BPF_SUB | BPF_X] = true, [BPF_ALU | BPF_MUL | BPF_K] = true, [BPF_ALU | BPF_MUL | BPF_X] = true, [BPF_ALU | BPF_DIV | BPF_K] = true, [BPF_ALU | BPF_DIV | BPF_X] = true, [BPF_ALU | BPF_MOD | BPF_K] = true, [BPF_ALU | BPF_MOD | BPF_X] = true, [BPF_ALU | BPF_AND | BPF_K] = true, [BPF_ALU | BPF_AND | BPF_X] = true, [BPF_ALU | BPF_OR | BPF_K] = true, [BPF_ALU | BPF_OR | BPF_X] = true, [BPF_ALU | BPF_XOR | BPF_K] = true, [BPF_ALU | BPF_XOR | BPF_X] = true, [BPF_ALU | BPF_LSH | BPF_K] = true, [BPF_ALU | BPF_LSH | BPF_X] = true, [BPF_ALU | BPF_RSH | BPF_K] = true, [BPF_ALU | BPF_RSH | BPF_X] = true, [BPF_ALU | BPF_NEG] = true, /* Load instructions */ [BPF_LD | BPF_W | BPF_ABS] = true, [BPF_LD | BPF_H | BPF_ABS] = true, [BPF_LD | BPF_B | BPF_ABS] = true, [BPF_LD | BPF_W | BPF_LEN] = true, [BPF_LD | BPF_W | BPF_IND] = true, [BPF_LD | BPF_H | BPF_IND] = true, [BPF_LD | BPF_B | BPF_IND] = true, [BPF_LD | BPF_IMM] = true, [BPF_LD | BPF_MEM] = true, [BPF_LDX | BPF_W | BPF_LEN] = true, [BPF_LDX | BPF_B | BPF_MSH] = true, [BPF_LDX | BPF_IMM] = true, [BPF_LDX | BPF_MEM] = true, /* Store instructions */ [BPF_ST] = true, [BPF_STX] = true, /* Misc instructions */ [BPF_MISC | BPF_TAX] = true, [BPF_MISC | BPF_TXA] = true, /* Return instructions */ [BPF_RET | BPF_K] = true, [BPF_RET | BPF_A] = true, /* Jump instructions */ [BPF_JMP | BPF_JA] = true, [BPF_JMP | BPF_JEQ | BPF_K] = true, [BPF_JMP | BPF_JEQ | BPF_X] = true, [BPF_JMP | BPF_JGE | BPF_K] = true, [BPF_JMP | BPF_JGE | BPF_X] = true, [BPF_JMP | BPF_JGT | BPF_K] = true, [BPF_JMP | BPF_JGT | BPF_X] = true, [BPF_JMP | BPF_JSET | BPF_K] = true, [BPF_JMP | BPF_JSET | BPF_X] = true, }; if (code_to_probe >= ARRAY_SIZE(codes)) return false; return codes[code_to_probe]; } static bool bpf_check_basics_ok(const struct sock_filter *filter, unsigned int flen) { if (filter == NULL) return false; if (flen == 0 || flen > BPF_MAXINSNS) return false; return true; } /** * bpf_check_classic - verify socket filter code * @filter: filter to verify * @flen: length of filter * * Check the user's filter code. If we let some ugly * filter code slip through kaboom! The filter must contain * no references or jumps that are out of range, no illegal * instructions, and must end with a RET instruction. * * All jumps are forward as they are not signed. * * Returns 0 if the rule set is legal or -EINVAL if not. */ static int bpf_check_classic(const struct sock_filter *filter, unsigned int flen) { bool anc_found; int pc; /* Check the filter code now */ for (pc = 0; pc < flen; pc++) { const struct sock_filter *ftest = &filter[pc]; /* May we actually operate on this code? */ if (!chk_code_allowed(ftest->code)) return -EINVAL; /* Some instructions need special checks */ switch (ftest->code) { case BPF_ALU | BPF_DIV | BPF_K: case BPF_ALU | BPF_MOD | BPF_K: /* Check for division by zero */ if (ftest->k == 0) return -EINVAL; break; case BPF_ALU | BPF_LSH | BPF_K: case BPF_ALU | BPF_RSH | BPF_K: if (ftest->k >= 32) return -EINVAL; break; case BPF_LD | BPF_MEM: case BPF_LDX | BPF_MEM: case BPF_ST: case BPF_STX: /* Check for invalid memory addresses */ if (ftest->k >= BPF_MEMWORDS) return -EINVAL; break; case BPF_JMP | BPF_JA: /* Note, the large ftest->k might cause loops. * Compare this with conditional jumps below, * where offsets are limited. --ANK (981016) */ if (ftest->k >= (unsigned int)(flen - pc - 1)) return -EINVAL; break; case BPF_JMP | BPF_JEQ | BPF_K: case BPF_JMP | BPF_JEQ | BPF_X: case BPF_JMP | BPF_JGE | BPF_K: case BPF_JMP | BPF_JGE | BPF_X: case BPF_JMP | BPF_JGT | BPF_K: case BPF_JMP | BPF_JGT | BPF_X: case BPF_JMP | BPF_JSET | BPF_K: case BPF_JMP | BPF_JSET | BPF_X: /* Both conditionals must be safe */ if (pc + ftest->jt + 1 >= flen || pc + ftest->jf + 1 >= flen) return -EINVAL; break; case BPF_LD | BPF_W | BPF_ABS: case BPF_LD | BPF_H | BPF_ABS: case BPF_LD | BPF_B | BPF_ABS: anc_found = false; if (bpf_anc_helper(ftest) & BPF_ANC) anc_found = true; /* Ancillary operation unknown or unsupported */ if (anc_found == false && ftest->k >= SKF_AD_OFF) return -EINVAL; } } /* Last instruction must be a RET code */ switch (filter[flen - 1].code) { case BPF_RET | BPF_K: case BPF_RET | BPF_A: return check_load_and_stores(filter, flen); } return -EINVAL; } static int bpf_prog_store_orig_filter(struct bpf_prog *fp, const struct sock_fprog *fprog) { unsigned int fsize = bpf_classic_proglen(fprog); struct sock_fprog_kern *fkprog; fp->orig_prog = kmalloc(sizeof(*fkprog), GFP_KERNEL); if (!fp->orig_prog) return -ENOMEM; fkprog = fp->orig_prog; fkprog->len = fprog->len; fkprog->filter = kmemdup(fp->insns, fsize, GFP_KERNEL | __GFP_NOWARN); if (!fkprog->filter) { kfree(fp->orig_prog); return -ENOMEM; } return 0; } static void bpf_release_orig_filter(struct bpf_prog *fp) { struct sock_fprog_kern *fprog = fp->orig_prog; if (fprog) { kfree(fprog->filter); kfree(fprog); } } static void __bpf_prog_release(struct bpf_prog *prog) { if (prog->type == BPF_PROG_TYPE_SOCKET_FILTER) { bpf_prog_put(prog); } else { bpf_release_orig_filter(prog); bpf_prog_free(prog); } } static void __sk_filter_release(struct sk_filter *fp) { __bpf_prog_release(fp->prog); kfree(fp); } /** * sk_filter_release_rcu - Release a socket filter by rcu_head * @rcu: rcu_head that contains the sk_filter to free */ static void sk_filter_release_rcu(struct rcu_head *rcu) { struct sk_filter *fp = container_of(rcu, struct sk_filter, rcu); __sk_filter_release(fp); } /** * sk_filter_release - release a socket filter * @fp: filter to remove * * Remove a filter from a socket and release its resources. */ static void sk_filter_release(struct sk_filter *fp) { if (refcount_dec_and_test(&fp->refcnt)) call_rcu(&fp->rcu, sk_filter_release_rcu); } void sk_filter_uncharge(struct sock *sk, struct sk_filter *fp) { u32 filter_size = bpf_prog_size(fp->prog->len); atomic_sub(filter_size, &sk->sk_omem_alloc); sk_filter_release(fp); } /* try to charge the socket memory if there is space available * return true on success */ static bool __sk_filter_charge(struct sock *sk, struct sk_filter *fp) { u32 filter_size = bpf_prog_size(fp->prog->len); /* same check as in sock_kmalloc() */ if (filter_size <= sysctl_optmem_max && atomic_read(&sk->sk_omem_alloc) + filter_size < sysctl_optmem_max) { atomic_add(filter_size, &sk->sk_omem_alloc); return true; } return false; } bool sk_filter_charge(struct sock *sk, struct sk_filter *fp) { if (!refcount_inc_not_zero(&fp->refcnt)) return false; if (!__sk_filter_charge(sk, fp)) { sk_filter_release(fp); return false; } return true; } static struct bpf_prog *bpf_migrate_filter(struct bpf_prog *fp) { struct sock_filter *old_prog; struct bpf_prog *old_fp; int err, new_len, old_len = fp->len; bool seen_ld_abs = false; /* We are free to overwrite insns et al right here as it * won't be used at this point in time anymore internally * after the migration to the internal BPF instruction * representation. */ BUILD_BUG_ON(sizeof(struct sock_filter) != sizeof(struct bpf_insn)); /* Conversion cannot happen on overlapping memory areas, * so we need to keep the user BPF around until the 2nd * pass. At this time, the user BPF is stored in fp->insns. */ old_prog = kmemdup(fp->insns, old_len * sizeof(struct sock_filter), GFP_KERNEL | __GFP_NOWARN); if (!old_prog) { err = -ENOMEM; goto out_err; } /* 1st pass: calculate the new program length. */ err = bpf_convert_filter(old_prog, old_len, NULL, &new_len, &seen_ld_abs); if (err) goto out_err_free; /* Expand fp for appending the new filter representation. */ old_fp = fp; fp = bpf_prog_realloc(old_fp, bpf_prog_size(new_len), 0); if (!fp) { /* The old_fp is still around in case we couldn't * allocate new memory, so uncharge on that one. */ fp = old_fp; err = -ENOMEM; goto out_err_free; } fp->len = new_len; /* 2nd pass: remap sock_filter insns into bpf_insn insns. */ err = bpf_convert_filter(old_prog, old_len, fp, &new_len, &seen_ld_abs); if (err) /* 2nd bpf_convert_filter() can fail only if it fails * to allocate memory, remapping must succeed. Note, * that at this time old_fp has already been released * by krealloc(). */ goto out_err_free; fp = bpf_prog_select_runtime(fp, &err); if (err) goto out_err_free; kfree(old_prog); return fp; out_err_free: kfree(old_prog); out_err: __bpf_prog_release(fp); return ERR_PTR(err); } static struct bpf_prog *bpf_prepare_filter(struct bpf_prog *fp, bpf_aux_classic_check_t trans) { int err; fp->bpf_func = NULL; fp->jited = 0; err = bpf_check_classic(fp->insns, fp->len); if (err) { __bpf_prog_release(fp); return ERR_PTR(err); } /* There might be additional checks and transformations * needed on classic filters, f.e. in case of seccomp. */ if (trans) { err = trans(fp->insns, fp->len); if (err) { __bpf_prog_release(fp); return ERR_PTR(err); } } /* Probe if we can JIT compile the filter and if so, do * the compilation of the filter. */ bpf_jit_compile(fp); /* JIT compiler couldn't process this filter, so do the * internal BPF translation for the optimized interpreter. */ if (!fp->jited) fp = bpf_migrate_filter(fp); return fp; } /** * bpf_prog_create - create an unattached filter * @pfp: the unattached filter that is created * @fprog: the filter program * * Create a filter independent of any socket. We first run some * sanity checks on it to make sure it does not explode on us later. * If an error occurs or there is insufficient memory for the filter * a negative errno code is returned. On success the return is zero. */ int bpf_prog_create(struct bpf_prog **pfp, struct sock_fprog_kern *fprog) { unsigned int fsize = bpf_classic_proglen(fprog); struct bpf_prog *fp; /* Make sure new filter is there and in the right amounts. */ if (!bpf_check_basics_ok(fprog->filter, fprog->len)) return -EINVAL; fp = bpf_prog_alloc(bpf_prog_size(fprog->len), 0); if (!fp) return -ENOMEM; memcpy(fp->insns, fprog->filter, fsize); fp->len = fprog->len; /* Since unattached filters are not copied back to user * space through sk_get_filter(), we do not need to hold * a copy here, and can spare us the work. */ fp->orig_prog = NULL; /* bpf_prepare_filter() already takes care of freeing * memory in case something goes wrong. */ fp = bpf_prepare_filter(fp, NULL); if (IS_ERR(fp)) return PTR_ERR(fp); *pfp = fp; return 0; } EXPORT_SYMBOL_GPL(bpf_prog_create); /** * bpf_prog_create_from_user - create an unattached filter from user buffer * @pfp: the unattached filter that is created * @fprog: the filter program * @trans: post-classic verifier transformation handler * @save_orig: save classic BPF program * * This function effectively does the same as bpf_prog_create(), only * that it builds up its insns buffer from user space provided buffer. * It also allows for passing a bpf_aux_classic_check_t handler. */ int bpf_prog_create_from_user(struct bpf_prog **pfp, struct sock_fprog *fprog, bpf_aux_classic_check_t trans, bool save_orig) { unsigned int fsize = bpf_classic_proglen(fprog); struct bpf_prog *fp; int err; /* Make sure new filter is there and in the right amounts. */ if (!bpf_check_basics_ok(fprog->filter, fprog->len)) return -EINVAL; fp = bpf_prog_alloc(bpf_prog_size(fprog->len), 0); if (!fp) return -ENOMEM; if (copy_from_user(fp->insns, fprog->filter, fsize)) { __bpf_prog_free(fp); return -EFAULT; } fp->len = fprog->len; fp->orig_prog = NULL; if (save_orig) { err = bpf_prog_store_orig_filter(fp, fprog); if (err) { __bpf_prog_free(fp); return -ENOMEM; } } /* bpf_prepare_filter() already takes care of freeing * memory in case something goes wrong. */ fp = bpf_prepare_filter(fp, trans); if (IS_ERR(fp)) return PTR_ERR(fp); *pfp = fp; return 0; } EXPORT_SYMBOL_GPL(bpf_prog_create_from_user); void bpf_prog_destroy(struct bpf_prog *fp) { __bpf_prog_release(fp); } EXPORT_SYMBOL_GPL(bpf_prog_destroy); static int __sk_attach_prog(struct bpf_prog *prog, struct sock *sk) { struct sk_filter *fp, *old_fp; fp = kmalloc(sizeof(*fp), GFP_KERNEL); if (!fp) return -ENOMEM; fp->prog = prog; if (!__sk_filter_charge(sk, fp)) { kfree(fp); return -ENOMEM; } refcount_set(&fp->refcnt, 1); old_fp = rcu_dereference_protected(sk->sk_filter, lockdep_sock_is_held(sk)); rcu_assign_pointer(sk->sk_filter, fp); if (old_fp) sk_filter_uncharge(sk, old_fp); return 0; } static struct bpf_prog *__get_filter(struct sock_fprog *fprog, struct sock *sk) { unsigned int fsize = bpf_classic_proglen(fprog); struct bpf_prog *prog; int err; if (sock_flag(sk, SOCK_FILTER_LOCKED)) return ERR_PTR(-EPERM); /* Make sure new filter is there and in the right amounts. */ if (!bpf_check_basics_ok(fprog->filter, fprog->len)) return ERR_PTR(-EINVAL); prog = bpf_prog_alloc(bpf_prog_size(fprog->len), 0); if (!prog) return ERR_PTR(-ENOMEM); if (copy_from_user(prog->insns, fprog->filter, fsize)) { __bpf_prog_free(prog); return ERR_PTR(-EFAULT); } prog->len = fprog->len; err = bpf_prog_store_orig_filter(prog, fprog); if (err) { __bpf_prog_free(prog); return ERR_PTR(-ENOMEM); } /* bpf_prepare_filter() already takes care of freeing * memory in case something goes wrong. */ return bpf_prepare_filter(prog, NULL); } /** * sk_attach_filter - attach a socket filter * @fprog: the filter program * @sk: the socket to use * * Attach the user's filter code. We first run some sanity checks on * it to make sure it does not explode on us later. If an error * occurs or there is insufficient memory for the filter a negative * errno code is returned. On success the return is zero. */ int sk_attach_filter(struct sock_fprog *fprog, struct sock *sk) { struct bpf_prog *prog = __get_filter(fprog, sk); int err; if (IS_ERR(prog)) return PTR_ERR(prog); err = __sk_attach_prog(prog, sk); if (err < 0) { __bpf_prog_release(prog); return err; } return 0; } EXPORT_SYMBOL_GPL(sk_attach_filter); int sk_reuseport_attach_filter(struct sock_fprog *fprog, struct sock *sk) { struct bpf_prog *prog = __get_filter(fprog, sk); int err; if (IS_ERR(prog)) return PTR_ERR(prog); if (bpf_prog_size(prog->len) > sysctl_optmem_max) err = -ENOMEM; else err = reuseport_attach_prog(sk, prog); if (err) __bpf_prog_release(prog); return err; } static struct bpf_prog *__get_bpf(u32 ufd, struct sock *sk) { if (sock_flag(sk, SOCK_FILTER_LOCKED)) return ERR_PTR(-EPERM); return bpf_prog_get_type(ufd, BPF_PROG_TYPE_SOCKET_FILTER); } int sk_attach_bpf(u32 ufd, struct sock *sk) { struct bpf_prog *prog = __get_bpf(ufd, sk); int err; if (IS_ERR(prog)) return PTR_ERR(prog); err = __sk_attach_prog(prog, sk); if (err < 0) { bpf_prog_put(prog); return err; } return 0; } int sk_reuseport_attach_bpf(u32 ufd, struct sock *sk) { struct bpf_prog *prog; int err; if (sock_flag(sk, SOCK_FILTER_LOCKED)) return -EPERM; prog = bpf_prog_get_type(ufd, BPF_PROG_TYPE_SOCKET_FILTER); if (IS_ERR(prog) && PTR_ERR(prog) == -EINVAL) prog = bpf_prog_get_type(ufd, BPF_PROG_TYPE_SK_REUSEPORT); if (IS_ERR(prog)) return PTR_ERR(prog); if (prog->type == BPF_PROG_TYPE_SK_REUSEPORT) { /* Like other non BPF_PROG_TYPE_SOCKET_FILTER * bpf prog (e.g. sockmap). It depends on the * limitation imposed by bpf_prog_load(). * Hence, sysctl_optmem_max is not checked. */ if ((sk->sk_type != SOCK_STREAM && sk->sk_type != SOCK_DGRAM) || (sk->sk_protocol != IPPROTO_UDP && sk->sk_protocol != IPPROTO_TCP) || (sk->sk_family != AF_INET && sk->sk_family != AF_INET6)) { err = -ENOTSUPP; goto err_prog_put; } } else { /* BPF_PROG_TYPE_SOCKET_FILTER */ if (bpf_prog_size(prog->len) > sysctl_optmem_max) { err = -ENOMEM; goto err_prog_put; } } err = reuseport_attach_prog(sk, prog); err_prog_put: if (err) bpf_prog_put(prog); return err; } void sk_reuseport_prog_free(struct bpf_prog *prog) { if (!prog) return; if (prog->type == BPF_PROG_TYPE_SK_REUSEPORT) bpf_prog_put(prog); else bpf_prog_destroy(prog); } struct bpf_scratchpad { union { __be32 diff[MAX_BPF_STACK / sizeof(__be32)]; u8 buff[MAX_BPF_STACK]; }; }; static DEFINE_PER_CPU(struct bpf_scratchpad, bpf_sp); static inline int __bpf_try_make_writable(struct sk_buff *skb, unsigned int write_len) { return skb_ensure_writable(skb, write_len); } static inline int bpf_try_make_writable(struct sk_buff *skb, unsigned int write_len) { int err = __bpf_try_make_writable(skb, write_len); bpf_compute_data_pointers(skb); return err; } static int bpf_try_make_head_writable(struct sk_buff *skb) { return bpf_try_make_writable(skb, skb_headlen(skb)); } static inline void bpf_push_mac_rcsum(struct sk_buff *skb) { if (skb_at_tc_ingress(skb)) skb_postpush_rcsum(skb, skb_mac_header(skb), skb->mac_len); } static inline void bpf_pull_mac_rcsum(struct sk_buff *skb) { if (skb_at_tc_ingress(skb)) skb_postpull_rcsum(skb, skb_mac_header(skb), skb->mac_len); } BPF_CALL_5(bpf_skb_store_bytes, struct sk_buff *, skb, u32, offset, const void *, from, u32, len, u64, flags) { void *ptr; if (unlikely(flags & ~(BPF_F_RECOMPUTE_CSUM | BPF_F_INVALIDATE_HASH))) return -EINVAL; if (unlikely(offset > 0xffff)) return -EFAULT; if (unlikely(bpf_try_make_writable(skb, offset + len))) return -EFAULT; ptr = skb->data + offset; if (flags & BPF_F_RECOMPUTE_CSUM) __skb_postpull_rcsum(skb, ptr, len, offset); memcpy(ptr, from, len); if (flags & BPF_F_RECOMPUTE_CSUM) __skb_postpush_rcsum(skb, ptr, len, offset); if (flags & BPF_F_INVALIDATE_HASH) skb_clear_hash(skb); return 0; } static const struct bpf_func_proto bpf_skb_store_bytes_proto = { .func = bpf_skb_store_bytes, .gpl_only = false, .ret_type = RET_INTEGER, .arg1_type = ARG_PTR_TO_CTX, .arg2_type = ARG_ANYTHING, .arg3_type = ARG_PTR_TO_MEM, .arg4_type = ARG_CONST_SIZE, .arg5_type = ARG_ANYTHING, }; BPF_CALL_4(bpf_skb_load_bytes, const struct sk_buff *, skb, u32, offset, void *, to, u32, len) { void *ptr; if (unlikely(offset > 0xffff)) goto err_clear; ptr = skb_header_pointer(skb, offset, len, to); if (unlikely(!ptr)) goto err_clear; if (ptr != to) memcpy(to, ptr, len); return 0; err_clear: memset(to, 0, len); return -EFAULT; } static const struct bpf_func_proto bpf_skb_load_bytes_proto = { .func = bpf_skb_load_bytes, .gpl_only = false, .ret_type = RET_INTEGER, .arg1_type = ARG_PTR_TO_CTX, .arg2_type = ARG_ANYTHING, .arg3_type = ARG_PTR_TO_UNINIT_MEM, .arg4_type = ARG_CONST_SIZE, }; BPF_CALL_4(bpf_flow_dissector_load_bytes, const struct bpf_flow_dissector *, ctx, u32, offset, void *, to, u32, len) { void *ptr; if (unlikely(offset > 0xffff)) goto err_clear; if (unlikely(!ctx->skb)) goto err_clear; ptr = skb_header_pointer(ctx->skb, offset, len, to); if (unlikely(!ptr)) goto err_clear; if (ptr != to) memcpy(to, ptr, len); return 0; err_clear: memset(to, 0, len); return -EFAULT; } static const struct bpf_func_proto bpf_flow_dissector_load_bytes_proto = { .func = bpf_flow_dissector_load_bytes, .gpl_only = false, .ret_type = RET_INTEGER, .arg1_type = ARG_PTR_TO_CTX, .arg2_type = ARG_ANYTHING, .arg3_type = ARG_PTR_TO_UNINIT_MEM, .arg4_type = ARG_CONST_SIZE, }; BPF_CALL_5(bpf_skb_load_bytes_relative, const struct sk_buff *, skb, u32, offset, void *, to, u32, len, u32, start_header) { u8 *end = skb_tail_pointer(skb); u8 *net = skb_network_header(skb); u8 *mac = skb_mac_header(skb); u8 *ptr; if (unlikely(offset > 0xffff || len > (end - mac))) goto err_clear; switch (start_header) { case BPF_HDR_START_MAC: ptr = mac + offset; break; case BPF_HDR_START_NET: ptr = net + offset; break; default: goto err_clear; } if (likely(ptr >= mac && ptr + len <= end)) { memcpy(to, ptr, len); return 0; } err_clear: memset(to, 0, len); return -EFAULT; } static const struct bpf_func_proto bpf_skb_load_bytes_relative_proto = { .func = bpf_skb_load_bytes_relative, .gpl_only = false, .ret_type = RET_INTEGER, .arg1_type = ARG_PTR_TO_CTX, .arg2_type = ARG_ANYTHING, .arg3_type = ARG_PTR_TO_UNINIT_MEM, .arg4_type = ARG_CONST_SIZE, .arg5_type = ARG_ANYTHING, }; BPF_CALL_2(bpf_skb_pull_data, struct sk_buff *, skb, u32, len) { /* Idea is the following: should the needed direct read/write * test fail during runtime, we can pull in more data and redo * again, since implicitly, we invalidate previous checks here. * * Or, since we know how much we need to make read/writeable, * this can be done once at the program beginning for direct * access case. By this we overcome limitations of only current * headroom being accessible. */ return bpf_try_make_writable(skb, len ? : skb_headlen(skb)); } static const struct bpf_func_proto bpf_skb_pull_data_proto = { .func = bpf_skb_pull_data, .gpl_only = false, .ret_type = RET_INTEGER, .arg1_type = ARG_PTR_TO_CTX, .arg2_type = ARG_ANYTHING, }; BPF_CALL_1(bpf_sk_fullsock, struct sock *, sk) { return sk_fullsock(sk) ? (unsigned long)sk : (unsigned long)NULL; } static const struct bpf_func_proto bpf_sk_fullsock_proto = { .func = bpf_sk_fullsock, .gpl_only = false, .ret_type = RET_PTR_TO_SOCKET_OR_NULL, .arg1_type = ARG_PTR_TO_SOCK_COMMON, }; static inline int sk_skb_try_make_writable(struct sk_buff *skb, unsigned int write_len) { int err = __bpf_try_make_writable(skb, write_len); bpf_compute_data_end_sk_skb(skb); return err; } BPF_CALL_2(sk_skb_pull_data, struct sk_buff *, skb, u32, len) { /* Idea is the following: should the needed direct read/write * test fail during runtime, we can pull in more data and redo * again, since implicitly, we invalidate previous checks here. * * Or, since we know how much we need to make read/writeable, * this can be done once at the program beginning for direct * access case. By this we overcome limitations of only current * headroom being accessible. */ return sk_skb_try_make_writable(skb, len ? : skb_headlen(skb)); } static const struct bpf_func_proto sk_skb_pull_data_proto = { .func = sk_skb_pull_data, .gpl_only = false, .ret_type = RET_INTEGER, .arg1_type = ARG_PTR_TO_CTX, .arg2_type = ARG_ANYTHING, }; BPF_CALL_5(bpf_l3_csum_replace, struct sk_buff *, skb, u32, offset, u64, from, u64, to, u64, flags) { __sum16 *ptr; if (unlikely(flags & ~(BPF_F_HDR_FIELD_MASK))) return -EINVAL; if (unlikely(offset > 0xffff || offset & 1)) return -EFAULT; if (unlikely(bpf_try_make_writable(skb, offset + sizeof(*ptr)))) return -EFAULT; ptr = (__sum16 *)(skb->data + offset); switch (flags & BPF_F_HDR_FIELD_MASK) { case 0: if (unlikely(from != 0)) return -EINVAL; csum_replace_by_diff(ptr, to); break; case 2: csum_replace2(ptr, from, to); break; case 4: csum_replace4(ptr, from, to); break; default: return -EINVAL; } return 0; } static const struct bpf_func_proto bpf_l3_csum_replace_proto = { .func = bpf_l3_csum_replace, .gpl_only = false, .ret_type = RET_INTEGER, .arg1_type = ARG_PTR_TO_CTX, .arg2_type = ARG_ANYTHING, .arg3_type = ARG_ANYTHING, .arg4_type = ARG_ANYTHING, .arg5_type = ARG_ANYTHING, }; BPF_CALL_5(bpf_l4_csum_replace, struct sk_buff *, skb, u32, offset, u64, from, u64, to, u64, flags) { bool is_pseudo = flags & BPF_F_PSEUDO_HDR; bool is_mmzero = flags & BPF_F_MARK_MANGLED_0; bool do_mforce = flags & BPF_F_MARK_ENFORCE; __sum16 *ptr; if (unlikely(flags & ~(BPF_F_MARK_MANGLED_0 | BPF_F_MARK_ENFORCE | BPF_F_PSEUDO_HDR | BPF_F_HDR_FIELD_MASK))) return -EINVAL; if (unlikely(offset > 0xffff || offset & 1)) return -EFAULT; if (unlikely(bpf_try_make_writable(skb, offset + sizeof(*ptr)))) return -EFAULT; ptr = (__sum16 *)(skb->data + offset); if (is_mmzero && !do_mforce && !*ptr) return 0; switch (flags & BPF_F_HDR_FIELD_MASK) { case 0: if (unlikely(from != 0)) return -EINVAL; inet_proto_csum_replace_by_diff(ptr, skb, to, is_pseudo); break; case 2: inet_proto_csum_replace2(ptr, skb, from, to, is_pseudo); break; case 4: inet_proto_csum_replace4(ptr, skb, from, to, is_pseudo); break; default: return -EINVAL; } if (is_mmzero && !*ptr) *ptr = CSUM_MANGLED_0; return 0; } static const struct bpf_func_proto bpf_l4_csum_replace_proto = { .func = bpf_l4_csum_replace, .gpl_only = false, .ret_type = RET_INTEGER, .arg1_type = ARG_PTR_TO_CTX, .arg2_type = ARG_ANYTHING, .arg3_type = ARG_ANYTHING, .arg4_type = ARG_ANYTHING, .arg5_type = ARG_ANYTHING, }; BPF_CALL_5(bpf_csum_diff, __be32 *, from, u32, from_size, __be32 *, to, u32, to_size, __wsum, seed) { struct bpf_scratchpad *sp = this_cpu_ptr(&bpf_sp); u32 diff_size = from_size + to_size; int i, j = 0; /* This is quite flexible, some examples: * * from_size == 0, to_size > 0, seed := csum --> pushing data * from_size > 0, to_size == 0, seed := csum --> pulling data * from_size > 0, to_size > 0, seed := 0 --> diffing data * * Even for diffing, from_size and to_size don't need to be equal. */ if (unlikely(((from_size | to_size) & (sizeof(__be32) - 1)) || diff_size > sizeof(sp->diff))) return -EINVAL; for (i = 0; i < from_size / sizeof(__be32); i++, j++) sp->diff[j] = ~from[i]; for (i = 0; i < to_size / sizeof(__be32); i++, j++) sp->diff[j] = to[i]; return csum_partial(sp->diff, diff_size, seed); } static const struct bpf_func_proto bpf_csum_diff_proto = { .func = bpf_csum_diff, .gpl_only = false, .pkt_access = true, .ret_type = RET_INTEGER, .arg1_type = ARG_PTR_TO_MEM_OR_NULL, .arg2_type = ARG_CONST_SIZE_OR_ZERO, .arg3_type = ARG_PTR_TO_MEM_OR_NULL, .arg4_type = ARG_CONST_SIZE_OR_ZERO, .arg5_type = ARG_ANYTHING, }; BPF_CALL_2(bpf_csum_update, struct sk_buff *, skb, __wsum, csum) { /* The interface is to be used in combination with bpf_csum_diff() * for direct packet writes. csum rotation for alignment as well * as emulating csum_sub() can be done from the eBPF program. */ if (skb->ip_summed == CHECKSUM_COMPLETE) return (skb->csum = csum_add(skb->csum, csum)); return -ENOTSUPP; } static const struct bpf_func_proto bpf_csum_update_proto = { .func = bpf_csum_update, .gpl_only = false, .ret_type = RET_INTEGER, .arg1_type = ARG_PTR_TO_CTX, .arg2_type = ARG_ANYTHING, }; static inline int __bpf_rx_skb(struct net_device *dev, struct sk_buff *skb) { return dev_forward_skb(dev, skb); } static inline int __bpf_rx_skb_no_mac(struct net_device *dev, struct sk_buff *skb) { int ret = ____dev_forward_skb(dev, skb); if (likely(!ret)) { skb->dev = dev; ret = netif_rx(skb); } return ret; } static inline int __bpf_tx_skb(struct net_device *dev, struct sk_buff *skb) { int ret; if (dev_xmit_recursion()) { net_crit_ratelimited("bpf: recursion limit reached on datapath, buggy bpf program?\n"); kfree_skb(skb); return -ENETDOWN; } skb->dev = dev; dev_xmit_recursion_inc(); ret = dev_queue_xmit(skb); dev_xmit_recursion_dec(); return ret; } static int __bpf_redirect_no_mac(struct sk_buff *skb, struct net_device *dev, u32 flags) { unsigned int mlen = skb_network_offset(skb); if (mlen) { __skb_pull(skb, mlen); /* At ingress, the mac header has already been pulled once. * At egress, skb_pospull_rcsum has to be done in case that * the skb is originated from ingress (i.e. a forwarded skb) * to ensure that rcsum starts at net header. */ if (!skb_at_tc_ingress(skb)) skb_postpull_rcsum(skb, skb_mac_header(skb), mlen); } skb_pop_mac_header(skb); skb_reset_mac_len(skb); return flags & BPF_F_INGRESS ? __bpf_rx_skb_no_mac(dev, skb) : __bpf_tx_skb(dev, skb); } static int __bpf_redirect_common(struct sk_buff *skb, struct net_device *dev, u32 flags) { /* Verify that a link layer header is carried */ if (unlikely(skb->mac_header >= skb->network_header)) { kfree_skb(skb); return -ERANGE; } bpf_push_mac_rcsum(skb); return flags & BPF_F_INGRESS ? __bpf_rx_skb(dev, skb) : __bpf_tx_skb(dev, skb); } static int __bpf_redirect(struct sk_buff *skb, struct net_device *dev, u32 flags) { if (dev_is_mac_header_xmit(dev)) return __bpf_redirect_common(skb, dev, flags); else return __bpf_redirect_no_mac(skb, dev, flags); } BPF_CALL_3(bpf_clone_redirect, struct sk_buff *, skb, u32, ifindex, u64, flags) { struct net_device *dev; struct sk_buff *clone; int ret; if (unlikely(flags & ~(BPF_F_INGRESS))) return -EINVAL; dev = dev_get_by_index_rcu(dev_net(skb->dev), ifindex); if (unlikely(!dev)) return -EINVAL; clone = skb_clone(skb, GFP_ATOMIC); if (unlikely(!clone)) return -ENOMEM; /* For direct write, we need to keep the invariant that the skbs * we're dealing with need to be uncloned. Should uncloning fail * here, we need to free the just generated clone to unclone once * again. */ ret = bpf_try_make_head_writable(skb); if (unlikely(ret)) { kfree_skb(clone); return -ENOMEM; } return __bpf_redirect(clone, dev, flags); } static const struct bpf_func_proto bpf_clone_redirect_proto = { .func = bpf_clone_redirect, .gpl_only = false, .ret_type = RET_INTEGER, .arg1_type = ARG_PTR_TO_CTX, .arg2_type = ARG_ANYTHING, .arg3_type = ARG_ANYTHING, }; DEFINE_PER_CPU(struct bpf_redirect_info, bpf_redirect_info); EXPORT_PER_CPU_SYMBOL_GPL(bpf_redirect_info); BPF_CALL_2(bpf_redirect, u32, ifindex, u64, flags) { struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info); if (unlikely(flags & ~(BPF_F_INGRESS))) return TC_ACT_SHOT; ri->ifindex = ifindex; ri->flags = flags; return TC_ACT_REDIRECT; } int skb_do_redirect(struct sk_buff *skb) { struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info); struct net_device *dev; dev = dev_get_by_index_rcu(dev_net(skb->dev), ri->ifindex); ri->ifindex = 0; if (unlikely(!dev)) { kfree_skb(skb); return -EINVAL; } return __bpf_redirect(skb, dev, ri->flags); } static const struct bpf_func_proto bpf_redirect_proto = { .func = bpf_redirect, .gpl_only = false, .ret_type = RET_INTEGER, .arg1_type = ARG_ANYTHING, .arg2_type = ARG_ANYTHING, }; BPF_CALL_2(bpf_msg_apply_bytes, struct sk_msg *, msg, u32, bytes) { msg->apply_bytes = bytes; return 0; } static const struct bpf_func_proto bpf_msg_apply_bytes_proto = { .func = bpf_msg_apply_bytes, .gpl_only = false, .ret_type = RET_INTEGER, .arg1_type = ARG_PTR_TO_CTX, .arg2_type = ARG_ANYTHING, }; BPF_CALL_2(bpf_msg_cork_bytes, struct sk_msg *, msg, u32, bytes) { msg->cork_bytes = bytes; return 0; } static const struct bpf_func_proto bpf_msg_cork_bytes_proto = { .func = bpf_msg_cork_bytes, .gpl_only = false, .ret_type = RET_INTEGER, .arg1_type = ARG_PTR_TO_CTX, .arg2_type = ARG_ANYTHING, }; BPF_CALL_4(bpf_msg_pull_data, struct sk_msg *, msg, u32, start, u32, end, u64, flags) { u32 len = 0, offset = 0, copy = 0, poffset = 0, bytes = end - start; u32 first_sge, last_sge, i, shift, bytes_sg_total; struct scatterlist *sge; u8 *raw, *to, *from; struct page *page; if (unlikely(flags || end <= start)) return -EINVAL; /* First find the starting scatterlist element */ i = msg->sg.start; do { len = sk_msg_elem(msg, i)->length; if (start < offset + len) break; offset += len; sk_msg_iter_var_next(i); } while (i != msg->sg.end); if (unlikely(start >= offset + len)) return -EINVAL; first_sge = i; /* The start may point into the sg element so we need to also * account for the headroom. */ bytes_sg_total = start - offset + bytes; if (!msg->sg.copy[i] && bytes_sg_total <= len) goto out; /* At this point we need to linearize multiple scatterlist * elements or a single shared page. Either way we need to * copy into a linear buffer exclusively owned by BPF. Then * place the buffer in the scatterlist and fixup the original * entries by removing the entries now in the linear buffer * and shifting the remaining entries. For now we do not try * to copy partial entries to avoid complexity of running out * of sg_entry slots. The downside is reading a single byte * will copy the entire sg entry. */ do { copy += sk_msg_elem(msg, i)->length; sk_msg_iter_var_next(i); if (bytes_sg_total <= copy) break; } while (i != msg->sg.end); last_sge = i; if (unlikely(bytes_sg_total > copy)) return -EINVAL; page = alloc_pages(__GFP_NOWARN | GFP_ATOMIC | __GFP_COMP, get_order(copy)); if (unlikely(!page)) return -ENOMEM; raw = page_address(page); i = first_sge; do { sge = sk_msg_elem(msg, i); from = sg_virt(sge); len = sge->length; to = raw + poffset; memcpy(to, from, len); poffset += len; sge->length = 0; put_page(sg_page(sge)); sk_msg_iter_var_next(i); } while (i != last_sge); sg_set_page(&msg->sg.data[first_sge], page, copy, 0); /* To repair sg ring we need to shift entries. If we only * had a single entry though we can just replace it and * be done. Otherwise walk the ring and shift the entries. */ WARN_ON_ONCE(last_sge == first_sge); shift = last_sge > first_sge ? last_sge - first_sge - 1 : MAX_SKB_FRAGS - first_sge + last_sge - 1; if (!shift) goto out; i = first_sge; sk_msg_iter_var_next(i); do { u32 move_from; if (i + shift >= MAX_MSG_FRAGS) move_from = i + shift - MAX_MSG_FRAGS; else move_from = i + shift; if (move_from == msg->sg.end) break; msg->sg.data[i] = msg->sg.data[move_from]; msg->sg.data[move_from].length = 0; msg->sg.data[move_from].page_link = 0; msg->sg.data[move_from].offset = 0; sk_msg_iter_var_next(i); } while (1); msg->sg.end = msg->sg.end - shift > msg->sg.end ? msg->sg.end - shift + MAX_MSG_FRAGS : msg->sg.end - shift; out: msg->data = sg_virt(&msg->sg.data[first_sge]) + start - offset; msg->data_end = msg->data + bytes; return 0; } static const struct bpf_func_proto bpf_msg_pull_data_proto = { .func = bpf_msg_pull_data, .gpl_only = false, .ret_type = RET_INTEGER, .arg1_type = ARG_PTR_TO_CTX, .arg2_type = ARG_ANYTHING, .arg3_type = ARG_ANYTHING, .arg4_type = ARG_ANYTHING, }; BPF_CALL_4(bpf_msg_push_data, struct sk_msg *, msg, u32, start, u32, len, u64, flags) { struct scatterlist sge, nsge, nnsge, rsge = {0}, *psge; u32 new, i = 0, l, space, copy = 0, offset = 0; u8 *raw, *to, *from; struct page *page; if (unlikely(flags)) return -EINVAL; /* First find the starting scatterlist element */ i = msg->sg.start; do { l = sk_msg_elem(msg, i)->length; if (start < offset + l) break; offset += l; sk_msg_iter_var_next(i); } while (i != msg->sg.end); if (start >= offset + l) return -EINVAL; space = MAX_MSG_FRAGS - sk_msg_elem_used(msg); /* If no space available will fallback to copy, we need at * least one scatterlist elem available to push data into * when start aligns to the beginning of an element or two * when it falls inside an element. We handle the start equals * offset case because its the common case for inserting a * header. */ if (!space || (space == 1 && start != offset)) copy = msg->sg.data[i].length; page = alloc_pages(__GFP_NOWARN | GFP_ATOMIC | __GFP_COMP, get_order(copy + len)); if (unlikely(!page)) return -ENOMEM; if (copy) { int front, back; raw = page_address(page); psge = sk_msg_elem(msg, i); front = start - offset; back = psge->length - front; from = sg_virt(psge); if (front) memcpy(raw, from, front); if (back) { from += front; to = raw + front + len; memcpy(to, from, back); } put_page(sg_page(psge)); } else if (start - offset) { psge = sk_msg_elem(msg, i); rsge = sk_msg_elem_cpy(msg, i); psge->length = start - offset; rsge.length -= psge->length; rsge.offset += start; sk_msg_iter_var_next(i); sg_unmark_end(psge); sk_msg_iter_next(msg, end); } /* Slot(s) to place newly allocated data */ new = i; /* Shift one or two slots as needed */ if (!copy) { sge = sk_msg_elem_cpy(msg, i); sk_msg_iter_var_next(i); sg_unmark_end(&sge); sk_msg_iter_next(msg, end); nsge = sk_msg_elem_cpy(msg, i); if (rsge.length) { sk_msg_iter_var_next(i); nnsge = sk_msg_elem_cpy(msg, i); } while (i != msg->sg.end) { msg->sg.data[i] = sge; sge = nsge; sk_msg_iter_var_next(i); if (rsge.length) { nsge = nnsge; nnsge = sk_msg_elem_cpy(msg, i); } else { nsge = sk_msg_elem_cpy(msg, i); } } } /* Place newly allocated data buffer */ sk_mem_charge(msg->sk, len); msg->sg.size += len; msg->sg.copy[new] = false; sg_set_page(&msg->sg.data[new], page, len + copy, 0); if (rsge.length) { get_page(sg_page(&rsge)); sk_msg_iter_var_next(new); msg->sg.data[new] = rsge; } sk_msg_compute_data_pointers(msg); return 0; } static const struct bpf_func_proto bpf_msg_push_data_proto = { .func = bpf_msg_push_data, .gpl_only = false, .ret_type = RET_INTEGER, .arg1_type = ARG_PTR_TO_CTX, .arg2_type = ARG_ANYTHING, .arg3_type = ARG_ANYTHING, .arg4_type = ARG_ANYTHING, }; static void sk_msg_shift_left(struct sk_msg *msg, int i) { int prev; do { prev = i; sk_msg_iter_var_next(i); msg->sg.data[prev] = msg->sg.data[i]; } while (i != msg->sg.end); sk_msg_iter_prev(msg, end); } static void sk_msg_shift_right(struct sk_msg *msg, int i) { struct scatterlist tmp, sge; sk_msg_iter_next(msg, end); sge = sk_msg_elem_cpy(msg, i); sk_msg_iter_var_next(i); tmp = sk_msg_elem_cpy(msg, i); while (i != msg->sg.end) { msg->sg.data[i] = sge; sk_msg_iter_var_next(i); sge = tmp; tmp = sk_msg_elem_cpy(msg, i); } } BPF_CALL_4(bpf_msg_pop_data, struct sk_msg *, msg, u32, start, u32, len, u64, flags) { u32 i = 0, l, space, offset = 0; u64 last = start + len; int pop; if (unlikely(flags)) return -EINVAL; /* First find the starting scatterlist element */ i = msg->sg.start; do { l = sk_msg_elem(msg, i)->length; if (start < offset + l) break; offset += l; sk_msg_iter_var_next(i); } while (i != msg->sg.end); /* Bounds checks: start and pop must be inside message */ if (start >= offset + l || last >= msg->sg.size) return -EINVAL; space = MAX_MSG_FRAGS - sk_msg_elem_used(msg); pop = len; /* --------------| offset * -| start |-------- len -------| * * |----- a ----|-------- pop -------|----- b ----| * |______________________________________________| length * * * a: region at front of scatter element to save * b: region at back of scatter element to save when length > A + pop * pop: region to pop from element, same as input 'pop' here will be * decremented below per iteration. * * Two top-level cases to handle when start != offset, first B is non * zero and second B is zero corresponding to when a pop includes more * than one element. * * Then if B is non-zero AND there is no space allocate space and * compact A, B regions into page. If there is space shift ring to * the rigth free'ing the next element in ring to place B, leaving * A untouched except to reduce length. */ if (start != offset) { struct scatterlist *nsge, *sge = sk_msg_elem(msg, i); int a = start; int b = sge->length - pop - a; sk_msg_iter_var_next(i); if (pop < sge->length - a) { if (space) { sge->length = a; sk_msg_shift_right(msg, i); nsge = sk_msg_elem(msg, i); get_page(sg_page(sge)); sg_set_page(nsge, sg_page(sge), b, sge->offset + pop + a); } else { struct page *page, *orig; u8 *to, *from; page = alloc_pages(__GFP_NOWARN | __GFP_COMP | GFP_ATOMIC, get_order(a + b)); if (unlikely(!page)) return -ENOMEM; sge->length = a; orig = sg_page(sge); from = sg_virt(sge); to = page_address(page); memcpy(to, from, a); memcpy(to + a, from + a + pop, b); sg_set_page(sge, page, a + b, 0); put_page(orig); } pop = 0; } else if (pop >= sge->length - a) { sge->length = a; pop -= (sge->length - a); } } /* From above the current layout _must_ be as follows, * * -| offset * -| start * * |---- pop ---|---------------- b ------------| * |____________________________________________| length * * Offset and start of the current msg elem are equal because in the * previous case we handled offset != start and either consumed the * entire element and advanced to the next element OR pop == 0. * * Two cases to handle here are first pop is less than the length * leaving some remainder b above. Simply adjust the element's layout * in this case. Or pop >= length of the element so that b = 0. In this * case advance to next element decrementing pop. */ while (pop) { struct scatterlist *sge = sk_msg_elem(msg, i); if (pop < sge->length) { sge->length -= pop; sge->offset += pop; pop = 0; } else { pop -= sge->length; sk_msg_shift_left(msg, i); } sk_msg_iter_var_next(i); } sk_mem_uncharge(msg->sk, len - pop); msg->sg.size -= (len - pop); sk_msg_compute_data_pointers(msg); return 0; } static const struct bpf_func_proto bpf_msg_pop_data_proto = { .func = bpf_msg_pop_data, .gpl_only = false, .ret_type = RET_INTEGER, .arg1_type = ARG_PTR_TO_CTX, .arg2_type = ARG_ANYTHING, .arg3_type = ARG_ANYTHING, .arg4_type = ARG_ANYTHING, }; BPF_CALL_1(bpf_get_cgroup_classid, const struct sk_buff *, skb) { return task_get_classid(skb); } static const struct bpf_func_proto bpf_get_cgroup_classid_proto = { .func = bpf_get_cgroup_classid, .gpl_only = false, .ret_type = RET_INTEGER, .arg1_type = ARG_PTR_TO_CTX, }; BPF_CALL_1(bpf_get_route_realm, const struct sk_buff *, skb) { return dst_tclassid(skb); } static const struct bpf_func_proto bpf_get_route_realm_proto = { .func = bpf_get_route_realm, .gpl_only = false, .ret_type = RET_INTEGER, .arg1_type = ARG_PTR_TO_CTX, }; BPF_CALL_1(bpf_get_hash_recalc, struct sk_buff *, skb) { /* If skb_clear_hash() was called due to mangling, we can * trigger SW recalculation here. Later access to hash * can then use the inline skb->hash via context directly * instead of calling this helper again. */ return skb_get_hash(skb); } static const struct bpf_func_proto bpf_get_hash_recalc_proto = { .func = bpf_get_hash_recalc, .gpl_only = false, .ret_type = RET_INTEGER, .arg1_type = ARG_PTR_TO_CTX, }; BPF_CALL_1(bpf_set_hash_invalid, struct sk_buff *, skb) { /* After all direct packet write, this can be used once for * triggering a lazy recalc on next skb_get_hash() invocation. */ skb_clear_hash(skb); return 0; } static const struct bpf_func_proto bpf_set_hash_invalid_proto = { .func = bpf_set_hash_invalid, .gpl_only = false, .ret_type = RET_INTEGER, .arg1_type = ARG_PTR_TO_CTX, }; BPF_CALL_2(bpf_set_hash, struct sk_buff *, skb, u32, hash) { /* Set user specified hash as L4(+), so that it gets returned * on skb_get_hash() call unless BPF prog later on triggers a * skb_clear_hash(). */ __skb_set_sw_hash(skb, hash, true); return 0; } static const struct bpf_func_proto bpf_set_hash_proto = { .func = bpf_set_hash, .gpl_only = false, .ret_type = RET_INTEGER, .arg1_type = ARG_PTR_TO_CTX, .arg2_type = ARG_ANYTHING, }; BPF_CALL_3(bpf_skb_vlan_push, struct sk_buff *, skb, __be16, vlan_proto, u16, vlan_tci) { int ret; if (unlikely(vlan_proto != htons(ETH_P_8021Q) && vlan_proto != htons(ETH_P_8021AD))) vlan_proto = htons(ETH_P_8021Q); bpf_push_mac_rcsum(skb); ret = skb_vlan_push(skb, vlan_proto, vlan_tci); bpf_pull_mac_rcsum(skb); bpf_compute_data_pointers(skb); return ret; } static const struct bpf_func_proto bpf_skb_vlan_push_proto = { .func = bpf_skb_vlan_push, .gpl_only = false, .ret_type = RET_INTEGER, .arg1_type = ARG_PTR_TO_CTX, .arg2_type = ARG_ANYTHING, .arg3_type = ARG_ANYTHING, }; BPF_CALL_1(bpf_skb_vlan_pop, struct sk_buff *, skb) { int ret; bpf_push_mac_rcsum(skb); ret = skb_vlan_pop(skb); bpf_pull_mac_rcsum(skb); bpf_compute_data_pointers(skb); return ret; } static const struct bpf_func_proto bpf_skb_vlan_pop_proto = { .func = bpf_skb_vlan_pop, .gpl_only = false, .ret_type = RET_INTEGER, .arg1_type = ARG_PTR_TO_CTX, }; static int bpf_skb_generic_push(struct sk_buff *skb, u32 off, u32 len) { /* Caller already did skb_cow() with len as headroom, * so no need to do it here. */ skb_push(skb, len); memmove(skb->data, skb->data + len, off); memset(skb->data + off, 0, len); /* No skb_postpush_rcsum(skb, skb->data + off, len) * needed here as it does not change the skb->csum * result for checksum complete when summing over * zeroed blocks. */ return 0; } static int bpf_skb_generic_pop(struct sk_buff *skb, u32 off, u32 len) { /* skb_ensure_writable() is not needed here, as we're * already working on an uncloned skb. */ if (unlikely(!pskb_may_pull(skb, off + len))) return -ENOMEM; skb_postpull_rcsum(skb, skb->data + off, len); memmove(skb->data + len, skb->data, off); __skb_pull(skb, len); return 0; } static int bpf_skb_net_hdr_push(struct sk_buff *skb, u32 off, u32 len) { bool trans_same = skb->transport_header == skb->network_header; int ret; /* There's no need for __skb_push()/__skb_pull() pair to * get to the start of the mac header as we're guaranteed * to always start from here under eBPF. */ ret = bpf_skb_generic_push(skb, off, len); if (likely(!ret)) { skb->mac_header -= len; skb->network_header -= len; if (trans_same) skb->transport_header = skb->network_header; } return ret; } static int bpf_skb_net_hdr_pop(struct sk_buff *skb, u32 off, u32 len) { bool trans_same = skb->transport_header == skb->network_header; int ret; /* Same here, __skb_push()/__skb_pull() pair not needed. */ ret = bpf_skb_generic_pop(skb, off, len); if (likely(!ret)) { skb->mac_header += len; skb->network_header += len; if (trans_same) skb->transport_header = skb->network_header; } return ret; } static int bpf_skb_proto_4_to_6(struct sk_buff *skb) { const u32 len_diff = sizeof(struct ipv6hdr) - sizeof(struct iphdr); u32 off = skb_mac_header_len(skb); int ret; if (skb_is_gso(skb) && !skb_is_gso_tcp(skb)) return -ENOTSUPP; ret = skb_cow(skb, len_diff); if (unlikely(ret < 0)) return ret; ret = bpf_skb_net_hdr_push(skb, off, len_diff); if (unlikely(ret < 0)) return ret; if (skb_is_gso(skb)) { struct skb_shared_info *shinfo = skb_shinfo(skb); /* SKB_GSO_TCPV4 needs to be changed into * SKB_GSO_TCPV6. */ if (shinfo->gso_type & SKB_GSO_TCPV4) { shinfo->gso_type &= ~SKB_GSO_TCPV4; shinfo->gso_type |= SKB_GSO_TCPV6; } /* Due to IPv6 header, MSS needs to be downgraded. */ skb_decrease_gso_size(shinfo, len_diff); /* Header must be checked, and gso_segs recomputed. */ shinfo->gso_type |= SKB_GSO_DODGY; shinfo->gso_segs = 0; } skb->protocol = htons(ETH_P_IPV6); skb_clear_hash(skb); return 0; } static int bpf_skb_proto_6_to_4(struct sk_buff *skb) { const u32 len_diff = sizeof(struct ipv6hdr) - sizeof(struct iphdr); u32 off = skb_mac_header_len(skb); int ret; if (skb_is_gso(skb) && !skb_is_gso_tcp(skb)) return -ENOTSUPP; ret = skb_unclone(skb, GFP_ATOMIC); if (unlikely(ret < 0)) return ret; ret = bpf_skb_net_hdr_pop(skb, off, len_diff); if (unlikely(ret < 0)) return ret; if (skb_is_gso(skb)) { struct skb_shared_info *shinfo = skb_shinfo(skb); /* SKB_GSO_TCPV6 needs to be changed into * SKB_GSO_TCPV4. */ if (shinfo->gso_type & SKB_GSO_TCPV6) { shinfo->gso_type &= ~SKB_GSO_TCPV6; shinfo->gso_type |= SKB_GSO_TCPV4; } /* Due to IPv4 header, MSS can be upgraded. */ skb_increase_gso_size(shinfo, len_diff); /* Header must be checked, and gso_segs recomputed. */ shinfo->gso_type |= SKB_GSO_DODGY; shinfo->gso_segs = 0; } skb->protocol = htons(ETH_P_IP); skb_clear_hash(skb); return 0; } static int bpf_skb_proto_xlat(struct sk_buff *skb, __be16 to_proto) { __be16 from_proto = skb->protocol; if (from_proto == htons(ETH_P_IP) && to_proto == htons(ETH_P_IPV6)) return bpf_skb_proto_4_to_6(skb); if (from_proto == htons(ETH_P_IPV6) && to_proto == htons(ETH_P_IP)) return bpf_skb_proto_6_to_4(skb); return -ENOTSUPP; } BPF_CALL_3(bpf_skb_change_proto, struct sk_buff *, skb, __be16, proto, u64, flags) { int ret; if (unlikely(flags)) return -EINVAL; /* General idea is that this helper does the basic groundwork * needed for changing the protocol, and eBPF program fills the * rest through bpf_skb_store_bytes(), bpf_lX_csum_replace() * and other helpers, rather than passing a raw buffer here. * * The rationale is to keep this minimal and without a need to * deal with raw packet data. F.e. even if we would pass buffers * here, the program still needs to call the bpf_lX_csum_replace() * helpers anyway. Plus, this way we keep also separation of * concerns, since f.e. bpf_skb_store_bytes() should only take * care of stores. * * Currently, additional options and extension header space are * not supported, but flags register is reserved so we can adapt * that. For offloads, we mark packet as dodgy, so that headers * need to be verified first. */ ret = bpf_skb_proto_xlat(skb, proto); bpf_compute_data_pointers(skb); return ret; } static const struct bpf_func_proto bpf_skb_change_proto_proto = { .func = bpf_skb_change_proto, .gpl_only = false, .ret_type = RET_INTEGER, .arg1_type = ARG_PTR_TO_CTX, .arg2_type = ARG_ANYTHING, .arg3_type = ARG_ANYTHING, }; BPF_CALL_2(bpf_skb_change_type, struct sk_buff *, skb, u32, pkt_type) { /* We only allow a restricted subset to be changed for now. */ if (unlikely(!skb_pkt_type_ok(skb->pkt_type) || !skb_pkt_type_ok(pkt_type))) return -EINVAL; skb->pkt_type = pkt_type; return 0; } static const struct bpf_func_proto bpf_skb_change_type_proto = { .func = bpf_skb_change_type, .gpl_only = false, .ret_type = RET_INTEGER, .arg1_type = ARG_PTR_TO_CTX, .arg2_type = ARG_ANYTHING, }; static u32 bpf_skb_net_base_len(const struct sk_buff *skb) { switch (skb->protocol) { case htons(ETH_P_IP): return sizeof(struct iphdr); case htons(ETH_P_IPV6): return sizeof(struct ipv6hdr); default: return ~0U; } } #define BPF_F_ADJ_ROOM_ENCAP_L3_MASK (BPF_F_ADJ_ROOM_ENCAP_L3_IPV4 | \ BPF_F_ADJ_ROOM_ENCAP_L3_IPV6) #define BPF_F_ADJ_ROOM_MASK (BPF_F_ADJ_ROOM_FIXED_GSO | \ BPF_F_ADJ_ROOM_ENCAP_L3_MASK | \ BPF_F_ADJ_ROOM_ENCAP_L4_GRE | \ BPF_F_ADJ_ROOM_ENCAP_L4_UDP | \ BPF_F_ADJ_ROOM_ENCAP_L2( \ BPF_ADJ_ROOM_ENCAP_L2_MASK)) static int bpf_skb_net_grow(struct sk_buff *skb, u32 off, u32 len_diff, u64 flags) { u8 inner_mac_len = flags >> BPF_ADJ_ROOM_ENCAP_L2_SHIFT; bool encap = flags & BPF_F_ADJ_ROOM_ENCAP_L3_MASK; u16 mac_len = 0, inner_net = 0, inner_trans = 0; unsigned int gso_type = SKB_GSO_DODGY; int ret; if (skb_is_gso(skb) && !skb_is_gso_tcp(skb)) { /* udp gso_size delineates datagrams, only allow if fixed */ if (!(skb_shinfo(skb)->gso_type & SKB_GSO_UDP_L4) || !(flags & BPF_F_ADJ_ROOM_FIXED_GSO)) return -ENOTSUPP; } ret = skb_cow_head(skb, len_diff); if (unlikely(ret < 0)) return ret; if (encap) { if (skb->protocol != htons(ETH_P_IP) && skb->protocol != htons(ETH_P_IPV6)) return -ENOTSUPP; if (flags & BPF_F_ADJ_ROOM_ENCAP_L3_IPV4 && flags & BPF_F_ADJ_ROOM_ENCAP_L3_IPV6) return -EINVAL; if (flags & BPF_F_ADJ_ROOM_ENCAP_L4_GRE && flags & BPF_F_ADJ_ROOM_ENCAP_L4_UDP) return -EINVAL; if (skb->encapsulation) return -EALREADY; mac_len = skb->network_header - skb->mac_header; inner_net = skb->network_header; if (inner_mac_len > len_diff) return -EINVAL; inner_trans = skb->transport_header; } ret = bpf_skb_net_hdr_push(skb, off, len_diff); if (unlikely(ret < 0)) return ret; if (encap) { skb->inner_mac_header = inner_net - inner_mac_len; skb->inner_network_header = inner_net; skb->inner_transport_header = inner_trans; skb_set_inner_protocol(skb, skb->protocol); skb->encapsulation = 1; skb_set_network_header(skb, mac_len); if (flags & BPF_F_ADJ_ROOM_ENCAP_L4_UDP) gso_type |= SKB_GSO_UDP_TUNNEL; else if (flags & BPF_F_ADJ_ROOM_ENCAP_L4_GRE) gso_type |= SKB_GSO_GRE; else if (flags & BPF_F_ADJ_ROOM_ENCAP_L3_IPV6) gso_type |= SKB_GSO_IPXIP6; else if (flags & BPF_F_ADJ_ROOM_ENCAP_L3_IPV4) gso_type |= SKB_GSO_IPXIP4; if (flags & BPF_F_ADJ_ROOM_ENCAP_L4_GRE || flags & BPF_F_ADJ_ROOM_ENCAP_L4_UDP) { int nh_len = flags & BPF_F_ADJ_ROOM_ENCAP_L3_IPV6 ? sizeof(struct ipv6hdr) : sizeof(struct iphdr); skb_set_transport_header(skb, mac_len + nh_len); } /* Match skb->protocol to new outer l3 protocol */ if (skb->protocol == htons(ETH_P_IP) && flags & BPF_F_ADJ_ROOM_ENCAP_L3_IPV6) skb->protocol = htons(ETH_P_IPV6); else if (skb->protocol == htons(ETH_P_IPV6) && flags & BPF_F_ADJ_ROOM_ENCAP_L3_IPV4) skb->protocol = htons(ETH_P_IP); } if (skb_is_gso(skb)) { struct skb_shared_info *shinfo = skb_shinfo(skb); /* Due to header grow, MSS needs to be downgraded. */ if (!(flags & BPF_F_ADJ_ROOM_FIXED_GSO)) skb_decrease_gso_size(shinfo, len_diff); /* Header must be checked, and gso_segs recomputed. */ shinfo->gso_type |= gso_type; shinfo->gso_segs = 0; } return 0; } static int bpf_skb_net_shrink(struct sk_buff *skb, u32 off, u32 len_diff, u64 flags) { int ret; if (flags & ~BPF_F_ADJ_ROOM_FIXED_GSO) return -EINVAL; if (skb_is_gso(skb) && !skb_is_gso_tcp(skb)) { /* udp gso_size delineates datagrams, only allow if fixed */ if (!(skb_shinfo(skb)->gso_type & SKB_GSO_UDP_L4) || !(flags & BPF_F_ADJ_ROOM_FIXED_GSO)) return -ENOTSUPP; } ret = skb_unclone(skb, GFP_ATOMIC); if (unlikely(ret < 0)) return ret; ret = bpf_skb_net_hdr_pop(skb, off, len_diff); if (unlikely(ret < 0)) return ret; if (skb_is_gso(skb)) { struct skb_shared_info *shinfo = skb_shinfo(skb); /* Due to header shrink, MSS can be upgraded. */ if (!(flags & BPF_F_ADJ_ROOM_FIXED_GSO)) skb_increase_gso_size(shinfo, len_diff); /* Header must be checked, and gso_segs recomputed. */ shinfo->gso_type |= SKB_GSO_DODGY; shinfo->gso_segs = 0; } return 0; } static u32 __bpf_skb_max_len(const struct sk_buff *skb) { return skb->dev ? skb->dev->mtu + skb->dev->hard_header_len : SKB_MAX_ALLOC; } BPF_CALL_4(bpf_skb_adjust_room, struct sk_buff *, skb, s32, len_diff, u32, mode, u64, flags) { u32 len_cur, len_diff_abs = abs(len_diff); u32 len_min = bpf_skb_net_base_len(skb); u32 len_max = __bpf_skb_max_len(skb); __be16 proto = skb->protocol; bool shrink = len_diff < 0; u32 off; int ret; if (unlikely(flags & ~BPF_F_ADJ_ROOM_MASK)) return -EINVAL; if (unlikely(len_diff_abs > 0xfffU)) return -EFAULT; if (unlikely(proto != htons(ETH_P_IP) && proto != htons(ETH_P_IPV6))) return -ENOTSUPP; off = skb_mac_header_len(skb); switch (mode) { case BPF_ADJ_ROOM_NET: off += bpf_skb_net_base_len(skb); break; case BPF_ADJ_ROOM_MAC: break; default: return -ENOTSUPP; } len_cur = skb->len - skb_network_offset(skb); if ((shrink && (len_diff_abs >= len_cur || len_cur - len_diff_abs < len_min)) || (!shrink && (skb->len + len_diff_abs > len_max && !skb_is_gso(skb)))) return -ENOTSUPP; ret = shrink ? bpf_skb_net_shrink(skb, off, len_diff_abs, flags) : bpf_skb_net_grow(skb, off, len_diff_abs, flags); bpf_compute_data_pointers(skb); return ret; } static const struct bpf_func_proto bpf_skb_adjust_room_proto = { .func = bpf_skb_adjust_room, .gpl_only = false, .ret_type = RET_INTEGER, .arg1_type = ARG_PTR_TO_CTX, .arg2_type = ARG_ANYTHING, .arg3_type = ARG_ANYTHING, .arg4_type = ARG_ANYTHING, }; static u32 __bpf_skb_min_len(const struct sk_buff *skb) { u32 min_len = skb_network_offset(skb); if (skb_transport_header_was_set(skb)) min_len = skb_transport_offset(skb); if (skb->ip_summed == CHECKSUM_PARTIAL) min_len = skb_checksum_start_offset(skb) + skb->csum_offset + sizeof(__sum16); return min_len; } static int bpf_skb_grow_rcsum(struct sk_buff *skb, unsigned int new_len) { unsigned int old_len = skb->len; int ret; ret = __skb_grow_rcsum(skb, new_len); if (!ret) memset(skb->data + old_len, 0, new_len - old_len); return ret; } static int bpf_skb_trim_rcsum(struct sk_buff *skb, unsigned int new_len) { return __skb_trim_rcsum(skb, new_len); } static inline int __bpf_skb_change_tail(struct sk_buff *skb, u32 new_len, u64 flags) { u32 max_len = __bpf_skb_max_len(skb); u32 min_len = __bpf_skb_min_len(skb); int ret; if (unlikely(flags || new_len > max_len || new_len < min_len)) return -EINVAL; if (skb->encapsulation) return -ENOTSUPP; /* The basic idea of this helper is that it's performing the * needed work to either grow or trim an skb, and eBPF program * rewrites the rest via helpers like bpf_skb_store_bytes(), * bpf_lX_csum_replace() and others rather than passing a raw * buffer here. This one is a slow path helper and intended * for replies with control messages. * * Like in bpf_skb_change_proto(), we want to keep this rather * minimal and without protocol specifics so that we are able * to separate concerns as in bpf_skb_store_bytes() should only * be the one responsible for writing buffers. * * It's really expected to be a slow path operation here for * control message replies, so we're implicitly linearizing, * uncloning and drop offloads from the skb by this. */ ret = __bpf_try_make_writable(skb, skb->len); if (!ret) { if (new_len > skb->len) ret = bpf_skb_grow_rcsum(skb, new_len); else if (new_len < skb->len) ret = bpf_skb_trim_rcsum(skb, new_len); if (!ret && skb_is_gso(skb)) skb_gso_reset(skb); } return ret; } BPF_CALL_3(bpf_skb_change_tail, struct sk_buff *, skb, u32, new_len, u64, flags) { int ret = __bpf_skb_change_tail(skb, new_len, flags); bpf_compute_data_pointers(skb); return ret; } static const struct bpf_func_proto bpf_skb_change_tail_proto = { .func = bpf_skb_change_tail, .gpl_only = false, .ret_type = RET_INTEGER, .arg1_type = ARG_PTR_TO_CTX, .arg2_type = ARG_ANYTHING, .arg3_type = ARG_ANYTHING, }; BPF_CALL_3(sk_skb_change_tail, struct sk_buff *, skb, u32, new_len, u64, flags) { int ret = __bpf_skb_change_tail(skb, new_len, flags); bpf_compute_data_end_sk_skb(skb); return ret; } static const struct bpf_func_proto sk_skb_change_tail_proto = { .func = sk_skb_change_tail, .gpl_only = false, .ret_type = RET_INTEGER, .arg1_type = ARG_PTR_TO_CTX, .arg2_type = ARG_ANYTHING, .arg3_type = ARG_ANYTHING, }; static inline int __bpf_skb_change_head(struct sk_buff *skb, u32 head_room, u64 flags) { u32 max_len = __bpf_skb_max_len(skb); u32 new_len = skb->len + head_room; int ret; if (unlikely(flags || (!skb_is_gso(skb) && new_len > max_len) || new_len < skb->len)) return -EINVAL; ret = skb_cow(skb, head_room); if (likely(!ret)) { /* Idea for this helper is that we currently only * allow to expand on mac header. This means that * skb->protocol network header, etc, stay as is. * Compared to bpf_skb_change_tail(), we're more * flexible due to not needing to linearize or * reset GSO. Intention for this helper is to be * used by an L3 skb that needs to push mac header * for redirection into L2 device. */ __skb_push(skb, head_room); memset(skb->data, 0, head_room); skb_reset_mac_header(skb); } return ret; } BPF_CALL_3(bpf_skb_change_head, struct sk_buff *, skb, u32, head_room, u64, flags) { int ret = __bpf_skb_change_head(skb, head_room, flags); bpf_compute_data_pointers(skb); return ret; } static const struct bpf_func_proto bpf_skb_change_head_proto = { .func = bpf_skb_change_head, .gpl_only = false, .ret_type = RET_INTEGER, .arg1_type = ARG_PTR_TO_CTX, .arg2_type = ARG_ANYTHING, .arg3_type = ARG_ANYTHING, }; BPF_CALL_3(sk_skb_change_head, struct sk_buff *, skb, u32, head_room, u64, flags) { int ret = __bpf_skb_change_head(skb, head_room, flags); bpf_compute_data_end_sk_skb(skb); return ret; } static const struct bpf_func_proto sk_skb_change_head_proto = { .func = sk_skb_change_head, .gpl_only = false, .ret_type = RET_INTEGER, .arg1_type = ARG_PTR_TO_CTX, .arg2_type = ARG_ANYTHING, .arg3_type = ARG_ANYTHING, }; static unsigned long xdp_get_metalen(const struct xdp_buff *xdp) { return xdp_data_meta_unsupported(xdp) ? 0 : xdp->data - xdp->data_meta; } BPF_CALL_2(bpf_xdp_adjust_head, struct xdp_buff *, xdp, int, offset) { void *xdp_frame_end = xdp->data_hard_start + sizeof(struct xdp_frame); unsigned long metalen = xdp_get_metalen(xdp); void *data_start = xdp_frame_end + metalen; void *data = xdp->data + offset; if (unlikely(data < data_start || data > xdp->data_end - ETH_HLEN)) return -EINVAL; if (metalen) memmove(xdp->data_meta + offset, xdp->data_meta, metalen); xdp->data_meta += offset; xdp->data = data; return 0; } static const struct bpf_func_proto bpf_xdp_adjust_head_proto = { .func = bpf_xdp_adjust_head, .gpl_only = false, .ret_type = RET_INTEGER, .arg1_type = ARG_PTR_TO_CTX, .arg2_type = ARG_ANYTHING, }; BPF_CALL_2(bpf_xdp_adjust_tail, struct xdp_buff *, xdp, int, offset) { void *data_end = xdp->data_end + offset; /* only shrinking is allowed for now. */ if (unlikely(offset >= 0)) return -EINVAL; if (unlikely(data_end < xdp->data + ETH_HLEN)) return -EINVAL; xdp->data_end = data_end; return 0; } static const struct bpf_func_proto bpf_xdp_adjust_tail_proto = { .func = bpf_xdp_adjust_tail, .gpl_only = false, .ret_type = RET_INTEGER, .arg1_type = ARG_PTR_TO_CTX, .arg2_type = ARG_ANYTHING, }; BPF_CALL_2(bpf_xdp_adjust_meta, struct xdp_buff *, xdp, int, offset) { void *xdp_frame_end = xdp->data_hard_start + sizeof(struct xdp_frame); void *meta = xdp->data_meta + offset; unsigned long metalen = xdp->data - meta; if (xdp_data_meta_unsupported(xdp)) return -ENOTSUPP; if (unlikely(meta < xdp_frame_end || meta > xdp->data)) return -EINVAL; if (unlikely((metalen & (sizeof(__u32) - 1)) || (metalen > 32))) return -EACCES; xdp->data_meta = meta; return 0; } static const struct bpf_func_proto bpf_xdp_adjust_meta_proto = { .func = bpf_xdp_adjust_meta, .gpl_only = false, .ret_type = RET_INTEGER, .arg1_type = ARG_PTR_TO_CTX, .arg2_type = ARG_ANYTHING, }; static int __bpf_tx_xdp(struct net_device *dev, struct bpf_map *map, struct xdp_buff *xdp, u32 index) { struct xdp_frame *xdpf; int err, sent; if (!dev->netdev_ops->ndo_xdp_xmit) { return -EOPNOTSUPP; } err = xdp_ok_fwd_dev(dev, xdp->data_end - xdp->data); if (unlikely(err)) return err; xdpf = convert_to_xdp_frame(xdp); if (unlikely(!xdpf)) return -EOVERFLOW; sent = dev->netdev_ops->ndo_xdp_xmit(dev, 1, &xdpf, XDP_XMIT_FLUSH); if (sent <= 0) return sent; return 0; } static noinline int xdp_do_redirect_slow(struct net_device *dev, struct xdp_buff *xdp, struct bpf_prog *xdp_prog, struct bpf_redirect_info *ri) { struct net_device *fwd; u32 index = ri->ifindex; int err; fwd = dev_get_by_index_rcu(dev_net(dev), index); ri->ifindex = 0; if (unlikely(!fwd)) { err = -EINVAL; goto err; } err = __bpf_tx_xdp(fwd, NULL, xdp, 0); if (unlikely(err)) goto err; _trace_xdp_redirect(dev, xdp_prog, index); return 0; err: _trace_xdp_redirect_err(dev, xdp_prog, index, err); return err; } static int __bpf_tx_xdp_map(struct net_device *dev_rx, void *fwd, struct bpf_map *map, struct xdp_buff *xdp, u32 index) { int err; switch (map->map_type) { case BPF_MAP_TYPE_DEVMAP: { struct bpf_dtab_netdev *dst = fwd; err = dev_map_enqueue(dst, xdp, dev_rx); if (unlikely(err)) return err; __dev_map_insert_ctx(map, index); break; } case BPF_MAP_TYPE_CPUMAP: { struct bpf_cpu_map_entry *rcpu = fwd; err = cpu_map_enqueue(rcpu, xdp, dev_rx); if (unlikely(err)) return err; __cpu_map_insert_ctx(map, index); break; } case BPF_MAP_TYPE_XSKMAP: { struct xdp_sock *xs = fwd; err = __xsk_map_redirect(map, xdp, xs); return err; } default: break; } return 0; } void xdp_do_flush_map(void) { struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info); struct bpf_map *map = ri->map_to_flush; ri->map_to_flush = NULL; if (map) { switch (map->map_type) { case BPF_MAP_TYPE_DEVMAP: __dev_map_flush(map); break; case BPF_MAP_TYPE_CPUMAP: __cpu_map_flush(map); break; case BPF_MAP_TYPE_XSKMAP: __xsk_map_flush(map); break; default: break; } } } EXPORT_SYMBOL_GPL(xdp_do_flush_map); static inline void *__xdp_map_lookup_elem(struct bpf_map *map, u32 index) { switch (map->map_type) { case BPF_MAP_TYPE_DEVMAP: return __dev_map_lookup_elem(map, index); case BPF_MAP_TYPE_CPUMAP: return __cpu_map_lookup_elem(map, index); case BPF_MAP_TYPE_XSKMAP: return __xsk_map_lookup_elem(map, index); default: return NULL; } } void bpf_clear_redirect_map(struct bpf_map *map) { struct bpf_redirect_info *ri; int cpu; for_each_possible_cpu(cpu) { ri = per_cpu_ptr(&bpf_redirect_info, cpu); /* Avoid polluting remote cacheline due to writes if * not needed. Once we pass this test, we need the * cmpxchg() to make sure it hasn't been changed in * the meantime by remote CPU. */ if (unlikely(READ_ONCE(ri->map) == map)) cmpxchg(&ri->map, map, NULL); } } static int xdp_do_redirect_map(struct net_device *dev, struct xdp_buff *xdp, struct bpf_prog *xdp_prog, struct bpf_map *map, struct bpf_redirect_info *ri) { u32 index = ri->ifindex; void *fwd = NULL; int err; ri->ifindex = 0; WRITE_ONCE(ri->map, NULL); fwd = __xdp_map_lookup_elem(map, index); if (unlikely(!fwd)) { err = -EINVAL; goto err; } if (ri->map_to_flush && unlikely(ri->map_to_flush != map)) xdp_do_flush_map(); err = __bpf_tx_xdp_map(dev, fwd, map, xdp, index); if (unlikely(err)) goto err; ri->map_to_flush = map; _trace_xdp_redirect_map(dev, xdp_prog, fwd, map, index); return 0; err: _trace_xdp_redirect_map_err(dev, xdp_prog, fwd, map, index, err); return err; } int xdp_do_redirect(struct net_device *dev, struct xdp_buff *xdp, struct bpf_prog *xdp_prog) { struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info); struct bpf_map *map = READ_ONCE(ri->map); if (likely(map)) return xdp_do_redirect_map(dev, xdp, xdp_prog, map, ri); return xdp_do_redirect_slow(dev, xdp, xdp_prog, ri); } EXPORT_SYMBOL_GPL(xdp_do_redirect); static int xdp_do_generic_redirect_map(struct net_device *dev, struct sk_buff *skb, struct xdp_buff *xdp, struct bpf_prog *xdp_prog, struct bpf_map *map) { struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info); u32 index = ri->ifindex; void *fwd = NULL; int err = 0; ri->ifindex = 0; WRITE_ONCE(ri->map, NULL); fwd = __xdp_map_lookup_elem(map, index); if (unlikely(!fwd)) { err = -EINVAL; goto err; } if (map->map_type == BPF_MAP_TYPE_DEVMAP) { struct bpf_dtab_netdev *dst = fwd; err = dev_map_generic_redirect(dst, skb, xdp_prog); if (unlikely(err)) goto err; } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) { struct xdp_sock *xs = fwd; err = xsk_generic_rcv(xs, xdp); if (err) goto err; consume_skb(skb); } else { /* TODO: Handle BPF_MAP_TYPE_CPUMAP */ err = -EBADRQC; goto err; } _trace_xdp_redirect_map(dev, xdp_prog, fwd, map, index); return 0; err: _trace_xdp_redirect_map_err(dev, xdp_prog, fwd, map, index, err); return err; } int xdp_do_generic_redirect(struct net_device *dev, struct sk_buff *skb, struct xdp_buff *xdp, struct bpf_prog *xdp_prog) { struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info); struct bpf_map *map = READ_ONCE(ri->map); u32 index = ri->ifindex; struct net_device *fwd; int err = 0; if (map) return xdp_do_generic_redirect_map(dev, skb, xdp, xdp_prog, map); ri->ifindex = 0; fwd = dev_get_by_index_rcu(dev_net(dev), index); if (unlikely(!fwd)) { err = -EINVAL; goto err; } err = xdp_ok_fwd_dev(fwd, skb->len); if (unlikely(err)) goto err; skb->dev = fwd; _trace_xdp_redirect(dev, xdp_prog, index); generic_xdp_tx(skb, xdp_prog); return 0; err: _trace_xdp_redirect_err(dev, xdp_prog, index, err); return err; } EXPORT_SYMBOL_GPL(xdp_do_generic_redirect); BPF_CALL_2(bpf_xdp_redirect, u32, ifindex, u64, flags) { struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info); if (unlikely(flags)) return XDP_ABORTED; ri->ifindex = ifindex; ri->flags = flags; WRITE_ONCE(ri->map, NULL); return XDP_REDIRECT; } static const struct bpf_func_proto bpf_xdp_redirect_proto = { .func = bpf_xdp_redirect, .gpl_only = false, .ret_type = RET_INTEGER, .arg1_type = ARG_ANYTHING, .arg2_type = ARG_ANYTHING, }; BPF_CALL_3(bpf_xdp_redirect_map, struct bpf_map *, map, u32, ifindex, u64, flags) { struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info); if (unlikely(flags)) return XDP_ABORTED; ri->ifindex = ifindex; ri->flags = flags; WRITE_ONCE(ri->map, map); return XDP_REDIRECT; } static const struct bpf_func_proto bpf_xdp_redirect_map_proto = { .func = bpf_xdp_redirect_map, .gpl_only = false, .ret_type = RET_INTEGER, .arg1_type = ARG_CONST_MAP_PTR, .arg2_type = ARG_ANYTHING, .arg3_type = ARG_ANYTHING, }; static unsigned long bpf_skb_copy(void *dst_buff, const void *skb, unsigned long off, unsigned long len) { void *ptr = skb_header_pointer(skb, off, len, dst_buff); if (unlikely(!ptr)) return len; if (ptr != dst_buff) memcpy(dst_buff, ptr, len); return 0; } BPF_CALL_5(bpf_skb_event_output, struct sk_buff *, skb, struct bpf_map *, map, u64, flags, void *, meta, u64, meta_size) { u64 skb_size = (flags & BPF_F_CTXLEN_MASK) >> 32; if (unlikely(flags & ~(BPF_F_CTXLEN_MASK | BPF_F_INDEX_MASK))) return -EINVAL; if (unlikely(skb_size > skb->len)) return -EFAULT; return bpf_event_output(map, flags, meta, meta_size, skb, skb_size, bpf_skb_copy); } static const struct bpf_func_proto bpf_skb_event_output_proto = { .func = bpf_skb_event_output, .gpl_only = true, .ret_type = RET_INTEGER, .arg1_type = ARG_PTR_TO_CTX, .arg2_type = ARG_CONST_MAP_PTR, .arg3_type = ARG_ANYTHING, .arg4_type = ARG_PTR_TO_MEM, .arg5_type = ARG_CONST_SIZE_OR_ZERO, }; static unsigned short bpf_tunnel_key_af(u64 flags) { return flags & BPF_F_TUNINFO_IPV6 ? AF_INET6 : AF_INET; } BPF_CALL_4(bpf_skb_get_tunnel_key, struct sk_buff *, skb, struct bpf_tunnel_key *, to, u32, size, u64, flags) { const struct ip_tunnel_info *info = skb_tunnel_info(skb); u8 compat[sizeof(struct bpf_tunnel_key)]; void *to_orig = to; int err; if (unlikely(!info || (flags & ~(BPF_F_TUNINFO_IPV6)))) { err = -EINVAL; goto err_clear; } if (ip_tunnel_info_af(info) != bpf_tunnel_key_af(flags)) { err = -EPROTO; goto err_clear; } if (unlikely(size != sizeof(struct bpf_tunnel_key))) { err = -EINVAL; switch (size) { case offsetof(struct bpf_tunnel_key, tunnel_label): case offsetof(struct bpf_tunnel_key, tunnel_ext): goto set_compat; case offsetof(struct bpf_tunnel_key, remote_ipv6[1]): /* Fixup deprecated structure layouts here, so we have * a common path later on. */ if (ip_tunnel_info_af(info) != AF_INET) goto err_clear; set_compat: to = (struct bpf_tunnel_key *)compat; break; default: goto err_clear; } } to->tunnel_id = be64_to_cpu(info->key.tun_id); to->tunnel_tos = info->key.tos; to->tunnel_ttl = info->key.ttl; to->tunnel_ext = 0; if (flags & BPF_F_TUNINFO_IPV6) { memcpy(to->remote_ipv6, &info->key.u.ipv6.src, sizeof(to->remote_ipv6)); to->tunnel_label = be32_to_cpu(info->key.label); } else { to->remote_ipv4 = be32_to_cpu(info->key.u.ipv4.src); memset(&to->remote_ipv6[1], 0, sizeof(__u32) * 3); to->tunnel_label = 0; } if (unlikely(size != sizeof(struct bpf_tunnel_key))) memcpy(to_orig, to, size); return 0; err_clear: memset(to_orig, 0, size); return err; } static const struct bpf_func_proto bpf_skb_get_tunnel_key_proto = { .func = bpf_skb_get_tunnel_key, .gpl_only = false, .ret_type = RET_INTEGER, .arg1_type = ARG_PTR_TO_CTX, .arg2_type = ARG_PTR_TO_UNINIT_MEM, .arg3_type = ARG_CONST_SIZE, .arg4_type = ARG_ANYTHING, }; BPF_CALL_3(bpf_skb_get_tunnel_opt, struct sk_buff *, skb, u8 *, to, u32, size) { const struct ip_tunnel_info *info = skb_tunnel_info(skb); int err; if (unlikely(!info || !(info->key.tun_flags & TUNNEL_OPTIONS_PRESENT))) { err = -ENOENT; goto err_clear; } if (unlikely(size < info->options_len)) { err = -ENOMEM; goto err_clear; } ip_tunnel_info_opts_get(to, info); if (size > info->options_len) memset(to + info->options_len, 0, size - info->options_len); return info->options_len; err_clear: memset(to, 0, size); return err; } static const struct bpf_func_proto bpf_skb_get_tunnel_opt_proto = { .func = bpf_skb_get_tunnel_opt, .gpl_only = false, .ret_type = RET_INTEGER, .arg1_type = ARG_PTR_TO_CTX, .arg2_type = ARG_PTR_TO_UNINIT_MEM, .arg3_type = ARG_CONST_SIZE, }; static struct metadata_dst __percpu *md_dst; BPF_CALL_4(bpf_skb_set_tunnel_key, struct sk_buff *, skb, const struct bpf_tunnel_key *, from, u32, size, u64, flags) { struct metadata_dst *md = this_cpu_ptr(md_dst); u8 compat[sizeof(struct bpf_tunnel_key)]; struct ip_tunnel_info *info; if (unlikely(flags & ~(BPF_F_TUNINFO_IPV6 | BPF_F_ZERO_CSUM_TX | BPF_F_DONT_FRAGMENT | BPF_F_SEQ_NUMBER))) return -EINVAL; if (unlikely(size != sizeof(struct bpf_tunnel_key))) { switch (size) { case offsetof(struct bpf_tunnel_key, tunnel_label): case offsetof(struct bpf_tunnel_key, tunnel_ext): case offsetof(struct bpf_tunnel_key, remote_ipv6[1]): /* Fixup deprecated structure layouts here, so we have * a common path later on. */ memcpy(compat, from, size); memset(compat + size, 0, sizeof(compat) - size); from = (const struct bpf_tunnel_key *) compat; break; default: return -EINVAL; } } if (unlikely((!(flags & BPF_F_TUNINFO_IPV6) && from->tunnel_label) || from->tunnel_ext)) return -EINVAL; skb_dst_drop(skb); dst_hold((struct dst_entry *) md); skb_dst_set(skb, (struct dst_entry *) md); info = &md->u.tun_info; memset(info, 0, sizeof(*info)); info->mode = IP_TUNNEL_INFO_TX; info->key.tun_flags = TUNNEL_KEY | TUNNEL_CSUM | TUNNEL_NOCACHE; if (flags & BPF_F_DONT_FRAGMENT) info->key.tun_flags |= TUNNEL_DONT_FRAGMENT; if (flags & BPF_F_ZERO_CSUM_TX) info->key.tun_flags &= ~TUNNEL_CSUM; if (flags & BPF_F_SEQ_NUMBER) info->key.tun_flags |= TUNNEL_SEQ; info->key.tun_id = cpu_to_be64(from->tunnel_id); info->key.tos = from->tunnel_tos; info->key.ttl = from->tunnel_ttl; if (flags & BPF_F_TUNINFO_IPV6) { info->mode |= IP_TUNNEL_INFO_IPV6; memcpy(&info->key.u.ipv6.dst, from->remote_ipv6, sizeof(from->remote_ipv6)); info->key.label = cpu_to_be32(from->tunnel_label) & IPV6_FLOWLABEL_MASK; } else { info->key.u.ipv4.dst = cpu_to_be32(from->remote_ipv4); } return 0; } static const struct bpf_func_proto bpf_skb_set_tunnel_key_proto = { .func = bpf_skb_set_tunnel_key, .gpl_only = false, .ret_type = RET_INTEGER, .arg1_type = ARG_PTR_TO_CTX, .arg2_type = ARG_PTR_TO_MEM, .arg3_type = ARG_CONST_SIZE, .arg4_type = ARG_ANYTHING, }; BPF_CALL_3(bpf_skb_set_tunnel_opt, struct sk_buff *, skb, const u8 *, from, u32, size) { struct ip_tunnel_info *info = skb_tunnel_info(skb); const struct metadata_dst *md = this_cpu_ptr(md_dst); if (unlikely(info != &md->u.tun_info || (size & (sizeof(u32) - 1)))) return -EINVAL; if (unlikely(size > IP_TUNNEL_OPTS_MAX)) return -ENOMEM; ip_tunnel_info_opts_set(info, from, size, TUNNEL_OPTIONS_PRESENT); return 0; } static const struct bpf_func_proto bpf_skb_set_tunnel_opt_proto = { .func = bpf_skb_set_tunnel_opt, .gpl_only = false, .ret_type = RET_INTEGER, .arg1_type = ARG_PTR_TO_CTX, .arg2_type = ARG_PTR_TO_MEM, .arg3_type = ARG_CONST_SIZE, }; static const struct bpf_func_proto * bpf_get_skb_set_tunnel_proto(enum bpf_func_id which) { if (!md_dst) { struct metadata_dst __percpu *tmp; tmp = metadata_dst_alloc_percpu(IP_TUNNEL_OPTS_MAX, METADATA_IP_TUNNEL, GFP_KERNEL); if (!tmp) return NULL; if (cmpxchg(&md_dst, NULL, tmp)) metadata_dst_free_percpu(tmp); } switch (which) { case BPF_FUNC_skb_set_tunnel_key: return &bpf_skb_set_tunnel_key_proto; case BPF_FUNC_skb_set_tunnel_opt: return &bpf_skb_set_tunnel_opt_proto; default: return NULL; } } BPF_CALL_3(bpf_skb_under_cgroup, struct sk_buff *, skb, struct bpf_map *, map, u32, idx) { struct bpf_array *array = container_of(map, struct bpf_array, map); struct cgroup *cgrp; struct sock *sk; sk = skb_to_full_sk(skb); if (!sk || !sk_fullsock(sk)) return -ENOENT; if (unlikely(idx >= array->map.max_entries)) return -E2BIG; cgrp = READ_ONCE(array->ptrs[idx]); if (unlikely(!cgrp)) return -EAGAIN; return sk_under_cgroup_hierarchy(sk, cgrp); } static const struct bpf_func_proto bpf_skb_under_cgroup_proto = { .func = bpf_skb_under_cgroup, .gpl_only = false, .ret_type = RET_INTEGER, .arg1_type = ARG_PTR_TO_CTX, .arg2_type = ARG_CONST_MAP_PTR, .arg3_type = ARG_ANYTHING, }; #ifdef CONFIG_SOCK_CGROUP_DATA BPF_CALL_1(bpf_skb_cgroup_id, const struct sk_buff *, skb) { struct sock *sk = skb_to_full_sk(skb); struct cgroup *cgrp; if (!sk || !sk_fullsock(sk)) return 0; cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data); return cgrp->kn->id.id; } static const struct bpf_func_proto bpf_skb_cgroup_id_proto = { .func = bpf_skb_cgroup_id, .gpl_only = false, .ret_type = RET_INTEGER, .arg1_type = ARG_PTR_TO_CTX, }; BPF_CALL_2(bpf_skb_ancestor_cgroup_id, const struct sk_buff *, skb, int, ancestor_level) { struct sock *sk = skb_to_full_sk(skb); struct cgroup *ancestor; struct cgroup *cgrp; if (!sk || !sk_fullsock(sk)) return 0; cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data); ancestor = cgroup_ancestor(cgrp, ancestor_level); if (!ancestor) return 0; return ancestor->kn->id.id; } static const struct bpf_func_proto bpf_skb_ancestor_cgroup_id_proto = { .func = bpf_skb_ancestor_cgroup_id, .gpl_only = false, .ret_type = RET_INTEGER, .arg1_type = ARG_PTR_TO_CTX, .arg2_type = ARG_ANYTHING, }; #endif static unsigned long bpf_xdp_copy(void *dst_buff, const void *src_buff, unsigned long off, unsigned long len) { memcpy(dst_buff, src_buff + off, len); return 0; } BPF_CALL_5(bpf_xdp_event_output, struct xdp_buff *, xdp, struct bpf_map *, map, u64, flags, void *, meta, u64, meta_size) { u64 xdp_size = (flags & BPF_F_CTXLEN_MASK) >> 32; if (unlikely(flags & ~(BPF_F_CTXLEN_MASK | BPF_F_INDEX_MASK))) return -EINVAL; if (unlikely(xdp_size > (unsigned long)(xdp->data_end - xdp->data))) return -EFAULT; return bpf_event_output(map, flags, meta, meta_size, xdp->data, xdp_size, bpf_xdp_copy); } static const struct bpf_func_proto bpf_xdp_event_output_proto = { .func = bpf_xdp_event_output, .gpl_only = true, .ret_type = RET_INTEGER, .arg1_type = ARG_PTR_TO_CTX, .arg2_type = ARG_CONST_MAP_PTR, .arg3_type = ARG_ANYTHING, .arg4_type = ARG_PTR_TO_MEM, .arg5_type = ARG_CONST_SIZE_OR_ZERO, }; BPF_CALL_1(bpf_get_socket_cookie, struct sk_buff *, skb) { return skb->sk ? sock_gen_cookie(skb->sk) : 0; } static const struct bpf_func_proto bpf_get_socket_cookie_proto = { .func = bpf_get_socket_cookie, .gpl_only = false, .ret_type = RET_INTEGER, .arg1_type = ARG_PTR_TO_CTX, }; BPF_CALL_1(bpf_get_socket_cookie_sock_addr, struct bpf_sock_addr_kern *, ctx) { return sock_gen_cookie(ctx->sk); } static const struct bpf_func_proto bpf_get_socket_cookie_sock_addr_proto = { .func = bpf_get_socket_cookie_sock_addr, .gpl_only = false, .ret_type = RET_INTEGER, .arg1_type = ARG_PTR_TO_CTX, }; BPF_CALL_1(bpf_get_socket_cookie_sock_ops, struct bpf_sock_ops_kern *, ctx) { return sock_gen_cookie(ctx->sk); } static const struct bpf_func_proto bpf_get_socket_cookie_sock_ops_proto = { .func = bpf_get_socket_cookie_sock_ops, .gpl_only = false, .ret_type = RET_INTEGER, .arg1_type = ARG_PTR_TO_CTX, }; BPF_CALL_1(bpf_get_socket_uid, struct sk_buff *, skb) { struct sock *sk = sk_to_full_sk(skb->sk); kuid_t kuid; if (!sk || !sk_fullsock(sk)) return overflowuid; kuid = sock_net_uid(sock_net(sk), sk); return from_kuid_munged(sock_net(sk)->user_ns, kuid); } static const struct bpf_func_proto bpf_get_socket_uid_proto = { .func = bpf_get_socket_uid, .gpl_only = false, .ret_type = RET_INTEGER, .arg1_type = ARG_PTR_TO_CTX, }; BPF_CALL_5(bpf_sockopt_event_output, struct bpf_sock_ops_kern *, bpf_sock, struct bpf_map *, map, u64, flags, void *, data, u64, size) { if (unlikely(flags & ~(BPF_F_INDEX_MASK))) return -EINVAL; return bpf_event_output(map, flags, data, size, NULL, 0, NULL); } static const struct bpf_func_proto bpf_sockopt_event_output_proto = { .func = bpf_sockopt_event_output, .gpl_only = true, .ret_type = RET_INTEGER, .arg1_type = ARG_PTR_TO_CTX, .arg2_type = ARG_CONST_MAP_PTR, .arg3_type = ARG_ANYTHING, .arg4_type = ARG_PTR_TO_MEM, .arg5_type = ARG_CONST_SIZE_OR_ZERO, }; BPF_CALL_5(bpf_setsockopt, struct bpf_sock_ops_kern *, bpf_sock, int, level, int, optname, char *, optval, int, optlen) { struct sock *sk = bpf_sock->sk; int ret = 0; int val; if (!sk_fullsock(sk)) return -EINVAL; if (level == SOL_SOCKET) { if (optlen != sizeof(int)) return -EINVAL; val = *((int *)optval); /* Only some socketops are supported */ switch (optname) { case SO_RCVBUF: val = min_t(u32, val, sysctl_rmem_max); sk->sk_userlocks |= SOCK_RCVBUF_LOCK; sk->sk_rcvbuf = max_t(int, val * 2, SOCK_MIN_RCVBUF); break; case SO_SNDBUF: val = min_t(u32, val, sysctl_wmem_max); sk->sk_userlocks |= SOCK_SNDBUF_LOCK; sk->sk_sndbuf = max_t(int, val * 2, SOCK_MIN_SNDBUF); break; case SO_MAX_PACING_RATE: /* 32bit version */ if (val != ~0U) cmpxchg(&sk->sk_pacing_status, SK_PACING_NONE, SK_PACING_NEEDED); sk->sk_max_pacing_rate = (val == ~0U) ? ~0UL : val; sk->sk_pacing_rate = min(sk->sk_pacing_rate, sk->sk_max_pacing_rate); break; case SO_PRIORITY: sk->sk_priority = val; break; case SO_RCVLOWAT: if (val < 0) val = INT_MAX; sk->sk_rcvlowat = val ? : 1; break; case SO_MARK: if (sk->sk_mark != val) { sk->sk_mark = val; sk_dst_reset(sk); } break; default: ret = -EINVAL; } #ifdef CONFIG_INET } else if (level == SOL_IP) { if (optlen != sizeof(int) || sk->sk_family != AF_INET) return -EINVAL; val = *((int *)optval); /* Only some options are supported */ switch (optname) { case IP_TOS: if (val < -1 || val > 0xff) { ret = -EINVAL; } else { struct inet_sock *inet = inet_sk(sk); if (val == -1) val = 0; inet->tos = val; } break; default: ret = -EINVAL; } #if IS_ENABLED(CONFIG_IPV6) } else if (level == SOL_IPV6) { if (optlen != sizeof(int) || sk->sk_family != AF_INET6) return -EINVAL; val = *((int *)optval); /* Only some options are supported */ switch (optname) { case IPV6_TCLASS: if (val < -1 || val > 0xff) { ret = -EINVAL; } else { struct ipv6_pinfo *np = inet6_sk(sk); if (val == -1) val = 0; np->tclass = val; } break; default: ret = -EINVAL; } #endif } else if (level == SOL_TCP && sk->sk_prot->setsockopt == tcp_setsockopt) { if (optname == TCP_CONGESTION) { char name[TCP_CA_NAME_MAX]; bool reinit = bpf_sock->op > BPF_SOCK_OPS_NEEDS_ECN; strncpy(name, optval, min_t(long, optlen, TCP_CA_NAME_MAX-1)); name[TCP_CA_NAME_MAX-1] = 0; ret = tcp_set_congestion_control(sk, name, false, reinit); } else { struct tcp_sock *tp = tcp_sk(sk); if (optlen != sizeof(int)) return -EINVAL; val = *((int *)optval); /* Only some options are supported */ switch (optname) { case TCP_BPF_IW: if (val <= 0 || tp->data_segs_out > tp->syn_data) ret = -EINVAL; else tp->snd_cwnd = val; break; case TCP_BPF_SNDCWND_CLAMP: if (val <= 0) { ret = -EINVAL; } else { tp->snd_cwnd_clamp = val; tp->snd_ssthresh = val; } break; case TCP_SAVE_SYN: if (val < 0 || val > 1) ret = -EINVAL; else tp->save_syn = val; break; default: ret = -EINVAL; } } #endif } else { ret = -EINVAL; } return ret; } static const struct bpf_func_proto bpf_setsockopt_proto = { .func = bpf_setsockopt, .gpl_only = false, .ret_type = RET_INTEGER, .arg1_type = ARG_PTR_TO_CTX, .arg2_type = ARG_ANYTHING, .arg3_type = ARG_ANYTHING, .arg4_type = ARG_PTR_TO_MEM, .arg5_type = ARG_CONST_SIZE, }; BPF_CALL_5(bpf_getsockopt, struct bpf_sock_ops_kern *, bpf_sock, int, level, int, optname, char *, optval, int, optlen) { struct sock *sk = bpf_sock->sk; if (!sk_fullsock(sk)) goto err_clear; #ifdef CONFIG_INET if (level == SOL_TCP && sk->sk_prot->getsockopt == tcp_getsockopt) { struct inet_connection_sock *icsk; struct tcp_sock *tp; switch (optname) { case TCP_CONGESTION: icsk = inet_csk(sk); if (!icsk->icsk_ca_ops || optlen <= 1) goto err_clear; strncpy(optval, icsk->icsk_ca_ops->name, optlen); optval[optlen - 1] = 0; break; case TCP_SAVED_SYN: tp = tcp_sk(sk); if (optlen <= 0 || !tp->saved_syn || optlen > tp->saved_syn[0]) goto err_clear; memcpy(optval, tp->saved_syn + 1, optlen); break; default: goto err_clear; } } else if (level == SOL_IP) { struct inet_sock *inet = inet_sk(sk); if (optlen != sizeof(int) || sk->sk_family != AF_INET) goto err_clear; /* Only some options are supported */ switch (optname) { case IP_TOS: *((int *)optval) = (int)inet->tos; break; default: goto err_clear; } #if IS_ENABLED(CONFIG_IPV6) } else if (level == SOL_IPV6) { struct ipv6_pinfo *np = inet6_sk(sk); if (optlen != sizeof(int) || sk->sk_family != AF_INET6) goto err_clear; /* Only some options are supported */ switch (optname) { case IPV6_TCLASS: *((int *)optval) = (int)np->tclass; break; default: goto err_clear; } #endif } else { goto err_clear; } return 0; #endif err_clear: memset(optval, 0, optlen); return -EINVAL; } static const struct bpf_func_proto bpf_getsockopt_proto = { .func = bpf_getsockopt, .gpl_only = false, .ret_type = RET_INTEGER, .arg1_type = ARG_PTR_TO_CTX, .arg2_type = ARG_ANYTHING, .arg3_type = ARG_ANYTHING, .arg4_type = ARG_PTR_TO_UNINIT_MEM, .arg5_type = ARG_CONST_SIZE, }; BPF_CALL_2(bpf_sock_ops_cb_flags_set, struct bpf_sock_ops_kern *, bpf_sock, int, argval) { struct sock *sk = bpf_sock->sk; int val = argval & BPF_SOCK_OPS_ALL_CB_FLAGS; if (!IS_ENABLED(CONFIG_INET) || !sk_fullsock(sk)) return -EINVAL; tcp_sk(sk)->bpf_sock_ops_cb_flags = val; return argval & (~BPF_SOCK_OPS_ALL_CB_FLAGS); } static const struct bpf_func_proto bpf_sock_ops_cb_flags_set_proto = { .func = bpf_sock_ops_cb_flags_set, .gpl_only = false, .ret_type = RET_INTEGER, .arg1_type = ARG_PTR_TO_CTX, .arg2_type = ARG_ANYTHING, }; const struct ipv6_bpf_stub *ipv6_bpf_stub __read_mostly; EXPORT_SYMBOL_GPL(ipv6_bpf_stub); BPF_CALL_3(bpf_bind, struct bpf_sock_addr_kern *, ctx, struct sockaddr *, addr, int, addr_len) { #ifdef CONFIG_INET struct sock *sk = ctx->sk; int err; /* Binding to port can be expensive so it's prohibited in the helper. * Only binding to IP is supported. */ err = -EINVAL; if (addr_len < offsetofend(struct sockaddr, sa_family)) return err; if (addr->sa_family == AF_INET) { if (addr_len < sizeof(struct sockaddr_in)) return err; if (((struct sockaddr_in *)addr)->sin_port != htons(0)) return err; return __inet_bind(sk, addr, addr_len, true, false); #if IS_ENABLED(CONFIG_IPV6) } else if (addr->sa_family == AF_INET6) { if (addr_len < SIN6_LEN_RFC2133) return err; if (((struct sockaddr_in6 *)addr)->sin6_port != htons(0)) return err; /* ipv6_bpf_stub cannot be NULL, since it's called from * bpf_cgroup_inet6_connect hook and ipv6 is already loaded */ return ipv6_bpf_stub->inet6_bind(sk, addr, addr_len, true, false); #endif /* CONFIG_IPV6 */ } #endif /* CONFIG_INET */ return -EAFNOSUPPORT; } static const struct bpf_func_proto bpf_bind_proto = { .func = bpf_bind, .gpl_only = false, .ret_type = RET_INTEGER, .arg1_type = ARG_PTR_TO_CTX, .arg2_type = ARG_PTR_TO_MEM, .arg3_type = ARG_CONST_SIZE, }; #ifdef CONFIG_XFRM BPF_CALL_5(bpf_skb_get_xfrm_state, struct sk_buff *, skb, u32, index, struct bpf_xfrm_state *, to, u32, size, u64, flags) { const struct sec_path *sp = skb_sec_path(skb); const struct xfrm_state *x; if (!sp || unlikely(index >= sp->len || flags)) goto err_clear; x = sp->xvec[index]; if (unlikely(size != sizeof(struct bpf_xfrm_state))) goto err_clear; to->reqid = x->props.reqid; to->spi = x->id.spi; to->family = x->props.family; to->ext = 0; if (to->family == AF_INET6) { memcpy(to->remote_ipv6, x->props.saddr.a6, sizeof(to->remote_ipv6)); } else { to->remote_ipv4 = x->props.saddr.a4; memset(&to->remote_ipv6[1], 0, sizeof(__u32) * 3); } return 0; err_clear: memset(to, 0, size); return -EINVAL; } static const struct bpf_func_proto bpf_skb_get_xfrm_state_proto = { .func = bpf_skb_get_xfrm_state, .gpl_only = false, .ret_type = RET_INTEGER, .arg1_type = ARG_PTR_TO_CTX, .arg2_type = ARG_ANYTHING, .arg3_type = ARG_PTR_TO_UNINIT_MEM, .arg4_type = ARG_CONST_SIZE, .arg5_type = ARG_ANYTHING, }; #endif #if IS_ENABLED(CONFIG_INET) || IS_ENABLED(CONFIG_IPV6) static int bpf_fib_set_fwd_params(struct bpf_fib_lookup *params, const struct neighbour *neigh, const struct net_device *dev) { memcpy(params->dmac, neigh->ha, ETH_ALEN); memcpy(params->smac, dev->dev_addr, ETH_ALEN); params->h_vlan_TCI = 0; params->h_vlan_proto = 0; params->ifindex = dev->ifindex; return 0; } #endif #if IS_ENABLED(CONFIG_INET) static int bpf_ipv4_fib_lookup(struct net *net, struct bpf_fib_lookup *params, u32 flags, bool check_mtu) { struct fib_nh_common *nhc; struct in_device *in_dev; struct neighbour *neigh; struct net_device *dev; struct fib_result res; struct flowi4 fl4; int err; u32 mtu; dev = dev_get_by_index_rcu(net, params->ifindex); if (unlikely(!dev)) return -ENODEV; /* verify forwarding is enabled on this interface */ in_dev = __in_dev_get_rcu(dev); if (unlikely(!in_dev || !IN_DEV_FORWARD(in_dev))) return BPF_FIB_LKUP_RET_FWD_DISABLED; if (flags & BPF_FIB_LOOKUP_OUTPUT) { fl4.flowi4_iif = 1; fl4.flowi4_oif = params->ifindex; } else { fl4.flowi4_iif = params->ifindex; fl4.flowi4_oif = 0; } fl4.flowi4_tos = params->tos & IPTOS_RT_MASK; fl4.flowi4_scope = RT_SCOPE_UNIVERSE; fl4.flowi4_flags = 0; fl4.flowi4_proto = params->l4_protocol; fl4.daddr = params->ipv4_dst; fl4.saddr = params->ipv4_src; fl4.fl4_sport = params->sport; fl4.fl4_dport = params->dport; if (flags & BPF_FIB_LOOKUP_DIRECT) { u32 tbid = l3mdev_fib_table_rcu(dev) ? : RT_TABLE_MAIN; struct fib_table *tb; tb = fib_get_table(net, tbid); if (unlikely(!tb)) return BPF_FIB_LKUP_RET_NOT_FWDED; err = fib_table_lookup(tb, &fl4, &res, FIB_LOOKUP_NOREF); } else { fl4.flowi4_mark = 0; fl4.flowi4_secid = 0; fl4.flowi4_tun_key.tun_id = 0; fl4.flowi4_uid = sock_net_uid(net, NULL); err = fib_lookup(net, &fl4, &res, FIB_LOOKUP_NOREF); } if (err) { /* map fib lookup errors to RTN_ type */ if (err == -EINVAL) return BPF_FIB_LKUP_RET_BLACKHOLE; if (err == -EHOSTUNREACH) return BPF_FIB_LKUP_RET_UNREACHABLE; if (err == -EACCES) return BPF_FIB_LKUP_RET_PROHIBIT; return BPF_FIB_LKUP_RET_NOT_FWDED; } if (res.type != RTN_UNICAST) return BPF_FIB_LKUP_RET_NOT_FWDED; if (res.fi->fib_nhs > 1) fib_select_path(net, &res, &fl4, NULL); if (check_mtu) { mtu = ip_mtu_from_fib_result(&res, params->ipv4_dst); if (params->tot_len > mtu) return BPF_FIB_LKUP_RET_FRAG_NEEDED; } nhc = res.nhc; /* do not handle lwt encaps right now */ if (nhc->nhc_lwtstate) return BPF_FIB_LKUP_RET_UNSUPP_LWT; dev = nhc->nhc_dev; params->rt_metric = res.fi->fib_priority; /* xdp and cls_bpf programs are run in RCU-bh so * rcu_read_lock_bh is not needed here */ if (likely(nhc->nhc_gw_family != AF_INET6)) { if (nhc->nhc_gw_family) params->ipv4_dst = nhc->nhc_gw.ipv4; neigh = __ipv4_neigh_lookup_noref(dev, (__force u32)params->ipv4_dst); } else { struct in6_addr *dst = (struct in6_addr *)params->ipv6_dst; params->family = AF_INET6; *dst = nhc->nhc_gw.ipv6; neigh = __ipv6_neigh_lookup_noref_stub(dev, dst); } if (!neigh) return BPF_FIB_LKUP_RET_NO_NEIGH; return bpf_fib_set_fwd_params(params, neigh, dev); } #endif #if IS_ENABLED(CONFIG_IPV6) static int bpf_ipv6_fib_lookup(struct net *net, struct bpf_fib_lookup *params, u32 flags, bool check_mtu) { struct in6_addr *src = (struct in6_addr *) params->ipv6_src; struct in6_addr *dst = (struct in6_addr *) params->ipv6_dst; struct fib6_result res = {}; struct neighbour *neigh; struct net_device *dev; struct inet6_dev *idev; struct flowi6 fl6; int strict = 0; int oif, err; u32 mtu; /* link local addresses are never forwarded */ if (rt6_need_strict(dst) || rt6_need_strict(src)) return BPF_FIB_LKUP_RET_NOT_FWDED; dev = dev_get_by_index_rcu(net, params->ifindex); if (unlikely(!dev)) return -ENODEV; idev = __in6_dev_get_safely(dev); if (unlikely(!idev || !net->ipv6.devconf_all->forwarding)) return BPF_FIB_LKUP_RET_FWD_DISABLED; if (flags & BPF_FIB_LOOKUP_OUTPUT) { fl6.flowi6_iif = 1; oif = fl6.flowi6_oif = params->ifindex; } else { oif = fl6.flowi6_iif = params->ifindex; fl6.flowi6_oif = 0; strict = RT6_LOOKUP_F_HAS_SADDR; } fl6.flowlabel = params->flowinfo; fl6.flowi6_scope = 0; fl6.flowi6_flags = 0; fl6.mp_hash = 0; fl6.flowi6_proto = params->l4_protocol; fl6.daddr = *dst; fl6.saddr = *src; fl6.fl6_sport = params->sport; fl6.fl6_dport = params->dport; if (flags & BPF_FIB_LOOKUP_DIRECT) { u32 tbid = l3mdev_fib_table_rcu(dev) ? : RT_TABLE_MAIN; struct fib6_table *tb; tb = ipv6_stub->fib6_get_table(net, tbid); if (unlikely(!tb)) return BPF_FIB_LKUP_RET_NOT_FWDED; err = ipv6_stub->fib6_table_lookup(net, tb, oif, &fl6, &res, strict); } else { fl6.flowi6_mark = 0; fl6.flowi6_secid = 0; fl6.flowi6_tun_key.tun_id = 0; fl6.flowi6_uid = sock_net_uid(net, NULL); err = ipv6_stub->fib6_lookup(net, oif, &fl6, &res, strict); } if (unlikely(err || IS_ERR_OR_NULL(res.f6i) || res.f6i == net->ipv6.fib6_null_entry)) return BPF_FIB_LKUP_RET_NOT_FWDED; switch (res.fib6_type) { /* only unicast is forwarded */ case RTN_UNICAST: break; case RTN_BLACKHOLE: return BPF_FIB_LKUP_RET_BLACKHOLE; case RTN_UNREACHABLE: return BPF_FIB_LKUP_RET_UNREACHABLE; case RTN_PROHIBIT: return BPF_FIB_LKUP_RET_PROHIBIT; default: return BPF_FIB_LKUP_RET_NOT_FWDED; } ipv6_stub->fib6_select_path(net, &res, &fl6, fl6.flowi6_oif, fl6.flowi6_oif != 0, NULL, strict); if (check_mtu) { mtu = ipv6_stub->ip6_mtu_from_fib6(&res, dst, src); if (params->tot_len > mtu) return BPF_FIB_LKUP_RET_FRAG_NEEDED; } if (res.nh->fib_nh_lws) return BPF_FIB_LKUP_RET_UNSUPP_LWT; if (res.nh->fib_nh_gw_family) *dst = res.nh->fib_nh_gw6; dev = res.nh->fib_nh_dev; params->rt_metric = res.f6i->fib6_metric; /* xdp and cls_bpf programs are run in RCU-bh so rcu_read_lock_bh is * not needed here. */ neigh = __ipv6_neigh_lookup_noref_stub(dev, dst); if (!neigh) return BPF_FIB_LKUP_RET_NO_NEIGH; return bpf_fib_set_fwd_params(params, neigh, dev); } #endif BPF_CALL_4(bpf_xdp_fib_lookup, struct xdp_buff *, ctx, struct bpf_fib_lookup *, params, int, plen, u32, flags) { if (plen < sizeof(*params)) return -EINVAL; if (flags & ~(BPF_FIB_LOOKUP_DIRECT | BPF_FIB_LOOKUP_OUTPUT)) return -EINVAL; switch (params->family) { #if IS_ENABLED(CONFIG_INET) case AF_INET: return bpf_ipv4_fib_lookup(dev_net(ctx->rxq->dev), params, flags, true); #endif #if IS_ENABLED(CONFIG_IPV6) case AF_INET6: return bpf_ipv6_fib_lookup(dev_net(ctx->rxq->dev), params, flags, true); #endif } return -EAFNOSUPPORT; } static const struct bpf_func_proto bpf_xdp_fib_lookup_proto = { .func = bpf_xdp_fib_lookup, .gpl_only = true, .ret_type = RET_INTEGER, .arg1_type = ARG_PTR_TO_CTX, .arg2_type = ARG_PTR_TO_MEM, .arg3_type = ARG_CONST_SIZE, .arg4_type = ARG_ANYTHING, }; BPF_CALL_4(bpf_skb_fib_lookup, struct sk_buff *, skb, struct bpf_fib_lookup *, params, int, plen, u32, flags) { struct net *net = dev_net(skb->dev); int rc = -EAFNOSUPPORT; if (plen < sizeof(*params)) return -EINVAL; if (flags & ~(BPF_FIB_LOOKUP_DIRECT | BPF_FIB_LOOKUP_OUTPUT)) return -EINVAL; switch (params->family) { #if IS_ENABLED(CONFIG_INET) case AF_INET: rc = bpf_ipv4_fib_lookup(net, params, flags, false); break; #endif #if IS_ENABLED(CONFIG_IPV6) case AF_INET6: rc = bpf_ipv6_fib_lookup(net, params, flags, false); break; #endif } if (!rc) { struct net_device *dev; dev = dev_get_by_index_rcu(net, params->ifindex); if (!is_skb_forwardable(dev, skb)) rc = BPF_FIB_LKUP_RET_FRAG_NEEDED; } return rc; } static const struct bpf_func_proto bpf_skb_fib_lookup_proto = { .func = bpf_skb_fib_lookup, .gpl_only = true, .ret_type = RET_INTEGER, .arg1_type = ARG_PTR_TO_CTX, .arg2_type = ARG_PTR_TO_MEM, .arg3_type = ARG_CONST_SIZE, .arg4_type = ARG_ANYTHING, }; #if IS_ENABLED(CONFIG_IPV6_SEG6_BPF) static int bpf_push_seg6_encap(struct sk_buff *skb, u32 type, void *hdr, u32 len) { int err; struct ipv6_sr_hdr *srh = (struct ipv6_sr_hdr *)hdr; if (!seg6_validate_srh(srh, len)) return -EINVAL; switch (type) { case BPF_LWT_ENCAP_SEG6_INLINE: if (skb->protocol != htons(ETH_P_IPV6)) return -EBADMSG; err = seg6_do_srh_inline(skb, srh); break; case BPF_LWT_ENCAP_SEG6: skb_reset_inner_headers(skb); skb->encapsulation = 1; err = seg6_do_srh_encap(skb, srh, IPPROTO_IPV6); break; default: return -EINVAL; } bpf_compute_data_pointers(skb); if (err) return err; ipv6_hdr(skb)->payload_len = htons(skb->len - sizeof(struct ipv6hdr)); skb_set_transport_header(skb, sizeof(struct ipv6hdr)); return seg6_lookup_nexthop(skb, NULL, 0); } #endif /* CONFIG_IPV6_SEG6_BPF */ #if IS_ENABLED(CONFIG_LWTUNNEL_BPF) static int bpf_push_ip_encap(struct sk_buff *skb, void *hdr, u32 len, bool ingress) { return bpf_lwt_push_ip_encap(skb, hdr, len, ingress); } #endif BPF_CALL_4(bpf_lwt_in_push_encap, struct sk_buff *, skb, u32, type, void *, hdr, u32, len) { switch (type) { #if IS_ENABLED(CONFIG_IPV6_SEG6_BPF) case BPF_LWT_ENCAP_SEG6: case BPF_LWT_ENCAP_SEG6_INLINE: return bpf_push_seg6_encap(skb, type, hdr, len); #endif #if IS_ENABLED(CONFIG_LWTUNNEL_BPF) case BPF_LWT_ENCAP_IP: return bpf_push_ip_encap(skb, hdr, len, true /* ingress */); #endif default: return -EINVAL; } } BPF_CALL_4(bpf_lwt_xmit_push_encap, struct sk_buff *, skb, u32, type, void *, hdr, u32, len) { switch (type) { #if IS_ENABLED(CONFIG_LWTUNNEL_BPF) case BPF_LWT_ENCAP_IP: return bpf_push_ip_encap(skb, hdr, len, false /* egress */); #endif default: return -EINVAL; } } static const struct bpf_func_proto bpf_lwt_in_push_encap_proto = { .func = bpf_lwt_in_push_encap, .gpl_only = false, .ret_type = RET_INTEGER, .arg1_type = ARG_PTR_TO_CTX, .arg2_type = ARG_ANYTHING, .arg3_type = ARG_PTR_TO_MEM, .arg4_type = ARG_CONST_SIZE }; static const struct bpf_func_proto bpf_lwt_xmit_push_encap_proto = { .func = bpf_lwt_xmit_push_encap, .gpl_only = false, .ret_type = RET_INTEGER, .arg1_type = ARG_PTR_TO_CTX, .arg2_type = ARG_ANYTHING, .arg3_type = ARG_PTR_TO_MEM, .arg4_type = ARG_CONST_SIZE }; #if IS_ENABLED(CONFIG_IPV6_SEG6_BPF) BPF_CALL_4(bpf_lwt_seg6_store_bytes, struct sk_buff *, skb, u32, offset, const void *, from, u32, len) { struct seg6_bpf_srh_state *srh_state = this_cpu_ptr(&seg6_bpf_srh_states); struct ipv6_sr_hdr *srh = srh_state->srh; void *srh_tlvs, *srh_end, *ptr; int srhoff = 0; if (srh == NULL) return -EINVAL; srh_tlvs = (void *)((char *)srh + ((srh->first_segment + 1) << 4)); srh_end = (void *)((char *)srh + sizeof(*srh) + srh_state->hdrlen); ptr = skb->data + offset; if (ptr >= srh_tlvs && ptr + len <= srh_end) srh_state->valid = false; else if (ptr < (void *)&srh->flags || ptr + len > (void *)&srh->segments) return -EFAULT; if (unlikely(bpf_try_make_writable(skb, offset + len))) return -EFAULT; if (ipv6_find_hdr(skb, &srhoff, IPPROTO_ROUTING, NULL, NULL) < 0) return -EINVAL; srh_state->srh = (struct ipv6_sr_hdr *)(skb->data + srhoff); memcpy(skb->data + offset, from, len); return 0; } static const struct bpf_func_proto bpf_lwt_seg6_store_bytes_proto = { .func = bpf_lwt_seg6_store_bytes, .gpl_only = false, .ret_type = RET_INTEGER, .arg1_type = ARG_PTR_TO_CTX, .arg2_type = ARG_ANYTHING, .arg3_type = ARG_PTR_TO_MEM, .arg4_type = ARG_CONST_SIZE }; static void bpf_update_srh_state(struct sk_buff *skb) { struct seg6_bpf_srh_state *srh_state = this_cpu_ptr(&seg6_bpf_srh_states); int srhoff = 0; if (ipv6_find_hdr(skb, &srhoff, IPPROTO_ROUTING, NULL, NULL) < 0) { srh_state->srh = NULL; } else { srh_state->srh = (struct ipv6_sr_hdr *)(skb->data + srhoff); srh_state->hdrlen = srh_state->srh->hdrlen << 3; srh_state->valid = true; } } BPF_CALL_4(bpf_lwt_seg6_action, struct sk_buff *, skb, u32, action, void *, param, u32, param_len) { struct seg6_bpf_srh_state *srh_state = this_cpu_ptr(&seg6_bpf_srh_states); int hdroff = 0; int err; switch (action) { case SEG6_LOCAL_ACTION_END_X: if (!seg6_bpf_has_valid_srh(skb)) return -EBADMSG; if (param_len != sizeof(struct in6_addr)) return -EINVAL; return seg6_lookup_nexthop(skb, (struct in6_addr *)param, 0); case SEG6_LOCAL_ACTION_END_T: if (!seg6_bpf_has_valid_srh(skb)) return -EBADMSG; if (param_len != sizeof(int)) return -EINVAL; return seg6_lookup_nexthop(skb, NULL, *(int *)param); case SEG6_LOCAL_ACTION_END_DT6: if (!seg6_bpf_has_valid_srh(skb)) return -EBADMSG; if (param_len != sizeof(int)) return -EINVAL; if (ipv6_find_hdr(skb, &hdroff, IPPROTO_IPV6, NULL, NULL) < 0) return -EBADMSG; if (!pskb_pull(skb, hdroff)) return -EBADMSG; skb_postpull_rcsum(skb, skb_network_header(skb), hdroff); skb_reset_network_header(skb); skb_reset_transport_header(skb); skb->encapsulation = 0; bpf_compute_data_pointers(skb); bpf_update_srh_state(skb); return seg6_lookup_nexthop(skb, NULL, *(int *)param); case SEG6_LOCAL_ACTION_END_B6: if (srh_state->srh && !seg6_bpf_has_valid_srh(skb)) return -EBADMSG; err = bpf_push_seg6_encap(skb, BPF_LWT_ENCAP_SEG6_INLINE, param, param_len); if (!err) bpf_update_srh_state(skb); return err; case SEG6_LOCAL_ACTION_END_B6_ENCAP: if (srh_state->srh && !seg6_bpf_has_valid_srh(skb)) return -EBADMSG; err = bpf_push_seg6_encap(skb, BPF_LWT_ENCAP_SEG6, param, param_len); if (!err) bpf_update_srh_state(skb); return err; default: return -EINVAL; } } static const struct bpf_func_proto bpf_lwt_seg6_action_proto = { .func = bpf_lwt_seg6_action, .gpl_only = false, .ret_type = RET_INTEGER, .arg1_type = ARG_PTR_TO_CTX, .arg2_type = ARG_ANYTHING, .arg3_type = ARG_PTR_TO_MEM, .arg4_type = ARG_CONST_SIZE }; BPF_CALL_3(bpf_lwt_seg6_adjust_srh, struct sk_buff *, skb, u32, offset, s32, len) { struct seg6_bpf_srh_state *srh_state = this_cpu_ptr(&seg6_bpf_srh_states); struct ipv6_sr_hdr *srh = srh_state->srh; void *srh_end, *srh_tlvs, *ptr; struct ipv6hdr *hdr; int srhoff = 0; int ret; if (unlikely(srh == NULL)) return -EINVAL; srh_tlvs = (void *)((unsigned char *)srh + sizeof(*srh) + ((srh->first_segment + 1) << 4)); srh_end = (void *)((unsigned char *)srh + sizeof(*srh) + srh_state->hdrlen); ptr = skb->data + offset; if (unlikely(ptr < srh_tlvs || ptr > srh_end)) return -EFAULT; if (unlikely(len < 0 && (void *)((char *)ptr - len) > srh_end)) return -EFAULT; if (len > 0) { ret = skb_cow_head(skb, len); if (unlikely(ret < 0)) return ret; ret = bpf_skb_net_hdr_push(skb, offset, len); } else { ret = bpf_skb_net_hdr_pop(skb, offset, -1 * len); } bpf_compute_data_pointers(skb); if (unlikely(ret < 0)) return ret; hdr = (struct ipv6hdr *)skb->data; hdr->payload_len = htons(skb->len - sizeof(struct ipv6hdr)); if (ipv6_find_hdr(skb, &srhoff, IPPROTO_ROUTING, NULL, NULL) < 0) return -EINVAL; srh_state->srh = (struct ipv6_sr_hdr *)(skb->data + srhoff); srh_state->hdrlen += len; srh_state->valid = false; return 0; } static const struct bpf_func_proto bpf_lwt_seg6_adjust_srh_proto = { .func = bpf_lwt_seg6_adjust_srh, .gpl_only = false, .ret_type = RET_INTEGER, .arg1_type = ARG_PTR_TO_CTX, .arg2_type = ARG_ANYTHING, .arg3_type = ARG_ANYTHING, }; #endif /* CONFIG_IPV6_SEG6_BPF */ #define CONVERT_COMMON_TCP_SOCK_FIELDS(md_type, CONVERT) \ do { \ switch (si->off) { \ case offsetof(md_type, snd_cwnd): \ CONVERT(snd_cwnd); break; \ case offsetof(md_type, srtt_us): \ CONVERT(srtt_us); break; \ case offsetof(md_type, snd_ssthresh): \ CONVERT(snd_ssthresh); break; \ case offsetof(md_type, rcv_nxt): \ CONVERT(rcv_nxt); break; \ case offsetof(md_type, snd_nxt): \ CONVERT(snd_nxt); break; \ case offsetof(md_type, snd_una): \ CONVERT(snd_una); break; \ case offsetof(md_type, mss_cache): \ CONVERT(mss_cache); break; \ case offsetof(md_type, ecn_flags): \ CONVERT(ecn_flags); break; \ case offsetof(md_type, rate_delivered): \ CONVERT(rate_delivered); break; \ case offsetof(md_type, rate_interval_us): \ CONVERT(rate_interval_us); break; \ case offsetof(md_type, packets_out): \ CONVERT(packets_out); break; \ case offsetof(md_type, retrans_out): \ CONVERT(retrans_out); break; \ case offsetof(md_type, total_retrans): \ CONVERT(total_retrans); break; \ case offsetof(md_type, segs_in): \ CONVERT(segs_in); break; \ case offsetof(md_type, data_segs_in): \ CONVERT(data_segs_in); break; \ case offsetof(md_type, segs_out): \ CONVERT(segs_out); break; \ case offsetof(md_type, data_segs_out): \ CONVERT(data_segs_out); break; \ case offsetof(md_type, lost_out): \ CONVERT(lost_out); break; \ case offsetof(md_type, sacked_out): \ CONVERT(sacked_out); break; \ case offsetof(md_type, bytes_received): \ CONVERT(bytes_received); break; \ case offsetof(md_type, bytes_acked): \ CONVERT(bytes_acked); break; \ } \ } while (0) #ifdef CONFIG_INET static struct sock *sk_lookup(struct net *net, struct bpf_sock_tuple *tuple, int dif, int sdif, u8 family, u8 proto) { bool refcounted = false; struct sock *sk = NULL; if (family == AF_INET) { __be32 src4 = tuple->ipv4.saddr; __be32 dst4 = tuple->ipv4.daddr; if (proto == IPPROTO_TCP) sk = __inet_lookup(net, &tcp_hashinfo, NULL, 0, src4, tuple->ipv4.sport, dst4, tuple->ipv4.dport, dif, sdif, &refcounted); else sk = __udp4_lib_lookup(net, src4, tuple->ipv4.sport, dst4, tuple->ipv4.dport, dif, sdif, &udp_table, NULL); #if IS_ENABLED(CONFIG_IPV6) } else { struct in6_addr *src6 = (struct in6_addr *)&tuple->ipv6.saddr; struct in6_addr *dst6 = (struct in6_addr *)&tuple->ipv6.daddr; if (proto == IPPROTO_TCP) sk = __inet6_lookup(net, &tcp_hashinfo, NULL, 0, src6, tuple->ipv6.sport, dst6, ntohs(tuple->ipv6.dport), dif, sdif, &refcounted); else if (likely(ipv6_bpf_stub)) sk = ipv6_bpf_stub->udp6_lib_lookup(net, src6, tuple->ipv6.sport, dst6, tuple->ipv6.dport, dif, sdif, &udp_table, NULL); #endif } if (unlikely(sk && !refcounted && !sock_flag(sk, SOCK_RCU_FREE))) { WARN_ONCE(1, "Found non-RCU, unreferenced socket!"); sk = NULL; } return sk; } /* bpf_skc_lookup performs the core lookup for different types of sockets, * taking a reference on the socket if it doesn't have the flag SOCK_RCU_FREE. * Returns the socket as an 'unsigned long' to simplify the casting in the * callers to satisfy BPF_CALL declarations. */ static struct sock * __bpf_skc_lookup(struct sk_buff *skb, struct bpf_sock_tuple *tuple, u32 len, struct net *caller_net, u32 ifindex, u8 proto, u64 netns_id, u64 flags) { struct sock *sk = NULL; u8 family = AF_UNSPEC; struct net *net; int sdif; if (len == sizeof(tuple->ipv4)) family = AF_INET; else if (len == sizeof(tuple->ipv6)) family = AF_INET6; else return NULL; if (unlikely(family == AF_UNSPEC || flags || !((s32)netns_id < 0 || netns_id <= S32_MAX))) goto out; if (family == AF_INET) sdif = inet_sdif(skb); else sdif = inet6_sdif(skb); if ((s32)netns_id < 0) { net = caller_net; sk = sk_lookup(net, tuple, ifindex, sdif, family, proto); } else { net = get_net_ns_by_id(caller_net, netns_id); if (unlikely(!net)) goto out; sk = sk_lookup(net, tuple, ifindex, sdif, family, proto); put_net(net); } out: return sk; } static struct sock * __bpf_sk_lookup(struct sk_buff *skb, struct bpf_sock_tuple *tuple, u32 len, struct net *caller_net, u32 ifindex, u8 proto, u64 netns_id, u64 flags) { struct sock *sk = __bpf_skc_lookup(skb, tuple, len, caller_net, ifindex, proto, netns_id, flags); if (sk) { sk = sk_to_full_sk(sk); if (!sk_fullsock(sk)) { if (!sock_flag(sk, SOCK_RCU_FREE)) sock_gen_put(sk); return NULL; } } return sk; } static struct sock * bpf_skc_lookup(struct sk_buff *skb, struct bpf_sock_tuple *tuple, u32 len, u8 proto, u64 netns_id, u64 flags) { struct net *caller_net; int ifindex; if (skb->dev) { caller_net = dev_net(skb->dev); ifindex = skb->dev->ifindex; } else { caller_net = sock_net(skb->sk); ifindex = 0; } return __bpf_skc_lookup(skb, tuple, len, caller_net, ifindex, proto, netns_id, flags); } static struct sock * bpf_sk_lookup(struct sk_buff *skb, struct bpf_sock_tuple *tuple, u32 len, u8 proto, u64 netns_id, u64 flags) { struct sock *sk = bpf_skc_lookup(skb, tuple, len, proto, netns_id, flags); if (sk) { sk = sk_to_full_sk(sk); if (!sk_fullsock(sk)) { if (!sock_flag(sk, SOCK_RCU_FREE)) sock_gen_put(sk); return NULL; } } return sk; } BPF_CALL_5(bpf_skc_lookup_tcp, struct sk_buff *, skb, struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags) { return (unsigned long)bpf_skc_lookup(skb, tuple, len, IPPROTO_TCP, netns_id, flags); } static const struct bpf_func_proto bpf_skc_lookup_tcp_proto = { .func = bpf_skc_lookup_tcp, .gpl_only = false, .pkt_access = true, .ret_type = RET_PTR_TO_SOCK_COMMON_OR_NULL, .arg1_type = ARG_PTR_TO_CTX, .arg2_type = ARG_PTR_TO_MEM, .arg3_type = ARG_CONST_SIZE, .arg4_type = ARG_ANYTHING, .arg5_type = ARG_ANYTHING, }; BPF_CALL_5(bpf_sk_lookup_tcp, struct sk_buff *, skb, struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags) { return (unsigned long)bpf_sk_lookup(skb, tuple, len, IPPROTO_TCP, netns_id, flags); } static const struct bpf_func_proto bpf_sk_lookup_tcp_proto = { .func = bpf_sk_lookup_tcp, .gpl_only = false, .pkt_access = true, .ret_type = RET_PTR_TO_SOCKET_OR_NULL, .arg1_type = ARG_PTR_TO_CTX, .arg2_type = ARG_PTR_TO_MEM, .arg3_type = ARG_CONST_SIZE, .arg4_type = ARG_ANYTHING, .arg5_type = ARG_ANYTHING, }; BPF_CALL_5(bpf_sk_lookup_udp, struct sk_buff *, skb, struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags) { return (unsigned long)bpf_sk_lookup(skb, tuple, len, IPPROTO_UDP, netns_id, flags); } static const struct bpf_func_proto bpf_sk_lookup_udp_proto = { .func = bpf_sk_lookup_udp, .gpl_only = false, .pkt_access = true, .ret_type = RET_PTR_TO_SOCKET_OR_NULL, .arg1_type = ARG_PTR_TO_CTX, .arg2_type = ARG_PTR_TO_MEM, .arg3_type = ARG_CONST_SIZE, .arg4_type = ARG_ANYTHING, .arg5_type = ARG_ANYTHING, }; BPF_CALL_1(bpf_sk_release, struct sock *, sk) { if (!sock_flag(sk, SOCK_RCU_FREE)) sock_gen_put(sk); return 0; } static const struct bpf_func_proto bpf_sk_release_proto = { .func = bpf_sk_release, .gpl_only = false, .ret_type = RET_INTEGER, .arg1_type = ARG_PTR_TO_SOCK_COMMON, }; BPF_CALL_5(bpf_xdp_sk_lookup_udp, struct xdp_buff *, ctx, struct bpf_sock_tuple *, tuple, u32, len, u32, netns_id, u64, flags) { struct net *caller_net = dev_net(ctx->rxq->dev); int ifindex = ctx->rxq->dev->ifindex; return (unsigned long)__bpf_sk_lookup(NULL, tuple, len, caller_net, ifindex, IPPROTO_UDP, netns_id, flags); } static const struct bpf_func_proto bpf_xdp_sk_lookup_udp_proto = { .func = bpf_xdp_sk_lookup_udp, .gpl_only = false, .pkt_access = true, .ret_type = RET_PTR_TO_SOCKET_OR_NULL, .arg1_type = ARG_PTR_TO_CTX, .arg2_type = ARG_PTR_TO_MEM, .arg3_type = ARG_CONST_SIZE, .arg4_type = ARG_ANYTHING, .arg5_type = ARG_ANYTHING, }; BPF_CALL_5(bpf_xdp_skc_lookup_tcp, struct xdp_buff *, ctx, struct bpf_sock_tuple *, tuple, u32, len, u32, netns_id, u64, flags) { struct net *caller_net = dev_net(ctx->rxq->dev); int ifindex = ctx->rxq->dev->ifindex; return (unsigned long)__bpf_skc_lookup(NULL, tuple, len, caller_net, ifindex, IPPROTO_TCP, netns_id, flags); } static const struct bpf_func_proto bpf_xdp_skc_lookup_tcp_proto = { .func = bpf_xdp_skc_lookup_tcp, .gpl_only = false, .pkt_access = true, .ret_type = RET_PTR_TO_SOCK_COMMON_OR_NULL, .arg1_type = ARG_PTR_TO_CTX, .arg2_type = ARG_PTR_TO_MEM, .arg3_type = ARG_CONST_SIZE, .arg4_type = ARG_ANYTHING, .arg5_type = ARG_ANYTHING, }; BPF_CALL_5(bpf_xdp_sk_lookup_tcp, struct xdp_buff *, ctx, struct bpf_sock_tuple *, tuple, u32, len, u32, netns_id, u64, flags) { struct net *caller_net = dev_net(ctx->rxq->dev); int ifindex = ctx->rxq->dev->ifindex; return (unsigned long)__bpf_sk_lookup(NULL, tuple, len, caller_net, ifindex, IPPROTO_TCP, netns_id, flags); } static const struct bpf_func_proto bpf_xdp_sk_lookup_tcp_proto = { .func = bpf_xdp_sk_lookup_tcp, .gpl_only = false, .pkt_access = true, .ret_type = RET_PTR_TO_SOCKET_OR_NULL, .arg1_type = ARG_PTR_TO_CTX, .arg2_type = ARG_PTR_TO_MEM, .arg3_type = ARG_CONST_SIZE, .arg4_type = ARG_ANYTHING, .arg5_type = ARG_ANYTHING, }; BPF_CALL_5(bpf_sock_addr_skc_lookup_tcp, struct bpf_sock_addr_kern *, ctx, struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags) { return (unsigned long)__bpf_skc_lookup(NULL, tuple, len, sock_net(ctx->sk), 0, IPPROTO_TCP, netns_id, flags); } static const struct bpf_func_proto bpf_sock_addr_skc_lookup_tcp_proto = { .func = bpf_sock_addr_skc_lookup_tcp, .gpl_only = false, .ret_type = RET_PTR_TO_SOCK_COMMON_OR_NULL, .arg1_type = ARG_PTR_TO_CTX, .arg2_type = ARG_PTR_TO_MEM, .arg3_type = ARG_CONST_SIZE, .arg4_type = ARG_ANYTHING, .arg5_type = ARG_ANYTHING, }; BPF_CALL_5(bpf_sock_addr_sk_lookup_tcp, struct bpf_sock_addr_kern *, ctx, struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags) { return (unsigned long)__bpf_sk_lookup(NULL, tuple, len, sock_net(ctx->sk), 0, IPPROTO_TCP, netns_id, flags); } static const struct bpf_func_proto bpf_sock_addr_sk_lookup_tcp_proto = { .func = bpf_sock_addr_sk_lookup_tcp, .gpl_only = false, .ret_type = RET_PTR_TO_SOCKET_OR_NULL, .arg1_type = ARG_PTR_TO_CTX, .arg2_type = ARG_PTR_TO_MEM, .arg3_type = ARG_CONST_SIZE, .arg4_type = ARG_ANYTHING, .arg5_type = ARG_ANYTHING, }; BPF_CALL_5(bpf_sock_addr_sk_lookup_udp, struct bpf_sock_addr_kern *, ctx, struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags) { return (unsigned long)__bpf_sk_lookup(NULL, tuple, len, sock_net(ctx->sk), 0, IPPROTO_UDP, netns_id, flags); } static const struct bpf_func_proto bpf_sock_addr_sk_lookup_udp_proto = { .func = bpf_sock_addr_sk_lookup_udp, .gpl_only = false, .ret_type = RET_PTR_TO_SOCKET_OR_NULL, .arg1_type = ARG_PTR_TO_CTX, .arg2_type = ARG_PTR_TO_MEM, .arg3_type = ARG_CONST_SIZE, .arg4_type = ARG_ANYTHING, .arg5_type = ARG_ANYTHING, }; bool bpf_tcp_sock_is_valid_access(int off, int size, enum bpf_access_type type, struct bpf_insn_access_aux *info) { if (off < 0 || off >= offsetofend(struct bpf_tcp_sock, bytes_acked)) return false; if (off % size != 0) return false; switch (off) { case offsetof(struct bpf_tcp_sock, bytes_received): case offsetof(struct bpf_tcp_sock, bytes_acked): return size == sizeof(__u64); default: return size == sizeof(__u32); } } u32 bpf_tcp_sock_convert_ctx_access(enum bpf_access_type type, const struct bpf_insn *si, struct bpf_insn *insn_buf, struct bpf_prog *prog, u32 *target_size) { struct bpf_insn *insn = insn_buf; #define BPF_TCP_SOCK_GET_COMMON(FIELD) \ do { \ BUILD_BUG_ON(FIELD_SIZEOF(struct tcp_sock, FIELD) > \ FIELD_SIZEOF(struct bpf_tcp_sock, FIELD)); \ *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct tcp_sock, FIELD),\ si->dst_reg, si->src_reg, \ offsetof(struct tcp_sock, FIELD)); \ } while (0) CONVERT_COMMON_TCP_SOCK_FIELDS(struct bpf_tcp_sock, BPF_TCP_SOCK_GET_COMMON); if (insn > insn_buf) return insn - insn_buf; switch (si->off) { case offsetof(struct bpf_tcp_sock, rtt_min): BUILD_BUG_ON(FIELD_SIZEOF(struct tcp_sock, rtt_min) != sizeof(struct minmax)); BUILD_BUG_ON(sizeof(struct minmax) < sizeof(struct minmax_sample)); *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg, offsetof(struct tcp_sock, rtt_min) + offsetof(struct minmax_sample, v)); break; } return insn - insn_buf; } BPF_CALL_1(bpf_tcp_sock, struct sock *, sk) { if (sk_fullsock(sk) && sk->sk_protocol == IPPROTO_TCP) return (unsigned long)sk; return (unsigned long)NULL; } static const struct bpf_func_proto bpf_tcp_sock_proto = { .func = bpf_tcp_sock, .gpl_only = false, .ret_type = RET_PTR_TO_TCP_SOCK_OR_NULL, .arg1_type = ARG_PTR_TO_SOCK_COMMON, }; BPF_CALL_1(bpf_get_listener_sock, struct sock *, sk) { sk = sk_to_full_sk(sk); if (sk->sk_state == TCP_LISTEN && sock_flag(sk, SOCK_RCU_FREE)) return (unsigned long)sk; return (unsigned long)NULL; } static const struct bpf_func_proto bpf_get_listener_sock_proto = { .func = bpf_get_listener_sock, .gpl_only = false, .ret_type = RET_PTR_TO_SOCKET_OR_NULL, .arg1_type = ARG_PTR_TO_SOCK_COMMON, }; BPF_CALL_1(bpf_skb_ecn_set_ce, struct sk_buff *, skb) { unsigned int iphdr_len; if (skb->protocol == cpu_to_be16(ETH_P_IP)) iphdr_len = sizeof(struct iphdr); else if (skb->protocol == cpu_to_be16(ETH_P_IPV6)) iphdr_len = sizeof(struct ipv6hdr); else return 0; if (skb_headlen(skb) < iphdr_len) return 0; if (skb_cloned(skb) && !skb_clone_writable(skb, iphdr_len)) return 0; return INET_ECN_set_ce(skb); } static const struct bpf_func_proto bpf_skb_ecn_set_ce_proto = { .func = bpf_skb_ecn_set_ce, .gpl_only = false, .ret_type = RET_INTEGER, .arg1_type = ARG_PTR_TO_CTX, }; BPF_CALL_5(bpf_tcp_check_syncookie, struct sock *, sk, void *, iph, u32, iph_len, struct tcphdr *, th, u32, th_len) { #ifdef CONFIG_SYN_COOKIES u32 cookie; int ret; if (unlikely(th_len < sizeof(*th))) return -EINVAL; /* sk_listener() allows TCP_NEW_SYN_RECV, which makes no sense here. */ if (sk->sk_protocol != IPPROTO_TCP || sk->sk_state != TCP_LISTEN) return -EINVAL; if (!sock_net(sk)->ipv4.sysctl_tcp_syncookies) return -EINVAL; if (!th->ack || th->rst || th->syn) return -ENOENT; if (tcp_synq_no_recent_overflow(sk)) return -ENOENT; cookie = ntohl(th->ack_seq) - 1; switch (sk->sk_family) { case AF_INET: if (unlikely(iph_len < sizeof(struct iphdr))) return -EINVAL; ret = __cookie_v4_check((struct iphdr *)iph, th, cookie); break; #if IS_BUILTIN(CONFIG_IPV6) case AF_INET6: if (unlikely(iph_len < sizeof(struct ipv6hdr))) return -EINVAL; ret = __cookie_v6_check((struct ipv6hdr *)iph, th, cookie); break; #endif /* CONFIG_IPV6 */ default: return -EPROTONOSUPPORT; } if (ret > 0) return 0; return -ENOENT; #else return -ENOTSUPP; #endif } static const struct bpf_func_proto bpf_tcp_check_syncookie_proto = { .func = bpf_tcp_check_syncookie, .gpl_only = true, .pkt_access = true, .ret_type = RET_INTEGER, .arg1_type = ARG_PTR_TO_SOCK_COMMON, .arg2_type = ARG_PTR_TO_MEM, .arg3_type = ARG_CONST_SIZE, .arg4_type = ARG_PTR_TO_MEM, .arg5_type = ARG_CONST_SIZE, }; #endif /* CONFIG_INET */ bool bpf_helper_changes_pkt_data(void *func) { if (func == bpf_skb_vlan_push || func == bpf_skb_vlan_pop || func == bpf_skb_store_bytes || func == bpf_skb_change_proto || func == bpf_skb_change_head || func == sk_skb_change_head || func == bpf_skb_change_tail || func == sk_skb_change_tail || func == bpf_skb_adjust_room || func == bpf_skb_pull_data || func == sk_skb_pull_data || func == bpf_clone_redirect || func == bpf_l3_csum_replace || func == bpf_l4_csum_replace || func == bpf_xdp_adjust_head || func == bpf_xdp_adjust_meta || func == bpf_msg_pull_data || func == bpf_msg_push_data || func == bpf_msg_pop_data || func == bpf_xdp_adjust_tail || #if IS_ENABLED(CONFIG_IPV6_SEG6_BPF) func == bpf_lwt_seg6_store_bytes || func == bpf_lwt_seg6_adjust_srh || func == bpf_lwt_seg6_action || #endif func == bpf_lwt_in_push_encap || func == bpf_lwt_xmit_push_encap) return true; return false; } static const struct bpf_func_proto * bpf_base_func_proto(enum bpf_func_id func_id) { switch (func_id) { case BPF_FUNC_map_lookup_elem: return &bpf_map_lookup_elem_proto; case BPF_FUNC_map_update_elem: return &bpf_map_update_elem_proto; case BPF_FUNC_map_delete_elem: return &bpf_map_delete_elem_proto; case BPF_FUNC_map_push_elem: return &bpf_map_push_elem_proto; case BPF_FUNC_map_pop_elem: return &bpf_map_pop_elem_proto; case BPF_FUNC_map_peek_elem: return &bpf_map_peek_elem_proto; case BPF_FUNC_get_prandom_u32: return &bpf_get_prandom_u32_proto; case BPF_FUNC_get_smp_processor_id: return &bpf_get_raw_smp_processor_id_proto; case BPF_FUNC_get_numa_node_id: return &bpf_get_numa_node_id_proto; case BPF_FUNC_tail_call: return &bpf_tail_call_proto; case BPF_FUNC_ktime_get_ns: return &bpf_ktime_get_ns_proto; default: break; } if (!capable(CAP_SYS_ADMIN)) return NULL; switch (func_id) { case BPF_FUNC_spin_lock: return &bpf_spin_lock_proto; case BPF_FUNC_spin_unlock: return &bpf_spin_unlock_proto; case BPF_FUNC_trace_printk: return bpf_get_trace_printk_proto(); default: return NULL; } } static const struct bpf_func_proto * sock_filter_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog) { switch (func_id) { /* inet and inet6 sockets are created in a process * context so there is always a valid uid/gid */ case BPF_FUNC_get_current_uid_gid: return &bpf_get_current_uid_gid_proto; case BPF_FUNC_get_local_storage: return &bpf_get_local_storage_proto; default: return bpf_base_func_proto(func_id); } } static const struct bpf_func_proto * sock_addr_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog) { switch (func_id) { /* inet and inet6 sockets are created in a process * context so there is always a valid uid/gid */ case BPF_FUNC_get_current_uid_gid: return &bpf_get_current_uid_gid_proto; case BPF_FUNC_bind: switch (prog->expected_attach_type) { case BPF_CGROUP_INET4_CONNECT: case BPF_CGROUP_INET6_CONNECT: return &bpf_bind_proto; default: return NULL; } case BPF_FUNC_get_socket_cookie: return &bpf_get_socket_cookie_sock_addr_proto; case BPF_FUNC_get_local_storage: return &bpf_get_local_storage_proto; #ifdef CONFIG_INET case BPF_FUNC_sk_lookup_tcp: return &bpf_sock_addr_sk_lookup_tcp_proto; case BPF_FUNC_sk_lookup_udp: return &bpf_sock_addr_sk_lookup_udp_proto; case BPF_FUNC_sk_release: return &bpf_sk_release_proto; case BPF_FUNC_skc_lookup_tcp: return &bpf_sock_addr_skc_lookup_tcp_proto; #endif /* CONFIG_INET */ default: return bpf_base_func_proto(func_id); } } static const struct bpf_func_proto * sk_filter_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog) { switch (func_id) { case BPF_FUNC_skb_load_bytes: return &bpf_skb_load_bytes_proto; case BPF_FUNC_skb_load_bytes_relative: return &bpf_skb_load_bytes_relative_proto; case BPF_FUNC_get_socket_cookie: return &bpf_get_socket_cookie_proto; case BPF_FUNC_get_socket_uid: return &bpf_get_socket_uid_proto; default: return bpf_base_func_proto(func_id); } } const struct bpf_func_proto bpf_sk_storage_get_proto __weak; const struct bpf_func_proto bpf_sk_storage_delete_proto __weak; static const struct bpf_func_proto * cg_skb_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog) { switch (func_id) { case BPF_FUNC_get_local_storage: return &bpf_get_local_storage_proto; case BPF_FUNC_sk_fullsock: return &bpf_sk_fullsock_proto; case BPF_FUNC_sk_storage_get: return &bpf_sk_storage_get_proto; case BPF_FUNC_sk_storage_delete: return &bpf_sk_storage_delete_proto; #ifdef CONFIG_INET case BPF_FUNC_tcp_sock: return &bpf_tcp_sock_proto; case BPF_FUNC_get_listener_sock: return &bpf_get_listener_sock_proto; case BPF_FUNC_skb_ecn_set_ce: return &bpf_skb_ecn_set_ce_proto; #endif default: return sk_filter_func_proto(func_id, prog); } } static const struct bpf_func_proto * tc_cls_act_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog) { switch (func_id) { case BPF_FUNC_skb_store_bytes: return &bpf_skb_store_bytes_proto; case BPF_FUNC_skb_load_bytes: return &bpf_skb_load_bytes_proto; case BPF_FUNC_skb_load_bytes_relative: return &bpf_skb_load_bytes_relative_proto; case BPF_FUNC_skb_pull_data: return &bpf_skb_pull_data_proto; case BPF_FUNC_csum_diff: return &bpf_csum_diff_proto; case BPF_FUNC_csum_update: return &bpf_csum_update_proto; case BPF_FUNC_l3_csum_replace: return &bpf_l3_csum_replace_proto; case BPF_FUNC_l4_csum_replace: return &bpf_l4_csum_replace_proto; case BPF_FUNC_clone_redirect: return &bpf_clone_redirect_proto; case BPF_FUNC_get_cgroup_classid: return &bpf_get_cgroup_classid_proto; case BPF_FUNC_skb_vlan_push: return &bpf_skb_vlan_push_proto; case BPF_FUNC_skb_vlan_pop: return &bpf_skb_vlan_pop_proto; case BPF_FUNC_skb_change_proto: return &bpf_skb_change_proto_proto; case BPF_FUNC_skb_change_type: return &bpf_skb_change_type_proto; case BPF_FUNC_skb_adjust_room: return &bpf_skb_adjust_room_proto; case BPF_FUNC_skb_change_tail: return &bpf_skb_change_tail_proto; case BPF_FUNC_skb_get_tunnel_key: return &bpf_skb_get_tunnel_key_proto; case BPF_FUNC_skb_set_tunnel_key: return bpf_get_skb_set_tunnel_proto(func_id); case BPF_FUNC_skb_get_tunnel_opt: return &bpf_skb_get_tunnel_opt_proto; case BPF_FUNC_skb_set_tunnel_opt: return bpf_get_skb_set_tunnel_proto(func_id); case BPF_FUNC_redirect: return &bpf_redirect_proto; case BPF_FUNC_get_route_realm: return &bpf_get_route_realm_proto; case BPF_FUNC_get_hash_recalc: return &bpf_get_hash_recalc_proto; case BPF_FUNC_set_hash_invalid: return &bpf_set_hash_invalid_proto; case BPF_FUNC_set_hash: return &bpf_set_hash_proto; case BPF_FUNC_perf_event_output: return &bpf_skb_event_output_proto; case BPF_FUNC_get_smp_processor_id: return &bpf_get_smp_processor_id_proto; case BPF_FUNC_skb_under_cgroup: return &bpf_skb_under_cgroup_proto; case BPF_FUNC_get_socket_cookie: return &bpf_get_socket_cookie_proto; case BPF_FUNC_get_socket_uid: return &bpf_get_socket_uid_proto; case BPF_FUNC_fib_lookup: return &bpf_skb_fib_lookup_proto; case BPF_FUNC_sk_fullsock: return &bpf_sk_fullsock_proto; case BPF_FUNC_sk_storage_get: return &bpf_sk_storage_get_proto; case BPF_FUNC_sk_storage_delete: return &bpf_sk_storage_delete_proto; #ifdef CONFIG_XFRM case BPF_FUNC_skb_get_xfrm_state: return &bpf_skb_get_xfrm_state_proto; #endif #ifdef CONFIG_SOCK_CGROUP_DATA case BPF_FUNC_skb_cgroup_id: return &bpf_skb_cgroup_id_proto; case BPF_FUNC_skb_ancestor_cgroup_id: return &bpf_skb_ancestor_cgroup_id_proto; #endif #ifdef CONFIG_INET case BPF_FUNC_sk_lookup_tcp: return &bpf_sk_lookup_tcp_proto; case BPF_FUNC_sk_lookup_udp: return &bpf_sk_lookup_udp_proto; case BPF_FUNC_sk_release: return &bpf_sk_release_proto; case BPF_FUNC_tcp_sock: return &bpf_tcp_sock_proto; case BPF_FUNC_get_listener_sock: return &bpf_get_listener_sock_proto; case BPF_FUNC_skc_lookup_tcp: return &bpf_skc_lookup_tcp_proto; case BPF_FUNC_tcp_check_syncookie: return &bpf_tcp_check_syncookie_proto; case BPF_FUNC_skb_ecn_set_ce: return &bpf_skb_ecn_set_ce_proto; #endif default: return bpf_base_func_proto(func_id); } } static const struct bpf_func_proto * xdp_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog) { switch (func_id) { case BPF_FUNC_perf_event_output: return &bpf_xdp_event_output_proto; case BPF_FUNC_get_smp_processor_id: return &bpf_get_smp_processor_id_proto; case BPF_FUNC_csum_diff: return &bpf_csum_diff_proto; case BPF_FUNC_xdp_adjust_head: return &bpf_xdp_adjust_head_proto; case BPF_FUNC_xdp_adjust_meta: return &bpf_xdp_adjust_meta_proto; case BPF_FUNC_redirect: return &bpf_xdp_redirect_proto; case BPF_FUNC_redirect_map: return &bpf_xdp_redirect_map_proto; case BPF_FUNC_xdp_adjust_tail: return &bpf_xdp_adjust_tail_proto; case BPF_FUNC_fib_lookup: return &bpf_xdp_fib_lookup_proto; #ifdef CONFIG_INET case BPF_FUNC_sk_lookup_udp: return &bpf_xdp_sk_lookup_udp_proto; case BPF_FUNC_sk_lookup_tcp: return &bpf_xdp_sk_lookup_tcp_proto; case BPF_FUNC_sk_release: return &bpf_sk_release_proto; case BPF_FUNC_skc_lookup_tcp: return &bpf_xdp_skc_lookup_tcp_proto; case BPF_FUNC_tcp_check_syncookie: return &bpf_tcp_check_syncookie_proto; #endif default: return bpf_base_func_proto(func_id); } } const struct bpf_func_proto bpf_sock_map_update_proto __weak; const struct bpf_func_proto bpf_sock_hash_update_proto __weak; static const struct bpf_func_proto * sock_ops_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog) { switch (func_id) { case BPF_FUNC_setsockopt: return &bpf_setsockopt_proto; case BPF_FUNC_getsockopt: return &bpf_getsockopt_proto; case BPF_FUNC_sock_ops_cb_flags_set: return &bpf_sock_ops_cb_flags_set_proto; case BPF_FUNC_sock_map_update: return &bpf_sock_map_update_proto; case BPF_FUNC_sock_hash_update: return &bpf_sock_hash_update_proto; case BPF_FUNC_get_socket_cookie: return &bpf_get_socket_cookie_sock_ops_proto; case BPF_FUNC_get_local_storage: return &bpf_get_local_storage_proto; case BPF_FUNC_perf_event_output: return &bpf_sockopt_event_output_proto; default: return bpf_base_func_proto(func_id); } } const struct bpf_func_proto bpf_msg_redirect_map_proto __weak; const struct bpf_func_proto bpf_msg_redirect_hash_proto __weak; static const struct bpf_func_proto * sk_msg_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog) { switch (func_id) { case BPF_FUNC_msg_redirect_map: return &bpf_msg_redirect_map_proto; case BPF_FUNC_msg_redirect_hash: return &bpf_msg_redirect_hash_proto; case BPF_FUNC_msg_apply_bytes: return &bpf_msg_apply_bytes_proto; case BPF_FUNC_msg_cork_bytes: return &bpf_msg_cork_bytes_proto; case BPF_FUNC_msg_pull_data: return &bpf_msg_pull_data_proto; case BPF_FUNC_msg_push_data: return &bpf_msg_push_data_proto; case BPF_FUNC_msg_pop_data: return &bpf_msg_pop_data_proto; default: return bpf_base_func_proto(func_id); } } const struct bpf_func_proto bpf_sk_redirect_map_proto __weak; const struct bpf_func_proto bpf_sk_redirect_hash_proto __weak; static const struct bpf_func_proto * sk_skb_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog) { switch (func_id) { case BPF_FUNC_skb_store_bytes: return &bpf_skb_store_bytes_proto; case BPF_FUNC_skb_load_bytes: return &bpf_skb_load_bytes_proto; case BPF_FUNC_skb_pull_data: return &sk_skb_pull_data_proto; case BPF_FUNC_skb_change_tail: return &sk_skb_change_tail_proto; case BPF_FUNC_skb_change_head: return &sk_skb_change_head_proto; case BPF_FUNC_get_socket_cookie: return &bpf_get_socket_cookie_proto; case BPF_FUNC_get_socket_uid: return &bpf_get_socket_uid_proto; case BPF_FUNC_sk_redirect_map: return &bpf_sk_redirect_map_proto; case BPF_FUNC_sk_redirect_hash: return &bpf_sk_redirect_hash_proto; #ifdef CONFIG_INET case BPF_FUNC_sk_lookup_tcp: return &bpf_sk_lookup_tcp_proto; case BPF_FUNC_sk_lookup_udp: return &bpf_sk_lookup_udp_proto; case BPF_FUNC_sk_release: return &bpf_sk_release_proto; case BPF_FUNC_skc_lookup_tcp: return &bpf_skc_lookup_tcp_proto; #endif default: return bpf_base_func_proto(func_id); } } static const struct bpf_func_proto * flow_dissector_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog) { switch (func_id) { case BPF_FUNC_skb_load_bytes: return &bpf_flow_dissector_load_bytes_proto; default: return bpf_base_func_proto(func_id); } } static const struct bpf_func_proto * lwt_out_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog) { switch (func_id) { case BPF_FUNC_skb_load_bytes: return &bpf_skb_load_bytes_proto; case BPF_FUNC_skb_pull_data: return &bpf_skb_pull_data_proto; case BPF_FUNC_csum_diff: return &bpf_csum_diff_proto; case BPF_FUNC_get_cgroup_classid: return &bpf_get_cgroup_classid_proto; case BPF_FUNC_get_route_realm: return &bpf_get_route_realm_proto; case BPF_FUNC_get_hash_recalc: return &bpf_get_hash_recalc_proto; case BPF_FUNC_perf_event_output: return &bpf_skb_event_output_proto; case BPF_FUNC_get_smp_processor_id: return &bpf_get_smp_processor_id_proto; case BPF_FUNC_skb_under_cgroup: return &bpf_skb_under_cgroup_proto; default: return bpf_base_func_proto(func_id); } } static const struct bpf_func_proto * lwt_in_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog) { switch (func_id) { case BPF_FUNC_lwt_push_encap: return &bpf_lwt_in_push_encap_proto; default: return lwt_out_func_proto(func_id, prog); } } static const struct bpf_func_proto * lwt_xmit_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog) { switch (func_id) { case BPF_FUNC_skb_get_tunnel_key: return &bpf_skb_get_tunnel_key_proto; case BPF_FUNC_skb_set_tunnel_key: return bpf_get_skb_set_tunnel_proto(func_id); case BPF_FUNC_skb_get_tunnel_opt: return &bpf_skb_get_tunnel_opt_proto; case BPF_FUNC_skb_set_tunnel_opt: return bpf_get_skb_set_tunnel_proto(func_id); case BPF_FUNC_redirect: return &bpf_redirect_proto; case BPF_FUNC_clone_redirect: return &bpf_clone_redirect_proto; case BPF_FUNC_skb_change_tail: return &bpf_skb_change_tail_proto; case BPF_FUNC_skb_change_head: return &bpf_skb_change_head_proto; case BPF_FUNC_skb_store_bytes: return &bpf_skb_store_bytes_proto; case BPF_FUNC_csum_update: return &bpf_csum_update_proto; case BPF_FUNC_l3_csum_replace: return &bpf_l3_csum_replace_proto; case BPF_FUNC_l4_csum_replace: return &bpf_l4_csum_replace_proto; case BPF_FUNC_set_hash_invalid: return &bpf_set_hash_invalid_proto; case BPF_FUNC_lwt_push_encap: return &bpf_lwt_xmit_push_encap_proto; default: return lwt_out_func_proto(func_id, prog); } } static const struct bpf_func_proto * lwt_seg6local_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog) { switch (func_id) { #if IS_ENABLED(CONFIG_IPV6_SEG6_BPF) case BPF_FUNC_lwt_seg6_store_bytes: return &bpf_lwt_seg6_store_bytes_proto; case BPF_FUNC_lwt_seg6_action: return &bpf_lwt_seg6_action_proto; case BPF_FUNC_lwt_seg6_adjust_srh: return &bpf_lwt_seg6_adjust_srh_proto; #endif default: return lwt_out_func_proto(func_id, prog); } } static bool bpf_skb_is_valid_access(int off, int size, enum bpf_access_type type, const struct bpf_prog *prog, struct bpf_insn_access_aux *info) { const int size_default = sizeof(__u32); if (off < 0 || off >= sizeof(struct __sk_buff)) return false; /* The verifier guarantees that size > 0. */ if (off % size != 0) return false; switch (off) { case bpf_ctx_range_till(struct __sk_buff, cb[0], cb[4]): if (off + size > offsetofend(struct __sk_buff, cb[4])) return false; break; case bpf_ctx_range_till(struct __sk_buff, remote_ip6[0], remote_ip6[3]): case bpf_ctx_range_till(struct __sk_buff, local_ip6[0], local_ip6[3]): case bpf_ctx_range_till(struct __sk_buff, remote_ip4, remote_ip4): case bpf_ctx_range_till(struct __sk_buff, local_ip4, local_ip4): case bpf_ctx_range(struct __sk_buff, data): case bpf_ctx_range(struct __sk_buff, data_meta): case bpf_ctx_range(struct __sk_buff, data_end): if (size != size_default) return false; break; case bpf_ctx_range_ptr(struct __sk_buff, flow_keys): return false; case bpf_ctx_range(struct __sk_buff, tstamp): if (size != sizeof(__u64)) return false; break; case offsetof(struct __sk_buff, sk): if (type == BPF_WRITE || size != sizeof(__u64)) return false; info->reg_type = PTR_TO_SOCK_COMMON_OR_NULL; break; default: /* Only narrow read access allowed for now. */ if (type == BPF_WRITE) { if (size != size_default) return false; } else { bpf_ctx_record_field_size(info, size_default); if (!bpf_ctx_narrow_access_ok(off, size, size_default)) return false; } } return true; } static bool sk_filter_is_valid_access(int off, int size, enum bpf_access_type type, const struct bpf_prog *prog, struct bpf_insn_access_aux *info) { switch (off) { case bpf_ctx_range(struct __sk_buff, tc_classid): case bpf_ctx_range(struct __sk_buff, data): case bpf_ctx_range(struct __sk_buff, data_meta): case bpf_ctx_range(struct __sk_buff, data_end): case bpf_ctx_range_till(struct __sk_buff, family, local_port): case bpf_ctx_range(struct __sk_buff, tstamp): case bpf_ctx_range(struct __sk_buff, wire_len): return false; } if (type == BPF_WRITE) { switch (off) { case bpf_ctx_range_till(struct __sk_buff, cb[0], cb[4]): break; default: return false; } } return bpf_skb_is_valid_access(off, size, type, prog, info); } static bool cg_skb_is_valid_access(int off, int size, enum bpf_access_type type, const struct bpf_prog *prog, struct bpf_insn_access_aux *info) { switch (off) { case bpf_ctx_range(struct __sk_buff, tc_classid): case bpf_ctx_range(struct __sk_buff, data_meta): case bpf_ctx_range(struct __sk_buff, wire_len): return false; case bpf_ctx_range(struct __sk_buff, data): case bpf_ctx_range(struct __sk_buff, data_end): if (!capable(CAP_SYS_ADMIN)) return false; break; } if (type == BPF_WRITE) { switch (off) { case bpf_ctx_range(struct __sk_buff, mark): case bpf_ctx_range(struct __sk_buff, priority): case bpf_ctx_range_till(struct __sk_buff, cb[0], cb[4]): break; case bpf_ctx_range(struct __sk_buff, tstamp): if (!capable(CAP_SYS_ADMIN)) return false; break; default: return false; } } switch (off) { case bpf_ctx_range(struct __sk_buff, data): info->reg_type = PTR_TO_PACKET; break; case bpf_ctx_range(struct __sk_buff, data_end): info->reg_type = PTR_TO_PACKET_END; break; } return bpf_skb_is_valid_access(off, size, type, prog, info); } static bool lwt_is_valid_access(int off, int size, enum bpf_access_type type, const struct bpf_prog *prog, struct bpf_insn_access_aux *info) { switch (off) { case bpf_ctx_range(struct __sk_buff, tc_classid): case bpf_ctx_range_till(struct __sk_buff, family, local_port): case bpf_ctx_range(struct __sk_buff, data_meta): case bpf_ctx_range(struct __sk_buff, tstamp): case bpf_ctx_range(struct __sk_buff, wire_len): return false; } if (type == BPF_WRITE) { switch (off) { case bpf_ctx_range(struct __sk_buff, mark): case bpf_ctx_range(struct __sk_buff, priority): case bpf_ctx_range_till(struct __sk_buff, cb[0], cb[4]): break; default: return false; } } switch (off) { case bpf_ctx_range(struct __sk_buff, data): info->reg_type = PTR_TO_PACKET; break; case bpf_ctx_range(struct __sk_buff, data_end): info->reg_type = PTR_TO_PACKET_END; break; } return bpf_skb_is_valid_access(off, size, type, prog, info); } /* Attach type specific accesses */ static bool __sock_filter_check_attach_type(int off, enum bpf_access_type access_type, enum bpf_attach_type attach_type) { switch (off) { case offsetof(struct bpf_sock, bound_dev_if): case offsetof(struct bpf_sock, mark): case offsetof(struct bpf_sock, priority): switch (attach_type) { case BPF_CGROUP_INET_SOCK_CREATE: goto full_access; default: return false; } case bpf_ctx_range(struct bpf_sock, src_ip4): switch (attach_type) { case BPF_CGROUP_INET4_POST_BIND: goto read_only; default: return false; } case bpf_ctx_range_till(struct bpf_sock, src_ip6[0], src_ip6[3]): switch (attach_type) { case BPF_CGROUP_INET6_POST_BIND: goto read_only; default: return false; } case bpf_ctx_range(struct bpf_sock, src_port): switch (attach_type) { case BPF_CGROUP_INET4_POST_BIND: case BPF_CGROUP_INET6_POST_BIND: goto read_only; default: return false; } } read_only: return access_type == BPF_READ; full_access: return true; } bool bpf_sock_common_is_valid_access(int off, int size, enum bpf_access_type type, struct bpf_insn_access_aux *info) { switch (off) { case bpf_ctx_range_till(struct bpf_sock, type, priority): return false; default: return bpf_sock_is_valid_access(off, size, type, info); } } bool bpf_sock_is_valid_access(int off, int size, enum bpf_access_type type, struct bpf_insn_access_aux *info) { const int size_default = sizeof(__u32); if (off < 0 || off >= sizeof(struct bpf_sock)) return false; if (off % size != 0) return false; switch (off) { case offsetof(struct bpf_sock, state): case offsetof(struct bpf_sock, family): case offsetof(struct bpf_sock, type): case offsetof(struct bpf_sock, protocol): case offsetof(struct bpf_sock, dst_port): case offsetof(struct bpf_sock, src_port): case bpf_ctx_range(struct bpf_sock, src_ip4): case bpf_ctx_range_till(struct bpf_sock, src_ip6[0], src_ip6[3]): case bpf_ctx_range(struct bpf_sock, dst_ip4): case bpf_ctx_range_till(struct bpf_sock, dst_ip6[0], dst_ip6[3]): bpf_ctx_record_field_size(info, size_default); return bpf_ctx_narrow_access_ok(off, size, size_default); } return size == size_default; } static bool sock_filter_is_valid_access(int off, int size, enum bpf_access_type type, const struct bpf_prog *prog, struct bpf_insn_access_aux *info) { if (!bpf_sock_is_valid_access(off, size, type, info)) return false; return __sock_filter_check_attach_type(off, type, prog->expected_attach_type); } static int bpf_noop_prologue(struct bpf_insn *insn_buf, bool direct_write, const struct bpf_prog *prog) { /* Neither direct read nor direct write requires any preliminary * action. */ return 0; } static int bpf_unclone_prologue(struct bpf_insn *insn_buf, bool direct_write, const struct bpf_prog *prog, int drop_verdict) { struct bpf_insn *insn = insn_buf; if (!direct_write) return 0; /* if (!skb->cloned) * goto start; * * (Fast-path, otherwise approximation that we might be * a clone, do the rest in helper.) */ *insn++ = BPF_LDX_MEM(BPF_B, BPF_REG_6, BPF_REG_1, CLONED_OFFSET()); *insn++ = BPF_ALU32_IMM(BPF_AND, BPF_REG_6, CLONED_MASK); *insn++ = BPF_JMP_IMM(BPF_JEQ, BPF_REG_6, 0, 7); /* ret = bpf_skb_pull_data(skb, 0); */ *insn++ = BPF_MOV64_REG(BPF_REG_6, BPF_REG_1); *insn++ = BPF_ALU64_REG(BPF_XOR, BPF_REG_2, BPF_REG_2); *insn++ = BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_skb_pull_data); /* if (!ret) * goto restore; * return TC_ACT_SHOT; */ *insn++ = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 2); *insn++ = BPF_ALU32_IMM(BPF_MOV, BPF_REG_0, drop_verdict); *insn++ = BPF_EXIT_INSN(); /* restore: */ *insn++ = BPF_MOV64_REG(BPF_REG_1, BPF_REG_6); /* start: */ *insn++ = prog->insnsi[0]; return insn - insn_buf; } static int bpf_gen_ld_abs(const struct bpf_insn *orig, struct bpf_insn *insn_buf) { bool indirect = BPF_MODE(orig->code) == BPF_IND; struct bpf_insn *insn = insn_buf; /* We're guaranteed here that CTX is in R6. */ *insn++ = BPF_MOV64_REG(BPF_REG_1, BPF_REG_CTX); if (!indirect) { *insn++ = BPF_MOV64_IMM(BPF_REG_2, orig->imm); } else { *insn++ = BPF_MOV64_REG(BPF_REG_2, orig->src_reg); if (orig->imm) *insn++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, orig->imm); } switch (BPF_SIZE(orig->code)) { case BPF_B: *insn++ = BPF_EMIT_CALL(bpf_skb_load_helper_8_no_cache); break; case BPF_H: *insn++ = BPF_EMIT_CALL(bpf_skb_load_helper_16_no_cache); break; case BPF_W: *insn++ = BPF_EMIT_CALL(bpf_skb_load_helper_32_no_cache); break; } *insn++ = BPF_JMP_IMM(BPF_JSGE, BPF_REG_0, 0, 2); *insn++ = BPF_ALU32_REG(BPF_XOR, BPF_REG_0, BPF_REG_0); *insn++ = BPF_EXIT_INSN(); return insn - insn_buf; } static int tc_cls_act_prologue(struct bpf_insn *insn_buf, bool direct_write, const struct bpf_prog *prog) { return bpf_unclone_prologue(insn_buf, direct_write, prog, TC_ACT_SHOT); } static bool tc_cls_act_is_valid_access(int off, int size, enum bpf_access_type type, const struct bpf_prog *prog, struct bpf_insn_access_aux *info) { if (type == BPF_WRITE) { switch (off) { case bpf_ctx_range(struct __sk_buff, mark): case bpf_ctx_range(struct __sk_buff, tc_index): case bpf_ctx_range(struct __sk_buff, priority): case bpf_ctx_range(struct __sk_buff, tc_classid): case bpf_ctx_range_till(struct __sk_buff, cb[0], cb[4]): case bpf_ctx_range(struct __sk_buff, tstamp): case bpf_ctx_range(struct __sk_buff, queue_mapping): break; default: return false; } } switch (off) { case bpf_ctx_range(struct __sk_buff, data): info->reg_type = PTR_TO_PACKET; break; case bpf_ctx_range(struct __sk_buff, data_meta): info->reg_type = PTR_TO_PACKET_META; break; case bpf_ctx_range(struct __sk_buff, data_end): info->reg_type = PTR_TO_PACKET_END; break; case bpf_ctx_range_till(struct __sk_buff, family, local_port): return false; } return bpf_skb_is_valid_access(off, size, type, prog, info); } static bool __is_valid_xdp_access(int off, int size) { if (off < 0 || off >= sizeof(struct xdp_md)) return false; if (off % size != 0) return false; if (size != sizeof(__u32)) return false; return true; } static bool xdp_is_valid_access(int off, int size, enum bpf_access_type type, const struct bpf_prog *prog, struct bpf_insn_access_aux *info) { if (type == BPF_WRITE) { if (bpf_prog_is_dev_bound(prog->aux)) { switch (off) { case offsetof(struct xdp_md, rx_queue_index): return __is_valid_xdp_access(off, size); } } return false; } switch (off) { case offsetof(struct xdp_md, data): info->reg_type = PTR_TO_PACKET; break; case offsetof(struct xdp_md, data_meta): info->reg_type = PTR_TO_PACKET_META; break; case offsetof(struct xdp_md, data_end): info->reg_type = PTR_TO_PACKET_END; break; } return __is_valid_xdp_access(off, size); } void bpf_warn_invalid_xdp_action(u32 act) { const u32 act_max = XDP_REDIRECT; WARN_ONCE(1, "%s XDP return value %u, expect packet loss!\n", act > act_max ? "Illegal" : "Driver unsupported", act); } EXPORT_SYMBOL_GPL(bpf_warn_invalid_xdp_action); static bool sock_addr_is_valid_access(int off, int size, enum bpf_access_type type, const struct bpf_prog *prog, struct bpf_insn_access_aux *info) { const int size_default = sizeof(__u32); if (off < 0 || off >= sizeof(struct bpf_sock_addr)) return false; if (off % size != 0) return false; /* Disallow access to IPv6 fields from IPv4 contex and vise * versa. */ switch (off) { case bpf_ctx_range(struct bpf_sock_addr, user_ip4): switch (prog->expected_attach_type) { case BPF_CGROUP_INET4_BIND: case BPF_CGROUP_INET4_CONNECT: case BPF_CGROUP_UDP4_SENDMSG: case BPF_CGROUP_UDP4_RECVMSG: break; default: return false; } break; case bpf_ctx_range_till(struct bpf_sock_addr, user_ip6[0], user_ip6[3]): switch (prog->expected_attach_type) { case BPF_CGROUP_INET6_BIND: case BPF_CGROUP_INET6_CONNECT: case BPF_CGROUP_UDP6_SENDMSG: case BPF_CGROUP_UDP6_RECVMSG: break; default: return false; } break; case bpf_ctx_range(struct bpf_sock_addr, msg_src_ip4): switch (prog->expected_attach_type) { case BPF_CGROUP_UDP4_SENDMSG: break; default: return false; } break; case bpf_ctx_range_till(struct bpf_sock_addr, msg_src_ip6[0], msg_src_ip6[3]): switch (prog->expected_attach_type) { case BPF_CGROUP_UDP6_SENDMSG: break; default: return false; } break; } switch (off) { case bpf_ctx_range(struct bpf_sock_addr, user_ip4): case bpf_ctx_range_till(struct bpf_sock_addr, user_ip6[0], user_ip6[3]): case bpf_ctx_range(struct bpf_sock_addr, msg_src_ip4): case bpf_ctx_range_till(struct bpf_sock_addr, msg_src_ip6[0], msg_src_ip6[3]): /* Only narrow read access allowed for now. */ if (type == BPF_READ) { bpf_ctx_record_field_size(info, size_default); if (!bpf_ctx_narrow_access_ok(off, size, size_default)) return false; } else { if (size != size_default) return false; } break; case bpf_ctx_range(struct bpf_sock_addr, user_port): if (size != size_default) return false; break; default: if (type == BPF_READ) { if (size != size_default) return false; } else { return false; } } return true; } static bool sock_ops_is_valid_access(int off, int size, enum bpf_access_type type, const struct bpf_prog *prog, struct bpf_insn_access_aux *info) { const int size_default = sizeof(__u32); if (off < 0 || off >= sizeof(struct bpf_sock_ops)) return false; /* The verifier guarantees that size > 0. */ if (off % size != 0) return false; if (type == BPF_WRITE) { switch (off) { case offsetof(struct bpf_sock_ops, reply): case offsetof(struct bpf_sock_ops, sk_txhash): if (size != size_default) return false; break; default: return false; } } else { switch (off) { case bpf_ctx_range_till(struct bpf_sock_ops, bytes_received, bytes_acked): if (size != sizeof(__u64)) return false; break; default: if (size != size_default) return false; break; } } return true; } static int sk_skb_prologue(struct bpf_insn *insn_buf, bool direct_write, const struct bpf_prog *prog) { return bpf_unclone_prologue(insn_buf, direct_write, prog, SK_DROP); } static bool sk_skb_is_valid_access(int off, int size, enum bpf_access_type type, const struct bpf_prog *prog, struct bpf_insn_access_aux *info) { switch (off) { case bpf_ctx_range(struct __sk_buff, tc_classid): case bpf_ctx_range(struct __sk_buff, data_meta): case bpf_ctx_range(struct __sk_buff, tstamp): case bpf_ctx_range(struct __sk_buff, wire_len): return false; } if (type == BPF_WRITE) { switch (off) { case bpf_ctx_range(struct __sk_buff, tc_index): case bpf_ctx_range(struct __sk_buff, priority): break; default: return false; } } switch (off) { case bpf_ctx_range(struct __sk_buff, mark): return false; case bpf_ctx_range(struct __sk_buff, data): info->reg_type = PTR_TO_PACKET; break; case bpf_ctx_range(struct __sk_buff, data_end): info->reg_type = PTR_TO_PACKET_END; break; } return bpf_skb_is_valid_access(off, size, type, prog, info); } static bool sk_msg_is_valid_access(int off, int size, enum bpf_access_type type, const struct bpf_prog *prog, struct bpf_insn_access_aux *info) { if (type == BPF_WRITE) return false; if (off % size != 0) return false; switch (off) { case offsetof(struct sk_msg_md, data): info->reg_type = PTR_TO_PACKET; if (size != sizeof(__u64)) return false; break; case offsetof(struct sk_msg_md, data_end): info->reg_type = PTR_TO_PACKET_END; if (size != sizeof(__u64)) return false; break; case bpf_ctx_range(struct sk_msg_md, family): case bpf_ctx_range(struct sk_msg_md, remote_ip4): case bpf_ctx_range(struct sk_msg_md, local_ip4): case bpf_ctx_range_till(struct sk_msg_md, remote_ip6[0], remote_ip6[3]): case bpf_ctx_range_till(struct sk_msg_md, local_ip6[0], local_ip6[3]): case bpf_ctx_range(struct sk_msg_md, remote_port): case bpf_ctx_range(struct sk_msg_md, local_port): case bpf_ctx_range(struct sk_msg_md, size): if (size != sizeof(__u32)) return false; break; default: return false; } return true; } static bool flow_dissector_is_valid_access(int off, int size, enum bpf_access_type type, const struct bpf_prog *prog, struct bpf_insn_access_aux *info) { const int size_default = sizeof(__u32); if (off < 0 || off >= sizeof(struct __sk_buff)) return false; if (type == BPF_WRITE) return false; switch (off) { case bpf_ctx_range(struct __sk_buff, data): if (size != size_default) return false; info->reg_type = PTR_TO_PACKET; return true; case bpf_ctx_range(struct __sk_buff, data_end): if (size != size_default) return false; info->reg_type = PTR_TO_PACKET_END; return true; case bpf_ctx_range_ptr(struct __sk_buff, flow_keys): if (size != sizeof(__u64)) return false; info->reg_type = PTR_TO_FLOW_KEYS; return true; default: return false; } } static u32 flow_dissector_convert_ctx_access(enum bpf_access_type type, const struct bpf_insn *si, struct bpf_insn *insn_buf, struct bpf_prog *prog, u32 *target_size) { struct bpf_insn *insn = insn_buf; switch (si->off) { case offsetof(struct __sk_buff, data): *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_flow_dissector, data), si->dst_reg, si->src_reg, offsetof(struct bpf_flow_dissector, data)); break; case offsetof(struct __sk_buff, data_end): *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_flow_dissector, data_end), si->dst_reg, si->src_reg, offsetof(struct bpf_flow_dissector, data_end)); break; case offsetof(struct __sk_buff, flow_keys): *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_flow_dissector, flow_keys), si->dst_reg, si->src_reg, offsetof(struct bpf_flow_dissector, flow_keys)); break; } return insn - insn_buf; } static u32 bpf_convert_ctx_access(enum bpf_access_type type, const struct bpf_insn *si, struct bpf_insn *insn_buf, struct bpf_prog *prog, u32 *target_size) { struct bpf_insn *insn = insn_buf; int off; switch (si->off) { case offsetof(struct __sk_buff, len): *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg, bpf_target_off(struct sk_buff, len, 4, target_size)); break; case offsetof(struct __sk_buff, protocol): *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg, bpf_target_off(struct sk_buff, protocol, 2, target_size)); break; case offsetof(struct __sk_buff, vlan_proto): *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg, bpf_target_off(struct sk_buff, vlan_proto, 2, target_size)); break; case offsetof(struct __sk_buff, priority): if (type == BPF_WRITE) *insn++ = BPF_STX_MEM(BPF_W, si->dst_reg, si->src_reg, bpf_target_off(struct sk_buff, priority, 4, target_size)); else *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg, bpf_target_off(struct sk_buff, priority, 4, target_size)); break; case offsetof(struct __sk_buff, ingress_ifindex): *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg, bpf_target_off(struct sk_buff, skb_iif, 4, target_size)); break; case offsetof(struct __sk_buff, ifindex): *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, dev), si->dst_reg, si->src_reg, offsetof(struct sk_buff, dev)); *insn++ = BPF_JMP_IMM(BPF_JEQ, si->dst_reg, 0, 1); *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg, bpf_target_off(struct net_device, ifindex, 4, target_size)); break; case offsetof(struct __sk_buff, hash): *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg, bpf_target_off(struct sk_buff, hash, 4, target_size)); break; case offsetof(struct __sk_buff, mark): if (type == BPF_WRITE) *insn++ = BPF_STX_MEM(BPF_W, si->dst_reg, si->src_reg, bpf_target_off(struct sk_buff, mark, 4, target_size)); else *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg, bpf_target_off(struct sk_buff, mark, 4, target_size)); break; case offsetof(struct __sk_buff, pkt_type): *target_size = 1; *insn++ = BPF_LDX_MEM(BPF_B, si->dst_reg, si->src_reg, PKT_TYPE_OFFSET()); *insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg, PKT_TYPE_MAX); #ifdef __BIG_ENDIAN_BITFIELD *insn++ = BPF_ALU32_IMM(BPF_RSH, si->dst_reg, 5); #endif break; case offsetof(struct __sk_buff, queue_mapping): if (type == BPF_WRITE) { *insn++ = BPF_JMP_IMM(BPF_JGE, si->src_reg, NO_QUEUE_MAPPING, 1); *insn++ = BPF_STX_MEM(BPF_H, si->dst_reg, si->src_reg, bpf_target_off(struct sk_buff, queue_mapping, 2, target_size)); } else { *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg, bpf_target_off(struct sk_buff, queue_mapping, 2, target_size)); } break; case offsetof(struct __sk_buff, vlan_present): *target_size = 1; *insn++ = BPF_LDX_MEM(BPF_B, si->dst_reg, si->src_reg, PKT_VLAN_PRESENT_OFFSET()); if (PKT_VLAN_PRESENT_BIT) *insn++ = BPF_ALU32_IMM(BPF_RSH, si->dst_reg, PKT_VLAN_PRESENT_BIT); if (PKT_VLAN_PRESENT_BIT < 7) *insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg, 1); break; case offsetof(struct __sk_buff, vlan_tci): *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg, bpf_target_off(struct sk_buff, vlan_tci, 2, target_size)); break; case offsetof(struct __sk_buff, cb[0]) ... offsetofend(struct __sk_buff, cb[4]) - 1: BUILD_BUG_ON(FIELD_SIZEOF(struct qdisc_skb_cb, data) < 20); BUILD_BUG_ON((offsetof(struct sk_buff, cb) + offsetof(struct qdisc_skb_cb, data)) % sizeof(__u64)); prog->cb_access = 1; off = si->off; off -= offsetof(struct __sk_buff, cb[0]); off += offsetof(struct sk_buff, cb); off += offsetof(struct qdisc_skb_cb, data); if (type == BPF_WRITE) *insn++ = BPF_STX_MEM(BPF_SIZE(si->code), si->dst_reg, si->src_reg, off); else *insn++ = BPF_LDX_MEM(BPF_SIZE(si->code), si->dst_reg, si->src_reg, off); break; case offsetof(struct __sk_buff, tc_classid): BUILD_BUG_ON(FIELD_SIZEOF(struct qdisc_skb_cb, tc_classid) != 2); off = si->off; off -= offsetof(struct __sk_buff, tc_classid); off += offsetof(struct sk_buff, cb); off += offsetof(struct qdisc_skb_cb, tc_classid); *target_size = 2; if (type == BPF_WRITE) *insn++ = BPF_STX_MEM(BPF_H, si->dst_reg, si->src_reg, off); else *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg, off); break; case offsetof(struct __sk_buff, data): *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, data), si->dst_reg, si->src_reg, offsetof(struct sk_buff, data)); break; case offsetof(struct __sk_buff, data_meta): off = si->off; off -= offsetof(struct __sk_buff, data_meta); off += offsetof(struct sk_buff, cb); off += offsetof(struct bpf_skb_data_end, data_meta); *insn++ = BPF_LDX_MEM(BPF_SIZEOF(void *), si->dst_reg, si->src_reg, off); break; case offsetof(struct __sk_buff, data_end): off = si->off; off -= offsetof(struct __sk_buff, data_end); off += offsetof(struct sk_buff, cb); off += offsetof(struct bpf_skb_data_end, data_end); *insn++ = BPF_LDX_MEM(BPF_SIZEOF(void *), si->dst_reg, si->src_reg, off); break; case offsetof(struct __sk_buff, tc_index): #ifdef CONFIG_NET_SCHED if (type == BPF_WRITE) *insn++ = BPF_STX_MEM(BPF_H, si->dst_reg, si->src_reg, bpf_target_off(struct sk_buff, tc_index, 2, target_size)); else *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg, bpf_target_off(struct sk_buff, tc_index, 2, target_size)); #else *target_size = 2; if (type == BPF_WRITE) *insn++ = BPF_MOV64_REG(si->dst_reg, si->dst_reg); else *insn++ = BPF_MOV64_IMM(si->dst_reg, 0); #endif break; case offsetof(struct __sk_buff, napi_id): #if defined(CONFIG_NET_RX_BUSY_POLL) *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg, bpf_target_off(struct sk_buff, napi_id, 4, target_size)); *insn++ = BPF_JMP_IMM(BPF_JGE, si->dst_reg, MIN_NAPI_ID, 1); *insn++ = BPF_MOV64_IMM(si->dst_reg, 0); #else *target_size = 4; *insn++ = BPF_MOV64_IMM(si->dst_reg, 0); #endif break; case offsetof(struct __sk_buff, family): BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_family) != 2); *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk), si->dst_reg, si->src_reg, offsetof(struct sk_buff, sk)); *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg, bpf_target_off(struct sock_common, skc_family, 2, target_size)); break; case offsetof(struct __sk_buff, remote_ip4): BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_daddr) != 4); *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk), si->dst_reg, si->src_reg, offsetof(struct sk_buff, sk)); *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg, bpf_target_off(struct sock_common, skc_daddr, 4, target_size)); break; case offsetof(struct __sk_buff, local_ip4): BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_rcv_saddr) != 4); *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk), si->dst_reg, si->src_reg, offsetof(struct sk_buff, sk)); *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg, bpf_target_off(struct sock_common, skc_rcv_saddr, 4, target_size)); break; case offsetof(struct __sk_buff, remote_ip6[0]) ... offsetof(struct __sk_buff, remote_ip6[3]): #if IS_ENABLED(CONFIG_IPV6) BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_v6_daddr.s6_addr32[0]) != 4); off = si->off; off -= offsetof(struct __sk_buff, remote_ip6[0]); *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk), si->dst_reg, si->src_reg, offsetof(struct sk_buff, sk)); *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg, offsetof(struct sock_common, skc_v6_daddr.s6_addr32[0]) + off); #else *insn++ = BPF_MOV32_IMM(si->dst_reg, 0); #endif break; case offsetof(struct __sk_buff, local_ip6[0]) ... offsetof(struct __sk_buff, local_ip6[3]): #if IS_ENABLED(CONFIG_IPV6) BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_v6_rcv_saddr.s6_addr32[0]) != 4); off = si->off; off -= offsetof(struct __sk_buff, local_ip6[0]); *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk), si->dst_reg, si->src_reg, offsetof(struct sk_buff, sk)); *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg, offsetof(struct sock_common, skc_v6_rcv_saddr.s6_addr32[0]) + off); #else *insn++ = BPF_MOV32_IMM(si->dst_reg, 0); #endif break; case offsetof(struct __sk_buff, remote_port): BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_dport) != 2); *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk), si->dst_reg, si->src_reg, offsetof(struct sk_buff, sk)); *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg, bpf_target_off(struct sock_common, skc_dport, 2, target_size)); #ifndef __BIG_ENDIAN_BITFIELD *insn++ = BPF_ALU32_IMM(BPF_LSH, si->dst_reg, 16); #endif break; case offsetof(struct __sk_buff, local_port): BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_num) != 2); *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk), si->dst_reg, si->src_reg, offsetof(struct sk_buff, sk)); *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg, bpf_target_off(struct sock_common, skc_num, 2, target_size)); break; case offsetof(struct __sk_buff, tstamp): BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, tstamp) != 8); if (type == BPF_WRITE) *insn++ = BPF_STX_MEM(BPF_DW, si->dst_reg, si->src_reg, bpf_target_off(struct sk_buff, tstamp, 8, target_size)); else *insn++ = BPF_LDX_MEM(BPF_DW, si->dst_reg, si->src_reg, bpf_target_off(struct sk_buff, tstamp, 8, target_size)); break; case offsetof(struct __sk_buff, gso_segs): /* si->dst_reg = skb_shinfo(SKB); */ #ifdef NET_SKBUFF_DATA_USES_OFFSET *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, head), si->dst_reg, si->src_reg, offsetof(struct sk_buff, head)); *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, end), BPF_REG_AX, si->src_reg, offsetof(struct sk_buff, end)); *insn++ = BPF_ALU64_REG(BPF_ADD, si->dst_reg, BPF_REG_AX); #else *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, end), si->dst_reg, si->src_reg, offsetof(struct sk_buff, end)); #endif *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct skb_shared_info, gso_segs), si->dst_reg, si->dst_reg, bpf_target_off(struct skb_shared_info, gso_segs, 2, target_size)); break; case offsetof(struct __sk_buff, wire_len): BUILD_BUG_ON(FIELD_SIZEOF(struct qdisc_skb_cb, pkt_len) != 4); off = si->off; off -= offsetof(struct __sk_buff, wire_len); off += offsetof(struct sk_buff, cb); off += offsetof(struct qdisc_skb_cb, pkt_len); *target_size = 4; *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg, off); break; case offsetof(struct __sk_buff, sk): *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk), si->dst_reg, si->src_reg, offsetof(struct sk_buff, sk)); break; } return insn - insn_buf; } u32 bpf_sock_convert_ctx_access(enum bpf_access_type type, const struct bpf_insn *si, struct bpf_insn *insn_buf, struct bpf_prog *prog, u32 *target_size) { struct bpf_insn *insn = insn_buf; int off; switch (si->off) { case offsetof(struct bpf_sock, bound_dev_if): BUILD_BUG_ON(FIELD_SIZEOF(struct sock, sk_bound_dev_if) != 4); if (type == BPF_WRITE) *insn++ = BPF_STX_MEM(BPF_W, si->dst_reg, si->src_reg, offsetof(struct sock, sk_bound_dev_if)); else *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg, offsetof(struct sock, sk_bound_dev_if)); break; case offsetof(struct bpf_sock, mark): BUILD_BUG_ON(FIELD_SIZEOF(struct sock, sk_mark) != 4); if (type == BPF_WRITE) *insn++ = BPF_STX_MEM(BPF_W, si->dst_reg, si->src_reg, offsetof(struct sock, sk_mark)); else *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg, offsetof(struct sock, sk_mark)); break; case offsetof(struct bpf_sock, priority): BUILD_BUG_ON(FIELD_SIZEOF(struct sock, sk_priority) != 4); if (type == BPF_WRITE) *insn++ = BPF_STX_MEM(BPF_W, si->dst_reg, si->src_reg, offsetof(struct sock, sk_priority)); else *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg, offsetof(struct sock, sk_priority)); break; case offsetof(struct bpf_sock, family): *insn++ = BPF_LDX_MEM( BPF_FIELD_SIZEOF(struct sock_common, skc_family), si->dst_reg, si->src_reg, bpf_target_off(struct sock_common, skc_family, FIELD_SIZEOF(struct sock_common, skc_family), target_size)); break; case offsetof(struct bpf_sock, type): BUILD_BUG_ON(HWEIGHT32(SK_FL_TYPE_MASK) != BITS_PER_BYTE * 2); *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg, offsetof(struct sock, __sk_flags_offset)); *insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg, SK_FL_TYPE_MASK); *insn++ = BPF_ALU32_IMM(BPF_RSH, si->dst_reg, SK_FL_TYPE_SHIFT); *target_size = 2; break; case offsetof(struct bpf_sock, protocol): BUILD_BUG_ON(HWEIGHT32(SK_FL_PROTO_MASK) != BITS_PER_BYTE); *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg, offsetof(struct sock, __sk_flags_offset)); *insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg, SK_FL_PROTO_MASK); *insn++ = BPF_ALU32_IMM(BPF_RSH, si->dst_reg, SK_FL_PROTO_SHIFT); *target_size = 1; break; case offsetof(struct bpf_sock, src_ip4): *insn++ = BPF_LDX_MEM( BPF_SIZE(si->code), si->dst_reg, si->src_reg, bpf_target_off(struct sock_common, skc_rcv_saddr, FIELD_SIZEOF(struct sock_common, skc_rcv_saddr), target_size)); break; case offsetof(struct bpf_sock, dst_ip4): *insn++ = BPF_LDX_MEM( BPF_SIZE(si->code), si->dst_reg, si->src_reg, bpf_target_off(struct sock_common, skc_daddr, FIELD_SIZEOF(struct sock_common, skc_daddr), target_size)); break; case bpf_ctx_range_till(struct bpf_sock, src_ip6[0], src_ip6[3]): #if IS_ENABLED(CONFIG_IPV6) off = si->off; off -= offsetof(struct bpf_sock, src_ip6[0]); *insn++ = BPF_LDX_MEM( BPF_SIZE(si->code), si->dst_reg, si->src_reg, bpf_target_off( struct sock_common, skc_v6_rcv_saddr.s6_addr32[0], FIELD_SIZEOF(struct sock_common, skc_v6_rcv_saddr.s6_addr32[0]), target_size) + off); #else (void)off; *insn++ = BPF_MOV32_IMM(si->dst_reg, 0); #endif break; case bpf_ctx_range_till(struct bpf_sock, dst_ip6[0], dst_ip6[3]): #if IS_ENABLED(CONFIG_IPV6) off = si->off; off -= offsetof(struct bpf_sock, dst_ip6[0]); *insn++ = BPF_LDX_MEM( BPF_SIZE(si->code), si->dst_reg, si->src_reg, bpf_target_off(struct sock_common, skc_v6_daddr.s6_addr32[0], FIELD_SIZEOF(struct sock_common, skc_v6_daddr.s6_addr32[0]), target_size) + off); #else *insn++ = BPF_MOV32_IMM(si->dst_reg, 0); *target_size = 4; #endif break; case offsetof(struct bpf_sock, src_port): *insn++ = BPF_LDX_MEM( BPF_FIELD_SIZEOF(struct sock_common, skc_num), si->dst_reg, si->src_reg, bpf_target_off(struct sock_common, skc_num, FIELD_SIZEOF(struct sock_common, skc_num), target_size)); break; case offsetof(struct bpf_sock, dst_port): *insn++ = BPF_LDX_MEM( BPF_FIELD_SIZEOF(struct sock_common, skc_dport), si->dst_reg, si->src_reg, bpf_target_off(struct sock_common, skc_dport, FIELD_SIZEOF(struct sock_common, skc_dport), target_size)); break; case offsetof(struct bpf_sock, state): *insn++ = BPF_LDX_MEM( BPF_FIELD_SIZEOF(struct sock_common, skc_state), si->dst_reg, si->src_reg, bpf_target_off(struct sock_common, skc_state, FIELD_SIZEOF(struct sock_common, skc_state), target_size)); break; } return insn - insn_buf; } static u32 tc_cls_act_convert_ctx_access(enum bpf_access_type type, const struct bpf_insn *si, struct bpf_insn *insn_buf, struct bpf_prog *prog, u32 *target_size) { struct bpf_insn *insn = insn_buf; switch (si->off) { case offsetof(struct __sk_buff, ifindex): *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, dev), si->dst_reg, si->src_reg, offsetof(struct sk_buff, dev)); *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg, bpf_target_off(struct net_device, ifindex, 4, target_size)); break; default: return bpf_convert_ctx_access(type, si, insn_buf, prog, target_size); } return insn - insn_buf; } static u32 xdp_convert_ctx_access(enum bpf_access_type type, const struct bpf_insn *si, struct bpf_insn *insn_buf, struct bpf_prog *prog, u32 *target_size) { struct bpf_insn *insn = insn_buf; switch (si->off) { case offsetof(struct xdp_md, data): *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_buff, data), si->dst_reg, si->src_reg, offsetof(struct xdp_buff, data)); break; case offsetof(struct xdp_md, data_meta): *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_buff, data_meta), si->dst_reg, si->src_reg, offsetof(struct xdp_buff, data_meta)); break; case offsetof(struct xdp_md, data_end): *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_buff, data_end), si->dst_reg, si->src_reg, offsetof(struct xdp_buff, data_end)); break; case offsetof(struct xdp_md, ingress_ifindex): *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_buff, rxq), si->dst_reg, si->src_reg, offsetof(struct xdp_buff, rxq)); *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_rxq_info, dev), si->dst_reg, si->dst_reg, offsetof(struct xdp_rxq_info, dev)); *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg, offsetof(struct net_device, ifindex)); break; case offsetof(struct xdp_md, rx_queue_index): *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_buff, rxq), si->dst_reg, si->src_reg, offsetof(struct xdp_buff, rxq)); *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg, offsetof(struct xdp_rxq_info, queue_index)); break; } return insn - insn_buf; } /* SOCK_ADDR_LOAD_NESTED_FIELD() loads Nested Field S.F.NF where S is type of * context Structure, F is Field in context structure that contains a pointer * to Nested Structure of type NS that has the field NF. * * SIZE encodes the load size (BPF_B, BPF_H, etc). It's up to caller to make * sure that SIZE is not greater than actual size of S.F.NF. * * If offset OFF is provided, the load happens from that offset relative to * offset of NF. */ #define SOCK_ADDR_LOAD_NESTED_FIELD_SIZE_OFF(S, NS, F, NF, SIZE, OFF) \ do { \ *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(S, F), si->dst_reg, \ si->src_reg, offsetof(S, F)); \ *insn++ = BPF_LDX_MEM( \ SIZE, si->dst_reg, si->dst_reg, \ bpf_target_off(NS, NF, FIELD_SIZEOF(NS, NF), \ target_size) \ + OFF); \ } while (0) #define SOCK_ADDR_LOAD_NESTED_FIELD(S, NS, F, NF) \ SOCK_ADDR_LOAD_NESTED_FIELD_SIZE_OFF(S, NS, F, NF, \ BPF_FIELD_SIZEOF(NS, NF), 0) /* SOCK_ADDR_STORE_NESTED_FIELD_OFF() has semantic similar to * SOCK_ADDR_LOAD_NESTED_FIELD_SIZE_OFF() but for store operation. * * It doesn't support SIZE argument though since narrow stores are not * supported for now. * * In addition it uses Temporary Field TF (member of struct S) as the 3rd * "register" since two registers available in convert_ctx_access are not * enough: we can't override neither SRC, since it contains value to store, nor * DST since it contains pointer to context that may be used by later * instructions. But we need a temporary place to save pointer to nested * structure whose field we want to store to. */ #define SOCK_ADDR_STORE_NESTED_FIELD_OFF(S, NS, F, NF, OFF, TF) \ do { \ int tmp_reg = BPF_REG_9; \ if (si->src_reg == tmp_reg || si->dst_reg == tmp_reg) \ --tmp_reg; \ if (si->src_reg == tmp_reg || si->dst_reg == tmp_reg) \ --tmp_reg; \ *insn++ = BPF_STX_MEM(BPF_DW, si->dst_reg, tmp_reg, \ offsetof(S, TF)); \ *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(S, F), tmp_reg, \ si->dst_reg, offsetof(S, F)); \ *insn++ = BPF_STX_MEM( \ BPF_FIELD_SIZEOF(NS, NF), tmp_reg, si->src_reg, \ bpf_target_off(NS, NF, FIELD_SIZEOF(NS, NF), \ target_size) \ + OFF); \ *insn++ = BPF_LDX_MEM(BPF_DW, tmp_reg, si->dst_reg, \ offsetof(S, TF)); \ } while (0) #define SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF(S, NS, F, NF, SIZE, OFF, \ TF) \ do { \ if (type == BPF_WRITE) { \ SOCK_ADDR_STORE_NESTED_FIELD_OFF(S, NS, F, NF, OFF, \ TF); \ } else { \ SOCK_ADDR_LOAD_NESTED_FIELD_SIZE_OFF( \ S, NS, F, NF, SIZE, OFF); \ } \ } while (0) #define SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD(S, NS, F, NF, TF) \ SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF( \ S, NS, F, NF, BPF_FIELD_SIZEOF(NS, NF), 0, TF) static u32 sock_addr_convert_ctx_access(enum bpf_access_type type, const struct bpf_insn *si, struct bpf_insn *insn_buf, struct bpf_prog *prog, u32 *target_size) { struct bpf_insn *insn = insn_buf; int off; switch (si->off) { case offsetof(struct bpf_sock_addr, user_family): SOCK_ADDR_LOAD_NESTED_FIELD(struct bpf_sock_addr_kern, struct sockaddr, uaddr, sa_family); break; case offsetof(struct bpf_sock_addr, user_ip4): SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF( struct bpf_sock_addr_kern, struct sockaddr_in, uaddr, sin_addr, BPF_SIZE(si->code), 0, tmp_reg); break; case bpf_ctx_range_till(struct bpf_sock_addr, user_ip6[0], user_ip6[3]): off = si->off; off -= offsetof(struct bpf_sock_addr, user_ip6[0]); SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF( struct bpf_sock_addr_kern, struct sockaddr_in6, uaddr, sin6_addr.s6_addr32[0], BPF_SIZE(si->code), off, tmp_reg); break; case offsetof(struct bpf_sock_addr, user_port): /* To get port we need to know sa_family first and then treat * sockaddr as either sockaddr_in or sockaddr_in6. * Though we can simplify since port field has same offset and * size in both structures. * Here we check this invariant and use just one of the * structures if it's true. */ BUILD_BUG_ON(offsetof(struct sockaddr_in, sin_port) != offsetof(struct sockaddr_in6, sin6_port)); BUILD_BUG_ON(FIELD_SIZEOF(struct sockaddr_in, sin_port) != FIELD_SIZEOF(struct sockaddr_in6, sin6_port)); SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD(struct bpf_sock_addr_kern, struct sockaddr_in6, uaddr, sin6_port, tmp_reg); break; case offsetof(struct bpf_sock_addr, family): SOCK_ADDR_LOAD_NESTED_FIELD(struct bpf_sock_addr_kern, struct sock, sk, sk_family); break; case offsetof(struct bpf_sock_addr, type): SOCK_ADDR_LOAD_NESTED_FIELD_SIZE_OFF( struct bpf_sock_addr_kern, struct sock, sk, __sk_flags_offset, BPF_W, 0); *insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg, SK_FL_TYPE_MASK); *insn++ = BPF_ALU32_IMM(BPF_RSH, si->dst_reg, SK_FL_TYPE_SHIFT); break; case offsetof(struct bpf_sock_addr, protocol): SOCK_ADDR_LOAD_NESTED_FIELD_SIZE_OFF( struct bpf_sock_addr_kern, struct sock, sk, __sk_flags_offset, BPF_W, 0); *insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg, SK_FL_PROTO_MASK); *insn++ = BPF_ALU32_IMM(BPF_RSH, si->dst_reg, SK_FL_PROTO_SHIFT); break; case offsetof(struct bpf_sock_addr, msg_src_ip4): /* Treat t_ctx as struct in_addr for msg_src_ip4. */ SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF( struct bpf_sock_addr_kern, struct in_addr, t_ctx, s_addr, BPF_SIZE(si->code), 0, tmp_reg); break; case bpf_ctx_range_till(struct bpf_sock_addr, msg_src_ip6[0], msg_src_ip6[3]): off = si->off; off -= offsetof(struct bpf_sock_addr, msg_src_ip6[0]); /* Treat t_ctx as struct in6_addr for msg_src_ip6. */ SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF( struct bpf_sock_addr_kern, struct in6_addr, t_ctx, s6_addr32[0], BPF_SIZE(si->code), off, tmp_reg); break; } return insn - insn_buf; } static u32 sock_ops_convert_ctx_access(enum bpf_access_type type, const struct bpf_insn *si, struct bpf_insn *insn_buf, struct bpf_prog *prog, u32 *target_size) { struct bpf_insn *insn = insn_buf; int off; /* Helper macro for adding read access to tcp_sock or sock fields. */ #define SOCK_OPS_GET_FIELD(BPF_FIELD, OBJ_FIELD, OBJ) \ do { \ BUILD_BUG_ON(FIELD_SIZEOF(OBJ, OBJ_FIELD) > \ FIELD_SIZEOF(struct bpf_sock_ops, BPF_FIELD)); \ *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF( \ struct bpf_sock_ops_kern, \ is_fullsock), \ si->dst_reg, si->src_reg, \ offsetof(struct bpf_sock_ops_kern, \ is_fullsock)); \ *insn++ = BPF_JMP_IMM(BPF_JEQ, si->dst_reg, 0, 2); \ *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF( \ struct bpf_sock_ops_kern, sk),\ si->dst_reg, si->src_reg, \ offsetof(struct bpf_sock_ops_kern, sk));\ *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(OBJ, \ OBJ_FIELD), \ si->dst_reg, si->dst_reg, \ offsetof(OBJ, OBJ_FIELD)); \ } while (0) #define SOCK_OPS_GET_TCP_SOCK_FIELD(FIELD) \ SOCK_OPS_GET_FIELD(FIELD, FIELD, struct tcp_sock) /* Helper macro for adding write access to tcp_sock or sock fields. * The macro is called with two registers, dst_reg which contains a pointer * to ctx (context) and src_reg which contains the value that should be * stored. However, we need an additional register since we cannot overwrite * dst_reg because it may be used later in the program. * Instead we "borrow" one of the other register. We first save its value * into a new (temp) field in bpf_sock_ops_kern, use it, and then restore * it at the end of the macro. */ #define SOCK_OPS_SET_FIELD(BPF_FIELD, OBJ_FIELD, OBJ) \ do { \ int reg = BPF_REG_9; \ BUILD_BUG_ON(FIELD_SIZEOF(OBJ, OBJ_FIELD) > \ FIELD_SIZEOF(struct bpf_sock_ops, BPF_FIELD)); \ if (si->dst_reg == reg || si->src_reg == reg) \ reg--; \ if (si->dst_reg == reg || si->src_reg == reg) \ reg--; \ *insn++ = BPF_STX_MEM(BPF_DW, si->dst_reg, reg, \ offsetof(struct bpf_sock_ops_kern, \ temp)); \ *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF( \ struct bpf_sock_ops_kern, \ is_fullsock), \ reg, si->dst_reg, \ offsetof(struct bpf_sock_ops_kern, \ is_fullsock)); \ *insn++ = BPF_JMP_IMM(BPF_JEQ, reg, 0, 2); \ *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF( \ struct bpf_sock_ops_kern, sk),\ reg, si->dst_reg, \ offsetof(struct bpf_sock_ops_kern, sk));\ *insn++ = BPF_STX_MEM(BPF_FIELD_SIZEOF(OBJ, OBJ_FIELD), \ reg, si->src_reg, \ offsetof(OBJ, OBJ_FIELD)); \ *insn++ = BPF_LDX_MEM(BPF_DW, reg, si->dst_reg, \ offsetof(struct bpf_sock_ops_kern, \ temp)); \ } while (0) #define SOCK_OPS_GET_OR_SET_FIELD(BPF_FIELD, OBJ_FIELD, OBJ, TYPE) \ do { \ if (TYPE == BPF_WRITE) \ SOCK_OPS_SET_FIELD(BPF_FIELD, OBJ_FIELD, OBJ); \ else \ SOCK_OPS_GET_FIELD(BPF_FIELD, OBJ_FIELD, OBJ); \ } while (0) CONVERT_COMMON_TCP_SOCK_FIELDS(struct bpf_sock_ops, SOCK_OPS_GET_TCP_SOCK_FIELD); if (insn > insn_buf) return insn - insn_buf; switch (si->off) { case offsetof(struct bpf_sock_ops, op) ... offsetof(struct bpf_sock_ops, replylong[3]): BUILD_BUG_ON(FIELD_SIZEOF(struct bpf_sock_ops, op) != FIELD_SIZEOF(struct bpf_sock_ops_kern, op)); BUILD_BUG_ON(FIELD_SIZEOF(struct bpf_sock_ops, reply) != FIELD_SIZEOF(struct bpf_sock_ops_kern, reply)); BUILD_BUG_ON(FIELD_SIZEOF(struct bpf_sock_ops, replylong) != FIELD_SIZEOF(struct bpf_sock_ops_kern, replylong)); off = si->off; off -= offsetof(struct bpf_sock_ops, op); off += offsetof(struct bpf_sock_ops_kern, op); if (type == BPF_WRITE) *insn++ = BPF_STX_MEM(BPF_W, si->dst_reg, si->src_reg, off); else *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg, off); break; case offsetof(struct bpf_sock_ops, family): BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_family) != 2); *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF( struct bpf_sock_ops_kern, sk), si->dst_reg, si->src_reg, offsetof(struct bpf_sock_ops_kern, sk)); *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg, offsetof(struct sock_common, skc_family)); break; case offsetof(struct bpf_sock_ops, remote_ip4): BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_daddr) != 4); *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF( struct bpf_sock_ops_kern, sk), si->dst_reg, si->src_reg, offsetof(struct bpf_sock_ops_kern, sk)); *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg, offsetof(struct sock_common, skc_daddr)); break; case offsetof(struct bpf_sock_ops, local_ip4): BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_rcv_saddr) != 4); *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF( struct bpf_sock_ops_kern, sk), si->dst_reg, si->src_reg, offsetof(struct bpf_sock_ops_kern, sk)); *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg, offsetof(struct sock_common, skc_rcv_saddr)); break; case offsetof(struct bpf_sock_ops, remote_ip6[0]) ... offsetof(struct bpf_sock_ops, remote_ip6[3]): #if IS_ENABLED(CONFIG_IPV6) BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_v6_daddr.s6_addr32[0]) != 4); off = si->off; off -= offsetof(struct bpf_sock_ops, remote_ip6[0]); *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF( struct bpf_sock_ops_kern, sk), si->dst_reg, si->src_reg, offsetof(struct bpf_sock_ops_kern, sk)); *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg, offsetof(struct sock_common, skc_v6_daddr.s6_addr32[0]) + off); #else *insn++ = BPF_MOV32_IMM(si->dst_reg, 0); #endif break; case offsetof(struct bpf_sock_ops, local_ip6[0]) ... offsetof(struct bpf_sock_ops, local_ip6[3]): #if IS_ENABLED(CONFIG_IPV6) BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_v6_rcv_saddr.s6_addr32[0]) != 4); off = si->off; off -= offsetof(struct bpf_sock_ops, local_ip6[0]); *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF( struct bpf_sock_ops_kern, sk), si->dst_reg, si->src_reg, offsetof(struct bpf_sock_ops_kern, sk)); *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg, offsetof(struct sock_common, skc_v6_rcv_saddr.s6_addr32[0]) + off); #else *insn++ = BPF_MOV32_IMM(si->dst_reg, 0); #endif break; case offsetof(struct bpf_sock_ops, remote_port): BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_dport) != 2); *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF( struct bpf_sock_ops_kern, sk), si->dst_reg, si->src_reg, offsetof(struct bpf_sock_ops_kern, sk)); *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg, offsetof(struct sock_common, skc_dport)); #ifndef __BIG_ENDIAN_BITFIELD *insn++ = BPF_ALU32_IMM(BPF_LSH, si->dst_reg, 16); #endif break; case offsetof(struct bpf_sock_ops, local_port): BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_num) != 2); *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF( struct bpf_sock_ops_kern, sk), si->dst_reg, si->src_reg, offsetof(struct bpf_sock_ops_kern, sk)); *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg, offsetof(struct sock_common, skc_num)); break; case offsetof(struct bpf_sock_ops, is_fullsock): *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF( struct bpf_sock_ops_kern, is_fullsock), si->dst_reg, si->src_reg, offsetof(struct bpf_sock_ops_kern, is_fullsock)); break; case offsetof(struct bpf_sock_ops, state): BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_state) != 1); *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF( struct bpf_sock_ops_kern, sk), si->dst_reg, si->src_reg, offsetof(struct bpf_sock_ops_kern, sk)); *insn++ = BPF_LDX_MEM(BPF_B, si->dst_reg, si->dst_reg, offsetof(struct sock_common, skc_state)); break; case offsetof(struct bpf_sock_ops, rtt_min): BUILD_BUG_ON(FIELD_SIZEOF(struct tcp_sock, rtt_min) != sizeof(struct minmax)); BUILD_BUG_ON(sizeof(struct minmax) < sizeof(struct minmax_sample)); *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF( struct bpf_sock_ops_kern, sk), si->dst_reg, si->src_reg, offsetof(struct bpf_sock_ops_kern, sk)); *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg, offsetof(struct tcp_sock, rtt_min) + FIELD_SIZEOF(struct minmax_sample, t)); break; case offsetof(struct bpf_sock_ops, bpf_sock_ops_cb_flags): SOCK_OPS_GET_FIELD(bpf_sock_ops_cb_flags, bpf_sock_ops_cb_flags, struct tcp_sock); break; case offsetof(struct bpf_sock_ops, sk_txhash): SOCK_OPS_GET_OR_SET_FIELD(sk_txhash, sk_txhash, struct sock, type); break; } return insn - insn_buf; } static u32 sk_skb_convert_ctx_access(enum bpf_access_type type, const struct bpf_insn *si, struct bpf_insn *insn_buf, struct bpf_prog *prog, u32 *target_size) { struct bpf_insn *insn = insn_buf; int off; switch (si->off) { case offsetof(struct __sk_buff, data_end): off = si->off; off -= offsetof(struct __sk_buff, data_end); off += offsetof(struct sk_buff, cb); off += offsetof(struct tcp_skb_cb, bpf.data_end); *insn++ = BPF_LDX_MEM(BPF_SIZEOF(void *), si->dst_reg, si->src_reg, off); break; default: return bpf_convert_ctx_access(type, si, insn_buf, prog, target_size); } return insn - insn_buf; } static u32 sk_msg_convert_ctx_access(enum bpf_access_type type, const struct bpf_insn *si, struct bpf_insn *insn_buf, struct bpf_prog *prog, u32 *target_size) { struct bpf_insn *insn = insn_buf; #if IS_ENABLED(CONFIG_IPV6) int off; #endif /* convert ctx uses the fact sg element is first in struct */ BUILD_BUG_ON(offsetof(struct sk_msg, sg) != 0); switch (si->off) { case offsetof(struct sk_msg_md, data): *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_msg, data), si->dst_reg, si->src_reg, offsetof(struct sk_msg, data)); break; case offsetof(struct sk_msg_md, data_end): *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_msg, data_end), si->dst_reg, si->src_reg, offsetof(struct sk_msg, data_end)); break; case offsetof(struct sk_msg_md, family): BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_family) != 2); *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF( struct sk_msg, sk), si->dst_reg, si->src_reg, offsetof(struct sk_msg, sk)); *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg, offsetof(struct sock_common, skc_family)); break; case offsetof(struct sk_msg_md, remote_ip4): BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_daddr) != 4); *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF( struct sk_msg, sk), si->dst_reg, si->src_reg, offsetof(struct sk_msg, sk)); *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg, offsetof(struct sock_common, skc_daddr)); break; case offsetof(struct sk_msg_md, local_ip4): BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_rcv_saddr) != 4); *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF( struct sk_msg, sk), si->dst_reg, si->src_reg, offsetof(struct sk_msg, sk)); *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg, offsetof(struct sock_common, skc_rcv_saddr)); break; case offsetof(struct sk_msg_md, remote_ip6[0]) ... offsetof(struct sk_msg_md, remote_ip6[3]): #if IS_ENABLED(CONFIG_IPV6) BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_v6_daddr.s6_addr32[0]) != 4); off = si->off; off -= offsetof(struct sk_msg_md, remote_ip6[0]); *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF( struct sk_msg, sk), si->dst_reg, si->src_reg, offsetof(struct sk_msg, sk)); *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg, offsetof(struct sock_common, skc_v6_daddr.s6_addr32[0]) + off); #else *insn++ = BPF_MOV32_IMM(si->dst_reg, 0); #endif break; case offsetof(struct sk_msg_md, local_ip6[0]) ... offsetof(struct sk_msg_md, local_ip6[3]): #if IS_ENABLED(CONFIG_IPV6) BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_v6_rcv_saddr.s6_addr32[0]) != 4); off = si->off; off -= offsetof(struct sk_msg_md, local_ip6[0]); *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF( struct sk_msg, sk), si->dst_reg, si->src_reg, offsetof(struct sk_msg, sk)); *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg, offsetof(struct sock_common, skc_v6_rcv_saddr.s6_addr32[0]) + off); #else *insn++ = BPF_MOV32_IMM(si->dst_reg, 0); #endif break; case offsetof(struct sk_msg_md, remote_port): BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_dport) != 2); *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF( struct sk_msg, sk), si->dst_reg, si->src_reg, offsetof(struct sk_msg, sk)); *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg, offsetof(struct sock_common, skc_dport)); #ifndef __BIG_ENDIAN_BITFIELD *insn++ = BPF_ALU32_IMM(BPF_LSH, si->dst_reg, 16); #endif break; case offsetof(struct sk_msg_md, local_port): BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_num) != 2); *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF( struct sk_msg, sk), si->dst_reg, si->src_reg, offsetof(struct sk_msg, sk)); *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg, offsetof(struct sock_common, skc_num)); break; case offsetof(struct sk_msg_md, size): *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_msg_sg, size), si->dst_reg, si->src_reg, offsetof(struct sk_msg_sg, size)); break; } return insn - insn_buf; } const struct bpf_verifier_ops sk_filter_verifier_ops = { .get_func_proto = sk_filter_func_proto, .is_valid_access = sk_filter_is_valid_access, .convert_ctx_access = bpf_convert_ctx_access, .gen_ld_abs = bpf_gen_ld_abs, }; const struct bpf_prog_ops sk_filter_prog_ops = { .test_run = bpf_prog_test_run_skb, }; const struct bpf_verifier_ops tc_cls_act_verifier_ops = { .get_func_proto = tc_cls_act_func_proto, .is_valid_access = tc_cls_act_is_valid_access, .convert_ctx_access = tc_cls_act_convert_ctx_access, .gen_prologue = tc_cls_act_prologue, .gen_ld_abs = bpf_gen_ld_abs, }; const struct bpf_prog_ops tc_cls_act_prog_ops = { .test_run = bpf_prog_test_run_skb, }; const struct bpf_verifier_ops xdp_verifier_ops = { .get_func_proto = xdp_func_proto, .is_valid_access = xdp_is_valid_access, .convert_ctx_access = xdp_convert_ctx_access, .gen_prologue = bpf_noop_prologue, }; const struct bpf_prog_ops xdp_prog_ops = { .test_run = bpf_prog_test_run_xdp, }; const struct bpf_verifier_ops cg_skb_verifier_ops = { .get_func_proto = cg_skb_func_proto, .is_valid_access = cg_skb_is_valid_access, .convert_ctx_access = bpf_convert_ctx_access, }; const struct bpf_prog_ops cg_skb_prog_ops = { .test_run = bpf_prog_test_run_skb, }; const struct bpf_verifier_ops lwt_in_verifier_ops = { .get_func_proto = lwt_in_func_proto, .is_valid_access = lwt_is_valid_access, .convert_ctx_access = bpf_convert_ctx_access, }; const struct bpf_prog_ops lwt_in_prog_ops = { .test_run = bpf_prog_test_run_skb, }; const struct bpf_verifier_ops lwt_out_verifier_ops = { .get_func_proto = lwt_out_func_proto, .is_valid_access = lwt_is_valid_access, .convert_ctx_access = bpf_convert_ctx_access, }; const struct bpf_prog_ops lwt_out_prog_ops = { .test_run = bpf_prog_test_run_skb, }; const struct bpf_verifier_ops lwt_xmit_verifier_ops = { .get_func_proto = lwt_xmit_func_proto, .is_valid_access = lwt_is_valid_access, .convert_ctx_access = bpf_convert_ctx_access, .gen_prologue = tc_cls_act_prologue, }; const struct bpf_prog_ops lwt_xmit_prog_ops = { .test_run = bpf_prog_test_run_skb, }; const struct bpf_verifier_ops lwt_seg6local_verifier_ops = { .get_func_proto = lwt_seg6local_func_proto, .is_valid_access = lwt_is_valid_access, .convert_ctx_access = bpf_convert_ctx_access, }; const struct bpf_prog_ops lwt_seg6local_prog_ops = { .test_run = bpf_prog_test_run_skb, }; const struct bpf_verifier_ops cg_sock_verifier_ops = { .get_func_proto = sock_filter_func_proto, .is_valid_access = sock_filter_is_valid_access, .convert_ctx_access = bpf_sock_convert_ctx_access, }; const struct bpf_prog_ops cg_sock_prog_ops = { }; const struct bpf_verifier_ops cg_sock_addr_verifier_ops = { .get_func_proto = sock_addr_func_proto, .is_valid_access = sock_addr_is_valid_access, .convert_ctx_access = sock_addr_convert_ctx_access, }; const struct bpf_prog_ops cg_sock_addr_prog_ops = { }; const struct bpf_verifier_ops sock_ops_verifier_ops = { .get_func_proto = sock_ops_func_proto, .is_valid_access = sock_ops_is_valid_access, .convert_ctx_access = sock_ops_convert_ctx_access, }; const struct bpf_prog_ops sock_ops_prog_ops = { }; const struct bpf_verifier_ops sk_skb_verifier_ops = { .get_func_proto = sk_skb_func_proto, .is_valid_access = sk_skb_is_valid_access, .convert_ctx_access = sk_skb_convert_ctx_access, .gen_prologue = sk_skb_prologue, }; const struct bpf_prog_ops sk_skb_prog_ops = { }; const struct bpf_verifier_ops sk_msg_verifier_ops = { .get_func_proto = sk_msg_func_proto, .is_valid_access = sk_msg_is_valid_access, .convert_ctx_access = sk_msg_convert_ctx_access, .gen_prologue = bpf_noop_prologue, }; const struct bpf_prog_ops sk_msg_prog_ops = { }; const struct bpf_verifier_ops flow_dissector_verifier_ops = { .get_func_proto = flow_dissector_func_proto, .is_valid_access = flow_dissector_is_valid_access, .convert_ctx_access = flow_dissector_convert_ctx_access, }; const struct bpf_prog_ops flow_dissector_prog_ops = { .test_run = bpf_prog_test_run_flow_dissector, }; int sk_detach_filter(struct sock *sk) { int ret = -ENOENT; struct sk_filter *filter; if (sock_flag(sk, SOCK_FILTER_LOCKED)) return -EPERM; filter = rcu_dereference_protected(sk->sk_filter, lockdep_sock_is_held(sk)); if (filter) { RCU_INIT_POINTER(sk->sk_filter, NULL); sk_filter_uncharge(sk, filter); ret = 0; } return ret; } EXPORT_SYMBOL_GPL(sk_detach_filter); int sk_get_filter(struct sock *sk, struct sock_filter __user *ubuf, unsigned int len) { struct sock_fprog_kern *fprog; struct sk_filter *filter; int ret = 0; lock_sock(sk); filter = rcu_dereference_protected(sk->sk_filter, lockdep_sock_is_held(sk)); if (!filter) goto out; /* We're copying the filter that has been originally attached, * so no conversion/decode needed anymore. eBPF programs that * have no original program cannot be dumped through this. */ ret = -EACCES; fprog = filter->prog->orig_prog; if (!fprog) goto out; ret = fprog->len; if (!len) /* User space only enquires number of filter blocks. */ goto out; ret = -EINVAL; if (len < fprog->len) goto out; ret = -EFAULT; if (copy_to_user(ubuf, fprog->filter, bpf_classic_proglen(fprog))) goto out; /* Instead of bytes, the API requests to return the number * of filter blocks. */ ret = fprog->len; out: release_sock(sk); return ret; } #ifdef CONFIG_INET struct sk_reuseport_kern { struct sk_buff *skb; struct sock *sk; struct sock *selected_sk; void *data_end; u32 hash; u32 reuseport_id; bool bind_inany; }; static void bpf_init_reuseport_kern(struct sk_reuseport_kern *reuse_kern, struct sock_reuseport *reuse, struct sock *sk, struct sk_buff *skb, u32 hash) { reuse_kern->skb = skb; reuse_kern->sk = sk; reuse_kern->selected_sk = NULL; reuse_kern->data_end = skb->data + skb_headlen(skb); reuse_kern->hash = hash; reuse_kern->reuseport_id = reuse->reuseport_id; reuse_kern->bind_inany = reuse->bind_inany; } struct sock *bpf_run_sk_reuseport(struct sock_reuseport *reuse, struct sock *sk, struct bpf_prog *prog, struct sk_buff *skb, u32 hash) { struct sk_reuseport_kern reuse_kern; enum sk_action action; bpf_init_reuseport_kern(&reuse_kern, reuse, sk, skb, hash); action = BPF_PROG_RUN(prog, &reuse_kern); if (action == SK_PASS) return reuse_kern.selected_sk; else return ERR_PTR(-ECONNREFUSED); } BPF_CALL_4(sk_select_reuseport, struct sk_reuseport_kern *, reuse_kern, struct bpf_map *, map, void *, key, u32, flags) { struct sock_reuseport *reuse; struct sock *selected_sk; selected_sk = map->ops->map_lookup_elem(map, key); if (!selected_sk) return -ENOENT; reuse = rcu_dereference(selected_sk->sk_reuseport_cb); if (!reuse) /* selected_sk is unhashed (e.g. by close()) after the * above map_lookup_elem(). Treat selected_sk has already * been removed from the map. */ return -ENOENT; if (unlikely(reuse->reuseport_id != reuse_kern->reuseport_id)) { struct sock *sk; if (unlikely(!reuse_kern->reuseport_id)) /* There is a small race between adding the * sk to the map and setting the * reuse_kern->reuseport_id. * Treat it as the sk has not been added to * the bpf map yet. */ return -ENOENT; sk = reuse_kern->sk; if (sk->sk_protocol != selected_sk->sk_protocol) return -EPROTOTYPE; else if (sk->sk_family != selected_sk->sk_family) return -EAFNOSUPPORT; /* Catch all. Likely bound to a different sockaddr. */ return -EBADFD; } reuse_kern->selected_sk = selected_sk; return 0; } static const struct bpf_func_proto sk_select_reuseport_proto = { .func = sk_select_reuseport, .gpl_only = false, .ret_type = RET_INTEGER, .arg1_type = ARG_PTR_TO_CTX, .arg2_type = ARG_CONST_MAP_PTR, .arg3_type = ARG_PTR_TO_MAP_KEY, .arg4_type = ARG_ANYTHING, }; BPF_CALL_4(sk_reuseport_load_bytes, const struct sk_reuseport_kern *, reuse_kern, u32, offset, void *, to, u32, len) { return ____bpf_skb_load_bytes(reuse_kern->skb, offset, to, len); } static const struct bpf_func_proto sk_reuseport_load_bytes_proto = { .func = sk_reuseport_load_bytes, .gpl_only = false, .ret_type = RET_INTEGER, .arg1_type = ARG_PTR_TO_CTX, .arg2_type = ARG_ANYTHING, .arg3_type = ARG_PTR_TO_UNINIT_MEM, .arg4_type = ARG_CONST_SIZE, }; BPF_CALL_5(sk_reuseport_load_bytes_relative, const struct sk_reuseport_kern *, reuse_kern, u32, offset, void *, to, u32, len, u32, start_header) { return ____bpf_skb_load_bytes_relative(reuse_kern->skb, offset, to, len, start_header); } static const struct bpf_func_proto sk_reuseport_load_bytes_relative_proto = { .func = sk_reuseport_load_bytes_relative, .gpl_only = false, .ret_type = RET_INTEGER, .arg1_type = ARG_PTR_TO_CTX, .arg2_type = ARG_ANYTHING, .arg3_type = ARG_PTR_TO_UNINIT_MEM, .arg4_type = ARG_CONST_SIZE, .arg5_type = ARG_ANYTHING, }; static const struct bpf_func_proto * sk_reuseport_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog) { switch (func_id) { case BPF_FUNC_sk_select_reuseport: return &sk_select_reuseport_proto; case BPF_FUNC_skb_load_bytes: return &sk_reuseport_load_bytes_proto; case BPF_FUNC_skb_load_bytes_relative: return &sk_reuseport_load_bytes_relative_proto; default: return bpf_base_func_proto(func_id); } } static bool sk_reuseport_is_valid_access(int off, int size, enum bpf_access_type type, const struct bpf_prog *prog, struct bpf_insn_access_aux *info) { const u32 size_default = sizeof(__u32); if (off < 0 || off >= sizeof(struct sk_reuseport_md) || off % size || type != BPF_READ) return false; switch (off) { case offsetof(struct sk_reuseport_md, data): info->reg_type = PTR_TO_PACKET; return size == sizeof(__u64); case offsetof(struct sk_reuseport_md, data_end): info->reg_type = PTR_TO_PACKET_END; return size == sizeof(__u64); case offsetof(struct sk_reuseport_md, hash): return size == size_default; /* Fields that allow narrowing */ case offsetof(struct sk_reuseport_md, eth_protocol): if (size < FIELD_SIZEOF(struct sk_buff, protocol)) return false; /* fall through */ case offsetof(struct sk_reuseport_md, ip_protocol): case offsetof(struct sk_reuseport_md, bind_inany): case offsetof(struct sk_reuseport_md, len): bpf_ctx_record_field_size(info, size_default); return bpf_ctx_narrow_access_ok(off, size, size_default); default: return false; } } #define SK_REUSEPORT_LOAD_FIELD(F) ({ \ *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_reuseport_kern, F), \ si->dst_reg, si->src_reg, \ bpf_target_off(struct sk_reuseport_kern, F, \ FIELD_SIZEOF(struct sk_reuseport_kern, F), \ target_size)); \ }) #define SK_REUSEPORT_LOAD_SKB_FIELD(SKB_FIELD) \ SOCK_ADDR_LOAD_NESTED_FIELD(struct sk_reuseport_kern, \ struct sk_buff, \ skb, \ SKB_FIELD) #define SK_REUSEPORT_LOAD_SK_FIELD_SIZE_OFF(SK_FIELD, BPF_SIZE, EXTRA_OFF) \ SOCK_ADDR_LOAD_NESTED_FIELD_SIZE_OFF(struct sk_reuseport_kern, \ struct sock, \ sk, \ SK_FIELD, BPF_SIZE, EXTRA_OFF) static u32 sk_reuseport_convert_ctx_access(enum bpf_access_type type, const struct bpf_insn *si, struct bpf_insn *insn_buf, struct bpf_prog *prog, u32 *target_size) { struct bpf_insn *insn = insn_buf; switch (si->off) { case offsetof(struct sk_reuseport_md, data): SK_REUSEPORT_LOAD_SKB_FIELD(data); break; case offsetof(struct sk_reuseport_md, len): SK_REUSEPORT_LOAD_SKB_FIELD(len); break; case offsetof(struct sk_reuseport_md, eth_protocol): SK_REUSEPORT_LOAD_SKB_FIELD(protocol); break; case offsetof(struct sk_reuseport_md, ip_protocol): BUILD_BUG_ON(HWEIGHT32(SK_FL_PROTO_MASK) != BITS_PER_BYTE); SK_REUSEPORT_LOAD_SK_FIELD_SIZE_OFF(__sk_flags_offset, BPF_W, 0); *insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg, SK_FL_PROTO_MASK); *insn++ = BPF_ALU32_IMM(BPF_RSH, si->dst_reg, SK_FL_PROTO_SHIFT); /* SK_FL_PROTO_MASK and SK_FL_PROTO_SHIFT are endian * aware. No further narrowing or masking is needed. */ *target_size = 1; break; case offsetof(struct sk_reuseport_md, data_end): SK_REUSEPORT_LOAD_FIELD(data_end); break; case offsetof(struct sk_reuseport_md, hash): SK_REUSEPORT_LOAD_FIELD(hash); break; case offsetof(struct sk_reuseport_md, bind_inany): SK_REUSEPORT_LOAD_FIELD(bind_inany); break; } return insn - insn_buf; } const struct bpf_verifier_ops sk_reuseport_verifier_ops = { .get_func_proto = sk_reuseport_func_proto, .is_valid_access = sk_reuseport_is_valid_access, .convert_ctx_access = sk_reuseport_convert_ctx_access, }; const struct bpf_prog_ops sk_reuseport_prog_ops = { }; #endif /* CONFIG_INET */
koct9i/linux
net/core/filter.c
C
gpl-2.0
234,767
<?php namespace Drupal\Tests\rest\Functional\EntityResource\Media; @trigger_error('The ' . __NAMESPACE__ . '\MediaResourceTestBase is deprecated in Drupal 8.6.x and will be removed before Drupal 9.0.0. Instead, use Drupal\Tests\media\Functional\Rest\MediaResourceTestBase. See https://www.drupal.org/node/2971931.', E_USER_DEPRECATED); use Drupal\Tests\media\Functional\Rest\MediaResourceTestBase as MediaResourceTestBaseReal; /** * @deprecated in drupal:8.6.0 and is removed from drupal:9.0.0. Use * Drupal\Tests\media\Functional\Rest\MediaResourceTestBase instead. * * @see https://www.drupal.org/node/2971931 */ abstract class MediaResourceTestBase extends MediaResourceTestBaseReal { }
maskedjellybean/tee-prop
web/core/modules/rest/tests/src/Functional/EntityResource/Media/MediaResourceTestBase.php
PHP
gpl-2.0
701
/* savage_bci.c -- BCI support for Savage * * Copyright 2004 Felix Kuehling * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sub license, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the * next paragraph) shall be included in all copies or substantial portions * of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NON-INFRINGEMENT. IN NO EVENT SHALL FELIX KUEHLING BE LIABLE FOR * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "drmP.h" #include "savage_drm.h" #include "savage_drv.h" /* Need a long timeout for shadow status updates can take a while * and so can waiting for events when the queue is full. */ #define SAVAGE_DEFAULT_USEC_TIMEOUT 1000000 /* 1s */ #define SAVAGE_EVENT_USEC_TIMEOUT 5000000 /* 5s */ #define SAVAGE_FREELIST_DEBUG 0 static int savage_do_cleanup_bci(struct drm_device *dev); static int savage_bci_wait_fifo_shadow(drm_savage_private_t * dev_priv, unsigned int n) { uint32_t mask = dev_priv->status_used_mask; uint32_t threshold = dev_priv->bci_threshold_hi; uint32_t status; int i; #if SAVAGE_BCI_DEBUG if (n > dev_priv->cob_size + SAVAGE_BCI_FIFO_SIZE - threshold) DRM_ERROR("Trying to emit %d words " "(more than guaranteed space in COB)\n", n); #endif for (i = 0; i < SAVAGE_DEFAULT_USEC_TIMEOUT; i++) { DRM_MEMORYBARRIER(); status = dev_priv->status_ptr[0]; if ((status & mask) < threshold) return 0; DRM_UDELAY(1); } #if SAVAGE_BCI_DEBUG DRM_ERROR("failed!\n"); DRM_INFO(" status=0x%08x, threshold=0x%08x\n", status, threshold); #endif return -EBUSY; } static int savage_bci_wait_fifo_s3d(drm_savage_private_t * dev_priv, unsigned int n) { uint32_t maxUsed = dev_priv->cob_size + SAVAGE_BCI_FIFO_SIZE - n; uint32_t status; int i; for (i = 0; i < SAVAGE_DEFAULT_USEC_TIMEOUT; i++) { status = SAVAGE_READ(SAVAGE_STATUS_WORD0); if ((status & SAVAGE_FIFO_USED_MASK_S3D) <= maxUsed) return 0; DRM_UDELAY(1); } #if SAVAGE_BCI_DEBUG DRM_ERROR("failed!\n"); DRM_INFO(" status=0x%08x\n", status); #endif return -EBUSY; } static int savage_bci_wait_fifo_s4(drm_savage_private_t * dev_priv, unsigned int n) { uint32_t maxUsed = dev_priv->cob_size + SAVAGE_BCI_FIFO_SIZE - n; uint32_t status; int i; for (i = 0; i < SAVAGE_DEFAULT_USEC_TIMEOUT; i++) { status = SAVAGE_READ(SAVAGE_ALT_STATUS_WORD0); if ((status & SAVAGE_FIFO_USED_MASK_S4) <= maxUsed) return 0; DRM_UDELAY(1); } #if SAVAGE_BCI_DEBUG DRM_ERROR("failed!\n"); DRM_INFO(" status=0x%08x\n", status); #endif return -EBUSY; } /* * Waiting for events. * * The BIOSresets the event tag to 0 on mode changes. Therefore we * never emit 0 to the event tag. If we find a 0 event tag we know the * BIOS stomped on it and return success assuming that the BIOS waited * for engine idle. * * Note: if the Xserver uses the event tag it has to follow the same * rule. Otherwise there may be glitches every 2^16 events. */ static int savage_bci_wait_event_shadow(drm_savage_private_t * dev_priv, uint16_t e) { uint32_t status; int i; for (i = 0; i < SAVAGE_EVENT_USEC_TIMEOUT; i++) { DRM_MEMORYBARRIER(); status = dev_priv->status_ptr[1]; if ((((status & 0xffff) - e) & 0xffff) <= 0x7fff || (status & 0xffff) == 0) return 0; DRM_UDELAY(1); } #if SAVAGE_BCI_DEBUG DRM_ERROR("failed!\n"); DRM_INFO(" status=0x%08x, e=0x%04x\n", status, e); #endif return -EBUSY; } static int savage_bci_wait_event_reg(drm_savage_private_t * dev_priv, uint16_t e) { uint32_t status; int i; for (i = 0; i < SAVAGE_EVENT_USEC_TIMEOUT; i++) { status = SAVAGE_READ(SAVAGE_STATUS_WORD1); if ((((status & 0xffff) - e) & 0xffff) <= 0x7fff || (status & 0xffff) == 0) return 0; DRM_UDELAY(1); } #if SAVAGE_BCI_DEBUG DRM_ERROR("failed!\n"); DRM_INFO(" status=0x%08x, e=0x%04x\n", status, e); #endif return -EBUSY; } uint16_t savage_bci_emit_event(drm_savage_private_t * dev_priv, unsigned int flags) { uint16_t count; BCI_LOCALS; if (dev_priv->status_ptr) { /* coordinate with Xserver */ count = dev_priv->status_ptr[1023]; if (count < dev_priv->event_counter) dev_priv->event_wrap++; } else { count = dev_priv->event_counter; } count = (count + 1) & 0xffff; if (count == 0) { count++; /* See the comment above savage_wait_event_*. */ dev_priv->event_wrap++; } dev_priv->event_counter = count; if (dev_priv->status_ptr) dev_priv->status_ptr[1023] = (uint32_t) count; if ((flags & (SAVAGE_WAIT_2D | SAVAGE_WAIT_3D))) { unsigned int wait_cmd = BCI_CMD_WAIT; if ((flags & SAVAGE_WAIT_2D)) wait_cmd |= BCI_CMD_WAIT_2D; if ((flags & SAVAGE_WAIT_3D)) wait_cmd |= BCI_CMD_WAIT_3D; BEGIN_BCI(2); BCI_WRITE(wait_cmd); } else { BEGIN_BCI(1); } BCI_WRITE(BCI_CMD_UPDATE_EVENT_TAG | (uint32_t) count); return count; } /* * Freelist management */ static int savage_freelist_init(struct drm_device * dev) { drm_savage_private_t *dev_priv = dev->dev_private; struct drm_device_dma *dma = dev->dma; struct drm_buf *buf; drm_savage_buf_priv_t *entry; int i; DRM_DEBUG("count=%d\n", dma->buf_count); dev_priv->head.next = &dev_priv->tail; dev_priv->head.prev = NULL; dev_priv->head.buf = NULL; dev_priv->tail.next = NULL; dev_priv->tail.prev = &dev_priv->head; dev_priv->tail.buf = NULL; for (i = 0; i < dma->buf_count; i++) { buf = dma->buflist[i]; entry = buf->dev_private; SET_AGE(&entry->age, 0, 0); entry->buf = buf; entry->next = dev_priv->head.next; entry->prev = &dev_priv->head; dev_priv->head.next->prev = entry; dev_priv->head.next = entry; } return 0; } static struct drm_buf *savage_freelist_get(struct drm_device * dev) { drm_savage_private_t *dev_priv = dev->dev_private; drm_savage_buf_priv_t *tail = dev_priv->tail.prev; uint16_t event; unsigned int wrap; DRM_DEBUG("\n"); UPDATE_EVENT_COUNTER(); if (dev_priv->status_ptr) event = dev_priv->status_ptr[1] & 0xffff; else event = SAVAGE_READ(SAVAGE_STATUS_WORD1) & 0xffff; wrap = dev_priv->event_wrap; if (event > dev_priv->event_counter) wrap--; /* hardware hasn't passed the last wrap yet */ DRM_DEBUG(" tail=0x%04x %d\n", tail->age.event, tail->age.wrap); DRM_DEBUG(" head=0x%04x %d\n", event, wrap); if (tail->buf && (TEST_AGE(&tail->age, event, wrap) || event == 0)) { drm_savage_buf_priv_t *next = tail->next; drm_savage_buf_priv_t *prev = tail->prev; prev->next = next; next->prev = prev; tail->next = tail->prev = NULL; return tail->buf; } DRM_DEBUG("returning NULL, tail->buf=%p!\n", tail->buf); return NULL; } void savage_freelist_put(struct drm_device * dev, struct drm_buf * buf) { drm_savage_private_t *dev_priv = dev->dev_private; drm_savage_buf_priv_t *entry = buf->dev_private, *prev, *next; DRM_DEBUG("age=0x%04x wrap=%d\n", entry->age.event, entry->age.wrap); if (entry->next != NULL || entry->prev != NULL) { DRM_ERROR("entry already on freelist.\n"); return; } prev = &dev_priv->head; next = prev->next; prev->next = entry; next->prev = entry; entry->prev = prev; entry->next = next; } /* * Command DMA */ static int savage_dma_init(drm_savage_private_t * dev_priv) { unsigned int i; dev_priv->nr_dma_pages = dev_priv->cmd_dma->size / (SAVAGE_DMA_PAGE_SIZE * 4); dev_priv->dma_pages = kmalloc(sizeof(drm_savage_dma_page_t) * dev_priv->nr_dma_pages, GFP_KERNEL); if (dev_priv->dma_pages == NULL) return -ENOMEM; for (i = 0; i < dev_priv->nr_dma_pages; ++i) { SET_AGE(&dev_priv->dma_pages[i].age, 0, 0); dev_priv->dma_pages[i].used = 0; dev_priv->dma_pages[i].flushed = 0; } SET_AGE(&dev_priv->last_dma_age, 0, 0); dev_priv->first_dma_page = 0; dev_priv->current_dma_page = 0; return 0; } void savage_dma_reset(drm_savage_private_t * dev_priv) { uint16_t event; unsigned int wrap, i; event = savage_bci_emit_event(dev_priv, 0); wrap = dev_priv->event_wrap; for (i = 0; i < dev_priv->nr_dma_pages; ++i) { SET_AGE(&dev_priv->dma_pages[i].age, event, wrap); dev_priv->dma_pages[i].used = 0; dev_priv->dma_pages[i].flushed = 0; } SET_AGE(&dev_priv->last_dma_age, event, wrap); dev_priv->first_dma_page = dev_priv->current_dma_page = 0; } void savage_dma_wait(drm_savage_private_t * dev_priv, unsigned int page) { uint16_t event; unsigned int wrap; /* Faked DMA buffer pages don't age. */ if (dev_priv->cmd_dma == &dev_priv->fake_dma) return; UPDATE_EVENT_COUNTER(); if (dev_priv->status_ptr) event = dev_priv->status_ptr[1] & 0xffff; else event = SAVAGE_READ(SAVAGE_STATUS_WORD1) & 0xffff; wrap = dev_priv->event_wrap; if (event > dev_priv->event_counter) wrap--; /* hardware hasn't passed the last wrap yet */ if (dev_priv->dma_pages[page].age.wrap > wrap || (dev_priv->dma_pages[page].age.wrap == wrap && dev_priv->dma_pages[page].age.event > event)) { if (dev_priv->wait_evnt(dev_priv, dev_priv->dma_pages[page].age.event) < 0) DRM_ERROR("wait_evnt failed!\n"); } } uint32_t *savage_dma_alloc(drm_savage_private_t * dev_priv, unsigned int n) { unsigned int cur = dev_priv->current_dma_page; unsigned int rest = SAVAGE_DMA_PAGE_SIZE - dev_priv->dma_pages[cur].used; unsigned int nr_pages = (n - rest + SAVAGE_DMA_PAGE_SIZE - 1) / SAVAGE_DMA_PAGE_SIZE; uint32_t *dma_ptr; unsigned int i; DRM_DEBUG("cur=%u, cur->used=%u, n=%u, rest=%u, nr_pages=%u\n", cur, dev_priv->dma_pages[cur].used, n, rest, nr_pages); if (cur + nr_pages < dev_priv->nr_dma_pages) { dma_ptr = (uint32_t *) dev_priv->cmd_dma->handle + cur * SAVAGE_DMA_PAGE_SIZE + dev_priv->dma_pages[cur].used; if (n < rest) rest = n; dev_priv->dma_pages[cur].used += rest; n -= rest; cur++; } else { dev_priv->dma_flush(dev_priv); nr_pages = (n + SAVAGE_DMA_PAGE_SIZE - 1) / SAVAGE_DMA_PAGE_SIZE; for (i = cur; i < dev_priv->nr_dma_pages; ++i) { dev_priv->dma_pages[i].age = dev_priv->last_dma_age; dev_priv->dma_pages[i].used = 0; dev_priv->dma_pages[i].flushed = 0; } dma_ptr = (uint32_t *) dev_priv->cmd_dma->handle; dev_priv->first_dma_page = cur = 0; } for (i = cur; nr_pages > 0; ++i, --nr_pages) { #if SAVAGE_DMA_DEBUG if (dev_priv->dma_pages[i].used) { DRM_ERROR("unflushed page %u: used=%u\n", i, dev_priv->dma_pages[i].used); } #endif if (n > SAVAGE_DMA_PAGE_SIZE) dev_priv->dma_pages[i].used = SAVAGE_DMA_PAGE_SIZE; else dev_priv->dma_pages[i].used = n; n -= SAVAGE_DMA_PAGE_SIZE; } dev_priv->current_dma_page = --i; DRM_DEBUG("cur=%u, cur->used=%u, n=%u\n", i, dev_priv->dma_pages[i].used, n); savage_dma_wait(dev_priv, dev_priv->current_dma_page); return dma_ptr; } static void savage_dma_flush(drm_savage_private_t * dev_priv) { unsigned int first = dev_priv->first_dma_page; unsigned int cur = dev_priv->current_dma_page; uint16_t event; unsigned int wrap, pad, align, len, i; unsigned long phys_addr; BCI_LOCALS; if (first == cur && dev_priv->dma_pages[cur].used == dev_priv->dma_pages[cur].flushed) return; /* pad length to multiples of 2 entries * align start of next DMA block to multiles of 8 entries */ pad = -dev_priv->dma_pages[cur].used & 1; align = -(dev_priv->dma_pages[cur].used + pad) & 7; DRM_DEBUG("first=%u, cur=%u, first->flushed=%u, cur->used=%u, " "pad=%u, align=%u\n", first, cur, dev_priv->dma_pages[first].flushed, dev_priv->dma_pages[cur].used, pad, align); /* pad with noops */ if (pad) { uint32_t *dma_ptr = (uint32_t *) dev_priv->cmd_dma->handle + cur * SAVAGE_DMA_PAGE_SIZE + dev_priv->dma_pages[cur].used; dev_priv->dma_pages[cur].used += pad; while (pad != 0) { *dma_ptr++ = BCI_CMD_WAIT; pad--; } } DRM_MEMORYBARRIER(); /* do flush ... */ phys_addr = dev_priv->cmd_dma->offset + (first * SAVAGE_DMA_PAGE_SIZE + dev_priv->dma_pages[first].flushed) * 4; len = (cur - first) * SAVAGE_DMA_PAGE_SIZE + dev_priv->dma_pages[cur].used - dev_priv->dma_pages[first].flushed; DRM_DEBUG("phys_addr=%lx, len=%u\n", phys_addr | dev_priv->dma_type, len); BEGIN_BCI(3); BCI_SET_REGISTERS(SAVAGE_DMABUFADDR, 1); BCI_WRITE(phys_addr | dev_priv->dma_type); BCI_DMA(len); /* fix alignment of the start of the next block */ dev_priv->dma_pages[cur].used += align; /* age DMA pages */ event = savage_bci_emit_event(dev_priv, 0); wrap = dev_priv->event_wrap; for (i = first; i < cur; ++i) { SET_AGE(&dev_priv->dma_pages[i].age, event, wrap); dev_priv->dma_pages[i].used = 0; dev_priv->dma_pages[i].flushed = 0; } /* age the current page only when it's full */ if (dev_priv->dma_pages[cur].used == SAVAGE_DMA_PAGE_SIZE) { SET_AGE(&dev_priv->dma_pages[cur].age, event, wrap); dev_priv->dma_pages[cur].used = 0; dev_priv->dma_pages[cur].flushed = 0; /* advance to next page */ cur++; if (cur == dev_priv->nr_dma_pages) cur = 0; dev_priv->first_dma_page = dev_priv->current_dma_page = cur; } else { dev_priv->first_dma_page = cur; dev_priv->dma_pages[cur].flushed = dev_priv->dma_pages[i].used; } SET_AGE(&dev_priv->last_dma_age, event, wrap); DRM_DEBUG("first=cur=%u, cur->used=%u, cur->flushed=%u\n", cur, dev_priv->dma_pages[cur].used, dev_priv->dma_pages[cur].flushed); } static void savage_fake_dma_flush(drm_savage_private_t * dev_priv) { unsigned int i, j; BCI_LOCALS; if (dev_priv->first_dma_page == dev_priv->current_dma_page && dev_priv->dma_pages[dev_priv->current_dma_page].used == 0) return; DRM_DEBUG("first=%u, cur=%u, cur->used=%u\n", dev_priv->first_dma_page, dev_priv->current_dma_page, dev_priv->dma_pages[dev_priv->current_dma_page].used); for (i = dev_priv->first_dma_page; i <= dev_priv->current_dma_page && dev_priv->dma_pages[i].used; ++i) { uint32_t *dma_ptr = (uint32_t *) dev_priv->cmd_dma->handle + i * SAVAGE_DMA_PAGE_SIZE; #if SAVAGE_DMA_DEBUG /* Sanity check: all pages except the last one must be full. */ if (i < dev_priv->current_dma_page && dev_priv->dma_pages[i].used != SAVAGE_DMA_PAGE_SIZE) { DRM_ERROR("partial DMA page %u: used=%u", i, dev_priv->dma_pages[i].used); } #endif BEGIN_BCI(dev_priv->dma_pages[i].used); for (j = 0; j < dev_priv->dma_pages[i].used; ++j) { BCI_WRITE(dma_ptr[j]); } dev_priv->dma_pages[i].used = 0; } /* reset to first page */ dev_priv->first_dma_page = dev_priv->current_dma_page = 0; } int savage_driver_load(struct drm_device *dev, unsigned long chipset) { drm_savage_private_t *dev_priv; dev_priv = kzalloc(sizeof(drm_savage_private_t), GFP_KERNEL); if (dev_priv == NULL) return -ENOMEM; dev->dev_private = (void *)dev_priv; dev_priv->chipset = (enum savage_family)chipset; pci_set_master(dev->pdev); return 0; } /* * Initialize mappings. On Savage4 and SavageIX the alignment * and size of the aperture is not suitable for automatic MTRR setup * in drm_addmap. Therefore we add them manually before the maps are * initialized, and tear them down on last close. */ int savage_driver_firstopen(struct drm_device *dev) { drm_savage_private_t *dev_priv = dev->dev_private; unsigned long mmio_base, fb_base, fb_size, aperture_base; /* fb_rsrc and aper_rsrc aren't really used currently, but still exist * in case we decide we need information on the BAR for BSD in the * future. */ unsigned int fb_rsrc, aper_rsrc; int ret = 0; dev_priv->mtrr[0].handle = -1; dev_priv->mtrr[1].handle = -1; dev_priv->mtrr[2].handle = -1; if (S3_SAVAGE3D_SERIES(dev_priv->chipset)) { fb_rsrc = 0; fb_base = pci_resource_start(dev->pdev, 0); fb_size = SAVAGE_FB_SIZE_S3; mmio_base = fb_base + SAVAGE_FB_SIZE_S3; aper_rsrc = 0; aperture_base = fb_base + SAVAGE_APERTURE_OFFSET; /* this should always be true */ if (pci_resource_len(dev->pdev, 0) == 0x08000000) { /* Don't make MMIO write-cobining! We need 3 * MTRRs. */ dev_priv->mtrr[0].base = fb_base; dev_priv->mtrr[0].size = 0x01000000; dev_priv->mtrr[0].handle = drm_mtrr_add(dev_priv->mtrr[0].base, dev_priv->mtrr[0].size, DRM_MTRR_WC); dev_priv->mtrr[1].base = fb_base + 0x02000000; dev_priv->mtrr[1].size = 0x02000000; dev_priv->mtrr[1].handle = drm_mtrr_add(dev_priv->mtrr[1].base, dev_priv->mtrr[1].size, DRM_MTRR_WC); dev_priv->mtrr[2].base = fb_base + 0x04000000; dev_priv->mtrr[2].size = 0x04000000; dev_priv->mtrr[2].handle = drm_mtrr_add(dev_priv->mtrr[2].base, dev_priv->mtrr[2].size, DRM_MTRR_WC); } else { DRM_ERROR("strange pci_resource_len %08llx\n", (unsigned long long) pci_resource_len(dev->pdev, 0)); } } else if (dev_priv->chipset != S3_SUPERSAVAGE && dev_priv->chipset != S3_SAVAGE2000) { mmio_base = pci_resource_start(dev->pdev, 0); fb_rsrc = 1; fb_base = pci_resource_start(dev->pdev, 1); fb_size = SAVAGE_FB_SIZE_S4; aper_rsrc = 1; aperture_base = fb_base + SAVAGE_APERTURE_OFFSET; /* this should always be true */ if (pci_resource_len(dev->pdev, 1) == 0x08000000) { /* Can use one MTRR to cover both fb and * aperture. */ dev_priv->mtrr[0].base = fb_base; dev_priv->mtrr[0].size = 0x08000000; dev_priv->mtrr[0].handle = drm_mtrr_add(dev_priv->mtrr[0].base, dev_priv->mtrr[0].size, DRM_MTRR_WC); } else { DRM_ERROR("strange pci_resource_len %08llx\n", (unsigned long long) pci_resource_len(dev->pdev, 1)); } } else { mmio_base = pci_resource_start(dev->pdev, 0); fb_rsrc = 1; fb_base = pci_resource_start(dev->pdev, 1); fb_size = pci_resource_len(dev->pdev, 1); aper_rsrc = 2; aperture_base = pci_resource_start(dev->pdev, 2); /* Automatic MTRR setup will do the right thing. */ } ret = drm_addmap(dev, mmio_base, SAVAGE_MMIO_SIZE, _DRM_REGISTERS, _DRM_READ_ONLY, &dev_priv->mmio); if (ret) return ret; ret = drm_addmap(dev, fb_base, fb_size, _DRM_FRAME_BUFFER, _DRM_WRITE_COMBINING, &dev_priv->fb); if (ret) return ret; ret = drm_addmap(dev, aperture_base, SAVAGE_APERTURE_SIZE, _DRM_FRAME_BUFFER, _DRM_WRITE_COMBINING, &dev_priv->aperture); return ret; } /* * Delete MTRRs and free device-private data. */ void savage_driver_lastclose(struct drm_device *dev) { drm_savage_private_t *dev_priv = dev->dev_private; int i; for (i = 0; i < 3; ++i) if (dev_priv->mtrr[i].handle >= 0) drm_mtrr_del(dev_priv->mtrr[i].handle, dev_priv->mtrr[i].base, dev_priv->mtrr[i].size, DRM_MTRR_WC); } int savage_driver_unload(struct drm_device *dev) { drm_savage_private_t *dev_priv = dev->dev_private; kfree(dev_priv); return 0; } static int savage_do_init_bci(struct drm_device * dev, drm_savage_init_t * init) { drm_savage_private_t *dev_priv = dev->dev_private; if (init->fb_bpp != 16 && init->fb_bpp != 32) { DRM_ERROR("invalid frame buffer bpp %d!\n", init->fb_bpp); return -EINVAL; } if (init->depth_bpp != 16 && init->depth_bpp != 32) { DRM_ERROR("invalid depth buffer bpp %d!\n", init->fb_bpp); return -EINVAL; } if (init->dma_type != SAVAGE_DMA_AGP && init->dma_type != SAVAGE_DMA_PCI) { DRM_ERROR("invalid dma memory type %d!\n", init->dma_type); return -EINVAL; } dev_priv->cob_size = init->cob_size; dev_priv->bci_threshold_lo = init->bci_threshold_lo; dev_priv->bci_threshold_hi = init->bci_threshold_hi; dev_priv->dma_type = init->dma_type; dev_priv->fb_bpp = init->fb_bpp; dev_priv->front_offset = init->front_offset; dev_priv->front_pitch = init->front_pitch; dev_priv->back_offset = init->back_offset; dev_priv->back_pitch = init->back_pitch; dev_priv->depth_bpp = init->depth_bpp; dev_priv->depth_offset = init->depth_offset; dev_priv->depth_pitch = init->depth_pitch; dev_priv->texture_offset = init->texture_offset; dev_priv->texture_size = init->texture_size; dev_priv->sarea = drm_getsarea(dev); if (!dev_priv->sarea) { DRM_ERROR("could not find sarea!\n"); savage_do_cleanup_bci(dev); return -EINVAL; } if (init->status_offset != 0) { dev_priv->status = drm_core_findmap(dev, init->status_offset); if (!dev_priv->status) { DRM_ERROR("could not find shadow status region!\n"); savage_do_cleanup_bci(dev); return -EINVAL; } } else { dev_priv->status = NULL; } if (dev_priv->dma_type == SAVAGE_DMA_AGP && init->buffers_offset) { dev->agp_buffer_token = init->buffers_offset; dev->agp_buffer_map = drm_core_findmap(dev, init->buffers_offset); if (!dev->agp_buffer_map) { DRM_ERROR("could not find DMA buffer region!\n"); savage_do_cleanup_bci(dev); return -EINVAL; } drm_core_ioremap(dev->agp_buffer_map, dev); if (!dev->agp_buffer_map->handle) { DRM_ERROR("failed to ioremap DMA buffer region!\n"); savage_do_cleanup_bci(dev); return -ENOMEM; } } if (init->agp_textures_offset) { dev_priv->agp_textures = drm_core_findmap(dev, init->agp_textures_offset); if (!dev_priv->agp_textures) { DRM_ERROR("could not find agp texture region!\n"); savage_do_cleanup_bci(dev); return -EINVAL; } } else { dev_priv->agp_textures = NULL; } if (init->cmd_dma_offset) { if (S3_SAVAGE3D_SERIES(dev_priv->chipset)) { DRM_ERROR("command DMA not supported on " "Savage3D/MX/IX.\n"); savage_do_cleanup_bci(dev); return -EINVAL; } if (dev->dma && dev->dma->buflist) { DRM_ERROR("command and vertex DMA not supported " "at the same time.\n"); savage_do_cleanup_bci(dev); return -EINVAL; } dev_priv->cmd_dma = drm_core_findmap(dev, init->cmd_dma_offset); if (!dev_priv->cmd_dma) { DRM_ERROR("could not find command DMA region!\n"); savage_do_cleanup_bci(dev); return -EINVAL; } if (dev_priv->dma_type == SAVAGE_DMA_AGP) { if (dev_priv->cmd_dma->type != _DRM_AGP) { DRM_ERROR("AGP command DMA region is not a " "_DRM_AGP map!\n"); savage_do_cleanup_bci(dev); return -EINVAL; } drm_core_ioremap(dev_priv->cmd_dma, dev); if (!dev_priv->cmd_dma->handle) { DRM_ERROR("failed to ioremap command " "DMA region!\n"); savage_do_cleanup_bci(dev); return -ENOMEM; } } else if (dev_priv->cmd_dma->type != _DRM_CONSISTENT) { DRM_ERROR("PCI command DMA region is not a " "_DRM_CONSISTENT map!\n"); savage_do_cleanup_bci(dev); return -EINVAL; } } else { dev_priv->cmd_dma = NULL; } dev_priv->dma_flush = savage_dma_flush; if (!dev_priv->cmd_dma) { DRM_DEBUG("falling back to faked command DMA.\n"); dev_priv->fake_dma.offset = 0; dev_priv->fake_dma.size = SAVAGE_FAKE_DMA_SIZE; dev_priv->fake_dma.type = _DRM_SHM; dev_priv->fake_dma.handle = kmalloc(SAVAGE_FAKE_DMA_SIZE, GFP_KERNEL); if (!dev_priv->fake_dma.handle) { DRM_ERROR("could not allocate faked DMA buffer!\n"); savage_do_cleanup_bci(dev); return -ENOMEM; } dev_priv->cmd_dma = &dev_priv->fake_dma; dev_priv->dma_flush = savage_fake_dma_flush; } dev_priv->sarea_priv = (drm_savage_sarea_t *) ((uint8_t *) dev_priv->sarea->handle + init->sarea_priv_offset); /* setup bitmap descriptors */ { unsigned int color_tile_format; unsigned int depth_tile_format; unsigned int front_stride, back_stride, depth_stride; if (dev_priv->chipset <= S3_SAVAGE4) { color_tile_format = dev_priv->fb_bpp == 16 ? SAVAGE_BD_TILE_16BPP : SAVAGE_BD_TILE_32BPP; depth_tile_format = dev_priv->depth_bpp == 16 ? SAVAGE_BD_TILE_16BPP : SAVAGE_BD_TILE_32BPP; } else { color_tile_format = SAVAGE_BD_TILE_DEST; depth_tile_format = SAVAGE_BD_TILE_DEST; } front_stride = dev_priv->front_pitch / (dev_priv->fb_bpp / 8); back_stride = dev_priv->back_pitch / (dev_priv->fb_bpp / 8); depth_stride = dev_priv->depth_pitch / (dev_priv->depth_bpp / 8); dev_priv->front_bd = front_stride | SAVAGE_BD_BW_DISABLE | (dev_priv->fb_bpp << SAVAGE_BD_BPP_SHIFT) | (color_tile_format << SAVAGE_BD_TILE_SHIFT); dev_priv->back_bd = back_stride | SAVAGE_BD_BW_DISABLE | (dev_priv->fb_bpp << SAVAGE_BD_BPP_SHIFT) | (color_tile_format << SAVAGE_BD_TILE_SHIFT); dev_priv->depth_bd = depth_stride | SAVAGE_BD_BW_DISABLE | (dev_priv->depth_bpp << SAVAGE_BD_BPP_SHIFT) | (depth_tile_format << SAVAGE_BD_TILE_SHIFT); } /* setup status and bci ptr */ dev_priv->event_counter = 0; dev_priv->event_wrap = 0; dev_priv->bci_ptr = (volatile uint32_t *) ((uint8_t *) dev_priv->mmio->handle + SAVAGE_BCI_OFFSET); if (S3_SAVAGE3D_SERIES(dev_priv->chipset)) { dev_priv->status_used_mask = SAVAGE_FIFO_USED_MASK_S3D; } else { dev_priv->status_used_mask = SAVAGE_FIFO_USED_MASK_S4; } if (dev_priv->status != NULL) { dev_priv->status_ptr = (volatile uint32_t *)dev_priv->status->handle; dev_priv->wait_fifo = savage_bci_wait_fifo_shadow; dev_priv->wait_evnt = savage_bci_wait_event_shadow; dev_priv->status_ptr[1023] = dev_priv->event_counter; } else { dev_priv->status_ptr = NULL; if (S3_SAVAGE3D_SERIES(dev_priv->chipset)) { dev_priv->wait_fifo = savage_bci_wait_fifo_s3d; } else { dev_priv->wait_fifo = savage_bci_wait_fifo_s4; } dev_priv->wait_evnt = savage_bci_wait_event_reg; } /* cliprect functions */ if (S3_SAVAGE3D_SERIES(dev_priv->chipset)) dev_priv->emit_clip_rect = savage_emit_clip_rect_s3d; else dev_priv->emit_clip_rect = savage_emit_clip_rect_s4; if (savage_freelist_init(dev) < 0) { DRM_ERROR("could not initialize freelist\n"); savage_do_cleanup_bci(dev); return -ENOMEM; } if (savage_dma_init(dev_priv) < 0) { DRM_ERROR("could not initialize command DMA\n"); savage_do_cleanup_bci(dev); return -ENOMEM; } return 0; } static int savage_do_cleanup_bci(struct drm_device * dev) { drm_savage_private_t *dev_priv = dev->dev_private; if (dev_priv->cmd_dma == &dev_priv->fake_dma) { kfree(dev_priv->fake_dma.handle); } else if (dev_priv->cmd_dma && dev_priv->cmd_dma->handle && dev_priv->cmd_dma->type == _DRM_AGP && dev_priv->dma_type == SAVAGE_DMA_AGP) drm_core_ioremapfree(dev_priv->cmd_dma, dev); if (dev_priv->dma_type == SAVAGE_DMA_AGP && dev->agp_buffer_map && dev->agp_buffer_map->handle) { drm_core_ioremapfree(dev->agp_buffer_map, dev); /* make sure the next instance (which may be running * in PCI mode) doesn't try to use an old * agp_buffer_map. */ dev->agp_buffer_map = NULL; } kfree(dev_priv->dma_pages); return 0; } static int savage_bci_init(struct drm_device *dev, void *data, struct drm_file *file_priv) { drm_savage_init_t *init = data; LOCK_TEST_WITH_RETURN(dev, file_priv); switch (init->func) { case SAVAGE_INIT_BCI: return savage_do_init_bci(dev, init); case SAVAGE_CLEANUP_BCI: return savage_do_cleanup_bci(dev); } return -EINVAL; } static int savage_bci_event_emit(struct drm_device *dev, void *data, struct drm_file *file_priv) { drm_savage_private_t *dev_priv = dev->dev_private; drm_savage_event_emit_t *event = data; DRM_DEBUG("\n"); LOCK_TEST_WITH_RETURN(dev, file_priv); event->count = savage_bci_emit_event(dev_priv, event->flags); event->count |= dev_priv->event_wrap << 16; return 0; } static int savage_bci_event_wait(struct drm_device *dev, void *data, struct drm_file *file_priv) { drm_savage_private_t *dev_priv = dev->dev_private; drm_savage_event_wait_t *event = data; unsigned int event_e, hw_e; unsigned int event_w, hw_w; DRM_DEBUG("\n"); UPDATE_EVENT_COUNTER(); if (dev_priv->status_ptr) hw_e = dev_priv->status_ptr[1] & 0xffff; else hw_e = SAVAGE_READ(SAVAGE_STATUS_WORD1) & 0xffff; hw_w = dev_priv->event_wrap; if (hw_e > dev_priv->event_counter) hw_w--; /* hardware hasn't passed the last wrap yet */ event_e = event->count & 0xffff; event_w = event->count >> 16; /* Don't need to wait if * - event counter wrapped since the event was emitted or * - the hardware has advanced up to or over the event to wait for. */ if (event_w < hw_w || (event_w == hw_w && event_e <= hw_e)) return 0; else return dev_priv->wait_evnt(dev_priv, event_e); } /* * DMA buffer management */ static int savage_bci_get_buffers(struct drm_device *dev, struct drm_file *file_priv, struct drm_dma *d) { struct drm_buf *buf; int i; for (i = d->granted_count; i < d->request_count; i++) { buf = savage_freelist_get(dev); if (!buf) return -EAGAIN; buf->file_priv = file_priv; if (DRM_COPY_TO_USER(&d->request_indices[i], &buf->idx, sizeof(buf->idx))) return -EFAULT; if (DRM_COPY_TO_USER(&d->request_sizes[i], &buf->total, sizeof(buf->total))) return -EFAULT; d->granted_count++; } return 0; } int savage_bci_buffers(struct drm_device *dev, void *data, struct drm_file *file_priv) { struct drm_device_dma *dma = dev->dma; struct drm_dma *d = data; int ret = 0; LOCK_TEST_WITH_RETURN(dev, file_priv); /* Please don't send us buffers. */ if (d->send_count != 0) { DRM_ERROR("Process %d trying to send %d buffers via drmDMA\n", DRM_CURRENTPID, d->send_count); return -EINVAL; } /* We'll send you buffers. */ if (d->request_count < 0 || d->request_count > dma->buf_count) { DRM_ERROR("Process %d trying to get %d buffers (of %d max)\n", DRM_CURRENTPID, d->request_count, dma->buf_count); return -EINVAL; } d->granted_count = 0; if (d->request_count) { ret = savage_bci_get_buffers(dev, file_priv, d); } return ret; } void savage_reclaim_buffers(struct drm_device *dev, struct drm_file *file_priv) { struct drm_device_dma *dma = dev->dma; drm_savage_private_t *dev_priv = dev->dev_private; int i; if (!dma) return; if (!dev_priv) return; if (!dma->buflist) return; /*i830_flush_queue(dev); */ for (i = 0; i < dma->buf_count; i++) { struct drm_buf *buf = dma->buflist[i]; drm_savage_buf_priv_t *buf_priv = buf->dev_private; if (buf->file_priv == file_priv && buf_priv && buf_priv->next == NULL && buf_priv->prev == NULL) { uint16_t event; DRM_DEBUG("reclaimed from client\n"); event = savage_bci_emit_event(dev_priv, SAVAGE_WAIT_3D); SET_AGE(&buf_priv->age, event, dev_priv->event_wrap); savage_freelist_put(dev, buf); } } drm_core_reclaim_buffers(dev, file_priv); } struct drm_ioctl_desc savage_ioctls[] = { DRM_IOCTL_DEF_DRV(SAVAGE_BCI_INIT, savage_bci_init, DRM_AUTH|DRM_MASTER|DRM_ROOT_ONLY), DRM_IOCTL_DEF_DRV(SAVAGE_BCI_CMDBUF, savage_bci_cmdbuf, DRM_AUTH), DRM_IOCTL_DEF_DRV(SAVAGE_BCI_EVENT_EMIT, savage_bci_event_emit, DRM_AUTH), DRM_IOCTL_DEF_DRV(SAVAGE_BCI_EVENT_WAIT, savage_bci_event_wait, DRM_AUTH), }; int savage_max_ioctl = DRM_ARRAY_SIZE(savage_ioctls);
kv193/buildroot
linux/linux-kernel/drivers/gpu/drm/savage/savage_bci.c
C
gpl-2.0
31,167
/* * Block driver for media (i.e., flash cards) * * Copyright 2002 Hewlett-Packard Company * Copyright 2005-2008 Pierre Ossman * * Use consistent with the GNU GPL is permitted, * provided that this copyright notice is * preserved in its entirety in all copies and derived works. * * HEWLETT-PACKARD COMPANY MAKES NO WARRANTIES, EXPRESSED OR IMPLIED, * AS TO THE USEFULNESS OR CORRECTNESS OF THIS CODE OR ITS * FITNESS FOR ANY PARTICULAR PURPOSE. * * Many thanks to Alessandro Rubini and Jonathan Corbet! * * Author: Andrew Christian * 28 May 2002 */ #include <linux/moduleparam.h> #include <linux/module.h> #include <linux/init.h> #include <linux/kernel.h> #include <linux/fs.h> #include <linux/slab.h> #include <linux/errno.h> #include <linux/hdreg.h> #include <linux/kdev_t.h> #include <linux/blkdev.h> #include <linux/mutex.h> #include <linux/scatterlist.h> #include <linux/string_helpers.h> #include <linux/delay.h> #include <linux/capability.h> #include <linux/compat.h> #include <linux/pm_runtime.h> #include <linux/mmc/ioctl.h> #include <linux/mmc/card.h> #include <linux/mmc/host.h> #include <linux/mmc/mmc.h> #include <linux/mmc/sd.h> #include <asm/uaccess.h> #include "queue.h" MODULE_ALIAS("mmc:block"); #ifdef MODULE_PARAM_PREFIX #undef MODULE_PARAM_PREFIX #endif #define MODULE_PARAM_PREFIX "mmcblk." #define INAND_CMD38_ARG_EXT_CSD 113 #define INAND_CMD38_ARG_ERASE 0x00 #define INAND_CMD38_ARG_TRIM 0x01 #define INAND_CMD38_ARG_SECERASE 0x80 #define INAND_CMD38_ARG_SECTRIM1 0x81 #define INAND_CMD38_ARG_SECTRIM2 0x88 #define MMC_BLK_TIMEOUT_MS (10 * 60 * 1000) /* 10 minute timeout */ #define MMC_SANITIZE_REQ_TIMEOUT 240000 #define MMC_EXTRACT_INDEX_FROM_ARG(x) ((x & 0x00FF0000) >> 16) #define mmc_req_rel_wr(req) (((req->cmd_flags & REQ_FUA) || \ (req->cmd_flags & REQ_META)) && \ (rq_data_dir(req) == WRITE)) #define PACKED_CMD_VER 0x01 #define PACKED_CMD_WR 0x02 static DEFINE_MUTEX(block_mutex); /* * The defaults come from config options but can be overriden by module * or bootarg options. */ static int perdev_minors = CONFIG_MMC_BLOCK_MINORS; /* * We've only got one major, so number of mmcblk devices is * limited to (1 << 20) / number of minors per device. It is also * currently limited by the size of the static bitmaps below. */ static int max_devices; #define MAX_DEVICES 256 /* TODO: Replace these with struct ida */ static DECLARE_BITMAP(dev_use, MAX_DEVICES); static DECLARE_BITMAP(name_use, MAX_DEVICES); /* * There is one mmc_blk_data per slot. */ struct mmc_blk_data { spinlock_t lock; struct gendisk *disk; struct mmc_queue queue; struct list_head part; unsigned int flags; #define MMC_BLK_CMD23 (1 << 0) /* Can do SET_BLOCK_COUNT for multiblock */ #define MMC_BLK_REL_WR (1 << 1) /* MMC Reliable write support */ #define MMC_BLK_PACKED_CMD (1 << 2) /* MMC packed command support */ unsigned int usage; unsigned int read_only; unsigned int part_type; unsigned int name_idx; unsigned int reset_done; #define MMC_BLK_READ BIT(0) #define MMC_BLK_WRITE BIT(1) #define MMC_BLK_DISCARD BIT(2) #define MMC_BLK_SECDISCARD BIT(3) /* * Only set in main mmc_blk_data associated * with mmc_card with dev_set_drvdata, and keeps * track of the current selected device partition. */ unsigned int part_curr; struct device_attribute force_ro; struct device_attribute power_ro_lock; int area_type; }; static DEFINE_MUTEX(open_lock); enum { MMC_PACKED_NR_IDX = -1, MMC_PACKED_NR_ZERO, MMC_PACKED_NR_SINGLE, }; module_param(perdev_minors, int, 0444); MODULE_PARM_DESC(perdev_minors, "Minors numbers to allocate per device"); static inline int mmc_blk_part_switch(struct mmc_card *card, struct mmc_blk_data *md); static int get_card_status(struct mmc_card *card, u32 *status, int retries); static inline void mmc_blk_clear_packed(struct mmc_queue_req *mqrq) { struct mmc_packed *packed = mqrq->packed; BUG_ON(!packed); mqrq->cmd_type = MMC_PACKED_NONE; packed->nr_entries = MMC_PACKED_NR_ZERO; packed->idx_failure = MMC_PACKED_NR_IDX; packed->retries = 0; packed->blocks = 0; } static struct mmc_blk_data *mmc_blk_get(struct gendisk *disk) { struct mmc_blk_data *md; mutex_lock(&open_lock); md = disk->private_data; if (md && md->usage == 0) md = NULL; if (md) md->usage++; mutex_unlock(&open_lock); return md; } static inline int mmc_get_devidx(struct gendisk *disk) { int devmaj = MAJOR(disk_devt(disk)); int devidx = MINOR(disk_devt(disk)) / perdev_minors; if (!devmaj) devidx = disk->first_minor / perdev_minors; return devidx; } static void mmc_blk_put(struct mmc_blk_data *md) { mutex_lock(&open_lock); md->usage--; if (md->usage == 0) { int devidx = mmc_get_devidx(md->disk); blk_cleanup_queue(md->queue.queue); __clear_bit(devidx, dev_use); put_disk(md->disk); kfree(md); } mutex_unlock(&open_lock); } static ssize_t power_ro_lock_show(struct device *dev, struct device_attribute *attr, char *buf) { int ret; struct mmc_blk_data *md = mmc_blk_get(dev_to_disk(dev)); struct mmc_card *card = md->queue.card; int locked = 0; if (card->ext_csd.boot_ro_lock & EXT_CSD_BOOT_WP_B_PERM_WP_EN) locked = 2; else if (card->ext_csd.boot_ro_lock & EXT_CSD_BOOT_WP_B_PWR_WP_EN) locked = 1; ret = snprintf(buf, PAGE_SIZE, "%d\n", locked); mmc_blk_put(md); return ret; } static ssize_t power_ro_lock_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { int ret; struct mmc_blk_data *md, *part_md; struct mmc_card *card; unsigned long set; if (kstrtoul(buf, 0, &set)) return -EINVAL; if (set != 1) return count; md = mmc_blk_get(dev_to_disk(dev)); card = md->queue.card; mmc_get_card(card); ret = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL, EXT_CSD_BOOT_WP, card->ext_csd.boot_ro_lock | EXT_CSD_BOOT_WP_B_PWR_WP_EN, card->ext_csd.part_time); if (ret) pr_err("%s: Locking boot partition ro until next power on failed: %d\n", md->disk->disk_name, ret); else card->ext_csd.boot_ro_lock |= EXT_CSD_BOOT_WP_B_PWR_WP_EN; mmc_put_card(card); if (!ret) { pr_info("%s: Locking boot partition ro until next power on\n", md->disk->disk_name); set_disk_ro(md->disk, 1); list_for_each_entry(part_md, &md->part, part) if (part_md->area_type == MMC_BLK_DATA_AREA_BOOT) { pr_info("%s: Locking boot partition ro until next power on\n", part_md->disk->disk_name); set_disk_ro(part_md->disk, 1); } } mmc_blk_put(md); return count; } static ssize_t force_ro_show(struct device *dev, struct device_attribute *attr, char *buf) { int ret; struct mmc_blk_data *md = mmc_blk_get(dev_to_disk(dev)); ret = snprintf(buf, PAGE_SIZE, "%d\n", get_disk_ro(dev_to_disk(dev)) ^ md->read_only); mmc_blk_put(md); return ret; } static ssize_t force_ro_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { int ret; char *end; struct mmc_blk_data *md = mmc_blk_get(dev_to_disk(dev)); unsigned long set = simple_strtoul(buf, &end, 0); if (end == buf) { ret = -EINVAL; goto out; } set_disk_ro(dev_to_disk(dev), set || md->read_only); ret = count; out: mmc_blk_put(md); return ret; } static int mmc_blk_open(struct block_device *bdev, fmode_t mode) { struct mmc_blk_data *md = mmc_blk_get(bdev->bd_disk); int ret = -ENXIO; mutex_lock(&block_mutex); if (md) { if (md->usage == 2) check_disk_change(bdev); ret = 0; if ((mode & FMODE_WRITE) && md->read_only) { mmc_blk_put(md); ret = -EROFS; } } mutex_unlock(&block_mutex); return ret; } static void mmc_blk_release(struct gendisk *disk, fmode_t mode) { struct mmc_blk_data *md = disk->private_data; mutex_lock(&block_mutex); mmc_blk_put(md); mutex_unlock(&block_mutex); } static int mmc_blk_getgeo(struct block_device *bdev, struct hd_geometry *geo) { geo->cylinders = get_capacity(bdev->bd_disk) / (4 * 16); geo->heads = 4; geo->sectors = 16; return 0; } struct mmc_blk_ioc_data { struct mmc_ioc_cmd ic; unsigned char *buf; u64 buf_bytes; }; static struct mmc_blk_ioc_data *mmc_blk_ioctl_copy_from_user( struct mmc_ioc_cmd __user *user) { struct mmc_blk_ioc_data *idata; int err; idata = kzalloc(sizeof(*idata), GFP_KERNEL); if (!idata) { err = -ENOMEM; goto out; } if (copy_from_user(&idata->ic, user, sizeof(idata->ic))) { err = -EFAULT; goto idata_err; } idata->buf_bytes = (u64) idata->ic.blksz * idata->ic.blocks; if (idata->buf_bytes > MMC_IOC_MAX_BYTES) { err = -EOVERFLOW; goto idata_err; } if (!idata->buf_bytes) return idata; idata->buf = kzalloc(idata->buf_bytes, GFP_KERNEL); if (!idata->buf) { err = -ENOMEM; goto idata_err; } if (copy_from_user(idata->buf, (void __user *)(unsigned long) idata->ic.data_ptr, idata->buf_bytes)) { err = -EFAULT; goto copy_err; } return idata; copy_err: kfree(idata->buf); idata_err: kfree(idata); out: return ERR_PTR(err); } static int ioctl_rpmb_card_status_poll(struct mmc_card *card, u32 *status, u32 retries_max) { int err; u32 retry_count = 0; if (!status || !retries_max) return -EINVAL; do { err = get_card_status(card, status, 5); if (err) break; if (!R1_STATUS(*status) && (R1_CURRENT_STATE(*status) != R1_STATE_PRG)) break; /* RPMB programming operation complete */ /* * Rechedule to give the MMC device a chance to continue * processing the previous command without being polled too * frequently. */ usleep_range(1000, 5000); } while (++retry_count < retries_max); if (retry_count == retries_max) err = -EPERM; return err; } static int ioctl_do_sanitize(struct mmc_card *card) { int err; if (!mmc_can_sanitize(card)) { pr_warn("%s: %s - SANITIZE is not supported\n", mmc_hostname(card->host), __func__); err = -EOPNOTSUPP; goto out; } pr_debug("%s: %s - SANITIZE IN PROGRESS...\n", mmc_hostname(card->host), __func__); err = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL, EXT_CSD_SANITIZE_START, 1, MMC_SANITIZE_REQ_TIMEOUT); if (err) pr_err("%s: %s - EXT_CSD_SANITIZE_START failed. err=%d\n", mmc_hostname(card->host), __func__, err); pr_debug("%s: %s - SANITIZE COMPLETED\n", mmc_hostname(card->host), __func__); out: return err; } static int mmc_blk_ioctl_cmd(struct block_device *bdev, struct mmc_ioc_cmd __user *ic_ptr) { struct mmc_blk_ioc_data *idata; struct mmc_blk_data *md; struct mmc_card *card; struct mmc_command cmd = {0}; struct mmc_data data = {0}; struct mmc_request mrq = {NULL}; struct scatterlist sg; int err; int is_rpmb = false; u32 status = 0; /* * The caller must have CAP_SYS_RAWIO, and must be calling this on the * whole block device, not on a partition. This prevents overspray * between sibling partitions. */ if ((!capable(CAP_SYS_RAWIO)) || (bdev != bdev->bd_contains)) return -EPERM; idata = mmc_blk_ioctl_copy_from_user(ic_ptr); if (IS_ERR(idata)) return PTR_ERR(idata); md = mmc_blk_get(bdev->bd_disk); if (!md) { err = -EINVAL; goto cmd_err; } if (md->area_type & MMC_BLK_DATA_AREA_RPMB) is_rpmb = true; card = md->queue.card; if (IS_ERR(card)) { err = PTR_ERR(card); goto cmd_done; } cmd.opcode = idata->ic.opcode; cmd.arg = idata->ic.arg; cmd.flags = idata->ic.flags; if (idata->buf_bytes) { data.sg = &sg; data.sg_len = 1; data.blksz = idata->ic.blksz; data.blocks = idata->ic.blocks; sg_init_one(data.sg, idata->buf, idata->buf_bytes); if (idata->ic.write_flag) data.flags = MMC_DATA_WRITE; else data.flags = MMC_DATA_READ; /* data.flags must already be set before doing this. */ mmc_set_data_timeout(&data, card); /* Allow overriding the timeout_ns for empirical tuning. */ if (idata->ic.data_timeout_ns) data.timeout_ns = idata->ic.data_timeout_ns; if ((cmd.flags & MMC_RSP_R1B) == MMC_RSP_R1B) { /* * Pretend this is a data transfer and rely on the * host driver to compute timeout. When all host * drivers support cmd.cmd_timeout for R1B, this * can be changed to: * * mrq.data = NULL; * cmd.cmd_timeout = idata->ic.cmd_timeout_ms; */ data.timeout_ns = idata->ic.cmd_timeout_ms * 1000000; } mrq.data = &data; } mrq.cmd = &cmd; mmc_get_card(card); err = mmc_blk_part_switch(card, md); if (err) goto cmd_rel_host; if (idata->ic.is_acmd) { err = mmc_app_cmd(card->host, card); if (err) goto cmd_rel_host; } if (is_rpmb) { err = mmc_set_blockcount(card, data.blocks, idata->ic.write_flag & (1 << 31)); if (err) goto cmd_rel_host; } if ((MMC_EXTRACT_INDEX_FROM_ARG(cmd.arg) == EXT_CSD_SANITIZE_START) && (cmd.opcode == MMC_SWITCH)) { err = ioctl_do_sanitize(card); if (err) pr_err("%s: ioctl_do_sanitize() failed. err = %d", __func__, err); goto cmd_rel_host; } mmc_wait_for_req(card->host, &mrq); if (cmd.error) { dev_err(mmc_dev(card->host), "%s: cmd error %d\n", __func__, cmd.error); err = cmd.error; goto cmd_rel_host; } if (data.error) { dev_err(mmc_dev(card->host), "%s: data error %d\n", __func__, data.error); err = data.error; goto cmd_rel_host; } /* * According to the SD specs, some commands require a delay after * issuing the command. */ if (idata->ic.postsleep_min_us) usleep_range(idata->ic.postsleep_min_us, idata->ic.postsleep_max_us); if (copy_to_user(&(ic_ptr->response), cmd.resp, sizeof(cmd.resp))) { err = -EFAULT; goto cmd_rel_host; } if (!idata->ic.write_flag) { if (copy_to_user((void __user *)(unsigned long) idata->ic.data_ptr, idata->buf, idata->buf_bytes)) { err = -EFAULT; goto cmd_rel_host; } } if (is_rpmb) { /* * Ensure RPMB command has completed by polling CMD13 * "Send Status". */ err = ioctl_rpmb_card_status_poll(card, &status, 5); if (err) dev_err(mmc_dev(card->host), "%s: Card Status=0x%08X, error %d\n", __func__, status, err); } cmd_rel_host: mmc_put_card(card); cmd_done: mmc_blk_put(md); cmd_err: kfree(idata->buf); kfree(idata); return err; } static int mmc_blk_ioctl(struct block_device *bdev, fmode_t mode, unsigned int cmd, unsigned long arg) { int ret = -EINVAL; if (cmd == MMC_IOC_CMD) ret = mmc_blk_ioctl_cmd(bdev, (struct mmc_ioc_cmd __user *)arg); return ret; } #ifdef CONFIG_COMPAT static int mmc_blk_compat_ioctl(struct block_device *bdev, fmode_t mode, unsigned int cmd, unsigned long arg) { return mmc_blk_ioctl(bdev, mode, cmd, (unsigned long) compat_ptr(arg)); } #endif static const struct block_device_operations mmc_bdops = { .open = mmc_blk_open, .release = mmc_blk_release, .getgeo = mmc_blk_getgeo, .owner = THIS_MODULE, .ioctl = mmc_blk_ioctl, #ifdef CONFIG_COMPAT .compat_ioctl = mmc_blk_compat_ioctl, #endif }; static inline int mmc_blk_part_switch(struct mmc_card *card, struct mmc_blk_data *md) { int ret; struct mmc_blk_data *main_md = dev_get_drvdata(&card->dev); if (main_md->part_curr == md->part_type) return 0; if (mmc_card_mmc(card)) { u8 part_config = card->ext_csd.part_config; part_config &= ~EXT_CSD_PART_CONFIG_ACC_MASK; part_config |= md->part_type; ret = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL, EXT_CSD_PART_CONFIG, part_config, card->ext_csd.part_time); if (ret) return ret; card->ext_csd.part_config = part_config; } main_md->part_curr = md->part_type; return 0; } static u32 mmc_sd_num_wr_blocks(struct mmc_card *card) { int err; u32 result; __be32 *blocks; struct mmc_request mrq = {NULL}; struct mmc_command cmd = {0}; struct mmc_data data = {0}; struct scatterlist sg; cmd.opcode = MMC_APP_CMD; cmd.arg = card->rca << 16; cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_AC; err = mmc_wait_for_cmd(card->host, &cmd, 0); if (err) return (u32)-1; if (!mmc_host_is_spi(card->host) && !(cmd.resp[0] & R1_APP_CMD)) return (u32)-1; memset(&cmd, 0, sizeof(struct mmc_command)); cmd.opcode = SD_APP_SEND_NUM_WR_BLKS; cmd.arg = 0; cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_ADTC; data.blksz = 4; data.blocks = 1; data.flags = MMC_DATA_READ; data.sg = &sg; data.sg_len = 1; mmc_set_data_timeout(&data, card); mrq.cmd = &cmd; mrq.data = &data; blocks = kmalloc(4, GFP_KERNEL); if (!blocks) return (u32)-1; sg_init_one(&sg, blocks, 4); mmc_wait_for_req(card->host, &mrq); result = ntohl(*blocks); kfree(blocks); if (cmd.error || data.error) result = (u32)-1; return result; } static int get_card_status(struct mmc_card *card, u32 *status, int retries) { struct mmc_command cmd = {0}; int err; cmd.opcode = MMC_SEND_STATUS; if (!mmc_host_is_spi(card->host)) cmd.arg = card->rca << 16; cmd.flags = MMC_RSP_SPI_R2 | MMC_RSP_R1 | MMC_CMD_AC; err = mmc_wait_for_cmd(card->host, &cmd, retries); if (err == 0) *status = cmd.resp[0]; return err; } static int card_busy_detect(struct mmc_card *card, unsigned int timeout_ms, bool hw_busy_detect, struct request *req, int *gen_err) { unsigned long timeout = jiffies + msecs_to_jiffies(timeout_ms); int err = 0; u32 status; do { err = get_card_status(card, &status, 5); if (err) { pr_err("%s: error %d requesting status\n", req->rq_disk->disk_name, err); return err; } if (status & R1_ERROR) { pr_err("%s: %s: error sending status cmd, status %#x\n", req->rq_disk->disk_name, __func__, status); *gen_err = 1; } /* We may rely on the host hw to handle busy detection.*/ if ((card->host->caps & MMC_CAP_WAIT_WHILE_BUSY) && hw_busy_detect) break; /* * Timeout if the device never becomes ready for data and never * leaves the program state. */ if (time_after(jiffies, timeout)) { pr_err("%s: Card stuck in programming state! %s %s\n", mmc_hostname(card->host), req->rq_disk->disk_name, __func__); return -ETIMEDOUT; } /* * Some cards mishandle the status bits, * so make sure to check both the busy * indication and the card state. */ } while (!(status & R1_READY_FOR_DATA) || (R1_CURRENT_STATE(status) == R1_STATE_PRG)); return err; } static int send_stop(struct mmc_card *card, unsigned int timeout_ms, struct request *req, int *gen_err, u32 *stop_status) { struct mmc_host *host = card->host; struct mmc_command cmd = {0}; int err; bool use_r1b_resp = rq_data_dir(req) == WRITE; /* * Normally we use R1B responses for WRITE, but in cases where the host * has specified a max_busy_timeout we need to validate it. A failure * means we need to prevent the host from doing hw busy detection, which * is done by converting to a R1 response instead. */ if (host->max_busy_timeout && (timeout_ms > host->max_busy_timeout)) use_r1b_resp = false; cmd.opcode = MMC_STOP_TRANSMISSION; if (use_r1b_resp) { cmd.flags = MMC_RSP_SPI_R1B | MMC_RSP_R1B | MMC_CMD_AC; cmd.busy_timeout = timeout_ms; } else { cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_AC; } err = mmc_wait_for_cmd(host, &cmd, 5); if (err) return err; *stop_status = cmd.resp[0]; /* No need to check card status in case of READ. */ if (rq_data_dir(req) == READ) return 0; if (!mmc_host_is_spi(host) && (*stop_status & R1_ERROR)) { pr_err("%s: %s: general error sending stop command, resp %#x\n", req->rq_disk->disk_name, __func__, *stop_status); *gen_err = 1; } return card_busy_detect(card, timeout_ms, use_r1b_resp, req, gen_err); } #define ERR_NOMEDIUM 3 #define ERR_RETRY 2 #define ERR_ABORT 1 #define ERR_CONTINUE 0 static int mmc_blk_cmd_error(struct request *req, const char *name, int error, bool status_valid, u32 status) { switch (error) { case -EILSEQ: /* response crc error, retry the r/w cmd */ pr_err("%s: %s sending %s command, card status %#x\n", req->rq_disk->disk_name, "response CRC error", name, status); return ERR_RETRY; case -ETIMEDOUT: pr_err("%s: %s sending %s command, card status %#x\n", req->rq_disk->disk_name, "timed out", name, status); /* If the status cmd initially failed, retry the r/w cmd */ if (!status_valid) return ERR_RETRY; /* * If it was a r/w cmd crc error, or illegal command * (eg, issued in wrong state) then retry - we should * have corrected the state problem above. */ if (status & (R1_COM_CRC_ERROR | R1_ILLEGAL_COMMAND)) return ERR_RETRY; /* Otherwise abort the command */ return ERR_ABORT; default: /* We don't understand the error code the driver gave us */ pr_err("%s: unknown error %d sending read/write command, card status %#x\n", req->rq_disk->disk_name, error, status); return ERR_ABORT; } } /* * Initial r/w and stop cmd error recovery. * We don't know whether the card received the r/w cmd or not, so try to * restore things back to a sane state. Essentially, we do this as follows: * - Obtain card status. If the first attempt to obtain card status fails, * the status word will reflect the failed status cmd, not the failed * r/w cmd. If we fail to obtain card status, it suggests we can no * longer communicate with the card. * - Check the card state. If the card received the cmd but there was a * transient problem with the response, it might still be in a data transfer * mode. Try to send it a stop command. If this fails, we can't recover. * - If the r/w cmd failed due to a response CRC error, it was probably * transient, so retry the cmd. * - If the r/w cmd timed out, but we didn't get the r/w cmd status, retry. * - If the r/w cmd timed out, and the r/w cmd failed due to CRC error or * illegal cmd, retry. * Otherwise we don't understand what happened, so abort. */ static int mmc_blk_cmd_recovery(struct mmc_card *card, struct request *req, struct mmc_blk_request *brq, int *ecc_err, int *gen_err) { bool prev_cmd_status_valid = true; u32 status, stop_status = 0; int err, retry; if (mmc_card_removed(card)) return ERR_NOMEDIUM; /* * Try to get card status which indicates both the card state * and why there was no response. If the first attempt fails, * we can't be sure the returned status is for the r/w command. */ for (retry = 2; retry >= 0; retry--) { err = get_card_status(card, &status, 0); if (!err) break; /* Re-tune if needed */ mmc_retune_recheck(card->host); prev_cmd_status_valid = false; pr_err("%s: error %d sending status command, %sing\n", req->rq_disk->disk_name, err, retry ? "retry" : "abort"); } /* We couldn't get a response from the card. Give up. */ if (err) { /* Check if the card is removed */ if (mmc_detect_card_removed(card->host)) return ERR_NOMEDIUM; return ERR_ABORT; } /* Flag ECC errors */ if ((status & R1_CARD_ECC_FAILED) || (brq->stop.resp[0] & R1_CARD_ECC_FAILED) || (brq->cmd.resp[0] & R1_CARD_ECC_FAILED)) *ecc_err = 1; /* Flag General errors */ if (!mmc_host_is_spi(card->host) && rq_data_dir(req) != READ) if ((status & R1_ERROR) || (brq->stop.resp[0] & R1_ERROR)) { pr_err("%s: %s: general error sending stop or status command, stop cmd response %#x, card status %#x\n", req->rq_disk->disk_name, __func__, brq->stop.resp[0], status); *gen_err = 1; } /* * Check the current card state. If it is in some data transfer * mode, tell it to stop (and hopefully transition back to TRAN.) */ if (R1_CURRENT_STATE(status) == R1_STATE_DATA || R1_CURRENT_STATE(status) == R1_STATE_RCV) { err = send_stop(card, DIV_ROUND_UP(brq->data.timeout_ns, 1000000), req, gen_err, &stop_status); if (err) { pr_err("%s: error %d sending stop command\n", req->rq_disk->disk_name, err); /* * If the stop cmd also timed out, the card is probably * not present, so abort. Other errors are bad news too. */ return ERR_ABORT; } if (stop_status & R1_CARD_ECC_FAILED) *ecc_err = 1; } /* Check for set block count errors */ if (brq->sbc.error) return mmc_blk_cmd_error(req, "SET_BLOCK_COUNT", brq->sbc.error, prev_cmd_status_valid, status); /* Check for r/w command errors */ if (brq->cmd.error) return mmc_blk_cmd_error(req, "r/w cmd", brq->cmd.error, prev_cmd_status_valid, status); /* Data errors */ if (!brq->stop.error) return ERR_CONTINUE; /* Now for stop errors. These aren't fatal to the transfer. */ pr_info("%s: error %d sending stop command, original cmd response %#x, card status %#x\n", req->rq_disk->disk_name, brq->stop.error, brq->cmd.resp[0], status); /* * Subsitute in our own stop status as this will give the error * state which happened during the execution of the r/w command. */ if (stop_status) { brq->stop.resp[0] = stop_status; brq->stop.error = 0; } return ERR_CONTINUE; } static int mmc_blk_reset(struct mmc_blk_data *md, struct mmc_host *host, int type) { int err; if (md->reset_done & type) return -EEXIST; md->reset_done |= type; err = mmc_hw_reset(host); /* Ensure we switch back to the correct partition */ if (err != -EOPNOTSUPP) { struct mmc_blk_data *main_md = dev_get_drvdata(&host->card->dev); int part_err; main_md->part_curr = main_md->part_type; part_err = mmc_blk_part_switch(host->card, md); if (part_err) { /* * We have failed to get back into the correct * partition, so we need to abort the whole request. */ return -ENODEV; } } return err; } static inline void mmc_blk_reset_success(struct mmc_blk_data *md, int type) { md->reset_done &= ~type; } int mmc_access_rpmb(struct mmc_queue *mq) { struct mmc_blk_data *md = mq->data; /* * If this is a RPMB partition access, return ture */ if (md && md->part_type == EXT_CSD_PART_CONFIG_ACC_RPMB) return true; return false; } static int mmc_blk_issue_discard_rq(struct mmc_queue *mq, struct request *req) { struct mmc_blk_data *md = mq->data; struct mmc_card *card = md->queue.card; unsigned int from, nr, arg; int err = 0, type = MMC_BLK_DISCARD; if (!mmc_can_erase(card)) { err = -EOPNOTSUPP; goto out; } from = blk_rq_pos(req); nr = blk_rq_sectors(req); if (mmc_can_discard(card)) arg = MMC_DISCARD_ARG; else if (mmc_can_trim(card)) arg = MMC_TRIM_ARG; else arg = MMC_ERASE_ARG; retry: if (card->quirks & MMC_QUIRK_INAND_CMD38) { err = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL, INAND_CMD38_ARG_EXT_CSD, arg == MMC_TRIM_ARG ? INAND_CMD38_ARG_TRIM : INAND_CMD38_ARG_ERASE, 0); if (err) goto out; } err = mmc_erase(card, from, nr, arg); out: if (err == -EIO && !mmc_blk_reset(md, card->host, type)) goto retry; if (!err) mmc_blk_reset_success(md, type); blk_end_request(req, err, blk_rq_bytes(req)); return err ? 0 : 1; } static int mmc_blk_issue_secdiscard_rq(struct mmc_queue *mq, struct request *req) { struct mmc_blk_data *md = mq->data; struct mmc_card *card = md->queue.card; unsigned int from, nr, arg; int err = 0, type = MMC_BLK_SECDISCARD; if (!(mmc_can_secure_erase_trim(card))) { err = -EOPNOTSUPP; goto out; } from = blk_rq_pos(req); nr = blk_rq_sectors(req); if (mmc_can_trim(card) && !mmc_erase_group_aligned(card, from, nr)) arg = MMC_SECURE_TRIM1_ARG; else arg = MMC_SECURE_ERASE_ARG; retry: if (card->quirks & MMC_QUIRK_INAND_CMD38) { err = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL, INAND_CMD38_ARG_EXT_CSD, arg == MMC_SECURE_TRIM1_ARG ? INAND_CMD38_ARG_SECTRIM1 : INAND_CMD38_ARG_SECERASE, 0); if (err) goto out_retry; } err = mmc_erase(card, from, nr, arg); if (err == -EIO) goto out_retry; if (err) goto out; if (arg == MMC_SECURE_TRIM1_ARG) { if (card->quirks & MMC_QUIRK_INAND_CMD38) { err = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL, INAND_CMD38_ARG_EXT_CSD, INAND_CMD38_ARG_SECTRIM2, 0); if (err) goto out_retry; } err = mmc_erase(card, from, nr, MMC_SECURE_TRIM2_ARG); if (err == -EIO) goto out_retry; if (err) goto out; } out_retry: if (err && !mmc_blk_reset(md, card->host, type)) goto retry; if (!err) mmc_blk_reset_success(md, type); out: blk_end_request(req, err, blk_rq_bytes(req)); return err ? 0 : 1; } static int mmc_blk_issue_flush(struct mmc_queue *mq, struct request *req) { struct mmc_blk_data *md = mq->data; struct mmc_card *card = md->queue.card; int ret = 0; ret = mmc_flush_cache(card); if (ret) ret = -EIO; blk_end_request_all(req, ret); return ret ? 0 : 1; } /* * Reformat current write as a reliable write, supporting * both legacy and the enhanced reliable write MMC cards. * In each transfer we'll handle only as much as a single * reliable write can handle, thus finish the request in * partial completions. */ static inline void mmc_apply_rel_rw(struct mmc_blk_request *brq, struct mmc_card *card, struct request *req) { if (!(card->ext_csd.rel_param & EXT_CSD_WR_REL_PARAM_EN)) { /* Legacy mode imposes restrictions on transfers. */ if (!IS_ALIGNED(brq->cmd.arg, card->ext_csd.rel_sectors)) brq->data.blocks = 1; if (brq->data.blocks > card->ext_csd.rel_sectors) brq->data.blocks = card->ext_csd.rel_sectors; else if (brq->data.blocks < card->ext_csd.rel_sectors) brq->data.blocks = 1; } } #define CMD_ERRORS \ (R1_OUT_OF_RANGE | /* Command argument out of range */ \ R1_ADDRESS_ERROR | /* Misaligned address */ \ R1_BLOCK_LEN_ERROR | /* Transferred block length incorrect */\ R1_WP_VIOLATION | /* Tried to write to protected block */ \ R1_CC_ERROR | /* Card controller error */ \ R1_ERROR) /* General/unknown error */ static int mmc_blk_err_check(struct mmc_card *card, struct mmc_async_req *areq) { struct mmc_queue_req *mq_mrq = container_of(areq, struct mmc_queue_req, mmc_active); struct mmc_blk_request *brq = &mq_mrq->brq; struct request *req = mq_mrq->req; int need_retune = card->host->need_retune; int ecc_err = 0, gen_err = 0; /* * sbc.error indicates a problem with the set block count * command. No data will have been transferred. * * cmd.error indicates a problem with the r/w command. No * data will have been transferred. * * stop.error indicates a problem with the stop command. Data * may have been transferred, or may still be transferring. */ if (brq->sbc.error || brq->cmd.error || brq->stop.error || brq->data.error) { switch (mmc_blk_cmd_recovery(card, req, brq, &ecc_err, &gen_err)) { case ERR_RETRY: return MMC_BLK_RETRY; case ERR_ABORT: return MMC_BLK_ABORT; case ERR_NOMEDIUM: return MMC_BLK_NOMEDIUM; case ERR_CONTINUE: break; } } /* * Check for errors relating to the execution of the * initial command - such as address errors. No data * has been transferred. */ if (brq->cmd.resp[0] & CMD_ERRORS) { pr_err("%s: r/w command failed, status = %#x\n", req->rq_disk->disk_name, brq->cmd.resp[0]); return MMC_BLK_ABORT; } /* * Everything else is either success, or a data error of some * kind. If it was a write, we may have transitioned to * program mode, which we have to wait for it to complete. */ if (!mmc_host_is_spi(card->host) && rq_data_dir(req) != READ) { int err; /* Check stop command response */ if (brq->stop.resp[0] & R1_ERROR) { pr_err("%s: %s: general error sending stop command, stop cmd response %#x\n", req->rq_disk->disk_name, __func__, brq->stop.resp[0]); gen_err = 1; } err = card_busy_detect(card, MMC_BLK_TIMEOUT_MS, false, req, &gen_err); if (err) return MMC_BLK_CMD_ERR; } /* if general error occurs, retry the write operation. */ if (gen_err) { pr_warn("%s: retrying write for general error\n", req->rq_disk->disk_name); return MMC_BLK_RETRY; } if (brq->data.error) { if (need_retune && !brq->retune_retry_done) { pr_info("%s: retrying because a re-tune was needed\n", req->rq_disk->disk_name); brq->retune_retry_done = 1; return MMC_BLK_RETRY; } pr_err("%s: error %d transferring data, sector %u, nr %u, cmd response %#x, card status %#x\n", req->rq_disk->disk_name, brq->data.error, (unsigned)blk_rq_pos(req), (unsigned)blk_rq_sectors(req), brq->cmd.resp[0], brq->stop.resp[0]); if (rq_data_dir(req) == READ) { if (ecc_err) return MMC_BLK_ECC_ERR; return MMC_BLK_DATA_ERR; } else { return MMC_BLK_CMD_ERR; } } if (!brq->data.bytes_xfered) return MMC_BLK_RETRY; if (mmc_packed_cmd(mq_mrq->cmd_type)) { if (unlikely(brq->data.blocks << 9 != brq->data.bytes_xfered)) return MMC_BLK_PARTIAL; else return MMC_BLK_SUCCESS; } if (blk_rq_bytes(req) != brq->data.bytes_xfered) return MMC_BLK_PARTIAL; return MMC_BLK_SUCCESS; } static int mmc_blk_packed_err_check(struct mmc_card *card, struct mmc_async_req *areq) { struct mmc_queue_req *mq_rq = container_of(areq, struct mmc_queue_req, mmc_active); struct request *req = mq_rq->req; struct mmc_packed *packed = mq_rq->packed; int err, check, status; u8 *ext_csd; BUG_ON(!packed); packed->retries--; check = mmc_blk_err_check(card, areq); err = get_card_status(card, &status, 0); if (err) { pr_err("%s: error %d sending status command\n", req->rq_disk->disk_name, err); return MMC_BLK_ABORT; } if (status & R1_EXCEPTION_EVENT) { err = mmc_get_ext_csd(card, &ext_csd); if (err) { pr_err("%s: error %d sending ext_csd\n", req->rq_disk->disk_name, err); return MMC_BLK_ABORT; } if ((ext_csd[EXT_CSD_EXP_EVENTS_STATUS] & EXT_CSD_PACKED_FAILURE) && (ext_csd[EXT_CSD_PACKED_CMD_STATUS] & EXT_CSD_PACKED_GENERIC_ERROR)) { if (ext_csd[EXT_CSD_PACKED_CMD_STATUS] & EXT_CSD_PACKED_INDEXED_ERROR) { packed->idx_failure = ext_csd[EXT_CSD_PACKED_FAILURE_INDEX] - 1; check = MMC_BLK_PARTIAL; } pr_err("%s: packed cmd failed, nr %u, sectors %u, " "failure index: %d\n", req->rq_disk->disk_name, packed->nr_entries, packed->blocks, packed->idx_failure); } kfree(ext_csd); } return check; } static void mmc_blk_rw_rq_prep(struct mmc_queue_req *mqrq, struct mmc_card *card, int disable_multi, struct mmc_queue *mq) { u32 readcmd, writecmd; struct mmc_blk_request *brq = &mqrq->brq; struct request *req = mqrq->req; struct mmc_blk_data *md = mq->data; bool do_data_tag; /* * Reliable writes are used to implement Forced Unit Access and * REQ_META accesses, and are supported only on MMCs. * * XXX: this really needs a good explanation of why REQ_META * is treated special. */ bool do_rel_wr = ((req->cmd_flags & REQ_FUA) || (req->cmd_flags & REQ_META)) && (rq_data_dir(req) == WRITE) && (md->flags & MMC_BLK_REL_WR); memset(brq, 0, sizeof(struct mmc_blk_request)); brq->mrq.cmd = &brq->cmd; brq->mrq.data = &brq->data; brq->cmd.arg = blk_rq_pos(req); if (!mmc_card_blockaddr(card)) brq->cmd.arg <<= 9; brq->cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_ADTC; brq->data.blksz = 512; brq->stop.opcode = MMC_STOP_TRANSMISSION; brq->stop.arg = 0; brq->data.blocks = blk_rq_sectors(req); /* * The block layer doesn't support all sector count * restrictions, so we need to be prepared for too big * requests. */ if (brq->data.blocks > card->host->max_blk_count) brq->data.blocks = card->host->max_blk_count; if (brq->data.blocks > 1) { /* * After a read error, we redo the request one sector * at a time in order to accurately determine which * sectors can be read successfully. */ if (disable_multi) brq->data.blocks = 1; /* * Some controllers have HW issues while operating * in multiple I/O mode */ if (card->host->ops->multi_io_quirk) brq->data.blocks = card->host->ops->multi_io_quirk(card, (rq_data_dir(req) == READ) ? MMC_DATA_READ : MMC_DATA_WRITE, brq->data.blocks); } if (brq->data.blocks > 1 || do_rel_wr) { /* SPI multiblock writes terminate using a special * token, not a STOP_TRANSMISSION request. */ if (!mmc_host_is_spi(card->host) || rq_data_dir(req) == READ) brq->mrq.stop = &brq->stop; readcmd = MMC_READ_MULTIPLE_BLOCK; writecmd = MMC_WRITE_MULTIPLE_BLOCK; } else { brq->mrq.stop = NULL; readcmd = MMC_READ_SINGLE_BLOCK; writecmd = MMC_WRITE_BLOCK; } if (rq_data_dir(req) == READ) { brq->cmd.opcode = readcmd; brq->data.flags |= MMC_DATA_READ; if (brq->mrq.stop) brq->stop.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_AC; } else { brq->cmd.opcode = writecmd; brq->data.flags |= MMC_DATA_WRITE; if (brq->mrq.stop) brq->stop.flags = MMC_RSP_SPI_R1B | MMC_RSP_R1B | MMC_CMD_AC; } if (do_rel_wr) mmc_apply_rel_rw(brq, card, req); /* * Data tag is used only during writing meta data to speed * up write and any subsequent read of this meta data */ do_data_tag = (card->ext_csd.data_tag_unit_size) && (req->cmd_flags & REQ_META) && (rq_data_dir(req) == WRITE) && ((brq->data.blocks * brq->data.blksz) >= card->ext_csd.data_tag_unit_size); /* * Pre-defined multi-block transfers are preferable to * open ended-ones (and necessary for reliable writes). * However, it is not sufficient to just send CMD23, * and avoid the final CMD12, as on an error condition * CMD12 (stop) needs to be sent anyway. This, coupled * with Auto-CMD23 enhancements provided by some * hosts, means that the complexity of dealing * with this is best left to the host. If CMD23 is * supported by card and host, we'll fill sbc in and let * the host deal with handling it correctly. This means * that for hosts that don't expose MMC_CAP_CMD23, no * change of behavior will be observed. * * N.B: Some MMC cards experience perf degradation. * We'll avoid using CMD23-bounded multiblock writes for * these, while retaining features like reliable writes. */ if ((md->flags & MMC_BLK_CMD23) && mmc_op_multi(brq->cmd.opcode) && (do_rel_wr || !(card->quirks & MMC_QUIRK_BLK_NO_CMD23) || do_data_tag)) { brq->sbc.opcode = MMC_SET_BLOCK_COUNT; brq->sbc.arg = brq->data.blocks | (do_rel_wr ? (1 << 31) : 0) | (do_data_tag ? (1 << 29) : 0); brq->sbc.flags = MMC_RSP_R1 | MMC_CMD_AC; brq->mrq.sbc = &brq->sbc; } mmc_set_data_timeout(&brq->data, card); brq->data.sg = mqrq->sg; brq->data.sg_len = mmc_queue_map_sg(mq, mqrq); /* * Adjust the sg list so it is the same size as the * request. */ if (brq->data.blocks != blk_rq_sectors(req)) { int i, data_size = brq->data.blocks << 9; struct scatterlist *sg; for_each_sg(brq->data.sg, sg, brq->data.sg_len, i) { data_size -= sg->length; if (data_size <= 0) { sg->length += data_size; i++; break; } } brq->data.sg_len = i; } mqrq->mmc_active.mrq = &brq->mrq; mqrq->mmc_active.err_check = mmc_blk_err_check; mmc_queue_bounce_pre(mqrq); } static inline u8 mmc_calc_packed_hdr_segs(struct request_queue *q, struct mmc_card *card) { unsigned int hdr_sz = mmc_large_sector(card) ? 4096 : 512; unsigned int max_seg_sz = queue_max_segment_size(q); unsigned int len, nr_segs = 0; do { len = min(hdr_sz, max_seg_sz); hdr_sz -= len; nr_segs++; } while (hdr_sz); return nr_segs; } static u8 mmc_blk_prep_packed_list(struct mmc_queue *mq, struct request *req) { struct request_queue *q = mq->queue; struct mmc_card *card = mq->card; struct request *cur = req, *next = NULL; struct mmc_blk_data *md = mq->data; struct mmc_queue_req *mqrq = mq->mqrq_cur; bool en_rel_wr = card->ext_csd.rel_param & EXT_CSD_WR_REL_PARAM_EN; unsigned int req_sectors = 0, phys_segments = 0; unsigned int max_blk_count, max_phys_segs; bool put_back = true; u8 max_packed_rw = 0; u8 reqs = 0; if (!(md->flags & MMC_BLK_PACKED_CMD)) goto no_packed; if ((rq_data_dir(cur) == WRITE) && mmc_host_packed_wr(card->host)) max_packed_rw = card->ext_csd.max_packed_writes; if (max_packed_rw == 0) goto no_packed; if (mmc_req_rel_wr(cur) && (md->flags & MMC_BLK_REL_WR) && !en_rel_wr) goto no_packed; if (mmc_large_sector(card) && !IS_ALIGNED(blk_rq_sectors(cur), 8)) goto no_packed; mmc_blk_clear_packed(mqrq); max_blk_count = min(card->host->max_blk_count, card->host->max_req_size >> 9); if (unlikely(max_blk_count > 0xffff)) max_blk_count = 0xffff; max_phys_segs = queue_max_segments(q); req_sectors += blk_rq_sectors(cur); phys_segments += cur->nr_phys_segments; if (rq_data_dir(cur) == WRITE) { req_sectors += mmc_large_sector(card) ? 8 : 1; phys_segments += mmc_calc_packed_hdr_segs(q, card); } do { if (reqs >= max_packed_rw - 1) { put_back = false; break; } spin_lock_irq(q->queue_lock); next = blk_fetch_request(q); spin_unlock_irq(q->queue_lock); if (!next) { put_back = false; break; } if (mmc_large_sector(card) && !IS_ALIGNED(blk_rq_sectors(next), 8)) break; if (next->cmd_flags & REQ_DISCARD || next->cmd_flags & REQ_FLUSH) break; if (rq_data_dir(cur) != rq_data_dir(next)) break; if (mmc_req_rel_wr(next) && (md->flags & MMC_BLK_REL_WR) && !en_rel_wr) break; req_sectors += blk_rq_sectors(next); if (req_sectors > max_blk_count) break; phys_segments += next->nr_phys_segments; if (phys_segments > max_phys_segs) break; list_add_tail(&next->queuelist, &mqrq->packed->list); cur = next; reqs++; } while (1); if (put_back) { spin_lock_irq(q->queue_lock); blk_requeue_request(q, next); spin_unlock_irq(q->queue_lock); } if (reqs > 0) { list_add(&req->queuelist, &mqrq->packed->list); mqrq->packed->nr_entries = ++reqs; mqrq->packed->retries = reqs; return reqs; } no_packed: mqrq->cmd_type = MMC_PACKED_NONE; return 0; } static void mmc_blk_packed_hdr_wrq_prep(struct mmc_queue_req *mqrq, struct mmc_card *card, struct mmc_queue *mq) { struct mmc_blk_request *brq = &mqrq->brq; struct request *req = mqrq->req; struct request *prq; struct mmc_blk_data *md = mq->data; struct mmc_packed *packed = mqrq->packed; bool do_rel_wr, do_data_tag; u32 *packed_cmd_hdr; u8 hdr_blocks; u8 i = 1; BUG_ON(!packed); mqrq->cmd_type = MMC_PACKED_WRITE; packed->blocks = 0; packed->idx_failure = MMC_PACKED_NR_IDX; packed_cmd_hdr = packed->cmd_hdr; memset(packed_cmd_hdr, 0, sizeof(packed->cmd_hdr)); packed_cmd_hdr[0] = (packed->nr_entries << 16) | (PACKED_CMD_WR << 8) | PACKED_CMD_VER; hdr_blocks = mmc_large_sector(card) ? 8 : 1; /* * Argument for each entry of packed group */ list_for_each_entry(prq, &packed->list, queuelist) { do_rel_wr = mmc_req_rel_wr(prq) && (md->flags & MMC_BLK_REL_WR); do_data_tag = (card->ext_csd.data_tag_unit_size) && (prq->cmd_flags & REQ_META) && (rq_data_dir(prq) == WRITE) && ((brq->data.blocks * brq->data.blksz) >= card->ext_csd.data_tag_unit_size); /* Argument of CMD23 */ packed_cmd_hdr[(i * 2)] = (do_rel_wr ? MMC_CMD23_ARG_REL_WR : 0) | (do_data_tag ? MMC_CMD23_ARG_TAG_REQ : 0) | blk_rq_sectors(prq); /* Argument of CMD18 or CMD25 */ packed_cmd_hdr[((i * 2)) + 1] = mmc_card_blockaddr(card) ? blk_rq_pos(prq) : blk_rq_pos(prq) << 9; packed->blocks += blk_rq_sectors(prq); i++; } memset(brq, 0, sizeof(struct mmc_blk_request)); brq->mrq.cmd = &brq->cmd; brq->mrq.data = &brq->data; brq->mrq.sbc = &brq->sbc; brq->mrq.stop = &brq->stop; brq->sbc.opcode = MMC_SET_BLOCK_COUNT; brq->sbc.arg = MMC_CMD23_ARG_PACKED | (packed->blocks + hdr_blocks); brq->sbc.flags = MMC_RSP_R1 | MMC_CMD_AC; brq->cmd.opcode = MMC_WRITE_MULTIPLE_BLOCK; brq->cmd.arg = blk_rq_pos(req); if (!mmc_card_blockaddr(card)) brq->cmd.arg <<= 9; brq->cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_ADTC; brq->data.blksz = 512; brq->data.blocks = packed->blocks + hdr_blocks; brq->data.flags |= MMC_DATA_WRITE; brq->stop.opcode = MMC_STOP_TRANSMISSION; brq->stop.arg = 0; brq->stop.flags = MMC_RSP_SPI_R1B | MMC_RSP_R1B | MMC_CMD_AC; mmc_set_data_timeout(&brq->data, card); brq->data.sg = mqrq->sg; brq->data.sg_len = mmc_queue_map_sg(mq, mqrq); mqrq->mmc_active.mrq = &brq->mrq; mqrq->mmc_active.err_check = mmc_blk_packed_err_check; mmc_queue_bounce_pre(mqrq); } static int mmc_blk_cmd_err(struct mmc_blk_data *md, struct mmc_card *card, struct mmc_blk_request *brq, struct request *req, int ret) { struct mmc_queue_req *mq_rq; mq_rq = container_of(brq, struct mmc_queue_req, brq); /* * If this is an SD card and we're writing, we can first * mark the known good sectors as ok. * * If the card is not SD, we can still ok written sectors * as reported by the controller (which might be less than * the real number of written sectors, but never more). */ if (mmc_card_sd(card)) { u32 blocks; blocks = mmc_sd_num_wr_blocks(card); if (blocks != (u32)-1) { ret = blk_end_request(req, 0, blocks << 9); } } else { if (!mmc_packed_cmd(mq_rq->cmd_type)) ret = blk_end_request(req, 0, brq->data.bytes_xfered); } return ret; } static int mmc_blk_end_packed_req(struct mmc_queue_req *mq_rq) { struct request *prq; struct mmc_packed *packed = mq_rq->packed; int idx = packed->idx_failure, i = 0; int ret = 0; BUG_ON(!packed); while (!list_empty(&packed->list)) { prq = list_entry_rq(packed->list.next); if (idx == i) { /* retry from error index */ packed->nr_entries -= idx; mq_rq->req = prq; ret = 1; if (packed->nr_entries == MMC_PACKED_NR_SINGLE) { list_del_init(&prq->queuelist); mmc_blk_clear_packed(mq_rq); } return ret; } list_del_init(&prq->queuelist); blk_end_request(prq, 0, blk_rq_bytes(prq)); i++; } mmc_blk_clear_packed(mq_rq); return ret; } static void mmc_blk_abort_packed_req(struct mmc_queue_req *mq_rq) { struct request *prq; struct mmc_packed *packed = mq_rq->packed; BUG_ON(!packed); while (!list_empty(&packed->list)) { prq = list_entry_rq(packed->list.next); list_del_init(&prq->queuelist); blk_end_request(prq, -EIO, blk_rq_bytes(prq)); } mmc_blk_clear_packed(mq_rq); } static void mmc_blk_revert_packed_req(struct mmc_queue *mq, struct mmc_queue_req *mq_rq) { struct request *prq; struct request_queue *q = mq->queue; struct mmc_packed *packed = mq_rq->packed; BUG_ON(!packed); while (!list_empty(&packed->list)) { prq = list_entry_rq(packed->list.prev); if (prq->queuelist.prev != &packed->list) { list_del_init(&prq->queuelist); spin_lock_irq(q->queue_lock); blk_requeue_request(mq->queue, prq); spin_unlock_irq(q->queue_lock); } else { list_del_init(&prq->queuelist); } } mmc_blk_clear_packed(mq_rq); } static int mmc_blk_issue_rw_rq(struct mmc_queue *mq, struct request *rqc) { struct mmc_blk_data *md = mq->data; struct mmc_card *card = md->queue.card; struct mmc_blk_request *brq = &mq->mqrq_cur->brq; int ret = 1, disable_multi = 0, retry = 0, type, retune_retry_done = 0; enum mmc_blk_status status; struct mmc_queue_req *mq_rq; struct request *req = rqc; struct mmc_async_req *areq; const u8 packed_nr = 2; u8 reqs = 0; if (!rqc && !mq->mqrq_prev->req) return 0; if (rqc) reqs = mmc_blk_prep_packed_list(mq, rqc); do { if (rqc) { /* * When 4KB native sector is enabled, only 8 blocks * multiple read or write is allowed */ if ((brq->data.blocks & 0x07) && (card->ext_csd.data_sector_size == 4096)) { pr_err("%s: Transfer size is not 4KB sector size aligned\n", req->rq_disk->disk_name); mq_rq = mq->mqrq_cur; goto cmd_abort; } if (reqs >= packed_nr) mmc_blk_packed_hdr_wrq_prep(mq->mqrq_cur, card, mq); else mmc_blk_rw_rq_prep(mq->mqrq_cur, card, 0, mq); areq = &mq->mqrq_cur->mmc_active; } else areq = NULL; areq = mmc_start_req(card->host, areq, (int *) &status); if (!areq) { if (status == MMC_BLK_NEW_REQUEST) mq->flags |= MMC_QUEUE_NEW_REQUEST; return 0; } mq_rq = container_of(areq, struct mmc_queue_req, mmc_active); brq = &mq_rq->brq; req = mq_rq->req; type = rq_data_dir(req) == READ ? MMC_BLK_READ : MMC_BLK_WRITE; mmc_queue_bounce_post(mq_rq); switch (status) { case MMC_BLK_SUCCESS: case MMC_BLK_PARTIAL: /* * A block was successfully transferred. */ mmc_blk_reset_success(md, type); if (mmc_packed_cmd(mq_rq->cmd_type)) { ret = mmc_blk_end_packed_req(mq_rq); break; } else { ret = blk_end_request(req, 0, brq->data.bytes_xfered); } /* * If the blk_end_request function returns non-zero even * though all data has been transferred and no errors * were returned by the host controller, it's a bug. */ if (status == MMC_BLK_SUCCESS && ret) { pr_err("%s BUG rq_tot %d d_xfer %d\n", __func__, blk_rq_bytes(req), brq->data.bytes_xfered); rqc = NULL; goto cmd_abort; } break; case MMC_BLK_CMD_ERR: ret = mmc_blk_cmd_err(md, card, brq, req, ret); if (mmc_blk_reset(md, card->host, type)) goto cmd_abort; if (!ret) goto start_new_req; break; case MMC_BLK_RETRY: retune_retry_done = brq->retune_retry_done; if (retry++ < 5) break; /* Fall through */ case MMC_BLK_ABORT: if (!mmc_blk_reset(md, card->host, type)) break; goto cmd_abort; case MMC_BLK_DATA_ERR: { int err; err = mmc_blk_reset(md, card->host, type); if (!err) break; if (err == -ENODEV || mmc_packed_cmd(mq_rq->cmd_type)) goto cmd_abort; /* Fall through */ } case MMC_BLK_ECC_ERR: if (brq->data.blocks > 1) { /* Redo read one sector at a time */ pr_warn("%s: retrying using single block read\n", req->rq_disk->disk_name); disable_multi = 1; break; } /* * After an error, we redo I/O one sector at a * time, so we only reach here after trying to * read a single sector. */ ret = blk_end_request(req, -EIO, brq->data.blksz); if (!ret) goto start_new_req; break; case MMC_BLK_NOMEDIUM: goto cmd_abort; default: pr_err("%s: Unhandled return value (%d)", req->rq_disk->disk_name, status); goto cmd_abort; } if (ret) { if (mmc_packed_cmd(mq_rq->cmd_type)) { if (!mq_rq->packed->retries) goto cmd_abort; mmc_blk_packed_hdr_wrq_prep(mq_rq, card, mq); mmc_start_req(card->host, &mq_rq->mmc_active, NULL); } else { /* * In case of a incomplete request * prepare it again and resend. */ mmc_blk_rw_rq_prep(mq_rq, card, disable_multi, mq); mmc_start_req(card->host, &mq_rq->mmc_active, NULL); } mq_rq->brq.retune_retry_done = retune_retry_done; } } while (ret); return 1; cmd_abort: if (mmc_packed_cmd(mq_rq->cmd_type)) { mmc_blk_abort_packed_req(mq_rq); } else { if (mmc_card_removed(card)) req->cmd_flags |= REQ_QUIET; while (ret) ret = blk_end_request(req, -EIO, blk_rq_cur_bytes(req)); } start_new_req: if (rqc) { if (mmc_card_removed(card)) { rqc->cmd_flags |= REQ_QUIET; blk_end_request_all(rqc, -EIO); } else { /* * If current request is packed, it needs to put back. */ if (mmc_packed_cmd(mq->mqrq_cur->cmd_type)) mmc_blk_revert_packed_req(mq, mq->mqrq_cur); mmc_blk_rw_rq_prep(mq->mqrq_cur, card, 0, mq); mmc_start_req(card->host, &mq->mqrq_cur->mmc_active, NULL); } } return 0; } static int mmc_blk_issue_rq(struct mmc_queue *mq, struct request *req) { int ret; struct mmc_blk_data *md = mq->data; struct mmc_card *card = md->queue.card; struct mmc_host *host = card->host; unsigned long flags; unsigned int cmd_flags = req ? req->cmd_flags : 0; if (req && !mq->mqrq_prev->req) /* claim host only for the first request */ mmc_get_card(card); ret = mmc_blk_part_switch(card, md); if (ret) { if (req) { blk_end_request_all(req, -EIO); } ret = 0; goto out; } mq->flags &= ~MMC_QUEUE_NEW_REQUEST; if (cmd_flags & REQ_DISCARD) { /* complete ongoing async transfer before issuing discard */ if (card->host->areq) mmc_blk_issue_rw_rq(mq, NULL); if (req->cmd_flags & REQ_SECURE) ret = mmc_blk_issue_secdiscard_rq(mq, req); else ret = mmc_blk_issue_discard_rq(mq, req); } else if (cmd_flags & REQ_FLUSH) { /* complete ongoing async transfer before issuing flush */ if (card->host->areq) mmc_blk_issue_rw_rq(mq, NULL); ret = mmc_blk_issue_flush(mq, req); } else { if (!req && host->areq) { spin_lock_irqsave(&host->context_info.lock, flags); host->context_info.is_waiting_last_req = true; spin_unlock_irqrestore(&host->context_info.lock, flags); } ret = mmc_blk_issue_rw_rq(mq, req); } out: if ((!req && !(mq->flags & MMC_QUEUE_NEW_REQUEST)) || (cmd_flags & MMC_REQ_SPECIAL_MASK)) /* * Release host when there are no more requests * and after special request(discard, flush) is done. * In case sepecial request, there is no reentry to * the 'mmc_blk_issue_rq' with 'mqrq_prev->req'. */ mmc_put_card(card); return ret; } static inline int mmc_blk_readonly(struct mmc_card *card) { return mmc_card_readonly(card) || !(card->csd.cmdclass & CCC_BLOCK_WRITE); } static struct mmc_blk_data *mmc_blk_alloc_req(struct mmc_card *card, struct device *parent, sector_t size, bool default_ro, const char *subname, int area_type) { struct mmc_blk_data *md; int devidx, ret; devidx = find_first_zero_bit(dev_use, max_devices); if (devidx >= max_devices) return ERR_PTR(-ENOSPC); __set_bit(devidx, dev_use); md = kzalloc(sizeof(struct mmc_blk_data), GFP_KERNEL); if (!md) { ret = -ENOMEM; goto out; } /* * !subname implies we are creating main mmc_blk_data that will be * associated with mmc_card with dev_set_drvdata. Due to device * partitions, devidx will not coincide with a per-physical card * index anymore so we keep track of a name index. */ if (!subname) { int idx; idx = mmc_get_reserved_index(card->host); if (idx >= 0 && !test_bit(idx, name_use)) md->name_idx = idx; else md->name_idx = find_next_zero_bit(name_use, max_devices, mmc_first_nonreserved_index()); __set_bit(md->name_idx, name_use); } else md->name_idx = ((struct mmc_blk_data *) dev_to_disk(parent)->private_data)->name_idx; md->area_type = area_type; /* * Set the read-only status based on the supported commands * and the write protect switch. */ md->read_only = mmc_blk_readonly(card); md->disk = alloc_disk(perdev_minors); if (md->disk == NULL) { ret = -ENOMEM; goto err_kfree; } spin_lock_init(&md->lock); INIT_LIST_HEAD(&md->part); md->usage = 1; ret = mmc_init_queue(&md->queue, card, &md->lock, subname); if (ret) goto err_putdisk; md->queue.issue_fn = mmc_blk_issue_rq; md->queue.data = md; md->disk->major = MMC_BLOCK_MAJOR; md->disk->first_minor = devidx * perdev_minors; md->disk->fops = &mmc_bdops; md->disk->private_data = md; md->disk->queue = md->queue.queue; md->disk->driverfs_dev = parent; set_disk_ro(md->disk, md->read_only || default_ro); if (area_type & (MMC_BLK_DATA_AREA_RPMB | MMC_BLK_DATA_AREA_BOOT)) md->disk->flags |= GENHD_FL_NO_PART_SCAN; /* * As discussed on lkml, GENHD_FL_REMOVABLE should: * * - be set for removable media with permanent block devices * - be unset for removable block devices with permanent media * * Since MMC block devices clearly fall under the second * case, we do not set GENHD_FL_REMOVABLE. Userspace * should use the block device creation/destruction hotplug * messages to tell when the card is present. */ snprintf(md->disk->disk_name, sizeof(md->disk->disk_name), "mmcblk%u%s", md->name_idx, subname ? subname : ""); if (mmc_card_mmc(card)) blk_queue_logical_block_size(md->queue.queue, card->ext_csd.data_sector_size); else blk_queue_logical_block_size(md->queue.queue, 512); set_capacity(md->disk, size); if (mmc_host_cmd23(card->host)) { if (mmc_card_mmc(card) || (mmc_card_sd(card) && card->scr.cmds & SD_SCR_CMD23_SUPPORT)) md->flags |= MMC_BLK_CMD23; } if (mmc_card_mmc(card) && md->flags & MMC_BLK_CMD23 && ((card->ext_csd.rel_param & EXT_CSD_WR_REL_PARAM_EN) || card->ext_csd.rel_sectors)) { md->flags |= MMC_BLK_REL_WR; blk_queue_flush(md->queue.queue, REQ_FLUSH | REQ_FUA); } if (mmc_card_mmc(card) && (area_type == MMC_BLK_DATA_AREA_MAIN) && (md->flags & MMC_BLK_CMD23) && card->ext_csd.packed_event_en) { if (!mmc_packed_init(&md->queue, card)) md->flags |= MMC_BLK_PACKED_CMD; } return md; err_putdisk: put_disk(md->disk); err_kfree: kfree(md); out: return ERR_PTR(ret); } static struct mmc_blk_data *mmc_blk_alloc(struct mmc_card *card) { sector_t size; if (!mmc_card_sd(card) && mmc_card_blockaddr(card)) { /* * The EXT_CSD sector count is in number or 512 byte * sectors. */ size = card->ext_csd.sectors; } else { /* * The CSD capacity field is in units of read_blkbits. * set_capacity takes units of 512 bytes. */ size = (typeof(sector_t))card->csd.capacity << (card->csd.read_blkbits - 9); } return mmc_blk_alloc_req(card, &card->dev, size, false, NULL, MMC_BLK_DATA_AREA_MAIN); } static int mmc_blk_alloc_part(struct mmc_card *card, struct mmc_blk_data *md, unsigned int part_type, sector_t size, bool default_ro, const char *subname, int area_type) { char cap_str[10]; struct mmc_blk_data *part_md; part_md = mmc_blk_alloc_req(card, disk_to_dev(md->disk), size, default_ro, subname, area_type); if (IS_ERR(part_md)) return PTR_ERR(part_md); part_md->part_type = part_type; list_add(&part_md->part, &md->part); string_get_size((u64)get_capacity(part_md->disk), 512, STRING_UNITS_2, cap_str, sizeof(cap_str)); pr_info("%s: %s %s partition %u %s\n", part_md->disk->disk_name, mmc_card_id(card), mmc_card_name(card), part_md->part_type, cap_str); return 0; } /* MMC Physical partitions consist of two boot partitions and * up to four general purpose partitions. * For each partition enabled in EXT_CSD a block device will be allocatedi * to provide access to the partition. */ static int mmc_blk_alloc_parts(struct mmc_card *card, struct mmc_blk_data *md) { int idx, ret = 0; if (!mmc_card_mmc(card)) return 0; for (idx = 0; idx < card->nr_parts; idx++) { if (card->part[idx].size) { ret = mmc_blk_alloc_part(card, md, card->part[idx].part_cfg, card->part[idx].size >> 9, card->part[idx].force_ro, card->part[idx].name, card->part[idx].area_type); if (ret) return ret; } } return ret; } static void mmc_blk_remove_req(struct mmc_blk_data *md) { struct mmc_card *card; if (md) { /* * Flush remaining requests and free queues. It * is freeing the queue that stops new requests * from being accepted. */ card = md->queue.card; mmc_cleanup_queue(&md->queue); if (md->flags & MMC_BLK_PACKED_CMD) mmc_packed_clean(&md->queue); if (md->disk->flags & GENHD_FL_UP) { device_remove_file(disk_to_dev(md->disk), &md->force_ro); if ((md->area_type & MMC_BLK_DATA_AREA_BOOT) && card->ext_csd.boot_ro_lockable) device_remove_file(disk_to_dev(md->disk), &md->power_ro_lock); del_gendisk(md->disk); } mmc_blk_put(md); } } static void mmc_blk_remove_parts(struct mmc_card *card, struct mmc_blk_data *md) { struct list_head *pos, *q; struct mmc_blk_data *part_md; __clear_bit(md->name_idx, name_use); list_for_each_safe(pos, q, &md->part) { part_md = list_entry(pos, struct mmc_blk_data, part); list_del(pos); mmc_blk_remove_req(part_md); } } static int mmc_add_disk(struct mmc_blk_data *md) { int ret; struct mmc_card *card = md->queue.card; add_disk(md->disk); md->force_ro.show = force_ro_show; md->force_ro.store = force_ro_store; sysfs_attr_init(&md->force_ro.attr); md->force_ro.attr.name = "force_ro"; md->force_ro.attr.mode = S_IRUGO | S_IWUSR; ret = device_create_file(disk_to_dev(md->disk), &md->force_ro); if (ret) goto force_ro_fail; if ((md->area_type & MMC_BLK_DATA_AREA_BOOT) && card->ext_csd.boot_ro_lockable) { umode_t mode; if (card->ext_csd.boot_ro_lock & EXT_CSD_BOOT_WP_B_PWR_WP_DIS) mode = S_IRUGO; else mode = S_IRUGO | S_IWUSR; md->power_ro_lock.show = power_ro_lock_show; md->power_ro_lock.store = power_ro_lock_store; sysfs_attr_init(&md->power_ro_lock.attr); md->power_ro_lock.attr.mode = mode; md->power_ro_lock.attr.name = "ro_lock_until_next_power_on"; ret = device_create_file(disk_to_dev(md->disk), &md->power_ro_lock); if (ret) goto power_ro_lock_fail; } return ret; power_ro_lock_fail: device_remove_file(disk_to_dev(md->disk), &md->force_ro); force_ro_fail: del_gendisk(md->disk); return ret; } #define CID_MANFID_SANDISK 0x2 #define CID_MANFID_TOSHIBA 0x11 #define CID_MANFID_MICRON 0x13 #define CID_MANFID_SAMSUNG 0x15 static const struct mmc_fixup blk_fixups[] = { MMC_FIXUP("SEM02G", CID_MANFID_SANDISK, 0x100, add_quirk, MMC_QUIRK_INAND_CMD38), MMC_FIXUP("SEM04G", CID_MANFID_SANDISK, 0x100, add_quirk, MMC_QUIRK_INAND_CMD38), MMC_FIXUP("SEM08G", CID_MANFID_SANDISK, 0x100, add_quirk, MMC_QUIRK_INAND_CMD38), MMC_FIXUP("SEM16G", CID_MANFID_SANDISK, 0x100, add_quirk, MMC_QUIRK_INAND_CMD38), MMC_FIXUP("SEM32G", CID_MANFID_SANDISK, 0x100, add_quirk, MMC_QUIRK_INAND_CMD38), /* * Some MMC cards experience performance degradation with CMD23 * instead of CMD12-bounded multiblock transfers. For now we'll * black list what's bad... * - Certain Toshiba cards. * * N.B. This doesn't affect SD cards. */ MMC_FIXUP("SDMB-32", CID_MANFID_SANDISK, CID_OEMID_ANY, add_quirk_mmc, MMC_QUIRK_BLK_NO_CMD23), MMC_FIXUP("SDM032", CID_MANFID_SANDISK, CID_OEMID_ANY, add_quirk_mmc, MMC_QUIRK_BLK_NO_CMD23), MMC_FIXUP("MMC08G", CID_MANFID_TOSHIBA, CID_OEMID_ANY, add_quirk_mmc, MMC_QUIRK_BLK_NO_CMD23), MMC_FIXUP("MMC16G", CID_MANFID_TOSHIBA, CID_OEMID_ANY, add_quirk_mmc, MMC_QUIRK_BLK_NO_CMD23), MMC_FIXUP("MMC32G", CID_MANFID_TOSHIBA, CID_OEMID_ANY, add_quirk_mmc, MMC_QUIRK_BLK_NO_CMD23), /* * Some Micron MMC cards needs longer data read timeout than * indicated in CSD. */ MMC_FIXUP(CID_NAME_ANY, CID_MANFID_MICRON, 0x200, add_quirk_mmc, MMC_QUIRK_LONG_READ_TIME), /* * On these Samsung MoviNAND parts, performing secure erase or * secure trim can result in unrecoverable corruption due to a * firmware bug. */ MMC_FIXUP("M8G2FA", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc, MMC_QUIRK_SEC_ERASE_TRIM_BROKEN), MMC_FIXUP("MAG4FA", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc, MMC_QUIRK_SEC_ERASE_TRIM_BROKEN), MMC_FIXUP("MBG8FA", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc, MMC_QUIRK_SEC_ERASE_TRIM_BROKEN), MMC_FIXUP("MCGAFA", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc, MMC_QUIRK_SEC_ERASE_TRIM_BROKEN), MMC_FIXUP("VAL00M", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc, MMC_QUIRK_SEC_ERASE_TRIM_BROKEN), MMC_FIXUP("VYL00M", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc, MMC_QUIRK_SEC_ERASE_TRIM_BROKEN), MMC_FIXUP("KYL00M", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc, MMC_QUIRK_SEC_ERASE_TRIM_BROKEN), MMC_FIXUP("VZL00M", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc, MMC_QUIRK_SEC_ERASE_TRIM_BROKEN), END_FIXUP }; static int mmc_blk_probe(struct mmc_card *card) { struct mmc_blk_data *md, *part_md; char cap_str[10]; /* * Check that the card supports the command class(es) we need. */ if (!(card->csd.cmdclass & CCC_BLOCK_READ)) return -ENODEV; mmc_fixup_device(card, blk_fixups); md = mmc_blk_alloc(card); if (IS_ERR(md)) return PTR_ERR(md); string_get_size((u64)get_capacity(md->disk), 512, STRING_UNITS_2, cap_str, sizeof(cap_str)); pr_info("%s: %s %s %s %s\n", md->disk->disk_name, mmc_card_id(card), mmc_card_name(card), cap_str, md->read_only ? "(ro)" : ""); if (mmc_blk_alloc_parts(card, md)) goto out; dev_set_drvdata(&card->dev, md); if (mmc_add_disk(md)) goto out; list_for_each_entry(part_md, &md->part, part) { if (mmc_add_disk(part_md)) goto out; } pm_runtime_set_autosuspend_delay(&card->dev, 3000); pm_runtime_use_autosuspend(&card->dev); /* * Don't enable runtime PM for SD-combo cards here. Leave that * decision to be taken during the SDIO init sequence instead. */ if (card->type != MMC_TYPE_SD_COMBO) { pm_runtime_set_active(&card->dev); pm_runtime_enable(&card->dev); } return 0; out: mmc_blk_remove_parts(card, md); mmc_blk_remove_req(md); return 0; } static void mmc_blk_remove(struct mmc_card *card) { struct mmc_blk_data *md = dev_get_drvdata(&card->dev); mmc_blk_remove_parts(card, md); pm_runtime_get_sync(&card->dev); mmc_claim_host(card->host); mmc_blk_part_switch(card, md); mmc_release_host(card->host); if (card->type != MMC_TYPE_SD_COMBO) pm_runtime_disable(&card->dev); pm_runtime_put_noidle(&card->dev); mmc_blk_remove_req(md); dev_set_drvdata(&card->dev, NULL); } static int _mmc_blk_suspend(struct mmc_card *card) { struct mmc_blk_data *part_md; struct mmc_blk_data *md = dev_get_drvdata(&card->dev); if (md) { mmc_queue_suspend(&md->queue); list_for_each_entry(part_md, &md->part, part) { mmc_queue_suspend(&part_md->queue); } } return 0; } static void mmc_blk_shutdown(struct mmc_card *card) { _mmc_blk_suspend(card); } #ifdef CONFIG_PM_SLEEP static int mmc_blk_suspend(struct device *dev) { struct mmc_card *card = mmc_dev_to_card(dev); return _mmc_blk_suspend(card); } static int mmc_blk_resume(struct device *dev) { struct mmc_blk_data *part_md; struct mmc_blk_data *md = dev_get_drvdata(dev); if (md) { /* * Resume involves the card going into idle state, * so current partition is always the main one. */ md->part_curr = md->part_type; mmc_queue_resume(&md->queue); list_for_each_entry(part_md, &md->part, part) { mmc_queue_resume(&part_md->queue); } } return 0; } #endif static SIMPLE_DEV_PM_OPS(mmc_blk_pm_ops, mmc_blk_suspend, mmc_blk_resume); static struct mmc_driver mmc_driver = { .drv = { .name = "mmcblk", .pm = &mmc_blk_pm_ops, }, .probe = mmc_blk_probe, .remove = mmc_blk_remove, .shutdown = mmc_blk_shutdown, }; static int __init mmc_blk_init(void) { int res; if (perdev_minors != CONFIG_MMC_BLOCK_MINORS) pr_info("mmcblk: using %d minors per device\n", perdev_minors); max_devices = min(MAX_DEVICES, (1 << MINORBITS) / perdev_minors); res = register_blkdev(MMC_BLOCK_MAJOR, "mmc"); if (res) goto out; res = mmc_register_driver(&mmc_driver); if (res) goto out2; return 0; out2: unregister_blkdev(MMC_BLOCK_MAJOR, "mmc"); out: return res; } static void __exit mmc_blk_exit(void) { mmc_unregister_driver(&mmc_driver); unregister_blkdev(MMC_BLOCK_MAJOR, "mmc"); } module_init(mmc_blk_init); module_exit(mmc_blk_exit); MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("Multimedia Card (MMC) block device driver");
npf-ati/linux-2.6-imx
drivers/mmc/card/block.c
C
gpl-2.0
67,016
/* * Copyright (C) 2007 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. */ /******************************************************************************* * * Filename: * --------- * AudDrv_Clk.c * * Project: * -------- * MT6583 Audio Driver clock control implement * * Description: * ------------ * Audio register * * Author: * ------- * Chipeng Chang (MTK02308) * *------------------------------------------------------------------------------ * $Revision: #1 $ * $Modtime:$ * $Log:$ * * *******************************************************************************/ /***************************************************************************** * C O M P I L E R F L A G S *****************************************************************************/ /***************************************************************************** * E X T E R N A L R E F E R E N C E S *****************************************************************************/ #include <mach/mt_clkmgr.h> #include <mach/mt_pm_ldo.h> #include <mach/pmic_mt6325_sw.h> #include <mach/upmu_common.h> #include <mach/upmu_hw.h> #include "AudDrv_Common.h" #include "AudDrv_Clk.h" #include "AudDrv_Afe.h" #include <linux/spinlock.h> #include <linux/delay.h> /***************************************************************************** * D A T A T Y P E S *****************************************************************************/ int Aud_Core_Clk_cntr = 0; int Aud_AFE_Clk_cntr = 0; int Aud_I2S_Clk_cntr = 0; int Aud_ADC_Clk_cntr = 0; int Aud_ADC2_Clk_cntr = 0; int Aud_ADC3_Clk_cntr = 0; int Aud_ANA_Clk_cntr = 0; int Aud_HDMI_Clk_cntr = 0; int Aud_APLL22M_Clk_cntr = 0; int Aud_APLL24M_Clk_cntr = 0; int Aud_APLL1_Tuner_cntr = 0; int Aud_APLL2_Tuner_cntr = 0; static int Aud_EMI_cntr = 0; static DEFINE_SPINLOCK(auddrv_Clk_lock); // amp mutex lock static DEFINE_MUTEX(auddrv_pmic_mutex); static DEFINE_MUTEX(audEMI_Clk_mutex); extern void disable_dpidle_by_bit(int id); extern void disable_soidle_by_bit(int id); extern void enable_dpidle_by_bit(int id); extern void enable_soidle_by_bit(int id); void AudDrv_Clk_AllOn(void) { unsigned long flags; printk("AudDrv_Clk_AllOn \n"); spin_lock_irqsave(&auddrv_Clk_lock, flags); Afe_Set_Reg(AUDIO_TOP_CON0, 0x00004000, 0xffffffff); spin_unlock_irqrestore(&auddrv_Clk_lock, flags); } void Auddrv_Bus_Init(void) { unsigned long flags; printk("%s \n", __func__); spin_lock_irqsave(&auddrv_Clk_lock, flags); Afe_Set_Reg(AUDIO_TOP_CON0, 0x00004000, 0x00004000); //must set, system will default set bit14 to 0 spin_unlock_irqrestore(&auddrv_Clk_lock, flags); } /***************************************************************************** * FUNCTION * AudDrv_Clk_Power_On / AudDrv_Clk_Power_Off * * DESCRIPTION * Power on this function , then all register can be access and set. * ***************************************************************************** */ void AudDrv_Clk_Power_On(void) { volatile uint32 *AFE_Register = (volatile uint32 *)Get_Afe_Powertop_Pointer(); volatile uint32 val_tmp; printk("%s", __func__); val_tmp = 0xd; mt_reg_sync_writel(val_tmp, AFE_Register); } void AudDrv_Clk_Power_Off(void) { } /***************************************************************************** * FUNCTION * AudDrv_Clk_On / AudDrv_Clk_Off * * DESCRIPTION * Enable/Disable PLL(26M clock) \ AFE clock * ***************************************************************************** */ void AudDrv_Clk_On(void) { unsigned long flags; PRINTK_AUD_CLK("+AudDrv_Clk_On, Aud_AFE_Clk_cntr:%d \n",Aud_AFE_Clk_cntr); spin_lock_irqsave(&auddrv_Clk_lock, flags); if (Aud_AFE_Clk_cntr == 0) { printk("-----------AudDrv_Clk_On, Aud_AFE_Clk_cntr:%d \n", Aud_AFE_Clk_cntr); #ifdef PM_MANAGER_API if (enable_clock(MT_CG_INFRA_AUDIO, "AUDIO")) { xlog_printk(ANDROID_LOG_ERROR, "Sound", "Aud enable_clock MT_CG_INFRA_AUDIO fail !!!\n"); } if (enable_clock(MT_CG_AUDIO_AFE, "AUDIO")) { xlog_printk(ANDROID_LOG_ERROR, "Sound", "Aud enable_clock MT_CG_AUDIO_AFE fail !!!\n"); } #else SetInfraCfg(AUDIO_CG_CLR, 0x2000000, 0x2000000); //bit 25=0, without 133m master and 66m slave bus clock cg gating Afe_Set_Reg(AUDIO_TOP_CON0, 0x4000, 0x06004044); #endif } Aud_AFE_Clk_cntr++; spin_unlock_irqrestore(&auddrv_Clk_lock, flags); PRINTK_AUD_CLK("-AudDrv_Clk_On, Aud_AFE_Clk_cntr:%d \n",Aud_AFE_Clk_cntr); } void AudDrv_Clk_Off(void) { unsigned long flags; PRINTK_AUD_CLK("+!! AudDrv_Clk_Off, Aud_AFE_Clk_cntr:%d \n",Aud_AFE_Clk_cntr); spin_lock_irqsave(&auddrv_Clk_lock, flags); Aud_AFE_Clk_cntr--; if (Aud_AFE_Clk_cntr == 0) { printk("------------AudDrv_Clk_Off, Aud_AFE_Clk_cntr:%d \n", Aud_AFE_Clk_cntr); { // Disable AFE clock #ifdef PM_MANAGER_API if (disable_clock(MT_CG_AUDIO_AFE, "AUDIO")) { xlog_printk(ANDROID_LOG_ERROR, "Sound", "disable_clock MT_CG_AUDIO_AFE fail"); } if (disable_clock(MT_CG_INFRA_AUDIO, "AUDIO")) { xlog_printk(ANDROID_LOG_ERROR, "Sound", "disable_clock MT_CG_INFRA_AUDIO fail !!!\n"); } #else Afe_Set_Reg(AUDIO_TOP_CON0, 0x06000044, 0x06000044); SetInfraCfg(AUDIO_CG_SET, 0x2000000, 0x2000000); //bit25=1, with 133m mastesr and 66m slave bus clock cg gating #endif } } else if (Aud_AFE_Clk_cntr < 0) { PRINTK_AUD_ERROR("!! AudDrv_Clk_Off, Aud_AFE_Clk_cntr<0 (%d) \n", Aud_AFE_Clk_cntr); AUDIO_ASSERT(true); Aud_AFE_Clk_cntr = 0; } PRINTK_AUD_CLK("-!! AudDrv_Clk_Off, Aud_AFE_Clk_cntr:%d \n",Aud_AFE_Clk_cntr); spin_unlock_irqrestore(&auddrv_Clk_lock, flags); } /***************************************************************************** * FUNCTION * AudDrv_ANA_Clk_On / AudDrv_ANA_Clk_Off * * DESCRIPTION * Enable/Disable analog part clock * *****************************************************************************/ void AudDrv_ANA_Clk_On(void) { mutex_lock(&auddrv_pmic_mutex); if (Aud_ANA_Clk_cntr == 0) { PRINTK_AUD_CLK("+AudDrv_ANA_Clk_On, Aud_ANA_Clk_cntr:%d \n", Aud_ANA_Clk_cntr); } Aud_ANA_Clk_cntr++; mutex_unlock(&auddrv_pmic_mutex); //PRINTK_AUD_CLK("-AudDrv_ANA_Clk_Off, Aud_ANA_Clk_cntr:%d \n",Aud_ANA_Clk_cntr); } void AudDrv_ANA_Clk_Off(void) { //PRINTK_AUD_CLK("+AudDrv_ANA_Clk_Off, Aud_ADC_Clk_cntr:%d \n", Aud_ANA_Clk_cntr); mutex_lock(&auddrv_pmic_mutex); Aud_ANA_Clk_cntr--; if (Aud_ANA_Clk_cntr == 0) { PRINTK_AUD_CLK("+AudDrv_ANA_Clk_Off disable_clock Ana clk(%x)\n", Aud_ANA_Clk_cntr); // Disable ADC clock #ifdef PM_MANAGER_API #else // TODO:: open ADC clock.... #endif } else if (Aud_ANA_Clk_cntr < 0) { PRINTK_AUD_ERROR("!! AudDrv_ANA_Clk_Off, Aud_ADC_Clk_cntr<0 (%d) \n", Aud_ANA_Clk_cntr); AUDIO_ASSERT(true); Aud_ANA_Clk_cntr = 0; } mutex_unlock(&auddrv_pmic_mutex); //PRINTK_AUD_CLK("-AudDrv_ANA_Clk_Off, Aud_ADC_Clk_cntr:%d \n", Aud_ANA_Clk_cntr); } /***************************************************************************** * FUNCTION * AudDrv_ADC_Clk_On / AudDrv_ADC_Clk_Off * * DESCRIPTION * Enable/Disable analog part clock * *****************************************************************************/ void AudDrv_ADC_Clk_On(void) { //PRINTK_AUDDRV("+AudDrv_ADC_Clk_On, Aud_ADC_Clk_cntr:%d \n", Aud_ADC_Clk_cntr); mutex_lock(&auddrv_pmic_mutex); if (Aud_ADC_Clk_cntr == 0) { PRINTK_AUDDRV("+AudDrv_ADC_Clk_On enable_clock ADC clk(%x)\n", Aud_ADC_Clk_cntr); Afe_Set_Reg(AUDIO_TOP_CON0, 0 << 24 , 1 << 24); } Aud_ADC_Clk_cntr++; mutex_unlock(&auddrv_pmic_mutex); } void AudDrv_ADC_Clk_Off(void) { //PRINTK_AUDDRV("+AudDrv_ADC_Clk_Off, Aud_ADC_Clk_cntr:%d \n", Aud_ADC_Clk_cntr); mutex_lock(&auddrv_pmic_mutex); Aud_ADC_Clk_cntr--; if (Aud_ADC_Clk_cntr == 0) { PRINTK_AUDDRV("+AudDrv_ADC_Clk_On disable_clock ADC clk(%x)\n", Aud_ADC_Clk_cntr); Afe_Set_Reg(AUDIO_TOP_CON0, 1 << 24 , 1 << 24); } if (Aud_ADC_Clk_cntr < 0) { PRINTK_AUDDRV("!! AudDrv_ADC_Clk_Off, Aud_ADC_Clk_cntr<0 (%d) \n", Aud_ADC_Clk_cntr); Aud_ADC_Clk_cntr = 0; } mutex_unlock(&auddrv_pmic_mutex); //PRINTK_AUDDRV("-AudDrv_ADC_Clk_Off, Aud_ADC_Clk_cntr:%d \n", Aud_ADC_Clk_cntr); } /***************************************************************************** * FUNCTION * AudDrv_ADC2_Clk_On / AudDrv_ADC2_Clk_Off * * DESCRIPTION * Enable/Disable clock * *****************************************************************************/ void AudDrv_ADC2_Clk_On(void) { PRINTK_AUD_CLK("+%s %d \n", __func__, Aud_ADC2_Clk_cntr); mutex_lock(&auddrv_pmic_mutex); if (Aud_ADC2_Clk_cntr == 0) { PRINTK_AUDDRV("+%s enable_clock ADC clk(%x)\n", __func__, Aud_ADC2_Clk_cntr); #if 0 //K2 removed #ifdef PM_MANAGER_API if (enable_clock(MT_CG_AUDIO_ADDA2, "AUDIO")) { PRINTK_AUD_CLK("%s fail", __func__); } #else Afe_Set_Reg(AUDIO_TOP_CON0, 0 << 23 , 1 << 23); //temp hard code setting, after confirm with enable clock usage, this could be removed. #endif #endif } Aud_ADC2_Clk_cntr++; mutex_unlock(&auddrv_pmic_mutex); } void AudDrv_ADC2_Clk_Off(void) { //PRINTK_AUDDRV("+%s %d \n", __func__,Aud_ADC2_Clk_cntr); mutex_lock(&auddrv_pmic_mutex); Aud_ADC2_Clk_cntr--; if (Aud_ADC2_Clk_cntr == 0) { PRINTK_AUDDRV("+%s disable_clock ADC clk(%x)\n", __func__, Aud_ADC2_Clk_cntr); #if 0 //K2 removed #ifdef PM_MANAGER_API if (disable_clock(MT_CG_AUDIO_ADDA2, "AUDIO")) { PRINTK_AUD_CLK("%s fail", __func__); } #else Afe_Set_Reg(AUDIO_TOP_CON0, 1 << 23 , 1 << 23); //temp hard code setting, after confirm with enable clock usage, this could be removed. #endif #endif } if (Aud_ADC2_Clk_cntr < 0) { PRINTK_AUDDRV("%s <0 (%d) \n", __func__, Aud_ADC2_Clk_cntr); Aud_ADC2_Clk_cntr = 0; } mutex_unlock(&auddrv_pmic_mutex); //PRINTK_AUDDRV("-AudDrv_ADC_Clk_Off, Aud_ADC_Clk_cntr:%d \n", Aud_ADC_Clk_cntr); } /***************************************************************************** * FUNCTION * AudDrv_ADC3_Clk_On / AudDrv_ADC3_Clk_Off * * DESCRIPTION * Enable/Disable clock * *****************************************************************************/ void AudDrv_ADC3_Clk_On(void) { PRINTK_AUD_CLK("+%s %d \n", __func__, Aud_ADC3_Clk_cntr); mutex_lock(&auddrv_pmic_mutex); if (Aud_ADC3_Clk_cntr == 0) { PRINTK_AUDDRV("+%s enable_clock ADC clk(%x)\n", __func__, Aud_ADC3_Clk_cntr); #if 0 //K2 removed #ifdef PM_MANAGER_API if (enable_clock(MT_CG_AUDIO_ADDA3, "AUDIO")) { PRINTK_AUD_CLK("%s fail", __func__); } #endif #endif } Aud_ADC2_Clk_cntr++; mutex_unlock(&auddrv_pmic_mutex); } void AudDrv_ADC3_Clk_Off(void) { //PRINTK_AUDDRV("+%s %d \n", __func__,Aud_ADC2_Clk_cntr); mutex_lock(&auddrv_pmic_mutex); Aud_ADC3_Clk_cntr--; if (Aud_ADC3_Clk_cntr == 0) { PRINTK_AUDDRV("+%s disable_clock ADC clk(%x)\n", __func__, Aud_ADC3_Clk_cntr); #if 0 //K2 removed #ifdef PM_MANAGER_API if (disable_clock(MT_CG_AUDIO_ADDA3, "AUDIO")) { PRINTK_AUD_CLK("%s fail", __func__); } #endif #endif } if (Aud_ADC3_Clk_cntr < 0) { PRINTK_AUDDRV("%s <0 (%d) \n", __func__, Aud_ADC3_Clk_cntr); Aud_ADC3_Clk_cntr = 0; } mutex_unlock(&auddrv_pmic_mutex); //PRINTK_AUDDRV("-AudDrv_ADC_Clk_Off, Aud_ADC_Clk_cntr:%d \n", Aud_ADC_Clk_cntr); } /***************************************************************************** * FUNCTION * AudDrv_APLL22M_Clk_On / AudDrv_APLL22M_Clk_Off * * DESCRIPTION * Enable/Disable clock * *****************************************************************************/ void AudDrv_APLL22M_Clk_On(void) { PRINTK_AUD_CLK("+%s %d \n", __func__, Aud_APLL22M_Clk_cntr); mutex_lock(&auddrv_pmic_mutex); if (Aud_APLL22M_Clk_cntr == 0) { PRINTK_AUDDRV("+%s enable_clock ADC clk(%x)\n", __func__, Aud_APLL22M_Clk_cntr); #ifdef PM_MANAGER_API enable_mux(MT_MUX_AUD1, "AUDIO"); clkmux_sel(MT_MUX_AUD1, 1 , "AUDIO"); //select APLL1 if (enable_clock(MT_CG_AUDIO_22M, "AUDIO")) { PRINTK_AUD_CLK("%s fail", __func__); } if (enable_clock(MT_CG_AUDIO_APLL_TUNER, "AUDIO")) { PRINTK_AUD_CLK("%s fail", __func__); } #endif } Aud_APLL22M_Clk_cntr++; mutex_unlock(&auddrv_pmic_mutex); } void AudDrv_APLL22M_Clk_Off(void) { mutex_lock(&auddrv_pmic_mutex); Aud_APLL22M_Clk_cntr--; if (Aud_APLL22M_Clk_cntr == 0) { PRINTK_AUDDRV("+%s disable_clock ADC clk(%x)\n", __func__, Aud_APLL22M_Clk_cntr); #ifdef PM_MANAGER_API if (disable_clock(MT_CG_AUDIO_22M, "AUDIO")) { PRINTK_AUD_CLK("%s fail", __func__); } if (disable_clock(MT_CG_AUDIO_APLL_TUNER, "AUDIO")) { PRINTK_AUD_CLK("%s fail", __func__); } clkmux_sel(MT_MUX_AUD1, 0, "AUDIO"); //select 26M disable_mux(MT_MUX_AUD1, "AUDIO"); #endif } if (Aud_APLL22M_Clk_cntr < 0) { PRINTK_AUDDRV("%s <0 (%d) \n", __func__, Aud_APLL22M_Clk_cntr); Aud_APLL22M_Clk_cntr = 0; } mutex_unlock(&auddrv_pmic_mutex); } /***************************************************************************** * FUNCTION * AudDrv_APLL24M_Clk_On / AudDrv_APLL24M_Clk_Off * * DESCRIPTION * Enable/Disable clock * *****************************************************************************/ void AudDrv_APLL24M_Clk_On(void) { PRINTK_AUD_CLK("+%s %d \n", __func__, Aud_APLL24M_Clk_cntr); mutex_lock(&auddrv_pmic_mutex); if (Aud_APLL24M_Clk_cntr == 0) { PRINTK_AUDDRV("+%s enable_clock ADC clk(%x)\n", __func__, Aud_APLL24M_Clk_cntr); #ifdef PM_MANAGER_API enable_mux(MT_MUX_AUD2, "AUDIO"); clkmux_sel(MT_MUX_AUD2, 1, "AUDIO"); //APLL2 if (enable_clock(MT_CG_AUDIO_24M, "AUDIO")) { PRINTK_AUD_CLK("%s fail", __func__); } if (enable_clock(MT_CG_AUDIO_APLL2_TUNER, "AUDIO")) { PRINTK_AUD_CLK("%s fail", __func__); } #endif } Aud_APLL24M_Clk_cntr++; mutex_unlock(&auddrv_pmic_mutex); } void AudDrv_APLL24M_Clk_Off(void) { mutex_lock(&auddrv_pmic_mutex); Aud_APLL24M_Clk_cntr--; if (Aud_APLL24M_Clk_cntr == 0) { PRINTK_AUDDRV("+%s disable_clock ADC clk(%x)\n", __func__, Aud_APLL24M_Clk_cntr); #ifdef PM_MANAGER_API if (disable_clock(MT_CG_AUDIO_24M, "AUDIO")) { PRINTK_AUD_CLK("%s fail", __func__); } if (disable_clock(MT_CG_AUDIO_APLL2_TUNER, "AUDIO")) { PRINTK_AUD_CLK("%s fail", __func__); } clkmux_sel(MT_MUX_AUD2, 0, "AUDIO"); //select 26M disable_mux(MT_MUX_AUD2, "AUDIO"); #endif } if (Aud_APLL24M_Clk_cntr < 0) { PRINTK_AUDDRV("%s <0 (%d) \n", __func__, Aud_APLL24M_Clk_cntr); Aud_APLL24M_Clk_cntr = 0; } mutex_unlock(&auddrv_pmic_mutex); } /***************************************************************************** * FUNCTION * AudDrv_I2S_Clk_On / AudDrv_I2S_Clk_Off * * DESCRIPTION * Enable/Disable analog part clock * *****************************************************************************/ void AudDrv_I2S_Clk_On(void) { unsigned long flags; //PRINTK_AUD_CLK("+AudDrv_I2S_Clk_On, Aud_I2S_Clk_cntr:%d \n", Aud_I2S_Clk_cntr); spin_lock_irqsave(&auddrv_Clk_lock, flags); if (Aud_I2S_Clk_cntr == 0) { #ifdef PM_MANAGER_API if (enable_clock(MT_CG_AUDIO_I2S, "AUDIO")) { PRINTK_AUD_ERROR("Aud enable_clock MT65XX_PDN_AUDIO_I2S fail !!!\n"); } #else Afe_Set_Reg(AUDIO_TOP_CON0, 0x00000000, 0x00000040); //power on I2S clock #endif } Aud_I2S_Clk_cntr++; spin_unlock_irqrestore(&auddrv_Clk_lock, flags); } void AudDrv_I2S_Clk_Off(void) { unsigned long flags; //PRINTK_AUD_CLK("+AudDrv_I2S_Clk_Off, Aud_I2S_Clk_cntr:%d \n", Aud_I2S_Clk_cntr); spin_lock_irqsave(&auddrv_Clk_lock, flags); Aud_I2S_Clk_cntr--; if (Aud_I2S_Clk_cntr == 0) { #ifdef PM_MANAGER_API if (disable_clock(MT_CG_AUDIO_I2S, "AUDIO")) { PRINTK_AUD_ERROR("disable_clock MT_CG_AUDIO_I2S fail"); } #else Afe_Set_Reg(AUDIO_TOP_CON0, 0x00000040, 0x00000040); //power off I2S clock #endif } else if (Aud_I2S_Clk_cntr < 0) { PRINTK_AUD_ERROR("!! AudDrv_I2S_Clk_Off, Aud_I2S_Clk_cntr<0 (%d) \n", Aud_I2S_Clk_cntr); AUDIO_ASSERT(true); Aud_I2S_Clk_cntr = 0; } spin_unlock_irqrestore(&auddrv_Clk_lock, flags); //PRINTK_AUD_CLK("-AudDrv_I2S_Clk_Off, Aud_I2S_Clk_cntr:%d \n",Aud_I2S_Clk_cntr); } /***************************************************************************** * FUNCTION * AudDrv_Core_Clk_On / AudDrv_Core_Clk_Off * * DESCRIPTION * Enable/Disable analog part clock * *****************************************************************************/ void AudDrv_Core_Clk_On(void) { //PRINTK_AUD_CLK("+AudDrv_Core_Clk_On, Aud_Core_Clk_cntr:%d \n", Aud_Core_Clk_cntr); unsigned long flags; spin_lock_irqsave(&auddrv_Clk_lock, flags); if (Aud_Core_Clk_cntr == 0) { #ifdef PM_MANAGER_API if (enable_clock(MT_CG_AUDIO_AFE, "AUDIO")) { PRINTK_AUD_ERROR("AudDrv_Core_Clk_On Aud enable_clock MT_CG_AUDIO_AFE fail !!!\n"); } #endif } Aud_Core_Clk_cntr++; spin_unlock_irqrestore(&auddrv_Clk_lock, flags); //PRINTK_AUD_CLK("-AudDrv_Core_Clk_On, Aud_Core_Clk_cntr:%d \n", Aud_Core_Clk_cntr); } void AudDrv_Core_Clk_Off(void) { //PRINTK_AUD_CLK("+AudDrv_Core_Clk_On, Aud_Core_Clk_cntr:%d \n", Aud_Core_Clk_cntr); unsigned long flags; spin_lock_irqsave(&auddrv_Clk_lock, flags); if (Aud_Core_Clk_cntr == 0) { #ifdef PM_MANAGER_API if (disable_clock(MT_CG_AUDIO_AFE, "AUDIO")) { PRINTK_AUD_ERROR("AudDrv_Core_Clk_On Aud disable_clock MT_CG_AUDIO_AFE fail !!!\n"); } #endif } Aud_Core_Clk_cntr++; spin_unlock_irqrestore(&auddrv_Clk_lock, flags); //PRINTK_AUD_CLK("-AudDrv_Core_Clk_On, Aud_Core_Clk_cntr:%d \n", Aud_Core_Clk_cntr); } void AudDrv_APLL1Tuner_Clk_On(void) { unsigned long flags; spin_lock_irqsave(&auddrv_Clk_lock, flags); if (Aud_APLL1_Tuner_cntr == 0) { PRINTK_AUD_CLK("+AudDrv_APLLTuner_Clk_On, Aud_APLL1_Tuner_cntr:%d \n", Aud_APLL1_Tuner_cntr); Afe_Set_Reg(AUDIO_TOP_CON0, 0x0 << 19, 0x1 << 19); SetpllCfg(AP_PLL_CON5, 0x1, 0x1); } Aud_APLL1_Tuner_cntr++; spin_unlock_irqrestore(&auddrv_Clk_lock, flags); } void AudDrv_APLL1Tuner_Clk_Off(void) { unsigned long flags; spin_lock_irqsave(&auddrv_Clk_lock, flags); Aud_APLL1_Tuner_cntr--; if (Aud_APLL1_Tuner_cntr == 0) { Afe_Set_Reg(AUDIO_TOP_CON0, 0x1 << 19, 0x1 << 19); Afe_Set_Reg(AFE_APLL1_TUNER_CFG, 0x00000033, 0x1 << 19); SetpllCfg(AP_PLL_CON5, 0x0, 0x1); } // handle for clock error else if (Aud_APLL1_Tuner_cntr < 0) { PRINTK_AUD_ERROR("!! AudDrv_APLLTuner_Clk_Off, Aud_APLL1_Tuner_cntr<0 (%d) \n", Aud_APLL1_Tuner_cntr); Aud_APLL1_Tuner_cntr = 0; } spin_unlock_irqrestore(&auddrv_Clk_lock, flags); } void AudDrv_APLL2Tuner_Clk_On(void) { unsigned long flags; spin_lock_irqsave(&auddrv_Clk_lock, flags); if (Aud_APLL2_Tuner_cntr == 0) { PRINTK_AUD_CLK("+Aud_APLL2_Tuner_cntr, Aud_APLL2_Tuner_cntr:%d \n", Aud_APLL2_Tuner_cntr); Afe_Set_Reg(AUDIO_TOP_CON0, 0x0 << 20, 0x1 << 20); Afe_Set_Reg(AFE_APLL2_TUNER_CFG, 0x00000033, 0x1 << 19); SetpllCfg(AP_PLL_CON5, 0x1<<1, 0x1<<1); } Aud_APLL2_Tuner_cntr++; spin_unlock_irqrestore(&auddrv_Clk_lock, flags); } void AudDrv_APLL2Tuner_Clk_Off(void) { unsigned long flags; spin_lock_irqsave(&auddrv_Clk_lock, flags); Aud_APLL2_Tuner_cntr--; if (Aud_APLL2_Tuner_cntr == 0) { Afe_Set_Reg(AUDIO_TOP_CON0, 0x1 << 20, 0x1 << 20); SetpllCfg(AP_PLL_CON5, 0x0<<1, 0x1<<1); } // handle for clock error else if (Aud_APLL2_Tuner_cntr < 0) { PRINTK_AUD_ERROR("!! AudDrv_APLL2Tuner_Clk_Off, Aud_APLL1_Tuner_cntr<0 (%d) \n", Aud_APLL2_Tuner_cntr); Aud_APLL2_Tuner_cntr = 0; } spin_unlock_irqrestore(&auddrv_Clk_lock, flags); } /***************************************************************************** * FUNCTION * AudDrv_HDMI_Clk_On / AudDrv_HDMI_Clk_Off * * DESCRIPTION * Enable/Disable analog part clock * *****************************************************************************/ void AudDrv_HDMI_Clk_On(void) { PRINTK_AUD_CLK("+AudDrv_HDMI_Clk_On, Aud_I2S_Clk_cntr:%d \n", Aud_HDMI_Clk_cntr); if (Aud_HDMI_Clk_cntr == 0) { AudDrv_ANA_Clk_On(); AudDrv_Clk_On(); } Aud_HDMI_Clk_cntr++; } void AudDrv_HDMI_Clk_Off(void) { PRINTK_AUD_CLK("+AudDrv_HDMI_Clk_Off, Aud_I2S_Clk_cntr:%d \n", Aud_HDMI_Clk_cntr); Aud_HDMI_Clk_cntr--; if (Aud_HDMI_Clk_cntr == 0) { AudDrv_ANA_Clk_Off(); AudDrv_Clk_Off(); } else if (Aud_HDMI_Clk_cntr < 0) { PRINTK_AUD_ERROR("!! AudDrv_Linein_Clk_Off, Aud_I2S_Clk_cntr<0 (%d) \n", Aud_HDMI_Clk_cntr); AUDIO_ASSERT(true); Aud_HDMI_Clk_cntr = 0; } PRINTK_AUD_CLK("-AudDrv_I2S_Clk_Off, Aud_I2S_Clk_cntr:%d \n", Aud_HDMI_Clk_cntr); } /***************************************************************************** * FUNCTION * AudDrv_Suspend_Clk_Off / AudDrv_Suspend_Clk_On * * DESCRIPTION * Enable/Disable AFE clock for suspend * ***************************************************************************** */ void AudDrv_Suspend_Clk_Off(void) { unsigned long flags; spin_lock_irqsave(&auddrv_Clk_lock, flags); if (Aud_Core_Clk_cntr > 0) { #ifdef PM_MANAGER_API if (Aud_AFE_Clk_cntr > 0) { if (disable_clock(MT_CG_AUDIO_AFE, "AUDIO")) { xlog_printk(ANDROID_LOG_ERROR, "Sound", "Aud enable_clock MT_CG_AUDIO_AFE fail !!!\n"); } } if (Aud_I2S_Clk_cntr > 0) { if (disable_clock(MT_CG_AUDIO_I2S, "AUDIO")) { PRINTK_AUD_ERROR("disable_clock MT_CG_AUDIO_I2S fail"); } } if (Aud_ADC_Clk_cntr > 0) { Afe_Set_Reg(AUDIO_TOP_CON0, 1 << 24 , 1 << 24); } if (Aud_ADC2_Clk_cntr > 0) { #if 0 //K2 removed if (disable_clock(MT_CG_AUDIO_ADDA2, "AUDIO")) { PRINTK_AUD_CLK("%s fail", __func__); } #endif } if (Aud_ADC3_Clk_cntr > 0) { #if 0 //K2 removed if (disable_clock(MT_CG_AUDIO_ADDA3, "AUDIO")) { PRINTK_AUD_CLK("%s fail", __func__); } #endif } if (Aud_ANA_Clk_cntr > 0) { } if (Aud_HDMI_Clk_cntr > 0) { } if (Aud_APLL22M_Clk_cntr > 0) { if (disable_clock(MT_CG_AUDIO_22M, "AUDIO")) { PRINTK_AUD_CLK("%s fail", __func__); } if (disable_clock(MT_CG_AUDIO_APLL_TUNER, "AUDIO")) { PRINTK_AUD_CLK("%s fail", __func__); } clkmux_sel(MT_MUX_AUD1, 0, "AUDIO"); //select 26M disable_mux(MT_MUX_AUD1, "AUDIO"); } if (Aud_APLL24M_Clk_cntr > 0) { if (disable_clock(MT_CG_AUDIO_24M, "AUDIO")) { PRINTK_AUD_CLK("%s fail", __func__); } if (disable_clock(MT_CG_AUDIO_APLL2_TUNER, "AUDIO")) { PRINTK_AUD_CLK("%s fail", __func__); } clkmux_sel(MT_MUX_AUD2, 0, "AUDIO"); //select 26M disable_mux(MT_MUX_AUD2, "AUDIO"); } #endif } spin_unlock_irqrestore(&auddrv_Clk_lock, flags); } void AudDrv_Suspend_Clk_On(void) { unsigned long flags; spin_lock_irqsave(&auddrv_Clk_lock, flags); if (Aud_Core_Clk_cntr > 0) { #ifdef PM_MANAGER_API if (Aud_AFE_Clk_cntr > 0) { if (enable_clock(MT_CG_AUDIO_AFE, "AUDIO")) { xlog_printk(ANDROID_LOG_ERROR, "Sound", "Aud enable_clock MT_CG_AUDIO_AFE fail !!!\n"); } } if (Aud_I2S_Clk_cntr > 0) { if (enable_clock(MT_CG_AUDIO_I2S, "AUDIO")) { PRINTK_AUD_ERROR("enable_clock MT_CG_AUDIO_I2S fail"); } } if (Aud_ADC_Clk_cntr > 0) { Afe_Set_Reg(AUDIO_TOP_CON0, 0 << 24 , 1 << 24); } if (Aud_ADC2_Clk_cntr > 0) { #if 0 //K2 removed if (enable_clock(MT_CG_AUDIO_ADDA2, "AUDIO")) { PRINTK_AUD_CLK("%s fail", __func__); } #endif } if (Aud_ADC3_Clk_cntr > 0) { #if 0 //K2 removed if (enable_clock(MT_CG_AUDIO_ADDA3, "AUDIO")) { PRINTK_AUD_CLK("%s fail", __func__); } #endif } if (Aud_ANA_Clk_cntr > 0) { } if (Aud_HDMI_Clk_cntr > 0) { } if (Aud_APLL22M_Clk_cntr > 0) { enable_mux(MT_MUX_AUD1, "AUDIO"); clkmux_sel(MT_MUX_AUD1, 1 , "AUDIO"); //select APLL1 if (enable_clock(MT_CG_AUDIO_22M, "AUDIO")) { PRINTK_AUD_CLK("%s fail", __func__); } if (enable_clock(MT_CG_AUDIO_APLL_TUNER, "AUDIO")) { PRINTK_AUD_CLK("%s fail", __func__); } } if (Aud_APLL24M_Clk_cntr > 0) { enable_mux(MT_MUX_AUD2, "AUDIO"); clkmux_sel(MT_MUX_AUD2, 1, "AUDIO"); //APLL2 if (enable_clock(MT_CG_AUDIO_24M, "AUDIO")) { PRINTK_AUD_CLK("%s fail", __func__); } if (enable_clock(MT_CG_AUDIO_APLL2_TUNER, "AUDIO")) { PRINTK_AUD_CLK("%s fail", __func__); } } #endif } spin_unlock_irqrestore(&auddrv_Clk_lock, flags); } void AudDrv_Emi_Clk_On(void) { mutex_lock(&auddrv_pmic_mutex); if(Aud_EMI_cntr == 0) { #ifndef DENALI_FPGA_EARLYPORTING //george early porting disable disable_dpidle_by_bit(MT_CG_AUDIO_AFE); disable_soidle_by_bit(MT_CG_AUDIO_AFE); #endif } Aud_EMI_cntr++; mutex_unlock(&auddrv_pmic_mutex); } void AudDrv_Emi_Clk_Off(void) { mutex_lock(&auddrv_pmic_mutex); Aud_EMI_cntr--; if(Aud_EMI_cntr ==0) { #ifndef DENALI_FPGA_EARLYPORTING //george early porting disable enable_dpidle_by_bit(MT_CG_AUDIO_AFE); enable_soidle_by_bit(MT_CG_AUDIO_AFE); #endif } if(Aud_EMI_cntr <0 ) { Aud_EMI_cntr = 0; printk("Aud_EMI_cntr = %d \n",Aud_EMI_cntr); } mutex_unlock(&auddrv_pmic_mutex); } // export symbol for other module use EXPORT_SYMBOL(AudDrv_Clk_On); EXPORT_SYMBOL(AudDrv_Clk_Off); EXPORT_SYMBOL(AudDrv_ANA_Clk_On); EXPORT_SYMBOL(AudDrv_ANA_Clk_Off); EXPORT_SYMBOL(AudDrv_I2S_Clk_On); EXPORT_SYMBOL(AudDrv_I2S_Clk_Off);
bq/aquaris-E4
sound/soc/mediatek/mt_soc_audio_v3/AudDrv_Clk.c
C
gpl-2.0
28,643
/* This file is part of the ScriptDev2 Project. See AUTHORS file for Copyright information * 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 */ /* ScriptData SDName: Boss_Moorabi SD%Complete: 20% SDComment: SDCategory: Gundrak EndScriptData */ #include "precompiled.h" #include "gundrak.h" enum { SAY_AGGRO = -1604011, SAY_QUAKE = -1604012, SAY_TRANSFORM = -1604013, SAY_SLAY_1 = -1604014, SAY_SLAY_2 = -1604015, SAY_SLAY_3 = -1604016, SAY_DEATH = -1604017, EMOTE_TRANSFORM = -1604018, EMOTE_TRANSFORMED = -1604029, // Troll form SPELL_DETERMINED_STAB = 55104, SPELL_MOJO_FRENZY = 55163, SPELL_GROUND_TREMOR = 55142, SPELL_NUMBING_SHOUT = 55106, SPELL_TRANSFORMATION = 55098, // Mammoth SPELL_DETERMINED_GORE = 55102, SPELL_DETERMINED_GORE_H = 59444, SPELL_QUAKE = 55101, SPELL_NUMBING_ROAR = 55100, }; /*###### ## boss_moorabi ######*/ struct boss_moorabiAI : public ScriptedAI { boss_moorabiAI(Creature* pCreature) : ScriptedAI(pCreature) { m_pInstance = (instance_gundrak*)pCreature->GetInstanceData(); m_bIsRegularMode = pCreature->GetMap()->IsRegularDifficulty(); Reset(); } instance_gundrak* m_pInstance; bool m_bIsRegularMode; uint32 m_uiStabTimer; // used for stab and gore uint32 m_uiQuakeTimer; // used for quake and ground tremor uint32 m_uiRoarTimer; // both roars on it uint32 m_uiTransformationTimer; uint32 m_uiPreviousTimer; bool m_bMammothPhase; void Reset() override { m_bMammothPhase = false; m_uiStabTimer = 8000; m_uiQuakeTimer = 1000; m_uiRoarTimer = 7000; m_uiTransformationTimer = 10000; m_uiPreviousTimer = 10000; } void Aggro(Unit* /*pWho*/) override { DoScriptText(SAY_AGGRO, m_creature); DoCastSpellIfCan(m_creature, SPELL_MOJO_FRENZY); if (m_pInstance) m_pInstance->SetData(TYPE_MOORABI, IN_PROGRESS); } void KilledUnit(Unit* /*pVictim*/) override { switch (urand(0, 2)) { case 0: DoScriptText(SAY_SLAY_1, m_creature); break; case 1: DoScriptText(SAY_SLAY_2, m_creature); break; case 2: DoScriptText(SAY_SLAY_3, m_creature); break; } } void JustDied(Unit* /*pKiller*/) override { DoScriptText(SAY_DEATH, m_creature); if (m_pInstance) m_pInstance->SetData(TYPE_MOORABI, DONE); } void UpdateAI(const uint32 uiDiff) override { if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) return; if (m_creature->HasAura(SPELL_TRANSFORMATION) && !m_bMammothPhase) { DoScriptText(EMOTE_TRANSFORMED, m_creature); m_bMammothPhase = true; // Set the achievement to failed if (m_pInstance) m_pInstance->SetLessRabiAchievementCriteria(false); } if (m_uiRoarTimer < uiDiff) { DoCastSpellIfCan(m_creature->getVictim(), m_bMammothPhase ? SPELL_NUMBING_ROAR : SPELL_NUMBING_SHOUT); m_uiRoarTimer = 20000; } else m_uiRoarTimer -= uiDiff; if (m_uiQuakeTimer < uiDiff) { DoScriptText(SAY_QUAKE, m_creature); DoCastSpellIfCan(m_creature->getVictim(), m_bMammothPhase ? SPELL_QUAKE : SPELL_GROUND_TREMOR); m_uiQuakeTimer = m_bMammothPhase ? 13000 : 18000; } else m_uiQuakeTimer -= uiDiff; if (m_uiStabTimer < uiDiff) { if (m_bMammothPhase) DoCastSpellIfCan(m_creature->getVictim(), m_bIsRegularMode ? SPELL_DETERMINED_GORE : SPELL_DETERMINED_GORE_H); else DoCastSpellIfCan(m_creature->getVictim(), SPELL_DETERMINED_STAB); m_uiStabTimer = 7000; } else m_uiStabTimer -= uiDiff; // check only in troll phase if (!m_bMammothPhase) { if (m_uiTransformationTimer < uiDiff) { DoScriptText(SAY_TRANSFORM, m_creature); DoScriptText(EMOTE_TRANSFORM, m_creature); DoCastSpellIfCan(m_creature, SPELL_TRANSFORMATION); m_uiPreviousTimer *= 0.8; m_uiTransformationTimer = m_uiPreviousTimer; } else m_uiTransformationTimer -= uiDiff; } DoMeleeAttackIfReady(); } }; CreatureAI* GetAI_boss_moorabi(Creature* pCreature) { return new boss_moorabiAI(pCreature); } void AddSC_boss_moorabi() { Script* pNewScript; pNewScript = new Script; pNewScript->Name = "boss_moorabi"; pNewScript->GetAI = &GetAI_boss_moorabi; pNewScript->RegisterSelf(); }
Exxenoz/mangos-wotlk
src/scriptdev2/scripts/northrend/gundrak/boss_moorabi.cpp
C++
gpl-2.0
5,803
/* * arch/arm/include/asm/cacheflush.h * * Copyright (C) 1999-2002 Russell King * * 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. */ #ifndef _ASMARM_CACHEFLUSH_H #define _ASMARM_CACHEFLUSH_H #include <linux/mm.h> #include <asm/glue-cache.h> #include <asm/shmparam.h> #include <asm/cachetype.h> #include <asm/outercache.h> #include <asm/rodata.h> #define CACHE_COLOUR(vaddr) ((vaddr & (SHMLBA - 1)) >> PAGE_SHIFT) /* * This flag is used to indicate that the page pointed to by a pte is clean * and does not require cleaning before returning it to the user. */ #define PG_dcache_clean PG_arch_1 /* * MM Cache Management * =================== * * The arch/arm/mm/cache-*.S and arch/arm/mm/proc-*.S files * implement these methods. * * Start addresses are inclusive and end addresses are exclusive; * start addresses should be rounded down, end addresses up. * * See Documentation/cachetlb.txt for more information. * Please note that the implementation of these, and the required * effects are cache-type (VIVT/VIPT/PIPT) specific. * * flush_icache_all() * * Unconditionally clean and invalidate the entire icache. * Currently only needed for cache-v6.S and cache-v7.S, see * __flush_icache_all for the generic implementation. * * flush_kern_all() * * Unconditionally clean and invalidate the entire cache. * * flush_user_all() * * Clean and invalidate all user space cache entries * before a change of page tables. * * flush_user_range(start, end, flags) * * Clean and invalidate a range of cache entries in the * specified address space before a change of page tables. * - start - user start address (inclusive, page aligned) * - end - user end address (exclusive, page aligned) * - flags - vma->vm_flags field * * coherent_kern_range(start, end) * * Ensure coherency between the Icache and the Dcache in the * region described by start, end. If you have non-snooping * Harvard caches, you need to implement this function. * - start - virtual start address * - end - virtual end address * * coherent_user_range(start, end) * * Ensure coherency between the Icache and the Dcache in the * region described by start, end. If you have non-snooping * Harvard caches, you need to implement this function. * - start - virtual start address * - end - virtual end address * * flush_kern_dcache_area(kaddr, size) * * Ensure that the data held in page is written back. * - kaddr - page address * - size - region size * * DMA Cache Coherency * =================== * * dma_flush_range(start, end) * * Clean and invalidate the specified virtual address range. * - start - virtual start address * - end - virtual end address */ struct cpu_cache_fns { void (*flush_icache_all)(void); void (*flush_kern_all)(void); void (*flush_user_all)(void); void (*flush_user_range)(unsigned long, unsigned long, unsigned int); void (*coherent_kern_range)(unsigned long, unsigned long); void (*coherent_user_range)(unsigned long, unsigned long); void (*flush_kern_dcache_area)(void *, size_t); void (*dma_map_area)(const void *, size_t, int); void (*dma_unmap_area)(const void *, size_t, int); void (*dma_flush_range)(const void *, const void *); }; /* * Select the calling method */ #ifdef MULTI_CACHE extern struct cpu_cache_fns cpu_cache; #define __cpuc_flush_icache_all cpu_cache.flush_icache_all #define __cpuc_flush_kern_all cpu_cache.flush_kern_all #define __cpuc_flush_user_all cpu_cache.flush_user_all #define __cpuc_flush_user_range cpu_cache.flush_user_range #define __cpuc_coherent_kern_range cpu_cache.coherent_kern_range #define __cpuc_coherent_user_range cpu_cache.coherent_user_range #define __cpuc_flush_dcache_area cpu_cache.flush_kern_dcache_area /* * These are private to the dma-mapping API. Do not use directly. * Their sole purpose is to ensure that data held in the cache * is visible to DMA, or data written by DMA to system memory is * visible to the CPU. */ #define dmac_map_area cpu_cache.dma_map_area #define dmac_unmap_area cpu_cache.dma_unmap_area #define dmac_flush_range cpu_cache.dma_flush_range #else extern void __cpuc_flush_icache_all(void); extern void __cpuc_flush_kern_all(void); extern void __cpuc_flush_user_all(void); extern void __cpuc_flush_user_range(unsigned long, unsigned long, unsigned int); extern void __cpuc_coherent_kern_range(unsigned long, unsigned long); extern void __cpuc_coherent_user_range(unsigned long, unsigned long); extern void __cpuc_flush_dcache_area(void *, size_t); /* * These are private to the dma-mapping API. Do not use directly. * Their sole purpose is to ensure that data held in the cache * is visible to DMA, or data written by DMA to system memory is * visible to the CPU. */ extern void dmac_map_area(const void *, size_t, int); extern void dmac_unmap_area(const void *, size_t, int); extern void dmac_flush_range(const void *, const void *); #endif /* * Copy user data from/to a page which is mapped into a different * processes address space. Really, we want to allow our "user * space" model to handle this. */ extern void copy_to_user_page(struct vm_area_struct *, struct page *, unsigned long, void *, const void *, unsigned long); #define copy_from_user_page(vma, page, vaddr, dst, src, len) \ do { \ memcpy(dst, src, len); \ } while (0) /* * Convert calls to our calling convention. */ /* Invalidate I-cache */ #define __flush_icache_all_generic() \ asm("mcr p15, 0, %0, c7, c5, 0" \ : : "r" (0)); /* Invalidate I-cache inner shareable */ #define __flush_icache_all_v7_smp() \ asm("mcr p15, 0, %0, c7, c1, 0" \ : : "r" (0)); /* * Optimized __flush_icache_all for the common cases. Note that UP ARMv7 * will fall through to use __flush_icache_all_generic. */ #if (defined(CONFIG_CPU_V7) && \ (defined(CONFIG_CPU_V6) || defined(CONFIG_CPU_V6K))) || \ defined(CONFIG_SMP_ON_UP) #define __flush_icache_preferred __cpuc_flush_icache_all #elif __LINUX_ARM_ARCH__ >= 7 && defined(CONFIG_SMP) #define __flush_icache_preferred __flush_icache_all_v7_smp #elif __LINUX_ARM_ARCH__ == 6 && defined(CONFIG_ARM_ERRATA_411920) #define __flush_icache_preferred __cpuc_flush_icache_all #else #define __flush_icache_preferred __flush_icache_all_generic #endif static inline void __flush_icache_all(void) { __flush_icache_preferred(); } #define flush_cache_all() __cpuc_flush_kern_all() #ifndef CONFIG_SMP #define flush_all_cpu_caches() flush_cache_all() #else extern void flush_all_cpu_caches(void); #endif static inline void vivt_flush_cache_mm(struct mm_struct *mm) { if (cpumask_test_cpu(smp_processor_id(), mm_cpumask(mm))) __cpuc_flush_user_all(); } static inline void vivt_flush_cache_range(struct vm_area_struct *vma, unsigned long start, unsigned long end) { struct mm_struct *mm = vma->vm_mm; if (!mm || cpumask_test_cpu(smp_processor_id(), mm_cpumask(mm))) __cpuc_flush_user_range(start & PAGE_MASK, PAGE_ALIGN(end), vma->vm_flags); } static inline void vivt_flush_cache_page(struct vm_area_struct *vma, unsigned long user_addr, unsigned long pfn) { struct mm_struct *mm = vma->vm_mm; if (!mm || cpumask_test_cpu(smp_processor_id(), mm_cpumask(mm))) { unsigned long addr = user_addr & PAGE_MASK; __cpuc_flush_user_range(addr, addr + PAGE_SIZE, vma->vm_flags); } } #ifndef CONFIG_CPU_CACHE_VIPT #define flush_cache_mm(mm) \ vivt_flush_cache_mm(mm) #define flush_cache_range(vma,start,end) \ vivt_flush_cache_range(vma,start,end) #define flush_cache_page(vma,addr,pfn) \ vivt_flush_cache_page(vma,addr,pfn) #else extern void flush_cache_mm(struct mm_struct *mm); extern void flush_cache_range(struct vm_area_struct *vma, unsigned long start, unsigned long end); extern void flush_cache_page(struct vm_area_struct *vma, unsigned long user_addr, unsigned long pfn); #endif #define flush_cache_dup_mm(mm) flush_cache_mm(mm) /* * flush_cache_user_range is used when we want to ensure that the * Harvard caches are synchronised for the user space address range. * This is used for the ARM private sys_cacheflush system call. */ #define flush_cache_user_range(start,end) \ __cpuc_coherent_user_range((start) & PAGE_MASK, PAGE_ALIGN(end)) /* * Perform necessary cache operations to ensure that data previously * stored within this range of addresses can be executed by the CPU. */ #define flush_icache_range(s,e) __cpuc_coherent_kern_range(s,e) /* * Perform necessary cache operations to ensure that the TLB will * see data written in the specified area. */ #define clean_dcache_area(start,size) cpu_dcache_clean_area(start, size) /* * flush_dcache_page is used when the kernel has written to the page * cache page at virtual address page->virtual. * * If this page isn't mapped (ie, page_mapping == NULL), or it might * have userspace mappings, then we _must_ always clean + invalidate * the dcache entries associated with the kernel mapping. * * Otherwise we can defer the operation, and clean the cache when we are * about to change to user space. This is the same method as used on SPARC64. * See update_mmu_cache for the user space part. */ #define ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE 1 extern void flush_dcache_page(struct page *); static inline void flush_kernel_vmap_range(void *addr, int size) { if ((cache_is_vivt() || cache_is_vipt_aliasing())) __cpuc_flush_dcache_area(addr, (size_t)size); } static inline void invalidate_kernel_vmap_range(void *addr, int size) { if ((cache_is_vivt() || cache_is_vipt_aliasing())) __cpuc_flush_dcache_area(addr, (size_t)size); } #define ARCH_HAS_FLUSH_ANON_PAGE static inline void flush_anon_page(struct vm_area_struct *vma, struct page *page, unsigned long vmaddr) { extern void __flush_anon_page(struct vm_area_struct *vma, struct page *, unsigned long); if (PageAnon(page)) __flush_anon_page(vma, page, vmaddr); } #define ARCH_HAS_FLUSH_KERNEL_DCACHE_PAGE static inline void flush_kernel_dcache_page(struct page *page) { } #define flush_dcache_mmap_lock(mapping) \ spin_lock_irq(&(mapping)->tree_lock) #define flush_dcache_mmap_unlock(mapping) \ spin_unlock_irq(&(mapping)->tree_lock) #define flush_icache_user_range(vma,page,addr,len) \ flush_dcache_page(page) /* * We don't appear to need to do anything here. In fact, if we did, we'd * duplicate cache flushing elsewhere performed by flush_dcache_page(). */ #define flush_icache_page(vma,page) do { } while (0) /* * flush_cache_vmap() is used when creating mappings (eg, via vmap, * vmalloc, ioremap etc) in kernel space for pages. On non-VIPT * caches, since the direct-mappings of these pages may contain cached * data, we need to do a full cache flush to ensure that writebacks * don't corrupt data placed into these pages via the new mappings. */ static inline void flush_cache_vmap(unsigned long start, unsigned long end) { if (!cache_is_vipt_nonaliasing()) flush_cache_all(); else /* * set_pte_at() called from vmap_pte_range() does not * have a DSB after cleaning the cache line. */ dsb(); } static inline void flush_cache_vunmap(unsigned long start, unsigned long end) { if (!cache_is_vipt_nonaliasing()) flush_cache_all(); } #endif
mlachwani/Android-4.4.2-Manta-Kernel
arch/arm/include/asm/cacheflush.h
C
gpl-2.0
11,383
/* * drivers/gpu/ion/ion.c * * Copyright (C) 2011 Google, Inc. * * This software is licensed under the terms of the GNU General Public * License version 2, as published by the Free Software Foundation, and * may be copied, distributed, and modified under those terms. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * */ #include <linux/device.h> #include <linux/file.h> #include <linux/freezer.h> #include <linux/fs.h> #include <linux/anon_inodes.h> #include <linux/ion.h> #include <linux/mtk_ion.h> #include <linux/kthread.h> #include <linux/list.h> #include <linux/memblock.h> #include <linux/miscdevice.h> #include <linux/export.h> #include <linux/mm.h> #include <linux/mm_types.h> #include <linux/rbtree.h> #include <linux/slab.h> #include <linux/seq_file.h> #include <linux/uaccess.h> #include <linux/vmalloc.h> #include <linux/debugfs.h> #include <linux/dma-buf.h> #include <linux/idr.h> #include "ion_priv.h" #include "ion_profile.h" #define DEBUG_HEAP_SHRINKER #if 0 //we move it to ion_priv.h. so we can dump every buffer info in ion_mm_heap.c /** * struct ion_device - the metadata of the ion device node * @dev: the actual misc device * @buffers: an rb tree of all the existing buffers * @buffer_lock: lock protecting the tree of buffers * @lock: rwsem protecting the tree of heaps and clients * @heaps: list of all the heaps in the system * @user_clients: list of all the clients created from userspace */ struct ion_device { struct miscdevice dev; struct rb_root buffers; struct mutex buffer_lock; struct rw_semaphore lock; struct plist_head heaps; long (*custom_ioctl) (struct ion_client *client, unsigned int cmd, unsigned long arg); struct rb_root clients; struct dentry *debug_root; }; /** * struct ion_client - a process/hw block local address space * @node: node in the tree of all clients * @dev: backpointer to ion device * @handles: an rb tree of all the handles in this client * @idr: an idr space for allocating handle ids * @lock: lock protecting the tree of handles * @name: used for debugging * @task: used for debugging * * A client represents a list of buffers this client may access. * The mutex stored here is used to protect both handles tree * as well as the handles themselves, and should be held while modifying either. */ struct ion_client { struct rb_node node; struct ion_device *dev; struct rb_root handles; struct idr idr; struct mutex lock; const char *name; struct task_struct *task; pid_t pid; struct dentry *debug_root; }; struct ion_handle_debug { pid_t pid; pid_t tgid; unsigned int backtrace[BACKTRACE_SIZE]; unsigned int backtrace_num; }; /** * ion_handle - a client local reference to a buffer * @ref: reference count * @client: back pointer to the client the buffer resides in * @buffer: pointer to the buffer * @node: node in the client's handle rbtree * @kmap_cnt: count of times this client has mapped to kernel * @id: client-unique id allocated by client->idr * * Modifications to node, map_cnt or mapping should be protected by the * lock in the client. Other fields are never changed after initialization. */ struct ion_handle { struct kref ref; struct ion_client *client; struct ion_buffer *buffer; struct rb_node node; unsigned int kmap_cnt; int id; #if ION_RUNTIME_DEBUGGER struct ion_handle_debug dbg; #endif }; #endif bool ion_buffer_fault_user_mappings(struct ion_buffer *buffer) { return ((buffer->flags & ION_FLAG_CACHED) && !(buffer->flags & ION_FLAG_CACHED_NEEDS_SYNC)); } bool ion_buffer_cached(struct ion_buffer *buffer) { return !!(buffer->flags & ION_FLAG_CACHED); } static inline struct page *ion_buffer_page(struct page *page) { return (struct page *)((unsigned long)page & ~(1UL)); } static inline bool ion_buffer_page_is_dirty(struct page *page) { return !!((unsigned long)page & 1UL); } static inline void ion_buffer_page_dirty(struct page **page) { *page = (struct page *)((unsigned long)(*page) | 1UL); } static inline void ion_buffer_page_clean(struct page **page) { *page = (struct page *)((unsigned long)(*page) & ~(1UL)); } /* this function should only be called while dev->lock is held */ static void ion_buffer_add(struct ion_device *dev, struct ion_buffer *buffer) { struct rb_node **p = &dev->buffers.rb_node; struct rb_node *parent = NULL; struct ion_buffer *entry; while (*p) { parent = *p; entry = rb_entry(parent, struct ion_buffer, node); if (buffer < entry) { p = &(*p)->rb_left; } else if (buffer > entry) { p = &(*p)->rb_right; } else { pr_err("%s: buffer already found.", __func__); BUG(); } } rb_link_node(&buffer->node, parent, p); rb_insert_color(&buffer->node, &dev->buffers); } /* this function should only be called while dev->lock is held */ static struct ion_buffer *ion_buffer_create(struct ion_heap *heap, struct ion_device *dev, unsigned long len, unsigned long align, unsigned long flags) { struct ion_buffer *buffer; struct sg_table *table; struct scatterlist *sg; int i, ret; buffer = kzalloc(sizeof(struct ion_buffer), GFP_KERNEL); if (!buffer) return ERR_PTR(-ENOMEM); buffer->heap = heap; buffer->flags = flags; kref_init(&buffer->ref); ret = heap->ops->allocate(heap, buffer, len, align, flags); if (ret) { if (!(heap->flags & ION_HEAP_FLAG_DEFER_FREE)) goto err2; ion_heap_freelist_drain(heap, 0); ret = heap->ops->allocate(heap, buffer, len, align, flags); if (ret) goto err2; } buffer->dev = dev; buffer->size = len; table = heap->ops->map_dma(heap, buffer); if (WARN_ONCE(table == NULL, "heap->ops->map_dma should return ERR_PTR on error")) table = ERR_PTR(-EINVAL); if (IS_ERR(table)) { heap->ops->free(buffer); kfree(buffer); return ERR_PTR(PTR_ERR(table)); } buffer->sg_table = table; if (ion_buffer_fault_user_mappings(buffer)) { int num_pages = PAGE_ALIGN(buffer->size) / PAGE_SIZE; struct scatterlist *sg; int i, j, k = 0; buffer->pages = vmalloc(sizeof(struct page *) * num_pages); if (!buffer->pages) { ret = -ENOMEM; goto err1; } for_each_sg(table->sgl, sg, table->nents, i) { struct page *page = sg_page(sg); for (j = 0; j < sg_dma_len(sg) / PAGE_SIZE; j++) buffer->pages[k++] = page++; } if (ret) goto err; } buffer->dev = dev; buffer->size = len; INIT_LIST_HEAD(&buffer->vmas); //log task pid for debug +by k.zhang { struct task_struct *task; task = current->group_leader; get_task_comm(buffer->task_comm, task); buffer->pid = task_pid_nr(task); } mutex_init(&buffer->lock); /* this will set up dma addresses for the sglist -- it is not technically correct as per the dma api -- a specific device isn't really taking ownership here. However, in practice on our systems the only dma_address space is physical addresses. Additionally, we can't afford the overhead of invalidating every allocation via dma_map_sg. The implicit contract here is that memory comming from the heaps is ready for dma, ie if it has a cached mapping that mapping has been invalidated */ for_each_sg(buffer->sg_table->sgl, sg, buffer->sg_table->nents, i) sg_dma_address(sg) = sg_phys(sg); mutex_lock(&dev->buffer_lock); ion_buffer_add(dev, buffer); mutex_unlock(&dev->buffer_lock); return buffer; err: heap->ops->unmap_dma(heap, buffer); heap->ops->free(buffer); err1: if (buffer->pages) vfree(buffer->pages); err2: kfree(buffer); return ERR_PTR(ret); } void ion_buffer_destroy(struct ion_buffer *buffer) { if (WARN_ON(buffer->kmap_cnt > 0)) buffer->heap->ops->unmap_kernel(buffer->heap, buffer); buffer->heap->ops->unmap_dma(buffer->heap, buffer); buffer->heap->ops->free(buffer); if (buffer->pages) vfree(buffer->pages); kfree(buffer); } static void _ion_buffer_destroy(struct kref *kref) { struct ion_buffer *buffer = container_of(kref, struct ion_buffer, ref); struct ion_heap *heap = buffer->heap; struct ion_device *dev = buffer->dev; mutex_lock(&dev->buffer_lock); rb_erase(&buffer->node, &dev->buffers); mutex_unlock(&dev->buffer_lock); if (heap->flags & ION_HEAP_FLAG_DEFER_FREE) ion_heap_freelist_add(heap, buffer); else ion_buffer_destroy(buffer); } static void ion_buffer_get(struct ion_buffer *buffer) { kref_get(&buffer->ref); } static int ion_buffer_put(struct ion_buffer *buffer) { return kref_put(&buffer->ref, _ion_buffer_destroy); } static void ion_buffer_add_to_handle(struct ion_buffer *buffer) { mutex_lock(&buffer->lock); buffer->handle_count++; mutex_unlock(&buffer->lock); } static void ion_buffer_remove_from_handle(struct ion_buffer *buffer) { /* * when a buffer is removed from a handle, if it is not in * any other handles, copy the taskcomm and the pid of the * process it's being removed from into the buffer. At this * point there will be no way to track what processes this buffer is * being used by, it only exists as a dma_buf file descriptor. * The taskcomm and pid can provide a debug hint as to where this fd * is in the system */ mutex_lock(&buffer->lock); buffer->handle_count--; BUG_ON(buffer->handle_count < 0); if (!buffer->handle_count) { struct task_struct *task; task = current->group_leader; get_task_comm(buffer->task_comm, task); buffer->pid = task_pid_nr(task); } mutex_unlock(&buffer->lock); } static struct ion_handle *ion_handle_create(struct ion_client *client, struct ion_buffer *buffer) { struct ion_handle *handle; handle = kzalloc(sizeof(struct ion_handle), GFP_KERNEL); if (!handle) return ERR_PTR(-ENOMEM); kref_init(&handle->ref); rb_init_node(&handle->node); handle->client = client; ion_buffer_get(buffer); ion_buffer_add_to_handle(buffer); handle->buffer = buffer; return handle; } static void ion_handle_kmap_put(struct ion_handle *); static void ion_handle_destroy(struct kref *kref) { struct ion_handle *handle = container_of(kref, struct ion_handle, ref); struct ion_client *client = handle->client; struct ion_buffer *buffer = handle->buffer; mutex_lock(&buffer->lock); while (handle->kmap_cnt) ion_handle_kmap_put(handle); mutex_unlock(&buffer->lock); idr_remove(&client->idr, handle->id); if (!RB_EMPTY_NODE(&handle->node)) rb_erase(&handle->node, &client->handles); ion_buffer_remove_from_handle(buffer); ion_buffer_put(buffer); handle->buffer = NULL; handle->client = NULL; kfree(handle); } struct ion_buffer *ion_handle_buffer(struct ion_handle *handle) { return handle->buffer; } static void ion_handle_get(struct ion_handle *handle) { kref_get(&handle->ref); } static int ion_handle_put(struct ion_handle *handle) { return kref_put(&handle->ref, ion_handle_destroy); } static struct ion_handle *ion_handle_lookup(struct ion_client *client, struct ion_buffer *buffer) { struct rb_node *n = client->handles.rb_node; while (n) { struct ion_handle *entry = rb_entry(n, struct ion_handle, node); if (buffer < entry->buffer) n = n->rb_left; else if (buffer > entry->buffer) n = n->rb_right; else return entry; } return ERR_PTR(-EINVAL); } struct ion_handle *ion_uhandle_get(struct ion_client *client, int id) { return idr_find(&client->idr, id); } bool ion_handle_validate(struct ion_client *client, struct ion_handle *handle) { return (ion_uhandle_get(client, handle->id) == handle); } static int ion_handle_add(struct ion_client *client, struct ion_handle *handle) { int rc; struct rb_node **p = &client->handles.rb_node; struct rb_node *parent = NULL; struct ion_handle *entry; do { int id; rc = idr_pre_get(&client->idr, GFP_KERNEL); if (!rc) return -ENOMEM; rc = idr_get_new_above(&client->idr, handle, 1, &id); handle->id = id; } while (rc == -EAGAIN); if (rc < 0) return rc; while (*p) { parent = *p; entry = rb_entry(parent, struct ion_handle, node); if (handle->buffer < entry->buffer) p = &(*p)->rb_left; else if (handle->buffer > entry->buffer) p = &(*p)->rb_right; else WARN(1, "%s: buffer already found.", __func__); } rb_link_node(&handle->node, parent, p); rb_insert_color(&handle->node, &client->handles); return 0; } struct ion_handle *ion_alloc(struct ion_client *client, size_t len, size_t align, unsigned int heap_id_mask, unsigned int flags) { struct ion_handle *handle; struct ion_device *dev = client->dev; struct ion_buffer *buffer = NULL; struct ion_heap *heap; int ret; pr_debug("%s: len %d align %d heap_id_mask %u flags %x\n", __func__, len, align, heap_id_mask, flags); /* * traverse the list of heaps available in this system in priority * order. If the heap type is supported by the client, and matches the * request of the caller allocate from it. Repeat until allocate has * succeeded or all heaps have been tried */ if (WARN_ON(!len)) return ERR_PTR(-EINVAL); //add by k.zhang if((len > 1024*1024*1024)) { IONMSG("%s error: size (%d) is more than 1G !!\n", len); return ERR_PTR(-EINVAL); } MMProfileLogEx(ION_MMP_Events[PROFILE_ALLOC], MMProfileFlagStart, len, 0); len = PAGE_ALIGN(len); down_read(&dev->lock); plist_for_each_entry(heap, &dev->heaps, node) { /* if the caller didn't specify this heap id */ if (!((1 << heap->id) & heap_id_mask)) continue; buffer = ion_buffer_create(heap, dev, len, align, flags); if (!IS_ERR(buffer)) break; } up_read(&dev->lock); if (buffer == NULL) return ERR_PTR(-ENODEV); if (IS_ERR(buffer)) return ERR_PTR(PTR_ERR(buffer)); handle = ion_handle_create(client, buffer); /* * ion_buffer_create will create a buffer with a ref_cnt of 1, * and ion_handle_create will take a second reference, drop one here */ ion_buffer_put(buffer); if (IS_ERR(handle)) return handle; mutex_lock(&client->lock); ret = ion_handle_add(client, handle); if (ret) { ion_handle_put(handle); handle = ERR_PTR(ret); } mutex_unlock(&client->lock); MMProfileLogEx(ION_MMP_Events[PROFILE_ALLOC], MMProfileFlagEnd, buffer->size, 0); return handle; } EXPORT_SYMBOL(ion_alloc); void ion_free(struct ion_client *client, struct ion_handle *handle) { bool valid_handle; BUG_ON(client != handle->client); mutex_lock(&client->lock); valid_handle = ion_handle_validate(client, handle); if (!valid_handle) { WARN(1, "%s: invalid handle passed to free.\n", __func__); mutex_unlock(&client->lock); return; } ion_handle_put(handle); mutex_unlock(&client->lock); } EXPORT_SYMBOL(ion_free); int ion_phys(struct ion_client *client, struct ion_handle *handle, ion_phys_addr_t *addr, size_t *len) { struct ion_buffer *buffer; int ret; MMProfileLogEx(ION_MMP_Events[PROFILE_GET_PHYS], MMProfileFlagStart, (unsigned int)client, (unsigned int)handle); mutex_lock(&client->lock); if (!ion_handle_validate(client, handle)) { mutex_unlock(&client->lock); return -EINVAL; } buffer = handle->buffer; if (!buffer->heap->ops->phys) { pr_err("%s: ion_phys is not implemented by this heap.\n", __func__); mutex_unlock(&client->lock); return -ENODEV; } mutex_unlock(&client->lock); ret = buffer->heap->ops->phys(buffer->heap, buffer, addr, len); MMProfileLogEx(ION_MMP_Events[PROFILE_GET_PHYS], MMProfileFlagEnd, buffer->size, *addr); return ret; } EXPORT_SYMBOL(ion_phys); static void *ion_buffer_kmap_get(struct ion_buffer *buffer) { void *vaddr; if (buffer->kmap_cnt) { buffer->kmap_cnt++; return buffer->vaddr; } vaddr = buffer->heap->ops->map_kernel(buffer->heap, buffer); if (WARN_ONCE(vaddr == NULL, "heap->ops->map_kernel should return ERR_PTR on error")) return ERR_PTR(-EINVAL); if (IS_ERR(vaddr)) return vaddr; buffer->vaddr = vaddr; buffer->kmap_cnt++; return vaddr; } static void *ion_handle_kmap_get(struct ion_handle *handle) { struct ion_buffer *buffer = handle->buffer; void *vaddr; if (handle->kmap_cnt) { handle->kmap_cnt++; return buffer->vaddr; } vaddr = ion_buffer_kmap_get(buffer); if (IS_ERR(vaddr)) return vaddr; handle->kmap_cnt++; return vaddr; } static void ion_buffer_kmap_put(struct ion_buffer *buffer) { buffer->kmap_cnt--; if (!buffer->kmap_cnt) { MMProfileLogEx(ION_MMP_Events[PROFILE_UNMAP_KERNEL], MMProfileFlagStart, buffer->size, 0); buffer->heap->ops->unmap_kernel(buffer->heap, buffer); MMProfileLogEx(ION_MMP_Events[PROFILE_UNMAP_KERNEL], MMProfileFlagEnd, buffer->size, 0); buffer->vaddr = NULL; } } static void ion_handle_kmap_put(struct ion_handle *handle) { struct ion_buffer *buffer = handle->buffer; handle->kmap_cnt--; if (!handle->kmap_cnt) ion_buffer_kmap_put(buffer); } void *ion_map_kernel(struct ion_client *client, struct ion_handle *handle) { struct ion_buffer *buffer; void *vaddr; mutex_lock(&client->lock); if (!ion_handle_validate(client, handle)) { pr_err("%s: invalid handle passed to map_kernel.\n", __func__); mutex_unlock(&client->lock); return ERR_PTR(-EINVAL); } buffer = handle->buffer; if (!handle->buffer->heap->ops->map_kernel) { pr_err("%s: map_kernel is not implemented by this heap.\n", __func__); mutex_unlock(&client->lock); return ERR_PTR(-ENODEV); } mutex_lock(&buffer->lock); vaddr = ion_handle_kmap_get(handle); mutex_unlock(&buffer->lock); mutex_unlock(&client->lock); return vaddr; } EXPORT_SYMBOL(ion_map_kernel); void ion_unmap_kernel(struct ion_client *client, struct ion_handle *handle) { struct ion_buffer *buffer; mutex_lock(&client->lock); buffer = handle->buffer; mutex_lock(&buffer->lock); ion_handle_kmap_put(handle); mutex_unlock(&buffer->lock); mutex_unlock(&client->lock); } EXPORT_SYMBOL(ion_unmap_kernel); static int ion_debug_client_show(struct seq_file *s, void *unused) { struct ion_client *client = s->private; struct rb_node *n; size_t sizes[ION_NUM_HEAP_IDS] = {0}; const char *names[ION_NUM_HEAP_IDS] = {0}; int i; mutex_lock(&client->lock); for (n = rb_first(&client->handles); n; n = rb_next(n)) { struct ion_handle *handle = rb_entry(n, struct ion_handle, node); unsigned int id = handle->buffer->heap->id; if (!names[id]) names[id] = handle->buffer->heap->name; sizes[id] += handle->buffer->size; } mutex_unlock(&client->lock); seq_printf(s, "%16.16s: %16.16s\n", "heap_name", "size_in_bytes"); for (i = 0; i < ION_NUM_HEAP_IDS; i++) { if (!names[i]) continue; seq_printf(s, "%16.16s: %16u\n", names[i], sizes[i]); } return 0; } static int ion_debug_client_open(struct inode *inode, struct file *file) { return single_open(file, ion_debug_client_show, inode->i_private); } static const struct file_operations debug_client_fops = { .open = ion_debug_client_open, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; struct ion_client *ion_client_create(struct ion_device *dev, const char *name) { struct ion_client *client; struct task_struct *task; struct rb_node **p; struct rb_node *parent = NULL; struct ion_client *entry; char debug_name[64]; pid_t pid; get_task_struct(current->group_leader); task_lock(current->group_leader); pid = task_pid_nr(current->group_leader); /* don't bother to store task struct for kernel threads, they can't be killed anyway */ if (current->group_leader->flags & PF_KTHREAD) { put_task_struct(current->group_leader); task = NULL; } else { task = current->group_leader; } task_unlock(current->group_leader); client = kzalloc(sizeof(struct ion_client), GFP_KERNEL); if (!client) { if (task) put_task_struct(current->group_leader); return ERR_PTR(-ENOMEM); } client->dev = dev; client->handles = RB_ROOT; idr_init(&client->idr); mutex_init(&client->lock); client->name = name; client->task = task; client->pid = pid; down_write(&dev->lock); p = &dev->clients.rb_node; while (*p) { parent = *p; entry = rb_entry(parent, struct ion_client, node); if (client < entry) p = &(*p)->rb_left; else if (client > entry) p = &(*p)->rb_right; } rb_link_node(&client->node, parent, p); rb_insert_color(&client->node, &dev->clients); snprintf(debug_name, 64, "%u", client->pid); client->debug_root = debugfs_create_file(debug_name, 0664, dev->debug_root, client, &debug_client_fops); up_write(&dev->lock); return client; } EXPORT_SYMBOL(ion_client_create); void ion_client_destroy(struct ion_client *client) { struct ion_device *dev = client->dev; struct rb_node *n; pr_debug("%s: %d\n", __func__, __LINE__); while ((n = rb_first(&client->handles))) { struct ion_handle *handle = rb_entry(n, struct ion_handle, node); mutex_lock(&client->lock); ion_handle_destroy(&handle->ref); mutex_unlock(&client->lock); } idr_remove_all(&client->idr); idr_destroy(&client->idr); down_write(&dev->lock); if (client->task) put_task_struct(client->task); rb_erase(&client->node, &dev->clients); debugfs_remove_recursive(client->debug_root); up_write(&dev->lock); kfree(client); } EXPORT_SYMBOL(ion_client_destroy); struct sg_table *ion_sg_table(struct ion_client *client, struct ion_handle *handle) { struct ion_buffer *buffer; struct sg_table *table; mutex_lock(&client->lock); if (!ion_handle_validate(client, handle)) { pr_err("%s: invalid handle passed to map_dma.\n", __func__); mutex_unlock(&client->lock); return ERR_PTR(-EINVAL); } buffer = handle->buffer; table = buffer->sg_table; mutex_unlock(&client->lock); return table; } EXPORT_SYMBOL(ion_sg_table); static void ion_buffer_sync_for_device(struct ion_buffer *buffer, struct device *dev, enum dma_data_direction direction); static struct sg_table *ion_map_dma_buf(struct dma_buf_attachment *attachment, enum dma_data_direction direction) { struct dma_buf *dmabuf = attachment->dmabuf; struct ion_buffer *buffer = dmabuf->priv; ion_buffer_sync_for_device(buffer, attachment->dev, direction); return buffer->sg_table; } static void ion_unmap_dma_buf(struct dma_buf_attachment *attachment, struct sg_table *table, enum dma_data_direction direction) { } struct ion_vma_list { struct list_head list; struct vm_area_struct *vma; }; static void ion_buffer_sync_for_device(struct ion_buffer *buffer, struct device *dev, enum dma_data_direction dir) { struct ion_vma_list *vma_list; int pages = PAGE_ALIGN(buffer->size) / PAGE_SIZE; int i; pr_debug("%s: syncing for device %s\n", __func__, dev ? dev_name(dev) : "null"); if (!ion_buffer_fault_user_mappings(buffer)) return; mutex_lock(&buffer->lock); for (i = 0; i < pages; i++) { struct page *page = buffer->pages[i]; if (ion_buffer_page_is_dirty(page)) __dma_page_cpu_to_dev(page, 0, PAGE_SIZE, dir); ion_buffer_page_clean(buffer->pages + i); } list_for_each_entry(vma_list, &buffer->vmas, list) { struct vm_area_struct *vma = vma_list->vma; zap_page_range(vma, vma->vm_start, vma->vm_end - vma->vm_start, NULL); } mutex_unlock(&buffer->lock); } int ion_vm_fault(struct vm_area_struct *vma, struct vm_fault *vmf) { struct ion_buffer *buffer = vma->vm_private_data; int ret; mutex_lock(&buffer->lock); ion_buffer_page_dirty(buffer->pages + vmf->pgoff); BUG_ON(!buffer->pages || !buffer->pages[vmf->pgoff]); ret = vm_insert_page(vma, (unsigned long)vmf->virtual_address, ion_buffer_page(buffer->pages[vmf->pgoff])); mutex_unlock(&buffer->lock); if (ret) return VM_FAULT_ERROR; return VM_FAULT_NOPAGE; } static void ion_vm_open(struct vm_area_struct *vma) { struct ion_buffer *buffer = vma->vm_private_data; struct ion_vma_list *vma_list; vma_list = kmalloc(sizeof(struct ion_vma_list), GFP_KERNEL); if (!vma_list) return; vma_list->vma = vma; mutex_lock(&buffer->lock); list_add(&vma_list->list, &buffer->vmas); mutex_unlock(&buffer->lock); pr_debug("%s: adding %p\n", __func__, vma); } static void ion_vm_close(struct vm_area_struct *vma) { struct ion_buffer *buffer = vma->vm_private_data; struct ion_vma_list *vma_list, *tmp; pr_debug("%s\n", __func__); mutex_lock(&buffer->lock); list_for_each_entry_safe(vma_list, tmp, &buffer->vmas, list) { if (vma_list->vma != vma) continue; list_del(&vma_list->list); kfree(vma_list); pr_debug("%s: deleting %p\n", __func__, vma); break; } mutex_unlock(&buffer->lock); } struct vm_operations_struct ion_vma_ops = { .open = ion_vm_open, .close = ion_vm_close, .fault = ion_vm_fault, }; static int ion_mmap(struct dma_buf *dmabuf, struct vm_area_struct *vma) { struct ion_buffer *buffer = dmabuf->priv; int ret = 0; MMProfileLogEx(ION_MMP_Events[PROFILE_MAP_USER], MMProfileFlagStart, buffer->size, vma->vm_start); if (!buffer->heap->ops->map_user) { pr_err("%s: this heap does not define a method for mapping " "to userspace\n", __func__); return -EINVAL; } if (ion_buffer_fault_user_mappings(buffer)) { vma->vm_private_data = buffer; vma->vm_ops = &ion_vma_ops; ion_vm_open(vma); return 0; } //if (!(buffer->flags & ION_FLAG_CACHED)) //vma->vm_page_prot = pgprot_writecombine(vma->vm_page_prot); mutex_lock(&buffer->lock); /* now map it to userspace */ ret = buffer->heap->ops->map_user(buffer->heap, buffer, vma); mutex_unlock(&buffer->lock); if (ret) pr_err("%s: failure mapping buffer to userspace\n", __func__); MMProfileLogEx(ION_MMP_Events[PROFILE_MAP_USER], MMProfileFlagEnd, buffer->size, vma->vm_start); return ret; } static void ion_dma_buf_release(struct dma_buf *dmabuf) { struct ion_buffer *buffer = dmabuf->priv; ion_buffer_put(buffer); } static void *ion_dma_buf_kmap(struct dma_buf *dmabuf, unsigned long offset) { struct ion_buffer *buffer = dmabuf->priv; return buffer->vaddr + offset * PAGE_SIZE; } static void ion_dma_buf_kunmap(struct dma_buf *dmabuf, unsigned long offset, void *ptr) { return; } static int ion_dma_buf_begin_cpu_access(struct dma_buf *dmabuf, size_t start, size_t len, enum dma_data_direction direction) { struct ion_buffer *buffer = dmabuf->priv; void *vaddr; if (!buffer->heap->ops->map_kernel) { pr_err("%s: map kernel is not implemented by this heap.\n", __func__); return -ENODEV; } mutex_lock(&buffer->lock); vaddr = ion_buffer_kmap_get(buffer); mutex_unlock(&buffer->lock); if (IS_ERR(vaddr)) return PTR_ERR(vaddr); return 0; } static void ion_dma_buf_end_cpu_access(struct dma_buf *dmabuf, size_t start, size_t len, enum dma_data_direction direction) { struct ion_buffer *buffer = dmabuf->priv; mutex_lock(&buffer->lock); ion_buffer_kmap_put(buffer); mutex_unlock(&buffer->lock); } struct dma_buf_ops dma_buf_ops = { .map_dma_buf = ion_map_dma_buf, .unmap_dma_buf = ion_unmap_dma_buf, .mmap = ion_mmap, .release = ion_dma_buf_release, .begin_cpu_access = ion_dma_buf_begin_cpu_access, .end_cpu_access = ion_dma_buf_end_cpu_access, .kmap_atomic = ion_dma_buf_kmap, .kunmap_atomic = ion_dma_buf_kunmap, .kmap = ion_dma_buf_kmap, .kunmap = ion_dma_buf_kunmap, }; struct dma_buf *ion_share_dma_buf(struct ion_client *client, struct ion_handle *handle) { struct ion_buffer *buffer; struct dma_buf *dmabuf; bool valid_handle; mutex_lock(&client->lock); valid_handle = ion_handle_validate(client, handle); mutex_unlock(&client->lock); if (!valid_handle) { WARN(1, "%s: invalid handle passed to share.\n", __func__); return ERR_PTR(-EINVAL); } buffer = handle->buffer; ion_buffer_get(buffer); dmabuf = dma_buf_export(buffer, &dma_buf_ops, buffer->size, O_RDWR); if (IS_ERR(dmabuf)) { ion_buffer_put(buffer); return dmabuf; } return dmabuf; } EXPORT_SYMBOL(ion_share_dma_buf); int ion_share_dma_buf_fd(struct ion_client *client, struct ion_handle *handle) { struct dma_buf *dmabuf; int fd; dmabuf = ion_share_dma_buf(client, handle); if (IS_ERR(dmabuf)) return PTR_ERR(dmabuf); fd = dma_buf_fd(dmabuf, O_CLOEXEC); if (fd < 0) dma_buf_put(dmabuf); return fd; } EXPORT_SYMBOL(ion_share_dma_buf_fd); struct ion_handle *ion_import_dma_buf(struct ion_client *client, int fd) { struct dma_buf *dmabuf; struct ion_buffer *buffer; struct ion_handle *handle; int ret; MMProfileLogEx(ION_MMP_Events[PROFILE_IMPORT], MMProfileFlagStart, 1, 1); dmabuf = dma_buf_get(fd); if (IS_ERR(dmabuf)) return ERR_PTR(PTR_ERR(dmabuf)); /* if this memory came from ion */ if (dmabuf->ops != &dma_buf_ops) { pr_err("%s: can not import dmabuf from another exporter\n", __func__); dma_buf_put(dmabuf); return ERR_PTR(-EINVAL); } buffer = dmabuf->priv; mutex_lock(&client->lock); /* if a handle exists for this buffer just take a reference to it */ handle = ion_handle_lookup(client, buffer); if (!IS_ERR(handle)) { ion_handle_get(handle); goto end; } handle = ion_handle_create(client, buffer); if (IS_ERR(handle)) goto end; ret = ion_handle_add(client, handle); if (ret) { ion_handle_put(handle); handle = ERR_PTR(ret); } end: mutex_unlock(&client->lock); dma_buf_put(dmabuf); MMProfileLogEx(ION_MMP_Events[PROFILE_IMPORT], MMProfileFlagEnd, 1, 1); return handle; } EXPORT_SYMBOL(ion_import_dma_buf); static int ion_sync_for_device(struct ion_client *client, int fd) { struct dma_buf *dmabuf; struct ion_buffer *buffer; dmabuf = dma_buf_get(fd); if (IS_ERR(dmabuf)) return PTR_ERR(dmabuf); /* if this memory came from ion */ if (dmabuf->ops != &dma_buf_ops) { pr_err("%s: can not sync dmabuf from another exporter\n", __func__); dma_buf_put(dmabuf); return -EINVAL; } buffer = dmabuf->priv; dma_sync_sg_for_device(NULL, buffer->sg_table->sgl, buffer->sg_table->nents, DMA_BIDIRECTIONAL); dma_buf_put(dmabuf); return 0; } static long ion_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) { struct ion_client *client = filp->private_data; switch (cmd) { case ION_IOC_ALLOC: { struct ion_allocation_data data; struct ion_handle *handle; if (copy_from_user(&data, (void __user *)arg, sizeof(data))) return -EFAULT; handle = ion_alloc(client, data.len, data.align, data.heap_id_mask, data.flags); if (IS_ERR(handle)) return PTR_ERR(handle); data.handle = (struct ion_handle *)handle->id; if (copy_to_user((void __user *)arg, &data, sizeof(data))) { ion_free(client, handle); return -EFAULT; } break; } case ION_IOC_FREE: { struct ion_handle_data data; struct ion_handle *handle; if (copy_from_user(&data, (void __user *)arg, sizeof(struct ion_handle_data))) return -EFAULT; mutex_lock(&client->lock); handle = ion_uhandle_get(client, (int)data.handle); mutex_unlock(&client->lock); if(IS_ERR_OR_NULL(handle)) { pr_err("%s: handle invalid, handle_id=%d.\n", __FUNCTION__, (int)data.handle); return -EINVAL; } ion_free(client, handle); break; } case ION_IOC_SHARE: case ION_IOC_MAP: { struct ion_fd_data data; struct ion_handle *handle; if (copy_from_user(&data, (void __user *)arg, sizeof(data))) return -EFAULT; handle = ion_uhandle_get(client, (int)data.handle); if(IS_ERR_OR_NULL(handle)) { pr_err("%s: handle invalid, handle_id=%d\n", __FUNCTION__, (int)data.handle); return -EINVAL; } data.fd = ion_share_dma_buf_fd(client, handle); if (copy_to_user((void __user *)arg, &data, sizeof(data))) return -EFAULT; if (data.fd < 0) return data.fd; break; } case ION_IOC_IMPORT: { struct ion_fd_data data; struct ion_handle *handle; int ret = 0; if (copy_from_user(&data, (void __user *)arg, sizeof(struct ion_fd_data))) return -EFAULT; handle = ion_import_dma_buf(client, data.fd); if (IS_ERR(handle)) ret = PTR_ERR(handle); else data.handle = (struct ion_handle *)handle->id; if (copy_to_user((void __user *)arg, &data, sizeof(struct ion_fd_data))) return -EFAULT; if (ret < 0) return ret; break; } case ION_IOC_SYNC: { struct ion_fd_data data; if (copy_from_user(&data, (void __user *)arg, sizeof(struct ion_fd_data))) return -EFAULT; ion_sync_for_device(client, data.fd); break; } case ION_IOC_CUSTOM: { struct ion_device *dev = client->dev; struct ion_custom_data data; if (!dev->custom_ioctl) return -ENOTTY; if (copy_from_user(&data, (void __user *)arg, sizeof(struct ion_custom_data))) return -EFAULT; return dev->custom_ioctl(client, data.cmd, data.arg); } default: return -ENOTTY; } return 0; } static int ion_release(struct inode *inode, struct file *file) { struct ion_client *client = file->private_data; pr_debug("%s: %d\n", __func__, __LINE__); ion_client_destroy(client); return 0; } static int ion_open(struct inode *inode, struct file *file) { struct miscdevice *miscdev = file->private_data; struct ion_device *dev = container_of(miscdev, struct ion_device, dev); struct ion_client *client; pr_debug("%s: %d\n", __func__, __LINE__); client = ion_client_create(dev, "user"); if (IS_ERR(client)) return PTR_ERR(client); file->private_data = client; return 0; } static const struct file_operations ion_fops = { .owner = THIS_MODULE, .open = ion_open, .release = ion_release, .unlocked_ioctl = ion_ioctl, }; static size_t ion_debug_heap_total(struct ion_client *client, unsigned int id) { size_t size = 0; struct rb_node *n; mutex_lock(&client->lock); for (n = rb_first(&client->handles); n; n = rb_next(n)) { struct ion_handle *handle = rb_entry(n, struct ion_handle, node); if (handle->buffer->heap->id == id) size += handle->buffer->size; } mutex_unlock(&client->lock); return size; } static int ion_debug_heap_show(struct seq_file *s, void *unused) { struct ion_heap *heap = s->private; struct ion_device *dev = heap->dev; struct rb_node *n; size_t total_size = 0; size_t total_orphaned_size = 0; seq_printf(s, "%16.s %16.s %16.s\n", "client", "pid", "size"); seq_printf(s, "----------------------------------------------------\n"); down_read(&dev->lock); for (n = rb_first(&dev->clients); n; n = rb_next(n)) { struct ion_client *client = rb_entry(n, struct ion_client, node); size_t size = ion_debug_heap_total(client, heap->id); if (!size) continue; if (client->task) { char task_comm[TASK_COMM_LEN]; get_task_comm(task_comm, client->task); seq_printf(s, "%16.s %16u %16u\n", task_comm, client->pid, size); } else { seq_printf(s, "%16.s %16u %16u\n", client->name, client->pid, size); } } up_read(&dev->lock); seq_printf(s, "----------------------------------------------------\n"); seq_printf(s, "orphaned allocations (info is from last known client):" "\n"); mutex_lock(&dev->buffer_lock); for (n = rb_first(&dev->buffers); n; n = rb_next(n)) { struct ion_buffer *buffer = rb_entry(n, struct ion_buffer, node); if (buffer->heap->id != heap->id) continue; total_size += buffer->size; if (!buffer->handle_count) { seq_printf(s, "%16.s %16u %16u %d %d\n", buffer->task_comm, buffer->pid, buffer->size, buffer->kmap_cnt, atomic_read(&buffer->ref.refcount)); total_orphaned_size += buffer->size; } } mutex_unlock(&dev->buffer_lock); seq_printf(s, "----------------------------------------------------\n"); seq_printf(s, "%16.s %16u\n", "total orphaned", total_orphaned_size); seq_printf(s, "%16.s %16u\n", "total ", total_size); if (heap->flags & ION_HEAP_FLAG_DEFER_FREE) seq_printf(s, "%16.s %16u\n", "deferred free", heap->free_list_size); seq_printf(s, "----------------------------------------------------\n"); if (heap->debug_show) heap->debug_show(heap, s, unused); return 0; } static int ion_debug_heap_open(struct inode *inode, struct file *file) { return single_open(file, ion_debug_heap_show, inode->i_private); } static const struct file_operations debug_heap_fops = { .open = ion_debug_heap_open, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; #ifdef DEBUG_HEAP_SHRINKER static int debug_shrink_set(void *data, u64 val) { struct ion_heap *heap = data; struct shrink_control sc; int objs; sc.gfp_mask = -1; sc.nr_to_scan = 0; if (!val) return 0; objs = heap->shrinker.shrink(&heap->shrinker, &sc); sc.nr_to_scan = objs; heap->shrinker.shrink(&heap->shrinker, &sc); return 0; } static int debug_shrink_get(void *data, u64 *val) { struct ion_heap *heap = data; struct shrink_control sc; int objs; sc.gfp_mask = -1; sc.nr_to_scan = 0; objs = heap->shrinker.shrink(&heap->shrinker, &sc); *val = objs; return 0; } DEFINE_SIMPLE_ATTRIBUTE(debug_shrink_fops, debug_shrink_get, debug_shrink_set, "%llu\n"); #endif void ion_device_add_heap(struct ion_device *dev, struct ion_heap *heap) { if (!heap->ops->allocate || !heap->ops->free || !heap->ops->map_dma || !heap->ops->unmap_dma) pr_err("%s: can not add heap with invalid ops struct.\n", __func__); if (heap->flags & ION_HEAP_FLAG_DEFER_FREE) ion_heap_init_deferred_free(heap); heap->dev = dev; down_write(&dev->lock); /* use negative heap->id to reverse the priority -- when traversing the list later attempt higher id numbers first */ plist_node_init(&heap->node, -heap->id); plist_add(&heap->node, &dev->heaps); debugfs_create_file(heap->name, 0664, dev->debug_root, heap, &debug_heap_fops); #ifdef DEBUG_HEAP_SHRINKER if (heap->shrinker.shrink) { char debug_name[64]; snprintf(debug_name, 64, "%s_shrink", heap->name); debugfs_create_file(debug_name, 0644, dev->debug_root, heap, &debug_shrink_fops); } #endif up_write(&dev->lock); } struct ion_device *ion_device_create(long (*custom_ioctl) (struct ion_client *client, unsigned int cmd, unsigned long arg)) { struct ion_device *idev; int ret; idev = kzalloc(sizeof(struct ion_device), GFP_KERNEL); if (!idev) return ERR_PTR(-ENOMEM); idev->dev.minor = MISC_DYNAMIC_MINOR; idev->dev.name = "ion"; idev->dev.fops = &ion_fops; idev->dev.parent = NULL; ret = misc_register(&idev->dev); if (ret) { pr_err("ion: failed to register misc device.\n"); return ERR_PTR(ret); } idev->debug_root = debugfs_create_dir("ion", NULL); if (!idev->debug_root) pr_err("ion: failed to create debug files.\n"); idev->custom_ioctl = custom_ioctl; idev->buffers = RB_ROOT; mutex_init(&idev->buffer_lock); init_rwsem(&idev->lock); plist_head_init(&idev->heaps); idev->clients = RB_ROOT; return idev; } void ion_device_destroy(struct ion_device *dev) { misc_deregister(&dev->dev); /* XXX need to free the heaps and clients ? */ kfree(dev); } void __init ion_reserve(struct ion_platform_data *data) { int i; for (i = 0; i < data->nr; i++) { if (data->heaps[i].size == 0) continue; IONMSG("reserve memory: base=0x%x, size=0x%x\n", data->heaps[i].base, data->heaps[i].size); if (data->heaps[i].base == 0) { phys_addr_t paddr; paddr = memblock_alloc_base(data->heaps[i].size, data->heaps[i].align, MEMBLOCK_ALLOC_ANYWHERE); if (!paddr) { pr_err("%s: error allocating memblock for " "heap %d\n", __func__, i); continue; } data->heaps[i].base = paddr; } else { int ret = memblock_reserve(data->heaps[i].base, data->heaps[i].size); if (ret) pr_err("memblock reserve of %x@%lx failed\n", data->heaps[i].size, data->heaps[i].base); } pr_info("%s: %s reserved base %lx size %d\n", __func__, data->heaps[i].name, data->heaps[i].base, data->heaps[i].size); } }
HelllGuest/boom_kernel_sprout_kk
drivers/gpu/ion/ion.c
C
gpl-2.0
48,833
/************************************************************************** * Copyright (c) 2007, Intel Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope 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 St - Fifth Floor, Boston, MA 02110-1301 USA. * **************************************************************************/ #include <drm/drmP.h> #ifdef CONFIG_DRM_VXD_BYT #include "vxd_drv.h" #else #include "psb_drv.h" #include "psb_reg.h" #endif #ifdef SUPPORT_VSP #include "vsp.h" #endif /* * Code for the MSVDX/TOPAZ MMU: */ /* * clflush on one processor only: * clflush should apparently flush the cache line on all processors in an * SMP system. */ /* * kmap atomic: * The usage of the slots must be completely encapsulated within a spinlock, and * no other functions that may be using the locks for other purposed may be * called from within the locked region. * Since the slots are per processor, this will guarantee that we are the only * user. */ /* * TODO: Inserting ptes from an interrupt handler: * This may be desirable for some SGX functionality where the GPU can fault in * needed pages. For that, we need to make an atomic insert_pages function, that * may fail. * If it fails, the caller need to insert the page using a workqueue function, * but on average it should be fast. */ struct psb_mmu_driver { /* protects driver- and pd structures. Always take in read mode * before taking the page table spinlock. */ struct rw_semaphore sem; /* protects page tables, directory tables and pt tables. * and pt structures. */ spinlock_t lock; atomic_t needs_tlbflush; uint8_t __iomem *register_map; struct psb_mmu_pd *default_pd; /*uint32_t bif_ctrl;*/ int has_clflush; int clflush_add; unsigned long clflush_mask; struct drm_psb_private *dev_priv; enum mmu_type_t mmu_type; }; struct psb_mmu_pd; struct psb_mmu_pt { struct psb_mmu_pd *pd; uint32_t index; uint32_t count; struct page *p; uint32_t *v; }; struct psb_mmu_pd { struct psb_mmu_driver *driver; int hw_context; struct psb_mmu_pt **tables; struct page *p; struct page *dummy_pt; struct page *dummy_page; uint32_t pd_mask; uint32_t invalid_pde; uint32_t invalid_pte; }; static inline uint32_t psb_mmu_pt_index(uint32_t offset) { return (offset >> PSB_PTE_SHIFT) & 0x3FF; } static inline uint32_t psb_mmu_pd_index(uint32_t offset) { return offset >> PSB_PDE_SHIFT; } #if defined(CONFIG_X86) static inline void psb_clflush(volatile void *addr) { __asm__ __volatile__("clflush (%0)\n" : : "r"(addr) : "memory"); } static inline void psb_mmu_clflush(struct psb_mmu_driver *driver, void *addr) { if (!driver->has_clflush) return; mb(); psb_clflush(addr); mb(); } static void psb_page_clflush(struct psb_mmu_driver *driver, struct page* page) { uint32_t clflush_add = driver->clflush_add >> PAGE_SHIFT; uint32_t clflush_count = PAGE_SIZE / clflush_add; int i; uint8_t *clf; #if (LINUX_VERSION_CODE < KERNEL_VERSION(3, 8, 0)) clf = kmap_atomic(page, KM_USER0); #else clf = kmap_atomic(page); #endif mb(); for (i = 0; i < clflush_count; ++i) { psb_clflush(clf); clf += clflush_add; } mb(); #if (LINUX_VERSION_CODE < KERNEL_VERSION(3, 8, 0)) kunmap_atomic(clf, KM_USER0); #else kunmap_atomic(clf); #endif } static void psb_pages_clflush(struct psb_mmu_driver *driver, struct page *page[], unsigned long num_pages) { int i; if (!driver->has_clflush) return ; for (i = 0; i < num_pages; i++) psb_page_clflush(driver, *page++); } #else static inline void psb_mmu_clflush(struct psb_mmu_driver *driver, void *addr) { ; } static void psb_pages_clflush(struct psb_mmu_driver *driver, struct page *page[], unsigned long num_pages) { printk("Dumy psb_pages_clflush\n"); } #endif static void psb_mmu_flush_pd_locked(struct psb_mmu_driver *driver, int force) { if (atomic_read(&driver->needs_tlbflush) || force) { if (!driver->dev_priv) goto out; if (driver->mmu_type == IMG_MMU) { atomic_set( &driver->dev_priv->msvdx_mmu_invaldc, 1); #ifndef CONFIG_DRM_VXD_BYT atomic_set( &driver->dev_priv->topaz_mmu_invaldc, 1); #endif } else if (driver->mmu_type == VSP_MMU) { #ifdef SUPPORT_VSP atomic_set(&driver->dev_priv->vsp_mmu_invaldc, 1); #endif } else { DRM_ERROR("MMU: invalid MMU type %d\n", driver->mmu_type); } } out: atomic_set(&driver->needs_tlbflush, 0); } #if 0 static void psb_mmu_flush_pd(struct psb_mmu_driver *driver, int force) { down_write(&driver->sem); psb_mmu_flush_pd_locked(driver, force); up_write(&driver->sem); } #endif static void psb_virtual_addr_clflush(struct psb_mmu_driver *driver, void *vaddr, uint32_t num_pages) { int i, j; uint8_t *clf = (uint8_t*)vaddr; uint32_t clflush_add = (driver->clflush_add * sizeof(uint32_t)) >> PAGE_SHIFT; uint32_t clflush_count = PAGE_SIZE / clflush_add; DRM_INFO("clflush pages %d\n", num_pages); mb(); for (i = 0; i < num_pages; ++i) { for (j = 0; j < clflush_count; ++j) { psb_clflush(clf); clf += clflush_add; } } mb(); } void psb_mmu_flush(struct psb_mmu_driver *driver, int rc_prot) { if (rc_prot) down_write(&driver->sem); if (!driver->dev_priv) goto out; if (driver->mmu_type == IMG_MMU) { atomic_set(&driver->dev_priv->msvdx_mmu_invaldc, 1); #ifndef CONFIG_DRM_VXD_BYT atomic_set(&driver->dev_priv->topaz_mmu_invaldc, 1); #endif } else if (driver->mmu_type == VSP_MMU) { #ifdef SUPPORT_VSP atomic_set(&driver->dev_priv->vsp_mmu_invaldc, 1); #endif } else { DRM_ERROR("MMU: invalid MMU type %d\n", driver->mmu_type); } out: if (rc_prot) up_write(&driver->sem); } void psb_mmu_set_pd_context(struct psb_mmu_pd *pd, int hw_context) { /*ttm_tt_cache_flush(&pd->p, 1);*/ psb_pages_clflush(pd->driver, &pd->p, 1); down_write(&pd->driver->sem); wmb(); psb_mmu_flush_pd_locked(pd->driver, 1); pd->hw_context = hw_context; up_write(&pd->driver->sem); } static inline unsigned long psb_pd_addr_end(unsigned long addr, unsigned long end) { addr = (addr + PSB_PDE_MASK + 1) & ~PSB_PDE_MASK; return (addr < end) ? addr : end; } static inline uint32_t psb_mmu_mask_pte(uint32_t pfn, int type) { uint32_t mask = PSB_PTE_VALID; if (type & PSB_MMU_CACHED_MEMORY) mask |= PSB_PTE_CACHED; if (type & PSB_MMU_RO_MEMORY) mask |= PSB_PTE_RO; if (type & PSB_MMU_WO_MEMORY) mask |= PSB_PTE_WO; return (pfn << PAGE_SHIFT) | mask; } #ifdef SUPPORT_VSP static inline uint32_t vsp_mmu_mask_pte(uint32_t pfn, int type) { return (pfn & VSP_PDE_MASK) | VSP_PTE_VALID; } #endif struct psb_mmu_pd *psb_mmu_alloc_pd(struct psb_mmu_driver *driver, int trap_pagefaults, int invalid_type) { struct psb_mmu_pd *pd = kmalloc(sizeof(*pd), GFP_KERNEL); uint32_t *v; int i; if (!pd) return NULL; pd->p = alloc_page(GFP_DMA32); if (!pd->p) goto out_err1; pd->dummy_pt = alloc_page(GFP_DMA32); if (!pd->dummy_pt) goto out_err2; pd->dummy_page = alloc_page(GFP_DMA32); if (!pd->dummy_page) goto out_err3; if (!trap_pagefaults) { if (driver->mmu_type == IMG_MMU) { pd->invalid_pde = psb_mmu_mask_pte(page_to_pfn(pd->dummy_pt), invalid_type); pd->invalid_pte = psb_mmu_mask_pte(page_to_pfn(pd->dummy_page), invalid_type); } else if (driver->mmu_type == VSP_MMU) { #ifdef SUPPORT_VSP pd->invalid_pde = vsp_mmu_mask_pte(page_to_pfn(pd->dummy_pt), invalid_type); pd->invalid_pte = vsp_mmu_mask_pte(page_to_pfn(pd->dummy_page), invalid_type); #endif } else { DRM_ERROR("MMU: invalid MMU type %d\n", driver->mmu_type); goto out_err4; } } else { pd->invalid_pde = 0; pd->invalid_pte = 0; } v = kmap(pd->dummy_pt); if (!v) goto out_err4; for (i = 0; i < (PAGE_SIZE / sizeof(uint32_t)); ++i) v[i] = pd->invalid_pte; kunmap(pd->dummy_pt); v = kmap(pd->p); if (!v) goto out_err4; for (i = 0; i < (PAGE_SIZE / sizeof(uint32_t)); ++i) v[i] = pd->invalid_pde; kunmap(pd->p); v = kmap(pd->dummy_page); if (!v) goto out_err4; clear_page(v); kunmap(pd->dummy_page); pd->tables = vmalloc_user(sizeof(struct psb_mmu_pt *) * 1024); if (!pd->tables) goto out_err4; pd->hw_context = -1; pd->pd_mask = PSB_PTE_VALID; pd->driver = driver; return pd; out_err4: __free_page(pd->dummy_page); out_err3: __free_page(pd->dummy_pt); out_err2: __free_page(pd->p); out_err1: kfree(pd); return NULL; } void psb_mmu_free_pt(struct psb_mmu_pt *pt) { __free_page(pt->p); kfree(pt); } void psb_mmu_free_pagedir(struct psb_mmu_pd *pd) { struct psb_mmu_driver *driver = pd->driver; struct psb_mmu_pt *pt; int i; down_write(&driver->sem); if (pd->hw_context != -1) psb_mmu_flush_pd_locked(driver, 1); /* Should take the spinlock here, but we don't need to do that since we have the semaphore in write mode. */ for (i = 0; i < 1024; ++i) { pt = pd->tables[i]; if (pt) psb_mmu_free_pt(pt); } vfree(pd->tables); __free_page(pd->dummy_page); __free_page(pd->dummy_pt); __free_page(pd->p); kfree(pd); up_write(&driver->sem); } static struct psb_mmu_pt *psb_mmu_alloc_pt(struct psb_mmu_pd *pd) { struct psb_mmu_pt *pt = kmalloc(sizeof(*pt), GFP_KERNEL); void *v; uint32_t clflush_add = pd->driver->clflush_add >> PAGE_SHIFT; uint32_t clflush_count = PAGE_SIZE / clflush_add; spinlock_t *lock = &pd->driver->lock; uint8_t *clf; uint32_t *ptes; int i; if (!pt) return NULL; pt->p = alloc_page(GFP_DMA32); if (!pt->p) { kfree(pt); return NULL; } spin_lock(lock); #if (LINUX_VERSION_CODE < KERNEL_VERSION(3, 8, 0)) v = kmap_atomic(pt->p, KM_USER0); #else v = kmap_atomic(pt->p); #endif clf = (uint8_t *) v; ptes = (uint32_t *) v; for (i = 0; i < (PAGE_SIZE / sizeof(uint32_t)); ++i) *ptes++ = pd->invalid_pte; #if defined(CONFIG_X86) if (pd->driver->has_clflush && pd->hw_context != -1) { mb(); for (i = 0; i < clflush_count; ++i) { psb_clflush(clf); clf += clflush_add; } mb(); } #endif #if (LINUX_VERSION_CODE < KERNEL_VERSION(3, 8, 0)) kunmap_atomic(v, KM_USER0); #else kunmap_atomic(v); #endif spin_unlock(lock); pt->count = 0; pt->pd = pd; pt->index = 0; return pt; } struct psb_mmu_pt *psb_mmu_pt_alloc_map_lock(struct psb_mmu_pd *pd, unsigned long addr) { uint32_t index = psb_mmu_pd_index(addr); struct psb_mmu_pt *pt; uint32_t *v; spinlock_t *lock = &pd->driver->lock; struct psb_mmu_driver *driver = pd->driver; spin_lock(lock); pt = pd->tables[index]; while (!pt) { spin_unlock(lock); pt = psb_mmu_alloc_pt(pd); if (!pt) return NULL; spin_lock(lock); if (pd->tables[index]) { spin_unlock(lock); psb_mmu_free_pt(pt); spin_lock(lock); pt = pd->tables[index]; continue; } #if (LINUX_VERSION_CODE < KERNEL_VERSION(3, 8, 0)) v = kmap_atomic(pd->p, KM_USER0); #else v = kmap_atomic(pd->p); #endif pd->tables[index] = pt; if (driver->mmu_type == IMG_MMU) v[index] = (page_to_pfn(pt->p) << 12) | pd->pd_mask; #ifdef SUPPORT_VSP else if (driver->mmu_type == VSP_MMU) v[index] = (page_to_pfn(pt->p)); #endif else DRM_ERROR("MMU: invalid MMU type %d\n", driver->mmu_type); pt->index = index; #if (LINUX_VERSION_CODE < KERNEL_VERSION(3, 8, 0)) kunmap_atomic((void *) v, KM_USER0); #else kunmap_atomic((void *) v); #endif if (pd->hw_context != -1) { psb_mmu_clflush(pd->driver, (void *) &v[index]); atomic_set(&pd->driver->needs_tlbflush, 1); } } #if (LINUX_VERSION_CODE < KERNEL_VERSION(3, 8, 0)) pt->v = kmap_atomic(pt->p, KM_USER0); #else pt->v = kmap_atomic(pt->p); #endif return pt; } static struct psb_mmu_pt *psb_mmu_pt_map_lock(struct psb_mmu_pd *pd, unsigned long addr) { uint32_t index = psb_mmu_pd_index(addr); struct psb_mmu_pt *pt; spinlock_t *lock = &pd->driver->lock; spin_lock(lock); pt = pd->tables[index]; if (!pt) { spin_unlock(lock); return NULL; } #if (LINUX_VERSION_CODE < KERNEL_VERSION(3, 8, 0)) pt->v = kmap_atomic(pt->p, KM_USER0); #else pt->v = kmap_atomic(pt->p); #endif return pt; } static void psb_mmu_pt_unmap_unlock(struct psb_mmu_pt *pt) { struct psb_mmu_pd *pd = pt->pd; uint32_t *v; #if (LINUX_VERSION_CODE < KERNEL_VERSION(3, 8, 0)) kunmap_atomic(pt->v, KM_USER0); #else kunmap_atomic(pt->v); #endif if (pt->count == 0) { #if (LINUX_VERSION_CODE < KERNEL_VERSION(3, 8, 0)) v = kmap_atomic(pd->p, KM_USER0); #else v = kmap_atomic(pd->p); #endif v[pt->index] = pd->invalid_pde; pd->tables[pt->index] = NULL; if (pd->hw_context != -1) { psb_mmu_clflush(pd->driver, (void *) &v[pt->index]); atomic_set(&pd->driver->needs_tlbflush, 1); } #if (LINUX_VERSION_CODE < KERNEL_VERSION(3, 8, 0)) kunmap_atomic(pt->v, KM_USER0); #else kunmap_atomic(pt->v); #endif spin_unlock(&pd->driver->lock); psb_mmu_free_pt(pt); return; } spin_unlock(&pd->driver->lock); } static inline void psb_mmu_set_pte(struct psb_mmu_pt *pt, unsigned long addr, uint32_t pte) { pt->v[psb_mmu_pt_index(addr)] = pte; } static inline void psb_mmu_invalidate_pte(struct psb_mmu_pt *pt, unsigned long addr) { pt->v[psb_mmu_pt_index(addr)] = pt->pd->invalid_pte; } #if 0 static uint32_t psb_mmu_check_pte_locked(struct psb_mmu_pd *pd, uint32_t mmu_offset) { uint32_t *v; uint32_t pfn; v = kmap_atomic(pd->p, KM_USER0); if (!v) { printk(KERN_INFO "Could not kmap pde page.\n"); return 0; } pfn = v[psb_mmu_pd_index(mmu_offset)]; /* printk(KERN_INFO "pde is 0x%08x\n",pfn); */ kunmap_atomic(v, KM_USER0); if (((pfn & 0x0F) != PSB_PTE_VALID)) { printk(KERN_INFO "Strange pde at 0x%08x: 0x%08x.\n", mmu_offset, pfn); } v = ioremap(pfn & 0xFFFFF000, 4096); if (!v) { printk(KERN_INFO "Could not kmap pte page.\n"); return 0; } pfn = v[psb_mmu_pt_index(mmu_offset)]; /* printk(KERN_INFO "pte is 0x%08x\n",pfn); */ iounmap(v); if (((pfn & 0x0F) != PSB_PTE_VALID)) { printk(KERN_INFO "Strange pte at 0x%08x: 0x%08x.\n", mmu_offset, pfn); } return pfn >> PAGE_SHIFT; } static void psb_mmu_check_mirrored_gtt(struct psb_mmu_pd *pd, uint32_t mmu_offset, uint32_t gtt_pages) { uint32_t start; uint32_t next; printk(KERN_INFO "Checking mirrored gtt 0x%08x %d\n", mmu_offset, gtt_pages); down_read(&pd->driver->sem); start = psb_mmu_check_pte_locked(pd, mmu_offset); mmu_offset += PAGE_SIZE; gtt_pages -= 1; while (gtt_pages--) { next = psb_mmu_check_pte_locked(pd, mmu_offset); if (next != start + 1) { printk(KERN_INFO "Ptes out of order: 0x%08x, 0x%08x.\n", start, next); } start = next; mmu_offset += PAGE_SIZE; } up_read(&pd->driver->sem); } void psb_mmu_mirror_gtt(struct psb_mmu_pd *pd, uint32_t mmu_offset, uint32_t gtt_start, uint32_t gtt_pages) { uint32_t *v; uint32_t start = psb_mmu_pd_index(mmu_offset); struct psb_mmu_driver *driver = pd->driver; int num_pages = gtt_pages; down_read(&driver->sem); spin_lock(&driver->lock); v = kmap_atomic(pd->p, KM_USER0); v += start; while (gtt_pages--) { *v++ = gtt_start | pd->pd_mask; gtt_start += PAGE_SIZE; } /*ttm_tt_cache_flush(&pd->p, num_pages);*/ psb_pages_clflush(pd->driver, &pd->p, num_pages); kunmap_atomic(v, KM_USER0); spin_unlock(&driver->lock); if (pd->hw_context != -1) atomic_set(&pd->driver->needs_tlbflush, 1); up_read(&pd->driver->sem); psb_mmu_flush_pd(pd->driver, 0); } #endif struct psb_mmu_pd *psb_mmu_get_default_pd(struct psb_mmu_driver *driver) { struct psb_mmu_pd *pd; /* down_read(&driver->sem); */ pd = driver->default_pd; /* up_read(&driver->sem); */ return pd; } /* Returns the physical address of the PD shared by sgx/msvdx */ uint32_t psb_get_default_pd_addr(struct psb_mmu_driver *driver) { struct psb_mmu_pd *pd; pd = psb_mmu_get_default_pd(driver); return page_to_pfn(pd->p) << PAGE_SHIFT; } void psb_mmu_driver_takedown(struct psb_mmu_driver *driver) { psb_mmu_free_pagedir(driver->default_pd); kfree(driver); } struct psb_mmu_driver *psb_mmu_driver_init(uint8_t __iomem * registers, int trap_pagefaults, int invalid_type, struct drm_psb_private *dev_priv, enum mmu_type_t mmu_type) { struct psb_mmu_driver *driver; driver = kmalloc(sizeof(*driver), GFP_KERNEL); if (!driver) return NULL; driver->dev_priv = dev_priv; driver->mmu_type = mmu_type; driver->default_pd = psb_mmu_alloc_pd(driver, trap_pagefaults, invalid_type); if (!driver->default_pd) goto out_err1; spin_lock_init(&driver->lock); init_rwsem(&driver->sem); down_write(&driver->sem); driver->register_map = registers; atomic_set(&driver->needs_tlbflush, 1); driver->has_clflush = 0; #if defined(CONFIG_X86) if (boot_cpu_has(X86_FEATURE_CLFLSH)) { uint32_t tfms, misc, cap0, cap4, clflush_size; /* * clflush size is determined at kernel setup for x86_64 * but not for i386. We have to do it here. */ cpuid(0x00000001, &tfms, &misc, &cap0, &cap4); clflush_size = ((misc >> 8) & 0xff) * 8; driver->has_clflush = 1; driver->clflush_add = PAGE_SIZE * clflush_size / sizeof(uint32_t); driver->clflush_mask = driver->clflush_add - 1; driver->clflush_mask = ~driver->clflush_mask; } #endif up_write(&driver->sem); return driver; out_err1: kfree(driver); return NULL; } #if defined(CONFIG_X86) static void psb_mmu_flush_ptes(struct psb_mmu_pd *pd, unsigned long address, uint32_t num_pages, uint32_t desired_tile_stride, uint32_t hw_tile_stride) { struct psb_mmu_pt *pt; uint32_t rows = 1; uint32_t i; unsigned long addr; unsigned long end; unsigned long next; unsigned long add; unsigned long row_add; unsigned long clflush_add = pd->driver->clflush_add; unsigned long clflush_mask = pd->driver->clflush_mask; if (!pd->driver->has_clflush) { /*ttm_tt_cache_flush(&pd->p, num_pages);*/ psb_pages_clflush(pd->driver, &pd->p, num_pages); return; } if (hw_tile_stride) rows = num_pages / desired_tile_stride; else desired_tile_stride = num_pages; add = desired_tile_stride << PAGE_SHIFT; row_add = hw_tile_stride << PAGE_SHIFT; mb(); for (i = 0; i < rows; ++i) { addr = address; end = addr + add; do { next = psb_pd_addr_end(addr, end); pt = psb_mmu_pt_map_lock(pd, addr); if (!pt) continue; do { psb_clflush(&pt->v [psb_mmu_pt_index(addr)]); } while (addr += clflush_add, (addr & clflush_mask) < next); psb_mmu_pt_unmap_unlock(pt); } while (addr = next, next != end); address += row_add; } mb(); } #else static void psb_mmu_flush_ptes(struct psb_mmu_pd *pd, unsigned long address, uint32_t num_pages, uint32_t desired_tile_stride, uint32_t hw_tile_stride) { drm_ttm_cache_flush(&pd->p, num_pages); } #endif void psb_mmu_remove_pfn_sequence(struct psb_mmu_pd *pd, unsigned long address, uint32_t num_pages) { struct psb_mmu_pt *pt; unsigned long addr; unsigned long end; unsigned long next; unsigned long f_address = address; down_read(&pd->driver->sem); addr = address; end = addr + (num_pages << PAGE_SHIFT); do { next = psb_pd_addr_end(addr, end); pt = psb_mmu_pt_alloc_map_lock(pd, addr); if (!pt) goto out; do { psb_mmu_invalidate_pte(pt, addr); --pt->count; } while (addr += PAGE_SIZE, addr < next); psb_mmu_pt_unmap_unlock(pt); } while (addr = next, next != end); out: if (pd->hw_context != -1) psb_mmu_flush_ptes(pd, f_address, num_pages, 1, 1); up_read(&pd->driver->sem); if (pd->hw_context != -1) psb_mmu_flush(pd->driver, 0); return; } void psb_mmu_remove_pages(struct psb_mmu_pd *pd, unsigned long address, uint32_t num_pages, uint32_t desired_tile_stride, uint32_t hw_tile_stride) { struct psb_mmu_pt *pt; uint32_t rows = 1; uint32_t i; unsigned long addr; unsigned long end; unsigned long next; unsigned long add; unsigned long row_add; unsigned long f_address = address; if (hw_tile_stride) rows = num_pages / desired_tile_stride; else desired_tile_stride = num_pages; add = desired_tile_stride << PAGE_SHIFT; row_add = hw_tile_stride << PAGE_SHIFT; /* down_read(&pd->driver->sem); */ /* Make sure we only need to flush this processor's cache */ for (i = 0; i < rows; ++i) { addr = address; end = addr + add; do { next = psb_pd_addr_end(addr, end); pt = psb_mmu_pt_map_lock(pd, addr); if (!pt) continue; do { psb_mmu_invalidate_pte(pt, addr); --pt->count; } while (addr += PAGE_SIZE, addr < next); psb_mmu_pt_unmap_unlock(pt); } while (addr = next, next != end); address += row_add; } if (pd->hw_context != -1) psb_mmu_flush_ptes(pd, f_address, num_pages, desired_tile_stride, hw_tile_stride); /* up_read(&pd->driver->sem); */ if (pd->hw_context != -1) psb_mmu_flush(pd->driver, 0); } int psb_mmu_insert_pfn_sequence(struct psb_mmu_pd *pd, uint32_t start_pfn, unsigned long address, uint32_t num_pages, int type) { struct psb_mmu_pt *pt; struct psb_mmu_driver *driver = pd->driver; uint32_t pte; unsigned long addr; unsigned long end; unsigned long next; unsigned long f_address = address; int ret = 0; down_read(&pd->driver->sem); addr = address; end = addr + (num_pages << PAGE_SHIFT); do { next = psb_pd_addr_end(addr, end); pt = psb_mmu_pt_alloc_map_lock(pd, addr); if (!pt) { ret = -ENOMEM; goto out; } do { if (driver->mmu_type == IMG_MMU) { pte = psb_mmu_mask_pte(start_pfn++, type); #ifdef SUPPORT_VSP } else if (driver->mmu_type == VSP_MMU) { pte = vsp_mmu_mask_pte(start_pfn++, type); #endif } else { DRM_ERROR("MMU: mmu type invalid %d\n", driver->mmu_type); ret = -EINVAL; goto out; } psb_mmu_set_pte(pt, addr, pte); pt->count++; } while (addr += PAGE_SIZE, addr < next); psb_mmu_pt_unmap_unlock(pt); } while (addr = next, next != end); out: if (pd->hw_context != -1) psb_mmu_flush_ptes(pd, f_address, num_pages, 1, 1); up_read(&pd->driver->sem); if (pd->hw_context != -1) psb_mmu_flush(pd->driver, 1); return ret; } int psb_mmu_insert_pages(struct psb_mmu_pd *pd, struct page **pages, unsigned long address, uint32_t num_pages, uint32_t desired_tile_stride, uint32_t hw_tile_stride, int type) { struct psb_mmu_pt *pt; struct psb_mmu_driver *driver = pd->driver; uint32_t rows = 1; uint32_t i; uint32_t pte; unsigned long addr; unsigned long end; unsigned long next; unsigned long add; unsigned long row_add; unsigned long f_address = address; int ret = 0; if (hw_tile_stride) { if (num_pages % desired_tile_stride != 0) return -EINVAL; rows = num_pages / desired_tile_stride; } else { desired_tile_stride = num_pages; } add = desired_tile_stride << PAGE_SHIFT; row_add = hw_tile_stride << PAGE_SHIFT; down_read(&pd->driver->sem); for (i = 0; i < rows; ++i) { addr = address; end = addr + add; do { next = psb_pd_addr_end(addr, end); pt = psb_mmu_pt_alloc_map_lock(pd, addr); if (!pt) { ret = -ENOMEM; goto out; } do { if (driver->mmu_type == IMG_MMU) { pte = psb_mmu_mask_pte( page_to_pfn(*pages++), type); #ifdef SUPPORT_VSP } else if (driver->mmu_type == VSP_MMU) { pte = vsp_mmu_mask_pte( page_to_pfn(*pages++), type); #endif } else { DRM_ERROR("MMU: mmu type invalid %d\n", driver->mmu_type); ret = -EINVAL; goto out; } psb_mmu_set_pte(pt, addr, pte); pt->count++; } while (addr += PAGE_SIZE, addr < next); psb_mmu_pt_unmap_unlock(pt); } while (addr = next, next != end); address += row_add; } out: if (pd->hw_context != -1) psb_mmu_flush_ptes(pd, f_address, num_pages, desired_tile_stride, hw_tile_stride); up_read(&pd->driver->sem); if (pd->hw_context != -1) psb_mmu_flush(pd->driver, 1); return ret; } #if 0 /*comented out, only used in mmu test now*/ void psb_mmu_enable_requestor(struct psb_mmu_driver *driver, uint32_t mask) { mask &= _PSB_MMU_ER_MASK; psb_iowrite32(driver, psb_ioread32(driver, PSB_CR_BIF_CTRL) & ~mask, PSB_CR_BIF_CTRL); (void) psb_ioread32(driver, PSB_CR_BIF_CTRL); } void psb_mmu_disable_requestor(struct psb_mmu_driver *driver, uint32_t mask) { mask &= _PSB_MMU_ER_MASK; psb_iowrite32(driver, psb_ioread32(driver, PSB_CR_BIF_CTRL) | mask, PSB_CR_BIF_CTRL); (void) psb_ioread32(driver, PSB_CR_BIF_CTRL); } int psb_mmu_virtual_to_pfn(struct psb_mmu_pd *pd, uint32_t virtual, unsigned long *pfn) { int ret; struct psb_mmu_pt *pt; uint32_t tmp; spinlock_t *lock = &pd->driver->lock; down_read(&pd->driver->sem); pt = psb_mmu_pt_map_lock(pd, virtual); if (!pt) { uint32_t *v; spin_lock(lock); v = kmap_atomic(pd->p, KM_USER0); tmp = v[psb_mmu_pd_index(virtual)]; kunmap_atomic(v, KM_USER0); spin_unlock(lock); if (tmp != pd->invalid_pde || !(tmp & PSB_PTE_VALID) || !(pd->invalid_pte & PSB_PTE_VALID)) { ret = -EINVAL; goto out; } ret = 0; *pfn = pd->invalid_pte >> PAGE_SHIFT; goto out; } tmp = pt->v[psb_mmu_pt_index(virtual)]; if (!(tmp & PSB_PTE_VALID)) { ret = -EINVAL; } else { ret = 0; *pfn = tmp >> PAGE_SHIFT; } psb_mmu_pt_unmap_unlock(pt); out: up_read(&pd->driver->sem); return ret; } void psb_mmu_test(struct psb_mmu_driver *driver, uint32_t offset) { struct page *p; unsigned long pfn; int ret = 0; struct psb_mmu_pd *pd; uint32_t *v; uint32_t *vmmu; pd = driver->default_pd; if (!pd) printk(KERN_WARNING "Could not get default pd\n"); p = alloc_page(GFP_DMA32); if (!p) { printk(KERN_WARNING "Failed allocating page\n"); return; } v = kmap(p); memset(v, 0x67, PAGE_SIZE); pfn = (offset >> PAGE_SHIFT); ret = psb_mmu_insert_pages(pd, &p, pfn << PAGE_SHIFT, 1, 0, 0, 0); if (ret) { printk(KERN_WARNING "Failed inserting mmu page\n"); goto out_err1; } /* Ioremap the page through the GART aperture */ vmmu = ioremap(pfn << PAGE_SHIFT, PAGE_SIZE); if (!vmmu) { printk(KERN_WARNING "Failed ioremapping page\n"); goto out_err2; } /* Read from the page with mmu disabled. */ printk(KERN_INFO "Page first dword is 0x%08x\n", ioread32(vmmu)); /* Enable the mmu for host accesses and read again. */ psb_mmu_enable_requestor(driver, _PSB_MMU_ER_HOST); printk(KERN_INFO "MMU Page first dword is (0x67676767) 0x%08x\n", ioread32(vmmu)); *v = 0x15243705; printk(KERN_INFO "MMU Page new dword is (0x15243705) 0x%08x\n", ioread32(vmmu)); iowrite32(0x16243355, vmmu); (void) ioread32(vmmu); printk(KERN_INFO "Page new dword is (0x16243355) 0x%08x\n", *v); printk(KERN_INFO "Int stat is 0x%08x\n", psb_ioread32(driver, PSB_CR_BIF_INT_STAT)); printk(KERN_INFO "Fault is 0x%08x\n", psb_ioread32(driver, PSB_CR_BIF_FAULT)); /* Disable MMU for host accesses and clear page fault register */ psb_mmu_disable_requestor(driver, _PSB_MMU_ER_HOST); iounmap(vmmu); out_err2: psb_mmu_remove_pages(pd, pfn << PAGE_SHIFT, 1, 0, 0); out_err1: kunmap(p); __free_page(p); } #endif /* void psb_mmu_pgtable_dump(struct drm_device *dev) { struct drm_psb_private *dev_priv = dev->dev_private; struct psb_mmu_pd *pd = psb_mmu_get_default_pd(dev_priv->mmu); struct psb_mmu_pt *pt; int i, j; uint32_t flags; uint32_t *v; spinlock_t *lock = &pd->driver->lock; down_read(&pd->driver->sem); spin_lock_irqsave(lock, flags); v = kmap_atomic(pd->p, KM_USER0); if (!v) { printk(KERN_INFO "%s: Kmap pg fail, abort\n", __func__); return; } printk(KERN_INFO "%s: start dump mmu page table\n", __func__); for (i = 0; i < 1024; i++) { pt = pd->tables[i]; if (!pt) { printk(KERN_INFO "pt[%d] is NULL, 0x%08x\n", i, v[i]); continue; } printk(KERN_INFO "pt[%d] is 0x%08x\n", i, v[i]); pt->v = kmap_atomic(pt->p, KM_USER0); if (!(pt->v)) { printk(KERN_INFO "%s: Kmap fail, abort\n", __func__); break; } for (j = 0; j < 1024; j++) { if (!(j%16)) printk(KERN_INFO "pte%d:", j); uint32_t pte = pt->v[j]; printk("%08xh ", pte); //if ((j%16) == 15) //printk(KERN_INFO "\n"); } kunmap_atomic(pt->v, KM_USER0); } spin_unlock_irqrestore(lock, flags); up_read(&pd->driver->sem); kunmap_atomic((void *) v, KM_USER0); printk(KERN_INFO "%s: finish dump mmu page table\n", __func__); } */ int psb_ttm_bo_clflush(struct psb_mmu_driver *mmu, struct ttm_buffer_object *bo) { int ret = 0; bool is_iomem; void *addr; struct ttm_bo_kmap_obj bo_kmap; if (unlikely(!mmu || !bo)) { DRM_ERROR("NULL pointer, mmu:%p bo:%p\n", mmu, bo); return 1; } /*map surface parameters*/ ret = ttm_bo_kmap(bo, 0, bo->num_pages, &bo_kmap); if (ret) { DRM_ERROR("ttm_bo_kmap failed: %d.\n", ret); return ret; } addr = (void *)ttm_kmap_obj_virtual(&bo_kmap, &is_iomem); if (unlikely(!addr)) { DRM_ERROR("failed to ttm_kmap_obj_virtual\n"); ret = 1; } psb_virtual_addr_clflush(mmu, addr, bo->num_pages); ttm_bo_kunmap(&bo_kmap); return ret; }
BenzoPlayer/kernel_asus_fugu
drivers/staging/imgtec/intel/video/common/psb_mmu.c
C
gpl-2.0
29,451
/* * Copyright (C) 2011-2014 MediaTek Inc. * * This program is free software: you can redistribute it and/or modify it under the terms of the * GNU General Public License version 2 as published by the Free Software Foundation. * * 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 <accdet_hal.h> #include <mach/mt_boot.h> #include <cust_eint.h> #include <cust_gpio_usage.h> #include <mach/mt_gpio.h> //#include "accdet_drv.h" static struct platform_driver accdet_driver; static int debug_enable_drv = 1; #define ACCDET_DEBUG_DRV(format, args...) do{ \ if(debug_enable_drv) \ {\ printk(KERN_WARNING format,##args);\ }\ }while(0) static long accdet_unlocked_ioctl(struct file *file, unsigned int cmd,unsigned long arg) { return mt_accdet_unlocked_ioctl(cmd, arg); } static int accdet_open(struct inode *inode, struct file *file) { return 0; } static int accdet_release(struct inode *inode, struct file *file) { return 0; } static struct file_operations accdet_fops = { .owner = THIS_MODULE, .unlocked_ioctl = accdet_unlocked_ioctl, .open = accdet_open, .release = accdet_release, }; struct file_operations *accdet_get_fops(void) { return &accdet_fops; } static int accdet_probe(struct platform_device *dev) { mt_accdet_probe(); return 0; } static int accdet_remove(struct platform_device *dev) { mt_accdet_remove(); return 0; } static int accdet_suspend(struct device *device) // wake up { mt_accdet_suspend(); return 0; } static int accdet_resume(struct device *device) // wake up { mt_accdet_resume(); return 0; } /********************************************************************** //add for IPO-H need update headset state when resume ***********************************************************************/ #ifdef CONFIG_PM static int accdet_pm_restore_noirq(struct device *device) { mt_accdet_pm_restore_noirq(); return 0; } static struct dev_pm_ops accdet_pm_ops = { .suspend = accdet_suspend, .resume = accdet_resume, .restore_noirq = accdet_pm_restore_noirq, }; #endif static struct platform_driver accdet_driver = { .probe = accdet_probe, //.suspend = accdet_suspend, //.resume = accdet_resume, .remove = accdet_remove, .driver = { .name = "Accdet_Driver", #ifdef CONFIG_PM .pm = &accdet_pm_ops, #endif }, }; struct platform_driver accdet_driver_func(void) { return accdet_driver; } static int accdet_mod_init(void) { int ret = 0; ACCDET_DEBUG_DRV("[Accdet]accdet_mod_init begin!\n"); //------------------------------------------------------------------ // Accdet PM //------------------------------------------------------------------ ret = platform_driver_register(&accdet_driver); if (ret) { ACCDET_DEBUG_DRV("[Accdet]platform_driver_register error:(%d)\n", ret); return ret; } else { ACCDET_DEBUG_DRV("[Accdet]platform_driver_register done!\n"); } ACCDET_DEBUG_DRV("[Accdet]accdet_mod_init done!\n"); return 0; } static void accdet_mod_exit(void) { ACCDET_DEBUG_DRV("[Accdet]accdet_mod_exit\n"); platform_driver_unregister(&accdet_driver); ACCDET_DEBUG_DRV("[Accdet]accdet_mod_exit Done!\n"); } /*Patch for CR ALPS00804150 & ALPS00804802 PMIC temp not correct issue*/ int accdet_cable_type_state(void) { //ACCDET_DEBUG("[ACCDET] accdet_cable_type_state=%d\n",accdet_get_cable_type()); return accdet_get_cable_type(); } EXPORT_SYMBOL(accdet_cable_type_state); /*Patch for CR ALPS00804150 & ALPS00804802 PMIC temp not correct issue*/ module_init(accdet_mod_init); module_exit(accdet_mod_exit); module_param(debug_enable_drv,int,0644); MODULE_DESCRIPTION("MTK MT6588 ACCDET driver"); MODULE_AUTHOR("Anny <Anny.Hu@mediatek.com>"); MODULE_LICENSE("GPL");
vredniiy/sprout
drivers/misc/mediatek/accdet/accdet_drv.c
C
gpl-2.0
4,055
/* * linux/kernel/seccomp.c * * Copyright 2004-2005 Andrea Arcangeli <andrea@cpushare.com> * * Copyright (C) 2012 Google, Inc. * Will Drewry <wad@chromium.org> * * This defines a simple but solid secure-computing facility. * * Mode 1 uses a fixed list of allowed system calls. * Mode 2 allows user-defined system call filters in the form * of Berkeley Packet Filters/Linux Socket Filters. */ #include <linux/atomic.h> #include <linux/audit.h> #include <linux/compat.h> #include <linux/sched.h> #include <linux/seccomp.h> #include <linux/slab.h> #include <linux/syscalls.h> /* #define SECCOMP_DEBUG 1 */ #ifdef CONFIG_HAVE_ARCH_SECCOMP_FILTER #include <asm/syscall.h> #endif #ifdef CONFIG_SECCOMP_FILTER #include <linux/filter.h> #include <linux/pid.h> #include <linux/ptrace.h> #include <linux/security.h> #include <linux/tracehook.h> #include <linux/uaccess.h> /** * struct seccomp_filter - container for seccomp BPF programs * * @usage: reference count to manage the object lifetime. * get/put helpers should be used when accessing an instance * outside of a lifetime-guarded section. In general, this * is only needed for handling filters shared across tasks. * @prev: points to a previously installed, or inherited, filter * @len: the number of instructions in the program * @insns: the BPF program instructions to evaluate * * seccomp_filter objects are organized in a tree linked via the @prev * pointer. For any task, it appears to be a singly-linked list starting * with current->seccomp.filter, the most recently attached or inherited filter. * However, multiple filters may share a @prev node, by way of fork(), which * results in a unidirectional tree existing in memory. This is similar to * how namespaces work. * * seccomp_filter objects should never be modified after being attached * to a task_struct (other than @usage). */ struct seccomp_filter { atomic_t usage; struct seccomp_filter *prev; unsigned short len; /* Instruction count */ struct sock_filter insns[]; }; /* Limit any path through the tree to 256KB worth of instructions. */ #define MAX_INSNS_PER_PATH ((1 << 18) / sizeof(struct sock_filter)) /** * get_u32 - returns a u32 offset into data * @data: a unsigned 64 bit value * @index: 0 or 1 to return the first or second 32-bits * * This inline exists to hide the length of unsigned long. If a 32-bit * unsigned long is passed in, it will be extended and the top 32-bits will be * 0. If it is a 64-bit unsigned long, then whatever data is resident will be * properly returned. * * Endianness is explicitly ignored and left for BPF program authors to manage * as per the specific architecture. */ static inline u32 get_u32(u64 data, int index) { return ((u32 *)&data)[index]; } /* Helper for bpf_load below. */ #define BPF_DATA(_name) offsetof(struct seccomp_data, _name) /** * bpf_load: checks and returns a pointer to the requested offset * @off: offset into struct seccomp_data to load from * * Returns the requested 32-bits of data. * seccomp_check_filter() should assure that @off is 32-bit aligned * and not out of bounds. Failure to do so is a BUG. */ u32 seccomp_bpf_load(int off) { struct pt_regs *regs = task_pt_regs(current); if (off == BPF_DATA(nr)) return syscall_get_nr(current, regs); if (off == BPF_DATA(arch)) return syscall_get_arch(); if (off >= BPF_DATA(args[0]) && off < BPF_DATA(args[6])) { unsigned long value; int arg = (off - BPF_DATA(args[0])) / sizeof(u64); int index = !!(off % sizeof(u64)); syscall_get_arguments(current, regs, arg, 1, &value); return get_u32(value, index); } if (off == BPF_DATA(instruction_pointer)) return get_u32(KSTK_EIP(current), 0); if (off == BPF_DATA(instruction_pointer) + sizeof(u32)) return get_u32(KSTK_EIP(current), 1); /* seccomp_check_filter should make this impossible. */ BUG(); } /** * seccomp_check_filter - verify seccomp filter code * @filter: filter to verify * @flen: length of filter * * Takes a previously checked filter (by sk_chk_filter) and * redirects all filter code that loads struct sk_buff data * and related data through seccomp_bpf_load. It also * enforces length and alignment checking of those loads. * * Returns 0 if the rule set is legal or -EINVAL if not. */ static int seccomp_check_filter(struct sock_filter *filter, unsigned int flen) { int pc; for (pc = 0; pc < flen; pc++) { struct sock_filter *ftest = &filter[pc]; u16 code = ftest->code; u32 k = ftest->k; switch (code) { case BPF_S_LD_W_ABS: ftest->code = BPF_S_ANC_SECCOMP_LD_W; /* 32-bit aligned and not out of bounds. */ if (k >= sizeof(struct seccomp_data) || k & 3) return -EINVAL; continue; case BPF_S_LD_W_LEN: ftest->code = BPF_S_LD_IMM; ftest->k = sizeof(struct seccomp_data); continue; case BPF_S_LDX_W_LEN: ftest->code = BPF_S_LDX_IMM; ftest->k = sizeof(struct seccomp_data); continue; /* Explicitly include allowed calls. */ case BPF_S_RET_K: case BPF_S_RET_A: case BPF_S_ALU_ADD_K: case BPF_S_ALU_ADD_X: case BPF_S_ALU_SUB_K: case BPF_S_ALU_SUB_X: case BPF_S_ALU_MUL_K: case BPF_S_ALU_MUL_X: case BPF_S_ALU_DIV_X: case BPF_S_ALU_AND_K: case BPF_S_ALU_AND_X: case BPF_S_ALU_OR_K: case BPF_S_ALU_OR_X: case BPF_S_ALU_XOR_K: case BPF_S_ALU_XOR_X: case BPF_S_ALU_LSH_K: case BPF_S_ALU_LSH_X: case BPF_S_ALU_RSH_K: case BPF_S_ALU_RSH_X: case BPF_S_ALU_NEG: case BPF_S_LD_IMM: case BPF_S_LDX_IMM: case BPF_S_MISC_TAX: case BPF_S_MISC_TXA: case BPF_S_ALU_DIV_K: case BPF_S_LD_MEM: case BPF_S_LDX_MEM: case BPF_S_ST: case BPF_S_STX: case BPF_S_JMP_JA: case BPF_S_JMP_JEQ_K: case BPF_S_JMP_JEQ_X: case BPF_S_JMP_JGE_K: case BPF_S_JMP_JGE_X: case BPF_S_JMP_JGT_K: case BPF_S_JMP_JGT_X: case BPF_S_JMP_JSET_K: case BPF_S_JMP_JSET_X: continue; default: return -EINVAL; } } return 0; } /** * seccomp_run_filters - evaluates all seccomp filters against @syscall * @syscall: number of the current system call * * Returns valid seccomp BPF response codes. */ static u32 seccomp_run_filters(void) { struct seccomp_filter *f = ACCESS_ONCE(current->seccomp.filter); u32 ret = SECCOMP_RET_ALLOW; /* Ensure unexpected behavior doesn't result in failing open. */ if (unlikely(WARN_ON(f == NULL))) return SECCOMP_RET_KILL; /* Make sure cross-thread synced filter points somewhere sane. */ smp_read_barrier_depends(); /* * All filters in the list are evaluated and the lowest BPF return * value always takes priority (ignoring the DATA). */ for (; f; f = f->prev) { u32 cur_ret = sk_run_filter(NULL, f->insns); if ((cur_ret & SECCOMP_RET_ACTION) < (ret & SECCOMP_RET_ACTION)) ret = cur_ret; } return ret; } #endif /* CONFIG_SECCOMP_FILTER */ static inline bool seccomp_may_assign_mode(unsigned long seccomp_mode) { assert_spin_locked(&current->sighand->siglock); if (current->seccomp.mode && current->seccomp.mode != seccomp_mode) return false; return true; } static inline void seccomp_assign_mode(struct task_struct *task, unsigned long seccomp_mode) { assert_spin_locked(&task->sighand->siglock); task->seccomp.mode = seccomp_mode; /* * Make sure TIF_SECCOMP cannot be set before the mode (and * filter) is set. */ smp_mb(); set_tsk_thread_flag(task, TIF_SECCOMP); } #ifdef CONFIG_SECCOMP_FILTER /* Returns 1 if the parent is an ancestor of the child. */ static int is_ancestor(struct seccomp_filter *parent, struct seccomp_filter *child) { /* NULL is the root ancestor. */ if (parent == NULL) return 1; for (; child; child = child->prev) if (child == parent) return 1; return 0; } /** * seccomp_can_sync_threads: checks if all threads can be synchronized * * Expects sighand and cred_guard_mutex locks to be held. * * Returns 0 on success, -ve on error, or the pid of a thread which was * either not in the correct seccomp mode or it did not have an ancestral * seccomp filter. */ static inline pid_t seccomp_can_sync_threads(void) { struct task_struct *thread, *caller; BUG_ON(!mutex_is_locked(&current->signal->cred_guard_mutex)); assert_spin_locked(&current->sighand->siglock); /* Validate all threads being eligible for synchronization. */ caller = current; for_each_thread(caller, thread) { pid_t failed; /* Skip current, since it is initiating the sync. */ if (thread == caller) continue; if (thread->seccomp.mode == SECCOMP_MODE_DISABLED || (thread->seccomp.mode == SECCOMP_MODE_FILTER && is_ancestor(thread->seccomp.filter, caller->seccomp.filter))) continue; /* Return the first thread that cannot be synchronized. */ failed = task_pid_vnr(thread); /* If the pid cannot be resolved, then return -ESRCH */ if (unlikely(WARN_ON(failed == 0))) failed = -ESRCH; return failed; } return 0; } /** * seccomp_sync_threads: sets all threads to use current's filter * * Expects sighand and cred_guard_mutex locks to be held, and for * seccomp_can_sync_threads() to have returned success already * without dropping the locks. * */ static inline void seccomp_sync_threads(void) { struct task_struct *thread, *caller; BUG_ON(!mutex_is_locked(&current->signal->cred_guard_mutex)); assert_spin_locked(&current->sighand->siglock); /* Synchronize all threads. */ caller = current; for_each_thread(caller, thread) { /* Skip current, since it needs no changes. */ if (thread == caller) continue; /* Get a task reference for the new leaf node. */ get_seccomp_filter(caller); /* * Drop the task reference to the shared ancestor since * current's path will hold a reference. (This also * allows a put before the assignment.) */ put_seccomp_filter(thread); smp_store_release(&thread->seccomp.filter, caller->seccomp.filter); /* * Opt the other thread into seccomp if needed. * As threads are considered to be trust-realm * equivalent (see ptrace_may_access), it is safe to * allow one thread to transition the other. */ if (thread->seccomp.mode == SECCOMP_MODE_DISABLED) { /* * Don't let an unprivileged task work around * the no_new_privs restriction by creating * a thread that sets it up, enters seccomp, * then dies. */ if (task_no_new_privs(caller)) task_set_no_new_privs(thread); seccomp_assign_mode(thread, SECCOMP_MODE_FILTER); } } } /** * seccomp_prepare_filter: Prepares a seccomp filter for use. * @fprog: BPF program to install * * Returns filter on success or an ERR_PTR on failure. */ static struct seccomp_filter *seccomp_prepare_filter(struct sock_fprog *fprog) { struct seccomp_filter *filter; unsigned long fp_size = fprog->len * sizeof(struct sock_filter); unsigned long total_insns = fprog->len; long ret; if (fprog->len == 0 || fprog->len > BPF_MAXINSNS) return ERR_PTR(-EINVAL); BUG_ON(INT_MAX / fprog->len < sizeof(struct sock_filter)); for (filter = current->seccomp.filter; filter; filter = filter->prev) total_insns += filter->len + 4; /* include a 4 instr penalty */ if (total_insns > MAX_INSNS_PER_PATH) return ERR_PTR(-ENOMEM); /* * Installing a seccomp filter requires that the task have * CAP_SYS_ADMIN in its namespace or be running with no_new_privs. * This avoids scenarios where unprivileged tasks can affect the * behavior of privileged children. */ if (!task_no_new_privs(current) && security_capable_noaudit(current_cred(), current_user_ns(), CAP_SYS_ADMIN) != 0) return ERR_PTR(-EACCES); /* Allocate a new seccomp_filter */ filter = kzalloc(sizeof(struct seccomp_filter) + fp_size, GFP_KERNEL|__GFP_NOWARN); if (!filter) return ERR_PTR(-ENOMEM);; atomic_set(&filter->usage, 1); filter->len = fprog->len; /* Copy the instructions from fprog. */ ret = -EFAULT; if (copy_from_user(filter->insns, fprog->filter, fp_size)) goto fail; /* Check and rewrite the fprog via the skb checker */ ret = sk_chk_filter(filter->insns, filter->len); if (ret) goto fail; /* Check and rewrite the fprog for seccomp use */ ret = seccomp_check_filter(filter->insns, filter->len); if (ret) goto fail; return filter; fail: kfree(filter); return ERR_PTR(ret); } /** * seccomp_prepare_user_filter - prepares a user-supplied sock_fprog * @user_filter: pointer to the user data containing a sock_fprog. * * Returns 0 on success and non-zero otherwise. */ static struct seccomp_filter * seccomp_prepare_user_filter(const char __user *user_filter) { struct sock_fprog fprog; struct seccomp_filter *filter = ERR_PTR(-EFAULT); #ifdef CONFIG_COMPAT if (is_compat_task()) { struct compat_sock_fprog fprog32; if (copy_from_user(&fprog32, user_filter, sizeof(fprog32))) goto out; fprog.len = fprog32.len; fprog.filter = compat_ptr(fprog32.filter); } else /* falls through to the if below. */ #endif if (copy_from_user(&fprog, user_filter, sizeof(fprog))) goto out; filter = seccomp_prepare_filter(&fprog); out: return filter; } /** * seccomp_attach_filter: validate and attach filter * @flags: flags to change filter behavior * @filter: seccomp filter to add to the current process * * Caller must be holding current->sighand->siglock lock. * * Returns 0 on success, -ve on error. */ static long seccomp_attach_filter(unsigned int flags, struct seccomp_filter *filter) { unsigned long total_insns; struct seccomp_filter *walker; assert_spin_locked(&current->sighand->siglock); /* Validate resulting filter length. */ total_insns = filter->len; for (walker = current->seccomp.filter; walker; walker = walker->prev) total_insns += walker->len + 4; /* 4 instr penalty */ if (total_insns > MAX_INSNS_PER_PATH) return -ENOMEM; /* If thread sync has been requested, check that it is possible. */ if (flags & SECCOMP_FILTER_FLAG_TSYNC) { int ret; ret = seccomp_can_sync_threads(); if (ret) return ret; } /* * If there is an existing filter, make it the prev and don't drop its * task reference. */ filter->prev = current->seccomp.filter; current->seccomp.filter = filter; /* Now that the new filter is in place, synchronize to all threads. */ if (flags & SECCOMP_FILTER_FLAG_TSYNC) seccomp_sync_threads(); return 0; } /* get_seccomp_filter - increments the reference count of the filter on @tsk */ void get_seccomp_filter(struct task_struct *tsk) { struct seccomp_filter *orig = tsk->seccomp.filter; if (!orig) return; /* Reference count is bounded by the number of total processes. */ atomic_inc(&orig->usage); } static inline void seccomp_filter_free(struct seccomp_filter *filter) { if (filter) { kfree(filter); } } /* put_seccomp_filter - decrements the ref count of tsk->seccomp.filter */ void put_seccomp_filter(struct task_struct *tsk) { struct seccomp_filter *orig = tsk->seccomp.filter; /* Clean up single-reference branches iteratively. */ while (orig && atomic_dec_and_test(&orig->usage)) { struct seccomp_filter *freeme = orig; orig = orig->prev; seccomp_filter_free(freeme); } } /** * seccomp_send_sigsys - signals the task to allow in-process syscall emulation * @syscall: syscall number to send to userland * @reason: filter-supplied reason code to send to userland (via si_errno) * * Forces a SIGSYS with a code of SYS_SECCOMP and related sigsys info. */ static void seccomp_send_sigsys(int syscall, int reason) { struct siginfo info; memset(&info, 0, sizeof(info)); info.si_signo = SIGSYS; info.si_code = SYS_SECCOMP; info.si_call_addr = (void __user *)KSTK_EIP(current); info.si_errno = reason; info.si_arch = syscall_get_arch(); info.si_syscall = syscall; force_sig_info(SIGSYS, &info, current); } #endif /* CONFIG_SECCOMP_FILTER */ /* * Secure computing mode 1 allows only read/write/exit/sigreturn. * To be fully secure this must be combined with rlimit * to limit the stack allocations too. */ static int mode1_syscalls[] = { __NR_seccomp_read, __NR_seccomp_write, __NR_seccomp_exit, __NR_seccomp_sigreturn, 0, /* null terminated */ }; #ifdef CONFIG_COMPAT static int mode1_syscalls_32[] = { __NR_seccomp_read_32, __NR_seccomp_write_32, __NR_seccomp_exit_32, __NR_seccomp_sigreturn_32, 0, /* null terminated */ }; #endif static void __secure_computing_strict(int this_syscall) { int *syscall_whitelist = mode1_syscalls; #ifdef CONFIG_COMPAT if (is_compat_task()) syscall_whitelist = mode1_syscalls_32; #endif do { if (*syscall_whitelist == this_syscall) return; } while (*++syscall_whitelist); #ifdef SECCOMP_DEBUG dump_stack(); #endif audit_seccomp(this_syscall, SIGKILL, SECCOMP_RET_KILL); do_exit(SIGKILL); } #ifndef CONFIG_HAVE_ARCH_SECCOMP_FILTER void secure_computing_strict(int this_syscall) { int mode = current->seccomp.mode; if (mode == 0) return; else if (mode == SECCOMP_MODE_STRICT) __secure_computing_strict(this_syscall); else BUG(); } #else int __secure_computing(void) { struct pt_regs *regs = task_pt_regs(current); int this_syscall = syscall_get_nr(current, regs); int exit_sig = 0; u32 ret; /* * Make sure that any changes to mode from another thread have * been seen after TIF_SECCOMP was seen. */ rmb(); switch (current->seccomp.mode) { case SECCOMP_MODE_STRICT: __secure_computing_strict(this_syscall); return 0; #ifdef CONFIG_SECCOMP_FILTER case SECCOMP_MODE_FILTER: { int data; ret = seccomp_run_filters(); data = ret & SECCOMP_RET_DATA; ret &= SECCOMP_RET_ACTION; switch (ret) { case SECCOMP_RET_ERRNO: /* Set low-order bits as an errno, capped at MAX_ERRNO. */ if (data > MAX_ERRNO) data = MAX_ERRNO; syscall_set_return_value(current, regs, -data, 0); goto skip; case SECCOMP_RET_TRAP: /* Show the handler the original registers. */ syscall_rollback(current, regs); /* Let the filter pass back 16 bits of data. */ seccomp_send_sigsys(this_syscall, data); goto skip; case SECCOMP_RET_TRACE: /* Skip these calls if there is no tracer. */ if (!ptrace_event_enabled(current, PTRACE_EVENT_SECCOMP)) { syscall_set_return_value(current, regs, -ENOSYS, 0); goto skip; } /* Allow the BPF to provide the event message */ ptrace_event(PTRACE_EVENT_SECCOMP, data); /* * The delivery of a fatal signal during event * notification may silently skip tracer notification. * Terminating the task now avoids executing a system * call that may not be intended. */ if (fatal_signal_pending(current)) break; if (syscall_get_nr(current, regs) < 0) goto skip; /* Explicit request to skip. */ return 0; case SECCOMP_RET_ALLOW: return 0; case SECCOMP_RET_KILL: default: break; } exit_sig = SIGSYS; break; } #endif default: BUG(); } #ifdef SECCOMP_DEBUG dump_stack(); #endif audit_seccomp(this_syscall, exit_sig, ret); do_exit(exit_sig); #ifdef CONFIG_SECCOMP_FILTER skip: audit_seccomp(this_syscall, exit_sig, ret); return -1; #endif } #endif /* CONFIG_HAVE_ARCH_SECCOMP_FILTER */ long prctl_get_seccomp(void) { return current->seccomp.mode; } /** * seccomp_set_mode_strict: internal function for setting strict seccomp * * Once current->seccomp.mode is non-zero, it may not be changed. * * Returns 0 on success or -EINVAL on failure. */ static long seccomp_set_mode_strict(void) { const unsigned long seccomp_mode = SECCOMP_MODE_STRICT; long ret = -EINVAL; spin_lock_irq(&current->sighand->siglock); if (!seccomp_may_assign_mode(seccomp_mode)) goto out; #ifdef TIF_NOTSC disable_TSC(); #endif seccomp_assign_mode(current, seccomp_mode); ret = 0; out: spin_unlock_irq(&current->sighand->siglock); return ret; } #ifdef CONFIG_SECCOMP_FILTER /** * seccomp_set_mode_filter: internal function for setting seccomp filter * @flags: flags to change filter behavior * @filter: struct sock_fprog containing filter * * This function may be called repeatedly to install additional filters. * Every filter successfully installed will be evaluated (in reverse order) * for each system call the task makes. * * Once current->seccomp.mode is non-zero, it may not be changed. * * Returns 0 on success or -EINVAL on failure. */ static long seccomp_set_mode_filter(unsigned int flags, const char __user *filter) { const unsigned long seccomp_mode = SECCOMP_MODE_FILTER; struct seccomp_filter *prepared = NULL; long ret = -EINVAL; /* Validate flags. */ if (flags & ~SECCOMP_FILTER_FLAG_MASK) return -EINVAL; /* Prepare the new filter before holding any locks. */ prepared = seccomp_prepare_user_filter(filter); if (IS_ERR(prepared)) return PTR_ERR(prepared); /* * Make sure we cannot change seccomp or nnp state via TSYNC * while another thread is in the middle of calling exec. */ if (flags & SECCOMP_FILTER_FLAG_TSYNC && mutex_lock_killable(&current->signal->cred_guard_mutex)) goto out_free; spin_lock_irq(&current->sighand->siglock); if (!seccomp_may_assign_mode(seccomp_mode)) goto out; ret = seccomp_attach_filter(flags, prepared); if (ret) goto out; /* Do not free the successfully attached filter. */ prepared = NULL; seccomp_assign_mode(current, seccomp_mode); out: spin_unlock_irq(&current->sighand->siglock); if (flags & SECCOMP_FILTER_FLAG_TSYNC) mutex_unlock(&current->signal->cred_guard_mutex); out_free: seccomp_filter_free(prepared); return ret; } #else static inline long seccomp_set_mode_filter(unsigned int flags, const char __user *filter) { return -EINVAL; } #endif /* Common entry point for both prctl and syscall. */ static long do_seccomp(unsigned int op, unsigned int flags, const char __user *uargs) { switch (op) { case SECCOMP_SET_MODE_STRICT: if (flags != 0 || uargs != NULL) return -EINVAL; return seccomp_set_mode_strict(); case SECCOMP_SET_MODE_FILTER: return seccomp_set_mode_filter(flags, uargs); default: return -EINVAL; } } SYSCALL_DEFINE3(seccomp, unsigned int, op, unsigned int, flags, const char __user *, uargs) { return do_seccomp(op, flags, uargs); } /** * prctl_set_seccomp: configures current->seccomp.mode * @seccomp_mode: requested mode to use * @filter: optional struct sock_fprog for use with SECCOMP_MODE_FILTER * * Returns 0 on success or -EINVAL on failure. */ long prctl_set_seccomp(unsigned long seccomp_mode, char __user *filter) { unsigned int op; char __user *uargs; switch (seccomp_mode) { case SECCOMP_MODE_STRICT: op = SECCOMP_SET_MODE_STRICT; /* * Setting strict mode through prctl always ignored filter, * so make sure it is always NULL here to pass the internal * check in do_seccomp(). */ uargs = NULL; break; case SECCOMP_MODE_FILTER: op = SECCOMP_SET_MODE_FILTER; uargs = filter; break; default: return -EINVAL; } /* prctl interface doesn't have flags, so they are always zero. */ return do_seccomp(op, 0, uargs); }
Elite-Kernels/Elite_angler
kernel/seccomp.c
C
gpl-2.0
22,899
/*--------------------------------------------------------------------*/ /*--- Platform-specific syscalls stuff. syswrap-ppc64-aix5.c ---*/ /*--------------------------------------------------------------------*/ /* This file is part of Valgrind, a dynamic binary instrumentation framework. Copyright (C) 2006-2010 OpenWorks LLP info@open-works.co.uk 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. The GNU General Public License is contained in the file COPYING. Neither the names of the U.S. Department of Energy nor the University of California nor the names of its contributors may be used to endorse or promote products derived from this software without prior written permission. */ #if defined(VGP_ppc64_aix5) #include "pub_core_basics.h" #include "pub_core_vki.h" #include "pub_core_vkiscnums.h" #include "pub_core_threadstate.h" #include "pub_core_debuglog.h" #include "pub_core_libcassert.h" #include "pub_core_libcprint.h" #include "pub_core_libcproc.h" #include "pub_core_options.h" #include "pub_core_scheduler.h" #include "pub_core_sigframe.h" // For VG_(sigframe_destroy)() #include "pub_core_signals.h" #include "pub_core_syscall.h" #include "pub_core_syswrap.h" #include "pub_core_tooliface.h" #include "priv_types_n_macros.h" #include "priv_syswrap-aix5.h" /* for decls of aix5-common wrappers */ #include "priv_syswrap-main.h" /* --------- HACKS --------- */ /* XXXXXXXXXXXX these HACKS are copies of stuff in syswrap-linux.c; check for duplication. */ /* HACK: is in syswrap-generic.c, but that doesn't get build on AIX. */ /* Dump out a summary, and a more detailed list, of open file descriptors. */ void VG_(show_open_fds) ( void ) { I_die_here; } static Bool i_am_the_only_thread ( void ) { Int c = VG_(count_living_threads)(); vg_assert(c >= 1); /* stay sane */ return c == 1; } void VG_(reap_threads)(ThreadId self) { while (!i_am_the_only_thread()) { /* Let other thread(s) run */ VG_(vg_yield)(); VG_(poll_signals)(self); } vg_assert(i_am_the_only_thread()); } void VG_(init_preopened_fds) ( void ) { I_die_here; } // Run a thread from beginning to end and return the thread's // scheduler-return-code. static VgSchedReturnCode thread_wrapper(Word /*ThreadId*/ tidW) { VgSchedReturnCode ret; ThreadId tid = (ThreadId)tidW; ThreadState* tst = VG_(get_ThreadState)(tid); VG_(debugLog)(1, "syswrap-aix64", "thread_wrapper(tid=%lld): entry\n", (ULong)tidW); vg_assert(tst->status == VgTs_Init); /* make sure we get the CPU lock before doing anything significant */ VG_(acquire_BigLock)(tid, "thread_wrapper(starting new thread)"); if (0) VG_(printf)("thread tid %d started: stack = %p\n", tid, &tid); VG_TRACK( pre_thread_first_insn, tid ); tst->os_state.lwpid = VG_(gettid)(); tst->os_state.threadgroup = VG_(getpid)(); /* Thread created with all signals blocked; scheduler will set the appropriate mask */ ret = VG_(scheduler)(tid); vg_assert(VG_(is_exiting)(tid)); vg_assert(tst->status == VgTs_Runnable); vg_assert(VG_(is_running_thread)(tid)); VG_(debugLog)(1, "syswrap-aix64", "thread_wrapper(tid=%lld): exit\n", (ULong)tidW); /* Return to caller, still holding the lock. */ return ret; } /* Run a thread all the way to the end, then do appropriate exit actions (this is the last-one-out-turn-off-the-lights bit). */ static void run_a_thread_NORETURN ( Word tidW ) { ThreadId tid = (ThreadId)tidW; VgSchedReturnCode src; Int c; VG_(debugLog)(1, "syswrap-aix64", "run_a_thread_NORETURN(tid=%lld): pre-thread_wrapper\n", (ULong)tidW); /* Run the thread all the way through. */ src = thread_wrapper(tid); VG_(debugLog)(1, "syswrap-aix64", "run_a_thread_NORETURN(tid=%lld): post-thread_wrapper\n", (ULong)tidW); c = VG_(count_living_threads)(); vg_assert(c >= 1); /* stay sane */ vg_assert(src == VgSrc_ExitThread || src == VgSrc_ExitProcess || src == VgSrc_FatalSig); if (c == 1 || src == VgSrc_ExitProcess) { VG_(debugLog)(1, "syswrap-aix64", "run_a_thread_NORETURN(tid=%lld): " "exit process (%d threads remaining)\n", (ULong)tidW, c); /* We are the last one standing. Keep hold of the lock and carry on to show final tool results, then exit the entire system. Use the continuation pointer set at startup in m_main. */ ( * VG_(address_of_m_main_shutdown_actions_NORETURN) ) (tid, src); } else { ThreadState *tst; VG_(debugLog)(1, "syswrap-aix64", "run_a_thread_NORETURN(tid=%lld): " "not last one standing\n", (ULong)tidW); /* OK, thread is dead, but others still exist. Just exit. */ vg_assert(c >= 2); tst = VG_(get_ThreadState)(tid); /* This releases the run lock */ VG_(exit_thread)(tid); vg_assert(tst->status == VgTs_Zombie); /* We have to use this sequence to terminate the thread to prevent a subtle race. If VG_(exit_thread)() had left the ThreadState as Empty, then it could have been reallocated, reusing the stack while we're doing these last cleanups. Instead, VG_(exit_thread) leaves it as Zombie to prevent reallocation. We need to make sure we don't touch the stack between marking it Empty and exiting. Hence the assembler. */ { ULong block[4]; vg_assert(sizeof(tst->status == 8)); vg_assert(__NR_AIX5_thread_terminate != __NR_AIX5_UNKNOWN); block[0] = (ULong)VgTs_Empty; block[1] = (ULong) & (tst->status); block[2] = (ULong) tst->os_state.exitcode; block[3] = __NR_AIX5_thread_terminate; asm volatile ( "mr 29,%0\n\t" /* r29 = &block[0] */ "ld 20, 0(29)\n\t" /* r20 = VgTs_Empty */ "ld 21, 8(29)\n\t" /* r21 = & (tst->status) */ "ld 22, 16(29)\n\t" /* r22 = tst->os_state.exitcode */ "ld 23, 24(29)\n\t" /* r23 = __NR_exit */ /* after this point we can't safely use the stack. */ "std 20, 0(21)\n\t" /* tst->status = VgTs_Empty */ "mr 2,23\n\t" /* r2 = __NR_exit */ "mr 3,22\n\t" /* set r3 = tst->os_state.exitcode */ /* set up for syscall */ "crorc 6,6,6\n\t" ".long 0x48000005\n\t" /* "bl here+4" */ "mflr 29\n\t" "addi 29,29,16\n\t" "mtlr 29\n\t" "sc\n\t" /* exit(tst->os_state.exitcode) */ : : "b" (&block[0]) : "lr", "memory", "r2", "r3", "r20", "r21", "r22", "r23", "r29" ); } VG_(core_panic)("Thread exit failed?\n"); } /*NOTREACHED*/ vg_assert(0); } static Word start_thread_NORETURN ( void* arg ) { ThreadState* tst = (ThreadState*)arg; ThreadId tid = tst->tid; run_a_thread_NORETURN ( (Word)tid ); /*NOTREACHED*/ vg_assert(0); } /* Call f(arg1), but first switch stacks, using 'stack' as the new stack. f itself needs to never return. */ __attribute__((noreturn)) static void call_on_new_stack_0_1_NORETURN ( Addr stack, void (*f_NORETURN)(Word), Word arg1 ) { UWord* fdescr = (UWord*)f_NORETURN; volatile UWord block[5]; block[0] = fdescr[0]; /* nia */ block[1] = stack; /* r1 */ block[2] = fdescr[1]; /* r2 */ block[3] = arg1; /* r3 */ block[4] = fdescr[2]; /* r11 */ __asm__ __volatile__( "mr 4,%0\n\t" /* r4 = block */ "ld 1, 8(4)\n\t" "ld 2, 16(4)\n\t" "ld 3, 24(4)\n\t" "ld 11,32(4)\n\t" "ld 4, 0(4)\n\t" "mtctr 4\n\t" "bctr\n" : /*out*/ : /*in*/ "b"(&block[0]) ); /*NOTREACHED*/ __asm__ __volatile__("trap"); while (1) {} /* convince gcc that this really doesn't return */ } /* Allocate a stack for the main thread, and run it all the way to the end. Although we already have a working VgStack (VG_(interim_stack)) it's better to allocate a new one, so that overflow detection works uniformly for all threads. */ void VG_(main_thread_wrapper_NORETURN)(ThreadId tid) { Addr sp; VG_(debugLog)(1, "syswrap-aix64", "entering VG_(main_thread_wrapper_NORETURN)\n"); sp = ML_(allocstack)(tid); /* If we can't even allocate the first thread's stack, we're hosed. Give up. */ vg_assert2(sp != 0, "Cannot allocate main thread's stack."); /* shouldn't be any other threads around yet */ vg_assert( VG_(count_living_threads)() == 1 ); /* make a stack frame */ sp -= 16; sp &= ~0xF; *(UWord *)sp = 0; call_on_new_stack_0_1_NORETURN( (Addr)sp, /* stack */ run_a_thread_NORETURN, /* fn to call */ (Word)tid /* arg to give it */ ); /*NOTREACHED*/ vg_assert(0); } /* --------- end HACKS --------- */ /* --------------------------------------------------------------------- More thread stuff ------------------------------------------------------------------ */ void VG_(cleanup_thread) ( ThreadArchState* arch ) { } /* --------------------------------------------------------------------- PRE/POST wrappers for ppc64/AIX5-specific syscalls ------------------------------------------------------------------ */ /* --- !!! --- EXTERNAL HEADERS start --- !!! --- */ #include <sys/thread.h> /* --- !!! --- EXTERNAL HEADERS end --- !!! --- */ /* Add prototypes for the wrappers declared here, so that gcc doesn't harass us for not having prototypes. Really this is a kludge -- the right thing to do is to make these wrappers 'static' since they aren't visible outside this file, but that requires even more macro magic. */ #define PRE(name) DEFN_PRE_TEMPLATE(ppc64_aix5, name) #define POST(name) DEFN_POST_TEMPLATE(ppc64_aix5, name) DECL_TEMPLATE(ppc64_aix5, sys__clock_gettime); DECL_TEMPLATE(ppc64_aix5, sys__fp_fpscrx64_); DECL_TEMPLATE(ppc64_aix5, sys_kload); DECL_TEMPLATE(ppc64_aix5, sys_kunload64); DECL_TEMPLATE(ppc64_aix5, sys_thread_setstate); DECL_TEMPLATE(ppc64_aix5, sys_FAKE_SIGRETURN); PRE(sys__clock_gettime) { /* Seems like ARG2 points at a destination buffer? */ /* _clock_gettime (UNDOCUMENTED) ( 0, 0xA, 0x2FF21808 ) */ PRINT("_clock_gettime (UNDOCUMENTED) ( %ld, %#lx, %#lx )", ARG1, ARG2, ARG3 ); PRE_REG_READ3(int, "_clock_gettime", int, arg1, int, arg2, void*, arg3); PRE_MEM_WRITE( "_clock_gettime(dst)", ARG2, sizeof(struct timespec) ); } POST(sys__clock_gettime) { vg_assert(SUCCESS); POST_MEM_WRITE( ARG2, sizeof(struct timespec) ); } PRE(sys__fp_fpscrx64_) { PRINT("_fp_fpscrx64_ (BOGUS HANDLER)"); } PRE(sys_kload) { PRINT("kload (UNDOCUMENTED)( %#lx(%s), %ld, %ld )", ARG1,(Char*)ARG1, ARG2, ARG3 ); PRE_REG_READ3(void*, "kload", char*, name, long, arg2, char*, arg3); } POST(sys_kload) { vg_assert(SUCCESS); if (0) VG_(printf)("kload result = %#lx\n", RES); if (RES) POST_MEM_WRITE( RES, 64 ); ML_(aix5_rescan_procmap_after_load_or_unload)(); } PRE(sys_kunload64) { PRINT("kunload64 (UNDOCUMENTED)( %#lx, %ld, %ld, %#lx )", ARG1, ARG2, ARG3, ARG4 ); PRE_REG_READ4(long, "kunload64", void*, arg1, long, arg2, long, arg3, void*, arg4); } POST(sys_kunload64) { vg_assert(SUCCESS); ML_(aix5_rescan_procmap_after_load_or_unload)(); } PRE(sys_thread_setstate) { UWord dst_lwpid = (UWord)ARG1; struct tstate* ats_new = (struct tstate*)ARG2; struct tstate* ats_old = (struct tstate*)ARG3; ThreadId dst_tid = VG_INVALID_THREADID; ThreadState* dst_ts = NULL; Int i; /* Arrgh. We MUST retain the lock during this syscall. Reason is that this is sometimes used for asynchronous thread cancellation (nuking other threads). If we don't have the lock during the syscall, then it's possible that the thread we're nuking might get the lock before it gets killed off, and so we can never re-acquire the lock after this syscall, and the system deadlocks. */ /* 10 July 06: above comment is a misdiagnosis. It appears that for thread cancellation (that is, with ->flags == TSTATE_INTR) the target thread is has its PC changed by the the kernel to something else, possibly to pthread_exit(), so that it can run its cancellation handlers and exit. Currently is unknown how the kernel knows what to set the target thread's PC to. I did establish that all the other data passed in the struct is not relevant: when ->flags == TSTATE_INTR, all the other words can be set to 0x0 or 0xFFFFFFFF and the syscall still works. So the address is not passed like that. Also I looked at args to thread_setmystate_fast, which is used when a thread sets its cancellation state, but none of those are code addresses. Also, it's ok for the kernel to simply change the target thread's PC to something else for async thread cancellation, but for deferred cancellation something else is needed, and I can't see how that would work either. Anyway, net result is, target thread ends up not running on the simulator (not dead), which is why it's necessary to hold onto the lock at this point. */ /* 30 July 06: added kludge to intercept attempts to cancel another thread and instead just force that thread to run pthread_exit(PTHREAD_CANCELED). This allows V to keep control. */ PRINT("thread_setstate (BOGUS HANDLER) " "( %ld, %p,%p )", dst_lwpid, ats_new, ats_old); if (1 && VG_(clo_trace_syscalls) && ats_new) ML_(aix5debugstuff_show_tstate)((Addr)ats_new, "thread_setstate (NEW)"); /* Intercept and handle ourselves any attempts to cancel another thread (including this one). */ if (ats_new && (!ats_old) && ats_new->flags == TSTATE_INTR) { dst_ts = NULL; if (VG_(clo_trace_syscalls)) VG_(printf)("(INTR for lwpid %ld)", dst_lwpid); dst_tid = VG_INVALID_THREADID; for (i = 0; i < VG_N_THREADS; i++) { dst_ts = VG_(get_ThreadState)(i); if ((dst_ts->status == VgTs_Runnable || dst_ts->status == VgTs_Yielding || dst_ts->status == VgTs_WaitSys) && dst_ts->os_state.lwpid == dst_lwpid) { dst_tid = i; break; } } if (VG_(clo_trace_syscalls)) { if (dst_tid == VG_INVALID_THREADID) VG_(printf)("(== unknown tid)"); else VG_(printf)("(== tid %d)", (Int)dst_tid); } if (dst_tid != VG_INVALID_THREADID) { /* A cancel has been requested for ctid. If the target thread has cancellation enabled, honour it right now. If not, mark the thread as having a cancellation request, so that if it later enables cancellation then the cancellation will take effect. */ vg_assert(dst_ts); if (dst_ts->os_state.cancel_progress == Canc_NoRequest) { if (dst_ts->os_state.cancel_disabled) { if (VG_(clo_trace_syscalls)) VG_(printf)("(target has cancel disabled" "; request lodged)"); dst_ts->os_state.cancel_progress = Canc_Requested; } else { if (VG_(clo_trace_syscalls)) VG_(printf)("(forcing target into pthread_exit)"); dst_ts->os_state.cancel_progress = Canc_Actioned; Bool ok = ML_(aix5_force_thread_into_pthread_exit)(dst_tid); if (!ok) { /* now at serious risk of deadlock/livelock. Give up rather than continue. */ ML_(aix5_set_threadstate_for_emergency_exit) (tid, "pthread_cancel(case2-64): " "cannot find pthread_exit; aborting"); SET_STATUS_Success(0); return; } } } SET_STATUS_Success(0); return; } } /* Well, it's not a cancellation request. Maybe it is the initialisation of a previously created thread? */ if (ats_new && !ats_old) { dst_tid = VG_INVALID_THREADID; for (i = 0; i < VG_N_THREADS; i++) { dst_ts = VG_(get_ThreadState)(i); if (dst_ts->status == VgTs_Init && dst_ts->os_state.lwpid == dst_lwpid) { dst_tid = i; break; } } if (dst_tid != VG_INVALID_THREADID) { /* Found the associated child */ if (VG_(clo_trace_syscalls)) VG_(printf)("(initialised child tid %d)", (Int)dst_tid); dst_ts = VG_(get_ThreadState)(dst_tid); UWord* stack = (UWord*)ML_(allocstack)(dst_tid); /* XXX TODO: check allocstack failure */ /* copy the specified child register state into the guest slot (we need that context to run on the simulated CPU, not the real one) and put pointers to our own run-the-simulator function into what we'll hand off to the kernel instead. */ /* The guest thread is to start running whatever context this syscall showed up with. */ dst_ts->arch.vex.guest_GPR0 = ats_new->mst.gpr[0]; dst_ts->arch.vex.guest_GPR1 = ats_new->mst.gpr[1]; /* sp */ dst_ts->arch.vex.guest_GPR2 = ats_new->mst.gpr[2]; /* toc */ dst_ts->arch.vex.guest_GPR3 = ats_new->mst.gpr[3]; /* initarg */ dst_ts->arch.vex.guest_GPR4 = ats_new->mst.gpr[4]; dst_ts->arch.vex.guest_GPR5 = ats_new->mst.gpr[5]; dst_ts->arch.vex.guest_GPR6 = ats_new->mst.gpr[6]; dst_ts->arch.vex.guest_GPR7 = ats_new->mst.gpr[7]; dst_ts->arch.vex.guest_GPR8 = ats_new->mst.gpr[8]; dst_ts->arch.vex.guest_GPR9 = ats_new->mst.gpr[9]; dst_ts->arch.vex.guest_GPR10 = ats_new->mst.gpr[10]; dst_ts->arch.vex.guest_GPR11 = ats_new->mst.gpr[11]; /* ?? */ dst_ts->arch.vex.guest_GPR12 = ats_new->mst.gpr[12]; dst_ts->arch.vex.guest_GPR13 = ats_new->mst.gpr[13]; dst_ts->arch.vex.guest_GPR14 = ats_new->mst.gpr[14]; dst_ts->arch.vex.guest_GPR15 = ats_new->mst.gpr[15]; dst_ts->arch.vex.guest_GPR16 = ats_new->mst.gpr[16]; dst_ts->arch.vex.guest_GPR17 = ats_new->mst.gpr[17]; dst_ts->arch.vex.guest_GPR18 = ats_new->mst.gpr[18]; dst_ts->arch.vex.guest_GPR19 = ats_new->mst.gpr[19]; dst_ts->arch.vex.guest_GPR20 = ats_new->mst.gpr[20]; dst_ts->arch.vex.guest_GPR21 = ats_new->mst.gpr[21]; dst_ts->arch.vex.guest_GPR22 = ats_new->mst.gpr[22]; dst_ts->arch.vex.guest_GPR23 = ats_new->mst.gpr[23]; dst_ts->arch.vex.guest_GPR24 = ats_new->mst.gpr[24]; dst_ts->arch.vex.guest_GPR25 = ats_new->mst.gpr[25]; dst_ts->arch.vex.guest_GPR26 = ats_new->mst.gpr[26]; dst_ts->arch.vex.guest_GPR27 = ats_new->mst.gpr[27]; dst_ts->arch.vex.guest_GPR28 = ats_new->mst.gpr[28]; dst_ts->arch.vex.guest_GPR29 = ats_new->mst.gpr[29]; dst_ts->arch.vex.guest_GPR30 = ats_new->mst.gpr[30]; dst_ts->arch.vex.guest_GPR31 = ats_new->mst.gpr[31]; dst_ts->arch.vex.guest_CIA = ats_new->mst.iar; /* pc */ dst_ts->arch.vex.guest_LR = ats_new->mst.lr; dst_ts->arch.vex.guest_CTR = ats_new->mst.ctr; LibVEX_GuestPPC64_put_CR( ats_new->mst.cr, &dst_ts->arch.vex ); LibVEX_GuestPPC64_put_XER( ats_new->mst.xer, &dst_ts->arch.vex ); /* Record what seems like the highest legitimate stack address for this thread, so that the stack unwinder works properly. It seems reasonable to use the R1 value supplied here. */ dst_ts->client_stack_highest_word = dst_ts->arch.vex.guest_GPR1; /* The host thread is to start running start_thread_NORETURN */ UWord* wrapper_fdescr = (UWord*) & start_thread_NORETURN; ats_new->mst.gpr[1] = (UWord)stack; ats_new->mst.gpr[2] = wrapper_fdescr[1]; ats_new->mst.iar = wrapper_fdescr[0]; ats_new->mst.gpr[3] = (UWord)dst_ts; /* Set initial cancellation status for the thread. */ dst_ts->os_state.cancel_async = False; dst_ts->os_state.cancel_disabled = False; dst_ts->os_state.cancel_progress = Canc_NoRequest; } } } POST(sys_thread_setstate) { if (ARG3) POST_MEM_WRITE( ARG3, sizeof(struct tstate) ); if (0 && VG_(clo_trace_syscalls) && ARG3) ML_(aix5debugstuff_show_tstate)(ARG3, "thread_setstate (OLD)"); } PRE(sys_FAKE_SIGRETURN) { /* See comments on PRE(sys_rt_sigreturn) in syswrap-amd64-linux.c for an explanation of what follows. */ /* This handles the fake signal-return system call created by sigframe-ppc64-aix5.c. */ PRINT("FAKE_SIGRETURN ( )"); vg_assert(VG_(is_valid_tid)(tid)); vg_assert(tid >= 1 && tid < VG_N_THREADS); vg_assert(VG_(is_running_thread)(tid)); /* Remove the signal frame from this thread's (guest) stack, in the process restoring the pre-signal guest state. */ VG_(sigframe_destroy)(tid, True); /* Tell the driver not to update the guest state with the "result", and set a bogus result to keep it happy. */ *flags |= SfNoWriteResult; SET_STATUS_Success(0); /* Check to see if any signals arose as a result of this. */ *flags |= SfPollAfter; } /* --------------------------------------------------------------------- The ppc64/AIX5 syscall table ------------------------------------------------------------------ */ typedef struct { UInt* pSysNo; SyscallTableEntry wrappers; } AIX5SCTabEntry; #undef PLAXY #undef PLAX_ #define PLAXY(sysno, name) \ { & sysno, \ { & WRAPPER_PRE_NAME(ppc64_aix5, name), \ & WRAPPER_POST_NAME(ppc64_aix5, name) }} #define PLAX_(sysno, name) \ { & sysno, \ { & WRAPPER_PRE_NAME(ppc64_aix5, name), \ NULL }} static /* but not const */ AIX5SCTabEntry aix5_ppc64_syscall_table[] = { AIXXY(__NR_AIX5___libc_sbrk, sys___libc_sbrk), AIXX_(__NR_AIX5___msleep, sys___msleep), PLAXY(__NR_AIX5__clock_gettime, sys__clock_gettime), AIXX_(__NR_AIX5__exit, sys__exit), PLAX_(__NR_AIX5__fp_fpscrx64_, sys__fp_fpscrx64_), AIXX_(__NR_AIX5__getpid, sys__getpid), AIXXY(__NR_AIX5__nsleep, sys__nsleep), AIXX_(__NR_AIX5__pause, sys__pause), AIXXY(__NR_AIX5__poll, sys__poll), AIXX_(__NR_AIX5__select, sys__select), AIXX_(__NR_AIX5__sem_wait, sys__sem_wait), AIXXY(__NR_AIX5__sigaction, sys__sigaction), AIXX_(__NR_AIX5__thread_self, sys__thread_self), AIXX_(__NR_AIX5_access, sys_access), AIXX_(__NR_AIX5_accessx, sys_accessx), AIXXY(__NR_AIX5_appgetrlimit, sys_appgetrlimit), AIXXY(__NR_AIX5_appgetrusage, sys_appgetrusage), AIXX_(__NR_AIX5_appsetrlimit, sys_appsetrlimit), AIXX_(__NR_AIX5_appulimit, sys_appulimit), AIXX_(__NR_AIX5_bind, sys_bind), AIXX_(__NR_AIX5_chdir, sys_chdir), AIXX_(__NR_AIX5_chmod, sys_chmod), AIXX_(__NR_AIX5_chown, sys_chown), AIXX_(__NR_AIX5_close, sys_close), AIXX_(__NR_AIX5_connext, sys_connext), AIXX_(__NR_AIX5_execve, sys_execve), AIXXY(__NR_AIX5_finfo, sys_finfo), AIXXY(__NR_AIX5_fstatfs, sys_fstatfs), AIXXY(__NR_AIX5_fstatx, sys_fstatx), AIXXY(__NR_AIX5_getdirent, sys_getdirent), AIXXY(__NR_AIX5_getdirent64, sys_getdirent64), AIXXY(__NR_AIX5_getdomainname, sys_getdomainname), AIXX_(__NR_AIX5_getgidx, sys_getgidx), AIXXY(__NR_AIX5_gethostname, sys_gethostname), AIXXY(__NR_AIX5_getpriv, sys_getpriv), AIXXY(__NR_AIX5_getprocs, sys_getprocs), AIXXY(__NR_AIX5_getprocs64, sys_getprocs), /* XXX: correct? */ AIXX_(__NR_AIX5_getrpid, sys_getrpid), AIXXY(__NR_AIX5_getsockopt, sys_getsockopt), AIXX_(__NR_AIX5_gettimerid, sys_gettimerid), AIXX_(__NR_AIX5_getuidx, sys_getuidx), AIXXY(__NR_AIX5_incinterval, sys_incinterval), AIXXY(__NR_AIX5_kfcntl, sys_kfcntl), AIXX_(__NR_AIX5_kfork, sys_kfork), AIXX_(__NR_AIX5_kill, sys_kill), AIXXY(__NR_AIX5_kioctl, sys_kioctl), PLAXY(__NR_AIX5_kload, sys_kload), AIXX_(__NR_AIX5_klseek, sys_klseek), AIXXY(__NR_AIX5_kread, sys_kread), AIXXY(__NR_AIX5_kreadv, sys_kreadv), AIXX_(__NR_AIX5_kthread_ctl, sys_kthread_ctl), AIXX_(__NR_AIX5_ktruncate, sys_ktruncate), PLAXY(__NR_AIX5_kunload64, sys_kunload64), AIXXY(__NR_AIX5_kwaitpid, sys_kwaitpid), AIXX_(__NR_AIX5_kwrite, sys_kwrite), AIXX_(__NR_AIX5_kwritev, sys_kwritev), AIXX_(__NR_AIX5_lseek, sys_lseek), AIXX_(__NR_AIX5_mkdir, sys_mkdir), AIXXY(__NR_AIX5_mmap, sys_mmap), AIXXY(__NR_AIX5_mntctl, sys_mntctl), AIXXY(__NR_AIX5_mprotect, sys_mprotect), AIXXY(__NR_AIX5_munmap, sys_munmap), AIXXY(__NR_AIX5_ngetpeername, sys_ngetpeername), AIXXY(__NR_AIX5_ngetsockname, sys_ngetsockname), AIXXY(__NR_AIX5_nrecvfrom, sys_nrecvfrom), AIXX_(__NR_AIX5_nrecvmsg, sys_nrecvmsg), AIXX_(__NR_AIX5_open, sys_open), AIXXY(__NR_AIX5_pipe, sys_pipe), AIXX_(__NR_AIX5_privcheck, sys_privcheck), AIXX_(__NR_AIX5_rename, sys_rename), AIXXY(__NR_AIX5_sbrk, sys_sbrk), AIXXY(__NR_AIX5_sem_init, sys_sem_init), AIXXY(__NR_AIX5_sem_post, sys_sem_post), AIXX_(__NR_AIX5_send, sys_send), AIXX_(__NR_AIX5_setgid, sys_setgid), AIXX_(__NR_AIX5_setsockopt, sys_setsockopt), AIXX_(__NR_AIX5_setuid, sys_setuid), AIXXY(__NR_AIX5_shmat, sys_shmat), AIXXY(__NR_AIX5_shmctl, sys_shmctl), AIXXY(__NR_AIX5_shmdt, sys_shmdt), AIXX_(__NR_AIX5_shmget, sys_shmget), AIXX_(__NR_AIX5_shutdown, sys_shutdown), AIXX_(__NR_AIX5_sigcleanup, sys_sigcleanup), AIXXY(__NR_AIX5_sigprocmask, sys_sigprocmask), AIXXY(__NR_AIX5_sys_parm, sys_sys_parm), AIXXY(__NR_AIX5_sysconfig, sys_sysconfig), AIXX_(__NR_AIX5_socket, sys_socket), AIXXY(__NR_AIX5_statx, sys_statx), AIXXY(__NR_AIX5_thread_create, sys_thread_create), AIXX_(__NR_AIX5_thread_init, sys_thread_init), AIXX_(__NR_AIX5_thread_kill, sys_thread_kill), AIXXY(__NR_AIX5_thread_setmystate, sys_thread_setmystate), AIXX_(__NR_AIX5_thread_setmystate_fast, sys_thread_setmystate_fast), PLAXY(__NR_AIX5_thread_setstate, sys_thread_setstate), AIXX_(__NR_AIX5_thread_terminate_unlock, sys_thread_terminate_unlock), AIXX_(__NR_AIX5_thread_tsleep, sys_thread_tsleep), AIXX_(__NR_AIX5_thread_twakeup, sys_thread_twakeup), AIXX_(__NR_AIX5_thread_unlock, sys_thread_unlock), AIXX_(__NR_AIX5_thread_waitlock_, sys_thread_waitlock_), AIXXY(__NR_AIX5_times, sys_times), AIXXY(__NR_AIX5_uname, sys_uname), AIXX_(__NR_AIX5_unlink, sys_unlink), AIXX_(__NR_AIX5_utimes, sys_utimes), AIXXY(__NR_AIX5_vmgetinfo, sys_vmgetinfo), AIXX_(__NR_AIX5_yield, sys_yield), PLAX_(__NR_AIX5_FAKE_SIGRETURN, sys_FAKE_SIGRETURN) }; SyscallTableEntry* ML_(get_ppc64_aix5_syscall_entry) ( UInt sysno ) { Int i; AIX5SCTabEntry tmp; const Int tab_size = sizeof(aix5_ppc64_syscall_table) / sizeof(aix5_ppc64_syscall_table[0]); for (i = 0; i < tab_size; i++) if (sysno == *(aix5_ppc64_syscall_table[i].pSysNo)) break; vg_assert(i >= 0 && i <= tab_size); if (i == tab_size) return NULL; /* can't find a wrapper */ /* Move found one a bit closer to the front, so as to make future searches cheaper. */ if (i > 0) { tmp = aix5_ppc64_syscall_table[i-1]; aix5_ppc64_syscall_table[i-1] = aix5_ppc64_syscall_table[i]; aix5_ppc64_syscall_table[i] = tmp; i--; } vg_assert(i >= 0 && i < tab_size); return &aix5_ppc64_syscall_table[i].wrappers; } #endif // defined(VGP_ppc64_aix5) /*--------------------------------------------------------------------*/ /*--- end ---*/ /*--------------------------------------------------------------------*/
MicroTrustRepos/microkernel
src/l4/pkg/valgrind/src/valgrind-3.6.0-svn/coregrind/m_syswrap/syswrap-ppc64-aix5.c
C
gpl-2.0
30,484
/** * The CSS values that are wrapped in '/*variable' comments are intended for use * by https://www.drupal.org/project/style_settings. Enable that module to * have those CSS variables exposed in the settings UI. */ .flickr-photo-img, img.flickr-photoset-img, .flickr-wrap, span.flickr-credit { -webkit-border-radius: /*variable:flickrstyle_radius*/1em/*variable*/; -moz-border-radius: /*variable:flickrstyle_radius*/1em/*variable*/; border-radius: /*variable:flickrstyle_radius*/1em/*variable*/; }
jamidwyer/flickr
style/css/flickrstyle_rounded.css
CSS
gpl-2.0
521
(function(){tinymce.PluginManager.requireLangPack('codemagic');tinymce.create('tinymce.plugins.CodeMagic',{init:function(ed,url){ed.addCommand('mceCodeMagic',function(){ed.windowManager.open({file:url+'/codemagic.php',width:1200,height:600,inline:1,maximizable:true},{plugin_url:url})});ed.addButton('codemagic',{title:'codemagic.editor_button',cmd:'mceCodeMagic',image:url+'/img/code.png'});ed.onNodeChange.add(function(ed,cm,n,co){cm.setDisabled('link',co&&n.nodeName!='A');cm.setActive('link',n.nodeName=='A'&&!n.name)})},getInfo:function(){return{longname:'CodeMagic - syntax coloring and intendation',author:'Sutulustus',authorurl:'http://www.triad.sk/#/en',version:'0.9.5'}}});tinymce.PluginManager.add('codemagic',tinymce.plugins.CodeMagic)})();
tgrimault/manorhouseporto.wp
wp-content/plugins/ultimate-tinymce/addons/codemagic/editor_plugin.js
JavaScript
gpl-2.0
752
/* This file is part of the ScriptDev2 Project. See AUTHORS file for Copyright information * 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 */ /* ScriptData SDName: boss_erekem SD%Complete: 90 SDComment: Timers may need adjustments SDCategory: Violet Hold EndScriptData */ #include "precompiled.h" #include "violet_hold.h" enum { SAY_AGGRO = -1608012, SAY_ADD_DIE_1 = -1608013, SAY_ADD_DIE_2 = -1608014, SAY_DEATH = -1608018, // A few Sound IDs on SLAY, if there _is_ text related, fields -1608015 to -1608017 are free SOUND_ID_SLAY_1 = 14222, SOUND_ID_SLAY_2 = 14223, SOUND_ID_SLAY_3 = 14224, SPELL_BLOODLUST = 54516, SPELL_BREAK_BONDS_H = 59463, SPELL_CHAIN_HEAL = 54481, SPELL_CHAIN_HEAL_H = 59473, SPELL_EARTH_SHIELD = 54479, SPELL_EARTH_SHIELD_H = 59471, SPELL_EARTH_SHOCK = 54511, SPELL_LIGHTNING_BOLT = 53044, SPELL_STORMSTRIKE = 51876, // Spells of adds SPELL_GUSHING_WOUND = 39215, SPELL_HOWLING_SCREECH = 54463, SPELL_STRIKE = 14516 }; struct boss_erekemAI : public ScriptedAI { boss_erekemAI(Creature* pCreature) : ScriptedAI(pCreature) { m_pInstance = (instance_violet_hold*)pCreature->GetInstanceData(); m_bIsRegularMode = pCreature->GetMap()->IsRegularDifficulty(); Reset(); } instance_violet_hold* m_pInstance; bool m_bIsRegularMode; uint32 m_uiBreakBondsTimer; uint32 m_uiChainHealTimer; uint32 m_uiEarthShieldTimer; uint32 m_uiEarthShockTimer; uint32 m_uiSpecialSpellTimer; uint8 m_uiGuardiansDead; void Reset() override { m_uiSpecialSpellTimer = 0; m_uiEarthShieldTimer = urand(2000, 3000); m_uiEarthShockTimer = urand(4000, 9000); m_uiChainHealTimer = urand(5000, 15000); m_uiBreakBondsTimer = urand(25000, 30000); m_uiGuardiansDead = 0; } void Aggro(Unit* /*pWho*/) override { DoScriptText(SAY_AGGRO, m_creature); } void JustDied(Unit* /*pKiller*/) override { DoScriptText(SAY_DEATH, m_creature); } void KilledUnit(Unit* /*pVictim*/) override { switch (urand(0, 2)) { case 0: DoPlaySoundToSet(m_creature, SOUND_ID_SLAY_1); break; case 1: DoPlaySoundToSet(m_creature, SOUND_ID_SLAY_2); break; case 2: DoPlaySoundToSet(m_creature, SOUND_ID_SLAY_3); break; } } void GuardianJustDied() { DoScriptText(!m_uiGuardiansDead ? SAY_ADD_DIE_1 : SAY_ADD_DIE_2, m_creature); ++m_uiGuardiansDead; // cast bloodlust if both guards are dead if (m_uiGuardiansDead == 2) DoCastSpellIfCan(m_creature, SPELL_BLOODLUST, CAST_INTERRUPT_PREVIOUS); } void UpdateAI(const uint32 uiDiff) override { if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) return; if (m_uiEarthShieldTimer < uiDiff) { if (DoCastSpellIfCan(m_creature, m_bIsRegularMode ? SPELL_EARTH_SHIELD : SPELL_EARTH_SHIELD_H, CAST_AURA_NOT_PRESENT) == CAST_OK) m_uiEarthShieldTimer = urand(25000, 30000); } else m_uiEarthShieldTimer -= uiDiff; if (m_uiEarthShockTimer < uiDiff) { if (Unit* pTarget = m_creature->SelectAttackingTarget(ATTACKING_TARGET_RANDOM, 0)) { if (DoCastSpellIfCan(pTarget, SPELL_EARTH_SHOCK) == CAST_OK) m_uiEarthShockTimer = urand(8000, 13000); } } else m_uiEarthShockTimer -= uiDiff; if (m_uiChainHealTimer < uiDiff) { if (DoCastSpellIfCan(m_creature, m_bIsRegularMode ? SPELL_CHAIN_HEAL : SPELL_CHAIN_HEAL_H) == CAST_OK) m_uiChainHealTimer = urand(15000, 25000); } else m_uiChainHealTimer -= uiDiff; // Cast Stormstrike only if both guards are down if (m_uiSpecialSpellTimer < uiDiff) { if (DoCastSpellIfCan(m_creature->getVictim(), m_uiGuardiansDead == 2 ? SPELL_STORMSTRIKE : SPELL_LIGHTNING_BOLT) == CAST_OK) m_uiSpecialSpellTimer = urand(2000, 3000); } else m_uiSpecialSpellTimer -= uiDiff; // Break bonds only on heroic if (!m_bIsRegularMode) { if (m_uiBreakBondsTimer < uiDiff) { if (DoCastSpellIfCan(m_creature, SPELL_BREAK_BONDS_H) == CAST_OK) m_uiBreakBondsTimer = urand(25000, 30000); } else m_uiBreakBondsTimer -= uiDiff; } DoMeleeAttackIfReady(); } }; CreatureAI* GetAI_boss_erekem(Creature* pCreature) { return new boss_erekemAI(pCreature); } struct npc_erekem_guardAI : public ScriptedAI { npc_erekem_guardAI(Creature* pCreature) : ScriptedAI(pCreature) { m_pInstance = ((instance_violet_hold*)pCreature->GetInstanceData()); Reset(); } instance_violet_hold* m_pInstance; uint32 m_uiGushingWoundTimer; uint32 m_uiHowlingScreechTimer; uint32 m_uiStrikeTimer; void Reset() override { m_uiGushingWoundTimer = urand(9000, 14000); m_uiHowlingScreechTimer = urand(8000, 12000); m_uiStrikeTimer = urand(5000, 7000); } void JustDied(Unit* /*pKiller*/) override { if (!m_pInstance) return; if (Creature* pBoss = m_pInstance->GetSingleCreatureFromStorage(m_pInstance->GetData(TYPE_EREKEM) != DONE ? NPC_EREKEM : NPC_ARAKKOA)) { if (!pBoss->isAlive()) return; ((boss_erekemAI*)pBoss->AI())->GuardianJustDied(); } } void UpdateAI(const uint32 uiDiff) override { if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) return; if (m_uiGushingWoundTimer < uiDiff) { if (DoCastSpellIfCan(m_creature->getVictim(), SPELL_GUSHING_WOUND) == CAST_OK) m_uiGushingWoundTimer = urand(25000, 30000); } else m_uiGushingWoundTimer -= uiDiff; if (m_uiHowlingScreechTimer < uiDiff) { if (DoCastSpellIfCan(m_creature, SPELL_HOWLING_SCREECH) == CAST_OK) m_uiHowlingScreechTimer = urand(10000, 16000); } else m_uiHowlingScreechTimer -= uiDiff; if (m_uiStrikeTimer < uiDiff) { if (DoCastSpellIfCan(m_creature->getVictim(), SPELL_STRIKE) == CAST_OK) m_uiStrikeTimer = urand(5000, 7000); } else m_uiStrikeTimer -= uiDiff; DoMeleeAttackIfReady(); } }; CreatureAI* GetAI_npc_erekem_guard(Creature* pCreature) { return new npc_erekem_guardAI(pCreature); } void AddSC_boss_erekem() { Script* pNewScript; pNewScript = new Script; pNewScript->Name = "boss_erekem"; pNewScript->GetAI = &GetAI_boss_erekem; pNewScript->RegisterSelf(); pNewScript = new Script; pNewScript->Name = "npc_erekem_guard"; pNewScript->GetAI = &GetAI_npc_erekem_guard; pNewScript->RegisterSelf(); }
Exxenoz/mangos-wotlk
src/scriptdev2/scripts/northrend/violet_hold/boss_erekem.cpp
C++
gpl-2.0
8,075
<header>ðÒÏÃÅÓÓ</header> ÷ ÜÔÏÍ ÐÏÌÅ ÎÁÈÏÄÉÔÓÑ ËÏÍÁÄÎÁÑ ÓÔÒÏËÁ ÐÒÏÇÒÁÍÍÙ, ËÏÔÏÒÁÑ ÂÕÄÅÔ ×ÙÚ×ÁÎÁ ÄÁÎÎÙÍ ÐÒÏÃÅÓÓÏÍ ÉÎÉÃÉÁÌÉÚÁÃÉÉ (ÎÁÐÒÉÍÅÒ: /etc/init.d/rc, /sbin/getty ...).<p> <hr>
pakohan/syso-kernel
webmin-1.660/inittab/help/process.ru_SU.html
HTML
gpl-2.0
182
/*! \file GUILabel.h \brief */ #pragma once /* * Copyright (C) 2005-2010 Team XBMC * http://www.xbmc.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, 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 XBMC; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. * http://www.gnu.org/copyleft/gpl.html * */ #include "GUITextLayout.h" #include "GUIInfoTypes.h" #include "GUIFont.h" #include "Geometry.h" class CLabelInfo { public: CLabelInfo() { font = NULL; align = XBFONT_LEFT; offsetX = offsetY = 0; width = 0; angle = 0; scrollSpeed = CScrollInfo::defaultSpeed; scrollSuffix = " | "; }; bool UpdateColors() { bool changed = false; changed |= textColor.Update(); changed |= shadowColor.Update(); changed |= selectedColor.Update(); changed |= disabledColor.Update(); changed |= focusedColor.Update(); return changed; }; CGUIInfoColor textColor; CGUIInfoColor shadowColor; CGUIInfoColor selectedColor; CGUIInfoColor disabledColor; CGUIInfoColor focusedColor; uint32_t align; float offsetX; float offsetY; float width; float angle; CGUIFont *font; int scrollSpeed; CStdString scrollSuffix; }; /*! \ingroup controls, labels \brief Class for rendering text labels. Handles alignment and rendering of text within a control. */ class CGUILabel { public: /*! \brief allowed color categories for labels, as defined by the skin */ enum COLOR { COLOR_TEXT = 0, COLOR_SELECTED, COLOR_FOCUSED, COLOR_DISABLED }; /*! \brief allowed overflow handling techniques for labels, as defined by the skin */ enum OVER_FLOW { OVER_FLOW_TRUNCATE = 0, OVER_FLOW_SCROLL, OVER_FLOW_WRAP }; CGUILabel(float posX, float posY, float width, float height, const CLabelInfo& labelInfo, OVER_FLOW overflow = OVER_FLOW_TRUNCATE); virtual ~CGUILabel(void); /*! \brief Process the label \return bool stating if process caused control to change */ bool Process(unsigned int currentTime); /*! \brief Render the label on screen */ void Render(); /*! \brief Set the maximal extent of the label Sets the maximal size and positioning that the label may render in. Note that <textwidth> can override this, and <textoffsetx> and <textoffsety> may also allow the label to be moved outside this rectangle. */ bool SetMaxRect(float x, float y, float w, float h); bool SetAlign(uint32_t align); /*! \brief Set the text to be displayed in the label Updates the label control and recomputes final position and size \param text CStdString to set as this labels text \sa SetTextW */ bool SetText(const CStdString &label); /*! \brief Set the text to be displayed in the label Updates the label control and recomputes final position and size \param text CStdStringW to set as this labels text \sa SetText */ bool SetTextW(const CStdStringW &label); /*! \brief Set the color to use for the label Sets the color to be used for this label. Takes effect at the next render \param color color to be used for the label */ bool SetColor(COLOR color); /*! \brief Set the final layout of the current text Overrides the calculated layout of the current text, forcing a particular size and position \param rect CRect containing the extents of the current text \sa GetRenderRect, UpdateRenderRect */ void SetRenderRect(const CRect &rect) { m_renderRect = rect; }; /*! \brief Set whether or not this label control should scroll \param scrolling true if this label should scroll. */ bool SetScrolling(bool scrolling); /*! \brief Set this label invalid. Forces an update of the control */ void SetInvalid(); /*! \brief Update this labels colors */ bool UpdateColors(); /*! \brief Returns the precalculated final layout of the current text \return CRect containing the extents of the current text \sa SetRenderRect, UpdateRenderRect */ const CRect &GetRenderRect() const { return m_renderRect; }; /*! \brief Returns the precalculated full width of the current text, regardless of layout \return full width of the current text \sa CalcTextWidth */ float GetTextWidth() const { return m_textLayout.GetTextWidth(); }; /*! \brief Returns the maximal width that this label can render into \return Maximal width that this label can render into. Note that this may differ from the amount given in SetMaxRect as offsets and text width overrides have been taken into account. \sa SetMaxRect */ float GetMaxWidth() const; /*! \brief Calculates the width of some text \param text CStdStringW of text whose width we want \return width of the given text \sa GetTextWidth */ float CalcTextWidth(const CStdStringW &text) const { return m_textLayout.GetTextWidth(text); }; const CLabelInfo& GetLabelInfo() const { return m_label; }; CLabelInfo &GetLabelInfo() { return m_label; }; /*! \brief Check a left aligned and right aligned label for overlap and cut the labels off so that no overlap occurs If a left-aligned label occupies some of the same space on screen as a right-aligned label, then we may be able to correct for this by restricting the width of one or both of them. This routine checks two labels to see whether they satisfy this assumption and, if so, adjusts the render rect of both labels so that they no longer do so. The order of the two labels is not important, but we do assume that the left-aligned label is also the left-most on screen, and that the right-aligned label is the right most on-screen, so that they overlap due to the fact that one or both of the labels are longer than anticipated. In the following diagram, [R...[R R] refers to the maximal allowed and actual space occupied by the right label. Similarly, [L L]...L] refers to the maximal and actual space occupied by the left label. | refers to the central cutting point, i.e. the point that would divide the maximal allowed overlap perfectly in two. There are 3 scenarios to consider: cut [L [R...[R L].|..........L] R] left label ends to the left of the cut -> just crop the left label. [L [R.....[R | L]..L] R] both left and right labels occupy more than the cut allows, so crop both. [L [R..........|.[R L]..L] R] right label ends to the right of the cut -> just crop the right label. \param label1 First label to check \param label2 Second label to check */ static bool CheckAndCorrectOverlap(CGUILabel &label1, CGUILabel &label2); protected: color_t GetColor() const; /*! \brief Computes the final layout of the text Uses the maximal position and width of the text, as well as the text length and alignment to compute the final render rect of the text. \sa GetRenderRect, SetRenderRect */ void UpdateRenderRect(); private: CLabelInfo m_label; CGUITextLayout m_textLayout; bool m_scrolling; OVER_FLOW m_overflowType; bool m_selected; CScrollInfo m_scrollInfo; CRect m_renderRect; ///< actual sizing of text CRect m_maxRect; ///< maximum sizing of text bool m_invalid; ///< if true, the label needs recomputing COLOR m_color; ///< color to render text \sa SetColor, GetColor };
rsalveti/xbmc-eden
xbmc/guilib/GUILabel.h
C
gpl-2.0
8,056
<?php /** * Outputs the RSS2 XML format comment feed using the feed-rss2.php file in * wp-includes folder. This file only sets the feed format and includes the * feed-rss2-comments.php. * * This file is no longer used in WordPress and while it is not deprecated now. * This file will most likely be deprecated or removed in a later version. * * The link for the rss2 comment feed is /index.php?feed=rss2&withcomments=1 * with permalinks off. * * @package WordPress */ if (empty($wp)) { require_once('./wp-load.php'); wp('feed=rss2&withcomments=1'); } require (ABSPATH . WPINC . '/feed-rss2-comments.php'); ?>
localshred/dtraders
wp-commentsrss2.php
PHP
gpl-2.0
625
<?php /** * File contains: eZ\Publish\Core\Persistence\Legacy\Tests\Content\StorageRegistryTest class. * * @copyright Copyright (C) eZ Systems AS. All rights reserved. * @license For full copyright and license information view LICENSE file distributed with this source code. * * @version //autogentag// */ namespace eZ\Publish\Core\Persistence\Legacy\Tests\Content; use eZ\Publish\Core\Persistence\Legacy\Tests\TestCase; use eZ\Publish\Core\Persistence\Legacy\Content\StorageRegistry; /** * Test case for StorageRegistry. */ class StorageRegistryTest extends TestCase { /** * @covers eZ\Publish\Core\Persistence\Legacy\Content\StorageRegistry::register */ public function testRegister() { $storage = $this->getStorageMock(); $registry = new StorageRegistry(array('some-type' => $storage)); $this->assertAttributeSame( array( 'some-type' => $storage, ), 'storageMap', $registry ); } /** * @covers eZ\Publish\Core\Persistence\Legacy\Content\StorageRegistry::getStorage */ public function testGetStorage() { $storage = $this->getStorageMock(); $registry = new StorageRegistry(array('some-type' => $storage)); $res = $registry->getStorage('some-type'); $this->assertSame( $storage, $res ); } /** * @covers eZ\Publish\Core\Persistence\Legacy\Content\StorageRegistry::getStorage * @covers eZ\Publish\Core\Persistence\Legacy\Exception\StorageNotFound */ public function testGetNotFound() { $registry = new StorageRegistry(array()); self::assertInstanceOf( 'eZ\\Publish\\Core\\FieldType\\NullStorage', $registry->getStorage('not-found') ); } /** * Returns a mock for Storage. * * @return Storage */ protected function getStorageMock() { return $this->getMock( 'eZ\\Publish\\SPI\\FieldType\\FieldStorage' ); } }
flovntp/BikeTutorialWebsite
vendor/ezsystems/ezpublish-kernel/eZ/Publish/Core/Persistence/Legacy/Tests/Content/StorageRegistryTest.php
PHP
gpl-2.0
2,076
<?php /** * Credits administration panel. * * @package WordPress * @subpackage Administration */ /** WordPress Administration Bootstrap */ require_once __DIR__ . '/admin.php'; require_once __DIR__ . '/includes/credits.php'; $title = __( 'Credits' ); list( $display_version ) = explode( '-', get_bloginfo( 'version' ) ); require_once ABSPATH . 'wp-admin/admin-header.php'; $credits = wp_credits(); ?> <div class="wrap about__container"> <div class="about__header"> <div class="about__header-image"> <img alt="<?php _e( 'Code is Poetry' ); ?>" src="<?php echo admin_url( 'images/about-badge.svg' ); ?>" /> </div> <div class="about__header-container"> <div class="about__header-title"> <p> <?php _e( 'WordPress' ); ?> <?php echo $display_version; ?> </p> </div> <div class="about__header-text"> <?php _e( 'Jazz up your stories in an editor that’s cleaner, crisper, and does more to get out of your way.' ); ?> </div> </div> <nav class="about__header-navigation nav-tab-wrapper wp-clearfix" aria-label="<?php esc_attr_e( 'Secondary menu' ); ?>"> <a href="about.php" class="nav-tab"><?php _e( 'What&#8217;s New' ); ?></a> <a href="credits.php" class="nav-tab nav-tab-active" aria-current="page"><?php _e( 'Credits' ); ?></a> <a href="freedoms.php" class="nav-tab"><?php _e( 'Freedoms' ); ?></a> <a href="privacy.php" class="nav-tab"><?php _e( 'Privacy' ); ?></a> </nav> </div> <div class="about__section is-feature"> <div class="column"> <h1><?php _e( 'Credits' ); ?></h1> <?php if ( ! $credits ) : ?> <p> <?php printf( /* translators: 1: https://wordpress.org/about/, 2: https://make.wordpress.org/ */ __( 'WordPress is created by a <a href="%1$s">worldwide team</a> of passionate individuals. <a href="%2$s">Get involved in WordPress</a>.' ), __( 'https://wordpress.org/about/' ), __( 'https://make.wordpress.org/' ) ); ?> </p> <?php else : ?> <p> <?php _e( 'WordPress is created by a worldwide team of passionate individuals.' ); ?> </p> <p> <?php printf( /* translators: %s: https://make.wordpress.org/ */ __( 'Want to see your name in lights on this page? <a href="%s">Get involved in WordPress</a>.' ), __( 'https://make.wordpress.org/' ) ); ?> </p> <?php endif; ?> </div> </div> <?php if ( ! $credits ) { echo '</div>'; require_once ABSPATH . 'wp-admin/admin-footer.php'; exit; } ?> <hr /> <div class="about__section"> <div class="column has-subtle-background-color"> <?php wp_credits_section_title( $credits['groups']['core-developers'] ); ?> <?php wp_credits_section_list( $credits, 'core-developers' ); ?> <?php wp_credits_section_list( $credits, 'contributing-developers' ); ?> </div> </div> <hr /> <div class="about__section"> <div class="column"> <?php wp_credits_section_title( $credits['groups']['props'] ); ?> <?php wp_credits_section_list( $credits, 'props' ); ?> </div> </div> <hr /> <?php if ( isset( $credits['groups']['translators'] ) || isset( $credits['groups']['validators'] ) ) : ?> <div class="about__section"> <div class="column"> <?php wp_credits_section_title( $credits['groups']['validators'] ); ?> <?php wp_credits_section_list( $credits, 'validators' ); ?> <?php wp_credits_section_list( $credits, 'translators' ); ?> </div> </div> <hr /> <?php endif; ?> <div class="about__section"> <div class="column"> <?php wp_credits_section_title( $credits['groups']['libraries'] ); ?> <?php wp_credits_section_list( $credits, 'libraries' ); ?> </div> </div> </div> <?php require_once ABSPATH . 'wp-admin/admin-footer.php'; return; // These are strings returned by the API that we want to be translatable. __( 'Project Leaders' ); /* translators: %s: The current WordPress version number. */ __( 'Core Contributors to WordPress %s' ); __( 'Noteworthy Contributors' ); __( 'Cofounder, Project Lead' ); __( 'Lead Developer' ); __( 'Release Lead' ); __( 'Release Design Lead' ); __( 'Release Deputy' ); __( 'Core Developer' ); __( 'External Libraries' );
TheThumbsupguy/Ross-Upholstery-Inc
wp-admin/credits.php
PHP
gpl-2.0
4,135
/* * linux/arch/arm/mach-mmp/brownstone.c * * Support for the Marvell Brownstone Development Platform. * * Copyright (C) 2009-2010 Marvell International Ltd. * * 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 * publishhed by the Free Software Foundation. */ #include <linux/init.h> #include <linux/kernel.h> #include <linux/platform_device.h> #include <linux/io.h> #include <linux/gpio-pxa.h> #include <linux/regulator/machine.h> #include <linux/regulator/max8649.h> #include <linux/regulator/fixed.h> #include <linux/mfd/max8925.h> #include <linux/usb/phy.h> #include <linux/usb/mv_usb2_phy.h> #include <linux/platform_data/mv_usb.h> #include <asm/mach-types.h> #include <asm/mach/arch.h> #include <mach/addr-map.h> #include <mach/mfp-mmp2.h> #include <mach/mmp2.h> #include <mach/irqs.h> #include "common.h" #define BROWNSTONE_NR_IRQS (MMP_NR_IRQS + 40) #define GPIO_5V_ENABLE (89) static unsigned long brownstone_pin_config[] __initdata = { /* UART1 */ GPIO29_UART1_RXD, GPIO30_UART1_TXD, /* UART3 */ GPIO51_UART3_RXD, GPIO52_UART3_TXD, /* DFI */ GPIO168_DFI_D0, GPIO167_DFI_D1, GPIO166_DFI_D2, GPIO165_DFI_D3, GPIO107_DFI_D4, GPIO106_DFI_D5, GPIO105_DFI_D6, GPIO104_DFI_D7, GPIO111_DFI_D8, GPIO164_DFI_D9, GPIO163_DFI_D10, GPIO162_DFI_D11, GPIO161_DFI_D12, GPIO110_DFI_D13, GPIO109_DFI_D14, GPIO108_DFI_D15, GPIO143_ND_nCS0, GPIO144_ND_nCS1, GPIO147_ND_nWE, GPIO148_ND_nRE, GPIO150_ND_ALE, GPIO149_ND_CLE, GPIO112_ND_RDY0, GPIO160_ND_RDY1, /* PMIC */ PMIC_PMIC_INT | MFP_LPM_EDGE_FALL, /* MMC0 */ GPIO131_MMC1_DAT3 | MFP_PULL_HIGH, GPIO132_MMC1_DAT2 | MFP_PULL_HIGH, GPIO133_MMC1_DAT1 | MFP_PULL_HIGH, GPIO134_MMC1_DAT0 | MFP_PULL_HIGH, GPIO136_MMC1_CMD | MFP_PULL_HIGH, GPIO139_MMC1_CLK, GPIO140_MMC1_CD | MFP_PULL_LOW, GPIO141_MMC1_WP | MFP_PULL_LOW, /* MMC1 */ GPIO37_MMC2_DAT3 | MFP_PULL_HIGH, GPIO38_MMC2_DAT2 | MFP_PULL_HIGH, GPIO39_MMC2_DAT1 | MFP_PULL_HIGH, GPIO40_MMC2_DAT0 | MFP_PULL_HIGH, GPIO41_MMC2_CMD | MFP_PULL_HIGH, GPIO42_MMC2_CLK, /* MMC2 */ GPIO165_MMC3_DAT7 | MFP_PULL_HIGH, GPIO162_MMC3_DAT6 | MFP_PULL_HIGH, GPIO166_MMC3_DAT5 | MFP_PULL_HIGH, GPIO163_MMC3_DAT4 | MFP_PULL_HIGH, GPIO167_MMC3_DAT3 | MFP_PULL_HIGH, GPIO164_MMC3_DAT2 | MFP_PULL_HIGH, GPIO168_MMC3_DAT1 | MFP_PULL_HIGH, GPIO111_MMC3_DAT0 | MFP_PULL_HIGH, GPIO112_MMC3_CMD | MFP_PULL_HIGH, GPIO151_MMC3_CLK, /* 5V regulator */ GPIO89_GPIO, }; static struct pxa_gpio_platform_data mmp2_gpio_pdata = { .irq_base = MMP_GPIO_TO_IRQ(0), }; static struct regulator_consumer_supply max8649_supply[] = { REGULATOR_SUPPLY("vcc_core", NULL), }; static struct regulator_init_data max8649_init_data = { .constraints = { .name = "vcc_core range", .min_uV = 1150000, .max_uV = 1280000, .always_on = 1, .boot_on = 1, .valid_ops_mask = REGULATOR_CHANGE_VOLTAGE, }, .num_consumer_supplies = 1, .consumer_supplies = &max8649_supply[0], }; static struct max8649_platform_data brownstone_max8649_info = { .mode = 2, /* VID1 = 1, VID0 = 0 */ .extclk = 0, .ramp_timing = MAX8649_RAMP_32MV, .regulator = &max8649_init_data, }; static struct regulator_consumer_supply brownstone_v_5vp_supplies[] = { REGULATOR_SUPPLY("v_5vp", NULL), }; static struct regulator_init_data brownstone_v_5vp_data = { .constraints = { .valid_ops_mask = REGULATOR_CHANGE_STATUS, }, .num_consumer_supplies = ARRAY_SIZE(brownstone_v_5vp_supplies), .consumer_supplies = brownstone_v_5vp_supplies, }; static struct fixed_voltage_config brownstone_v_5vp = { .supply_name = "v_5vp", .microvolts = 5000000, .gpio = GPIO_5V_ENABLE, .enable_high = 1, .enabled_at_boot = 1, .init_data = &brownstone_v_5vp_data, }; static struct platform_device brownstone_v_5vp_device = { .name = "reg-fixed-voltage", .id = 1, .dev = { .platform_data = &brownstone_v_5vp, }, }; static struct max8925_platform_data brownstone_max8925_info = { .irq_base = MMP_NR_IRQS, }; static struct i2c_board_info brownstone_twsi1_info[] = { [0] = { .type = "max8649", .addr = 0x60, .platform_data = &brownstone_max8649_info, }, [1] = { .type = "max8925", .addr = 0x3c, .irq = IRQ_MMP2_PMIC, .platform_data = &brownstone_max8925_info, }, }; static struct sdhci_pxa_platdata mmp2_sdh_platdata_mmc0 = { .clk_delay_cycles = 0x1f, }; static struct sdhci_pxa_platdata mmp2_sdh_platdata_mmc2 = { .clk_delay_cycles = 0x1f, .flags = PXA_FLAG_CARD_PERMANENT | PXA_FLAG_SD_8_BIT_CAPABLE_SLOT, }; static struct sram_platdata mmp2_asram_platdata = { .pool_name = "asram", .granularity = SRAM_GRANULARITY, }; static struct sram_platdata mmp2_isram_platdata = { .pool_name = "isram", .granularity = SRAM_GRANULARITY, }; #ifdef CONFIG_USB_SUPPORT #if defined(CONFIG_USB_MV_UDC) || defined(CONFIG_USB_EHCI_MV_U2O) static struct mv_usb_platform_data brownstone_usb_pdata = { .vbus = NULL, .mode = MV_USB_MODE_OTG, .otg_force_a_bus_req = 1, .set_vbus = NULL, }; #endif #endif static void __init brownstone_init(void) { mfp_config(ARRAY_AND_SIZE(brownstone_pin_config)); /* on-chip devices */ mmp2_add_uart(1); mmp2_add_uart(3); platform_device_add_data(&mmp2_device_gpio, &mmp2_gpio_pdata, sizeof(struct pxa_gpio_platform_data)); platform_device_register(&mmp2_device_gpio); mmp2_add_twsi(1, NULL, ARRAY_AND_SIZE(brownstone_twsi1_info)); mmp2_add_sdhost(0, &mmp2_sdh_platdata_mmc0); /* SD/MMC */ mmp2_add_sdhost(2, &mmp2_sdh_platdata_mmc2); /* eMMC */ mmp2_add_asram(&mmp2_asram_platdata); mmp2_add_isram(&mmp2_isram_platdata); /* enable 5v regulator */ platform_device_register(&brownstone_v_5vp_device); #ifdef CONFIG_USB_SUPPORT pxa_register_device(&mmp2_device_u2ophy, NULL, 0); #endif #ifdef CONFIG_USB_MV_UDC /* for usb2 phy */ usb_bind_phy(mmp2_device_u2o.drv_name, MV_USB2_PHY_INDEX, mmp2_device_u2ophy.drv_name); #ifdef CONFIG_USB_MV_OTG /* for usb2 otg phy */ usb_bind_phy(mmp2_device_u2o.drv_name, MV_USB2_OTG_PHY_INDEX, mmp2_device_u2ootg.drv_name); #endif pxa_register_device(&mmp2_device_u2o, &brownstone_usb_pdata, sizeof(brownstone_usb_pdata)); #endif #ifdef CONFIG_USB_EHCI_MV_U2O /* for usb2 phy */ usb_bind_phy(mmp2_device_u2oehci.dev_name, MV_USB2_PHY_INDEX, mmp2_device_u2ophy.dev_name); #ifdef CONFIG_USB_MV_OTG /* for usb2 otg phy */ usb_bind_phy(mmp2_device_u2oehci.drv_name, MV_USB2_OTG_PHY_INDEX, mmp2_device_u2ootg.drv_name); #endif pxa_register_device(&mmp2_device_u2oehci, &brownstone_usb_pdata, sizeof(brownstone_usb_pdata)); #endif #ifdef CONFIG_USB_MV_OTG /* for usb2 phy */ usb_bind_phy(mmp2_device_u2ootg.dev_name, MV_USB2_PHY_INDEX, mmp2_device_u2ophy.dev_name); pxa_register_device(&mmp2_device_u2ootg, &brownstone_usb_pdata, sizeof(brownstone_usb_pdata)); #endif } MACHINE_START(BROWNSTONE, "Brownstone Development Platform") /* Maintainer: Haojian Zhuang <haojian.zhuang@marvell.com> */ .map_io = mmp_map_io, .nr_irqs = BROWNSTONE_NR_IRQS, .init_irq = mmp2_init_irq, .init_time = mmp2_timer_init, .init_machine = brownstone_init, .restart = mmp_restart, MACHINE_END
chase2534/gtab47.freekern
arch/arm/mach-mmp/brownstone.c
C
gpl-2.0
7,186
/* * INET An implementation of the TCP/IP protocol suite for the LINUX * operating system. INET is implemented using the BSD Socket * interface as the means of communication with the user level. * * Implementation of the Transmission Control Protocol(TCP). * * Authors: Ross Biro * Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG> * Mark Evans, <evansmp@uhura.aston.ac.uk> * Corey Minyard <wf-rch!minyard@relay.EU.net> * Florian La Roche, <flla@stud.uni-sb.de> * Charles Hedrick, <hedrick@klinzhai.rutgers.edu> * Linus Torvalds, <torvalds@cs.helsinki.fi> * Alan Cox, <gw4pts@gw4pts.ampr.org> * Matthew Dillon, <dillon@apollo.west.oic.com> * Arnt Gulbrandsen, <agulbra@nvg.unit.no> * Jorge Cwik, <jorge@laser.satlink.net> */ /* * Changes: * Pedro Roque : Fast Retransmit/Recovery. * Two receive queues. * Retransmit queue handled by TCP. * Better retransmit timer handling. * New congestion avoidance. * Header prediction. * Variable renaming. * * Eric : Fast Retransmit. * Randy Scott : MSS option defines. * Eric Schenk : Fixes to slow start algorithm. * Eric Schenk : Yet another double ACK bug. * Eric Schenk : Delayed ACK bug fixes. * Eric Schenk : Floyd style fast retrans war avoidance. * David S. Miller : Don't allow zero congestion window. * Eric Schenk : Fix retransmitter so that it sends * next packet on ack of previous packet. * Andi Kleen : Moved open_request checking here * and process RSTs for open_requests. * Andi Kleen : Better prune_queue, and other fixes. * Andrey Savochkin: Fix RTT measurements in the presence of * timestamps. * Andrey Savochkin: Check sequence numbers correctly when * removing SACKs due to in sequence incoming * data segments. * Andi Kleen: Make sure we never ack data there is not * enough room for. Also make this condition * a fatal error if it might still happen. * Andi Kleen: Add tcp_measure_rcv_mss to make * connections with MSS<min(MTU,ann. MSS) * work without delayed acks. * Andi Kleen: Process packets with PSH set in the * fast path. * J Hadi Salim: ECN support * Andrei Gurtov, * Pasi Sarolahti, * Panu Kuhlberg: Experimental audit of TCP (re)transmission * engine. Lots of bugs are found. * Pasi Sarolahti: F-RTO for dealing with spurious RTOs */ #define pr_fmt(fmt) "TCP: " fmt #include <linux/mm.h> #include <linux/slab.h> #include <linux/module.h> #include <linux/sysctl.h> #include <linux/kernel.h> #include <net/dst.h> #include <net/tcp.h> #include <net/inet_common.h> #include <linux/ipsec.h> #include <asm/unaligned.h> #include <net/netdma.h> int sysctl_tcp_timestamps __read_mostly = 1; int sysctl_tcp_window_scaling __read_mostly = 1; int sysctl_tcp_sack __read_mostly = 1; int sysctl_tcp_fack __read_mostly = 1; int sysctl_tcp_reordering __read_mostly = TCP_FASTRETRANS_THRESH; EXPORT_SYMBOL(sysctl_tcp_reordering); int sysctl_tcp_dsack __read_mostly = 1; int sysctl_tcp_app_win __read_mostly = 31; int sysctl_tcp_adv_win_scale __read_mostly = 1; EXPORT_SYMBOL(sysctl_tcp_adv_win_scale); /* rfc5961 challenge ack rate limiting */ int sysctl_tcp_challenge_ack_limit = 100; int sysctl_tcp_stdurg __read_mostly; int sysctl_tcp_rfc1337 __read_mostly; int sysctl_tcp_max_orphans __read_mostly = NR_FILE; int sysctl_tcp_frto __read_mostly = 2; int sysctl_tcp_thin_dupack __read_mostly; int sysctl_tcp_moderate_rcvbuf __read_mostly = 1; int sysctl_tcp_early_retrans __read_mostly = 3; int sysctl_tcp_default_init_rwnd __read_mostly = TCP_DEFAULT_INIT_RCVWND; #define FLAG_DATA 0x01 /* Incoming frame contained data. */ #define FLAG_WIN_UPDATE 0x02 /* Incoming ACK was a window update. */ #define FLAG_DATA_ACKED 0x04 /* This ACK acknowledged new data. */ #define FLAG_RETRANS_DATA_ACKED 0x08 /* "" "" some of which was retransmitted. */ #define FLAG_SYN_ACKED 0x10 /* This ACK acknowledged SYN. */ #define FLAG_DATA_SACKED 0x20 /* New SACK. */ #define FLAG_ECE 0x40 /* ECE in this ACK */ #define FLAG_SLOWPATH 0x100 /* Do not skip RFC checks for window update.*/ #define FLAG_ORIG_SACK_ACKED 0x200 /* Never retransmitted data are (s)acked */ #define FLAG_SND_UNA_ADVANCED 0x400 /* Snd_una was changed (!= FLAG_DATA_ACKED) */ #define FLAG_DSACKING_ACK 0x800 /* SACK blocks contained D-SACK info */ #define FLAG_SACK_RENEGING 0x2000 /* snd_una advanced to a sacked seq */ #define FLAG_UPDATE_TS_RECENT 0x4000 /* tcp_replace_ts_recent() */ #define FLAG_ACKED (FLAG_DATA_ACKED|FLAG_SYN_ACKED) #define FLAG_NOT_DUP (FLAG_DATA|FLAG_WIN_UPDATE|FLAG_ACKED) #define FLAG_CA_ALERT (FLAG_DATA_SACKED|FLAG_ECE) #define FLAG_FORWARD_PROGRESS (FLAG_ACKED|FLAG_DATA_SACKED) #define TCP_REMNANT (TCP_FLAG_FIN|TCP_FLAG_URG|TCP_FLAG_SYN|TCP_FLAG_PSH) #define TCP_HP_BITS (~(TCP_RESERVED_BITS|TCP_FLAG_PSH)) /* Adapt the MSS value used to make delayed ack decision to the * real world. */ static void tcp_measure_rcv_mss(struct sock *sk, const struct sk_buff *skb) { struct inet_connection_sock *icsk = inet_csk(sk); const unsigned int lss = icsk->icsk_ack.last_seg_size; unsigned int len; icsk->icsk_ack.last_seg_size = 0; /* skb->len may jitter because of SACKs, even if peer * sends good full-sized frames. */ len = skb_shinfo(skb)->gso_size ? : skb->len; if (len >= icsk->icsk_ack.rcv_mss) { icsk->icsk_ack.rcv_mss = len; } else { /* Otherwise, we make more careful check taking into account, * that SACKs block is variable. * * "len" is invariant segment length, including TCP header. */ len += skb->data - skb_transport_header(skb); if (len >= TCP_MSS_DEFAULT + sizeof(struct tcphdr) || /* If PSH is not set, packet should be * full sized, provided peer TCP is not badly broken. * This observation (if it is correct 8)) allows * to handle super-low mtu links fairly. */ (len >= TCP_MIN_MSS + sizeof(struct tcphdr) && !(tcp_flag_word(tcp_hdr(skb)) & TCP_REMNANT))) { /* Subtract also invariant (if peer is RFC compliant), * tcp header plus fixed timestamp option length. * Resulting "len" is MSS free of SACK jitter. */ len -= tcp_sk(sk)->tcp_header_len; icsk->icsk_ack.last_seg_size = len; if (len == lss) { icsk->icsk_ack.rcv_mss = len; return; } } if (icsk->icsk_ack.pending & ICSK_ACK_PUSHED) icsk->icsk_ack.pending |= ICSK_ACK_PUSHED2; icsk->icsk_ack.pending |= ICSK_ACK_PUSHED; } } static void tcp_incr_quickack(struct sock *sk) { struct inet_connection_sock *icsk = inet_csk(sk); unsigned int quickacks = tcp_sk(sk)->rcv_wnd / (2 * icsk->icsk_ack.rcv_mss); if (quickacks == 0) quickacks = 2; if (quickacks > icsk->icsk_ack.quick) icsk->icsk_ack.quick = min(quickacks, TCP_MAX_QUICKACKS); } static void tcp_enter_quickack_mode(struct sock *sk) { struct inet_connection_sock *icsk = inet_csk(sk); tcp_incr_quickack(sk); icsk->icsk_ack.pingpong = 0; icsk->icsk_ack.ato = TCP_ATO_MIN; } /* Send ACKs quickly, if "quick" count is not exhausted * and the session is not interactive. */ static inline bool tcp_in_quickack_mode(const struct sock *sk) { const struct inet_connection_sock *icsk = inet_csk(sk); return icsk->icsk_ack.quick && !icsk->icsk_ack.pingpong; } static inline void TCP_ECN_queue_cwr(struct tcp_sock *tp) { if (tp->ecn_flags & TCP_ECN_OK) tp->ecn_flags |= TCP_ECN_QUEUE_CWR; } static inline void TCP_ECN_accept_cwr(struct tcp_sock *tp, const struct sk_buff *skb) { if (tcp_hdr(skb)->cwr) tp->ecn_flags &= ~TCP_ECN_DEMAND_CWR; } static inline void TCP_ECN_withdraw_cwr(struct tcp_sock *tp) { tp->ecn_flags &= ~TCP_ECN_DEMAND_CWR; } static inline void TCP_ECN_check_ce(struct tcp_sock *tp, const struct sk_buff *skb) { if (!(tp->ecn_flags & TCP_ECN_OK)) return; switch (TCP_SKB_CB(skb)->ip_dsfield & INET_ECN_MASK) { case INET_ECN_NOT_ECT: /* Funny extension: if ECT is not set on a segment, * and we already seen ECT on a previous segment, * it is probably a retransmit. */ if (tp->ecn_flags & TCP_ECN_SEEN) tcp_enter_quickack_mode((struct sock *)tp); break; case INET_ECN_CE: if (!(tp->ecn_flags & TCP_ECN_DEMAND_CWR)) { /* Better not delay acks, sender can have a very low cwnd */ tcp_enter_quickack_mode((struct sock *)tp); tp->ecn_flags |= TCP_ECN_DEMAND_CWR; } /* fallinto */ default: tp->ecn_flags |= TCP_ECN_SEEN; } } static inline void TCP_ECN_rcv_synack(struct tcp_sock *tp, const struct tcphdr *th) { if ((tp->ecn_flags & TCP_ECN_OK) && (!th->ece || th->cwr)) tp->ecn_flags &= ~TCP_ECN_OK; } static inline void TCP_ECN_rcv_syn(struct tcp_sock *tp, const struct tcphdr *th) { if ((tp->ecn_flags & TCP_ECN_OK) && (!th->ece || !th->cwr)) tp->ecn_flags &= ~TCP_ECN_OK; } static bool TCP_ECN_rcv_ecn_echo(const struct tcp_sock *tp, const struct tcphdr *th) { if (th->ece && !th->syn && (tp->ecn_flags & TCP_ECN_OK)) return true; return false; } /* Buffer size and advertised window tuning. * * 1. Tuning sk->sk_sndbuf, when connection enters established state. */ static void tcp_fixup_sndbuf(struct sock *sk) { int sndmem = SKB_TRUESIZE(tcp_sk(sk)->rx_opt.mss_clamp + MAX_TCP_HEADER); sndmem *= TCP_INIT_CWND; if (sk->sk_sndbuf < sndmem) sk->sk_sndbuf = min(sndmem, sysctl_tcp_wmem[2]); } /* 2. Tuning advertised window (window_clamp, rcv_ssthresh) * * All tcp_full_space() is split to two parts: "network" buffer, allocated * forward and advertised in receiver window (tp->rcv_wnd) and * "application buffer", required to isolate scheduling/application * latencies from network. * window_clamp is maximal advertised window. It can be less than * tcp_full_space(), in this case tcp_full_space() - window_clamp * is reserved for "application" buffer. The less window_clamp is * the smoother our behaviour from viewpoint of network, but the lower * throughput and the higher sensitivity of the connection to losses. 8) * * rcv_ssthresh is more strict window_clamp used at "slow start" * phase to predict further behaviour of this connection. * It is used for two goals: * - to enforce header prediction at sender, even when application * requires some significant "application buffer". It is check #1. * - to prevent pruning of receive queue because of misprediction * of receiver window. Check #2. * * The scheme does not work when sender sends good segments opening * window and then starts to feed us spaghetti. But it should work * in common situations. Otherwise, we have to rely on queue collapsing. */ /* Slow part of check#2. */ static int __tcp_grow_window(const struct sock *sk, const struct sk_buff *skb) { struct tcp_sock *tp = tcp_sk(sk); /* Optimize this! */ int truesize = tcp_win_from_space(skb->truesize) >> 1; int window = tcp_win_from_space(sysctl_tcp_rmem[2]) >> 1; while (tp->rcv_ssthresh <= window) { if (truesize <= skb->len) return 2 * inet_csk(sk)->icsk_ack.rcv_mss; truesize >>= 1; window >>= 1; } return 0; } static void tcp_grow_window(struct sock *sk, const struct sk_buff *skb) { struct tcp_sock *tp = tcp_sk(sk); /* Check #1 */ if (tp->rcv_ssthresh < tp->window_clamp && (int)tp->rcv_ssthresh < tcp_space(sk) && !sk_under_memory_pressure(sk)) { int incr; /* Check #2. Increase window, if skb with such overhead * will fit to rcvbuf in future. */ if (tcp_win_from_space(skb->truesize) <= skb->len) incr = 2 * tp->advmss; else incr = __tcp_grow_window(sk, skb); if (incr) { incr = max_t(int, incr, 2 * skb->len); tp->rcv_ssthresh = min(tp->rcv_ssthresh + incr, tp->window_clamp); inet_csk(sk)->icsk_ack.quick |= 1; } } } /* 3. Tuning rcvbuf, when connection enters established state. */ static void tcp_fixup_rcvbuf(struct sock *sk) { u32 mss = tcp_sk(sk)->advmss; u32 icwnd = sysctl_tcp_default_init_rwnd; int rcvmem; /* Limit to 10 segments if mss <= 1460, * or 14600/mss segments, with a minimum of two segments. */ if (mss > 1460) icwnd = max_t(u32, (1460 * icwnd) / mss, 2); rcvmem = SKB_TRUESIZE(mss + MAX_TCP_HEADER); while (tcp_win_from_space(rcvmem) < mss) rcvmem += 128; rcvmem *= icwnd; if (sk->sk_rcvbuf < rcvmem) sk->sk_rcvbuf = min(rcvmem, sysctl_tcp_rmem[2]); } /* 4. Try to fixup all. It is made immediately after connection enters * established state. */ void tcp_init_buffer_space(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); int maxwin; if (!(sk->sk_userlocks & SOCK_RCVBUF_LOCK)) tcp_fixup_rcvbuf(sk); if (!(sk->sk_userlocks & SOCK_SNDBUF_LOCK)) tcp_fixup_sndbuf(sk); tp->rcvq_space.space = tp->rcv_wnd; maxwin = tcp_full_space(sk); if (tp->window_clamp >= maxwin) { tp->window_clamp = maxwin; if (sysctl_tcp_app_win && maxwin > 4 * tp->advmss) tp->window_clamp = max(maxwin - (maxwin >> sysctl_tcp_app_win), 4 * tp->advmss); } /* Force reservation of one segment. */ if (sysctl_tcp_app_win && tp->window_clamp > 2 * tp->advmss && tp->window_clamp + tp->advmss > maxwin) tp->window_clamp = max(2 * tp->advmss, maxwin - tp->advmss); tp->rcv_ssthresh = min(tp->rcv_ssthresh, tp->window_clamp); tp->snd_cwnd_stamp = tcp_time_stamp; } /* 5. Recalculate window clamp after socket hit its memory bounds. */ static void tcp_clamp_window(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); struct inet_connection_sock *icsk = inet_csk(sk); icsk->icsk_ack.quick = 0; if (sk->sk_rcvbuf < sysctl_tcp_rmem[2] && !(sk->sk_userlocks & SOCK_RCVBUF_LOCK) && !sk_under_memory_pressure(sk) && sk_memory_allocated(sk) < sk_prot_mem_limits(sk, 0)) { sk->sk_rcvbuf = min(atomic_read(&sk->sk_rmem_alloc), sysctl_tcp_rmem[2]); } if (atomic_read(&sk->sk_rmem_alloc) > sk->sk_rcvbuf) tp->rcv_ssthresh = min(tp->window_clamp, 2U * tp->advmss); } /* Initialize RCV_MSS value. * RCV_MSS is an our guess about MSS used by the peer. * We haven't any direct information about the MSS. * It's better to underestimate the RCV_MSS rather than overestimate. * Overestimations make us ACKing less frequently than needed. * Underestimations are more easy to detect and fix by tcp_measure_rcv_mss(). */ void tcp_initialize_rcv_mss(struct sock *sk) { const struct tcp_sock *tp = tcp_sk(sk); unsigned int hint = min_t(unsigned int, tp->advmss, tp->mss_cache); hint = min(hint, tp->rcv_wnd / 2); hint = min(hint, TCP_MSS_DEFAULT); hint = max(hint, TCP_MIN_MSS); inet_csk(sk)->icsk_ack.rcv_mss = hint; } EXPORT_SYMBOL(tcp_initialize_rcv_mss); /* Receiver "autotuning" code. * * The algorithm for RTT estimation w/o timestamps is based on * Dynamic Right-Sizing (DRS) by Wu Feng and Mike Fisk of LANL. * <http://public.lanl.gov/radiant/pubs.html#DRS> * * More detail on this code can be found at * <http://staff.psc.edu/jheffner/>, * though this reference is out of date. A new paper * is pending. */ static void tcp_rcv_rtt_update(struct tcp_sock *tp, u32 sample, int win_dep) { u32 new_sample = tp->rcv_rtt_est.rtt; long m = sample; if (m == 0) m = 1; if (new_sample != 0) { /* If we sample in larger samples in the non-timestamp * case, we could grossly overestimate the RTT especially * with chatty applications or bulk transfer apps which * are stalled on filesystem I/O. * * Also, since we are only going for a minimum in the * non-timestamp case, we do not smooth things out * else with timestamps disabled convergence takes too * long. */ if (!win_dep) { m -= (new_sample >> 3); new_sample += m; } else { m <<= 3; if (m < new_sample) new_sample = m; } } else { /* No previous measure. */ new_sample = m << 3; } if (tp->rcv_rtt_est.rtt != new_sample) tp->rcv_rtt_est.rtt = new_sample; } static inline void tcp_rcv_rtt_measure(struct tcp_sock *tp) { if (tp->rcv_rtt_est.time == 0) goto new_measure; if (before(tp->rcv_nxt, tp->rcv_rtt_est.seq)) return; tcp_rcv_rtt_update(tp, tcp_time_stamp - tp->rcv_rtt_est.time, 1); new_measure: tp->rcv_rtt_est.seq = tp->rcv_nxt + tp->rcv_wnd; tp->rcv_rtt_est.time = tcp_time_stamp; } static inline void tcp_rcv_rtt_measure_ts(struct sock *sk, const struct sk_buff *skb) { struct tcp_sock *tp = tcp_sk(sk); if (tp->rx_opt.rcv_tsecr && (TCP_SKB_CB(skb)->end_seq - TCP_SKB_CB(skb)->seq >= inet_csk(sk)->icsk_ack.rcv_mss)) tcp_rcv_rtt_update(tp, tcp_time_stamp - tp->rx_opt.rcv_tsecr, 0); } /* * This function should be called every time data is copied to user space. * It calculates the appropriate TCP receive buffer space. */ void tcp_rcv_space_adjust(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); int time; int space; if (tp->rcvq_space.time == 0) goto new_measure; time = tcp_time_stamp - tp->rcvq_space.time; if (time < (tp->rcv_rtt_est.rtt >> 3) || tp->rcv_rtt_est.rtt == 0) return; space = 2 * (tp->copied_seq - tp->rcvq_space.seq); space = max(tp->rcvq_space.space, space); if (tp->rcvq_space.space != space) { int rcvmem; tp->rcvq_space.space = space; if (sysctl_tcp_moderate_rcvbuf && !(sk->sk_userlocks & SOCK_RCVBUF_LOCK)) { int new_clamp = space; /* Receive space grows, normalize in order to * take into account packet headers and sk_buff * structure overhead. */ space /= tp->advmss; if (!space) space = 1; rcvmem = SKB_TRUESIZE(tp->advmss + MAX_TCP_HEADER); while (tcp_win_from_space(rcvmem) < tp->advmss) rcvmem += 128; space *= rcvmem; space = min(space, sysctl_tcp_rmem[2]); if (space > sk->sk_rcvbuf) { sk->sk_rcvbuf = space; /* Make the window clamp follow along. */ tp->window_clamp = new_clamp; } } } new_measure: tp->rcvq_space.seq = tp->copied_seq; tp->rcvq_space.time = tcp_time_stamp; } /* There is something which you must keep in mind when you analyze the * behavior of the tp->ato delayed ack timeout interval. When a * connection starts up, we want to ack as quickly as possible. The * problem is that "good" TCP's do slow start at the beginning of data * transmission. The means that until we send the first few ACK's the * sender will sit on his end and only queue most of his data, because * he can only send snd_cwnd unacked packets at any given time. For * each ACK we send, he increments snd_cwnd and transmits more of his * queue. -DaveM */ static void tcp_event_data_recv(struct sock *sk, struct sk_buff *skb) { struct tcp_sock *tp = tcp_sk(sk); struct inet_connection_sock *icsk = inet_csk(sk); u32 now; inet_csk_schedule_ack(sk); tcp_measure_rcv_mss(sk, skb); tcp_rcv_rtt_measure(tp); now = tcp_time_stamp; if (!icsk->icsk_ack.ato) { /* The _first_ data packet received, initialize * delayed ACK engine. */ tcp_incr_quickack(sk); icsk->icsk_ack.ato = TCP_ATO_MIN; } else { int m = now - icsk->icsk_ack.lrcvtime; if (m <= TCP_ATO_MIN / 2) { /* The fastest case is the first. */ icsk->icsk_ack.ato = (icsk->icsk_ack.ato >> 1) + TCP_ATO_MIN / 2; } else if (m < icsk->icsk_ack.ato) { icsk->icsk_ack.ato = (icsk->icsk_ack.ato >> 1) + m; if (icsk->icsk_ack.ato > icsk->icsk_rto) icsk->icsk_ack.ato = icsk->icsk_rto; } else if (m > icsk->icsk_rto) { /* Too long gap. Apparently sender failed to * restart window, so that we send ACKs quickly. */ tcp_incr_quickack(sk); sk_mem_reclaim(sk); } } icsk->icsk_ack.lrcvtime = now; TCP_ECN_check_ce(tp, skb); if (skb->len >= 128) tcp_grow_window(sk, skb); } /* Called to compute a smoothed rtt estimate. The data fed to this * routine either comes from timestamps, or from segments that were * known _not_ to have been retransmitted [see Karn/Partridge * Proceedings SIGCOMM 87]. The algorithm is from the SIGCOMM 88 * piece by Van Jacobson. * NOTE: the next three routines used to be one big routine. * To save cycles in the RFC 1323 implementation it was better to break * it up into three procedures. -- erics */ static void tcp_rtt_estimator(struct sock *sk, const __u32 mrtt) { struct tcp_sock *tp = tcp_sk(sk); long m = mrtt; /* RTT */ /* The following amusing code comes from Jacobson's * article in SIGCOMM '88. Note that rtt and mdev * are scaled versions of rtt and mean deviation. * This is designed to be as fast as possible * m stands for "measurement". * * On a 1990 paper the rto value is changed to: * RTO = rtt + 4 * mdev * * Funny. This algorithm seems to be very broken. * These formulae increase RTO, when it should be decreased, increase * too slowly, when it should be increased quickly, decrease too quickly * etc. I guess in BSD RTO takes ONE value, so that it is absolutely * does not matter how to _calculate_ it. Seems, it was trap * that VJ failed to avoid. 8) */ if (m == 0) m = 1; if (tp->srtt != 0) { m -= (tp->srtt >> 3); /* m is now error in rtt est */ tp->srtt += m; /* rtt = 7/8 rtt + 1/8 new */ if (m < 0) { m = -m; /* m is now abs(error) */ m -= (tp->mdev >> 2); /* similar update on mdev */ /* This is similar to one of Eifel findings. * Eifel blocks mdev updates when rtt decreases. * This solution is a bit different: we use finer gain * for mdev in this case (alpha*beta). * Like Eifel it also prevents growth of rto, * but also it limits too fast rto decreases, * happening in pure Eifel. */ if (m > 0) m >>= 3; } else { m -= (tp->mdev >> 2); /* similar update on mdev */ } tp->mdev += m; /* mdev = 3/4 mdev + 1/4 new */ if (tp->mdev > tp->mdev_max) { tp->mdev_max = tp->mdev; if (tp->mdev_max > tp->rttvar) tp->rttvar = tp->mdev_max; } if (after(tp->snd_una, tp->rtt_seq)) { if (tp->mdev_max < tp->rttvar) tp->rttvar -= (tp->rttvar - tp->mdev_max) >> 2; tp->rtt_seq = tp->snd_nxt; tp->mdev_max = tcp_rto_min(sk); } } else { /* no previous measure. */ tp->srtt = m << 3; /* take the measured time to be rtt */ tp->mdev = m << 1; /* make sure rto = 3*rtt */ tp->mdev_max = tp->rttvar = max(tp->mdev, tcp_rto_min(sk)); tp->rtt_seq = tp->snd_nxt; } } /* Set the sk_pacing_rate to allow proper sizing of TSO packets. * Note: TCP stack does not yet implement pacing. * FQ packet scheduler can be used to implement cheap but effective * TCP pacing, to smooth the burst on large writes when packets * in flight is significantly lower than cwnd (or rwin) */ static void tcp_update_pacing_rate(struct sock *sk) { const struct tcp_sock *tp = tcp_sk(sk); u64 rate; /* set sk_pacing_rate to 200 % of current rate (mss * cwnd / srtt) */ rate = (u64)tp->mss_cache * 2 * (HZ << 3); rate *= max(tp->snd_cwnd, tp->packets_out); /* Correction for small srtt : minimum srtt being 8 (1 jiffy << 3), * be conservative and assume srtt = 1 (125 us instead of 1.25 ms) * We probably need usec resolution in the future. * Note: This also takes care of possible srtt=0 case, * when tcp_rtt_estimator() was not yet called. */ if (tp->srtt > 8 + 2) do_div(rate, tp->srtt); sk->sk_pacing_rate = min_t(u64, rate, ~0U); } /* Calculate rto without backoff. This is the second half of Van Jacobson's * routine referred to above. */ void tcp_set_rto(struct sock *sk) { const struct tcp_sock *tp = tcp_sk(sk); /* Old crap is replaced with new one. 8) * * More seriously: * 1. If rtt variance happened to be less 50msec, it is hallucination. * It cannot be less due to utterly erratic ACK generation made * at least by solaris and freebsd. "Erratic ACKs" has _nothing_ * to do with delayed acks, because at cwnd>2 true delack timeout * is invisible. Actually, Linux-2.4 also generates erratic * ACKs in some circumstances. */ inet_csk(sk)->icsk_rto = __tcp_set_rto(tp); /* 2. Fixups made earlier cannot be right. * If we do not estimate RTO correctly without them, * all the algo is pure shit and should be replaced * with correct one. It is exactly, which we pretend to do. */ /* NOTE: clamping at TCP_RTO_MIN is not required, current algo * guarantees that rto is higher. */ tcp_bound_rto(sk); } __u32 tcp_init_cwnd(const struct tcp_sock *tp, const struct dst_entry *dst) { __u32 cwnd = (dst ? dst_metric(dst, RTAX_INITCWND) : 0); if (!cwnd) cwnd = TCP_INIT_CWND; return min_t(__u32, cwnd, tp->snd_cwnd_clamp); } /* * Packet counting of FACK is based on in-order assumptions, therefore TCP * disables it when reordering is detected */ void tcp_disable_fack(struct tcp_sock *tp) { /* RFC3517 uses different metric in lost marker => reset on change */ if (tcp_is_fack(tp)) tp->lost_skb_hint = NULL; tp->rx_opt.sack_ok &= ~TCP_FACK_ENABLED; } /* Take a notice that peer is sending D-SACKs */ static void tcp_dsack_seen(struct tcp_sock *tp) { tp->rx_opt.sack_ok |= TCP_DSACK_SEEN; } static void tcp_update_reordering(struct sock *sk, const int metric, const int ts) { struct tcp_sock *tp = tcp_sk(sk); if (metric > tp->reordering) { int mib_idx; tp->reordering = min(TCP_MAX_REORDERING, metric); /* This exciting event is worth to be remembered. 8) */ if (ts) mib_idx = LINUX_MIB_TCPTSREORDER; else if (tcp_is_reno(tp)) mib_idx = LINUX_MIB_TCPRENOREORDER; else if (tcp_is_fack(tp)) mib_idx = LINUX_MIB_TCPFACKREORDER; else mib_idx = LINUX_MIB_TCPSACKREORDER; NET_INC_STATS_BH(sock_net(sk), mib_idx); #if FASTRETRANS_DEBUG > 1 pr_debug("Disorder%d %d %u f%u s%u rr%d\n", tp->rx_opt.sack_ok, inet_csk(sk)->icsk_ca_state, tp->reordering, tp->fackets_out, tp->sacked_out, tp->undo_marker ? tp->undo_retrans : 0); #endif tcp_disable_fack(tp); } if (metric > 0) tcp_disable_early_retrans(tp); } /* This must be called before lost_out is incremented */ static void tcp_verify_retransmit_hint(struct tcp_sock *tp, struct sk_buff *skb) { if ((tp->retransmit_skb_hint == NULL) || before(TCP_SKB_CB(skb)->seq, TCP_SKB_CB(tp->retransmit_skb_hint)->seq)) tp->retransmit_skb_hint = skb; if (!tp->lost_out || after(TCP_SKB_CB(skb)->end_seq, tp->retransmit_high)) tp->retransmit_high = TCP_SKB_CB(skb)->end_seq; } static void tcp_skb_mark_lost(struct tcp_sock *tp, struct sk_buff *skb) { if (!(TCP_SKB_CB(skb)->sacked & (TCPCB_LOST|TCPCB_SACKED_ACKED))) { tcp_verify_retransmit_hint(tp, skb); tp->lost_out += tcp_skb_pcount(skb); TCP_SKB_CB(skb)->sacked |= TCPCB_LOST; } } static void tcp_skb_mark_lost_uncond_verify(struct tcp_sock *tp, struct sk_buff *skb) { tcp_verify_retransmit_hint(tp, skb); if (!(TCP_SKB_CB(skb)->sacked & (TCPCB_LOST|TCPCB_SACKED_ACKED))) { tp->lost_out += tcp_skb_pcount(skb); TCP_SKB_CB(skb)->sacked |= TCPCB_LOST; } } /* This procedure tags the retransmission queue when SACKs arrive. * * We have three tag bits: SACKED(S), RETRANS(R) and LOST(L). * Packets in queue with these bits set are counted in variables * sacked_out, retrans_out and lost_out, correspondingly. * * Valid combinations are: * Tag InFlight Description * 0 1 - orig segment is in flight. * S 0 - nothing flies, orig reached receiver. * L 0 - nothing flies, orig lost by net. * R 2 - both orig and retransmit are in flight. * L|R 1 - orig is lost, retransmit is in flight. * S|R 1 - orig reached receiver, retrans is still in flight. * (L|S|R is logically valid, it could occur when L|R is sacked, * but it is equivalent to plain S and code short-curcuits it to S. * L|S is logically invalid, it would mean -1 packet in flight 8)) * * These 6 states form finite state machine, controlled by the following events: * 1. New ACK (+SACK) arrives. (tcp_sacktag_write_queue()) * 2. Retransmission. (tcp_retransmit_skb(), tcp_xmit_retransmit_queue()) * 3. Loss detection event of two flavors: * A. Scoreboard estimator decided the packet is lost. * A'. Reno "three dupacks" marks head of queue lost. * A''. Its FACK modification, head until snd.fack is lost. * B. SACK arrives sacking SND.NXT at the moment, when the * segment was retransmitted. * 4. D-SACK added new rule: D-SACK changes any tag to S. * * It is pleasant to note, that state diagram turns out to be commutative, * so that we are allowed not to be bothered by order of our actions, * when multiple events arrive simultaneously. (see the function below). * * Reordering detection. * -------------------- * Reordering metric is maximal distance, which a packet can be displaced * in packet stream. With SACKs we can estimate it: * * 1. SACK fills old hole and the corresponding segment was not * ever retransmitted -> reordering. Alas, we cannot use it * when segment was retransmitted. * 2. The last flaw is solved with D-SACK. D-SACK arrives * for retransmitted and already SACKed segment -> reordering.. * Both of these heuristics are not used in Loss state, when we cannot * account for retransmits accurately. * * SACK block validation. * ---------------------- * * SACK block range validation checks that the received SACK block fits to * the expected sequence limits, i.e., it is between SND.UNA and SND.NXT. * Note that SND.UNA is not included to the range though being valid because * it means that the receiver is rather inconsistent with itself reporting * SACK reneging when it should advance SND.UNA. Such SACK block this is * perfectly valid, however, in light of RFC2018 which explicitly states * that "SACK block MUST reflect the newest segment. Even if the newest * segment is going to be discarded ...", not that it looks very clever * in case of head skb. Due to potentional receiver driven attacks, we * choose to avoid immediate execution of a walk in write queue due to * reneging and defer head skb's loss recovery to standard loss recovery * procedure that will eventually trigger (nothing forbids us doing this). * * Implements also blockage to start_seq wrap-around. Problem lies in the * fact that though start_seq (s) is before end_seq (i.e., not reversed), * there's no guarantee that it will be before snd_nxt (n). The problem * happens when start_seq resides between end_seq wrap (e_w) and snd_nxt * wrap (s_w): * * <- outs wnd -> <- wrapzone -> * u e n u_w e_w s n_w * | | | | | | | * |<------------+------+----- TCP seqno space --------------+---------->| * ...-- <2^31 ->| |<--------... * ...---- >2^31 ------>| |<--------... * * Current code wouldn't be vulnerable but it's better still to discard such * crazy SACK blocks. Doing this check for start_seq alone closes somewhat * similar case (end_seq after snd_nxt wrap) as earlier reversed check in * snd_nxt wrap -> snd_una region will then become "well defined", i.e., * equal to the ideal case (infinite seqno space without wrap caused issues). * * With D-SACK the lower bound is extended to cover sequence space below * SND.UNA down to undo_marker, which is the last point of interest. Yet * again, D-SACK block must not to go across snd_una (for the same reason as * for the normal SACK blocks, explained above). But there all simplicity * ends, TCP might receive valid D-SACKs below that. As long as they reside * fully below undo_marker they do not affect behavior in anyway and can * therefore be safely ignored. In rare cases (which are more or less * theoretical ones), the D-SACK will nicely cross that boundary due to skb * fragmentation and packet reordering past skb's retransmission. To consider * them correctly, the acceptable range must be extended even more though * the exact amount is rather hard to quantify. However, tp->max_window can * be used as an exaggerated estimate. */ static bool tcp_is_sackblock_valid(struct tcp_sock *tp, bool is_dsack, u32 start_seq, u32 end_seq) { /* Too far in future, or reversed (interpretation is ambiguous) */ if (after(end_seq, tp->snd_nxt) || !before(start_seq, end_seq)) return false; /* Nasty start_seq wrap-around check (see comments above) */ if (!before(start_seq, tp->snd_nxt)) return false; /* In outstanding window? ...This is valid exit for D-SACKs too. * start_seq == snd_una is non-sensical (see comments above) */ if (after(start_seq, tp->snd_una)) return true; if (!is_dsack || !tp->undo_marker) return false; /* ...Then it's D-SACK, and must reside below snd_una completely */ if (after(end_seq, tp->snd_una)) return false; if (!before(start_seq, tp->undo_marker)) return true; /* Too old */ if (!after(end_seq, tp->undo_marker)) return false; /* Undo_marker boundary crossing (overestimates a lot). Known already: * start_seq < undo_marker and end_seq >= undo_marker. */ return !before(start_seq, end_seq - tp->max_window); } /* Check for lost retransmit. This superb idea is borrowed from "ratehalving". * Event "B". Later note: FACK people cheated me again 8), we have to account * for reordering! Ugly, but should help. * * Search retransmitted skbs from write_queue that were sent when snd_nxt was * less than what is now known to be received by the other end (derived from * highest SACK block). Also calculate the lowest snd_nxt among the remaining * retransmitted skbs to avoid some costly processing per ACKs. */ static void tcp_mark_lost_retrans(struct sock *sk) { const struct inet_connection_sock *icsk = inet_csk(sk); struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *skb; int cnt = 0; u32 new_low_seq = tp->snd_nxt; u32 received_upto = tcp_highest_sack_seq(tp); if (!tcp_is_fack(tp) || !tp->retrans_out || !after(received_upto, tp->lost_retrans_low) || icsk->icsk_ca_state != TCP_CA_Recovery) return; tcp_for_write_queue(skb, sk) { u32 ack_seq = TCP_SKB_CB(skb)->ack_seq; if (skb == tcp_send_head(sk)) break; if (cnt == tp->retrans_out) break; if (!after(TCP_SKB_CB(skb)->end_seq, tp->snd_una)) continue; if (!(TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_RETRANS)) continue; /* TODO: We would like to get rid of tcp_is_fack(tp) only * constraint here (see above) but figuring out that at * least tp->reordering SACK blocks reside between ack_seq * and received_upto is not easy task to do cheaply with * the available datastructures. * * Whether FACK should check here for tp->reordering segs * in-between one could argue for either way (it would be * rather simple to implement as we could count fack_count * during the walk and do tp->fackets_out - fack_count). */ if (after(received_upto, ack_seq)) { TCP_SKB_CB(skb)->sacked &= ~TCPCB_SACKED_RETRANS; tp->retrans_out -= tcp_skb_pcount(skb); tcp_skb_mark_lost_uncond_verify(tp, skb); NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPLOSTRETRANSMIT); } else { if (before(ack_seq, new_low_seq)) new_low_seq = ack_seq; cnt += tcp_skb_pcount(skb); } } if (tp->retrans_out) tp->lost_retrans_low = new_low_seq; } static bool tcp_check_dsack(struct sock *sk, const struct sk_buff *ack_skb, struct tcp_sack_block_wire *sp, int num_sacks, u32 prior_snd_una) { struct tcp_sock *tp = tcp_sk(sk); u32 start_seq_0 = get_unaligned_be32(&sp[0].start_seq); u32 end_seq_0 = get_unaligned_be32(&sp[0].end_seq); bool dup_sack = false; if (before(start_seq_0, TCP_SKB_CB(ack_skb)->ack_seq)) { dup_sack = true; tcp_dsack_seen(tp); NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPDSACKRECV); } else if (num_sacks > 1) { u32 end_seq_1 = get_unaligned_be32(&sp[1].end_seq); u32 start_seq_1 = get_unaligned_be32(&sp[1].start_seq); if (!after(end_seq_0, end_seq_1) && !before(start_seq_0, start_seq_1)) { dup_sack = true; tcp_dsack_seen(tp); NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPDSACKOFORECV); } } /* D-SACK for already forgotten data... Do dumb counting. */ if (dup_sack && tp->undo_marker && tp->undo_retrans && !after(end_seq_0, prior_snd_una) && after(end_seq_0, tp->undo_marker)) tp->undo_retrans--; return dup_sack; } struct tcp_sacktag_state { int reord; int fack_count; int flag; }; /* Check if skb is fully within the SACK block. In presence of GSO skbs, * the incoming SACK may not exactly match but we can find smaller MSS * aligned portion of it that matches. Therefore we might need to fragment * which may fail and creates some hassle (caller must handle error case * returns). * * FIXME: this could be merged to shift decision code */ static int tcp_match_skb_to_sack(struct sock *sk, struct sk_buff *skb, u32 start_seq, u32 end_seq) { int err; bool in_sack; unsigned int pkt_len; unsigned int mss; in_sack = !after(start_seq, TCP_SKB_CB(skb)->seq) && !before(end_seq, TCP_SKB_CB(skb)->end_seq); if (tcp_skb_pcount(skb) > 1 && !in_sack && after(TCP_SKB_CB(skb)->end_seq, start_seq)) { mss = tcp_skb_mss(skb); in_sack = !after(start_seq, TCP_SKB_CB(skb)->seq); if (!in_sack) { pkt_len = start_seq - TCP_SKB_CB(skb)->seq; if (pkt_len < mss) pkt_len = mss; } else { pkt_len = end_seq - TCP_SKB_CB(skb)->seq; if (pkt_len < mss) return -EINVAL; } /* Round if necessary so that SACKs cover only full MSSes * and/or the remaining small portion (if present) */ if (pkt_len > mss) { unsigned int new_len = (pkt_len / mss) * mss; if (!in_sack && new_len < pkt_len) { new_len += mss; if (new_len > skb->len) return 0; } pkt_len = new_len; } err = tcp_fragment(sk, skb, pkt_len, mss); if (err < 0) return err; } return in_sack; } /* Mark the given newly-SACKed range as such, adjusting counters and hints. */ static u8 tcp_sacktag_one(struct sock *sk, struct tcp_sacktag_state *state, u8 sacked, u32 start_seq, u32 end_seq, bool dup_sack, int pcount) { struct tcp_sock *tp = tcp_sk(sk); int fack_count = state->fack_count; /* Account D-SACK for retransmitted packet. */ if (dup_sack && (sacked & TCPCB_RETRANS)) { if (tp->undo_marker && tp->undo_retrans && after(end_seq, tp->undo_marker)) tp->undo_retrans--; if (sacked & TCPCB_SACKED_ACKED) state->reord = min(fack_count, state->reord); } /* Nothing to do; acked frame is about to be dropped (was ACKed). */ if (!after(end_seq, tp->snd_una)) return sacked; if (!(sacked & TCPCB_SACKED_ACKED)) { if (sacked & TCPCB_SACKED_RETRANS) { /* If the segment is not tagged as lost, * we do not clear RETRANS, believing * that retransmission is still in flight. */ if (sacked & TCPCB_LOST) { sacked &= ~(TCPCB_LOST|TCPCB_SACKED_RETRANS); tp->lost_out -= pcount; tp->retrans_out -= pcount; } } else { if (!(sacked & TCPCB_RETRANS)) { /* New sack for not retransmitted frame, * which was in hole. It is reordering. */ if (before(start_seq, tcp_highest_sack_seq(tp))) state->reord = min(fack_count, state->reord); if (!after(end_seq, tp->high_seq)) state->flag |= FLAG_ORIG_SACK_ACKED; } if (sacked & TCPCB_LOST) { sacked &= ~TCPCB_LOST; tp->lost_out -= pcount; } } sacked |= TCPCB_SACKED_ACKED; state->flag |= FLAG_DATA_SACKED; tp->sacked_out += pcount; fack_count += pcount; /* Lost marker hint past SACKed? Tweak RFC3517 cnt */ if (!tcp_is_fack(tp) && (tp->lost_skb_hint != NULL) && before(start_seq, TCP_SKB_CB(tp->lost_skb_hint)->seq)) tp->lost_cnt_hint += pcount; if (fack_count > tp->fackets_out) tp->fackets_out = fack_count; } /* D-SACK. We can detect redundant retransmission in S|R and plain R * frames and clear it. undo_retrans is decreased above, L|R frames * are accounted above as well. */ if (dup_sack && (sacked & TCPCB_SACKED_RETRANS)) { sacked &= ~TCPCB_SACKED_RETRANS; tp->retrans_out -= pcount; } return sacked; } /* Shift newly-SACKed bytes from this skb to the immediately previous * already-SACKed sk_buff. Mark the newly-SACKed bytes as such. */ static bool tcp_shifted_skb(struct sock *sk, struct sk_buff *skb, struct tcp_sacktag_state *state, unsigned int pcount, int shifted, int mss, bool dup_sack) { struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *prev = tcp_write_queue_prev(sk, skb); u32 start_seq = TCP_SKB_CB(skb)->seq; /* start of newly-SACKed */ u32 end_seq = start_seq + shifted; /* end of newly-SACKed */ BUG_ON(!pcount); /* Adjust counters and hints for the newly sacked sequence * range but discard the return value since prev is already * marked. We must tag the range first because the seq * advancement below implicitly advances * tcp_highest_sack_seq() when skb is highest_sack. */ tcp_sacktag_one(sk, state, TCP_SKB_CB(skb)->sacked, start_seq, end_seq, dup_sack, pcount); if (skb == tp->lost_skb_hint) tp->lost_cnt_hint += pcount; TCP_SKB_CB(prev)->end_seq += shifted; TCP_SKB_CB(skb)->seq += shifted; skb_shinfo(prev)->gso_segs += pcount; BUG_ON(skb_shinfo(skb)->gso_segs < pcount); skb_shinfo(skb)->gso_segs -= pcount; /* When we're adding to gso_segs == 1, gso_size will be zero, * in theory this shouldn't be necessary but as long as DSACK * code can come after this skb later on it's better to keep * setting gso_size to something. */ if (!skb_shinfo(prev)->gso_size) { skb_shinfo(prev)->gso_size = mss; skb_shinfo(prev)->gso_type = sk->sk_gso_type; } /* CHECKME: To clear or not to clear? Mimics normal skb currently */ if (skb_shinfo(skb)->gso_segs <= 1) { skb_shinfo(skb)->gso_size = 0; skb_shinfo(skb)->gso_type = 0; } /* Difference in this won't matter, both ACKed by the same cumul. ACK */ TCP_SKB_CB(prev)->sacked |= (TCP_SKB_CB(skb)->sacked & TCPCB_EVER_RETRANS); if (skb->len > 0) { BUG_ON(!tcp_skb_pcount(skb)); NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_SACKSHIFTED); return false; } /* Whole SKB was eaten :-) */ if (skb == tp->retransmit_skb_hint) tp->retransmit_skb_hint = prev; if (skb == tp->scoreboard_skb_hint) tp->scoreboard_skb_hint = prev; if (skb == tp->lost_skb_hint) { tp->lost_skb_hint = prev; tp->lost_cnt_hint -= tcp_skb_pcount(prev); } TCP_SKB_CB(prev)->tcp_flags |= TCP_SKB_CB(skb)->tcp_flags; if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN) TCP_SKB_CB(prev)->end_seq++; if (skb == tcp_highest_sack(sk)) tcp_advance_highest_sack(sk, skb); tcp_unlink_write_queue(skb, sk); sk_wmem_free_skb(sk, skb); NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_SACKMERGED); return true; } /* I wish gso_size would have a bit more sane initialization than * something-or-zero which complicates things */ static int tcp_skb_seglen(const struct sk_buff *skb) { return tcp_skb_pcount(skb) == 1 ? skb->len : tcp_skb_mss(skb); } /* Shifting pages past head area doesn't work */ static int skb_can_shift(const struct sk_buff *skb) { return !skb_headlen(skb) && skb_is_nonlinear(skb); } /* Try collapsing SACK blocks spanning across multiple skbs to a single * skb. */ static struct sk_buff *tcp_shift_skb_data(struct sock *sk, struct sk_buff *skb, struct tcp_sacktag_state *state, u32 start_seq, u32 end_seq, bool dup_sack) { struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *prev; int mss; int pcount = 0; int len; int in_sack; if (!sk_can_gso(sk)) goto fallback; /* Normally R but no L won't result in plain S */ if (!dup_sack && (TCP_SKB_CB(skb)->sacked & (TCPCB_LOST|TCPCB_SACKED_RETRANS)) == TCPCB_SACKED_RETRANS) goto fallback; if (!skb_can_shift(skb)) goto fallback; /* This frame is about to be dropped (was ACKed). */ if (!after(TCP_SKB_CB(skb)->end_seq, tp->snd_una)) goto fallback; /* Can only happen with delayed DSACK + discard craziness */ if (unlikely(skb == tcp_write_queue_head(sk))) goto fallback; prev = tcp_write_queue_prev(sk, skb); if ((TCP_SKB_CB(prev)->sacked & TCPCB_TAGBITS) != TCPCB_SACKED_ACKED) goto fallback; in_sack = !after(start_seq, TCP_SKB_CB(skb)->seq) && !before(end_seq, TCP_SKB_CB(skb)->end_seq); if (in_sack) { len = skb->len; pcount = tcp_skb_pcount(skb); mss = tcp_skb_seglen(skb); /* TODO: Fix DSACKs to not fragment already SACKed and we can * drop this restriction as unnecessary */ if (mss != tcp_skb_seglen(prev)) goto fallback; } else { if (!after(TCP_SKB_CB(skb)->end_seq, start_seq)) goto noop; /* CHECKME: This is non-MSS split case only?, this will * cause skipped skbs due to advancing loop btw, original * has that feature too */ if (tcp_skb_pcount(skb) <= 1) goto noop; in_sack = !after(start_seq, TCP_SKB_CB(skb)->seq); if (!in_sack) { /* TODO: head merge to next could be attempted here * if (!after(TCP_SKB_CB(skb)->end_seq, end_seq)), * though it might not be worth of the additional hassle * * ...we can probably just fallback to what was done * previously. We could try merging non-SACKed ones * as well but it probably isn't going to buy off * because later SACKs might again split them, and * it would make skb timestamp tracking considerably * harder problem. */ goto fallback; } len = end_seq - TCP_SKB_CB(skb)->seq; BUG_ON(len < 0); BUG_ON(len > skb->len); /* MSS boundaries should be honoured or else pcount will * severely break even though it makes things bit trickier. * Optimize common case to avoid most of the divides */ mss = tcp_skb_mss(skb); /* TODO: Fix DSACKs to not fragment already SACKed and we can * drop this restriction as unnecessary */ if (mss != tcp_skb_seglen(prev)) goto fallback; if (len == mss) { pcount = 1; } else if (len < mss) { goto noop; } else { pcount = len / mss; len = pcount * mss; } } /* tcp_sacktag_one() won't SACK-tag ranges below snd_una */ if (!after(TCP_SKB_CB(skb)->seq + len, tp->snd_una)) goto fallback; if (!skb_shift(prev, skb, len)) goto fallback; if (!tcp_shifted_skb(sk, skb, state, pcount, len, mss, dup_sack)) goto out; /* Hole filled allows collapsing with the next as well, this is very * useful when hole on every nth skb pattern happens */ if (prev == tcp_write_queue_tail(sk)) goto out; skb = tcp_write_queue_next(sk, prev); if (!skb_can_shift(skb) || (skb == tcp_send_head(sk)) || ((TCP_SKB_CB(skb)->sacked & TCPCB_TAGBITS) != TCPCB_SACKED_ACKED) || (mss != tcp_skb_seglen(skb))) goto out; len = skb->len; if (skb_shift(prev, skb, len)) { pcount += tcp_skb_pcount(skb); tcp_shifted_skb(sk, skb, state, tcp_skb_pcount(skb), len, mss, 0); } out: state->fack_count += pcount; return prev; noop: return skb; fallback: NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_SACKSHIFTFALLBACK); return NULL; } static struct sk_buff *tcp_sacktag_walk(struct sk_buff *skb, struct sock *sk, struct tcp_sack_block *next_dup, struct tcp_sacktag_state *state, u32 start_seq, u32 end_seq, bool dup_sack_in) { struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *tmp; tcp_for_write_queue_from(skb, sk) { int in_sack = 0; bool dup_sack = dup_sack_in; if (skb == tcp_send_head(sk)) break; /* queue is in-order => we can short-circuit the walk early */ if (!before(TCP_SKB_CB(skb)->seq, end_seq)) break; if ((next_dup != NULL) && before(TCP_SKB_CB(skb)->seq, next_dup->end_seq)) { in_sack = tcp_match_skb_to_sack(sk, skb, next_dup->start_seq, next_dup->end_seq); if (in_sack > 0) dup_sack = true; } /* skb reference here is a bit tricky to get right, since * shifting can eat and free both this skb and the next, * so not even _safe variant of the loop is enough. */ if (in_sack <= 0) { tmp = tcp_shift_skb_data(sk, skb, state, start_seq, end_seq, dup_sack); if (tmp != NULL) { if (tmp != skb) { skb = tmp; continue; } in_sack = 0; } else { in_sack = tcp_match_skb_to_sack(sk, skb, start_seq, end_seq); } } if (unlikely(in_sack < 0)) break; if (in_sack) { TCP_SKB_CB(skb)->sacked = tcp_sacktag_one(sk, state, TCP_SKB_CB(skb)->sacked, TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb)->end_seq, dup_sack, tcp_skb_pcount(skb)); if (!before(TCP_SKB_CB(skb)->seq, tcp_highest_sack_seq(tp))) tcp_advance_highest_sack(sk, skb); } state->fack_count += tcp_skb_pcount(skb); } return skb; } /* Avoid all extra work that is being done by sacktag while walking in * a normal way */ static struct sk_buff *tcp_sacktag_skip(struct sk_buff *skb, struct sock *sk, struct tcp_sacktag_state *state, u32 skip_to_seq) { tcp_for_write_queue_from(skb, sk) { if (skb == tcp_send_head(sk)) break; if (after(TCP_SKB_CB(skb)->end_seq, skip_to_seq)) break; state->fack_count += tcp_skb_pcount(skb); } return skb; } static struct sk_buff *tcp_maybe_skipping_dsack(struct sk_buff *skb, struct sock *sk, struct tcp_sack_block *next_dup, struct tcp_sacktag_state *state, u32 skip_to_seq) { if (next_dup == NULL) return skb; if (before(next_dup->start_seq, skip_to_seq)) { skb = tcp_sacktag_skip(skb, sk, state, next_dup->start_seq); skb = tcp_sacktag_walk(skb, sk, NULL, state, next_dup->start_seq, next_dup->end_seq, 1); } return skb; } static int tcp_sack_cache_ok(const struct tcp_sock *tp, const struct tcp_sack_block *cache) { return cache < tp->recv_sack_cache + ARRAY_SIZE(tp->recv_sack_cache); } static int tcp_sacktag_write_queue(struct sock *sk, const struct sk_buff *ack_skb, u32 prior_snd_una) { struct tcp_sock *tp = tcp_sk(sk); const unsigned char *ptr = (skb_transport_header(ack_skb) + TCP_SKB_CB(ack_skb)->sacked); struct tcp_sack_block_wire *sp_wire = (struct tcp_sack_block_wire *)(ptr+2); struct tcp_sack_block sp[TCP_NUM_SACKS]; struct tcp_sack_block *cache; struct tcp_sacktag_state state; struct sk_buff *skb; int num_sacks = min(TCP_NUM_SACKS, (ptr[1] - TCPOLEN_SACK_BASE) >> 3); int used_sacks; bool found_dup_sack = false; int i, j; int first_sack_index; state.flag = 0; state.reord = tp->packets_out; if (!tp->sacked_out) { if (WARN_ON(tp->fackets_out)) tp->fackets_out = 0; tcp_highest_sack_reset(sk); } found_dup_sack = tcp_check_dsack(sk, ack_skb, sp_wire, num_sacks, prior_snd_una); if (found_dup_sack) state.flag |= FLAG_DSACKING_ACK; /* Eliminate too old ACKs, but take into * account more or less fresh ones, they can * contain valid SACK info. */ if (before(TCP_SKB_CB(ack_skb)->ack_seq, prior_snd_una - tp->max_window)) return 0; if (!tp->packets_out) goto out; used_sacks = 0; first_sack_index = 0; for (i = 0; i < num_sacks; i++) { bool dup_sack = !i && found_dup_sack; sp[used_sacks].start_seq = get_unaligned_be32(&sp_wire[i].start_seq); sp[used_sacks].end_seq = get_unaligned_be32(&sp_wire[i].end_seq); if (!tcp_is_sackblock_valid(tp, dup_sack, sp[used_sacks].start_seq, sp[used_sacks].end_seq)) { int mib_idx; if (dup_sack) { if (!tp->undo_marker) mib_idx = LINUX_MIB_TCPDSACKIGNOREDNOUNDO; else mib_idx = LINUX_MIB_TCPDSACKIGNOREDOLD; } else { /* Don't count olds caused by ACK reordering */ if ((TCP_SKB_CB(ack_skb)->ack_seq != tp->snd_una) && !after(sp[used_sacks].end_seq, tp->snd_una)) continue; mib_idx = LINUX_MIB_TCPSACKDISCARD; } NET_INC_STATS_BH(sock_net(sk), mib_idx); if (i == 0) first_sack_index = -1; continue; } /* Ignore very old stuff early */ if (!after(sp[used_sacks].end_seq, prior_snd_una)) continue; used_sacks++; } /* order SACK blocks to allow in order walk of the retrans queue */ for (i = used_sacks - 1; i > 0; i--) { for (j = 0; j < i; j++) { if (after(sp[j].start_seq, sp[j + 1].start_seq)) { swap(sp[j], sp[j + 1]); /* Track where the first SACK block goes to */ if (j == first_sack_index) first_sack_index = j + 1; } } } skb = tcp_write_queue_head(sk); state.fack_count = 0; i = 0; if (!tp->sacked_out) { /* It's already past, so skip checking against it */ cache = tp->recv_sack_cache + ARRAY_SIZE(tp->recv_sack_cache); } else { cache = tp->recv_sack_cache; /* Skip empty blocks in at head of the cache */ while (tcp_sack_cache_ok(tp, cache) && !cache->start_seq && !cache->end_seq) cache++; } while (i < used_sacks) { u32 start_seq = sp[i].start_seq; u32 end_seq = sp[i].end_seq; bool dup_sack = (found_dup_sack && (i == first_sack_index)); struct tcp_sack_block *next_dup = NULL; if (found_dup_sack && ((i + 1) == first_sack_index)) next_dup = &sp[i + 1]; /* Skip too early cached blocks */ while (tcp_sack_cache_ok(tp, cache) && !before(start_seq, cache->end_seq)) cache++; /* Can skip some work by looking recv_sack_cache? */ if (tcp_sack_cache_ok(tp, cache) && !dup_sack && after(end_seq, cache->start_seq)) { /* Head todo? */ if (before(start_seq, cache->start_seq)) { skb = tcp_sacktag_skip(skb, sk, &state, start_seq); skb = tcp_sacktag_walk(skb, sk, next_dup, &state, start_seq, cache->start_seq, dup_sack); } /* Rest of the block already fully processed? */ if (!after(end_seq, cache->end_seq)) goto advance_sp; skb = tcp_maybe_skipping_dsack(skb, sk, next_dup, &state, cache->end_seq); /* ...tail remains todo... */ if (tcp_highest_sack_seq(tp) == cache->end_seq) { /* ...but better entrypoint exists! */ skb = tcp_highest_sack(sk); if (skb == NULL) break; state.fack_count = tp->fackets_out; cache++; goto walk; } skb = tcp_sacktag_skip(skb, sk, &state, cache->end_seq); /* Check overlap against next cached too (past this one already) */ cache++; continue; } if (!before(start_seq, tcp_highest_sack_seq(tp))) { skb = tcp_highest_sack(sk); if (skb == NULL) break; state.fack_count = tp->fackets_out; } skb = tcp_sacktag_skip(skb, sk, &state, start_seq); walk: skb = tcp_sacktag_walk(skb, sk, next_dup, &state, start_seq, end_seq, dup_sack); advance_sp: i++; } /* Clear the head of the cache sack blocks so we can skip it next time */ for (i = 0; i < ARRAY_SIZE(tp->recv_sack_cache) - used_sacks; i++) { tp->recv_sack_cache[i].start_seq = 0; tp->recv_sack_cache[i].end_seq = 0; } for (j = 0; j < used_sacks; j++) tp->recv_sack_cache[i++] = sp[j]; tcp_mark_lost_retrans(sk); tcp_verify_left_out(tp); if ((state.reord < tp->fackets_out) && ((inet_csk(sk)->icsk_ca_state != TCP_CA_Loss) || tp->undo_marker)) tcp_update_reordering(sk, tp->fackets_out - state.reord, 0); out: #if FASTRETRANS_DEBUG > 0 WARN_ON((int)tp->sacked_out < 0); WARN_ON((int)tp->lost_out < 0); WARN_ON((int)tp->retrans_out < 0); WARN_ON((int)tcp_packets_in_flight(tp) < 0); #endif return state.flag; } /* Limits sacked_out so that sum with lost_out isn't ever larger than * packets_out. Returns false if sacked_out adjustement wasn't necessary. */ static bool tcp_limit_reno_sacked(struct tcp_sock *tp) { u32 holes; holes = max(tp->lost_out, 1U); holes = min(holes, tp->packets_out); if ((tp->sacked_out + holes) > tp->packets_out) { tp->sacked_out = tp->packets_out - holes; return true; } return false; } /* If we receive more dupacks than we expected counting segments * in assumption of absent reordering, interpret this as reordering. * The only another reason could be bug in receiver TCP. */ static void tcp_check_reno_reordering(struct sock *sk, const int addend) { struct tcp_sock *tp = tcp_sk(sk); if (tcp_limit_reno_sacked(tp)) tcp_update_reordering(sk, tp->packets_out + addend, 0); } /* Emulate SACKs for SACKless connection: account for a new dupack. */ static void tcp_add_reno_sack(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); tp->sacked_out++; tcp_check_reno_reordering(sk, 0); tcp_verify_left_out(tp); } /* Account for ACK, ACKing some data in Reno Recovery phase. */ static void tcp_remove_reno_sacks(struct sock *sk, int acked) { struct tcp_sock *tp = tcp_sk(sk); if (acked > 0) { /* One ACK acked hole. The rest eat duplicate ACKs. */ if (acked - 1 >= tp->sacked_out) tp->sacked_out = 0; else tp->sacked_out -= acked - 1; } tcp_check_reno_reordering(sk, acked); tcp_verify_left_out(tp); } static inline void tcp_reset_reno_sack(struct tcp_sock *tp) { tp->sacked_out = 0; } static void tcp_clear_retrans_partial(struct tcp_sock *tp) { tp->retrans_out = 0; tp->lost_out = 0; tp->undo_marker = 0; tp->undo_retrans = 0; } void tcp_clear_retrans(struct tcp_sock *tp) { tcp_clear_retrans_partial(tp); tp->fackets_out = 0; tp->sacked_out = 0; } /* Enter Loss state. If "how" is not zero, forget all SACK information * and reset tags completely, otherwise preserve SACKs. If receiver * dropped its ofo queue, we will know this due to reneging detection. */ void tcp_enter_loss(struct sock *sk, int how) { const struct inet_connection_sock *icsk = inet_csk(sk); struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *skb; bool new_recovery = false; /* Reduce ssthresh if it has not yet been made inside this window. */ if (icsk->icsk_ca_state <= TCP_CA_Disorder || !after(tp->high_seq, tp->snd_una) || (icsk->icsk_ca_state == TCP_CA_Loss && !icsk->icsk_retransmits)) { new_recovery = true; tp->prior_ssthresh = tcp_current_ssthresh(sk); tp->snd_ssthresh = icsk->icsk_ca_ops->ssthresh(sk); tcp_ca_event(sk, CA_EVENT_LOSS); } tp->snd_cwnd = 1; tp->snd_cwnd_cnt = 0; tp->snd_cwnd_stamp = tcp_time_stamp; tcp_clear_retrans_partial(tp); if (tcp_is_reno(tp)) tcp_reset_reno_sack(tp); tp->undo_marker = tp->snd_una; if (how) { tp->sacked_out = 0; tp->fackets_out = 0; } tcp_clear_all_retrans_hints(tp); tcp_for_write_queue(skb, sk) { if (skb == tcp_send_head(sk)) break; if (TCP_SKB_CB(skb)->sacked & TCPCB_RETRANS) tp->undo_marker = 0; TCP_SKB_CB(skb)->sacked &= (~TCPCB_TAGBITS)|TCPCB_SACKED_ACKED; if (!(TCP_SKB_CB(skb)->sacked&TCPCB_SACKED_ACKED) || how) { TCP_SKB_CB(skb)->sacked &= ~TCPCB_SACKED_ACKED; TCP_SKB_CB(skb)->sacked |= TCPCB_LOST; tp->lost_out += tcp_skb_pcount(skb); tp->retransmit_high = TCP_SKB_CB(skb)->end_seq; } } tcp_verify_left_out(tp); tp->reordering = min_t(unsigned int, tp->reordering, sysctl_tcp_reordering); tcp_set_ca_state(sk, TCP_CA_Loss); tp->high_seq = tp->snd_nxt; TCP_ECN_queue_cwr(tp); /* F-RTO RFC5682 sec 3.1 step 1: retransmit SND.UNA if no previous * loss recovery is underway except recurring timeout(s) on * the same SND.UNA (sec 3.2). Disable F-RTO on path MTU probing */ tp->frto = sysctl_tcp_frto && (new_recovery || icsk->icsk_retransmits) && !inet_csk(sk)->icsk_mtup.probe_size; } /* If ACK arrived pointing to a remembered SACK, it means that our * remembered SACKs do not reflect real state of receiver i.e. * receiver _host_ is heavily congested (or buggy). * * Do processing similar to RTO timeout. */ static bool tcp_check_sack_reneging(struct sock *sk, int flag) { if (flag & FLAG_SACK_RENEGING) { struct inet_connection_sock *icsk = inet_csk(sk); NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPSACKRENEGING); tcp_enter_loss(sk, 1); icsk->icsk_retransmits++; tcp_retransmit_skb(sk, tcp_write_queue_head(sk)); inet_csk_reset_xmit_timer(sk, ICSK_TIME_RETRANS, icsk->icsk_rto, TCP_RTO_MAX); return true; } return false; } static inline int tcp_fackets_out(const struct tcp_sock *tp) { return tcp_is_reno(tp) ? tp->sacked_out + 1 : tp->fackets_out; } /* Heurestics to calculate number of duplicate ACKs. There's no dupACKs * counter when SACK is enabled (without SACK, sacked_out is used for * that purpose). * * Instead, with FACK TCP uses fackets_out that includes both SACKed * segments up to the highest received SACK block so far and holes in * between them. * * With reordering, holes may still be in flight, so RFC3517 recovery * uses pure sacked_out (total number of SACKed segments) even though * it violates the RFC that uses duplicate ACKs, often these are equal * but when e.g. out-of-window ACKs or packet duplication occurs, * they differ. Since neither occurs due to loss, TCP should really * ignore them. */ static inline int tcp_dupack_heuristics(const struct tcp_sock *tp) { return tcp_is_fack(tp) ? tp->fackets_out : tp->sacked_out + 1; } static bool tcp_pause_early_retransmit(struct sock *sk, int flag) { struct tcp_sock *tp = tcp_sk(sk); unsigned long delay; /* Delay early retransmit and entering fast recovery for * max(RTT/4, 2msec) unless ack has ECE mark, no RTT samples * available, or RTO is scheduled to fire first. */ if (sysctl_tcp_early_retrans < 2 || sysctl_tcp_early_retrans > 3 || (flag & FLAG_ECE) || !tp->srtt) return false; delay = max_t(unsigned long, (tp->srtt >> 5), msecs_to_jiffies(2)); if (!time_after(inet_csk(sk)->icsk_timeout, (jiffies + delay))) return false; inet_csk_reset_xmit_timer(sk, ICSK_TIME_EARLY_RETRANS, delay, TCP_RTO_MAX); return true; } static inline int tcp_skb_timedout(const struct sock *sk, const struct sk_buff *skb) { return tcp_time_stamp - TCP_SKB_CB(skb)->when > inet_csk(sk)->icsk_rto; } static inline int tcp_head_timedout(const struct sock *sk) { const struct tcp_sock *tp = tcp_sk(sk); return tp->packets_out && tcp_skb_timedout(sk, tcp_write_queue_head(sk)); } /* Linux NewReno/SACK/FACK/ECN state machine. * -------------------------------------- * * "Open" Normal state, no dubious events, fast path. * "Disorder" In all the respects it is "Open", * but requires a bit more attention. It is entered when * we see some SACKs or dupacks. It is split of "Open" * mainly to move some processing from fast path to slow one. * "CWR" CWND was reduced due to some Congestion Notification event. * It can be ECN, ICMP source quench, local device congestion. * "Recovery" CWND was reduced, we are fast-retransmitting. * "Loss" CWND was reduced due to RTO timeout or SACK reneging. * * tcp_fastretrans_alert() is entered: * - each incoming ACK, if state is not "Open" * - when arrived ACK is unusual, namely: * * SACK * * Duplicate ACK. * * ECN ECE. * * Counting packets in flight is pretty simple. * * in_flight = packets_out - left_out + retrans_out * * packets_out is SND.NXT-SND.UNA counted in packets. * * retrans_out is number of retransmitted segments. * * left_out is number of segments left network, but not ACKed yet. * * left_out = sacked_out + lost_out * * sacked_out: Packets, which arrived to receiver out of order * and hence not ACKed. With SACKs this number is simply * amount of SACKed data. Even without SACKs * it is easy to give pretty reliable estimate of this number, * counting duplicate ACKs. * * lost_out: Packets lost by network. TCP has no explicit * "loss notification" feedback from network (for now). * It means that this number can be only _guessed_. * Actually, it is the heuristics to predict lossage that * distinguishes different algorithms. * * F.e. after RTO, when all the queue is considered as lost, * lost_out = packets_out and in_flight = retrans_out. * * Essentially, we have now two algorithms counting * lost packets. * * FACK: It is the simplest heuristics. As soon as we decided * that something is lost, we decide that _all_ not SACKed * packets until the most forward SACK are lost. I.e. * lost_out = fackets_out - sacked_out and left_out = fackets_out. * It is absolutely correct estimate, if network does not reorder * packets. And it loses any connection to reality when reordering * takes place. We use FACK by default until reordering * is suspected on the path to this destination. * * NewReno: when Recovery is entered, we assume that one segment * is lost (classic Reno). While we are in Recovery and * a partial ACK arrives, we assume that one more packet * is lost (NewReno). This heuristics are the same in NewReno * and SACK. * * Imagine, that's all! Forget about all this shamanism about CWND inflation * deflation etc. CWND is real congestion window, never inflated, changes * only according to classic VJ rules. * * Really tricky (and requiring careful tuning) part of algorithm * is hidden in functions tcp_time_to_recover() and tcp_xmit_retransmit_queue(). * The first determines the moment _when_ we should reduce CWND and, * hence, slow down forward transmission. In fact, it determines the moment * when we decide that hole is caused by loss, rather than by a reorder. * * tcp_xmit_retransmit_queue() decides, _what_ we should retransmit to fill * holes, caused by lost packets. * * And the most logically complicated part of algorithm is undo * heuristics. We detect false retransmits due to both too early * fast retransmit (reordering) and underestimated RTO, analyzing * timestamps and D-SACKs. When we detect that some segments were * retransmitted by mistake and CWND reduction was wrong, we undo * window reduction and abort recovery phase. This logic is hidden * inside several functions named tcp_try_undo_<something>. */ /* This function decides, when we should leave Disordered state * and enter Recovery phase, reducing congestion window. * * Main question: may we further continue forward transmission * with the same cwnd? */ static bool tcp_time_to_recover(struct sock *sk, int flag) { struct tcp_sock *tp = tcp_sk(sk); __u32 packets_out; /* Trick#1: The loss is proven. */ if (tp->lost_out) return true; /* Not-A-Trick#2 : Classic rule... */ if (tcp_dupack_heuristics(tp) > tp->reordering) return true; /* Trick#3 : when we use RFC2988 timer restart, fast * retransmit can be triggered by timeout of queue head. */ if (tcp_is_fack(tp) && tcp_head_timedout(sk)) return true; /* Trick#4: It is still not OK... But will it be useful to delay * recovery more? */ packets_out = tp->packets_out; if (packets_out <= tp->reordering && tp->sacked_out >= max_t(__u32, packets_out/2, sysctl_tcp_reordering) && !tcp_may_send_now(sk)) { /* We have nothing to send. This connection is limited * either by receiver window or by application. */ return true; } /* If a thin stream is detected, retransmit after first * received dupack. Employ only if SACK is supported in order * to avoid possible corner-case series of spurious retransmissions * Use only if there are no unsent data. */ if ((tp->thin_dupack || sysctl_tcp_thin_dupack) && tcp_stream_is_thin(tp) && tcp_dupack_heuristics(tp) > 1 && tcp_is_sack(tp) && !tcp_send_head(sk)) return true; /* Trick#6: TCP early retransmit, per RFC5827. To avoid spurious * retransmissions due to small network reorderings, we implement * Mitigation A.3 in the RFC and delay the retransmission for a short * interval if appropriate. */ if (tp->do_early_retrans && !tp->retrans_out && tp->sacked_out && (tp->packets_out >= (tp->sacked_out + 1) && tp->packets_out < 4) && !tcp_may_send_now(sk)) return !tcp_pause_early_retransmit(sk, flag); return false; } /* New heuristics: it is possible only after we switched to restart timer * each time when something is ACKed. Hence, we can detect timed out packets * during fast retransmit without falling to slow start. * * Usefulness of this as is very questionable, since we should know which of * the segments is the next to timeout which is relatively expensive to find * in general case unless we add some data structure just for that. The * current approach certainly won't find the right one too often and when it * finally does find _something_ it usually marks large part of the window * right away (because a retransmission with a larger timestamp blocks the * loop from advancing). -ij */ static void tcp_timeout_skbs(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *skb; if (!tcp_is_fack(tp) || !tcp_head_timedout(sk)) return; skb = tp->scoreboard_skb_hint; if (tp->scoreboard_skb_hint == NULL) skb = tcp_write_queue_head(sk); tcp_for_write_queue_from(skb, sk) { if (skb == tcp_send_head(sk)) break; if (!tcp_skb_timedout(sk, skb)) break; tcp_skb_mark_lost(tp, skb); } tp->scoreboard_skb_hint = skb; tcp_verify_left_out(tp); } /* Detect loss in event "A" above by marking head of queue up as lost. * For FACK or non-SACK(Reno) senders, the first "packets" number of segments * are considered lost. For RFC3517 SACK, a segment is considered lost if it * has at least tp->reordering SACKed seqments above it; "packets" refers to * the maximum SACKed segments to pass before reaching this limit. */ static void tcp_mark_head_lost(struct sock *sk, int packets, int mark_head) { struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *skb; int cnt, oldcnt; int err; unsigned int mss; /* Use SACK to deduce losses of new sequences sent during recovery */ const u32 loss_high = tcp_is_sack(tp) ? tp->snd_nxt : tp->high_seq; WARN_ON(packets > tp->packets_out); if (tp->lost_skb_hint) { skb = tp->lost_skb_hint; cnt = tp->lost_cnt_hint; /* Head already handled? */ if (mark_head && skb != tcp_write_queue_head(sk)) return; } else { skb = tcp_write_queue_head(sk); cnt = 0; } tcp_for_write_queue_from(skb, sk) { if (skb == tcp_send_head(sk)) break; /* TODO: do this better */ /* this is not the most efficient way to do this... */ tp->lost_skb_hint = skb; tp->lost_cnt_hint = cnt; if (after(TCP_SKB_CB(skb)->end_seq, loss_high)) break; oldcnt = cnt; if (tcp_is_fack(tp) || tcp_is_reno(tp) || (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED)) cnt += tcp_skb_pcount(skb); if (cnt > packets) { if ((tcp_is_sack(tp) && !tcp_is_fack(tp)) || (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED) || (oldcnt >= packets)) break; mss = skb_shinfo(skb)->gso_size; err = tcp_fragment(sk, skb, (packets - oldcnt) * mss, mss); if (err < 0) break; cnt = packets; } tcp_skb_mark_lost(tp, skb); if (mark_head) break; } tcp_verify_left_out(tp); } /* Account newly detected lost packet(s) */ static void tcp_update_scoreboard(struct sock *sk, int fast_rexmit) { struct tcp_sock *tp = tcp_sk(sk); if (tcp_is_reno(tp)) { tcp_mark_head_lost(sk, 1, 1); } else if (tcp_is_fack(tp)) { int lost = tp->fackets_out - tp->reordering; if (lost <= 0) lost = 1; tcp_mark_head_lost(sk, lost, 0); } else { int sacked_upto = tp->sacked_out - tp->reordering; if (sacked_upto >= 0) tcp_mark_head_lost(sk, sacked_upto, 0); else if (fast_rexmit) tcp_mark_head_lost(sk, 1, 1); } tcp_timeout_skbs(sk); } /* CWND moderation, preventing bursts due to too big ACKs * in dubious situations. */ static inline void tcp_moderate_cwnd(struct tcp_sock *tp) { tp->snd_cwnd = min(tp->snd_cwnd, tcp_packets_in_flight(tp) + tcp_max_burst(tp)); tp->snd_cwnd_stamp = tcp_time_stamp; } /* Nothing was retransmitted or returned timestamp is less * than timestamp of the first retransmission. */ static inline bool tcp_packet_delayed(const struct tcp_sock *tp) { return !tp->retrans_stamp || (tp->rx_opt.saw_tstamp && tp->rx_opt.rcv_tsecr && before(tp->rx_opt.rcv_tsecr, tp->retrans_stamp)); } /* Undo procedures. */ #if FASTRETRANS_DEBUG > 1 static void DBGUNDO(struct sock *sk, const char *msg) { struct tcp_sock *tp = tcp_sk(sk); struct inet_sock *inet = inet_sk(sk); if (sk->sk_family == AF_INET) { pr_debug("Undo %s %pI4/%u c%u l%u ss%u/%u p%u\n", msg, &inet->inet_daddr, ntohs(inet->inet_dport), tp->snd_cwnd, tcp_left_out(tp), tp->snd_ssthresh, tp->prior_ssthresh, tp->packets_out); } #if IS_ENABLED(CONFIG_IPV6) else if (sk->sk_family == AF_INET6) { struct ipv6_pinfo *np = inet6_sk(sk); pr_debug("Undo %s %pI6/%u c%u l%u ss%u/%u p%u\n", msg, &np->daddr, ntohs(inet->inet_dport), tp->snd_cwnd, tcp_left_out(tp), tp->snd_ssthresh, tp->prior_ssthresh, tp->packets_out); } #endif } #else #define DBGUNDO(x...) do { } while (0) #endif static void tcp_undo_cwr(struct sock *sk, const bool undo_ssthresh) { struct tcp_sock *tp = tcp_sk(sk); if (tp->prior_ssthresh) { const struct inet_connection_sock *icsk = inet_csk(sk); if (icsk->icsk_ca_ops->undo_cwnd) tp->snd_cwnd = icsk->icsk_ca_ops->undo_cwnd(sk); else tp->snd_cwnd = max(tp->snd_cwnd, tp->snd_ssthresh << 1); if (undo_ssthresh && tp->prior_ssthresh > tp->snd_ssthresh) { tp->snd_ssthresh = tp->prior_ssthresh; TCP_ECN_withdraw_cwr(tp); } } else { tp->snd_cwnd = max(tp->snd_cwnd, tp->snd_ssthresh); } tp->snd_cwnd_stamp = tcp_time_stamp; } static inline bool tcp_may_undo(const struct tcp_sock *tp) { return tp->undo_marker && (!tp->undo_retrans || tcp_packet_delayed(tp)); } /* People celebrate: "We love our President!" */ static bool tcp_try_undo_recovery(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); if (tcp_may_undo(tp)) { int mib_idx; /* Happy end! We did not retransmit anything * or our original transmission succeeded. */ DBGUNDO(sk, inet_csk(sk)->icsk_ca_state == TCP_CA_Loss ? "loss" : "retrans"); tcp_undo_cwr(sk, true); if (inet_csk(sk)->icsk_ca_state == TCP_CA_Loss) mib_idx = LINUX_MIB_TCPLOSSUNDO; else mib_idx = LINUX_MIB_TCPFULLUNDO; NET_INC_STATS_BH(sock_net(sk), mib_idx); tp->undo_marker = 0; } if (tp->snd_una == tp->high_seq && tcp_is_reno(tp)) { /* Hold old state until something *above* high_seq * is ACKed. For Reno it is MUST to prevent false * fast retransmits (RFC2582). SACK TCP is safe. */ tcp_moderate_cwnd(tp); return true; } tcp_set_ca_state(sk, TCP_CA_Open); return false; } /* Try to undo cwnd reduction, because D-SACKs acked all retransmitted data */ static void tcp_try_undo_dsack(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); if (tp->undo_marker && !tp->undo_retrans) { DBGUNDO(sk, "D-SACK"); tcp_undo_cwr(sk, true); tp->undo_marker = 0; NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPDSACKUNDO); } } /* We can clear retrans_stamp when there are no retransmissions in the * window. It would seem that it is trivially available for us in * tp->retrans_out, however, that kind of assumptions doesn't consider * what will happen if errors occur when sending retransmission for the * second time. ...It could the that such segment has only * TCPCB_EVER_RETRANS set at the present time. It seems that checking * the head skb is enough except for some reneging corner cases that * are not worth the effort. * * Main reason for all this complexity is the fact that connection dying * time now depends on the validity of the retrans_stamp, in particular, * that successive retransmissions of a segment must not advance * retrans_stamp under any conditions. */ static bool tcp_any_retrans_done(const struct sock *sk) { const struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *skb; if (tp->retrans_out) return true; skb = tcp_write_queue_head(sk); if (unlikely(skb && TCP_SKB_CB(skb)->sacked & TCPCB_EVER_RETRANS)) return true; return false; } /* Undo during fast recovery after partial ACK. */ static int tcp_try_undo_partial(struct sock *sk, int acked) { struct tcp_sock *tp = tcp_sk(sk); /* Partial ACK arrived. Force Hoe's retransmit. */ int failed = tcp_is_reno(tp) || (tcp_fackets_out(tp) > tp->reordering); if (tcp_may_undo(tp)) { /* Plain luck! Hole if filled with delayed * packet, rather than with a retransmit. */ if (!tcp_any_retrans_done(sk)) tp->retrans_stamp = 0; tcp_update_reordering(sk, tcp_fackets_out(tp) + acked, 1); DBGUNDO(sk, "Hoe"); tcp_undo_cwr(sk, false); NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPPARTIALUNDO); /* So... Do not make Hoe's retransmit yet. * If the first packet was delayed, the rest * ones are most probably delayed as well. */ failed = 0; } return failed; } /* Undo during loss recovery after partial ACK or using F-RTO. */ static bool tcp_try_undo_loss(struct sock *sk, bool frto_undo) { struct tcp_sock *tp = tcp_sk(sk); if (frto_undo || tcp_may_undo(tp)) { struct sk_buff *skb; tcp_for_write_queue(skb, sk) { if (skb == tcp_send_head(sk)) break; TCP_SKB_CB(skb)->sacked &= ~TCPCB_LOST; } tcp_clear_all_retrans_hints(tp); DBGUNDO(sk, "partial loss"); tp->lost_out = 0; tcp_undo_cwr(sk, true); NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPLOSSUNDO); if (frto_undo) NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPSPURIOUSRTOS); inet_csk(sk)->icsk_retransmits = 0; tp->undo_marker = 0; if (frto_undo || tcp_is_sack(tp)) tcp_set_ca_state(sk, TCP_CA_Open); return true; } return false; } /* The cwnd reduction in CWR and Recovery use the PRR algorithm * https://datatracker.ietf.org/doc/draft-ietf-tcpm-proportional-rate-reduction/ * It computes the number of packets to send (sndcnt) based on packets newly * delivered: * 1) If the packets in flight is larger than ssthresh, PRR spreads the * cwnd reductions across a full RTT. * 2) If packets in flight is lower than ssthresh (such as due to excess * losses and/or application stalls), do not perform any further cwnd * reductions, but instead slow start up to ssthresh. */ static void tcp_init_cwnd_reduction(struct sock *sk, const bool set_ssthresh) { struct tcp_sock *tp = tcp_sk(sk); tp->high_seq = tp->snd_nxt; tp->tlp_high_seq = 0; tp->snd_cwnd_cnt = 0; tp->prior_cwnd = tp->snd_cwnd; tp->prr_delivered = 0; tp->prr_out = 0; if (set_ssthresh) tp->snd_ssthresh = inet_csk(sk)->icsk_ca_ops->ssthresh(sk); TCP_ECN_queue_cwr(tp); } static void tcp_cwnd_reduction(struct sock *sk, int newly_acked_sacked, int fast_rexmit) { struct tcp_sock *tp = tcp_sk(sk); int sndcnt = 0; int delta = tp->snd_ssthresh - tcp_packets_in_flight(tp); tp->prr_delivered += newly_acked_sacked; if (tcp_packets_in_flight(tp) > tp->snd_ssthresh) { u64 dividend = (u64)tp->snd_ssthresh * tp->prr_delivered + tp->prior_cwnd - 1; sndcnt = div_u64(dividend, tp->prior_cwnd) - tp->prr_out; } else { sndcnt = min_t(int, delta, max_t(int, tp->prr_delivered - tp->prr_out, newly_acked_sacked) + 1); } sndcnt = max(sndcnt, (fast_rexmit ? 1 : 0)); tp->snd_cwnd = tcp_packets_in_flight(tp) + sndcnt; } static inline void tcp_end_cwnd_reduction(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); /* Reset cwnd to ssthresh in CWR or Recovery (unless it's undone) */ if (inet_csk(sk)->icsk_ca_state == TCP_CA_CWR || (tp->undo_marker && tp->snd_ssthresh < TCP_INFINITE_SSTHRESH)) { tp->snd_cwnd = tp->snd_ssthresh; tp->snd_cwnd_stamp = tcp_time_stamp; } tcp_ca_event(sk, CA_EVENT_COMPLETE_CWR); } /* Enter CWR state. Disable cwnd undo since congestion is proven with ECN */ void tcp_enter_cwr(struct sock *sk, const int set_ssthresh) { struct tcp_sock *tp = tcp_sk(sk); tp->prior_ssthresh = 0; if (inet_csk(sk)->icsk_ca_state < TCP_CA_CWR) { tp->undo_marker = 0; tcp_init_cwnd_reduction(sk, set_ssthresh); tcp_set_ca_state(sk, TCP_CA_CWR); } } static void tcp_try_keep_open(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); int state = TCP_CA_Open; if (tcp_left_out(tp) || tcp_any_retrans_done(sk)) state = TCP_CA_Disorder; if (inet_csk(sk)->icsk_ca_state != state) { tcp_set_ca_state(sk, state); tp->high_seq = tp->snd_nxt; } } static void tcp_try_to_open(struct sock *sk, int flag, int newly_acked_sacked) { struct tcp_sock *tp = tcp_sk(sk); tcp_verify_left_out(tp); if (!tcp_any_retrans_done(sk)) tp->retrans_stamp = 0; if (flag & FLAG_ECE) tcp_enter_cwr(sk, 1); if (inet_csk(sk)->icsk_ca_state != TCP_CA_CWR) { tcp_try_keep_open(sk); if (inet_csk(sk)->icsk_ca_state != TCP_CA_Open) tcp_moderate_cwnd(tp); } else { tcp_cwnd_reduction(sk, newly_acked_sacked, 0); } } static void tcp_mtup_probe_failed(struct sock *sk) { struct inet_connection_sock *icsk = inet_csk(sk); icsk->icsk_mtup.search_high = icsk->icsk_mtup.probe_size - 1; icsk->icsk_mtup.probe_size = 0; } static void tcp_mtup_probe_success(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); struct inet_connection_sock *icsk = inet_csk(sk); /* FIXME: breaks with very large cwnd */ tp->prior_ssthresh = tcp_current_ssthresh(sk); tp->snd_cwnd = tp->snd_cwnd * tcp_mss_to_mtu(sk, tp->mss_cache) / icsk->icsk_mtup.probe_size; tp->snd_cwnd_cnt = 0; tp->snd_cwnd_stamp = tcp_time_stamp; tp->snd_ssthresh = tcp_current_ssthresh(sk); icsk->icsk_mtup.search_low = icsk->icsk_mtup.probe_size; icsk->icsk_mtup.probe_size = 0; tcp_sync_mss(sk, icsk->icsk_pmtu_cookie); } /* Do a simple retransmit without using the backoff mechanisms in * tcp_timer. This is used for path mtu discovery. * The socket is already locked here. */ void tcp_simple_retransmit(struct sock *sk) { const struct inet_connection_sock *icsk = inet_csk(sk); struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *skb; unsigned int mss = tcp_current_mss(sk); u32 prior_lost = tp->lost_out; tcp_for_write_queue(skb, sk) { if (skb == tcp_send_head(sk)) break; if (tcp_skb_seglen(skb) > mss && !(TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED)) { if (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_RETRANS) { TCP_SKB_CB(skb)->sacked &= ~TCPCB_SACKED_RETRANS; tp->retrans_out -= tcp_skb_pcount(skb); } tcp_skb_mark_lost_uncond_verify(tp, skb); } } tcp_clear_retrans_hints_partial(tp); if (prior_lost == tp->lost_out) return; if (tcp_is_reno(tp)) tcp_limit_reno_sacked(tp); tcp_verify_left_out(tp); /* Don't muck with the congestion window here. * Reason is that we do not increase amount of _data_ * in network, but units changed and effective * cwnd/ssthresh really reduced now. */ if (icsk->icsk_ca_state != TCP_CA_Loss) { tp->high_seq = tp->snd_nxt; tp->snd_ssthresh = tcp_current_ssthresh(sk); tp->prior_ssthresh = 0; tp->undo_marker = 0; tcp_set_ca_state(sk, TCP_CA_Loss); } tcp_xmit_retransmit_queue(sk); } EXPORT_SYMBOL(tcp_simple_retransmit); static void tcp_enter_recovery(struct sock *sk, bool ece_ack) { struct tcp_sock *tp = tcp_sk(sk); int mib_idx; if (tcp_is_reno(tp)) mib_idx = LINUX_MIB_TCPRENORECOVERY; else mib_idx = LINUX_MIB_TCPSACKRECOVERY; NET_INC_STATS_BH(sock_net(sk), mib_idx); tp->prior_ssthresh = 0; tp->undo_marker = tp->snd_una; tp->undo_retrans = tp->retrans_out; if (inet_csk(sk)->icsk_ca_state < TCP_CA_CWR) { if (!ece_ack) tp->prior_ssthresh = tcp_current_ssthresh(sk); tcp_init_cwnd_reduction(sk, true); } tcp_set_ca_state(sk, TCP_CA_Recovery); } /* Process an ACK in CA_Loss state. Move to CA_Open if lost data are * recovered or spurious. Otherwise retransmits more on partial ACKs. */ static void tcp_process_loss(struct sock *sk, int flag, bool is_dupack) { struct inet_connection_sock *icsk = inet_csk(sk); struct tcp_sock *tp = tcp_sk(sk); bool recovered = !before(tp->snd_una, tp->high_seq); if (tp->frto) { /* F-RTO RFC5682 sec 3.1 (sack enhanced version). */ /* Step 3.b. A timeout is spurious if not all data are * lost, i.e., never-retransmitted data are (s)acked. */ if (tcp_try_undo_loss(sk, flag & FLAG_ORIG_SACK_ACKED)) return; if (after(tp->snd_nxt, tp->high_seq) && (flag & FLAG_DATA_SACKED || is_dupack)) { tp->frto = 0; /* Loss was real: 2nd part of step 3.a */ } else if (flag & FLAG_SND_UNA_ADVANCED && !recovered) { tp->high_seq = tp->snd_nxt; __tcp_push_pending_frames(sk, tcp_current_mss(sk), TCP_NAGLE_OFF); if (after(tp->snd_nxt, tp->high_seq)) return; /* Step 2.b */ tp->frto = 0; } } if (recovered) { /* F-RTO RFC5682 sec 3.1 step 2.a and 1st part of step 3.a */ icsk->icsk_retransmits = 0; tcp_try_undo_recovery(sk); return; } if (flag & FLAG_DATA_ACKED) icsk->icsk_retransmits = 0; if (tcp_is_reno(tp)) { /* A Reno DUPACK means new data in F-RTO step 2.b above are * delivered. Lower inflight to clock out (re)tranmissions. */ if (after(tp->snd_nxt, tp->high_seq) && is_dupack) tcp_add_reno_sack(sk); else if (flag & FLAG_SND_UNA_ADVANCED) tcp_reset_reno_sack(tp); } if (tcp_try_undo_loss(sk, false)) return; tcp_xmit_retransmit_queue(sk); } /* Process an event, which can update packets-in-flight not trivially. * Main goal of this function is to calculate new estimate for left_out, * taking into account both packets sitting in receiver's buffer and * packets lost by network. * * Besides that it does CWND reduction, when packet loss is detected * and changes state of machine. * * It does _not_ decide what to send, it is made in function * tcp_xmit_retransmit_queue(). */ static void tcp_fastretrans_alert(struct sock *sk, int pkts_acked, int prior_sacked, int prior_packets, bool is_dupack, int flag) { struct inet_connection_sock *icsk = inet_csk(sk); struct tcp_sock *tp = tcp_sk(sk); int do_lost = is_dupack || ((flag & FLAG_DATA_SACKED) && (tcp_fackets_out(tp) > tp->reordering)); int newly_acked_sacked = 0; int fast_rexmit = 0; if (WARN_ON(!tp->packets_out && tp->sacked_out)) tp->sacked_out = 0; if (WARN_ON(!tp->sacked_out && tp->fackets_out)) tp->fackets_out = 0; /* Now state machine starts. * A. ECE, hence prohibit cwnd undoing, the reduction is required. */ if (flag & FLAG_ECE) tp->prior_ssthresh = 0; /* B. In all the states check for reneging SACKs. */ if (tcp_check_sack_reneging(sk, flag)) return; /* C. Check consistency of the current state. */ tcp_verify_left_out(tp); /* D. Check state exit conditions. State can be terminated * when high_seq is ACKed. */ if (icsk->icsk_ca_state == TCP_CA_Open) { WARN_ON(tp->retrans_out != 0); tp->retrans_stamp = 0; } else if (!before(tp->snd_una, tp->high_seq)) { switch (icsk->icsk_ca_state) { case TCP_CA_CWR: /* CWR is to be held something *above* high_seq * is ACKed for CWR bit to reach receiver. */ if (tp->snd_una != tp->high_seq) { tcp_end_cwnd_reduction(sk); tcp_set_ca_state(sk, TCP_CA_Open); } break; case TCP_CA_Recovery: if (tcp_is_reno(tp)) tcp_reset_reno_sack(tp); if (tcp_try_undo_recovery(sk)) return; tcp_end_cwnd_reduction(sk); break; } } /* E. Process state. */ switch (icsk->icsk_ca_state) { case TCP_CA_Recovery: if (!(flag & FLAG_SND_UNA_ADVANCED)) { if (tcp_is_reno(tp) && is_dupack) tcp_add_reno_sack(sk); } else do_lost = tcp_try_undo_partial(sk, pkts_acked); newly_acked_sacked = prior_packets - tp->packets_out + tp->sacked_out - prior_sacked; break; case TCP_CA_Loss: tcp_process_loss(sk, flag, is_dupack); if (icsk->icsk_ca_state != TCP_CA_Open) return; /* Fall through to processing in Open state. */ default: if (tcp_is_reno(tp)) { if (flag & FLAG_SND_UNA_ADVANCED) tcp_reset_reno_sack(tp); if (is_dupack) tcp_add_reno_sack(sk); } newly_acked_sacked = prior_packets - tp->packets_out + tp->sacked_out - prior_sacked; if (icsk->icsk_ca_state <= TCP_CA_Disorder) tcp_try_undo_dsack(sk); if (!tcp_time_to_recover(sk, flag)) { tcp_try_to_open(sk, flag, newly_acked_sacked); return; } /* MTU probe failure: don't reduce cwnd */ if (icsk->icsk_ca_state < TCP_CA_CWR && icsk->icsk_mtup.probe_size && tp->snd_una == tp->mtu_probe.probe_seq_start) { tcp_mtup_probe_failed(sk); /* Restores the reduction we did in tcp_mtup_probe() */ tp->snd_cwnd++; tcp_simple_retransmit(sk); return; } /* Otherwise enter Recovery state */ tcp_enter_recovery(sk, (flag & FLAG_ECE)); fast_rexmit = 1; } if (do_lost || (tcp_is_fack(tp) && tcp_head_timedout(sk))) tcp_update_scoreboard(sk, fast_rexmit); tcp_cwnd_reduction(sk, newly_acked_sacked, fast_rexmit); tcp_xmit_retransmit_queue(sk); } void tcp_valid_rtt_meas(struct sock *sk, u32 seq_rtt) { tcp_rtt_estimator(sk, seq_rtt); tcp_set_rto(sk); inet_csk(sk)->icsk_backoff = 0; } EXPORT_SYMBOL(tcp_valid_rtt_meas); /* Read draft-ietf-tcplw-high-performance before mucking * with this code. (Supersedes RFC1323) */ static void tcp_ack_saw_tstamp(struct sock *sk, int flag) { /* RTTM Rule: A TSecr value received in a segment is used to * update the averaged RTT measurement only if the segment * acknowledges some new data, i.e., only if it advances the * left edge of the send window. * * See draft-ietf-tcplw-high-performance-00, section 3.3. * 1998/04/10 Andrey V. Savochkin <saw@msu.ru> * * Changed: reset backoff as soon as we see the first valid sample. * If we do not, we get strongly overestimated rto. With timestamps * samples are accepted even from very old segments: f.e., when rtt=1 * increases to 8, we retransmit 5 times and after 8 seconds delayed * answer arrives rto becomes 120 seconds! If at least one of segments * in window is lost... Voila. --ANK (010210) */ struct tcp_sock *tp = tcp_sk(sk); tcp_valid_rtt_meas(sk, tcp_time_stamp - tp->rx_opt.rcv_tsecr); } static void tcp_ack_no_tstamp(struct sock *sk, u32 seq_rtt, int flag) { /* We don't have a timestamp. Can only use * packets that are not retransmitted to determine * rtt estimates. Also, we must not reset the * backoff for rto until we get a non-retransmitted * packet. This allows us to deal with a situation * where the network delay has increased suddenly. * I.e. Karn's algorithm. (SIGCOMM '87, p5.) */ if (flag & FLAG_RETRANS_DATA_ACKED) return; tcp_valid_rtt_meas(sk, seq_rtt); } static inline void tcp_ack_update_rtt(struct sock *sk, const int flag, const s32 seq_rtt) { const struct tcp_sock *tp = tcp_sk(sk); /* Note that peer MAY send zero echo. In this case it is ignored. (rfc1323) */ if (tp->rx_opt.saw_tstamp && tp->rx_opt.rcv_tsecr) tcp_ack_saw_tstamp(sk, flag); else if (seq_rtt >= 0) tcp_ack_no_tstamp(sk, seq_rtt, flag); } static void tcp_cong_avoid(struct sock *sk, u32 ack, u32 in_flight) { const struct inet_connection_sock *icsk = inet_csk(sk); icsk->icsk_ca_ops->cong_avoid(sk, ack, in_flight); tcp_sk(sk)->snd_cwnd_stamp = tcp_time_stamp; } /* Restart timer after forward progress on connection. * RFC2988 recommends to restart timer to now+rto. */ void tcp_rearm_rto(struct sock *sk) { const struct inet_connection_sock *icsk = inet_csk(sk); struct tcp_sock *tp = tcp_sk(sk); /* If the retrans timer is currently being used by Fast Open * for SYN-ACK retrans purpose, stay put. */ if (tp->fastopen_rsk) return; if (!tp->packets_out) { inet_csk_clear_xmit_timer(sk, ICSK_TIME_RETRANS); } else { u32 rto = inet_csk(sk)->icsk_rto; /* Offset the time elapsed after installing regular RTO */ if (icsk->icsk_pending == ICSK_TIME_EARLY_RETRANS || icsk->icsk_pending == ICSK_TIME_LOSS_PROBE) { struct sk_buff *skb = tcp_write_queue_head(sk); const u32 rto_time_stamp = TCP_SKB_CB(skb)->when + rto; s32 delta = (s32)(rto_time_stamp - tcp_time_stamp); /* delta may not be positive if the socket is locked * when the retrans timer fires and is rescheduled. */ if (delta > 0) rto = delta; } inet_csk_reset_xmit_timer(sk, ICSK_TIME_RETRANS, rto, TCP_RTO_MAX); } } /* This function is called when the delayed ER timer fires. TCP enters * fast recovery and performs fast-retransmit. */ void tcp_resume_early_retransmit(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); tcp_rearm_rto(sk); /* Stop if ER is disabled after the delayed ER timer is scheduled */ if (!tp->do_early_retrans) return; tcp_enter_recovery(sk, false); tcp_update_scoreboard(sk, 1); tcp_xmit_retransmit_queue(sk); } /* If we get here, the whole TSO packet has not been acked. */ static u32 tcp_tso_acked(struct sock *sk, struct sk_buff *skb) { struct tcp_sock *tp = tcp_sk(sk); u32 packets_acked; BUG_ON(!after(TCP_SKB_CB(skb)->end_seq, tp->snd_una)); packets_acked = tcp_skb_pcount(skb); if (tcp_trim_head(sk, skb, tp->snd_una - TCP_SKB_CB(skb)->seq)) return 0; packets_acked -= tcp_skb_pcount(skb); if (packets_acked) { BUG_ON(tcp_skb_pcount(skb) == 0); BUG_ON(!before(TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb)->end_seq)); } return packets_acked; } /* Remove acknowledged frames from the retransmission queue. If our packet * is before the ack sequence we can discard it as it's confirmed to have * arrived at the other end. */ static int tcp_clean_rtx_queue(struct sock *sk, int prior_fackets, u32 prior_snd_una) { struct tcp_sock *tp = tcp_sk(sk); const struct inet_connection_sock *icsk = inet_csk(sk); struct sk_buff *skb; u32 now = tcp_time_stamp; int fully_acked = true; int flag = 0; u32 pkts_acked = 0; u32 reord = tp->packets_out; u32 prior_sacked = tp->sacked_out; s32 seq_rtt = -1; s32 ca_seq_rtt = -1; ktime_t last_ackt = net_invalid_timestamp(); while ((skb = tcp_write_queue_head(sk)) && skb != tcp_send_head(sk)) { struct tcp_skb_cb *scb = TCP_SKB_CB(skb); u32 acked_pcount; u8 sacked = scb->sacked; /* Determine how many packets and what bytes were acked, tso and else */ if (after(scb->end_seq, tp->snd_una)) { if (tcp_skb_pcount(skb) == 1 || !after(tp->snd_una, scb->seq)) break; acked_pcount = tcp_tso_acked(sk, skb); if (!acked_pcount) break; fully_acked = false; } else { acked_pcount = tcp_skb_pcount(skb); } if (sacked & TCPCB_RETRANS) { if (sacked & TCPCB_SACKED_RETRANS) tp->retrans_out -= acked_pcount; flag |= FLAG_RETRANS_DATA_ACKED; ca_seq_rtt = -1; seq_rtt = -1; } else { ca_seq_rtt = now - scb->when; last_ackt = skb->tstamp; if (seq_rtt < 0) { seq_rtt = ca_seq_rtt; } if (!(sacked & TCPCB_SACKED_ACKED)) reord = min(pkts_acked, reord); if (!after(scb->end_seq, tp->high_seq)) flag |= FLAG_ORIG_SACK_ACKED; } if (sacked & TCPCB_SACKED_ACKED) tp->sacked_out -= acked_pcount; if (sacked & TCPCB_LOST) tp->lost_out -= acked_pcount; tp->packets_out -= acked_pcount; pkts_acked += acked_pcount; /* Initial outgoing SYN's get put onto the write_queue * just like anything else we transmit. It is not * true data, and if we misinform our callers that * this ACK acks real data, we will erroneously exit * connection startup slow start one packet too * quickly. This is severely frowned upon behavior. */ if (!(scb->tcp_flags & TCPHDR_SYN)) { flag |= FLAG_DATA_ACKED; } else { flag |= FLAG_SYN_ACKED; tp->retrans_stamp = 0; } if (!fully_acked) break; tcp_unlink_write_queue(skb, sk); sk_wmem_free_skb(sk, skb); tp->scoreboard_skb_hint = NULL; if (skb == tp->retransmit_skb_hint) tp->retransmit_skb_hint = NULL; if (skb == tp->lost_skb_hint) tp->lost_skb_hint = NULL; } if (likely(between(tp->snd_up, prior_snd_una, tp->snd_una))) tp->snd_up = tp->snd_una; if (skb && (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED)) flag |= FLAG_SACK_RENEGING; if (flag & FLAG_ACKED) { const struct tcp_congestion_ops *ca_ops = inet_csk(sk)->icsk_ca_ops; if (unlikely(icsk->icsk_mtup.probe_size && !after(tp->mtu_probe.probe_seq_end, tp->snd_una))) { tcp_mtup_probe_success(sk); } tcp_ack_update_rtt(sk, flag, seq_rtt); tcp_rearm_rto(sk); if (tcp_is_reno(tp)) { tcp_remove_reno_sacks(sk, pkts_acked); } else { int delta; /* Non-retransmitted hole got filled? That's reordering */ if (reord < prior_fackets) tcp_update_reordering(sk, tp->fackets_out - reord, 0); delta = tcp_is_fack(tp) ? pkts_acked : prior_sacked - tp->sacked_out; tp->lost_cnt_hint -= min(tp->lost_cnt_hint, delta); } tp->fackets_out -= min(pkts_acked, tp->fackets_out); if (ca_ops->pkts_acked) { s32 rtt_us = -1; /* Is the ACK triggering packet unambiguous? */ if (!(flag & FLAG_RETRANS_DATA_ACKED)) { /* High resolution needed and available? */ if (ca_ops->flags & TCP_CONG_RTT_STAMP && !ktime_equal(last_ackt, net_invalid_timestamp())) rtt_us = ktime_us_delta(ktime_get_real(), last_ackt); else if (ca_seq_rtt >= 0) rtt_us = jiffies_to_usecs(ca_seq_rtt); } ca_ops->pkts_acked(sk, pkts_acked, rtt_us); } } #if FASTRETRANS_DEBUG > 0 WARN_ON((int)tp->sacked_out < 0); WARN_ON((int)tp->lost_out < 0); WARN_ON((int)tp->retrans_out < 0); if (!tp->packets_out && tcp_is_sack(tp)) { icsk = inet_csk(sk); if (tp->lost_out) { pr_debug("Leak l=%u %d\n", tp->lost_out, icsk->icsk_ca_state); tp->lost_out = 0; } if (tp->sacked_out) { pr_debug("Leak s=%u %d\n", tp->sacked_out, icsk->icsk_ca_state); tp->sacked_out = 0; } if (tp->retrans_out) { pr_debug("Leak r=%u %d\n", tp->retrans_out, icsk->icsk_ca_state); tp->retrans_out = 0; } } #endif return flag; } static void tcp_ack_probe(struct sock *sk) { const struct tcp_sock *tp = tcp_sk(sk); struct inet_connection_sock *icsk = inet_csk(sk); /* Was it a usable window open? */ if (!after(TCP_SKB_CB(tcp_send_head(sk))->end_seq, tcp_wnd_end(tp))) { icsk->icsk_backoff = 0; inet_csk_clear_xmit_timer(sk, ICSK_TIME_PROBE0); /* Socket must be waked up by subsequent tcp_data_snd_check(). * This function is not for random using! */ } else { inet_csk_reset_xmit_timer(sk, ICSK_TIME_PROBE0, min(icsk->icsk_rto << icsk->icsk_backoff, TCP_RTO_MAX), TCP_RTO_MAX); } } static inline bool tcp_ack_is_dubious(const struct sock *sk, const int flag) { return !(flag & FLAG_NOT_DUP) || (flag & FLAG_CA_ALERT) || inet_csk(sk)->icsk_ca_state != TCP_CA_Open; } static inline bool tcp_may_raise_cwnd(const struct sock *sk, const int flag) { const struct tcp_sock *tp = tcp_sk(sk); return (!(flag & FLAG_ECE) || tp->snd_cwnd < tp->snd_ssthresh) && !tcp_in_cwnd_reduction(sk); } /* Check that window update is acceptable. * The function assumes that snd_una<=ack<=snd_next. */ static inline bool tcp_may_update_window(const struct tcp_sock *tp, const u32 ack, const u32 ack_seq, const u32 nwin) { return after(ack, tp->snd_una) || after(ack_seq, tp->snd_wl1) || (ack_seq == tp->snd_wl1 && nwin > tp->snd_wnd); } /* Update our send window. * * Window update algorithm, described in RFC793/RFC1122 (used in linux-2.2 * and in FreeBSD. NetBSD's one is even worse.) is wrong. */ static int tcp_ack_update_window(struct sock *sk, const struct sk_buff *skb, u32 ack, u32 ack_seq) { struct tcp_sock *tp = tcp_sk(sk); int flag = 0; u32 nwin = ntohs(tcp_hdr(skb)->window); if (likely(!tcp_hdr(skb)->syn)) nwin <<= tp->rx_opt.snd_wscale; if (tcp_may_update_window(tp, ack, ack_seq, nwin)) { flag |= FLAG_WIN_UPDATE; tcp_update_wl(tp, ack_seq); if (tp->snd_wnd != nwin) { tp->snd_wnd = nwin; /* Note, it is the only place, where * fast path is recovered for sending TCP. */ tp->pred_flags = 0; tcp_fast_path_check(sk); if (nwin > tp->max_window) { tp->max_window = nwin; tcp_sync_mss(sk, inet_csk(sk)->icsk_pmtu_cookie); } } } tp->snd_una = ack; return flag; } /* RFC 5961 7 [ACK Throttling] */ static void tcp_send_challenge_ack(struct sock *sk) { /* unprotected vars, we dont care of overwrites */ static u32 challenge_timestamp; static unsigned int challenge_count; u32 now = jiffies / HZ; if (now != challenge_timestamp) { challenge_timestamp = now; challenge_count = 0; } if (++challenge_count <= sysctl_tcp_challenge_ack_limit) { NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPCHALLENGEACK); tcp_send_ack(sk); } } static void tcp_store_ts_recent(struct tcp_sock *tp) { tp->rx_opt.ts_recent = tp->rx_opt.rcv_tsval; tp->rx_opt.ts_recent_stamp = get_seconds(); } static void tcp_replace_ts_recent(struct tcp_sock *tp, u32 seq) { if (tp->rx_opt.saw_tstamp && !after(seq, tp->rcv_wup)) { /* PAWS bug workaround wrt. ACK frames, the PAWS discard * extra check below makes sure this can only happen * for pure ACK frames. -DaveM * * Not only, also it occurs for expired timestamps. */ if (tcp_paws_check(&tp->rx_opt, 0)) tcp_store_ts_recent(tp); } } /* This routine deals with acks during a TLP episode. * Ref: loss detection algorithm in draft-dukkipati-tcpm-tcp-loss-probe. */ static void tcp_process_tlp_ack(struct sock *sk, u32 ack, int flag) { struct tcp_sock *tp = tcp_sk(sk); bool is_tlp_dupack = (ack == tp->tlp_high_seq) && !(flag & (FLAG_SND_UNA_ADVANCED | FLAG_NOT_DUP | FLAG_DATA_SACKED)); /* Mark the end of TLP episode on receiving TLP dupack or when * ack is after tlp_high_seq. */ if (is_tlp_dupack) { tp->tlp_high_seq = 0; return; } if (after(ack, tp->tlp_high_seq)) { tp->tlp_high_seq = 0; /* Don't reduce cwnd if DSACK arrives for TLP retrans. */ if (!(flag & FLAG_DSACKING_ACK)) { tcp_init_cwnd_reduction(sk, true); tcp_set_ca_state(sk, TCP_CA_CWR); tcp_end_cwnd_reduction(sk); tcp_try_keep_open(sk); NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPLOSSPROBERECOVERY); } } } /* This routine deals with incoming acks, but not outgoing ones. */ static int tcp_ack(struct sock *sk, const struct sk_buff *skb, int flag) { struct inet_connection_sock *icsk = inet_csk(sk); struct tcp_sock *tp = tcp_sk(sk); u32 prior_snd_una = tp->snd_una; u32 ack_seq = TCP_SKB_CB(skb)->seq; u32 ack = TCP_SKB_CB(skb)->ack_seq; bool is_dupack = false; u32 prior_in_flight, prior_cwnd = tp->snd_cwnd, prior_rtt = tp->srtt; u32 prior_fackets; int prior_packets = tp->packets_out; int prior_sacked = tp->sacked_out; int pkts_acked = 0; int previous_packets_out = 0; /* If the ack is older than previous acks * then we can probably ignore it. */ if (before(ack, prior_snd_una)) { /* RFC 5961 5.2 [Blind Data Injection Attack].[Mitigation] */ if (before(ack, prior_snd_una - tp->max_window)) { tcp_send_challenge_ack(sk); return -1; } goto old_ack; } /* If the ack includes data we haven't sent yet, discard * this segment (RFC793 Section 3.9). */ if (after(ack, tp->snd_nxt)) goto invalid_ack; if (icsk->icsk_pending == ICSK_TIME_EARLY_RETRANS || icsk->icsk_pending == ICSK_TIME_LOSS_PROBE) tcp_rearm_rto(sk); if (after(ack, prior_snd_una)) flag |= FLAG_SND_UNA_ADVANCED; prior_fackets = tp->fackets_out; prior_in_flight = tcp_packets_in_flight(tp); /* ts_recent update must be made after we are sure that the packet * is in window. */ if (flag & FLAG_UPDATE_TS_RECENT) tcp_replace_ts_recent(tp, TCP_SKB_CB(skb)->seq); if (!(flag & FLAG_SLOWPATH) && after(ack, prior_snd_una)) { /* Window is constant, pure forward advance. * No more checks are required. * Note, we use the fact that SND.UNA>=SND.WL2. */ tcp_update_wl(tp, ack_seq); tp->snd_una = ack; flag |= FLAG_WIN_UPDATE; tcp_ca_event(sk, CA_EVENT_FAST_ACK); NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPHPACKS); } else { if (ack_seq != TCP_SKB_CB(skb)->end_seq) flag |= FLAG_DATA; else NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPPUREACKS); flag |= tcp_ack_update_window(sk, skb, ack, ack_seq); if (TCP_SKB_CB(skb)->sacked) flag |= tcp_sacktag_write_queue(sk, skb, prior_snd_una); if (TCP_ECN_rcv_ecn_echo(tp, tcp_hdr(skb))) flag |= FLAG_ECE; tcp_ca_event(sk, CA_EVENT_SLOW_ACK); } /* We passed data and got it acked, remove any soft error * log. Something worked... */ sk->sk_err_soft = 0; icsk->icsk_probes_out = 0; tp->rcv_tstamp = tcp_time_stamp; if (!prior_packets) goto no_queue; /* See if we can take anything off of the retransmit queue. */ previous_packets_out = tp->packets_out; flag |= tcp_clean_rtx_queue(sk, prior_fackets, prior_snd_una); pkts_acked = previous_packets_out - tp->packets_out; if (tcp_ack_is_dubious(sk, flag)) { /* Advance CWND, if state allows this. */ if ((flag & FLAG_DATA_ACKED) && tcp_may_raise_cwnd(sk, flag)) tcp_cong_avoid(sk, ack, prior_in_flight); is_dupack = !(flag & (FLAG_SND_UNA_ADVANCED | FLAG_NOT_DUP)); tcp_fastretrans_alert(sk, pkts_acked, prior_sacked, prior_packets, is_dupack, flag); } else { if (flag & FLAG_DATA_ACKED) tcp_cong_avoid(sk, ack, prior_in_flight); } if (tp->tlp_high_seq) tcp_process_tlp_ack(sk, ack, flag); if ((flag & FLAG_FORWARD_PROGRESS) || !(flag & FLAG_NOT_DUP)) { struct dst_entry *dst = __sk_dst_get(sk); if (dst) dst_confirm(dst); } if (icsk->icsk_pending == ICSK_TIME_RETRANS) tcp_schedule_loss_probe(sk); if (tp->srtt != prior_rtt || tp->snd_cwnd != prior_cwnd) tcp_update_pacing_rate(sk); return 1; no_queue: /* If data was DSACKed, see if we can undo a cwnd reduction. */ if (flag & FLAG_DSACKING_ACK) tcp_fastretrans_alert(sk, pkts_acked, prior_sacked, prior_packets, is_dupack, flag); /* If this ack opens up a zero window, clear backoff. It was * being used to time the probes, and is probably far higher than * it needs to be for normal retransmission. */ if (tcp_send_head(sk)) tcp_ack_probe(sk); if (tp->tlp_high_seq) tcp_process_tlp_ack(sk, ack, flag); return 1; invalid_ack: SOCK_DEBUG(sk, "Ack %u after %u:%u\n", ack, tp->snd_una, tp->snd_nxt); return -1; old_ack: /* If data was SACKed, tag it and see if we should send more data. * If data was DSACKed, see if we can undo a cwnd reduction. */ if (TCP_SKB_CB(skb)->sacked) { flag |= tcp_sacktag_write_queue(sk, skb, prior_snd_una); tcp_fastretrans_alert(sk, pkts_acked, prior_sacked, prior_packets, is_dupack, flag); } SOCK_DEBUG(sk, "Ack %u before %u:%u\n", ack, tp->snd_una, tp->snd_nxt); return 0; } /* Look for tcp options. Normally only called on SYN and SYNACK packets. * But, this can also be called on packets in the established flow when * the fast version below fails. */ void tcp_parse_options(const struct sk_buff *skb, struct tcp_options_received *opt_rx, int estab, struct tcp_fastopen_cookie *foc) { const unsigned char *ptr; const struct tcphdr *th = tcp_hdr(skb); int length = (th->doff * 4) - sizeof(struct tcphdr); ptr = (const unsigned char *)(th + 1); opt_rx->saw_tstamp = 0; while (length > 0) { int opcode = *ptr++; int opsize; switch (opcode) { case TCPOPT_EOL: return; case TCPOPT_NOP: /* Ref: RFC 793 section 3.1 */ length--; continue; default: opsize = *ptr++; if (opsize < 2) /* "silly options" */ return; if (opsize > length) return; /* don't parse partial options */ switch (opcode) { case TCPOPT_MSS: if (opsize == TCPOLEN_MSS && th->syn && !estab) { u16 in_mss = get_unaligned_be16(ptr); if (in_mss) { if (opt_rx->user_mss && opt_rx->user_mss < in_mss) in_mss = opt_rx->user_mss; opt_rx->mss_clamp = in_mss; } } break; case TCPOPT_WINDOW: if (opsize == TCPOLEN_WINDOW && th->syn && !estab && sysctl_tcp_window_scaling) { __u8 snd_wscale = *(__u8 *)ptr; opt_rx->wscale_ok = 1; if (snd_wscale > 14) { net_info_ratelimited("%s: Illegal window scaling value %d >14 received\n", __func__, snd_wscale); snd_wscale = 14; } opt_rx->snd_wscale = snd_wscale; } break; case TCPOPT_TIMESTAMP: if ((opsize == TCPOLEN_TIMESTAMP) && ((estab && opt_rx->tstamp_ok) || (!estab && sysctl_tcp_timestamps))) { opt_rx->saw_tstamp = 1; opt_rx->rcv_tsval = get_unaligned_be32(ptr); opt_rx->rcv_tsecr = get_unaligned_be32(ptr + 4); } break; case TCPOPT_SACK_PERM: if (opsize == TCPOLEN_SACK_PERM && th->syn && !estab && sysctl_tcp_sack) { opt_rx->sack_ok = TCP_SACK_SEEN; tcp_sack_reset(opt_rx); } break; case TCPOPT_SACK: if ((opsize >= (TCPOLEN_SACK_BASE + TCPOLEN_SACK_PERBLOCK)) && !((opsize - TCPOLEN_SACK_BASE) % TCPOLEN_SACK_PERBLOCK) && opt_rx->sack_ok) { TCP_SKB_CB(skb)->sacked = (ptr - 2) - (unsigned char *)th; } break; #ifdef CONFIG_TCP_MD5SIG case TCPOPT_MD5SIG: /* * The MD5 Hash has already been * checked (see tcp_v{4,6}_do_rcv()). */ break; #endif case TCPOPT_EXP: /* Fast Open option shares code 254 using a * 16 bits magic number. It's valid only in * SYN or SYN-ACK with an even size. */ if (opsize < TCPOLEN_EXP_FASTOPEN_BASE || get_unaligned_be16(ptr) != TCPOPT_FASTOPEN_MAGIC || foc == NULL || !th->syn || (opsize & 1)) break; foc->len = opsize - TCPOLEN_EXP_FASTOPEN_BASE; if (foc->len >= TCP_FASTOPEN_COOKIE_MIN && foc->len <= TCP_FASTOPEN_COOKIE_MAX) memcpy(foc->val, ptr + 2, foc->len); else if (foc->len != 0) foc->len = -1; break; } ptr += opsize-2; length -= opsize; } } } EXPORT_SYMBOL(tcp_parse_options); static bool tcp_parse_aligned_timestamp(struct tcp_sock *tp, const struct tcphdr *th) { const __be32 *ptr = (const __be32 *)(th + 1); if (*ptr == htonl((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16) | (TCPOPT_TIMESTAMP << 8) | TCPOLEN_TIMESTAMP)) { tp->rx_opt.saw_tstamp = 1; ++ptr; tp->rx_opt.rcv_tsval = ntohl(*ptr); ++ptr; if (*ptr) tp->rx_opt.rcv_tsecr = ntohl(*ptr) - tp->tsoffset; else tp->rx_opt.rcv_tsecr = 0; return true; } return false; } /* Fast parse options. This hopes to only see timestamps. * If it is wrong it falls back on tcp_parse_options(). */ static bool tcp_fast_parse_options(const struct sk_buff *skb, const struct tcphdr *th, struct tcp_sock *tp) { /* In the spirit of fast parsing, compare doff directly to constant * values. Because equality is used, short doff can be ignored here. */ if (th->doff == (sizeof(*th) / 4)) { tp->rx_opt.saw_tstamp = 0; return false; } else if (tp->rx_opt.tstamp_ok && th->doff == ((sizeof(*th) + TCPOLEN_TSTAMP_ALIGNED) / 4)) { if (tcp_parse_aligned_timestamp(tp, th)) return true; } tcp_parse_options(skb, &tp->rx_opt, 1, NULL); if (tp->rx_opt.saw_tstamp && tp->rx_opt.rcv_tsecr) tp->rx_opt.rcv_tsecr -= tp->tsoffset; return true; } #ifdef CONFIG_TCP_MD5SIG /* * Parse MD5 Signature option */ const u8 *tcp_parse_md5sig_option(const struct tcphdr *th) { int length = (th->doff << 2) - sizeof(*th); const u8 *ptr = (const u8 *)(th + 1); /* If the TCP option is too short, we can short cut */ if (length < TCPOLEN_MD5SIG) return NULL; while (length > 0) { int opcode = *ptr++; int opsize; switch(opcode) { case TCPOPT_EOL: return NULL; case TCPOPT_NOP: length--; continue; default: opsize = *ptr++; if (opsize < 2 || opsize > length) return NULL; if (opcode == TCPOPT_MD5SIG) return opsize == TCPOLEN_MD5SIG ? ptr : NULL; } ptr += opsize - 2; length -= opsize; } return NULL; } EXPORT_SYMBOL(tcp_parse_md5sig_option); #endif /* Sorry, PAWS as specified is broken wrt. pure-ACKs -DaveM * * It is not fatal. If this ACK does _not_ change critical state (seqs, window) * it can pass through stack. So, the following predicate verifies that * this segment is not used for anything but congestion avoidance or * fast retransmit. Moreover, we even are able to eliminate most of such * second order effects, if we apply some small "replay" window (~RTO) * to timestamp space. * * All these measures still do not guarantee that we reject wrapped ACKs * on networks with high bandwidth, when sequence space is recycled fastly, * but it guarantees that such events will be very rare and do not affect * connection seriously. This doesn't look nice, but alas, PAWS is really * buggy extension. * * [ Later note. Even worse! It is buggy for segments _with_ data. RFC * states that events when retransmit arrives after original data are rare. * It is a blatant lie. VJ forgot about fast retransmit! 8)8) It is * the biggest problem on large power networks even with minor reordering. * OK, let's give it small replay window. If peer clock is even 1hz, it is safe * up to bandwidth of 18Gigabit/sec. 8) ] */ static int tcp_disordered_ack(const struct sock *sk, const struct sk_buff *skb) { const struct tcp_sock *tp = tcp_sk(sk); const struct tcphdr *th = tcp_hdr(skb); u32 seq = TCP_SKB_CB(skb)->seq; u32 ack = TCP_SKB_CB(skb)->ack_seq; return (/* 1. Pure ACK with correct sequence number. */ (th->ack && seq == TCP_SKB_CB(skb)->end_seq && seq == tp->rcv_nxt) && /* 2. ... and duplicate ACK. */ ack == tp->snd_una && /* 3. ... and does not update window. */ !tcp_may_update_window(tp, ack, seq, ntohs(th->window) << tp->rx_opt.snd_wscale) && /* 4. ... and sits in replay window. */ (s32)(tp->rx_opt.ts_recent - tp->rx_opt.rcv_tsval) <= (inet_csk(sk)->icsk_rto * 1024) / HZ); } static inline bool tcp_paws_discard(const struct sock *sk, const struct sk_buff *skb) { const struct tcp_sock *tp = tcp_sk(sk); return !tcp_paws_check(&tp->rx_opt, TCP_PAWS_WINDOW) && !tcp_disordered_ack(sk, skb); } /* Check segment sequence number for validity. * * Segment controls are considered valid, if the segment * fits to the window after truncation to the window. Acceptability * of data (and SYN, FIN, of course) is checked separately. * See tcp_data_queue(), for example. * * Also, controls (RST is main one) are accepted using RCV.WUP instead * of RCV.NXT. Peer still did not advance his SND.UNA when we * delayed ACK, so that hisSND.UNA<=ourRCV.WUP. * (borrowed from freebsd) */ static inline bool tcp_sequence(const struct tcp_sock *tp, u32 seq, u32 end_seq) { return !before(end_seq, tp->rcv_wup) && !after(seq, tp->rcv_nxt + tcp_receive_window(tp)); } /* When we get a reset we do this. */ void tcp_reset(struct sock *sk) { /* We want the right error as BSD sees it (and indeed as we do). */ switch (sk->sk_state) { case TCP_SYN_SENT: sk->sk_err = ECONNREFUSED; break; case TCP_CLOSE_WAIT: sk->sk_err = EPIPE; break; case TCP_CLOSE: return; default: sk->sk_err = ECONNRESET; } /* This barrier is coupled with smp_rmb() in tcp_poll() */ smp_wmb(); if (!sock_flag(sk, SOCK_DEAD)) sk->sk_error_report(sk); tcp_done(sk); } /* * Process the FIN bit. This now behaves as it is supposed to work * and the FIN takes effect when it is validly part of sequence * space. Not before when we get holes. * * If we are ESTABLISHED, a received fin moves us to CLOSE-WAIT * (and thence onto LAST-ACK and finally, CLOSE, we never enter * TIME-WAIT) * * If we are in FINWAIT-1, a received FIN indicates simultaneous * close and we go into CLOSING (and later onto TIME-WAIT) * * If we are in FINWAIT-2, a received FIN moves us to TIME-WAIT. */ static void tcp_fin(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); inet_csk_schedule_ack(sk); sk->sk_shutdown |= RCV_SHUTDOWN; sock_set_flag(sk, SOCK_DONE); switch (sk->sk_state) { case TCP_SYN_RECV: case TCP_ESTABLISHED: /* Move to CLOSE_WAIT */ tcp_set_state(sk, TCP_CLOSE_WAIT); inet_csk(sk)->icsk_ack.pingpong = 1; break; case TCP_CLOSE_WAIT: case TCP_CLOSING: /* Received a retransmission of the FIN, do * nothing. */ break; case TCP_LAST_ACK: /* RFC793: Remain in the LAST-ACK state. */ break; case TCP_FIN_WAIT1: /* This case occurs when a simultaneous close * happens, we must ack the received FIN and * enter the CLOSING state. */ tcp_send_ack(sk); tcp_set_state(sk, TCP_CLOSING); break; case TCP_FIN_WAIT2: /* Received a FIN -- send ACK and enter TIME_WAIT. */ tcp_send_ack(sk); tcp_time_wait(sk, TCP_TIME_WAIT, 0); break; default: /* Only TCP_LISTEN and TCP_CLOSE are left, in these * cases we should never reach this piece of code. */ pr_err("%s: Impossible, sk->sk_state=%d\n", __func__, sk->sk_state); break; } /* It _is_ possible, that we have something out-of-order _after_ FIN. * Probably, we should reset in this case. For now drop them. */ __skb_queue_purge(&tp->out_of_order_queue); if (tcp_is_sack(tp)) tcp_sack_reset(&tp->rx_opt); sk_mem_reclaim(sk); if (!sock_flag(sk, SOCK_DEAD)) { sk->sk_state_change(sk); /* Do not send POLL_HUP for half duplex close. */ if (sk->sk_shutdown == SHUTDOWN_MASK || sk->sk_state == TCP_CLOSE) sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_HUP); else sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_IN); } } static inline bool tcp_sack_extend(struct tcp_sack_block *sp, u32 seq, u32 end_seq) { if (!after(seq, sp->end_seq) && !after(sp->start_seq, end_seq)) { if (before(seq, sp->start_seq)) sp->start_seq = seq; if (after(end_seq, sp->end_seq)) sp->end_seq = end_seq; return true; } return false; } static void tcp_dsack_set(struct sock *sk, u32 seq, u32 end_seq) { struct tcp_sock *tp = tcp_sk(sk); if (tcp_is_sack(tp) && sysctl_tcp_dsack) { int mib_idx; if (before(seq, tp->rcv_nxt)) mib_idx = LINUX_MIB_TCPDSACKOLDSENT; else mib_idx = LINUX_MIB_TCPDSACKOFOSENT; NET_INC_STATS_BH(sock_net(sk), mib_idx); tp->rx_opt.dsack = 1; tp->duplicate_sack[0].start_seq = seq; tp->duplicate_sack[0].end_seq = end_seq; } } static void tcp_dsack_extend(struct sock *sk, u32 seq, u32 end_seq) { struct tcp_sock *tp = tcp_sk(sk); if (!tp->rx_opt.dsack) tcp_dsack_set(sk, seq, end_seq); else tcp_sack_extend(tp->duplicate_sack, seq, end_seq); } static void tcp_send_dupack(struct sock *sk, const struct sk_buff *skb) { struct tcp_sock *tp = tcp_sk(sk); if (TCP_SKB_CB(skb)->end_seq != TCP_SKB_CB(skb)->seq && before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt)) { NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_DELAYEDACKLOST); tcp_enter_quickack_mode(sk); if (tcp_is_sack(tp) && sysctl_tcp_dsack) { u32 end_seq = TCP_SKB_CB(skb)->end_seq; if (after(TCP_SKB_CB(skb)->end_seq, tp->rcv_nxt)) end_seq = tp->rcv_nxt; tcp_dsack_set(sk, TCP_SKB_CB(skb)->seq, end_seq); } } tcp_send_ack(sk); } /* These routines update the SACK block as out-of-order packets arrive or * in-order packets close up the sequence space. */ static void tcp_sack_maybe_coalesce(struct tcp_sock *tp) { int this_sack; struct tcp_sack_block *sp = &tp->selective_acks[0]; struct tcp_sack_block *swalk = sp + 1; /* See if the recent change to the first SACK eats into * or hits the sequence space of other SACK blocks, if so coalesce. */ for (this_sack = 1; this_sack < tp->rx_opt.num_sacks;) { if (tcp_sack_extend(sp, swalk->start_seq, swalk->end_seq)) { int i; /* Zap SWALK, by moving every further SACK up by one slot. * Decrease num_sacks. */ tp->rx_opt.num_sacks--; for (i = this_sack; i < tp->rx_opt.num_sacks; i++) sp[i] = sp[i + 1]; continue; } this_sack++, swalk++; } } static void tcp_sack_new_ofo_skb(struct sock *sk, u32 seq, u32 end_seq) { struct tcp_sock *tp = tcp_sk(sk); struct tcp_sack_block *sp = &tp->selective_acks[0]; int cur_sacks = tp->rx_opt.num_sacks; int this_sack; if (!cur_sacks) goto new_sack; for (this_sack = 0; this_sack < cur_sacks; this_sack++, sp++) { if (tcp_sack_extend(sp, seq, end_seq)) { /* Rotate this_sack to the first one. */ for (; this_sack > 0; this_sack--, sp--) swap(*sp, *(sp - 1)); if (cur_sacks > 1) tcp_sack_maybe_coalesce(tp); return; } } /* Could not find an adjacent existing SACK, build a new one, * put it at the front, and shift everyone else down. We * always know there is at least one SACK present already here. * * If the sack array is full, forget about the last one. */ if (this_sack >= TCP_NUM_SACKS) { this_sack--; tp->rx_opt.num_sacks--; sp--; } for (; this_sack > 0; this_sack--, sp--) *sp = *(sp - 1); new_sack: /* Build the new head SACK, and we're done. */ sp->start_seq = seq; sp->end_seq = end_seq; tp->rx_opt.num_sacks++; } /* RCV.NXT advances, some SACKs should be eaten. */ static void tcp_sack_remove(struct tcp_sock *tp) { struct tcp_sack_block *sp = &tp->selective_acks[0]; int num_sacks = tp->rx_opt.num_sacks; int this_sack; /* Empty ofo queue, hence, all the SACKs are eaten. Clear. */ if (skb_queue_empty(&tp->out_of_order_queue)) { tp->rx_opt.num_sacks = 0; return; } for (this_sack = 0; this_sack < num_sacks;) { /* Check if the start of the sack is covered by RCV.NXT. */ if (!before(tp->rcv_nxt, sp->start_seq)) { int i; /* RCV.NXT must cover all the block! */ WARN_ON(before(tp->rcv_nxt, sp->end_seq)); /* Zap this SACK, by moving forward any other SACKS. */ for (i=this_sack+1; i < num_sacks; i++) tp->selective_acks[i-1] = tp->selective_acks[i]; num_sacks--; continue; } this_sack++; sp++; } tp->rx_opt.num_sacks = num_sacks; } /* This one checks to see if we can put data from the * out_of_order queue into the receive_queue. */ static void tcp_ofo_queue(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); __u32 dsack_high = tp->rcv_nxt; struct sk_buff *skb; while ((skb = skb_peek(&tp->out_of_order_queue)) != NULL) { if (after(TCP_SKB_CB(skb)->seq, tp->rcv_nxt)) break; if (before(TCP_SKB_CB(skb)->seq, dsack_high)) { __u32 dsack = dsack_high; if (before(TCP_SKB_CB(skb)->end_seq, dsack_high)) dsack_high = TCP_SKB_CB(skb)->end_seq; tcp_dsack_extend(sk, TCP_SKB_CB(skb)->seq, dsack); } if (!after(TCP_SKB_CB(skb)->end_seq, tp->rcv_nxt)) { SOCK_DEBUG(sk, "ofo packet was already received\n"); __skb_unlink(skb, &tp->out_of_order_queue); __kfree_skb(skb); continue; } SOCK_DEBUG(sk, "ofo requeuing : rcv_next %X seq %X - %X\n", tp->rcv_nxt, TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb)->end_seq); __skb_unlink(skb, &tp->out_of_order_queue); __skb_queue_tail(&sk->sk_receive_queue, skb); tp->rcv_nxt = TCP_SKB_CB(skb)->end_seq; if (tcp_hdr(skb)->fin) tcp_fin(sk); } } static bool tcp_prune_ofo_queue(struct sock *sk); static int tcp_prune_queue(struct sock *sk); static int tcp_try_rmem_schedule(struct sock *sk, struct sk_buff *skb, unsigned int size) { if (atomic_read(&sk->sk_rmem_alloc) > sk->sk_rcvbuf || !sk_rmem_schedule(sk, skb, size)) { if (tcp_prune_queue(sk) < 0) return -1; if (!sk_rmem_schedule(sk, skb, size)) { if (!tcp_prune_ofo_queue(sk)) return -1; if (!sk_rmem_schedule(sk, skb, size)) return -1; } } return 0; } /** * tcp_try_coalesce - try to merge skb to prior one * @sk: socket * @to: prior buffer * @from: buffer to add in queue * @fragstolen: pointer to boolean * * Before queueing skb @from after @to, try to merge them * to reduce overall memory use and queue lengths, if cost is small. * Packets in ofo or receive queues can stay a long time. * Better try to coalesce them right now to avoid future collapses. * Returns true if caller should free @from instead of queueing it */ static bool tcp_try_coalesce(struct sock *sk, struct sk_buff *to, struct sk_buff *from, bool *fragstolen) { int delta; *fragstolen = false; if (tcp_hdr(from)->fin) return false; /* Its possible this segment overlaps with prior segment in queue */ if (TCP_SKB_CB(from)->seq != TCP_SKB_CB(to)->end_seq) return false; if (!skb_try_coalesce(to, from, fragstolen, &delta)) return false; atomic_add(delta, &sk->sk_rmem_alloc); sk_mem_charge(sk, delta); NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPRCVCOALESCE); TCP_SKB_CB(to)->end_seq = TCP_SKB_CB(from)->end_seq; TCP_SKB_CB(to)->ack_seq = TCP_SKB_CB(from)->ack_seq; return true; } static void tcp_data_queue_ofo(struct sock *sk, struct sk_buff *skb) { struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *skb1; u32 seq, end_seq; TCP_ECN_check_ce(tp, skb); if (unlikely(tcp_try_rmem_schedule(sk, skb, skb->truesize))) { NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPOFODROP); __kfree_skb(skb); return; } /* Disable header prediction. */ tp->pred_flags = 0; inet_csk_schedule_ack(sk); NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPOFOQUEUE); SOCK_DEBUG(sk, "out of order segment: rcv_next %X seq %X - %X\n", tp->rcv_nxt, TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb)->end_seq); skb1 = skb_peek_tail(&tp->out_of_order_queue); if (!skb1) { /* Initial out of order segment, build 1 SACK. */ if (tcp_is_sack(tp)) { tp->rx_opt.num_sacks = 1; tp->selective_acks[0].start_seq = TCP_SKB_CB(skb)->seq; tp->selective_acks[0].end_seq = TCP_SKB_CB(skb)->end_seq; } __skb_queue_head(&tp->out_of_order_queue, skb); goto end; } seq = TCP_SKB_CB(skb)->seq; end_seq = TCP_SKB_CB(skb)->end_seq; if (seq == TCP_SKB_CB(skb1)->end_seq) { bool fragstolen; if (!tcp_try_coalesce(sk, skb1, skb, &fragstolen)) { __skb_queue_after(&tp->out_of_order_queue, skb1, skb); } else { kfree_skb_partial(skb, fragstolen); skb = NULL; } if (!tp->rx_opt.num_sacks || tp->selective_acks[0].end_seq != seq) goto add_sack; /* Common case: data arrive in order after hole. */ tp->selective_acks[0].end_seq = end_seq; goto end; } /* Find place to insert this segment. */ while (1) { if (!after(TCP_SKB_CB(skb1)->seq, seq)) break; if (skb_queue_is_first(&tp->out_of_order_queue, skb1)) { skb1 = NULL; break; } skb1 = skb_queue_prev(&tp->out_of_order_queue, skb1); } /* Do skb overlap to previous one? */ if (skb1 && before(seq, TCP_SKB_CB(skb1)->end_seq)) { if (!after(end_seq, TCP_SKB_CB(skb1)->end_seq)) { /* All the bits are present. Drop. */ NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPOFOMERGE); __kfree_skb(skb); skb = NULL; tcp_dsack_set(sk, seq, end_seq); goto add_sack; } if (after(seq, TCP_SKB_CB(skb1)->seq)) { /* Partial overlap. */ tcp_dsack_set(sk, seq, TCP_SKB_CB(skb1)->end_seq); } else { if (skb_queue_is_first(&tp->out_of_order_queue, skb1)) skb1 = NULL; else skb1 = skb_queue_prev( &tp->out_of_order_queue, skb1); } } if (!skb1) __skb_queue_head(&tp->out_of_order_queue, skb); else __skb_queue_after(&tp->out_of_order_queue, skb1, skb); /* And clean segments covered by new one as whole. */ while (!skb_queue_is_last(&tp->out_of_order_queue, skb)) { skb1 = skb_queue_next(&tp->out_of_order_queue, skb); if (!after(end_seq, TCP_SKB_CB(skb1)->seq)) break; if (before(end_seq, TCP_SKB_CB(skb1)->end_seq)) { tcp_dsack_extend(sk, TCP_SKB_CB(skb1)->seq, end_seq); break; } __skb_unlink(skb1, &tp->out_of_order_queue); tcp_dsack_extend(sk, TCP_SKB_CB(skb1)->seq, TCP_SKB_CB(skb1)->end_seq); NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPOFOMERGE); __kfree_skb(skb1); } add_sack: if (tcp_is_sack(tp)) tcp_sack_new_ofo_skb(sk, seq, end_seq); end: if (skb) skb_set_owner_r(skb, sk); } static int __must_check tcp_queue_rcv(struct sock *sk, struct sk_buff *skb, int hdrlen, bool *fragstolen) { int eaten; struct sk_buff *tail = skb_peek_tail(&sk->sk_receive_queue); __skb_pull(skb, hdrlen); eaten = (tail && tcp_try_coalesce(sk, tail, skb, fragstolen)) ? 1 : 0; tcp_sk(sk)->rcv_nxt = TCP_SKB_CB(skb)->end_seq; if (!eaten) { __skb_queue_tail(&sk->sk_receive_queue, skb); skb_set_owner_r(skb, sk); } return eaten; } int tcp_send_rcvq(struct sock *sk, struct msghdr *msg, size_t size) { struct sk_buff *skb = NULL; struct tcphdr *th; bool fragstolen; if (size == 0) return 0; skb = alloc_skb(size + sizeof(*th), sk->sk_allocation); if (!skb) goto err; if (tcp_try_rmem_schedule(sk, skb, size + sizeof(*th))) goto err_free; th = (struct tcphdr *)skb_put(skb, sizeof(*th)); skb_reset_transport_header(skb); memset(th, 0, sizeof(*th)); if (memcpy_fromiovec(skb_put(skb, size), msg->msg_iov, size)) goto err_free; TCP_SKB_CB(skb)->seq = tcp_sk(sk)->rcv_nxt; TCP_SKB_CB(skb)->end_seq = TCP_SKB_CB(skb)->seq + size; TCP_SKB_CB(skb)->ack_seq = tcp_sk(sk)->snd_una - 1; if (tcp_queue_rcv(sk, skb, sizeof(*th), &fragstolen)) { WARN_ON_ONCE(fragstolen); /* should not happen */ __kfree_skb(skb); } return size; err_free: kfree_skb(skb); err: return -ENOMEM; } static void tcp_data_queue(struct sock *sk, struct sk_buff *skb) { const struct tcphdr *th = tcp_hdr(skb); struct tcp_sock *tp = tcp_sk(sk); int eaten = -1; bool fragstolen = false; if (TCP_SKB_CB(skb)->seq == TCP_SKB_CB(skb)->end_seq) goto drop; skb_dst_drop(skb); __skb_pull(skb, th->doff * 4); TCP_ECN_accept_cwr(tp, skb); tp->rx_opt.dsack = 0; /* Queue data for delivery to the user. * Packets in sequence go to the receive queue. * Out of sequence packets to the out_of_order_queue. */ if (TCP_SKB_CB(skb)->seq == tp->rcv_nxt) { if (tcp_receive_window(tp) == 0) goto out_of_window; /* Ok. In sequence. In window. */ if (tp->ucopy.task == current && tp->copied_seq == tp->rcv_nxt && tp->ucopy.len && sock_owned_by_user(sk) && !tp->urg_data) { int chunk = min_t(unsigned int, skb->len, tp->ucopy.len); __set_current_state(TASK_RUNNING); local_bh_enable(); if (!skb_copy_datagram_iovec(skb, 0, tp->ucopy.iov, chunk)) { tp->ucopy.len -= chunk; tp->copied_seq += chunk; eaten = (chunk == skb->len); tcp_rcv_space_adjust(sk); } local_bh_disable(); } if (eaten <= 0) { queue_and_out: if (eaten < 0 && tcp_try_rmem_schedule(sk, skb, skb->truesize)) goto drop; eaten = tcp_queue_rcv(sk, skb, 0, &fragstolen); } tp->rcv_nxt = TCP_SKB_CB(skb)->end_seq; if (skb->len) tcp_event_data_recv(sk, skb); if (th->fin) tcp_fin(sk); if (!skb_queue_empty(&tp->out_of_order_queue)) { tcp_ofo_queue(sk); /* RFC2581. 4.2. SHOULD send immediate ACK, when * gap in queue is filled. */ if (skb_queue_empty(&tp->out_of_order_queue)) inet_csk(sk)->icsk_ack.pingpong = 0; } if (tp->rx_opt.num_sacks) tcp_sack_remove(tp); tcp_fast_path_check(sk); if (eaten > 0) kfree_skb_partial(skb, fragstolen); if (!sock_flag(sk, SOCK_DEAD)) sk->sk_data_ready(sk, 0); return; } if (!after(TCP_SKB_CB(skb)->end_seq, tp->rcv_nxt)) { /* A retransmit, 2nd most common case. Force an immediate ack. */ NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_DELAYEDACKLOST); tcp_dsack_set(sk, TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb)->end_seq); out_of_window: tcp_enter_quickack_mode(sk); inet_csk_schedule_ack(sk); drop: __kfree_skb(skb); return; } /* Out of window. F.e. zero window probe. */ if (!before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt + tcp_receive_window(tp))) goto out_of_window; tcp_enter_quickack_mode(sk); if (before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt)) { /* Partial packet, seq < rcv_next < end_seq */ SOCK_DEBUG(sk, "partial packet: rcv_next %X seq %X - %X\n", tp->rcv_nxt, TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb)->end_seq); tcp_dsack_set(sk, TCP_SKB_CB(skb)->seq, tp->rcv_nxt); /* If window is closed, drop tail of packet. But after * remembering D-SACK for its head made in previous line. */ if (!tcp_receive_window(tp)) goto out_of_window; goto queue_and_out; } tcp_data_queue_ofo(sk, skb); } static struct sk_buff *tcp_collapse_one(struct sock *sk, struct sk_buff *skb, struct sk_buff_head *list) { struct sk_buff *next = NULL; if (!skb_queue_is_last(list, skb)) next = skb_queue_next(list, skb); __skb_unlink(skb, list); __kfree_skb(skb); NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPRCVCOLLAPSED); return next; } /* Collapse contiguous sequence of skbs head..tail with * sequence numbers start..end. * * If tail is NULL, this means until the end of the list. * * Segments with FIN/SYN are not collapsed (only because this * simplifies code) */ static void tcp_collapse(struct sock *sk, struct sk_buff_head *list, struct sk_buff *head, struct sk_buff *tail, u32 start, u32 end) { struct sk_buff *skb, *n; bool end_of_skbs; /* First, check that queue is collapsible and find * the point where collapsing can be useful. */ skb = head; restart: end_of_skbs = true; skb_queue_walk_from_safe(list, skb, n) { if (skb == tail) break; /* No new bits? It is possible on ofo queue. */ if (!before(start, TCP_SKB_CB(skb)->end_seq)) { skb = tcp_collapse_one(sk, skb, list); if (!skb) break; goto restart; } /* The first skb to collapse is: * - not SYN/FIN and * - bloated or contains data before "start" or * overlaps to the next one. */ if (!tcp_hdr(skb)->syn && !tcp_hdr(skb)->fin && (tcp_win_from_space(skb->truesize) > skb->len || before(TCP_SKB_CB(skb)->seq, start))) { end_of_skbs = false; break; } if (!skb_queue_is_last(list, skb)) { struct sk_buff *next = skb_queue_next(list, skb); if (next != tail && TCP_SKB_CB(skb)->end_seq != TCP_SKB_CB(next)->seq) { end_of_skbs = false; break; } } /* Decided to skip this, advance start seq. */ start = TCP_SKB_CB(skb)->end_seq; } if (end_of_skbs || tcp_hdr(skb)->syn || tcp_hdr(skb)->fin) return; while (before(start, end)) { struct sk_buff *nskb; unsigned int header = skb_headroom(skb); int copy = SKB_MAX_ORDER(header, 0); /* Too big header? This can happen with IPv6. */ if (copy < 0) return; if (end - start < copy) copy = end - start; nskb = alloc_skb(copy + header, GFP_ATOMIC); if (!nskb) return; skb_set_mac_header(nskb, skb_mac_header(skb) - skb->head); skb_set_network_header(nskb, (skb_network_header(skb) - skb->head)); skb_set_transport_header(nskb, (skb_transport_header(skb) - skb->head)); skb_reserve(nskb, header); memcpy(nskb->head, skb->head, header); memcpy(nskb->cb, skb->cb, sizeof(skb->cb)); TCP_SKB_CB(nskb)->seq = TCP_SKB_CB(nskb)->end_seq = start; __skb_queue_before(list, skb, nskb); skb_set_owner_r(nskb, sk); /* Copy data, releasing collapsed skbs. */ while (copy > 0) { int offset = start - TCP_SKB_CB(skb)->seq; int size = TCP_SKB_CB(skb)->end_seq - start; BUG_ON(offset < 0); if (size > 0) { size = min(copy, size); if (skb_copy_bits(skb, offset, skb_put(nskb, size), size)) BUG(); TCP_SKB_CB(nskb)->end_seq += size; copy -= size; start += size; } if (!before(start, TCP_SKB_CB(skb)->end_seq)) { skb = tcp_collapse_one(sk, skb, list); if (!skb || skb == tail || tcp_hdr(skb)->syn || tcp_hdr(skb)->fin) return; } } } } /* Collapse ofo queue. Algorithm: select contiguous sequence of skbs * and tcp_collapse() them until all the queue is collapsed. */ static void tcp_collapse_ofo_queue(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *skb = skb_peek(&tp->out_of_order_queue); struct sk_buff *head; u32 start, end; if (skb == NULL) return; start = TCP_SKB_CB(skb)->seq; end = TCP_SKB_CB(skb)->end_seq; head = skb; for (;;) { struct sk_buff *next = NULL; if (!skb_queue_is_last(&tp->out_of_order_queue, skb)) next = skb_queue_next(&tp->out_of_order_queue, skb); skb = next; /* Segment is terminated when we see gap or when * we are at the end of all the queue. */ if (!skb || after(TCP_SKB_CB(skb)->seq, end) || before(TCP_SKB_CB(skb)->end_seq, start)) { tcp_collapse(sk, &tp->out_of_order_queue, head, skb, start, end); head = skb; if (!skb) break; /* Start new segment */ start = TCP_SKB_CB(skb)->seq; end = TCP_SKB_CB(skb)->end_seq; } else { if (before(TCP_SKB_CB(skb)->seq, start)) start = TCP_SKB_CB(skb)->seq; if (after(TCP_SKB_CB(skb)->end_seq, end)) end = TCP_SKB_CB(skb)->end_seq; } } } /* * Purge the out-of-order queue. * Return true if queue was pruned. */ static bool tcp_prune_ofo_queue(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); bool res = false; if (!skb_queue_empty(&tp->out_of_order_queue)) { NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_OFOPRUNED); __skb_queue_purge(&tp->out_of_order_queue); /* Reset SACK state. A conforming SACK implementation will * do the same at a timeout based retransmit. When a connection * is in a sad state like this, we care only about integrity * of the connection not performance. */ if (tp->rx_opt.sack_ok) tcp_sack_reset(&tp->rx_opt); sk_mem_reclaim(sk); res = true; } return res; } /* Reduce allocated memory if we can, trying to get * the socket within its memory limits again. * * Return less than zero if we should start dropping frames * until the socket owning process reads some of the data * to stabilize the situation. */ static int tcp_prune_queue(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); SOCK_DEBUG(sk, "prune_queue: c=%x\n", tp->copied_seq); NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_PRUNECALLED); if (atomic_read(&sk->sk_rmem_alloc) >= sk->sk_rcvbuf) tcp_clamp_window(sk); else if (sk_under_memory_pressure(sk)) tp->rcv_ssthresh = min(tp->rcv_ssthresh, 4U * tp->advmss); tcp_collapse_ofo_queue(sk); if (!skb_queue_empty(&sk->sk_receive_queue)) tcp_collapse(sk, &sk->sk_receive_queue, skb_peek(&sk->sk_receive_queue), NULL, tp->copied_seq, tp->rcv_nxt); sk_mem_reclaim(sk); if (atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf) return 0; /* Collapsing did not help, destructive actions follow. * This must not ever occur. */ tcp_prune_ofo_queue(sk); if (atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf) return 0; /* If we are really being abused, tell the caller to silently * drop receive data on the floor. It will get retransmitted * and hopefully then we'll have sufficient space. */ NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_RCVPRUNED); /* Massive buffer overcommit. */ tp->pred_flags = 0; return -1; } /* RFC2861, slow part. Adjust cwnd, after it was not full during one rto. * As additional protections, we do not touch cwnd in retransmission phases, * and if application hit its sndbuf limit recently. */ void tcp_cwnd_application_limited(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); if (inet_csk(sk)->icsk_ca_state == TCP_CA_Open && sk->sk_socket && !test_bit(SOCK_NOSPACE, &sk->sk_socket->flags)) { /* Limited by application or receiver window. */ u32 init_win = tcp_init_cwnd(tp, __sk_dst_get(sk)); u32 win_used = max(tp->snd_cwnd_used, init_win); if (win_used < tp->snd_cwnd) { tp->snd_ssthresh = tcp_current_ssthresh(sk); tp->snd_cwnd = (tp->snd_cwnd + win_used) >> 1; } tp->snd_cwnd_used = 0; } tp->snd_cwnd_stamp = tcp_time_stamp; } static bool tcp_should_expand_sndbuf(const struct sock *sk) { const struct tcp_sock *tp = tcp_sk(sk); /* If the user specified a specific send buffer setting, do * not modify it. */ if (sk->sk_userlocks & SOCK_SNDBUF_LOCK) return false; /* If we are under global TCP memory pressure, do not expand. */ if (sk_under_memory_pressure(sk)) return false; /* If we are under soft global TCP memory pressure, do not expand. */ if (sk_memory_allocated(sk) >= sk_prot_mem_limits(sk, 0)) return false; /* If we filled the congestion window, do not expand. */ if (tp->packets_out >= tp->snd_cwnd) return false; return true; } /* When incoming ACK allowed to free some skb from write_queue, * we remember this event in flag SOCK_QUEUE_SHRUNK and wake up socket * on the exit from tcp input handler. * * PROBLEM: sndbuf expansion does not work well with largesend. */ static void tcp_new_space(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); if (tcp_should_expand_sndbuf(sk)) { int sndmem = SKB_TRUESIZE(max_t(u32, tp->rx_opt.mss_clamp, tp->mss_cache) + MAX_TCP_HEADER); int demanded = max_t(unsigned int, tp->snd_cwnd, tp->reordering + 1); sndmem *= 2 * demanded; if (sndmem > sk->sk_sndbuf) sk->sk_sndbuf = min(sndmem, sysctl_tcp_wmem[2]); tp->snd_cwnd_stamp = tcp_time_stamp; } sk->sk_write_space(sk); } static void tcp_check_space(struct sock *sk) { if (sock_flag(sk, SOCK_QUEUE_SHRUNK)) { sock_reset_flag(sk, SOCK_QUEUE_SHRUNK); if (sk->sk_socket && test_bit(SOCK_NOSPACE, &sk->sk_socket->flags)) tcp_new_space(sk); } } static inline void tcp_data_snd_check(struct sock *sk) { tcp_push_pending_frames(sk); tcp_check_space(sk); } /* * Check if sending an ack is needed. */ static void __tcp_ack_snd_check(struct sock *sk, int ofo_possible) { struct tcp_sock *tp = tcp_sk(sk); /* More than one full frame received... */ if (((tp->rcv_nxt - tp->rcv_wup) > (inet_csk(sk)->icsk_ack.rcv_mss) * sysctl_tcp_delack_seg && /* ... and right edge of window advances far enough. * (tcp_recvmsg() will send ACK otherwise). Or... */ __tcp_select_window(sk) >= tp->rcv_wnd) || /* We ACK each frame or... */ tcp_in_quickack_mode(sk) || /* We have out of order data. */ (ofo_possible && skb_peek(&tp->out_of_order_queue))) { /* Then ack it now */ tcp_send_ack(sk); } else { /* Else, send delayed ack. */ tcp_send_delayed_ack(sk); } } static inline void tcp_ack_snd_check(struct sock *sk) { if (!inet_csk_ack_scheduled(sk)) { /* We sent a data segment already. */ return; } __tcp_ack_snd_check(sk, 1); } /* * This routine is only called when we have urgent data * signaled. Its the 'slow' part of tcp_urg. It could be * moved inline now as tcp_urg is only called from one * place. We handle URGent data wrong. We have to - as * BSD still doesn't use the correction from RFC961. * For 1003.1g we should support a new option TCP_STDURG to permit * either form (or just set the sysctl tcp_stdurg). */ static void tcp_check_urg(struct sock *sk, const struct tcphdr *th) { struct tcp_sock *tp = tcp_sk(sk); u32 ptr = ntohs(th->urg_ptr); if (ptr && !sysctl_tcp_stdurg) ptr--; ptr += ntohl(th->seq); /* Ignore urgent data that we've already seen and read. */ if (after(tp->copied_seq, ptr)) return; /* Do not replay urg ptr. * * NOTE: interesting situation not covered by specs. * Misbehaving sender may send urg ptr, pointing to segment, * which we already have in ofo queue. We are not able to fetch * such data and will stay in TCP_URG_NOTYET until will be eaten * by recvmsg(). Seems, we are not obliged to handle such wicked * situations. But it is worth to think about possibility of some * DoSes using some hypothetical application level deadlock. */ if (before(ptr, tp->rcv_nxt)) return; /* Do we already have a newer (or duplicate) urgent pointer? */ if (tp->urg_data && !after(ptr, tp->urg_seq)) return; /* Tell the world about our new urgent pointer. */ sk_send_sigurg(sk); /* We may be adding urgent data when the last byte read was * urgent. To do this requires some care. We cannot just ignore * tp->copied_seq since we would read the last urgent byte again * as data, nor can we alter copied_seq until this data arrives * or we break the semantics of SIOCATMARK (and thus sockatmark()) * * NOTE. Double Dutch. Rendering to plain English: author of comment * above did something sort of send("A", MSG_OOB); send("B", MSG_OOB); * and expect that both A and B disappear from stream. This is _wrong_. * Though this happens in BSD with high probability, this is occasional. * Any application relying on this is buggy. Note also, that fix "works" * only in this artificial test. Insert some normal data between A and B and we will * decline of BSD again. Verdict: it is better to remove to trap * buggy users. */ if (tp->urg_seq == tp->copied_seq && tp->urg_data && !sock_flag(sk, SOCK_URGINLINE) && tp->copied_seq != tp->rcv_nxt) { struct sk_buff *skb = skb_peek(&sk->sk_receive_queue); tp->copied_seq++; if (skb && !before(tp->copied_seq, TCP_SKB_CB(skb)->end_seq)) { __skb_unlink(skb, &sk->sk_receive_queue); __kfree_skb(skb); } } tp->urg_data = TCP_URG_NOTYET; tp->urg_seq = ptr; /* Disable header prediction. */ tp->pred_flags = 0; } /* This is the 'fast' part of urgent handling. */ static void tcp_urg(struct sock *sk, struct sk_buff *skb, const struct tcphdr *th) { struct tcp_sock *tp = tcp_sk(sk); /* Check if we get a new urgent pointer - normally not. */ if (th->urg) tcp_check_urg(sk, th); /* Do we wait for any urgent data? - normally not... */ if (tp->urg_data == TCP_URG_NOTYET) { u32 ptr = tp->urg_seq - ntohl(th->seq) + (th->doff * 4) - th->syn; /* Is the urgent pointer pointing into this packet? */ if (ptr < skb->len) { u8 tmp; if (skb_copy_bits(skb, ptr, &tmp, 1)) BUG(); tp->urg_data = TCP_URG_VALID | tmp; if (!sock_flag(sk, SOCK_DEAD)) sk->sk_data_ready(sk, 0); } } } static int tcp_copy_to_iovec(struct sock *sk, struct sk_buff *skb, int hlen) { struct tcp_sock *tp = tcp_sk(sk); int chunk = skb->len - hlen; int err; local_bh_enable(); if (skb_csum_unnecessary(skb)) err = skb_copy_datagram_iovec(skb, hlen, tp->ucopy.iov, chunk); else err = skb_copy_and_csum_datagram_iovec(skb, hlen, tp->ucopy.iov); if (!err) { tp->ucopy.len -= chunk; tp->copied_seq += chunk; tcp_rcv_space_adjust(sk); } local_bh_disable(); return err; } static __sum16 __tcp_checksum_complete_user(struct sock *sk, struct sk_buff *skb) { __sum16 result; if (sock_owned_by_user(sk)) { local_bh_enable(); result = __tcp_checksum_complete(skb); local_bh_disable(); } else { result = __tcp_checksum_complete(skb); } return result; } static inline bool tcp_checksum_complete_user(struct sock *sk, struct sk_buff *skb) { return !skb_csum_unnecessary(skb) && __tcp_checksum_complete_user(sk, skb); } #ifdef CONFIG_NET_DMA static bool tcp_dma_try_early_copy(struct sock *sk, struct sk_buff *skb, int hlen) { struct tcp_sock *tp = tcp_sk(sk); int chunk = skb->len - hlen; int dma_cookie; bool copied_early = false; if (tp->ucopy.wakeup) return false; if (!tp->ucopy.dma_chan && tp->ucopy.pinned_list) tp->ucopy.dma_chan = net_dma_find_channel(); if (tp->ucopy.dma_chan && skb_csum_unnecessary(skb)) { dma_cookie = dma_skb_copy_datagram_iovec(tp->ucopy.dma_chan, skb, hlen, tp->ucopy.iov, chunk, tp->ucopy.pinned_list); if (dma_cookie < 0) goto out; tp->ucopy.dma_cookie = dma_cookie; copied_early = true; tp->ucopy.len -= chunk; tp->copied_seq += chunk; tcp_rcv_space_adjust(sk); if ((tp->ucopy.len == 0) || (tcp_flag_word(tcp_hdr(skb)) & TCP_FLAG_PSH) || (atomic_read(&sk->sk_rmem_alloc) > (sk->sk_rcvbuf >> 1))) { tp->ucopy.wakeup = 1; sk->sk_data_ready(sk, 0); } } else if (chunk > 0) { tp->ucopy.wakeup = 1; sk->sk_data_ready(sk, 0); } out: return copied_early; } #endif /* CONFIG_NET_DMA */ /* Does PAWS and seqno based validation of an incoming segment, flags will * play significant role here. */ static bool tcp_validate_incoming(struct sock *sk, struct sk_buff *skb, const struct tcphdr *th, int syn_inerr) { struct tcp_sock *tp = tcp_sk(sk); /* RFC1323: H1. Apply PAWS check first. */ if (tcp_fast_parse_options(skb, th, tp) && tp->rx_opt.saw_tstamp && tcp_paws_discard(sk, skb)) { if (!th->rst) { NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_PAWSESTABREJECTED); tcp_send_dupack(sk, skb); goto discard; } /* Reset is accepted even if it did not pass PAWS. */ } /* Step 1: check sequence number */ if (!tcp_sequence(tp, TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb)->end_seq)) { /* RFC793, page 37: "In all states except SYN-SENT, all reset * (RST) segments are validated by checking their SEQ-fields." * And page 69: "If an incoming segment is not acceptable, * an acknowledgment should be sent in reply (unless the RST * bit is set, if so drop the segment and return)". */ if (!th->rst) { if (th->syn) goto syn_challenge; tcp_send_dupack(sk, skb); } goto discard; } /* Step 2: check RST bit */ if (th->rst) { /* RFC 5961 3.2 : * If sequence number exactly matches RCV.NXT, then * RESET the connection * else * Send a challenge ACK */ if (TCP_SKB_CB(skb)->seq == tp->rcv_nxt) tcp_reset(sk); else tcp_send_challenge_ack(sk); goto discard; } /* step 3: check security and precedence [ignored] */ /* step 4: Check for a SYN * RFC 5691 4.2 : Send a challenge ack */ if (th->syn) { syn_challenge: if (syn_inerr) TCP_INC_STATS_BH(sock_net(sk), TCP_MIB_INERRS); NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPSYNCHALLENGE); tcp_send_challenge_ack(sk); goto discard; } return true; discard: __kfree_skb(skb); return false; } /* * TCP receive function for the ESTABLISHED state. * * It is split into a fast path and a slow path. The fast path is * disabled when: * - A zero window was announced from us - zero window probing * is only handled properly in the slow path. * - Out of order segments arrived. * - Urgent data is expected. * - There is no buffer space left * - Unexpected TCP flags/window values/header lengths are received * (detected by checking the TCP header against pred_flags) * - Data is sent in both directions. Fast path only supports pure senders * or pure receivers (this means either the sequence number or the ack * value must stay constant) * - Unexpected TCP option. * * When these conditions are not satisfied it drops into a standard * receive procedure patterned after RFC793 to handle all cases. * The first three cases are guaranteed by proper pred_flags setting, * the rest is checked inline. Fast processing is turned on in * tcp_data_queue when everything is OK. */ int tcp_rcv_established(struct sock *sk, struct sk_buff *skb, const struct tcphdr *th, unsigned int len) { struct tcp_sock *tp = tcp_sk(sk); if (unlikely(sk->sk_rx_dst == NULL)) inet_csk(sk)->icsk_af_ops->sk_rx_dst_set(sk, skb); /* * Header prediction. * The code loosely follows the one in the famous * "30 instruction TCP receive" Van Jacobson mail. * * Van's trick is to deposit buffers into socket queue * on a device interrupt, to call tcp_recv function * on the receive process context and checksum and copy * the buffer to user space. smart... * * Our current scheme is not silly either but we take the * extra cost of the net_bh soft interrupt processing... * We do checksum and copy also but from device to kernel. */ tp->rx_opt.saw_tstamp = 0; /* pred_flags is 0xS?10 << 16 + snd_wnd * if header_prediction is to be made * 'S' will always be tp->tcp_header_len >> 2 * '?' will be 0 for the fast path, otherwise pred_flags is 0 to * turn it off (when there are holes in the receive * space for instance) * PSH flag is ignored. */ if ((tcp_flag_word(th) & TCP_HP_BITS) == tp->pred_flags && TCP_SKB_CB(skb)->seq == tp->rcv_nxt && !after(TCP_SKB_CB(skb)->ack_seq, tp->snd_nxt)) { int tcp_header_len = tp->tcp_header_len; /* Timestamp header prediction: tcp_header_len * is automatically equal to th->doff*4 due to pred_flags * match. */ /* Check timestamp */ if (tcp_header_len == sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED) { /* No? Slow path! */ if (!tcp_parse_aligned_timestamp(tp, th)) goto slow_path; /* If PAWS failed, check it more carefully in slow path */ if ((s32)(tp->rx_opt.rcv_tsval - tp->rx_opt.ts_recent) < 0) goto slow_path; /* DO NOT update ts_recent here, if checksum fails * and timestamp was corrupted part, it will result * in a hung connection since we will drop all * future packets due to the PAWS test. */ } if (len <= tcp_header_len) { /* Bulk data transfer: sender */ if (len == tcp_header_len) { /* Predicted packet is in window by definition. * seq == rcv_nxt and rcv_wup <= rcv_nxt. * Hence, check seq<=rcv_wup reduces to: */ if (tcp_header_len == (sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED) && tp->rcv_nxt == tp->rcv_wup) tcp_store_ts_recent(tp); /* We know that such packets are checksummed * on entry. */ tcp_ack(sk, skb, 0); __kfree_skb(skb); tcp_data_snd_check(sk); return 0; } else { /* Header too small */ TCP_INC_STATS_BH(sock_net(sk), TCP_MIB_INERRS); goto discard; } } else { int eaten = 0; int copied_early = 0; bool fragstolen = false; if (tp->copied_seq == tp->rcv_nxt && len - tcp_header_len <= tp->ucopy.len) { #ifdef CONFIG_NET_DMA if (tp->ucopy.task == current && sock_owned_by_user(sk) && tcp_dma_try_early_copy(sk, skb, tcp_header_len)) { copied_early = 1; eaten = 1; } #endif if (tp->ucopy.task == current && sock_owned_by_user(sk) && !copied_early) { __set_current_state(TASK_RUNNING); if (!tcp_copy_to_iovec(sk, skb, tcp_header_len)) eaten = 1; } if (eaten) { /* Predicted packet is in window by definition. * seq == rcv_nxt and rcv_wup <= rcv_nxt. * Hence, check seq<=rcv_wup reduces to: */ if (tcp_header_len == (sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED) && tp->rcv_nxt == tp->rcv_wup) tcp_store_ts_recent(tp); tcp_rcv_rtt_measure_ts(sk, skb); __skb_pull(skb, tcp_header_len); tp->rcv_nxt = TCP_SKB_CB(skb)->end_seq; NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPHPHITSTOUSER); } if (copied_early) tcp_cleanup_rbuf(sk, skb->len); } if (!eaten) { if (tcp_checksum_complete_user(sk, skb)) goto csum_error; if ((int)skb->truesize > sk->sk_forward_alloc) goto step5; /* Predicted packet is in window by definition. * seq == rcv_nxt and rcv_wup <= rcv_nxt. * Hence, check seq<=rcv_wup reduces to: */ if (tcp_header_len == (sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED) && tp->rcv_nxt == tp->rcv_wup) tcp_store_ts_recent(tp); tcp_rcv_rtt_measure_ts(sk, skb); NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPHPHITS); /* Bulk data transfer: receiver */ eaten = tcp_queue_rcv(sk, skb, tcp_header_len, &fragstolen); } tcp_event_data_recv(sk, skb); if (TCP_SKB_CB(skb)->ack_seq != tp->snd_una) { /* Well, only one small jumplet in fast path... */ tcp_ack(sk, skb, FLAG_DATA); tcp_data_snd_check(sk); if (!inet_csk_ack_scheduled(sk)) goto no_ack; } if (!copied_early || tp->rcv_nxt != tp->rcv_wup) __tcp_ack_snd_check(sk, 0); no_ack: #ifdef CONFIG_NET_DMA if (copied_early) __skb_queue_tail(&sk->sk_async_wait_queue, skb); else #endif if (eaten) kfree_skb_partial(skb, fragstolen); sk->sk_data_ready(sk, 0); return 0; } } slow_path: if (len < (th->doff << 2) || tcp_checksum_complete_user(sk, skb)) goto csum_error; if (!th->ack && !th->rst && !th->syn) goto discard; /* * Standard slow path. */ if (!tcp_validate_incoming(sk, skb, th, 1)) return 0; step5: if (tcp_ack(sk, skb, FLAG_SLOWPATH | FLAG_UPDATE_TS_RECENT) < 0) goto discard; tcp_rcv_rtt_measure_ts(sk, skb); /* Process urgent data. */ tcp_urg(sk, skb, th); /* step 7: process the segment text */ tcp_data_queue(sk, skb); tcp_data_snd_check(sk); tcp_ack_snd_check(sk); return 0; csum_error: TCP_INC_STATS_BH(sock_net(sk), TCP_MIB_CSUMERRORS); TCP_INC_STATS_BH(sock_net(sk), TCP_MIB_INERRS); discard: __kfree_skb(skb); return 0; } EXPORT_SYMBOL(tcp_rcv_established); void tcp_finish_connect(struct sock *sk, struct sk_buff *skb) { struct tcp_sock *tp = tcp_sk(sk); struct inet_connection_sock *icsk = inet_csk(sk); tcp_set_state(sk, TCP_ESTABLISHED); if (skb != NULL) { icsk->icsk_af_ops->sk_rx_dst_set(sk, skb); security_inet_conn_established(sk, skb); } /* Make sure socket is routed, for correct metrics. */ icsk->icsk_af_ops->rebuild_header(sk); tcp_init_metrics(sk); tcp_init_congestion_control(sk); /* Prevent spurious tcp_cwnd_restart() on first data * packet. */ tp->lsndtime = tcp_time_stamp; tcp_init_buffer_space(sk); if (sock_flag(sk, SOCK_KEEPOPEN)) inet_csk_reset_keepalive_timer(sk, keepalive_time_when(tp)); if (!tp->rx_opt.snd_wscale) __tcp_fast_path_on(tp, tp->snd_wnd); else tp->pred_flags = 0; if (!sock_flag(sk, SOCK_DEAD)) { sk->sk_state_change(sk); sk_wake_async(sk, SOCK_WAKE_IO, POLL_OUT); } } static bool tcp_rcv_fastopen_synack(struct sock *sk, struct sk_buff *synack, struct tcp_fastopen_cookie *cookie) { struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *data = tp->syn_data ? tcp_write_queue_head(sk) : NULL; u16 mss = tp->rx_opt.mss_clamp; bool syn_drop; if (mss == tp->rx_opt.user_mss) { struct tcp_options_received opt; /* Get original SYNACK MSS value if user MSS sets mss_clamp */ tcp_clear_options(&opt); opt.user_mss = opt.mss_clamp = 0; tcp_parse_options(synack, &opt, 0, NULL); mss = opt.mss_clamp; } if (!tp->syn_fastopen) /* Ignore an unsolicited cookie */ cookie->len = -1; /* The SYN-ACK neither has cookie nor acknowledges the data. Presumably * the remote receives only the retransmitted (regular) SYNs: either * the original SYN-data or the corresponding SYN-ACK is lost. */ syn_drop = (cookie->len <= 0 && data && tp->total_retrans); tcp_fastopen_cache_set(sk, mss, cookie, syn_drop); if (data) { /* Retransmit unacked data in SYN */ tcp_for_write_queue_from(data, sk) { if (data == tcp_send_head(sk) || __tcp_retransmit_skb(sk, data)) break; } tcp_rearm_rto(sk); return true; } tp->syn_data_acked = tp->syn_data; return false; } static int tcp_rcv_synsent_state_process(struct sock *sk, struct sk_buff *skb, const struct tcphdr *th, unsigned int len) { struct inet_connection_sock *icsk = inet_csk(sk); struct tcp_sock *tp = tcp_sk(sk); struct tcp_fastopen_cookie foc = { .len = -1 }; int saved_clamp = tp->rx_opt.mss_clamp; tcp_parse_options(skb, &tp->rx_opt, 0, &foc); if (tp->rx_opt.saw_tstamp && tp->rx_opt.rcv_tsecr) tp->rx_opt.rcv_tsecr -= tp->tsoffset; if (th->ack) { /* rfc793: * "If the state is SYN-SENT then * first check the ACK bit * If the ACK bit is set * If SEG.ACK =< ISS, or SEG.ACK > SND.NXT, send * a reset (unless the RST bit is set, if so drop * the segment and return)" */ if (!after(TCP_SKB_CB(skb)->ack_seq, tp->snd_una) || after(TCP_SKB_CB(skb)->ack_seq, tp->snd_nxt)) goto reset_and_undo; if (tp->rx_opt.saw_tstamp && tp->rx_opt.rcv_tsecr && !between(tp->rx_opt.rcv_tsecr, tp->retrans_stamp, tcp_time_stamp)) { NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_PAWSACTIVEREJECTED); goto reset_and_undo; } /* Now ACK is acceptable. * * "If the RST bit is set * If the ACK was acceptable then signal the user "error: * connection reset", drop the segment, enter CLOSED state, * delete TCB, and return." */ if (th->rst) { tcp_reset(sk); goto discard; } /* rfc793: * "fifth, if neither of the SYN or RST bits is set then * drop the segment and return." * * See note below! * --ANK(990513) */ if (!th->syn) goto discard_and_undo; /* rfc793: * "If the SYN bit is on ... * are acceptable then ... * (our SYN has been ACKed), change the connection * state to ESTABLISHED..." */ TCP_ECN_rcv_synack(tp, th); tcp_init_wl(tp, TCP_SKB_CB(skb)->seq); tcp_ack(sk, skb, FLAG_SLOWPATH); /* Ok.. it's good. Set up sequence numbers and * move to established. */ tp->rcv_nxt = TCP_SKB_CB(skb)->seq + 1; tp->rcv_wup = TCP_SKB_CB(skb)->seq + 1; /* RFC1323: The window in SYN & SYN/ACK segments is * never scaled. */ tp->snd_wnd = ntohs(th->window); if (!tp->rx_opt.wscale_ok) { tp->rx_opt.snd_wscale = tp->rx_opt.rcv_wscale = 0; tp->window_clamp = min(tp->window_clamp, 65535U); } if (tp->rx_opt.saw_tstamp) { tp->rx_opt.tstamp_ok = 1; tp->tcp_header_len = sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED; tp->advmss -= TCPOLEN_TSTAMP_ALIGNED; tcp_store_ts_recent(tp); } else { tp->tcp_header_len = sizeof(struct tcphdr); } if (tcp_is_sack(tp) && sysctl_tcp_fack) tcp_enable_fack(tp); tcp_mtup_init(sk); tcp_sync_mss(sk, icsk->icsk_pmtu_cookie); tcp_initialize_rcv_mss(sk); /* Remember, tcp_poll() does not lock socket! * Change state from SYN-SENT only after copied_seq * is initialized. */ tp->copied_seq = tp->rcv_nxt; smp_mb(); tcp_finish_connect(sk, skb); if ((tp->syn_fastopen || tp->syn_data) && tcp_rcv_fastopen_synack(sk, skb, &foc)) return -1; if (sk->sk_write_pending || icsk->icsk_accept_queue.rskq_defer_accept || icsk->icsk_ack.pingpong) { /* Save one ACK. Data will be ready after * several ticks, if write_pending is set. * * It may be deleted, but with this feature tcpdumps * look so _wonderfully_ clever, that I was not able * to stand against the temptation 8) --ANK */ inet_csk_schedule_ack(sk); icsk->icsk_ack.lrcvtime = tcp_time_stamp; tcp_enter_quickack_mode(sk); inet_csk_reset_xmit_timer(sk, ICSK_TIME_DACK, TCP_DELACK_MAX, TCP_RTO_MAX); discard: __kfree_skb(skb); return 0; } else { tcp_send_ack(sk); } return -1; } /* No ACK in the segment */ if (th->rst) { /* rfc793: * "If the RST bit is set * * Otherwise (no ACK) drop the segment and return." */ goto discard_and_undo; } /* PAWS check. */ if (tp->rx_opt.ts_recent_stamp && tp->rx_opt.saw_tstamp && tcp_paws_reject(&tp->rx_opt, 0)) goto discard_and_undo; if (th->syn) { /* We see SYN without ACK. It is attempt of * simultaneous connect with crossed SYNs. * Particularly, it can be connect to self. */ tcp_set_state(sk, TCP_SYN_RECV); if (tp->rx_opt.saw_tstamp) { tp->rx_opt.tstamp_ok = 1; tcp_store_ts_recent(tp); tp->tcp_header_len = sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED; } else { tp->tcp_header_len = sizeof(struct tcphdr); } tp->rcv_nxt = TCP_SKB_CB(skb)->seq + 1; tp->rcv_wup = TCP_SKB_CB(skb)->seq + 1; /* RFC1323: The window in SYN & SYN/ACK segments is * never scaled. */ tp->snd_wnd = ntohs(th->window); tp->snd_wl1 = TCP_SKB_CB(skb)->seq; tp->max_window = tp->snd_wnd; TCP_ECN_rcv_syn(tp, th); tcp_mtup_init(sk); tcp_sync_mss(sk, icsk->icsk_pmtu_cookie); tcp_initialize_rcv_mss(sk); tcp_send_synack(sk); #if 0 /* Note, we could accept data and URG from this segment. * There are no obstacles to make this (except that we must * either change tcp_recvmsg() to prevent it from returning data * before 3WHS completes per RFC793, or employ TCP Fast Open). * * However, if we ignore data in ACKless segments sometimes, * we have no reasons to accept it sometimes. * Also, seems the code doing it in step6 of tcp_rcv_state_process * is not flawless. So, discard packet for sanity. * Uncomment this return to process the data. */ return -1; #else goto discard; #endif } /* "fifth, if neither of the SYN or RST bits is set then * drop the segment and return." */ discard_and_undo: tcp_clear_options(&tp->rx_opt); tp->rx_opt.mss_clamp = saved_clamp; goto discard; reset_and_undo: tcp_clear_options(&tp->rx_opt); tp->rx_opt.mss_clamp = saved_clamp; return 1; } /* * This function implements the receiving procedure of RFC 793 for * all states except ESTABLISHED and TIME_WAIT. * It's called from both tcp_v4_rcv and tcp_v6_rcv and should be * address independent. */ int tcp_rcv_state_process(struct sock *sk, struct sk_buff *skb, const struct tcphdr *th, unsigned int len) { struct tcp_sock *tp = tcp_sk(sk); struct inet_connection_sock *icsk = inet_csk(sk); struct request_sock *req; int queued = 0; tp->rx_opt.saw_tstamp = 0; switch (sk->sk_state) { case TCP_CLOSE: goto discard; case TCP_LISTEN: if (th->ack) return 1; if (th->rst) goto discard; if (th->syn) { if (th->fin) goto discard; if (icsk->icsk_af_ops->conn_request(sk, skb) < 0) return 1; /* Now we have several options: In theory there is * nothing else in the frame. KA9Q has an option to * send data with the syn, BSD accepts data with the * syn up to the [to be] advertised window and * Solaris 2.1 gives you a protocol error. For now * we just ignore it, that fits the spec precisely * and avoids incompatibilities. It would be nice in * future to drop through and process the data. * * Now that TTCP is starting to be used we ought to * queue this data. * But, this leaves one open to an easy denial of * service attack, and SYN cookies can't defend * against this problem. So, we drop the data * in the interest of security over speed unless * it's still in use. */ kfree_skb(skb); return 0; } goto discard; case TCP_SYN_SENT: queued = tcp_rcv_synsent_state_process(sk, skb, th, len); if (queued >= 0) return queued; /* Do step6 onward by hand. */ tcp_urg(sk, skb, th); __kfree_skb(skb); tcp_data_snd_check(sk); return 0; } req = tp->fastopen_rsk; if (req != NULL) { WARN_ON_ONCE(sk->sk_state != TCP_SYN_RECV && sk->sk_state != TCP_FIN_WAIT1); if (tcp_check_req(sk, skb, req, NULL, true) == NULL) goto discard; } if (!th->ack && !th->rst && !th->syn) goto discard; if (!tcp_validate_incoming(sk, skb, th, 0)) return 0; /* step 5: check the ACK field */ if (true) { int acceptable = tcp_ack(sk, skb, FLAG_SLOWPATH | FLAG_UPDATE_TS_RECENT) > 0; switch (sk->sk_state) { case TCP_SYN_RECV: if (acceptable) { /* Once we leave TCP_SYN_RECV, we no longer * need req so release it. */ if (req) { tcp_synack_rtt_meas(sk, req); tp->total_retrans = req->num_retrans; reqsk_fastopen_remove(sk, req, false); } else { /* Make sure socket is routed, for * correct metrics. */ icsk->icsk_af_ops->rebuild_header(sk); tcp_init_congestion_control(sk); tcp_mtup_init(sk); tcp_init_buffer_space(sk); tp->copied_seq = tp->rcv_nxt; } smp_mb(); tcp_set_state(sk, TCP_ESTABLISHED); sk->sk_state_change(sk); /* Note, that this wakeup is only for marginal * crossed SYN case. Passively open sockets * are not waked up, because sk->sk_sleep == * NULL and sk->sk_socket == NULL. */ if (sk->sk_socket) sk_wake_async(sk, SOCK_WAKE_IO, POLL_OUT); tp->snd_una = TCP_SKB_CB(skb)->ack_seq; tp->snd_wnd = ntohs(th->window) << tp->rx_opt.snd_wscale; tcp_init_wl(tp, TCP_SKB_CB(skb)->seq); if (tp->rx_opt.tstamp_ok) tp->advmss -= TCPOLEN_TSTAMP_ALIGNED; if (req) { /* Re-arm the timer because data may * have been sent out. This is similar * to the regular data transmission case * when new data has just been ack'ed. * * (TFO) - we could try to be more * aggressive and retranmitting any data * sooner based on when they were sent * out. */ tcp_rearm_rto(sk); } else tcp_init_metrics(sk); tcp_update_pacing_rate(sk); /* Prevent spurious tcp_cwnd_restart() on * first data packet. */ tp->lsndtime = tcp_time_stamp; tcp_initialize_rcv_mss(sk); tcp_fast_path_on(tp); } else { return 1; } break; case TCP_FIN_WAIT1: /* If we enter the TCP_FIN_WAIT1 state and we are a * Fast Open socket and this is the first acceptable * ACK we have received, this would have acknowledged * our SYNACK so stop the SYNACK timer. */ if (req != NULL) { /* Return RST if ack_seq is invalid. * Note that RFC793 only says to generate a * DUPACK for it but for TCP Fast Open it seems * better to treat this case like TCP_SYN_RECV * above. */ if (!acceptable) return 1; /* We no longer need the request sock. */ reqsk_fastopen_remove(sk, req, false); tcp_rearm_rto(sk); } if (tp->snd_una == tp->write_seq) { struct dst_entry *dst; tcp_set_state(sk, TCP_FIN_WAIT2); sk->sk_shutdown |= SEND_SHUTDOWN; dst = __sk_dst_get(sk); if (dst) dst_confirm(dst); if (!sock_flag(sk, SOCK_DEAD)) /* Wake up lingering close() */ sk->sk_state_change(sk); else { int tmo; if (tp->linger2 < 0 || (TCP_SKB_CB(skb)->end_seq != TCP_SKB_CB(skb)->seq && after(TCP_SKB_CB(skb)->end_seq - th->fin, tp->rcv_nxt))) { tcp_done(sk); NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPABORTONDATA); return 1; } tmo = tcp_fin_time(sk); if (tmo > TCP_TIMEWAIT_LEN) { inet_csk_reset_keepalive_timer(sk, tmo - TCP_TIMEWAIT_LEN); } else if (th->fin || sock_owned_by_user(sk)) { /* Bad case. We could lose such FIN otherwise. * It is not a big problem, but it looks confusing * and not so rare event. We still can lose it now, * if it spins in bh_lock_sock(), but it is really * marginal case. */ inet_csk_reset_keepalive_timer(sk, tmo); } else { tcp_time_wait(sk, TCP_FIN_WAIT2, tmo); goto discard; } } } break; case TCP_CLOSING: if (tp->snd_una == tp->write_seq) { tcp_time_wait(sk, TCP_TIME_WAIT, 0); goto discard; } break; case TCP_LAST_ACK: if (tp->snd_una == tp->write_seq) { tcp_update_metrics(sk); tcp_done(sk); goto discard; } break; } } /* step 6: check the URG bit */ tcp_urg(sk, skb, th); /* step 7: process the segment text */ switch (sk->sk_state) { case TCP_CLOSE_WAIT: case TCP_CLOSING: case TCP_LAST_ACK: if (!before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt)) break; case TCP_FIN_WAIT1: case TCP_FIN_WAIT2: /* RFC 793 says to queue data in these states, * RFC 1122 says we MUST send a reset. * BSD 4.4 also does reset. */ if (sk->sk_shutdown & RCV_SHUTDOWN) { if (TCP_SKB_CB(skb)->end_seq != TCP_SKB_CB(skb)->seq && after(TCP_SKB_CB(skb)->end_seq - th->fin, tp->rcv_nxt)) { NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPABORTONDATA); tcp_reset(sk); return 1; } } /* Fall through */ case TCP_ESTABLISHED: tcp_data_queue(sk, skb); queued = 1; break; } /* tcp_data could move socket to TIME-WAIT */ if (sk->sk_state != TCP_CLOSE) { tcp_data_snd_check(sk); tcp_ack_snd_check(sk); } if (!queued) { discard: __kfree_skb(skb); } return 0; } EXPORT_SYMBOL(tcp_rcv_state_process);
GameTheory-/android_kernel_g4stylusn2
net/ipv4/tcp_input.c
C
gpl-2.0
170,266
from Source import Source from Components.Element import cached from Components.SystemInfo import SystemInfo from enigma import eServiceReference StreamServiceList = [] class StreamService(Source): def __init__(self, navcore): Source.__init__(self) self.ref = None self.__service = None self.navcore = navcore def serviceEvent(self, event): pass @cached def getService(self): return self.__service service = property(getService) def handleCommand(self, cmd): print "[StreamService] handle command", cmd self.ref = eServiceReference(cmd) def recordEvent(self, service, event): if service is self.__service: return print "[StreamService] RECORD event for us:", service self.changed((self.CHANGED_ALL, )) def execBegin(self): if self.ref is None: print "[StreamService] has no service ref set" return print "[StreamService]e execBegin", self.ref.toString() if SystemInfo["CanNotDoSimultaneousTranscodeAndPIP"]: from Screens.InfoBar import InfoBar if InfoBar.instance and hasattr(InfoBar.instance.session, 'pipshown') and InfoBar.instance.session.pipshown: hasattr(InfoBar.instance, "showPiP") and InfoBar.instance.showPiP() print "[StreamService] try to disable pip before start stream" if hasattr(InfoBar.instance.session, 'pip'): del InfoBar.instance.session.pip InfoBar.instance.session.pipshown = False self.__service = self.navcore.recordService(self.ref) self.navcore.record_event.append(self.recordEvent) if self.__service is not None: if self.__service.__deref__() not in StreamServiceList: StreamServiceList.append(self.__service.__deref__()) self.__service.prepareStreaming() self.__service.start() def execEnd(self): print "[StreamService] execEnd", self.ref.toString() self.navcore.record_event.remove(self.recordEvent) if self.__service is not None: if self.__service.__deref__() in StreamServiceList: StreamServiceList.remove(self.__service.__deref__()) self.navcore.stopRecordService(self.__service) self.__service = None self.ref = None
Dima73/enigma2
lib/python/Components/Sources/StreamService.py
Python
gpl-2.0
2,074
<?php /** * Template Name: Wide Page Template * * Description: A page template that provides a key component of WordPress as a CMS * by meeting the need for a carefully crafted introductory page. The front page template * in Twenty Twelve consists of a page content area for adding text, images, video -- * anything you'd like -- followed by front-page-only widgets in one or two columns. * * @package WordPress * @subpackage Plum_Tree * @since Plum Tree 0.1 */ get_header(); ?> <?php if ( have_posts() ) : ?> <?php while ( have_posts() ) : the_post(); ?> <?php if ( (get_option('blog_spacer_bg_color') != '') && (get_option('blog_spacer_bg_color') != '#fff') ) { $spacer_bg = 'style="background:'.get_option('blog_spacer_bg_color').';"'; } elseif ( get_option('blog_spacer_custom_pattern') != '' ) { $spacer_bg = 'style="background: url('.get_option('blog_spacer_custom_pattern').') repeat;"'; } else { $spacer_bg = 'style="background: url('.get_template_directory_uri().'/assets/spacer-'.get_option('blog_spacer_default_pattern').'.png) repeat;"'; } ?> <div class="spacer" <?php echo $spacer_bg; ?> data-stellar-background-ratio="0.5"> <div class="container-fluid"> <div class="row-fluid"> <h1 class="spacer-title" data-stellar-ratio="0.93"><?php the_title(); ?></h1> </div> </div> </div> <section id="content" role="main" class="site-content"><!-- Main content --> <div class="entry-content"> <?php the_content(); ?> </div><!-- .entry-content --> <?php endwhile; ?> <?php endif; ?> </section><!-- Main content --> <?php get_footer(); ?>
as1anhawk/ICT2_Team3
wp-content/themes/clickboutique/page-templates/page-wide.php
PHP
gpl-2.0
1,843
<html lang="en"> <head> <title>Context management - Debugging with GDB</title> <meta http-equiv="Content-Type" content="text/html"> <meta name="description" content="Debugging with GDB"> <meta name="generator" content="makeinfo 4.13"> <link title="Top" rel="start" href="index.html#Top"> <link rel="up" href="GDB_002fMI-General-Design.html#GDB_002fMI-General-Design" title="GDB/MI General Design"> <link rel="next" href="Asynchronous-and-non_002dstop-modes.html#Asynchronous-and-non_002dstop-modes" title="Asynchronous and non-stop modes"> <link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage"> <!-- Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with the Invariant Sections being ``Free Software'' and ``Free Software Needs Free Documentation'', with the Front-Cover Texts being ``A GNU Manual,'' and with the Back-Cover Texts as in (a) below. (a) The FSF's Back-Cover Text is: ``You are free to copy and modify this GNU Manual. Buying copies from GNU Press supports the FSF in developing GNU and promoting software freedom.''--> <meta http-equiv="Content-Style-Type" content="text/css"> <style type="text/css"><!-- pre.display { font-family:inherit } pre.format { font-family:inherit } pre.smalldisplay { font-family:inherit; font-size:smaller } pre.smallformat { font-family:inherit; font-size:smaller } pre.smallexample { font-size:smaller } pre.smalllisp { font-size:smaller } span.sc { font-variant:small-caps } span.roman { font-family:serif; font-weight:normal; } span.sansserif { font-family:sans-serif; font-weight:normal; } --></style> <link rel="stylesheet" type="text/css" href="../cs.css"> </head> <body> <div class="node"> <a name="Context-management"></a> <p> Next:&nbsp;<a rel="next" accesskey="n" href="Asynchronous-and-non_002dstop-modes.html#Asynchronous-and-non_002dstop-modes">Asynchronous and non-stop modes</a>, Up:&nbsp;<a rel="up" accesskey="u" href="GDB_002fMI-General-Design.html#GDB_002fMI-General-Design">GDB/MI General Design</a> <hr> </div> <h4 class="subsection">27.1.1 Context management</h4> <p>In most cases when <span class="sc">gdb</span> accesses the target, this access is done in context of a specific thread and frame (see <a href="Frames.html#Frames">Frames</a>). Often, even when accessing global data, the target requires that a thread be specified. The CLI interface maintains the selected thread and frame, and supplies them to target on each command. This is convenient, because a command line user would not want to specify that information explicitly on each command, and because user interacts with <span class="sc">gdb</span> via a single terminal, so no confusion is possible as to what thread and frame are the current ones. <p>In the case of MI, the concept of selected thread and frame is less useful. First, a frontend can easily remember this information itself. Second, a graphical frontend can have more than one window, each one used for debugging a different thread, and the frontend might want to access additional threads for internal purposes. This increases the risk that by relying on implicitly selected thread, the frontend may be operating on a wrong one. Therefore, each MI command should explicitly specify which thread and frame to operate on. To make it possible, each MI command accepts the &lsquo;<samp><span class="samp">--thread</span></samp>&rsquo; and &lsquo;<samp><span class="samp">--frame</span></samp>&rsquo; options, the value to each is <span class="sc">gdb</span> identifier for thread and frame to operate on. <p>Usually, each top-level window in a frontend allows the user to select a thread and a frame, and remembers the user selection for further operations. However, in some cases <span class="sc">gdb</span> may suggest that the current thread be changed. For example, when stopping on a breakpoint it is reasonable to switch to the thread where breakpoint is hit. For another example, if the user issues the CLI &lsquo;<samp><span class="samp">thread</span></samp>&rsquo; command via the frontend, it is desirable to change the frontend's selected thread to the one specified by user. <span class="sc">gdb</span> communicates the suggestion to change current thread using the &lsquo;<samp><span class="samp">=thread-selected</span></samp>&rsquo; notification. No such notification is available for the selected frame at the moment. <p>Note that historically, MI shares the selected thread with CLI, so frontends used the <code>-thread-select</code> to execute commands in the right context. However, getting this to work right is cumbersome. The simplest way is for frontend to emit <code>-thread-select</code> command before every command. This doubles the number of commands that need to be sent. The alternative approach is to suppress <code>-thread-select</code> if the selected thread in <span class="sc">gdb</span> is supposed to be identical to the thread the frontend wants to operate on. However, getting this optimization right can be tricky. In particular, if the frontend sends several commands to <span class="sc">gdb</span>, and one of the commands changes the selected thread, then the behaviour of subsequent commands will change. So, a frontend should either wait for response from such problematic commands, or explicitly add <code>-thread-select</code> for all subsequent commands. No frontend is known to do this exactly right, so it is suggested to just always pass the &lsquo;<samp><span class="samp">--thread</span></samp>&rsquo; and &lsquo;<samp><span class="samp">--frame</span></samp>&rsquo; options. </body></html>
byeonggonlee/lynx-ns-gb
toolchain/share/doc/arm-arm-none-eabi/html/gdb/Context-management.html
HTML
gpl-2.0
5,980
int main() { if(true) {return 1;} else if(true) {return 1;} else {return 1;} }
brmqk3/uncrustify
tests/output/cpp/34171-i1181.cpp
C++
gpl-2.0
81
#!/usr/bin/python # -*- coding: utf-8 -*- # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = r''' --- module: aci_tenant_span_dst_group short_description: Manage SPAN destination groups (span:DestGrp) description: - Manage SPAN destination groups on Cisco ACI fabrics. notes: - The C(tenant) used must exist before using this module in your playbook. The M(aci_tenant) module can be used for this. - More information about the internal APIC class B(span:DestGrp) from L(the APIC Management Information Model reference,https://developer.cisco.com/docs/apic-mim-ref/). author: - Dag Wieers (@dagwieers) version_added: '2.4' options: dst_group: description: - The name of the SPAN destination group. required: yes aliases: [ name ] description: description: - The description of the SPAN destination group. aliases: [ descr ] tenant: description: - The name of the tenant. required: yes aliases: [ tenant_name ] state: description: - Use C(present) or C(absent) for adding or removing. - Use C(query) for listing an object or multiple objects. choices: [ absent, present, query ] default: present extends_documentation_fragment: aci ''' # FIXME: Add more, better examples EXAMPLES = r''' - aci_tenant_span_dst_group: host: apic username: admin password: SomeSecretPassword dst_group: '{{ dst_group }}' description: '{{ descr }}' tenant: '{{ tenant }}' ''' RETURN = r''' current: description: The existing configuration from the APIC after the module has finished returned: success type: list sample: [ { "fvTenant": { "attributes": { "descr": "Production environment", "dn": "uni/tn-production", "name": "production", "nameAlias": "", "ownerKey": "", "ownerTag": "" } } } ] error: description: The error information as returned from the APIC returned: failure type: dict sample: { "code": "122", "text": "unknown managed object class foo" } raw: description: The raw output returned by the APIC REST API (xml or json) returned: parse error type: string sample: '<?xml version="1.0" encoding="UTF-8"?><imdata totalCount="1"><error code="122" text="unknown managed object class foo"/></imdata>' sent: description: The actual/minimal configuration pushed to the APIC returned: info type: list sample: { "fvTenant": { "attributes": { "descr": "Production environment" } } } previous: description: The original configuration from the APIC before the module has started returned: info type: list sample: [ { "fvTenant": { "attributes": { "descr": "Production", "dn": "uni/tn-production", "name": "production", "nameAlias": "", "ownerKey": "", "ownerTag": "" } } } ] proposed: description: The assembled configuration from the user-provided parameters returned: info type: dict sample: { "fvTenant": { "attributes": { "descr": "Production environment", "name": "production" } } } filter_string: description: The filter string used for the request returned: failure or debug type: string sample: ?rsp-prop-include=config-only method: description: The HTTP method used for the request to the APIC returned: failure or debug type: string sample: POST response: description: The HTTP response from the APIC returned: failure or debug type: string sample: OK (30 bytes) status: description: The HTTP status from the APIC returned: failure or debug type: int sample: 200 url: description: The HTTP url used for the request to the APIC returned: failure or debug type: string sample: https://10.11.12.13/api/mo/uni/tn-production.json ''' from ansible.module_utils.network.aci.aci import ACIModule, aci_argument_spec from ansible.module_utils.basic import AnsibleModule def main(): argument_spec = aci_argument_spec() argument_spec.update( dst_group=dict(type='str', required=False, aliases=['name']), # Not required for querying all objects tenant=dict(type='str', required=False, aliases=['tenant_name']), # Not required for querying all objects description=dict(type='str', aliases=['descr']), state=dict(type='str', default='present', choices=['absent', 'present', 'query']), ) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, required_if=[ ['state', 'absent', ['dst_group', 'tenant']], ['state', 'present', ['dst_group', 'tenant']], ], ) dst_group = module.params['dst_group'] description = module.params['description'] state = module.params['state'] tenant = module.params['tenant'] aci = ACIModule(module) aci.construct_url( root_class=dict( aci_class='fvTenant', aci_rn='tn-{0}'.format(tenant), filter_target='eq(fvTenant.name, "{0}")'.format(tenant), module_object=tenant, ), subclass_1=dict( aci_class='spanDestGrp', aci_rn='destgrp-{0}'.format(dst_group), filter_target='eq(spanDestGrp.name, "{0}")'.format(dst_group), module_object=dst_group, ), ) aci.get_existing() if state == 'present': aci.payload( aci_class='spanDestGrp', class_config=dict( name=dst_group, descr=description, ), ) aci.get_diff(aci_class='spanDestGrp') aci.post_config() elif state == 'absent': aci.delete_config() aci.exit_json() if __name__ == "__main__": main()
hryamzik/ansible
lib/ansible/modules/network/aci/aci_tenant_span_dst_group.py
Python
gpl-3.0
6,414
/* * libtcod 1.5.1 * Copyright (c) 2008,2009,2010,2012 Jice & Mingos * 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. * * The name of Jice or Mingos may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY JICE AND MINGOS ``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 JICE OR MINGOS 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 _TCOD_ZIP_H #define _TCOD_ZIP_H typedef void *TCOD_zip_t; TCODLIB_API TCOD_zip_t TCOD_zip_new(); TCODLIB_API void TCOD_zip_delete(TCOD_zip_t zip); /* output interface */ TCODLIB_API void TCOD_zip_put_char(TCOD_zip_t zip, char val); TCODLIB_API void TCOD_zip_put_int(TCOD_zip_t zip, int val); TCODLIB_API void TCOD_zip_put_float(TCOD_zip_t zip, float val); TCODLIB_API void TCOD_zip_put_string(TCOD_zip_t zip, const char *val); TCODLIB_API void TCOD_zip_put_color(TCOD_zip_t zip, const TCOD_color_t val); TCODLIB_API void TCOD_zip_put_image(TCOD_zip_t zip, const TCOD_image_t val); TCODLIB_API void TCOD_zip_put_console(TCOD_zip_t zip, const TCOD_console_t val); TCODLIB_API void TCOD_zip_put_data(TCOD_zip_t zip, int nbBytes, const void *data); TCODLIB_API uint32 TCOD_zip_get_current_bytes(TCOD_zip_t zip); TCODLIB_API int TCOD_zip_save_to_file(TCOD_zip_t zip, const char *filename); /* input interface */ TCODLIB_API int TCOD_zip_load_from_file(TCOD_zip_t zip, const char *filename); TCODLIB_API char TCOD_zip_get_char(TCOD_zip_t zip); TCODLIB_API int TCOD_zip_get_int(TCOD_zip_t zip); TCODLIB_API float TCOD_zip_get_float(TCOD_zip_t zip); TCODLIB_API const char *TCOD_zip_get_string(TCOD_zip_t zip); TCODLIB_API TCOD_color_t TCOD_zip_get_color(TCOD_zip_t zip); TCODLIB_API TCOD_image_t TCOD_zip_get_image(TCOD_zip_t zip); TCODLIB_API TCOD_console_t TCOD_zip_get_console(TCOD_zip_t zip); TCODLIB_API int TCOD_zip_get_data(TCOD_zip_t zip, int nbBytes, void *data); TCODLIB_API uint32 TCOD_zip_get_remaining_bytes(TCOD_zip_t zip); TCODLIB_API void TCOD_zip_skip_bytes(TCOD_zip_t zip, uint32 nbBytes); #endif
pasoev/innfin
src/oldcot/zip.h
C
gpl-3.0
3,130
Clazz.declarePackage ("JSV.common"); Clazz.load (["java.lang.Enum", "JSV.source.JDXDataObject", "JU.Lst"], "JSV.common.Spectrum", ["java.lang.Boolean", "$.Double", "java.util.Hashtable", "JU.PT", "JSV.common.Coordinate", "$.Parameters", "$.PeakInfo", "JSV.source.JDXSourceStreamTokenizer", "JU.Logger"], function () { c$ = Clazz.decorateAsClass (function () { this.subSpectra = null; this.peakList = null; this.piUnitsX = null; this.piUnitsY = null; this.selectedPeak = null; this.highlightedPeak = null; this.specShift = 0; this.currentSubSpectrumIndex = 0; this.$isForcedSubset = false; this.id = ""; this.convertedSpectrum = null; this.userYFactor = 1; this.exportXAxisLeftToRight = false; this.fillColor = null; Clazz.instantialize (this, arguments); }, JSV.common, "Spectrum", JSV.source.JDXDataObject); Clazz.prepareFields (c$, function () { this.peakList = new JU.Lst (); }); Clazz.overrideMethod (c$, "finalize", function () { System.out.println ("JDXSpectrum " + this + " finalized " + this.title); }); Clazz.defineMethod (c$, "dispose", function () { }); Clazz.defineMethod (c$, "isForcedSubset", function () { return this.$isForcedSubset; }); Clazz.defineMethod (c$, "setId", function (id) { this.id = id; }, "~S"); Clazz.makeConstructor (c$, function () { Clazz.superConstructor (this, JSV.common.Spectrum, []); this.headerTable = new JU.Lst (); this.xyCoords = new Array (0); this.parent = this; }); Clazz.defineMethod (c$, "copy", function () { var newSpectrum = new JSV.common.Spectrum (); this.copyTo (newSpectrum); newSpectrum.setPeakList (this.peakList, this.piUnitsX, null); newSpectrum.fillColor = this.fillColor; return newSpectrum; }); Clazz.defineMethod (c$, "getXYCoords", function () { return this.getCurrentSubSpectrum ().xyCoords; }); Clazz.defineMethod (c$, "getPeakList", function () { return this.peakList; }); Clazz.defineMethod (c$, "setPeakList", function (list, piUnitsX, piUnitsY) { this.peakList = list; this.piUnitsX = piUnitsX; this.piUnitsY = piUnitsY; for (var i = list.size (); --i >= 0; ) this.peakList.get (i).spectrum = this; if (JU.Logger.debugging) JU.Logger.info ("Spectrum " + this.getTitle () + " peaks: " + list.size ()); return list.size (); }, "JU.Lst,~S,~S"); Clazz.defineMethod (c$, "selectPeakByFileIndex", function (filePath, index, atomKey) { if (this.peakList != null && this.peakList.size () > 0 && (atomKey == null || this.sourceID.equals (index))) for (var i = 0; i < this.peakList.size (); i++) if (this.peakList.get (i).checkFileIndex (filePath, index, atomKey)) { System.out.println ("selecting peak by FileIndex " + this + " " + this.peakList.get (i)); return (this.selectedPeak = this.peakList.get (i)); } return null; }, "~S,~S,~S"); Clazz.defineMethod (c$, "selectPeakByFilePathTypeModel", function (filePath, type, model) { if (this.peakList != null && this.peakList.size () > 0) for (var i = 0; i < this.peakList.size (); i++) if (this.peakList.get (i).checkFileTypeModel (filePath, type, model)) { System.out.println ("selecting peak byFilePathTypeModel " + this + " " + this.peakList.get (i)); return (this.selectedPeak = this.peakList.get (i)); } return null; }, "~S,~S,~S"); Clazz.defineMethod (c$, "matchesPeakTypeModel", function (type, model) { if (type.equals ("ID")) return (this.sourceID.equalsIgnoreCase (model)); if (this.peakList != null && this.peakList.size () > 0) for (var i = 0; i < this.peakList.size (); i++) if (this.peakList.get (i).checkTypeModel (type, model)) return true; return false; }, "~S,~S"); Clazz.defineMethod (c$, "setSelectedPeak", function (peak) { this.selectedPeak = peak; }, "JSV.common.PeakInfo"); Clazz.defineMethod (c$, "setHighlightedPeak", function (peak) { this.highlightedPeak = peak; }, "JSV.common.PeakInfo"); Clazz.defineMethod (c$, "getSelectedPeak", function () { return this.selectedPeak; }); Clazz.defineMethod (c$, "getModelPeakInfoForAutoSelectOnLoad", function () { if (this.peakList != null) for (var i = 0; i < this.peakList.size (); i++) if (this.peakList.get (i).autoSelectOnLoad ()) return this.peakList.get (i); return null; }); Clazz.defineMethod (c$, "getAssociatedPeakInfo", function (xPixel, coord) { this.selectedPeak = this.findPeakByCoord (xPixel, coord); return (this.selectedPeak == null ? this.getBasePeakInfo () : this.selectedPeak); }, "~N,JSV.common.Coordinate"); Clazz.defineMethod (c$, "findPeakByCoord", function (xPixel, coord) { if (coord != null && this.peakList != null && this.peakList.size () > 0) { var xVal = coord.getXVal (); var iBest = -1; var dBest = 1e100; for (var i = 0; i < this.peakList.size (); i++) { var d = this.peakList.get (i).checkRange (xPixel, xVal); if (d < dBest) { dBest = d; iBest = i; }} if (iBest >= 0) return this.peakList.get (iBest); }return null; }, "~N,JSV.common.Coordinate"); Clazz.defineMethod (c$, "getPeakTitle", function () { return (this.selectedPeak != null ? this.selectedPeak.getTitle () : this.highlightedPeak != null ? this.highlightedPeak.getTitle () : this.getTitleLabel ()); }); Clazz.defineMethod (c$, "getTitleLabel", function () { var type = (this.peakList == null || this.peakList.size () == 0 ? this.getQualifiedDataType () : this.peakList.get (0).getType ()); if (type != null && type.startsWith ("NMR")) { if (this.nucleusY != null && !this.nucleusY.equals ("?")) { type = "2D" + type; } else { type = this.nucleusX + type; }}return (type != null && type.length > 0 ? type + " " : "") + this.getTitle (); }); Clazz.defineMethod (c$, "setNextPeak", function (coord, istep) { if (this.peakList == null || this.peakList.size () == 0) return -1; var x0 = coord.getXVal () + istep * 0.000001; var ipt1 = -1; var ipt2 = -1; var dmin1 = 1.7976931348623157E308 * istep; var dmin2 = 0; for (var i = this.peakList.size (); --i >= 0; ) { var x = this.peakList.get (i).getX (); if (istep > 0) { if (x > x0 && x < dmin1) { ipt1 = i; dmin1 = x; } else if (x < x0 && x - x0 < dmin2) { ipt2 = i; dmin2 = x - x0; }} else { if (x < x0 && x > dmin1) { ipt1 = i; dmin1 = x; } else if (x > x0 && x - x0 > dmin2) { ipt2 = i; dmin2 = x - x0; }}} if (ipt1 < 0) { if (ipt2 < 0) return -1; ipt1 = ipt2; }return ipt1; }, "JSV.common.Coordinate,~N"); Clazz.defineMethod (c$, "getPercentYValueAt", function (x) { if (!this.isContinuous ()) return NaN; return this.getYValueAt (x); }, "~N"); Clazz.defineMethod (c$, "getYValueAt", function (x) { return JSV.common.Coordinate.getYValueAt (this.xyCoords, x); }, "~N"); Clazz.defineMethod (c$, "setUserYFactor", function (userYFactor) { this.userYFactor = userYFactor; }, "~N"); Clazz.defineMethod (c$, "getUserYFactor", function () { return this.userYFactor; }); Clazz.defineMethod (c$, "getConvertedSpectrum", function () { return this.convertedSpectrum; }); Clazz.defineMethod (c$, "setConvertedSpectrum", function (spectrum) { this.convertedSpectrum = spectrum; }, "JSV.common.Spectrum"); c$.taConvert = Clazz.defineMethod (c$, "taConvert", function (spectrum, mode) { if (!spectrum.isContinuous ()) return spectrum; switch (mode) { case JSV.common.Spectrum.IRMode.NO_CONVERT: return spectrum; case JSV.common.Spectrum.IRMode.TO_ABS: if (!spectrum.isTransmittance ()) return spectrum; break; case JSV.common.Spectrum.IRMode.TO_TRANS: if (!spectrum.isAbsorbance ()) return spectrum; break; case JSV.common.Spectrum.IRMode.TOGGLE: break; } var spec = spectrum.getConvertedSpectrum (); return (spec != null ? spec : spectrum.isAbsorbance () ? JSV.common.Spectrum.toT (spectrum) : JSV.common.Spectrum.toA (spectrum)); }, "JSV.common.Spectrum,JSV.common.Spectrum.IRMode"); c$.toT = Clazz.defineMethod (c$, "toT", function (spectrum) { if (!spectrum.isAbsorbance ()) return null; var xyCoords = spectrum.getXYCoords (); var newXYCoords = new Array (xyCoords.length); if (!JSV.common.Coordinate.isYInRange (xyCoords, 0, 4.0)) xyCoords = JSV.common.Coordinate.normalise (xyCoords, 0, 4.0); for (var i = 0; i < xyCoords.length; i++) newXYCoords[i] = new JSV.common.Coordinate ().set (xyCoords[i].getXVal (), JSV.common.Spectrum.toTransmittance (xyCoords[i].getYVal ())); return JSV.common.Spectrum.newSpectrum (spectrum, newXYCoords, "TRANSMITTANCE"); }, "JSV.common.Spectrum"); c$.toA = Clazz.defineMethod (c$, "toA", function (spectrum) { if (!spectrum.isTransmittance ()) return null; var xyCoords = spectrum.getXYCoords (); var newXYCoords = new Array (xyCoords.length); var isPercent = JSV.common.Coordinate.isYInRange (xyCoords, -2, 2); for (var i = 0; i < xyCoords.length; i++) newXYCoords[i] = new JSV.common.Coordinate ().set (xyCoords[i].getXVal (), JSV.common.Spectrum.toAbsorbance (xyCoords[i].getYVal (), isPercent)); return JSV.common.Spectrum.newSpectrum (spectrum, newXYCoords, "ABSORBANCE"); }, "JSV.common.Spectrum"); c$.newSpectrum = Clazz.defineMethod (c$, "newSpectrum", function (spectrum, newXYCoords, units) { var specNew = spectrum.copy (); specNew.setOrigin ("JSpecView Converted"); specNew.setOwner ("JSpecView Generated"); specNew.setXYCoords (newXYCoords); specNew.setYUnits (units); spectrum.setConvertedSpectrum (specNew); specNew.setConvertedSpectrum (spectrum); return specNew; }, "JSV.common.Spectrum,~A,~S"); c$.toAbsorbance = Clazz.defineMethod (c$, "toAbsorbance", function (x, isPercent) { return (Math.min (4.0, isPercent ? 2 - JSV.common.Spectrum.log10 (x) : -JSV.common.Spectrum.log10 (x))); }, "~N,~B"); c$.toTransmittance = Clazz.defineMethod (c$, "toTransmittance", function (x) { return (x <= 0 ? 1 : Math.pow (10, -x)); }, "~N"); c$.log10 = Clazz.defineMethod (c$, "log10", function (value) { return Math.log (value) / Math.log (10); }, "~N"); c$.process = Clazz.defineMethod (c$, "process", function (specs, irMode) { if (irMode === JSV.common.Spectrum.IRMode.TO_ABS || irMode === JSV.common.Spectrum.IRMode.TO_TRANS) for (var i = 0; i < specs.size (); i++) specs.set (i, JSV.common.Spectrum.taConvert (specs.get (i), irMode)); return true; }, "JU.Lst,JSV.common.Spectrum.IRMode"); Clazz.defineMethod (c$, "getSubSpectra", function () { return this.subSpectra; }); Clazz.defineMethod (c$, "getCurrentSubSpectrum", function () { return (this.subSpectra == null ? this : this.subSpectra.get (this.currentSubSpectrumIndex)); }); Clazz.defineMethod (c$, "advanceSubSpectrum", function (dir) { return this.setCurrentSubSpectrum (this.currentSubSpectrumIndex + dir); }, "~N"); Clazz.defineMethod (c$, "setCurrentSubSpectrum", function (n) { return (this.currentSubSpectrumIndex = JSV.common.Coordinate.intoRange (n, 0, this.subSpectra.size () - 1)); }, "~N"); Clazz.defineMethod (c$, "addSubSpectrum", function (spectrum, forceSub) { if (!forceSub && (this.numDim < 2 || this.blockID != spectrum.blockID) || !JSV.common.Spectrum.allowSubSpec (this, spectrum)) return false; this.$isForcedSubset = forceSub; if (this.subSpectra == null) { this.subSpectra = new JU.Lst (); this.addSubSpectrum (this, true); }this.subSpectra.addLast (spectrum); spectrum.parent = this; return true; }, "JSV.common.Spectrum,~B"); Clazz.defineMethod (c$, "getSubIndex", function () { return (this.subSpectra == null ? -1 : this.currentSubSpectrumIndex); }); Clazz.defineMethod (c$, "setExportXAxisDirection", function (leftToRight) { this.exportXAxisLeftToRight = leftToRight; }, "~B"); Clazz.defineMethod (c$, "isExportXAxisLeftToRight", function () { return this.exportXAxisLeftToRight; }); Clazz.defineMethod (c$, "getInfo", function (key) { var info = new java.util.Hashtable (); if ("id".equalsIgnoreCase (key)) { info.put (key, this.id); return info; }info.put ("id", this.id); JSV.common.Parameters.putInfo (key, info, "specShift", Double.$valueOf (this.specShift)); var justHeader = ("header".equals (key)); if (!justHeader && key != null) { for (var i = this.headerTable.size (); --i >= 0; ) { var entry = this.headerTable.get (i); if (entry[0].equalsIgnoreCase (key) || entry[2].equalsIgnoreCase (key)) { info.put (key, entry[1]); return info; }} }var head = new java.util.Hashtable (); var list = this.getHeaderRowDataAsArray (); for (var i = 0; i < list.length; i++) { var label = JSV.source.JDXSourceStreamTokenizer.cleanLabel (list[i][0]); if (key != null && !justHeader && !label.equals (key)) continue; var val = JSV.common.Spectrum.fixInfoValue (list[i][1]); if (key == null) { var data = new java.util.Hashtable (); data.put ("value", val); data.put ("index", Integer.$valueOf (i + 1)); info.put (label, data); } else { info.put (label, val); }} if (head.size () > 0) info.put ("header", head); if (!justHeader) { JSV.common.Parameters.putInfo (key, info, "titleLabel", this.getTitleLabel ()); JSV.common.Parameters.putInfo (key, info, "type", this.getDataType ()); JSV.common.Parameters.putInfo (key, info, "isHZToPPM", Boolean.$valueOf (this.$isHZtoPPM)); JSV.common.Parameters.putInfo (key, info, "subSpectrumCount", Integer.$valueOf (this.subSpectra == null ? 0 : this.subSpectra.size ())); }return info; }, "~S"); c$.fixInfoValue = Clazz.defineMethod (c$, "fixInfoValue", function (info) { try { return (Integer.$valueOf (info)); } catch (e) { if (Clazz.exceptionOf (e, Exception)) { } else { throw e; } } try { return (Double.$valueOf (info)); } catch (e) { if (Clazz.exceptionOf (e, Exception)) { } else { throw e; } } return info; }, "~S"); Clazz.overrideMethod (c$, "toString", function () { return this.getTitleLabel (); }); Clazz.defineMethod (c$, "findMatchingPeakInfo", function (pi) { for (var i = 0; i < this.peakList.size (); i++) if (this.peakList.get (i).checkTypeMatch (pi)) return this.peakList.get (i); return null; }, "JSV.common.PeakInfo"); Clazz.defineMethod (c$, "getBasePeakInfo", function () { return (this.peakList.size () == 0 ? new JSV.common.PeakInfo () : new JSV.common.PeakInfo (" baseModel=\"\" " + this.peakList.get (0))); }); Clazz.defineMethod (c$, "getAxisLabel", function (isX) { var units = (isX ? this.piUnitsX : this.piUnitsY); if (units == null) units = (isX ? this.xLabel : this.yLabel); if (units == null) units = (isX ? this.xUnits : this.yUnits); return (units == null ? "" : units.equalsIgnoreCase ("WAVENUMBERS") ? "1/cm" : units.equalsIgnoreCase ("nanometers") ? "nm" : units); }, "~B"); Clazz.defineMethod (c$, "findXForPeakNearest", function (x) { return JSV.common.Coordinate.findXForPeakNearest (this.xyCoords, x, this.isInverted ()); }, "~N"); Clazz.defineMethod (c$, "addSpecShift", function (dx) { if (dx != 0) { this.specShift += dx; JSV.common.Coordinate.shiftX (this.xyCoords, dx); if (this.subSpectra != null) for (var i = this.subSpectra.size (); --i >= 0; ) { var spec = this.subSpectra.get (i); if (spec !== this && spec !== this.parent) spec.addSpecShift (dx); } }return this.specShift; }, "~N"); c$.allowSubSpec = Clazz.defineMethod (c$, "allowSubSpec", function (s1, s2) { return (s1.is1D () == s2.is1D () && s1.xUnits.equalsIgnoreCase (s2.xUnits) && s1.isHNMR () == s2.isHNMR ()); }, "JSV.common.Spectrum,JSV.common.Spectrum"); c$.areXScalesCompatible = Clazz.defineMethod (c$, "areXScalesCompatible", function (s1, s2, isSubspecCheck, isLinkCheck) { var isNMR1 = s1.isNMR (); if (isNMR1 != s2.isNMR () || s1.isContinuous () != s2.isContinuous () || !isLinkCheck && !JSV.common.Spectrum.areUnitsCompatible (s1.xUnits, s2.xUnits)) return false; if (isSubspecCheck) { if (s1.is1D () != s2.is1D ()) return false; } else if (isLinkCheck) { if (!isNMR1) return true; } else if (!s1.is1D () || !s2.is1D ()) { return false; }return (!isNMR1 || s2.is1D () && s1.parent.nucleusX.equals (s2.parent.nucleusX)); }, "JSV.common.Spectrum,JSV.common.Spectrum,~B,~B"); c$.areUnitsCompatible = Clazz.defineMethod (c$, "areUnitsCompatible", function (u1, u2) { if (u1.equalsIgnoreCase (u2)) return true; u1 = u1.toUpperCase (); u2 = u2.toUpperCase (); return (u1.equals ("HZ") && u2.equals ("PPM") || u1.equals ("PPM") && u2.equals ("HZ")); }, "~S,~S"); c$.areLinkableX = Clazz.defineMethod (c$, "areLinkableX", function (s1, s2) { return (s1.isNMR () && s2.isNMR () && s1.nucleusX.equals (s2.nucleusX)); }, "JSV.common.Spectrum,JSV.common.Spectrum"); c$.areLinkableY = Clazz.defineMethod (c$, "areLinkableY", function (s1, s2) { return (s1.isNMR () && s2.isNMR () && s1.nucleusX.equals (s2.nucleusY)); }, "JSV.common.Spectrum,JSV.common.Spectrum"); Clazz.defineMethod (c$, "setNHydrogens", function (nH) { this.nH = nH; }, "~N"); Clazz.defineMethod (c$, "getPeakWidth", function () { var w = this.getLastX () - this.getFirstX (); return (w / 100); }); Clazz.defineMethod (c$, "setSimulated", function (filePath) { this.isSimulation = true; var s = this.sourceID; if (s.length == 0) s = JU.PT.rep (filePath, "http://SIMULATION/", ""); if (s.indexOf ("MOL=") >= 0) s = ""; this.title = "SIMULATED " + JU.PT.rep (s, "$", ""); }, "~S"); Clazz.defineMethod (c$, "setFillColor", function (color) { this.fillColor = color; if (this.convertedSpectrum != null) this.convertedSpectrum.fillColor = color; }, "javajs.api.GenericColor"); Clazz.pu$h(self.c$); c$ = Clazz.declareType (JSV.common.Spectrum, "IRMode", Enum); c$.getMode = Clazz.defineMethod (c$, "getMode", function (a) { switch (a == null ? 'I' : a.toUpperCase ().charAt (0)) { case 'A': return JSV.common.Spectrum.IRMode.TO_ABS; case 'T': return (a.equalsIgnoreCase ("TOGGLE") ? JSV.common.Spectrum.IRMode.TOGGLE : JSV.common.Spectrum.IRMode.TO_TRANS); case 'N': return JSV.common.Spectrum.IRMode.NO_CONVERT; default: return JSV.common.Spectrum.IRMode.TOGGLE; } }, "~S"); Clazz.defineEnumConstant (c$, "NO_CONVERT", 0, []); Clazz.defineEnumConstant (c$, "TO_TRANS", 1, []); Clazz.defineEnumConstant (c$, "TO_ABS", 2, []); Clazz.defineEnumConstant (c$, "TOGGLE", 3, []); c$ = Clazz.p0p (); Clazz.defineStatics (c$, "MAXABS", 4); });
davidbuzatto/CryProteinModelsComparisonLab
web/j2s/JSV/common/Spectrum.js
JavaScript
gpl-3.0
18,056
;; XSTORMY16 Machine description template ;; Copyright (C) 1997, 1998, 1999, 2001, 2002 Free Software Foundation, Inc. ;; Contributed by Red Hat, Inc. ;; This file is part of GNU CC. ;; GNU CC is free software; you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation; either version 2, or (at your option) ;; any later version. ;; GNU CC is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; You should have received a copy of the GNU General Public License ;; along with GNU CC; see the file COPYING. If not, write to ;; the Free Software Foundation, 59 Temple Place - Suite 330, ;; Boston, MA 02111-1307, USA. ;;- See file "rtl.def" for documentation on define_insn, match_*, et. al. ;; :::::::::::::::::::: ;; :: ;; :: Attributes ;; :: ;; :::::::::::::::::::: ; Categorize branches for the conditional in the length attribute. (define_attr "branch_class" "notdirectbranch,br12,bcc12,bcc8p2,bcc8p4" (const_string "notdirectbranch")) ; The length of an instruction, used for branch shortening. (define_attr "length" "" (cond [(eq_attr "branch_class" "br12") (if_then_else (and (ge (minus (match_dup 0) (pc)) (const_int -2046)) (lt (minus (match_dup 0) (pc)) (const_int 2048))) (const_int 2) (const_int 4)) (eq_attr "branch_class" "bcc12") (if_then_else (and (ge (minus (match_dup 0) (pc)) (const_int -2044)) (lt (minus (match_dup 0) (pc)) (const_int 2048))) (const_int 4) (const_int 8)) (eq_attr "branch_class" "bcc8p2") (if_then_else (and (ge (minus (match_dup 0) (pc)) (const_int -124)) (lt (minus (match_dup 0) (pc)) (const_int 128))) (const_int 4) (const_int 8)) (eq_attr "branch_class" "bcc8p4") (if_then_else (and (ge (minus (match_dup 0) (pc)) (const_int -122)) (lt (minus (match_dup 0) (pc)) (const_int 128))) (const_int 6) (const_int 10))] (const_int 2))) ; The operand which determines the setting of Rpsw. ; The numbers indicate the operand number, ; 'clobber' indicates it is changed in some unspecified way ; 'nop' means it is not changed. (define_attr "psw_operand" "clobber,nop,0,1,2,3,4" (const_string "0")) (define_asm_attributes [(set_attr "length" "4") (set_attr "psw_operand" "clobber")]) ;; :::::::::::::::::::: ;; :: ;; :: Moves ;; :: ;; :::::::::::::::::::: ;; push/pop qi and hi are here as separate insns rather than part of ;; the movqi/hi patterns because we need to ensure that reload isn't ;; passed anything it can't cope with. Without these patterns, we ;; might end up with ;; (set (mem (post_inc (sp))) mem (post_inc (reg))) ;; If, in this example, reg needs reloading, reload will read reg from ;; the stack , adjust sp, and store reg back at what is now the wrong ;; offset. By using separate patterns for push and pop we ensure that ;; insns like this one are never generated. (define_insn "pushqi" [(set (mem:QI (post_inc (reg:HI 15))) (match_operand:QI 0 "register_operand" "r"))] "" "push %0" [(set_attr "psw_operand" "nop") (set_attr "length" "2")]) (define_insn "popqi" [(set (match_operand:QI 0 "register_operand" "=r") (mem:QI (pre_dec (reg:HI 15))))] "" "pop %0" [(set_attr "psw_operand" "nop") (set_attr "length" "2")]) (define_expand "movqi" [(set (match_operand:QI 0 "nonimmediate_nonstack_operand" "") (match_operand:QI 1 "general_operand" ""))] "" "{ xstormy16_expand_move (QImode, operands[0], operands[1]); DONE; }") (define_insn "*movqi_internal" [(set (match_operand:QI 0 "nonimmediate_nonstack_operand" "=r,m,e,e,T,r,S") (match_operand:QI 1 "general_operand" "r,e,m,i,i,i,i"))] "" "@ mov %0,%1 mov.b %0,%1 mov.b %0,%1 mov %0,%1 mov Rx,%1 mov %0,%1 mov.b %0,%1" [(set_attr_alternative "length" [(const_int 2) (if_then_else (match_operand:QI 0 "short_memory_operand" "") (const_int 2) (const_int 4)) (if_then_else (match_operand:QI 1 "short_memory_operand" "") (const_int 2) (const_int 4)) (const_int 2) (const_int 2) (const_int 4) (const_int 4)]) (set_attr "psw_operand" "0,0,0,0,nop,0,nop")]) (define_insn "pushhi" [(set (mem:HI (post_inc (reg:HI 15))) (match_operand:HI 0 "register_operand" "r"))] "" "push %0" [(set_attr "psw_operand" "nop") (set_attr "length" "2")]) (define_insn "pophi" [(set (match_operand:HI 0 "register_operand" "=r") (mem:HI (pre_dec (reg:HI 15))))] "" "pop %0" [(set_attr "psw_operand" "nop") (set_attr "length" "2")]) (define_expand "movhi" [(set (match_operand:HI 0 "nonimmediate_nonstack_operand" "") (match_operand:HI 1 "general_operand" ""))] "" "{ xstormy16_expand_move (HImode, operands[0], operands[1]); DONE; }") (define_insn "*movhi_internal" [(set (match_operand:HI 0 "nonimmediate_nonstack_operand" "=r,m,e,e,T,r,S") (match_operand:HI 1 "general_operand" "r,e,m,L,L,i,i"))] "" "@ mov %0,%1 mov.w %0,%1 mov.w %0,%1 mov.w %0,%1 mov.w Rx,%1 mov.w %0,%1 mov.w %0,%1" [(set_attr_alternative "length" [(const_int 2) (if_then_else (match_operand:QI 0 "short_memory_operand" "") (const_int 2) (const_int 4)) (if_then_else (match_operand:QI 1 "short_memory_operand" "") (const_int 2) (const_int 4)) (const_int 2) (const_int 2) (const_int 4) (const_int 4)]) (set_attr "psw_operand" "0,0,0,0,nop,0,nop")]) (define_expand "movsi" [(set (match_operand:SI 0 "nonimmediate_operand" "") (match_operand:SI 1 "general_operand" ""))] "" "{ xstormy16_expand_move (SImode, operands[0], operands[1]); DONE; }") (define_insn_and_split "*movsi_internal" [(set (match_operand:SI 0 "nonimmediate_operand" "=r,Q,r,m,e,&e,e,r,S") (match_operand:SI 1 "general_operand" "r,r,R,e,o, V,L,i,i"))] "" "#" "reload_completed" [(pc)] "{ xstormy16_split_move (SImode, operands[0], operands[1]); DONE; }" [(set_attr_alternative "length" [(const_int 4) (const_int 4) (const_int 4) (if_then_else (match_operand:QI 0 "short_memory_operand" "") (const_int 6) (const_int 8)) (if_then_else (match_operand:QI 1 "short_memory_operand" "") (const_int 6) (const_int 8)) (if_then_else (match_operand:QI 1 "short_memory_operand" "") (const_int 6) (const_int 8)) (const_int 4) (const_int 8) (const_int 8)])]) ;; :::::::::::::::::::: ;; :: ;; :: Conversions ;; :: ;; :::::::::::::::::::: (define_insn "extendqihi2" [(set (match_operand:HI 0 "register_operand" "=r") (sign_extend:HI (match_operand:QI 1 "register_operand" "0")))] "" "cbw %0") (define_insn "zero_extendqihi2" [(set (match_operand:HI 0 "register_operand" "=e,r") (zero_extend:HI (match_operand:QI 1 "nonimmediate_operand" "m,0")))] "" "@ mov.b %0, %1 shl %0,#8\n\tshr %0,#8" [(set_attr "psw_operand" "nop,0") (set_attr_alternative "length" [(const_int 2) (const_int 4)])]) ;; :::::::::::::::::::: ;; :: ;; :: Bit field extraction ;; :: ;; :::::::::::::::::::: ;; Extract an unsigned bit field ;(define_insn "extzv" ; [(set (match_operand:SI 0 "register_operand" "=r") ; (zero_extract:SI (match_operand:SI 1 "register_operand" "r") ; (match_operand:SI 2 "const_int_operand" "n") ; (match_operand:SI 3 "const_int_operand" "n")))] ; "" ; "extzv %0,%1,%2,%3" ; [(set_attr "length" "4")]) ;; Insert a bit field ;(define_insn "insv" ; [(set (zero_extract:SI (match_operand:SI 0 "register_operand" "+r") ; (match_operand:SI 1 "const_int_operand" "n") ; (match_operand:SI 2 "const_int_operand" "n")) ; (match_operand:SI 3 "nonmemory_operand" "ri"))] ; "" ; "insv %0,%1,%2,%3" ; [(set_attr "length" "4")]) ;; :::::::::::::::::::: ;; :: ;; :: 16 bit Integer arithmetic ;; :: ;; :::::::::::::::::::: ;; Addition ; Operand 3 is marked earlyclobber because that helps reload ; to generate better code---this pattern will never need the ; carry register as an input, and some output reloads or input ; reloads might need to use it. In fact, without the '&' reload ; will fail in some cases. (define_insn "addhi3" [(set (match_operand:HI 0 "register_operand" "=r,r,T,T,r,r,r") (plus:HI (match_operand:HI 1 "register_operand" "%0,0,0,0,0,0,0") (match_operand:HI 2 "nonmemory_operand" "O,P,L,M,Ir,N,i"))) (clobber (match_scratch:BI 3 "=X,X,&y,&y,&y,&y,&y"))] "" "@ inc %0,%o2 dec %0,%O2 add Rx,%2 sub Rx,#%n2 add %0,%2 sub %0,#%n2 add %0,%2" [(set_attr "length" "2,2,2,2,2,2,4")]) ; Reload can generate addition operations. The SECONDARY_RELOAD_CLASS ; macro causes it to allocate the carry register; this pattern ; shows it how to place the register in RTL to make the addition work. (define_expand "reload_inhi" [(parallel [(set (match_operand:HI 0 "register_operand" "=r") (match_operand:HI 1 "xstormy16_carry_plus_operand" "")) (clobber (match_operand:BI 2 "" "=&y"))])] "" "if (! rtx_equal_p (operands[0], XEXP (operands[1], 0))) { emit_insn (gen_rtx_SET (VOIDmode, operands[0], XEXP (operands[1], 0))); operands[1] = gen_rtx_PLUS (GET_MODE (operands[1]), operands[0], XEXP (operands[1], 1)); } ") (define_insn "addchi4" [(set (match_operand:HI 0 "register_operand" "=T,r,r") (plus:HI (match_operand:HI 1 "register_operand" "%0,0,0") (match_operand:HI 2 "nonmemory_operand" "L,Ir,i"))) (set (match_operand:BI 3 "register_operand" "=y,y,y") (truncate:BI (lshiftrt:SI (plus:SI (zero_extend:SI (match_dup 1)) (zero_extend:SI (match_dup 2))) (const_int 16))))] "" "@ add Rx,%2 add %0,%2 add %0,%2" [(set_attr "length" "2,2,4")]) (define_insn "addchi5" [(set (match_operand:HI 0 "register_operand" "=T,r,r") (plus:HI (plus:HI (match_operand:HI 1 "register_operand" "%0,0,0") (zero_extend:HI (match_operand:BI 3 "register_operand" "y,y,y"))) (match_operand:HI 2 "nonmemory_operand" "L,Ir,i"))) (set (match_operand:BI 4 "register_operand" "=y,y,y") (truncate:BI (lshiftrt:SI (plus:SI (plus:SI (zero_extend:SI (match_dup 1)) (zero_extend:SI (match_dup 3))) (zero_extend:SI (match_dup 2))) (const_int 16))))] "" "@ adc Rx,%2 adc %0,%2 adc %0,%2" [(set_attr "length" "2,2,4")]) ;; Subtraction ; Operand 3 is marked earlyclobber because that helps reload ; to generate better code---this pattern will never need the ; carry register as an input, and some output reloads or input ; reloads might need to use it. In fact, without the '&' reload ; will fail in some cases. (define_insn "subhi3" [(set (match_operand:HI 0 "register_operand" "=r,r,T,T,r,r,r") (minus:HI (match_operand:HI 1 "register_operand" "0,0,0,0,0,0,0") (match_operand:HI 2 "nonmemory_operand" "O,P,L,M,rI,M,i"))) (clobber (match_scratch:BI 3 "=X,X,&y,&y,&y,&y,&y"))] "" "@ dec %0,%o2 inc %0,%O2 sub Rx,%2 add Rx,#%n2 sub %0,%2 add %0,#%n2 sub %0,%2" [(set_attr "length" "2,2,2,2,2,2,4")]) (define_insn "subchi4" [(set (match_operand:HI 0 "register_operand" "=T,r,r") (minus:HI (match_operand:HI 1 "register_operand" "0,0,0") (match_operand:HI 2 "nonmemory_operand" "L,Ir,i"))) (set (match_operand:BI 3 "register_operand" "=y,y,y") (truncate:BI (lshiftrt:SI (minus:SI (zero_extend:SI (match_dup 1)) (zero_extend:SI (match_dup 2))) (const_int 16))))] "" "@ sub Rx,%2 sub %0,%2 sub %0,%2" [(set_attr "length" "2,2,4")]) (define_insn "subchi5" [(set (match_operand:HI 0 "register_operand" "=T,r,r") (minus:HI (minus:HI (match_operand:HI 1 "register_operand" "0,0,0") (zero_extend:HI (match_operand:BI 3 "register_operand" "y,y,y"))) (match_operand:HI 2 "nonmemory_operand" "L,Ir,i"))) (set (match_operand:BI 4 "register_operand" "=y,y,y") (truncate:BI (lshiftrt:SI (minus:SI (minus:SI (zero_extend:SI (match_dup 1)) (zero_extend:SI (match_dup 3))) (zero_extend:SI (match_dup 2))) (const_int 16))))] "" "@ sbc Rx,%2 sbc %0,%2 sbc %0,%2" [(set_attr "length" "2,2,4")]) ; Basic multiplication (define_insn "mulhi3" [(set (match_operand:HI 0 "register_operand" "=a") (mult:HI (match_operand:HI 1 "register_operand" "%a") (match_operand:HI 2 "register_operand" "c"))) (clobber (match_scratch:HI 3 "=b")) ] "" "mul" [(set_attr "psw_operand" "nop")]) ;; Unsigned multiplication producing 64 bit results from 32 bit inputs ; The constraint on operand 0 is 't' because it is actually two regs ; long, and both regs must match the constraint. (define_insn "umulhisi3" [(set (match_operand:SI 0 "register_operand" "=t") (mult:SI (zero_extend:SI (match_operand:HI 1 "register_operand" "%a")) (zero_extend:SI (match_operand:HI 2 "register_operand" "c")))) ] "" "mul" [(set_attr "psw_operand" "nop")]) ;; Unsigned division giving both quotient and remainder (define_insn "udivmodhi4" [(set (match_operand:HI 0 "register_operand" "=a") (udiv:HI (match_operand:HI 1 "register_operand" "a") (match_operand:HI 2 "register_operand" "c"))) (set (match_operand:HI 3 "register_operand" "=b") (umod:HI (match_dup 1) (match_dup 2)))] "" "div" [(set_attr "psw_operand" "nop")]) ;; Negation (define_expand "neghi2" [(set (match_operand:HI 0 "register_operand" "") (not:HI (match_operand:HI 1 "register_operand" ""))) (parallel [(set (match_dup 0) (plus:HI (match_dup 0) (const_int 1))) (clobber (match_scratch:BI 3 ""))])] "" "") ;; :::::::::::::::::::: ;; :: ;; :: 16 bit Integer Shifts and Rotates ;; :: ;; :::::::::::::::::::: ;; Arithmetic Shift Left (define_insn "ashlhi3" [(set (match_operand:HI 0 "register_operand" "=r") (ashift:HI (match_operand:HI 1 "register_operand" "0") (match_operand:HI 2 "nonmemory_operand" "ri"))) (clobber (match_scratch:BI 3 "=y"))] "" "shl %0,%2") ;; Arithmetic Shift Right (define_insn "ashrhi3" [(set (match_operand:HI 0 "register_operand" "=r") (ashiftrt:HI (match_operand:HI 1 "register_operand" "0") (match_operand:HI 2 "nonmemory_operand" "ri"))) (clobber (match_scratch:BI 3 "=y"))] "" "asr %0,%2") ;; Logical Shift Right (define_insn "lshrhi3" [(set (match_operand:HI 0 "register_operand" "=r") (lshiftrt:HI (match_operand:HI 1 "register_operand" "0") (match_operand:HI 2 "nonmemory_operand" "ri"))) (clobber (match_scratch:BI 3 "=y"))] "" "shr %0,%2") ;; :::::::::::::::::::: ;; :: ;; :: 16 Bit Integer Logical operations ;; :: ;; :::::::::::::::::::: ;; Logical AND, 16 bit integers (define_insn "andhi3" [(set (match_operand:HI 0 "register_operand" "=T,r,r,r") (and:HI (match_operand:HI 1 "register_operand" "%0,0,0,0") (match_operand:HI 2 "nonmemory_operand" "L,r,K,i")))] "" "@ and Rx,%2 and %0,%2 clr1 %0,%B2 and %0,%2" [(set_attr "length" "2,2,2,4")]) ;; Inclusive OR, 16 bit integers (define_insn "iorhi3" [(set (match_operand:HI 0 "register_operand" "=T,r,r,r") (ior:HI (match_operand:HI 1 "register_operand" "%0,0,0,0") (match_operand:HI 2 "nonmemory_operand" "L,r,J,i")))] "" "@ or Rx,%2 or %0,%2 set1 %0,%B2 or %0,%2" [(set_attr "length" "2,2,2,4")]) ;; Exclusive OR, 16 bit integers (define_insn "xorhi3" [(set (match_operand:HI 0 "register_operand" "=T,r,r") (xor:HI (match_operand:HI 1 "register_operand" "%0,0,0") (match_operand:HI 2 "nonmemory_operand" "L,r,i")))] "" "@ xor Rx,%2 xor %0,%2 xor %0,%2" [(set_attr "length" "2,2,4")]) ;; One's complement, 16 bit integers (define_insn "one_cmplhi2" [(set (match_operand:HI 0 "register_operand" "=r") (not:HI (match_operand:HI 1 "register_operand" "0")))] "" "not %0") ;; :::::::::::::::::::: ;; :: ;; :: 32 bit Integer arithmetic ;; :: ;; :::::::::::::::::::: ;; Addition (define_insn_and_split "addsi3" [(set (match_operand:SI 0 "register_operand" "=r") (plus:SI (match_operand:SI 1 "register_operand" "%0") (match_operand:SI 2 "nonmemory_operand" "ri"))) (clobber (match_scratch:BI 3 "=y"))] "" "#" "reload_completed" [(pc)] "{ xstormy16_expand_arith (SImode, PLUS, operands[0], operands[1], operands[2], operands[3]); DONE; } " [(set_attr "length" "4")]) ;; Subtraction (define_insn_and_split "subsi3" [(set (match_operand:SI 0 "register_operand" "=r") (minus:SI (match_operand:SI 1 "register_operand" "0") (match_operand:SI 2 "nonmemory_operand" "ri"))) (clobber (match_scratch:BI 3 "=y"))] "" "#" "reload_completed" [(pc)] "{ xstormy16_expand_arith (SImode, MINUS, operands[0], operands[1], operands[2], operands[3]); DONE; } " [(set_attr "length" "4")]) (define_expand "negsi2" [(set (match_operand:SI 0 "register_operand" "") (neg:SI (match_operand:SI 1 "register_operand" "")))] "" "{ xstormy16_expand_arith (SImode, NEG, operands[0], const0_rtx, operands[1], gen_reg_rtx (BImode)); DONE; }") ;; :::::::::::::::::::: ;; :: ;; :: 32 bit Integer Shifts and Rotates ;; :: ;; :::::::::::::::::::: ;; Arithmetic Shift Left (define_expand "ashlsi3" [(parallel [(set (match_operand:SI 0 "register_operand" "") (ashift:SI (match_operand:SI 1 "register_operand" "") (match_operand:SI 2 "const_int_operand" ""))) (clobber (match_dup 3)) (clobber (match_dup 4))])] "" " if (! const_int_operand (operands[2], SImode)) FAIL; operands[3] = gen_reg_rtx (BImode); operands[4] = gen_reg_rtx (HImode); ") ;; Arithmetic Shift Right (define_expand "ashrsi3" [(parallel [(set (match_operand:SI 0 "register_operand" "") (ashiftrt:SI (match_operand:SI 1 "register_operand" "") (match_operand:SI 2 "const_int_operand" ""))) (clobber (match_dup 3)) (clobber (match_dup 4))])] "" " if (! const_int_operand (operands[2], SImode)) FAIL; operands[3] = gen_reg_rtx (BImode); operands[4] = gen_reg_rtx (HImode); ") ;; Logical Shift Right (define_expand "lshrsi3" [(parallel [(set (match_operand:SI 0 "register_operand" "") (lshiftrt:SI (match_operand:SI 1 "register_operand" "") (match_operand:SI 2 "const_int_operand" ""))) (clobber (match_dup 3)) (clobber (match_dup 4))])] "" " if (! const_int_operand (operands[2], SImode)) FAIL; operands[3] = gen_reg_rtx (BImode); operands[4] = gen_reg_rtx (HImode); ") (define_insn "*shiftsi" [(set (match_operand:SI 0 "register_operand" "=r,r") (match_operator:SI 5 "shift_operator" [(match_operand:SI 1 "register_operand" "0,0") (match_operand:SI 2 "const_int_operand" "U,n")])) (clobber (match_operand:BI 3 "register_operand" "=y,y")) (clobber (match_operand:HI 4 "" "=X,r"))] "" "* return xstormy16_output_shift (SImode, GET_CODE (operands[5]), operands[0], operands[2], operands[4]);" [(set_attr "length" "6,10") (set_attr "psw_operand" "clobber,clobber")]) ;; :::::::::::::::::::: ;; :: ;; :: Comparisons ;; :: ;; :::::::::::::::::::: ;; Note, we store the operands in the comparison insns, and use them later ;; when generating the branch or scc operation. ;; First the routines called by the machine independent part of the compiler (define_expand "cmphi" [(set (cc0) (compare (match_operand:HI 0 "register_operand" "") (match_operand:HI 1 "nonmemory_operand" "")))] "" " { xstormy16_compare_op0 = operands[0]; xstormy16_compare_op1 = operands[1]; DONE; }") ; There are no real SImode comparisons, but some can be emulated ; by performing a SImode subtract and looking at the condition flags. (define_expand "cmpsi" [(set (cc0) (compare (match_operand:SI 0 "register_operand" "") (match_operand:SI 1 "nonmemory_operand" "")))] "" " { xstormy16_compare_op0 = operands[0]; xstormy16_compare_op1 = operands[1]; DONE; }") ;; :::::::::::::::::::: ;; :: ;; :: Branches ;; :: ;; :::::::::::::::::::: (define_expand "beq" [(use (match_operand 0 "" ""))] "" "{ xstormy16_emit_cbranch (EQ, operands[0]); DONE; }") (define_expand "bne" [(use (match_operand 0 "" ""))] "" "{ xstormy16_emit_cbranch (NE, operands[0]); DONE; }") (define_expand "bge" [(use (match_operand 0 "" ""))] "" "{ xstormy16_emit_cbranch (GE, operands[0]); DONE; }") (define_expand "bgt" [(use (match_operand 0 "" ""))] "" "{ xstormy16_emit_cbranch (GT, operands[0]); DONE; }") (define_expand "ble" [(use (match_operand 0 "" ""))] "" "{ xstormy16_emit_cbranch (LE, operands[0]); DONE; }") (define_expand "blt" [(use (match_operand 0 "" ""))] "" "{ xstormy16_emit_cbranch (LT, operands[0]); DONE; }") (define_expand "bgeu" [(use (match_operand 0 "" ""))] "" "{ xstormy16_emit_cbranch (GEU, operands[0]); DONE; }") (define_expand "bgtu" [(use (match_operand 0 "" ""))] "" "{ xstormy16_emit_cbranch (GTU, operands[0]); DONE; }") (define_expand "bleu" [(use (match_operand 0 "" ""))] "" "{ xstormy16_emit_cbranch (LEU, operands[0]); DONE; }") (define_expand "bltu" [(use (match_operand 0 "" ""))] "" "{ xstormy16_emit_cbranch (LTU, operands[0]); DONE; }") (define_insn "*cbranchhi" [(set (pc) (if_then_else (match_operator:HI 1 "comparison_operator" [(match_operand:HI 2 "nonmemory_operand" "r,e,L") (match_operand:HI 3 "nonmemory_operand" "r,L,e")]) (label_ref (match_operand 0 "" "")) (pc))) (clobber (match_operand:BI 4 "" "=&y,&y,&y"))] "" "* { return xstormy16_output_cbranch_hi (operands[1], \"%l0\", 0, insn); }" [(set_attr "branch_class" "bcc12") (set_attr "psw_operand" "0,0,1")]) (define_insn "*cbranchhi_neg" [(set (pc) (if_then_else (match_operator:HI 1 "comparison_operator" [(match_operand:HI 2 "nonmemory_operand" "r,e,L") (match_operand:HI 3 "nonmemory_operand" "r,L,e")]) (pc) (label_ref (match_operand 0 "" "")))) (clobber (match_operand:BI 4 "" "=&y,&y,&y"))] "" "* { return xstormy16_output_cbranch_hi (operands[1], \"%l0\", 1, insn); }" [(set_attr "branch_class" "bcc12") (set_attr "psw_operand" "0,0,1")]) (define_insn "*eqbranchsi" [(set (pc) (if_then_else (match_operator:SI 1 "equality_operator" [(match_operand:SI 2 "register_operand" "+r") (const_int 0)]) (label_ref (match_operand 0 "" "")) (pc))) ;; Although I would greatly like the 'match_dup' in the following line ;; to actually be a register constraint, there is (at the time of writing) no ;; way for reload to insert an output reload on the edges out of a branch. ;; If reload is fixed to use insert_insn_on_edge, this can be changed. (clobber (match_dup 2))] "" "* { return xstormy16_output_cbranch_si (operands[1], \"%l0\", 0, insn); }" [(set_attr "branch_class" "bcc8p2") (set_attr "psw_operand" "clobber")]) (define_insn_and_split "*ineqbranchsi" [(set (pc) (if_then_else (match_operator:SI 1 "xstormy16_ineqsi_operator" [(match_operand:SI 2 "register_operand" "+r") (match_operand:SI 3 "nonmemory_operand" "ri")]) (label_ref (match_operand 0 "" "")) (pc))) ;; Although I would greatly like the 'match_dup' in the following line ;; to actually be a register constraint, there is (at the time of writing) no ;; way for reload to insert an output reload on the edges out of a branch. ;; If reload is fixed to use insert_insn_on_edge, this can be changed, ;; preferably to a 'minus' operand that explains the actual operation, like: ; (set (match_operand 5 "register_operand" "=2") ; (minus:SI (match_operand 6 "register_operand" "2") ; (match_operand 7 "register_operand" "3"))) (clobber (match_dup 2)) (clobber (match_operand:BI 4 "" "=&y"))] "" "#" "reload_completed" [(pc)] "{ xstormy16_split_cbranch (SImode, operands[0], operands[1], operands[2], operands[4]); DONE; }" [(set_attr "length" "8")]) (define_insn "*ineqbranch_1" [(set (pc) (if_then_else (match_operator:HI 5 "xstormy16_ineqsi_operator" [(minus:HI (match_operand:HI 1 "register_operand" "T,r,r") (zero_extend:HI (match_operand:BI 4 "register_operand" "y,y,y"))) (match_operand:HI 3 "nonmemory_operand" "L,Ir,i")]) (label_ref (match_operand 0 "" "")) (pc))) (set (match_operand:HI 2 "register_operand" "=2,2,2") (minus:HI (minus:HI (match_dup 1) (zero_extend:HI (match_dup 4))) (match_dup 3))) (clobber (match_operand:BI 6 "" "=y,y,y"))] "" "* { return xstormy16_output_cbranch_si (operands[5], \"%l0\", 0, insn); }" [(set_attr "branch_class" "bcc8p2,bcc8p2,bcc8p4") (set_attr "psw_operand" "2,2,2")]) ;; :::::::::::::::::::: ;; :: ;; :: Call and branch instructions ;; :: ;; :::::::::::::::::::: ;; Subroutine call instruction returning no value. Operand 0 is the function ;; to call; operand 1 is the number of bytes of arguments pushed (in mode ;; `SImode', except it is normally a `const_int'); operand 2 is the number of ;; registers used as operands. ;; On most machines, operand 2 is not actually stored into the RTL pattern. It ;; is supplied for the sake of some RISC machines which need to put this ;; information into the assembler code; they can put it in the RTL instead of ;; operand 1. (define_expand "call" [(call (match_operand:HI 0 "memory_operand" "m") (match_operand 1 "" "")) (use (match_operand 2 "immediate_operand" ""))] "" "xstormy16_expand_call (NULL_RTX, operands[0], operands[1]); DONE;") ;; Subroutine call instruction returning a value. Operand 0 is the hard ;; register in which the value is returned. There are three more operands, the ;; same as the three operands of the `call' instruction (but with numbers ;; increased by one). ;; Subroutines that return `BLKmode' objects use the `call' insn. (define_expand "call_value" [(set (match_operand 0 "register_operand" "=r") (call (match_operand:HI 1 "memory_operand" "m") (match_operand:SI 2 "" ""))) (use (match_operand 3 "immediate_operand" ""))] "" "xstormy16_expand_call (operands[0], operands[1], operands[2]); DONE;") (define_insn "*call_internal" [(call (mem:HI (match_operand:HI 0 "nonmemory_operand" "i,r")) (match_operand 1 "" "")) (use (match_operand:HI 2 "nonmemory_operand" "X,z"))] "" "@ callf %C0 call %2,%0" [(set_attr "length" "4,2") (set_attr "psw_operand" "clobber")]) (define_insn "*call_value_internal" [(set (match_operand 3 "register_operand" "=r,r") (call (mem:HI (match_operand:HI 0 "nonmemory_operand" "i,r")) (match_operand 1 "" ""))) (use (match_operand:HI 2 "nonmemory_operand" "X,z"))] "" "@ callf %C0 call %2,%0" [(set_attr "length" "4,2") (set_attr "psw_operand" "clobber")]) ;; Subroutine return (define_expand "return" [(return)] "direct_return()" "") (define_insn "return_internal" [(return)] "" "ret" [(set_attr "psw_operand" "nop")]) (define_insn "return_internal_interrupt" [(return) (unspec_volatile [(const_int 0)] 1)] "" "iret" [(set_attr "psw_operand" "clobber")]) ;; Normal unconditional jump (define_insn "jump" [(set (pc) (label_ref (match_operand 0 "" "")))] "" "* { return xstormy16_output_cbranch_hi (NULL_RTX, \"%l0\", 0, insn); }" [(set_attr "branch_class" "br12") (set_attr "psw_operand" "nop")]) ;; Indirect jump through a register (define_expand "indirect_jump" [(set (match_dup 1) (const_int 0)) (parallel [(set (pc) (match_operand:HI 0 "register_operand" "r")) (use (match_dup 1))])] "" "operands[1] = gen_reg_rtx (HImode);") (define_insn "" [(set (pc) (match_operand:HI 0 "register_operand" "r")) (use (match_operand:HI 1 "register_operand" "z"))] "" "jmp %1,%0" [(set_attr "length" "4") (set_attr "psw_operand" "nop")]) ;; Table-based switch statements. (define_expand "casesi" [(use (match_operand:SI 0 "register_operand" "")) (use (match_operand:SI 1 "immediate_operand" "")) (use (match_operand:SI 2 "immediate_operand" "")) (use (label_ref (match_operand 3 "" ""))) (use (label_ref (match_operand 4 "" "")))] "" " { xstormy16_expand_casesi (operands[0], operands[1], operands[2], operands[3], operands[4]); DONE; }") (define_insn "tablejump_pcrel" [(set (pc) (mem:HI (plus:HI (pc) (match_operand:HI 0 "register_operand" "r")))) (use (label_ref:SI (match_operand 1 "" "")))] "" "br %0" [(set_attr "psw_operand" "nop")]) ;; :::::::::::::::::::: ;; :: ;; :: Prologue and Epilogue instructions ;; :: ;; :::::::::::::::::::: ;; Called after register allocation to add any instructions needed for ;; the prologue. Using a prologue insn is favored compared to putting ;; all of the instructions in the TARGET_ASM_FUNCTION_PROLOGUE macro, ;; since it allows the scheduler to intermix instructions with the ;; saves of the caller saved registers. In some cases, it might be ;; necessary to emit a barrier instruction as the last insn to prevent ;; such scheduling. (define_expand "prologue" [(const_int 1)] "" " { xstormy16_expand_prologue (); DONE; }") ;; Called after register allocation to add any instructions needed for ;; the epilogue. Using an epilogue insn is favored compared to putting ;; all of the instructions in the TARGET_ASM_FUNCTION_EPILOGUE macro, ;; since it allows the scheduler to intermix instructions with the ;; restires of the caller saved registers. In some cases, it might be ;; necessary to emit a barrier instruction as the first insn to ;; prevent such scheduling. (define_expand "epilogue" [(const_int 2)] "" " { xstormy16_expand_epilogue (); DONE; }") ;; :::::::::::::::::::: ;; :: ;; :: Miscellaneous instructions ;; :: ;; :::::::::::::::::::: ;; No operation, needed in case the user uses -g but not -O. (define_insn "nop" [(const_int 0)] "" "nop" [(set_attr "psw_operand" "nop")]) ;; Pseudo instruction that prevents the scheduler from moving code above this ;; point. (define_insn "blockage" [(unspec_volatile [(const_int 0)] 0)] "" "" [(set_attr "length" "0") (set_attr "psw_operand" "nop")])
pumpkin83/OpenUH-OpenACC
osprey/kgccfe/gnu/config/stormy16/stormy16.md
Markdown
gpl-3.0
30,393
/* mpq_div -- divide two rational numbers. Copyright 1991, 1994, 1995, 1996, 2000, 2001 Free Software Foundation, Inc. This file is part of the GNU MP Library. The GNU MP Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. The GNU MP 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 the GNU MP Library. If not, see http://www.gnu.org/licenses/. */ #include "gmp.h" #include "gmp-impl.h" void mpq_div (mpq_ptr quot, mpq_srcptr op1, mpq_srcptr op2) { mpz_t gcd1, gcd2; mpz_t tmp1, tmp2; mpz_t numtmp; mp_size_t op1_num_size; mp_size_t op1_den_size; mp_size_t op2_num_size; mp_size_t op2_den_size; mp_size_t alloc; TMP_DECL; op2_num_size = ABSIZ(NUM(op2)); if (UNLIKELY (op2_num_size == 0)) DIVIDE_BY_ZERO; op1_num_size = ABSIZ(NUM(op1)); if (op1_num_size == 0) { /* We special case this to simplify allocation logic; gcd(0,x) = x is a singular case for the allocations. */ SIZ(NUM(quot)) = 0; PTR(DEN(quot))[0] = 1; SIZ(DEN(quot)) = 1; return; } op2_den_size = SIZ(DEN(op2)); op1_den_size = SIZ(DEN(op1)); TMP_MARK; alloc = MIN (op1_num_size, op2_num_size); MPZ_TMP_INIT (gcd1, alloc); alloc = MIN (op1_den_size, op2_den_size); MPZ_TMP_INIT (gcd2, alloc); alloc = MAX (op1_num_size, op2_num_size); MPZ_TMP_INIT (tmp1, alloc); alloc = MAX (op1_den_size, op2_den_size); MPZ_TMP_INIT (tmp2, alloc); alloc = op1_num_size + op2_den_size; MPZ_TMP_INIT (numtmp, alloc); /* QUOT might be identical to either operand, so don't store the result there until we are finished with the input operands. We can overwrite the numerator of QUOT when we are finished with the numerators of OP1 and OP2. */ mpz_gcd (gcd1, NUM(op1), NUM(op2)); mpz_gcd (gcd2, DEN(op2), DEN(op1)); mpz_divexact_gcd (tmp1, NUM(op1), gcd1); mpz_divexact_gcd (tmp2, DEN(op2), gcd2); mpz_mul (numtmp, tmp1, tmp2); mpz_divexact_gcd (tmp1, NUM(op2), gcd1); mpz_divexact_gcd (tmp2, DEN(op1), gcd2); mpz_mul (DEN(quot), tmp1, tmp2); /* We needed to go via NUMTMP to take care of QUOT being the same as OP2. Now move NUMTMP to QUOT->_mp_num. */ mpz_set (NUM(quot), numtmp); /* Keep the denominator positive. */ if (SIZ(DEN(quot)) < 0) { SIZ(DEN(quot)) = -SIZ(DEN(quot)); SIZ(NUM(quot)) = -SIZ(NUM(quot)); } TMP_FREE; }
carthy/beard.gmp
mpq/div.c
C
gpl-3.0
2,833
#ifndef The_Powder_Toy_Sample_h #define The_Powder_Toy_Sample_h #include "Particle.h" class SimulationSample { public: Particle particle; int ParticleID; int PositionX, PositionY; float AirPressure; float AirTemperature; float AirVelocityX; float AirVelocityY; int WallType; float Gravity; float GravityVelocityX; float GravityVelocityY; int NumParts; bool isMouseInSim; SimulationSample() : PositionX(0), PositionY(0), ParticleID(0), particle(), AirPressure(0), AirVelocityX(0), AirVelocityY(0), WallType(0), Gravity(0), GravityVelocityX(0), GravityVelocityY(0), AirTemperature(0), NumParts(0), isMouseInSim(true) {} }; #endif
GreenFireDragon/GreenFireDragon-s-TPTMod
src/simulation/Sample.h
C
gpl-3.0
650
s = new ShardingTest( "diffservers1" , 2 ); assert.eq( 2 , s.config.shards.count() , "server count wrong" ); assert.eq( 2 , s._connections[0].getDB( "config" ).shards.count() , "where are servers!" ); assert.eq( 0 , s._connections[1].getDB( "config" ).shards.count() , "shouldn't be here" ); test1 = s.getDB( "test1" ).foo; test1.save( { a : 1 } ); test1.save( { a : 2 } ); test1.save( { a : 3 } ); assert( 3 , test1.count() ); assert( ! s.admin.runCommand( { addshard: "sdd$%" } ).ok , "bad hostname" ); assert( ! s.admin.runCommand( { addshard: "127.0.0.1:43415" } ).ok , "host not up" ); assert( ! s.admin.runCommand( { addshard: "10.0.0.1:43415" } ).ok , "allowed shard in IP when config is localhost" ); s.stop();
wvdd007/robomongo
src/third-party/mongodb/jstests/sharding/diffservers1.js
JavaScript
gpl-3.0
726
// -*- mode: C++; c-indent-level: 4; c-basic-offset: 4; tab-width: 4 -*- // // IndexHash.h: Rcpp R/C++ interface class library -- hashing utility, inspired // from Simon's fastmatch package // // Copyright (C) 2010, 2011 Simon Urbanek // Copyright (C) 2012 Dirk Eddelbuettel and Romain Francois // Copyright (C) 2014 Dirk Eddelbuettel, Romain Francois and Kevin Ushey // // This file is part of Rcpp. // // Rcpp 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. // // Rcpp 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 Rcpp. If not, see <http://www.gnu.org/licenses/>. #ifndef RCPP__HASH__INDEX_HASH_H #define RCPP__HASH__INDEX_HASH_H #if ( defined(HASH_PROFILE) && defined(__APPLE__) ) // only mac version for now #include <mach/mach_time.h> #define ABSOLUTE_TIME mach_absolute_time #define RCPP_PROFILE_TIC start = ABSOLUTE_TIME() ; #define RCPP_PROFILE_TOC end = ABSOLUTE_TIME() ; #define RCPP_PROFILE_RECORD(name) profile_data[#name] = end - start ; #else #define RCPP_PROFILE_TIC #define RCPP_PROFILE_TOC #define RCPP_PROFILE_RECORD(name) #endif #define RCPP_USE_CACHE_HASH namespace Rcpp{ namespace sugar{ #ifndef RCPP_HASH #define RCPP_HASH(X) (3141592653U * ((unsigned int)(X)) >> (32 - k)) #endif template <int RTYPE> class IndexHash { public: typedef typename traits::storage_type<RTYPE>::type STORAGE ; typedef Vector<RTYPE> VECTOR ; IndexHash( SEXP table ) : n(Rf_length(table)), m(2), k(1), src( (STORAGE*)dataptr(table) ), size_(0) , data() #ifdef HASH_PROFILE , profile_data() #endif { RCPP_PROFILE_TIC int desired = n*2 ; while( m < desired ){ m *= 2 ; k++ ; } #ifdef RCPP_USE_CACHE_HASH data = get_cache(m) ; #else data.resize( m ) ; #endif RCPP_PROFILE_TOC RCPP_PROFILE_RECORD(ctor_body) } inline IndexHash& fill(){ RCPP_PROFILE_TIC for( int i=0; i<n; i++) add_value(i) ; RCPP_PROFILE_TOC RCPP_PROFILE_RECORD(fill) return *this ; } inline LogicalVector fill_and_get_duplicated() { LogicalVector result = no_init(n) ; int* res = LOGICAL(result) ; for( int i=0; i<n; i++) res[i] = ! add_value(i) ; return result ; } template <typename T> inline SEXP lookup(const T& vec) const { return lookup__impl(vec, vec.size() ) ; } // use the pointers for actual (non sugar expression vectors) inline SEXP lookup(const VECTOR& vec) const { return lookup__impl(vec.begin(), vec.size() ) ; } inline bool contains(STORAGE val) const { return get_index(val) != NA_INTEGER ; } inline int size() const { return size_ ; } // keys, in the order they appear in the data inline Vector<RTYPE> keys() const{ Vector<RTYPE> res = no_init(size_) ; for( int i=0, j=0; j<size_; i++){ if( data[i] ) res[j++] = src[data[i]-1] ; } return res ; } int n, m, k ; STORAGE* src ; int size_ ; #ifdef RCPP_USE_CACHE_HASH int* data ; #else std::vector<int> data ; #endif #ifdef HASH_PROFILE mutable std::map<std::string,int> profile_data ; mutable uint64_t start ; mutable uint64_t end ; #endif template <typename T> SEXP lookup__impl(const T& vec, int n_) const { RCPP_PROFILE_TIC SEXP res = Rf_allocVector(INTSXP, n_) ; RCPP_PROFILE_TOC RCPP_PROFILE_RECORD(allocVector) int *v = INTEGER(res) ; RCPP_PROFILE_TIC for( int i=0; i<n_; i++) v[i] = get_index( vec[i] ) ; RCPP_PROFILE_TOC RCPP_PROFILE_RECORD(lookup) return res ; } SEXP get_profile_data(){ #ifdef HASH_PROFILE return wrap( profile_data ) ; #else return R_NilValue ; #endif } inline bool not_equal(const STORAGE& lhs, const STORAGE& rhs) { return ! internal::NAEquals<STORAGE>()(lhs, rhs); } bool add_value(int i){ RCPP_DEBUG_2( "%s::add_value(%d)", DEMANGLE(IndexHash), i ) STORAGE val = src[i++] ; int addr = get_addr(val) ; while (data[addr] && not_equal( src[data[addr] - 1], val)) { addr++; if (addr == m) { addr = 0; } } if (!data[addr]){ data[addr] = i ; size_++ ; return true ; } return false; } /* NOTE: we are returning a 1-based index ! */ inline int get_index(STORAGE value) const { int addr = get_addr(value) ; while (data[addr]) { if (src[data[addr] - 1] == value) return data[addr]; addr++; if (addr == m) addr = 0; } return NA_INTEGER; } // defined below int get_addr(STORAGE value) const ; } ; template <> inline int IndexHash<INTSXP>::get_addr(int value) const { return RCPP_HASH(value) ; } template <> inline int IndexHash<REALSXP>::get_addr(double val) const { int addr; union dint_u { double d; unsigned int u[2]; }; union dint_u val_u; /* double is a bit tricky - we nave to normalize 0.0, NA and NaN */ if (val == 0.0) val = 0.0; if (internal::Rcpp_IsNA(val)) val = NA_REAL; else if (internal::Rcpp_IsNaN(val)) val = R_NaN; val_u.d = val; addr = RCPP_HASH(val_u.u[0] + val_u.u[1]); return addr ; } template <> inline int IndexHash<STRSXP>::get_addr(SEXP value) const { intptr_t val = (intptr_t) value; int addr; #if (defined _LP64) || (defined __LP64__) || (defined WIN64) addr = RCPP_HASH((val & 0xffffffff) ^ (val >> 32)); #else addr = RCPP_HASH(val); #endif return addr ; } } // sugar } // Rcpp #endif
nafiux/portableR
site-library/Rcpp/include/Rcpp/hash/IndexHash.h
C
agpl-3.0
6,906
<?php return array( 'group_exists' => 'குழு ஏற்கனவே உள்ளது!', 'group_not_found' => 'குழு [: id] இல்லை.', 'group_name_required' => 'பெயர் புலம் தேவை', 'success' => array( 'create' => 'குழு வெற்றிகரமாக உருவாக்கப்பட்டது.', 'update' => 'குழு வெற்றிகரமாக புதுப்பிக்கப்பட்டது.', 'delete' => 'குழு வெற்றிகரமாக நீக்கப்பட்டது.', ), 'delete' => array( 'confirm' => 'இந்த குழுவையை நிச்சயமாக நீக்க விரும்புகிறீர்களா?', 'create' => 'குழுவை உருவாக்கும் ஒரு சிக்கல் இருந்தது. தயவு செய்து மீண்டும் முயற்சிக்கவும்.', 'update' => 'குழுவை புதுப்பிப்பதில் சிக்கல் ஏற்பட்டது. தயவு செய்து மீண்டும் முயற்சிக்கவும்.', 'delete' => 'குழுவை நீக்குவதில் ஒரு சிக்கல் இருந்தது. தயவு செய்து மீண்டும் முயற்சிக்கவும்.', ), );
uberbrady/snipe-it
resources/lang/ta/admin/groups/message.php
PHP
agpl-3.0
1,553
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models class ResConfigSettings(models.TransientModel): _inherit = "res.config.settings" google_drive_authorization_code = fields.Char(string='Authorization Code') google_drive_uri = fields.Char(compute='_compute_drive_uri', string='URI', help="The URL to generate the authorization code from Google") @api.depends('google_drive_authorization_code') def _compute_drive_uri(self): google_drive_uri = self.env['google.service']._get_google_token_uri('drive', scope=self.env['google.drive.config'].get_google_scope()) for config in self: config.google_drive_uri = google_drive_uri @api.model def get_values(self): res = super(ResConfigSettings, self).get_values() res.update( google_drive_authorization_code=self.env['ir.config_parameter'].sudo().get_param('google_drive_authorization_code'), ) return res def set_values(self): super(ResConfigSettings, self).set_values() params = self.env['ir.config_parameter'].sudo() authorization_code = self.google_drive_authorization_code refresh_token = False if authorization_code and authorization_code != params.get_param('google_drive_authorization_code'): refresh_token = self.env['google.service'].generate_refresh_token('drive', authorization_code) params.set_param('google_drive_authorization_code', authorization_code) params.set_param('google_drive_refresh_token', refresh_token)
Aravinthu/odoo
addons/google_drive/models/res_config_settings.py
Python
agpl-3.0
1,634
#Track Items Using Barcode A barcode is a value decoded into vertical spaced lines. Barcode scanners are the input medium, like Keyboard. When it scans a barcode, the data appears in the computer screens at the point of a cursor. To enable barcode feature in ERPNext go to: `Setup > Customize > Features Setup` Check "Item Barcode". <img alt="Material Transfer" class="screenshot" src="{{docs_base_url}}/assets/img/articles/barcode-feature-setup.png"> Now a new field "Barcode" will be appear in Item master. Enter barcode while creating a new item. <img alt="Material Transfer" class="screenshot" src="{{docs_base_url}}/assets/img/articles/barcode-item-master.png"> Once barcode field is updated in item master, items can be fetched using barcode. This feature will be availble in Delivery Note, Sales Invoice and Purchase Receipt transactions only. <img alt="Material Transfer" class="screenshot" src="{{docs_base_url}}/assets/img/articles/barcode-item-selection.gif"> <!-- markdown -->
indictranstech/osmosis-erpnext
erpnext/docs/user/manual/en/stock/articles/track-items-using-barcode.md
Markdown
agpl-3.0
998
/** * Orthanc - A Lightweight, RESTful DICOM Store * Copyright (C) 2012-2015 Sebastien Jodogne, Medical Physics * Department, University Hospital of Liege, Belgium * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * In addition, as a special exception, the copyright holders of this * program give permission to link the code of its release with the * OpenSSL project's "OpenSSL" library (or with modified versions of it * that use the same license as the "OpenSSL" library), and distribute * the linked executables. You must obey the GNU General Public License * in all respects for all of the code used other than "OpenSSL". If you * modify file(s) with this exception, you may extend this exception to * your version of the file(s), but you are not obligated to do so. If * you do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source files * in the program, then also delete it here. * * 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 "PrecompiledHeaders.h" #include "Uuid.h" // http://stackoverflow.com/a/1626302 extern "C" { #ifdef WIN32 #include <rpc.h> #else #include <uuid/uuid.h> #endif } #include <boost/filesystem.hpp> namespace Orthanc { namespace Toolbox { std::string GenerateUuid() { #ifdef WIN32 UUID uuid; UuidCreate ( &uuid ); unsigned char * str; UuidToStringA ( &uuid, &str ); std::string s( ( char* ) str ); RpcStringFreeA ( &str ); #else uuid_t uuid; uuid_generate_random ( uuid ); char s[37]; uuid_unparse ( uuid, s ); #endif return s; } bool IsUuid(const std::string& str) { if (str.size() != 36) { return false; } for (size_t i = 0; i < str.length(); i++) { if (i == 8 || i == 13 || i == 18 || i == 23) { if (str[i] != '-') return false; } else { if (!isalnum(str[i])) return false; } } return true; } bool StartsWithUuid(const std::string& str) { if (str.size() < 36) { return false; } if (str.size() == 36) { return IsUuid(str); } assert(str.size() > 36); if (!isspace(str[36])) { return false; } return IsUuid(str.substr(0, 36)); } static std::string CreateTemporaryPath(const char* extension) { #if BOOST_HAS_FILESYSTEM_V3 == 1 boost::filesystem::path tmpDir = boost::filesystem::temp_directory_path(); #elif defined(__linux__) boost::filesystem::path tmpDir("/tmp"); #else #error Support your platform here #endif // We use UUID to create unique path to temporary files std::string filename = "Orthanc-" + Orthanc::Toolbox::GenerateUuid(); if (extension != NULL) { filename.append(extension); } tmpDir /= filename; return tmpDir.string(); } TemporaryFile::TemporaryFile() : path_(CreateTemporaryPath(NULL)) { } TemporaryFile::TemporaryFile(const char* extension) : path_(CreateTemporaryPath(extension)) { } TemporaryFile::~TemporaryFile() { boost::filesystem::remove(path_); } } }
rbetancor/orthanc-webviewer
Orthanc/Uuid.cpp
C++
agpl-3.0
3,863
/* * ref.c: reference counting * * Copyright (C) 2009-2011 David Lutterkort * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: David Lutterkort <lutter@redhat.com> */ #include <config.h> #include "ref.h" #include <stdlib.h> int ref_make_ref(void *ptrptr, size_t size, size_t ref_ofs) { *(void**) ptrptr = calloc(1, size); if (*(void **)ptrptr == NULL) { return -1; } else { void *ptr = *(void **)ptrptr; *((ref_t *) ((char*) ptr + ref_ofs)) = 1; return 0; } } /* * Local variables: * indent-tabs-mode: nil * c-indent-level: 4 * c-basic-offset: 4 * tab-width: 4 * End: */
camptocamp/augeas-debian
src/ref.c
C
lgpl-2.1
1,339
// @(#)root/ged:$Id$ // Author: Ilka Antcheva 11/05/04 /************************************************************************* * Copyright (C) 1995-2002, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #ifndef ROOT_TAxisEditor #define ROOT_TAxisEditor ////////////////////////////////////////////////////////////////////////// // // // TAxisEditor // // // // Implements GUI for axis attributes. // // // ////////////////////////////////////////////////////////////////////////// #ifndef ROOT_TGedFrame #include "TGedFrame.h" #endif class TAxis; class TGLabel; class TGComboBox; class TGNumberEntry; class TGTextEntry; class TGCheckButton; class TGColorSelect; class TGFontTypeComboBox; class TAxisEditor : public TGedFrame { protected: TAxis *fAxis; // axis object TGColorSelect *fAxisColor; // color selection widget TGCheckButton *fLogAxis; // logarithmic check box TGNumberEntry *fTickLength; // tick length number entry TGNumberEntry *fDiv1; // primary axis division number entry TGNumberEntry *fDiv2; // secondary axis division number entry TGNumberEntry *fDiv3; // tertiary axis division number entry TGCheckButton *fOptimize; // tick optimization check box TGCheckButton *fTicksBoth; // check box setting ticks on both axis sides TGCheckButton *fMoreLog; // more logarithmic labels check box Int_t fTicksFlag; // positive/negative ticks' flag TGTextEntry *fTitle; // axis title input field TGColorSelect *fTitleColor; // color selection widget TGFontTypeComboBox *fTitleFont; // title font combo box Int_t fTitlePrec; // font precision level TGNumberEntry *fTitleSize; // title size number entry TGNumberEntry *fTitleOffset; // title offset number entry TGCheckButton *fCentered; // check button for centered title TGCheckButton *fRotated; // check button for rotated title TGColorSelect *fLabelColor; // color selection widget TGFontTypeComboBox *fLabelFont; // label font combo box Int_t fLabelPrec; // font precision level TGNumberEntry *fLabelSize; // label size number entry TGNumberEntry *fLabelOffset; // label offset number entry TGCheckButton *fNoExponent; // check box for No exponent choice TGCheckButton *fDecimal; // decimal part check box virtual void ConnectSignals2Slots(); public: TAxisEditor(const TGWindow *p = 0, Int_t width = 140, Int_t height = 30, UInt_t options = kChildFrame, Pixel_t back = GetDefaultFrameBackground()); virtual ~TAxisEditor(); virtual void SetModel(TObject* obj); // slots related to axis attributes virtual void DoTickLength(); virtual void DoAxisColor(Pixel_t color); virtual void DoTicks(); virtual void DoDivisions(); virtual void DoLogAxis(); virtual void DoMoreLog(); // slots related to axis title attributes virtual void DoTitleColor(Pixel_t color); virtual void DoTitle(const char *text); virtual void DoTitleSize(); virtual void DoTitleFont(Int_t font); virtual void DoTitleOffset(); virtual void DoTitleCentered(); virtual void DoTitleRotated(); // slots related to axis labels attributes virtual void DoLabelColor(Pixel_t color); virtual void DoLabelSize(); virtual void DoLabelFont(Int_t font); virtual void DoLabelOffset(); virtual void DoNoExponent(); virtual void DoDecimal(Bool_t on); ClassDef(TAxisEditor,0) // axis editor }; #endif
dawehner/root
gui/ged/inc/TAxisEditor.h
C
lgpl-2.1
4,432
/** * Copyright © 2002 Instituto Superior Técnico * * This file is part of FenixEdu Academic. * * FenixEdu Academic is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * FenixEdu Academic 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 FenixEdu Academic. If not, see <http://www.gnu.org/licenses/>. */ package org.fenixedu.academic.ui.faces.components.util; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import org.apache.struts.util.MessageResources; import org.fenixedu.academic.domain.Exam; import org.fenixedu.academic.domain.ExecutionCourse; import org.fenixedu.academic.domain.Project; import org.fenixedu.academic.domain.WrittenEvaluation; import org.fenixedu.academic.domain.WrittenTest; import org.fenixedu.academic.util.Bundle; import org.fenixedu.academic.util.DateFormatUtil; public class CalendarLink { private Calendar objectOccurrence; private String objectLinkLabel; private Map<String, String> linkParameters = new HashMap<String, String>(); private boolean asLink; public CalendarLink(boolean asLink) { setAsLink(asLink); } public CalendarLink() { this(true); } public CalendarLink(final ExecutionCourse executionCourse, final WrittenEvaluation writtenEvaluation, final Locale locale) { setObjectOccurrence(writtenEvaluation.getDay()); setObjectLinkLabel(constructCalendarPresentation(executionCourse, writtenEvaluation, locale)); } public CalendarLink(final ExecutionCourse executionCourse, final Project project, final Date date, final String tail, final Locale locale) { setObjectOccurrence(date); setObjectLinkLabel(constructCalendarPresentation(executionCourse, project, date, tail, locale)); } public void setObjectOccurrence(Calendar objectOccurrence) { this.objectOccurrence = objectOccurrence; } public void setObjectOccurrence(Date objectOccurrence) { final Calendar calendar = Calendar.getInstance(); calendar.setTime(objectOccurrence); this.objectOccurrence = calendar; } public Calendar getObjectOccurrence() { return this.objectOccurrence; } public void setObjectLinkLabel(String objectLinkLabel) { this.objectLinkLabel = objectLinkLabel; } public String getObjectLinkLabel() { return this.objectLinkLabel; } public void setLinkParameters(Map<String, String> linkParameters) { this.linkParameters = linkParameters; } public String giveLink(String editLinkPage) { final StringBuilder linkParameters = new StringBuilder(); linkParameters.append(editLinkPage); if (this.linkParameters != null && !this.linkParameters.isEmpty()) { linkParameters.append(editLinkPage.indexOf('?') > 0 ? '&' : '?'); for (final Iterator<Entry<String, String>> iterator = this.linkParameters.entrySet().iterator(); iterator.hasNext();) { final Entry<String, String> entry = iterator.next(); linkParameters.append(entry.getKey()); linkParameters.append('='); linkParameters.append(entry.getValue()); if (iterator.hasNext()) { linkParameters.append('&'); } } } return linkParameters.toString(); } public void addLinkParameter(final String key, final String value) { linkParameters.put(key, value); } private static final MessageResources messages = MessageResources.getMessageResources(Bundle.DEGREE); private String constructCalendarPresentation(final ExecutionCourse executionCourse, final WrittenEvaluation writtenEvaluation, final Locale locale) { final StringBuilder stringBuilder = new StringBuilder(); if (writtenEvaluation instanceof WrittenTest) { stringBuilder.append(messages.getMessage(locale, "label.evaluation.shortname.test")); } else if (writtenEvaluation instanceof Exam) { stringBuilder.append(messages.getMessage(locale, "label.evaluation.shortname.exam")); } stringBuilder.append(" "); stringBuilder.append(executionCourse.getSigla()); stringBuilder.append(" ("); stringBuilder.append(DateFormatUtil.format("HH:mm", writtenEvaluation.getBeginningDate())); stringBuilder.append("-"); stringBuilder.append(DateFormatUtil.format("HH:mm", writtenEvaluation.getEndDate())); stringBuilder.append(")"); return stringBuilder.toString(); } private String constructCalendarPresentation(final ExecutionCourse executionCourse, final Project project, final Date time, final String tail, final Locale locale) { final StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(messages.getMessage(locale, "label.evaluation.shortname.project")); stringBuilder.append(" "); stringBuilder.append(executionCourse.getSigla()); stringBuilder.append(" ("); stringBuilder.append(DateFormatUtil.format("HH:mm", time)); stringBuilder.append(") "); stringBuilder.append(tail); return stringBuilder.toString(); } public boolean isAsLink() { return asLink; } public void setAsLink(boolean asLink) { this.asLink = asLink; } }
pedrosan7os/fenixedu-academic
src/main/java/org/fenixedu/academic/ui/faces/components/util/CalendarLink.java
Java
lgpl-3.0
5,981
// personal includes ".h" #include "EUTELESCOPE.h" #include "EUTelBaseDetector.h" #include "EUTelTLUDetector.h" // system includes <> #include <iostream> #include <iomanip> #include <vector> #include <string> using namespace std; using namespace eutelescope; EUTelTLUDetector::EUTelTLUDetector() : EUTelBaseDetector() { _name = "TLU"; // nothing else to do ! } void EUTelTLUDetector::setAndMask(unsigned short value) { _andMask = value; } void EUTelTLUDetector::setOrMask(unsigned short value) { _orMask = value; } void EUTelTLUDetector::setVetoMask(unsigned short value) { _vetoMask = value; } void EUTelTLUDetector::setDUTMask(unsigned short value) { _dutMask = value; } void EUTelTLUDetector::setFirmwareID(unsigned short value) { _firmwareID = value; } void EUTelTLUDetector::setTimeInterval(short value) { _timeInterval = value; } void EUTelTLUDetector::print(ostream &os) const { size_t w = 35; os << resetiosflags(ios::right) << setiosflags(ios::left) << setfill('.') << setw(w) << setiosflags(ios::left) << "Detector name " << resetiosflags(ios::left) << " " << _name << endl << setw(w) << setiosflags(ios::left) << "AndMask " << resetiosflags(ios::left) << " 0x" << to_hex(_andMask, 2) << endl << setw(w) << setiosflags(ios::left) << "OrMask " << resetiosflags(ios::left) << " 0x" << to_hex(_orMask, 2) << endl << setw(w) << setiosflags(ios::left) << "VetoMask " << resetiosflags(ios::left) << " 0x" << to_hex(_vetoMask, 2) << endl << setw(w) << setiosflags(ios::left) << "DUTMask " << resetiosflags(ios::left) << " 0x" << to_hex(_dutMask, 2) << endl << setw(w) << setiosflags(ios::left) << "FirmwareID " << resetiosflags(ios::left) << " " << _firmwareID << endl << setw(w) << setiosflags(ios::left) << "TimeInterval " << resetiosflags(ios::left) << " " << _timeInterval << setfill(' ') << endl; }
freidt/eudaq
nreader/detdescription/EUTelTLUDetector.cc
C++
lgpl-3.0
1,905
package uk.co.alt236.bluetoothlelib.device.beacon.ibeacon; /** * */ public class IBeaconConstants { public static final byte[] MANUFACTURER_DATA_IBEACON_PREFIX = {0x4C, 0x00, 0x02, 0x15}; }
StuartGuo/Bluetooth-LE-Library---Android
library/src/main/java/uk/co/alt236/bluetoothlelib/device/beacon/ibeacon/IBeaconConstants.java
Java
apache-2.0
198
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/autocomplete/autocomplete_match.h" #include "base/basictypes.h" #include "testing/gtest/include/gtest/gtest.h" TEST(AutocompleteMatchTest, MoreRelevant) { struct RelevantCases { int r1; int r2; bool expected_result; } cases[] = { { 10, 0, true }, { 10, -5, true }, { -5, 10, false }, { 0, 10, false }, { -10, -5, false }, { -5, -10, true }, }; AutocompleteMatch m1(NULL, 0, false, AutocompleteMatch::URL_WHAT_YOU_TYPED); AutocompleteMatch m2(NULL, 0, false, AutocompleteMatch::URL_WHAT_YOU_TYPED); for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i) { m1.relevance = cases[i].r1; m2.relevance = cases[i].r2; EXPECT_EQ(cases[i].expected_result, AutocompleteMatch::MoreRelevant(m1, m2)); } } TEST(AutocompleteMatchTest, MergeClassifications) { // Merging two empty vectors should result in an empty vector. EXPECT_EQ(std::string(), AutocompleteMatch::ClassificationsToString( AutocompleteMatch::MergeClassifications( AutocompleteMatch::ACMatchClassifications(), AutocompleteMatch::ACMatchClassifications()))); // If one vector is empty and the other is "trivial" but non-empty (i.e. (0, // NONE)), the non-empty vector should be returned. EXPECT_EQ("0,0", AutocompleteMatch::ClassificationsToString( AutocompleteMatch::MergeClassifications( AutocompleteMatch::ClassificationsFromString("0,0"), AutocompleteMatch::ACMatchClassifications()))); EXPECT_EQ("0,0", AutocompleteMatch::ClassificationsToString( AutocompleteMatch::MergeClassifications( AutocompleteMatch::ACMatchClassifications(), AutocompleteMatch::ClassificationsFromString("0,0")))); // Ditto if the one-entry vector is non-trivial. EXPECT_EQ("0,1", AutocompleteMatch::ClassificationsToString( AutocompleteMatch::MergeClassifications( AutocompleteMatch::ClassificationsFromString("0,1"), AutocompleteMatch::ACMatchClassifications()))); EXPECT_EQ("0,1", AutocompleteMatch::ClassificationsToString( AutocompleteMatch::MergeClassifications( AutocompleteMatch::ACMatchClassifications(), AutocompleteMatch::ClassificationsFromString("0,1")))); // Merge an unstyled one-entry vector with a styled one-entry vector. EXPECT_EQ("0,1", AutocompleteMatch::ClassificationsToString( AutocompleteMatch::MergeClassifications( AutocompleteMatch::ClassificationsFromString("0,0"), AutocompleteMatch::ClassificationsFromString("0,1")))); // Test simple cases of overlap. EXPECT_EQ("0,3," "1,2", AutocompleteMatch::ClassificationsToString( AutocompleteMatch::MergeClassifications( AutocompleteMatch::ClassificationsFromString("0,1," "1,0"), AutocompleteMatch::ClassificationsFromString("0,2")))); EXPECT_EQ("0,3," "1,2", AutocompleteMatch::ClassificationsToString( AutocompleteMatch::MergeClassifications( AutocompleteMatch::ClassificationsFromString("0,2"), AutocompleteMatch::ClassificationsFromString("0,1," "1,0")))); // Test the case where both vectors have classifications at the same // positions. EXPECT_EQ("0,3", AutocompleteMatch::ClassificationsToString( AutocompleteMatch::MergeClassifications( AutocompleteMatch::ClassificationsFromString("0,1," "1,2"), AutocompleteMatch::ClassificationsFromString("0,2," "1,1")))); // Test an arbitrary complicated case. EXPECT_EQ("0,2," "1,0," "2,1," "4,3," "5,7," "6,3," "7,7," "15,1," "17,0", AutocompleteMatch::ClassificationsToString( AutocompleteMatch::MergeClassifications( AutocompleteMatch::ClassificationsFromString( "0,0," "2,1," "4,3," "7,7," "10,6," "15,0"), AutocompleteMatch::ClassificationsFromString( "0,2," "1,0," "5,7," "6,1," "17,0")))); }
plxaye/chromium
src/chrome/browser/autocomplete/autocomplete_match_unittest.cc
C++
apache-2.0
4,260
// This is a generated file. Not intended for manual editing. package com.intellij.sh.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.intellij.psi.util.PsiTreeUtil; import static com.intellij.sh.ShTypes.*; import com.intellij.sh.psi.*; public class ShUnaryExpressionImpl extends ShExpressionImpl implements ShUnaryExpression { public ShUnaryExpressionImpl(ASTNode node) { super(node); } @Override public void accept(@NotNull ShVisitor visitor) { visitor.visitUnaryExpression(this); } @Override public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof ShVisitor) accept((ShVisitor)visitor); else super.accept(visitor); } @Override @Nullable public ShExpression getExpression() { return findChildByClass(ShExpression.class); } @Override @Nullable public PsiElement getMinus() { return findChildByType(MINUS); } @Override @Nullable public PsiElement getPlus() { return findChildByType(PLUS); } }
smmribeiro/intellij-community
plugins/sh/gen/com/intellij/sh/psi/impl/ShUnaryExpressionImpl.java
Java
apache-2.0
1,138
/* * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.das.analytics.rest.beans; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; /** * This class represents a facet object bean. facet object defines the hierarchical fieldName, * which can be drilled down. This can be used as a value in a record. * Example : * Assume a record represents a book. * Then the record field : value pairs will be, e.g. * Price : $50.00 * Author : firstName LastName * ISBN : 234325435445435436 * Published Date : "1987" , "March", "21" * * Here Publish Date will be a facet/categoryPath, since it can be drilled down to Year, then month and date * and categorizes by each level. * */ @XmlRootElement(name = "categoryPath") @XmlAccessorType(XmlAccessType.FIELD) public class DrillDownPathBean { @XmlElement(name = "path") private String[] path; @XmlElement(name = "fieldName") private String fieldName; /** * This constructor is for jax-rs json serialization/deserialization */ public DrillDownPathBean() { } public String[] getPath() { return path; } public String getFieldName() { return fieldName; } public void setPath(String[] path) { this.path = path; } public void setFieldName(String fieldName) { this.fieldName = fieldName; } }
wso2/product-das
modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/das/analytics/rest/beans/DrillDownPathBean.java
Java
apache-2.0
2,162
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.sql.planner.assertions; import com.facebook.presto.Session; import com.facebook.presto.cost.PlanNodeCost; import com.facebook.presto.metadata.Metadata; import com.facebook.presto.sql.planner.plan.LimitNode; import com.facebook.presto.sql.planner.plan.PlanNode; import static com.google.common.base.Preconditions.checkState; public class LimitMatcher implements Matcher { private final long limit; public LimitMatcher(long limit) { this.limit = limit; } @Override public boolean shapeMatches(PlanNode node) { if (!(node instanceof LimitNode)) { return false; } LimitNode limitNode = (LimitNode) node; return limitNode.getCount() == limit; } @Override public MatchResult detailMatches(PlanNode node, PlanNodeCost planNodeCost, Session session, Metadata metadata, SymbolAliases symbolAliases) { checkState(shapeMatches(node)); return MatchResult.match(); } }
gh351135612/presto
presto-main/src/test/java/com/facebook/presto/sql/planner/assertions/LimitMatcher.java
Java
apache-2.0
1,577
/* * JBoss, Home of Professional Open Source. * Copyright 2014 Red Hat, Inc., and individual 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. */ package io.undertow.util; import java.util.Collections; import java.util.HashMap; import java.util.Map; /** * NOTE: If you add a new method here you must also add it to {@link io.undertow.server.protocol.http.HttpRequestParser} * * @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a> */ public final class Methods { private Methods() { } public static final String OPTIONS_STRING = "OPTIONS"; public static final String GET_STRING = "GET"; public static final String HEAD_STRING = "HEAD"; public static final String POST_STRING = "POST"; public static final String PUT_STRING = "PUT"; public static final String DELETE_STRING = "DELETE"; public static final String TRACE_STRING = "TRACE"; public static final String CONNECT_STRING = "CONNECT"; public static final String PROPFIND_STRING = "PROPFIND"; public static final String PROPPATCH_STRING = "PROPPATCH"; public static final String MKCOL_STRING = "MKCOL"; public static final String COPY_STRING = "COPY"; public static final String MOVE_STRING = "MOVE"; public static final String LOCK_STRING = "LOCK"; public static final String UNLOCK_STRING = "UNLOCK"; public static final String ACL_STRING = "ACL"; public static final String REPORT_STRING = "REPORT"; public static final String VERSION_CONTROL_STRING = "VERSION-CONTROL"; public static final String CHECKIN_STRING = "CHECKIN"; public static final String CHECKOUT_STRING = "CHECKOUT"; public static final String UNCHECKOUT_STRING = "UNCHECKOUT"; public static final String SEARCH_STRING = "SEARCH"; public static final String MKWORKSPACE_STRING = "MKWORKSPACE"; public static final String UPDATE_STRING = "UPDATE"; public static final String LABEL_STRING = "LABEL"; public static final String MERGE_STRING = "MERGE"; public static final String BASELINE_CONTROL_STRING = "BASELINE_CONTROL"; public static final String MKACTIVITY_STRING = "MKACTIVITY"; public static final HttpString OPTIONS = new HttpString(OPTIONS_STRING); public static final HttpString GET = new HttpString(GET_STRING); public static final HttpString HEAD = new HttpString(HEAD_STRING); public static final HttpString POST = new HttpString(POST_STRING); public static final HttpString PUT = new HttpString(PUT_STRING); public static final HttpString DELETE = new HttpString(DELETE_STRING); public static final HttpString TRACE = new HttpString(TRACE_STRING); public static final HttpString CONNECT = new HttpString(CONNECT_STRING); public static final HttpString PROPFIND = new HttpString(PROPFIND_STRING); public static final HttpString PROPPATCH = new HttpString(PROPPATCH_STRING); public static final HttpString MKCOL = new HttpString(MKCOL_STRING); public static final HttpString COPY = new HttpString(COPY_STRING); public static final HttpString MOVE = new HttpString(MOVE_STRING); public static final HttpString LOCK = new HttpString(LOCK_STRING); public static final HttpString UNLOCK = new HttpString(UNLOCK_STRING); public static final HttpString ACL = new HttpString(ACL_STRING); public static final HttpString REPORT = new HttpString(REPORT_STRING); public static final HttpString VERSION_CONTROL = new HttpString(VERSION_CONTROL_STRING); public static final HttpString CHECKIN = new HttpString(CHECKIN_STRING); public static final HttpString CHECKOUT = new HttpString(CHECKOUT_STRING); public static final HttpString UNCHECKOUT = new HttpString(UNCHECKOUT_STRING); public static final HttpString SEARCH = new HttpString(SEARCH_STRING); public static final HttpString MKWORKSPACE = new HttpString(MKWORKSPACE_STRING); public static final HttpString UPDATE = new HttpString(UPDATE_STRING); public static final HttpString LABEL = new HttpString(LABEL_STRING); public static final HttpString MERGE = new HttpString(MERGE_STRING); public static final HttpString BASELINE_CONTROL = new HttpString(BASELINE_CONTROL_STRING); public static final HttpString MKACTIVITY = new HttpString(MKACTIVITY_STRING); private static final Map<String, HttpString> METHODS; static { Map<String, HttpString> methods = new HashMap<>(); putString(methods, OPTIONS); putString(methods, GET); putString(methods, HEAD); putString(methods, POST); putString(methods, PUT); putString(methods, DELETE); putString(methods, TRACE); putString(methods, CONNECT); putString(methods, PROPFIND); putString(methods, PROPPATCH); putString(methods, MKCOL); putString(methods, COPY); putString(methods, MOVE); putString(methods, LOCK); putString(methods, UNLOCK); putString(methods, ACL); putString(methods, REPORT); putString(methods, VERSION_CONTROL); putString(methods, CHECKIN); putString(methods, CHECKOUT); putString(methods, UNCHECKOUT); putString(methods, SEARCH); putString(methods, MKWORKSPACE); putString(methods, UPDATE); putString(methods, LABEL); putString(methods, MERGE); putString(methods, BASELINE_CONTROL); putString(methods, MKACTIVITY); METHODS = Collections.unmodifiableMap(methods); } private static void putString(Map<String, HttpString> methods, HttpString options) { methods.put(options.toString(), options); } public static HttpString fromString(String method) { HttpString res = METHODS.get(method); if(res == null) { return new HttpString(method); } return res; } }
TomasHofman/undertow
core/src/main/java/io/undertow/util/Methods.java
Java
apache-2.0
6,437
--- 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. title: globalization.getPreferredLanguage --- globalization.getPreferredLanguage =========== Get the string identifier for the client's current language. navigator.globalization.getPreferredLanguage(successCB, errorCB); Description ----------- It returns the language identifier string to the successCB callback with a properties object as a parameter. That object should have a ``value`` property with a String value. If there is an error getting the language, then the errorCB callback is invoked with a [GlobalizationError](GlobalizationError/globalizationerror.html) object as a parameter. The expected code for this error is [GlobalizationError](GlobalizationError/globalizationerror.html).UNKNOWN\_ERROR. Supported Platforms ------------------- - Android - BlackBerry WebWorks (OS 5.0 and higher) - iPhone - Windows Phone 8 Quick [Example](../storage/storage.opendatabase.html) ------------- In the case when the browser is set to the en\_US locale, this should display a popup dialog with the text "language: English". navigator.globalization.getPreferredLanguage( function (language) {alert('language: ' + language.value + '\n');}, function () {alert('Error getting language\n');} ); Full [Example](../storage/storage.opendatabase.html) ------------ <!DOCTYPE HTML> <html> <head> <title>Cordova</title> <script type="text/javascript" charset="utf-8" src="cordova-2.3.0.js"></script> <script type="text/javascript" charset="utf-8"> function checkLanguage() { navigator.globalization.getPreferredLanguage( function (language) {alert('language: ' + language.value + '\n');}, function () {alert('Error getting language\n');} ); } </script> </head> <body> <button onclick="checkLanguage()">Click for language</button> </body> </html> Windows Phone 8 Quirks ------- - Returns the ISO 639-1 two-letter code for the current language.
Icenium/cordova-docs
www/docs/en/2.3.0/cordova/globalization/globalization.getPreferredLanguage.md
Markdown
apache-2.0
2,849
package com.intellij.execution.configurations; /** * Configuration of such type can't be manually added or removed by the user; the template entry is hidden. */ public interface VirtualConfigurationType { }
siosio/intellij-community
platform/lang-api/src/com/intellij/execution/configurations/VirtualConfigurationType.java
Java
apache-2.0
210
@org.osgi.annotation.bundle.Export @org.osgi.annotation.versioning.Version("2.0.0") package bndtools.editor.model;
psoreide/bnd
bndtools.core/src/bndtools/editor/model/package-info.java
Java
apache-2.0
115
/* * * 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 grpc import ( "net" "testing" "time" "golang.org/x/net/context" "google.golang.org/grpc/credentials" ) const tlsDir = "testdata/" func TestDialTimeout(t *testing.T) { conn, err := Dial("Non-Existent.Server:80", WithTimeout(time.Millisecond), WithBlock(), WithInsecure()) if err == nil { conn.Close() } if err != context.DeadlineExceeded { t.Fatalf("Dial(_, _) = %v, %v, want %v", conn, err, context.DeadlineExceeded) } } func TestTLSDialTimeout(t *testing.T) { creds, err := credentials.NewClientTLSFromFile(tlsDir+"ca.pem", "x.test.youtube.com") if err != nil { t.Fatalf("Failed to create credentials %v", err) } conn, err := Dial("Non-Existent.Server:80", WithTransportCredentials(creds), WithTimeout(time.Millisecond), WithBlock()) if err == nil { conn.Close() } if err != context.DeadlineExceeded { t.Fatalf("Dial(_, _) = %v, %v, want %v", conn, err, context.DeadlineExceeded) } } func TestTLSServerNameOverwrite(t *testing.T) { overwriteServerName := "over.write.server.name" creds, err := credentials.NewClientTLSFromFile(tlsDir+"ca.pem", overwriteServerName) if err != nil { t.Fatalf("Failed to create credentials %v", err) } conn, err := Dial("Non-Existent.Server:80", WithTransportCredentials(creds)) if err != nil { t.Fatalf("Dial(_, _) = _, %v, want _, <nil>", err) } conn.Close() if conn.authority != overwriteServerName { t.Fatalf("%v.authority = %v, want %v", conn, conn.authority, overwriteServerName) } } func TestDialContextCancel(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) cancel() if _, err := DialContext(ctx, "Non-Existent.Server:80", WithBlock(), WithInsecure()); err != context.Canceled { t.Fatalf("DialContext(%v, _) = _, %v, want _, %v", ctx, err, context.Canceled) } } // blockingBalancer mimics the behavior of balancers whose initialization takes a long time. // In this test, reading from blockingBalancer.Notify() blocks forever. type blockingBalancer struct { ch chan []Address } func newBlockingBalancer() Balancer { return &blockingBalancer{ch: make(chan []Address)} } func (b *blockingBalancer) Start(target string, config BalancerConfig) error { return nil } func (b *blockingBalancer) Up(addr Address) func(error) { return nil } func (b *blockingBalancer) Get(ctx context.Context, opts BalancerGetOptions) (addr Address, put func(), err error) { return Address{}, nil, nil } func (b *blockingBalancer) Notify() <-chan []Address { return b.ch } func (b *blockingBalancer) Close() error { close(b.ch) return nil } func TestDialWithBlockingBalancer(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) dialDone := make(chan struct{}) go func() { DialContext(ctx, "Non-Existent.Server:80", WithBlock(), WithInsecure(), WithBalancer(newBlockingBalancer())) close(dialDone) }() cancel() <-dialDone } // securePerRPCCredentials always requires transport security. type securePerRPCCredentials struct{} func (c securePerRPCCredentials) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) { return nil, nil } func (c securePerRPCCredentials) RequireTransportSecurity() bool { return true } func TestCredentialsMisuse(t *testing.T) { tlsCreds, err := credentials.NewClientTLSFromFile(tlsDir+"ca.pem", "x.test.youtube.com") if err != nil { t.Fatalf("Failed to create authenticator %v", err) } // Two conflicting credential configurations if _, err := Dial("Non-Existent.Server:80", WithTransportCredentials(tlsCreds), WithBlock(), WithInsecure()); err != errCredentialsConflict { t.Fatalf("Dial(_, _) = _, %v, want _, %v", err, errCredentialsConflict) } // security info on insecure connection if _, err := Dial("Non-Existent.Server:80", WithPerRPCCredentials(securePerRPCCredentials{}), WithBlock(), WithInsecure()); err != errTransportCredentialsMissing { t.Fatalf("Dial(_, _) = _, %v, want _, %v", err, errTransportCredentialsMissing) } } func TestWithBackoffConfigDefault(t *testing.T) { testBackoffConfigSet(t, &DefaultBackoffConfig) } func TestWithBackoffConfig(t *testing.T) { b := BackoffConfig{MaxDelay: DefaultBackoffConfig.MaxDelay / 2} expected := b setDefaults(&expected) // defaults should be set testBackoffConfigSet(t, &expected, WithBackoffConfig(b)) } func TestWithBackoffMaxDelay(t *testing.T) { md := DefaultBackoffConfig.MaxDelay / 2 expected := BackoffConfig{MaxDelay: md} setDefaults(&expected) testBackoffConfigSet(t, &expected, WithBackoffMaxDelay(md)) } func testBackoffConfigSet(t *testing.T, expected *BackoffConfig, opts ...DialOption) { opts = append(opts, WithInsecure()) conn, err := Dial("foo:80", opts...) if err != nil { t.Fatalf("unexpected error dialing connection: %v", err) } if conn.dopts.bs == nil { t.Fatalf("backoff config not set") } actual, ok := conn.dopts.bs.(BackoffConfig) if !ok { t.Fatalf("unexpected type of backoff config: %#v", conn.dopts.bs) } if actual != *expected { t.Fatalf("unexpected backoff config on connection: %v, want %v", actual, expected) } conn.Close() } type testErr struct { temp bool } func (e *testErr) Error() string { return "test error" } func (e *testErr) Temporary() bool { return e.temp } var nonTemporaryError = &testErr{false} func nonTemporaryErrorDialer(addr string, timeout time.Duration) (net.Conn, error) { return nil, nonTemporaryError } func TestDialWithBlockErrorOnNonTemporaryErrorDialer(t *testing.T) { ctx, _ := context.WithTimeout(context.Background(), 100*time.Millisecond) if _, err := DialContext(ctx, "", WithInsecure(), WithDialer(nonTemporaryErrorDialer), WithBlock(), FailOnNonTempDialError(true)); err != nonTemporaryError { t.Fatalf("Dial(%q) = %v, want %v", "", err, nonTemporaryError) } // Without FailOnNonTempDialError, gRPC will retry to connect, and dial should exit with time out error. if _, err := DialContext(ctx, "", WithInsecure(), WithDialer(nonTemporaryErrorDialer), WithBlock()); err != context.DeadlineExceeded { t.Fatalf("Dial(%q) = %v, want %v", "", err, context.DeadlineExceeded) } }
otsimo/analytics
vendor/src/google.golang.org/grpc/clientconn_test.go
GO
apache-2.0
7,643
/* * Copyright 2003-2013 Dave Griffith, Bas Leijdekkers * * 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.siyeh.ig.abstraction; import com.intellij.codeInsight.AnnotationUtil; import com.intellij.codeInspection.ui.MultipleCheckboxOptionsPanel; import com.intellij.psi.*; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.util.PsiUtil; import com.siyeh.InspectionGadgetsBundle; import com.siyeh.ig.BaseInspection; import com.siyeh.ig.BaseInspectionVisitor; import com.siyeh.ig.InspectionGadgetsFix; import com.siyeh.ig.fixes.IntroduceConstantFix; import com.siyeh.ig.fixes.SuppressForTestsScopeFix; import com.siyeh.ig.psiutils.ClassUtils; import com.siyeh.ig.psiutils.ExpressionUtils; import com.siyeh.ig.psiutils.MethodUtils; import com.siyeh.ig.psiutils.TypeUtils; import org.jetbrains.annotations.NotNull; import javax.swing.*; public class MagicNumberInspection extends BaseInspection { @SuppressWarnings("PublicField") public boolean ignoreInHashCode = true; @SuppressWarnings({"PublicField", "UnusedDeclaration"}) public boolean ignoreInTestCode = false; // keep for compatibility @SuppressWarnings("PublicField") public boolean ignoreInAnnotations = true; @SuppressWarnings("PublicField") public boolean ignoreInitialCapacity = false; @Override protected InspectionGadgetsFix @NotNull [] buildFixes(Object... infos) { final PsiElement context = (PsiElement)infos[0]; final InspectionGadgetsFix fix = SuppressForTestsScopeFix.build(this, context); if (fix == null) { return new InspectionGadgetsFix[] {new IntroduceConstantFix()}; } return new InspectionGadgetsFix[] {new IntroduceConstantFix(), fix}; } @Override protected boolean buildQuickFixesOnlyForOnTheFlyErrors() { return true; } @Override @NotNull public String buildErrorString(Object... infos) { return InspectionGadgetsBundle.message("magic.number.problem.descriptor"); } @Override public JComponent createOptionsPanel() { final MultipleCheckboxOptionsPanel panel = new MultipleCheckboxOptionsPanel(this); panel.addCheckbox(InspectionGadgetsBundle.message("inspection.option.ignore.in.hashcode"), "ignoreInHashCode"); panel.addCheckbox(InspectionGadgetsBundle.message("inspection.option.ignore.in.annotations"), "ignoreInAnnotations"); panel.addCheckbox(InspectionGadgetsBundle.message("inspection.option.ignore.as.initial.capacity"), "ignoreInitialCapacity"); return panel; } @Override public BaseInspectionVisitor buildVisitor() { return new MagicNumberVisitor(); } private class MagicNumberVisitor extends BaseInspectionVisitor { @Override public void visitLiteralExpression(@NotNull PsiLiteralExpression expression) { super.visitLiteralExpression(expression); final PsiType type = expression.getType(); if (!ClassUtils.isPrimitiveNumericType(type) || PsiType.CHAR.equals(type)) { return; } if (isSpecialCaseLiteral(expression) || isFinalVariableInitialization(expression)) { return; } if (ignoreInHashCode) { final PsiMethod containingMethod = PsiTreeUtil.getParentOfType(expression, PsiMethod.class, true, PsiClass.class, PsiLambdaExpression.class); if (MethodUtils.isHashCode(containingMethod)) { return; } } if (ignoreInAnnotations) { final boolean insideAnnotation = AnnotationUtil.isInsideAnnotation(expression); if (insideAnnotation) { return; } } if (ignoreInitialCapacity && isInitialCapacity(expression)) { return; } final PsiField field = PsiTreeUtil.getParentOfType(expression, PsiField.class, true, PsiCallExpression.class); if (field != null && PsiUtil.isCompileTimeConstant(field)) { return; } final PsiElement parent = expression.getParent(); if (parent instanceof PsiPrefixExpression) { registerError(parent, parent); } else { registerError(expression, expression); } } private boolean isInitialCapacity(PsiLiteralExpression expression) { final PsiElement element = PsiTreeUtil.skipParentsOfType(expression, PsiTypeCastExpression.class, PsiParenthesizedExpression.class); if (!(element instanceof PsiExpressionList)) { return false; } final PsiElement parent = element.getParent(); if (!(parent instanceof PsiNewExpression)) { return false; } final PsiNewExpression newExpression = (PsiNewExpression)parent; return TypeUtils.expressionHasTypeOrSubtype(newExpression, CommonClassNames.JAVA_LANG_ABSTRACT_STRING_BUILDER, CommonClassNames.JAVA_UTIL_MAP, CommonClassNames.JAVA_UTIL_COLLECTION, "java.io.ByteArrayOutputStream", "java.awt.Dimension") != null; } private boolean isSpecialCaseLiteral(PsiLiteralExpression expression) { final Object object = ExpressionUtils.computeConstantExpression(expression); if (object instanceof Integer) { final int i = ((Integer)object).intValue(); return i >= 0 && i <= 10 || i == 100 || i == 1000; } else if (object instanceof Long) { final long l = ((Long)object).longValue(); return l >= 0L && l <= 2L; } else if (object instanceof Double) { final double d = ((Double)object).doubleValue(); return d == 1.0 || d == 0.0; } else if (object instanceof Float) { final float f = ((Float)object).floatValue(); return f == 1.0f || f == 0.0f; } return false; } public boolean isFinalVariableInitialization(PsiExpression expression) { final PsiElement parent = PsiTreeUtil.getParentOfType(expression, PsiVariable.class, PsiAssignmentExpression.class); final PsiVariable variable; if (!(parent instanceof PsiVariable)) { if (!(parent instanceof PsiAssignmentExpression)) { return false; } final PsiAssignmentExpression assignmentExpression = (PsiAssignmentExpression)parent; final PsiExpression lhs = assignmentExpression.getLExpression(); if (!(lhs instanceof PsiReferenceExpression)) { return false; } final PsiReferenceExpression referenceExpression = (PsiReferenceExpression)lhs; final PsiElement target = referenceExpression.resolve(); if (!(target instanceof PsiVariable)) { return false; } variable = (PsiVariable)target; } else { variable = (PsiVariable)parent; } return variable.hasModifierProperty(PsiModifier.FINAL); } } }
siosio/intellij-community
plugins/InspectionGadgets/src/com/siyeh/ig/abstraction/MagicNumberInspection.java
Java
apache-2.0
7,475
package main import ( "fmt" "os" "path/filepath" "github.com/karrick/godirwalk" "github.com/pkg/errors" ) func main() { if len(os.Args) < 2 { fmt.Fprintf(os.Stderr, "usage: %s dir1 [dir2 [dir3...]]\n", filepath.Base(os.Args[0])) os.Exit(2) } scratchBuffer := make([]byte, 64*1024) // allocate once and re-use each time var count, total int var err error for _, arg := range os.Args[1:] { count, err = pruneEmptyDirectories(arg, scratchBuffer) total += count if err != nil { break } } fmt.Fprintf(os.Stderr, "Removed %d empty directories\n", total) if err != nil { fmt.Fprintf(os.Stderr, "ERROR: %s\n", err) os.Exit(1) } } func pruneEmptyDirectories(osDirname string, scratchBuffer []byte) (int, error) { var count int err := godirwalk.Walk(osDirname, &godirwalk.Options{ Unsorted: true, ScratchBuffer: scratchBuffer, Callback: func(_ string, _ *godirwalk.Dirent) error { // no-op while diving in; all the fun happens in PostChildrenCallback return nil }, PostChildrenCallback: func(osPathname string, _ *godirwalk.Dirent) error { deChildren, err := godirwalk.ReadDirents(osPathname, scratchBuffer) if err != nil { return errors.Wrap(err, "cannot ReadDirents") } // NOTE: ReadDirents skips "." and ".." if len(deChildren) > 0 { return nil // this directory has children; no additional work here } if osPathname == osDirname { return nil // do not remove provided root directory } err = os.Remove(osPathname) if err == nil { count++ } return err }, }) return count, err }
pweil-/origin
vendor/github.com/karrick/godirwalk/examples/clean-empties/main.go
GO
apache-2.0
1,592
/* * Copyright 2014 Open Networking Laboratory * * 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 org.onosproject.provider.pcep.tunnel.impl; import org.onosproject.net.DeviceId; import org.onosproject.pcep.api.PcepController; import org.onosproject.pcep.api.PcepDpid; import org.onosproject.pcep.api.PcepLinkListener; import org.onosproject.pcep.api.PcepSwitch; import org.onosproject.pcep.api.PcepSwitchListener; import org.onosproject.pcep.api.PcepTunnel; import org.onosproject.pcep.api.PcepTunnelListener; public class PcepControllerAdapter implements PcepController { @Override public Iterable<PcepSwitch> getSwitches() { return null; } @Override public PcepSwitch getSwitch(PcepDpid did) { return null; } @Override public void addListener(PcepSwitchListener listener) { } @Override public void removeListener(PcepSwitchListener listener) { } @Override public void addLinkListener(PcepLinkListener listener) { } @Override public void removeLinkListener(PcepLinkListener listener) { } @Override public void addTunnelListener(PcepTunnelListener listener) { } @Override public void removeTunnelListener(PcepTunnelListener listener) { } @Override public PcepTunnel applyTunnel(DeviceId srcDid, DeviceId dstDid, long srcPort, long dstPort, long bandwidth, String name) { return null; } @Override public Boolean deleteTunnel(String id) { return null; } @Override public Boolean updateTunnelBandwidth(String id, long bandwidth) { return null; } @Override public void getTunnelStatistics(String pcepTunnelId) { } }
packet-tracker/onos
providers/pcep/tunnel/src/test/java/org/onosproject/provider/pcep/tunnel/impl/PcepControllerAdapter.java
Java
apache-2.0
2,267
########################################################################### # # Copyright 2016 Samsung Electronics All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, # either express or implied. See the License for the specific # language governing permissions and limitations under the License. # ########################################################################### ############################################################################ # apps/system/i2c/Makefile # # Copyright (C) 2011-2012 Gregory Nutt. All rights reserved. # Author: Gregory Nutt <gnutt@nuttx.org> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # 3. Neither the name NuttX nor the names of its contributors may be # used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS # OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED # AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ############################################################################ -include $(TOPDIR)/.config -include $(TOPDIR)/Make.defs include $(APPDIR)/Make.defs # I2C tool ASRCS = CSRCS = i2c_bus.c i2c_common.c i2c_dev.c i2c_get.c i2c_set.c i2c_verf.c MAINSRC = i2c_main.c AOBJS = $(ASRCS:.S=$(OBJEXT)) COBJS = $(CSRCS:.c=$(OBJEXT)) MAINOBJ = $(MAINSRC:.c=$(OBJEXT)) SRCS = $(ASRCS) $(CSRCS) $(MAINSRC) OBJS = $(AOBJS) $(COBJS) ifneq ($(CONFIG_BUILD_KERNEL),y) OBJS += $(MAINOBJ) endif ifeq ($(CONFIG_WINDOWS_NATIVE),y) BIN = ..\..\libapps$(LIBEXT) else ifeq ($(WINTOOL),y) BIN = ..\\..\\libapps$(LIBEXT) else BIN = ../../libapps$(LIBEXT) endif endif ifeq ($(WINTOOL),y) INSTALL_DIR = "${shell cygpath -w $(BIN_DIR)}" else INSTALL_DIR = $(BIN_DIR) endif CONFIG_XYZ_PROGNAME ?= i2c$(EXEEXT) PROGNAME = $(CONFIG_XYZ_PROGNAME) ROOTDEPPATH = --dep-path . VPATH = APPNAME = i2c FUNCNAME = i2c_main PRIORITY = SCHED_PRIORITY_DEFAULT STACKSIZE = 2048 THREADEXEC = TASH_EXECMD_ASYNC # Build targets all: .built .PHONY: context .depend depend clean distclean $(AOBJS): %$(OBJEXT): %.S $(call ASSEMBLE, $<, $@) $(COBJS) $(MAINOBJ): %$(OBJEXT): %.c $(call COMPILE, $<, $@) .built: $(OBJS) $(call ARCHIVE, $(BIN), $(OBJS)) $(Q) touch .built ifeq ($(CONFIG_BUILD_KERNEL),y) $(BIN_DIR)$(DELIM)$(PROGNAME): $(OBJS) $(MAINOBJ) @echo "LD: $(PROGNAME)" $(Q) $(LD) $(LDELFFLAGS) $(LDLIBPATH) -o $(INSTALL_DIR)$(DELIM)$(PROGNAME) $(ARCHCRT0OBJ) $(MAINOBJ) $(LDLIBS) $(Q) $(NM) -u $(INSTALL_DIR)$(DELIM)$(PROGNAME) install: $(BIN_DIR)$(DELIM)$(PROGNAME) else install: endif ifeq ($(CONFIG_BUILTIN_APPS)$(CONFIG_SYSTEM_I2CTOOL),yy) $(BUILTIN_REGISTRY)$(DELIM)$(FUNCNAME).bdat: $(DEPCONFIG) Makefile $(Q) $(call REGISTER,$(APPNAME),$(FUNCNAME),$(THREADEXEC),$(PRIORITY),$(STACKSIZE)) context: $(BUILTIN_REGISTRY)$(DELIM)$(FUNCNAME).bdat else context: endif .depend: Makefile $(SRCS) $(Q) $(MKDEP) $(ROOTDEPPATH) "$(CC)" -- $(CFLAGS) -- $(SRCS) >Make.dep $(Q) touch $@ depend: .depend clean: $(call DELFILE, .built) $(call CLEAN) distclean: clean $(call DELFILE, Make.dep) $(call DELFILE, .depend) -include Make.dep .PHONY: preconfig preconfig:
jsdosa/TizenRT
apps/system/i2c/Makefile
Makefile
apache-2.0
4,624
// "Replace 'collect(toUnmodifiableList())' with 'toList()'" "true" import java.util.List; import java.util.stream.*; class X { void test(Stream<String> stream) { List<String> list = stream.collect<caret>(Collectors.toUnmodifiableList()); } }
smmribeiro/intellij-community
java/java-tests/testData/inspection/streamApiCallChains/beforeUnmodifiableListJava16.java
Java
apache-2.0
251
/* * Copyright 2005-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.springframework.ldap.core.support; import org.springframework.ldap.core.ContextMapper; import javax.naming.NamingException; import javax.naming.ldap.HasControls; /** * Extension of the {@link org.springframework.ldap.core.ContextMapper} interface that allows * controls to be passed to the mapper implementation. Uses Java 5 covariant * return types to override the return type of the * {@link #mapFromContextWithControls(Object, javax.naming.ldap.HasControls)} method to be the * type parameter T. * * @author Tim Terry * @author Ulrik Sandberg * @param <T> return type of the * {@link #mapFromContextWithControls(Object, javax.naming.ldap.HasControls)} method */ public interface ContextMapperWithControls<T> extends ContextMapper<T> { T mapFromContextWithControls(final Object ctx, final HasControls hasControls) throws NamingException; }
likaiwalkman/spring-ldap
core/src/main/java/org/springframework/ldap/core/support/ContextMapperWithControls.java
Java
apache-2.0
1,490
# Copyright 2008-2015 Nokia Solutions and Networks # # 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. """Implementation of the public test library logging API. This is exposed via :py:mod:`robot.api.logger`. Implementation must reside here to avoid cyclic imports. """ import sys import threading from robot.errors import DataError from robot.utils import unic, encode_output from .logger import LOGGER from .loggerhelper import Message LOGGING_THREADS = ('MainThread', 'RobotFrameworkTimeoutThread') def write(msg, level, html=False): # Callable messages allow lazy logging internally, but we don't want to # expose this functionality publicly. See the following issue for details: # http://code.google.com/p/robotframework/issues/detail?id=1505 if callable(msg): msg = unic(msg) if level.upper() not in ('TRACE', 'DEBUG', 'INFO', 'HTML', 'WARN', 'ERROR'): raise DataError("Invalid log level '%s'." % level) if threading.currentThread().getName() in LOGGING_THREADS: LOGGER.log_message(Message(msg, level, html)) def trace(msg, html=False): write(msg, 'TRACE', html) def debug(msg, html=False): write(msg, 'DEBUG', html) def info(msg, html=False, also_console=False): write(msg, 'INFO', html) if also_console: console(msg) def warn(msg, html=False): write(msg, 'WARN', html) def error(msg, html=False): write(msg, 'ERROR', html) def console(msg, newline=True, stream='stdout'): msg = unic(msg) if newline: msg += '\n' stream = sys.__stdout__ if stream.lower() != 'stderr' else sys.__stderr__ stream.write(encode_output(msg)) stream.flush()
caio2k/RIDE
src/robotide/lib/robot/output/librarylogger.py
Python
apache-2.0
2,175
/* * 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.jackrabbit.oak.plugins.nodetype; import java.util.List; import java.util.Set; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; import org.apache.jackrabbit.oak.api.PropertyState; import org.apache.jackrabbit.oak.api.Type; import org.apache.jackrabbit.oak.spi.state.ChildNodeEntry; import org.apache.jackrabbit.oak.spi.state.NodeState; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.Iterables.addAll; import static com.google.common.collect.Iterables.concat; import static com.google.common.collect.Iterables.contains; import static com.google.common.collect.Lists.newArrayListWithCapacity; import static com.google.common.collect.Sets.newHashSet; import static org.apache.jackrabbit.JcrConstants.JCR_DEFAULTPRIMARYTYPE; import static org.apache.jackrabbit.JcrConstants.JCR_MANDATORY; import static org.apache.jackrabbit.JcrConstants.JCR_MIXINTYPES; import static org.apache.jackrabbit.JcrConstants.JCR_NODETYPENAME; import static org.apache.jackrabbit.JcrConstants.JCR_PRIMARYTYPE; import static org.apache.jackrabbit.JcrConstants.JCR_SAMENAMESIBLINGS; import static org.apache.jackrabbit.JcrConstants.JCR_UUID; import static org.apache.jackrabbit.oak.api.Type.UNDEFINED; import static org.apache.jackrabbit.oak.api.Type.UNDEFINEDS; import static org.apache.jackrabbit.oak.commons.PathUtils.dropIndexFromName; import static org.apache.jackrabbit.oak.plugins.nodetype.NodeTypeConstants.REP_MANDATORY_CHILD_NODES; import static org.apache.jackrabbit.oak.plugins.nodetype.NodeTypeConstants.REP_MANDATORY_PROPERTIES; import static org.apache.jackrabbit.oak.plugins.nodetype.NodeTypeConstants.REP_NAMED_CHILD_NODE_DEFINITIONS; import static org.apache.jackrabbit.oak.plugins.nodetype.NodeTypeConstants.REP_NAMED_PROPERTY_DEFINITIONS; import static org.apache.jackrabbit.oak.plugins.nodetype.NodeTypeConstants.REP_RESIDUAL_CHILD_NODE_DEFINITIONS; import static org.apache.jackrabbit.oak.plugins.nodetype.NodeTypeConstants.REP_RESIDUAL_PROPERTY_DEFINITIONS; import static org.apache.jackrabbit.oak.plugins.nodetype.NodeTypeConstants.REP_SUPERTYPES; class EffectiveType { private final List<NodeState> types; EffectiveType(@Nonnull List<NodeState> types) { this.types = checkNotNull(types); } /** * Checks whether this effective type contains the named type. * * @param name node type name * @return {@code true} if the named type is included, * {@code false} otherwise */ boolean isNodeType(@Nonnull String name) { for (NodeState type : types) { if (name.equals(type.getName(JCR_NODETYPENAME)) || contains(type.getNames(REP_SUPERTYPES), name)) { return true; } } return false; } boolean isMandatoryProperty(@Nonnull String name) { return nameSetContains(REP_MANDATORY_PROPERTIES, name); } @Nonnull Set<String> getMandatoryProperties() { return getNameSet(REP_MANDATORY_PROPERTIES); } boolean isMandatoryChildNode(@Nonnull String name) { return nameSetContains(REP_MANDATORY_CHILD_NODES, name); } @Nonnull Set<String> getMandatoryChildNodes() { return getNameSet(REP_MANDATORY_CHILD_NODES); } /** * Finds a matching definition for a property with the given name and type. * * @param property modified property * @return matching property definition, or {@code null} */ @CheckForNull NodeState getDefinition(@Nonnull PropertyState property) { String propertyName = property.getName(); Type<?> propertyType = property.getType(); String escapedName; if (JCR_PRIMARYTYPE.equals(propertyName)) { escapedName = NodeTypeConstants.REP_PRIMARY_TYPE; } else if (JCR_MIXINTYPES.equals(propertyName)) { escapedName = NodeTypeConstants.REP_MIXIN_TYPES; } else if (JCR_UUID.equals(propertyName)) { escapedName = NodeTypeConstants.REP_UUID; } else { escapedName = propertyName; } String definedType = propertyType.toString(); String undefinedType; if (propertyType.isArray()) { undefinedType = UNDEFINEDS.toString(); } else { undefinedType = UNDEFINED.toString(); } // Find matching named property definition for (NodeState type : types) { NodeState definitions = type .getChildNode(REP_NAMED_PROPERTY_DEFINITIONS) .getChildNode(escapedName); NodeState definition = definitions.getChildNode(definedType); if (definition.exists()) { return definition; } definition = definitions.getChildNode(undefinedType); if (definition.exists()) { return definition; } // OAK-822: a mandatory definition always overrides residual ones // TODO: unnecessary if the OAK-713 fallback wasn't needed below for (ChildNodeEntry entry : definitions.getChildNodeEntries()) { definition = entry.getNodeState(); if (definition.getBoolean(JCR_MANDATORY)) { return definition; } } // TODO: Fall back to residual definitions until we have consensus on OAK-713 // throw new ConstraintViolationException( // "No matching definition found for property " + propertyName); } // Find matching residual property definition for (NodeState type : types) { NodeState residual = type.getChildNode(REP_RESIDUAL_PROPERTY_DEFINITIONS); NodeState definition = residual.getChildNode(definedType); if (!definition.exists()) { definition = residual.getChildNode(undefinedType); } if (definition.exists()) { return definition; } } return null; } /** * Finds a matching definition for a child node with the given name and * types. * * @param nameWithIndex child node name, possibly with an SNS index * @param effective effective types of the child node * @return {@code true} if there's a matching child node definition, * {@code false} otherwise */ boolean isValidChildNode(@Nonnull String nameWithIndex, @Nonnull EffectiveType effective) { String name = dropIndexFromName(nameWithIndex); boolean sns = !name.equals(nameWithIndex); Set<String> typeNames = effective.getTypeNames(); // Find matching named child node definition for (NodeState type : types) { NodeState definitions = type .getChildNode(REP_NAMED_CHILD_NODE_DEFINITIONS) .getChildNode(name); for (String typeName : typeNames) { NodeState definition = definitions.getChildNode(typeName); if (definition.exists() && snsMatch(sns, definition)) { return true; } } // OAK-822: a mandatory definition always overrides alternatives // TODO: unnecessary if the OAK-713 fallback wasn't needed below for (ChildNodeEntry entry : definitions.getChildNodeEntries()) { NodeState definition = entry.getNodeState(); if (definition.getBoolean(JCR_MANDATORY)) { return false; } } // TODO: Fall back to residual definitions until we have consensus on OAK-713 // throw new ConstraintViolationException( // "Incorrect node type of child node " + nodeName); } // Find matching residual child node definition for (NodeState type : types) { NodeState residual = type.getChildNode(REP_RESIDUAL_CHILD_NODE_DEFINITIONS); for (String typeName : typeNames) { NodeState definition = residual.getChildNode(typeName); if (definition.exists() && snsMatch(sns, definition)) { return true; } } } return false; } /** * Finds the default node type for a child node with the given name. * * @param nameWithIndex child node name, possibly with an SNS index * @return default type, or {@code null} if not found */ @CheckForNull String getDefaultType(@Nonnull String nameWithIndex) { String name = dropIndexFromName(nameWithIndex); boolean sns = !name.equals(nameWithIndex); for (NodeState type : types) { NodeState named = type .getChildNode(REP_NAMED_CHILD_NODE_DEFINITIONS) .getChildNode(name); NodeState residual = type .getChildNode(REP_RESIDUAL_CHILD_NODE_DEFINITIONS); for (ChildNodeEntry entry : concat( named.getChildNodeEntries(), residual.getChildNodeEntries())) { NodeState definition = entry.getNodeState(); String defaultType = definition.getName(JCR_DEFAULTPRIMARYTYPE); if (defaultType != null && snsMatch(sns, definition)) { return defaultType; } } } return null; } @Nonnull Set<String> getTypeNames() { Set<String> names = newHashSet(); for (NodeState type : types) { names.add(type.getName(JCR_NODETYPENAME)); addAll(names, type.getNames(REP_SUPERTYPES)); } return names; } //------------------------------------------------------------< Object >-- @Override public String toString() { List<String> names = newArrayListWithCapacity(types.size()); for (NodeState type : types) { names.add(type.getName(JCR_NODETYPENAME)); } return names.toString(); } //-----------------------------------------------------------< private >-- /** * Depending on the given SNS flag, checks whether the given child node * definition allows same-name-siblings. * * @param sns SNS flag, {@code true} if processing an SNS node * @param definition child node definition */ private boolean snsMatch(boolean sns, @Nonnull NodeState definition) { return !sns || definition.getBoolean(JCR_SAMENAMESIBLINGS); } private boolean nameSetContains(@Nonnull String set, @Nonnull String name) { for (NodeState type : types) { if (contains(type.getNames(set), name)) { return true; } } return false; } @Nonnull private Set<String> getNameSet(@Nonnull String set) { Set<String> names = newHashSet(); for (NodeState type : types) { addAll(names, type.getNames(set)); } return names; } }
AndreasAbdi/jackrabbit-oak
oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/nodetype/EffectiveType.java
Java
apache-2.0
11,952
/** ****************************************************************************** * @file stm32h7xx_hal_sram.c * @author MCD Application Team * @brief SRAM HAL module driver. * This file provides a generic firmware to drive SRAM memories * mounted as external device. * @verbatim ============================================================================== ##### How to use this driver ##### ============================================================================== [..] This driver is a generic layered driver which contains a set of APIs used to control SRAM memories. It uses the FMC layer functions to interface with SRAM devices. The following sequence should be followed to configure the FMC to interface with SRAM/PSRAM memories: (#) Declare a SRAM_HandleTypeDef handle structure, for example: SRAM_HandleTypeDef hsram; and: (++) Fill the SRAM_HandleTypeDef handle "Init" field with the allowed values of the structure member. (++) Fill the SRAM_HandleTypeDef handle "Instance" field with a predefined base register instance for NOR or SRAM device (++) Fill the SRAM_HandleTypeDef handle "Extended" field with a predefined base register instance for NOR or SRAM extended mode (#) Declare two FMC_NORSRAM_TimingTypeDef structures, for both normal and extended mode timings; for example: FMC_NORSRAM_TimingTypeDef Timing and FMC_NORSRAM_TimingTypeDef ExTiming; and fill its fields with the allowed values of the structure member. (#) Initialize the SRAM Controller by calling the function HAL_SRAM_Init(). This function performs the following sequence: (##) MSP hardware layer configuration using the function HAL_SRAM_MspInit() (##) Control register configuration using the FMC NORSRAM interface function FMC_NORSRAM_Init() (##) Timing register configuration using the FMC NORSRAM interface function FMC_NORSRAM_Timing_Init() (##) Extended mode Timing register configuration using the FMC NORSRAM interface function FMC_NORSRAM_Extended_Timing_Init() (##) Enable the SRAM device using the macro __FMC_NORSRAM_ENABLE() (#) At this stage you can perform read/write accesses from/to the memory connected to the NOR/SRAM Bank. You can perform either polling or DMA transfer using the following APIs: (++) HAL_SRAM_Read()/HAL_SRAM_Write() for polling read/write access (++) HAL_SRAM_Read_DMA()/HAL_SRAM_Write_DMA() for DMA read/write transfer (#) You can also control the SRAM device by calling the control APIs HAL_SRAM_WriteOperation_Enable()/ HAL_SRAM_WriteOperation_Disable() to respectively enable/disable the SRAM write operation (#) You can continuously monitor the SRAM device HAL state by calling the function HAL_SRAM_GetState() *** Callback registration *** ============================================= [..] The compilation define USE_HAL_SRAM_REGISTER_CALLBACKS when set to 1 allows the user to configure dynamically the driver callbacks. Use Functions @ref HAL_SRAM_RegisterCallback() to register a user callback, it allows to register following callbacks: (+) MspInitCallback : SRAM MspInit. (+) MspDeInitCallback : SRAM MspDeInit. This function takes as parameters the HAL peripheral handle, the Callback ID and a pointer to the user callback function. Use function @ref HAL_SRAM_UnRegisterCallback() to reset a callback to the default weak (surcharged) function. It allows to reset following callbacks: (+) MspInitCallback : SRAM MspInit. (+) MspDeInitCallback : SRAM MspDeInit. This function) takes as parameters the HAL peripheral handle and the Callback ID. By default, after the @ref HAL_SRAM_Init and if the state is HAL_SRAM_STATE_RESET all callbacks are reset to the corresponding legacy weak (surcharged) functions. Exception done for MspInit and MspDeInit callbacks that are respectively reset to the legacy weak (surcharged) functions in the @ref HAL_SRAM_Init and @ref HAL_SRAM_DeInit only when these callbacks are null (not registered beforehand). If not, MspInit or MspDeInit are not null, the @ref HAL_SRAM_Init and @ref HAL_SRAM_DeInit keep and use the user MspInit/MspDeInit callbacks (registered beforehand) Callbacks can be registered/unregistered in READY state only. Exception done for MspInit/MspDeInit callbacks that can be registered/unregistered in READY or RESET state, thus registered (user) MspInit/DeInit callbacks can be used during the Init/DeInit. In that case first register the MspInit/MspDeInit user callbacks using @ref HAL_SRAM_RegisterCallback before calling @ref HAL_SRAM_DeInit or @ref HAL_SRAM_Init function. When The compilation define USE_HAL_SRAM_REGISTER_CALLBACKS is set to 0 or not defined, the callback registering feature is not available and weak (surcharged) callbacks are used. @endverbatim ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2017 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under BSD 3-Clause license, * the "License"; You may not use this file except in compliance with the * License. You may obtain a copy of the License at: * opensource.org/licenses/BSD-3-Clause * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "stm32h7xx_hal.h" /** @addtogroup STM32H7xx_HAL_Driver * @{ */ #ifdef HAL_SRAM_MODULE_ENABLED /** @defgroup SRAM SRAM * @brief SRAM driver modules * @{ */ /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ static void SRAM_DMACplt(MDMA_HandleTypeDef *hmdma); static void SRAM_DMACpltProt(MDMA_HandleTypeDef *hmdma); static void SRAM_DMAError(MDMA_HandleTypeDef *hmdma); /* Exported functions --------------------------------------------------------*/ /** @defgroup SRAM_Exported_Functions SRAM Exported Functions * @{ */ /** @defgroup SRAM_Exported_Functions_Group1 Initialization and de-initialization functions * @brief Initialization and Configuration functions. * @verbatim ============================================================================== ##### SRAM Initialization and de_initialization functions ##### ============================================================================== [..] This section provides functions allowing to initialize/de-initialize the SRAM memory @endverbatim * @{ */ /** * @brief Performs the SRAM device initialization sequence * @param hsram pointer to a SRAM_HandleTypeDef structure that contains * the configuration information for SRAM module. * @param Timing Pointer to SRAM control timing structure * @param ExtTiming Pointer to SRAM extended mode timing structure * @retval HAL status */ HAL_StatusTypeDef HAL_SRAM_Init(SRAM_HandleTypeDef *hsram, FMC_NORSRAM_TimingTypeDef *Timing, FMC_NORSRAM_TimingTypeDef *ExtTiming) { /* Check the SRAM handle parameter */ if (hsram == NULL) { return HAL_ERROR; } if (hsram->State == HAL_SRAM_STATE_RESET) { /* Allocate lock resource and initialize it */ hsram->Lock = HAL_UNLOCKED; #if (USE_HAL_SRAM_REGISTER_CALLBACKS == 1) if (hsram->MspInitCallback == NULL) { hsram->MspInitCallback = HAL_SRAM_MspInit; } hsram->DmaXferCpltCallback = HAL_SRAM_DMA_XferCpltCallback; hsram->DmaXferErrorCallback = HAL_SRAM_DMA_XferErrorCallback; /* Init the low level hardware */ hsram->MspInitCallback(hsram); #else /* Initialize the low level hardware (MSP) */ HAL_SRAM_MspInit(hsram); #endif /* USE_HAL_SRAM_REGISTER_CALLBACKS */ } /* Initialize SRAM control Interface */ (void)FMC_NORSRAM_Init(hsram->Instance, &(hsram->Init)); /* Initialize SRAM timing Interface */ (void)FMC_NORSRAM_Timing_Init(hsram->Instance, Timing, hsram->Init.NSBank); /* Initialize SRAM extended mode timing Interface */ (void)FMC_NORSRAM_Extended_Timing_Init(hsram->Extended, ExtTiming, hsram->Init.NSBank, hsram->Init.ExtendedMode); /* Enable the NORSRAM device */ __FMC_NORSRAM_ENABLE(hsram->Instance, hsram->Init.NSBank); /* Enable FMC Peripheral */ __FMC_ENABLE(); /* Initialize the SRAM controller state */ hsram->State = HAL_SRAM_STATE_READY; return HAL_OK; } /** * @brief Performs the SRAM device De-initialization sequence. * @param hsram pointer to a SRAM_HandleTypeDef structure that contains * the configuration information for SRAM module. * @retval HAL status */ HAL_StatusTypeDef HAL_SRAM_DeInit(SRAM_HandleTypeDef *hsram) { #if (USE_HAL_SRAM_REGISTER_CALLBACKS == 1) if (hsram->MspDeInitCallback == NULL) { hsram->MspDeInitCallback = HAL_SRAM_MspDeInit; } /* DeInit the low level hardware */ hsram->MspDeInitCallback(hsram); #else /* De-Initialize the low level hardware (MSP) */ HAL_SRAM_MspDeInit(hsram); #endif /* USE_HAL_SRAM_REGISTER_CALLBACKS */ /* Configure the SRAM registers with their reset values */ (void)FMC_NORSRAM_DeInit(hsram->Instance, hsram->Extended, hsram->Init.NSBank); /* Reset the SRAM controller state */ hsram->State = HAL_SRAM_STATE_RESET; /* Release Lock */ __HAL_UNLOCK(hsram); return HAL_OK; } /** * @brief SRAM MSP Init. * @param hsram pointer to a SRAM_HandleTypeDef structure that contains * the configuration information for SRAM module. * @retval None */ __weak void HAL_SRAM_MspInit(SRAM_HandleTypeDef *hsram) { /* Prevent unused argument(s) compilation warning */ UNUSED(hsram); /* NOTE : This function Should not be modified, when the callback is needed, the HAL_SRAM_MspInit could be implemented in the user file */ } /** * @brief SRAM MSP DeInit. * @param hsram pointer to a SRAM_HandleTypeDef structure that contains * the configuration information for SRAM module. * @retval None */ __weak void HAL_SRAM_MspDeInit(SRAM_HandleTypeDef *hsram) { /* Prevent unused argument(s) compilation warning */ UNUSED(hsram); /* NOTE : This function Should not be modified, when the callback is needed, the HAL_SRAM_MspDeInit could be implemented in the user file */ } /** * @brief DMA transfer complete callback. * @param hmdma pointer to a SRAM_HandleTypeDef structure that contains * the configuration information for SRAM module. * @retval None */ __weak void HAL_SRAM_DMA_XferCpltCallback(MDMA_HandleTypeDef *hmdma) { /* Prevent unused argument(s) compilation warning */ UNUSED(hmdma); /* NOTE : This function Should not be modified, when the callback is needed, the HAL_SRAM_DMA_XferCpltCallback could be implemented in the user file */ } /** * @brief DMA transfer complete error callback. * @param hmdma pointer to a SRAM_HandleTypeDef structure that contains * the configuration information for SRAM module. * @retval None */ __weak void HAL_SRAM_DMA_XferErrorCallback(MDMA_HandleTypeDef *hmdma) { /* Prevent unused argument(s) compilation warning */ UNUSED(hmdma); /* NOTE : This function Should not be modified, when the callback is needed, the HAL_SRAM_DMA_XferErrorCallback could be implemented in the user file */ } /** * @} */ /** @defgroup SRAM_Exported_Functions_Group2 Input Output and memory control functions * @brief Input Output and memory control functions * @verbatim ============================================================================== ##### SRAM Input and Output functions ##### ============================================================================== [..] This section provides functions allowing to use and control the SRAM memory @endverbatim * @{ */ /** * @brief Reads 8-bit buffer from SRAM memory. * @param hsram pointer to a SRAM_HandleTypeDef structure that contains * the configuration information for SRAM module. * @param pAddress Pointer to read start address * @param pDstBuffer Pointer to destination buffer * @param BufferSize Size of the buffer to read from memory * @retval HAL status */ HAL_StatusTypeDef HAL_SRAM_Read_8b(SRAM_HandleTypeDef *hsram, uint32_t *pAddress, uint8_t *pDstBuffer, uint32_t BufferSize) { uint32_t size; __IO uint8_t *psramaddress = (uint8_t *)pAddress; uint8_t *pdestbuff = pDstBuffer; HAL_SRAM_StateTypeDef state = hsram->State; /* Check the SRAM controller state */ if ((state == HAL_SRAM_STATE_READY) || (state == HAL_SRAM_STATE_PROTECTED)) { /* Process Locked */ __HAL_LOCK(hsram); /* Update the SRAM controller state */ hsram->State = HAL_SRAM_STATE_BUSY; /* Read data from memory */ for (size = BufferSize; size != 0U; size--) { *pdestbuff = *psramaddress; pdestbuff++; psramaddress++; } /* Update the SRAM controller state */ hsram->State = state; /* Process unlocked */ __HAL_UNLOCK(hsram); } else { return HAL_ERROR; } return HAL_OK; } /** * @brief Writes 8-bit buffer to SRAM memory. * @param hsram pointer to a SRAM_HandleTypeDef structure that contains * the configuration information for SRAM module. * @param pAddress Pointer to write start address * @param pSrcBuffer Pointer to source buffer to write * @param BufferSize Size of the buffer to write to memory * @retval HAL status */ HAL_StatusTypeDef HAL_SRAM_Write_8b(SRAM_HandleTypeDef *hsram, uint32_t *pAddress, uint8_t *pSrcBuffer, uint32_t BufferSize) { uint32_t size; __IO uint8_t *psramaddress = (uint8_t *)pAddress; uint8_t *psrcbuff = pSrcBuffer; /* Check the SRAM controller state */ if (hsram->State == HAL_SRAM_STATE_READY) { /* Process Locked */ __HAL_LOCK(hsram); /* Update the SRAM controller state */ hsram->State = HAL_SRAM_STATE_BUSY; /* Write data to memory */ for (size = BufferSize; size != 0U; size--) { *psramaddress = *psrcbuff; psrcbuff++; psramaddress++; } /* Update the SRAM controller state */ hsram->State = HAL_SRAM_STATE_READY; /* Process unlocked */ __HAL_UNLOCK(hsram); } else { return HAL_ERROR; } return HAL_OK; } /** * @brief Reads 16-bit buffer from SRAM memory. * @param hsram pointer to a SRAM_HandleTypeDef structure that contains * the configuration information for SRAM module. * @param pAddress Pointer to read start address * @param pDstBuffer Pointer to destination buffer * @param BufferSize Size of the buffer to read from memory * @retval HAL status */ HAL_StatusTypeDef HAL_SRAM_Read_16b(SRAM_HandleTypeDef *hsram, uint32_t *pAddress, uint16_t *pDstBuffer, uint32_t BufferSize) { uint32_t size; __IO uint32_t *psramaddress = pAddress; uint16_t *pdestbuff = pDstBuffer; uint8_t limit; HAL_SRAM_StateTypeDef state = hsram->State; /* Check the SRAM controller state */ if ((state == HAL_SRAM_STATE_READY) || (state == HAL_SRAM_STATE_PROTECTED)) { /* Process Locked */ __HAL_LOCK(hsram); /* Update the SRAM controller state */ hsram->State = HAL_SRAM_STATE_BUSY; /* Check if the size is a 32-bits multiple */ limit = (((BufferSize % 2U) != 0U) ? 1U : 0U); /* Read data from memory */ for (size = BufferSize; size != limit; size -= 2U) { *pdestbuff = (uint16_t)((*psramaddress) & 0x0000FFFFU); pdestbuff++; *pdestbuff = (uint16_t)(((*psramaddress) & 0xFFFF0000U) >> 16U); pdestbuff++; psramaddress++; } /* Read last 16-bits if size is not 32-bits multiple */ if (limit != 0U) { *pdestbuff = (uint16_t)((*psramaddress) & 0x0000FFFFU); } /* Update the SRAM controller state */ hsram->State = state; /* Process unlocked */ __HAL_UNLOCK(hsram); } else { return HAL_ERROR; } return HAL_OK; } /** * @brief Writes 16-bit buffer to SRAM memory. * @param hsram pointer to a SRAM_HandleTypeDef structure that contains * the configuration information for SRAM module. * @param pAddress Pointer to write start address * @param pSrcBuffer Pointer to source buffer to write * @param BufferSize Size of the buffer to write to memory * @retval HAL status */ HAL_StatusTypeDef HAL_SRAM_Write_16b(SRAM_HandleTypeDef *hsram, uint32_t *pAddress, uint16_t *pSrcBuffer, uint32_t BufferSize) { uint32_t size; __IO uint32_t *psramaddress = pAddress; uint16_t *psrcbuff = pSrcBuffer; uint8_t limit; /* Check the SRAM controller state */ if (hsram->State == HAL_SRAM_STATE_READY) { /* Process Locked */ __HAL_LOCK(hsram); /* Update the SRAM controller state */ hsram->State = HAL_SRAM_STATE_BUSY; /* Check if the size is a 32-bits multiple */ limit = (((BufferSize % 2U) != 0U) ? 1U : 0U); /* Write data to memory */ for (size = BufferSize; size != limit; size -= 2U) { *psramaddress = (uint32_t)(*psrcbuff); psrcbuff++; *psramaddress |= ((uint32_t)(*psrcbuff) << 16U); psrcbuff++; psramaddress++; } /* Write last 16-bits if size is not 32-bits multiple */ if (limit != 0U) { *psramaddress = ((uint32_t)(*psrcbuff) & 0x0000FFFFU) | ((*psramaddress) & 0xFFFF0000U); } /* Update the SRAM controller state */ hsram->State = HAL_SRAM_STATE_READY; /* Process unlocked */ __HAL_UNLOCK(hsram); } else { return HAL_ERROR; } return HAL_OK; } /** * @brief Reads 32-bit buffer from SRAM memory. * @param hsram pointer to a SRAM_HandleTypeDef structure that contains * the configuration information for SRAM module. * @param pAddress Pointer to read start address * @param pDstBuffer Pointer to destination buffer * @param BufferSize Size of the buffer to read from memory * @retval HAL status */ HAL_StatusTypeDef HAL_SRAM_Read_32b(SRAM_HandleTypeDef *hsram, uint32_t *pAddress, uint32_t *pDstBuffer, uint32_t BufferSize) { uint32_t size; __IO uint32_t *psramaddress = pAddress; uint32_t *pdestbuff = pDstBuffer; HAL_SRAM_StateTypeDef state = hsram->State; /* Check the SRAM controller state */ if ((state == HAL_SRAM_STATE_READY) || (state == HAL_SRAM_STATE_PROTECTED)) { /* Process Locked */ __HAL_LOCK(hsram); /* Update the SRAM controller state */ hsram->State = HAL_SRAM_STATE_BUSY; /* Read data from memory */ for (size = BufferSize; size != 0U; size--) { *pdestbuff = *psramaddress; pdestbuff++; psramaddress++; } /* Update the SRAM controller state */ hsram->State = state; /* Process unlocked */ __HAL_UNLOCK(hsram); } else { return HAL_ERROR; } return HAL_OK; } /** * @brief Writes 32-bit buffer to SRAM memory. * @param hsram pointer to a SRAM_HandleTypeDef structure that contains * the configuration information for SRAM module. * @param pAddress Pointer to write start address * @param pSrcBuffer Pointer to source buffer to write * @param BufferSize Size of the buffer to write to memory * @retval HAL status */ HAL_StatusTypeDef HAL_SRAM_Write_32b(SRAM_HandleTypeDef *hsram, uint32_t *pAddress, uint32_t *pSrcBuffer, uint32_t BufferSize) { uint32_t size; __IO uint32_t *psramaddress = pAddress; uint32_t *psrcbuff = pSrcBuffer; /* Check the SRAM controller state */ if (hsram->State == HAL_SRAM_STATE_READY) { /* Process Locked */ __HAL_LOCK(hsram); /* Update the SRAM controller state */ hsram->State = HAL_SRAM_STATE_BUSY; /* Write data to memory */ for (size = BufferSize; size != 0U; size--) { *psramaddress = *psrcbuff; psrcbuff++; psramaddress++; } /* Update the SRAM controller state */ hsram->State = HAL_SRAM_STATE_READY; /* Process unlocked */ __HAL_UNLOCK(hsram); } else { return HAL_ERROR; } return HAL_OK; } /** * @brief Reads a Words data from the SRAM memory using DMA transfer. * @param hsram pointer to a SRAM_HandleTypeDef structure that contains * the configuration information for SRAM module. * @param pAddress Pointer to read start address * @param pDstBuffer Pointer to destination buffer * @param BufferSize Size of the buffer to read from memory * @retval HAL status */ HAL_StatusTypeDef HAL_SRAM_Read_DMA(SRAM_HandleTypeDef *hsram, uint32_t *pAddress, uint32_t *pDstBuffer, uint32_t BufferSize) { HAL_StatusTypeDef status; HAL_SRAM_StateTypeDef state = hsram->State; /* Check the SRAM controller state */ if ((state == HAL_SRAM_STATE_READY) || (state == HAL_SRAM_STATE_PROTECTED)) { /* Process Locked */ __HAL_LOCK(hsram); /* Update the SRAM controller state */ hsram->State = HAL_SRAM_STATE_BUSY; /* Configure DMA user callbacks */ if (state == HAL_SRAM_STATE_READY) { hsram->hmdma->XferCpltCallback = SRAM_DMACplt; } else { hsram->hmdma->XferCpltCallback = SRAM_DMACpltProt; } hsram->hmdma->XferErrorCallback = SRAM_DMAError; /* Enable the DMA Stream */ status = HAL_MDMA_Start_IT(hsram->hmdma, (uint32_t)pAddress, (uint32_t)pDstBuffer, (uint32_t)(BufferSize * 4U), 1); /* Process unlocked */ __HAL_UNLOCK(hsram); } else { status = HAL_ERROR; } return status; } /** * @brief Writes a Words data buffer to SRAM memory using DMA transfer. * @param hsram pointer to a SRAM_HandleTypeDef structure that contains * the configuration information for SRAM module. * @param pAddress Pointer to write start address * @param pSrcBuffer Pointer to source buffer to write * @param BufferSize Size of the buffer to write to memory * @retval HAL status */ HAL_StatusTypeDef HAL_SRAM_Write_DMA(SRAM_HandleTypeDef *hsram, uint32_t *pAddress, uint32_t *pSrcBuffer, uint32_t BufferSize) { HAL_StatusTypeDef status; /* Check the SRAM controller state */ if (hsram->State == HAL_SRAM_STATE_READY) { /* Process Locked */ __HAL_LOCK(hsram); /* Update the SRAM controller state */ hsram->State = HAL_SRAM_STATE_BUSY; /* Configure DMA user callbacks */ hsram->hmdma->XferCpltCallback = SRAM_DMACplt; hsram->hmdma->XferErrorCallback = SRAM_DMAError; /* Enable the DMA Stream */ status = HAL_MDMA_Start_IT(hsram->hmdma, (uint32_t)pSrcBuffer, (uint32_t)pAddress, (uint32_t)(BufferSize * 4U), 1); /* Process unlocked */ __HAL_UNLOCK(hsram); } else { status = HAL_ERROR; } return status; } #if (USE_HAL_SRAM_REGISTER_CALLBACKS == 1) /** * @brief Register a User SRAM Callback * To be used instead of the weak (surcharged) predefined callback * @param hsram : SRAM handle * @param CallbackId : ID of the callback to be registered * This parameter can be one of the following values: * @arg @ref HAL_SRAM_MSP_INIT_CB_ID SRAM MspInit callback ID * @arg @ref HAL_SRAM_MSP_DEINIT_CB_ID SRAM MspDeInit callback ID * @param pCallback : pointer to the Callback function * @retval status */ HAL_StatusTypeDef HAL_SRAM_RegisterCallback(SRAM_HandleTypeDef *hsram, HAL_SRAM_CallbackIDTypeDef CallbackId, pSRAM_CallbackTypeDef pCallback) { HAL_StatusTypeDef status = HAL_OK; HAL_SRAM_StateTypeDef state; if (pCallback == NULL) { return HAL_ERROR; } /* Process locked */ __HAL_LOCK(hsram); state = hsram->State; if ((state == HAL_SRAM_STATE_READY) || (state == HAL_SRAM_STATE_RESET) || (state == HAL_SRAM_STATE_PROTECTED)) { switch (CallbackId) { case HAL_SRAM_MSP_INIT_CB_ID : hsram->MspInitCallback = pCallback; break; case HAL_SRAM_MSP_DEINIT_CB_ID : hsram->MspDeInitCallback = pCallback; break; default : /* update return status */ status = HAL_ERROR; break; } } else { /* update return status */ status = HAL_ERROR; } /* Release Lock */ __HAL_UNLOCK(hsram); return status; } /** * @brief Unregister a User SRAM Callback * SRAM Callback is redirected to the weak (surcharged) predefined callback * @param hsram : SRAM handle * @param CallbackId : ID of the callback to be unregistered * This parameter can be one of the following values: * @arg @ref HAL_SRAM_MSP_INIT_CB_ID SRAM MspInit callback ID * @arg @ref HAL_SRAM_MSP_DEINIT_CB_ID SRAM MspDeInit callback ID * @arg @ref HAL_SRAM_DMA_XFER_CPLT_CB_ID SRAM DMA Xfer Complete callback ID * @arg @ref HAL_SRAM_DMA_XFER_ERR_CB_ID SRAM DMA Xfer Error callback ID * @retval status */ HAL_StatusTypeDef HAL_SRAM_UnRegisterCallback(SRAM_HandleTypeDef *hsram, HAL_SRAM_CallbackIDTypeDef CallbackId) { HAL_StatusTypeDef status = HAL_OK; HAL_SRAM_StateTypeDef state; /* Process locked */ __HAL_LOCK(hsram); state = hsram->State; if ((state == HAL_SRAM_STATE_READY) || (state == HAL_SRAM_STATE_PROTECTED)) { switch (CallbackId) { case HAL_SRAM_MSP_INIT_CB_ID : hsram->MspInitCallback = HAL_SRAM_MspInit; break; case HAL_SRAM_MSP_DEINIT_CB_ID : hsram->MspDeInitCallback = HAL_SRAM_MspDeInit; break; case HAL_SRAM_DMA_XFER_CPLT_CB_ID : hsram->DmaXferCpltCallback = HAL_SRAM_DMA_XferCpltCallback; break; case HAL_SRAM_DMA_XFER_ERR_CB_ID : hsram->DmaXferErrorCallback = HAL_SRAM_DMA_XferErrorCallback; break; default : /* update return status */ status = HAL_ERROR; break; } } else if (state == HAL_SRAM_STATE_RESET) { switch (CallbackId) { case HAL_SRAM_MSP_INIT_CB_ID : hsram->MspInitCallback = HAL_SRAM_MspInit; break; case HAL_SRAM_MSP_DEINIT_CB_ID : hsram->MspDeInitCallback = HAL_SRAM_MspDeInit; break; default : /* update return status */ status = HAL_ERROR; break; } } else { /* update return status */ status = HAL_ERROR; } /* Release Lock */ __HAL_UNLOCK(hsram); return status; } /** * @brief Register a User SRAM Callback for DMA transfers * To be used instead of the weak (surcharged) predefined callback * @param hsram : SRAM handle * @param CallbackId : ID of the callback to be registered * This parameter can be one of the following values: * @arg @ref HAL_SRAM_DMA_XFER_CPLT_CB_ID SRAM DMA Xfer Complete callback ID * @arg @ref HAL_SRAM_DMA_XFER_ERR_CB_ID SRAM DMA Xfer Error callback ID * @param pCallback : pointer to the Callback function * @retval status */ HAL_StatusTypeDef HAL_SRAM_RegisterDmaCallback(SRAM_HandleTypeDef *hsram, HAL_SRAM_CallbackIDTypeDef CallbackId, pSRAM_DmaCallbackTypeDef pCallback) { HAL_StatusTypeDef status = HAL_OK; HAL_SRAM_StateTypeDef state; if (pCallback == NULL) { return HAL_ERROR; } /* Process locked */ __HAL_LOCK(hsram); state = hsram->State; if ((state == HAL_SRAM_STATE_READY) || (state == HAL_SRAM_STATE_PROTECTED)) { switch (CallbackId) { case HAL_SRAM_DMA_XFER_CPLT_CB_ID : hsram->DmaXferCpltCallback = pCallback; break; case HAL_SRAM_DMA_XFER_ERR_CB_ID : hsram->DmaXferErrorCallback = pCallback; break; default : /* update return status */ status = HAL_ERROR; break; } } else { /* update return status */ status = HAL_ERROR; } /* Release Lock */ __HAL_UNLOCK(hsram); return status; } #endif /* USE_HAL_SRAM_REGISTER_CALLBACKS */ /** * @} */ /** @defgroup SRAM_Exported_Functions_Group3 Control functions * @brief Control functions * @verbatim ============================================================================== ##### SRAM Control functions ##### ============================================================================== [..] This subsection provides a set of functions allowing to control dynamically the SRAM interface. @endverbatim * @{ */ /** * @brief Enables dynamically SRAM write operation. * @param hsram pointer to a SRAM_HandleTypeDef structure that contains * the configuration information for SRAM module. * @retval HAL status */ HAL_StatusTypeDef HAL_SRAM_WriteOperation_Enable(SRAM_HandleTypeDef *hsram) { /* Check the SRAM controller state */ if (hsram->State == HAL_SRAM_STATE_PROTECTED) { /* Process Locked */ __HAL_LOCK(hsram); /* Update the SRAM controller state */ hsram->State = HAL_SRAM_STATE_BUSY; /* Enable write operation */ (void)FMC_NORSRAM_WriteOperation_Enable(hsram->Instance, hsram->Init.NSBank); /* Update the SRAM controller state */ hsram->State = HAL_SRAM_STATE_READY; /* Process unlocked */ __HAL_UNLOCK(hsram); } else { return HAL_ERROR; } return HAL_OK; } /** * @brief Disables dynamically SRAM write operation. * @param hsram pointer to a SRAM_HandleTypeDef structure that contains * the configuration information for SRAM module. * @retval HAL status */ HAL_StatusTypeDef HAL_SRAM_WriteOperation_Disable(SRAM_HandleTypeDef *hsram) { /* Check the SRAM controller state */ if (hsram->State == HAL_SRAM_STATE_READY) { /* Process Locked */ __HAL_LOCK(hsram); /* Update the SRAM controller state */ hsram->State = HAL_SRAM_STATE_BUSY; /* Disable write operation */ (void)FMC_NORSRAM_WriteOperation_Disable(hsram->Instance, hsram->Init.NSBank); /* Update the SRAM controller state */ hsram->State = HAL_SRAM_STATE_PROTECTED; /* Process unlocked */ __HAL_UNLOCK(hsram); } else { return HAL_ERROR; } return HAL_OK; } /** * @} */ /** @defgroup SRAM_Exported_Functions_Group4 Peripheral State functions * @brief Peripheral State functions * @verbatim ============================================================================== ##### SRAM State functions ##### ============================================================================== [..] This subsection permits to get in run-time the status of the SRAM controller and the data flow. @endverbatim * @{ */ /** * @brief Returns the SRAM controller state * @param hsram pointer to a SRAM_HandleTypeDef structure that contains * the configuration information for SRAM module. * @retval HAL state */ HAL_SRAM_StateTypeDef HAL_SRAM_GetState(SRAM_HandleTypeDef *hsram) { return hsram->State; } /** * @} */ /** * @} */ /** * @brief MDMA SRAM process complete callback. * @param hmdma : MDMA handle * @retval None */ static void SRAM_DMACplt(MDMA_HandleTypeDef *hmdma) { SRAM_HandleTypeDef *hsram = (SRAM_HandleTypeDef *)(hmdma->Parent); /* Disable the MDMA channel */ __HAL_MDMA_DISABLE(hmdma); /* Update the SRAM controller state */ hsram->State = HAL_SRAM_STATE_READY; #if (USE_HAL_SRAM_REGISTER_CALLBACKS == 1) hsram->DmaXferCpltCallback(hmdma); #else HAL_SRAM_DMA_XferCpltCallback(hmdma); #endif /* USE_HAL_SRAM_REGISTER_CALLBACKS */ } /** * @brief MDMA SRAM process complete callback. * @param hmdma : MDMA handle * @retval None */ static void SRAM_DMACpltProt(MDMA_HandleTypeDef *hmdma) { SRAM_HandleTypeDef *hsram = (SRAM_HandleTypeDef *)(hmdma->Parent); /* Disable the MDMA channel */ __HAL_MDMA_DISABLE(hmdma); /* Update the SRAM controller state */ hsram->State = HAL_SRAM_STATE_PROTECTED; #if (USE_HAL_SRAM_REGISTER_CALLBACKS == 1) hsram->DmaXferCpltCallback(hmdma); #else HAL_SRAM_DMA_XferCpltCallback(hmdma); #endif /* USE_HAL_SRAM_REGISTER_CALLBACKS */ } /** * @brief MDMA SRAM error callback. * @param hmdma : MDMA handle * @retval None */ static void SRAM_DMAError(MDMA_HandleTypeDef *hmdma) { SRAM_HandleTypeDef *hsram = (SRAM_HandleTypeDef *)(hmdma->Parent); /* Disable the MDMA channel */ __HAL_MDMA_DISABLE(hmdma); /* Update the SRAM controller state */ hsram->State = HAL_SRAM_STATE_ERROR; #if (USE_HAL_SRAM_REGISTER_CALLBACKS == 1) hsram->DmaXferErrorCallback(hmdma); #else HAL_SRAM_DMA_XferErrorCallback(hmdma); #endif /* USE_HAL_SRAM_REGISTER_CALLBACKS */ } /** * @} */ #endif /* HAL_SRAM_MODULE_ENABLED */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
adfernandes/mbed
targets/TARGET_STM/TARGET_STM32H7/STM32Cube_FW/STM32H7xx_HAL_Driver/stm32h7xx_hal_sram.c
C
apache-2.0
33,824
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.lang.psi.impl.synthetic; import com.intellij.openapi.diagnostic.Logger; import com.intellij.psi.*; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifierList; import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField; import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition; import org.jetbrains.plugins.groovy.lang.psi.util.GrTraitUtil; import org.jetbrains.plugins.groovy.transformations.TransformationContext; public class GrTraitField extends GrLightField implements PsiMirrorElement { private static final Logger LOG = Logger.getInstance(GrTraitField.class); private final PsiField myField; public GrTraitField(@NotNull GrField field, GrTypeDefinition clazz, PsiSubstitutor substitutor, @Nullable TransformationContext context) { super(clazz, getNewNameForField(field), substitutor.substitute(field.getType()), field); GrLightModifierList modifierList = getModifierList(); for (String modifier : PsiModifier.MODIFIERS) { boolean hasModifierProperty; GrModifierList fieldModifierList = field.getModifierList(); if (context == null || fieldModifierList == null) { hasModifierProperty = field.hasModifierProperty(modifier); } else { hasModifierProperty = context.hasModifierProperty(fieldModifierList, modifier); } if (hasModifierProperty) { modifierList.addModifier(modifier); } } modifierList.copyAnnotations(field.getModifierList()); myField = field; } @NotNull private static String getNewNameForField(@NotNull PsiField field) { PsiClass containingClass = field.getContainingClass(); LOG.assertTrue(containingClass != null); return GrTraitUtil.getTraitFieldPrefix(containingClass) + field.getName(); } @NotNull @Override public PsiField getPrototype() { return myField; } }
siosio/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/synthetic/GrTraitField.java
Java
apache-2.0
2,141
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // 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. // ---------------------------------------------------------------------------------- using Microsoft.Azure.Commands.Insights.OutputClasses; using Microsoft.Azure.Management.Insights; using Microsoft.Azure.Management.Insights.Models; using System.Management.Automation; using System.Threading; namespace Microsoft.Azure.Commands.Insights.Diagnostics { /// <summary> /// Gets the logs and metrics for the resource. /// </summary> [Cmdlet(VerbsCommon.Get, "AzureRmDiagnosticSetting"), OutputType(typeof(PSServiceDiagnosticSettings))] public class GetAzureRmDiagnosticSettingCommand : ManagementCmdletBase { #region Parameters declarations /// <summary> /// Gets or sets the resourceId parameter of the cmdlet /// </summary> [Parameter(Position = 0, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The ResourceId")] [ValidateNotNullOrEmpty] public string ResourceId { get; set; } #endregion protected override void ProcessRecordInternal() { ServiceDiagnosticSettingsResource result = this.InsightsManagementClient.ServiceDiagnosticSettings.GetAsync(resourceUri: this.ResourceId, cancellationToken: CancellationToken.None).Result; PSServiceDiagnosticSettings psResult = new PSServiceDiagnosticSettings(result); WriteObject(psResult); } } }
seanbamsft/azure-powershell
src/ResourceManager/Insights/Commands.Insights/Diagnostics/GetAzureRmDiagnosticSettingCommand.cs
C#
apache-2.0
2,092
#!/bin/bash # Copyright 2015 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. # A library of helper functions and constant for debian os distro # create-master-instance creates the master instance. If called with # an argument, the argument is used as the name to a reserved IP # address for the master. (In the case of upgrade/repair, we re-use # the same IP.) # # It requires a whole slew of assumed variables, partially due to to # the call to write-master-env. Listing them would be rather # futile. Instead, we list the required calls to ensure any additional # variables are set: # ensure-temp-dir # detect-project # get-bearer-token # function create-master-instance { local address_opt="" [[ -n ${1:-} ]] && address_opt="--address ${1}" local preemptible_master="" if [[ "${PREEMPTIBLE_MASTER:-}" == "true" ]]; then preemptible_master="--preemptible --maintenance-policy TERMINATE" fi write-master-env prepare-startup-script create-master-instance-internal "${MASTER_NAME}" "${address_opt}" "${preemptible_master}" } function replicate-master-instance() { local existing_master_zone="${1}" local existing_master_name="${2}" local existing_master_replicas="${3}" local kube_env="$(get-metadata "${existing_master_zone}" "${existing_master_name}" kube-env)" # Substitute INITIAL_ETCD_CLUSTER to enable etcd clustering. kube_env="$(echo "${kube_env}" | grep -v "INITIAL_ETCD_CLUSTER")" kube_env="$(echo -e "${kube_env}\nINITIAL_ETCD_CLUSTER: '${existing_master_replicas},${REPLICA_NAME}'")" ETCD_CA_KEY="$(echo "${kube_env}" | grep "ETCD_CA_KEY" | sed "s/^.*: '//" | sed "s/'$//")" ETCD_CA_CERT="$(echo "${kube_env}" | grep "ETCD_CA_CERT" | sed "s/^.*: '//" | sed "s/'$//")" create-etcd-certs "${REPLICA_NAME}" "${ETCD_CA_CERT}" "${ETCD_CA_KEY}" kube_env="$(echo "${kube_env}" | grep -v "ETCD_PEER_KEY")" kube_env="$(echo -e "${kube_env}\nETCD_PEER_KEY: '${ETCD_PEER_KEY_BASE64}'")" kube_env="$(echo "${kube_env}" | grep -v "ETCD_PEER_CERT")" kube_env="$(echo -e "${kube_env}\nETCD_PEER_CERT: '${ETCD_PEER_CERT_BASE64}'")" echo "${kube_env}" > ${KUBE_TEMP}/master-kube-env.yaml get-metadata "${existing_master_zone}" "${existing_master_name}" cluster-name > ${KUBE_TEMP}/cluster-name.txt get-metadata "${existing_master_zone}" "${existing_master_name}" startup-script > ${KUBE_TEMP}/configure-vm.sh create-master-instance-internal "${REPLICA_NAME}" } function create-master-instance-internal() { local -r master_name="${1}" local -r address_option="${2:-}" local -r preemptible_master="${3:-}" gcloud compute instances create "${master_name}" \ ${address_option} \ --project "${PROJECT}" \ --zone "${ZONE}" \ --machine-type "${MASTER_SIZE}" \ --image-project="${MASTER_IMAGE_PROJECT}" \ --image "${MASTER_IMAGE}" \ --tags "${MASTER_TAG}" \ --network "${NETWORK}" \ --scopes "storage-ro,compute-rw,monitoring,logging-write" \ --can-ip-forward \ --metadata-from-file \ "startup-script=${KUBE_TEMP}/configure-vm.sh,kube-env=${KUBE_TEMP}/master-kube-env.yaml,cluster-name=${KUBE_TEMP}/cluster-name.txt,kube-master-certs=${KUBE_TEMP}/kube-master-certs.yaml" \ --disk "name=${master_name}-pd,device-name=master-pd,mode=rw,boot=no,auto-delete=no" \ --boot-disk-size "${MASTER_ROOT_DISK_SIZE:-10}" \ ${preemptible_master} } # TODO: This is most likely not the best way to read metadata from the existing master. function get-metadata() { local zone="${1}" local name="${2}" local key="${3}" gcloud compute ssh "${name}" \ --project "${PROJECT}" \ --zone="${zone}" \ --command "curl \"http://metadata.google.internal/computeMetadata/v1/instance/attributes/${key}\" -H \"Metadata-Flavor: Google\"" 2>/dev/null }
jawnsy/cri-o
vendor/k8s.io/kubernetes/cluster/gce/debian/master-helper.sh
Shell
apache-2.0
4,297
/* * 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.action.search.type; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.support.ActionFilters; import org.elasticsearch.cluster.ClusterService; import org.elasticsearch.cluster.node.DiscoveryNode; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.util.concurrent.AtomicArray; import org.elasticsearch.search.action.SearchServiceListener; import org.elasticsearch.search.action.SearchServiceTransportAction; import org.elasticsearch.search.controller.SearchPhaseController; import org.elasticsearch.search.fetch.FetchSearchResultProvider; import org.elasticsearch.search.internal.InternalSearchResponse; import org.elasticsearch.search.internal.ShardSearchRequest; import org.elasticsearch.search.query.QuerySearchResult; import org.elasticsearch.search.query.QuerySearchResultProvider; import org.elasticsearch.threadpool.ThreadPool; import static org.elasticsearch.action.search.type.TransportSearchHelper.buildScrollId; /** * */ public class TransportSearchCountAction extends TransportSearchTypeAction { @Inject public TransportSearchCountAction(Settings settings, ThreadPool threadPool, ClusterService clusterService, SearchServiceTransportAction searchService, SearchPhaseController searchPhaseController, ActionFilters actionFilters) { super(settings, threadPool, clusterService, searchService, searchPhaseController, actionFilters); } @Override protected void doExecute(SearchRequest searchRequest, ActionListener<SearchResponse> listener) { new AsyncAction(searchRequest, listener).start(); } private class AsyncAction extends BaseAsyncAction<QuerySearchResultProvider> { private AsyncAction(SearchRequest request, ActionListener<SearchResponse> listener) { super(request, listener); } @Override protected String firstPhaseName() { return "query"; } @Override protected void sendExecuteFirstPhase(DiscoveryNode node, ShardSearchRequest request, SearchServiceListener<QuerySearchResultProvider> listener) { searchService.sendExecuteQuery(node, request, listener); } @Override protected void moveToSecondPhase() throws Exception { // no need to sort, since we know we have no hits back final InternalSearchResponse internalResponse = searchPhaseController.merge(SearchPhaseController.EMPTY_DOCS, firstResults, (AtomicArray<? extends FetchSearchResultProvider>) AtomicArray.empty()); String scrollId = null; if (request.scroll() != null) { scrollId = buildScrollId(request.searchType(), firstResults, null); } listener.onResponse(new SearchResponse(internalResponse, scrollId, expectedSuccessfulOps, successfulOps.get(), buildTookInMillis(), buildShardFailures())); } } }
dmiszkiewicz/elasticsearch
src/main/java/org/elasticsearch/action/search/type/TransportSearchCountAction.java
Java
apache-2.0
3,920
/*========================================================================= Program: Visualization Toolkit Module: vtkDataSetTriangleFilter.h Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ // .NAME vtkDataSetTriangleFilter - triangulate any type of dataset // .SECTION Description // vtkDataSetTriangleFilter generates n-dimensional simplices from any input // dataset. That is, 3D cells are converted to tetrahedral meshes, 2D cells // to triangles, and so on. The triangulation is guaranteed to be compatible. // // This filter uses simple 1D and 2D triangulation techniques for cells // that are of topological dimension 2 or less. For 3D cells--due to the // issue of face compatibility across quadrilateral faces (which way to // orient the diagonal?)--a fancier ordered Delaunay triangulation is used. // This approach produces templates on the fly for triangulating the // cells. The templates are then used to do the actual triangulation. // // .SECTION See Also // vtkOrderedTriangulator vtkTriangleFilter #ifndef vtkDataSetTriangleFilter_h #define vtkDataSetTriangleFilter_h #include "vtkFiltersGeneralModule.h" // For export macro #include "vtkUnstructuredGridAlgorithm.h" class vtkOrderedTriangulator; class VTKFILTERSGENERAL_EXPORT vtkDataSetTriangleFilter : public vtkUnstructuredGridAlgorithm { public: static vtkDataSetTriangleFilter *New(); vtkTypeMacro(vtkDataSetTriangleFilter,vtkUnstructuredGridAlgorithm); void PrintSelf(ostream& os, vtkIndent indent); // Description: // When On this filter will cull all 1D and 2D cells from the output. // The default is Off. vtkSetMacro(TetrahedraOnly, int); vtkGetMacro(TetrahedraOnly, int); vtkBooleanMacro(TetrahedraOnly, int); protected: vtkDataSetTriangleFilter(); ~vtkDataSetTriangleFilter(); // Usual data generation method virtual int RequestData(vtkInformation *, vtkInformationVector **, vtkInformationVector *); virtual int FillInputPortInformation(int port, vtkInformation *info); // Used to triangulate 3D cells vtkOrderedTriangulator *Triangulator; // Different execute methods depending on whether input is structured or not void StructuredExecute(vtkDataSet *, vtkUnstructuredGrid *); void UnstructuredExecute(vtkDataSet *, vtkUnstructuredGrid *); int TetrahedraOnly; private: vtkDataSetTriangleFilter(const vtkDataSetTriangleFilter&); // Not implemented. void operator=(const vtkDataSetTriangleFilter&); // Not implemented. }; #endif
gisfromscratch/datavisualizer
lib/vtk/include/Filters/General/vtkDataSetTriangleFilter.h
C
apache-2.0
2,876
/** * 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.stratos.common.beans.topology; import org.apache.stratos.common.beans.PropertyBean; import javax.xml.bind.annotation.XmlRootElement; import java.util.List; @XmlRootElement(name = "clusters") public class ClusterBean { private String alias; private String serviceName; private String clusterId; private List<MemberBean> member; private String tenantRange; private List<String> hostNames; private boolean isLbCluster; private List<PropertyBean> property; private List<InstanceBean> instances; public List<InstanceBean> getInstances() { return instances; } public void setInstances(List<InstanceBean> instances) { this.instances = instances; } @Override public String toString() { return "Cluster [serviceName=" + getServiceName() + ", clusterId=" + getClusterId() + ", member=" + getMember() + ", tenantRange=" + getTenantRange() + ", hostNames=" + getHostNames() + ", isLbCluster=" + isLbCluster() + ", property=" + getProperty() + "]"; } public String getAlias() { return alias; } public void setAlias(String alias) { this.alias = alias; } public String getServiceName() { return serviceName; } public void setServiceName(String serviceName) { this.serviceName = serviceName; } public String getClusterId() { return clusterId; } public void setClusterId(String clusterId) { this.clusterId = clusterId; } public List<MemberBean> getMember() { return member; } public void setMember(List<MemberBean> member) { this.member = member; } public String getTenantRange() { return tenantRange; } public void setTenantRange(String tenantRange) { this.tenantRange = tenantRange; } public List<String> getHostNames() { return hostNames; } public void setHostNames(List<String> hostNames) { this.hostNames = hostNames; } public boolean isLbCluster() { return isLbCluster; } public void setLbCluster(boolean isLbCluster) { this.isLbCluster = isLbCluster; } public List<PropertyBean> getProperty() { return property; } public void setProperty(List<PropertyBean> property) { this.property = property; } }
pkdevbox/stratos
components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/beans/topology/ClusterBean.java
Java
apache-2.0
3,225
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates. * * 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 org.kie.workbench.common.screens.datasource.management.client.dbexplorer.schemas; import com.google.gwt.view.client.AsyncDataProvider; import org.uberfire.client.mvp.UberElement; import org.uberfire.ext.widgets.common.client.common.HasBusyIndicator; public interface DatabaseSchemaExplorerView extends UberElement< DatabaseSchemaExplorerView.Presenter >, HasBusyIndicator { interface Presenter { void onOpen( DatabaseSchemaRow row ); } interface Handler { void onOpen( String schemaName ); } void setDataProvider( AsyncDataProvider< DatabaseSchemaRow > dataProvider ); void redraw( ); }
romartin/kie-wb-common
kie-wb-common-screens/kie-wb-common-datasource-mgmt/kie-wb-common-datasource-mgmt-client/src/main/java/org/kie/workbench/common/screens/datasource/management/client/dbexplorer/schemas/DatabaseSchemaExplorerView.java
Java
apache-2.0
1,272
//===--- BasicInstructionPropertyDumper.cpp -------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #include "swift/SIL/SILFunction.h" #include "swift/SIL/SILInstruction.h" #include "swift/SIL/SILModule.h" #include "swift/SILOptimizer/PassManager/Transforms.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/raw_ostream.h" using namespace swift; namespace { class BasicInstructionPropertyDumper : public SILModuleTransform { void run() override { for (auto &Fn : *getModule()) { unsigned Count = 0; llvm::outs() << "@" << Fn.getName() << "\n"; for (auto &BB : Fn) { for (auto &I : BB) { llvm::outs() << "Inst #: " << Count++ << "\n " << I; llvm::outs() << " Mem Behavior: " << I.getMemoryBehavior() << "\n"; llvm::outs() << " Release Behavior: " << I.getReleasingBehavior() << "\n"; } } } } llvm::StringRef getName() override { return "BasicInstructionPropertyDumper"; } }; } // end anonymous namespace SILTransform *swift::createBasicInstructionPropertyDumper() { return new BasicInstructionPropertyDumper(); }
russbishop/swift
lib/SILOptimizer/UtilityPasses/BasicInstructionPropertyDumper.cpp
C++
apache-2.0
1,568
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/views/apps/chrome_native_app_window_views_aura.h" #include "apps/ui/views/app_window_frame_view.h" #include "ash/ash_constants.h" #include "ash/frame/custom_frame_view_ash.h" #include "ash/screen_util.h" #include "ash/shell.h" #include "ash/wm/immersive_fullscreen_controller.h" #include "ash/wm/panels/panel_frame_view.h" #include "ash/wm/window_properties.h" #include "ash/wm/window_state.h" #include "ash/wm/window_state_delegate.h" #include "ash/wm/window_state_observer.h" #include "chrome/browser/ui/ash/ash_util.h" #include "chrome/browser/ui/ash/multi_user/multi_user_context_menu.h" #include "chrome/browser/ui/host_desktop.h" #include "chrome/browser/ui/views/apps/app_window_easy_resize_window_targeter.h" #include "chrome/browser/ui/views/apps/shaped_app_window_targeter.h" #include "chrome/browser/web_applications/web_app.h" #include "ui/aura/client/aura_constants.h" #include "ui/aura/window.h" #include "ui/aura/window_observer.h" #include "ui/base/hit_test.h" #include "ui/base/models/simple_menu_model.h" #include "ui/gfx/image/image_skia.h" #include "ui/views/controls/menu/menu_runner.h" #include "ui/views/widget/widget.h" #if defined(OS_CHROMEOS) #include "ash/shell_window_ids.h" #endif #if defined(OS_LINUX) #include "chrome/browser/shell_integration_linux.h" #endif using extensions::AppWindow; namespace { // This class handles a user's fullscreen request (Shift+F4/F4). class NativeAppWindowStateDelegate : public ash::wm::WindowStateDelegate, public ash::wm::WindowStateObserver, public aura::WindowObserver { public: NativeAppWindowStateDelegate(AppWindow* app_window, extensions::NativeAppWindow* native_app_window) : app_window_(app_window), window_state_( ash::wm::GetWindowState(native_app_window->GetNativeWindow())) { // Add a window state observer to exit fullscreen properly in case // fullscreen is exited without going through AppWindow::Restore(). This // is the case when exiting immersive fullscreen via the "Restore" window // control. // TODO(pkotwicz): This is a hack. Remove ASAP. http://crbug.com/319048 window_state_->AddObserver(this); window_state_->window()->AddObserver(this); } ~NativeAppWindowStateDelegate() override { if (window_state_) { window_state_->RemoveObserver(this); window_state_->window()->RemoveObserver(this); } } private: // Overridden from ash::wm::WindowStateDelegate. bool ToggleFullscreen(ash::wm::WindowState* window_state) override { // Windows which cannot be maximized should not be fullscreened. DCHECK(window_state->IsFullscreen() || window_state->CanMaximize()); if (window_state->IsFullscreen()) app_window_->Restore(); else if (window_state->CanMaximize()) app_window_->OSFullscreen(); return true; } // Overridden from ash::wm::WindowStateDelegate. bool RestoreAlwaysOnTop(ash::wm::WindowState* window_state) override { app_window_->RestoreAlwaysOnTop(); return true; } // Overridden from ash::wm::WindowStateObserver: void OnPostWindowStateTypeChange(ash::wm::WindowState* window_state, ash::wm::WindowStateType old_type) override { // Since the window state might get set by a window manager, it is possible // to come here before the application set its |BaseWindow|. if (!window_state->IsFullscreen() && !window_state->IsMinimized() && app_window_->GetBaseWindow() && app_window_->GetBaseWindow()->IsFullscreenOrPending()) { app_window_->Restore(); // Usually OnNativeWindowChanged() is called when the window bounds are // changed as a result of a state type change. Because the change in state // type has already occurred, we need to call OnNativeWindowChanged() // explicitly. app_window_->OnNativeWindowChanged(); } } // Overridden from aura::WindowObserver: void OnWindowDestroying(aura::Window* window) override { window_state_->RemoveObserver(this); window_state_->window()->RemoveObserver(this); window_state_ = NULL; } // Not owned. AppWindow* app_window_; ash::wm::WindowState* window_state_; DISALLOW_COPY_AND_ASSIGN(NativeAppWindowStateDelegate); }; } // namespace ChromeNativeAppWindowViewsAura::ChromeNativeAppWindowViewsAura() { } ChromeNativeAppWindowViewsAura::~ChromeNativeAppWindowViewsAura() { } void ChromeNativeAppWindowViewsAura::InitializeWindow( AppWindow* app_window, const AppWindow::CreateParams& create_params) { ChromeNativeAppWindowViews::InitializeWindow(app_window, create_params); // Restore docked state on ash desktop and ignore it elsewhere. if (create_params.state == ui::SHOW_STATE_DOCKED && chrome::GetHostDesktopTypeForNativeWindow(widget()->GetNativeWindow()) == chrome::HOST_DESKTOP_TYPE_ASH) { widget()->GetNativeWindow()->SetProperty(aura::client::kShowStateKey, create_params.state); } } void ChromeNativeAppWindowViewsAura::OnBeforeWidgetInit( const AppWindow::CreateParams& create_params, views::Widget::InitParams* init_params, views::Widget* widget) { #if defined(OS_LINUX) && !defined(OS_CHROMEOS) std::string app_name = web_app::GenerateApplicationNameFromExtensionId( app_window()->extension_id()); // Set up a custom WM_CLASS for app windows. This allows task switchers in // X11 environments to distinguish them from main browser windows. init_params->wm_class_name = web_app::GetWMClassFromAppName(app_name); init_params->wm_class_class = shell_integration_linux::GetProgramClassName(); const char kX11WindowRoleApp[] = "app"; init_params->wm_role_name = std::string(kX11WindowRoleApp); #endif ChromeNativeAppWindowViews::OnBeforeWidgetInit(create_params, init_params, widget); #if defined(OS_CHROMEOS) if (create_params.is_ime_window) { // Puts ime windows into ime window container. init_params->parent = ash::Shell::GetContainer(ash::Shell::GetPrimaryRootWindow(), ash::kShellWindowId_ImeWindowParentContainer); } #endif } void ChromeNativeAppWindowViewsAura::OnBeforePanelWidgetInit( bool use_default_bounds, views::Widget::InitParams* init_params, views::Widget* widget) { ChromeNativeAppWindowViews::OnBeforePanelWidgetInit(use_default_bounds, init_params, widget); if (ash::Shell::HasInstance() && use_default_bounds) { // Open a new panel on the target root. init_params->bounds = ash::ScreenUtil::ConvertRectToScreen( ash::Shell::GetTargetRootWindow(), gfx::Rect(GetPreferredSize())); } } views::NonClientFrameView* ChromeNativeAppWindowViewsAura::CreateNonStandardAppFrame() { apps::AppWindowFrameView* frame = new apps::AppWindowFrameView(widget(), this, HasFrameColor(), ActiveFrameColor(), InactiveFrameColor()); frame->Init(); // For Aura windows on the Ash desktop the sizes are different and the user // can resize the window from slightly outside the bounds as well. if (chrome::IsNativeWindowInAsh(widget()->GetNativeWindow())) { frame->SetResizeSizes(ash::kResizeInsideBoundsSize, ash::kResizeOutsideBoundsSize, ash::kResizeAreaCornerSize); } #if !defined(OS_CHROMEOS) // For non-Ash windows, install an easy resize window targeter, which ensures // that the root window (not the app) receives mouse events on the edges. if (chrome::GetHostDesktopTypeForNativeWindow(widget()->GetNativeWindow()) != chrome::HOST_DESKTOP_TYPE_ASH) { aura::Window* window = widget()->GetNativeWindow(); int resize_inside = frame->resize_inside_bounds_size(); gfx::Insets inset(resize_inside, resize_inside, resize_inside, resize_inside); // Add the AppWindowEasyResizeWindowTargeter on the window, not its root // window. The root window does not have a delegate, which is needed to // handle the event in Linux. window->SetEventTargeter(scoped_ptr<ui::EventTargeter>( new AppWindowEasyResizeWindowTargeter(window, inset, this))); } #endif return frame; } gfx::Rect ChromeNativeAppWindowViewsAura::GetRestoredBounds() const { gfx::Rect* bounds = widget()->GetNativeWindow()->GetProperty(ash::kRestoreBoundsOverrideKey); if (bounds && !bounds->IsEmpty()) return *bounds; return ChromeNativeAppWindowViews::GetRestoredBounds(); } ui::WindowShowState ChromeNativeAppWindowViewsAura::GetRestoredState() const { // Use kRestoreShowStateKey in case a window is minimized/hidden. ui::WindowShowState restore_state = widget()->GetNativeWindow()->GetProperty( aura::client::kRestoreShowStateKey); if (widget()->GetNativeWindow()->GetProperty( ash::kRestoreBoundsOverrideKey)) { // If an override is given, we use that restore state (after filtering). restore_state = widget()->GetNativeWindow()->GetProperty( ash::kRestoreShowStateOverrideKey); } else { // Otherwise first normal states are checked. if (IsMaximized()) return ui::SHOW_STATE_MAXIMIZED; if (IsFullscreen()) { if (immersive_fullscreen_controller_.get() && immersive_fullscreen_controller_->IsEnabled()) { // Restore windows which were previously in immersive fullscreen to // maximized. Restoring the window to a different fullscreen type // makes for a bad experience. return ui::SHOW_STATE_MAXIMIZED; } return ui::SHOW_STATE_FULLSCREEN; } if (widget()->GetNativeWindow()->GetProperty( aura::client::kShowStateKey) == ui::SHOW_STATE_DOCKED || widget()->GetNativeWindow()->GetProperty( aura::client::kRestoreShowStateKey) == ui::SHOW_STATE_DOCKED) { return ui::SHOW_STATE_DOCKED; } } // Whitelist states to return so that invalid and transient states // are not saved and used to restore windows when they are recreated. switch (restore_state) { case ui::SHOW_STATE_NORMAL: case ui::SHOW_STATE_MAXIMIZED: case ui::SHOW_STATE_FULLSCREEN: return restore_state; case ui::SHOW_STATE_DEFAULT: case ui::SHOW_STATE_MINIMIZED: case ui::SHOW_STATE_INACTIVE: case ui::SHOW_STATE_DOCKED: case ui::SHOW_STATE_END: return ui::SHOW_STATE_NORMAL; } return ui::SHOW_STATE_NORMAL; } bool ChromeNativeAppWindowViewsAura::IsAlwaysOnTop() const { return app_window()->window_type_is_panel() ? ash::wm::GetWindowState(widget()->GetNativeWindow()) ->panel_attached() : widget()->IsAlwaysOnTop(); } void ChromeNativeAppWindowViewsAura::ShowContextMenuForView( views::View* source, const gfx::Point& p, ui::MenuSourceType source_type) { #if defined(OS_CHROMEOS) scoped_ptr<ui::MenuModel> model = CreateMultiUserContextMenu(app_window()->GetNativeWindow()); if (!model.get()) return; // Only show context menu if point is in caption. gfx::Point point_in_view_coords(p); views::View::ConvertPointFromScreen(widget()->non_client_view(), &point_in_view_coords); int hit_test = widget()->non_client_view()->NonClientHitTest(point_in_view_coords); if (hit_test == HTCAPTION) { menu_runner_.reset(new views::MenuRunner( model.get(), views::MenuRunner::HAS_MNEMONICS | views::MenuRunner::CONTEXT_MENU)); if (menu_runner_->RunMenuAt(source->GetWidget(), NULL, gfx::Rect(p, gfx::Size(0, 0)), views::MENU_ANCHOR_TOPLEFT, source_type) == views::MenuRunner::MENU_DELETED) { return; } } #endif } views::NonClientFrameView* ChromeNativeAppWindowViewsAura::CreateNonClientFrameView( views::Widget* widget) { if (chrome::IsNativeViewInAsh(widget->GetNativeView())) { // Set the delegate now because CustomFrameViewAsh sets the // WindowStateDelegate if one is not already set. ash::wm::GetWindowState(GetNativeWindow()) ->SetDelegate( scoped_ptr<ash::wm::WindowStateDelegate>( new NativeAppWindowStateDelegate(app_window(), this)).Pass()); if (IsFrameless()) return CreateNonStandardAppFrame(); if (app_window()->window_type_is_panel()) { views::NonClientFrameView* frame_view = new ash::PanelFrameView(widget, ash::PanelFrameView::FRAME_ASH); frame_view->set_context_menu_controller(this); return frame_view; } ash::CustomFrameViewAsh* custom_frame_view = new ash::CustomFrameViewAsh(widget); // Non-frameless app windows can be put into immersive fullscreen. immersive_fullscreen_controller_.reset( new ash::ImmersiveFullscreenController()); custom_frame_view->InitImmersiveFullscreenControllerForView( immersive_fullscreen_controller_.get()); custom_frame_view->GetHeaderView()->set_context_menu_controller(this); if (HasFrameColor()) { custom_frame_view->SetFrameColors(ActiveFrameColor(), InactiveFrameColor()); } return custom_frame_view; } return ChromeNativeAppWindowViews::CreateNonClientFrameView(widget); } void ChromeNativeAppWindowViewsAura::SetFullscreen(int fullscreen_types) { ChromeNativeAppWindowViews::SetFullscreen(fullscreen_types); if (immersive_fullscreen_controller_.get()) { // |immersive_fullscreen_controller_| should only be set if immersive // fullscreen is the fullscreen type used by the OS. immersive_fullscreen_controller_->SetEnabled( ash::ImmersiveFullscreenController::WINDOW_TYPE_PACKAGED_APP, (fullscreen_types & AppWindow::FULLSCREEN_TYPE_OS) != 0); // Autohide the shelf instead of hiding the shelf completely when only in // OS fullscreen. ash::wm::WindowState* window_state = ash::wm::GetWindowState(widget()->GetNativeWindow()); window_state->set_hide_shelf_when_fullscreen(fullscreen_types != AppWindow::FULLSCREEN_TYPE_OS); DCHECK(ash::Shell::HasInstance()); ash::Shell::GetInstance()->UpdateShelfVisibility(); } } void ChromeNativeAppWindowViewsAura::UpdateShape(scoped_ptr<SkRegion> region) { bool had_shape = !!shape(); ChromeNativeAppWindowViews::UpdateShape(region.Pass()); aura::Window* native_window = widget()->GetNativeWindow(); if (shape() && !had_shape) { native_window->SetEventTargeter(scoped_ptr<ui::EventTargeter>( new ShapedAppWindowTargeter(native_window, this))); } else if (!shape() && had_shape) { native_window->SetEventTargeter(scoped_ptr<ui::EventTargeter>()); } }
Chilledheart/chromium
chrome/browser/ui/views/apps/chrome_native_app_window_views_aura.cc
C++
bsd-3-clause
15,174
<header>Program zewnętrzny używany zamiast doręczania do skrzynki pocztowej</header> <center><tt>mailbox_command</tt></center> <hr> Ten parametr określa fakultatywne zewnętrzne polecenie wykorzystywane zamiast doręczania do skrzynki pocztowej. Polecenie będzie uruchamiane z&nbsp;prawami odbiorcy i&nbsp;z&nbsp;prawidłowymi ustawieniami <tt>HOME</tt>, <tt>SHELL</tt> i&nbsp;<tt>LOGNAME</tt> w&nbsp;środowisku. Wyjątek: doręczanie dla <tt>root</tt>-a odbywa się jako <tt>$default_user</tt>. <p> Inne interesujące zmienne środowiska: <tt>USER</tt> (nazwa użytkownika będącego odbiorcą), <tt>EXTENSION</tt> (rozszerzenie adresu), <tt>DOMAIN</tt> (domenowa część adresu), i&nbsp;<tt>LOCAL</tt> (lokalna część adresu). <p> W&nbsp;odróżnieniu od innych parametrów konfiguracyjnych Postfiksa, ta opcja nie jest poddana podstawianiu parametrów. Ma to na celu ułatwienie podawania składni powłoki (patrz poniższy przykład). <p> Unikaj metaznaków powłoki, gdyż zmuszą one Postfiksa do uruchomienia kosztownego procesu powłoki. Sam <tt>procmail</tt> jest dostatecznie kosztowny. <p> JEŚLI KORZYSTASZ Z&nbsp;TEJ OPCJI DLA DORĘCZANIA POCZTY W&nbsp;CAŁYM SYSTEMIE, MUSISZ USTAWIĆ ALIAS PRZEKIEROWUJĄCY POCZTĘ DO ROOT-A DO ZWYKŁEGO UŻYTKOWNIKA. <p> Przykłady: <ul> <li><tt>/gdzies/tam/procmail</tt> <li><tt>/gdzies/tam/procmail -a "$EXTENSION"</tt> </ul> <hr>
rcuvgd/Webmin22.01.2016
postfix/help/opt_mailbox_command.pl.UTF-8.html
HTML
bsd-3-clause
1,401
// 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 REMOTING_CLIENT_JNI_CHROMOTING_JNI_RUNTIME_H_ #define REMOTING_CLIENT_JNI_CHROMOTING_JNI_RUNTIME_H_ #include <jni.h> #include <string> #include "base/android/scoped_java_ref.h" #include "base/at_exit.h" #include "net/url_request/url_request_context_getter.h" #include "remoting/base/auto_thread.h" #include "remoting/client/jni/chromoting_jni_instance.h" #include "remoting/protocol/connection_to_host.h" template<typename T> struct DefaultSingletonTraits; namespace remoting { bool RegisterJni(JNIEnv* env); // Houses the global resources on which the Chromoting components run // (e.g. message loops and task runners). Proxies outgoing JNI calls from its // ChromotingJniInstance member to Java. All its methods should be invoked // exclusively from the UI thread unless otherwise noted. class ChromotingJniRuntime { public: // This class is instantiated at process initialization and persists until // we close. Its components are reused across |ChromotingJniInstance|s. static ChromotingJniRuntime* GetInstance(); scoped_refptr<AutoThreadTaskRunner> ui_task_runner() { return ui_task_runner_; } scoped_refptr<AutoThreadTaskRunner> network_task_runner() { return network_task_runner_; } scoped_refptr<AutoThreadTaskRunner> display_task_runner() { return display_task_runner_; } scoped_refptr<net::URLRequestContextGetter> url_requester() { return url_requester_; } // Initiates a connection with the specified host. Only call when a host // connection is active (i.e. between a call to Connect() and the // corresponding call to Disconnect()). To skip the attempt at pair-based // authentication, leave |pairing_id| and |pairing_secret| as empty strings. void ConnectToHost(const char* username, const char* auth_token, const char* host_jid, const char* host_id, const char* host_pubkey, const char* pairing_id, const char* pairing_secret, const char* capabilities); // Terminates any ongoing connection attempt and cleans up by nullifying // |session_|. This is a no-op unless |session| is currently non-null. void DisconnectFromHost(); // Returns the client for the currently-active session. Do not call if // |session| is null. scoped_refptr<ChromotingJniInstance> session() { DCHECK(session_.get()); return session_; } // Notifies Java code of the current connection status. Call on UI thread. void OnConnectionState(protocol::ConnectionToHost::State state, protocol::ErrorCode error); // Pops up a dialog box asking the user to enter a PIN. Call on UI thread. void DisplayAuthenticationPrompt(bool pairing_supported); // Saves new pairing credentials to permanent storage. Call on UI thread. void CommitPairingCredentials(const std::string& host, const std::string& id, const std::string& secret); // Pops up a third party login page to fetch token required for // authentication. Call on UI thread. void FetchThirdPartyToken(const GURL& token_url, const std::string& client_id, const std::string& scope); // Pass on the set of negotiated capabilities to the client. void SetCapabilities(const std::string& capabilities); // Passes on the deconstructed ExtensionMessage to the client to handle // appropriately. void HandleExtensionMessage(const std::string& type, const std::string& message); // Creates a new Bitmap object to store a video frame. base::android::ScopedJavaLocalRef<jobject> NewBitmap( webrtc::DesktopSize size); // Updates video frame bitmap. |bitmap| must be an instance of // android.graphics.Bitmap. Call on the display thread. void UpdateFrameBitmap(jobject bitmap); // Updates cursor shape. Call on display thread. void UpdateCursorShape(const protocol::CursorShapeInfo& cursor_shape); // Draws the latest image buffer onto the canvas. Call on the display thread. void RedrawCanvas(); private: ChromotingJniRuntime(); // Forces a DisconnectFromHost() in case there is any active or failed // connection, then proceeds to tear down the Chromium dependencies on which // all sessions depended. Because destruction only occurs at application exit // after all connections have terminated, it is safe to make unretained // cross-thread calls on the class. virtual ~ChromotingJniRuntime(); // Detaches JVM from the current thread, then signals. Doesn't own |waiter|. void DetachFromVmAndSignal(base::WaitableEvent* waiter); // Used by the Chromium libraries to clean up the base and net libraries' JNI // bindings. It must persist for the lifetime of the singleton. scoped_ptr<base::AtExitManager> at_exit_manager_; // Chromium code's connection to the Java message loop. scoped_ptr<base::MessageLoopForUI> ui_loop_; // References to native threads. scoped_refptr<AutoThreadTaskRunner> ui_task_runner_; scoped_refptr<AutoThreadTaskRunner> network_task_runner_; scoped_refptr<AutoThreadTaskRunner> display_task_runner_; scoped_refptr<net::URLRequestContextGetter> url_requester_; // Contains all connection-specific state. scoped_refptr<ChromotingJniInstance> session_; friend struct DefaultSingletonTraits<ChromotingJniRuntime>; DISALLOW_COPY_AND_ASSIGN(ChromotingJniRuntime); }; } // namespace remoting #endif
CTSRD-SOAAP/chromium-42.0.2311.135
remoting/client/jni/chromoting_jni_runtime.h
C
bsd-3-clause
5,739
// 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_AUTOFILL_CORE_BROWSER_AUTOFILL_DATA_MODEL_H_ #define COMPONENTS_AUTOFILL_CORE_BROWSER_AUTOFILL_DATA_MODEL_H_ #include <string> #include "base/strings/string16.h" #include "base/time/time.h" #include "components/autofill/core/browser/form_group.h" namespace autofill { class AutofillType; // This class is an interface for the primary data models that back Autofill. // The information in objects of this class is managed by the // PersonalDataManager. class AutofillDataModel : public FormGroup { public: AutofillDataModel(const std::string& guid, const std::string& origin); ~AutofillDataModel() override; // Returns true if the data in this model was entered directly by the user, // rather than automatically aggregated. bool IsVerified() const; // Called to update |use_count_| and |use_date_| when this data model is // the subject of user interaction (usually, when it's used to fill a form). void RecordUse(); std::string guid() const { return guid_; } void set_guid(const std::string& guid) { guid_ = guid; } std::string origin() const { return origin_; } void set_origin(const std::string& origin) { origin_ = origin; } size_t use_count() const { return use_count_; } void set_use_count(size_t count) { use_count_ = count; } const base::Time& use_date() const { return use_date_; } void set_use_date(const base::Time& time) { use_date_ = time; } const base::Time& modification_date() const { return modification_date_; } // This should only be called from database code. void set_modification_date(const base::Time& time) { modification_date_ = time; } private: // A globally unique ID for this object. std::string guid_; // The origin of this data. This should be // (a) a web URL for the domain of the form from which the data was // automatically aggregated, e.g. https://www.example.com/register, // (b) some other non-empty string, which cannot be interpreted as a web // URL, identifying the origin for non-aggregated data, or // (c) an empty string, indicating that the origin for this data is unknown. std::string origin_; // The number of times this model has been used. size_t use_count_; // The last time the model was used. base::Time use_date_; // The last time data in the model was modified. base::Time modification_date_; }; } // namespace autofill #endif // COMPONENTS_AUTOFILL_CORE_BROWSER_AUTOFILL_DATA_MODEL_H_
Chilledheart/chromium
components/autofill/core/browser/autofill_data_model.h
C
bsd-3-clause
2,641
import warnings from django.conf import settings from django.contrib.auth.models import User, Group, Permission, AnonymousUser from django.contrib.contenttypes.models import ContentType from django.test import TestCase class BackendTest(TestCase): backend = 'django.contrib.auth.backends.ModelBackend' def setUp(self): self.curr_auth = settings.AUTHENTICATION_BACKENDS settings.AUTHENTICATION_BACKENDS = (self.backend,) User.objects.create_user('test', 'test@example.com', 'test') def tearDown(self): settings.AUTHENTICATION_BACKENDS = self.curr_auth def test_has_perm(self): user = User.objects.get(username='test') self.assertEqual(user.has_perm('auth.test'), False) user.is_staff = True user.save() self.assertEqual(user.has_perm('auth.test'), False) user.is_superuser = True user.save() self.assertEqual(user.has_perm('auth.test'), True) user.is_staff = False user.is_superuser = False user.save() self.assertEqual(user.has_perm('auth.test'), False) user.is_staff = True user.is_superuser = True user.is_active = False user.save() self.assertEqual(user.has_perm('auth.test'), False) def test_custom_perms(self): user = User.objects.get(username='test') content_type=ContentType.objects.get_for_model(Group) perm = Permission.objects.create(name='test', content_type=content_type, codename='test') user.user_permissions.add(perm) user.save() # reloading user to purge the _perm_cache user = User.objects.get(username='test') self.assertEqual(user.get_all_permissions() == set([u'auth.test']), True) self.assertEqual(user.get_group_permissions(), set([])) self.assertEqual(user.has_module_perms('Group'), False) self.assertEqual(user.has_module_perms('auth'), True) perm = Permission.objects.create(name='test2', content_type=content_type, codename='test2') user.user_permissions.add(perm) user.save() perm = Permission.objects.create(name='test3', content_type=content_type, codename='test3') user.user_permissions.add(perm) user.save() user = User.objects.get(username='test') self.assertEqual(user.get_all_permissions(), set([u'auth.test2', u'auth.test', u'auth.test3'])) self.assertEqual(user.has_perm('test'), False) self.assertEqual(user.has_perm('auth.test'), True) self.assertEqual(user.has_perms(['auth.test2', 'auth.test3']), True) perm = Permission.objects.create(name='test_group', content_type=content_type, codename='test_group') group = Group.objects.create(name='test_group') group.permissions.add(perm) group.save() user.groups.add(group) user = User.objects.get(username='test') exp = set([u'auth.test2', u'auth.test', u'auth.test3', u'auth.test_group']) self.assertEqual(user.get_all_permissions(), exp) self.assertEqual(user.get_group_permissions(), set([u'auth.test_group'])) self.assertEqual(user.has_perms(['auth.test3', 'auth.test_group']), True) user = AnonymousUser() self.assertEqual(user.has_perm('test'), False) self.assertEqual(user.has_perms(['auth.test2', 'auth.test3']), False) def test_has_no_object_perm(self): """Regressiontest for #12462""" user = User.objects.get(username='test') content_type=ContentType.objects.get_for_model(Group) perm = Permission.objects.create(name='test', content_type=content_type, codename='test') user.user_permissions.add(perm) user.save() self.assertEqual(user.has_perm('auth.test', 'object'), False) self.assertEqual(user.get_all_permissions('object'), set([])) self.assertEqual(user.has_perm('auth.test'), True) self.assertEqual(user.get_all_permissions(), set(['auth.test'])) class TestObj(object): pass class SimpleRowlevelBackend(object): supports_object_permissions = True # This class also supports tests for anonymous user permissions, # via subclasses which just set the 'supports_anonymous_user' attribute. def has_perm(self, user, perm, obj=None): if not obj: return # We only support row level perms if isinstance(obj, TestObj): if user.username == 'test2': return True elif user.is_anonymous() and perm == 'anon': # not reached due to supports_anonymous_user = False return True return False def has_module_perms(self, user, app_label): return app_label == "app1" def get_all_permissions(self, user, obj=None): if not obj: return [] # We only support row level perms if not isinstance(obj, TestObj): return ['none'] if user.is_anonymous(): return ['anon'] if user.username == 'test2': return ['simple', 'advanced'] else: return ['simple'] def get_group_permissions(self, user, obj=None): if not obj: return # We only support row level perms if not isinstance(obj, TestObj): return ['none'] if 'test_group' in [group.name for group in user.groups.all()]: return ['group_perm'] else: return ['none'] class RowlevelBackendTest(TestCase): """ Tests for auth backend that supports object level permissions """ backend = 'django.contrib.auth.tests.auth_backends.SimpleRowlevelBackend' def setUp(self): self.curr_auth = settings.AUTHENTICATION_BACKENDS settings.AUTHENTICATION_BACKENDS = tuple(self.curr_auth) + (self.backend,) self.user1 = User.objects.create_user('test', 'test@example.com', 'test') self.user2 = User.objects.create_user('test2', 'test2@example.com', 'test') self.user3 = User.objects.create_user('test3', 'test3@example.com', 'test') self.save_warnings_state() warnings.filterwarnings('ignore', category=DeprecationWarning, module='django.contrib.auth') def tearDown(self): settings.AUTHENTICATION_BACKENDS = self.curr_auth self.restore_warnings_state() def test_has_perm(self): self.assertEqual(self.user1.has_perm('perm', TestObj()), False) self.assertEqual(self.user2.has_perm('perm', TestObj()), True) self.assertEqual(self.user2.has_perm('perm'), False) self.assertEqual(self.user2.has_perms(['simple', 'advanced'], TestObj()), True) self.assertEqual(self.user3.has_perm('perm', TestObj()), False) self.assertEqual(self.user3.has_perm('anon', TestObj()), False) self.assertEqual(self.user3.has_perms(['simple', 'advanced'], TestObj()), False) def test_get_all_permissions(self): self.assertEqual(self.user1.get_all_permissions(TestObj()), set(['simple'])) self.assertEqual(self.user2.get_all_permissions(TestObj()), set(['simple', 'advanced'])) self.assertEqual(self.user2.get_all_permissions(), set([])) def test_get_group_permissions(self): content_type=ContentType.objects.get_for_model(Group) group = Group.objects.create(name='test_group') self.user3.groups.add(group) self.assertEqual(self.user3.get_group_permissions(TestObj()), set(['group_perm'])) class AnonymousUserBackend(SimpleRowlevelBackend): supports_anonymous_user = True class NoAnonymousUserBackend(SimpleRowlevelBackend): supports_anonymous_user = False class AnonymousUserBackendTest(TestCase): """ Tests for AnonymousUser delegating to backend if it has 'supports_anonymous_user' = True """ backend = 'django.contrib.auth.tests.auth_backends.AnonymousUserBackend' def setUp(self): self.curr_auth = settings.AUTHENTICATION_BACKENDS settings.AUTHENTICATION_BACKENDS = (self.backend,) self.user1 = AnonymousUser() def tearDown(self): settings.AUTHENTICATION_BACKENDS = self.curr_auth def test_has_perm(self): self.assertEqual(self.user1.has_perm('perm', TestObj()), False) self.assertEqual(self.user1.has_perm('anon', TestObj()), True) def test_has_perms(self): self.assertEqual(self.user1.has_perms(['anon'], TestObj()), True) self.assertEqual(self.user1.has_perms(['anon', 'perm'], TestObj()), False) def test_has_module_perms(self): self.assertEqual(self.user1.has_module_perms("app1"), True) self.assertEqual(self.user1.has_module_perms("app2"), False) def test_get_all_permissions(self): self.assertEqual(self.user1.get_all_permissions(TestObj()), set(['anon'])) class NoAnonymousUserBackendTest(TestCase): """ Tests that AnonymousUser does not delegate to backend if it has 'supports_anonymous_user' = False """ backend = 'django.contrib.auth.tests.auth_backends.NoAnonymousUserBackend' def setUp(self): self.curr_auth = settings.AUTHENTICATION_BACKENDS settings.AUTHENTICATION_BACKENDS = tuple(self.curr_auth) + (self.backend,) self.user1 = AnonymousUser() def tearDown(self): settings.AUTHENTICATION_BACKENDS = self.curr_auth def test_has_perm(self): self.assertEqual(self.user1.has_perm('perm', TestObj()), False) self.assertEqual(self.user1.has_perm('anon', TestObj()), False) def test_has_perms(self): self.assertEqual(self.user1.has_perms(['anon'], TestObj()), False) def test_has_module_perms(self): self.assertEqual(self.user1.has_module_perms("app1"), False) self.assertEqual(self.user1.has_module_perms("app2"), False) def test_get_all_permissions(self): self.assertEqual(self.user1.get_all_permissions(TestObj()), set())
towerjoo/mindsbook
django/contrib/auth/tests/auth_backends.py
Python
bsd-3-clause
9,952
using FluentNHibernate.Conventions; using FluentNHibernate.Conventions.Instances; namespace Examples.FirstAutomappedProject { /// <summary> /// This is a convention that will be applied to all entities in your application. What this particular /// convention does is to specify that many-to-one, one-to-many, and many-to-many relationships will all /// have their Cascade option set to All. /// </summary> class CascadeConvention : IReferenceConvention, IHasManyConvention, IHasManyToManyConvention { public void Apply(IManyToOneInstance instance) { instance.Cascade.All(); } public void Apply(IOneToManyCollectionInstance instance) { instance.Cascade.All(); } public void Apply(IManyToManyCollectionInstance instance) { instance.Cascade.All(); } } }
HermanSchoenfeld/fluent-nhibernate
src/Examples.FirstAutomappedProject/CascadeConvention.cs
C#
bsd-3-clause
923
from SimpleCV import Camera, Image, Color, TemporalColorTracker, ROI, Display import matplotlib.pyplot as plt cam = Camera(1) tct = TemporalColorTracker() img = cam.getImage() roi = ROI(img.width*0.45,img.height*0.45,img.width*0.1,img.height*0.1,img) tct.train(cam,roi=roi,maxFrames=250,pkWndw=20) # Matplot Lib example plotting plotc = {'r':'r','g':'g','b':'b','i':'m','h':'y'} for key in tct.data.keys(): plt.plot(tct.data[key],plotc[key]) for pt in tct.peaks[key]: plt.plot(pt[0],pt[1],'r*') for pt in tct.valleys[key]: plt.plot(pt[0],pt[1],'b*') plt.grid() plt.show() disp = Display((800,600)) while disp.isNotDone(): img = cam.getImage() result = tct.recognize(img) plt.plot(tct._rtData,'r-') plt.grid() plt.savefig('temp.png') plt.clf() plotImg = Image('temp.png') roi = ROI(img.width*0.45,img.height*0.45,img.width*0.1,img.height*0.1,img) roi.draw(width=3) img.drawText(str(result),20,20,color=Color.RED,fontsize=32) img = img.applyLayers() img = img.blit(plotImg.resize(w=img.width,h=img.height),pos=(0,0),alpha=0.5) img.save(disp)
beni55/SimpleCV
SimpleCV/MachineLearning/TestTemporalColorTracker.py
Python
bsd-3-clause
1,136
# [Echo](https://github.com/labstack/echo) (Go) Benchmarking Test This is the go portion of a [benchmarking test suite](https://www.techempower.com/benchmarks/) comparing a variety of web development platforms. > High performance, extensible, minimalist Go web framework ## Test URLs - http://localhost:8080/json - http://localhost:8080/db - http://localhost:8080/queries/:n[1-500] - http://localhost:8080/fortunes - http://localhost:8080/updates/:n[1-500] - http://localhost:8080/plaintext
sumeetchhetri/FrameworkBenchmarks
frameworks/Go/echo/README.md
Markdown
bsd-3-clause
495
// 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 CHROME_BROWSER_UI_BLOCKED_CONTENT_BLOCKED_WINDOW_PARAMS_H_ #define CHROME_BROWSER_UI_BLOCKED_CONTENT_BLOCKED_WINDOW_PARAMS_H_ #include "chrome/browser/ui/browser_navigator.h" #include "content/public/common/referrer.h" #include "third_party/WebKit/public/web/WebWindowFeatures.h" #include "ui/base/window_open_disposition.h" #include "url/gurl.h" namespace content { class WebContents; } // namespace content class BlockedWindowParams { public: BlockedWindowParams(const GURL& target_url, const content::Referrer& referrer, WindowOpenDisposition disposition, const blink::WebWindowFeatures& features, bool user_gesture, bool opener_suppressed, int render_process_id, int opener_render_frame_id); chrome::NavigateParams CreateNavigateParams( content::WebContents* web_contents) const; blink::WebWindowFeatures features() const { return features_; } int opener_render_frame_id() const { return opener_render_frame_id_; } int render_process_id() const { return render_process_id_; } const GURL& target_url() const { return target_url_; } private: GURL target_url_; content::Referrer referrer_; WindowOpenDisposition disposition_; blink::WebWindowFeatures features_; bool user_gesture_; bool opener_suppressed_; int render_process_id_; int opener_render_frame_id_; }; #endif // CHROME_BROWSER_UI_BLOCKED_CONTENT_BLOCKED_WINDOW_PARAMS_H_
SaschaMester/delicium
chrome/browser/ui/blocked_content/blocked_window_params.h
C
bsd-3-clause
1,733
Объекты доступа к данным (DAO) ============================== Построенные поверх [PDO](http://php.net/manual/ru/book.pdo.php), Yii DAO (объекты доступа к данным) обеспечивают объектно-ориентированный API для доступа к реляционным базам данных. Это основа для других, более продвинутых, методов доступа к базам данных, включая [построитель запросов](db-query-builder.md) и [active record](db-active-record.md). При использовании Yii DAO вы в основном будете использовать чистый SQL и массивы PHP. Как результат, это самый эффективный способ доступа к базам данных. Тем не менее, так как синтаксис SQL может отличаться для разных баз данных, используя Yii DAO вам нужно будет приложить дополнительные усилия, чтобы сделать приложение не зависящим от конкретной базы данных. Yii DAO из коробки поддерживает следующие базы данных: - [MySQL](http://www.mysql.com/) - [MariaDB](https://mariadb.com/) - [SQLite](http://sqlite.org/) - [PostgreSQL](http://www.postgresql.org/) - [CUBRID](http://www.cubrid.org/): версии 9.3 или выше. - [Oracle](http://www.oracle.com/us/products/database/overview/index.html) - [MSSQL](https://www.microsoft.com/en-us/sqlserver/default.aspx): версии 2008 или выше. ## Создание подключения к базе данных <span id="creating-db-connections"></span> Для доступа к базе данных, вы сначала должны подключится к ней, создав экземпляр класса [[yii\db\Connection]]: ```php $db = new yii\db\Connection([ 'dsn' => 'mysql:host=localhost;dbname=example', 'username' => 'root', 'password' => '', 'charset' => 'utf8', ]); ``` Так как подключение к БД часто нужно в нескольких местах, распространённой практикой является его настройка как [компонента приложения](structure-application-components.md): ```php return [ // ... 'components' => [ // ... 'db' => [ 'class' => 'yii\db\Connection', 'dsn' => 'mysql:host=localhost;dbname=example', 'username' => 'root', 'password' => '', 'charset' => 'utf8', ], ], // ... ]; ``` Теперь вы можете получить доступ к подключению к БД с помощью выражения `Yii::$app->db`. > Tip: Вы можете настроить несколько компонентов подключения, если в вашем приложении используется несколько баз данных. При настройке подключения, вы должны обязательно указывать Имя Источника Данных (DSN) через параметр [[yii\db\Connection::dsn|dsn]]. Формат DSN отличается для разных баз данных. Дополнительное описание смотрите в [справочнике PHP](http://php.net/manual/ru/pdo.construct.php). Ниже представлены несколько примеров: * MySQL, MariaDB: `mysql:host=localhost;dbname=mydatabase` * SQLite: `sqlite:/path/to/database/file` * PostgreSQL: `pgsql:host=localhost;port=5432;dbname=mydatabase` * CUBRID: `cubrid:dbname=demodb;host=localhost;port=33000` * MS SQL Server (via sqlsrv driver): `sqlsrv:Server=localhost;Database=mydatabase` * MS SQL Server (via dblib driver): `dblib:host=localhost;dbname=mydatabase` * MS SQL Server (via mssql driver): `mssql:host=localhost;dbname=mydatabase` * Oracle: `oci:dbname=//localhost:1521/mydatabase` Заметьте, что если вы подключаетесь к базе данных через ODBC, вам необходимо указать свойство [[yii\db\Connection::driverName]], чтобы Yii знал какой тип базы данных используется. Например, ```php 'db' => [ 'class' => 'yii\db\Connection', 'driverName' => 'mysql', 'dsn' => 'odbc:Driver={MySQL};Server=localhost;Database=test', 'username' => 'root', 'password' => '', ], ``` Кроме свойства [[yii\db\Connection::dsn|dsn]], вам необходимо указать [[yii\db\Connection::username|username]] и [[yii\db\Connection::password|password]]. Смотрите [[yii\db\Connection]] для того, чтоб посмотреть полный список свойств. > Info: При создании экземпляра соединения к БД, фактическое соединение с базой данных будет установлено только при выполнении первого SQL запроса или при явном вызове метода [[yii\db\Connection::open()|open()]]. > Tip: Иногда может потребоваться выполнить некоторые запросы сразу после соединения с базой данных, для инициализации > переменных окружения. Например, чтобы задать часовой пояс или кодировку. Сделать это можно зарегистрировав обработчик > для события [[yii\db\Connection::EVENT_AFTER_OPEN|afterOpen]] в конфигурации приложения: > > ```php > 'db' => [ > // ... > 'on afterOpen' => function($event) { > // $event->sender содержит соединение с базой данных > $event->sender->createCommand("SET time_zone = 'UTC'")->execute(); > } > ] > ``` ## Выполнение SQL запросов <span id="executing-sql-queries"></span> После создания экземпляра соединения, вы можете выполнить SQL запрос, выполнив следующие шаги: 1. Создать [[yii\db\Command]] из запроса SQL; 2. Привязать параметры (не обязательно); 3. Вызвать один из методов выполнения SQL из [[yii\db\Command]]. Следующий пример показывает различные способы получения данных из базы дынных: ```php // возвращает набор строк. каждая строка - это ассоциативный массив с именами столбцов и значений. // если выборка ничего не вернёт, то будет получен пустой массив. $posts = Yii::$app->db->createCommand('SELECT * FROM post') ->queryAll(); // вернёт одну строку (первую строку) // false, если ничего не будет выбрано $post = Yii::$app->db->createCommand('SELECT * FROM post WHERE id=1') ->queryOne(); // вернёт один столбец (первый столбец) // пустой массив, при отсутствии результата $titles = Yii::$app->db->createCommand('SELECT title FROM post') ->queryColumn(); // вернёт скалярное значение // или false, при отсутствии результата $count = Yii::$app->db->createCommand('SELECT COUNT(*) FROM post') ->queryScalar(); ``` > Note: Чтобы сохранить точность, данные извлекаются как строки, даже если тип поля в базе данных является числовым. ### Привязка параметров <span id="binding-parameters"></span> При создании команды из SQL запроса с параметрами, вы почти всегда должны использовать привязку параметров для предотвращения атак через SQL инъекции. Например, ```php $post = Yii::$app->db->createCommand('SELECT * FROM post WHERE id=:id AND status=:status') ->bindValue(':id', $_GET['id']) ->bindValue(':status', 1) ->queryOne(); ``` В SQL запрос, вы можете встраивать один или несколько маркеров (например `:id` в примере выше). Маркеры должны быть строкой, начинающейся с двоеточия. Далее вам нужно вызвать один из следующих методов для привязки значений к параметрам: * [[yii\db\Command::bindValue()|bindValue()]]: привязка одного параметра по значению * [[yii\db\Command::bindValues()|bindValues()]]: привязка нескольких параметров в одном вызове * [[yii\db\Command::bindParam()|bindParam()]]: похоже на [[yii\db\Command::bindValue()|bindValue()]] но привязка происходит по ссылке. Следующий пример показывает альтернативный путь привязки параметров: ```php $params = [':id' => $_GET['id'], ':status' => 1]; $post = Yii::$app->db->createCommand('SELECT * FROM post WHERE id=:id AND status=:status') ->bindValues($params) ->queryOne(); $post = Yii::$app->db->createCommand('SELECT * FROM post WHERE id=:id AND status=:status', $params) ->queryOne(); ``` Привязка переменных реализована через [подготавливаемые запросы](http://php.net/manual/ru/mysqli.quickstart.prepared-statements.php). Помимо предотвращения атак путём SQL инъекций, это увеличивает производительность, так как запрос подготавливается один раз, а потом выполняется много раз с разными параметрами. Например, ```php $command = Yii::$app->db->createCommand('SELECT * FROM post WHERE id=:id'); $post1 = $command->bindValue(':id', 1)->queryOne(); $post2 = $command->bindValue(':id', 2)->queryOne(); // ... ``` Так как [[yii\db\Command::bindParam()|bindParam()]] поддерживает привязку параметров по ссылке, следующий код может быть написан следующим образом: ```php $command = Yii::$app->db->createCommand('SELECT * FROM post WHERE id=:id') ->bindParam(':id', $id); $id = 1; $post1 = $command->queryOne(); $id = 2; $post2 = $command->queryOne(); // ... ``` Обратите внимание что вы связываете маркер `$id` с переменной перед выполнением запроса, и затем меняете это значение перед каждым последующим выполнением (часто это делается в цикле). Выполнении запросов таким образом может быть значительно более эффективным, чем выполнение запроса для каждого значения параметра. ### Выполнение Не-SELECT запросов <span id="non-select-queries"></span> В методах `queryXyz()`, описанных в предыдущих разделах, вызываются SELECT запросы для извлечения данных из базы. Для запросов не возвращающих данные, вы должны использовать метод [[yii\db\Command::execute()]]. Например, ```php Yii::$app->db->createCommand('UPDATE post SET status=1 WHERE id=1') ->execute(); ``` Метод [[yii\db\Command::execute()]] возвращает количество строк обработанных SQL запросом. Для запросов INSERT, UPDATE и DELETE, вместо написания чистого SQL, вы можете вызвать методы [[yii\db\Command::insert()|insert()]], [[yii\db\Command::update()|update()]], [[yii\db\Command::delete()|delete()]], соответственно, для создания указанных SQL конструкций. Например, ```php // INSERT (table name, column values) Yii::$app->db->createCommand()->insert('user', [ 'name' => 'Sam', 'age' => 30, ])->execute(); // UPDATE (table name, column values, condition) Yii::$app->db->createCommand()->update('user', ['status' => 1], 'age > 30')->execute(); // DELETE (table name, condition) Yii::$app->db->createCommand()->delete('user', 'status = 0')->execute(); ``` Вы можете также вызвать [[yii\db\Command::batchInsert()|batchInsert()]] для вставки множества строк за один вызов. Это более эффективно чем вставлять записи по одной за раз: ```php // table name, column names, column values Yii::$app->db->createCommand()->batchInsert('user', ['name', 'age'], [ ['Tom', 30], ['Jane', 20], ['Linda', 25], ])->execute(); ``` Обратите внимание, что перечисленные методы лишь создают запрос. Чтобы его выполнить нужно вызывать [[yii\db\Command::execute()|execute()]]. ## Экранирование имён таблиц и столбцов <span id="quoting-table-and-column-names"></span> При написании независимого от базы данных кода, правильно экранировать имена таблиц и столбцов довольно трудно, так как в разных базах данных правила экранирования разные. Чтоб преодолеть данную проблему вы можете использовать следующий синтаксис экранирования используемый в Yii: * `[[column name]]`: заключайте имя столбца в двойные квадратные скобки; * `{{table name}}`: заключайте имя таблицы в двойные фигурные скобки. Yii DAO будет автоматически преобразовывать подобные конструкции в SQL в правильно экранированные имена таблиц и столбцов. Например, ```php // executes this SQL for MySQL: SELECT COUNT(`id`) FROM `employee` $count = Yii::$app->db->createCommand("SELECT COUNT([[id]]) FROM {{employee}}") ->queryScalar(); ``` ### Использование префиксов таблиц <span id="using-table-prefix"></span> Если большинство ваших таблиц использует общий префикс в имени, вы можете использовать свойство Yii DAO для указания префикса. Сначала, укажите префикс таблиц через свойство [[yii\db\Connection::tablePrefix]]: ```php return [ // ... 'components' => [ // ... 'db' => [ // ... 'tablePrefix' => 'tbl_', ], ], ]; ``` Затем в коде, когда вам нужно ссылаться на таблицу, имя которой содержит такой префикс, используйте синтаксис `{{%table name}}`. Символ процента будет автоматически заменён на префикс таблицы, который вы указали во время конфигурации соединения с базой данных. Например, ```php // для MySQL будет выполнен следующий SQL: SELECT COUNT(`id`) FROM `tbl_employee` $count = Yii::$app->db->createCommand("SELECT COUNT([[id]]) FROM {{%employee}}") ->queryScalar(); ``` ## Исполнение транзакций <span id="performing-transactions"></span> Когда вы выполняете несколько зависимых запросов последовательно, вам может потребоваться обернуть их в транзакцию для обеспечения целостности вашей базы данных. Если в любом из запросов произойдёт ошибка, база данных откатится на состояние, которое было до выполнения запросов. Следующий код показывает типичное использование транзакций: ```php Yii::$app->db->transaction(function($db) { $db->createCommand($sql1)->execute(); $db->createCommand($sql2)->execute(); // ... executing other SQL statements ... }); ``` Код выше эквивалентен приведённому ниже. Разница в том, что в данном случае мы получаем больше контроля над обработкой ошибок: ```php $db = Yii::$app->db; $transaction = $db->beginTransaction(); try { $db->createCommand($sql1)->execute(); $db->createCommand($sql2)->execute(); // ... executing other SQL statements ... $transaction->commit(); } catch(\Exception $e) { $transaction->rollBack(); throw $e; } ``` При вызове метода [[yii\db\Connection::beginTransaction()|beginTransaction()]], будет запущена новая транзакция. Транзакция представлена объектом [[yii\db\Transaction]] сохранённым в переменной `$transaction`. Потом, запросы будут выполняться в блоке `try...catch...`. Если запросы будут выполнены удачно, будет выполнен метод [[yii\db\Transaction::commit()|commit()]]. Иначе, будет вызвано исключение, и будет вызван метод [[yii\db\Transaction::rollBack()|rollBack()]] для отката изменений сделанных до неудачно выполненного запроса внутри транзакции. ### Указание уровня изоляции <span id="specifying-isolation-levels"></span> Yii поддерживает настройку [уровня изоляции] для ваших транзакций. По умолчанию, при старте транзакции, будет использован уровень изоляции настроенный в вашей базе данных. Вы можете переопределить уровень изоляции по умолчанию, как указано ниже: ```php $isolationLevel = \yii\db\Transaction::REPEATABLE_READ; Yii::$app->db->transaction(function ($db) { .... }, $isolationLevel); // or alternatively $transaction = Yii::$app->db->beginTransaction($isolationLevel); ``` Yii предоставляет четыре константы для наиболее распространённых уровней изоляции: - [[\yii\db\Transaction::READ_UNCOMMITTED]] - низший уровень, «Грязное» чтение, не повторяющееся чтение и фантомное чтение. - [[\yii\db\Transaction::READ_COMMITTED]] - предотвращает «Грязное» чтение. - [[\yii\db\Transaction::REPEATABLE_READ]] - предотвращает «Грязное» чтение и не повторяющееся чтение. - [[\yii\db\Transaction::SERIALIZABLE]] - высший уровень, предотвращает все вышеуказанные проблемы. Помимо использования приведённых выше констант для задания уровня изоляции, вы можете, также, использовать строки поддерживаемые вашей СУБД. Например, в PostgreSQL, вы можете использовать `SERIALIZABLE READ ONLY DEFERRABLE`. Заметьте что некоторые СУБД допускают настраивать уровень изоляции только для всего соединения. Следующие транзакции будут получать тот же уровень изоляции, даже если вы его не укажете. При использовании этой функции может потребоваться установить уровень изоляции для всех транзакций, чтоб избежать явно конфликтующих настроек. На момент написания этой статьи страдали от этого ограничения только MSSQL и SQLite. > Note: SQLite поддерживает только два уровня изоляции, таким образом вы можете использовать только `READ UNCOMMITTED` и `SERIALIZABLE`. Использование других уровней изоляции приведёт к генерации исключения. > Note: PostgreSQL не допускает установки уровня изоляции до старта транзакции, так что вы не сможете установить уровень изоляции прямо при старте транзакции. Вы можете использовать [[yii\db\Transaction::setIsolationLevel()]] в таком случае после старта транзакции. [Уровни изоляции]: https://ru.wikipedia.org/wiki/%D0%A3%D1%80%D0%BE%D0%B2%D0%B5%D0%BD%D1%8C_%D0%B8%D0%B7%D0%BE%D0%BB%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D0%BD%D0%BD%D0%BE%D1%81%D1%82%D0%B8_%D1%82%D1%80%D0%B0%D0%BD%D0%B7%D0%B0%D0%BA%D1%86%D0%B8%D0%B9 ### Вложенные транзакции <span id="nesting-transactions"></span> Если ваша СУБД поддерживает Savepoint, вы можете вкладывать транзакции как показано ниже: ```php Yii::$app->db->transaction(function ($db) { // outer transaction $db->transaction(function ($db) { // inner transaction }); }); ``` Или так, ```php $db = Yii::$app->db; $outerTransaction = $db->beginTransaction(); try { $db->createCommand($sql1)->execute(); $innerTransaction = $db->beginTransaction(); try { $db->createCommand($sql2)->execute(); $innerTransaction->commit(); } catch (\Exception $e) { $innerTransaction->rollBack(); } $outerTransaction->commit(); } catch (\Exception $e) { $outerTransaction->rollBack(); } ``` ## Репликация и разделение запросов на чтение и запись <span id="read-write-splitting"></span> Многие СУБД поддерживают [репликацию баз данных](http://en.wikipedia.org/wiki/Replication_(computing)#Database_replication) для лучшей доступности базы данных и уменьшения времени ответа сервера. С репликацией базы данных, данные копируются из *master servers* на *slave servers*. Все вставки и обновления должны происходить на основном сервере, хотя чтение может производится и с подчинённых серверов. Чтоб воспользоваться преимуществами репликации и достичь разделения чтения и записи, вам необходимо настроить компонент [[yii\db\Connection]] как указано ниже: ```php [ 'class' => 'yii\db\Connection', // настройки для мастера 'dsn' => 'dsn for master server', 'username' => 'master', 'password' => '', // общие настройки для подчинённых 'slaveConfig' => [ 'username' => 'slave', 'password' => '', 'attributes' => [ // используем небольшой таймаут для соединения PDO::ATTR_TIMEOUT => 10, ], ], // список настроек для подчинённых серверов 'slaves' => [ ['dsn' => 'dsn for slave server 1'], ['dsn' => 'dsn for slave server 2'], ['dsn' => 'dsn for slave server 3'], ['dsn' => 'dsn for slave server 4'], ], ] ``` Вышеуказанная конфигурация определяет систему с одним мастером и несколькими подчинёнными. Один из подчинённых будет подключен и использован для чтения, в то время как мастер будет использоваться для запросов записи. Такое разделение чтения и записи будет осуществлено автоматически с указанной конфигурацией. Например, ```php // создание экземпляра соединения, использующего вышеуказанную конфигурацию Yii::$app->db = Yii::createObject($config); // запрос к одному из подчинённых $rows = Yii::$app->db->createCommand('SELECT * FROM user LIMIT 10')->queryAll(); // запрос к мастеру Yii::$app->db->createCommand("UPDATE user SET username='demo' WHERE id=1")->execute(); ``` > Info: Запросы выполненные через [[yii\db\Command::execute()]] определяются как запросы на запись, а все остальные запросы через один из "query" методов [[yii\db\Command]] воспринимаются как запросы на чтение. Вы можете получить текущий статус соединения к подчинённому серверу через `$db->slave`. Компонент `Connection` поддерживает балансировку нагрузки и переключение при сбое для подчинённых серверов. При выполнении первого запроса на чтение, компонент `Connection` будет случайным образом выбирать подчинённый сервер и попытается подключиться к нему. Если сервер окажется "мёртвым", он попробует подключиться к другому. Если ни один из подчинённых серверов не будет доступен, он подключится к мастеру. Если настроить [[yii\db\Connection::serverStatusCache|кеш статуса серверов]], то недоступность серверов может быть запомнена, чтоб не использоваться в течении [[yii\db\Connection::serverRetryInterval|заданного промежутка времени]]. > Info: В конфигурации выше, таймаут соединения к подчинённому серверу настроен на 10 секунд. Это означает, что если сервер не ответит за 10 секунд, он будет считаться "мёртвым". Вы можете отрегулировать этот параметр исходя из настроек вашей среды. Вы также можете настроить несколько основных и несколько подчинённых серверов. Например, ```php [ 'class' => 'yii\db\Connection', // общая конфигурация для основных серверов 'masterConfig' => [ 'username' => 'master', 'password' => '', 'attributes' => [ // используем небольшой таймаут для соединения PDO::ATTR_TIMEOUT => 10, ], ], // список настроек для основных серверов 'masters' => [ ['dsn' => 'dsn for master server 1'], ['dsn' => 'dsn for master server 2'], ], // общие настройки для подчинённых 'slaveConfig' => [ 'username' => 'slave', 'password' => '', 'attributes' => [ // используем небольшой таймаут для соединения PDO::ATTR_TIMEOUT => 10, ], ], // список настроек для подчинённых серверов 'slaves' => [ ['dsn' => 'dsn for slave server 1'], ['dsn' => 'dsn for slave server 2'], ['dsn' => 'dsn for slave server 3'], ['dsn' => 'dsn for slave server 4'], ], ] ``` Конфигурация выше, определяет два основных и четыре подчинённых серверов. Компонент `Connection` поддерживает балансировку нагрузки и переключение при сбое между основными серверами, также как и между подчинёнными. Различие заключается в том, что когда ни к одному из основных серверов не удастся подключиться будет выброшено исключение. > Note: Когда вы используете свойство [[yii\db\Connection::masters|masters]] для настройки одного или нескольких основных серверов, все остальные свойства для настройки соединения с базой данных (такие как `dsn`, `username`, `password`) будут проигнорированы компонентом `Connection`. По умолчанию, транзакции используют соединение с основным сервером. И в рамках транзакции, все операции с БД будут использовать соединение с основным сервером. Например, ```php $db = Yii::$app->db; // Транзакция запускается на основном сервере $transaction = $db->beginTransaction(); try { // оба запроса выполняются на основном сервере $rows = $db->createCommand('SELECT * FROM user LIMIT 10')->queryAll(); $db->createCommand("UPDATE user SET username='demo' WHERE id=1")->execute(); $transaction->commit(); } catch(\Exception $e) { $transaction->rollBack(); throw $e; } ``` Если вы хотите запустить транзакцию на подчинённом сервере, вы должны указать это явно, как показано ниже: ```php $transaction = Yii::$app->db->slave->beginTransaction(); ``` Иногда может потребоваться выполнить запрос на чтение через подключение к основному серверу. Это может быть достигнуто с использованием метода `useMaster()`: ```php $rows = Yii::$app->db->useMaster(function ($db) { return $db->createCommand('SELECT * FROM user LIMIT 10')->queryAll(); }); ``` Вы также можете явно установить `$db->enableSlaves` в ложь, чтоб направлять все запросы к соединению с мастером. ## Работа со схемой базы данных <span id="database-schema"></span> Yii DAO предоставляет целый набор методов для управления схемой базы данных, таких как создание новых таблиц, удаление столбцов из таблицы, и т.д.. Эти методы описаны ниже: * [[yii\db\Command::createTable()|createTable()]]: создание таблицы * [[yii\db\Command::renameTable()|renameTable()]]: переименование таблицы * [[yii\db\Command::dropTable()|dropTable()]]: удаление таблицы * [[yii\db\Command::truncateTable()|truncateTable()]]: удаление всех записей в таблице * [[yii\db\Command::addColumn()|addColumn()]]: добавление столбца * [[yii\db\Command::renameColumn()|renameColumn()]]: переименование столбца * [[yii\db\Command::dropColumn()|dropColumn()]]: удаление столбца * [[yii\db\Command::alterColumn()|alterColumn()]]: преобразование столбца * [[yii\db\Command::addPrimaryKey()|addPrimaryKey()]]: добавление первичного ключа * [[yii\db\Command::dropPrimaryKey()|dropPrimaryKey()]]: удаление первичного ключа * [[yii\db\Command::addForeignKey()|addForeignKey()]]: добавление внешнего ключа * [[yii\db\Command::dropForeignKey()|dropForeignKey()]]: удаление внешнего ключа * [[yii\db\Command::createIndex()|createIndex()]]: создания индекса * [[yii\db\Command::dropIndex()|dropIndex()]]: удаление индекса Эти методы могут быть использованы, как указано ниже: ```php // CREATE TABLE Yii::$app->db->createCommand()->createTable('post', [ 'id' => 'pk', 'title' => 'string', 'text' => 'text', ]); ``` Вы также сможете получить описание схемы таблицы через вызов метода [[yii\db\Connection::getTableSchema()|getTableSchema()]]. Например, ```php $table = Yii::$app->db->getTableSchema('post'); ``` Метод вернёт объект [[yii\db\TableSchema]], который содержит информацию о столбцах таблицы, первичных ключах, внешних ключах, и т.д.. Вся эта информация используется главным образом для [построителя запросов](db-query-builder.md) и [active record](db-active-record.md), чтоб помочь вам писать независимый от базы данных код.
janisto/yii2
docs/guide-ru/db-dao.md
Markdown
bsd-3-clause
35,417
// Copyright 2014 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/base/bits.h" #include "src/base/division-by-constant.h" #include "src/compiler/js-graph.h" #include "src/compiler/machine-operator-reducer.h" #include "src/compiler/typer.h" #include "test/unittests/compiler/graph-unittest.h" #include "test/unittests/compiler/node-test-utils.h" #include "testing/gmock-support.h" using testing::AllOf; using testing::BitEq; using testing::Capture; using testing::CaptureEq; namespace v8 { namespace internal { namespace compiler { class MachineOperatorReducerTest : public TypedGraphTest { public: explicit MachineOperatorReducerTest(int num_parameters = 2) : TypedGraphTest(num_parameters), machine_(zone()) {} protected: Reduction Reduce(Node* node) { JSOperatorBuilder javascript(zone()); JSGraph jsgraph(isolate(), graph(), common(), &javascript, &machine_); MachineOperatorReducer reducer(&jsgraph); return reducer.Reduce(node); } Matcher<Node*> IsTruncatingDiv(const Matcher<Node*>& dividend_matcher, const int32_t divisor) { base::MagicNumbersForDivision<uint32_t> const mag = base::SignedDivisionByConstant(bit_cast<uint32_t>(divisor)); int32_t const multiplier = bit_cast<int32_t>(mag.multiplier); int32_t const shift = bit_cast<int32_t>(mag.shift); Matcher<Node*> quotient_matcher = IsInt32MulHigh(dividend_matcher, IsInt32Constant(multiplier)); if (divisor > 0 && multiplier < 0) { quotient_matcher = IsInt32Add(quotient_matcher, dividend_matcher); } else if (divisor < 0 && multiplier > 0) { quotient_matcher = IsInt32Sub(quotient_matcher, dividend_matcher); } if (shift) { quotient_matcher = IsWord32Sar(quotient_matcher, IsInt32Constant(shift)); } return IsInt32Add(quotient_matcher, IsWord32Shr(dividend_matcher, IsInt32Constant(31))); } MachineOperatorBuilder* machine() { return &machine_; } private: MachineOperatorBuilder machine_; }; template <typename T> class MachineOperatorReducerTestWithParam : public MachineOperatorReducerTest, public ::testing::WithParamInterface<T> { public: explicit MachineOperatorReducerTestWithParam(int num_parameters = 2) : MachineOperatorReducerTest(num_parameters) {} ~MachineOperatorReducerTestWithParam() OVERRIDE {} }; namespace { const float kFloat32Values[] = { -std::numeric_limits<float>::infinity(), -2.70497e+38f, -1.4698e+37f, -1.22813e+35f, -1.20555e+35f, -1.34584e+34f, -1.0079e+32f, -6.49364e+26f, -3.06077e+25f, -1.46821e+25f, -1.17658e+23f, -1.9617e+22f, -2.7357e+20f, -1.48708e+13f, -1.89633e+12f, -4.66622e+11f, -2.22581e+11f, -1.45381e+10f, -1.3956e+09f, -1.32951e+09f, -1.30721e+09f, -1.19756e+09f, -9.26822e+08f, -6.35647e+08f, -4.00037e+08f, -1.81227e+08f, -5.09256e+07f, -964300.0f, -192446.0f, -28455.0f, -27194.0f, -26401.0f, -20575.0f, -17069.0f, -9167.0f, -960.178f, -113.0f, -62.0f, -15.0f, -7.0f, -0.0256635f, -4.60374e-07f, -3.63759e-10f, -4.30175e-14f, -5.27385e-15f, -1.48084e-15f, -1.05755e-19f, -3.2995e-21f, -1.67354e-23f, -1.11885e-23f, -1.78506e-30f, -5.07594e-31f, -3.65799e-31f, -1.43718e-34f, -1.27126e-38f, -0.0f, 0.0f, 1.17549e-38f, 1.56657e-37f, 4.08512e-29f, 3.31357e-28f, 6.25073e-22f, 4.1723e-13f, 1.44343e-09f, 5.27004e-08f, 9.48298e-08f, 5.57888e-07f, 4.89988e-05f, 0.244326f, 12.4895f, 19.0f, 47.0f, 106.0f, 538.324f, 564.536f, 819.124f, 7048.0f, 12611.0f, 19878.0f, 20309.0f, 797056.0f, 1.77219e+09f, 1.51116e+11f, 4.18193e+13f, 3.59167e+16f, 3.38211e+19f, 2.67488e+20f, 1.78831e+21f, 9.20914e+21f, 8.35654e+23f, 1.4495e+24f, 5.94015e+25f, 4.43608e+30f, 2.44502e+33f, 2.61152e+33f, 1.38178e+37f, 1.71306e+37f, 3.31899e+38f, 3.40282e+38f, std::numeric_limits<float>::infinity()}; const double kFloat64Values[] = { -V8_INFINITY, -4.23878e+275, -5.82632e+265, -6.60355e+220, -6.26172e+212, -2.56222e+211, -4.82408e+201, -1.84106e+157, -1.63662e+127, -1.55772e+100, -1.67813e+72, -2.3382e+55, -3.179e+30, -1.441e+09, -1.0647e+09, -7.99361e+08, -5.77375e+08, -2.20984e+08, -32757, -13171, -9970, -3984, -107, -105, -92, -77, -61, -0.000208163, -1.86685e-06, -1.17296e-10, -9.26358e-11, -5.08004e-60, -1.74753e-65, -1.06561e-71, -5.67879e-79, -5.78459e-130, -2.90989e-171, -7.15489e-243, -3.76242e-252, -1.05639e-263, -4.40497e-267, -2.19666e-273, -4.9998e-276, -5.59821e-278, -2.03855e-282, -5.99335e-283, -7.17554e-284, -3.11744e-309, -0.0, 0.0, 2.22507e-308, 1.30127e-270, 7.62898e-260, 4.00313e-249, 3.16829e-233, 1.85244e-228, 2.03544e-129, 1.35126e-110, 1.01182e-106, 5.26333e-94, 1.35292e-90, 2.85394e-83, 1.78323e-77, 5.4967e-57, 1.03207e-25, 4.57401e-25, 1.58738e-05, 2, 125, 2310, 9636, 14802, 17168, 28945, 29305, 4.81336e+07, 1.41207e+08, 4.65962e+08, 1.40499e+09, 2.12648e+09, 8.80006e+30, 1.4446e+45, 1.12164e+54, 2.48188e+89, 6.71121e+102, 3.074e+112, 4.9699e+152, 5.58383e+166, 4.30654e+172, 7.08824e+185, 9.6586e+214, 2.028e+223, 6.63277e+243, 1.56192e+261, 1.23202e+269, 5.72883e+289, 8.5798e+290, 1.40256e+294, 1.79769e+308, V8_INFINITY}; const int32_t kInt32Values[] = { std::numeric_limits<int32_t>::min(), -1914954528, -1698749618, -1578693386, -1577976073, -1573998034, -1529085059, -1499540537, -1299205097, -1090814845, -938186388, -806828902, -750927650, -520676892, -513661538, -453036354, -433622833, -282638793, -28375, -27788, -22770, -18806, -14173, -11956, -11200, -10212, -8160, -3751, -2758, -1522, -121, -120, -118, -117, -106, -84, -80, -74, -59, -52, -48, -39, -35, -17, -11, -10, -9, -7, -5, 0, 9, 12, 17, 23, 29, 31, 33, 35, 40, 47, 55, 56, 62, 64, 67, 68, 69, 74, 79, 84, 89, 90, 97, 104, 118, 124, 126, 127, 7278, 17787, 24136, 24202, 25570, 26680, 30242, 32399, 420886487, 642166225, 821912648, 822577803, 851385718, 1212241078, 1411419304, 1589626102, 1596437184, 1876245816, 1954730266, 2008792749, 2045320228, std::numeric_limits<int32_t>::max()}; const int64_t kInt64Values[] = { std::numeric_limits<int64_t>::min(), V8_INT64_C(-8974392461363618006), V8_INT64_C(-8874367046689588135), V8_INT64_C(-8269197512118230839), V8_INT64_C(-8146091527100606733), V8_INT64_C(-7550917981466150848), V8_INT64_C(-7216590251577894337), V8_INT64_C(-6464086891160048440), V8_INT64_C(-6365616494908257190), V8_INT64_C(-6305630541365849726), V8_INT64_C(-5982222642272245453), V8_INT64_C(-5510103099058504169), V8_INT64_C(-5496838675802432701), V8_INT64_C(-4047626578868642657), V8_INT64_C(-4033755046900164544), V8_INT64_C(-3554299241457877041), V8_INT64_C(-2482258764588614470), V8_INT64_C(-1688515425526875335), V8_INT64_C(-924784137176548532), V8_INT64_C(-725316567157391307), V8_INT64_C(-439022654781092241), V8_INT64_C(-105545757668917080), V8_INT64_C(-2088319373), V8_INT64_C(-2073699916), V8_INT64_C(-1844949911), V8_INT64_C(-1831090548), V8_INT64_C(-1756711933), V8_INT64_C(-1559409497), V8_INT64_C(-1281179700), V8_INT64_C(-1211513985), V8_INT64_C(-1182371520), V8_INT64_C(-785934753), V8_INT64_C(-767480697), V8_INT64_C(-705745662), V8_INT64_C(-514362436), V8_INT64_C(-459916580), V8_INT64_C(-312328082), V8_INT64_C(-302949707), V8_INT64_C(-285499304), V8_INT64_C(-125701262), V8_INT64_C(-95139843), V8_INT64_C(-32768), V8_INT64_C(-27542), V8_INT64_C(-23600), V8_INT64_C(-18582), V8_INT64_C(-17770), V8_INT64_C(-9086), V8_INT64_C(-9010), V8_INT64_C(-8244), V8_INT64_C(-2890), V8_INT64_C(-103), V8_INT64_C(-34), V8_INT64_C(-27), V8_INT64_C(-25), V8_INT64_C(-9), V8_INT64_C(-7), V8_INT64_C(0), V8_INT64_C(2), V8_INT64_C(38), V8_INT64_C(58), V8_INT64_C(65), V8_INT64_C(93), V8_INT64_C(111), V8_INT64_C(1003), V8_INT64_C(1267), V8_INT64_C(12797), V8_INT64_C(23122), V8_INT64_C(28200), V8_INT64_C(30888), V8_INT64_C(42648848), V8_INT64_C(116836693), V8_INT64_C(263003643), V8_INT64_C(571039860), V8_INT64_C(1079398689), V8_INT64_C(1145196402), V8_INT64_C(1184846321), V8_INT64_C(1758281648), V8_INT64_C(1859991374), V8_INT64_C(1960251588), V8_INT64_C(2042443199), V8_INT64_C(296220586027987448), V8_INT64_C(1015494173071134726), V8_INT64_C(1151237951914455318), V8_INT64_C(1331941174616854174), V8_INT64_C(2022020418667972654), V8_INT64_C(2450251424374977035), V8_INT64_C(3668393562685561486), V8_INT64_C(4858229301215502171), V8_INT64_C(4919426235170669383), V8_INT64_C(5034286595330341762), V8_INT64_C(5055797915536941182), V8_INT64_C(6072389716149252074), V8_INT64_C(6185309910199801210), V8_INT64_C(6297328311011094138), V8_INT64_C(6932372858072165827), V8_INT64_C(8483640924987737210), V8_INT64_C(8663764179455849203), V8_INT64_C(8877197042645298254), V8_INT64_C(8901543506779157333), std::numeric_limits<int64_t>::max()}; const uint32_t kUint32Values[] = { 0x00000000, 0x00000001, 0xffffffff, 0x1b09788b, 0x04c5fce8, 0xcc0de5bf, 0x273a798e, 0x187937a3, 0xece3af83, 0x5495a16b, 0x0b668ecc, 0x11223344, 0x0000009e, 0x00000043, 0x0000af73, 0x0000116b, 0x00658ecc, 0x002b3b4c, 0x88776655, 0x70000000, 0x07200000, 0x7fffffff, 0x56123761, 0x7fffff00, 0x761c4761, 0x80000000, 0x88888888, 0xa0000000, 0xdddddddd, 0xe0000000, 0xeeeeeeee, 0xfffffffd, 0xf0000000, 0x007fffff, 0x003fffff, 0x001fffff, 0x000fffff, 0x0007ffff, 0x0003ffff, 0x0001ffff, 0x0000ffff, 0x00007fff, 0x00003fff, 0x00001fff, 0x00000fff, 0x000007ff, 0x000003ff, 0x000001ff}; struct ComparisonBinaryOperator { const Operator* (MachineOperatorBuilder::*constructor)(); const char* constructor_name; }; std::ostream& operator<<(std::ostream& os, ComparisonBinaryOperator const& cbop) { return os << cbop.constructor_name; } const ComparisonBinaryOperator kComparisonBinaryOperators[] = { #define OPCODE(Opcode) \ { &MachineOperatorBuilder::Opcode, #Opcode } \ , MACHINE_COMPARE_BINOP_LIST(OPCODE) #undef OPCODE }; } // namespace // ----------------------------------------------------------------------------- // Unary operators namespace { struct UnaryOperator { const Operator* (MachineOperatorBuilder::*constructor)(); const char* constructor_name; }; std::ostream& operator<<(std::ostream& os, const UnaryOperator& unop) { return os << unop.constructor_name; } static const UnaryOperator kUnaryOperators[] = { {&MachineOperatorBuilder::ChangeInt32ToFloat64, "ChangeInt32ToFloat64"}, {&MachineOperatorBuilder::ChangeUint32ToFloat64, "ChangeUint32ToFloat64"}, {&MachineOperatorBuilder::ChangeFloat64ToInt32, "ChangeFloat64ToInt32"}, {&MachineOperatorBuilder::ChangeFloat64ToUint32, "ChangeFloat64ToUint32"}, {&MachineOperatorBuilder::ChangeInt32ToInt64, "ChangeInt32ToInt64"}, {&MachineOperatorBuilder::ChangeUint32ToUint64, "ChangeUint32ToUint64"}, {&MachineOperatorBuilder::TruncateFloat64ToInt32, "TruncateFloat64ToInt32"}, {&MachineOperatorBuilder::TruncateInt64ToInt32, "TruncateInt64ToInt32"}}; } // namespace typedef MachineOperatorReducerTestWithParam<UnaryOperator> MachineUnaryOperatorReducerTest; TEST_P(MachineUnaryOperatorReducerTest, Parameter) { const UnaryOperator unop = GetParam(); Reduction reduction = Reduce(graph()->NewNode((machine()->*unop.constructor)(), Parameter(0))); EXPECT_FALSE(reduction.Changed()); } INSTANTIATE_TEST_CASE_P(MachineOperatorReducerTest, MachineUnaryOperatorReducerTest, ::testing::ValuesIn(kUnaryOperators)); // ----------------------------------------------------------------------------- // ChangeFloat64ToFloat32 TEST_F(MachineOperatorReducerTest, ChangeFloat64ToFloat32WithConstant) { TRACED_FOREACH(float, x, kFloat32Values) { Reduction reduction = Reduce(graph()->NewNode( machine()->ChangeFloat32ToFloat64(), Float32Constant(x))); ASSERT_TRUE(reduction.Changed()); EXPECT_THAT(reduction.replacement(), IsFloat64Constant(BitEq<double>(x))); } } // ----------------------------------------------------------------------------- // ChangeFloat64ToInt32 TEST_F(MachineOperatorReducerTest, ChangeFloat64ToInt32WithChangeInt32ToFloat64) { Node* value = Parameter(0); Reduction reduction = Reduce(graph()->NewNode( machine()->ChangeFloat64ToInt32(), graph()->NewNode(machine()->ChangeInt32ToFloat64(), value))); ASSERT_TRUE(reduction.Changed()); EXPECT_EQ(value, reduction.replacement()); } TEST_F(MachineOperatorReducerTest, ChangeFloat64ToInt32WithConstant) { TRACED_FOREACH(int32_t, x, kInt32Values) { Reduction reduction = Reduce(graph()->NewNode( machine()->ChangeFloat64ToInt32(), Float64Constant(FastI2D(x)))); ASSERT_TRUE(reduction.Changed()); EXPECT_THAT(reduction.replacement(), IsInt32Constant(x)); } } // ----------------------------------------------------------------------------- // ChangeFloat64ToUint32 TEST_F(MachineOperatorReducerTest, ChangeFloat64ToUint32WithChangeUint32ToFloat64) { Node* value = Parameter(0); Reduction reduction = Reduce(graph()->NewNode( machine()->ChangeFloat64ToUint32(), graph()->NewNode(machine()->ChangeUint32ToFloat64(), value))); ASSERT_TRUE(reduction.Changed()); EXPECT_EQ(value, reduction.replacement()); } TEST_F(MachineOperatorReducerTest, ChangeFloat64ToUint32WithConstant) { TRACED_FOREACH(uint32_t, x, kUint32Values) { Reduction reduction = Reduce(graph()->NewNode( machine()->ChangeFloat64ToUint32(), Float64Constant(FastUI2D(x)))); ASSERT_TRUE(reduction.Changed()); EXPECT_THAT(reduction.replacement(), IsInt32Constant(bit_cast<int32_t>(x))); } } // ----------------------------------------------------------------------------- // ChangeInt32ToFloat64 TEST_F(MachineOperatorReducerTest, ChangeInt32ToFloat64WithConstant) { TRACED_FOREACH(int32_t, x, kInt32Values) { Reduction reduction = Reduce( graph()->NewNode(machine()->ChangeInt32ToFloat64(), Int32Constant(x))); ASSERT_TRUE(reduction.Changed()); EXPECT_THAT(reduction.replacement(), IsFloat64Constant(BitEq(FastI2D(x)))); } } // ----------------------------------------------------------------------------- // ChangeInt32ToInt64 TEST_F(MachineOperatorReducerTest, ChangeInt32ToInt64WithConstant) { TRACED_FOREACH(int32_t, x, kInt32Values) { Reduction reduction = Reduce( graph()->NewNode(machine()->ChangeInt32ToInt64(), Int32Constant(x))); ASSERT_TRUE(reduction.Changed()); EXPECT_THAT(reduction.replacement(), IsInt64Constant(x)); } } // ----------------------------------------------------------------------------- // ChangeUint32ToFloat64 TEST_F(MachineOperatorReducerTest, ChangeUint32ToFloat64WithConstant) { TRACED_FOREACH(uint32_t, x, kUint32Values) { Reduction reduction = Reduce(graph()->NewNode(machine()->ChangeUint32ToFloat64(), Int32Constant(bit_cast<int32_t>(x)))); ASSERT_TRUE(reduction.Changed()); EXPECT_THAT(reduction.replacement(), IsFloat64Constant(BitEq(FastUI2D(x)))); } } // ----------------------------------------------------------------------------- // ChangeUint32ToUint64 TEST_F(MachineOperatorReducerTest, ChangeUint32ToUint64WithConstant) { TRACED_FOREACH(uint32_t, x, kUint32Values) { Reduction reduction = Reduce(graph()->NewNode(machine()->ChangeUint32ToUint64(), Int32Constant(bit_cast<int32_t>(x)))); ASSERT_TRUE(reduction.Changed()); EXPECT_THAT(reduction.replacement(), IsInt64Constant(bit_cast<int64_t>(static_cast<uint64_t>(x)))); } } // ----------------------------------------------------------------------------- // TruncateFloat64ToFloat32 TEST_F(MachineOperatorReducerTest, TruncateFloat64ToFloat32WithChangeFloat32ToFloat64) { Node* value = Parameter(0); Reduction reduction = Reduce(graph()->NewNode( machine()->TruncateFloat64ToFloat32(), graph()->NewNode(machine()->ChangeFloat32ToFloat64(), value))); ASSERT_TRUE(reduction.Changed()); EXPECT_EQ(value, reduction.replacement()); } TEST_F(MachineOperatorReducerTest, TruncateFloat64ToFloat32WithConstant) { TRACED_FOREACH(double, x, kFloat64Values) { Reduction reduction = Reduce(graph()->NewNode( machine()->TruncateFloat64ToFloat32(), Float64Constant(x))); ASSERT_TRUE(reduction.Changed()); EXPECT_THAT(reduction.replacement(), IsFloat32Constant(BitEq(DoubleToFloat32(x)))); } } // ----------------------------------------------------------------------------- // TruncateFloat64ToInt32 TEST_F(MachineOperatorReducerTest, TruncateFloat64ToInt32WithChangeInt32ToFloat64) { Node* value = Parameter(0); Reduction reduction = Reduce(graph()->NewNode( machine()->TruncateFloat64ToInt32(), graph()->NewNode(machine()->ChangeInt32ToFloat64(), value))); ASSERT_TRUE(reduction.Changed()); EXPECT_EQ(value, reduction.replacement()); } TEST_F(MachineOperatorReducerTest, TruncateFloat64ToInt32WithConstant) { TRACED_FOREACH(double, x, kFloat64Values) { Reduction reduction = Reduce(graph()->NewNode( machine()->TruncateFloat64ToInt32(), Float64Constant(x))); ASSERT_TRUE(reduction.Changed()); EXPECT_THAT(reduction.replacement(), IsInt32Constant(DoubleToInt32(x))); } } TEST_F(MachineOperatorReducerTest, TruncateFloat64ToInt32WithPhi) { Node* const p0 = Parameter(0); Node* const p1 = Parameter(1); Node* const merge = graph()->start(); Reduction reduction = Reduce(graph()->NewNode( machine()->TruncateFloat64ToInt32(), graph()->NewNode(common()->Phi(kMachFloat64, 2), p0, p1, merge))); ASSERT_TRUE(reduction.Changed()); EXPECT_THAT(reduction.replacement(), IsPhi(kMachInt32, IsTruncateFloat64ToInt32(p0), IsTruncateFloat64ToInt32(p1), merge)); } // ----------------------------------------------------------------------------- // TruncateInt64ToInt32 TEST_F(MachineOperatorReducerTest, TruncateInt64ToInt32WithChangeInt32ToInt64) { Node* value = Parameter(0); Reduction reduction = Reduce(graph()->NewNode( machine()->TruncateInt64ToInt32(), graph()->NewNode(machine()->ChangeInt32ToInt64(), value))); ASSERT_TRUE(reduction.Changed()); EXPECT_EQ(value, reduction.replacement()); } TEST_F(MachineOperatorReducerTest, TruncateInt64ToInt32WithConstant) { TRACED_FOREACH(int64_t, x, kInt64Values) { Reduction reduction = Reduce( graph()->NewNode(machine()->TruncateInt64ToInt32(), Int64Constant(x))); ASSERT_TRUE(reduction.Changed()); EXPECT_THAT(reduction.replacement(), IsInt32Constant(bit_cast<int32_t>( static_cast<uint32_t>(bit_cast<uint64_t>(x))))); } } // ----------------------------------------------------------------------------- // Word32And TEST_F(MachineOperatorReducerTest, Word32AndWithWord32ShlWithConstant) { Node* const p0 = Parameter(0); TRACED_FORRANGE(int32_t, l, 1, 31) { TRACED_FORRANGE(int32_t, k, 1, l) { // (x << L) & (-1 << K) => x << L Reduction const r1 = Reduce(graph()->NewNode( machine()->Word32And(), graph()->NewNode(machine()->Word32Shl(), p0, Int32Constant(l)), Int32Constant(-1 << k))); ASSERT_TRUE(r1.Changed()); EXPECT_THAT(r1.replacement(), IsWord32Shl(p0, IsInt32Constant(l))); // (-1 << K) & (x << L) => x << L Reduction const r2 = Reduce(graph()->NewNode( machine()->Word32And(), Int32Constant(-1 << k), graph()->NewNode(machine()->Word32Shl(), p0, Int32Constant(l)))); ASSERT_TRUE(r2.Changed()); EXPECT_THAT(r2.replacement(), IsWord32Shl(p0, IsInt32Constant(l))); } } } TEST_F(MachineOperatorReducerTest, Word32AndWithWord32AndWithConstant) { Node* const p0 = Parameter(0); TRACED_FOREACH(int32_t, k, kInt32Values) { TRACED_FOREACH(int32_t, l, kInt32Values) { if (k == 0 || k == -1 || l == 0 || l == -1) continue; // (x & K) & L => x & (K & L) Reduction const r1 = Reduce(graph()->NewNode( machine()->Word32And(), graph()->NewNode(machine()->Word32And(), p0, Int32Constant(k)), Int32Constant(l))); ASSERT_TRUE(r1.Changed()); EXPECT_THAT(r1.replacement(), (k & l) ? IsWord32And(p0, IsInt32Constant(k & l)) : IsInt32Constant(0)); // (K & x) & L => x & (K & L) Reduction const r2 = Reduce(graph()->NewNode( machine()->Word32And(), graph()->NewNode(machine()->Word32And(), Int32Constant(k), p0), Int32Constant(l))); ASSERT_TRUE(r2.Changed()); EXPECT_THAT(r2.replacement(), (k & l) ? IsWord32And(p0, IsInt32Constant(k & l)) : IsInt32Constant(0)); } } } TEST_F(MachineOperatorReducerTest, Word32AndWithInt32AddAndConstant) { Node* const p0 = Parameter(0); Node* const p1 = Parameter(1); TRACED_FORRANGE(int32_t, l, 1, 31) { TRACED_FOREACH(int32_t, k, kInt32Values) { if ((k << l) == 0) continue; // (x + (K << L)) & (-1 << L) => (x & (-1 << L)) + (K << L) Reduction const r = Reduce(graph()->NewNode( machine()->Word32And(), graph()->NewNode(machine()->Int32Add(), p0, Int32Constant(k << l)), Int32Constant(-1 << l))); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsInt32Add(IsWord32And(p0, IsInt32Constant(-1 << l)), IsInt32Constant(k << l))); } Node* s1 = graph()->NewNode(machine()->Word32Shl(), p1, Int32Constant(l)); // (y << L + x) & (-1 << L) => (x & (-1 << L)) + y << L Reduction const r1 = Reduce(graph()->NewNode( machine()->Word32And(), graph()->NewNode(machine()->Int32Add(), s1, p0), Int32Constant(-1 << l))); ASSERT_TRUE(r1.Changed()); EXPECT_THAT(r1.replacement(), IsInt32Add(IsWord32And(p0, IsInt32Constant(-1 << l)), s1)); // (x + y << L) & (-1 << L) => (x & (-1 << L)) + y << L Reduction const r2 = Reduce(graph()->NewNode( machine()->Word32And(), graph()->NewNode(machine()->Int32Add(), p0, s1), Int32Constant(-1 << l))); ASSERT_TRUE(r2.Changed()); EXPECT_THAT(r2.replacement(), IsInt32Add(IsWord32And(p0, IsInt32Constant(-1 << l)), s1)); } } TEST_F(MachineOperatorReducerTest, Word32AndWithInt32MulAndConstant) { Node* const p0 = Parameter(0); TRACED_FORRANGE(int32_t, l, 1, 31) { TRACED_FOREACH(int32_t, k, kInt32Values) { if ((k << l) == 0) continue; // (x * (K << L)) & (-1 << L) => x * (K << L) Reduction const r1 = Reduce(graph()->NewNode( machine()->Word32And(), graph()->NewNode(machine()->Int32Mul(), p0, Int32Constant(k << l)), Int32Constant(-1 << l))); ASSERT_TRUE(r1.Changed()); EXPECT_THAT(r1.replacement(), IsInt32Mul(p0, IsInt32Constant(k << l))); // ((K << L) * x) & (-1 << L) => x * (K << L) Reduction const r2 = Reduce(graph()->NewNode( machine()->Word32And(), graph()->NewNode(machine()->Int32Mul(), Int32Constant(k << l), p0), Int32Constant(-1 << l))); ASSERT_TRUE(r2.Changed()); EXPECT_THAT(r2.replacement(), IsInt32Mul(p0, IsInt32Constant(k << l))); } } } TEST_F(MachineOperatorReducerTest, Word32AndWithInt32AddAndInt32MulAndConstant) { Node* const p0 = Parameter(0); Node* const p1 = Parameter(1); TRACED_FORRANGE(int32_t, l, 1, 31) { TRACED_FOREACH(int32_t, k, kInt32Values) { if ((k << l) == 0) continue; // (y * (K << L) + x) & (-1 << L) => (x & (-1 << L)) + y * (K << L) Reduction const r1 = Reduce(graph()->NewNode( machine()->Word32And(), graph()->NewNode(machine()->Int32Add(), graph()->NewNode(machine()->Int32Mul(), p1, Int32Constant(k << l)), p0), Int32Constant(-1 << l))); ASSERT_TRUE(r1.Changed()); EXPECT_THAT(r1.replacement(), IsInt32Add(IsWord32And(p0, IsInt32Constant(-1 << l)), IsInt32Mul(p1, IsInt32Constant(k << l)))); // (x + y * (K << L)) & (-1 << L) => (x & (-1 << L)) + y * (K << L) Reduction const r2 = Reduce(graph()->NewNode( machine()->Word32And(), graph()->NewNode(machine()->Int32Add(), p0, graph()->NewNode(machine()->Int32Mul(), p1, Int32Constant(k << l))), Int32Constant(-1 << l))); ASSERT_TRUE(r2.Changed()); EXPECT_THAT(r2.replacement(), IsInt32Add(IsWord32And(p0, IsInt32Constant(-1 << l)), IsInt32Mul(p1, IsInt32Constant(k << l)))); } } } TEST_F(MachineOperatorReducerTest, Word32AndWithComparisonAndConstantOne) { Node* const p0 = Parameter(0); Node* const p1 = Parameter(1); TRACED_FOREACH(ComparisonBinaryOperator, cbop, kComparisonBinaryOperators) { Node* cmp = graph()->NewNode((machine()->*cbop.constructor)(), p0, p1); // cmp & 1 => cmp Reduction const r1 = Reduce(graph()->NewNode(machine()->Word32And(), cmp, Int32Constant(1))); ASSERT_TRUE(r1.Changed()); EXPECT_EQ(cmp, r1.replacement()); // 1 & cmp => cmp Reduction const r2 = Reduce(graph()->NewNode(machine()->Word32And(), Int32Constant(1), cmp)); ASSERT_TRUE(r2.Changed()); EXPECT_EQ(cmp, r2.replacement()); } } // ----------------------------------------------------------------------------- // Word32Xor TEST_F(MachineOperatorReducerTest, Word32XorWithWord32XorAndMinusOne) { Node* const p0 = Parameter(0); // (x ^ -1) ^ -1 => x Reduction r1 = Reduce(graph()->NewNode( machine()->Word32Xor(), graph()->NewNode(machine()->Word32Xor(), p0, Int32Constant(-1)), Int32Constant(-1))); ASSERT_TRUE(r1.Changed()); EXPECT_EQ(r1.replacement(), p0); // -1 ^ (x ^ -1) => x Reduction r2 = Reduce(graph()->NewNode( machine()->Word32Xor(), Int32Constant(-1), graph()->NewNode(machine()->Word32Xor(), p0, Int32Constant(-1)))); ASSERT_TRUE(r2.Changed()); EXPECT_EQ(r2.replacement(), p0); // (-1 ^ x) ^ -1 => x Reduction r3 = Reduce(graph()->NewNode( machine()->Word32Xor(), graph()->NewNode(machine()->Word32Xor(), Int32Constant(-1), p0), Int32Constant(-1))); ASSERT_TRUE(r3.Changed()); EXPECT_EQ(r3.replacement(), p0); // -1 ^ (-1 ^ x) => x Reduction r4 = Reduce(graph()->NewNode( machine()->Word32Xor(), Int32Constant(-1), graph()->NewNode(machine()->Word32Xor(), Int32Constant(-1), p0))); ASSERT_TRUE(r4.Changed()); EXPECT_EQ(r4.replacement(), p0); } // ----------------------------------------------------------------------------- // Word32Ror TEST_F(MachineOperatorReducerTest, ReduceToWord32RorWithParameters) { Node* value = Parameter(0); Node* shift = Parameter(1); Node* sub = graph()->NewNode(machine()->Int32Sub(), Int32Constant(32), shift); // Testing rotate left. Node* shl_l = graph()->NewNode(machine()->Word32Shl(), value, shift); Node* shr_l = graph()->NewNode(machine()->Word32Shr(), value, sub); // (x << y) | (x >>> (32 - y)) => x ror (32 - y) Node* node1 = graph()->NewNode(machine()->Word32Or(), shl_l, shr_l); Reduction reduction1 = Reduce(node1); EXPECT_TRUE(reduction1.Changed()); EXPECT_EQ(reduction1.replacement(), node1); EXPECT_THAT(reduction1.replacement(), IsWord32Ror(value, sub)); // (x >>> (32 - y)) | (x << y) => x ror (32 - y) Node* node2 = graph()->NewNode(machine()->Word32Or(), shr_l, shl_l); Reduction reduction2 = Reduce(node2); EXPECT_TRUE(reduction2.Changed()); EXPECT_EQ(reduction2.replacement(), node2); EXPECT_THAT(reduction2.replacement(), IsWord32Ror(value, sub)); // Testing rotate right. Node* shl_r = graph()->NewNode(machine()->Word32Shl(), value, sub); Node* shr_r = graph()->NewNode(machine()->Word32Shr(), value, shift); // (x << (32 - y)) | (x >>> y) => x ror y Node* node3 = graph()->NewNode(machine()->Word32Or(), shl_r, shr_r); Reduction reduction3 = Reduce(node3); EXPECT_TRUE(reduction3.Changed()); EXPECT_EQ(reduction3.replacement(), node3); EXPECT_THAT(reduction3.replacement(), IsWord32Ror(value, shift)); // (x >>> y) | (x << (32 - y)) => x ror y Node* node4 = graph()->NewNode(machine()->Word32Or(), shr_r, shl_r); Reduction reduction4 = Reduce(node4); EXPECT_TRUE(reduction4.Changed()); EXPECT_EQ(reduction4.replacement(), node4); EXPECT_THAT(reduction4.replacement(), IsWord32Ror(value, shift)); } TEST_F(MachineOperatorReducerTest, ReduceToWord32RorWithConstant) { Node* value = Parameter(0); TRACED_FORRANGE(int32_t, k, 0, 31) { Node* shl = graph()->NewNode(machine()->Word32Shl(), value, Int32Constant(k)); Node* shr = graph()->NewNode(machine()->Word32Shr(), value, Int32Constant(32 - k)); // (x << K) | (x >>> ((32 - K) - y)) => x ror (32 - K) Node* node1 = graph()->NewNode(machine()->Word32Or(), shl, shr); Reduction reduction1 = Reduce(node1); EXPECT_TRUE(reduction1.Changed()); EXPECT_EQ(reduction1.replacement(), node1); EXPECT_THAT(reduction1.replacement(), IsWord32Ror(value, IsInt32Constant(32 - k))); // (x >>> (32 - K)) | (x << K) => x ror (32 - K) Node* node2 = graph()->NewNode(machine()->Word32Or(), shr, shl); Reduction reduction2 = Reduce(node2); EXPECT_TRUE(reduction2.Changed()); EXPECT_EQ(reduction2.replacement(), node2); EXPECT_THAT(reduction2.replacement(), IsWord32Ror(value, IsInt32Constant(32 - k))); } } TEST_F(MachineOperatorReducerTest, Word32RorWithZeroShift) { Node* value = Parameter(0); Node* node = graph()->NewNode(machine()->Word32Ror(), value, Int32Constant(0)); Reduction reduction = Reduce(node); EXPECT_TRUE(reduction.Changed()); EXPECT_EQ(reduction.replacement(), value); } TEST_F(MachineOperatorReducerTest, Word32RorWithConstants) { TRACED_FOREACH(int32_t, x, kUint32Values) { TRACED_FORRANGE(int32_t, y, 0, 31) { Node* node = graph()->NewNode(machine()->Word32Ror(), Int32Constant(x), Int32Constant(y)); Reduction reduction = Reduce(node); EXPECT_TRUE(reduction.Changed()); EXPECT_THAT(reduction.replacement(), IsInt32Constant(base::bits::RotateRight32(x, y))); } } } // ----------------------------------------------------------------------------- // Word32Sar TEST_F(MachineOperatorReducerTest, Word32SarWithWord32ShlAndComparison) { Node* const p0 = Parameter(0); Node* const p1 = Parameter(1); TRACED_FOREACH(ComparisonBinaryOperator, cbop, kComparisonBinaryOperators) { Node* cmp = graph()->NewNode((machine()->*cbop.constructor)(), p0, p1); // cmp << 31 >> 31 => 0 - cmp Reduction const r = Reduce(graph()->NewNode( machine()->Word32Sar(), graph()->NewNode(machine()->Word32Shl(), cmp, Int32Constant(31)), Int32Constant(31))); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsInt32Sub(IsInt32Constant(0), cmp)); } } TEST_F(MachineOperatorReducerTest, Word32SarWithWord32ShlAndLoad) { Node* const p0 = Parameter(0); Node* const p1 = Parameter(1); { Node* const l = graph()->NewNode(machine()->Load(kMachInt8), p0, p1, graph()->start(), graph()->start()); Reduction const r = Reduce(graph()->NewNode( machine()->Word32Sar(), graph()->NewNode(machine()->Word32Shl(), l, Int32Constant(24)), Int32Constant(24))); ASSERT_TRUE(r.Changed()); EXPECT_EQ(l, r.replacement()); } { Node* const l = graph()->NewNode(machine()->Load(kMachInt16), p0, p1, graph()->start(), graph()->start()); Reduction const r = Reduce(graph()->NewNode( machine()->Word32Sar(), graph()->NewNode(machine()->Word32Shl(), l, Int32Constant(16)), Int32Constant(16))); ASSERT_TRUE(r.Changed()); EXPECT_EQ(l, r.replacement()); } } // ----------------------------------------------------------------------------- // Word32Shl TEST_F(MachineOperatorReducerTest, Word32ShlWithZeroShift) { Node* p0 = Parameter(0); Node* node = graph()->NewNode(machine()->Word32Shl(), p0, Int32Constant(0)); Reduction r = Reduce(node); ASSERT_TRUE(r.Changed()); EXPECT_EQ(p0, r.replacement()); } TEST_F(MachineOperatorReducerTest, Word32ShlWithWord32Sar) { Node* p0 = Parameter(0); TRACED_FORRANGE(int32_t, x, 1, 31) { Node* node = graph()->NewNode( machine()->Word32Shl(), graph()->NewNode(machine()->Word32Sar(), p0, Int32Constant(x)), Int32Constant(x)); Reduction r = Reduce(node); ASSERT_TRUE(r.Changed()); int32_t m = bit_cast<int32_t>(~((1U << x) - 1U)); EXPECT_THAT(r.replacement(), IsWord32And(p0, IsInt32Constant(m))); } } TEST_F(MachineOperatorReducerTest, Word32ShlWithWord32SarAndInt32AddAndConstant) { Node* const p0 = Parameter(0); TRACED_FOREACH(int32_t, k, kInt32Values) { TRACED_FORRANGE(int32_t, l, 1, 31) { if ((k << l) == 0) continue; // (x + (K << L)) >> L << L => (x & (-1 << L)) + (K << L) Reduction const r = Reduce(graph()->NewNode( machine()->Word32Shl(), graph()->NewNode(machine()->Word32Sar(), graph()->NewNode(machine()->Int32Add(), p0, Int32Constant(k << l)), Int32Constant(l)), Int32Constant(l))); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsInt32Add(IsWord32And(p0, IsInt32Constant(-1 << l)), IsInt32Constant(k << l))); } } } TEST_F(MachineOperatorReducerTest, Word32ShlWithWord32Shr) { Node* p0 = Parameter(0); TRACED_FORRANGE(int32_t, x, 1, 31) { Node* node = graph()->NewNode( machine()->Word32Shl(), graph()->NewNode(machine()->Word32Shr(), p0, Int32Constant(x)), Int32Constant(x)); Reduction r = Reduce(node); ASSERT_TRUE(r.Changed()); int32_t m = bit_cast<int32_t>(~((1U << x) - 1U)); EXPECT_THAT(r.replacement(), IsWord32And(p0, IsInt32Constant(m))); } } // ----------------------------------------------------------------------------- // Int32Sub TEST_F(MachineOperatorReducerTest, Int32SubWithConstant) { Node* const p0 = Parameter(0); TRACED_FOREACH(int32_t, k, kInt32Values) { Reduction const r = Reduce(graph()->NewNode(machine()->Int32Sub(), p0, Int32Constant(k))); ASSERT_TRUE(r.Changed()); if (k == 0) { EXPECT_EQ(p0, r.replacement()); } else { EXPECT_THAT(r.replacement(), IsInt32Add(p0, IsInt32Constant(-k))); } } } // ----------------------------------------------------------------------------- // Int32Div TEST_F(MachineOperatorReducerTest, Int32DivWithConstant) { Node* const p0 = Parameter(0); { Reduction const r = Reduce(graph()->NewNode( machine()->Int32Div(), p0, Int32Constant(0), graph()->start())); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsInt32Constant(0)); } { Reduction const r = Reduce(graph()->NewNode( machine()->Int32Div(), p0, Int32Constant(1), graph()->start())); ASSERT_TRUE(r.Changed()); EXPECT_EQ(r.replacement(), p0); } { Reduction const r = Reduce(graph()->NewNode( machine()->Int32Div(), p0, Int32Constant(-1), graph()->start())); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsInt32Sub(IsInt32Constant(0), p0)); } { Reduction const r = Reduce(graph()->NewNode( machine()->Int32Div(), p0, Int32Constant(2), graph()->start())); ASSERT_TRUE(r.Changed()); EXPECT_THAT( r.replacement(), IsWord32Sar(IsInt32Add(IsWord32Shr(p0, IsInt32Constant(31)), p0), IsInt32Constant(1))); } { Reduction const r = Reduce(graph()->NewNode( machine()->Int32Div(), p0, Int32Constant(-2), graph()->start())); ASSERT_TRUE(r.Changed()); EXPECT_THAT( r.replacement(), IsInt32Sub( IsInt32Constant(0), IsWord32Sar(IsInt32Add(IsWord32Shr(p0, IsInt32Constant(31)), p0), IsInt32Constant(1)))); } TRACED_FORRANGE(int32_t, shift, 2, 30) { Reduction const r = Reduce(graph()->NewNode(machine()->Int32Div(), p0, Int32Constant(1 << shift), graph()->start())); ASSERT_TRUE(r.Changed()); EXPECT_THAT( r.replacement(), IsWord32Sar(IsInt32Add(IsWord32Shr(IsWord32Sar(p0, IsInt32Constant(31)), IsInt32Constant(32 - shift)), p0), IsInt32Constant(shift))); } TRACED_FORRANGE(int32_t, shift, 2, 31) { Reduction const r = Reduce(graph()->NewNode( machine()->Int32Div(), p0, Uint32Constant(bit_cast<uint32_t, int32_t>(-1) << shift), graph()->start())); ASSERT_TRUE(r.Changed()); EXPECT_THAT( r.replacement(), IsInt32Sub( IsInt32Constant(0), IsWord32Sar( IsInt32Add(IsWord32Shr(IsWord32Sar(p0, IsInt32Constant(31)), IsInt32Constant(32 - shift)), p0), IsInt32Constant(shift)))); } TRACED_FOREACH(int32_t, divisor, kInt32Values) { if (divisor < 0) { if (base::bits::IsPowerOfTwo32(-divisor)) continue; Reduction const r = Reduce(graph()->NewNode( machine()->Int32Div(), p0, Int32Constant(divisor), graph()->start())); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsInt32Sub(IsInt32Constant(0), IsTruncatingDiv(p0, -divisor))); } else if (divisor > 0) { if (base::bits::IsPowerOfTwo32(divisor)) continue; Reduction const r = Reduce(graph()->NewNode( machine()->Int32Div(), p0, Int32Constant(divisor), graph()->start())); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsTruncatingDiv(p0, divisor)); } } } TEST_F(MachineOperatorReducerTest, Int32DivWithParameters) { Node* const p0 = Parameter(0); Reduction const r = Reduce(graph()->NewNode(machine()->Int32Div(), p0, p0, graph()->start())); ASSERT_TRUE(r.Changed()); EXPECT_THAT( r.replacement(), IsWord32Equal(IsWord32Equal(p0, IsInt32Constant(0)), IsInt32Constant(0))); } // ----------------------------------------------------------------------------- // Uint32Div TEST_F(MachineOperatorReducerTest, Uint32DivWithConstant) { Node* const p0 = Parameter(0); { Reduction const r = Reduce(graph()->NewNode( machine()->Uint32Div(), Int32Constant(0), p0, graph()->start())); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsInt32Constant(0)); } { Reduction const r = Reduce(graph()->NewNode( machine()->Uint32Div(), p0, Int32Constant(0), graph()->start())); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsInt32Constant(0)); } { Reduction const r = Reduce(graph()->NewNode( machine()->Uint32Div(), p0, Int32Constant(1), graph()->start())); ASSERT_TRUE(r.Changed()); EXPECT_EQ(r.replacement(), p0); } TRACED_FOREACH(uint32_t, dividend, kUint32Values) { TRACED_FOREACH(uint32_t, divisor, kUint32Values) { Reduction const r = Reduce( graph()->NewNode(machine()->Uint32Div(), Uint32Constant(dividend), Uint32Constant(divisor), graph()->start())); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsInt32Constant(bit_cast<int32_t>( base::bits::UnsignedDiv32(dividend, divisor)))); } } TRACED_FORRANGE(uint32_t, shift, 1, 31) { Reduction const r = Reduce(graph()->NewNode(machine()->Uint32Div(), p0, Uint32Constant(1u << shift), graph()->start())); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsWord32Shr(p0, IsInt32Constant(bit_cast<int32_t>(shift)))); } } TEST_F(MachineOperatorReducerTest, Uint32DivWithParameters) { Node* const p0 = Parameter(0); Reduction const r = Reduce( graph()->NewNode(machine()->Uint32Div(), p0, p0, graph()->start())); ASSERT_TRUE(r.Changed()); EXPECT_THAT( r.replacement(), IsWord32Equal(IsWord32Equal(p0, IsInt32Constant(0)), IsInt32Constant(0))); } // ----------------------------------------------------------------------------- // Int32Mod TEST_F(MachineOperatorReducerTest, Int32ModWithConstant) { Node* const p0 = Parameter(0); { Reduction const r = Reduce(graph()->NewNode( machine()->Int32Mod(), Int32Constant(0), p0, graph()->start())); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsInt32Constant(0)); } { Reduction const r = Reduce(graph()->NewNode( machine()->Int32Mod(), p0, Int32Constant(0), graph()->start())); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsInt32Constant(0)); } { Reduction const r = Reduce(graph()->NewNode( machine()->Int32Mod(), p0, Int32Constant(1), graph()->start())); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsInt32Constant(0)); } { Reduction const r = Reduce(graph()->NewNode( machine()->Int32Mod(), p0, Int32Constant(-1), graph()->start())); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsInt32Constant(0)); } TRACED_FOREACH(int32_t, dividend, kInt32Values) { TRACED_FOREACH(int32_t, divisor, kInt32Values) { Reduction const r = Reduce( graph()->NewNode(machine()->Int32Mod(), Int32Constant(dividend), Int32Constant(divisor), graph()->start())); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsInt32Constant(base::bits::SignedMod32(dividend, divisor))); } } TRACED_FORRANGE(int32_t, shift, 1, 30) { Reduction const r = Reduce(graph()->NewNode(machine()->Int32Mod(), p0, Int32Constant(1 << shift), graph()->start())); int32_t const mask = (1 << shift) - 1; ASSERT_TRUE(r.Changed()); EXPECT_THAT( r.replacement(), IsSelect(kMachInt32, IsInt32LessThan(p0, IsInt32Constant(0)), IsInt32Sub(IsInt32Constant(0), IsWord32And(IsInt32Sub(IsInt32Constant(0), p0), IsInt32Constant(mask))), IsWord32And(p0, IsInt32Constant(mask)))); } TRACED_FORRANGE(int32_t, shift, 1, 31) { Reduction const r = Reduce(graph()->NewNode( machine()->Int32Mod(), p0, Uint32Constant(bit_cast<uint32_t, int32_t>(-1) << shift), graph()->start())); int32_t const mask = bit_cast<int32_t, uint32_t>((1U << shift) - 1); ASSERT_TRUE(r.Changed()); EXPECT_THAT( r.replacement(), IsSelect(kMachInt32, IsInt32LessThan(p0, IsInt32Constant(0)), IsInt32Sub(IsInt32Constant(0), IsWord32And(IsInt32Sub(IsInt32Constant(0), p0), IsInt32Constant(mask))), IsWord32And(p0, IsInt32Constant(mask)))); } TRACED_FOREACH(int32_t, divisor, kInt32Values) { if (divisor == 0 || base::bits::IsPowerOfTwo32(Abs(divisor))) continue; Reduction const r = Reduce(graph()->NewNode( machine()->Int32Mod(), p0, Int32Constant(divisor), graph()->start())); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsInt32Sub(p0, IsInt32Mul(IsTruncatingDiv(p0, Abs(divisor)), IsInt32Constant(Abs(divisor))))); } } TEST_F(MachineOperatorReducerTest, Int32ModWithParameters) { Node* const p0 = Parameter(0); Reduction const r = Reduce(graph()->NewNode(machine()->Int32Mod(), p0, p0, graph()->start())); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsInt32Constant(0)); } // ----------------------------------------------------------------------------- // Uint32Mod TEST_F(MachineOperatorReducerTest, Uint32ModWithConstant) { Node* const p0 = Parameter(0); { Reduction const r = Reduce(graph()->NewNode( machine()->Uint32Mod(), p0, Int32Constant(0), graph()->start())); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsInt32Constant(0)); } { Reduction const r = Reduce(graph()->NewNode( machine()->Uint32Mod(), Int32Constant(0), p0, graph()->start())); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsInt32Constant(0)); } { Reduction const r = Reduce(graph()->NewNode( machine()->Uint32Mod(), p0, Int32Constant(1), graph()->start())); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsInt32Constant(0)); } TRACED_FOREACH(uint32_t, dividend, kUint32Values) { TRACED_FOREACH(uint32_t, divisor, kUint32Values) { Reduction const r = Reduce( graph()->NewNode(machine()->Uint32Mod(), Uint32Constant(dividend), Uint32Constant(divisor), graph()->start())); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsInt32Constant(bit_cast<int32_t>( base::bits::UnsignedMod32(dividend, divisor)))); } } TRACED_FORRANGE(uint32_t, shift, 1, 31) { Reduction const r = Reduce(graph()->NewNode(machine()->Uint32Mod(), p0, Uint32Constant(1u << shift), graph()->start())); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsWord32And(p0, IsInt32Constant( bit_cast<int32_t>((1u << shift) - 1u)))); } } TEST_F(MachineOperatorReducerTest, Uint32ModWithParameters) { Node* const p0 = Parameter(0); Reduction const r = Reduce( graph()->NewNode(machine()->Uint32Mod(), p0, p0, graph()->start())); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsInt32Constant(0)); } // ----------------------------------------------------------------------------- // Int32Add TEST_F(MachineOperatorReducerTest, Int32AddWithInt32SubWithConstantZero) { Node* const p0 = Parameter(0); Node* const p1 = Parameter(1); Reduction const r1 = Reduce(graph()->NewNode( machine()->Int32Add(), graph()->NewNode(machine()->Int32Sub(), Int32Constant(0), p0), p1)); ASSERT_TRUE(r1.Changed()); EXPECT_THAT(r1.replacement(), IsInt32Sub(p1, p0)); Reduction const r2 = Reduce(graph()->NewNode( machine()->Int32Add(), p0, graph()->NewNode(machine()->Int32Sub(), Int32Constant(0), p1))); ASSERT_TRUE(r2.Changed()); EXPECT_THAT(r2.replacement(), IsInt32Sub(p0, p1)); } // ----------------------------------------------------------------------------- // Int32AddWithOverflow TEST_F(MachineOperatorReducerTest, Int32AddWithOverflowWithZero) { Node* p0 = Parameter(0); { Node* add = graph()->NewNode(machine()->Int32AddWithOverflow(), Int32Constant(0), p0); Reduction r = Reduce(graph()->NewNode(common()->Projection(1), add)); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsInt32Constant(0)); r = Reduce(graph()->NewNode(common()->Projection(0), add)); ASSERT_TRUE(r.Changed()); EXPECT_EQ(p0, r.replacement()); } { Node* add = graph()->NewNode(machine()->Int32AddWithOverflow(), p0, Int32Constant(0)); Reduction r = Reduce(graph()->NewNode(common()->Projection(1), add)); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsInt32Constant(0)); r = Reduce(graph()->NewNode(common()->Projection(0), add)); ASSERT_TRUE(r.Changed()); EXPECT_EQ(p0, r.replacement()); } } TEST_F(MachineOperatorReducerTest, Int32AddWithOverflowWithConstant) { TRACED_FOREACH(int32_t, x, kInt32Values) { TRACED_FOREACH(int32_t, y, kInt32Values) { int32_t z; Node* add = graph()->NewNode(machine()->Int32AddWithOverflow(), Int32Constant(x), Int32Constant(y)); Reduction r = Reduce(graph()->NewNode(common()->Projection(1), add)); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsInt32Constant(base::bits::SignedAddOverflow32(x, y, &z))); r = Reduce(graph()->NewNode(common()->Projection(0), add)); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsInt32Constant(z)); } } } // ----------------------------------------------------------------------------- // Int32SubWithOverflow TEST_F(MachineOperatorReducerTest, Int32SubWithOverflowWithZero) { Node* p0 = Parameter(0); Node* add = graph()->NewNode(machine()->Int32SubWithOverflow(), p0, Int32Constant(0)); Reduction r = Reduce(graph()->NewNode(common()->Projection(1), add)); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsInt32Constant(0)); r = Reduce(graph()->NewNode(common()->Projection(0), add)); ASSERT_TRUE(r.Changed()); EXPECT_EQ(p0, r.replacement()); } TEST_F(MachineOperatorReducerTest, Int32SubWithOverflowWithConstant) { TRACED_FOREACH(int32_t, x, kInt32Values) { TRACED_FOREACH(int32_t, y, kInt32Values) { int32_t z; Node* add = graph()->NewNode(machine()->Int32SubWithOverflow(), Int32Constant(x), Int32Constant(y)); Reduction r = Reduce(graph()->NewNode(common()->Projection(1), add)); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsInt32Constant(base::bits::SignedSubOverflow32(x, y, &z))); r = Reduce(graph()->NewNode(common()->Projection(0), add)); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsInt32Constant(z)); } } } // ----------------------------------------------------------------------------- // Uint32LessThan TEST_F(MachineOperatorReducerTest, Uint32LessThanWithWord32Sar) { Node* const p0 = Parameter(0); TRACED_FORRANGE(uint32_t, shift, 1, 3) { const uint32_t limit = (kMaxInt >> shift) - 1; Node* const node = graph()->NewNode( machine()->Uint32LessThan(), graph()->NewNode(machine()->Word32Sar(), p0, Uint32Constant(shift)), Uint32Constant(limit)); Reduction r = Reduce(node); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsUint32LessThan( p0, IsInt32Constant(bit_cast<int32_t>(limit << shift)))); } } // ----------------------------------------------------------------------------- // Float64Mul TEST_F(MachineOperatorReducerTest, Float64MulWithMinusOne) { Node* const p0 = Parameter(0); { Reduction r = Reduce( graph()->NewNode(machine()->Float64Mul(), p0, Float64Constant(-1.0))); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsFloat64Sub(IsFloat64Constant(BitEq(-0.0)), p0)); } { Reduction r = Reduce( graph()->NewNode(machine()->Float64Mul(), Float64Constant(-1.0), p0)); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsFloat64Sub(IsFloat64Constant(BitEq(-0.0)), p0)); } } // ----------------------------------------------------------------------------- // Float64InsertLowWord32 TEST_F(MachineOperatorReducerTest, Float64InsertLowWord32WithConstant) { TRACED_FOREACH(double, x, kFloat64Values) { TRACED_FOREACH(uint32_t, y, kUint32Values) { Reduction const r = Reduce(graph()->NewNode(machine()->Float64InsertLowWord32(), Float64Constant(x), Uint32Constant(y))); ASSERT_TRUE(r.Changed()); EXPECT_THAT( r.replacement(), IsFloat64Constant(BitEq(bit_cast<double>( (bit_cast<uint64_t>(x) & V8_UINT64_C(0xFFFFFFFF00000000)) | y)))); } } } // ----------------------------------------------------------------------------- // Float64InsertHighWord32 TEST_F(MachineOperatorReducerTest, Float64InsertHighWord32WithConstant) { TRACED_FOREACH(double, x, kFloat64Values) { TRACED_FOREACH(uint32_t, y, kUint32Values) { Reduction const r = Reduce(graph()->NewNode(machine()->Float64InsertHighWord32(), Float64Constant(x), Uint32Constant(y))); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsFloat64Constant(BitEq(bit_cast<double>( (bit_cast<uint64_t>(x) & V8_UINT64_C(0xFFFFFFFF)) | (static_cast<uint64_t>(y) << 32))))); } } } // ----------------------------------------------------------------------------- // Store TEST_F(MachineOperatorReducerTest, StoreRepWord8WithWord32And) { const StoreRepresentation rep(kRepWord8, kNoWriteBarrier); Node* const base = Parameter(0); Node* const index = Parameter(1); Node* const value = Parameter(2); Node* const effect = graph()->start(); Node* const control = graph()->start(); TRACED_FOREACH(uint32_t, x, kUint32Values) { Node* const node = graph()->NewNode(machine()->Store(rep), base, index, graph()->NewNode(machine()->Word32And(), value, Uint32Constant(x | 0xffu)), effect, control); Reduction r = Reduce(node); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsStore(rep, base, index, value, effect, control)); } } TEST_F(MachineOperatorReducerTest, StoreRepWord8WithWord32SarAndWord32Shl) { const StoreRepresentation rep(kRepWord8, kNoWriteBarrier); Node* const base = Parameter(0); Node* const index = Parameter(1); Node* const value = Parameter(2); Node* const effect = graph()->start(); Node* const control = graph()->start(); TRACED_FORRANGE(int32_t, x, 1, 24) { Node* const node = graph()->NewNode( machine()->Store(rep), base, index, graph()->NewNode( machine()->Word32Sar(), graph()->NewNode(machine()->Word32Shl(), value, Int32Constant(x)), Int32Constant(x)), effect, control); Reduction r = Reduce(node); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsStore(rep, base, index, value, effect, control)); } } TEST_F(MachineOperatorReducerTest, StoreRepWord16WithWord32And) { const StoreRepresentation rep(kRepWord16, kNoWriteBarrier); Node* const base = Parameter(0); Node* const index = Parameter(1); Node* const value = Parameter(2); Node* const effect = graph()->start(); Node* const control = graph()->start(); TRACED_FOREACH(uint32_t, x, kUint32Values) { Node* const node = graph()->NewNode(machine()->Store(rep), base, index, graph()->NewNode(machine()->Word32And(), value, Uint32Constant(x | 0xffffu)), effect, control); Reduction r = Reduce(node); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsStore(rep, base, index, value, effect, control)); } } TEST_F(MachineOperatorReducerTest, StoreRepWord16WithWord32SarAndWord32Shl) { const StoreRepresentation rep(kRepWord16, kNoWriteBarrier); Node* const base = Parameter(0); Node* const index = Parameter(1); Node* const value = Parameter(2); Node* const effect = graph()->start(); Node* const control = graph()->start(); TRACED_FORRANGE(int32_t, x, 1, 16) { Node* const node = graph()->NewNode( machine()->Store(rep), base, index, graph()->NewNode( machine()->Word32Sar(), graph()->NewNode(machine()->Word32Shl(), value, Int32Constant(x)), Int32Constant(x)), effect, control); Reduction r = Reduce(node); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsStore(rep, base, index, value, effect, control)); } } } // namespace compiler } // namespace internal } // namespace v8
sgraham/nope
v8/test/unittests/compiler/machine-operator-reducer-unittest.cc
C++
bsd-3-clause
59,530
/* * Copyright 2016 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #ifndef GrResourceHandle_DEFINED #define GrResourceHandle_DEFINED #include "include/core/SkTypes.h" // Opaque handle to a resource. Users should always use the macro below to create a specific // template instantiation of GrResourceHandle. template <typename kind> class GrResourceHandle { public: GrResourceHandle(int value) : fValue(value) { SkASSERT(this->isValid()); } GrResourceHandle() : fValue(kInvalid_ResourceHandle) {} bool operator==(const GrResourceHandle& other) const { return other.fValue == fValue; } bool isValid() const { return kInvalid_ResourceHandle != fValue; } int toIndex() const { SkASSERT(this->isValid()); return fValue; } private: static const int kInvalid_ResourceHandle = -1; int fValue; }; // Creates a type "name", which is a specfic template instantiation of GrResourceHandle. #define GR_DEFINE_RESOURCE_HANDLE_CLASS(name) \ struct name##Kind {}; \ using name = GrResourceHandle<name##Kind>; #endif
youtube/cobalt
third_party/skia_next/third_party/skia/src/gpu/GrResourceHandle.h
C
bsd-3-clause
1,131
require 'rubygems' require 'rubygems/user_interaction' require 'uri' ## # RemoteFetcher handles the details of fetching gems and gem information from # a remote source. class Gem::RemoteFetcher BuiltinSSLCerts = File.expand_path("./ssl_certs/*.pem", File.dirname(__FILE__)) include Gem::UserInteraction ## # A FetchError exception wraps up the various possible IO and HTTP failures # that could happen while downloading from the internet. class FetchError < Gem::Exception ## # The URI which was being accessed when the exception happened. attr_accessor :uri def initialize(message, uri) super message @uri = uri end def to_s # :nodoc: "#{super} (#{uri})" end end @fetcher = nil ## # Cached RemoteFetcher instance. def self.fetcher @fetcher ||= self.new Gem.configuration[:http_proxy] end ## # Initialize a remote fetcher using the source URI and possible proxy # information. # # +proxy+ # * [String]: explicit specification of proxy; overrides any environment # variable setting # * nil: respect environment variables (HTTP_PROXY, HTTP_PROXY_USER, # HTTP_PROXY_PASS) # * <tt>:no_proxy</tt>: ignore environment variables and _don't_ use a proxy def initialize(proxy = nil) require 'net/http' require 'stringio' require 'time' require 'uri' Socket.do_not_reverse_lookup = true @connections = {} @requests = Hash.new 0 @proxy_uri = case proxy when :no_proxy then nil when nil then get_proxy_from_env when URI::HTTP then proxy else URI.parse(proxy) end @user_agent = user_agent end ## # Given a name and requirement, downloads this gem into cache and returns the # filename. Returns nil if the gem cannot be located. #-- # Should probably be integrated with #download below, but that will be a # larger, more emcompassing effort. -erikh def download_to_cache dependency found = Gem::SpecFetcher.fetcher.fetch dependency, true, true, dependency.prerelease? return if found.empty? spec, source_uri = found.sort_by { |(s,_)| s.version }.last download spec, source_uri end ## # Moves the gem +spec+ from +source_uri+ to the cache dir unless it is # already there. If the source_uri is local the gem cache dir copy is # always replaced. def download(spec, source_uri, install_dir = Gem.dir) Gem.ensure_gem_subdirectories(install_dir) rescue nil if File.writable?(install_dir) cache_dir = File.join install_dir, "cache" else cache_dir = File.join Gem.user_dir, "cache" end gem_file_name = File.basename spec.cache_file local_gem_path = File.join cache_dir, gem_file_name FileUtils.mkdir_p cache_dir rescue nil unless File.exist? cache_dir # Always escape URI's to deal with potential spaces and such unless URI::Generic === source_uri source_uri = URI.parse(URI.const_defined?(:DEFAULT_PARSER) ? URI::DEFAULT_PARSER.escape(source_uri.to_s) : URI.escape(source_uri.to_s)) end scheme = source_uri.scheme # URI.parse gets confused by MS Windows paths with forward slashes. scheme = nil if scheme =~ /^[a-z]$/i case scheme when 'http', 'https' then unless File.exist? local_gem_path then begin say "Downloading gem #{gem_file_name}" if Gem.configuration.really_verbose remote_gem_path = source_uri + "gems/#{gem_file_name}" gem = self.fetch_path remote_gem_path rescue Gem::RemoteFetcher::FetchError raise if spec.original_platform == spec.platform alternate_name = "#{spec.original_name}.gem" say "Failed, downloading gem #{alternate_name}" if Gem.configuration.really_verbose remote_gem_path = source_uri + "gems/#{alternate_name}" gem = self.fetch_path remote_gem_path end File.open local_gem_path, 'wb' do |fp| fp.write gem end end when 'file' then begin path = source_uri.path path = File.dirname(path) if File.extname(path) == '.gem' remote_gem_path = correct_for_windows_path(File.join(path, 'gems', gem_file_name)) FileUtils.cp(remote_gem_path, local_gem_path) rescue Errno::EACCES local_gem_path = source_uri.to_s end say "Using local gem #{local_gem_path}" if Gem.configuration.really_verbose when nil then # TODO test for local overriding cache source_path = if Gem.win_platform? && source_uri.scheme && !source_uri.path.include?(':') then "#{source_uri.scheme}:#{source_uri.path}" else source_uri.path end source_path = unescape source_path begin FileUtils.cp source_path, local_gem_path unless File.identical?(source_path, local_gem_path) rescue Errno::EACCES local_gem_path = source_uri.to_s end say "Using local gem #{local_gem_path}" if Gem.configuration.really_verbose else raise Gem::InstallError, "unsupported URI scheme #{source_uri.scheme}" end local_gem_path end ## # File Fetcher. Dispatched by +fetch_path+. Use it instead. def fetch_file uri, *_ Gem.read_binary correct_for_windows_path uri.path end ## # HTTP Fetcher. Dispatched by +fetch_path+. Use it instead. def fetch_http uri, last_modified = nil, head = false, depth = 0 fetch_type = head ? Net::HTTP::Head : Net::HTTP::Get response = request uri, fetch_type, last_modified case response when Net::HTTPOK, Net::HTTPNotModified then head ? response : response.body when Net::HTTPMovedPermanently, Net::HTTPFound, Net::HTTPSeeOther, Net::HTTPTemporaryRedirect then raise FetchError.new('too many redirects', uri) if depth > 10 location = URI.parse response['Location'] if https?(uri) && !https?(location) raise FetchError.new("redirecting to non-https resource: #{location}", uri) end fetch_http(location, last_modified, head, depth + 1) else raise FetchError.new("bad response #{response.message} #{response.code}", uri) end end alias :fetch_https :fetch_http ## # Downloads +uri+ and returns it as a String. def fetch_path(uri, mtime = nil, head = false) uri = URI.parse uri unless URI::Generic === uri raise ArgumentError, "bad uri: #{uri}" unless uri raise ArgumentError, "uri scheme is invalid: #{uri.scheme.inspect}" unless uri.scheme data = send "fetch_#{uri.scheme}", uri, mtime, head data = Gem.gunzip data if data and not head and uri.to_s =~ /gz$/ data rescue FetchError raise rescue Timeout::Error raise FetchError.new('timed out', uri.to_s) rescue IOError, SocketError, SystemCallError => e raise FetchError.new("#{e.class}: #{e}", uri.to_s) end ## # Returns the size of +uri+ in bytes. def fetch_size(uri) # TODO: phase this out response = fetch_path(uri, nil, true) response['content-length'].to_i end def escape(str) return unless str @uri_parser ||= uri_escaper @uri_parser.escape str end def unescape(str) return unless str @uri_parser ||= uri_escaper @uri_parser.unescape str end def uri_escaper URI::Parser.new rescue NameError URI end ## # Returns an HTTP proxy URI if one is set in the environment variables. def get_proxy_from_env env_proxy = ENV['http_proxy'] || ENV['HTTP_PROXY'] return nil if env_proxy.nil? or env_proxy.empty? uri = URI.parse(normalize_uri(env_proxy)) if uri and uri.user.nil? and uri.password.nil? then # Probably we have http_proxy_* variables? uri.user = escape(ENV['http_proxy_user'] || ENV['HTTP_PROXY_USER']) uri.password = escape(ENV['http_proxy_pass'] || ENV['HTTP_PROXY_PASS']) end uri end ## # Normalize the URI by adding "http://" if it is missing. def normalize_uri(uri) (uri =~ /^(https?|ftp|file):/) ? uri : "http://#{uri}" end ## # Creates or an HTTP connection based on +uri+, or retrieves an existing # connection, using a proxy if needed. def connection_for(uri) net_http_args = [uri.host, uri.port] if @proxy_uri then net_http_args += [ @proxy_uri.host, @proxy_uri.port, @proxy_uri.user, @proxy_uri.password ] end connection_id = [Thread.current.object_id, *net_http_args].join ':' @connections[connection_id] ||= Net::HTTP.new(*net_http_args) connection = @connections[connection_id] if https?(uri) and !connection.started? then configure_connection_for_https(connection) # Don't refactor this with the else branch. We don't want the # http-only code path to not depend on anything in OpenSSL. # begin connection.start rescue OpenSSL::SSL::SSLError, Errno::EHOSTDOWN => e raise FetchError.new(e.message, uri) end else begin connection.start unless connection.started? rescue Errno::EHOSTDOWN => e raise FetchError.new(e.message, uri) end end connection end def configure_connection_for_https(connection) require 'net/https' connection.use_ssl = true connection.verify_mode = Gem.configuration.ssl_verify_mode || OpenSSL::SSL::VERIFY_PEER store = OpenSSL::X509::Store.new if Gem.configuration.ssl_ca_cert if File.directory? Gem.configuration.ssl_ca_cert store.add_path Gem.configuration.ssl_ca_cert else store.add_file Gem.configuration.ssl_ca_cert end else store.set_default_paths add_rubygems_trusted_certs(store) end connection.cert_store = store end def add_rubygems_trusted_certs(store) Dir.glob(BuiltinSSLCerts).each do |ssl_cert_file| store.add_file ssl_cert_file end end def correct_for_windows_path(path) if path[0].chr == '/' && path[1].chr =~ /[a-z]/i && path[2].chr == ':' path = path[1..-1] else path end end ## # Read the data from the (source based) URI, but if it is a file:// URI, # read from the filesystem instead. def open_uri_or_path(uri, last_modified = nil, head = false, depth = 0) raise "NO: Use fetch_path instead" # TODO: deprecate for fetch_path end ## # Performs a Net::HTTP request of type +request_class+ on +uri+ returning # a Net::HTTP response object. request maintains a table of persistent # connections to reduce connect overhead. def request(uri, request_class, last_modified = nil) request = request_class.new uri.request_uri unless uri.nil? || uri.user.nil? || uri.user.empty? then request.basic_auth uri.user, uri.password end request.add_field 'User-Agent', @user_agent request.add_field 'Connection', 'keep-alive' request.add_field 'Keep-Alive', '30' if last_modified then last_modified = last_modified.utc request.add_field 'If-Modified-Since', last_modified.rfc2822 end yield request if block_given? connection = connection_for uri retried = false bad_response = false begin @requests[connection.object_id] += 1 say "#{request.method} #{uri}" if Gem.configuration.really_verbose file_name = File.basename(uri.path) # perform download progress reporter only for gems if request.response_body_permitted? && file_name =~ /\.gem$/ reporter = ui.download_reporter response = connection.request(request) do |incomplete_response| if Net::HTTPOK === incomplete_response reporter.fetch(file_name, incomplete_response.content_length) downloaded = 0 data = '' incomplete_response.read_body do |segment| data << segment downloaded += segment.length reporter.update(downloaded) end reporter.done if incomplete_response.respond_to? :body= incomplete_response.body = data else incomplete_response.instance_variable_set(:@body, data) end end end else response = connection.request request end say "#{response.code} #{response.message}" if Gem.configuration.really_verbose rescue Net::HTTPBadResponse say "bad response" if Gem.configuration.really_verbose reset connection raise FetchError.new('too many bad responses', uri) if bad_response bad_response = true retry # HACK work around EOFError bug in Net::HTTP # NOTE Errno::ECONNABORTED raised a lot on Windows, and make impossible # to install gems. rescue EOFError, Timeout::Error, Errno::ECONNABORTED, Errno::ECONNRESET, Errno::EPIPE requests = @requests[connection.object_id] say "connection reset after #{requests} requests, retrying" if Gem.configuration.really_verbose raise FetchError.new('too many connection resets', uri) if retried reset connection retried = true retry end response end ## # Resets HTTP connection +connection+. def reset(connection) @requests.delete connection.object_id connection.finish connection.start end def user_agent ua = "RubyGems/#{Gem::VERSION} #{Gem::Platform.local}" ruby_version = RUBY_VERSION ruby_version += 'dev' if RUBY_PATCHLEVEL == -1 ua << " Ruby/#{ruby_version} (#{RUBY_RELEASE_DATE}" if RUBY_PATCHLEVEL >= 0 then ua << " patchlevel #{RUBY_PATCHLEVEL}" elsif defined?(RUBY_REVISION) then ua << " revision #{RUBY_REVISION}" end ua << ")" ua << " #{RUBY_ENGINE}" if defined?(RUBY_ENGINE) and RUBY_ENGINE != 'ruby' ua end def https?(uri) uri.scheme.downcase == 'https' end end
yob/debian-rubinius
lib/rubygems/remote_fetcher.rb
Ruby
bsd-3-clause
14,114
namespace std { template<typename T> class allocator { public: void in_base(); }; template<typename T, typename Alloc = std::allocator<T> > class vector : Alloc { public: void foo(); void stop(); }; template<typename Alloc> class vector<bool, Alloc>; } void f() { std::vector<int> v; v.foo(); // RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:18:8 %s -o - | FileCheck -check-prefix=CHECK-CC1 %s // CHECK-CC1: allocator<<#typename T#>> // CHECK-CC1-NEXT: vector<<#typename T#>{#, <#typename Alloc#>#}> // RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:19:5 %s -o - | FileCheck -check-prefix=CHECK-CC2 %s // CHECK-CC2: foo // CHECK-CC2: in_base // CHECK-CC2: stop } template <typename> struct X; template <typename T> struct X<T*> { X(double); }; X<int*> x(42); // RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:32:11 %s -o - | FileCheck -check-prefix=CHECK-CONSTRUCTOR %s // CHECK-CONSTRUCTOR: OVERLOAD: X(<#double#>) // (rather than X<type-parameter-0-0 *>(<#double#>)
endlessm/chromium-browser
third_party/llvm/clang/test/CodeCompletion/templates.cpp
C++
bsd-3-clause
1,042