file_name
int64
0
72.3k
vulnerable_line_numbers
stringlengths
1
1.06k
dataset_type
stringclasses
1 value
commit_hash
stringlengths
40
44
unique_id
int64
0
271k
project
stringclasses
10 values
target
int64
0
1
repo_url
stringclasses
10 values
date
stringlengths
25
25
code
stringlengths
0
20.4M
CVE
stringlengths
13
43
CWE
stringclasses
50 values
commit_link
stringlengths
73
97
severity
stringclasses
4 values
__index_level_0__
int64
0
124k
32,668
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
32,668
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
/* * Copyright (C) 2004, 2005 Nikolas Zimmermann <zimmermann@kde.org> * Copyright (C) 2004, 2005, 2006, 2007 Rob Buis <buis@kde.org> * Copyright (C) 2007 Eric Seidel <eric@webkit.org> * Copyright (C) 2008 Apple Inc. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef THIRD_PARTY_BLINK_RENDERER_CORE_SVG_SVG_ANIMATE_TRANSFORM_ELEMENT_H_ #define THIRD_PARTY_BLINK_RENDERER_CORE_SVG_SVG_ANIMATE_TRANSFORM_ELEMENT_H_ #include "third_party/blink/renderer/core/svg/svg_animate_element.h" #include "third_party/blink/renderer/core/svg/svg_transform.h" namespace blink { class SVGAnimateTransformElement final : public SVGAnimateElement { DEFINE_WRAPPERTYPEINFO(); public: DECLARE_NODE_FACTORY(SVGAnimateTransformElement); private: explicit SVGAnimateTransformElement(Document&); bool HasValidTarget() override; void ParseAttribute(const AttributeModificationParams&) override; void ResolveTargetProperty() override; SVGPropertyBase* CreatePropertyForAnimation(const String&) const override; SVGTransformType transform_type_; }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_CORE_SVG_SVG_ANIMATE_TRANSFORM_ELEMENT_H_
null
null
null
null
29,531
70,260
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
70,260
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// 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 "device/usb/usb_ids.h" #include <stdlib.h> namespace device { namespace { static int CompareVendors(const void* a, const void* b) { const UsbVendor* vendor_a = static_cast<const UsbVendor*>(a); const UsbVendor* vendor_b = static_cast<const UsbVendor*>(b); return vendor_a->id - vendor_b->id; } static int CompareProducts(const void* a, const void* b) { const UsbProduct* product_a = static_cast<const UsbProduct*>(a); const UsbProduct* product_b = static_cast<const UsbProduct*>(b); return product_a->id - product_b->id; } } // namespace const UsbVendor* UsbIds::FindVendor(uint16_t vendor_id) { const UsbVendor key = {vendor_id, NULL, 0, NULL}; void* result = bsearch(&key, vendors_, vendor_size_, sizeof(vendors_[0]), &CompareVendors); if (!result) return NULL; return static_cast<const UsbVendor*>(result); } const char* UsbIds::GetVendorName(uint16_t vendor_id) { const UsbVendor* vendor = FindVendor(vendor_id); if (!vendor) return NULL; return vendor->name; } const char* UsbIds::GetProductName(uint16_t vendor_id, uint16_t product_id) { const UsbVendor* vendor = FindVendor(vendor_id); if (!vendor) return NULL; const UsbProduct key = {product_id, NULL}; void* result = bsearch(&key, vendor->products, vendor->product_size, sizeof(vendor->products[0]), &CompareProducts); if (!result) return NULL; return static_cast<const UsbProduct*>(result)->name; } } // namespace device
null
null
null
null
67,123
27,329
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
27,329
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
/*********************************************************************** Copyright (c) 2006-2011, Skype Limited. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of Internet Society, IETF or IETF Trust, nor the names of specific contributors, may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ***********************************************************************/ #ifdef HAVE_CONFIG_H #include "config.h" #endif /***************************************************************************** * Pitch analyser function ******************************************************************************/ #include "SigProc_FLP.h" #include "SigProc_FIX.h" #include "pitch_est_defines.h" #include "pitch.h" #define SCRATCH_SIZE 22 /************************************************************/ /* Internally used functions */ /************************************************************/ static void silk_P_Ana_calc_corr_st3( silk_float cross_corr_st3[ PE_MAX_NB_SUBFR ][ PE_NB_CBKS_STAGE3_MAX ][ PE_NB_STAGE3_LAGS ], /* O 3 DIM correlation array */ const silk_float frame[], /* I vector to correlate */ opus_int start_lag, /* I start lag */ opus_int sf_length, /* I sub frame length */ opus_int nb_subfr, /* I number of subframes */ opus_int complexity, /* I Complexity setting */ int arch /* I Run-time architecture */ ); static void silk_P_Ana_calc_energy_st3( silk_float energies_st3[ PE_MAX_NB_SUBFR ][ PE_NB_CBKS_STAGE3_MAX ][ PE_NB_STAGE3_LAGS ], /* O 3 DIM correlation array */ const silk_float frame[], /* I vector to correlate */ opus_int start_lag, /* I start lag */ opus_int sf_length, /* I sub frame length */ opus_int nb_subfr, /* I number of subframes */ opus_int complexity /* I Complexity setting */ ); /************************************************************/ /* CORE PITCH ANALYSIS FUNCTION */ /************************************************************/ opus_int silk_pitch_analysis_core_FLP( /* O Voicing estimate: 0 voiced, 1 unvoiced */ const silk_float *frame, /* I Signal of length PE_FRAME_LENGTH_MS*Fs_kHz */ opus_int *pitch_out, /* O Pitch lag values [nb_subfr] */ opus_int16 *lagIndex, /* O Lag Index */ opus_int8 *contourIndex, /* O Pitch contour Index */ silk_float *LTPCorr, /* I/O Normalized correlation; input: value from previous frame */ opus_int prevLag, /* I Last lag of previous frame; set to zero is unvoiced */ const silk_float search_thres1, /* I First stage threshold for lag candidates 0 - 1 */ const silk_float search_thres2, /* I Final threshold for lag candidates 0 - 1 */ const opus_int Fs_kHz, /* I sample frequency (kHz) */ const opus_int complexity, /* I Complexity setting, 0-2, where 2 is highest */ const opus_int nb_subfr, /* I Number of 5 ms subframes */ int arch /* I Run-time architecture */ ) { opus_int i, k, d, j; silk_float frame_8kHz[ PE_MAX_FRAME_LENGTH_MS * 8 ]; silk_float frame_4kHz[ PE_MAX_FRAME_LENGTH_MS * 4 ]; opus_int16 frame_8_FIX[ PE_MAX_FRAME_LENGTH_MS * 8 ]; opus_int16 frame_4_FIX[ PE_MAX_FRAME_LENGTH_MS * 4 ]; opus_int32 filt_state[ 6 ]; silk_float threshold, contour_bias; silk_float C[ PE_MAX_NB_SUBFR][ (PE_MAX_LAG >> 1) + 5 ]; opus_val32 xcorr[ PE_MAX_LAG_MS * 4 - PE_MIN_LAG_MS * 4 + 1 ]; silk_float CC[ PE_NB_CBKS_STAGE2_EXT ]; const silk_float *target_ptr, *basis_ptr; double cross_corr, normalizer, energy, energy_tmp; opus_int d_srch[ PE_D_SRCH_LENGTH ]; opus_int16 d_comp[ (PE_MAX_LAG >> 1) + 5 ]; opus_int length_d_srch, length_d_comp; silk_float Cmax, CCmax, CCmax_b, CCmax_new_b, CCmax_new; opus_int CBimax, CBimax_new, lag, start_lag, end_lag, lag_new; opus_int cbk_size; silk_float lag_log2, prevLag_log2, delta_lag_log2_sqr; silk_float energies_st3[ PE_MAX_NB_SUBFR ][ PE_NB_CBKS_STAGE3_MAX ][ PE_NB_STAGE3_LAGS ]; silk_float cross_corr_st3[ PE_MAX_NB_SUBFR ][ PE_NB_CBKS_STAGE3_MAX ][ PE_NB_STAGE3_LAGS ]; opus_int lag_counter; opus_int frame_length, frame_length_8kHz, frame_length_4kHz; opus_int sf_length, sf_length_8kHz, sf_length_4kHz; opus_int min_lag, min_lag_8kHz, min_lag_4kHz; opus_int max_lag, max_lag_8kHz, max_lag_4kHz; opus_int nb_cbk_search; const opus_int8 *Lag_CB_ptr; /* Check for valid sampling frequency */ silk_assert( Fs_kHz == 8 || Fs_kHz == 12 || Fs_kHz == 16 ); /* Check for valid complexity setting */ silk_assert( complexity >= SILK_PE_MIN_COMPLEX ); silk_assert( complexity <= SILK_PE_MAX_COMPLEX ); silk_assert( search_thres1 >= 0.0f && search_thres1 <= 1.0f ); silk_assert( search_thres2 >= 0.0f && search_thres2 <= 1.0f ); /* Set up frame lengths max / min lag for the sampling frequency */ frame_length = ( PE_LTP_MEM_LENGTH_MS + nb_subfr * PE_SUBFR_LENGTH_MS ) * Fs_kHz; frame_length_4kHz = ( PE_LTP_MEM_LENGTH_MS + nb_subfr * PE_SUBFR_LENGTH_MS ) * 4; frame_length_8kHz = ( PE_LTP_MEM_LENGTH_MS + nb_subfr * PE_SUBFR_LENGTH_MS ) * 8; sf_length = PE_SUBFR_LENGTH_MS * Fs_kHz; sf_length_4kHz = PE_SUBFR_LENGTH_MS * 4; sf_length_8kHz = PE_SUBFR_LENGTH_MS * 8; min_lag = PE_MIN_LAG_MS * Fs_kHz; min_lag_4kHz = PE_MIN_LAG_MS * 4; min_lag_8kHz = PE_MIN_LAG_MS * 8; max_lag = PE_MAX_LAG_MS * Fs_kHz - 1; max_lag_4kHz = PE_MAX_LAG_MS * 4; max_lag_8kHz = PE_MAX_LAG_MS * 8 - 1; /* Resample from input sampled at Fs_kHz to 8 kHz */ if( Fs_kHz == 16 ) { /* Resample to 16 -> 8 khz */ opus_int16 frame_16_FIX[ 16 * PE_MAX_FRAME_LENGTH_MS ]; silk_float2short_array( frame_16_FIX, frame, frame_length ); silk_memset( filt_state, 0, 2 * sizeof( opus_int32 ) ); silk_resampler_down2( filt_state, frame_8_FIX, frame_16_FIX, frame_length ); silk_short2float_array( frame_8kHz, frame_8_FIX, frame_length_8kHz ); } else if( Fs_kHz == 12 ) { /* Resample to 12 -> 8 khz */ opus_int16 frame_12_FIX[ 12 * PE_MAX_FRAME_LENGTH_MS ]; silk_float2short_array( frame_12_FIX, frame, frame_length ); silk_memset( filt_state, 0, 6 * sizeof( opus_int32 ) ); silk_resampler_down2_3( filt_state, frame_8_FIX, frame_12_FIX, frame_length ); silk_short2float_array( frame_8kHz, frame_8_FIX, frame_length_8kHz ); } else { silk_assert( Fs_kHz == 8 ); silk_float2short_array( frame_8_FIX, frame, frame_length_8kHz ); } /* Decimate again to 4 kHz */ silk_memset( filt_state, 0, 2 * sizeof( opus_int32 ) ); silk_resampler_down2( filt_state, frame_4_FIX, frame_8_FIX, frame_length_8kHz ); silk_short2float_array( frame_4kHz, frame_4_FIX, frame_length_4kHz ); /* Low-pass filter */ for( i = frame_length_4kHz - 1; i > 0; i-- ) { frame_4kHz[ i ] = silk_ADD_SAT16( frame_4kHz[ i ], frame_4kHz[ i - 1 ] ); } /****************************************************************************** * FIRST STAGE, operating in 4 khz ******************************************************************************/ silk_memset(C, 0, sizeof(silk_float) * nb_subfr * ((PE_MAX_LAG >> 1) + 5)); target_ptr = &frame_4kHz[ silk_LSHIFT( sf_length_4kHz, 2 ) ]; for( k = 0; k < nb_subfr >> 1; k++ ) { /* Check that we are within range of the array */ silk_assert( target_ptr >= frame_4kHz ); silk_assert( target_ptr + sf_length_8kHz <= frame_4kHz + frame_length_4kHz ); basis_ptr = target_ptr - min_lag_4kHz; /* Check that we are within range of the array */ silk_assert( basis_ptr >= frame_4kHz ); silk_assert( basis_ptr + sf_length_8kHz <= frame_4kHz + frame_length_4kHz ); celt_pitch_xcorr( target_ptr, target_ptr-max_lag_4kHz, xcorr, sf_length_8kHz, max_lag_4kHz - min_lag_4kHz + 1, arch ); /* Calculate first vector products before loop */ cross_corr = xcorr[ max_lag_4kHz - min_lag_4kHz ]; normalizer = silk_energy_FLP( target_ptr, sf_length_8kHz ) + silk_energy_FLP( basis_ptr, sf_length_8kHz ) + sf_length_8kHz * 4000.0f; C[ 0 ][ min_lag_4kHz ] += (silk_float)( 2 * cross_corr / normalizer ); /* From now on normalizer is computed recursively */ for( d = min_lag_4kHz + 1; d <= max_lag_4kHz; d++ ) { basis_ptr--; /* Check that we are within range of the array */ silk_assert( basis_ptr >= frame_4kHz ); silk_assert( basis_ptr + sf_length_8kHz <= frame_4kHz + frame_length_4kHz ); cross_corr = xcorr[ max_lag_4kHz - d ]; /* Add contribution of new sample and remove contribution from oldest sample */ normalizer += basis_ptr[ 0 ] * (double)basis_ptr[ 0 ] - basis_ptr[ sf_length_8kHz ] * (double)basis_ptr[ sf_length_8kHz ]; C[ 0 ][ d ] += (silk_float)( 2 * cross_corr / normalizer ); } /* Update target pointer */ target_ptr += sf_length_8kHz; } /* Apply short-lag bias */ for( i = max_lag_4kHz; i >= min_lag_4kHz; i-- ) { C[ 0 ][ i ] -= C[ 0 ][ i ] * i / 4096.0f; } /* Sort */ length_d_srch = 4 + 2 * complexity; silk_assert( 3 * length_d_srch <= PE_D_SRCH_LENGTH ); silk_insertion_sort_decreasing_FLP( &C[ 0 ][ min_lag_4kHz ], d_srch, max_lag_4kHz - min_lag_4kHz + 1, length_d_srch ); /* Escape if correlation is very low already here */ Cmax = C[ 0 ][ min_lag_4kHz ]; if( Cmax < 0.2f ) { silk_memset( pitch_out, 0, nb_subfr * sizeof( opus_int ) ); *LTPCorr = 0.0f; *lagIndex = 0; *contourIndex = 0; return 1; } threshold = search_thres1 * Cmax; for( i = 0; i < length_d_srch; i++ ) { /* Convert to 8 kHz indices for the sorted correlation that exceeds the threshold */ if( C[ 0 ][ min_lag_4kHz + i ] > threshold ) { d_srch[ i ] = silk_LSHIFT( d_srch[ i ] + min_lag_4kHz, 1 ); } else { length_d_srch = i; break; } } silk_assert( length_d_srch > 0 ); for( i = min_lag_8kHz - 5; i < max_lag_8kHz + 5; i++ ) { d_comp[ i ] = 0; } for( i = 0; i < length_d_srch; i++ ) { d_comp[ d_srch[ i ] ] = 1; } /* Convolution */ for( i = max_lag_8kHz + 3; i >= min_lag_8kHz; i-- ) { d_comp[ i ] += d_comp[ i - 1 ] + d_comp[ i - 2 ]; } length_d_srch = 0; for( i = min_lag_8kHz; i < max_lag_8kHz + 1; i++ ) { if( d_comp[ i + 1 ] > 0 ) { d_srch[ length_d_srch ] = i; length_d_srch++; } } /* Convolution */ for( i = max_lag_8kHz + 3; i >= min_lag_8kHz; i-- ) { d_comp[ i ] += d_comp[ i - 1 ] + d_comp[ i - 2 ] + d_comp[ i - 3 ]; } length_d_comp = 0; for( i = min_lag_8kHz; i < max_lag_8kHz + 4; i++ ) { if( d_comp[ i ] > 0 ) { d_comp[ length_d_comp ] = (opus_int16)( i - 2 ); length_d_comp++; } } /********************************************************************************** ** SECOND STAGE, operating at 8 kHz, on lag sections with high correlation *************************************************************************************/ /********************************************************************************* * Find energy of each subframe projected onto its history, for a range of delays *********************************************************************************/ silk_memset( C, 0, PE_MAX_NB_SUBFR*((PE_MAX_LAG >> 1) + 5) * sizeof(silk_float)); if( Fs_kHz == 8 ) { target_ptr = &frame[ PE_LTP_MEM_LENGTH_MS * 8 ]; } else { target_ptr = &frame_8kHz[ PE_LTP_MEM_LENGTH_MS * 8 ]; } for( k = 0; k < nb_subfr; k++ ) { energy_tmp = silk_energy_FLP( target_ptr, sf_length_8kHz ) + 1.0; for( j = 0; j < length_d_comp; j++ ) { d = d_comp[ j ]; basis_ptr = target_ptr - d; cross_corr = silk_inner_product_FLP( basis_ptr, target_ptr, sf_length_8kHz ); if( cross_corr > 0.0f ) { energy = silk_energy_FLP( basis_ptr, sf_length_8kHz ); C[ k ][ d ] = (silk_float)( 2 * cross_corr / ( energy + energy_tmp ) ); } else { C[ k ][ d ] = 0.0f; } } target_ptr += sf_length_8kHz; } /* search over lag range and lags codebook */ /* scale factor for lag codebook, as a function of center lag */ CCmax = 0.0f; /* This value doesn't matter */ CCmax_b = -1000.0f; CBimax = 0; /* To avoid returning undefined lag values */ lag = -1; /* To check if lag with strong enough correlation has been found */ if( prevLag > 0 ) { if( Fs_kHz == 12 ) { prevLag = silk_LSHIFT( prevLag, 1 ) / 3; } else if( Fs_kHz == 16 ) { prevLag = silk_RSHIFT( prevLag, 1 ); } prevLag_log2 = silk_log2( (silk_float)prevLag ); } else { prevLag_log2 = 0; } /* Set up stage 2 codebook based on number of subframes */ if( nb_subfr == PE_MAX_NB_SUBFR ) { cbk_size = PE_NB_CBKS_STAGE2_EXT; Lag_CB_ptr = &silk_CB_lags_stage2[ 0 ][ 0 ]; if( Fs_kHz == 8 && complexity > SILK_PE_MIN_COMPLEX ) { /* If input is 8 khz use a larger codebook here because it is last stage */ nb_cbk_search = PE_NB_CBKS_STAGE2_EXT; } else { nb_cbk_search = PE_NB_CBKS_STAGE2; } } else { cbk_size = PE_NB_CBKS_STAGE2_10MS; Lag_CB_ptr = &silk_CB_lags_stage2_10_ms[ 0 ][ 0 ]; nb_cbk_search = PE_NB_CBKS_STAGE2_10MS; } for( k = 0; k < length_d_srch; k++ ) { d = d_srch[ k ]; for( j = 0; j < nb_cbk_search; j++ ) { CC[j] = 0.0f; for( i = 0; i < nb_subfr; i++ ) { /* Try all codebooks */ CC[ j ] += C[ i ][ d + matrix_ptr( Lag_CB_ptr, i, j, cbk_size )]; } } /* Find best codebook */ CCmax_new = -1000.0f; CBimax_new = 0; for( i = 0; i < nb_cbk_search; i++ ) { if( CC[ i ] > CCmax_new ) { CCmax_new = CC[ i ]; CBimax_new = i; } } /* Bias towards shorter lags */ lag_log2 = silk_log2( (silk_float)d ); CCmax_new_b = CCmax_new - PE_SHORTLAG_BIAS * nb_subfr * lag_log2; /* Bias towards previous lag */ if( prevLag > 0 ) { delta_lag_log2_sqr = lag_log2 - prevLag_log2; delta_lag_log2_sqr *= delta_lag_log2_sqr; CCmax_new_b -= PE_PREVLAG_BIAS * nb_subfr * (*LTPCorr) * delta_lag_log2_sqr / ( delta_lag_log2_sqr + 0.5f ); } if( CCmax_new_b > CCmax_b && /* Find maximum biased correlation */ CCmax_new > nb_subfr * search_thres2 /* Correlation needs to be high enough to be voiced */ ) { CCmax_b = CCmax_new_b; CCmax = CCmax_new; lag = d; CBimax = CBimax_new; } } if( lag == -1 ) { /* No suitable candidate found */ silk_memset( pitch_out, 0, PE_MAX_NB_SUBFR * sizeof(opus_int) ); *LTPCorr = 0.0f; *lagIndex = 0; *contourIndex = 0; return 1; } /* Output normalized correlation */ *LTPCorr = (silk_float)( CCmax / nb_subfr ); silk_assert( *LTPCorr >= 0.0f ); if( Fs_kHz > 8 ) { /* Search in original signal */ /* Compensate for decimation */ silk_assert( lag == silk_SAT16( lag ) ); if( Fs_kHz == 12 ) { lag = silk_RSHIFT_ROUND( silk_SMULBB( lag, 3 ), 1 ); } else { /* Fs_kHz == 16 */ lag = silk_LSHIFT( lag, 1 ); } lag = silk_LIMIT_int( lag, min_lag, max_lag ); start_lag = silk_max_int( lag - 2, min_lag ); end_lag = silk_min_int( lag + 2, max_lag ); lag_new = lag; /* to avoid undefined lag */ CBimax = 0; /* to avoid undefined lag */ CCmax = -1000.0f; /* Calculate the correlations and energies needed in stage 3 */ silk_P_Ana_calc_corr_st3( cross_corr_st3, frame, start_lag, sf_length, nb_subfr, complexity, arch ); silk_P_Ana_calc_energy_st3( energies_st3, frame, start_lag, sf_length, nb_subfr, complexity ); lag_counter = 0; silk_assert( lag == silk_SAT16( lag ) ); contour_bias = PE_FLATCONTOUR_BIAS / lag; /* Set up cbk parameters according to complexity setting and frame length */ if( nb_subfr == PE_MAX_NB_SUBFR ) { nb_cbk_search = (opus_int)silk_nb_cbk_searchs_stage3[ complexity ]; cbk_size = PE_NB_CBKS_STAGE3_MAX; Lag_CB_ptr = &silk_CB_lags_stage3[ 0 ][ 0 ]; } else { nb_cbk_search = PE_NB_CBKS_STAGE3_10MS; cbk_size = PE_NB_CBKS_STAGE3_10MS; Lag_CB_ptr = &silk_CB_lags_stage3_10_ms[ 0 ][ 0 ]; } target_ptr = &frame[ PE_LTP_MEM_LENGTH_MS * Fs_kHz ]; energy_tmp = silk_energy_FLP( target_ptr, nb_subfr * sf_length ) + 1.0; for( d = start_lag; d <= end_lag; d++ ) { for( j = 0; j < nb_cbk_search; j++ ) { cross_corr = 0.0; energy = energy_tmp; for( k = 0; k < nb_subfr; k++ ) { cross_corr += cross_corr_st3[ k ][ j ][ lag_counter ]; energy += energies_st3[ k ][ j ][ lag_counter ]; } if( cross_corr > 0.0 ) { CCmax_new = (silk_float)( 2 * cross_corr / energy ); /* Reduce depending on flatness of contour */ CCmax_new *= 1.0f - contour_bias * j; } else { CCmax_new = 0.0f; } if( CCmax_new > CCmax && ( d + (opus_int)silk_CB_lags_stage3[ 0 ][ j ] ) <= max_lag ) { CCmax = CCmax_new; lag_new = d; CBimax = j; } } lag_counter++; } for( k = 0; k < nb_subfr; k++ ) { pitch_out[ k ] = lag_new + matrix_ptr( Lag_CB_ptr, k, CBimax, cbk_size ); pitch_out[ k ] = silk_LIMIT( pitch_out[ k ], min_lag, PE_MAX_LAG_MS * Fs_kHz ); } *lagIndex = (opus_int16)( lag_new - min_lag ); *contourIndex = (opus_int8)CBimax; } else { /* Fs_kHz == 8 */ /* Save Lags */ for( k = 0; k < nb_subfr; k++ ) { pitch_out[ k ] = lag + matrix_ptr( Lag_CB_ptr, k, CBimax, cbk_size ); pitch_out[ k ] = silk_LIMIT( pitch_out[ k ], min_lag_8kHz, PE_MAX_LAG_MS * 8 ); } *lagIndex = (opus_int16)( lag - min_lag_8kHz ); *contourIndex = (opus_int8)CBimax; } silk_assert( *lagIndex >= 0 ); /* return as voiced */ return 0; } /*********************************************************************** * Calculates the correlations used in stage 3 search. In order to cover * the whole lag codebook for all the searched offset lags (lag +- 2), * the following correlations are needed in each sub frame: * * sf1: lag range [-8,...,7] total 16 correlations * sf2: lag range [-4,...,4] total 9 correlations * sf3: lag range [-3,....4] total 8 correltions * sf4: lag range [-6,....8] total 15 correlations * * In total 48 correlations. The direct implementation computed in worst * case 4*12*5 = 240 correlations, but more likely around 120. ***********************************************************************/ static void silk_P_Ana_calc_corr_st3( silk_float cross_corr_st3[ PE_MAX_NB_SUBFR ][ PE_NB_CBKS_STAGE3_MAX ][ PE_NB_STAGE3_LAGS ], /* O 3 DIM correlation array */ const silk_float frame[], /* I vector to correlate */ opus_int start_lag, /* I start lag */ opus_int sf_length, /* I sub frame length */ opus_int nb_subfr, /* I number of subframes */ opus_int complexity, /* I Complexity setting */ int arch /* I Run-time architecture */ ) { const silk_float *target_ptr; opus_int i, j, k, lag_counter, lag_low, lag_high; opus_int nb_cbk_search, delta, idx, cbk_size; silk_float scratch_mem[ SCRATCH_SIZE ]; opus_val32 xcorr[ SCRATCH_SIZE ]; const opus_int8 *Lag_range_ptr, *Lag_CB_ptr; silk_assert( complexity >= SILK_PE_MIN_COMPLEX ); silk_assert( complexity <= SILK_PE_MAX_COMPLEX ); if( nb_subfr == PE_MAX_NB_SUBFR ) { Lag_range_ptr = &silk_Lag_range_stage3[ complexity ][ 0 ][ 0 ]; Lag_CB_ptr = &silk_CB_lags_stage3[ 0 ][ 0 ]; nb_cbk_search = silk_nb_cbk_searchs_stage3[ complexity ]; cbk_size = PE_NB_CBKS_STAGE3_MAX; } else { silk_assert( nb_subfr == PE_MAX_NB_SUBFR >> 1); Lag_range_ptr = &silk_Lag_range_stage3_10_ms[ 0 ][ 0 ]; Lag_CB_ptr = &silk_CB_lags_stage3_10_ms[ 0 ][ 0 ]; nb_cbk_search = PE_NB_CBKS_STAGE3_10MS; cbk_size = PE_NB_CBKS_STAGE3_10MS; } target_ptr = &frame[ silk_LSHIFT( sf_length, 2 ) ]; /* Pointer to middle of frame */ for( k = 0; k < nb_subfr; k++ ) { lag_counter = 0; /* Calculate the correlations for each subframe */ lag_low = matrix_ptr( Lag_range_ptr, k, 0, 2 ); lag_high = matrix_ptr( Lag_range_ptr, k, 1, 2 ); silk_assert(lag_high-lag_low+1 <= SCRATCH_SIZE); celt_pitch_xcorr( target_ptr, target_ptr - start_lag - lag_high, xcorr, sf_length, lag_high - lag_low + 1, arch ); for( j = lag_low; j <= lag_high; j++ ) { silk_assert( lag_counter < SCRATCH_SIZE ); scratch_mem[ lag_counter ] = xcorr[ lag_high - j ]; lag_counter++; } delta = matrix_ptr( Lag_range_ptr, k, 0, 2 ); for( i = 0; i < nb_cbk_search; i++ ) { /* Fill out the 3 dim array that stores the correlations for */ /* each code_book vector for each start lag */ idx = matrix_ptr( Lag_CB_ptr, k, i, cbk_size ) - delta; for( j = 0; j < PE_NB_STAGE3_LAGS; j++ ) { silk_assert( idx + j < SCRATCH_SIZE ); silk_assert( idx + j < lag_counter ); cross_corr_st3[ k ][ i ][ j ] = scratch_mem[ idx + j ]; } } target_ptr += sf_length; } } /********************************************************************/ /* Calculate the energies for first two subframes. The energies are */ /* calculated recursively. */ /********************************************************************/ static void silk_P_Ana_calc_energy_st3( silk_float energies_st3[ PE_MAX_NB_SUBFR ][ PE_NB_CBKS_STAGE3_MAX ][ PE_NB_STAGE3_LAGS ], /* O 3 DIM correlation array */ const silk_float frame[], /* I vector to correlate */ opus_int start_lag, /* I start lag */ opus_int sf_length, /* I sub frame length */ opus_int nb_subfr, /* I number of subframes */ opus_int complexity /* I Complexity setting */ ) { const silk_float *target_ptr, *basis_ptr; double energy; opus_int k, i, j, lag_counter; opus_int nb_cbk_search, delta, idx, cbk_size, lag_diff; silk_float scratch_mem[ SCRATCH_SIZE ]; const opus_int8 *Lag_range_ptr, *Lag_CB_ptr; silk_assert( complexity >= SILK_PE_MIN_COMPLEX ); silk_assert( complexity <= SILK_PE_MAX_COMPLEX ); if( nb_subfr == PE_MAX_NB_SUBFR ) { Lag_range_ptr = &silk_Lag_range_stage3[ complexity ][ 0 ][ 0 ]; Lag_CB_ptr = &silk_CB_lags_stage3[ 0 ][ 0 ]; nb_cbk_search = silk_nb_cbk_searchs_stage3[ complexity ]; cbk_size = PE_NB_CBKS_STAGE3_MAX; } else { silk_assert( nb_subfr == PE_MAX_NB_SUBFR >> 1); Lag_range_ptr = &silk_Lag_range_stage3_10_ms[ 0 ][ 0 ]; Lag_CB_ptr = &silk_CB_lags_stage3_10_ms[ 0 ][ 0 ]; nb_cbk_search = PE_NB_CBKS_STAGE3_10MS; cbk_size = PE_NB_CBKS_STAGE3_10MS; } target_ptr = &frame[ silk_LSHIFT( sf_length, 2 ) ]; for( k = 0; k < nb_subfr; k++ ) { lag_counter = 0; /* Calculate the energy for first lag */ basis_ptr = target_ptr - ( start_lag + matrix_ptr( Lag_range_ptr, k, 0, 2 ) ); energy = silk_energy_FLP( basis_ptr, sf_length ) + 1e-3; silk_assert( energy >= 0.0 ); scratch_mem[lag_counter] = (silk_float)energy; lag_counter++; lag_diff = ( matrix_ptr( Lag_range_ptr, k, 1, 2 ) - matrix_ptr( Lag_range_ptr, k, 0, 2 ) + 1 ); for( i = 1; i < lag_diff; i++ ) { /* remove part outside new window */ energy -= basis_ptr[sf_length - i] * (double)basis_ptr[sf_length - i]; silk_assert( energy >= 0.0 ); /* add part that comes into window */ energy += basis_ptr[ -i ] * (double)basis_ptr[ -i ]; silk_assert( energy >= 0.0 ); silk_assert( lag_counter < SCRATCH_SIZE ); scratch_mem[lag_counter] = (silk_float)energy; lag_counter++; } delta = matrix_ptr( Lag_range_ptr, k, 0, 2 ); for( i = 0; i < nb_cbk_search; i++ ) { /* Fill out the 3 dim array that stores the correlations for */ /* each code_book vector for each start lag */ idx = matrix_ptr( Lag_CB_ptr, k, i, cbk_size ) - delta; for( j = 0; j < PE_NB_STAGE3_LAGS; j++ ) { silk_assert( idx + j < SCRATCH_SIZE ); silk_assert( idx + j < lag_counter ); energies_st3[ k ][ i ][ j ] = scratch_mem[ idx + j ]; silk_assert( energies_st3[ k ][ i ][ j ] >= 0.0f ); } } target_ptr += sf_length; } }
null
null
null
null
24,192
2,843
null
train_val
04b570817b2b38e35675b17328239746212f4c3f
155,900
FFmpeg
0
https://github.com/FFmpeg/FFmpeg
2018-06-01 01:23:12+05:30
/* * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVRESAMPLE_VERSION_H #define AVRESAMPLE_VERSION_H /** * @file * @ingroup lavr * Libavresample version macros. */ #include "libavutil/version.h" #define LIBAVRESAMPLE_VERSION_MAJOR 4 #define LIBAVRESAMPLE_VERSION_MINOR 0 #define LIBAVRESAMPLE_VERSION_MICRO 0 #define LIBAVRESAMPLE_VERSION_INT AV_VERSION_INT(LIBAVRESAMPLE_VERSION_MAJOR, \ LIBAVRESAMPLE_VERSION_MINOR, \ LIBAVRESAMPLE_VERSION_MICRO) #define LIBAVRESAMPLE_VERSION AV_VERSION(LIBAVRESAMPLE_VERSION_MAJOR, \ LIBAVRESAMPLE_VERSION_MINOR, \ LIBAVRESAMPLE_VERSION_MICRO) #define LIBAVRESAMPLE_BUILD LIBAVRESAMPLE_VERSION_INT #define LIBAVRESAMPLE_IDENT "Lavr" AV_STRINGIFY(LIBAVRESAMPLE_VERSION) /** * FF_API_* defines may be placed below to indicate public API that will be * dropped at a future version bump. The defines themselves are not part of * the public API and may change, break or disappear at any time. */ #endif /* AVRESAMPLE_VERSION_H */
null
null
null
null
71,955
36,394
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
36,394
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright 2016 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 "third_party/blink/public/platform/web_mouse_event.h" #include "third_party/blink/public/platform/web_gesture_event.h" namespace blink { WebMouseEvent::WebMouseEvent(WebInputEvent::Type type, const WebGestureEvent& gesture_event, Button button_param, int click_count_param, int modifiers, double time_stamp_seconds, PointerId id_param) : WebInputEvent(sizeof(WebMouseEvent), type, modifiers, time_stamp_seconds), WebPointerProperties(id_param, WebPointerProperties::PointerType::kMouse, button_param), click_count(click_count_param) { DCHECK_GE(type, kMouseTypeFirst); DCHECK_LE(type, kMouseTypeLast); SetPositionInWidget(gesture_event.PositionInWidget()); SetPositionInScreen(gesture_event.PositionInScreen()); SetFrameScale(gesture_event.FrameScale()); SetFrameTranslate(gesture_event.FrameTranslate()); SetMenuSourceType(gesture_event.GetType()); } WebFloatPoint WebMouseEvent::MovementInRootFrame() const { return WebFloatPoint((movement_x / frame_scale_), (movement_y / frame_scale_)); } WebFloatPoint WebMouseEvent::PositionInRootFrame() const { return WebFloatPoint( (position_in_widget_.x / frame_scale_) + frame_translate_.x, (position_in_widget_.y / frame_scale_) + frame_translate_.y); } WebMouseEvent WebMouseEvent::FlattenTransform() const { WebMouseEvent result = *this; result.FlattenTransformSelf(); return result; } void WebMouseEvent::FlattenTransformSelf() { position_in_widget_ = PositionInRootFrame(); frame_translate_.x = 0; frame_translate_.y = 0; frame_scale_ = 1; } void WebMouseEvent::SetMenuSourceType(WebInputEvent::Type type) { switch (type) { case kGestureTapDown: case kGestureTap: case kGestureDoubleTap: menu_source_type = kMenuSourceTouch; break; case kGestureLongPress: menu_source_type = kMenuSourceLongPress; break; case kGestureLongTap: menu_source_type = kMenuSourceLongTap; break; default: menu_source_type = kMenuSourceNone; } } } // namespace blink
null
null
null
null
33,257
2,261
44,46
train_val
01c9a7e71ca435651723e8cbcab0b3ad4c5351e2
2,261
Chrome
1
https://github.com/chromium/chromium
2017-11-09 01:56:02+00:00
bool PDFiumEngine::HandleEvent(const pp::InputEvent& event) { DCHECK(!defer_page_unload_); defer_page_unload_ = true; bool rv = false; switch (event.GetType()) { case PP_INPUTEVENT_TYPE_MOUSEDOWN: rv = OnMouseDown(pp::MouseInputEvent(event)); break; case PP_INPUTEVENT_TYPE_MOUSEUP: rv = OnMouseUp(pp::MouseInputEvent(event)); break; case PP_INPUTEVENT_TYPE_MOUSEMOVE: rv = OnMouseMove(pp::MouseInputEvent(event)); break; case PP_INPUTEVENT_TYPE_KEYDOWN: rv = OnKeyDown(pp::KeyboardInputEvent(event)); break; case PP_INPUTEVENT_TYPE_KEYUP: rv = OnKeyUp(pp::KeyboardInputEvent(event)); break; case PP_INPUTEVENT_TYPE_CHAR: rv = OnChar(pp::KeyboardInputEvent(event)); break; case PP_INPUTEVENT_TYPE_TOUCHSTART: { KillTouchTimer(next_touch_timer_id_); pp::TouchInputEvent touch_event(event); if (touch_event.GetTouchCount(PP_TOUCHLIST_TYPE_TARGETTOUCHES) == 1) ScheduleTouchTimer(touch_event); break; } case PP_INPUTEVENT_TYPE_TOUCHEND: KillTouchTimer(next_touch_timer_id_); break; case PP_INPUTEVENT_TYPE_TOUCHMOVE: // TODO(dsinclair): This should allow a little bit of movement (up to the // touch radii) to account for finger jiggle. KillTouchTimer(next_touch_timer_id_); default: break; } DCHECK(defer_page_unload_); defer_page_unload_ = false; for (int page_index : deferred_page_unloads_) pages_[page_index]->Unload(); deferred_page_unloads_.clear(); return rv; }
CVE-2018-6031
CWE-416
https://github.com/chromium/chromium/commit/01c9a7e71ca435651723e8cbcab0b3ad4c5351e2
Medium
2,261
31,028
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
196,023
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * SH7720 Pinmux * * Copyright (C) 2008 Magnus Damm * * This file is subject to the terms and conditions of the GNU General Public * License. See the file "COPYING" in the main directory of this archive * for more details. */ #include <linux/kernel.h> #include <linux/gpio.h> #include <cpu/sh7720.h> #include "sh_pfc.h" enum { PINMUX_RESERVED = 0, PINMUX_DATA_BEGIN, PTA7_DATA, PTA6_DATA, PTA5_DATA, PTA4_DATA, PTA3_DATA, PTA2_DATA, PTA1_DATA, PTA0_DATA, PTB7_DATA, PTB6_DATA, PTB5_DATA, PTB4_DATA, PTB3_DATA, PTB2_DATA, PTB1_DATA, PTB0_DATA, PTC7_DATA, PTC6_DATA, PTC5_DATA, PTC4_DATA, PTC3_DATA, PTC2_DATA, PTC1_DATA, PTC0_DATA, PTD7_DATA, PTD6_DATA, PTD5_DATA, PTD4_DATA, PTD3_DATA, PTD2_DATA, PTD1_DATA, PTD0_DATA, PTE6_DATA, PTE5_DATA, PTE4_DATA, PTE3_DATA, PTE2_DATA, PTE1_DATA, PTE0_DATA, PTF6_DATA, PTF5_DATA, PTF4_DATA, PTF3_DATA, PTF2_DATA, PTF1_DATA, PTF0_DATA, PTG6_DATA, PTG5_DATA, PTG4_DATA, PTG3_DATA, PTG2_DATA, PTG1_DATA, PTG0_DATA, PTH6_DATA, PTH5_DATA, PTH4_DATA, PTH3_DATA, PTH2_DATA, PTH1_DATA, PTH0_DATA, PTJ6_DATA, PTJ5_DATA, PTJ4_DATA, PTJ3_DATA, PTJ2_DATA, PTJ1_DATA, PTJ0_DATA, PTK3_DATA, PTK2_DATA, PTK1_DATA, PTK0_DATA, PTL7_DATA, PTL6_DATA, PTL5_DATA, PTL4_DATA, PTL3_DATA, PTM7_DATA, PTM6_DATA, PTM5_DATA, PTM4_DATA, PTM3_DATA, PTM2_DATA, PTM1_DATA, PTM0_DATA, PTP4_DATA, PTP3_DATA, PTP2_DATA, PTP1_DATA, PTP0_DATA, PTR7_DATA, PTR6_DATA, PTR5_DATA, PTR4_DATA, PTR3_DATA, PTR2_DATA, PTR1_DATA, PTR0_DATA, PTS4_DATA, PTS3_DATA, PTS2_DATA, PTS1_DATA, PTS0_DATA, PTT4_DATA, PTT3_DATA, PTT2_DATA, PTT1_DATA, PTT0_DATA, PTU4_DATA, PTU3_DATA, PTU2_DATA, PTU1_DATA, PTU0_DATA, PTV4_DATA, PTV3_DATA, PTV2_DATA, PTV1_DATA, PTV0_DATA, PINMUX_DATA_END, PINMUX_INPUT_BEGIN, PTA7_IN, PTA6_IN, PTA5_IN, PTA4_IN, PTA3_IN, PTA2_IN, PTA1_IN, PTA0_IN, PTB7_IN, PTB6_IN, PTB5_IN, PTB4_IN, PTB3_IN, PTB2_IN, PTB1_IN, PTB0_IN, PTC7_IN, PTC6_IN, PTC5_IN, PTC4_IN, PTC3_IN, PTC2_IN, PTC1_IN, PTC0_IN, PTD7_IN, PTD6_IN, PTD5_IN, PTD4_IN, PTD3_IN, PTD2_IN, PTD1_IN, PTD0_IN, PTE6_IN, PTE5_IN, PTE4_IN, PTE3_IN, PTE2_IN, PTE1_IN, PTE0_IN, PTF6_IN, PTF5_IN, PTF4_IN, PTF3_IN, PTF2_IN, PTF1_IN, PTF0_IN, PTG6_IN, PTG5_IN, PTG4_IN, PTG3_IN, PTG2_IN, PTG1_IN, PTG0_IN, PTH6_IN, PTH5_IN, PTH4_IN, PTH3_IN, PTH2_IN, PTH1_IN, PTH0_IN, PTJ6_IN, PTJ5_IN, PTJ4_IN, PTJ3_IN, PTJ2_IN, PTJ1_IN, PTJ0_IN, PTK3_IN, PTK2_IN, PTK1_IN, PTK0_IN, PTL7_IN, PTL6_IN, PTL5_IN, PTL4_IN, PTL3_IN, PTM7_IN, PTM6_IN, PTM5_IN, PTM4_IN, PTM3_IN, PTM2_IN, PTM1_IN, PTM0_IN, PTP4_IN, PTP3_IN, PTP2_IN, PTP1_IN, PTP0_IN, PTR7_IN, PTR6_IN, PTR5_IN, PTR4_IN, PTR3_IN, PTR2_IN, PTR1_IN, PTR0_IN, PTS4_IN, PTS3_IN, PTS2_IN, PTS1_IN, PTS0_IN, PTT4_IN, PTT3_IN, PTT2_IN, PTT1_IN, PTT0_IN, PTU4_IN, PTU3_IN, PTU2_IN, PTU1_IN, PTU0_IN, PTV4_IN, PTV3_IN, PTV2_IN, PTV1_IN, PTV0_IN, PINMUX_INPUT_END, PINMUX_OUTPUT_BEGIN, PTA7_OUT, PTA6_OUT, PTA5_OUT, PTA4_OUT, PTA3_OUT, PTA2_OUT, PTA1_OUT, PTA0_OUT, PTB7_OUT, PTB6_OUT, PTB5_OUT, PTB4_OUT, PTB3_OUT, PTB2_OUT, PTB1_OUT, PTB0_OUT, PTC7_OUT, PTC6_OUT, PTC5_OUT, PTC4_OUT, PTC3_OUT, PTC2_OUT, PTC1_OUT, PTC0_OUT, PTD7_OUT, PTD6_OUT, PTD5_OUT, PTD4_OUT, PTD3_OUT, PTD2_OUT, PTD1_OUT, PTD0_OUT, PTE4_OUT, PTE3_OUT, PTE2_OUT, PTE1_OUT, PTE0_OUT, PTF0_OUT, PTG6_OUT, PTG5_OUT, PTG4_OUT, PTG3_OUT, PTG2_OUT, PTG1_OUT, PTG0_OUT, PTH6_OUT, PTH5_OUT, PTH4_OUT, PTH3_OUT, PTH2_OUT, PTH1_OUT, PTH0_OUT, PTJ6_OUT, PTJ5_OUT, PTJ4_OUT, PTJ3_OUT, PTJ2_OUT, PTJ1_OUT, PTJ0_OUT, PTK3_OUT, PTK2_OUT, PTK1_OUT, PTK0_OUT, PTL7_OUT, PTL6_OUT, PTL5_OUT, PTL4_OUT, PTL3_OUT, PTM7_OUT, PTM6_OUT, PTM5_OUT, PTM4_OUT, PTM3_OUT, PTM2_OUT, PTM1_OUT, PTM0_OUT, PTP4_OUT, PTP3_OUT, PTP2_OUT, PTP1_OUT, PTP0_OUT, PTR7_OUT, PTR6_OUT, PTR5_OUT, PTR4_OUT, PTR3_OUT, PTR2_OUT, PTR1_OUT, PTR0_OUT, PTS4_OUT, PTS3_OUT, PTS2_OUT, PTS1_OUT, PTS0_OUT, PTT4_OUT, PTT3_OUT, PTT2_OUT, PTT1_OUT, PTT0_OUT, PTU4_OUT, PTU3_OUT, PTU2_OUT, PTU1_OUT, PTU0_OUT, PTV4_OUT, PTV3_OUT, PTV2_OUT, PTV1_OUT, PTV0_OUT, PINMUX_OUTPUT_END, PINMUX_FUNCTION_BEGIN, PTA7_FN, PTA6_FN, PTA5_FN, PTA4_FN, PTA3_FN, PTA2_FN, PTA1_FN, PTA0_FN, PTB7_FN, PTB6_FN, PTB5_FN, PTB4_FN, PTB3_FN, PTB2_FN, PTB1_FN, PTB0_FN, PTC7_FN, PTC6_FN, PTC5_FN, PTC4_FN, PTC3_FN, PTC2_FN, PTC1_FN, PTC0_FN, PTD7_FN, PTD6_FN, PTD5_FN, PTD4_FN, PTD3_FN, PTD2_FN, PTD1_FN, PTD0_FN, PTE6_FN, PTE5_FN, PTE4_FN, PTE3_FN, PTE2_FN, PTE1_FN, PTE0_FN, PTF6_FN, PTF5_FN, PTF4_FN, PTF3_FN, PTF2_FN, PTF1_FN, PTF0_FN, PTG6_FN, PTG5_FN, PTG4_FN, PTG3_FN, PTG2_FN, PTG1_FN, PTG0_FN, PTH6_FN, PTH5_FN, PTH4_FN, PTH3_FN, PTH2_FN, PTH1_FN, PTH0_FN, PTJ6_FN, PTJ5_FN, PTJ4_FN, PTJ3_FN, PTJ2_FN, PTJ1_FN, PTJ0_FN, PTK3_FN, PTK2_FN, PTK1_FN, PTK0_FN, PTL7_FN, PTL6_FN, PTL5_FN, PTL4_FN, PTL3_FN, PTM7_FN, PTM6_FN, PTM5_FN, PTM4_FN, PTM3_FN, PTM2_FN, PTM1_FN, PTM0_FN, PTP4_FN, PTP3_FN, PTP2_FN, PTP1_FN, PTP0_FN, PTR7_FN, PTR6_FN, PTR5_FN, PTR4_FN, PTR3_FN, PTR2_FN, PTR1_FN, PTR0_FN, PTS4_FN, PTS3_FN, PTS2_FN, PTS1_FN, PTS0_FN, PTT4_FN, PTT3_FN, PTT2_FN, PTT1_FN, PTT0_FN, PTU4_FN, PTU3_FN, PTU2_FN, PTU1_FN, PTU0_FN, PTV4_FN, PTV3_FN, PTV2_FN, PTV1_FN, PTV0_FN, PSELA_1_0_00, PSELA_1_0_01, PSELA_1_0_10, PSELA_3_2_00, PSELA_3_2_01, PSELA_3_2_10, PSELA_3_2_11, PSELA_5_4_00, PSELA_5_4_01, PSELA_5_4_10, PSELA_5_4_11, PSELA_7_6_00, PSELA_7_6_01, PSELA_7_6_10, PSELA_9_8_00, PSELA_9_8_01, PSELA_9_8_10, PSELA_11_10_00, PSELA_11_10_01, PSELA_11_10_10, PSELA_13_12_00, PSELA_13_12_10, PSELA_15_14_00, PSELA_15_14_10, PSELB_9_8_00, PSELB_9_8_11, PSELB_11_10_00, PSELB_11_10_01, PSELB_11_10_10, PSELB_11_10_11, PSELB_13_12_00, PSELB_13_12_01, PSELB_13_12_10, PSELB_13_12_11, PSELB_15_14_00, PSELB_15_14_11, PSELC_9_8_00, PSELC_9_8_10, PSELC_11_10_00, PSELC_11_10_10, PSELC_13_12_00, PSELC_13_12_01, PSELC_13_12_10, PSELC_15_14_00, PSELC_15_14_01, PSELC_15_14_10, PSELD_1_0_00, PSELD_1_0_10, PSELD_11_10_00, PSELD_11_10_01, PSELD_15_14_00, PSELD_15_14_01, PSELD_15_14_10, PINMUX_FUNCTION_END, PINMUX_MARK_BEGIN, D31_MARK, D30_MARK, D29_MARK, D28_MARK, D27_MARK, D26_MARK, D25_MARK, D24_MARK, D23_MARK, D22_MARK, D21_MARK, D20_MARK, D19_MARK, D18_MARK, D17_MARK, D16_MARK, IOIS16_MARK, RAS_MARK, CAS_MARK, CKE_MARK, CS5B_CE1A_MARK, CS6B_CE1B_MARK, A25_MARK, A24_MARK, A23_MARK, A22_MARK, A21_MARK, A20_MARK, A19_MARK, A0_MARK, REFOUT_MARK, IRQOUT_MARK, LCD_DATA15_MARK, LCD_DATA14_MARK, LCD_DATA13_MARK, LCD_DATA12_MARK, LCD_DATA11_MARK, LCD_DATA10_MARK, LCD_DATA9_MARK, LCD_DATA8_MARK, LCD_DATA7_MARK, LCD_DATA6_MARK, LCD_DATA5_MARK, LCD_DATA4_MARK, LCD_DATA3_MARK, LCD_DATA2_MARK, LCD_DATA1_MARK, LCD_DATA0_MARK, LCD_M_DISP_MARK, LCD_CL1_MARK, LCD_CL2_MARK, LCD_DON_MARK, LCD_FLM_MARK, LCD_VEPWC_MARK, LCD_VCPWC_MARK, AFE_RXIN_MARK, AFE_RDET_MARK, AFE_FS_MARK, AFE_TXOUT_MARK, AFE_SCLK_MARK, AFE_RLYCNT_MARK, AFE_HC1_MARK, IIC_SCL_MARK, IIC_SDA_MARK, DA1_MARK, DA0_MARK, AN3_MARK, AN2_MARK, AN1_MARK, AN0_MARK, ADTRG_MARK, USB1D_RCV_MARK, USB1D_TXSE0_MARK, USB1D_TXDPLS_MARK, USB1D_DMNS_MARK, USB1D_DPLS_MARK, USB1D_SPEED_MARK, USB1D_TXENL_MARK, USB2_PWR_EN_MARK, USB1_PWR_EN_USBF_UPLUP_MARK, USB1D_SUSPEND_MARK, IRQ5_MARK, IRQ4_MARK, IRQ3_IRL3_MARK, IRQ2_IRL2_MARK, IRQ1_IRL1_MARK, IRQ0_IRL0_MARK, PCC_REG_MARK, PCC_DRV_MARK, PCC_BVD2_MARK, PCC_BVD1_MARK, PCC_CD2_MARK, PCC_CD1_MARK, PCC_RESET_MARK, PCC_RDY_MARK, PCC_VS2_MARK, PCC_VS1_MARK, AUDATA3_MARK, AUDATA2_MARK, AUDATA1_MARK, AUDATA0_MARK, AUDCK_MARK, AUDSYNC_MARK, ASEBRKAK_MARK, TRST_MARK, TMS_MARK, TDO_MARK, TDI_MARK, TCK_MARK, DACK1_MARK, DREQ1_MARK, DACK0_MARK, DREQ0_MARK, TEND1_MARK, TEND0_MARK, SIOF0_SYNC_MARK, SIOF0_MCLK_MARK, SIOF0_TXD_MARK, SIOF0_RXD_MARK, SIOF0_SCK_MARK, SIOF1_SYNC_MARK, SIOF1_MCLK_MARK, SIOF1_TXD_MARK, SIOF1_RXD_MARK, SIOF1_SCK_MARK, SCIF0_TXD_MARK, SCIF0_RXD_MARK, SCIF0_RTS_MARK, SCIF0_CTS_MARK, SCIF0_SCK_MARK, SCIF1_TXD_MARK, SCIF1_RXD_MARK, SCIF1_RTS_MARK, SCIF1_CTS_MARK, SCIF1_SCK_MARK, TPU_TO1_MARK, TPU_TO0_MARK, TPU_TI3B_MARK, TPU_TI3A_MARK, TPU_TI2B_MARK, TPU_TI2A_MARK, TPU_TO3_MARK, TPU_TO2_MARK, SIM_D_MARK, SIM_CLK_MARK, SIM_RST_MARK, MMC_DAT_MARK, MMC_CMD_MARK, MMC_CLK_MARK, MMC_VDDON_MARK, MMC_ODMOD_MARK, STATUS0_MARK, STATUS1_MARK, PINMUX_MARK_END, }; static const u16 pinmux_data[] = { /* PTA GPIO */ PINMUX_DATA(PTA7_DATA, PTA7_IN, PTA7_OUT), PINMUX_DATA(PTA6_DATA, PTA6_IN, PTA6_OUT), PINMUX_DATA(PTA5_DATA, PTA5_IN, PTA5_OUT), PINMUX_DATA(PTA4_DATA, PTA4_IN, PTA4_OUT), PINMUX_DATA(PTA3_DATA, PTA3_IN, PTA3_OUT), PINMUX_DATA(PTA2_DATA, PTA2_IN, PTA2_OUT), PINMUX_DATA(PTA1_DATA, PTA1_IN, PTA1_OUT), PINMUX_DATA(PTA0_DATA, PTA0_IN, PTA0_OUT), /* PTB GPIO */ PINMUX_DATA(PTB7_DATA, PTB7_IN, PTB7_OUT), PINMUX_DATA(PTB6_DATA, PTB6_IN, PTB6_OUT), PINMUX_DATA(PTB5_DATA, PTB5_IN, PTB5_OUT), PINMUX_DATA(PTB4_DATA, PTB4_IN, PTB4_OUT), PINMUX_DATA(PTB3_DATA, PTB3_IN, PTB3_OUT), PINMUX_DATA(PTB2_DATA, PTB2_IN, PTB2_OUT), PINMUX_DATA(PTB1_DATA, PTB1_IN, PTB1_OUT), PINMUX_DATA(PTB0_DATA, PTB0_IN, PTB0_OUT), /* PTC GPIO */ PINMUX_DATA(PTC7_DATA, PTC7_IN, PTC7_OUT), PINMUX_DATA(PTC6_DATA, PTC6_IN, PTC6_OUT), PINMUX_DATA(PTC5_DATA, PTC5_IN, PTC5_OUT), PINMUX_DATA(PTC4_DATA, PTC4_IN, PTC4_OUT), PINMUX_DATA(PTC3_DATA, PTC3_IN, PTC3_OUT), PINMUX_DATA(PTC2_DATA, PTC2_IN, PTC2_OUT), PINMUX_DATA(PTC1_DATA, PTC1_IN, PTC1_OUT), PINMUX_DATA(PTC0_DATA, PTC0_IN, PTC0_OUT), /* PTD GPIO */ PINMUX_DATA(PTD7_DATA, PTD7_IN, PTD7_OUT), PINMUX_DATA(PTD6_DATA, PTD6_IN, PTD6_OUT), PINMUX_DATA(PTD5_DATA, PTD5_IN, PTD5_OUT), PINMUX_DATA(PTD4_DATA, PTD4_IN, PTD4_OUT), PINMUX_DATA(PTD3_DATA, PTD3_IN, PTD3_OUT), PINMUX_DATA(PTD2_DATA, PTD2_IN, PTD2_OUT), PINMUX_DATA(PTD1_DATA, PTD1_IN, PTD1_OUT), PINMUX_DATA(PTD0_DATA, PTD0_IN, PTD0_OUT), /* PTE GPIO */ PINMUX_DATA(PTE6_DATA, PTE6_IN), PINMUX_DATA(PTE5_DATA, PTE5_IN), PINMUX_DATA(PTE4_DATA, PTE4_IN, PTE4_OUT), PINMUX_DATA(PTE3_DATA, PTE3_IN, PTE3_OUT), PINMUX_DATA(PTE2_DATA, PTE2_IN, PTE2_OUT), PINMUX_DATA(PTE1_DATA, PTE1_IN, PTE1_OUT), PINMUX_DATA(PTE0_DATA, PTE0_IN, PTE0_OUT), /* PTF GPIO */ PINMUX_DATA(PTF6_DATA, PTF6_IN), PINMUX_DATA(PTF5_DATA, PTF5_IN), PINMUX_DATA(PTF4_DATA, PTF4_IN), PINMUX_DATA(PTF3_DATA, PTF3_IN), PINMUX_DATA(PTF2_DATA, PTF2_IN), PINMUX_DATA(PTF1_DATA, PTF1_IN), PINMUX_DATA(PTF0_DATA, PTF0_IN, PTF0_OUT), /* PTG GPIO */ PINMUX_DATA(PTG6_DATA, PTG6_IN, PTG6_OUT), PINMUX_DATA(PTG5_DATA, PTG5_IN, PTG5_OUT), PINMUX_DATA(PTG4_DATA, PTG4_IN, PTG4_OUT), PINMUX_DATA(PTG3_DATA, PTG3_IN, PTG3_OUT), PINMUX_DATA(PTG2_DATA, PTG2_IN, PTG2_OUT), PINMUX_DATA(PTG1_DATA, PTG1_IN, PTG1_OUT), PINMUX_DATA(PTG0_DATA, PTG0_IN, PTG0_OUT), /* PTH GPIO */ PINMUX_DATA(PTH6_DATA, PTH6_IN, PTH6_OUT), PINMUX_DATA(PTH5_DATA, PTH5_IN, PTH5_OUT), PINMUX_DATA(PTH4_DATA, PTH4_IN, PTH4_OUT), PINMUX_DATA(PTH3_DATA, PTH3_IN, PTH3_OUT), PINMUX_DATA(PTH2_DATA, PTH2_IN, PTH2_OUT), PINMUX_DATA(PTH1_DATA, PTH1_IN, PTH1_OUT), PINMUX_DATA(PTH0_DATA, PTH0_IN, PTH0_OUT), /* PTJ GPIO */ PINMUX_DATA(PTJ6_DATA, PTJ6_IN, PTJ6_OUT), PINMUX_DATA(PTJ5_DATA, PTJ5_IN, PTJ5_OUT), PINMUX_DATA(PTJ4_DATA, PTJ4_IN, PTJ4_OUT), PINMUX_DATA(PTJ3_DATA, PTJ3_IN, PTJ3_OUT), PINMUX_DATA(PTJ2_DATA, PTJ2_IN, PTJ2_OUT), PINMUX_DATA(PTJ1_DATA, PTJ1_IN, PTJ1_OUT), PINMUX_DATA(PTJ0_DATA, PTJ0_IN, PTJ0_OUT), /* PTK GPIO */ PINMUX_DATA(PTK3_DATA, PTK3_IN, PTK3_OUT), PINMUX_DATA(PTK2_DATA, PTK2_IN, PTK2_OUT), PINMUX_DATA(PTK1_DATA, PTK1_IN, PTK1_OUT), PINMUX_DATA(PTK0_DATA, PTK0_IN, PTK0_OUT), /* PTL GPIO */ PINMUX_DATA(PTL7_DATA, PTL7_IN, PTL7_OUT), PINMUX_DATA(PTL6_DATA, PTL6_IN, PTL6_OUT), PINMUX_DATA(PTL5_DATA, PTL5_IN, PTL5_OUT), PINMUX_DATA(PTL4_DATA, PTL4_IN, PTL4_OUT), PINMUX_DATA(PTL3_DATA, PTL3_IN, PTL3_OUT), /* PTM GPIO */ PINMUX_DATA(PTM7_DATA, PTM7_IN, PTM7_OUT), PINMUX_DATA(PTM6_DATA, PTM6_IN, PTM6_OUT), PINMUX_DATA(PTM5_DATA, PTM5_IN, PTM5_OUT), PINMUX_DATA(PTM4_DATA, PTM4_IN, PTM4_OUT), PINMUX_DATA(PTM3_DATA, PTM3_IN, PTM3_OUT), PINMUX_DATA(PTM2_DATA, PTM2_IN, PTM2_OUT), PINMUX_DATA(PTM1_DATA, PTM1_IN, PTM1_OUT), PINMUX_DATA(PTM0_DATA, PTM0_IN, PTM0_OUT), /* PTP GPIO */ PINMUX_DATA(PTP4_DATA, PTP4_IN, PTP4_OUT), PINMUX_DATA(PTP3_DATA, PTP3_IN, PTP3_OUT), PINMUX_DATA(PTP2_DATA, PTP2_IN, PTP2_OUT), PINMUX_DATA(PTP1_DATA, PTP1_IN, PTP1_OUT), PINMUX_DATA(PTP0_DATA, PTP0_IN, PTP0_OUT), /* PTR GPIO */ PINMUX_DATA(PTR7_DATA, PTR7_IN, PTR7_OUT), PINMUX_DATA(PTR6_DATA, PTR6_IN, PTR6_OUT), PINMUX_DATA(PTR5_DATA, PTR5_IN, PTR5_OUT), PINMUX_DATA(PTR4_DATA, PTR4_IN, PTR4_OUT), PINMUX_DATA(PTR3_DATA, PTR3_IN, PTR3_OUT), PINMUX_DATA(PTR2_DATA, PTR2_IN, PTR2_OUT), PINMUX_DATA(PTR1_DATA, PTR1_IN, PTR1_OUT), PINMUX_DATA(PTR0_DATA, PTR0_IN, PTR0_OUT), /* PTS GPIO */ PINMUX_DATA(PTS4_DATA, PTS4_IN, PTS4_OUT), PINMUX_DATA(PTS3_DATA, PTS3_IN, PTS3_OUT), PINMUX_DATA(PTS2_DATA, PTS2_IN, PTS2_OUT), PINMUX_DATA(PTS1_DATA, PTS1_IN, PTS1_OUT), PINMUX_DATA(PTS0_DATA, PTS0_IN, PTS0_OUT), /* PTT GPIO */ PINMUX_DATA(PTT4_DATA, PTT4_IN, PTT4_OUT), PINMUX_DATA(PTT3_DATA, PTT3_IN, PTT3_OUT), PINMUX_DATA(PTT2_DATA, PTT2_IN, PTT2_OUT), PINMUX_DATA(PTT1_DATA, PTT1_IN, PTT1_OUT), PINMUX_DATA(PTT0_DATA, PTT0_IN, PTT0_OUT), /* PTU GPIO */ PINMUX_DATA(PTU4_DATA, PTU4_IN, PTU4_OUT), PINMUX_DATA(PTU3_DATA, PTU3_IN, PTU3_OUT), PINMUX_DATA(PTU2_DATA, PTU2_IN, PTU2_OUT), PINMUX_DATA(PTU1_DATA, PTU1_IN, PTU1_OUT), PINMUX_DATA(PTU0_DATA, PTU0_IN, PTU0_OUT), /* PTV GPIO */ PINMUX_DATA(PTV4_DATA, PTV4_IN, PTV4_OUT), PINMUX_DATA(PTV3_DATA, PTV3_IN, PTV3_OUT), PINMUX_DATA(PTV2_DATA, PTV2_IN, PTV2_OUT), PINMUX_DATA(PTV1_DATA, PTV1_IN, PTV1_OUT), PINMUX_DATA(PTV0_DATA, PTV0_IN, PTV0_OUT), /* PTA FN */ PINMUX_DATA(D23_MARK, PTA7_FN), PINMUX_DATA(D22_MARK, PTA6_FN), PINMUX_DATA(D21_MARK, PTA5_FN), PINMUX_DATA(D20_MARK, PTA4_FN), PINMUX_DATA(D19_MARK, PTA3_FN), PINMUX_DATA(D18_MARK, PTA2_FN), PINMUX_DATA(D17_MARK, PTA1_FN), PINMUX_DATA(D16_MARK, PTA0_FN), /* PTB FN */ PINMUX_DATA(D31_MARK, PTB7_FN), PINMUX_DATA(D30_MARK, PTB6_FN), PINMUX_DATA(D29_MARK, PTB5_FN), PINMUX_DATA(D28_MARK, PTB4_FN), PINMUX_DATA(D27_MARK, PTB3_FN), PINMUX_DATA(D26_MARK, PTB2_FN), PINMUX_DATA(D25_MARK, PTB1_FN), PINMUX_DATA(D24_MARK, PTB0_FN), /* PTC FN */ PINMUX_DATA(LCD_DATA7_MARK, PTC7_FN), PINMUX_DATA(LCD_DATA6_MARK, PTC6_FN), PINMUX_DATA(LCD_DATA5_MARK, PTC5_FN), PINMUX_DATA(LCD_DATA4_MARK, PTC4_FN), PINMUX_DATA(LCD_DATA3_MARK, PTC3_FN), PINMUX_DATA(LCD_DATA2_MARK, PTC2_FN), PINMUX_DATA(LCD_DATA1_MARK, PTC1_FN), PINMUX_DATA(LCD_DATA0_MARK, PTC0_FN), /* PTD FN */ PINMUX_DATA(LCD_DATA15_MARK, PTD7_FN), PINMUX_DATA(LCD_DATA14_MARK, PTD6_FN), PINMUX_DATA(LCD_DATA13_MARK, PTD5_FN), PINMUX_DATA(LCD_DATA12_MARK, PTD4_FN), PINMUX_DATA(LCD_DATA11_MARK, PTD3_FN), PINMUX_DATA(LCD_DATA10_MARK, PTD2_FN), PINMUX_DATA(LCD_DATA9_MARK, PTD1_FN), PINMUX_DATA(LCD_DATA8_MARK, PTD0_FN), /* PTE FN */ PINMUX_DATA(IIC_SCL_MARK, PSELB_9_8_00, PTE6_FN), PINMUX_DATA(AFE_RXIN_MARK, PSELB_9_8_11, PTE6_FN), PINMUX_DATA(IIC_SDA_MARK, PSELB_9_8_00, PTE5_FN), PINMUX_DATA(AFE_RDET_MARK, PSELB_9_8_11, PTE5_FN), PINMUX_DATA(LCD_M_DISP_MARK, PTE4_FN), PINMUX_DATA(LCD_CL1_MARK, PTE3_FN), PINMUX_DATA(LCD_CL2_MARK, PTE2_FN), PINMUX_DATA(LCD_DON_MARK, PTE1_FN), PINMUX_DATA(LCD_FLM_MARK, PTE0_FN), /* PTF FN */ PINMUX_DATA(DA1_MARK, PTF6_FN), PINMUX_DATA(DA0_MARK, PTF5_FN), PINMUX_DATA(AN3_MARK, PTF4_FN), PINMUX_DATA(AN2_MARK, PTF3_FN), PINMUX_DATA(AN1_MARK, PTF2_FN), PINMUX_DATA(AN0_MARK, PTF1_FN), PINMUX_DATA(ADTRG_MARK, PTF0_FN), /* PTG FN */ PINMUX_DATA(USB1D_RCV_MARK, PSELA_3_2_00, PTG6_FN), PINMUX_DATA(AFE_FS_MARK, PSELA_3_2_01, PTG6_FN), PINMUX_DATA(PCC_REG_MARK, PSELA_3_2_10, PTG6_FN), PINMUX_DATA(IRQ5_MARK, PSELA_3_2_11, PTG6_FN), PINMUX_DATA(USB1D_TXSE0_MARK, PSELA_5_4_00, PTG5_FN), PINMUX_DATA(AFE_TXOUT_MARK, PSELA_5_4_01, PTG5_FN), PINMUX_DATA(PCC_DRV_MARK, PSELA_5_4_10, PTG5_FN), PINMUX_DATA(IRQ4_MARK, PSELA_5_4_11, PTG5_FN), PINMUX_DATA(USB1D_TXDPLS_MARK, PSELA_7_6_00, PTG4_FN), PINMUX_DATA(AFE_SCLK_MARK, PSELA_7_6_01, PTG4_FN), PINMUX_DATA(IOIS16_MARK, PSELA_7_6_10, PTG4_FN), PINMUX_DATA(USB1D_DMNS_MARK, PSELA_9_8_00, PTG3_FN), PINMUX_DATA(AFE_RLYCNT_MARK, PSELA_9_8_01, PTG3_FN), PINMUX_DATA(PCC_BVD2_MARK, PSELA_9_8_10, PTG3_FN), PINMUX_DATA(USB1D_DPLS_MARK, PSELA_11_10_00, PTG2_FN), PINMUX_DATA(AFE_HC1_MARK, PSELA_11_10_01, PTG2_FN), PINMUX_DATA(PCC_BVD1_MARK, PSELA_11_10_10, PTG2_FN), PINMUX_DATA(USB1D_SPEED_MARK, PSELA_13_12_00, PTG1_FN), PINMUX_DATA(PCC_CD2_MARK, PSELA_13_12_10, PTG1_FN), PINMUX_DATA(USB1D_TXENL_MARK, PSELA_15_14_00, PTG0_FN), PINMUX_DATA(PCC_CD1_MARK, PSELA_15_14_10, PTG0_FN), /* PTH FN */ PINMUX_DATA(RAS_MARK, PTH6_FN), PINMUX_DATA(CAS_MARK, PTH5_FN), PINMUX_DATA(CKE_MARK, PTH4_FN), PINMUX_DATA(STATUS1_MARK, PTH3_FN), PINMUX_DATA(STATUS0_MARK, PTH2_FN), PINMUX_DATA(USB2_PWR_EN_MARK, PTH1_FN), PINMUX_DATA(USB1_PWR_EN_USBF_UPLUP_MARK, PTH0_FN), /* PTJ FN */ PINMUX_DATA(AUDCK_MARK, PTJ6_FN), PINMUX_DATA(ASEBRKAK_MARK, PTJ5_FN), PINMUX_DATA(AUDATA3_MARK, PTJ4_FN), PINMUX_DATA(AUDATA2_MARK, PTJ3_FN), PINMUX_DATA(AUDATA1_MARK, PTJ2_FN), PINMUX_DATA(AUDATA0_MARK, PTJ1_FN), PINMUX_DATA(AUDSYNC_MARK, PTJ0_FN), /* PTK FN */ PINMUX_DATA(PCC_RESET_MARK, PTK3_FN), PINMUX_DATA(PCC_RDY_MARK, PTK2_FN), PINMUX_DATA(PCC_VS2_MARK, PTK1_FN), PINMUX_DATA(PCC_VS1_MARK, PTK0_FN), /* PTL FN */ PINMUX_DATA(TRST_MARK, PTL7_FN), PINMUX_DATA(TMS_MARK, PTL6_FN), PINMUX_DATA(TDO_MARK, PTL5_FN), PINMUX_DATA(TDI_MARK, PTL4_FN), PINMUX_DATA(TCK_MARK, PTL3_FN), /* PTM FN */ PINMUX_DATA(DREQ1_MARK, PTM7_FN), PINMUX_DATA(DREQ0_MARK, PTM6_FN), PINMUX_DATA(DACK1_MARK, PTM5_FN), PINMUX_DATA(DACK0_MARK, PTM4_FN), PINMUX_DATA(TEND1_MARK, PTM3_FN), PINMUX_DATA(TEND0_MARK, PTM2_FN), PINMUX_DATA(CS5B_CE1A_MARK, PTM1_FN), PINMUX_DATA(CS6B_CE1B_MARK, PTM0_FN), /* PTP FN */ PINMUX_DATA(USB1D_SUSPEND_MARK, PSELA_1_0_00, PTP4_FN), PINMUX_DATA(REFOUT_MARK, PSELA_1_0_01, PTP4_FN), PINMUX_DATA(IRQOUT_MARK, PSELA_1_0_10, PTP4_FN), PINMUX_DATA(IRQ3_IRL3_MARK, PTP3_FN), PINMUX_DATA(IRQ2_IRL2_MARK, PTP2_FN), PINMUX_DATA(IRQ1_IRL1_MARK, PTP1_FN), PINMUX_DATA(IRQ0_IRL0_MARK, PTP0_FN), /* PTR FN */ PINMUX_DATA(A25_MARK, PTR7_FN), PINMUX_DATA(A24_MARK, PTR6_FN), PINMUX_DATA(A23_MARK, PTR5_FN), PINMUX_DATA(A22_MARK, PTR4_FN), PINMUX_DATA(A21_MARK, PTR3_FN), PINMUX_DATA(A20_MARK, PTR2_FN), PINMUX_DATA(A19_MARK, PTR1_FN), PINMUX_DATA(A0_MARK, PTR0_FN), /* PTS FN */ PINMUX_DATA(SIOF0_SYNC_MARK, PTS4_FN), PINMUX_DATA(SIOF0_MCLK_MARK, PTS3_FN), PINMUX_DATA(SIOF0_TXD_MARK, PTS2_FN), PINMUX_DATA(SIOF0_RXD_MARK, PTS1_FN), PINMUX_DATA(SIOF0_SCK_MARK, PTS0_FN), /* PTT FN */ PINMUX_DATA(SCIF0_CTS_MARK, PSELB_15_14_00, PTT4_FN), PINMUX_DATA(TPU_TO1_MARK, PSELB_15_14_11, PTT4_FN), PINMUX_DATA(SCIF0_RTS_MARK, PSELB_15_14_00, PTT3_FN), PINMUX_DATA(TPU_TO0_MARK, PSELB_15_14_11, PTT3_FN), PINMUX_DATA(SCIF0_TXD_MARK, PTT2_FN), PINMUX_DATA(SCIF0_RXD_MARK, PTT1_FN), PINMUX_DATA(SCIF0_SCK_MARK, PTT0_FN), /* PTU FN */ PINMUX_DATA(SIOF1_SYNC_MARK, PTU4_FN), PINMUX_DATA(SIOF1_MCLK_MARK, PSELD_11_10_00, PTU3_FN), PINMUX_DATA(TPU_TI3B_MARK, PSELD_11_10_01, PTU3_FN), PINMUX_DATA(SIOF1_TXD_MARK, PSELD_15_14_00, PTU2_FN), PINMUX_DATA(TPU_TI3A_MARK, PSELD_15_14_01, PTU2_FN), PINMUX_DATA(MMC_DAT_MARK, PSELD_15_14_10, PTU2_FN), PINMUX_DATA(SIOF1_RXD_MARK, PSELC_13_12_00, PTU1_FN), PINMUX_DATA(TPU_TI2B_MARK, PSELC_13_12_01, PTU1_FN), PINMUX_DATA(MMC_CMD_MARK, PSELC_13_12_10, PTU1_FN), PINMUX_DATA(SIOF1_SCK_MARK, PSELC_15_14_00, PTU0_FN), PINMUX_DATA(TPU_TI2A_MARK, PSELC_15_14_01, PTU0_FN), PINMUX_DATA(MMC_CLK_MARK, PSELC_15_14_10, PTU0_FN), /* PTV FN */ PINMUX_DATA(SCIF1_CTS_MARK, PSELB_11_10_00, PTV4_FN), PINMUX_DATA(TPU_TO3_MARK, PSELB_11_10_01, PTV4_FN), PINMUX_DATA(MMC_VDDON_MARK, PSELB_11_10_10, PTV4_FN), PINMUX_DATA(LCD_VEPWC_MARK, PSELB_11_10_11, PTV4_FN), PINMUX_DATA(SCIF1_RTS_MARK, PSELB_13_12_00, PTV3_FN), PINMUX_DATA(TPU_TO2_MARK, PSELB_13_12_01, PTV3_FN), PINMUX_DATA(MMC_ODMOD_MARK, PSELB_13_12_10, PTV3_FN), PINMUX_DATA(LCD_VCPWC_MARK, PSELB_13_12_11, PTV3_FN), PINMUX_DATA(SCIF1_TXD_MARK, PSELC_9_8_00, PTV2_FN), PINMUX_DATA(SIM_D_MARK, PSELC_9_8_10, PTV2_FN), PINMUX_DATA(SCIF1_RXD_MARK, PSELC_11_10_00, PTV1_FN), PINMUX_DATA(SIM_RST_MARK, PSELC_11_10_10, PTV1_FN), PINMUX_DATA(SCIF1_SCK_MARK, PSELD_1_0_00, PTV0_FN), PINMUX_DATA(SIM_CLK_MARK, PSELD_1_0_10, PTV0_FN), }; static const struct sh_pfc_pin pinmux_pins[] = { /* PTA */ PINMUX_GPIO(PTA7), PINMUX_GPIO(PTA6), PINMUX_GPIO(PTA5), PINMUX_GPIO(PTA4), PINMUX_GPIO(PTA3), PINMUX_GPIO(PTA2), PINMUX_GPIO(PTA1), PINMUX_GPIO(PTA0), /* PTB */ PINMUX_GPIO(PTB7), PINMUX_GPIO(PTB6), PINMUX_GPIO(PTB5), PINMUX_GPIO(PTB4), PINMUX_GPIO(PTB3), PINMUX_GPIO(PTB2), PINMUX_GPIO(PTB1), PINMUX_GPIO(PTB0), /* PTC */ PINMUX_GPIO(PTC7), PINMUX_GPIO(PTC6), PINMUX_GPIO(PTC5), PINMUX_GPIO(PTC4), PINMUX_GPIO(PTC3), PINMUX_GPIO(PTC2), PINMUX_GPIO(PTC1), PINMUX_GPIO(PTC0), /* PTD */ PINMUX_GPIO(PTD7), PINMUX_GPIO(PTD6), PINMUX_GPIO(PTD5), PINMUX_GPIO(PTD4), PINMUX_GPIO(PTD3), PINMUX_GPIO(PTD2), PINMUX_GPIO(PTD1), PINMUX_GPIO(PTD0), /* PTE */ PINMUX_GPIO(PTE6), PINMUX_GPIO(PTE5), PINMUX_GPIO(PTE4), PINMUX_GPIO(PTE3), PINMUX_GPIO(PTE2), PINMUX_GPIO(PTE1), PINMUX_GPIO(PTE0), /* PTF */ PINMUX_GPIO(PTF6), PINMUX_GPIO(PTF5), PINMUX_GPIO(PTF4), PINMUX_GPIO(PTF3), PINMUX_GPIO(PTF2), PINMUX_GPIO(PTF1), PINMUX_GPIO(PTF0), /* PTG */ PINMUX_GPIO(PTG6), PINMUX_GPIO(PTG5), PINMUX_GPIO(PTG4), PINMUX_GPIO(PTG3), PINMUX_GPIO(PTG2), PINMUX_GPIO(PTG1), PINMUX_GPIO(PTG0), /* PTH */ PINMUX_GPIO(PTH6), PINMUX_GPIO(PTH5), PINMUX_GPIO(PTH4), PINMUX_GPIO(PTH3), PINMUX_GPIO(PTH2), PINMUX_GPIO(PTH1), PINMUX_GPIO(PTH0), /* PTJ */ PINMUX_GPIO(PTJ6), PINMUX_GPIO(PTJ5), PINMUX_GPIO(PTJ4), PINMUX_GPIO(PTJ3), PINMUX_GPIO(PTJ2), PINMUX_GPIO(PTJ1), PINMUX_GPIO(PTJ0), /* PTK */ PINMUX_GPIO(PTK3), PINMUX_GPIO(PTK2), PINMUX_GPIO(PTK1), PINMUX_GPIO(PTK0), /* PTL */ PINMUX_GPIO(PTL7), PINMUX_GPIO(PTL6), PINMUX_GPIO(PTL5), PINMUX_GPIO(PTL4), PINMUX_GPIO(PTL3), /* PTM */ PINMUX_GPIO(PTM7), PINMUX_GPIO(PTM6), PINMUX_GPIO(PTM5), PINMUX_GPIO(PTM4), PINMUX_GPIO(PTM3), PINMUX_GPIO(PTM2), PINMUX_GPIO(PTM1), PINMUX_GPIO(PTM0), /* PTP */ PINMUX_GPIO(PTP4), PINMUX_GPIO(PTP3), PINMUX_GPIO(PTP2), PINMUX_GPIO(PTP1), PINMUX_GPIO(PTP0), /* PTR */ PINMUX_GPIO(PTR7), PINMUX_GPIO(PTR6), PINMUX_GPIO(PTR5), PINMUX_GPIO(PTR4), PINMUX_GPIO(PTR3), PINMUX_GPIO(PTR2), PINMUX_GPIO(PTR1), PINMUX_GPIO(PTR0), /* PTS */ PINMUX_GPIO(PTS4), PINMUX_GPIO(PTS3), PINMUX_GPIO(PTS2), PINMUX_GPIO(PTS1), PINMUX_GPIO(PTS0), /* PTT */ PINMUX_GPIO(PTT4), PINMUX_GPIO(PTT3), PINMUX_GPIO(PTT2), PINMUX_GPIO(PTT1), PINMUX_GPIO(PTT0), /* PTU */ PINMUX_GPIO(PTU4), PINMUX_GPIO(PTU3), PINMUX_GPIO(PTU2), PINMUX_GPIO(PTU1), PINMUX_GPIO(PTU0), /* PTV */ PINMUX_GPIO(PTV4), PINMUX_GPIO(PTV3), PINMUX_GPIO(PTV2), PINMUX_GPIO(PTV1), PINMUX_GPIO(PTV0), }; #define PINMUX_FN_BASE ARRAY_SIZE(pinmux_pins) static const struct pinmux_func pinmux_func_gpios[] = { /* BSC */ GPIO_FN(D31), GPIO_FN(D30), GPIO_FN(D29), GPIO_FN(D28), GPIO_FN(D27), GPIO_FN(D26), GPIO_FN(D25), GPIO_FN(D24), GPIO_FN(D23), GPIO_FN(D22), GPIO_FN(D21), GPIO_FN(D20), GPIO_FN(D19), GPIO_FN(D18), GPIO_FN(D17), GPIO_FN(D16), GPIO_FN(IOIS16), GPIO_FN(RAS), GPIO_FN(CAS), GPIO_FN(CKE), GPIO_FN(CS5B_CE1A), GPIO_FN(CS6B_CE1B), GPIO_FN(A25), GPIO_FN(A24), GPIO_FN(A23), GPIO_FN(A22), GPIO_FN(A21), GPIO_FN(A20), GPIO_FN(A19), GPIO_FN(A0), GPIO_FN(REFOUT), GPIO_FN(IRQOUT), /* LCDC */ GPIO_FN(LCD_DATA15), GPIO_FN(LCD_DATA14), GPIO_FN(LCD_DATA13), GPIO_FN(LCD_DATA12), GPIO_FN(LCD_DATA11), GPIO_FN(LCD_DATA10), GPIO_FN(LCD_DATA9), GPIO_FN(LCD_DATA8), GPIO_FN(LCD_DATA7), GPIO_FN(LCD_DATA6), GPIO_FN(LCD_DATA5), GPIO_FN(LCD_DATA4), GPIO_FN(LCD_DATA3), GPIO_FN(LCD_DATA2), GPIO_FN(LCD_DATA1), GPIO_FN(LCD_DATA0), GPIO_FN(LCD_M_DISP), GPIO_FN(LCD_CL1), GPIO_FN(LCD_CL2), GPIO_FN(LCD_DON), GPIO_FN(LCD_FLM), GPIO_FN(LCD_VEPWC), GPIO_FN(LCD_VCPWC), /* AFEIF */ GPIO_FN(AFE_RXIN), GPIO_FN(AFE_RDET), GPIO_FN(AFE_FS), GPIO_FN(AFE_TXOUT), GPIO_FN(AFE_SCLK), GPIO_FN(AFE_RLYCNT), GPIO_FN(AFE_HC1), /* IIC */ GPIO_FN(IIC_SCL), GPIO_FN(IIC_SDA), /* DAC */ GPIO_FN(DA1), GPIO_FN(DA0), /* ADC */ GPIO_FN(AN3), GPIO_FN(AN2), GPIO_FN(AN1), GPIO_FN(AN0), GPIO_FN(ADTRG), /* USB */ GPIO_FN(USB1D_RCV), GPIO_FN(USB1D_TXSE0), GPIO_FN(USB1D_TXDPLS), GPIO_FN(USB1D_DMNS), GPIO_FN(USB1D_DPLS), GPIO_FN(USB1D_SPEED), GPIO_FN(USB1D_TXENL), GPIO_FN(USB2_PWR_EN), GPIO_FN(USB1_PWR_EN_USBF_UPLUP), GPIO_FN(USB1D_SUSPEND), /* INTC */ GPIO_FN(IRQ5), GPIO_FN(IRQ4), GPIO_FN(IRQ3_IRL3), GPIO_FN(IRQ2_IRL2), GPIO_FN(IRQ1_IRL1), GPIO_FN(IRQ0_IRL0), /* PCC */ GPIO_FN(PCC_REG), GPIO_FN(PCC_DRV), GPIO_FN(PCC_BVD2), GPIO_FN(PCC_BVD1), GPIO_FN(PCC_CD2), GPIO_FN(PCC_CD1), GPIO_FN(PCC_RESET), GPIO_FN(PCC_RDY), GPIO_FN(PCC_VS2), GPIO_FN(PCC_VS1), /* HUDI */ GPIO_FN(AUDATA3), GPIO_FN(AUDATA2), GPIO_FN(AUDATA1), GPIO_FN(AUDATA0), GPIO_FN(AUDCK), GPIO_FN(AUDSYNC), GPIO_FN(ASEBRKAK), GPIO_FN(TRST), GPIO_FN(TMS), GPIO_FN(TDO), GPIO_FN(TDI), GPIO_FN(TCK), /* DMAC */ GPIO_FN(DACK1), GPIO_FN(DREQ1), GPIO_FN(DACK0), GPIO_FN(DREQ0), GPIO_FN(TEND1), GPIO_FN(TEND0), /* SIOF0 */ GPIO_FN(SIOF0_SYNC), GPIO_FN(SIOF0_MCLK), GPIO_FN(SIOF0_TXD), GPIO_FN(SIOF0_RXD), GPIO_FN(SIOF0_SCK), /* SIOF1 */ GPIO_FN(SIOF1_SYNC), GPIO_FN(SIOF1_MCLK), GPIO_FN(SIOF1_TXD), GPIO_FN(SIOF1_RXD), GPIO_FN(SIOF1_SCK), /* SCIF0 */ GPIO_FN(SCIF0_TXD), GPIO_FN(SCIF0_RXD), GPIO_FN(SCIF0_RTS), GPIO_FN(SCIF0_CTS), GPIO_FN(SCIF0_SCK), /* SCIF1 */ GPIO_FN(SCIF1_TXD), GPIO_FN(SCIF1_RXD), GPIO_FN(SCIF1_RTS), GPIO_FN(SCIF1_CTS), GPIO_FN(SCIF1_SCK), /* TPU */ GPIO_FN(TPU_TO1), GPIO_FN(TPU_TO0), GPIO_FN(TPU_TI3B), GPIO_FN(TPU_TI3A), GPIO_FN(TPU_TI2B), GPIO_FN(TPU_TI2A), GPIO_FN(TPU_TO3), GPIO_FN(TPU_TO2), /* SIM */ GPIO_FN(SIM_D), GPIO_FN(SIM_CLK), GPIO_FN(SIM_RST), /* MMC */ GPIO_FN(MMC_DAT), GPIO_FN(MMC_CMD), GPIO_FN(MMC_CLK), GPIO_FN(MMC_VDDON), GPIO_FN(MMC_ODMOD), /* SYSC */ GPIO_FN(STATUS0), GPIO_FN(STATUS1), }; static const struct pinmux_cfg_reg pinmux_config_regs[] = { { PINMUX_CFG_REG("PACR", 0xa4050100, 16, 2) { PTA7_FN, PTA7_OUT, 0, PTA7_IN, PTA6_FN, PTA6_OUT, 0, PTA6_IN, PTA5_FN, PTA5_OUT, 0, PTA5_IN, PTA4_FN, PTA4_OUT, 0, PTA4_IN, PTA3_FN, PTA3_OUT, 0, PTA3_IN, PTA2_FN, PTA2_OUT, 0, PTA2_IN, PTA1_FN, PTA1_OUT, 0, PTA1_IN, PTA0_FN, PTA0_OUT, 0, PTA0_IN } }, { PINMUX_CFG_REG("PBCR", 0xa4050102, 16, 2) { PTB7_FN, PTB7_OUT, 0, PTB7_IN, PTB6_FN, PTB6_OUT, 0, PTB6_IN, PTB5_FN, PTB5_OUT, 0, PTB5_IN, PTB4_FN, PTB4_OUT, 0, PTB4_IN, PTB3_FN, PTB3_OUT, 0, PTB3_IN, PTB2_FN, PTB2_OUT, 0, PTB2_IN, PTB1_FN, PTB1_OUT, 0, PTB1_IN, PTB0_FN, PTB0_OUT, 0, PTB0_IN } }, { PINMUX_CFG_REG("PCCR", 0xa4050104, 16, 2) { PTC7_FN, PTC7_OUT, 0, PTC7_IN, PTC6_FN, PTC6_OUT, 0, PTC6_IN, PTC5_FN, PTC5_OUT, 0, PTC5_IN, PTC4_FN, PTC4_OUT, 0, PTC4_IN, PTC3_FN, PTC3_OUT, 0, PTC3_IN, PTC2_FN, PTC2_OUT, 0, PTC2_IN, PTC1_FN, PTC1_OUT, 0, PTC1_IN, PTC0_FN, PTC0_OUT, 0, PTC0_IN } }, { PINMUX_CFG_REG("PDCR", 0xa4050106, 16, 2) { PTD7_FN, PTD7_OUT, 0, PTD7_IN, PTD6_FN, PTD6_OUT, 0, PTD6_IN, PTD5_FN, PTD5_OUT, 0, PTD5_IN, PTD4_FN, PTD4_OUT, 0, PTD4_IN, PTD3_FN, PTD3_OUT, 0, PTD3_IN, PTD2_FN, PTD2_OUT, 0, PTD2_IN, PTD1_FN, PTD1_OUT, 0, PTD1_IN, PTD0_FN, PTD0_OUT, 0, PTD0_IN } }, { PINMUX_CFG_REG("PECR", 0xa4050108, 16, 2) { 0, 0, 0, 0, PTE6_FN, 0, 0, PTE6_IN, PTE5_FN, 0, 0, PTE5_IN, PTE4_FN, PTE4_OUT, 0, PTE4_IN, PTE3_FN, PTE3_OUT, 0, PTE3_IN, PTE2_FN, PTE2_OUT, 0, PTE2_IN, PTE1_FN, PTE1_OUT, 0, PTE1_IN, PTE0_FN, PTE0_OUT, 0, PTE0_IN } }, { PINMUX_CFG_REG("PFCR", 0xa405010a, 16, 2) { 0, 0, 0, 0, PTF6_FN, 0, 0, PTF6_IN, PTF5_FN, 0, 0, PTF5_IN, PTF4_FN, 0, 0, PTF4_IN, PTF3_FN, 0, 0, PTF3_IN, PTF2_FN, 0, 0, PTF2_IN, PTF1_FN, 0, 0, PTF1_IN, PTF0_FN, 0, 0, PTF0_IN } }, { PINMUX_CFG_REG("PGCR", 0xa405010c, 16, 2) { 0, 0, 0, 0, PTG6_FN, PTG6_OUT, 0, PTG6_IN, PTG5_FN, PTG5_OUT, 0, PTG5_IN, PTG4_FN, PTG4_OUT, 0, PTG4_IN, PTG3_FN, PTG3_OUT, 0, PTG3_IN, PTG2_FN, PTG2_OUT, 0, PTG2_IN, PTG1_FN, PTG1_OUT, 0, PTG1_IN, PTG0_FN, PTG0_OUT, 0, PTG0_IN } }, { PINMUX_CFG_REG("PHCR", 0xa405010e, 16, 2) { 0, 0, 0, 0, PTH6_FN, PTH6_OUT, 0, PTH6_IN, PTH5_FN, PTH5_OUT, 0, PTH5_IN, PTH4_FN, PTH4_OUT, 0, PTH4_IN, PTH3_FN, PTH3_OUT, 0, PTH3_IN, PTH2_FN, PTH2_OUT, 0, PTH2_IN, PTH1_FN, PTH1_OUT, 0, PTH1_IN, PTH0_FN, PTH0_OUT, 0, PTH0_IN } }, { PINMUX_CFG_REG("PJCR", 0xa4050110, 16, 2) { 0, 0, 0, 0, PTJ6_FN, PTJ6_OUT, 0, PTJ6_IN, PTJ5_FN, PTJ5_OUT, 0, PTJ5_IN, PTJ4_FN, PTJ4_OUT, 0, PTJ4_IN, PTJ3_FN, PTJ3_OUT, 0, PTJ3_IN, PTJ2_FN, PTJ2_OUT, 0, PTJ2_IN, PTJ1_FN, PTJ1_OUT, 0, PTJ1_IN, PTJ0_FN, PTJ0_OUT, 0, PTJ0_IN } }, { PINMUX_CFG_REG("PKCR", 0xa4050112, 16, 2) { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, PTK3_FN, PTK3_OUT, 0, PTK3_IN, PTK2_FN, PTK2_OUT, 0, PTK2_IN, PTK1_FN, PTK1_OUT, 0, PTK1_IN, PTK0_FN, PTK0_OUT, 0, PTK0_IN } }, { PINMUX_CFG_REG("PLCR", 0xa4050114, 16, 2) { PTL7_FN, PTL7_OUT, 0, PTL7_IN, PTL6_FN, PTL6_OUT, 0, PTL6_IN, PTL5_FN, PTL5_OUT, 0, PTL5_IN, PTL4_FN, PTL4_OUT, 0, PTL4_IN, PTL3_FN, PTL3_OUT, 0, PTL3_IN, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, { PINMUX_CFG_REG("PMCR", 0xa4050116, 16, 2) { PTM7_FN, PTM7_OUT, 0, PTM7_IN, PTM6_FN, PTM6_OUT, 0, PTM6_IN, PTM5_FN, PTM5_OUT, 0, PTM5_IN, PTM4_FN, PTM4_OUT, 0, PTM4_IN, PTM3_FN, PTM3_OUT, 0, PTM3_IN, PTM2_FN, PTM2_OUT, 0, PTM2_IN, PTM1_FN, PTM1_OUT, 0, PTM1_IN, PTM0_FN, PTM0_OUT, 0, PTM0_IN } }, { PINMUX_CFG_REG("PPCR", 0xa4050118, 16, 2) { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, PTP4_FN, PTP4_OUT, 0, PTP4_IN, PTP3_FN, PTP3_OUT, 0, PTP3_IN, PTP2_FN, PTP2_OUT, 0, PTP2_IN, PTP1_FN, PTP1_OUT, 0, PTP1_IN, PTP0_FN, PTP0_OUT, 0, PTP0_IN } }, { PINMUX_CFG_REG("PRCR", 0xa405011a, 16, 2) { PTR7_FN, PTR7_OUT, 0, PTR7_IN, PTR6_FN, PTR6_OUT, 0, PTR6_IN, PTR5_FN, PTR5_OUT, 0, PTR5_IN, PTR4_FN, PTR4_OUT, 0, PTR4_IN, PTR3_FN, PTR3_OUT, 0, PTR3_IN, PTR2_FN, PTR2_OUT, 0, PTR2_IN, PTR1_FN, PTR1_OUT, 0, PTR1_IN, PTR0_FN, PTR0_OUT, 0, PTR0_IN } }, { PINMUX_CFG_REG("PSCR", 0xa405011c, 16, 2) { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, PTS4_FN, PTS4_OUT, 0, PTS4_IN, PTS3_FN, PTS3_OUT, 0, PTS3_IN, PTS2_FN, PTS2_OUT, 0, PTS2_IN, PTS1_FN, PTS1_OUT, 0, PTS1_IN, PTS0_FN, PTS0_OUT, 0, PTS0_IN } }, { PINMUX_CFG_REG("PTCR", 0xa405011e, 16, 2) { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, PTT4_FN, PTT4_OUT, 0, PTT4_IN, PTT3_FN, PTT3_OUT, 0, PTT3_IN, PTT2_FN, PTT2_OUT, 0, PTT2_IN, PTT1_FN, PTT1_OUT, 0, PTT1_IN, PTT0_FN, PTT0_OUT, 0, PTT0_IN } }, { PINMUX_CFG_REG("PUCR", 0xa4050120, 16, 2) { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, PTU4_FN, PTU4_OUT, 0, PTU4_IN, PTU3_FN, PTU3_OUT, 0, PTU3_IN, PTU2_FN, PTU2_OUT, 0, PTU2_IN, PTU1_FN, PTU1_OUT, 0, PTU1_IN, PTU0_FN, PTU0_OUT, 0, PTU0_IN } }, { PINMUX_CFG_REG("PVCR", 0xa4050122, 16, 2) { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, PTV4_FN, PTV4_OUT, 0, PTV4_IN, PTV3_FN, PTV3_OUT, 0, PTV3_IN, PTV2_FN, PTV2_OUT, 0, PTV2_IN, PTV1_FN, PTV1_OUT, 0, PTV1_IN, PTV0_FN, PTV0_OUT, 0, PTV0_IN } }, {} }; static const struct pinmux_data_reg pinmux_data_regs[] = { { PINMUX_DATA_REG("PADR", 0xa4050140, 8) { PTA7_DATA, PTA6_DATA, PTA5_DATA, PTA4_DATA, PTA3_DATA, PTA2_DATA, PTA1_DATA, PTA0_DATA } }, { PINMUX_DATA_REG("PBDR", 0xa4050142, 8) { PTB7_DATA, PTB6_DATA, PTB5_DATA, PTB4_DATA, PTB3_DATA, PTB2_DATA, PTB1_DATA, PTB0_DATA } }, { PINMUX_DATA_REG("PCDR", 0xa4050144, 8) { PTC7_DATA, PTC6_DATA, PTC5_DATA, PTC4_DATA, PTC3_DATA, PTC2_DATA, PTC1_DATA, PTC0_DATA } }, { PINMUX_DATA_REG("PDDR", 0xa4050126, 8) { PTD7_DATA, PTD6_DATA, PTD5_DATA, PTD4_DATA, PTD3_DATA, PTD2_DATA, PTD1_DATA, PTD0_DATA } }, { PINMUX_DATA_REG("PEDR", 0xa4050148, 8) { 0, PTE6_DATA, PTE5_DATA, PTE4_DATA, PTE3_DATA, PTE2_DATA, PTE1_DATA, PTE0_DATA } }, { PINMUX_DATA_REG("PFDR", 0xa405014a, 8) { 0, PTF6_DATA, PTF5_DATA, PTF4_DATA, PTF3_DATA, PTF2_DATA, PTF1_DATA, PTF0_DATA } }, { PINMUX_DATA_REG("PGDR", 0xa405014c, 8) { 0, PTG6_DATA, PTG5_DATA, PTG4_DATA, PTG3_DATA, PTG2_DATA, PTG1_DATA, PTG0_DATA } }, { PINMUX_DATA_REG("PHDR", 0xa405014e, 8) { 0, PTH6_DATA, PTH5_DATA, PTH4_DATA, PTH3_DATA, PTH2_DATA, PTH1_DATA, PTH0_DATA } }, { PINMUX_DATA_REG("PJDR", 0xa4050150, 8) { 0, PTJ6_DATA, PTJ5_DATA, PTJ4_DATA, PTJ3_DATA, PTJ2_DATA, PTJ1_DATA, PTJ0_DATA } }, { PINMUX_DATA_REG("PKDR", 0xa4050152, 8) { 0, 0, 0, 0, PTK3_DATA, PTK2_DATA, PTK1_DATA, PTK0_DATA } }, { PINMUX_DATA_REG("PLDR", 0xa4050154, 8) { PTL7_DATA, PTL6_DATA, PTL5_DATA, PTL4_DATA, PTL3_DATA, 0, 0, 0 } }, { PINMUX_DATA_REG("PMDR", 0xa4050156, 8) { PTM7_DATA, PTM6_DATA, PTM5_DATA, PTM4_DATA, PTM3_DATA, PTM2_DATA, PTM1_DATA, PTM0_DATA } }, { PINMUX_DATA_REG("PPDR", 0xa4050158, 8) { 0, 0, 0, PTP4_DATA, PTP3_DATA, PTP2_DATA, PTP1_DATA, PTP0_DATA } }, { PINMUX_DATA_REG("PRDR", 0xa405015a, 8) { PTR7_DATA, PTR6_DATA, PTR5_DATA, PTR4_DATA, PTR3_DATA, PTR2_DATA, PTR1_DATA, PTR0_DATA } }, { PINMUX_DATA_REG("PSDR", 0xa405015c, 8) { 0, 0, 0, PTS4_DATA, PTS3_DATA, PTS2_DATA, PTS1_DATA, PTS0_DATA } }, { PINMUX_DATA_REG("PTDR", 0xa405015e, 8) { 0, 0, 0, PTT4_DATA, PTT3_DATA, PTT2_DATA, PTT1_DATA, PTT0_DATA } }, { PINMUX_DATA_REG("PUDR", 0xa4050160, 8) { 0, 0, 0, PTU4_DATA, PTU3_DATA, PTU2_DATA, PTU1_DATA, PTU0_DATA } }, { PINMUX_DATA_REG("PVDR", 0xa4050162, 8) { 0, 0, 0, PTV4_DATA, PTV3_DATA, PTV2_DATA, PTV1_DATA, PTV0_DATA } }, { }, }; const struct sh_pfc_soc_info sh7720_pinmux_info = { .name = "sh7720_pfc", .input = { PINMUX_INPUT_BEGIN, PINMUX_INPUT_END }, .output = { PINMUX_OUTPUT_BEGIN, PINMUX_OUTPUT_END }, .function = { PINMUX_FUNCTION_BEGIN, PINMUX_FUNCTION_END }, .pins = pinmux_pins, .nr_pins = ARRAY_SIZE(pinmux_pins), .func_gpios = pinmux_func_gpios, .nr_func_gpios = ARRAY_SIZE(pinmux_func_gpios), .cfg_regs = pinmux_config_regs, .data_regs = pinmux_data_regs, .pinmux_data = pinmux_data, .pinmux_data_size = ARRAY_SIZE(pinmux_data), };
null
null
null
null
104,370
11,486
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
176,481
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * Copyright 2015 Tilera Corporation. All Rights Reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation, version 2. * * 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, GOOD TITLE or * NON INFRINGEMENT. See the GNU General Public License for * more details. */ #ifndef __ASM_TILE_INSN_H #define __ASM_TILE_INSN_H #include <arch/opcode.h> static inline tilegx_bundle_bits NOP(void) { return create_UnaryOpcodeExtension_X0(FNOP_UNARY_OPCODE_X0) | create_RRROpcodeExtension_X0(UNARY_RRR_0_OPCODE_X0) | create_Opcode_X0(RRR_0_OPCODE_X0) | create_UnaryOpcodeExtension_X1(NOP_UNARY_OPCODE_X1) | create_RRROpcodeExtension_X1(UNARY_RRR_0_OPCODE_X1) | create_Opcode_X1(RRR_0_OPCODE_X1); } static inline tilegx_bundle_bits tilegx_gen_branch(unsigned long pc, unsigned long addr, bool link) { tilegx_bundle_bits opcode_x0, opcode_x1; long pcrel_by_instr = (addr - pc) >> TILEGX_LOG2_BUNDLE_SIZE_IN_BYTES; if (link) { /* opcode: jal addr */ opcode_x1 = create_Opcode_X1(JUMP_OPCODE_X1) | create_JumpOpcodeExtension_X1(JAL_JUMP_OPCODE_X1) | create_JumpOff_X1(pcrel_by_instr); } else { /* opcode: j addr */ opcode_x1 = create_Opcode_X1(JUMP_OPCODE_X1) | create_JumpOpcodeExtension_X1(J_JUMP_OPCODE_X1) | create_JumpOff_X1(pcrel_by_instr); } /* opcode: fnop */ opcode_x0 = create_UnaryOpcodeExtension_X0(FNOP_UNARY_OPCODE_X0) | create_RRROpcodeExtension_X0(UNARY_RRR_0_OPCODE_X0) | create_Opcode_X0(RRR_0_OPCODE_X0); return opcode_x1 | opcode_x0; } #endif /* __ASM_TILE_INSN_H */
null
null
null
null
84,828
20,978
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
185,973
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
#ifndef B43_RADIO_2057_H_ #define B43_RADIO_2057_H_ #include <linux/types.h> #include "tables_nphy.h" #define R2057_DACBUF_VINCM_CORE0 0x000 #define R2057_IDCODE 0x001 #define R2057_RCCAL_MASTER 0x002 #define R2057_RCCAL_CAP_SIZE 0x003 #define R2057_RCAL_CONFIG 0x004 #define R2057_GPAIO_CONFIG 0x005 #define R2057_GPAIO_SEL1 0x006 #define R2057_GPAIO_SEL0 0x007 #define R2057_CLPO_CONFIG 0x008 #define R2057_BANDGAP_CONFIG 0x009 #define R2057_BANDGAP_RCAL_TRIM 0x00a #define R2057_AFEREG_CONFIG 0x00b #define R2057_TEMPSENSE_CONFIG 0x00c #define R2057_XTAL_CONFIG1 0x00d #define R2057_XTAL_ICORE_SIZE 0x00e #define R2057_XTAL_BUF_SIZE 0x00f #define R2057_XTAL_PULLCAP_SIZE 0x010 #define R2057_RFPLL_MASTER 0x011 #define R2057_VCOMONITOR_VTH_L 0x012 #define R2057_VCOMONITOR_VTH_H 0x013 #define R2057_VCOCAL_BIASRESET_RFPLLREG_VOUT 0x014 #define R2057_VCO_VARCSIZE_IDAC 0x015 #define R2057_VCOCAL_COUNTVAL0 0x016 #define R2057_VCOCAL_COUNTVAL1 0x017 #define R2057_VCOCAL_INTCLK_COUNT 0x018 #define R2057_VCOCAL_MASTER 0x019 #define R2057_VCOCAL_NUMCAPCHANGE 0x01a #define R2057_VCOCAL_WINSIZE 0x01b #define R2057_VCOCAL_DELAY_AFTER_REFRESH 0x01c #define R2057_VCOCAL_DELAY_AFTER_CLOSELOOP 0x01d #define R2057_VCOCAL_DELAY_AFTER_OPENLOOP 0x01e #define R2057_VCOCAL_DELAY_BEFORE_OPENLOOP 0x01f #define R2057_VCO_FORCECAPEN_FORCECAP1 0x020 #define R2057_VCO_FORCECAP0 0x021 #define R2057_RFPLL_REFMASTER_SPAREXTALSIZE 0x022 #define R2057_RFPLL_PFD_RESET_PW 0x023 #define R2057_RFPLL_LOOPFILTER_R2 0x024 #define R2057_RFPLL_LOOPFILTER_R1 0x025 #define R2057_RFPLL_LOOPFILTER_C3 0x026 #define R2057_RFPLL_LOOPFILTER_C2 0x027 #define R2057_RFPLL_LOOPFILTER_C1 0x028 #define R2057_CP_KPD_IDAC 0x029 #define R2057_RFPLL_IDACS 0x02a #define R2057_RFPLL_MISC_EN 0x02b #define R2057_RFPLL_MMD0 0x02c #define R2057_RFPLL_MMD1 0x02d #define R2057_RFPLL_MISC_CAL_RESETN 0x02e #define R2057_JTAGXTAL_SIZE_CPBIAS_FILTRES 0x02f #define R2057_VCO_ALCREF_BBPLLXTAL_SIZE 0x030 #define R2057_VCOCAL_READCAP0 0x031 #define R2057_VCOCAL_READCAP1 0x032 #define R2057_VCOCAL_STATUS 0x033 #define R2057_LOGEN_PUS 0x034 #define R2057_LOGEN_PTAT_RESETS 0x035 #define R2057_VCOBUF_IDACS 0x036 #define R2057_VCOBUF_TUNE 0x037 #define R2057_CMOSBUF_TX2GQ_IDACS 0x038 #define R2057_CMOSBUF_TX2GI_IDACS 0x039 #define R2057_CMOSBUF_TX5GQ_IDACS 0x03a #define R2057_CMOSBUF_TX5GI_IDACS 0x03b #define R2057_CMOSBUF_RX2GQ_IDACS 0x03c #define R2057_CMOSBUF_RX2GI_IDACS 0x03d #define R2057_CMOSBUF_RX5GQ_IDACS 0x03e #define R2057_CMOSBUF_RX5GI_IDACS 0x03f #define R2057_LOGEN_MX2G_IDACS 0x040 #define R2057_LOGEN_MX2G_TUNE 0x041 #define R2057_LOGEN_MX5G_IDACS 0x042 #define R2057_LOGEN_MX5G_TUNE 0x043 #define R2057_LOGEN_MX5G_RCCR 0x044 #define R2057_LOGEN_INDBUF2G_IDAC 0x045 #define R2057_LOGEN_INDBUF2G_IBOOST 0x046 #define R2057_LOGEN_INDBUF2G_TUNE 0x047 #define R2057_LOGEN_INDBUF5G_IDAC 0x048 #define R2057_LOGEN_INDBUF5G_IBOOST 0x049 #define R2057_LOGEN_INDBUF5G_TUNE 0x04a #define R2057_CMOSBUF_TX_RCCR 0x04b #define R2057_CMOSBUF_RX_RCCR 0x04c #define R2057_LOGEN_SEL_PKDET 0x04d #define R2057_CMOSBUF_SHAREIQ_PTAT 0x04e /* MISC core 0 */ #define R2057_RXTXBIAS_CONFIG_CORE0 0x04f #define R2057_TXGM_TXRF_PUS_CORE0 0x050 #define R2057_TXGM_IDAC_BLEED_CORE0 0x051 #define R2057_TXGM_GAIN_CORE0 0x056 #define R2057_TXGM2G_PKDET_PUS_CORE0 0x057 #define R2057_PAD2G_PTATS_CORE0 0x058 #define R2057_PAD2G_IDACS_CORE0 0x059 #define R2057_PAD2G_BOOST_PU_CORE0 0x05a #define R2057_PAD2G_CASCV_GAIN_CORE0 0x05b #define R2057_TXMIX2G_TUNE_BOOST_PU_CORE0 0x05c #define R2057_TXMIX2G_LODC_CORE0 0x05d #define R2057_PAD2G_TUNE_PUS_CORE0 0x05e #define R2057_IPA2G_GAIN_CORE0 0x05f #define R2057_TSSI2G_SPARE1_CORE0 0x060 #define R2057_TSSI2G_SPARE2_CORE0 0x061 #define R2057_IPA2G_TUNEV_CASCV_PTAT_CORE0 0x062 #define R2057_IPA2G_IMAIN_CORE0 0x063 #define R2057_IPA2G_CASCONV_CORE0 0x064 #define R2057_IPA2G_CASCOFFV_CORE0 0x065 #define R2057_IPA2G_BIAS_FILTER_CORE0 0x066 #define R2057_TX5G_PKDET_CORE0 0x069 #define R2057_PGA_PTAT_TXGM5G_PU_CORE0 0x06a #define R2057_PAD5G_PTATS1_CORE0 0x06b #define R2057_PAD5G_CLASS_PTATS2_CORE0 0x06c #define R2057_PGA_BOOSTPTAT_IMAIN_CORE0 0x06d #define R2057_PAD5G_CASCV_IMAIN_CORE0 0x06e #define R2057_TXMIX5G_IBOOST_PAD_IAUX_CORE0 0x06f #define R2057_PGA_BOOST_TUNE_CORE0 0x070 #define R2057_PGA_GAIN_CORE0 0x071 #define R2057_PAD5G_CASCOFFV_GAIN_PUS_CORE0 0x072 #define R2057_TXMIX5G_BOOST_TUNE_CORE0 0x073 #define R2057_PAD5G_TUNE_MISC_PUS_CORE0 0x074 #define R2057_IPA5G_IAUX_CORE0 0x075 #define R2057_IPA5G_GAIN_CORE0 0x076 #define R2057_TSSI5G_SPARE1_CORE0 0x077 #define R2057_TSSI5G_SPARE2_CORE0 0x078 #define R2057_IPA5G_CASCOFFV_PU_CORE0 0x079 #define R2057_IPA5G_PTAT_CORE0 0x07a #define R2057_IPA5G_IMAIN_CORE0 0x07b #define R2057_IPA5G_CASCONV_CORE0 0x07c #define R2057_IPA5G_BIAS_FILTER_CORE0 0x07d #define R2057_PAD_BIAS_FILTER_BWS_CORE0 0x080 #define R2057_TR2G_CONFIG1_CORE0_NU 0x081 #define R2057_TR2G_CONFIG2_CORE0_NU 0x082 #define R2057_LNA5G_RFEN_CORE0 0x083 #define R2057_TR5G_CONFIG2_CORE0_NU 0x084 #define R2057_RXRFBIAS_IBOOST_PU_CORE0 0x085 #define R2057_RXRF_IABAND_RXGM_IMAIN_PTAT_CORE0 0x086 #define R2057_RXGM_CMFBITAIL_AUXPTAT_CORE0 0x087 #define R2057_RXMIX_ICORE_RXGM_IAUX_CORE0 0x088 #define R2057_RXMIX_CMFBITAIL_PU_CORE0 0x089 #define R2057_LNA2_IMAIN_PTAT_PU_CORE0 0x08a #define R2057_LNA2_IAUX_PTAT_CORE0 0x08b #define R2057_LNA1_IMAIN_PTAT_PU_CORE0 0x08c #define R2057_LNA15G_INPUT_MATCH_TUNE_CORE0 0x08d #define R2057_RXRFBIAS_BANDSEL_CORE0 0x08e #define R2057_TIA_CONFIG_CORE0 0x08f #define R2057_TIA_IQGAIN_CORE0 0x090 #define R2057_TIA_IBIAS2_CORE0 0x091 #define R2057_TIA_IBIAS1_CORE0 0x092 #define R2057_TIA_SPARE_Q_CORE0 0x093 #define R2057_TIA_SPARE_I_CORE0 0x094 #define R2057_RXMIX2G_PUS_CORE0 0x095 #define R2057_RXMIX2G_VCMREFS_CORE0 0x096 #define R2057_RXMIX2G_LODC_QI_CORE0 0x097 #define R2057_W12G_BW_LNA2G_PUS_CORE0 0x098 #define R2057_LNA2G_GAIN_CORE0 0x099 #define R2057_LNA2G_TUNE_CORE0 0x09a #define R2057_RXMIX5G_PUS_CORE0 0x09b #define R2057_RXMIX5G_VCMREFS_CORE0 0x09c #define R2057_RXMIX5G_LODC_QI_CORE0 0x09d #define R2057_W15G_BW_LNA5G_PUS_CORE0 0x09e #define R2057_LNA5G_GAIN_CORE0 0x09f #define R2057_LNA5G_TUNE_CORE0 0x0a0 #define R2057_LPFSEL_TXRX_RXBB_PUS_CORE0 0x0a1 #define R2057_RXBB_BIAS_MASTER_CORE0 0x0a2 #define R2057_RXBB_VGABUF_IDACS_CORE0 0x0a3 #define R2057_LPF_VCMREF_TXBUF_VCMREF_CORE0 0x0a4 #define R2057_TXBUF_VINCM_CORE0 0x0a5 #define R2057_TXBUF_IDACS_CORE0 0x0a6 #define R2057_LPF_RESP_RXBUF_BW_CORE0 0x0a7 #define R2057_RXBB_CC_CORE0 0x0a8 #define R2057_RXBB_SPARE3_CORE0 0x0a9 #define R2057_RXBB_RCCAL_HPC_CORE0 0x0aa #define R2057_LPF_IDACS_CORE0 0x0ab #define R2057_LPFBYP_DCLOOP_BYP_IDAC_CORE0 0x0ac #define R2057_TXBUF_GAIN_CORE0 0x0ad #define R2057_AFELOOPBACK_AACI_RESP_CORE0 0x0ae #define R2057_RXBUF_DEGEN_CORE0 0x0af #define R2057_RXBB_SPARE2_CORE0 0x0b0 #define R2057_RXBB_SPARE1_CORE0 0x0b1 #define R2057_RSSI_MASTER_CORE0 0x0b2 #define R2057_W2_MASTER_CORE0 0x0b3 #define R2057_NB_MASTER_CORE0 0x0b4 #define R2057_W2_IDACS0_Q_CORE0 0x0b5 #define R2057_W2_IDACS1_Q_CORE0 0x0b6 #define R2057_W2_IDACS0_I_CORE0 0x0b7 #define R2057_W2_IDACS1_I_CORE0 0x0b8 #define R2057_RSSI_GPAIOSEL_W1_IDACS_CORE0 0x0b9 #define R2057_NB_IDACS_Q_CORE0 0x0ba #define R2057_NB_IDACS_I_CORE0 0x0bb #define R2057_BACKUP4_CORE0 0x0c1 #define R2057_BACKUP3_CORE0 0x0c2 #define R2057_BACKUP2_CORE0 0x0c3 #define R2057_BACKUP1_CORE0 0x0c4 #define R2057_SPARE16_CORE0 0x0c5 #define R2057_SPARE15_CORE0 0x0c6 #define R2057_SPARE14_CORE0 0x0c7 #define R2057_SPARE13_CORE0 0x0c8 #define R2057_SPARE12_CORE0 0x0c9 #define R2057_SPARE11_CORE0 0x0ca #define R2057_TX2G_BIAS_RESETS_CORE0 0x0cb #define R2057_TX5G_BIAS_RESETS_CORE0 0x0cc #define R2057_IQTEST_SEL_PU 0x0cd #define R2057_XTAL_CONFIG2 0x0ce #define R2057_BUFS_MISC_LPFBW_CORE0 0x0cf #define R2057_TXLPF_RCCAL_CORE0 0x0d0 #define R2057_RXBB_GPAIOSEL_RXLPF_RCCAL_CORE0 0x0d1 #define R2057_LPF_GAIN_CORE0 0x0d2 #define R2057_DACBUF_IDACS_BW_CORE0 0x0d3 /* MISC core 1 */ #define R2057_RXTXBIAS_CONFIG_CORE1 0x0d4 #define R2057_TXGM_TXRF_PUS_CORE1 0x0d5 #define R2057_TXGM_IDAC_BLEED_CORE1 0x0d6 #define R2057_TXGM_GAIN_CORE1 0x0db #define R2057_TXGM2G_PKDET_PUS_CORE1 0x0dc #define R2057_PAD2G_PTATS_CORE1 0x0dd #define R2057_PAD2G_IDACS_CORE1 0x0de #define R2057_PAD2G_BOOST_PU_CORE1 0x0df #define R2057_PAD2G_CASCV_GAIN_CORE1 0x0e0 #define R2057_TXMIX2G_TUNE_BOOST_PU_CORE1 0x0e1 #define R2057_TXMIX2G_LODC_CORE1 0x0e2 #define R2057_PAD2G_TUNE_PUS_CORE1 0x0e3 #define R2057_IPA2G_GAIN_CORE1 0x0e4 #define R2057_TSSI2G_SPARE1_CORE1 0x0e5 #define R2057_TSSI2G_SPARE2_CORE1 0x0e6 #define R2057_IPA2G_TUNEV_CASCV_PTAT_CORE1 0x0e7 #define R2057_IPA2G_IMAIN_CORE1 0x0e8 #define R2057_IPA2G_CASCONV_CORE1 0x0e9 #define R2057_IPA2G_CASCOFFV_CORE1 0x0ea #define R2057_IPA2G_BIAS_FILTER_CORE1 0x0eb #define R2057_TX5G_PKDET_CORE1 0x0ee #define R2057_PGA_PTAT_TXGM5G_PU_CORE1 0x0ef #define R2057_PAD5G_PTATS1_CORE1 0x0f0 #define R2057_PAD5G_CLASS_PTATS2_CORE1 0x0f1 #define R2057_PGA_BOOSTPTAT_IMAIN_CORE1 0x0f2 #define R2057_PAD5G_CASCV_IMAIN_CORE1 0x0f3 #define R2057_TXMIX5G_IBOOST_PAD_IAUX_CORE1 0x0f4 #define R2057_PGA_BOOST_TUNE_CORE1 0x0f5 #define R2057_PGA_GAIN_CORE1 0x0f6 #define R2057_PAD5G_CASCOFFV_GAIN_PUS_CORE1 0x0f7 #define R2057_TXMIX5G_BOOST_TUNE_CORE1 0x0f8 #define R2057_PAD5G_TUNE_MISC_PUS_CORE1 0x0f9 #define R2057_IPA5G_IAUX_CORE1 0x0fa #define R2057_IPA5G_GAIN_CORE1 0x0fb #define R2057_TSSI5G_SPARE1_CORE1 0x0fc #define R2057_TSSI5G_SPARE2_CORE1 0x0fd #define R2057_IPA5G_CASCOFFV_PU_CORE1 0x0fe #define R2057_IPA5G_PTAT_CORE1 0x0ff #define R2057_IPA5G_IMAIN_CORE1 0x100 #define R2057_IPA5G_CASCONV_CORE1 0x101 #define R2057_IPA5G_BIAS_FILTER_CORE1 0x102 #define R2057_PAD_BIAS_FILTER_BWS_CORE1 0x105 #define R2057_TR2G_CONFIG1_CORE1_NU 0x106 #define R2057_TR2G_CONFIG2_CORE1_NU 0x107 #define R2057_LNA5G_RFEN_CORE1 0x108 #define R2057_TR5G_CONFIG2_CORE1_NU 0x109 #define R2057_RXRFBIAS_IBOOST_PU_CORE1 0x10a #define R2057_RXRF_IABAND_RXGM_IMAIN_PTAT_CORE1 0x10b #define R2057_RXGM_CMFBITAIL_AUXPTAT_CORE1 0x10c #define R2057_RXMIX_ICORE_RXGM_IAUX_CORE1 0x10d #define R2057_RXMIX_CMFBITAIL_PU_CORE1 0x10e #define R2057_LNA2_IMAIN_PTAT_PU_CORE1 0x10f #define R2057_LNA2_IAUX_PTAT_CORE1 0x110 #define R2057_LNA1_IMAIN_PTAT_PU_CORE1 0x111 #define R2057_LNA15G_INPUT_MATCH_TUNE_CORE1 0x112 #define R2057_RXRFBIAS_BANDSEL_CORE1 0x113 #define R2057_TIA_CONFIG_CORE1 0x114 #define R2057_TIA_IQGAIN_CORE1 0x115 #define R2057_TIA_IBIAS2_CORE1 0x116 #define R2057_TIA_IBIAS1_CORE1 0x117 #define R2057_TIA_SPARE_Q_CORE1 0x118 #define R2057_TIA_SPARE_I_CORE1 0x119 #define R2057_RXMIX2G_PUS_CORE1 0x11a #define R2057_RXMIX2G_VCMREFS_CORE1 0x11b #define R2057_RXMIX2G_LODC_QI_CORE1 0x11c #define R2057_W12G_BW_LNA2G_PUS_CORE1 0x11d #define R2057_LNA2G_GAIN_CORE1 0x11e #define R2057_LNA2G_TUNE_CORE1 0x11f #define R2057_RXMIX5G_PUS_CORE1 0x120 #define R2057_RXMIX5G_VCMREFS_CORE1 0x121 #define R2057_RXMIX5G_LODC_QI_CORE1 0x122 #define R2057_W15G_BW_LNA5G_PUS_CORE1 0x123 #define R2057_LNA5G_GAIN_CORE1 0x124 #define R2057_LNA5G_TUNE_CORE1 0x125 #define R2057_LPFSEL_TXRX_RXBB_PUS_CORE1 0x126 #define R2057_RXBB_BIAS_MASTER_CORE1 0x127 #define R2057_RXBB_VGABUF_IDACS_CORE1 0x128 #define R2057_LPF_VCMREF_TXBUF_VCMREF_CORE1 0x129 #define R2057_TXBUF_VINCM_CORE1 0x12a #define R2057_TXBUF_IDACS_CORE1 0x12b #define R2057_LPF_RESP_RXBUF_BW_CORE1 0x12c #define R2057_RXBB_CC_CORE1 0x12d #define R2057_RXBB_SPARE3_CORE1 0x12e #define R2057_RXBB_RCCAL_HPC_CORE1 0x12f #define R2057_LPF_IDACS_CORE1 0x130 #define R2057_LPFBYP_DCLOOP_BYP_IDAC_CORE1 0x131 #define R2057_TXBUF_GAIN_CORE1 0x132 #define R2057_AFELOOPBACK_AACI_RESP_CORE1 0x133 #define R2057_RXBUF_DEGEN_CORE1 0x134 #define R2057_RXBB_SPARE2_CORE1 0x135 #define R2057_RXBB_SPARE1_CORE1 0x136 #define R2057_RSSI_MASTER_CORE1 0x137 #define R2057_W2_MASTER_CORE1 0x138 #define R2057_NB_MASTER_CORE1 0x139 #define R2057_W2_IDACS0_Q_CORE1 0x13a #define R2057_W2_IDACS1_Q_CORE1 0x13b #define R2057_W2_IDACS0_I_CORE1 0x13c #define R2057_W2_IDACS1_I_CORE1 0x13d #define R2057_RSSI_GPAIOSEL_W1_IDACS_CORE1 0x13e #define R2057_NB_IDACS_Q_CORE1 0x13f #define R2057_NB_IDACS_I_CORE1 0x140 #define R2057_BACKUP4_CORE1 0x146 #define R2057_BACKUP3_CORE1 0x147 #define R2057_BACKUP2_CORE1 0x148 #define R2057_BACKUP1_CORE1 0x149 #define R2057_SPARE16_CORE1 0x14a #define R2057_SPARE15_CORE1 0x14b #define R2057_SPARE14_CORE1 0x14c #define R2057_SPARE13_CORE1 0x14d #define R2057_SPARE12_CORE1 0x14e #define R2057_SPARE11_CORE1 0x14f #define R2057_TX2G_BIAS_RESETS_CORE1 0x150 #define R2057_TX5G_BIAS_RESETS_CORE1 0x151 #define R2057_SPARE8_CORE1 0x152 #define R2057_SPARE7_CORE1 0x153 #define R2057_BUFS_MISC_LPFBW_CORE1 0x154 #define R2057_TXLPF_RCCAL_CORE1 0x155 #define R2057_RXBB_GPAIOSEL_RXLPF_RCCAL_CORE1 0x156 #define R2057_LPF_GAIN_CORE1 0x157 #define R2057_DACBUF_IDACS_BW_CORE1 0x158 #define R2057_DACBUF_VINCM_CORE1 0x159 #define R2057_RCCAL_START_R1_Q1_P1 0x15a #define R2057_RCCAL_X1 0x15b #define R2057_RCCAL_TRC0 0x15c #define R2057_RCCAL_TRC1 0x15d #define R2057_RCCAL_DONE_OSCCAP 0x15e #define R2057_RCCAL_N0_0 0x15f #define R2057_RCCAL_N0_1 0x160 #define R2057_RCCAL_N1_0 0x161 #define R2057_RCCAL_N1_1 0x162 #define R2057_RCAL_STATUS 0x163 #define R2057_XTALPUOVR_PINCTRL 0x164 #define R2057_OVR_REG0 0x165 #define R2057_OVR_REG1 0x166 #define R2057_OVR_REG2 0x167 #define R2057_OVR_REG3 0x168 #define R2057_OVR_REG4 0x169 #define R2057_RCCAL_SCAP_VAL 0x16a #define R2057_RCCAL_BCAP_VAL 0x16b #define R2057_RCCAL_HPC_VAL 0x16c #define R2057_RCCAL_OVERRIDES 0x16d /* TX core 0 */ #define R2057_TX0_IQCAL_GAIN_BW 0x170 #define R2057_TX0_LOFT_FINE_I 0x171 #define R2057_TX0_LOFT_FINE_Q 0x172 #define R2057_TX0_LOFT_COARSE_I 0x173 #define R2057_TX0_LOFT_COARSE_Q 0x174 #define R2057_TX0_TX_SSI_MASTER 0x175 #define R2057_TX0_IQCAL_VCM_HG 0x176 #define R2057_TX0_IQCAL_IDAC 0x177 #define R2057_TX0_TSSI_VCM 0x178 #define R2057_TX0_TX_SSI_MUX 0x179 #define R2057_TX0_TSSIA 0x17a #define R2057_TX0_TSSIG 0x17b #define R2057_TX0_TSSI_MISC1 0x17c #define R2057_TX0_TXRXCOUPLE_2G_ATTEN 0x17d #define R2057_TX0_TXRXCOUPLE_2G_PWRUP 0x17e #define R2057_TX0_TXRXCOUPLE_5G_ATTEN 0x17f #define R2057_TX0_TXRXCOUPLE_5G_PWRUP 0x180 /* TX core 1 */ #define R2057_TX1_IQCAL_GAIN_BW 0x190 #define R2057_TX1_LOFT_FINE_I 0x191 #define R2057_TX1_LOFT_FINE_Q 0x192 #define R2057_TX1_LOFT_COARSE_I 0x193 #define R2057_TX1_LOFT_COARSE_Q 0x194 #define R2057_TX1_TX_SSI_MASTER 0x195 #define R2057_TX1_IQCAL_VCM_HG 0x196 #define R2057_TX1_IQCAL_IDAC 0x197 #define R2057_TX1_TSSI_VCM 0x198 #define R2057_TX1_TX_SSI_MUX 0x199 #define R2057_TX1_TSSIA 0x19a #define R2057_TX1_TSSIG 0x19b #define R2057_TX1_TSSI_MISC1 0x19c #define R2057_TX1_TXRXCOUPLE_2G_ATTEN 0x19d #define R2057_TX1_TXRXCOUPLE_2G_PWRUP 0x19e #define R2057_TX1_TXRXCOUPLE_5G_ATTEN 0x19f #define R2057_TX1_TXRXCOUPLE_5G_PWRUP 0x1a0 #define R2057_AFE_VCM_CAL_MASTER_CORE0 0x1a1 #define R2057_AFE_SET_VCM_I_CORE0 0x1a2 #define R2057_AFE_SET_VCM_Q_CORE0 0x1a3 #define R2057_AFE_STATUS_VCM_IQADC_CORE0 0x1a4 #define R2057_AFE_STATUS_VCM_I_CORE0 0x1a5 #define R2057_AFE_STATUS_VCM_Q_CORE0 0x1a6 #define R2057_AFE_VCM_CAL_MASTER_CORE1 0x1a7 #define R2057_AFE_SET_VCM_I_CORE1 0x1a8 #define R2057_AFE_SET_VCM_Q_CORE1 0x1a9 #define R2057_AFE_STATUS_VCM_IQADC_CORE1 0x1aa #define R2057_AFE_STATUS_VCM_I_CORE1 0x1ab #define R2057_AFE_STATUS_VCM_Q_CORE1 0x1ac #define R2057v7_DACBUF_VINCM_CORE0 0x1ad #define R2057v7_RCCAL_MASTER 0x1ae #define R2057v7_TR2G_CONFIG3_CORE0_NU 0x1af #define R2057v7_TR2G_CONFIG3_CORE1_NU 0x1b0 #define R2057v7_LOGEN_PUS1 0x1b1 #define R2057v7_OVR_REG5 0x1b2 #define R2057v7_OVR_REG6 0x1b3 #define R2057v7_OVR_REG7 0x1b4 #define R2057v7_OVR_REG8 0x1b5 #define R2057v7_OVR_REG9 0x1b6 #define R2057v7_OVR_REG10 0x1b7 #define R2057v7_OVR_REG11 0x1b8 #define R2057v7_OVR_REG12 0x1b9 #define R2057v7_OVR_REG13 0x1ba #define R2057v7_OVR_REG14 0x1bb #define R2057v7_OVR_REG15 0x1bc #define R2057v7_OVR_REG16 0x1bd #define R2057v7_OVR_REG1 0x1be #define R2057v7_OVR_REG18 0x1bf #define R2057v7_OVR_REG19 0x1c0 #define R2057v7_OVR_REG20 0x1c1 #define R2057v7_OVR_REG21 0x1c2 #define R2057v7_OVR_REG2 0x1c3 #define R2057v7_OVR_REG23 0x1c4 #define R2057v7_OVR_REG24 0x1c5 #define R2057v7_OVR_REG25 0x1c6 #define R2057v7_OVR_REG26 0x1c7 #define R2057v7_OVR_REG27 0x1c8 #define R2057v7_OVR_REG28 0x1c9 #define R2057v7_IQTEST_SEL_PU2 0x1ca #define R2057_VCM_MASK 0x7 struct b43_nphy_chantabent_rev7 { /* The channel frequency in MHz */ u16 freq; /* Radio regs values on channelswitch */ u8 radio_vcocal_countval0; u8 radio_vcocal_countval1; u8 radio_rfpll_refmaster_sparextalsize; u8 radio_rfpll_loopfilter_r1; u8 radio_rfpll_loopfilter_c2; u8 radio_rfpll_loopfilter_c1; u8 radio_cp_kpd_idac; u8 radio_rfpll_mmd0; u8 radio_rfpll_mmd1; u8 radio_vcobuf_tune; u8 radio_logen_mx2g_tune; u8 radio_logen_mx5g_tune; u8 radio_logen_indbuf2g_tune; u8 radio_logen_indbuf5g_tune; u8 radio_txmix2g_tune_boost_pu_core0; u8 radio_pad2g_tune_pus_core0; u8 radio_pga_boost_tune_core0; u8 radio_txmix5g_boost_tune_core0; u8 radio_pad5g_tune_misc_pus_core0; u8 radio_lna2g_tune_core0; u8 radio_lna5g_tune_core0; u8 radio_txmix2g_tune_boost_pu_core1; u8 radio_pad2g_tune_pus_core1; u8 radio_pga_boost_tune_core1; u8 radio_txmix5g_boost_tune_core1; u8 radio_pad5g_tune_misc_pus_core1; u8 radio_lna2g_tune_core1; u8 radio_lna5g_tune_core1; /* PHY res values on channelswitch */ struct b43_phy_n_sfo_cfg phy_regs; }; struct b43_nphy_chantabent_rev7_2g { /* The channel frequency in MHz */ u16 freq; /* Radio regs values on channelswitch */ u8 radio_vcocal_countval0; u8 radio_vcocal_countval1; u8 radio_rfpll_refmaster_sparextalsize; u8 radio_rfpll_loopfilter_r1; u8 radio_rfpll_loopfilter_c2; u8 radio_rfpll_loopfilter_c1; u8 radio_cp_kpd_idac; u8 radio_rfpll_mmd0; u8 radio_rfpll_mmd1; u8 radio_vcobuf_tune; u8 radio_logen_mx2g_tune; u8 radio_logen_indbuf2g_tune; u8 radio_txmix2g_tune_boost_pu_core0; u8 radio_pad2g_tune_pus_core0; u8 radio_lna2g_tune_core0; u8 radio_txmix2g_tune_boost_pu_core1; u8 radio_pad2g_tune_pus_core1; u8 radio_lna2g_tune_core1; /* PHY regs values on channelswitch */ struct b43_phy_n_sfo_cfg phy_regs; }; void r2057_upload_inittabs(struct b43_wldev *dev); void r2057_get_chantabent_rev7(struct b43_wldev *dev, u16 freq, const struct b43_nphy_chantabent_rev7 **tabent_r7, const struct b43_nphy_chantabent_rev7_2g **tabent_r7_2g); #endif /* B43_RADIO_2057_H_ */
null
null
null
null
94,320
33,007
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
33,007
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
/* * Copyright (C) 2012 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "third_party/blink/renderer/core/inspector/dom_editor.h" #include "base/macros.h" #include "base/memory/scoped_refptr.h" #include "third_party/blink/renderer/bindings/core/v8/exception_state.h" #include "third_party/blink/renderer/core/dom/document.h" #include "third_party/blink/renderer/core/dom/dom_exception.h" #include "third_party/blink/renderer/core/dom/element.h" #include "third_party/blink/renderer/core/dom/node.h" #include "third_party/blink/renderer/core/dom/text.h" #include "third_party/blink/renderer/core/editing/serializers/serialization.h" #include "third_party/blink/renderer/core/inspector/dom_patch_support.h" #include "third_party/blink/renderer/core/inspector/inspector_history.h" #include "third_party/blink/renderer/core/inspector/protocol/Protocol.h" namespace blink { using protocol::Response; class DOMEditor::RemoveChildAction final : public InspectorHistory::Action { public: RemoveChildAction(ContainerNode* parent_node, Node* node) : InspectorHistory::Action("RemoveChild"), parent_node_(parent_node), node_(node) {} bool Perform(ExceptionState& exception_state) override { anchor_node_ = node_->nextSibling(); return Redo(exception_state); } bool Undo(ExceptionState& exception_state) override { parent_node_->InsertBefore(node_.Get(), anchor_node_.Get(), exception_state); return !exception_state.HadException(); } bool Redo(ExceptionState& exception_state) override { parent_node_->RemoveChild(node_.Get(), exception_state); return !exception_state.HadException(); } void Trace(blink::Visitor* visitor) override { visitor->Trace(parent_node_); visitor->Trace(node_); visitor->Trace(anchor_node_); InspectorHistory::Action::Trace(visitor); } private: Member<ContainerNode> parent_node_; Member<Node> node_; Member<Node> anchor_node_; DISALLOW_COPY_AND_ASSIGN(RemoveChildAction); }; class DOMEditor::InsertBeforeAction final : public InspectorHistory::Action { public: InsertBeforeAction(ContainerNode* parent_node, Node* node, Node* anchor_node) : InspectorHistory::Action("InsertBefore"), parent_node_(parent_node), node_(node), anchor_node_(anchor_node) {} bool Perform(ExceptionState& exception_state) override { if (node_->parentNode()) { remove_child_action_ = new RemoveChildAction(node_->parentNode(), node_.Get()); if (!remove_child_action_->Perform(exception_state)) return false; } parent_node_->InsertBefore(node_.Get(), anchor_node_.Get(), exception_state); return !exception_state.HadException(); } bool Undo(ExceptionState& exception_state) override { parent_node_->RemoveChild(node_.Get(), exception_state); if (exception_state.HadException()) return false; if (remove_child_action_) return remove_child_action_->Undo(exception_state); return true; } bool Redo(ExceptionState& exception_state) override { if (remove_child_action_ && !remove_child_action_->Redo(exception_state)) return false; parent_node_->InsertBefore(node_.Get(), anchor_node_.Get(), exception_state); return !exception_state.HadException(); } void Trace(blink::Visitor* visitor) override { visitor->Trace(parent_node_); visitor->Trace(node_); visitor->Trace(anchor_node_); visitor->Trace(remove_child_action_); InspectorHistory::Action::Trace(visitor); } private: Member<ContainerNode> parent_node_; Member<Node> node_; Member<Node> anchor_node_; Member<RemoveChildAction> remove_child_action_; DISALLOW_COPY_AND_ASSIGN(InsertBeforeAction); }; class DOMEditor::RemoveAttributeAction final : public InspectorHistory::Action { public: RemoveAttributeAction(Element* element, const AtomicString& name) : InspectorHistory::Action("RemoveAttribute"), element_(element), name_(name) {} bool Perform(ExceptionState& exception_state) override { value_ = element_->getAttribute(name_); return Redo(exception_state); } bool Undo(ExceptionState& exception_state) override { element_->setAttribute(name_, value_, exception_state); return true; } bool Redo(ExceptionState&) override { element_->removeAttribute(name_); return true; } void Trace(blink::Visitor* visitor) override { visitor->Trace(element_); InspectorHistory::Action::Trace(visitor); } private: Member<Element> element_; AtomicString name_; AtomicString value_; DISALLOW_COPY_AND_ASSIGN(RemoveAttributeAction); }; class DOMEditor::SetAttributeAction final : public InspectorHistory::Action { public: SetAttributeAction(Element* element, const AtomicString& name, const AtomicString& value) : InspectorHistory::Action("SetAttribute"), element_(element), name_(name), value_(value), had_attribute_(false) {} bool Perform(ExceptionState& exception_state) override { const AtomicString& value = element_->getAttribute(name_); had_attribute_ = !value.IsNull(); if (had_attribute_) old_value_ = value; return Redo(exception_state); } bool Undo(ExceptionState& exception_state) override { if (had_attribute_) element_->setAttribute(name_, old_value_, exception_state); else element_->removeAttribute(name_); return true; } bool Redo(ExceptionState& exception_state) override { element_->setAttribute(name_, value_, exception_state); return true; } void Trace(blink::Visitor* visitor) override { visitor->Trace(element_); InspectorHistory::Action::Trace(visitor); } private: Member<Element> element_; AtomicString name_; AtomicString value_; bool had_attribute_; AtomicString old_value_; DISALLOW_COPY_AND_ASSIGN(SetAttributeAction); }; class DOMEditor::SetOuterHTMLAction final : public InspectorHistory::Action { public: SetOuterHTMLAction(Node* node, const String& html) : InspectorHistory::Action("SetOuterHTML"), node_(node), next_sibling_(node->nextSibling()), html_(html), new_node_(nullptr), history_(new InspectorHistory()), dom_editor_(new DOMEditor(history_.Get())) {} bool Perform(ExceptionState& exception_state) override { old_html_ = CreateMarkup(node_.Get()); Document* document = node_->IsDocumentNode() ? ToDocument(node_) : node_->ownerDocument(); DCHECK(document); if (!document->documentElement()) return false; DOMPatchSupport dom_patch_support(dom_editor_.Get(), *document); new_node_ = dom_patch_support.PatchNode(node_.Get(), html_, exception_state); return !exception_state.HadException(); } bool Undo(ExceptionState& exception_state) override { return history_->Undo(exception_state); } bool Redo(ExceptionState& exception_state) override { return history_->Redo(exception_state); } Node* NewNode() { return new_node_; } void Trace(blink::Visitor* visitor) override { visitor->Trace(node_); visitor->Trace(next_sibling_); visitor->Trace(new_node_); visitor->Trace(history_); visitor->Trace(dom_editor_); InspectorHistory::Action::Trace(visitor); } private: Member<Node> node_; Member<Node> next_sibling_; String html_; String old_html_; Member<Node> new_node_; Member<InspectorHistory> history_; Member<DOMEditor> dom_editor_; DISALLOW_COPY_AND_ASSIGN(SetOuterHTMLAction); }; class DOMEditor::ReplaceWholeTextAction final : public InspectorHistory::Action { public: ReplaceWholeTextAction(Text* text_node, const String& text) : InspectorHistory::Action("ReplaceWholeText"), text_node_(text_node), text_(text) {} bool Perform(ExceptionState& exception_state) override { old_text_ = text_node_->wholeText(); return Redo(exception_state); } bool Undo(ExceptionState&) override { text_node_->ReplaceWholeText(old_text_); return true; } bool Redo(ExceptionState&) override { text_node_->ReplaceWholeText(text_); return true; } void Trace(blink::Visitor* visitor) override { visitor->Trace(text_node_); InspectorHistory::Action::Trace(visitor); } private: Member<Text> text_node_; String text_; String old_text_; DISALLOW_COPY_AND_ASSIGN(ReplaceWholeTextAction); }; class DOMEditor::ReplaceChildNodeAction final : public InspectorHistory::Action { public: ReplaceChildNodeAction(ContainerNode* parent_node, Node* new_node, Node* old_node) : InspectorHistory::Action("ReplaceChildNode"), parent_node_(parent_node), new_node_(new_node), old_node_(old_node) {} bool Perform(ExceptionState& exception_state) override { return Redo(exception_state); } bool Undo(ExceptionState& exception_state) override { parent_node_->ReplaceChild(old_node_, new_node_.Get(), exception_state); return !exception_state.HadException(); } bool Redo(ExceptionState& exception_state) override { parent_node_->ReplaceChild(new_node_, old_node_.Get(), exception_state); return !exception_state.HadException(); } void Trace(blink::Visitor* visitor) override { visitor->Trace(parent_node_); visitor->Trace(new_node_); visitor->Trace(old_node_); InspectorHistory::Action::Trace(visitor); } private: Member<ContainerNode> parent_node_; Member<Node> new_node_; Member<Node> old_node_; DISALLOW_COPY_AND_ASSIGN(ReplaceChildNodeAction); }; class DOMEditor::SetNodeValueAction final : public InspectorHistory::Action { public: SetNodeValueAction(Node* node, const String& value) : InspectorHistory::Action("SetNodeValue"), node_(node), value_(value) {} bool Perform(ExceptionState&) override { old_value_ = node_->nodeValue(); return Redo(IGNORE_EXCEPTION_FOR_TESTING); } bool Undo(ExceptionState&) override { node_->setNodeValue(old_value_); return true; } bool Redo(ExceptionState&) override { node_->setNodeValue(value_); return true; } void Trace(blink::Visitor* visitor) override { visitor->Trace(node_); InspectorHistory::Action::Trace(visitor); } private: Member<Node> node_; String value_; String old_value_; DISALLOW_COPY_AND_ASSIGN(SetNodeValueAction); }; DOMEditor::DOMEditor(InspectorHistory* history) : history_(history) {} bool DOMEditor::InsertBefore(ContainerNode* parent_node, Node* node, Node* anchor_node, ExceptionState& exception_state) { return history_->Perform( new InsertBeforeAction(parent_node, node, anchor_node), exception_state); } bool DOMEditor::RemoveChild(ContainerNode* parent_node, Node* node, ExceptionState& exception_state) { return history_->Perform(new RemoveChildAction(parent_node, node), exception_state); } bool DOMEditor::SetAttribute(Element* element, const String& name, const String& value, ExceptionState& exception_state) { return history_->Perform( new SetAttributeAction(element, AtomicString(name), AtomicString(value)), exception_state); } bool DOMEditor::RemoveAttribute(Element* element, const String& name, ExceptionState& exception_state) { return history_->Perform( new RemoveAttributeAction(element, AtomicString(name)), exception_state); } bool DOMEditor::SetOuterHTML(Node* node, const String& html, Node** new_node, ExceptionState& exception_state) { SetOuterHTMLAction* action = new SetOuterHTMLAction(node, html); bool result = history_->Perform(action, exception_state); if (result) *new_node = action->NewNode(); return result; } bool DOMEditor::ReplaceWholeText(Text* text_node, const String& text, ExceptionState& exception_state) { return history_->Perform(new ReplaceWholeTextAction(text_node, text), exception_state); } bool DOMEditor::ReplaceChild(ContainerNode* parent_node, Node* new_node, Node* old_node, ExceptionState& exception_state) { return history_->Perform( new ReplaceChildNodeAction(parent_node, new_node, old_node), exception_state); } bool DOMEditor::SetNodeValue(Node* node, const String& value, ExceptionState& exception_state) { return history_->Perform(new SetNodeValueAction(node, value), exception_state); } static Response ToResponse(ExceptionState& exception_state) { if (exception_state.HadException()) { return Response::Error(DOMException::GetErrorName(exception_state.Code()) + " " + exception_state.Message()); } return Response::OK(); } Response DOMEditor::InsertBefore(ContainerNode* parent_node, Node* node, Node* anchor_node) { DummyExceptionStateForTesting exception_state; InsertBefore(parent_node, node, anchor_node, exception_state); return ToResponse(exception_state); } Response DOMEditor::RemoveChild(ContainerNode* parent_node, Node* node) { DummyExceptionStateForTesting exception_state; RemoveChild(parent_node, node, exception_state); return ToResponse(exception_state); } Response DOMEditor::SetAttribute(Element* element, const String& name, const String& value) { DummyExceptionStateForTesting exception_state; SetAttribute(element, name, value, exception_state); return ToResponse(exception_state); } Response DOMEditor::RemoveAttribute(Element* element, const String& name) { DummyExceptionStateForTesting exception_state; RemoveAttribute(element, name, exception_state); return ToResponse(exception_state); } Response DOMEditor::SetOuterHTML(Node* node, const String& html, Node** new_node) { DummyExceptionStateForTesting exception_state; SetOuterHTML(node, html, new_node, exception_state); return ToResponse(exception_state); } Response DOMEditor::ReplaceWholeText(Text* text_node, const String& text) { DummyExceptionStateForTesting exception_state; ReplaceWholeText(text_node, text, exception_state); return ToResponse(exception_state); } void DOMEditor::Trace(blink::Visitor* visitor) { visitor->Trace(history_); } } // namespace blink
null
null
null
null
29,870
56,823
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
56,823
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_CHROMEOS_EXTENSIONS_EXTERNAL_CACHE_H_ #define CHROME_BROWSER_CHROMEOS_EXTENSIONS_EXTERNAL_CACHE_H_ #include <memory> #include <string> #include <vector> #include "base/callback_forward.h" #include "url/gurl.h" namespace base { class DictionaryValue; class FilePath; class Value; } namespace chromeos { // The ExternalCache manages a cache for external extensions. class ExternalCache { public: using PutExternalExtensionCallback = base::OnceCallback<void(const std::string& id, bool success)>; virtual ~ExternalCache() = default; // If an external extension should be downloaded, returns the extension's // update URL. Otherwise, returns an empty URL. static GURL GetExtensionUpdateUrl(const base::Value& extension_value, bool always_checking_for_updates); // Converts an external extension value to the external extension value // describing a cached extension - i.e. a value describing an extension // returned by GetCachedExtensions(). static base::Value GetExtensionValueToCache(const base::Value& original_value, const std::string& path, const std::string& version); // If the external extension is not curently cached, whether the extension's // value should be added to the set of cached extensions (returned by // GetCachedExtensions()) regardles of the extension's download status. static bool ShouldCacheImmediately(const base::Value& extension_value, const std::string& installed_version); // Returns already cached extensions. virtual const base::DictionaryValue* GetCachedExtensions() = 0; // Shut down the cache. The |callback| will be invoked when the cache has shut // down completely and there are no more pending file I/O operations. virtual void Shutdown(base::OnceClosure callback) = 0; // Replace the list of extensions to cache with |prefs| and perform update // checks for these. virtual void UpdateExtensionsList( std::unique_ptr<base::DictionaryValue> prefs) = 0; // If a user of one of the ExternalCache's extensions detects that // the extension is damaged then this method can be used to remove it from // the cache and retry to download it after a restart. virtual void OnDamagedFileDetected(const base::FilePath& path) = 0; // Removes extensions listed in |ids| from external cache, corresponding crx // files will be removed from disk too. virtual void RemoveExtensions(const std::vector<std::string>& ids) = 0; // If extension with |id| exists in the cache, returns |true|, |file_path| and // |version| for the extension. Extension will be marked as used with current // timestamp. virtual bool GetExtension(const std::string& id, base::FilePath* file_path, std::string* version) = 0; // Whether the extension with the provided id is currently being cached - // i.e. whether the extension have been added to the external cache, but it's // data has not yet been fetched, and thus is not available using // GetExtension(). virtual bool ExtensionFetchPending(const std::string& id) = 0; // Puts the external |crx_file_path| into |local_cache_| for extension with // |id|. virtual void PutExternalExtension(const std::string& id, const base::FilePath& crx_file_path, const std::string& version, PutExternalExtensionCallback callback) = 0; }; } // namespace chromeos #endif // CHROME_BROWSER_CHROMEOS_EXTENSIONS_EXTERNAL_CACHE_H_
null
null
null
null
53,686
19,122
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
19,122
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright 2017 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_FEATURE_ENGAGEMENT_TEST_TEST_TRACKER_H_ #define COMPONENTS_FEATURE_ENGAGEMENT_TEST_TEST_TRACKER_H_ #include <memory> namespace feature_engagement { class Tracker; // Provides a test feature_engagement::Tracker that makes all non-relevant // conditions true so you can test per-feature specific configurations. // Note: Your feature config params must have |"availability": "ANY"| // or the FeatureConfigConditionValidator will return false. std::unique_ptr<Tracker> CreateTestTracker(); } // namespace feature_engagement #endif // COMPONENTS_FEATURE_ENGAGEMENT_TEST_TEST_TRACKER_H_
null
null
null
null
15,985
54,441
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
54,441
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "base/test/launcher/test_launcher.h" #include "build/build_config.h" #include "chrome/test/base/chrome_test_launcher.h" #include "chrome/test/base/chrome_test_suite.h" #if defined(OS_WIN) #include "base/test/test_switches.h" #include "base/win/win_util.h" #endif // defined(OS_WIN) int main(int argc, char** argv) { base::CommandLine::Init(argc, argv); size_t parallel_jobs = base::NumParallelJobs(); if (parallel_jobs == 0U) { return 1; } else if (parallel_jobs > 1U) { parallel_jobs /= 2U; } #if defined(OS_WIN) // Enable high-DPI for interactive tests where the user is expected to // manually verify results. if (base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kTestLauncherInteractive)) { base::win::EnableHighDPISupport(); } #endif // defined(OS_WIN) ChromeTestSuiteRunner runner; ChromeTestLauncherDelegate delegate(&runner); return LaunchChromeTests(parallel_jobs, &delegate, argc, argv); }
null
null
null
null
51,304
46,674
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
46,674
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright 2016 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 <memory> #include "ash/public/cpp/config.h" #include "ash/shell.h" #include "ash/shell_test_api.h" #include "ash/system/palette/mock_palette_tool_delegate.h" #include "ash/system/palette/palette_ids.h" #include "ash/system/palette/palette_tool.h" #include "ash/system/palette/tools/capture_region_mode.h" #include "ash/system/palette/tools/capture_screen_action.h" #include "ash/test/ash_test_base.h" #include "ash/test_screenshot_delegate.h" #include "ash/utility/screenshot_controller.h" #include "base/macros.h" #include "ui/events/test/event_generator.h" namespace ash { // Base class for all screenshot pallette tools tests. class ScreenshotToolTest : public AshTestBase { public: ScreenshotToolTest() = default; ~ScreenshotToolTest() override = default; void SetUp() override { AshTestBase::SetUp(); palette_tool_delegate_ = std::make_unique<MockPaletteToolDelegate>(); } protected: std::unique_ptr<MockPaletteToolDelegate> palette_tool_delegate_; bool IsPartialScreenshotActive() { return static_cast<bool>( Shell::Get()->screenshot_controller()->on_screenshot_session_done_); } private: DISALLOW_COPY_AND_ASSIGN(ScreenshotToolTest); }; // Verifies that capturing a region triggers the partial screenshot delegate // method. Invoking the callback passed to the delegate disables the tool. TEST_F(ScreenshotToolTest, EnablingCaptureRegionCallsDelegateAndDisablesTool) { std::unique_ptr<PaletteTool> tool = std::make_unique<CaptureRegionMode>(palette_tool_delegate_.get()); // Starting a partial screenshot calls the calls the palette delegate to start // a screenshot session and hides the palette. EXPECT_CALL(*palette_tool_delegate_.get(), HidePalette()); tool->OnEnable(); EXPECT_TRUE(IsPartialScreenshotActive()); testing::Mock::VerifyAndClearExpectations(palette_tool_delegate_.get()); // Simulate region selection. EXPECT_CALL(*palette_tool_delegate_.get(), DisableTool(PaletteToolId::CAPTURE_REGION)); const gfx::Rect selection(100, 200, 300, 400); GetEventGenerator().EnterPenPointerMode(); GetEventGenerator().MoveTouch(selection.origin()); GetEventGenerator().PressTouch(); GetEventGenerator().MoveTouch( gfx::Point(selection.right(), selection.bottom())); GetEventGenerator().ReleaseTouch(); EXPECT_FALSE(IsPartialScreenshotActive()); EXPECT_EQ(1, GetScreenshotDelegate()->handle_take_partial_screenshot_count()); EXPECT_EQ(selection.ToString(), GetScreenshotDelegate()->last_rect().ToString()); testing::Mock::VerifyAndClearExpectations(palette_tool_delegate_.get()); // Enable the tool again tool->OnEnable(); EXPECT_TRUE(IsPartialScreenshotActive()); // Calling the associated callback (partial screenshot finished) will disable // the tool. EXPECT_CALL(*palette_tool_delegate_.get(), DisableTool(PaletteToolId::CAPTURE_REGION)); Shell::Get()->screenshot_controller()->CancelScreenshotSession(); EXPECT_FALSE(IsPartialScreenshotActive()); } // Verifies that capturing the screen triggers the screenshot delegate method, // disables the tool, and hides the palette. TEST_F(ScreenshotToolTest, EnablingCaptureScreenCallsDelegateAndDisablesTool) { std::unique_ptr<PaletteTool> tool = std::make_unique<CaptureScreenAction>(palette_tool_delegate_.get()); EXPECT_CALL(*palette_tool_delegate_.get(), DisableTool(PaletteToolId::CAPTURE_SCREEN)); EXPECT_CALL(*palette_tool_delegate_.get(), HidePaletteImmediately()); tool->OnEnable(); EXPECT_EQ(1, GetScreenshotDelegate()->handle_take_screenshot_count()); } } // namespace ash
null
null
null
null
43,537
29,342
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
194,337
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * Intel Management Engine Interface (Intel MEI) Linux driver * Copyright (c) 2012-2013, 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. * */ #include <linux/module.h> #include <linux/device.h> #include <linux/kernel.h> #include <linux/sched/signal.h> #include <linux/init.h> #include <linux/errno.h> #include <linux/slab.h> #include <linux/mutex.h> #include <linux/interrupt.h> #include <linux/mei_cl_bus.h> #include "mei_dev.h" #include "client.h" #define to_mei_cl_driver(d) container_of(d, struct mei_cl_driver, driver) #define to_mei_cl_device(d) container_of(d, struct mei_cl_device, dev) /** * __mei_cl_send - internal client send (write) * * @cl: host client * @buf: buffer to send * @length: buffer length * @mode: sending mode * * Return: written size bytes or < 0 on error */ ssize_t __mei_cl_send(struct mei_cl *cl, u8 *buf, size_t length, unsigned int mode) { struct mei_device *bus; struct mei_cl_cb *cb; ssize_t rets; if (WARN_ON(!cl || !cl->dev)) return -ENODEV; bus = cl->dev; mutex_lock(&bus->device_lock); if (bus->dev_state != MEI_DEV_ENABLED) { rets = -ENODEV; goto out; } if (!mei_cl_is_connected(cl)) { rets = -ENODEV; goto out; } /* Check if we have an ME client device */ if (!mei_me_cl_is_active(cl->me_cl)) { rets = -ENOTTY; goto out; } if (length > mei_cl_mtu(cl)) { rets = -EFBIG; goto out; } cb = mei_cl_alloc_cb(cl, length, MEI_FOP_WRITE, NULL); if (!cb) { rets = -ENOMEM; goto out; } cb->internal = !!(mode & MEI_CL_IO_TX_INTERNAL); cb->blocking = !!(mode & MEI_CL_IO_TX_BLOCKING); memcpy(cb->buf.data, buf, length); rets = mei_cl_write(cl, cb); out: mutex_unlock(&bus->device_lock); return rets; } /** * __mei_cl_recv - internal client receive (read) * * @cl: host client * @buf: buffer to receive * @length: buffer length * @mode: io mode * * Return: read size in bytes of < 0 on error */ ssize_t __mei_cl_recv(struct mei_cl *cl, u8 *buf, size_t length, unsigned int mode) { struct mei_device *bus; struct mei_cl_cb *cb; size_t r_length; ssize_t rets; bool nonblock = !!(mode & MEI_CL_IO_RX_NONBLOCK); if (WARN_ON(!cl || !cl->dev)) return -ENODEV; bus = cl->dev; mutex_lock(&bus->device_lock); if (bus->dev_state != MEI_DEV_ENABLED) { rets = -ENODEV; goto out; } cb = mei_cl_read_cb(cl, NULL); if (cb) goto copy; rets = mei_cl_read_start(cl, length, NULL); if (rets && rets != -EBUSY) goto out; if (nonblock) { rets = -EAGAIN; goto out; } /* wait on event only if there is no other waiter */ /* synchronized under device mutex */ if (!waitqueue_active(&cl->rx_wait)) { mutex_unlock(&bus->device_lock); if (wait_event_interruptible(cl->rx_wait, (!list_empty(&cl->rd_completed)) || (!mei_cl_is_connected(cl)))) { if (signal_pending(current)) return -EINTR; return -ERESTARTSYS; } mutex_lock(&bus->device_lock); if (!mei_cl_is_connected(cl)) { rets = -ENODEV; goto out; } } cb = mei_cl_read_cb(cl, NULL); if (!cb) { rets = 0; goto out; } copy: if (cb->status) { rets = cb->status; goto free; } r_length = min_t(size_t, length, cb->buf_idx); memcpy(buf, cb->buf.data, r_length); rets = r_length; free: mei_io_cb_free(cb); out: mutex_unlock(&bus->device_lock); return rets; } /** * mei_cldev_send - me device send (write) * * @cldev: me client device * @buf: buffer to send * @length: buffer length * * Return: written size in bytes or < 0 on error */ ssize_t mei_cldev_send(struct mei_cl_device *cldev, u8 *buf, size_t length) { struct mei_cl *cl = cldev->cl; return __mei_cl_send(cl, buf, length, MEI_CL_IO_TX_BLOCKING); } EXPORT_SYMBOL_GPL(mei_cldev_send); /** * mei_cldev_recv_nonblock - non block client receive (read) * * @cldev: me client device * @buf: buffer to receive * @length: buffer length * * Return: read size in bytes of < 0 on error * -EAGAIN if function will block. */ ssize_t mei_cldev_recv_nonblock(struct mei_cl_device *cldev, u8 *buf, size_t length) { struct mei_cl *cl = cldev->cl; return __mei_cl_recv(cl, buf, length, MEI_CL_IO_RX_NONBLOCK); } EXPORT_SYMBOL_GPL(mei_cldev_recv_nonblock); /** * mei_cldev_recv - client receive (read) * * @cldev: me client device * @buf: buffer to receive * @length: buffer length * * Return: read size in bytes of < 0 on error */ ssize_t mei_cldev_recv(struct mei_cl_device *cldev, u8 *buf, size_t length) { struct mei_cl *cl = cldev->cl; return __mei_cl_recv(cl, buf, length, 0); } EXPORT_SYMBOL_GPL(mei_cldev_recv); /** * mei_cl_bus_rx_work - dispatch rx event for a bus device * * @work: work */ static void mei_cl_bus_rx_work(struct work_struct *work) { struct mei_cl_device *cldev; struct mei_device *bus; cldev = container_of(work, struct mei_cl_device, rx_work); bus = cldev->bus; if (cldev->rx_cb) cldev->rx_cb(cldev); mutex_lock(&bus->device_lock); mei_cl_read_start(cldev->cl, mei_cl_mtu(cldev->cl), NULL); mutex_unlock(&bus->device_lock); } /** * mei_cl_bus_notif_work - dispatch FW notif event for a bus device * * @work: work */ static void mei_cl_bus_notif_work(struct work_struct *work) { struct mei_cl_device *cldev; cldev = container_of(work, struct mei_cl_device, notif_work); if (cldev->notif_cb) cldev->notif_cb(cldev); } /** * mei_cl_bus_notify_event - schedule notify cb on bus client * * @cl: host client * * Return: true if event was scheduled * false if the client is not waiting for event */ bool mei_cl_bus_notify_event(struct mei_cl *cl) { struct mei_cl_device *cldev = cl->cldev; if (!cldev || !cldev->notif_cb) return false; if (!cl->notify_ev) return false; schedule_work(&cldev->notif_work); cl->notify_ev = false; return true; } /** * mei_cl_bus_rx_event - schedule rx event * * @cl: host client * * Return: true if event was scheduled * false if the client is not waiting for event */ bool mei_cl_bus_rx_event(struct mei_cl *cl) { struct mei_cl_device *cldev = cl->cldev; if (!cldev || !cldev->rx_cb) return false; schedule_work(&cldev->rx_work); return true; } /** * mei_cldev_register_rx_cb - register Rx event callback * * @cldev: me client devices * @rx_cb: callback function * * Return: 0 on success * -EALREADY if an callback is already registered * <0 on other errors */ int mei_cldev_register_rx_cb(struct mei_cl_device *cldev, mei_cldev_cb_t rx_cb) { struct mei_device *bus = cldev->bus; int ret; if (!rx_cb) return -EINVAL; if (cldev->rx_cb) return -EALREADY; cldev->rx_cb = rx_cb; INIT_WORK(&cldev->rx_work, mei_cl_bus_rx_work); mutex_lock(&bus->device_lock); ret = mei_cl_read_start(cldev->cl, mei_cl_mtu(cldev->cl), NULL); mutex_unlock(&bus->device_lock); if (ret && ret != -EBUSY) return ret; return 0; } EXPORT_SYMBOL_GPL(mei_cldev_register_rx_cb); /** * mei_cldev_register_notif_cb - register FW notification event callback * * @cldev: me client devices * @notif_cb: callback function * * Return: 0 on success * -EALREADY if an callback is already registered * <0 on other errors */ int mei_cldev_register_notif_cb(struct mei_cl_device *cldev, mei_cldev_cb_t notif_cb) { struct mei_device *bus = cldev->bus; int ret; if (!notif_cb) return -EINVAL; if (cldev->notif_cb) return -EALREADY; cldev->notif_cb = notif_cb; INIT_WORK(&cldev->notif_work, mei_cl_bus_notif_work); mutex_lock(&bus->device_lock); ret = mei_cl_notify_request(cldev->cl, NULL, 1); mutex_unlock(&bus->device_lock); if (ret) return ret; return 0; } EXPORT_SYMBOL_GPL(mei_cldev_register_notif_cb); /** * mei_cldev_get_drvdata - driver data getter * * @cldev: mei client device * * Return: driver private data */ void *mei_cldev_get_drvdata(const struct mei_cl_device *cldev) { return dev_get_drvdata(&cldev->dev); } EXPORT_SYMBOL_GPL(mei_cldev_get_drvdata); /** * mei_cldev_set_drvdata - driver data setter * * @cldev: mei client device * @data: data to store */ void mei_cldev_set_drvdata(struct mei_cl_device *cldev, void *data) { dev_set_drvdata(&cldev->dev, data); } EXPORT_SYMBOL_GPL(mei_cldev_set_drvdata); /** * mei_cldev_uuid - return uuid of the underlying me client * * @cldev: mei client device * * Return: me client uuid */ const uuid_le *mei_cldev_uuid(const struct mei_cl_device *cldev) { return mei_me_cl_uuid(cldev->me_cl); } EXPORT_SYMBOL_GPL(mei_cldev_uuid); /** * mei_cldev_ver - return protocol version of the underlying me client * * @cldev: mei client device * * Return: me client protocol version */ u8 mei_cldev_ver(const struct mei_cl_device *cldev) { return mei_me_cl_ver(cldev->me_cl); } EXPORT_SYMBOL_GPL(mei_cldev_ver); /** * mei_cldev_enabled - check whether the device is enabled * * @cldev: mei client device * * Return: true if me client is initialized and connected */ bool mei_cldev_enabled(struct mei_cl_device *cldev) { return mei_cl_is_connected(cldev->cl); } EXPORT_SYMBOL_GPL(mei_cldev_enabled); /** * mei_cldev_enable - enable me client device * create connection with me client * * @cldev: me client device * * Return: 0 on success and < 0 on error */ int mei_cldev_enable(struct mei_cl_device *cldev) { struct mei_device *bus = cldev->bus; struct mei_cl *cl; int ret; cl = cldev->cl; if (cl->state == MEI_FILE_UNINITIALIZED) { mutex_lock(&bus->device_lock); ret = mei_cl_link(cl); mutex_unlock(&bus->device_lock); if (ret) return ret; /* update pointers */ cl->cldev = cldev; } mutex_lock(&bus->device_lock); if (mei_cl_is_connected(cl)) { ret = 0; goto out; } if (!mei_me_cl_is_active(cldev->me_cl)) { dev_err(&cldev->dev, "me client is not active\n"); ret = -ENOTTY; goto out; } ret = mei_cl_connect(cl, cldev->me_cl, NULL); if (ret < 0) dev_err(&cldev->dev, "cannot connect\n"); out: mutex_unlock(&bus->device_lock); return ret; } EXPORT_SYMBOL_GPL(mei_cldev_enable); /** * mei_cldev_unregister_callbacks - internal wrapper for unregistering * callbacks. * * @cldev: client device */ static void mei_cldev_unregister_callbacks(struct mei_cl_device *cldev) { if (cldev->rx_cb) { cancel_work_sync(&cldev->rx_work); cldev->rx_cb = NULL; } if (cldev->notif_cb) { cancel_work_sync(&cldev->notif_work); cldev->notif_cb = NULL; } } /** * mei_cldev_disable - disable me client device * disconnect form the me client * * @cldev: me client device * * Return: 0 on success and < 0 on error */ int mei_cldev_disable(struct mei_cl_device *cldev) { struct mei_device *bus; struct mei_cl *cl; int err; if (!cldev) return -ENODEV; cl = cldev->cl; bus = cldev->bus; mei_cldev_unregister_callbacks(cldev); mutex_lock(&bus->device_lock); if (!mei_cl_is_connected(cl)) { dev_dbg(bus->dev, "Already disconnected"); err = 0; goto out; } err = mei_cl_disconnect(cl); if (err < 0) dev_err(bus->dev, "Could not disconnect from the ME client"); out: /* Flush queues and remove any pending read */ mei_cl_flush_queues(cl, NULL); mei_cl_unlink(cl); mutex_unlock(&bus->device_lock); return err; } EXPORT_SYMBOL_GPL(mei_cldev_disable); /** * mei_cl_bus_module_get - acquire module of the underlying * hw module. * * @cl: host client * * Return: true on success; false if the module was removed. */ bool mei_cl_bus_module_get(struct mei_cl *cl) { struct mei_cl_device *cldev = cl->cldev; if (!cldev) return true; return try_module_get(cldev->bus->dev->driver->owner); } /** * mei_cl_bus_module_put - release the underlying hw module. * * @cl: host client */ void mei_cl_bus_module_put(struct mei_cl *cl) { struct mei_cl_device *cldev = cl->cldev; if (cldev) module_put(cldev->bus->dev->driver->owner); } /** * mei_cl_device_find - find matching entry in the driver id table * * @cldev: me client device * @cldrv: me client driver * * Return: id on success; NULL if no id is matching */ static const struct mei_cl_device_id *mei_cl_device_find(struct mei_cl_device *cldev, struct mei_cl_driver *cldrv) { const struct mei_cl_device_id *id; const uuid_le *uuid; u8 version; bool match; uuid = mei_me_cl_uuid(cldev->me_cl); version = mei_me_cl_ver(cldev->me_cl); id = cldrv->id_table; while (uuid_le_cmp(NULL_UUID_LE, id->uuid)) { if (!uuid_le_cmp(*uuid, id->uuid)) { match = true; if (cldev->name[0]) if (strncmp(cldev->name, id->name, sizeof(id->name))) match = false; if (id->version != MEI_CL_VERSION_ANY) if (id->version != version) match = false; if (match) return id; } id++; } return NULL; } /** * mei_cl_device_match - device match function * * @dev: device * @drv: driver * * Return: 1 if matching device was found 0 otherwise */ static int mei_cl_device_match(struct device *dev, struct device_driver *drv) { struct mei_cl_device *cldev = to_mei_cl_device(dev); struct mei_cl_driver *cldrv = to_mei_cl_driver(drv); const struct mei_cl_device_id *found_id; if (!cldev) return 0; if (!cldev->do_match) return 0; if (!cldrv || !cldrv->id_table) return 0; found_id = mei_cl_device_find(cldev, cldrv); if (found_id) return 1; return 0; } /** * mei_cl_device_probe - bus probe function * * @dev: device * * Return: 0 on success; < 0 otherwise */ static int mei_cl_device_probe(struct device *dev) { struct mei_cl_device *cldev; struct mei_cl_driver *cldrv; const struct mei_cl_device_id *id; int ret; cldev = to_mei_cl_device(dev); cldrv = to_mei_cl_driver(dev->driver); if (!cldev) return 0; if (!cldrv || !cldrv->probe) return -ENODEV; id = mei_cl_device_find(cldev, cldrv); if (!id) return -ENODEV; ret = cldrv->probe(cldev, id); if (ret) return ret; __module_get(THIS_MODULE); return 0; } /** * mei_cl_device_remove - remove device from the bus * * @dev: device * * Return: 0 on success; < 0 otherwise */ static int mei_cl_device_remove(struct device *dev) { struct mei_cl_device *cldev = to_mei_cl_device(dev); struct mei_cl_driver *cldrv; int ret = 0; if (!cldev || !dev->driver) return 0; cldrv = to_mei_cl_driver(dev->driver); if (cldrv->remove) ret = cldrv->remove(cldev); mei_cldev_unregister_callbacks(cldev); module_put(THIS_MODULE); dev->driver = NULL; return ret; } static ssize_t name_show(struct device *dev, struct device_attribute *a, char *buf) { struct mei_cl_device *cldev = to_mei_cl_device(dev); return scnprintf(buf, PAGE_SIZE, "%s", cldev->name); } static DEVICE_ATTR_RO(name); static ssize_t uuid_show(struct device *dev, struct device_attribute *a, char *buf) { struct mei_cl_device *cldev = to_mei_cl_device(dev); const uuid_le *uuid = mei_me_cl_uuid(cldev->me_cl); return scnprintf(buf, PAGE_SIZE, "%pUl", uuid); } static DEVICE_ATTR_RO(uuid); static ssize_t version_show(struct device *dev, struct device_attribute *a, char *buf) { struct mei_cl_device *cldev = to_mei_cl_device(dev); u8 version = mei_me_cl_ver(cldev->me_cl); return scnprintf(buf, PAGE_SIZE, "%02X", version); } static DEVICE_ATTR_RO(version); static ssize_t modalias_show(struct device *dev, struct device_attribute *a, char *buf) { struct mei_cl_device *cldev = to_mei_cl_device(dev); const uuid_le *uuid = mei_me_cl_uuid(cldev->me_cl); return scnprintf(buf, PAGE_SIZE, "mei:%s:%pUl:", cldev->name, uuid); } static DEVICE_ATTR_RO(modalias); static struct attribute *mei_cldev_attrs[] = { &dev_attr_name.attr, &dev_attr_uuid.attr, &dev_attr_version.attr, &dev_attr_modalias.attr, NULL, }; ATTRIBUTE_GROUPS(mei_cldev); /** * mei_cl_device_uevent - me client bus uevent handler * * @dev: device * @env: uevent kobject * * Return: 0 on success -ENOMEM on when add_uevent_var fails */ static int mei_cl_device_uevent(struct device *dev, struct kobj_uevent_env *env) { struct mei_cl_device *cldev = to_mei_cl_device(dev); const uuid_le *uuid = mei_me_cl_uuid(cldev->me_cl); u8 version = mei_me_cl_ver(cldev->me_cl); if (add_uevent_var(env, "MEI_CL_VERSION=%d", version)) return -ENOMEM; if (add_uevent_var(env, "MEI_CL_UUID=%pUl", uuid)) return -ENOMEM; if (add_uevent_var(env, "MEI_CL_NAME=%s", cldev->name)) return -ENOMEM; if (add_uevent_var(env, "MODALIAS=mei:%s:%pUl:%02X:", cldev->name, uuid, version)) return -ENOMEM; return 0; } static struct bus_type mei_cl_bus_type = { .name = "mei", .dev_groups = mei_cldev_groups, .match = mei_cl_device_match, .probe = mei_cl_device_probe, .remove = mei_cl_device_remove, .uevent = mei_cl_device_uevent, }; static struct mei_device *mei_dev_bus_get(struct mei_device *bus) { if (bus) get_device(bus->dev); return bus; } static void mei_dev_bus_put(struct mei_device *bus) { if (bus) put_device(bus->dev); } static void mei_cl_bus_dev_release(struct device *dev) { struct mei_cl_device *cldev = to_mei_cl_device(dev); if (!cldev) return; mei_me_cl_put(cldev->me_cl); mei_dev_bus_put(cldev->bus); kfree(cldev->cl); kfree(cldev); } static struct device_type mei_cl_device_type = { .release = mei_cl_bus_dev_release, }; /** * mei_cl_bus_set_name - set device name for me client device * * @cldev: me client device */ static inline void mei_cl_bus_set_name(struct mei_cl_device *cldev) { dev_set_name(&cldev->dev, "mei:%s:%pUl:%02X", cldev->name, mei_me_cl_uuid(cldev->me_cl), mei_me_cl_ver(cldev->me_cl)); } /** * mei_cl_bus_dev_alloc - initialize and allocate mei client device * * @bus: mei device * @me_cl: me client * * Return: allocated device structur or NULL on allocation failure */ static struct mei_cl_device *mei_cl_bus_dev_alloc(struct mei_device *bus, struct mei_me_client *me_cl) { struct mei_cl_device *cldev; struct mei_cl *cl; cldev = kzalloc(sizeof(struct mei_cl_device), GFP_KERNEL); if (!cldev) return NULL; cl = mei_cl_allocate(bus); if (!cl) { kfree(cldev); return NULL; } device_initialize(&cldev->dev); cldev->dev.parent = bus->dev; cldev->dev.bus = &mei_cl_bus_type; cldev->dev.type = &mei_cl_device_type; cldev->bus = mei_dev_bus_get(bus); cldev->me_cl = mei_me_cl_get(me_cl); cldev->cl = cl; mei_cl_bus_set_name(cldev); cldev->is_added = 0; INIT_LIST_HEAD(&cldev->bus_list); return cldev; } /** * mei_cl_dev_setup - setup me client device * run fix up routines and set the device name * * @bus: mei device * @cldev: me client device * * Return: true if the device is eligible for enumeration */ static bool mei_cl_bus_dev_setup(struct mei_device *bus, struct mei_cl_device *cldev) { cldev->do_match = 1; mei_cl_bus_dev_fixup(cldev); /* the device name can change during fix up */ if (cldev->do_match) mei_cl_bus_set_name(cldev); return cldev->do_match == 1; } /** * mei_cl_bus_dev_add - add me client devices * * @cldev: me client device * * Return: 0 on success; < 0 on failre */ static int mei_cl_bus_dev_add(struct mei_cl_device *cldev) { int ret; dev_dbg(cldev->bus->dev, "adding %pUL:%02X\n", mei_me_cl_uuid(cldev->me_cl), mei_me_cl_ver(cldev->me_cl)); ret = device_add(&cldev->dev); if (!ret) cldev->is_added = 1; return ret; } /** * mei_cl_bus_dev_stop - stop the driver * * @cldev: me client device */ static void mei_cl_bus_dev_stop(struct mei_cl_device *cldev) { if (cldev->is_added) device_release_driver(&cldev->dev); } /** * mei_cl_bus_dev_destroy - destroy me client devices object * * @cldev: me client device * * Locking: called under "dev->cl_bus_lock" lock */ static void mei_cl_bus_dev_destroy(struct mei_cl_device *cldev) { WARN_ON(!mutex_is_locked(&cldev->bus->cl_bus_lock)); if (!cldev->is_added) return; device_del(&cldev->dev); list_del_init(&cldev->bus_list); cldev->is_added = 0; put_device(&cldev->dev); } /** * mei_cl_bus_remove_device - remove a devices form the bus * * @cldev: me client device */ static void mei_cl_bus_remove_device(struct mei_cl_device *cldev) { mei_cl_bus_dev_stop(cldev); mei_cl_bus_dev_destroy(cldev); } /** * mei_cl_bus_remove_devices - remove all devices form the bus * * @bus: mei device */ void mei_cl_bus_remove_devices(struct mei_device *bus) { struct mei_cl_device *cldev, *next; mutex_lock(&bus->cl_bus_lock); list_for_each_entry_safe(cldev, next, &bus->device_list, bus_list) mei_cl_bus_remove_device(cldev); mutex_unlock(&bus->cl_bus_lock); } /** * mei_cl_bus_dev_init - allocate and initializes an mei client devices * based on me client * * @bus: mei device * @me_cl: me client * * Locking: called under "dev->cl_bus_lock" lock */ static void mei_cl_bus_dev_init(struct mei_device *bus, struct mei_me_client *me_cl) { struct mei_cl_device *cldev; WARN_ON(!mutex_is_locked(&bus->cl_bus_lock)); dev_dbg(bus->dev, "initializing %pUl", mei_me_cl_uuid(me_cl)); if (me_cl->bus_added) return; cldev = mei_cl_bus_dev_alloc(bus, me_cl); if (!cldev) return; me_cl->bus_added = true; list_add_tail(&cldev->bus_list, &bus->device_list); } /** * mei_cl_bus_rescan - scan me clients list and add create * devices for eligible clients * * @bus: mei device */ void mei_cl_bus_rescan(struct mei_device *bus) { struct mei_cl_device *cldev, *n; struct mei_me_client *me_cl; mutex_lock(&bus->cl_bus_lock); down_read(&bus->me_clients_rwsem); list_for_each_entry(me_cl, &bus->me_clients, list) mei_cl_bus_dev_init(bus, me_cl); up_read(&bus->me_clients_rwsem); list_for_each_entry_safe(cldev, n, &bus->device_list, bus_list) { if (!mei_me_cl_is_active(cldev->me_cl)) { mei_cl_bus_remove_device(cldev); continue; } if (cldev->is_added) continue; if (mei_cl_bus_dev_setup(bus, cldev)) mei_cl_bus_dev_add(cldev); else { list_del_init(&cldev->bus_list); put_device(&cldev->dev); } } mutex_unlock(&bus->cl_bus_lock); dev_dbg(bus->dev, "rescan end"); } void mei_cl_bus_rescan_work(struct work_struct *work) { struct mei_device *bus = container_of(work, struct mei_device, bus_rescan_work); struct mei_me_client *me_cl; me_cl = mei_me_cl_by_uuid(bus, &mei_amthif_guid); if (me_cl) mei_amthif_host_init(bus, me_cl); mei_me_cl_put(me_cl); mei_cl_bus_rescan(bus); } int __mei_cldev_driver_register(struct mei_cl_driver *cldrv, struct module *owner) { int err; cldrv->driver.name = cldrv->name; cldrv->driver.owner = owner; cldrv->driver.bus = &mei_cl_bus_type; err = driver_register(&cldrv->driver); if (err) return err; pr_debug("mei: driver [%s] registered\n", cldrv->driver.name); return 0; } EXPORT_SYMBOL_GPL(__mei_cldev_driver_register); void mei_cldev_driver_unregister(struct mei_cl_driver *cldrv) { driver_unregister(&cldrv->driver); pr_debug("mei: driver [%s] unregistered\n", cldrv->driver.name); } EXPORT_SYMBOL_GPL(mei_cldev_driver_unregister); int __init mei_cl_bus_init(void) { return bus_register(&mei_cl_bus_type); } void __exit mei_cl_bus_exit(void) { bus_unregister(&mei_cl_bus_type); }
null
null
null
null
102,684
40,280
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
40,280
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
/* config.h. Generated from config.h.in by configure. */ /* config.h.in. Generated from configure.in by autoheader. */ /* Define to 1 if you have the <ansidecl.h> header file. */ /* #undef HAVE_ANSIDECL_H */ /* Define to 1 if you have the `clock_gettime' function. */ /* Define to 1 if you have the <dlfcn.h> header file. */ #define HAVE_DLFCN_H 1 /* Define to 1 if you have the <errno.h> header file. */ #define HAVE_ERRNO_H 1 /* Define if fabs is there */ /* #undef HAVE_FABS */ /* Define to 1 if you have the <float.h> header file. */ #define HAVE_FLOAT_H 1 /* Define if floor is there */ /* #undef HAVE_FLOOR */ /* Define to 1 if you have the `fprintf' function. */ #define HAVE_FPRINTF 1 /* Define to 1 if you have the <fp_class.h> header file. */ /* #undef HAVE_FP_CLASS_H */ /* Define to 1 if you have the `ftime' function. */ #define HAVE_FTIME 1 /* Define if gcrypt library is available. */ /* #undef HAVE_GCRYPT */ /* Define to 1 if you have the `gettimeofday' function. */ #define HAVE_GETTIMEOFDAY 1 /* Define to 1 if you have the `gmtime' function. */ #define HAVE_GMTIME 1 /* Define to 1 if you have the `gmtime_r' function. */ #define HAVE_GMTIME_R 1 /* Define to 1 if you have the <ieeefp.h> header file. */ /* #undef HAVE_IEEEFP_H */ /* Define to 1 if you have the <inttypes.h> header file. */ #define HAVE_INTTYPES_H 1 /* Define if pthread library is there (-lpthread) */ #define HAVE_LIBPTHREAD /**/ /* Define to 1 if you have the <locale.h> header file. */ #define HAVE_LOCALE_H 1 /* Define to 1 if you have the `localtime' function. */ /* Define to 1 if you have the `localtime_r' function. */ #define HAVE_LOCALTIME_R 1 /* Define to 1 if you have the <math.h> header file. */ #define HAVE_MATH_H 1 /* Define to 1 if you have the <memory.h> header file. */ #define HAVE_MEMORY_H 1 /* Define to 1 if you have the <nan.h> header file. */ /* #undef HAVE_NAN_H */ /* Define if pow is there */ /* #undef HAVE_POW */ /* Define to 1 if you have the `printf' function. */ #define HAVE_PRINTF 1 /* Define if <pthread.h> is there */ #define HAVE_PTHREAD_H /**/ /* Define to 1 if you have the `snprintf' function. */ #define HAVE_SNPRINTF 1 /* Define to 1 if you have the `sprintf' function. */ #define HAVE_SPRINTF 1 /* Define to 1 if you have the `sscanf' function. */ #define HAVE_SSCANF 1 /* Define to 1 if you have the `stat' function. */ #define HAVE_STAT 1 /* Define to 1 if you have the <stdarg.h> header file. */ #define HAVE_STDARG_H 1 /* Define to 1 if you have the <stdint.h> header file. */ #define HAVE_STDINT_H 1 /* Define to 1 if you have the <stdlib.h> header file. */ #define HAVE_STDLIB_H 1 /* Define to 1 if you have the <strings.h> header file. */ #define HAVE_STRINGS_H 1 /* Define to 1 if you have the <string.h> header file. */ #define HAVE_STRING_H 1 /* Define to 1 if you have the `strxfrm_l' function. */ #define HAVE_STRXFRM_L 1 /* Define to 1 if you have the <sys/select.h> header file. */ #define HAVE_SYS_SELECT_H 1 /* Define to 1 if you have the <sys/stat.h> header file. */ #define HAVE_SYS_STAT_H 1 /* Define to 1 if you have the <sys/timeb.h> header file. */ #define HAVE_SYS_TIMEB_H 1 /* Define to 1 if you have the <sys/time.h> header file. */ #define HAVE_SYS_TIME_H 1 /* Define to 1 if you have the <sys/types.h> header file. */ #define HAVE_SYS_TYPES_H 1 /* Define to 1 if you have the `time' function. */ #define HAVE_TIME 1 /* Define to 1 if you have the <time.h> header file. */ #define HAVE_TIME_H 1 /* Define to 1 if you have the <unistd.h> header file. */ #define HAVE_UNISTD_H 1 /* Define to 1 if you have the `vfprintf' function. */ #define HAVE_VFPRINTF 1 /* Define to 1 if you have the `vsnprintf' function. */ #define HAVE_VSNPRINTF 1 /* Define to 1 if you have the `vsprintf' function. */ #define HAVE_VSPRINTF 1 /* Define to 1 if you have the <xlocale.h> header file. */ #define HAVE_XLOCALE_H 1 /* Define to 1 if you have the `_stat' function. */ /* #undef HAVE__STAT */ /* Define to the sub-directory where libtool stores uninstalled libraries. */ #define LT_OBJDIR ".libs/" /* Name of package */ #define PACKAGE "libxslt" /* Define to the address where bug reports for this package should be sent. */ #define PACKAGE_BUGREPORT "" /* Define to the full name of this package. */ #define PACKAGE_NAME "libxslt" /* Define to the full name and version of this package. */ #define PACKAGE_STRING "libxslt 1.1.32" /* Define to the one symbol short name of this package. */ #define PACKAGE_TARNAME "libxslt" /* Define to the home page for this package. */ #define PACKAGE_URL "" /* Define to the version of this package. */ #define PACKAGE_VERSION "1.1.32" /* Define to 1 if you have the ANSI C header files. */ #define STDC_HEADERS 1 /* Enable extensions on AIX 3, Interix. */ #ifndef _ALL_SOURCE # define _ALL_SOURCE 1 #endif /* Enable GNU extensions on systems that have them. */ #ifndef _GNU_SOURCE # define _GNU_SOURCE 1 #endif /* Enable threading extensions on Solaris. */ #ifndef _POSIX_PTHREAD_SEMANTICS # define _POSIX_PTHREAD_SEMANTICS 1 #endif /* Enable extensions on HP NonStop. */ #ifndef _TANDEM_SOURCE # define _TANDEM_SOURCE 1 #endif /* Enable general extensions on Solaris. */ #ifndef __EXTENSIONS__ # define __EXTENSIONS__ 1 #endif /* Version number of package */ #define VERSION "1.1.32" /* Define if debugging support is enabled */ /* #undef WITH_DEBUGGER */ /* Define to 1 if on MINIX. */ /* #undef _MINIX */ /* Define to 2 if the system does not provide POSIX.1 features except with this defined. */ /* #undef _POSIX_1_SOURCE */ /* Define to 1 if you need to in order for `stat' and other things to work. */ /* #undef _POSIX_SOURCE */ /* Using the Win32 Socket implementation */ /* #undef _WINSOCKAPI_ */ /* Win32 Std C name mangling work-around */ /* #undef snprintf */ /* Win32 Std C name mangling work-around */ /* #undef vsnprintf */
null
null
null
null
37,143
15,240
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
180,235
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * This file is subject to the terms and conditions of the GNU General Public * License. See the file "COPYING" in the main directory of this archive * for more details. * * Copyright (C) 2008 Maxime Bizon <mbizon@freebox.fr> */ #include <linux/init.h> #include <linux/kernel.h> #include <linux/platform_device.h> #include <bcm63xx_cpu.h> static struct resource uart0_resources[] = { { /* start & end filled at runtime */ .flags = IORESOURCE_MEM, }, { /* start filled at runtime */ .flags = IORESOURCE_IRQ, }, }; static struct resource uart1_resources[] = { { /* start & end filled at runtime */ .flags = IORESOURCE_MEM, }, { /* start filled at runtime */ .flags = IORESOURCE_IRQ, }, }; static struct platform_device bcm63xx_uart_devices[] = { { .name = "bcm63xx_uart", .id = 0, .num_resources = ARRAY_SIZE(uart0_resources), .resource = uart0_resources, }, { .name = "bcm63xx_uart", .id = 1, .num_resources = ARRAY_SIZE(uart1_resources), .resource = uart1_resources, } }; int __init bcm63xx_uart_register(unsigned int id) { if (id >= ARRAY_SIZE(bcm63xx_uart_devices)) return -ENODEV; if (id == 1 && (!BCMCPU_IS_3368() && !BCMCPU_IS_6358() && !BCMCPU_IS_6368())) return -ENODEV; if (id == 0) { uart0_resources[0].start = bcm63xx_regset_address(RSET_UART0); uart0_resources[0].end = uart0_resources[0].start + RSET_UART_SIZE - 1; uart0_resources[1].start = bcm63xx_get_irq_number(IRQ_UART0); } if (id == 1) { uart1_resources[0].start = bcm63xx_regset_address(RSET_UART1); uart1_resources[0].end = uart1_resources[0].start + RSET_UART_SIZE - 1; uart1_resources[1].start = bcm63xx_get_irq_number(IRQ_UART1); } return platform_device_register(&bcm63xx_uart_devices[id]); }
null
null
null
null
88,582
23,931
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
188,926
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * lms501kf03 TFT LCD panel driver. * * Copyright (c) 2012 Samsung Electronics Co., Ltd. * Author: Jingoo Han <jg1.han@samsung.com> * * 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. */ #include <linux/backlight.h> #include <linux/delay.h> #include <linux/fb.h> #include <linux/gpio.h> #include <linux/lcd.h> #include <linux/module.h> #include <linux/spi/spi.h> #include <linux/wait.h> #define COMMAND_ONLY 0x00 #define DATA_ONLY 0x01 struct lms501kf03 { struct device *dev; struct spi_device *spi; unsigned int power; struct lcd_device *ld; struct lcd_platform_data *lcd_pd; }; static const unsigned char seq_password[] = { 0xb9, 0xff, 0x83, 0x69, }; static const unsigned char seq_power[] = { 0xb1, 0x01, 0x00, 0x34, 0x06, 0x00, 0x14, 0x14, 0x20, 0x28, 0x12, 0x12, 0x17, 0x0a, 0x01, 0xe6, 0xe6, 0xe6, 0xe6, 0xe6, }; static const unsigned char seq_display[] = { 0xb2, 0x00, 0x2b, 0x03, 0x03, 0x70, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0x03, 0x03, 0x00, 0x01, }; static const unsigned char seq_rgb_if[] = { 0xb3, 0x09, }; static const unsigned char seq_display_inv[] = { 0xb4, 0x01, 0x08, 0x77, 0x0e, 0x06, }; static const unsigned char seq_vcom[] = { 0xb6, 0x4c, 0x2e, }; static const unsigned char seq_gate[] = { 0xd5, 0x00, 0x05, 0x03, 0x29, 0x01, 0x07, 0x17, 0x68, 0x13, 0x37, 0x20, 0x31, 0x8a, 0x46, 0x9b, 0x57, 0x13, 0x02, 0x75, 0xb9, 0x64, 0xa8, 0x07, 0x0f, 0x04, 0x07, }; static const unsigned char seq_panel[] = { 0xcc, 0x02, }; static const unsigned char seq_col_mod[] = { 0x3a, 0x77, }; static const unsigned char seq_w_gamma[] = { 0xe0, 0x00, 0x04, 0x09, 0x0f, 0x1f, 0x3f, 0x1f, 0x2f, 0x0a, 0x0f, 0x10, 0x16, 0x18, 0x16, 0x17, 0x0d, 0x15, 0x00, 0x04, 0x09, 0x0f, 0x38, 0x3f, 0x20, 0x39, 0x0a, 0x0f, 0x10, 0x16, 0x18, 0x16, 0x17, 0x0d, 0x15, }; static const unsigned char seq_rgb_gamma[] = { 0xc1, 0x01, 0x03, 0x07, 0x0f, 0x1a, 0x22, 0x2c, 0x33, 0x3c, 0x46, 0x4f, 0x58, 0x60, 0x69, 0x71, 0x79, 0x82, 0x89, 0x92, 0x9a, 0xa1, 0xa9, 0xb1, 0xb9, 0xc1, 0xc9, 0xcf, 0xd6, 0xde, 0xe5, 0xec, 0xf3, 0xf9, 0xff, 0xdd, 0x39, 0x07, 0x1c, 0xcb, 0xab, 0x5f, 0x49, 0x80, 0x03, 0x07, 0x0f, 0x19, 0x20, 0x2a, 0x31, 0x39, 0x42, 0x4b, 0x53, 0x5b, 0x63, 0x6b, 0x73, 0x7b, 0x83, 0x8a, 0x92, 0x9b, 0xa2, 0xaa, 0xb2, 0xba, 0xc2, 0xca, 0xd0, 0xd8, 0xe1, 0xe8, 0xf0, 0xf8, 0xff, 0xf7, 0xd8, 0xbe, 0xa7, 0x39, 0x40, 0x85, 0x8c, 0xc0, 0x04, 0x07, 0x0c, 0x17, 0x1c, 0x23, 0x2b, 0x34, 0x3b, 0x43, 0x4c, 0x54, 0x5b, 0x63, 0x6a, 0x73, 0x7a, 0x82, 0x8a, 0x91, 0x98, 0xa1, 0xa8, 0xb0, 0xb7, 0xc1, 0xc9, 0xcf, 0xd9, 0xe3, 0xea, 0xf4, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; static const unsigned char seq_up_dn[] = { 0x36, 0x10, }; static const unsigned char seq_sleep_in[] = { 0x10, }; static const unsigned char seq_sleep_out[] = { 0x11, }; static const unsigned char seq_display_on[] = { 0x29, }; static const unsigned char seq_display_off[] = { 0x10, }; static int lms501kf03_spi_write_byte(struct lms501kf03 *lcd, int addr, int data) { u16 buf[1]; struct spi_message msg; struct spi_transfer xfer = { .len = 2, .tx_buf = buf, }; buf[0] = (addr << 8) | data; spi_message_init(&msg); spi_message_add_tail(&xfer, &msg); return spi_sync(lcd->spi, &msg); } static int lms501kf03_spi_write(struct lms501kf03 *lcd, unsigned char address, unsigned char command) { return lms501kf03_spi_write_byte(lcd, address, command); } static int lms501kf03_panel_send_sequence(struct lms501kf03 *lcd, const unsigned char *wbuf, unsigned int len) { int ret = 0, i = 0; while (i < len) { if (i == 0) ret = lms501kf03_spi_write(lcd, COMMAND_ONLY, wbuf[i]); else ret = lms501kf03_spi_write(lcd, DATA_ONLY, wbuf[i]); if (ret) break; i += 1; } return ret; } static int lms501kf03_ldi_init(struct lms501kf03 *lcd) { int ret, i; static const unsigned char *init_seq[] = { seq_password, seq_power, seq_display, seq_rgb_if, seq_display_inv, seq_vcom, seq_gate, seq_panel, seq_col_mod, seq_w_gamma, seq_rgb_gamma, seq_sleep_out, }; static const unsigned int size_seq[] = { ARRAY_SIZE(seq_password), ARRAY_SIZE(seq_power), ARRAY_SIZE(seq_display), ARRAY_SIZE(seq_rgb_if), ARRAY_SIZE(seq_display_inv), ARRAY_SIZE(seq_vcom), ARRAY_SIZE(seq_gate), ARRAY_SIZE(seq_panel), ARRAY_SIZE(seq_col_mod), ARRAY_SIZE(seq_w_gamma), ARRAY_SIZE(seq_rgb_gamma), ARRAY_SIZE(seq_sleep_out), }; for (i = 0; i < ARRAY_SIZE(init_seq); i++) { ret = lms501kf03_panel_send_sequence(lcd, init_seq[i], size_seq[i]); if (ret) break; } /* * According to the datasheet, 120ms delay time is required. * After sleep out sequence, command is blocked for 120ms. * Thus, LDI should wait for 120ms. */ msleep(120); return ret; } static int lms501kf03_ldi_enable(struct lms501kf03 *lcd) { return lms501kf03_panel_send_sequence(lcd, seq_display_on, ARRAY_SIZE(seq_display_on)); } static int lms501kf03_ldi_disable(struct lms501kf03 *lcd) { return lms501kf03_panel_send_sequence(lcd, seq_display_off, ARRAY_SIZE(seq_display_off)); } static int lms501kf03_power_is_on(int power) { return (power) <= FB_BLANK_NORMAL; } static int lms501kf03_power_on(struct lms501kf03 *lcd) { int ret = 0; struct lcd_platform_data *pd; pd = lcd->lcd_pd; if (!pd->power_on) { dev_err(lcd->dev, "power_on is NULL.\n"); return -EINVAL; } pd->power_on(lcd->ld, 1); msleep(pd->power_on_delay); if (!pd->reset) { dev_err(lcd->dev, "reset is NULL.\n"); return -EINVAL; } pd->reset(lcd->ld); msleep(pd->reset_delay); ret = lms501kf03_ldi_init(lcd); if (ret) { dev_err(lcd->dev, "failed to initialize ldi.\n"); return ret; } ret = lms501kf03_ldi_enable(lcd); if (ret) { dev_err(lcd->dev, "failed to enable ldi.\n"); return ret; } return 0; } static int lms501kf03_power_off(struct lms501kf03 *lcd) { int ret = 0; struct lcd_platform_data *pd; pd = lcd->lcd_pd; ret = lms501kf03_ldi_disable(lcd); if (ret) { dev_err(lcd->dev, "lcd setting failed.\n"); return -EIO; } msleep(pd->power_off_delay); pd->power_on(lcd->ld, 0); return 0; } static int lms501kf03_power(struct lms501kf03 *lcd, int power) { int ret = 0; if (lms501kf03_power_is_on(power) && !lms501kf03_power_is_on(lcd->power)) ret = lms501kf03_power_on(lcd); else if (!lms501kf03_power_is_on(power) && lms501kf03_power_is_on(lcd->power)) ret = lms501kf03_power_off(lcd); if (!ret) lcd->power = power; return ret; } static int lms501kf03_get_power(struct lcd_device *ld) { struct lms501kf03 *lcd = lcd_get_data(ld); return lcd->power; } static int lms501kf03_set_power(struct lcd_device *ld, int power) { struct lms501kf03 *lcd = lcd_get_data(ld); if (power != FB_BLANK_UNBLANK && power != FB_BLANK_POWERDOWN && power != FB_BLANK_NORMAL) { dev_err(lcd->dev, "power value should be 0, 1 or 4.\n"); return -EINVAL; } return lms501kf03_power(lcd, power); } static struct lcd_ops lms501kf03_lcd_ops = { .get_power = lms501kf03_get_power, .set_power = lms501kf03_set_power, }; static int lms501kf03_probe(struct spi_device *spi) { struct lms501kf03 *lcd = NULL; struct lcd_device *ld = NULL; int ret = 0; lcd = devm_kzalloc(&spi->dev, sizeof(struct lms501kf03), GFP_KERNEL); if (!lcd) return -ENOMEM; /* lms501kf03 lcd panel uses 3-wire 9-bit SPI Mode. */ spi->bits_per_word = 9; ret = spi_setup(spi); if (ret < 0) { dev_err(&spi->dev, "spi setup failed.\n"); return ret; } lcd->spi = spi; lcd->dev = &spi->dev; lcd->lcd_pd = dev_get_platdata(&spi->dev); if (!lcd->lcd_pd) { dev_err(&spi->dev, "platform data is NULL\n"); return -EINVAL; } ld = devm_lcd_device_register(&spi->dev, "lms501kf03", &spi->dev, lcd, &lms501kf03_lcd_ops); if (IS_ERR(ld)) return PTR_ERR(ld); lcd->ld = ld; if (!lcd->lcd_pd->lcd_enabled) { /* * if lcd panel was off from bootloader then * current lcd status is powerdown and then * it enables lcd panel. */ lcd->power = FB_BLANK_POWERDOWN; lms501kf03_power(lcd, FB_BLANK_UNBLANK); } else { lcd->power = FB_BLANK_UNBLANK; } spi_set_drvdata(spi, lcd); dev_info(&spi->dev, "lms501kf03 panel driver has been probed.\n"); return 0; } static int lms501kf03_remove(struct spi_device *spi) { struct lms501kf03 *lcd = spi_get_drvdata(spi); lms501kf03_power(lcd, FB_BLANK_POWERDOWN); return 0; } #ifdef CONFIG_PM_SLEEP static int lms501kf03_suspend(struct device *dev) { struct lms501kf03 *lcd = dev_get_drvdata(dev); dev_dbg(dev, "lcd->power = %d\n", lcd->power); /* * when lcd panel is suspend, lcd panel becomes off * regardless of status. */ return lms501kf03_power(lcd, FB_BLANK_POWERDOWN); } static int lms501kf03_resume(struct device *dev) { struct lms501kf03 *lcd = dev_get_drvdata(dev); lcd->power = FB_BLANK_POWERDOWN; return lms501kf03_power(lcd, FB_BLANK_UNBLANK); } #endif static SIMPLE_DEV_PM_OPS(lms501kf03_pm_ops, lms501kf03_suspend, lms501kf03_resume); static void lms501kf03_shutdown(struct spi_device *spi) { struct lms501kf03 *lcd = spi_get_drvdata(spi); lms501kf03_power(lcd, FB_BLANK_POWERDOWN); } static struct spi_driver lms501kf03_driver = { .driver = { .name = "lms501kf03", .pm = &lms501kf03_pm_ops, }, .probe = lms501kf03_probe, .remove = lms501kf03_remove, .shutdown = lms501kf03_shutdown, }; module_spi_driver(lms501kf03_driver); MODULE_AUTHOR("Jingoo Han <jg1.han@samsung.com>"); MODULE_DESCRIPTION("lms501kf03 LCD Driver"); MODULE_LICENSE("GPL");
null
null
null
null
97,273
69,933
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
69,933
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// 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 "device/bluetooth/bluetooth_adapter_win.h" #include <memory> #include <string> #include <utility> #include "base/location.h" #include "base/logging.h" #include "base/memory/ptr_util.h" #include "base/sequenced_task_runner.h" #include "base/single_thread_task_runner.h" #include "base/stl_util.h" #include "base/threading/thread_task_runner_handle.h" #include "device/bluetooth/bluetooth_device_win.h" #include "device/bluetooth/bluetooth_discovery_session_outcome.h" #include "device/bluetooth/bluetooth_socket_thread.h" #include "device/bluetooth/bluetooth_socket_win.h" #include "device/bluetooth/bluetooth_task_manager_win.h" #include "device/bluetooth/bluetooth_uuid.h" namespace device { // static base::WeakPtr<BluetoothAdapter> BluetoothAdapter::CreateAdapter( const InitCallback& init_callback) { return BluetoothAdapterWin::CreateAdapter(init_callback); } // static base::WeakPtr<BluetoothAdapter> BluetoothAdapterWin::CreateAdapter( const InitCallback& init_callback) { BluetoothAdapterWin* adapter = new BluetoothAdapterWin(init_callback); adapter->Init(); return adapter->weak_ptr_factory_.GetWeakPtr(); } BluetoothAdapterWin::BluetoothAdapterWin(const InitCallback& init_callback) : BluetoothAdapter(), init_callback_(init_callback), initialized_(false), powered_(false), discovery_status_(NOT_DISCOVERING), num_discovery_listeners_(0), force_update_device_for_test_(false), weak_ptr_factory_(this) {} BluetoothAdapterWin::~BluetoothAdapterWin() { if (task_manager_.get()) task_manager_->RemoveObserver(this); } std::string BluetoothAdapterWin::GetAddress() const { return address_; } std::string BluetoothAdapterWin::GetName() const { return name_; } void BluetoothAdapterWin::SetName(const std::string& name, const base::Closure& callback, const ErrorCallback& error_callback) { NOTIMPLEMENTED(); } // TODO(youngki): Return true when |task_manager_| initializes the adapter // state. bool BluetoothAdapterWin::IsInitialized() const { return initialized_; } bool BluetoothAdapterWin::IsPresent() const { return !address_.empty(); } bool BluetoothAdapterWin::IsPowered() const { return powered_; } void BluetoothAdapterWin::SetPowered( bool powered, const base::Closure& callback, const ErrorCallback& error_callback) { task_manager_->PostSetPoweredBluetoothTask(powered, callback, error_callback); } bool BluetoothAdapterWin::IsDiscoverable() const { NOTIMPLEMENTED(); return false; } void BluetoothAdapterWin::SetDiscoverable( bool discoverable, const base::Closure& callback, const ErrorCallback& error_callback) { NOTIMPLEMENTED(); } bool BluetoothAdapterWin::IsDiscovering() const { return discovery_status_ == DISCOVERING || discovery_status_ == DISCOVERY_STOPPING; } static void RunDiscoverySessionErrorCallback( const base::Callback<void(UMABluetoothDiscoverySessionOutcome)>& callback, UMABluetoothDiscoverySessionOutcome outcome) { callback.Run(outcome); } void BluetoothAdapterWin::DiscoveryStarted(bool success) { discovery_status_ = success ? DISCOVERING : NOT_DISCOVERING; for (const auto& callbacks : on_start_discovery_callbacks_) { if (success) ui_task_runner_->PostTask(FROM_HERE, callbacks.first); else ui_task_runner_->PostTask( FROM_HERE, base::Bind(&RunDiscoverySessionErrorCallback, callbacks.second, UMABluetoothDiscoverySessionOutcome::UNKNOWN)); } num_discovery_listeners_ = on_start_discovery_callbacks_.size(); on_start_discovery_callbacks_.clear(); if (success) { for (auto& observer : observers_) observer.AdapterDiscoveringChanged(this, true); // If there are stop discovery requests, post the stop discovery again. MaybePostStopDiscoveryTask(); } else if (!on_stop_discovery_callbacks_.empty()) { // If there are stop discovery requests but start discovery has failed, // notify that stop discovery has been complete. DiscoveryStopped(); } } void BluetoothAdapterWin::DiscoveryStopped() { discovered_devices_.clear(); bool was_discovering = IsDiscovering(); discovery_status_ = NOT_DISCOVERING; for (std::vector<base::Closure>::const_iterator iter = on_stop_discovery_callbacks_.begin(); iter != on_stop_discovery_callbacks_.end(); ++iter) { ui_task_runner_->PostTask(FROM_HERE, *iter); } num_discovery_listeners_ = 0; on_stop_discovery_callbacks_.clear(); if (was_discovering) for (auto& observer : observers_) observer.AdapterDiscoveringChanged(this, false); // If there are start discovery requests, post the start discovery again. MaybePostStartDiscoveryTask(); } BluetoothAdapter::UUIDList BluetoothAdapterWin::GetUUIDs() const { NOTIMPLEMENTED(); return UUIDList(); } void BluetoothAdapterWin::CreateRfcommService( const BluetoothUUID& uuid, const ServiceOptions& options, const CreateServiceCallback& callback, const CreateServiceErrorCallback& error_callback) { scoped_refptr<BluetoothSocketWin> socket = BluetoothSocketWin::CreateBluetoothSocket( ui_task_runner_, socket_thread_); socket->Listen(this, uuid, options, base::Bind(callback, socket), error_callback); } void BluetoothAdapterWin::CreateL2capService( const BluetoothUUID& uuid, const ServiceOptions& options, const CreateServiceCallback& callback, const CreateServiceErrorCallback& error_callback) { // TODO(keybuk): implement. NOTIMPLEMENTED(); } void BluetoothAdapterWin::RegisterAdvertisement( std::unique_ptr<BluetoothAdvertisement::Data> advertisement_data, const CreateAdvertisementCallback& callback, const AdvertisementErrorCallback& error_callback) { NOTIMPLEMENTED(); error_callback.Run(BluetoothAdvertisement::ERROR_UNSUPPORTED_PLATFORM); } BluetoothLocalGattService* BluetoothAdapterWin::GetGattService( const std::string& identifier) const { return nullptr; } void BluetoothAdapterWin::RemovePairingDelegateInternal( BluetoothDevice::PairingDelegate* pairing_delegate) { } void BluetoothAdapterWin::AdapterStateChanged( const BluetoothTaskManagerWin::AdapterState& state) { DCHECK(thread_checker_.CalledOnValidThread()); name_ = state.name; bool was_present = IsPresent(); bool is_present = !state.address.empty(); address_ = BluetoothDevice::CanonicalizeAddress(state.address); if (was_present != is_present) { for (auto& observer : observers_) observer.AdapterPresentChanged(this, is_present); } if (powered_ != state.powered) { powered_ = state.powered; for (auto& observer : observers_) observer.AdapterPoweredChanged(this, powered_); } if (!initialized_) { initialized_ = true; init_callback_.Run(); } } void BluetoothAdapterWin::DevicesPolled( const std::vector<std::unique_ptr<BluetoothTaskManagerWin::DeviceState>>& devices) { DCHECK(thread_checker_.CalledOnValidThread()); // We are receiving a new list of all devices known to the system. Merge this // new list with the list we know of (|devices_|) and raise corresponding // DeviceAdded, DeviceRemoved and DeviceChanged events. using DeviceAddressSet = std::set<std::string>; DeviceAddressSet known_devices; for (const auto& device : devices_) known_devices.insert(device.first); DeviceAddressSet new_devices; for (const auto& device_state : devices) new_devices.insert(device_state->address); // Process device removal first. DeviceAddressSet removed_devices = base::STLSetDifference<DeviceAddressSet>(known_devices, new_devices); for (const auto& device : removed_devices) { auto it = devices_.find(device); std::unique_ptr<BluetoothDevice> device_win = std::move(it->second); devices_.erase(it); for (auto& observer : observers_) observer.DeviceRemoved(this, device_win.get()); } // Process added and (maybe) changed devices in one pass. DeviceAddressSet added_devices = base::STLSetDifference<DeviceAddressSet>(new_devices, known_devices); DeviceAddressSet changed_devices = base::STLSetIntersection<DeviceAddressSet>(known_devices, new_devices); for (const auto& device_state : devices) { if (added_devices.find(device_state->address) != added_devices.end()) { auto device_win = std::make_unique<BluetoothDeviceWin>( this, *device_state, ui_task_runner_, socket_thread_); BluetoothDeviceWin* device_win_raw = device_win.get(); devices_[device_state->address] = std::move(device_win); for (auto& observer : observers_) observer.DeviceAdded(this, device_win_raw); } else if (changed_devices.find(device_state->address) != changed_devices.end()) { auto iter = devices_.find(device_state->address); DCHECK(iter != devices_.end()); BluetoothDeviceWin* device_win = static_cast<BluetoothDeviceWin*>(iter->second.get()); if (!device_win->IsEqual(*device_state)) { device_win->Update(*device_state); for (auto& observer : observers_) observer.DeviceChanged(this, device_win); } // Above IsEqual returns true if device name, address, status and services // (primary services of BLE device) are the same. However, in BLE tests, // we may simulate characteristic, descriptor and secondary GATT service // after device has been initialized. if (force_update_device_for_test_) { device_win->Update(*device_state); } } } } // BluetoothAdapterWin should override SetPowered() instead. bool BluetoothAdapterWin::SetPoweredImpl(bool powered) { NOTREACHED(); return false; } // If the method is called when |discovery_status_| is DISCOVERY_STOPPING, // starting again is handled by BluetoothAdapterWin::DiscoveryStopped(). void BluetoothAdapterWin::AddDiscoverySession( BluetoothDiscoveryFilter* discovery_filter, const base::Closure& callback, const DiscoverySessionErrorCallback& error_callback) { if (discovery_status_ == DISCOVERING) { num_discovery_listeners_++; callback.Run(); return; } on_start_discovery_callbacks_.push_back( std::make_pair(callback, error_callback)); MaybePostStartDiscoveryTask(); } void BluetoothAdapterWin::RemoveDiscoverySession( BluetoothDiscoveryFilter* discovery_filter, const base::Closure& callback, const DiscoverySessionErrorCallback& error_callback) { if (discovery_status_ == NOT_DISCOVERING) { error_callback.Run(UMABluetoothDiscoverySessionOutcome::NOT_ACTIVE); return; } on_stop_discovery_callbacks_.push_back(callback); MaybePostStopDiscoveryTask(); } void BluetoothAdapterWin::SetDiscoveryFilter( std::unique_ptr<BluetoothDiscoveryFilter> discovery_filter, const base::Closure& callback, const DiscoverySessionErrorCallback& error_callback) { NOTIMPLEMENTED(); error_callback.Run(UMABluetoothDiscoverySessionOutcome::NOT_IMPLEMENTED); } void BluetoothAdapterWin::Init() { ui_task_runner_ = base::ThreadTaskRunnerHandle::Get(); socket_thread_ = BluetoothSocketThread::Get(); task_manager_ = new BluetoothTaskManagerWin(ui_task_runner_); task_manager_->AddObserver(this); task_manager_->Initialize(); } void BluetoothAdapterWin::InitForTest( scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner, scoped_refptr<base::SequencedTaskRunner> bluetooth_task_runner) { ui_task_runner_ = ui_task_runner; if (!ui_task_runner_) ui_task_runner_ = base::ThreadTaskRunnerHandle::Get(); task_manager_ = new BluetoothTaskManagerWin(ui_task_runner_); task_manager_->AddObserver(this); task_manager_->InitializeWithBluetoothTaskRunner(bluetooth_task_runner); } void BluetoothAdapterWin::MaybePostStartDiscoveryTask() { if (discovery_status_ == NOT_DISCOVERING && !on_start_discovery_callbacks_.empty()) { discovery_status_ = DISCOVERY_STARTING; task_manager_->PostStartDiscoveryTask(); } } void BluetoothAdapterWin::MaybePostStopDiscoveryTask() { if (discovery_status_ != DISCOVERING) return; if (on_stop_discovery_callbacks_.size() < num_discovery_listeners_) { for (std::vector<base::Closure>::const_iterator iter = on_stop_discovery_callbacks_.begin(); iter != on_stop_discovery_callbacks_.end(); ++iter) { ui_task_runner_->PostTask(FROM_HERE, *iter); } num_discovery_listeners_ -= on_stop_discovery_callbacks_.size(); on_stop_discovery_callbacks_.clear(); return; } discovery_status_ = DISCOVERY_STOPPING; task_manager_->PostStopDiscoveryTask(); } } // namespace device
null
null
null
null
66,796
26,418
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
26,418
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// 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 <stdint.h> #include "base/bind.h" #include "base/threading/thread_task_runner_handle.h" #include "jingle/glue/task_pump.h" namespace jingle_glue { TaskPump::TaskPump() : posted_wake_(false), stopped_(false), weak_factory_(this) { } TaskPump::~TaskPump() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); } void TaskPump::WakeTasks() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); if (!stopped_ && !posted_wake_) { // Do the requested wake up. base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&TaskPump::CheckAndRunTasks, weak_factory_.GetWeakPtr())); posted_wake_ = true; } } int64_t TaskPump::CurrentTime() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); // Only timeout tasks rely on this function. Since we're not using // libjingle tasks for timeout, it's safe to return 0 here. return 0; } void TaskPump::Stop() { stopped_ = true; } void TaskPump::CheckAndRunTasks() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); if (stopped_) { return; } posted_wake_ = false; // We shouldn't be using libjingle for timeout tasks, so we should // have no timeout tasks at all. // TODO(akalin): Add HasTimeoutTask() back in TaskRunner class and // uncomment this check. // DCHECK(!HasTimeoutTask()) RunTasks(); } } // namespace jingle_glue
null
null
null
null
23,281
45,318
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
45,318
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef ASH_DISPLAY_SCREEN_POSITION_CONTROLLER_H_ #define ASH_DISPLAY_SCREEN_POSITION_CONTROLLER_H_ #include <vector> #include "ash/ash_export.h" #include "base/macros.h" #include "ui/aura/client/screen_position_client.h" namespace ash { class ASH_EXPORT ScreenPositionController : public aura::client::ScreenPositionClient { public: // Finds the root window at |location| in |window|'s coordinates // from given |root_windows| and returns the found root window and // location in that root window's coordinates. The function usually // returns |window->GetRootWindow()|, but if the mouse pointer is // moved outside the |window|'s root while the mouse is captured, it // returns the other root window. static void ConvertHostPointToRelativeToRootWindow( aura::Window* root_window, const std::vector<aura::Window*>& root_windows, gfx::Point* point_in_host, aura::Window** target_window); ScreenPositionController() {} ~ScreenPositionController() override {} // aura::client::ScreenPositionClient overrides: void ConvertPointToScreen(const aura::Window* window, gfx::PointF* point) override; void ConvertPointFromScreen(const aura::Window* window, gfx::PointF* point) override; void ConvertHostPointToScreen(aura::Window* window, gfx::Point* point) override; void SetBounds(aura::Window* window, const gfx::Rect& bounds, const display::Display& display) override; private: DISALLOW_COPY_AND_ASSIGN(ScreenPositionController); }; } // namespace ash #endif // ASH_DISPLAY_SCREEN_POSITION_CONTROLLER_H_
null
null
null
null
42,181
31,588
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
196,583
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* $Id: b1pci.c,v 1.1.2.2 2004/01/16 21:09:27 keil Exp $ * * Module for AVM B1 PCI-card. * * Copyright 1999 by Carsten Paeth <calle@calle.de> * * This software may be used and distributed according to the terms * of the GNU General Public License, incorporated herein by reference. * */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/skbuff.h> #include <linux/delay.h> #include <linux/mm.h> #include <linux/interrupt.h> #include <linux/ioport.h> #include <linux/pci.h> #include <linux/capi.h> #include <asm/io.h> #include <linux/init.h> #include <linux/isdn/capicmd.h> #include <linux/isdn/capiutil.h> #include <linux/isdn/capilli.h> #include "avmcard.h" /* ------------------------------------------------------------- */ static char *revision = "$Revision: 1.1.2.2 $"; /* ------------------------------------------------------------- */ static struct pci_device_id b1pci_pci_tbl[] = { { PCI_VENDOR_ID_AVM, PCI_DEVICE_ID_AVM_B1, PCI_ANY_ID, PCI_ANY_ID }, { } /* Terminating entry */ }; MODULE_DEVICE_TABLE(pci, b1pci_pci_tbl); MODULE_DESCRIPTION("CAPI4Linux: Driver for AVM B1 PCI card"); MODULE_AUTHOR("Carsten Paeth"); MODULE_LICENSE("GPL"); /* ------------------------------------------------------------- */ static char *b1pci_procinfo(struct capi_ctr *ctrl) { avmctrl_info *cinfo = (avmctrl_info *)(ctrl->driverdata); if (!cinfo) return ""; sprintf(cinfo->infobuf, "%s %s 0x%x %d r%d", cinfo->cardname[0] ? cinfo->cardname : "-", cinfo->version[VER_DRIVER] ? cinfo->version[VER_DRIVER] : "-", cinfo->card ? cinfo->card->port : 0x0, cinfo->card ? cinfo->card->irq : 0, cinfo->card ? cinfo->card->revision : 0 ); return cinfo->infobuf; } /* ------------------------------------------------------------- */ static int b1pci_probe(struct capicardparams *p, struct pci_dev *pdev) { avmcard *card; avmctrl_info *cinfo; int retval; card = b1_alloc_card(1); if (!card) { printk(KERN_WARNING "b1pci: no memory.\n"); retval = -ENOMEM; goto err; } cinfo = card->ctrlinfo; sprintf(card->name, "b1pci-%x", p->port); card->port = p->port; card->irq = p->irq; card->cardtype = avm_b1pci; if (!request_region(card->port, AVMB1_PORTLEN, card->name)) { printk(KERN_WARNING "b1pci: ports 0x%03x-0x%03x in use.\n", card->port, card->port + AVMB1_PORTLEN); retval = -EBUSY; goto err_free; } b1_reset(card->port); retval = b1_detect(card->port, card->cardtype); if (retval) { printk(KERN_NOTICE "b1pci: NO card at 0x%x (%d)\n", card->port, retval); retval = -ENODEV; goto err_release_region; } b1_reset(card->port); b1_getrevision(card); retval = request_irq(card->irq, b1_interrupt, IRQF_SHARED, card->name, card); if (retval) { printk(KERN_ERR "b1pci: unable to get IRQ %d.\n", card->irq); retval = -EBUSY; goto err_release_region; } cinfo->capi_ctrl.driver_name = "b1pci"; cinfo->capi_ctrl.driverdata = cinfo; cinfo->capi_ctrl.register_appl = b1_register_appl; cinfo->capi_ctrl.release_appl = b1_release_appl; cinfo->capi_ctrl.send_message = b1_send_message; cinfo->capi_ctrl.load_firmware = b1_load_firmware; cinfo->capi_ctrl.reset_ctr = b1_reset_ctr; cinfo->capi_ctrl.procinfo = b1pci_procinfo; cinfo->capi_ctrl.proc_fops = &b1ctl_proc_fops; strcpy(cinfo->capi_ctrl.name, card->name); cinfo->capi_ctrl.owner = THIS_MODULE; retval = attach_capi_ctr(&cinfo->capi_ctrl); if (retval) { printk(KERN_ERR "b1pci: attach controller failed.\n"); goto err_free_irq; } if (card->revision >= 4) { printk(KERN_INFO "b1pci: AVM B1 PCI V4 at i/o %#x, irq %d, revision %d (no dma)\n", card->port, card->irq, card->revision); } else { printk(KERN_INFO "b1pci: AVM B1 PCI at i/o %#x, irq %d, revision %d\n", card->port, card->irq, card->revision); } pci_set_drvdata(pdev, card); return 0; err_free_irq: free_irq(card->irq, card); err_release_region: release_region(card->port, AVMB1_PORTLEN); err_free: b1_free_card(card); err: return retval; } static void b1pci_remove(struct pci_dev *pdev) { avmcard *card = pci_get_drvdata(pdev); avmctrl_info *cinfo = card->ctrlinfo; unsigned int port = card->port; b1_reset(port); b1_reset(port); detach_capi_ctr(&cinfo->capi_ctrl); free_irq(card->irq, card); release_region(card->port, AVMB1_PORTLEN); b1_free_card(card); } #ifdef CONFIG_ISDN_DRV_AVMB1_B1PCIV4 /* ------------------------------------------------------------- */ static char *b1pciv4_procinfo(struct capi_ctr *ctrl) { avmctrl_info *cinfo = (avmctrl_info *)(ctrl->driverdata); if (!cinfo) return ""; sprintf(cinfo->infobuf, "%s %s 0x%x %d 0x%lx r%d", cinfo->cardname[0] ? cinfo->cardname : "-", cinfo->version[VER_DRIVER] ? cinfo->version[VER_DRIVER] : "-", cinfo->card ? cinfo->card->port : 0x0, cinfo->card ? cinfo->card->irq : 0, cinfo->card ? cinfo->card->membase : 0, cinfo->card ? cinfo->card->revision : 0 ); return cinfo->infobuf; } /* ------------------------------------------------------------- */ static int b1pciv4_probe(struct capicardparams *p, struct pci_dev *pdev) { avmcard *card; avmctrl_info *cinfo; int retval; card = b1_alloc_card(1); if (!card) { printk(KERN_WARNING "b1pci: no memory.\n"); retval = -ENOMEM; goto err; } card->dma = avmcard_dma_alloc("b1pci", pdev, 2048 + 128, 2048 + 128); if (!card->dma) { printk(KERN_WARNING "b1pci: dma alloc.\n"); retval = -ENOMEM; goto err_free; } cinfo = card->ctrlinfo; sprintf(card->name, "b1pciv4-%x", p->port); card->port = p->port; card->irq = p->irq; card->membase = p->membase; card->cardtype = avm_b1pci; if (!request_region(card->port, AVMB1_PORTLEN, card->name)) { printk(KERN_WARNING "b1pci: ports 0x%03x-0x%03x in use.\n", card->port, card->port + AVMB1_PORTLEN); retval = -EBUSY; goto err_free_dma; } card->mbase = ioremap(card->membase, 64); if (!card->mbase) { printk(KERN_NOTICE "b1pci: can't remap memory at 0x%lx\n", card->membase); retval = -ENOMEM; goto err_release_region; } b1dma_reset(card); retval = b1pciv4_detect(card); if (retval) { printk(KERN_NOTICE "b1pci: NO card at 0x%x (%d)\n", card->port, retval); retval = -ENODEV; goto err_unmap; } b1dma_reset(card); b1_getrevision(card); retval = request_irq(card->irq, b1dma_interrupt, IRQF_SHARED, card->name, card); if (retval) { printk(KERN_ERR "b1pci: unable to get IRQ %d.\n", card->irq); retval = -EBUSY; goto err_unmap; } cinfo->capi_ctrl.owner = THIS_MODULE; cinfo->capi_ctrl.driver_name = "b1pciv4"; cinfo->capi_ctrl.driverdata = cinfo; cinfo->capi_ctrl.register_appl = b1dma_register_appl; cinfo->capi_ctrl.release_appl = b1dma_release_appl; cinfo->capi_ctrl.send_message = b1dma_send_message; cinfo->capi_ctrl.load_firmware = b1dma_load_firmware; cinfo->capi_ctrl.reset_ctr = b1dma_reset_ctr; cinfo->capi_ctrl.procinfo = b1pciv4_procinfo; cinfo->capi_ctrl.proc_fops = &b1dmactl_proc_fops; strcpy(cinfo->capi_ctrl.name, card->name); retval = attach_capi_ctr(&cinfo->capi_ctrl); if (retval) { printk(KERN_ERR "b1pci: attach controller failed.\n"); goto err_free_irq; } card->cardnr = cinfo->capi_ctrl.cnr; printk(KERN_INFO "b1pci: AVM B1 PCI V4 at i/o %#x, irq %d, mem %#lx, revision %d (dma)\n", card->port, card->irq, card->membase, card->revision); pci_set_drvdata(pdev, card); return 0; err_free_irq: free_irq(card->irq, card); err_unmap: iounmap(card->mbase); err_release_region: release_region(card->port, AVMB1_PORTLEN); err_free_dma: avmcard_dma_free(card->dma); err_free: b1_free_card(card); err: return retval; } static void b1pciv4_remove(struct pci_dev *pdev) { avmcard *card = pci_get_drvdata(pdev); avmctrl_info *cinfo = card->ctrlinfo; b1dma_reset(card); detach_capi_ctr(&cinfo->capi_ctrl); free_irq(card->irq, card); iounmap(card->mbase); release_region(card->port, AVMB1_PORTLEN); avmcard_dma_free(card->dma); b1_free_card(card); } #endif /* CONFIG_ISDN_DRV_AVMB1_B1PCIV4 */ static int b1pci_pci_probe(struct pci_dev *pdev, const struct pci_device_id *ent) { struct capicardparams param; int retval; if (pci_enable_device(pdev) < 0) { printk(KERN_ERR "b1pci: failed to enable AVM-B1\n"); return -ENODEV; } param.irq = pdev->irq; if (pci_resource_start(pdev, 2)) { /* B1 PCI V4 */ #ifdef CONFIG_ISDN_DRV_AVMB1_B1PCIV4 pci_set_master(pdev); #endif param.membase = pci_resource_start(pdev, 0); param.port = pci_resource_start(pdev, 2); printk(KERN_INFO "b1pci: PCI BIOS reports AVM-B1 V4 at i/o %#x, irq %d, mem %#x\n", param.port, param.irq, param.membase); #ifdef CONFIG_ISDN_DRV_AVMB1_B1PCIV4 retval = b1pciv4_probe(&param, pdev); #else retval = b1pci_probe(&param, pdev); #endif if (retval != 0) { printk(KERN_ERR "b1pci: no AVM-B1 V4 at i/o %#x, irq %d, mem %#x detected\n", param.port, param.irq, param.membase); } } else { param.membase = 0; param.port = pci_resource_start(pdev, 1); printk(KERN_INFO "b1pci: PCI BIOS reports AVM-B1 at i/o %#x, irq %d\n", param.port, param.irq); retval = b1pci_probe(&param, pdev); if (retval != 0) { printk(KERN_ERR "b1pci: no AVM-B1 at i/o %#x, irq %d detected\n", param.port, param.irq); } } return retval; } static void b1pci_pci_remove(struct pci_dev *pdev) { #ifdef CONFIG_ISDN_DRV_AVMB1_B1PCIV4 avmcard *card = pci_get_drvdata(pdev); if (card->dma) b1pciv4_remove(pdev); else b1pci_remove(pdev); #else b1pci_remove(pdev); #endif } static struct pci_driver b1pci_pci_driver = { .name = "b1pci", .id_table = b1pci_pci_tbl, .probe = b1pci_pci_probe, .remove = b1pci_pci_remove, }; static struct capi_driver capi_driver_b1pci = { .name = "b1pci", .revision = "1.0", }; #ifdef CONFIG_ISDN_DRV_AVMB1_B1PCIV4 static struct capi_driver capi_driver_b1pciv4 = { .name = "b1pciv4", .revision = "1.0", }; #endif static int __init b1pci_init(void) { char *p; char rev[32]; int err; if ((p = strchr(revision, ':')) != NULL && p[1]) { strlcpy(rev, p + 2, 32); if ((p = strchr(rev, '$')) != NULL && p > rev) *(p - 1) = 0; } else strcpy(rev, "1.0"); err = pci_register_driver(&b1pci_pci_driver); if (!err) { strlcpy(capi_driver_b1pci.revision, rev, 32); register_capi_driver(&capi_driver_b1pci); #ifdef CONFIG_ISDN_DRV_AVMB1_B1PCIV4 strlcpy(capi_driver_b1pciv4.revision, rev, 32); register_capi_driver(&capi_driver_b1pciv4); #endif printk(KERN_INFO "b1pci: revision %s\n", rev); } return err; } static void __exit b1pci_exit(void) { unregister_capi_driver(&capi_driver_b1pci); #ifdef CONFIG_ISDN_DRV_AVMB1_B1PCIV4 unregister_capi_driver(&capi_driver_b1pciv4); #endif pci_unregister_driver(&b1pci_pci_driver); } module_init(b1pci_init); module_exit(b1pci_exit);
null
null
null
null
104,930
11,423
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
176,418
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
#ifndef _ASM_WORD_AT_A_TIME_H #define _ASM_WORD_AT_A_TIME_H #include <asm/byteorder.h> struct word_at_a_time { /* unused */ }; #define WORD_AT_A_TIME_CONSTANTS {} /* Generate 0x01 byte values for zero bytes using a SIMD instruction. */ static inline unsigned long has_zero(unsigned long val, unsigned long *data, const struct word_at_a_time *c) { #ifdef __tilegx__ unsigned long mask = __insn_v1cmpeqi(val, 0); #else /* tilepro */ unsigned long mask = __insn_seqib(val, 0); #endif *data = mask; return mask; } /* These operations are both nops. */ #define prep_zero_mask(val, data, c) (data) #define create_zero_mask(data) (data) /* And this operation just depends on endianness. */ static inline long find_zero(unsigned long mask) { #ifdef __BIG_ENDIAN return __builtin_clzl(mask) >> 3; #else return __builtin_ctzl(mask) >> 3; #endif } #ifdef __BIG_ENDIAN #define zero_bytemask(mask) (~1ul << (63 - __builtin_clzl(mask))) #else #define zero_bytemask(mask) ((2ul << __builtin_ctzl(mask)) - 1) #endif #endif /* _ASM_WORD_AT_A_TIME_H */
null
null
null
null
84,765
30,268
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
195,263
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * bdc_udc.c - BRCM BDC USB3.0 device controller gagdet ops * * Copyright (C) 2014 Broadcom Corporation * * Author: Ashwini Pahuja * * Based on drivers under drivers/usb/gadget/udc/ * * 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. * */ #include <linux/module.h> #include <linux/pci.h> #include <linux/dma-mapping.h> #include <linux/kernel.h> #include <linux/delay.h> #include <linux/ioport.h> #include <linux/sched.h> #include <linux/slab.h> #include <linux/errno.h> #include <linux/init.h> #include <linux/timer.h> #include <linux/list.h> #include <linux/interrupt.h> #include <linux/moduleparam.h> #include <linux/device.h> #include <linux/usb/ch9.h> #include <linux/usb/gadget.h> #include <linux/usb/otg.h> #include <linux/pm.h> #include <linux/io.h> #include <linux/irq.h> #include <asm/unaligned.h> #include <linux/platform_device.h> #include "bdc.h" #include "bdc_ep.h" #include "bdc_cmd.h" #include "bdc_dbg.h" static const struct usb_gadget_ops bdc_gadget_ops; static const char * const conn_speed_str[] = { "Not connected", "Full Speed", "Low Speed", "High Speed", "Super Speed", }; /* EP0 initial descripror */ static struct usb_endpoint_descriptor bdc_gadget_ep0_desc = { .bLength = USB_DT_ENDPOINT_SIZE, .bDescriptorType = USB_DT_ENDPOINT, .bmAttributes = USB_ENDPOINT_XFER_CONTROL, .bEndpointAddress = 0, .wMaxPacketSize = cpu_to_le16(EP0_MAX_PKT_SIZE), }; /* Advance the srr dqp maintained by SW */ static void srr_dqp_index_advc(struct bdc *bdc, u32 srr_num) { struct srr *srr; srr = &bdc->srr; dev_dbg_ratelimited(bdc->dev, "srr->dqp_index:%d\n", srr->dqp_index); srr->dqp_index++; /* rollback to 0 if we are past the last */ if (srr->dqp_index == NUM_SR_ENTRIES) srr->dqp_index = 0; } /* connect sr */ static void bdc_uspc_connected(struct bdc *bdc) { u32 speed, temp; u32 usppms; int ret; temp = bdc_readl(bdc->regs, BDC_USPC); speed = BDC_PSP(temp); dev_dbg(bdc->dev, "%s speed=%x\n", __func__, speed); switch (speed) { case BDC_SPEED_SS: bdc_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(EP0_MAX_PKT_SIZE); bdc->gadget.ep0->maxpacket = EP0_MAX_PKT_SIZE; bdc->gadget.speed = USB_SPEED_SUPER; /* Enable U1T in SS mode */ usppms = bdc_readl(bdc->regs, BDC_USPPMS); usppms &= ~BDC_U1T(0xff); usppms |= BDC_U1T(U1_TIMEOUT); usppms |= BDC_PORT_W1S; bdc_writel(bdc->regs, BDC_USPPMS, usppms); break; case BDC_SPEED_HS: bdc_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(64); bdc->gadget.ep0->maxpacket = 64; bdc->gadget.speed = USB_SPEED_HIGH; break; case BDC_SPEED_FS: bdc_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(64); bdc->gadget.ep0->maxpacket = 64; bdc->gadget.speed = USB_SPEED_FULL; break; case BDC_SPEED_LS: bdc_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(8); bdc->gadget.ep0->maxpacket = 8; bdc->gadget.speed = USB_SPEED_LOW; break; default: dev_err(bdc->dev, "UNDEFINED SPEED\n"); return; } dev_dbg(bdc->dev, "connected at %s\n", conn_speed_str[speed]); /* Now we know the speed, configure ep0 */ bdc->bdc_ep_array[1]->desc = &bdc_gadget_ep0_desc; ret = bdc_config_ep(bdc, bdc->bdc_ep_array[1]); if (ret) dev_err(bdc->dev, "EP0 config failed\n"); bdc->bdc_ep_array[1]->usb_ep.desc = &bdc_gadget_ep0_desc; bdc->bdc_ep_array[1]->flags |= BDC_EP_ENABLED; usb_gadget_set_state(&bdc->gadget, USB_STATE_DEFAULT); } /* device got disconnected */ static void bdc_uspc_disconnected(struct bdc *bdc, bool reinit) { struct bdc_ep *ep; dev_dbg(bdc->dev, "%s\n", __func__); /* * Only stop ep0 from here, rest of the endpoints will be disabled * from gadget_disconnect */ ep = bdc->bdc_ep_array[1]; if (ep && (ep->flags & BDC_EP_ENABLED)) /* if enabled then stop and remove requests */ bdc_ep_disable(ep); if (bdc->gadget_driver && bdc->gadget_driver->disconnect) { spin_unlock(&bdc->lock); bdc->gadget_driver->disconnect(&bdc->gadget); spin_lock(&bdc->lock); } /* Set Unknown speed */ bdc->gadget.speed = USB_SPEED_UNKNOWN; bdc->devstatus &= DEVSTATUS_CLEAR; bdc->delayed_status = false; bdc->reinit = reinit; bdc->test_mode = false; } /* TNotify wkaeup timer */ static void bdc_func_wake_timer(struct work_struct *work) { struct bdc *bdc = container_of(work, struct bdc, func_wake_notify.work); unsigned long flags; dev_dbg(bdc->dev, "%s\n", __func__); spin_lock_irqsave(&bdc->lock, flags); /* * Check if host has started transferring on endpoints * FUNC_WAKE_ISSUED is cleared when transfer has started after resume */ if (bdc->devstatus & FUNC_WAKE_ISSUED) { dev_dbg(bdc->dev, "FUNC_WAKE_ISSUED FLAG IS STILL SET\n"); /* flag is still set, so again send func wake */ bdc_function_wake_fh(bdc, 0); schedule_delayed_work(&bdc->func_wake_notify, msecs_to_jiffies(BDC_TNOTIFY)); } spin_unlock_irqrestore(&bdc->lock, flags); } /* handler for Link state change condition */ static void handle_link_state_change(struct bdc *bdc, u32 uspc) { u32 link_state; dev_dbg(bdc->dev, "Link state change"); link_state = BDC_PST(uspc); switch (link_state) { case BDC_LINK_STATE_U3: if ((bdc->gadget.speed != USB_SPEED_UNKNOWN) && bdc->gadget_driver->suspend) { dev_dbg(bdc->dev, "Entered Suspend mode\n"); spin_unlock(&bdc->lock); bdc->devstatus |= DEVICE_SUSPENDED; bdc->gadget_driver->suspend(&bdc->gadget); spin_lock(&bdc->lock); } break; case BDC_LINK_STATE_U0: if (bdc->devstatus & REMOTE_WAKEUP_ISSUED) { bdc->devstatus &= ~REMOTE_WAKEUP_ISSUED; if (bdc->gadget.speed == USB_SPEED_SUPER) { bdc_function_wake_fh(bdc, 0); bdc->devstatus |= FUNC_WAKE_ISSUED; /* * Start a Notification timer and check if the * Host transferred anything on any of the EPs, * if not then send function wake again every * TNotification secs until host initiates * transfer to BDC, USB3 spec Table 8.13 */ schedule_delayed_work( &bdc->func_wake_notify, msecs_to_jiffies(BDC_TNOTIFY)); dev_dbg(bdc->dev, "sched func_wake_notify\n"); } } break; case BDC_LINK_STATE_RESUME: dev_dbg(bdc->dev, "Resumed from Suspend\n"); if (bdc->devstatus & DEVICE_SUSPENDED) { bdc->gadget_driver->resume(&bdc->gadget); bdc->devstatus &= ~DEVICE_SUSPENDED; } break; default: dev_dbg(bdc->dev, "link state:%d\n", link_state); } } /* something changes on upstream port, handle it here */ void bdc_sr_uspc(struct bdc *bdc, struct bdc_sr *sreport) { u32 clear_flags = 0; u32 uspc; bool connected = false; bool disconn = false; uspc = bdc_readl(bdc->regs, BDC_USPC); dev_dbg(bdc->dev, "%s uspc=0x%08x\n", __func__, uspc); /* Port connect changed */ if (uspc & BDC_PCC) { /* Vbus not present, and not connected to Downstream port */ if ((uspc & BDC_VBC) && !(uspc & BDC_VBS) && !(uspc & BDC_PCS)) disconn = true; else if ((uspc & BDC_PCS) && !BDC_PST(uspc)) connected = true; } /* Change in VBus and VBus is present */ if ((uspc & BDC_VBC) && (uspc & BDC_VBS)) { if (bdc->pullup) { dev_dbg(bdc->dev, "Do a softconnect\n"); /* Attached state, do a softconnect */ bdc_softconn(bdc); usb_gadget_set_state(&bdc->gadget, USB_STATE_POWERED); } clear_flags = BDC_VBC; } else if ((uspc & BDC_PRS) || (uspc & BDC_PRC) || disconn) { /* Hot reset, warm reset, 2.0 bus reset or disconn */ dev_dbg(bdc->dev, "Port reset or disconn\n"); bdc_uspc_disconnected(bdc, disconn); clear_flags = BDC_PCC|BDC_PCS|BDC_PRS|BDC_PRC; } else if ((uspc & BDC_PSC) && (uspc & BDC_PCS)) { /* Change in Link state */ handle_link_state_change(bdc, uspc); clear_flags = BDC_PSC|BDC_PCS; } /* * In SS we might not have PRC bit set before connection, but in 2.0 * the PRC bit is set before connection, so moving this condition out * of bus reset to handle both SS/2.0 speeds. */ if (connected) { /* This is the connect event for U0/L0 */ dev_dbg(bdc->dev, "Connected\n"); bdc_uspc_connected(bdc); bdc->devstatus &= ~(DEVICE_SUSPENDED); } uspc = bdc_readl(bdc->regs, BDC_USPC); uspc &= (~BDC_USPSC_RW); dev_dbg(bdc->dev, "uspc=%x\n", uspc); bdc_writel(bdc->regs, BDC_USPC, clear_flags); } /* Main interrupt handler for bdc */ static irqreturn_t bdc_udc_interrupt(int irq, void *_bdc) { u32 eqp_index, dqp_index, sr_type, srr_int; struct bdc_sr *sreport; struct bdc *bdc = _bdc; u32 status; int ret; spin_lock(&bdc->lock); status = bdc_readl(bdc->regs, BDC_BDCSC); if (!(status & BDC_GIP)) { spin_unlock(&bdc->lock); return IRQ_NONE; } srr_int = bdc_readl(bdc->regs, BDC_SRRINT(0)); /* Check if the SRR IP bit it set? */ if (!(srr_int & BDC_SRR_IP)) { dev_warn(bdc->dev, "Global irq pending but SRR IP is 0\n"); spin_unlock(&bdc->lock); return IRQ_NONE; } eqp_index = BDC_SRR_EPI(srr_int); dqp_index = BDC_SRR_DPI(srr_int); dev_dbg(bdc->dev, "%s eqp_index=%d dqp_index=%d srr.dqp_index=%d\n\n", __func__, eqp_index, dqp_index, bdc->srr.dqp_index); /* check for ring empty condition */ if (eqp_index == dqp_index) { dev_dbg(bdc->dev, "SRR empty?\n"); spin_unlock(&bdc->lock); return IRQ_HANDLED; } while (bdc->srr.dqp_index != eqp_index) { sreport = &bdc->srr.sr_bds[bdc->srr.dqp_index]; /* sreport is read before using it */ rmb(); sr_type = le32_to_cpu(sreport->offset[3]) & BD_TYPE_BITMASK; dev_dbg_ratelimited(bdc->dev, "sr_type=%d\n", sr_type); switch (sr_type) { case SR_XSF: bdc->sr_handler[0](bdc, sreport); break; case SR_USPC: bdc->sr_handler[1](bdc, sreport); break; default: dev_warn(bdc->dev, "SR:%d not handled\n", sr_type); } /* Advance the srr dqp index */ srr_dqp_index_advc(bdc, 0); } /* update the hw dequeue pointer */ srr_int = bdc_readl(bdc->regs, BDC_SRRINT(0)); srr_int &= ~BDC_SRR_DPI_MASK; srr_int &= ~(BDC_SRR_RWS|BDC_SRR_RST|BDC_SRR_ISR); srr_int |= ((bdc->srr.dqp_index) << 16); srr_int |= BDC_SRR_IP; bdc_writel(bdc->regs, BDC_SRRINT(0), srr_int); srr_int = bdc_readl(bdc->regs, BDC_SRRINT(0)); if (bdc->reinit) { ret = bdc_reinit(bdc); if (ret) dev_err(bdc->dev, "err in bdc reinit\n"); } spin_unlock(&bdc->lock); return IRQ_HANDLED; } /* Gadget ops */ static int bdc_udc_start(struct usb_gadget *gadget, struct usb_gadget_driver *driver) { struct bdc *bdc = gadget_to_bdc(gadget); unsigned long flags; int ret = 0; dev_dbg(bdc->dev, "%s()\n", __func__); spin_lock_irqsave(&bdc->lock, flags); if (bdc->gadget_driver) { dev_err(bdc->dev, "%s is already bound to %s\n", bdc->gadget.name, bdc->gadget_driver->driver.name); ret = -EBUSY; goto err; } /* * Run the controller from here and when BDC is connected to * Host then driver will receive a USPC SR with VBUS present * and then driver will do a softconnect. */ ret = bdc_run(bdc); if (ret) { dev_err(bdc->dev, "%s bdc run fail\n", __func__); goto err; } bdc->gadget_driver = driver; bdc->gadget.dev.driver = &driver->driver; err: spin_unlock_irqrestore(&bdc->lock, flags); return ret; } static int bdc_udc_stop(struct usb_gadget *gadget) { struct bdc *bdc = gadget_to_bdc(gadget); unsigned long flags; dev_dbg(bdc->dev, "%s()\n", __func__); spin_lock_irqsave(&bdc->lock, flags); bdc_stop(bdc); bdc->gadget_driver = NULL; bdc->gadget.dev.driver = NULL; spin_unlock_irqrestore(&bdc->lock, flags); return 0; } static int bdc_udc_pullup(struct usb_gadget *gadget, int is_on) { struct bdc *bdc = gadget_to_bdc(gadget); unsigned long flags; u32 uspc; dev_dbg(bdc->dev, "%s() is_on:%d\n", __func__, is_on); if (!gadget) return -EINVAL; spin_lock_irqsave(&bdc->lock, flags); if (!is_on) { bdc_softdisconn(bdc); bdc->pullup = false; } else { /* * For a self powered device, we need to wait till we receive * a VBUS change and Vbus present event, then if pullup flag * is set, then only we present the Termintation. */ bdc->pullup = true; /* * Check if BDC is already connected to Host i.e Vbus=1, * if yes, then present TERM now, this is typical for bus * powered devices. */ uspc = bdc_readl(bdc->regs, BDC_USPC); if (uspc & BDC_VBS) bdc_softconn(bdc); } spin_unlock_irqrestore(&bdc->lock, flags); return 0; } static int bdc_udc_set_selfpowered(struct usb_gadget *gadget, int is_self) { struct bdc *bdc = gadget_to_bdc(gadget); unsigned long flags; dev_dbg(bdc->dev, "%s()\n", __func__); gadget->is_selfpowered = (is_self != 0); spin_lock_irqsave(&bdc->lock, flags); if (!is_self) bdc->devstatus |= 1 << USB_DEVICE_SELF_POWERED; else bdc->devstatus &= ~(1 << USB_DEVICE_SELF_POWERED); spin_unlock_irqrestore(&bdc->lock, flags); return 0; } static int bdc_udc_wakeup(struct usb_gadget *gadget) { struct bdc *bdc = gadget_to_bdc(gadget); unsigned long flags; u8 link_state; u32 uspc; int ret = 0; dev_dbg(bdc->dev, "%s() bdc->devstatus=%08x\n", __func__, bdc->devstatus); if (!(bdc->devstatus & REMOTE_WAKE_ENABLE)) return -EOPNOTSUPP; spin_lock_irqsave(&bdc->lock, flags); uspc = bdc_readl(bdc->regs, BDC_USPC); link_state = BDC_PST(uspc); dev_dbg(bdc->dev, "link_state =%d portsc=%x", link_state, uspc); if (link_state != BDC_LINK_STATE_U3) { dev_warn(bdc->dev, "can't wakeup from link state %d\n", link_state); ret = -EINVAL; goto out; } if (bdc->gadget.speed == USB_SPEED_SUPER) bdc->devstatus |= REMOTE_WAKEUP_ISSUED; uspc &= ~BDC_PST_MASK; uspc &= (~BDC_USPSC_RW); uspc |= BDC_PST(BDC_LINK_STATE_U0); uspc |= BDC_SWS; bdc_writel(bdc->regs, BDC_USPC, uspc); uspc = bdc_readl(bdc->regs, BDC_USPC); link_state = BDC_PST(uspc); dev_dbg(bdc->dev, "link_state =%d portsc=%x", link_state, uspc); out: spin_unlock_irqrestore(&bdc->lock, flags); return ret; } static const struct usb_gadget_ops bdc_gadget_ops = { .wakeup = bdc_udc_wakeup, .set_selfpowered = bdc_udc_set_selfpowered, .pullup = bdc_udc_pullup, .udc_start = bdc_udc_start, .udc_stop = bdc_udc_stop, }; /* Init the gadget interface and register the udc */ int bdc_udc_init(struct bdc *bdc) { u32 temp; int ret; dev_dbg(bdc->dev, "%s()\n", __func__); bdc->gadget.ops = &bdc_gadget_ops; bdc->gadget.max_speed = USB_SPEED_SUPER; bdc->gadget.speed = USB_SPEED_UNKNOWN; bdc->gadget.dev.parent = bdc->dev; bdc->gadget.sg_supported = false; bdc->gadget.name = BRCM_BDC_NAME; ret = devm_request_irq(bdc->dev, bdc->irq, bdc_udc_interrupt, IRQF_SHARED , BRCM_BDC_NAME, bdc); if (ret) { dev_err(bdc->dev, "failed to request irq #%d %d\n", bdc->irq, ret); return ret; } ret = bdc_init_ep(bdc); if (ret) { dev_err(bdc->dev, "bdc init ep fail: %d\n", ret); return ret; } ret = usb_add_gadget_udc(bdc->dev, &bdc->gadget); if (ret) { dev_err(bdc->dev, "failed to register udc\n"); goto err0; } usb_gadget_set_state(&bdc->gadget, USB_STATE_NOTATTACHED); bdc->bdc_ep_array[1]->desc = &bdc_gadget_ep0_desc; /* * Allocate bd list for ep0 only, ep0 will be enabled on connect * status report when the speed is known */ ret = bdc_ep_enable(bdc->bdc_ep_array[1]); if (ret) { dev_err(bdc->dev, "fail to enable %s\n", bdc->bdc_ep_array[1]->name); goto err1; } INIT_DELAYED_WORK(&bdc->func_wake_notify, bdc_func_wake_timer); /* Enable Interrupts */ temp = bdc_readl(bdc->regs, BDC_BDCSC); temp |= BDC_GIE; bdc_writel(bdc->regs, BDC_BDCSC, temp); return 0; err1: usb_del_gadget_udc(&bdc->gadget); err0: bdc_free_ep(bdc); return ret; } void bdc_udc_exit(struct bdc *bdc) { unsigned long flags; dev_dbg(bdc->dev, "%s()\n", __func__); spin_lock_irqsave(&bdc->lock, flags); bdc_ep_disable(bdc->bdc_ep_array[1]); spin_unlock_irqrestore(&bdc->lock, flags); usb_del_gadget_udc(&bdc->gadget); bdc_free_ep(bdc); }
null
null
null
null
103,610
35,530
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
35,530
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright 2017 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 "third_party/blink/renderer/core/editing/state_machines/forward_code_point_state_machine.h" #include "testing/gtest/include/gtest/gtest.h" namespace blink { TEST(ForwardCodePointStateMachineTest, DoNothingCase) { ForwardCodePointStateMachine machine; EXPECT_EQ(0, machine.GetBoundaryOffset()); } TEST(ForwardCodePointStateMachineTest, SingleCharacter) { ForwardCodePointStateMachine machine; EXPECT_EQ(TextSegmentationMachineState::kFinished, machine.FeedFollowingCodeUnit('a')); EXPECT_EQ(1, machine.GetBoundaryOffset()); machine.Reset(); EXPECT_EQ(TextSegmentationMachineState::kFinished, machine.FeedFollowingCodeUnit('-')); EXPECT_EQ(1, machine.GetBoundaryOffset()); machine.Reset(); EXPECT_EQ(TextSegmentationMachineState::kFinished, machine.FeedFollowingCodeUnit('\t')); EXPECT_EQ(1, machine.GetBoundaryOffset()); machine.Reset(); // U+3042 HIRAGANA LETTER A. EXPECT_EQ(TextSegmentationMachineState::kFinished, machine.FeedFollowingCodeUnit(0x3042)); EXPECT_EQ(1, machine.GetBoundaryOffset()); } TEST(ForwardCodePointStateMachineTest, SurrogatePair) { ForwardCodePointStateMachine machine; // U+20BB7 is \uD83D\uDDFA in UTF-16. const UChar kLeadSurrogate = 0xD842; const UChar kTrailSurrogate = 0xDFB7; EXPECT_EQ(TextSegmentationMachineState::kNeedMoreCodeUnit, machine.FeedFollowingCodeUnit(kLeadSurrogate)); EXPECT_EQ(TextSegmentationMachineState::kFinished, machine.FeedFollowingCodeUnit(kTrailSurrogate)); EXPECT_EQ(2, machine.GetBoundaryOffset()); // Edge cases // Unpaired leading surrogate. Nothing to delete. machine.Reset(); EXPECT_EQ(TextSegmentationMachineState::kNeedMoreCodeUnit, machine.FeedFollowingCodeUnit(kLeadSurrogate)); EXPECT_EQ(TextSegmentationMachineState::kInvalid, machine.FeedFollowingCodeUnit('a')); EXPECT_EQ(0, machine.GetBoundaryOffset()); machine.Reset(); EXPECT_EQ(TextSegmentationMachineState::kNeedMoreCodeUnit, machine.FeedFollowingCodeUnit(kLeadSurrogate)); EXPECT_EQ(TextSegmentationMachineState::kInvalid, machine.FeedFollowingCodeUnit(kLeadSurrogate)); EXPECT_EQ(0, machine.GetBoundaryOffset()); // Unpaired trailing surrogate. Nothing to delete. machine.Reset(); EXPECT_EQ(TextSegmentationMachineState::kInvalid, machine.FeedFollowingCodeUnit(kTrailSurrogate)); EXPECT_EQ(0, machine.GetBoundaryOffset()); } } // namespace blink
null
null
null
null
32,393
39,113
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
204,108
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * Kernel module for testing copy_to/from_user infrastructure. * * Copyright 2013 Google Inc. All Rights Reserved * * Authors: * Kees Cook <keescook@chromium.org> * * This software is licensed under the terms of the GNU General Public * License version 2, as published by the Free Software Foundation, and * may be copied, distributed, and modified under those terms. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/mman.h> #include <linux/module.h> #include <linux/sched.h> #include <linux/slab.h> #include <linux/uaccess.h> #include <linux/vmalloc.h> /* * Several 32-bit architectures support 64-bit {get,put}_user() calls. * As there doesn't appear to be anything that can safely determine * their capability at compile-time, we just have to opt-out certain archs. */ #if BITS_PER_LONG == 64 || (!(defined(CONFIG_ARM) && !defined(MMU)) && \ !defined(CONFIG_AVR32) && \ !defined(CONFIG_BLACKFIN) && \ !defined(CONFIG_M32R) && \ !defined(CONFIG_M68K) && \ !defined(CONFIG_MICROBLAZE) && \ !defined(CONFIG_MN10300) && \ !defined(CONFIG_NIOS2) && \ !defined(CONFIG_PPC32) && \ !defined(CONFIG_SUPERH)) # define TEST_U64 #endif #define test(condition, msg) \ ({ \ int cond = (condition); \ if (cond) \ pr_warn("%s\n", msg); \ cond; \ }) static int __init test_user_copy_init(void) { int ret = 0; char *kmem; char __user *usermem; char *bad_usermem; unsigned long user_addr; u8 val_u8; u16 val_u16; u32 val_u32; #ifdef TEST_U64 u64 val_u64; #endif kmem = kmalloc(PAGE_SIZE * 2, GFP_KERNEL); if (!kmem) return -ENOMEM; user_addr = vm_mmap(NULL, 0, PAGE_SIZE * 2, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_ANONYMOUS | MAP_PRIVATE, 0); if (user_addr >= (unsigned long)(TASK_SIZE)) { pr_warn("Failed to allocate user memory\n"); kfree(kmem); return -ENOMEM; } usermem = (char __user *)user_addr; bad_usermem = (char *)user_addr; /* * Legitimate usage: none of these copies should fail. */ memset(kmem, 0x3a, PAGE_SIZE * 2); ret |= test(copy_to_user(usermem, kmem, PAGE_SIZE), "legitimate copy_to_user failed"); memset(kmem, 0x0, PAGE_SIZE); ret |= test(copy_from_user(kmem, usermem, PAGE_SIZE), "legitimate copy_from_user failed"); ret |= test(memcmp(kmem, kmem + PAGE_SIZE, PAGE_SIZE), "legitimate usercopy failed to copy data"); #define test_legit(size, check) \ do { \ val_##size = check; \ ret |= test(put_user(val_##size, (size __user *)usermem), \ "legitimate put_user (" #size ") failed"); \ val_##size = 0; \ ret |= test(get_user(val_##size, (size __user *)usermem), \ "legitimate get_user (" #size ") failed"); \ ret |= test(val_##size != check, \ "legitimate get_user (" #size ") failed to do copy"); \ if (val_##size != check) { \ pr_info("0x%llx != 0x%llx\n", \ (unsigned long long)val_##size, \ (unsigned long long)check); \ } \ } while (0) test_legit(u8, 0x5a); test_legit(u16, 0x5a5b); test_legit(u32, 0x5a5b5c5d); #ifdef TEST_U64 test_legit(u64, 0x5a5b5c5d6a6b6c6d); #endif #undef test_legit /* * Invalid usage: none of these copies should succeed. */ /* Prepare kernel memory with check values. */ memset(kmem, 0x5a, PAGE_SIZE); memset(kmem + PAGE_SIZE, 0, PAGE_SIZE); /* Reject kernel-to-kernel copies through copy_from_user(). */ ret |= test(!copy_from_user(kmem, (char __user *)(kmem + PAGE_SIZE), PAGE_SIZE), "illegal all-kernel copy_from_user passed"); /* Destination half of buffer should have been zeroed. */ ret |= test(memcmp(kmem + PAGE_SIZE, kmem, PAGE_SIZE), "zeroing failure for illegal all-kernel copy_from_user"); #if 0 /* * When running with SMAP/PAN/etc, this will Oops the kernel * due to the zeroing of userspace memory on failure. This needs * to be tested in LKDTM instead, since this test module does not * expect to explode. */ ret |= test(!copy_from_user(bad_usermem, (char __user *)kmem, PAGE_SIZE), "illegal reversed copy_from_user passed"); #endif ret |= test(!copy_to_user((char __user *)kmem, kmem + PAGE_SIZE, PAGE_SIZE), "illegal all-kernel copy_to_user passed"); ret |= test(!copy_to_user((char __user *)kmem, bad_usermem, PAGE_SIZE), "illegal reversed copy_to_user passed"); #define test_illegal(size, check) \ do { \ val_##size = (check); \ ret |= test(!get_user(val_##size, (size __user *)kmem), \ "illegal get_user (" #size ") passed"); \ ret |= test(val_##size != (size)0, \ "zeroing failure for illegal get_user (" #size ")"); \ if (val_##size != (size)0) { \ pr_info("0x%llx != 0\n", \ (unsigned long long)val_##size); \ } \ ret |= test(!put_user(val_##size, (size __user *)kmem), \ "illegal put_user (" #size ") passed"); \ } while (0) test_illegal(u8, 0x5a); test_illegal(u16, 0x5a5b); test_illegal(u32, 0x5a5b5c5d); #ifdef TEST_U64 test_illegal(u64, 0x5a5b5c5d6a6b6c6d); #endif #undef test_illegal vm_munmap(user_addr, PAGE_SIZE * 2); kfree(kmem); if (ret == 0) { pr_info("tests passed.\n"); return 0; } return -EINVAL; } module_init(test_user_copy_init); static void __exit test_user_copy_exit(void) { pr_info("unloaded.\n"); } module_exit(test_user_copy_exit); MODULE_AUTHOR("Kees Cook <keescook@chromium.org>"); MODULE_LICENSE("GPL");
null
null
null
null
112,455
4,298
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
4,298
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef IOS_CHROME_BROWSER_BROWSER_STATE_CHROME_BROWSER_STATE_REMOVAL_CONTROLLER_H_ #define IOS_CHROME_BROWSER_BROWSER_STATE_CHROME_BROWSER_STATE_REMOVAL_CONTROLLER_H_ #include <string> // Controls the removal of extra browser states. class ChromeBrowserStateRemovalController { public: static ChromeBrowserStateRemovalController* GetInstance(); // Removes the browser states marked as not to keep if they exist. It also // converts the most recently used bookmarks file to an HTML representation. void RemoveBrowserStatesIfNecessary(); // Returns whether a browser state has been removed. The value is conserved // across application restarts. bool HasBrowserStateBeenRemoved(); // Returns the GAIA Id of the removed browser state if it was authenticated. // The value should not be trusted unless HasBrowserStateBeenRemoved() returns // true. const std::string& removed_browser_state_gaia_id() const { return removed_browser_state_gaia_id_; } // Returns whether the last used browser sate was changed during this session. bool has_changed_last_used_browser_state() const { return has_changed_last_used_browser_state_; } private: ChromeBrowserStateRemovalController(); ~ChromeBrowserStateRemovalController(); // Returns the relative path of the browser state path to keep. This value // was stored from the user choice. std::string GetBrowserStatePathToKeep(); // Sets whether a browser state has been removed. The value is conserved // across application restarts. void SetHasBrowserStateBeenRemoved(bool value); // Returns the relative path of the last browser state used (during the // previous application run). std::string GetLastBrowserStatePathUsed(); // Sets the relative path of the last browser state used. void SetLastBrowserStatePathUsed(const std::string& browser_state_path); // The GAIA Id of the removed browser state (if any). std::string removed_browser_state_gaia_id_; // Whether the last used browser state was changed. bool has_changed_last_used_browser_state_; }; #endif // IOS_CHROME_BROWSER_BROWSER_STATE_CHROME_BROWSER_STATE_REMOVAL_CONTROLLER_H_
null
null
null
null
1,161
53,028
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
53,028
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef MEDIA_BASE_CHANNEL_MIXER_H_ #define MEDIA_BASE_CHANNEL_MIXER_H_ #include <vector> #include "base/macros.h" #include "media/base/channel_layout.h" #include "media/base/media_export.h" namespace media { class AudioBus; class AudioParameters; // ChannelMixer is for converting audio between channel layouts. The conversion // matrix is built upon construction and used during each Transform() call. The // algorithm works by generating a conversion matrix mapping each output channel // to list of input channels. The transform renders all of the output channels, // with each output channel rendered according to a weighted sum of the relevant // input channels as defined in the matrix. class MEDIA_EXPORT ChannelMixer { public: // To mix two channels into one and preserve loudness, we must apply // (1 / sqrt(2)) gain to each. static constexpr float kHalfPower = 0.707106781186547524401f; ChannelMixer(ChannelLayout input_layout, ChannelLayout output_layout); ChannelMixer(const AudioParameters& input, const AudioParameters& output); ~ChannelMixer(); // Transforms all channels from |input| into |output| channels. void Transform(const AudioBus* input, AudioBus* output); private: void Initialize(ChannelLayout input_layout, int input_channels, ChannelLayout output_layout, int output_channels); // 2D matrix of output channels to input channels. std::vector< std::vector<float> > matrix_; // Optimization case for when we can simply remap the input channels to output // channels and don't need to do a multiply-accumulate loop over |matrix_|. bool remapping_; DISALLOW_COPY_AND_ASSIGN(ChannelMixer); }; } // namespace media #endif // MEDIA_BASE_CHANNEL_MIXER_H_
null
null
null
null
49,891
10,661
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
175,656
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * arch/arm/plat-spear/restart.c * * SPEAr platform specific restart functions * * Copyright (C) 2009 ST Microelectronics * Viresh Kumar <vireshk@kernel.org> * * This file is licensed under the terms of the GNU General Public * License version 2. This program is licensed "as is" without any * warranty of any kind, whether express or implied. */ #include <linux/io.h> #include <linux/amba/sp810.h> #include <linux/reboot.h> #include <asm/system_misc.h> #include <mach/spear.h> #include "generic.h" #define SPEAR13XX_SYS_SW_RES (VA_MISC_BASE + 0x204) void spear_restart(enum reboot_mode mode, const char *cmd) { if (mode == REBOOT_SOFT) { /* software reset, Jump into ROM at address 0 */ soft_restart(0); } else { /* hardware reset, Use on-chip reset capability */ #ifdef CONFIG_ARCH_SPEAR13XX writel_relaxed(0x01, SPEAR13XX_SYS_SW_RES); #endif #if defined(CONFIG_ARCH_SPEAR3XX) || defined(CONFIG_ARCH_SPEAR6XX) sysctl_soft_reset((void __iomem *)VA_SPEAR_SYS_CTRL_BASE); #endif } }
null
null
null
null
84,003
60,052
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
60,052
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright 2017 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_OFFLINE_PAGES_PREFETCH_PREFETCH_BACKGROUND_TASK_HANDLER_IMPL_H_ #define CHROME_BROWSER_OFFLINE_PAGES_PREFETCH_PREFETCH_BACKGROUND_TASK_HANDLER_IMPL_H_ #include <memory> #include "base/macros.h" #include "base/time/tick_clock.h" #include "components/offline_pages/core/prefetch/prefetch_background_task_handler.h" class PrefRegistrySimple; class PrefService; namespace base { class TickClock; } namespace net { class BackoffEntry; } namespace offline_pages { // A class living on the PrefetchService that is able to ask the Android // background task system to schedule tasks at the appropriate time based on the // backoff value, or cancel tasks. // // The background task will be rescheduled in the time calculated as: // delay = 15 minutes + backoff // backoff = (30 seconds ^ N * Rand(0.67, 1)) | (1 day) // 15 minutes is the minimum delay, defined in PrefetchBackgroundTaskScheduler. // |backoff| is the additional delay needed to avoid overflowing the server, // which could be one of the following: // 1) 0: No additional delay when the request succeeds // 2) 30s^N * Rand(0.67,1): Exponential backoff w/ jitter when the request fails // (N is the count of the request failures) // 3) 1 day: Suspend for 1 day due to certain severe server errors // The backoff value is controlled by a persisted BackoffEntry. class PrefetchBackgroundTaskHandlerImpl : public PrefetchBackgroundTaskHandler { public: explicit PrefetchBackgroundTaskHandlerImpl(PrefService* profile); ~PrefetchBackgroundTaskHandlerImpl() override; // PrefetchBackgroundTaskHandler implementation. void CancelBackgroundTask() override; void EnsureTaskScheduled() override; // Backoff control. These functions directly modify/read prefs. void Backoff() override; void ResetBackoff() override; void PauseBackoffUntilNextRun() override; void Suspend() override; void RemoveSuspension() override; int GetAdditionalBackoffSeconds() const override; // This is used to construct the backoff value. void SetTickClockForTesting(const base::TickClock* clock); private: std::unique_ptr<net::BackoffEntry> GetCurrentBackoff() const; void UpdateBackoff(net::BackoffEntry* backoff); PrefService* prefs_; const base::TickClock* clock_ = nullptr; DISALLOW_COPY_AND_ASSIGN(PrefetchBackgroundTaskHandlerImpl); }; void RegisterPrefetchBackgroundTaskPrefs(PrefRegistrySimple* registry); } // namespace offline_pages #endif // CHROME_BROWSER_OFFLINE_PAGES_PREFETCH_PREFETCH_BACKGROUND_TASK_HANDLER_IMPL_H_
null
null
null
null
56,915
49,412
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
49,412
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright (c) 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/gfx/codec/vector_wstream.h" namespace gfx { bool VectorWStream::write(const void* buffer, size_t size) { const unsigned char* ptr = reinterpret_cast<const unsigned char*>(buffer); dst_->insert(dst_->end(), ptr, ptr + size); return true; } size_t VectorWStream::bytesWritten() const { return dst_->size(); } } // namespace gfx
null
null
null
null
46,275
43,026
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
208,021
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
#ifndef _UAPI_ASM_GENERIC_SIGINFO_H #define _UAPI_ASM_GENERIC_SIGINFO_H #include <linux/compiler.h> #include <linux/types.h> typedef union sigval { int sival_int; void __user *sival_ptr; } sigval_t; /* * This is the size (including padding) of the part of the * struct siginfo that is before the union. */ #ifndef __ARCH_SI_PREAMBLE_SIZE #define __ARCH_SI_PREAMBLE_SIZE (3 * sizeof(int)) #endif #define SI_MAX_SIZE 128 #ifndef SI_PAD_SIZE #define SI_PAD_SIZE ((SI_MAX_SIZE - __ARCH_SI_PREAMBLE_SIZE) / sizeof(int)) #endif #ifndef __ARCH_SI_UID_T #define __ARCH_SI_UID_T __kernel_uid32_t #endif /* * The default "si_band" type is "long", as specified by POSIX. * However, some architectures want to override this to "int" * for historical compatibility reasons, so we allow that. */ #ifndef __ARCH_SI_BAND_T #define __ARCH_SI_BAND_T long #endif #ifndef __ARCH_SI_CLOCK_T #define __ARCH_SI_CLOCK_T __kernel_clock_t #endif #ifndef __ARCH_SI_ATTRIBUTES #define __ARCH_SI_ATTRIBUTES #endif #ifndef HAVE_ARCH_SIGINFO_T typedef struct siginfo { int si_signo; int si_errno; int si_code; union { int _pad[SI_PAD_SIZE]; /* kill() */ struct { __kernel_pid_t _pid; /* sender's pid */ __ARCH_SI_UID_T _uid; /* sender's uid */ } _kill; /* POSIX.1b timers */ struct { __kernel_timer_t _tid; /* timer id */ int _overrun; /* overrun count */ char _pad[sizeof( __ARCH_SI_UID_T) - sizeof(int)]; sigval_t _sigval; /* same as below */ int _sys_private; /* not to be passed to user */ } _timer; /* POSIX.1b signals */ struct { __kernel_pid_t _pid; /* sender's pid */ __ARCH_SI_UID_T _uid; /* sender's uid */ sigval_t _sigval; } _rt; /* SIGCHLD */ struct { __kernel_pid_t _pid; /* which child */ __ARCH_SI_UID_T _uid; /* sender's uid */ int _status; /* exit code */ __ARCH_SI_CLOCK_T _utime; __ARCH_SI_CLOCK_T _stime; } _sigchld; /* SIGILL, SIGFPE, SIGSEGV, SIGBUS */ struct { void __user *_addr; /* faulting insn/memory ref. */ #ifdef __ARCH_SI_TRAPNO int _trapno; /* TRAP # which caused the signal */ #endif short _addr_lsb; /* LSB of the reported address */ union { /* used when si_code=SEGV_BNDERR */ struct { void __user *_lower; void __user *_upper; } _addr_bnd; /* used when si_code=SEGV_PKUERR */ __u32 _pkey; }; } _sigfault; /* SIGPOLL */ struct { __ARCH_SI_BAND_T _band; /* POLL_IN, POLL_OUT, POLL_MSG */ int _fd; } _sigpoll; /* SIGSYS */ struct { void __user *_call_addr; /* calling user insn */ int _syscall; /* triggering system call number */ unsigned int _arch; /* AUDIT_ARCH_* of syscall */ } _sigsys; } _sifields; } __ARCH_SI_ATTRIBUTES siginfo_t; /* If the arch shares siginfo, then it has SIGSYS. */ #define __ARCH_SIGSYS #endif /* * How these fields are to be accessed. */ #define si_pid _sifields._kill._pid #define si_uid _sifields._kill._uid #define si_tid _sifields._timer._tid #define si_overrun _sifields._timer._overrun #define si_sys_private _sifields._timer._sys_private #define si_status _sifields._sigchld._status #define si_utime _sifields._sigchld._utime #define si_stime _sifields._sigchld._stime #define si_value _sifields._rt._sigval #define si_int _sifields._rt._sigval.sival_int #define si_ptr _sifields._rt._sigval.sival_ptr #define si_addr _sifields._sigfault._addr #ifdef __ARCH_SI_TRAPNO #define si_trapno _sifields._sigfault._trapno #endif #define si_addr_lsb _sifields._sigfault._addr_lsb #define si_lower _sifields._sigfault._addr_bnd._lower #define si_upper _sifields._sigfault._addr_bnd._upper #define si_pkey _sifields._sigfault._pkey #define si_band _sifields._sigpoll._band #define si_fd _sifields._sigpoll._fd #ifdef __ARCH_SIGSYS #define si_call_addr _sifields._sigsys._call_addr #define si_syscall _sifields._sigsys._syscall #define si_arch _sifields._sigsys._arch #endif #ifndef __KERNEL__ #define __SI_KILL 0 #define __SI_TIMER 0 #define __SI_POLL 0 #define __SI_FAULT 0 #define __SI_CHLD 0 #define __SI_RT 0 #define __SI_MESGQ 0 #define __SI_SYS 0 #define __SI_CODE(T,N) (N) #endif /* * si_code values * Digital reserves positive values for kernel-generated signals. */ #define SI_USER 0 /* sent by kill, sigsend, raise */ #define SI_KERNEL 0x80 /* sent by the kernel from somewhere */ #define SI_QUEUE -1 /* sent by sigqueue */ #define SI_TIMER __SI_CODE(__SI_TIMER,-2) /* sent by timer expiration */ #define SI_MESGQ __SI_CODE(__SI_MESGQ,-3) /* sent by real time mesq state change */ #define SI_ASYNCIO -4 /* sent by AIO completion */ #define SI_SIGIO -5 /* sent by queued SIGIO */ #define SI_TKILL -6 /* sent by tkill system call */ #define SI_DETHREAD -7 /* sent by execve() killing subsidiary threads */ #define SI_FROMUSER(siptr) ((siptr)->si_code <= 0) #define SI_FROMKERNEL(siptr) ((siptr)->si_code > 0) /* * SIGILL si_codes */ #define ILL_ILLOPC (__SI_FAULT|1) /* illegal opcode */ #define ILL_ILLOPN (__SI_FAULT|2) /* illegal operand */ #define ILL_ILLADR (__SI_FAULT|3) /* illegal addressing mode */ #define ILL_ILLTRP (__SI_FAULT|4) /* illegal trap */ #define ILL_PRVOPC (__SI_FAULT|5) /* privileged opcode */ #define ILL_PRVREG (__SI_FAULT|6) /* privileged register */ #define ILL_COPROC (__SI_FAULT|7) /* coprocessor error */ #define ILL_BADSTK (__SI_FAULT|8) /* internal stack error */ #define NSIGILL 8 /* * SIGFPE si_codes */ #define FPE_INTDIV (__SI_FAULT|1) /* integer divide by zero */ #define FPE_INTOVF (__SI_FAULT|2) /* integer overflow */ #define FPE_FLTDIV (__SI_FAULT|3) /* floating point divide by zero */ #define FPE_FLTOVF (__SI_FAULT|4) /* floating point overflow */ #define FPE_FLTUND (__SI_FAULT|5) /* floating point underflow */ #define FPE_FLTRES (__SI_FAULT|6) /* floating point inexact result */ #define FPE_FLTINV (__SI_FAULT|7) /* floating point invalid operation */ #define FPE_FLTSUB (__SI_FAULT|8) /* subscript out of range */ #define NSIGFPE 8 /* * SIGSEGV si_codes */ #define SEGV_MAPERR (__SI_FAULT|1) /* address not mapped to object */ #define SEGV_ACCERR (__SI_FAULT|2) /* invalid permissions for mapped object */ #define SEGV_BNDERR (__SI_FAULT|3) /* failed address bound checks */ #define SEGV_PKUERR (__SI_FAULT|4) /* failed protection key checks */ #define NSIGSEGV 4 /* * SIGBUS si_codes */ #define BUS_ADRALN (__SI_FAULT|1) /* invalid address alignment */ #define BUS_ADRERR (__SI_FAULT|2) /* non-existent physical address */ #define BUS_OBJERR (__SI_FAULT|3) /* object specific hardware error */ /* hardware memory error consumed on a machine check: action required */ #define BUS_MCEERR_AR (__SI_FAULT|4) /* hardware memory error detected in process but not consumed: action optional*/ #define BUS_MCEERR_AO (__SI_FAULT|5) #define NSIGBUS 5 /* * SIGTRAP si_codes */ #define TRAP_BRKPT (__SI_FAULT|1) /* process breakpoint */ #define TRAP_TRACE (__SI_FAULT|2) /* process trace trap */ #define TRAP_BRANCH (__SI_FAULT|3) /* process taken branch trap */ #define TRAP_HWBKPT (__SI_FAULT|4) /* hardware breakpoint/watchpoint */ #define NSIGTRAP 4 /* * SIGCHLD si_codes */ #define CLD_EXITED (__SI_CHLD|1) /* child has exited */ #define CLD_KILLED (__SI_CHLD|2) /* child was killed */ #define CLD_DUMPED (__SI_CHLD|3) /* child terminated abnormally */ #define CLD_TRAPPED (__SI_CHLD|4) /* traced child has trapped */ #define CLD_STOPPED (__SI_CHLD|5) /* child has stopped */ #define CLD_CONTINUED (__SI_CHLD|6) /* stopped child has continued */ #define NSIGCHLD 6 /* * SIGPOLL si_codes */ #define POLL_IN (__SI_POLL|1) /* data input available */ #define POLL_OUT (__SI_POLL|2) /* output buffers available */ #define POLL_MSG (__SI_POLL|3) /* input message available */ #define POLL_ERR (__SI_POLL|4) /* i/o error */ #define POLL_PRI (__SI_POLL|5) /* high priority input available */ #define POLL_HUP (__SI_POLL|6) /* device disconnected */ #define NSIGPOLL 6 /* * SIGSYS si_codes */ #define SYS_SECCOMP (__SI_SYS|1) /* seccomp triggered */ #define NSIGSYS 1 /* * sigevent definitions * * It seems likely that SIGEV_THREAD will have to be handled from * userspace, libpthread transmuting it to SIGEV_SIGNAL, which the * thread manager then catches and does the appropriate nonsense. * However, everything is written out here so as to not get lost. */ #define SIGEV_SIGNAL 0 /* notify via signal */ #define SIGEV_NONE 1 /* other notification: meaningless */ #define SIGEV_THREAD 2 /* deliver via thread creation */ #define SIGEV_THREAD_ID 4 /* deliver to thread */ /* * This works because the alignment is ok on all current architectures * but we leave open this being overridden in the future */ #ifndef __ARCH_SIGEV_PREAMBLE_SIZE #define __ARCH_SIGEV_PREAMBLE_SIZE (sizeof(int) * 2 + sizeof(sigval_t)) #endif #define SIGEV_MAX_SIZE 64 #define SIGEV_PAD_SIZE ((SIGEV_MAX_SIZE - __ARCH_SIGEV_PREAMBLE_SIZE) \ / sizeof(int)) typedef struct sigevent { sigval_t sigev_value; int sigev_signo; int sigev_notify; union { int _pad[SIGEV_PAD_SIZE]; int _tid; struct { void (*_function)(sigval_t); void *_attribute; /* really pthread_attr_t */ } _sigev_thread; } _sigev_un; } sigevent_t; #define sigev_notify_function _sigev_un._sigev_thread._function #define sigev_notify_attributes _sigev_un._sigev_thread._attribute #define sigev_notify_thread_id _sigev_un._tid #endif /* _UAPI_ASM_GENERIC_SIGINFO_H */
null
null
null
null
116,368
23,209
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
23,209
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright 2017 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 CONTENT_BROWSER_BACKGROUND_FETCH_MOCK_BACKGROUND_FETCH_DELEGATE_H_ #define CONTENT_BROWSER_BACKGROUND_FETCH_MOCK_BACKGROUND_FETCH_DELEGATE_H_ #include <map> #include <memory> #include <set> #include <string> #include <vector> #include "base/files/scoped_temp_dir.h" #include "content/public/browser/background_fetch_delegate.h" #include "url/gurl.h" namespace net { class HttpResponseHeaders; } // namespace net namespace content { class MockBackgroundFetchDelegate : public BackgroundFetchDelegate { public: // Structure encapsulating the data for a injected response. Should only be // created by the builder, which also defines the ownership semantics. struct TestResponse { TestResponse(); ~TestResponse(); bool succeeded_; scoped_refptr<net::HttpResponseHeaders> headers; std::string data; private: DISALLOW_COPY_AND_ASSIGN(TestResponse); }; // Builder for creating a TestResponse object with the given data. // MockBackgroundFetchDelegate will respond to the corresponding request based // on this. class TestResponseBuilder { public: explicit TestResponseBuilder(int response_code); ~TestResponseBuilder(); TestResponseBuilder& AddResponseHeader(const std::string& name, const std::string& value); TestResponseBuilder& SetResponseData(std::string data); // Finalizes the builder and invalidates the underlying response. std::unique_ptr<TestResponse> Build(); private: std::unique_ptr<TestResponse> response_; DISALLOW_COPY_AND_ASSIGN(TestResponseBuilder); }; MockBackgroundFetchDelegate(); ~MockBackgroundFetchDelegate() override; // BackgroundFetchDelegate implementation: void GetIconDisplaySize( BackgroundFetchDelegate::GetIconDisplaySizeCallback callback) override; void CreateDownloadJob( const std::string& job_unique_id, const std::string& title, const url::Origin& origin, const SkBitmap& icon, int completed_parts, int total_parts, const std::vector<std::string>& current_guids) override; void DownloadUrl(const std::string& job_unique_id, const std::string& guid, const std::string& method, const GURL& url, const net::NetworkTrafficAnnotationTag& traffic_annotation, const net::HttpRequestHeaders& headers) override; void Abort(const std::string& job_unique_id) override; void RegisterResponse(const GURL& url, std::unique_ptr<TestResponse> response); private: // Posts (to the default task runner) a callback that is only run if the job // indicated by |job_unique_id| has not been aborted. void PostAbortCheckingTask(const std::string& job_unique_id, base::OnceCallback<void()> callback); // Immediately runs the callback if the job indicated by |job_unique_id| has // not been aborted. void RunAbortCheckingTask(const std::string& job_unique_id, base::OnceCallback<void()> callback); // Single-use responses registered for specific URLs. std::map<const GURL, std::unique_ptr<TestResponse>> url_responses_; // GUIDs that have been registered via DownloadUrl and thus cannot be reused. std::set<std::string> seen_guids_; // Temporary directory in which successfully downloaded files will be stored. base::ScopedTempDir temp_directory_; // Set of unique job ids that have been aborted. std::set<std::string> aborted_jobs_; // Map from download GUIDs to unique job ids. std::map<std::string, std::string> download_guid_to_job_id_map_; DISALLOW_COPY_AND_ASSIGN(MockBackgroundFetchDelegate); }; } // namespace content #endif // CONTENT_BROWSER_BACKGROUND_FETCH_MOCK_BACKGROUND_FETCH_DELEGATE_H_
null
null
null
null
20,072
32,305
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
197,300
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * Promise PATA TX2/TX4/TX2000/133 IDE driver for pdc20268 to pdc20277. * * 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. * * Ported to libata by: * Albert Lee <albertcc@tw.ibm.com> IBM Corporation * * Copyright (C) 1998-2002 Andre Hedrick <andre@linux-ide.org> * Portions Copyright (C) 1999 Promise Technology, Inc. * * Author: Frank Tiernan (frankt@promise.com) * Released under terms of General Public License * * * libata documentation is available via 'make {ps|pdf}docs', * as Documentation/DocBook/libata.* * * Hardware information only available under NDA. * */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/pci.h> #include <linux/blkdev.h> #include <linux/delay.h> #include <linux/device.h> #include <linux/ktime.h> #include <scsi/scsi.h> #include <scsi/scsi_host.h> #include <scsi/scsi_cmnd.h> #include <linux/libata.h> #define DRV_NAME "pata_pdc2027x" #define DRV_VERSION "1.0" #undef PDC_DEBUG #ifdef PDC_DEBUG #define PDPRINTK(fmt, args...) printk(KERN_ERR "%s: " fmt, __func__, ## args) #else #define PDPRINTK(fmt, args...) #endif enum { PDC_MMIO_BAR = 5, PDC_UDMA_100 = 0, PDC_UDMA_133 = 1, PDC_100_MHZ = 100000000, PDC_133_MHZ = 133333333, PDC_SYS_CTL = 0x1100, PDC_ATA_CTL = 0x1104, PDC_GLOBAL_CTL = 0x1108, PDC_CTCR0 = 0x110C, PDC_CTCR1 = 0x1110, PDC_BYTE_COUNT = 0x1120, PDC_PLL_CTL = 0x1202, }; static int pdc2027x_init_one(struct pci_dev *pdev, const struct pci_device_id *ent); #ifdef CONFIG_PM_SLEEP static int pdc2027x_reinit_one(struct pci_dev *pdev); #endif static int pdc2027x_prereset(struct ata_link *link, unsigned long deadline); static void pdc2027x_set_piomode(struct ata_port *ap, struct ata_device *adev); static void pdc2027x_set_dmamode(struct ata_port *ap, struct ata_device *adev); static int pdc2027x_check_atapi_dma(struct ata_queued_cmd *qc); static unsigned long pdc2027x_mode_filter(struct ata_device *adev, unsigned long mask); static int pdc2027x_cable_detect(struct ata_port *ap); static int pdc2027x_set_mode(struct ata_link *link, struct ata_device **r_failed); /* * ATA Timing Tables based on 133MHz controller clock. * These tables are only used when the controller is in 133MHz clock. * If the controller is in 100MHz clock, the ASIC hardware will * set the timing registers automatically when "set feature" command * is issued to the device. However, if the controller clock is 133MHz, * the following tables must be used. */ static struct pdc2027x_pio_timing { u8 value0, value1, value2; } pdc2027x_pio_timing_tbl [] = { { 0xfb, 0x2b, 0xac }, /* PIO mode 0 */ { 0x46, 0x29, 0xa4 }, /* PIO mode 1 */ { 0x23, 0x26, 0x64 }, /* PIO mode 2 */ { 0x27, 0x0d, 0x35 }, /* PIO mode 3, IORDY on, Prefetch off */ { 0x23, 0x09, 0x25 }, /* PIO mode 4, IORDY on, Prefetch off */ }; static struct pdc2027x_mdma_timing { u8 value0, value1; } pdc2027x_mdma_timing_tbl [] = { { 0xdf, 0x5f }, /* MDMA mode 0 */ { 0x6b, 0x27 }, /* MDMA mode 1 */ { 0x69, 0x25 }, /* MDMA mode 2 */ }; static struct pdc2027x_udma_timing { u8 value0, value1, value2; } pdc2027x_udma_timing_tbl [] = { { 0x4a, 0x0f, 0xd5 }, /* UDMA mode 0 */ { 0x3a, 0x0a, 0xd0 }, /* UDMA mode 1 */ { 0x2a, 0x07, 0xcd }, /* UDMA mode 2 */ { 0x1a, 0x05, 0xcd }, /* UDMA mode 3 */ { 0x1a, 0x03, 0xcd }, /* UDMA mode 4 */ { 0x1a, 0x02, 0xcb }, /* UDMA mode 5 */ { 0x1a, 0x01, 0xcb }, /* UDMA mode 6 */ }; static const struct pci_device_id pdc2027x_pci_tbl[] = { { PCI_VDEVICE(PROMISE, PCI_DEVICE_ID_PROMISE_20268), PDC_UDMA_100 }, { PCI_VDEVICE(PROMISE, PCI_DEVICE_ID_PROMISE_20269), PDC_UDMA_133 }, { PCI_VDEVICE(PROMISE, PCI_DEVICE_ID_PROMISE_20270), PDC_UDMA_100 }, { PCI_VDEVICE(PROMISE, PCI_DEVICE_ID_PROMISE_20271), PDC_UDMA_133 }, { PCI_VDEVICE(PROMISE, PCI_DEVICE_ID_PROMISE_20275), PDC_UDMA_133 }, { PCI_VDEVICE(PROMISE, PCI_DEVICE_ID_PROMISE_20276), PDC_UDMA_133 }, { PCI_VDEVICE(PROMISE, PCI_DEVICE_ID_PROMISE_20277), PDC_UDMA_133 }, { } /* terminate list */ }; static struct pci_driver pdc2027x_pci_driver = { .name = DRV_NAME, .id_table = pdc2027x_pci_tbl, .probe = pdc2027x_init_one, .remove = ata_pci_remove_one, #ifdef CONFIG_PM_SLEEP .suspend = ata_pci_device_suspend, .resume = pdc2027x_reinit_one, #endif }; static struct scsi_host_template pdc2027x_sht = { ATA_BMDMA_SHT(DRV_NAME), }; static struct ata_port_operations pdc2027x_pata100_ops = { .inherits = &ata_bmdma_port_ops, .check_atapi_dma = pdc2027x_check_atapi_dma, .cable_detect = pdc2027x_cable_detect, .prereset = pdc2027x_prereset, }; static struct ata_port_operations pdc2027x_pata133_ops = { .inherits = &pdc2027x_pata100_ops, .mode_filter = pdc2027x_mode_filter, .set_piomode = pdc2027x_set_piomode, .set_dmamode = pdc2027x_set_dmamode, .set_mode = pdc2027x_set_mode, }; static struct ata_port_info pdc2027x_port_info[] = { /* PDC_UDMA_100 */ { .flags = ATA_FLAG_SLAVE_POSS, .pio_mask = ATA_PIO4, .mwdma_mask = ATA_MWDMA2, .udma_mask = ATA_UDMA5, .port_ops = &pdc2027x_pata100_ops, }, /* PDC_UDMA_133 */ { .flags = ATA_FLAG_SLAVE_POSS, .pio_mask = ATA_PIO4, .mwdma_mask = ATA_MWDMA2, .udma_mask = ATA_UDMA6, .port_ops = &pdc2027x_pata133_ops, }, }; MODULE_AUTHOR("Andre Hedrick, Frank Tiernan, Albert Lee"); MODULE_DESCRIPTION("libata driver module for Promise PDC20268 to PDC20277"); MODULE_LICENSE("GPL"); MODULE_VERSION(DRV_VERSION); MODULE_DEVICE_TABLE(pci, pdc2027x_pci_tbl); /** * port_mmio - Get the MMIO address of PDC2027x extended registers * @ap: Port * @offset: offset from mmio base */ static inline void __iomem *port_mmio(struct ata_port *ap, unsigned int offset) { return ap->host->iomap[PDC_MMIO_BAR] + ap->port_no * 0x100 + offset; } /** * dev_mmio - Get the MMIO address of PDC2027x extended registers * @ap: Port * @adev: device * @offset: offset from mmio base */ static inline void __iomem *dev_mmio(struct ata_port *ap, struct ata_device *adev, unsigned int offset) { u8 adj = (adev->devno) ? 0x08 : 0x00; return port_mmio(ap, offset) + adj; } /** * pdc2027x_pata_cable_detect - Probe host controller cable detect info * @ap: Port for which cable detect info is desired * * Read 80c cable indicator from Promise extended register. * This register is latched when the system is reset. * * LOCKING: * None (inherited from caller). */ static int pdc2027x_cable_detect(struct ata_port *ap) { u32 cgcr; /* check cable detect results */ cgcr = ioread32(port_mmio(ap, PDC_GLOBAL_CTL)); if (cgcr & (1 << 26)) goto cbl40; PDPRINTK("No cable or 80-conductor cable on port %d\n", ap->port_no); return ATA_CBL_PATA80; cbl40: printk(KERN_INFO DRV_NAME ": 40-conductor cable detected on port %d\n", ap->port_no); return ATA_CBL_PATA40; } /** * pdc2027x_port_enabled - Check PDC ATA control register to see whether the port is enabled. * @ap: Port to check */ static inline int pdc2027x_port_enabled(struct ata_port *ap) { return ioread8(port_mmio(ap, PDC_ATA_CTL)) & 0x02; } /** * pdc2027x_prereset - prereset for PATA host controller * @link: Target link * @deadline: deadline jiffies for the operation * * Probeinit including cable detection. * * LOCKING: * None (inherited from caller). */ static int pdc2027x_prereset(struct ata_link *link, unsigned long deadline) { /* Check whether port enabled */ if (!pdc2027x_port_enabled(link->ap)) return -ENOENT; return ata_sff_prereset(link, deadline); } /** * pdc2720x_mode_filter - mode selection filter * @adev: ATA device * @mask: list of modes proposed * * Block UDMA on devices that cause trouble with this controller. */ static unsigned long pdc2027x_mode_filter(struct ata_device *adev, unsigned long mask) { unsigned char model_num[ATA_ID_PROD_LEN + 1]; struct ata_device *pair = ata_dev_pair(adev); if (adev->class != ATA_DEV_ATA || adev->devno == 0 || pair == NULL) return mask; /* Check for slave of a Maxtor at UDMA6 */ ata_id_c_string(pair->id, model_num, ATA_ID_PROD, ATA_ID_PROD_LEN + 1); /* If the master is a maxtor in UDMA6 then the slave should not use UDMA 6 */ if (strstr(model_num, "Maxtor") == NULL && pair->dma_mode == XFER_UDMA_6) mask &= ~ (1 << (6 + ATA_SHIFT_UDMA)); return mask; } /** * pdc2027x_set_piomode - Initialize host controller PATA PIO timings * @ap: Port to configure * @adev: um * * Set PIO mode for device. * * LOCKING: * None (inherited from caller). */ static void pdc2027x_set_piomode(struct ata_port *ap, struct ata_device *adev) { unsigned int pio = adev->pio_mode - XFER_PIO_0; u32 ctcr0, ctcr1; PDPRINTK("adev->pio_mode[%X]\n", adev->pio_mode); /* Sanity check */ if (pio > 4) { printk(KERN_ERR DRV_NAME ": Unknown pio mode [%d] ignored\n", pio); return; } /* Set the PIO timing registers using value table for 133MHz */ PDPRINTK("Set pio regs... \n"); ctcr0 = ioread32(dev_mmio(ap, adev, PDC_CTCR0)); ctcr0 &= 0xffff0000; ctcr0 |= pdc2027x_pio_timing_tbl[pio].value0 | (pdc2027x_pio_timing_tbl[pio].value1 << 8); iowrite32(ctcr0, dev_mmio(ap, adev, PDC_CTCR0)); ctcr1 = ioread32(dev_mmio(ap, adev, PDC_CTCR1)); ctcr1 &= 0x00ffffff; ctcr1 |= (pdc2027x_pio_timing_tbl[pio].value2 << 24); iowrite32(ctcr1, dev_mmio(ap, adev, PDC_CTCR1)); PDPRINTK("Set pio regs done\n"); PDPRINTK("Set to pio mode[%u] \n", pio); } /** * pdc2027x_set_dmamode - Initialize host controller PATA UDMA timings * @ap: Port to configure * @adev: um * * Set UDMA mode for device. * * LOCKING: * None (inherited from caller). */ static void pdc2027x_set_dmamode(struct ata_port *ap, struct ata_device *adev) { unsigned int dma_mode = adev->dma_mode; u32 ctcr0, ctcr1; if ((dma_mode >= XFER_UDMA_0) && (dma_mode <= XFER_UDMA_6)) { /* Set the UDMA timing registers with value table for 133MHz */ unsigned int udma_mode = dma_mode & 0x07; if (dma_mode == XFER_UDMA_2) { /* * Turn off tHOLD. * If tHOLD is '1', the hardware will add half clock for data hold time. * This code segment seems to be no effect. tHOLD will be overwritten below. */ ctcr1 = ioread32(dev_mmio(ap, adev, PDC_CTCR1)); iowrite32(ctcr1 & ~(1 << 7), dev_mmio(ap, adev, PDC_CTCR1)); } PDPRINTK("Set udma regs... \n"); ctcr1 = ioread32(dev_mmio(ap, adev, PDC_CTCR1)); ctcr1 &= 0xff000000; ctcr1 |= pdc2027x_udma_timing_tbl[udma_mode].value0 | (pdc2027x_udma_timing_tbl[udma_mode].value1 << 8) | (pdc2027x_udma_timing_tbl[udma_mode].value2 << 16); iowrite32(ctcr1, dev_mmio(ap, adev, PDC_CTCR1)); PDPRINTK("Set udma regs done\n"); PDPRINTK("Set to udma mode[%u] \n", udma_mode); } else if ((dma_mode >= XFER_MW_DMA_0) && (dma_mode <= XFER_MW_DMA_2)) { /* Set the MDMA timing registers with value table for 133MHz */ unsigned int mdma_mode = dma_mode & 0x07; PDPRINTK("Set mdma regs... \n"); ctcr0 = ioread32(dev_mmio(ap, adev, PDC_CTCR0)); ctcr0 &= 0x0000ffff; ctcr0 |= (pdc2027x_mdma_timing_tbl[mdma_mode].value0 << 16) | (pdc2027x_mdma_timing_tbl[mdma_mode].value1 << 24); iowrite32(ctcr0, dev_mmio(ap, adev, PDC_CTCR0)); PDPRINTK("Set mdma regs done\n"); PDPRINTK("Set to mdma mode[%u] \n", mdma_mode); } else { printk(KERN_ERR DRV_NAME ": Unknown dma mode [%u] ignored\n", dma_mode); } } /** * pdc2027x_set_mode - Set the timing registers back to correct values. * @link: link to configure * @r_failed: Returned device for failure * * The pdc2027x hardware will look at "SET FEATURES" and change the timing registers * automatically. The values set by the hardware might be incorrect, under 133Mhz PLL. * This function overwrites the possibly incorrect values set by the hardware to be correct. */ static int pdc2027x_set_mode(struct ata_link *link, struct ata_device **r_failed) { struct ata_port *ap = link->ap; struct ata_device *dev; int rc; rc = ata_do_set_mode(link, r_failed); if (rc < 0) return rc; ata_for_each_dev(dev, link, ENABLED) { pdc2027x_set_piomode(ap, dev); /* * Enable prefetch if the device support PIO only. */ if (dev->xfer_shift == ATA_SHIFT_PIO) { u32 ctcr1 = ioread32(dev_mmio(ap, dev, PDC_CTCR1)); ctcr1 |= (1 << 25); iowrite32(ctcr1, dev_mmio(ap, dev, PDC_CTCR1)); PDPRINTK("Turn on prefetch\n"); } else { pdc2027x_set_dmamode(ap, dev); } } return 0; } /** * pdc2027x_check_atapi_dma - Check whether ATAPI DMA can be supported for this command * @qc: Metadata associated with taskfile to check * * LOCKING: * None (inherited from caller). * * RETURNS: 0 when ATAPI DMA can be used * 1 otherwise */ static int pdc2027x_check_atapi_dma(struct ata_queued_cmd *qc) { struct scsi_cmnd *cmd = qc->scsicmd; u8 *scsicmd = cmd->cmnd; int rc = 1; /* atapi dma off by default */ /* * This workaround is from Promise's GPL driver. * If ATAPI DMA is used for commands not in the * following white list, say MODE_SENSE and REQUEST_SENSE, * pdc2027x might hit the irq lost problem. */ switch (scsicmd[0]) { case READ_10: case WRITE_10: case READ_12: case WRITE_12: case READ_6: case WRITE_6: case 0xad: /* READ_DVD_STRUCTURE */ case 0xbe: /* READ_CD */ /* ATAPI DMA is ok */ rc = 0; break; default: ; } return rc; } /** * pdc_read_counter - Read the ctr counter * @host: target ATA host */ static long pdc_read_counter(struct ata_host *host) { void __iomem *mmio_base = host->iomap[PDC_MMIO_BAR]; long counter; int retry = 1; u32 bccrl, bccrh, bccrlv, bccrhv; retry: bccrl = ioread32(mmio_base + PDC_BYTE_COUNT) & 0x7fff; bccrh = ioread32(mmio_base + PDC_BYTE_COUNT + 0x100) & 0x7fff; /* Read the counter values again for verification */ bccrlv = ioread32(mmio_base + PDC_BYTE_COUNT) & 0x7fff; bccrhv = ioread32(mmio_base + PDC_BYTE_COUNT + 0x100) & 0x7fff; counter = (bccrh << 15) | bccrl; PDPRINTK("bccrh [%X] bccrl [%X]\n", bccrh, bccrl); PDPRINTK("bccrhv[%X] bccrlv[%X]\n", bccrhv, bccrlv); /* * The 30-bit decreasing counter are read by 2 pieces. * Incorrect value may be read when both bccrh and bccrl are changing. * Ex. When 7900 decrease to 78FF, wrong value 7800 might be read. */ if (retry && !(bccrh == bccrhv && bccrl >= bccrlv)) { retry--; PDPRINTK("rereading counter\n"); goto retry; } return counter; } /** * adjust_pll - Adjust the PLL input clock in Hz. * * @pdc_controller: controller specific information * @host: target ATA host * @pll_clock: The input of PLL in HZ */ static void pdc_adjust_pll(struct ata_host *host, long pll_clock, unsigned int board_idx) { void __iomem *mmio_base = host->iomap[PDC_MMIO_BAR]; u16 pll_ctl; long pll_clock_khz = pll_clock / 1000; long pout_required = board_idx? PDC_133_MHZ:PDC_100_MHZ; long ratio = pout_required / pll_clock_khz; int F, R; /* Sanity check */ if (unlikely(pll_clock_khz < 5000L || pll_clock_khz > 70000L)) { printk(KERN_ERR DRV_NAME ": Invalid PLL input clock %ldkHz, give up!\n", pll_clock_khz); return; } #ifdef PDC_DEBUG PDPRINTK("pout_required is %ld\n", pout_required); /* Show the current clock value of PLL control register * (maybe already configured by the firmware) */ pll_ctl = ioread16(mmio_base + PDC_PLL_CTL); PDPRINTK("pll_ctl[%X]\n", pll_ctl); #endif /* * Calculate the ratio of F, R and OD * POUT = (F + 2) / (( R + 2) * NO) */ if (ratio < 8600L) { /* 8.6x */ /* Using NO = 0x01, R = 0x0D */ R = 0x0d; } else if (ratio < 12900L) { /* 12.9x */ /* Using NO = 0x01, R = 0x08 */ R = 0x08; } else if (ratio < 16100L) { /* 16.1x */ /* Using NO = 0x01, R = 0x06 */ R = 0x06; } else if (ratio < 64000L) { /* 64x */ R = 0x00; } else { /* Invalid ratio */ printk(KERN_ERR DRV_NAME ": Invalid ratio %ld, give up!\n", ratio); return; } F = (ratio * (R+2)) / 1000 - 2; if (unlikely(F < 0 || F > 127)) { /* Invalid F */ printk(KERN_ERR DRV_NAME ": F[%d] invalid!\n", F); return; } PDPRINTK("F[%d] R[%d] ratio*1000[%ld]\n", F, R, ratio); pll_ctl = (R << 8) | F; PDPRINTK("Writing pll_ctl[%X]\n", pll_ctl); iowrite16(pll_ctl, mmio_base + PDC_PLL_CTL); ioread16(mmio_base + PDC_PLL_CTL); /* flush */ /* Wait the PLL circuit to be stable */ mdelay(30); #ifdef PDC_DEBUG /* * Show the current clock value of PLL control register * (maybe configured by the firmware) */ pll_ctl = ioread16(mmio_base + PDC_PLL_CTL); PDPRINTK("pll_ctl[%X]\n", pll_ctl); #endif return; } /** * detect_pll_input_clock - Detect the PLL input clock in Hz. * @host: target ATA host * Ex. 16949000 on 33MHz PCI bus for pdc20275. * Half of the PCI clock. */ static long pdc_detect_pll_input_clock(struct ata_host *host) { void __iomem *mmio_base = host->iomap[PDC_MMIO_BAR]; u32 scr; long start_count, end_count; ktime_t start_time, end_time; long pll_clock, usec_elapsed; /* Start the test mode */ scr = ioread32(mmio_base + PDC_SYS_CTL); PDPRINTK("scr[%X]\n", scr); iowrite32(scr | (0x01 << 14), mmio_base + PDC_SYS_CTL); ioread32(mmio_base + PDC_SYS_CTL); /* flush */ /* Read current counter value */ start_count = pdc_read_counter(host); start_time = ktime_get(); /* Let the counter run for 100 ms. */ mdelay(100); /* Read the counter values again */ end_count = pdc_read_counter(host); end_time = ktime_get(); /* Stop the test mode */ scr = ioread32(mmio_base + PDC_SYS_CTL); PDPRINTK("scr[%X]\n", scr); iowrite32(scr & ~(0x01 << 14), mmio_base + PDC_SYS_CTL); ioread32(mmio_base + PDC_SYS_CTL); /* flush */ /* calculate the input clock in Hz */ usec_elapsed = (long) ktime_us_delta(end_time, start_time); pll_clock = ((start_count - end_count) & 0x3fffffff) / 100 * (100000000 / usec_elapsed); PDPRINTK("start[%ld] end[%ld] \n", start_count, end_count); PDPRINTK("PLL input clock[%ld]Hz\n", pll_clock); return pll_clock; } /** * pdc_hardware_init - Initialize the hardware. * @host: target ATA host * @board_idx: board identifier */ static int pdc_hardware_init(struct ata_host *host, unsigned int board_idx) { long pll_clock; /* * Detect PLL input clock rate. * On some system, where PCI bus is running at non-standard clock rate. * Ex. 25MHz or 40MHz, we have to adjust the cycle_time. * The pdc20275 controller employs PLL circuit to help correct timing registers setting. */ pll_clock = pdc_detect_pll_input_clock(host); dev_info(host->dev, "PLL input clock %ld kHz\n", pll_clock/1000); /* Adjust PLL control register */ pdc_adjust_pll(host, pll_clock, board_idx); return 0; } /** * pdc_ata_setup_port - setup the mmio address * @port: ata ioports to setup * @base: base address */ static void pdc_ata_setup_port(struct ata_ioports *port, void __iomem *base) { port->cmd_addr = port->data_addr = base; port->feature_addr = port->error_addr = base + 0x05; port->nsect_addr = base + 0x0a; port->lbal_addr = base + 0x0f; port->lbam_addr = base + 0x10; port->lbah_addr = base + 0x15; port->device_addr = base + 0x1a; port->command_addr = port->status_addr = base + 0x1f; port->altstatus_addr = port->ctl_addr = base + 0x81a; } /** * pdc2027x_init_one - PCI probe function * Called when an instance of PCI adapter is inserted. * This function checks whether the hardware is supported, * initialize hardware and register an instance of ata_host to * libata. (implements struct pci_driver.probe() ) * * @pdev: instance of pci_dev found * @ent: matching entry in the id_tbl[] */ static int pdc2027x_init_one(struct pci_dev *pdev, const struct pci_device_id *ent) { static const unsigned long cmd_offset[] = { 0x17c0, 0x15c0 }; static const unsigned long bmdma_offset[] = { 0x1000, 0x1008 }; unsigned int board_idx = (unsigned int) ent->driver_data; const struct ata_port_info *ppi[] = { &pdc2027x_port_info[board_idx], NULL }; struct ata_host *host; void __iomem *mmio_base; int i, rc; ata_print_version_once(&pdev->dev, DRV_VERSION); /* alloc host */ host = ata_host_alloc_pinfo(&pdev->dev, ppi, 2); if (!host) return -ENOMEM; /* acquire resources and fill host */ rc = pcim_enable_device(pdev); if (rc) return rc; rc = pcim_iomap_regions(pdev, 1 << PDC_MMIO_BAR, DRV_NAME); if (rc) return rc; host->iomap = pcim_iomap_table(pdev); rc = dma_set_mask(&pdev->dev, ATA_DMA_MASK); if (rc) return rc; rc = dma_set_coherent_mask(&pdev->dev, ATA_DMA_MASK); if (rc) return rc; mmio_base = host->iomap[PDC_MMIO_BAR]; for (i = 0; i < 2; i++) { struct ata_port *ap = host->ports[i]; pdc_ata_setup_port(&ap->ioaddr, mmio_base + cmd_offset[i]); ap->ioaddr.bmdma_addr = mmio_base + bmdma_offset[i]; ata_port_pbar_desc(ap, PDC_MMIO_BAR, -1, "mmio"); ata_port_pbar_desc(ap, PDC_MMIO_BAR, cmd_offset[i], "cmd"); } //pci_enable_intx(pdev); /* initialize adapter */ if (pdc_hardware_init(host, board_idx) != 0) return -EIO; pci_set_master(pdev); return ata_host_activate(host, pdev->irq, ata_bmdma_interrupt, IRQF_SHARED, &pdc2027x_sht); } #ifdef CONFIG_PM_SLEEP static int pdc2027x_reinit_one(struct pci_dev *pdev) { struct ata_host *host = pci_get_drvdata(pdev); unsigned int board_idx; int rc; rc = ata_pci_device_do_resume(pdev); if (rc) return rc; if (pdev->device == PCI_DEVICE_ID_PROMISE_20268 || pdev->device == PCI_DEVICE_ID_PROMISE_20270) board_idx = PDC_UDMA_100; else board_idx = PDC_UDMA_133; if (pdc_hardware_init(host, board_idx)) return -EIO; ata_host_resume(host); return 0; } #endif module_pci_driver(pdc2027x_pci_driver);
null
null
null
null
105,647
1,314
null
train_val
83ed75feba32e46f736fcce0d96a0445f29b96c2
163,158
krb5
0
https://github.com/krb5/krb5
2016-01-27 15:43:28-05:00
/* lib/rpc/svc_run.c */ /* * Copyright (c) 2010, Oracle America, 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 the "Oracle America, 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 * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * This is the rpc server side idle loop * Wait for input, call server program. */ #include <gssrpc/rpc.h> #include <errno.h> extern int svc_maxfd; void svc_run(void) { #ifdef FD_SETSIZE fd_set readfds; #else int readfds; #endif /* def FD_SETSIZE */ for (;;) { #ifdef FD_SETSIZE readfds = svc_fdset; #else readfds = svc_fds; #endif /* def FD_SETSIZE */ switch (select(svc_maxfd + 1, &readfds, (fd_set *)0, (fd_set *)0, (struct timeval *)0)) { case -1: if (errno == EINTR) { continue; } perror("svc_run: - select failed"); return; case 0: continue; default: svc_getreqset(&readfds); } } }
null
null
null
null
74,466
65,500
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
65,500
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_UI_TASK_MANAGER_TASK_MANAGER_TABLE_MODEL_H_ #define CHROME_BROWSER_UI_TASK_MANAGER_TASK_MANAGER_TABLE_MODEL_H_ #include <stdint.h> #include <memory> #include "base/macros.h" #include "base/values.h" #include "chrome/browser/task_manager/task_manager_observer.h" #include "ui/base/models/table_model.h" namespace content { class WebContents; } namespace task_manager { class TaskManagerValuesStringifier; // Describes how the platform specific table view is sorted. struct TableSortDescriptor { TableSortDescriptor(); TableSortDescriptor(int col_id, bool ascending); // The ID of the sorted column, -1 if the table is not sorted. int sorted_column_id; // True if the column is sorted ascending. bool is_ascending; }; // An interface to be able to communicate with the platform-specific table view // (Either views::TableView or NSTableView on the Mac). class TableViewDelegate { public: TableViewDelegate() {} virtual ~TableViewDelegate() {} virtual bool IsColumnVisible(int column_id) const = 0; virtual void SetColumnVisibility(int column_id, bool new_visibility) = 0; virtual bool IsTableSorted() const = 0; virtual TableSortDescriptor GetSortDescriptor() const = 0; virtual void SetSortDescriptor( const TableSortDescriptor& sort_descriptor) = 0; private: DISALLOW_COPY_AND_ASSIGN(TableViewDelegate); }; class TaskManagerTableModel : public TaskManagerObserver, public ui::TableModel { public: explicit TaskManagerTableModel(TableViewDelegate* delegate); ~TaskManagerTableModel() override; // ui::TableModel: int RowCount() override; base::string16 GetText(int row, int column) override; gfx::ImageSkia GetIcon(int row) override; void SetObserver(ui::TableModelObserver* observer) override; int CompareValues(int row1, int row2, int column_id) override; // task_manager::TaskManagerObserver: void OnTaskAdded(TaskId id) override; void OnTaskToBeRemoved(TaskId id) override; void OnTasksRefreshed(const TaskIdList& task_ids) override; // Gets the start index and length of the group to which the task at // |row_index| belongs. void GetRowsGroupRange(int row_index, int* out_start, int* out_length); // Activates the browser tab associated with the process in the specified // |row_index|. void ActivateTask(int row_index); // Kills the process on which the task at |row_index| is running. void KillTask(int row_index); // Based on the given |visibility| and the |column_id|, a particular refresh // type will be enabled or disabled. void UpdateRefreshTypes(int column_id, bool visibility); // Checks if the task at |row_index| is killable. bool IsTaskKillable(int row_index) const; // Restores the saved columns settings from a previous session into // |columns_settings_| and updates the table view. void RetrieveSavedColumnsSettingsAndUpdateTable(); // Stores the current values in |column_settings_| to the user prefs so that // it can be restored later next time the task manager view is opened. void StoreColumnsSettings(); void ToggleColumnVisibility(int column_id); // Returns the row index corresponding to a particular WebContents. Returns -1 // if |web_contents| is nullptr, or is not currently found in the model (for // example, if the tab is currently crashed). int GetRowForWebContents(content::WebContents* web_contents); private: friend class TaskManagerTester; // Start / stop observing the task manager. void StartUpdating(); void StopUpdating(); void OnRefresh(); // Checks whether the task at |row_index| is the first task in its process // group of tasks. bool IsTaskFirstInGroup(int row_index) const; // The delegate that will be used to communicate with the platform-specific // TableView. TableViewDelegate* table_view_delegate_; // Contains either the column settings retrieved from user preferences if it // exists, or the default column settings. // The columns settings are the visible columns and the last sorted column // and the direction of the sort. std::unique_ptr<base::DictionaryValue> columns_settings_; // The table model observer that will be set by the table view of the task // manager. ui::TableModelObserver* table_model_observer_; // The sorted list of task IDs by process ID then by task ID. std::vector<TaskId> tasks_; // The owned task manager values stringifier that will be used to convert the // values to string16. std::unique_ptr<TaskManagerValuesStringifier> stringifier_; // The status of the flag #enable-nacl-debug. bool is_nacl_debugging_flag_enabled_; DISALLOW_COPY_AND_ASSIGN(TaskManagerTableModel); }; } // namespace task_manager #endif // CHROME_BROWSER_UI_TASK_MANAGER_TASK_MANAGER_TABLE_MODEL_H_
null
null
null
null
62,363
70,799
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
70,799
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright 2017 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 <windows.h> #include "base/files/file_path.h" #include "base/scoped_native_library.h" namespace { //------------------------------------------------------------------------------ // PRIVATE: Control Flow Guard test things // - MS binary indirect call tests. //------------------------------------------------------------------------------ // These structures hold chunks of binary. No padding wanted. #pragma pack(push, 1) #if defined(_WIN64) const USHORT kCmpRsi = 0x3B48; const BYTE kRax = 0xF0; const USHORT kJzLoc = 0x0074; const ULONG kMovRcxRsiCall = 0xFFCE8B48; const BYTE kPadding = 0x00; const ULONG kMovEcxEbxCallRsi = 0xD6FFCB8B; const ULONG kMovRcxRsiAdd = 0x48CE8B48; const ULONG kRcx10hNop = 0x9010C183; // Sequence of bytes in GetSystemMetrics. struct Signature { // This struct contains roughly the following code: // cmp rsi, rax // jz jmp_addr // mov rcx, rsi // call ULONG_addr <-- CFG check function // mov ecx, ebx // call rsi <-- Actual call to GetSystemMetrics // Patch will start here and be 8 bytes. USHORT cmp_rsi; // = 48 3B BYTE rax; // = F0 USHORT jz_loc; // = 74 XX ULONG mov_rcx_rsi_call; // = 48 8B CE FF ULONG guard_check_icall_fptr; // = XX XX XX XX BYTE padding; // = 00 ULONG mov_ecx_ebx_call_rsi; // = 8B CB FF D6 }; struct Patch { // Just add 16 to the existing function address. // This ensures a 16-byte aligned address that is // definitely not a valid function address. // mov rcx, rsi = 48 4B CE // add rcx, 10h = 48 83 C1 10 // nop = 90 ULONG first_four_bytes; // = 48 4B CE 48 ULONG second_four_bytes; // = 83 C1 10 90 }; #else // x86 const USHORT kCmpEbx = 0x0081; const USHORT kJzLoc = 0x0074; const ULONG kMovEcxEbxCall = 0x15FFCB8B; const USHORT kCallEbx = 0xD3FF; const ULONG kMovEcxEbxAddEcx = 0xC183CB8B; const ULONG k16Nops = 0x90909010; const USHORT kTwoNops = 0x9090; // Sequence of bytes in GetSystemMetrics, x86. struct Signature { // This struct contains roughly the following code: // cmp ebx, offset // jz jmp_addr // mov ecx, ebx // call ULONG_addr <-- CFG check function // call ebx <-- Actual call to GetSystemMetrics // Patch will start here and be 10 bytes. USHORT cmp_ebx; // = 81 XX ULONG addr; // = XX XX XX XX USHORT jz_loc; // = 74 XX ULONG mov_ecx_ebx_call; // = 8B CB FF 15 ULONG guard_check_icall_fptr; // = XX XX XX XX USHORT call_ebx; // = FF D3 }; struct Patch { // Just add 16 to the existing function address. // This ensures a 16-byte aligned address that is // definitely not a valid function address. // mov ecx, ebx = 8B CB // add ecx, 10h = 83 C1 10 90 // nop = 90 90 90 90 ULONG first_four_bytes; // = 8B CB 83 C1 ULONG second_four_bytes; // = 10 90 90 90 USHORT last_two_bytes; // = 90 90 }; #endif // _WIN64 #pragma pack(pop) //------------------------------------------------------------------------------ // - Search binary starting at |address_start| for a matching chunk of // |binary_to_find|, of size |size_to_match|. // - A byte of value 0 in |binary_to_find|, is a wildcard for anything. // - Give a |max_distance| to find the chunk within, before failing. // - If return value is true, |out_offset| will hold the offset from // |address_start| that the match starts. bool FindBinary(BYTE* binary_to_find, DWORD size_to_match, BYTE* address_start, DWORD max_distance, DWORD* out_offset) { assert(size_to_match <= max_distance); assert(size_to_match > 0); BYTE* max_byte = address_start + max_distance - size_to_match; BYTE* temp_ptr = address_start; // Yes, it's a double while loop. while (temp_ptr <= max_byte) { size_t i = 0; // 0 is a wildcard match. while (binary_to_find[i] == 0 || temp_ptr[i] == binary_to_find[i]) { // Check if this is the last byte. if (i == size_to_match - 1) { *out_offset = temp_ptr - address_start; return true; } ++i; } ++temp_ptr; } return false; } // - Will write patch starting at |start_addr| with the patch for x86 // or x64. // - This function is only for writes within this process. bool DoPatch(BYTE* start_addr) { Patch patch = {}; #if defined(_WIN64) patch.first_four_bytes = kMovRcxRsiAdd; patch.second_four_bytes = kRcx10hNop; #else // x86 patch.first_four_bytes = kMovEcxEbxAddEcx; patch.second_four_bytes = k16Nops; patch.last_two_bytes = kTwoNops; #endif // _WIN64 DWORD old_protection; // PAGE_WRITECOPY explicitly allows "copy-on-write" behaviour for // system DLL patches. if (!::VirtualProtect(start_addr, sizeof(patch), PAGE_WRITECOPY, &old_protection)) return false; ::memcpy(start_addr, &patch, sizeof(patch)); ::VirtualProtect(start_addr, sizeof(patch), old_protection, &old_protection); return true; } // - Find the offset from |start| that the x86 or x64 signature starts. bool FindSignature(BYTE* start, DWORD* offset_found) { Signature signature = {}; #if defined(_WIN64) signature.cmp_rsi = kCmpRsi; signature.rax = kRax; signature.jz_loc = kJzLoc; signature.mov_rcx_rsi_call = kMovRcxRsiCall; signature.padding = kPadding; signature.mov_ecx_ebx_call_rsi = kMovEcxEbxCallRsi; // This is far enough into GetSystemMetrics that the signature should // have been found. See disassembly. DWORD max_area = 0xB0; #else // x86 signature.cmp_ebx = kCmpEbx; signature.jz_loc = kJzLoc; signature.mov_ecx_ebx_call = kMovEcxEbxCall; signature.call_ebx = kCallEbx; // This is far enough into GetSystemMetrics x86 that the signature should // have been found. See disassembly. DWORD max_area = 0xD9; #endif // _WIN64 if (!FindBinary(reinterpret_cast<BYTE*>(&signature), sizeof(signature), start, max_area, offset_found)) return false; return true; } // - This function tests for CFG in MS system binaries, in process. // // A few words about the patching for this test: // // - In both x86 and x64, the function FindSignature() will scan // GetSystemMetrics in user32.dll, to find the ideal place chosen // for this test. It's a spot where a CFG check was compiled into // a Microsoft system DLL. For more visualization, open user32.dll // in IDA to follow along (especially if planning to change this test). // // - The CFG security check basically calls __guard_check_icall_fptr, with // the function address about to be called as the argument in EAX/RAX reg. // If the address is not in the process' "valid indirect call bitmap", a // CFG exception will be thrown. // // - The DoPatch() function then overwrites with a small, custom change. This // change will simply add 16 (0x10) to the real function address in EAX/RAX // about to be checked. This will maintain the 16-byte alignment required in // a target address by CFG, but also ensure that it fails the check. // // The whole purpose of this unittest is to ensure that a failed CFG check in // a Microsoft binary results in an exception. If CFG is not properly // enabled for a process, no exception will be thrown. // All Chromium projects should be linked with "common_linker_setup" config // (build\config\win\BUILD.gn), which should result in CFG enabled on the // process. // // - The patches (x86 or x64) were carefully constructed to be valid and not // mess up the executing instructions. Need to ensure that the CFG check // fully happens, and that nothing else goes wrong before OR AFTER that // point. The only exception expected is a very intentional one. // **The patches also allow the call to GetSystemMetrics to SUCCEED if CFG is // NOT enabled for the process! This makes for very clear behaviour. void TestMsIndirect() { base::ScopedNativeLibrary user32(base::FilePath(L"user32.dll")); if (!user32.is_valid()) _exit(1); using GetSystemMetricsFunction = decltype(&::GetSystemMetrics); GetSystemMetricsFunction get_system_metrics = reinterpret_cast<GetSystemMetricsFunction>( user32.GetFunctionPointer("GetSystemMetrics")); if (!get_system_metrics) _exit(2); // Sanity check the function works fine pre-patch. Tests should only be // running from normal boot (0). if (0 != get_system_metrics(SM_CLEANBOOT)) _exit(3); BYTE* target = reinterpret_cast<BYTE*>(get_system_metrics); DWORD offset = 0; if (!FindSignature(target, &offset)) _exit(4); // Now patch the function. Don't bother saving original code, // as this process will end very soon. if (!DoPatch(target + offset)) _exit(5); // Call the patched function! get_system_metrics(SM_CLEANBOOT); } } // namespace //------------------------------------------------------------------------------ // PUBLIC //------------------------------------------------------------------------------ // Good ol' main. // - Exe exits with non-zero return codes for unexpected errors. // - Return code of zero indicates no issues at all. // - Else, a CFG exception will result in the process being destroyed. int main(int argc, char** argv) { if (argc != 2) _exit(-1); const char* arg = argv[1]; int iarg = ::atoi(arg); if (!iarg) _exit(-1); switch (iarg) { // kSysDllTest case 1: TestMsIndirect(); break; // Unsupported argument. default: _exit(-1); } return 0; }
null
null
null
null
67,662
24,596
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
189,591
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
static uint32_t gf100_pmu_data[] = { /* 0x0000: proc_kern */ 0x52544e49, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, /* 0x0058: proc_list_head */ 0x54534f48, 0x0000050a, 0x000004a7, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x584d454d, 0x00000756, 0x00000748, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x46524550, 0x0000075a, 0x00000758, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x5f433249, 0x00000b8a, 0x00000a2d, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x54534554, 0x00000bb3, 0x00000b8c, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x454c4449, 0x00000bbf, 0x00000bbd, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, /* 0x0268: proc_list_tail */ /* 0x0268: time_prev */ 0x00000000, /* 0x026c: time_next */ 0x00000000, /* 0x0270: fifo_queue */ 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, /* 0x02f0: rfifo_queue */ 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, /* 0x0370: memx_func_head */ 0x00000001, 0x00000000, 0x00000549, /* 0x037c: memx_func_next */ 0x00000002, 0x00000000, 0x000005d3, 0x00000003, 0x00000002, 0x0000069d, 0x00040004, 0x00000000, 0x000006b9, 0x00010005, 0x00000000, 0x000006d6, 0x00010006, 0x00000000, 0x0000065b, 0x00000007, 0x00000000, 0x000006e1, /* 0x03c4: memx_func_tail */ /* 0x03c4: memx_ts_start */ 0x00000000, /* 0x03c8: memx_ts_end */ 0x00000000, /* 0x03cc: memx_data_head */ 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, /* 0x0bcc: memx_data_tail */ /* 0x0bcc: memx_train_head */ 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, /* 0x0ccc: memx_train_tail */ /* 0x0ccc: i2c_scl_map */ 0x00001000, 0x00004000, 0x00010000, 0x00000100, 0x00040000, 0x00100000, 0x00400000, 0x01000000, 0x04000000, 0x10000000, /* 0x0cf4: i2c_sda_map */ 0x00002000, 0x00008000, 0x00020000, 0x00000200, 0x00080000, 0x00200000, 0x00800000, 0x02000000, 0x08000000, 0x20000000, /* 0x0d1c: i2c_ctrl */ 0x0000e138, 0x0000e150, 0x0000e168, 0x0000e180, 0x0000e254, 0x0000e274, 0x0000e764, 0x0000e780, 0x0000e79c, 0x0000e7b8, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, }; static uint32_t gf100_pmu_code[] = { 0x03920ef5, /* 0x0004: rd32 */ 0x07a007f1, 0xd00604b6, 0x04bd000e, 0x0001d7f1, 0xf101d3f0, 0xb607ac07, 0x0dd00604, /* 0x0023: rd32_wait */ 0xf104bd00, 0xb607acd7, 0xddcf06d4, 0x00d4f100, 0xf21bf470, 0x07a4d7f1, 0xcf06d4b6, 0x00f800dd, /* 0x0040: wr32 */ 0x07a007f1, 0xd00604b6, 0x04bd000e, 0x07a407f1, 0xd00604b6, 0x04bd000d, 0x00f2d7f1, 0xf101d3f0, 0xb607ac07, 0x0dd00604, /* 0x006b: wr32_wait */ 0xf104bd00, 0xb607acd7, 0xddcf06d4, 0x00d4f100, 0xf21bf470, /* 0x007e: nsec */ 0x90f900f8, 0x87f080f9, 0x0684b62c, /* 0x008b: nsec_loop */ 0xf00088cf, 0x94b62c97, 0x0099cf06, 0xb80298bb, 0x1ef4069e, 0xfc80fcf1, /* 0x00a3: wait */ 0xf900f890, 0xf080f990, 0x84b62c87, 0x0088cf06, /* 0x00b0: wait_loop */ 0xf402eeb9, 0xdab90421, 0x04adfd02, 0xf406acb8, 0x97f0150b, 0x0694b62c, 0xbb0099cf, 0x9bb80298, 0xdf1ef406, /* 0x00d4: wait_done */ 0x90fc80fc, /* 0x00da: intr_watchdog */ 0xe99800f8, 0x0096b003, 0x982a0bf4, 0x9abb9a0a, 0x0f1cf402, 0xf501d7f0, 0xbd02d121, 0x150ef494, /* 0x00f8: intr_watchdog_next_time */ 0xb09b0a98, 0x0bf400a6, 0x069ab809, /* 0x0107: intr_watchdog_next_time_set */ 0x80061cf4, /* 0x010a: intr_watchdog_next_proc */ 0xe9809b09, 0x58e0b603, 0x0268e6b1, 0xf8c61bf4, /* 0x0119: intr */ 0xbd00f900, 0xf980f904, 0xf9a0f990, 0xf9c0f9b0, 0xf9e0f9d0, 0x00f7f0f0, 0xf90188fe, 0xd087f180, 0x0684b605, 0xb60088cf, 0x07f10180, 0x04b605d0, 0x0008d006, 0x87f004bd, 0x0684b608, 0xc40088cf, 0x0bf40289, 0x9b008023, 0xf458e7f0, 0x0998da21, 0x0096b09b, 0xf0110bf4, 0x04b63407, 0x0009d006, 0x098004bd, /* 0x017d: intr_skip_watchdog */ 0x0089e49a, 0x480bf408, 0x068897f1, 0xcf0694b6, 0x9ac40099, 0x2c0bf402, 0x04c0c7f1, 0xcf06c4b6, 0xc0f900cc, 0x4f48e7f1, 0x5453e3f1, 0xf500d7f0, 0xfc033621, 0xc007f1c0, 0x0604b604, 0xbd000cd0, /* 0x01bd: intr_subintr_skip_fifo */ 0x8807f104, 0x0604b606, 0xbd0009d0, /* 0x01c9: intr_skip_subintr */ 0xe097f104, 0xfd90bd00, 0x07f00489, 0x0604b604, 0xbd0008d0, 0xfe80fc04, 0xf0fc0088, 0xd0fce0fc, 0xb0fcc0fc, 0x90fca0fc, 0x00fc80fc, 0xf80032f4, /* 0x01f9: ticks_from_ns */ 0xf9c0f901, 0xcbd7f1b0, 0x00d3f000, 0x040b21f5, 0x03e8ccec, 0xf400b4b0, 0xeeec120b, 0xd7f103e8, 0xd3f000cb, 0x0b21f500, /* 0x0221: ticks_from_ns_quit */ 0x02ceb904, 0xc0fcb0fc, /* 0x022a: ticks_from_us */ 0xc0f900f8, 0xd7f1b0f9, 0xd3f000cb, 0x0b21f500, 0x02ceb904, 0xf400b4b0, 0xe4bd050b, /* 0x0244: ticks_from_us_quit */ 0xc0fcb0fc, /* 0x024a: ticks_to_us */ 0xd7f100f8, 0xd3f000cb, 0xecedff00, /* 0x0256: timer */ 0x90f900f8, 0x32f480f9, 0x03f89810, 0xf40086b0, 0x84bd651c, 0xb63807f0, 0x08d00604, 0xf004bd00, 0x84b63487, 0x0088cf06, 0xbb9a0998, 0xe9bb0298, 0x03fe8000, 0xb60887f0, 0x88cf0684, 0x0284f000, 0xf0261bf4, 0x84b63487, 0x0088cf06, 0xf406e0b8, 0xe8b8090b, 0x111cf406, /* 0x02ac: timer_reset */ 0xb63407f0, 0x0ed00604, 0x8004bd00, /* 0x02ba: timer_enable */ 0x87f09a0e, 0x3807f001, 0xd00604b6, 0x04bd0008, /* 0x02c8: timer_done */ 0xfc1031f4, 0xf890fc80, /* 0x02d1: send_proc */ 0xf980f900, 0x05e89890, 0xf004e998, 0x89b80486, 0x2a0bf406, 0x940398c4, 0x80b60488, 0x008ebb18, 0x8000fa98, 0x8d80008a, 0x028c8001, 0xb6038b80, 0x94f00190, 0x04e98007, /* 0x030b: send_done */ 0xfc0231f4, 0xf880fc90, /* 0x0311: find */ 0xf080f900, 0x31f45887, /* 0x0319: find_loop */ 0x008a9801, 0xf406aeb8, 0x80b6100b, 0x6886b158, 0xf01bf402, /* 0x032f: find_done */ 0xb90132f4, 0x80fc028e, /* 0x0336: send */ 0x21f500f8, 0x01f40311, /* 0x033f: recv */ 0xf900f897, 0x9880f990, 0xe99805e8, 0x0132f404, 0xf40689b8, 0x89c43d0b, 0x0180b603, 0x800784f0, 0xea9805e8, 0xfef0f902, 0xf0f9018f, 0x9402efb9, 0xe9bb0499, 0x18e0b600, 0x9803eb98, 0xed9802ec, 0x00ee9801, 0xf0fca5f9, 0xf400f8fe, 0xf0fc0131, /* 0x038c: recv_done */ 0x90fc80fc, /* 0x0392: init */ 0x17f100f8, 0x14b60108, 0x0011cf06, 0x010911e7, 0xfe0814b6, 0x17f10014, 0x13f000e0, 0x1c07f000, 0xd00604b6, 0x04bd0001, 0xf0ff17f0, 0x04b61407, 0x0001d006, 0x17f004bd, 0x0015f102, 0x1007f008, 0xd00604b6, 0x04bd0001, 0x011917f1, 0xf10013f0, 0xfeffff14, 0x31f40010, 0x0117f010, 0xb63807f0, 0x01d00604, 0xf004bd00, /* 0x03fa: init_proc */ 0xf19858f7, 0x0016b001, 0xf9fa0bf4, 0x58f0b615, /* 0x040b: mulu32_32_64 */ 0xf9f20ef4, 0xf920f910, 0x9540f930, 0xd29510e1, 0xbdc4bd10, 0xc0edffb4, 0xb9301dff, 0x34f10234, 0x34b6ffff, 0x1045b610, 0xbb00c3bb, 0xe2ff01b4, 0x0234b930, 0xffff34f1, 0xb61034b6, 0xc3bb1045, 0x01b4bb00, 0xbb3012ff, 0x40fc00b3, 0x20fc30fc, 0x00f810fc, /* 0x045c: host_send */ 0x04b017f1, 0xcf0614b6, 0x27f10011, 0x24b604a0, 0x0022cf06, 0xf40612b8, 0x1ec4320b, 0x04ee9407, 0x0270e0b7, 0x9803eb98, 0xed9802ec, 0x00ee9801, 0x033621f5, 0xc40110b6, 0x07f10f1e, 0x04b604b0, 0x000ed006, 0x0ef404bd, /* 0x04a5: host_send_done */ /* 0x04a7: host_recv */ 0xf100f8ba, 0xf14e4917, 0xb8525413, 0x0bf406e1, /* 0x04b5: host_recv_wait */ 0xcc17f1aa, 0x0614b604, 0xf10011cf, 0xb604c827, 0x22cf0624, 0x0816f000, 0xf40612b8, 0x23c4e60b, 0x0434b607, 0x02f030b7, 0x80033b80, 0x3d80023c, 0x003e8001, 0xf00120b6, 0x07f10f24, 0x04b604c8, 0x0002d006, 0x27f004bd, 0x0007f040, 0xd00604b6, 0x04bd0002, /* 0x050a: host_init */ 0x17f100f8, 0x14b60080, 0x7015f110, 0xd007f102, 0x0604b604, 0xbd0001d0, 0x8017f104, 0x1014b600, 0x02f015f1, 0x04dc07f1, 0xd00604b6, 0x04bd0001, 0xf10117f0, 0xb604c407, 0x01d00604, 0xf804bd00, /* 0x0549: memx_func_enter */ 0x2067f100, 0x5d77f116, 0xff73f1f5, 0x026eb9ff, 0xb90421f4, 0x87fd02d8, 0xf960f904, 0xfcd0fc80, 0x4021f4e0, 0xfffe77f1, 0xffff73f1, 0xf4026eb9, 0xd8b90421, 0x0487fd02, 0x80f960f9, 0xe0fcd0fc, 0xf14021f4, 0xb926f067, 0x21f4026e, 0x02d8b904, 0xf90487fd, 0xfc80f960, 0xf4e0fcd0, 0x67f04021, 0xe007f104, 0x0604b607, 0xbd0006d0, /* 0x05b5: memx_func_enter_wait */ 0xc067f104, 0x0664b607, 0xf00066cf, 0x0bf40464, 0x2c67f0f3, 0xcf0664b6, 0x06800066, /* 0x05d3: memx_func_leave */ 0xf000f8f1, 0x64b62c67, 0x0066cf06, 0xf0f20680, 0x07f10467, 0x04b607e4, 0x0006d006, /* 0x05ee: memx_func_leave_wait */ 0x67f104bd, 0x64b607c0, 0x0066cf06, 0xf40464f0, 0x67f1f31b, 0x77f126f0, 0x73f00001, 0x026eb900, 0xb90421f4, 0x87fd02d8, 0xf960f905, 0xfcd0fc80, 0x4021f4e0, 0x162067f1, 0xf4026eb9, 0xd8b90421, 0x0587fd02, 0x80f960f9, 0xe0fcd0fc, 0xf14021f4, 0xf00aa277, 0x6eb90073, 0x0421f402, 0xfd02d8b9, 0x60f90587, 0xd0fc80f9, 0x21f4e0fc, /* 0x065b: memx_func_wait_vblank */ 0x9800f840, 0x66b00016, 0x130bf400, 0xf40166b0, 0x0ef4060b, /* 0x066d: memx_func_wait_vblank_head1 */ 0x2077f12e, 0x070ef400, /* 0x0674: memx_func_wait_vblank_head0 */ 0x000877f1, /* 0x0678: memx_func_wait_vblank_0 */ 0x07c467f1, 0xcf0664b6, 0x67fd0066, 0xf31bf404, /* 0x0688: memx_func_wait_vblank_1 */ 0x07c467f1, 0xcf0664b6, 0x67fd0066, 0xf30bf404, /* 0x0698: memx_func_wait_vblank_fini */ 0xf80410b6, /* 0x069d: memx_func_wr32 */ 0x00169800, 0xb6011598, 0x60f90810, 0xd0fc50f9, 0x21f4e0fc, 0x0242b640, 0xf8e91bf4, /* 0x06b9: memx_func_wait */ 0x2c87f000, 0xcf0684b6, 0x1e980088, 0x011d9800, 0x98021c98, 0x10b6031b, 0xa321f410, /* 0x06d6: memx_func_delay */ 0x1e9800f8, 0x0410b600, 0xf87e21f4, /* 0x06e1: memx_func_train */ /* 0x06e3: memx_exec */ 0xf900f800, 0xb9d0f9e0, 0xb2b902c1, /* 0x06ed: memx_exec_next */ 0x00139802, 0xe70410b6, 0xe701f034, 0xb601e033, 0x30f00132, 0xde35980c, 0x12b855f9, 0xe41ef406, 0x98f10b98, 0xcbbbf20c, 0xc4b7f102, 0x06b4b607, 0xfc00bbcf, 0xf5e0fcd0, 0xf8033621, /* 0x0729: memx_info */ 0x01c67000, /* 0x072f: memx_info_data */ 0xf10e0bf4, 0xf103ccc7, 0xf40800b7, /* 0x073a: memx_info_train */ 0xc7f10b0e, 0xb7f10bcc, /* 0x0742: memx_info_send */ 0x21f50100, 0x00f80336, /* 0x0748: memx_recv */ 0xf401d6b0, 0xd6b0980b, 0xd80bf400, /* 0x0756: memx_init */ 0x00f800f8, /* 0x0758: perf_recv */ /* 0x075a: perf_init */ 0x00f800f8, /* 0x075c: i2c_drive_scl */ 0xf40036b0, 0x07f1110b, 0x04b607e0, 0x0001d006, 0x00f804bd, /* 0x0770: i2c_drive_scl_lo */ 0x07e407f1, 0xd00604b6, 0x04bd0001, /* 0x077e: i2c_drive_sda */ 0x36b000f8, 0x110bf400, 0x07e007f1, 0xd00604b6, 0x04bd0002, /* 0x0792: i2c_drive_sda_lo */ 0x07f100f8, 0x04b607e4, 0x0002d006, 0x00f804bd, /* 0x07a0: i2c_sense_scl */ 0xf10132f4, 0xb607c437, 0x33cf0634, 0x0431fd00, 0xf4060bf4, /* 0x07b6: i2c_sense_scl_done */ 0x00f80131, /* 0x07b8: i2c_sense_sda */ 0xf10132f4, 0xb607c437, 0x33cf0634, 0x0432fd00, 0xf4060bf4, /* 0x07ce: i2c_sense_sda_done */ 0x00f80131, /* 0x07d0: i2c_raise_scl */ 0x47f140f9, 0x37f00898, 0x5c21f501, /* 0x07dd: i2c_raise_scl_wait */ 0xe8e7f107, 0x7e21f403, 0x07a021f5, 0xb60901f4, 0x1bf40142, /* 0x07f1: i2c_raise_scl_done */ 0xf840fcef, /* 0x07f5: i2c_start */ 0xa021f500, 0x0d11f407, 0x07b821f5, 0xf40611f4, /* 0x0806: i2c_start_rep */ 0x37f0300e, 0x5c21f500, 0x0137f007, 0x077e21f5, 0xb60076bb, 0x50f90465, 0xbb046594, 0x50bd0256, 0xfc0475fd, 0xd021f550, 0x0464b607, /* 0x0833: i2c_start_send */ 0xf01f11f4, 0x21f50037, 0xe7f1077e, 0x21f41388, 0x0037f07e, 0x075c21f5, 0x1388e7f1, /* 0x084f: i2c_start_out */ 0xf87e21f4, /* 0x0851: i2c_stop */ 0x0037f000, 0x075c21f5, 0xf50037f0, 0xf1077e21, 0xf403e8e7, 0x37f07e21, 0x5c21f501, 0x88e7f107, 0x7e21f413, 0xf50137f0, 0xf1077e21, 0xf41388e7, 0x00f87e21, /* 0x0884: i2c_bitw */ 0x077e21f5, 0x03e8e7f1, 0xbb7e21f4, 0x65b60076, 0x9450f904, 0x56bb0465, 0xfd50bd02, 0x50fc0475, 0x07d021f5, 0xf40464b6, 0xe7f11811, 0x21f41388, 0x0037f07e, 0x075c21f5, 0x1388e7f1, /* 0x08c3: i2c_bitw_out */ 0xf87e21f4, /* 0x08c5: i2c_bitr */ 0x0137f000, 0x077e21f5, 0x03e8e7f1, 0xbb7e21f4, 0x65b60076, 0x9450f904, 0x56bb0465, 0xfd50bd02, 0x50fc0475, 0x07d021f5, 0xf40464b6, 0x21f51b11, 0x37f007b8, 0x5c21f500, 0x88e7f107, 0x7e21f413, 0xf4013cf0, /* 0x090a: i2c_bitr_done */ 0x00f80131, /* 0x090c: i2c_get_byte */ 0xf00057f0, /* 0x0912: i2c_get_byte_next */ 0x54b60847, 0x0076bb01, 0xf90465b6, 0x04659450, 0xbd0256bb, 0x0475fd50, 0x21f550fc, 0x64b608c5, 0x2b11f404, 0xb60553fd, 0x1bf40142, 0x0137f0d8, 0xb60076bb, 0x50f90465, 0xbb046594, 0x50bd0256, 0xfc0475fd, 0x8421f550, 0x0464b608, /* 0x095c: i2c_get_byte_done */ /* 0x095e: i2c_put_byte */ 0x47f000f8, /* 0x0961: i2c_put_byte_next */ 0x0142b608, 0xbb3854ff, 0x65b60076, 0x9450f904, 0x56bb0465, 0xfd50bd02, 0x50fc0475, 0x088421f5, 0xf40464b6, 0x46b03411, 0xd81bf400, 0xb60076bb, 0x50f90465, 0xbb046594, 0x50bd0256, 0xfc0475fd, 0xc521f550, 0x0464b608, 0xbb0f11f4, 0x36b00076, 0x061bf401, /* 0x09b7: i2c_put_byte_done */ 0xf80132f4, /* 0x09b9: i2c_addr */ 0x0076bb00, 0xf90465b6, 0x04659450, 0xbd0256bb, 0x0475fd50, 0x21f550fc, 0x64b607f5, 0x2911f404, 0x012ec3e7, 0xfd0134b6, 0x76bb0553, 0x0465b600, 0x659450f9, 0x0256bb04, 0x75fd50bd, 0xf550fc04, 0xb6095e21, /* 0x09fe: i2c_addr_done */ 0x00f80464, /* 0x0a00: i2c_acquire_addr */ 0xb6f8cec7, 0xe0b702e4, 0xee980d1c, /* 0x0a0f: i2c_acquire */ 0xf500f800, 0xf40a0021, 0xd9f00421, 0x4021f403, /* 0x0a1e: i2c_release */ 0x21f500f8, 0x21f40a00, 0x03daf004, 0xf84021f4, /* 0x0a2d: i2c_recv */ 0x0132f400, 0xb6f8c1c7, 0x16b00214, 0x3a1ff528, 0xf413a001, 0x0032980c, 0x0ccc13a0, 0xf4003198, 0xd0f90231, 0xd0f9e0f9, 0x000067f1, 0x100063f1, 0xbb016792, 0x65b60076, 0x9450f904, 0x56bb0465, 0xfd50bd02, 0x50fc0475, 0x0a0f21f5, 0xfc0464b6, 0x00d6b0d0, 0x00b31bf5, 0xbb0057f0, 0x65b60076, 0x9450f904, 0x56bb0465, 0xfd50bd02, 0x50fc0475, 0x09b921f5, 0xf50464b6, 0xc700d011, 0x76bbe0c5, 0x0465b600, 0x659450f9, 0x0256bb04, 0x75fd50bd, 0xf550fc04, 0xb6095e21, 0x11f50464, 0x57f000ad, 0x0076bb01, 0xf90465b6, 0x04659450, 0xbd0256bb, 0x0475fd50, 0x21f550fc, 0x64b609b9, 0x8a11f504, 0x0076bb00, 0xf90465b6, 0x04659450, 0xbd0256bb, 0x0475fd50, 0x21f550fc, 0x64b6090c, 0x6a11f404, 0xbbe05bcb, 0x65b60076, 0x9450f904, 0x56bb0465, 0xfd50bd02, 0x50fc0475, 0x085121f5, 0xb90464b6, 0x74bd025b, /* 0x0b33: i2c_recv_not_rd08 */ 0xb0430ef4, 0x1bf401d6, 0x0057f03d, 0x09b921f5, 0xc73311f4, 0x21f5e0c5, 0x11f4095e, 0x0057f029, 0x09b921f5, 0xc71f11f4, 0x21f5e0b5, 0x11f4095e, 0x5121f515, 0xc774bd08, 0x1bf408c5, 0x0232f409, /* 0x0b73: i2c_recv_not_wr08 */ /* 0x0b73: i2c_recv_done */ 0xc7030ef4, 0x21f5f8ce, 0xe0fc0a1e, 0x12f4d0fc, 0x027cb90a, 0x033621f5, /* 0x0b88: i2c_recv_exit */ /* 0x0b8a: i2c_init */ 0x00f800f8, /* 0x0b8c: test_recv */ 0x05d817f1, 0xcf0614b6, 0x10b60011, 0xd807f101, 0x0604b605, 0xbd0001d0, 0x00e7f104, 0x4fe3f1d9, 0x5621f513, /* 0x0bb3: test_init */ 0xf100f802, 0xf50800e7, 0xf8025621, /* 0x0bbd: idle_recv */ /* 0x0bbf: idle */ 0xf400f800, 0x17f10031, 0x14b605d4, 0x0011cf06, 0xf10110b6, 0xb605d407, 0x01d00604, /* 0x0bdb: idle_loop */ 0xf004bd00, 0x32f45817, /* 0x0be1: idle_proc */ /* 0x0be1: idle_proc_exec */ 0xb910f902, 0x21f5021e, 0x10fc033f, 0xf40911f4, 0x0ef40231, /* 0x0bf5: idle_proc_next */ 0x5810b6ef, 0xf4061fb8, 0x02f4e61b, 0x0028f4dd, 0x00bb0ef4, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, };
null
null
null
null
97,938
33,439
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
198,434
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * CAAM Protocol Data Block (PDB) definition header file * * Copyright 2008-2016 Freescale Semiconductor, Inc. * */ #ifndef CAAM_PDB_H #define CAAM_PDB_H #include "compat.h" /* * PDB- IPSec ESP Header Modification Options */ #define PDBHMO_ESP_DECAP_SHIFT 28 #define PDBHMO_ESP_ENCAP_SHIFT 28 /* * Encap and Decap - Decrement TTL (Hop Limit) - Based on the value of the * Options Byte IP version (IPvsn) field: * if IPv4, decrement the inner IP header TTL field (byte 8); * if IPv6 decrement the inner IP header Hop Limit field (byte 7). */ #define PDBHMO_ESP_DECAP_DEC_TTL (0x02 << PDBHMO_ESP_DECAP_SHIFT) #define PDBHMO_ESP_ENCAP_DEC_TTL (0x02 << PDBHMO_ESP_ENCAP_SHIFT) /* * Decap - DiffServ Copy - Copy the IPv4 TOS or IPv6 Traffic Class byte * from the outer IP header to the inner IP header. */ #define PDBHMO_ESP_DIFFSERV (0x01 << PDBHMO_ESP_DECAP_SHIFT) /* * Encap- Copy DF bit -if an IPv4 tunnel mode outer IP header is coming from * the PDB, copy the DF bit from the inner IP header to the outer IP header. */ #define PDBHMO_ESP_DFBIT (0x04 << PDBHMO_ESP_ENCAP_SHIFT) #define PDBNH_ESP_ENCAP_SHIFT 16 #define PDBNH_ESP_ENCAP_MASK (0xff << PDBNH_ESP_ENCAP_SHIFT) #define PDBHDRLEN_ESP_DECAP_SHIFT 16 #define PDBHDRLEN_MASK (0x0fff << PDBHDRLEN_ESP_DECAP_SHIFT) #define PDB_NH_OFFSET_SHIFT 8 #define PDB_NH_OFFSET_MASK (0xff << PDB_NH_OFFSET_SHIFT) /* * PDB - IPSec ESP Encap/Decap Options */ #define PDBOPTS_ESP_ARSNONE 0x00 /* no antireplay window */ #define PDBOPTS_ESP_ARS32 0x40 /* 32-entry antireplay window */ #define PDBOPTS_ESP_ARS128 0x80 /* 128-entry antireplay window */ #define PDBOPTS_ESP_ARS64 0xc0 /* 64-entry antireplay window */ #define PDBOPTS_ESP_ARS_MASK 0xc0 /* antireplay window mask */ #define PDBOPTS_ESP_IVSRC 0x20 /* IV comes from internal random gen */ #define PDBOPTS_ESP_ESN 0x10 /* extended sequence included */ #define PDBOPTS_ESP_OUTFMT 0x08 /* output only decapsulation (decap) */ #define PDBOPTS_ESP_IPHDRSRC 0x08 /* IP header comes from PDB (encap) */ #define PDBOPTS_ESP_INCIPHDR 0x04 /* Prepend IP header to output frame */ #define PDBOPTS_ESP_IPVSN 0x02 /* process IPv6 header */ #define PDBOPTS_ESP_AOFL 0x04 /* adjust out frame len (decap, SEC>=5.3)*/ #define PDBOPTS_ESP_TUNNEL 0x01 /* tunnel mode next-header byte */ #define PDBOPTS_ESP_IPV6 0x02 /* ip header version is V6 */ #define PDBOPTS_ESP_DIFFSERV 0x40 /* copy TOS/TC from inner iphdr */ #define PDBOPTS_ESP_UPDATE_CSUM 0x80 /* encap-update ip header checksum */ #define PDBOPTS_ESP_VERIFY_CSUM 0x20 /* decap-validate ip header checksum */ /* * General IPSec encap/decap PDB definitions */ /** * ipsec_encap_cbc - PDB part for IPsec CBC encapsulation * @iv: 16-byte array initialization vector */ struct ipsec_encap_cbc { u8 iv[16]; }; /** * ipsec_encap_ctr - PDB part for IPsec CTR encapsulation * @ctr_nonce: 4-byte array nonce * @ctr_initial: initial count constant * @iv: initialization vector */ struct ipsec_encap_ctr { u8 ctr_nonce[4]; u32 ctr_initial; u64 iv; }; /** * ipsec_encap_ccm - PDB part for IPsec CCM encapsulation * @salt: 3-byte array salt (lower 24 bits) * @ccm_opt: CCM algorithm options - MSB-LSB description: * b0_flags (8b) - CCM B0; use 0x5B for 8-byte ICV, 0x6B for 12-byte ICV, * 0x7B for 16-byte ICV (cf. RFC4309, RFC3610) * ctr_flags (8b) - counter flags; constant equal to 0x3 * ctr_initial (16b) - initial count constant * @iv: initialization vector */ struct ipsec_encap_ccm { u8 salt[4]; u32 ccm_opt; u64 iv; }; /** * ipsec_encap_gcm - PDB part for IPsec GCM encapsulation * @salt: 3-byte array salt (lower 24 bits) * @rsvd: reserved, do not use * @iv: initialization vector */ struct ipsec_encap_gcm { u8 salt[4]; u32 rsvd1; u64 iv; }; /** * ipsec_encap_pdb - PDB for IPsec encapsulation * @options: MSB-LSB description * hmo (header manipulation options) - 4b * reserved - 4b * next header - 8b * next header offset - 8b * option flags (depend on selected algorithm) - 8b * @seq_num_ext_hi: (optional) IPsec Extended Sequence Number (ESN) * @seq_num: IPsec sequence number * @spi: IPsec SPI (Security Parameters Index) * @ip_hdr_len: optional IP Header length (in bytes) * reserved - 16b * Opt. IP Hdr Len - 16b * @ip_hdr: optional IP Header content */ struct ipsec_encap_pdb { u32 options; u32 seq_num_ext_hi; u32 seq_num; union { struct ipsec_encap_cbc cbc; struct ipsec_encap_ctr ctr; struct ipsec_encap_ccm ccm; struct ipsec_encap_gcm gcm; }; u32 spi; u32 ip_hdr_len; u32 ip_hdr[0]; }; /** * ipsec_decap_cbc - PDB part for IPsec CBC decapsulation * @rsvd: reserved, do not use */ struct ipsec_decap_cbc { u32 rsvd[2]; }; /** * ipsec_decap_ctr - PDB part for IPsec CTR decapsulation * @ctr_nonce: 4-byte array nonce * @ctr_initial: initial count constant */ struct ipsec_decap_ctr { u8 ctr_nonce[4]; u32 ctr_initial; }; /** * ipsec_decap_ccm - PDB part for IPsec CCM decapsulation * @salt: 3-byte salt (lower 24 bits) * @ccm_opt: CCM algorithm options - MSB-LSB description: * b0_flags (8b) - CCM B0; use 0x5B for 8-byte ICV, 0x6B for 12-byte ICV, * 0x7B for 16-byte ICV (cf. RFC4309, RFC3610) * ctr_flags (8b) - counter flags; constant equal to 0x3 * ctr_initial (16b) - initial count constant */ struct ipsec_decap_ccm { u8 salt[4]; u32 ccm_opt; }; /** * ipsec_decap_gcm - PDB part for IPsec GCN decapsulation * @salt: 4-byte salt * @rsvd: reserved, do not use */ struct ipsec_decap_gcm { u8 salt[4]; u32 resvd; }; /** * ipsec_decap_pdb - PDB for IPsec decapsulation * @options: MSB-LSB description * hmo (header manipulation options) - 4b * IP header length - 12b * next header offset - 8b * option flags (depend on selected algorithm) - 8b * @seq_num_ext_hi: (optional) IPsec Extended Sequence Number (ESN) * @seq_num: IPsec sequence number * @anti_replay: Anti-replay window; size depends on ARS (option flags) */ struct ipsec_decap_pdb { u32 options; union { struct ipsec_decap_cbc cbc; struct ipsec_decap_ctr ctr; struct ipsec_decap_ccm ccm; struct ipsec_decap_gcm gcm; }; u32 seq_num_ext_hi; u32 seq_num; __be32 anti_replay[4]; }; /* * IPSec ESP Datapath Protocol Override Register (DPOVRD) */ struct ipsec_deco_dpovrd { #define IPSEC_ENCAP_DECO_DPOVRD_USE 0x80 u8 ovrd_ecn; u8 ip_hdr_len; u8 nh_offset; u8 next_header; /* reserved if decap */ }; /* * IEEE 802.11i WiFi Protocol Data Block */ #define WIFI_PDBOPTS_FCS 0x01 #define WIFI_PDBOPTS_AR 0x40 struct wifi_encap_pdb { u16 mac_hdr_len; u8 rsvd; u8 options; u8 iv_flags; u8 pri; u16 pn1; u32 pn2; u16 frm_ctrl_mask; u16 seq_ctrl_mask; u8 rsvd1[2]; u8 cnst; u8 key_id; u8 ctr_flags; u8 rsvd2; u16 ctr_init; }; struct wifi_decap_pdb { u16 mac_hdr_len; u8 rsvd; u8 options; u8 iv_flags; u8 pri; u16 pn1; u32 pn2; u16 frm_ctrl_mask; u16 seq_ctrl_mask; u8 rsvd1[4]; u8 ctr_flags; u8 rsvd2; u16 ctr_init; }; /* * IEEE 802.16 WiMAX Protocol Data Block */ #define WIMAX_PDBOPTS_FCS 0x01 #define WIMAX_PDBOPTS_AR 0x40 /* decap only */ struct wimax_encap_pdb { u8 rsvd[3]; u8 options; u32 nonce; u8 b0_flags; u8 ctr_flags; u16 ctr_init; /* begin DECO writeback region */ u32 pn; /* end DECO writeback region */ }; struct wimax_decap_pdb { u8 rsvd[3]; u8 options; u32 nonce; u8 iv_flags; u8 ctr_flags; u16 ctr_init; /* begin DECO writeback region */ u32 pn; u8 rsvd1[2]; u16 antireplay_len; u64 antireplay_scorecard; /* end DECO writeback region */ }; /* * IEEE 801.AE MacSEC Protocol Data Block */ #define MACSEC_PDBOPTS_FCS 0x01 #define MACSEC_PDBOPTS_AR 0x40 /* used in decap only */ struct macsec_encap_pdb { u16 aad_len; u8 rsvd; u8 options; u64 sci; u16 ethertype; u8 tci_an; u8 rsvd1; /* begin DECO writeback region */ u32 pn; /* end DECO writeback region */ }; struct macsec_decap_pdb { u16 aad_len; u8 rsvd; u8 options; u64 sci; u8 rsvd1[3]; /* begin DECO writeback region */ u8 antireplay_len; u32 pn; u64 antireplay_scorecard; /* end DECO writeback region */ }; /* * SSL/TLS/DTLS Protocol Data Blocks */ #define TLS_PDBOPTS_ARS32 0x40 #define TLS_PDBOPTS_ARS64 0xc0 #define TLS_PDBOPTS_OUTFMT 0x08 #define TLS_PDBOPTS_IV_WRTBK 0x02 /* 1.1/1.2/DTLS only */ #define TLS_PDBOPTS_EXP_RND_IV 0x01 /* 1.1/1.2/DTLS only */ struct tls_block_encap_pdb { u8 type; u8 version[2]; u8 options; u64 seq_num; u32 iv[4]; }; struct tls_stream_encap_pdb { u8 type; u8 version[2]; u8 options; u64 seq_num; u8 i; u8 j; u8 rsvd1[2]; }; struct dtls_block_encap_pdb { u8 type; u8 version[2]; u8 options; u16 epoch; u16 seq_num[3]; u32 iv[4]; }; struct tls_block_decap_pdb { u8 rsvd[3]; u8 options; u64 seq_num; u32 iv[4]; }; struct tls_stream_decap_pdb { u8 rsvd[3]; u8 options; u64 seq_num; u8 i; u8 j; u8 rsvd1[2]; }; struct dtls_block_decap_pdb { u8 rsvd[3]; u8 options; u16 epoch; u16 seq_num[3]; u32 iv[4]; u64 antireplay_scorecard; }; /* * SRTP Protocol Data Blocks */ #define SRTP_PDBOPTS_MKI 0x08 #define SRTP_PDBOPTS_AR 0x40 struct srtp_encap_pdb { u8 x_len; u8 mki_len; u8 n_tag; u8 options; u32 cnst0; u8 rsvd[2]; u16 cnst1; u16 salt[7]; u16 cnst2; u32 rsvd1; u32 roc; u32 opt_mki; }; struct srtp_decap_pdb { u8 x_len; u8 mki_len; u8 n_tag; u8 options; u32 cnst0; u8 rsvd[2]; u16 cnst1; u16 salt[7]; u16 cnst2; u16 rsvd1; u16 seq_num; u32 roc; u64 antireplay_scorecard; }; /* * DSA/ECDSA Protocol Data Blocks * Two of these exist: DSA-SIGN, and DSA-VERIFY. They are similar * except for the treatment of "w" for verify, "s" for sign, * and the placement of "a,b". */ #define DSA_PDB_SGF_SHIFT 24 #define DSA_PDB_SGF_MASK (0xff << DSA_PDB_SGF_SHIFT) #define DSA_PDB_SGF_Q (0x80 << DSA_PDB_SGF_SHIFT) #define DSA_PDB_SGF_R (0x40 << DSA_PDB_SGF_SHIFT) #define DSA_PDB_SGF_G (0x20 << DSA_PDB_SGF_SHIFT) #define DSA_PDB_SGF_W (0x10 << DSA_PDB_SGF_SHIFT) #define DSA_PDB_SGF_S (0x10 << DSA_PDB_SGF_SHIFT) #define DSA_PDB_SGF_F (0x08 << DSA_PDB_SGF_SHIFT) #define DSA_PDB_SGF_C (0x04 << DSA_PDB_SGF_SHIFT) #define DSA_PDB_SGF_D (0x02 << DSA_PDB_SGF_SHIFT) #define DSA_PDB_SGF_AB_SIGN (0x02 << DSA_PDB_SGF_SHIFT) #define DSA_PDB_SGF_AB_VERIFY (0x01 << DSA_PDB_SGF_SHIFT) #define DSA_PDB_L_SHIFT 7 #define DSA_PDB_L_MASK (0x3ff << DSA_PDB_L_SHIFT) #define DSA_PDB_N_MASK 0x7f struct dsa_sign_pdb { u32 sgf_ln; /* Use DSA_PDB_ defintions per above */ u8 *q; u8 *r; u8 *g; /* or Gx,y */ u8 *s; u8 *f; u8 *c; u8 *d; u8 *ab; /* ECC only */ u8 *u; }; struct dsa_verify_pdb { u32 sgf_ln; u8 *q; u8 *r; u8 *g; /* or Gx,y */ u8 *w; /* or Wx,y */ u8 *f; u8 *c; u8 *d; u8 *tmp; /* temporary data block */ u8 *ab; /* only used if ECC processing */ }; /* RSA Protocol Data Block */ #define RSA_PDB_SGF_SHIFT 28 #define RSA_PDB_E_SHIFT 12 #define RSA_PDB_E_MASK (0xFFF << RSA_PDB_E_SHIFT) #define RSA_PDB_D_SHIFT 12 #define RSA_PDB_D_MASK (0xFFF << RSA_PDB_D_SHIFT) #define RSA_PDB_SGF_F (0x8 << RSA_PDB_SGF_SHIFT) #define RSA_PDB_SGF_G (0x4 << RSA_PDB_SGF_SHIFT) #define RSA_PRIV_PDB_SGF_F (0x4 << RSA_PDB_SGF_SHIFT) #define RSA_PRIV_PDB_SGF_G (0x8 << RSA_PDB_SGF_SHIFT) #define RSA_PRIV_KEY_FRM_1 0 /** * RSA Encrypt Protocol Data Block * @sgf: scatter-gather field * @f_dma: dma address of input data * @g_dma: dma address of encrypted output data * @n_dma: dma address of RSA modulus * @e_dma: dma address of RSA public exponent * @f_len: length in octets of the input data */ struct rsa_pub_pdb { u32 sgf; dma_addr_t f_dma; dma_addr_t g_dma; dma_addr_t n_dma; dma_addr_t e_dma; u32 f_len; } __packed; /** * RSA Decrypt PDB - Private Key Form #1 * @sgf: scatter-gather field * @g_dma: dma address of encrypted input data * @f_dma: dma address of output data * @n_dma: dma address of RSA modulus * @d_dma: dma address of RSA private exponent */ struct rsa_priv_f1_pdb { u32 sgf; dma_addr_t g_dma; dma_addr_t f_dma; dma_addr_t n_dma; dma_addr_t d_dma; } __packed; #endif
null
null
null
null
106,781
2,502
null
train_val
1b0d3845b454eaaac0b2064c78926ca4d739a080
265,070
qemu
0
https://github.com/bonzini/qemu
2016-10-18 11:40:27+01:00
/* * Initial TCG Implementation for aarch64 * * Copyright (c) 2013 Huawei Technologies Duesseldorf GmbH * Written by Claudio Fontana * * This work is licensed under the terms of the GNU GPL, version 2 or * (at your option) any later version. * * See the COPYING file in the top-level directory for details. */ #ifndef AARCH64_TCG_TARGET_H #define AARCH64_TCG_TARGET_H #define TCG_TARGET_INSN_UNIT_SIZE 4 #define TCG_TARGET_TLB_DISPLACEMENT_BITS 24 #undef TCG_TARGET_STACK_GROWSUP typedef enum { TCG_REG_X0, TCG_REG_X1, TCG_REG_X2, TCG_REG_X3, TCG_REG_X4, TCG_REG_X5, TCG_REG_X6, TCG_REG_X7, TCG_REG_X8, TCG_REG_X9, TCG_REG_X10, TCG_REG_X11, TCG_REG_X12, TCG_REG_X13, TCG_REG_X14, TCG_REG_X15, TCG_REG_X16, TCG_REG_X17, TCG_REG_X18, TCG_REG_X19, TCG_REG_X20, TCG_REG_X21, TCG_REG_X22, TCG_REG_X23, TCG_REG_X24, TCG_REG_X25, TCG_REG_X26, TCG_REG_X27, TCG_REG_X28, TCG_REG_X29, TCG_REG_X30, /* X31 is either the stack pointer or zero, depending on context. */ TCG_REG_SP = 31, TCG_REG_XZR = 31, /* Aliases. */ TCG_REG_FP = TCG_REG_X29, TCG_REG_LR = TCG_REG_X30, TCG_AREG0 = TCG_REG_X19, } TCGReg; #define TCG_TARGET_NB_REGS 32 /* used for function call generation */ #define TCG_REG_CALL_STACK TCG_REG_SP #define TCG_TARGET_STACK_ALIGN 16 #define TCG_TARGET_CALL_ALIGN_ARGS 1 #define TCG_TARGET_CALL_STACK_OFFSET 0 /* optional instructions */ #define TCG_TARGET_HAS_div_i32 1 #define TCG_TARGET_HAS_rem_i32 1 #define TCG_TARGET_HAS_ext8s_i32 1 #define TCG_TARGET_HAS_ext16s_i32 1 #define TCG_TARGET_HAS_ext8u_i32 1 #define TCG_TARGET_HAS_ext16u_i32 1 #define TCG_TARGET_HAS_bswap16_i32 1 #define TCG_TARGET_HAS_bswap32_i32 1 #define TCG_TARGET_HAS_not_i32 1 #define TCG_TARGET_HAS_neg_i32 1 #define TCG_TARGET_HAS_rot_i32 1 #define TCG_TARGET_HAS_andc_i32 1 #define TCG_TARGET_HAS_orc_i32 1 #define TCG_TARGET_HAS_eqv_i32 1 #define TCG_TARGET_HAS_nand_i32 0 #define TCG_TARGET_HAS_nor_i32 0 #define TCG_TARGET_HAS_deposit_i32 1 #define TCG_TARGET_HAS_movcond_i32 1 #define TCG_TARGET_HAS_add2_i32 1 #define TCG_TARGET_HAS_sub2_i32 1 #define TCG_TARGET_HAS_mulu2_i32 0 #define TCG_TARGET_HAS_muls2_i32 0 #define TCG_TARGET_HAS_muluh_i32 0 #define TCG_TARGET_HAS_mulsh_i32 0 #define TCG_TARGET_HAS_extrl_i64_i32 0 #define TCG_TARGET_HAS_extrh_i64_i32 0 #define TCG_TARGET_HAS_div_i64 1 #define TCG_TARGET_HAS_rem_i64 1 #define TCG_TARGET_HAS_ext8s_i64 1 #define TCG_TARGET_HAS_ext16s_i64 1 #define TCG_TARGET_HAS_ext32s_i64 1 #define TCG_TARGET_HAS_ext8u_i64 1 #define TCG_TARGET_HAS_ext16u_i64 1 #define TCG_TARGET_HAS_ext32u_i64 1 #define TCG_TARGET_HAS_bswap16_i64 1 #define TCG_TARGET_HAS_bswap32_i64 1 #define TCG_TARGET_HAS_bswap64_i64 1 #define TCG_TARGET_HAS_not_i64 1 #define TCG_TARGET_HAS_neg_i64 1 #define TCG_TARGET_HAS_rot_i64 1 #define TCG_TARGET_HAS_andc_i64 1 #define TCG_TARGET_HAS_orc_i64 1 #define TCG_TARGET_HAS_eqv_i64 1 #define TCG_TARGET_HAS_nand_i64 0 #define TCG_TARGET_HAS_nor_i64 0 #define TCG_TARGET_HAS_deposit_i64 1 #define TCG_TARGET_HAS_movcond_i64 1 #define TCG_TARGET_HAS_add2_i64 1 #define TCG_TARGET_HAS_sub2_i64 1 #define TCG_TARGET_HAS_mulu2_i64 0 #define TCG_TARGET_HAS_muls2_i64 0 #define TCG_TARGET_HAS_muluh_i64 1 #define TCG_TARGET_HAS_mulsh_i64 1 static inline void flush_icache_range(uintptr_t start, uintptr_t stop) { __builtin___clear_cache((char *)start, (char *)stop); } #endif /* AARCH64_TCG_TARGET_H */
null
null
null
null
123,194
71,492
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
71,492
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright 2017 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 SERVICES_RESOURCE_COORDINATOR_PUBLIC_CPP_RESOURCE_COORDINATOR_INTERFACE_H_ #define SERVICES_RESOURCE_COORDINATOR_PUBLIC_CPP_RESOURCE_COORDINATOR_INTERFACE_H_ #include <stdint.h> #include "base/macros.h" #include "services/resource_coordinator/public/cpp/coordination_unit_id.h" #include "services/resource_coordinator/public/cpp/resource_coordinator_export.h" #include "services/resource_coordinator/public/mojom/coordination_unit_provider.mojom.h" #include "services/resource_coordinator/public/mojom/service_constants.mojom.h" #include "services/service_manager/public/cpp/connector.h" namespace resource_coordinator { template <class CoordinationUnitMojoPtr, class CoordinationUnitMojoRequest> class ResourceCoordinatorInterface { public: ResourceCoordinatorInterface() = default; virtual ~ResourceCoordinatorInterface() = default; void AddBinding(CoordinationUnitMojoRequest request) { if (!service_) return; service_->AddBinding(std::move(request)); } CoordinationUnitID id() const { return cu_id_; } const CoordinationUnitMojoPtr& service() const { return service_; } protected: virtual void ConnectToService(mojom::CoordinationUnitProviderPtr& provider, const CoordinationUnitID& cu_id) = 0; void ConnectToService(service_manager::Connector* connector, const CoordinationUnitID& cu_id) { if (!connector) return; cu_id_ = cu_id; mojom::CoordinationUnitProviderPtr provider; connector->BindInterface(mojom::kServiceName, mojo::MakeRequest(&provider)); ConnectToService(provider, cu_id); } CoordinationUnitMojoPtr service_; CoordinationUnitID cu_id_; private: DISALLOW_COPY_AND_ASSIGN(ResourceCoordinatorInterface); }; } // namespace resource_coordinator #endif // SERVICES_RESOURCE_COORDINATOR_PUBLIC_CPP_RESOURCE_COORDINATOR_INTERFACE_H_
null
null
null
null
68,355
38,245
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
203,240
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* Measure nanosleep timer latency * by: john stultz (john.stultz@linaro.org) * (C) Copyright Linaro 2013 * Licensed under the GPLv2 * * To build: * $ gcc nsleep-lat.c -o nsleep-lat -lrt * * 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. */ #include <stdio.h> #include <stdlib.h> #include <time.h> #include <sys/time.h> #include <sys/timex.h> #include <string.h> #include <signal.h> #ifdef KTEST #include "../kselftest.h" #else static inline int ksft_exit_pass(void) { exit(0); } static inline int ksft_exit_fail(void) { exit(1); } #endif #define NSEC_PER_SEC 1000000000ULL #define UNRESONABLE_LATENCY 40000000 /* 40ms in nanosecs */ #define CLOCK_REALTIME 0 #define CLOCK_MONOTONIC 1 #define CLOCK_PROCESS_CPUTIME_ID 2 #define CLOCK_THREAD_CPUTIME_ID 3 #define CLOCK_MONOTONIC_RAW 4 #define CLOCK_REALTIME_COARSE 5 #define CLOCK_MONOTONIC_COARSE 6 #define CLOCK_BOOTTIME 7 #define CLOCK_REALTIME_ALARM 8 #define CLOCK_BOOTTIME_ALARM 9 #define CLOCK_HWSPECIFIC 10 #define CLOCK_TAI 11 #define NR_CLOCKIDS 12 #define UNSUPPORTED 0xf00f char *clockstring(int clockid) { switch (clockid) { case CLOCK_REALTIME: return "CLOCK_REALTIME"; case CLOCK_MONOTONIC: return "CLOCK_MONOTONIC"; case CLOCK_PROCESS_CPUTIME_ID: return "CLOCK_PROCESS_CPUTIME_ID"; case CLOCK_THREAD_CPUTIME_ID: return "CLOCK_THREAD_CPUTIME_ID"; case CLOCK_MONOTONIC_RAW: return "CLOCK_MONOTONIC_RAW"; case CLOCK_REALTIME_COARSE: return "CLOCK_REALTIME_COARSE"; case CLOCK_MONOTONIC_COARSE: return "CLOCK_MONOTONIC_COARSE"; case CLOCK_BOOTTIME: return "CLOCK_BOOTTIME"; case CLOCK_REALTIME_ALARM: return "CLOCK_REALTIME_ALARM"; case CLOCK_BOOTTIME_ALARM: return "CLOCK_BOOTTIME_ALARM"; case CLOCK_TAI: return "CLOCK_TAI"; }; return "UNKNOWN_CLOCKID"; } struct timespec timespec_add(struct timespec ts, unsigned long long ns) { ts.tv_nsec += ns; while (ts.tv_nsec >= NSEC_PER_SEC) { ts.tv_nsec -= NSEC_PER_SEC; ts.tv_sec++; } return ts; } long long timespec_sub(struct timespec a, struct timespec b) { long long ret = NSEC_PER_SEC * b.tv_sec + b.tv_nsec; ret -= NSEC_PER_SEC * a.tv_sec + a.tv_nsec; return ret; } int nanosleep_lat_test(int clockid, long long ns) { struct timespec start, end, target; long long latency = 0; int i, count; target.tv_sec = ns/NSEC_PER_SEC; target.tv_nsec = ns%NSEC_PER_SEC; if (clock_gettime(clockid, &start)) return UNSUPPORTED; if (clock_nanosleep(clockid, 0, &target, NULL)) return UNSUPPORTED; count = 10; /* First check relative latency */ clock_gettime(clockid, &start); for (i = 0; i < count; i++) clock_nanosleep(clockid, 0, &target, NULL); clock_gettime(clockid, &end); if (((timespec_sub(start, end)/count)-ns) > UNRESONABLE_LATENCY) { printf("Large rel latency: %lld ns :", (timespec_sub(start, end)/count)-ns); return -1; } /* Next check absolute latency */ for (i = 0; i < count; i++) { clock_gettime(clockid, &start); target = timespec_add(start, ns); clock_nanosleep(clockid, TIMER_ABSTIME, &target, NULL); clock_gettime(clockid, &end); latency += timespec_sub(target, end); } if (latency/count > UNRESONABLE_LATENCY) { printf("Large abs latency: %lld ns :", latency/count); return -1; } return 0; } int main(int argc, char **argv) { long long length; int clockid, ret; for (clockid = CLOCK_REALTIME; clockid < NR_CLOCKIDS; clockid++) { /* Skip cputime clockids since nanosleep won't increment cputime */ if (clockid == CLOCK_PROCESS_CPUTIME_ID || clockid == CLOCK_THREAD_CPUTIME_ID || clockid == CLOCK_HWSPECIFIC) continue; printf("nsleep latency %-26s ", clockstring(clockid)); length = 10; while (length <= (NSEC_PER_SEC * 10)) { ret = nanosleep_lat_test(clockid, length); if (ret) break; length *= 100; } if (ret == UNSUPPORTED) { printf("[UNSUPPORTED]\n"); continue; } if (ret < 0) { printf("[FAILED]\n"); return ksft_exit_fail(); } printf("[OK]\n"); } return ksft_exit_pass(); }
null
null
null
null
111,587
46,538
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
46,538
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/system/overview/overview_button_tray.h" #include "ash/metrics/user_metrics_recorder.h" #include "ash/resources/vector_icons/vector_icons.h" #include "ash/session/session_controller.h" #include "ash/shelf/shelf_constants.h" #include "ash/shell.h" #include "ash/strings/grit/ash_strings.h" #include "ash/system/tray/tray_constants.h" #include "ash/system/tray/tray_container.h" #include "ash/wm/mru_window_tracker.h" #include "ash/wm/overview/window_selector_controller.h" #include "ash/wm/splitview/split_view_controller.h" #include "ash/wm/tablet_mode/tablet_mode_controller.h" #include "ash/wm/window_state.h" #include "base/metrics/user_metrics.h" #include "base/metrics/user_metrics_action.h" #include "ui/base/l10n/l10n_util.h" #include "ui/gfx/paint_vector_icon.h" #include "ui/views/border.h" #include "ui/views/controls/image_view.h" #include "ui/wm/core/window_util.h" namespace ash { constexpr base::TimeDelta OverviewButtonTray::kDoubleTapThresholdMs; OverviewButtonTray::OverviewButtonTray(Shelf* shelf) : TrayBackgroundView(shelf), icon_(new views::ImageView()), scoped_session_observer_(this) { SetInkDropMode(InkDropMode::ON); gfx::ImageSkia image = gfx::CreateVectorIcon(kShelfOverviewIcon, kShelfIconColor); icon_->SetImage(image); const int vertical_padding = (kTrayItemSize - image.height()) / 2; const int horizontal_padding = (kTrayItemSize - image.width()) / 2; icon_->SetBorder(views::CreateEmptyBorder( gfx::Insets(vertical_padding, horizontal_padding))); tray_container()->AddChildView(icon_); // Since OverviewButtonTray is located on the rightmost position of a // horizontal shelf, no separator is required. set_separator_visibility(false); Shell::Get()->AddShellObserver(this); Shell::Get()->tablet_mode_controller()->AddObserver(this); } OverviewButtonTray::~OverviewButtonTray() { if (Shell::Get()->tablet_mode_controller()) Shell::Get()->tablet_mode_controller()->RemoveObserver(this); Shell::Get()->RemoveShellObserver(this); } void OverviewButtonTray::UpdateAfterLoginStatusChange(LoginStatus status) { UpdateIconVisibility(); } void OverviewButtonTray::OnGestureEvent(ui::GestureEvent* event) { Button::OnGestureEvent(event); if (event->type() == ui::ET_GESTURE_LONG_PRESS) { Shell::Get()->window_selector_controller()->OnOverviewButtonTrayLongPressed( event->location()); } } bool OverviewButtonTray::PerformAction(const ui::Event& event) { DCHECK(event.type() == ui::ET_MOUSE_RELEASED || event.type() == ui::ET_GESTURE_TAP); if (last_press_event_time_ && event.time_stamp() - last_press_event_time_.value() < kDoubleTapThresholdMs) { // Second taps should not be processed outside of overview mode. (First // taps should be outside of overview). DCHECK(Shell::Get()->window_selector_controller()->IsSelecting()); base::RecordAction(base::UserMetricsAction("Tablet_QuickSwitch")); // Build mru window list. Use cycle as it excludes some windows we are not // interested in such as transient children. MruWindowTracker::WindowList mru_window_list = Shell::Get()->mru_window_tracker()->BuildWindowForCycleList(); // Switch to the second most recently used window (most recent is the // current window) if it exists, unless splitview mode is active. if (mru_window_list.size() > 1u) { aura::Window* new_active_window = mru_window_list[1]; // In splitview mode, quick switch will only affect the windows on the non // default side. The window which was dragged to either side to begin // splitview will remain untouched. Skip that window if it appears in the // mru list. SplitViewController* split_view_controller = Shell::Get()->split_view_controller(); if (split_view_controller->IsSplitViewModeActive() && mru_window_list.size() > 2u) { if (mru_window_list[0] == split_view_controller->GetDefaultSnappedWindow() || mru_window_list[1] == split_view_controller->GetDefaultSnappedWindow()) { new_active_window = mru_window_list[2]; } } AnimateInkDrop(views::InkDropState::DEACTIVATED, nullptr); wm::GetWindowState(new_active_window)->Activate(); last_press_event_time_ = base::nullopt; return true; } } // If not in overview mode record the time of this tap. A subsequent tap will // be checked against this to see if we should quick switch. last_press_event_time_ = Shell::Get()->window_selector_controller()->IsSelecting() ? base::nullopt : base::make_optional(event.time_stamp()); WindowSelectorController* controller = Shell::Get()->window_selector_controller(); // Note: Toggling overview mode will fail if there is no window to show, the // screen is locked, a modal dialog is open or is running in kiosk app // session. bool performed = controller->ToggleOverview(); Shell::Get()->metrics()->RecordUserMetricsAction(UMA_TRAY_OVERVIEW); return performed; } void OverviewButtonTray::OnSessionStateChanged( session_manager::SessionState state) { UpdateIconVisibility(); } void OverviewButtonTray::OnTabletModeStarted() { UpdateIconVisibility(); } void OverviewButtonTray::OnTabletModeEnded() { UpdateIconVisibility(); } void OverviewButtonTray::OnOverviewModeStarting() { SetIsActive(true); } void OverviewButtonTray::OnOverviewModeEnded() { SetIsActive(false); } void OverviewButtonTray::ClickedOutsideBubble() {} base::string16 OverviewButtonTray::GetAccessibleNameForTray() { return l10n_util::GetStringUTF16(IDS_ASH_OVERVIEW_BUTTON_ACCESSIBLE_NAME); } void OverviewButtonTray::HideBubbleWithView( const views::TrayBubbleView* bubble_view) { // This class has no bubbles to hide. } void OverviewButtonTray::UpdateIconVisibility() { // The visibility of the OverviewButtonTray has diverged from // WindowSelectorController::CanSelect. The visibility of the button should // not change during transient times in which CanSelect is false. Such as when // a modal dialog is present. SessionController* session_controller = Shell::Get()->session_controller(); Shell* shell = Shell::Get(); SetVisible( shell->tablet_mode_controller()->IsTabletModeWindowManagerEnabled() && session_controller->GetSessionState() == session_manager::SessionState::ACTIVE && !session_controller->IsRunningInAppMode()); } } // namespace ash
null
null
null
null
43,401
27,852
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
192,847
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * GPL HEADER START * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 only, * as published by the Free Software Foundation. * * This 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 version 2 for more details (a copy is included * in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU General Public License * version 2 along with this program; If not, see * http://www.gnu.org/licenses/gpl-2.0.html * * GPL HEADER END */ /* * Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved. * Use is subject to license terms. * * Copyright (c) 2012, 2015, Intel Corporation. */ /* * This file is part of Lustre, http://www.lustre.org/ * Lustre is a trademark of Seagate, Inc. */ #define DEBUG_SUBSYSTEM S_LNET #include <linux/if.h> #include <linux/in.h> #include <linux/net.h> #include <linux/file.h> #include <linux/pagemap.h> /* For sys_open & sys_close */ #include <linux/syscalls.h> #include <net/sock.h> #include "../../include/linux/libcfs/libcfs.h" #include "../../include/linux/lnet/lib-lnet.h" static int kernel_sock_unlocked_ioctl(struct file *filp, int cmd, unsigned long arg) { mm_segment_t oldfs = get_fs(); int err; set_fs(KERNEL_DS); err = filp->f_op->unlocked_ioctl(filp, cmd, arg); set_fs(oldfs); return err; } static int lnet_sock_ioctl(int cmd, unsigned long arg) { struct file *sock_filp; struct socket *sock; int rc; rc = sock_create(PF_INET, SOCK_STREAM, 0, &sock); if (rc) { CERROR("Can't create socket: %d\n", rc); return rc; } sock_filp = sock_alloc_file(sock, 0, NULL); if (IS_ERR(sock_filp)) { sock_release(sock); rc = PTR_ERR(sock_filp); goto out; } rc = kernel_sock_unlocked_ioctl(sock_filp, cmd, arg); fput(sock_filp); out: return rc; } int lnet_ipif_query(char *name, int *up, __u32 *ip, __u32 *mask) { struct ifreq ifr; int nob; int rc; __u32 val; nob = strnlen(name, IFNAMSIZ); if (nob == IFNAMSIZ) { CERROR("Interface name %s too long\n", name); return -EINVAL; } BUILD_BUG_ON(sizeof(ifr.ifr_name) < IFNAMSIZ); if (strlen(name) > sizeof(ifr.ifr_name) - 1) return -E2BIG; strncpy(ifr.ifr_name, name, sizeof(ifr.ifr_name)); rc = lnet_sock_ioctl(SIOCGIFFLAGS, (unsigned long)&ifr); if (rc) { CERROR("Can't get flags for interface %s\n", name); return rc; } if (!(ifr.ifr_flags & IFF_UP)) { CDEBUG(D_NET, "Interface %s down\n", name); *up = 0; *ip = *mask = 0; return 0; } *up = 1; if (strlen(name) > sizeof(ifr.ifr_name) - 1) return -E2BIG; strncpy(ifr.ifr_name, name, sizeof(ifr.ifr_name)); ifr.ifr_addr.sa_family = AF_INET; rc = lnet_sock_ioctl(SIOCGIFADDR, (unsigned long)&ifr); if (rc) { CERROR("Can't get IP address for interface %s\n", name); return rc; } val = ((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr.s_addr; *ip = ntohl(val); if (strlen(name) > sizeof(ifr.ifr_name) - 1) return -E2BIG; strncpy(ifr.ifr_name, name, sizeof(ifr.ifr_name)); ifr.ifr_addr.sa_family = AF_INET; rc = lnet_sock_ioctl(SIOCGIFNETMASK, (unsigned long)&ifr); if (rc) { CERROR("Can't get netmask for interface %s\n", name); return rc; } val = ((struct sockaddr_in *)&ifr.ifr_netmask)->sin_addr.s_addr; *mask = ntohl(val); return 0; } EXPORT_SYMBOL(lnet_ipif_query); int lnet_ipif_enumerate(char ***namesp) { /* Allocate and fill in 'names', returning # interfaces/error */ char **names; int toobig; int nalloc; int nfound; struct ifreq *ifr; struct ifconf ifc; int rc; int nob; int i; nalloc = 16; /* first guess at max interfaces */ toobig = 0; for (;;) { if (nalloc * sizeof(*ifr) > PAGE_SIZE) { toobig = 1; nalloc = PAGE_SIZE / sizeof(*ifr); CWARN("Too many interfaces: only enumerating first %d\n", nalloc); } LIBCFS_ALLOC(ifr, nalloc * sizeof(*ifr)); if (!ifr) { CERROR("ENOMEM enumerating up to %d interfaces\n", nalloc); rc = -ENOMEM; goto out0; } ifc.ifc_buf = (char *)ifr; ifc.ifc_len = nalloc * sizeof(*ifr); rc = lnet_sock_ioctl(SIOCGIFCONF, (unsigned long)&ifc); if (rc < 0) { CERROR("Error %d enumerating interfaces\n", rc); goto out1; } LASSERT(!rc); nfound = ifc.ifc_len / sizeof(*ifr); LASSERT(nfound <= nalloc); if (nfound < nalloc || toobig) break; LIBCFS_FREE(ifr, nalloc * sizeof(*ifr)); nalloc *= 2; } if (!nfound) goto out1; LIBCFS_ALLOC(names, nfound * sizeof(*names)); if (!names) { rc = -ENOMEM; goto out1; } for (i = 0; i < nfound; i++) { nob = strnlen(ifr[i].ifr_name, IFNAMSIZ); if (nob == IFNAMSIZ) { /* no space for terminating NULL */ CERROR("interface name %.*s too long (%d max)\n", nob, ifr[i].ifr_name, IFNAMSIZ); rc = -ENAMETOOLONG; goto out2; } LIBCFS_ALLOC(names[i], IFNAMSIZ); if (!names[i]) { rc = -ENOMEM; goto out2; } memcpy(names[i], ifr[i].ifr_name, nob); names[i][nob] = 0; } *namesp = names; rc = nfound; out2: if (rc < 0) lnet_ipif_free_enumeration(names, nfound); out1: LIBCFS_FREE(ifr, nalloc * sizeof(*ifr)); out0: return rc; } EXPORT_SYMBOL(lnet_ipif_enumerate); void lnet_ipif_free_enumeration(char **names, int n) { int i; LASSERT(n > 0); for (i = 0; i < n && names[i]; i++) LIBCFS_FREE(names[i], IFNAMSIZ); LIBCFS_FREE(names, n * sizeof(*names)); } EXPORT_SYMBOL(lnet_ipif_free_enumeration); int lnet_sock_write(struct socket *sock, void *buffer, int nob, int timeout) { int rc; long jiffies_left = timeout * msecs_to_jiffies(MSEC_PER_SEC); unsigned long then; struct timeval tv; struct kvec iov = { .iov_base = buffer, .iov_len = nob }; struct msghdr msg = {NULL,}; LASSERT(nob > 0); /* * Caller may pass a zero timeout if she thinks the socket buffer is * empty enough to take the whole message immediately */ iov_iter_kvec(&msg.msg_iter, WRITE | ITER_KVEC, &iov, 1, nob); for (;;) { msg.msg_flags = !timeout ? MSG_DONTWAIT : 0; if (timeout) { /* Set send timeout to remaining time */ jiffies_to_timeval(jiffies_left, &tv); rc = kernel_setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, (char *)&tv, sizeof(tv)); if (rc) { CERROR("Can't set socket send timeout %ld.%06d: %d\n", (long)tv.tv_sec, (int)tv.tv_usec, rc); return rc; } } then = jiffies; rc = kernel_sendmsg(sock, &msg, &iov, 1, nob); jiffies_left -= jiffies - then; if (rc < 0) return rc; if (!rc) { CERROR("Unexpected zero rc\n"); return -ECONNABORTED; } if (!msg_data_left(&msg)) break; if (jiffies_left <= 0) return -EAGAIN; } return 0; } EXPORT_SYMBOL(lnet_sock_write); int lnet_sock_read(struct socket *sock, void *buffer, int nob, int timeout) { int rc; long jiffies_left = timeout * msecs_to_jiffies(MSEC_PER_SEC); unsigned long then; struct timeval tv; LASSERT(nob > 0); LASSERT(jiffies_left > 0); for (;;) { struct kvec iov = { .iov_base = buffer, .iov_len = nob }; struct msghdr msg = { .msg_flags = 0 }; /* Set receive timeout to remaining time */ jiffies_to_timeval(jiffies_left, &tv); rc = kernel_setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(tv)); if (rc) { CERROR("Can't set socket recv timeout %ld.%06d: %d\n", (long)tv.tv_sec, (int)tv.tv_usec, rc); return rc; } then = jiffies; rc = kernel_recvmsg(sock, &msg, &iov, 1, nob, 0); jiffies_left -= jiffies - then; if (rc < 0) return rc; if (!rc) return -ECONNRESET; buffer = ((char *)buffer) + rc; nob -= rc; if (!nob) return 0; if (jiffies_left <= 0) return -ETIMEDOUT; } } EXPORT_SYMBOL(lnet_sock_read); static int lnet_sock_create(struct socket **sockp, int *fatal, __u32 local_ip, int local_port) { struct sockaddr_in locaddr; struct socket *sock; int rc; int option; /* All errors are fatal except bind failure if the port is in use */ *fatal = 1; rc = sock_create(PF_INET, SOCK_STREAM, 0, &sock); *sockp = sock; if (rc) { CERROR("Can't create socket: %d\n", rc); return rc; } option = 1; rc = kernel_setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *)&option, sizeof(option)); if (rc) { CERROR("Can't set SO_REUSEADDR for socket: %d\n", rc); goto failed; } if (local_ip || local_port) { memset(&locaddr, 0, sizeof(locaddr)); locaddr.sin_family = AF_INET; locaddr.sin_port = htons(local_port); if (!local_ip) locaddr.sin_addr.s_addr = htonl(INADDR_ANY); else locaddr.sin_addr.s_addr = htonl(local_ip); rc = kernel_bind(sock, (struct sockaddr *)&locaddr, sizeof(locaddr)); if (rc == -EADDRINUSE) { CDEBUG(D_NET, "Port %d already in use\n", local_port); *fatal = 0; goto failed; } if (rc) { CERROR("Error trying to bind to port %d: %d\n", local_port, rc); goto failed; } } return 0; failed: sock_release(sock); return rc; } int lnet_sock_setbuf(struct socket *sock, int txbufsize, int rxbufsize) { int option; int rc; if (txbufsize) { option = txbufsize; rc = kernel_setsockopt(sock, SOL_SOCKET, SO_SNDBUF, (char *)&option, sizeof(option)); if (rc) { CERROR("Can't set send buffer %d: %d\n", option, rc); return rc; } } if (rxbufsize) { option = rxbufsize; rc = kernel_setsockopt(sock, SOL_SOCKET, SO_RCVBUF, (char *)&option, sizeof(option)); if (rc) { CERROR("Can't set receive buffer %d: %d\n", option, rc); return rc; } } return 0; } EXPORT_SYMBOL(lnet_sock_setbuf); int lnet_sock_getaddr(struct socket *sock, bool remote, __u32 *ip, int *port) { struct sockaddr_in sin; int len = sizeof(sin); int rc; if (remote) rc = kernel_getpeername(sock, (struct sockaddr *)&sin, &len); else rc = kernel_getsockname(sock, (struct sockaddr *)&sin, &len); if (rc) { CERROR("Error %d getting sock %s IP/port\n", rc, remote ? "peer" : "local"); return rc; } if (ip) *ip = ntohl(sin.sin_addr.s_addr); if (port) *port = ntohs(sin.sin_port); return 0; } EXPORT_SYMBOL(lnet_sock_getaddr); int lnet_sock_getbuf(struct socket *sock, int *txbufsize, int *rxbufsize) { if (txbufsize) *txbufsize = sock->sk->sk_sndbuf; if (rxbufsize) *rxbufsize = sock->sk->sk_rcvbuf; return 0; } EXPORT_SYMBOL(lnet_sock_getbuf); int lnet_sock_listen(struct socket **sockp, __u32 local_ip, int local_port, int backlog) { int fatal; int rc; rc = lnet_sock_create(sockp, &fatal, local_ip, local_port); if (rc) { if (!fatal) CERROR("Can't create socket: port %d already in use\n", local_port); return rc; } rc = kernel_listen(*sockp, backlog); if (!rc) return 0; CERROR("Can't set listen backlog %d: %d\n", backlog, rc); sock_release(*sockp); return rc; } int lnet_sock_accept(struct socket **newsockp, struct socket *sock) { wait_queue_t wait; struct socket *newsock; int rc; /* * XXX this should add a ref to sock->ops->owner, if * TCP could be a module */ rc = sock_create_lite(PF_PACKET, sock->type, IPPROTO_TCP, &newsock); if (rc) { CERROR("Can't allocate socket\n"); return rc; } newsock->ops = sock->ops; rc = sock->ops->accept(sock, newsock, O_NONBLOCK, false); if (rc == -EAGAIN) { /* Nothing ready, so wait for activity */ init_waitqueue_entry(&wait, current); add_wait_queue(sk_sleep(sock->sk), &wait); set_current_state(TASK_INTERRUPTIBLE); schedule(); remove_wait_queue(sk_sleep(sock->sk), &wait); rc = sock->ops->accept(sock, newsock, O_NONBLOCK, false); } if (rc) goto failed; *newsockp = newsock; return 0; failed: sock_release(newsock); return rc; } int lnet_sock_connect(struct socket **sockp, int *fatal, __u32 local_ip, int local_port, __u32 peer_ip, int peer_port) { struct sockaddr_in srvaddr; int rc; rc = lnet_sock_create(sockp, fatal, local_ip, local_port); if (rc) return rc; memset(&srvaddr, 0, sizeof(srvaddr)); srvaddr.sin_family = AF_INET; srvaddr.sin_port = htons(peer_port); srvaddr.sin_addr.s_addr = htonl(peer_ip); rc = kernel_connect(*sockp, (struct sockaddr *)&srvaddr, sizeof(srvaddr), 0); if (!rc) return 0; /* * EADDRNOTAVAIL probably means we're already connected to the same * peer/port on the same local port on a differently typed * connection. Let our caller retry with a different local * port... */ *fatal = !(rc == -EADDRNOTAVAIL); CDEBUG_LIMIT(*fatal ? D_NETERROR : D_NET, "Error %d connecting %pI4h/%d -> %pI4h/%d\n", rc, &local_ip, local_port, &peer_ip, peer_port); sock_release(*sockp); return rc; }
null
null
null
null
101,194
30,138
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
30,138
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
/* * Copyright (C) 2012 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef THIRD_PARTY_BLINK_PUBLIC_WEB_WEB_HIT_TEST_RESULT_H_ #define THIRD_PARTY_BLINK_PUBLIC_WEB_WEB_HIT_TEST_RESULT_H_ #include "third_party/blink/public/platform/web_private_ptr.h" namespace blink { class HitTestResult; class WebElement; class WebHitTestResultPrivate; class WebNode; class WebURL; struct WebPoint; // Properties of a hit test result, i.e. properties of the nodes at a given // point (the hit point) on the page. Both urls may be populated at the same // time, for example in the instance of an <img> inside an <a>. class WebHitTestResult { public: WebHitTestResult() = default; WebHitTestResult(const WebHitTestResult& info) { Assign(info); } ~WebHitTestResult() { Reset(); } BLINK_EXPORT void Assign(const WebHitTestResult&); BLINK_EXPORT void Reset(); BLINK_EXPORT bool IsNull() const; // The node that was hit (only one for point-based tests). BLINK_EXPORT WebNode GetNode() const; // Coordinates of the point that was hit. Relative to the node. BLINK_EXPORT WebPoint LocalPoint() const; // If a link (eg. anchor or area tag) is hit, return the element. // Return null otheriwse. BLINK_EXPORT WebElement UrlElement() const; // If an image is hit, return the image source. Return empty otherwise. BLINK_EXPORT WebURL AbsoluteImageURL() const; // If an link is hit, return the link url source. Return empty otherwise. BLINK_EXPORT WebURL AbsoluteLinkURL() const; // Return whether an editable input element was hit. BLINK_EXPORT bool IsContentEditable() const; #if INSIDE_BLINK BLINK_EXPORT WebHitTestResult(const HitTestResult&); BLINK_EXPORT WebHitTestResult& operator=(const HitTestResult&); #endif protected: WebPrivatePtr<WebHitTestResultPrivate> private_; }; } // namespace blink #endif
null
null
null
null
27,001
28,864
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
193,859
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * Copyright (c) 2010 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. * * The full GNU General Public License is included in this distribution in * the file called "COPYING". */ void ips_link_to_i915_driver(void);
null
null
null
null
102,206
39,570
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
39,570
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
/* * Copyright (C) 2011 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. * * 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 "third_party/blink/public/platform/modules/indexeddb/web_idb_key.h" #include "third_party/blink/renderer/modules/indexeddb/idb_key.h" namespace blink { size_t WebIDBKeyArrayView::size() const { return private_->Array().size(); } WebIDBKeyView WebIDBKeyArrayView::operator[](size_t index) const { return WebIDBKeyView(private_->Array()[index].get()); } WebIDBKeyType WebIDBKeyView::KeyType() const { if (!private_) return kWebIDBKeyTypeNull; return static_cast<WebIDBKeyType>(private_->GetType()); } bool WebIDBKeyView::IsValid() const { if (!private_) return false; return private_->IsValid(); } WebData WebIDBKeyView::Binary() const { return private_->Binary(); } WebString WebIDBKeyView::String() const { return private_->GetString(); } double WebIDBKeyView::Date() const { return private_->Date(); } double WebIDBKeyView::Number() const { return private_->Number(); } WebIDBKey WebIDBKey::CreateArray(WebVector<WebIDBKey> array) { IDBKey::KeyArray keys; keys.ReserveCapacity(array.size()); for (WebIDBKey& key : array) { DCHECK(key.View().KeyType() != kWebIDBKeyTypeNull); keys.emplace_back(key.ReleaseIdbKey()); } return WebIDBKey(IDBKey::CreateArray(std::move(keys))); } WebIDBKey WebIDBKey::CreateBinary(const WebData& binary) { return WebIDBKey(IDBKey::CreateBinary(binary)); } WebIDBKey WebIDBKey::CreateString(const WebString& string) { return WebIDBKey(IDBKey::CreateString(string)); } WebIDBKey WebIDBKey::CreateDate(double date) { return WebIDBKey(IDBKey::CreateDate(date)); } WebIDBKey WebIDBKey::CreateNumber(double number) { return WebIDBKey(IDBKey::CreateNumber(number)); } WebIDBKey WebIDBKey::CreateInvalid() { return WebIDBKey(IDBKey::CreateInvalid()); } WebIDBKey::WebIDBKey() noexcept = default; WebIDBKey::WebIDBKey(WebIDBKey&&) noexcept = default; WebIDBKey& WebIDBKey::operator=(WebIDBKey&&) noexcept = default; WebIDBKey::~WebIDBKey() noexcept = default; WebIDBKey::WebIDBKey(std::unique_ptr<IDBKey> idb_key) noexcept : private_(std::move(idb_key)) {} WebIDBKey& WebIDBKey::operator=(std::unique_ptr<IDBKey> idb_key) noexcept { private_ = std::move(idb_key); return *this; } } // namespace blink
null
null
null
null
36,433
44,095
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
44,095
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// 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 "ppapi/cpp/view.h" #include "ppapi/c/ppb_view.h" #include "ppapi/cpp/module_impl.h" namespace pp { namespace { template <> const char* interface_name<PPB_View_1_0>() { return PPB_VIEW_INTERFACE_1_0; } template <> const char* interface_name<PPB_View_1_1>() { return PPB_VIEW_INTERFACE_1_1; } template <> const char* interface_name<PPB_View_1_2>() { return PPB_VIEW_INTERFACE_1_2; } } // namespace View::View() : Resource() { } View::View(PP_Resource view_resource) : Resource(view_resource) { } Rect View::GetRect() const { PP_Rect out; if (has_interface<PPB_View_1_2>()) { if (PP_ToBool(get_interface<PPB_View_1_2>()->GetRect(pp_resource(), &out))) return Rect(out); } else if (has_interface<PPB_View_1_1>()) { if (PP_ToBool(get_interface<PPB_View_1_1>()->GetRect(pp_resource(), &out))) return Rect(out); } else if (has_interface<PPB_View_1_0>()) { if (PP_ToBool(get_interface<PPB_View_1_0>()->GetRect(pp_resource(), &out))) return Rect(out); } return Rect(); } bool View::IsFullscreen() const { if (has_interface<PPB_View_1_2>()) { return PP_ToBool(get_interface<PPB_View_1_2>()->IsFullscreen( pp_resource())); } else if (has_interface<PPB_View_1_1>()) { return PP_ToBool(get_interface<PPB_View_1_1>()->IsFullscreen( pp_resource())); } else if (has_interface<PPB_View_1_0>()) { return PP_ToBool(get_interface<PPB_View_1_0>()->IsFullscreen( pp_resource())); } return false; } bool View::IsVisible() const { if (has_interface<PPB_View_1_2>()) return PP_ToBool(get_interface<PPB_View_1_2>()->IsVisible(pp_resource())); else if (has_interface<PPB_View_1_1>()) return PP_ToBool(get_interface<PPB_View_1_1>()->IsVisible(pp_resource())); else if (has_interface<PPB_View_1_0>()) return PP_ToBool(get_interface<PPB_View_1_0>()->IsVisible(pp_resource())); return false; } bool View::IsPageVisible() const { if (has_interface<PPB_View_1_2>()) { return PP_ToBool(get_interface<PPB_View_1_2>()->IsPageVisible( pp_resource())); } else if (has_interface<PPB_View_1_1>()) { return PP_ToBool(get_interface<PPB_View_1_1>()->IsPageVisible( pp_resource())); } else if (has_interface<PPB_View_1_0>()) { return PP_ToBool(get_interface<PPB_View_1_0>()->IsPageVisible( pp_resource())); } return true; } Rect View::GetClipRect() const { PP_Rect out; if (has_interface<PPB_View_1_2>()) { if (PP_ToBool(get_interface<PPB_View_1_2>()->GetClipRect(pp_resource(), &out))) return Rect(out); } else if (has_interface<PPB_View_1_1>()) { if (PP_ToBool(get_interface<PPB_View_1_1>()->GetClipRect(pp_resource(), &out))) return Rect(out); } else if (has_interface<PPB_View_1_0>()) { if (PP_ToBool(get_interface<PPB_View_1_0>()->GetClipRect(pp_resource(), &out))) return Rect(out); } return Rect(); } float View::GetDeviceScale() const { if (has_interface<PPB_View_1_2>()) return get_interface<PPB_View_1_2>()->GetDeviceScale(pp_resource()); else if (has_interface<PPB_View_1_1>()) return get_interface<PPB_View_1_1>()->GetDeviceScale(pp_resource()); return 1.0f; } float View::GetCSSScale() const { if (has_interface<PPB_View_1_2>()) return get_interface<PPB_View_1_2>()->GetCSSScale(pp_resource()); else if (has_interface<PPB_View_1_1>()) return get_interface<PPB_View_1_1>()->GetCSSScale(pp_resource()); return 1.0f; } Point View::GetScrollOffset() const { PP_Point out; if (has_interface<PPB_View_1_2>()) { if (PP_ToBool(get_interface<PPB_View_1_2>()->GetScrollOffset(pp_resource(), &out))) { return Point(out); } } return Point(); } } // namespace pp
null
null
null
null
40,958
55,068
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
55,068
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/common/chrome_content_client.h" #if defined(GOOGLE_CHROME_BUILD) const char ChromeContentClient::kNotPresent[] = "internal-not-yet-present"; const char ChromeContentClient::kPDFExtensionPluginName[] = "Chrome PDF Viewer"; const char ChromeContentClient::kPDFInternalPluginName[] = "Chrome PDF Plugin"; #else const char ChromeContentClient::kPDFExtensionPluginName[] = "Chromium PDF Viewer"; const char ChromeContentClient::kPDFInternalPluginName[] = "Chromium PDF Plugin"; #endif const char ChromeContentClient::kPDFPluginPath[] = "internal-pdf-viewer";
null
null
null
null
51,931
17,087
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
17,087
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright 2018 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_VIZ_TEST_TEST_LATEST_LOCAL_SURFACE_ID_LOOKUP_DELEGATE_H_ #define COMPONENTS_VIZ_TEST_TEST_LATEST_LOCAL_SURFACE_ID_LOOKUP_DELEGATE_H_ #include "base/containers/flat_map.h" #include "base/macros.h" #include "components/viz/common/surfaces/surface_id.h" #include "components/viz/service/surfaces/latest_local_surface_id_lookup_delegate.h" namespace viz { class TestLatestLocalSurfaceIdLookupDelegate : public LatestLocalSurfaceIdLookupDelegate { public: TestLatestLocalSurfaceIdLookupDelegate(); ~TestLatestLocalSurfaceIdLookupDelegate() override; // LatestLocalSurfaceIdLookupDelegate: LocalSurfaceId GetSurfaceAtAggregation( const FrameSinkId& frame_sink_id) const override; void SetSurfaceIdMap(const SurfaceId& surface_id); private: base::flat_map<FrameSinkId, LocalSurfaceId> surface_id_map_; DISALLOW_COPY_AND_ASSIGN(TestLatestLocalSurfaceIdLookupDelegate); }; } // namespace viz #endif // COMPONENTS_VIZ_TEST_TEST_LATEST_LOCAL_SURFACE_ID_LOOKUP_DELEGATE_H_
null
null
null
null
13,950
12,669
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
177,664
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * Copyright (C) 2008-2011 Freescale Semiconductor, Inc. All rights reserved. * * Author: Yu Liu, <yu.liu@freescale.com> * * Description: * This file is derived from arch/powerpc/kvm/44x_emulate.c, * by Hollis Blanchard <hollisb@us.ibm.com>. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License, version 2, as * published by the Free Software Foundation. */ #include <asm/kvm_ppc.h> #include <asm/disassemble.h> #include <asm/dbell.h> #include <asm/reg_booke.h> #include "booke.h" #include "e500.h" #define XOP_DCBTLS 166 #define XOP_MSGSND 206 #define XOP_MSGCLR 238 #define XOP_MFTMR 366 #define XOP_TLBIVAX 786 #define XOP_TLBSX 914 #define XOP_TLBRE 946 #define XOP_TLBWE 978 #define XOP_TLBILX 18 #define XOP_EHPRIV 270 #ifdef CONFIG_KVM_E500MC static int dbell2prio(ulong param) { int msg = param & PPC_DBELL_TYPE_MASK; int prio = -1; switch (msg) { case PPC_DBELL_TYPE(PPC_DBELL): prio = BOOKE_IRQPRIO_DBELL; break; case PPC_DBELL_TYPE(PPC_DBELL_CRIT): prio = BOOKE_IRQPRIO_DBELL_CRIT; break; default: break; } return prio; } static int kvmppc_e500_emul_msgclr(struct kvm_vcpu *vcpu, int rb) { ulong param = vcpu->arch.gpr[rb]; int prio = dbell2prio(param); if (prio < 0) return EMULATE_FAIL; clear_bit(prio, &vcpu->arch.pending_exceptions); return EMULATE_DONE; } static int kvmppc_e500_emul_msgsnd(struct kvm_vcpu *vcpu, int rb) { ulong param = vcpu->arch.gpr[rb]; int prio = dbell2prio(rb); int pir = param & PPC_DBELL_PIR_MASK; int i; struct kvm_vcpu *cvcpu; if (prio < 0) return EMULATE_FAIL; kvm_for_each_vcpu(i, cvcpu, vcpu->kvm) { int cpir = cvcpu->arch.shared->pir; if ((param & PPC_DBELL_MSG_BRDCAST) || (cpir == pir)) { set_bit(prio, &cvcpu->arch.pending_exceptions); kvm_vcpu_kick(cvcpu); } } return EMULATE_DONE; } #endif static int kvmppc_e500_emul_ehpriv(struct kvm_run *run, struct kvm_vcpu *vcpu, unsigned int inst, int *advance) { int emulated = EMULATE_DONE; switch (get_oc(inst)) { case EHPRIV_OC_DEBUG: run->exit_reason = KVM_EXIT_DEBUG; run->debug.arch.address = vcpu->arch.pc; run->debug.arch.status = 0; kvmppc_account_exit(vcpu, DEBUG_EXITS); emulated = EMULATE_EXIT_USER; *advance = 0; break; default: emulated = EMULATE_FAIL; } return emulated; } static int kvmppc_e500_emul_dcbtls(struct kvm_vcpu *vcpu) { struct kvmppc_vcpu_e500 *vcpu_e500 = to_e500(vcpu); /* Always fail to lock the cache */ vcpu_e500->l1csr0 |= L1CSR0_CUL; return EMULATE_DONE; } static int kvmppc_e500_emul_mftmr(struct kvm_vcpu *vcpu, unsigned int inst, int rt) { /* Expose one thread per vcpu */ if (get_tmrn(inst) == TMRN_TMCFG0) { kvmppc_set_gpr(vcpu, rt, 1 | (1 << TMRN_TMCFG0_NATHRD_SHIFT)); return EMULATE_DONE; } return EMULATE_FAIL; } int kvmppc_core_emulate_op_e500(struct kvm_run *run, struct kvm_vcpu *vcpu, unsigned int inst, int *advance) { int emulated = EMULATE_DONE; int ra = get_ra(inst); int rb = get_rb(inst); int rt = get_rt(inst); gva_t ea; switch (get_op(inst)) { case 31: switch (get_xop(inst)) { case XOP_DCBTLS: emulated = kvmppc_e500_emul_dcbtls(vcpu); break; #ifdef CONFIG_KVM_E500MC case XOP_MSGSND: emulated = kvmppc_e500_emul_msgsnd(vcpu, rb); break; case XOP_MSGCLR: emulated = kvmppc_e500_emul_msgclr(vcpu, rb); break; #endif case XOP_TLBRE: emulated = kvmppc_e500_emul_tlbre(vcpu); break; case XOP_TLBWE: emulated = kvmppc_e500_emul_tlbwe(vcpu); break; case XOP_TLBSX: ea = kvmppc_get_ea_indexed(vcpu, ra, rb); emulated = kvmppc_e500_emul_tlbsx(vcpu, ea); break; case XOP_TLBILX: { int type = rt & 0x3; ea = kvmppc_get_ea_indexed(vcpu, ra, rb); emulated = kvmppc_e500_emul_tlbilx(vcpu, type, ea); break; } case XOP_TLBIVAX: ea = kvmppc_get_ea_indexed(vcpu, ra, rb); emulated = kvmppc_e500_emul_tlbivax(vcpu, ea); break; case XOP_MFTMR: emulated = kvmppc_e500_emul_mftmr(vcpu, inst, rt); break; case XOP_EHPRIV: emulated = kvmppc_e500_emul_ehpriv(run, vcpu, inst, advance); break; default: emulated = EMULATE_FAIL; } break; default: emulated = EMULATE_FAIL; } if (emulated == EMULATE_FAIL) emulated = kvmppc_booke_emulate_op(run, vcpu, inst, advance); return emulated; } int kvmppc_core_emulate_mtspr_e500(struct kvm_vcpu *vcpu, int sprn, ulong spr_val) { struct kvmppc_vcpu_e500 *vcpu_e500 = to_e500(vcpu); int emulated = EMULATE_DONE; switch (sprn) { #ifndef CONFIG_KVM_BOOKE_HV case SPRN_PID: kvmppc_set_pid(vcpu, spr_val); break; case SPRN_PID1: if (spr_val != 0) return EMULATE_FAIL; vcpu_e500->pid[1] = spr_val; break; case SPRN_PID2: if (spr_val != 0) return EMULATE_FAIL; vcpu_e500->pid[2] = spr_val; break; case SPRN_MAS0: vcpu->arch.shared->mas0 = spr_val; break; case SPRN_MAS1: vcpu->arch.shared->mas1 = spr_val; break; case SPRN_MAS2: vcpu->arch.shared->mas2 = spr_val; break; case SPRN_MAS3: vcpu->arch.shared->mas7_3 &= ~(u64)0xffffffff; vcpu->arch.shared->mas7_3 |= spr_val; break; case SPRN_MAS4: vcpu->arch.shared->mas4 = spr_val; break; case SPRN_MAS6: vcpu->arch.shared->mas6 = spr_val; break; case SPRN_MAS7: vcpu->arch.shared->mas7_3 &= (u64)0xffffffff; vcpu->arch.shared->mas7_3 |= (u64)spr_val << 32; break; #endif case SPRN_L1CSR0: vcpu_e500->l1csr0 = spr_val; vcpu_e500->l1csr0 &= ~(L1CSR0_DCFI | L1CSR0_CLFC); break; case SPRN_L1CSR1: vcpu_e500->l1csr1 = spr_val; vcpu_e500->l1csr1 &= ~(L1CSR1_ICFI | L1CSR1_ICLFR); break; case SPRN_HID0: vcpu_e500->hid0 = spr_val; break; case SPRN_HID1: vcpu_e500->hid1 = spr_val; break; case SPRN_MMUCSR0: emulated = kvmppc_e500_emul_mt_mmucsr0(vcpu_e500, spr_val); break; case SPRN_PWRMGTCR0: /* * Guest relies on host power management configurations * Treat the request as a general store */ vcpu->arch.pwrmgtcr0 = spr_val; break; /* extra exceptions */ #ifdef CONFIG_SPE_POSSIBLE case SPRN_IVOR32: vcpu->arch.ivor[BOOKE_IRQPRIO_SPE_UNAVAIL] = spr_val; break; case SPRN_IVOR33: vcpu->arch.ivor[BOOKE_IRQPRIO_SPE_FP_DATA] = spr_val; break; case SPRN_IVOR34: vcpu->arch.ivor[BOOKE_IRQPRIO_SPE_FP_ROUND] = spr_val; break; #endif #ifdef CONFIG_ALTIVEC case SPRN_IVOR32: vcpu->arch.ivor[BOOKE_IRQPRIO_ALTIVEC_UNAVAIL] = spr_val; break; case SPRN_IVOR33: vcpu->arch.ivor[BOOKE_IRQPRIO_ALTIVEC_ASSIST] = spr_val; break; #endif case SPRN_IVOR35: vcpu->arch.ivor[BOOKE_IRQPRIO_PERFORMANCE_MONITOR] = spr_val; break; #ifdef CONFIG_KVM_BOOKE_HV case SPRN_IVOR36: vcpu->arch.ivor[BOOKE_IRQPRIO_DBELL] = spr_val; break; case SPRN_IVOR37: vcpu->arch.ivor[BOOKE_IRQPRIO_DBELL_CRIT] = spr_val; break; #endif default: emulated = kvmppc_booke_emulate_mtspr(vcpu, sprn, spr_val); } return emulated; } int kvmppc_core_emulate_mfspr_e500(struct kvm_vcpu *vcpu, int sprn, ulong *spr_val) { struct kvmppc_vcpu_e500 *vcpu_e500 = to_e500(vcpu); int emulated = EMULATE_DONE; switch (sprn) { #ifndef CONFIG_KVM_BOOKE_HV case SPRN_PID: *spr_val = vcpu_e500->pid[0]; break; case SPRN_PID1: *spr_val = vcpu_e500->pid[1]; break; case SPRN_PID2: *spr_val = vcpu_e500->pid[2]; break; case SPRN_MAS0: *spr_val = vcpu->arch.shared->mas0; break; case SPRN_MAS1: *spr_val = vcpu->arch.shared->mas1; break; case SPRN_MAS2: *spr_val = vcpu->arch.shared->mas2; break; case SPRN_MAS3: *spr_val = (u32)vcpu->arch.shared->mas7_3; break; case SPRN_MAS4: *spr_val = vcpu->arch.shared->mas4; break; case SPRN_MAS6: *spr_val = vcpu->arch.shared->mas6; break; case SPRN_MAS7: *spr_val = vcpu->arch.shared->mas7_3 >> 32; break; #endif case SPRN_DECAR: *spr_val = vcpu->arch.decar; break; case SPRN_TLB0CFG: *spr_val = vcpu->arch.tlbcfg[0]; break; case SPRN_TLB1CFG: *spr_val = vcpu->arch.tlbcfg[1]; break; case SPRN_TLB0PS: if (!has_feature(vcpu, VCPU_FTR_MMU_V2)) return EMULATE_FAIL; *spr_val = vcpu->arch.tlbps[0]; break; case SPRN_TLB1PS: if (!has_feature(vcpu, VCPU_FTR_MMU_V2)) return EMULATE_FAIL; *spr_val = vcpu->arch.tlbps[1]; break; case SPRN_L1CSR0: *spr_val = vcpu_e500->l1csr0; break; case SPRN_L1CSR1: *spr_val = vcpu_e500->l1csr1; break; case SPRN_HID0: *spr_val = vcpu_e500->hid0; break; case SPRN_HID1: *spr_val = vcpu_e500->hid1; break; case SPRN_SVR: *spr_val = vcpu_e500->svr; break; case SPRN_MMUCSR0: *spr_val = 0; break; case SPRN_MMUCFG: *spr_val = vcpu->arch.mmucfg; break; case SPRN_EPTCFG: if (!has_feature(vcpu, VCPU_FTR_MMU_V2)) return EMULATE_FAIL; /* * Legacy Linux guests access EPTCFG register even if the E.PT * category is disabled in the VM. Give them a chance to live. */ *spr_val = vcpu->arch.eptcfg; break; case SPRN_PWRMGTCR0: *spr_val = vcpu->arch.pwrmgtcr0; break; /* extra exceptions */ #ifdef CONFIG_SPE_POSSIBLE case SPRN_IVOR32: *spr_val = vcpu->arch.ivor[BOOKE_IRQPRIO_SPE_UNAVAIL]; break; case SPRN_IVOR33: *spr_val = vcpu->arch.ivor[BOOKE_IRQPRIO_SPE_FP_DATA]; break; case SPRN_IVOR34: *spr_val = vcpu->arch.ivor[BOOKE_IRQPRIO_SPE_FP_ROUND]; break; #endif #ifdef CONFIG_ALTIVEC case SPRN_IVOR32: *spr_val = vcpu->arch.ivor[BOOKE_IRQPRIO_ALTIVEC_UNAVAIL]; break; case SPRN_IVOR33: *spr_val = vcpu->arch.ivor[BOOKE_IRQPRIO_ALTIVEC_ASSIST]; break; #endif case SPRN_IVOR35: *spr_val = vcpu->arch.ivor[BOOKE_IRQPRIO_PERFORMANCE_MONITOR]; break; #ifdef CONFIG_KVM_BOOKE_HV case SPRN_IVOR36: *spr_val = vcpu->arch.ivor[BOOKE_IRQPRIO_DBELL]; break; case SPRN_IVOR37: *spr_val = vcpu->arch.ivor[BOOKE_IRQPRIO_DBELL_CRIT]; break; #endif default: emulated = kvmppc_booke_emulate_mfspr(vcpu, sprn, spr_val); } return emulated; }
null
null
null
null
86,011
70,585
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
70,585
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright 2016 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 SKIA_EXT_FONTMGR_DEFAULT_ANDROID_H_ #define SKIA_EXT_FONTMGR_DEFAULT_ANDROID_H_ #include "third_party/skia/include/core/SkTypes.h" class SkFontMgr; template <typename T> class sk_sp; SK_API void SetDefaultSkiaFactory(sk_sp<SkFontMgr> fontmgr); #endif // SKIA_EXT_FONTMGR_DEFAULT_ANDROID_H_
null
null
null
null
67,448
43,250
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
43,250
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright 2018 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 BASE_MEMORY_READ_ONLY_SHARED_MEMORY_REGION_H_ #define BASE_MEMORY_READ_ONLY_SHARED_MEMORY_REGION_H_ #include <utility> #include "base/macros.h" #include "base/memory/platform_shared_memory_region.h" #include "base/memory/shared_memory_mapping.h" namespace base { struct MappedReadOnlyRegion; // Scoped move-only handle to a region of platform shared memory. The instance // owns the platform handle it wraps. Mappings created by this region are // read-only. These mappings remain valid even after the region handle is moved // or destroyed. class BASE_EXPORT ReadOnlySharedMemoryRegion { public: using MappingType = ReadOnlySharedMemoryMapping; // Creates a new ReadOnlySharedMemoryRegion instance of a given size along // with the WritableSharedMemoryMapping which provides the only way to modify // the content of the newly created region. // // This means that the caller's process is the only process that can modify // the region content. If you need to pass write access to another process, // consider using WritableSharedMemoryRegion or UnsafeSharedMemoryRegion. static MappedReadOnlyRegion Create(size_t size); // Returns a ReadOnlySharedMemoryRegion built from a platform-specific handle // that was taken from another ReadOnlySharedMemoryRegion instance. Returns an // invalid region iff the |handle| is invalid. CHECK-fails if the |handle| // isn't read-only. // This should be used only by the code passing handles across process // boundaries. static ReadOnlySharedMemoryRegion Deserialize( subtle::PlatformSharedMemoryRegion handle); // Extracts a platform handle from the region. Ownership is transferred to the // returned region object. // This should be used only for sending the handle from the current process to // another. static subtle::PlatformSharedMemoryRegion TakeHandleForSerialization( ReadOnlySharedMemoryRegion region); // Default constructor initializes an invalid instance. ReadOnlySharedMemoryRegion(); // Move operations are allowed. ReadOnlySharedMemoryRegion(ReadOnlySharedMemoryRegion&&); ReadOnlySharedMemoryRegion& operator=(ReadOnlySharedMemoryRegion&&); // Destructor closes shared memory region if valid. // All created mappings will remain valid. ~ReadOnlySharedMemoryRegion(); // Duplicates the underlying platform handle and creates a new // ReadOnlySharedMemoryRegion instance that owns this handle. Returns a valid // ReadOnlySharedMemoryRegion on success, invalid otherwise. The current // region instance remains valid in any case. ReadOnlySharedMemoryRegion Duplicate() const; // Maps the shared memory region into the caller's address space with // read-only access. The mapped address is guaranteed to have an alignment of // at least |subtle::PlatformSharedMemoryRegion::kMapMinimumAlignment|. // Returns a valid ReadOnlySharedMemoryMapping instance on success, invalid // otherwise. ReadOnlySharedMemoryMapping Map() const; // Same as above, but maps only |size| bytes of the shared memory region // starting with the given |offset|. |offset| must be aligned to value of // |SysInfo::VMAllocationGranularity()|. Returns an invalid mapping if // requested bytes are out of the region limits. ReadOnlySharedMemoryMapping MapAt(off_t offset, size_t size) const; // Whether the underlying platform handle is valid. bool IsValid() const; // Returns the maximum mapping size that can be created from this region. size_t GetSize() const { DCHECK(IsValid()); return handle_.GetSize(); } private: explicit ReadOnlySharedMemoryRegion( subtle::PlatformSharedMemoryRegion handle); subtle::PlatformSharedMemoryRegion handle_; DISALLOW_COPY_AND_ASSIGN(ReadOnlySharedMemoryRegion); }; // Helper struct for return value of ReadOnlySharedMemoryRegion::Create(). struct MappedReadOnlyRegion { ReadOnlySharedMemoryRegion region; WritableSharedMemoryMapping mapping; }; } // namespace base #endif // BASE_MEMORY_READ_ONLY_SHARED_MEMORY_REGION_H_
null
null
null
null
40,113
58,570
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
58,570
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// 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/extensions/extension_apitest.h" IN_PROC_BROWSER_TEST_F(ExtensionApiTest, BackgroundScripts) { ASSERT_TRUE(RunExtensionTest("background_scripts")) << message_; }
null
null
null
null
55,433
3,540
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
168,535
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * file.c * * Copyright (c) 1999 Al Smith * * Portions derived from work (c) 1995,1996 Christian Vogelgsang. */ #include <linux/buffer_head.h> #include "efs.h" int efs_get_block(struct inode *inode, sector_t iblock, struct buffer_head *bh_result, int create) { int error = -EROFS; long phys; if (create) return error; if (iblock >= inode->i_blocks) { #ifdef DEBUG /* * i have no idea why this happens as often as it does */ pr_warn("%s(): block %d >= %ld (filesize %ld)\n", __func__, block, inode->i_blocks, inode->i_size); #endif return 0; } phys = efs_map_block(inode, iblock); if (phys) map_bh(bh_result, inode->i_sb, phys); return 0; } int efs_bmap(struct inode *inode, efs_block_t block) { if (block < 0) { pr_warn("%s(): block < 0\n", __func__); return 0; } /* are we about to read past the end of a file ? */ if (!(block < inode->i_blocks)) { #ifdef DEBUG /* * i have no idea why this happens as often as it does */ pr_warn("%s(): block %d >= %ld (filesize %ld)\n", __func__, block, inode->i_blocks, inode->i_size); #endif return 0; } return efs_map_block(inode, block); }
null
null
null
null
76,882
3,294
null
train_val
1b0d3845b454eaaac0b2064c78926ca4d739a080
265,862
qemu
0
https://github.com/bonzini/qemu
2016-10-18 11:40:27+01:00
/* * QEMU Crypto XTS cipher mode * * Copyright (c) 2015-2016 Red Hat, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, see <http://www.gnu.org/licenses/>. * * This code is originally derived from public domain / WTFPL code in * LibTomCrypt crytographic library http://libtom.org. The XTS code * was donated by Elliptic Semiconductor Inc (www.ellipticsemi.com) * to the LibTom Projects * */ #ifndef QCRYPTO_XTS_H #define QCRYPTO_XTS_H #include "qemu-common.h" #include "qapi/error.h" #define XTS_BLOCK_SIZE 16 typedef void xts_cipher_func(const void *ctx, size_t length, uint8_t *dst, const uint8_t *src); /** * xts_decrypt: * @datactx: the cipher context for data decryption * @tweakctx: the cipher context for tweak decryption * @encfunc: the cipher function for encryption * @decfunc: the cipher function for decryption * @iv: the initialization vector tweak of XTS_BLOCK_SIZE bytes * @length: the length of @dst and @src * @dst: buffer to hold the decrypted plaintext * @src: buffer providing the ciphertext * * Decrypts @src into @dst */ void xts_decrypt(const void *datactx, const void *tweakctx, xts_cipher_func *encfunc, xts_cipher_func *decfunc, uint8_t *iv, size_t length, uint8_t *dst, const uint8_t *src); /** * xts_decrypt: * @datactx: the cipher context for data encryption * @tweakctx: the cipher context for tweak encryption * @encfunc: the cipher function for encryption * @decfunc: the cipher function for decryption * @iv: the initialization vector tweak of XTS_BLOCK_SIZE bytes * @length: the length of @dst and @src * @dst: buffer to hold the encrypted ciphertext * @src: buffer providing the plaintext * * Decrypts @src into @dst */ void xts_encrypt(const void *datactx, const void *tweakctx, xts_cipher_func *encfunc, xts_cipher_func *decfunc, uint8_t *iv, size_t length, uint8_t *dst, const uint8_t *src); #endif /* QCRYPTO_XTS_H */
null
null
null
null
123,986
30,513
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
30,513
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
/* * Copyright (C) 2010 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef THIRD_PARTY_BLINK_PUBLIC_PLATFORM_WEB_FONT_DESCRIPTION_H_ #define THIRD_PARTY_BLINK_PUBLIC_PLATFORM_WEB_FONT_DESCRIPTION_H_ #include "third_party/blink/public/platform/web_string.h" namespace blink { class FontDescription; struct WebFontDescription { enum GenericFamily { kGenericFamilyNone, kGenericFamilyStandard, kGenericFamilySerif, kGenericFamilySansSerif, kGenericFamilyMonospace, kGenericFamilyCursive, kGenericFamilyFantasy }; enum Smoothing { kSmoothingAuto, kSmoothingNone, kSmoothingGrayscale, kSmoothingSubpixel }; enum Weight { kWeight100, kWeight200, kWeight300, kWeight400, kWeight500, kWeight600, kWeight700, kWeight800, kWeight900, kWeightNormal = kWeight400, kWeightBold = kWeight700 }; WebFontDescription() : generic_family(kGenericFamilyNone), size(0), italic(false), small_caps(false), weight(kWeightNormal), smoothing(kSmoothingAuto), letter_spacing(0), word_spacing(0) {} WebString family; GenericFamily generic_family; float size; bool italic; bool small_caps; Weight weight; Smoothing smoothing; short letter_spacing; short word_spacing; #if INSIDE_BLINK BLINK_PLATFORM_EXPORT WebFontDescription(const FontDescription&); BLINK_PLATFORM_EXPORT operator FontDescription() const; #endif }; } // namespace blink #endif
null
null
null
null
27,376
371
null
train_val
1b0d3845b454eaaac0b2064c78926ca4d739a080
262,939
qemu
0
https://github.com/bonzini/qemu
2016-10-18 11:40:27+01:00
/* * ARM AArch64 specific CPU ABI and functions for linux-user * * Copyright (c) 2013 Alexander Graf <agraf@suse.de> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, see <http://www.gnu.org/licenses/>. */ #ifndef AARCH64_TARGET_CPU_H #define AARCH64_TARGET_CPU_H static inline void cpu_clone_regs(CPUARMState *env, target_ulong newsp) { if (newsp) { env->xregs[31] = newsp; } env->xregs[0] = 0; } static inline void cpu_set_tls(CPUARMState *env, target_ulong newtls) { /* Note that AArch64 Linux keeps the TLS pointer in TPIDR; this is * different from AArch32 Linux, which uses TPIDRRO. */ env->cp15.tpidr_el[0] = newtls; } #endif
null
null
null
null
121,063
1,942
null
train_val
1b0d3845b454eaaac0b2064c78926ca4d739a080
264,510
qemu
0
https://github.com/bonzini/qemu
2016-10-18 11:40:27+01:00
/* * QEMU 8253/8254 - common bits of emulated and KVM kernel model * * Copyright (c) 2003-2004 Fabrice Bellard * Copyright (c) 2012 Jan Kiszka, Siemens AG * * 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. */ #include "qemu/osdep.h" #include "hw/hw.h" #include "hw/i386/pc.h" #include "hw/isa/isa.h" #include "qemu/timer.h" #include "hw/timer/i8254.h" #include "hw/timer/i8254_internal.h" /* val must be 0 or 1 */ void pit_set_gate(ISADevice *dev, int channel, int val) { PITCommonState *pit = PIT_COMMON(dev); PITChannelState *s = &pit->channels[channel]; PITCommonClass *c = PIT_COMMON_GET_CLASS(pit); c->set_channel_gate(pit, s, val); } /* get pit output bit */ int pit_get_out(PITChannelState *s, int64_t current_time) { uint64_t d; int out; d = muldiv64(current_time - s->count_load_time, PIT_FREQ, NANOSECONDS_PER_SECOND); switch (s->mode) { default: case 0: out = (d >= s->count); break; case 1: out = (d < s->count); break; case 2: if ((d % s->count) == 0 && d != 0) { out = 1; } else { out = 0; } break; case 3: out = (d % s->count) < ((s->count + 1) >> 1); break; case 4: case 5: out = (d == s->count); break; } return out; } /* return -1 if no transition will occur. */ int64_t pit_get_next_transition_time(PITChannelState *s, int64_t current_time) { uint64_t d, next_time, base; int period2; d = muldiv64(current_time - s->count_load_time, PIT_FREQ, NANOSECONDS_PER_SECOND); switch (s->mode) { default: case 0: case 1: if (d < s->count) { next_time = s->count; } else { return -1; } break; case 2: base = (d / s->count) * s->count; if ((d - base) == 0 && d != 0) { next_time = base + s->count; } else { next_time = base + s->count + 1; } break; case 3: base = (d / s->count) * s->count; period2 = ((s->count + 1) >> 1); if ((d - base) < period2) { next_time = base + period2; } else { next_time = base + s->count; } break; case 4: case 5: if (d < s->count) { next_time = s->count; } else if (d == s->count) { next_time = s->count + 1; } else { return -1; } break; } /* convert to timer units */ next_time = s->count_load_time + muldiv64(next_time, NANOSECONDS_PER_SECOND, PIT_FREQ); /* fix potential rounding problems */ /* XXX: better solution: use a clock at PIT_FREQ Hz */ if (next_time <= current_time) { next_time = current_time + 1; } return next_time; } void pit_get_channel_info_common(PITCommonState *s, PITChannelState *sc, PITChannelInfo *info) { info->gate = sc->gate; info->mode = sc->mode; info->initial_count = sc->count; info->out = pit_get_out(sc, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL)); } void pit_get_channel_info(ISADevice *dev, int channel, PITChannelInfo *info) { PITCommonState *pit = PIT_COMMON(dev); PITChannelState *s = &pit->channels[channel]; PITCommonClass *c = PIT_COMMON_GET_CLASS(pit); c->get_channel_info(pit, s, info); } void pit_reset_common(PITCommonState *pit) { PITChannelState *s; int i; for (i = 0; i < 3; i++) { s = &pit->channels[i]; s->mode = 3; s->gate = (i != 2); s->count_load_time = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL); s->count = 0x10000; if (i == 0 && !s->irq_disabled) { s->next_transition_time = pit_get_next_transition_time(s, s->count_load_time); } } } static void pit_common_realize(DeviceState *dev, Error **errp) { ISADevice *isadev = ISA_DEVICE(dev); PITCommonState *pit = PIT_COMMON(dev); isa_register_ioport(isadev, &pit->ioports, pit->iobase); qdev_set_legacy_instance_id(dev, pit->iobase, 2); } static const VMStateDescription vmstate_pit_channel = { .name = "pit channel", .version_id = 2, .minimum_version_id = 2, .fields = (VMStateField[]) { VMSTATE_INT32(count, PITChannelState), VMSTATE_UINT16(latched_count, PITChannelState), VMSTATE_UINT8(count_latched, PITChannelState), VMSTATE_UINT8(status_latched, PITChannelState), VMSTATE_UINT8(status, PITChannelState), VMSTATE_UINT8(read_state, PITChannelState), VMSTATE_UINT8(write_state, PITChannelState), VMSTATE_UINT8(write_latch, PITChannelState), VMSTATE_UINT8(rw_mode, PITChannelState), VMSTATE_UINT8(mode, PITChannelState), VMSTATE_UINT8(bcd, PITChannelState), VMSTATE_UINT8(gate, PITChannelState), VMSTATE_INT64(count_load_time, PITChannelState), VMSTATE_INT64(next_transition_time, PITChannelState), VMSTATE_END_OF_LIST() } }; static int pit_load_old(QEMUFile *f, void *opaque, int version_id) { PITCommonState *pit = opaque; PITCommonClass *c = PIT_COMMON_GET_CLASS(pit); PITChannelState *s; int i; if (version_id != 1) { return -EINVAL; } for (i = 0; i < 3; i++) { s = &pit->channels[i]; s->count = qemu_get_be32(f); qemu_get_be16s(f, &s->latched_count); qemu_get_8s(f, &s->count_latched); qemu_get_8s(f, &s->status_latched); qemu_get_8s(f, &s->status); qemu_get_8s(f, &s->read_state); qemu_get_8s(f, &s->write_state); qemu_get_8s(f, &s->write_latch); qemu_get_8s(f, &s->rw_mode); qemu_get_8s(f, &s->mode); qemu_get_8s(f, &s->bcd); qemu_get_8s(f, &s->gate); s->count_load_time = qemu_get_be64(f); s->irq_disabled = 0; if (i == 0) { s->next_transition_time = qemu_get_be64(f); } } if (c->post_load) { c->post_load(pit); } return 0; } static void pit_dispatch_pre_save(void *opaque) { PITCommonState *s = opaque; PITCommonClass *c = PIT_COMMON_GET_CLASS(s); if (c->pre_save) { c->pre_save(s); } } static int pit_dispatch_post_load(void *opaque, int version_id) { PITCommonState *s = opaque; PITCommonClass *c = PIT_COMMON_GET_CLASS(s); if (c->post_load) { c->post_load(s); } return 0; } static const VMStateDescription vmstate_pit_common = { .name = "i8254", .version_id = 3, .minimum_version_id = 2, .minimum_version_id_old = 1, .load_state_old = pit_load_old, .pre_save = pit_dispatch_pre_save, .post_load = pit_dispatch_post_load, .fields = (VMStateField[]) { VMSTATE_UINT32_V(channels[0].irq_disabled, PITCommonState, 3), VMSTATE_STRUCT_ARRAY(channels, PITCommonState, 3, 2, vmstate_pit_channel, PITChannelState), VMSTATE_INT64(channels[0].next_transition_time, PITCommonState), /* formerly irq_timer */ VMSTATE_END_OF_LIST() } }; static void pit_common_class_init(ObjectClass *klass, void *data) { DeviceClass *dc = DEVICE_CLASS(klass); dc->realize = pit_common_realize; dc->vmsd = &vmstate_pit_common; /* * Reason: unlike ordinary ISA devices, the PIT may need to be * wired to the HPET, and because of that, some wiring is always * done by board code. */ dc->cannot_instantiate_with_device_add_yet = true; } static const TypeInfo pit_common_type = { .name = TYPE_PIT_COMMON, .parent = TYPE_ISA_DEVICE, .instance_size = sizeof(PITCommonState), .class_size = sizeof(PITCommonClass), .class_init = pit_common_class_init, .abstract = true, }; static void register_devices(void) { type_register_static(&pit_common_type); } type_init(register_devices);
null
null
null
null
122,634
30,730
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
30,730
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This file has been auto-generated from the Jinja2 template // third_party/blink/renderer/bindings/templates/union_container.cpp.tmpl // by the script code_generator_v8.py. // DO NOT MODIFY! // clang-format off #include "long_sequence_or_event.h" #include "bindings/core/v8/idl_types.h" #include "bindings/core/v8/native_value_traits_impl.h" #include "bindings/core/v8/to_v8_for_core.h" #include "bindings/core/v8/v8_event.h" namespace blink { LongSequenceOrEvent::LongSequenceOrEvent() : type_(SpecificType::kNone) {} Event* LongSequenceOrEvent::GetAsEvent() const { DCHECK(IsEvent()); return event_; } void LongSequenceOrEvent::SetEvent(Event* value) { DCHECK(IsNull()); event_ = value; type_ = SpecificType::kEvent; } LongSequenceOrEvent LongSequenceOrEvent::FromEvent(Event* value) { LongSequenceOrEvent container; container.SetEvent(value); return container; } const Vector<int32_t>& LongSequenceOrEvent::GetAsLongSequence() const { DCHECK(IsLongSequence()); return long_sequence_; } void LongSequenceOrEvent::SetLongSequence(const Vector<int32_t>& value) { DCHECK(IsNull()); long_sequence_ = value; type_ = SpecificType::kLongSequence; } LongSequenceOrEvent LongSequenceOrEvent::FromLongSequence(const Vector<int32_t>& value) { LongSequenceOrEvent container; container.SetLongSequence(value); return container; } LongSequenceOrEvent::LongSequenceOrEvent(const LongSequenceOrEvent&) = default; LongSequenceOrEvent::~LongSequenceOrEvent() = default; LongSequenceOrEvent& LongSequenceOrEvent::operator=(const LongSequenceOrEvent&) = default; void LongSequenceOrEvent::Trace(blink::Visitor* visitor) { visitor->Trace(event_); } void V8LongSequenceOrEvent::ToImpl(v8::Isolate* isolate, v8::Local<v8::Value> v8Value, LongSequenceOrEvent& impl, UnionTypeConversionMode conversionMode, ExceptionState& exceptionState) { if (v8Value.IsEmpty()) return; if (conversionMode == UnionTypeConversionMode::kNullable && IsUndefinedOrNull(v8Value)) return; if (V8Event::hasInstance(v8Value, isolate)) { Event* cppValue = V8Event::ToImpl(v8::Local<v8::Object>::Cast(v8Value)); impl.SetEvent(cppValue); return; } if (HasCallableIteratorSymbol(isolate, v8Value, exceptionState)) { Vector<int32_t> cppValue = NativeValueTraits<IDLSequence<IDLLong>>::NativeValue(isolate, v8Value, exceptionState); if (exceptionState.HadException()) return; impl.SetLongSequence(cppValue); return; } exceptionState.ThrowTypeError("The provided value is not of type '(sequence<long> or Event)'"); } v8::Local<v8::Value> ToV8(const LongSequenceOrEvent& impl, v8::Local<v8::Object> creationContext, v8::Isolate* isolate) { switch (impl.type_) { case LongSequenceOrEvent::SpecificType::kNone: return v8::Null(isolate); case LongSequenceOrEvent::SpecificType::kEvent: return ToV8(impl.GetAsEvent(), creationContext, isolate); case LongSequenceOrEvent::SpecificType::kLongSequence: return ToV8(impl.GetAsLongSequence(), creationContext, isolate); default: NOTREACHED(); } return v8::Local<v8::Value>(); } LongSequenceOrEvent NativeValueTraits<LongSequenceOrEvent>::NativeValue(v8::Isolate* isolate, v8::Local<v8::Value> value, ExceptionState& exceptionState) { LongSequenceOrEvent impl; V8LongSequenceOrEvent::ToImpl(isolate, value, impl, UnionTypeConversionMode::kNotNullable, exceptionState); return impl; } } // namespace blink
null
null
null
null
27,593
2,649
null
train_val
1b0d3845b454eaaac0b2064c78926ca4d739a080
265,217
qemu
0
https://github.com/bonzini/qemu
2016-10-18 11:40:27+01:00
/* * QEMU Crypto block device encryption * * Copyright (c) 2015-2016 Red Hat, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, see <http://www.gnu.org/licenses/>. * */ #include "qemu/osdep.h" #include "qapi/error.h" #include "crypto/blockpriv.h" #include "crypto/block-qcow.h" #include "crypto/block-luks.h" static const QCryptoBlockDriver *qcrypto_block_drivers[] = { [Q_CRYPTO_BLOCK_FORMAT_QCOW] = &qcrypto_block_driver_qcow, [Q_CRYPTO_BLOCK_FORMAT_LUKS] = &qcrypto_block_driver_luks, }; bool qcrypto_block_has_format(QCryptoBlockFormat format, const uint8_t *buf, size_t len) { const QCryptoBlockDriver *driver; if (format >= G_N_ELEMENTS(qcrypto_block_drivers) || !qcrypto_block_drivers[format]) { return false; } driver = qcrypto_block_drivers[format]; return driver->has_format(buf, len); } QCryptoBlock *qcrypto_block_open(QCryptoBlockOpenOptions *options, QCryptoBlockReadFunc readfunc, void *opaque, unsigned int flags, Error **errp) { QCryptoBlock *block = g_new0(QCryptoBlock, 1); block->format = options->format; if (options->format >= G_N_ELEMENTS(qcrypto_block_drivers) || !qcrypto_block_drivers[options->format]) { error_setg(errp, "Unsupported block driver %s", QCryptoBlockFormat_lookup[options->format]); g_free(block); return NULL; } block->driver = qcrypto_block_drivers[options->format]; if (block->driver->open(block, options, readfunc, opaque, flags, errp) < 0) { g_free(block); return NULL; } return block; } QCryptoBlock *qcrypto_block_create(QCryptoBlockCreateOptions *options, QCryptoBlockInitFunc initfunc, QCryptoBlockWriteFunc writefunc, void *opaque, Error **errp) { QCryptoBlock *block = g_new0(QCryptoBlock, 1); block->format = options->format; if (options->format >= G_N_ELEMENTS(qcrypto_block_drivers) || !qcrypto_block_drivers[options->format]) { error_setg(errp, "Unsupported block driver %s", QCryptoBlockFormat_lookup[options->format]); g_free(block); return NULL; } block->driver = qcrypto_block_drivers[options->format]; if (block->driver->create(block, options, initfunc, writefunc, opaque, errp) < 0) { g_free(block); return NULL; } return block; } QCryptoBlockInfo *qcrypto_block_get_info(QCryptoBlock *block, Error **errp) { QCryptoBlockInfo *info = g_new0(QCryptoBlockInfo, 1); info->format = block->format; if (block->driver->get_info && block->driver->get_info(block, info, errp) < 0) { g_free(info); return NULL; } return info; } int qcrypto_block_decrypt(QCryptoBlock *block, uint64_t startsector, uint8_t *buf, size_t len, Error **errp) { return block->driver->decrypt(block, startsector, buf, len, errp); } int qcrypto_block_encrypt(QCryptoBlock *block, uint64_t startsector, uint8_t *buf, size_t len, Error **errp) { return block->driver->encrypt(block, startsector, buf, len, errp); } QCryptoCipher *qcrypto_block_get_cipher(QCryptoBlock *block) { return block->cipher; } QCryptoIVGen *qcrypto_block_get_ivgen(QCryptoBlock *block) { return block->ivgen; } QCryptoHashAlgorithm qcrypto_block_get_kdf_hash(QCryptoBlock *block) { return block->kdfhash; } uint64_t qcrypto_block_get_payload_offset(QCryptoBlock *block) { return block->payload_offset; } void qcrypto_block_free(QCryptoBlock *block) { if (!block) { return; } block->driver->cleanup(block); qcrypto_cipher_free(block->cipher); qcrypto_ivgen_free(block->ivgen); g_free(block); } int qcrypto_block_decrypt_helper(QCryptoCipher *cipher, size_t niv, QCryptoIVGen *ivgen, int sectorsize, uint64_t startsector, uint8_t *buf, size_t len, Error **errp) { uint8_t *iv; int ret = -1; iv = niv ? g_new0(uint8_t, niv) : NULL; while (len > 0) { size_t nbytes; if (niv) { if (qcrypto_ivgen_calculate(ivgen, startsector, iv, niv, errp) < 0) { goto cleanup; } if (qcrypto_cipher_setiv(cipher, iv, niv, errp) < 0) { goto cleanup; } } nbytes = len > sectorsize ? sectorsize : len; if (qcrypto_cipher_decrypt(cipher, buf, buf, nbytes, errp) < 0) { goto cleanup; } startsector++; buf += nbytes; len -= nbytes; } ret = 0; cleanup: g_free(iv); return ret; } int qcrypto_block_encrypt_helper(QCryptoCipher *cipher, size_t niv, QCryptoIVGen *ivgen, int sectorsize, uint64_t startsector, uint8_t *buf, size_t len, Error **errp) { uint8_t *iv; int ret = -1; iv = niv ? g_new0(uint8_t, niv) : NULL; while (len > 0) { size_t nbytes; if (niv) { if (qcrypto_ivgen_calculate(ivgen, startsector, iv, niv, errp) < 0) { goto cleanup; } if (qcrypto_cipher_setiv(cipher, iv, niv, errp) < 0) { goto cleanup; } } nbytes = len > sectorsize ? sectorsize : len; if (qcrypto_cipher_encrypt(cipher, buf, buf, nbytes, errp) < 0) { goto cleanup; } startsector++; buf += nbytes; len -= nbytes; } ret = 0; cleanup: g_free(iv); return ret; }
null
null
null
null
123,341
14,404
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
14,404
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// 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 "components/ntp_snippets/remote/remote_suggestion.h" #include <limits> #include "base/memory/ptr_util.h" #include "base/strings/string_number_conversions.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/values.h" #include "components/ntp_snippets/category.h" #include "components/ntp_snippets/remote/proto/ntp_snippets.pb.h" #include "components/ntp_snippets/time_serialization.h" namespace { // dict.Get() specialization for base::Time values bool GetTimeValue(const base::DictionaryValue& dict, const std::string& key, base::Time* time) { std::string time_value; return dict.GetString(key, &time_value) && base::Time::FromString(time_value.c_str(), time); } // dict.Get() specialization for GURL values bool GetURLValue(const base::DictionaryValue& dict, const std::string& key, GURL* url) { std::string spec; if (!dict.GetString(key, &spec)) { return false; } *url = GURL(spec); return url->is_valid(); } } // namespace namespace ntp_snippets { const int kArticlesRemoteId = 1; static_assert( static_cast<int>(KnownCategories::ARTICLES) - static_cast<int>(KnownCategories::REMOTE_CATEGORIES_OFFSET) == kArticlesRemoteId, "kArticlesRemoteId has a wrong value?!"); RemoteSuggestion::RemoteSuggestion(const std::vector<std::string>& ids, int remote_category_id) : ids_(ids), score_(0), is_dismissed_(false), remote_category_id_(remote_category_id), rank_(std::numeric_limits<int>::max()), should_notify_(false), content_type_(ContentType::UNKNOWN) {} RemoteSuggestion::~RemoteSuggestion() = default; // static std::unique_ptr<RemoteSuggestion> RemoteSuggestion::CreateFromContentSuggestionsDictionary( const base::DictionaryValue& dict, int remote_category_id, const base::Time& fetch_date) { const base::ListValue* ids; if (!dict.GetList("ids", &ids)) { return nullptr; } std::vector<std::string> parsed_ids; for (const auto& value : *ids) { std::string id; if (!value.GetAsString(&id)) { return nullptr; } parsed_ids.push_back(id); } if (parsed_ids.empty()) { return nullptr; } auto snippet = MakeUnique(parsed_ids, remote_category_id); snippet->fetch_date_ = fetch_date; if (!(dict.GetString("title", &snippet->title_) && dict.GetString("snippet", &snippet->snippet_) && GetTimeValue(dict, "creationTime", &snippet->publish_date_) && GetTimeValue(dict, "expirationTime", &snippet->expiry_date_) && GetURLValue(dict, "imageUrl", &snippet->salient_image_url_) && dict.GetString("attribution", &snippet->publisher_name_) && GetURLValue(dict, "fullPageUrl", &snippet->url_))) { return nullptr; } GetURLValue(dict, "ampUrl", &snippet->amp_url_); // May fail; OK. // TODO(sfiera): also favicon URL. const base::Value* image_dominant_color_value = dict.FindKey("imageDominantColor"); if (image_dominant_color_value) { // The field is defined as fixed32 in the proto (effectively 32 bits // unsigned int), however, JSON does not support unsigned types. As a result // the value is parsed as int if it fits and as double otherwise. Double can // hold 32 bits precisely. uint32_t image_dominant_color; if (image_dominant_color_value->is_int()) { image_dominant_color = image_dominant_color_value->GetInt(); } else if (image_dominant_color_value->is_double()) { image_dominant_color = static_cast<uint32_t>(image_dominant_color_value->GetDouble()); } snippet->image_dominant_color_ = image_dominant_color; } double score; if (dict.GetDouble("score", &score)) { snippet->score_ = score; } const base::DictionaryValue* notification_info = nullptr; if (dict.GetDictionary("notificationInfo", &notification_info)) { if (notification_info->GetBoolean("shouldNotify", &snippet->should_notify_) && snippet->should_notify_) { if (!GetTimeValue(*notification_info, "deadline", &snippet->notification_deadline_)) { snippet->notification_deadline_ = base::Time::Max(); } } } // In the JSON dictionary contentType is an optional field. The field // content_type_ of the class |RemoteSuggestion| is by default initialized to // ContentType::UNKNOWN. std::string content_type; if (dict.GetString("contentType", &content_type)) { if (content_type == "VIDEO") { snippet->content_type_ = ContentType::VIDEO; } else { // The supported values are: VIDEO, UNKNOWN. Therefore if the field is // present the value has to be "UNKNOWN" here. DCHECK_EQ(content_type, "UNKNOWN"); snippet->content_type_ = ContentType::UNKNOWN; } } return snippet; } // static std::unique_ptr<RemoteSuggestion> RemoteSuggestion::CreateFromContextualSuggestionsDictionary( const base::DictionaryValue& dict) { std::string id; if (!dict.GetString("url", &id) || id.empty()) { return nullptr; } // TODO(gaschler): Remove the unused kArticlesRemoteId argument when moving // away from RemoteSuggestion. auto remote_suggestion = MakeUnique({id}, kArticlesRemoteId); GetURLValue(dict, "url", &remote_suggestion->url_); if (!dict.GetString("title", &remote_suggestion->title_)) { dict.GetString("source", &remote_suggestion->title_); } dict.GetString("snippet", &remote_suggestion->snippet_); GetTimeValue(dict, "creationTime", &remote_suggestion->publish_date_); GetTimeValue(dict, "expirationTime", &remote_suggestion->expiry_date_); GetURLValue(dict, "imageUrl", &remote_suggestion->salient_image_url_); if (!dict.GetString("attribution", &remote_suggestion->publisher_name_)) { dict.GetString("source", &remote_suggestion->publisher_name_); } return remote_suggestion; } // static std::unique_ptr<RemoteSuggestion> RemoteSuggestion::CreateFromProto( const SnippetProto& proto) { // Need at least the id. if (proto.ids_size() == 0 || proto.ids(0).empty()) { return nullptr; } int remote_category_id = proto.has_remote_category_id() ? proto.remote_category_id() : kArticlesRemoteId; std::vector<std::string> ids(proto.ids().begin(), proto.ids().end()); auto snippet = MakeUnique(ids, remote_category_id); snippet->title_ = proto.title(); snippet->snippet_ = proto.snippet(); snippet->salient_image_url_ = GURL(proto.salient_image_url()); if (proto.has_image_dominant_color()) { snippet->image_dominant_color_ = proto.image_dominant_color(); } snippet->publish_date_ = DeserializeTime(proto.publish_date()); snippet->expiry_date_ = DeserializeTime(proto.expiry_date()); snippet->score_ = proto.score(); snippet->is_dismissed_ = proto.dismissed(); if (!proto.has_source()) { DLOG(WARNING) << "No source found for article " << snippet->id(); return nullptr; } GURL url(proto.source().url()); if (!url.is_valid()) { // We must at least have a valid source URL. DLOG(WARNING) << "Invalid article url " << proto.source().url(); return nullptr; } GURL amp_url; if (proto.source().has_amp_url()) { amp_url = GURL(proto.source().amp_url()); DLOG_IF(WARNING, !amp_url.is_valid()) << "Invalid AMP URL " << proto.source().amp_url(); } snippet->url_ = url; snippet->publisher_name_ = proto.source().publisher_name(); snippet->amp_url_ = amp_url; if (proto.has_fetch_date()) { snippet->fetch_date_ = DeserializeTime(proto.fetch_date()); } if (proto.content_type() == SnippetProto_ContentType_VIDEO) { snippet->content_type_ = ContentType::VIDEO; } snippet->rank_ = proto.has_rank() ? proto.rank() : std::numeric_limits<int>::max(); return snippet; } SnippetProto RemoteSuggestion::ToProto() const { SnippetProto result; for (const std::string& id : ids_) { result.add_ids(id); } if (!title_.empty()) { result.set_title(title_); } if (!snippet_.empty()) { result.set_snippet(snippet_); } if (salient_image_url_.is_valid()) { result.set_salient_image_url(salient_image_url_.spec()); } if (image_dominant_color_.has_value()) { result.set_image_dominant_color(*image_dominant_color_); } if (!publish_date_.is_null()) { result.set_publish_date(SerializeTime(publish_date_)); } if (!expiry_date_.is_null()) { result.set_expiry_date(SerializeTime(expiry_date_)); } result.set_score(score_); result.set_dismissed(is_dismissed_); result.set_remote_category_id(remote_category_id_); SnippetSourceProto* source_proto = result.mutable_source(); source_proto->set_url(url_.spec()); if (!publisher_name_.empty()) { source_proto->set_publisher_name(publisher_name_); } if (amp_url_.is_valid()) { source_proto->set_amp_url(amp_url_.spec()); } if (!fetch_date_.is_null()) { result.set_fetch_date(SerializeTime(fetch_date_)); } if (content_type_ == ContentType::VIDEO) { result.set_content_type(SnippetProto_ContentType_VIDEO); } result.set_rank(rank_); return result; } ContentSuggestion RemoteSuggestion::ToContentSuggestion( Category category) const { GURL url = url_; bool use_amp = !amp_url_.is_empty(); if (use_amp) { url = amp_url_; } ContentSuggestion suggestion(category, id(), url); // Set url for fetching favicons if it differs from the main url (domains of // AMP URLs sometimes failed to provide favicons). if (use_amp) { suggestion.set_url_with_favicon(url_); } suggestion.set_title(base::UTF8ToUTF16(title_)); suggestion.set_snippet_text(base::UTF8ToUTF16(snippet_)); suggestion.set_publish_date(publish_date_); suggestion.set_publisher_name(base::UTF8ToUTF16(publisher_name_)); suggestion.set_score(score_); if (should_notify_) { NotificationExtra extra; extra.deadline = notification_deadline_; suggestion.set_notification_extra( std::make_unique<NotificationExtra>(extra)); } suggestion.set_fetch_date(fetch_date_); if (content_type_ == ContentType::VIDEO) { suggestion.set_is_video_suggestion(true); } suggestion.set_optional_image_dominant_color(image_dominant_color_); return suggestion; } // static std::unique_ptr<RemoteSuggestion> RemoteSuggestion::MakeUnique( const std::vector<std::string>& ids, int remote_category_id) { return base::WrapUnique(new RemoteSuggestion(ids, remote_category_id)); } } // namespace ntp_snippets
null
null
null
null
11,267
24,987
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
24,987
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright 2017 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 "extensions/renderer/bindings/api_binding_hooks_delegate.h" namespace extensions { APIBindingHooksDelegate::~APIBindingHooksDelegate() {} bool APIBindingHooksDelegate::CreateCustomEvent( v8::Local<v8::Context> context, const std::string& event_name, v8::Local<v8::Value>* event_out) { return false; } APIBindingHooks::RequestResult APIBindingHooksDelegate::HandleRequest( const std::string& method_name, const APISignature* signature, v8::Local<v8::Context> context, std::vector<v8::Local<v8::Value>>* arguments, const APITypeReferenceMap& refs) { return APIBindingHooks::RequestResult( APIBindingHooks::RequestResult::NOT_HANDLED); } } // namespace extensions
null
null
null
null
21,850
4,166
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
169,161
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * Copyright (c) 2000-2005 Silicon Graphics, Inc. * All Rights Reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation. * * This program is distributed in the hope that it would 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 the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "xfs.h" #include "xfs_sysctl.h" /* * Tunable XFS parameters. xfs_params is required even when CONFIG_SYSCTL=n, * other XFS code uses these values. Times are measured in centisecs (i.e. * 100ths of a second) with the exception of eofb_timer and cowb_timer, which * are measured in seconds. */ xfs_param_t xfs_params = { /* MIN DFLT MAX */ .sgid_inherit = { 0, 0, 1 }, .symlink_mode = { 0, 0, 1 }, .panic_mask = { 0, 0, 255 }, .error_level = { 0, 3, 11 }, .syncd_timer = { 1*100, 30*100, 7200*100}, .stats_clear = { 0, 0, 1 }, .inherit_sync = { 0, 1, 1 }, .inherit_nodump = { 0, 1, 1 }, .inherit_noatim = { 0, 1, 1 }, .xfs_buf_timer = { 100/2, 1*100, 30*100 }, .xfs_buf_age = { 1*100, 15*100, 7200*100}, .inherit_nosym = { 0, 0, 1 }, .rotorstep = { 1, 1, 255 }, .inherit_nodfrg = { 0, 1, 1 }, .fstrm_timer = { 1, 30*100, 3600*100}, .eofb_timer = { 1, 300, 3600*24}, .cowb_timer = { 1, 1800, 3600*24}, }; struct xfs_globals xfs_globals = { .log_recovery_delay = 0, /* no delay by default */ };
null
null
null
null
77,508
42,323
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
42,323
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// 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 BASE_SYS_INFO_INTERNAL_H_ #define BASE_SYS_INFO_INTERNAL_H_ #include "base/macros.h" namespace base { namespace internal { template<typename T, T (*F)(void)> class LazySysInfoValue { public: LazySysInfoValue() : value_(F()) { } ~LazySysInfoValue() = default; T value() { return value_; } private: const T value_; DISALLOW_COPY_AND_ASSIGN(LazySysInfoValue); }; } // namespace internal } // namespace base #endif // BASE_SYS_INFO_INTERNAL_H_
null
null
null
null
39,186
54,910
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
54,910
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright 2017 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/renderer/extensions/extension_hooks_delegate.h" #include "content/public/renderer/v8_value_converter.h" #include "extensions/common/api/messaging/message.h" #include "extensions/common/constants.h" #include "extensions/common/extension.h" #include "extensions/common/manifest.h" #include "extensions/common/view_type.h" #include "extensions/renderer/bindings/api_signature.h" #include "extensions/renderer/extension_frame_helper.h" #include "extensions/renderer/extensions_renderer_client.h" #include "extensions/renderer/get_script_context.h" #include "extensions/renderer/message_target.h" #include "extensions/renderer/messaging_util.h" #include "extensions/renderer/native_renderer_messaging_service.h" #include "extensions/renderer/script_context.h" #include "gin/converter.h" #include "gin/dictionary.h" namespace extensions { namespace { using RequestResult = APIBindingHooks::RequestResult; constexpr char kSendRequest[] = "extension.sendRequest"; constexpr char kGetURL[] = "extension.getURL"; constexpr char kGetBackgroundPage[] = "extension.getBackgroundPage"; constexpr char kGetViews[] = "extension.getViews"; constexpr char kGetExtensionTabs[] = "extension.getExtensionTabs"; // We alias a bunch of chrome.extension APIs to their chrome.runtime // counterparts. // NOTE(devlin): This is a very simple alias, in which we just return the // runtime version from the chrome.runtime object. This is important to note // for a few reasons: // - Modifications to the chrome.runtime object will affect the return result // here. i.e., if script does chrome.runtime.sendMessage = 'some string', // then chrome.extension.sendMessage will also be 'some string'. // - Events will share listeners. i.e., a listener added to // chrome.extension.onMessage will fire from a runtime.onMessage event, and // vice versa. // All of these APIs have been deprecated, and are no longer even documented, // but still have usage. This is the cheap workaround that JS bindings have been // using, and, while not robust, it should be secure, so use it native bindings, // too. void GetAliasedFeature(v8::Local<v8::Name> property_name, const v8::PropertyCallbackInfo<v8::Value>& info) { v8::Isolate* isolate = info.GetIsolate(); v8::HandleScope handle_scope(isolate); v8::Local<v8::Context> context = info.Holder()->CreationContext(); v8::TryCatch try_catch(isolate); v8::Local<v8::Value> chrome; if (!context->Global() ->Get(context, gin::StringToSymbol(isolate, "chrome")) .ToLocal(&chrome) || !chrome->IsObject()) { return; } v8::Local<v8::Value> runtime; if (!chrome.As<v8::Object>() ->Get(context, gin::StringToSymbol(isolate, "runtime")) .ToLocal(&runtime) || !runtime->IsObject()) { return; } v8::Local<v8::Object> runtime_obj = runtime.As<v8::Object>(); v8::Maybe<bool> has_property = runtime_obj->HasRealNamedProperty(context, property_name); if (!has_property.IsJust() || !has_property.FromJust()) return; info.GetReturnValue().Set( runtime_obj->Get(context, property_name).ToLocalChecked()); } // A helper method to throw a deprecation error on access. void ThrowDeprecatedAccessError( v8::Local<v8::Name> name, const v8::PropertyCallbackInfo<v8::Value>& info) { static constexpr char kError[] = "extension.sendRequest, extension.onRequest, and " "extension.onRequestExternal are deprecated. Please use " "runtime.sendMessage, runtime.onMessage, and runtime.onMessageExternal " "instead."; v8::Isolate* isolate = info.GetIsolate(); isolate->ThrowException( v8::Exception::Error(gin::StringToV8(isolate, kError))); } } // namespace ExtensionHooksDelegate::ExtensionHooksDelegate( NativeRendererMessagingService* messaging_service) : messaging_service_(messaging_service) {} ExtensionHooksDelegate::~ExtensionHooksDelegate() {} RequestResult ExtensionHooksDelegate::HandleRequest( const std::string& method_name, const APISignature* signature, v8::Local<v8::Context> context, std::vector<v8::Local<v8::Value>>* arguments, const APITypeReferenceMap& refs) { // TODO(devlin): This logic is the same in the RuntimeCustomHooksDelegate - // would it make sense to share it? using Handler = RequestResult (ExtensionHooksDelegate::*)( ScriptContext*, const std::vector<v8::Local<v8::Value>>&); static struct { Handler handler; base::StringPiece method; } kHandlers[] = { {&ExtensionHooksDelegate::HandleSendRequest, kSendRequest}, {&ExtensionHooksDelegate::HandleGetURL, kGetURL}, {&ExtensionHooksDelegate::HandleGetBackgroundPage, kGetBackgroundPage}, {&ExtensionHooksDelegate::HandleGetExtensionTabs, kGetExtensionTabs}, {&ExtensionHooksDelegate::HandleGetViews, kGetViews}, }; ScriptContext* script_context = GetScriptContextFromV8ContextChecked(context); Handler handler = nullptr; for (const auto& handler_entry : kHandlers) { if (handler_entry.method == method_name) { handler = handler_entry.handler; break; } } if (!handler) return RequestResult(RequestResult::NOT_HANDLED); if (method_name == kSendRequest) { messaging_util::MassageSendMessageArguments(context->GetIsolate(), false, arguments); } std::string error; std::vector<v8::Local<v8::Value>> parsed_arguments; if (!signature->ParseArgumentsToV8(context, *arguments, refs, &parsed_arguments, &error)) { RequestResult result(RequestResult::INVALID_INVOCATION); result.error = std::move(error); return result; } return (this->*handler)(script_context, parsed_arguments); } void ExtensionHooksDelegate::InitializeTemplate( v8::Isolate* isolate, v8::Local<v8::ObjectTemplate> object_template, const APITypeReferenceMap& type_refs) { static constexpr const char* kAliases[] = { "connect", "connectNative", "sendMessage", "sendNativeMessage", "onConnect", "onConnectExternal", "onMessage", "onMessageExternal", }; for (const auto* alias : kAliases) { object_template->SetAccessor(gin::StringToSymbol(isolate, alias), &GetAliasedFeature); } bool is_incognito = ExtensionsRendererClient::Get()->IsIncognitoProcess(); object_template->Set(isolate, "inIncognitoContext", v8::Boolean::New(isolate, is_incognito)); } void ExtensionHooksDelegate::InitializeInstance( v8::Local<v8::Context> context, v8::Local<v8::Object> instance) { // Throw access errors for deprecated sendRequest-related properties. This // isn't terribly efficient, but is only done for certain unpacked extensions // and only if they access the chrome.extension module. if (messaging_util::IsSendRequestDisabled( GetScriptContextFromV8ContextChecked(context))) { static constexpr const char* kDeprecatedSendRequestProperties[] = { "sendRequest", "onRequest", "onRequestExternal"}; for (const char* property : kDeprecatedSendRequestProperties) { v8::Maybe<bool> success = instance->SetAccessor( context, gin::StringToV8(context->GetIsolate(), property), &ThrowDeprecatedAccessError); DCHECK(success.IsJust()); DCHECK(success.FromJust()); } } } RequestResult ExtensionHooksDelegate::HandleSendRequest( ScriptContext* script_context, const std::vector<v8::Local<v8::Value>>& arguments) { DCHECK_EQ(3u, arguments.size()); // This DCHECK() is correct because no context with sendRequest-related // APIs disabled should have scriptable access to a context with them // enabled. DCHECK(!messaging_util::IsSendRequestDisabled(script_context)); std::string target_id; std::string error; if (!messaging_util::GetTargetExtensionId(script_context, arguments[0], "extension.sendRequest", &target_id, &error)) { RequestResult result(RequestResult::INVALID_INVOCATION); result.error = std::move(error); return result; } v8::Local<v8::Value> v8_message = arguments[1]; std::unique_ptr<Message> message = messaging_util::MessageFromV8( script_context->v8_context(), v8_message, &error); if (!message) { RequestResult result(RequestResult::INVALID_INVOCATION); result.error = std::move(error); return result; } v8::Local<v8::Function> response_callback; if (!arguments[2]->IsNull()) response_callback = arguments[2].As<v8::Function>(); messaging_service_->SendOneTimeMessage( script_context, MessageTarget::ForExtension(target_id), messaging_util::kSendRequestChannel, false, *message, response_callback); return RequestResult(RequestResult::HANDLED); } RequestResult ExtensionHooksDelegate::HandleGetURL( ScriptContext* script_context, const std::vector<v8::Local<v8::Value>>& arguments) { DCHECK_EQ(1u, arguments.size()); DCHECK(arguments[0]->IsString()); DCHECK(script_context->extension()); std::string path = gin::V8ToString(arguments[0]); RequestResult result(RequestResult::HANDLED); result.return_value = gin::StringToV8(script_context->isolate(), script_context->extension()->GetResourceURL(path).spec()); return result; } APIBindingHooks::RequestResult ExtensionHooksDelegate::HandleGetViews( ScriptContext* script_context, const std::vector<v8::Local<v8::Value>>& arguments) { const Extension* extension = script_context->extension(); DCHECK(extension); ViewType view_type = VIEW_TYPE_INVALID; int window_id = extension_misc::kUnknownWindowId; int tab_id = extension_misc::kUnknownTabId; if (!arguments[0]->IsNull()) { gin::Dictionary options_dict(script_context->isolate(), arguments[0].As<v8::Object>()); v8::Local<v8::Value> v8_window_id; v8::Local<v8::Value> v8_tab_id; v8::Local<v8::Value> v8_view_type; if (!options_dict.Get("windowId", &v8_window_id) || !options_dict.Get("tabId", &v8_tab_id) || !options_dict.Get("type", &v8_view_type)) { NOTREACHED() << "Unexpected exception: argument parsing produces plain objects"; return RequestResult(RequestResult::THROWN); } if (!v8_window_id->IsUndefined()) { DCHECK(v8_window_id->IsInt32()); window_id = v8_window_id.As<v8::Int32>()->Value(); } if (!v8_tab_id->IsUndefined()) { DCHECK(v8_tab_id->IsInt32()); tab_id = v8_tab_id.As<v8::Int32>()->Value(); } if (!v8_view_type->IsUndefined()) { DCHECK(v8_view_type->IsString()); std::string view_type_string = base::ToUpperASCII(gin::V8ToString(v8_view_type)); if (view_type_string != "ALL") { bool success = GetViewTypeFromString(view_type_string, &view_type); DCHECK(success); } } } RequestResult result(RequestResult::HANDLED); result.return_value = ExtensionFrameHelper::GetV8MainFrames( script_context->v8_context(), extension->id(), window_id, tab_id, view_type); return result; } RequestResult ExtensionHooksDelegate::HandleGetExtensionTabs( ScriptContext* script_context, const std::vector<v8::Local<v8::Value>>& arguments) { const Extension* extension = script_context->extension(); DCHECK(extension); ViewType view_type = VIEW_TYPE_TAB_CONTENTS; int window_id = extension_misc::kUnknownWindowId; int tab_id = extension_misc::kUnknownTabId; if (!arguments[0]->IsNull()) window_id = arguments[0].As<v8::Int32>()->Value(); RequestResult result(RequestResult::HANDLED); result.return_value = ExtensionFrameHelper::GetV8MainFrames( script_context->v8_context(), extension->id(), window_id, tab_id, view_type); return result; } RequestResult ExtensionHooksDelegate::HandleGetBackgroundPage( ScriptContext* script_context, const std::vector<v8::Local<v8::Value>>& arguments) { const Extension* extension = script_context->extension(); DCHECK(extension); RequestResult result(RequestResult::HANDLED); result.return_value = ExtensionFrameHelper::GetV8BackgroundPageMainFrame( script_context->isolate(), extension->id()); return result; } } // namespace extensions
null
null
null
null
51,773
36,091
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
201,086
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * Real Time Clock interface for XScale PXA27x and PXA3xx * * Copyright (C) 2008 Robert Jarzmik * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ #include <linux/init.h> #include <linux/platform_device.h> #include <linux/module.h> #include <linux/rtc.h> #include <linux/seq_file.h> #include <linux/interrupt.h> #include <linux/io.h> #include <linux/slab.h> #include <linux/of.h> #include <linux/of_device.h> #include <mach/hardware.h> #include "rtc-sa1100.h" #define RTC_DEF_DIVIDER (32768 - 1) #define RTC_DEF_TRIM 0 #define MAXFREQ_PERIODIC 1000 /* * PXA Registers and bits definitions */ #define RTSR_PICE (1 << 15) /* Periodic interrupt count enable */ #define RTSR_PIALE (1 << 14) /* Periodic interrupt Alarm enable */ #define RTSR_PIAL (1 << 13) /* Periodic interrupt detected */ #define RTSR_SWALE2 (1 << 11) /* RTC stopwatch alarm2 enable */ #define RTSR_SWAL2 (1 << 10) /* RTC stopwatch alarm2 detected */ #define RTSR_SWALE1 (1 << 9) /* RTC stopwatch alarm1 enable */ #define RTSR_SWAL1 (1 << 8) /* RTC stopwatch alarm1 detected */ #define RTSR_RDALE2 (1 << 7) /* RTC alarm2 enable */ #define RTSR_RDAL2 (1 << 6) /* RTC alarm2 detected */ #define RTSR_RDALE1 (1 << 5) /* RTC alarm1 enable */ #define RTSR_RDAL1 (1 << 4) /* RTC alarm1 detected */ #define RTSR_HZE (1 << 3) /* HZ interrupt enable */ #define RTSR_ALE (1 << 2) /* RTC alarm interrupt enable */ #define RTSR_HZ (1 << 1) /* HZ rising-edge detected */ #define RTSR_AL (1 << 0) /* RTC alarm detected */ #define RTSR_TRIG_MASK (RTSR_AL | RTSR_HZ | RTSR_RDAL1 | RTSR_RDAL2\ | RTSR_SWAL1 | RTSR_SWAL2) #define RYxR_YEAR_S 9 #define RYxR_YEAR_MASK (0xfff << RYxR_YEAR_S) #define RYxR_MONTH_S 5 #define RYxR_MONTH_MASK (0xf << RYxR_MONTH_S) #define RYxR_DAY_MASK 0x1f #define RDxR_WOM_S 20 #define RDxR_WOM_MASK (0x7 << RDxR_WOM_S) #define RDxR_DOW_S 17 #define RDxR_DOW_MASK (0x7 << RDxR_DOW_S) #define RDxR_HOUR_S 12 #define RDxR_HOUR_MASK (0x1f << RDxR_HOUR_S) #define RDxR_MIN_S 6 #define RDxR_MIN_MASK (0x3f << RDxR_MIN_S) #define RDxR_SEC_MASK 0x3f #define RTSR 0x08 #define RTTR 0x0c #define RDCR 0x10 #define RYCR 0x14 #define RDAR1 0x18 #define RYAR1 0x1c #define RTCPICR 0x34 #define PIAR 0x38 #define rtc_readl(pxa_rtc, reg) \ __raw_readl((pxa_rtc)->base + (reg)) #define rtc_writel(pxa_rtc, reg, value) \ __raw_writel((value), (pxa_rtc)->base + (reg)) struct pxa_rtc { struct sa1100_rtc sa1100_rtc; struct resource *ress; void __iomem *base; struct rtc_device *rtc; spinlock_t lock; /* Protects this structure */ }; static u32 ryxr_calc(struct rtc_time *tm) { return ((tm->tm_year + 1900) << RYxR_YEAR_S) | ((tm->tm_mon + 1) << RYxR_MONTH_S) | tm->tm_mday; } static u32 rdxr_calc(struct rtc_time *tm) { return ((((tm->tm_mday + 6) / 7) << RDxR_WOM_S) & RDxR_WOM_MASK) | (((tm->tm_wday + 1) << RDxR_DOW_S) & RDxR_DOW_MASK) | (tm->tm_hour << RDxR_HOUR_S) | (tm->tm_min << RDxR_MIN_S) | tm->tm_sec; } static void tm_calc(u32 rycr, u32 rdcr, struct rtc_time *tm) { tm->tm_year = ((rycr & RYxR_YEAR_MASK) >> RYxR_YEAR_S) - 1900; tm->tm_mon = (((rycr & RYxR_MONTH_MASK) >> RYxR_MONTH_S)) - 1; tm->tm_mday = (rycr & RYxR_DAY_MASK); tm->tm_wday = ((rycr & RDxR_DOW_MASK) >> RDxR_DOW_S) - 1; tm->tm_hour = (rdcr & RDxR_HOUR_MASK) >> RDxR_HOUR_S; tm->tm_min = (rdcr & RDxR_MIN_MASK) >> RDxR_MIN_S; tm->tm_sec = rdcr & RDxR_SEC_MASK; } static void rtsr_clear_bits(struct pxa_rtc *pxa_rtc, u32 mask) { u32 rtsr; rtsr = rtc_readl(pxa_rtc, RTSR); rtsr &= ~RTSR_TRIG_MASK; rtsr &= ~mask; rtc_writel(pxa_rtc, RTSR, rtsr); } static void rtsr_set_bits(struct pxa_rtc *pxa_rtc, u32 mask) { u32 rtsr; rtsr = rtc_readl(pxa_rtc, RTSR); rtsr &= ~RTSR_TRIG_MASK; rtsr |= mask; rtc_writel(pxa_rtc, RTSR, rtsr); } static irqreturn_t pxa_rtc_irq(int irq, void *dev_id) { struct platform_device *pdev = to_platform_device(dev_id); struct pxa_rtc *pxa_rtc = platform_get_drvdata(pdev); u32 rtsr; unsigned long events = 0; spin_lock(&pxa_rtc->lock); /* clear interrupt sources */ rtsr = rtc_readl(pxa_rtc, RTSR); rtc_writel(pxa_rtc, RTSR, rtsr); /* temporary disable rtc interrupts */ rtsr_clear_bits(pxa_rtc, RTSR_RDALE1 | RTSR_PIALE | RTSR_HZE); /* clear alarm interrupt if it has occurred */ if (rtsr & RTSR_RDAL1) rtsr &= ~RTSR_RDALE1; /* update irq data & counter */ if (rtsr & RTSR_RDAL1) events |= RTC_AF | RTC_IRQF; if (rtsr & RTSR_HZ) events |= RTC_UF | RTC_IRQF; if (rtsr & RTSR_PIAL) events |= RTC_PF | RTC_IRQF; rtc_update_irq(pxa_rtc->rtc, 1, events); /* enable back rtc interrupts */ rtc_writel(pxa_rtc, RTSR, rtsr & ~RTSR_TRIG_MASK); spin_unlock(&pxa_rtc->lock); return IRQ_HANDLED; } static int pxa_rtc_open(struct device *dev) { struct pxa_rtc *pxa_rtc = dev_get_drvdata(dev); int ret; ret = request_irq(pxa_rtc->sa1100_rtc.irq_1hz, pxa_rtc_irq, 0, "rtc 1Hz", dev); if (ret < 0) { dev_err(dev, "can't get irq %i, err %d\n", pxa_rtc->sa1100_rtc.irq_1hz, ret); goto err_irq_1Hz; } ret = request_irq(pxa_rtc->sa1100_rtc.irq_alarm, pxa_rtc_irq, 0, "rtc Alrm", dev); if (ret < 0) { dev_err(dev, "can't get irq %i, err %d\n", pxa_rtc->sa1100_rtc.irq_alarm, ret); goto err_irq_Alrm; } return 0; err_irq_Alrm: free_irq(pxa_rtc->sa1100_rtc.irq_1hz, dev); err_irq_1Hz: return ret; } static void pxa_rtc_release(struct device *dev) { struct pxa_rtc *pxa_rtc = dev_get_drvdata(dev); spin_lock_irq(&pxa_rtc->lock); rtsr_clear_bits(pxa_rtc, RTSR_PIALE | RTSR_RDALE1 | RTSR_HZE); spin_unlock_irq(&pxa_rtc->lock); free_irq(pxa_rtc->sa1100_rtc.irq_1hz, dev); free_irq(pxa_rtc->sa1100_rtc.irq_alarm, dev); } static int pxa_alarm_irq_enable(struct device *dev, unsigned int enabled) { struct pxa_rtc *pxa_rtc = dev_get_drvdata(dev); spin_lock_irq(&pxa_rtc->lock); if (enabled) rtsr_set_bits(pxa_rtc, RTSR_RDALE1); else rtsr_clear_bits(pxa_rtc, RTSR_RDALE1); spin_unlock_irq(&pxa_rtc->lock); return 0; } static int pxa_rtc_read_time(struct device *dev, struct rtc_time *tm) { struct pxa_rtc *pxa_rtc = dev_get_drvdata(dev); u32 rycr, rdcr; rycr = rtc_readl(pxa_rtc, RYCR); rdcr = rtc_readl(pxa_rtc, RDCR); tm_calc(rycr, rdcr, tm); return 0; } static int pxa_rtc_set_time(struct device *dev, struct rtc_time *tm) { struct pxa_rtc *pxa_rtc = dev_get_drvdata(dev); rtc_writel(pxa_rtc, RYCR, ryxr_calc(tm)); rtc_writel(pxa_rtc, RDCR, rdxr_calc(tm)); return 0; } static int pxa_rtc_read_alarm(struct device *dev, struct rtc_wkalrm *alrm) { struct pxa_rtc *pxa_rtc = dev_get_drvdata(dev); u32 rtsr, ryar, rdar; ryar = rtc_readl(pxa_rtc, RYAR1); rdar = rtc_readl(pxa_rtc, RDAR1); tm_calc(ryar, rdar, &alrm->time); rtsr = rtc_readl(pxa_rtc, RTSR); alrm->enabled = (rtsr & RTSR_RDALE1) ? 1 : 0; alrm->pending = (rtsr & RTSR_RDAL1) ? 1 : 0; return 0; } static int pxa_rtc_set_alarm(struct device *dev, struct rtc_wkalrm *alrm) { struct pxa_rtc *pxa_rtc = dev_get_drvdata(dev); u32 rtsr; spin_lock_irq(&pxa_rtc->lock); rtc_writel(pxa_rtc, RYAR1, ryxr_calc(&alrm->time)); rtc_writel(pxa_rtc, RDAR1, rdxr_calc(&alrm->time)); rtsr = rtc_readl(pxa_rtc, RTSR); if (alrm->enabled) rtsr |= RTSR_RDALE1; else rtsr &= ~RTSR_RDALE1; rtc_writel(pxa_rtc, RTSR, rtsr); spin_unlock_irq(&pxa_rtc->lock); return 0; } static int pxa_rtc_proc(struct device *dev, struct seq_file *seq) { struct pxa_rtc *pxa_rtc = dev_get_drvdata(dev); seq_printf(seq, "trim/divider\t: 0x%08x\n", rtc_readl(pxa_rtc, RTTR)); seq_printf(seq, "update_IRQ\t: %s\n", (rtc_readl(pxa_rtc, RTSR) & RTSR_HZE) ? "yes" : "no"); seq_printf(seq, "periodic_IRQ\t: %s\n", (rtc_readl(pxa_rtc, RTSR) & RTSR_PIALE) ? "yes" : "no"); seq_printf(seq, "periodic_freq\t: %u\n", rtc_readl(pxa_rtc, PIAR)); return 0; } static const struct rtc_class_ops pxa_rtc_ops = { .read_time = pxa_rtc_read_time, .set_time = pxa_rtc_set_time, .read_alarm = pxa_rtc_read_alarm, .set_alarm = pxa_rtc_set_alarm, .alarm_irq_enable = pxa_alarm_irq_enable, .proc = pxa_rtc_proc, }; static int __init pxa_rtc_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; struct pxa_rtc *pxa_rtc; struct sa1100_rtc *sa1100_rtc; int ret; pxa_rtc = devm_kzalloc(dev, sizeof(*pxa_rtc), GFP_KERNEL); if (!pxa_rtc) return -ENOMEM; sa1100_rtc = &pxa_rtc->sa1100_rtc; spin_lock_init(&pxa_rtc->lock); platform_set_drvdata(pdev, pxa_rtc); pxa_rtc->ress = platform_get_resource(pdev, IORESOURCE_MEM, 0); if (!pxa_rtc->ress) { dev_err(dev, "No I/O memory resource defined\n"); return -ENXIO; } sa1100_rtc->irq_1hz = platform_get_irq(pdev, 0); if (sa1100_rtc->irq_1hz < 0) { dev_err(dev, "No 1Hz IRQ resource defined\n"); return -ENXIO; } sa1100_rtc->irq_alarm = platform_get_irq(pdev, 1); if (sa1100_rtc->irq_alarm < 0) { dev_err(dev, "No alarm IRQ resource defined\n"); return -ENXIO; } pxa_rtc_open(dev); pxa_rtc->base = devm_ioremap(dev, pxa_rtc->ress->start, resource_size(pxa_rtc->ress)); if (!pxa_rtc->base) { dev_err(dev, "Unable to map pxa RTC I/O memory\n"); return -ENOMEM; } sa1100_rtc->rcnr = pxa_rtc->base + 0x0; sa1100_rtc->rtsr = pxa_rtc->base + 0x8; sa1100_rtc->rtar = pxa_rtc->base + 0x4; sa1100_rtc->rttr = pxa_rtc->base + 0xc; ret = sa1100_rtc_init(pdev, sa1100_rtc); if (!ret) { dev_err(dev, "Unable to init SA1100 RTC sub-device\n"); return ret; } rtsr_clear_bits(pxa_rtc, RTSR_PIALE | RTSR_RDALE1 | RTSR_HZE); pxa_rtc->rtc = devm_rtc_device_register(&pdev->dev, "pxa-rtc", &pxa_rtc_ops, THIS_MODULE); if (IS_ERR(pxa_rtc->rtc)) { ret = PTR_ERR(pxa_rtc->rtc); dev_err(dev, "Failed to register RTC device -> %d\n", ret); return ret; } device_init_wakeup(dev, 1); return 0; } static int __exit pxa_rtc_remove(struct platform_device *pdev) { struct device *dev = &pdev->dev; pxa_rtc_release(dev); return 0; } #ifdef CONFIG_OF static const struct of_device_id pxa_rtc_dt_ids[] = { { .compatible = "marvell,pxa-rtc" }, {} }; MODULE_DEVICE_TABLE(of, pxa_rtc_dt_ids); #endif #ifdef CONFIG_PM_SLEEP static int pxa_rtc_suspend(struct device *dev) { struct pxa_rtc *pxa_rtc = dev_get_drvdata(dev); if (device_may_wakeup(dev)) enable_irq_wake(pxa_rtc->sa1100_rtc.irq_alarm); return 0; } static int pxa_rtc_resume(struct device *dev) { struct pxa_rtc *pxa_rtc = dev_get_drvdata(dev); if (device_may_wakeup(dev)) disable_irq_wake(pxa_rtc->sa1100_rtc.irq_alarm); return 0; } #endif static SIMPLE_DEV_PM_OPS(pxa_rtc_pm_ops, pxa_rtc_suspend, pxa_rtc_resume); static struct platform_driver pxa_rtc_driver = { .remove = __exit_p(pxa_rtc_remove), .driver = { .name = "pxa-rtc", .of_match_table = of_match_ptr(pxa_rtc_dt_ids), .pm = &pxa_rtc_pm_ops, }, }; module_platform_driver_probe(pxa_rtc_driver, pxa_rtc_probe); MODULE_AUTHOR("Robert Jarzmik <robert.jarzmik@free.fr>"); MODULE_DESCRIPTION("PXA27x/PXA3xx Realtime Clock Driver (RTC)"); MODULE_LICENSE("GPL"); MODULE_ALIAS("platform:pxa-rtc");
null
null
null
null
109,433
46
7
train_val
60253ed1e6ec6d8e5ef2efe7bf755f475dce9956
262,614
qemu
1
https://github.com/bonzini/qemu
2016-03-03 17:42:26+05:30
void rng_backend_request_entropy(RngBackend *s, size_t size, EntropyReceiveFunc *receive_entropy, void *opaque) { RngBackendClass *k = RNG_BACKEND_GET_CLASS(s); if (k->request_entropy) { k->request_entropy(s, size, receive_entropy, opaque); } }
CVE-2016-2858
CWE-119
https://git.qemu.org/?p=qemu.git;a=commit;h=60253ed1e6ec6d8e5ef2efe7bf755f475dce9956
Medium
4,287
69,243
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
69,243
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
/* Copyright (c) 2012 The Chromium Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #ifndef LIBRARIES_NACL_IO_OSSTAT_H_ #define LIBRARIES_NACL_IO_OSSTAT_H_ #include <sys/stat.h> #if defined(WIN32) #define S_IFCHR _S_IFCHR #define S_IFDIR _S_IFDIR #define S_IFIFO _S_IFIFO #define S_IFREG _S_IFREG #define S_IFMT _S_IFMT #define S_IFSOCK _S_IFIFO #define S_IREAD _S_IREAD #define S_IWRITE _S_IWRITE #define S_IEXEC _S_IEXEC #endif #endif /* LIBRARIES_NACL_IO_OSSTAT_H_ */
null
null
null
null
66,106
3,704
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
3,704
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef IOS_WEB_WEB_STATE_JS_CRW_JS_POST_REQUEST_LOADER_H_ #define IOS_WEB_WEB_STATE_JS_CRW_JS_POST_REQUEST_LOADER_H_ #import <WebKit/WebKit.h> @class CRWWKScriptMessageRouter; // Class to load POST requests in a provided web view via JavaScript. // TODO(crbug.com/740987): Remove |CRWJSPOSTRequestLoader| once iOS 10 is // dropped. @interface CRWJSPOSTRequestLoader : NSObject // Asynchronously loads a POST |request| in provided |webView|. // It temporarily installs JavaScript message routers with |messageRouter| to // handle HTTP errors. The |completionHandler| is called once the request has // been executed. In case of successful request, the passed error is nil. // The |completionHandler| must not be null. The |messageRouter| and |webView| // must not be nil. The |request| must be a POST request. - (WKNavigation*)loadPOSTRequest:(NSURLRequest*)request inWebView:(WKWebView*)webView messageRouter:(CRWWKScriptMessageRouter*)messageRouter completionHandler:(void (^)(NSError*))completionHandler; @end #endif // IOS_WEB_WEB_STATE_JS_CRW_JS_POST_REQUEST_LOADER_H_
null
null
null
null
567
59,392
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
59,392
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/api/enterprise_platform_keys/enterprise_platform_keys_api.h" #include <string> #include "base/bind.h" #include "base/location.h" #include "base/memory/ptr_util.h" #include "base/strings/stringprintf.h" #include "base/threading/thread_task_runner_handle.h" #include "base/values.h" #include "chrome/browser/chromeos/login/users/fake_chrome_user_manager.h" #include "chrome/browser/chromeos/settings/scoped_cros_settings_test_helper.h" #include "chrome/browser/chromeos/settings/stub_install_attributes.h" #include "chrome/browser/extensions/extension_function_test_utils.h" #include "chrome/browser/signin/signin_manager_factory.h" #include "chrome/browser/ui/browser.h" #include "chrome/common/pref_names.h" #include "chrome/test/base/browser_with_test_window_test.h" #include "chrome/test/base/testing_browser_process.h" #include "chrome/test/base/testing_profile_manager.h" #include "chromeos/attestation/attestation_constants.h" #include "chromeos/attestation/mock_attestation_flow.h" #include "chromeos/cryptohome/async_method_caller.h" #include "chromeos/cryptohome/mock_async_method_caller.h" #include "chromeos/dbus/dbus_method_call_status.h" #include "chromeos/dbus/fake_cryptohome_client.h" #include "components/policy/core/common/cloud/cloud_policy_constants.h" #include "components/prefs/pref_service.h" #include "components/signin/core/account_id/account_id.h" #include "components/signin/core/browser/signin_manager.h" #include "components/user_manager/scoped_user_manager.h" #include "extensions/common/extension_builder.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/cros_system_api/dbus/service_constants.h" using testing::_; using testing::Invoke; using testing::NiceMock; using testing::Return; using testing::WithArgs; namespace utils = extension_function_test_utils; namespace extensions { namespace { // Certificate errors as reported to the calling extension. const int kDBusError = 1; const int kUserRejected = 2; const int kGetCertificateFailed = 3; const int kResetRequired = 4; const char kUserEmail[] = "test@google.com"; void RegisterKeyCallbackTrue( chromeos::attestation::AttestationKeyType key_type, const cryptohome::Identification& user_id, const std::string& key_name, const cryptohome::AsyncMethodCaller::Callback& callback) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(callback, true, cryptohome::MOUNT_ERROR_NONE)); } void RegisterKeyCallbackFalse( chromeos::attestation::AttestationKeyType key_type, const cryptohome::Identification& user_id, const std::string& key_name, const cryptohome::AsyncMethodCaller::Callback& callback) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(callback, false, cryptohome::MOUNT_ERROR_NONE)); } void SignChallengeCallbackTrue( chromeos::attestation::AttestationKeyType key_type, const cryptohome::Identification& user_id, const std::string& key_name, const std::string& domain, const std::string& device_id, chromeos::attestation::AttestationChallengeOptions options, const std::string& challenge, const cryptohome::AsyncMethodCaller::DataCallback& callback) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(callback, true, "response")); } void SignChallengeCallbackFalse( chromeos::attestation::AttestationKeyType key_type, const cryptohome::Identification& user_id, const std::string& key_name, const std::string& domain, const std::string& device_id, chromeos::attestation::AttestationChallengeOptions options, const std::string& challenge, const cryptohome::AsyncMethodCaller::DataCallback& callback) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(callback, false, "")); } void GetCertificateCallbackTrue( chromeos::attestation::AttestationCertificateProfile certificate_profile, const AccountId& account_id, const std::string& request_origin, bool force_new_key, const chromeos::attestation::AttestationFlow::CertificateCallback& callback) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(callback, chromeos::attestation::ATTESTATION_SUCCESS, "certificate")); } void GetCertificateCallbackFalse( chromeos::attestation::AttestationCertificateProfile certificate_profile, const AccountId& account_id, const std::string& request_origin, bool force_new_key, const chromeos::attestation::AttestationFlow::CertificateCallback& callback) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(callback, chromeos::attestation::ATTESTATION_UNSPECIFIED_FAILURE, "")); } class EPKChallengeKeyTestBase : public BrowserWithTestWindowTest { protected: EPKChallengeKeyTestBase() : settings_helper_(false), extension_(ExtensionBuilder("Test").Build()), fake_user_manager_(new chromeos::FakeChromeUserManager), user_manager_enabler_(base::WrapUnique(fake_user_manager_)) { // Set up the default behavior of mocks. ON_CALL(mock_async_method_caller_, TpmAttestationRegisterKey(_, _, _, _)) .WillByDefault(Invoke(RegisterKeyCallbackTrue)); ON_CALL(mock_async_method_caller_, TpmAttestationSignEnterpriseChallenge(_, _, _, _, _, _, _, _)) .WillByDefault(Invoke(SignChallengeCallbackTrue)); ON_CALL(mock_attestation_flow_, GetCertificate(_, _, _, _, _)) .WillByDefault(Invoke(GetCertificateCallbackTrue)); stub_install_attributes_.SetCloudManaged("google.com", "device_id"); settings_helper_.ReplaceProvider(chromeos::kDeviceAttestationEnabled); settings_helper_.SetBoolean(chromeos::kDeviceAttestationEnabled, true); } void SetUp() override { BrowserWithTestWindowTest::SetUp(); // Set the user preferences. prefs_ = browser()->profile()->GetPrefs(); base::ListValue whitelist; whitelist.AppendString(extension_->id()); prefs_->Set(prefs::kAttestationExtensionWhitelist, whitelist); SetAuthenticatedUser(); } // This will be called by BrowserWithTestWindowTest::SetUp(); TestingProfile* CreateProfile() override { fake_user_manager_->AddUserWithAffiliation( AccountId::FromUserEmail(kUserEmail), true); return profile_manager()->CreateTestingProfile(kUserEmail); } // Derived classes can override this method to set the required authenticated // user in the SigninManager class. virtual void SetAuthenticatedUser() { SigninManagerFactory::GetForProfile(browser()->profile()) ->SetAuthenticatedAccountInfo("12345", kUserEmail); } // Like extension_function_test_utils::RunFunctionAndReturnError but with an // explicit ListValue. std::string RunFunctionAndReturnError(UIThreadExtensionFunction* function, std::unique_ptr<base::ListValue> args, Browser* browser) { utils::RunFunction(function, std::move(args), browser, extensions::api_test_utils::NONE); EXPECT_EQ(ExtensionFunction::FAILED, *function->response_type()); return function->GetError(); } // Like extension_function_test_utils::RunFunctionAndReturnSingleResult but // with an explicit ListValue. base::Value* RunFunctionAndReturnSingleResult( UIThreadExtensionFunction* function, std::unique_ptr<base::ListValue> args, Browser* browser) { scoped_refptr<ExtensionFunction> function_owner(function); // Without a callback the function will not generate a result. function->set_has_callback(true); utils::RunFunction(function, std::move(args), browser, extensions::api_test_utils::NONE); EXPECT_TRUE(function->GetError().empty()) << "Unexpected error: " << function->GetError(); const base::Value* single_result = NULL; if (function->GetResultList() != NULL && function->GetResultList()->Get(0, &single_result)) { return single_result->DeepCopy(); } return NULL; } chromeos::FakeCryptohomeClient cryptohome_client_; NiceMock<cryptohome::MockAsyncMethodCaller> mock_async_method_caller_; NiceMock<chromeos::attestation::MockAttestationFlow> mock_attestation_flow_; chromeos::ScopedCrosSettingsTestHelper settings_helper_; scoped_refptr<extensions::Extension> extension_; chromeos::StubInstallAttributes stub_install_attributes_; // fake_user_manager_ is owned by user_manager_enabler_. chromeos::FakeChromeUserManager* fake_user_manager_; user_manager::ScopedUserManager user_manager_enabler_; PrefService* prefs_ = nullptr; }; class EPKChallengeMachineKeyTest : public EPKChallengeKeyTestBase { protected: EPKChallengeMachineKeyTest() : impl_(&cryptohome_client_, &mock_async_method_caller_, &mock_attestation_flow_, &stub_install_attributes_), func_(new EnterprisePlatformKeysChallengeMachineKeyFunction(&impl_)) { func_->set_extension(extension_.get()); } // Returns an error string for the given code. std::string GetCertificateError(int error_code) { return base::StringPrintf( EPKPChallengeMachineKey::kGetCertificateFailedError, error_code); } std::unique_ptr<base::ListValue> CreateArgs() { return CreateArgsInternal(nullptr); } std::unique_ptr<base::ListValue> CreateArgsNoRegister() { return CreateArgsInternal(std::make_unique<bool>(false)); } std::unique_ptr<base::ListValue> CreateArgsRegister() { return CreateArgsInternal(std::make_unique<bool>(true)); } std::unique_ptr<base::ListValue> CreateArgsInternal( std::unique_ptr<bool> register_key) { std::unique_ptr<base::ListValue> args(new base::ListValue); args->Append(base::Value::CreateWithCopiedBuffer("challenge", 9)); if (register_key) { args->AppendBoolean(*register_key); } return args; } EPKPChallengeMachineKey impl_; scoped_refptr<EnterprisePlatformKeysChallengeMachineKeyFunction> func_; base::ListValue args_; }; TEST_F(EPKChallengeMachineKeyTest, NonEnterpriseDevice) { stub_install_attributes_.SetConsumerOwned(); EXPECT_EQ(EPKPChallengeMachineKey::kNonEnterpriseDeviceError, RunFunctionAndReturnError(func_.get(), CreateArgs(), browser())); } TEST_F(EPKChallengeMachineKeyTest, ExtensionNotWhitelisted) { base::ListValue empty_whitelist; prefs_->Set(prefs::kAttestationExtensionWhitelist, empty_whitelist); EXPECT_EQ(EPKPChallengeKeyBase::kExtensionNotWhitelistedError, RunFunctionAndReturnError(func_.get(), CreateArgs(), browser())); } TEST_F(EPKChallengeMachineKeyTest, DevicePolicyDisabled) { settings_helper_.SetBoolean(chromeos::kDeviceAttestationEnabled, false); EXPECT_EQ(EPKPChallengeKeyBase::kDevicePolicyDisabledError, RunFunctionAndReturnError(func_.get(), CreateArgs(), browser())); } TEST_F(EPKChallengeMachineKeyTest, DoesKeyExistDbusFailed) { cryptohome_client_.set_tpm_attestation_does_key_exist_should_succeed(false); EXPECT_EQ(GetCertificateError(kDBusError), RunFunctionAndReturnError(func_.get(), CreateArgs(), browser())); } TEST_F(EPKChallengeMachineKeyTest, GetCertificateFailed) { EXPECT_CALL(mock_attestation_flow_, GetCertificate(_, _, _, _, _)) .WillRepeatedly(Invoke(GetCertificateCallbackFalse)); EXPECT_EQ(GetCertificateError(kGetCertificateFailed), RunFunctionAndReturnError(func_.get(), CreateArgs(), browser())); } TEST_F(EPKChallengeMachineKeyTest, SignChallengeFailed) { EXPECT_CALL(mock_async_method_caller_, TpmAttestationSignEnterpriseChallenge(_, _, _, _, _, _, _, _)) .WillRepeatedly(Invoke(SignChallengeCallbackFalse)); EXPECT_EQ(EPKPChallengeKeyBase::kSignChallengeFailedError, RunFunctionAndReturnError(func_.get(), CreateArgs(), browser())); } TEST_F(EPKChallengeMachineKeyTest, KeyRegistrationFailed) { EXPECT_CALL(mock_async_method_caller_, TpmAttestationRegisterKey(_, _, _, _)) .WillRepeatedly(Invoke(RegisterKeyCallbackFalse)); EXPECT_EQ( EPKPChallengeMachineKey::kKeyRegistrationFailedError, RunFunctionAndReturnError(func_.get(), CreateArgsRegister(), browser())); } TEST_F(EPKChallengeMachineKeyTest, KeyExists) { cryptohome_client_.SetTpmAttestationDeviceCertificate("attest-ent-machine", std::string()); // GetCertificate must not be called if the key exists. EXPECT_CALL(mock_attestation_flow_, GetCertificate(_, _, _, _, _)).Times(0); EXPECT_TRUE(utils::RunFunction(func_.get(), CreateArgs(), browser(), extensions::api_test_utils::NONE)); } TEST_F(EPKChallengeMachineKeyTest, KeyNotRegisteredByDefault) { EXPECT_CALL(mock_async_method_caller_, TpmAttestationRegisterKey(_, _, _, _)) .Times(0); EXPECT_TRUE(utils::RunFunction(func_.get(), CreateArgs(), browser(), extensions::api_test_utils::NONE)); } TEST_F(EPKChallengeMachineKeyTest, KeyNotRegistered) { EXPECT_CALL(mock_async_method_caller_, TpmAttestationRegisterKey(_, _, _, _)) .Times(0); EXPECT_TRUE(utils::RunFunction(func_.get(), CreateArgsNoRegister(), browser(), extensions::api_test_utils::NONE)); } TEST_F(EPKChallengeMachineKeyTest, Success) { // GetCertificate must be called exactly once. EXPECT_CALL(mock_attestation_flow_, GetCertificate( chromeos::attestation::PROFILE_ENTERPRISE_MACHINE_CERTIFICATE, _, _, _, _)) .Times(1); // SignEnterpriseChallenge must be called exactly once. EXPECT_CALL( mock_async_method_caller_, TpmAttestationSignEnterpriseChallenge( chromeos::attestation::KEY_DEVICE, cryptohome::Identification(), "attest-ent-machine", "google.com", "device_id", _, "challenge", _)) .Times(1); std::unique_ptr<base::Value> value( RunFunctionAndReturnSingleResult(func_.get(), CreateArgs(), browser())); ASSERT_TRUE(value->is_blob()); EXPECT_EQ("response", std::string(value->GetBlob().data(), value->GetBlob().size())); } TEST_F(EPKChallengeMachineKeyTest, KeyRegisteredSuccess) { // GetCertificate must be called exactly once. EXPECT_CALL(mock_attestation_flow_, GetCertificate( chromeos::attestation::PROFILE_ENTERPRISE_MACHINE_CERTIFICATE, _, _, _, _)) .Times(1); // TpmAttestationRegisterKey must be called exactly once. EXPECT_CALL(mock_async_method_caller_, TpmAttestationRegisterKey(chromeos::attestation::KEY_DEVICE, _ /* Unused by the API. */, "attest-ent-machine", _)) .Times(1); // SignEnterpriseChallenge must be called exactly once. EXPECT_CALL( mock_async_method_caller_, TpmAttestationSignEnterpriseChallenge( chromeos::attestation::KEY_DEVICE, cryptohome::Identification(), "attest-ent-machine", "google.com", "device_id", _, "challenge", _)) .Times(1); std::unique_ptr<base::Value> value(RunFunctionAndReturnSingleResult( func_.get(), CreateArgsRegister(), browser())); ASSERT_TRUE(value->is_blob()); EXPECT_EQ("response", std::string(value->GetBlob().data(), value->GetBlob().size())); } TEST_F(EPKChallengeMachineKeyTest, AttestationNotPrepared) { cryptohome_client_.set_tpm_attestation_is_prepared(false); EXPECT_EQ(GetCertificateError(kResetRequired), RunFunctionAndReturnError(func_.get(), CreateArgs(), browser())); } TEST_F(EPKChallengeMachineKeyTest, AttestationPreparedDbusFailed) { cryptohome_client_.SetServiceIsAvailable(false); EXPECT_EQ(GetCertificateError(kDBusError), RunFunctionAndReturnError(func_.get(), CreateArgs(), browser())); } class EPKChallengeUserKeyTest : public EPKChallengeKeyTestBase { protected: EPKChallengeUserKeyTest() : impl_(&cryptohome_client_, &mock_async_method_caller_, &mock_attestation_flow_, &stub_install_attributes_), func_(new EnterprisePlatformKeysChallengeUserKeyFunction(&impl_)) { func_->set_extension(extension_.get()); } void SetUp() override { EPKChallengeKeyTestBase::SetUp(); // Set the user preferences. prefs_->SetBoolean(prefs::kAttestationEnabled, true); } // Returns an error string for the given code. std::string GetCertificateError(int error_code) { return base::StringPrintf(EPKPChallengeUserKey::kGetCertificateFailedError, error_code); } std::unique_ptr<base::ListValue> CreateArgs() { return CreateArgsInternal(true); } std::unique_ptr<base::ListValue> CreateArgsNoRegister() { return CreateArgsInternal(false); } std::unique_ptr<base::ListValue> CreateArgsInternal(bool register_key) { std::unique_ptr<base::ListValue> args(new base::ListValue); args->Append(base::Value::CreateWithCopiedBuffer("challenge", 9)); args->AppendBoolean(register_key); return args; } EPKPChallengeUserKey impl_; scoped_refptr<EnterprisePlatformKeysChallengeUserKeyFunction> func_; }; TEST_F(EPKChallengeUserKeyTest, UserPolicyDisabled) { prefs_->SetBoolean(prefs::kAttestationEnabled, false); EXPECT_EQ(EPKPChallengeUserKey::kUserPolicyDisabledError, RunFunctionAndReturnError(func_.get(), CreateArgs(), browser())); } TEST_F(EPKChallengeUserKeyTest, ExtensionNotWhitelisted) { base::ListValue empty_whitelist; prefs_->Set(prefs::kAttestationExtensionWhitelist, empty_whitelist); EXPECT_EQ(EPKPChallengeKeyBase::kExtensionNotWhitelistedError, RunFunctionAndReturnError(func_.get(), CreateArgs(), browser())); } TEST_F(EPKChallengeUserKeyTest, DevicePolicyDisabled) { settings_helper_.SetBoolean(chromeos::kDeviceAttestationEnabled, false); EXPECT_EQ(EPKPChallengeKeyBase::kDevicePolicyDisabledError, RunFunctionAndReturnError(func_.get(), CreateArgs(), browser())); } TEST_F(EPKChallengeUserKeyTest, DoesKeyExistDbusFailed) { cryptohome_client_.set_tpm_attestation_does_key_exist_should_succeed(false); EXPECT_EQ(GetCertificateError(kDBusError), RunFunctionAndReturnError(func_.get(), CreateArgs(), browser())); } TEST_F(EPKChallengeUserKeyTest, GetCertificateFailed) { EXPECT_CALL(mock_attestation_flow_, GetCertificate(_, _, _, _, _)) .WillRepeatedly(Invoke(GetCertificateCallbackFalse)); EXPECT_EQ(GetCertificateError(kGetCertificateFailed), RunFunctionAndReturnError(func_.get(), CreateArgs(), browser())); } TEST_F(EPKChallengeUserKeyTest, SignChallengeFailed) { EXPECT_CALL(mock_async_method_caller_, TpmAttestationSignEnterpriseChallenge(_, _, _, _, _, _, _, _)) .WillRepeatedly(Invoke(SignChallengeCallbackFalse)); EXPECT_EQ(EPKPChallengeKeyBase::kSignChallengeFailedError, RunFunctionAndReturnError(func_.get(), CreateArgs(), browser())); } TEST_F(EPKChallengeUserKeyTest, KeyRegistrationFailed) { EXPECT_CALL(mock_async_method_caller_, TpmAttestationRegisterKey(_, _, _, _)) .WillRepeatedly(Invoke(RegisterKeyCallbackFalse)); EXPECT_EQ(EPKPChallengeUserKey::kKeyRegistrationFailedError, RunFunctionAndReturnError(func_.get(), CreateArgs(), browser())); } TEST_F(EPKChallengeUserKeyTest, KeyExists) { cryptohome_client_.SetTpmAttestationUserCertificate( cryptohome::Identification(AccountId::FromUserEmail(kUserEmail)), "attest-ent-user", std::string()); // GetCertificate must not be called if the key exists. EXPECT_CALL(mock_attestation_flow_, GetCertificate(_, _, _, _, _)).Times(0); EXPECT_TRUE(utils::RunFunction(func_.get(), CreateArgs(), browser(), extensions::api_test_utils::NONE)); } TEST_F(EPKChallengeUserKeyTest, KeyNotRegistered) { EXPECT_CALL(mock_async_method_caller_, TpmAttestationRegisterKey(_, _, _, _)) .Times(0); EXPECT_TRUE(utils::RunFunction(func_.get(), CreateArgsNoRegister(), browser(), extensions::api_test_utils::NONE)); } TEST_F(EPKChallengeUserKeyTest, PersonalDevice) { stub_install_attributes_.SetConsumerOwned(); // Currently personal devices are not supported. EXPECT_EQ(GetCertificateError(kUserRejected), RunFunctionAndReturnError(func_.get(), CreateArgs(), browser())); } TEST_F(EPKChallengeUserKeyTest, Success) { // GetCertificate must be called exactly once. EXPECT_CALL( mock_attestation_flow_, GetCertificate(chromeos::attestation::PROFILE_ENTERPRISE_USER_CERTIFICATE, _, _, _, _)) .Times(1); const cryptohome::Identification cryptohome_id( AccountId::FromUserEmail(kUserEmail)); // SignEnterpriseChallenge must be called exactly once. EXPECT_CALL( mock_async_method_caller_, TpmAttestationSignEnterpriseChallenge( chromeos::attestation::KEY_USER, cryptohome_id, "attest-ent-user", kUserEmail, "device_id", _, "challenge", _)) .Times(1); // RegisterKey must be called exactly once. EXPECT_CALL(mock_async_method_caller_, TpmAttestationRegisterKey(chromeos::attestation::KEY_USER, cryptohome_id, "attest-ent-user", _)) .Times(1); std::unique_ptr<base::Value> value( RunFunctionAndReturnSingleResult(func_.get(), CreateArgs(), browser())); ASSERT_TRUE(value->is_blob()); EXPECT_EQ("response", std::string(value->GetBlob().data(), value->GetBlob().size())); } TEST_F(EPKChallengeUserKeyTest, AttestationNotPrepared) { cryptohome_client_.set_tpm_attestation_is_prepared(false); EXPECT_EQ(GetCertificateError(kResetRequired), RunFunctionAndReturnError(func_.get(), CreateArgs(), browser())); } TEST_F(EPKChallengeUserKeyTest, AttestationPreparedDbusFailed) { cryptohome_client_.SetServiceIsAvailable(false); EXPECT_EQ(GetCertificateError(kDBusError), RunFunctionAndReturnError(func_.get(), CreateArgs(), browser())); } class EPKChallengeMachineKeyUnmanagedUserTest : public EPKChallengeMachineKeyTest { protected: void SetAuthenticatedUser() override { SigninManagerFactory::GetForProfile(browser()->profile()) ->SetAuthenticatedAccountInfo(account_id_.GetGaiaId(), account_id_.GetUserEmail()); } TestingProfile* CreateProfile() override { fake_user_manager_->AddUser(account_id_); return profile_manager()->CreateTestingProfile(account_id_.GetUserEmail()); } const AccountId account_id_ = AccountId::FromUserEmailGaiaId("test@chromium.com", "12345"); }; TEST_F(EPKChallengeMachineKeyUnmanagedUserTest, UserNotManaged) { EXPECT_EQ(EPKPChallengeKeyBase::kUserNotManaged, RunFunctionAndReturnError(func_.get(), CreateArgs(), browser())); } class EPKChallengeUserKeyUnmanagedUserTest : public EPKChallengeUserKeyTest { protected: void SetAuthenticatedUser() override { SigninManagerFactory::GetForProfile(browser()->profile()) ->SetAuthenticatedAccountInfo(account_id_.GetGaiaId(), account_id_.GetUserEmail()); } TestingProfile* CreateProfile() override { fake_user_manager_->AddUser(account_id_); return profile_manager()->CreateTestingProfile(account_id_.GetUserEmail()); } const AccountId account_id_ = AccountId::FromUserEmailGaiaId("test@chromium.com", "12345"); }; TEST_F(EPKChallengeUserKeyUnmanagedUserTest, UserNotManaged) { EXPECT_EQ(EPKPChallengeKeyBase::kUserNotManaged, RunFunctionAndReturnError(func_.get(), CreateArgs(), browser())); } } // namespace } // namespace extensions
null
null
null
null
56,255
60,072
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
60,072
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright 2017 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/offline_pages/prefetch/prefetch_background_task_handler_impl.h" #include "base/time/time.h" #include "chrome/browser/offline_pages/prefetch/prefetch_background_task_scheduler.h" #include "chrome/common/pref_names.h" #include "components/offline_pages/core/offline_page_feature.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/pref_service.h" #include "net/base/backoff_entry_serializer.h" namespace offline_pages { namespace { const int kDefaultSuspensionDays = 1; const net::BackoffEntry::Policy kPrefetchBackoffPolicy = { 0, // Number of initial errors to ignore without backoff. 30 * 1000, // Initial delay for backoff in ms: 30 seconds. 2, // Factor to multiply for exponential backoff. 0.33, // Fuzzing percentage. 24 * 3600 * 1000, // Maximum time to delay requests in ms: 1 day. -1, // Don't discard entry even if unused. false // Don't use initial delay unless the last was an error. }; } // namespace PrefetchBackgroundTaskHandlerImpl::PrefetchBackgroundTaskHandlerImpl( PrefService* prefs) : prefs_(prefs) {} PrefetchBackgroundTaskHandlerImpl::~PrefetchBackgroundTaskHandlerImpl() = default; void PrefetchBackgroundTaskHandlerImpl::CancelBackgroundTask() { PrefetchBackgroundTaskScheduler::Cancel(); } void PrefetchBackgroundTaskHandlerImpl::EnsureTaskScheduled() { if (IsLimitlessPrefetchingEnabled()) { PrefetchBackgroundTaskScheduler::ScheduleLimitless( GetAdditionalBackoffSeconds()); } else { PrefetchBackgroundTaskScheduler::Schedule(GetAdditionalBackoffSeconds()); } } int PrefetchBackgroundTaskHandlerImpl::GetAdditionalBackoffSeconds() const { return static_cast<int>( GetCurrentBackoff()->GetTimeUntilRelease().InSeconds()); } std::unique_ptr<net::BackoffEntry> PrefetchBackgroundTaskHandlerImpl::GetCurrentBackoff() const { const base::ListValue* value = prefs_->GetList(prefs::kOfflinePrefetchBackoff); std::unique_ptr<net::BackoffEntry> result; if (value) { result = net::BackoffEntrySerializer::DeserializeFromValue( *value, &kPrefetchBackoffPolicy, clock_, base::Time::Now()); } if (!result) return std::make_unique<net::BackoffEntry>(&kPrefetchBackoffPolicy, clock_); return result; } void PrefetchBackgroundTaskHandlerImpl::Backoff() { std::unique_ptr<net::BackoffEntry> current = GetCurrentBackoff(); current->InformOfRequest(false); UpdateBackoff(current.get()); } void PrefetchBackgroundTaskHandlerImpl::ResetBackoff() { std::unique_ptr<net::BackoffEntry> current = GetCurrentBackoff(); current->Reset(); UpdateBackoff(current.get()); } void PrefetchBackgroundTaskHandlerImpl::PauseBackoffUntilNextRun() { std::unique_ptr<net::BackoffEntry> current = GetCurrentBackoff(); // Erase the existing delay but retain the failure count so that the next // time we run if backoff is requested again we will continue the exponential // backoff from where we left off. current->SetCustomReleaseTime(base::TimeTicks::Now()); UpdateBackoff(current.get()); } void PrefetchBackgroundTaskHandlerImpl::Suspend() { std::unique_ptr<net::BackoffEntry> current = GetCurrentBackoff(); // Set the failure count to 0. current->Reset(); // Set a custom delay to be a 1 day interval. After the day passes, the next // backoff value will be back to the initial 30s delay. current->SetCustomReleaseTime( base::TimeTicks::Now() + base::TimeDelta::FromDays(kDefaultSuspensionDays)); UpdateBackoff(current.get()); } void PrefetchBackgroundTaskHandlerImpl::RemoveSuspension() { std::unique_ptr<net::BackoffEntry> current = GetCurrentBackoff(); // Reset the backoff completely, but only if the failure count is 0 and there // is a custom delay. This should only happen after Suspend() has been called. if (current->failure_count() == 0 && !current->GetReleaseTime().is_null()) current->Reset(); UpdateBackoff(current.get()); } void PrefetchBackgroundTaskHandlerImpl::SetTickClockForTesting( const base::TickClock* clock) { clock_ = clock; } void PrefetchBackgroundTaskHandlerImpl::UpdateBackoff( net::BackoffEntry* backoff) { std::unique_ptr<base::Value> value = net::BackoffEntrySerializer::SerializeToValue(*backoff, base::Time::Now()); prefs_->Set(prefs::kOfflinePrefetchBackoff, *value); } void RegisterPrefetchBackgroundTaskPrefs(PrefRegistrySimple* registry) { registry->RegisterListPref(prefs::kOfflinePrefetchBackoff); } } // namespace offline_pages
null
null
null
null
56,935
29,791
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
29,791
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
/* ** 2014 May 31 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** */ #ifndef _FTS5INT_H #define _FTS5INT_H #include "fts5.h" #include "sqlite3ext.h" SQLITE_EXTENSION_INIT1 #include <string.h> #include <assert.h> #ifndef SQLITE_AMALGAMATION typedef unsigned char u8; typedef unsigned int u32; typedef unsigned short u16; typedef short i16; typedef sqlite3_int64 i64; typedef sqlite3_uint64 u64; #ifndef ArraySize # define ArraySize(x) ((int)(sizeof(x) / sizeof(x[0]))) #endif #define testcase(x) #define ALWAYS(x) 1 #define NEVER(x) 0 #define MIN(x,y) (((x) < (y)) ? (x) : (y)) #define MAX(x,y) (((x) > (y)) ? (x) : (y)) /* ** Constants for the largest and smallest possible 64-bit signed integers. */ # define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32)) # define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64) #endif /* Truncate very long tokens to this many bytes. Hard limit is ** (65536-1-1-4-9)==65521 bytes. The limiting factor is the 16-bit offset ** field that occurs at the start of each leaf page (see fts5_index.c). */ #define FTS5_MAX_TOKEN_SIZE 32768 /* ** Maximum number of prefix indexes on single FTS5 table. This must be ** less than 32. If it is set to anything large than that, an #error ** directive in fts5_index.c will cause the build to fail. */ #define FTS5_MAX_PREFIX_INDEXES 31 #define FTS5_DEFAULT_NEARDIST 10 #define FTS5_DEFAULT_RANK "bm25" /* Name of rank and rowid columns */ #define FTS5_RANK_NAME "rank" #define FTS5_ROWID_NAME "rowid" #ifdef SQLITE_DEBUG # define FTS5_CORRUPT sqlite3Fts5Corrupt() int sqlite3Fts5Corrupt(void); #else # define FTS5_CORRUPT SQLITE_CORRUPT_VTAB #endif /* ** The assert_nc() macro is similar to the assert() macro, except that it ** is used for assert() conditions that are true only if it can be ** guranteed that the database is not corrupt. */ #ifdef SQLITE_DEBUG extern int sqlite3_fts5_may_be_corrupt; # define assert_nc(x) assert(sqlite3_fts5_may_be_corrupt || (x)) #else # define assert_nc(x) assert(x) #endif /* Mark a function parameter as unused, to suppress nuisance compiler ** warnings. */ #ifndef UNUSED_PARAM # define UNUSED_PARAM(X) (void)(X) #endif #ifndef UNUSED_PARAM2 # define UNUSED_PARAM2(X, Y) (void)(X), (void)(Y) #endif typedef struct Fts5Global Fts5Global; typedef struct Fts5Colset Fts5Colset; /* If a NEAR() clump or phrase may only match a specific set of columns, ** then an object of the following type is used to record the set of columns. ** Each entry in the aiCol[] array is a column that may be matched. ** ** This object is used by fts5_expr.c and fts5_index.c. */ struct Fts5Colset { int nCol; int aiCol[1]; }; /************************************************************************** ** Interface to code in fts5_config.c. fts5_config.c contains contains code ** to parse the arguments passed to the CREATE VIRTUAL TABLE statement. */ typedef struct Fts5Config Fts5Config; /* ** An instance of the following structure encodes all information that can ** be gleaned from the CREATE VIRTUAL TABLE statement. ** ** And all information loaded from the %_config table. ** ** nAutomerge: ** The minimum number of segments that an auto-merge operation should ** attempt to merge together. A value of 1 sets the object to use the ** compile time default. Zero disables auto-merge altogether. ** ** zContent: ** ** zContentRowid: ** The value of the content_rowid= option, if one was specified. Or ** the string "rowid" otherwise. This text is not quoted - if it is ** used as part of an SQL statement it needs to be quoted appropriately. ** ** zContentExprlist: ** ** pzErrmsg: ** This exists in order to allow the fts5_index.c module to return a ** decent error message if it encounters a file-format version it does ** not understand. ** ** bColumnsize: ** True if the %_docsize table is created. ** ** bPrefixIndex: ** This is only used for debugging. If set to false, any prefix indexes ** are ignored. This value is configured using: ** ** INSERT INTO tbl(tbl, rank) VALUES('prefix-index', $bPrefixIndex); ** */ struct Fts5Config { sqlite3 *db; /* Database handle */ char *zDb; /* Database holding FTS index (e.g. "main") */ char *zName; /* Name of FTS index */ int nCol; /* Number of columns */ char **azCol; /* Column names */ u8 *abUnindexed; /* True for unindexed columns */ int nPrefix; /* Number of prefix indexes */ int *aPrefix; /* Sizes in bytes of nPrefix prefix indexes */ int eContent; /* An FTS5_CONTENT value */ char *zContent; /* content table */ char *zContentRowid; /* "content_rowid=" option value */ int bColumnsize; /* "columnsize=" option value (dflt==1) */ int eDetail; /* FTS5_DETAIL_XXX value */ char *zContentExprlist; Fts5Tokenizer *pTok; fts5_tokenizer *pTokApi; /* Values loaded from the %_config table */ int iCookie; /* Incremented when %_config is modified */ int pgsz; /* Approximate page size used in %_data */ int nAutomerge; /* 'automerge' setting */ int nCrisisMerge; /* Maximum allowed segments per level */ int nUsermerge; /* 'usermerge' setting */ int nHashSize; /* Bytes of memory for in-memory hash */ char *zRank; /* Name of rank function */ char *zRankArgs; /* Arguments to rank function */ /* If non-NULL, points to sqlite3_vtab.base.zErrmsg. Often NULL. */ char **pzErrmsg; #ifdef SQLITE_DEBUG int bPrefixIndex; /* True to use prefix-indexes */ #endif }; /* Current expected value of %_config table 'version' field */ #define FTS5_CURRENT_VERSION 4 #define FTS5_CONTENT_NORMAL 0 #define FTS5_CONTENT_NONE 1 #define FTS5_CONTENT_EXTERNAL 2 #define FTS5_DETAIL_FULL 0 #define FTS5_DETAIL_NONE 1 #define FTS5_DETAIL_COLUMNS 2 int sqlite3Fts5ConfigParse( Fts5Global*, sqlite3*, int, const char **, Fts5Config**, char** ); void sqlite3Fts5ConfigFree(Fts5Config*); int sqlite3Fts5ConfigDeclareVtab(Fts5Config *pConfig); int sqlite3Fts5Tokenize( Fts5Config *pConfig, /* FTS5 Configuration object */ int flags, /* FTS5_TOKENIZE_* flags */ const char *pText, int nText, /* Text to tokenize */ void *pCtx, /* Context passed to xToken() */ int (*xToken)(void*, int, const char*, int, int, int) /* Callback */ ); void sqlite3Fts5Dequote(char *z); /* Load the contents of the %_config table */ int sqlite3Fts5ConfigLoad(Fts5Config*, int); /* Set the value of a single config attribute */ int sqlite3Fts5ConfigSetValue(Fts5Config*, const char*, sqlite3_value*, int*); int sqlite3Fts5ConfigParseRank(const char*, char**, char**); /* ** End of interface to code in fts5_config.c. **************************************************************************/ /************************************************************************** ** Interface to code in fts5_buffer.c. */ /* ** Buffer object for the incremental building of string data. */ typedef struct Fts5Buffer Fts5Buffer; struct Fts5Buffer { u8 *p; int n; int nSpace; }; int sqlite3Fts5BufferSize(int*, Fts5Buffer*, u32); void sqlite3Fts5BufferAppendVarint(int*, Fts5Buffer*, i64); void sqlite3Fts5BufferAppendBlob(int*, Fts5Buffer*, u32, const u8*); void sqlite3Fts5BufferAppendString(int *, Fts5Buffer*, const char*); void sqlite3Fts5BufferFree(Fts5Buffer*); void sqlite3Fts5BufferZero(Fts5Buffer*); void sqlite3Fts5BufferSet(int*, Fts5Buffer*, int, const u8*); void sqlite3Fts5BufferAppendPrintf(int *, Fts5Buffer*, char *zFmt, ...); char *sqlite3Fts5Mprintf(int *pRc, const char *zFmt, ...); #define fts5BufferZero(x) sqlite3Fts5BufferZero(x) #define fts5BufferAppendVarint(a,b,c) sqlite3Fts5BufferAppendVarint(a,b,c) #define fts5BufferFree(a) sqlite3Fts5BufferFree(a) #define fts5BufferAppendBlob(a,b,c,d) sqlite3Fts5BufferAppendBlob(a,b,c,d) #define fts5BufferSet(a,b,c,d) sqlite3Fts5BufferSet(a,b,c,d) #define fts5BufferGrow(pRc,pBuf,nn) ( \ (u32)((pBuf)->n) + (u32)(nn) <= (u32)((pBuf)->nSpace) ? 0 : \ sqlite3Fts5BufferSize((pRc),(pBuf),(nn)+(pBuf)->n) \ ) /* Write and decode big-endian 32-bit integer values */ void sqlite3Fts5Put32(u8*, int); int sqlite3Fts5Get32(const u8*); #define FTS5_POS2COLUMN(iPos) (int)(iPos >> 32) #define FTS5_POS2OFFSET(iPos) (int)(iPos & 0xFFFFFFFF) typedef struct Fts5PoslistReader Fts5PoslistReader; struct Fts5PoslistReader { /* Variables used only by sqlite3Fts5PoslistIterXXX() functions. */ const u8 *a; /* Position list to iterate through */ int n; /* Size of buffer at a[] in bytes */ int i; /* Current offset in a[] */ u8 bFlag; /* For client use (any custom purpose) */ /* Output variables */ u8 bEof; /* Set to true at EOF */ i64 iPos; /* (iCol<<32) + iPos */ }; int sqlite3Fts5PoslistReaderInit( const u8 *a, int n, /* Poslist buffer to iterate through */ Fts5PoslistReader *pIter /* Iterator object to initialize */ ); int sqlite3Fts5PoslistReaderNext(Fts5PoslistReader*); typedef struct Fts5PoslistWriter Fts5PoslistWriter; struct Fts5PoslistWriter { i64 iPrev; }; int sqlite3Fts5PoslistWriterAppend(Fts5Buffer*, Fts5PoslistWriter*, i64); void sqlite3Fts5PoslistSafeAppend(Fts5Buffer*, i64*, i64); int sqlite3Fts5PoslistNext64( const u8 *a, int n, /* Buffer containing poslist */ int *pi, /* IN/OUT: Offset within a[] */ i64 *piOff /* IN/OUT: Current offset */ ); /* Malloc utility */ void *sqlite3Fts5MallocZero(int *pRc, int nByte); char *sqlite3Fts5Strndup(int *pRc, const char *pIn, int nIn); /* Character set tests (like isspace(), isalpha() etc.) */ int sqlite3Fts5IsBareword(char t); /* Bucket of terms object used by the integrity-check in offsets=0 mode. */ typedef struct Fts5Termset Fts5Termset; int sqlite3Fts5TermsetNew(Fts5Termset**); int sqlite3Fts5TermsetAdd(Fts5Termset*, int, const char*, int, int *pbPresent); void sqlite3Fts5TermsetFree(Fts5Termset*); /* ** End of interface to code in fts5_buffer.c. **************************************************************************/ /************************************************************************** ** Interface to code in fts5_index.c. fts5_index.c contains contains code ** to access the data stored in the %_data table. */ typedef struct Fts5Index Fts5Index; typedef struct Fts5IndexIter Fts5IndexIter; struct Fts5IndexIter { i64 iRowid; const u8 *pData; int nData; u8 bEof; }; #define sqlite3Fts5IterEof(x) ((x)->bEof) /* ** Values used as part of the flags argument passed to IndexQuery(). */ #define FTS5INDEX_QUERY_PREFIX 0x0001 /* Prefix query */ #define FTS5INDEX_QUERY_DESC 0x0002 /* Docs in descending rowid order */ #define FTS5INDEX_QUERY_TEST_NOIDX 0x0004 /* Do not use prefix index */ #define FTS5INDEX_QUERY_SCAN 0x0008 /* Scan query (fts5vocab) */ /* The following are used internally by the fts5_index.c module. They are ** defined here only to make it easier to avoid clashes with the flags ** above. */ #define FTS5INDEX_QUERY_SKIPEMPTY 0x0010 #define FTS5INDEX_QUERY_NOOUTPUT 0x0020 /* ** Create/destroy an Fts5Index object. */ int sqlite3Fts5IndexOpen(Fts5Config *pConfig, int bCreate, Fts5Index**, char**); int sqlite3Fts5IndexClose(Fts5Index *p); /* ** Return a simple checksum value based on the arguments. */ u64 sqlite3Fts5IndexEntryCksum( i64 iRowid, int iCol, int iPos, int iIdx, const char *pTerm, int nTerm ); /* ** Argument p points to a buffer containing utf-8 text that is n bytes in ** size. Return the number of bytes in the nChar character prefix of the ** buffer, or 0 if there are less than nChar characters in total. */ int sqlite3Fts5IndexCharlenToBytelen( const char *p, int nByte, int nChar ); /* ** Open a new iterator to iterate though all rowids that match the ** specified token or token prefix. */ int sqlite3Fts5IndexQuery( Fts5Index *p, /* FTS index to query */ const char *pToken, int nToken, /* Token (or prefix) to query for */ int flags, /* Mask of FTS5INDEX_QUERY_X flags */ Fts5Colset *pColset, /* Match these columns only */ Fts5IndexIter **ppIter /* OUT: New iterator object */ ); /* ** The various operations on open token or token prefix iterators opened ** using sqlite3Fts5IndexQuery(). */ int sqlite3Fts5IterNext(Fts5IndexIter*); int sqlite3Fts5IterNextFrom(Fts5IndexIter*, i64 iMatch); /* ** Close an iterator opened by sqlite3Fts5IndexQuery(). */ void sqlite3Fts5IterClose(Fts5IndexIter*); /* ** This interface is used by the fts5vocab module. */ const char *sqlite3Fts5IterTerm(Fts5IndexIter*, int*); int sqlite3Fts5IterNextScan(Fts5IndexIter*); /* ** Insert or remove data to or from the index. Each time a document is ** added to or removed from the index, this function is called one or more ** times. ** ** For an insert, it must be called once for each token in the new document. ** If the operation is a delete, it must be called (at least) once for each ** unique token in the document with an iCol value less than zero. The iPos ** argument is ignored for a delete. */ int sqlite3Fts5IndexWrite( Fts5Index *p, /* Index to write to */ int iCol, /* Column token appears in (-ve -> delete) */ int iPos, /* Position of token within column */ const char *pToken, int nToken /* Token to add or remove to or from index */ ); /* ** Indicate that subsequent calls to sqlite3Fts5IndexWrite() pertain to ** document iDocid. */ int sqlite3Fts5IndexBeginWrite( Fts5Index *p, /* Index to write to */ int bDelete, /* True if current operation is a delete */ i64 iDocid /* Docid to add or remove data from */ ); /* ** Flush any data stored in the in-memory hash tables to the database. ** Also close any open blob handles. */ int sqlite3Fts5IndexSync(Fts5Index *p); /* ** Discard any data stored in the in-memory hash tables. Do not write it ** to the database. Additionally, assume that the contents of the %_data ** table may have changed on disk. So any in-memory caches of %_data ** records must be invalidated. */ int sqlite3Fts5IndexRollback(Fts5Index *p); /* ** Get or set the "averages" values. */ int sqlite3Fts5IndexGetAverages(Fts5Index *p, i64 *pnRow, i64 *anSize); int sqlite3Fts5IndexSetAverages(Fts5Index *p, const u8*, int); /* ** Functions called by the storage module as part of integrity-check. */ int sqlite3Fts5IndexIntegrityCheck(Fts5Index*, u64 cksum); /* ** Called during virtual module initialization to register UDF ** fts5_decode() with SQLite */ int sqlite3Fts5IndexInit(sqlite3*); int sqlite3Fts5IndexSetCookie(Fts5Index*, int); /* ** Return the total number of entries read from the %_data table by ** this connection since it was created. */ int sqlite3Fts5IndexReads(Fts5Index *p); int sqlite3Fts5IndexReinit(Fts5Index *p); int sqlite3Fts5IndexOptimize(Fts5Index *p); int sqlite3Fts5IndexMerge(Fts5Index *p, int nMerge); int sqlite3Fts5IndexReset(Fts5Index *p); int sqlite3Fts5IndexLoadConfig(Fts5Index *p); /* ** End of interface to code in fts5_index.c. **************************************************************************/ /************************************************************************** ** Interface to code in fts5_varint.c. */ int sqlite3Fts5GetVarint32(const unsigned char *p, u32 *v); int sqlite3Fts5GetVarintLen(u32 iVal); u8 sqlite3Fts5GetVarint(const unsigned char*, u64*); int sqlite3Fts5PutVarint(unsigned char *p, u64 v); #define fts5GetVarint32(a,b) sqlite3Fts5GetVarint32(a,(u32*)&b) #define fts5GetVarint sqlite3Fts5GetVarint #define fts5FastGetVarint32(a, iOff, nVal) { \ nVal = (a)[iOff++]; \ if( nVal & 0x80 ){ \ iOff--; \ iOff += fts5GetVarint32(&(a)[iOff], nVal); \ } \ } /* ** End of interface to code in fts5_varint.c. **************************************************************************/ /************************************************************************** ** Interface to code in fts5.c. */ int sqlite3Fts5GetTokenizer( Fts5Global*, const char **azArg, int nArg, Fts5Tokenizer**, fts5_tokenizer**, char **pzErr ); Fts5Index *sqlite3Fts5IndexFromCsrid(Fts5Global*, i64, Fts5Config **); /* ** End of interface to code in fts5.c. **************************************************************************/ /************************************************************************** ** Interface to code in fts5_hash.c. */ typedef struct Fts5Hash Fts5Hash; /* ** Create a hash table, free a hash table. */ int sqlite3Fts5HashNew(Fts5Config*, Fts5Hash**, int *pnSize); void sqlite3Fts5HashFree(Fts5Hash*); int sqlite3Fts5HashWrite( Fts5Hash*, i64 iRowid, /* Rowid for this entry */ int iCol, /* Column token appears in (-ve -> delete) */ int iPos, /* Position of token within column */ char bByte, const char *pToken, int nToken /* Token to add or remove to or from index */ ); /* ** Empty (but do not delete) a hash table. */ void sqlite3Fts5HashClear(Fts5Hash*); int sqlite3Fts5HashQuery( Fts5Hash*, /* Hash table to query */ const char *pTerm, int nTerm, /* Query term */ const u8 **ppDoclist, /* OUT: Pointer to doclist for pTerm */ int *pnDoclist /* OUT: Size of doclist in bytes */ ); int sqlite3Fts5HashScanInit( Fts5Hash*, /* Hash table to query */ const char *pTerm, int nTerm /* Query prefix */ ); void sqlite3Fts5HashScanNext(Fts5Hash*); int sqlite3Fts5HashScanEof(Fts5Hash*); void sqlite3Fts5HashScanEntry(Fts5Hash *, const char **pzTerm, /* OUT: term (nul-terminated) */ const u8 **ppDoclist, /* OUT: pointer to doclist */ int *pnDoclist /* OUT: size of doclist in bytes */ ); /* ** End of interface to code in fts5_hash.c. **************************************************************************/ /************************************************************************** ** Interface to code in fts5_storage.c. fts5_storage.c contains contains ** code to access the data stored in the %_content and %_docsize tables. */ #define FTS5_STMT_SCAN_ASC 0 /* SELECT rowid, * FROM ... ORDER BY 1 ASC */ #define FTS5_STMT_SCAN_DESC 1 /* SELECT rowid, * FROM ... ORDER BY 1 DESC */ #define FTS5_STMT_LOOKUP 2 /* SELECT rowid, * FROM ... WHERE rowid=? */ typedef struct Fts5Storage Fts5Storage; int sqlite3Fts5StorageOpen(Fts5Config*, Fts5Index*, int, Fts5Storage**, char**); int sqlite3Fts5StorageClose(Fts5Storage *p); int sqlite3Fts5StorageRename(Fts5Storage*, const char *zName); int sqlite3Fts5DropAll(Fts5Config*); int sqlite3Fts5CreateTable(Fts5Config*, const char*, const char*, int, char **); int sqlite3Fts5StorageDelete(Fts5Storage *p, i64, sqlite3_value**); int sqlite3Fts5StorageContentInsert(Fts5Storage *p, sqlite3_value**, i64*); int sqlite3Fts5StorageIndexInsert(Fts5Storage *p, sqlite3_value**, i64); int sqlite3Fts5StorageIntegrity(Fts5Storage *p); int sqlite3Fts5StorageStmt(Fts5Storage *p, int eStmt, sqlite3_stmt**, char**); void sqlite3Fts5StorageStmtRelease(Fts5Storage *p, int eStmt, sqlite3_stmt*); int sqlite3Fts5StorageDocsize(Fts5Storage *p, i64 iRowid, int *aCol); int sqlite3Fts5StorageSize(Fts5Storage *p, int iCol, i64 *pnAvg); int sqlite3Fts5StorageRowCount(Fts5Storage *p, i64 *pnRow); int sqlite3Fts5StorageSync(Fts5Storage *p); int sqlite3Fts5StorageRollback(Fts5Storage *p); int sqlite3Fts5StorageConfigValue( Fts5Storage *p, const char*, sqlite3_value*, int ); int sqlite3Fts5StorageDeleteAll(Fts5Storage *p); int sqlite3Fts5StorageRebuild(Fts5Storage *p); int sqlite3Fts5StorageOptimize(Fts5Storage *p); int sqlite3Fts5StorageMerge(Fts5Storage *p, int nMerge); int sqlite3Fts5StorageReset(Fts5Storage *p); /* ** End of interface to code in fts5_storage.c. **************************************************************************/ /************************************************************************** ** Interface to code in fts5_expr.c. */ typedef struct Fts5Expr Fts5Expr; typedef struct Fts5ExprNode Fts5ExprNode; typedef struct Fts5Parse Fts5Parse; typedef struct Fts5Token Fts5Token; typedef struct Fts5ExprPhrase Fts5ExprPhrase; typedef struct Fts5ExprNearset Fts5ExprNearset; struct Fts5Token { const char *p; /* Token text (not NULL terminated) */ int n; /* Size of buffer p in bytes */ }; /* Parse a MATCH expression. */ int sqlite3Fts5ExprNew( Fts5Config *pConfig, int iCol, /* Column on LHS of MATCH operator */ const char *zExpr, Fts5Expr **ppNew, char **pzErr ); /* ** for(rc = sqlite3Fts5ExprFirst(pExpr, pIdx, bDesc); ** rc==SQLITE_OK && 0==sqlite3Fts5ExprEof(pExpr); ** rc = sqlite3Fts5ExprNext(pExpr) ** ){ ** // The document with rowid iRowid matches the expression! ** i64 iRowid = sqlite3Fts5ExprRowid(pExpr); ** } */ int sqlite3Fts5ExprFirst(Fts5Expr*, Fts5Index *pIdx, i64 iMin, int bDesc); int sqlite3Fts5ExprNext(Fts5Expr*, i64 iMax); int sqlite3Fts5ExprEof(Fts5Expr*); i64 sqlite3Fts5ExprRowid(Fts5Expr*); void sqlite3Fts5ExprFree(Fts5Expr*); /* Called during startup to register a UDF with SQLite */ int sqlite3Fts5ExprInit(Fts5Global*, sqlite3*); int sqlite3Fts5ExprPhraseCount(Fts5Expr*); int sqlite3Fts5ExprPhraseSize(Fts5Expr*, int iPhrase); int sqlite3Fts5ExprPoslist(Fts5Expr*, int, const u8 **); typedef struct Fts5PoslistPopulator Fts5PoslistPopulator; Fts5PoslistPopulator *sqlite3Fts5ExprClearPoslists(Fts5Expr*, int); int sqlite3Fts5ExprPopulatePoslists( Fts5Config*, Fts5Expr*, Fts5PoslistPopulator*, int, const char*, int ); void sqlite3Fts5ExprCheckPoslists(Fts5Expr*, i64); int sqlite3Fts5ExprClonePhrase(Fts5Expr*, int, Fts5Expr**); int sqlite3Fts5ExprPhraseCollist(Fts5Expr *, int, const u8 **, int *); /******************************************* ** The fts5_expr.c API above this point is used by the other hand-written ** C code in this module. The interfaces below this point are called by ** the parser code in fts5parse.y. */ void sqlite3Fts5ParseError(Fts5Parse *pParse, const char *zFmt, ...); Fts5ExprNode *sqlite3Fts5ParseNode( Fts5Parse *pParse, int eType, Fts5ExprNode *pLeft, Fts5ExprNode *pRight, Fts5ExprNearset *pNear ); Fts5ExprNode *sqlite3Fts5ParseImplicitAnd( Fts5Parse *pParse, Fts5ExprNode *pLeft, Fts5ExprNode *pRight ); Fts5ExprPhrase *sqlite3Fts5ParseTerm( Fts5Parse *pParse, Fts5ExprPhrase *pPhrase, Fts5Token *pToken, int bPrefix ); void sqlite3Fts5ParseSetCaret(Fts5ExprPhrase*); Fts5ExprNearset *sqlite3Fts5ParseNearset( Fts5Parse*, Fts5ExprNearset*, Fts5ExprPhrase* ); Fts5Colset *sqlite3Fts5ParseColset( Fts5Parse*, Fts5Colset*, Fts5Token * ); void sqlite3Fts5ParsePhraseFree(Fts5ExprPhrase*); void sqlite3Fts5ParseNearsetFree(Fts5ExprNearset*); void sqlite3Fts5ParseNodeFree(Fts5ExprNode*); void sqlite3Fts5ParseSetDistance(Fts5Parse*, Fts5ExprNearset*, Fts5Token*); void sqlite3Fts5ParseSetColset(Fts5Parse*, Fts5ExprNode*, Fts5Colset*); Fts5Colset *sqlite3Fts5ParseColsetInvert(Fts5Parse*, Fts5Colset*); void sqlite3Fts5ParseFinished(Fts5Parse *pParse, Fts5ExprNode *p); void sqlite3Fts5ParseNear(Fts5Parse *pParse, Fts5Token*); /* ** End of interface to code in fts5_expr.c. **************************************************************************/ /************************************************************************** ** Interface to code in fts5_aux.c. */ int sqlite3Fts5AuxInit(fts5_api*); /* ** End of interface to code in fts5_aux.c. **************************************************************************/ /************************************************************************** ** Interface to code in fts5_tokenizer.c. */ int sqlite3Fts5TokenizerInit(fts5_api*); /* ** End of interface to code in fts5_tokenizer.c. **************************************************************************/ /************************************************************************** ** Interface to code in fts5_vocab.c. */ int sqlite3Fts5VocabInit(Fts5Global*, sqlite3*); /* ** End of interface to code in fts5_vocab.c. **************************************************************************/ /************************************************************************** ** Interface to automatically generated code in fts5_unicode2.c. */ int sqlite3Fts5UnicodeIsalnum(int c); int sqlite3Fts5UnicodeIsdiacritic(int c); int sqlite3Fts5UnicodeFold(int c, int bRemoveDiacritic); /* ** End of interface to code in fts5_unicode2.c. **************************************************************************/ #endif
null
null
null
null
26,654
12,126
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
177,121
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
#include <linux/types.h> #include <linux/errno.h> #include <linux/uaccess.h> #include <asm/sfp-machine.h> #include <math-emu/soft-fp.h> #include <math-emu/double.h> #include <math-emu/single.h> int frsp(void *frD, void *frB) { FP_DECL_D(B); FP_DECL_EX; #ifdef DEBUG printk("%s: D %p, B %p\n", __func__, frD, frB); #endif FP_UNPACK_DP(B, frB); #ifdef DEBUG printk("B: %ld %lu %lu %ld (%ld)\n", B_s, B_f1, B_f0, B_e, B_c); #endif __FP_PACK_DS(frD, B); return FP_CUR_EXCEPTIONS; }
null
null
null
null
85,468
36,262
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
36,262
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// 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 "third_party/blink/renderer/core/page/scrolling/scroll_state.h" #include <memory> #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/renderer/core/dom/document.h" #include "third_party/blink/renderer/core/dom/element.h" namespace blink { namespace { ScrollState* CreateScrollState(double delta_x, double delta_y, bool beginning, bool ending) { std::unique_ptr<ScrollStateData> scroll_state_data = std::make_unique<ScrollStateData>(); scroll_state_data->delta_x = delta_x; scroll_state_data->delta_y = delta_y; scroll_state_data->is_beginning = beginning; scroll_state_data->is_ending = ending; return ScrollState::Create(std::move(scroll_state_data)); } class ScrollStateTest : public testing::Test {}; TEST_F(ScrollStateTest, ConsumeDeltaNative) { const float kDeltaX = 12.3; const float kDeltaY = 3.9; const float kDeltaXToConsume = 1.2; const float kDeltaYToConsume = 2.3; ScrollState* scroll_state = CreateScrollState(kDeltaX, kDeltaY, false, false); EXPECT_FLOAT_EQ(kDeltaX, scroll_state->deltaX()); EXPECT_FLOAT_EQ(kDeltaY, scroll_state->deltaY()); EXPECT_FALSE(scroll_state->DeltaConsumedForScrollSequence()); EXPECT_FALSE(scroll_state->FullyConsumed()); scroll_state->ConsumeDeltaNative(0, 0); EXPECT_FLOAT_EQ(kDeltaX, scroll_state->deltaX()); EXPECT_FLOAT_EQ(kDeltaY, scroll_state->deltaY()); EXPECT_FALSE(scroll_state->DeltaConsumedForScrollSequence()); EXPECT_FALSE(scroll_state->FullyConsumed()); scroll_state->ConsumeDeltaNative(kDeltaXToConsume, 0); EXPECT_FLOAT_EQ(kDeltaX - kDeltaXToConsume, scroll_state->deltaX()); EXPECT_FLOAT_EQ(kDeltaY, scroll_state->deltaY()); EXPECT_TRUE(scroll_state->DeltaConsumedForScrollSequence()); EXPECT_FALSE(scroll_state->FullyConsumed()); scroll_state->ConsumeDeltaNative(0, kDeltaYToConsume); EXPECT_FLOAT_EQ(kDeltaX - kDeltaXToConsume, scroll_state->deltaX()); EXPECT_FLOAT_EQ(kDeltaY - kDeltaYToConsume, scroll_state->deltaY()); EXPECT_TRUE(scroll_state->DeltaConsumedForScrollSequence()); EXPECT_FALSE(scroll_state->FullyConsumed()); scroll_state->ConsumeDeltaNative(scroll_state->deltaX(), scroll_state->deltaY()); EXPECT_TRUE(scroll_state->DeltaConsumedForScrollSequence()); EXPECT_TRUE(scroll_state->FullyConsumed()); } TEST_F(ScrollStateTest, CurrentNativeScrollingElement) { ScrollState* scroll_state = CreateScrollState(0, 0, false, false); Element* element = Element::Create(QualifiedName::Null(), Document::CreateForTest()); scroll_state->SetCurrentNativeScrollingElement(element); EXPECT_EQ(element, scroll_state->CurrentNativeScrollingElement()); } TEST_F(ScrollStateTest, FullyConsumed) { ScrollState* scroll_state_begin = CreateScrollState(0, 0, true, false); ScrollState* scroll_state = CreateScrollState(0, 0, false, false); ScrollState* scroll_state_end = CreateScrollState(0, 0, false, true); EXPECT_FALSE(scroll_state_begin->FullyConsumed()); EXPECT_TRUE(scroll_state->FullyConsumed()); EXPECT_FALSE(scroll_state_end->FullyConsumed()); } } // namespace } // namespace blink
null
null
null
null
33,125
15,889
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
15,889
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_SYNC_TEST_FAKE_SERVER_FAKE_SERVER_HTTP_POST_PROVIDER_H_ #define COMPONENTS_SYNC_TEST_FAKE_SERVER_FAKE_SERVER_HTTP_POST_PROVIDER_H_ #include <string> #include "base/callback.h" #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" #include "base/sequenced_task_runner.h" #include "base/synchronization/waitable_event.h" #include "components/sync/engine/net/http_post_provider_factory.h" #include "components/sync/engine/net/http_post_provider_interface.h" namespace fake_server { class FakeServer; class FakeServerHttpPostProvider : public syncer::HttpPostProviderInterface, public base::RefCountedThreadSafe<FakeServerHttpPostProvider> { public: FakeServerHttpPostProvider( const base::WeakPtr<FakeServer>& fake_server, scoped_refptr<base::SequencedTaskRunner> fake_server_task_runner); // HttpPostProviderInterface implementation. void SetExtraRequestHeaders(const char* headers) override; void SetURL(const char* url, int port) override; void SetPostPayload(const char* content_type, int content_length, const char* content) override; bool MakeSynchronousPost(int* error_code, int* response_code) override; void Abort() override; int GetResponseContentLength() const override; const char* GetResponseContent() const override; const std::string GetResponseHeaderValue( const std::string& name) const override; protected: ~FakeServerHttpPostProvider() override; private: friend class base::RefCountedThreadSafe<FakeServerHttpPostProvider>; // |fake_server_| should only be dereferenced on the same thread as // |fake_server_task_runner_| runs on. base::WeakPtr<FakeServer> fake_server_; scoped_refptr<base::SequencedTaskRunner> fake_server_task_runner_; std::string response_; std::string request_url_; int request_port_; std::string request_content_; std::string request_content_type_; std::string extra_request_headers_; int post_error_code_; int post_response_code_; DISALLOW_COPY_AND_ASSIGN(FakeServerHttpPostProvider); }; class FakeServerHttpPostProviderFactory : public syncer::HttpPostProviderFactory { public: FakeServerHttpPostProviderFactory( const base::WeakPtr<FakeServer>& fake_server, scoped_refptr<base::SequencedTaskRunner> fake_server_task_runner); ~FakeServerHttpPostProviderFactory() override; // HttpPostProviderFactory: void Init( const std::string& user_agent, const syncer::BindToTrackerCallback& bind_to_tracker_callback) override; syncer::HttpPostProviderInterface* Create() override; void Destroy(syncer::HttpPostProviderInterface* http) override; private: // |fake_server_| should only be dereferenced on the same thread as // |fake_server_task_runner_| runs on. base::WeakPtr<FakeServer> fake_server_; scoped_refptr<base::SequencedTaskRunner> fake_server_task_runner_; DISALLOW_COPY_AND_ASSIGN(FakeServerHttpPostProviderFactory); }; } // namespace fake_server #endif // COMPONENTS_SYNC_TEST_FAKE_SERVER_FAKE_SERVER_HTTP_POST_PROVIDER_H_
null
null
null
null
12,752
34,133
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
199,128
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * Copyright 2014-2015 Cisco Systems, Inc. and/or its affiliates. * All rights reserved. * * This program is free software; you may redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 2 of the License. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #ifndef M00460_EVCNT_MEMMAP_PACKAGE_H #define M00460_EVCNT_MEMMAP_PACKAGE_H /******************************************************************* * Register Block * M00460_EVCNT_MEMMAP_PACKAGE_VHD_REGMAP *******************************************************************/ struct m00460_evcnt_regmap { uint32_t control; /* Reg 0x0000, Default=0x0 */ uint32_t count; /* Reg 0x0004 */ }; #define M00460_EVCNT_REG_CONTROL_OFST 0 #define M00460_EVCNT_REG_COUNT_OFST 4 /******************************************************************* * Bit Mask for register * M00460_EVCNT_MEMMAP_PACKAGE_VHD_BITMAP *******************************************************************/ /* control [1:0] */ #define M00460_CONTROL_BITMAP_ENABLE_OFST (0) #define M00460_CONTROL_BITMAP_ENABLE_MSK (0x1 << M00460_CONTROL_BITMAP_ENABLE_OFST) #define M00460_CONTROL_BITMAP_CLEAR_OFST (1) #define M00460_CONTROL_BITMAP_CLEAR_MSK (0x1 << M00460_CONTROL_BITMAP_CLEAR_OFST) #endif /*M00460_EVCNT_MEMMAP_PACKAGE_H*/
null
null
null
null
107,475
39,952
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
204,947
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* System trusted keyring for trusted public keys * * Copyright (C) 2012 Red Hat, Inc. All Rights Reserved. * Written by David Howells (dhowells@redhat.com) * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public Licence * as published by the Free Software Foundation; either version * 2 of the Licence, or (at your option) any later version. */ #include <linux/export.h> #include <linux/kernel.h> #include <linux/sched.h> #include <linux/cred.h> #include <linux/err.h> #include <keys/asymmetric-type.h> #include <keys/system_keyring.h> #include <crypto/pkcs7.h> static struct key *builtin_trusted_keys; #ifdef CONFIG_SECONDARY_TRUSTED_KEYRING static struct key *secondary_trusted_keys; #endif extern __initconst const u8 system_certificate_list[]; extern __initconst const unsigned long system_certificate_list_size; /** * restrict_link_to_builtin_trusted - Restrict keyring addition by built in CA * * Restrict the addition of keys into a keyring based on the key-to-be-added * being vouched for by a key in the built in system keyring. */ int restrict_link_by_builtin_trusted(struct key *keyring, const struct key_type *type, const union key_payload *payload) { return restrict_link_by_signature(builtin_trusted_keys, type, payload); } #ifdef CONFIG_SECONDARY_TRUSTED_KEYRING /** * restrict_link_by_builtin_and_secondary_trusted - Restrict keyring * addition by both builtin and secondary keyrings * * Restrict the addition of keys into a keyring based on the key-to-be-added * being vouched for by a key in either the built-in or the secondary system * keyrings. */ int restrict_link_by_builtin_and_secondary_trusted( struct key *keyring, const struct key_type *type, const union key_payload *payload) { /* If we have a secondary trusted keyring, then that contains a link * through to the builtin keyring and the search will follow that link. */ if (type == &key_type_keyring && keyring == secondary_trusted_keys && payload == &builtin_trusted_keys->payload) /* Allow the builtin keyring to be added to the secondary */ return 0; return restrict_link_by_signature(secondary_trusted_keys, type, payload); } #endif /* * Create the trusted keyrings */ static __init int system_trusted_keyring_init(void) { pr_notice("Initialise system trusted keyrings\n"); builtin_trusted_keys = keyring_alloc(".builtin_trusted_keys", KUIDT_INIT(0), KGIDT_INIT(0), current_cred(), ((KEY_POS_ALL & ~KEY_POS_SETATTR) | KEY_USR_VIEW | KEY_USR_READ | KEY_USR_SEARCH), KEY_ALLOC_NOT_IN_QUOTA, NULL, NULL); if (IS_ERR(builtin_trusted_keys)) panic("Can't allocate builtin trusted keyring\n"); #ifdef CONFIG_SECONDARY_TRUSTED_KEYRING secondary_trusted_keys = keyring_alloc(".secondary_trusted_keys", KUIDT_INIT(0), KGIDT_INIT(0), current_cred(), ((KEY_POS_ALL & ~KEY_POS_SETATTR) | KEY_USR_VIEW | KEY_USR_READ | KEY_USR_SEARCH | KEY_USR_WRITE), KEY_ALLOC_NOT_IN_QUOTA, restrict_link_by_builtin_and_secondary_trusted, NULL); if (IS_ERR(secondary_trusted_keys)) panic("Can't allocate secondary trusted keyring\n"); if (key_link(secondary_trusted_keys, builtin_trusted_keys) < 0) panic("Can't link trusted keyrings\n"); #endif return 0; } /* * Must be initialised before we try and load the keys into the keyring. */ device_initcall(system_trusted_keyring_init); /* * Load the compiled-in list of X.509 certificates. */ static __init int load_system_certificate_list(void) { key_ref_t key; const u8 *p, *end; size_t plen; pr_notice("Loading compiled-in X.509 certificates\n"); p = system_certificate_list; end = p + system_certificate_list_size; while (p < end) { /* Each cert begins with an ASN.1 SEQUENCE tag and must be more * than 256 bytes in size. */ if (end - p < 4) goto dodgy_cert; if (p[0] != 0x30 && p[1] != 0x82) goto dodgy_cert; plen = (p[2] << 8) | p[3]; plen += 4; if (plen > end - p) goto dodgy_cert; key = key_create_or_update(make_key_ref(builtin_trusted_keys, 1), "asymmetric", NULL, p, plen, ((KEY_POS_ALL & ~KEY_POS_SETATTR) | KEY_USR_VIEW | KEY_USR_READ), KEY_ALLOC_NOT_IN_QUOTA | KEY_ALLOC_BUILT_IN | KEY_ALLOC_BYPASS_RESTRICTION); if (IS_ERR(key)) { pr_err("Problem loading in-kernel X.509 certificate (%ld)\n", PTR_ERR(key)); } else { pr_notice("Loaded X.509 cert '%s'\n", key_ref_to_ptr(key)->description); key_ref_put(key); } p += plen; } return 0; dodgy_cert: pr_err("Problem parsing in-kernel X.509 certificate list\n"); return 0; } late_initcall(load_system_certificate_list); #ifdef CONFIG_SYSTEM_DATA_VERIFICATION /** * verify_pkcs7_signature - Verify a PKCS#7-based signature on system data. * @data: The data to be verified (NULL if expecting internal data). * @len: Size of @data. * @raw_pkcs7: The PKCS#7 message that is the signature. * @pkcs7_len: The size of @raw_pkcs7. * @trusted_keys: Trusted keys to use (NULL for builtin trusted keys only, * (void *)1UL for all trusted keys). * @usage: The use to which the key is being put. * @view_content: Callback to gain access to content. * @ctx: Context for callback. */ int verify_pkcs7_signature(const void *data, size_t len, const void *raw_pkcs7, size_t pkcs7_len, struct key *trusted_keys, enum key_being_used_for usage, int (*view_content)(void *ctx, const void *data, size_t len, size_t asn1hdrlen), void *ctx) { struct pkcs7_message *pkcs7; int ret; pkcs7 = pkcs7_parse_message(raw_pkcs7, pkcs7_len); if (IS_ERR(pkcs7)) return PTR_ERR(pkcs7); /* The data should be detached - so we need to supply it. */ if (data && pkcs7_supply_detached_data(pkcs7, data, len) < 0) { pr_err("PKCS#7 signature with non-detached data\n"); ret = -EBADMSG; goto error; } ret = pkcs7_verify(pkcs7, usage); if (ret < 0) goto error; if (!trusted_keys) { trusted_keys = builtin_trusted_keys; } else if (trusted_keys == (void *)1UL) { #ifdef CONFIG_SECONDARY_TRUSTED_KEYRING trusted_keys = secondary_trusted_keys; #else trusted_keys = builtin_trusted_keys; #endif } ret = pkcs7_validate_trust(pkcs7, trusted_keys); if (ret < 0) { if (ret == -ENOKEY) pr_err("PKCS#7 signature not signed with a trusted key\n"); goto error; } if (view_content) { size_t asn1hdrlen; ret = pkcs7_get_content_data(pkcs7, &data, &len, &asn1hdrlen); if (ret < 0) { if (ret == -ENODATA) pr_devel("PKCS#7 message does not contain data\n"); goto error; } ret = view_content(ctx, data, len, asn1hdrlen); } error: pkcs7_free_message(pkcs7); pr_devel("<==%s() = %d\n", __func__, ret); return ret; } EXPORT_SYMBOL_GPL(verify_pkcs7_signature); #endif /* CONFIG_SYSTEM_DATA_VERIFICATION */
null
null
null
null
113,294
67,676
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
67,676
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// 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. // Multiply-included file, hence no include guard. #include "ipc/ipc_test_messages.h"
null
null
null
null
64,539
43,798
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
43,798
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// 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 "base/trace_event/heap_profiler_allocation_register.h" #include <algorithm> #include <limits> namespace base { namespace trace_event { size_t AllocationRegister::AddressHasher::operator()( const void* address) const { // The multiplicative hashing scheme from [Knuth 1998]. The value of |a| has // been chosen carefully based on measurements with real-word data (addresses // recorded from a Chrome trace run). It is the first prime after 2^17. For // |shift|, 15 yield good results for both 2^18 and 2^19 bucket sizes. // Microbenchmarks show that this simple scheme outperforms fancy hashes like // Murmur3 by 20 to 40 percent. const uintptr_t key = reinterpret_cast<uintptr_t>(address); const uintptr_t a = 131101; const uintptr_t shift = 15; const uintptr_t h = (key * a) >> shift; return h; } AllocationRegister::ConstIterator::ConstIterator( const AllocationRegister& alloc_register, AllocationIndex index) : register_(alloc_register), index_(index) {} void AllocationRegister::ConstIterator::operator++() { index_ = register_.allocations_.Next(index_ + 1); } bool AllocationRegister::ConstIterator::operator!=( const ConstIterator& other) const { return index_ != other.index_; } AllocationRegister::Allocation AllocationRegister::ConstIterator::operator*() const { return register_.GetAllocation(index_); } size_t AllocationRegister::BacktraceHasher::operator()( const Backtrace& backtrace) const { const size_t kSampleLength = 10; uintptr_t total_value = 0; size_t head_end = std::min(backtrace.frame_count, kSampleLength); for (size_t i = 0; i != head_end; ++i) { total_value += reinterpret_cast<uintptr_t>(backtrace.frames[i].value); } size_t tail_start = backtrace.frame_count - std::min(backtrace.frame_count - head_end, kSampleLength); for (size_t i = tail_start; i != backtrace.frame_count; ++i) { total_value += reinterpret_cast<uintptr_t>(backtrace.frames[i].value); } total_value += backtrace.frame_count; // These magic constants give best results in terms of average collisions // per backtrace. They were found by replaying real backtraces from Linux // and Android against different hash functions. return (total_value * 131101) >> 14; } AllocationRegister::AllocationRegister() : AllocationRegister(kAllocationCapacity, kBacktraceCapacity) {} AllocationRegister::AllocationRegister(size_t allocation_capacity, size_t backtrace_capacity) : allocations_(allocation_capacity), backtraces_(backtrace_capacity) { Backtrace sentinel = {}; sentinel.frames[0] = StackFrame::FromThreadName("[out of heap profiler mem]"); sentinel.frame_count = 1; // Rationale for max / 2: in theory we could just start the sentinel with a // refcount == 0. However, using max / 2 allows short circuiting of the // conditional in RemoveBacktrace() keeping the sentinel logic out of the fast // path. From a functional viewpoint, the sentinel is safe even if we wrap // over refcount because . BacktraceMap::KVPair::second_type sentinel_refcount = std::numeric_limits<BacktraceMap::KVPair::second_type>::max() / 2; auto index_and_flag = backtraces_.Insert(sentinel, sentinel_refcount); DCHECK(index_and_flag.second); DCHECK_EQ(index_and_flag.first, kOutOfStorageBacktraceIndex); } AllocationRegister::~AllocationRegister() = default; bool AllocationRegister::Insert(const void* address, size_t size, const AllocationContext& context) { DCHECK(address != nullptr); if (size == 0) { return false; } AllocationInfo info = {size, context.type_name, InsertBacktrace(context.backtrace)}; // Try to insert the allocation. auto index_and_flag = allocations_.Insert(address, info); if (!index_and_flag.second && index_and_flag.first != AllocationMap::kInvalidKVIndex) { // |address| is already there - overwrite the allocation info. auto& old_info = allocations_.Get(index_and_flag.first).second; RemoveBacktrace(old_info.backtrace_index); old_info = info; return true; } return index_and_flag.second; } void AllocationRegister::Remove(const void* address) { auto index = allocations_.Find(address); if (index == AllocationMap::kInvalidKVIndex) { return; } const AllocationInfo& info = allocations_.Get(index).second; RemoveBacktrace(info.backtrace_index); allocations_.Remove(index); } bool AllocationRegister::Get(const void* address, Allocation* out_allocation) const { auto index = allocations_.Find(address); if (index == AllocationMap::kInvalidKVIndex) { return false; } if (out_allocation) { *out_allocation = GetAllocation(index); } return true; } AllocationRegister::ConstIterator AllocationRegister::begin() const { return ConstIterator(*this, allocations_.Next(0)); } AllocationRegister::ConstIterator AllocationRegister::end() const { return ConstIterator(*this, AllocationMap::kInvalidKVIndex); } size_t AllocationRegister::EstimateAllocatedMemory() const { return sizeof(AllocationRegister); } size_t AllocationRegister::EstimateResidentMemory() const { return sizeof(AllocationRegister) + allocations_.EstimateUsedMemory() + backtraces_.EstimateUsedMemory(); } AllocationRegister::BacktraceMap::KVIndex AllocationRegister::InsertBacktrace( const Backtrace& backtrace) { auto index = backtraces_.Insert(backtrace, 0).first; if (index == BacktraceMap::kInvalidKVIndex) return kOutOfStorageBacktraceIndex; auto& backtrace_and_count = backtraces_.Get(index); backtrace_and_count.second++; return index; } void AllocationRegister::RemoveBacktrace(BacktraceMap::KVIndex index) { auto& backtrace_and_count = backtraces_.Get(index); if (--backtrace_and_count.second == 0 && index != kOutOfStorageBacktraceIndex) { // Backtrace is not referenced anymore - remove it. backtraces_.Remove(index); } } AllocationRegister::Allocation AllocationRegister::GetAllocation( AllocationMap::KVIndex index) const { const auto& address_and_info = allocations_.Get(index); const auto& backtrace_and_count = backtraces_.Get(address_and_info.second.backtrace_index); return {address_and_info.first, address_and_info.second.size, AllocationContext(backtrace_and_count.first, address_and_info.second.type_name)}; } } // namespace trace_event } // namespace base
null
null
null
null
40,661
36,559
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
36,559
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// 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 "third_party/blink/renderer/platform/geometry/geometry_as_json.h" #include "third_party/blink/renderer/platform/transforms/transformation_matrix.h" namespace blink { static double RoundCloseToZero(double number) { return std::abs(number) < 1e-7 ? 0 : number; } std::unique_ptr<JSONArray> TransformAsJSONArray(const TransformationMatrix& t) { std::unique_ptr<JSONArray> array = JSONArray::Create(); { std::unique_ptr<JSONArray> row = JSONArray::Create(); row->PushDouble(RoundCloseToZero(t.M11())); row->PushDouble(RoundCloseToZero(t.M12())); row->PushDouble(RoundCloseToZero(t.M13())); row->PushDouble(RoundCloseToZero(t.M14())); array->PushArray(std::move(row)); } { std::unique_ptr<JSONArray> row = JSONArray::Create(); row->PushDouble(RoundCloseToZero(t.M21())); row->PushDouble(RoundCloseToZero(t.M22())); row->PushDouble(RoundCloseToZero(t.M23())); row->PushDouble(RoundCloseToZero(t.M24())); array->PushArray(std::move(row)); } { std::unique_ptr<JSONArray> row = JSONArray::Create(); row->PushDouble(RoundCloseToZero(t.M31())); row->PushDouble(RoundCloseToZero(t.M32())); row->PushDouble(RoundCloseToZero(t.M33())); row->PushDouble(RoundCloseToZero(t.M34())); array->PushArray(std::move(row)); } { std::unique_ptr<JSONArray> row = JSONArray::Create(); row->PushDouble(RoundCloseToZero(t.M41())); row->PushDouble(RoundCloseToZero(t.M42())); row->PushDouble(RoundCloseToZero(t.M43())); row->PushDouble(RoundCloseToZero(t.M44())); array->PushArray(std::move(row)); } return array; } } // namespace blink
null
null
null
null
33,422
44,551
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
209,546
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * Copyright (C) 2008 Nir Tzachar <nir.tzachar@gmail.com? * Released under the terms of the GNU GPL v2.0. * * Derived from menuconfig. * */ #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #include <string.h> #include <stdlib.h> #include "lkc.h" #include "nconf.h" #include <ctype.h> static const char nconf_global_help[] = N_( "Help windows\n" "------------\n" "o Global help: Unless in a data entry window, pressing <F1> will give \n" " you the global help window, which you are just reading.\n" "\n" "o A short version of the global help is available by pressing <F3>.\n" "\n" "o Local help: To get help related to the current menu entry, use any\n" " of <?> <h>, or if in a data entry window then press <F1>.\n" "\n" "\n" "Menu entries\n" "------------\n" "This interface lets you select features and parameters for the kernel\n" "build. Kernel features can either be built-in, modularized, or removed.\n" "Parameters must be entered as text or decimal or hexadecimal numbers.\n" "\n" "Menu entries beginning with following braces represent features that\n" " [ ] can be built in or removed\n" " < > can be built in, modularized or removed\n" " { } can be built in or modularized, are selected by another feature\n" " - - are selected by another feature\n" " XXX cannot be selected. Symbol Info <F2> tells you why.\n" "*, M or whitespace inside braces means to build in, build as a module\n" "or to exclude the feature respectively.\n" "\n" "To change any of these features, highlight it with the movement keys\n" "listed below and press <y> to build it in, <m> to make it a module or\n" "<n> to remove it. You may press the <Space> key to cycle through the\n" "available options.\n" "\n" "A trailing \"--->\" designates a submenu, a trailing \"----\" an\n" "empty submenu.\n" "\n" "Menu navigation keys\n" "----------------------------------------------------------------------\n" "Linewise up <Up>\n" "Linewise down <Down>\n" "Pagewise up <Page Up>\n" "Pagewise down <Page Down>\n" "First entry <Home>\n" "Last entry <End>\n" "Enter a submenu <Right> <Enter>\n" "Go back to parent menu <Left> <Esc> <F5>\n" "Close a help window <Enter> <Esc> <F5>\n" "Close entry window, apply <Enter>\n" "Close entry window, forget <Esc> <F5>\n" "Start incremental, case-insensitive search for STRING in menu entries,\n" " no regex support, STRING is displayed in upper left corner\n" " </>STRING\n" " Remove last character <Backspace>\n" " Jump to next hit <Down>\n" " Jump to previous hit <Up>\n" "Exit menu search mode </> <Esc>\n" "Search for configuration variables with or without leading CONFIG_\n" " <F8>RegExpr<Enter>\n" "Verbose search help <F8><F1>\n" "----------------------------------------------------------------------\n" "\n" "Unless in a data entry window, key <1> may be used instead of <F1>,\n" "<2> instead of <F2>, etc.\n" "\n" "\n" "Radiolist (Choice list)\n" "-----------------------\n" "Use the movement keys listed above to select the option you wish to set\n" "and press <Space>.\n" "\n" "\n" "Data entry\n" "----------\n" "Enter the requested information and press <Enter>. Hexadecimal values\n" "may be entered without the \"0x\" prefix.\n" "\n" "\n" "Text Box (Help Window)\n" "----------------------\n" "Use movement keys as listed in table above.\n" "\n" "Press any of <Enter> <Esc> <q> <F5> <F9> to exit.\n" "\n" "\n" "Alternate configuration files\n" "-----------------------------\n" "nconfig supports switching between different configurations.\n" "Press <F6> to save your current configuration. Press <F7> and enter\n" "a file name to load a previously saved configuration.\n" "\n" "\n" "Terminal configuration\n" "----------------------\n" "If you use nconfig in a xterm window, make sure your TERM environment\n" "variable specifies a terminal configuration which supports at least\n" "16 colors. Otherwise nconfig will look rather bad.\n" "\n" "If the \"stty size\" command reports the current terminalsize correctly,\n" "nconfig will adapt to sizes larger than the traditional 80x25 \"standard\"\n" "and display longer menus properly.\n" "\n" "\n" "Single menu mode\n" "----------------\n" "If you prefer to have all of the menu entries listed in a single menu,\n" "rather than the default multimenu hierarchy, run nconfig with\n" "NCONFIG_MODE environment variable set to single_menu. Example:\n" "\n" "make NCONFIG_MODE=single_menu nconfig\n" "\n" "<Enter> will then unfold the appropriate category, or fold it if it\n" "is already unfolded. Folded menu entries will be designated by a\n" "leading \"++>\" and unfolded entries by a leading \"-->\".\n" "\n" "Note that this mode can eventually be a little more CPU expensive than\n" "the default mode, especially with a larger number of unfolded submenus.\n" "\n"), menu_no_f_instructions[] = N_( "Legend: [*] built-in [ ] excluded <M> module < > module capable.\n" "Submenus are designated by a trailing \"--->\", empty ones by \"----\".\n" "\n" "Use the following keys to navigate the menus:\n" "Move up or down with <Up> and <Down>.\n" "Enter a submenu with <Enter> or <Right>.\n" "Exit a submenu to its parent menu with <Esc> or <Left>.\n" "Pressing <y> includes, <n> excludes, <m> modularizes features.\n" "Pressing <Space> cycles through the available options.\n" "To search for menu entries press </>.\n" "<Esc> always leaves the current window.\n" "\n" "You do not have function keys support.\n" "Press <1> instead of <F1>, <2> instead of <F2>, etc.\n" "For verbose global help use key <1>.\n" "For help related to the current menu entry press <?> or <h>.\n"), menu_instructions[] = N_( "Legend: [*] built-in [ ] excluded <M> module < > module capable.\n" "Submenus are designated by a trailing \"--->\", empty ones by \"----\".\n" "\n" "Use the following keys to navigate the menus:\n" "Move up or down with <Up> or <Down>.\n" "Enter a submenu with <Enter> or <Right>.\n" "Exit a submenu to its parent menu with <Esc> or <Left>.\n" "Pressing <y> includes, <n> excludes, <m> modularizes features.\n" "Pressing <Space> cycles through the available options.\n" "To search for menu entries press </>.\n" "<Esc> always leaves the current window.\n" "\n" "Pressing <1> may be used instead of <F1>, <2> instead of <F2>, etc.\n" "For verbose global help press <F1>.\n" "For help related to the current menu entry press <?> or <h>.\n"), radiolist_instructions[] = N_( "Press <Up>, <Down>, <Home> or <End> to navigate a radiolist, select\n" "with <Space>.\n" "For help related to the current entry press <?> or <h>.\n" "For global help press <F1>.\n"), inputbox_instructions_int[] = N_( "Please enter a decimal value.\n" "Fractions will not be accepted.\n" "Press <Enter> to apply, <Esc> to cancel."), inputbox_instructions_hex[] = N_( "Please enter a hexadecimal value.\n" "Press <Enter> to apply, <Esc> to cancel."), inputbox_instructions_string[] = N_( "Please enter a string value.\n" "Press <Enter> to apply, <Esc> to cancel."), setmod_text[] = N_( "This feature depends on another feature which has been configured as a\n" "module. As a result, the current feature will be built as a module too."), load_config_text[] = N_( "Enter the name of the configuration file you wish to load.\n" "Accept the name shown to restore the configuration you last\n" "retrieved. Leave empty to abort."), load_config_help[] = N_( "For various reasons, one may wish to keep several different\n" "configurations available on a single machine.\n" "\n" "If you have saved a previous configuration in a file other than the\n" "default one, entering its name here will allow you to load and modify\n" "that configuration.\n" "\n" "Leave empty to abort.\n"), save_config_text[] = N_( "Enter a filename to which this configuration should be saved\n" "as an alternate. Leave empty to abort."), save_config_help[] = N_( "For various reasons, one may wish to keep several different\n" "configurations available on a single machine.\n" "\n" "Entering a file name here will allow you to later retrieve, modify\n" "and use the current configuration as an alternate to whatever\n" "configuration options you have selected at that time.\n" "\n" "Leave empty to abort.\n"), search_help[] = N_( "Search for symbols (configuration variable names CONFIG_*) and display\n" "their relations. Regular expressions are supported.\n" "Example: Search for \"^FOO\".\n" "Result:\n" "-----------------------------------------------------------------\n" "Symbol: FOO [ = m]\n" "Prompt: Foo bus is used to drive the bar HW\n" "Defined at drivers/pci/Kconfig:47\n" "Depends on: X86_LOCAL_APIC && X86_IO_APIC || IA64\n" "Location:\n" " -> Bus options (PCI, PCMCIA, EISA, ISA)\n" " -> PCI support (PCI [ = y])\n" " -> PCI access mode (<choice> [ = y])\n" "Selects: LIBCRC32\n" "Selected by: BAR\n" "-----------------------------------------------------------------\n" "o The line 'Prompt:' shows the text displayed for this symbol in\n" " the menu hierarchy.\n" "o The 'Defined at' line tells at what file / line number the symbol is\n" " defined.\n" "o The 'Depends on:' line lists symbols that need to be defined for\n" " this symbol to be visible and selectable in the menu.\n" "o The 'Location:' lines tell, where in the menu structure this symbol\n" " is located. A location followed by a [ = y] indicates that this is\n" " a selectable menu item, and the current value is displayed inside\n" " brackets.\n" "o The 'Selects:' line tells, what symbol will be automatically selected\n" " if this symbol is selected (y or m).\n" "o The 'Selected by' line tells what symbol has selected this symbol.\n" "\n" "Only relevant lines are shown.\n" "\n\n" "Search examples:\n" "USB => find all symbols containing USB\n" "^USB => find all symbols starting with USB\n" "USB$ => find all symbols ending with USB\n" "\n"); struct mitem { char str[256]; char tag; void *usrptr; int is_visible; }; #define MAX_MENU_ITEMS 4096 static int show_all_items; static int indent; static struct menu *current_menu; static int child_count; static int single_menu_mode; /* the window in which all information appears */ static WINDOW *main_window; /* the largest size of the menu window */ static int mwin_max_lines; static int mwin_max_cols; /* the window in which we show option buttons */ static MENU *curses_menu; static ITEM *curses_menu_items[MAX_MENU_ITEMS]; static struct mitem k_menu_items[MAX_MENU_ITEMS]; static int items_num; static int global_exit; /* the currently selected button */ const char *current_instructions = menu_instructions; static char *dialog_input_result; static int dialog_input_result_len; static void conf(struct menu *menu); static void conf_choice(struct menu *menu); static void conf_string(struct menu *menu); static void conf_load(void); static void conf_save(void); static void show_help(struct menu *menu); static int do_exit(void); static void setup_windows(void); static void search_conf(void); typedef void (*function_key_handler_t)(int *key, struct menu *menu); static void handle_f1(int *key, struct menu *current_item); static void handle_f2(int *key, struct menu *current_item); static void handle_f3(int *key, struct menu *current_item); static void handle_f4(int *key, struct menu *current_item); static void handle_f5(int *key, struct menu *current_item); static void handle_f6(int *key, struct menu *current_item); static void handle_f7(int *key, struct menu *current_item); static void handle_f8(int *key, struct menu *current_item); static void handle_f9(int *key, struct menu *current_item); struct function_keys { const char *key_str; const char *func; function_key key; function_key_handler_t handler; }; static const int function_keys_num = 9; struct function_keys function_keys[] = { { .key_str = "F1", .func = "Help", .key = F_HELP, .handler = handle_f1, }, { .key_str = "F2", .func = "SymInfo", .key = F_SYMBOL, .handler = handle_f2, }, { .key_str = "F3", .func = "Help 2", .key = F_INSTS, .handler = handle_f3, }, { .key_str = "F4", .func = "ShowAll", .key = F_CONF, .handler = handle_f4, }, { .key_str = "F5", .func = "Back", .key = F_BACK, .handler = handle_f5, }, { .key_str = "F6", .func = "Save", .key = F_SAVE, .handler = handle_f6, }, { .key_str = "F7", .func = "Load", .key = F_LOAD, .handler = handle_f7, }, { .key_str = "F8", .func = "SymSearch", .key = F_SEARCH, .handler = handle_f8, }, { .key_str = "F9", .func = "Exit", .key = F_EXIT, .handler = handle_f9, }, }; static void print_function_line(void) { int i; int offset = 1; const int skip = 1; int lines = getmaxy(stdscr); for (i = 0; i < function_keys_num; i++) { (void) wattrset(main_window, attributes[FUNCTION_HIGHLIGHT]); mvwprintw(main_window, lines-3, offset, "%s", function_keys[i].key_str); (void) wattrset(main_window, attributes[FUNCTION_TEXT]); offset += strlen(function_keys[i].key_str); mvwprintw(main_window, lines-3, offset, "%s", function_keys[i].func); offset += strlen(function_keys[i].func) + skip; } (void) wattrset(main_window, attributes[NORMAL]); } /* help */ static void handle_f1(int *key, struct menu *current_item) { show_scroll_win(main_window, _("Global help"), _(nconf_global_help)); return; } /* symbole help */ static void handle_f2(int *key, struct menu *current_item) { show_help(current_item); return; } /* instructions */ static void handle_f3(int *key, struct menu *current_item) { show_scroll_win(main_window, _("Short help"), _(current_instructions)); return; } /* config */ static void handle_f4(int *key, struct menu *current_item) { int res = btn_dialog(main_window, _("Show all symbols?"), 2, " <Show All> ", "<Don't show all>"); if (res == 0) show_all_items = 1; else if (res == 1) show_all_items = 0; return; } /* back */ static void handle_f5(int *key, struct menu *current_item) { *key = KEY_LEFT; return; } /* save */ static void handle_f6(int *key, struct menu *current_item) { conf_save(); return; } /* load */ static void handle_f7(int *key, struct menu *current_item) { conf_load(); return; } /* search */ static void handle_f8(int *key, struct menu *current_item) { search_conf(); return; } /* exit */ static void handle_f9(int *key, struct menu *current_item) { do_exit(); return; } /* return != 0 to indicate the key was handles */ static int process_special_keys(int *key, struct menu *menu) { int i; if (*key == KEY_RESIZE) { setup_windows(); return 1; } for (i = 0; i < function_keys_num; i++) { if (*key == KEY_F(function_keys[i].key) || *key == '0' + function_keys[i].key){ function_keys[i].handler(key, menu); return 1; } } return 0; } static void clean_items(void) { int i; for (i = 0; curses_menu_items[i]; i++) free_item(curses_menu_items[i]); bzero(curses_menu_items, sizeof(curses_menu_items)); bzero(k_menu_items, sizeof(k_menu_items)); items_num = 0; } typedef enum {MATCH_TINKER_PATTERN_UP, MATCH_TINKER_PATTERN_DOWN, FIND_NEXT_MATCH_DOWN, FIND_NEXT_MATCH_UP} match_f; /* return the index of the matched item, or -1 if no such item exists */ static int get_mext_match(const char *match_str, match_f flag) { int match_start = item_index(current_item(curses_menu)); int index; if (flag == FIND_NEXT_MATCH_DOWN) ++match_start; else if (flag == FIND_NEXT_MATCH_UP) --match_start; index = match_start; index = (index + items_num) % items_num; while (true) { char *str = k_menu_items[index].str; if (strcasestr(str, match_str) != 0) return index; if (flag == FIND_NEXT_MATCH_UP || flag == MATCH_TINKER_PATTERN_UP) --index; else ++index; index = (index + items_num) % items_num; if (index == match_start) return -1; } } /* Make a new item. */ static void item_make(struct menu *menu, char tag, const char *fmt, ...) { va_list ap; if (items_num > MAX_MENU_ITEMS-1) return; bzero(&k_menu_items[items_num], sizeof(k_menu_items[0])); k_menu_items[items_num].tag = tag; k_menu_items[items_num].usrptr = menu; if (menu != NULL) k_menu_items[items_num].is_visible = menu_is_visible(menu); else k_menu_items[items_num].is_visible = 1; va_start(ap, fmt); vsnprintf(k_menu_items[items_num].str, sizeof(k_menu_items[items_num].str), fmt, ap); va_end(ap); if (!k_menu_items[items_num].is_visible) memcpy(k_menu_items[items_num].str, "XXX", 3); curses_menu_items[items_num] = new_item( k_menu_items[items_num].str, k_menu_items[items_num].str); set_item_userptr(curses_menu_items[items_num], &k_menu_items[items_num]); /* if (!k_menu_items[items_num].is_visible) item_opts_off(curses_menu_items[items_num], O_SELECTABLE); */ items_num++; curses_menu_items[items_num] = NULL; } /* very hackish. adds a string to the last item added */ static void item_add_str(const char *fmt, ...) { va_list ap; int index = items_num-1; char new_str[256]; char tmp_str[256]; if (index < 0) return; va_start(ap, fmt); vsnprintf(new_str, sizeof(new_str), fmt, ap); va_end(ap); snprintf(tmp_str, sizeof(tmp_str), "%s%s", k_menu_items[index].str, new_str); strncpy(k_menu_items[index].str, tmp_str, sizeof(k_menu_items[index].str)); free_item(curses_menu_items[index]); curses_menu_items[index] = new_item( k_menu_items[index].str, k_menu_items[index].str); set_item_userptr(curses_menu_items[index], &k_menu_items[index]); } /* get the tag of the currently selected item */ static char item_tag(void) { ITEM *cur; struct mitem *mcur; cur = current_item(curses_menu); if (cur == NULL) return 0; mcur = (struct mitem *) item_userptr(cur); return mcur->tag; } static int curses_item_index(void) { return item_index(current_item(curses_menu)); } static void *item_data(void) { ITEM *cur; struct mitem *mcur; cur = current_item(curses_menu); if (!cur) return NULL; mcur = (struct mitem *) item_userptr(cur); return mcur->usrptr; } static int item_is_tag(char tag) { return item_tag() == tag; } static char filename[PATH_MAX+1]; static char menu_backtitle[PATH_MAX+128]; static const char *set_config_filename(const char *config_filename) { int size; size = snprintf(menu_backtitle, sizeof(menu_backtitle), "%s - %s", config_filename, rootmenu.prompt->text); if (size >= sizeof(menu_backtitle)) menu_backtitle[sizeof(menu_backtitle)-1] = '\0'; size = snprintf(filename, sizeof(filename), "%s", config_filename); if (size >= sizeof(filename)) filename[sizeof(filename)-1] = '\0'; return menu_backtitle; } /* return = 0 means we are successful. * -1 means go on doing what you were doing */ static int do_exit(void) { int res; if (!conf_get_changed()) { global_exit = 1; return 0; } res = btn_dialog(main_window, _("Do you wish to save your new configuration?\n" "<ESC> to cancel and resume nconfig."), 2, " <save> ", "<don't save>"); if (res == KEY_EXIT) { global_exit = 0; return -1; } /* if we got here, the user really wants to exit */ switch (res) { case 0: res = conf_write(filename); if (res) btn_dialog( main_window, _("Error during writing of configuration.\n" "Your configuration changes were NOT saved."), 1, "<OK>"); break; default: btn_dialog( main_window, _("Your configuration changes were NOT saved."), 1, "<OK>"); break; } global_exit = 1; return 0; } static void search_conf(void) { struct symbol **sym_arr; struct gstr res; struct gstr title; char *dialog_input; int dres; title = str_new(); str_printf( &title, _("Enter (sub)string or regexp to search for " "(with or without \"%s\")"), CONFIG_); again: dres = dialog_inputbox(main_window, _("Search Configuration Parameter"), str_get(&title), "", &dialog_input_result, &dialog_input_result_len); switch (dres) { case 0: break; case 1: show_scroll_win(main_window, _("Search Configuration"), search_help); goto again; default: str_free(&title); return; } /* strip the prefix if necessary */ dialog_input = dialog_input_result; if (strncasecmp(dialog_input_result, CONFIG_, strlen(CONFIG_)) == 0) dialog_input += strlen(CONFIG_); sym_arr = sym_re_search(dialog_input); res = get_relations_str(sym_arr, NULL); free(sym_arr); show_scroll_win(main_window, _("Search Results"), str_get(&res)); str_free(&res); str_free(&title); } static void build_conf(struct menu *menu) { struct symbol *sym; struct property *prop; struct menu *child; int type, tmp, doint = 2; tristate val; char ch; if (!menu || (!show_all_items && !menu_is_visible(menu))) return; sym = menu->sym; prop = menu->prompt; if (!sym) { if (prop && menu != current_menu) { const char *prompt = menu_get_prompt(menu); enum prop_type ptype; ptype = menu->prompt ? menu->prompt->type : P_UNKNOWN; switch (ptype) { case P_MENU: child_count++; prompt = _(prompt); if (single_menu_mode) { item_make(menu, 'm', "%s%*c%s", menu->data ? "-->" : "++>", indent + 1, ' ', prompt); } else item_make(menu, 'm', " %*c%s %s", indent + 1, ' ', prompt, menu_is_empty(menu) ? "----" : "--->"); if (single_menu_mode && menu->data) goto conf_childs; return; case P_COMMENT: if (prompt) { child_count++; item_make(menu, ':', " %*c*** %s ***", indent + 1, ' ', _(prompt)); } break; default: if (prompt) { child_count++; item_make(menu, ':', "---%*c%s", indent + 1, ' ', _(prompt)); } } } else doint = 0; goto conf_childs; } type = sym_get_type(sym); if (sym_is_choice(sym)) { struct symbol *def_sym = sym_get_choice_value(sym); struct menu *def_menu = NULL; child_count++; for (child = menu->list; child; child = child->next) { if (menu_is_visible(child) && child->sym == def_sym) def_menu = child; } val = sym_get_tristate_value(sym); if (sym_is_changable(sym)) { switch (type) { case S_BOOLEAN: item_make(menu, 't', "[%c]", val == no ? ' ' : '*'); break; case S_TRISTATE: switch (val) { case yes: ch = '*'; break; case mod: ch = 'M'; break; default: ch = ' '; break; } item_make(menu, 't', "<%c>", ch); break; } } else { item_make(menu, def_menu ? 't' : ':', " "); } item_add_str("%*c%s", indent + 1, ' ', _(menu_get_prompt(menu))); if (val == yes) { if (def_menu) { item_add_str(" (%s)", _(menu_get_prompt(def_menu))); item_add_str(" --->"); if (def_menu->list) { indent += 2; build_conf(def_menu); indent -= 2; } } return; } } else { if (menu == current_menu) { item_make(menu, ':', "---%*c%s", indent + 1, ' ', _(menu_get_prompt(menu))); goto conf_childs; } child_count++; val = sym_get_tristate_value(sym); if (sym_is_choice_value(sym) && val == yes) { item_make(menu, ':', " "); } else { switch (type) { case S_BOOLEAN: if (sym_is_changable(sym)) item_make(menu, 't', "[%c]", val == no ? ' ' : '*'); else item_make(menu, 't', "-%c-", val == no ? ' ' : '*'); break; case S_TRISTATE: switch (val) { case yes: ch = '*'; break; case mod: ch = 'M'; break; default: ch = ' '; break; } if (sym_is_changable(sym)) { if (sym->rev_dep.tri == mod) item_make(menu, 't', "{%c}", ch); else item_make(menu, 't', "<%c>", ch); } else item_make(menu, 't', "-%c-", ch); break; default: tmp = 2 + strlen(sym_get_string_value(sym)); item_make(menu, 's', " (%s)", sym_get_string_value(sym)); tmp = indent - tmp + 4; if (tmp < 0) tmp = 0; item_add_str("%*c%s%s", tmp, ' ', _(menu_get_prompt(menu)), (sym_has_value(sym) || !sym_is_changable(sym)) ? "" : _(" (NEW)")); goto conf_childs; } } item_add_str("%*c%s%s", indent + 1, ' ', _(menu_get_prompt(menu)), (sym_has_value(sym) || !sym_is_changable(sym)) ? "" : _(" (NEW)")); if (menu->prompt && menu->prompt->type == P_MENU) { item_add_str(" %s", menu_is_empty(menu) ? "----" : "--->"); return; } } conf_childs: indent += doint; for (child = menu->list; child; child = child->next) build_conf(child); indent -= doint; } static void reset_menu(void) { unpost_menu(curses_menu); clean_items(); } /* adjust the menu to show this item. * prefer not to scroll the menu if possible*/ static void center_item(int selected_index, int *last_top_row) { int toprow; set_top_row(curses_menu, *last_top_row); toprow = top_row(curses_menu); if (selected_index < toprow || selected_index >= toprow+mwin_max_lines) { toprow = max(selected_index-mwin_max_lines/2, 0); if (toprow >= item_count(curses_menu)-mwin_max_lines) toprow = item_count(curses_menu)-mwin_max_lines; set_top_row(curses_menu, toprow); } set_current_item(curses_menu, curses_menu_items[selected_index]); *last_top_row = toprow; post_menu(curses_menu); refresh_all_windows(main_window); } /* this function assumes reset_menu has been called before */ static void show_menu(const char *prompt, const char *instructions, int selected_index, int *last_top_row) { int maxx, maxy; WINDOW *menu_window; current_instructions = instructions; clear(); (void) wattrset(main_window, attributes[NORMAL]); print_in_middle(stdscr, 1, 0, getmaxx(stdscr), menu_backtitle, attributes[MAIN_HEADING]); (void) wattrset(main_window, attributes[MAIN_MENU_BOX]); box(main_window, 0, 0); (void) wattrset(main_window, attributes[MAIN_MENU_HEADING]); mvwprintw(main_window, 0, 3, " %s ", prompt); (void) wattrset(main_window, attributes[NORMAL]); set_menu_items(curses_menu, curses_menu_items); /* position the menu at the middle of the screen */ scale_menu(curses_menu, &maxy, &maxx); maxx = min(maxx, mwin_max_cols-2); maxy = mwin_max_lines; menu_window = derwin(main_window, maxy, maxx, 2, (mwin_max_cols-maxx)/2); keypad(menu_window, TRUE); set_menu_win(curses_menu, menu_window); set_menu_sub(curses_menu, menu_window); /* must reassert this after changing items, otherwise returns to a * default of 16 */ set_menu_format(curses_menu, maxy, 1); center_item(selected_index, last_top_row); set_menu_format(curses_menu, maxy, 1); print_function_line(); /* Post the menu */ post_menu(curses_menu); refresh_all_windows(main_window); } static void adj_match_dir(match_f *match_direction) { if (*match_direction == FIND_NEXT_MATCH_DOWN) *match_direction = MATCH_TINKER_PATTERN_DOWN; else if (*match_direction == FIND_NEXT_MATCH_UP) *match_direction = MATCH_TINKER_PATTERN_UP; /* else, do no change.. */ } struct match_state { int in_search; match_f match_direction; char pattern[256]; }; /* Return 0 means I have handled the key. In such a case, ans should hold the * item to center, or -1 otherwise. * Else return -1 . */ static int do_match(int key, struct match_state *state, int *ans) { char c = (char) key; int terminate_search = 0; *ans = -1; if (key == '/' || (state->in_search && key == 27)) { move(0, 0); refresh(); clrtoeol(); state->in_search = 1-state->in_search; bzero(state->pattern, sizeof(state->pattern)); state->match_direction = MATCH_TINKER_PATTERN_DOWN; return 0; } else if (!state->in_search) return 1; if (isalnum(c) || isgraph(c) || c == ' ') { state->pattern[strlen(state->pattern)] = c; state->pattern[strlen(state->pattern)] = '\0'; adj_match_dir(&state->match_direction); *ans = get_mext_match(state->pattern, state->match_direction); } else if (key == KEY_DOWN) { state->match_direction = FIND_NEXT_MATCH_DOWN; *ans = get_mext_match(state->pattern, state->match_direction); } else if (key == KEY_UP) { state->match_direction = FIND_NEXT_MATCH_UP; *ans = get_mext_match(state->pattern, state->match_direction); } else if (key == KEY_BACKSPACE || key == 127) { state->pattern[strlen(state->pattern)-1] = '\0'; adj_match_dir(&state->match_direction); } else terminate_search = 1; if (terminate_search) { state->in_search = 0; bzero(state->pattern, sizeof(state->pattern)); move(0, 0); refresh(); clrtoeol(); return -1; } return 0; } static void conf(struct menu *menu) { struct menu *submenu = 0; const char *prompt = menu_get_prompt(menu); struct symbol *sym; int res; int current_index = 0; int last_top_row = 0; struct match_state match_state = { .in_search = 0, .match_direction = MATCH_TINKER_PATTERN_DOWN, .pattern = "", }; while (!global_exit) { reset_menu(); current_menu = menu; build_conf(menu); if (!child_count) break; show_menu(prompt ? _(prompt) : _("Main Menu"), _(menu_instructions), current_index, &last_top_row); keypad((menu_win(curses_menu)), TRUE); while (!global_exit) { if (match_state.in_search) { mvprintw(0, 0, "searching: %s", match_state.pattern); clrtoeol(); } refresh_all_windows(main_window); res = wgetch(menu_win(curses_menu)); if (!res) break; if (do_match(res, &match_state, &current_index) == 0) { if (current_index != -1) center_item(current_index, &last_top_row); continue; } if (process_special_keys(&res, (struct menu *) item_data())) break; switch (res) { case KEY_DOWN: menu_driver(curses_menu, REQ_DOWN_ITEM); break; case KEY_UP: menu_driver(curses_menu, REQ_UP_ITEM); break; case KEY_NPAGE: menu_driver(curses_menu, REQ_SCR_DPAGE); break; case KEY_PPAGE: menu_driver(curses_menu, REQ_SCR_UPAGE); break; case KEY_HOME: menu_driver(curses_menu, REQ_FIRST_ITEM); break; case KEY_END: menu_driver(curses_menu, REQ_LAST_ITEM); break; case 'h': case '?': show_help((struct menu *) item_data()); break; } if (res == 10 || res == 27 || res == 32 || res == 'n' || res == 'y' || res == KEY_LEFT || res == KEY_RIGHT || res == 'm') break; refresh_all_windows(main_window); } refresh_all_windows(main_window); /* if ESC or left*/ if (res == 27 || (menu != &rootmenu && res == KEY_LEFT)) break; /* remember location in the menu */ last_top_row = top_row(curses_menu); current_index = curses_item_index(); if (!item_tag()) continue; submenu = (struct menu *) item_data(); if (!submenu || !menu_is_visible(submenu)) continue; sym = submenu->sym; switch (res) { case ' ': if (item_is_tag('t')) sym_toggle_tristate_value(sym); else if (item_is_tag('m')) conf(submenu); break; case KEY_RIGHT: case 10: /* ENTER WAS PRESSED */ switch (item_tag()) { case 'm': if (single_menu_mode) submenu->data = (void *) (long) !submenu->data; else conf(submenu); break; case 't': if (sym_is_choice(sym) && sym_get_tristate_value(sym) == yes) conf_choice(submenu); else if (submenu->prompt && submenu->prompt->type == P_MENU) conf(submenu); else if (res == 10) sym_toggle_tristate_value(sym); break; case 's': conf_string(submenu); break; } break; case 'y': if (item_is_tag('t')) { if (sym_set_tristate_value(sym, yes)) break; if (sym_set_tristate_value(sym, mod)) btn_dialog(main_window, setmod_text, 0); } break; case 'n': if (item_is_tag('t')) sym_set_tristate_value(sym, no); break; case 'm': if (item_is_tag('t')) sym_set_tristate_value(sym, mod); break; } } } static void conf_message_callback(const char *fmt, va_list ap) { char buf[1024]; vsnprintf(buf, sizeof(buf), fmt, ap); btn_dialog(main_window, buf, 1, "<OK>"); } static void show_help(struct menu *menu) { struct gstr help; if (!menu) return; help = str_new(); menu_get_ext_help(menu, &help); show_scroll_win(main_window, _(menu_get_prompt(menu)), str_get(&help)); str_free(&help); } static void conf_choice(struct menu *menu) { const char *prompt = _(menu_get_prompt(menu)); struct menu *child = 0; struct symbol *active; int selected_index = 0; int last_top_row = 0; int res, i = 0; struct match_state match_state = { .in_search = 0, .match_direction = MATCH_TINKER_PATTERN_DOWN, .pattern = "", }; active = sym_get_choice_value(menu->sym); /* this is mostly duplicated from the conf() function. */ while (!global_exit) { reset_menu(); for (i = 0, child = menu->list; child; child = child->next) { if (!show_all_items && !menu_is_visible(child)) continue; if (child->sym == sym_get_choice_value(menu->sym)) item_make(child, ':', "<X> %s", _(menu_get_prompt(child))); else if (child->sym) item_make(child, ':', " %s", _(menu_get_prompt(child))); else item_make(child, ':', "*** %s ***", _(menu_get_prompt(child))); if (child->sym == active){ last_top_row = top_row(curses_menu); selected_index = i; } i++; } show_menu(prompt ? _(prompt) : _("Choice Menu"), _(radiolist_instructions), selected_index, &last_top_row); while (!global_exit) { if (match_state.in_search) { mvprintw(0, 0, "searching: %s", match_state.pattern); clrtoeol(); } refresh_all_windows(main_window); res = wgetch(menu_win(curses_menu)); if (!res) break; if (do_match(res, &match_state, &selected_index) == 0) { if (selected_index != -1) center_item(selected_index, &last_top_row); continue; } if (process_special_keys( &res, (struct menu *) item_data())) break; switch (res) { case KEY_DOWN: menu_driver(curses_menu, REQ_DOWN_ITEM); break; case KEY_UP: menu_driver(curses_menu, REQ_UP_ITEM); break; case KEY_NPAGE: menu_driver(curses_menu, REQ_SCR_DPAGE); break; case KEY_PPAGE: menu_driver(curses_menu, REQ_SCR_UPAGE); break; case KEY_HOME: menu_driver(curses_menu, REQ_FIRST_ITEM); break; case KEY_END: menu_driver(curses_menu, REQ_LAST_ITEM); break; case 'h': case '?': show_help((struct menu *) item_data()); break; } if (res == 10 || res == 27 || res == ' ' || res == KEY_LEFT){ break; } refresh_all_windows(main_window); } /* if ESC or left */ if (res == 27 || res == KEY_LEFT) break; child = item_data(); if (!child || !menu_is_visible(child) || !child->sym) continue; switch (res) { case ' ': case 10: case KEY_RIGHT: sym_set_tristate_value(child->sym, yes); return; case 'h': case '?': show_help(child); active = child->sym; break; case KEY_EXIT: return; } } } static void conf_string(struct menu *menu) { const char *prompt = menu_get_prompt(menu); while (1) { int res; const char *heading; switch (sym_get_type(menu->sym)) { case S_INT: heading = _(inputbox_instructions_int); break; case S_HEX: heading = _(inputbox_instructions_hex); break; case S_STRING: heading = _(inputbox_instructions_string); break; default: heading = _("Internal nconf error!"); } res = dialog_inputbox(main_window, prompt ? _(prompt) : _("Main Menu"), heading, sym_get_string_value(menu->sym), &dialog_input_result, &dialog_input_result_len); switch (res) { case 0: if (sym_set_string_value(menu->sym, dialog_input_result)) return; btn_dialog(main_window, _("You have made an invalid entry."), 0); break; case 1: show_help(menu); break; case KEY_EXIT: return; } } } static void conf_load(void) { while (1) { int res; res = dialog_inputbox(main_window, NULL, load_config_text, filename, &dialog_input_result, &dialog_input_result_len); switch (res) { case 0: if (!dialog_input_result[0]) return; if (!conf_read(dialog_input_result)) { set_config_filename(dialog_input_result); sym_set_change_count(1); return; } btn_dialog(main_window, _("File does not exist!"), 0); break; case 1: show_scroll_win(main_window, _("Load Alternate Configuration"), load_config_help); break; case KEY_EXIT: return; } } } static void conf_save(void) { while (1) { int res; res = dialog_inputbox(main_window, NULL, save_config_text, filename, &dialog_input_result, &dialog_input_result_len); switch (res) { case 0: if (!dialog_input_result[0]) return; res = conf_write(dialog_input_result); if (!res) { set_config_filename(dialog_input_result); return; } btn_dialog(main_window, _("Can't create file! " "Probably a nonexistent directory."), 1, "<OK>"); break; case 1: show_scroll_win(main_window, _("Save Alternate Configuration"), save_config_help); break; case KEY_EXIT: return; } } } void setup_windows(void) { int lines, columns; getmaxyx(stdscr, lines, columns); if (main_window != NULL) delwin(main_window); /* set up the menu and menu window */ main_window = newwin(lines-2, columns-2, 2, 1); keypad(main_window, TRUE); mwin_max_lines = lines-7; mwin_max_cols = columns-6; /* panels order is from bottom to top */ new_panel(main_window); } int main(int ac, char **av) { int lines, columns; char *mode; setlocale(LC_ALL, ""); bindtextdomain(PACKAGE, LOCALEDIR); textdomain(PACKAGE); if (ac > 1 && strcmp(av[1], "-s") == 0) { /* Silence conf_read() until the real callback is set up */ conf_set_message_callback(NULL); av++; } conf_parse(av[1]); conf_read(NULL); mode = getenv("NCONFIG_MODE"); if (mode) { if (!strcasecmp(mode, "single_menu")) single_menu_mode = 1; } /* Initialize curses */ initscr(); /* set color theme */ set_colors(); cbreak(); noecho(); keypad(stdscr, TRUE); curs_set(0); getmaxyx(stdscr, lines, columns); if (columns < 75 || lines < 20) { endwin(); printf("Your terminal should have at " "least 20 lines and 75 columns\n"); return 1; } notimeout(stdscr, FALSE); #if NCURSES_REENTRANT set_escdelay(1); #else ESCDELAY = 1; #endif /* set btns menu */ curses_menu = new_menu(curses_menu_items); menu_opts_off(curses_menu, O_SHOWDESC); menu_opts_on(curses_menu, O_SHOWMATCH); menu_opts_on(curses_menu, O_ONEVALUE); menu_opts_on(curses_menu, O_NONCYCLIC); menu_opts_on(curses_menu, O_IGNORECASE); set_menu_mark(curses_menu, " "); set_menu_fore(curses_menu, attributes[MAIN_MENU_FORE]); set_menu_back(curses_menu, attributes[MAIN_MENU_BACK]); set_menu_grey(curses_menu, attributes[MAIN_MENU_GREY]); set_config_filename(conf_get_configname()); setup_windows(); /* check for KEY_FUNC(1) */ if (has_key(KEY_F(1)) == FALSE) { show_scroll_win(main_window, _("Instructions"), _(menu_no_f_instructions)); } conf_set_message_callback(conf_message_callback); /* do the work */ while (!global_exit) { conf(&rootmenu); if (!global_exit && do_exit() == 0) break; } /* ok, we are done */ unpost_menu(curses_menu); free_menu(curses_menu); delwin(main_window); clear(); refresh(); endwin(); return 0; }
null
null
null
null
117,893
50,921
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
50,921
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_WM_CORE_WINDOW_UTIL_H_ #define UI_WM_CORE_WINDOW_UTIL_H_ #include <memory> #include <utility> #include <vector> #include "base/callback_forward.h" #include "base/compiler_specific.h" #include "ui/base/ui_base_types.h" #include "ui/wm/core/wm_core_export.h" namespace aura { class Window; } namespace ui { class Layer; class LayerOwner; class LayerTreeOwner; } namespace wm { WM_CORE_EXPORT void ActivateWindow(aura::Window* window); WM_CORE_EXPORT void DeactivateWindow(aura::Window* window); WM_CORE_EXPORT bool IsActiveWindow(const aura::Window* window); WM_CORE_EXPORT bool CanActivateWindow(aura::Window* window); WM_CORE_EXPORT void SetWindowFullscreen(aura::Window* window, bool fullscreen); // Returns true if |window|'s show state is |state|. WM_CORE_EXPORT bool WindowStateIs(aura::Window* window, ui::WindowShowState state); // Sets the window state to |state|. WM_CORE_EXPORT void SetWindowState(aura::Window* window, ui::WindowShowState state); // Changes a window's state to its pre-minimized state. WM_CORE_EXPORT void Unminimize(aura::Window* window); // Retrieves the activatable window for |window|. The ActivationClient makes // this determination. WM_CORE_EXPORT aura::Window* GetActivatableWindow(aura::Window* window); // Retrieves the toplevel window for |window|. The ActivationClient makes this // determination. WM_CORE_EXPORT aura::Window* GetToplevelWindow(aura::Window* window); // Returns the existing Layer for |root| (and all its descendants) and creates // a new layer for |root| and all its descendants. This is intended for // animations that want to animate between the existing visuals and a new state. // // As a result of this |root| has freshly created layers, meaning the layers // have not yet been painted to. WM_CORE_EXPORT std::unique_ptr<ui::LayerTreeOwner> RecreateLayers( ui::LayerOwner* root); using MapLayerFunc = base::RepeatingCallback<std::unique_ptr<ui::Layer>(ui::LayerOwner*)>; // Maps |map_func| over each layer of the layer tree and returns a copy of the // layer tree. The recursion stops at the level when |map_func| returns nullptr // on the owner's layer. MapLayers might return nullptr when |map_func| returns // nullptr on the root layer's owner. WM_CORE_EXPORT std::unique_ptr<ui::LayerTreeOwner> RecreateLayersWithClosure( ui::LayerOwner* root, const MapLayerFunc& map_func); // Returns a layer tree that mirrors |root|. Used for live window previews. If // |sync_bounds| is true, the bounds of all mirror layers except the root are // synchronized. See |sync_bounds_| in ui::Layer. WM_CORE_EXPORT std::unique_ptr<ui::LayerTreeOwner> MirrorLayers( ui::LayerOwner* root, bool sync_bounds); // Convenience functions that get the TransientWindowManager for the window and // redirect appropriately. These are preferable to calling functions on // TransientWindowManager as they handle the appropriate NULL checks. WM_CORE_EXPORT aura::Window* GetTransientParent(aura::Window* window); WM_CORE_EXPORT const aura::Window* GetTransientParent( const aura::Window* window); WM_CORE_EXPORT const std::vector<aura::Window*>& GetTransientChildren( const aura::Window* window); WM_CORE_EXPORT void AddTransientChild(aura::Window* parent, aura::Window* child); WM_CORE_EXPORT void RemoveTransientChild(aura::Window* parent, aura::Window* child); // Returns true if |window| has |ancestor| as a transient ancestor. A transient // ancestor is found by following the transient parent chain of the window. WM_CORE_EXPORT bool HasTransientAncestor(const aura::Window* window, const aura::Window* ancestor); } // namespace wm #endif // UI_WM_CORE_WINDOW_UTIL_H_
null
null
null
null
47,784
3,174
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
3,174
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CONTENT_BROWSER_QUOTA_MOCK_QUOTA_MANAGER_PROXY_H_ #define CONTENT_BROWSER_QUOTA_MOCK_QUOTA_MANAGER_PROXY_H_ #include <stdint.h> #include "base/macros.h" #include "storage/browser/quota/quota_client.h" #include "storage/browser/quota/quota_manager_proxy.h" #include "storage/browser/test/mock_quota_manager.h" #include "third_party/blink/public/mojom/quota/quota_types.mojom.h" #include "url/gurl.h" using storage::QuotaManagerProxy; namespace content { class MockQuotaManager; class MockQuotaManagerProxy : public QuotaManagerProxy { public: // It is ok to give NULL to |quota_manager|. MockQuotaManagerProxy(MockQuotaManager* quota_manager, base::SingleThreadTaskRunner* task_runner); void RegisterClient(QuotaClient* client) override; void SimulateQuotaManagerDestroyed(); // We don't mock them. void NotifyOriginInUse(const url::Origin& origin) override {} void NotifyOriginNoLongerInUse(const url::Origin& origin) override {} void SetUsageCacheEnabled(QuotaClient::ID client_id, const url::Origin& origin, blink::mojom::StorageType type, bool enabled) override {} void GetUsageAndQuota(base::SequencedTaskRunner* original_task_runner, const url::Origin& origin, blink::mojom::StorageType type, QuotaManager::UsageAndQuotaCallback callback) override; // Validates the |client_id| and updates the internal access count // which can be accessed via notify_storage_accessed_count(). // The also records the |origin| and |type| in last_notified_origin_ and // last_notified_type_. void NotifyStorageAccessed(QuotaClient::ID client_id, const url::Origin& origin, blink::mojom::StorageType type) override; // Records the |origin|, |type| and |delta| as last_notified_origin_, // last_notified_type_ and last_notified_delta_ respecitvely. // If non-null MockQuotaManager is given to the constructor this also // updates the manager's internal usage information. void NotifyStorageModified(QuotaClient::ID client_id, const url::Origin& origin, blink::mojom::StorageType type, int64_t delta) override; int notify_storage_accessed_count() const { return storage_accessed_count_; } int notify_storage_modified_count() const { return storage_modified_count_; } url::Origin last_notified_origin() const { return last_notified_origin_; } blink::mojom::StorageType last_notified_type() const { return last_notified_type_; } int64_t last_notified_delta() const { return last_notified_delta_; } protected: ~MockQuotaManagerProxy() override; private: MockQuotaManager* mock_manager() const { return static_cast<MockQuotaManager*>(quota_manager()); } int storage_accessed_count_; int storage_modified_count_; url::Origin last_notified_origin_; blink::mojom::StorageType last_notified_type_; int64_t last_notified_delta_; QuotaClient* registered_client_; DISALLOW_COPY_AND_ASSIGN(MockQuotaManagerProxy); }; } // namespace content #endif // CONTENT_BROWSER_QUOTA_MOCK_QUOTA_MANAGER_PROXY_H_
null
null
null
null
37
43,152
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
43,152
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/strings/utf_string_conversion_utils.h" #include "base/third_party/icu/icu_utf.h" #include "build/build_config.h" namespace base { // ReadUnicodeCharacter -------------------------------------------------------- bool ReadUnicodeCharacter(const char* src, int32_t src_len, int32_t* char_index, uint32_t* code_point_out) { // U8_NEXT expects to be able to use -1 to signal an error, so we must // use a signed type for code_point. But this function returns false // on error anyway, so code_point_out is unsigned. int32_t code_point; CBU8_NEXT(src, *char_index, src_len, code_point); *code_point_out = static_cast<uint32_t>(code_point); // The ICU macro above moves to the next char, we want to point to the last // char consumed. (*char_index)--; // Validate the decoded value. return IsValidCodepoint(code_point); } bool ReadUnicodeCharacter(const char16* src, int32_t src_len, int32_t* char_index, uint32_t* code_point) { if (CBU16_IS_SURROGATE(src[*char_index])) { if (!CBU16_IS_SURROGATE_LEAD(src[*char_index]) || *char_index + 1 >= src_len || !CBU16_IS_TRAIL(src[*char_index + 1])) { // Invalid surrogate pair. return false; } // Valid surrogate pair. *code_point = CBU16_GET_SUPPLEMENTARY(src[*char_index], src[*char_index + 1]); (*char_index)++; } else { // Not a surrogate, just one 16-bit word. *code_point = src[*char_index]; } return IsValidCodepoint(*code_point); } #if defined(WCHAR_T_IS_UTF32) bool ReadUnicodeCharacter(const wchar_t* src, int32_t src_len, int32_t* char_index, uint32_t* code_point) { // Conversion is easy since the source is 32-bit. *code_point = src[*char_index]; // Validate the value. return IsValidCodepoint(*code_point); } #endif // defined(WCHAR_T_IS_UTF32) // WriteUnicodeCharacter ------------------------------------------------------- size_t WriteUnicodeCharacter(uint32_t code_point, std::string* output) { if (code_point <= 0x7f) { // Fast path the common case of one byte. output->push_back(static_cast<char>(code_point)); return 1; } // CBU8_APPEND_UNSAFE can append up to 4 bytes. size_t char_offset = output->length(); size_t original_char_offset = char_offset; output->resize(char_offset + CBU8_MAX_LENGTH); CBU8_APPEND_UNSAFE(&(*output)[0], char_offset, code_point); // CBU8_APPEND_UNSAFE will advance our pointer past the inserted character, so // it will represent the new length of the string. output->resize(char_offset); return char_offset - original_char_offset; } size_t WriteUnicodeCharacter(uint32_t code_point, string16* output) { if (CBU16_LENGTH(code_point) == 1) { // Thie code point is in the Basic Multilingual Plane (BMP). output->push_back(static_cast<char16>(code_point)); return 1; } // Non-BMP characters use a double-character encoding. size_t char_offset = output->length(); output->resize(char_offset + CBU16_MAX_LENGTH); CBU16_APPEND_UNSAFE(&(*output)[0], char_offset, code_point); return CBU16_MAX_LENGTH; } // Generalized Unicode converter ----------------------------------------------- template<typename CHAR> void PrepareForUTF8Output(const CHAR* src, size_t src_len, std::string* output) { output->clear(); if (src_len == 0) return; if (src[0] < 0x80) { // Assume that the entire input will be ASCII. output->reserve(src_len); } else { // Assume that the entire input is non-ASCII and will have 3 bytes per char. output->reserve(src_len * 3); } } // Instantiate versions we know callers will need. #if !defined(OS_WIN) // wchar_t and char16 are the same thing on Windows. template void PrepareForUTF8Output(const wchar_t*, size_t, std::string*); #endif template void PrepareForUTF8Output(const char16*, size_t, std::string*); template<typename STRING> void PrepareForUTF16Or32Output(const char* src, size_t src_len, STRING* output) { output->clear(); if (src_len == 0) return; if (static_cast<unsigned char>(src[0]) < 0x80) { // Assume the input is all ASCII, which means 1:1 correspondence. output->reserve(src_len); } else { // Otherwise assume that the UTF-8 sequences will have 2 bytes for each // character. output->reserve(src_len / 2); } } // Instantiate versions we know callers will need. #if !defined(OS_WIN) // std::wstring and string16 are the same thing on Windows. template void PrepareForUTF16Or32Output(const char*, size_t, std::wstring*); #endif template void PrepareForUTF16Or32Output(const char*, size_t, string16*); } // namespace base
null
null
null
null
40,015
13,231
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
13,231
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright 2017 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_PASSWORD_MANAGER_CORE_BROWSER_SUPPRESSED_FORM_FETCHER_H_ #define COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_SUPPRESSED_FORM_FETCHER_H_ #include <memory> #include <vector> #include "base/gtest_prod_util.h" #include "base/macros.h" #include "components/autofill/core/common/password_form.h" #include "components/password_manager/core/browser/password_store_consumer.h" namespace password_manager { class PasswordManagerClient; // Fetches credentials saved for the HTTPS counterpart of the given HTTP realm. // // Filling these HTTPS credentials into forms served over HTTP is obviously // suppressed, the purpose of doing such a query is to collect metrics on how // often this happens and inconveniences the user. // // This logic is implemented by this class, a separate PasswordStore consumer, // to make it very sure that these credentials will not get mistakenly filled. class SuppressedFormFetcher : public PasswordStoreConsumer { public: // Interface to be implemented by the consumer of this class. class Consumer { public: virtual void ProcessSuppressedForms( std::vector<std::unique_ptr<autofill::PasswordForm>> forms) = 0; }; SuppressedFormFetcher(const std::string& observed_signon_realm, const PasswordManagerClient* client, Consumer* consumer); ~SuppressedFormFetcher() override; protected: // PasswordStoreConsumer: void OnGetPasswordStoreResults( std::vector<std::unique_ptr<autofill::PasswordForm>> results) override; private: FRIEND_TEST_ALL_PREFIXES(SuppressedFormFetcherTest, EmptyStore); FRIEND_TEST_ALL_PREFIXES(SuppressedFormFetcherTest, FullStore); // The client and the consumer should outlive |this|. const PasswordManagerClient* client_; Consumer* consumer_; const std::string observed_signon_realm_; DISALLOW_COPY_AND_ASSIGN(SuppressedFormFetcher); }; } // namespace password_manager #endif // COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_SUPPRESSED_FORM_FETCHER_H_
null
null
null
null
10,094
402
null
train_val
a6802e21d824e786d1e2a8440cf749a6e1a8d95f
160,530
ImageMagick
0
https://github.com/ImageMagick/ImageMagick
2017-07-18 18:28:29-04:00
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % CCCC OOO L OOO RRRR SSSSS PPPP AAA CCCC EEEEE % % C O O L O O R R SS P P A A C E % % C O O L O O RRRR SSS PPPP AAAAA C EEE % % C O O L O O R R SS P A A C E % % CCCC OOO LLLLL OOO R R SSSSS P A A CCCC EEEEE % % % % % % MagickCore Image Colorspace Methods % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://www.imagemagick.org/script/license.php % % % % 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/attribute.h" #include "MagickCore/property.h" #include "MagickCore/cache.h" #include "MagickCore/cache-private.h" #include "MagickCore/cache-view.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/gem.h" #include "MagickCore/gem-private.h" #include "MagickCore/memory_.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/pixel-private.h" #include "MagickCore/quantize.h" #include "MagickCore/quantum.h" #include "MagickCore/quantum-private.h" #include "MagickCore/resource_.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/utility.h" /* Typedef declarations. */ typedef struct _TransformPacket { MagickRealType x, y, z; } TransformPacket; /* Forward declarations. */ static MagickBooleanType TransformsRGBImage(Image *,ExceptionInfo *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + s R G B T r a n s f o r m I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % sRGBTransformImage() converts the reference image from sRGB to an alternate % colorspace. The transformation matrices are not the standard ones: the % weights are rescaled to normalized the range of the transformed values to % be [0..QuantumRange]. % % The format of the sRGBTransformImage method is: % % MagickBooleanType sRGBTransformImage(Image *image, % const ColorspaceType colorspace,EsceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o colorspace: the colorspace to transform the image to. % % o exception: return any errors or warnings in this structure. % */ static inline void ConvertRGBToCMY(const double red,const double green, const double blue,double *cyan,double *magenta,double *yellow) { *cyan=QuantumScale*(QuantumRange-red); *magenta=QuantumScale*(QuantumRange-green); *yellow=QuantumScale*(QuantumRange-blue); } static inline void ConvertXYZToLMS(const double x,const double y, const double z,double *L,double *M,double *S) { *L=0.7328*x+0.4296*y-0.1624*z; *M=(-0.7036*x+1.6975*y+0.0061*z); *S=0.0030*x+0.0136*y+0.9834*z; } static void ConvertRGBToLMS(const double red,const double green, const double blue,double *L,double *M,double *S) { double X, Y, Z; ConvertRGBToXYZ(red,green,blue,&X,&Y,&Z); ConvertXYZToLMS(X,Y,Z,L,M,S); } static void ConvertRGBToLab(const double red,const double green, const double blue,double *L,double *a,double *b) { double X, Y, Z; ConvertRGBToXYZ(red,green,blue,&X,&Y,&Z); ConvertXYZToLab(X,Y,Z,L,a,b); } static void ConvertRGBToLuv(const double red,const double green, const double blue,double *L,double *u,double *v) { double X, Y, Z; ConvertRGBToXYZ(red,green,blue,&X,&Y,&Z); ConvertXYZToLuv(X,Y,Z,L,u,v); } static void ConvertRGBToxyY(const double red,const double green, const double blue,double *low_x,double *low_y,double *cap_Y) { double gamma, X, Y, Z; ConvertRGBToXYZ(red,green,blue,&X,&Y,&Z); gamma=PerceptibleReciprocal(X+Y+Z); *low_x=gamma*X; *low_y=gamma*Y; *cap_Y=Y; } static void ConvertRGBToYDbDr(const double red,const double green, const double blue,double *Y,double *Db,double *Dr) { *Y=QuantumScale*(0.298839*red+0.586811*green+0.114350*blue); *Db=QuantumScale*(-0.450*red-0.883*green+1.333*blue)+0.5; *Dr=QuantumScale*(-1.333*red+1.116*green+0.217*blue)+0.5; } static void ConvertRGBToYIQ(const double red,const double green, const double blue,double *Y,double *I,double *Q) { *Y=QuantumScale*(0.298839*red+0.586811*green+0.114350*blue); *I=QuantumScale*(0.595716*red-0.274453*green-0.321263*blue)+0.5; *Q=QuantumScale*(0.211456*red-0.522591*green+0.311135*blue)+0.5; } static void ConvertRGBToYPbPr(const double red,const double green, const double blue,double *Y,double *Pb,double *Pr) { *Y=QuantumScale*(0.298839*red+0.586811*green+0.114350*blue); *Pb=QuantumScale*((-0.1687367)*red-0.331264*green+0.5*blue)+0.5; *Pr=QuantumScale*(0.5*red-0.418688*green-0.081312*blue)+0.5; } static void ConvertRGBToYCbCr(const double red,const double green, const double blue,double *Y,double *Cb,double *Cr) { ConvertRGBToYPbPr(red,green,blue,Y,Cb,Cr); } static void ConvertRGBToYUV(const double red,const double green, const double blue,double *Y,double *U,double *V) { *Y=QuantumScale*(0.298839*red+0.586811*green+0.114350*blue); *U=QuantumScale*((-0.147)*red-0.289*green+0.436*blue)+0.5; *V=QuantumScale*(0.615*red-0.515*green-0.100*blue)+0.5; } static MagickBooleanType sRGBTransformImage(Image *image, const ColorspaceType colorspace,ExceptionInfo *exception) { #define sRGBTransformImageTag "RGBTransform/Image" CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; PrimaryInfo primary_info; register ssize_t i; ssize_t y; TransformPacket *x_map, *y_map, *z_map; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(colorspace != sRGBColorspace); assert(colorspace != TransparentColorspace); assert(colorspace != UndefinedColorspace); status=MagickTrue; progress=0; switch (colorspace) { case CMYKColorspace: { PixelInfo zero; /* Convert RGB to CMYK colorspace. */ if (image->storage_class == PseudoClass) { if (SyncImage(image,exception) == MagickFalse) return(MagickFalse); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); } if (SetImageColorspace(image,colorspace,exception) == MagickFalse) return(MagickFalse); GetPixelInfo(image,&zero); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; PixelInfo pixel; register ssize_t x; register Quantum *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } pixel=zero; for (x=0; x < (ssize_t) image->columns; x++) { GetPixelInfoPixel(image,q,&pixel); ConvertRGBToCMYK(&pixel); SetPixelViaPixelInfo(image,&pixel,q); q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); image->type=image->alpha_trait == UndefinedPixelTrait ? ColorSeparationType : ColorSeparationAlphaType; if (SetImageColorspace(image,colorspace,exception) == MagickFalse) return(MagickFalse); return(status); } case GRAYColorspace: { /* Transform image from sRGB to GRAY. */ if (image->storage_class == PseudoClass) { if (SyncImage(image,exception) == MagickFalse) return(MagickFalse); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); } image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; register ssize_t x; register Quantum *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { SetPixelGray(image,ClampToQuantum(GetPixelIntensity(image,q)),q); q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); if (SetImageColorspace(image,colorspace,exception) == MagickFalse) return(MagickFalse); image->type=GrayscaleType; return(status); } case CMYColorspace: case HCLColorspace: case HCLpColorspace: case HSBColorspace: case HSIColorspace: case HSLColorspace: case HSVColorspace: case HWBColorspace: case LabColorspace: case LCHColorspace: case LCHabColorspace: case LCHuvColorspace: case LMSColorspace: case LuvColorspace: case xyYColorspace: case XYZColorspace: case YCbCrColorspace: case YDbDrColorspace: case YIQColorspace: case YPbPrColorspace: case YUVColorspace: { /* Transform image from sRGB to target colorspace. */ if (image->storage_class == PseudoClass) { if (SyncImage(image,exception) == MagickFalse) return(MagickFalse); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); } image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; register ssize_t x; register Quantum *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double blue, green, red, X, Y, Z; red=(double) GetPixelRed(image,q); green=(double) GetPixelGreen(image,q); blue=(double) GetPixelBlue(image,q); switch (colorspace) { case CMYColorspace: { ConvertRGBToCMY(red,green,blue,&X,&Y,&Z); break; } case HCLColorspace: { ConvertRGBToHCL(red,green,blue,&X,&Y,&Z); break; } case HCLpColorspace: { ConvertRGBToHCLp(red,green,blue,&X,&Y,&Z); break; } case HSBColorspace: { ConvertRGBToHSB(red,green,blue,&X,&Y,&Z); break; } case HSIColorspace: { ConvertRGBToHSI(red,green,blue,&X,&Y,&Z); break; } case HSLColorspace: { ConvertRGBToHSL(red,green,blue,&X,&Y,&Z); break; } case HSVColorspace: { ConvertRGBToHSV(red,green,blue,&X,&Y,&Z); break; } case HWBColorspace: { ConvertRGBToHWB(red,green,blue,&X,&Y,&Z); break; } case LabColorspace: { ConvertRGBToLab(red,green,blue,&X,&Y,&Z); break; } case LCHColorspace: case LCHabColorspace: { ConvertRGBToLCHab(red,green,blue,&X,&Y,&Z); break; } case LCHuvColorspace: { ConvertRGBToLCHuv(red,green,blue,&X,&Y,&Z); break; } case LMSColorspace: { ConvertRGBToLMS(red,green,blue,&X,&Y,&Z); break; } case LuvColorspace: { ConvertRGBToLuv(red,green,blue,&X,&Y,&Z); break; } case xyYColorspace: { ConvertRGBToxyY(red,green,blue,&X,&Y,&Z); break; } case XYZColorspace: { ConvertRGBToXYZ(red,green,blue,&X,&Y,&Z); break; } case YCbCrColorspace: { ConvertRGBToYCbCr(red,green,blue,&X,&Y,&Z); break; } case YDbDrColorspace: { ConvertRGBToYDbDr(red,green,blue,&X,&Y,&Z); break; } case YIQColorspace: { ConvertRGBToYIQ(red,green,blue,&X,&Y,&Z); break; } case YPbPrColorspace: { ConvertRGBToYPbPr(red,green,blue,&X,&Y,&Z); break; } case YUVColorspace: { ConvertRGBToYUV(red,green,blue,&X,&Y,&Z); break; } default: { X=QuantumScale*red; Y=QuantumScale*green; Z=QuantumScale*blue; break; } } SetPixelRed(image,ClampToQuantum(QuantumRange*X),q); SetPixelGreen(image,ClampToQuantum(QuantumRange*Y),q); SetPixelBlue(image,ClampToQuantum(QuantumRange*Z),q); q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); if (SetImageColorspace(image,colorspace,exception) == MagickFalse) return(MagickFalse); return(status); } case LogColorspace: { #define DisplayGamma (1.0/1.7) #define FilmGamma 0.6 #define ReferenceBlack 95.0 #define ReferenceWhite 685.0 const char *value; double black, density, film_gamma, gamma, reference_black, reference_white; Quantum *logmap; /* Transform RGB to Log colorspace. */ density=DisplayGamma; gamma=DisplayGamma; value=GetImageProperty(image,"gamma",exception); if (value != (const char *) NULL) gamma=PerceptibleReciprocal(StringToDouble(value,(char **) NULL)); film_gamma=FilmGamma; value=GetImageProperty(image,"film-gamma",exception); if (value != (const char *) NULL) film_gamma=StringToDouble(value,(char **) NULL); reference_black=ReferenceBlack; value=GetImageProperty(image,"reference-black",exception); if (value != (const char *) NULL) reference_black=StringToDouble(value,(char **) NULL); reference_white=ReferenceWhite; value=GetImageProperty(image,"reference-white",exception); if (value != (const char *) NULL) reference_white=StringToDouble(value,(char **) NULL); logmap=(Quantum *) AcquireQuantumMemory((size_t) MaxMap+1UL, sizeof(*logmap)); if (logmap == (Quantum *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); black=pow(10.0,(reference_black-reference_white)*(gamma/density)*0.002/ film_gamma); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) \ magick_threads(image,image,1,1) #endif for (i=0; i <= (ssize_t) MaxMap; i++) logmap[i]=ScaleMapToQuantum((double) (MaxMap*(reference_white+ log10(black+(1.0*i/MaxMap)*(1.0-black))/((gamma/density)*0.002/ film_gamma))/1024.0)); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; register ssize_t x; register Quantum *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=(ssize_t) image->columns; x != 0; x--) { double blue, green, red; red=(double) DecodePixelGamma((MagickRealType) GetPixelRed(image,q)); green=(double) DecodePixelGamma((MagickRealType) GetPixelGreen(image,q)); blue=(double) DecodePixelGamma((MagickRealType) GetPixelBlue(image,q)); SetPixelRed(image,logmap[ScaleQuantumToMap(ClampToQuantum(red))],q); SetPixelGreen(image,logmap[ScaleQuantumToMap(ClampToQuantum(green))], q); SetPixelBlue(image,logmap[ScaleQuantumToMap(ClampToQuantum(blue))],q); q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); logmap=(Quantum *) RelinquishMagickMemory(logmap); if (SetImageColorspace(image,colorspace,exception) == MagickFalse) return(MagickFalse); return(status); } case RGBColorspace: case scRGBColorspace: { /* Transform image from sRGB to linear RGB. */ if (image->storage_class == PseudoClass) { if (SyncImage(image,exception) == MagickFalse) return(MagickFalse); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); } image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; register ssize_t x; register Quantum *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double blue, green, red; red=DecodePixelGamma((MagickRealType) GetPixelRed(image,q)); green=DecodePixelGamma((MagickRealType) GetPixelGreen(image,q)); blue=DecodePixelGamma((MagickRealType) GetPixelBlue(image,q)); SetPixelRed(image,ClampToQuantum(red),q); SetPixelGreen(image,ClampToQuantum(green),q); SetPixelBlue(image,ClampToQuantum(blue),q); q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); if (SetImageColorspace(image,colorspace,exception) == MagickFalse) return(MagickFalse); return(status); } default: break; } /* Allocate the tables. */ x_map=(TransformPacket *) AcquireQuantumMemory((size_t) MaxMap+1UL, sizeof(*x_map)); y_map=(TransformPacket *) AcquireQuantumMemory((size_t) MaxMap+1UL, sizeof(*y_map)); z_map=(TransformPacket *) AcquireQuantumMemory((size_t) MaxMap+1UL, sizeof(*z_map)); if ((x_map == (TransformPacket *) NULL) || (y_map == (TransformPacket *) NULL) || (z_map == (TransformPacket *) NULL)) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); (void) ResetMagickMemory(&primary_info,0,sizeof(primary_info)); switch (colorspace) { case OHTAColorspace: { /* Initialize OHTA tables: I1 = 0.33333*R+0.33334*G+0.33333*B I2 = 0.50000*R+0.00000*G-0.50000*B I3 =-0.25000*R+0.50000*G-0.25000*B I and Q, normally -0.5 through 0.5, are normalized to the range 0 through QuantumRange. */ primary_info.y=(double) (MaxMap+1.0)/2.0; primary_info.z=(double) (MaxMap+1.0)/2.0; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) \ magick_threads(image,image,1,1) #endif for (i=0; i <= (ssize_t) MaxMap; i++) { x_map[i].x=(MagickRealType) (0.33333*(double) i); y_map[i].x=(MagickRealType) (0.33334*(double) i); z_map[i].x=(MagickRealType) (0.33333*(double) i); x_map[i].y=(MagickRealType) (0.50000*(double) i); y_map[i].y=(MagickRealType) (0.00000*(double) i); z_map[i].y=(MagickRealType) (-0.50000*(double) i); x_map[i].z=(MagickRealType) (-0.25000*(double) i); y_map[i].z=(MagickRealType) (0.50000*(double) i); z_map[i].z=(MagickRealType) (-0.25000*(double) i); } break; } case Rec601YCbCrColorspace: { /* Initialize YCbCr tables (ITU-R BT.601): Y = 0.2988390*R+0.5868110*G+0.1143500*B Cb= -0.1687367*R-0.3312640*G+0.5000000*B Cr= 0.5000000*R-0.4186880*G-0.0813120*B Cb and Cr, normally -0.5 through 0.5, are normalized to the range 0 through QuantumRange. */ primary_info.y=(double) (MaxMap+1.0)/2.0; primary_info.z=(double) (MaxMap+1.0)/2.0; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) \ magick_threads(image,image,1,1) #endif for (i=0; i <= (ssize_t) MaxMap; i++) { x_map[i].x=(MagickRealType) (0.298839*(double) i); y_map[i].x=(MagickRealType) (0.586811*(double) i); z_map[i].x=(MagickRealType) (0.114350*(double) i); x_map[i].y=(MagickRealType) (-0.1687367*(double) i); y_map[i].y=(MagickRealType) (-0.331264*(double) i); z_map[i].y=(MagickRealType) (0.500000*(double) i); x_map[i].z=(MagickRealType) (0.500000*(double) i); y_map[i].z=(MagickRealType) (-0.418688*(double) i); z_map[i].z=(MagickRealType) (-0.081312*(double) i); } break; } case Rec709YCbCrColorspace: { /* Initialize YCbCr tables (ITU-R BT.709): Y = 0.212656*R+0.715158*G+0.072186*B Cb= -0.114572*R-0.385428*G+0.500000*B Cr= 0.500000*R-0.454153*G-0.045847*B Cb and Cr, normally -0.5 through 0.5, are normalized to the range 0 through QuantumRange. */ primary_info.y=(double) (MaxMap+1.0)/2.0; primary_info.z=(double) (MaxMap+1.0)/2.0; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) \ magick_threads(image,image,1,1) #endif for (i=0; i <= (ssize_t) MaxMap; i++) { x_map[i].x=(MagickRealType) (0.212656*(double) i); y_map[i].x=(MagickRealType) (0.715158*(double) i); z_map[i].x=(MagickRealType) (0.072186*(double) i); x_map[i].y=(MagickRealType) (-0.114572*(double) i); y_map[i].y=(MagickRealType) (-0.385428*(double) i); z_map[i].y=(MagickRealType) (0.500000*(double) i); x_map[i].z=(MagickRealType) (0.500000*(double) i); y_map[i].z=(MagickRealType) (-0.454153*(double) i); z_map[i].z=(MagickRealType) (-0.045847*(double) i); } break; } case YCCColorspace: { /* Initialize YCC tables: Y = 0.298839*R+0.586811*G+0.114350*B C1= -0.298839*R-0.586811*G+0.88600*B C2= 0.70100*R-0.586811*G-0.114350*B YCC is scaled by 1.3584. C1 zero is 156 and C2 is at 137. */ primary_info.y=(double) ScaleQuantumToMap(ScaleCharToQuantum(156)); primary_info.z=(double) ScaleQuantumToMap(ScaleCharToQuantum(137)); for (i=0; i <= (ssize_t) (0.018*MaxMap); i++) { x_map[i].x=0.005382*i; y_map[i].x=0.010566*i; z_map[i].x=0.002052*i; x_map[i].y=(-0.003296)*i; y_map[i].y=(-0.006471)*i; z_map[i].y=0.009768*i; x_map[i].z=0.009410*i; y_map[i].z=(-0.007880)*i; z_map[i].z=(-0.001530)*i; } for ( ; i <= (ssize_t) MaxMap; i++) { x_map[i].x=0.298839*(1.099*i-0.099); y_map[i].x=0.586811*(1.099*i-0.099); z_map[i].x=0.114350*(1.099*i-0.099); x_map[i].y=(-0.298839)*(1.099*i-0.099); y_map[i].y=(-0.586811)*(1.099*i-0.099); z_map[i].y=0.88600*(1.099*i-0.099); x_map[i].z=0.70100*(1.099*i-0.099); y_map[i].z=(-0.586811)*(1.099*i-0.099); z_map[i].z=(-0.114350)*(1.099*i-0.099); } break; } default: { /* Linear conversion tables. */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) \ magick_threads(image,image,1,1) #endif for (i=0; i <= (ssize_t) MaxMap; i++) { x_map[i].x=(MagickRealType) (1.0*(double) i); y_map[i].x=(MagickRealType) 0.0; z_map[i].x=(MagickRealType) 0.0; x_map[i].y=(MagickRealType) 0.0; y_map[i].y=(MagickRealType) (1.0*(double) i); z_map[i].y=(MagickRealType) 0.0; x_map[i].z=(MagickRealType) 0.0; y_map[i].z=(MagickRealType) 0.0; z_map[i].z=(MagickRealType) (1.0*(double) i); } break; } } /* Convert from sRGB. */ switch (image->storage_class) { case DirectClass: default: { /* Convert DirectClass image. */ image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; PixelInfo pixel; register Quantum *magick_restrict q; register ssize_t x; register unsigned int blue, green, red; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { red=ScaleQuantumToMap(ClampToQuantum((MagickRealType) GetPixelRed(image,q))); green=ScaleQuantumToMap(ClampToQuantum((MagickRealType) GetPixelGreen(image,q))); blue=ScaleQuantumToMap(ClampToQuantum((MagickRealType) GetPixelBlue(image,q))); pixel.red=(x_map[red].x+y_map[green].x+z_map[blue].x)+ primary_info.x; pixel.green=(x_map[red].y+y_map[green].y+z_map[blue].y)+ primary_info.y; pixel.blue=(x_map[red].z+y_map[green].z+z_map[blue].z)+ primary_info.z; SetPixelRed(image,ScaleMapToQuantum(pixel.red),q); SetPixelGreen(image,ScaleMapToQuantum(pixel.green),q); SetPixelBlue(image,ScaleMapToQuantum(pixel.blue),q); q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_sRGBTransformImage) #endif proceed=SetImageProgress(image,sRGBTransformImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); break; } case PseudoClass: { register unsigned int blue, green, red; /* Convert PseudoClass image. */ for (i=0; i < (ssize_t) image->colors; i++) { PixelInfo pixel; red=ScaleQuantumToMap(ClampToQuantum(image->colormap[i].red)); green=ScaleQuantumToMap(ClampToQuantum(image->colormap[i].green)); blue=ScaleQuantumToMap(ClampToQuantum(image->colormap[i].blue)); pixel.red=x_map[red].x+y_map[green].x+z_map[blue].x+primary_info.x; pixel.green=x_map[red].y+y_map[green].y+z_map[blue].y+primary_info.y; pixel.blue=x_map[red].z+y_map[green].z+z_map[blue].z+primary_info.z; image->colormap[i].red=(double) ScaleMapToQuantum(pixel.red); image->colormap[i].green=(double) ScaleMapToQuantum(pixel.green); image->colormap[i].blue=(double) ScaleMapToQuantum(pixel.blue); } (void) SyncImage(image,exception); break; } } /* Relinquish resources. */ z_map=(TransformPacket *) RelinquishMagickMemory(z_map); y_map=(TransformPacket *) RelinquishMagickMemory(y_map); x_map=(TransformPacket *) RelinquishMagickMemory(x_map); if (SetImageColorspace(image,colorspace,exception) == MagickFalse) return(MagickFalse); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e C o l o r s p a c e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageColorspace() sets the colorspace member of the Image structure. % % The format of the SetImageColorspace method is: % % MagickBooleanType SetImageColorspace(Image *image, % const ColorspaceType colorspace,ExceptiionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o colorspace: the colorspace. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SetImageColorspace(Image *image, const ColorspaceType colorspace,ExceptionInfo *exception) { ImageType type; MagickBooleanType status; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if (image->colorspace == colorspace) return(MagickTrue); image->colorspace=colorspace; image->rendering_intent=UndefinedIntent; image->gamma=1.000/2.200; (void) ResetMagickMemory(&image->chromaticity,0,sizeof(image->chromaticity)); type=image->type; if (IsGrayColorspace(colorspace) != MagickFalse) { if ((image->intensity == Rec601LuminancePixelIntensityMethod) || (image->intensity == Rec709LuminancePixelIntensityMethod)) image->gamma=1.000; type=GrayscaleType; } else if ((IsRGBColorspace(colorspace) != MagickFalse) || (colorspace == XYZColorspace) || (colorspace == xyYColorspace)) image->gamma=1.000; else { image->rendering_intent=PerceptualIntent; image->chromaticity.red_primary.x=0.6400; image->chromaticity.red_primary.y=0.3300; image->chromaticity.red_primary.z=0.0300; image->chromaticity.green_primary.x=0.3000; image->chromaticity.green_primary.y=0.6000; image->chromaticity.green_primary.z=0.1000; image->chromaticity.blue_primary.x=0.1500; image->chromaticity.blue_primary.y=0.0600; image->chromaticity.blue_primary.z=0.7900; image->chromaticity.white_point.x=0.3127; image->chromaticity.white_point.y=0.3290; image->chromaticity.white_point.z=0.3583; } status=SyncImagePixelCache(image,exception); image->type=type; return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e G r a y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageGray() returns MagickTrue if all the pixels in the image have the % same red, green, and blue intensities and changes the type of the image to % bi-level or grayscale. % % The format of the SetImageGray method is: % % MagickBooleanType SetImageGray(const Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SetImageGray(Image *image, ExceptionInfo *exception) { const char *value; ImageType type; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (IsImageGray(image)) return(MagickTrue); if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) return(MagickFalse); value=GetImageProperty(image,"colorspace:auto-grayscale",exception); if (IsStringFalse(value) != MagickFalse) return(MagickFalse); type=IdentifyImageGray(image,exception); if (type == UndefinedType) return(MagickFalse); image->colorspace=GRAYColorspace; if (SyncImagePixelCache((Image *) image,exception) == MagickFalse) return(MagickFalse); image->type=type; return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e M o n o c h r o m e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageMonochrome() returns MagickTrue if all the pixels in the image have % the same red, green, and blue intensities and the intensity is either % 0 or QuantumRange and changes the type of the image to bi-level. % % The format of the SetImageMonochrome method is: % % MagickBooleanType SetImageMonochrome(Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SetImageMonochrome(Image *image, ExceptionInfo *exception) { const char *value; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->type == BilevelType) return(MagickTrue); if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) return(MagickFalse); value=GetImageProperty(image,"colorspace:auto-grayscale",exception); if (IsStringFalse(value) != MagickFalse) return(MagickFalse); if (IdentifyImageMonochrome(image,exception) == MagickFalse) return(MagickFalse); image->colorspace=GRAYColorspace; if (SyncImagePixelCache((Image *) image,exception) == MagickFalse) return(MagickFalse); image->type=BilevelType; return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % T r a n s f o r m I m a g e C o l o r s p a c e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % TransformImageColorspace() transforms an image colorspace, changing the % image data to reflect the new colorspace. % % The format of the TransformImageColorspace method is: % % MagickBooleanType TransformImageColorspace(Image *image, % const ColorspaceType colorspace,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o colorspace: the colorspace. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType TransformImageColorspace(Image *image, const ColorspaceType colorspace,ExceptionInfo *exception) { MagickBooleanType status; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->colorspace == colorspace) return(SetImageColorspace(image,colorspace,exception)); if ((image->colorspace == GRAYColorspace) && (image->gamma != 1.0) && (colorspace == sRGBColorspace)) return(SetImageColorspace(image,colorspace,exception)); if (colorspace == UndefinedColorspace) return(SetImageColorspace(image,colorspace,exception)); /* Convert the reference image from an alternate colorspace to sRGB. */ (void) DeleteImageProfile(image,"icc"); (void) DeleteImageProfile(image,"icm"); if (IssRGBColorspace(colorspace) != MagickFalse) return(TransformsRGBImage(image,exception)); status=MagickTrue; if (IssRGBColorspace(image->colorspace) == MagickFalse) status=TransformsRGBImage(image,exception); if (status == MagickFalse) return(status); /* Convert the reference image from sRGB to an alternate colorspace. */ if (sRGBTransformImage(image,colorspace,exception) == MagickFalse) status=MagickFalse; return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + T r a n s f o r m s R G B I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % TransformsRGBImage() converts the reference image from an alternate % colorspace to sRGB. The transformation matrices are not the standard ones: % the weights are rescaled to normalize the range of the transformed values % to be [0..QuantumRange]. % % The format of the TransformsRGBImage method is: % % MagickBooleanType TransformsRGBImage(Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ static inline void ConvertCMYToRGB(const double cyan,const double magenta, const double yellow,double *red,double *green,double *blue) { *red=QuantumRange*(1.0-cyan); *green=QuantumRange*(1.0-magenta); *blue=QuantumRange*(1.0-yellow); } static inline void ConvertLMSToXYZ(const double L,const double M,const double S, double *X,double *Y,double *Z) { *X=1.096123820835514*L-0.278869000218287*M+0.182745179382773*S; *Y=0.454369041975359*L+0.473533154307412*M+0.072097803717229*S; *Z=(-0.009627608738429)*L-0.005698031216113*M+1.015325639954543*S; } static inline void ConvertLMSToRGB(const double L,const double M, const double S,double *red,double *green,double *blue) { double X, Y, Z; ConvertLMSToXYZ(L,M,S,&X,&Y,&Z); ConvertXYZToRGB(X,Y,Z,red,green,blue); } static inline void ConvertLuvToRGB(const double L,const double u, const double v,double *red,double *green,double *blue) { double X, Y, Z; ConvertLuvToXYZ(100.0*L,354.0*u-134.0,262.0*v-140.0,&X,&Y,&Z); ConvertXYZToRGB(X,Y,Z,red,green,blue); } static inline ssize_t RoundToYCC(const double value) { if (value <= 0.0) return(0); if (value >= 1388.0) return(1388); return((ssize_t) (value+0.5)); } static inline void ConvertLabToRGB(const double L,const double a, const double b,double *red,double *green,double *blue) { double X, Y, Z; ConvertLabToXYZ(100.0*L,255.0*(a-0.5),255.0*(b-0.5),&X,&Y,&Z); ConvertXYZToRGB(X,Y,Z,red,green,blue); } static inline void ConvertxyYToRGB(const double low_x,const double low_y, const double cap_Y,double *red,double *green,double *blue) { double gamma, X, Y, Z; gamma=PerceptibleReciprocal(low_y); X=gamma*cap_Y*low_x; Y=cap_Y; Z=gamma*cap_Y*(1.0-low_x-low_y); ConvertXYZToRGB(X,Y,Z,red,green,blue); } static void ConvertYPbPrToRGB(const double Y,const double Pb,const double Pr, double *red,double *green,double *blue) { *red=QuantumRange*(0.99999999999914679361*Y-1.2188941887145875e-06*(Pb-0.5)+ 1.4019995886561440468*(Pr-0.5)); *green=QuantumRange*(0.99999975910502514331*Y-0.34413567816504303521*(Pb-0.5)- 0.71413649331646789076*(Pr-0.5)); *blue=QuantumRange*(1.00000124040004623180*Y+1.77200006607230409200*(Pb-0.5)+ 2.1453384174593273e-06*(Pr-0.5)); } static void ConvertYCbCrToRGB(const double Y,const double Cb, const double Cr,double *red,double *green,double *blue) { ConvertYPbPrToRGB(Y,Cb,Cr,red,green,blue); } static void ConvertYIQToRGB(const double Y,const double I,const double Q, double *red,double *green,double *blue) { *red=QuantumRange*(Y+0.9562957197589482261*(I-0.5)+0.6210244164652610754* (Q-0.5)); *green=QuantumRange*(Y-0.2721220993185104464*(I-0.5)-0.6473805968256950427* (Q-0.5)); *blue=QuantumRange*(Y-1.1069890167364901945*(I-0.5)+1.7046149983646481374* (Q-0.5)); } static void ConvertYDbDrToRGB(const double Y,const double Db,const double Dr, double *red,double *green,double *blue) { *red=QuantumRange*(Y+9.2303716147657e-05*(Db-0.5)- 0.52591263066186533*(Dr-0.5)); *green=QuantumRange*(Y-0.12913289889050927*(Db-0.5)+ 0.26789932820759876*(Dr-0.5)); *blue=QuantumRange*(Y+0.66467905997895482*(Db-0.5)- 7.9202543533108e-05*(Dr-0.5)); } static void ConvertYUVToRGB(const double Y,const double U,const double V, double *red,double *green,double *blue) { *red=QuantumRange*(Y-3.945707070708279e-05*(U-0.5)+1.1398279671717170825* (V-0.5)); *green=QuantumRange*(Y-0.3946101641414141437*(U-0.5)-0.5805003156565656797* (V-0.5)); *blue=QuantumRange*(Y+2.0319996843434342537*(U-0.5)-4.813762626262513e-04* (V-0.5)); } static MagickBooleanType TransformsRGBImage(Image *image, ExceptionInfo *exception) { #define TransformsRGBImageTag "Transform/Image" static const float YCCMap[1389] = { 0.000000f, 0.000720f, 0.001441f, 0.002161f, 0.002882f, 0.003602f, 0.004323f, 0.005043f, 0.005764f, 0.006484f, 0.007205f, 0.007925f, 0.008646f, 0.009366f, 0.010086f, 0.010807f, 0.011527f, 0.012248f, 0.012968f, 0.013689f, 0.014409f, 0.015130f, 0.015850f, 0.016571f, 0.017291f, 0.018012f, 0.018732f, 0.019452f, 0.020173f, 0.020893f, 0.021614f, 0.022334f, 0.023055f, 0.023775f, 0.024496f, 0.025216f, 0.025937f, 0.026657f, 0.027378f, 0.028098f, 0.028818f, 0.029539f, 0.030259f, 0.030980f, 0.031700f, 0.032421f, 0.033141f, 0.033862f, 0.034582f, 0.035303f, 0.036023f, 0.036744f, 0.037464f, 0.038184f, 0.038905f, 0.039625f, 0.040346f, 0.041066f, 0.041787f, 0.042507f, 0.043228f, 0.043948f, 0.044669f, 0.045389f, 0.046110f, 0.046830f, 0.047550f, 0.048271f, 0.048991f, 0.049712f, 0.050432f, 0.051153f, 0.051873f, 0.052594f, 0.053314f, 0.054035f, 0.054755f, 0.055476f, 0.056196f, 0.056916f, 0.057637f, 0.058357f, 0.059078f, 0.059798f, 0.060519f, 0.061239f, 0.061960f, 0.062680f, 0.063401f, 0.064121f, 0.064842f, 0.065562f, 0.066282f, 0.067003f, 0.067723f, 0.068444f, 0.069164f, 0.069885f, 0.070605f, 0.071326f, 0.072046f, 0.072767f, 0.073487f, 0.074207f, 0.074928f, 0.075648f, 0.076369f, 0.077089f, 0.077810f, 0.078530f, 0.079251f, 0.079971f, 0.080692f, 0.081412f, 0.082133f, 0.082853f, 0.083573f, 0.084294f, 0.085014f, 0.085735f, 0.086455f, 0.087176f, 0.087896f, 0.088617f, 0.089337f, 0.090058f, 0.090778f, 0.091499f, 0.092219f, 0.092939f, 0.093660f, 0.094380f, 0.095101f, 0.095821f, 0.096542f, 0.097262f, 0.097983f, 0.098703f, 0.099424f, 0.100144f, 0.100865f, 0.101585f, 0.102305f, 0.103026f, 0.103746f, 0.104467f, 0.105187f, 0.105908f, 0.106628f, 0.107349f, 0.108069f, 0.108790f, 0.109510f, 0.110231f, 0.110951f, 0.111671f, 0.112392f, 0.113112f, 0.113833f, 0.114553f, 0.115274f, 0.115994f, 0.116715f, 0.117435f, 0.118156f, 0.118876f, 0.119597f, 0.120317f, 0.121037f, 0.121758f, 0.122478f, 0.123199f, 0.123919f, 0.124640f, 0.125360f, 0.126081f, 0.126801f, 0.127522f, 0.128242f, 0.128963f, 0.129683f, 0.130403f, 0.131124f, 0.131844f, 0.132565f, 0.133285f, 0.134006f, 0.134726f, 0.135447f, 0.136167f, 0.136888f, 0.137608f, 0.138329f, 0.139049f, 0.139769f, 0.140490f, 0.141210f, 0.141931f, 0.142651f, 0.143372f, 0.144092f, 0.144813f, 0.145533f, 0.146254f, 0.146974f, 0.147695f, 0.148415f, 0.149135f, 0.149856f, 0.150576f, 0.151297f, 0.152017f, 0.152738f, 0.153458f, 0.154179f, 0.154899f, 0.155620f, 0.156340f, 0.157061f, 0.157781f, 0.158501f, 0.159222f, 0.159942f, 0.160663f, 0.161383f, 0.162104f, 0.162824f, 0.163545f, 0.164265f, 0.164986f, 0.165706f, 0.166427f, 0.167147f, 0.167867f, 0.168588f, 0.169308f, 0.170029f, 0.170749f, 0.171470f, 0.172190f, 0.172911f, 0.173631f, 0.174352f, 0.175072f, 0.175793f, 0.176513f, 0.177233f, 0.177954f, 0.178674f, 0.179395f, 0.180115f, 0.180836f, 0.181556f, 0.182277f, 0.182997f, 0.183718f, 0.184438f, 0.185159f, 0.185879f, 0.186599f, 0.187320f, 0.188040f, 0.188761f, 0.189481f, 0.190202f, 0.190922f, 0.191643f, 0.192363f, 0.193084f, 0.193804f, 0.194524f, 0.195245f, 0.195965f, 0.196686f, 0.197406f, 0.198127f, 0.198847f, 0.199568f, 0.200288f, 0.201009f, 0.201729f, 0.202450f, 0.203170f, 0.203890f, 0.204611f, 0.205331f, 0.206052f, 0.206772f, 0.207493f, 0.208213f, 0.208934f, 0.209654f, 0.210375f, 0.211095f, 0.211816f, 0.212536f, 0.213256f, 0.213977f, 0.214697f, 0.215418f, 0.216138f, 0.216859f, 0.217579f, 0.218300f, 0.219020f, 0.219741f, 0.220461f, 0.221182f, 0.221902f, 0.222622f, 0.223343f, 0.224063f, 0.224784f, 0.225504f, 0.226225f, 0.226945f, 0.227666f, 0.228386f, 0.229107f, 0.229827f, 0.230548f, 0.231268f, 0.231988f, 0.232709f, 0.233429f, 0.234150f, 0.234870f, 0.235591f, 0.236311f, 0.237032f, 0.237752f, 0.238473f, 0.239193f, 0.239914f, 0.240634f, 0.241354f, 0.242075f, 0.242795f, 0.243516f, 0.244236f, 0.244957f, 0.245677f, 0.246398f, 0.247118f, 0.247839f, 0.248559f, 0.249280f, 0.250000f, 0.250720f, 0.251441f, 0.252161f, 0.252882f, 0.253602f, 0.254323f, 0.255043f, 0.255764f, 0.256484f, 0.257205f, 0.257925f, 0.258646f, 0.259366f, 0.260086f, 0.260807f, 0.261527f, 0.262248f, 0.262968f, 0.263689f, 0.264409f, 0.265130f, 0.265850f, 0.266571f, 0.267291f, 0.268012f, 0.268732f, 0.269452f, 0.270173f, 0.270893f, 0.271614f, 0.272334f, 0.273055f, 0.273775f, 0.274496f, 0.275216f, 0.275937f, 0.276657f, 0.277378f, 0.278098f, 0.278818f, 0.279539f, 0.280259f, 0.280980f, 0.281700f, 0.282421f, 0.283141f, 0.283862f, 0.284582f, 0.285303f, 0.286023f, 0.286744f, 0.287464f, 0.288184f, 0.288905f, 0.289625f, 0.290346f, 0.291066f, 0.291787f, 0.292507f, 0.293228f, 0.293948f, 0.294669f, 0.295389f, 0.296109f, 0.296830f, 0.297550f, 0.298271f, 0.298991f, 0.299712f, 0.300432f, 0.301153f, 0.301873f, 0.302594f, 0.303314f, 0.304035f, 0.304755f, 0.305476f, 0.306196f, 0.306916f, 0.307637f, 0.308357f, 0.309078f, 0.309798f, 0.310519f, 0.311239f, 0.311960f, 0.312680f, 0.313401f, 0.314121f, 0.314842f, 0.315562f, 0.316282f, 0.317003f, 0.317723f, 0.318444f, 0.319164f, 0.319885f, 0.320605f, 0.321326f, 0.322046f, 0.322767f, 0.323487f, 0.324207f, 0.324928f, 0.325648f, 0.326369f, 0.327089f, 0.327810f, 0.328530f, 0.329251f, 0.329971f, 0.330692f, 0.331412f, 0.332133f, 0.332853f, 0.333573f, 0.334294f, 0.335014f, 0.335735f, 0.336455f, 0.337176f, 0.337896f, 0.338617f, 0.339337f, 0.340058f, 0.340778f, 0.341499f, 0.342219f, 0.342939f, 0.343660f, 0.344380f, 0.345101f, 0.345821f, 0.346542f, 0.347262f, 0.347983f, 0.348703f, 0.349424f, 0.350144f, 0.350865f, 0.351585f, 0.352305f, 0.353026f, 0.353746f, 0.354467f, 0.355187f, 0.355908f, 0.356628f, 0.357349f, 0.358069f, 0.358790f, 0.359510f, 0.360231f, 0.360951f, 0.361671f, 0.362392f, 0.363112f, 0.363833f, 0.364553f, 0.365274f, 0.365994f, 0.366715f, 0.367435f, 0.368156f, 0.368876f, 0.369597f, 0.370317f, 0.371037f, 0.371758f, 0.372478f, 0.373199f, 0.373919f, 0.374640f, 0.375360f, 0.376081f, 0.376801f, 0.377522f, 0.378242f, 0.378963f, 0.379683f, 0.380403f, 0.381124f, 0.381844f, 0.382565f, 0.383285f, 0.384006f, 0.384726f, 0.385447f, 0.386167f, 0.386888f, 0.387608f, 0.388329f, 0.389049f, 0.389769f, 0.390490f, 0.391210f, 0.391931f, 0.392651f, 0.393372f, 0.394092f, 0.394813f, 0.395533f, 0.396254f, 0.396974f, 0.397695f, 0.398415f, 0.399135f, 0.399856f, 0.400576f, 0.401297f, 0.402017f, 0.402738f, 0.403458f, 0.404179f, 0.404899f, 0.405620f, 0.406340f, 0.407061f, 0.407781f, 0.408501f, 0.409222f, 0.409942f, 0.410663f, 0.411383f, 0.412104f, 0.412824f, 0.413545f, 0.414265f, 0.414986f, 0.415706f, 0.416427f, 0.417147f, 0.417867f, 0.418588f, 0.419308f, 0.420029f, 0.420749f, 0.421470f, 0.422190f, 0.422911f, 0.423631f, 0.424352f, 0.425072f, 0.425793f, 0.426513f, 0.427233f, 0.427954f, 0.428674f, 0.429395f, 0.430115f, 0.430836f, 0.431556f, 0.432277f, 0.432997f, 0.433718f, 0.434438f, 0.435158f, 0.435879f, 0.436599f, 0.437320f, 0.438040f, 0.438761f, 0.439481f, 0.440202f, 0.440922f, 0.441643f, 0.442363f, 0.443084f, 0.443804f, 0.444524f, 0.445245f, 0.445965f, 0.446686f, 0.447406f, 0.448127f, 0.448847f, 0.449568f, 0.450288f, 0.451009f, 0.451729f, 0.452450f, 0.453170f, 0.453891f, 0.454611f, 0.455331f, 0.456052f, 0.456772f, 0.457493f, 0.458213f, 0.458934f, 0.459654f, 0.460375f, 0.461095f, 0.461816f, 0.462536f, 0.463256f, 0.463977f, 0.464697f, 0.465418f, 0.466138f, 0.466859f, 0.467579f, 0.468300f, 0.469020f, 0.469741f, 0.470461f, 0.471182f, 0.471902f, 0.472622f, 0.473343f, 0.474063f, 0.474784f, 0.475504f, 0.476225f, 0.476945f, 0.477666f, 0.478386f, 0.479107f, 0.479827f, 0.480548f, 0.481268f, 0.481988f, 0.482709f, 0.483429f, 0.484150f, 0.484870f, 0.485591f, 0.486311f, 0.487032f, 0.487752f, 0.488473f, 0.489193f, 0.489914f, 0.490634f, 0.491354f, 0.492075f, 0.492795f, 0.493516f, 0.494236f, 0.494957f, 0.495677f, 0.496398f, 0.497118f, 0.497839f, 0.498559f, 0.499280f, 0.500000f, 0.500720f, 0.501441f, 0.502161f, 0.502882f, 0.503602f, 0.504323f, 0.505043f, 0.505764f, 0.506484f, 0.507205f, 0.507925f, 0.508646f, 0.509366f, 0.510086f, 0.510807f, 0.511527f, 0.512248f, 0.512968f, 0.513689f, 0.514409f, 0.515130f, 0.515850f, 0.516571f, 0.517291f, 0.518012f, 0.518732f, 0.519452f, 0.520173f, 0.520893f, 0.521614f, 0.522334f, 0.523055f, 0.523775f, 0.524496f, 0.525216f, 0.525937f, 0.526657f, 0.527378f, 0.528098f, 0.528818f, 0.529539f, 0.530259f, 0.530980f, 0.531700f, 0.532421f, 0.533141f, 0.533862f, 0.534582f, 0.535303f, 0.536023f, 0.536744f, 0.537464f, 0.538184f, 0.538905f, 0.539625f, 0.540346f, 0.541066f, 0.541787f, 0.542507f, 0.543228f, 0.543948f, 0.544669f, 0.545389f, 0.546109f, 0.546830f, 0.547550f, 0.548271f, 0.548991f, 0.549712f, 0.550432f, 0.551153f, 0.551873f, 0.552594f, 0.553314f, 0.554035f, 0.554755f, 0.555476f, 0.556196f, 0.556916f, 0.557637f, 0.558357f, 0.559078f, 0.559798f, 0.560519f, 0.561239f, 0.561960f, 0.562680f, 0.563401f, 0.564121f, 0.564842f, 0.565562f, 0.566282f, 0.567003f, 0.567723f, 0.568444f, 0.569164f, 0.569885f, 0.570605f, 0.571326f, 0.572046f, 0.572767f, 0.573487f, 0.574207f, 0.574928f, 0.575648f, 0.576369f, 0.577089f, 0.577810f, 0.578530f, 0.579251f, 0.579971f, 0.580692f, 0.581412f, 0.582133f, 0.582853f, 0.583573f, 0.584294f, 0.585014f, 0.585735f, 0.586455f, 0.587176f, 0.587896f, 0.588617f, 0.589337f, 0.590058f, 0.590778f, 0.591499f, 0.592219f, 0.592939f, 0.593660f, 0.594380f, 0.595101f, 0.595821f, 0.596542f, 0.597262f, 0.597983f, 0.598703f, 0.599424f, 0.600144f, 0.600865f, 0.601585f, 0.602305f, 0.603026f, 0.603746f, 0.604467f, 0.605187f, 0.605908f, 0.606628f, 0.607349f, 0.608069f, 0.608790f, 0.609510f, 0.610231f, 0.610951f, 0.611671f, 0.612392f, 0.613112f, 0.613833f, 0.614553f, 0.615274f, 0.615994f, 0.616715f, 0.617435f, 0.618156f, 0.618876f, 0.619597f, 0.620317f, 0.621037f, 0.621758f, 0.622478f, 0.623199f, 0.623919f, 0.624640f, 0.625360f, 0.626081f, 0.626801f, 0.627522f, 0.628242f, 0.628963f, 0.629683f, 0.630403f, 0.631124f, 0.631844f, 0.632565f, 0.633285f, 0.634006f, 0.634726f, 0.635447f, 0.636167f, 0.636888f, 0.637608f, 0.638329f, 0.639049f, 0.639769f, 0.640490f, 0.641210f, 0.641931f, 0.642651f, 0.643372f, 0.644092f, 0.644813f, 0.645533f, 0.646254f, 0.646974f, 0.647695f, 0.648415f, 0.649135f, 0.649856f, 0.650576f, 0.651297f, 0.652017f, 0.652738f, 0.653458f, 0.654179f, 0.654899f, 0.655620f, 0.656340f, 0.657061f, 0.657781f, 0.658501f, 0.659222f, 0.659942f, 0.660663f, 0.661383f, 0.662104f, 0.662824f, 0.663545f, 0.664265f, 0.664986f, 0.665706f, 0.666427f, 0.667147f, 0.667867f, 0.668588f, 0.669308f, 0.670029f, 0.670749f, 0.671470f, 0.672190f, 0.672911f, 0.673631f, 0.674352f, 0.675072f, 0.675793f, 0.676513f, 0.677233f, 0.677954f, 0.678674f, 0.679395f, 0.680115f, 0.680836f, 0.681556f, 0.682277f, 0.682997f, 0.683718f, 0.684438f, 0.685158f, 0.685879f, 0.686599f, 0.687320f, 0.688040f, 0.688761f, 0.689481f, 0.690202f, 0.690922f, 0.691643f, 0.692363f, 0.693084f, 0.693804f, 0.694524f, 0.695245f, 0.695965f, 0.696686f, 0.697406f, 0.698127f, 0.698847f, 0.699568f, 0.700288f, 0.701009f, 0.701729f, 0.702450f, 0.703170f, 0.703891f, 0.704611f, 0.705331f, 0.706052f, 0.706772f, 0.707493f, 0.708213f, 0.708934f, 0.709654f, 0.710375f, 0.711095f, 0.711816f, 0.712536f, 0.713256f, 0.713977f, 0.714697f, 0.715418f, 0.716138f, 0.716859f, 0.717579f, 0.718300f, 0.719020f, 0.719741f, 0.720461f, 0.721182f, 0.721902f, 0.722622f, 0.723343f, 0.724063f, 0.724784f, 0.725504f, 0.726225f, 0.726945f, 0.727666f, 0.728386f, 0.729107f, 0.729827f, 0.730548f, 0.731268f, 0.731988f, 0.732709f, 0.733429f, 0.734150f, 0.734870f, 0.735591f, 0.736311f, 0.737032f, 0.737752f, 0.738473f, 0.739193f, 0.739914f, 0.740634f, 0.741354f, 0.742075f, 0.742795f, 0.743516f, 0.744236f, 0.744957f, 0.745677f, 0.746398f, 0.747118f, 0.747839f, 0.748559f, 0.749280f, 0.750000f, 0.750720f, 0.751441f, 0.752161f, 0.752882f, 0.753602f, 0.754323f, 0.755043f, 0.755764f, 0.756484f, 0.757205f, 0.757925f, 0.758646f, 0.759366f, 0.760086f, 0.760807f, 0.761527f, 0.762248f, 0.762968f, 0.763689f, 0.764409f, 0.765130f, 0.765850f, 0.766571f, 0.767291f, 0.768012f, 0.768732f, 0.769452f, 0.770173f, 0.770893f, 0.771614f, 0.772334f, 0.773055f, 0.773775f, 0.774496f, 0.775216f, 0.775937f, 0.776657f, 0.777378f, 0.778098f, 0.778818f, 0.779539f, 0.780259f, 0.780980f, 0.781700f, 0.782421f, 0.783141f, 0.783862f, 0.784582f, 0.785303f, 0.786023f, 0.786744f, 0.787464f, 0.788184f, 0.788905f, 0.789625f, 0.790346f, 0.791066f, 0.791787f, 0.792507f, 0.793228f, 0.793948f, 0.794669f, 0.795389f, 0.796109f, 0.796830f, 0.797550f, 0.798271f, 0.798991f, 0.799712f, 0.800432f, 0.801153f, 0.801873f, 0.802594f, 0.803314f, 0.804035f, 0.804755f, 0.805476f, 0.806196f, 0.806916f, 0.807637f, 0.808357f, 0.809078f, 0.809798f, 0.810519f, 0.811239f, 0.811960f, 0.812680f, 0.813401f, 0.814121f, 0.814842f, 0.815562f, 0.816282f, 0.817003f, 0.817723f, 0.818444f, 0.819164f, 0.819885f, 0.820605f, 0.821326f, 0.822046f, 0.822767f, 0.823487f, 0.824207f, 0.824928f, 0.825648f, 0.826369f, 0.827089f, 0.827810f, 0.828530f, 0.829251f, 0.829971f, 0.830692f, 0.831412f, 0.832133f, 0.832853f, 0.833573f, 0.834294f, 0.835014f, 0.835735f, 0.836455f, 0.837176f, 0.837896f, 0.838617f, 0.839337f, 0.840058f, 0.840778f, 0.841499f, 0.842219f, 0.842939f, 0.843660f, 0.844380f, 0.845101f, 0.845821f, 0.846542f, 0.847262f, 0.847983f, 0.848703f, 0.849424f, 0.850144f, 0.850865f, 0.851585f, 0.852305f, 0.853026f, 0.853746f, 0.854467f, 0.855187f, 0.855908f, 0.856628f, 0.857349f, 0.858069f, 0.858790f, 0.859510f, 0.860231f, 0.860951f, 0.861671f, 0.862392f, 0.863112f, 0.863833f, 0.864553f, 0.865274f, 0.865994f, 0.866715f, 0.867435f, 0.868156f, 0.868876f, 0.869597f, 0.870317f, 0.871037f, 0.871758f, 0.872478f, 0.873199f, 0.873919f, 0.874640f, 0.875360f, 0.876081f, 0.876801f, 0.877522f, 0.878242f, 0.878963f, 0.879683f, 0.880403f, 0.881124f, 0.881844f, 0.882565f, 0.883285f, 0.884006f, 0.884726f, 0.885447f, 0.886167f, 0.886888f, 0.887608f, 0.888329f, 0.889049f, 0.889769f, 0.890490f, 0.891210f, 0.891931f, 0.892651f, 0.893372f, 0.894092f, 0.894813f, 0.895533f, 0.896254f, 0.896974f, 0.897695f, 0.898415f, 0.899135f, 0.899856f, 0.900576f, 0.901297f, 0.902017f, 0.902738f, 0.903458f, 0.904179f, 0.904899f, 0.905620f, 0.906340f, 0.907061f, 0.907781f, 0.908501f, 0.909222f, 0.909942f, 0.910663f, 0.911383f, 0.912104f, 0.912824f, 0.913545f, 0.914265f, 0.914986f, 0.915706f, 0.916427f, 0.917147f, 0.917867f, 0.918588f, 0.919308f, 0.920029f, 0.920749f, 0.921470f, 0.922190f, 0.922911f, 0.923631f, 0.924352f, 0.925072f, 0.925793f, 0.926513f, 0.927233f, 0.927954f, 0.928674f, 0.929395f, 0.930115f, 0.930836f, 0.931556f, 0.932277f, 0.932997f, 0.933718f, 0.934438f, 0.935158f, 0.935879f, 0.936599f, 0.937320f, 0.938040f, 0.938761f, 0.939481f, 0.940202f, 0.940922f, 0.941643f, 0.942363f, 0.943084f, 0.943804f, 0.944524f, 0.945245f, 0.945965f, 0.946686f, 0.947406f, 0.948127f, 0.948847f, 0.949568f, 0.950288f, 0.951009f, 0.951729f, 0.952450f, 0.953170f, 0.953891f, 0.954611f, 0.955331f, 0.956052f, 0.956772f, 0.957493f, 0.958213f, 0.958934f, 0.959654f, 0.960375f, 0.961095f, 0.961816f, 0.962536f, 0.963256f, 0.963977f, 0.964697f, 0.965418f, 0.966138f, 0.966859f, 0.967579f, 0.968300f, 0.969020f, 0.969741f, 0.970461f, 0.971182f, 0.971902f, 0.972622f, 0.973343f, 0.974063f, 0.974784f, 0.975504f, 0.976225f, 0.976945f, 0.977666f, 0.978386f, 0.979107f, 0.979827f, 0.980548f, 0.981268f, 0.981988f, 0.982709f, 0.983429f, 0.984150f, 0.984870f, 0.985591f, 0.986311f, 0.987032f, 0.987752f, 0.988473f, 0.989193f, 0.989914f, 0.990634f, 0.991354f, 0.992075f, 0.992795f, 0.993516f, 0.994236f, 0.994957f, 0.995677f, 0.996398f, 0.997118f, 0.997839f, 0.998559f, 0.999280f, 1.000000f }; CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; register ssize_t i; ssize_t y; TransformPacket *y_map, *x_map, *z_map; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=MagickTrue; progress=0; switch (image->colorspace) { case CMYKColorspace: { PixelInfo zero; /* Transform image from CMYK to sRGB. */ if (image->storage_class == PseudoClass) { if (SyncImage(image,exception) == MagickFalse) return(MagickFalse); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); } GetPixelInfo(image,&zero); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; PixelInfo pixel; register ssize_t x; register Quantum *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } pixel=zero; for (x=0; x < (ssize_t) image->columns; x++) { GetPixelInfoPixel(image,q,&pixel); ConvertCMYKToRGB(&pixel); SetPixelViaPixelInfo(image,&pixel,q); q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); if (SetImageColorspace(image,sRGBColorspace,exception) == MagickFalse) return(MagickFalse); return(status); } case GRAYColorspace: { /* Transform linear GRAY to sRGB colorspace. */ if (image->storage_class == PseudoClass) { if (SyncImage(image,exception) == MagickFalse) return(MagickFalse); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); } if (SetImageColorspace(image,sRGBColorspace,exception) == MagickFalse) return(MagickFalse); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; register ssize_t x; register Quantum *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=(ssize_t) image->columns; x != 0; x--) { MagickRealType gray; gray=(MagickRealType) GetPixelGray(image,q); if ((image->intensity == Rec601LuminancePixelIntensityMethod) || (image->intensity == Rec709LuminancePixelIntensityMethod)) gray=EncodePixelGamma(gray); SetPixelRed(image,ClampToQuantum(gray),q); SetPixelGreen(image,ClampToQuantum(gray),q); SetPixelBlue(image,ClampToQuantum(gray),q); q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); if (SetImageColorspace(image,sRGBColorspace,exception) == MagickFalse) return(MagickFalse); return(status); } case CMYColorspace: case HCLColorspace: case HCLpColorspace: case HSBColorspace: case HSIColorspace: case HSLColorspace: case HSVColorspace: case HWBColorspace: case LabColorspace: case LCHColorspace: case LCHabColorspace: case LCHuvColorspace: case LMSColorspace: case LuvColorspace: case xyYColorspace: case XYZColorspace: case YCbCrColorspace: case YDbDrColorspace: case YIQColorspace: case YPbPrColorspace: case YUVColorspace: { /* Transform image from source colorspace to sRGB. */ if (image->storage_class == PseudoClass) { if (SyncImage(image,exception) == MagickFalse) return(MagickFalse); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); } image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; register ssize_t x; register Quantum *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double blue, green, red, X, Y, Z; X=QuantumScale*GetPixelRed(image,q); Y=QuantumScale*GetPixelGreen(image,q); Z=QuantumScale*GetPixelBlue(image,q); switch (image->colorspace) { case CMYColorspace: { ConvertCMYToRGB(X,Y,Z,&red,&green,&blue); break; } case HCLColorspace: { ConvertHCLToRGB(X,Y,Z,&red,&green,&blue); break; } case HCLpColorspace: { ConvertHCLpToRGB(X,Y,Z,&red,&green,&blue); break; } case HSBColorspace: { ConvertHSBToRGB(X,Y,Z,&red,&green,&blue); break; } case HSIColorspace: { ConvertHSIToRGB(X,Y,Z,&red,&green,&blue); break; } case HSLColorspace: { ConvertHSLToRGB(X,Y,Z,&red,&green,&blue); break; } case HSVColorspace: { ConvertHSVToRGB(X,Y,Z,&red,&green,&blue); break; } case HWBColorspace: { ConvertHWBToRGB(X,Y,Z,&red,&green,&blue); break; } case LabColorspace: { ConvertLabToRGB(X,Y,Z,&red,&green,&blue); break; } case LCHColorspace: case LCHabColorspace: { ConvertLCHabToRGB(X,Y,Z,&red,&green,&blue); break; } case LCHuvColorspace: { ConvertLCHuvToRGB(X,Y,Z,&red,&green,&blue); break; } case LMSColorspace: { ConvertLMSToRGB(X,Y,Z,&red,&green,&blue); break; } case LuvColorspace: { ConvertLuvToRGB(X,Y,Z,&red,&green,&blue); break; } case xyYColorspace: { ConvertxyYToRGB(X,Y,Z,&red,&green,&blue); break; } case XYZColorspace: { ConvertXYZToRGB(X,Y,Z,&red,&green,&blue); break; } case YCbCrColorspace: { ConvertYCbCrToRGB(X,Y,Z,&red,&green,&blue); break; } case YDbDrColorspace: { ConvertYDbDrToRGB(X,Y,Z,&red,&green,&blue); break; } case YIQColorspace: { ConvertYIQToRGB(X,Y,Z,&red,&green,&blue); break; } case YPbPrColorspace: { ConvertYPbPrToRGB(X,Y,Z,&red,&green,&blue); break; } case YUVColorspace: { ConvertYUVToRGB(X,Y,Z,&red,&green,&blue); break; } default: { red=QuantumRange*X; green=QuantumRange*Y; blue=QuantumRange*Z; break; } } SetPixelRed(image,ClampToQuantum(red),q); SetPixelGreen(image,ClampToQuantum(green),q); SetPixelBlue(image,ClampToQuantum(blue),q); q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); if (SetImageColorspace(image,sRGBColorspace,exception) == MagickFalse) return(MagickFalse); return(status); } case LogColorspace: { const char *value; double black, density, film_gamma, gamma, reference_black, reference_white; Quantum *logmap; /* Transform Log to sRGB colorspace. */ density=DisplayGamma; gamma=DisplayGamma; value=GetImageProperty(image,"gamma",exception); if (value != (const char *) NULL) gamma=PerceptibleReciprocal(StringToDouble(value,(char **) NULL)); film_gamma=FilmGamma; value=GetImageProperty(image,"film-gamma",exception); if (value != (const char *) NULL) film_gamma=StringToDouble(value,(char **) NULL); reference_black=ReferenceBlack; value=GetImageProperty(image,"reference-black",exception); if (value != (const char *) NULL) reference_black=StringToDouble(value,(char **) NULL); reference_white=ReferenceWhite; value=GetImageProperty(image,"reference-white",exception); if (value != (const char *) NULL) reference_white=StringToDouble(value,(char **) NULL); logmap=(Quantum *) AcquireQuantumMemory((size_t) MaxMap+1UL, sizeof(*logmap)); if (logmap == (Quantum *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); black=pow(10.0,(reference_black-reference_white)*(gamma/density)*0.002/ film_gamma); for (i=0; i <= (ssize_t) (reference_black*MaxMap/1024.0); i++) logmap[i]=(Quantum) 0; for ( ; i < (ssize_t) (reference_white*MaxMap/1024.0); i++) logmap[i]=ClampToQuantum(QuantumRange/(1.0-black)* (pow(10.0,(1024.0*i/MaxMap-reference_white)*(gamma/density)*0.002/ film_gamma)-black)); for ( ; i <= (ssize_t) MaxMap; i++) logmap[i]=QuantumRange; if (image->storage_class == PseudoClass) { if (SyncImage(image,exception) == MagickFalse) return(MagickFalse); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); } image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; register ssize_t x; register Quantum *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=(ssize_t) image->columns; x != 0; x--) { double blue, green, red; red=(double) logmap[ScaleQuantumToMap(GetPixelRed(image,q))]; green=(double) logmap[ScaleQuantumToMap(GetPixelGreen(image,q))]; blue=(double) logmap[ScaleQuantumToMap(GetPixelBlue(image,q))]; SetPixelRed(image,ClampToQuantum(EncodePixelGamma((MagickRealType) red)),q); SetPixelGreen(image,ClampToQuantum(EncodePixelGamma((MagickRealType) green)),q); SetPixelBlue(image,ClampToQuantum(EncodePixelGamma((MagickRealType) blue)),q); q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); logmap=(Quantum *) RelinquishMagickMemory(logmap); if (SetImageColorspace(image,sRGBColorspace,exception) == MagickFalse) return(MagickFalse); return(status); } case RGBColorspace: case scRGBColorspace: { /* Transform linear RGB to sRGB colorspace. */ if (image->storage_class == PseudoClass) { if (SyncImage(image,exception) == MagickFalse) return(MagickFalse); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); } image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; register ssize_t x; register Quantum *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=(ssize_t) image->columns; x != 0; x--) { double blue, green, red; red=EncodePixelGamma((MagickRealType) GetPixelRed(image,q)); green=EncodePixelGamma((MagickRealType) GetPixelGreen(image,q)); blue=EncodePixelGamma((MagickRealType) GetPixelBlue(image,q)); SetPixelRed(image,ClampToQuantum(red),q); SetPixelGreen(image,ClampToQuantum(green),q); SetPixelBlue(image,ClampToQuantum(blue),q); q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); if (SetImageColorspace(image,sRGBColorspace,exception) == MagickFalse) return(MagickFalse); return(status); } default: break; } /* Allocate the tables. */ x_map=(TransformPacket *) AcquireQuantumMemory((size_t) MaxMap+1UL, sizeof(*x_map)); y_map=(TransformPacket *) AcquireQuantumMemory((size_t) MaxMap+1UL, sizeof(*y_map)); z_map=(TransformPacket *) AcquireQuantumMemory((size_t) MaxMap+1UL, sizeof(*z_map)); if ((x_map == (TransformPacket *) NULL) || (y_map == (TransformPacket *) NULL) || (z_map == (TransformPacket *) NULL)) { if (z_map != (TransformPacket *) NULL) z_map=(TransformPacket *) RelinquishMagickMemory(z_map); if (y_map != (TransformPacket *) NULL) y_map=(TransformPacket *) RelinquishMagickMemory(y_map); if (x_map != (TransformPacket *) NULL) x_map=(TransformPacket *) RelinquishMagickMemory(x_map); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } switch (image->colorspace) { case OHTAColorspace: { /* Initialize OHTA tables: I1 = 0.33333*R+0.33334*G+0.33333*B I2 = 0.50000*R+0.00000*G-0.50000*B I3 =-0.25000*R+0.50000*G-0.25000*B R = I1+1.00000*I2-0.66668*I3 G = I1+0.00000*I2+1.33333*I3 B = I1-1.00000*I2-0.66668*I3 I and Q, normally -0.5 through 0.5, must be normalized to the range 0 through QuantumRange. */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) \ magick_threads(image,image,1,1) #endif for (i=0; i <= (ssize_t) MaxMap; i++) { x_map[i].x=(MagickRealType) (1.0*(double) i); y_map[i].x=(MagickRealType) (0.5*1.00000*(2.0*(double) i-MaxMap)); z_map[i].x=(MagickRealType) (-0.5*0.66668*(2.0*(double) i-MaxMap)); x_map[i].y=(MagickRealType) (1.0*(double) i); y_map[i].y=(MagickRealType) (0.5*0.00000*(2.0*(double) i-MaxMap)); z_map[i].y=(MagickRealType) (0.5*1.33333*(2.0*(double) i-MaxMap)); x_map[i].z=(MagickRealType) (1.0*(double) i); y_map[i].z=(MagickRealType) (-0.5*1.00000*(2.0*(double) i-MaxMap)); z_map[i].z=(MagickRealType) (-0.5*0.66668*(2.0*(double) i-MaxMap)); } break; } case Rec601YCbCrColorspace: { /* Initialize YCbCr tables: R = Y +1.402000*Cr G = Y-0.344136*Cb-0.714136*Cr B = Y+1.772000*Cb Cb and Cr, normally -0.5 through 0.5, must be normalized to the range 0 through QuantumRange. */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) \ magick_threads(image,image,1,1) #endif for (i=0; i <= (ssize_t) MaxMap; i++) { x_map[i].x=0.99999999999914679361*(double) i; y_map[i].x=0.5*(-1.2188941887145875e-06)*(2.00*(double) i-MaxMap); z_map[i].x=0.5*1.4019995886561440468*(2.00*(double) i-MaxMap); x_map[i].y=0.99999975910502514331*(double) i; y_map[i].y=0.5*(-0.34413567816504303521)*(2.00*(double) i-MaxMap); z_map[i].y=0.5*(-0.71413649331646789076)*(2.00*(double) i-MaxMap); x_map[i].z=1.00000124040004623180*(double) i; y_map[i].z=0.5*1.77200006607230409200*(2.00*(double) i-MaxMap); z_map[i].z=0.5*2.1453384174593273e-06*(2.00*(double) i-MaxMap); } break; } case Rec709YCbCrColorspace: { /* Initialize YCbCr tables: R = Y +1.574800*Cr G = Y-0.187324*Cb-0.468124*Cr B = Y+1.855600*Cb Cb and Cr, normally -0.5 through 0.5, must be normalized to the range 0 through QuantumRange. */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) \ magick_threads(image,image,1,1) #endif for (i=0; i <= (ssize_t) MaxMap; i++) { x_map[i].x=(MagickRealType) (1.0*i); y_map[i].x=(MagickRealType) (0.5*0.000000*(2.0*i-MaxMap)); z_map[i].x=(MagickRealType) (0.5*1.574800*(2.0*i-MaxMap)); x_map[i].y=(MagickRealType) (1.0*i); y_map[i].y=(MagickRealType) (0.5*(-0.187324)*(2.0*i-MaxMap)); z_map[i].y=(MagickRealType) (0.5*(-0.468124)*(2.0*i-MaxMap)); x_map[i].z=(MagickRealType) (1.0*i); y_map[i].z=(MagickRealType) (0.5*1.855600*(2.0*i-MaxMap)); z_map[i].z=(MagickRealType) (0.5*0.000000*(2.0*i-MaxMap)); } break; } case YCCColorspace: { /* Initialize YCC tables: R = Y +1.340762*C2 G = Y-0.317038*C1-0.682243*C2 B = Y+1.632639*C1 YCC is scaled by 1.3584. C1 zero is 156 and C2 is at 137. */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) \ magick_threads(image,image,1,1) #endif for (i=0; i <= (ssize_t) MaxMap; i++) { x_map[i].x=(MagickRealType) (1.3584000*(double) i); y_map[i].x=(MagickRealType) 0.0000000; z_map[i].x=(MagickRealType) (1.8215000*(1.0*(double) i-(double) ScaleQuantumToMap(ScaleCharToQuantum(137)))); x_map[i].y=(MagickRealType) (1.3584000*(double) i); y_map[i].y=(MagickRealType) (-0.4302726*(1.0*(double) i-(double) ScaleQuantumToMap(ScaleCharToQuantum(156)))); z_map[i].y=(MagickRealType) (-0.9271435*(1.0*(double) i-(double) ScaleQuantumToMap(ScaleCharToQuantum(137)))); x_map[i].z=(MagickRealType) (1.3584000*(double) i); y_map[i].z=(MagickRealType) (2.2179000*(1.0*(double) i-(double) ScaleQuantumToMap(ScaleCharToQuantum(156)))); z_map[i].z=(MagickRealType) 0.0000000; } break; } default: { /* Linear conversion tables. */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) \ magick_threads(image,image,1,1) #endif for (i=0; i <= (ssize_t) MaxMap; i++) { x_map[i].x=(MagickRealType) (1.0*(double) i); y_map[i].x=(MagickRealType) 0.0; z_map[i].x=(MagickRealType) 0.0; x_map[i].y=(MagickRealType) 0.0; y_map[i].y=(MagickRealType) (1.0*(double) i); z_map[i].y=(MagickRealType) 0.0; x_map[i].z=(MagickRealType) 0.0; y_map[i].z=(MagickRealType) 0.0; z_map[i].z=(MagickRealType) (1.0*(double) i); } break; } } /* Convert to sRGB. */ switch (image->storage_class) { case DirectClass: default: { /* Convert DirectClass image. */ image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; PixelInfo pixel; register ssize_t x; register Quantum *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register size_t blue, green, red; red=ScaleQuantumToMap(GetPixelRed(image,q)); green=ScaleQuantumToMap(GetPixelGreen(image,q)); blue=ScaleQuantumToMap(GetPixelBlue(image,q)); pixel.red=x_map[red].x+y_map[green].x+z_map[blue].x; pixel.green=x_map[red].y+y_map[green].y+z_map[blue].y; pixel.blue=x_map[red].z+y_map[green].z+z_map[blue].z; if (image->colorspace == YCCColorspace) { pixel.red=QuantumRange*YCCMap[RoundToYCC(1024.0*pixel.red/ (double) MaxMap)]; pixel.green=QuantumRange*YCCMap[RoundToYCC(1024.0*pixel.green/ (double) MaxMap)]; pixel.blue=QuantumRange*YCCMap[RoundToYCC(1024.0*pixel.blue/ (double) MaxMap)]; } else { pixel.red=(MagickRealType) ScaleMapToQuantum(pixel.red); pixel.green=(MagickRealType) ScaleMapToQuantum(pixel.green); pixel.blue=(MagickRealType) ScaleMapToQuantum(pixel.blue); } SetPixelRed(image,ClampToQuantum(pixel.red),q); SetPixelGreen(image,ClampToQuantum(pixel.green),q); SetPixelBlue(image,ClampToQuantum(pixel.blue),q); q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_TransformsRGBImage) #endif proceed=SetImageProgress(image,TransformsRGBImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); break; } case PseudoClass: { /* Convert PseudoClass image. */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,1,1) #endif for (i=0; i < (ssize_t) image->colors; i++) { PixelInfo pixel; register size_t blue, green, red; red=ScaleQuantumToMap(ClampToQuantum(image->colormap[i].red)); green=ScaleQuantumToMap(ClampToQuantum(image->colormap[i].green)); blue=ScaleQuantumToMap(ClampToQuantum(image->colormap[i].blue)); pixel.red=x_map[red].x+y_map[green].x+z_map[blue].x; pixel.green=x_map[red].y+y_map[green].y+z_map[blue].y; pixel.blue=x_map[red].z+y_map[green].z+z_map[blue].z; if (image->colorspace == YCCColorspace) { pixel.red=QuantumRange*YCCMap[RoundToYCC(1024.0*pixel.red/ (double) MaxMap)]; pixel.green=QuantumRange*YCCMap[RoundToYCC(1024.0*pixel.green/ (double) MaxMap)]; pixel.blue=QuantumRange*YCCMap[RoundToYCC(1024.0*pixel.blue/ (double) MaxMap)]; } else { pixel.red=(MagickRealType) ScaleMapToQuantum(pixel.red); pixel.green=(MagickRealType) ScaleMapToQuantum(pixel.green); pixel.blue=(MagickRealType) ScaleMapToQuantum(pixel.blue); } image->colormap[i].red=(double) ClampToQuantum(pixel.red); image->colormap[i].green=(double) ClampToQuantum(pixel.green); image->colormap[i].blue=(double) ClampToQuantum(pixel.blue); } (void) SyncImage(image,exception); break; } } /* Relinquish resources. */ z_map=(TransformPacket *) RelinquishMagickMemory(z_map); y_map=(TransformPacket *) RelinquishMagickMemory(y_map); x_map=(TransformPacket *) RelinquishMagickMemory(x_map); if (SetImageColorspace(image,sRGBColorspace,exception) == MagickFalse) return(MagickFalse); return(MagickTrue); }
null
null
null
null
72,823
29,830
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
29,830
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
#include "lsmtest.h" int do_work(int nArg, char **azArg){ struct Option { const char *zName; } aOpt [] = { { "-nmerge" }, { "-nkb" }, { 0 } }; lsm_db *pDb; int rc; int i; const char *zDb; int nMerge = 1; int nKB = (1<<30); if( nArg==0 ) goto usage; zDb = azArg[nArg-1]; for(i=0; i<(nArg-1); i++){ int iSel; rc = testArgSelect(aOpt, "option", azArg[i], &iSel); if( rc ) return rc; switch( iSel ){ case 0: i++; if( i==(nArg-1) ) goto usage; nMerge = atoi(azArg[i]); break; case 1: i++; if( i==(nArg-1) ) goto usage; nKB = atoi(azArg[i]); break; } } rc = lsm_new(0, &pDb); if( rc!=LSM_OK ){ testPrintError("lsm_open(): rc=%d\n", rc); }else{ rc = lsm_open(pDb, zDb); if( rc!=LSM_OK ){ testPrintError("lsm_open(): rc=%d\n", rc); }else{ int n = -1; lsm_config(pDb, LSM_CONFIG_BLOCK_SIZE, &n); n = n*2; lsm_config(pDb, LSM_CONFIG_AUTOCHECKPOINT, &n); rc = lsm_work(pDb, nMerge, nKB, 0); if( rc!=LSM_OK ){ testPrintError("lsm_work(): rc=%d\n", rc); } } } if( rc==LSM_OK ){ rc = lsm_checkpoint(pDb, 0); } lsm_close(pDb); return rc; usage: testPrintUsage("?-optimize? ?-n N? DATABASE"); return -1; } /* ** lsmtest show ?-config LSM-CONFIG? DATABASE ?COMMAND ?PGNO?? */ int do_show(int nArg, char **azArg){ lsm_db *pDb; int rc; const char *zDb; int eOpt = LSM_INFO_DB_STRUCTURE; unsigned int iPg = 0; int bConfig = 0; const char *zConfig = ""; struct Option { const char *zName; int bConfig; int eOpt; } aOpt [] = { { "array", 0, LSM_INFO_ARRAY_STRUCTURE }, { "array-pages", 0, LSM_INFO_ARRAY_PAGES }, { "blocksize", 1, LSM_CONFIG_BLOCK_SIZE }, { "pagesize", 1, LSM_CONFIG_PAGE_SIZE }, { "freelist", 0, LSM_INFO_FREELIST }, { "page-ascii", 0, LSM_INFO_PAGE_ASCII_DUMP }, { "page-hex", 0, LSM_INFO_PAGE_HEX_DUMP }, { 0, 0 } }; char *z = 0; int iDb = 0; /* Index of DATABASE in azArg[] */ /* Check if there is a "-config" option: */ if( nArg>2 && strlen(azArg[0])>1 && memcmp(azArg[0], "-config", strlen(azArg[0]))==0 ){ zConfig = azArg[1]; iDb = 2; } if( nArg<(iDb+1) ) goto usage; if( nArg>(iDb+1) ){ rc = testArgSelect(aOpt, "option", azArg[iDb+1], &eOpt); if( rc!=0 ) return rc; bConfig = aOpt[eOpt].bConfig; eOpt = aOpt[eOpt].eOpt; if( (bConfig==0 && eOpt==LSM_INFO_FREELIST) || (bConfig==1 && eOpt==LSM_CONFIG_BLOCK_SIZE) || (bConfig==1 && eOpt==LSM_CONFIG_PAGE_SIZE) ){ if( nArg!=(iDb+2) ) goto usage; }else{ if( nArg!=(iDb+3) ) goto usage; iPg = atoi(azArg[iDb+2]); } } zDb = azArg[iDb]; rc = lsm_new(0, &pDb); tdb_lsm_configure(pDb, zConfig); if( rc!=LSM_OK ){ testPrintError("lsm_new(): rc=%d\n", rc); }else{ rc = lsm_open(pDb, zDb); if( rc!=LSM_OK ){ testPrintError("lsm_open(): rc=%d\n", rc); } } if( rc==LSM_OK ){ if( bConfig==0 ){ switch( eOpt ){ case LSM_INFO_DB_STRUCTURE: case LSM_INFO_FREELIST: rc = lsm_info(pDb, eOpt, &z); break; case LSM_INFO_ARRAY_STRUCTURE: case LSM_INFO_ARRAY_PAGES: case LSM_INFO_PAGE_ASCII_DUMP: case LSM_INFO_PAGE_HEX_DUMP: rc = lsm_info(pDb, eOpt, iPg, &z); break; default: assert( !"no chance" ); } if( rc==LSM_OK ){ printf("%s\n", z ? z : ""); fflush(stdout); } lsm_free(lsm_get_env(pDb), z); }else{ int iRes = -1; lsm_config(pDb, eOpt, &iRes); printf("%d\n", iRes); fflush(stdout); } } lsm_close(pDb); return rc; usage: testPrintUsage("DATABASE ?array|page-ascii|page-hex PGNO?"); return -1; }
null
null
null
null
26,693
7,309
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
172,304
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * Intel Merrifield FLIS platform device initialization file * * Copyright (C) 2016, Intel Corporation * * Author: Andy Shevchenko <andriy.shevchenko@linux.intel.com> * * 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; version 2 * of the License. */ #include <linux/init.h> #include <linux/ioport.h> #include <linux/platform_device.h> #include <asm/intel-mid.h> #define FLIS_BASE_ADDR 0xff0c0000 #define FLIS_LENGTH 0x8000 static struct resource mrfld_pinctrl_mmio_resource = { .start = FLIS_BASE_ADDR, .end = FLIS_BASE_ADDR + FLIS_LENGTH - 1, .flags = IORESOURCE_MEM, }; static struct platform_device mrfld_pinctrl_device = { .name = "pinctrl-merrifield", .id = PLATFORM_DEVID_NONE, .resource = &mrfld_pinctrl_mmio_resource, .num_resources = 1, }; static int __init mrfld_pinctrl_init(void) { if (intel_mid_identify_cpu() == INTEL_MID_CPU_CHIP_TANGIER) return platform_device_register(&mrfld_pinctrl_device); return -ENODEV; } arch_initcall(mrfld_pinctrl_init);
null
null
null
null
80,651
41,002
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
205,997
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * 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. */ #ifndef _MV64XXX_I2C_H_ #define _MV64XXX_I2C_H_ #include <linux/types.h> #define MV64XXX_I2C_CTLR_NAME "mv64xxx_i2c" /* i2c Platform Device, Driver Data */ struct mv64xxx_i2c_pdata { u32 freq_m; u32 freq_n; u32 timeout; /* In milliseconds */ }; #endif /*_MV64XXX_I2C_H_*/
null
null
null
null
114,344
24,003
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
24,003
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CONTENT_BROWSER_MEDIA_URL_PROVISION_FETCHER_H_ #define CONTENT_BROWSER_MEDIA_URL_PROVISION_FETCHER_H_ #include "base/macros.h" #include "media/base/provision_fetcher.h" #include "net/url_request/url_fetcher.h" #include "net/url_request/url_fetcher_delegate.h" namespace content { // The ProvisionFetcher that retrieves the data by HTTP POST request. class URLProvisionFetcher : public media::ProvisionFetcher, public net::URLFetcherDelegate { public: explicit URLProvisionFetcher(net::URLRequestContextGetter* context_getter); ~URLProvisionFetcher() override; // media::ProvisionFetcher implementation. void Retrieve(const std::string& default_url, const std::string& request_data, const ProvisionFetcher::ResponseCB& response_cb) override; private: // net::URLFetcherDelegate implementation. void OnURLFetchComplete(const net::URLFetcher* source) override; net::URLRequestContextGetter* context_getter_; std::unique_ptr<net::URLFetcher> request_; media::ProvisionFetcher::ResponseCB response_cb_; DISALLOW_COPY_AND_ASSIGN(URLProvisionFetcher); }; } // namespace content #endif // CONTENT_BROWSER_MEDIA_URL_PROVISION_FETCHER_H_
null
null
null
null
20,866
10,397
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
175,392
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
#ifndef _ARM_FCNTL_H #define _ARM_FCNTL_H #define O_DIRECTORY 040000 /* must be a directory */ #define O_NOFOLLOW 0100000 /* don't follow links */ #define O_DIRECT 0200000 /* direct disk access hint - currently ignored */ #define O_LARGEFILE 0400000 #include <asm-generic/fcntl.h> #endif
null
null
null
null
83,739
66,231
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
66,231
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright 2017 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_MEDIA_ROUTER_MOJO_MEDIA_ROUTER_DESKTOP_H_ #define CHROME_BROWSER_MEDIA_ROUTER_MOJO_MEDIA_ROUTER_DESKTOP_H_ #include "base/gtest_prod_util.h" #include "build/build_config.h" #include "chrome/browser/media/router/mojo/media_router_mojo_impl.h" #include "chrome/browser/media/router/mojo/media_sink_service_status.h" #include "chrome/browser/media/router/providers/cast/dual_media_sink_service.h" #include "chrome/browser/media/router/providers/dial/dial_media_route_provider.h" #include "chrome/browser/media/router/providers/extension/extension_media_route_provider_proxy.h" namespace content { class RenderFrameHost; } namespace extensions { class Extension; } namespace media_router { class CastMediaRouteProvider; class DualMediaSinkService; class WiredDisplayMediaRouteProvider; // MediaRouter implementation that uses the MediaRouteProvider implemented in // the component extension. class MediaRouterDesktop : public MediaRouterMojoImpl { public: ~MediaRouterDesktop() override; // Sets up the MediaRouter instance owned by |context| to handle // MediaRouterObserver requests from the component extension given by // |extension|. Creates the MediaRouterMojoImpl instance if it does not // exist. // Called by the Mojo module registry. // |extension|: The component extension, used for querying // suspension state. // |context|: The BrowserContext which owns the extension process. // |request|: The Mojo connection request used for binding. static void BindToRequest(const extensions::Extension* extension, content::BrowserContext* context, mojom::MediaRouterRequest request, content::RenderFrameHost* source); // MediaRouter implementation. void OnUserGesture() override; base::Value GetState() const override; protected: // MediaRouterMojoImpl override: base::Optional<MediaRouteProviderId> GetProviderIdForPresentation( const std::string& presentation_id) override; private: template <bool> friend class MediaRouterDesktopTestBase; friend class MediaRouterFactory; FRIEND_TEST_ALL_PREFIXES(MediaRouterDesktopTest, ProvideSinks); // This constructor performs a firewall check on Windows and is not suitable // for use in unit tests; instead use the constructor below. explicit MediaRouterDesktop(content::BrowserContext* context); // Used by tests only. This constructor skips the firewall check so unit tests // do not have to depend on the system's firewall configuration. MediaRouterDesktop(content::BrowserContext* context, DualMediaSinkService* media_sink_service); // mojom::MediaRouter implementation. void RegisterMediaRouteProvider( MediaRouteProviderId provider_id, mojom::MediaRouteProviderPtr media_route_provider_ptr, mojom::MediaRouter::RegisterMediaRouteProviderCallback callback) override; void OnSinksReceived(MediaRouteProviderId provider_id, const std::string& media_source, const std::vector<MediaSinkInternal>& internal_sinks, const std::vector<url::Origin>& origins) override; void GetMediaSinkServiceStatus( mojom::MediaRouter::GetMediaSinkServiceStatusCallback callback) override; // Registers a Mojo pointer to the extension MRP with // |extension_provider_proxy_| and does initializations specific to the // extension MRP. void RegisterExtensionMediaRouteProvider( mojom::MediaRouteProviderPtr extension_provider_ptr); // Binds |this| to a Mojo interface request, so that clients can acquire a // handle to a MediaRouter instance via the Mojo service connector. // Passes the extension's ID to the event page request manager. void BindToMojoRequest(mojo::InterfaceRequest<mojom::MediaRouter> request, const extensions::Extension& extension); // Provides the current list of sinks from |media_sink_service_| to the // extension. Also registers with |media_sink_service_| to listen for updates. void ProvideSinksToExtension(); // Notifies the Media Router that the list of MediaSinks discovered by a // MediaSinkService has been updated. // |provider_name|: Name of the MediaSinkService providing the sinks. // |sinks|: sinks discovered by MediaSinkService. void ProvideSinks(const std::string& provider_name, const std::vector<MediaSinkInternal>& sinks); // Initializes MRPs and adds them to |media_route_providers_|. void InitializeMediaRouteProviders(); // Helper methods for InitializeMediaRouteProviders(). void InitializeExtensionMediaRouteProviderProxy(); void InitializeWiredDisplayMediaRouteProvider(); void InitializeCastMediaRouteProvider(); void InitializeDialMediaRouteProvider(); #if defined(OS_WIN) // Ensures that mDNS discovery is enabled in the MRPM extension. This can be // called many times but the MRPM will only be called once per registration // period. void EnsureMdnsDiscoveryEnabled(); // Callback used to enable mDNS in the MRPM if a firewall prompt will not be // triggered. If a firewall prompt would be triggered, enabling mDNS won't // happen until the user is clearly interacting with MR. void OnFirewallCheckComplete(bool firewall_can_use_local_ports); #endif // MediaRouteProvider proxy that forwards calls to the MRPM in the component // extension. std::unique_ptr<ExtensionMediaRouteProviderProxy> extension_provider_proxy_; // MediaRouteProvider for casting to local screens. std::unique_ptr<WiredDisplayMediaRouteProvider> wired_display_provider_; // MediaRouteProvider for casting to Cast devices. std::unique_ptr<CastMediaRouteProvider, base::OnTaskRunnerDeleter> cast_provider_; // MediaRouteProvider for DIAL. std::unique_ptr<DialMediaRouteProvider> dial_provider_; DualMediaSinkService* media_sink_service_; DualMediaSinkService::Subscription media_sink_service_subscription_; // A flag to ensure that we record the provider version once, during the // initial event page wakeup attempt. bool provider_version_was_recorded_ = false; // A status object that keeps track of sinks discovered by media sink // services. MediaSinkServiceStatus media_sink_service_status_; #if defined(OS_WIN) // A flag to ensure that mDNS discovery is only enabled on Windows when there // will be appropriate context for the user to associate a firewall prompt // with Media Router. |should_enable_mdns_discovery_| can only go from // |false| to |true|. bool should_enable_mdns_discovery_ = false; #endif base::WeakPtrFactory<MediaRouterDesktop> weak_factory_; DISALLOW_COPY_AND_ASSIGN(MediaRouterDesktop); }; } // namespace media_router #endif // CHROME_BROWSER_MEDIA_ROUTER_MOJO_MEDIA_ROUTER_DESKTOP_H_
null
null
null
null
63,094
3,233
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
3,233
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// 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 STORAGE_BROWSER_FILEAPI_FILE_SYSTEM_OPERATION_IMPL_H_ #define STORAGE_BROWSER_FILEAPI_FILE_SYSTEM_OPERATION_IMPL_H_ #include <stdint.h> #include <memory> #include <vector> #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" #include "storage/browser/blob/scoped_file.h" #include "storage/browser/fileapi/file_system_operation.h" #include "storage/browser/fileapi/file_system_operation_context.h" #include "storage/browser/fileapi/file_system_url.h" #include "storage/browser/fileapi/file_writer_delegate.h" #include "storage/browser/storage_browser_export.h" #include "third_party/blink/public/mojom/quota/quota_types.mojom.h" namespace storage { class AsyncFileUtil; class FileSystemContext; class RecursiveOperationDelegate; // The default implementation of FileSystemOperation for file systems. class STORAGE_EXPORT FileSystemOperationImpl : public FileSystemOperation { public: ~FileSystemOperationImpl() override; // FileSystemOperation overrides. void CreateFile(const FileSystemURL& url, bool exclusive, const StatusCallback& callback) override; void CreateDirectory(const FileSystemURL& url, bool exclusive, bool recursive, const StatusCallback& callback) override; void Copy(const FileSystemURL& src_url, const FileSystemURL& dest_url, CopyOrMoveOption option, ErrorBehavior error_behavior, const CopyProgressCallback& progress_callback, const StatusCallback& callback) override; void Move(const FileSystemURL& src_url, const FileSystemURL& dest_url, CopyOrMoveOption option, const StatusCallback& callback) override; void DirectoryExists(const FileSystemURL& url, const StatusCallback& callback) override; void FileExists(const FileSystemURL& url, const StatusCallback& callback) override; void GetMetadata(const FileSystemURL& url, int fields, const GetMetadataCallback& callback) override; void ReadDirectory(const FileSystemURL& url, const ReadDirectoryCallback& callback) override; void Remove(const FileSystemURL& url, bool recursive, const StatusCallback& callback) override; void Write(const FileSystemURL& url, std::unique_ptr<FileWriterDelegate> writer_delegate, std::unique_ptr<net::URLRequest> blob_request, const WriteCallback& callback) override; void Truncate(const FileSystemURL& url, int64_t length, const StatusCallback& callback) override; void TouchFile(const FileSystemURL& url, const base::Time& last_access_time, const base::Time& last_modified_time, const StatusCallback& callback) override; void OpenFile(const FileSystemURL& url, int file_flags, const OpenFileCallback& callback) override; void Cancel(const StatusCallback& cancel_callback) override; void CreateSnapshotFile(const FileSystemURL& path, const SnapshotFileCallback& callback) override; void CopyInForeignFile(const base::FilePath& src_local_disk_path, const FileSystemURL& dest_url, const StatusCallback& callback) override; void RemoveFile(const FileSystemURL& url, const StatusCallback& callback) override; void RemoveDirectory(const FileSystemURL& url, const StatusCallback& callback) override; void CopyFileLocal(const FileSystemURL& src_url, const FileSystemURL& dest_url, CopyOrMoveOption option, const CopyFileProgressCallback& progress_callback, const StatusCallback& callback) override; void MoveFileLocal(const FileSystemURL& src_url, const FileSystemURL& dest_url, CopyOrMoveOption option, const StatusCallback& callback) override; base::File::Error SyncGetPlatformPath(const FileSystemURL& url, base::FilePath* platform_path) override; FileSystemContext* file_system_context() const { return file_system_context_.get(); } private: friend class FileSystemOperation; FileSystemOperationImpl( const FileSystemURL& url, FileSystemContext* file_system_context, std::unique_ptr<FileSystemOperationContext> operation_context); // Queries the quota and usage and then runs the given |task|. // If an error occurs during the quota query it runs |error_callback| instead. void GetUsageAndQuotaThenRunTask( const FileSystemURL& url, const base::Closure& task, const base::Closure& error_callback); // Called after the quota info is obtained from the quota manager // (which is triggered by GetUsageAndQuotaThenRunTask). // Sets the quota info in the operation_context_ and then runs the given // |task| if the returned quota status is successful, otherwise runs // |error_callback|. void DidGetUsageAndQuotaAndRunTask(const base::Closure& task, const base::Closure& error_callback, blink::mojom::QuotaStatusCode status, int64_t usage, int64_t quota); // The 'body' methods that perform the actual work (i.e. posting the // file task on proxy_) after the quota check. void DoCreateFile(const FileSystemURL& url, const StatusCallback& callback, bool exclusive); void DoCreateDirectory(const FileSystemURL& url, const StatusCallback& callback, bool exclusive, bool recursive); void DoCopyFileLocal(const FileSystemURL& src, const FileSystemURL& dest, CopyOrMoveOption option, const CopyFileProgressCallback& progress_callback, const StatusCallback& callback); void DoMoveFileLocal(const FileSystemURL& src, const FileSystemURL& dest, CopyOrMoveOption option, const StatusCallback& callback); void DoCopyInForeignFile(const base::FilePath& src_local_disk_file_path, const FileSystemURL& dest, const StatusCallback& callback); void DoTruncate(const FileSystemURL& url, const StatusCallback& callback, int64_t length); void DoOpenFile(const FileSystemURL& url, const OpenFileCallback& callback, int file_flags); // Callback for CreateFile for |exclusive|=true cases. void DidEnsureFileExistsExclusive(const StatusCallback& callback, base::File::Error rv, bool created); // Callback for CreateFile for |exclusive|=false cases. void DidEnsureFileExistsNonExclusive(const StatusCallback& callback, base::File::Error rv, bool created); void DidFinishOperation(const StatusCallback& callback, base::File::Error rv); void DidDirectoryExists(const StatusCallback& callback, base::File::Error rv, const base::File::Info& file_info); void DidFileExists(const StatusCallback& callback, base::File::Error rv, const base::File::Info& file_info); void DidDeleteRecursively(const FileSystemURL& url, const StatusCallback& callback, base::File::Error rv); void DidWrite(const FileSystemURL& url, const WriteCallback& callback, base::File::Error rv, int64_t bytes, FileWriterDelegate::WriteProgressStatus write_status); // Used only for internal assertions. // Returns false if there's another inflight pending operation. bool SetPendingOperationType(OperationType type); scoped_refptr<FileSystemContext> file_system_context_; std::unique_ptr<FileSystemOperationContext> operation_context_; AsyncFileUtil* async_file_util_; // Not owned. std::unique_ptr<FileWriterDelegate> file_writer_delegate_; std::unique_ptr<RecursiveOperationDelegate> recursive_operation_delegate_; StatusCallback cancel_callback_; // A flag to make sure we call operation only once per instance. OperationType pending_operation_; base::WeakPtrFactory<FileSystemOperationImpl> weak_factory_; DISALLOW_COPY_AND_ASSIGN(FileSystemOperationImpl); }; } // namespace storage #endif // STORAGE_BROWSER_FILEAPI_FILE_SYSTEM_OPERATION_IMPL_H_
null
null
null
null
96
37,133
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
202,128
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * 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. * * Copyright (C) 2013 ARM Limited */ #include <linux/amba/sp810.h> #include <linux/slab.h> #include <linux/clk.h> #include <linux/clk-provider.h> #include <linux/err.h> #include <linux/of.h> #include <linux/of_address.h> #define to_clk_sp810_timerclken(_hw) \ container_of(_hw, struct clk_sp810_timerclken, hw) struct clk_sp810; struct clk_sp810_timerclken { struct clk_hw hw; struct clk *clk; struct clk_sp810 *sp810; int channel; }; struct clk_sp810 { struct device_node *node; void __iomem *base; spinlock_t lock; struct clk_sp810_timerclken timerclken[4]; }; static u8 clk_sp810_timerclken_get_parent(struct clk_hw *hw) { struct clk_sp810_timerclken *timerclken = to_clk_sp810_timerclken(hw); u32 val = readl(timerclken->sp810->base + SCCTRL); return !!(val & (1 << SCCTRL_TIMERENnSEL_SHIFT(timerclken->channel))); } static int clk_sp810_timerclken_set_parent(struct clk_hw *hw, u8 index) { struct clk_sp810_timerclken *timerclken = to_clk_sp810_timerclken(hw); struct clk_sp810 *sp810 = timerclken->sp810; u32 val, shift = SCCTRL_TIMERENnSEL_SHIFT(timerclken->channel); unsigned long flags = 0; if (WARN_ON(index > 1)) return -EINVAL; spin_lock_irqsave(&sp810->lock, flags); val = readl(sp810->base + SCCTRL); val &= ~(1 << shift); val |= index << shift; writel(val, sp810->base + SCCTRL); spin_unlock_irqrestore(&sp810->lock, flags); return 0; } static const struct clk_ops clk_sp810_timerclken_ops = { .get_parent = clk_sp810_timerclken_get_parent, .set_parent = clk_sp810_timerclken_set_parent, }; static struct clk *clk_sp810_timerclken_of_get(struct of_phandle_args *clkspec, void *data) { struct clk_sp810 *sp810 = data; if (WARN_ON(clkspec->args_count != 1 || clkspec->args[0] >= ARRAY_SIZE(sp810->timerclken))) return NULL; return sp810->timerclken[clkspec->args[0]].clk; } static void __init clk_sp810_of_setup(struct device_node *node) { struct clk_sp810 *sp810 = kzalloc(sizeof(*sp810), GFP_KERNEL); const char *parent_names[2]; int num = ARRAY_SIZE(parent_names); char name[12]; struct clk_init_data init; static int instance; int i; bool deprecated; if (!sp810) return; if (of_clk_parent_fill(node, parent_names, num) != num) { pr_warn("Failed to obtain parent clocks for SP810!\n"); kfree(sp810); return; } sp810->node = node; sp810->base = of_iomap(node, 0); spin_lock_init(&sp810->lock); init.name = name; init.ops = &clk_sp810_timerclken_ops; init.flags = CLK_IS_BASIC; init.parent_names = parent_names; init.num_parents = num; deprecated = !of_find_property(node, "assigned-clock-parents", NULL); for (i = 0; i < ARRAY_SIZE(sp810->timerclken); i++) { snprintf(name, sizeof(name), "sp810_%d_%d", instance, i); sp810->timerclken[i].sp810 = sp810; sp810->timerclken[i].channel = i; sp810->timerclken[i].hw.init = &init; /* * If DT isn't setting the parent, force it to be * the 1 MHz clock without going through the framework. * We do this before clk_register() so that it can determine * the parent and setup the tree properly. */ if (deprecated) init.ops->set_parent(&sp810->timerclken[i].hw, 1); sp810->timerclken[i].clk = clk_register(NULL, &sp810->timerclken[i].hw); WARN_ON(IS_ERR(sp810->timerclken[i].clk)); } of_clk_add_provider(node, clk_sp810_timerclken_of_get, sp810); instance++; } CLK_OF_DECLARE(sp810, "arm,sp810", clk_sp810_of_setup);
null
null
null
null
110,475
21,036
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
21,036
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CONTENT_RENDERER_DOM_STORAGE_DOM_STORAGE_CACHED_AREA_H_ #define CONTENT_RENDERER_DOM_STORAGE_DOM_STORAGE_CACHED_AREA_H_ #include <stddef.h> #include <stdint.h> #include <map> #include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" #include "base/strings/nullable_string16.h" #include "content/common/content_export.h" #include "third_party/blink/public/platform/web_scoped_virtual_time_pauser.h" #include "url/gurl.h" namespace blink { namespace scheduler { class WebMainThreadScheduler; } } // namespace blink namespace content { class DOMStorageMap; class DOMStorageProxy; // Unlike the other classes in the dom_storage library, this one is intended // for use in renderer processes. It maintains a complete cache of the // origin's Map of key/value pairs for fast access. The cache is primed on // first access and changes are written to the backend thru the |proxy|. // Mutations originating in other processes are applied to the cache via // the ApplyMutation method. class CONTENT_EXPORT DOMStorageCachedArea : public base::RefCounted<DOMStorageCachedArea> { public: DOMStorageCachedArea( const std::string& namespace_id, const GURL& origin, DOMStorageProxy* proxy, blink::scheduler::WebMainThreadScheduler* main_thread_scheduler); const std::string& namespace_id() const { return namespace_id_; } const GURL& origin() const { return origin_; } unsigned GetLength(int connection_id); base::NullableString16 GetKey(int connection_id, unsigned index); base::NullableString16 GetItem(int connection_id, const base::string16& key); bool SetItem(int connection_id, const base::string16& key, const base::string16& value, const GURL& page_url); void RemoveItem(int connection_id, const base::string16& key, const GURL& page_url); void Clear(int connection_id, const GURL& page_url); void ApplyMutation(const base::NullableString16& key, const base::NullableString16& new_value); private: friend class DOMStorageCachedAreaTest; friend class base::RefCounted<DOMStorageCachedArea>; ~DOMStorageCachedArea(); // Primes the cache, loading all values for the area. void Prime(int connection_id); void PrimeIfNeeded(int connection_id) { if (!map_.get()) Prime(connection_id); } // Resets the object back to its newly constructed state. void Reset(); // Async completion callbacks for proxied operations. // These are used to maintain cache consistency by preventing // mutation events from other processes from overwriting local // changes made after the mutation. void OnLoadComplete(bool success); void OnSetItemComplete(const base::string16& key, blink::WebScopedVirtualTimePauser virtual_time_pauser, bool success); void OnClearComplete(blink::WebScopedVirtualTimePauser virtual_time_pauser, bool success); void OnRemoveItemComplete( const base::string16& key, blink::WebScopedVirtualTimePauser virtual_time_pauser, bool success); bool should_ignore_key_mutation(const base::string16& key) const { return ignore_key_mutations_.find(key) != ignore_key_mutations_.end(); } bool ignore_all_mutations_; std::map<base::string16, int> ignore_key_mutations_; std::string namespace_id_; GURL origin_; scoped_refptr<DOMStorageMap> map_; scoped_refptr<DOMStorageProxy> proxy_; // Not owned. blink::scheduler::WebMainThreadScheduler* main_thread_scheduler_; base::WeakPtrFactory<DOMStorageCachedArea> weak_factory_; }; } // namespace content #endif // CONTENT_RENDERER_DOM_STORAGE_DOM_STORAGE_CACHED_AREA_H_
null
null
null
null
17,899
4,936
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
169,931
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * The driver for the Yamaha's DS1/DS1E cards * Copyright (c) by Jaroslav Kysela <perex@perex.cz> * * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ #include <linux/init.h> #include <linux/pci.h> #include <linux/time.h> #include <linux/module.h> #include <sound/core.h> #include "ymfpci.h" #include <sound/mpu401.h> #include <sound/opl3.h> #include <sound/initval.h> MODULE_AUTHOR("Jaroslav Kysela <perex@perex.cz>"); MODULE_DESCRIPTION("Yamaha DS-1 PCI"); MODULE_LICENSE("GPL"); MODULE_SUPPORTED_DEVICE("{{Yamaha,YMF724}," "{Yamaha,YMF724F}," "{Yamaha,YMF740}," "{Yamaha,YMF740C}," "{Yamaha,YMF744}," "{Yamaha,YMF754}}"); static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX; /* Index 0-MAX */ static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR; /* ID for this card */ static bool enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_PNP; /* Enable this card */ static long fm_port[SNDRV_CARDS]; static long mpu_port[SNDRV_CARDS]; #ifdef SUPPORT_JOYSTICK static long joystick_port[SNDRV_CARDS]; #endif static bool rear_switch[SNDRV_CARDS]; module_param_array(index, int, NULL, 0444); MODULE_PARM_DESC(index, "Index value for the Yamaha DS-1 PCI soundcard."); module_param_array(id, charp, NULL, 0444); MODULE_PARM_DESC(id, "ID string for the Yamaha DS-1 PCI soundcard."); module_param_array(enable, bool, NULL, 0444); MODULE_PARM_DESC(enable, "Enable Yamaha DS-1 soundcard."); module_param_array(mpu_port, long, NULL, 0444); MODULE_PARM_DESC(mpu_port, "MPU-401 Port."); module_param_array(fm_port, long, NULL, 0444); MODULE_PARM_DESC(fm_port, "FM OPL-3 Port."); #ifdef SUPPORT_JOYSTICK module_param_array(joystick_port, long, NULL, 0444); MODULE_PARM_DESC(joystick_port, "Joystick port address"); #endif module_param_array(rear_switch, bool, NULL, 0444); MODULE_PARM_DESC(rear_switch, "Enable shared rear/line-in switch"); static const struct pci_device_id snd_ymfpci_ids[] = { { PCI_VDEVICE(YAMAHA, 0x0004), 0, }, /* YMF724 */ { PCI_VDEVICE(YAMAHA, 0x000d), 0, }, /* YMF724F */ { PCI_VDEVICE(YAMAHA, 0x000a), 0, }, /* YMF740 */ { PCI_VDEVICE(YAMAHA, 0x000c), 0, }, /* YMF740C */ { PCI_VDEVICE(YAMAHA, 0x0010), 0, }, /* YMF744 */ { PCI_VDEVICE(YAMAHA, 0x0012), 0, }, /* YMF754 */ { 0, } }; MODULE_DEVICE_TABLE(pci, snd_ymfpci_ids); #ifdef SUPPORT_JOYSTICK static int snd_ymfpci_create_gameport(struct snd_ymfpci *chip, int dev, int legacy_ctrl, int legacy_ctrl2) { struct gameport *gp; struct resource *r = NULL; int io_port = joystick_port[dev]; if (!io_port) return -ENODEV; if (chip->pci->device >= 0x0010) { /* YMF 744/754 */ if (io_port == 1) { /* auto-detect */ if (!(io_port = pci_resource_start(chip->pci, 2))) return -ENODEV; } } else { if (io_port == 1) { /* auto-detect */ for (io_port = 0x201; io_port <= 0x205; io_port++) { if (io_port == 0x203) continue; if ((r = request_region(io_port, 1, "YMFPCI gameport")) != NULL) break; } if (!r) { dev_err(chip->card->dev, "no gameport ports available\n"); return -EBUSY; } } switch (io_port) { case 0x201: legacy_ctrl2 |= 0 << 6; break; case 0x202: legacy_ctrl2 |= 1 << 6; break; case 0x204: legacy_ctrl2 |= 2 << 6; break; case 0x205: legacy_ctrl2 |= 3 << 6; break; default: dev_err(chip->card->dev, "invalid joystick port %#x", io_port); return -EINVAL; } } if (!r && !(r = request_region(io_port, 1, "YMFPCI gameport"))) { dev_err(chip->card->dev, "joystick port %#x is in use.\n", io_port); return -EBUSY; } chip->gameport = gp = gameport_allocate_port(); if (!gp) { dev_err(chip->card->dev, "cannot allocate memory for gameport\n"); release_and_free_resource(r); return -ENOMEM; } gameport_set_name(gp, "Yamaha YMF Gameport"); gameport_set_phys(gp, "pci%s/gameport0", pci_name(chip->pci)); gameport_set_dev_parent(gp, &chip->pci->dev); gp->io = io_port; gameport_set_port_data(gp, r); if (chip->pci->device >= 0x0010) /* YMF 744/754 */ pci_write_config_word(chip->pci, PCIR_DSXG_JOYBASE, io_port); pci_write_config_word(chip->pci, PCIR_DSXG_LEGACY, legacy_ctrl | YMFPCI_LEGACY_JPEN); pci_write_config_word(chip->pci, PCIR_DSXG_ELEGACY, legacy_ctrl2); gameport_register_port(chip->gameport); return 0; } void snd_ymfpci_free_gameport(struct snd_ymfpci *chip) { if (chip->gameport) { struct resource *r = gameport_get_port_data(chip->gameport); gameport_unregister_port(chip->gameport); chip->gameport = NULL; release_and_free_resource(r); } } #else static inline int snd_ymfpci_create_gameport(struct snd_ymfpci *chip, int dev, int l, int l2) { return -ENOSYS; } void snd_ymfpci_free_gameport(struct snd_ymfpci *chip) { } #endif /* SUPPORT_JOYSTICK */ static int snd_card_ymfpci_probe(struct pci_dev *pci, const struct pci_device_id *pci_id) { static int dev; struct snd_card *card; struct resource *fm_res = NULL; struct resource *mpu_res = NULL; struct snd_ymfpci *chip; struct snd_opl3 *opl3; const char *str, *model; int err; u16 legacy_ctrl, legacy_ctrl2, old_legacy_ctrl; if (dev >= SNDRV_CARDS) return -ENODEV; if (!enable[dev]) { dev++; return -ENOENT; } err = snd_card_new(&pci->dev, index[dev], id[dev], THIS_MODULE, 0, &card); if (err < 0) return err; switch (pci_id->device) { case 0x0004: str = "YMF724"; model = "DS-1"; break; case 0x000d: str = "YMF724F"; model = "DS-1"; break; case 0x000a: str = "YMF740"; model = "DS-1L"; break; case 0x000c: str = "YMF740C"; model = "DS-1L"; break; case 0x0010: str = "YMF744"; model = "DS-1S"; break; case 0x0012: str = "YMF754"; model = "DS-1E"; break; default: model = str = "???"; break; } legacy_ctrl = 0; legacy_ctrl2 = 0x0800; /* SBEN = 0, SMOD = 01, LAD = 0 */ if (pci_id->device >= 0x0010) { /* YMF 744/754 */ if (fm_port[dev] == 1) { /* auto-detect */ fm_port[dev] = pci_resource_start(pci, 1); } if (fm_port[dev] > 0 && (fm_res = request_region(fm_port[dev], 4, "YMFPCI OPL3")) != NULL) { legacy_ctrl |= YMFPCI_LEGACY_FMEN; pci_write_config_word(pci, PCIR_DSXG_FMBASE, fm_port[dev]); } if (mpu_port[dev] == 1) { /* auto-detect */ mpu_port[dev] = pci_resource_start(pci, 1) + 0x20; } if (mpu_port[dev] > 0 && (mpu_res = request_region(mpu_port[dev], 2, "YMFPCI MPU401")) != NULL) { legacy_ctrl |= YMFPCI_LEGACY_MEN; pci_write_config_word(pci, PCIR_DSXG_MPU401BASE, mpu_port[dev]); } } else { switch (fm_port[dev]) { case 0x388: legacy_ctrl2 |= 0; break; case 0x398: legacy_ctrl2 |= 1; break; case 0x3a0: legacy_ctrl2 |= 2; break; case 0x3a8: legacy_ctrl2 |= 3; break; default: fm_port[dev] = 0; break; } if (fm_port[dev] > 0 && (fm_res = request_region(fm_port[dev], 4, "YMFPCI OPL3")) != NULL) { legacy_ctrl |= YMFPCI_LEGACY_FMEN; } else { legacy_ctrl2 &= ~YMFPCI_LEGACY2_FMIO; fm_port[dev] = 0; } switch (mpu_port[dev]) { case 0x330: legacy_ctrl2 |= 0 << 4; break; case 0x300: legacy_ctrl2 |= 1 << 4; break; case 0x332: legacy_ctrl2 |= 2 << 4; break; case 0x334: legacy_ctrl2 |= 3 << 4; break; default: mpu_port[dev] = 0; break; } if (mpu_port[dev] > 0 && (mpu_res = request_region(mpu_port[dev], 2, "YMFPCI MPU401")) != NULL) { legacy_ctrl |= YMFPCI_LEGACY_MEN; } else { legacy_ctrl2 &= ~YMFPCI_LEGACY2_MPUIO; mpu_port[dev] = 0; } } if (mpu_res) { legacy_ctrl |= YMFPCI_LEGACY_MIEN; legacy_ctrl2 |= YMFPCI_LEGACY2_IMOD; } pci_read_config_word(pci, PCIR_DSXG_LEGACY, &old_legacy_ctrl); pci_write_config_word(pci, PCIR_DSXG_LEGACY, legacy_ctrl); pci_write_config_word(pci, PCIR_DSXG_ELEGACY, legacy_ctrl2); if ((err = snd_ymfpci_create(card, pci, old_legacy_ctrl, &chip)) < 0) { snd_card_free(card); release_and_free_resource(mpu_res); release_and_free_resource(fm_res); return err; } chip->fm_res = fm_res; chip->mpu_res = mpu_res; card->private_data = chip; strcpy(card->driver, str); sprintf(card->shortname, "Yamaha %s (%s)", model, str); sprintf(card->longname, "%s at 0x%lx, irq %i", card->shortname, chip->reg_area_phys, chip->irq); if ((err = snd_ymfpci_pcm(chip, 0)) < 0) { snd_card_free(card); return err; } if ((err = snd_ymfpci_pcm_spdif(chip, 1)) < 0) { snd_card_free(card); return err; } err = snd_ymfpci_mixer(chip, rear_switch[dev]); if (err < 0) { snd_card_free(card); return err; } if (chip->ac97->ext_id & AC97_EI_SDAC) { err = snd_ymfpci_pcm_4ch(chip, 2); if (err < 0) { snd_card_free(card); return err; } err = snd_ymfpci_pcm2(chip, 3); if (err < 0) { snd_card_free(card); return err; } } if ((err = snd_ymfpci_timer(chip, 0)) < 0) { snd_card_free(card); return err; } if (chip->mpu_res) { if ((err = snd_mpu401_uart_new(card, 0, MPU401_HW_YMFPCI, mpu_port[dev], MPU401_INFO_INTEGRATED | MPU401_INFO_IRQ_HOOK, -1, &chip->rawmidi)) < 0) { dev_warn(card->dev, "cannot initialize MPU401 at 0x%lx, skipping...\n", mpu_port[dev]); legacy_ctrl &= ~YMFPCI_LEGACY_MIEN; /* disable MPU401 irq */ pci_write_config_word(pci, PCIR_DSXG_LEGACY, legacy_ctrl); } } if (chip->fm_res) { if ((err = snd_opl3_create(card, fm_port[dev], fm_port[dev] + 2, OPL3_HW_OPL3, 1, &opl3)) < 0) { dev_warn(card->dev, "cannot initialize FM OPL3 at 0x%lx, skipping...\n", fm_port[dev]); legacy_ctrl &= ~YMFPCI_LEGACY_FMEN; pci_write_config_word(pci, PCIR_DSXG_LEGACY, legacy_ctrl); } else if ((err = snd_opl3_hwdep_new(opl3, 0, 1, NULL)) < 0) { snd_card_free(card); dev_err(card->dev, "cannot create opl3 hwdep\n"); return err; } } snd_ymfpci_create_gameport(chip, dev, legacy_ctrl, legacy_ctrl2); if ((err = snd_card_register(card)) < 0) { snd_card_free(card); return err; } pci_set_drvdata(pci, card); dev++; return 0; } static void snd_card_ymfpci_remove(struct pci_dev *pci) { snd_card_free(pci_get_drvdata(pci)); } static struct pci_driver ymfpci_driver = { .name = KBUILD_MODNAME, .id_table = snd_ymfpci_ids, .probe = snd_card_ymfpci_probe, .remove = snd_card_ymfpci_remove, #ifdef CONFIG_PM_SLEEP .driver = { .pm = &snd_ymfpci_pm, }, #endif }; module_pci_driver(ymfpci_driver);
null
null
null
null
78,278
55,561
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
55,561
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright 2017 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/services/printing/pdf_to_pwg_raster_converter.h" #include <limits> #include <string> #include <utility> #include "components/pwg_encoder/bitmap_image.h" #include "components/pwg_encoder/pwg_encoder.h" #include "mojo/public/cpp/bindings/strong_binding.h" #include "mojo/public/cpp/system/platform_handle.h" #include "pdf/pdf.h" #include "printing/pdf_render_settings.h" namespace printing { namespace { bool RenderPdfPagesToPwgRaster(base::File pdf_file, const PdfRenderSettings& settings, const PwgRasterSettings& bitmap_settings, base::File bitmap_file) { base::File::Info info; if (!pdf_file.GetInfo(&info) || info.size <= 0 || info.size > std::numeric_limits<int>::max()) return false; int data_size = static_cast<int>(info.size); std::string data(data_size, 0); if (pdf_file.Read(0, &data[0], data_size) != data_size) return false; int total_page_count = 0; if (!chrome_pdf::GetPDFDocInfo(data.data(), data_size, &total_page_count, nullptr)) { return false; } std::string pwg_header = pwg_encoder::PwgEncoder::GetDocumentHeader(); int bytes_written = bitmap_file.WriteAtCurrentPos(pwg_header.data(), pwg_header.size()); if (bytes_written != static_cast<int>(pwg_header.size())) return false; pwg_encoder::BitmapImage image(settings.area.size(), pwg_encoder::BitmapImage::BGRA); for (int i = 0; i < total_page_count; ++i) { int page_number = i; if (bitmap_settings.reverse_page_order) page_number = total_page_count - 1 - page_number; if (!chrome_pdf::RenderPDFPageToBitmap( data.data(), data_size, page_number, image.pixel_data(), image.size().width(), image.size().height(), settings.dpi.width(), settings.dpi.height(), settings.autorotate)) { return false; } pwg_encoder::PwgHeaderInfo header_info; header_info.dpi = settings.dpi; header_info.total_pages = total_page_count; header_info.color_space = bitmap_settings.use_color ? pwg_encoder::PwgHeaderInfo::SRGB : pwg_encoder::PwgHeaderInfo::SGRAY; // Transform odd pages. if (page_number % 2) { switch (bitmap_settings.odd_page_transform) { case TRANSFORM_NORMAL: break; case TRANSFORM_ROTATE_180: header_info.flipx = true; header_info.flipy = true; break; case TRANSFORM_FLIP_HORIZONTAL: header_info.flipx = true; break; case TRANSFORM_FLIP_VERTICAL: header_info.flipy = true; break; } } if (bitmap_settings.rotate_all_pages) { header_info.flipx = !header_info.flipx; header_info.flipy = !header_info.flipy; } std::string pwg_page = pwg_encoder::PwgEncoder::EncodePage(image, header_info); if (pwg_page.empty()) return false; bytes_written = bitmap_file.WriteAtCurrentPos(pwg_page.data(), pwg_page.size()); if (bytes_written != static_cast<int>(pwg_page.size())) return false; } return true; } } // namespace PdfToPwgRasterConverter::PdfToPwgRasterConverter( std::unique_ptr<service_manager::ServiceContextRef> service_ref) : service_ref_(std::move(service_ref)) {} PdfToPwgRasterConverter::~PdfToPwgRasterConverter() {} void PdfToPwgRasterConverter::Convert( mojo::ScopedHandle pdf_file_in, const PdfRenderSettings& pdf_settings, const PwgRasterSettings& pwg_raster_settings, mojo::ScopedHandle pwg_raster_file_out, ConvertCallback callback) { base::PlatformFile pdf_file; if (mojo::UnwrapPlatformFile(std::move(pdf_file_in), &pdf_file) != MOJO_RESULT_OK) { LOG(ERROR) << "Invalid PDF file passed to PdfToPwgRasterConverter."; std::move(callback).Run(false); return; } base::PlatformFile pwg_raster_file; if (mojo::UnwrapPlatformFile(std::move(pwg_raster_file_out), &pwg_raster_file) != MOJO_RESULT_OK) { LOG(ERROR) << "Invalid PWGRaster file passed to PdfToPwgRasterConverter."; std::move(callback).Run(false); return; } bool result = RenderPdfPagesToPwgRaster(base::File(pdf_file), pdf_settings, pwg_raster_settings, base::File(pwg_raster_file)); std::move(callback).Run(result); } } // namespace printing
null
null
null
null
52,424
69,934
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
69,934
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright 2016 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 "device/bluetooth/bluetooth_local_gatt_service.h" #include "build/build_config.h" namespace device { #if !defined(OS_LINUX) || defined(LINUX_WITHOUT_DBUS) // static base::WeakPtr<BluetoothLocalGattService> BluetoothLocalGattService::Create( BluetoothAdapter* adapter, const BluetoothUUID& uuid, bool is_primary, BluetoothLocalGattService* included_service, BluetoothLocalGattService::Delegate* delegate) { NOTIMPLEMENTED(); return nullptr; } #endif BluetoothLocalGattService::BluetoothLocalGattService() = default; BluetoothLocalGattService::~BluetoothLocalGattService() = default; } // namespace device
null
null
null
null
66,797
63,716
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
63,716
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_UI_WEBUI_SIGNIN_INTERNALS_UI_H_ #define CHROME_BROWSER_UI_WEBUI_SIGNIN_INTERNALS_UI_H_ #include "base/compiler_specific.h" #include "base/macros.h" #include "base/values.h" #include "components/signin/core/browser/about_signin_internals.h" #include "content/public/browser/web_ui_controller.h" // The implementation for the chrome://signin-internals page. class SignInInternalsUI : public content::WebUIController, public AboutSigninInternals::Observer { public: explicit SignInInternalsUI(content::WebUI* web_ui); ~SignInInternalsUI() override; // content::WebUIController implementation. bool OverrideHandleWebUIMessage(const GURL& source_url, const std::string& name, const base::ListValue& args) override; // AboutSigninInternals::Observer::OnSigninStateChanged implementation. void OnSigninStateChanged(const base::DictionaryValue* info) override; // Notification that the cookie accounts are ready to be displayed. void OnCookieAccountsFetched(const base::DictionaryValue* info) override; private: DISALLOW_COPY_AND_ASSIGN(SignInInternalsUI); }; #endif // CHROME_BROWSER_UI_WEBUI_SIGNIN_INTERNALS_UI_H_
null
null
null
null
60,579