code
stringlengths
4
1.01M
language
stringclasses
2 values
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // Intel License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000, Intel Corporation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of Intel Corporation may not 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 Intel Corporation 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. // //M*/ #include "precomp.hpp" // The function calculates center of gravity and the central second order moments static void icvCompleteMomentState( CvMoments* moments ) { double cx = 0, cy = 0; double mu20, mu11, mu02; assert( moments != 0 ); moments->inv_sqrt_m00 = 0; if( fabs(moments->m00) > DBL_EPSILON ) { double inv_m00 = 1. / moments->m00; cx = moments->m10 * inv_m00; cy = moments->m01 * inv_m00; moments->inv_sqrt_m00 = std::sqrt( fabs(inv_m00) ); } // mu20 = m20 - m10*cx mu20 = moments->m20 - moments->m10 * cx; // mu11 = m11 - m10*cy mu11 = moments->m11 - moments->m10 * cy; // mu02 = m02 - m01*cy mu02 = moments->m02 - moments->m01 * cy; moments->mu20 = mu20; moments->mu11 = mu11; moments->mu02 = mu02; // mu30 = m30 - cx*(3*mu20 + cx*m10) moments->mu30 = moments->m30 - cx * (3 * mu20 + cx * moments->m10); mu11 += mu11; // mu21 = m21 - cx*(2*mu11 + cx*m01) - cy*mu20 moments->mu21 = moments->m21 - cx * (mu11 + cx * moments->m01) - cy * mu20; // mu12 = m12 - cy*(2*mu11 + cy*m10) - cx*mu02 moments->mu12 = moments->m12 - cy * (mu11 + cy * moments->m10) - cx * mu02; // mu03 = m03 - cy*(3*mu02 + cy*m01) moments->mu03 = moments->m03 - cy * (3 * mu02 + cy * moments->m01); } static void icvContourMoments( CvSeq* contour, CvMoments* moments ) { int is_float = CV_SEQ_ELTYPE(contour) == CV_32FC2; if( contour->total ) { CvSeqReader reader; double a00, a10, a01, a20, a11, a02, a30, a21, a12, a03; double xi, yi, xi2, yi2, xi_1, yi_1, xi_12, yi_12, dxy, xii_1, yii_1; int lpt = contour->total; a00 = a10 = a01 = a20 = a11 = a02 = a30 = a21 = a12 = a03 = 0; cvStartReadSeq( contour, &reader, 0 ); if( !is_float ) { xi_1 = ((CvPoint*)(reader.ptr))->x; yi_1 = ((CvPoint*)(reader.ptr))->y; } else { xi_1 = ((CvPoint2D32f*)(reader.ptr))->x; yi_1 = ((CvPoint2D32f*)(reader.ptr))->y; } CV_NEXT_SEQ_ELEM( contour->elem_size, reader ); xi_12 = xi_1 * xi_1; yi_12 = yi_1 * yi_1; while( lpt-- > 0 ) { if( !is_float ) { xi = ((CvPoint*)(reader.ptr))->x; yi = ((CvPoint*)(reader.ptr))->y; } else { xi = ((CvPoint2D32f*)(reader.ptr))->x; yi = ((CvPoint2D32f*)(reader.ptr))->y; } CV_NEXT_SEQ_ELEM( contour->elem_size, reader ); xi2 = xi * xi; yi2 = yi * yi; dxy = xi_1 * yi - xi * yi_1; xii_1 = xi_1 + xi; yii_1 = yi_1 + yi; a00 += dxy; a10 += dxy * xii_1; a01 += dxy * yii_1; a20 += dxy * (xi_1 * xii_1 + xi2); a11 += dxy * (xi_1 * (yii_1 + yi_1) + xi * (yii_1 + yi)); a02 += dxy * (yi_1 * yii_1 + yi2); a30 += dxy * xii_1 * (xi_12 + xi2); a03 += dxy * yii_1 * (yi_12 + yi2); a21 += dxy * (xi_12 * (3 * yi_1 + yi) + 2 * xi * xi_1 * yii_1 + xi2 * (yi_1 + 3 * yi)); a12 += dxy * (yi_12 * (3 * xi_1 + xi) + 2 * yi * yi_1 * xii_1 + yi2 * (xi_1 + 3 * xi)); xi_1 = xi; yi_1 = yi; xi_12 = xi2; yi_12 = yi2; } double db1_2, db1_6, db1_12, db1_24, db1_20, db1_60; if( fabs(a00) > FLT_EPSILON ) { if( a00 > 0 ) { db1_2 = 0.5; db1_6 = 0.16666666666666666666666666666667; db1_12 = 0.083333333333333333333333333333333; db1_24 = 0.041666666666666666666666666666667; db1_20 = 0.05; db1_60 = 0.016666666666666666666666666666667; } else { db1_2 = -0.5; db1_6 = -0.16666666666666666666666666666667; db1_12 = -0.083333333333333333333333333333333; db1_24 = -0.041666666666666666666666666666667; db1_20 = -0.05; db1_60 = -0.016666666666666666666666666666667; } // spatial moments moments->m00 = a00 * db1_2; moments->m10 = a10 * db1_6; moments->m01 = a01 * db1_6; moments->m20 = a20 * db1_12; moments->m11 = a11 * db1_24; moments->m02 = a02 * db1_12; moments->m30 = a30 * db1_20; moments->m21 = a21 * db1_60; moments->m12 = a12 * db1_60; moments->m03 = a03 * db1_20; icvCompleteMomentState( moments ); } } } /****************************************************************************************\ * Spatial Raster Moments * \****************************************************************************************/ template<typename T, typename WT, typename MT> static void momentsInTile( const cv::Mat& img, double* moments ) { cv::Size size = img.size(); int x, y; MT mom[10] = {0,0,0,0,0,0,0,0,0,0}; for( y = 0; y < size.height; y++ ) { const T* ptr = (const T*)(img.data + y*img.step); WT x0 = 0, x1 = 0, x2 = 0; MT x3 = 0; for( x = 0; x < size.width; x++ ) { WT p = ptr[x]; WT xp = x * p, xxp; x0 += p; x1 += xp; xxp = xp * x; x2 += xxp; x3 += xxp * x; } WT py = y * x0, sy = y*y; mom[9] += ((MT)py) * sy; // m03 mom[8] += ((MT)x1) * sy; // m12 mom[7] += ((MT)x2) * y; // m21 mom[6] += x3; // m30 mom[5] += x0 * sy; // m02 mom[4] += x1 * y; // m11 mom[3] += x2; // m20 mom[2] += py; // m01 mom[1] += x1; // m10 mom[0] += x0; // m00 } for( x = 0; x < 10; x++ ) moments[x] = (double)mom[x]; } #if CV_SSE2 template<> void momentsInTile<uchar, int, int>( const cv::Mat& img, double* moments ) { typedef uchar T; typedef int WT; typedef int MT; cv::Size size = img.size(); int x, y; MT mom[10] = {0,0,0,0,0,0,0,0,0,0}; bool useSIMD = cv::checkHardwareSupport(CV_CPU_SSE2); for( y = 0; y < size.height; y++ ) { const T* ptr = img.ptr<T>(y); int x0 = 0, x1 = 0, x2 = 0, x3 = 0, x = 0; if( useSIMD ) { __m128i qx_init = _mm_setr_epi16(0, 1, 2, 3, 4, 5, 6, 7); __m128i dx = _mm_set1_epi16(8); __m128i z = _mm_setzero_si128(), qx0 = z, qx1 = z, qx2 = z, qx3 = z, qx = qx_init; for( ; x <= size.width - 8; x += 8 ) { __m128i p = _mm_unpacklo_epi8(_mm_loadl_epi64((const __m128i*)(ptr + x)), z); qx0 = _mm_add_epi32(qx0, _mm_sad_epu8(p, z)); __m128i px = _mm_mullo_epi16(p, qx); __m128i sx = _mm_mullo_epi16(qx, qx); qx1 = _mm_add_epi32(qx1, _mm_madd_epi16(p, qx)); qx2 = _mm_add_epi32(qx2, _mm_madd_epi16(p, sx)); qx3 = _mm_add_epi32(qx3, _mm_madd_epi16(px, sx)); qx = _mm_add_epi16(qx, dx); } int CV_DECL_ALIGNED(16) buf[4]; _mm_store_si128((__m128i*)buf, qx0); x0 = buf[0] + buf[1] + buf[2] + buf[3]; _mm_store_si128((__m128i*)buf, qx1); x1 = buf[0] + buf[1] + buf[2] + buf[3]; _mm_store_si128((__m128i*)buf, qx2); x2 = buf[0] + buf[1] + buf[2] + buf[3]; _mm_store_si128((__m128i*)buf, qx3); x3 = buf[0] + buf[1] + buf[2] + buf[3]; } for( ; x < size.width; x++ ) { WT p = ptr[x]; WT xp = x * p, xxp; x0 += p; x1 += xp; xxp = xp * x; x2 += xxp; x3 += xxp * x; } WT py = y * x0, sy = y*y; mom[9] += ((MT)py) * sy; // m03 mom[8] += ((MT)x1) * sy; // m12 mom[7] += ((MT)x2) * y; // m21 mom[6] += x3; // m30 mom[5] += x0 * sy; // m02 mom[4] += x1 * y; // m11 mom[3] += x2; // m20 mom[2] += py; // m01 mom[1] += x1; // m10 mom[0] += x0; // m00 } for( x = 0; x < 10; x++ ) moments[x] = (double)mom[x]; } #endif typedef void (*CvMomentsInTileFunc)(const cv::Mat& img, double* moments); CV_IMPL void cvMoments( const void* array, CvMoments* moments, int binary ) { const int TILE_SIZE = 32; int type, depth, cn, coi = 0; CvMat stub, *mat = (CvMat*)array; CvMomentsInTileFunc func = 0; CvContour contourHeader; CvSeq* contour = 0; CvSeqBlock block; double buf[TILE_SIZE*TILE_SIZE]; uchar nzbuf[TILE_SIZE*TILE_SIZE]; if( CV_IS_SEQ( array )) { contour = (CvSeq*)array; if( !CV_IS_SEQ_POINT_SET( contour )) CV_Error( CV_StsBadArg, "The passed sequence is not a valid contour" ); } if( !moments ) CV_Error( CV_StsNullPtr, "" ); memset( moments, 0, sizeof(*moments)); if( !contour ) { mat = cvGetMat( mat, &stub, &coi ); type = CV_MAT_TYPE( mat->type ); if( type == CV_32SC2 || type == CV_32FC2 ) { contour = cvPointSeqFromMat( CV_SEQ_KIND_CURVE | CV_SEQ_FLAG_CLOSED, mat, &contourHeader, &block ); } } if( contour ) { icvContourMoments( contour, moments ); return; } type = CV_MAT_TYPE( mat->type ); depth = CV_MAT_DEPTH( type ); cn = CV_MAT_CN( type ); cv::Size size = cvGetMatSize( mat ); if( cn > 1 && coi == 0 ) CV_Error( CV_StsBadArg, "Invalid image type" ); if( size.width <= 0 || size.height <= 0 ) return; if( binary || depth == CV_8U ) func = momentsInTile<uchar, int, int>; else if( depth == CV_16U ) func = momentsInTile<ushort, int, int64>; else if( depth == CV_16S ) func = momentsInTile<short, int, int64>; else if( depth == CV_32F ) func = momentsInTile<float, double, double>; else if( depth == CV_64F ) func = momentsInTile<double, double, double>; else CV_Error( CV_StsUnsupportedFormat, "" ); cv::Mat src0(mat); for( int y = 0; y < size.height; y += TILE_SIZE ) { cv::Size tileSize; tileSize.height = std::min(TILE_SIZE, size.height - y); for( int x = 0; x < size.width; x += TILE_SIZE ) { tileSize.width = std::min(TILE_SIZE, size.width - x); cv::Mat src(src0, cv::Rect(x, y, tileSize.width, tileSize.height)); if( coi > 0 ) { cv::Mat tmp(tileSize, depth, buf); int pairs[] = {coi-1, 0}; cv::mixChannels(&src, 1, &tmp, 1, pairs, 1); src = tmp; } if( binary ) { cv::Mat tmp(tileSize, CV_8U, nzbuf); cv::compare( src, 0, tmp, CV_CMP_NE ); src = tmp; } double mom[10]; func( src, mom ); if(binary) { double s = 1./255; for( int k = 0; k < 10; k++ ) mom[k] *= s; } double xm = x * mom[0], ym = y * mom[0]; // accumulate moments computed in each tile // + m00 ( = m00' ) moments->m00 += mom[0]; // + m10 ( = m10' + x*m00' ) moments->m10 += mom[1] + xm; // + m01 ( = m01' + y*m00' ) moments->m01 += mom[2] + ym; // + m20 ( = m20' + 2*x*m10' + x*x*m00' ) moments->m20 += mom[3] + x * (mom[1] * 2 + xm); // + m11 ( = m11' + x*m01' + y*m10' + x*y*m00' ) moments->m11 += mom[4] + x * (mom[2] + ym) + y * mom[1]; // + m02 ( = m02' + 2*y*m01' + y*y*m00' ) moments->m02 += mom[5] + y * (mom[2] * 2 + ym); // + m30 ( = m30' + 3*x*m20' + 3*x*x*m10' + x*x*x*m00' ) moments->m30 += mom[6] + x * (3. * mom[3] + x * (3. * mom[1] + xm)); // + m21 ( = m21' + x*(2*m11' + 2*y*m10' + x*m01' + x*y*m00') + y*m20') moments->m21 += mom[7] + x * (2 * (mom[4] + y * mom[1]) + x * (mom[2] + ym)) + y * mom[3]; // + m12 ( = m12' + y*(2*m11' + 2*x*m01' + y*m10' + x*y*m00') + x*m02') moments->m12 += mom[8] + y * (2 * (mom[4] + x * mom[2]) + y * (mom[1] + xm)) + x * mom[5]; // + m03 ( = m03' + 3*y*m02' + 3*y*y*m01' + y*y*y*m00' ) moments->m03 += mom[9] + y * (3. * mom[5] + y * (3. * mom[2] + ym)); } } icvCompleteMomentState( moments ); } CV_IMPL void cvGetHuMoments( CvMoments * mState, CvHuMoments * HuState ) { if( !mState || !HuState ) CV_Error( CV_StsNullPtr, "" ); double m00s = mState->inv_sqrt_m00, m00 = m00s * m00s, s2 = m00 * m00, s3 = s2 * m00s; double nu20 = mState->mu20 * s2, nu11 = mState->mu11 * s2, nu02 = mState->mu02 * s2, nu30 = mState->mu30 * s3, nu21 = mState->mu21 * s3, nu12 = mState->mu12 * s3, nu03 = mState->mu03 * s3; double t0 = nu30 + nu12; double t1 = nu21 + nu03; double q0 = t0 * t0, q1 = t1 * t1; double n4 = 4 * nu11; double s = nu20 + nu02; double d = nu20 - nu02; HuState->hu1 = s; HuState->hu2 = d * d + n4 * nu11; HuState->hu4 = q0 + q1; HuState->hu6 = d * (q0 - q1) + n4 * t0 * t1; t0 *= q0 - 3 * q1; t1 *= 3 * q0 - q1; q0 = nu30 - 3 * nu12; q1 = 3 * nu21 - nu03; HuState->hu3 = q0 * q0 + q1 * q1; HuState->hu5 = q0 * t0 + q1 * t1; HuState->hu7 = q1 * t0 - q0 * t1; } CV_IMPL double cvGetSpatialMoment( CvMoments * moments, int x_order, int y_order ) { int order = x_order + y_order; if( !moments ) CV_Error( CV_StsNullPtr, "" ); if( (x_order | y_order) < 0 || order > 3 ) CV_Error( CV_StsOutOfRange, "" ); return (&(moments->m00))[order + (order >> 1) + (order > 2) * 2 + y_order]; } CV_IMPL double cvGetCentralMoment( CvMoments * moments, int x_order, int y_order ) { int order = x_order + y_order; if( !moments ) CV_Error( CV_StsNullPtr, "" ); if( (x_order | y_order) < 0 || order > 3 ) CV_Error( CV_StsOutOfRange, "" ); return order >= 2 ? (&(moments->m00))[4 + order * 3 + y_order] : order == 0 ? moments->m00 : 0; } CV_IMPL double cvGetNormalizedCentralMoment( CvMoments * moments, int x_order, int y_order ) { int order = x_order + y_order; double mu = cvGetCentralMoment( moments, x_order, y_order ); double m00s = moments->inv_sqrt_m00; while( --order >= 0 ) mu *= m00s; return mu * m00s * m00s; } namespace cv { Moments::Moments() { m00 = m10 = m01 = m20 = m11 = m02 = m30 = m21 = m12 = m03 = mu20 = mu11 = mu02 = mu30 = mu21 = mu12 = mu03 = nu20 = nu11 = nu02 = nu30 = nu21 = nu12 = nu03 = 0.; } Moments::Moments( double _m00, double _m10, double _m01, double _m20, double _m11, double _m02, double _m30, double _m21, double _m12, double _m03 ) { m00 = _m00; m10 = _m10; m01 = _m01; m20 = _m20; m11 = _m11; m02 = _m02; m30 = _m30; m21 = _m21; m12 = _m12; m03 = _m03; double cx = 0, cy = 0, inv_m00 = 0; if( std::abs(m00) > DBL_EPSILON ) { inv_m00 = 1./m00; cx = m10*inv_m00; cy = m01*inv_m00; } mu20 = m20 - m10*cx; mu11 = m11 - m10*cy; mu02 = m02 - m01*cy; mu30 = m30 - cx*(3*mu20 + cx*m10); mu21 = m21 - cx*(2*mu11 + cx*m01) - cy*mu20; mu12 = m12 - cy*(2*mu11 + cy*m10) - cx*mu02; mu03 = m03 - cy*(3*mu02 + cy*m01); double inv_sqrt_m00 = std::sqrt(std::abs(inv_m00)); double s2 = inv_m00*inv_m00, s3 = s2*inv_sqrt_m00; nu20 = mu20*s2; nu11 = mu11*s2; nu02 = mu02*s2; nu30 = mu30*s3; nu21 = mu21*s3; nu12 = mu12*s3; nu03 = mu03*s3; } Moments::Moments( const CvMoments& m ) { *this = Moments(m.m00, m.m10, m.m01, m.m20, m.m11, m.m02, m.m30, m.m21, m.m12, m.m03); } Moments::operator CvMoments() const { CvMoments m; m.m00 = m00; m.m10 = m10; m.m01 = m01; m.m20 = m20; m.m11 = m11; m.m02 = m02; m.m30 = m30; m.m21 = m21; m.m12 = m12; m.m03 = m03; m.mu20 = mu20; m.mu11 = mu11; m.mu02 = mu02; m.mu30 = mu30; m.mu21 = mu21; m.mu12 = mu12; m.mu03 = mu03; double am00 = std::abs(m00); m.inv_sqrt_m00 = am00 > DBL_EPSILON ? 1./std::sqrt(am00) : 0; return m; } } cv::Moments cv::moments( const Mat& array, bool binaryImage ) { CvMoments om; CvMat _array = array; cvMoments(&_array, &om, binaryImage); return om; } void cv::HuMoments( const Moments& m, double hu[7] ) { double t0 = m.nu30 + m.nu12; double t1 = m.nu21 + m.nu03; double q0 = t0 * t0, q1 = t1 * t1; double n4 = 4 * m.nu11; double s = m.nu20 + m.nu02; double d = m.nu20 - m.nu02; hu[0] = s; hu[1] = d * d + n4 * m.nu11; hu[3] = q0 + q1; hu[5] = d * (q0 - q1) + n4 * t0 * t1; t0 *= q0 - 3 * q1; t1 *= 3 * q0 - q1; q0 = m.nu30 - 3 * m.nu12; q1 = 3 * m.nu21 - m.nu03; hu[2] = q0 * q0 + q1 * q1; hu[4] = q0 * t0 + q1 * t1; hu[6] = q1 * t0 - q0 * t1; } /* End of file. */
Java
## About threex.tweencontrols.js * NOTES: is it position only ? * it gives the currentPosition * it gives the targetPosition * it gives a transitionDelay * targetPosition is dynamic - everytime it changes, test if a tweening is in progress - if current tweening, don't change the delay - else put default delay * which function for the tweening ? ## About size variations * if focus generation changes, the display size will change too * could that be handled at the css level ## About dynamic generation based on wikipedia content * how to query it from wikipedia * query some info from a page * query related pages from a page - build from it * cache all that * how to build it dynamically ## About threex.peppernodestaticcontrols.js ### About controls strategy * i went for a dynamic physics - it seems hard to controls - it is hard to predict too * what about a hardcoded topology - like a given tree portion will be visualized this way - with very little freedom, thus very predictive - a given tree portion got a single visualisation - switch from a portion to another is just a tweening on top - it seems possible and seems to be simpler, what about the details ### Deterministic visualisation * without animation for now, as a simplification assumption. - go for the simplest * focused node at the center * children of a node spread around the parent node - equal angle between each link - so the parent is included in the computation * the length of a link is relative to the child node generation #### Nice... how to code it now * if generation === 1, then position.set(0,0,0) * the world position of children is set by the parent * so setting position of each node is only done on a node if it got children - what is the algo to apply to each node ? - reccursive function: handle current node and forward to all child - to handle a node is finding its position in world space #### Pseudo code for computePosition(node) ``` function computePosition(node){ // special case of focus node position var isFocusedNode = node.parent !== null ? true : false if( isFocusedNode ){ node.position.set(0,0,0) } // if no children, do nothing more if( node.children.length === 0 ) continue; // ... here compute the position of each node // forward to each child node.children.forEach(function(child){ computePosition(child) }) } ``` **how to compute the position of each child ?** * is there a node.parent ? * how many children are there. ``` var linksCount = node.children.length + (node.parent !== null? 1 : 0) var deltaAngle = Math.PI*2 / linksCount var startAngle = 0 if( node.parent !== null ){ var deltaY = node.parent.position.y - node.position.y var deltaX = node.parent.position.x - node.position.x startAngle = Math.atan2(deltaY, deltaX) startAngle += deltaAngle } // compute the radius var radiuses= [0,100, 40] console.assert(node.generation >= 1 && node.generation < radiuses.length ) var radius = radiuses[node.generation] var angle = startAngle node.children.forEach(function(nodeChild){ nodeChild.position.x = Math.cos(angle)*radius nodeChild.position.y = Math.sin(angle)*radius angle += deltaAngle }) ```
Java
/********************************************************************** *< FILE: RealWorldMapUtils.h DESCRIPTION: Utilities for supporting real-world maps size parameters CREATED BY: Scott Morrison HISTORY: created Feb. 1, 2005 *> Copyright (c) 2005, All Rights Reserved. **********************************************************************/ #pragma once //! Class for creating undo record for any class with a "Real-World Map Size" property. //! //! This is a template class where the template parameter T is the type //! which supports the real-world map size property. This class must have //! a method called SetUsePhysicalScaleUVs(BOOL state). template <class T> class RealWorldScaleRecord: public RestoreObj { public: //! Create a real-world map size undo record //! \param[in] pObj - the object which supports the undo/redo toggle //! \param[in] oldState - the state of the real-world map size toggle to restore to. RealWorldScaleRecord(T* pObj, BOOL oldState) { mpObj = pObj; mOldState = oldState; } //! \see RestoreObj::Restore void Restore(int isUndo) { if (isUndo) mpObj->SetUsePhysicalScaleUVs(mOldState); } //! \see RestoreObj::Redo void Redo() { mpObj->SetUsePhysicalScaleUVs(!mOldState); } private: T* mpObj; BOOL mOldState; }; //! The class ID of the real-world scale interface RealWorldMapSizeInterface. #define RWS_INTERFACE Interface_ID(0x9ff44ef, 0x6c050704) //! The unique instance of the real worls map size interface extern CoreExport FPInterfaceDesc gRealWorldMapSizeDesc; //! \brief The commong mix-in interface for setting realWorldMapSize properties on //! objects and modifiers //! //! Details follow here. //! This class is used with multiple inheritence from a class //! which exports a "real-world map size" toggle. The class must //! implement two abstract methods for setting and getting this value. //! The class must implement the following method: //! BaseInterface* GetInterface(Interface_ID id) //! { //! if (id == RWS_INTERFACE) //! return this; //! else //! return FPMixinInterface::GetInterface(id); //! } //! The client class must add this interface the first time ClassDesc::Create() //! is called on the class's class descriptor. //! See maxsdk/samples/objects/boxobj.cpp for an example of the use of this class. class RealWorldMapSizeInterface: public FPMixinInterface { public: //! Gets the state of the real-world map size toggle //! \return the current state of the toggle virtual BOOL GetUsePhysicalScaleUVs() = 0; //! Set the real-world map size toggle //! \param[in] flag - the new value of the toggle virtual void SetUsePhysicalScaleUVs(BOOL flag) = 0; //From FPMixinInterface //! \see FPMixinInterface::GetDesc FPInterfaceDesc* GetDesc() { return &gRealWorldMapSizeDesc; } //! Function published properties for real-world map size enum{ rws_getRealWorldMapSize, rws_setRealWorldMapSize}; // Function Map for Function Publishing System //*********************************** BEGIN_FUNCTION_MAP PROP_FNS (rws_getRealWorldMapSize, GetUsePhysicalScaleUVs, rws_setRealWorldMapSize, SetUsePhysicalScaleUVs, TYPE_BOOL ); END_FUNCTION_MAP }; //@{ //! These methods are used by many objects and modifiers to handle //! the app data required to tag an object as using phyically scaled UVs. //! \param[in] pAnim - The object to query for the real-world app data. //! \return the current value of the flag stored in the app date. CoreExport BOOL GetUsePhysicalScaleUVs(Animatable* pAnim); //! \param[in] pAnim - The object to set for the real-world app data on. //! \param[in] flag - the new value of the toggle to set in the app data. CoreExport void SetUsePhysicalScaleUVs(Animatable* pAnim, BOOL flag); //@} //@{ //! Set/Get the property which says we should use real-world map size by default. //! This value is stored in the market defaults INI file. //! \return the current value of the flag from the market defaults file. CoreExport BOOL GetPhysicalScaleUVsDisabled(); //! Set the value of this flag. //! \param[in] disable - the new value of the flag to store in the market defaults file. CoreExport void SetPhysicalScaleUVsDisabled(BOOL disable); //@}
Java
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Interactive; using Microsoft.VisualStudio.InteractiveWindow; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Operations; using Microsoft.VisualStudio.Utilities; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Interactive { [ExportInteractive(typeof(IExecuteInInteractiveCommandHandler), ContentTypeNames.CSharpContentType)] internal sealed class CSharpInteractiveCommandHandler : InteractiveCommandHandler, IExecuteInInteractiveCommandHandler { private readonly CSharpVsInteractiveWindowProvider _interactiveWindowProvider; private readonly ISendToInteractiveSubmissionProvider _sendToInteractiveSubmissionProvider; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpInteractiveCommandHandler( CSharpVsInteractiveWindowProvider interactiveWindowProvider, ISendToInteractiveSubmissionProvider sendToInteractiveSubmissionProvider, IContentTypeRegistryService contentTypeRegistryService, IEditorOptionsFactoryService editorOptionsFactoryService, IEditorOperationsFactoryService editorOperationsFactoryService) : base(contentTypeRegistryService, editorOptionsFactoryService, editorOperationsFactoryService) { _interactiveWindowProvider = interactiveWindowProvider; _sendToInteractiveSubmissionProvider = sendToInteractiveSubmissionProvider; } protected override ISendToInteractiveSubmissionProvider SendToInteractiveSubmissionProvider => _sendToInteractiveSubmissionProvider; protected override IInteractiveWindow OpenInteractiveWindow(bool focus) => _interactiveWindowProvider.Open(instanceId: 0, focus: focus).InteractiveWindow; } }
Java
class AddIndexes < ActiveRecord::Migration def self.up add_index :authentications, :user_id add_index :games, :black_player_id add_index :games, :white_player_id add_index :games, :current_player_id add_index :games, [:id, :current_player_id, :finished_at] end def self.down remove_index :authentications, :user_id remove_index :games, :black_player_id remove_index :games, :white_player_id remove_index :games, :current_player_id remove_index :games, :column => [:id, :current_player_id, :finished_at] end end
Java
module.exports = { getMeta: function(meta) { var d = meta.metaDescription || meta.description || meta.Description; if (d && d instanceof Array) { d = d[0]; } return { description: d } } };
Java
![preview Long Haul](/preview.jpg) Long Haul is a minimal jekyll theme built with COMPASS / SASS / SUSY and focuses on long form blog plosts. It is meant to used as a starting point for a jekyll blog/website. If you really enjoy Long Haul and want to give me credit somewhere on the send or tweet out your experience with Long Haul and tag me [@brianmaierjr](https://twitter.com/brianmaier). ####[View Demo](http://brianmaierjr.com/long-haul) ## Features - Minimal, Type Focused Design - Built with SASS + COMPASS - Layout with SUSY Grid - SVG Social Icons - Responsive Nav Menu - XML Feed for RSS Readers - Contact Form via Formspree - 5 Post Loop with excerpt on Home Page - Previous / Next Post Navigation - Estimated Reading Time for posts - Stylish Drop Cap on posts - A Better Type Scale for all devices ## Setup 1. [Install Jekyll](http://jekyllrb.com) 2. Fork the [Long Haul repo](http://github.com/brianmaierjr/long-haul) 3. Clone it 4. Install susy `gem install susy` 5. Install normalize `gem install normalize-scss` 6. Run Jekyll `jekyll serve -w` 7. Run `compass watch` 8. Customize! ## Site Settings The main settings can be found inside the `_config.yml` file: - **title:** title of your site - **description:** description of your site - **url:** your url - **paginate:** the amount of posts displayed on homepage - **navigation:** these are the links in the main site navigation - **social** diverse social media usernames (optional) - **google_analytics** Google Analytics key (optional) ## License This is [MIT](LICENSE) with no added caveats, so feel free to use this Jekyll theme on your site without linking back to me or using a disclaimer.
Java
#ifndef _BMP_IO_H #define _BMP_IO_H #include <stdio.h> #include "dot_matrix_font_to_bmp.h" int read_and_alloc_one_bmp(FILE *fp, bmp_file_t *ptrbmp); void free_bmp(bmp_file_t *ptrbmp); int output_bmp(FILE *fp, bmp_file_t *ptrbmp); #endif
Java
/* * Treeview 1.5pre - jQuery plugin to hide and show branches of a tree * * http://bassistance.de/jquery-plugins/jquery-plugin-treeview/ * http://docs.jquery.com/Plugins/Treeview * * Copyright (c) 2007 Jörn Zaefferer * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * * Revision: $Id: jquery.treeview.js 5759 2008-07-01 07:50:28Z joern.zaefferer $ * */ ;(function($) { // TODO rewrite as a widget, removing all the extra plugins $.extend($.fn, { swapClass: function(c1, c2) { var c1Elements = this.filter('.' + c1); this.filter('.' + c2).removeClass(c2).addClass(c1); c1Elements.removeClass(c1).addClass(c2); return this; }, replaceClass: function(c1, c2) { return this.filter('.' + c1).removeClass(c1).addClass(c2).end(); }, hoverClass: function(className) { className = className || "hover"; return this.hover(function() { $(this).addClass(className); }, function() { $(this).removeClass(className); }); }, heightToggle: function(animated, callback) { animated ? this.animate({ height: "toggle" }, animated, callback) : this.each(function(){ jQuery(this)[ jQuery(this).is(":hidden") ? "show" : "hide" ](); if(callback) callback.apply(this, arguments); }); }, heightHide: function(animated, callback) { if (animated) { this.animate({ height: "hide" }, animated, callback); } else { this.hide(); if (callback) this.each(callback); } }, prepareBranches: function(settings) { if (!settings.prerendered) { // mark last tree items this.filter(":last-child:not(ul)").addClass(CLASSES.last); // collapse whole tree, or only those marked as closed, anyway except those marked as open this.filter((settings.collapsed ? "" : "." + CLASSES.closed) + ":not(." + CLASSES.open + ")").find(">ul").hide(); } // return all items with sublists return this.filter(":has(>ul)"); }, applyClasses: function(settings, toggler) { // TODO use event delegation this.filter(":has(>ul):not(:has(>a))").find(">span").unbind("click.treeview").bind("click.treeview", function(event) { // don't handle click events on children, eg. checkboxes if ( this == event.target ) toggler.apply($(this).next()); }).add( $("a", this) ).hoverClass(); if (!settings.prerendered) { // handle closed ones first this.filter(":has(>ul:hidden)") .addClass(CLASSES.expandable) .replaceClass(CLASSES.last, CLASSES.lastExpandable); // handle open ones this.not(":has(>ul:hidden)") .addClass(CLASSES.collapsable) .replaceClass(CLASSES.last, CLASSES.lastCollapsable); // create hitarea if not present var hitarea = this.find("div." + CLASSES.hitarea); if (!hitarea.length) hitarea = this.prepend("<div class=\"" + CLASSES.hitarea + "\"/>").find("div." + CLASSES.hitarea); hitarea.removeClass().addClass(CLASSES.hitarea).each(function() { var classes = ""; $.each($(this).parent().attr("class").split(" "), function() { classes += this + "-hitarea "; }); $(this).addClass( classes ); }) } // apply event to hitarea this.find("div." + CLASSES.hitarea).click( toggler ); }, treeview: function(settings) { settings = $.extend({ cookieId: "treeview" }, settings); if ( settings.toggle ) { var callback = settings.toggle; settings.toggle = function() { return callback.apply($(this).parent()[0], arguments); }; } // factory for treecontroller function treeController(tree, control) { // factory for click handlers function handler(filter) { return function() { // reuse toggle event handler, applying the elements to toggle // start searching for all hitareas toggler.apply( $("div." + CLASSES.hitarea, tree).filter(function() { // for plain toggle, no filter is provided, otherwise we need to check the parent element return filter ? $(this).parent("." + filter).length : true; }) ); return false; }; } // click on first element to collapse tree $("a:eq(0)", control).click( handler(CLASSES.collapsable) ); // click on second to expand tree $("a:eq(1)", control).click( handler(CLASSES.expandable) ); // click on third to toggle tree $("a:eq(2)", control).click( handler() ); } // handle toggle event function toggler() { $(this) .parent() // swap classes for hitarea .find(">.hitarea") .swapClass( CLASSES.collapsableHitarea, CLASSES.expandableHitarea ) .swapClass( CLASSES.lastCollapsableHitarea, CLASSES.lastExpandableHitarea ) .end() // swap classes for parent li .swapClass( CLASSES.collapsable, CLASSES.expandable ) .swapClass( CLASSES.lastCollapsable, CLASSES.lastExpandable ) // find child lists .find( ">ul" ) // toggle them .heightToggle( settings.animated, settings.toggle ); if ( settings.unique ) { $(this).parent() .siblings() // swap classes for hitarea .find(">.hitarea") .replaceClass( CLASSES.collapsableHitarea, CLASSES.expandableHitarea ) .replaceClass( CLASSES.lastCollapsableHitarea, CLASSES.lastExpandableHitarea ) .end() .replaceClass( CLASSES.collapsable, CLASSES.expandable ) .replaceClass( CLASSES.lastCollapsable, CLASSES.lastExpandable ) .find( ">ul" ) .heightHide( settings.animated, settings.toggle ); } } this.data("toggler", toggler); function serialize() { function binary(arg) { return arg ? 1 : 0; } var data = []; branches.each(function(i, e) { data[i] = $(e).is(":has(>ul:visible)") ? 1 : 0; }); $.cookie(settings.cookieId, data.join(""), settings.cookieOptions ); } function deserialize() { var stored = $.cookie(settings.cookieId); if ( stored ) { var data = stored.split(""); branches.each(function(i, e) { $(e).find(">ul")[ parseInt(data[i]) ? "show" : "hide" ](); }); } } // add treeview class to activate styles this.addClass("treeview"); // prepare branches and find all tree items with child lists var branches = this.find("li").prepareBranches(settings); switch(settings.persist) { case "cookie": var toggleCallback = settings.toggle; settings.toggle = function() { serialize(); if (toggleCallback) { toggleCallback.apply(this, arguments); } }; deserialize(); break; case "location": var current = this.find("a").filter(function() { return this.href.toLowerCase() == location.href.toLowerCase(); }); if ( current.length ) { // TODO update the open/closed classes var items = current.addClass("selected").parents("ul, li").add( current.next() ).show(); if (settings.prerendered) { // if prerendered is on, replicate the basic class swapping items.filter("li") .swapClass( CLASSES.collapsable, CLASSES.expandable ) .swapClass( CLASSES.lastCollapsable, CLASSES.lastExpandable ) .find(">.hitarea") .swapClass( CLASSES.collapsableHitarea, CLASSES.expandableHitarea ) .swapClass( CLASSES.lastCollapsableHitarea, CLASSES.lastExpandableHitarea ); } } break; } branches.applyClasses(settings, toggler); // if control option is set, create the treecontroller and show it if ( settings.control ) { treeController(this, settings.control); $(settings.control).show(); } return this; } }); // classes used by the plugin // need to be styled via external stylesheet, see first example $.treeview = {}; var CLASSES = ($.treeview.classes = { open: "open", closed: "closed", expandable: "expandable", expandableHitarea: "expandable-hitarea", lastExpandableHitarea: "lastExpandable-hitarea", collapsable: "collapsable", collapsableHitarea: "collapsable-hitarea", lastCollapsableHitarea: "lastCollapsable-hitarea", lastCollapsable: "lastCollapsable", lastExpandable: "lastExpandable", last: "last", hitarea: "hitarea" }); })(jQuery);
Java
--- title: '如何玩想玩的断恨我和大家一样是一个喜欢举高高的人.' layout: post tags: - bootstrap - simple - css - web --- 我和大家一样是一个喜欢举高高的人.
Java
<?php /* * This file is part of the phpflo\phpflo-fbp package. * * (c) Marc Aschmann <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PhpFlo\Fbp\Loader\Tests; use org\bovigo\vfs\vfsStream; use org\bovigo\vfs\vfsStreamFile; use PhpFlo\Common\Exception\LoaderException; use PhpFlo\Fbp\Loader\Loader; use PhpFlo\Fbp\Test\TestCase; class LoaderTest extends TestCase { /** * @var vfsStreamFile */ private $file; /** * @expectedException \PhpFlo\Common\Exception\LoaderException */ public function testStaticLoadException() { $data = Loader::load('test.yml'); } public function testLoadYamlFile() { $yaml = <<<EOF properties: name: '' initializers: { } processes: ReadFile: component: ReadFile metadata: { label: ReadFile } SplitbyLines: component: SplitStr metadata: { label: SplitStr } Display: component: Output metadata: { label: Output } CountLines: component: Counter metadata: { label: Counter } connections: - src: { process: ReadFile, port: OUT } tgt: { process: SplitbyLines, port: IN } - src: { process: ReadFile, port: ERROR } tgt: { process: Display, port: IN } - src: { process: SplitbyLines, port: OUT } tgt: { process: CountLines, port: IN } - src: { process: CountLines, port: COUNT } tgt: { process: Display, port: IN } EOF; $url = $this->createFile('test.yml', $yaml); $definition = Loader::load($url); $this->assertArrayHasKey('connections', $definition->toArray()); } public function testLoadJsonFile() { $json = <<< EOF { "properties": { "name": "" }, "initializers": [], "processes": { "ReadFile": { "component": "ReadFile", "metadata": { "label": "ReadFile" } }, "SplitbyLines": { "component": "SplitStr", "metadata": { "label": "SplitStr" } }, "Display": { "component": "Output", "metadata": { "label": "Output" } }, "CountLines": { "component": "Counter", "metadata": { "label": "Counter" } } }, "connections": [ { "src": { "process": "ReadFile", "port": "OUT" }, "tgt": { "process": "SplitbyLines", "port": "IN" } }, { "src": { "process": "ReadFile", "port": "ERROR" }, "tgt": { "process": "Display", "port": "IN" } }, { "src": { "process": "SplitbyLines", "port": "OUT" }, "tgt": { "process": "CountLines", "port": "IN" } }, { "src": { "process": "CountLines", "port": "COUNT" }, "tgt": { "process": "Display", "port": "IN" } } ] } EOF; $url = $this->createFile('test.json', $json); $definition = Loader::load($url); $this->assertArrayHasKey('connections', $definition->toArray()); } public function testLoadFbpFile() { $fbp = <<<EOF ReadFile(ReadFile) OUT -> IN SplitbyLines(SplitStr) ReadFile(ReadFile) ERROR -> IN Display(Output) SplitbyLines(SplitStr) OUT -> IN CountLines(Counter) CountLines(Counter) COUNT -> IN Display(Output) EOF; $url = $this->createFile('test.fbp', $fbp); $definition = Loader::load($url); $this->assertArrayHasKey('connections', $definition->toArray()); } /** * @expectedException \PhpFlo\Common\Exception\LoaderException */ public function testLoadEmptyFileWithException() { $uri = $this->createFile('test.fbp', ''); Loader::load($uri); } /** * @expectedException \PhpFlo\Common\Exception\LoaderException */ public function testUnsupportedFileTypeException() { Loader::load('my/file/test.xyz'); } /** * @expectedException \PhpFlo\Common\Exception\LoaderException */ public function testFileNotFoundExcetion() { Loader::load('test.fbp'); } private function createFile($name, $content) { $root = vfsStream::setup(); $this->file = vfsStream::newFile($name)->at($root); $this->file->setContent($content); return $this->file->url(); } }
Java
!((document, $) => { var clip = new Clipboard('.copy-button'); clip.on('success', function(e) { $('.copied').show(); $('.copied').fadeOut(2000); }); })(document, jQuery);
Java
--- title: Christ’s Messages for Then and Now date: 09/01/2019 --- There were more than seven churches in Asia, but Jesus spoke 7 distinctive messages (Rev 2&3) for the churches in that province. This suggests the symbolic significance of these messages for Christians (Rev 1:11, 19, 20). Their meanings apply on three levels: **Historical:** The recipients were 7 churches in prosperous cities of 1st Century Asia where emperor worship had been set in as a token of their loyalty to Rome. Participation in this and other pagan religious rituals became compulsory. The Christians who refused to participate faced trials and at times martyrdom. **Prophetic Application:** Revelation is a prophetic book, the messages are of prophetic character as well. The spiritual conditions in the 7 churches coincide with the spiritual conditions of God’s church in different historical periods and are a panoramic survey of the spiritual state of Christianity from the 1st century to the end of the world. **Universal Application:** Just as the entire book was sent as one letter that was to be read in every church (Rev 1:11; 22:16) so the seven messages also contain lessons that can apply to Christians in every age. While the general characteristic of Christianity today is Laodicean, some Christians may identify with the characteristics of the other churches.
Java
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ .yui-h-slider, .yui-v-slider { position: relative; } .yui-h-slider .yui-slider-thumb, .yui-v-slider .yui-slider-thumb { position: absolute; cursor: default; } .yui-skin-sam .yui-h-slider { background: url(bg-h.gif) no-repeat 5px 0; height: 28px; width: 228px; } .yui-skin-sam .yui-h-slider .yui-slider-thumb { top: 4px; } .yui-skin-sam .yui-v-slider { background: url(bg-v.gif) no-repeat 12px 0; height: 228px; width: 48px; } .cke_uicolor_picker .yui-picker-panel { background: #e3e3e3; border-color: #888; } .cke_uicolor_picker .yui-picker-panel .hd { background-color: #ccc; font-size: 100%; line-height: 100%; border: 1px solid #e3e3e3; font-weight: bold; overflow: hidden; padding: 6px; color: #000; } .cke_uicolor_picker .yui-picker-panel .bd { background: #e8e8e8; margin: 1px; height: 200px; } .cke_uicolor_picker .yui-picker-panel .ft { background: #e8e8e8; margin: 1px; padding: 1px; } .cke_uicolor_picker .yui-picker { position: relative; } .cke_uicolor_picker .yui-picker-hue-thumb { cursor: default; width: 18px; height: 18px; top: -8px; left: -2px; z-index: 9; position: absolute; } .cke_uicolor_picker .yui-picker-hue-bg { -moz-outline: none; outline: 0 none; position: absolute; left: 200px; height: 183px; width: 14px; background: url(hue_bg.png) no-repeat; top: 4px; } .cke_uicolor_picker .yui-picker-bg { -moz-outline: none; outline: 0 none; position: absolute; top: 4px; left: 4px; height: 182px; width: 182px; background-color: #F00; background-image: url(picker_mask.png); } *html .cke_uicolor_picker .yui-picker-bg { background-image: none; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src = 'picker_mask.png', sizingMethod = 'scale'); } .cke_uicolor_picker .yui-picker-mask { position: absolute; z-index: 1; top: 0; left: 0; } .cke_uicolor_picker .yui-picker-thumb { cursor: default; width: 11px; height: 11px; z-index: 9; position: absolute; top: -4px; left: -4px; } .cke_uicolor_picker .yui-picker-swatch { position: absolute; left: 240px; top: 4px; height: 60px; width: 55px; border: 1px solid #888; } .cke_uicolor_picker .yui-picker-websafe-swatch { position: absolute; left: 304px; top: 4px; height: 24px; width: 24px; border: 1px solid #888; } .cke_uicolor_picker .yui-picker-controls { position: absolute; top: 72px; left: 226px; font: 1em monospace; } .cke_uicolor_picker .yui-picker-controls .hd { background: transparent; border-width: 0 !important; } .cke_uicolor_picker .yui-picker-controls .bd { height: 100px; border-width: 0 !important; } .cke_uicolor_picker .yui-picker-controls ul { float: left; padding: 0 2px 0 0; margin: 0; } .cke_uicolor_picker .yui-picker-controls li { padding: 2px; list-style: none; margin: 0; } .cke_uicolor_picker .yui-picker-controls input { font-size: .85em; width: 2.4em; } .cke_uicolor_picker .yui-picker-hex-controls { clear: both; padding: 2px; } .cke_uicolor_picker .yui-picker-hex-controls input { width: 4.6em; } .cke_uicolor_picker .yui-picker-controls a { font: 1em arial, helvetica, clean, sans-serif; display: block; *display: inline-block; padding: 0; color: #000; }
Java
<!DOCTYPE html> <html> <head> <title>Centering grid content</title> <meta content="text/html; charset=utf-8" http-equiv="content-type"> <meta name="description" content="Centering grid content" /> <meta name="keywords" content="javascript, dynamic, grid, layout, jquery plugin, flex layouts"/> <link rel="icon" href="favicon.ico" type="image/x-icon" /> <link rel="stylesheet" type="text/css" href="css/style.css" /> <script type="text/javascript" src="js/jquery-1.10.2.min.js"></script> <script type="text/javascript" src="../freewall.js"></script> <script type="text/javascript" src="../plugin/centering.js"></script> <style type="text/css"> .free-wall { margin: 15px; } </style> </head> <body> <div class='header'> <div class="clearfix"> <div class="float-left"> <h1><a href="http://vnjs.net/www/project/freewall/">Free Wall</a></h1> <div class='target'>Creating dynamic grid layouts.</div> </div> </div> </div> <div id="freewall" class="free-wall"> <div class="brick size32"> <div class='cover'> <h2>Centering grid content</h2> </div> </div> <div class="brick size12 add-more"> <div class='cover'> <h2>Add more block</h2> </div> </div> </div> <script type="text/javascript"> var colour = [ "rgb(142, 68, 173)", "rgb(243, 156, 18)", "rgb(211, 84, 0)", "rgb(0, 106, 63)", "rgb(41, 128, 185)", "rgb(192, 57, 43)", "rgb(135, 0, 0)", "rgb(39, 174, 96)" ]; $(".brick").each(function() { this.style.backgroundColor = colour[colour.length * Math.random() << 0]; }); $(function() { var wall = new Freewall("#freewall"); wall.reset({ selector: '.brick', animate: true, cellW: 160, cellH: 160, delay: 50, onResize: function() { wall.fitWidth(); } }); wall.fitWidth(); var temp = '<div class="brick {size}" style="background-color: {color}"><div class="cover"></div></div>'; var size = "size23 size22 size21 size13 size12 size11".split(" "); $(".add-more").click(function() { var html = temp.replace('{size}', size[size.length * Math.random() << 0]) .replace('{color}', colour[colour.length * Math.random() << 0]); wall.prepend(html); }); }); </script> </body> </html>
Java
var binary = require('node-pre-gyp'); var path = require('path'); var binding_path = binary.find(path.resolve(path.join(__dirname,'./package.json'))); var binding = require(binding_path); var Stream = require('stream').Stream, inherits = require('util').inherits; function Snapshot() {} Snapshot.prototype.getHeader = function() { return { typeId: this.typeId, uid: this.uid, title: this.title } } /** * @param {Snapshot} other * @returns {Object} */ Snapshot.prototype.compare = function(other) { var selfHist = nodesHist(this), otherHist = nodesHist(other), keys = Object.keys(selfHist).concat(Object.keys(otherHist)), diff = {}; keys.forEach(function(key) { if (key in diff) return; var selfCount = selfHist[key] || 0, otherCount = otherHist[key] || 0; diff[key] = otherCount - selfCount; }); return diff; }; function ExportStream() { Stream.Transform.call(this); this._transform = function noTransform(chunk, encoding, done) { done(null, chunk); } } inherits(ExportStream, Stream.Transform); /** * @param {Stream.Writable|function} dataReceiver * @returns {Stream|undefined} */ Snapshot.prototype.export = function(dataReceiver) { dataReceiver = dataReceiver || new ExportStream(); var toStream = dataReceiver instanceof Stream, chunks = toStream ? null : []; function onChunk(chunk, len) { if (toStream) dataReceiver.write(chunk); else chunks.push(chunk); } function onDone() { if (toStream) dataReceiver.end(); else dataReceiver(null, chunks.join('')); } this.serialize(onChunk, onDone); return toStream ? dataReceiver : undefined; }; function nodes(snapshot) { var n = snapshot.nodesCount, i, nodes = []; for (i = 0; i < n; i++) { nodes[i] = snapshot.getNode(i); } return nodes; }; function nodesHist(snapshot) { var objects = {}; nodes(snapshot).forEach(function(node){ var key = node.type === "Object" ? node.name : node.type; objects[key] = objects[node.name] || 0; objects[key]++; }); return objects; }; function CpuProfile() {} CpuProfile.prototype.getHeader = function() { return { typeId: this.typeId, uid: this.uid, title: this.title } } CpuProfile.prototype.export = function(dataReceiver) { dataReceiver = dataReceiver || new ExportStream(); var toStream = dataReceiver instanceof Stream; var error, result; try { result = JSON.stringify(this); } catch (err) { error = err; } process.nextTick(function() { if (toStream) { if (error) { dataReceiver.emit('error', error); } dataReceiver.end(result); } else { dataReceiver(error, result); } }); return toStream ? dataReceiver : undefined; }; var startTime, endTime; var activeProfiles = []; var profiler = { /*HEAP PROFILER API*/ get snapshots() { return binding.heap.snapshots; }, takeSnapshot: function(name, control) { var snapshot = binding.heap.takeSnapshot.apply(null, arguments); snapshot.__proto__ = Snapshot.prototype; snapshot.title = name; return snapshot; }, getSnapshot: function(index) { var snapshot = binding.heap.snapshots[index]; if (!snapshot) return; snapshot.__proto__ = Snapshot.prototype; return snapshot; }, findSnapshot: function(uid) { var snapshot = binding.heap.snapshots.filter(function(snapshot) { return snapshot.uid == uid; })[0]; if (!snapshot) return; snapshot.__proto__ = Snapshot.prototype; return snapshot; }, deleteAllSnapshots: function () { binding.heap.snapshots.forEach(function(snapshot) { snapshot.delete(); }); }, startTrackingHeapObjects: binding.heap.startTrackingHeapObjects, stopTrackingHeapObjects: binding.heap.stopTrackingHeapObjects, getHeapStats: binding.heap.getHeapStats, getObjectByHeapObjectId: binding.heap.getObjectByHeapObjectId, /*CPU PROFILER API*/ get profiles() { return binding.cpu.profiles; }, startProfiling: function(name, recsamples) { if (activeProfiles.length == 0 && typeof process._startProfilerIdleNotifier == "function") process._startProfilerIdleNotifier(); name = name || ""; if (activeProfiles.indexOf(name) < 0) activeProfiles.push(name) startTime = Date.now(); binding.cpu.startProfiling(name, recsamples); }, stopProfiling: function(name) { var index = activeProfiles.indexOf(name); if (name && index < 0) return; var profile = binding.cpu.stopProfiling(name); endTime = Date.now(); profile.__proto__ = CpuProfile.prototype; if (!profile.startTime) profile.startTime = startTime; if (!profile.endTime) profile.endTime = endTime; if (name) activeProfiles.splice(index, 1); else activeProfiles.length = activeProfiles.length - 1; if (activeProfiles.length == 0 && typeof process._stopProfilerIdleNotifier == "function") process._stopProfilerIdleNotifier(); return profile; }, getProfile: function(index) { return binding.cpu.profiles[index]; }, findProfile: function(uid) { var profile = binding.cpu.profiles.filter(function(profile) { return profile.uid == uid; })[0]; return profile; }, deleteAllProfiles: function() { binding.cpu.profiles.forEach(function(profile) { profile.delete(); }); } }; module.exports = profiler; process.profiler = profiler;
Java
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2019 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. /** * Server/client environment: argument handling, config file parsing, * thread wrappers, startup time */ #ifndef BITCOIN_UTIL_SYSTEM_H #define BITCOIN_UTIL_SYSTEM_H #if defined(HAVE_CONFIG_H) #include <config/bitcoin-config.h> #endif #include <attributes.h> #include <compat.h> #include <compat/assumptions.h> #include <fs.h> #include <logging.h> #include <sync.h> #include <tinyformat.h> #include <util/memory.h> #include <util/threadnames.h> #include <util/time.h> #include <exception> #include <map> #include <set> #include <stdint.h> #include <string> #include <utility> #include <vector> #include <boost/thread/condition_variable.hpp> // for boost::thread_interrupted // Application startup time (used for uptime calculation) int64_t GetStartupTime(); extern const char * const BITCOIN_CONF_FILENAME; void SetupEnvironment(); bool SetupNetworking(); template<typename... Args> bool error(const char* fmt, const Args&... args) { LogPrintf("ERROR: %s\n", tfm::format(fmt, args...)); return false; } void PrintExceptionContinue(const std::exception *pex, const char* pszThread); bool FileCommit(FILE *file); bool TruncateFile(FILE *file, unsigned int length); int RaiseFileDescriptorLimit(int nMinFD); void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length); bool RenameOver(fs::path src, fs::path dest); bool LockDirectory(const fs::path& directory, const std::string lockfile_name, bool probe_only=false); void UnlockDirectory(const fs::path& directory, const std::string& lockfile_name); bool DirIsWritable(const fs::path& directory); bool CheckDiskSpace(const fs::path& dir, uint64_t additional_bytes = 0); /** Release all directory locks. This is used for unit testing only, at runtime * the global destructor will take care of the locks. */ void ReleaseDirectoryLocks(); bool TryCreateDirectories(const fs::path& p); fs::path GetDefaultDataDir(); // The blocks directory is always net specific. const fs::path &GetBlocksDir(); const fs::path &GetDataDir(bool fNetSpecific = true); // Return true if -datadir option points to a valid directory or is not specified. bool CheckDataDirOption(); /** Tests only */ void ClearDatadirCache(); fs::path GetConfigFile(const std::string& confPath); #ifdef WIN32 fs::path GetSpecialFolderPath(int nFolder, bool fCreate = true); #endif #if HAVE_SYSTEM void runCommand(const std::string& strCommand); #endif /** * Most paths passed as configuration arguments are treated as relative to * the datadir if they are not absolute. * * @param path The path to be conditionally prefixed with datadir. * @param net_specific Forwarded to GetDataDir(). * @return The normalized path. */ fs::path AbsPathForConfigVal(const fs::path& path, bool net_specific = true); inline bool IsSwitchChar(char c) { #ifdef WIN32 return c == '-' || c == '/'; #else return c == '-'; #endif } enum class OptionsCategory { OPTIONS, CONNECTION, WALLET, WALLET_DEBUG_TEST, ZMQ, DEBUG_TEST, CHAINPARAMS, NODE_RELAY, BLOCK_CREATION, RPC, GUI, COMMANDS, REGISTER_COMMANDS, HIDDEN // Always the last option to avoid printing these in the help }; struct SectionInfo { std::string m_name; std::string m_file; int m_line; }; class ArgsManager { public: enum Flags { NONE = 0x00, // Boolean options can accept negation syntax -noOPTION or -noOPTION=1 ALLOW_BOOL = 0x01, ALLOW_INT = 0x02, ALLOW_STRING = 0x04, ALLOW_ANY = ALLOW_BOOL | ALLOW_INT | ALLOW_STRING, DEBUG_ONLY = 0x100, /* Some options would cause cross-contamination if values for * mainnet were used while running on regtest/testnet (or vice-versa). * Setting them as NETWORK_ONLY ensures that sharing a config file * between mainnet and regtest/testnet won't cause problems due to these * parameters by accident. */ NETWORK_ONLY = 0x200, }; protected: friend class ArgsManagerHelper; struct Arg { std::string m_help_param; std::string m_help_text; unsigned int m_flags; }; mutable CCriticalSection cs_args; std::map<std::string, std::vector<std::string>> m_override_args GUARDED_BY(cs_args); std::map<std::string, std::vector<std::string>> m_config_args GUARDED_BY(cs_args); std::string m_network GUARDED_BY(cs_args); std::set<std::string> m_network_only_args GUARDED_BY(cs_args); std::map<OptionsCategory, std::map<std::string, Arg>> m_available_args GUARDED_BY(cs_args); std::list<SectionInfo> m_config_sections GUARDED_BY(cs_args); NODISCARD bool ReadConfigStream(std::istream& stream, const std::string& filepath, std::string& error, bool ignore_invalid_keys = false); public: ArgsManager(); /** * Select the network in use */ void SelectConfigNetwork(const std::string& network); NODISCARD bool ParseParameters(int argc, const char* const argv[], std::string& error); NODISCARD bool ReadConfigFiles(std::string& error, bool ignore_invalid_keys = false); /** * Log warnings for options in m_section_only_args when * they are specified in the default section but not overridden * on the command line or in a network-specific section in the * config file. */ const std::set<std::string> GetUnsuitableSectionOnlyArgs() const; /** * Log warnings for unrecognized section names in the config file. */ const std::list<SectionInfo> GetUnrecognizedSections() const; /** * Return a vector of strings of the given argument * * @param strArg Argument to get (e.g. "-foo") * @return command-line arguments */ std::vector<std::string> GetArgs(const std::string& strArg) const; /** * Return true if the given argument has been manually set * * @param strArg Argument to get (e.g. "-foo") * @return true if the argument has been set */ bool IsArgSet(const std::string& strArg) const; /** * Return true if the argument was originally passed as a negated option, * i.e. -nofoo. * * @param strArg Argument to get (e.g. "-foo") * @return true if the argument was passed negated */ bool IsArgNegated(const std::string& strArg) const; /** * Return string argument or default value * * @param strArg Argument to get (e.g. "-foo") * @param strDefault (e.g. "1") * @return command-line argument or default value */ std::string GetArg(const std::string& strArg, const std::string& strDefault) const; /** * Return integer argument or default value * * @param strArg Argument to get (e.g. "-foo") * @param nDefault (e.g. 1) * @return command-line argument (0 if invalid number) or default value */ int64_t GetArg(const std::string& strArg, int64_t nDefault) const; /** * Return boolean argument or default value * * @param strArg Argument to get (e.g. "-foo") * @param fDefault (true or false) * @return command-line argument or default value */ bool GetBoolArg(const std::string& strArg, bool fDefault) const; /** * Set an argument if it doesn't already have a value * * @param strArg Argument to set (e.g. "-foo") * @param strValue Value (e.g. "1") * @return true if argument gets set, false if it already had a value */ bool SoftSetArg(const std::string& strArg, const std::string& strValue); /** * Set a boolean argument if it doesn't already have a value * * @param strArg Argument to set (e.g. "-foo") * @param fValue Value (e.g. false) * @return true if argument gets set, false if it already had a value */ bool SoftSetBoolArg(const std::string& strArg, bool fValue); // Forces an arg setting. Called by SoftSetArg() if the arg hasn't already // been set. Also called directly in testing. void ForceSetArg(const std::string& strArg, const std::string& strValue); /** * Looks for -regtest, -testnet and returns the appropriate BIP70 chain name. * @return CBaseChainParams::MAIN by default; raises runtime error if an invalid combination is given. */ std::string GetChainName() const; /** * Add argument */ void AddArg(const std::string& name, const std::string& help, unsigned int flags, const OptionsCategory& cat); /** * Add many hidden arguments */ void AddHiddenArgs(const std::vector<std::string>& args); /** * Clear available arguments */ void ClearArgs() { LOCK(cs_args); m_available_args.clear(); m_network_only_args.clear(); } /** * Get the help string */ std::string GetHelpMessage() const; /** * Return Flags for known arg. * Return ArgsManager::NONE for unknown arg. */ unsigned int FlagsOfKnownArg(const std::string& key) const; }; extern ArgsManager gArgs; /** * @return true if help has been requested via a command-line arg */ bool HelpRequested(const ArgsManager& args); /** Add help options to the args manager */ void SetupHelpOptions(ArgsManager& args); /** * Format a string to be used as group of options in help messages * * @param message Group name (e.g. "RPC server options:") * @return the formatted string */ std::string HelpMessageGroup(const std::string& message); /** * Format a string to be used as option description in help messages * * @param option Option message (e.g. "-rpcuser=<user>") * @param message Option description (e.g. "Username for JSON-RPC connections") * @return the formatted string */ std::string HelpMessageOpt(const std::string& option, const std::string& message); /** * Return the number of cores available on the current system. * @note This does count virtual cores, such as those provided by HyperThreading. */ int GetNumCores(); /** * .. and a wrapper that just calls func once */ template <typename Callable> void TraceThread(const char* name, Callable func) { util::ThreadRename(name); try { LogPrintf("%s thread start\n", name); func(); LogPrintf("%s thread exit\n", name); } catch (const boost::thread_interrupted&) { LogPrintf("%s thread interrupt\n", name); throw; } catch (const std::exception& e) { PrintExceptionContinue(&e, name); throw; } catch (...) { PrintExceptionContinue(nullptr, name); throw; } } std::string CopyrightHolders(const std::string& strPrefix); /** * On platforms that support it, tell the kernel the calling thread is * CPU-intensive and non-interactive. See SCHED_BATCH in sched(7) for details. * * @return The return value of sched_setschedule(), or 1 on systems without * sched_setschedule(). */ int ScheduleBatchPriority(); namespace util { //! Simplification of std insertion template <typename Tdst, typename Tsrc> inline void insert(Tdst& dst, const Tsrc& src) { dst.insert(dst.begin(), src.begin(), src.end()); } template <typename TsetT, typename Tsrc> inline void insert(std::set<TsetT>& dst, const Tsrc& src) { dst.insert(src.begin(), src.end()); } #ifdef WIN32 class WinCmdLineArgs { public: WinCmdLineArgs(); ~WinCmdLineArgs(); std::pair<int, char**> get(); private: int argc; char** argv; std::vector<std::string> args; }; #endif } // namespace util #endif // BITCOIN_UTIL_SYSTEM_H
Java
<?php /* * This file is part of the Sonata Project package. * * (c) Thomas Rabaix <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sonata\AdminBundle\DependencyInjection; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\HttpKernel\DependencyInjection\Extension; /** * Class AbstractSonataAdminExtension. * * @author Thomas Rabaix <[email protected]> */ abstract class AbstractSonataAdminExtension extends Extension { /** * Fix template configuration. * * @param array $configs * @param ContainerBuilder $container * @param array $defaultSonataDoctrineConfig * * @return array */ protected function fixTemplatesConfiguration(array $configs, ContainerBuilder $container, array $defaultSonataDoctrineConfig = array()) { $defaultConfig = array( 'templates' => array( 'types' => array( 'list' => array( 'array' => 'SonataAdminBundle:CRUD:list_array.html.twig', 'boolean' => 'SonataAdminBundle:CRUD:list_boolean.html.twig', 'date' => 'SonataAdminBundle:CRUD:list_date.html.twig', 'time' => 'SonataAdminBundle:CRUD:list_time.html.twig', 'datetime' => 'SonataAdminBundle:CRUD:list_datetime.html.twig', 'text' => 'SonataAdminBundle:CRUD:list_string.html.twig', 'textarea' => 'SonataAdminBundle:CRUD:list_string.html.twig', 'email' => 'SonataAdminBundle:CRUD:list_string.html.twig', 'trans' => 'SonataAdminBundle:CRUD:list_trans.html.twig', 'string' => 'SonataAdminBundle:CRUD:list_string.html.twig', 'smallint' => 'SonataAdminBundle:CRUD:list_string.html.twig', 'bigint' => 'SonataAdminBundle:CRUD:list_string.html.twig', 'integer' => 'SonataAdminBundle:CRUD:list_string.html.twig', 'decimal' => 'SonataAdminBundle:CRUD:list_string.html.twig', 'identifier' => 'SonataAdminBundle:CRUD:list_string.html.twig', 'currency' => 'SonataAdminBundle:CRUD:list_currency.html.twig', 'percent' => 'SonataAdminBundle:CRUD:list_percent.html.twig', 'choice' => 'SonataAdminBundle:CRUD:list_choice.html.twig', 'url' => 'SonataAdminBundle:CRUD:list_url.html.twig', 'html' => 'SonataAdminBundle:CRUD:list_html.html.twig', ), 'show' => array( 'array' => 'SonataAdminBundle:CRUD:show_array.html.twig', 'boolean' => 'SonataAdminBundle:CRUD:show_boolean.html.twig', 'date' => 'SonataAdminBundle:CRUD:show_date.html.twig', 'time' => 'SonataAdminBundle:CRUD:show_time.html.twig', 'datetime' => 'SonataAdminBundle:CRUD:show_datetime.html.twig', 'text' => 'SonataAdminBundle:CRUD:base_show_field.html.twig', 'trans' => 'SonataAdminBundle:CRUD:show_trans.html.twig', 'string' => 'SonataAdminBundle:CRUD:base_show_field.html.twig', 'smallint' => 'SonataAdminBundle:CRUD:base_show_field.html.twig', 'bigint' => 'SonataAdminBundle:CRUD:base_show_field.html.twig', 'integer' => 'SonataAdminBundle:CRUD:base_show_field.html.twig', 'decimal' => 'SonataAdminBundle:CRUD:base_show_field.html.twig', 'currency' => 'SonataAdminBundle:CRUD:show_currency.html.twig', 'percent' => 'SonataAdminBundle:CRUD:show_percent.html.twig', 'choice' => 'SonataAdminBundle:CRUD:show_choice.html.twig', 'url' => 'SonataAdminBundle:CRUD:show_url.html.twig', 'html' => 'SonataAdminBundle:CRUD:show_html.html.twig', ), ), ), ); // let's add some magic, only overwrite template if the SonataIntlBundle is enabled $bundles = $container->getParameter('kernel.bundles'); if (isset($bundles['SonataIntlBundle'])) { $defaultConfig['templates']['types']['list'] = array_merge($defaultConfig['templates']['types']['list'], array( 'date' => 'SonataIntlBundle:CRUD:list_date.html.twig', 'datetime' => 'SonataIntlBundle:CRUD:list_datetime.html.twig', 'smallint' => 'SonataIntlBundle:CRUD:list_decimal.html.twig', 'bigint' => 'SonataIntlBundle:CRUD:list_decimal.html.twig', 'integer' => 'SonataIntlBundle:CRUD:list_decimal.html.twig', 'decimal' => 'SonataIntlBundle:CRUD:list_decimal.html.twig', 'currency' => 'SonataIntlBundle:CRUD:list_currency.html.twig', 'percent' => 'SonataIntlBundle:CRUD:list_percent.html.twig', )); $defaultConfig['templates']['types']['show'] = array_merge($defaultConfig['templates']['types']['show'], array( 'date' => 'SonataIntlBundle:CRUD:show_date.html.twig', 'datetime' => 'SonataIntlBundle:CRUD:show_datetime.html.twig', 'smallint' => 'SonataIntlBundle:CRUD:show_decimal.html.twig', 'bigint' => 'SonataIntlBundle:CRUD:show_decimal.html.twig', 'integer' => 'SonataIntlBundle:CRUD:show_decimal.html.twig', 'decimal' => 'SonataIntlBundle:CRUD:show_decimal.html.twig', 'currency' => 'SonataIntlBundle:CRUD:show_currency.html.twig', 'percent' => 'SonataIntlBundle:CRUD:show_percent.html.twig', )); } if (!empty($defaultSonataDoctrineConfig)) { $defaultConfig = array_merge_recursive($defaultConfig, $defaultSonataDoctrineConfig); } array_unshift($configs, $defaultConfig); return $configs; } }
Java
<?php namespace Druidfi; class Envs { const ENV_DEVELOPMENT = 'development'; const ENV_TESTING = 'testing'; const ENV_STAGING = 'staging'; const ENV_PRODUCTION = 'production'; const ERROR_NOT_VALID = 'Error: env "%s" is not valid! Please use one of the following: %s'; /** * Get error message for invalid env * * @param $env * * @return string */ public static function getNotValidErrorMessage($env) { return sprintf(self::ERROR_NOT_VALID, $env, join(', ', self::getValidEnvs())); } /** * Get list of valid environments * * @return array Valid environments */ public static function getValidEnvs() { return [ self::ENV_DEVELOPMENT, self::ENV_TESTING, self::ENV_STAGING, self::ENV_PRODUCTION, ]; } /** * Check if given env is valid * * @param $env * * @return bool */ public static function isValidEnv($env) { return in_array($env, self::getValidEnvs()); } }
Java
// This file was generated based on 'C:\ProgramData\Uno\Packages\Fuse.Reactive\0.18.8\$.uno'. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Fuse.Behavior.h> namespace g{namespace Fuse{namespace Reactive{struct Binding;}}} namespace g{namespace Fuse{struct Node;}} namespace g{ namespace Fuse{ namespace Reactive{ // public abstract class Binding :450 // { struct Binding_type : ::g::Fuse::Behavior_type { void(*fp_NewValue)(::g::Fuse::Reactive::Binding*, uObject*); }; Binding_type* Binding_typeof(); void Binding__ctor_1_fn(Binding* __this, uString* key); void Binding__get_Key_fn(Binding* __this, uString** __retval); void Binding__set_Key_fn(Binding* __this, uString* value); void Binding__get_Node_fn(Binding* __this, ::g::Fuse::Node** __retval); void Binding__OnRooted_fn(Binding* __this, ::g::Fuse::Node* n); void Binding__OnUnrooted_fn(Binding* __this, ::g::Fuse::Node* n); struct Binding : ::g::Fuse::Behavior { uStrong<uObject*> _pathSubscription; uStrong<uString*> _Key; void ctor_1(uString* key); uString* Key(); void Key(uString* value); void NewValue(uObject* obj) { (((Binding_type*)__type)->fp_NewValue)(this, obj); } ::g::Fuse::Node* Node(); }; // } }}} // ::g::Fuse::Reactive
Java
from itertools import imap, chain def set_name(name, f): try: f.__pipetools__name__ = name except (AttributeError, UnicodeEncodeError): pass return f def get_name(f): from pipetools.main import Pipe pipetools_name = getattr(f, '__pipetools__name__', None) if pipetools_name: return pipetools_name() if callable(pipetools_name) else pipetools_name if isinstance(f, Pipe): return repr(f) return f.__name__ if hasattr(f, '__name__') else repr(f) def repr_args(*args, **kwargs): return ', '.join(chain( imap('{0!r}'.format, args), imap('{0[0]}={0[1]!r}'.format, kwargs.iteritems())))
Java
# gl-geometry [![experimental](http://badges.github.io/stability-badges/dist/experimental.svg)](http://github.com/badges/stability-badges) A flexible wrapper for [gl-vao](http://github.com/mikolalysenko/gl-vao) and [gl-buffer](http://github.com/mikolalysenko/gl-buffer) that you can use to set up renderable WebGL geometries from a variety of different formats. ## Usage ## [![NPM](https://nodei.co/npm/gl-geometry.png)](https://nodei.co/npm/gl-geometry/) ### geom = createGeometry(gl) ### Creates a new geometry attached to the WebGL canvas context `gl`. ### geom.attr(name, values[, opt]) ### Define a new attribute value, for example using a simplicial complex: ``` javascript var createGeometry = require('gl-geometry') var bunny = require('bunny') var geom = createGeometry(gl) .attr('positions', bunny) ``` The following vertex formats are supported and will be normalized: * Arrays of arrays, e.g. `[[0, 0, 0], [1, 0, 0], [1, 1, 0]]`. * Flat arrays, e.g. `[0, 0, 0, 1, 0, 0, 1, 1, 0]`. * [Typed arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays), preferably a `Float32Array`. * 1-dimensional [ndarrays](http://github.com/mikolalysenko/ndarray). * [simplicial complexes](https://github.com/mikolalysenko/simplicial-complex), i.e. an object with a `positions` array and a `cells` array. The former is a list of unique vertices in the mesh (if you've used three.js, think `THREE.Vector3`), and the latter is an index mapping these vertices to faces (`THREE.Face3`) in the mesh. It looks something like this: ``` json { "positions": [ [0.0, 0.0, 0.0], [1.5, 0.0, 0.0], [1.5, 1.5, 0.0], [0.0, 1.5, 0.0] ], "cells": [ [0, 1, 2], [1, 2, 3] ] } ``` You can specify `opt.size` for the vertex size, defaults to 3. ### geom.faces(values[, opt]) ### Pass a simplicial complex's `cells` property here in any of the above formats to use it as your index when drawing the geometry. For example: ``` javascript var createGeometry = require('gl-geometry') var bunny = require('bunny') bunny.normals = normals.vertexNormals( bunny.cells , bunny.positions ) var geom = createGeometry(gl) .attr('positions', bunny.positions) .attr('normals', bunny.normals) .faces(bunny.cells) ``` You can specify `opt.size` for the cell size, defaults to 3. ### geom.bind([shader]) ### Binds the underlying [VAO](https://github.com/gl-modules/gl-vao) – this must be called before calling `geom.draw`. Optionally, you can pass in a [gl-shader](http://github.com/gl-modules/gl-shader) or [glslify](http://github.com/chrisdickinson/glslify) shader instance to automatically set up your attribute locations for you. ### geom.draw(mode, start, stop) ### Draws the geometry to the screen using the currently bound shader. Optionally, you can pass in the drawing mode, which should be one of the following: * `gl.POINTS` * `gl.LINES` * `gl.LINE_STRIP` * `gl.LINE_LOOP` * `gl.TRIANGLES` * `gl.TRIANGLE_STRIP` * `gl.TRIANGLE_FAN` The default value is `gl.TRIANGLES`. You're also able to pass in a `start` and `stop` range for the points you want to render, just the same as you would with `gl.drawArrays` or `gl.drawElements`. ### geom.unbind() ### Unbinds the underlying VAO. This *must* be done when you're finished drawing, unless you're binding to another gl-geometry or gl-vao instance. ### geom.dispose() ### Disposes the underlying element and array buffers, as well as the VAO. ## See Also * [ArrayBuffer and Typed Arrays](https://www.khronos.org/registry/webgl/specs/1.0/#5.13) * [The WebGL Context](https://www.khronos.org/registry/webgl/specs/1.0/#5.14) * [simplicial-complex](http://github.com/mikolalysenko/simplicial-complex) * [ndarray](http://github.com/mikolalysenko/ndarray) * [gl-shader](http://github.com/mikolalysenko/gl-shader) * [gl-buffer](http://github.com/mikolalysenko/gl-buffer) * [gl-vao](http://github.com/mikolalysenko/gl-vao) ## License MIT. See [LICENSE.md](http://github.com/hughsk/is-typedarray/blob/master/LICENSE.md) for details.
Java
--- title: СТРАЖДАННЯ І ПРИКЛАД ХРИСТА date: 01/05/2017 --- ### СТРАЖДАННЯ І ПРИКЛАД ХРИСТА `Прочитайте уривок 1 Петра 3:13-22. Як християни повинні відповідати тим, хто завдає їм страждань через їхню віру? Який зв’язок між стражданнями Ісуса та стражданнями віруючих за свою віру?` Коли Петро каже: «А коли й терпите через праведність, то ви – блаженні» (1 Петра 3:14), він повторює слова Ісуса: «Блаженні переслідувані за праведність» (Матв. 5:10). Потім апостол застерігає, що християнам не слід боятися своїх кривдників, натомість вони повинні освячувати (шанувати) Христа як Господа у своїх серцях (див. 1 Петра 3:15). Таке визнання Ісуса в серці допоможе подолати страх, який викликають їхні вороги. Далі Петро пише, що християнам необхідно завжди бути готовими дати відповідь про свою надію з лагідністю і шанобливістю (див. 1 Петра 3:15, 16). Апостол наполягає: християни повинні бути впевнені, що не дають іншим приводу для звинувачень на свою адресу. Їм слід мати «добру совість» (1 Петра 3:16). Це важливо, оскільки в такому разі обвинувачі християнина будуть посоромлені його непорочним життям. Звичайно, немає жодної заслуги в стражданні за злочин (див. 1 Петра 3:17). Саме страждання за добру справу, за правильний учинок справляють позитивний вплив. «Бо краще, якщо на те Божа воля, страждати, будучи доброчинцем, аніж злочинцем» (1 Петра 3:17). Петро наводить Ісуса як приклад. Сам Христос постраждав за Свою праведність; святість і чистота Його життя були постійним докором для Його ненависників. Якщо хтось і постраждав за свої добрі діла, так це Ісус. Однак Його страждання також здобули єдиний засіб спасіння. Він помер замість грішників («праведний за неправедних», 1 Петра 3:18), щоб віруючі в Нього отримали обітницю вічного життя. `Чи страждали ви колись через свій правильний вчинок? Розкажіть про цей досвід. Чи навчив він вас, що значить бути християнином та відображати характер Христа?`
Java
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"/><!-- using block title in layout.dt--><!-- using block ddox.defs in ddox.layout.dt--><!-- using block ddox.title in ddox.layout.dt--> <title>Class FilePath</title> <link rel="stylesheet" type="text/css" href="../../styles/ddox.css"/> <link rel="stylesheet" href="../../prettify/prettify.css" type="text/css"/> <script type="text/javascript" src="../../scripts/jquery.js">/**/</script> <script type="text/javascript" src="../../prettify/prettify.js">/**/</script> <script type="text/javascript" src="../../scripts/ddox.js">/**/</script> </head> <body onload="prettyPrint(); setupDdox();"> <nav id="main-nav"><!-- using block navigation in layout.dt--> <ul class="tree-view"> <li class="collapsed tree-view"> <a href="#" class="package">components</a> <ul class="tree-view"> <li> <a href="../../components/animation.html" class=" module">animation</a> </li> <li> <a href="../../components/assetanimation.html" class=" module">assetanimation</a> </li> <li> <a href="../../components/assets.html" class=" module">assets</a> </li> <li> <a href="../../components/camera.html" class=" module">camera</a> </li> <li> <a href="../../components/icomponent.html" class=" module">icomponent</a> </li> <li> <a href="../../components/lights.html" class=" module">lights</a> </li> <li> <a href="../../components/material.html" class=" module">material</a> </li> <li> <a href="../../components/mesh.html" class=" module">mesh</a> </li> <li> <a href="../../components/userinterface.html" class=" module">userinterface</a> </li> </ul> </li> <li class="collapsed tree-view"> <a href="#" class="package">core</a> <ul class="tree-view"> <li> <a href="../../core/dgame.html" class=" module">dgame</a> </li> <li> <a href="../../core/gameobject.html" class=" module">gameobject</a> </li> <li> <a href="../../core/gameobjectcollection.html" class=" module">gameobjectcollection</a> </li> <li> <a href="../../core/prefabs.html" class=" module">prefabs</a> </li> <li> <a href="../../core/properties.html" class=" module">properties</a> </li> <li> <a href="../../core/reflection.html" class=" module">reflection</a> </li> <li> <a href="../../core/scene.html" class=" module">scene</a> </li> </ul> </li> <li class="collapsed tree-view"> <a href="#" class="package">graphics</a> <ul class="tree-view"> <li class="collapsed tree-view"> <a href="#" class="package">adapters</a> <ul class="tree-view"> <li> <a href="../../graphics/adapters/adapter.html" class=" module">adapter</a> </li> <li> <a href="../../graphics/adapters/linux.html" class=" module">linux</a> </li> <li> <a href="../../graphics/adapters/mac.html" class=" module">mac</a> </li> <li> <a href="../../graphics/adapters/win32.html" class=" module">win32</a> </li> </ul> </li> <li class="collapsed tree-view"> <a href="#" class="package">shaders</a> <ul class="tree-view"> <li class="collapsed tree-view"> <a href="#" class="package">glsl</a> <ul class="tree-view"> <li> <a href="../../graphics/shaders/glsl/ambientlight.html" class=" module">ambientlight</a> </li> <li> <a href="../../graphics/shaders/glsl/animatedgeometry.html" class=" module">animatedgeometry</a> </li> <li> <a href="../../graphics/shaders/glsl/directionallight.html" class=" module">directionallight</a> </li> <li> <a href="../../graphics/shaders/glsl/geometry.html" class=" module">geometry</a> </li> <li> <a href="../../graphics/shaders/glsl/pointlight.html" class=" module">pointlight</a> </li> <li> <a href="../../graphics/shaders/glsl/userinterface.html" class=" module">userinterface</a> </li> </ul> </li> <li> <a href="../../graphics/shaders/glsl.html" class=" module">glsl</a> </li> <li> <a href="../../graphics/shaders/shaders.html" class=" module">shaders</a> </li> </ul> </li> <li> <a href="../../graphics/adapters.html" class=" module">adapters</a> </li> <li> <a href="../../graphics/graphics.html" class=" module">graphics</a> </li> <li> <a href="../../graphics/shaders.html" class=" module">shaders</a> </li> </ul> </li> <li class=" tree-view"> <a href="#" class="package">utility</a> <ul class="tree-view"> <li> <a href="../../utility/awesomium.html" class=" module">awesomium</a> </li> <li> <a href="../../utility/concurrency.html" class=" module">concurrency</a> </li> <li> <a href="../../utility/config.html" class=" module">config</a> </li> <li> <a href="../../utility/filepath.html" class="selected module">filepath</a> </li> <li> <a href="../../utility/input.html" class=" module">input</a> </li> <li> <a href="../../utility/output.html" class=" module">output</a> </li> <li> <a href="../../utility/string.html" class=" module">string</a> </li> <li> <a href="../../utility/time.html" class=" module">time</a> </li> </ul> </li> <li> <a href="../../components.html" class=" module">components</a> </li> <li> <a href="../../core.html" class=" module">core</a> </li> <li> <a href="../../graphics.html" class=" module">graphics</a> </li> <li> <a href="../../utility.html" class=" module">utility</a> </li> </ul> <noscript> <p style="color: red">The search functionality needs JavaScript enabled</p> </noscript> <div id="symbolSearchPane" style="display: none"> <p> <input id="symbolSearch" type="text" placeholder="Search for symbols" onchange="performSymbolSearch(24);" onkeypress="this.onchange();" onpaste="this.onchange();" oninput="this.onchange();"/> </p> <ul id="symbolSearchResults" style="display: none"></ul> <script type="application/javascript" src="../../symbols.js"></script> <script type="application/javascript"> //<![CDATA[ var symbolSearchRootDir = "../../"; $('#symbolSearchPane').show(); //]]> </script> </div> </nav> <div id="main-contents"> <h1>Class FilePath</h1><!-- using block body in layout.dt--><!-- using block ddox.description in ddox.layout.dt--> <p> A class which stores default resource paths, and handles path manipulation. </p> <section> </section> <section> <h2>Inherits from</h2> <ul> <li> <code class="prettyprint lang-d"><code class="prettyprint lang-d">Object</code></code> (base class) </li> </ul> </section><!-- using block ddox.sections in ddox.layout.dt--> <!-- using block ddox.members in ddox.layout.dt--> <section> <h2>Constructors</h2> <table> <col class="caption"/> <tr> <th>Name</th> <th>Description</th> </tr> <tr> <td> <a href="../../utility/filepath/FilePath.this.html" class="public"> <code>this</code> </a> </td> <td> Create an instance based on a given file <a href="../../utility/filepath/FilePath.this.html#path"><code class="prettyprint lang-d">path</code></a>. </td> </tr> </table> </section> <section> <h2>Fields</h2> <table> <col class="caption"/> <tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr> <tr> <td> <a href="../../utility/filepath/FilePath.ResourceHome.html" class="public"><code>ResourceHome</code></a> </td> <td><code class="prettyprint lang-d">string</code></td> <td> The path to the resources home folder. </td> </tr> </table> </section> <section> <h2>Properties</h2> <table> <col class="caption"/> <tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr> <tr> <td> <a href="../../utility/filepath/FilePath.baseFileName.html" class="public property"><code>baseFileName</code></a> <span class="tableEntryAnnotation">[get]</span> </td> <td><code class="prettyprint lang-d">string</code></td> <td> The name of the file without its <a href="../../utility/filepath/FilePath.extension.html"><code class="prettyprint lang-d">extension</code></a>. </td> </tr> <tr> <td> <a href="../../utility/filepath/FilePath.directory.html" class="public property"><code>directory</code></a> <span class="tableEntryAnnotation">[get]</span> </td> <td><code class="prettyprint lang-d">string</code></td> <td> The path to the <code class="prettyprint lang-d">directory</code> containing the file. </td> </tr> <tr> <td> <a href="../../utility/filepath/FilePath.extension.html" class="public property"><code>extension</code></a> <span class="tableEntryAnnotation">[get]</span> </td> <td><code class="prettyprint lang-d">string</code></td> <td> The extensino of the file. </td> </tr> <tr> <td> <a href="../../utility/filepath/FilePath.fileName.html" class="public property"><code>fileName</code></a> <span class="tableEntryAnnotation">[get]</span> </td> <td><code class="prettyprint lang-d">string</code></td> <td> The name of the file with its <a href="../../utility/filepath/FilePath.extension.html"><code class="prettyprint lang-d">extension</code></a>. </td> </tr> <tr> <td> <a href="../../utility/filepath/FilePath.fullPath.html" class="public property"><code>fullPath</code></a> <span class="tableEntryAnnotation">[get]</span> </td> <td><code class="prettyprint lang-d">string</code></td> <td> The full path to the file. </td> </tr> <tr> <td> <a href="../../utility/filepath/FilePath.relativePath.html" class="public property"><code>relativePath</code></a> <span class="tableEntryAnnotation">[get]</span> </td> <td><code class="prettyprint lang-d">string</code></td> <td> The relative path from the executable to the file. </td> </tr> </table> </section> <section> <h2>Methods</h2> <table> <col class="caption"/> <tr> <th>Name</th> <th>Description</th> </tr> <tr> <td> <a href="../../utility/filepath/FilePath.getContents.html" class="public"> <code>getContents</code> </a> </td> <td> TODO </td> </tr> <tr> <td> <a href="../../utility/filepath/FilePath.scanDirectory.html" class="public"> <code>scanDirectory</code> </a> </td> <td> Get all files in a given <a href="../../utility/filepath/FilePath.directory.html"><code class="prettyprint lang-d">directory</code></a>. </td> </tr> <tr> <td> <a href="../../utility/filepath/FilePath.toFile.html" class="public"> <code>toFile</code> </a> </td> <td> Converts to a std.stdio.File </td> </tr> </table> </section> <section> <h2>Enums</h2> <table> <col class="caption"/> <tr> <th>Name</th> <th>Description</th> </tr> <tr> <td> <a href="../../utility/filepath/FilePath.Resources.html" class="public"> <code>Resources</code> </a> </td> <td> Paths to the different resource files. </td> </tr> </table> </section> <section> <h2>Authors</h2><!-- using block ddox.authors in ddox.layout.dt--> </section> <section> <h2>Copyright</h2><!-- using block ddox.copyright in ddox.layout.dt--> </section> <section> <h2>License</h2><!-- using block ddox.license in ddox.layout.dt--> </section> </div> </body> </html>
Java
{% if page.meta_description %} {% assign meta_description = page.meta_description %} {% else %} {% assign meta_description = page.content | strip_html | strip_newlines | truncate: 150 %} {% endif %} <head prefix="og: http://ogp.me/ns# fb: http://ogp.me/ns/fb# website: http://ogp.me/ns/website#"> <title>{{ page.meta_title }}</title> <meta charset="utf-8" /> <meta name="keywords" content="{{ page.keywords | default: site.keywords }}" /> <meta name="description" content="{{ meta_description }}" /> <meta name="author" content="{{ page.author | default: site.author }}" /> <meta name="robots" content="index, follow" /> <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1.0" /> <link rel="canonical" href="{{ page.url | replace:'index.html','' | prepend: site.url }}" /> <!-- Verifications --> <meta name="p:domain_verify" content="{{ site.pinterest_verify }}" /> <meta name="msvalidate.01" content="{{ site.bing_verify }}" /> <!-- Facebook Open Graph Info --> <meta property="og:type" content="website" /> <meta property="og:url" content="{{ page.url | replace:'index.html','' | prepend: site.url }}" /> <meta property="og:title" content="{{ meta_title }}" /> <meta property="og:description" content="{{ meta_description | truncate: 160 }}" /> <meta property="fb:app_id" content="{{ site.fb_app_id }}" /> <meta property="fb:admins" content="{{ site.fb_admins }}" /> <meta property="fb:profile_id" content="{{ site.fb_profile_id }}" /> <meta property="og:image" content="{{ site.images | prepend: site.url }}/{{ page.og_image | default: site.og_image }}" /> <meta property="og:image:type" content="image/jpeg" /> <meta property="og:image:width" content="1500" /> <meta property="og:image:height" content="785" /> <!-- Favicons etc --> <link rel="apple-touch-icon" sizes="57x57" href="{{ site.images }}/favicons/apple-icon-57x57.png" /> <link rel="apple-touch-icon" sizes="60x60" href="{{ site.images }}/favicons/apple-icon-60x60.png" /> <link rel="apple-touch-icon" sizes="72x72" href="{{ site.images }}/favicons/apple-icon-72x72.png" /> <link rel="apple-touch-icon" sizes="76x76" href="{{ site.images }}/favicons/apple-icon-76x76.png" /> <link rel="apple-touch-icon" sizes="114x114" href="{{ site.images }}/favicons/apple-icon-114x114.png" /> <link rel="apple-touch-icon" sizes="120x120" href="{{ site.images }}/favicons/apple-icon-120x120.png" /> <link rel="apple-touch-icon" sizes="144x144" href="{{ site.images }}/favicons/apple-icon-144x144.png" /> <link rel="apple-touch-icon" sizes="152x152" href="{{ site.images }}/favicons/apple-icon-152x152.png" /> <link rel="apple-touch-icon" sizes="180x180" href="{{ site.images }}/favicons/apple-icon-180x180.png" /> <link rel="icon" type="image/png" sizes="192x192" href="{{ site.images }}/favicons/android-icon-192x192.png" /> <link rel="icon" type="image/png" sizes="32x32" href="{{ site.images }}/favicons/favicon-32x32.png" /> <link rel="icon" type="image/png" sizes="96x96" href="{{ site.images }}/favicons/favicon-96x96.png" /> <link rel="icon" type="image/png" sizes="16x16" href="{{ site.images }}/favicons/favicon-16x16.png" /> <link rel="manifest" href="{{ site.images }}/favicons/manifest.json" /> <meta name="msapplication-TileColor" content="#ffffff" /> <meta name="msapplication-TileImage" content="{{ site.images }}/favicons/ms-icon-144x144.png" /> <meta name="theme-color" content="#ffffff" /> <script> // Add a class to the html element if JS is enabled (function(html) { html.classList.add('js'); })(document.documentElement); </script> <link href="{{ site.assets }}/css/main.css?v=@version@" rel="stylesheet" /> <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,700,700i|Playfair+Display:900" rel="stylesheet" /> </head>
Java
--- layout: media title: "In front of book shelves" excerpt: "PaperFaces portrait of @mr_craig drawn with Paper by 53 on an iPad." image: feature: paperfaces-mr-craig-twitter-lg.jpg thumb: paperfaces-mr-craig-twitter-150.jpg category: paperfaces tags: [portrait, illustration, paper by 53] --- PaperFaces portrait of [@mr_craig](http://twitter.com/mr_craig). {% include paperfaces-boilerplate.html %}
Java
using System; using NPoco; using Umbraco.Cms.Infrastructure.Persistence.DatabaseAnnotations; namespace Umbraco.Cms.Infrastructure.Persistence.Dtos { [TableName(TableName)] [ExplicitColumns] [PrimaryKey("Id")] internal class TwoFactorLoginDto { public const string TableName = Cms.Core.Constants.DatabaseSchema.Tables.TwoFactorLogin; [Column("id")] [PrimaryKeyColumn] public int Id { get; set; } [Column("userOrMemberKey")] [Index(IndexTypes.NonClustered)] public Guid UserOrMemberKey { get; set; } [Column("providerName")] [Length(400)] [NullSetting(NullSetting = NullSettings.NotNull)] [Index(IndexTypes.UniqueNonClustered, ForColumns = "providerName,userOrMemberKey", Name = "IX_" + TableName + "_ProviderName")] public string ProviderName { get; set; } [Column("secret")] [Length(400)] [NullSetting(NullSetting = NullSettings.NotNull)] public string Secret { get; set; } } }
Java
/** * webdriverio * https://github.com/Camme/webdriverio * * A WebDriver module for nodejs. Either use the super easy help commands or use the base * Webdriver wire protocol commands. Its totally inspired by jellyfishs webdriver, but the * goal is to make all the webdriver protocol items available, as near the original as possible. * * Copyright (c) 2013 Camilo Tapia <[email protected]> * Licensed under the MIT license. * * Contributors: * Dan Jenkins <[email protected]> * Christian Bromann <[email protected]> * Vincent Voyer <[email protected]> */ import WebdriverIO from './lib/webdriverio' import Multibrowser from './lib/multibrowser' import ErrorHandler from './lib/utils/ErrorHandler' import getImplementedCommands from './lib/helpers/getImplementedCommands' import pkg from './package.json' const IMPLEMENTED_COMMANDS = getImplementedCommands() const VERSION = pkg.version let remote = function (options = {}, modifier) { /** * initialise monad */ let wdio = WebdriverIO(options, modifier) /** * build prototype: commands */ for (let commandName of Object.keys(IMPLEMENTED_COMMANDS)) { wdio.lift(commandName, IMPLEMENTED_COMMANDS[commandName]) } let prototype = wdio() prototype.defer.resolve() return prototype } let multiremote = function (options) { let multibrowser = new Multibrowser() for (let browserName of Object.keys(options)) { multibrowser.addInstance( browserName, remote(options[browserName], multibrowser.getInstanceModifier()) ) } return remote(options, multibrowser.getModifier()) } export { remote, multiremote, VERSION, ErrorHandler }
Java
<?php /* * This file is part of the Elcodi package. * * Copyright (c) 2014-2015 Elcodi.com * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * Feel free to edit as you please, and have fun. * * @author Marc Morera <[email protected]> * @author Aldo Chiecchia <[email protected]> * @author Elcodi Team <[email protected]> */ namespace Elcodi\Component\Currency\Adapter\CurrencyExchangeRatesProvider; use GuzzleHttp\Client; use Elcodi\Component\Currency\Adapter\CurrencyExchangeRatesProvider\Interfaces\CurrencyExchangeRatesProviderAdapterInterface; /** * Class YahooFinanceProviderAdapter */ class YahooFinanceProviderAdapter implements CurrencyExchangeRatesProviderAdapterInterface { /** * @var Client * * Client */ private $client; /** * Service constructor * * @param Client $client Guzzle client for requests */ public function __construct(Client $client) { $this->client = $client; } /** * Get the latest exchange rates. * * This method will take in account always that the base currency is USD, * and the result must complain this format. * * [ * "EUR" => "1,78342784", * "YEN" => "0,67438268", * ... * ] * * @return array exchange rates */ public function getExchangeRates() { $exchangeRates = []; $response = $this ->client ->get( 'http://finance.yahoo.com/webservice/v1/symbols/allcurrencies/quote', [ 'query' => [ 'format' => 'json', ], ] ) ->json(); foreach ($response['list']['resources'] as $resource) { $fields = $resource['resource']['fields']; $symbol = str_replace('=X', '', $fields['symbol']); $exchangeRates[$symbol] = (float) $fields['price']; } return $exchangeRates; } }
Java
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Unicode Manipulation: GLib Reference Manual</title> <meta name="generator" content="DocBook XSL Stylesheets V1.78.1"> <link rel="home" href="index.html" title="GLib Reference Manual"> <link rel="up" href="glib-utilities.html" title="GLib Utilities"> <link rel="prev" href="glib-Character-Set-Conversion.html" title="Character Set Conversion"> <link rel="next" href="glib-Base64-Encoding.html" title="Base64 Encoding"> <meta name="generator" content="GTK-Doc V1.24 (XML mode)"> <link rel="stylesheet" href="style.css" type="text/css"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table class="navigation" id="top" width="100%" summary="Navigation header" cellpadding="2" cellspacing="5"><tr valign="middle"> <td width="100%" align="left" class="shortcuts"> <a href="#" class="shortcut">Top</a><span id="nav_description">  <span class="dim">|</span>  <a href="#glib-Unicode-Manipulation.description" class="shortcut">Description</a></span> </td> <td><a accesskey="h" href="index.html"><img src="home.png" width="16" height="16" border="0" alt="Home"></a></td> <td><a accesskey="u" href="glib-utilities.html"><img src="up.png" width="16" height="16" border="0" alt="Up"></a></td> <td><a accesskey="p" href="glib-Character-Set-Conversion.html"><img src="left.png" width="16" height="16" border="0" alt="Prev"></a></td> <td><a accesskey="n" href="glib-Base64-Encoding.html"><img src="right.png" width="16" height="16" border="0" alt="Next"></a></td> </tr></table> <div class="refentry"> <a name="glib-Unicode-Manipulation"></a><div class="titlepage"></div> <div class="refnamediv"><table width="100%"><tr> <td valign="top"> <h2><span class="refentrytitle"><a name="glib-Unicode-Manipulation.top_of_page"></a>Unicode Manipulation</span></h2> <p>Unicode Manipulation — functions operating on Unicode characters and UTF-8 strings</p> </td> <td class="gallery_image" valign="top" align="right"></td> </tr></table></div> <div class="refsect1"> <a name="glib-Unicode-Manipulation.functions"></a><h2>Functions</h2> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="functions_return"> <col class="functions_name"> </colgroup> <tbody> <tr> <td class="function_type"> <a class="link" href="glib-Basic-Types.html#gboolean" title="gboolean"><span class="returnvalue">gboolean</span></a> </td> <td class="function_name"> <a class="link" href="glib-Unicode-Manipulation.html#g-unichar-validate" title="g_unichar_validate ()">g_unichar_validate</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="glib-Basic-Types.html#gboolean" title="gboolean"><span class="returnvalue">gboolean</span></a> </td> <td class="function_name"> <a class="link" href="glib-Unicode-Manipulation.html#g-unichar-isalnum" title="g_unichar_isalnum ()">g_unichar_isalnum</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="glib-Basic-Types.html#gboolean" title="gboolean"><span class="returnvalue">gboolean</span></a> </td> <td class="function_name"> <a class="link" href="glib-Unicode-Manipulation.html#g-unichar-isalpha" title="g_unichar_isalpha ()">g_unichar_isalpha</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="glib-Basic-Types.html#gboolean" title="gboolean"><span class="returnvalue">gboolean</span></a> </td> <td class="function_name"> <a class="link" href="glib-Unicode-Manipulation.html#g-unichar-iscntrl" title="g_unichar_iscntrl ()">g_unichar_iscntrl</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="glib-Basic-Types.html#gboolean" title="gboolean"><span class="returnvalue">gboolean</span></a> </td> <td class="function_name"> <a class="link" href="glib-Unicode-Manipulation.html#g-unichar-isdefined" title="g_unichar_isdefined ()">g_unichar_isdefined</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="glib-Basic-Types.html#gboolean" title="gboolean"><span class="returnvalue">gboolean</span></a> </td> <td class="function_name"> <a class="link" href="glib-Unicode-Manipulation.html#g-unichar-isdigit" title="g_unichar_isdigit ()">g_unichar_isdigit</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="glib-Basic-Types.html#gboolean" title="gboolean"><span class="returnvalue">gboolean</span></a> </td> <td class="function_name"> <a class="link" href="glib-Unicode-Manipulation.html#g-unichar-isgraph" title="g_unichar_isgraph ()">g_unichar_isgraph</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="glib-Basic-Types.html#gboolean" title="gboolean"><span class="returnvalue">gboolean</span></a> </td> <td class="function_name"> <a class="link" href="glib-Unicode-Manipulation.html#g-unichar-islower" title="g_unichar_islower ()">g_unichar_islower</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="glib-Basic-Types.html#gboolean" title="gboolean"><span class="returnvalue">gboolean</span></a> </td> <td class="function_name"> <a class="link" href="glib-Unicode-Manipulation.html#g-unichar-ismark" title="g_unichar_ismark ()">g_unichar_ismark</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="glib-Basic-Types.html#gboolean" title="gboolean"><span class="returnvalue">gboolean</span></a> </td> <td class="function_name"> <a class="link" href="glib-Unicode-Manipulation.html#g-unichar-isprint" title="g_unichar_isprint ()">g_unichar_isprint</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="glib-Basic-Types.html#gboolean" title="gboolean"><span class="returnvalue">gboolean</span></a> </td> <td class="function_name"> <a class="link" href="glib-Unicode-Manipulation.html#g-unichar-ispunct" title="g_unichar_ispunct ()">g_unichar_ispunct</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="glib-Basic-Types.html#gboolean" title="gboolean"><span class="returnvalue">gboolean</span></a> </td> <td class="function_name"> <a class="link" href="glib-Unicode-Manipulation.html#g-unichar-isspace" title="g_unichar_isspace ()">g_unichar_isspace</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="glib-Basic-Types.html#gboolean" title="gboolean"><span class="returnvalue">gboolean</span></a> </td> <td class="function_name"> <a class="link" href="glib-Unicode-Manipulation.html#g-unichar-istitle" title="g_unichar_istitle ()">g_unichar_istitle</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="glib-Basic-Types.html#gboolean" title="gboolean"><span class="returnvalue">gboolean</span></a> </td> <td class="function_name"> <a class="link" href="glib-Unicode-Manipulation.html#g-unichar-isupper" title="g_unichar_isupper ()">g_unichar_isupper</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="glib-Basic-Types.html#gboolean" title="gboolean"><span class="returnvalue">gboolean</span></a> </td> <td class="function_name"> <a class="link" href="glib-Unicode-Manipulation.html#g-unichar-isxdigit" title="g_unichar_isxdigit ()">g_unichar_isxdigit</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="glib-Basic-Types.html#gboolean" title="gboolean"><span class="returnvalue">gboolean</span></a> </td> <td class="function_name"> <a class="link" href="glib-Unicode-Manipulation.html#g-unichar-iswide" title="g_unichar_iswide ()">g_unichar_iswide</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="glib-Basic-Types.html#gboolean" title="gboolean"><span class="returnvalue">gboolean</span></a> </td> <td class="function_name"> <a class="link" href="glib-Unicode-Manipulation.html#g-unichar-iswide-cjk" title="g_unichar_iswide_cjk ()">g_unichar_iswide_cjk</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="glib-Basic-Types.html#gboolean" title="gboolean"><span class="returnvalue">gboolean</span></a> </td> <td class="function_name"> <a class="link" href="glib-Unicode-Manipulation.html#g-unichar-iszerowidth" title="g_unichar_iszerowidth ()">g_unichar_iszerowidth</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="glib-Unicode-Manipulation.html#gunichar" title="gunichar"><span class="returnvalue">gunichar</span></a> </td> <td class="function_name"> <a class="link" href="glib-Unicode-Manipulation.html#g-unichar-toupper" title="g_unichar_toupper ()">g_unichar_toupper</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="glib-Unicode-Manipulation.html#gunichar" title="gunichar"><span class="returnvalue">gunichar</span></a> </td> <td class="function_name"> <a class="link" href="glib-Unicode-Manipulation.html#g-unichar-tolower" title="g_unichar_tolower ()">g_unichar_tolower</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="glib-Unicode-Manipulation.html#gunichar" title="gunichar"><span class="returnvalue">gunichar</span></a> </td> <td class="function_name"> <a class="link" href="glib-Unicode-Manipulation.html#g-unichar-totitle" title="g_unichar_totitle ()">g_unichar_totitle</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="glib-Basic-Types.html#gint" title="gint"><span class="returnvalue">gint</span></a> </td> <td class="function_name"> <a class="link" href="glib-Unicode-Manipulation.html#g-unichar-digit-value" title="g_unichar_digit_value ()">g_unichar_digit_value</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="glib-Basic-Types.html#gint" title="gint"><span class="returnvalue">gint</span></a> </td> <td class="function_name"> <a class="link" href="glib-Unicode-Manipulation.html#g-unichar-xdigit-value" title="g_unichar_xdigit_value ()">g_unichar_xdigit_value</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="glib-Basic-Types.html#gboolean" title="gboolean"><span class="returnvalue">gboolean</span></a> </td> <td class="function_name"> <a class="link" href="glib-Unicode-Manipulation.html#g-unichar-compose" title="g_unichar_compose ()">g_unichar_compose</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="glib-Basic-Types.html#gboolean" title="gboolean"><span class="returnvalue">gboolean</span></a> </td> <td class="function_name"> <a class="link" href="glib-Unicode-Manipulation.html#g-unichar-decompose" title="g_unichar_decompose ()">g_unichar_decompose</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="glib-Basic-Types.html#gsize" title="gsize"><span class="returnvalue">gsize</span></a> </td> <td class="function_name"> <a class="link" href="glib-Unicode-Manipulation.html#g-unichar-fully-decompose" title="g_unichar_fully_decompose ()">g_unichar_fully_decompose</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="glib-Unicode-Manipulation.html#GUnicodeType" title="enum GUnicodeType"><span class="returnvalue">GUnicodeType</span></a> </td> <td class="function_name"> <a class="link" href="glib-Unicode-Manipulation.html#g-unichar-type" title="g_unichar_type ()">g_unichar_type</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="glib-Unicode-Manipulation.html#GUnicodeBreakType" title="enum GUnicodeBreakType"><span class="returnvalue">GUnicodeBreakType</span></a> </td> <td class="function_name"> <a class="link" href="glib-Unicode-Manipulation.html#g-unichar-break-type" title="g_unichar_break_type ()">g_unichar_break_type</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="glib-Basic-Types.html#gint" title="gint"><span class="returnvalue">gint</span></a> </td> <td class="function_name"> <a class="link" href="glib-Unicode-Manipulation.html#g-unichar-combining-class" title="g_unichar_combining_class ()">g_unichar_combining_class</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <span class="returnvalue">void</span> </td> <td class="function_name"> <a class="link" href="glib-Unicode-Manipulation.html#g-unicode-canonical-ordering" title="g_unicode_canonical_ordering ()">g_unicode_canonical_ordering</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="glib-Unicode-Manipulation.html#gunichar" title="gunichar"><span class="returnvalue">gunichar</span></a> * </td> <td class="function_name"> <a class="link" href="glib-Unicode-Manipulation.html#g-unicode-canonical-decomposition" title="g_unicode_canonical_decomposition ()">g_unicode_canonical_decomposition</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="glib-Basic-Types.html#gboolean" title="gboolean"><span class="returnvalue">gboolean</span></a> </td> <td class="function_name"> <a class="link" href="glib-Unicode-Manipulation.html#g-unichar-get-mirror-char" title="g_unichar_get_mirror_char ()">g_unichar_get_mirror_char</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="glib-Unicode-Manipulation.html#GUnicodeScript" title="enum GUnicodeScript"><span class="returnvalue">GUnicodeScript</span></a> </td> <td class="function_name"> <a class="link" href="glib-Unicode-Manipulation.html#g-unichar-get-script" title="g_unichar_get_script ()">g_unichar_get_script</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="glib-Unicode-Manipulation.html#GUnicodeScript" title="enum GUnicodeScript"><span class="returnvalue">GUnicodeScript</span></a> </td> <td class="function_name"> <a class="link" href="glib-Unicode-Manipulation.html#g-unicode-script-from-iso15924" title="g_unicode_script_from_iso15924 ()">g_unicode_script_from_iso15924</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="glib-Basic-Types.html#guint32" title="guint32"><span class="returnvalue">guint32</span></a> </td> <td class="function_name"> <a class="link" href="glib-Unicode-Manipulation.html#g-unicode-script-to-iso15924" title="g_unicode_script_to_iso15924 ()">g_unicode_script_to_iso15924</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="define_keyword">#define</td> <td class="function_name"> <a class="link" href="glib-Unicode-Manipulation.html#g-utf8-next-char" title="g_utf8_next_char()">g_utf8_next_char</a><span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="glib-Unicode-Manipulation.html#gunichar" title="gunichar"><span class="returnvalue">gunichar</span></a> </td> <td class="function_name"> <a class="link" href="glib-Unicode-Manipulation.html#g-utf8-get-char" title="g_utf8_get_char ()">g_utf8_get_char</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="glib-Unicode-Manipulation.html#gunichar" title="gunichar"><span class="returnvalue">gunichar</span></a> </td> <td class="function_name"> <a class="link" href="glib-Unicode-Manipulation.html#g-utf8-get-char-validated" title="g_utf8_get_char_validated ()">g_utf8_get_char_validated</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="glib-Basic-Types.html#gchar" title="gchar"><span class="returnvalue">gchar</span></a> * </td> <td class="function_name"> <a class="link" href="glib-Unicode-Manipulation.html#g-utf8-offset-to-pointer" title="g_utf8_offset_to_pointer ()">g_utf8_offset_to_pointer</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="glib-Basic-Types.html#glong" title="glong"><span class="returnvalue">glong</span></a> </td> <td class="function_name"> <a class="link" href="glib-Unicode-Manipulation.html#g-utf8-pointer-to-offset" title="g_utf8_pointer_to_offset ()">g_utf8_pointer_to_offset</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="glib-Basic-Types.html#gchar" title="gchar"><span class="returnvalue">gchar</span></a> * </td> <td class="function_name"> <a class="link" href="glib-Unicode-Manipulation.html#g-utf8-prev-char" title="g_utf8_prev_char ()">g_utf8_prev_char</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="glib-Basic-Types.html#gchar" title="gchar"><span class="returnvalue">gchar</span></a> * </td> <td class="function_name"> <a class="link" href="glib-Unicode-Manipulation.html#g-utf8-find-next-char" title="g_utf8_find_next_char ()">g_utf8_find_next_char</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="glib-Basic-Types.html#gchar" title="gchar"><span class="returnvalue">gchar</span></a> * </td> <td class="function_name"> <a class="link" href="glib-Unicode-Manipulation.html#g-utf8-find-prev-char" title="g_utf8_find_prev_char ()">g_utf8_find_prev_char</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="glib-Basic-Types.html#glong" title="glong"><span class="returnvalue">glong</span></a> </td> <td class="function_name"> <a class="link" href="glib-Unicode-Manipulation.html#g-utf8-strlen" title="g_utf8_strlen ()">g_utf8_strlen</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="glib-Basic-Types.html#gchar" title="gchar"><span class="returnvalue">gchar</span></a> * </td> <td class="function_name"> <a class="link" href="glib-Unicode-Manipulation.html#g-utf8-strncpy" title="g_utf8_strncpy ()">g_utf8_strncpy</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="glib-Basic-Types.html#gchar" title="gchar"><span class="returnvalue">gchar</span></a> * </td> <td class="function_name"> <a class="link" href="glib-Unicode-Manipulation.html#g-utf8-strchr" title="g_utf8_strchr ()">g_utf8_strchr</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="glib-Basic-Types.html#gchar" title="gchar"><span class="returnvalue">gchar</span></a> * </td> <td class="function_name"> <a class="link" href="glib-Unicode-Manipulation.html#g-utf8-strrchr" title="g_utf8_strrchr ()">g_utf8_strrchr</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="glib-Basic-Types.html#gchar" title="gchar"><span class="returnvalue">gchar</span></a> * </td> <td class="function_name"> <a class="link" href="glib-Unicode-Manipulation.html#g-utf8-strreverse" title="g_utf8_strreverse ()">g_utf8_strreverse</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="glib-Basic-Types.html#gchar" title="gchar"><span class="returnvalue">gchar</span></a> * </td> <td class="function_name"> <a class="link" href="glib-Unicode-Manipulation.html#g-utf8-substring" title="g_utf8_substring ()">g_utf8_substring</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="glib-Basic-Types.html#gboolean" title="gboolean"><span class="returnvalue">gboolean</span></a> </td> <td class="function_name"> <a class="link" href="glib-Unicode-Manipulation.html#g-utf8-validate" title="g_utf8_validate ()">g_utf8_validate</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="glib-Basic-Types.html#gchar" title="gchar"><span class="returnvalue">gchar</span></a> * </td> <td class="function_name"> <a class="link" href="glib-Unicode-Manipulation.html#g-utf8-strup" title="g_utf8_strup ()">g_utf8_strup</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="glib-Basic-Types.html#gchar" title="gchar"><span class="returnvalue">gchar</span></a> * </td> <td class="function_name"> <a class="link" href="glib-Unicode-Manipulation.html#g-utf8-strdown" title="g_utf8_strdown ()">g_utf8_strdown</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="glib-Basic-Types.html#gchar" title="gchar"><span class="returnvalue">gchar</span></a> * </td> <td class="function_name"> <a class="link" href="glib-Unicode-Manipulation.html#g-utf8-casefold" title="g_utf8_casefold ()">g_utf8_casefold</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="glib-Basic-Types.html#gchar" title="gchar"><span class="returnvalue">gchar</span></a> * </td> <td class="function_name"> <a class="link" href="glib-Unicode-Manipulation.html#g-utf8-normalize" title="g_utf8_normalize ()">g_utf8_normalize</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="glib-Basic-Types.html#gint" title="gint"><span class="returnvalue">gint</span></a> </td> <td class="function_name"> <a class="link" href="glib-Unicode-Manipulation.html#g-utf8-collate" title="g_utf8_collate ()">g_utf8_collate</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="glib-Basic-Types.html#gchar" title="gchar"><span class="returnvalue">gchar</span></a> * </td> <td class="function_name"> <a class="link" href="glib-Unicode-Manipulation.html#g-utf8-collate-key" title="g_utf8_collate_key ()">g_utf8_collate_key</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="glib-Basic-Types.html#gchar" title="gchar"><span class="returnvalue">gchar</span></a> * </td> <td class="function_name"> <a class="link" href="glib-Unicode-Manipulation.html#g-utf8-collate-key-for-filename" title="g_utf8_collate_key_for_filename ()">g_utf8_collate_key_for_filename</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="glib-Unicode-Manipulation.html#gunichar2" title="gunichar2"><span class="returnvalue">gunichar2</span></a> * </td> <td class="function_name"> <a class="link" href="glib-Unicode-Manipulation.html#g-utf8-to-utf16" title="g_utf8_to_utf16 ()">g_utf8_to_utf16</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="glib-Unicode-Manipulation.html#gunichar" title="gunichar"><span class="returnvalue">gunichar</span></a> * </td> <td class="function_name"> <a class="link" href="glib-Unicode-Manipulation.html#g-utf8-to-ucs4" title="g_utf8_to_ucs4 ()">g_utf8_to_ucs4</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="glib-Unicode-Manipulation.html#gunichar" title="gunichar"><span class="returnvalue">gunichar</span></a> * </td> <td class="function_name"> <a class="link" href="glib-Unicode-Manipulation.html#g-utf8-to-ucs4-fast" title="g_utf8_to_ucs4_fast ()">g_utf8_to_ucs4_fast</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="glib-Unicode-Manipulation.html#gunichar" title="gunichar"><span class="returnvalue">gunichar</span></a> * </td> <td class="function_name"> <a class="link" href="glib-Unicode-Manipulation.html#g-utf16-to-ucs4" title="g_utf16_to_ucs4 ()">g_utf16_to_ucs4</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="glib-Basic-Types.html#gchar" title="gchar"><span class="returnvalue">gchar</span></a> * </td> <td class="function_name"> <a class="link" href="glib-Unicode-Manipulation.html#g-utf16-to-utf8" title="g_utf16_to_utf8 ()">g_utf16_to_utf8</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="glib-Unicode-Manipulation.html#gunichar2" title="gunichar2"><span class="returnvalue">gunichar2</span></a> * </td> <td class="function_name"> <a class="link" href="glib-Unicode-Manipulation.html#g-ucs4-to-utf16" title="g_ucs4_to_utf16 ()">g_ucs4_to_utf16</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="glib-Basic-Types.html#gchar" title="gchar"><span class="returnvalue">gchar</span></a> * </td> <td class="function_name"> <a class="link" href="glib-Unicode-Manipulation.html#g-ucs4-to-utf8" title="g_ucs4_to_utf8 ()">g_ucs4_to_utf8</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="glib-Basic-Types.html#gint" title="gint"><span class="returnvalue">gint</span></a> </td> <td class="function_name"> <a class="link" href="glib-Unicode-Manipulation.html#g-unichar-to-utf8" title="g_unichar_to_utf8 ()">g_unichar_to_utf8</a> <span class="c_punctuation">()</span> </td> </tr> </tbody> </table></div> </div> <div class="refsect1"> <a name="glib-Unicode-Manipulation.other"></a><h2>Types and Values</h2> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="name"> <col class="description"> </colgroup> <tbody> <tr> <td class="typedef_keyword">typedef</td> <td class="function_name"><a class="link" href="glib-Unicode-Manipulation.html#gunichar" title="gunichar">gunichar</a></td> </tr> <tr> <td class="typedef_keyword">typedef</td> <td class="function_name"><a class="link" href="glib-Unicode-Manipulation.html#gunichar2" title="gunichar2">gunichar2</a></td> </tr> <tr> <td class="define_keyword">#define</td> <td class="function_name"><a class="link" href="glib-Unicode-Manipulation.html#G-UNICHAR-MAX-DECOMPOSITION-LENGTH:CAPS" title="G_UNICHAR_MAX_DECOMPOSITION_LENGTH">G_UNICHAR_MAX_DECOMPOSITION_LENGTH</a></td> </tr> <tr> <td class="datatype_keyword">enum</td> <td class="function_name"><a class="link" href="glib-Unicode-Manipulation.html#GUnicodeType" title="enum GUnicodeType">GUnicodeType</a></td> </tr> <tr> <td class="define_keyword">#define</td> <td class="function_name"><a class="link" href="glib-Unicode-Manipulation.html#G-UNICODE-COMBINING-MARK:CAPS" title="G_UNICODE_COMBINING_MARK">G_UNICODE_COMBINING_MARK</a></td> </tr> <tr> <td class="datatype_keyword">enum</td> <td class="function_name"><a class="link" href="glib-Unicode-Manipulation.html#GUnicodeBreakType" title="enum GUnicodeBreakType">GUnicodeBreakType</a></td> </tr> <tr> <td class="datatype_keyword">enum</td> <td class="function_name"><a class="link" href="glib-Unicode-Manipulation.html#GUnicodeScript" title="enum GUnicodeScript">GUnicodeScript</a></td> </tr> <tr> <td class="datatype_keyword">enum</td> <td class="function_name"><a class="link" href="glib-Unicode-Manipulation.html#GNormalizeMode" title="enum GNormalizeMode">GNormalizeMode</a></td> </tr> </tbody> </table></div> </div> <div class="refsect1"> <a name="glib-Unicode-Manipulation.includes"></a><h2>Includes</h2> <pre class="synopsis">#include &lt;glib.h&gt; </pre> </div> <div class="refsect1"> <a name="glib-Unicode-Manipulation.description"></a><h2>Description</h2> <p>This section describes a number of functions for dealing with Unicode characters and strings. There are analogues of the traditional <code class="literal">ctype.h</code> character classification and case conversion functions, UTF-8 analogues of some string utility functions, functions to perform normalization, case conversion and collation on UTF-8 strings and finally functions to convert between the UTF-8, UTF-16 and UCS-4 encodings of Unicode.</p> <p>The implementations of the Unicode functions in GLib are based on the Unicode Character Data tables, which are available from <a class="ulink" href="http://www.unicode.org/" target="_top">www.unicode.org</a>. GLib 2.8 supports Unicode 4.0, GLib 2.10 supports Unicode 4.1, GLib 2.12 supports Unicode 5.0, GLib 2.16.3 supports Unicode 5.1, GLib 2.30 supports Unicode 6.0.</p> </div> <div class="refsect1"> <a name="glib-Unicode-Manipulation.functions_details"></a><h2>Functions</h2> <div class="refsect2"> <a name="g-unichar-validate"></a><h3>g_unichar_validate ()</h3> <pre class="programlisting"><a class="link" href="glib-Basic-Types.html#gboolean" title="gboolean"><span class="returnvalue">gboolean</span></a> g_unichar_validate (<em class="parameter"><code><a class="link" href="glib-Unicode-Manipulation.html#gunichar" title="gunichar"><span class="type">gunichar</span></a> ch</code></em>);</pre> <p>Checks whether <em class="parameter"><code>ch</code></em> is a valid Unicode character. Some possible integer values of <em class="parameter"><code>ch</code></em> will not be valid. 0 is considered a valid character, though it's normally a string terminator.</p> <div class="refsect3"> <a name="id-1.5.4.7.2.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody><tr> <td class="parameter_name"><p>ch</p></td> <td class="parameter_description"><p>a Unicode character</p></td> <td class="parameter_annotations"> </td> </tr></tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.5.4.7.2.6"></a><h4>Returns</h4> <p> <a class="link" href="glib-Standard-Macros.html#TRUE:CAPS" title="TRUE"><code class="literal">TRUE</code></a> if <em class="parameter"><code>ch</code></em> is a valid Unicode character</p> </div> </div> <hr> <div class="refsect2"> <a name="g-unichar-isalnum"></a><h3>g_unichar_isalnum ()</h3> <pre class="programlisting"><a class="link" href="glib-Basic-Types.html#gboolean" title="gboolean"><span class="returnvalue">gboolean</span></a> g_unichar_isalnum (<em class="parameter"><code><a class="link" href="glib-Unicode-Manipulation.html#gunichar" title="gunichar"><span class="type">gunichar</span></a> c</code></em>);</pre> <p>Determines whether a character is alphanumeric. Given some UTF-8 text, obtain a character value with <a class="link" href="glib-Unicode-Manipulation.html#g-utf8-get-char" title="g_utf8_get_char ()"><code class="function">g_utf8_get_char()</code></a>.</p> <div class="refsect3"> <a name="id-1.5.4.7.3.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody><tr> <td class="parameter_name"><p>c</p></td> <td class="parameter_description"><p>a Unicode character</p></td> <td class="parameter_annotations"> </td> </tr></tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.5.4.7.3.6"></a><h4>Returns</h4> <p> <a class="link" href="glib-Standard-Macros.html#TRUE:CAPS" title="TRUE"><code class="literal">TRUE</code></a> if <em class="parameter"><code>c</code></em> is an alphanumeric character</p> </div> </div> <hr> <div class="refsect2"> <a name="g-unichar-isalpha"></a><h3>g_unichar_isalpha ()</h3> <pre class="programlisting"><a class="link" href="glib-Basic-Types.html#gboolean" title="gboolean"><span class="returnvalue">gboolean</span></a> g_unichar_isalpha (<em class="parameter"><code><a class="link" href="glib-Unicode-Manipulation.html#gunichar" title="gunichar"><span class="type">gunichar</span></a> c</code></em>);</pre> <p>Determines whether a character is alphabetic (i.e. a letter). Given some UTF-8 text, obtain a character value with <a class="link" href="glib-Unicode-Manipulation.html#g-utf8-get-char" title="g_utf8_get_char ()"><code class="function">g_utf8_get_char()</code></a>.</p> <div class="refsect3"> <a name="id-1.5.4.7.4.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody><tr> <td class="parameter_name"><p>c</p></td> <td class="parameter_description"><p>a Unicode character</p></td> <td class="parameter_annotations"> </td> </tr></tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.5.4.7.4.6"></a><h4>Returns</h4> <p> <a class="link" href="glib-Standard-Macros.html#TRUE:CAPS" title="TRUE"><code class="literal">TRUE</code></a> if <em class="parameter"><code>c</code></em> is an alphabetic character</p> </div> </div> <hr> <div class="refsect2"> <a name="g-unichar-iscntrl"></a><h3>g_unichar_iscntrl ()</h3> <pre class="programlisting"><a class="link" href="glib-Basic-Types.html#gboolean" title="gboolean"><span class="returnvalue">gboolean</span></a> g_unichar_iscntrl (<em class="parameter"><code><a class="link" href="glib-Unicode-Manipulation.html#gunichar" title="gunichar"><span class="type">gunichar</span></a> c</code></em>);</pre> <p>Determines whether a character is a control character. Given some UTF-8 text, obtain a character value with <a class="link" href="glib-Unicode-Manipulation.html#g-utf8-get-char" title="g_utf8_get_char ()"><code class="function">g_utf8_get_char()</code></a>.</p> <div class="refsect3"> <a name="id-1.5.4.7.5.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody><tr> <td class="parameter_name"><p>c</p></td> <td class="parameter_description"><p>a Unicode character</p></td> <td class="parameter_annotations"> </td> </tr></tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.5.4.7.5.6"></a><h4>Returns</h4> <p> <a class="link" href="glib-Standard-Macros.html#TRUE:CAPS" title="TRUE"><code class="literal">TRUE</code></a> if <em class="parameter"><code>c</code></em> is a control character</p> </div> </div> <hr> <div class="refsect2"> <a name="g-unichar-isdefined"></a><h3>g_unichar_isdefined ()</h3> <pre class="programlisting"><a class="link" href="glib-Basic-Types.html#gboolean" title="gboolean"><span class="returnvalue">gboolean</span></a> g_unichar_isdefined (<em class="parameter"><code><a class="link" href="glib-Unicode-Manipulation.html#gunichar" title="gunichar"><span class="type">gunichar</span></a> c</code></em>);</pre> <p>Determines if a given character is assigned in the Unicode standard.</p> <div class="refsect3"> <a name="id-1.5.4.7.6.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody><tr> <td class="parameter_name"><p>c</p></td> <td class="parameter_description"><p>a Unicode character</p></td> <td class="parameter_annotations"> </td> </tr></tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.5.4.7.6.6"></a><h4>Returns</h4> <p> <a class="link" href="glib-Standard-Macros.html#TRUE:CAPS" title="TRUE"><code class="literal">TRUE</code></a> if the character has an assigned value</p> </div> </div> <hr> <div class="refsect2"> <a name="g-unichar-isdigit"></a><h3>g_unichar_isdigit ()</h3> <pre class="programlisting"><a class="link" href="glib-Basic-Types.html#gboolean" title="gboolean"><span class="returnvalue">gboolean</span></a> g_unichar_isdigit (<em class="parameter"><code><a class="link" href="glib-Unicode-Manipulation.html#gunichar" title="gunichar"><span class="type">gunichar</span></a> c</code></em>);</pre> <p>Determines whether a character is numeric (i.e. a digit). This covers ASCII 0-9 and also digits in other languages/scripts. Given some UTF-8 text, obtain a character value with <a class="link" href="glib-Unicode-Manipulation.html#g-utf8-get-char" title="g_utf8_get_char ()"><code class="function">g_utf8_get_char()</code></a>.</p> <div class="refsect3"> <a name="id-1.5.4.7.7.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody><tr> <td class="parameter_name"><p>c</p></td> <td class="parameter_description"><p>a Unicode character</p></td> <td class="parameter_annotations"> </td> </tr></tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.5.4.7.7.6"></a><h4>Returns</h4> <p> <a class="link" href="glib-Standard-Macros.html#TRUE:CAPS" title="TRUE"><code class="literal">TRUE</code></a> if <em class="parameter"><code>c</code></em> is a digit</p> </div> </div> <hr> <div class="refsect2"> <a name="g-unichar-isgraph"></a><h3>g_unichar_isgraph ()</h3> <pre class="programlisting"><a class="link" href="glib-Basic-Types.html#gboolean" title="gboolean"><span class="returnvalue">gboolean</span></a> g_unichar_isgraph (<em class="parameter"><code><a class="link" href="glib-Unicode-Manipulation.html#gunichar" title="gunichar"><span class="type">gunichar</span></a> c</code></em>);</pre> <p>Determines whether a character is printable and not a space (returns <a class="link" href="glib-Standard-Macros.html#FALSE:CAPS" title="FALSE"><code class="literal">FALSE</code></a> for control characters, format characters, and spaces). <a class="link" href="glib-Unicode-Manipulation.html#g-unichar-isprint" title="g_unichar_isprint ()"><code class="function">g_unichar_isprint()</code></a> is similar, but returns <a class="link" href="glib-Standard-Macros.html#TRUE:CAPS" title="TRUE"><code class="literal">TRUE</code></a> for spaces. Given some UTF-8 text, obtain a character value with <a class="link" href="glib-Unicode-Manipulation.html#g-utf8-get-char" title="g_utf8_get_char ()"><code class="function">g_utf8_get_char()</code></a>.</p> <div class="refsect3"> <a name="id-1.5.4.7.8.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody><tr> <td class="parameter_name"><p>c</p></td> <td class="parameter_description"><p>a Unicode character</p></td> <td class="parameter_annotations"> </td> </tr></tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.5.4.7.8.6"></a><h4>Returns</h4> <p> <a class="link" href="glib-Standard-Macros.html#TRUE:CAPS" title="TRUE"><code class="literal">TRUE</code></a> if <em class="parameter"><code>c</code></em> is printable unless it's a space</p> </div> </div> <hr> <div class="refsect2"> <a name="g-unichar-islower"></a><h3>g_unichar_islower ()</h3> <pre class="programlisting"><a class="link" href="glib-Basic-Types.html#gboolean" title="gboolean"><span class="returnvalue">gboolean</span></a> g_unichar_islower (<em class="parameter"><code><a class="link" href="glib-Unicode-Manipulation.html#gunichar" title="gunichar"><span class="type">gunichar</span></a> c</code></em>);</pre> <p>Determines whether a character is a lowercase letter. Given some UTF-8 text, obtain a character value with <a class="link" href="glib-Unicode-Manipulation.html#g-utf8-get-char" title="g_utf8_get_char ()"><code class="function">g_utf8_get_char()</code></a>.</p> <div class="refsect3"> <a name="id-1.5.4.7.9.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody><tr> <td class="parameter_name"><p>c</p></td> <td class="parameter_description"><p>a Unicode character</p></td> <td class="parameter_annotations"> </td> </tr></tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.5.4.7.9.6"></a><h4>Returns</h4> <p> <a class="link" href="glib-Standard-Macros.html#TRUE:CAPS" title="TRUE"><code class="literal">TRUE</code></a> if <em class="parameter"><code>c</code></em> is a lowercase letter</p> </div> </div> <hr> <div class="refsect2"> <a name="g-unichar-ismark"></a><h3>g_unichar_ismark ()</h3> <pre class="programlisting"><a class="link" href="glib-Basic-Types.html#gboolean" title="gboolean"><span class="returnvalue">gboolean</span></a> g_unichar_ismark (<em class="parameter"><code><a class="link" href="glib-Unicode-Manipulation.html#gunichar" title="gunichar"><span class="type">gunichar</span></a> c</code></em>);</pre> <p>Determines whether a character is a mark (non-spacing mark, combining mark, or enclosing mark in Unicode speak). Given some UTF-8 text, obtain a character value with <a class="link" href="glib-Unicode-Manipulation.html#g-utf8-get-char" title="g_utf8_get_char ()"><code class="function">g_utf8_get_char()</code></a>.</p> <p>Note: in most cases where isalpha characters are allowed, ismark characters should be allowed to as they are essential for writing most European languages as well as many non-Latin scripts.</p> <div class="refsect3"> <a name="id-1.5.4.7.10.6"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody><tr> <td class="parameter_name"><p>c</p></td> <td class="parameter_description"><p>a Unicode character</p></td> <td class="parameter_annotations"> </td> </tr></tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.5.4.7.10.7"></a><h4>Returns</h4> <p> <a class="link" href="glib-Standard-Macros.html#TRUE:CAPS" title="TRUE"><code class="literal">TRUE</code></a> if <em class="parameter"><code>c</code></em> is a mark character</p> </div> <p class="since">Since: <a class="link" href="api-index-2-14.html#api-index-2.14">2.14</a></p> </div> <hr> <div class="refsect2"> <a name="g-unichar-isprint"></a><h3>g_unichar_isprint ()</h3> <pre class="programlisting"><a class="link" href="glib-Basic-Types.html#gboolean" title="gboolean"><span class="returnvalue">gboolean</span></a> g_unichar_isprint (<em class="parameter"><code><a class="link" href="glib-Unicode-Manipulation.html#gunichar" title="gunichar"><span class="type">gunichar</span></a> c</code></em>);</pre> <p>Determines whether a character is printable. Unlike <a class="link" href="glib-Unicode-Manipulation.html#g-unichar-isgraph" title="g_unichar_isgraph ()"><code class="function">g_unichar_isgraph()</code></a>, returns <a class="link" href="glib-Standard-Macros.html#TRUE:CAPS" title="TRUE"><code class="literal">TRUE</code></a> for spaces. Given some UTF-8 text, obtain a character value with <a class="link" href="glib-Unicode-Manipulation.html#g-utf8-get-char" title="g_utf8_get_char ()"><code class="function">g_utf8_get_char()</code></a>.</p> <div class="refsect3"> <a name="id-1.5.4.7.11.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody><tr> <td class="parameter_name"><p>c</p></td> <td class="parameter_description"><p>a Unicode character</p></td> <td class="parameter_annotations"> </td> </tr></tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.5.4.7.11.6"></a><h4>Returns</h4> <p> <a class="link" href="glib-Standard-Macros.html#TRUE:CAPS" title="TRUE"><code class="literal">TRUE</code></a> if <em class="parameter"><code>c</code></em> is printable</p> </div> </div> <hr> <div class="refsect2"> <a name="g-unichar-ispunct"></a><h3>g_unichar_ispunct ()</h3> <pre class="programlisting"><a class="link" href="glib-Basic-Types.html#gboolean" title="gboolean"><span class="returnvalue">gboolean</span></a> g_unichar_ispunct (<em class="parameter"><code><a class="link" href="glib-Unicode-Manipulation.html#gunichar" title="gunichar"><span class="type">gunichar</span></a> c</code></em>);</pre> <p>Determines whether a character is punctuation or a symbol. Given some UTF-8 text, obtain a character value with <a class="link" href="glib-Unicode-Manipulation.html#g-utf8-get-char" title="g_utf8_get_char ()"><code class="function">g_utf8_get_char()</code></a>.</p> <div class="refsect3"> <a name="id-1.5.4.7.12.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody><tr> <td class="parameter_name"><p>c</p></td> <td class="parameter_description"><p>a Unicode character</p></td> <td class="parameter_annotations"> </td> </tr></tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.5.4.7.12.6"></a><h4>Returns</h4> <p> <a class="link" href="glib-Standard-Macros.html#TRUE:CAPS" title="TRUE"><code class="literal">TRUE</code></a> if <em class="parameter"><code>c</code></em> is a punctuation or symbol character</p> </div> </div> <hr> <div class="refsect2"> <a name="g-unichar-isspace"></a><h3>g_unichar_isspace ()</h3> <pre class="programlisting"><a class="link" href="glib-Basic-Types.html#gboolean" title="gboolean"><span class="returnvalue">gboolean</span></a> g_unichar_isspace (<em class="parameter"><code><a class="link" href="glib-Unicode-Manipulation.html#gunichar" title="gunichar"><span class="type">gunichar</span></a> c</code></em>);</pre> <p>Determines whether a character is a space, tab, or line separator (newline, carriage return, etc.). Given some UTF-8 text, obtain a character value with <a class="link" href="glib-Unicode-Manipulation.html#g-utf8-get-char" title="g_utf8_get_char ()"><code class="function">g_utf8_get_char()</code></a>.</p> <p>(Note: don't use this to do word breaking; you have to use Pango or equivalent to get word breaking right, the algorithm is fairly complex.)</p> <div class="refsect3"> <a name="id-1.5.4.7.13.6"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody><tr> <td class="parameter_name"><p>c</p></td> <td class="parameter_description"><p>a Unicode character</p></td> <td class="parameter_annotations"> </td> </tr></tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.5.4.7.13.7"></a><h4>Returns</h4> <p> <a class="link" href="glib-Standard-Macros.html#TRUE:CAPS" title="TRUE"><code class="literal">TRUE</code></a> if <em class="parameter"><code>c</code></em> is a space character</p> </div> </div> <hr> <div class="refsect2"> <a name="g-unichar-istitle"></a><h3>g_unichar_istitle ()</h3> <pre class="programlisting"><a class="link" href="glib-Basic-Types.html#gboolean" title="gboolean"><span class="returnvalue">gboolean</span></a> g_unichar_istitle (<em class="parameter"><code><a class="link" href="glib-Unicode-Manipulation.html#gunichar" title="gunichar"><span class="type">gunichar</span></a> c</code></em>);</pre> <p>Determines if a character is titlecase. Some characters in Unicode which are composites, such as the DZ digraph have three case variants instead of just two. The titlecase form is used at the beginning of a word where only the first letter is capitalized. The titlecase form of the DZ digraph is U+01F2 LATIN CAPITAL LETTTER D WITH SMALL LETTER Z.</p> <div class="refsect3"> <a name="id-1.5.4.7.14.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody><tr> <td class="parameter_name"><p>c</p></td> <td class="parameter_description"><p>a Unicode character</p></td> <td class="parameter_annotations"> </td> </tr></tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.5.4.7.14.6"></a><h4>Returns</h4> <p> <a class="link" href="glib-Standard-Macros.html#TRUE:CAPS" title="TRUE"><code class="literal">TRUE</code></a> if the character is titlecase</p> </div> </div> <hr> <div class="refsect2"> <a name="g-unichar-isupper"></a><h3>g_unichar_isupper ()</h3> <pre class="programlisting"><a class="link" href="glib-Basic-Types.html#gboolean" title="gboolean"><span class="returnvalue">gboolean</span></a> g_unichar_isupper (<em class="parameter"><code><a class="link" href="glib-Unicode-Manipulation.html#gunichar" title="gunichar"><span class="type">gunichar</span></a> c</code></em>);</pre> <p>Determines if a character is uppercase.</p> <div class="refsect3"> <a name="id-1.5.4.7.15.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody><tr> <td class="parameter_name"><p>c</p></td> <td class="parameter_description"><p>a Unicode character</p></td> <td class="parameter_annotations"> </td> </tr></tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.5.4.7.15.6"></a><h4>Returns</h4> <p> <a class="link" href="glib-Standard-Macros.html#TRUE:CAPS" title="TRUE"><code class="literal">TRUE</code></a> if <em class="parameter"><code>c</code></em> is an uppercase character</p> </div> </div> <hr> <div class="refsect2"> <a name="g-unichar-isxdigit"></a><h3>g_unichar_isxdigit ()</h3> <pre class="programlisting"><a class="link" href="glib-Basic-Types.html#gboolean" title="gboolean"><span class="returnvalue">gboolean</span></a> g_unichar_isxdigit (<em class="parameter"><code><a class="link" href="glib-Unicode-Manipulation.html#gunichar" title="gunichar"><span class="type">gunichar</span></a> c</code></em>);</pre> <p>Determines if a character is a hexidecimal digit.</p> <div class="refsect3"> <a name="id-1.5.4.7.16.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody><tr> <td class="parameter_name"><p>c</p></td> <td class="parameter_description"><p>a Unicode character.</p></td> <td class="parameter_annotations"> </td> </tr></tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.5.4.7.16.6"></a><h4>Returns</h4> <p> <a class="link" href="glib-Standard-Macros.html#TRUE:CAPS" title="TRUE"><code class="literal">TRUE</code></a> if the character is a hexadecimal digit</p> </div> </div> <hr> <div class="refsect2"> <a name="g-unichar-iswide"></a><h3>g_unichar_iswide ()</h3> <pre class="programlisting"><a class="link" href="glib-Basic-Types.html#gboolean" title="gboolean"><span class="returnvalue">gboolean</span></a> g_unichar_iswide (<em class="parameter"><code><a class="link" href="glib-Unicode-Manipulation.html#gunichar" title="gunichar"><span class="type">gunichar</span></a> c</code></em>);</pre> <p>Determines if a character is typically rendered in a double-width cell.</p> <div class="refsect3"> <a name="id-1.5.4.7.17.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody><tr> <td class="parameter_name"><p>c</p></td> <td class="parameter_description"><p>a Unicode character</p></td> <td class="parameter_annotations"> </td> </tr></tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.5.4.7.17.6"></a><h4>Returns</h4> <p> <a class="link" href="glib-Standard-Macros.html#TRUE:CAPS" title="TRUE"><code class="literal">TRUE</code></a> if the character is wide</p> </div> </div> <hr> <div class="refsect2"> <a name="g-unichar-iswide-cjk"></a><h3>g_unichar_iswide_cjk ()</h3> <pre class="programlisting"><a class="link" href="glib-Basic-Types.html#gboolean" title="gboolean"><span class="returnvalue">gboolean</span></a> g_unichar_iswide_cjk (<em class="parameter"><code><a class="link" href="glib-Unicode-Manipulation.html#gunichar" title="gunichar"><span class="type">gunichar</span></a> c</code></em>);</pre> <p>Determines if a character is typically rendered in a double-width cell under legacy East Asian locales. If a character is wide according to <a class="link" href="glib-Unicode-Manipulation.html#g-unichar-iswide" title="g_unichar_iswide ()"><code class="function">g_unichar_iswide()</code></a>, then it is also reported wide with this function, but the converse is not necessarily true. See the <a class="ulink" href="http://www.unicode.org/reports/tr11/" target="_top">Unicode Standard Annex <span class="type">11</span></a> for details.</p> <p>If a character passes the <a class="link" href="glib-Unicode-Manipulation.html#g-unichar-iswide" title="g_unichar_iswide ()"><code class="function">g_unichar_iswide()</code></a> test then it will also pass this test, but not the other way around. Note that some characters may pass both this test and <a class="link" href="glib-Unicode-Manipulation.html#g-unichar-iszerowidth" title="g_unichar_iszerowidth ()"><code class="function">g_unichar_iszerowidth()</code></a>.</p> <div class="refsect3"> <a name="id-1.5.4.7.18.6"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody><tr> <td class="parameter_name"><p>c</p></td> <td class="parameter_description"><p>a Unicode character</p></td> <td class="parameter_annotations"> </td> </tr></tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.5.4.7.18.7"></a><h4>Returns</h4> <p> <a class="link" href="glib-Standard-Macros.html#TRUE:CAPS" title="TRUE"><code class="literal">TRUE</code></a> if the character is wide in legacy East Asian locales</p> </div> <p class="since">Since: <a class="link" href="api-index-2-12.html#api-index-2.12">2.12</a></p> </div> <hr> <div class="refsect2"> <a name="g-unichar-iszerowidth"></a><h3>g_unichar_iszerowidth ()</h3> <pre class="programlisting"><a class="link" href="glib-Basic-Types.html#gboolean" title="gboolean"><span class="returnvalue">gboolean</span></a> g_unichar_iszerowidth (<em class="parameter"><code><a class="link" href="glib-Unicode-Manipulation.html#gunichar" title="gunichar"><span class="type">gunichar</span></a> c</code></em>);</pre> <p>Determines if a given character typically takes zero width when rendered. The return value is <a class="link" href="glib-Standard-Macros.html#TRUE:CAPS" title="TRUE"><code class="literal">TRUE</code></a> for all non-spacing and enclosing marks (e.g., combining accents), format characters, zero-width space, but not U+00AD SOFT HYPHEN.</p> <p>A typical use of this function is with one of <a class="link" href="glib-Unicode-Manipulation.html#g-unichar-iswide" title="g_unichar_iswide ()"><code class="function">g_unichar_iswide()</code></a> or <a class="link" href="glib-Unicode-Manipulation.html#g-unichar-iswide-cjk" title="g_unichar_iswide_cjk ()"><code class="function">g_unichar_iswide_cjk()</code></a> to determine the number of cells a string occupies when displayed on a grid display (terminals). However, note that not all terminals support zero-width rendering of zero-width marks.</p> <div class="refsect3"> <a name="id-1.5.4.7.19.6"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody><tr> <td class="parameter_name"><p>c</p></td> <td class="parameter_description"><p>a Unicode character</p></td> <td class="parameter_annotations"> </td> </tr></tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.5.4.7.19.7"></a><h4>Returns</h4> <p> <a class="link" href="glib-Standard-Macros.html#TRUE:CAPS" title="TRUE"><code class="literal">TRUE</code></a> if the character has zero width</p> </div> <p class="since">Since: <a class="link" href="api-index-2-14.html#api-index-2.14">2.14</a></p> </div> <hr> <div class="refsect2"> <a name="g-unichar-toupper"></a><h3>g_unichar_toupper ()</h3> <pre class="programlisting"><a class="link" href="glib-Unicode-Manipulation.html#gunichar" title="gunichar"><span class="returnvalue">gunichar</span></a> g_unichar_toupper (<em class="parameter"><code><a class="link" href="glib-Unicode-Manipulation.html#gunichar" title="gunichar"><span class="type">gunichar</span></a> c</code></em>);</pre> <p>Converts a character to uppercase.</p> <div class="refsect3"> <a name="id-1.5.4.7.20.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody><tr> <td class="parameter_name"><p>c</p></td> <td class="parameter_description"><p>a Unicode character</p></td> <td class="parameter_annotations"> </td> </tr></tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.5.4.7.20.6"></a><h4>Returns</h4> <p> the result of converting <em class="parameter"><code>c</code></em> to uppercase. If <em class="parameter"><code>c</code></em> is not an lowercase or titlecase character, or has no upper case equivalent <em class="parameter"><code>c</code></em> is returned unchanged.</p> </div> </div> <hr> <div class="refsect2"> <a name="g-unichar-tolower"></a><h3>g_unichar_tolower ()</h3> <pre class="programlisting"><a class="link" href="glib-Unicode-Manipulation.html#gunichar" title="gunichar"><span class="returnvalue">gunichar</span></a> g_unichar_tolower (<em class="parameter"><code><a class="link" href="glib-Unicode-Manipulation.html#gunichar" title="gunichar"><span class="type">gunichar</span></a> c</code></em>);</pre> <p>Converts a character to lower case.</p> <div class="refsect3"> <a name="id-1.5.4.7.21.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody><tr> <td class="parameter_name"><p>c</p></td> <td class="parameter_description"><p>a Unicode character.</p></td> <td class="parameter_annotations"> </td> </tr></tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.5.4.7.21.6"></a><h4>Returns</h4> <p> the result of converting <em class="parameter"><code>c</code></em> to lower case. If <em class="parameter"><code>c</code></em> is not an upperlower or titlecase character, or has no lowercase equivalent <em class="parameter"><code>c</code></em> is returned unchanged.</p> </div> </div> <hr> <div class="refsect2"> <a name="g-unichar-totitle"></a><h3>g_unichar_totitle ()</h3> <pre class="programlisting"><a class="link" href="glib-Unicode-Manipulation.html#gunichar" title="gunichar"><span class="returnvalue">gunichar</span></a> g_unichar_totitle (<em class="parameter"><code><a class="link" href="glib-Unicode-Manipulation.html#gunichar" title="gunichar"><span class="type">gunichar</span></a> c</code></em>);</pre> <p>Converts a character to the titlecase.</p> <div class="refsect3"> <a name="id-1.5.4.7.22.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody><tr> <td class="parameter_name"><p>c</p></td> <td class="parameter_description"><p>a Unicode character</p></td> <td class="parameter_annotations"> </td> </tr></tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.5.4.7.22.6"></a><h4>Returns</h4> <p> the result of converting <em class="parameter"><code>c</code></em> to titlecase. If <em class="parameter"><code>c</code></em> is not an uppercase or lowercase character, <em class="parameter"><code>c</code></em> is returned unchanged.</p> </div> </div> <hr> <div class="refsect2"> <a name="g-unichar-digit-value"></a><h3>g_unichar_digit_value ()</h3> <pre class="programlisting"><a class="link" href="glib-Basic-Types.html#gint" title="gint"><span class="returnvalue">gint</span></a> g_unichar_digit_value (<em class="parameter"><code><a class="link" href="glib-Unicode-Manipulation.html#gunichar" title="gunichar"><span class="type">gunichar</span></a> c</code></em>);</pre> <p>Determines the numeric value of a character as a decimal digit.</p> <div class="refsect3"> <a name="id-1.5.4.7.23.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody><tr> <td class="parameter_name"><p>c</p></td> <td class="parameter_description"><p>a Unicode character</p></td> <td class="parameter_annotations"> </td> </tr></tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.5.4.7.23.6"></a><h4>Returns</h4> <p> If <em class="parameter"><code>c</code></em> is a decimal digit (according to <a class="link" href="glib-Unicode-Manipulation.html#g-unichar-isdigit" title="g_unichar_isdigit ()"><code class="function">g_unichar_isdigit()</code></a>), its numeric value. Otherwise, -1.</p> </div> </div> <hr> <div class="refsect2"> <a name="g-unichar-xdigit-value"></a><h3>g_unichar_xdigit_value ()</h3> <pre class="programlisting"><a class="link" href="glib-Basic-Types.html#gint" title="gint"><span class="returnvalue">gint</span></a> g_unichar_xdigit_value (<em class="parameter"><code><a class="link" href="glib-Unicode-Manipulation.html#gunichar" title="gunichar"><span class="type">gunichar</span></a> c</code></em>);</pre> <p>Determines the numeric value of a character as a hexidecimal digit.</p> <div class="refsect3"> <a name="id-1.5.4.7.24.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody><tr> <td class="parameter_name"><p>c</p></td> <td class="parameter_description"><p>a Unicode character</p></td> <td class="parameter_annotations"> </td> </tr></tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.5.4.7.24.6"></a><h4>Returns</h4> <p> If <em class="parameter"><code>c</code></em> is a hex digit (according to <a class="link" href="glib-Unicode-Manipulation.html#g-unichar-isxdigit" title="g_unichar_isxdigit ()"><code class="function">g_unichar_isxdigit()</code></a>), its numeric value. Otherwise, -1.</p> </div> </div> <hr> <div class="refsect2"> <a name="g-unichar-compose"></a><h3>g_unichar_compose ()</h3> <pre class="programlisting"><a class="link" href="glib-Basic-Types.html#gboolean" title="gboolean"><span class="returnvalue">gboolean</span></a> g_unichar_compose (<em class="parameter"><code><a class="link" href="glib-Unicode-Manipulation.html#gunichar" title="gunichar"><span class="type">gunichar</span></a> a</code></em>, <em class="parameter"><code><a class="link" href="glib-Unicode-Manipulation.html#gunichar" title="gunichar"><span class="type">gunichar</span></a> b</code></em>, <em class="parameter"><code><a class="link" href="glib-Unicode-Manipulation.html#gunichar" title="gunichar"><span class="type">gunichar</span></a> *ch</code></em>);</pre> <p>Performs a single composition step of the Unicode canonical composition algorithm.</p> <p>This function includes algorithmic Hangul Jamo composition, but it is not exactly the inverse of <a class="link" href="glib-Unicode-Manipulation.html#g-unichar-decompose" title="g_unichar_decompose ()"><code class="function">g_unichar_decompose()</code></a>. No composition can have either of <em class="parameter"><code>a</code></em> or <em class="parameter"><code>b</code></em> equal to zero. To be precise, this function composes if and only if there exists a Primary Composite P which is canonically equivalent to the sequence &lt;<em class="parameter"><code>a</code></em> ,<em class="parameter"><code>b</code></em> &gt;. See the Unicode Standard for the definition of Primary Composite.</p> <p>If <em class="parameter"><code>a</code></em> and <em class="parameter"><code>b</code></em> do not compose a new character, <em class="parameter"><code>ch</code></em> is set to zero.</p> <p>See <a class="ulink" href="http://unicode.org/reports/tr15/" target="_top">UAX<span class="type">15</span></a> for details.</p> <div class="refsect3"> <a name="id-1.5.4.7.25.8"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>a</p></td> <td class="parameter_description"><p>a Unicode character</p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>b</p></td> <td class="parameter_description"><p>a Unicode character</p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>ch</p></td> <td class="parameter_description"><p>return location for the composed character</p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.5.4.7.25.9"></a><h4>Returns</h4> <p> <a class="link" href="glib-Standard-Macros.html#TRUE:CAPS" title="TRUE"><code class="literal">TRUE</code></a> if the characters could be composed</p> </div> <p class="since">Since: <a class="link" href="api-index-2-30.html#api-index-2.30">2.30</a></p> </div> <hr> <div class="refsect2"> <a name="g-unichar-decompose"></a><h3>g_unichar_decompose ()</h3> <pre class="programlisting"><a class="link" href="glib-Basic-Types.html#gboolean" title="gboolean"><span class="returnvalue">gboolean</span></a> g_unichar_decompose (<em class="parameter"><code><a class="link" href="glib-Unicode-Manipulation.html#gunichar" title="gunichar"><span class="type">gunichar</span></a> ch</code></em>, <em class="parameter"><code><a class="link" href="glib-Unicode-Manipulation.html#gunichar" title="gunichar"><span class="type">gunichar</span></a> *a</code></em>, <em class="parameter"><code><a class="link" href="glib-Unicode-Manipulation.html#gunichar" title="gunichar"><span class="type">gunichar</span></a> *b</code></em>);</pre> <p>Performs a single decomposition step of the Unicode canonical decomposition algorithm.</p> <p>This function does not include compatibility decompositions. It does, however, include algorithmic Hangul Jamo decomposition, as well as 'singleton' decompositions which replace a character by a single other character. In the case of singletons *<em class="parameter"><code>b</code></em> will be set to zero.</p> <p>If <em class="parameter"><code>ch</code></em> is not decomposable, *<em class="parameter"><code>a</code></em> is set to <em class="parameter"><code>ch</code></em> and *<em class="parameter"><code>b</code></em> is set to zero.</p> <p>Note that the way Unicode decomposition pairs are defined, it is guaranteed that <em class="parameter"><code>b</code></em> would not decompose further, but <em class="parameter"><code>a</code></em> may itself decompose. To get the full canonical decomposition for <em class="parameter"><code>ch</code></em> , one would need to recursively call this function on <em class="parameter"><code>a</code></em> . Or use <a class="link" href="glib-Unicode-Manipulation.html#g-unichar-fully-decompose" title="g_unichar_fully_decompose ()"><code class="function">g_unichar_fully_decompose()</code></a>.</p> <p>See <a class="ulink" href="http://unicode.org/reports/tr15/" target="_top">UAX<span class="type">15</span></a> for details.</p> <div class="refsect3"> <a name="id-1.5.4.7.26.9"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>ch</p></td> <td class="parameter_description"><p>a Unicode character</p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>a</p></td> <td class="parameter_description"><p>return location for the first component of <em class="parameter"><code>ch</code></em> </p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>b</p></td> <td class="parameter_description"><p>return location for the second component of <em class="parameter"><code>ch</code></em> </p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.5.4.7.26.10"></a><h4>Returns</h4> <p> <a class="link" href="glib-Standard-Macros.html#TRUE:CAPS" title="TRUE"><code class="literal">TRUE</code></a> if the character could be decomposed</p> </div> <p class="since">Since: <a class="link" href="api-index-2-30.html#api-index-2.30">2.30</a></p> </div> <hr> <div class="refsect2"> <a name="g-unichar-fully-decompose"></a><h3>g_unichar_fully_decompose ()</h3> <pre class="programlisting"><a class="link" href="glib-Basic-Types.html#gsize" title="gsize"><span class="returnvalue">gsize</span></a> g_unichar_fully_decompose (<em class="parameter"><code><a class="link" href="glib-Unicode-Manipulation.html#gunichar" title="gunichar"><span class="type">gunichar</span></a> ch</code></em>, <em class="parameter"><code><a class="link" href="glib-Basic-Types.html#gboolean" title="gboolean"><span class="type">gboolean</span></a> compat</code></em>, <em class="parameter"><code><a class="link" href="glib-Unicode-Manipulation.html#gunichar" title="gunichar"><span class="type">gunichar</span></a> *result</code></em>, <em class="parameter"><code><a class="link" href="glib-Basic-Types.html#gsize" title="gsize"><span class="type">gsize</span></a> result_len</code></em>);</pre> <p>Computes the canonical or compatibility decomposition of a Unicode character. For compatibility decomposition, pass <a class="link" href="glib-Standard-Macros.html#TRUE:CAPS" title="TRUE"><code class="literal">TRUE</code></a> for <em class="parameter"><code>compat</code></em> ; for canonical decomposition pass <a class="link" href="glib-Standard-Macros.html#FALSE:CAPS" title="FALSE"><code class="literal">FALSE</code></a> for <em class="parameter"><code>compat</code></em> .</p> <p>The decomposed sequence is placed in <em class="parameter"><code>result</code></em> . Only up to <em class="parameter"><code>result_len</code></em> characters are written into <em class="parameter"><code>result</code></em> . The length of the full decomposition (irrespective of <em class="parameter"><code>result_len</code></em> ) is returned by the function. For canonical decomposition, currently all decompositions are of length at most 4, but this may change in the future (very unlikely though). At any rate, Unicode does guarantee that a buffer of length 18 is always enough for both compatibility and canonical decompositions, so that is the size recommended. This is provided as <a class="link" href="glib-Unicode-Manipulation.html#G-UNICHAR-MAX-DECOMPOSITION-LENGTH:CAPS" title="G_UNICHAR_MAX_DECOMPOSITION_LENGTH"><code class="literal">G_UNICHAR_MAX_DECOMPOSITION_LENGTH</code></a>.</p> <p>See <a class="ulink" href="http://unicode.org/reports/tr15/" target="_top">UAX<span class="type">15</span></a> for details.</p> <div class="refsect3"> <a name="id-1.5.4.7.27.7"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>ch</p></td> <td class="parameter_description"><p>a Unicode character.</p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>compat</p></td> <td class="parameter_description"><p>whether perform canonical or compatibility decomposition</p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>result</p></td> <td class="parameter_description"><p> location to store decomposed result, or <a class="link" href="glib-Standard-Macros.html#NULL:CAPS" title="NULL"><code class="literal">NULL</code></a>. </p></td> <td class="parameter_annotations"><span class="annotation">[<acronym title="NULL is OK, both for passing and for returning."><span class="acronym">allow-none</span></acronym>]</span></td> </tr> <tr> <td class="parameter_name"><p>result_len</p></td> <td class="parameter_description"><p>length of <em class="parameter"><code>result</code></em> </p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.5.4.7.27.8"></a><h4>Returns</h4> <p> the length of the full decomposition.</p> </div> <p class="since">Since: <a class="link" href="api-index-2-30.html#api-index-2.30">2.30</a></p> </div> <hr> <div class="refsect2"> <a name="g-unichar-type"></a><h3>g_unichar_type ()</h3> <pre class="programlisting"><a class="link" href="glib-Unicode-Manipulation.html#GUnicodeType" title="enum GUnicodeType"><span class="returnvalue">GUnicodeType</span></a> g_unichar_type (<em class="parameter"><code><a class="link" href="glib-Unicode-Manipulation.html#gunichar" title="gunichar"><span class="type">gunichar</span></a> c</code></em>);</pre> <p>Classifies a Unicode character by type.</p> <div class="refsect3"> <a name="id-1.5.4.7.28.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody><tr> <td class="parameter_name"><p>c</p></td> <td class="parameter_description"><p>a Unicode character</p></td> <td class="parameter_annotations"> </td> </tr></tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.5.4.7.28.6"></a><h4>Returns</h4> <p> the type of the character.</p> </div> </div> <hr> <div class="refsect2"> <a name="g-unichar-break-type"></a><h3>g_unichar_break_type ()</h3> <pre class="programlisting"><a class="link" href="glib-Unicode-Manipulation.html#GUnicodeBreakType" title="enum GUnicodeBreakType"><span class="returnvalue">GUnicodeBreakType</span></a> g_unichar_break_type (<em class="parameter"><code><a class="link" href="glib-Unicode-Manipulation.html#gunichar" title="gunichar"><span class="type">gunichar</span></a> c</code></em>);</pre> <p>Determines the break type of <em class="parameter"><code>c</code></em> . <em class="parameter"><code>c</code></em> should be a Unicode character (to derive a character from UTF-8 encoded text, use <a class="link" href="glib-Unicode-Manipulation.html#g-utf8-get-char" title="g_utf8_get_char ()"><code class="function">g_utf8_get_char()</code></a>). The break type is used to find word and line breaks ("text boundaries"), Pango implements the Unicode boundary resolution algorithms and normally you would use a function such as <code class="function">pango_break()</code> instead of caring about break types yourself.</p> <div class="refsect3"> <a name="id-1.5.4.7.29.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody><tr> <td class="parameter_name"><p>c</p></td> <td class="parameter_description"><p>a Unicode character</p></td> <td class="parameter_annotations"> </td> </tr></tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.5.4.7.29.6"></a><h4>Returns</h4> <p> the break type of <em class="parameter"><code>c</code></em> </p> </div> </div> <hr> <div class="refsect2"> <a name="g-unichar-combining-class"></a><h3>g_unichar_combining_class ()</h3> <pre class="programlisting"><a class="link" href="glib-Basic-Types.html#gint" title="gint"><span class="returnvalue">gint</span></a> g_unichar_combining_class (<em class="parameter"><code><a class="link" href="glib-Unicode-Manipulation.html#gunichar" title="gunichar"><span class="type">gunichar</span></a> uc</code></em>);</pre> <p>Determines the canonical combining class of a Unicode character.</p> <div class="refsect3"> <a name="id-1.5.4.7.30.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody><tr> <td class="parameter_name"><p>uc</p></td> <td class="parameter_description"><p>a Unicode character</p></td> <td class="parameter_annotations"> </td> </tr></tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.5.4.7.30.6"></a><h4>Returns</h4> <p> the combining class of the character</p> </div> <p class="since">Since: <a class="link" href="api-index-2-14.html#api-index-2.14">2.14</a></p> </div> <hr> <div class="refsect2"> <a name="g-unicode-canonical-ordering"></a><h3>g_unicode_canonical_ordering ()</h3> <pre class="programlisting"><span class="returnvalue">void</span> g_unicode_canonical_ordering (<em class="parameter"><code><a class="link" href="glib-Unicode-Manipulation.html#gunichar" title="gunichar"><span class="type">gunichar</span></a> *string</code></em>, <em class="parameter"><code><a class="link" href="glib-Basic-Types.html#gsize" title="gsize"><span class="type">gsize</span></a> len</code></em>);</pre> <p>Computes the canonical ordering of a string in-place. This rearranges decomposed characters in the string according to their combining classes. See the Unicode manual for more information.</p> <div class="refsect3"> <a name="id-1.5.4.7.31.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>string</p></td> <td class="parameter_description"><p>a UCS-4 encoded string.</p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>len</p></td> <td class="parameter_description"><p>the maximum length of <em class="parameter"><code>string</code></em> to use.</p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> </div> <hr> <div class="refsect2"> <a name="g-unicode-canonical-decomposition"></a><h3>g_unicode_canonical_decomposition ()</h3> <pre class="programlisting"><a class="link" href="glib-Unicode-Manipulation.html#gunichar" title="gunichar"><span class="returnvalue">gunichar</span></a> * g_unicode_canonical_decomposition (<em class="parameter"><code><a class="link" href="glib-Unicode-Manipulation.html#gunichar" title="gunichar"><span class="type">gunichar</span></a> ch</code></em>, <em class="parameter"><code><a class="link" href="glib-Basic-Types.html#gsize" title="gsize"><span class="type">gsize</span></a> *result_len</code></em>);</pre> <div class="warning"> <p><code class="literal">g_unicode_canonical_decomposition</code> has been deprecated since version 2.30 and should not be used in newly-written code.</p> <p>Use the more flexible <a class="link" href="glib-Unicode-Manipulation.html#g-unichar-fully-decompose" title="g_unichar_fully_decompose ()"><code class="function">g_unichar_fully_decompose()</code></a> instead.</p> </div> <p>Computes the canonical decomposition of a Unicode character.</p> <div class="refsect3"> <a name="id-1.5.4.7.32.6"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>ch</p></td> <td class="parameter_description"><p>a Unicode character.</p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>result_len</p></td> <td class="parameter_description"><p>location to store the length of the return value.</p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.5.4.7.32.7"></a><h4>Returns</h4> <p> a newly allocated string of Unicode characters. <em class="parameter"><code>result_len</code></em> is set to the resulting length of the string.</p> </div> </div> <hr> <div class="refsect2"> <a name="g-unichar-get-mirror-char"></a><h3>g_unichar_get_mirror_char ()</h3> <pre class="programlisting"><a class="link" href="glib-Basic-Types.html#gboolean" title="gboolean"><span class="returnvalue">gboolean</span></a> g_unichar_get_mirror_char (<em class="parameter"><code><a class="link" href="glib-Unicode-Manipulation.html#gunichar" title="gunichar"><span class="type">gunichar</span></a> ch</code></em>, <em class="parameter"><code><a class="link" href="glib-Unicode-Manipulation.html#gunichar" title="gunichar"><span class="type">gunichar</span></a> *mirrored_ch</code></em>);</pre> <p>In Unicode, some characters are "mirrored". This means that their images are mirrored horizontally in text that is laid out from right to left. For instance, "(" would become its mirror image, ")", in right-to-left text.</p> <p>If <em class="parameter"><code>ch</code></em> has the Unicode mirrored property and there is another unicode character that typically has a glyph that is the mirror image of <em class="parameter"><code>ch</code></em> 's glyph and <em class="parameter"><code>mirrored_ch</code></em> is set, it puts that character in the address pointed to by <em class="parameter"><code>mirrored_ch</code></em> . Otherwise the original character is put.</p> <div class="refsect3"> <a name="id-1.5.4.7.33.6"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>ch</p></td> <td class="parameter_description"><p>a Unicode character</p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>mirrored_ch</p></td> <td class="parameter_description"><p>location to store the mirrored character</p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.5.4.7.33.7"></a><h4>Returns</h4> <p> <a class="link" href="glib-Standard-Macros.html#TRUE:CAPS" title="TRUE"><code class="literal">TRUE</code></a> if <em class="parameter"><code>ch</code></em> has a mirrored character, <a class="link" href="glib-Standard-Macros.html#FALSE:CAPS" title="FALSE"><code class="literal">FALSE</code></a> otherwise</p> </div> <p class="since">Since: <a class="link" href="api-index-2-4.html#api-index-2.4">2.4</a></p> </div> <hr> <div class="refsect2"> <a name="g-unichar-get-script"></a><h3>g_unichar_get_script ()</h3> <pre class="programlisting"><a class="link" href="glib-Unicode-Manipulation.html#GUnicodeScript" title="enum GUnicodeScript"><span class="returnvalue">GUnicodeScript</span></a> g_unichar_get_script (<em class="parameter"><code><a class="link" href="glib-Unicode-Manipulation.html#gunichar" title="gunichar"><span class="type">gunichar</span></a> ch</code></em>);</pre> <p>Looks up the <a class="link" href="glib-Unicode-Manipulation.html#GUnicodeScript" title="enum GUnicodeScript"><span class="type">GUnicodeScript</span></a> for a particular character (as defined by Unicode Standard Annex #24). No check is made for <em class="parameter"><code>ch</code></em> being a valid Unicode character; if you pass in invalid character, the result is undefined.</p> <p>This function is equivalent to <code class="function">pango_script_for_unichar()</code> and the two are interchangeable.</p> <div class="refsect3"> <a name="id-1.5.4.7.34.6"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody><tr> <td class="parameter_name"><p>ch</p></td> <td class="parameter_description"><p>a Unicode character</p></td> <td class="parameter_annotations"> </td> </tr></tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.5.4.7.34.7"></a><h4>Returns</h4> <p> the <a class="link" href="glib-Unicode-Manipulation.html#GUnicodeScript" title="enum GUnicodeScript"><span class="type">GUnicodeScript</span></a> for the character.</p> </div> <p class="since">Since: <a class="link" href="api-index-2-14.html#api-index-2.14">2.14</a></p> </div> <hr> <div class="refsect2"> <a name="g-unicode-script-from-iso15924"></a><h3>g_unicode_script_from_iso15924 ()</h3> <pre class="programlisting"><a class="link" href="glib-Unicode-Manipulation.html#GUnicodeScript" title="enum GUnicodeScript"><span class="returnvalue">GUnicodeScript</span></a> g_unicode_script_from_iso15924 (<em class="parameter"><code><a class="link" href="glib-Basic-Types.html#guint32" title="guint32"><span class="type">guint32</span></a> iso15924</code></em>);</pre> <p>Looks up the Unicode script for <em class="parameter"><code>iso15924</code></em> . ISO 15924 assigns four-letter codes to scripts. For example, the code for Arabic is 'Arab'. This function accepts four letter codes encoded as a <em class="parameter"><code>guint32</code></em> in a big-endian fashion. That is, the code expected for Arabic is 0x41726162 (0x41 is ASCII code for 'A', 0x72 is ASCII code for 'r', etc).</p> <p>See <a class="ulink" href="http://unicode.org/iso15924/codelists.html" target="_top">Codes for the representation of names of scripts</a> for details.</p> <div class="refsect3"> <a name="id-1.5.4.7.35.6"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody><tr> <td class="parameter_name"><p>iso15924</p></td> <td class="parameter_description"><p>a Unicode script</p></td> <td class="parameter_annotations"> </td> </tr></tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.5.4.7.35.7"></a><h4>Returns</h4> <p> the Unicode script for <em class="parameter"><code>iso15924</code></em> , or of <a class="link" href="glib-Unicode-Manipulation.html#G-UNICODE-SCRIPT-INVALID-CODE:CAPS"><code class="literal">G_UNICODE_SCRIPT_INVALID_CODE</code></a> if <em class="parameter"><code>iso15924</code></em> is zero and <a class="link" href="glib-Unicode-Manipulation.html#G-UNICODE-SCRIPT-UNKNOWN:CAPS"><code class="literal">G_UNICODE_SCRIPT_UNKNOWN</code></a> if <em class="parameter"><code>iso15924</code></em> is unknown.</p> </div> <p class="since">Since: <a class="link" href="api-index-2-30.html#api-index-2.30">2.30</a></p> </div> <hr> <div class="refsect2"> <a name="g-unicode-script-to-iso15924"></a><h3>g_unicode_script_to_iso15924 ()</h3> <pre class="programlisting"><a class="link" href="glib-Basic-Types.html#guint32" title="guint32"><span class="returnvalue">guint32</span></a> g_unicode_script_to_iso15924 (<em class="parameter"><code><a class="link" href="glib-Unicode-Manipulation.html#GUnicodeScript" title="enum GUnicodeScript"><span class="type">GUnicodeScript</span></a> script</code></em>);</pre> <p>Looks up the ISO 15924 code for <em class="parameter"><code>script</code></em> . ISO 15924 assigns four-letter codes to scripts. For example, the code for Arabic is 'Arab'. The four letter codes are encoded as a <em class="parameter"><code>guint32</code></em> by this function in a big-endian fashion. That is, the code returned for Arabic is 0x41726162 (0x41 is ASCII code for 'A', 0x72 is ASCII code for 'r', etc).</p> <p>See <a class="ulink" href="http://unicode.org/iso15924/codelists.html" target="_top">Codes for the representation of names of scripts</a> for details.</p> <div class="refsect3"> <a name="id-1.5.4.7.36.6"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody><tr> <td class="parameter_name"><p>script</p></td> <td class="parameter_description"><p>a Unicode script</p></td> <td class="parameter_annotations"> </td> </tr></tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.5.4.7.36.7"></a><h4>Returns</h4> <p> the ISO 15924 code for <em class="parameter"><code>script</code></em> , encoded as an integer, of zero if <em class="parameter"><code>script</code></em> is <a class="link" href="glib-Unicode-Manipulation.html#G-UNICODE-SCRIPT-INVALID-CODE:CAPS"><code class="literal">G_UNICODE_SCRIPT_INVALID_CODE</code></a> or ISO 15924 code 'Zzzz' (script code for UNKNOWN) if <em class="parameter"><code>script</code></em> is not understood.</p> </div> <p class="since">Since: <a class="link" href="api-index-2-30.html#api-index-2.30">2.30</a></p> </div> <hr> <div class="refsect2"> <a name="g-utf8-next-char"></a><h3>g_utf8_next_char()</h3> <pre class="programlisting">#define g_utf8_next_char(p)</pre> <p>Skips to the next character in a UTF-8 string. The string must be valid; this macro is as fast as possible, and has no error-checking. You would use this macro to iterate over a string character by character. The macro returns the start of the next UTF-8 character. Before using this macro, use <a class="link" href="glib-Unicode-Manipulation.html#g-utf8-validate" title="g_utf8_validate ()"><code class="function">g_utf8_validate()</code></a> to validate strings that may contain invalid UTF-8.</p> <div class="refsect3"> <a name="id-1.5.4.7.37.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody><tr> <td class="parameter_name"><p>p</p></td> <td class="parameter_description"><p>Pointer to the start of a valid UTF-8 character</p></td> <td class="parameter_annotations"> </td> </tr></tbody> </table></div> </div> </div> <hr> <div class="refsect2"> <a name="g-utf8-get-char"></a><h3>g_utf8_get_char ()</h3> <pre class="programlisting"><a class="link" href="glib-Unicode-Manipulation.html#gunichar" title="gunichar"><span class="returnvalue">gunichar</span></a> g_utf8_get_char (<em class="parameter"><code>const <a class="link" href="glib-Basic-Types.html#gchar" title="gchar"><span class="type">gchar</span></a> *p</code></em>);</pre> <p>Converts a sequence of bytes encoded as UTF-8 to a Unicode character.</p> <p>If <em class="parameter"><code>p</code></em> does not point to a valid UTF-8 encoded character, results are undefined. If you are not sure that the bytes are complete valid Unicode characters, you should use <a class="link" href="glib-Unicode-Manipulation.html#g-utf8-get-char-validated" title="g_utf8_get_char_validated ()"><code class="function">g_utf8_get_char_validated()</code></a> instead.</p> <div class="refsect3"> <a name="id-1.5.4.7.38.6"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody><tr> <td class="parameter_name"><p>p</p></td> <td class="parameter_description"><p>a pointer to Unicode character encoded as UTF-8</p></td> <td class="parameter_annotations"> </td> </tr></tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.5.4.7.38.7"></a><h4>Returns</h4> <p> the resulting character</p> </div> </div> <hr> <div class="refsect2"> <a name="g-utf8-get-char-validated"></a><h3>g_utf8_get_char_validated ()</h3> <pre class="programlisting"><a class="link" href="glib-Unicode-Manipulation.html#gunichar" title="gunichar"><span class="returnvalue">gunichar</span></a> g_utf8_get_char_validated (<em class="parameter"><code>const <a class="link" href="glib-Basic-Types.html#gchar" title="gchar"><span class="type">gchar</span></a> *p</code></em>, <em class="parameter"><code><a class="link" href="glib-Basic-Types.html#gssize" title="gssize"><span class="type">gssize</span></a> max_len</code></em>);</pre> <p>Convert a sequence of bytes encoded as UTF-8 to a Unicode character. This function checks for incomplete characters, for invalid characters such as characters that are out of the range of Unicode, and for overlong encodings of valid characters.</p> <div class="refsect3"> <a name="id-1.5.4.7.39.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>p</p></td> <td class="parameter_description"><p>a pointer to Unicode character encoded as UTF-8</p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>max_len</p></td> <td class="parameter_description"><p>the maximum number of bytes to read, or -1, for no maximum or if <em class="parameter"><code>p</code></em> is nul-terminated</p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.5.4.7.39.6"></a><h4>Returns</h4> <p> the resulting character. If <em class="parameter"><code>p</code></em> points to a partial sequence at the end of a string that could begin a valid character (or if <em class="parameter"><code>max_len</code></em> is zero), returns (gunichar)-2; otherwise, if <em class="parameter"><code>p</code></em> does not point to a valid UTF-8 encoded Unicode character, returns (gunichar)-1.</p> </div> </div> <hr> <div class="refsect2"> <a name="g-utf8-offset-to-pointer"></a><h3>g_utf8_offset_to_pointer ()</h3> <pre class="programlisting"><a class="link" href="glib-Basic-Types.html#gchar" title="gchar"><span class="returnvalue">gchar</span></a> * g_utf8_offset_to_pointer (<em class="parameter"><code>const <a class="link" href="glib-Basic-Types.html#gchar" title="gchar"><span class="type">gchar</span></a> *str</code></em>, <em class="parameter"><code><a class="link" href="glib-Basic-Types.html#glong" title="glong"><span class="type">glong</span></a> offset</code></em>);</pre> <p>Converts from an integer character offset to a pointer to a position within the string.</p> <p>Since 2.10, this function allows to pass a negative <em class="parameter"><code>offset</code></em> to step backwards. It is usually worth stepping backwards from the end instead of forwards if <em class="parameter"><code>offset</code></em> is in the last fourth of the string, since moving forward is about 3 times faster than moving backward.</p> <p>Note that this function doesn't abort when reaching the end of <em class="parameter"><code>str</code></em> . Therefore you should be sure that <em class="parameter"><code>offset</code></em> is within string boundaries before calling that function. Call <a class="link" href="glib-Unicode-Manipulation.html#g-utf8-strlen" title="g_utf8_strlen ()"><code class="function">g_utf8_strlen()</code></a> when unsure. This limitation exists as this function is called frequently during text rendering and therefore has to be as fast as possible.</p> <div class="refsect3"> <a name="id-1.5.4.7.40.7"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>str</p></td> <td class="parameter_description"><p>a UTF-8 encoded string</p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>offset</p></td> <td class="parameter_description"><p>a character offset within <em class="parameter"><code>str</code></em> </p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.5.4.7.40.8"></a><h4>Returns</h4> <p> the resulting pointer</p> </div> </div> <hr> <div class="refsect2"> <a name="g-utf8-pointer-to-offset"></a><h3>g_utf8_pointer_to_offset ()</h3> <pre class="programlisting"><a class="link" href="glib-Basic-Types.html#glong" title="glong"><span class="returnvalue">glong</span></a> g_utf8_pointer_to_offset (<em class="parameter"><code>const <a class="link" href="glib-Basic-Types.html#gchar" title="gchar"><span class="type">gchar</span></a> *str</code></em>, <em class="parameter"><code>const <a class="link" href="glib-Basic-Types.html#gchar" title="gchar"><span class="type">gchar</span></a> *pos</code></em>);</pre> <p>Converts from a pointer to position within a string to a integer character offset.</p> <p>Since 2.10, this function allows <em class="parameter"><code>pos</code></em> to be before <em class="parameter"><code>str</code></em> , and returns a negative offset in this case.</p> <div class="refsect3"> <a name="id-1.5.4.7.41.6"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>str</p></td> <td class="parameter_description"><p>a UTF-8 encoded string</p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>pos</p></td> <td class="parameter_description"><p>a pointer to a position within <em class="parameter"><code>str</code></em> </p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.5.4.7.41.7"></a><h4>Returns</h4> <p> the resulting character offset</p> </div> </div> <hr> <div class="refsect2"> <a name="g-utf8-prev-char"></a><h3>g_utf8_prev_char ()</h3> <pre class="programlisting"><a class="link" href="glib-Basic-Types.html#gchar" title="gchar"><span class="returnvalue">gchar</span></a> * g_utf8_prev_char (<em class="parameter"><code>const <a class="link" href="glib-Basic-Types.html#gchar" title="gchar"><span class="type">gchar</span></a> *p</code></em>);</pre> <p>Finds the previous UTF-8 character in the string before <em class="parameter"><code>p</code></em> .</p> <p><em class="parameter"><code>p</code></em> does not have to be at the beginning of a UTF-8 character. No check is made to see if the character found is actually valid other than it starts with an appropriate byte. If <em class="parameter"><code>p</code></em> might be the first character of the string, you must use <a class="link" href="glib-Unicode-Manipulation.html#g-utf8-find-prev-char" title="g_utf8_find_prev_char ()"><code class="function">g_utf8_find_prev_char()</code></a> instead.</p> <div class="refsect3"> <a name="id-1.5.4.7.42.6"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody><tr> <td class="parameter_name"><p>p</p></td> <td class="parameter_description"><p>a pointer to a position within a UTF-8 encoded string</p></td> <td class="parameter_annotations"> </td> </tr></tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.5.4.7.42.7"></a><h4>Returns</h4> <p> a pointer to the found character</p> </div> </div> <hr> <div class="refsect2"> <a name="g-utf8-find-next-char"></a><h3>g_utf8_find_next_char ()</h3> <pre class="programlisting"><a class="link" href="glib-Basic-Types.html#gchar" title="gchar"><span class="returnvalue">gchar</span></a> * g_utf8_find_next_char (<em class="parameter"><code>const <a class="link" href="glib-Basic-Types.html#gchar" title="gchar"><span class="type">gchar</span></a> *p</code></em>, <em class="parameter"><code>const <a class="link" href="glib-Basic-Types.html#gchar" title="gchar"><span class="type">gchar</span></a> *end</code></em>);</pre> <p>Finds the start of the next UTF-8 character in the string after <em class="parameter"><code>p</code></em> .</p> <p><em class="parameter"><code>p</code></em> does not have to be at the beginning of a UTF-8 character. No check is made to see if the character found is actually valid other than it starts with an appropriate byte.</p> <div class="refsect3"> <a name="id-1.5.4.7.43.6"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>p</p></td> <td class="parameter_description"><p>a pointer to a position within a UTF-8 encoded string</p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>end</p></td> <td class="parameter_description"><p>a pointer to the byte following the end of the string, or <a class="link" href="glib-Standard-Macros.html#NULL:CAPS" title="NULL"><code class="literal">NULL</code></a> to indicate that the string is nul-terminated</p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.5.4.7.43.7"></a><h4>Returns</h4> <p> a pointer to the found character or <a class="link" href="glib-Standard-Macros.html#NULL:CAPS" title="NULL"><code class="literal">NULL</code></a></p> </div> </div> <hr> <div class="refsect2"> <a name="g-utf8-find-prev-char"></a><h3>g_utf8_find_prev_char ()</h3> <pre class="programlisting"><a class="link" href="glib-Basic-Types.html#gchar" title="gchar"><span class="returnvalue">gchar</span></a> * g_utf8_find_prev_char (<em class="parameter"><code>const <a class="link" href="glib-Basic-Types.html#gchar" title="gchar"><span class="type">gchar</span></a> *str</code></em>, <em class="parameter"><code>const <a class="link" href="glib-Basic-Types.html#gchar" title="gchar"><span class="type">gchar</span></a> *p</code></em>);</pre> <p>Given a position <em class="parameter"><code>p</code></em> with a UTF-8 encoded string <em class="parameter"><code>str</code></em> , find the start of the previous UTF-8 character starting before <em class="parameter"><code>p</code></em> . Returns <a class="link" href="glib-Standard-Macros.html#NULL:CAPS" title="NULL"><code class="literal">NULL</code></a> if no UTF-8 characters are present in <em class="parameter"><code>str</code></em> before <em class="parameter"><code>p</code></em> .</p> <p><em class="parameter"><code>p</code></em> does not have to be at the beginning of a UTF-8 character. No check is made to see if the character found is actually valid other than it starts with an appropriate byte.</p> <div class="refsect3"> <a name="id-1.5.4.7.44.6"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>str</p></td> <td class="parameter_description"><p>pointer to the beginning of a UTF-8 encoded string</p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>p</p></td> <td class="parameter_description"><p>pointer to some position within <em class="parameter"><code>str</code></em> </p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.5.4.7.44.7"></a><h4>Returns</h4> <p> a pointer to the found character or <a class="link" href="glib-Standard-Macros.html#NULL:CAPS" title="NULL"><code class="literal">NULL</code></a>.</p> </div> </div> <hr> <div class="refsect2"> <a name="g-utf8-strlen"></a><h3>g_utf8_strlen ()</h3> <pre class="programlisting"><a class="link" href="glib-Basic-Types.html#glong" title="glong"><span class="returnvalue">glong</span></a> g_utf8_strlen (<em class="parameter"><code>const <a class="link" href="glib-Basic-Types.html#gchar" title="gchar"><span class="type">gchar</span></a> *p</code></em>, <em class="parameter"><code><a class="link" href="glib-Basic-Types.html#gssize" title="gssize"><span class="type">gssize</span></a> max</code></em>);</pre> <p>Computes the length of the string in characters, not including the terminating nul character. If the <em class="parameter"><code>max</code></em> 'th byte falls in the middle of a character, the last (partial) character is not counted.</p> <div class="refsect3"> <a name="id-1.5.4.7.45.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>p</p></td> <td class="parameter_description"><p>pointer to the start of a UTF-8 encoded string</p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>max</p></td> <td class="parameter_description"><p>the maximum number of bytes to examine. If <em class="parameter"><code>max</code></em> is less than 0, then the string is assumed to be nul-terminated. If <em class="parameter"><code>max</code></em> is 0, <em class="parameter"><code>p</code></em> will not be examined and may be <a class="link" href="glib-Standard-Macros.html#NULL:CAPS" title="NULL"><code class="literal">NULL</code></a>. If <em class="parameter"><code>max</code></em> is greater than 0, up to <em class="parameter"><code>max</code></em> bytes are examined</p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.5.4.7.45.6"></a><h4>Returns</h4> <p> the length of the string in characters</p> </div> </div> <hr> <div class="refsect2"> <a name="g-utf8-strncpy"></a><h3>g_utf8_strncpy ()</h3> <pre class="programlisting"><a class="link" href="glib-Basic-Types.html#gchar" title="gchar"><span class="returnvalue">gchar</span></a> * g_utf8_strncpy (<em class="parameter"><code><a class="link" href="glib-Basic-Types.html#gchar" title="gchar"><span class="type">gchar</span></a> *dest</code></em>, <em class="parameter"><code>const <a class="link" href="glib-Basic-Types.html#gchar" title="gchar"><span class="type">gchar</span></a> *src</code></em>, <em class="parameter"><code><a class="link" href="glib-Basic-Types.html#gsize" title="gsize"><span class="type">gsize</span></a> n</code></em>);</pre> <p>Like the standard C <code class="function">strncpy()</code> function, but copies a given number of characters instead of a given number of bytes. The <em class="parameter"><code>src</code></em> string must be valid UTF-8 encoded text. (Use <a class="link" href="glib-Unicode-Manipulation.html#g-utf8-validate" title="g_utf8_validate ()"><code class="function">g_utf8_validate()</code></a> on all text before trying to use UTF-8 utility functions with it.)</p> <div class="refsect3"> <a name="id-1.5.4.7.46.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>dest</p></td> <td class="parameter_description"><p>buffer to fill with characters from <em class="parameter"><code>src</code></em> </p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>src</p></td> <td class="parameter_description"><p>UTF-8 encoded string</p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>n</p></td> <td class="parameter_description"><p>character count</p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.5.4.7.46.6"></a><h4>Returns</h4> <p> <em class="parameter"><code>dest</code></em> </p> </div> </div> <hr> <div class="refsect2"> <a name="g-utf8-strchr"></a><h3>g_utf8_strchr ()</h3> <pre class="programlisting"><a class="link" href="glib-Basic-Types.html#gchar" title="gchar"><span class="returnvalue">gchar</span></a> * g_utf8_strchr (<em class="parameter"><code>const <a class="link" href="glib-Basic-Types.html#gchar" title="gchar"><span class="type">gchar</span></a> *p</code></em>, <em class="parameter"><code><a class="link" href="glib-Basic-Types.html#gssize" title="gssize"><span class="type">gssize</span></a> len</code></em>, <em class="parameter"><code><a class="link" href="glib-Unicode-Manipulation.html#gunichar" title="gunichar"><span class="type">gunichar</span></a> c</code></em>);</pre> <p>Finds the leftmost occurrence of the given Unicode character in a UTF-8 encoded string, while limiting the search to <em class="parameter"><code>len</code></em> bytes. If <em class="parameter"><code>len</code></em> is -1, allow unbounded search.</p> <div class="refsect3"> <a name="id-1.5.4.7.47.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>p</p></td> <td class="parameter_description"><p>a nul-terminated UTF-8 encoded string</p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>len</p></td> <td class="parameter_description"><p>the maximum length of <em class="parameter"><code>p</code></em> </p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>c</p></td> <td class="parameter_description"><p>a Unicode character</p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.5.4.7.47.6"></a><h4>Returns</h4> <p> <a class="link" href="glib-Standard-Macros.html#NULL:CAPS" title="NULL"><code class="literal">NULL</code></a> if the string does not contain the character, otherwise, a pointer to the start of the leftmost occurrence of the character in the string.</p> </div> </div> <hr> <div class="refsect2"> <a name="g-utf8-strrchr"></a><h3>g_utf8_strrchr ()</h3> <pre class="programlisting"><a class="link" href="glib-Basic-Types.html#gchar" title="gchar"><span class="returnvalue">gchar</span></a> * g_utf8_strrchr (<em class="parameter"><code>const <a class="link" href="glib-Basic-Types.html#gchar" title="gchar"><span class="type">gchar</span></a> *p</code></em>, <em class="parameter"><code><a class="link" href="glib-Basic-Types.html#gssize" title="gssize"><span class="type">gssize</span></a> len</code></em>, <em class="parameter"><code><a class="link" href="glib-Unicode-Manipulation.html#gunichar" title="gunichar"><span class="type">gunichar</span></a> c</code></em>);</pre> <p>Find the rightmost occurrence of the given Unicode character in a UTF-8 encoded string, while limiting the search to <em class="parameter"><code>len</code></em> bytes. If <em class="parameter"><code>len</code></em> is -1, allow unbounded search.</p> <div class="refsect3"> <a name="id-1.5.4.7.48.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>p</p></td> <td class="parameter_description"><p>a nul-terminated UTF-8 encoded string</p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>len</p></td> <td class="parameter_description"><p>the maximum length of <em class="parameter"><code>p</code></em> </p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>c</p></td> <td class="parameter_description"><p>a Unicode character</p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.5.4.7.48.6"></a><h4>Returns</h4> <p> <a class="link" href="glib-Standard-Macros.html#NULL:CAPS" title="NULL"><code class="literal">NULL</code></a> if the string does not contain the character, otherwise, a pointer to the start of the rightmost occurrence of the character in the string.</p> </div> </div> <hr> <div class="refsect2"> <a name="g-utf8-strreverse"></a><h3>g_utf8_strreverse ()</h3> <pre class="programlisting"><a class="link" href="glib-Basic-Types.html#gchar" title="gchar"><span class="returnvalue">gchar</span></a> * g_utf8_strreverse (<em class="parameter"><code>const <a class="link" href="glib-Basic-Types.html#gchar" title="gchar"><span class="type">gchar</span></a> *str</code></em>, <em class="parameter"><code><a class="link" href="glib-Basic-Types.html#gssize" title="gssize"><span class="type">gssize</span></a> len</code></em>);</pre> <p>Reverses a UTF-8 string. <em class="parameter"><code>str</code></em> must be valid UTF-8 encoded text. (Use <a class="link" href="glib-Unicode-Manipulation.html#g-utf8-validate" title="g_utf8_validate ()"><code class="function">g_utf8_validate()</code></a> on all text before trying to use UTF-8 utility functions with it.)</p> <p>This function is intended for programmatic uses of reversed strings. It pays no attention to decomposed characters, combining marks, byte order marks, directional indicators (LRM, LRO, etc) and similar characters which might need special handling when reversing a string for display purposes.</p> <p>Note that unlike <a class="link" href="glib-String-Utility-Functions.html#g-strreverse" title="g_strreverse ()"><code class="function">g_strreverse()</code></a>, this function returns newly-allocated memory, which should be freed with <a class="link" href="glib-Memory-Allocation.html#g-free" title="g_free ()"><code class="function">g_free()</code></a> when no longer needed.</p> <div class="refsect3"> <a name="id-1.5.4.7.49.7"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>str</p></td> <td class="parameter_description"><p>a UTF-8 encoded string</p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>len</p></td> <td class="parameter_description"><p>the maximum length of <em class="parameter"><code>str</code></em> to use, in bytes. If <em class="parameter"><code>len</code></em> &lt; 0, then the string is nul-terminated.</p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.5.4.7.49.8"></a><h4>Returns</h4> <p> a newly-allocated string which is the reverse of <em class="parameter"><code>str</code></em> </p> </div> <p class="since">Since: <a class="link" href="api-index-2-2.html#api-index-2.2">2.2</a></p> </div> <hr> <div class="refsect2"> <a name="g-utf8-substring"></a><h3>g_utf8_substring ()</h3> <pre class="programlisting"><a class="link" href="glib-Basic-Types.html#gchar" title="gchar"><span class="returnvalue">gchar</span></a> * g_utf8_substring (<em class="parameter"><code>const <a class="link" href="glib-Basic-Types.html#gchar" title="gchar"><span class="type">gchar</span></a> *str</code></em>, <em class="parameter"><code><a class="link" href="glib-Basic-Types.html#glong" title="glong"><span class="type">glong</span></a> start_pos</code></em>, <em class="parameter"><code><a class="link" href="glib-Basic-Types.html#glong" title="glong"><span class="type">glong</span></a> end_pos</code></em>);</pre> <p>Copies a substring out of a UTF-8 encoded string. The substring will contain <em class="parameter"><code>end_pos</code></em> - <em class="parameter"><code>start_pos</code></em> characters.</p> <div class="refsect3"> <a name="id-1.5.4.7.50.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>str</p></td> <td class="parameter_description"><p>a UTF-8 encoded string</p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>start_pos</p></td> <td class="parameter_description"><p>a character offset within <em class="parameter"><code>str</code></em> </p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>end_pos</p></td> <td class="parameter_description"><p>another character offset within <em class="parameter"><code>str</code></em> </p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.5.4.7.50.6"></a><h4>Returns</h4> <p> a newly allocated copy of the requested substring. Free with <a class="link" href="glib-Memory-Allocation.html#g-free" title="g_free ()"><code class="function">g_free()</code></a> when no longer needed.</p> </div> <p class="since">Since: <a class="link" href="api-index-2-30.html#api-index-2.30">2.30</a></p> </div> <hr> <div class="refsect2"> <a name="g-utf8-validate"></a><h3>g_utf8_validate ()</h3> <pre class="programlisting"><a class="link" href="glib-Basic-Types.html#gboolean" title="gboolean"><span class="returnvalue">gboolean</span></a> g_utf8_validate (<em class="parameter"><code>const <a class="link" href="glib-Basic-Types.html#gchar" title="gchar"><span class="type">gchar</span></a> *str</code></em>, <em class="parameter"><code><a class="link" href="glib-Basic-Types.html#gssize" title="gssize"><span class="type">gssize</span></a> max_len</code></em>, <em class="parameter"><code>const <a class="link" href="glib-Basic-Types.html#gchar" title="gchar"><span class="type">gchar</span></a> **end</code></em>);</pre> <p>Validates UTF-8 encoded text. <em class="parameter"><code>str</code></em> is the text to validate; if <em class="parameter"><code>str</code></em> is nul-terminated, then <em class="parameter"><code>max_len</code></em> can be -1, otherwise <em class="parameter"><code>max_len</code></em> should be the number of bytes to validate. If <em class="parameter"><code>end</code></em> is non-<a class="link" href="glib-Standard-Macros.html#NULL:CAPS" title="NULL"><code class="literal">NULL</code></a>, then the end of the valid range will be stored there (i.e. the start of the first invalid character if some bytes were invalid, or the end of the text being validated otherwise).</p> <p>Note that <a class="link" href="glib-Unicode-Manipulation.html#g-utf8-validate" title="g_utf8_validate ()"><code class="function">g_utf8_validate()</code></a> returns <a class="link" href="glib-Standard-Macros.html#FALSE:CAPS" title="FALSE"><code class="literal">FALSE</code></a> if <em class="parameter"><code>max_len</code></em> is positive and any of the <em class="parameter"><code>max_len</code></em> bytes are nul.</p> <p>Returns <a class="link" href="glib-Standard-Macros.html#TRUE:CAPS" title="TRUE"><code class="literal">TRUE</code></a> if all of <em class="parameter"><code>str</code></em> was valid. Many GLib and GTK+ routines require valid UTF-8 as input; so data read from a file or the network should be checked with <a class="link" href="glib-Unicode-Manipulation.html#g-utf8-validate" title="g_utf8_validate ()"><code class="function">g_utf8_validate()</code></a> before doing anything else with it.</p> <div class="refsect3"> <a name="id-1.5.4.7.51.7"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>str</p></td> <td class="parameter_description"><p> a pointer to character data. </p></td> <td class="parameter_annotations"><span class="annotation">[<acronym title="Parameter points to an array of items."><span class="acronym">array</span></acronym> length=max_len][<acronym title="Generics and defining elements of containers and arrays."><span class="acronym">element-type</span></acronym> guint8]</span></td> </tr> <tr> <td class="parameter_name"><p>max_len</p></td> <td class="parameter_description"><p>max bytes to validate, or -1 to go until NUL</p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>end</p></td> <td class="parameter_description"><p> return location for end of valid data. </p></td> <td class="parameter_annotations"><span class="annotation">[<acronym title="NULL is OK, both for passing and for returning."><span class="acronym">allow-none</span></acronym>][<acronym title="Parameter for returning results. Default is transfer full."><span class="acronym">out</span></acronym>][<acronym title="Don't free data after the code is done."><span class="acronym">transfer none</span></acronym>]</span></td> </tr> </tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.5.4.7.51.8"></a><h4>Returns</h4> <p> <a class="link" href="glib-Standard-Macros.html#TRUE:CAPS" title="TRUE"><code class="literal">TRUE</code></a> if the text was valid UTF-8</p> </div> </div> <hr> <div class="refsect2"> <a name="g-utf8-strup"></a><h3>g_utf8_strup ()</h3> <pre class="programlisting"><a class="link" href="glib-Basic-Types.html#gchar" title="gchar"><span class="returnvalue">gchar</span></a> * g_utf8_strup (<em class="parameter"><code>const <a class="link" href="glib-Basic-Types.html#gchar" title="gchar"><span class="type">gchar</span></a> *str</code></em>, <em class="parameter"><code><a class="link" href="glib-Basic-Types.html#gssize" title="gssize"><span class="type">gssize</span></a> len</code></em>);</pre> <p>Converts all Unicode characters in the string that have a case to uppercase. The exact manner that this is done depends on the current locale, and may result in the number of characters in the string increasing. (For instance, the German ess-zet will be changed to SS.)</p> <div class="refsect3"> <a name="id-1.5.4.7.52.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>str</p></td> <td class="parameter_description"><p>a UTF-8 encoded string</p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>len</p></td> <td class="parameter_description"><p>length of <em class="parameter"><code>str</code></em> , in bytes, or -1 if <em class="parameter"><code>str</code></em> is nul-terminated.</p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.5.4.7.52.6"></a><h4>Returns</h4> <p> a newly allocated string, with all characters converted to uppercase. </p> </div> </div> <hr> <div class="refsect2"> <a name="g-utf8-strdown"></a><h3>g_utf8_strdown ()</h3> <pre class="programlisting"><a class="link" href="glib-Basic-Types.html#gchar" title="gchar"><span class="returnvalue">gchar</span></a> * g_utf8_strdown (<em class="parameter"><code>const <a class="link" href="glib-Basic-Types.html#gchar" title="gchar"><span class="type">gchar</span></a> *str</code></em>, <em class="parameter"><code><a class="link" href="glib-Basic-Types.html#gssize" title="gssize"><span class="type">gssize</span></a> len</code></em>);</pre> <p>Converts all Unicode characters in the string that have a case to lowercase. The exact manner that this is done depends on the current locale, and may result in the number of characters in the string changing.</p> <div class="refsect3"> <a name="id-1.5.4.7.53.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>str</p></td> <td class="parameter_description"><p>a UTF-8 encoded string</p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>len</p></td> <td class="parameter_description"><p>length of <em class="parameter"><code>str</code></em> , in bytes, or -1 if <em class="parameter"><code>str</code></em> is nul-terminated.</p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.5.4.7.53.6"></a><h4>Returns</h4> <p> a newly allocated string, with all characters converted to lowercase. </p> </div> </div> <hr> <div class="refsect2"> <a name="g-utf8-casefold"></a><h3>g_utf8_casefold ()</h3> <pre class="programlisting"><a class="link" href="glib-Basic-Types.html#gchar" title="gchar"><span class="returnvalue">gchar</span></a> * g_utf8_casefold (<em class="parameter"><code>const <a class="link" href="glib-Basic-Types.html#gchar" title="gchar"><span class="type">gchar</span></a> *str</code></em>, <em class="parameter"><code><a class="link" href="glib-Basic-Types.html#gssize" title="gssize"><span class="type">gssize</span></a> len</code></em>);</pre> <p>Converts a string into a form that is independent of case. The result will not correspond to any particular case, but can be compared for equality or ordered with the results of calling <a class="link" href="glib-Unicode-Manipulation.html#g-utf8-casefold" title="g_utf8_casefold ()"><code class="function">g_utf8_casefold()</code></a> on other strings.</p> <p>Note that calling <a class="link" href="glib-Unicode-Manipulation.html#g-utf8-casefold" title="g_utf8_casefold ()"><code class="function">g_utf8_casefold()</code></a> followed by <a class="link" href="glib-Unicode-Manipulation.html#g-utf8-collate" title="g_utf8_collate ()"><code class="function">g_utf8_collate()</code></a> is only an approximation to the correct linguistic case insensitive ordering, though it is a fairly good one. Getting this exactly right would require a more sophisticated collation function that takes case sensitivity into account. GLib does not currently provide such a function.</p> <div class="refsect3"> <a name="id-1.5.4.7.54.6"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>str</p></td> <td class="parameter_description"><p>a UTF-8 encoded string</p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>len</p></td> <td class="parameter_description"><p>length of <em class="parameter"><code>str</code></em> , in bytes, or -1 if <em class="parameter"><code>str</code></em> is nul-terminated.</p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.5.4.7.54.7"></a><h4>Returns</h4> <p> a newly allocated string, that is a case independent form of <em class="parameter"><code>str</code></em> .</p> </div> </div> <hr> <div class="refsect2"> <a name="g-utf8-normalize"></a><h3>g_utf8_normalize ()</h3> <pre class="programlisting"><a class="link" href="glib-Basic-Types.html#gchar" title="gchar"><span class="returnvalue">gchar</span></a> * g_utf8_normalize (<em class="parameter"><code>const <a class="link" href="glib-Basic-Types.html#gchar" title="gchar"><span class="type">gchar</span></a> *str</code></em>, <em class="parameter"><code><a class="link" href="glib-Basic-Types.html#gssize" title="gssize"><span class="type">gssize</span></a> len</code></em>, <em class="parameter"><code><a class="link" href="glib-Unicode-Manipulation.html#GNormalizeMode" title="enum GNormalizeMode"><span class="type">GNormalizeMode</span></a> mode</code></em>);</pre> <p>Converts a string into canonical form, standardizing such issues as whether a character with an accent is represented as a base character and combining accent or as a single precomposed character. The string has to be valid UTF-8, otherwise <a class="link" href="glib-Standard-Macros.html#NULL:CAPS" title="NULL"><code class="literal">NULL</code></a> is returned. You should generally call <a class="link" href="glib-Unicode-Manipulation.html#g-utf8-normalize" title="g_utf8_normalize ()"><code class="function">g_utf8_normalize()</code></a> before comparing two Unicode strings.</p> <p>The normalization mode <a class="link" href="glib-Unicode-Manipulation.html#G-NORMALIZE-DEFAULT:CAPS"><code class="literal">G_NORMALIZE_DEFAULT</code></a> only standardizes differences that do not affect the text content, such as the above-mentioned accent representation. <a class="link" href="glib-Unicode-Manipulation.html#G-NORMALIZE-ALL:CAPS"><code class="literal">G_NORMALIZE_ALL</code></a> also standardizes the "compatibility" characters in Unicode, such as SUPERSCRIPT THREE to the standard forms (in this case DIGIT THREE). Formatting information may be lost but for most text operations such characters should be considered the same.</p> <p><a class="link" href="glib-Unicode-Manipulation.html#G-NORMALIZE-DEFAULT-COMPOSE:CAPS"><code class="literal">G_NORMALIZE_DEFAULT_COMPOSE</code></a> and <a class="link" href="glib-Unicode-Manipulation.html#G-NORMALIZE-ALL-COMPOSE:CAPS"><code class="literal">G_NORMALIZE_ALL_COMPOSE</code></a> are like <a class="link" href="glib-Unicode-Manipulation.html#G-NORMALIZE-DEFAULT:CAPS"><code class="literal">G_NORMALIZE_DEFAULT</code></a> and <a class="link" href="glib-Unicode-Manipulation.html#G-NORMALIZE-ALL:CAPS"><code class="literal">G_NORMALIZE_ALL</code></a>, but returned a result with composed forms rather than a maximally decomposed form. This is often useful if you intend to convert the string to a legacy encoding or pass it to a system with less capable Unicode handling.</p> <div class="refsect3"> <a name="id-1.5.4.7.55.7"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>str</p></td> <td class="parameter_description"><p>a UTF-8 encoded string.</p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>len</p></td> <td class="parameter_description"><p>length of <em class="parameter"><code>str</code></em> , in bytes, or -1 if <em class="parameter"><code>str</code></em> is nul-terminated.</p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>mode</p></td> <td class="parameter_description"><p>the type of normalization to perform.</p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.5.4.7.55.8"></a><h4>Returns</h4> <p> a newly allocated string, that is the normalized form of <em class="parameter"><code>str</code></em> , or <a class="link" href="glib-Standard-Macros.html#NULL:CAPS" title="NULL"><code class="literal">NULL</code></a> if <em class="parameter"><code>str</code></em> is not valid UTF-8.</p> </div> </div> <hr> <div class="refsect2"> <a name="g-utf8-collate"></a><h3>g_utf8_collate ()</h3> <pre class="programlisting"><a class="link" href="glib-Basic-Types.html#gint" title="gint"><span class="returnvalue">gint</span></a> g_utf8_collate (<em class="parameter"><code>const <a class="link" href="glib-Basic-Types.html#gchar" title="gchar"><span class="type">gchar</span></a> *str1</code></em>, <em class="parameter"><code>const <a class="link" href="glib-Basic-Types.html#gchar" title="gchar"><span class="type">gchar</span></a> *str2</code></em>);</pre> <p>Compares two strings for ordering using the linguistically correct rules for the <a class="link" href="glib-running.html#setlocale" title="Locale">current locale</a>. When sorting a large number of strings, it will be significantly faster to obtain collation keys with <a class="link" href="glib-Unicode-Manipulation.html#g-utf8-collate-key" title="g_utf8_collate_key ()"><code class="function">g_utf8_collate_key()</code></a> and compare the keys with <code class="function">strcmp()</code> when sorting instead of sorting the original strings.</p> <div class="refsect3"> <a name="id-1.5.4.7.56.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>str1</p></td> <td class="parameter_description"><p>a UTF-8 encoded string</p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>str2</p></td> <td class="parameter_description"><p>a UTF-8 encoded string</p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.5.4.7.56.6"></a><h4>Returns</h4> <p> &lt; 0 if <em class="parameter"><code>str1</code></em> compares before <em class="parameter"><code>str2</code></em> , 0 if they compare equal, &gt; 0 if <em class="parameter"><code>str1</code></em> compares after <em class="parameter"><code>str2</code></em> .</p> </div> </div> <hr> <div class="refsect2"> <a name="g-utf8-collate-key"></a><h3>g_utf8_collate_key ()</h3> <pre class="programlisting"><a class="link" href="glib-Basic-Types.html#gchar" title="gchar"><span class="returnvalue">gchar</span></a> * g_utf8_collate_key (<em class="parameter"><code>const <a class="link" href="glib-Basic-Types.html#gchar" title="gchar"><span class="type">gchar</span></a> *str</code></em>, <em class="parameter"><code><a class="link" href="glib-Basic-Types.html#gssize" title="gssize"><span class="type">gssize</span></a> len</code></em>);</pre> <p>Converts a string into a collation key that can be compared with other collation keys produced by the same function using <code class="function">strcmp()</code>. </p> <p>The results of comparing the collation keys of two strings with <code class="function">strcmp()</code> will always be the same as comparing the two original keys with <a class="link" href="glib-Unicode-Manipulation.html#g-utf8-collate" title="g_utf8_collate ()"><code class="function">g_utf8_collate()</code></a>.</p> <p>Note that this function depends on the <a class="link" href="glib-running.html#setlocale" title="Locale">current locale</a>.</p> <div class="refsect3"> <a name="id-1.5.4.7.57.7"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>str</p></td> <td class="parameter_description"><p>a UTF-8 encoded string.</p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>len</p></td> <td class="parameter_description"><p>length of <em class="parameter"><code>str</code></em> , in bytes, or -1 if <em class="parameter"><code>str</code></em> is nul-terminated.</p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.5.4.7.57.8"></a><h4>Returns</h4> <p> a newly allocated string. This string should be freed with <a class="link" href="glib-Memory-Allocation.html#g-free" title="g_free ()"><code class="function">g_free()</code></a> when you are done with it.</p> </div> </div> <hr> <div class="refsect2"> <a name="g-utf8-collate-key-for-filename"></a><h3>g_utf8_collate_key_for_filename ()</h3> <pre class="programlisting"><a class="link" href="glib-Basic-Types.html#gchar" title="gchar"><span class="returnvalue">gchar</span></a> * g_utf8_collate_key_for_filename (<em class="parameter"><code>const <a class="link" href="glib-Basic-Types.html#gchar" title="gchar"><span class="type">gchar</span></a> *str</code></em>, <em class="parameter"><code><a class="link" href="glib-Basic-Types.html#gssize" title="gssize"><span class="type">gssize</span></a> len</code></em>);</pre> <p>Converts a string into a collation key that can be compared with other collation keys produced by the same function using <code class="function">strcmp()</code>. </p> <p>In order to sort filenames correctly, this function treats the dot '.' as a special case. Most dictionary orderings seem to consider it insignificant, thus producing the ordering "event.c" "eventgenerator.c" "event.h" instead of "event.c" "event.h" "eventgenerator.c". Also, we would like to treat numbers intelligently so that "file1" "file10" "file5" is sorted as "file1" "file5" "file10".</p> <p>Note that this function depends on the <a class="link" href="glib-running.html#setlocale" title="Locale">current locale</a>.</p> <div class="refsect3"> <a name="id-1.5.4.7.58.7"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>str</p></td> <td class="parameter_description"><p>a UTF-8 encoded string.</p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>len</p></td> <td class="parameter_description"><p>length of <em class="parameter"><code>str</code></em> , in bytes, or -1 if <em class="parameter"><code>str</code></em> is nul-terminated.</p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.5.4.7.58.8"></a><h4>Returns</h4> <p> a newly allocated string. This string should be freed with <a class="link" href="glib-Memory-Allocation.html#g-free" title="g_free ()"><code class="function">g_free()</code></a> when you are done with it.</p> </div> <p class="since">Since: <a class="link" href="api-index-2-8.html#api-index-2.8">2.8</a></p> </div> <hr> <div class="refsect2"> <a name="g-utf8-to-utf16"></a><h3>g_utf8_to_utf16 ()</h3> <pre class="programlisting"><a class="link" href="glib-Unicode-Manipulation.html#gunichar2" title="gunichar2"><span class="returnvalue">gunichar2</span></a> * g_utf8_to_utf16 (<em class="parameter"><code>const <a class="link" href="glib-Basic-Types.html#gchar" title="gchar"><span class="type">gchar</span></a> *str</code></em>, <em class="parameter"><code><a class="link" href="glib-Basic-Types.html#glong" title="glong"><span class="type">glong</span></a> len</code></em>, <em class="parameter"><code><a class="link" href="glib-Basic-Types.html#glong" title="glong"><span class="type">glong</span></a> *items_read</code></em>, <em class="parameter"><code><a class="link" href="glib-Basic-Types.html#glong" title="glong"><span class="type">glong</span></a> *items_written</code></em>, <em class="parameter"><code><a class="link" href="glib-Error-Reporting.html#GError" title="struct GError"><span class="type">GError</span></a> **error</code></em>);</pre> <p>Convert a string from UTF-8 to UTF-16. A 0 character will be added to the result after the converted text.</p> <div class="refsect3"> <a name="id-1.5.4.7.59.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>str</p></td> <td class="parameter_description"><p>a UTF-8 encoded string</p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>len</p></td> <td class="parameter_description"><p>the maximum length (number of bytes) of <em class="parameter"><code>str</code></em> to use. If <em class="parameter"><code>len</code></em> &lt; 0, then the string is nul-terminated.</p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>items_read</p></td> <td class="parameter_description"><p> location to store number of bytes read, or <a class="link" href="glib-Standard-Macros.html#NULL:CAPS" title="NULL"><code class="literal">NULL</code></a>. If <a class="link" href="glib-Standard-Macros.html#NULL:CAPS" title="NULL"><code class="literal">NULL</code></a>, then <a class="link" href="glib-Character-Set-Conversion.html#G-CONVERT-ERROR-PARTIAL-INPUT:CAPS"><code class="literal">G_CONVERT_ERROR_PARTIAL_INPUT</code></a> will be returned in case <em class="parameter"><code>str</code></em> contains a trailing partial character. If an error occurs then the index of the invalid input is stored here. </p></td> <td class="parameter_annotations"><span class="annotation">[<acronym title="NULL is OK, both for passing and for returning."><span class="acronym">allow-none</span></acronym>]</span></td> </tr> <tr> <td class="parameter_name"><p>items_written</p></td> <td class="parameter_description"><p> location to store number of <a class="link" href="glib-Unicode-Manipulation.html#gunichar2" title="gunichar2"><span class="type">gunichar2</span></a> written, or <a class="link" href="glib-Standard-Macros.html#NULL:CAPS" title="NULL"><code class="literal">NULL</code></a>. The value stored here does not include the trailing 0. </p></td> <td class="parameter_annotations"><span class="annotation">[<acronym title="NULL is OK, both for passing and for returning."><span class="acronym">allow-none</span></acronym>]</span></td> </tr> <tr> <td class="parameter_name"><p>error</p></td> <td class="parameter_description"><p>location to store the error occurring, or <a class="link" href="glib-Standard-Macros.html#NULL:CAPS" title="NULL"><code class="literal">NULL</code></a> to ignore errors. Any of the errors in <a class="link" href="glib-Character-Set-Conversion.html#GConvertError" title="enum GConvertError"><span class="type">GConvertError</span></a> other than <a class="link" href="glib-Character-Set-Conversion.html#G-CONVERT-ERROR-NO-CONVERSION:CAPS"><code class="literal">G_CONVERT_ERROR_NO_CONVERSION</code></a> may occur.</p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.5.4.7.59.6"></a><h4>Returns</h4> <p> a pointer to a newly allocated UTF-16 string. This value must be freed with <a class="link" href="glib-Memory-Allocation.html#g-free" title="g_free ()"><code class="function">g_free()</code></a>. If an error occurs, <a class="link" href="glib-Standard-Macros.html#NULL:CAPS" title="NULL"><code class="literal">NULL</code></a> will be returned and <em class="parameter"><code>error</code></em> set.</p> </div> </div> <hr> <div class="refsect2"> <a name="g-utf8-to-ucs4"></a><h3>g_utf8_to_ucs4 ()</h3> <pre class="programlisting"><a class="link" href="glib-Unicode-Manipulation.html#gunichar" title="gunichar"><span class="returnvalue">gunichar</span></a> * g_utf8_to_ucs4 (<em class="parameter"><code>const <a class="link" href="glib-Basic-Types.html#gchar" title="gchar"><span class="type">gchar</span></a> *str</code></em>, <em class="parameter"><code><a class="link" href="glib-Basic-Types.html#glong" title="glong"><span class="type">glong</span></a> len</code></em>, <em class="parameter"><code><a class="link" href="glib-Basic-Types.html#glong" title="glong"><span class="type">glong</span></a> *items_read</code></em>, <em class="parameter"><code><a class="link" href="glib-Basic-Types.html#glong" title="glong"><span class="type">glong</span></a> *items_written</code></em>, <em class="parameter"><code><a class="link" href="glib-Error-Reporting.html#GError" title="struct GError"><span class="type">GError</span></a> **error</code></em>);</pre> <p>Convert a string from UTF-8 to a 32-bit fixed width representation as UCS-4. A trailing 0 character will be added to the string after the converted text.</p> <div class="refsect3"> <a name="id-1.5.4.7.60.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>str</p></td> <td class="parameter_description"><p>a UTF-8 encoded string</p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>len</p></td> <td class="parameter_description"><p>the maximum length of <em class="parameter"><code>str</code></em> to use, in bytes. If <em class="parameter"><code>len</code></em> &lt; 0, then the string is nul-terminated.</p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>items_read</p></td> <td class="parameter_description"><p> location to store number of bytes read, or <a class="link" href="glib-Standard-Macros.html#NULL:CAPS" title="NULL"><code class="literal">NULL</code></a>. If <a class="link" href="glib-Standard-Macros.html#NULL:CAPS" title="NULL"><code class="literal">NULL</code></a>, then <a class="link" href="glib-Character-Set-Conversion.html#G-CONVERT-ERROR-PARTIAL-INPUT:CAPS"><code class="literal">G_CONVERT_ERROR_PARTIAL_INPUT</code></a> will be returned in case <em class="parameter"><code>str</code></em> contains a trailing partial character. If an error occurs then the index of the invalid input is stored here. </p></td> <td class="parameter_annotations"><span class="annotation">[<acronym title="NULL is OK, both for passing and for returning."><span class="acronym">allow-none</span></acronym>]</span></td> </tr> <tr> <td class="parameter_name"><p>items_written</p></td> <td class="parameter_description"><p> location to store number of characters written or <a class="link" href="glib-Standard-Macros.html#NULL:CAPS" title="NULL"><code class="literal">NULL</code></a>. The value here stored does not include the trailing 0 character. </p></td> <td class="parameter_annotations"><span class="annotation">[<acronym title="NULL is OK, both for passing and for returning."><span class="acronym">allow-none</span></acronym>]</span></td> </tr> <tr> <td class="parameter_name"><p>error</p></td> <td class="parameter_description"><p>location to store the error occurring, or <a class="link" href="glib-Standard-Macros.html#NULL:CAPS" title="NULL"><code class="literal">NULL</code></a> to ignore errors. Any of the errors in <a class="link" href="glib-Character-Set-Conversion.html#GConvertError" title="enum GConvertError"><span class="type">GConvertError</span></a> other than <a class="link" href="glib-Character-Set-Conversion.html#G-CONVERT-ERROR-NO-CONVERSION:CAPS"><code class="literal">G_CONVERT_ERROR_NO_CONVERSION</code></a> may occur.</p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.5.4.7.60.6"></a><h4>Returns</h4> <p> a pointer to a newly allocated UCS-4 string. This value must be freed with <a class="link" href="glib-Memory-Allocation.html#g-free" title="g_free ()"><code class="function">g_free()</code></a>. If an error occurs, <a class="link" href="glib-Standard-Macros.html#NULL:CAPS" title="NULL"><code class="literal">NULL</code></a> will be returned and <em class="parameter"><code>error</code></em> set.</p> </div> </div> <hr> <div class="refsect2"> <a name="g-utf8-to-ucs4-fast"></a><h3>g_utf8_to_ucs4_fast ()</h3> <pre class="programlisting"><a class="link" href="glib-Unicode-Manipulation.html#gunichar" title="gunichar"><span class="returnvalue">gunichar</span></a> * g_utf8_to_ucs4_fast (<em class="parameter"><code>const <a class="link" href="glib-Basic-Types.html#gchar" title="gchar"><span class="type">gchar</span></a> *str</code></em>, <em class="parameter"><code><a class="link" href="glib-Basic-Types.html#glong" title="glong"><span class="type">glong</span></a> len</code></em>, <em class="parameter"><code><a class="link" href="glib-Basic-Types.html#glong" title="glong"><span class="type">glong</span></a> *items_written</code></em>);</pre> <p>Convert a string from UTF-8 to a 32-bit fixed width representation as UCS-4, assuming valid UTF-8 input. This function is roughly twice as fast as <a class="link" href="glib-Unicode-Manipulation.html#g-utf8-to-ucs4" title="g_utf8_to_ucs4 ()"><code class="function">g_utf8_to_ucs4()</code></a> but does no error checking on the input. A trailing 0 character will be added to the string after the converted text.</p> <div class="refsect3"> <a name="id-1.5.4.7.61.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>str</p></td> <td class="parameter_description"><p>a UTF-8 encoded string</p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>len</p></td> <td class="parameter_description"><p>the maximum length of <em class="parameter"><code>str</code></em> to use, in bytes. If <em class="parameter"><code>len</code></em> &lt; 0, then the string is nul-terminated.</p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>items_written</p></td> <td class="parameter_description"><p> location to store the number of characters in the result, or <a class="link" href="glib-Standard-Macros.html#NULL:CAPS" title="NULL"><code class="literal">NULL</code></a>. </p></td> <td class="parameter_annotations"><span class="annotation">[<acronym title="NULL is OK, both for passing and for returning."><span class="acronym">allow-none</span></acronym>]</span></td> </tr> </tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.5.4.7.61.6"></a><h4>Returns</h4> <p> a pointer to a newly allocated UCS-4 string. This value must be freed with <a class="link" href="glib-Memory-Allocation.html#g-free" title="g_free ()"><code class="function">g_free()</code></a>.</p> </div> </div> <hr> <div class="refsect2"> <a name="g-utf16-to-ucs4"></a><h3>g_utf16_to_ucs4 ()</h3> <pre class="programlisting"><a class="link" href="glib-Unicode-Manipulation.html#gunichar" title="gunichar"><span class="returnvalue">gunichar</span></a> * g_utf16_to_ucs4 (<em class="parameter"><code>const <a class="link" href="glib-Unicode-Manipulation.html#gunichar2" title="gunichar2"><span class="type">gunichar2</span></a> *str</code></em>, <em class="parameter"><code><a class="link" href="glib-Basic-Types.html#glong" title="glong"><span class="type">glong</span></a> len</code></em>, <em class="parameter"><code><a class="link" href="glib-Basic-Types.html#glong" title="glong"><span class="type">glong</span></a> *items_read</code></em>, <em class="parameter"><code><a class="link" href="glib-Basic-Types.html#glong" title="glong"><span class="type">glong</span></a> *items_written</code></em>, <em class="parameter"><code><a class="link" href="glib-Error-Reporting.html#GError" title="struct GError"><span class="type">GError</span></a> **error</code></em>);</pre> <p>Convert a string from UTF-16 to UCS-4. The result will be nul-terminated.</p> <div class="refsect3"> <a name="id-1.5.4.7.62.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>str</p></td> <td class="parameter_description"><p>a UTF-16 encoded string</p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>len</p></td> <td class="parameter_description"><p>the maximum length (number of <a class="link" href="glib-Unicode-Manipulation.html#gunichar2" title="gunichar2"><span class="type">gunichar2</span></a>) of <em class="parameter"><code>str</code></em> to use. If <em class="parameter"><code>len</code></em> &lt; 0, then the string is nul-terminated.</p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>items_read</p></td> <td class="parameter_description"><p> location to store number of words read, or <a class="link" href="glib-Standard-Macros.html#NULL:CAPS" title="NULL"><code class="literal">NULL</code></a>. If <a class="link" href="glib-Standard-Macros.html#NULL:CAPS" title="NULL"><code class="literal">NULL</code></a>, then <a class="link" href="glib-Character-Set-Conversion.html#G-CONVERT-ERROR-PARTIAL-INPUT:CAPS"><code class="literal">G_CONVERT_ERROR_PARTIAL_INPUT</code></a> will be returned in case <em class="parameter"><code>str</code></em> contains a trailing partial character. If an error occurs then the index of the invalid input is stored here. </p></td> <td class="parameter_annotations"><span class="annotation">[<acronym title="NULL is OK, both for passing and for returning."><span class="acronym">allow-none</span></acronym>]</span></td> </tr> <tr> <td class="parameter_name"><p>items_written</p></td> <td class="parameter_description"><p> location to store number of characters written, or <a class="link" href="glib-Standard-Macros.html#NULL:CAPS" title="NULL"><code class="literal">NULL</code></a>. The value stored here does not include the trailing 0 character. </p></td> <td class="parameter_annotations"><span class="annotation">[<acronym title="NULL is OK, both for passing and for returning."><span class="acronym">allow-none</span></acronym>]</span></td> </tr> <tr> <td class="parameter_name"><p>error</p></td> <td class="parameter_description"><p>location to store the error occurring, or <a class="link" href="glib-Standard-Macros.html#NULL:CAPS" title="NULL"><code class="literal">NULL</code></a> to ignore errors. Any of the errors in <a class="link" href="glib-Character-Set-Conversion.html#GConvertError" title="enum GConvertError"><span class="type">GConvertError</span></a> other than <a class="link" href="glib-Character-Set-Conversion.html#G-CONVERT-ERROR-NO-CONVERSION:CAPS"><code class="literal">G_CONVERT_ERROR_NO_CONVERSION</code></a> may occur.</p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.5.4.7.62.6"></a><h4>Returns</h4> <p> a pointer to a newly allocated UCS-4 string. This value must be freed with <a class="link" href="glib-Memory-Allocation.html#g-free" title="g_free ()"><code class="function">g_free()</code></a>. If an error occurs, <a class="link" href="glib-Standard-Macros.html#NULL:CAPS" title="NULL"><code class="literal">NULL</code></a> will be returned and <em class="parameter"><code>error</code></em> set.</p> </div> </div> <hr> <div class="refsect2"> <a name="g-utf16-to-utf8"></a><h3>g_utf16_to_utf8 ()</h3> <pre class="programlisting"><a class="link" href="glib-Basic-Types.html#gchar" title="gchar"><span class="returnvalue">gchar</span></a> * g_utf16_to_utf8 (<em class="parameter"><code>const <a class="link" href="glib-Unicode-Manipulation.html#gunichar2" title="gunichar2"><span class="type">gunichar2</span></a> *str</code></em>, <em class="parameter"><code><a class="link" href="glib-Basic-Types.html#glong" title="glong"><span class="type">glong</span></a> len</code></em>, <em class="parameter"><code><a class="link" href="glib-Basic-Types.html#glong" title="glong"><span class="type">glong</span></a> *items_read</code></em>, <em class="parameter"><code><a class="link" href="glib-Basic-Types.html#glong" title="glong"><span class="type">glong</span></a> *items_written</code></em>, <em class="parameter"><code><a class="link" href="glib-Error-Reporting.html#GError" title="struct GError"><span class="type">GError</span></a> **error</code></em>);</pre> <p>Convert a string from UTF-16 to UTF-8. The result will be terminated with a 0 byte.</p> <p>Note that the input is expected to be already in native endianness, an initial byte-order-mark character is not handled specially. <a class="link" href="glib-Character-Set-Conversion.html#g-convert" title="g_convert ()"><code class="function">g_convert()</code></a> can be used to convert a byte buffer of UTF-16 data of ambiguous endianess.</p> <p>Further note that this function does not validate the result string; it may e.g. include embedded NUL characters. The only validation done by this function is to ensure that the input can be correctly interpreted as UTF-16, i.e. it doesn't contain things unpaired surrogates.</p> <div class="refsect3"> <a name="id-1.5.4.7.63.7"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>str</p></td> <td class="parameter_description"><p>a UTF-16 encoded string</p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>len</p></td> <td class="parameter_description"><p>the maximum length (number of <a class="link" href="glib-Unicode-Manipulation.html#gunichar2" title="gunichar2"><span class="type">gunichar2</span></a>) of <em class="parameter"><code>str</code></em> to use. If <em class="parameter"><code>len</code></em> &lt; 0, then the string is nul-terminated.</p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>items_read</p></td> <td class="parameter_description"><p> location to store number of words read, or <a class="link" href="glib-Standard-Macros.html#NULL:CAPS" title="NULL"><code class="literal">NULL</code></a>. If <a class="link" href="glib-Standard-Macros.html#NULL:CAPS" title="NULL"><code class="literal">NULL</code></a>, then <a class="link" href="glib-Character-Set-Conversion.html#G-CONVERT-ERROR-PARTIAL-INPUT:CAPS"><code class="literal">G_CONVERT_ERROR_PARTIAL_INPUT</code></a> will be returned in case <em class="parameter"><code>str</code></em> contains a trailing partial character. If an error occurs then the index of the invalid input is stored here. </p></td> <td class="parameter_annotations"><span class="annotation">[<acronym title="NULL is OK, both for passing and for returning."><span class="acronym">allow-none</span></acronym>]</span></td> </tr> <tr> <td class="parameter_name"><p>items_written</p></td> <td class="parameter_description"><p> location to store number of bytes written, or <a class="link" href="glib-Standard-Macros.html#NULL:CAPS" title="NULL"><code class="literal">NULL</code></a>. The value stored here does not include the trailing 0 byte. </p></td> <td class="parameter_annotations"><span class="annotation">[<acronym title="NULL is OK, both for passing and for returning."><span class="acronym">allow-none</span></acronym>]</span></td> </tr> <tr> <td class="parameter_name"><p>error</p></td> <td class="parameter_description"><p>location to store the error occurring, or <a class="link" href="glib-Standard-Macros.html#NULL:CAPS" title="NULL"><code class="literal">NULL</code></a> to ignore errors. Any of the errors in <a class="link" href="glib-Character-Set-Conversion.html#GConvertError" title="enum GConvertError"><span class="type">GConvertError</span></a> other than <a class="link" href="glib-Character-Set-Conversion.html#G-CONVERT-ERROR-NO-CONVERSION:CAPS"><code class="literal">G_CONVERT_ERROR_NO_CONVERSION</code></a> may occur.</p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.5.4.7.63.8"></a><h4>Returns</h4> <p> a pointer to a newly allocated UTF-8 string. This value must be freed with <a class="link" href="glib-Memory-Allocation.html#g-free" title="g_free ()"><code class="function">g_free()</code></a>. If an error occurs, <a class="link" href="glib-Standard-Macros.html#NULL:CAPS" title="NULL"><code class="literal">NULL</code></a> will be returned and <em class="parameter"><code>error</code></em> set.</p> </div> </div> <hr> <div class="refsect2"> <a name="g-ucs4-to-utf16"></a><h3>g_ucs4_to_utf16 ()</h3> <pre class="programlisting"><a class="link" href="glib-Unicode-Manipulation.html#gunichar2" title="gunichar2"><span class="returnvalue">gunichar2</span></a> * g_ucs4_to_utf16 (<em class="parameter"><code>const <a class="link" href="glib-Unicode-Manipulation.html#gunichar" title="gunichar"><span class="type">gunichar</span></a> *str</code></em>, <em class="parameter"><code><a class="link" href="glib-Basic-Types.html#glong" title="glong"><span class="type">glong</span></a> len</code></em>, <em class="parameter"><code><a class="link" href="glib-Basic-Types.html#glong" title="glong"><span class="type">glong</span></a> *items_read</code></em>, <em class="parameter"><code><a class="link" href="glib-Basic-Types.html#glong" title="glong"><span class="type">glong</span></a> *items_written</code></em>, <em class="parameter"><code><a class="link" href="glib-Error-Reporting.html#GError" title="struct GError"><span class="type">GError</span></a> **error</code></em>);</pre> <p>Convert a string from UCS-4 to UTF-16. A 0 character will be added to the result after the converted text.</p> <div class="refsect3"> <a name="id-1.5.4.7.64.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>str</p></td> <td class="parameter_description"><p>a UCS-4 encoded string</p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>len</p></td> <td class="parameter_description"><p>the maximum length (number of characters) of <em class="parameter"><code>str</code></em> to use. If <em class="parameter"><code>len</code></em> &lt; 0, then the string is nul-terminated.</p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>items_read</p></td> <td class="parameter_description"><p> location to store number of bytes read, or <a class="link" href="glib-Standard-Macros.html#NULL:CAPS" title="NULL"><code class="literal">NULL</code></a>. If an error occurs then the index of the invalid input is stored here. </p></td> <td class="parameter_annotations"><span class="annotation">[<acronym title="NULL is OK, both for passing and for returning."><span class="acronym">allow-none</span></acronym>]</span></td> </tr> <tr> <td class="parameter_name"><p>items_written</p></td> <td class="parameter_description"><p> location to store number of <a class="link" href="glib-Unicode-Manipulation.html#gunichar2" title="gunichar2"><span class="type">gunichar2</span></a> written, or <a class="link" href="glib-Standard-Macros.html#NULL:CAPS" title="NULL"><code class="literal">NULL</code></a>. The value stored here does not include the trailing 0. </p></td> <td class="parameter_annotations"><span class="annotation">[<acronym title="NULL is OK, both for passing and for returning."><span class="acronym">allow-none</span></acronym>]</span></td> </tr> <tr> <td class="parameter_name"><p>error</p></td> <td class="parameter_description"><p>location to store the error occurring, or <a class="link" href="glib-Standard-Macros.html#NULL:CAPS" title="NULL"><code class="literal">NULL</code></a> to ignore errors. Any of the errors in <a class="link" href="glib-Character-Set-Conversion.html#GConvertError" title="enum GConvertError"><span class="type">GConvertError</span></a> other than <a class="link" href="glib-Character-Set-Conversion.html#G-CONVERT-ERROR-NO-CONVERSION:CAPS"><code class="literal">G_CONVERT_ERROR_NO_CONVERSION</code></a> may occur.</p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.5.4.7.64.6"></a><h4>Returns</h4> <p> a pointer to a newly allocated UTF-16 string. This value must be freed with <a class="link" href="glib-Memory-Allocation.html#g-free" title="g_free ()"><code class="function">g_free()</code></a>. If an error occurs, <a class="link" href="glib-Standard-Macros.html#NULL:CAPS" title="NULL"><code class="literal">NULL</code></a> will be returned and <em class="parameter"><code>error</code></em> set.</p> </div> </div> <hr> <div class="refsect2"> <a name="g-ucs4-to-utf8"></a><h3>g_ucs4_to_utf8 ()</h3> <pre class="programlisting"><a class="link" href="glib-Basic-Types.html#gchar" title="gchar"><span class="returnvalue">gchar</span></a> * g_ucs4_to_utf8 (<em class="parameter"><code>const <a class="link" href="glib-Unicode-Manipulation.html#gunichar" title="gunichar"><span class="type">gunichar</span></a> *str</code></em>, <em class="parameter"><code><a class="link" href="glib-Basic-Types.html#glong" title="glong"><span class="type">glong</span></a> len</code></em>, <em class="parameter"><code><a class="link" href="glib-Basic-Types.html#glong" title="glong"><span class="type">glong</span></a> *items_read</code></em>, <em class="parameter"><code><a class="link" href="glib-Basic-Types.html#glong" title="glong"><span class="type">glong</span></a> *items_written</code></em>, <em class="parameter"><code><a class="link" href="glib-Error-Reporting.html#GError" title="struct GError"><span class="type">GError</span></a> **error</code></em>);</pre> <p>Convert a string from a 32-bit fixed width representation as UCS-4. to UTF-8. The result will be terminated with a 0 byte.</p> <div class="refsect3"> <a name="id-1.5.4.7.65.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>str</p></td> <td class="parameter_description"><p>a UCS-4 encoded string</p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>len</p></td> <td class="parameter_description"><p>the maximum length (number of characters) of <em class="parameter"><code>str</code></em> to use. If <em class="parameter"><code>len</code></em> &lt; 0, then the string is nul-terminated.</p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>items_read</p></td> <td class="parameter_description"><p> location to store number of characters read, or <a class="link" href="glib-Standard-Macros.html#NULL:CAPS" title="NULL"><code class="literal">NULL</code></a>. </p></td> <td class="parameter_annotations"><span class="annotation">[<acronym title="NULL is OK, both for passing and for returning."><span class="acronym">allow-none</span></acronym>]</span></td> </tr> <tr> <td class="parameter_name"><p>items_written</p></td> <td class="parameter_description"><p> location to store number of bytes written or <a class="link" href="glib-Standard-Macros.html#NULL:CAPS" title="NULL"><code class="literal">NULL</code></a>. The value here stored does not include the trailing 0 byte. </p></td> <td class="parameter_annotations"><span class="annotation">[<acronym title="NULL is OK, both for passing and for returning."><span class="acronym">allow-none</span></acronym>]</span></td> </tr> <tr> <td class="parameter_name"><p>error</p></td> <td class="parameter_description"><p>location to store the error occurring, or <a class="link" href="glib-Standard-Macros.html#NULL:CAPS" title="NULL"><code class="literal">NULL</code></a> to ignore errors. Any of the errors in <a class="link" href="glib-Character-Set-Conversion.html#GConvertError" title="enum GConvertError"><span class="type">GConvertError</span></a> other than <a class="link" href="glib-Character-Set-Conversion.html#G-CONVERT-ERROR-NO-CONVERSION:CAPS"><code class="literal">G_CONVERT_ERROR_NO_CONVERSION</code></a> may occur.</p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.5.4.7.65.6"></a><h4>Returns</h4> <p> a pointer to a newly allocated UTF-8 string. This value must be freed with <a class="link" href="glib-Memory-Allocation.html#g-free" title="g_free ()"><code class="function">g_free()</code></a>. If an error occurs, <a class="link" href="glib-Standard-Macros.html#NULL:CAPS" title="NULL"><code class="literal">NULL</code></a> will be returned and <em class="parameter"><code>error</code></em> set. In that case, <em class="parameter"><code>items_read</code></em> will be set to the position of the first invalid input character.</p> </div> </div> <hr> <div class="refsect2"> <a name="g-unichar-to-utf8"></a><h3>g_unichar_to_utf8 ()</h3> <pre class="programlisting"><a class="link" href="glib-Basic-Types.html#gint" title="gint"><span class="returnvalue">gint</span></a> g_unichar_to_utf8 (<em class="parameter"><code><a class="link" href="glib-Unicode-Manipulation.html#gunichar" title="gunichar"><span class="type">gunichar</span></a> c</code></em>, <em class="parameter"><code><a class="link" href="glib-Basic-Types.html#gchar" title="gchar"><span class="type">gchar</span></a> *outbuf</code></em>);</pre> <p>Converts a single character to UTF-8.</p> <div class="refsect3"> <a name="id-1.5.4.7.66.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>c</p></td> <td class="parameter_description"><p>a Unicode character code</p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>outbuf</p></td> <td class="parameter_description"><p>output buffer, must have at least 6 bytes of space. If <a class="link" href="glib-Standard-Macros.html#NULL:CAPS" title="NULL"><code class="literal">NULL</code></a>, the length will be computed and returned and nothing will be written to <em class="parameter"><code>outbuf</code></em> .</p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.5.4.7.66.6"></a><h4>Returns</h4> <p> number of bytes written</p> </div> </div> </div> <div class="refsect1"> <a name="glib-Unicode-Manipulation.other_details"></a><h2>Types and Values</h2> <div class="refsect2"> <a name="gunichar"></a><h3>gunichar</h3> <pre class="programlisting">typedef guint32 gunichar; </pre> <p>A type which can hold any UTF-32 or UCS-4 character code, also known as a Unicode code point.</p> <p>If you want to produce the UTF-8 representation of a <a class="link" href="glib-Unicode-Manipulation.html#gunichar" title="gunichar"><span class="type">gunichar</span></a>, use <a class="link" href="glib-Unicode-Manipulation.html#g-ucs4-to-utf8" title="g_ucs4_to_utf8 ()"><code class="function">g_ucs4_to_utf8()</code></a>. See also <a class="link" href="glib-Unicode-Manipulation.html#g-utf8-to-ucs4" title="g_utf8_to_ucs4 ()"><code class="function">g_utf8_to_ucs4()</code></a> for the reverse process.</p> <p>To print/scan values of this type as integer, use <a class="link" href="glib-Basic-Types.html#G-GINT32-MODIFIER:CAPS" title="G_GINT32_MODIFIER"><code class="literal">G_GINT32_MODIFIER</code></a> and/or <a class="link" href="glib-Basic-Types.html#G-GUINT32-FORMAT:CAPS" title="G_GUINT32_FORMAT"><code class="literal">G_GUINT32_FORMAT</code></a>.</p> <p>The notation to express a Unicode code point in running text is as a hexadecimal number with four to six digits and uppercase letters, prefixed by the string "U+". Leading zeros are omitted, unless the code point would have fewer than four hexadecimal digits. For example, "U+0041 LATIN CAPITAL LETTER A". To print a code point in the U+-notation, use the format string "U+%04"G_GINT32_FORMAT"X". To scan, use the format string "U+%06"G_GINT32_FORMAT"X".</p> <div class="informalexample"> <table class="listing_frame" border="0" cellpadding="0" cellspacing="0"> <tbody> <tr> <td class="listing_lines" align="right"><pre>1 2 3</pre></td> <td class="listing_code"><pre class="programlisting">gunichar c<span class="gtkdoc opt">;</span> <span class="function">sscanf</span> <span class="gtkdoc opt">(</span><span class="string">&quot;U+0041&quot;</span><span class="gtkdoc opt">,</span> <span class="string">&quot;U+%06&quot;</span>G_GINT32_FORMAT<span class="string">&quot;X&quot;</span><span class="gtkdoc opt">, &amp;</span>c<span class="gtkdoc opt">)</span> <span class="function"><a href="glib-Warnings-and-Assertions.html#g-print">g_print</a></span> <span class="gtkdoc opt">(</span><span class="string">&quot;Read U+%04&quot;</span>G_GINT32_FORMAT<span class="string">&quot;X&quot;</span><span class="gtkdoc opt">,</span> c<span class="gtkdoc opt">);</span></pre></td> </tr> </tbody> </table> </div> <p></p> </div> <hr> <div class="refsect2"> <a name="gunichar2"></a><h3>gunichar2</h3> <pre class="programlisting">typedef guint16 gunichar2; </pre> <p>A type which can hold any UTF-16 code point&lt;footnote id="utf16_surrogate_pairs"&gt;UTF-16 also has so called &lt;firstterm&gt;surrogate pairs&lt;/firstterm&gt; to encode characters beyond the BMP as pairs of 16bit numbers. Surrogate pairs cannot be stored in a single gunichar2 field, but all GLib functions accepting gunichar2 arrays will correctly interpret surrogate pairs.&lt;/footnote&gt;.</p> <p>To print/scan values of this type to/from text you need to convert to/from UTF-8, using <a class="link" href="glib-Unicode-Manipulation.html#g-utf16-to-utf8" title="g_utf16_to_utf8 ()"><code class="function">g_utf16_to_utf8()</code></a>/<a class="link" href="glib-Unicode-Manipulation.html#g-utf8-to-utf16" title="g_utf8_to_utf16 ()"><code class="function">g_utf8_to_utf16()</code></a>.</p> <p>To print/scan values of this type as integer, use <a class="link" href="glib-Basic-Types.html#G-GINT16-MODIFIER:CAPS" title="G_GINT16_MODIFIER"><code class="literal">G_GINT16_MODIFIER</code></a> and/or <a class="link" href="glib-Basic-Types.html#G-GUINT16-FORMAT:CAPS" title="G_GUINT16_FORMAT"><code class="literal">G_GUINT16_FORMAT</code></a>.</p> </div> <hr> <div class="refsect2"> <a name="G-UNICHAR-MAX-DECOMPOSITION-LENGTH:CAPS"></a><h3>G_UNICHAR_MAX_DECOMPOSITION_LENGTH</h3> <pre class="programlisting">#define G_UNICHAR_MAX_DECOMPOSITION_LENGTH 18 /* codepoints */ </pre> <p>The maximum length (in codepoints) of a compatibility or canonical decomposition of a single Unicode character.</p> <p>This is as defined by Unicode 6.1.</p> <p class="since">Since: <a class="link" href="api-index-2-32.html#api-index-2.32">2.32</a></p> </div> <hr> <div class="refsect2"> <a name="GUnicodeType"></a><h3>enum GUnicodeType</h3> <p>These are the possible character classifications from the Unicode specification. See &lt;ulink url="http://www.unicode.org/Public/UNIDATA/UnicodeData.html"&gt;http://www.unicode.org/Public/UNIDATA/UnicodeData.html&lt;/ulink&gt;.</p> <div class="refsect3"> <a name="id-1.5.4.8.5.4"></a><h4>Members</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="300px" class="enum_members_name"> <col class="enum_members_description"> <col width="200px" class="enum_members_annotations"> </colgroup> <tbody> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-CONTROL:CAPS"></a>G_UNICODE_CONTROL</p></td> <td class="enum_member_description"> <p>General category "Other, Control" (Cc)</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-FORMAT:CAPS"></a>G_UNICODE_FORMAT</p></td> <td class="enum_member_description"> <p>General category "Other, Format" (Cf)</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-UNASSIGNED:CAPS"></a>G_UNICODE_UNASSIGNED</p></td> <td class="enum_member_description"> <p>General category "Other, Not Assigned" (Cn)</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-PRIVATE-USE:CAPS"></a>G_UNICODE_PRIVATE_USE</p></td> <td class="enum_member_description"> <p>General category "Other, Private Use" (Co)</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SURROGATE:CAPS"></a>G_UNICODE_SURROGATE</p></td> <td class="enum_member_description"> <p>General category "Other, Surrogate" (Cs)</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-LOWERCASE-LETTER:CAPS"></a>G_UNICODE_LOWERCASE_LETTER</p></td> <td class="enum_member_description"> <p>General category "Letter, Lowercase" (Ll)</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-MODIFIER-LETTER:CAPS"></a>G_UNICODE_MODIFIER_LETTER</p></td> <td class="enum_member_description"> <p>General category "Letter, Modifier" (Lm)</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-OTHER-LETTER:CAPS"></a>G_UNICODE_OTHER_LETTER</p></td> <td class="enum_member_description"> <p>General category "Letter, Other" (Lo)</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-TITLECASE-LETTER:CAPS"></a>G_UNICODE_TITLECASE_LETTER</p></td> <td class="enum_member_description"> <p>General category "Letter, Titlecase" (Lt)</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-UPPERCASE-LETTER:CAPS"></a>G_UNICODE_UPPERCASE_LETTER</p></td> <td class="enum_member_description"> <p>General category "Letter, Uppercase" (Lu)</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SPACING-MARK:CAPS"></a>G_UNICODE_SPACING_MARK</p></td> <td class="enum_member_description"> <p>General category "Mark, Spacing" (Mc)</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-ENCLOSING-MARK:CAPS"></a>G_UNICODE_ENCLOSING_MARK</p></td> <td class="enum_member_description"> <p>General category "Mark, Enclosing" (Me)</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-NON-SPACING-MARK:CAPS"></a>G_UNICODE_NON_SPACING_MARK</p></td> <td class="enum_member_description"> <p>General category "Mark, Nonspacing" (Mn)</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-DECIMAL-NUMBER:CAPS"></a>G_UNICODE_DECIMAL_NUMBER</p></td> <td class="enum_member_description"> <p>General category "Number, Decimal Digit" (Nd)</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-LETTER-NUMBER:CAPS"></a>G_UNICODE_LETTER_NUMBER</p></td> <td class="enum_member_description"> <p>General category "Number, Letter" (Nl)</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-OTHER-NUMBER:CAPS"></a>G_UNICODE_OTHER_NUMBER</p></td> <td class="enum_member_description"> <p>General category "Number, Other" (No)</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-CONNECT-PUNCTUATION:CAPS"></a>G_UNICODE_CONNECT_PUNCTUATION</p></td> <td class="enum_member_description"> <p>General category "Punctuation, Connector" (Pc)</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-DASH-PUNCTUATION:CAPS"></a>G_UNICODE_DASH_PUNCTUATION</p></td> <td class="enum_member_description"> <p>General category "Punctuation, Dash" (Pd)</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-CLOSE-PUNCTUATION:CAPS"></a>G_UNICODE_CLOSE_PUNCTUATION</p></td> <td class="enum_member_description"> <p>General category "Punctuation, Close" (Pe)</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-FINAL-PUNCTUATION:CAPS"></a>G_UNICODE_FINAL_PUNCTUATION</p></td> <td class="enum_member_description"> <p>General category "Punctuation, Final quote" (Pf)</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-INITIAL-PUNCTUATION:CAPS"></a>G_UNICODE_INITIAL_PUNCTUATION</p></td> <td class="enum_member_description"> <p>General category "Punctuation, Initial quote" (Pi)</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-OTHER-PUNCTUATION:CAPS"></a>G_UNICODE_OTHER_PUNCTUATION</p></td> <td class="enum_member_description"> <p>General category "Punctuation, Other" (Po)</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-OPEN-PUNCTUATION:CAPS"></a>G_UNICODE_OPEN_PUNCTUATION</p></td> <td class="enum_member_description"> <p>General category "Punctuation, Open" (Ps)</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-CURRENCY-SYMBOL:CAPS"></a>G_UNICODE_CURRENCY_SYMBOL</p></td> <td class="enum_member_description"> <p>General category "Symbol, Currency" (Sc)</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-MODIFIER-SYMBOL:CAPS"></a>G_UNICODE_MODIFIER_SYMBOL</p></td> <td class="enum_member_description"> <p>General category "Symbol, Modifier" (Sk)</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-MATH-SYMBOL:CAPS"></a>G_UNICODE_MATH_SYMBOL</p></td> <td class="enum_member_description"> <p>General category "Symbol, Math" (Sm)</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-OTHER-SYMBOL:CAPS"></a>G_UNICODE_OTHER_SYMBOL</p></td> <td class="enum_member_description"> <p>General category "Symbol, Other" (So)</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-LINE-SEPARATOR:CAPS"></a>G_UNICODE_LINE_SEPARATOR</p></td> <td class="enum_member_description"> <p>General category "Separator, Line" (Zl)</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-PARAGRAPH-SEPARATOR:CAPS"></a>G_UNICODE_PARAGRAPH_SEPARATOR</p></td> <td class="enum_member_description"> <p>General category "Separator, Paragraph" (Zp)</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SPACE-SEPARATOR:CAPS"></a>G_UNICODE_SPACE_SEPARATOR</p></td> <td class="enum_member_description"> <p>General category "Separator, Space" (Zs)</p> </td> <td class="enum_member_annotations"> </td> </tr> </tbody> </table></div> </div> </div> <hr> <div class="refsect2"> <a name="G-UNICODE-COMBINING-MARK:CAPS"></a><h3>G_UNICODE_COMBINING_MARK</h3> <pre class="programlisting">#define G_UNICODE_COMBINING_MARK G_UNICODE_SPACING_MARK </pre> <div class="warning"> <p><code class="literal">G_UNICODE_COMBINING_MARK</code> has been deprecated since version 2.30 and should not be used in newly-written code.</p> <p>Use <a class="link" href="glib-Unicode-Manipulation.html#G-UNICODE-SPACING-MARK:CAPS"><code class="literal">G_UNICODE_SPACING_MARK</code></a>.</p> </div> <p>Older name for <a class="link" href="glib-Unicode-Manipulation.html#G-UNICODE-SPACING-MARK:CAPS"><code class="literal">G_UNICODE_SPACING_MARK</code></a>.</p> </div> <hr> <div class="refsect2"> <a name="GUnicodeBreakType"></a><h3>enum GUnicodeBreakType</h3> <p>These are the possible line break classifications.</p> <p>Since new unicode versions may add new types here, applications should be ready to handle unknown values. They may be regarded as <a class="link" href="glib-Unicode-Manipulation.html#G-UNICODE-BREAK-UNKNOWN:CAPS"><code class="literal">G_UNICODE_BREAK_UNKNOWN</code></a>.</p> <p>See &lt;ulink url="http://www.unicode.org/unicode/reports/tr14/"&gt;http://www.unicode.org/unicode/reports/tr14/&lt;/ulink&gt;.</p> <div class="refsect3"> <a name="id-1.5.4.8.7.6"></a><h4>Members</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="300px" class="enum_members_name"> <col class="enum_members_description"> <col width="200px" class="enum_members_annotations"> </colgroup> <tbody> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-BREAK-MANDATORY:CAPS"></a>G_UNICODE_BREAK_MANDATORY</p></td> <td class="enum_member_description"> <p>Mandatory Break (BK)</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-BREAK-CARRIAGE-RETURN:CAPS"></a>G_UNICODE_BREAK_CARRIAGE_RETURN</p></td> <td class="enum_member_description"> <p>Carriage Return (CR)</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-BREAK-LINE-FEED:CAPS"></a>G_UNICODE_BREAK_LINE_FEED</p></td> <td class="enum_member_description"> <p>Line Feed (LF)</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-BREAK-COMBINING-MARK:CAPS"></a>G_UNICODE_BREAK_COMBINING_MARK</p></td> <td class="enum_member_description"> <p>Attached Characters and Combining Marks (CM)</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-BREAK-SURROGATE:CAPS"></a>G_UNICODE_BREAK_SURROGATE</p></td> <td class="enum_member_description"> <p>Surrogates (SG)</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-BREAK-ZERO-WIDTH-SPACE:CAPS"></a>G_UNICODE_BREAK_ZERO_WIDTH_SPACE</p></td> <td class="enum_member_description"> <p>Zero Width Space (ZW)</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-BREAK-INSEPARABLE:CAPS"></a>G_UNICODE_BREAK_INSEPARABLE</p></td> <td class="enum_member_description"> <p>Inseparable (IN)</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-BREAK-NON-BREAKING-GLUE:CAPS"></a>G_UNICODE_BREAK_NON_BREAKING_GLUE</p></td> <td class="enum_member_description"> <p>Non-breaking ("Glue") (GL)</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-BREAK-CONTINGENT:CAPS"></a>G_UNICODE_BREAK_CONTINGENT</p></td> <td class="enum_member_description"> <p>Contingent Break Opportunity (CB)</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-BREAK-SPACE:CAPS"></a>G_UNICODE_BREAK_SPACE</p></td> <td class="enum_member_description"> <p>Space (SP)</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-BREAK-AFTER:CAPS"></a>G_UNICODE_BREAK_AFTER</p></td> <td class="enum_member_description"> <p>Break Opportunity After (BA)</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-BREAK-BEFORE:CAPS"></a>G_UNICODE_BREAK_BEFORE</p></td> <td class="enum_member_description"> <p>Break Opportunity Before (BB)</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-BREAK-BEFORE-AND-AFTER:CAPS"></a>G_UNICODE_BREAK_BEFORE_AND_AFTER</p></td> <td class="enum_member_description"> <p>Break Opportunity Before and After (B2)</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-BREAK-HYPHEN:CAPS"></a>G_UNICODE_BREAK_HYPHEN</p></td> <td class="enum_member_description"> <p>Hyphen (HY)</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-BREAK-NON-STARTER:CAPS"></a>G_UNICODE_BREAK_NON_STARTER</p></td> <td class="enum_member_description"> <p>Nonstarter (NS)</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-BREAK-OPEN-PUNCTUATION:CAPS"></a>G_UNICODE_BREAK_OPEN_PUNCTUATION</p></td> <td class="enum_member_description"> <p>Opening Punctuation (OP)</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-BREAK-CLOSE-PUNCTUATION:CAPS"></a>G_UNICODE_BREAK_CLOSE_PUNCTUATION</p></td> <td class="enum_member_description"> <p>Closing Punctuation (CL)</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-BREAK-QUOTATION:CAPS"></a>G_UNICODE_BREAK_QUOTATION</p></td> <td class="enum_member_description"> <p>Ambiguous Quotation (QU)</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-BREAK-EXCLAMATION:CAPS"></a>G_UNICODE_BREAK_EXCLAMATION</p></td> <td class="enum_member_description"> <p>Exclamation/Interrogation (EX)</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-BREAK-IDEOGRAPHIC:CAPS"></a>G_UNICODE_BREAK_IDEOGRAPHIC</p></td> <td class="enum_member_description"> <p>Ideographic (ID)</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-BREAK-NUMERIC:CAPS"></a>G_UNICODE_BREAK_NUMERIC</p></td> <td class="enum_member_description"> <p>Numeric (NU)</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-BREAK-INFIX-SEPARATOR:CAPS"></a>G_UNICODE_BREAK_INFIX_SEPARATOR</p></td> <td class="enum_member_description"> <p>Infix Separator (Numeric) (IS)</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-BREAK-SYMBOL:CAPS"></a>G_UNICODE_BREAK_SYMBOL</p></td> <td class="enum_member_description"> <p>Symbols Allowing Break After (SY)</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-BREAK-ALPHABETIC:CAPS"></a>G_UNICODE_BREAK_ALPHABETIC</p></td> <td class="enum_member_description"> <p>Ordinary Alphabetic and Symbol Characters (AL)</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-BREAK-PREFIX:CAPS"></a>G_UNICODE_BREAK_PREFIX</p></td> <td class="enum_member_description"> <p>Prefix (Numeric) (PR)</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-BREAK-POSTFIX:CAPS"></a>G_UNICODE_BREAK_POSTFIX</p></td> <td class="enum_member_description"> <p>Postfix (Numeric) (PO)</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-BREAK-COMPLEX-CONTEXT:CAPS"></a>G_UNICODE_BREAK_COMPLEX_CONTEXT</p></td> <td class="enum_member_description"> <p>Complex Content Dependent (South East Asian) (SA)</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-BREAK-AMBIGUOUS:CAPS"></a>G_UNICODE_BREAK_AMBIGUOUS</p></td> <td class="enum_member_description"> <p>Ambiguous (Alphabetic or Ideographic) (AI)</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-BREAK-UNKNOWN:CAPS"></a>G_UNICODE_BREAK_UNKNOWN</p></td> <td class="enum_member_description"> <p>Unknown (XX)</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-BREAK-NEXT-LINE:CAPS"></a>G_UNICODE_BREAK_NEXT_LINE</p></td> <td class="enum_member_description"> <p>Next Line (NL)</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-BREAK-WORD-JOINER:CAPS"></a>G_UNICODE_BREAK_WORD_JOINER</p></td> <td class="enum_member_description"> <p>Word Joiner (WJ)</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-BREAK-HANGUL-L-JAMO:CAPS"></a>G_UNICODE_BREAK_HANGUL_L_JAMO</p></td> <td class="enum_member_description"> <p>Hangul L Jamo (JL)</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-BREAK-HANGUL-V-JAMO:CAPS"></a>G_UNICODE_BREAK_HANGUL_V_JAMO</p></td> <td class="enum_member_description"> <p>Hangul V Jamo (JV)</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-BREAK-HANGUL-T-JAMO:CAPS"></a>G_UNICODE_BREAK_HANGUL_T_JAMO</p></td> <td class="enum_member_description"> <p>Hangul T Jamo (JT)</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-BREAK-HANGUL-LV-SYLLABLE:CAPS"></a>G_UNICODE_BREAK_HANGUL_LV_SYLLABLE</p></td> <td class="enum_member_description"> <p>Hangul LV Syllable (H2)</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-BREAK-HANGUL-LVT-SYLLABLE:CAPS"></a>G_UNICODE_BREAK_HANGUL_LVT_SYLLABLE</p></td> <td class="enum_member_description"> <p>Hangul LVT Syllable (H3)</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-BREAK-CLOSE-PARANTHESIS:CAPS"></a>G_UNICODE_BREAK_CLOSE_PARANTHESIS</p></td> <td class="enum_member_description"> <p>Closing Parenthesis (CP). Since 2.28</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-BREAK-CONDITIONAL-JAPANESE-STARTER:CAPS"></a>G_UNICODE_BREAK_CONDITIONAL_JAPANESE_STARTER</p></td> <td class="enum_member_description"> <p>Conditional Japanese Starter (CJ). Since: 2.32</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-BREAK-HEBREW-LETTER:CAPS"></a>G_UNICODE_BREAK_HEBREW_LETTER</p></td> <td class="enum_member_description"> <p>Hebrew Letter (HL). Since: 2.32</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-BREAK-REGIONAL-INDICATOR:CAPS"></a>G_UNICODE_BREAK_REGIONAL_INDICATOR</p></td> <td class="enum_member_description"> <p>Regional Indicator (RI). Since: 2.36</p> </td> <td class="enum_member_annotations"> </td> </tr> </tbody> </table></div> </div> </div> <hr> <div class="refsect2"> <a name="GUnicodeScript"></a><h3>enum GUnicodeScript</h3> <p>The <a class="link" href="glib-Unicode-Manipulation.html#GUnicodeScript" title="enum GUnicodeScript"><span class="type">GUnicodeScript</span></a> enumeration identifies different writing systems. The values correspond to the names as defined in the Unicode standard. The enumeration has been added in GLib 2.14, and is interchangeable with <span class="type">PangoScript</span>.</p> <p>Note that new types may be added in the future. Applications should be ready to handle unknown values. See &lt;ulink url="http://www.unicode.org/reports/tr24/"&gt;Unicode Standard Annex <span class="type">24</span>: Script names&lt;/ulink&gt;.</p> <div class="refsect3"> <a name="id-1.5.4.8.8.5"></a><h4>Members</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="300px" class="enum_members_name"> <col class="enum_members_description"> <col width="200px" class="enum_members_annotations"> </colgroup> <tbody> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-INVALID-CODE:CAPS"></a>G_UNICODE_SCRIPT_INVALID_CODE</p></td> <td class="enum_member_description"> <p> a value never returned from <a class="link" href="glib-Unicode-Manipulation.html#g-unichar-get-script" title="g_unichar_get_script ()"><code class="function">g_unichar_get_script()</code></a></p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-COMMON:CAPS"></a>G_UNICODE_SCRIPT_COMMON</p></td> <td class="enum_member_description"> <p>a character used by multiple different scripts</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-INHERITED:CAPS"></a>G_UNICODE_SCRIPT_INHERITED</p></td> <td class="enum_member_description"> <p>a mark glyph that takes its script from the base glyph to which it is attached</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-ARABIC:CAPS"></a>G_UNICODE_SCRIPT_ARABIC</p></td> <td class="enum_member_description"> <p>Arabic</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-ARMENIAN:CAPS"></a>G_UNICODE_SCRIPT_ARMENIAN</p></td> <td class="enum_member_description"> <p>Armenian</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-BENGALI:CAPS"></a>G_UNICODE_SCRIPT_BENGALI</p></td> <td class="enum_member_description"> <p>Bengali</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-BOPOMOFO:CAPS"></a>G_UNICODE_SCRIPT_BOPOMOFO</p></td> <td class="enum_member_description"> <p>Bopomofo</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-CHEROKEE:CAPS"></a>G_UNICODE_SCRIPT_CHEROKEE</p></td> <td class="enum_member_description"> <p>Cherokee</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-COPTIC:CAPS"></a>G_UNICODE_SCRIPT_COPTIC</p></td> <td class="enum_member_description"> <p>Coptic</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-CYRILLIC:CAPS"></a>G_UNICODE_SCRIPT_CYRILLIC</p></td> <td class="enum_member_description"> <p>Cyrillic</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-DESERET:CAPS"></a>G_UNICODE_SCRIPT_DESERET</p></td> <td class="enum_member_description"> <p>Deseret</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-DEVANAGARI:CAPS"></a>G_UNICODE_SCRIPT_DEVANAGARI</p></td> <td class="enum_member_description"> <p>Devanagari</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-ETHIOPIC:CAPS"></a>G_UNICODE_SCRIPT_ETHIOPIC</p></td> <td class="enum_member_description"> <p>Ethiopic</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-GEORGIAN:CAPS"></a>G_UNICODE_SCRIPT_GEORGIAN</p></td> <td class="enum_member_description"> <p>Georgian</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-GOTHIC:CAPS"></a>G_UNICODE_SCRIPT_GOTHIC</p></td> <td class="enum_member_description"> <p>Gothic</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-GREEK:CAPS"></a>G_UNICODE_SCRIPT_GREEK</p></td> <td class="enum_member_description"> <p>Greek</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-GUJARATI:CAPS"></a>G_UNICODE_SCRIPT_GUJARATI</p></td> <td class="enum_member_description"> <p>Gujarati</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-GURMUKHI:CAPS"></a>G_UNICODE_SCRIPT_GURMUKHI</p></td> <td class="enum_member_description"> <p>Gurmukhi</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-HAN:CAPS"></a>G_UNICODE_SCRIPT_HAN</p></td> <td class="enum_member_description"> <p>Han</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-HANGUL:CAPS"></a>G_UNICODE_SCRIPT_HANGUL</p></td> <td class="enum_member_description"> <p>Hangul</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-HEBREW:CAPS"></a>G_UNICODE_SCRIPT_HEBREW</p></td> <td class="enum_member_description"> <p>Hebrew</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-HIRAGANA:CAPS"></a>G_UNICODE_SCRIPT_HIRAGANA</p></td> <td class="enum_member_description"> <p>Hiragana</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-KANNADA:CAPS"></a>G_UNICODE_SCRIPT_KANNADA</p></td> <td class="enum_member_description"> <p>Kannada</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-KATAKANA:CAPS"></a>G_UNICODE_SCRIPT_KATAKANA</p></td> <td class="enum_member_description"> <p>Katakana</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-KHMER:CAPS"></a>G_UNICODE_SCRIPT_KHMER</p></td> <td class="enum_member_description"> <p>Khmer</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-LAO:CAPS"></a>G_UNICODE_SCRIPT_LAO</p></td> <td class="enum_member_description"> <p>Lao</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-LATIN:CAPS"></a>G_UNICODE_SCRIPT_LATIN</p></td> <td class="enum_member_description"> <p>Latin</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-MALAYALAM:CAPS"></a>G_UNICODE_SCRIPT_MALAYALAM</p></td> <td class="enum_member_description"> <p>Malayalam</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-MONGOLIAN:CAPS"></a>G_UNICODE_SCRIPT_MONGOLIAN</p></td> <td class="enum_member_description"> <p>Mongolian</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-MYANMAR:CAPS"></a>G_UNICODE_SCRIPT_MYANMAR</p></td> <td class="enum_member_description"> <p>Myanmar</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-OGHAM:CAPS"></a>G_UNICODE_SCRIPT_OGHAM</p></td> <td class="enum_member_description"> <p>Ogham</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-OLD-ITALIC:CAPS"></a>G_UNICODE_SCRIPT_OLD_ITALIC</p></td> <td class="enum_member_description"> <p>Old Italic</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-ORIYA:CAPS"></a>G_UNICODE_SCRIPT_ORIYA</p></td> <td class="enum_member_description"> <p>Oriya</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-RUNIC:CAPS"></a>G_UNICODE_SCRIPT_RUNIC</p></td> <td class="enum_member_description"> <p>Runic</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-SINHALA:CAPS"></a>G_UNICODE_SCRIPT_SINHALA</p></td> <td class="enum_member_description"> <p>Sinhala</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-SYRIAC:CAPS"></a>G_UNICODE_SCRIPT_SYRIAC</p></td> <td class="enum_member_description"> <p>Syriac</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-TAMIL:CAPS"></a>G_UNICODE_SCRIPT_TAMIL</p></td> <td class="enum_member_description"> <p>Tamil</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-TELUGU:CAPS"></a>G_UNICODE_SCRIPT_TELUGU</p></td> <td class="enum_member_description"> <p>Telugu</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-THAANA:CAPS"></a>G_UNICODE_SCRIPT_THAANA</p></td> <td class="enum_member_description"> <p>Thaana</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-THAI:CAPS"></a>G_UNICODE_SCRIPT_THAI</p></td> <td class="enum_member_description"> <p>Thai</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-TIBETAN:CAPS"></a>G_UNICODE_SCRIPT_TIBETAN</p></td> <td class="enum_member_description"> <p>Tibetan</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-CANADIAN-ABORIGINAL:CAPS"></a>G_UNICODE_SCRIPT_CANADIAN_ABORIGINAL</p></td> <td class="enum_member_description"> <p> Canadian Aboriginal</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-YI:CAPS"></a>G_UNICODE_SCRIPT_YI</p></td> <td class="enum_member_description"> <p>Yi</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-TAGALOG:CAPS"></a>G_UNICODE_SCRIPT_TAGALOG</p></td> <td class="enum_member_description"> <p>Tagalog</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-HANUNOO:CAPS"></a>G_UNICODE_SCRIPT_HANUNOO</p></td> <td class="enum_member_description"> <p>Hanunoo</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-BUHID:CAPS"></a>G_UNICODE_SCRIPT_BUHID</p></td> <td class="enum_member_description"> <p>Buhid</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-TAGBANWA:CAPS"></a>G_UNICODE_SCRIPT_TAGBANWA</p></td> <td class="enum_member_description"> <p>Tagbanwa</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-BRAILLE:CAPS"></a>G_UNICODE_SCRIPT_BRAILLE</p></td> <td class="enum_member_description"> <p>Braille</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-CYPRIOT:CAPS"></a>G_UNICODE_SCRIPT_CYPRIOT</p></td> <td class="enum_member_description"> <p>Cypriot</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-LIMBU:CAPS"></a>G_UNICODE_SCRIPT_LIMBU</p></td> <td class="enum_member_description"> <p>Limbu</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-OSMANYA:CAPS"></a>G_UNICODE_SCRIPT_OSMANYA</p></td> <td class="enum_member_description"> <p>Osmanya</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-SHAVIAN:CAPS"></a>G_UNICODE_SCRIPT_SHAVIAN</p></td> <td class="enum_member_description"> <p>Shavian</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-LINEAR-B:CAPS"></a>G_UNICODE_SCRIPT_LINEAR_B</p></td> <td class="enum_member_description"> <p>Linear B</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-TAI-LE:CAPS"></a>G_UNICODE_SCRIPT_TAI_LE</p></td> <td class="enum_member_description"> <p>Tai Le</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-UGARITIC:CAPS"></a>G_UNICODE_SCRIPT_UGARITIC</p></td> <td class="enum_member_description"> <p>Ugaritic</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-NEW-TAI-LUE:CAPS"></a>G_UNICODE_SCRIPT_NEW_TAI_LUE</p></td> <td class="enum_member_description"> <p> New Tai Lue</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-BUGINESE:CAPS"></a>G_UNICODE_SCRIPT_BUGINESE</p></td> <td class="enum_member_description"> <p>Buginese</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-GLAGOLITIC:CAPS"></a>G_UNICODE_SCRIPT_GLAGOLITIC</p></td> <td class="enum_member_description"> <p>Glagolitic</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-TIFINAGH:CAPS"></a>G_UNICODE_SCRIPT_TIFINAGH</p></td> <td class="enum_member_description"> <p>Tifinagh</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-SYLOTI-NAGRI:CAPS"></a>G_UNICODE_SCRIPT_SYLOTI_NAGRI</p></td> <td class="enum_member_description"> <p> Syloti Nagri</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-OLD-PERSIAN:CAPS"></a>G_UNICODE_SCRIPT_OLD_PERSIAN</p></td> <td class="enum_member_description"> <p> Old Persian</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-KHAROSHTHI:CAPS"></a>G_UNICODE_SCRIPT_KHAROSHTHI</p></td> <td class="enum_member_description"> <p>Kharoshthi</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-UNKNOWN:CAPS"></a>G_UNICODE_SCRIPT_UNKNOWN</p></td> <td class="enum_member_description"> <p>an unassigned code point</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-BALINESE:CAPS"></a>G_UNICODE_SCRIPT_BALINESE</p></td> <td class="enum_member_description"> <p>Balinese</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-CUNEIFORM:CAPS"></a>G_UNICODE_SCRIPT_CUNEIFORM</p></td> <td class="enum_member_description"> <p>Cuneiform</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-PHOENICIAN:CAPS"></a>G_UNICODE_SCRIPT_PHOENICIAN</p></td> <td class="enum_member_description"> <p>Phoenician</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-PHAGS-PA:CAPS"></a>G_UNICODE_SCRIPT_PHAGS_PA</p></td> <td class="enum_member_description"> <p>Phags-pa</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-NKO:CAPS"></a>G_UNICODE_SCRIPT_NKO</p></td> <td class="enum_member_description"> <p>N'Ko</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-KAYAH-LI:CAPS"></a>G_UNICODE_SCRIPT_KAYAH_LI</p></td> <td class="enum_member_description"> <p>Kayah Li. Since 2.16.3</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-LEPCHA:CAPS"></a>G_UNICODE_SCRIPT_LEPCHA</p></td> <td class="enum_member_description"> <p>Lepcha. Since 2.16.3</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-REJANG:CAPS"></a>G_UNICODE_SCRIPT_REJANG</p></td> <td class="enum_member_description"> <p>Rejang. Since 2.16.3</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-SUNDANESE:CAPS"></a>G_UNICODE_SCRIPT_SUNDANESE</p></td> <td class="enum_member_description"> <p>Sundanese. Since 2.16.3</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-SAURASHTRA:CAPS"></a>G_UNICODE_SCRIPT_SAURASHTRA</p></td> <td class="enum_member_description"> <p>Saurashtra. Since 2.16.3</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-CHAM:CAPS"></a>G_UNICODE_SCRIPT_CHAM</p></td> <td class="enum_member_description"> <p>Cham. Since 2.16.3</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-OL-CHIKI:CAPS"></a>G_UNICODE_SCRIPT_OL_CHIKI</p></td> <td class="enum_member_description"> <p>Ol Chiki. Since 2.16.3</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-VAI:CAPS"></a>G_UNICODE_SCRIPT_VAI</p></td> <td class="enum_member_description"> <p>Vai. Since 2.16.3</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-CARIAN:CAPS"></a>G_UNICODE_SCRIPT_CARIAN</p></td> <td class="enum_member_description"> <p>Carian. Since 2.16.3</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-LYCIAN:CAPS"></a>G_UNICODE_SCRIPT_LYCIAN</p></td> <td class="enum_member_description"> <p>Lycian. Since 2.16.3</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-LYDIAN:CAPS"></a>G_UNICODE_SCRIPT_LYDIAN</p></td> <td class="enum_member_description"> <p>Lydian. Since 2.16.3</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-AVESTAN:CAPS"></a>G_UNICODE_SCRIPT_AVESTAN</p></td> <td class="enum_member_description"> <p>Avestan. Since 2.26</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-BAMUM:CAPS"></a>G_UNICODE_SCRIPT_BAMUM</p></td> <td class="enum_member_description"> <p>Bamum. Since 2.26</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-EGYPTIAN-HIEROGLYPHS:CAPS"></a>G_UNICODE_SCRIPT_EGYPTIAN_HIEROGLYPHS</p></td> <td class="enum_member_description"> <p> Egyptian Hieroglpyhs. Since 2.26</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-IMPERIAL-ARAMAIC:CAPS"></a>G_UNICODE_SCRIPT_IMPERIAL_ARAMAIC</p></td> <td class="enum_member_description"> <p> Imperial Aramaic. Since 2.26</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-INSCRIPTIONAL-PAHLAVI:CAPS"></a>G_UNICODE_SCRIPT_INSCRIPTIONAL_PAHLAVI</p></td> <td class="enum_member_description"> <p> Inscriptional Pahlavi. Since 2.26</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-INSCRIPTIONAL-PARTHIAN:CAPS"></a>G_UNICODE_SCRIPT_INSCRIPTIONAL_PARTHIAN</p></td> <td class="enum_member_description"> <p> Inscriptional Parthian. Since 2.26</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-JAVANESE:CAPS"></a>G_UNICODE_SCRIPT_JAVANESE</p></td> <td class="enum_member_description"> <p>Javanese. Since 2.26</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-KAITHI:CAPS"></a>G_UNICODE_SCRIPT_KAITHI</p></td> <td class="enum_member_description"> <p>Kaithi. Since 2.26</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-LISU:CAPS"></a>G_UNICODE_SCRIPT_LISU</p></td> <td class="enum_member_description"> <p>Lisu. Since 2.26</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-MEETEI-MAYEK:CAPS"></a>G_UNICODE_SCRIPT_MEETEI_MAYEK</p></td> <td class="enum_member_description"> <p> Meetei Mayek. Since 2.26</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-OLD-SOUTH-ARABIAN:CAPS"></a>G_UNICODE_SCRIPT_OLD_SOUTH_ARABIAN</p></td> <td class="enum_member_description"> <p> Old South Arabian. Since 2.26</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-OLD-TURKIC:CAPS"></a>G_UNICODE_SCRIPT_OLD_TURKIC</p></td> <td class="enum_member_description"> <p>Old Turkic. Since 2.28</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-SAMARITAN:CAPS"></a>G_UNICODE_SCRIPT_SAMARITAN</p></td> <td class="enum_member_description"> <p>Samaritan. Since 2.26</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-TAI-THAM:CAPS"></a>G_UNICODE_SCRIPT_TAI_THAM</p></td> <td class="enum_member_description"> <p>Tai Tham. Since 2.26</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-TAI-VIET:CAPS"></a>G_UNICODE_SCRIPT_TAI_VIET</p></td> <td class="enum_member_description"> <p>Tai Viet. Since 2.26</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-BATAK:CAPS"></a>G_UNICODE_SCRIPT_BATAK</p></td> <td class="enum_member_description"> <p>Batak. Since 2.28</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-BRAHMI:CAPS"></a>G_UNICODE_SCRIPT_BRAHMI</p></td> <td class="enum_member_description"> <p>Brahmi. Since 2.28</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-MANDAIC:CAPS"></a>G_UNICODE_SCRIPT_MANDAIC</p></td> <td class="enum_member_description"> <p>Mandaic. Since 2.28</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-CHAKMA:CAPS"></a>G_UNICODE_SCRIPT_CHAKMA</p></td> <td class="enum_member_description"> <p>Chakma. Since: 2.32</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-MEROITIC-CURSIVE:CAPS"></a>G_UNICODE_SCRIPT_MEROITIC_CURSIVE</p></td> <td class="enum_member_description"> <p>Meroitic Cursive. Since: 2.32</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-MEROITIC-HIEROGLYPHS:CAPS"></a>G_UNICODE_SCRIPT_MEROITIC_HIEROGLYPHS</p></td> <td class="enum_member_description"> <p>Meroitic Hieroglyphs. Since: 2.32</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-MIAO:CAPS"></a>G_UNICODE_SCRIPT_MIAO</p></td> <td class="enum_member_description"> <p>Miao. Since: 2.32</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-SHARADA:CAPS"></a>G_UNICODE_SCRIPT_SHARADA</p></td> <td class="enum_member_description"> <p>Sharada. Since: 2.32</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-SORA-SOMPENG:CAPS"></a>G_UNICODE_SCRIPT_SORA_SOMPENG</p></td> <td class="enum_member_description"> <p>Sora Sompeng. Since: 2.32</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-TAKRI:CAPS"></a>G_UNICODE_SCRIPT_TAKRI</p></td> <td class="enum_member_description"> <p>Takri. Since: 2.32</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-BASSA-VAH:CAPS"></a>G_UNICODE_SCRIPT_BASSA_VAH</p></td> <td class="enum_member_description"> <p>Bassa. Since: 2.42</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-CAUCASIAN-ALBANIAN:CAPS"></a>G_UNICODE_SCRIPT_CAUCASIAN_ALBANIAN</p></td> <td class="enum_member_description"> <p>Caucasian Albanian. Since: 2.42</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-DUPLOYAN:CAPS"></a>G_UNICODE_SCRIPT_DUPLOYAN</p></td> <td class="enum_member_description"> <p>Duployan. Since: 2.42</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-ELBASAN:CAPS"></a>G_UNICODE_SCRIPT_ELBASAN</p></td> <td class="enum_member_description"> <p>Elbasan. Since: 2.42</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-GRANTHA:CAPS"></a>G_UNICODE_SCRIPT_GRANTHA</p></td> <td class="enum_member_description"> <p>Grantha. Since: 2.42</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-KHOJKI:CAPS"></a>G_UNICODE_SCRIPT_KHOJKI</p></td> <td class="enum_member_description"> <p>Kjohki. Since: 2.42</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-KHUDAWADI:CAPS"></a>G_UNICODE_SCRIPT_KHUDAWADI</p></td> <td class="enum_member_description"> <p>Khudawadi, Sindhi. Since: 2.42</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-LINEAR-A:CAPS"></a>G_UNICODE_SCRIPT_LINEAR_A</p></td> <td class="enum_member_description"> <p>Linear A. Since: 2.42</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-MAHAJANI:CAPS"></a>G_UNICODE_SCRIPT_MAHAJANI</p></td> <td class="enum_member_description"> <p>Mahajani. Since: 2.42</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-MANICHAEAN:CAPS"></a>G_UNICODE_SCRIPT_MANICHAEAN</p></td> <td class="enum_member_description"> <p>Manichaean. Since: 2.42</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-MENDE-KIKAKUI:CAPS"></a>G_UNICODE_SCRIPT_MENDE_KIKAKUI</p></td> <td class="enum_member_description"> <p>Mende Kikakui. Since: 2.42</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-MODI:CAPS"></a>G_UNICODE_SCRIPT_MODI</p></td> <td class="enum_member_description"> <p>Modi. Since: 2.42</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-MRO:CAPS"></a>G_UNICODE_SCRIPT_MRO</p></td> <td class="enum_member_description"> <p>Mro. Since: 2.42</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-NABATAEAN:CAPS"></a>G_UNICODE_SCRIPT_NABATAEAN</p></td> <td class="enum_member_description"> <p>Nabataean. Since: 2.42</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-OLD-NORTH-ARABIAN:CAPS"></a>G_UNICODE_SCRIPT_OLD_NORTH_ARABIAN</p></td> <td class="enum_member_description"> <p>Old North Arabian. Since: 2.42</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-OLD-PERMIC:CAPS"></a>G_UNICODE_SCRIPT_OLD_PERMIC</p></td> <td class="enum_member_description"> <p>Old Permic. Since: 2.42</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-PAHAWH-HMONG:CAPS"></a>G_UNICODE_SCRIPT_PAHAWH_HMONG</p></td> <td class="enum_member_description"> <p>Pahawh Hmong. Since: 2.42</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-PALMYRENE:CAPS"></a>G_UNICODE_SCRIPT_PALMYRENE</p></td> <td class="enum_member_description"> <p>Palmyrene. Since: 2.42</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-PAU-CIN-HAU:CAPS"></a>G_UNICODE_SCRIPT_PAU_CIN_HAU</p></td> <td class="enum_member_description"> <p>Pau Cin Hau. Since: 2.42</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-PSALTER-PAHLAVI:CAPS"></a>G_UNICODE_SCRIPT_PSALTER_PAHLAVI</p></td> <td class="enum_member_description"> <p>Psalter Pahlavi. Since: 2.42</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-SIDDHAM:CAPS"></a>G_UNICODE_SCRIPT_SIDDHAM</p></td> <td class="enum_member_description"> <p>Siddham. Since: 2.42</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-TIRHUTA:CAPS"></a>G_UNICODE_SCRIPT_TIRHUTA</p></td> <td class="enum_member_description"> <p>Tirhuta. Since: 2.42</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-UNICODE-SCRIPT-WARANG-CITI:CAPS"></a>G_UNICODE_SCRIPT_WARANG_CITI</p></td> <td class="enum_member_description"> <p>Warang Citi. Since: 2.42</p> </td> <td class="enum_member_annotations"> </td> </tr> </tbody> </table></div> </div> </div> <hr> <div class="refsect2"> <a name="GNormalizeMode"></a><h3>enum GNormalizeMode</h3> <p>Defines how a Unicode string is transformed in a canonical form, standardizing such issues as whether a character with an accent is represented as a base character and combining accent or as a single precomposed character. Unicode strings should generally be normalized before comparing them.</p> <div class="refsect3"> <a name="id-1.5.4.8.9.4"></a><h4>Members</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="300px" class="enum_members_name"> <col class="enum_members_description"> <col width="200px" class="enum_members_annotations"> </colgroup> <tbody> <tr> <td class="enum_member_name"><p><a name="G-NORMALIZE-DEFAULT:CAPS"></a>G_NORMALIZE_DEFAULT</p></td> <td class="enum_member_description"> <p>standardize differences that do not affect the text content, such as the above-mentioned accent representation</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-NORMALIZE-NFD:CAPS"></a>G_NORMALIZE_NFD</p></td> <td class="enum_member_description"> <p>another name for <a class="link" href="glib-Unicode-Manipulation.html#G-NORMALIZE-DEFAULT:CAPS"><code class="literal">G_NORMALIZE_DEFAULT</code></a></p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-NORMALIZE-DEFAULT-COMPOSE:CAPS"></a>G_NORMALIZE_DEFAULT_COMPOSE</p></td> <td class="enum_member_description"> <p>like <a class="link" href="glib-Unicode-Manipulation.html#G-NORMALIZE-DEFAULT:CAPS"><code class="literal">G_NORMALIZE_DEFAULT</code></a>, but with composed forms rather than a maximally decomposed form</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-NORMALIZE-NFC:CAPS"></a>G_NORMALIZE_NFC</p></td> <td class="enum_member_description"> <p>another name for <a class="link" href="glib-Unicode-Manipulation.html#G-NORMALIZE-DEFAULT-COMPOSE:CAPS"><code class="literal">G_NORMALIZE_DEFAULT_COMPOSE</code></a></p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-NORMALIZE-ALL:CAPS"></a>G_NORMALIZE_ALL</p></td> <td class="enum_member_description"> <p>beyond <a class="link" href="glib-Unicode-Manipulation.html#G-NORMALIZE-DEFAULT:CAPS"><code class="literal">G_NORMALIZE_DEFAULT</code></a> also standardize the "compatibility" characters in Unicode, such as SUPERSCRIPT THREE to the standard forms (in this case DIGIT THREE). Formatting information may be lost but for most text operations such characters should be considered the same</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-NORMALIZE-NFKD:CAPS"></a>G_NORMALIZE_NFKD</p></td> <td class="enum_member_description"> <p>another name for <a class="link" href="glib-Unicode-Manipulation.html#G-NORMALIZE-ALL:CAPS"><code class="literal">G_NORMALIZE_ALL</code></a></p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-NORMALIZE-ALL-COMPOSE:CAPS"></a>G_NORMALIZE_ALL_COMPOSE</p></td> <td class="enum_member_description"> <p>like <a class="link" href="glib-Unicode-Manipulation.html#G-NORMALIZE-ALL:CAPS"><code class="literal">G_NORMALIZE_ALL</code></a>, but with composed forms rather than a maximally decomposed form</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="G-NORMALIZE-NFKC:CAPS"></a>G_NORMALIZE_NFKC</p></td> <td class="enum_member_description"> <p>another name for <a class="link" href="glib-Unicode-Manipulation.html#G-NORMALIZE-ALL-COMPOSE:CAPS"><code class="literal">G_NORMALIZE_ALL_COMPOSE</code></a></p> </td> <td class="enum_member_annotations"> </td> </tr> </tbody> </table></div> </div> </div> </div> <div class="refsect1"> <a name="glib-Unicode-Manipulation.see-also"></a><h2>See Also</h2> <p>g_locale_to_utf8(), <a class="link" href="glib-Character-Set-Conversion.html#g-locale-from-utf8" title="g_locale_from_utf8 ()"><code class="function">g_locale_from_utf8()</code></a></p> </div> </div> <div class="footer"> <hr>Generated by GTK-Doc V1.24</div> </body> </html>
Java
package org.telegram.android.views.dialog; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.os.SystemClock; import android.text.TextPaint; import android.util.AttributeSet; import android.util.TypedValue; import android.view.View; import android.widget.AbsListView; import android.widget.HeaderViewListAdapter; import android.widget.ListAdapter; import android.widget.ListView; import org.telegram.android.R; import org.telegram.android.TelegramApplication; import org.telegram.android.log.Logger; import org.telegram.android.ui.FontController; import org.telegram.android.ui.TextUtil; /** * Created by ex3ndr on 15.11.13. */ public class ConversationListView extends ListView { private static final String TAG = "ConversationListView"; private static final int DELTA = 26; private static final long ANIMATION_DURATION = 200; private static final int ACTIVATE_DELTA = 50; private static final long UI_TIMEOUT = 900; private TelegramApplication application; private String visibleDate = null; private int formattedVisibleDate = -1; private int timeDivMeasure; private String visibleDateNext = null; private int formattedVisibleDateNext = -1; private int timeDivMeasureNext; private TextPaint timeDivPaint; private Drawable serviceDrawable; private Rect servicePadding; private int offset; private int oldHeight; private long animationTime = 0; private boolean isTimeVisible = false; private Handler handler = new Handler(Looper.getMainLooper()) { @Override public void handleMessage(Message msg) { Logger.d(TAG, "notify"); if (msg.what == 0) { if (isTimeVisible) { isTimeVisible = false; scrollDistance = 0; animationTime = SystemClock.uptimeMillis(); } invalidate(); } else if (msg.what == 1) { isTimeVisible = true; invalidate(); } } }; private int scrollDistance; public ConversationListView(Context context) { super(context); init(); } public ConversationListView(Context context, AttributeSet attrs) { super(context, attrs); init(); } public ConversationListView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(); } public VisibleViewItem[] dump() { int childCount = getChildCount(); int idCount = 0; int headerCount = 0; for (int i = 0; i < childCount; i++) { int index = getFirstVisiblePosition() + i; long id = getItemIdAtPosition(index); if (id > 0) { idCount++; } else { headerCount++; } } VisibleViewItem[] res = new VisibleViewItem[idCount]; int resIndex = 0; for (int i = 0; i < childCount; i++) { View v = getChildAt(i); int index = getFirstVisiblePosition() + i; long id = getItemIdAtPosition(index); if (id > 0) { int top = ((v == null) ? 0 : v.getTop()) - getPaddingTop(); res[resIndex++] = new VisibleViewItem(index + headerCount, top, id); } } return res; } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { VisibleViewItem[] items = null; if (changed) { items = dump(); } super.onLayout(changed, l, t, r, b); if (changed) { final int changeDelta = (b - t) - oldHeight; if (changeDelta < 0 && items.length > 0) { final VisibleViewItem item = items[items.length - 1]; setSelectionFromTop(item.getIndex(), item.getTop() + changeDelta); post(new Runnable() { @Override public void run() { setSelectionFromTop(item.getIndex(), item.getTop() + changeDelta); } }); } } oldHeight = b - t; } private void init() { application = (TelegramApplication) getContext().getApplicationContext(); setOnScrollListener(new ScrollListener()); serviceDrawable = getResources().getDrawable(R.drawable.st_bubble_service); servicePadding = new Rect(); serviceDrawable.getPadding(servicePadding); timeDivPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG | Paint.SUBPIXEL_TEXT_FLAG); timeDivPaint.setTextSize(getSp(15)); timeDivPaint.setColor(0xffFFFFFF); timeDivPaint.setTypeface(FontController.loadTypeface(getContext(), "regular")); } private void drawTime(Canvas canvas, int drawOffset, float alpha, boolean first) { int w = first ? timeDivMeasure : timeDivMeasureNext; serviceDrawable.setAlpha((int) (alpha * 255)); timeDivPaint.setAlpha((int) (alpha * 255)); serviceDrawable.setBounds( getWidth() / 2 - w / 2 - servicePadding.left, getPx(44 - 8) - serviceDrawable.getIntrinsicHeight() + drawOffset, getWidth() / 2 + w / 2 + servicePadding.right, getPx(44 - 8) + drawOffset); serviceDrawable.draw(canvas); canvas.drawText(first ? visibleDate : visibleDateNext, getWidth() / 2 - w / 2, getPx(44 - 17) + drawOffset, timeDivPaint); } @Override public void draw(Canvas canvas) { super.draw(canvas); boolean isAnimated = false; boolean isShown; if (isTimeVisible) { isShown = isTimeVisible; } else { isShown = SystemClock.uptimeMillis() - animationTime < ANIMATION_DURATION; } if (isShown) { float animationRatio = 1.0f; if (SystemClock.uptimeMillis() - animationTime < ANIMATION_DURATION) { isAnimated = true; animationRatio = (SystemClock.uptimeMillis() - animationTime) / ((float) ANIMATION_DURATION); if (animationRatio > 1.0f) { animationRatio = 1.0f; } if (!isTimeVisible) { animationRatio = 1.0f - animationRatio; } } int drawOffset = offset; if (offset == 0) { if (visibleDate != null) { drawTime(canvas, drawOffset, 1.0f * animationRatio, true); } } else { float ratio = Math.min(1.0f, Math.abs(offset / (float) getPx(DELTA))); if (visibleDateNext != null) { drawTime(canvas, drawOffset + getPx(DELTA), ratio * animationRatio, false); } if (visibleDate != null) { drawTime(canvas, drawOffset, (1.0f - ratio) * animationRatio, true); } } } if (isAnimated) { invalidate(); } } protected int getPx(float dp) { return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics()); } protected int getSp(float sp) { return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp, getResources().getDisplayMetrics()); } private class ScrollListener implements OnScrollListener { private int state = SCROLL_STATE_IDLE; private int lastVisibleItem = -1; private int lastTop = 0; private int lastScrollY = -1; @Override public void onScrollStateChanged(AbsListView absListView, int i) { if (i == SCROLL_STATE_FLING || i == SCROLL_STATE_TOUCH_SCROLL) { handler.removeMessages(0); } if (i == SCROLL_STATE_IDLE) { handler.removeMessages(0); handler.sendEmptyMessageDelayed(0, UI_TIMEOUT); } state = i; } @Override public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) { // if (lastScrollY == -1) { // lastScrollY = getScrollY(); // } else if (lastScrollY != getScrollY()) { // lastScrollY = getScrollY(); // application.getImageController().doPause(); // } if (lastVisibleItem == -1 || lastVisibleItem != firstVisibleItem || state == SCROLL_STATE_IDLE) { lastVisibleItem = firstVisibleItem; lastTop = 0; View view = getChildAt(0 + getHeaderViewsCount()); if (view != null) { lastTop = view.getTop(); } } else { View view = getChildAt(0 + getHeaderViewsCount()); if (view != null) { int topDelta = Math.abs(view.getTop() - lastTop); lastTop = view.getTop(); scrollDistance += topDelta; if (scrollDistance > getPx(ACTIVATE_DELTA) && !isTimeVisible) { isTimeVisible = true; animationTime = SystemClock.uptimeMillis(); handler.removeMessages(0); } } } // handler.removeMessages(0); ListAdapter adapter = getAdapter(); if (adapter instanceof HeaderViewListAdapter) { adapter = ((HeaderViewListAdapter) adapter).getWrappedAdapter(); } if (adapter instanceof ConversationAdapter) { if (firstVisibleItem == 0) { visibleDate = null; visibleDateNext = null; formattedVisibleDate = -1; formattedVisibleDateNext = -1; View view = getChildAt(1); if (view != null) { offset = Math.min(view.getTop() - getPx(DELTA), 0); if (adapter.getCount() > 0) { int date = ((ConversationAdapter) adapter).getItemDate(0); visibleDateNext = TextUtil.formatDateLong(date); timeDivMeasureNext = (int) timeDivPaint.measureText(visibleDateNext); } } return; } int realFirstVisibleItem = firstVisibleItem - getHeaderViewsCount(); if (realFirstVisibleItem >= 0 && realFirstVisibleItem < adapter.getCount()) { int date = ((ConversationAdapter) adapter).getItemDate(realFirstVisibleItem); int prevDate = date; boolean isSameDays = true; if (realFirstVisibleItem > 0 && realFirstVisibleItem + 2 < adapter.getCount()) { prevDate = ((ConversationAdapter) adapter).getItemDate(realFirstVisibleItem + 1); isSameDays = TextUtil.areSameDays(prevDate, date); } if (isSameDays) { offset = 0; } else { View view = getChildAt(firstVisibleItem - realFirstVisibleItem); if (view != null) { offset = Math.min(view.getTop() - getPx(DELTA), 0); } if (!TextUtil.areSameDays(prevDate, System.currentTimeMillis() / 1000)) { if (!TextUtil.areSameDays(prevDate, formattedVisibleDateNext)) { formattedVisibleDateNext = prevDate; visibleDateNext = TextUtil.formatDateLong(prevDate); timeDivMeasureNext = (int) timeDivPaint.measureText(visibleDateNext); } } else { visibleDateNext = null; formattedVisibleDateNext = -1; } } if (!TextUtil.areSameDays(date, System.currentTimeMillis() / 1000)) { if (!TextUtil.areSameDays(date, formattedVisibleDate)) { formattedVisibleDate = date; visibleDate = TextUtil.formatDateLong(date); timeDivMeasure = (int) timeDivPaint.measureText(visibleDate); } } else { visibleDate = null; formattedVisibleDate = -1; } } } } } }
Java
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2014 Torus Knot Software Ltd 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 "OgreOverlay.h" #include "OgreRoot.h" #include "OgreSceneManager.h" #include "OgreOverlayContainer.h" #include "OgreCamera.h" #include "OgreOverlayManager.h" #include "OgreQuaternion.h" #include "OgreVector3.h" namespace Ogre { //--------------------------------------------------------------------- Overlay::Overlay(const String& name) : mName(name), mRotate(0.0f), mScrollX(0.0f), mScrollY(0.0f), mScaleX(1.0f), mScaleY(1.0f), mTransformOutOfDate(true), mTransformUpdated(true), mZOrder(100), mVisible(false), mInitialised(false) { mRootNode = OGRE_NEW SceneNode(NULL); } //--------------------------------------------------------------------- Overlay::~Overlay() { // remove children OGRE_DELETE mRootNode; for (OverlayContainerList::iterator i = m2DElements.begin(); i != m2DElements.end(); ++i) { (*i)->_notifyParent(0, 0); } } //--------------------------------------------------------------------- const String& Overlay::getName(void) const { return mName; } //--------------------------------------------------------------------- void Overlay::assignZOrders() { ushort zorder = static_cast<ushort>(mZOrder * 100.0f); // Notify attached 2D elements OverlayContainerList::iterator i, iend; iend = m2DElements.end(); for (i = m2DElements.begin(); i != iend; ++i) { zorder = (*i)->_notifyZOrder(zorder); } } //--------------------------------------------------------------------- void Overlay::setZOrder(ushort zorder) { // Limit to 650 since this is multiplied by 100 to pad out for containers assert (zorder <= 650 && "Overlay Z-order cannot be greater than 650!"); mZOrder = zorder; assignZOrders(); } //--------------------------------------------------------------------- ushort Overlay::getZOrder(void) const { return (ushort)mZOrder; } //--------------------------------------------------------------------- bool Overlay::isVisible(void) const { return mVisible; } //--------------------------------------------------------------------- void Overlay::show(void) { mVisible = true; if (!mInitialised) { initialise(); } } //--------------------------------------------------------------------- void Overlay::hide(void) { mVisible = false; } //--------------------------------------------------------------------- void Overlay::initialise(void) { OverlayContainerList::iterator i, iend; iend = m2DElements.end(); for (i = m2DElements.begin(); i != m2DElements.end(); ++i) { (*i)->initialise(); } mInitialised = true; } //--------------------------------------------------------------------- void Overlay::add2D(OverlayContainer* cont) { m2DElements.push_back(cont); // Notify parent cont->_notifyParent(0, this); assignZOrders(); Matrix4 xform; _getWorldTransforms(&xform); cont->_notifyWorldTransforms(xform); cont->_notifyViewport(); } //--------------------------------------------------------------------- void Overlay::remove2D(OverlayContainer* cont) { m2DElements.remove(cont); cont->_notifyParent(0, 0); assignZOrders(); } //--------------------------------------------------------------------- void Overlay::add3D(SceneNode* node) { mRootNode->addChild(node); } //--------------------------------------------------------------------- void Overlay::remove3D(SceneNode* node) { mRootNode->removeChild(node->getName()); } //--------------------------------------------------------------------- void Overlay::clear(void) { mRootNode->removeAllChildren(); m2DElements.clear(); // Note no deallocation, memory handled by OverlayManager & SceneManager } //--------------------------------------------------------------------- void Overlay::setScroll(Real x, Real y) { mScrollX = x; mScrollY = y; mTransformOutOfDate = true; mTransformUpdated = true; } //--------------------------------------------------------------------- Real Overlay::getScrollX(void) const { return mScrollX; } //--------------------------------------------------------------------- Real Overlay::getScrollY(void) const { return mScrollY; } //--------------------------------------------------------------------- OverlayContainer* Overlay::getChild(const String& name) { OverlayContainerList::iterator i, iend; iend = m2DElements.end(); for (i = m2DElements.begin(); i != iend; ++i) { if ((*i)->getName() == name) { return *i; } } return NULL; } //--------------------------------------------------------------------- void Overlay::scroll(Real xoff, Real yoff) { mScrollX += xoff; mScrollY += yoff; mTransformOutOfDate = true; mTransformUpdated = true; } //--------------------------------------------------------------------- void Overlay::setRotate(const Radian& angle) { mRotate = angle; mTransformOutOfDate = true; mTransformUpdated = true; } //--------------------------------------------------------------------- void Overlay::rotate(const Radian& angle) { setRotate(mRotate + angle); } //--------------------------------------------------------------------- void Overlay::setScale(Real x, Real y) { mScaleX = x; mScaleY = y; mTransformOutOfDate = true; mTransformUpdated = true; } //--------------------------------------------------------------------- Real Overlay::getScaleX(void) const { return mScaleX; } //--------------------------------------------------------------------- Real Overlay::getScaleY(void) const { return mScaleY; } //--------------------------------------------------------------------- void Overlay::_getWorldTransforms(Matrix4* xform) const { if (mTransformOutOfDate) { updateTransform(); } *xform = mTransform; } //--------------------------------------------------------------------- void Overlay::_findVisibleObjects(Camera* cam, RenderQueue* queue) { OverlayContainerList::iterator i, iend; if (OverlayManager::getSingleton().hasViewportChanged()) { iend = m2DElements.end(); for (i = m2DElements.begin(); i != iend; ++i) { (*i)->_notifyViewport(); } } // update elements if (mTransformUpdated) { Matrix4 xform; _getWorldTransforms(&xform); iend = m2DElements.end(); for (i = m2DElements.begin(); i != iend; ++i) { (*i)->_notifyWorldTransforms(xform); } mTransformUpdated = false; } if (mVisible) { // Add 3D elements mRootNode->setPosition(cam->getDerivedPosition()); mRootNode->setOrientation(cam->getDerivedOrientation()); mRootNode->_update(true, false); // Set up the default queue group for the objects about to be added uint8 oldgrp = queue->getDefaultQueueGroup(); ushort oldPriority = queue-> getDefaultRenderablePriority(); queue->setDefaultQueueGroup(RENDER_QUEUE_OVERLAY); queue->setDefaultRenderablePriority(static_cast<ushort>((mZOrder*100)-1)); mRootNode->_findVisibleObjects(cam, queue, NULL, true, false); // Reset the group queue->setDefaultQueueGroup(oldgrp); queue->setDefaultRenderablePriority(oldPriority); // Add 2D elements iend = m2DElements.end(); for (i = m2DElements.begin(); i != iend; ++i) { (*i)->_update(); (*i)->_updateRenderQueue(queue); } } } //--------------------------------------------------------------------- void Overlay::updateTransform(void) const { // Ordering: // 1. Scale // 2. Rotate // 3. Translate Radian orientationRotation = Radian(0); #if OGRE_NO_VIEWPORT_ORIENTATIONMODE == 0 orientationRotation = Radian(OverlayManager::getSingleton().getViewportOrientationMode() * Math::HALF_PI); #endif Matrix3 rot3x3, scale3x3; rot3x3.FromEulerAnglesXYZ(Radian(0), Radian(0), mRotate + orientationRotation); scale3x3 = Matrix3::ZERO; scale3x3[0][0] = mScaleX; scale3x3[1][1] = mScaleY; scale3x3[2][2] = 1.0f; mTransform = Matrix4::IDENTITY; mTransform = rot3x3 * scale3x3; mTransform.setTrans(Vector3(mScrollX, mScrollY, 0)); mTransformOutOfDate = false; } //--------------------------------------------------------------------- OverlayElement* Overlay::findElementAt(Real x, Real y) { OverlayElement* ret = NULL; int currZ = -1; OverlayContainerList::iterator i, iend; iend = m2DElements.end(); for (i = m2DElements.begin(); i != iend; ++i) { int z = (*i)->getZOrder(); if (z > currZ) { OverlayElement* elementFound = (*i)->findElementAt(x,y); if(elementFound) { currZ = elementFound->getZOrder(); ret = elementFound; } } } return ret; } }
Java
#pragma once #include <GLUL/Config.h> #include <GLUL/Input/Event.h> #include <GLUL/Input/Types.h> #include <glm/vec2.hpp> namespace GLUL { namespace Input { class GLUL_API MouseButtonEvent : public Event { public: MouseButtonEvent(); MouseButtonEvent(MouseButton button, Action action, float x, float y); MouseButtonEvent(MouseButton button, Action action, const glm::vec2& position); float getX() const; float getY() const; const glm::vec2& getPosition() const; MouseButton getMouseButton() const; Action getAction() const; void setX(float x); void setY(float y); void setPosition(const glm::vec2& position); void setMouseButton(MouseButton button); void setAction(Action action); public: MouseButtonEvent* asMouseButtonEvent(); const MouseButtonEvent* asMouseButtonEvent() const; private: void _abstract() { } MouseButton _button; Action _action; glm::vec2 _position; }; } }
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>FreeType-2.5.0 API Reference</title> <style type="text/css"> body { font-family: Verdana, Geneva, Arial, Helvetica, serif; color: #000000; background: #FFFFFF; } p { text-align: justify; } h1 { text-align: center; } li { text-align: justify; } td { padding: 0 0.5em 0 0.5em; } td.left { padding: 0 0.5em 0 0.5em; text-align: left; } a:link { color: #0000EF; } a:visited { color: #51188E; } a:hover { color: #FF0000; } span.keyword { font-family: monospace; text-align: left; white-space: pre; color: darkblue; } pre.colored { color: blue; } ul.empty { list-style-type: none; } </style> </head> <body> <table align=center><tr><td><font size=-1>[<a href="ft2-index.html">Index</a>]</font></td> <td width="100%"></td> <td><font size=-1>[<a href="ft2-toc.html">TOC</a>]</font></td></tr></table> <center><h1>FreeType-2.5.0 API Reference</h1></center> <center><h1> LCD Filtering </h1></center> <h2>Synopsis</h2> <table align=center cellspacing=5 cellpadding=0 border=0> <tr><td></td><td><a href="#FT_LcdFilter">FT_LcdFilter</a></td><td></td><td><a href="#FT_Library_SetLcdFilterWeights">FT_Library_SetLcdFilterWeights</a></td></tr> <tr><td></td><td><a href="#FT_Library_SetLcdFilter">FT_Library_SetLcdFilter</a></td><td></td><td></td></tr> </table><br><br> <table align=center width="87%"><tr><td> <p>The <a href="ft2-lcd_filtering.html#FT_Library_SetLcdFilter">FT_Library_SetLcdFilter</a> API can be used to specify a low-pass filter which is then applied to LCD-optimized bitmaps generated through <a href="ft2-base_interface.html#FT_Render_Glyph">FT_Render_Glyph</a>. This is useful to reduce color fringes which would occur with unfiltered rendering.</p> <p>Note that no filter is active by default, and that this function is <b>not</b> implemented in default builds of the library. You need to #define FT_CONFIG_OPTION_SUBPIXEL_RENDERING in your &lsquo;ftoption.h&rsquo; file in order to activate it.</p> <p>FreeType generates alpha coverage maps, which are linear by nature. For instance, the value 0x80 in bitmap representation means that (within numerical precision) 0x80/0xff fraction of that pixel is covered by the glyph's outline. The blending function for placing text over a background is</p> <pre class="colored"> dst = alpha * src + (1 - alpha) * dst , </pre> <p>which is known as OVER. However, when calculating the output of the OVER operator, the source colors should first be transformed to a linear color space, then alpha blended in that space, and transformed back to the output color space.</p> <p>When linear light blending is used, the default FIR5 filtering weights (as given by FT_LCD_FILTER_DEFAULT) are no longer optimal, as they have been designed for black on white rendering while lacking gamma correction. To preserve color neutrality, weights for a FIR5 filter should be chosen according to two free parameters &lsquo;a&rsquo; and &lsquo;c&rsquo;, and the FIR weights should be</p> <pre class="colored"> [a - c, a + c, 2 * a, a + c, a - c] . </pre> <p>This formula generates equal weights for all the color primaries across the filter kernel, which makes it colorless. One suggested set of weights is</p> <pre class="colored"> [0x10, 0x50, 0x60, 0x50, 0x10] , </pre> <p>where &lsquo;a&rsquo; has value 0x30 and &lsquo;b&rsquo; value 0x20. The weights in filter may have a sum larger than 0x100, which increases coloration slightly but also improves contrast.</p> </td></tr></table><br> <table align=center width="75%"><tr><td> <h4><a name="FT_LcdFilter">FT_LcdFilter</a></h4> <table align=center width="87%"><tr><td> Defined in FT_LCD_FILTER_H (freetype/ftlcdfil.h). </td></tr></table><br> <table align=center width="87%"><tr bgcolor="#D6E8FF"><td><pre> <span class="keyword">typedef</span> <span class="keyword">enum</span> FT_LcdFilter_ { <a href="ft2-lcd_filtering.html#FT_LcdFilter">FT_LCD_FILTER_NONE</a> = 0, <a href="ft2-lcd_filtering.html#FT_LcdFilter">FT_LCD_FILTER_DEFAULT</a> = 1, <a href="ft2-lcd_filtering.html#FT_LcdFilter">FT_LCD_FILTER_LIGHT</a> = 2, <a href="ft2-lcd_filtering.html#FT_LcdFilter">FT_LCD_FILTER_LEGACY</a> = 16, FT_LCD_FILTER_MAX /* do not remove */ } <b>FT_LcdFilter</b>; </pre></table><br> <table align=center width="87%"><tr><td> <p>A list of values to identify various types of LCD filters.</p> </td></tr></table><br> <table align=center width="87%" cellpadding=5><tr bgcolor="#EEEEFF"><td><em><b>values</b></em></td></tr><tr><td> <p></p> <table cellpadding=3 border=0> <tr valign=top><td><b>FT_LCD_FILTER_NONE</b></td><td> <p>Do not perform filtering. When used with subpixel rendering, this results in sometimes severe color fringes.</p> </td></tr> <tr valign=top><td><b>FT_LCD_FILTER_DEFAULT</b></td><td> <p>The default filter reduces color fringes considerably, at the cost of a slight blurriness in the output.</p> </td></tr> <tr valign=top><td><b>FT_LCD_FILTER_LIGHT</b></td><td> <p>The light filter is a variant that produces less blurriness at the cost of slightly more color fringes than the default one. It might be better, depending on taste, your monitor, or your personal vision.</p> </td></tr> <tr valign=top><td><b>FT_LCD_FILTER_LEGACY</b></td><td> <p>This filter corresponds to the original libXft color filter. It provides high contrast output but can exhibit really bad color fringes if glyphs are not extremely well hinted to the pixel grid. In other words, it only works well if the TrueType bytecode interpreter is enabled <b>and</b> high-quality hinted fonts are used.</p> <p>This filter is only provided for comparison purposes, and might be disabled or stay unsupported in the future.</p> </td></tr> </table> </td></tr></table> <table align=center width="87%" cellpadding=5><tr bgcolor="#EEEEFF"><td><em><b>since</b></em></td></tr><tr><td> <p>2.3.0</p> </td></tr></table> </td></tr></table> <hr width="75%"> <table align=center width="75%"><tr><td><font size=-2>[<a href="ft2-index.html">Index</a>]</font></td> <td width="100%"></td> <td><font size=-2>[<a href="ft2-toc.html">TOC</a>]</font></td></tr></table> <table align=center width="75%"><tr><td> <h4><a name="FT_Library_SetLcdFilter">FT_Library_SetLcdFilter</a></h4> <table align=center width="87%"><tr><td> Defined in FT_LCD_FILTER_H (freetype/ftlcdfil.h). </td></tr></table><br> <table align=center width="87%"><tr bgcolor="#D6E8FF"><td><pre> FT_EXPORT( <a href="ft2-basic_types.html#FT_Error">FT_Error</a> ) <b>FT_Library_SetLcdFilter</b>( <a href="ft2-base_interface.html#FT_Library">FT_Library</a> library, <a href="ft2-lcd_filtering.html#FT_LcdFilter">FT_LcdFilter</a> filter ); </pre></table><br> <table align=center width="87%"><tr><td> <p>This function is used to apply color filtering to LCD decimated bitmaps, like the ones used when calling <a href="ft2-base_interface.html#FT_Render_Glyph">FT_Render_Glyph</a> with <a href="ft2-base_interface.html#FT_Render_Mode">FT_RENDER_MODE_LCD</a> or <a href="ft2-base_interface.html#FT_Render_Mode">FT_RENDER_MODE_LCD_V</a>.</p> </td></tr></table><br> <table align=center width="87%" cellpadding=5><tr bgcolor="#EEEEFF"><td><em><b>input</b></em></td></tr><tr><td> <p></p> <table cellpadding=3 border=0> <tr valign=top><td><b>library</b></td><td> <p>A handle to the target library instance.</p> </td></tr> <tr valign=top><td><b>filter</b></td><td> <p>The filter type.</p> <p>You can use <a href="ft2-lcd_filtering.html#FT_LcdFilter">FT_LCD_FILTER_NONE</a> here to disable this feature, or <a href="ft2-lcd_filtering.html#FT_LcdFilter">FT_LCD_FILTER_DEFAULT</a> to use a default filter that should work well on most LCD screens.</p> </td></tr> </table> </td></tr></table> <table align=center width="87%" cellpadding=5><tr bgcolor="#EEEEFF"><td><em><b>return</b></em></td></tr><tr><td> <p>FreeType error code. 0&nbsp;means success.</p> </td></tr></table> <table align=center width="87%" cellpadding=5><tr bgcolor="#EEEEFF"><td><em><b>note</b></em></td></tr><tr><td> <p>This feature is always disabled by default. Clients must make an explicit call to this function with a &lsquo;filter&rsquo; value other than <a href="ft2-lcd_filtering.html#FT_LcdFilter">FT_LCD_FILTER_NONE</a> in order to enable it.</p> <p>Due to <b>PATENTS</b> covering subpixel rendering, this function doesn't do anything except returning &lsquo;FT_Err_Unimplemented_Feature&rsquo; if the configuration macro FT_CONFIG_OPTION_SUBPIXEL_RENDERING is not defined in your build of the library, which should correspond to all default builds of FreeType.</p> <p>The filter affects glyph bitmaps rendered through <a href="ft2-base_interface.html#FT_Render_Glyph">FT_Render_Glyph</a>, <a href="ft2-outline_processing.html#FT_Outline_Get_Bitmap">FT_Outline_Get_Bitmap</a>, <a href="ft2-base_interface.html#FT_Load_Glyph">FT_Load_Glyph</a>, and <a href="ft2-base_interface.html#FT_Load_Char">FT_Load_Char</a>.</p> <p>It does <i>not</i> affect the output of <a href="ft2-outline_processing.html#FT_Outline_Render">FT_Outline_Render</a> and <a href="ft2-outline_processing.html#FT_Outline_Get_Bitmap">FT_Outline_Get_Bitmap</a>.</p> <p>If this feature is activated, the dimensions of LCD glyph bitmaps are either larger or taller than the dimensions of the corresponding outline with regards to the pixel grid. For example, for <a href="ft2-base_interface.html#FT_Render_Mode">FT_RENDER_MODE_LCD</a>, the filter adds up to 3&nbsp;pixels to the left, and up to 3&nbsp;pixels to the right.</p> <p>The bitmap offset values are adjusted correctly, so clients shouldn't need to modify their layout and glyph positioning code when enabling the filter.</p> </td></tr></table> <table align=center width="87%" cellpadding=5><tr bgcolor="#EEEEFF"><td><em><b>since</b></em></td></tr><tr><td> <p>2.3.0</p> </td></tr></table> </td></tr></table> <hr width="75%"> <table align=center width="75%"><tr><td><font size=-2>[<a href="ft2-index.html">Index</a>]</font></td> <td width="100%"></td> <td><font size=-2>[<a href="ft2-toc.html">TOC</a>]</font></td></tr></table> <table align=center width="75%"><tr><td> <h4><a name="FT_Library_SetLcdFilterWeights">FT_Library_SetLcdFilterWeights</a></h4> <table align=center width="87%"><tr><td> Defined in FT_LCD_FILTER_H (freetype/ftlcdfil.h). </td></tr></table><br> <table align=center width="87%"><tr bgcolor="#D6E8FF"><td><pre> FT_EXPORT( <a href="ft2-basic_types.html#FT_Error">FT_Error</a> ) <b>FT_Library_SetLcdFilterWeights</b>( <a href="ft2-base_interface.html#FT_Library">FT_Library</a> library, <span class="keyword">unsigned</span> <span class="keyword">char</span> *weights ); </pre></table><br> <table align=center width="87%"><tr><td> <p>Use this function to override the filter weights selected by <a href="ft2-lcd_filtering.html#FT_Library_SetLcdFilter">FT_Library_SetLcdFilter</a>. By default, FreeType uses the quintuple (0x00, 0x55, 0x56, 0x55, 0x00) for FT_LCD_FILTER_LIGHT, and (0x10, 0x40, 0x70, 0x40, 0x10) for FT_LCD_FILTER_DEFAULT and FT_LCD_FILTER_LEGACY.</p> </td></tr></table><br> <table align=center width="87%" cellpadding=5><tr bgcolor="#EEEEFF"><td><em><b>input</b></em></td></tr><tr><td> <p></p> <table cellpadding=3 border=0> <tr valign=top><td><b>library</b></td><td> <p>A handle to the target library instance.</p> </td></tr> <tr valign=top><td><b>weights</b></td><td> <p>A pointer to an array; the function copies the first five bytes and uses them to specify the filter weights.</p> </td></tr> </table> </td></tr></table> <table align=center width="87%" cellpadding=5><tr bgcolor="#EEEEFF"><td><em><b>return</b></em></td></tr><tr><td> <p>FreeType error code. 0&nbsp;means success.</p> </td></tr></table> <table align=center width="87%" cellpadding=5><tr bgcolor="#EEEEFF"><td><em><b>note</b></em></td></tr><tr><td> <p>Due to <b>PATENTS</b> covering subpixel rendering, this function doesn't do anything except returning &lsquo;FT_Err_Unimplemented_Feature&rsquo; if the configuration macro FT_CONFIG_OPTION_SUBPIXEL_RENDERING is not defined in your build of the library, which should correspond to all default builds of FreeType.</p> <p>This function must be called after <a href="ft2-lcd_filtering.html#FT_Library_SetLcdFilter">FT_Library_SetLcdFilter</a> to have any effect.</p> </td></tr></table> <table align=center width="87%" cellpadding=5><tr bgcolor="#EEEEFF"><td><em><b>since</b></em></td></tr><tr><td> <p>2.4.0</p> </td></tr></table> </td></tr></table> <hr width="75%"> <table align=center width="75%"><tr><td><font size=-2>[<a href="ft2-index.html">Index</a>]</font></td> <td width="100%"></td> <td><font size=-2>[<a href="ft2-toc.html">TOC</a>]</font></td></tr></table> </body> </html>
Java
/* Highcharts JS v8.2.2 (2020-10-22) (c) 2016-2019 Highsoft AS Authors: Jon Arild Nygard License: www.highcharts.com/license */ (function(b){"object"===typeof module&&module.exports?(b["default"]=b,module.exports=b):"function"===typeof define&&define.amd?define("highcharts/modules/sunburst",["highcharts"],function(q){b(q);b.Highcharts=q;return b}):b("undefined"!==typeof Highcharts?Highcharts:void 0)})(function(b){function q(b,d,p,D){b.hasOwnProperty(d)||(b[d]=D.apply(null,p))}b=b?b._modules:{};q(b,"Mixins/DrawPoint.js",[],function(){var b=function(b){return"function"===typeof b},d=function(p){var d,u=this,l=u.graphic,w=p.animatableAttribs, A=p.onComplete,g=p.css,k=p.renderer,V=null===(d=u.series)||void 0===d?void 0:d.options.animation;if(u.shouldDraw())l||(u.graphic=l=k[p.shapeType](p.shapeArgs).add(p.group)),l.css(g).attr(p.attribs).animate(w,p.isNew?!1:V,A);else if(l){var H=function(){u.graphic=l=l.destroy();b(A)&&A()};Object.keys(w).length?l.animate(w,void 0,function(){H()}):H()}};return{draw:d,drawPoint:function(b){(b.attribs=b.attribs||{})["class"]=this.getClassName();d.call(this,b)},isFn:b}});q(b,"Mixins/TreeSeries.js",[b["Core/Color/Color.js"], b["Core/Utilities.js"]],function(b,d){var p=d.extend,D=d.isArray,u=d.isNumber,l=d.isObject,w=d.merge,A=d.pick;return{getColor:function(g,k){var l=k.index,d=k.mapOptionsToLevel,p=k.parentColor,u=k.parentColorIndex,K=k.series,C=k.colors,I=k.siblings,r=K.points,w=K.chart.options.chart,B;if(g){r=r[g.i];g=d[g.level]||{};if(d=r&&g.colorByPoint){var D=r.index%(C?C.length:w.colorCount);var L=C&&C[D]}if(!K.chart.styledMode){C=r&&r.options.color;w=g&&g.color;if(B=p)B=(B=g&&g.colorVariation)&&"brightness"=== B.key?b.parse(p).brighten(l/I*B.to).get():p;B=A(C,w,L,B,K.color)}var q=A(r&&r.options.colorIndex,g&&g.colorIndex,D,u,k.colorIndex)}return{color:B,colorIndex:q}},getLevelOptions:function(b){var k=null;if(l(b)){k={};var d=u(b.from)?b.from:1;var g=b.levels;var A={};var q=l(b.defaults)?b.defaults:{};D(g)&&(A=g.reduce(function(b,k){if(l(k)&&u(k.level)){var g=w({},k);var r="boolean"===typeof g.levelIsConstant?g.levelIsConstant:q.levelIsConstant;delete g.levelIsConstant;delete g.level;k=k.level+(r?0:d-1); l(b[k])?p(b[k],g):b[k]=g}return b},{}));g=u(b.to)?b.to:1;for(b=0;b<=g;b++)k[b]=w({},q,l(A[b])?A[b]:{})}return k},setTreeValues:function H(b,d){var k=d.before,l=d.idRoot,u=d.mapIdToNode[l],C=d.points[b.i],w=C&&C.options||{},r=0,q=[];p(b,{levelDynamic:b.level-(("boolean"===typeof d.levelIsConstant?d.levelIsConstant:1)?0:u.level),name:A(C&&C.name,""),visible:l===b.id||("boolean"===typeof d.visible?d.visible:!1)});"function"===typeof k&&(b=k(b,d));b.children.forEach(function(k,l){var u=p({},d);p(u,{index:l, siblings:b.children.length,visible:b.visible});k=H(k,u);q.push(k);k.visible&&(r+=k.val)});b.visible=0<r||b.visible;k=A(w.value,r);p(b,{children:q,childrenTotal:r,isLeaf:b.visible&&!r,val:k});return b},updateRootId:function(b){if(l(b)){var d=l(b.options)?b.options:{};d=A(b.rootNode,d.rootId,"");l(b.userOptions)&&(b.userOptions.rootId=d);b.rootNode=d}return d}}});q(b,"Mixins/ColorMapSeries.js",[b["Core/Globals.js"],b["Core/Series/Point.js"],b["Core/Utilities.js"]],function(b,d,p){var q=p.defined;return{colorMapPointMixin:{dataLabelOnNull:!0, isValid:function(){return null!==this.value&&Infinity!==this.value&&-Infinity!==this.value},setState:function(b){d.prototype.setState.call(this,b);this.graphic&&this.graphic.attr({zIndex:"hover"===b?1:0})}},colorMapSeriesMixin:{pointArrayMap:["value"],axisTypes:["xAxis","yAxis","colorAxis"],trackerGroups:["group","markerGroup","dataLabelsGroup"],getSymbol:b.noop,parallelArrays:["x","y","value"],colorKey:"value",pointAttribs:b.seriesTypes.column.prototype.pointAttribs,colorAttribs:function(b){var d= {};q(b.color)&&(d[this.colorProp||"fill"]=b.color);return d}}}});q(b,"Series/TreemapSeries.js",[b["Core/Series/Series.js"],b["Core/Color/Color.js"],b["Mixins/ColorMapSeries.js"],b["Mixins/DrawPoint.js"],b["Core/Globals.js"],b["Mixins/LegendSymbol.js"],b["Core/Series/Point.js"],b["Mixins/TreeSeries.js"],b["Core/Utilities.js"]],function(b,d,p,q,u,l,w,A,g){var k=b.seriesTypes,D=d.parse,H=p.colorMapSeriesMixin;d=u.noop;var Q=A.getColor,N=A.getLevelOptions,K=A.updateRootId,C=g.addEvent,I=g.correctFloat, r=g.defined,R=g.error,B=g.extend,S=g.fireEvent,L=g.isArray,O=g.isNumber,P=g.isObject,M=g.isString,J=g.merge,T=g.objectEach,f=g.pick,h=g.stableSort,t=u.Series,y=function(a,c,e){e=e||this;T(a,function(b,m){c.call(e,b,m,a)})},E=function(a,c,e){e=e||this;a=c.call(e,a);!1!==a&&E(a,c,e)},n=!1;b.seriesType("treemap","scatter",{allowTraversingTree:!1,animationLimit:250,showInLegend:!1,marker:void 0,colorByPoint:!1,dataLabels:{defer:!1,enabled:!0,formatter:function(){var a=this&&this.point?this.point:{};return M(a.name)? a.name:""},inside:!0,verticalAlign:"middle"},tooltip:{headerFormat:"",pointFormat:"<b>{point.name}</b>: {point.value}<br/>"},ignoreHiddenPoint:!0,layoutAlgorithm:"sliceAndDice",layoutStartingDirection:"vertical",alternateStartingDirection:!1,levelIsConstant:!0,drillUpButton:{position:{align:"right",x:-10,y:10}},traverseUpButton:{position:{align:"right",x:-10,y:10}},borderColor:"#e6e6e6",borderWidth:1,colorKey:"colorValue",opacity:.15,states:{hover:{borderColor:"#999999",brightness:k.heatmap?0:.1, halo:!1,opacity:.75,shadow:!1}}},{pointArrayMap:["value"],directTouch:!0,optionalAxis:"colorAxis",getSymbol:d,parallelArrays:["x","y","value","colorValue"],colorKey:"colorValue",trackerGroups:["group","dataLabelsGroup"],getListOfParents:function(a,c){a=L(a)?a:[];var e=L(c)?c:[];c=a.reduce(function(a,c,e){c=f(c.parent,"");"undefined"===typeof a[c]&&(a[c]=[]);a[c].push(e);return a},{"":[]});y(c,function(a,c,b){""!==c&&-1===e.indexOf(c)&&(a.forEach(function(a){b[""].push(a)}),delete b[c])});return c}, getTree:function(){var a=this.data.map(function(a){return a.id});a=this.getListOfParents(this.data,a);this.nodeMap={};return this.buildNode("",-1,0,a)},hasData:function(){return!!this.processedXData.length},init:function(a,c){H&&(this.colorAttribs=H.colorAttribs);var e=C(this,"setOptions",function(a){a=a.userOptions;r(a.allowDrillToNode)&&!r(a.allowTraversingTree)&&(a.allowTraversingTree=a.allowDrillToNode,delete a.allowDrillToNode);r(a.drillUpButton)&&!r(a.traverseUpButton)&&(a.traverseUpButton= a.drillUpButton,delete a.drillUpButton)});t.prototype.init.call(this,a,c);delete this.opacity;this.eventsToUnbind.push(e);this.options.allowTraversingTree&&this.eventsToUnbind.push(C(this,"click",this.onClickDrillToNode))},buildNode:function(a,c,e,b,m){var f=this,x=[],h=f.points[c],d=0,F;(b[a]||[]).forEach(function(c){F=f.buildNode(f.points[c].id,c,e+1,b,a);d=Math.max(F.height+1,d);x.push(F)});c={id:a,i:c,children:x,height:d,level:e,parent:m,visible:!1};f.nodeMap[c.id]=c;h&&(h.node=c);return c},setTreeValues:function(a){var c= this,e=c.options,b=c.nodeMap[c.rootNode];e="boolean"===typeof e.levelIsConstant?e.levelIsConstant:!0;var m=0,U=[],v=c.points[a.i];a.children.forEach(function(a){a=c.setTreeValues(a);U.push(a);a.ignore||(m+=a.val)});h(U,function(a,c){return(a.sortIndex||0)-(c.sortIndex||0)});var d=f(v&&v.options.value,m);v&&(v.value=d);B(a,{children:U,childrenTotal:m,ignore:!(f(v&&v.visible,!0)&&0<d),isLeaf:a.visible&&!m,levelDynamic:a.level-(e?0:b.level),name:f(v&&v.name,""),sortIndex:f(v&&v.sortIndex,-d),val:d}); return a},calculateChildrenAreas:function(a,c){var e=this,b=e.options,m=e.mapOptionsToLevel[a.level+1],d=f(e[m&&m.layoutAlgorithm]&&m.layoutAlgorithm,b.layoutAlgorithm),v=b.alternateStartingDirection,h=[];a=a.children.filter(function(a){return!a.ignore});m&&m.layoutStartingDirection&&(c.direction="vertical"===m.layoutStartingDirection?0:1);h=e[d](c,a);a.forEach(function(a,b){b=h[b];a.values=J(b,{val:a.childrenTotal,direction:v?1-c.direction:c.direction});a.pointValues=J(b,{x:b.x/e.axisRatio,y:100- b.y-b.height,width:b.width/e.axisRatio});a.children.length&&e.calculateChildrenAreas(a,a.values)})},setPointValues:function(){var a=this,c=a.xAxis,e=a.yAxis,b=a.chart.styledMode;a.points.forEach(function(f){var m=f.node,x=m.pointValues;m=m.visible;if(x&&m){m=x.height;var d=x.width,h=x.x,t=x.y,n=b?0:(a.pointAttribs(f)["stroke-width"]||0)%2/2;x=Math.round(c.toPixels(h,!0))-n;d=Math.round(c.toPixels(h+d,!0))-n;h=Math.round(e.toPixels(t,!0))-n;m=Math.round(e.toPixels(t+m,!0))-n;f.shapeArgs={x:Math.min(x, d),y:Math.min(h,m),width:Math.abs(d-x),height:Math.abs(m-h)};f.plotX=f.shapeArgs.x+f.shapeArgs.width/2;f.plotY=f.shapeArgs.y+f.shapeArgs.height/2}else delete f.plotX,delete f.plotY})},setColorRecursive:function(a,c,e,b,f){var m=this,x=m&&m.chart;x=x&&x.options&&x.options.colors;if(a){var d=Q(a,{colors:x,index:b,mapOptionsToLevel:m.mapOptionsToLevel,parentColor:c,parentColorIndex:e,series:m,siblings:f});if(c=m.points[a.i])c.color=d.color,c.colorIndex=d.colorIndex;(a.children||[]).forEach(function(c, e){m.setColorRecursive(c,d.color,d.colorIndex,e,a.children.length)})}},algorithmGroup:function(a,c,e,b){this.height=a;this.width=c;this.plot=b;this.startDirection=this.direction=e;this.lH=this.nH=this.lW=this.nW=this.total=0;this.elArr=[];this.lP={total:0,lH:0,nH:0,lW:0,nW:0,nR:0,lR:0,aspectRatio:function(a,c){return Math.max(a/c,c/a)}};this.addElement=function(a){this.lP.total=this.elArr[this.elArr.length-1];this.total+=a;0===this.direction?(this.lW=this.nW,this.lP.lH=this.lP.total/this.lW,this.lP.lR= this.lP.aspectRatio(this.lW,this.lP.lH),this.nW=this.total/this.height,this.lP.nH=this.lP.total/this.nW,this.lP.nR=this.lP.aspectRatio(this.nW,this.lP.nH)):(this.lH=this.nH,this.lP.lW=this.lP.total/this.lH,this.lP.lR=this.lP.aspectRatio(this.lP.lW,this.lH),this.nH=this.total/this.width,this.lP.nW=this.lP.total/this.nH,this.lP.nR=this.lP.aspectRatio(this.lP.nW,this.nH));this.elArr.push(a)};this.reset=function(){this.lW=this.nW=0;this.elArr=[];this.total=0}},algorithmCalcPoints:function(a,c,e,b){var f, x,d,h,t=e.lW,n=e.lH,g=e.plot,k=0,y=e.elArr.length-1;if(c)t=e.nW,n=e.nH;else var G=e.elArr[e.elArr.length-1];e.elArr.forEach(function(a){if(c||k<y)0===e.direction?(f=g.x,x=g.y,d=t,h=a/d):(f=g.x,x=g.y,h=n,d=a/h),b.push({x:f,y:x,width:d,height:I(h)}),0===e.direction?g.y+=h:g.x+=d;k+=1});e.reset();0===e.direction?e.width-=t:e.height-=n;g.y=g.parent.y+(g.parent.height-e.height);g.x=g.parent.x+(g.parent.width-e.width);a&&(e.direction=1-e.direction);c||e.addElement(G)},algorithmLowAspectRatio:function(a, c,e){var b=[],f=this,d,h={x:c.x,y:c.y,parent:c},t=0,g=e.length-1,n=new this.algorithmGroup(c.height,c.width,c.direction,h);e.forEach(function(e){d=e.val/c.val*c.height*c.width;n.addElement(d);n.lP.nR>n.lP.lR&&f.algorithmCalcPoints(a,!1,n,b,h);t===g&&f.algorithmCalcPoints(a,!0,n,b,h);t+=1});return b},algorithmFill:function(a,c,e){var b=[],f,d=c.direction,h=c.x,t=c.y,n=c.width,g=c.height,k,y,l,G;e.forEach(function(e){f=e.val/c.val*c.height*c.width;k=h;y=t;0===d?(G=g,l=f/G,n-=l,h+=l):(l=n,G=f/l,g-=G, t+=G);b.push({x:k,y:y,width:l,height:G});a&&(d=1-d)});return b},strip:function(a,c){return this.algorithmLowAspectRatio(!1,a,c)},squarified:function(a,c){return this.algorithmLowAspectRatio(!0,a,c)},sliceAndDice:function(a,c){return this.algorithmFill(!0,a,c)},stripes:function(a,c){return this.algorithmFill(!1,a,c)},translate:function(){var a=this,c=a.options,e=K(a);t.prototype.translate.call(a);var b=a.tree=a.getTree();var f=a.nodeMap[e];a.renderTraverseUpButton(e);a.mapOptionsToLevel=N({from:f.level+ 1,levels:c.levels,to:b.height,defaults:{levelIsConstant:a.options.levelIsConstant,colorByPoint:c.colorByPoint}});""===e||f&&f.children.length||(a.setRootNode("",!1),e=a.rootNode,f=a.nodeMap[e]);E(a.nodeMap[a.rootNode],function(c){var e=!1,b=c.parent;c.visible=!0;if(b||""===b)e=a.nodeMap[b];return e});E(a.nodeMap[a.rootNode].children,function(a){var c=!1;a.forEach(function(a){a.visible=!0;a.children.length&&(c=(c||[]).concat(a.children))});return c});a.setTreeValues(b);a.axisRatio=a.xAxis.len/a.yAxis.len; a.nodeMap[""].pointValues=e={x:0,y:0,width:100,height:100};a.nodeMap[""].values=e=J(e,{width:e.width*a.axisRatio,direction:"vertical"===c.layoutStartingDirection?0:1,val:b.val});a.calculateChildrenAreas(b,e);a.colorAxis||c.colorByPoint||a.setColorRecursive(a.tree);c.allowTraversingTree&&(c=f.pointValues,a.xAxis.setExtremes(c.x,c.x+c.width,!1),a.yAxis.setExtremes(c.y,c.y+c.height,!1),a.xAxis.setScale(),a.yAxis.setScale());a.setPointValues()},drawDataLabels:function(){var a=this,c=a.mapOptionsToLevel, e,b;a.points.filter(function(a){return a.node.visible}).forEach(function(f){b=c[f.node.level];e={style:{}};f.node.isLeaf||(e.enabled=!1);b&&b.dataLabels&&(e=J(e,b.dataLabels),a._hasPointLabels=!0);f.shapeArgs&&(e.style.width=f.shapeArgs.width,f.dataLabel&&f.dataLabel.css({width:f.shapeArgs.width+"px"}));f.dlOptions=J(e,f.options.dataLabels)});t.prototype.drawDataLabels.call(this)},alignDataLabel:function(a,c,b){var e=b.style;!r(e.textOverflow)&&c.text&&c.getBBox().width>c.text.textWidth&&c.css({textOverflow:"ellipsis", width:e.width+="px"});k.column.prototype.alignDataLabel.apply(this,arguments);a.dataLabel&&a.dataLabel.attr({zIndex:(a.node.zIndex||0)+1})},pointAttribs:function(a,c){var b=P(this.mapOptionsToLevel)?this.mapOptionsToLevel:{},d=a&&b[a.node.level]||{};b=this.options;var h=c&&b.states[c]||{},t=a&&a.getClassName()||"";a={stroke:a&&a.borderColor||d.borderColor||h.borderColor||b.borderColor,"stroke-width":f(a&&a.borderWidth,d.borderWidth,h.borderWidth,b.borderWidth),dashstyle:a&&a.borderDashStyle||d.borderDashStyle|| h.borderDashStyle||b.borderDashStyle,fill:a&&a.color||this.color};-1!==t.indexOf("highcharts-above-level")?(a.fill="none",a["stroke-width"]=0):-1!==t.indexOf("highcharts-internal-node-interactive")?(c=f(h.opacity,b.opacity),a.fill=D(a.fill).setOpacity(c).get(),a.cursor="pointer"):-1!==t.indexOf("highcharts-internal-node")?a.fill="none":c&&(a.fill=D(a.fill).brighten(h.brightness).get());return a},drawPoints:function(){var a=this,c=a.chart,b=c.renderer,f=c.styledMode,d=a.options,h=f?{}:d.shadow,t=d.borderRadius, n=c.pointCount<d.animationLimit,g=d.allowTraversingTree;a.points.forEach(function(c){var e=c.node.levelDynamic,m={},x={},G={},k="level-group-"+c.node.level,l=!!c.graphic,y=n&&l,E=c.shapeArgs;c.shouldDraw()&&(t&&(x.r=t),J(!0,y?m:x,l?E:{},f?{}:a.pointAttribs(c,c.selected?"select":void 0)),a.colorAttribs&&f&&B(G,a.colorAttribs(c)),a[k]||(a[k]=b.g(k).attr({zIndex:1E3-(e||0)}).add(a.group),a[k].survive=!0));c.draw({animatableAttribs:m,attribs:x,css:G,group:a[k],renderer:b,shadow:h,shapeArgs:E,shapeType:"rect"}); g&&c.graphic&&(c.drillId=d.interactByLeaf?a.drillToByLeaf(c):a.drillToByGroup(c))})},onClickDrillToNode:function(a){var c=(a=a.point)&&a.drillId;M(c)&&(a.setState(""),this.setRootNode(c,!0,{trigger:"click"}))},drillToByGroup:function(a){var c=!1;1!==a.node.level-this.nodeMap[this.rootNode].level||a.node.isLeaf||(c=a.id);return c},drillToByLeaf:function(a){var c=!1;if(a.node.parent!==this.rootNode&&a.node.isLeaf)for(a=a.node;!c;)a=this.nodeMap[a.parent],a.parent===this.rootNode&&(c=a.id);return c}, drillUp:function(){var a=this.nodeMap[this.rootNode];a&&M(a.parent)&&this.setRootNode(a.parent,!0,{trigger:"traverseUpButton"})},drillToNode:function(a,c){R(32,!1,void 0,{"treemap.drillToNode":"use treemap.setRootNode"});this.setRootNode(a,c)},setRootNode:function(a,c,b){a=B({newRootId:a,previousRootId:this.rootNode,redraw:f(c,!0),series:this},b);S(this,"setRootNode",a,function(a){var c=a.series;c.idPreviousRoot=a.previousRootId;c.rootNode=a.newRootId;c.isDirty=!0;a.redraw&&c.chart.redraw()})},renderTraverseUpButton:function(a){var c= this,b=c.options.traverseUpButton,d=f(b.text,c.nodeMap[a].name,"\u25c1 Back");if(""===a||c.is("sunburst")&&1===c.tree.children.length&&a===c.tree.children[0].id)c.drillUpButton&&(c.drillUpButton=c.drillUpButton.destroy());else if(this.drillUpButton)this.drillUpButton.placed=!1,this.drillUpButton.attr({text:d}).align();else{var h=(a=b.theme)&&a.states;this.drillUpButton=this.chart.renderer.button(d,0,0,function(){c.drillUp()},a,h&&h.hover,h&&h.select).addClass("highcharts-drillup-button").attr({align:b.position.align, zIndex:7}).add().align(b.position,!1,b.relativeTo||"plotBox")}},buildKDTree:d,drawLegendSymbol:l.drawRectangle,getExtremes:function(){var a=t.prototype.getExtremes.call(this,this.colorValueData),c=a.dataMax;this.valueMin=a.dataMin;this.valueMax=c;return t.prototype.getExtremes.call(this)},getExtremesFromAll:!0,setState:function(a){this.options.inactiveOtherPoints=!0;t.prototype.setState.call(this,a,!1);this.options.inactiveOtherPoints=!1},utils:{recursive:E}},{draw:q.drawPoint,setVisible:k.pie.prototype.pointClass.prototype.setVisible, getClassName:function(){var a=w.prototype.getClassName.call(this),c=this.series,b=c.options;this.node.level<=c.nodeMap[c.rootNode].level?a+=" highcharts-above-level":this.node.isLeaf||f(b.interactByLeaf,!b.allowTraversingTree)?this.node.isLeaf||(a+=" highcharts-internal-node"):a+=" highcharts-internal-node-interactive";return a},isValid:function(){return!(!this.id&&!O(this.value))},setState:function(a){w.prototype.setState.call(this,a);this.graphic&&this.graphic.attr({zIndex:"hover"===a?1:0})},shouldDraw:function(){return O(this.plotY)&& null!==this.y}});C(u.Series,"afterBindAxes",function(){var a=this.xAxis,c=this.yAxis;if(a&&c)if(this.is("treemap")){var b={endOnTick:!1,gridLineWidth:0,lineWidth:0,min:0,dataMin:0,minPadding:0,max:100,dataMax:100,maxPadding:0,startOnTick:!1,title:null,tickPositions:[]};B(c.options,b);B(a.options,b);n=!0}else n&&(c.setOptions(c.userOptions),a.setOptions(a.userOptions),n=!1)});""});q(b,"Series/SunburstSeries.js",[b["Core/Series/Series.js"],b["Mixins/CenteredSeries.js"],b["Mixins/DrawPoint.js"],b["Core/Globals.js"], b["Mixins/TreeSeries.js"],b["Core/Utilities.js"]],function(b,d,p,q,u,l){var w=b.seriesTypes,A=d.getCenter,g=d.getStartAndEndRadians,k=u.getColor,D=u.getLevelOptions,H=u.setTreeValues,Q=u.updateRootId,N=l.correctFloat,K=l.error,C=l.extend,I=l.isNumber,r=l.isObject,R=l.isString,B=l.merge,S=l.splat,L=q.Series,O=180/Math.PI,P=function(b,d){var f=[];if(I(b)&&I(d)&&b<=d)for(;b<=d;b++)f.push(b);return f},M=function(b,d){d=r(d)?d:{};var f=0,h;if(r(b)){var g=B({},b);b=I(d.from)?d.from:0;var n=I(d.to)?d.to: 0;var a=P(b,n);b=Object.keys(g).filter(function(c){return-1===a.indexOf(+c)});var c=h=I(d.diffRadius)?d.diffRadius:0;a.forEach(function(a){a=g[a];var b=a.levelSize.unit,e=a.levelSize.value;"weight"===b?f+=e:"percentage"===b?(a.levelSize={unit:"pixels",value:e/100*c},h-=a.levelSize.value):"pixels"===b&&(h-=e)});a.forEach(function(a){var c=g[a];"weight"===c.levelSize.unit&&(c=c.levelSize.value,g[a].levelSize={unit:"pixels",value:c/f*h})});b.forEach(function(a){g[a].levelSize={value:0,unit:"pixels"}})}return g}, J=function(b){var f=b.level;return{from:0<f?f:1,to:f+b.height}},T=function(b,d){var f=d.mapIdToNode[b.parent],h=d.series,g=h.chart,n=h.points[b.i];f=k(b,{colors:h.options.colors||g&&g.options.colors,colorIndex:h.colorIndex,index:d.index,mapOptionsToLevel:d.mapOptionsToLevel,parentColor:f&&f.color,parentColorIndex:f&&f.colorIndex,series:d.series,siblings:d.siblings});b.color=f.color;b.colorIndex=f.colorIndex;n&&(n.color=b.color,n.colorIndex=b.colorIndex,b.sliced=b.id!==d.idRoot?n.sliced:!1);return b}; d={drawDataLabels:q.noop,drawPoints:function(){var b=this,d=b.mapOptionsToLevel,g=b.shapeRoot,k=b.group,l=b.hasRendered,n=b.rootNode,a=b.idPreviousRoot,c=b.nodeMap,e=c[a],x=e&&e.shapeArgs;e=b.points;var m=b.startAndEndRadians,p=b.chart,v=p&&p.options&&p.options.chart||{},u="boolean"===typeof v.animation?v.animation:!0,q=b.center[3]/2,A=b.chart.renderer,w=!1,D=!1;if(v=!!(u&&l&&n!==a&&b.dataLabelsGroup)){b.dataLabelsGroup.attr({opacity:0});var H=function(){w=!0;b.dataLabelsGroup&&b.dataLabelsGroup.animate({opacity:1, visibility:"visible"})}}e.forEach(function(e){var f=e.node,h=d[f.level];var t=e.shapeExisting||{};var y=f.shapeArgs||{},v=!(!f.visible||!f.shapeArgs);if(l&&u){var E={};var w={end:y.end,start:y.start,innerR:y.innerR,r:y.r,x:y.x,y:y.y};v?!e.graphic&&x&&(E=n===e.id?{start:m.start,end:m.end}:x.end<=y.start?{start:m.end,end:m.end}:{start:m.start,end:m.start},E.innerR=E.r=q):e.graphic&&(a===e.id?w={innerR:q,r:q}:g&&(w=g.end<=t.start?{innerR:q,r:q,start:m.end,end:m.end}:{innerR:q,r:q,start:m.start,end:m.start})); t=E}else w=y,t={};E=[y.plotX,y.plotY];if(!e.node.isLeaf)if(n===e.id){var z=c[n];z=z.parent}else z=e.id;C(e,{shapeExisting:y,tooltipPos:E,drillId:z,name:""+(e.name||e.id||e.index),plotX:y.plotX,plotY:y.plotY,value:f.val,isNull:!v});z=e.options;f=r(y)?y:{};z=r(z)?z.dataLabels:{};h=S(r(h)?h.dataLabels:{})[0];h=B({style:{}},h,z);z=h.rotationMode;if(!I(h.rotation)){if("auto"===z||"circular"===z)if(1>e.innerArcLength&&e.outerArcLength>f.radius){var F=0;e.dataLabelPath&&"circular"===z&&(h.textPath={enabled:!0})}else 1< e.innerArcLength&&e.outerArcLength>1.5*f.radius?"circular"===z?h.textPath={enabled:!0,attributes:{dy:5}}:z="parallel":(e.dataLabel&&e.dataLabel.textPathWrapper&&"circular"===z&&(h.textPath={enabled:!1}),z="perpendicular");"auto"!==z&&"circular"!==z&&(F=f.end-(f.end-f.start)/2);h.style.width="parallel"===z?Math.min(2.5*f.radius,(e.outerArcLength+e.innerArcLength)/2):f.radius;"perpendicular"===z&&e.series.chart.renderer.fontMetrics(h.style.fontSize).h>e.outerArcLength&&(h.style.width=1);h.style.width= Math.max(h.style.width-2*(h.padding||0),1);F=F*O%180;"parallel"===z&&(F-=90);90<F?F-=180:-90>F&&(F+=180);h.rotation=F}h.textPath&&(0===e.shapeExisting.innerR&&h.textPath.enabled?(h.rotation=0,h.textPath.enabled=!1,h.style.width=Math.max(2*e.shapeExisting.r-2*(h.padding||0),1)):e.dlOptions&&e.dlOptions.textPath&&!e.dlOptions.textPath.enabled&&"circular"===z&&(h.textPath.enabled=!0),h.textPath.enabled&&(h.rotation=0,h.style.width=Math.max((e.outerArcLength+e.innerArcLength)/2-2*(h.padding||0),1))); 0===h.rotation&&(h.rotation=.001);e.dlOptions=h;if(!D&&v){D=!0;var G=H}e.draw({animatableAttribs:w,attribs:C(t,!p.styledMode&&b.pointAttribs(e,e.selected&&"select")),onComplete:G,group:k,renderer:A,shapeType:"arc",shapeArgs:y})});v&&D?(b.hasRendered=!1,b.options.dataLabels.defer=!0,L.prototype.drawDataLabels.call(b),b.hasRendered=!0,w&&H()):L.prototype.drawDataLabels.call(b)},pointAttribs:w.column.prototype.pointAttribs,layoutAlgorithm:function(b,d,g){var f=b.start,h=b.end-f,n=b.val,a=b.x,c=b.y,e= g&&r(g.levelSize)&&I(g.levelSize.value)?g.levelSize.value:0,k=b.r,t=k+e,l=g&&I(g.slicedOffset)?g.slicedOffset:0;return(d||[]).reduce(function(b,d){var g=1/n*d.val*h,m=f+g/2,y=a+Math.cos(m)*l;m=c+Math.sin(m)*l;d={x:d.sliced?y:a,y:d.sliced?m:c,innerR:k,r:t,radius:e,start:f,end:f+g};b.push(d);f=d.end;return b},[])},setShapeArgs:function(b,d,g){var f=[],h=g[b.level+1];b=b.children.filter(function(b){return b.visible});f=this.layoutAlgorithm(d,b,h);b.forEach(function(b,a){a=f[a];var c=a.start+(a.end-a.start)/ 2,e=a.innerR+(a.r-a.innerR)/2,d=a.end-a.start;e=0===a.innerR&&6.28<d?{x:a.x,y:a.y}:{x:a.x+Math.cos(c)*e,y:a.y+Math.sin(c)*e};var h=b.val?b.childrenTotal>b.val?b.childrenTotal:b.val:b.childrenTotal;this.points[b.i]&&(this.points[b.i].innerArcLength=d*a.innerR,this.points[b.i].outerArcLength=d*a.r);b.shapeArgs=B(a,{plotX:e.x,plotY:e.y+4*Math.abs(Math.cos(c))});b.values=B(a,{val:h});b.children.length&&this.setShapeArgs(b,b.values,g)},this)},translate:function(){var b=this,d=b.options,k=b.center=A.call(b), l=b.startAndEndRadians=g(d.startAngle,d.endAngle),p=k[3]/2,n=k[2]/2-p,a=Q(b),c=b.nodeMap,e=c&&c[a],q={};b.shapeRoot=e&&e.shapeArgs;L.prototype.translate.call(b);var m=b.tree=b.getTree();b.renderTraverseUpButton(a);c=b.nodeMap;e=c[a];var r=R(e.parent)?e.parent:"";r=c[r];var v=J(e);var u=v.from,w=v.to;v=D({from:u,levels:b.options.levels,to:w,defaults:{colorByPoint:d.colorByPoint,dataLabels:d.dataLabels,levelIsConstant:d.levelIsConstant,levelSize:d.levelSize,slicedOffset:d.slicedOffset}});v=M(v,{diffRadius:n, from:u,to:w});H(m,{before:T,idRoot:a,levelIsConstant:d.levelIsConstant,mapOptionsToLevel:v,mapIdToNode:c,points:b.points,series:b});d=c[""].shapeArgs={end:l.end,r:p,start:l.start,val:e.val,x:k[0],y:k[1]};this.setShapeArgs(r,d,v);b.mapOptionsToLevel=v;b.data.forEach(function(a){q[a.id]&&K(31,!1,b.chart);q[a.id]=!0});q={}},alignDataLabel:function(b,d,g){if(!g.textPath||!g.textPath.enabled)return w.treemap.prototype.alignDataLabel.apply(this,arguments)},animate:function(b){var d=this.chart,f=[d.plotWidth/ 2,d.plotHeight/2],g=d.plotLeft,k=d.plotTop;d=this.group;b?(b={translateX:f[0]+g,translateY:f[1]+k,scaleX:.001,scaleY:.001,rotation:10,opacity:.01},d.attr(b)):(b={translateX:g,translateY:k,scaleX:1,scaleY:1,rotation:0,opacity:1},d.animate(b,this.options.animation))},utils:{calculateLevelSizes:M,getLevelFromAndTo:J,range:P}};p={draw:p.drawPoint,shouldDraw:function(){return!this.isNull},isValid:function(){return!0},getDataLabelPath:function(b){var d=this.series.chart.renderer,f=this.shapeExisting,g= f.start,k=f.end,l=g+(k-g)/2;l=0>l&&l>-Math.PI||l>Math.PI;var a=f.r+(b.options.distance||0);g===-Math.PI/2&&N(k)===N(1.5*Math.PI)&&(g=-Math.PI+Math.PI/360,k=-Math.PI/360,l=!0);if(k-g>Math.PI){l=!1;var c=!0}this.dataLabelPath&&(this.dataLabelPath=this.dataLabelPath.destroy());this.dataLabelPath=d.arc({open:!0,longArc:c?1:0}).add(b);this.dataLabelPath.attr({start:l?g:k,end:l?k:g,clockwise:+l,x:f.x,y:f.y,r:(a+f.innerR)/2});return this.dataLabelPath}};"";b.seriesType("sunburst","treemap",{center:["50%", "50%"],colorByPoint:!1,opacity:1,dataLabels:{allowOverlap:!0,defer:!0,rotationMode:"auto",style:{textOverflow:"ellipsis"}},rootId:void 0,levelIsConstant:!0,levelSize:{value:1,unit:"weight"},slicedOffset:10},d,p)});q(b,"masters/modules/sunburst.src.js",[],function(){})}); //# sourceMappingURL=sunburst.js.map
Java
import _extends from "@babel/runtime/helpers/esm/extends"; import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose"; import * as React from 'react'; import PropTypes from 'prop-types'; import { Transition } from 'react-transition-group'; import useTheme from '../styles/useTheme'; import { reflow, getTransitionProps } from '../transitions/utils'; import useForkRef from '../utils/useForkRef'; function getScale(value) { return `scale(${value}, ${value ** 2})`; } const styles = { entering: { opacity: 1, transform: getScale(1) }, entered: { opacity: 1, transform: 'none' } }; /** * The Grow transition is used by the [Tooltip](/components/tooltips/) and * [Popover](/components/popover/) components. * It uses [react-transition-group](https://github.com/reactjs/react-transition-group) internally. */ const Grow = React.forwardRef(function Grow(props, ref) { const { children, in: inProp, onEnter, onExit, style, timeout = 'auto' } = props, other = _objectWithoutPropertiesLoose(props, ["children", "in", "onEnter", "onExit", "style", "timeout"]); const timer = React.useRef(); const autoTimeout = React.useRef(); const handleRef = useForkRef(children.ref, ref); const theme = useTheme(); const handleEnter = (node, isAppearing) => { reflow(node); // So the animation always start from the start. const { duration: transitionDuration, delay } = getTransitionProps({ style, timeout }, { mode: 'enter' }); let duration; if (timeout === 'auto') { duration = theme.transitions.getAutoHeightDuration(node.clientHeight); autoTimeout.current = duration; } else { duration = transitionDuration; } node.style.transition = [theme.transitions.create('opacity', { duration, delay }), theme.transitions.create('transform', { duration: duration * 0.666, delay })].join(','); if (onEnter) { onEnter(node, isAppearing); } }; const handleExit = node => { const { duration: transitionDuration, delay } = getTransitionProps({ style, timeout }, { mode: 'exit' }); let duration; if (timeout === 'auto') { duration = theme.transitions.getAutoHeightDuration(node.clientHeight); autoTimeout.current = duration; } else { duration = transitionDuration; } node.style.transition = [theme.transitions.create('opacity', { duration, delay }), theme.transitions.create('transform', { duration: duration * 0.666, delay: delay || duration * 0.333 })].join(','); node.style.opacity = '0'; node.style.transform = getScale(0.75); if (onExit) { onExit(node); } }; const addEndListener = (_, next) => { if (timeout === 'auto') { timer.current = setTimeout(next, autoTimeout.current || 0); } }; React.useEffect(() => { return () => { clearTimeout(timer.current); }; }, []); return /*#__PURE__*/React.createElement(Transition, _extends({ appear: true, in: inProp, onEnter: handleEnter, onExit: handleExit, addEndListener: addEndListener, timeout: timeout === 'auto' ? null : timeout }, other), (state, childProps) => { return React.cloneElement(children, _extends({ style: _extends({ opacity: 0, transform: getScale(0.75), visibility: state === 'exited' && !inProp ? 'hidden' : undefined }, styles[state], {}, style, {}, children.props.style), ref: handleRef }, childProps)); }); }); process.env.NODE_ENV !== "production" ? Grow.propTypes = { // ----------------------------- Warning -------------------------------- // | These PropTypes are generated from the TypeScript type definitions | // | To update them edit the d.ts file and run "yarn proptypes" | // ---------------------------------------------------------------------- /** * A single child content element. */ children: PropTypes.element, /** * If `true`, show the component; triggers the enter or exit animation. */ in: PropTypes.bool, /** * @ignore */ onEnter: PropTypes.func, /** * @ignore */ onExit: PropTypes.func, /** * @ignore */ style: PropTypes.object, /** * The duration for the transition, in milliseconds. * You may specify a single timeout for all transitions, or individually with an object. * * Set to 'auto' to automatically calculate transition time based on height. */ timeout: PropTypes.oneOfType([PropTypes.oneOf(['auto']), PropTypes.number, PropTypes.shape({ appear: PropTypes.number, enter: PropTypes.number, exit: PropTypes.number })]) } : void 0; Grow.muiSupportAuto = true; export default Grow;
Java
import * as React from 'react'; declare class JqxGrid extends React.PureComponent<IGridProps, IState> { protected static getDerivedStateFromProps(props: IGridProps, state: IState): null | IState; private _jqx; private _id; private _componentSelector; constructor(props: IGridProps); componentDidMount(): void; componentDidUpdate(): void; render(): React.ReactNode; setOptions(options: IGridProps): void; getOptions(option: string): any; autoresizecolumns(type?: string): void; autoresizecolumn(dataField: string, type?: string): void; beginupdate(): void; clear(): void; createChart(type: string, dataSource?: any): void; destroy(): void; endupdate(): void; ensurerowvisible(rowBoundIndex: number): void; focus(): void; getcolumnindex(dataField: string): number; getcolumn(dataField: string): IGridGetColumn; getcolumnproperty(dataField: string, propertyName: string): any; getrowid(rowBoundIndex: number): string; getrowdata(rowBoundIndex: number): any; getrowdatabyid(rowID: string): any; getrowboundindexbyid(rowID: string): number; getrowboundindex(rowDisplayIndex: number): number; getrows(): any[]; getboundrows(): any[]; getdisplayrows(): any[]; getdatainformation(): IGridGetDataInformation; getsortinformation(): IGridGetSortInformation; getpaginginformation(): IGridGetPagingInformation; hidecolumn(dataField: string): void; hideloadelement(): void; hiderowdetails(rowBoundIndex: number): void; iscolumnvisible(dataField: string): boolean; iscolumnpinned(dataField: string): boolean; localizestrings(localizationobject: IGridLocalizationobject): void; pincolumn(dataField: string): void; refreshdata(): void; refresh(): void; renderWidget(): void; scrolloffset(top: number, left: number): void; scrollposition(): IGridScrollPosition; showloadelement(): void; showrowdetails(rowBoundIndex: number): void; setcolumnindex(dataField: string, index: number): void; setcolumnproperty(dataField: string, propertyName: any, propertyValue: any): void; showcolumn(dataField: string): void; unpincolumn(dataField: string): void; updatebounddata(type?: any): void; updating(): boolean; getsortcolumn(): string; removesort(): void; sortby(dataField: string, sortOrder: string): void; addgroup(dataField: string): void; cleargroups(): void; collapsegroup(group: number | string): void; collapseallgroups(): void; expandallgroups(): void; expandgroup(group: number | string): void; getrootgroupscount(): number; getgroup(groupIndex: number): IGridGetGroup; insertgroup(groupIndex: number, dataField: string): void; iscolumngroupable(): boolean; removegroupat(groupIndex: number): void; removegroup(dataField: string): void; addfilter(dataField: string, filterGroup: any, refreshGrid?: boolean): void; applyfilters(): void; clearfilters(): void; getfilterinformation(): any; getcolumnat(index: number): any; removefilter(dataField: string, refreshGrid: boolean): void; refreshfilterrow(): void; gotopage(pagenumber: number): void; gotoprevpage(): void; gotonextpage(): void; addrow(rowIds: any, data: any, rowPosition?: any): void; begincelledit(rowBoundIndex: number, dataField: string): void; beginrowedit(rowBoundIndex: number): void; closemenu(): void; deleterow(rowIds: string | number | Array<number | string>): void; endcelledit(rowBoundIndex: number, dataField: string, confirmChanges: boolean): void; endrowedit(rowBoundIndex: number, confirmChanges: boolean): void; getcell(rowBoundIndex: number, datafield: string): IGridGetCell; getcellatposition(left: number, top: number): IGridGetCell; getcelltext(rowBoundIndex: number, dataField: string): string; getcelltextbyid(rowID: string, dataField: string): string; getcellvaluebyid(rowID: string, dataField: string): any; getcellvalue(rowBoundIndex: number, dataField: string): any; isBindingCompleted(): boolean; openmenu(dataField: string): void; setcellvalue(rowBoundIndex: number, dataField: string, value: any): void; setcellvaluebyid(rowID: string, dataField: string, value: any): void; showvalidationpopup(rowBoundIndex: number, dataField: string, validationMessage: string): void; updaterow(rowIds: string | number | Array<number | string>, data: any): void; clearselection(): void; getselectedrowindex(): number; getselectedrowindexes(): number[]; getselectedcell(): IGridGetSelectedCell; getselectedcells(): IGridGetSelectedCell[]; selectcell(rowBoundIndex: number, dataField: string): void; selectallrows(): void; selectrow(rowBoundIndex: number): void; unselectrow(rowBoundIndex: number): void; unselectcell(rowBoundIndex: number, dataField: string): void; getcolumnaggregateddata(dataField: string, aggregates: any[]): string; refreshaggregates(): void; renderaggregates(): void; exportdata(dataType: string, fileName?: string, exportHeader?: boolean, rows?: number[], exportHiddenColumns?: boolean, serverURL?: string, charSet?: string): any; exportview(dataType: string, fileName?: string): any; openColumnChooser(columns?: any, header?: string): void; getstate(): IGridGetState; loadstate(stateobject: any): void; savestate(): IGridGetState; private _manageProps; private _wireEvents; } export default JqxGrid; export declare const jqx: any; export declare const JQXLite: any; interface IState { lastProps: object; } export interface IGridCharting { appendTo?: string; colorScheme?: string; dialog?: (width: number, height: number, header: string, position: any, enabled: boolean) => void; formatSettings?: any; ready?: any; } export interface IGridColumn { text?: string; datafield?: string; displayfield?: string; threestatecheckbox?: boolean; sortable?: boolean; filterable?: boolean; filter?: (cellValue?: any, rowData?: any, dataField?: string, filterGroup?: any, defaultFilterResult?: any) => any; buttonclick?: (row: number) => void; hideable?: boolean; hidden?: boolean; groupable?: boolean; menu?: boolean; exportable?: boolean; columngroup?: string; enabletooltips?: boolean; columntype?: 'number' | 'checkbox' | 'button' | 'numberinput' | 'dropdownlist' | 'combobox' | 'datetimeinput' | 'textbox' | 'rating' | 'progressbar' | 'template' | 'custom'; renderer?: (defaultText?: string, alignment?: string, height?: number) => string; rendered?: (columnHeaderElement?: any) => void; cellsrenderer?: (row?: number, columnfield?: string, value?: any, defaulthtml?: string, columnproperties?: any, rowdata?: any) => string; aggregatesrenderer?: (aggregates?: any, column?: any, element?: any, summaryData?: any) => string; validation?: (cell?: any, value?: number) => any; createwidget?: (row: any, column: any, value: string, cellElement: any) => void; initwidget?: (row: number, column: string, value: string, cellElement: any) => void; createfilterwidget?: (column: any, htmlElement: HTMLElement, editor: any) => void; createfilterpanel?: (datafield: string, filterPanel: any) => void; initeditor?: (row: number, cellvalue: any, editor: any, celltext: any, pressedChar: string, callback: any) => void; createeditor?: (row: number, cellvalue: any, editor: any, celltext: any, cellwidth: any, cellheight: any) => void; destroyeditor?: (row: number, callback: any) => void; geteditorvalue?: (row: number, cellvalue: any, editor: any) => any; cellbeginedit?: (row: number, datafield: string, columntype: string, value: any) => boolean; cellendedit?: (row: number, datafield: string, columntype: string, oldvalue: any, newvalue: any) => boolean; cellvaluechanging?: (row: number, datafield: string, columntype: string, oldvalue: any, newvalue: any) => string | void; createeverpresentrowwidget?: (datafield: string, htmlElement: HTMLElement, popup: any, addRowCallback: any) => any; initeverpresentrowwidget?: (datafield: string, htmlElement: HTMLElement, popup: any) => void; reseteverpresentrowwidgetvalue?: (datafield: string, htmlElement: HTMLElement) => void; geteverpresentrowwidgetvalue?: (datafield: string, htmlElement: HTMLElement) => any; destroyeverpresentrowwidget?: (htmlElement: HTMLElement) => void; validateeverpresentrowwidgetvalue?: (datafield: string, value: any, rowValues: any) => boolean | object; cellsformat?: string; cellclassname?: any; aggregates?: any; align?: 'left' | 'center' | 'right'; cellsalign?: 'left' | 'center' | 'right'; width?: number | string; minwidth?: any; maxwidth?: any; resizable?: boolean; draggable?: boolean; editable?: boolean; classname?: string; pinned?: boolean; nullable?: boolean; filteritems?: any; filterdelay?: number; filtertype?: 'textbox' | 'input' | 'checkedlist' | 'list' | 'number' | 'bool' | 'date' | 'range' | 'custom'; filtercondition?: 'EMPTY' | 'NOT_EMPTY' | 'CONTAINS' | 'CONTAINS_CASE_SENSITIVE' | 'DOES_NOT_CONTAIN' | 'DOES_NOT_CONTAIN_CASE_SENSITIVE' | 'STARTS_WITH' | 'STARTS_WITH_CASE_SENSITIVE' | 'ENDS_WITH' | 'ENDS_WITH_CASE_SENSITIVE' | 'EQUAL' | 'EQUAL_CASE_SENSITIVE' | 'NULL' | 'NOT_NULL' | 'EQUAL' | 'NOT_EQUAL' | 'LESS_THAN' | 'LESS_THAN_OR_EQUAL' | 'GREATER_THAN' | 'GREATER_THAN_OR_EQUAL' | 'NULL' | 'NOT_NULL'; } export interface IGridSourceDataFields { name?: string; type?: 'string' | 'date' | 'int' | 'float' | 'number' | 'bool'; format?: string; map?: string; id?: string; text?: string; source?: any[]; } export interface IGridSource { url?: string; data?: any; localdata?: any; datatype?: 'xml' | 'json' | 'jsonp' | 'tsv' | 'csv' | 'local' | 'array' | 'observablearray'; type?: 'GET' | 'POST'; id?: string; root?: string; record?: string; datafields?: IGridSourceDataFields[]; pagenum?: number; pagesize?: number; pager?: (pagenum?: number, pagesize?: number, oldpagenum?: number) => any; sortcolumn?: string; sortdirection?: 'asc' | 'desc'; sort?: (column?: any, direction?: any) => void; filter?: (filters?: any, recordsArray?: any) => void; addrow?: (rowid?: any, rowdata?: any, position?: any, commit?: boolean) => void; deleterow?: (rowid?: any, commit?: boolean) => void; updaterow?: (rowid?: any, newdata?: any, commit?: any) => void; processdata?: (data: any) => void; formatdata?: (data: any) => any; async?: boolean; totalrecords?: number; unboundmode?: boolean; } export interface IGridGetColumn { datafield?: string; displayfield?: string; text?: string; sortable?: boolean; filterable?: boolean; exportable?: boolean; editable?: boolean; groupable?: boolean; resizable?: boolean; draggable?: boolean; classname?: string; cellclassname?: any; width?: number | string; menu?: boolean; } export interface IGridGetDataInformation { rowscount?: string; sortinformation?: any; sortcolumn?: any; sortdirection?: any; paginginformation?: any; pagenum?: any; pagesize?: any; pagescount?: any; } export interface IGridGetSortInformation { sortcolumn?: string; sortdirection?: any; } export interface IGridGetPagingInformation { pagenum?: string; pagesize?: any; pagescount?: any; } export interface IGridDateNaming { names?: string[]; namesAbbr?: string[]; namesShort?: string[]; } export interface IGridLocalizationobject { filterstringcomparisonoperators?: any; filternumericcomparisonoperators?: any; filterdatecomparisonoperators?: any; filterbooleancomparisonoperators?: any; pagergotopagestring?: string; pagershowrowsstring?: string; pagerrangestring?: string; pagernextbuttonstring?: string; pagerpreviousbuttonstring?: string; sortascendingstring?: string; sortdescendingstring?: string; sortremovestring?: string; firstDay?: number; percentsymbol?: string; currencysymbol?: string; currencysymbolposition?: string; decimalseparator?: string; thousandsseparator?: string; days?: IGridDateNaming; months?: IGridDateNaming; addrowstring?: string; updaterowstring?: string; deleterowstring?: string; resetrowstring?: string; everpresentrowplaceholder?: string; emptydatastring?: string; } export interface IGridScrollPosition { top?: number; left?: number; } export interface IGridGetGroup { group?: number; level?: number; expanded?: number; subgroups?: number; subrows?: number; } export interface IGridGetCell { value?: number; row?: number; column?: number; } export interface IGridGetSelectedCell { rowindex?: number; datafield?: string; } export interface IGridGetStateColumns { width?: number | string; hidden?: boolean; index?: number; pinned?: boolean; groupable?: boolean; resizable?: boolean; draggable?: boolean; text?: string; align?: string; cellsalign?: string; } export interface IGridGetState { width?: number | string; height?: number | string; pagenum?: number; pagesize?: number; pagesizeoptions?: string[]; sortcolumn?: any; sortdirection?: any; filters?: any; groups?: any; columns?: IGridGetStateColumns; } export interface IGridColumnmenuopening { menu?: any; datafield?: any; height?: any; } export interface IGridColumnmenuclosing { menu?: any; datafield?: any; height?: any; } export interface IGridCellhover { cellhtmlElement?: any; x?: any; y?: any; } export interface IGridGroupsrenderer { text?: string; group?: number; expanded?: boolean; data?: object; } export interface IGridGroupcolumnrenderer { text?: any; } export interface IGridHandlekeyboardnavigation { event?: any; } export interface IGridScrollfeedback { row?: object; } export interface IGridFilter { cellValue?: any; rowData?: any; dataField?: string; filterGroup?: any; defaultFilterResult?: boolean; } export interface IGridRendertoolbar { toolbar?: any; } export interface IGridRenderstatusbar { statusbar?: any; } interface IGridOptions { altrows?: boolean; altstart?: number; altstep?: number; autoshowloadelement?: boolean; autoshowfiltericon?: boolean; autoshowcolumnsmenubutton?: boolean; showcolumnlines?: boolean; showrowlines?: boolean; showcolumnheaderlines?: boolean; adaptive?: boolean; adaptivewidth?: number; clipboard?: boolean; closeablegroups?: boolean; columnsmenuwidth?: number; columnmenuopening?: (menu?: IGridColumnmenuopening['menu'], datafield?: IGridColumnmenuopening['datafield'], height?: IGridColumnmenuopening['height']) => boolean | void; columnmenuclosing?: (menu?: IGridColumnmenuclosing['menu'], datafield?: IGridColumnmenuclosing['datafield'], height?: IGridColumnmenuclosing['height']) => boolean; cellhover?: (cellhtmlElement?: IGridCellhover['cellhtmlElement'], x?: IGridCellhover['x'], y?: IGridCellhover['y']) => void; enablekeyboarddelete?: boolean; enableellipsis?: boolean; enablemousewheel?: boolean; enableanimations?: boolean; enabletooltips?: boolean; enablehover?: boolean; enablebrowserselection?: boolean; everpresentrowposition?: 'top' | 'bottom' | 'topAboveFilterRow'; everpresentrowheight?: number; everpresentrowactions?: string; everpresentrowactionsmode?: 'popup' | 'columns'; filterrowheight?: number; filtermode?: 'default' | 'excel'; groupsrenderer?: (text?: IGridGroupsrenderer['text'], group?: IGridGroupsrenderer['group'], expanded?: IGridGroupsrenderer['expanded'], data?: IGridGroupsrenderer['data']) => string; groupcolumnrenderer?: (text?: IGridGroupcolumnrenderer['text']) => string; groupsexpandedbydefault?: boolean; handlekeyboardnavigation?: (event: IGridHandlekeyboardnavigation['event']) => boolean; pagerrenderer?: () => any[]; rtl?: boolean; showdefaultloadelement?: boolean; showfiltercolumnbackground?: boolean; showfiltermenuitems?: boolean; showpinnedcolumnbackground?: boolean; showsortcolumnbackground?: boolean; showsortmenuitems?: boolean; showgroupmenuitems?: boolean; showrowdetailscolumn?: boolean; showheader?: boolean; showgroupsheader?: boolean; showaggregates?: boolean; showgroupaggregates?: boolean; showeverpresentrow?: boolean; showfilterrow?: boolean; showemptyrow?: boolean; showstatusbar?: boolean; statusbarheight?: number; showtoolbar?: boolean; showfilterbar?: boolean; filterbarmode?: string; selectionmode?: 'none' | 'singlerow' | 'multiplerows' | 'multiplerowsextended' | 'singlecell' | 'multiplecells' | 'multiplecellsextended' | 'multiplecellsadvanced' | 'checkbox'; updatefilterconditions?: (type?: string, defaultconditions?: any) => any; updatefilterpanel?: (filtertypedropdown1?: any, filtertypedropdown2?: any, filteroperatordropdown?: any, filterinputfield1?: any, filterinputfield2?: any, filterbutton?: any, clearbutton?: any, columnfilter?: any, filtertype?: any, filterconditions?: any) => any; theme?: string; toolbarheight?: number; autoheight?: boolean; autorowheight?: boolean; columnsheight?: number; deferreddatafields?: string[]; groupsheaderheight?: number; groupindentwidth?: number; height?: number | string; pagerheight?: number | string; rowsheight?: number; scrollbarsize?: number | string; scrollmode?: 'default' | 'logical' | 'deferred'; scrollfeedback?: (row: IGridScrollfeedback['row']) => string; width?: string | number; autosavestate?: boolean; autoloadstate?: boolean; columns?: IGridColumn[]; enableSanitize?: boolean; cardview?: boolean; cardviewcolumns?: any; cardheight?: number; cardsize?: number; columngroups?: any[]; columnsmenu?: boolean; columnsresize?: boolean; columnsautoresize?: boolean; columnsreorder?: boolean; charting?: IGridCharting; disabled?: boolean; editable?: boolean; editmode?: 'click' | 'selectedcell' | 'selectedrow' | 'dblclick' | 'programmatic'; filter?: (cellValue?: IGridFilter['cellValue'], rowData?: IGridFilter['rowData'], dataField?: IGridFilter['dataField'], filterGroup?: IGridFilter['filterGroup'], defaultFilterResult?: IGridFilter['defaultFilterResult']) => any; filterable?: boolean; groupable?: boolean; groups?: string[]; horizontalscrollbarstep?: number; horizontalscrollbarlargestep?: number; initrowdetails?: (index?: number, parentElement?: any, gridElement?: any, datarecord?: any) => void; keyboardnavigation?: boolean; localization?: IGridLocalizationobject; pagesize?: number; pagesizeoptions?: Array<number | string>; pagermode?: 'simple' | 'default' | 'material'; pagerbuttonscount?: number; pageable?: boolean; autofill?: boolean; rowdetails?: boolean; rowdetailstemplate?: any; ready?: () => void; rendered?: (type: any) => void; renderstatusbar?: (statusbar?: IGridRenderstatusbar['statusbar']) => void; rendertoolbar?: (toolbar?: IGridRendertoolbar['toolbar']) => void; rendergridrows?: (params?: any) => any; sortable?: boolean; sortmode?: string; selectedrowindex?: number; selectedrowindexes?: number[]; source?: IGridSource; sorttogglestates?: '0' | '1' | '2'; updatedelay?: number; virtualmode?: boolean; verticalscrollbarstep?: number; verticalscrollbarlargestep?: number; } export interface IGridProps extends IGridOptions { className?: string; style?: React.CSSProperties; onBindingcomplete?: (e?: Event) => void; onColumnresized?: (e?: Event) => void; onColumnreordered?: (e?: Event) => void; onColumnclick?: (e?: Event) => void; onCellclick?: (e?: Event) => void; onCelldoubleclick?: (e?: Event) => void; onCellselect?: (e?: Event) => void; onCellunselect?: (e?: Event) => void; onCellvaluechanged?: (e?: Event) => void; onCellbeginedit?: (e?: Event) => void; onCellendedit?: (e?: Event) => void; onFilter?: (e?: Event) => void; onGroupschanged?: (e?: Event) => void; onGroupexpand?: (e?: Event) => void; onGroupcollapse?: (e?: Event) => void; onPagechanged?: (e?: Event) => void; onPagesizechanged?: (e?: Event) => void; onRowclick?: (e?: Event) => void; onRowdoubleclick?: (e?: Event) => void; onRowselect?: (e?: Event) => void; onRowunselect?: (e?: Event) => void; onRowexpand?: (e?: Event) => void; onRowcollapse?: (e?: Event) => void; onSort?: (e?: Event) => void; }
Java
"use strict"; exports.__esModule = true; exports.default = void 0; var React = _interopRequireWildcard(require("react")); var _createElement = _interopRequireDefault(require("../createElement")); var _css = _interopRequireDefault(require("../StyleSheet/css")); var _pick = _interopRequireDefault(require("../../modules/pick")); var _useElementLayout = _interopRequireDefault(require("../../hooks/useElementLayout")); var _useMergeRefs = _interopRequireDefault(require("../../modules/useMergeRefs")); var _usePlatformMethods = _interopRequireDefault(require("../../hooks/usePlatformMethods")); var _useResponderEvents = _interopRequireDefault(require("../../hooks/useResponderEvents")); var _StyleSheet = _interopRequireDefault(require("../StyleSheet")); var _TextAncestorContext = _interopRequireDefault(require("../Text/TextAncestorContext")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } /** * Copyright (c) Nicolas Gallagher. * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ var forwardPropsList = { accessibilityLabel: true, accessibilityLiveRegion: true, accessibilityRole: true, accessibilityState: true, accessibilityValue: true, accessible: true, children: true, classList: true, disabled: true, importantForAccessibility: true, nativeID: true, onBlur: true, onClick: true, onClickCapture: true, onContextMenu: true, onFocus: true, onKeyDown: true, onKeyUp: true, onTouchCancel: true, onTouchCancelCapture: true, onTouchEnd: true, onTouchEndCapture: true, onTouchMove: true, onTouchMoveCapture: true, onTouchStart: true, onTouchStartCapture: true, pointerEvents: true, ref: true, style: true, testID: true, // unstable dataSet: true, onMouseDown: true, onMouseEnter: true, onMouseLeave: true, onMouseMove: true, onMouseOver: true, onMouseOut: true, onMouseUp: true, onScroll: true, onWheel: true, href: true, rel: true, target: true }; var pickProps = function pickProps(props) { return (0, _pick.default)(props, forwardPropsList); }; var View = (0, React.forwardRef)(function (props, forwardedRef) { var onLayout = props.onLayout, onMoveShouldSetResponder = props.onMoveShouldSetResponder, onMoveShouldSetResponderCapture = props.onMoveShouldSetResponderCapture, onResponderEnd = props.onResponderEnd, onResponderGrant = props.onResponderGrant, onResponderMove = props.onResponderMove, onResponderReject = props.onResponderReject, onResponderRelease = props.onResponderRelease, onResponderStart = props.onResponderStart, onResponderTerminate = props.onResponderTerminate, onResponderTerminationRequest = props.onResponderTerminationRequest, onScrollShouldSetResponder = props.onScrollShouldSetResponder, onScrollShouldSetResponderCapture = props.onScrollShouldSetResponderCapture, onSelectionChangeShouldSetResponder = props.onSelectionChangeShouldSetResponder, onSelectionChangeShouldSetResponderCapture = props.onSelectionChangeShouldSetResponderCapture, onStartShouldSetResponder = props.onStartShouldSetResponder, onStartShouldSetResponderCapture = props.onStartShouldSetResponderCapture; if (process.env.NODE_ENV !== 'production') { React.Children.toArray(props.children).forEach(function (item) { if (typeof item === 'string') { console.error("Unexpected text node: " + item + ". A text node cannot be a child of a <View>."); } }); } var hasTextAncestor = (0, React.useContext)(_TextAncestorContext.default); var hostRef = (0, React.useRef)(null); var classList = [classes.view]; var style = _StyleSheet.default.compose(hasTextAncestor && styles.inline, props.style); (0, _useElementLayout.default)(hostRef, onLayout); (0, _useResponderEvents.default)(hostRef, { onMoveShouldSetResponder: onMoveShouldSetResponder, onMoveShouldSetResponderCapture: onMoveShouldSetResponderCapture, onResponderEnd: onResponderEnd, onResponderGrant: onResponderGrant, onResponderMove: onResponderMove, onResponderReject: onResponderReject, onResponderRelease: onResponderRelease, onResponderStart: onResponderStart, onResponderTerminate: onResponderTerminate, onResponderTerminationRequest: onResponderTerminationRequest, onScrollShouldSetResponder: onScrollShouldSetResponder, onScrollShouldSetResponderCapture: onScrollShouldSetResponderCapture, onSelectionChangeShouldSetResponder: onSelectionChangeShouldSetResponder, onSelectionChangeShouldSetResponderCapture: onSelectionChangeShouldSetResponderCapture, onStartShouldSetResponder: onStartShouldSetResponder, onStartShouldSetResponderCapture: onStartShouldSetResponderCapture }); var supportedProps = pickProps(props); supportedProps.classList = classList; supportedProps.style = style; var platformMethodsRef = (0, _usePlatformMethods.default)(hostRef, supportedProps); var setRef = (0, _useMergeRefs.default)(hostRef, platformMethodsRef, forwardedRef); supportedProps.ref = setRef; return (0, _createElement.default)('div', supportedProps); }); View.displayName = 'View'; var classes = _css.default.create({ view: { alignItems: 'stretch', border: '0 solid black', boxSizing: 'border-box', display: 'flex', flexBasis: 'auto', flexDirection: 'column', flexShrink: 0, margin: 0, minHeight: 0, minWidth: 0, padding: 0, position: 'relative', zIndex: 0 } }); var styles = _StyleSheet.default.create({ inline: { display: 'inline-flex' } }); var _default = View; exports.default = _default; module.exports = exports.default;
Java
/******************************************************************************* * Copyright (c) 2011, 2020 Eurotech and/or its affiliates and others * * This program and the accompanying materials are made * available under the terms of the Eclipse Public License 2.0 * which is available at https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 * * Contributors: * Eurotech ******************************************************************************/ package org.eclipse.kura.net; import java.util.Map; import org.osgi.annotation.versioning.ProviderType; import org.osgi.service.event.Event; /** * An event raised when a network interface has been removed from the system. * * @noextend This class is not intended to be subclassed by clients. */ @ProviderType public class NetInterfaceRemovedEvent extends Event { /** Topic of the NetworkInterfaceRemovedEvent */ public static final String NETWORK_EVENT_INTERFACE_REMOVED_TOPIC = "org/eclipse/kura/net/NetworkEvent/interface/REMOVED"; /** Name of the property to access the network interface name */ public static final String NETWORK_EVENT_INTERFACE_PROPERTY = "network.interface"; public NetInterfaceRemovedEvent(Map<String, ?> properties) { super(NETWORK_EVENT_INTERFACE_REMOVED_TOPIC, properties); } /** * Returns the name of the removed interface. * * @return */ public String getInterfaceName() { return (String) getProperty(NETWORK_EVENT_INTERFACE_PROPERTY); } }
Java
package invalid; public class TestInvalidFieldInitializer3 { private Object field= /*]*/foo()/*[*/; public Object foo() { return field; } }
Java
// Copyright (c) 2016 IBM Corporation. #ifndef LANGUAGE_EXTERN_H #define LANGUAGE_EXTERN_H #include "language-extern_sigs.h" #include <stdexcept> #include <fstream> #include <sstream> #include "termprinter.h" #include "termreader.h" template <typename a> tosca::StringTerm& PrintTerm(tosca::Context& ctx, tosca::StringTerm& category, a& term) { tosca::Term& t = dynamic_cast<tosca::Term&>(term); return newStringTerm(ctx, tosca::PrintToString(t, true)); } template <typename a> a& ParseResource(tosca::Context& ctx, tosca::StringTerm& category, tosca::StringTerm& filename) { // TODO: user-defined category std::fstream input(filename.Unbox().c_str(), std::ios_base::in); tosca::TermParser parser(&input); tosca::Term& term = parser.ParseTerm(ctx); a& result = dynamic_cast<a&>(term); category.Release(); filename.Release(); return result; } template <typename a, typename b> b& Save(tosca::Context& ctx, tosca::StringTerm& category, tosca::StringTerm& filename, a& term, tosca::MapTerm<tosca::StringTerm, tosca::StringTerm>& props, b& result) { // TODO: user-defined category. //const std::string& ucat = category.Unbox(); //if (ucat == "" || ucat == "term") { std::fstream output(filename.Unbox().c_str(), std::ios_base::out); tosca::Print(static_cast<tosca::Term&>(term), output, false); } category.Release(); filename.Release(); props.Release(); return result; } template <typename a> a& ParseText(tosca::Context& ctx, tosca::StringTerm& category, tosca::StringTerm& content) { std::stringstream input(content.Unbox().c_str(), std::ios_base::in); tosca::TermParser parser(&input); tosca::Term& term = parser.ParseTerm(ctx); a& result = dynamic_cast<a&>(term); category.Release(); content.Release(); return result; } #endif
Java
/* ********************************************************************** ** ** Copyright notice ** ** ** ** (c) 2005-2009 RSSOwl Development Team ** ** http://www.rssowl.org/ ** ** ** ** All rights reserved ** ** ** ** This program and the accompanying materials are made available under ** ** the terms of the Eclipse Public License v1.0 which accompanies this ** ** distribution, and is available at: ** ** http://www.rssowl.org/legal/epl-v10.html ** ** ** ** A copy is found in the file epl-v10.html and important notices to the ** ** license from the team is found in the textfile LICENSE.txt distributed ** ** in this package. ** ** ** ** This copyright notice MUST APPEAR in all copies of the file! ** ** ** ** Contributors: ** ** RSSOwl Development Team - initial API and implementation ** ** ** ** ********************************************************************** */ package org.rssowl.core.internal.persist.service; import org.rssowl.core.persist.IEntity; import org.rssowl.core.persist.event.ModelEvent; import org.rssowl.core.persist.event.runnable.EventRunnable; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.IdentityHashMap; import java.util.List; import java.util.Map; /** * A {@link Map} of {@link ModelEvent} pointing to {@link EventRunnable}. */ public class EventsMap { private static final EventsMap INSTANCE = new EventsMap(); private static class InternalMap extends HashMap<Class<? extends ModelEvent>, EventRunnable<? extends ModelEvent>> { InternalMap() { super(); } } private final ThreadLocal<InternalMap> fEvents = new ThreadLocal<InternalMap>(); private final ThreadLocal<Map<IEntity, ModelEvent>> fEventTemplatesMap = new ThreadLocal<Map<IEntity, ModelEvent>>(); private EventsMap() { // Enforce singleton pattern } public final static EventsMap getInstance() { return INSTANCE; } public final void putPersistEvent(ModelEvent event) { EventRunnable<? extends ModelEvent> eventRunnable = getEventRunnable(event); eventRunnable.addCheckedPersistEvent(event); } public final void putUpdateEvent(ModelEvent event) { EventRunnable<? extends ModelEvent> eventRunnable = getEventRunnable(event); eventRunnable.addCheckedUpdateEvent(event); } public final void putRemoveEvent(ModelEvent event) { EventRunnable<? extends ModelEvent> eventRunnable = getEventRunnable(event); eventRunnable.addCheckedRemoveEvent(event); } public final boolean containsPersistEvent(Class<? extends ModelEvent> eventClass, IEntity entity) { EventRunnable<? extends ModelEvent> eventRunnable = getEventRunnable(eventClass); return eventRunnable.getPersistEvents().contains(entity); } public final boolean containsUpdateEvent(Class<? extends ModelEvent> eventClass, IEntity entity) { EventRunnable<? extends ModelEvent> eventRunnable = getEventRunnable(eventClass); return eventRunnable.getUpdateEvents().contains(entity); } public final boolean containsRemoveEvent(Class<? extends ModelEvent> eventClass, IEntity entity) { EventRunnable<? extends ModelEvent> eventRunnable = getEventRunnable(eventClass); return eventRunnable.getRemoveEvents().contains(entity); } private EventRunnable<? extends ModelEvent> getEventRunnable(Class<? extends ModelEvent> eventClass) { InternalMap map = fEvents.get(); if (map == null) { map = new InternalMap(); fEvents.set(map); } EventRunnable<? extends ModelEvent> eventRunnable = map.get(eventClass); return eventRunnable; } private EventRunnable<? extends ModelEvent> getEventRunnable(ModelEvent event) { Class<? extends ModelEvent> eventClass = event.getClass(); EventRunnable<? extends ModelEvent> eventRunnable = getEventRunnable(eventClass); if (eventRunnable == null) { eventRunnable = event.createEventRunnable(); fEvents.get().put(eventClass, eventRunnable); } return eventRunnable; } public EventRunnable<? extends ModelEvent> removeEventRunnable(Class<? extends ModelEvent> klass) { InternalMap map = fEvents.get(); if (map == null) return null; EventRunnable<? extends ModelEvent> runnable = map.remove(klass); return runnable; } public List<EventRunnable<?>> getEventRunnables() { InternalMap map = fEvents.get(); if (map == null) return new ArrayList<EventRunnable<?>>(0); List<EventRunnable<?>> eventRunnables = new ArrayList<EventRunnable<?>>(map.size()); for (Map.Entry<Class<? extends ModelEvent>, EventRunnable<? extends ModelEvent>> entry : map.entrySet()) { eventRunnables.add(entry.getValue()); } return eventRunnables; } public List<EventRunnable<?>> removeEventRunnables() { InternalMap map = fEvents.get(); if (map == null) return new ArrayList<EventRunnable<?>>(0); List<EventRunnable<?>> eventRunnables = getEventRunnables(); map.clear(); return eventRunnables; } public void putEventTemplate(ModelEvent event) { Map<IEntity, ModelEvent> map = fEventTemplatesMap.get(); if (map == null) { map = new IdentityHashMap<IEntity, ModelEvent>(); fEventTemplatesMap.set(map); } map.put(event.getEntity(), event); } public final Map<IEntity, ModelEvent> getEventTemplatesMap() { Map<IEntity, ModelEvent> map = fEventTemplatesMap.get(); if (map == null) return Collections.emptyMap(); return Collections.unmodifiableMap(fEventTemplatesMap.get()); } public Map<IEntity, ModelEvent> removeEventTemplatesMap() { Map<IEntity, ModelEvent> map = fEventTemplatesMap.get(); fEventTemplatesMap.remove(); return map; } }
Java
/******************************************************************************* * Copyright (c) 2011, 2020 Eurotech and/or its affiliates and others * * This program and the accompanying materials are made * available under the terms of the Eclipse Public License 2.0 * which is available at https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 * * Contributors: * Eurotech *******************************************************************************/ package org.eclipse.kura.web.shared.model; import java.io.Serializable; import java.util.Date; import org.eclipse.kura.web.shared.DateUtils; public class GwtDeviceConfig extends GwtBaseModel implements Serializable { private static final long serialVersionUID = 1708831984640005284L; public GwtDeviceConfig() { } @Override @SuppressWarnings({ "unchecked" }) public <X> X get(String property) { if ("lastEventOnFormatted".equals(property)) { return (X) DateUtils.formatDateTime((Date) get("lastEventOn")); } else if ("uptimeFormatted".equals(property)) { if (getUptime() == -1) { return (X) "Unknown"; } else { return (X) String.valueOf(getUptime()); } } else { return super.get(property); } } public String getAccountName() { return get("accountName"); } public void setAccountName(String accountName) { set("accountName", accountName); } public String getClientId() { return (String) get("clientId"); } public void setClientId(String clientId) { set("clientId", clientId); } public Long getUptime() { return (Long) get("uptime"); } public String getUptimeFormatted() { return (String) get("uptimeFormatted"); } public void setUptime(Long uptime) { set("uptime", uptime); } public String getGwtDeviceStatus() { return (String) get("gwtDeviceStatus"); } public void setGwtDeviceStatus(String gwtDeviceStatus) { set("gwtDeviceStatus", gwtDeviceStatus); } public String getDisplayName() { return (String) get("displayName"); } public void setDisplayName(String displayName) { set("displayName", displayName); } public String getModelName() { return (String) get("modelName"); } public void setModelName(String modelName) { set("modelName", modelName); } public String getModelId() { return (String) get("modelId"); } public void setModelId(String modelId) { set("modelId", modelId); } public String getPartNumber() { return (String) get("partNumber"); } public void setPartNumber(String partNumber) { set("partNumber", partNumber); } public String getSerialNumber() { return (String) get("serialNumber"); } public void setSerialNumber(String serialNumber) { set("serialNumber", serialNumber); } public String getAvailableProcessors() { return (String) get("availableProcessors"); } public void setAvailableProcessors(String availableProcessors) { set("availableProcessors", availableProcessors); } public String getTotalMemory() { return (String) get("totalMemory"); } public void setTotalMemory(String totalMemory) { set("totalMemory", totalMemory); } public String getFirmwareVersion() { return (String) get("firmwareVersion"); } public void setFirmwareVersion(String firmwareVersion) { set("firmwareVersion", firmwareVersion); } public String getBiosVersion() { return (String) get("biosVersion"); } public void setBiosVersion(String biosVersion) { set("biosVersion", biosVersion); } public String getOs() { return (String) get("os"); } public void setOs(String os) { set("os", os); } public String getOsVersion() { return (String) get("osVersion"); } public void setOsVersion(String osVersion) { set("osVersion", osVersion); } public String getOsArch() { return (String) get("osArch"); } public void setOsArch(String osArch) { set("osArch", osArch); } public String getJvmName() { return (String) get("jvmName"); } public void setJvmName(String jvmName) { set("jvmName", jvmName); } public String getJvmVersion() { return (String) get("jvmVersion"); } public void setJvmVersion(String jvmVersion) { set("jvmVersion", jvmVersion); } public String getJvmProfile() { return (String) get("jvmProfile"); } public void setJvmProfile(String jvmProfile) { set("jvmProfile", jvmProfile); } public String getOsgiFramework() { return (String) get("osgiFramework"); } public void setOsgiFramework(String osgiFramework) { set("osgiFramework", osgiFramework); } public String getOsgiFrameworkVersion() { return (String) get("osgiFrameworkVersion"); } public void setOsgiFrameworkVersion(String osgiFrameworkVersion) { set("osgiFrameworkVersion", osgiFrameworkVersion); } public String getConnectionInterface() { return (String) get("connectionInterface"); } public void setConnectionInterface(String connectionInterface) { set("connectionInterface", connectionInterface); } public String getConnectionIp() { return (String) get("connectionIp"); } public void setConnectionIp(String connectionIp) { set("connectionIp", connectionIp); } public String getAcceptEncoding() { return (String) get("acceptEncoding"); } public void setAcceptEncoding(String acceptEncoding) { set("acceptEncoding", acceptEncoding); } public String getApplicationIdentifiers() { return (String) get("applicationIdentifiers"); } public void setApplicationIdentifiers(String applicationIdentifiers) { set("applicationIdentifiers", applicationIdentifiers); } public Double getGpsLatitude() { return (Double) get("gpsLatitude"); } public void setGpsLatitude(Double gpsLatitude) { set("gpsLatitude", gpsLatitude); } public Double getGpsLongitude() { return (Double) get("gpsLongitude"); } public void setGpsLongitude(Double gpsLongitude) { set("gpsLongitude", gpsLongitude); } public Double getGpsAltitude() { return (Double) get("gpsAltitude"); } public void setGpsAltitude(Double gpsAltitude) { set("gpsAltitude", gpsAltitude); } public String getGpsAddress() { return (String) get("gpsAddress"); } public void setGpsAddress(String gpsAddress) { set("gpsAddress", gpsAddress); } public Date getLastEventOn() { return (Date) get("lastEventOn"); } public String getLastEventOnFormatted() { return (String) get("lastEventOnFormatted"); } public void setLastEventOn(Date lastEventDate) { set("lastEventOn", lastEventDate); } public String getLastEventType() { return (String) get("lastEventType"); } public void setLastEventType(String lastEventType) { set("lastEventType", lastEventType); } public boolean isOnline() { return getGwtDeviceStatus().compareTo("CONNECTED") == 0; } }
Java
/* * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.controller.sal.connector.remoterpc; import com.google.common.base.Optional; import junit.framework.Assert; import org.junit.*; import org.opendaylight.controller.sal.connector.api.RpcRouter; import org.opendaylight.controller.sal.connector.remoterpc.api.RoutingTable; import org.opendaylight.controller.sal.connector.remoterpc.utils.MessagingUtil; import org.opendaylight.controller.sal.core.api.Broker; import org.opendaylight.controller.sal.core.api.RpcRegistrationListener; import org.opendaylight.yangtools.yang.data.api.CompositeNode; import org.zeromq.ZMQ; import zmq.Ctx; import zmq.SocketBase; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.ThreadPoolExecutor; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class ServerImplTest { private static ZMQ.Context context; private ServerImpl server; private Broker.ProviderSession brokerSession; private RoutingTableProvider routingTableProvider; private RpcRegistrationListener listener; ExecutorService pool; //Server configuration private final int HANDLER_COUNT = 2; private final int HWM = 200; private final int port = 5554; //server address private final String SERVER_ADDRESS = "tcp://localhost:5554"; //@BeforeClass public static void init() { context = ZMQ.context(1); } //@AfterClass public static void destroy() { MessagingUtil.closeZmqContext(context); } @Before public void setup() throws InterruptedException { context = ZMQ.context(1); brokerSession = mock(Broker.ProviderSession.class); routingTableProvider = mock(RoutingTableProvider.class); listener = mock(RpcRegistrationListener.class); server = new ServerImpl(port); server.setBrokerSession(brokerSession); RoutingTable<RpcRouter.RouteIdentifier, String> mockRoutingTable = new MockRoutingTable<String, String>(); Optional<RoutingTable<RpcRouter.RouteIdentifier, String>> optionalRoutingTable = Optional.fromNullable(mockRoutingTable); when(routingTableProvider.getRoutingTable()).thenReturn(optionalRoutingTable); when(brokerSession.addRpcRegistrationListener(listener)).thenReturn(null); when(brokerSession.getSupportedRpcs()).thenReturn(Collections.EMPTY_SET); when(brokerSession.rpc(null, mock(CompositeNode.class))).thenReturn(null); server.start(); Thread.sleep(5000);//wait for server to start } @After public void tearDown() throws InterruptedException { if (pool != null) pool.shutdown(); if (server != null) server.stop(); MessagingUtil.closeZmqContext(context); Thread.sleep(5000);//wait for server to stop Assert.assertEquals(ServerImpl.State.STOPPED, server.getStatus()); } @Test public void getBrokerSession_Call_ShouldReturnBrokerSession() throws Exception { Optional<Broker.ProviderSession> mayBeBroker = server.getBrokerSession(); if (mayBeBroker.isPresent()) Assert.assertEquals(brokerSession, mayBeBroker.get()); else Assert.fail("Broker does not exist in Remote RPC Server"); } @Test public void start_Call_ShouldSetServerStatusToStarted() throws Exception { Assert.assertEquals(ServerImpl.State.STARTED, server.getStatus()); } @Test public void start_Call_ShouldCreateNZmqSockets() throws Exception { final int EXPECTED_COUNT = 2 + HANDLER_COUNT; //1 ROUTER + 1 DEALER + HANDLER_COUNT Optional<ZMQ.Context> mayBeContext = server.getZmqContext(); if (mayBeContext.isPresent()) Assert.assertEquals(EXPECTED_COUNT, findSocketCount(mayBeContext.get())); else Assert.fail("ZMQ Context does not exist in Remote RPC Server"); } @Test public void start_Call_ShouldCreate1ServerThread() { final String SERVER_THREAD_NAME = "remote-rpc-server"; final int EXPECTED_COUNT = 1; List<Thread> serverThreads = findThreadsWithName(SERVER_THREAD_NAME); Assert.assertEquals(EXPECTED_COUNT, serverThreads.size()); } @Test public void start_Call_ShouldCreateNHandlerThreads() { //final String WORKER_THREAD_NAME = "remote-rpc-worker"; final int EXPECTED_COUNT = HANDLER_COUNT; Optional<ServerRequestHandler> serverRequestHandlerOptional = server.getHandler(); if (serverRequestHandlerOptional.isPresent()){ ServerRequestHandler handler = serverRequestHandlerOptional.get(); ThreadPoolExecutor workerPool = handler.getWorkerPool(); Assert.assertEquals(EXPECTED_COUNT, workerPool.getPoolSize()); } else { Assert.fail("Server is in illegal state. ServerHandler does not exist"); } } @Test public void testStop() throws Exception { } @Test public void testOnRouteUpdated() throws Exception { } @Test public void testOnRouteDeleted() throws Exception { } private int findSocketCount(ZMQ.Context context) throws NoSuchFieldException, IllegalAccessException { Field ctxField = context.getClass().getDeclaredField("ctx"); ctxField.setAccessible(true); Ctx ctx = Ctx.class.cast(ctxField.get(context)); Field socketListField = ctx.getClass().getDeclaredField("sockets"); socketListField.setAccessible(true); List<SocketBase> sockets = List.class.cast(socketListField.get(ctx)); return sockets.size(); } private List<Thread> findThreadsWithName(String name) { Thread[] threads = new Thread[Thread.activeCount()]; Thread.enumerate(threads); List<Thread> foundThreads = new ArrayList(); for (Thread t : threads) { if (t.getName().startsWith(name)) foundThreads.add(t); } return foundThreads; } }
Java
/******************************************************************************* * Copyright (c) 2010 - 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation * Lars Vogel <[email protected]> - Bug 419770 *******************************************************************************/ package com.vogella.e4.appmodel.app.handlers; import org.eclipse.e4.core.di.annotations.Execute; import org.eclipse.e4.ui.workbench.IWorkbench; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.swt.widgets.Shell; public class QuitHandler { @Execute public void execute(IWorkbench workbench, Shell shell){ if (MessageDialog.openConfirm(shell, "Confirmation", "Do you want to exit?")) { workbench.close(); } } }
Java
/* * Copyright (c) 2012-2018 Red Hat, Inc. * This program and the accompanying materials are made * available under the terms of the Eclipse Public License 2.0 * which is available at https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 * * Contributors: * Red Hat, Inc. - initial API and implementation */ package org.eclipse.che.ide.ext.git.client.compare; import org.eclipse.che.ide.api.resources.Project; import org.eclipse.che.ide.ext.git.client.compare.FileStatus.Status; /** * Describes changed in any way project files. Supports adding and removing items dynamically. * * @author Mykola Morhun */ public class MutableAlteredFiles extends AlteredFiles { /** * Parses raw git diff string and creates advanced representation. * * @param project the project under diff operation * @param diff plain result of git diff operation */ public MutableAlteredFiles(Project project, String diff) { super(project, diff); } /** * Creates mutable altered files list based on changes from another project. * * @param project the project under diff operation * @param alteredFiles changes from another project */ public MutableAlteredFiles(Project project, AlteredFiles alteredFiles) { super(project, ""); this.alteredFilesStatuses.putAll(alteredFiles.alteredFilesStatuses); this.alteredFilesList.addAll(alteredFiles.alteredFilesList); } /** * Creates an empty list of altered files. * * @param project the project under diff operation */ public MutableAlteredFiles(Project project) { super(project, ""); } /** * Adds or updates a file in altered file list. If given file is already exists does nothing. * * @param file full path to file and its name relatively to project root * @param status git status of the file * @return true if file was added or updated and false if the file is already exists in this list */ public boolean addFile(String file, Status status) { if (status.equals(alteredFilesStatuses.get(file))) { return false; } if (alteredFilesStatuses.put(file, status) == null) { // it's not a status change, new file was added alteredFilesList.add(file); } return true; } /** * Removes given file from the altered files list. If given file isn't present does nothing. * * @param file full path to file and its name relatively to project root * @return true if the file was deleted and false otherwise */ public boolean removeFile(String file) { alteredFilesStatuses.remove(file); return alteredFilesList.remove(file); } }
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_25) on Thu Sep 12 10:51:18 BST 2013 --> <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"> <title>Uses of Interface com.hp.hpl.jena.rdf.model.ModelGraphInterface (Apache Jena)</title> <meta name="date" content="2013-09-12"> <link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Interface com.hp.hpl.jena.rdf.model.ModelGraphInterface (Apache Jena)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../com/hp/hpl/jena/rdf/model/ModelGraphInterface.html" title="interface in com.hp.hpl.jena.rdf.model">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?com/hp/hpl/jena/rdf/model/class-use/ModelGraphInterface.html" target="_top">Frames</a></li> <li><a href="ModelGraphInterface.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Interface com.hp.hpl.jena.rdf.model.ModelGraphInterface" class="title">Uses of Interface<br>com.hp.hpl.jena.rdf.model.ModelGraphInterface</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../../../com/hp/hpl/jena/rdf/model/ModelGraphInterface.html" title="interface in com.hp.hpl.jena.rdf.model">ModelGraphInterface</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#com.hp.hpl.jena.ontology">com.hp.hpl.jena.ontology</a></td> <td class="colLast"> <div class="block"> Provides a set of abstractions and convenience classes for accessing and manipluating ontologies represented in RDF.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="#com.hp.hpl.jena.rdf.model">com.hp.hpl.jena.rdf.model</a></td> <td class="colLast"> <div class="block">A package for creating and manipulating RDF graphs.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><a href="#com.hp.hpl.jena.rdf.model.impl">com.hp.hpl.jena.rdf.model.impl</a></td> <td class="colLast"> <div class="block">This package contains implementations of the interfaces defined in the .model package, eg ModelCom for Model, ResourceImpl for Resource, and so on.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="#com.hp.hpl.jena.util">com.hp.hpl.jena.util</a></td> <td class="colLast"> <div class="block"> Miscellaneous collection of utility classes.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="com.hp.hpl.jena.ontology"> <!-- --> </a> <h3>Uses of <a href="../../../../../../../com/hp/hpl/jena/rdf/model/ModelGraphInterface.html" title="interface in com.hp.hpl.jena.rdf.model">ModelGraphInterface</a> in <a href="../../../../../../../com/hp/hpl/jena/ontology/package-summary.html">com.hp.hpl.jena.ontology</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing subinterfaces, and an explanation"> <caption><span>Subinterfaces of <a href="../../../../../../../com/hp/hpl/jena/rdf/model/ModelGraphInterface.html" title="interface in com.hp.hpl.jena.rdf.model">ModelGraphInterface</a> in <a href="../../../../../../../com/hp/hpl/jena/ontology/package-summary.html">com.hp.hpl.jena.ontology</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Interface and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>interface&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../../../com/hp/hpl/jena/ontology/OntModel.html" title="interface in com.hp.hpl.jena.ontology">OntModel</a></strong></code> <div class="block"> An enhanced view of a Jena model that is known to contain ontology data, under a given ontology <a href="../../../../../../../com/hp/hpl/jena/ontology/Profile.html" title="interface in com.hp.hpl.jena.ontology"><code>vocabulary</code></a> (such as OWL).</div> </td> </tr> </tbody> </table> </li> <li class="blockList"><a name="com.hp.hpl.jena.rdf.model"> <!-- --> </a> <h3>Uses of <a href="../../../../../../../com/hp/hpl/jena/rdf/model/ModelGraphInterface.html" title="interface in com.hp.hpl.jena.rdf.model">ModelGraphInterface</a> in <a href="../../../../../../../com/hp/hpl/jena/rdf/model/package-summary.html">com.hp.hpl.jena.rdf.model</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing subinterfaces, and an explanation"> <caption><span>Subinterfaces of <a href="../../../../../../../com/hp/hpl/jena/rdf/model/ModelGraphInterface.html" title="interface in com.hp.hpl.jena.rdf.model">ModelGraphInterface</a> in <a href="../../../../../../../com/hp/hpl/jena/rdf/model/package-summary.html">com.hp.hpl.jena.rdf.model</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Interface and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>interface&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../../../com/hp/hpl/jena/rdf/model/InfModel.html" title="interface in com.hp.hpl.jena.rdf.model">InfModel</a></strong></code> <div class="block">An extension to the normal Model interface that supports access to any underlying inference capability.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>interface&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../../../com/hp/hpl/jena/rdf/model/Model.html" title="interface in com.hp.hpl.jena.rdf.model">Model</a></strong></code> <div class="block">An RDF Model.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"><a name="com.hp.hpl.jena.rdf.model.impl"> <!-- --> </a> <h3>Uses of <a href="../../../../../../../com/hp/hpl/jena/rdf/model/ModelGraphInterface.html" title="interface in com.hp.hpl.jena.rdf.model">ModelGraphInterface</a> in com.hp.hpl.jena.rdf.model.impl</h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation"> <caption><span>Classes in com.hp.hpl.jena.rdf.model.impl that implement <a href="../../../../../../../com/hp/hpl/jena/rdf/model/ModelGraphInterface.html" title="interface in com.hp.hpl.jena.rdf.model">ModelGraphInterface</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong>com.hp.hpl.jena.rdf.model.impl.ModelCom</strong></code> <div class="block">Common methods for model implementations.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"><a name="com.hp.hpl.jena.util"> <!-- --> </a> <h3>Uses of <a href="../../../../../../../com/hp/hpl/jena/rdf/model/ModelGraphInterface.html" title="interface in com.hp.hpl.jena.rdf.model">ModelGraphInterface</a> in <a href="../../../../../../../com/hp/hpl/jena/util/package-summary.html">com.hp.hpl.jena.util</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation"> <caption><span>Classes in <a href="../../../../../../../com/hp/hpl/jena/util/package-summary.html">com.hp.hpl.jena.util</a> that implement <a href="../../../../../../../com/hp/hpl/jena/rdf/model/ModelGraphInterface.html" title="interface in com.hp.hpl.jena.rdf.model">ModelGraphInterface</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../../../com/hp/hpl/jena/util/MonitorModel.html" title="class in com.hp.hpl.jena.util">MonitorModel</a></strong></code> <div class="block">Model wrapper which provides normal access to an underlying model but also maintains a snapshot of the triples it was last known to contain.</div> </td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../com/hp/hpl/jena/rdf/model/ModelGraphInterface.html" title="interface in com.hp.hpl.jena.rdf.model">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?com/hp/hpl/jena/rdf/model/class-use/ModelGraphInterface.html" target="_top">Frames</a></li> <li><a href="ModelGraphInterface.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Licenced under the Apache License, Version 2.0</small></p> </body> </html>
Java
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activemq.transport.multicast; import java.net.SocketAddress; import java.nio.ByteBuffer; import org.apache.activemq.command.Command; import org.apache.activemq.command.Endpoint; import org.apache.activemq.transport.udp.DatagramEndpoint; import org.apache.activemq.transport.udp.DatagramHeaderMarshaller; /** * * */ public class MulticastDatagramHeaderMarshaller extends DatagramHeaderMarshaller { private final byte[] localUriAsBytes; public MulticastDatagramHeaderMarshaller(String localUri) { this.localUriAsBytes = localUri.getBytes(); } public Endpoint createEndpoint(ByteBuffer readBuffer, SocketAddress address) { int size = readBuffer.getInt(); byte[] data = new byte[size]; readBuffer.get(data); return new DatagramEndpoint(new String(data), address); } public void writeHeader(Command command, ByteBuffer writeBuffer) { writeBuffer.putInt(localUriAsBytes.length); writeBuffer.put(localUriAsBytes); super.writeHeader(command, writeBuffer); } }
Java
/******************************************************************************* * Copyright (c) 2010 Oak Ridge National Laboratory. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html ******************************************************************************/ package org.csstudio.trends.databrowser2.propsheet; import org.csstudio.swt.rtplot.undo.UndoableActionManager; import org.csstudio.trends.databrowser2.Activator; import org.csstudio.trends.databrowser2.Messages; import org.csstudio.trends.databrowser2.model.PVItem; import org.csstudio.trends.databrowser2.preferences.Preferences; import org.eclipse.jface.action.Action; /** Action that configures PVs to use default archive data sources. * @author Kay Kasemir */ public class UseDefaultArchivesAction extends Action { final private UndoableActionManager operations_manager; final private PVItem pvs[]; /** Initialize * @param shell Parent shell for dialog * @param pvs PVs that should use default archives */ public UseDefaultArchivesAction(final UndoableActionManager operations_manager, final PVItem pvs[]) { super(Messages.UseDefaultArchives, Activator.getDefault().getImageDescriptor("icons/archive.gif")); //$NON-NLS-1$ this.operations_manager = operations_manager; this.pvs = pvs; } @Override public void run() { new AddArchiveCommand(operations_manager, pvs, Preferences.getArchives(), true); } }
Java
/* * Debrief - the Open Source Maritime Analysis Application * http://debrief.info * * (C) 2000-2014, PlanetMayo Ltd * * This library is free software; you can redistribute it and/or * modify it under the terms of the Eclipse Public License v1.0 * (http://www.eclipse.org/legal/epl-v10.html) * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. */ package MWC.GUI.Properties.Swing; // Copyright MWC 1999, Debrief 3 Project // $RCSfile: SwingDatePropertyEditor.java,v $ // @author $Author: Ian.Mayo $ // @version $Revision: 1.3 $ // $Log: SwingDatePropertyEditor.java,v $ // Revision 1.3 2004/11/26 11:32:48 Ian.Mayo // Moving closer, supporting checking for time resolution // // Revision 1.2 2004/05/25 15:29:37 Ian.Mayo // Commit updates from home // // Revision 1.1.1.1 2004/03/04 20:31:20 ian // no message // // Revision 1.1.1.1 2003/07/17 10:07:26 Ian.Mayo // Initial import // // Revision 1.2 2002-05-28 09:25:47+01 ian_mayo // after switch to new system // // Revision 1.1 2002-05-28 09:14:33+01 ian_mayo // Initial revision // // Revision 1.1 2002-04-11 14:01:26+01 ian_mayo // Initial revision // // Revision 1.1 2001-08-31 10:36:55+01 administrator // Tidied up layout, so all data is displayed when editor panel is first opened // // Revision 1.0 2001-07-17 08:43:31+01 administrator // Initial revision // // Revision 1.4 2001-07-12 12:06:59+01 novatech // use tooltips to show the date format // // Revision 1.3 2001-01-21 21:38:23+00 novatech // handle focusGained = select all text // // Revision 1.2 2001-01-17 09:41:37+00 novatech // factor generic processing to parent class, and provide support for NULL values // // Revision 1.1 2001-01-03 13:42:39+00 novatech // Initial revision // // Revision 1.1.1.1 2000/12/12 21:45:37 ianmayo // initial version // // Revision 1.5 2000-10-09 13:35:47+01 ian_mayo // Switched stack traces to go to log file // // Revision 1.4 2000-04-03 10:48:57+01 ian_mayo // squeeze up the controls // // Revision 1.3 2000-02-02 14:25:07+00 ian_mayo // correct package naming // // Revision 1.2 1999-11-23 11:05:03+00 ian_mayo // further introduction of SWING components // // Revision 1.1 1999-11-16 16:07:19+00 ian_mayo // Initial revision // // Revision 1.1 1999-11-16 16:02:29+00 ian_mayo // Initial revision // // Revision 1.2 1999-11-11 18:16:09+00 ian_mayo // new class, now working // // Revision 1.1 1999-10-12 15:36:48+01 ian_mayo // Initial revision // // Revision 1.1 1999-08-26 10:05:48+01 administrator // Initial revision // import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusEvent; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import MWC.GUI.Dialogs.DialogFactory; import MWC.GenericData.HiResDate; import MWC.Utilities.TextFormatting.DebriefFormatDateTime; public class SwingDatePropertyEditor extends MWC.GUI.Properties.DatePropertyEditor implements java.awt.event.FocusListener { ///////////////////////////////////////////////////////////// // member variables //////////////////////////////////////////////////////////// /** * field to edit the date */ JTextField _theDate; /** * field to edit the time */ JTextField _theTime; /** * label to show the microsecodns */ JLabel _theMicrosTxt; /** * panel to hold everything */ JPanel _theHolder; ///////////////////////////////////////////////////////////// // constructor //////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// // member functions //////////////////////////////////////////////////////////// /** * build the editor */ public java.awt.Component getCustomEditor() { _theHolder = new JPanel(); final java.awt.BorderLayout bl1 = new java.awt.BorderLayout(); bl1.setVgap(0); bl1.setHgap(0); final java.awt.BorderLayout bl2 = new java.awt.BorderLayout(); bl2.setVgap(0); bl2.setHgap(0); final JPanel lPanel = new JPanel(); lPanel.setLayout(bl1); final JPanel rPanel = new JPanel(); rPanel.setLayout(bl2); _theHolder.setLayout(new java.awt.GridLayout(0, 2)); _theDate = new JTextField(); _theDate.setToolTipText("Format: " + NULL_DATE); _theTime = new JTextField(); _theTime.setToolTipText("Format: " + NULL_TIME); lPanel.add("Center", new JLabel("Date:", JLabel.RIGHT)); lPanel.add("East", _theDate); rPanel.add("Center", new JLabel("Time:", JLabel.RIGHT)); rPanel.add("East", _theTime); _theHolder.add(lPanel); _theHolder.add(rPanel); // get the fields to select the full text when they're selected _theDate.addFocusListener(this); _theTime.addFocusListener(this); // right, just see if we are in hi-res DTG editing mode if (HiResDate.inHiResProcessingMode()) { // ok, add a button to allow the user to enter DTG data final JButton editMicros = new JButton("Micros"); editMicros.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { editMicrosPressed(); } }); // ok, we' _theMicrosTxt = new JLabel(".."); _theHolder.add(_theMicrosTxt); _theHolder.add(editMicros); } resetData(); return _theHolder; } /** * user wants to edit the microseconds. give him a popup */ void editMicrosPressed() { //To change body of created methods use File | Settings | File Templates. final Integer res = DialogFactory.getInteger("Edit microseconds", "Enter microseconds",(int) _theMicros); // did user enter anything? if(res != null) { // store the data _theMicros = res.intValue(); // and update the screen resetData(); } } /** * get the date text as a string */ protected String getDateText() { return _theDate.getText(); } /** * get the date text as a string */ protected String getTimeText() { return _theTime.getText(); } /** * set the date text in string form */ protected void setDateText(final String val) { if (_theHolder != null) { _theDate.setText(val); } } /** * set the time text in string form */ protected void setTimeText(final String val) { if (_theHolder != null) { _theTime.setText(val); } } /** * show the user how many microseconds there are * * @param val */ protected void setMicroText(final long val) { // output the number of microseconds _theMicrosTxt.setText(DebriefFormatDateTime.formatMicros(new HiResDate(0, val)) + " micros"); } ///////////////////////////// // focus listener support classes ///////////////////////////// /** * Invoked when a component gains the keyboard focus. */ public void focusGained(final FocusEvent e) { final java.awt.Component c = e.getComponent(); if (c instanceof JTextField) { final JTextField jt = (JTextField) c; jt.setSelectionStart(0); jt.setSelectionEnd(jt.getText().length()); } } /** * Invoked when a component loses the keyboard focus. */ public void focusLost(final FocusEvent e) { } }
Java
/* Copyright (c) 2007 Scott Lembcke * * 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. */ /// @defgroup cpPinJoint cpPinJoint /// @{ const cpConstraintClass *cpPinJointGetClass(void); /// @private typedef struct cpPinJoint { cpConstraint constraint; cpVect anchr1, anchr2; cpFloat dist; cpVect r1, r2; cpVect n; cpFloat nMass; cpFloat jnAcc; cpFloat bias; } cpPinJoint; /// Allocate a pin joint. cpPinJoint* cpPinJointAlloc(void); /// Initialize a pin joint. cpPinJoint* cpPinJointInit(cpPinJoint *joint, cpBody *a, cpBody *b, cpVect anchr1, cpVect anchr2); /// Allocate and initialize a pin joint. cpConstraint* cpPinJointNew(cpBody *a, cpBody *b, cpVect anchr1, cpVect anchr2); CP_DefineConstraintProperty(cpPinJoint, cpVect, anchr1, Anchr1) CP_DefineConstraintProperty(cpPinJoint, cpVect, anchr2, Anchr2) CP_DefineConstraintProperty(cpPinJoint, cpFloat, dist, Dist) ///@}
Java
/* * Syscall interface to knfsd. * * Copyright (C) 1995, 1996 Olaf Kirch <[email protected]> */ #include <linux/slab.h> #include <linux/namei.h> #include <linux/ctype.h> #include <linux/sunrpc/svcsock.h> #include <linux/lockd/lockd.h> #include <linux/sunrpc/addr.h> #include <linux/sunrpc/gss_api.h> #include <linux/sunrpc/gss_krb5_enctypes.h> #include <linux/sunrpc/rpc_pipe_fs.h> #include <linux/module.h> #include "idmap.h" #include "nfsd.h" #include "cache.h" #include "state.h" #include "netns.h" /* * We have a single directory with several nodes in it. */ enum { NFSD_Root = 1, NFSD_List, NFSD_Export_features, NFSD_Fh, NFSD_FO_UnlockIP, NFSD_FO_UnlockFS, NFSD_Threads, NFSD_Pool_Threads, NFSD_Pool_Stats, NFSD_Reply_Cache_Stats, NFSD_Versions, NFSD_Ports, NFSD_MaxBlkSize, NFSD_SupportedEnctypes, /* * The below MUST come last. Otherwise we leave a hole in nfsd_files[] * with !CONFIG_NFSD_V4 and simple_fill_super() goes oops */ #ifdef CONFIG_NFSD_V4 NFSD_Leasetime, NFSD_Gracetime, NFSD_RecoveryDir, #endif }; /* * write() for these nodes. */ static ssize_t write_filehandle(struct file *file, char *buf, size_t size); static ssize_t write_unlock_ip(struct file *file, char *buf, size_t size); static ssize_t write_unlock_fs(struct file *file, char *buf, size_t size); static ssize_t write_threads(struct file *file, char *buf, size_t size); static ssize_t write_pool_threads(struct file *file, char *buf, size_t size); static ssize_t write_versions(struct file *file, char *buf, size_t size); static ssize_t write_ports(struct file *file, char *buf, size_t size); static ssize_t write_maxblksize(struct file *file, char *buf, size_t size); #ifdef CONFIG_NFSD_V4 static ssize_t write_leasetime(struct file *file, char *buf, size_t size); static ssize_t write_gracetime(struct file *file, char *buf, size_t size); static ssize_t write_recoverydir(struct file *file, char *buf, size_t size); #endif static ssize_t (*write_op[])(struct file *, char *, size_t) = { [NFSD_Fh] = write_filehandle, [NFSD_FO_UnlockIP] = write_unlock_ip, [NFSD_FO_UnlockFS] = write_unlock_fs, [NFSD_Threads] = write_threads, [NFSD_Pool_Threads] = write_pool_threads, [NFSD_Versions] = write_versions, [NFSD_Ports] = write_ports, [NFSD_MaxBlkSize] = write_maxblksize, #ifdef CONFIG_NFSD_V4 [NFSD_Leasetime] = write_leasetime, [NFSD_Gracetime] = write_gracetime, [NFSD_RecoveryDir] = write_recoverydir, #endif }; static ssize_t nfsctl_transaction_write(struct file *file, const char __user *buf, size_t size, loff_t *pos) { ino_t ino = file_inode(file)->i_ino; char *data; ssize_t rv; if (ino >= ARRAY_SIZE(write_op) || !write_op[ino]) return -EINVAL; data = simple_transaction_get(file, buf, size); if (IS_ERR(data)) return PTR_ERR(data); rv = write_op[ino](file, data, size); if (rv >= 0) { simple_transaction_set(file, rv); rv = size; } return rv; } static ssize_t nfsctl_transaction_read(struct file *file, char __user *buf, size_t size, loff_t *pos) { if (! file->private_data) { /* An attempt to read a transaction file without writing * causes a 0-byte write so that the file can return * state information */ ssize_t rv = nfsctl_transaction_write(file, buf, 0, pos); if (rv < 0) return rv; } return simple_transaction_read(file, buf, size, pos); } static const struct file_operations transaction_ops = { .write = nfsctl_transaction_write, .read = nfsctl_transaction_read, .release = simple_transaction_release, .llseek = default_llseek, }; static int exports_net_open(struct net *net, struct file *file) { int err; struct seq_file *seq; struct nfsd_net *nn = net_generic(net, nfsd_net_id); err = seq_open(file, &nfs_exports_op); if (err) return err; seq = file->private_data; seq->private = nn->svc_export_cache; return 0; } static int exports_proc_open(struct inode *inode, struct file *file) { return exports_net_open(current->nsproxy->net_ns, file); } static const struct file_operations exports_proc_operations = { .open = exports_proc_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release, .owner = THIS_MODULE, }; static int exports_nfsd_open(struct inode *inode, struct file *file) { return exports_net_open(inode->i_sb->s_fs_info, file); } static const struct file_operations exports_nfsd_operations = { .open = exports_nfsd_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release, .owner = THIS_MODULE, }; static int export_features_show(struct seq_file *m, void *v) { seq_printf(m, "0x%x 0x%x\n", NFSEXP_ALLFLAGS, NFSEXP_SECINFO_FLAGS); return 0; } static int export_features_open(struct inode *inode, struct file *file) { return single_open(file, export_features_show, NULL); } static const struct file_operations export_features_operations = { .open = export_features_open, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; #if defined(CONFIG_SUNRPC_GSS) || defined(CONFIG_SUNRPC_GSS_MODULE) static int supported_enctypes_show(struct seq_file *m, void *v) { seq_printf(m, KRB5_SUPPORTED_ENCTYPES); return 0; } static int supported_enctypes_open(struct inode *inode, struct file *file) { return single_open(file, supported_enctypes_show, NULL); } static const struct file_operations supported_enctypes_ops = { .open = supported_enctypes_open, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; #endif /* CONFIG_SUNRPC_GSS or CONFIG_SUNRPC_GSS_MODULE */ static const struct file_operations pool_stats_operations = { .open = nfsd_pool_stats_open, .read = seq_read, .llseek = seq_lseek, .release = nfsd_pool_stats_release, .owner = THIS_MODULE, }; static struct file_operations reply_cache_stats_operations = { .open = nfsd_reply_cache_stats_open, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; /*----------------------------------------------------------------------------*/ /* * payload - write methods */ /** * write_unlock_ip - Release all locks used by a client * * Experimental. * * Input: * buf: '\n'-terminated C string containing a * presentation format IP address * size: length of C string in @buf * Output: * On success: returns zero if all specified locks were released; * returns one if one or more locks were not released * On error: return code is negative errno value */ static ssize_t write_unlock_ip(struct file *file, char *buf, size_t size) { struct sockaddr_storage address; struct sockaddr *sap = (struct sockaddr *)&address; size_t salen = sizeof(address); char *fo_path; struct net *net = file->f_dentry->d_sb->s_fs_info; /* sanity check */ if (size == 0) return -EINVAL; if (buf[size-1] != '\n') return -EINVAL; fo_path = buf; if (qword_get(&buf, fo_path, size) < 0) return -EINVAL; if (rpc_pton(net, fo_path, size, sap, salen) == 0) return -EINVAL; return nlmsvc_unlock_all_by_ip(sap); } /** * write_unlock_fs - Release all locks on a local file system * * Experimental. * * Input: * buf: '\n'-terminated C string containing the * absolute pathname of a local file system * size: length of C string in @buf * Output: * On success: returns zero if all specified locks were released; * returns one if one or more locks were not released * On error: return code is negative errno value */ static ssize_t write_unlock_fs(struct file *file, char *buf, size_t size) { struct path path; char *fo_path; int error; /* sanity check */ if (size == 0) return -EINVAL; if (buf[size-1] != '\n') return -EINVAL; fo_path = buf; if (qword_get(&buf, fo_path, size) < 0) return -EINVAL; error = kern_path(fo_path, 0, &path); if (error) return error; /* * XXX: Needs better sanity checking. Otherwise we could end up * releasing locks on the wrong file system. * * For example: * 1. Does the path refer to a directory? * 2. Is that directory a mount point, or * 3. Is that directory the root of an exported file system? */ error = nlmsvc_unlock_all_by_sb(path.dentry->d_sb); path_put(&path); return error; } /** * write_filehandle - Get a variable-length NFS file handle by path * * On input, the buffer contains a '\n'-terminated C string comprised of * three alphanumeric words separated by whitespace. The string may * contain escape sequences. * * Input: * buf: * domain: client domain name * path: export pathname * maxsize: numeric maximum size of * @buf * size: length of C string in @buf * Output: * On success: passed-in buffer filled with '\n'-terminated C * string containing a ASCII hex text version * of the NFS file handle; * return code is the size in bytes of the string * On error: return code is negative errno value */ static ssize_t write_filehandle(struct file *file, char *buf, size_t size) { char *dname, *path; int uninitialized_var(maxsize); char *mesg = buf; int len; struct auth_domain *dom; struct knfsd_fh fh; struct net *net = file->f_dentry->d_sb->s_fs_info; if (size == 0) return -EINVAL; if (buf[size-1] != '\n') return -EINVAL; buf[size-1] = 0; dname = mesg; len = qword_get(&mesg, dname, size); if (len <= 0) return -EINVAL; path = dname+len+1; len = qword_get(&mesg, path, size); if (len <= 0) return -EINVAL; len = get_int(&mesg, &maxsize); if (len) return len; if (maxsize < NFS_FHSIZE) return -EINVAL; if (maxsize > NFS3_FHSIZE) maxsize = NFS3_FHSIZE; if (qword_get(&mesg, mesg, size)>0) return -EINVAL; /* we have all the words, they are in buf.. */ dom = unix_domain_find(dname); if (!dom) return -ENOMEM; len = exp_rootfh(net, dom, path, &fh, maxsize); auth_domain_put(dom); if (len) return len; mesg = buf; len = SIMPLE_TRANSACTION_LIMIT; qword_addhex(&mesg, &len, (char*)&fh.fh_base, fh.fh_size); mesg[-1] = '\n'; return mesg - buf; } /** * write_threads - Start NFSD, or report the current number of running threads * * Input: * buf: ignored * size: zero * Output: * On success: passed-in buffer filled with '\n'-terminated C * string numeric value representing the number of * running NFSD threads; * return code is the size in bytes of the string * On error: return code is zero * * OR * * Input: * buf: C string containing an unsigned * integer value representing the * number of NFSD threads to start * size: non-zero length of C string in @buf * Output: * On success: NFS service is started; * passed-in buffer filled with '\n'-terminated C * string numeric value representing the number of * running NFSD threads; * return code is the size in bytes of the string * On error: return code is zero or a negative errno value */ static ssize_t write_threads(struct file *file, char *buf, size_t size) { char *mesg = buf; int rv; struct net *net = file->f_dentry->d_sb->s_fs_info; if (size > 0) { int newthreads; rv = get_int(&mesg, &newthreads); if (rv) return rv; if (newthreads < 0) return -EINVAL; rv = nfsd_svc(newthreads, net); if (rv < 0) return rv; } else rv = nfsd_nrthreads(net); return scnprintf(buf, SIMPLE_TRANSACTION_LIMIT, "%d\n", rv); } /** * write_pool_threads - Set or report the current number of threads per pool * * Input: * buf: ignored * size: zero * * OR * * Input: * buf: C string containing whitespace- * separated unsigned integer values * representing the number of NFSD * threads to start in each pool * size: non-zero length of C string in @buf * Output: * On success: passed-in buffer filled with '\n'-terminated C * string containing integer values representing the * number of NFSD threads in each pool; * return code is the size in bytes of the string * On error: return code is zero or a negative errno value */ static ssize_t write_pool_threads(struct file *file, char *buf, size_t size) { /* if size > 0, look for an array of number of threads per node * and apply them then write out number of threads per node as reply */ char *mesg = buf; int i; int rv; int len; int npools; int *nthreads; struct net *net = file->f_dentry->d_sb->s_fs_info; mutex_lock(&nfsd_mutex); npools = nfsd_nrpools(net); if (npools == 0) { /* * NFS is shut down. The admin can start it by * writing to the threads file but NOT the pool_threads * file, sorry. Report zero threads. */ mutex_unlock(&nfsd_mutex); strcpy(buf, "0\n"); return strlen(buf); } nthreads = kcalloc(npools, sizeof(int), GFP_KERNEL); rv = -ENOMEM; if (nthreads == NULL) goto out_free; if (size > 0) { for (i = 0; i < npools; i++) { rv = get_int(&mesg, &nthreads[i]); if (rv == -ENOENT) break; /* fewer numbers than pools */ if (rv) goto out_free; /* syntax error */ rv = -EINVAL; if (nthreads[i] < 0) goto out_free; } rv = nfsd_set_nrthreads(i, nthreads, net); if (rv) goto out_free; } rv = nfsd_get_nrthreads(npools, nthreads, net); if (rv) goto out_free; mesg = buf; size = SIMPLE_TRANSACTION_LIMIT; for (i = 0; i < npools && size > 0; i++) { snprintf(mesg, size, "%d%c", nthreads[i], (i == npools-1 ? '\n' : ' ')); len = strlen(mesg); size -= len; mesg += len; } rv = mesg - buf; out_free: kfree(nthreads); mutex_unlock(&nfsd_mutex); return rv; } static ssize_t __write_versions(struct file *file, char *buf, size_t size) { char *mesg = buf; char *vers, *minorp, sign; int len, num, remaining; unsigned minor; ssize_t tlen = 0; char *sep; struct net *net = file->f_dentry->d_sb->s_fs_info; struct nfsd_net *nn = net_generic(net, nfsd_net_id); if (size>0) { if (nn->nfsd_serv) /* Cannot change versions without updating * nn->nfsd_serv->sv_xdrsize, and reallocing * rq_argp and rq_resp */ return -EBUSY; if (buf[size-1] != '\n') return -EINVAL; buf[size-1] = 0; vers = mesg; len = qword_get(&mesg, vers, size); if (len <= 0) return -EINVAL; do { sign = *vers; if (sign == '+' || sign == '-') num = simple_strtol((vers+1), &minorp, 0); else num = simple_strtol(vers, &minorp, 0); if (*minorp == '.') { if (num != 4) return -EINVAL; minor = simple_strtoul(minorp+1, NULL, 0); if (minor == 0) return -EINVAL; if (nfsd_minorversion(minor, sign == '-' ? NFSD_CLEAR : NFSD_SET) < 0) return -EINVAL; goto next; } switch(num) { case 2: case 3: case 4: nfsd_vers(num, sign == '-' ? NFSD_CLEAR : NFSD_SET); break; default: return -EINVAL; } next: vers += len + 1; } while ((len = qword_get(&mesg, vers, size)) > 0); /* If all get turned off, turn them back on, as * having no versions is BAD */ nfsd_reset_versions(); } /* Now write current state into reply buffer */ len = 0; sep = ""; remaining = SIMPLE_TRANSACTION_LIMIT; for (num=2 ; num <= 4 ; num++) if (nfsd_vers(num, NFSD_AVAIL)) { len = snprintf(buf, remaining, "%s%c%d", sep, nfsd_vers(num, NFSD_TEST)?'+':'-', num); sep = " "; if (len > remaining) break; remaining -= len; buf += len; tlen += len; } if (nfsd_vers(4, NFSD_AVAIL)) for (minor = 1; minor <= NFSD_SUPPORTED_MINOR_VERSION; minor++) { len = snprintf(buf, remaining, " %c4.%u", (nfsd_vers(4, NFSD_TEST) && nfsd_minorversion(minor, NFSD_TEST)) ? '+' : '-', minor); if (len > remaining) break; remaining -= len; buf += len; tlen += len; } len = snprintf(buf, remaining, "\n"); if (len > remaining) return -EINVAL; return tlen + len; } /** * write_versions - Set or report the available NFS protocol versions * * Input: * buf: ignored * size: zero * Output: * On success: passed-in buffer filled with '\n'-terminated C * string containing positive or negative integer * values representing the current status of each * protocol version; * return code is the size in bytes of the string * On error: return code is zero or a negative errno value * * OR * * Input: * buf: C string containing whitespace- * separated positive or negative * integer values representing NFS * protocol versions to enable ("+n") * or disable ("-n") * size: non-zero length of C string in @buf * Output: * On success: status of zero or more protocol versions has * been updated; passed-in buffer filled with * '\n'-terminated C string containing positive * or negative integer values representing the * current status of each protocol version; * return code is the size in bytes of the string * On error: return code is zero or a negative errno value */ static ssize_t write_versions(struct file *file, char *buf, size_t size) { ssize_t rv; mutex_lock(&nfsd_mutex); rv = __write_versions(file, buf, size); mutex_unlock(&nfsd_mutex); return rv; } /* * Zero-length write. Return a list of NFSD's current listener * transports. */ static ssize_t __write_ports_names(char *buf, struct net *net) { struct nfsd_net *nn = net_generic(net, nfsd_net_id); if (nn->nfsd_serv == NULL) return 0; return svc_xprt_names(nn->nfsd_serv, buf, SIMPLE_TRANSACTION_LIMIT); } /* * A single 'fd' number was written, in which case it must be for * a socket of a supported family/protocol, and we use it as an * nfsd listener. */ static ssize_t __write_ports_addfd(char *buf, struct net *net) { char *mesg = buf; int fd, err; struct nfsd_net *nn = net_generic(net, nfsd_net_id); err = get_int(&mesg, &fd); if (err != 0 || fd < 0) return -EINVAL; err = nfsd_create_serv(net); if (err != 0) return err; err = svc_addsock(nn->nfsd_serv, fd, buf, SIMPLE_TRANSACTION_LIMIT); if (err < 0) { nfsd_destroy(net); return err; } /* Decrease the count, but don't shut down the service */ nn->nfsd_serv->sv_nrthreads--; return err; } /* * A transport listener is added by writing it's transport name and * a port number. */ static ssize_t __write_ports_addxprt(char *buf, struct net *net) { char transport[16]; struct svc_xprt *xprt; int port, err; struct nfsd_net *nn = net_generic(net, nfsd_net_id); if (sscanf(buf, "%15s %5u", transport, &port) != 2) return -EINVAL; if (port < 1 || port > USHRT_MAX) return -EINVAL; err = nfsd_create_serv(net); if (err != 0) return err; err = svc_create_xprt(nn->nfsd_serv, transport, net, PF_INET, port, SVC_SOCK_ANONYMOUS); if (err < 0) goto out_err; err = svc_create_xprt(nn->nfsd_serv, transport, net, PF_INET6, port, SVC_SOCK_ANONYMOUS); if (err < 0 && err != -EAFNOSUPPORT) goto out_close; /* Decrease the count, but don't shut down the service */ nn->nfsd_serv->sv_nrthreads--; return 0; out_close: xprt = svc_find_xprt(nn->nfsd_serv, transport, net, PF_INET, port); if (xprt != NULL) { svc_close_xprt(xprt); svc_xprt_put(xprt); } out_err: nfsd_destroy(net); return err; } static ssize_t __write_ports(struct file *file, char *buf, size_t size, struct net *net) { if (size == 0) return __write_ports_names(buf, net); if (isdigit(buf[0])) return __write_ports_addfd(buf, net); if (isalpha(buf[0])) return __write_ports_addxprt(buf, net); return -EINVAL; } /** * write_ports - Pass a socket file descriptor or transport name to listen on * * Input: * buf: ignored * size: zero * Output: * On success: passed-in buffer filled with a '\n'-terminated C * string containing a whitespace-separated list of * named NFSD listeners; * return code is the size in bytes of the string * On error: return code is zero or a negative errno value * * OR * * Input: * buf: C string containing an unsigned * integer value representing a bound * but unconnected socket that is to be * used as an NFSD listener; listen(3) * must be called for a SOCK_STREAM * socket, otherwise it is ignored * size: non-zero length of C string in @buf * Output: * On success: NFS service is started; * passed-in buffer filled with a '\n'-terminated C * string containing a unique alphanumeric name of * the listener; * return code is the size in bytes of the string * On error: return code is a negative errno value * * OR * * Input: * buf: C string containing a transport * name and an unsigned integer value * representing the port to listen on, * separated by whitespace * size: non-zero length of C string in @buf * Output: * On success: returns zero; NFS service is started * On error: return code is a negative errno value */ static ssize_t write_ports(struct file *file, char *buf, size_t size) { ssize_t rv; struct net *net = file->f_dentry->d_sb->s_fs_info; mutex_lock(&nfsd_mutex); rv = __write_ports(file, buf, size, net); mutex_unlock(&nfsd_mutex); return rv; } int nfsd_max_blksize; /** * write_maxblksize - Set or report the current NFS blksize * * Input: * buf: ignored * size: zero * * OR * * Input: * buf: C string containing an unsigned * integer value representing the new * NFS blksize * size: non-zero length of C string in @buf * Output: * On success: passed-in buffer filled with '\n'-terminated C string * containing numeric value of the current NFS blksize * setting; * return code is the size in bytes of the string * On error: return code is zero or a negative errno value */ static ssize_t write_maxblksize(struct file *file, char *buf, size_t size) { char *mesg = buf; struct net *net = file->f_dentry->d_sb->s_fs_info; struct nfsd_net *nn = net_generic(net, nfsd_net_id); if (size > 0) { int bsize; int rv = get_int(&mesg, &bsize); if (rv) return rv; /* force bsize into allowed range and * required alignment. */ if (bsize < 1024) bsize = 1024; if (bsize > NFSSVC_MAXBLKSIZE) bsize = NFSSVC_MAXBLKSIZE; bsize &= ~(1024-1); mutex_lock(&nfsd_mutex); if (nn->nfsd_serv) { mutex_unlock(&nfsd_mutex); return -EBUSY; } nfsd_max_blksize = bsize; mutex_unlock(&nfsd_mutex); } return scnprintf(buf, SIMPLE_TRANSACTION_LIMIT, "%d\n", nfsd_max_blksize); } #ifdef CONFIG_NFSD_V4 static ssize_t __nfsd4_write_time(struct file *file, char *buf, size_t size, time_t *time, struct nfsd_net *nn) { char *mesg = buf; int rv, i; if (size > 0) { if (nn->nfsd_serv) return -EBUSY; rv = get_int(&mesg, &i); if (rv) return rv; /* * Some sanity checking. We don't have a reason for * these particular numbers, but problems with the * extremes are: * - Too short: the briefest network outage may * cause clients to lose all their locks. Also, * the frequent polling may be wasteful. * - Too long: do you really want reboot recovery * to take more than an hour? Or to make other * clients wait an hour before being able to * revoke a dead client's locks? */ if (i < 10 || i > 3600) return -EINVAL; *time = i; } return scnprintf(buf, SIMPLE_TRANSACTION_LIMIT, "%ld\n", *time); } static ssize_t nfsd4_write_time(struct file *file, char *buf, size_t size, time_t *time, struct nfsd_net *nn) { ssize_t rv; mutex_lock(&nfsd_mutex); rv = __nfsd4_write_time(file, buf, size, time, nn); mutex_unlock(&nfsd_mutex); return rv; } /** * write_leasetime - Set or report the current NFSv4 lease time * * Input: * buf: ignored * size: zero * * OR * * Input: * buf: C string containing an unsigned * integer value representing the new * NFSv4 lease expiry time * size: non-zero length of C string in @buf * Output: * On success: passed-in buffer filled with '\n'-terminated C * string containing unsigned integer value of the * current lease expiry time; * return code is the size in bytes of the string * On error: return code is zero or a negative errno value */ static ssize_t write_leasetime(struct file *file, char *buf, size_t size) { struct net *net = file->f_dentry->d_sb->s_fs_info; struct nfsd_net *nn = net_generic(net, nfsd_net_id); return nfsd4_write_time(file, buf, size, &nn->nfsd4_lease, nn); } /** * write_gracetime - Set or report current NFSv4 grace period time * * As above, but sets the time of the NFSv4 grace period. * * Note this should never be set to less than the *previous* * lease-period time, but we don't try to enforce this. (In the common * case (a new boot), we don't know what the previous lease time was * anyway.) */ static ssize_t write_gracetime(struct file *file, char *buf, size_t size) { struct net *net = file->f_dentry->d_sb->s_fs_info; struct nfsd_net *nn = net_generic(net, nfsd_net_id); return nfsd4_write_time(file, buf, size, &nn->nfsd4_grace, nn); } static ssize_t __write_recoverydir(struct file *file, char *buf, size_t size, struct nfsd_net *nn) { char *mesg = buf; char *recdir; int len, status; if (size > 0) { if (nn->nfsd_serv) return -EBUSY; if (size > PATH_MAX || buf[size-1] != '\n') return -EINVAL; buf[size-1] = 0; recdir = mesg; len = qword_get(&mesg, recdir, size); if (len <= 0) return -EINVAL; status = nfs4_reset_recoverydir(recdir); if (status) return status; } return scnprintf(buf, SIMPLE_TRANSACTION_LIMIT, "%s\n", nfs4_recoverydir()); } /** * write_recoverydir - Set or report the pathname of the recovery directory * * Input: * buf: ignored * size: zero * * OR * * Input: * buf: C string containing the pathname * of the directory on a local file * system containing permanent NFSv4 * recovery data * size: non-zero length of C string in @buf * Output: * On success: passed-in buffer filled with '\n'-terminated C string * containing the current recovery pathname setting; * return code is the size in bytes of the string * On error: return code is zero or a negative errno value */ static ssize_t write_recoverydir(struct file *file, char *buf, size_t size) { ssize_t rv; struct net *net = file->f_dentry->d_sb->s_fs_info; struct nfsd_net *nn = net_generic(net, nfsd_net_id); mutex_lock(&nfsd_mutex); rv = __write_recoverydir(file, buf, size, nn); mutex_unlock(&nfsd_mutex); return rv; } #endif /*----------------------------------------------------------------------------*/ /* * populating the filesystem. */ static int nfsd_fill_super(struct super_block * sb, void * data, int silent) { static struct tree_descr nfsd_files[] = { [NFSD_List] = {"exports", &exports_nfsd_operations, S_IRUGO}, [NFSD_Export_features] = {"export_features", &export_features_operations, S_IRUGO}, [NFSD_FO_UnlockIP] = {"unlock_ip", &transaction_ops, S_IWUSR|S_IRUSR}, [NFSD_FO_UnlockFS] = {"unlock_filesystem", &transaction_ops, S_IWUSR|S_IRUSR}, [NFSD_Fh] = {"filehandle", &transaction_ops, S_IWUSR|S_IRUSR}, [NFSD_Threads] = {"threads", &transaction_ops, S_IWUSR|S_IRUSR}, [NFSD_Pool_Threads] = {"pool_threads", &transaction_ops, S_IWUSR|S_IRUSR}, [NFSD_Pool_Stats] = {"pool_stats", &pool_stats_operations, S_IRUGO}, [NFSD_Reply_Cache_Stats] = {"reply_cache_stats", &reply_cache_stats_operations, S_IRUGO}, [NFSD_Versions] = {"versions", &transaction_ops, S_IWUSR|S_IRUSR}, [NFSD_Ports] = {"portlist", &transaction_ops, S_IWUSR|S_IRUGO}, [NFSD_MaxBlkSize] = {"max_block_size", &transaction_ops, S_IWUSR|S_IRUGO}, #if defined(CONFIG_SUNRPC_GSS) || defined(CONFIG_SUNRPC_GSS_MODULE) [NFSD_SupportedEnctypes] = {"supported_krb5_enctypes", &supported_enctypes_ops, S_IRUGO}, #endif /* CONFIG_SUNRPC_GSS or CONFIG_SUNRPC_GSS_MODULE */ #ifdef CONFIG_NFSD_V4 [NFSD_Leasetime] = {"nfsv4leasetime", &transaction_ops, S_IWUSR|S_IRUSR}, [NFSD_Gracetime] = {"nfsv4gracetime", &transaction_ops, S_IWUSR|S_IRUSR}, [NFSD_RecoveryDir] = {"nfsv4recoverydir", &transaction_ops, S_IWUSR|S_IRUSR}, #endif /* last one */ {""} }; struct net *net = sb->s_ns; int ret; ret = simple_fill_super(sb, 0x6e667364, nfsd_files); if (ret) return ret; sb->s_fs_info = get_net(net); return 0; } static struct dentry *nfsd_mount(struct file_system_type *fs_type, int flags, const char *dev_name, void *data) { return mount_ns(fs_type, flags, NULL, current->nsproxy->net_ns, nfsd_fill_super); } static void nfsd_umount(struct super_block *sb) { struct net *net = sb->s_fs_info; kill_litter_super(sb); put_net(net); } static struct file_system_type nfsd_fs_type = { .owner = THIS_MODULE, .name = "nfsd", .mount = nfsd_mount, .kill_sb = nfsd_umount, .fs_flags = FS_VIRTUALIZED, }; MODULE_ALIAS_FS("nfsd"); #ifdef CONFIG_PROC_FS static int create_proc_exports_entry(void) { struct proc_dir_entry *entry; entry = proc_mkdir("fs/nfs", NULL); if (!entry) return -ENOMEM; entry = proc_create("exports", 0, entry, &exports_proc_operations); if (!entry) { remove_proc_entry("fs/nfs", NULL); return -ENOMEM; } return 0; } #else /* CONFIG_PROC_FS */ static int create_proc_exports_entry(void) { return 0; } #endif int nfsd_net_id; static __net_init int nfsd_init_net(struct net *net) { int retval; struct nfsd_net *nn = net_generic(net, nfsd_net_id); retval = nfsd_export_init(net); if (retval) goto out_export_error; retval = nfsd_idmap_init(net); if (retval) goto out_idmap_error; nn->nfsd4_lease = 90; /* default lease time */ nn->nfsd4_grace = 90; return 0; out_idmap_error: nfsd_export_shutdown(net); out_export_error: return retval; } static __net_exit void nfsd_exit_net(struct net *net) { nfsd_idmap_shutdown(net); nfsd_export_shutdown(net); } static struct pernet_operations nfsd_net_ops = { .init = nfsd_init_net, .exit = nfsd_exit_net, .id = &nfsd_net_id, .size = sizeof(struct nfsd_net), }; static int __init init_nfsd(void) { int retval; printk(KERN_INFO "Installing knfsd (copyright (C) 1996 [email protected]).\n"); retval = register_cld_notifier(); if (retval) return retval; retval = register_pernet_subsys(&nfsd_net_ops); if (retval < 0) goto out_unregister_notifier; retval = nfsd4_init_slabs(); if (retval) goto out_unregister_pernet; nfs4_state_init(); retval = nfsd_fault_inject_init(); /* nfsd fault injection controls */ if (retval) goto out_free_slabs; nfsd_stat_init(); /* Statistics */ retval = nfsd_reply_cache_init(); if (retval) goto out_free_stat; nfsd_lockd_init(); /* lockd->nfsd callbacks */ retval = create_proc_exports_entry(); if (retval) goto out_free_lockd; retval = register_filesystem(&nfsd_fs_type); if (retval) goto out_free_all; return 0; out_free_all: remove_proc_entry("fs/nfs/exports", NULL); remove_proc_entry("fs/nfs", NULL); out_free_lockd: nfsd_lockd_shutdown(); nfsd_reply_cache_shutdown(); out_free_stat: nfsd_stat_shutdown(); nfsd_fault_inject_cleanup(); out_free_slabs: nfsd4_free_slabs(); out_unregister_pernet: unregister_pernet_subsys(&nfsd_net_ops); out_unregister_notifier: unregister_cld_notifier(); return retval; } static void __exit exit_nfsd(void) { nfsd_reply_cache_shutdown(); remove_proc_entry("fs/nfs/exports", NULL); remove_proc_entry("fs/nfs", NULL); nfsd_stat_shutdown(); nfsd_lockd_shutdown(); nfsd4_free_slabs(); nfsd_fault_inject_cleanup(); unregister_filesystem(&nfsd_fs_type); unregister_pernet_subsys(&nfsd_net_ops); unregister_cld_notifier(); } MODULE_AUTHOR("Olaf Kirch <[email protected]>"); MODULE_LICENSE("GPL"); module_init(init_nfsd) module_exit(exit_nfsd)
Java
/* Copyright_License { XCSoar Glide Computer - http://www.xcsoar.org/ Copyright (C) 2000-2012 The XCSoar Project A detailed list of copyright holders can be found in the file "AUTHORS". 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 "Polar/Polar.hpp" #include "Engine/GlideSolvers/PolarCoefficients.hpp" #include "Units/System.hpp" #include <stdlib.h> #include <cstdio> PolarCoefficients PolarInfo::CalculateCoefficients() const { return PolarCoefficients::From3VW(v1, v2, v3, w1, w2, w3); } bool PolarInfo::IsValid() const { return CalculateCoefficients().IsValid(); } void PolarInfo::GetString(TCHAR* line, size_t size, bool include_v_no) const { fixed V1, V2, V3; V1 = Units::ToUserUnit(v1, Unit::KILOMETER_PER_HOUR); V2 = Units::ToUserUnit(v2, Unit::KILOMETER_PER_HOUR); V3 = Units::ToUserUnit(v3, Unit::KILOMETER_PER_HOUR); if (include_v_no) _sntprintf(line, size, _T("%.0f,%.0f,%.3f,%.3f,%.3f,%.3f,%.3f,%.3f,%.3f,%.3f"), (double)reference_mass, (double)max_ballast, (double)V1, (double)w1, (double)V2, (double)w2, (double)V3, (double)w3, (double)wing_area, (double)v_no); else _sntprintf(line, size, _T("%.0f,%.0f,%.3f,%.3f,%.3f,%.3f,%.3f,%.3f,%.3f"), (double)reference_mass, (double)max_ballast, (double)V1, (double)w1, (double)V2, (double)w2, (double)V3, (double)w3, (double)wing_area); } bool PolarInfo::ReadString(const TCHAR *line) { PolarInfo polar; // Example: // *LS-3 WinPilot POLAR file: MassDryGross[kg], MaxWaterBallast[liters], Speed1[km/h], Sink1[m/s], Speed2, Sink2, Speed3, Sink3 // 403, 101, 115.03, -0.86, 174.04, -1.76, 212.72, -3.4 if (line[0] == _T('*')) /* a comment */ return false; TCHAR *p; polar.reference_mass = fixed(_tcstod(line, &p)); if (*p != _T(',')) return false; polar.max_ballast = fixed(_tcstod(p + 1, &p)); if (*p != _T(',')) return false; polar.v1 = Units::ToSysUnit(fixed(_tcstod(p + 1, &p)), Unit::KILOMETER_PER_HOUR); if (*p != _T(',')) return false; polar.w1 = fixed(_tcstod(p + 1, &p)); if (*p != _T(',')) return false; polar.v2 = Units::ToSysUnit(fixed(_tcstod(p + 1, &p)), Unit::KILOMETER_PER_HOUR); if (*p != _T(',')) return false; polar.w2 = fixed(_tcstod(p + 1, &p)); if (*p != _T(',')) return false; polar.v3 = Units::ToSysUnit(fixed(_tcstod(p + 1, &p)), Unit::KILOMETER_PER_HOUR); if (*p != _T(',')) return false; polar.w3 = fixed(_tcstod(p + 1, &p)); polar.wing_area = (*p != _T(',')) ? fixed_zero : fixed(_tcstod(p + 1, &p)); polar.v_no = (*p != _T(',')) ? fixed_zero : fixed(_tcstod(p + 1, &p)); *this = polar; return true; }
Java
package io.mycat.backend.postgresql; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.nio.channels.NetworkChannel; import java.nio.channels.SocketChannel; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import io.mycat.backend.jdbc.ShowVariables; import io.mycat.backend.mysql.CharsetUtil; import io.mycat.backend.mysql.nio.MySQLConnectionHandler; import io.mycat.backend.mysql.nio.handler.ResponseHandler; import io.mycat.backend.postgresql.packet.Query; import io.mycat.backend.postgresql.packet.Terminate; import io.mycat.backend.postgresql.utils.PIOUtils; import io.mycat.backend.postgresql.utils.PacketUtils; import io.mycat.backend.postgresql.utils.PgSqlApaterUtils; import io.mycat.config.Isolations; import io.mycat.net.BackendAIOConnection; import io.mycat.route.RouteResultsetNode; import io.mycat.server.ServerConnection; import io.mycat.server.parser.ServerParse; import io.mycat.util.exception.UnknownTxIsolationException; /************************************************************* * PostgreSQL Native Connection impl * * @author Coollf * */ public class PostgreSQLBackendConnection extends BackendAIOConnection { public static enum BackendConnectionState { closed, connected, connecting } private static class StatusSync { private final Boolean autocommit; private final Integer charsetIndex; private final String schema; private final AtomicInteger synCmdCount; private final Integer txtIsolation; private final boolean xaStarted; public StatusSync(boolean xaStarted, String schema, Integer charsetIndex, Integer txtIsolation, Boolean autocommit, int synCount) { super(); this.xaStarted = xaStarted; this.schema = schema; this.charsetIndex = charsetIndex; this.txtIsolation = txtIsolation; this.autocommit = autocommit; this.synCmdCount = new AtomicInteger(synCount); } public boolean synAndExecuted(PostgreSQLBackendConnection conn) { int remains = synCmdCount.decrementAndGet(); if (remains == 0) {// syn command finished this.updateConnectionInfo(conn); conn.metaDataSyned = true; return false; } else if (remains < 0) { return true; } return false; } private void updateConnectionInfo(PostgreSQLBackendConnection conn) { conn.xaStatus = (xaStarted) ? 1 : 0; if (schema != null) { conn.schema = schema; conn.oldSchema = conn.schema; } if (charsetIndex != null) { conn.setCharset(CharsetUtil.getCharset(charsetIndex)); } if (txtIsolation != null) { conn.txIsolation = txtIsolation; } if (autocommit != null) { conn.autocommit = autocommit; } } } private static final Query _COMMIT = new Query("commit"); private static final Query _ROLLBACK = new Query("rollback"); private static void getCharsetCommand(StringBuilder sb, int clientCharIndex) { sb.append("SET names '").append(CharsetUtil.getCharset(clientCharIndex).toUpperCase()).append("';"); } /** * 获取 更改事物级别sql * * @param * @param txIsolation */ private static void getTxIsolationCommand(StringBuilder sb, int txIsolation) { switch (txIsolation) { case Isolations.READ_UNCOMMITTED: sb.append("SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;"); return; case Isolations.READ_COMMITTED: sb.append("SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;"); return; case Isolations.REPEATED_READ: sb.append("SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;"); return; case Isolations.SERIALIZABLE: sb.append("SET SESSION TRANSACTION ISOLATION LEVEL SERIALIZABLE;"); return; default: throw new UnknownTxIsolationException("txIsolation:" + txIsolation); } } private Object attachment; private volatile boolean autocommit=true; private volatile boolean borrowed; protected volatile String charset = "utf8"; /*** * 当前事物ID */ private volatile String currentXaTxId; /** * 来自子接口 */ private volatile boolean fromSlaveDB; /**** * PG是否在事物中 */ private volatile boolean inTransaction = false; private AtomicBoolean isQuit = new AtomicBoolean(false); private volatile long lastTime; /** * 元数据同步 */ private volatile boolean metaDataSyned = true; private volatile boolean modifiedSQLExecuted = false; private volatile String oldSchema; /** * 密码 */ private volatile String password; /** * 数据源配置 */ private PostgreSQLDataSource pool; /*** * 响应handler */ private volatile ResponseHandler responseHandler; /*** * 对应数据库空间 */ private volatile String schema; // PostgreSQL服务端密码 private volatile int serverSecretKey; private volatile BackendConnectionState state = BackendConnectionState.connecting; private volatile StatusSync statusSync; private volatile int txIsolation; /*** * 用户名 */ private volatile String user; private volatile int xaStatus; public PostgreSQLBackendConnection(NetworkChannel channel, boolean fromSlaveDB) { super(channel); this.fromSlaveDB = fromSlaveDB; } @Override public void commit() { ByteBuffer buf = this.allocate(); _COMMIT.write(buf); this.write(buf); } @Override public void execute(RouteResultsetNode rrn, ServerConnection sc, boolean autocommit) throws IOException { int sqlType = rrn.getSqlType(); String orgin = rrn.getStatement(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("{}查询任务。。。。{}", id, rrn.getStatement()); LOGGER.debug(orgin); } //FIX BUG https://github.com/MyCATApache/Mycat-Server/issues/1185 if (sqlType == ServerParse.SELECT || sqlType == ServerParse.SHOW) { if (sqlType == ServerParse.SHOW) { //此处进行部分SHOW 语法适配 String _newSql = PgSqlApaterUtils.apater(orgin); if(_newSql.trim().substring(0,4).equalsIgnoreCase("show")){//未能适配成功 ShowVariables.execute(sc, orgin, this); return; } } else if ("SELECT CONNECTION_ID()".equalsIgnoreCase(orgin)) { ShowVariables.justReturnValue(sc, String.valueOf(sc.getId()), this); return; } } if (!modifiedSQLExecuted && rrn.isModifySQL()) { modifiedSQLExecuted = true; } String xaTXID = sc.getSession2().getXaTXID(); synAndDoExecute(xaTXID, rrn, sc.getCharsetIndex(), sc.getTxIsolation(), autocommit); } @Override public Object getAttachment() { return attachment; } private void getAutocommitCommand(StringBuilder sb, boolean autoCommit) { if (autoCommit) { sb.append(/*"SET autocommit=1;"*/"");//Fix bug 由于 PG9.0 开始不支持此选项,默认是为自动提交逻辑。 } else { sb.append("begin transaction;"); } } @Override public long getLastTime() { return lastTime; } public String getPassword() { return password; } public PostgreSQLDataSource getPool() { return pool; } public ResponseHandler getResponseHandler() { return responseHandler; } @Override public String getSchema() { return this.schema; } public int getServerSecretKey() { return serverSecretKey; } public BackendConnectionState getState() { return state; } @Override public int getTxIsolation() { return txIsolation; } public String getUser() { return user; } @Override public boolean isAutocommit() { return autocommit; } @Override public boolean isBorrowed() { return borrowed; } @Override public boolean isClosedOrQuit() { return isClosed() || isQuit.get(); } @Override public boolean isFromSlaveDB() { return fromSlaveDB; } public boolean isInTransaction() { return inTransaction; } @Override public boolean isModifiedSQLExecuted() { return modifiedSQLExecuted; } @Override public void onConnectFailed(Throwable t) { if (handler instanceof MySQLConnectionHandler) { } } @Override public void onConnectfinish() { LOGGER.debug("连接后台真正完成"); try { SocketChannel chan = (SocketChannel) this.channel; ByteBuffer buf = PacketUtils.makeStartUpPacket(user, schema); buf.flip(); chan.write(buf); } catch (Exception e) { LOGGER.error("Connected PostgreSQL Send StartUpPacket ERROR", e); throw new RuntimeException(e); } } protected final int getPacketLength(ByteBuffer buffer, int offset) { // Pg 协议获取包长度的方法和mysql 不一样 return PIOUtils.redInteger4(buffer, offset + 1) + 1; } /********** * 此查询用于心跳检查和获取连接后的健康检查 */ @Override public void query(String query) throws UnsupportedEncodingException { RouteResultsetNode rrn = new RouteResultsetNode("default", ServerParse.SELECT, query); synAndDoExecute(null, rrn, this.charsetIndex, this.txIsolation, true); } @Override public void quit() { if (isQuit.compareAndSet(false, true) && !isClosed()) { if (state == BackendConnectionState.connected) {// 断开 与PostgreSQL连接 Terminate terminate = new Terminate(); ByteBuffer buf = this.allocate(); terminate.write(buf); write(buf); } else { close("normal"); } } } /******* * 记录sql执行信息 */ @Override public void recordSql(String host, String schema, String statement) { LOGGER.debug(String.format("executed sql: host=%s,schema=%s,statement=%s", host, schema, statement)); } @Override public void release() { if (!metaDataSyned) {/* * indicate connection not normalfinished ,and * we can't know it's syn status ,so close it */ LOGGER.warn("can't sure connection syn result,so close it " + this); this.responseHandler = null; this.close("syn status unkown "); return; } metaDataSyned = true; attachment = null; statusSync = null; modifiedSQLExecuted = false; setResponseHandler(null); pool.releaseChannel(this); } @Override public void rollback() { ByteBuffer buf = this.allocate(); _ROLLBACK.write(buf); this.write(buf); } @Override public void setAttachment(Object attachment) { this.attachment = attachment; } @Override public void setBorrowed(boolean borrowed) { this.borrowed = borrowed; } public void setInTransaction(boolean inTransaction) { this.inTransaction = inTransaction; } @Override public void setLastTime(long currentTimeMillis) { this.lastTime = currentTimeMillis; } public void setPassword(String password) { this.password = password; } public void setPool(PostgreSQLDataSource pool) { this.pool = pool; } @Override public boolean setResponseHandler(ResponseHandler commandHandler) { this.responseHandler = commandHandler; return true; } @Override public void setSchema(String newSchema) { String curSchema = schema; if (curSchema == null) { this.schema = newSchema; this.oldSchema = newSchema; } else { this.oldSchema = curSchema; this.schema = newSchema; } } public void setServerSecretKey(int serverSecretKey) { this.serverSecretKey = serverSecretKey; } public void setState(BackendConnectionState state) { this.state = state; } public void setUser(String user) { this.user = user; } private void synAndDoExecute(String xaTxID, RouteResultsetNode rrn, int clientCharSetIndex, int clientTxIsoLation, boolean clientAutoCommit) { String xaCmd = null; boolean conAutoComit = this.autocommit; String conSchema = this.schema; // never executed modify sql,so auto commit boolean expectAutocommit = !modifiedSQLExecuted || isFromSlaveDB() || clientAutoCommit; if (!expectAutocommit && xaTxID != null && xaStatus == 0) { clientTxIsoLation = Isolations.SERIALIZABLE; xaCmd = "XA START " + xaTxID + ';'; currentXaTxId = xaTxID; } int schemaSyn = conSchema.equals(oldSchema) ? 0 : 1; int charsetSyn = (this.charsetIndex == clientCharSetIndex) ? 0 : 1; int txIsoLationSyn = (txIsolation == clientTxIsoLation) ? 0 : 1; int autoCommitSyn = (conAutoComit == expectAutocommit) ? 0 : 1; int synCount = schemaSyn + charsetSyn + txIsoLationSyn + autoCommitSyn; if (synCount == 0) { String sql = rrn.getStatement(); Query query = new Query(PgSqlApaterUtils.apater(sql)); ByteBuffer buf = this.allocate();// XXX 此处处理问题 query.write(buf); this.write(buf); return; } // TODO COOLLF 此处大锅待实现. 相关 事物, 切换 库,自动提交等功能实现 StringBuilder sb = new StringBuilder(); if (charsetSyn == 1) { getCharsetCommand(sb, clientCharSetIndex); } if (txIsoLationSyn == 1) { getTxIsolationCommand(sb, clientTxIsoLation); } if (autoCommitSyn == 1) { getAutocommitCommand(sb, expectAutocommit); } if (xaCmd != null) { sb.append(xaCmd); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("con need syn ,total syn cmd " + synCount + " commands " + sb.toString() + "schema change:" + ("" != null) + " con:" + this); } metaDataSyned = false; statusSync = new StatusSync(xaCmd != null, conSchema, clientCharSetIndex, clientTxIsoLation, expectAutocommit, synCount); String sql = sb.append(PgSqlApaterUtils.apater(rrn.getStatement())).toString(); if(LOGGER.isDebugEnabled()){ LOGGER.debug("con={}, SQL={}", this, sql); } Query query = new Query(sql); ByteBuffer buf = allocate();// 申请ByetBuffer query.write(buf); this.write(buf); metaDataSyned = true; } public void close(String reason) { if (!isClosed.get()) { isQuit.set(true); super.close(reason); pool.connectionClosed(this); if (this.responseHandler != null) { this.responseHandler.connectionClose(this, reason); responseHandler = null; } } } @Override public boolean syncAndExcute() { StatusSync sync = this.statusSync; if (sync != null) { boolean executed = sync.synAndExecuted(this); if (executed) { statusSync = null; } return executed; } return true; } @Override public String toString() { return "PostgreSQLBackendConnection [id=" + id + ", host=" + host + ", port=" + port + ", localPort=" + localPort + "]"; } }
Java
/* bnx2.c: QLogic NX2 network driver. * * Copyright (c) 2009-2014 QLogic Corporation * * 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. * * Written by: Michael Chan ([email protected]) */ #include <linux/version.h> #if (LINUX_VERSION_CODE < 0x020612) #include <linux/config.h> #endif #if (LINUX_VERSION_CODE < 0x020500) #if defined(CONFIG_MODVERSIONS) && defined(MODULE) && ! defined(MODVERSIONS) #define MODVERSIONS #include <linux/modversions.h> #endif #endif #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/module.h> #if (LINUX_VERSION_CODE >= 0x020600) #include <linux/moduleparam.h> #endif #include <linux/stringify.h> #include <linux/kernel.h> #include <linux/timer.h> #include <linux/errno.h> #include <linux/ioport.h> #include <linux/slab.h> #include <linux/vmalloc.h> #include <linux/interrupt.h> #include <linux/pci.h> #include <linux/init.h> #include <linux/netdevice.h> #include <linux/etherdevice.h> #include <linux/skbuff.h> #if (LINUX_VERSION_CODE >= 0x020600) #include <linux/dma-mapping.h> #endif #include <linux/bitops.h> #include <asm/io.h> #include <asm/irq.h> #include <linux/delay.h> #include <asm/byteorder.h> #include <asm/page.h> #include <linux/time.h> #include <linux/ethtool.h> #include <linux/mii.h> #include <linux/if_vlan.h> #if defined(CONFIG_VLAN_8021Q) || defined(CONFIG_VLAN_8021Q_MODULE) #define BCM_VLAN 1 #endif #ifdef NETIF_F_TSO #include <net/ip.h> #include <net/tcp.h> #include <net/checksum.h> #define BCM_TSO 1 #endif #if (LINUX_VERSION_CODE >= 0x020600) #include <linux/workqueue.h> #endif #ifndef BNX2_BOOT_DISK #include <linux/crc32.h> #endif #include <linux/prefetch.h> #include <linux/cache.h> #include <linux/zlib.h> #if (LINUX_VERSION_CODE >= 0x20617) && !defined(NETIF_F_MULTI_QUEUE) #include <linux/log2.h> #endif #ifdef HAVE_AER #include <linux/aer.h> #endif #if (LINUX_VERSION_CODE >= 0x020610) #define BCM_CNIC 1 #include "cnic_if.h" #endif #include "bnx2_compat0.h" #include "bnx2_compat.h" #include "bnx2.h" #include "bnx2_fw.h" #include "bnx2_fw2.h" #define DRV_MODULE_NAME "bnx2" #define DRV_MODULE_VERSION "2.2.4f.v60.10" #define DRV_MODULE_RELDATE "May 21, 2014" #define RUN_AT(x) (jiffies + (x)) /* Time in jiffies before concluding the transmitter is hung. */ #if defined(__VMKLNX__) /* On VMware ESX there is a possibility that that netdev watchdog thread * runs before the reset task if the machine is loaded. If this occurs * too many times, these premature watchdog triggers will cause a PSOD * on a VMware ESX beta build */ #define TX_TIMEOUT (20*HZ) #else #define TX_TIMEOUT (5*HZ) #endif /* defined(__VMKLNX__) */ #if defined(__VMKLNX__) && (VMWARE_ESX_DDK_VERSION >= 50000) #include "cnic_register.h" static int bnx2_registered_cnic_adapter; #endif /* defined(__VMKLNX__) && (VMWARE_ESX_DDK_VERSION >= 50000)*/ static char version[] __devinitdata = "QLogic NetXtreme II Gigabit Ethernet Driver " DRV_MODULE_NAME " v" DRV_MODULE_VERSION " (" DRV_MODULE_RELDATE ")\n"; MODULE_AUTHOR("Michael Chan <[email protected]>"); MODULE_DESCRIPTION("QLogic NetXtreme II BCM5706/5708/5709/5716 Driver"); MODULE_LICENSE("GPL"); MODULE_VERSION(DRV_MODULE_VERSION); static int disable_msi = 0; static int debug; #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 0)) /* BNX2X_UPSTREAM */ module_param(debug, int, 0); MODULE_PARM_DESC(debug, " Default debug msglevel"); #endif #if (LINUX_VERSION_CODE >= 0x20600) module_param(disable_msi, int, 0); MODULE_PARM_DESC(disable_msi, "Disable Message Signaled Interrupt (MSI)"); #endif static int stop_on_tx_timeout = 0; module_param(stop_on_tx_timeout, int, 0); MODULE_PARM_DESC(stop_on_tx_timeout, "For debugging purposes, prevent a chip " " reset when a tx timeout occurs"); #if defined(__VMKLNX__) static int psod_on_tx_timeout; module_param(psod_on_tx_timeout, int, 0); MODULE_PARM_DESC(psod_on_tx_timeout, "For debugging purposes, crash the system " " when a tx timeout occurs"); static int disable_msi_1shot = 0; module_param(disable_msi_1shot, int, 0); MODULE_PARM_DESC(disable_msi_1shot, "For debugging purposes, disable 1shot " " MSI mode if set to value of 1"); #if (VMWARE_ESX_DDK_VERSION >= 55000) static int disable_fw_dmp; module_param(disable_fw_dmp, int, 0); MODULE_PARM_DESC(disable_fw_dmp, "For debugging purposes, disable firmware " "dump feature when set to value of 1"); #endif #endif #define BNX2_MAX_NIC 32 #ifdef BNX2_ENABLE_NETQUEUE #define BNX2_OPTION_UNSET -1 #define BNX2_OPTION_ZERO 0 #define BNX2_NETQUEUE_ENABLED(bp) ((force_netq_param[bp->index] > 1) || \ (force_netq_param[bp->index] == \ BNX2_OPTION_UNSET)) #define BNX2_NETQUEUE_DISABLED(bp) (force_netq_param[bp->index] == 0) static int __devinitdata force_netq_param[BNX2_MAX_NIC+1] = { [0 ... BNX2_MAX_NIC] = BNX2_OPTION_UNSET }; static unsigned int num_force_netq; module_param_array_named(force_netq, force_netq_param, int, &num_force_netq, 0); MODULE_PARM_DESC(force_netq, "Option used for 5709/5716 only: " "Enforce the number of NetQueues per port " "(allowed values: -1 to 7 queues: " "1-7 will force the number of NetQueues for the " " given device, " "0 to disable NetQueue, " "-1 to use the default driver NetQueues value) " "[Maximum supported NIC's = 32] " "[example usage: force_net=-1,0,1,2: " "This corresponds to the first 5709/5716 to use " "the default number of NetQueues, " "disable NetQueue on the second 5709/5716, " "use 1 NetQueue on the third 5709/5716" "use 2 NetQueues on the fourth 5709/5716]"); #endif /* BNX2_ENABLE_NETQUEUE */ #if defined(__VMKLNX__) && (VMWARE_ESX_DDK_VERSION >= 55000) #include <vmklinux_9/vmklinux_dump.h> #define BNX2_DUMPNAME "bnx2_fwdmp" static vmklnx_DumpFileHandle bnx2_fwdmp_dh; static void *fwdmp_va_ptr; static struct bnx2 *fwdmp_bp_ptr[BNX2_MAX_NIC]; static VMK_ReturnStatus bnx2_fwdmp_callback(void *cookie, vmk_Bool liveDump); #endif typedef enum { BCM5706 = 0, NC370T, NC370I, BCM5706S, NC370F, BCM5708, BCM5708S, BCM5709, BCM5709S, BCM5716, BCM5716S, } board_t; /* indexed by board_t, above */ static struct { char *name; } board_info[] __devinitdata = { { "QLogic NetXtreme II BCM5706 1000Base-T" }, { "HP NC370T Multifunction Gigabit Server Adapter" }, { "HP NC370i Multifunction Gigabit Server Adapter" }, { "QLogic NetXtreme II BCM5706 1000Base-SX" }, { "HP NC370F Multifunction Gigabit Server Adapter" }, { "QLogic NetXtreme II BCM5708 1000Base-T" }, { "QLogic NetXtreme II BCM5708 1000Base-SX" }, { "QLogic NetXtreme II BCM5709 1000Base-T" }, { "QLogic NetXtreme II BCM5709 1000Base-SX" }, { "QLogic NetXtreme II BCM5716 1000Base-T" }, { "QLogic NetXtreme II BCM5716 1000Base-SX" }, }; static DEFINE_PCI_DEVICE_TABLE(bnx2_pci_tbl) = { { PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_NX2_5706, PCI_VENDOR_ID_HP, 0x3101, 0, 0, NC370T }, { PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_NX2_5706, PCI_VENDOR_ID_HP, 0x3106, 0, 0, NC370I }, { PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_NX2_5706, PCI_ANY_ID, PCI_ANY_ID, 0, 0, BCM5706 }, { PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_NX2_5708, PCI_ANY_ID, PCI_ANY_ID, 0, 0, BCM5708 }, { PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_NX2_5706S, PCI_VENDOR_ID_HP, 0x3102, 0, 0, NC370F }, { PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_NX2_5706S, PCI_ANY_ID, PCI_ANY_ID, 0, 0, BCM5706S }, { PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_NX2_5708S, PCI_ANY_ID, PCI_ANY_ID, 0, 0, BCM5708S }, { PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_NX2_5709, PCI_ANY_ID, PCI_ANY_ID, 0, 0, BCM5709 }, { PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_NX2_5709S, PCI_ANY_ID, PCI_ANY_ID, 0, 0, BCM5709S }, { PCI_VENDOR_ID_BROADCOM, 0x163b, PCI_ANY_ID, PCI_ANY_ID, 0, 0, BCM5716 }, { PCI_VENDOR_ID_BROADCOM, 0x163c, PCI_ANY_ID, PCI_ANY_ID, 0, 0, BCM5716S }, { 0, } }; static const struct flash_spec flash_table[] = { #define BUFFERED_FLAGS (BNX2_NV_BUFFERED | BNX2_NV_TRANSLATE) #define NONBUFFERED_FLAGS (BNX2_NV_WREN) /* Slow EEPROM */ {0x00000000, 0x40830380, 0x009f0081, 0xa184a053, 0xaf000400, BUFFERED_FLAGS, SEEPROM_PAGE_BITS, SEEPROM_PAGE_SIZE, SEEPROM_BYTE_ADDR_MASK, SEEPROM_TOTAL_SIZE, "EEPROM - slow"}, /* Expansion entry 0001 */ {0x08000002, 0x4b808201, 0x00050081, 0x03840253, 0xaf020406, NONBUFFERED_FLAGS, SAIFUN_FLASH_PAGE_BITS, SAIFUN_FLASH_PAGE_SIZE, SAIFUN_FLASH_BYTE_ADDR_MASK, 0, "Entry 0001"}, /* Saifun SA25F010 (non-buffered flash) */ /* strap, cfg1, & write1 need updates */ {0x04000001, 0x47808201, 0x00050081, 0x03840253, 0xaf020406, NONBUFFERED_FLAGS, SAIFUN_FLASH_PAGE_BITS, SAIFUN_FLASH_PAGE_SIZE, SAIFUN_FLASH_BYTE_ADDR_MASK, SAIFUN_FLASH_BASE_TOTAL_SIZE*2, "Non-buffered flash (128kB)"}, /* Saifun SA25F020 (non-buffered flash) */ /* strap, cfg1, & write1 need updates */ {0x0c000003, 0x4f808201, 0x00050081, 0x03840253, 0xaf020406, NONBUFFERED_FLAGS, SAIFUN_FLASH_PAGE_BITS, SAIFUN_FLASH_PAGE_SIZE, SAIFUN_FLASH_BYTE_ADDR_MASK, SAIFUN_FLASH_BASE_TOTAL_SIZE*4, "Non-buffered flash (256kB)"}, /* Expansion entry 0100 */ {0x11000000, 0x53808201, 0x00050081, 0x03840253, 0xaf020406, NONBUFFERED_FLAGS, SAIFUN_FLASH_PAGE_BITS, SAIFUN_FLASH_PAGE_SIZE, SAIFUN_FLASH_BYTE_ADDR_MASK, 0, "Entry 0100"}, /* Entry 0101: ST M45PE10 (non-buffered flash, TetonII B0) */ {0x19000002, 0x5b808201, 0x000500db, 0x03840253, 0xaf020406, NONBUFFERED_FLAGS, ST_MICRO_FLASH_PAGE_BITS, ST_MICRO_FLASH_PAGE_SIZE, ST_MICRO_FLASH_BYTE_ADDR_MASK, ST_MICRO_FLASH_BASE_TOTAL_SIZE*2, "Entry 0101: ST M45PE10 (128kB non-bufferred)"}, /* Entry 0110: ST M45PE20 (non-buffered flash)*/ {0x15000001, 0x57808201, 0x000500db, 0x03840253, 0xaf020406, NONBUFFERED_FLAGS, ST_MICRO_FLASH_PAGE_BITS, ST_MICRO_FLASH_PAGE_SIZE, ST_MICRO_FLASH_BYTE_ADDR_MASK, ST_MICRO_FLASH_BASE_TOTAL_SIZE*4, "Entry 0110: ST M45PE20 (256kB non-bufferred)"}, /* Saifun SA25F005 (non-buffered flash) */ /* strap, cfg1, & write1 need updates */ {0x1d000003, 0x5f808201, 0x00050081, 0x03840253, 0xaf020406, NONBUFFERED_FLAGS, SAIFUN_FLASH_PAGE_BITS, SAIFUN_FLASH_PAGE_SIZE, SAIFUN_FLASH_BYTE_ADDR_MASK, SAIFUN_FLASH_BASE_TOTAL_SIZE, "Non-buffered flash (64kB)"}, /* Fast EEPROM */ {0x22000000, 0x62808380, 0x009f0081, 0xa184a053, 0xaf000400, BUFFERED_FLAGS, SEEPROM_PAGE_BITS, SEEPROM_PAGE_SIZE, SEEPROM_BYTE_ADDR_MASK, SEEPROM_TOTAL_SIZE, "EEPROM - fast"}, /* Expansion entry 1001 */ {0x2a000002, 0x6b808201, 0x00050081, 0x03840253, 0xaf020406, NONBUFFERED_FLAGS, SAIFUN_FLASH_PAGE_BITS, SAIFUN_FLASH_PAGE_SIZE, SAIFUN_FLASH_BYTE_ADDR_MASK, 0, "Entry 1001"}, /* Expansion entry 1010 */ {0x26000001, 0x67808201, 0x00050081, 0x03840253, 0xaf020406, NONBUFFERED_FLAGS, SAIFUN_FLASH_PAGE_BITS, SAIFUN_FLASH_PAGE_SIZE, SAIFUN_FLASH_BYTE_ADDR_MASK, 0, "Entry 1010"}, /* ATMEL AT45DB011B (buffered flash) */ {0x2e000003, 0x6e808273, 0x00570081, 0x68848353, 0xaf000400, BUFFERED_FLAGS, BUFFERED_FLASH_PAGE_BITS, BUFFERED_FLASH_PAGE_SIZE, BUFFERED_FLASH_BYTE_ADDR_MASK, BUFFERED_FLASH_TOTAL_SIZE, "Buffered flash (128kB)"}, /* Expansion entry 1100 */ {0x33000000, 0x73808201, 0x00050081, 0x03840253, 0xaf020406, NONBUFFERED_FLAGS, SAIFUN_FLASH_PAGE_BITS, SAIFUN_FLASH_PAGE_SIZE, SAIFUN_FLASH_BYTE_ADDR_MASK, 0, "Entry 1100"}, /* Expansion entry 1101 */ {0x3b000002, 0x7b808201, 0x00050081, 0x03840253, 0xaf020406, NONBUFFERED_FLAGS, SAIFUN_FLASH_PAGE_BITS, SAIFUN_FLASH_PAGE_SIZE, SAIFUN_FLASH_BYTE_ADDR_MASK, 0, "Entry 1101"}, /* Ateml Expansion entry 1110 */ {0x37000001, 0x76808273, 0x00570081, 0x68848353, 0xaf000400, BUFFERED_FLAGS, BUFFERED_FLASH_PAGE_BITS, BUFFERED_FLASH_PAGE_SIZE, BUFFERED_FLASH_BYTE_ADDR_MASK, 0, "Entry 1110 (Atmel)"}, /* ATMEL AT45DB021B (buffered flash) */ {0x3f000003, 0x7e808273, 0x00570081, 0x68848353, 0xaf000400, BUFFERED_FLAGS, BUFFERED_FLASH_PAGE_BITS, BUFFERED_FLASH_PAGE_SIZE, BUFFERED_FLASH_BYTE_ADDR_MASK, BUFFERED_FLASH_TOTAL_SIZE*2, "Buffered flash (256kB)"}, }; static const struct flash_spec flash_5709 = { .flags = BNX2_NV_BUFFERED, .page_bits = BCM5709_FLASH_PAGE_BITS, .page_size = BCM5709_FLASH_PAGE_SIZE, .addr_mask = BCM5709_FLASH_BYTE_ADDR_MASK, .total_size = BUFFERED_FLASH_TOTAL_SIZE*2, .name = "5709 Buffered flash (256kB)", }; MODULE_DEVICE_TABLE(pci, bnx2_pci_tbl); #if !defined(__VMKLNX__) static void bnx2_init_napi(struct bnx2 *bp); static void bnx2_del_napi(struct bnx2 *bp); #else static void __devinit bnx2_init_napi(struct bnx2 *bp); static void __devexit bnx2_del_napi(struct bnx2 *bp); #endif static void bnx2_set_rx_ring_size(struct bnx2 *bp, u32 size); #if defined(__VMKLNX__) static int bnx2_tx_int(struct bnx2 *bp, struct bnx2_napi *bnapi, int budget, int check_queue); #endif /* defined(__VMKLNX__) */ #if defined(BNX2_ENABLE_NETQUEUE) static int bnx2_netqueue_ops(vmknetddi_queueops_op_t op, void *args); static void bnx2_stop_netqueue_hw(struct bnx2 *bp); static void bnx2_start_netqueue_hw(struct bnx2 *bp); static void bnx2_netqueue_service_bnx2_msix(struct bnx2_napi *bnapi); static int bnx2_netqueue_is_avail(struct bnx2 *bp); static void bnx2_close_netqueue_hw(struct bnx2 *bp); static void bnx2_init_netqueue_hw(struct bnx2 *bp); static int bnx2_open_netqueue_hw(struct bnx2 *bp); static void bnx2_netqueue_flush_all(struct bnx2 *bp); static int bnx2_netqueue_open_started(struct bnx2 *bp); static void bnx2_close_netqueue(struct bnx2 *bp); static void bnx2_start_netqueue(struct bnx2 *bp); static void bnx2_stop_netqueue(struct bnx2 *bp); static void bnx2_force_stop_netqueue(struct bnx2 * bp); static inline u16 bnx2_get_hw_tx_cons(struct bnx2_napi *bnapi); static inline u16 bnx2_get_hw_rx_cons(struct bnx2_napi *bnapi); #ifdef BNX2_DEBUG static u32 bnx2_read_ctx(struct bnx2 *bp, u32 offset); #endif static int bnx2_netq_alloc_tx_queue(struct bnx2 *bp, struct bnx2_napi *bnapi, int index); #define TRUE 1 #define FALSE 0 #define for_each_nondefault_rx_queue(bp, var) \ for (var = 1; var < bp->num_rx_rings; var++) #define for_each_nondefault_tx_queue(bp, var) \ for (var = 1; var < bp->num_tx_rings; var++) #define is_multi(bp) (bp->num_rx_ring > 1) #endif /* defined(BNX2_ENABLE_NETQUEUE) */ #ifdef BNX2_BOOT_DISK u32 ether_crc_le(size_t len, unsigned char const *p) { u32 crc = ~0; int i; #define CRCPOLY_LE 0xedb88320 while (len--) { crc ^= *p++; for (i = 0; i < 8; i++) crc = (crc >> 1) ^ ((crc & 1) ? CRCPOLY_LE : 0); } return crc; } #endif static inline u32 bnx2_tx_avail(struct bnx2 *bp, struct bnx2_tx_ring_info *txr) { u32 diff; /* Tell compiler to fetch tx_prod and tx_cons from memory. */ barrier(); /* The ring uses 256 indices for 255 entries, one of them * needs to be skipped. */ diff = txr->tx_prod - txr->tx_cons; if (unlikely(diff >= BNX2_TX_DESC_CNT)) { diff &= 0xffff; if (diff == BNX2_TX_DESC_CNT) diff = BNX2_MAX_TX_DESC_CNT; } return bp->tx_ring_size - diff; } static u32 bnx2_reg_rd_ind(struct bnx2 *bp, u32 offset) { u32 val; spin_lock_bh(&bp->indirect_lock); BNX2_WR(bp, BNX2_PCICFG_REG_WINDOW_ADDRESS, offset); val = BNX2_RD(bp, BNX2_PCICFG_REG_WINDOW); spin_unlock_bh(&bp->indirect_lock); return val; } static void bnx2_reg_wr_ind(struct bnx2 *bp, u32 offset, u32 val) { spin_lock_bh(&bp->indirect_lock); BNX2_WR(bp, BNX2_PCICFG_REG_WINDOW_ADDRESS, offset); BNX2_WR(bp, BNX2_PCICFG_REG_WINDOW, val); spin_unlock_bh(&bp->indirect_lock); } #if defined(__VMKLNX__) static void bnx2_reg_wr_ind_cfg(struct bnx2 *bp, u32 offset, u32 val) { struct pci_dev *pdev = bp->pdev; spin_lock_bh(&bp->indirect_lock); pci_write_config_dword(pdev, BNX2_PCICFG_REG_WINDOW_ADDRESS, offset); pci_write_config_dword(pdev, BNX2_PCICFG_REG_WINDOW, val); spin_unlock_bh(&bp->indirect_lock); } #endif /* defined(__VMKLNX__) */ static void bnx2_shmem_wr(struct bnx2 *bp, u32 offset, u32 val) { bnx2_reg_wr_ind(bp, bp->shmem_base + offset, val); } static u32 bnx2_shmem_rd(struct bnx2 *bp, u32 offset) { return bnx2_reg_rd_ind(bp, bp->shmem_base + offset); } static void bnx2_ctx_wr(struct bnx2 *bp, u32 cid_addr, u32 offset, u32 val) { offset += cid_addr; spin_lock_bh(&bp->indirect_lock); if (BNX2_CHIP(bp) == BNX2_CHIP_5709) { int i; BNX2_WR(bp, BNX2_CTX_CTX_DATA, val); BNX2_WR(bp, BNX2_CTX_CTX_CTRL, offset | BNX2_CTX_CTX_CTRL_WRITE_REQ); for (i = 0; i < 5; i++) { val = BNX2_RD(bp, BNX2_CTX_CTX_CTRL); if ((val & BNX2_CTX_CTX_CTRL_WRITE_REQ) == 0) break; udelay(5); } } else { BNX2_WR(bp, BNX2_CTX_DATA_ADR, offset); BNX2_WR(bp, BNX2_CTX_DATA, val); } spin_unlock_bh(&bp->indirect_lock); } #ifdef BCM_CNIC static int bnx2_drv_ctl(struct net_device *dev, struct drv_ctl_info *info) { struct bnx2 *bp = netdev_priv(dev); struct drv_ctl_io *io = &info->data.io; switch (info->cmd) { case DRV_CTL_IO_WR_CMD: bnx2_reg_wr_ind(bp, io->offset, io->data); break; case DRV_CTL_IO_RD_CMD: io->data = bnx2_reg_rd_ind(bp, io->offset); break; case DRV_CTL_CTX_WR_CMD: bnx2_ctx_wr(bp, io->cid_addr, io->offset, io->data); break; default: return -EINVAL; } return 0; } static void bnx2_setup_cnic_irq_info(struct bnx2 *bp) { struct cnic_eth_dev *cp = &bp->cnic_eth_dev; struct bnx2_napi *bnapi = &bp->bnx2_napi[0]; int sb_id; if (bp->flags & BNX2_FLAG_USING_MSIX) { cp->drv_state |= CNIC_DRV_STATE_USING_MSIX; bnapi->cnic_present = 0; sb_id = bp->irq_nvecs; cp->irq_arr[0].irq_flags |= CNIC_IRQ_FL_MSIX; } else { cp->drv_state &= ~CNIC_DRV_STATE_USING_MSIX; bnapi->cnic_tag = bnapi->last_status_idx; bnapi->cnic_present = 1; sb_id = 0; cp->irq_arr[0].irq_flags &= ~CNIC_IRQ_FL_MSIX; } cp->irq_arr[0].vector = bp->irq_tbl[sb_id].vector; cp->irq_arr[0].status_blk = (void *) ((unsigned long) bnapi->status_blk.msi + (BNX2_SBLK_MSIX_ALIGN_SIZE * sb_id)); cp->irq_arr[0].status_blk_num = sb_id; cp->num_irq = 1; } static int bnx2_register_cnic(struct net_device *dev, struct cnic_ops *ops, void *data) { struct bnx2 *bp = netdev_priv(dev); struct cnic_eth_dev *cp = &bp->cnic_eth_dev; if (ops == NULL) return -EINVAL; if (cp->drv_state & CNIC_DRV_STATE_REGD) return -EBUSY; if (!bnx2_reg_rd_ind(bp, BNX2_FW_MAX_ISCSI_CONN)) return -ENODEV; bp->cnic_data = data; rcu_assign_pointer(bp->cnic_ops, ops); cp->num_irq = 0; cp->drv_state = CNIC_DRV_STATE_REGD; bnx2_setup_cnic_irq_info(bp); return 0; } static int bnx2_unregister_cnic(struct net_device *dev) { struct bnx2 *bp = netdev_priv(dev); struct bnx2_napi *bnapi = &bp->bnx2_napi[0]; struct cnic_eth_dev *cp = &bp->cnic_eth_dev; mutex_lock(&bp->cnic_lock); cp->drv_state = 0; bnapi->cnic_present = 0; RCU_INIT_POINTER(bp->cnic_ops, NULL); mutex_unlock(&bp->cnic_lock); synchronize_rcu(); return 0; } #if defined(BNX2_INBOX) struct cnic_eth_dev *bnx2_cnic_probe(struct net_device *dev) #else /* !defined(BNX2_INBOX) */ static struct cnic_eth_dev *bnx2_cnic_probe2(struct net_device *dev) #endif /* defined(BNX2_INBOX) */ { struct bnx2 *bp = netdev_priv(dev); struct cnic_eth_dev *cp = &bp->cnic_eth_dev; if (!cp->max_iscsi_conn) return NULL; cp->version = CNIC_ETH_DEV_VER; cp->drv_owner = THIS_MODULE; cp->chip_id = bp->chip_id; cp->pdev = bp->pdev; cp->io_base = bp->regview; cp->drv_ctl = bnx2_drv_ctl; cp->drv_register_cnic = bnx2_register_cnic; cp->drv_unregister_cnic = bnx2_unregister_cnic; return cp; } static void bnx2_cnic_stop(struct bnx2 *bp) { struct cnic_ops *c_ops; struct cnic_ctl_info info; mutex_lock(&bp->cnic_lock); c_ops = rcu_dereference_protected(bp->cnic_ops, lockdep_is_held(&bp->cnic_lock)); if (c_ops) { info.cmd = CNIC_CTL_STOP_CMD; #if defined(__VMKLNX__) VMKAPI_MODULE_CALL_VOID(c_ops->cnic_owner->moduleID, c_ops->cnic_ctl, bp->cnic_data, &info); #else c_ops->cnic_ctl(bp->cnic_data, &info); #endif } mutex_unlock(&bp->cnic_lock); } static void bnx2_cnic_start(struct bnx2 *bp) { struct cnic_ops *c_ops; struct cnic_ctl_info info; mutex_lock(&bp->cnic_lock); c_ops = rcu_dereference_protected(bp->cnic_ops, lockdep_is_held(&bp->cnic_lock)); if (c_ops) { if (!(bp->flags & BNX2_FLAG_USING_MSIX)) { struct bnx2_napi *bnapi = &bp->bnx2_napi[0]; bnapi->cnic_tag = bnapi->last_status_idx; } info.cmd = CNIC_CTL_START_CMD; #if defined(__VMKLNX__) VMKAPI_MODULE_CALL_VOID(c_ops->cnic_owner->moduleID, c_ops->cnic_ctl, bp->cnic_data, &info); #else c_ops->cnic_ctl(bp->cnic_data, &info); #endif } mutex_unlock(&bp->cnic_lock); } #else static void bnx2_cnic_stop(struct bnx2 *bp) { } static void bnx2_cnic_start(struct bnx2 *bp) { } #endif static int bnx2_read_phy(struct bnx2 *bp, u32 reg, u32 *val) { u32 val1; int i, ret; if (bp->phy_flags & BNX2_PHY_FLAG_INT_MODE_AUTO_POLLING) { val1 = BNX2_RD(bp, BNX2_EMAC_MDIO_MODE); val1 &= ~BNX2_EMAC_MDIO_MODE_AUTO_POLL; BNX2_WR(bp, BNX2_EMAC_MDIO_MODE, val1); BNX2_RD(bp, BNX2_EMAC_MDIO_MODE); udelay(40); } val1 = (bp->phy_addr << 21) | (reg << 16) | BNX2_EMAC_MDIO_COMM_COMMAND_READ | BNX2_EMAC_MDIO_COMM_DISEXT | BNX2_EMAC_MDIO_COMM_START_BUSY; BNX2_WR(bp, BNX2_EMAC_MDIO_COMM, val1); for (i = 0; i < 50; i++) { udelay(10); val1 = BNX2_RD(bp, BNX2_EMAC_MDIO_COMM); if (!(val1 & BNX2_EMAC_MDIO_COMM_START_BUSY)) { udelay(5); val1 = BNX2_RD(bp, BNX2_EMAC_MDIO_COMM); val1 &= BNX2_EMAC_MDIO_COMM_DATA; break; } } if (val1 & BNX2_EMAC_MDIO_COMM_START_BUSY) { *val = 0x0; ret = -EBUSY; } else { *val = val1; ret = 0; } if (bp->phy_flags & BNX2_PHY_FLAG_INT_MODE_AUTO_POLLING) { val1 = BNX2_RD(bp, BNX2_EMAC_MDIO_MODE); val1 |= BNX2_EMAC_MDIO_MODE_AUTO_POLL; BNX2_WR(bp, BNX2_EMAC_MDIO_MODE, val1); BNX2_RD(bp, BNX2_EMAC_MDIO_MODE); udelay(40); } return ret; } static int bnx2_write_phy(struct bnx2 *bp, u32 reg, u32 val) { u32 val1; int i, ret; if (bp->phy_flags & BNX2_PHY_FLAG_INT_MODE_AUTO_POLLING) { val1 = BNX2_RD(bp, BNX2_EMAC_MDIO_MODE); val1 &= ~BNX2_EMAC_MDIO_MODE_AUTO_POLL; BNX2_WR(bp, BNX2_EMAC_MDIO_MODE, val1); BNX2_RD(bp, BNX2_EMAC_MDIO_MODE); udelay(40); } val1 = (bp->phy_addr << 21) | (reg << 16) | val | BNX2_EMAC_MDIO_COMM_COMMAND_WRITE | BNX2_EMAC_MDIO_COMM_START_BUSY | BNX2_EMAC_MDIO_COMM_DISEXT; BNX2_WR(bp, BNX2_EMAC_MDIO_COMM, val1); for (i = 0; i < 50; i++) { udelay(10); val1 = BNX2_RD(bp, BNX2_EMAC_MDIO_COMM); if (!(val1 & BNX2_EMAC_MDIO_COMM_START_BUSY)) { udelay(5); break; } } if (val1 & BNX2_EMAC_MDIO_COMM_START_BUSY) ret = -EBUSY; else ret = 0; if (bp->phy_flags & BNX2_PHY_FLAG_INT_MODE_AUTO_POLLING) { val1 = BNX2_RD(bp, BNX2_EMAC_MDIO_MODE); val1 |= BNX2_EMAC_MDIO_MODE_AUTO_POLL; BNX2_WR(bp, BNX2_EMAC_MDIO_MODE, val1); BNX2_RD(bp, BNX2_EMAC_MDIO_MODE); udelay(40); } return ret; } static void bnx2_disable_int(struct bnx2 *bp) { int i; struct bnx2_napi *bnapi; for (i = 0; i < bp->irq_nvecs; i++) { bnapi = &bp->bnx2_napi[i]; BNX2_WR(bp, BNX2_PCICFG_INT_ACK_CMD, bnapi->int_num | BNX2_PCICFG_INT_ACK_CMD_MASK_INT); } BNX2_RD(bp, BNX2_PCICFG_INT_ACK_CMD); } static void bnx2_enable_int(struct bnx2 *bp) { int i; struct bnx2_napi *bnapi; for (i = 0; i < bp->irq_nvecs; i++) { bnapi = &bp->bnx2_napi[i]; BNX2_WR(bp, BNX2_PCICFG_INT_ACK_CMD, bnapi->int_num | BNX2_PCICFG_INT_ACK_CMD_INDEX_VALID | BNX2_PCICFG_INT_ACK_CMD_MASK_INT | bnapi->last_status_idx); BNX2_WR(bp, BNX2_PCICFG_INT_ACK_CMD, bnapi->int_num | BNX2_PCICFG_INT_ACK_CMD_INDEX_VALID | bnapi->last_status_idx); } BNX2_WR(bp, BNX2_HC_COMMAND, bp->hc_cmd | BNX2_HC_COMMAND_COAL_NOW); } static void bnx2_disable_int_sync(struct bnx2 *bp) { int i; atomic_inc(&bp->intr_sem); if (!netif_running(bp->dev)) return; bnx2_disable_int(bp); for (i = 0; i < bp->irq_nvecs; i++) #if (LINUX_VERSION_CODE >= 0x2051c) synchronize_irq(bp->irq_tbl[i].vector); #else synchronize_irq(); #endif } static void bnx2_napi_disable(struct bnx2 *bp) { #ifdef BNX2_NEW_NAPI int i; for (i = 0; i < bp->irq_nvecs; i++) napi_disable(&bp->bnx2_napi[i].napi); #else netif_poll_disable(bp->dev); #endif } static void bnx2_napi_enable(struct bnx2 *bp) { #ifdef BNX2_NEW_NAPI int i; for (i = 0; i < bp->irq_nvecs; i++) napi_enable(&bp->bnx2_napi[i].napi); #else netif_poll_enable(bp->dev); #endif } #if defined(BNX2_ENABLE_NETQUEUE) static void bnx2_netqueue_tx_flush_queue(struct bnx2_napi *bnapi, struct bnx2_tx_ring_info *txr) { struct bnx2 *bp = bnapi->bp; rmb(); if ((bnx2_get_hw_tx_cons(bnapi) != txr->hw_tx_cons) || (bnapi->tx_packets_sent != bnapi->tx_packets_processed)) { bnx2_tx_int(bp, bnapi, 100, 0); msleep(1); rmb(); } } static void bnx2_netqueue_tx_flush(struct bnx2 *bp) { int i; struct bnx2_napi *bnapi; struct bnx2_tx_ring_info *txr; /* Flush default ring */ bnapi = &bp->bnx2_napi[0]; txr = &bnapi->tx_ring; bnx2_netqueue_tx_flush_queue(bnapi, txr); netdev_info(bp->dev, "flushed default TX queue\n"); /* Flush NetQ rings */ for_each_nondefault_tx_queue(bp, i) { bnapi = &bp->bnx2_napi[i]; txr = &bnapi->tx_ring; rmb(); bnx2_netqueue_tx_flush_queue(bnapi, txr); netdev_info(bp->dev, "flushed TX queue %d\n", i); } } static void bnx2_netif_stop(struct bnx2 *bp, bool stop_cnic) { if (stop_cnic) { #if defined(BNX2_ENABLE_NETQUEUE) /* Note that queues allocated MUST be read before they * got reset during stop_nequeue */ int tx_queues_allocated = bp->n_tx_queues_allocated; int rx_queues_allocated = bp->n_rx_queues_allocated; bnx2_stop_netqueue(bp); if (rx_queues_allocated == 0 && tx_queues_allocated == bp->num_tx_rings - 1) /* to avoid repeated callbacks from ESX host, * we need to skip invalidating state in no * rx queues are allocated. */ bp->skip_invalidate_tx_netq = tx_queues_allocated; else vmknetddi_queueops_invalidate_state(bp->dev); #endif bnx2_cnic_stop(bp); } if (netif_running(bp->dev)) { bnx2_napi_disable(bp); bnx2_disable_int_sync(bp); netif_carrier_off(bp->dev); /* prevent tx timeout */ netif_tx_disable(bp->dev); } rmb(); #if defined(BNX2_ENABLE_NETQUEUE) if (bnx2_netqueue_open_started(bp)) bnx2_netqueue_tx_flush(bp); if (stop_cnic) { /* if for whatever the reason, netqueue failed to stop in case of chip getting stuck, we should force the netqueue to stop since chip will go thru full reset afterward. */ if (bnx2_netqueue_is_avail(bp)) bnx2_force_stop_netqueue(bp); } #endif /* defined(BNX2_ENABLE_NETQUEUE) */ } #else static void bnx2_netif_stop(struct bnx2 *bp, bool stop_cnic) { if (stop_cnic) bnx2_cnic_stop(bp); if (netif_running(bp->dev)) { bnx2_napi_disable(bp); bnx2_disable_int_sync(bp); netif_carrier_off(bp->dev); /* prevent tx timeout */ netif_tx_disable(bp->dev); } } #endif static void bnx2_netif_start(struct bnx2 *bp, bool start_cnic) { #if defined(__VMKLNX__) && defined(BNX2_ENABLE_NETQUEUE) if (start_cnic && bnx2_netqueue_is_avail(bp)) { bnx2_start_netqueue(bp); /* we might have skipped invalidating netq state * when stopping netq earlier to avoid repeated * callbacks from ESX host. If so, we need to * manually allocate the tx queues accordingly. */ if (bp->skip_invalidate_tx_netq) { int index; for_each_nondefault_tx_queue(bp, index) { struct bnx2_napi *bnapi = &bp->bnx2_napi[index]; if (bnx2_netq_alloc_tx_queue(bp, bnapi, index) != VMKNETDDI_QUEUEOPS_OK) break; } BUG_ON(index - 1 != bp->skip_invalidate_tx_netq); bp->skip_invalidate_tx_netq = 0; } } #endif if (atomic_dec_and_test(&bp->intr_sem)) { if (netif_running(bp->dev)) { netif_tx_wake_all_queues(bp->dev); spin_lock_bh(&bp->phy_lock); if (bp->link_up) netif_carrier_on(bp->dev); spin_unlock_bh(&bp->phy_lock); bnx2_napi_enable(bp); bnx2_enable_int(bp); if (start_cnic) bnx2_cnic_start(bp); } } } static void bnx2_free_tx_mem(struct bnx2 *bp) { int i; for (i = 0; i < bp->num_tx_rings; i++) { struct bnx2_napi *bnapi = &bp->bnx2_napi[i]; struct bnx2_tx_ring_info *txr = &bnapi->tx_ring; if (txr->tx_desc_ring) { #if (LINUX_VERSION_CODE >= 0x02061b) dma_free_coherent(&bp->pdev->dev, TXBD_RING_SIZE, txr->tx_desc_ring, txr->tx_desc_mapping); #else pci_free_consistent(bp->pdev, TXBD_RING_SIZE, txr->tx_desc_ring, txr->tx_desc_mapping); #endif txr->tx_desc_ring = NULL; } kfree(txr->tx_buf_ring); txr->tx_buf_ring = NULL; } } static void bnx2_free_rx_mem(struct bnx2 *bp) { int i; for (i = 0; i < bp->num_rx_rings; i++) { struct bnx2_napi *bnapi = &bp->bnx2_napi[i]; struct bnx2_rx_ring_info *rxr = &bnapi->rx_ring; int j; for (j = 0; j < bp->rx_max_ring; j++) { if (rxr->rx_desc_ring[j]) #if (LINUX_VERSION_CODE >= 0x02061b) dma_free_coherent(&bp->pdev->dev, RXBD_RING_SIZE, rxr->rx_desc_ring[j], rxr->rx_desc_mapping[j]); #else pci_free_consistent(bp->pdev, RXBD_RING_SIZE, rxr->rx_desc_ring[j], rxr->rx_desc_mapping[j]); #endif rxr->rx_desc_ring[j] = NULL; } vfree(rxr->rx_buf_ring); rxr->rx_buf_ring = NULL; for (j = 0; j < bp->rx_max_pg_ring; j++) { if (rxr->rx_pg_desc_ring[j]) #if (LINUX_VERSION_CODE >= 0x02061b) dma_free_coherent(&bp->pdev->dev, RXBD_RING_SIZE, rxr->rx_pg_desc_ring[j], rxr->rx_pg_desc_mapping[j]); #else pci_free_consistent(bp->pdev, RXBD_RING_SIZE, rxr->rx_pg_desc_ring[j], rxr->rx_pg_desc_mapping[j]); #endif rxr->rx_pg_desc_ring[j] = NULL; } vfree(rxr->rx_pg_ring); rxr->rx_pg_ring = NULL; } } static int bnx2_alloc_tx_mem(struct bnx2 *bp) { int i; for (i = 0; i < bp->num_tx_rings; i++) { struct bnx2_napi *bnapi = &bp->bnx2_napi[i]; struct bnx2_tx_ring_info *txr = &bnapi->tx_ring; txr->tx_buf_ring = kmalloc(SW_TXBD_RING_SIZE, GFP_KERNEL); if (txr->tx_buf_ring == NULL) return -ENOMEM; memset(txr->tx_buf_ring, 0, SW_TXBD_RING_SIZE); txr->tx_desc_ring = #if (LINUX_VERSION_CODE >= 0x02061b) dma_alloc_coherent(&bp->pdev->dev, TXBD_RING_SIZE, &txr->tx_desc_mapping, GFP_KERNEL); #else pci_alloc_consistent(bp->pdev, TXBD_RING_SIZE, &txr->tx_desc_mapping); #endif if (txr->tx_desc_ring == NULL) return -ENOMEM; } return 0; } static int bnx2_alloc_rx_mem(struct bnx2 *bp) { int i; for (i = 0; i < bp->num_rx_rings; i++) { struct bnx2_napi *bnapi = &bp->bnx2_napi[i]; struct bnx2_rx_ring_info *rxr = &bnapi->rx_ring; int j; rxr->rx_buf_ring = vmalloc(SW_RXBD_RING_SIZE * bp->rx_max_ring); if (rxr->rx_buf_ring == NULL) return -ENOMEM; memset(rxr->rx_buf_ring, 0, SW_RXBD_RING_SIZE * bp->rx_max_ring); for (j = 0; j < bp->rx_max_ring; j++) { rxr->rx_desc_ring[j] = #if (LINUX_VERSION_CODE >= 0x02061b) dma_alloc_coherent(&bp->pdev->dev, RXBD_RING_SIZE, &rxr->rx_desc_mapping[j], GFP_KERNEL); #else pci_alloc_consistent(bp->pdev, RXBD_RING_SIZE, &rxr->rx_desc_mapping[j]); #endif if (rxr->rx_desc_ring[j] == NULL) return -ENOMEM; } if (bp->rx_pg_ring_size) { rxr->rx_pg_ring = vmalloc(SW_RXPG_RING_SIZE * bp->rx_max_pg_ring); if (rxr->rx_pg_ring == NULL) return -ENOMEM; memset(rxr->rx_pg_ring, 0, SW_RXPG_RING_SIZE * bp->rx_max_pg_ring); } for (j = 0; j < bp->rx_max_pg_ring; j++) { rxr->rx_pg_desc_ring[j] = #if (LINUX_VERSION_CODE >= 0x02061b) dma_alloc_coherent(&bp->pdev->dev, RXBD_RING_SIZE, &rxr->rx_pg_desc_mapping[j], GFP_KERNEL); #else pci_alloc_consistent(bp->pdev, RXBD_RING_SIZE, &rxr->rx_pg_desc_mapping[j]); #endif if (rxr->rx_pg_desc_ring[j] == NULL) return -ENOMEM; } } return 0; } static void bnx2_free_mem(struct bnx2 *bp) { int i; struct bnx2_napi *bnapi = &bp->bnx2_napi[0]; bnx2_free_tx_mem(bp); bnx2_free_rx_mem(bp); for (i = 0; i < bp->ctx_pages; i++) { if (bp->ctx_blk[i]) { #if (LINUX_VERSION_CODE >= 0x02061b) dma_free_coherent(&bp->pdev->dev, BNX2_PAGE_SIZE, bp->ctx_blk[i], bp->ctx_blk_mapping[i]); #else pci_free_consistent(bp->pdev, BNX2_PAGE_SIZE, bp->ctx_blk[i], bp->ctx_blk_mapping[i]); #endif bp->ctx_blk[i] = NULL; } } if (bnapi->status_blk.msi) { #if (LINUX_VERSION_CODE >= 0x02061b) dma_free_coherent(&bp->pdev->dev, bp->status_stats_size, bnapi->status_blk.msi, bp->status_blk_mapping); #else pci_free_consistent(bp->pdev, bp->status_stats_size, bnapi->status_blk.msi, bp->status_blk_mapping); #endif bnapi->status_blk.msi = NULL; bp->stats_blk = NULL; } } static int bnx2_alloc_mem(struct bnx2 *bp) { int i, status_blk_size, err; struct bnx2_napi *bnapi; void *status_blk; /* Combine status and statistics blocks into one allocation. */ status_blk_size = L1_CACHE_ALIGN(sizeof(struct status_block)); #ifdef CONFIG_PCI_MSI if (bp->flags & BNX2_FLAG_MSIX_CAP) status_blk_size = L1_CACHE_ALIGN(BNX2_MAX_MSIX_HW_VEC * BNX2_SBLK_MSIX_ALIGN_SIZE); #endif bp->status_stats_size = status_blk_size + sizeof(struct statistics_block); #if (LINUX_VERSION_CODE >= 0x02061b) status_blk = dma_alloc_coherent(&bp->pdev->dev, bp->status_stats_size, &bp->status_blk_mapping, GFP_KERNEL); #else status_blk = pci_alloc_consistent(bp->pdev, bp->status_stats_size, &bp->status_blk_mapping); #endif if (status_blk == NULL) goto alloc_mem_err; memset(status_blk, 0, bp->status_stats_size); bnapi = &bp->bnx2_napi[0]; bnapi->status_blk.msi = status_blk; bnapi->hw_tx_cons_ptr = &bnapi->status_blk.msi->status_tx_quick_consumer_index0; bnapi->hw_rx_cons_ptr = &bnapi->status_blk.msi->status_rx_quick_consumer_index0; if (bp->flags & BNX2_FLAG_MSIX_CAP) { for (i = 1; i < bp->irq_nvecs; i++) { struct status_block_msix *sblk; bnapi = &bp->bnx2_napi[i]; sblk = (status_blk + BNX2_SBLK_MSIX_ALIGN_SIZE * i); bnapi->status_blk.msix = sblk; bnapi->hw_tx_cons_ptr = &sblk->status_tx_quick_consumer_index; bnapi->hw_rx_cons_ptr = &sblk->status_rx_quick_consumer_index; bnapi->int_num = i << 24; } } bp->stats_blk = status_blk + status_blk_size; bp->stats_blk_mapping = bp->status_blk_mapping + status_blk_size; if (BNX2_CHIP(bp) == BNX2_CHIP_5709) { /* NetQ uses CID 100, so we need 16K of context memory */ #if defined(BNX2_ENABLE_NETQUEUE) bp->ctx_pages = 0x4000 / BNX2_PAGE_SIZE; #else /* !defined(__VMKLNX__) */ bp->ctx_pages = 0x2000 / BNX2_PAGE_SIZE; #endif /* defined(__VMKLNX__) */ if (bp->ctx_pages == 0) bp->ctx_pages = 1; for (i = 0; i < bp->ctx_pages; i++) { #if (LINUX_VERSION_CODE >= 0x02061b) bp->ctx_blk[i] = dma_alloc_coherent(&bp->pdev->dev, BNX2_PAGE_SIZE, &bp->ctx_blk_mapping[i], GFP_KERNEL); #else bp->ctx_blk[i] = pci_alloc_consistent(bp->pdev, BNX2_PAGE_SIZE, &bp->ctx_blk_mapping[i]); #endif if (bp->ctx_blk[i] == NULL) goto alloc_mem_err; } } err = bnx2_alloc_rx_mem(bp); if (err) goto alloc_mem_err; err = bnx2_alloc_tx_mem(bp); if (err) goto alloc_mem_err; return 0; alloc_mem_err: bnx2_free_mem(bp); return -ENOMEM; } static void bnx2_report_fw_link(struct bnx2 *bp) { u32 fw_link_status = 0; if (bp->phy_flags & BNX2_PHY_FLAG_REMOTE_PHY_CAP) return; if (bp->link_up) { u32 bmsr; switch (bp->line_speed) { case SPEED_10: if (bp->duplex == DUPLEX_HALF) fw_link_status = BNX2_LINK_STATUS_10HALF; else fw_link_status = BNX2_LINK_STATUS_10FULL; break; case SPEED_100: if (bp->duplex == DUPLEX_HALF) fw_link_status = BNX2_LINK_STATUS_100HALF; else fw_link_status = BNX2_LINK_STATUS_100FULL; break; case SPEED_1000: if (bp->duplex == DUPLEX_HALF) fw_link_status = BNX2_LINK_STATUS_1000HALF; else fw_link_status = BNX2_LINK_STATUS_1000FULL; break; case SPEED_2500: if (bp->duplex == DUPLEX_HALF) fw_link_status = BNX2_LINK_STATUS_2500HALF; else fw_link_status = BNX2_LINK_STATUS_2500FULL; break; } fw_link_status |= BNX2_LINK_STATUS_LINK_UP; if (bp->autoneg) { fw_link_status |= BNX2_LINK_STATUS_AN_ENABLED; bnx2_read_phy(bp, bp->mii_bmsr, &bmsr); bnx2_read_phy(bp, bp->mii_bmsr, &bmsr); if (!(bmsr & BMSR_ANEGCOMPLETE) || bp->phy_flags & BNX2_PHY_FLAG_PARALLEL_DETECT) fw_link_status |= BNX2_LINK_STATUS_PARALLEL_DET; else fw_link_status |= BNX2_LINK_STATUS_AN_COMPLETE; } } else fw_link_status = BNX2_LINK_STATUS_LINK_DOWN; bnx2_shmem_wr(bp, BNX2_LINK_STATUS, fw_link_status); } static char * bnx2_xceiver_str(struct bnx2 *bp) { return (bp->phy_port == PORT_FIBRE) ? "SerDes" : ((bp->phy_flags & BNX2_PHY_FLAG_SERDES) ? "Remote Copper" : "Copper"); } static void bnx2_report_link(struct bnx2 *bp) { if (bp->link_up) { netif_carrier_on(bp->dev); netdev_info(bp->dev, "NIC %s Link is Up, %d Mbps %s duplex", bnx2_xceiver_str(bp), bp->line_speed, bp->duplex == DUPLEX_FULL ? "full" : "half"); if (bp->flow_ctrl) { if (bp->flow_ctrl & FLOW_CTRL_RX) { pr_cont(", receive "); if (bp->flow_ctrl & FLOW_CTRL_TX) pr_cont("& transmit "); } else { pr_cont(", transmit "); } pr_cont("flow control ON"); } pr_cont("\n"); } else { netif_carrier_off(bp->dev); netdev_err(bp->dev, "NIC %s Link is Down\n", bnx2_xceiver_str(bp)); } bnx2_report_fw_link(bp); } static void bnx2_resolve_flow_ctrl(struct bnx2 *bp) { u32 local_adv, remote_adv; bp->flow_ctrl = 0; if ((bp->autoneg & (AUTONEG_SPEED | AUTONEG_FLOW_CTRL)) != (AUTONEG_SPEED | AUTONEG_FLOW_CTRL)) { if (bp->duplex == DUPLEX_FULL) { bp->flow_ctrl = bp->req_flow_ctrl; } return; } if (bp->duplex != DUPLEX_FULL) { return; } if ((bp->phy_flags & BNX2_PHY_FLAG_SERDES) && (BNX2_CHIP(bp) == BNX2_CHIP_5708)) { u32 val; bnx2_read_phy(bp, BCM5708S_1000X_STAT1, &val); if (val & BCM5708S_1000X_STAT1_TX_PAUSE) bp->flow_ctrl |= FLOW_CTRL_TX; if (val & BCM5708S_1000X_STAT1_RX_PAUSE) bp->flow_ctrl |= FLOW_CTRL_RX; return; } bnx2_read_phy(bp, bp->mii_adv, &local_adv); bnx2_read_phy(bp, bp->mii_lpa, &remote_adv); if (bp->phy_flags & BNX2_PHY_FLAG_SERDES) { u32 new_local_adv = 0; u32 new_remote_adv = 0; if (local_adv & ADVERTISE_1000XPAUSE) new_local_adv |= ADVERTISE_PAUSE_CAP; if (local_adv & ADVERTISE_1000XPSE_ASYM) new_local_adv |= ADVERTISE_PAUSE_ASYM; if (remote_adv & ADVERTISE_1000XPAUSE) new_remote_adv |= ADVERTISE_PAUSE_CAP; if (remote_adv & ADVERTISE_1000XPSE_ASYM) new_remote_adv |= ADVERTISE_PAUSE_ASYM; local_adv = new_local_adv; remote_adv = new_remote_adv; } /* See Table 28B-3 of 802.3ab-1999 spec. */ if (local_adv & ADVERTISE_PAUSE_CAP) { if(local_adv & ADVERTISE_PAUSE_ASYM) { if (remote_adv & ADVERTISE_PAUSE_CAP) { bp->flow_ctrl = FLOW_CTRL_TX | FLOW_CTRL_RX; } else if (remote_adv & ADVERTISE_PAUSE_ASYM) { bp->flow_ctrl = FLOW_CTRL_RX; } } else { if (remote_adv & ADVERTISE_PAUSE_CAP) { bp->flow_ctrl = FLOW_CTRL_TX | FLOW_CTRL_RX; } } } else if (local_adv & ADVERTISE_PAUSE_ASYM) { if ((remote_adv & ADVERTISE_PAUSE_CAP) && (remote_adv & ADVERTISE_PAUSE_ASYM)) { bp->flow_ctrl = FLOW_CTRL_TX; } } } static int bnx2_5709s_linkup(struct bnx2 *bp) { u32 val, speed; bp->link_up = 1; bnx2_write_phy(bp, MII_BNX2_BLK_ADDR, MII_BNX2_BLK_ADDR_GP_STATUS); bnx2_read_phy(bp, MII_BNX2_GP_TOP_AN_STATUS1, &val); bnx2_write_phy(bp, MII_BNX2_BLK_ADDR, MII_BNX2_BLK_ADDR_COMBO_IEEEB0); if ((bp->autoneg & AUTONEG_SPEED) == 0) { bp->line_speed = bp->req_line_speed; bp->duplex = bp->req_duplex; return 0; } speed = val & MII_BNX2_GP_TOP_AN_SPEED_MSK; switch (speed) { case MII_BNX2_GP_TOP_AN_SPEED_10: bp->line_speed = SPEED_10; break; case MII_BNX2_GP_TOP_AN_SPEED_100: bp->line_speed = SPEED_100; break; case MII_BNX2_GP_TOP_AN_SPEED_1G: case MII_BNX2_GP_TOP_AN_SPEED_1GKV: bp->line_speed = SPEED_1000; break; case MII_BNX2_GP_TOP_AN_SPEED_2_5G: bp->line_speed = SPEED_2500; break; } if (val & MII_BNX2_GP_TOP_AN_FD) bp->duplex = DUPLEX_FULL; else bp->duplex = DUPLEX_HALF; return 0; } static int bnx2_5708s_linkup(struct bnx2 *bp) { u32 val; bp->link_up = 1; bnx2_read_phy(bp, BCM5708S_1000X_STAT1, &val); switch (val & BCM5708S_1000X_STAT1_SPEED_MASK) { case BCM5708S_1000X_STAT1_SPEED_10: bp->line_speed = SPEED_10; break; case BCM5708S_1000X_STAT1_SPEED_100: bp->line_speed = SPEED_100; break; case BCM5708S_1000X_STAT1_SPEED_1G: bp->line_speed = SPEED_1000; break; case BCM5708S_1000X_STAT1_SPEED_2G5: bp->line_speed = SPEED_2500; break; } if (val & BCM5708S_1000X_STAT1_FD) bp->duplex = DUPLEX_FULL; else bp->duplex = DUPLEX_HALF; return 0; } static int bnx2_5706s_linkup(struct bnx2 *bp) { u32 bmcr, local_adv, remote_adv, common; bp->link_up = 1; bp->line_speed = SPEED_1000; bnx2_read_phy(bp, bp->mii_bmcr, &bmcr); if (bmcr & BMCR_FULLDPLX) { bp->duplex = DUPLEX_FULL; } else { bp->duplex = DUPLEX_HALF; } if (!(bmcr & BMCR_ANENABLE)) { return 0; } bnx2_read_phy(bp, bp->mii_adv, &local_adv); bnx2_read_phy(bp, bp->mii_lpa, &remote_adv); common = local_adv & remote_adv; if (common & (ADVERTISE_1000XHALF | ADVERTISE_1000XFULL)) { if (common & ADVERTISE_1000XFULL) { bp->duplex = DUPLEX_FULL; } else { bp->duplex = DUPLEX_HALF; } } return 0; } static int bnx2_copper_linkup(struct bnx2 *bp) { u32 bmcr; bnx2_read_phy(bp, bp->mii_bmcr, &bmcr); if (bmcr & BMCR_ANENABLE) { u32 local_adv, remote_adv, common; bnx2_read_phy(bp, MII_CTRL1000, &local_adv); bnx2_read_phy(bp, MII_STAT1000, &remote_adv); common = local_adv & (remote_adv >> 2); if (common & ADVERTISE_1000FULL) { bp->line_speed = SPEED_1000; bp->duplex = DUPLEX_FULL; } else if (common & ADVERTISE_1000HALF) { bp->line_speed = SPEED_1000; bp->duplex = DUPLEX_HALF; } else { bnx2_read_phy(bp, bp->mii_adv, &local_adv); bnx2_read_phy(bp, bp->mii_lpa, &remote_adv); common = local_adv & remote_adv; if (common & ADVERTISE_100FULL) { bp->line_speed = SPEED_100; bp->duplex = DUPLEX_FULL; } else if (common & ADVERTISE_100HALF) { bp->line_speed = SPEED_100; bp->duplex = DUPLEX_HALF; } else if (common & ADVERTISE_10FULL) { bp->line_speed = SPEED_10; bp->duplex = DUPLEX_FULL; } else if (common & ADVERTISE_10HALF) { bp->line_speed = SPEED_10; bp->duplex = DUPLEX_HALF; } else { bp->line_speed = 0; bp->link_up = 0; } } } else { if (bmcr & BMCR_SPEED100) { bp->line_speed = SPEED_100; } else { bp->line_speed = SPEED_10; } if (bmcr & BMCR_FULLDPLX) { bp->duplex = DUPLEX_FULL; } else { bp->duplex = DUPLEX_HALF; } } return 0; } static void bnx2_init_rx_context(struct bnx2 *bp, u32 cid) { u32 val, rx_cid_addr = GET_CID_ADDR(cid); val = BNX2_L2CTX_CTX_TYPE_CTX_BD_CHN_TYPE_VALUE; val |= BNX2_L2CTX_CTX_TYPE_SIZE_L2; val |= 0x02 << 8; if (bp->flow_ctrl & FLOW_CTRL_TX) val |= BNX2_L2CTX_FLOW_CTRL_ENABLE; bnx2_ctx_wr(bp, rx_cid_addr, BNX2_L2CTX_CTX_TYPE, val); } static void bnx2_init_all_rx_contexts(struct bnx2 *bp) { int i; u32 cid; for (i = 0, cid = RX_CID; i < bp->num_rx_rings; i++, cid++) { if (i == 1) cid = RX_RSS_CID; bnx2_init_rx_context(bp, cid); } } static void bnx2_set_mac_link(struct bnx2 *bp) { u32 val; BNX2_WR(bp, BNX2_EMAC_TX_LENGTHS, 0x2620); if (bp->link_up && (bp->line_speed == SPEED_1000) && (bp->duplex == DUPLEX_HALF)) { BNX2_WR(bp, BNX2_EMAC_TX_LENGTHS, 0x26ff); } /* Configure the EMAC mode register. */ val = BNX2_RD(bp, BNX2_EMAC_MODE); val &= ~(BNX2_EMAC_MODE_PORT | BNX2_EMAC_MODE_HALF_DUPLEX | BNX2_EMAC_MODE_MAC_LOOP | BNX2_EMAC_MODE_FORCE_LINK | BNX2_EMAC_MODE_25G_MODE); if (bp->link_up) { switch (bp->line_speed) { case SPEED_10: if (BNX2_CHIP(bp) != BNX2_CHIP_5706) { val |= BNX2_EMAC_MODE_PORT_MII_10M; break; } /* fall through */ case SPEED_100: val |= BNX2_EMAC_MODE_PORT_MII; break; case SPEED_2500: val |= BNX2_EMAC_MODE_25G_MODE; /* fall through */ case SPEED_1000: val |= BNX2_EMAC_MODE_PORT_GMII; break; } } else { val |= BNX2_EMAC_MODE_PORT_GMII; } /* Set the MAC to operate in the appropriate duplex mode. */ if (bp->duplex == DUPLEX_HALF) val |= BNX2_EMAC_MODE_HALF_DUPLEX; BNX2_WR(bp, BNX2_EMAC_MODE, val); /* Enable/disable rx PAUSE. */ bp->rx_mode &= ~BNX2_EMAC_RX_MODE_FLOW_EN; if (bp->flow_ctrl & FLOW_CTRL_RX) bp->rx_mode |= BNX2_EMAC_RX_MODE_FLOW_EN; BNX2_WR(bp, BNX2_EMAC_RX_MODE, bp->rx_mode); /* Enable/disable tx PAUSE. */ val = BNX2_RD(bp, BNX2_EMAC_TX_MODE); val &= ~BNX2_EMAC_TX_MODE_FLOW_EN; if (bp->flow_ctrl & FLOW_CTRL_TX) val |= BNX2_EMAC_TX_MODE_FLOW_EN; BNX2_WR(bp, BNX2_EMAC_TX_MODE, val); /* Acknowledge the interrupt. */ BNX2_WR(bp, BNX2_EMAC_STATUS, BNX2_EMAC_STATUS_LINK_CHANGE); bnx2_init_all_rx_contexts(bp); } static void bnx2_enable_bmsr1(struct bnx2 *bp) { if ((bp->phy_flags & BNX2_PHY_FLAG_SERDES) && (BNX2_CHIP(bp) == BNX2_CHIP_5709)) bnx2_write_phy(bp, MII_BNX2_BLK_ADDR, MII_BNX2_BLK_ADDR_GP_STATUS); } static void bnx2_disable_bmsr1(struct bnx2 *bp) { if ((bp->phy_flags & BNX2_PHY_FLAG_SERDES) && (BNX2_CHIP(bp) == BNX2_CHIP_5709)) bnx2_write_phy(bp, MII_BNX2_BLK_ADDR, MII_BNX2_BLK_ADDR_COMBO_IEEEB0); } static int bnx2_test_and_enable_2g5(struct bnx2 *bp) { u32 up1; int ret = 1; if (!(bp->phy_flags & BNX2_PHY_FLAG_2_5G_CAPABLE)) return 0; if (bp->autoneg & AUTONEG_SPEED) bp->advertising |= ADVERTISED_2500baseX_Full; if (BNX2_CHIP(bp) == BNX2_CHIP_5709) bnx2_write_phy(bp, MII_BNX2_BLK_ADDR, MII_BNX2_BLK_ADDR_OVER1G); bnx2_read_phy(bp, bp->mii_up1, &up1); if (!(up1 & BCM5708S_UP1_2G5)) { up1 |= BCM5708S_UP1_2G5; bnx2_write_phy(bp, bp->mii_up1, up1); ret = 0; } if (BNX2_CHIP(bp) == BNX2_CHIP_5709) bnx2_write_phy(bp, MII_BNX2_BLK_ADDR, MII_BNX2_BLK_ADDR_COMBO_IEEEB0); return ret; } static int bnx2_test_and_disable_2g5(struct bnx2 *bp) { u32 up1; int ret = 0; if (!(bp->phy_flags & BNX2_PHY_FLAG_2_5G_CAPABLE)) return 0; if (BNX2_CHIP(bp) == BNX2_CHIP_5709) bnx2_write_phy(bp, MII_BNX2_BLK_ADDR, MII_BNX2_BLK_ADDR_OVER1G); bnx2_read_phy(bp, bp->mii_up1, &up1); if (up1 & BCM5708S_UP1_2G5) { up1 &= ~BCM5708S_UP1_2G5; bnx2_write_phy(bp, bp->mii_up1, up1); ret = 1; } if (BNX2_CHIP(bp) == BNX2_CHIP_5709) bnx2_write_phy(bp, MII_BNX2_BLK_ADDR, MII_BNX2_BLK_ADDR_COMBO_IEEEB0); return ret; } static void bnx2_enable_forced_2g5(struct bnx2 *bp) { u32 uninitialized_var(bmcr); int err; if (!(bp->phy_flags & BNX2_PHY_FLAG_2_5G_CAPABLE)) return; if (BNX2_CHIP(bp) == BNX2_CHIP_5709) { u32 val; bnx2_write_phy(bp, MII_BNX2_BLK_ADDR, MII_BNX2_BLK_ADDR_SERDES_DIG); if (!bnx2_read_phy(bp, MII_BNX2_SERDES_DIG_MISC1, &val)) { val &= ~MII_BNX2_SD_MISC1_FORCE_MSK; val |= MII_BNX2_SD_MISC1_FORCE | MII_BNX2_SD_MISC1_FORCE_2_5G; bnx2_write_phy(bp, MII_BNX2_SERDES_DIG_MISC1, val); } bnx2_write_phy(bp, MII_BNX2_BLK_ADDR, MII_BNX2_BLK_ADDR_COMBO_IEEEB0); err = bnx2_read_phy(bp, bp->mii_bmcr, &bmcr); } else if (BNX2_CHIP(bp) == BNX2_CHIP_5708) { err = bnx2_read_phy(bp, bp->mii_bmcr, &bmcr); if (!err) bmcr |= BCM5708S_BMCR_FORCE_2500; } else { return; } if (err) return; if (bp->autoneg & AUTONEG_SPEED) { bmcr &= ~BMCR_ANENABLE; if (bp->req_duplex == DUPLEX_FULL) bmcr |= BMCR_FULLDPLX; } bnx2_write_phy(bp, bp->mii_bmcr, bmcr); } static void bnx2_disable_forced_2g5(struct bnx2 *bp) { u32 uninitialized_var(bmcr); int err; if (!(bp->phy_flags & BNX2_PHY_FLAG_2_5G_CAPABLE)) return; if (BNX2_CHIP(bp) == BNX2_CHIP_5709) { u32 val; bnx2_write_phy(bp, MII_BNX2_BLK_ADDR, MII_BNX2_BLK_ADDR_SERDES_DIG); if (!bnx2_read_phy(bp, MII_BNX2_SERDES_DIG_MISC1, &val)) { val &= ~MII_BNX2_SD_MISC1_FORCE; bnx2_write_phy(bp, MII_BNX2_SERDES_DIG_MISC1, val); } bnx2_write_phy(bp, MII_BNX2_BLK_ADDR, MII_BNX2_BLK_ADDR_COMBO_IEEEB0); err = bnx2_read_phy(bp, bp->mii_bmcr, &bmcr); } else if (BNX2_CHIP(bp) == BNX2_CHIP_5708) { err = bnx2_read_phy(bp, bp->mii_bmcr, &bmcr); if (!err) bmcr &= ~BCM5708S_BMCR_FORCE_2500; } else { return; } if (err) return; if (bp->autoneg & AUTONEG_SPEED) bmcr |= BMCR_SPEED1000 | BMCR_ANENABLE | BMCR_ANRESTART; bnx2_write_phy(bp, bp->mii_bmcr, bmcr); } static void bnx2_5706s_force_link_dn(struct bnx2 *bp, int start) { u32 val; bnx2_write_phy(bp, MII_BNX2_DSP_ADDRESS, MII_EXPAND_SERDES_CTL); bnx2_read_phy(bp, MII_BNX2_DSP_RW_PORT, &val); if (start) bnx2_write_phy(bp, MII_BNX2_DSP_RW_PORT, val & 0xff0f); else bnx2_write_phy(bp, MII_BNX2_DSP_RW_PORT, val | 0xc0); } static int bnx2_set_link(struct bnx2 *bp) { u32 bmsr; u8 link_up; if (bp->loopback == MAC_LOOPBACK || bp->loopback == PHY_LOOPBACK) { bp->link_up = 1; return 0; } if (bp->phy_flags & BNX2_PHY_FLAG_REMOTE_PHY_CAP) return 0; link_up = bp->link_up; bnx2_enable_bmsr1(bp); bnx2_read_phy(bp, bp->mii_bmsr1, &bmsr); bnx2_read_phy(bp, bp->mii_bmsr1, &bmsr); bnx2_disable_bmsr1(bp); if ((bp->phy_flags & BNX2_PHY_FLAG_SERDES) && (BNX2_CHIP(bp) == BNX2_CHIP_5706)) { u32 val, an_dbg; if (bp->phy_flags & BNX2_PHY_FLAG_FORCED_DOWN) { bnx2_5706s_force_link_dn(bp, 0); bp->phy_flags &= ~BNX2_PHY_FLAG_FORCED_DOWN; } val = BNX2_RD(bp, BNX2_EMAC_STATUS); bnx2_write_phy(bp, MII_BNX2_MISC_SHADOW, MISC_SHDW_AN_DBG); bnx2_read_phy(bp, MII_BNX2_MISC_SHADOW, &an_dbg); bnx2_read_phy(bp, MII_BNX2_MISC_SHADOW, &an_dbg); if ((val & BNX2_EMAC_STATUS_LINK) && !(an_dbg & MISC_SHDW_AN_DBG_NOSYNC)) bmsr |= BMSR_LSTATUS; else bmsr &= ~BMSR_LSTATUS; } if (bmsr & BMSR_LSTATUS) { bp->link_up = 1; if (bp->phy_flags & BNX2_PHY_FLAG_SERDES) { if (BNX2_CHIP(bp) == BNX2_CHIP_5706) bnx2_5706s_linkup(bp); else if (BNX2_CHIP(bp) == BNX2_CHIP_5708) bnx2_5708s_linkup(bp); else if (BNX2_CHIP(bp) == BNX2_CHIP_5709) bnx2_5709s_linkup(bp); } else { bnx2_copper_linkup(bp); } bnx2_resolve_flow_ctrl(bp); } else { if ((bp->phy_flags & BNX2_PHY_FLAG_SERDES) && (bp->autoneg & AUTONEG_SPEED)) bnx2_disable_forced_2g5(bp); if (bp->phy_flags & BNX2_PHY_FLAG_PARALLEL_DETECT) { u32 bmcr; bnx2_read_phy(bp, bp->mii_bmcr, &bmcr); bmcr |= BMCR_ANENABLE; bnx2_write_phy(bp, bp->mii_bmcr, bmcr); bp->phy_flags &= ~BNX2_PHY_FLAG_PARALLEL_DETECT; } bp->link_up = 0; } if (bp->link_up != link_up) { bnx2_report_link(bp); } bnx2_set_mac_link(bp); return 0; } static int bnx2_reset_phy(struct bnx2 *bp) { int i; u32 reg; bnx2_write_phy(bp, bp->mii_bmcr, BMCR_RESET); #define PHY_RESET_MAX_WAIT 100 for (i = 0; i < PHY_RESET_MAX_WAIT; i++) { udelay(10); bnx2_read_phy(bp, bp->mii_bmcr, &reg); if (!(reg & BMCR_RESET)) { udelay(20); break; } } if (i == PHY_RESET_MAX_WAIT) { return -EBUSY; } return 0; } static u32 bnx2_phy_get_pause_adv(struct bnx2 *bp) { u32 adv = 0; if ((bp->req_flow_ctrl & (FLOW_CTRL_RX | FLOW_CTRL_TX)) == (FLOW_CTRL_RX | FLOW_CTRL_TX)) { if (bp->phy_flags & BNX2_PHY_FLAG_SERDES) { adv = ADVERTISE_1000XPAUSE; } else { adv = ADVERTISE_PAUSE_CAP; } } else if (bp->req_flow_ctrl & FLOW_CTRL_TX) { if (bp->phy_flags & BNX2_PHY_FLAG_SERDES) { adv = ADVERTISE_1000XPSE_ASYM; } else { adv = ADVERTISE_PAUSE_ASYM; } } else if (bp->req_flow_ctrl & FLOW_CTRL_RX) { if (bp->phy_flags & BNX2_PHY_FLAG_SERDES) { adv = ADVERTISE_1000XPAUSE | ADVERTISE_1000XPSE_ASYM; } else { adv = ADVERTISE_PAUSE_CAP | ADVERTISE_PAUSE_ASYM; } } return adv; } static int bnx2_fw_sync(struct bnx2 *, u32, int, int); static int bnx2_setup_remote_phy(struct bnx2 *bp, u8 port) __releases(&bp->phy_lock) __acquires(&bp->phy_lock) { u32 speed_arg = 0, pause_adv; pause_adv = bnx2_phy_get_pause_adv(bp); if (bp->autoneg & AUTONEG_SPEED) { speed_arg |= BNX2_NETLINK_SET_LINK_ENABLE_AUTONEG; if (bp->advertising & ADVERTISED_10baseT_Half) speed_arg |= BNX2_NETLINK_SET_LINK_SPEED_10HALF; if (bp->advertising & ADVERTISED_10baseT_Full) speed_arg |= BNX2_NETLINK_SET_LINK_SPEED_10FULL; if (bp->advertising & ADVERTISED_100baseT_Half) speed_arg |= BNX2_NETLINK_SET_LINK_SPEED_100HALF; if (bp->advertising & ADVERTISED_100baseT_Full) speed_arg |= BNX2_NETLINK_SET_LINK_SPEED_100FULL; if (bp->advertising & ADVERTISED_1000baseT_Full) speed_arg |= BNX2_NETLINK_SET_LINK_SPEED_1GFULL; if (bp->advertising & ADVERTISED_2500baseX_Full) speed_arg |= BNX2_NETLINK_SET_LINK_SPEED_2G5FULL; } else { if (bp->req_line_speed == SPEED_2500) speed_arg = BNX2_NETLINK_SET_LINK_SPEED_2G5FULL; else if (bp->req_line_speed == SPEED_1000) speed_arg = BNX2_NETLINK_SET_LINK_SPEED_1GFULL; else if (bp->req_line_speed == SPEED_100) { if (bp->req_duplex == DUPLEX_FULL) speed_arg = BNX2_NETLINK_SET_LINK_SPEED_100FULL; else speed_arg = BNX2_NETLINK_SET_LINK_SPEED_100HALF; } else if (bp->req_line_speed == SPEED_10) { if (bp->req_duplex == DUPLEX_FULL) speed_arg = BNX2_NETLINK_SET_LINK_SPEED_10FULL; else speed_arg = BNX2_NETLINK_SET_LINK_SPEED_10HALF; } } if (pause_adv & (ADVERTISE_1000XPAUSE | ADVERTISE_PAUSE_CAP)) speed_arg |= BNX2_NETLINK_SET_LINK_FC_SYM_PAUSE; if (pause_adv & (ADVERTISE_1000XPSE_ASYM | ADVERTISE_PAUSE_ASYM)) speed_arg |= BNX2_NETLINK_SET_LINK_FC_ASYM_PAUSE; if (port == PORT_TP) speed_arg |= BNX2_NETLINK_SET_LINK_PHY_APP_REMOTE | BNX2_NETLINK_SET_LINK_ETH_AT_WIRESPEED; bnx2_shmem_wr(bp, BNX2_DRV_MB_ARG0, speed_arg); spin_unlock_bh(&bp->phy_lock); bnx2_fw_sync(bp, BNX2_DRV_MSG_CODE_CMD_SET_LINK, 1, 0); spin_lock_bh(&bp->phy_lock); return 0; } static int bnx2_setup_serdes_phy(struct bnx2 *bp, u8 port) __releases(&bp->phy_lock) __acquires(&bp->phy_lock) { u32 adv, bmcr; u32 new_adv = 0; if (bp->phy_flags & BNX2_PHY_FLAG_REMOTE_PHY_CAP) return bnx2_setup_remote_phy(bp, port); if (!(bp->autoneg & AUTONEG_SPEED)) { u32 new_bmcr; int force_link_down = 0; if (bp->req_line_speed == SPEED_2500) { if (!bnx2_test_and_enable_2g5(bp)) force_link_down = 1; } else if (bp->req_line_speed == SPEED_1000) { if (bnx2_test_and_disable_2g5(bp)) force_link_down = 1; } bnx2_read_phy(bp, bp->mii_adv, &adv); adv &= ~(ADVERTISE_1000XFULL | ADVERTISE_1000XHALF); bnx2_read_phy(bp, bp->mii_bmcr, &bmcr); new_bmcr = bmcr & ~BMCR_ANENABLE; new_bmcr |= BMCR_SPEED1000; if (BNX2_CHIP(bp) == BNX2_CHIP_5709) { if (bp->req_line_speed == SPEED_2500) bnx2_enable_forced_2g5(bp); else if (bp->req_line_speed == SPEED_1000) { bnx2_disable_forced_2g5(bp); new_bmcr &= ~0x2000; } } else if (BNX2_CHIP(bp) == BNX2_CHIP_5708) { if (bp->req_line_speed == SPEED_2500) new_bmcr |= BCM5708S_BMCR_FORCE_2500; else new_bmcr = bmcr & ~BCM5708S_BMCR_FORCE_2500; } if (bp->req_duplex == DUPLEX_FULL) { adv |= ADVERTISE_1000XFULL; new_bmcr |= BMCR_FULLDPLX; } else { adv |= ADVERTISE_1000XHALF; new_bmcr &= ~BMCR_FULLDPLX; } if ((new_bmcr != bmcr) || (force_link_down)) { /* Force a link down visible on the other side */ if (bp->link_up) { bnx2_write_phy(bp, bp->mii_adv, adv & ~(ADVERTISE_1000XFULL | ADVERTISE_1000XHALF)); bnx2_write_phy(bp, bp->mii_bmcr, bmcr | BMCR_ANRESTART | BMCR_ANENABLE); bp->link_up = 0; netif_carrier_off(bp->dev); bnx2_write_phy(bp, bp->mii_bmcr, new_bmcr); bnx2_report_link(bp); } bnx2_write_phy(bp, bp->mii_adv, adv); bnx2_write_phy(bp, bp->mii_bmcr, new_bmcr); } else { bnx2_resolve_flow_ctrl(bp); bnx2_set_mac_link(bp); } return 0; } bnx2_test_and_enable_2g5(bp); if (bp->advertising & ADVERTISED_1000baseT_Full) new_adv |= ADVERTISE_1000XFULL; new_adv |= bnx2_phy_get_pause_adv(bp); bnx2_read_phy(bp, bp->mii_adv, &adv); bnx2_read_phy(bp, bp->mii_bmcr, &bmcr); bp->serdes_an_pending = 0; if ((adv != new_adv) || ((bmcr & BMCR_ANENABLE) == 0)) { /* Force a link down visible on the other side */ if (bp->link_up) { bnx2_write_phy(bp, bp->mii_bmcr, BMCR_LOOPBACK); spin_unlock_bh(&bp->phy_lock); bnx2_msleep(20); spin_lock_bh(&bp->phy_lock); } bnx2_write_phy(bp, bp->mii_adv, new_adv); bnx2_write_phy(bp, bp->mii_bmcr, bmcr | BMCR_ANRESTART | BMCR_ANENABLE); /* Speed up link-up time when the link partner * does not autonegotiate which is very common * in blade servers. Some blade servers use * IPMI for kerboard input and it's important * to minimize link disruptions. Autoneg. involves * exchanging base pages plus 3 next pages and * normally completes in about 120 msec. */ bp->current_interval = BNX2_SERDES_AN_TIMEOUT; bp->serdes_an_pending = 1; mod_timer(&bp->timer, jiffies + bp->current_interval); } else { bnx2_resolve_flow_ctrl(bp); bnx2_set_mac_link(bp); } return 0; } #define ETHTOOL_ALL_FIBRE_SPEED \ (bp->phy_flags & BNX2_PHY_FLAG_2_5G_CAPABLE) ? \ (ADVERTISED_2500baseX_Full | ADVERTISED_1000baseT_Full) :\ (ADVERTISED_1000baseT_Full) #define ETHTOOL_ALL_COPPER_SPEED \ (ADVERTISED_10baseT_Half | ADVERTISED_10baseT_Full | \ ADVERTISED_100baseT_Half | ADVERTISED_100baseT_Full | \ ADVERTISED_1000baseT_Full) #define PHY_ALL_10_100_SPEED (ADVERTISE_10HALF | ADVERTISE_10FULL | \ ADVERTISE_100HALF | ADVERTISE_100FULL | ADVERTISE_CSMA) #define PHY_ALL_1000_SPEED (ADVERTISE_1000HALF | ADVERTISE_1000FULL) static void bnx2_set_default_remote_link(struct bnx2 *bp) { u32 link; if (bp->phy_port == PORT_TP) link = bnx2_shmem_rd(bp, BNX2_RPHY_COPPER_LINK); else link = bnx2_shmem_rd(bp, BNX2_RPHY_SERDES_LINK); if (link & BNX2_NETLINK_SET_LINK_ENABLE_AUTONEG) { bp->req_line_speed = 0; bp->autoneg |= AUTONEG_SPEED; bp->advertising = ADVERTISED_Autoneg; if (link & BNX2_NETLINK_SET_LINK_SPEED_10HALF) bp->advertising |= ADVERTISED_10baseT_Half; if (link & BNX2_NETLINK_SET_LINK_SPEED_10FULL) bp->advertising |= ADVERTISED_10baseT_Full; if (link & BNX2_NETLINK_SET_LINK_SPEED_100HALF) bp->advertising |= ADVERTISED_100baseT_Half; if (link & BNX2_NETLINK_SET_LINK_SPEED_100FULL) bp->advertising |= ADVERTISED_100baseT_Full; if (link & BNX2_NETLINK_SET_LINK_SPEED_1GFULL) bp->advertising |= ADVERTISED_1000baseT_Full; if (link & BNX2_NETLINK_SET_LINK_SPEED_2G5FULL) bp->advertising |= ADVERTISED_2500baseX_Full; } else { bp->autoneg = 0; bp->advertising = 0; bp->req_duplex = DUPLEX_FULL; if (link & BNX2_NETLINK_SET_LINK_SPEED_10) { bp->req_line_speed = SPEED_10; if (link & BNX2_NETLINK_SET_LINK_SPEED_10HALF) bp->req_duplex = DUPLEX_HALF; } if (link & BNX2_NETLINK_SET_LINK_SPEED_100) { bp->req_line_speed = SPEED_100; if (link & BNX2_NETLINK_SET_LINK_SPEED_100HALF) bp->req_duplex = DUPLEX_HALF; } if (link & BNX2_NETLINK_SET_LINK_SPEED_1GFULL) bp->req_line_speed = SPEED_1000; if (link & BNX2_NETLINK_SET_LINK_SPEED_2G5FULL) bp->req_line_speed = SPEED_2500; } } static void bnx2_set_default_link(struct bnx2 *bp) { if (bp->phy_flags & BNX2_PHY_FLAG_REMOTE_PHY_CAP) { bnx2_set_default_remote_link(bp); return; } bp->autoneg = AUTONEG_SPEED | AUTONEG_FLOW_CTRL; bp->req_line_speed = 0; if (bp->phy_flags & BNX2_PHY_FLAG_SERDES) { u32 reg; bp->advertising = ETHTOOL_ALL_FIBRE_SPEED | ADVERTISED_Autoneg; reg = bnx2_shmem_rd(bp, BNX2_PORT_HW_CFG_CONFIG); reg &= BNX2_PORT_HW_CFG_CFG_DFLT_LINK_MASK; if (reg == BNX2_PORT_HW_CFG_CFG_DFLT_LINK_1G) { bp->autoneg = 0; bp->req_line_speed = bp->line_speed = SPEED_1000; bp->req_duplex = DUPLEX_FULL; } } else bp->advertising = ETHTOOL_ALL_COPPER_SPEED | ADVERTISED_Autoneg; } static void bnx2_send_heart_beat(struct bnx2 *bp) { u32 msg; u32 addr; spin_lock(&bp->indirect_lock); msg = (u32) (++bp->fw_drv_pulse_wr_seq & BNX2_DRV_PULSE_SEQ_MASK); addr = bp->shmem_base + BNX2_DRV_PULSE_MB; BNX2_WR(bp, BNX2_PCICFG_REG_WINDOW_ADDRESS, addr); BNX2_WR(bp, BNX2_PCICFG_REG_WINDOW, msg); spin_unlock(&bp->indirect_lock); } static void bnx2_remote_phy_event(struct bnx2 *bp) { u32 msg; u8 link_up = bp->link_up; u8 old_port; msg = bnx2_shmem_rd(bp, BNX2_LINK_STATUS); if (msg & BNX2_LINK_STATUS_HEART_BEAT_EXPIRED) bnx2_send_heart_beat(bp); msg &= ~BNX2_LINK_STATUS_HEART_BEAT_EXPIRED; if ((msg & BNX2_LINK_STATUS_LINK_UP) == BNX2_LINK_STATUS_LINK_DOWN) bp->link_up = 0; else { u32 speed; bp->link_up = 1; speed = msg & BNX2_LINK_STATUS_SPEED_MASK; bp->duplex = DUPLEX_FULL; switch (speed) { case BNX2_LINK_STATUS_10HALF: bp->duplex = DUPLEX_HALF; /* fall through */ case BNX2_LINK_STATUS_10FULL: bp->line_speed = SPEED_10; break; case BNX2_LINK_STATUS_100HALF: bp->duplex = DUPLEX_HALF; /* fall through */ case BNX2_LINK_STATUS_100BASE_T4: /* fall through */ case BNX2_LINK_STATUS_100FULL: bp->line_speed = SPEED_100; break; case BNX2_LINK_STATUS_1000HALF: bp->duplex = DUPLEX_HALF; /* fall through */ case BNX2_LINK_STATUS_1000FULL: bp->line_speed = SPEED_1000; break; case BNX2_LINK_STATUS_2500HALF: bp->duplex = DUPLEX_HALF; /* fall through */ case BNX2_LINK_STATUS_2500FULL: bp->line_speed = SPEED_2500; break; default: bp->line_speed = 0; break; } bp->flow_ctrl = 0; if ((bp->autoneg & (AUTONEG_SPEED | AUTONEG_FLOW_CTRL)) != (AUTONEG_SPEED | AUTONEG_FLOW_CTRL)) { if (bp->duplex == DUPLEX_FULL) bp->flow_ctrl = bp->req_flow_ctrl; } else { if (msg & BNX2_LINK_STATUS_TX_FC_ENABLED) bp->flow_ctrl |= FLOW_CTRL_TX; if (msg & BNX2_LINK_STATUS_RX_FC_ENABLED) bp->flow_ctrl |= FLOW_CTRL_RX; } old_port = bp->phy_port; if (msg & BNX2_LINK_STATUS_SERDES_LINK) bp->phy_port = PORT_FIBRE; else bp->phy_port = PORT_TP; if (old_port != bp->phy_port) bnx2_set_default_link(bp); } if (bp->link_up != link_up) bnx2_report_link(bp); bnx2_set_mac_link(bp); } static int bnx2_set_remote_link(struct bnx2 *bp) { u32 evt_code; spin_lock(&bp->indirect_lock); BNX2_WR(bp, BNX2_PCICFG_REG_WINDOW_ADDRESS, bp->shmem_base + BNX2_FW_EVT_CODE_MB); evt_code = BNX2_RD(bp, BNX2_PCICFG_REG_WINDOW); spin_unlock(&bp->indirect_lock); switch (evt_code) { case BNX2_FW_EVT_CODE_LINK_EVENT: bnx2_remote_phy_event(bp); break; case BNX2_FW_EVT_CODE_SW_TIMER_EXPIRATION_EVENT: default: bnx2_send_heart_beat(bp); break; } return 0; } static int bnx2_setup_copper_phy(struct bnx2 *bp) __releases(&bp->phy_lock) __acquires(&bp->phy_lock) { u32 bmcr; u32 new_bmcr; bnx2_read_phy(bp, bp->mii_bmcr, &bmcr); if (bp->autoneg & AUTONEG_SPEED) { u32 adv_reg, adv1000_reg; u32 new_adv = 0; u32 new_adv1000 = 0; bnx2_read_phy(bp, bp->mii_adv, &adv_reg); adv_reg &= (PHY_ALL_10_100_SPEED | ADVERTISE_PAUSE_CAP | ADVERTISE_PAUSE_ASYM); bnx2_read_phy(bp, MII_CTRL1000, &adv1000_reg); adv1000_reg &= PHY_ALL_1000_SPEED; new_adv = ethtool_adv_to_mii_adv_t(bp->advertising); new_adv |= ADVERTISE_CSMA; new_adv |= bnx2_phy_get_pause_adv(bp); new_adv1000 |= ethtool_adv_to_mii_ctrl1000_t(bp->advertising); if ((adv1000_reg != new_adv1000) || (adv_reg != new_adv) || ((bmcr & BMCR_ANENABLE) == 0)) { bnx2_write_phy(bp, bp->mii_adv, new_adv); bnx2_write_phy(bp, MII_CTRL1000, new_adv1000); bnx2_write_phy(bp, bp->mii_bmcr, BMCR_ANRESTART | BMCR_ANENABLE); } else if (bp->link_up) { /* Flow ctrl may have changed from auto to forced */ /* or vice-versa. */ bnx2_resolve_flow_ctrl(bp); bnx2_set_mac_link(bp); } return 0; } new_bmcr = 0; if (bp->req_line_speed == SPEED_100) { new_bmcr |= BMCR_SPEED100; } if (bp->req_duplex == DUPLEX_FULL) { new_bmcr |= BMCR_FULLDPLX; } if (new_bmcr != bmcr) { u32 bmsr; bnx2_read_phy(bp, bp->mii_bmsr, &bmsr); bnx2_read_phy(bp, bp->mii_bmsr, &bmsr); if (bmsr & BMSR_LSTATUS) { /* Force link down */ bnx2_write_phy(bp, bp->mii_bmcr, BMCR_LOOPBACK); spin_unlock_bh(&bp->phy_lock); bnx2_msleep(50); spin_lock_bh(&bp->phy_lock); bnx2_read_phy(bp, bp->mii_bmsr, &bmsr); bnx2_read_phy(bp, bp->mii_bmsr, &bmsr); } bnx2_write_phy(bp, bp->mii_bmcr, new_bmcr); /* Normally, the new speed is setup after the link has * gone down and up again. In some cases, link will not go * down so we need to set up the new speed here. */ if (bmsr & BMSR_LSTATUS) { bp->line_speed = bp->req_line_speed; bp->duplex = bp->req_duplex; bnx2_resolve_flow_ctrl(bp); bnx2_set_mac_link(bp); } } else { bnx2_resolve_flow_ctrl(bp); bnx2_set_mac_link(bp); } return 0; } static int bnx2_setup_phy(struct bnx2 *bp, u8 port) __releases(&bp->phy_lock) __acquires(&bp->phy_lock) { if (bp->loopback == MAC_LOOPBACK) return 0; if (bp->phy_flags & BNX2_PHY_FLAG_SERDES) { return bnx2_setup_serdes_phy(bp, port); } else { return bnx2_setup_copper_phy(bp); } } static int bnx2_init_5709s_phy(struct bnx2 *bp, int reset_phy) { u32 val; bp->mii_bmcr = MII_BMCR + 0x10; bp->mii_bmsr = MII_BMSR + 0x10; bp->mii_bmsr1 = MII_BNX2_GP_TOP_AN_STATUS1; bp->mii_adv = MII_ADVERTISE + 0x10; bp->mii_lpa = MII_LPA + 0x10; bp->mii_up1 = MII_BNX2_OVER1G_UP1; bnx2_write_phy(bp, MII_BNX2_BLK_ADDR, MII_BNX2_BLK_ADDR_AER); bnx2_write_phy(bp, MII_BNX2_AER_AER, MII_BNX2_AER_AER_AN_MMD); bnx2_write_phy(bp, MII_BNX2_BLK_ADDR, MII_BNX2_BLK_ADDR_COMBO_IEEEB0); if (reset_phy) bnx2_reset_phy(bp); bnx2_write_phy(bp, MII_BNX2_BLK_ADDR, MII_BNX2_BLK_ADDR_SERDES_DIG); bnx2_read_phy(bp, MII_BNX2_SERDES_DIG_1000XCTL1, &val); val &= ~MII_BNX2_SD_1000XCTL1_AUTODET; val |= MII_BNX2_SD_1000XCTL1_FIBER; /* NEMO temp. FIX */ if (bnx2_shmem_rd(bp, BNX2_SHARED_HW_CFG_CONFIG) & 0x80000000) val |= (1 << 3); bnx2_write_phy(bp, MII_BNX2_SERDES_DIG_1000XCTL1, val); bnx2_write_phy(bp, MII_BNX2_BLK_ADDR, MII_BNX2_BLK_ADDR_OVER1G); bnx2_read_phy(bp, MII_BNX2_OVER1G_UP1, &val); if (bp->phy_flags & BNX2_PHY_FLAG_2_5G_CAPABLE) val |= BCM5708S_UP1_2G5; else val &= ~BCM5708S_UP1_2G5; bnx2_write_phy(bp, MII_BNX2_OVER1G_UP1, val); bnx2_write_phy(bp, MII_BNX2_BLK_ADDR, MII_BNX2_BLK_ADDR_BAM_NXTPG); bnx2_read_phy(bp, MII_BNX2_BAM_NXTPG_CTL, &val); val |= MII_BNX2_NXTPG_CTL_T2 | MII_BNX2_NXTPG_CTL_BAM; bnx2_write_phy(bp, MII_BNX2_BAM_NXTPG_CTL, val); bnx2_write_phy(bp, MII_BNX2_BLK_ADDR, MII_BNX2_BLK_ADDR_CL73_USERB0); val = MII_BNX2_CL73_BAM_EN | MII_BNX2_CL73_BAM_STA_MGR_EN | MII_BNX2_CL73_BAM_NP_AFT_BP_EN; bnx2_write_phy(bp, MII_BNX2_CL73_BAM_CTL1, val); bnx2_write_phy(bp, MII_BNX2_BLK_ADDR, MII_BNX2_BLK_ADDR_COMBO_IEEEB0); return 0; } static int bnx2_init_5708s_phy(struct bnx2 *bp, int reset_phy) { u32 val; if (reset_phy) bnx2_reset_phy(bp); bp->mii_up1 = BCM5708S_UP1; bnx2_write_phy(bp, BCM5708S_BLK_ADDR, BCM5708S_BLK_ADDR_DIG3); bnx2_write_phy(bp, BCM5708S_DIG_3_0, BCM5708S_DIG_3_0_USE_IEEE); bnx2_write_phy(bp, BCM5708S_BLK_ADDR, BCM5708S_BLK_ADDR_DIG); bnx2_read_phy(bp, BCM5708S_1000X_CTL1, &val); val |= BCM5708S_1000X_CTL1_FIBER_MODE | BCM5708S_1000X_CTL1_AUTODET_EN; bnx2_write_phy(bp, BCM5708S_1000X_CTL1, val); bnx2_read_phy(bp, BCM5708S_1000X_CTL2, &val); val |= BCM5708S_1000X_CTL2_PLLEL_DET_EN; bnx2_write_phy(bp, BCM5708S_1000X_CTL2, val); if (bp->phy_flags & BNX2_PHY_FLAG_2_5G_CAPABLE) { bnx2_read_phy(bp, BCM5708S_UP1, &val); val |= BCM5708S_UP1_2G5; bnx2_write_phy(bp, BCM5708S_UP1, val); } if ((BNX2_CHIP_ID(bp) == BNX2_CHIP_ID_5708_A0) || (BNX2_CHIP_ID(bp) == BNX2_CHIP_ID_5708_B0) || (BNX2_CHIP_ID(bp) == BNX2_CHIP_ID_5708_B1)) { /* increase tx signal amplitude */ bnx2_write_phy(bp, BCM5708S_BLK_ADDR, BCM5708S_BLK_ADDR_TX_MISC); bnx2_read_phy(bp, BCM5708S_TX_ACTL1, &val); val &= ~BCM5708S_TX_ACTL1_DRIVER_VCM; bnx2_write_phy(bp, BCM5708S_TX_ACTL1, val); bnx2_write_phy(bp, BCM5708S_BLK_ADDR, BCM5708S_BLK_ADDR_DIG); } val = bnx2_shmem_rd(bp, BNX2_PORT_HW_CFG_CONFIG) & BNX2_PORT_HW_CFG_CFG_TXCTL3_MASK; if (val) { u32 is_backplane; is_backplane = bnx2_shmem_rd(bp, BNX2_SHARED_HW_CFG_CONFIG); if (is_backplane & BNX2_SHARED_HW_CFG_PHY_BACKPLANE) { bnx2_write_phy(bp, BCM5708S_BLK_ADDR, BCM5708S_BLK_ADDR_TX_MISC); bnx2_write_phy(bp, BCM5708S_TX_ACTL3, val); bnx2_write_phy(bp, BCM5708S_BLK_ADDR, BCM5708S_BLK_ADDR_DIG); } } return 0; } static int bnx2_init_5706s_phy(struct bnx2 *bp, int reset_phy) { if (reset_phy) bnx2_reset_phy(bp); bp->phy_flags &= ~BNX2_PHY_FLAG_PARALLEL_DETECT; if (BNX2_CHIP(bp) == BNX2_CHIP_5706) BNX2_WR(bp, BNX2_MISC_GP_HW_CTL0, 0x300); if (bp->dev->mtu > 1500) { u32 val; /* Set extended packet length bit */ bnx2_write_phy(bp, 0x18, 0x7); bnx2_read_phy(bp, 0x18, &val); bnx2_write_phy(bp, 0x18, (val & 0xfff8) | 0x4000); bnx2_write_phy(bp, 0x1c, 0x6c00); bnx2_read_phy(bp, 0x1c, &val); bnx2_write_phy(bp, 0x1c, (val & 0x3ff) | 0xec02); } else { u32 val; bnx2_write_phy(bp, 0x18, 0x7); bnx2_read_phy(bp, 0x18, &val); bnx2_write_phy(bp, 0x18, val & ~0x4007); bnx2_write_phy(bp, 0x1c, 0x6c00); bnx2_read_phy(bp, 0x1c, &val); bnx2_write_phy(bp, 0x1c, (val & 0x3fd) | 0xec00); } return 0; } static int bnx2_init_copper_phy(struct bnx2 *bp, int reset_phy) { u32 val; if (reset_phy) bnx2_reset_phy(bp); if (bp->phy_flags & BNX2_PHY_FLAG_CRC_FIX) { bnx2_write_phy(bp, 0x18, 0x0c00); bnx2_write_phy(bp, 0x17, 0x000a); bnx2_write_phy(bp, 0x15, 0x310b); bnx2_write_phy(bp, 0x17, 0x201f); bnx2_write_phy(bp, 0x15, 0x9506); bnx2_write_phy(bp, 0x17, 0x401f); bnx2_write_phy(bp, 0x15, 0x14e2); bnx2_write_phy(bp, 0x18, 0x0400); } if (bp->phy_flags & BNX2_PHY_FLAG_DIS_EARLY_DAC) { bnx2_write_phy(bp, MII_BNX2_DSP_ADDRESS, MII_BNX2_DSP_EXPAND_REG | 0x8); bnx2_read_phy(bp, MII_BNX2_DSP_RW_PORT, &val); val &= ~(1 << 8); bnx2_write_phy(bp, MII_BNX2_DSP_RW_PORT, val); } if (bp->dev->mtu > 1500) { /* Set extended packet length bit */ bnx2_write_phy(bp, 0x18, 0x7); bnx2_read_phy(bp, 0x18, &val); bnx2_write_phy(bp, 0x18, val | 0x4000); bnx2_read_phy(bp, 0x10, &val); bnx2_write_phy(bp, 0x10, val | 0x1); } else { bnx2_write_phy(bp, 0x18, 0x7); bnx2_read_phy(bp, 0x18, &val); bnx2_write_phy(bp, 0x18, val & ~0x4007); bnx2_read_phy(bp, 0x10, &val); bnx2_write_phy(bp, 0x10, val & ~0x1); } /* ethernet@wirespeed & auto-mdix*/ bnx2_write_phy(bp, 0x18, 0x7007); bnx2_read_phy(bp, 0x18, &val); bnx2_write_phy(bp, 0x18, val | (1 << 15) | (1 << 4) | (1 << 9)); return 0; } static int bnx2_init_phy(struct bnx2 *bp, int reset_phy) __releases(&bp->phy_lock) __acquires(&bp->phy_lock) { u32 val; int rc = 0; bp->phy_flags &= ~BNX2_PHY_FLAG_INT_MODE_MASK; bp->phy_flags |= BNX2_PHY_FLAG_INT_MODE_LINK_READY; bp->mii_bmcr = MII_BMCR; bp->mii_bmsr = MII_BMSR; bp->mii_bmsr1 = MII_BMSR; bp->mii_adv = MII_ADVERTISE; bp->mii_lpa = MII_LPA; BNX2_WR(bp, BNX2_EMAC_ATTENTION_ENA, BNX2_EMAC_ATTENTION_ENA_LINK); if (bp->phy_flags & BNX2_PHY_FLAG_REMOTE_PHY_CAP) goto setup_phy; bnx2_read_phy(bp, MII_PHYSID1, &val); bp->phy_id = val << 16; bnx2_read_phy(bp, MII_PHYSID2, &val); bp->phy_id |= val & 0xffff; if (bp->phy_flags & BNX2_PHY_FLAG_SERDES) { if (BNX2_CHIP(bp) == BNX2_CHIP_5706) rc = bnx2_init_5706s_phy(bp, reset_phy); else if (BNX2_CHIP(bp) == BNX2_CHIP_5708) rc = bnx2_init_5708s_phy(bp, reset_phy); else if (BNX2_CHIP(bp) == BNX2_CHIP_5709) rc = bnx2_init_5709s_phy(bp, reset_phy); } else { rc = bnx2_init_copper_phy(bp, reset_phy); } setup_phy: if (!rc) rc = bnx2_setup_phy(bp, bp->phy_port); return rc; } static int bnx2_set_mac_loopback(struct bnx2 *bp) { u32 mac_mode; mac_mode = BNX2_RD(bp, BNX2_EMAC_MODE); mac_mode &= ~BNX2_EMAC_MODE_PORT; mac_mode |= BNX2_EMAC_MODE_MAC_LOOP | BNX2_EMAC_MODE_FORCE_LINK; BNX2_WR(bp, BNX2_EMAC_MODE, mac_mode); bp->link_up = 1; return 0; } static int bnx2_test_link(struct bnx2 *); static int bnx2_set_phy_loopback(struct bnx2 *bp) { u32 mac_mode; int rc, i; spin_lock_bh(&bp->phy_lock); rc = bnx2_write_phy(bp, bp->mii_bmcr, BMCR_LOOPBACK | BMCR_FULLDPLX | BMCR_SPEED1000); spin_unlock_bh(&bp->phy_lock); if (rc) return rc; for (i = 0; i < 10; i++) { if (bnx2_test_link(bp) == 0) break; bnx2_msleep(100); } mac_mode = BNX2_RD(bp, BNX2_EMAC_MODE); mac_mode &= ~(BNX2_EMAC_MODE_PORT | BNX2_EMAC_MODE_HALF_DUPLEX | BNX2_EMAC_MODE_MAC_LOOP | BNX2_EMAC_MODE_FORCE_LINK | BNX2_EMAC_MODE_25G_MODE); mac_mode |= BNX2_EMAC_MODE_PORT_GMII; BNX2_WR(bp, BNX2_EMAC_MODE, mac_mode); bp->link_up = 1; return 0; } static void bnx2_dump_mcp_state(struct bnx2 *bp) { struct net_device *dev = bp->dev; u32 mcp_p0, mcp_p1; netdev_err(dev, "<--- start MCP states dump --->\n"); if (BNX2_CHIP(bp) == BNX2_CHIP_5709) { mcp_p0 = BNX2_MCP_STATE_P0; mcp_p1 = BNX2_MCP_STATE_P1; } else { mcp_p0 = BNX2_MCP_STATE_P0_5708; mcp_p1 = BNX2_MCP_STATE_P1_5708; } netdev_err(dev, "DEBUG: MCP_STATE_P0[%08x] MCP_STATE_P1[%08x]\n", bnx2_reg_rd_ind(bp, mcp_p0), bnx2_reg_rd_ind(bp, mcp_p1)); netdev_err(dev, "DEBUG: MCP mode[%08x] state[%08x] evt_mask[%08x]\n", bnx2_reg_rd_ind(bp, BNX2_MCP_CPU_MODE), bnx2_reg_rd_ind(bp, BNX2_MCP_CPU_STATE), bnx2_reg_rd_ind(bp, BNX2_MCP_CPU_EVENT_MASK)); netdev_err(dev, "DEBUG: pc[%08x] pc[%08x] instr[%08x]\n", bnx2_reg_rd_ind(bp, BNX2_MCP_CPU_PROGRAM_COUNTER), bnx2_reg_rd_ind(bp, BNX2_MCP_CPU_PROGRAM_COUNTER), bnx2_reg_rd_ind(bp, BNX2_MCP_CPU_INSTRUCTION)); netdev_err(dev, "DEBUG: shmem states:\n"); netdev_err(dev, "DEBUG: drv_mb[%08x] fw_mb[%08x] link_status[%08x]", bnx2_shmem_rd(bp, BNX2_DRV_MB), bnx2_shmem_rd(bp, BNX2_FW_MB), bnx2_shmem_rd(bp, BNX2_LINK_STATUS)); pr_cont(" drv_pulse_mb[%08x]\n", bnx2_shmem_rd(bp, BNX2_DRV_PULSE_MB)); netdev_err(dev, "DEBUG: dev_info_signature[%08x] reset_type[%08x]", bnx2_shmem_rd(bp, BNX2_DEV_INFO_SIGNATURE), bnx2_shmem_rd(bp, BNX2_BC_STATE_RESET_TYPE)); pr_cont(" condition[%08x]\n", bnx2_shmem_rd(bp, BNX2_BC_STATE_CONDITION)); DP_SHMEM_LINE(bp, BNX2_BC_STATE_RESET_TYPE); DP_SHMEM_LINE(bp, 0x3cc); DP_SHMEM_LINE(bp, 0x3dc); DP_SHMEM_LINE(bp, 0x3ec); netdev_err(dev, "DEBUG: 0x3fc[%08x]\n", bnx2_shmem_rd(bp, 0x3fc)); netdev_err(dev, "<--- end MCP states dump --->\n"); } static int bnx2_fw_sync(struct bnx2 *bp, u32 msg_data, int ack, int silent) { int i; u32 val; bp->fw_wr_seq++; msg_data |= bp->fw_wr_seq; bnx2_shmem_wr(bp, BNX2_DRV_MB, msg_data); if (!ack) return 0; /* wait for an acknowledgement. */ for (i = 0; i < (BNX2_FW_ACK_TIME_OUT_MS / 10); i++) { bnx2_msleep(10); val = bnx2_shmem_rd(bp, BNX2_FW_MB); if ((val & BNX2_FW_MSG_ACK) == (msg_data & BNX2_DRV_MSG_SEQ)) break; } if ((msg_data & BNX2_DRV_MSG_DATA) == BNX2_DRV_MSG_DATA_WAIT0) return 0; /* If we timed out, inform the firmware that this is the case. */ if ((val & BNX2_FW_MSG_ACK) != (msg_data & BNX2_DRV_MSG_SEQ)) { msg_data &= ~BNX2_DRV_MSG_CODE; msg_data |= BNX2_DRV_MSG_CODE_FW_TIMEOUT; bnx2_shmem_wr(bp, BNX2_DRV_MB, msg_data); if (!silent) { pr_err("fw sync timeout, reset code = %x\n", msg_data); bnx2_dump_mcp_state(bp); } return -EBUSY; } if ((val & BNX2_FW_MSG_STATUS_MASK) != BNX2_FW_MSG_STATUS_OK) return -EIO; return 0; } static int bnx2_init_5709_context(struct bnx2 *bp) { int i, ret = 0; u32 val; val = BNX2_CTX_COMMAND_ENABLED | BNX2_CTX_COMMAND_MEM_INIT | (1 << 12); val |= (BNX2_PAGE_BITS - 8) << 16; BNX2_WR(bp, BNX2_CTX_COMMAND, val); for (i = 0; i < 10; i++) { val = BNX2_RD(bp, BNX2_CTX_COMMAND); if (!(val & BNX2_CTX_COMMAND_MEM_INIT)) break; udelay(2); } if (val & BNX2_CTX_COMMAND_MEM_INIT) return -EBUSY; for (i = 0; i < bp->ctx_pages; i++) { int j; if (bp->ctx_blk[i]) memset(bp->ctx_blk[i], 0, BNX2_PAGE_SIZE); else return -ENOMEM; BNX2_WR(bp, BNX2_CTX_HOST_PAGE_TBL_DATA0, (bp->ctx_blk_mapping[i] & 0xffffffff) | BNX2_CTX_HOST_PAGE_TBL_DATA0_VALID); BNX2_WR(bp, BNX2_CTX_HOST_PAGE_TBL_DATA1, (u64) bp->ctx_blk_mapping[i] >> 32); BNX2_WR(bp, BNX2_CTX_HOST_PAGE_TBL_CTRL, i | BNX2_CTX_HOST_PAGE_TBL_CTRL_WRITE_REQ); for (j = 0; j < 10; j++) { val = BNX2_RD(bp, BNX2_CTX_HOST_PAGE_TBL_CTRL); if (!(val & BNX2_CTX_HOST_PAGE_TBL_CTRL_WRITE_REQ)) break; udelay(5); } if (val & BNX2_CTX_HOST_PAGE_TBL_CTRL_WRITE_REQ) { ret = -EBUSY; break; } } return ret; } static void bnx2_init_context(struct bnx2 *bp) { u32 vcid; vcid = 96; while (vcid) { u32 vcid_addr, pcid_addr, offset; int i; vcid--; if (BNX2_CHIP_ID(bp) == BNX2_CHIP_ID_5706_A0) { u32 new_vcid; vcid_addr = GET_PCID_ADDR(vcid); if (vcid & 0x8) { new_vcid = 0x60 + (vcid & 0xf0) + (vcid & 0x7); } else { new_vcid = vcid; } pcid_addr = GET_PCID_ADDR(new_vcid); } else { vcid_addr = GET_CID_ADDR(vcid); pcid_addr = vcid_addr; } for (i = 0; i < (CTX_SIZE / PHY_CTX_SIZE); i++) { vcid_addr += (i << PHY_CTX_SHIFT); pcid_addr += (i << PHY_CTX_SHIFT); BNX2_WR(bp, BNX2_CTX_VIRT_ADDR, vcid_addr); BNX2_WR(bp, BNX2_CTX_PAGE_TBL, pcid_addr); /* Zero out the context. */ for (offset = 0; offset < PHY_CTX_SIZE; offset += 4) bnx2_ctx_wr(bp, vcid_addr, offset, 0); } } } static int bnx2_alloc_bad_rbuf(struct bnx2 *bp) { u16 *good_mbuf; u32 good_mbuf_cnt; u32 val; good_mbuf = kmalloc(512 * sizeof(u16), GFP_KERNEL); if (good_mbuf == NULL) return -ENOMEM; BNX2_WR(bp, BNX2_MISC_ENABLE_SET_BITS, BNX2_MISC_ENABLE_SET_BITS_RX_MBUF_ENABLE); good_mbuf_cnt = 0; /* Allocate a bunch of mbufs and save the good ones in an array. */ val = bnx2_reg_rd_ind(bp, BNX2_RBUF_STATUS1); while (val & BNX2_RBUF_STATUS1_FREE_COUNT) { bnx2_reg_wr_ind(bp, BNX2_RBUF_COMMAND, BNX2_RBUF_COMMAND_ALLOC_REQ); val = bnx2_reg_rd_ind(bp, BNX2_RBUF_FW_BUF_ALLOC); val &= BNX2_RBUF_FW_BUF_ALLOC_VALUE; /* The addresses with Bit 9 set are bad memory blocks. */ if (!(val & (1 << 9))) { good_mbuf[good_mbuf_cnt] = (u16) val; good_mbuf_cnt++; } val = bnx2_reg_rd_ind(bp, BNX2_RBUF_STATUS1); } /* Free the good ones back to the mbuf pool thus discarding * all the bad ones. */ while (good_mbuf_cnt) { good_mbuf_cnt--; val = good_mbuf[good_mbuf_cnt]; val = (val << 9) | val | 1; bnx2_reg_wr_ind(bp, BNX2_RBUF_FW_BUF_FREE, val); } kfree(good_mbuf); return 0; } static void bnx2_set_mac_addr(struct bnx2 *bp, u8 *mac_addr, u32 pos) { u32 val; val = (mac_addr[0] << 8) | mac_addr[1]; BNX2_WR(bp, BNX2_EMAC_MAC_MATCH0 + (pos * 8), val); val = (mac_addr[2] << 24) | (mac_addr[3] << 16) | (mac_addr[4] << 8) | mac_addr[5]; BNX2_WR(bp, BNX2_EMAC_MAC_MATCH1 + (pos * 8), val); } static inline int bnx2_alloc_rx_page(struct bnx2 *bp, struct bnx2_rx_ring_info *rxr, u16 index, gfp_t gfp) { dma_addr_t mapping; struct bnx2_sw_pg *rx_pg = &rxr->rx_pg_ring[index]; struct bnx2_rx_bd *rxbd = &rxr->rx_pg_desc_ring[BNX2_RX_RING(index)][BNX2_RX_IDX(index)]; struct page *page = alloc_page(gfp); if (!page) return -ENOMEM; #if (LINUX_VERSION_CODE >= 0x02061b) mapping = dma_map_page(&bp->pdev->dev, page, 0, PAGE_SIZE, PCI_DMA_FROMDEVICE); if (dma_mapping_error(&bp->pdev->dev, mapping)) { #else mapping = pci_map_page(bp->pdev, page, 0, PAGE_SIZE, PCI_DMA_FROMDEVICE); if (pci_dma_mapping_error(mapping)) { #endif __free_page(page); return -EIO; } rx_pg->page = page; dma_unmap_addr_set(rx_pg, mapping, mapping); rxbd->rx_bd_haddr_hi = (u64) mapping >> 32; rxbd->rx_bd_haddr_lo = (u64) mapping & 0xffffffff; return 0; } static void bnx2_free_rx_page(struct bnx2 *bp, struct bnx2_rx_ring_info *rxr, u16 index) { struct bnx2_sw_pg *rx_pg = &rxr->rx_pg_ring[index]; struct page *page = rx_pg->page; if (!page) return; #if (LINUX_VERSION_CODE >= 0x02061b) dma_unmap_page(&bp->pdev->dev, dma_unmap_addr(rx_pg, mapping), PAGE_SIZE, PCI_DMA_FROMDEVICE); #else pci_unmap_page(bp->pdev, dma_unmap_addr(rx_pg, mapping), PAGE_SIZE, PCI_DMA_FROMDEVICE); #endif __free_page(page); rx_pg->page = NULL; } static inline int bnx2_alloc_rx_skb(struct bnx2 *bp, struct bnx2_rx_ring_info *rxr, u16 index, gfp_t gfp) { struct sk_buff *skb; struct bnx2_sw_bd *rx_buf = &rxr->rx_buf_ring[index]; dma_addr_t mapping; struct bnx2_rx_bd *rxbd = &rxr->rx_desc_ring[BNX2_RX_RING(index)][BNX2_RX_IDX(index)]; unsigned long align; skb = __netdev_alloc_skb(bp->dev, bp->rx_buf_size, gfp); if (skb == NULL) { return -ENOMEM; } if (unlikely((align = (unsigned long) skb->data & (BNX2_RX_ALIGN - 1)))) skb_reserve(skb, BNX2_RX_ALIGN - align); #if (LINUX_VERSION_CODE >= 0x02061b) mapping = dma_map_single(&bp->pdev->dev, skb->data, bp->rx_buf_use_size, PCI_DMA_FROMDEVICE); if (dma_mapping_error(&bp->pdev->dev, mapping)) { #else mapping = pci_map_single(bp->pdev, skb->data, bp->rx_buf_use_size, PCI_DMA_FROMDEVICE); if (pci_dma_mapping_error(mapping)) { #endif dev_kfree_skb(skb); return -EIO; } rx_buf->skb = skb; rx_buf->desc = (struct l2_fhdr *) skb->data; dma_unmap_addr_set(rx_buf, mapping, mapping); rxbd->rx_bd_haddr_hi = (u64) mapping >> 32; rxbd->rx_bd_haddr_lo = (u64) mapping & 0xffffffff; rxr->rx_prod_bseq += bp->rx_buf_use_size; return 0; } static int bnx2_phy_event_is_set(struct bnx2 *bp, struct bnx2_napi *bnapi, u32 event) { struct status_block *sblk = bnapi->status_blk.msi; u32 new_link_state, old_link_state; int is_set = 1; new_link_state = sblk->status_attn_bits & event; old_link_state = sblk->status_attn_bits_ack & event; if (new_link_state != old_link_state) { if (new_link_state) BNX2_WR(bp, BNX2_PCICFG_STATUS_BIT_SET_CMD, event); else BNX2_WR(bp, BNX2_PCICFG_STATUS_BIT_CLEAR_CMD, event); } else is_set = 0; return is_set; } static void bnx2_phy_int(struct bnx2 *bp, struct bnx2_napi *bnapi) { spin_lock(&bp->phy_lock); if (bnx2_phy_event_is_set(bp, bnapi, STATUS_ATTN_BITS_LINK_STATE)) bnx2_set_link(bp); if (bnx2_phy_event_is_set(bp, bnapi, STATUS_ATTN_BITS_TIMER_ABORT)) bnx2_set_remote_link(bp); spin_unlock(&bp->phy_lock); } static inline u16 bnx2_get_hw_tx_cons(struct bnx2_napi *bnapi) { u16 cons; /* Tell compiler that status block fields can change. */ barrier(); cons = *bnapi->hw_tx_cons_ptr; barrier(); if (unlikely((cons & BNX2_MAX_TX_DESC_CNT) == BNX2_MAX_TX_DESC_CNT)) cons++; return cons; } static int #if defined(__VMKLNX__) bnx2_tx_int(struct bnx2 *bp, struct bnx2_napi *bnapi, int budget, int check_queue) #else bnx2_tx_int(struct bnx2 *bp, struct bnx2_napi *bnapi, int budget) #endif { struct bnx2_tx_ring_info *txr = &bnapi->tx_ring; u16 hw_cons, sw_cons, sw_ring_cons; #ifndef BCM_HAVE_MULTI_QUEUE int tx_pkt = 0; #else int tx_pkt = 0, index; struct netdev_queue *txq; index = (bnapi - bp->bnx2_napi); txq = netdev_get_tx_queue(bp->dev, index); #endif hw_cons = bnx2_get_hw_tx_cons(bnapi); sw_cons = txr->tx_cons; while (sw_cons != hw_cons) { struct bnx2_sw_tx_bd *tx_buf; struct sk_buff *skb; int i, last; sw_ring_cons = BNX2_TX_RING_IDX(sw_cons); tx_buf = &txr->tx_buf_ring[sw_ring_cons]; skb = tx_buf->skb; /* prefetch skb_end_pointer() to speedup skb_shinfo(skb) */ prefetch(&skb->end); #ifdef BCM_TSO /* partial BD completions possible with TSO packets */ if (tx_buf->is_gso) { u16 last_idx, last_ring_idx; last_idx = sw_cons + tx_buf->nr_frags + 1; last_ring_idx = sw_ring_cons + tx_buf->nr_frags + 1; if (unlikely(last_ring_idx >= BNX2_MAX_TX_DESC_CNT)) { last_idx++; } if (((s16) ((s16) last_idx - (s16) hw_cons)) > 0) { break; } } #endif #if (LINUX_VERSION_CODE >= 0x02061b) dma_unmap_single(&bp->pdev->dev, dma_unmap_addr(tx_buf, mapping), skb_headlen(skb), PCI_DMA_TODEVICE); #else pci_unmap_single(bp->pdev, dma_unmap_addr(tx_buf, mapping), skb_headlen(skb), PCI_DMA_TODEVICE); #endif tx_buf->skb = NULL; last = tx_buf->nr_frags; for (i = 0; i < last; i++) { struct bnx2_sw_tx_bd *tx_buf; sw_cons = BNX2_NEXT_TX_BD(sw_cons); tx_buf = &txr->tx_buf_ring[BNX2_TX_RING_IDX(sw_cons)]; #if (LINUX_VERSION_CODE >= 0x02061b) dma_unmap_page(&bp->pdev->dev, #else pci_unmap_page(bp->pdev, #endif dma_unmap_addr(tx_buf, mapping), skb_frag_size(&skb_shinfo(skb)->frags[i]), PCI_DMA_TODEVICE); } sw_cons = BNX2_NEXT_TX_BD(sw_cons); dev_kfree_skb(skb); #if defined(BNX2_ENABLE_NETQUEUE) bnapi->stats.tx_packets++; bnapi->stats.tx_bytes += skb->len; bnapi->tx_packets_processed++; wmb(); #endif tx_pkt++; if (tx_pkt == budget) break; if (hw_cons == sw_cons) hw_cons = bnx2_get_hw_tx_cons(bnapi); } txr->hw_tx_cons = hw_cons; txr->tx_cons = sw_cons; /* Need to make the tx_cons update visible to bnx2_start_xmit() * before checking for netif_tx_queue_stopped(). Without the * memory barrier, there is a small possibility that bnx2_start_xmit() * will miss it and cause the queue to be stopped forever. */ smp_mb(); #if defined(BNX2_ENABLE_NETQUEUE) if ((!check_queue) || (bp->netq_state & BNX2_NETQ_SUSPENDED)) return tx_pkt; #endif #ifndef BCM_HAVE_MULTI_QUEUE if (unlikely(netif_queue_stopped(bp->dev)) && (bnx2_tx_avail(bp, txr) > bp->tx_wake_thresh)) { netif_tx_lock(bp->dev); if ((netif_queue_stopped(bp->dev)) && (bnx2_tx_avail(bp, txr) > bp->tx_wake_thresh)) netif_wake_queue(bp->dev); netif_tx_unlock(bp->dev); } #else if (unlikely(netif_tx_queue_stopped(txq)) && (bnx2_tx_avail(bp, txr) > bp->tx_wake_thresh)) { __netif_tx_lock(txq, smp_processor_id()); if ((netif_tx_queue_stopped(txq)) && (bnx2_tx_avail(bp, txr) > bp->tx_wake_thresh)) netif_tx_wake_queue(txq); __netif_tx_unlock(txq); } #endif return tx_pkt; } static void bnx2_reuse_rx_skb_pages(struct bnx2 *bp, struct bnx2_rx_ring_info *rxr, struct sk_buff *skb, int count) { struct bnx2_sw_pg *cons_rx_pg, *prod_rx_pg; struct bnx2_rx_bd *cons_bd, *prod_bd; int i; u16 hw_prod, prod; u16 cons = rxr->rx_pg_cons; cons_rx_pg = &rxr->rx_pg_ring[cons]; /* The caller was unable to allocate a new page to replace the * last one in the frags array, so we need to recycle that page * and then free the skb. */ if (skb) { struct page *page; struct skb_shared_info *shinfo; shinfo = skb_shinfo(skb); shinfo->nr_frags--; page = skb_frag_page(&shinfo->frags[shinfo->nr_frags]); __skb_frag_set_page(&shinfo->frags[shinfo->nr_frags], NULL); cons_rx_pg->page = page; dev_kfree_skb(skb); } hw_prod = rxr->rx_pg_prod; for (i = 0; i < count; i++) { prod = BNX2_RX_PG_RING_IDX(hw_prod); prod_rx_pg = &rxr->rx_pg_ring[prod]; cons_rx_pg = &rxr->rx_pg_ring[cons]; cons_bd = &rxr->rx_pg_desc_ring[BNX2_RX_RING(cons)] [BNX2_RX_IDX(cons)]; prod_bd = &rxr->rx_pg_desc_ring[BNX2_RX_RING(prod)] [BNX2_RX_IDX(prod)]; if (prod != cons) { prod_rx_pg->page = cons_rx_pg->page; cons_rx_pg->page = NULL; dma_unmap_addr_set(prod_rx_pg, mapping, dma_unmap_addr(cons_rx_pg, mapping)); prod_bd->rx_bd_haddr_hi = cons_bd->rx_bd_haddr_hi; prod_bd->rx_bd_haddr_lo = cons_bd->rx_bd_haddr_lo; } cons = BNX2_RX_PG_RING_IDX(BNX2_NEXT_RX_BD(cons)); hw_prod = BNX2_NEXT_RX_BD(hw_prod); } rxr->rx_pg_prod = hw_prod; rxr->rx_pg_cons = cons; } static inline void bnx2_reuse_rx_skb(struct bnx2 *bp, struct bnx2_rx_ring_info *rxr, struct sk_buff *skb, u16 cons, u16 prod) { struct bnx2_sw_bd *cons_rx_buf, *prod_rx_buf; struct bnx2_rx_bd *cons_bd, *prod_bd; cons_rx_buf = &rxr->rx_buf_ring[cons]; prod_rx_buf = &rxr->rx_buf_ring[prod]; #if (LINUX_VERSION_CODE >= 0x02061b) dma_sync_single_for_device(&bp->pdev->dev, #else pci_dma_sync_single_for_device(bp->pdev, #endif dma_unmap_addr(cons_rx_buf, mapping), BNX2_RX_OFFSET + BNX2_RX_COPY_THRESH, PCI_DMA_FROMDEVICE); rxr->rx_prod_bseq += bp->rx_buf_use_size; prod_rx_buf->skb = skb; prod_rx_buf->desc = (struct l2_fhdr *) skb->data; if (cons == prod) return; dma_unmap_addr_set(prod_rx_buf, mapping, dma_unmap_addr(cons_rx_buf, mapping)); cons_bd = &rxr->rx_desc_ring[BNX2_RX_RING(cons)][BNX2_RX_IDX(cons)]; prod_bd = &rxr->rx_desc_ring[BNX2_RX_RING(prod)][BNX2_RX_IDX(prod)]; prod_bd->rx_bd_haddr_hi = cons_bd->rx_bd_haddr_hi; prod_bd->rx_bd_haddr_lo = cons_bd->rx_bd_haddr_lo; } static int bnx2_rx_skb(struct bnx2 *bp, struct bnx2_rx_ring_info *rxr, struct sk_buff *skb, unsigned int len, unsigned int hdr_len, dma_addr_t dma_addr, u32 ring_idx) { int err; u16 prod = ring_idx & 0xffff; err = bnx2_alloc_rx_skb(bp, rxr, prod, GFP_ATOMIC); if (unlikely(err)) { bnx2_reuse_rx_skb(bp, rxr, skb, (u16) (ring_idx >> 16), prod); if (hdr_len) { unsigned int raw_len = len + 4; int pages = PAGE_ALIGN(raw_len - hdr_len) >> PAGE_SHIFT; bnx2_reuse_rx_skb_pages(bp, rxr, NULL, pages); } return err; } skb_reserve(skb, BNX2_RX_OFFSET); #if (LINUX_VERSION_CODE >= 0x02061b) dma_unmap_single(&bp->pdev->dev, dma_addr, bp->rx_buf_use_size, PCI_DMA_FROMDEVICE); #else pci_unmap_single(bp->pdev, dma_addr, bp->rx_buf_use_size, PCI_DMA_FROMDEVICE); #endif if (hdr_len == 0) { skb_put(skb, len); return 0; } else { unsigned int i, frag_len, frag_size, pages; struct bnx2_sw_pg *rx_pg; u16 pg_cons = rxr->rx_pg_cons; u16 pg_prod = rxr->rx_pg_prod; frag_size = len + 4 - hdr_len; pages = PAGE_ALIGN(frag_size) >> PAGE_SHIFT; skb_put(skb, hdr_len); for (i = 0; i < pages; i++) { dma_addr_t mapping_old; frag_len = min(frag_size, (unsigned int) PAGE_SIZE); if (unlikely(frag_len <= 4)) { unsigned int tail = 4 - frag_len; rxr->rx_pg_cons = pg_cons; rxr->rx_pg_prod = pg_prod; bnx2_reuse_rx_skb_pages(bp, rxr, NULL, pages - i); skb->len -= tail; if (i == 0) { skb->tail -= tail; } else { skb_frag_t *frag = &skb_shinfo(skb)->frags[i - 1]; skb_frag_size_sub(frag, tail); skb->data_len -= tail; } return 0; } rx_pg = &rxr->rx_pg_ring[pg_cons]; /* Don't unmap yet. If we're unable to allocate a new * page, we need to recycle the page and the DMA addr. */ mapping_old = dma_unmap_addr(rx_pg, mapping); if (i == pages - 1) frag_len -= 4; bnx2_skb_fill_page_desc(skb, i, rx_pg->page, 0, frag_len); rx_pg->page = NULL; err = bnx2_alloc_rx_page(bp, rxr, BNX2_RX_PG_RING_IDX(pg_prod), GFP_ATOMIC); if (unlikely(err)) { rxr->rx_pg_cons = pg_cons; rxr->rx_pg_prod = pg_prod; bnx2_reuse_rx_skb_pages(bp, rxr, skb, pages - i); return err; } #if (LINUX_VERSION_CODE >= 0x02061b) dma_unmap_page(&bp->pdev->dev, mapping_old, PAGE_SIZE, PCI_DMA_FROMDEVICE); #else pci_unmap_page(bp->pdev, mapping_old, PAGE_SIZE, PCI_DMA_FROMDEVICE); #endif frag_size -= frag_len; skb->data_len += frag_len; skb->truesize += PAGE_SIZE; skb->len += frag_len; pg_prod = BNX2_NEXT_RX_BD(pg_prod); pg_cons = BNX2_RX_PG_RING_IDX(BNX2_NEXT_RX_BD(pg_cons)); } rxr->rx_pg_prod = pg_prod; rxr->rx_pg_cons = pg_cons; } return 0; } static inline u16 bnx2_get_hw_rx_cons(struct bnx2_napi *bnapi) { u16 cons; /* Tell compiler that status block fields can change. */ barrier(); cons = *bnapi->hw_rx_cons_ptr; barrier(); if (unlikely((cons & BNX2_MAX_RX_DESC_CNT) == BNX2_MAX_RX_DESC_CNT)) cons++; return cons; } static int bnx2_rx_int(struct bnx2 *bp, struct bnx2_napi *bnapi, int budget) { struct bnx2_rx_ring_info *rxr = &bnapi->rx_ring; u16 hw_cons, sw_cons, sw_ring_cons, sw_prod, sw_ring_prod; struct l2_fhdr *rx_hdr; int rx_pkt = 0, pg_ring_used = 0; #if defined(BNX2_ENABLE_NETQUEUE) int index = (bnapi - bp->bnx2_napi); #endif hw_cons = bnx2_get_hw_rx_cons(bnapi); sw_cons = rxr->rx_cons; sw_prod = rxr->rx_prod; /* Memory barrier necessary as speculative reads of the rx * buffer can be ahead of the index in the status block */ rmb(); while (sw_cons != hw_cons) { unsigned int len, hdr_len; u32 status; struct bnx2_sw_bd *rx_buf, *next_rx_buf; struct sk_buff *skb; dma_addr_t dma_addr; u16 vtag = 0; int hw_vlan __maybe_unused = 0; u16 next_ring_idx; sw_ring_cons = BNX2_RX_RING_IDX(sw_cons); sw_ring_prod = BNX2_RX_RING_IDX(sw_prod); rx_buf = &rxr->rx_buf_ring[sw_ring_cons]; skb = rx_buf->skb; prefetchw(skb); next_ring_idx = BNX2_RX_RING_IDX(BNX2_NEXT_RX_BD(sw_cons)); next_rx_buf = &rxr->rx_buf_ring[next_ring_idx]; prefetch(next_rx_buf->desc); rx_buf->skb = NULL; dma_addr = dma_unmap_addr(rx_buf, mapping); #if (LINUX_VERSION_CODE >= 0x02061b) dma_sync_single_for_cpu(&bp->pdev->dev, dma_addr, #else pci_dma_sync_single_for_cpu(bp->pdev, dma_addr, #endif BNX2_RX_OFFSET + BNX2_RX_COPY_THRESH, PCI_DMA_FROMDEVICE); rx_hdr = rx_buf->desc; len = rx_hdr->l2_fhdr_pkt_len; status = rx_hdr->l2_fhdr_status; hdr_len = 0; if (status & L2_FHDR_STATUS_SPLIT) { hdr_len = rx_hdr->l2_fhdr_ip_xsum; pg_ring_used = 1; } else if (len > bp->rx_jumbo_thresh) { hdr_len = bp->rx_jumbo_thresh; pg_ring_used = 1; } if (unlikely(status & (L2_FHDR_ERRORS_BAD_CRC | L2_FHDR_ERRORS_PHY_DECODE | L2_FHDR_ERRORS_ALIGNMENT | L2_FHDR_ERRORS_TOO_SHORT | L2_FHDR_ERRORS_GIANT_FRAME))) { #if defined(BNX2_ENABLE_NETQUEUE) bnapi->stats.rx_errors++; if (status & L2_FHDR_ERRORS_BAD_CRC) bnapi->stats.rx_crc_errors++; if (status & (L2_FHDR_ERRORS_TOO_SHORT | L2_FHDR_ERRORS_GIANT_FRAME)) bnapi->stats.rx_frame_errors++; #endif bnx2_reuse_rx_skb(bp, rxr, skb, sw_ring_cons, sw_ring_prod); if (pg_ring_used) { int pages; pages = PAGE_ALIGN(len - hdr_len) >> PAGE_SHIFT; bnx2_reuse_rx_skb_pages(bp, rxr, NULL, pages); } goto next_rx; } len -= 4; if (len <= bp->rx_copy_thresh) { struct sk_buff *new_skb; new_skb = netdev_alloc_skb(bp->dev, len + 6); if (new_skb == NULL) { bnx2_reuse_rx_skb(bp, rxr, skb, sw_ring_cons, sw_ring_prod); goto next_rx; } /* aligned copy */ #if (LINUX_VERSION_CODE >= 0x20616) skb_copy_from_linear_data_offset(skb, BNX2_RX_OFFSET - 6, new_skb->data, len + 6); #else memcpy(new_skb->data, skb->data + BNX2_RX_OFFSET - 6, len + 6); #endif skb_reserve(new_skb, 6); skb_put(new_skb, len); bnx2_reuse_rx_skb(bp, rxr, skb, sw_ring_cons, sw_ring_prod); skb = new_skb; } else if (unlikely(bnx2_rx_skb(bp, rxr, skb, len, hdr_len, dma_addr, (sw_ring_cons << 16) | sw_ring_prod))) goto next_rx; if ((status & L2_FHDR_STATUS_L2_VLAN_TAG) && !(bp->rx_mode & BNX2_EMAC_RX_MODE_KEEP_VLAN_TAG)) { vtag = rx_hdr->l2_fhdr_vlan_tag; #ifdef NEW_VLAN __vlan_hwaccel_put_tag(skb, htons(ETH_P_8021Q), vtag); #else #ifdef BCM_VLAN if (bp->vlgrp) hw_vlan = 1; else #endif { struct vlan_ethhdr *ve = (struct vlan_ethhdr *) __skb_push(skb, 4); bcm_memmove(ve, skb->data + 4, ETH_ALEN * 2); ve->h_vlan_proto = htons(ETH_P_8021Q); ve->h_vlan_TCI = htons(vtag); len += 4; } #endif } skb->protocol = eth_type_trans(skb, bp->dev); if ((len > (bp->dev->mtu + ETH_HLEN)) && (ntohs(skb->protocol) != 0x8100)) { dev_kfree_skb(skb); goto next_rx; } skb->ip_summed = CHECKSUM_NONE; if (bp->rx_csum && (status & (L2_FHDR_STATUS_TCP_SEGMENT | L2_FHDR_STATUS_UDP_DATAGRAM))) { if (likely((status & (L2_FHDR_ERRORS_TCP_XSUM | L2_FHDR_ERRORS_UDP_XSUM)) == 0)) skb->ip_summed = CHECKSUM_UNNECESSARY; } #ifdef NETIF_F_RXHASH if ((bp->dev->features & NETIF_F_RXHASH) && ((status & L2_FHDR_STATUS_USE_RXHASH) == L2_FHDR_STATUS_USE_RXHASH)) skb->rxhash = rx_hdr->l2_fhdr_hash; #endif skb_record_rx_queue(skb, bnapi - &bp->bnx2_napi[0]); #if defined(BNX2_ENABLE_NETQUEUE) vmknetddi_queueops_set_skb_queueid(skb, VMKNETDDI_QUEUEOPS_MK_RX_QUEUEID(index)); #endif #if defined(NETIF_F_GRO) && defined(BNX2_NEW_NAPI) #if defined(BCM_VLAN) && !defined(NEW_VLAN) if (hw_vlan) vlan_gro_receive(&bnapi->napi, bp->vlgrp, vtag, skb); else #endif napi_gro_receive(&bnapi->napi, skb); #else #ifdef BCM_VLAN if (hw_vlan) vlan_hwaccel_receive_skb(skb, bp->vlgrp, vtag); else #endif netif_receive_skb(skb); #endif #if (LINUX_VERSION_CODE < 0x02061b) || defined(__VMKLNX__) bp->dev->last_rx = jiffies; #endif rx_pkt++; #if defined(BNX2_ENABLE_NETQUEUE) /* Update queue specific stats */ bnapi->stats.rx_packets++; bnapi->stats.rx_bytes += len; #endif next_rx: sw_cons = BNX2_NEXT_RX_BD(sw_cons); sw_prod = BNX2_NEXT_RX_BD(sw_prod); if ((rx_pkt == budget)) break; /* Refresh hw_cons to see if there is new work */ if (sw_cons == hw_cons) { hw_cons = bnx2_get_hw_rx_cons(bnapi); rmb(); } } rxr->rx_cons = sw_cons; rxr->rx_prod = sw_prod; if (pg_ring_used) BNX2_WR16(bp, rxr->rx_pg_bidx_addr, rxr->rx_pg_prod); BNX2_WR16(bp, rxr->rx_bidx_addr, sw_prod); BNX2_WR(bp, rxr->rx_bseq_addr, rxr->rx_prod_bseq); mmiowb(); return rx_pkt; } #ifdef CONFIG_PCI_MSI /* MSI ISR - The only difference between this and the INTx ISR * is that the MSI interrupt is always serviced. */ static irqreturn_t #if (LINUX_VERSION_CODE >= 0x20613) || (defined(__VMKLNX__) && (VMWARE_ESX_DDK_VERSION >= 40000)) bnx2_msi(int irq, void *dev_instance) #else bnx2_msi(int irq, void *dev_instance, struct pt_regs *regs) #endif { struct bnx2_napi *bnapi = dev_instance; struct bnx2 *bp = bnapi->bp; prefetch(bnapi->status_blk.msi); BNX2_WR(bp, BNX2_PCICFG_INT_ACK_CMD, #if defined(__VMKLNX__) bnapi->int_num | #endif BNX2_PCICFG_INT_ACK_CMD_USE_INT_HC_PARAM | BNX2_PCICFG_INT_ACK_CMD_MASK_INT); /* Return here if interrupt is disabled. */ if (unlikely(atomic_read(&bp->intr_sem) != 0)) return IRQ_HANDLED; #ifdef BNX2_NEW_NAPI napi_schedule(&bnapi->napi); #else netif_rx_schedule(bp->dev); #endif return IRQ_HANDLED; } static irqreturn_t #if (LINUX_VERSION_CODE >= 0x20613) || (defined(__VMKLNX__) && (VMWARE_ESX_DDK_VERSION >= 40000)) bnx2_msi_1shot(int irq, void *dev_instance) #else bnx2_msi_1shot(int irq, void *dev_instance, struct pt_regs *regs) #endif { struct bnx2_napi *bnapi = dev_instance; struct bnx2 *bp = bnapi->bp; prefetch(bnapi->status_blk.msi); /* Return here if interrupt is disabled. */ if (unlikely(atomic_read(&bp->intr_sem) != 0)) return IRQ_HANDLED; #ifdef BNX2_NEW_NAPI napi_schedule(&bnapi->napi); #else netif_rx_schedule(bp->dev); #endif return IRQ_HANDLED; } #endif static irqreturn_t #if (LINUX_VERSION_CODE >= 0x20613) || (defined(__VMKLNX__) && (VMWARE_ESX_DDK_VERSION >= 40000)) bnx2_interrupt(int irq, void *dev_instance) #else bnx2_interrupt(int irq, void *dev_instance, struct pt_regs *regs) #endif { struct bnx2_napi *bnapi = dev_instance; struct bnx2 *bp = bnapi->bp; struct status_block *sblk = bnapi->status_blk.msi; /* When using INTx, it is possible for the interrupt to arrive * at the CPU before the status block posted prior to the * interrupt. Reading a register will flush the status block. * When using MSI, the MSI message will always complete after * the status block write. */ if ((sblk->status_idx == bnapi->last_status_idx) && (BNX2_RD(bp, BNX2_PCICFG_MISC_STATUS) & BNX2_PCICFG_MISC_STATUS_INTA_VALUE)) return IRQ_NONE; BNX2_WR(bp, BNX2_PCICFG_INT_ACK_CMD, BNX2_PCICFG_INT_ACK_CMD_USE_INT_HC_PARAM | BNX2_PCICFG_INT_ACK_CMD_MASK_INT); /* Read back to deassert IRQ immediately to avoid too many * spurious interrupts. */ BNX2_RD(bp, BNX2_PCICFG_INT_ACK_CMD); /* Return here if interrupt is shared and is disabled. */ if (unlikely(atomic_read(&bp->intr_sem) != 0)) return IRQ_HANDLED; #ifdef BNX2_NEW_NAPI if (napi_schedule_prep(&bnapi->napi)) { bnapi->last_status_idx = sblk->status_idx; __napi_schedule(&bnapi->napi); } #else if (netif_rx_schedule_prep(bp->dev)) { bnapi->last_status_idx = sblk->status_idx; __netif_rx_schedule(bp->dev); } #endif return IRQ_HANDLED; } static inline int bnx2_has_fast_work(struct bnx2_napi *bnapi) { struct bnx2_tx_ring_info *txr = &bnapi->tx_ring; struct bnx2_rx_ring_info *rxr = &bnapi->rx_ring; if ((bnx2_get_hw_rx_cons(bnapi) != rxr->rx_cons) || (bnx2_get_hw_tx_cons(bnapi) != txr->hw_tx_cons)) return 1; return 0; } #define STATUS_ATTN_EVENTS (STATUS_ATTN_BITS_LINK_STATE | \ STATUS_ATTN_BITS_TIMER_ABORT) static inline int bnx2_has_work(struct bnx2_napi *bnapi) { struct status_block *sblk = bnapi->status_blk.msi; if (bnx2_has_fast_work(bnapi)) return 1; #ifdef BCM_CNIC if (bnapi->cnic_present && (bnapi->cnic_tag != sblk->status_idx)) return 1; #endif if ((sblk->status_attn_bits & STATUS_ATTN_EVENTS) != (sblk->status_attn_bits_ack & STATUS_ATTN_EVENTS)) return 1; return 0; } #ifdef CONFIG_PCI_MSI static void bnx2_chk_missed_msi(struct bnx2 *bp) { struct bnx2_napi *bnapi = &bp->bnx2_napi[0]; u32 msi_ctrl; if (bnx2_has_work(bnapi)) { msi_ctrl = BNX2_RD(bp, BNX2_PCICFG_MSI_CONTROL); if (!(msi_ctrl & BNX2_PCICFG_MSI_CONTROL_ENABLE)) return; if (bnapi->last_status_idx == bp->idle_chk_status_idx) { BNX2_WR(bp, BNX2_PCICFG_MSI_CONTROL, msi_ctrl & ~BNX2_PCICFG_MSI_CONTROL_ENABLE); BNX2_WR(bp, BNX2_PCICFG_MSI_CONTROL, msi_ctrl); #if (LINUX_VERSION_CODE >= 0x20613) || (defined(__VMKLNX__) && (VMWARE_ESX_DDK_VERSION >= 40000)) bnx2_msi(bp->irq_tbl[0].vector, bnapi); #else bnx2_msi(bp->irq_tbl[0].vector, bnapi, NULL); #endif } } bp->idle_chk_status_idx = bnapi->last_status_idx; } #endif #ifdef BCM_CNIC static void bnx2_poll_cnic(struct bnx2 *bp, struct bnx2_napi *bnapi) { struct cnic_ops *c_ops; if (!bnapi->cnic_present) return; rcu_read_lock(); c_ops = rcu_dereference(bp->cnic_ops); if (c_ops) bnapi->cnic_tag = c_ops->cnic_handler(bp->cnic_data, bnapi->status_blk.msi); rcu_read_unlock(); } #endif #ifdef BNX2_NEW_NAPI static void bnx2_poll_link(struct bnx2 *bp, struct bnx2_napi *bnapi) { struct status_block *sblk = bnapi->status_blk.msi; u32 status_attn_bits = sblk->status_attn_bits; u32 status_attn_bits_ack = sblk->status_attn_bits_ack; if ((status_attn_bits & STATUS_ATTN_EVENTS) != (status_attn_bits_ack & STATUS_ATTN_EVENTS)) { bnx2_phy_int(bp, bnapi); /* This is needed to take care of transient status * during link changes. */ BNX2_WR(bp, BNX2_HC_COMMAND, bp->hc_cmd | BNX2_HC_COMMAND_COAL_NOW_WO_INT); BNX2_RD(bp, BNX2_HC_COMMAND); } } static int bnx2_poll_work(struct bnx2 *bp, struct bnx2_napi *bnapi, int work_done, int budget) { struct bnx2_tx_ring_info *txr = &bnapi->tx_ring; struct bnx2_rx_ring_info *rxr = &bnapi->rx_ring; if (bnx2_get_hw_tx_cons(bnapi) != txr->hw_tx_cons) #if defined(__VMKLNX__) bnx2_tx_int(bp, bnapi, 0, 1); #else bnx2_tx_int(bp, bnapi, 0); #endif if (bnx2_get_hw_rx_cons(bnapi) != rxr->rx_cons) work_done += bnx2_rx_int(bp, bnapi, budget - work_done); #if defined(__VMKLNX__) wmb(); #endif return work_done; } static int bnx2_poll_msix(struct napi_struct *napi, int budget) { struct bnx2_napi *bnapi = container_of(napi, struct bnx2_napi, napi); struct bnx2 *bp = bnapi->bp; int work_done = 0; struct status_block_msix *sblk = bnapi->status_blk.msix; while (1) { work_done = bnx2_poll_work(bp, bnapi, work_done, budget); if (unlikely(work_done >= budget)) break; bnapi->last_status_idx = sblk->status_idx; /* status idx must be read before checking for more work. */ rmb(); if (likely(!bnx2_has_fast_work(bnapi))) { napi_complete(napi); BNX2_WR(bp, BNX2_PCICFG_INT_ACK_CMD, bnapi->int_num | BNX2_PCICFG_INT_ACK_CMD_INDEX_VALID | bnapi->last_status_idx); break; } } return work_done; } static int bnx2_poll(struct napi_struct *napi, int budget) { struct bnx2_napi *bnapi = container_of(napi, struct bnx2_napi, napi); struct bnx2 *bp = bnapi->bp; int work_done = 0; struct status_block *sblk = bnapi->status_blk.msi; while (1) { bnx2_poll_link(bp, bnapi); work_done = bnx2_poll_work(bp, bnapi, work_done, budget); #if defined(BNX2_ENABLE_NETQUEUE) if (bnx2_netqueue_is_avail(bp) && bnx2_netqueue_open_started(bp)) bnx2_netqueue_service_bnx2_msix(bnapi); #endif #ifdef BCM_CNIC bnx2_poll_cnic(bp, bnapi); #endif /* bnapi->last_status_idx is used below to tell the hw how * much work has been processed, so we must read it before * checking for more work. */ bnapi->last_status_idx = sblk->status_idx; if (unlikely(work_done >= budget)) break; rmb(); if (likely(!bnx2_has_work(bnapi))) { napi_complete(napi); if (likely(bp->flags & BNX2_FLAG_USING_MSI_OR_MSIX)) { BNX2_WR(bp, BNX2_PCICFG_INT_ACK_CMD, BNX2_PCICFG_INT_ACK_CMD_INDEX_VALID | bnapi->last_status_idx); break; } BNX2_WR(bp, BNX2_PCICFG_INT_ACK_CMD, BNX2_PCICFG_INT_ACK_CMD_INDEX_VALID | BNX2_PCICFG_INT_ACK_CMD_MASK_INT | bnapi->last_status_idx); BNX2_WR(bp, BNX2_PCICFG_INT_ACK_CMD, BNX2_PCICFG_INT_ACK_CMD_INDEX_VALID | bnapi->last_status_idx); break; } } return work_done; } #else static int bnx2_poll(struct net_device *dev, int *budget) { struct bnx2 *bp = netdev_priv(dev); struct bnx2_napi *bnapi = &bp->bnx2_napi[0]; struct bnx2_tx_ring_info *txr = &bnapi->tx_ring; struct bnx2_rx_ring_info *rxr = &bnapi->rx_ring; struct status_block *sblk = bnapi->status_blk.msi; u32 status_attn_bits = sblk->status_attn_bits; u32 status_attn_bits_ack = sblk->status_attn_bits_ack; if ((status_attn_bits & STATUS_ATTN_EVENTS) != (status_attn_bits_ack & STATUS_ATTN_EVENTS)) { bnx2_phy_int(bp, bnapi); /* This is needed to take care of transient status * during link changes. */ BNX2_WR(bp, BNX2_HC_COMMAND, bp->hc_cmd | BNX2_HC_COMMAND_COAL_NOW_WO_INT); BNX2_RD(bp, BNX2_HC_COMMAND); } if (bnx2_get_hw_tx_cons(bnapi) != txr->hw_tx_cons) #if defined(__VMKLNX__) bnx2_tx_int(bp, bnapi, 0, 1); #else bnx2_tx_int(bp, bnapi, 0); #endif if (bnx2_get_hw_rx_cons(bnapi) != rxr->rx_cons) { int orig_budget = *budget; int work_done; if (orig_budget > dev->quota) orig_budget = dev->quota; work_done = bnx2_rx_int(bp, bnapi, orig_budget); *budget -= work_done; dev->quota -= work_done; } #ifdef BCM_CNIC bnx2_poll_cnic(bp, bnapi); #endif bnapi->last_status_idx = sblk->status_idx; rmb(); if (!bnx2_has_work(bnapi)) { netif_rx_complete(dev); if (likely(bp->flags & BNX2_FLAG_USING_MSI_OR_MSIX)) { BNX2_WR(bp, BNX2_PCICFG_INT_ACK_CMD, BNX2_PCICFG_INT_ACK_CMD_INDEX_VALID | bnapi->last_status_idx); return 0; } BNX2_WR(bp, BNX2_PCICFG_INT_ACK_CMD, BNX2_PCICFG_INT_ACK_CMD_INDEX_VALID | BNX2_PCICFG_INT_ACK_CMD_MASK_INT | bnapi->last_status_idx); BNX2_WR(bp, BNX2_PCICFG_INT_ACK_CMD, BNX2_PCICFG_INT_ACK_CMD_INDEX_VALID | bnapi->last_status_idx); return 0; } return 1; } #endif /* Called with rtnl_lock from vlan functions and also netif_tx_lock * from set_multicast. */ static void bnx2_set_rx_mode(struct net_device *dev) { struct bnx2 *bp = netdev_priv(dev); u32 rx_mode, sort_mode; #ifdef BCM_HAVE_SET_RX_MODE #if (LINUX_VERSION_CODE >= 0x2061f) struct netdev_hw_addr *ha; #else struct dev_addr_list *uc_ptr; #endif #endif int i; if (!netif_running(dev)) return; spin_lock_bh(&bp->phy_lock); rx_mode = bp->rx_mode & ~(BNX2_EMAC_RX_MODE_PROMISCUOUS | BNX2_EMAC_RX_MODE_KEEP_VLAN_TAG); sort_mode = 1 | BNX2_RPM_SORT_USER0_BC_EN; #ifdef NEW_VLAN if (!(dev->features & NETIF_F_HW_VLAN_CTAG_RX) && (bp->flags & BNX2_FLAG_CAN_KEEP_VLAN)) rx_mode |= BNX2_EMAC_RX_MODE_KEEP_VLAN_TAG; #else #ifdef BCM_VLAN if (!bp->vlgrp && (bp->flags & BNX2_FLAG_CAN_KEEP_VLAN)) rx_mode |= BNX2_EMAC_RX_MODE_KEEP_VLAN_TAG; #else if (bp->flags & BNX2_FLAG_CAN_KEEP_VLAN) rx_mode |= BNX2_EMAC_RX_MODE_KEEP_VLAN_TAG; #endif #endif if (dev->flags & IFF_PROMISC) { /* Promiscuous mode. */ rx_mode |= BNX2_EMAC_RX_MODE_PROMISCUOUS; sort_mode |= BNX2_RPM_SORT_USER0_PROM_EN | BNX2_RPM_SORT_USER0_PROM_VLAN; } else if (dev->flags & IFF_ALLMULTI) { for (i = 0; i < NUM_MC_HASH_REGISTERS; i++) { BNX2_WR(bp, BNX2_EMAC_MULTICAST_HASH0 + (i * 4), 0xffffffff); } sort_mode |= BNX2_RPM_SORT_USER0_MC_EN; } else { /* Accept one or more multicast(s). */ #ifndef BCM_NEW_NETDEV_HW_ADDR struct dev_mc_list *mclist; #endif u32 mc_filter[NUM_MC_HASH_REGISTERS]; u32 regidx; u32 bit; u32 crc; memset(mc_filter, 0, 4 * NUM_MC_HASH_REGISTERS); #ifdef BCM_NEW_NETDEV_HW_ADDR netdev_for_each_mc_addr(ha, dev) { crc = ether_crc_le(ETH_ALEN, ha->addr); #else netdev_for_each_mc_addr(mclist, dev) { crc = ether_crc_le(ETH_ALEN, mclist->dmi_addr); #endif bit = crc & 0xff; regidx = (bit & 0xe0) >> 5; bit &= 0x1f; mc_filter[regidx] |= (1 << bit); } for (i = 0; i < NUM_MC_HASH_REGISTERS; i++) { BNX2_WR(bp, BNX2_EMAC_MULTICAST_HASH0 + (i * 4), mc_filter[i]); } sort_mode |= BNX2_RPM_SORT_USER0_MC_HSH_EN; } #ifdef BCM_HAVE_SET_RX_MODE if (netdev_uc_count(dev) > BNX2_MAX_UNICAST_ADDRESSES) { rx_mode |= BNX2_EMAC_RX_MODE_PROMISCUOUS; sort_mode |= BNX2_RPM_SORT_USER0_PROM_EN | BNX2_RPM_SORT_USER0_PROM_VLAN; } else if (!(dev->flags & IFF_PROMISC)) { #if (LINUX_VERSION_CODE < 0x2061f) uc_ptr = dev->uc_list; /* Add all entries into to the match filter list */ for (i = 0; i < dev->uc_count; i++) { bnx2_set_mac_addr(bp, uc_ptr->da_addr, i + BNX2_START_UNICAST_ADDRESS_INDEX); sort_mode |= (1 << (i + BNX2_START_UNICAST_ADDRESS_INDEX)); uc_ptr = uc_ptr->next; } #else i = 0; netdev_for_each_uc_addr(ha, dev) { bnx2_set_mac_addr(bp, ha->addr, i + BNX2_START_UNICAST_ADDRESS_INDEX); sort_mode |= (1 << (i + BNX2_START_UNICAST_ADDRESS_INDEX)); i++; } #endif } #endif if (rx_mode != bp->rx_mode) { bp->rx_mode = rx_mode; BNX2_WR(bp, BNX2_EMAC_RX_MODE, rx_mode); } BNX2_WR(bp, BNX2_RPM_SORT_USER0, 0x0); BNX2_WR(bp, BNX2_RPM_SORT_USER0, sort_mode); BNX2_WR(bp, BNX2_RPM_SORT_USER0, sort_mode | BNX2_RPM_SORT_USER0_ENA); spin_unlock_bh(&bp->phy_lock); } #define FW_BUF_SIZE 0x10000 static int bnx2_gunzip_init(struct bnx2 *bp) { if ((bp->gunzip_buf = vmalloc(FW_BUF_SIZE)) == NULL) goto gunzip_nomem1; if ((bp->strm = kmalloc(sizeof(*bp->strm), GFP_KERNEL)) == NULL) goto gunzip_nomem2; bp->strm->workspace = kmalloc(zlib_inflate_workspacesize(), GFP_KERNEL); if (bp->strm->workspace == NULL) goto gunzip_nomem3; return 0; gunzip_nomem3: kfree(bp->strm); bp->strm = NULL; gunzip_nomem2: vfree(bp->gunzip_buf); bp->gunzip_buf = NULL; gunzip_nomem1: netdev_err(bp->dev, "Cannot allocate firmware buffer for " "uncompression.\n"); return -ENOMEM; } static void bnx2_gunzip_end(struct bnx2 *bp) { kfree(bp->strm->workspace); kfree(bp->strm); bp->strm = NULL; if (bp->gunzip_buf) { vfree(bp->gunzip_buf); bp->gunzip_buf = NULL; } } static int bnx2_gunzip(struct bnx2 *bp, const u8 *zbuf, int len, void **outbuf, int *outlen) { int rc; bp->strm->next_in = zbuf; bp->strm->avail_in = len; bp->strm->next_out = bp->gunzip_buf; bp->strm->avail_out = FW_BUF_SIZE; rc = zlib_inflateInit2(bp->strm, -MAX_WBITS); if (rc != Z_OK) return rc; rc = zlib_inflate(bp->strm, Z_FINISH); *outlen = FW_BUF_SIZE - bp->strm->avail_out; *outbuf = bp->gunzip_buf; if ((rc != Z_OK) && (rc != Z_STREAM_END)) netdev_err(bp->dev, "Firmware decompression error: %s\n", bp->strm->msg); zlib_inflateEnd(bp->strm); if (rc == Z_STREAM_END) return 0; return rc; } #if defined(__VMKLNX__) struct bnx2_cpus_scratch_debug { u32 offset; /* Scratch pad offset to firmware version */ char *name; /* Name of the CPU */ }; #define BNX2_SCRATCH_FW_VERSION_OFFSET 0x10 #define BNX2_TPAT_SCRATCH_FW_VERSION_OFFSET 0x410 static void bnx2_print_fw_versions(struct bnx2 *bp) { /* Array of the firmware offset's + CPU strings */ const struct bnx2_cpus_scratch_debug cpus_scratch[] = { { .offset = BNX2_TXP_SCRATCH + BNX2_SCRATCH_FW_VERSION_OFFSET, .name = "TXP" }, { .offset = BNX2_TPAT_SCRATCH + BNX2_TPAT_SCRATCH_FW_VERSION_OFFSET, .name = "TPAT" }, { .offset = BNX2_RXP_SCRATCH + BNX2_SCRATCH_FW_VERSION_OFFSET, .name = "RXP" }, { .offset = BNX2_COM_SCRATCH + BNX2_SCRATCH_FW_VERSION_OFFSET, .name = "COM" }, { .offset = BNX2_CP_SCRATCH + BNX2_SCRATCH_FW_VERSION_OFFSET, .name = "CP" }, /* There is no versioning for MCP firmware */ }; int i; netdev_info(bp->dev, "CPU fw versions: "); for (i = 0; i < ARRAY_SIZE(cpus_scratch); i++) { /* The FW versions are 11 bytes long + 1 extra byte for * the NULL termination */ char version[12]; int j; /* Copy 4 bytes at a time */ for (j = 0; j < sizeof(version); j += 4) { u32 val; val = bnx2_reg_rd_ind(bp, cpus_scratch[i].offset + j); val = be32_to_cpu(val); memcpy(&version[j], &val, sizeof(val)); } /* Force a NULL terminiated string */ version[11] = '\0'; printk("%s: '%s' ", cpus_scratch[i].name, version); } printk("\n"); } #endif static u32 rv2p_fw_fixup(u32 rv2p_proc, int idx, u32 loc, u32 rv2p_code) { switch (idx) { case RV2P_P1_FIXUP_PAGE_SIZE_IDX: rv2p_code &= ~RV2P_BD_PAGE_SIZE_MSK; rv2p_code |= RV2P_BD_PAGE_SIZE; break; } return rv2p_code; } static void load_rv2p_fw(struct bnx2 *bp, __le32 *rv2p_code, u32 rv2p_code_len, u32 rv2p_proc, u32 fixup_loc) { __le32 *rv2p_code_start = rv2p_code; int i; u32 val, cmd, addr; if (rv2p_proc == RV2P_PROC1) { cmd = BNX2_RV2P_PROC1_ADDR_CMD_RDWR; addr = BNX2_RV2P_PROC1_ADDR_CMD; } else { cmd = BNX2_RV2P_PROC2_ADDR_CMD_RDWR; addr = BNX2_RV2P_PROC2_ADDR_CMD; } for (i = 0; i < rv2p_code_len; i += 8) { BNX2_WR(bp, BNX2_RV2P_INSTR_HIGH, le32_to_cpu(*rv2p_code)); rv2p_code++; BNX2_WR(bp, BNX2_RV2P_INSTR_LOW, le32_to_cpu(*rv2p_code)); rv2p_code++; val = (i / 8) | cmd; BNX2_WR(bp, addr, val); } rv2p_code = rv2p_code_start; if (fixup_loc && ((fixup_loc * 4) < rv2p_code_len)) { u32 code; code = le32_to_cpu(*(rv2p_code + fixup_loc - 1)); BNX2_WR(bp, BNX2_RV2P_INSTR_HIGH, code); code = le32_to_cpu(*(rv2p_code + fixup_loc)); code = rv2p_fw_fixup(rv2p_proc, 0, fixup_loc, code); BNX2_WR(bp, BNX2_RV2P_INSTR_LOW, code); val = (fixup_loc / 2) | cmd; BNX2_WR(bp, addr, val); } /* Reset the processor, un-stall is done later. */ if (rv2p_proc == RV2P_PROC1) { BNX2_WR(bp, BNX2_RV2P_COMMAND, BNX2_RV2P_COMMAND_PROC1_RESET); } else { BNX2_WR(bp, BNX2_RV2P_COMMAND, BNX2_RV2P_COMMAND_PROC2_RESET); } } static int load_cpu_fw(struct bnx2 *bp, const struct cpu_reg *cpu_reg, struct fw_info *fw) { u32 offset; u32 val; int rc; /* Halt the CPU. */ val = bnx2_reg_rd_ind(bp, cpu_reg->mode); val |= cpu_reg->mode_value_halt; bnx2_reg_wr_ind(bp, cpu_reg->mode, val); bnx2_reg_wr_ind(bp, cpu_reg->state, cpu_reg->state_value_clear); /* Load the Text area. */ offset = cpu_reg->spad_base + (fw->text_addr - cpu_reg->mips_view_base); if (fw->gz_text) { u32 text_len; void *text; rc = bnx2_gunzip(bp, fw->gz_text, fw->gz_text_len, &text, &text_len); if (rc) return rc; fw->text = text; } if (fw->text) { int j; for (j = 0; j < (fw->text_len / 4); j++, offset += 4) { bnx2_reg_wr_ind(bp, offset, le32_to_cpu(fw->text[j])); } } /* Load the Data area. */ offset = cpu_reg->spad_base + (fw->data_addr - cpu_reg->mips_view_base); if (fw->data) { int j; for (j = 0; j < (fw->data_len / 4); j++, offset += 4) { bnx2_reg_wr_ind(bp, offset, fw->data[j]); } } /* Load the SBSS area. */ offset = cpu_reg->spad_base + (fw->sbss_addr - cpu_reg->mips_view_base); if (fw->sbss_len) { int j; for (j = 0; j < (fw->sbss_len / 4); j++, offset += 4) { bnx2_reg_wr_ind(bp, offset, 0); } } /* Load the BSS area. */ offset = cpu_reg->spad_base + (fw->bss_addr - cpu_reg->mips_view_base); if (fw->bss_len) { int j; for (j = 0; j < (fw->bss_len/4); j++, offset += 4) { bnx2_reg_wr_ind(bp, offset, 0); } } /* Load the Read-Only area. */ offset = cpu_reg->spad_base + (fw->rodata_addr - cpu_reg->mips_view_base); if (fw->rodata) { int j; for (j = 0; j < (fw->rodata_len / 4); j++, offset += 4) { bnx2_reg_wr_ind(bp, offset, fw->rodata[j]); } } /* Clear the pre-fetch instruction. */ bnx2_reg_wr_ind(bp, cpu_reg->inst, 0); bnx2_reg_wr_ind(bp, cpu_reg->pc, fw->start_addr); /* Start the CPU. */ val = bnx2_reg_rd_ind(bp, cpu_reg->mode); val &= ~cpu_reg->mode_value_halt; bnx2_reg_wr_ind(bp, cpu_reg->state, cpu_reg->state_value_clear); bnx2_reg_wr_ind(bp, cpu_reg->mode, val); return 0; } static int bnx2_init_cpus(struct bnx2 *bp) { struct fw_info *fw; int rc = 0, rv2p_len; void *text; const void *rv2p; u32 text_len, fixup_loc; if ((rc = bnx2_gunzip_init(bp)) != 0) return rc; /* Initialize the RV2P processor. */ if (BNX2_CHIP(bp) == BNX2_CHIP_5709) { if ((BNX2_CHIP_ID(bp) == BNX2_CHIP_ID_5709_A0) || (BNX2_CHIP_ID(bp) == BNX2_CHIP_ID_5709_A1)) { rv2p = bnx2_xi90_rv2p_proc1; rv2p_len = sizeof(bnx2_xi90_rv2p_proc1); fixup_loc = XI90_RV2P_PROC1_MAX_BD_PAGE_LOC; } else { rv2p = bnx2_xi_rv2p_proc1; rv2p_len = sizeof(bnx2_xi_rv2p_proc1); fixup_loc = XI_RV2P_PROC1_MAX_BD_PAGE_LOC; } } else { rv2p = bnx2_rv2p_proc1; rv2p_len = sizeof(bnx2_rv2p_proc1); fixup_loc = RV2P_PROC1_MAX_BD_PAGE_LOC; } rc = bnx2_gunzip(bp, rv2p, rv2p_len, &text, &text_len); if (rc) goto init_cpu_err; load_rv2p_fw(bp, text, text_len, RV2P_PROC1, fixup_loc); if (BNX2_CHIP(bp) == BNX2_CHIP_5709) { if ((BNX2_CHIP_ID(bp) == BNX2_CHIP_ID_5709_A0) || (BNX2_CHIP_ID(bp) == BNX2_CHIP_ID_5709_A1)) { rv2p = bnx2_xi90_rv2p_proc2; rv2p_len = sizeof(bnx2_xi90_rv2p_proc2); fixup_loc = XI90_RV2P_PROC2_MAX_BD_PAGE_LOC; } else { rv2p = bnx2_xi_rv2p_proc2; rv2p_len = sizeof(bnx2_xi_rv2p_proc2); fixup_loc = XI_RV2P_PROC2_MAX_BD_PAGE_LOC; } } else { rv2p = bnx2_rv2p_proc2; rv2p_len = sizeof(bnx2_rv2p_proc2); fixup_loc = RV2P_PROC2_MAX_BD_PAGE_LOC; } rc = bnx2_gunzip(bp, rv2p, rv2p_len, &text, &text_len); if (rc) goto init_cpu_err; load_rv2p_fw(bp, text, text_len, RV2P_PROC2, fixup_loc); /* Initialize the RX Processor. */ if (BNX2_CHIP(bp) == BNX2_CHIP_5709) fw = &bnx2_rxp_fw_09; else fw = &bnx2_rxp_fw_06; rc = load_cpu_fw(bp, &cpu_reg_rxp, fw); if (rc) goto init_cpu_err; /* Initialize the TX Processor. */ if (BNX2_CHIP(bp) == BNX2_CHIP_5709) fw = &bnx2_txp_fw_09; else fw = &bnx2_txp_fw_06; rc = load_cpu_fw(bp, &cpu_reg_txp, fw); if (rc) goto init_cpu_err; /* Initialize the TX Patch-up Processor. */ if (BNX2_CHIP(bp) == BNX2_CHIP_5709) fw = &bnx2_tpat_fw_09; else fw = &bnx2_tpat_fw_06; rc = load_cpu_fw(bp, &cpu_reg_tpat, fw); if (rc) goto init_cpu_err; /* Initialize the Completion Processor. */ if (BNX2_CHIP(bp) == BNX2_CHIP_5709) fw = &bnx2_com_fw_09; else fw = &bnx2_com_fw_06; rc = load_cpu_fw(bp, &cpu_reg_com, fw); if (rc) goto init_cpu_err; /* Initialize the Command Processor. */ if (BNX2_CHIP(bp) == BNX2_CHIP_5709) fw = &bnx2_cp_fw_09; else fw = &bnx2_cp_fw_06; rc = load_cpu_fw(bp, &cpu_reg_cp, fw); if (rc) goto init_cpu_err; #if defined(__VMKLNX__) bnx2_print_fw_versions(bp); #endif init_cpu_err: bnx2_gunzip_end(bp); return rc; } static void bnx2_setup_wol(struct bnx2 *bp) { int i; u32 val, wol_msg; if (bp->wol) { u32 advertising; u8 autoneg; autoneg = bp->autoneg; advertising = bp->advertising; if (bp->phy_port == PORT_TP) { bp->autoneg = AUTONEG_SPEED; bp->advertising = ADVERTISED_10baseT_Half | ADVERTISED_10baseT_Full | ADVERTISED_100baseT_Half | ADVERTISED_100baseT_Full | ADVERTISED_Autoneg; } spin_lock_bh(&bp->phy_lock); bnx2_setup_phy(bp, bp->phy_port); spin_unlock_bh(&bp->phy_lock); bp->autoneg = autoneg; bp->advertising = advertising; bnx2_set_mac_addr(bp, bp->dev->dev_addr, 0); val = BNX2_RD(bp, BNX2_EMAC_MODE); /* Enable port mode. */ val &= ~BNX2_EMAC_MODE_PORT; val |= BNX2_EMAC_MODE_MPKT_RCVD | BNX2_EMAC_MODE_ACPI_RCVD | BNX2_EMAC_MODE_MPKT; if (bp->phy_port == PORT_TP) { val |= BNX2_EMAC_MODE_PORT_MII; } else { val |= BNX2_EMAC_MODE_PORT_GMII; if (bp->line_speed == SPEED_2500) val |= BNX2_EMAC_MODE_25G_MODE; } BNX2_WR(bp, BNX2_EMAC_MODE, val); /* receive all multicast */ for (i = 0; i < NUM_MC_HASH_REGISTERS; i++) { BNX2_WR(bp, BNX2_EMAC_MULTICAST_HASH0 + (i * 4), 0xffffffff); } BNX2_WR(bp, BNX2_EMAC_RX_MODE, BNX2_EMAC_RX_MODE_SORT_MODE); val = 1 | BNX2_RPM_SORT_USER0_BC_EN | BNX2_RPM_SORT_USER0_MC_EN; BNX2_WR(bp, BNX2_RPM_SORT_USER0, 0x0); BNX2_WR(bp, BNX2_RPM_SORT_USER0, val); BNX2_WR(bp, BNX2_RPM_SORT_USER0, val | BNX2_RPM_SORT_USER0_ENA); /* Need to enable EMAC and RPM for WOL. */ BNX2_WR(bp, BNX2_MISC_ENABLE_SET_BITS, BNX2_MISC_ENABLE_SET_BITS_RX_PARSER_MAC_ENABLE | BNX2_MISC_ENABLE_SET_BITS_TX_HEADER_Q_ENABLE | BNX2_MISC_ENABLE_SET_BITS_EMAC_ENABLE); val = BNX2_RD(bp, BNX2_RPM_CONFIG); val &= ~BNX2_RPM_CONFIG_ACPI_ENA; BNX2_WR(bp, BNX2_RPM_CONFIG, val); wol_msg = BNX2_DRV_MSG_CODE_SUSPEND_WOL; } else { wol_msg = BNX2_DRV_MSG_CODE_SUSPEND_NO_WOL; } if (!(bp->flags & BNX2_FLAG_NO_WOL)) bnx2_fw_sync(bp, BNX2_DRV_MSG_DATA_WAIT3 | wol_msg, 1, 0); } static int bnx2_set_power_state(struct bnx2 *bp, pci_power_t state) { switch (state) { case PCI_D0: { u32 val; pci_enable_wake(bp->pdev, PCI_D0, false); pci_set_power_state(bp->pdev, PCI_D0); val = BNX2_RD(bp, BNX2_EMAC_MODE); val |= BNX2_EMAC_MODE_MPKT_RCVD | BNX2_EMAC_MODE_ACPI_RCVD; val &= ~BNX2_EMAC_MODE_MPKT; BNX2_WR(bp, BNX2_EMAC_MODE, val); val = BNX2_RD(bp, BNX2_RPM_CONFIG); val &= ~BNX2_RPM_CONFIG_ACPI_ENA; BNX2_WR(bp, BNX2_RPM_CONFIG, val); break; } case PCI_D3hot: { bnx2_setup_wol(bp); pci_wake_from_d3(bp->pdev, bp->wol); if ((BNX2_CHIP_ID(bp) == BNX2_CHIP_ID_5706_A0) || (BNX2_CHIP_ID(bp) == BNX2_CHIP_ID_5706_A1)) { if (bp->wol) pci_set_power_state(bp->pdev, PCI_D3hot); } else { pci_set_power_state(bp->pdev, PCI_D3hot); } /* No more memory access after this point until * device is brought back to D0. */ break; } default: return -EINVAL; } return 0; } static int bnx2_acquire_nvram_lock(struct bnx2 *bp) { u32 val; int j; /* Request access to the flash interface. */ BNX2_WR(bp, BNX2_NVM_SW_ARB, BNX2_NVM_SW_ARB_ARB_REQ_SET2); for (j = 0; j < NVRAM_TIMEOUT_COUNT; j++) { val = BNX2_RD(bp, BNX2_NVM_SW_ARB); if (val & BNX2_NVM_SW_ARB_ARB_ARB2) break; udelay(5); } if (j >= NVRAM_TIMEOUT_COUNT) return -EBUSY; return 0; } static int bnx2_release_nvram_lock(struct bnx2 *bp) { int j; u32 val; /* Relinquish nvram interface. */ BNX2_WR(bp, BNX2_NVM_SW_ARB, BNX2_NVM_SW_ARB_ARB_REQ_CLR2); for (j = 0; j < NVRAM_TIMEOUT_COUNT; j++) { val = BNX2_RD(bp, BNX2_NVM_SW_ARB); if (!(val & BNX2_NVM_SW_ARB_ARB_ARB2)) break; udelay(5); } if (j >= NVRAM_TIMEOUT_COUNT) return -EBUSY; return 0; } static int bnx2_enable_nvram_write(struct bnx2 *bp) { u32 val; val = BNX2_RD(bp, BNX2_MISC_CFG); BNX2_WR(bp, BNX2_MISC_CFG, val | BNX2_MISC_CFG_NVM_WR_EN_PCI); if (bp->flash_info->flags & BNX2_NV_WREN) { int j; BNX2_WR(bp, BNX2_NVM_COMMAND, BNX2_NVM_COMMAND_DONE); BNX2_WR(bp, BNX2_NVM_COMMAND, BNX2_NVM_COMMAND_WREN | BNX2_NVM_COMMAND_DOIT); for (j = 0; j < NVRAM_TIMEOUT_COUNT; j++) { udelay(5); val = BNX2_RD(bp, BNX2_NVM_COMMAND); if (val & BNX2_NVM_COMMAND_DONE) break; } if (j >= NVRAM_TIMEOUT_COUNT) return -EBUSY; } return 0; } static void bnx2_disable_nvram_write(struct bnx2 *bp) { u32 val; val = BNX2_RD(bp, BNX2_MISC_CFG); BNX2_WR(bp, BNX2_MISC_CFG, val & ~BNX2_MISC_CFG_NVM_WR_EN); } static void bnx2_enable_nvram_access(struct bnx2 *bp) { u32 val; val = BNX2_RD(bp, BNX2_NVM_ACCESS_ENABLE); /* Enable both bits, even on read. */ BNX2_WR(bp, BNX2_NVM_ACCESS_ENABLE, val | BNX2_NVM_ACCESS_ENABLE_EN | BNX2_NVM_ACCESS_ENABLE_WR_EN); } static void bnx2_disable_nvram_access(struct bnx2 *bp) { u32 val; val = BNX2_RD(bp, BNX2_NVM_ACCESS_ENABLE); /* Disable both bits, even after read. */ BNX2_WR(bp, BNX2_NVM_ACCESS_ENABLE, val & ~(BNX2_NVM_ACCESS_ENABLE_EN | BNX2_NVM_ACCESS_ENABLE_WR_EN)); } static int bnx2_nvram_erase_page(struct bnx2 *bp, u32 offset) { u32 cmd; int j; if (bp->flash_info->flags & BNX2_NV_BUFFERED) /* Buffered flash, no erase needed */ return 0; /* Build an erase command */ cmd = BNX2_NVM_COMMAND_ERASE | BNX2_NVM_COMMAND_WR | BNX2_NVM_COMMAND_DOIT; /* Need to clear DONE bit separately. */ BNX2_WR(bp, BNX2_NVM_COMMAND, BNX2_NVM_COMMAND_DONE); /* Address of the NVRAM to read from. */ BNX2_WR(bp, BNX2_NVM_ADDR, offset & BNX2_NVM_ADDR_NVM_ADDR_VALUE); /* Issue an erase command. */ BNX2_WR(bp, BNX2_NVM_COMMAND, cmd); /* Wait for completion. */ for (j = 0; j < NVRAM_TIMEOUT_COUNT; j++) { u32 val; udelay(5); val = BNX2_RD(bp, BNX2_NVM_COMMAND); if (val & BNX2_NVM_COMMAND_DONE) break; } if (j >= NVRAM_TIMEOUT_COUNT) return -EBUSY; return 0; } static int bnx2_nvram_read_dword(struct bnx2 *bp, u32 offset, u8 *ret_val, u32 cmd_flags) { u32 cmd; int j; /* Build the command word. */ cmd = BNX2_NVM_COMMAND_DOIT | cmd_flags; /* Calculate an offset of a buffered flash, not needed for 5709. */ if (bp->flash_info->flags & BNX2_NV_TRANSLATE) { offset = ((offset / bp->flash_info->page_size) << bp->flash_info->page_bits) + (offset % bp->flash_info->page_size); } /* Need to clear DONE bit separately. */ BNX2_WR(bp, BNX2_NVM_COMMAND, BNX2_NVM_COMMAND_DONE); /* Address of the NVRAM to read from. */ BNX2_WR(bp, BNX2_NVM_ADDR, offset & BNX2_NVM_ADDR_NVM_ADDR_VALUE); /* Issue a read command. */ BNX2_WR(bp, BNX2_NVM_COMMAND, cmd); /* Wait for completion. */ for (j = 0; j < NVRAM_TIMEOUT_COUNT; j++) { u32 val; udelay(5); val = BNX2_RD(bp, BNX2_NVM_COMMAND); if (val & BNX2_NVM_COMMAND_DONE) { __be32 v = cpu_to_be32(BNX2_RD(bp, BNX2_NVM_READ)); memcpy(ret_val, &v, 4); break; } } if (j >= NVRAM_TIMEOUT_COUNT) return -EBUSY; return 0; } static int bnx2_nvram_write_dword(struct bnx2 *bp, u32 offset, u8 *val, u32 cmd_flags) { u32 cmd; __be32 val32; int j; /* Build the command word. */ cmd = BNX2_NVM_COMMAND_DOIT | BNX2_NVM_COMMAND_WR | cmd_flags; /* Calculate an offset of a buffered flash, not needed for 5709. */ if (bp->flash_info->flags & BNX2_NV_TRANSLATE) { offset = ((offset / bp->flash_info->page_size) << bp->flash_info->page_bits) + (offset % bp->flash_info->page_size); } /* Need to clear DONE bit separately. */ BNX2_WR(bp, BNX2_NVM_COMMAND, BNX2_NVM_COMMAND_DONE); memcpy(&val32, val, 4); /* Write the data. */ BNX2_WR(bp, BNX2_NVM_WRITE, be32_to_cpu(val32)); /* Address of the NVRAM to write to. */ BNX2_WR(bp, BNX2_NVM_ADDR, offset & BNX2_NVM_ADDR_NVM_ADDR_VALUE); /* Issue the write command. */ BNX2_WR(bp, BNX2_NVM_COMMAND, cmd); /* Wait for completion. */ for (j = 0; j < NVRAM_TIMEOUT_COUNT; j++) { udelay(5); if (BNX2_RD(bp, BNX2_NVM_COMMAND) & BNX2_NVM_COMMAND_DONE) break; } if (j >= NVRAM_TIMEOUT_COUNT) return -EBUSY; return 0; } static int bnx2_init_nvram(struct bnx2 *bp) { u32 val; int j, entry_count, rc = 0; const struct flash_spec *flash; if (BNX2_CHIP(bp) == BNX2_CHIP_5709) { bp->flash_info = &flash_5709; goto get_flash_size; } /* Determine the selected interface. */ val = BNX2_RD(bp, BNX2_NVM_CFG1); entry_count = ARRAY_SIZE(flash_table); if (val & 0x40000000) { /* Flash interface has been reconfigured */ for (j = 0, flash = &flash_table[0]; j < entry_count; j++, flash++) { if ((val & FLASH_BACKUP_STRAP_MASK) == (flash->config1 & FLASH_BACKUP_STRAP_MASK)) { bp->flash_info = flash; break; } } } else { u32 mask; /* Not yet been reconfigured */ if (val & (1 << 23)) mask = FLASH_BACKUP_STRAP_MASK; else mask = FLASH_STRAP_MASK; for (j = 0, flash = &flash_table[0]; j < entry_count; j++, flash++) { if ((val & mask) == (flash->strapping & mask)) { bp->flash_info = flash; /* Request access to the flash interface. */ if ((rc = bnx2_acquire_nvram_lock(bp)) != 0) return rc; /* Enable access to flash interface */ bnx2_enable_nvram_access(bp); /* Reconfigure the flash interface */ BNX2_WR(bp, BNX2_NVM_CFG1, flash->config1); BNX2_WR(bp, BNX2_NVM_CFG2, flash->config2); BNX2_WR(bp, BNX2_NVM_CFG3, flash->config3); BNX2_WR(bp, BNX2_NVM_WRITE1, flash->write1); /* Disable access to flash interface */ bnx2_disable_nvram_access(bp); bnx2_release_nvram_lock(bp); break; } } } /* if (val & 0x40000000) */ if (j == entry_count) { bp->flash_info = NULL; pr_alert("Unknown flash/EEPROM type\n"); return -ENODEV; } get_flash_size: val = bnx2_shmem_rd(bp, BNX2_SHARED_HW_CFG_CONFIG2); val &= BNX2_SHARED_HW_CFG2_NVM_SIZE_MASK; if (val) bp->flash_size = val; else bp->flash_size = bp->flash_info->total_size; return rc; } static int bnx2_nvram_read(struct bnx2 *bp, u32 offset, u8 *ret_buf, int buf_size) { int rc = 0; u32 cmd_flags, offset32, len32, extra; if (buf_size == 0) return 0; /* Request access to the flash interface. */ if ((rc = bnx2_acquire_nvram_lock(bp)) != 0) return rc; /* Enable access to flash interface */ bnx2_enable_nvram_access(bp); len32 = buf_size; offset32 = offset; extra = 0; cmd_flags = 0; if (offset32 & 3) { u8 buf[4]; u32 pre_len; offset32 &= ~3; pre_len = 4 - (offset & 3); if (pre_len >= len32) { pre_len = len32; cmd_flags = BNX2_NVM_COMMAND_FIRST | BNX2_NVM_COMMAND_LAST; } else { cmd_flags = BNX2_NVM_COMMAND_FIRST; } rc = bnx2_nvram_read_dword(bp, offset32, buf, cmd_flags); if (rc) return rc; memcpy(ret_buf, buf + (offset & 3), pre_len); offset32 += 4; ret_buf += pre_len; len32 -= pre_len; } if (len32 & 3) { extra = 4 - (len32 & 3); len32 = (len32 + 4) & ~3; } if (len32 == 4) { u8 buf[4]; if (cmd_flags) cmd_flags = BNX2_NVM_COMMAND_LAST; else cmd_flags = BNX2_NVM_COMMAND_FIRST | BNX2_NVM_COMMAND_LAST; rc = bnx2_nvram_read_dword(bp, offset32, buf, cmd_flags); memcpy(ret_buf, buf, 4 - extra); } else if (len32 > 0) { u8 buf[4]; /* Read the first word. */ if (cmd_flags) cmd_flags = 0; else cmd_flags = BNX2_NVM_COMMAND_FIRST; rc = bnx2_nvram_read_dword(bp, offset32, ret_buf, cmd_flags); /* Advance to the next dword. */ offset32 += 4; ret_buf += 4; len32 -= 4; while (len32 > 4 && rc == 0) { rc = bnx2_nvram_read_dword(bp, offset32, ret_buf, 0); /* Advance to the next dword. */ offset32 += 4; ret_buf += 4; len32 -= 4; } if (rc) return rc; cmd_flags = BNX2_NVM_COMMAND_LAST; rc = bnx2_nvram_read_dword(bp, offset32, buf, cmd_flags); memcpy(ret_buf, buf, 4 - extra); } /* Disable access to flash interface */ bnx2_disable_nvram_access(bp); bnx2_release_nvram_lock(bp); return rc; } static int bnx2_nvram_write(struct bnx2 *bp, u32 offset, u8 *data_buf, int buf_size) { u32 written, offset32, len32; u8 *buf, start[4], end[4], *align_buf = NULL, *flash_buffer = NULL; int rc = 0; int align_start, align_end; buf = data_buf; offset32 = offset; len32 = buf_size; align_start = align_end = 0; if ((align_start = (offset32 & 3))) { offset32 &= ~3; len32 += align_start; if (len32 < 4) len32 = 4; if ((rc = bnx2_nvram_read(bp, offset32, start, 4))) return rc; } if (len32 & 3) { align_end = 4 - (len32 & 3); len32 += align_end; if ((rc = bnx2_nvram_read(bp, offset32 + len32 - 4, end, 4))) return rc; } if (align_start || align_end) { align_buf = kmalloc(len32, GFP_KERNEL); if (align_buf == NULL) return -ENOMEM; if (align_start) { memcpy(align_buf, start, 4); } if (align_end) { memcpy(align_buf + len32 - 4, end, 4); } memcpy(align_buf + align_start, data_buf, buf_size); buf = align_buf; } if (!(bp->flash_info->flags & BNX2_NV_BUFFERED)) { flash_buffer = kmalloc(264, GFP_KERNEL); if (flash_buffer == NULL) { rc = -ENOMEM; goto nvram_write_end; } } written = 0; while ((written < len32) && (rc == 0)) { u32 page_start, page_end, data_start, data_end; u32 addr, cmd_flags; int i; /* Find the page_start addr */ page_start = offset32 + written; page_start -= (page_start % bp->flash_info->page_size); /* Find the page_end addr */ page_end = page_start + bp->flash_info->page_size; /* Find the data_start addr */ data_start = (written == 0) ? offset32 : page_start; /* Find the data_end addr */ data_end = (page_end > offset32 + len32) ? (offset32 + len32) : page_end; /* Request access to the flash interface. */ if ((rc = bnx2_acquire_nvram_lock(bp)) != 0) goto nvram_write_end; /* Enable access to flash interface */ bnx2_enable_nvram_access(bp); cmd_flags = BNX2_NVM_COMMAND_FIRST; if (!(bp->flash_info->flags & BNX2_NV_BUFFERED)) { int j; /* Read the whole page into the buffer * (non-buffer flash only) */ for (j = 0; j < bp->flash_info->page_size; j += 4) { if (j == (bp->flash_info->page_size - 4)) { cmd_flags |= BNX2_NVM_COMMAND_LAST; } rc = bnx2_nvram_read_dword(bp, page_start + j, &flash_buffer[j], cmd_flags); if (rc) goto nvram_write_end; cmd_flags = 0; } } /* Enable writes to flash interface (unlock write-protect) */ if ((rc = bnx2_enable_nvram_write(bp)) != 0) goto nvram_write_end; /* Loop to write back the buffer data from page_start to * data_start */ i = 0; if (!(bp->flash_info->flags & BNX2_NV_BUFFERED)) { /* Erase the page */ if ((rc = bnx2_nvram_erase_page(bp, page_start)) != 0) goto nvram_write_end; /* Re-enable the write again for the actual write */ bnx2_enable_nvram_write(bp); for (addr = page_start; addr < data_start; addr += 4, i += 4) { rc = bnx2_nvram_write_dword(bp, addr, &flash_buffer[i], cmd_flags); if (rc != 0) goto nvram_write_end; cmd_flags = 0; } } /* Loop to write the new data from data_start to data_end */ for (addr = data_start; addr < data_end; addr += 4, i += 4) { if ((addr == page_end - 4) || ((bp->flash_info->flags & BNX2_NV_BUFFERED) && (addr == data_end - 4))) { cmd_flags |= BNX2_NVM_COMMAND_LAST; } rc = bnx2_nvram_write_dword(bp, addr, buf, cmd_flags); if (rc != 0) goto nvram_write_end; cmd_flags = 0; buf += 4; } /* Loop to write back the buffer data from data_end * to page_end */ if (!(bp->flash_info->flags & BNX2_NV_BUFFERED)) { for (addr = data_end; addr < page_end; addr += 4, i += 4) { if (addr == page_end-4) { cmd_flags = BNX2_NVM_COMMAND_LAST; } rc = bnx2_nvram_write_dword(bp, addr, &flash_buffer[i], cmd_flags); if (rc != 0) goto nvram_write_end; cmd_flags = 0; } } /* Disable writes to flash interface (lock write-protect) */ bnx2_disable_nvram_write(bp); /* Disable access to flash interface */ bnx2_disable_nvram_access(bp); bnx2_release_nvram_lock(bp); /* Increment written */ written += data_end - data_start; } nvram_write_end: kfree(flash_buffer); kfree(align_buf); return rc; } static void bnx2_init_fw_cap(struct bnx2 *bp) { u32 val, sig = 0; bp->phy_flags &= ~BNX2_PHY_FLAG_REMOTE_PHY_CAP; bp->flags &= ~BNX2_FLAG_CAN_KEEP_VLAN; if (!(bp->flags & BNX2_FLAG_ASF_ENABLE)) bp->flags |= BNX2_FLAG_CAN_KEEP_VLAN; val = bnx2_shmem_rd(bp, BNX2_FW_CAP_MB); if ((val & BNX2_FW_CAP_SIGNATURE_MASK) != BNX2_FW_CAP_SIGNATURE) return; if ((val & BNX2_FW_CAP_CAN_KEEP_VLAN) == BNX2_FW_CAP_CAN_KEEP_VLAN) { bp->flags |= BNX2_FLAG_CAN_KEEP_VLAN; sig |= BNX2_DRV_ACK_CAP_SIGNATURE | BNX2_FW_CAP_CAN_KEEP_VLAN; } if ((bp->phy_flags & BNX2_PHY_FLAG_SERDES) && (val & BNX2_FW_CAP_REMOTE_PHY_CAPABLE)) { u32 link; bp->phy_flags |= BNX2_PHY_FLAG_REMOTE_PHY_CAP; link = bnx2_shmem_rd(bp, BNX2_LINK_STATUS); if (link & BNX2_LINK_STATUS_SERDES_LINK) bp->phy_port = PORT_FIBRE; else bp->phy_port = PORT_TP; sig |= BNX2_DRV_ACK_CAP_SIGNATURE | BNX2_FW_CAP_REMOTE_PHY_CAPABLE; } if (netif_running(bp->dev) && sig) bnx2_shmem_wr(bp, BNX2_DRV_ACK_CAP_MB, sig); } #if defined(__VMKLNX__) static void bnx2_setup_msix_tbl_cfg(struct bnx2 *bp) { bnx2_reg_wr_ind_cfg(bp, BNX2_PCI_GRC_WINDOW_ADDR, BNX2_PCI_GRC_WINDOW_ADDR_SEP_WIN); bnx2_reg_wr_ind_cfg(bp, BNX2_PCI_GRC_WINDOW2_ADDR, BNX2_MSIX_TABLE_ADDR); bnx2_reg_wr_ind_cfg(bp, BNX2_PCI_GRC_WINDOW3_ADDR, BNX2_MSIX_PBA_ADDR); } #endif /* defined(__VMKLNX__) */ static void bnx2_setup_msix_tbl(struct bnx2 *bp) { BNX2_WR(bp, BNX2_PCI_GRC_WINDOW_ADDR, BNX2_PCI_GRC_WINDOW_ADDR_SEP_WIN); BNX2_WR(bp, BNX2_PCI_GRC_WINDOW2_ADDR, BNX2_MSIX_TABLE_ADDR); BNX2_WR(bp, BNX2_PCI_GRC_WINDOW3_ADDR, BNX2_MSIX_PBA_ADDR); } static int bnx2_reset_chip(struct bnx2 *bp, u32 reset_code) { u32 val; int i, rc = 0; u8 old_port; /* Wait for the current PCI transaction to complete before * issuing a reset. */ if ((BNX2_CHIP(bp) == BNX2_CHIP_5706) || (BNX2_CHIP(bp) == BNX2_CHIP_5708)) { BNX2_WR(bp, BNX2_MISC_ENABLE_CLR_BITS, BNX2_MISC_ENABLE_CLR_BITS_TX_DMA_ENABLE | BNX2_MISC_ENABLE_CLR_BITS_DMA_ENGINE_ENABLE | BNX2_MISC_ENABLE_CLR_BITS_RX_DMA_ENABLE | BNX2_MISC_ENABLE_CLR_BITS_HOST_COALESCE_ENABLE); val = BNX2_RD(bp, BNX2_MISC_ENABLE_CLR_BITS); udelay(5); } else { /* 5709 */ val = BNX2_RD(bp, BNX2_MISC_NEW_CORE_CTL); val &= ~BNX2_MISC_NEW_CORE_CTL_DMA_ENABLE; BNX2_WR(bp, BNX2_MISC_NEW_CORE_CTL, val); val = BNX2_RD(bp, BNX2_MISC_NEW_CORE_CTL); for (i = 0; i < 100; i++) { bnx2_msleep(1); val = BNX2_RD(bp, BNX2_PCICFG_DEVICE_CONTROL); if (!(val & BNX2_PCICFG_DEVICE_STATUS_NO_PEND)) break; } } /* Wait for the firmware to tell us it is ok to issue a reset. */ bnx2_fw_sync(bp, BNX2_DRV_MSG_DATA_WAIT0 | reset_code, 1, 1); /* Deposit a driver reset signature so the firmware knows that * this is a soft reset. */ bnx2_shmem_wr(bp, BNX2_DRV_RESET_SIGNATURE, BNX2_DRV_RESET_SIGNATURE_MAGIC); #if defined(__VMKLNX__) #if (LINUX_VERSION_CODE >= 0x020611) pci_save_state(bp->pdev); #endif #endif /* defined(__VMKLNX__) */ /* Do a dummy read to force the chip to complete all current transaction * before we issue a reset. */ val = BNX2_RD(bp, BNX2_MISC_ID); if (BNX2_CHIP(bp) == BNX2_CHIP_5709) { BNX2_WR(bp, BNX2_MISC_COMMAND, BNX2_MISC_COMMAND_SW_RESET); BNX2_RD(bp, BNX2_MISC_COMMAND); udelay(5); val = BNX2_PCICFG_MISC_CONFIG_REG_WINDOW_ENA | BNX2_PCICFG_MISC_CONFIG_TARGET_MB_WORD_SWAP; BNX2_WR(bp, BNX2_PCICFG_MISC_CONFIG, val); } else { val = BNX2_PCICFG_MISC_CONFIG_CORE_RST_REQ | BNX2_PCICFG_MISC_CONFIG_REG_WINDOW_ENA | BNX2_PCICFG_MISC_CONFIG_TARGET_MB_WORD_SWAP; /* Chip reset. */ BNX2_WR(bp, BNX2_PCICFG_MISC_CONFIG, val); /* Reading back any register after chip reset will hang the * bus on 5706 A0 and A1. The msleep below provides plenty * of margin for write posting. */ if ((BNX2_CHIP_ID(bp) == BNX2_CHIP_ID_5706_A0) || (BNX2_CHIP_ID(bp) == BNX2_CHIP_ID_5706_A1)) bnx2_msleep(20); /* Reset takes approximate 30 usec */ for (i = 0; i < 10; i++) { val = BNX2_RD(bp, BNX2_PCICFG_MISC_CONFIG); if ((val & (BNX2_PCICFG_MISC_CONFIG_CORE_RST_REQ | BNX2_PCICFG_MISC_CONFIG_CORE_RST_BSY)) == 0) break; udelay(10); } if (val & (BNX2_PCICFG_MISC_CONFIG_CORE_RST_REQ | BNX2_PCICFG_MISC_CONFIG_CORE_RST_BSY)) { pr_err("Chip reset did not complete\n"); return -EBUSY; } } #if defined(__VMKLNX__) if (bp->flags & BNX2_FLAG_USING_MSIX) bnx2_setup_msix_tbl_cfg(bp); #if (LINUX_VERSION_CODE >= 0x020611) pci_restore_state(bp->pdev); #endif #endif /* defined(__VMKLNX__) */ /* Make sure byte swapping is properly configured. */ val = BNX2_RD(bp, BNX2_PCI_SWAP_DIAG0); if (val != 0x01020304) { pr_err("Chip not in correct endian mode\n"); return -ENODEV; } /* Wait for the firmware to finish its initialization. */ rc = bnx2_fw_sync(bp, BNX2_DRV_MSG_DATA_WAIT1 | reset_code, 1, 0); if (rc) return rc; spin_lock_bh(&bp->phy_lock); old_port = bp->phy_port; bnx2_init_fw_cap(bp); if ((bp->phy_flags & BNX2_PHY_FLAG_REMOTE_PHY_CAP) && old_port != bp->phy_port) bnx2_set_default_remote_link(bp); spin_unlock_bh(&bp->phy_lock); if (BNX2_CHIP_ID(bp) == BNX2_CHIP_ID_5706_A0) { /* Adjust the voltage regular to two steps lower. The default * of this register is 0x0000000e. */ BNX2_WR(bp, BNX2_MISC_VREG_CONTROL, 0x000000fa); /* Remove bad rbuf memory from the free pool. */ rc = bnx2_alloc_bad_rbuf(bp); } if (bp->flags & BNX2_FLAG_USING_MSIX) { bnx2_setup_msix_tbl(bp); /* Prevent MSIX table reads and write from timing out */ BNX2_WR(bp, BNX2_MISC_ECO_HW_CTL, BNX2_MISC_ECO_HW_CTL_LARGE_GRC_TMOUT_EN); } return rc; } static int bnx2_init_chip(struct bnx2 *bp) { u32 val, mtu; int rc, i; /* Make sure the interrupt is not active. */ BNX2_WR(bp, BNX2_PCICFG_INT_ACK_CMD, BNX2_PCICFG_INT_ACK_CMD_MASK_INT); val = BNX2_DMA_CONFIG_DATA_BYTE_SWAP | BNX2_DMA_CONFIG_DATA_WORD_SWAP | #ifdef __BIG_ENDIAN BNX2_DMA_CONFIG_CNTL_BYTE_SWAP | #endif BNX2_DMA_CONFIG_CNTL_WORD_SWAP | DMA_READ_CHANS << 12 | DMA_WRITE_CHANS << 16; val |= (0x2 << 20) | (1 << 11); if ((bp->flags & BNX2_FLAG_PCIX) && (bp->bus_speed_mhz == 133)) val |= (1 << 23); if ((BNX2_CHIP(bp) == BNX2_CHIP_5706) && (BNX2_CHIP_ID(bp) != BNX2_CHIP_ID_5706_A0) && !(bp->flags & BNX2_FLAG_PCIX)) val |= BNX2_DMA_CONFIG_CNTL_PING_PONG_DMA; BNX2_WR(bp, BNX2_DMA_CONFIG, val); if (BNX2_CHIP_ID(bp) == BNX2_CHIP_ID_5706_A0) { val = BNX2_RD(bp, BNX2_TDMA_CONFIG); val |= BNX2_TDMA_CONFIG_ONE_DMA; BNX2_WR(bp, BNX2_TDMA_CONFIG, val); } if (bp->flags & BNX2_FLAG_PCIX) { u16 val16; pci_read_config_word(bp->pdev, bp->pcix_cap + PCI_X_CMD, &val16); pci_write_config_word(bp->pdev, bp->pcix_cap + PCI_X_CMD, val16 & ~PCI_X_CMD_ERO); } BNX2_WR(bp, BNX2_MISC_ENABLE_SET_BITS, BNX2_MISC_ENABLE_SET_BITS_HOST_COALESCE_ENABLE | BNX2_MISC_ENABLE_STATUS_BITS_RX_V2P_ENABLE | BNX2_MISC_ENABLE_STATUS_BITS_CONTEXT_ENABLE); /* Initialize context mapping and zero out the quick contexts. The * context block must have already been enabled. */ if (BNX2_CHIP(bp) == BNX2_CHIP_5709) { rc = bnx2_init_5709_context(bp); if (rc) return rc; } else bnx2_init_context(bp); if ((rc = bnx2_init_cpus(bp)) != 0) return rc; bnx2_init_nvram(bp); bnx2_set_mac_addr(bp, bp->dev->dev_addr, 0); val = BNX2_RD(bp, BNX2_MQ_CONFIG); val &= ~BNX2_MQ_CONFIG_KNL_BYP_BLK_SIZE; val |= BNX2_MQ_CONFIG_KNL_BYP_BLK_SIZE_256; if (BNX2_CHIP(bp) == BNX2_CHIP_5709) { val |= BNX2_MQ_CONFIG_BIN_MQ_MODE; if (BNX2_CHIP_REV(bp) == BNX2_CHIP_REV_Ax) val |= BNX2_MQ_CONFIG_HALT_DIS; } BNX2_WR(bp, BNX2_MQ_CONFIG, val); val = 0x10000 + (MAX_CID_CNT * MB_KERNEL_CTX_SIZE); BNX2_WR(bp, BNX2_MQ_KNL_BYP_WIND_START, val); BNX2_WR(bp, BNX2_MQ_KNL_WIND_END, val); val = (BNX2_PAGE_BITS - 8) << 24; BNX2_WR(bp, BNX2_RV2P_CONFIG, val); /* Configure page size. */ val = BNX2_RD(bp, BNX2_TBDR_CONFIG); val &= ~BNX2_TBDR_CONFIG_PAGE_SIZE; val |= (BNX2_PAGE_BITS - 8) << 24 | 0x40; BNX2_WR(bp, BNX2_TBDR_CONFIG, val); val = bp->mac_addr[0] + (bp->mac_addr[1] << 8) + (bp->mac_addr[2] << 16) + bp->mac_addr[3] + (bp->mac_addr[4] << 8) + (bp->mac_addr[5] << 16); BNX2_WR(bp, BNX2_EMAC_BACKOFF_SEED, val); /* Program the MTU. Also include 4 bytes for CRC32. */ mtu = bp->dev->mtu; val = mtu + ETH_HLEN + ETH_FCS_LEN; if (val > (MAX_ETHERNET_PACKET_SIZE + 4)) val |= BNX2_EMAC_RX_MTU_SIZE_JUMBO_ENA; BNX2_WR(bp, BNX2_EMAC_RX_MTU_SIZE, val); if (mtu < 1500) mtu = 1500; bnx2_reg_wr_ind(bp, BNX2_RBUF_CONFIG, BNX2_RBUF_CONFIG_VAL(mtu)); bnx2_reg_wr_ind(bp, BNX2_RBUF_CONFIG2, BNX2_RBUF_CONFIG2_VAL(mtu)); bnx2_reg_wr_ind(bp, BNX2_RBUF_CONFIG3, BNX2_RBUF_CONFIG3_VAL(mtu)); memset(bp->bnx2_napi[0].status_blk.msi, 0, bp->status_stats_size); for (i = 0; i < BNX2_MAX_MSIX_VEC; i++) bp->bnx2_napi[i].last_status_idx = 0; bp->idle_chk_status_idx = 0xffff; bp->rx_mode = BNX2_EMAC_RX_MODE_SORT_MODE; /* Set up how to generate a link change interrupt. */ BNX2_WR(bp, BNX2_EMAC_ATTENTION_ENA, BNX2_EMAC_ATTENTION_ENA_LINK); BNX2_WR(bp, BNX2_HC_STATUS_ADDR_L, (u64) bp->status_blk_mapping & 0xffffffff); BNX2_WR(bp, BNX2_HC_STATUS_ADDR_H, (u64) bp->status_blk_mapping >> 32); BNX2_WR(bp, BNX2_HC_STATISTICS_ADDR_L, (u64) bp->stats_blk_mapping & 0xffffffff); BNX2_WR(bp, BNX2_HC_STATISTICS_ADDR_H, (u64) bp->stats_blk_mapping >> 32); BNX2_WR(bp, BNX2_HC_TX_QUICK_CONS_TRIP, (bp->tx_quick_cons_trip_int << 16) | bp->tx_quick_cons_trip); BNX2_WR(bp, BNX2_HC_RX_QUICK_CONS_TRIP, (bp->rx_quick_cons_trip_int << 16) | bp->rx_quick_cons_trip); BNX2_WR(bp, BNX2_HC_COMP_PROD_TRIP, (bp->comp_prod_trip_int << 16) | bp->comp_prod_trip); BNX2_WR(bp, BNX2_HC_TX_TICKS, (bp->tx_ticks_int << 16) | bp->tx_ticks); BNX2_WR(bp, BNX2_HC_RX_TICKS, (bp->rx_ticks_int << 16) | bp->rx_ticks); BNX2_WR(bp, BNX2_HC_COM_TICKS, (bp->com_ticks_int << 16) | bp->com_ticks); BNX2_WR(bp, BNX2_HC_CMD_TICKS, (bp->cmd_ticks_int << 16) | bp->cmd_ticks); if (bp->flags & BNX2_FLAG_BROKEN_STATS) BNX2_WR(bp, BNX2_HC_STATS_TICKS, 0); else BNX2_WR(bp, BNX2_HC_STATS_TICKS, bp->stats_ticks); BNX2_WR(bp, BNX2_HC_STAT_COLLECT_TICKS, 0xbb8); /* 3ms */ if (BNX2_CHIP_ID(bp) == BNX2_CHIP_ID_5706_A1) val = BNX2_HC_CONFIG_COLLECT_STATS; else { val = BNX2_HC_CONFIG_RX_TMR_MODE | BNX2_HC_CONFIG_TX_TMR_MODE | BNX2_HC_CONFIG_COLLECT_STATS; } if (bp->flags & BNX2_FLAG_USING_MSIX) { BNX2_WR(bp, BNX2_HC_MSIX_BIT_VECTOR, BNX2_HC_MSIX_BIT_VECTOR_VAL); val |= BNX2_HC_CONFIG_SB_ADDR_INC_128B; } if (bp->flags & BNX2_FLAG_ONE_SHOT_MSI) val |= BNX2_HC_CONFIG_ONE_SHOT | BNX2_HC_CONFIG_USE_INT_PARAM; BNX2_WR(bp, BNX2_HC_CONFIG, val); if (bp->rx_ticks < 25) bnx2_reg_wr_ind(bp, BNX2_FW_RX_LOW_LATENCY, 1); else bnx2_reg_wr_ind(bp, BNX2_FW_RX_LOW_LATENCY, 0); for (i = 1; i < bp->irq_nvecs; i++) { u32 base = ((i - 1) * BNX2_HC_SB_CONFIG_SIZE) + BNX2_HC_SB_CONFIG_1; BNX2_WR(bp, base, BNX2_HC_SB_CONFIG_1_TX_TMR_MODE | BNX2_HC_SB_CONFIG_1_RX_TMR_MODE | BNX2_HC_SB_CONFIG_1_ONE_SHOT); BNX2_WR(bp, base + BNX2_HC_TX_QUICK_CONS_TRIP_OFF, (bp->tx_quick_cons_trip_int << 16) | bp->tx_quick_cons_trip); BNX2_WR(bp, base + BNX2_HC_TX_TICKS_OFF, (bp->tx_ticks_int << 16) | bp->tx_ticks); BNX2_WR(bp, base + BNX2_HC_RX_QUICK_CONS_TRIP_OFF, (bp->rx_quick_cons_trip_int << 16) | bp->rx_quick_cons_trip); BNX2_WR(bp, base + BNX2_HC_RX_TICKS_OFF, (bp->rx_ticks_int << 16) | bp->rx_ticks); } /* Clear internal stats counters. */ BNX2_WR(bp, BNX2_HC_COMMAND, BNX2_HC_COMMAND_CLR_STAT_NOW); BNX2_WR(bp, BNX2_HC_ATTN_BITS_ENABLE, STATUS_ATTN_EVENTS); /* Initialize the receive filter. */ bnx2_set_rx_mode(bp->dev); if (BNX2_CHIP(bp) == BNX2_CHIP_5709) { val = BNX2_RD(bp, BNX2_MISC_NEW_CORE_CTL); val |= BNX2_MISC_NEW_CORE_CTL_DMA_ENABLE; BNX2_WR(bp, BNX2_MISC_NEW_CORE_CTL, val); } rc = bnx2_fw_sync(bp, BNX2_DRV_MSG_DATA_WAIT2 | BNX2_DRV_MSG_CODE_RESET, 1, 0); BNX2_WR(bp, BNX2_MISC_ENABLE_SET_BITS, BNX2_MISC_ENABLE_DEFAULT); BNX2_RD(bp, BNX2_MISC_ENABLE_SET_BITS); udelay(20); bp->hc_cmd = BNX2_RD(bp, BNX2_HC_COMMAND); return rc; } static void bnx2_clear_ring_states(struct bnx2 *bp) { struct bnx2_napi *bnapi; struct bnx2_tx_ring_info *txr; struct bnx2_rx_ring_info *rxr; int i; for (i = 0; i < BNX2_MAX_MSIX_VEC; i++) { bnapi = &bp->bnx2_napi[i]; txr = &bnapi->tx_ring; rxr = &bnapi->rx_ring; txr->tx_cons = 0; txr->hw_tx_cons = 0; rxr->rx_prod_bseq = 0; rxr->rx_prod = 0; rxr->rx_cons = 0; rxr->rx_pg_prod = 0; rxr->rx_pg_cons = 0; } } static void bnx2_init_tx_context(struct bnx2 *bp, u32 cid, struct bnx2_tx_ring_info *txr) { u32 val, offset0, offset1, offset2, offset3; u32 cid_addr = GET_CID_ADDR(cid); if (BNX2_CHIP(bp) == BNX2_CHIP_5709) { offset0 = BNX2_L2CTX_TYPE_XI; offset1 = BNX2_L2CTX_CMD_TYPE_XI; offset2 = BNX2_L2CTX_TBDR_BHADDR_HI_XI; offset3 = BNX2_L2CTX_TBDR_BHADDR_LO_XI; } else { offset0 = BNX2_L2CTX_TYPE; offset1 = BNX2_L2CTX_CMD_TYPE; offset2 = BNX2_L2CTX_TBDR_BHADDR_HI; offset3 = BNX2_L2CTX_TBDR_BHADDR_LO; } val = BNX2_L2CTX_TYPE_TYPE_L2 | BNX2_L2CTX_TYPE_SIZE_L2; bnx2_ctx_wr(bp, cid_addr, offset0, val); val = BNX2_L2CTX_CMD_TYPE_TYPE_L2 | (8 << 16); bnx2_ctx_wr(bp, cid_addr, offset1, val); val = (u64) txr->tx_desc_mapping >> 32; bnx2_ctx_wr(bp, cid_addr, offset2, val); val = (u64) txr->tx_desc_mapping & 0xffffffff; bnx2_ctx_wr(bp, cid_addr, offset3, val); } static void bnx2_init_tx_ring(struct bnx2 *bp, int ring_num) { struct bnx2_tx_bd *txbd; u32 cid = TX_CID; struct bnx2_napi *bnapi; struct bnx2_tx_ring_info *txr; bnapi = &bp->bnx2_napi[ring_num]; txr = &bnapi->tx_ring; if (ring_num == 0) cid = TX_CID; else cid = TX_TSS_CID + ring_num - 1; bp->tx_wake_thresh = bp->tx_ring_size / 2; txbd = &txr->tx_desc_ring[BNX2_MAX_TX_DESC_CNT]; txbd->tx_bd_haddr_hi = (u64) txr->tx_desc_mapping >> 32; txbd->tx_bd_haddr_lo = (u64) txr->tx_desc_mapping & 0xffffffff; txr->tx_prod = 0; txr->tx_prod_bseq = 0; txr->tx_bidx_addr = MB_GET_CID_ADDR(cid) + BNX2_L2CTX_TX_HOST_BIDX; txr->tx_bseq_addr = MB_GET_CID_ADDR(cid) + BNX2_L2CTX_TX_HOST_BSEQ; bnx2_init_tx_context(bp, cid, txr); } static void bnx2_init_rxbd_rings(struct bnx2_rx_bd *rx_ring[], dma_addr_t dma[], u32 buf_size, int num_rings) { int i; struct bnx2_rx_bd *rxbd; for (i = 0; i < num_rings; i++) { int j; rxbd = &rx_ring[i][0]; for (j = 0; j < BNX2_MAX_RX_DESC_CNT; j++, rxbd++) { rxbd->rx_bd_len = buf_size; rxbd->rx_bd_flags = RX_BD_FLAGS_START | RX_BD_FLAGS_END; } if (i == (num_rings - 1)) j = 0; else j = i + 1; rxbd->rx_bd_haddr_hi = (u64) dma[j] >> 32; rxbd->rx_bd_haddr_lo = (u64) dma[j] & 0xffffffff; } } static void bnx2_init_rx_ring(struct bnx2 *bp, int ring_num) { int i; u16 prod, ring_prod; u32 cid, rx_cid_addr, val; struct bnx2_napi *bnapi = &bp->bnx2_napi[ring_num]; struct bnx2_rx_ring_info *rxr = &bnapi->rx_ring; if (ring_num == 0) cid = RX_CID; else cid = RX_RSS_CID + ring_num - 1; rx_cid_addr = GET_CID_ADDR(cid); bnx2_init_rxbd_rings(rxr->rx_desc_ring, rxr->rx_desc_mapping, bp->rx_buf_use_size, bp->rx_max_ring); bnx2_init_rx_context(bp, cid); if (BNX2_CHIP(bp) == BNX2_CHIP_5709) { val = BNX2_RD(bp, BNX2_MQ_MAP_L2_5); BNX2_WR(bp, BNX2_MQ_MAP_L2_5, val | BNX2_MQ_MAP_L2_5_ARM); #if defined(BNX2_ENABLE_NETQUEUE) /* Set in the RX context the proper CID location * for the completion */ if(BNX2_NETQUEUE_ENABLED(bp)) bnx2_ctx_wr(bp, rx_cid_addr, 0x04, 1 << 16); #endif } bnx2_ctx_wr(bp, rx_cid_addr, BNX2_L2CTX_PG_BUF_SIZE, 0); if (bp->rx_pg_ring_size) { bnx2_init_rxbd_rings(rxr->rx_pg_desc_ring, rxr->rx_pg_desc_mapping, PAGE_SIZE, bp->rx_max_pg_ring); val = (bp->rx_buf_use_size << 16) | PAGE_SIZE; bnx2_ctx_wr(bp, rx_cid_addr, BNX2_L2CTX_PG_BUF_SIZE, val); bnx2_ctx_wr(bp, rx_cid_addr, BNX2_L2CTX_RBDC_KEY, BNX2_L2CTX_RBDC_JUMBO_KEY - ring_num); val = (u64) rxr->rx_pg_desc_mapping[0] >> 32; bnx2_ctx_wr(bp, rx_cid_addr, BNX2_L2CTX_NX_PG_BDHADDR_HI, val); val = (u64) rxr->rx_pg_desc_mapping[0] & 0xffffffff; bnx2_ctx_wr(bp, rx_cid_addr, BNX2_L2CTX_NX_PG_BDHADDR_LO, val); if (BNX2_CHIP(bp) == BNX2_CHIP_5709) BNX2_WR(bp, BNX2_MQ_MAP_L2_3, BNX2_MQ_MAP_L2_3_DEFAULT); } val = (u64) rxr->rx_desc_mapping[0] >> 32; bnx2_ctx_wr(bp, rx_cid_addr, BNX2_L2CTX_NX_BDHADDR_HI, val); val = (u64) rxr->rx_desc_mapping[0] & 0xffffffff; bnx2_ctx_wr(bp, rx_cid_addr, BNX2_L2CTX_NX_BDHADDR_LO, val); ring_prod = prod = rxr->rx_pg_prod; for (i = 0; i < bp->rx_pg_ring_size; i++) { if (bnx2_alloc_rx_page(bp, rxr, ring_prod, GFP_KERNEL) < 0) { netdev_warn(bp->dev, "init'ed rx page ring %d with %d/%d pages only\n", ring_num, i, bp->rx_pg_ring_size); break; } prod = BNX2_NEXT_RX_BD(prod); ring_prod = BNX2_RX_PG_RING_IDX(prod); } rxr->rx_pg_prod = prod; ring_prod = prod = rxr->rx_prod; for (i = 0; i < bp->rx_ring_size; i++) { if (bnx2_alloc_rx_skb(bp, rxr, ring_prod, GFP_KERNEL) < 0) { netdev_warn(bp->dev, "init'ed rx ring %d with %d/%d skbs only\n", ring_num, i, bp->rx_ring_size); break; } prod = BNX2_NEXT_RX_BD(prod); ring_prod = BNX2_RX_RING_IDX(prod); } rxr->rx_prod = prod; rxr->rx_bidx_addr = MB_GET_CID_ADDR(cid) + BNX2_L2CTX_HOST_BDIDX; rxr->rx_bseq_addr = MB_GET_CID_ADDR(cid) + BNX2_L2CTX_HOST_BSEQ; rxr->rx_pg_bidx_addr = MB_GET_CID_ADDR(cid) + BNX2_L2CTX_HOST_PG_BDIDX; BNX2_WR16(bp, rxr->rx_pg_bidx_addr, rxr->rx_pg_prod); BNX2_WR16(bp, rxr->rx_bidx_addr, prod); BNX2_WR(bp, rxr->rx_bseq_addr, rxr->rx_prod_bseq); } static void bnx2_init_all_rings(struct bnx2 *bp) { int i; #if !defined(BNX2_ENABLE_NETQUEUE) u32 val; #endif bnx2_clear_ring_states(bp); BNX2_WR(bp, BNX2_TSCH_TSS_CFG, 0); for (i = 0; i < bp->num_tx_rings; i++) bnx2_init_tx_ring(bp, i); if (bp->num_tx_rings > 1) BNX2_WR(bp, BNX2_TSCH_TSS_CFG, ((bp->num_tx_rings - 1) << 24) | (TX_TSS_CID << 7)); BNX2_WR(bp, BNX2_RLUP_RSS_CONFIG, 0); bnx2_reg_wr_ind(bp, BNX2_RXP_SCRATCH_RSS_TBL_SZ, 0); for (i = 0; i < bp->num_rx_rings; i++) bnx2_init_rx_ring(bp, i); #if !defined(BNX2_ENABLE_NETQUEUE) if (bp->num_rx_rings > 1) { u32 tbl_32 = 0; for (i = 0; i < BNX2_RXP_SCRATCH_RSS_TBL_MAX_ENTRIES; i++) { int shift = (i % 8) << 2; tbl_32 |= (i % (bp->num_rx_rings - 1)) << shift; if ((i % 8) == 7) { BNX2_WR(bp, BNX2_RLUP_RSS_DATA, tbl_32); BNX2_WR(bp, BNX2_RLUP_RSS_COMMAND, (i >> 3) | BNX2_RLUP_RSS_COMMAND_RSS_WRITE_MASK | BNX2_RLUP_RSS_COMMAND_WRITE | BNX2_RLUP_RSS_COMMAND_HASH_MASK); tbl_32 = 0; } } val = BNX2_RLUP_RSS_CONFIG_IPV4_RSS_TYPE_ALL_XI | BNX2_RLUP_RSS_CONFIG_IPV6_RSS_TYPE_ALL_XI; BNX2_WR(bp, BNX2_RLUP_RSS_CONFIG, val); } #endif } static u32 bnx2_find_max_ring(u32 ring_size, u32 max_size) { u32 max, num_rings = 1; while (ring_size > BNX2_MAX_RX_DESC_CNT) { ring_size -= BNX2_MAX_RX_DESC_CNT; num_rings++; } /* round to next power of 2 */ max = max_size; while ((max & num_rings) == 0) max >>= 1; if (num_rings != max) max <<= 1; return max; } static void bnx2_set_rx_ring_size(struct bnx2 *bp, u32 size) { u32 rx_size, rx_space; /* 8 for CRC and VLAN */ rx_size = bp->dev->mtu + ETH_HLEN + BNX2_RX_OFFSET + 8; rx_space = SKB_DATA_ALIGN(rx_size + BNX2_RX_ALIGN) + NET_SKB_PAD + sizeof(struct skb_shared_info); bp->rx_copy_thresh = BNX2_RX_COPY_THRESH; bp->rx_pg_ring_size = 0; bp->rx_max_pg_ring = 0; bp->rx_max_pg_ring_idx = 0; #if !defined(__VMKLNX__) if ((rx_space > PAGE_SIZE) && !(bp->flags & BNX2_FLAG_JUMBO_BROKEN)) { int pages = PAGE_ALIGN(bp->dev->mtu - 40) >> PAGE_SHIFT; u32 jumbo_size = size * pages; if (jumbo_size > BNX2_MAX_TOTAL_RX_PG_DESC_CNT) jumbo_size = BNX2_MAX_TOTAL_RX_PG_DESC_CNT; bp->rx_pg_ring_size = jumbo_size; bp->rx_max_pg_ring = bnx2_find_max_ring(jumbo_size, BNX2_MAX_RX_PG_RINGS); bp->rx_max_pg_ring_idx = (bp->rx_max_pg_ring * BNX2_RX_DESC_CNT) - 1; rx_size = BNX2_RX_COPY_THRESH + BNX2_RX_OFFSET; bp->rx_copy_thresh = 0; } #endif bp->rx_buf_use_size = rx_size; /* hw alignment */ bp->rx_buf_size = bp->rx_buf_use_size + BNX2_RX_ALIGN; bp->rx_jumbo_thresh = rx_size - BNX2_RX_OFFSET; bp->rx_ring_size = size; bp->rx_max_ring = bnx2_find_max_ring(size, BNX2_MAX_RX_RINGS); bp->rx_max_ring_idx = (bp->rx_max_ring * BNX2_RX_DESC_CNT) - 1; } static void bnx2_free_tx_skbs(struct bnx2 *bp) { int i; for (i = 0; i < bp->num_tx_rings; i++) { struct bnx2_napi *bnapi = &bp->bnx2_napi[i]; struct bnx2_tx_ring_info *txr = &bnapi->tx_ring; int j; if (txr->tx_buf_ring == NULL) continue; for (j = 0; j < BNX2_TX_DESC_CNT; ) { struct bnx2_sw_tx_bd *tx_buf = &txr->tx_buf_ring[j]; struct sk_buff *skb = tx_buf->skb; int k, last; if (skb == NULL) { j = BNX2_NEXT_TX_BD(j); continue; } #if (LINUX_VERSION_CODE >= 0x02061b) dma_unmap_single(&bp->pdev->dev, #else pci_unmap_single(bp->pdev, #endif dma_unmap_addr(tx_buf, mapping), skb_headlen(skb), PCI_DMA_TODEVICE); tx_buf->skb = NULL; last = tx_buf->nr_frags; j = BNX2_NEXT_TX_BD(j); for (k = 0; k < last; k++, j = BNX2_NEXT_TX_BD(j)) { tx_buf = &txr->tx_buf_ring[BNX2_TX_RING_IDX(j)]; #if (LINUX_VERSION_CODE >= 0x02061b) dma_unmap_page(&bp->pdev->dev, #else pci_unmap_page(bp->pdev, #endif dma_unmap_addr(tx_buf, mapping), skb_frag_size(&skb_shinfo(skb)->frags[k]), PCI_DMA_TODEVICE); } dev_kfree_skb(skb); } } } static void bnx2_free_rx_skbs(struct bnx2 *bp) { int i; for (i = 0; i < bp->num_rx_rings; i++) { struct bnx2_napi *bnapi = &bp->bnx2_napi[i]; struct bnx2_rx_ring_info *rxr = &bnapi->rx_ring; int j; if (rxr->rx_buf_ring == NULL) return; for (j = 0; j < bp->rx_max_ring_idx; j++) { struct bnx2_sw_bd *rx_buf = &rxr->rx_buf_ring[j]; struct sk_buff *skb = rx_buf->skb; if (skb == NULL) continue; #if (LINUX_VERSION_CODE >= 0x02061b) dma_unmap_single(&bp->pdev->dev, #else pci_unmap_single(bp->pdev, #endif dma_unmap_addr(rx_buf, mapping), bp->rx_buf_use_size, PCI_DMA_FROMDEVICE); rx_buf->skb = NULL; dev_kfree_skb(skb); } for (j = 0; j < bp->rx_max_pg_ring_idx; j++) bnx2_free_rx_page(bp, rxr, j); } } static void bnx2_free_skbs(struct bnx2 *bp) { bnx2_free_tx_skbs(bp); bnx2_free_rx_skbs(bp); } static int bnx2_reset_nic(struct bnx2 *bp, u32 reset_code) { int rc; rc = bnx2_reset_chip(bp, reset_code); bnx2_free_skbs(bp); if (rc) return rc; if ((rc = bnx2_init_chip(bp)) != 0) return rc; bnx2_init_all_rings(bp); return 0; } static int bnx2_init_nic(struct bnx2 *bp, int reset_phy) { int rc; if ((rc = bnx2_reset_nic(bp, BNX2_DRV_MSG_CODE_RESET)) != 0) return rc; spin_lock_bh(&bp->phy_lock); bnx2_init_phy(bp, reset_phy); bnx2_set_link(bp); if (bp->phy_flags & BNX2_PHY_FLAG_REMOTE_PHY_CAP) bnx2_remote_phy_event(bp); spin_unlock_bh(&bp->phy_lock); return 0; } static int bnx2_shutdown_chip(struct bnx2 *bp) { u32 reset_code; if (bp->flags & BNX2_FLAG_NO_WOL) reset_code = BNX2_DRV_MSG_CODE_UNLOAD_LNK_DN; else if (bp->wol) reset_code = BNX2_DRV_MSG_CODE_SUSPEND_WOL; else reset_code = BNX2_DRV_MSG_CODE_SUSPEND_NO_WOL; return bnx2_reset_chip(bp, reset_code); } static int bnx2_test_registers(struct bnx2 *bp) { int ret; int i, is_5709; static const struct { u16 offset; u16 flags; #define BNX2_FL_NOT_5709 1 u32 rw_mask; u32 ro_mask; } reg_tbl[] = { { 0x006c, 0, 0x00000000, 0x0000003f }, { 0x0090, 0, 0xffffffff, 0x00000000 }, { 0x0094, 0, 0x00000000, 0x00000000 }, { 0x0404, BNX2_FL_NOT_5709, 0x00003f00, 0x00000000 }, { 0x0418, BNX2_FL_NOT_5709, 0x00000000, 0xffffffff }, { 0x041c, BNX2_FL_NOT_5709, 0x00000000, 0xffffffff }, { 0x0420, BNX2_FL_NOT_5709, 0x00000000, 0x80ffffff }, { 0x0424, BNX2_FL_NOT_5709, 0x00000000, 0x00000000 }, { 0x0428, BNX2_FL_NOT_5709, 0x00000000, 0x00000001 }, { 0x0450, BNX2_FL_NOT_5709, 0x00000000, 0x0000ffff }, { 0x0454, BNX2_FL_NOT_5709, 0x00000000, 0xffffffff }, { 0x0458, BNX2_FL_NOT_5709, 0x00000000, 0xffffffff }, { 0x0808, BNX2_FL_NOT_5709, 0x00000000, 0xffffffff }, { 0x0854, BNX2_FL_NOT_5709, 0x00000000, 0xffffffff }, { 0x0868, BNX2_FL_NOT_5709, 0x00000000, 0x77777777 }, { 0x086c, BNX2_FL_NOT_5709, 0x00000000, 0x77777777 }, { 0x0870, BNX2_FL_NOT_5709, 0x00000000, 0x77777777 }, { 0x0874, BNX2_FL_NOT_5709, 0x00000000, 0x77777777 }, { 0x0c00, BNX2_FL_NOT_5709, 0x00000000, 0x00000001 }, { 0x0c04, BNX2_FL_NOT_5709, 0x00000000, 0x03ff0001 }, { 0x0c08, BNX2_FL_NOT_5709, 0x0f0ff073, 0x00000000 }, { 0x1000, 0, 0x00000000, 0x00000001 }, { 0x1004, BNX2_FL_NOT_5709, 0x00000000, 0x000f0001 }, { 0x1408, 0, 0x01c00800, 0x00000000 }, { 0x149c, 0, 0x8000ffff, 0x00000000 }, { 0x14a8, 0, 0x00000000, 0x000001ff }, { 0x14ac, 0, 0x0fffffff, 0x10000000 }, { 0x14b0, 0, 0x00000002, 0x00000001 }, { 0x14b8, 0, 0x00000000, 0x00000000 }, { 0x14c0, 0, 0x00000000, 0x00000009 }, { 0x14c4, 0, 0x00003fff, 0x00000000 }, { 0x14cc, 0, 0x00000000, 0x00000001 }, { 0x14d0, 0, 0xffffffff, 0x00000000 }, { 0x1800, 0, 0x00000000, 0x00000001 }, { 0x1804, 0, 0x00000000, 0x00000003 }, { 0x2800, 0, 0x00000000, 0x00000001 }, { 0x2804, 0, 0x00000000, 0x00003f01 }, { 0x2808, 0, 0x0f3f3f03, 0x00000000 }, { 0x2810, 0, 0xffff0000, 0x00000000 }, { 0x2814, 0, 0xffff0000, 0x00000000 }, { 0x2818, 0, 0xffff0000, 0x00000000 }, { 0x281c, 0, 0xffff0000, 0x00000000 }, { 0x2834, 0, 0xffffffff, 0x00000000 }, { 0x2840, 0, 0x00000000, 0xffffffff }, { 0x2844, 0, 0x00000000, 0xffffffff }, { 0x2848, 0, 0xffffffff, 0x00000000 }, { 0x284c, 0, 0xf800f800, 0x07ff07ff }, { 0x2c00, 0, 0x00000000, 0x00000011 }, { 0x2c04, 0, 0x00000000, 0x00030007 }, { 0x3c00, 0, 0x00000000, 0x00000001 }, { 0x3c04, 0, 0x00000000, 0x00070000 }, { 0x3c08, 0, 0x00007f71, 0x07f00000 }, { 0x3c0c, 0, 0x1f3ffffc, 0x00000000 }, { 0x3c10, 0, 0xffffffff, 0x00000000 }, { 0x3c14, 0, 0x00000000, 0xffffffff }, { 0x3c18, 0, 0x00000000, 0xffffffff }, { 0x3c1c, 0, 0xfffff000, 0x00000000 }, { 0x3c20, 0, 0xffffff00, 0x00000000 }, { 0x5004, 0, 0x00000000, 0x0000007f }, { 0x5008, 0, 0x0f0007ff, 0x00000000 }, { 0x5c00, 0, 0x00000000, 0x00000001 }, { 0x5c04, 0, 0x00000000, 0x0003000f }, { 0x5c08, 0, 0x00000003, 0x00000000 }, { 0x5c0c, 0, 0x0000fff8, 0x00000000 }, { 0x5c10, 0, 0x00000000, 0xffffffff }, { 0x5c80, 0, 0x00000000, 0x0f7113f1 }, { 0x5c84, 0, 0x00000000, 0x0000f333 }, { 0x5c88, 0, 0x00000000, 0x00077373 }, { 0x5c8c, 0, 0x00000000, 0x0007f737 }, { 0x6808, 0, 0x0000ff7f, 0x00000000 }, { 0x680c, 0, 0xffffffff, 0x00000000 }, { 0x6810, 0, 0xffffffff, 0x00000000 }, { 0x6814, 0, 0xffffffff, 0x00000000 }, { 0x6818, 0, 0xffffffff, 0x00000000 }, { 0x681c, 0, 0xffffffff, 0x00000000 }, { 0x6820, 0, 0x00ff00ff, 0x00000000 }, { 0x6824, 0, 0x00ff00ff, 0x00000000 }, { 0x6828, 0, 0x00ff00ff, 0x00000000 }, { 0x682c, 0, 0x03ff03ff, 0x00000000 }, { 0x6830, 0, 0x03ff03ff, 0x00000000 }, { 0x6834, 0, 0x03ff03ff, 0x00000000 }, { 0x6838, 0, 0x03ff03ff, 0x00000000 }, { 0x683c, 0, 0x0000ffff, 0x00000000 }, { 0x6840, 0, 0x00000ff0, 0x00000000 }, { 0x6844, 0, 0x00ffff00, 0x00000000 }, { 0x684c, 0, 0xffffffff, 0x00000000 }, { 0x6850, 0, 0x7f7f7f7f, 0x00000000 }, { 0x6854, 0, 0x7f7f7f7f, 0x00000000 }, { 0x6858, 0, 0x7f7f7f7f, 0x00000000 }, { 0x685c, 0, 0x7f7f7f7f, 0x00000000 }, { 0x6908, 0, 0x00000000, 0x0001ff0f }, { 0x690c, 0, 0x00000000, 0x0ffe00f0 }, { 0xffff, 0, 0x00000000, 0x00000000 }, }; ret = 0; is_5709 = 0; if (BNX2_CHIP(bp) == BNX2_CHIP_5709) is_5709 = 1; for (i = 0; reg_tbl[i].offset != 0xffff; i++) { u32 offset, rw_mask, ro_mask, save_val, val; u16 flags = reg_tbl[i].flags; if (is_5709 && (flags & BNX2_FL_NOT_5709)) continue; offset = (u32) reg_tbl[i].offset; rw_mask = reg_tbl[i].rw_mask; ro_mask = reg_tbl[i].ro_mask; save_val = readl(bp->regview + offset); writel(0, bp->regview + offset); val = readl(bp->regview + offset); if ((val & rw_mask) != 0) { goto reg_test_err; } if ((val & ro_mask) != (save_val & ro_mask)) { goto reg_test_err; } writel(0xffffffff, bp->regview + offset); val = readl(bp->regview + offset); if ((val & rw_mask) != rw_mask) { goto reg_test_err; } if ((val & ro_mask) != (save_val & ro_mask)) { goto reg_test_err; } writel(save_val, bp->regview + offset); continue; reg_test_err: writel(save_val, bp->regview + offset); ret = -ENODEV; break; } return ret; } static int bnx2_do_mem_test(struct bnx2 *bp, u32 start, u32 size) { static const u32 test_pattern[] = { 0x00000000, 0xffffffff, 0x55555555, 0xaaaaaaaa , 0xaa55aa55, 0x55aa55aa }; int i; for (i = 0; i < sizeof(test_pattern) / 4; i++) { u32 offset; for (offset = 0; offset < size; offset += 4) { bnx2_reg_wr_ind(bp, start + offset, test_pattern[i]); if (bnx2_reg_rd_ind(bp, start + offset) != test_pattern[i]) { return -ENODEV; } } } return 0; } static int bnx2_test_memory(struct bnx2 *bp) { int ret = 0; int i; static struct mem_entry { u32 offset; u32 len; } mem_tbl_5706[] = { { 0x60000, 0x4000 }, { 0xa0000, 0x3000 }, { 0xe0000, 0x4000 }, { 0x120000, 0x4000 }, { 0x1a0000, 0x4000 }, { 0x160000, 0x4000 }, { 0xffffffff, 0 }, }, mem_tbl_5709[] = { { 0x60000, 0x4000 }, { 0xa0000, 0x3000 }, { 0xe0000, 0x4000 }, { 0x120000, 0x4000 }, { 0x1a0000, 0x4000 }, { 0xffffffff, 0 }, }; struct mem_entry *mem_tbl; if (BNX2_CHIP(bp) == BNX2_CHIP_5709) mem_tbl = mem_tbl_5709; else mem_tbl = mem_tbl_5706; for (i = 0; mem_tbl[i].offset != 0xffffffff; i++) { if ((ret = bnx2_do_mem_test(bp, mem_tbl[i].offset, mem_tbl[i].len)) != 0) { return ret; } } return ret; } #define BNX2_MAC_LOOPBACK 0 #define BNX2_PHY_LOOPBACK 1 static int bnx2_run_loopback(struct bnx2 *bp, int loopback_mode) { unsigned int pkt_size, num_pkts, i; struct sk_buff *skb, *rx_skb; unsigned char *packet; u16 rx_start_idx, rx_idx; dma_addr_t map; struct bnx2_tx_bd *txbd; struct bnx2_sw_bd *rx_buf; struct l2_fhdr *rx_hdr; int ret = -ENODEV; struct bnx2_napi *bnapi = &bp->bnx2_napi[0], *tx_napi; struct bnx2_tx_ring_info *txr = &bnapi->tx_ring; struct bnx2_rx_ring_info *rxr = &bnapi->rx_ring; tx_napi = bnapi; txr = &tx_napi->tx_ring; rxr = &bnapi->rx_ring; if (loopback_mode == BNX2_MAC_LOOPBACK) { bp->loopback = MAC_LOOPBACK; bnx2_set_mac_loopback(bp); } else if (loopback_mode == BNX2_PHY_LOOPBACK) { if (bp->phy_flags & BNX2_PHY_FLAG_REMOTE_PHY_CAP) return 0; bp->loopback = PHY_LOOPBACK; bnx2_set_phy_loopback(bp); } else return -EINVAL; pkt_size = min(bp->dev->mtu + ETH_HLEN, bp->rx_jumbo_thresh - 4); skb = netdev_alloc_skb(bp->dev, pkt_size); if (!skb) return -ENOMEM; packet = skb_put(skb, pkt_size); memcpy(packet, bp->dev->dev_addr, 6); memset(packet + 6, 0x0, 8); for (i = 14; i < pkt_size; i++) packet[i] = (unsigned char) (i & 0xff); #if (LINUX_VERSION_CODE >= 0x02061b) map = dma_map_single(&bp->pdev->dev, skb->data, pkt_size, PCI_DMA_TODEVICE); if (dma_mapping_error(&bp->pdev->dev, map)) { #else map = pci_map_single(bp->pdev, skb->data, pkt_size, PCI_DMA_TODEVICE); if (pci_dma_mapping_error(map)) { #endif dev_kfree_skb(skb); return -EIO; } BNX2_WR(bp, BNX2_HC_COMMAND, bp->hc_cmd | BNX2_HC_COMMAND_COAL_NOW_WO_INT); BNX2_RD(bp, BNX2_HC_COMMAND); udelay(5); rx_start_idx = bnx2_get_hw_rx_cons(bnapi); num_pkts = 0; txbd = &txr->tx_desc_ring[BNX2_TX_RING_IDX(txr->tx_prod)]; txbd->tx_bd_haddr_hi = (u64) map >> 32; txbd->tx_bd_haddr_lo = (u64) map & 0xffffffff; txbd->tx_bd_mss_nbytes = pkt_size; txbd->tx_bd_vlan_tag_flags = TX_BD_FLAGS_START | TX_BD_FLAGS_END; num_pkts++; txr->tx_prod = BNX2_NEXT_TX_BD(txr->tx_prod); txr->tx_prod_bseq += pkt_size; BNX2_WR16(bp, txr->tx_bidx_addr, txr->tx_prod); BNX2_WR(bp, txr->tx_bseq_addr, txr->tx_prod_bseq); udelay(100); BNX2_WR(bp, BNX2_HC_COMMAND, bp->hc_cmd | BNX2_HC_COMMAND_COAL_NOW_WO_INT); BNX2_RD(bp, BNX2_HC_COMMAND); udelay(5); #if (LINUX_VERSION_CODE >= 0x02061b) dma_unmap_single(&bp->pdev->dev, map, pkt_size, PCI_DMA_TODEVICE); #else pci_unmap_single(bp->pdev, map, pkt_size, PCI_DMA_TODEVICE); #endif dev_kfree_skb(skb); if (bnx2_get_hw_tx_cons(tx_napi) != txr->tx_prod) goto loopback_test_done; rx_idx = bnx2_get_hw_rx_cons(bnapi); if (rx_idx != rx_start_idx + num_pkts) { goto loopback_test_done; } rx_buf = &rxr->rx_buf_ring[rx_start_idx]; rx_skb = rx_buf->skb; rx_hdr = rx_buf->desc; skb_reserve(rx_skb, BNX2_RX_OFFSET); #if (LINUX_VERSION_CODE >= 0x02061b) dma_sync_single_for_cpu(&bp->pdev->dev, #else pci_dma_sync_single_for_cpu(bp->pdev, #endif dma_unmap_addr(rx_buf, mapping), bp->rx_buf_size, PCI_DMA_FROMDEVICE); if (rx_hdr->l2_fhdr_status & (L2_FHDR_ERRORS_BAD_CRC | L2_FHDR_ERRORS_PHY_DECODE | L2_FHDR_ERRORS_ALIGNMENT | L2_FHDR_ERRORS_TOO_SHORT | L2_FHDR_ERRORS_GIANT_FRAME)) { goto loopback_test_done; } if ((rx_hdr->l2_fhdr_pkt_len - 4) != pkt_size) { goto loopback_test_done; } for (i = 14; i < pkt_size; i++) { if (*(rx_skb->data + i) != (unsigned char) (i & 0xff)) { goto loopback_test_done; } } ret = 0; loopback_test_done: bp->loopback = 0; return ret; } #define BNX2_MAC_LOOPBACK_FAILED 1 #define BNX2_PHY_LOOPBACK_FAILED 2 #define BNX2_LOOPBACK_FAILED (BNX2_MAC_LOOPBACK_FAILED | \ BNX2_PHY_LOOPBACK_FAILED) static int bnx2_test_loopback(struct bnx2 *bp) { int rc = 0; if (!netif_running(bp->dev)) return BNX2_LOOPBACK_FAILED; bnx2_reset_nic(bp, BNX2_DRV_MSG_CODE_RESET); spin_lock_bh(&bp->phy_lock); bnx2_init_phy(bp, 1); spin_unlock_bh(&bp->phy_lock); if (bnx2_run_loopback(bp, BNX2_MAC_LOOPBACK)) rc |= BNX2_MAC_LOOPBACK_FAILED; if (bnx2_run_loopback(bp, BNX2_PHY_LOOPBACK)) rc |= BNX2_PHY_LOOPBACK_FAILED; return rc; } #define NVRAM_SIZE 0x200 #define CRC32_RESIDUAL 0xdebb20e3 static int bnx2_test_nvram(struct bnx2 *bp) { __be32 buf[NVRAM_SIZE / 4]; u8 *data = (u8 *) buf; int rc = 0; u32 magic, csum; if ((rc = bnx2_nvram_read(bp, 0, data, 4)) != 0) goto test_nvram_done; magic = be32_to_cpu(buf[0]); if (magic != 0x669955aa) { rc = -ENODEV; goto test_nvram_done; } if ((rc = bnx2_nvram_read(bp, 0x100, data, NVRAM_SIZE)) != 0) goto test_nvram_done; csum = ether_crc_le(0x100, data); if (csum != CRC32_RESIDUAL) { rc = -ENODEV; goto test_nvram_done; } csum = ether_crc_le(0x100, data + 0x100); if (csum != CRC32_RESIDUAL) { rc = -ENODEV; } test_nvram_done: return rc; } static int bnx2_test_link(struct bnx2 *bp) { u32 bmsr; if (!netif_running(bp->dev)) return -ENODEV; if (bp->phy_flags & BNX2_PHY_FLAG_REMOTE_PHY_CAP) { int i; for (i = 0; i < 6 && !bp->link_up; i++) { if (bnx2_msleep_interruptible(500)) break; } if (bp->link_up) return 0; return -ENODEV; } spin_lock_bh(&bp->phy_lock); bnx2_enable_bmsr1(bp); bnx2_read_phy(bp, bp->mii_bmsr1, &bmsr); bnx2_read_phy(bp, bp->mii_bmsr1, &bmsr); bnx2_disable_bmsr1(bp); spin_unlock_bh(&bp->phy_lock); if (bmsr & BMSR_LSTATUS) { return 0; } return -ENODEV; } static int bnx2_test_intr(struct bnx2 *bp) { int i; u16 status_idx; if (!netif_running(bp->dev)) return -ENODEV; status_idx = BNX2_RD(bp, BNX2_PCICFG_INT_ACK_CMD) & 0xffff; /* This register is not touched during run-time. */ BNX2_WR(bp, BNX2_HC_COMMAND, bp->hc_cmd | BNX2_HC_COMMAND_COAL_NOW); BNX2_RD(bp, BNX2_HC_COMMAND); for (i = 0; i < 10; i++) { if ((BNX2_RD(bp, BNX2_PCICFG_INT_ACK_CMD) & 0xffff) != status_idx) { break; } bnx2_msleep_interruptible(10); } if (i < 10) return 0; return -ENODEV; } /* Determining link for parallel detection. */ static int bnx2_5706_serdes_has_link(struct bnx2 *bp) { u32 mode_ctl, an_dbg, exp; if (bp->phy_flags & BNX2_PHY_FLAG_NO_PARALLEL) return 0; bnx2_write_phy(bp, MII_BNX2_MISC_SHADOW, MISC_SHDW_MODE_CTL); bnx2_read_phy(bp, MII_BNX2_MISC_SHADOW, &mode_ctl); if (!(mode_ctl & MISC_SHDW_MODE_CTL_SIG_DET)) return 0; bnx2_write_phy(bp, MII_BNX2_MISC_SHADOW, MISC_SHDW_AN_DBG); bnx2_read_phy(bp, MII_BNX2_MISC_SHADOW, &an_dbg); bnx2_read_phy(bp, MII_BNX2_MISC_SHADOW, &an_dbg); if (an_dbg & (MISC_SHDW_AN_DBG_NOSYNC | MISC_SHDW_AN_DBG_RUDI_INVALID)) return 0; bnx2_write_phy(bp, MII_BNX2_DSP_ADDRESS, MII_EXPAND_REG1); bnx2_read_phy(bp, MII_BNX2_DSP_RW_PORT, &exp); bnx2_read_phy(bp, MII_BNX2_DSP_RW_PORT, &exp); if (exp & MII_EXPAND_REG1_RUDI_C) /* receiving CONFIG */ return 0; return 1; } static void bnx2_5706_serdes_timer(struct bnx2 *bp) { int check_link = 1; spin_lock(&bp->phy_lock); if (bp->serdes_an_pending) { bp->serdes_an_pending--; check_link = 0; } else if ((bp->link_up == 0) && (bp->autoneg & AUTONEG_SPEED)) { u32 bmcr; bp->current_interval = BNX2_TIMER_INTERVAL; bnx2_read_phy(bp, bp->mii_bmcr, &bmcr); if (bmcr & BMCR_ANENABLE) { if (bnx2_5706_serdes_has_link(bp)) { bmcr &= ~BMCR_ANENABLE; bmcr |= BMCR_SPEED1000 | BMCR_FULLDPLX; bnx2_write_phy(bp, bp->mii_bmcr, bmcr); bp->phy_flags |= BNX2_PHY_FLAG_PARALLEL_DETECT; } } } else if ((bp->link_up) && (bp->autoneg & AUTONEG_SPEED) && (bp->phy_flags & BNX2_PHY_FLAG_PARALLEL_DETECT)) { u32 phy2; bnx2_write_phy(bp, 0x17, 0x0f01); bnx2_read_phy(bp, 0x15, &phy2); if (phy2 & 0x20) { u32 bmcr; bnx2_read_phy(bp, bp->mii_bmcr, &bmcr); bmcr |= BMCR_ANENABLE; bnx2_write_phy(bp, bp->mii_bmcr, bmcr); bp->phy_flags &= ~BNX2_PHY_FLAG_PARALLEL_DETECT; } } else bp->current_interval = BNX2_TIMER_INTERVAL; if (check_link) { u32 val; bnx2_write_phy(bp, MII_BNX2_MISC_SHADOW, MISC_SHDW_AN_DBG); bnx2_read_phy(bp, MII_BNX2_MISC_SHADOW, &val); bnx2_read_phy(bp, MII_BNX2_MISC_SHADOW, &val); if (bp->link_up && (val & MISC_SHDW_AN_DBG_NOSYNC)) { if (!(bp->phy_flags & BNX2_PHY_FLAG_FORCED_DOWN)) { bnx2_5706s_force_link_dn(bp, 1); bp->phy_flags |= BNX2_PHY_FLAG_FORCED_DOWN; } else bnx2_set_link(bp); } else if (!bp->link_up && !(val & MISC_SHDW_AN_DBG_NOSYNC)) bnx2_set_link(bp); } spin_unlock(&bp->phy_lock); } static void bnx2_5708_serdes_timer(struct bnx2 *bp) { if (bp->phy_flags & BNX2_PHY_FLAG_REMOTE_PHY_CAP) return; if ((bp->phy_flags & BNX2_PHY_FLAG_2_5G_CAPABLE) == 0) { bp->serdes_an_pending = 0; return; } spin_lock(&bp->phy_lock); if (bp->serdes_an_pending) bp->serdes_an_pending--; else if ((bp->link_up == 0) && (bp->autoneg & AUTONEG_SPEED)) { u32 bmcr; bnx2_read_phy(bp, bp->mii_bmcr, &bmcr); if (bmcr & BMCR_ANENABLE) { bnx2_enable_forced_2g5(bp); bp->current_interval = BNX2_SERDES_FORCED_TIMEOUT; } else { bnx2_disable_forced_2g5(bp); bp->serdes_an_pending = 2; bp->current_interval = BNX2_TIMER_INTERVAL; } } else bp->current_interval = BNX2_TIMER_INTERVAL; spin_unlock(&bp->phy_lock); } static void bnx2_timer(unsigned long data) { struct bnx2 *bp = (struct bnx2 *) data; if (!netif_running(bp->dev)) return; if (atomic_read(&bp->intr_sem) != 0) goto bnx2_restart_timer; #ifdef CONFIG_PCI_MSI if ((bp->flags & (BNX2_FLAG_USING_MSI | BNX2_FLAG_ONE_SHOT_MSI)) == BNX2_FLAG_USING_MSI) bnx2_chk_missed_msi(bp); #endif bnx2_send_heart_beat(bp); bp->stats_blk->stat_FwRxDrop = bnx2_reg_rd_ind(bp, BNX2_FW_RX_DROP_COUNT); /* workaround occasional corrupted counters */ if ((bp->flags & BNX2_FLAG_BROKEN_STATS) && bp->stats_ticks) BNX2_WR(bp, BNX2_HC_COMMAND, bp->hc_cmd | BNX2_HC_COMMAND_STATS_NOW); if (bp->phy_flags & BNX2_PHY_FLAG_SERDES) { if (BNX2_CHIP(bp) == BNX2_CHIP_5706) bnx2_5706_serdes_timer(bp); else bnx2_5708_serdes_timer(bp); } bnx2_restart_timer: mod_timer(&bp->timer, jiffies + bp->current_interval); } static int bnx2_request_irq(struct bnx2 *bp) { unsigned long flags; struct bnx2_irq *irq; int rc = 0, i; if (bp->flags & BNX2_FLAG_USING_MSI_OR_MSIX) flags = 0; else flags = IRQF_SHARED; #if defined(__VMKLNX__) /* * In ESX, bnx2 will setup int mode during .probe time. However, the dev->name * will be finalized only when pci_announce_device is done. So, we assign * irq->name here instead of in bnx2_setup_int_mode. */ strcpy(bp->irq_tbl[0].name, bp->dev->name); if (bp->flags & BNX2_FLAG_USING_MSIX) { for (i = 0; i < BNX2_MAX_MSIX_VEC; i++) { snprintf(bp->irq_tbl[i].name, sizeof(bp->irq_tbl[i].name), "%s-%d", bp->dev->name, i); } } #endif for (i = 0; i < bp->irq_nvecs; i++) { irq = &bp->irq_tbl[i]; rc = request_irq(irq->vector, irq->handler, flags, irq->name, &bp->bnx2_napi[i]); if (rc) break; irq->requested = 1; } return rc; } #if defined(__VMKLNX__) /* disable MSI/MSIX */ static void bnx2_disable_msi(struct bnx2 *bp) { #ifdef CONFIG_PCI_MSI if (bp->flags & BNX2_FLAG_USING_MSI) pci_disable_msi(bp->pdev); else if (bp->flags & BNX2_FLAG_USING_MSIX) pci_disable_msix(bp->pdev); bp->flags &= ~(BNX2_FLAG_USING_MSI_OR_MSIX | BNX2_FLAG_ONE_SHOT_MSI); #endif } #endif /* defined(__VMKLNX__) */ static void __bnx2_free_irq(struct bnx2 *bp) { struct bnx2_irq *irq; int i; for (i = 0; i < bp->irq_nvecs; i++) { irq = &bp->irq_tbl[i]; if (irq->requested) free_irq(irq->vector, &bp->bnx2_napi[i]); irq->requested = 0; } } static void bnx2_free_irq(struct bnx2 *bp) { __bnx2_free_irq(bp); #if !defined(__VMKLNX__) #ifdef CONFIG_PCI_MSI if (bp->flags & BNX2_FLAG_USING_MSI) pci_disable_msi(bp->pdev); else if (bp->flags & BNX2_FLAG_USING_MSIX) pci_disable_msix(bp->pdev); bp->flags &= ~(BNX2_FLAG_USING_MSI_OR_MSIX | BNX2_FLAG_ONE_SHOT_MSI); #endif #endif /* __VMKLNX__ */ } #ifdef CONFIG_PCI_MSI static void bnx2_enable_msix(struct bnx2 *bp, int msix_vecs) { #ifdef BNX2_NEW_NAPI int i, total_vecs, rc; struct msix_entry msix_ent[BNX2_MAX_MSIX_VEC]; #if !defined(__VMKLNX__) struct net_device *dev = bp->dev; const int len = sizeof(bp->irq_tbl[0].name); #endif bnx2_setup_msix_tbl(bp); BNX2_WR(bp, BNX2_PCI_MSIX_CONTROL, BNX2_MAX_MSIX_HW_VEC - 1); BNX2_WR(bp, BNX2_PCI_MSIX_TBL_OFF_BIR, BNX2_PCI_GRC_WINDOW2_BASE); BNX2_WR(bp, BNX2_PCI_MSIX_PBA_OFF_BIT, BNX2_PCI_GRC_WINDOW3_BASE); /* Need to flush the previous three writes to ensure MSI-X * is setup properly */ BNX2_RD(bp, BNX2_PCI_MSIX_CONTROL); for (i = 0; i < BNX2_MAX_MSIX_VEC; i++) { msix_ent[i].entry = i; msix_ent[i].vector = 0; } total_vecs = msix_vecs; #ifdef BCM_CNIC total_vecs++; #endif rc = -ENOSPC; while (total_vecs >= BNX2_MIN_MSIX_VEC) { rc = pci_enable_msix(bp->pdev, msix_ent, total_vecs); if (rc <= 0) break; if (rc > 0) total_vecs = rc; } if (rc != 0) return; msix_vecs = total_vecs; #ifdef BCM_CNIC msix_vecs--; #endif bp->irq_nvecs = msix_vecs; bp->flags |= BNX2_FLAG_USING_MSIX | BNX2_FLAG_ONE_SHOT_MSI; #if defined(__VMKLNX__) if (disable_msi_1shot) bp->flags &= ~BNX2_FLAG_ONE_SHOT_MSI; #endif for (i = 0; i < total_vecs; i++) { bp->irq_tbl[i].vector = msix_ent[i].vector; #if !defined(__VMKLNX__) snprintf(bp->irq_tbl[i].name, len, "%s-%d", dev->name, i); bp->irq_tbl[i].handler = bnx2_msi_1shot; #else if (disable_msi_1shot) bp->irq_tbl[i].handler = bnx2_msi; else bp->irq_tbl[i].handler = bnx2_msi_1shot; #endif } #endif } #endif static int bnx2_setup_int_mode(struct bnx2 *bp, int dis_msi) { #ifdef CONFIG_PCI_MSI #if defined(BNX2_ENABLE_NETQUEUE) int cpus = num_online_cpus(); int msix_vecs = min(cpus, 4); if (force_netq_param[bp->index] != BNX2_OPTION_UNSET) msix_vecs = min(force_netq_param[bp->index], RX_MAX_RSS_RINGS); /* Once is for the default queuue */ msix_vecs += 1; #else #if defined(__VMKLNX__) /* If NetQueue is not enable then force the number of queues to 1 */ int msix_vecs = 1; #else int cpus = num_online_cpus(); int msix_vecs; #endif /* defined(__VMKLNX__) */ #endif #endif #if !defined(__VMKLNX__) if (!bp->num_req_rx_rings) msix_vecs = max(cpus + 1, bp->num_req_tx_rings); else if (!bp->num_req_tx_rings) msix_vecs = max(cpus, bp->num_req_rx_rings); else msix_vecs = max(bp->num_req_rx_rings, bp->num_req_tx_rings); msix_vecs = min(msix_vecs, RX_MAX_RINGS); #endif bp->irq_tbl[0].handler = bnx2_interrupt; #if !defined(__VMKLNX__) strcpy(bp->irq_tbl[0].name, bp->dev->name); #endif bp->irq_nvecs = 1; bp->irq_tbl[0].vector = bp->pdev->irq; #ifdef CONFIG_PCI_MSI if ((bp->flags & BNX2_FLAG_MSIX_CAP) && !dis_msi) bnx2_enable_msix(bp, msix_vecs); if ((bp->flags & BNX2_FLAG_MSI_CAP) && !dis_msi && !(bp->flags & BNX2_FLAG_USING_MSIX)) { if (pci_enable_msi(bp->pdev) == 0) { bp->flags |= BNX2_FLAG_USING_MSI; if (BNX2_CHIP(bp) == BNX2_CHIP_5709) { bp->flags |= BNX2_FLAG_ONE_SHOT_MSI; bp->irq_tbl[0].handler = bnx2_msi_1shot; #if defined(__VMKLNX__) if (disable_msi_1shot) { bp->flags &= ~BNX2_FLAG_ONE_SHOT_MSI; bp->irq_tbl[0].handler = bnx2_msi; } #endif } else bp->irq_tbl[0].handler = bnx2_msi; bp->irq_tbl[0].vector = bp->pdev->irq; } } #endif #ifndef BCM_HAVE_MULTI_QUEUE bp->num_tx_rings = 1; bp->num_rx_rings = bp->irq_nvecs; #else #if defined(__VMKLNX__) #if defined(BNX2_ENABLE_NETQUEUE) bp->num_tx_rings = bp->irq_nvecs; bp->dev->real_num_tx_queues = bp->num_tx_rings; #else bp->num_tx_rings = 1; #endif bp->num_rx_rings = bp->irq_nvecs; #else if (!bp->num_req_tx_rings) bp->num_tx_rings = rounddown_pow_of_two(bp->irq_nvecs); else bp->num_tx_rings = min(bp->irq_nvecs, bp->num_req_tx_rings); if (!bp->num_req_rx_rings) bp->num_rx_rings = bp->irq_nvecs; else bp->num_rx_rings = min(bp->irq_nvecs, bp->num_req_rx_rings); #endif netif_set_real_num_tx_queues(bp->dev, bp->num_tx_rings); #endif return netif_set_real_num_rx_queues(bp->dev, bp->num_rx_rings); } /* Called with rtnl_lock */ static int bnx2_open(struct net_device *dev) { struct bnx2 *bp = netdev_priv(dev); int rc; netif_carrier_off(dev); bnx2_disable_int(bp); #if !(defined __VMKLNX__) rc = bnx2_setup_int_mode(bp, disable_msi); if (rc) goto open_err; bnx2_init_napi(bp); #endif /* !(defined __VMKLNX__) */ rc = bnx2_alloc_mem(bp); if (rc) goto open_err; rc = bnx2_request_irq(bp); if (rc) goto open_err; rc = bnx2_init_nic(bp, 1); if (rc) goto open_err; #ifdef BNX2_NEW_NAPI bnx2_napi_enable(bp); #endif mod_timer(&bp->timer, jiffies + bp->current_interval); atomic_set(&bp->intr_sem, 0); memset(bp->temp_stats_blk, 0, sizeof(struct statistics_block)); bnx2_enable_int(bp); #ifdef CONFIG_PCI_MSI if (bp->flags & BNX2_FLAG_USING_MSI) { /* Test MSI to make sure it is working * If MSI test fails, go back to INTx mode */ if (bnx2_test_intr(bp) != 0) { netdev_warn(bp->dev, "No interrupt was generated using MSI, switching to INTx mode. Please report this failure to the PCI maintainer and include system chipset information.\n"); #ifdef BNX2_NEW_NAPI bnx2_napi_disable(bp); #endif bnx2_disable_int(bp); bnx2_free_irq(bp); #if defined(__VMKLNX__) bnx2_disable_msi(bp); #endif bnx2_setup_int_mode(bp, 1); rc = bnx2_init_nic(bp, 0); if (!rc) rc = bnx2_request_irq(bp); if (rc) { del_timer_sync(&bp->timer); goto open_err; } #ifdef BNX2_NEW_NAPI bnx2_napi_enable(bp); #endif bnx2_enable_int(bp); } } if (bp->flags & BNX2_FLAG_USING_MSI) netdev_info(dev, "using MSI\n"); else if (bp->flags & BNX2_FLAG_USING_MSIX) netdev_info(dev, "using MSIX\n"); #endif #if defined(BNX2_ENABLE_NETQUEUE) if (bnx2_netqueue_is_avail(bp)) bnx2_open_netqueue_hw(bp); #endif netif_tx_start_all_queues(dev); #if defined(__VMKLNX__) if (bp->cnic_eth_dev.drv_state & CNIC_DRV_STATE_REGD) { bnx2_setup_cnic_irq_info(bp); bnx2_cnic_start(bp); } #endif return 0; open_err: bnx2_free_skbs(bp); bnx2_free_irq(bp); bnx2_free_mem(bp); #if !defined(__VMKLNX__) bnx2_del_napi(bp); #endif /* !(defined __VMKLNX__) */ return rc; } static void #if defined(INIT_DELAYED_WORK_DEFERRABLE) || defined(INIT_WORK_NAR) || defined(INIT_DEFERRABLE_WORK) || (defined(__VMKLNX__) && (VMWARE_ESX_DDK_VERSION >= 40000)) bnx2_reset_task(struct work_struct *work) #else bnx2_reset_task(void *data) #endif { #if defined(INIT_DELAYED_WORK_DEFERRABLE) || defined(INIT_WORK_NAR) || defined(INIT_DEFERRABLE_WORK) || (defined(__VMKLNX__) && (VMWARE_ESX_DDK_VERSION >= 40000)) struct bnx2 *bp = container_of(work, struct bnx2, reset_task); #else struct bnx2 *bp = data; #endif int rc; u16 pcicmd; rtnl_lock(); if (!netif_running(bp->dev)) { rtnl_unlock(); return; } bnx2_netif_stop(bp, true); pci_read_config_word(bp->pdev, PCI_COMMAND, &pcicmd); if (!(pcicmd & PCI_COMMAND_MEMORY)) { /* in case PCI block has reset */ pci_restore_state(bp->pdev); pci_save_state(bp->pdev); } rc = bnx2_init_nic(bp, 1); if (rc) { netdev_err(bp->dev, "failed to reset NIC, closing\n"); bnx2_napi_enable(bp); dev_close(bp->dev); #if defined(__VMKLNX__) #if (VMWARE_ESX_DDK_VERSION >= 41000) /* PR 533926 * This is a workaround to sync device status in dev->flags and * dev->gflags. It is needed to avoid PSOD (due to double dev_close) * on reboot. */ bp->dev->gflags &= ~IFF_DEV_IS_OPEN; #endif #endif rtnl_unlock(); return; } atomic_set(&bp->intr_sem, 1); bnx2_netif_start(bp, true); rtnl_unlock(); } #define BNX2_FTQ_ENTRY(ftq) { __stringify(ftq##FTQ_CTL), BNX2_##ftq##FTQ_CTL } static const struct ftq_reg { char *name; u32 off; } ftq_arr[] = { BNX2_FTQ_ENTRY(RV2P_P), BNX2_FTQ_ENTRY(RV2P_T), BNX2_FTQ_ENTRY(RV2P_M), BNX2_FTQ_ENTRY(TBDR_), BNX2_FTQ_ENTRY(TSCH_), BNX2_FTQ_ENTRY(TDMA_), BNX2_FTQ_ENTRY(TXP_), BNX2_FTQ_ENTRY(TPAT_), BNX2_FTQ_ENTRY(TAS_), BNX2_FTQ_ENTRY(RXP_C), BNX2_FTQ_ENTRY(RXP_), BNX2_FTQ_ENTRY(RLUP_), BNX2_FTQ_ENTRY(COM_COMXQ_), BNX2_FTQ_ENTRY(COM_COMTQ_), BNX2_FTQ_ENTRY(COM_COMQ_), BNX2_FTQ_ENTRY(CP_CPQ_), BNX2_FTQ_ENTRY(RDMA_), BNX2_FTQ_ENTRY(CSCH_CH_), BNX2_FTQ_ENTRY(MCP_MCPQ_), }; static void bnx2_dump_ftq(struct bnx2 *bp) { int i; u32 reg, bdidx, cid, valid; struct net_device *dev = bp->dev; netdev_err(dev, "<--- start FTQ dump --->\n"); for (i = 0; i < ARRAY_SIZE(ftq_arr); i++) netdev_err(dev, "%s %08x\n", ftq_arr[i].name, bnx2_reg_rd_ind(bp, ftq_arr[i].off)); netdev_err(dev, "CPU states:\n"); for (reg = BNX2_TXP_CPU_MODE; reg <= BNX2_CP_CPU_MODE; reg += 0x40000) netdev_err(dev, "%06x mode %x state %x evt_mask %x pc %x pc %x instr %x\n", reg, bnx2_reg_rd_ind(bp, reg), bnx2_reg_rd_ind(bp, reg + 4), bnx2_reg_rd_ind(bp, reg + 8), bnx2_reg_rd_ind(bp, reg + 0x1c), bnx2_reg_rd_ind(bp, reg + 0x1c), bnx2_reg_rd_ind(bp, reg + 0x20)); netdev_err(dev, "<--- end FTQ dump --->\n"); netdev_err(dev, "<--- start TBDC dump --->\n"); netdev_err(dev, "TBDC free cnt: %ld\n", BNX2_RD(bp, BNX2_TBDC_STATUS) & BNX2_TBDC_STATUS_FREE_CNT); netdev_err(dev, "LINE CID BIDX CMD VALIDS\n"); for (i = 0; i < 0x20; i++) { int j = 0; BNX2_WR(bp, BNX2_TBDC_BD_ADDR, i); BNX2_WR(bp, BNX2_TBDC_CAM_OPCODE, BNX2_TBDC_CAM_OPCODE_OPCODE_CAM_READ); BNX2_WR(bp, BNX2_TBDC_COMMAND, BNX2_TBDC_COMMAND_CMD_REG_ARB); while ((BNX2_RD(bp, BNX2_TBDC_COMMAND) & BNX2_TBDC_COMMAND_CMD_REG_ARB) && j < 100) j++; cid = BNX2_RD(bp, BNX2_TBDC_CID); bdidx = BNX2_RD(bp, BNX2_TBDC_BIDX); valid = BNX2_RD(bp, BNX2_TBDC_CAM_OPCODE); netdev_err(dev, "%02x %06x %04lx %02x [%x]\n", i, cid, bdidx & BNX2_TBDC_BDIDX_BDIDX, bdidx >> 24, (valid >> 8) & 0x0ff); } netdev_err(dev, "<--- end TBDC dump --->\n"); } static void bnx2_dump_state(struct bnx2 *bp) { struct net_device *dev = bp->dev; u32 val1, val2; pci_read_config_dword(bp->pdev, PCI_COMMAND, &val1); netdev_err(dev, "DEBUG: intr_sem[%x] PCI_CMD[%08x]\n", atomic_read(&bp->intr_sem), val1); pci_read_config_dword(bp->pdev, bp->pm_cap + PCI_PM_CTRL, &val1); pci_read_config_dword(bp->pdev, BNX2_PCICFG_MISC_CONFIG, &val2); netdev_err(dev, "DEBUG: PCI_PM[%08x] PCI_MISC_CFG[%08x]\n", val1, val2); netdev_err(dev, "DEBUG: EMAC_TX_STATUS[%08x] EMAC_RX_STATUS[%08x]\n", BNX2_RD(bp, BNX2_EMAC_TX_STATUS), BNX2_RD(bp, BNX2_EMAC_RX_STATUS)); netdev_err(dev, "DEBUG: RPM_MGMT_PKT_CTRL[%08x]\n", BNX2_RD(bp, BNX2_RPM_MGMT_PKT_CTRL)); netdev_err(dev, "DEBUG: HC_STATS_INTERRUPT_STATUS[%08x]\n", BNX2_RD(bp, BNX2_HC_STATS_INTERRUPT_STATUS)); if (bp->flags & BNX2_FLAG_USING_MSIX) { int i; netdev_err(dev, "DEBUG: PBA[%08x]\n", BNX2_RD(bp, BNX2_PCI_GRC_WINDOW3_BASE)); netdev_err(dev, "DEBUG: MSIX table:\n"); val1 = BNX2_PCI_GRC_WINDOW2_BASE; for (i = 0; i < bp->irq_nvecs; i++) { netdev_err(dev, "DEBUG: [%d]: %08x %08x %08x %08x\n", i, BNX2_RD(bp, val1), BNX2_RD(bp, val1 + 4), BNX2_RD(bp, val1 + 8), BNX2_RD(bp, val1 + 12)); val1 += 16; } } } static void bnx2_tx_timeout(struct net_device *dev) { struct bnx2 *bp = netdev_priv(dev); bnx2_dump_ftq(bp); bnx2_dump_state(bp); bnx2_dump_mcp_state(bp); #if defined(__VMKLNX__) if (psod_on_tx_timeout) { msleep(100); BUG_ON(1); return; } #endif if (stop_on_tx_timeout) { netdev_err(dev, "prevent chip reset during tx timeout\n"); return; } /* This allows the netif to be shutdown gracefully before resetting */ #if (LINUX_VERSION_CODE >= 0x20600) schedule_work(&bp->reset_task); #else schedule_task(&bp->reset_task); #endif } #if defined(BCM_VLAN) && !defined(NEW_VLAN) /* Called with rtnl_lock */ static void bnx2_vlan_rx_register(struct net_device *dev, struct vlan_group *vlgrp) { struct bnx2 *bp = netdev_priv(dev); #if defined(__VMKLNX__) && (VMWARE_ESX_DDK_VERSION < 50000) /* rtnl_lock() needed for ESX 4.0 and 4.1 only */ rtnl_lock(); #endif if (netif_running(dev)) bnx2_netif_stop(bp, false); bp->vlgrp = vlgrp; if (netif_running(dev)) { bnx2_set_rx_mode(dev); if (bp->flags & BNX2_FLAG_CAN_KEEP_VLAN) bnx2_fw_sync(bp, BNX2_DRV_MSG_CODE_KEEP_VLAN_UPDATE, 0, 1); bnx2_netif_start(bp, false); } #if defined(__VMKLNX__) && (VMWARE_ESX_DDK_VERSION < 50000) rtnl_unlock(); #endif } #if (LINUX_VERSION_CODE < 0x20616) /* Called with rtnl_lock */ static void bnx2_vlan_rx_kill_vid(struct net_device *dev, uint16_t vid) { struct bnx2 *bp = netdev_priv(dev); #if defined(__VMKLNX__) && (VMWARE_ESX_DDK_VERSION < 50000) /* rtnl_lock() needed for ESX 4.0 and 4.1 only */ rtnl_lock(); #endif if (netif_running(dev)) bnx2_netif_stop(bp, false); vlan_group_set_device(bp->vlgrp, vid, NULL); if (!netif_running(dev)) { #if defined(__VMKLNX__) && (VMWARE_ESX_DDK_VERSION < 50000) rtnl_unlock(); #endif return; } bnx2_set_rx_mode(dev); if (bp->flags & BNX2_FLAG_CAN_KEEP_VLAN) bnx2_fw_sync(bp, BNX2_DRV_MSG_CODE_KEEP_VLAN_UPDATE, 0, 1); bnx2_netif_start(bp, false); #if defined(__VMKLNX__) && (VMWARE_ESX_DDK_VERSION < 50000) rtnl_unlock(); #endif } #endif #endif /* Called with netif_tx_lock. * bnx2_tx_int() runs without netif_tx_lock unless it needs to call * netif_wake_queue(). */ static netdev_tx_t bnx2_start_xmit(struct sk_buff *skb, struct net_device *dev) { struct bnx2 *bp = netdev_priv(dev); dma_addr_t mapping; struct bnx2_tx_bd *txbd; struct bnx2_sw_tx_bd *tx_buf; u32 len, vlan_tag_flags, last_frag, mss; u16 prod, ring_prod; int i; #ifndef BCM_HAVE_MULTI_QUEUE struct bnx2_napi *bnapi = &bp->bnx2_napi[0]; struct bnx2_tx_ring_info *txr = &bnapi->tx_ring; #if defined(__VMKLNX__) && (VMWARE_ESX_DDK_VERSION < 50000) /* Drop the packet if the queue has been stopped */ if (unlikely(netif_queue_stopped(dev))) { dev_kfree_skb(skb); return NETDEV_TX_OK; } #endif #else struct bnx2_napi *bnapi; struct bnx2_tx_ring_info *txr; struct netdev_queue *txq; /* Determine which tx ring we will be placed on */ i = skb_get_queue_mapping(skb); bnapi = &bp->bnx2_napi[i]; txr = &bnapi->tx_ring; txq = netdev_get_tx_queue(dev, i); #if defined(__VMKLNX__) && (VMWARE_ESX_DDK_VERSION < 50000) /* Drop the packet if the queue has been stopped */ if (unlikely(netif_tx_queue_stopped(txq))) { dev_kfree_skb(skb); return NETDEV_TX_OK; } #endif #endif if (unlikely(bnx2_tx_avail(bp, txr) < (skb_shinfo(skb)->nr_frags + 1))) { #ifndef BCM_HAVE_MULTI_QUEUE netif_stop_queue(dev); #else netif_tx_stop_queue(txq); #endif netdev_err(dev, "BUG! Tx ring full when queue awake!\n"); return NETDEV_TX_BUSY; } len = skb_headlen(skb); prod = txr->tx_prod; ring_prod = BNX2_TX_RING_IDX(prod); vlan_tag_flags = 0; if (skb->ip_summed == CHECKSUM_PARTIAL) { vlan_tag_flags |= TX_BD_FLAGS_TCP_UDP_CKSUM; } #ifdef BCM_VLAN #ifdef NEW_VLAN if (vlan_tx_tag_present(skb)) { #else if (bp->vlgrp && vlan_tx_tag_present(skb)) { #endif vlan_tag_flags |= (TX_BD_FLAGS_VLAN_TAG | (vlan_tx_tag_get(skb) << 16)); } #endif #ifdef BCM_TSO if ((mss = skb_shinfo(skb)->gso_size)) { u32 tcp_opt_len; struct iphdr *iph; tcp_opt_len = tcp_optlen(skb); if (skb_transport_offset(skb) + tcp_opt_len + sizeof(struct tcphdr) + mss >= skb->len) goto abort_tso; vlan_tag_flags |= TX_BD_FLAGS_SW_LSO; #ifndef BCM_NO_TSO6 if (skb_shinfo(skb)->gso_type & SKB_GSO_TCPV6) { u32 tcp_off = skb_transport_offset(skb) - sizeof(struct ipv6hdr) - ETH_HLEN; vlan_tag_flags |= ((tcp_opt_len >> 2) << 8) | TX_BD_FLAGS_SW_FLAGS; if (likely(tcp_off == 0)) vlan_tag_flags &= ~TX_BD_FLAGS_TCP6_OFF0_MSK; else { tcp_off >>= 3; vlan_tag_flags |= ((tcp_off & 0x3) << TX_BD_FLAGS_TCP6_OFF0_SHL) | ((tcp_off & 0x10) << TX_BD_FLAGS_TCP6_OFF4_SHL); mss |= (tcp_off & 0xc) << TX_BD_TCP6_OFF2_SHL; } } else #endif { iph = ip_hdr(skb); if (tcp_opt_len || (iph->ihl > 5)) { vlan_tag_flags |= ((iph->ihl - 5) + (tcp_opt_len >> 2)) << 8; } } } else abort_tso: #endif { mss = 0; } #if (LINUX_VERSION_CODE >= 0x02061b) mapping = dma_map_single(&bp->pdev->dev, skb->data, len, PCI_DMA_TODEVICE); if (dma_mapping_error(&bp->pdev->dev, mapping)) { #else mapping = pci_map_single(bp->pdev, skb->data, len, PCI_DMA_TODEVICE); if (pci_dma_mapping_error(mapping)) { #endif dev_kfree_skb(skb); return NETDEV_TX_OK; } tx_buf = &txr->tx_buf_ring[ring_prod]; tx_buf->skb = skb; dma_unmap_addr_set(tx_buf, mapping, mapping); txbd = &txr->tx_desc_ring[ring_prod]; txbd->tx_bd_haddr_hi = (u64) mapping >> 32; txbd->tx_bd_haddr_lo = (u64) mapping & 0xffffffff; txbd->tx_bd_mss_nbytes = len | (mss << 16); txbd->tx_bd_vlan_tag_flags = vlan_tag_flags | TX_BD_FLAGS_START; last_frag = skb_shinfo(skb)->nr_frags; tx_buf->nr_frags = last_frag; tx_buf->is_gso = skb_is_gso(skb); for (i = 0; i < last_frag; i++) { const skb_frag_t *frag = &skb_shinfo(skb)->frags[i]; prod = BNX2_NEXT_TX_BD(prod); ring_prod = BNX2_TX_RING_IDX(prod); txbd = &txr->tx_desc_ring[ring_prod]; len = skb_frag_size(frag); mapping = skb_frag_dma_map(&bp->pdev->dev, frag, 0, len, DMA_TO_DEVICE); #if (LINUX_VERSION_CODE >= 0x02061b) if (dma_mapping_error(&bp->pdev->dev, mapping)) #else if (pci_dma_mapping_error(mapping)) #endif goto dma_error; dma_unmap_addr_set(&txr->tx_buf_ring[ring_prod], mapping, mapping); txbd->tx_bd_haddr_hi = (u64) mapping >> 32; txbd->tx_bd_haddr_lo = (u64) mapping & 0xffffffff; txbd->tx_bd_mss_nbytes = len | (mss << 16); txbd->tx_bd_vlan_tag_flags = vlan_tag_flags; } txbd->tx_bd_vlan_tag_flags |= TX_BD_FLAGS_END; /* Sync BD data before updating TX mailbox */ wmb(); prod = BNX2_NEXT_TX_BD(prod); txr->tx_prod_bseq += skb->len; BNX2_WR16(bp, txr->tx_bidx_addr, prod); BNX2_WR(bp, txr->tx_bseq_addr, txr->tx_prod_bseq); mmiowb(); txr->tx_prod = prod; #if (LINUX_VERSION_CODE <= 0x2061e) || defined(__VMKLNX__) dev->trans_start = jiffies; #endif #if defined(BNX2_ENABLE_NETQUEUE) bnapi->tx_packets_sent++; wmb(); #endif if (unlikely(bnx2_tx_avail(bp, txr) <= MAX_SKB_FRAGS)) { #ifndef BCM_HAVE_MULTI_QUEUE netif_stop_queue(dev); #else netif_tx_stop_queue(txq); #endif /* netif_tx_stop_queue() must be done before checking * tx index in bnx2_tx_avail() below, because in * bnx2_tx_int(), we update tx index before checking for * netif_tx_queue_stopped(). */ smp_mb(); if (bnx2_tx_avail(bp, txr) > bp->tx_wake_thresh) #ifndef BCM_HAVE_MULTI_QUEUE netif_wake_queue(dev); #else netif_tx_wake_queue(txq); #endif } return NETDEV_TX_OK; dma_error: /* save value of frag that failed */ last_frag = i; /* start back at beginning and unmap skb */ prod = txr->tx_prod; ring_prod = BNX2_TX_RING_IDX(prod); tx_buf = &txr->tx_buf_ring[ring_prod]; tx_buf->skb = NULL; #if (LINUX_VERSION_CODE >= 0x02061b) dma_unmap_single(&bp->pdev->dev, dma_unmap_addr(tx_buf, mapping), skb_headlen(skb), PCI_DMA_TODEVICE); #else pci_unmap_single(bp->pdev, dma_unmap_addr(tx_buf, mapping), skb_headlen(skb), PCI_DMA_TODEVICE); #endif /* unmap remaining mapped pages */ for (i = 0; i < last_frag; i++) { prod = BNX2_NEXT_TX_BD(prod); ring_prod = BNX2_TX_RING_IDX(prod); tx_buf = &txr->tx_buf_ring[ring_prod]; #if (LINUX_VERSION_CODE >= 0x02061b) dma_unmap_page(&bp->pdev->dev, dma_unmap_addr(tx_buf, mapping), #else pci_unmap_page(bp->pdev, dma_unmap_addr(tx_buf, mapping), #endif skb_frag_size(&skb_shinfo(skb)->frags[i]), PCI_DMA_TODEVICE); } dev_kfree_skb(skb); return NETDEV_TX_OK; } /* Called with rtnl_lock */ static int bnx2_close(struct net_device *dev) { struct bnx2 *bp = netdev_priv(dev); #if defined(__VMKLNX__) bnx2_cnic_stop(bp); #endif /* defined(__VMKLNX__) */ bnx2_disable_int_sync(bp); #ifdef BNX2_NEW_NAPI bnx2_napi_disable(bp); #endif netif_tx_disable(bp->dev); #if defined(BNX2_ENABLE_NETQUEUE) bnx2_close_netqueue(bp); #endif /* BNX2_ENABLE_NETQUEUE */ del_timer_sync(&bp->timer); #if defined(BNX2_ENABLE_NETQUEUE) if (bp->reset_failed == 0) bnx2_shutdown_chip(bp); #else /* BNX2_ENABLE_NETQUEUE */ bnx2_shutdown_chip(bp); #endif /* BNX2_ENABLE_NETQUEUE */ bnx2_free_irq(bp); bnx2_free_skbs(bp); bnx2_free_mem(bp); #if !defined(__VMKLNX__) bnx2_del_napi(bp); #endif bp->link_up = 0; netif_carrier_off(bp->dev); return 0; } static void bnx2_save_stats(struct bnx2 *bp) { u32 *hw_stats = (u32 *) bp->stats_blk; u32 *temp_stats = (u32 *) bp->temp_stats_blk; int i; /* The 1st 10 counters are 64-bit counters */ for (i = 0; i < 20; i += 2) { u32 hi; u64 lo; hi = temp_stats[i] + hw_stats[i]; lo = (u64) temp_stats[i + 1] + (u64) hw_stats[i + 1]; if (lo > 0xffffffff) hi++; temp_stats[i] = hi; temp_stats[i + 1] = lo & 0xffffffff; } for ( ; i < sizeof(struct statistics_block) / 4; i++) temp_stats[i] += hw_stats[i]; } #define GET_64BIT_NET_STATS64(ctr) \ (unsigned long) ((unsigned long) (ctr##_hi) << 32) + \ (unsigned long) (ctr##_lo) #define GET_64BIT_NET_STATS32(ctr) \ (ctr##_lo) #if (BITS_PER_LONG == 64) #define GET_64BIT_NET_STATS(ctr) \ GET_64BIT_NET_STATS64(bp->stats_blk->ctr) + \ GET_64BIT_NET_STATS64(bp->temp_stats_blk->ctr) #else #define GET_64BIT_NET_STATS(ctr) \ GET_64BIT_NET_STATS32(bp->stats_blk->ctr) + \ GET_64BIT_NET_STATS32(bp->temp_stats_blk->ctr) #endif #define GET_32BIT_NET_STATS(ctr) \ (unsigned long) (bp->stats_blk->ctr + \ bp->temp_stats_blk->ctr) static struct net_device_stats * bnx2_get_stats(struct net_device *dev) { struct bnx2 *bp = netdev_priv(dev); struct net_device_stats *net_stats = &bp->net_stats; if (bp->stats_blk == NULL) return net_stats; net_stats->rx_packets = GET_64BIT_NET_STATS(stat_IfHCInUcastPkts) + GET_64BIT_NET_STATS(stat_IfHCInMulticastPkts) + GET_64BIT_NET_STATS(stat_IfHCInBroadcastPkts); net_stats->tx_packets = GET_64BIT_NET_STATS(stat_IfHCOutUcastPkts) + GET_64BIT_NET_STATS(stat_IfHCOutMulticastPkts) + GET_64BIT_NET_STATS(stat_IfHCOutBroadcastPkts); net_stats->rx_bytes = GET_64BIT_NET_STATS(stat_IfHCInOctets); net_stats->tx_bytes = GET_64BIT_NET_STATS(stat_IfHCOutOctets); net_stats->multicast = GET_64BIT_NET_STATS(stat_IfHCInMulticastPkts); net_stats->collisions = GET_32BIT_NET_STATS(stat_EtherStatsCollisions); net_stats->rx_length_errors = GET_32BIT_NET_STATS(stat_EtherStatsUndersizePkts) + GET_32BIT_NET_STATS(stat_EtherStatsOverrsizePkts); net_stats->rx_over_errors = GET_32BIT_NET_STATS(stat_IfInFTQDiscards) + GET_32BIT_NET_STATS(stat_IfInMBUFDiscards); net_stats->rx_frame_errors = GET_32BIT_NET_STATS(stat_Dot3StatsAlignmentErrors); net_stats->rx_crc_errors = GET_32BIT_NET_STATS(stat_Dot3StatsFCSErrors); net_stats->rx_errors = net_stats->rx_length_errors + net_stats->rx_over_errors + net_stats->rx_frame_errors + net_stats->rx_crc_errors; net_stats->tx_aborted_errors = GET_32BIT_NET_STATS(stat_Dot3StatsExcessiveCollisions) + GET_32BIT_NET_STATS(stat_Dot3StatsLateCollisions); if ((BNX2_CHIP(bp) == BNX2_CHIP_5706) || (BNX2_CHIP_ID(bp) == BNX2_CHIP_ID_5708_A0)) net_stats->tx_carrier_errors = 0; else { net_stats->tx_carrier_errors = GET_32BIT_NET_STATS(stat_Dot3StatsCarrierSenseErrors); } net_stats->tx_errors = GET_32BIT_NET_STATS(stat_emac_tx_stat_dot3statsinternalmactransmiterrors) + net_stats->tx_aborted_errors + net_stats->tx_carrier_errors; net_stats->rx_missed_errors = GET_32BIT_NET_STATS(stat_IfInFTQDiscards) + GET_32BIT_NET_STATS(stat_IfInMBUFDiscards) + GET_32BIT_NET_STATS(stat_FwRxDrop); return net_stats; } /* All ethtool functions called with rtnl_lock */ static int bnx2_get_settings(struct net_device *dev, struct ethtool_cmd *cmd) { struct bnx2 *bp = netdev_priv(dev); int support_serdes = 0, support_copper = 0; cmd->supported = SUPPORTED_Autoneg; if (bp->phy_flags & BNX2_PHY_FLAG_REMOTE_PHY_CAP) { support_serdes = 1; support_copper = 1; } else if (bp->phy_port == PORT_FIBRE) support_serdes = 1; else support_copper = 1; if (support_serdes) { cmd->supported |= SUPPORTED_1000baseT_Full | SUPPORTED_FIBRE; if (bp->phy_flags & BNX2_PHY_FLAG_2_5G_CAPABLE) cmd->supported |= SUPPORTED_2500baseX_Full; } if (support_copper) { cmd->supported |= SUPPORTED_10baseT_Half | SUPPORTED_10baseT_Full | SUPPORTED_100baseT_Half | SUPPORTED_100baseT_Full | SUPPORTED_1000baseT_Full | SUPPORTED_TP; } spin_lock_bh(&bp->phy_lock); cmd->port = bp->phy_port; cmd->advertising = bp->advertising; if (bp->autoneg & AUTONEG_SPEED) { cmd->autoneg = AUTONEG_ENABLE; } else { cmd->autoneg = AUTONEG_DISABLE; } if (netif_carrier_ok(dev)) { ethtool_cmd_speed_set(cmd, bp->line_speed); cmd->duplex = bp->duplex; } else { ethtool_cmd_speed_set(cmd, -1); cmd->duplex = -1; } spin_unlock_bh(&bp->phy_lock); cmd->transceiver = XCVR_INTERNAL; cmd->phy_address = bp->phy_addr; return 0; } static int bnx2_set_settings(struct net_device *dev, struct ethtool_cmd *cmd) { struct bnx2 *bp = netdev_priv(dev); u8 autoneg = bp->autoneg; u8 req_duplex = bp->req_duplex; u16 req_line_speed = bp->req_line_speed; u32 advertising = bp->advertising; int err = -EINVAL; spin_lock_bh(&bp->phy_lock); if (cmd->port != PORT_TP && cmd->port != PORT_FIBRE) goto err_out_unlock; if (cmd->port != bp->phy_port && !(bp->phy_flags & BNX2_PHY_FLAG_REMOTE_PHY_CAP)) goto err_out_unlock; /* If device is down, we can store the settings only if the user * is setting the currently active port. */ if (!netif_running(dev) && cmd->port != bp->phy_port) goto err_out_unlock; if (cmd->autoneg == AUTONEG_ENABLE) { autoneg |= AUTONEG_SPEED; advertising = cmd->advertising; if (cmd->port == PORT_TP) { advertising &= ETHTOOL_ALL_COPPER_SPEED; if (!advertising) advertising = ETHTOOL_ALL_COPPER_SPEED; } else { advertising &= ETHTOOL_ALL_FIBRE_SPEED; if (!advertising) advertising = ETHTOOL_ALL_FIBRE_SPEED; } advertising |= ADVERTISED_Autoneg; } else { if (cmd->port == PORT_FIBRE) { if ((cmd->speed != SPEED_1000 && cmd->speed != SPEED_2500) || (cmd->duplex != DUPLEX_FULL)) goto err_out_unlock; if (cmd->speed == SPEED_2500 && !(bp->phy_flags & BNX2_PHY_FLAG_2_5G_CAPABLE)) goto err_out_unlock; } else if (cmd->speed == SPEED_1000 || cmd->speed == SPEED_2500) goto err_out_unlock; autoneg &= ~AUTONEG_SPEED; req_line_speed = cmd->speed; req_duplex = cmd->duplex; advertising = 0; } bp->autoneg = autoneg; bp->advertising = advertising; bp->req_line_speed = req_line_speed; bp->req_duplex = req_duplex; err = 0; /* If device is down, the new settings will be picked up when it is * brought up. */ if (netif_running(dev)) err = bnx2_setup_phy(bp, cmd->port); err_out_unlock: spin_unlock_bh(&bp->phy_lock); return err; } static void bnx2_get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info) { struct bnx2 *bp = netdev_priv(dev); #if !defined(__VMKLNX__) strcpy(info->driver, DRV_MODULE_NAME); strcpy(info->version, DRV_MODULE_VERSION); strcpy(info->bus_info, pci_name(bp->pdev)); strcpy(info->fw_version, bp->fw_version); #else /* defined (__VMKLNX__) */ strlcpy(info->driver, DRV_MODULE_NAME, sizeof(info->driver)); strlcpy(info->version, DRV_MODULE_VERSION, sizeof(info->version)); strlcpy(info->bus_info, pci_name(bp->pdev), sizeof(info->bus_info)); strlcpy(info->fw_version, bp->fw_version, sizeof(info->fw_version)); #endif /* !defined(__VMKLNX__) */ #if defined(VMWARE_ESX_DDK_VERSION) && \ (VMWARE_ESX_DDK_VERSION >= 35000) && (VMWARE_ESX_DDK_VERSION < 40000) info->eedump_len = bnx2_get_eeprom_len(dev); #endif } #define BNX2_REGDUMP_LEN (32 * 1024) static int bnx2_get_regs_len(struct net_device *dev) { return BNX2_REGDUMP_LEN; } static void bnx2_get_regs(struct net_device *dev, struct ethtool_regs *regs, void *_p) { u32 *p = _p, i, offset; u8 *orig_p = _p; struct bnx2 *bp = netdev_priv(dev); static const u32 reg_boundaries[] = { 0x0000, 0x0098, 0x0400, 0x045c, 0x0800, 0x0880, 0x0c00, 0x0c10, 0x0c30, 0x0d08, 0x1000, 0x101c, 0x1040, 0x1048, 0x1080, 0x10a4, 0x1400, 0x1490, 0x1498, 0x14f0, 0x1500, 0x155c, 0x1580, 0x15dc, 0x1600, 0x1658, 0x1680, 0x16d8, 0x1800, 0x1820, 0x1840, 0x1854, 0x1880, 0x1894, 0x1900, 0x1984, 0x1c00, 0x1c0c, 0x1c40, 0x1c54, 0x1c80, 0x1c94, 0x1d00, 0x1d84, 0x2000, 0x2030, 0x23c0, 0x2400, 0x2800, 0x2820, 0x2830, 0x2850, 0x2b40, 0x2c10, 0x2fc0, 0x3058, 0x3c00, 0x3c94, 0x4000, 0x4010, 0x4080, 0x4090, 0x43c0, 0x4458, 0x4c00, 0x4c18, 0x4c40, 0x4c54, 0x4fc0, 0x5010, 0x53c0, 0x5444, 0x5c00, 0x5c18, 0x5c80, 0x5c90, 0x5fc0, 0x6000, 0x6400, 0x6428, 0x6800, 0x6848, 0x684c, 0x6860, 0x6888, 0x6910, 0x8000 }; regs->version = 0; memset(p, 0, BNX2_REGDUMP_LEN); if (!netif_running(bp->dev)) return; i = 0; offset = reg_boundaries[0]; p += offset; while (offset < BNX2_REGDUMP_LEN) { *p++ = BNX2_RD(bp, offset); offset += 4; if (offset == reg_boundaries[i + 1]) { offset = reg_boundaries[i + 2]; p = (u32 *) (orig_p + offset); i += 2; } } } static void bnx2_get_wol(struct net_device *dev, struct ethtool_wolinfo *wol) { struct bnx2 *bp = netdev_priv(dev); if (bp->flags & BNX2_FLAG_NO_WOL) { wol->supported = 0; wol->wolopts = 0; } else { wol->supported = WAKE_MAGIC; if (bp->wol) wol->wolopts = WAKE_MAGIC; else wol->wolopts = 0; } memset(&wol->sopass, 0, sizeof(wol->sopass)); } static int bnx2_set_wol(struct net_device *dev, struct ethtool_wolinfo *wol) { struct bnx2 *bp = netdev_priv(dev); if (wol->wolopts & ~WAKE_MAGIC) return -EINVAL; if (wol->wolopts & WAKE_MAGIC) { if (bp->flags & BNX2_FLAG_NO_WOL) return -EINVAL; bp->wol = 1; } else { bp->wol = 0; } device_set_wakeup_enable(&bp->pdev->dev, bp->wol); return 0; } static u32 bnx2_get_msglevel(struct net_device *dev) { struct bnx2 *bp = netdev_priv(dev); return bp->msg_enable; } static void bnx2_set_msglevel(struct net_device *dev, u32 value) { struct bnx2 *bp = netdev_priv(dev); bp->msg_enable = value; } static int bnx2_nway_reset(struct net_device *dev) { struct bnx2 *bp = netdev_priv(dev); u32 bmcr; if (!netif_running(dev)) return -EAGAIN; if (!(bp->autoneg & AUTONEG_SPEED)) { return -EINVAL; } spin_lock_bh(&bp->phy_lock); if (bp->phy_flags & BNX2_PHY_FLAG_REMOTE_PHY_CAP) { int rc; rc = bnx2_setup_remote_phy(bp, bp->phy_port); spin_unlock_bh(&bp->phy_lock); return rc; } /* Force a link down visible on the other side */ if (bp->phy_flags & BNX2_PHY_FLAG_SERDES) { bnx2_write_phy(bp, bp->mii_bmcr, BMCR_LOOPBACK); spin_unlock_bh(&bp->phy_lock); bnx2_msleep(20); spin_lock_bh(&bp->phy_lock); bp->current_interval = BNX2_SERDES_AN_TIMEOUT; bp->serdes_an_pending = 1; mod_timer(&bp->timer, jiffies + bp->current_interval); } bnx2_read_phy(bp, bp->mii_bmcr, &bmcr); bmcr &= ~BMCR_LOOPBACK; bnx2_write_phy(bp, bp->mii_bmcr, bmcr | BMCR_ANRESTART | BMCR_ANENABLE); spin_unlock_bh(&bp->phy_lock); return 0; } static u32 bnx2_get_link(struct net_device *dev) { struct bnx2 *bp = netdev_priv(dev); return bp->link_up; } #if (LINUX_VERSION_CODE >= 0x20418) || \ (defined(VMWARE_ESX_DDK_VERSION) && \ ((VMWARE_ESX_DDK_VERSION >= 35000) && (VMWARE_ESX_DDK_VERSION < 40000))) static int bnx2_get_eeprom_len(struct net_device *dev) { struct bnx2 *bp = netdev_priv(dev); if (bp->flash_info == NULL) return 0; return (int) bp->flash_size; } #endif #ifdef ETHTOOL_GEEPROM static int bnx2_get_eeprom(struct net_device *dev, struct ethtool_eeprom *eeprom, u8 *eebuf) { struct bnx2 *bp = netdev_priv(dev); int rc; /* parameters already validated in ethtool_get_eeprom */ rc = bnx2_nvram_read(bp, eeprom->offset, eebuf, eeprom->len); return rc; } #endif #ifdef ETHTOOL_SEEPROM static int bnx2_set_eeprom(struct net_device *dev, struct ethtool_eeprom *eeprom, u8 *eebuf) { struct bnx2 *bp = netdev_priv(dev); int rc; /* parameters already validated in ethtool_set_eeprom */ rc = bnx2_nvram_write(bp, eeprom->offset, eebuf, eeprom->len); return rc; } #endif static int bnx2_get_coalesce(struct net_device *dev, struct ethtool_coalesce *coal) { struct bnx2 *bp = netdev_priv(dev); memset(coal, 0, sizeof(struct ethtool_coalesce)); coal->rx_coalesce_usecs = bp->rx_ticks; coal->rx_max_coalesced_frames = bp->rx_quick_cons_trip; coal->rx_coalesce_usecs_irq = bp->rx_ticks_int; coal->rx_max_coalesced_frames_irq = bp->rx_quick_cons_trip_int; coal->tx_coalesce_usecs = bp->tx_ticks; coal->tx_max_coalesced_frames = bp->tx_quick_cons_trip; coal->tx_coalesce_usecs_irq = bp->tx_ticks_int; coal->tx_max_coalesced_frames_irq = bp->tx_quick_cons_trip_int; coal->stats_block_coalesce_usecs = bp->stats_ticks; return 0; } static int bnx2_set_coalesce(struct net_device *dev, struct ethtool_coalesce *coal) { struct bnx2 *bp = netdev_priv(dev); uint32_t i; bp->rx_ticks = (u16) coal->rx_coalesce_usecs; if (bp->rx_ticks > 0x3ff) bp->rx_ticks = 0x3ff; bp->rx_quick_cons_trip = (u16) coal->rx_max_coalesced_frames; if (bp->rx_quick_cons_trip > 0xff) bp->rx_quick_cons_trip = 0xff; bp->rx_ticks_int = (u16) coal->rx_coalesce_usecs_irq; if (bp->rx_ticks_int > 0x3ff) bp->rx_ticks_int = 0x3ff; bp->rx_quick_cons_trip_int = (u16) coal->rx_max_coalesced_frames_irq; if (bp->rx_quick_cons_trip_int > 0xff) bp->rx_quick_cons_trip_int = 0xff; bp->tx_ticks = (u16) coal->tx_coalesce_usecs; if (bp->tx_ticks > 0x3ff) bp->tx_ticks = 0x3ff; bp->tx_quick_cons_trip = (u16) coal->tx_max_coalesced_frames; if (bp->tx_quick_cons_trip > 0xff) bp->tx_quick_cons_trip = 0xff; bp->tx_ticks_int = (u16) coal->tx_coalesce_usecs_irq; if (bp->tx_ticks_int > 0x3ff) bp->tx_ticks_int = 0x3ff; bp->tx_quick_cons_trip_int = (u16) coal->tx_max_coalesced_frames_irq; if (bp->tx_quick_cons_trip_int > 0xff) bp->tx_quick_cons_trip_int = 0xff; bp->stats_ticks = coal->stats_block_coalesce_usecs; if (bp->flags & BNX2_FLAG_BROKEN_STATS) { if (bp->stats_ticks != 0 && bp->stats_ticks != USEC_PER_SEC) bp->stats_ticks = USEC_PER_SEC; } if (bp->stats_ticks > BNX2_HC_STATS_TICKS_HC_STAT_TICKS) bp->stats_ticks = BNX2_HC_STATS_TICKS_HC_STAT_TICKS; bp->stats_ticks &= BNX2_HC_STATS_TICKS_HC_STAT_TICKS; if (netif_running(bp->dev)) { #if (defined(__VMKLNX__) && (VMWARE_ESX_DDK_VERSION >= 55000)) BNX2_WR(bp, BNX2_HC_TX_QUICK_CONS_TRIP, (bp->tx_quick_cons_trip_int << 16) | bp->tx_quick_cons_trip); BNX2_WR(bp, BNX2_HC_RX_QUICK_CONS_TRIP, (bp->rx_quick_cons_trip_int << 16) | bp->rx_quick_cons_trip); BNX2_WR(bp, BNX2_HC_TX_TICKS, (bp->tx_ticks_int << 16) | bp->tx_ticks); BNX2_WR(bp, BNX2_HC_RX_TICKS, (bp->rx_ticks_int << 16) | bp->rx_ticks); if (bp->flags & BNX2_FLAG_BROKEN_STATS) BNX2_WR(bp, BNX2_HC_STATS_TICKS, 0); else BNX2_WR(bp, BNX2_HC_STATS_TICKS, bp->stats_ticks); if (bp->rx_ticks < 25) bnx2_reg_wr_ind(bp, BNX2_FW_RX_LOW_LATENCY, 1); else bnx2_reg_wr_ind(bp, BNX2_FW_RX_LOW_LATENCY, 0); for (i = 1; i < bp->irq_nvecs; i++) { u32 base = ((i - 1) * BNX2_HC_SB_CONFIG_SIZE) + BNX2_HC_SB_CONFIG_1; BNX2_WR(bp, base, BNX2_HC_SB_CONFIG_1_TX_TMR_MODE | BNX2_HC_SB_CONFIG_1_RX_TMR_MODE | BNX2_HC_SB_CONFIG_1_ONE_SHOT); BNX2_WR(bp, base + BNX2_HC_TX_QUICK_CONS_TRIP_OFF, (bp->tx_quick_cons_trip_int << 16) | bp->tx_quick_cons_trip); BNX2_WR(bp, base + BNX2_HC_TX_TICKS_OFF, (bp->tx_ticks_int << 16) | bp->tx_ticks); BNX2_WR(bp, base + BNX2_HC_RX_QUICK_CONS_TRIP_OFF, (bp->rx_quick_cons_trip_int << 16) | bp->rx_quick_cons_trip); BNX2_WR(bp, base + BNX2_HC_RX_TICKS_OFF, (bp->rx_ticks_int << 16) | bp->rx_ticks); } #else bnx2_netif_stop(bp, true); bnx2_init_nic(bp, 0); bnx2_netif_start(bp, true); #endif /* defined(__VMKLNX__) && (VMWARE_ESX_DDK_VERSION >= 55000) */ } return 0; } static void bnx2_get_ringparam(struct net_device *dev, struct ethtool_ringparam *ering) { struct bnx2 *bp = netdev_priv(dev); ering->rx_max_pending = BNX2_MAX_TOTAL_RX_DESC_CNT; ering->rx_jumbo_max_pending = BNX2_MAX_TOTAL_RX_PG_DESC_CNT; ering->rx_pending = bp->rx_ring_size; ering->rx_jumbo_pending = bp->rx_pg_ring_size; ering->tx_max_pending = BNX2_MAX_TX_DESC_CNT; ering->tx_pending = bp->tx_ring_size; } static int bnx2_change_ring_size(struct bnx2 *bp, u32 rx, u32 tx, bool reset_irq) { int rc = 0; #if defined(__VMKLNX__) if(bp->reset_failed) { netdev_err(bp->dev, "Previous error detected preventing MTU " "change\n"); return -EIO; } #endif /* defined(__VMKLNX__) */ if (netif_running(bp->dev)) { /* Reset will erase chipset stats; save them */ bnx2_save_stats(bp); bnx2_netif_stop(bp, true); #if defined(__VMKLNX__) rc = bnx2_reset_chip(bp, BNX2_DRV_MSG_CODE_RESET); /* Did the chip reset fail ? */ if (rc != 0) { netdev_err(bp->dev, "chip reset failed during MTU " "change\n"); bp->reset_failed = 1; goto error; } bnx2_free_irq(bp); #else /* !defined(__VMKLNX__) */ bnx2_reset_chip(bp, BNX2_DRV_MSG_CODE_RESET); if (reset_irq) { bnx2_free_irq(bp); bnx2_del_napi(bp); } else { __bnx2_free_irq(bp); } #endif /* defined(__VMKLNX__) */ bnx2_free_skbs(bp); bnx2_free_mem(bp); } bnx2_set_rx_ring_size(bp, rx); bp->tx_ring_size = tx; if (netif_running(bp->dev)) { if (reset_irq) { rc = bnx2_setup_int_mode(bp, disable_msi); bnx2_init_napi(bp); } if (!rc) rc = bnx2_alloc_mem(bp); #if defined(BNX2_ENABLE_NETQUEUE) if (rc) { netdev_err(bp->dev, "failed alloc mem during MTU " "change\n"); goto error; } rc = bnx2_request_irq(bp); if (rc) { netdev_err(bp->dev, "failed request irq during MTU " "change %d\n", rc); goto error; } rc = bnx2_init_nic(bp, 0); if (rc) { netdev_err(bp->dev, "failed init nic during MTU " "change\n"); goto error; } #else /* !defined(BNX2_ENABLE_NETQUEUE) */ if (!rc) rc = bnx2_request_irq(bp); if (!rc) rc = bnx2_init_nic(bp, 0); if (rc) { bnx2_napi_enable(bp); dev_close(bp->dev); #if defined(__VMKLNX__) && (VMWARE_ESX_DDK_VERSION == 41000) /* PR 533926 * This is a workaround to sync device status in dev->flags and * dev->gflags. It is needed to avoid PSOD (due to double dev_close) * on reboot. In ESX5.0, the return value of this function will be * checked by NICSetMTU, where gflags will be updated appropriately. */ bp->dev->gflags &= ~IFF_DEV_IS_OPEN; #endif return rc; } #endif /* defined(BNX2_ENABLE_NETQUEUE) */ #ifdef BCM_CNIC mutex_lock(&bp->cnic_lock); /* Let cnic know about the new status block. */ if (bp->cnic_eth_dev.drv_state & CNIC_DRV_STATE_REGD) bnx2_setup_cnic_irq_info(bp); mutex_unlock(&bp->cnic_lock); #endif bnx2_netif_start(bp, true); } return 0; #if defined(__VMKLNX__) error: netif_carrier_off(bp->dev); return rc; #endif /* defined(__VMKLNX__) */ } static int bnx2_set_ringparam(struct net_device *dev, struct ethtool_ringparam *ering) { struct bnx2 *bp = netdev_priv(dev); int rc; if ((ering->rx_pending > BNX2_MAX_TOTAL_RX_DESC_CNT) || (ering->tx_pending > BNX2_MAX_TX_DESC_CNT) || (ering->tx_pending <= MAX_SKB_FRAGS)) { return -EINVAL; } rc = bnx2_change_ring_size(bp, ering->rx_pending, ering->tx_pending, false); return rc; } static void bnx2_get_pauseparam(struct net_device *dev, struct ethtool_pauseparam *epause) { struct bnx2 *bp = netdev_priv(dev); epause->autoneg = ((bp->autoneg & AUTONEG_FLOW_CTRL) != 0); epause->rx_pause = ((bp->flow_ctrl & FLOW_CTRL_RX) != 0); epause->tx_pause = ((bp->flow_ctrl & FLOW_CTRL_TX) != 0); } static int bnx2_set_pauseparam(struct net_device *dev, struct ethtool_pauseparam *epause) { struct bnx2 *bp = netdev_priv(dev); bp->req_flow_ctrl = 0; if (epause->rx_pause) bp->req_flow_ctrl |= FLOW_CTRL_RX; if (epause->tx_pause) bp->req_flow_ctrl |= FLOW_CTRL_TX; if (epause->autoneg) { bp->autoneg |= AUTONEG_FLOW_CTRL; } else { bp->autoneg &= ~AUTONEG_FLOW_CTRL; } if (netif_running(dev)) { spin_lock_bh(&bp->phy_lock); bnx2_setup_phy(bp, bp->phy_port); spin_unlock_bh(&bp->phy_lock); } return 0; } #ifndef NEW_ETHTOOL static u32 bnx2_get_rx_csum(struct net_device *dev) { struct bnx2 *bp = netdev_priv(dev); return bp->rx_csum; } static int bnx2_set_rx_csum(struct net_device *dev, u32 data) { struct bnx2 *bp = netdev_priv(dev); bp->rx_csum = data; return 0; } #ifdef BCM_TSO static int bnx2_set_tso(struct net_device *dev, u32 data) { struct bnx2 *bp = netdev_priv(dev); if (data) { dev->features |= NETIF_F_TSO | NETIF_F_TSO_ECN; if (BNX2_CHIP(bp) == BNX2_CHIP_5709) dev->features |= NETIF_F_TSO6; } else dev->features &= ~(NETIF_F_TSO | NETIF_F_TSO6 | NETIF_F_TSO_ECN); return 0; } #endif #endif static struct { char string[ETH_GSTRING_LEN]; } bnx2_stats_str_arr[] = { { "rx_bytes" }, { "rx_error_bytes" }, { "tx_bytes" }, { "tx_error_bytes" }, { "rx_ucast_packets" }, { "rx_mcast_packets" }, { "rx_bcast_packets" }, { "tx_ucast_packets" }, { "tx_mcast_packets" }, { "tx_bcast_packets" }, { "tx_mac_errors" }, { "tx_carrier_errors" }, { "rx_crc_errors" }, { "rx_align_errors" }, { "tx_single_collisions" }, { "tx_multi_collisions" }, { "tx_deferred" }, { "tx_excess_collisions" }, { "tx_late_collisions" }, { "tx_total_collisions" }, { "rx_fragments" }, { "rx_jabbers" }, { "rx_undersize_packets" }, { "rx_oversize_packets" }, { "rx_64_byte_packets" }, { "rx_65_to_127_byte_packets" }, { "rx_128_to_255_byte_packets" }, { "rx_256_to_511_byte_packets" }, { "rx_512_to_1023_byte_packets" }, { "rx_1024_to_1522_byte_packets" }, { "rx_1523_to_9022_byte_packets" }, { "tx_64_byte_packets" }, { "tx_65_to_127_byte_packets" }, { "tx_128_to_255_byte_packets" }, { "tx_256_to_511_byte_packets" }, { "tx_512_to_1023_byte_packets" }, { "tx_1024_to_1522_byte_packets" }, { "tx_1523_to_9022_byte_packets" }, { "rx_xon_frames" }, { "rx_xoff_frames" }, { "tx_xon_frames" }, { "tx_xoff_frames" }, { "rx_mac_ctrl_frames" }, { "rx_filtered_packets" }, { "rx_ftq_discards" }, { "rx_discards" }, { "rx_fw_discards" }, #if defined(BNX2_ENABLE_NETQUEUE) { "[0] rx_packets" }, { "[0] rx_bytes" }, { "[0] rx_errors" }, { "[0] tx_packets" }, { "[0] tx_bytes" }, { "[1] rx_packets" }, { "[1] rx_bytes" }, { "[1] rx_errors" }, { "[1] tx_packets" }, { "[1] tx_bytes" }, { "[2] rx_packets" }, { "[2] rx_bytes" }, { "[2] rx_errors" }, { "[2] tx_packets" }, { "[2] tx_bytes" }, { "[3] rx_packets" }, { "[3] rx_bytes" }, { "[3] rx_errors" }, { "[3] tx_packets" }, { "[3] tx_bytes" }, { "[4] rx_packets" }, { "[4] rx_bytes" }, { "[4] rx_errors" }, { "[4] tx_packets" }, { "[4] tx_bytes" }, { "[5] rx_packets" }, { "[5] rx_bytes" }, { "[5] rx_errors" }, { "[5] tx_packets" }, { "[5] tx_bytes" }, { "[6] rx_packets" }, { "[6] rx_bytes" }, { "[6] rx_errors" }, { "[6] tx_packets" }, { "[6] tx_bytes" }, { "[7] rx_packets" }, { "[7] rx_bytes" }, { "[7] rx_errors" }, { "[7] tx_packets" }, { "[7] tx_bytes" }, { "[8] rx_packets" }, { "[8] rx_bytes" }, { "[8] rx_errors" }, { "[8] tx_packets" }, { "[8] tx_bytes" }, #endif }; #define BNX2_NUM_STATS ARRAY_SIZE(bnx2_stats_str_arr) #if defined(BNX2_ENABLE_NETQUEUE) #define BNX2_NUM_NETQ_STATS 45 #endif #define STATS_OFFSET32(offset_name) (offsetof(struct statistics_block, offset_name) / 4) static const unsigned long bnx2_stats_offset_arr[BNX2_NUM_STATS] = { STATS_OFFSET32(stat_IfHCInOctets_hi), STATS_OFFSET32(stat_IfHCInBadOctets_hi), STATS_OFFSET32(stat_IfHCOutOctets_hi), STATS_OFFSET32(stat_IfHCOutBadOctets_hi), STATS_OFFSET32(stat_IfHCInUcastPkts_hi), STATS_OFFSET32(stat_IfHCInMulticastPkts_hi), STATS_OFFSET32(stat_IfHCInBroadcastPkts_hi), STATS_OFFSET32(stat_IfHCOutUcastPkts_hi), STATS_OFFSET32(stat_IfHCOutMulticastPkts_hi), STATS_OFFSET32(stat_IfHCOutBroadcastPkts_hi), STATS_OFFSET32(stat_emac_tx_stat_dot3statsinternalmactransmiterrors), STATS_OFFSET32(stat_Dot3StatsCarrierSenseErrors), STATS_OFFSET32(stat_Dot3StatsFCSErrors), STATS_OFFSET32(stat_Dot3StatsAlignmentErrors), STATS_OFFSET32(stat_Dot3StatsSingleCollisionFrames), STATS_OFFSET32(stat_Dot3StatsMultipleCollisionFrames), STATS_OFFSET32(stat_Dot3StatsDeferredTransmissions), STATS_OFFSET32(stat_Dot3StatsExcessiveCollisions), STATS_OFFSET32(stat_Dot3StatsLateCollisions), STATS_OFFSET32(stat_EtherStatsCollisions), STATS_OFFSET32(stat_EtherStatsFragments), STATS_OFFSET32(stat_EtherStatsJabbers), STATS_OFFSET32(stat_EtherStatsUndersizePkts), STATS_OFFSET32(stat_EtherStatsOverrsizePkts), STATS_OFFSET32(stat_EtherStatsPktsRx64Octets), STATS_OFFSET32(stat_EtherStatsPktsRx65Octetsto127Octets), STATS_OFFSET32(stat_EtherStatsPktsRx128Octetsto255Octets), STATS_OFFSET32(stat_EtherStatsPktsRx256Octetsto511Octets), STATS_OFFSET32(stat_EtherStatsPktsRx512Octetsto1023Octets), STATS_OFFSET32(stat_EtherStatsPktsRx1024Octetsto1522Octets), STATS_OFFSET32(stat_EtherStatsPktsRx1523Octetsto9022Octets), STATS_OFFSET32(stat_EtherStatsPktsTx64Octets), STATS_OFFSET32(stat_EtherStatsPktsTx65Octetsto127Octets), STATS_OFFSET32(stat_EtherStatsPktsTx128Octetsto255Octets), STATS_OFFSET32(stat_EtherStatsPktsTx256Octetsto511Octets), STATS_OFFSET32(stat_EtherStatsPktsTx512Octetsto1023Octets), STATS_OFFSET32(stat_EtherStatsPktsTx1024Octetsto1522Octets), STATS_OFFSET32(stat_EtherStatsPktsTx1523Octetsto9022Octets), STATS_OFFSET32(stat_XonPauseFramesReceived), STATS_OFFSET32(stat_XoffPauseFramesReceived), STATS_OFFSET32(stat_OutXonSent), STATS_OFFSET32(stat_OutXoffSent), STATS_OFFSET32(stat_MacControlFramesReceived), STATS_OFFSET32(stat_IfInFramesL2FilterDiscards), STATS_OFFSET32(stat_IfInFTQDiscards), STATS_OFFSET32(stat_IfInMBUFDiscards), STATS_OFFSET32(stat_FwRxDrop), }; /* stat_IfHCInBadOctets and stat_Dot3StatsCarrierSenseErrors are * skipped because of errata. */ static u8 bnx2_5706_stats_len_arr[BNX2_NUM_STATS] = { 8,0,8,8,8,8,8,8,8,8, 4,0,4,4,4,4,4,4,4,4, 4,4,4,4,4,4,4,4,4,4, 4,4,4,4,4,4,4,4,4,4, 4,4,4,4,4,4,4, }; static u8 bnx2_5708_stats_len_arr[BNX2_NUM_STATS] = { 8,0,8,8,8,8,8,8,8,8, 4,4,4,4,4,4,4,4,4,4, 4,4,4,4,4,4,4,4,4,4, 4,4,4,4,4,4,4,4,4,4, 4,4,4,4,4,4,4, }; #define BNX2_NUM_TESTS 6 static struct { char string[ETH_GSTRING_LEN]; } bnx2_tests_str_arr[BNX2_NUM_TESTS] = { { "register_test (offline)" }, { "memory_test (offline)" }, { "loopback_test (offline)" }, { "nvram_test (online)" }, { "interrupt_test (online)" }, { "link_test (online)" }, }; #ifdef ETHTOOL_GFLAGS static int bnx2_get_sset_count(struct net_device *dev, int sset) { switch (sset) { case ETH_SS_TEST: return BNX2_NUM_TESTS; case ETH_SS_STATS: return BNX2_NUM_STATS; default: return -EOPNOTSUPP; } } #else static int bnx2_self_test_count(struct net_device *dev) { return BNX2_NUM_TESTS; } #endif static void bnx2_self_test(struct net_device *dev, struct ethtool_test *etest, u64 *buf) { struct bnx2 *bp = netdev_priv(dev); memset(buf, 0, sizeof(u64) * BNX2_NUM_TESTS); if (etest->flags & ETH_TEST_FL_OFFLINE) { int i; bnx2_netif_stop(bp, true); bnx2_reset_chip(bp, BNX2_DRV_MSG_CODE_DIAG); bnx2_free_skbs(bp); if (bnx2_test_registers(bp) != 0) { buf[0] = 1; etest->flags |= ETH_TEST_FL_FAILED; } if (bnx2_test_memory(bp) != 0) { buf[1] = 1; etest->flags |= ETH_TEST_FL_FAILED; } if ((buf[2] = bnx2_test_loopback(bp)) != 0) etest->flags |= ETH_TEST_FL_FAILED; if (!netif_running(bp->dev)) bnx2_shutdown_chip(bp); else { bnx2_init_nic(bp, 1); bnx2_netif_start(bp, true); } /* wait for link up */ for (i = 0; i < 7; i++) { if (bp->link_up) break; bnx2_msleep_interruptible(1000); } } if (bnx2_test_nvram(bp) != 0) { buf[3] = 1; etest->flags |= ETH_TEST_FL_FAILED; } if (bnx2_test_intr(bp) != 0) { buf[4] = 1; etest->flags |= ETH_TEST_FL_FAILED; } if (bnx2_test_link(bp) != 0) { buf[5] = 1; etest->flags |= ETH_TEST_FL_FAILED; } } static void bnx2_get_strings(struct net_device *dev, u32 stringset, u8 *buf) { switch (stringset) { case ETH_SS_STATS: memcpy(buf, bnx2_stats_str_arr, sizeof(bnx2_stats_str_arr)); break; case ETH_SS_TEST: memcpy(buf, bnx2_tests_str_arr, sizeof(bnx2_tests_str_arr)); break; } } #ifndef ETHTOOL_GFLAGS static int bnx2_get_stats_count(struct net_device *dev) { return BNX2_NUM_STATS; } #endif static void bnx2_get_ethtool_stats(struct net_device *dev, struct ethtool_stats *stats, u64 *buf) { struct bnx2 *bp = netdev_priv(dev); int i; u32 *hw_stats = (u32 *) bp->stats_blk; u32 *temp_stats = (u32 *) bp->temp_stats_blk; u8 *stats_len_arr = NULL; if (hw_stats == NULL) { memset(buf, 0, sizeof(u64) * BNX2_NUM_STATS); return; } if ((BNX2_CHIP_ID(bp) == BNX2_CHIP_ID_5706_A0) || (BNX2_CHIP_ID(bp) == BNX2_CHIP_ID_5706_A1) || (BNX2_CHIP_ID(bp) == BNX2_CHIP_ID_5706_A2) || (BNX2_CHIP_ID(bp) == BNX2_CHIP_ID_5708_A0)) stats_len_arr = bnx2_5706_stats_len_arr; else stats_len_arr = bnx2_5708_stats_len_arr; #if defined(BNX2_ENABLE_NETQUEUE) for (i = 0; i < BNX2_NUM_STATS - BNX2_NUM_NETQ_STATS; i++) { #else for (i = 0; i < BNX2_NUM_STATS; i++) { #endif unsigned long offset; if (stats_len_arr[i] == 0) { /* skip this counter */ buf[i] = 0; continue; } offset = bnx2_stats_offset_arr[i]; if (stats_len_arr[i] == 4) { /* 4-byte counter */ buf[i] = (u64) *(hw_stats + offset) + *(temp_stats + offset); continue; } /* 8-byte counter */ buf[i] = (((u64) *(hw_stats + offset)) << 32) + *(hw_stats + offset + 1) + (((u64) *(temp_stats + offset)) << 32) + *(temp_stats + offset + 1); } #if defined(BNX2_ENABLE_NETQUEUE) /* Copy over the NetQ specific statistics */ { int j; for (j = 0; j < BNX2_MAX_MSIX_VEC; j++) { struct bnx2_napi *bnapi = &bp->bnx2_napi[j]; buf[i + (j*5) + 0] = (u64) (bnapi->stats.rx_packets); buf[i + (j*5) + 1] = (u64) (bnapi->stats.rx_bytes); buf[i + (j*5) + 2] = (u64) (bnapi->stats.rx_errors); buf[i + (j*5) + 3] = (u64) (bnapi->stats.tx_packets); buf[i + (j*5) + 4] = (u64) (bnapi->stats.tx_bytes); } } #endif } #if (LINUX_VERSION_CODE < 0x30000) static int bnx2_phys_id(struct net_device *dev, u32 data) { struct bnx2 *bp = netdev_priv(dev); int i; u32 save; if (data == 0) data = 2; save = BNX2_RD(bp, BNX2_MISC_CFG); BNX2_WR(bp, BNX2_MISC_CFG, BNX2_MISC_CFG_LEDMODE_MAC); for (i = 0; i < (data * 2); i++) { if ((i % 2) == 0) { BNX2_WR(bp, BNX2_EMAC_LED, BNX2_EMAC_LED_OVERRIDE); } else { BNX2_WR(bp, BNX2_EMAC_LED, BNX2_EMAC_LED_OVERRIDE | BNX2_EMAC_LED_1000MB_OVERRIDE | BNX2_EMAC_LED_100MB_OVERRIDE | BNX2_EMAC_LED_10MB_OVERRIDE | BNX2_EMAC_LED_TRAFFIC_OVERRIDE | BNX2_EMAC_LED_TRAFFIC); } bnx2_msleep_interruptible(500); if (signal_pending(current)) break; } BNX2_WR(bp, BNX2_EMAC_LED, 0); BNX2_WR(bp, BNX2_MISC_CFG, save); return 0; } #else static int bnx2_set_phys_id(struct net_device *dev, enum ethtool_phys_id_state state) { struct bnx2 *bp = netdev_priv(dev); switch (state) { case ETHTOOL_ID_ACTIVE: bp->leds_save = BNX2_RD(bp, BNX2_MISC_CFG); BNX2_WR(bp, BNX2_MISC_CFG, BNX2_MISC_CFG_LEDMODE_MAC); return 1; /* cycle on/off once per second */ case ETHTOOL_ID_ON: BNX2_WR(bp, BNX2_EMAC_LED, BNX2_EMAC_LED_OVERRIDE | BNX2_EMAC_LED_1000MB_OVERRIDE | BNX2_EMAC_LED_100MB_OVERRIDE | BNX2_EMAC_LED_10MB_OVERRIDE | BNX2_EMAC_LED_TRAFFIC_OVERRIDE | BNX2_EMAC_LED_TRAFFIC); break; case ETHTOOL_ID_OFF: BNX2_WR(bp, BNX2_EMAC_LED, BNX2_EMAC_LED_OVERRIDE); break; case ETHTOOL_ID_INACTIVE: BNX2_WR(bp, BNX2_EMAC_LED, 0); BNX2_WR(bp, BNX2_MISC_CFG, bp->leds_save); break; } return 0; } #endif #if (LINUX_VERSION_CODE >= 0x20418) && !defined(NEW_ETHTOOL) static int bnx2_set_tx_csum(struct net_device *dev, u32 data) { struct bnx2 *bp = netdev_priv(dev); if (BNX2_CHIP(bp) == BNX2_CHIP_5709) #if (LINUX_VERSION_CODE < 0x2060c) return bnx2_set_tx_hw_csum(dev, data); #elif (LINUX_VERSION_CODE >= 0x20617) return ethtool_op_set_tx_ipv6_csum(dev, data); #else return ethtool_op_set_tx_hw_csum(dev, data); #endif else return ethtool_op_set_tx_csum(dev, data); } #endif #if defined(NETIF_F_RXHASH) && !defined(NEW_ETHTOOL) #if (LINUX_VERSION_CODE >= 0x20624) static int bnx2_set_flags(struct net_device *dev, u32 data) { return ethtool_op_set_flags(dev, data, ETH_FLAG_RXHASH); } #else static int bnx2_set_flags(struct net_device *dev, u32 data) { if (data & (ETH_FLAG_LRO | ETH_FLAG_NTUPLE)) return -EOPNOTSUPP; if (data & ETH_FLAG_RXHASH) dev->features |= NETIF_F_RXHASH; else dev->features &= ~NETIF_F_RXHASH; return 0; } #endif #endif #ifdef HAVE_FIX_FEATURES static netdev_features_t bnx2_fix_features(struct net_device *dev, netdev_features_t features) { struct bnx2 *bp = netdev_priv(dev); if (!(bp->flags & BNX2_FLAG_CAN_KEEP_VLAN)) features |= NETIF_F_HW_VLAN_CTAG_RX; return features; } static int bnx2_set_features(struct net_device *dev, netdev_features_t features) { struct bnx2 *bp = netdev_priv(dev); /* TSO with VLAN tag won't work with current firmware */ if (features & NETIF_F_HW_VLAN_CTAG_TX) dev->vlan_features |= (dev->hw_features & NETIF_F_ALL_TSO); else dev->vlan_features &= ~NETIF_F_ALL_TSO; if ((!!(features & NETIF_F_HW_VLAN_CTAG_RX) != !!(bp->rx_mode & BNX2_EMAC_RX_MODE_KEEP_VLAN_TAG)) && netif_running(dev)) { bnx2_netif_stop(bp, false); dev->features = features; bnx2_set_rx_mode(dev); bnx2_fw_sync(bp, BNX2_DRV_MSG_CODE_KEEP_VLAN_UPDATE, 0, 1); bnx2_netif_start(bp, false); return 1; } return 0; } #endif #if defined(ETHTOOL_GCHANNELS) && !defined(GET_ETHTOOL_OP_EXT) static void bnx2_get_channels(struct net_device *dev, struct ethtool_channels *channels) { struct bnx2 *bp = netdev_priv(dev); u32 max_rx_rings = 1; u32 max_tx_rings = 1; if ((bp->flags & BNX2_FLAG_MSIX_CAP) && !disable_msi) { max_rx_rings = RX_MAX_RINGS; max_tx_rings = TX_MAX_RINGS; } channels->max_rx = max_rx_rings; channels->max_tx = max_tx_rings; channels->max_other = 0; channels->max_combined = 0; channels->rx_count = bp->num_rx_rings; channels->tx_count = bp->num_tx_rings; channels->other_count = 0; channels->combined_count = 0; } static int bnx2_set_channels(struct net_device *dev, struct ethtool_channels *channels) { struct bnx2 *bp = netdev_priv(dev); u32 max_rx_rings = 1; u32 max_tx_rings = 1; int rc = 0; if ((bp->flags & BNX2_FLAG_MSIX_CAP) && !disable_msi) { max_rx_rings = RX_MAX_RINGS; max_tx_rings = TX_MAX_RINGS; } if (channels->rx_count > max_rx_rings || channels->tx_count > max_tx_rings) return -EINVAL; bp->num_req_rx_rings = channels->rx_count; bp->num_req_tx_rings = channels->tx_count; if (netif_running(dev)) rc = bnx2_change_ring_size(bp, bp->rx_ring_size, bp->tx_ring_size, true); return rc; } #endif static struct ethtool_ops bnx2_ethtool_ops = { .get_settings = bnx2_get_settings, .set_settings = bnx2_set_settings, .get_drvinfo = bnx2_get_drvinfo, .get_regs_len = bnx2_get_regs_len, .get_regs = bnx2_get_regs, .get_wol = bnx2_get_wol, .set_wol = bnx2_set_wol, .get_msglevel = bnx2_get_msglevel, .set_msglevel = bnx2_set_msglevel, .nway_reset = bnx2_nway_reset, .get_link = bnx2_get_link, #if (LINUX_VERSION_CODE >= 0x20418) .get_eeprom_len = bnx2_get_eeprom_len, #endif #ifdef ETHTOOL_GEEPROM .get_eeprom = bnx2_get_eeprom, #endif #ifdef ETHTOOL_SEEPROM .set_eeprom = bnx2_set_eeprom, #endif .get_coalesce = bnx2_get_coalesce, .set_coalesce = bnx2_set_coalesce, .get_ringparam = bnx2_get_ringparam, .set_ringparam = bnx2_set_ringparam, .get_pauseparam = bnx2_get_pauseparam, .set_pauseparam = bnx2_set_pauseparam, #ifndef NEW_ETHTOOL .get_rx_csum = bnx2_get_rx_csum, .set_rx_csum = bnx2_set_rx_csum, .get_tx_csum = ethtool_op_get_tx_csum, #if (LINUX_VERSION_CODE >= 0x20418) .set_tx_csum = bnx2_set_tx_csum, #endif .get_sg = ethtool_op_get_sg, .set_sg = ethtool_op_set_sg, #ifdef BCM_TSO .get_tso = ethtool_op_get_tso, .set_tso = bnx2_set_tso, #endif #endif #ifndef ETHTOOL_GFLAGS .self_test_count = bnx2_self_test_count, #endif .self_test = bnx2_self_test, .get_strings = bnx2_get_strings, #if (LINUX_VERSION_CODE < 0x30000) .phys_id = bnx2_phys_id, #else .set_phys_id = bnx2_set_phys_id, #endif #ifndef ETHTOOL_GFLAGS .get_stats_count = bnx2_get_stats_count, #endif .get_ethtool_stats = bnx2_get_ethtool_stats, #ifdef ETHTOOL_GPERMADDR #if (LINUX_VERSION_CODE < 0x020617) .get_perm_addr = ethtool_op_get_perm_addr, #endif #endif #ifdef ETHTOOL_GFLAGS .get_sset_count = bnx2_get_sset_count, #endif #if defined(NETIF_F_RXHASH) && !defined(NEW_ETHTOOL) .set_flags = bnx2_set_flags, .get_flags = ethtool_op_get_flags, #endif #if defined(ETHTOOL_GCHANNELS) && !defined(GET_ETHTOOL_OP_EXT) .get_channels = bnx2_get_channels, .set_channels = bnx2_set_channels, #endif }; #if defined(BNX2_VMWARE_BMAPILNX) static int bnx2_ioctl_cim(struct net_device *dev, struct ifreq *ifr) { struct bnx2 *bp = netdev_priv(dev); void __user *useraddr = ifr->ifr_data; struct bnx2_ioctl_req req; int rc = 0; u32 val; if (copy_from_user(&req, useraddr, sizeof(req))) { netdev_err(bp->dev, "bnx2_ioctl() could not copy from user"); return -EFAULT; } switch(req.cmd) { case BNX2_VMWARE_CIM_CMD_ENABLE_NIC: BNX2_DP(BNX2_MSG_ESX_IOCTL, "enable NIC\n"); rc = bnx2_open(bp->dev); break; case BNX2_VMWARE_CIM_CMD_DISABLE_NIC: BNX2_DP(BNX2_MSG_ESX_IOCTL, "disable NIC\n"); rc = bnx2_close(bp->dev); break; case BNX2_VMWARE_CIM_CMD_REG_READ: { struct bnx2_ioctl_reg_read_req *rd_req; u32 mem_len; #if defined(__VMKLNX__) && defined(__VMKNETDDI_QUEUEOPS__) mem_len = MB_GET_CID_ADDR(NETQUEUE_KCQ_CID + 2); #else mem_len = MB_GET_CID_ADDR(TX_TSS_CID + TX_MAX_TSS_RINGS + 1); #endif rd_req = &req.cmd_req.reg_read; switch (rd_req->reg_access_type) { case BRCM_VMWARE_REG_ACCESS_DIRECT: if (mem_len < rd_req->reg_offset) { netdev_err(bp->dev, "bnx2_ioctl() reg read: " "out of range: " "max reg: 0x%x req reg: 0x%x\n", mem_len, rd_req->reg_offset); rc = -EINVAL; break; } val = BNX2_RD(bp, req.cmd_req.reg_read.reg_offset); BNX2_DP(BNX2_MSG_ESX_IOCTL, "reg read: reg: 0x%x value:0x%x\n", rd_req->reg_offset, rd_req->reg_value); rd_req->reg_value = val; break; case BRCM_VMWARE_REG_ACCESS_PCI_CFG: BNX2_DP(BNX2_MSG_ESX_IOCTL, "PCI config reg read: reg: 0x%x value:0x%x\n", rd_req->reg_offset, rd_req->reg_value); pci_read_config_dword(bp->pdev, rd_req->reg_offset, &val); rd_req->reg_value = val; break; case BRCM_VMWARE_REG_ACCESS_INDIRECT: mem_len = 0x240800; if (mem_len < rd_req->reg_offset) { netdev_err(bp->dev, "bnx2_ioctl() indirect reg read: " "out of range: " "max reg: 0x%x req reg: 0x%x\n", mem_len, rd_req->reg_offset); rc = -EINVAL; break; } val = bnx2_reg_rd_ind(bp, rd_req->reg_offset); BNX2_DP(BNX2_MSG_ESX_IOCTL, "indirect reg read: reg: 0x%x value:0x%x", rd_req->reg_offset, rd_req->reg_value); rd_req->reg_value = val; break; default: netdev_err(bp->dev, "invalid reg read access method: " "access type: 0x%x req reg: 0x%x\n", rd_req->reg_access_type, rd_req->reg_offset); rc = -EINVAL; break; } } case BNX2_VMWARE_CIM_CMD_REG_WRITE: { struct bnx2_ioctl_reg_write_req *wr_req; u32 mem_len; #if defined(__VMKLNX__) && defined(__VMKNETDDI_QUEUEOPS__) mem_len = MB_GET_CID_ADDR(NETQUEUE_KCQ_CID + 2); #else mem_len = MB_GET_CID_ADDR(TX_TSS_CID + TX_MAX_TSS_RINGS + 1); #endif wr_req = &req.cmd_req.reg_write; switch (wr_req->reg_access_type) { case BRCM_VMWARE_REG_ACCESS_DIRECT: if (mem_len < req.cmd_req.reg_write.reg_offset) { netdev_err(bp->dev, "bnx2_ioctl() reg write: " "out of range: max reg: 0x%x " "req reg: 0x%x\n", mem_len, req.cmd_req.reg_write.reg_offset); rc = -EINVAL; break; } BNX2_DP(BNX2_MSG_ESX_IOCTL, "reg write: reg: 0x%x value:0x%x\n", wr_req->reg_offset, wr_req->reg_value); BNX2_WR(bp, wr_req->reg_offset, wr_req->reg_value); break; case BRCM_VMWARE_REG_ACCESS_PCI_CFG: netdev_info(bp->dev, "bnx2_ioctl() PCI config reg write: " "reg: 0x%x value:0x%x\n", wr_req->reg_offset, wr_req->reg_value); pci_write_config_dword(bp->pdev, wr_req->reg_offset, wr_req->reg_value); break; case BRCM_VMWARE_REG_ACCESS_INDIRECT: mem_len = 0x240800; if (mem_len < wr_req->reg_offset) { netdev_err(bp->dev, "bnx2_ioctl() indirect reg write: " "out of range: " "max reg: 0x%x req reg: 0x%x\n", mem_len, wr_req->reg_offset); rc = -EINVAL; break; } bnx2_reg_wr_ind(bp, wr_req->reg_offset, wr_req->reg_value); BNX2_DP(BNX2_MSG_ESX_IOCTL, "indirect reg write: reg: 0x%x value:0x%x\n", wr_req->reg_offset, wr_req->reg_value); wr_req->reg_value = val; break; default: netdev_err(bp->dev, "invalid reg write access method: " "access type: 0x%x reg: 0x%x\n", wr_req->reg_access_type, wr_req->reg_offset); rc = -EINVAL; break; } } case BNX2_VMWARE_CIM_CMD_GET_NIC_PARAM: BNX2_DP(BNX2_MSG_ESX_IOCTL, "get NIC param\n"); req.cmd_req.get_nic_param.mtu = dev->mtu; memcpy(req.cmd_req.get_nic_param.current_mac_addr, dev->dev_addr, sizeof(req.cmd_req.get_nic_param.current_mac_addr)); break; case BNX2_VMWARE_CIM_CMD_GET_NIC_STATUS: BNX2_DP(BNX2_MSG_ESX_IOCTL, "get NIC status\n"); req.cmd_req.get_nic_status.nic_status = netif_running(dev); break; default: netdev_warn(bp->dev, "bnx2_ioctl() unknown req.cmd: 0x%x\n", req.cmd); rc = -EINVAL; } if (rc == 0 && copy_to_user(useraddr, &req, sizeof(req))) { netdev_err(bp->dev, "bnx2_ioctl() couldn't copy to user " "bnx2_ioctl_req\n"); return -EFAULT; } return rc; } #endif /* BNX2_VMWARE_BMAPILNX */ /* Called with rtnl_lock */ static int bnx2_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd) { #if (LINUX_VERSION_CODE >= 0x020607) struct mii_ioctl_data *data = if_mii(ifr); #else struct mii_ioctl_data *data = (struct mii_ioctl_data *) &ifr->ifr_ifru; #endif struct bnx2 *bp = netdev_priv(dev); int err; switch(cmd) { case SIOCGMIIPHY: data->phy_id = bp->phy_addr; /* fallthru */ case SIOCGMIIREG: { u32 mii_regval; if (bp->phy_flags & BNX2_PHY_FLAG_REMOTE_PHY_CAP) return -EOPNOTSUPP; if (!netif_running(dev)) return -EAGAIN; spin_lock_bh(&bp->phy_lock); err = bnx2_read_phy(bp, data->reg_num & 0x1f, &mii_regval); spin_unlock_bh(&bp->phy_lock); data->val_out = mii_regval; return err; } case SIOCSMIIREG: #if defined(__VMKLNX__) if (!capable(CAP_NET_ADMIN)) return -EPERM; #endif if (bp->phy_flags & BNX2_PHY_FLAG_REMOTE_PHY_CAP) return -EOPNOTSUPP; if (!netif_running(dev)) return -EAGAIN; spin_lock_bh(&bp->phy_lock); err = bnx2_write_phy(bp, data->reg_num & 0x1f, data->val_in); spin_unlock_bh(&bp->phy_lock); return err; #if defined(BNX2_VMWARE_BMAPILNX) #define SIOBNX2CIM 0x89F0 case SIOBNX2CIM: return bnx2_ioctl_cim(dev, ifr); #endif /* BNX2_VMWARE_BMAPILNX */ default: /* do nothing */ break; } return -EOPNOTSUPP; } #if defined(__VMKLNX__) static int bnx2_vmk_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd) { int rc; #if (VMWARE_ESX_DDK_VERSION < 50000) /* rtnl_lock() needed for ESX 4.0 and 4.1 only */ rtnl_lock(); #endif rc = bnx2_ioctl(dev, ifr, cmd); #if (VMWARE_ESX_DDK_VERSION < 50000) rtnl_unlock(); #endif return rc; } #endif /* Called with rtnl_lock */ static int bnx2_change_mac_addr(struct net_device *dev, void *p) { struct sockaddr *addr = p; struct bnx2 *bp = netdev_priv(dev); if (!is_valid_ether_addr(addr->sa_data)) return -EADDRNOTAVAIL; memcpy(dev->dev_addr, addr->sa_data, dev->addr_len); if (netif_running(dev)) bnx2_set_mac_addr(bp, bp->dev->dev_addr, 0); return 0; } /* Called with rtnl_lock */ static int bnx2_change_mtu(struct net_device *dev, int new_mtu) { struct bnx2 *bp = netdev_priv(dev); if (((new_mtu + ETH_HLEN) > MAX_ETHERNET_JUMBO_PACKET_SIZE) || ((new_mtu + ETH_HLEN) < MIN_ETHERNET_PACKET_SIZE)) return -EINVAL; dev->mtu = new_mtu; return (bnx2_change_ring_size(bp, bp->rx_ring_size, bp->tx_ring_size, false)); } #if defined(__VMKLNX__) static int bnx2_vmk_change_mtu(struct net_device *dev, int new_mtu) { int rc; #if (VMWARE_ESX_DDK_VERSION < 50000) /* rtnl_lock() needed for ESX 4.0 and 4.1 only */ rtnl_lock(); #endif rc = bnx2_change_mtu(dev, new_mtu); #if (VMWARE_ESX_DDK_VERSION < 50000) rtnl_unlock(); #endif return rc; } #endif #if defined(HAVE_POLL_CONTROLLER) || defined(CONFIG_NET_POLL_CONTROLLER) static void poll_bnx2(struct net_device *dev) { struct bnx2 *bp = netdev_priv(dev); #if defined(RED_HAT_LINUX_KERNEL) && (LINUX_VERSION_CODE < 0x020600) if (netdump_mode) { struct bnx2_irq *irq = &bp->irq_tbl[0]; irq_handler(irq->vector, &bp->bnx2_napi[0], NULL); if (dev->poll_list.prev) { int budget = 64; bnx2_poll(dev, &budget); } } else #endif { int i; for (i = 0; i < bp->irq_nvecs; i++) { struct bnx2_irq *irq = &bp->irq_tbl[i]; disable_irq(irq->vector); #if (LINUX_VERSION_CODE >= 0x20613) || (defined(__VMKLNX__) && (VMWARE_ESX_DDK_VERSION >= 40000)) irq->handler(irq->vector, &bp->bnx2_napi[i]); #else irq->handler(irq->vector, &bp->bnx2_napi[i], NULL); #endif enable_irq(irq->vector); } } } #endif static void __devinit bnx2_get_5709_media(struct bnx2 *bp) { u32 val = BNX2_RD(bp, BNX2_MISC_DUAL_MEDIA_CTRL); u32 bond_id = val & BNX2_MISC_DUAL_MEDIA_CTRL_BOND_ID; u32 strap; if (bond_id == BNX2_MISC_DUAL_MEDIA_CTRL_BOND_ID_C) return; else if (bond_id == BNX2_MISC_DUAL_MEDIA_CTRL_BOND_ID_S) { bp->phy_flags |= BNX2_PHY_FLAG_SERDES; return; } if (val & BNX2_MISC_DUAL_MEDIA_CTRL_STRAP_OVERRIDE) strap = (val & BNX2_MISC_DUAL_MEDIA_CTRL_PHY_CTRL) >> 21; else strap = (val & BNX2_MISC_DUAL_MEDIA_CTRL_PHY_CTRL_STRAP) >> 8; if (bp->func == 0) { switch (strap) { case 0x4: case 0x5: case 0x6: bp->phy_flags |= BNX2_PHY_FLAG_SERDES; return; } } else { switch (strap) { case 0x1: case 0x2: case 0x4: bp->phy_flags |= BNX2_PHY_FLAG_SERDES; return; } } } static void __devinit bnx2_get_pci_speed(struct bnx2 *bp) { u32 reg; reg = BNX2_RD(bp, BNX2_PCICFG_MISC_STATUS); if (reg & BNX2_PCICFG_MISC_STATUS_PCIX_DET) { u32 clkreg; bp->flags |= BNX2_FLAG_PCIX; clkreg = BNX2_RD(bp, BNX2_PCICFG_PCI_CLOCK_CONTROL_BITS); clkreg &= BNX2_PCICFG_PCI_CLOCK_CONTROL_BITS_PCI_CLK_SPD_DET; switch (clkreg) { case BNX2_PCICFG_PCI_CLOCK_CONTROL_BITS_PCI_CLK_SPD_DET_133MHZ: bp->bus_speed_mhz = 133; break; case BNX2_PCICFG_PCI_CLOCK_CONTROL_BITS_PCI_CLK_SPD_DET_95MHZ: bp->bus_speed_mhz = 100; break; case BNX2_PCICFG_PCI_CLOCK_CONTROL_BITS_PCI_CLK_SPD_DET_66MHZ: case BNX2_PCICFG_PCI_CLOCK_CONTROL_BITS_PCI_CLK_SPD_DET_80MHZ: bp->bus_speed_mhz = 66; break; case BNX2_PCICFG_PCI_CLOCK_CONTROL_BITS_PCI_CLK_SPD_DET_48MHZ: case BNX2_PCICFG_PCI_CLOCK_CONTROL_BITS_PCI_CLK_SPD_DET_55MHZ: bp->bus_speed_mhz = 50; break; case BNX2_PCICFG_PCI_CLOCK_CONTROL_BITS_PCI_CLK_SPD_DET_LOW: case BNX2_PCICFG_PCI_CLOCK_CONTROL_BITS_PCI_CLK_SPD_DET_32MHZ: case BNX2_PCICFG_PCI_CLOCK_CONTROL_BITS_PCI_CLK_SPD_DET_38MHZ: bp->bus_speed_mhz = 33; break; } } else { if (reg & BNX2_PCICFG_MISC_STATUS_M66EN) bp->bus_speed_mhz = 66; else bp->bus_speed_mhz = 33; } if (reg & BNX2_PCICFG_MISC_STATUS_32BIT_DET) bp->flags |= BNX2_FLAG_PCI_32BIT; } static void __devinit bnx2_read_vpd_fw_ver(struct bnx2 *bp) { int rc, i, v0_len = 0; u8 *data; u8 *v0_str = NULL; bool mn_match = false; #define BNX2_VPD_NVRAM_OFFSET 0x300 #define BNX2_VPD_LEN 128 #define BNX2_MAX_VER_SLEN 30 data = kmalloc(256, GFP_KERNEL); if (!data) return; rc = bnx2_nvram_read(bp, BNX2_VPD_NVRAM_OFFSET, data + BNX2_VPD_LEN, BNX2_VPD_LEN); if (rc) goto vpd_done; for (i = 0; i < BNX2_VPD_LEN; i += 4) { data[i] = data[i + BNX2_VPD_LEN + 3]; data[i + 1] = data[i + BNX2_VPD_LEN + 2]; data[i + 2] = data[i + BNX2_VPD_LEN + 1]; data[i + 3] = data[i + BNX2_VPD_LEN]; } for (i = 0; i <= BNX2_VPD_LEN - 3; ) { unsigned char val = data[i]; unsigned int block_end; if (val == 0x82 || val == 0x91) { i = (i + 3 + (data[i + 1] + (data[i + 2] << 8))); continue; } if (val != 0x90) goto vpd_done; block_end = (i + 3 + (data[i + 1] + (data[i + 2] << 8))); i += 3; if (block_end > BNX2_VPD_LEN) goto vpd_done; while (i < (block_end - 2)) { int len = data[i + 2]; if (i + 3 + len > block_end) goto vpd_done; if (data[i] == 'M' && data[i + 1] == 'N') { if (len != 4 || memcmp(&data[i + 3], "1028", 4)) goto vpd_done; mn_match = true; } else if (data[i] == 'V' && data[i + 1] == '0') { if (len > BNX2_MAX_VER_SLEN) goto vpd_done; v0_len = len; v0_str = &data[i + 3]; } i += 3 + len; if (mn_match && v0_str) { memcpy(bp->fw_version, v0_str, v0_len); bp->fw_version[v0_len] = ' '; goto vpd_done; } } goto vpd_done; } vpd_done: kfree(data); } static int __devinit bnx2_init_board(struct pci_dev *pdev, struct net_device *dev) { struct bnx2 *bp; int rc, i, j; u32 reg; u64 dma_mask, persist_dma_mask; int __maybe_unused err; #if (LINUX_VERSION_CODE < 0x20610) SET_MODULE_OWNER(dev); #endif #if (LINUX_VERSION_CODE >= 0x20419) SET_NETDEV_DEV(dev, &pdev->dev); #endif bp = netdev_priv(dev); bp->flags = 0; bp->phy_flags = 0; bp->temp_stats_blk = kmalloc(sizeof(struct statistics_block), GFP_KERNEL); if (bp->temp_stats_blk == NULL) { rc = -ENOMEM; goto err_out; } memset(bp->temp_stats_blk, 0, sizeof(struct statistics_block)); /* enable device (incl. PCI PM wakeup), and bus-mastering */ rc = pci_enable_device(pdev); if (rc) { dev_err(&pdev->dev, "Cannot enable PCI device, aborting\n"); goto err_out; } if (!(pci_resource_flags(pdev, 0) & IORESOURCE_MEM)) { dev_err(&pdev->dev, "Cannot find PCI device base address, aborting\n"); rc = -ENODEV; goto err_out_disable; } rc = pci_request_regions(pdev, DRV_MODULE_NAME); if (rc) { dev_err(&pdev->dev, "Cannot obtain PCI resources, aborting\n"); goto err_out_disable; } pci_set_master(pdev); bp->pm_cap = pci_find_capability(pdev, PCI_CAP_ID_PM); if (bp->pm_cap == 0) { dev_err(&pdev->dev, "Cannot find power management capability, aborting\n"); rc = -EIO; goto err_out_release; } bp->dev = dev; bp->pdev = pdev; spin_lock_init(&bp->phy_lock); spin_lock_init(&bp->indirect_lock); #if defined(BNX2_ENABLE_NETQUEUE) mutex_init(&bp->netq_lock); #endif #ifdef BCM_CNIC mutex_init(&bp->cnic_lock); #endif #if (LINUX_VERSION_CODE >= 0x20600) #if defined(INIT_DELAYED_WORK_DEFERRABLE) || defined(INIT_WORK_NAR) || defined(INIT_DEFERRABLE_WORK) || (defined(__VMKLNX__) && (VMWARE_ESX_DDK_VERSION >= 40000)) INIT_WORK(&bp->reset_task, bnx2_reset_task); #else INIT_WORK(&bp->reset_task, bnx2_reset_task, bp); #endif #else INIT_TQUEUE(&bp->reset_task, bnx2_reset_task, bp); #endif #if defined(BNX2_ENABLE_NETQUEUE) bp->regview = pci_iomap(pdev, 0, MB_GET_CID_ADDR(NETQUEUE_KCQ_CID + 2)); #else bp->regview = pci_iomap(pdev, 0, MB_GET_CID_ADDR(TX_TSS_CID + TX_MAX_TSS_RINGS + 1)); #endif if (!bp->regview) { dev_err(&pdev->dev, "Cannot map register space, aborting\n"); rc = -ENOMEM; goto err_out_release; } /* Configure byte swap and enable write to the reg_window registers. * Rely on CPU to do target byte swapping on big endian systems * The chip's target access swapping will not swap all accesses */ BNX2_WR(bp, BNX2_PCICFG_MISC_CONFIG, BNX2_PCICFG_MISC_CONFIG_REG_WINDOW_ENA | BNX2_PCICFG_MISC_CONFIG_TARGET_MB_WORD_SWAP); bp->chip_id = BNX2_RD(bp, BNX2_MISC_ID); if (BNX2_CHIP(bp) == BNX2_CHIP_5709) { if (!pci_is_pcie(pdev)) { dev_err(&pdev->dev, "Not PCIE, aborting\n"); rc = -EIO; goto err_out_unmap; } bp->flags |= BNX2_FLAG_PCIE; if (BNX2_CHIP_REV(bp) == BNX2_CHIP_REV_Ax) bp->flags |= BNX2_FLAG_JUMBO_BROKEN; #if !defined(CONFIG_PPC64) && !defined(CONFIG_PPC32) /* AER (Advanced Error Reporting) hooks */ err = pci_enable_pcie_error_reporting(pdev); if (!err) bp->flags |= BNX2_FLAG_AER_ENABLED; #endif } else { bp->pcix_cap = pci_find_capability(pdev, PCI_CAP_ID_PCIX); if (bp->pcix_cap == 0) { dev_err(&pdev->dev, "Cannot find PCIX capability, aborting\n"); rc = -EIO; goto err_out_unmap; } bp->flags |= BNX2_FLAG_BROKEN_STATS; } #ifdef CONFIG_PCI_MSI if (BNX2_CHIP(bp) == BNX2_CHIP_5709 && BNX2_CHIP_REV(bp) != BNX2_CHIP_REV_Ax) { if (pci_find_capability(pdev, PCI_CAP_ID_MSIX)) bp->flags |= BNX2_FLAG_MSIX_CAP; } #endif if (BNX2_CHIP_ID(bp) != BNX2_CHIP_ID_5706_A0 && BNX2_CHIP_ID(bp) != BNX2_CHIP_ID_5706_A1) { if (pci_find_capability(pdev, PCI_CAP_ID_MSI)) bp->flags |= BNX2_FLAG_MSI_CAP; } /* 5708 cannot support DMA addresses > 40-bit. */ if (BNX2_CHIP(bp) == BNX2_CHIP_5708) persist_dma_mask = dma_mask = DMA_BIT_MASK(40); else persist_dma_mask = dma_mask = DMA_BIT_MASK(64); /* Configure DMA attributes. */ if (pci_set_dma_mask(pdev, dma_mask) == 0) { #if defined(__VMKLNX__) && (VMWARE_ESX_DDK_VERSION >= 50000) if (BNX2_CHIP(bp) == BNX2_CHIP_5708) dev->features |= NETIF_F_DMA40; else dev->features |= NETIF_F_HIGHDMA; #else dev->features |= NETIF_F_HIGHDMA; #endif rc = pci_set_consistent_dma_mask(pdev, persist_dma_mask); if (rc) { dev_err(&pdev->dev, "pci_set_consistent_dma_mask failed, aborting\n"); goto err_out_unmap; } } else if ((rc = pci_set_dma_mask(pdev, DMA_BIT_MASK(32))) != 0) { dev_err(&pdev->dev, "System does not support DMA, aborting\n"); goto err_out_unmap; } if (!(bp->flags & BNX2_FLAG_PCIE)) bnx2_get_pci_speed(bp); /* 5706A0 may falsely detect SERR and PERR. */ if (BNX2_CHIP_ID(bp) == BNX2_CHIP_ID_5706_A0) { reg = BNX2_RD(bp, PCI_COMMAND); reg &= ~(PCI_COMMAND_SERR | PCI_COMMAND_PARITY); BNX2_WR(bp, PCI_COMMAND, reg); } else if ((BNX2_CHIP_ID(bp) == BNX2_CHIP_ID_5706_A1) && !(bp->flags & BNX2_FLAG_PCIX)) { dev_err(&pdev->dev, "5706 A1 can only be used in a PCIX bus, aborting\n"); goto err_out_unmap; } bnx2_init_nvram(bp); reg = bnx2_reg_rd_ind(bp, BNX2_SHM_HDR_SIGNATURE); if (bnx2_reg_rd_ind(bp, BNX2_MCP_TOE_ID) & BNX2_MCP_TOE_ID_FUNCTION_ID) bp->func = 1; if ((reg & BNX2_SHM_HDR_SIGNATURE_SIG_MASK) == BNX2_SHM_HDR_SIGNATURE_SIG) { u32 off = bp->func << 2; bp->shmem_base = bnx2_reg_rd_ind(bp, BNX2_SHM_HDR_ADDR_0 + off); } else bp->shmem_base = HOST_VIEW_SHMEM_BASE; /* Get the permanent MAC address. First we need to make sure the * firmware is actually running. */ reg = bnx2_shmem_rd(bp, BNX2_DEV_INFO_SIGNATURE); if ((reg & BNX2_DEV_INFO_SIGNATURE_MAGIC_MASK) != BNX2_DEV_INFO_SIGNATURE_MAGIC) { dev_err(&pdev->dev, "Firmware not running, aborting\n"); rc = -ENODEV; goto err_out_unmap; } bnx2_read_vpd_fw_ver(bp); j = strlen(bp->fw_version); reg = bnx2_shmem_rd(bp, BNX2_DEV_INFO_BC_REV); for (i = 0; i < 3 && j < 24; i++) { u8 num, k, skip0; if (i == 0) { bp->fw_version[j++] = 'b'; bp->fw_version[j++] = 'c'; bp->fw_version[j++] = ' '; } num = (u8) (reg >> (24 - (i * 8))); for (k = 100, skip0 = 1; k >= 1; num %= k, k /= 10) { if (num >= k || !skip0 || k == 1) { bp->fw_version[j++] = (num / k) + '0'; skip0 = 0; } } if (i != 2) bp->fw_version[j++] = '.'; } reg = bnx2_shmem_rd(bp, BNX2_PORT_FEATURE); if (reg & BNX2_PORT_FEATURE_WOL_ENABLED) bp->wol = 1; if (reg & BNX2_PORT_FEATURE_ASF_ENABLED) { bp->flags |= BNX2_FLAG_ASF_ENABLE; for (i = 0; i < 30; i++) { reg = bnx2_shmem_rd(bp, BNX2_BC_STATE_CONDITION); if (reg & BNX2_CONDITION_MFW_RUN_MASK) break; bnx2_msleep(10); } } reg = bnx2_shmem_rd(bp, BNX2_BC_STATE_CONDITION); reg &= BNX2_CONDITION_MFW_RUN_MASK; if (reg != BNX2_CONDITION_MFW_RUN_UNKNOWN && reg != BNX2_CONDITION_MFW_RUN_NONE) { u32 addr = bnx2_shmem_rd(bp, BNX2_MFW_VER_PTR); if (j < 32) bp->fw_version[j++] = ' '; for (i = 0; i < 3 && j < 28; i++) { reg = bnx2_reg_rd_ind(bp, addr + i * 4); reg = be32_to_cpu(reg); memcpy(&bp->fw_version[j], &reg, 4); j += 4; } } reg = bnx2_shmem_rd(bp, BNX2_PORT_HW_CFG_MAC_UPPER); bp->mac_addr[0] = (u8) (reg >> 8); bp->mac_addr[1] = (u8) reg; reg = bnx2_shmem_rd(bp, BNX2_PORT_HW_CFG_MAC_LOWER); bp->mac_addr[2] = (u8) (reg >> 24); bp->mac_addr[3] = (u8) (reg >> 16); bp->mac_addr[4] = (u8) (reg >> 8); bp->mac_addr[5] = (u8) reg; bp->tx_ring_size = BNX2_MAX_TX_DESC_CNT; bnx2_set_rx_ring_size(bp, 255); bp->rx_csum = 1; bp->tx_quick_cons_trip_int = 2; bp->tx_quick_cons_trip = 20; bp->tx_ticks_int = 18; bp->tx_ticks = 80; bp->rx_quick_cons_trip_int = 2; bp->rx_quick_cons_trip = 12; bp->rx_ticks_int = 18; bp->rx_ticks = 18; bp->stats_ticks = USEC_PER_SEC & BNX2_HC_STATS_TICKS_HC_STAT_TICKS; bp->current_interval = BNX2_TIMER_INTERVAL; bp->phy_addr = 1; /* Disable WOL support if we are running on a SERDES chip. */ if (BNX2_CHIP(bp) == BNX2_CHIP_5709) bnx2_get_5709_media(bp); else if (BNX2_CHIP_BOND(bp) & BNX2_CHIP_BOND_SERDES_BIT) bp->phy_flags |= BNX2_PHY_FLAG_SERDES; bp->phy_port = PORT_TP; if (bp->phy_flags & BNX2_PHY_FLAG_SERDES) { bp->phy_port = PORT_FIBRE; reg = bnx2_shmem_rd(bp, BNX2_SHARED_HW_CFG_CONFIG); if (!(reg & BNX2_SHARED_HW_CFG_GIG_LINK_ON_VAUX)) { bp->flags |= BNX2_FLAG_NO_WOL; bp->wol = 0; } if (BNX2_CHIP(bp) == BNX2_CHIP_5706) { /* Don't do parallel detect on this board because of * some board problems. The link will not go down * if we do parallel detect. */ if (pdev->subsystem_vendor == PCI_VENDOR_ID_HP && pdev->subsystem_device == 0x310c) bp->phy_flags |= BNX2_PHY_FLAG_NO_PARALLEL; } else { bp->phy_addr = 2; if (reg & BNX2_SHARED_HW_CFG_PHY_2_5G) bp->phy_flags |= BNX2_PHY_FLAG_2_5G_CAPABLE; } } else if (BNX2_CHIP(bp) == BNX2_CHIP_5706 || BNX2_CHIP(bp) == BNX2_CHIP_5708) bp->phy_flags |= BNX2_PHY_FLAG_CRC_FIX; else if (BNX2_CHIP(bp) == BNX2_CHIP_5709 && (BNX2_CHIP_REV(bp) == BNX2_CHIP_REV_Ax || BNX2_CHIP_REV(bp) == BNX2_CHIP_REV_Bx)) bp->phy_flags |= BNX2_PHY_FLAG_DIS_EARLY_DAC; bp->fw_wr_seq = bnx2_shmem_rd(bp, BNX2_FW_MB) & BNX2_FW_MSG_ACK; bnx2_init_fw_cap(bp); if ((BNX2_CHIP_ID(bp) == BNX2_CHIP_ID_5708_A0) || (BNX2_CHIP_ID(bp) == BNX2_CHIP_ID_5708_B0) || (BNX2_CHIP_ID(bp) == BNX2_CHIP_ID_5708_B1) || !(BNX2_RD(bp, BNX2_PCI_CONFIG_3) & BNX2_PCI_CONFIG_3_VAUX_PRESET)) { bp->flags |= BNX2_FLAG_NO_WOL; bp->wol = 0; } if (bp->flags & BNX2_FLAG_NO_WOL) device_set_wakeup_capable(&bp->pdev->dev, false); else device_set_wakeup_enable(&bp->pdev->dev, bp->wol); if (BNX2_CHIP_ID(bp) == BNX2_CHIP_ID_5706_A0) { bp->tx_quick_cons_trip_int = bp->tx_quick_cons_trip; bp->tx_ticks_int = bp->tx_ticks; bp->rx_quick_cons_trip_int = bp->rx_quick_cons_trip; bp->rx_ticks_int = bp->rx_ticks; bp->comp_prod_trip_int = bp->comp_prod_trip; bp->com_ticks_int = bp->com_ticks; bp->cmd_ticks_int = bp->cmd_ticks; } #ifdef CONFIG_PCI_MSI #if defined(__VMKLNX__) /* PR496996: There is some additional setup needed for the P2P * ServerWorks bridge with VID/DID of 0x1666/0x0036 when * 5706 is plugged into an IBM system x3655 server and MSI * is used. Since that workaround cannot be done using * vmklinux api, we are disabling MSI on 5706 to avoid PSOD. */ if (BNX2_CHIP(bp) == BNX2_CHIP_5706) disable_msi = 1; #else /* !defined(__VMKLNX__) */ /* Disable MSI on 5706 if AMD 8132 bridge is found. * * MSI is defined to be 32-bit write. The 5706 does 64-bit MSI writes * with byte enables disabled on the unused 32-bit word. This is legal * but causes problems on the AMD 8132 which will eventually stop * responding after a while. * * AMD believes this incompatibility is unique to the 5706, and * prefers to locally disable MSI rather than globally disabling it. */ if (BNX2_CHIP(bp) == BNX2_CHIP_5706 && disable_msi == 0) { struct pci_dev *amd_8132 = NULL; while ((amd_8132 = pci_get_device(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_8132_BRIDGE, amd_8132))) { u8 rev; pci_read_config_byte(amd_8132, PCI_REVISION_ID, &rev); if (rev >= 0x10 && rev <= 0x13) { disable_msi = 1; pci_dev_put(amd_8132); break; } } } #endif /* defined(__VMKLNX__) */ #endif bnx2_set_default_link(bp); bp->req_flow_ctrl = FLOW_CTRL_RX | FLOW_CTRL_TX; init_timer(&bp->timer); bp->timer.expires = RUN_AT(BNX2_TIMER_INTERVAL); bp->timer.data = (unsigned long) bp; bp->timer.function = bnx2_timer; #ifdef BCM_CNIC if (bnx2_shmem_rd(bp, BNX2_ISCSI_INITIATOR) & BNX2_ISCSI_INITIATOR_EN) bp->cnic_eth_dev.max_iscsi_conn = (bnx2_shmem_rd(bp, BNX2_ISCSI_MAX_CONN) & BNX2_ISCSI_MAX_CONN_MASK) >> BNX2_ISCSI_MAX_CONN_SHIFT; bp->version = BNX2_DEV_VER; #if defined(BNX2_INBOX) bp->cnic_probe = bnx2_cnic_probe; #else bp->cnic_probe = bnx2_cnic_probe2; #endif #endif #if (LINUX_VERSION_CODE >= 0x020611) pci_save_state(pdev); #endif return 0; err_out_unmap: if (bp->flags & BNX2_FLAG_AER_ENABLED) { pci_disable_pcie_error_reporting(pdev); bp->flags &= ~BNX2_FLAG_AER_ENABLED; } pci_iounmap(pdev, bp->regview); bp->regview = NULL; err_out_release: pci_release_regions(pdev); err_out_disable: pci_disable_device(pdev); pci_set_drvdata(pdev, NULL); err_out: return rc; } static char * __devinit bnx2_bus_string(struct bnx2 *bp, char *str) { char *s = str; if (bp->flags & BNX2_FLAG_PCIE) { s += sprintf(s, "PCI Express"); } else { s += sprintf(s, "PCI"); if (bp->flags & BNX2_FLAG_PCIX) s += sprintf(s, "-X"); if (bp->flags & BNX2_FLAG_PCI_32BIT) s += sprintf(s, " 32-bit"); else s += sprintf(s, " 64-bit"); s += sprintf(s, " %dMHz", bp->bus_speed_mhz); } return str; } #if !defined(__VMKLNX__) static void bnx2_del_napi(struct bnx2 *bp) #else static void __devinit bnx2_del_napi(struct bnx2 *bp) #endif { #ifdef BNX2_NEW_NAPI int i; for (i = 0; i < bp->irq_nvecs; i++) netif_napi_del(&bp->bnx2_napi[i].napi); #endif } #if !defined(__VMKLNX__) static void bnx2_init_napi(struct bnx2 *bp) #else static void __devinit bnx2_init_napi(struct bnx2 *bp) #endif { int i; for (i = 0; i < bp->irq_nvecs; i++) { struct bnx2_napi *bnapi = &bp->bnx2_napi[i]; #ifdef BNX2_NEW_NAPI int (*poll)(struct napi_struct *, int); if (i == 0) poll = bnx2_poll; else poll = bnx2_poll_msix; netif_napi_add(bp->dev, &bp->bnx2_napi[i].napi, poll, 64); #endif bnapi->bp = bp; } #ifndef BNX2_NEW_NAPI bp->dev->poll = bnx2_poll; bp->dev->weight = 64; #endif } #if defined(HAVE_NET_DEVICE_OPS) || (LINUX_VERSION_CODE >= 0x30000) static const struct net_device_ops bnx2_netdev_ops = { .ndo_open = bnx2_open, .ndo_start_xmit = bnx2_start_xmit, .ndo_stop = bnx2_close, .ndo_get_stats = bnx2_get_stats, .ndo_set_rx_mode = bnx2_set_rx_mode, #if defined(__VMKLNX__) .ndo_do_ioctl = bnx2_vmk_ioctl, #else .ndo_do_ioctl = bnx2_ioctl, #endif .ndo_validate_addr = eth_validate_addr, .ndo_set_mac_address = bnx2_change_mac_addr, #if defined(__VMKLNX__) .ndo_change_mtu = bnx2_vmk_change_mtu, #else .ndo_change_mtu = bnx2_change_mtu, #endif #ifdef HAVE_FIX_FEATURES .ndo_fix_features = bnx2_fix_features, .ndo_set_features = bnx2_set_features, #endif .ndo_tx_timeout = bnx2_tx_timeout, #if defined(BCM_VLAN) && !defined(NEW_VLAN) .ndo_vlan_rx_register = bnx2_vlan_rx_register, #endif #if defined(HAVE_POLL_CONTROLLER) || defined(CONFIG_NET_POLL_CONTROLLER) .ndo_poll_controller = poll_bnx2, #endif }; #endif static inline void vlan_features_add(struct net_device *dev, unsigned long flags) { #if (LINUX_VERSION_CODE >= 0x2061a) #ifdef BCM_VLAN dev->vlan_features |= flags; #endif #endif } static int __devinit bnx2_init_one(struct pci_dev *pdev, const struct pci_device_id *ent) { static int version_printed = 0; struct net_device *dev; struct bnx2 *bp; int rc; char str[40]; DECLARE_MAC_BUF(mac); #if (defined(__VMKLNX__) && (VMWARE_ESX_DDK_VERSION >= 55000)) || \ (defined(BNX2_ENABLE_NETQUEUE)) static int index = 0; #endif if (version_printed++ == 0) pr_info("%s", version); /* dev zeroed in init_etherdev */ #if (LINUX_VERSION_CODE >= 0x20418) #ifndef BCM_HAVE_MULTI_QUEUE dev = alloc_etherdev(sizeof(*bp)); #else dev = alloc_etherdev_mq(sizeof(*bp), TX_MAX_RINGS); #endif #else dev = init_etherdev(NULL, sizeof(*bp)); #endif if (!dev) return -ENOMEM; rc = bnx2_init_board(pdev, dev); if (rc < 0) goto err_free; #if !defined(HAVE_NET_DEVICE_OPS) && (LINUX_VERSION_CODE < 0x30000) dev->open = bnx2_open; dev->hard_start_xmit = bnx2_start_xmit; dev->stop = bnx2_close; dev->get_stats = bnx2_get_stats; #ifdef BCM_HAVE_SET_RX_MODE dev->set_rx_mode = bnx2_set_rx_mode; #else dev->set_multicast_list = bnx2_set_rx_mode; #endif #if defined(__VMKLNX__) dev->do_ioctl = bnx2_vmk_ioctl; #else dev->do_ioctl = bnx2_ioctl; #endif dev->set_mac_address = bnx2_change_mac_addr; #if defined(__VMKLNX__) dev->change_mtu = bnx2_vmk_change_mtu; #else dev->change_mtu = bnx2_change_mtu; #endif dev->tx_timeout = bnx2_tx_timeout; #ifdef BCM_VLAN dev->vlan_rx_register = bnx2_vlan_rx_register; #if (LINUX_VERSION_CODE < 0x20616) dev->vlan_rx_kill_vid = bnx2_vlan_rx_kill_vid; #endif #endif #if defined(HAVE_POLL_CONTROLLER) || defined(CONFIG_NET_POLL_CONTROLLER) dev->poll_controller = poll_bnx2; #endif #else dev->netdev_ops = &bnx2_netdev_ops; #endif dev->watchdog_timeo = TX_TIMEOUT; dev->ethtool_ops = &bnx2_ethtool_ops; bp = netdev_priv(dev); /* NAPI add must be called in bnx2_init_one() on ESX so that the * proper affinity will be assigned */ bp->msg_enable = debug; #if defined(__VMKLNX__) bnx2_setup_int_mode(bp, disable_msi); bnx2_init_napi(bp); #endif /* (__VMKLNX__)*/ pci_set_drvdata(pdev, dev); memcpy(dev->dev_addr, bp->mac_addr, 6); #ifdef ETHTOOL_GPERMADDR memcpy(dev->perm_addr, bp->mac_addr, 6); #endif #ifdef NETIF_F_IPV6_CSUM dev->features |= NETIF_F_IP_CSUM | NETIF_F_SG; #if defined(NETIF_F_GRO) && defined(BNX2_NEW_NAPI) dev->features |= NETIF_F_GRO; #endif #ifdef NETIF_F_RXHASH dev->features |= NETIF_F_RXHASH; #endif vlan_features_add(dev, NETIF_F_IP_CSUM | NETIF_F_SG); if (BNX2_CHIP(bp) == BNX2_CHIP_5709) { dev->features |= NETIF_F_IPV6_CSUM; vlan_features_add(dev, NETIF_F_IPV6_CSUM); } #else dev->features |= NETIF_F_SG; if (BNX2_CHIP(bp) == BNX2_CHIP_5709) dev->features |= NETIF_F_HW_CSUM; else dev->features |= NETIF_F_IP_CSUM; #endif #ifdef BCM_VLAN dev->features |= NETIF_F_HW_VLAN_CTAG_TX | NETIF_F_HW_VLAN_CTAG_RX; #endif #ifdef BCM_TSO dev->features |= NETIF_F_TSO | NETIF_F_TSO_ECN; vlan_features_add(dev, NETIF_F_TSO | NETIF_F_TSO_ECN); if (BNX2_CHIP(bp) == BNX2_CHIP_5709) { dev->features |= NETIF_F_TSO6; vlan_features_add(dev, NETIF_F_TSO6); } #endif #if defined(__VMKLNX__) && (VMWARE_ESX_DDK_VERSION >= 50000) if (BNX2_CHIP(bp) == BNX2_CHIP_5706 || BNX2_CHIP(bp) == BNX2_CHIP_5708) { dev->features |= NETIF_F_NO_SCHED; } #endif #if (defined(__VMKLNX__) && (VMWARE_ESX_DDK_VERSION >= 55000)) || \ (defined(BNX2_ENABLE_NETQUEUE)) bp->index = index; index++; #endif #if defined(BNX2_ENABLE_NETQUEUE) /* If enabled register the NetQueue callbacks */ if (BNX2_CHIP(bp) == BNX2_CHIP_5709) { if (BNX2_NETQUEUE_ENABLED(bp)) VMKNETDDI_REGISTER_QUEUEOPS(dev, bnx2_netqueue_ops); } #endif #if defined(__VMKLNX__) && (VMWARE_ESX_DDK_VERSION >= 55000) fwdmp_bp_ptr[bp->index] = bp; #endif #if (LINUX_VERSION_CODE >= 0x20418) if ((rc = register_netdev(dev))) { dev_err(&pdev->dev, "Cannot register net device\n"); goto error; } #endif netdev_info(dev, "%s (%c%d) %s found at mem %lx, IRQ %d, " "node addr %s\n", board_info[ent->driver_data].name, ((BNX2_CHIP_ID(bp) & 0xf000) >> 12) + 'A', ((BNX2_CHIP_ID(bp) & 0x0ff0) >> 4), bnx2_bus_string(bp, str), (long)pci_resource_start(pdev, 0), bp->pdev->irq, print_mac(mac, dev->dev_addr)); #if defined(BNX2_ENABLE_NETQUEUE) if (BNX2_CHIP(bp) == BNX2_CHIP_5709) { if (BNX2_NETQUEUE_ENABLED(bp)) { netdev_info(bp->dev, "NetQueue Ops registered [%d]\n", bp->index); } else netdev_info(bp->dev, "NetQueue Ops not registered " "[%d]\n", bp->index); } #endif return 0; error: pci_iounmap(pdev, bp->regview); pci_release_regions(pdev); pci_disable_device(pdev); pci_set_drvdata(pdev, NULL); err_free: #if (LINUX_VERSION_CODE >= 0x20418) free_netdev(dev); #else unregister_netdev(dev); kfree(dev); #endif return rc; } static void __devexit bnx2_remove_one(struct pci_dev *pdev) { struct net_device *dev = pci_get_drvdata(pdev); struct bnx2 *bp = netdev_priv(dev); #if defined(__VMKLNX__) bnx2_del_napi(bp); bnx2_disable_msi(bp); #endif /* !(defined __VMKLNX__) */ unregister_netdev(dev); del_timer_sync(&bp->timer); #if (LINUX_VERSION_CODE >= 0x20616) || defined(__VMKLNX__) cancel_work_sync(&bp->reset_task); #elif (LINUX_VERSION_CODE >= 0x20600) flush_scheduled_work(); #endif pci_iounmap(bp->pdev, bp->regview); kfree(bp->temp_stats_blk); if (bp->flags & BNX2_FLAG_AER_ENABLED) { pci_disable_pcie_error_reporting(pdev); bp->flags &= ~BNX2_FLAG_AER_ENABLED; } #if (LINUX_VERSION_CODE >= 0x20418) free_netdev(dev); #else kfree(dev); #endif pci_disable_pcie_error_reporting(pdev); pci_release_regions(pdev); pci_disable_device(pdev); pci_set_drvdata(pdev, NULL); } static int #ifdef SIMPLE_DEV_PM_OPS bnx2_suspend(struct device *device) #else bnx2_suspend(struct pci_dev *pdev, pm_message_t state) #endif { #ifdef SIMPLE_DEV_PM_OPS struct pci_dev *pdev = to_pci_dev(device); #endif struct net_device *dev = pci_get_drvdata(pdev); struct bnx2 *bp = netdev_priv(dev); #if (LINUX_VERSION_CODE >= 0x2060b) && !defined(SIMPLE_DEV_PM_OPS) /* PCI register 4 needs to be saved whether netif_running() or not. * MSI address and data need to be saved if using MSI and * netif_running(). */ pci_save_state(pdev); #endif if (netif_running(dev)) { #if (LINUX_VERSION_CODE >= 0x20616) || defined(__VMKLNX__) cancel_work_sync(&bp->reset_task); #endif bnx2_netif_stop(bp, true); netif_device_detach(dev); del_timer_sync(&bp->timer); bnx2_shutdown_chip(bp); __bnx2_free_irq(bp); bnx2_free_skbs(bp); } #ifdef SIMPLE_DEV_PM_OPS bnx2_setup_wol(bp); #else #if (LINUX_VERSION_CODE < 0x2060b) bnx2_set_power_state(bp, state); #else bnx2_set_power_state(bp, pci_choose_state(pdev, state)); #endif #endif return 0; } static int #ifdef SIMPLE_DEV_PM_OPS bnx2_resume(struct device *device) #else bnx2_resume(struct pci_dev *pdev) #endif { #ifdef SIMPLE_DEV_PM_OPS struct pci_dev *pdev = to_pci_dev(device); #endif struct net_device *dev = pci_get_drvdata(pdev); struct bnx2 *bp = netdev_priv(dev); #if (LINUX_VERSION_CODE >= 0x2060b) && !defined(SIMPLE_DEV_PM_OPS) pci_restore_state(pdev); #endif if (!netif_running(dev)) return 0; bnx2_set_power_state(bp, PCI_D0); netif_device_attach(dev); bnx2_request_irq(bp); bnx2_init_nic(bp, 1); bnx2_netif_start(bp, true); return 0; } #ifdef SIMPLE_DEV_PM_OPS #ifdef CONFIG_PM_SLEEP static SIMPLE_DEV_PM_OPS(bnx2_pm_ops, bnx2_suspend, bnx2_resume); #define BNX2_PM_OPS (&bnx2_pm_ops) #else #define BNX2_PM_OPS NULL #endif /* CONFIG_PM_SLEEP */ #endif #if !defined(__VMKLNX__) #if (LINUX_VERSION_CODE >= 0x020611) /** * bnx2_io_error_detected - called when PCI error is detected * @pdev: Pointer to PCI device * @state: The current pci connection state * * This function is called after a PCI bus error affecting * this device has been detected. */ static pci_ers_result_t bnx2_io_error_detected(struct pci_dev *pdev, pci_channel_state_t state) { struct net_device *dev = pci_get_drvdata(pdev); struct bnx2 *bp = netdev_priv(dev); rtnl_lock(); netif_device_detach(dev); if (state == pci_channel_io_perm_failure) { rtnl_unlock(); return PCI_ERS_RESULT_DISCONNECT; } if (netif_running(dev)) { bnx2_netif_stop(bp, true); del_timer_sync(&bp->timer); bnx2_reset_nic(bp, BNX2_DRV_MSG_CODE_RESET); } pci_disable_device(pdev); rtnl_unlock(); /* Request a slot slot reset. */ return PCI_ERS_RESULT_NEED_RESET; } /** * bnx2_io_slot_reset - called after the pci bus has been reset. * @pdev: Pointer to PCI device * * Restart the card from scratch, as if from a cold-boot. */ static pci_ers_result_t bnx2_io_slot_reset(struct pci_dev *pdev) { struct net_device *dev = pci_get_drvdata(pdev); struct bnx2 *bp = netdev_priv(dev); pci_ers_result_t result = PCI_ERS_RESULT_DISCONNECT; int err = 0; rtnl_lock(); if (pci_enable_device(pdev)) { dev_err(&pdev->dev, "Cannot re-enable PCI device after reset\n"); } else { pci_set_master(pdev); pci_restore_state(pdev); pci_save_state(pdev); if (netif_running(dev)) err = bnx2_init_nic(bp, 1); if (!err) result = PCI_ERS_RESULT_RECOVERED; } if (result != PCI_ERS_RESULT_RECOVERED && netif_running(dev)) { bnx2_napi_enable(bp); dev_close(bp->dev); } rtnl_unlock(); if (!(bp->flags & BNX2_FLAG_AER_ENABLED)) return result; err = pci_cleanup_aer_uncorrect_error_status(pdev); if (err) { dev_err(&pdev->dev, "pci_cleanup_aer_uncorrect_error_status failed 0x%0x\n", err); /* non-fatal, continue */ } return result; } /** * bnx2_io_resume - called when traffic can start flowing again. * @pdev: Pointer to PCI device * * This callback is called when the error recovery driver tells us that * its OK to resume normal operation. */ static void bnx2_io_resume(struct pci_dev *pdev) { struct net_device *dev = pci_get_drvdata(pdev); struct bnx2 *bp = netdev_priv(dev); rtnl_lock(); if (netif_running(dev)) bnx2_netif_start(bp, true); netif_device_attach(dev); rtnl_unlock(); } static struct pci_error_handlers bnx2_err_handler = { .error_detected = bnx2_io_error_detected, .slot_reset = bnx2_io_slot_reset, .resume = bnx2_io_resume, }; #endif #endif #if (LINUX_VERSION_CODE >= 0x02060c) static void bnx2_shutdown(struct pci_dev *pdev) { struct net_device *dev = pci_get_drvdata(pdev); struct bnx2 *bp; if (!dev) return; bp = netdev_priv(dev); if (!bp) return; rtnl_lock(); if (netif_running(dev)) dev_close(bp->dev); if (system_state == SYSTEM_POWER_OFF) bnx2_set_power_state(bp, PCI_D3hot); rtnl_unlock(); } #endif static struct pci_driver bnx2_pci_driver = { .name = DRV_MODULE_NAME, .id_table = bnx2_pci_tbl, .probe = bnx2_init_one, .remove = __devexit_p(bnx2_remove_one), #ifdef SIMPLE_DEV_PM_OPS .driver.pm = BNX2_PM_OPS, #else .suspend = bnx2_suspend, .resume = bnx2_resume, #endif #if !defined(__VMKLNX__) #if (LINUX_VERSION_CODE >= 0x020611) .err_handler = &bnx2_err_handler, #endif #endif #if (LINUX_VERSION_CODE >= 0x02060c) .shutdown = bnx2_shutdown, #endif }; static int __init bnx2_init(void) { int rc = 0; #if defined(__VMKLNX__) && (VMWARE_ESX_DDK_VERSION >= 55000) VMK_ReturnStatus status; #endif #if defined(BNX2_ENABLE_NETQUEUE) int i; /* sanity check the force_netq parameter */ for (i = 0; i < BNX2_MAX_NIC; i++) { if((force_netq_param[i] < BNX2_OPTION_UNSET) || (force_netq_param[i] > 7)) { pr_err("bnx2: please use a 'force_netq' " "value between (-1 to 7), " "0 to disable NetQueue, " "-1 to use the default value " "failure at index %d val: %d\n", i, force_netq_param[i]); rc = -EINVAL; } } if(rc != 0) return rc; #endif #if (LINUX_VERSION_CODE < 0x020613) rc = pci_module_init(&bnx2_pci_driver); #else rc = pci_register_driver(&bnx2_pci_driver); #endif #if defined(__VMKLNX__) && (VMWARE_ESX_DDK_VERSION >= 50000) #if defined(BNX2_INBOX) if (cnic_register_adapter("bnx2", bnx2_cnic_probe) < 0) { #else /* !defined(BNX2_INBOX) */ if (cnic_register_adapter("bnx2", bnx2_cnic_probe2) < 0) { #endif /* defined(BNX2_INBOX) */ pr_warn("bnx2: Unable to register with CNIC adapter\n"); /* * We won't call pci_unregister_driver(&bnx2_pci_driver) here, * because we still want to retain L2 funtion * even if cnic_register_adapter failed */ } else { bnx2_registered_cnic_adapter = 1; } #endif /* defined(__VMKLNX__) && (VMWARE_ESX_DDK_VERSION >= 50000) */ #if defined(__VMKLNX__) && (VMWARE_ESX_DDK_VERSION >= 55000) if (!disable_fw_dmp) { fwdmp_va_ptr = kzalloc(BNX2_FWDMP_SIZE, GFP_KERNEL); if (!fwdmp_va_ptr) pr_warn("bnx2: Unable to allocate memory " "for firmware dump handler!\n"); else { status = vmklnx_dump_add_callback(BNX2_DUMPNAME, bnx2_fwdmp_callback, NULL, BNX2_DUMPNAME, &bnx2_fwdmp_dh); if (status != VMK_OK) pr_warn("bnx2: Unable to register firmware " "dump handler (rc = 0x%x!)\n", status); } } #endif return rc; } static void __exit bnx2_cleanup(void) { #if defined(__VMKLNX__) #if (VMWARE_ESX_DDK_VERSION >= 55000) if (bnx2_fwdmp_dh) { VMK_ReturnStatus status; status = vmklnx_dump_delete_callback(bnx2_fwdmp_dh); if (status != VMK_OK) { VMK_ASSERT(0); } else { pr_info("bnx2: firmware dump handler (%p)" " unregistered!\n", bnx2_fwdmp_dh); } } kfree(fwdmp_va_ptr); fwdmp_va_ptr = NULL; #endif #if (VMWARE_ESX_DDK_VERSION >= 50000) if (bnx2_registered_cnic_adapter) { cnic_register_cancel("bnx2"); bnx2_registered_cnic_adapter = 0; } #endif #endif /* defined(__VMKLNX__) */ pci_unregister_driver(&bnx2_pci_driver); } module_init(bnx2_init); module_exit(bnx2_cleanup); #if defined(BNX2_ENABLE_NETQUEUE) #ifdef BNX2_DEBUG static u32 bnx2_read_ctx(struct bnx2 *bp, u32 offset) { int i; if (BNX2_CHIP(bp) != BNX2_CHIP_5709) { BNX2_WR(bp, BNX2_CTX_DATA_ADR, offset); return BNX2_RD(bp, BNX2_CTX_DATA); } BNX2_WR(bp, BNX2_CTX_CTX_CTRL, offset | BNX2_CTX_CTX_CTRL_READ_REQ); for (i = 0; i < 5; i++) { udelay(5); if (BNX2_RD(bp, BNX2_CTX_CTX_CTRL) & BNX2_CTX_CTX_CTRL_READ_REQ) continue; break; } return BNX2_RD(bp, BNX2_CTX_CTX_DATA); } static void dump_ctx(struct bnx2 *bp, u32 cid) { u32 addr = cid * 128; int i; for (i = 0; i < 8; i++) { u32 val, val1, val2, val3; val = bnx2_read_ctx(bp, addr); val1 = bnx2_read_ctx(bp, addr+4); val2 = bnx2_read_ctx(bp, addr+8); val3 = bnx2_read_ctx(bp, addr+0xc); netdev_err(bp->dev, "ctx %08x: %08x %08x %08x %08x\n", addr, val, val1, val2, val3); addr += 0x10; } } #endif #define BNX2_NETQ_WAIT_EVENT_TIMEOUT msecs_to_jiffies(1000) #define L2_KWQ_PAGE_CNT 1 #define L2_KCQ_PAGE_CNT 1 #define L2_KWQE_CNT (BNX2_PAGE_SIZE / sizeof(struct l2_kwqe)) #define L2_KCQE_CNT (BNX2_PAGE_SIZE / sizeof(struct l2_kcqe)) #define MAX_L2_KWQE_CNT (L2_KWQE_CNT - 1) #define MAX_L2_KCQE_CNT (L2_KCQE_CNT - 1) #define MAX_L2_KWQ_IDX ((L2_KWQ_PAGE_CNT * L2_KWQE_CNT) - 1) #define MAX_L2_KCQ_IDX ((L2_KCQ_PAGE_CNT * L2_KCQE_CNT) - 1) #define L2_KWQ_PG(x) (((x) & ~MAX_L2_KWQE_CNT) >> (BNX2_PAGE_BITS - 5)) #define L2_KWQ_IDX(x) ((x) & MAX_L2_KWQE_CNT) #define L2_KCQ_PG(x) (((x) & ~MAX_L2_KCQE_CNT) >> (BNX2_PAGE_BITS - 5)) #define L2_KCQ_IDX(x) ((x) & MAX_L2_KCQE_CNT) /* * krnlq_context definition */ #define L2_KRNLQ_FLAGS 0x00000000 #define L2_KRNLQ_SIZE 0x00000000 #define L2_KRNLQ_TYPE 0x00000000 #define KRNLQ_FLAGS_PG_SZ (0xf<<0) #define KRNLQ_FLAGS_PG_SZ_256 (0<<0) #define KRNLQ_FLAGS_PG_SZ_512 (1<<0) #define KRNLQ_FLAGS_PG_SZ_1K (2<<0) #define KRNLQ_FLAGS_PG_SZ_2K (3<<0) #define KRNLQ_FLAGS_PG_SZ_4K (4<<0) #define KRNLQ_FLAGS_PG_SZ_8K (5<<0) #define KRNLQ_FLAGS_PG_SZ_16K (6<<0) #define KRNLQ_FLAGS_PG_SZ_32K (7<<0) #define KRNLQ_FLAGS_PG_SZ_64K (8<<0) #define KRNLQ_FLAGS_PG_SZ_128K (9<<0) #define KRNLQ_FLAGS_PG_SZ_256K (10<<0) #define KRNLQ_FLAGS_PG_SZ_512K (11<<0) #define KRNLQ_FLAGS_PG_SZ_1M (12<<0) #define KRNLQ_FLAGS_PG_SZ_2M (13<<0) #define KRNLQ_FLAGS_QE_SELF_SEQ (1<<15) #define KRNLQ_SIZE_TYPE_SIZE ((((0x28 + 0x1f) & ~0x1f) / 0x20) << 16) #define KRNLQ_TYPE_TYPE (0xf<<28) #define KRNLQ_TYPE_TYPE_EMPTY (0<<28) #define KRNLQ_TYPE_TYPE_KRNLQ (6<<28) #define L2_KRNLQ_HOST_QIDX 0x00000004 #define L2_KRNLQ_HOST_FW_QIDX 0x00000008 #define L2_KRNLQ_NX_QE_SELF_SEQ 0x0000000c #define L2_KRNLQ_QE_SELF_SEQ_MAX 0x0000000c #define L2_KRNLQ_NX_QE_HADDR_HI 0x00000010 #define L2_KRNLQ_NX_QE_HADDR_LO 0x00000014 #define L2_KRNLQ_PGTBL_PGIDX 0x00000018 #define L2_KRNLQ_NX_PG_QIDX 0x00000018 #define L2_KRNLQ_PGTBL_NPAGES 0x0000001c #define L2_KRNLQ_QIDX_INCR 0x0000001c #define L2_KRNLQ_PGTBL_HADDR_HI 0x00000020 #define L2_KRNLQ_PGTBL_HADDR_LO 0x00000024 #define BNX2_PG_CTX_MAP 0x1a0034 static int bnx2_netq_free_rx_queue(struct net_device *netdev, int index); static int bnx2_netqueue_is_avail(struct bnx2 *bp) { rmb(); return ((BNX2_NETQUEUE_ENABLED(bp)) && (bp->flags & BNX2_FLAG_USING_MSIX) && (BNX2_CHIP(bp) == BNX2_CHIP_5709)); } static inline u32 bnx2_netqueue_kwq_avail(struct bnx2 *bp) { return MAX_L2_KWQ_IDX - ((bp->netq_kwq_prod_idx - bp->netq_kwq_con_idx) & MAX_L2_KWQ_IDX); } static int bnx2_netqueue_submit_kwqes(struct bnx2 *bp, struct l2_kwqe *wqes) { struct l2_kwqe *prod_qe; u16 prod, sw_prod; if (1 > bnx2_netqueue_kwq_avail(bp)) { netdev_warn(bp->dev, "No kwq's available\n"); return -EAGAIN; } prod = bp->netq_kwq_prod_idx; sw_prod = prod & MAX_L2_KWQ_IDX; prod_qe = &bp->netq_kwq[L2_KWQ_PG(sw_prod)][L2_KWQ_IDX(sw_prod)]; memcpy(prod_qe, wqes, sizeof(struct l2_kwqe)); prod++; sw_prod = prod & MAX_L2_KWQ_IDX; bp->netq_kwq_prod_idx = prod; barrier(); BNX2_WR16(bp, bp->netq_kwq_io_addr, bp->netq_kwq_prod_idx); wmb(); mmiowb(); return 0; } static void bnx2_netqueue_free_dma(struct bnx2 *bp, struct netq_dma *dma) { int i; if (dma->pg_arr) { for (i = 0; i < dma->num_pages; i++) { if (dma->pg_arr[i]) { pci_free_consistent(bp->pdev, BNX2_PAGE_SIZE, dma->pg_arr[i], dma->pg_map_arr[i]); dma->pg_arr[i] = NULL; } } } if (dma->pgtbl) { pci_free_consistent(bp->pdev, dma->pgtbl_size, dma->pgtbl, dma->pgtbl_map); dma->pgtbl = NULL; } kfree(dma->pg_arr); dma->pg_arr = NULL; dma->num_pages = 0; } static void bnx2_netqueue_free_resc(struct bnx2 *bp) { bnx2_netqueue_free_dma(bp, &bp->netq_kwq_info); bnx2_netqueue_free_dma(bp, &bp->netq_kcq_info); } static void bnx2_netqueue_setup_page_tbl(struct bnx2 *bp, struct netq_dma *dma) { int i; u32 *page_table = dma->pgtbl; for (i = 0; i < dma->num_pages; i++) { /* Each entry needs to be in big endian format. */ *page_table = (u32) ((u64) dma->pg_map_arr[i] >> 32); page_table++; *page_table = (u32) dma->pg_map_arr[i]; page_table++; } } static int bnx2_netqueue_alloc_dma(struct bnx2 *bp, struct netq_dma *dma, int pages) { int i, size; size = pages * (sizeof(void *) + sizeof(dma_addr_t)); dma->pg_arr = kzalloc(size, GFP_ATOMIC); if (dma->pg_arr == NULL) { netdev_err(bp->dev, "Couldn't alloc dma page array\n"); return -ENOMEM; } dma->pg_map_arr = (dma_addr_t *) (dma->pg_arr + pages); dma->num_pages = pages; for (i = 0; i < pages; i++) { dma->pg_arr[i] = pci_alloc_consistent(bp->pdev, BNX2_PAGE_SIZE, &dma->pg_map_arr[i]); if (dma->pg_arr[i] == NULL) { netdev_err(bp->dev, "Couldn't alloc dma page\n"); goto error; } } dma->pgtbl_size = ((pages * 8) + BNX2_PAGE_SIZE - 1) & ~(BNX2_PAGE_SIZE - 1); dma->pgtbl = pci_alloc_consistent(bp->pdev, dma->pgtbl_size, &dma->pgtbl_map); if (dma->pgtbl == NULL) goto error; bnx2_netqueue_setup_page_tbl(bp, dma); return 0; error: bnx2_netqueue_free_dma(bp, dma); return -ENOMEM; } static int bnx2_netqueue_alloc_resc(struct bnx2 *bp) { int ret; ret = bnx2_netqueue_alloc_dma(bp, &bp->netq_kwq_info, L2_KWQ_PAGE_CNT); if (ret) { netdev_err(bp->dev, "Couldn't alloc space for kwq\n"); goto error; } bp->netq_kwq = (struct l2_kwqe **) bp->netq_kwq_info.pg_arr; ret = bnx2_netqueue_alloc_dma(bp, &bp->netq_kcq_info, L2_KCQ_PAGE_CNT); if (ret) { netdev_err(bp->dev, "Couldn't alloc space for kwq\n"); goto error; } bp->netq_kcq = (struct l2_kcqe **) bp->netq_kcq_info.pg_arr; return 0; error: bnx2_netqueue_free_resc(bp); bp->netq_kwq = NULL; bp->netq_kcq = NULL; return ret; } static void bnx2_init_netqueue_context(struct bnx2 *bp, u32 cid) { u32 cid_addr; int i; cid_addr = GET_CID_ADDR(cid); for (i = 0; i < CTX_SIZE; i += 4) bnx2_ctx_wr(bp, cid_addr, i, 0); } static int bnx2_netqueue_get_kcqes(struct bnx2 *bp, u16 hw_prod, u16 *sw_prod) { u16 i, ri, last; struct l2_kcqe *kcqe; int kcqe_cnt = 0, last_cnt = 0; i = ri = last = *sw_prod; ri &= MAX_L2_KCQ_IDX; while ((i != hw_prod) && (kcqe_cnt < BNX2_NETQ_MAX_COMPLETED_KCQE)) { kcqe = &bp->netq_kcq[L2_KCQ_PG(ri)][L2_KCQ_IDX(ri)]; bp->netq_completed_kcq[kcqe_cnt++] = kcqe; i = (i + 1); ri = i & MAX_L2_KCQ_IDX; if (likely(!(kcqe->flags & L2_KCQE_FLAGS_NEXT))) { last_cnt = kcqe_cnt; last = i; } } *sw_prod = last; return last_cnt; } static void bnx2_service_netq_kcqes(struct bnx2_napi *bnapi, int num_cqes) { struct bnx2 *bp = bnapi->bp; int i, j; i = 0; j = 1; while (num_cqes) { u32 kcqe_op_flag = bp->netq_completed_kcq[i]->opcode; u32 kcqe_layer = bp->netq_completed_kcq[i]->flags & L2_KCQE_FLAGS_LAYER_MASK; while (j < num_cqes) { u32 next_op = bp->netq_completed_kcq[i + j]->opcode; if ((next_op & L2_KCQE_FLAGS_LAYER_MASK) != kcqe_layer) break; j++; } if (kcqe_layer != L2_KCQE_FLAGS_LAYER_MASK_L2) { netdev_err(bp->dev, "Unknown type of KCQE(0x%x)\n", kcqe_op_flag); goto end; } bp->netq_flags = kcqe_op_flag; wake_up(&bp->netq_wait); wmb(); end: num_cqes -= j; i += j; j = 1; } return; } static void bnx2_netqueue_service_bnx2_msix(struct bnx2_napi *bnapi) { struct bnx2 *bp = bnapi->bp; struct status_block *status_blk = bp->bnx2_napi[0].status_blk.msi; u32 status_idx = status_blk->status_idx; u16 hw_prod, sw_prod; int kcqe_cnt; bp->netq_kwq_con_idx = status_blk->status_cmd_consumer_index; hw_prod = status_blk->status_completion_producer_index; sw_prod = bp->netq_kcq_prod_idx; /* Ensure that there is a NetQ kcq avaliable */ if (sw_prod == hw_prod) return; while (sw_prod != hw_prod) { kcqe_cnt = bnx2_netqueue_get_kcqes(bp, hw_prod, &sw_prod); if (kcqe_cnt == 0) goto done; bnx2_service_netq_kcqes(bnapi, kcqe_cnt); /* Tell compiler that status_blk fields can change. */ barrier(); if (status_idx != status_blk->status_idx) { status_idx = status_blk->status_idx; bp->netq_kwq_con_idx = status_blk->status_cmd_consumer_index; hw_prod = status_blk->status_completion_producer_index; } else break; } barrier(); done: BNX2_WR16(bp, bp->netq_kcq_io_addr, sw_prod); bp->netq_kcq_prod_idx = sw_prod; bp->netq_last_status_idx = status_idx; } static void bnx2_close_netqueue(struct bnx2 *bp) { if (bnx2_netqueue_is_avail(bp) && (bp->netq_state == BNX2_NETQ_HW_STARTED)) bnx2_netqueue_flush_all(bp); if (bnx2_netqueue_open_started(bp)) bnx2_netqueue_tx_flush(bp); if (bnx2_netqueue_is_avail(bp)) bnx2_close_netqueue_hw(bp); vmknetddi_queueops_invalidate_state(bp->dev); } static int bnx2_netqueue_open_started(struct bnx2 *bp) { return (((bp->netq_state & BNX2_NETQ_HW_STARTED) == BNX2_NETQ_HW_STARTED) && ((bp->netq_state & BNX2_NETQ_HW_OPENED) == BNX2_NETQ_HW_OPENED)); } static void bnx2_stop_netqueue_hw(struct bnx2 *bp) { u32 val; /* Disable the CP and COM doorbells. These two processors polls the * doorbell for a non zero value before running. This must be done * after setting up the kernel queue contexts. This is for * KQW/KCQ #1. */ val = bnx2_reg_rd_ind(bp, BNX2_CP_SCRATCH + 0x20); val &= ~KWQ1_READY; bnx2_reg_wr_ind(bp, BNX2_CP_SCRATCH + 0x20, val); val = bnx2_reg_rd_ind(bp, BNX2_COM_SCRATCH + 0x20); val &= ~KCQ1_READY; bnx2_reg_wr_ind(bp, BNX2_COM_SCRATCH + 0x20, val); barrier(); bp->netq_state &= ~BNX2_NETQ_HW_STARTED; wmb(); } static void bnx2_force_stop_netqueue(struct bnx2 * bp) { int index; for_each_nondefault_rx_queue(bp, index) { struct bnx2_napi *bnapi = &bp->bnx2_napi[index]; if(bnapi->netq_state & BNX2_NETQ_RX_FILTER_APPLIED) { bnapi->rx_queue_active = FALSE; bnapi->netq_state &= ~BNX2_NETQ_RX_FILTER_APPLIED; netdev_info(bp->dev, "NetQ force removed RX filter: %d\n", index); } if (bnapi->rx_queue_allocated == TRUE) { bnapi->rx_queue_allocated = FALSE; bp->n_rx_queues_allocated--; netdev_info(bp->dev, "Force free NetQ RX Queue %d\n", index); } } for_each_nondefault_tx_queue(bp, index) { struct bnx2_napi *bnapi = &bp->bnx2_napi[index]; if(bnapi->tx_queue_allocated == TRUE) { bnapi->tx_queue_allocated = FALSE; bp->n_tx_queues_allocated--; netdev_info(bp->dev, "Force free NetQ TX Queue: 0x%x\n", index); } } } static void bnx2_stop_netqueue(struct bnx2 *bp) { netif_tx_disable(bp->dev); bp->dev->trans_start = jiffies; /* prevent tx timeout */ if (bnx2_netqueue_is_avail(bp) && (bp->netq_state & BNX2_NETQ_HW_STARTED)) { bnx2_netqueue_flush_all(bp); } bnx2_stop_netqueue_hw(bp); } static void bnx2_close_netqueue_hw(struct bnx2 *bp) { bnx2_stop_netqueue_hw(bp); bnx2_netqueue_free_resc(bp); bp->netq_state &= ~BNX2_NETQ_HW_OPENED; wmb(); } static void bnx2_start_netqueue_hw(struct bnx2 *bp) { /* Set the CP and COM doorbells. These two processors polls the * doorbell for a non zero value before running. This must be done * after setting up the kernel queue contexts. This is for * KQW/KCQ 1. */ bnx2_reg_wr_ind(bp, BNX2_CP_SCRATCH + 0x20, KWQ1_READY); bnx2_reg_wr_ind(bp, BNX2_COM_SCRATCH + 0x20, KCQ1_READY); bp->netq_state |= BNX2_NETQ_HW_STARTED; wmb(); } static void bnx2_init_netqueue_hw(struct bnx2 *bp) { u32 val; /* Initialize the bnx2 netqueue structures */ init_waitqueue_head(&bp->netq_wait); val = BNX2_RD(bp, BNX2_MQ_CONFIG); val &= ~BNX2_MQ_CONFIG_KNL_BYP_BLK_SIZE; if (BNX2_PAGE_BITS > 12) val |= (12 - 8) << 4; else val |= (BNX2_PAGE_BITS - 8) << 4; BNX2_WR(bp, BNX2_MQ_CONFIG, val); BNX2_WR(bp, BNX2_HC_COMP_PROD_TRIP, (2 << 16) | 8); BNX2_WR(bp, BNX2_HC_COM_TICKS, (64 << 16) | 220); BNX2_WR(bp, BNX2_HC_CMD_TICKS, (64 << 16) | 220); bnx2_init_netqueue_context(bp, NETQUEUE_KWQ_CID); bnx2_init_netqueue_context(bp, NETQUEUE_KCQ_CID); bp->netq_kwq_cid_addr = GET_CID_ADDR(NETQUEUE_KWQ_CID); bp->netq_kwq_io_addr = MB_GET_CID_ADDR(NETQUEUE_KWQ_CID) + L2_KRNLQ_HOST_QIDX; bp->netq_kwq_prod_idx = 0; bp->netq_kwq_con_idx = 0; /* Initialize the kernel work queue context. */ val = KRNLQ_TYPE_TYPE_KRNLQ | KRNLQ_SIZE_TYPE_SIZE | (BNX2_PAGE_BITS - 8) | KRNLQ_FLAGS_QE_SELF_SEQ; bnx2_ctx_wr(bp, bp->netq_kwq_cid_addr, L2_KRNLQ_TYPE, val); val = (BNX2_PAGE_SIZE / sizeof(struct l2_kwqe) - 1) << 16; bnx2_ctx_wr(bp, bp->netq_kwq_cid_addr, L2_KRNLQ_QE_SELF_SEQ_MAX, val); val = ((BNX2_PAGE_SIZE / sizeof(struct l2_kwqe)) << 16) | L2_KWQ_PAGE_CNT; bnx2_ctx_wr(bp, bp->netq_kwq_cid_addr, L2_KRNLQ_PGTBL_NPAGES, val); val = (u32) ((u64) bp->netq_kwq_info.pgtbl_map >> 32); bnx2_ctx_wr(bp, bp->netq_kwq_cid_addr, L2_KRNLQ_PGTBL_HADDR_HI, val); val = (u32) bp->netq_kwq_info.pgtbl_map; bnx2_ctx_wr(bp, bp->netq_kwq_cid_addr, L2_KRNLQ_PGTBL_HADDR_LO, val); bp->netq_kcq_cid_addr = GET_CID_ADDR(NETQUEUE_KCQ_CID); bp->netq_kcq_io_addr = MB_GET_CID_ADDR(NETQUEUE_KCQ_CID) + L2_KRNLQ_HOST_QIDX; bp->netq_kcq_prod_idx = 0; /* Initialize the kernel complete queue context. */ val = KRNLQ_TYPE_TYPE_KRNLQ | KRNLQ_SIZE_TYPE_SIZE | (BNX2_PAGE_BITS - 8) | KRNLQ_FLAGS_QE_SELF_SEQ; bnx2_ctx_wr(bp, bp->netq_kcq_cid_addr, L2_KRNLQ_TYPE, val); val = (BNX2_PAGE_SIZE / sizeof(struct l2_kcqe) - 1) << 16; bnx2_ctx_wr(bp, bp->netq_kcq_cid_addr, L2_KRNLQ_QE_SELF_SEQ_MAX, val); val = ((BNX2_PAGE_SIZE / sizeof(struct l2_kcqe)) << 16)|L2_KCQ_PAGE_CNT; bnx2_ctx_wr(bp, bp->netq_kcq_cid_addr, L2_KRNLQ_PGTBL_NPAGES, val); val = (u32) ((u64) bp->netq_kcq_info.pgtbl_map >> 32); bnx2_ctx_wr(bp, bp->netq_kcq_cid_addr, L2_KRNLQ_PGTBL_HADDR_HI, val); val = (u32) bp->netq_kcq_info.pgtbl_map; bnx2_ctx_wr(bp, bp->netq_kcq_cid_addr, L2_KRNLQ_PGTBL_HADDR_LO, val); /* Enable Commnad Scheduler notification when we write to the * host producer index of the kernel contexts. */ BNX2_WR(bp, BNX2_MQ_KNL_CMD_MASK1, 2); /* Enable Command Scheduler notification when we write to either * the Send Queue or Receive Queue producer indexes of the kernel * bypass contexts. */ BNX2_WR(bp, BNX2_MQ_KNL_BYP_CMD_MASK1, 7); BNX2_WR(bp, BNX2_MQ_KNL_BYP_WRITE_MASK1, 7); /* Notify COM when the driver post an application buffer. */ BNX2_WR(bp, BNX2_MQ_KNL_RX_V2P_MASK2, 0x2000); barrier(); } static void bnx2_start_netqueue(struct bnx2 *bp) { bnx2_init_netqueue_hw(bp); bnx2_start_netqueue_hw(bp); } static int bnx2_open_netqueue_hw(struct bnx2 *bp) { int err; err = bnx2_netqueue_alloc_resc(bp); if (err != 0) { netdev_err(bp->dev, "Couldn't allocate netq resources\n"); return err; } bnx2_start_netqueue(bp); bp->netq_state |= BNX2_NETQ_HW_OPENED; wmb(); netdev_info(bp->dev, "NetQueue hardware support is enabled\n"); return 0; } static int bnx2_netq_get_netqueue_features(vmknetddi_queueop_get_features_args_t *args) { args->features = VMKNETDDI_QUEUEOPS_FEATURE_NONE; args->features |= VMKNETDDI_QUEUEOPS_FEATURE_RXQUEUES; args->features |= VMKNETDDI_QUEUEOPS_FEATURE_TXQUEUES; return VMKNETDDI_QUEUEOPS_OK; } static int bnx2_netq_get_queue_count(vmknetddi_queueop_get_queue_count_args_t *args) { struct bnx2 *bp = netdev_priv(args->netdev); /* workaround for packets duplicated */ if (bp->num_tx_rings + bp->num_rx_rings > 1) bp->netq_enabled = 1; if (args->type == VMKNETDDI_QUEUEOPS_QUEUE_TYPE_RX) { args->count = max_t(u16, bp->num_rx_rings - 1, 0); netdev_info(args->netdev, "Using %d RX NetQ rings\n", args->count); return VMKNETDDI_QUEUEOPS_OK; } else if (args->type == VMKNETDDI_QUEUEOPS_QUEUE_TYPE_TX) { args->count = max_t(u16, bp->num_tx_rings - 1, 0); netdev_info(args->netdev, "Using %d TX NetQ rings\n", args->count); return VMKNETDDI_QUEUEOPS_OK; } else { netdev_err(args->netdev, "queue count: invalid queue type " "0x%x\n", args->type); return VMKNETDDI_QUEUEOPS_ERR; } } static int bnx2_netq_get_filter_count(vmknetddi_queueop_get_filter_count_args_t *args) { /* Only support 1 Mac filter per queue */ args->count = 1; return VMKNETDDI_QUEUEOPS_OK; } static int bnx2_netq_alloc_rx_queue(struct bnx2 *bp, struct bnx2_napi *bnapi, int index) { /* We need to count the default ring as part of the number of RX rings avaliable */ if (bp->n_rx_queues_allocated >= (bp->num_rx_rings - 1)) { netdev_warn(bp->dev, "Unable to allocate RX NetQueue n_rx_queues_allocated(%d) >= Num NetQ's(%d)\n", bp->n_rx_queues_allocated, (bp->num_rx_rings - 1)); return VMKNETDDI_QUEUEOPS_ERR; } if((bp->netq_state & BNX2_NETQ_HW_STARTED) != BNX2_NETQ_HW_STARTED) { netdev_warn(bp->dev, "NetQueue hardware not running\n"); return VMKNETDDI_QUEUEOPS_ERR; } if (!bnapi->rx_queue_allocated) { int rc; struct l2_kwqe_vm_alloc_rx_queue kwqe_alloc_rx; /* Prepare the kwqe to be passed to the firmware */ memset(&kwqe_alloc_rx, 0, sizeof(kwqe_alloc_rx)); kwqe_alloc_rx.kwqe_flags = L2_KWQE_FLAGS_LAYER_MASK_L2; kwqe_alloc_rx.kwqe_opcode = L2_KWQE_OPCODE_VALUE_VM_ALLOC_RX_QUEUE; kwqe_alloc_rx.queue_type = L2_NET_QUEUE; kwqe_alloc_rx.qid = BNX2_DRV_TO_FW_QUEUE_ID(index); rc = bnx2_netqueue_submit_kwqes(bp, (struct l2_kwqe *)&kwqe_alloc_rx); if (rc != 0) { netdev_err(bp->dev, "Couldn't submit alloc rx kwqe\n"); return VMKNETDDI_QUEUEOPS_ERR; } bp->netq_flags = 0; wmb(); rc = wait_event_timeout(bp->netq_wait, (bp->netq_flags & L2_KCQE_OPCODE_VALUE_VM_ALLOC_RX_QUEUE), BNX2_NETQ_WAIT_EVENT_TIMEOUT); if (rc != 0) { bnapi->rx_queue_allocated = TRUE; netdev_info(bp->dev, "RX NetQ allocated on %d\n", index); return VMKNETDDI_QUEUEOPS_OK; } else { netdev_info(bp->dev, "Timeout RX NetQ allocate on %d\n", index); return VMKNETDDI_QUEUEOPS_ERR; } } netdev_info(bp->dev, "No RX NetQueues avaliable!\n"); return VMKNETDDI_QUEUEOPS_ERR; } static int bnx2_netq_alloc_rx_queue_vmk(struct net_device *netdev, vmknetddi_queueops_queueid_t *p_qid, struct napi_struct **napi_p) { int index; struct bnx2 *bp = netdev_priv(netdev); /* We need to count the default ring as part of the number of RX rings avaliable */ if (bp->n_rx_queues_allocated >= (bp->num_rx_rings - 1)) { netdev_warn(bp->dev, "Unable to allocate RX NetQueue n_rx_queues_allocated(%d) >= Num NetQ's(%d)\n", bp->n_rx_queues_allocated, (bp->num_rx_rings - 1)); return VMKNETDDI_QUEUEOPS_ERR; } for_each_nondefault_rx_queue(bp, index) { struct bnx2_napi *bnapi = &bp->bnx2_napi[index]; if (!bnapi->rx_queue_allocated) { int rc; rc = bnx2_netq_alloc_rx_queue(bp, bnapi, index); if (rc == VMKNETDDI_QUEUEOPS_OK) { bp->n_rx_queues_allocated++; *p_qid = VMKNETDDI_QUEUEOPS_MK_RX_QUEUEID(index); *napi_p = &bnapi->napi; return VMKNETDDI_QUEUEOPS_OK; } else return VMKNETDDI_QUEUEOPS_ERR; } } netdev_err(bp->dev, "No free RX NetQueues found!\n"); return VMKNETDDI_QUEUEOPS_ERR; } static int bnx2_netq_alloc_tx_queue(struct bnx2 *bp, struct bnx2_napi *bnapi, int index) { if (bp->n_tx_queues_allocated >= (bp->num_tx_rings - 1)) return VMKNETDDI_QUEUEOPS_ERR; if (!bnapi->tx_queue_allocated) { bnapi->tx_queue_allocated = TRUE; bp->n_tx_queues_allocated++; netdev_info(bp->dev, "TX NetQ allocated on %d\n", index); return VMKNETDDI_QUEUEOPS_OK; } netdev_err(bp->dev, "tx queue already allocated!\n"); return VMKNETDDI_QUEUEOPS_ERR; } static int bnx2_netq_alloc_tx_queue_vmk(struct net_device *netdev, vmknetddi_queueops_queueid_t *p_qid, u16 *queue_mapping) { int index; struct bnx2 *bp = netdev_priv(netdev); if (bp->n_tx_queues_allocated >= (bp->num_tx_rings - 1)) return VMKNETDDI_QUEUEOPS_ERR; for_each_nondefault_tx_queue(bp, index) { struct bnx2_napi *bnapi = &bp->bnx2_napi[index]; if (!bnapi->tx_queue_allocated) { int rc = bnx2_netq_alloc_tx_queue(bp, bnapi, index); *p_qid = VMKNETDDI_QUEUEOPS_MK_TX_QUEUEID(index); *queue_mapping = index; return rc; } } netdev_err(bp->dev, "no free tx queues found!\n"); return VMKNETDDI_QUEUEOPS_ERR; } static int bnx2_netq_alloc_queue(vmknetddi_queueop_alloc_queue_args_t *args) { struct net_device *netdev = args->netdev; struct bnx2 *bp = netdev_priv(netdev); if(bp->reset_failed == 1) { netdev_err(bp->dev, "Trying to alloc NetQueue on failed reset " "device\n"); return VMKNETDDI_QUEUEOPS_ERR; } if (!bnx2_netqueue_open_started(bp)) { netdev_warn(bp->dev, "NetQueue hardware not running yet\n"); return VMKNETDDI_QUEUEOPS_ERR; } if (args->type == VMKNETDDI_QUEUEOPS_QUEUE_TYPE_TX) { return bnx2_netq_alloc_tx_queue_vmk(args->netdev, &args->queueid, &args->queue_mapping); } else if (args->type == VMKNETDDI_QUEUEOPS_QUEUE_TYPE_RX) { return bnx2_netq_alloc_rx_queue_vmk(args->netdev, &args->queueid, &args->napi); } else { netdev_err(bp->dev, "Trying to alloc invalid queue type: %x\n", args->type); return VMKNETDDI_QUEUEOPS_ERR; } } static int bnx2_netq_free_tx_queue(struct net_device *netdev, vmknetddi_queueops_queueid_t qid) { struct bnx2 *bp = netdev_priv(netdev); struct bnx2_napi *bnapi; u16 index = VMKNETDDI_QUEUEOPS_QUEUEID_VAL(qid); if (index > bp->num_tx_rings) return VMKNETDDI_QUEUEOPS_ERR; bnapi = &bp->bnx2_napi[index]; if (bnapi->tx_queue_allocated != TRUE) return VMKNETDDI_QUEUEOPS_ERR; bnapi->tx_queue_allocated = FALSE; bp->n_tx_queues_allocated--; netdev_info(bp->dev, "Free NetQ TX Queue: 0x%x\n", index); return VMKNETDDI_QUEUEOPS_OK; } static int bnx2_netq_free_rx_queue(struct net_device *netdev, int index) { int rc; struct bnx2 *bp = netdev_priv(netdev); struct bnx2_napi *bnapi; struct l2_kwqe_vm_free_rx_queue kwqe_free_rx; if (index > bp->num_rx_rings) { netdev_err(bp->dev, "Error Free NetQ RX Queue: " "index(%d) > bp->num_rx_rings(%d)\n", index, bp->num_rx_rings); return VMKNETDDI_QUEUEOPS_ERR; } if (!bnx2_netqueue_open_started(bp)) { netdev_warn(bp->dev, "NetQueue hardware not running yet\n"); return VMKNETDDI_QUEUEOPS_ERR; } bnapi = &bp->bnx2_napi[index]; if (bnapi->rx_queue_allocated != TRUE) { netdev_warn(bp->dev, "NetQ RX Queue %d already freed\n", index); return VMKNETDDI_QUEUEOPS_OK; } memset(&kwqe_free_rx, 0, sizeof(kwqe_free_rx)); kwqe_free_rx.flags = L2_KWQE_FLAGS_LAYER_MASK_L2; kwqe_free_rx.opcode = L2_KWQE_OPCODE_VALUE_VM_FREE_RX_QUEUE; kwqe_free_rx.qid = BNX2_DRV_TO_FW_QUEUE_ID(index); kwqe_free_rx.queue_type = L2_NET_QUEUE; rc = bnx2_netqueue_submit_kwqes(bp, (struct l2_kwqe *) &kwqe_free_rx); if (rc != 0) { netdev_err(bp->dev, "Couldn't submit free rx kwqe\n"); return VMKNETDDI_QUEUEOPS_ERR; } bp->netq_flags = 0; wmb(); rc = wait_event_timeout(bp->netq_wait, (bp->netq_flags & L2_KCQE_OPCODE_VALUE_VM_FREE_RX_QUEUE), BNX2_NETQ_WAIT_EVENT_TIMEOUT); if (rc != 0) { bnapi->rx_queue_allocated = FALSE; bp->n_rx_queues_allocated--; netdev_info(bp->dev, "Free NetQ RX Queue %d\n", index); return VMKNETDDI_QUEUEOPS_OK; } else { netdev_err(bp->dev, "Timeout free NetQ RX Queue %d\n", index); return VMKNETDDI_QUEUEOPS_ERR; } } static int bnx2_netq_free_queue(vmknetddi_queueop_free_queue_args_t *args) { struct bnx2 *bp = netdev_priv(args->netdev); if(bp->reset_failed == 1) { netdev_err(bp->dev, "Trying to free NetQueue on failed reset " "device\n"); return VMKNETDDI_QUEUEOPS_ERR; } if (!bnx2_netqueue_open_started(bp)) { netdev_warn(bp->dev, "NetQueue hardware not running yet\n"); return VMKNETDDI_QUEUEOPS_ERR; } if (VMKNETDDI_QUEUEOPS_IS_TX_QUEUEID(args->queueid)) { return bnx2_netq_free_tx_queue(args->netdev, args->queueid); } else if (VMKNETDDI_QUEUEOPS_IS_RX_QUEUEID(args->queueid)) { return bnx2_netq_free_rx_queue(args->netdev, VMKNETDDI_QUEUEOPS_QUEUEID_VAL(args->queueid)); } else { netdev_err(bp->dev, "free netq: invalid queue type: 0x%x\n", args->queueid); return VMKNETDDI_QUEUEOPS_ERR; } } static int bnx2_netq_get_queue_vector(vmknetddi_queueop_get_queue_vector_args_t *args) { int qid; struct bnx2 *bp = netdev_priv(args->netdev); qid = VMKNETDDI_QUEUEOPS_QUEUEID_VAL(args->queueid); if (qid > bp->num_rx_rings) return VMKNETDDI_QUEUEOPS_ERR; #ifdef CONFIG_PCI_MSI args->vector = bp->bnx2_napi[qid].int_num; #endif return VMKNETDDI_QUEUEOPS_OK; } static int bnx2_netq_get_default_queue(vmknetddi_queueop_get_default_queue_args_t *args) { struct bnx2 *bp = netdev_priv(args->netdev); if (args->type == VMKNETDDI_QUEUEOPS_QUEUE_TYPE_RX) { args->queueid = VMKNETDDI_QUEUEOPS_MK_RX_QUEUEID(0); args->napi = &bp->bnx2_napi[0].napi; return VMKNETDDI_QUEUEOPS_OK; } else if (args->type == VMKNETDDI_QUEUEOPS_QUEUE_TYPE_TX) { args->queueid = VMKNETDDI_QUEUEOPS_MK_TX_QUEUEID(0); args->queue_mapping = 0; return VMKNETDDI_QUEUEOPS_OK; } else return VMKNETDDI_QUEUEOPS_ERR; } static int bnx2_netq_remove_rx_filter(struct bnx2 *bp, int index) { u16 fw_qid = BNX2_DRV_TO_FW_QUEUE_ID(index); struct bnx2_napi *bnapi; struct l2_kwqe_vm_remove_rx_filter kwqe_remove_rx_filter; int rc; if(bp->reset_failed == 1) { netdev_err(bp->dev, "Trying to remove RX filter NetQueue on " "failed reset device\n"); return VMKNETDDI_QUEUEOPS_ERR; } if (!bnx2_netqueue_open_started(bp)) { netdev_err(bp->dev, "NetQueue hardware not running yet\n"); return VMKNETDDI_QUEUEOPS_ERR; } bnapi = &bp->bnx2_napi[index]; if (fw_qid > bp->num_rx_rings) { netdev_info(bp->dev, "Free RX Filter NetQ: failed " "qid(%d) > bp->num_rx_rings(%d)\n", index, bp->num_rx_rings); return VMKNETDDI_QUEUEOPS_ERR; } memset(&kwqe_remove_rx_filter, 0, sizeof(kwqe_remove_rx_filter)); kwqe_remove_rx_filter.flags = L2_KWQE_FLAGS_LAYER_MASK_L2; kwqe_remove_rx_filter.opcode = L2_KWQE_OPCODE_VALUE_VM_REMOVE_RX_FILTER; kwqe_remove_rx_filter.filter_type = L2_VM_FILTER_MAC; kwqe_remove_rx_filter.qid = fw_qid; kwqe_remove_rx_filter.filter_id = fw_qid + BNX2_START_FILTER_ID; rc = bnx2_netqueue_submit_kwqes(bp, (struct l2_kwqe *) &kwqe_remove_rx_filter); if (rc != 0) { netdev_err(bp->dev, "Couldn't submit rx filter kwqe\n"); return VMKNETDDI_QUEUEOPS_ERR; } bp->netq_flags = 0; wmb(); rc = wait_event_timeout(bp->netq_wait, (bp->netq_flags & L2_KCQE_OPCODE_VALUE_VM_REMOVE_RX_FILTER), BNX2_NETQ_WAIT_EVENT_TIMEOUT); if (rc != 0) { bnapi->rx_queue_active = FALSE; bnapi->netq_state &= ~BNX2_NETQ_RX_FILTER_APPLIED; netdev_info(bp->dev, "NetQ remove RX filter: %d\n", index); return VMKNETDDI_QUEUEOPS_OK; } else { netdev_warn(bp->dev, "Timeout NetQ remove RX filter: %d\n", index); return VMKNETDDI_QUEUEOPS_ERR; } } static int bnx2_netq_remove_rx_filter_vmk(vmknetddi_queueop_remove_rx_filter_args_t *args) { struct bnx2 *bp = netdev_priv(args->netdev); u16 index = VMKNETDDI_QUEUEOPS_QUEUEID_VAL(args->queueid); struct bnx2_napi *bnapi; if (bp->reset_failed == 1) { netdev_err(bp->dev, "Trying to remove RX filter NetQueue on " "failed reset device\n"); return VMKNETDDI_QUEUEOPS_ERR; } if (!bnx2_netqueue_open_started(bp)) { netdev_warn(bp->dev, "NetQueue hardware not running yet\n"); return VMKNETDDI_QUEUEOPS_ERR; } bnapi = &bp->bnx2_napi[index]; if (!VMKNETDDI_QUEUEOPS_IS_RX_QUEUEID(args->queueid)) { netdev_err(bp->dev, "!VMKNETDDI_QUEUEOPS_IS_RX_QUEUEID: " "qid: %d)\n", index); return VMKNETDDI_QUEUEOPS_ERR; } if (index > bp->num_rx_rings) { netdev_err(bp->dev, "qid(%d) > bp->num_rx_rings(%d)\n", index, bp->num_rx_rings); return VMKNETDDI_QUEUEOPS_ERR; } /* Only support one Mac filter per queue */ if (bnapi->rx_queue_active == 0) { netdev_info(bp->dev, "bnapi->rx_queue_active(%d) == 0\n", bnapi->rx_queue_active); return VMKNETDDI_QUEUEOPS_ERR; } return bnx2_netq_remove_rx_filter(bp, index); } static int bnx2_netq_apply_rx_filter(struct bnx2 *bp, struct bnx2_napi *bnapi, int index) { u16 fw_queueid = BNX2_DRV_TO_FW_QUEUE_ID(index); struct l2_kwqe_vm_set_rx_filter kwqe_set_rx_filter; int rc; DECLARE_MAC_BUF(mac); if (bp->reset_failed == 1) { netdev_err(bp->dev, "Trying to apply RX filter NetQueue on %d" "failed reset device\n", index); return VMKNETDDI_QUEUEOPS_ERR; } if (!bnx2_netqueue_open_started(bp)) { netdev_warn(bp->dev, "NetQueue hardware not running yet\n"); return VMKNETDDI_QUEUEOPS_ERR; } if (bnapi->rx_queue_active == TRUE || !bnapi->rx_queue_allocated) { netdev_err(bp->dev, "apply filter: RX NetQ %d already active" "bnapi->rx_queue_active(%d) || " "!bnapi->rx_queue_allocated(%d)\n", index, bnapi->rx_queue_active, bnapi->rx_queue_allocated); return VMKNETDDI_QUEUEOPS_ERR; } bnx2_set_mac_addr(bp, bnapi->mac_filter_addr, fw_queueid + QID_TO_PM_OFFSET); memset(&kwqe_set_rx_filter, 0, sizeof(kwqe_set_rx_filter)); kwqe_set_rx_filter.flags = L2_KWQE_FLAGS_LAYER_MASK_L2; kwqe_set_rx_filter.opcode = L2_KWQE_OPCODE_VALUE_VM_SET_RX_FILTER; kwqe_set_rx_filter.filter_id = fw_queueid + BNX2_START_FILTER_ID; #if defined(__LITTLE_ENDIAN) memcpy(&kwqe_set_rx_filter.mac_addr_hi, bnapi->mac_filter_addr, 2); memcpy(&kwqe_set_rx_filter.mac_addr_lo, bnapi->mac_filter_addr + 2, 4); #else memcpy(&kwqe_set_rx_filter.mac_addr, bnapi->mac_filter_addr, 6); #endif if (bnapi->class == VMKNETDDI_QUEUEOPS_FILTER_MACADDR) { kwqe_set_rx_filter.filter_type = L2_VM_FILTER_MAC; } else { kwqe_set_rx_filter.filter_type = L2_VM_FILTER_MAC_VLAN; kwqe_set_rx_filter.vlan = bnapi->vlan_id; } kwqe_set_rx_filter.qid = fw_queueid; rc = bnx2_netqueue_submit_kwqes(bp, (struct l2_kwqe *) &kwqe_set_rx_filter); if (rc != 0) { netdev_err(bp->dev, "Couldn't submit rx filter kwqe\n"); return VMKNETDDI_QUEUEOPS_ERR; } bp->netq_flags = 0; wmb(); rc = wait_event_timeout(bp->netq_wait, (bp->netq_flags & L2_KCQE_OPCODE_VALUE_VM_SET_RX_FILTER), BNX2_NETQ_WAIT_EVENT_TIMEOUT); if (rc != 0) { bnapi->rx_queue_active = TRUE; bnapi->netq_state |= BNX2_NETQ_RX_FILTER_APPLIED; netdev_info(bp->dev, "NetQ set RX Filter: %d [%s %d]\n", index, print_mac(mac, bnapi->mac_filter_addr), bnapi->vlan_id); return VMKNETDDI_QUEUEOPS_OK; } else { netdev_info(bp->dev, "Timeout submitting NetQ set RX Filter: " "%d [%s]\n", index, print_mac(mac, bnapi->mac_filter_addr)); return VMKNETDDI_QUEUEOPS_ERR; } } static int bnx2_netq_apply_rx_filter_vmk(vmknetddi_queueop_apply_rx_filter_args_t *args) { u8 *macaddr; struct bnx2_napi *bnapi; struct bnx2 *bp = netdev_priv(args->netdev); u16 index = VMKNETDDI_QUEUEOPS_QUEUEID_VAL(args->queueid); vmknetddi_queueops_filter_class_t class; DECLARE_MAC_BUF(mac); if (bp->reset_failed == 1) { netdev_err(bp->dev, "Trying to apply RX filter NetQueue on %d" "failed reset device\n", index); return VMKNETDDI_QUEUEOPS_ERR; } if (!bnx2_netqueue_open_started(bp)) { netdev_warn(bp->dev, "NetQueue hardware not running yet\n"); return VMKNETDDI_QUEUEOPS_ERR; } if (!VMKNETDDI_QUEUEOPS_IS_RX_QUEUEID(args->queueid)) { netdev_err(bp->dev, "invalid NetQ RX ID: %x\n", args->queueid); return VMKNETDDI_QUEUEOPS_ERR; } class = vmknetddi_queueops_get_filter_class(&args->filter); if ((class != VMKNETDDI_QUEUEOPS_FILTER_MACADDR) && (class != VMKNETDDI_QUEUEOPS_FILTER_VLANMACADDR)) { netdev_err(bp->dev, "recieved invalid RX NetQ filter: %x\n", class); return VMKNETDDI_QUEUEOPS_ERR; } if (index > bp->num_rx_rings) { netdev_err(bp->dev, "applying filter with invalid " "RX NetQ %d ID\n", index); return VMKNETDDI_QUEUEOPS_ERR; } bnapi = &bp->bnx2_napi[index]; if (bnapi->rx_queue_active || !bnapi->rx_queue_allocated) { netdev_err(bp->dev, "RX NetQ %d already active\n", index); return VMKNETDDI_QUEUEOPS_ERR; } macaddr = (void *)vmknetddi_queueops_get_filter_macaddr(&args->filter); memcpy(bnapi->mac_filter_addr, macaddr, ETH_ALEN); bnapi->vlan_id = vmknetddi_queueops_get_filter_vlanid(&args->filter); bnapi->class = class; /* Apply RX filter code here */ args->filterid = VMKNETDDI_QUEUEOPS_MK_FILTERID(index); return bnx2_netq_apply_rx_filter(bp, bnapi, index); } static int bnx2_netq_get_queue_stats(vmknetddi_queueop_get_stats_args_t *args) { u16 index = VMKNETDDI_QUEUEOPS_QUEUEID_VAL(args->queueid); struct bnx2_napi *bnapi; struct bnx2 *bp = netdev_priv(args->netdev); bnapi = &bp->bnx2_napi[index]; args->stats = &bnapi->stats; return VMKNETDDI_QUEUEOPS_OK; } static int bnx2_netq_get_netqueue_version(vmknetddi_queueop_get_version_args_t *args) { return vmknetddi_queueops_version(args); } static void bnx2_netqueue_flush_all(struct bnx2 *bp) { int index; u16 num_tx = 0, num_rx = 0; netdev_info(bp->dev, "Flushing NetQueues\n"); mutex_lock(&bp->netq_lock); for_each_nondefault_rx_queue(bp, index) { struct bnx2_napi *bnapi = &bp->bnx2_napi[index]; if(bnapi->netq_state & BNX2_NETQ_RX_FILTER_APPLIED) { int rc = bnx2_netq_remove_rx_filter(bp, index); if (rc == VMKNETDDI_QUEUEOPS_ERR) { netdev_err(bp->dev, "could not remove RX " "filter during flush\n"); } if(bnapi->rx_queue_allocated == TRUE) { rc = bnx2_netq_free_rx_queue(bp->dev, index); if (rc == VMKNETDDI_QUEUEOPS_OK) { num_rx++; } else { netdev_err(bp->dev, "couldn't free RX " "queue %d during " "flush\n", index); } } } } for_each_nondefault_tx_queue(bp, index) { struct bnx2_napi *bnapi = &bp->bnx2_napi[index]; if(bnapi->tx_queue_allocated == TRUE) { bnx2_netq_free_tx_queue(bp->dev, index); } num_tx++; } mutex_unlock(&bp->netq_lock); netdev_info(bp->dev, "Flushed NetQueues: rx: %d tx: %d\n", num_rx, num_tx); } static int bnx2_netqueue_ops(vmknetddi_queueops_op_t op, void *args) { int rc; struct bnx2 *bp; if (op == VMKNETDDI_QUEUEOPS_OP_GET_VERSION) return bnx2_netq_get_netqueue_version( (vmknetddi_queueop_get_version_args_t *)args); bp = netdev_priv(((vmknetddi_queueop_get_features_args_t *)args)->netdev); if (!bnx2_netqueue_is_avail(bp) || !bnx2_netqueue_open_started(bp)) return VMKNETDDI_QUEUEOPS_ERR; mutex_lock(&bp->netq_lock); switch (op) { case VMKNETDDI_QUEUEOPS_OP_GET_FEATURES: rc = bnx2_netq_get_netqueue_features( (vmknetddi_queueop_get_features_args_t *)args); break; case VMKNETDDI_QUEUEOPS_OP_GET_QUEUE_COUNT: rc = bnx2_netq_get_queue_count( (vmknetddi_queueop_get_queue_count_args_t *)args); break; case VMKNETDDI_QUEUEOPS_OP_GET_FILTER_COUNT: rc = bnx2_netq_get_filter_count( (vmknetddi_queueop_get_filter_count_args_t *)args); break; case VMKNETDDI_QUEUEOPS_OP_ALLOC_QUEUE: rc = bnx2_netq_alloc_queue( (vmknetddi_queueop_alloc_queue_args_t *)args); break; case VMKNETDDI_QUEUEOPS_OP_FREE_QUEUE: rc = bnx2_netq_free_queue( (vmknetddi_queueop_free_queue_args_t *)args); break; case VMKNETDDI_QUEUEOPS_OP_GET_QUEUE_VECTOR: rc = bnx2_netq_get_queue_vector( (vmknetddi_queueop_get_queue_vector_args_t *)args); break; case VMKNETDDI_QUEUEOPS_OP_GET_DEFAULT_QUEUE: rc = bnx2_netq_get_default_queue( (vmknetddi_queueop_get_default_queue_args_t *)args); break; case VMKNETDDI_QUEUEOPS_OP_APPLY_RX_FILTER: rc = bnx2_netq_apply_rx_filter_vmk( (vmknetddi_queueop_apply_rx_filter_args_t *)args); break; case VMKNETDDI_QUEUEOPS_OP_REMOVE_RX_FILTER: rc = bnx2_netq_remove_rx_filter_vmk( (vmknetddi_queueop_remove_rx_filter_args_t *)args); break; case VMKNETDDI_QUEUEOPS_OP_GET_STATS: rc = bnx2_netq_get_queue_stats( (vmknetddi_queueop_get_stats_args_t *)args); break; /* Unsupported for now */ case VMKNETDDI_QUEUEOPS_OP_SET_TX_PRIORITY: rc = VMKNETDDI_QUEUEOPS_ERR; break; #if (VMWARE_ESX_DDK_VERSION >= 41000) case VMKNETDDI_QUEUEOPS_OP_ALLOC_QUEUE_WITH_ATTR: rc = VMKNETDDI_QUEUEOPS_ERR; break; case VMKNETDDI_QUEUEOPS_OP_GET_SUPPORTED_FEAT: rc = VMKNETDDI_QUEUEOPS_ERR; break; #if (VMWARE_ESX_DDK_VERSION >= 50000) case VMKNETDDI_QUEUEOPS_OP_GET_SUPPORTED_FILTER_CLASS: rc = VMKNETDDI_QUEUEOPS_ERR; break; #endif #endif default: netdev_warn(bp->dev, "Unhandled NETQUEUE OP %d\n", op); rc = VMKNETDDI_QUEUEOPS_ERR; } mutex_unlock(&bp->netq_lock); return rc; } #endif /* defined(BNX2_ENABLE_NETQUEUE) */ #if defined(__VMKLNX__) #if (VMWARE_ESX_DDK_VERSION >= 55000) static void bnx2_dump(struct bnx2 *bp, u32 reg_offset, u32 *dest_addr, u32 word_cnt) { u32 *dst = dest_addr; u32 i; for (i = 0; i < word_cnt; i++) { *dst++ = BNX2_RD(bp, reg_offset); reg_offset += 4; } } static void bnx2_dump_ind(struct bnx2 *bp, u32 reg_offset, u32 *dest_addr, u32 word_cnt) { u32 *dst = dest_addr; u32 i; for (i = 0; i < word_cnt; i++) { *dst++ = bnx2_reg_rd_ind(bp, reg_offset); reg_offset += 4; } } #define BNX2_CPU_ENTRY(offset, size) { offset, size } static const struct cpu_data_reg { u32 off; u32 size; } cpu_arr[] = { BNX2_CPU_ENTRY(0, 3), BNX2_CPU_ENTRY(0x1c, 8), BNX2_CPU_ENTRY(0x48, 1), BNX2_CPU_ENTRY(0x200, 32), }; static u32 * dump_cpu_state(struct bnx2 *bp, u32 *dst, struct bnx2_chip_core_dmp *dmp) { u32 reg, i; u32 cpu_size = 0; if (dmp->fw_hdr.dmp_size >= BNX2_FWDMP_SIZE) return dst; for (reg = BNX2_TXP_CPU_MODE; reg <= BNX2_CP_CPU_MODE; reg += 0x40000) { /* make sure these are 64-bit align */ for (i = 0; i < ARRAY_SIZE(cpu_arr); i++) cpu_size += cpu_arr[i].size * 4; } if ((dmp->fw_hdr.dmp_size + cpu_size + BNX2_FWDMP_MARKER_SZ) > BNX2_FWDMP_SIZE) return dst; *dst++ = BNX2_FWDMP_MARKER; *dst++ = 0; *dst++ = BNX2_FWDMP_CPU_DUMP; *dst++ = cpu_size; for (reg = BNX2_TXP_CPU_MODE; reg <= BNX2_CP_CPU_MODE; reg += 0x40000) { /* make sure these are 64-bit align */ for (i = 0; i < ARRAY_SIZE(cpu_arr); i++) { bnx2_dump_ind(bp, reg + cpu_arr[i].off, dst, cpu_arr[i].size); dst += cpu_arr[i].size; } } *dst++ = BNX2_FWDMP_MARKER_END; dmp->fw_hdr.dmp_size += cpu_size + BNX2_FWDMP_MARKER_SZ; return dst; } #define BNX2_FTQ_DATA_ENTRY(offset, cmdoff, size, dataoff) { BNX2_##offset, \ BNX2_##cmdoff, \ size, \ BNX2_##dataoff } static const struct ftq_data_reg { u32 off; u32 cmdoff; u32 size; u32 dataoff; } ftq_data_arr[] = { BNX2_FTQ_DATA_ENTRY(TSCH_FTQ_CMD, TSCH_FTQ_CMD_RD_DATA, 2, TSCH_TSCHQ), BNX2_FTQ_DATA_ENTRY(TBDR_FTQ_CMD, TBDR_FTQ_CMD_RD_DATA, 5, TBDR_TBDRQ), BNX2_FTQ_DATA_ENTRY(TXP_FTQ_CMD, TXP_FTQ_CMD_RD_DATA, 5, TXP_TXPQ), BNX2_FTQ_DATA_ENTRY(TDMA_FTQ_CMD, TDMA_FTQ_CMD_RD_DATA, 12, TDMA_TDMAQ), BNX2_FTQ_DATA_ENTRY(TPAT_FTQ_CMD, TPAT_FTQ_CMD_RD_DATA, 5, TPAT_TPATQ), BNX2_FTQ_DATA_ENTRY(TAS_FTQ_CMD, TAS_FTQ_CMD_RD_DATA, 4, TPAT_TPATQ), BNX2_FTQ_DATA_ENTRY(RLUP_FTQ_COMMAND, RLUP_FTQ_CMD_RD_DATA, 30, RLUP_RLUPQ), BNX2_FTQ_DATA_ENTRY(RXP_FTQ_CMD, RXP_FTQ_CMD_RD_DATA, 13, RXP_RXPQ), BNX2_FTQ_DATA_ENTRY(RXP_CFTQ_CMD, RXP_CFTQ_CMD_RD_DATA, 4, RXP_RXPCQ), BNX2_FTQ_DATA_ENTRY(RV2P_MFTQ_CMD, RV2P_MFTQ_CMD_RD_DATA, 1, RV2P_RV2PMQ), BNX2_FTQ_DATA_ENTRY(RV2P_TFTQ_CMD, RV2P_TFTQ_CMD_RD_DATA, 1, RV2P_RV2PTQ), BNX2_FTQ_DATA_ENTRY(RV2P_PFTQ_CMD, RV2P_PFTQ_CMD_RD_DATA, 13, RV2P_RV2PPQ), BNX2_FTQ_DATA_ENTRY(RDMA_FTQ_COMMAND, RDMA_FTQ_CMD_RD_DATA, 13, RDMA_RDMAQ), BNX2_FTQ_DATA_ENTRY(COM_COMQ_FTQ_CMD, COM_COMQ_FTQ_CMD_RD_DATA, 10, COM_COMQ), BNX2_FTQ_DATA_ENTRY(COM_COMTQ_FTQ_CMD, COM_COMTQ_FTQ_CMD_RD_DATA, 3, COM_COMTQ), BNX2_FTQ_DATA_ENTRY(COM_COMXQ_FTQ_CMD, COM_COMXQ_FTQ_CMD_RD_DATA, 4, COM_COMXQ), BNX2_FTQ_DATA_ENTRY(CP_CPQ_FTQ_CMD, CP_CPQ_FTQ_CMD_RD_DATA, 1, CP_CPQ), BNX2_FTQ_DATA_ENTRY(CSCH_CH_FTQ_COMMAND, CSCH_CH_FTQ_CMD_RD_DATA, 2, CSCH_CSQ), BNX2_FTQ_DATA_ENTRY(MCP_MCPQ_FTQ_CMD, MCP_MCPQ_FTQ_CMD_RD_DATA, 5, MCP_MCPQ), }; static u32 * dump_ftq_ctrl_info(struct bnx2 *bp, u32 *dst, struct bnx2_chip_core_dmp *dmp) { int i; u32 ftq_size = 0; if (dmp->fw_hdr.dmp_size >= BNX2_FWDMP_SIZE) return dst; for (i = 0; i < ARRAY_SIZE(ftq_arr); i++) ftq_size += 4; for (i = 0; i < ARRAY_SIZE(ftq_data_arr); i++) ftq_size += ftq_data_arr[i].size * 4; if ((dmp->fw_hdr.dmp_size + ftq_size + BNX2_FWDMP_MARKER_SZ) > BNX2_FWDMP_SIZE) return dst; *dst++ = BNX2_FWDMP_MARKER; *dst++ = 0; *dst++ = BNX2_FWDMP_FTQ_DUMP; *dst++ = ftq_size; for (i = 0; i < ARRAY_SIZE(ftq_arr); i++) *dst++ = bnx2_reg_rd_ind(bp, ftq_arr[i].off); for (i = 0; i < ARRAY_SIZE(ftq_data_arr); i++) { bnx2_reg_wr_ind(bp, ftq_data_arr[i].off, ftq_data_arr[i].cmdoff); bnx2_dump_ind(bp, ftq_data_arr[i].dataoff, dst, ftq_data_arr[i].size); dst += ftq_data_arr[i].size; } *dst++ = BNX2_FWDMP_MARKER_END; dmp->fw_hdr.dmp_size += ftq_size + BNX2_FWDMP_MARKER_SZ; return dst; } #define BNX2_GRCBLK_SIZE 0x400 #define BNX2_GRC_ENTRY(offset) { BNX2_##offset } static const struct grc_reg { u32 off; } grc_arr[] = { BNX2_GRC_ENTRY(PCICFG_START), BNX2_GRC_ENTRY(PCI_GRC_WINDOW_ADDR), BNX2_GRC_ENTRY(MISC_COMMAND), BNX2_GRC_ENTRY(DMA_COMMAND), BNX2_GRC_ENTRY(CTX_COMMAND), BNX2_GRC_ENTRY(EMAC_MODE), BNX2_GRC_ENTRY(RPM_COMMAND), BNX2_GRC_ENTRY(RCP_START), BNX2_GRC_ENTRY(RLUP_COMMAND), BNX2_GRC_ENTRY(CH_COMMAND), BNX2_GRC_ENTRY(RV2P_COMMAND), BNX2_GRC_ENTRY(RDMA_COMMAND), BNX2_GRC_ENTRY(RBDC_COMMAND), BNX2_GRC_ENTRY(MQ_COMMAND), BNX2_GRC_ENTRY(TIMER_COMMAND), BNX2_GRC_ENTRY(TSCH_COMMAND), BNX2_GRC_ENTRY(TBDR_COMMAND), BNX2_GRC_ENTRY(TBDC_COMMAND), BNX2_GRC_ENTRY(TDMA_COMMAND), BNX2_GRC_ENTRY(DBU_CMD), BNX2_GRC_ENTRY(NVM_COMMAND), BNX2_GRC_ENTRY(HC_COMMAND), BNX2_GRC_ENTRY(DEBUG_COMMAND), }; static u32 *dump_grc(struct bnx2 *bp, u32 *dst, struct bnx2_chip_core_dmp *dmp) { u32 i; u32 grc_size = 0; if (dmp->fw_hdr.dmp_size >= BNX2_FWDMP_SIZE) return dst; for (i = 0; i < ARRAY_SIZE(grc_arr); i++) grc_size += BNX2_GRCBLK_SIZE; if ((dmp->fw_hdr.dmp_size + grc_size + BNX2_FWDMP_MARKER_SZ) > BNX2_FWDMP_SIZE) return dst; *dst++ = BNX2_FWDMP_MARKER; *dst++ = 0; *dst++ = BNX2_FWDMP_GRC_DUMP; *dst++ = grc_size; for (i = 0; i < ARRAY_SIZE(grc_arr); i++) { bnx2_dump(bp, grc_arr[i].off, dst, BNX2_GRCBLK_SIZE/4); dst += BNX2_GRCBLK_SIZE/4; } *dst++ = BNX2_FWDMP_MARKER_END; dmp->fw_hdr.dmp_size += grc_size + BNX2_FWDMP_MARKER_SZ; return dst; } #define BNX2_HSI_ENTRY(offset, size) { BNX2_##offset, BNX2_##size } static const struct hsi_reg { u32 off; u32 size; } hsi_arr[] = { BNX2_HSI_ENTRY(CP_HSI_START, CP_HSI_SIZE), BNX2_HSI_ENTRY(COM_HSI_START, COM_HSI_SIZE), BNX2_HSI_ENTRY(RXP_HSI_START, RXP_HSI_SIZE), BNX2_HSI_ENTRY(TXP_HSI_START, TXP_HSI_SIZE), BNX2_HSI_ENTRY(TPAT_HSI_START, TPAT_HSI_SIZE), }; static u32 *dump_hsi(struct bnx2 *bp, u32 *dst, struct bnx2_chip_core_dmp *dmp) { u32 i; u32 hsi_size = 0; if (dmp->fw_hdr.dmp_size >= BNX2_FWDMP_SIZE) return dst; for (i = 0; i < ARRAY_SIZE(hsi_arr); i++) hsi_size += hsi_arr[i].size; if ((dmp->fw_hdr.dmp_size + hsi_size + BNX2_FWDMP_MARKER_SZ) > BNX2_FWDMP_SIZE) return dst; *dst++ = BNX2_FWDMP_MARKER; *dst++ = 0; *dst++ = BNX2_FWDMP_HSI_DUMP; *dst++ = hsi_size; for (i = 0; i < ARRAY_SIZE(hsi_arr); i++) { bnx2_dump_ind(bp, hsi_arr[i].off, dst, hsi_arr[i].size/4); dst += hsi_arr[i].size/4; } *dst++ = BNX2_FWDMP_MARKER_END; dmp->fw_hdr.dmp_size += hsi_size + BNX2_FWDMP_MARKER_SZ; return dst; } static u32 * dump_mcp_info(struct bnx2 *bp, u32 *dst, struct bnx2_chip_core_dmp *dmp) { u32 i; if (dmp->fw_hdr.dmp_size >= BNX2_FWDMP_SIZE) return dst; *dst++ = BNX2_FWDMP_MARKER; *dst++ = 0; *dst++ = BNX2_FWDMP_MCP_DUMP; *dst++ = BNX2_MCP_DUMP_SIZE; if (BNX2_CHIP(bp) == BNX2_CHIP_5709) { *dst++ = bnx2_reg_rd_ind(bp, BNX2_MCP_STATE_P0); *dst++ = bnx2_reg_rd_ind(bp, BNX2_MCP_STATE_P1); } else { *dst++ = bnx2_reg_rd_ind(bp, BNX2_MCP_STATE_P0_5708); *dst++ = bnx2_reg_rd_ind(bp, BNX2_MCP_STATE_P1_5708); } *dst++ = bnx2_reg_rd_ind(bp, BNX2_MCP_CPU_MODE); *dst++ = bnx2_reg_rd_ind(bp, BNX2_MCP_CPU_STATE); *dst++ = bnx2_reg_rd_ind(bp, BNX2_MCP_CPU_EVENT_MASK); *dst++ = bnx2_reg_rd_ind(bp, BNX2_MCP_CPU_PROGRAM_COUNTER); *dst++ = bnx2_reg_rd_ind(bp, BNX2_MCP_CPU_PROGRAM_COUNTER); *dst++ = bnx2_reg_rd_ind(bp, BNX2_MCP_CPU_INSTRUCTION); *dst++ = bnx2_shmem_rd(bp, BNX2_DRV_MB); *dst++ = bnx2_shmem_rd(bp, BNX2_FW_MB); *dst++ = bnx2_shmem_rd(bp, BNX2_LINK_STATUS); *dst++ = bnx2_shmem_rd(bp, BNX2_DRV_PULSE_MB); *dst++ = bnx2_shmem_rd(bp, BNX2_DEV_INFO_SIGNATURE); *dst++ = bnx2_shmem_rd(bp, BNX2_BC_STATE_RESET_TYPE); *dst++ = bnx2_shmem_rd(bp, BNX2_BC_STATE_CONDITION); for (i = 0; i < 16;) { *dst++ = bnx2_shmem_rd(bp, BNX2_BC_STATE_RESET_TYPE); i += 4; } for (i = 0; i < 16;) { *dst++ = bnx2_shmem_rd(bp, 0x3cc); i += 4; } for (i = 0; i < 16;) { *dst++ = bnx2_shmem_rd(bp, 0x3dc); i += 4; } for (i = 0; i < 16;) { *dst++ = bnx2_shmem_rd(bp, 0x3ec); i += 4; } *dst++ = bnx2_shmem_rd(bp, 0x3fc); *dst++ = BNX2_FWDMP_MARKER_END; dmp->fw_hdr.dmp_size += BNX2_MCP_DUMP_SIZE + BNX2_FWDMP_MARKER_SZ; return dst; } static u32 *dump_tbdc(struct bnx2 *bp, u32 *dst, struct bnx2_chip_core_dmp *dmp) { u32 i; if (dmp->fw_hdr.dmp_size >= BNX2_FWDMP_SIZE) return dst; if ((dmp->fw_hdr.dmp_size + BNX2_TBDC_DUMP_SIZE + BNX2_FWDMP_MARKER_SZ) > BNX2_FWDMP_SIZE) return dst; *dst++ = BNX2_FWDMP_MARKER; *dst++ = 0; *dst++ = BNX2_FWDMP_TBDC_DUMP; *dst++ = BNX2_TBDC_DUMP_SIZE; for (i = 0; i < 0x20; i++) { int j = 0; BNX2_WR(bp, BNX2_TBDC_BD_ADDR, i); BNX2_WR(bp, BNX2_TBDC_CAM_OPCODE, BNX2_TBDC_CAM_OPCODE_OPCODE_CAM_READ); BNX2_WR(bp, BNX2_TBDC_COMMAND, BNX2_TBDC_COMMAND_CMD_REG_ARB); while ((BNX2_RD(bp, BNX2_TBDC_COMMAND) & BNX2_TBDC_COMMAND_CMD_REG_ARB) && j < 100) j++; *dst++ = BNX2_RD(bp, BNX2_TBDC_CID); *dst++ = BNX2_RD(bp, BNX2_TBDC_BIDX); *dst++ = BNX2_RD(bp, BNX2_TBDC_CAM_OPCODE); } *dst++ = BNX2_FWDMP_MARKER_END; dmp->fw_hdr.dmp_size += BNX2_TBDC_DUMP_SIZE + BNX2_FWDMP_MARKER_SZ; return dst; } static VMK_ReturnStatus bnx2_fwdmp_callback(void *cookie, vmk_Bool liveDump) { VMK_ReturnStatus status = VMK_OK; u32 idx; u32 *dst; struct bnx2_chip_core_dmp *dmp; struct bnx2 *bp; printk(KERN_INFO "FW dump for QLogic Nx2 Gigabit Ethernet Driver " DRV_MODULE_NAME " v" DRV_MODULE_VERSION " (" DRV_MODULE_RELDATE ")\n"); for (idx = 0; idx < BNX2_MAX_NIC; idx++) { if (fwdmp_va_ptr && fwdmp_bp_ptr[idx]) { /* dump chip information to buffer */ bp = fwdmp_bp_ptr[idx]; dmp = (struct bnx2_chip_core_dmp *)fwdmp_va_ptr; snprintf(dmp->fw_hdr.name, sizeof(dmp->fw_hdr.name), "%s", bp->dev->name); dmp->fw_hdr.bp = (void *)bp; dmp->fw_hdr.chip_id = bp->chip_id; dmp->fw_hdr.len = sizeof(struct bnx2_fw_dmp_hdr); dmp->fw_hdr.ver = 0x000700006; dmp->fw_hdr.dmp_size = dmp->fw_hdr.len; /* 1. dump all CPUs states */ dst = dmp->fw_dmp_buf; dst = dump_cpu_state(bp, dst, dmp); /* 2. dump all ftqs control information */ dst = dump_ftq_ctrl_info(bp, dst, dmp); /* 3. dump mcp info */ dst = dump_mcp_info(bp, dst, dmp); /* 4. dump tbdc contents */ dst = dump_tbdc(bp, dst, dmp); /* 5. dump hsi section for all processors */ dst = dump_hsi(bp, dst, dmp); /* 6. dump 32k grc registers */ dst = dump_grc(bp, dst, dmp); status = vmklnx_dump_range(bnx2_fwdmp_dh, fwdmp_va_ptr, dmp->fw_hdr.dmp_size); if (status != VMK_OK) { printk(KERN_ERR "####failed to dump firmware/chip data %x %d!\n", status, idx); break; } } } return status; } #endif /* The following debug buffers and exported routines are used by GDB to access teton/xinan hardware registers when doing live debug over serial port. */ #define DBG_BUF_SZ 128 static u32 bnx2_dbg_buf[DBG_BUF_SZ]; static u32 bnx2_dbg_read32_ind_single(void __iomem *reg_view, u32 off) { u32 val; writel(off, reg_view + BNX2_PCICFG_REG_WINDOW_ADDRESS); val = readl(reg_view + BNX2_PCICFG_REG_WINDOW); return val; } void bnx2_dbg_read32_ind(void __iomem *reg_view, u32 off, u32 len) { u32 *buf = bnx2_dbg_buf; if (len & 0x3) len = (len + 3) & ~3; if (len > DBG_BUF_SZ) len = DBG_BUF_SZ; while (len > 0) { *buf = bnx2_dbg_read32_ind_single(reg_view, off); buf++; off += 4; len -= 4; } } EXPORT_SYMBOL(bnx2_dbg_read32_ind); static u32 bnx2_dbg_read32_single(void __iomem *reg_view, u32 off) { return readl(reg_view + off); } void bnx2_dbg_read32(void __iomem *reg_view, u32 off, u32 len) { u32 *buf = bnx2_dbg_buf; if (len & 0x3) len = (len + 3) & ~3; if (len > DBG_BUF_SZ) len = DBG_BUF_SZ; while (len > 0) { *buf = bnx2_dbg_read32_single(reg_view, off); buf++; off += 4; len -= 4; } } EXPORT_SYMBOL(bnx2_dbg_read32); void bnx2_dbg_write32(void __iomem *reg_view, u32 off, u32 val) { writel(val, reg_view + off); } EXPORT_SYMBOL(bnx2_dbg_write32); void bnx2_dbg_write32_ind(void __iomem *reg_view, u32 off, u32 val) { writel(off, reg_view + BNX2_PCICFG_REG_WINDOW_ADDRESS); writel(val, reg_view + BNX2_PCICFG_REG_WINDOW); } EXPORT_SYMBOL(bnx2_dbg_write32_ind); #endif /*__VMKLNX__ */
Java
/* * libpal - Automated Placement of Labels Library * * Copyright (C) 2008 Maxence Laurent, MIS-TIC, HEIG-VD * University of Applied Sciences, Western Switzerland * http://www.hes-so.ch * * Contact: * maxence.laurent <at> heig-vd <dot> ch * or * eric.taillard <at> heig-vd <dot> ch * * This file is part of libpal. * * libpal is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * libpal 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 libpal. If not, see <http://www.gnu.org/licenses/>. * */ #ifndef FEATURE_H #define FEATURE_H #define SIP_NO_FILE #include "qgis_core.h" #include "pointset.h" #include "labelposition.h" // for LabelPosition enum #include "qgslabelfeature.h" #include <iostream> #include <fstream> #include <cmath> #include <QString> /** * \ingroup core * \class pal::LabelInfo * \note not available in Python bindings */ namespace pal { //! Optional additional info about label (for curved labels) class CORE_EXPORT LabelInfo { public: struct CharacterInfo { double width; }; LabelInfo( int num, double height, double maxinangle = 20.0, double maxoutangle = -20.0 ) { max_char_angle_inside = maxinangle; // outside angle should be negative max_char_angle_outside = maxoutangle > 0 ? -maxoutangle : maxoutangle; label_height = height; char_num = num; char_info = new CharacterInfo[num]; } ~LabelInfo() { delete [] char_info; } //! LabelInfo cannot be copied LabelInfo( const LabelInfo &rh ) = delete; //! LabelInfo cannot be copied LabelInfo &operator=( const LabelInfo &rh ) = delete; double max_char_angle_inside; double max_char_angle_outside; double label_height; int char_num; CharacterInfo *char_info = nullptr; }; class LabelPosition; class FeaturePart; /** * \ingroup core * \brief Main class to handle feature * \class pal::FeaturePart * \note not available in Python bindings */ class CORE_EXPORT FeaturePart : public PointSet { public: /** * Creates a new generic feature. * \param lf a pointer for a feature which contains the spatial entites * \param geom a pointer to a GEOS geometry */ FeaturePart( QgsLabelFeature *lf, const GEOSGeometry *geom ); FeaturePart( const FeaturePart &other ); /** * Delete the feature */ ~FeaturePart() override; /** * Returns the parent feature. */ QgsLabelFeature *feature() { return mLF; } /** * Returns the layer that feature belongs to. */ Layer *layer(); /** * Returns the unique ID of the feature. */ QgsFeatureId featureId() const; /** * Returns the maximum number of point candidates to generate for this feature. */ std::size_t maximumPointCandidates() const; /** * Returns the maximum number of line candidates to generate for this feature. */ std::size_t maximumLineCandidates() const; /** * Returns the maximum number of polygon candidates to generate for this feature. */ std::size_t maximumPolygonCandidates() const; /** * Generates a list of candidate positions for labels for this feature. */ std::vector<std::unique_ptr<LabelPosition> > createCandidates( Pal *pal ); /** * Generate candidates for point feature, located around a specified point. * \param x x coordinate of the point * \param y y coordinate of the point * \param lPos pointer to an array of candidates, will be filled by generated candidates * \param angle orientation of the label * \returns the number of generated candidates */ std::size_t createCandidatesAroundPoint( double x, double y, std::vector<std::unique_ptr<LabelPosition> > &lPos, double angle ); /** * Generate one candidate over or offset the specified point. * \param x x coordinate of the point * \param y y coordinate of the point * \param lPos pointer to an array of candidates, will be filled by generated candidate * \param angle orientation of the label * \returns the number of generated candidates (always 1) */ std::size_t createCandidatesOverPoint( double x, double y, std::vector<std::unique_ptr<LabelPosition> > &lPos, double angle ); /** * Creates a single candidate using the "point on sruface" algorithm. * * \note Unlike the other create candidates methods, this method * bypasses the usual candidate filtering steps and ALWAYS returns a single candidate. */ std::unique_ptr< LabelPosition > createCandidatePointOnSurface( PointSet *mapShape ); /** * Generates candidates following a prioritized list of predefined positions around a point. * \param x x coordinate of the point * \param y y coordinate of the point * \param lPos pointer to an array of candidates, will be filled by generated candidate * \param angle orientation of the label * \returns the number of generated candidates */ std::size_t createCandidatesAtOrderedPositionsOverPoint( double x, double y, std::vector<std::unique_ptr<LabelPosition> > &lPos, double angle ); /** * Generate candidates for line feature. * \param lPos pointer to an array of candidates, will be filled by generated candidates * \param mapShape a pointer to the line * \param allowOverrun set to TRUE to allow labels to overrun features * \param pal point to pal settings object, for cancellation support * \returns the number of generated candidates */ std::size_t createCandidatesAlongLine( std::vector<std::unique_ptr<LabelPosition> > &lPos, PointSet *mapShape, bool allowOverrun, Pal *pal ); /** * Generate candidates for line feature, by trying to place candidates towards the middle of the longest * straightish segments of the line. Segments closer to horizontal are preferred over vertical segments. * \param lPos pointer to an array of candidates, will be filled by generated candidates * \param mapShape a pointer to the line * \param pal point to pal settings object, for cancellation support * \returns the number of generated candidates */ std::size_t createCandidatesAlongLineNearStraightSegments( std::vector<std::unique_ptr<LabelPosition> > &lPos, PointSet *mapShape, Pal *pal ); /** * Generate candidates for line feature, by trying to place candidates as close as possible to the line's midpoint. * Candidates can "cut corners" if it helps them place near this mid point. * \param lPos pointer to an array of candidates, will be filled by generated candidates * \param mapShape a pointer to the line * \param initialCost initial cost for candidates generated using this method. If set, cost can be increased * by a preset amount. * \param pal point to pal settings object, for cancellation support * \returns the number of generated candidates */ std::size_t createCandidatesAlongLineNearMidpoint( std::vector<std::unique_ptr<LabelPosition> > &lPos, PointSet *mapShape, double initialCost = 0.0, Pal *pal = nullptr ); /** * Returns the label position for a curved label at a specific offset along a path. * \param path_positions line path to place label on * \param path_distances array of distances to each segment on path * \param orientation can be 0 for automatic calculation of orientation, or -1/+1 for a specific label orientation * \param distance distance to offset label along curve by * \param reversed if TRUE label is reversed from lefttoright to righttoleft * \param flip if TRUE label is placed on the other side of the line * \returns calculated label position */ std::unique_ptr< LabelPosition > curvedPlacementAtOffset( PointSet *path_positions, double *path_distances, int &orientation, double distance, bool &reversed, bool &flip ); /** * Generate curved candidates for line features. * \param lPos pointer to an array of candidates, will be filled by generated candidates * \param mapShape a pointer to the line * \param allowOverrun set to TRUE to allow labels to overrun features * \param pal point to pal settings object, for cancellation support * \returns the number of generated candidates */ std::size_t createCurvedCandidatesAlongLine( std::vector<std::unique_ptr<LabelPosition> > &lPos, PointSet *mapShape, bool allowOverrun, Pal *pal ); /** * Generate candidates for polygon features. * \param lPos pointer to an array of candidates, will be filled by generated candidates * \param mapShape a pointer to the polygon * \param pal point to pal settings object, for cancellation support * \returns the number of generated candidates */ std::size_t createCandidatesForPolygon( std::vector<std::unique_ptr<LabelPosition> > &lPos, PointSet *mapShape, Pal *pal ); /** * Tests whether this feature part belongs to the same QgsLabelFeature as another * feature part. * \param part part to compare to * \returns TRUE if both parts belong to same QgsLabelFeature */ bool hasSameLabelFeatureAs( FeaturePart *part ) const; #if 0 /** * \brief Print feature information * Print feature unique id, geometry type, points, and holes on screen */ void print(); #endif /** * Returns the width of the label, optionally taking an \a angle into account. * \returns the width of the label */ double getLabelWidth( double angle = 0.0 ) const { return mLF->size( angle ).width(); } /** * Returns the height of the label, optionally taking an \a angle into account. * \returns the hieght of the label */ double getLabelHeight( double angle = 0.0 ) const { return mLF->size( angle ).height(); } /** * Returns the distance from the anchor point to the label * \returns the distance to the label */ double getLabelDistance() const { return mLF->distLabel(); } //! Returns TRUE if the feature's label has a fixed rotation bool hasFixedRotation() const { return mLF->hasFixedAngle(); } //! Returns the fixed angle for the feature's label double fixedAngle() const { return mLF->fixedAngle(); } //! Returns TRUE if the feature's label has a fixed position bool hasFixedPosition() const { return mLF->hasFixedPosition(); } /** * Returns TRUE if the feature's label should always been shown, * even when it collides with other labels */ bool alwaysShow() const { return mLF->alwaysShow(); } /** * Returns the feature's obstacle settings. */ const QgsLabelObstacleSettings &obstacleSettings() const { return mLF->obstacleSettings(); } //! Returns the distance between repeating labels for this feature double repeatDistance() const { return mLF->repeatDistance(); } //! Gets number of holes (inner rings) - they are considered as obstacles int getNumSelfObstacles() const { return mHoles.count(); } //! Gets hole (inner ring) - considered as obstacle FeaturePart *getSelfObstacle( int i ) { return mHoles.at( i ); } //! Check whether this part is connected with some other part bool isConnected( FeaturePart *p2 ); /** * Merge other (connected) part with this one and save the result in this part (other is unchanged). * Returns TRUE on success, FALSE if the feature wasn't modified */ bool mergeWithFeaturePart( FeaturePart *other ); /** * Increases the cost of the label candidates for this feature, based on the size of the feature. * * E.g. small lines or polygons get higher cost so that larger features are more likely to be labeled. */ void addSizePenalty( std::vector<std::unique_ptr<LabelPosition> > &lPos, double bbx[4], double bby[4] ); /** * Calculates the priority for the feature. This will be the feature's priority if set, * otherwise the layer's default priority. */ double calculatePriority() const; //! Returns TRUE if feature's label must be displayed upright bool showUprightLabels() const; //! Returns TRUE if the next char position is found. The referenced parameters are updated. bool nextCharPosition( double charWidth, double segmentLength, PointSet *path_positions, int &index, double &currentDistanceAlongSegment, double &characterStartX, double &characterStartY, double &characterEndX, double &characterEndY ) const; /** * Returns the total number of repeating labels associated with this label. * \see setTotalRepeats() */ int totalRepeats() const; /** * Returns the total number of repeating labels associated with this label. * \see totalRepeats() */ void setTotalRepeats( int repeats ); protected: QgsLabelFeature *mLF = nullptr; QList<FeaturePart *> mHoles; //! \brief read coordinates from a GEOS geom void extractCoords( const GEOSGeometry *geom ); private: LabelPosition::Quadrant quadrantFromOffset() const; int mTotalRepeats = 0; mutable std::size_t mCachedMaxLineCandidates = 0; mutable std::size_t mCachedMaxPolygonCandidates = 0; }; } // end namespace pal #endif
Java
<?php // @codingStandardsIgnoreFile namespace Drupal\Tests\Component\Annotation\Doctrine; use Drupal\Component\Annotation\Doctrine\DocParser; use Doctrine\Common\Annotations\AnnotationRegistry; use Doctrine\Common\Annotations\Annotation\Target; use Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithConstants; use Drupal\Tests\Component\Annotation\Doctrine\Fixtures\ClassWithConstants; use Drupal\Tests\Component\Annotation\Doctrine\Fixtures\IntefaceWithConstants; use PHPUnit\Framework\TestCase; /** * @coversDefaultClass \Drupal\Component\Annotation\Doctrine\DocParser * * This class is a near-copy of * Doctrine\Tests\Common\Annotations\DocParserTest, which is part of the * Doctrine project: <http://www.doctrine-project.org>. It was copied from * version 1.2.7. * * The supporting test fixture classes in * core/tests/Drupal/Tests/Component/Annotation/Doctrine/Fixtures were also * copied from version 1.2.7. * * @group Annotation */ class DocParserTest extends TestCase { public function testNestedArraysWithNestedAnnotation() { $parser = $this->createTestParser(); // Nested arrays with nested annotations $result = $parser->parse('@Name(foo={1,2, {"key"=@Name}})'); $annot = $result[0]; $this->assertTrue($annot instanceof Name); $this->assertNull($annot->value); $this->assertEquals(3, count($annot->foo)); $this->assertEquals(1, $annot->foo[0]); $this->assertEquals(2, $annot->foo[1]); $this->assertTrue(is_array($annot->foo[2])); $nestedArray = $annot->foo[2]; $this->assertTrue(isset($nestedArray['key'])); $this->assertTrue($nestedArray['key'] instanceof Name); } public function testBasicAnnotations() { $parser = $this->createTestParser(); // Marker annotation $result = $parser->parse("@Name"); $annot = $result[0]; $this->assertTrue($annot instanceof Name); $this->assertNull($annot->value); $this->assertNull($annot->foo); // Associative arrays $result = $parser->parse('@Name(foo={"key1" = "value1"})'); $annot = $result[0]; $this->assertNull($annot->value); $this->assertTrue(is_array($annot->foo)); $this->assertTrue(isset($annot->foo['key1'])); // Numerical arrays $result = $parser->parse('@Name({2="foo", 4="bar"})'); $annot = $result[0]; $this->assertTrue(is_array($annot->value)); $this->assertEquals('foo', $annot->value[2]); $this->assertEquals('bar', $annot->value[4]); $this->assertFalse(isset($annot->value[0])); $this->assertFalse(isset($annot->value[1])); $this->assertFalse(isset($annot->value[3])); // Multiple values $result = $parser->parse('@Name(@Name, @Name)'); $annot = $result[0]; $this->assertTrue($annot instanceof Name); $this->assertTrue(is_array($annot->value)); $this->assertTrue($annot->value[0] instanceof Name); $this->assertTrue($annot->value[1] instanceof Name); // Multiple types as values $result = $parser->parse('@Name(foo="Bar", @Name, {"key1"="value1", "key2"="value2"})'); $annot = $result[0]; $this->assertTrue($annot instanceof Name); $this->assertTrue(is_array($annot->value)); $this->assertTrue($annot->value[0] instanceof Name); $this->assertTrue(is_array($annot->value[1])); $this->assertEquals('value1', $annot->value[1]['key1']); $this->assertEquals('value2', $annot->value[1]['key2']); // Complete docblock $docblock = <<<DOCBLOCK /** * Some nifty class. * * @author Mr.X * @Name(foo="bar") */ DOCBLOCK; $result = $parser->parse($docblock); $this->assertEquals(1, count($result)); $annot = $result[0]; $this->assertTrue($annot instanceof Name); $this->assertEquals("bar", $annot->foo); $this->assertNull($annot->value); } public function testDefaultValueAnnotations() { $parser = $this->createTestParser(); // Array as first value $result = $parser->parse('@Name({"key1"="value1"})'); $annot = $result[0]; $this->assertTrue($annot instanceof Name); $this->assertTrue(is_array($annot->value)); $this->assertEquals('value1', $annot->value['key1']); // Array as first value and additional values $result = $parser->parse('@Name({"key1"="value1"}, foo="bar")'); $annot = $result[0]; $this->assertTrue($annot instanceof Name); $this->assertTrue(is_array($annot->value)); $this->assertEquals('value1', $annot->value['key1']); $this->assertEquals('bar', $annot->foo); } public function testNamespacedAnnotations() { $parser = new DocParser; $parser->setIgnoreNotImportedAnnotations(true); $docblock = <<<DOCBLOCK /** * Some nifty class. * * @package foo * @subpackage bar * @author Mr.X <[email protected]> * @Drupal\Tests\Component\Annotation\Doctrine\Name(foo="bar") * @ignore */ DOCBLOCK; $result = $parser->parse($docblock); $this->assertEquals(1, count($result)); $annot = $result[0]; $this->assertTrue($annot instanceof Name); $this->assertEquals("bar", $annot->foo); } /** * @group debug */ public function testTypicalMethodDocBlock() { $parser = $this->createTestParser(); $docblock = <<<DOCBLOCK /** * Some nifty method. * * @since 2.0 * @Drupal\Tests\Component\Annotation\Doctrine\Name(foo="bar") * @param string \$foo This is foo. * @param mixed \$bar This is bar. * @return string Foo and bar. * @This is irrelevant * @Marker */ DOCBLOCK; $result = $parser->parse($docblock); $this->assertEquals(2, count($result)); $this->assertTrue(isset($result[0])); $this->assertTrue(isset($result[1])); $annot = $result[0]; $this->assertTrue($annot instanceof Name); $this->assertEquals("bar", $annot->foo); $marker = $result[1]; $this->assertTrue($marker instanceof Marker); } public function testAnnotationWithoutConstructor() { $parser = $this->createTestParser(); $docblock = <<<DOCBLOCK /** * @SomeAnnotationClassNameWithoutConstructor("Some data") */ DOCBLOCK; $result = $parser->parse($docblock); $this->assertEquals(count($result), 1); $annot = $result[0]; $this->assertNotNull($annot); $this->assertTrue($annot instanceof SomeAnnotationClassNameWithoutConstructor); $this->assertNull($annot->name); $this->assertNotNull($annot->data); $this->assertEquals($annot->data, "Some data"); $docblock = <<<DOCBLOCK /** * @SomeAnnotationClassNameWithoutConstructor(name="Some Name", data = "Some data") */ DOCBLOCK; $result = $parser->parse($docblock); $this->assertEquals(count($result), 1); $annot = $result[0]; $this->assertNotNull($annot); $this->assertTrue($annot instanceof SomeAnnotationClassNameWithoutConstructor); $this->assertEquals($annot->name, "Some Name"); $this->assertEquals($annot->data, "Some data"); $docblock = <<<DOCBLOCK /** * @SomeAnnotationClassNameWithoutConstructor(data = "Some data") */ DOCBLOCK; $result = $parser->parse($docblock); $this->assertEquals(count($result), 1); $annot = $result[0]; $this->assertEquals($annot->data, "Some data"); $this->assertNull($annot->name); $docblock = <<<DOCBLOCK /** * @SomeAnnotationClassNameWithoutConstructor(name = "Some name") */ DOCBLOCK; $result = $parser->parse($docblock); $this->assertEquals(count($result), 1); $annot = $result[0]; $this->assertEquals($annot->name, "Some name"); $this->assertNull($annot->data); $docblock = <<<DOCBLOCK /** * @SomeAnnotationClassNameWithoutConstructor("Some data") */ DOCBLOCK; $result = $parser->parse($docblock); $this->assertEquals(count($result), 1); $annot = $result[0]; $this->assertEquals($annot->data, "Some data"); $this->assertNull($annot->name); $docblock = <<<DOCBLOCK /** * @SomeAnnotationClassNameWithoutConstructor("Some data",name = "Some name") */ DOCBLOCK; $result = $parser->parse($docblock); $this->assertEquals(count($result), 1); $annot = $result[0]; $this->assertEquals($annot->name, "Some name"); $this->assertEquals($annot->data, "Some data"); $docblock = <<<DOCBLOCK /** * @SomeAnnotationWithConstructorWithoutParams(name = "Some name") */ DOCBLOCK; $result = $parser->parse($docblock); $this->assertEquals(count($result), 1); $annot = $result[0]; $this->assertEquals($annot->name, "Some name"); $this->assertEquals($annot->data, "Some data"); $docblock = <<<DOCBLOCK /** * @SomeAnnotationClassNameWithoutConstructorAndProperties() */ DOCBLOCK; $result = $parser->parse($docblock); $this->assertEquals(count($result), 1); $this->assertTrue($result[0] instanceof SomeAnnotationClassNameWithoutConstructorAndProperties); } public function testAnnotationTarget() { $parser = new DocParser; $parser->setImports(array( '__NAMESPACE__' => 'Drupal\Tests\Component\Annotation\Doctrine\Fixtures', )); $class = new \ReflectionClass('Drupal\Tests\Component\Annotation\Doctrine\Fixtures\ClassWithValidAnnotationTarget'); $context = 'class ' . $class->getName(); $docComment = $class->getDocComment(); $parser->setTarget(Target::TARGET_CLASS); $this->assertNotNull($parser->parse($docComment,$context)); $property = $class->getProperty('foo'); $docComment = $property->getDocComment(); $context = 'property ' . $class->getName() . "::\$" . $property->getName(); $parser->setTarget(Target::TARGET_PROPERTY); $this->assertNotNull($parser->parse($docComment,$context)); $method = $class->getMethod('someFunction'); $docComment = $property->getDocComment(); $context = 'method ' . $class->getName() . '::' . $method->getName() . '()'; $parser->setTarget(Target::TARGET_METHOD); $this->assertNotNull($parser->parse($docComment,$context)); try { $class = new \ReflectionClass('Drupal\Tests\Component\Annotation\Doctrine\Fixtures\ClassWithInvalidAnnotationTargetAtClass'); $context = 'class ' . $class->getName(); $docComment = $class->getDocComment(); $parser->setTarget(Target::TARGET_CLASS); $parser->parse($docComment, $context); $this->fail(); } catch (\Doctrine\Common\Annotations\AnnotationException $exc) { $this->assertNotNull($exc->getMessage()); } try { $class = new \ReflectionClass('Drupal\Tests\Component\Annotation\Doctrine\Fixtures\ClassWithInvalidAnnotationTargetAtMethod'); $method = $class->getMethod('functionName'); $docComment = $method->getDocComment(); $context = 'method ' . $class->getName() . '::' . $method->getName() . '()'; $parser->setTarget(Target::TARGET_METHOD); $parser->parse($docComment, $context); $this->fail(); } catch (\Doctrine\Common\Annotations\AnnotationException $exc) { $this->assertNotNull($exc->getMessage()); } try { $class = new \ReflectionClass('Drupal\Tests\Component\Annotation\Doctrine\Fixtures\ClassWithInvalidAnnotationTargetAtProperty'); $property = $class->getProperty('foo'); $docComment = $property->getDocComment(); $context = 'property ' . $class->getName() . "::\$" . $property->getName(); $parser->setTarget(Target::TARGET_PROPERTY); $parser->parse($docComment, $context); $this->fail(); } catch (\Doctrine\Common\Annotations\AnnotationException $exc) { $this->assertNotNull($exc->getMessage()); } } public function getAnnotationVarTypeProviderValid() { //({attribute name}, {attribute value}) return array( // mixed type array('mixed', '"String Value"'), array('mixed', 'true'), array('mixed', 'false'), array('mixed', '1'), array('mixed', '1.2'), array('mixed', '@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAll'), // boolean type array('boolean', 'true'), array('boolean', 'false'), // alias for internal type boolean array('bool', 'true'), array('bool', 'false'), // integer type array('integer', '0'), array('integer', '1'), array('integer', '123456789'), array('integer', '9223372036854775807'), // alias for internal type double array('float', '0.1'), array('float', '1.2'), array('float', '123.456'), // string type array('string', '"String Value"'), array('string', '"true"'), array('string', '"123"'), // array type array('array', '{@AnnotationExtendsAnnotationTargetAll}'), array('array', '{@AnnotationExtendsAnnotationTargetAll,@AnnotationExtendsAnnotationTargetAll}'), array('arrayOfIntegers', '1'), array('arrayOfIntegers', '{1}'), array('arrayOfIntegers', '{1,2,3,4}'), array('arrayOfAnnotations', '@AnnotationExtendsAnnotationTargetAll'), array('arrayOfAnnotations', '{@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAll}'), array('arrayOfAnnotations', '{@AnnotationExtendsAnnotationTargetAll, @Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAll}'), // annotation instance array('annotation', '@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAll'), array('annotation', '@AnnotationExtendsAnnotationTargetAll'), ); } public function getAnnotationVarTypeProviderInvalid() { //({attribute name}, {type declared type}, {attribute value} , {given type or class}) return array( // boolean type array('boolean','boolean','1','integer'), array('boolean','boolean','1.2','double'), array('boolean','boolean','"str"','string'), array('boolean','boolean','{1,2,3}','array'), array('boolean','boolean','@Name', 'an instance of Drupal\Tests\Component\Annotation\Doctrine\Name'), // alias for internal type boolean array('bool','bool', '1','integer'), array('bool','bool', '1.2','double'), array('bool','bool', '"str"','string'), array('bool','bool', '{"str"}','array'), // integer type array('integer','integer', 'true','boolean'), array('integer','integer', 'false','boolean'), array('integer','integer', '1.2','double'), array('integer','integer', '"str"','string'), array('integer','integer', '{"str"}','array'), array('integer','integer', '{1,2,3,4}','array'), // alias for internal type double array('float','float', 'true','boolean'), array('float','float', 'false','boolean'), array('float','float', '123','integer'), array('float','float', '"str"','string'), array('float','float', '{"str"}','array'), array('float','float', '{12.34}','array'), array('float','float', '{1,2,3}','array'), // string type array('string','string', 'true','boolean'), array('string','string', 'false','boolean'), array('string','string', '12','integer'), array('string','string', '1.2','double'), array('string','string', '{"str"}','array'), array('string','string', '{1,2,3,4}','array'), // annotation instance array('annotation','Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAll', 'true','boolean'), array('annotation','Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAll', 'false','boolean'), array('annotation','Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAll', '12','integer'), array('annotation','Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAll', '1.2','double'), array('annotation','Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAll', '{"str"}','array'), array('annotation','Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAll', '{1,2,3,4}','array'), array('annotation','Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAll', '@Name','an instance of Drupal\Tests\Component\Annotation\Doctrine\Name'), ); } public function getAnnotationVarTypeArrayProviderInvalid() { //({attribute name}, {type declared type}, {attribute value} , {given type or class}) return array( array('arrayOfIntegers', 'integer', 'true', 'boolean'), array('arrayOfIntegers', 'integer', 'false', 'boolean'), array('arrayOfIntegers', 'integer', '{true,true}', 'boolean'), array('arrayOfIntegers', 'integer', '{1,true}', 'boolean'), array('arrayOfIntegers', 'integer', '{1,2,1.2}', 'double'), array('arrayOfIntegers', 'integer', '{1,2,"str"}', 'string'), array('arrayOfStrings', 'string', 'true', 'boolean'), array('arrayOfStrings', 'string', 'false', 'boolean'), array('arrayOfStrings', 'string', '{true,true}', 'boolean'), array('arrayOfStrings', 'string', '{"foo",true}', 'boolean'), array('arrayOfStrings', 'string', '{"foo","bar",1.2}', 'double'), array('arrayOfStrings', 'string', '1', 'integer'), array('arrayOfAnnotations', 'Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAll', 'true', 'boolean'), array('arrayOfAnnotations', 'Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAll', 'false', 'boolean'), array('arrayOfAnnotations', 'Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAll', '{@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAll,true}', 'boolean'), array('arrayOfAnnotations', 'Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAll', '{@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAll,true}', 'boolean'), array('arrayOfAnnotations', 'Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAll', '{@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAll,1.2}', 'double'), array('arrayOfAnnotations', 'Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAll', '{@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAll,@AnnotationExtendsAnnotationTargetAll,"str"}', 'string'), ); } /** * @dataProvider getAnnotationVarTypeProviderValid */ public function testAnnotationWithVarType($attribute, $value) { $parser = $this->createTestParser(); $context = 'property SomeClassName::$invalidProperty.'; $docblock = sprintf('@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithVarType(%s = %s)',$attribute, $value); $parser->setTarget(Target::TARGET_PROPERTY); $result = $parser->parse($docblock, $context); $this->assertTrue(sizeof($result) === 1); $this->assertInstanceOf('Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithVarType', $result[0]); $this->assertNotNull($result[0]->$attribute); } /** * @dataProvider getAnnotationVarTypeProviderInvalid */ public function testAnnotationWithVarTypeError($attribute,$type,$value,$given) { $parser = $this->createTestParser(); $context = 'property SomeClassName::invalidProperty.'; $docblock = sprintf('@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithVarType(%s = %s)',$attribute, $value); $parser->setTarget(Target::TARGET_PROPERTY); try { $parser->parse($docblock, $context); $this->fail(); } catch (\Doctrine\Common\Annotations\AnnotationException $exc) { $this->assertContains("[Type Error] Attribute \"$attribute\" of @Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithVarType declared on property SomeClassName::invalidProperty. expects a(n) $type, but got $given.", $exc->getMessage()); } } /** * @dataProvider getAnnotationVarTypeArrayProviderInvalid */ public function testAnnotationWithVarTypeArrayError($attribute,$type,$value,$given) { $parser = $this->createTestParser(); $context = 'property SomeClassName::invalidProperty.'; $docblock = sprintf('@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithVarType(%s = %s)',$attribute, $value); $parser->setTarget(Target::TARGET_PROPERTY); try { $parser->parse($docblock, $context); $this->fail(); } catch (\Doctrine\Common\Annotations\AnnotationException $exc) { $this->assertContains("[Type Error] Attribute \"$attribute\" of @Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithVarType declared on property SomeClassName::invalidProperty. expects either a(n) $type, or an array of {$type}s, but got $given.", $exc->getMessage()); } } /** * @dataProvider getAnnotationVarTypeProviderValid */ public function testAnnotationWithAttributes($attribute, $value) { $parser = $this->createTestParser(); $context = 'property SomeClassName::$invalidProperty.'; $docblock = sprintf('@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithAttributes(%s = %s)',$attribute, $value); $parser->setTarget(Target::TARGET_PROPERTY); $result = $parser->parse($docblock, $context); $this->assertTrue(sizeof($result) === 1); $this->assertInstanceOf('Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithAttributes', $result[0]); $getter = "get".ucfirst($attribute); $this->assertNotNull($result[0]->$getter()); } /** * @dataProvider getAnnotationVarTypeProviderInvalid */ public function testAnnotationWithAttributesError($attribute,$type,$value,$given) { $parser = $this->createTestParser(); $context = 'property SomeClassName::invalidProperty.'; $docblock = sprintf('@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithAttributes(%s = %s)',$attribute, $value); $parser->setTarget(Target::TARGET_PROPERTY); try { $parser->parse($docblock, $context); $this->fail(); } catch (\Doctrine\Common\Annotations\AnnotationException $exc) { $this->assertContains("[Type Error] Attribute \"$attribute\" of @Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithAttributes declared on property SomeClassName::invalidProperty. expects a(n) $type, but got $given.", $exc->getMessage()); } } /** * @dataProvider getAnnotationVarTypeArrayProviderInvalid */ public function testAnnotationWithAttributesWithVarTypeArrayError($attribute,$type,$value,$given) { $parser = $this->createTestParser(); $context = 'property SomeClassName::invalidProperty.'; $docblock = sprintf('@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithAttributes(%s = %s)',$attribute, $value); $parser->setTarget(Target::TARGET_PROPERTY); try { $parser->parse($docblock, $context); $this->fail(); } catch (\Doctrine\Common\Annotations\AnnotationException $exc) { $this->assertContains("[Type Error] Attribute \"$attribute\" of @Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithAttributes declared on property SomeClassName::invalidProperty. expects either a(n) $type, or an array of {$type}s, but got $given.", $exc->getMessage()); } } public function testAnnotationWithRequiredAttributes() { $parser = $this->createTestParser(); $context = 'property SomeClassName::invalidProperty.'; $parser->setTarget(Target::TARGET_PROPERTY); $docblock = '@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithRequiredAttributes("Some Value", annot = @Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAnnotation)'; $result = $parser->parse($docblock); $this->assertTrue(sizeof($result) === 1); $this->assertInstanceOf('Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithRequiredAttributes', $result[0]); $this->assertEquals("Some Value",$result[0]->getValue()); $this->assertInstanceOf('Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAnnotation', $result[0]->getAnnot()); $docblock = '@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithRequiredAttributes("Some Value")'; try { $result = $parser->parse($docblock,$context); $this->fail(); } catch (\Doctrine\Common\Annotations\AnnotationException $exc) { $this->assertContains('Attribute "annot" of @Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithRequiredAttributes declared on property SomeClassName::invalidProperty. expects a(n) Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAnnotation. This value should not be null.', $exc->getMessage()); } $docblock = '@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithRequiredAttributes(annot = @Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAnnotation)'; try { $result = $parser->parse($docblock,$context); $this->fail(); } catch (\Doctrine\Common\Annotations\AnnotationException $exc) { $this->assertContains('Attribute "value" of @Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithRequiredAttributes declared on property SomeClassName::invalidProperty. expects a(n) string. This value should not be null.', $exc->getMessage()); } } public function testAnnotationWithRequiredAttributesWithoutContructor() { $parser = $this->createTestParser(); $context = 'property SomeClassName::invalidProperty.'; $parser->setTarget(Target::TARGET_PROPERTY); $docblock = '@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithRequiredAttributesWithoutContructor("Some Value", annot = @Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAnnotation)'; $result = $parser->parse($docblock); $this->assertTrue(sizeof($result) === 1); $this->assertInstanceOf('Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithRequiredAttributesWithoutContructor', $result[0]); $this->assertEquals("Some Value", $result[0]->value); $this->assertInstanceOf('Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAnnotation', $result[0]->annot); $docblock = '@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithRequiredAttributesWithoutContructor("Some Value")'; try { $result = $parser->parse($docblock,$context); $this->fail(); } catch (\Doctrine\Common\Annotations\AnnotationException $exc) { $this->assertContains('Attribute "annot" of @Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithRequiredAttributesWithoutContructor declared on property SomeClassName::invalidProperty. expects a(n) Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAnnotation. This value should not be null.', $exc->getMessage()); } $docblock = '@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithRequiredAttributesWithoutContructor(annot = @Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAnnotation)'; try { $result = $parser->parse($docblock,$context); $this->fail(); } catch (\Doctrine\Common\Annotations\AnnotationException $exc) { $this->assertContains('Attribute "value" of @Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithRequiredAttributesWithoutContructor declared on property SomeClassName::invalidProperty. expects a(n) string. This value should not be null.', $exc->getMessage()); } } /** * @expectedException \Doctrine\Common\Annotations\AnnotationException * @expectedExceptionMessage Attribute "value" of @Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationEnum declared on property SomeClassName::invalidProperty. accept only [ONE, TWO, THREE], but got FOUR. */ public function testAnnotationEnumeratorException() { $parser = $this->createTestParser(); $context = 'property SomeClassName::invalidProperty.'; $docblock = '@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationEnum("FOUR")'; $parser->setIgnoreNotImportedAnnotations(false); $parser->setTarget(Target::TARGET_PROPERTY); $parser->parse($docblock, $context); } /** * @expectedException \Doctrine\Common\Annotations\AnnotationException * @expectedExceptionMessage Attribute "value" of @Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationEnumLiteral declared on property SomeClassName::invalidProperty. accept only [AnnotationEnumLiteral::ONE, AnnotationEnumLiteral::TWO, AnnotationEnumLiteral::THREE], but got 4. */ public function testAnnotationEnumeratorLiteralException() { $parser = $this->createTestParser(); $context = 'property SomeClassName::invalidProperty.'; $docblock = '@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationEnumLiteral(4)'; $parser->setIgnoreNotImportedAnnotations(false); $parser->setTarget(Target::TARGET_PROPERTY); $parser->parse($docblock, $context); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage @Enum supports only scalar values "array" given. */ public function testAnnotationEnumInvalidTypeDeclarationException() { $parser = $this->createTestParser(); $docblock = '@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationEnumInvalid("foo")'; $parser->setIgnoreNotImportedAnnotations(false); $parser->parse($docblock); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage Undefined enumerator value "3" for literal "AnnotationEnumLiteral::THREE". */ public function testAnnotationEnumInvalidLiteralDeclarationException() { $parser = $this->createTestParser(); $docblock = '@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationEnumLiteralInvalid("foo")'; $parser->setIgnoreNotImportedAnnotations(false); $parser->parse($docblock); } public function getConstantsProvider() { $provider[] = array( '@AnnotationWithConstants(PHP_EOL)', PHP_EOL ); $provider[] = array( '@AnnotationWithConstants(AnnotationWithConstants::INTEGER)', AnnotationWithConstants::INTEGER ); $provider[] = array( '@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithConstants(AnnotationWithConstants::STRING)', AnnotationWithConstants::STRING ); $provider[] = array( '@AnnotationWithConstants(Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithConstants::FLOAT)', AnnotationWithConstants::FLOAT ); $provider[] = array( '@AnnotationWithConstants(ClassWithConstants::SOME_VALUE)', ClassWithConstants::SOME_VALUE ); $provider[] = array( '@AnnotationWithConstants(ClassWithConstants::OTHER_KEY_)', ClassWithConstants::OTHER_KEY_ ); $provider[] = array( '@AnnotationWithConstants(ClassWithConstants::OTHER_KEY_2)', ClassWithConstants::OTHER_KEY_2 ); $provider[] = array( '@AnnotationWithConstants(Drupal\Tests\Component\Annotation\Doctrine\Fixtures\ClassWithConstants::SOME_VALUE)', ClassWithConstants::SOME_VALUE ); $provider[] = array( '@AnnotationWithConstants(IntefaceWithConstants::SOME_VALUE)', IntefaceWithConstants::SOME_VALUE ); $provider[] = array( '@AnnotationWithConstants(\Drupal\Tests\Component\Annotation\Doctrine\Fixtures\IntefaceWithConstants::SOME_VALUE)', IntefaceWithConstants::SOME_VALUE ); $provider[] = array( '@AnnotationWithConstants({AnnotationWithConstants::STRING, AnnotationWithConstants::INTEGER, AnnotationWithConstants::FLOAT})', array(AnnotationWithConstants::STRING, AnnotationWithConstants::INTEGER, AnnotationWithConstants::FLOAT) ); $provider[] = array( '@AnnotationWithConstants({ AnnotationWithConstants::STRING = AnnotationWithConstants::INTEGER })', array(AnnotationWithConstants::STRING => AnnotationWithConstants::INTEGER) ); $provider[] = array( '@AnnotationWithConstants({ Drupal\Tests\Component\Annotation\Doctrine\Fixtures\IntefaceWithConstants::SOME_KEY = AnnotationWithConstants::INTEGER })', array(IntefaceWithConstants::SOME_KEY => AnnotationWithConstants::INTEGER) ); $provider[] = array( '@AnnotationWithConstants({ \Drupal\Tests\Component\Annotation\Doctrine\Fixtures\IntefaceWithConstants::SOME_KEY = AnnotationWithConstants::INTEGER })', array(IntefaceWithConstants::SOME_KEY => AnnotationWithConstants::INTEGER) ); $provider[] = array( '@AnnotationWithConstants({ AnnotationWithConstants::STRING = AnnotationWithConstants::INTEGER, ClassWithConstants::SOME_KEY = ClassWithConstants::SOME_VALUE, Drupal\Tests\Component\Annotation\Doctrine\Fixtures\ClassWithConstants::SOME_KEY = IntefaceWithConstants::SOME_VALUE })', array( AnnotationWithConstants::STRING => AnnotationWithConstants::INTEGER, ClassWithConstants::SOME_KEY => ClassWithConstants::SOME_VALUE, ClassWithConstants::SOME_KEY => IntefaceWithConstants::SOME_VALUE ) ); $provider[] = array( '@AnnotationWithConstants(AnnotationWithConstants::class)', 'Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithConstants' ); $provider[] = array( '@AnnotationWithConstants({AnnotationWithConstants::class = AnnotationWithConstants::class})', array('Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithConstants' => 'Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithConstants') ); $provider[] = array( '@AnnotationWithConstants(Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithConstants::class)', 'Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithConstants' ); $provider[] = array( '@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithConstants(Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithConstants::class)', 'Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithConstants' ); return $provider; } /** * @dataProvider getConstantsProvider */ public function testSupportClassConstants($docblock, $expected) { $parser = $this->createTestParser(); $parser->setImports(array( 'classwithconstants' => 'Drupal\Tests\Component\Annotation\Doctrine\Fixtures\ClassWithConstants', 'intefacewithconstants' => 'Drupal\Tests\Component\Annotation\Doctrine\Fixtures\IntefaceWithConstants', 'annotationwithconstants' => 'Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithConstants' )); $result = $parser->parse($docblock); $this->assertInstanceOf('\Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithConstants', $annotation = $result[0]); $this->assertEquals($expected, $annotation->value); } /** * @expectedException \Doctrine\Common\Annotations\AnnotationException * @expectedExceptionMessage The annotation @SomeAnnotationClassNameWithoutConstructorAndProperties declared on does not accept any values, but got {"value":"Foo"}. */ public function testWithoutConstructorWhenIsNotDefaultValue() { $parser = $this->createTestParser(); $docblock = <<<DOCBLOCK /** * @SomeAnnotationClassNameWithoutConstructorAndProperties("Foo") */ DOCBLOCK; $parser->setTarget(Target::TARGET_CLASS); $parser->parse($docblock); } /** * @expectedException \Doctrine\Common\Annotations\AnnotationException * @expectedExceptionMessage The annotation @SomeAnnotationClassNameWithoutConstructorAndProperties declared on does not accept any values, but got {"value":"Foo"}. */ public function testWithoutConstructorWhenHasNoProperties() { $parser = $this->createTestParser(); $docblock = <<<DOCBLOCK /** * @SomeAnnotationClassNameWithoutConstructorAndProperties(value = "Foo") */ DOCBLOCK; $parser->setTarget(Target::TARGET_CLASS); $parser->parse($docblock); } /** * @expectedException \Doctrine\Common\Annotations\AnnotationException * @expectedExceptionMessage Expected namespace separator or identifier, got ')' at position 24 in class @Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithTargetSyntaxError. */ public function testAnnotationTargetSyntaxError() { $parser = $this->createTestParser(); $context = 'class ' . 'SomeClassName'; $docblock = <<<DOCBLOCK /** * @Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithTargetSyntaxError() */ DOCBLOCK; $parser->setTarget(Target::TARGET_CLASS); $parser->parse($docblock,$context); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage Invalid Target "Foo". Available targets: [ALL, CLASS, METHOD, PROPERTY, ANNOTATION] */ public function testAnnotationWithInvalidTargetDeclarationError() { $parser = $this->createTestParser(); $context = 'class ' . 'SomeClassName'; $docblock = <<<DOCBLOCK /** * @AnnotationWithInvalidTargetDeclaration() */ DOCBLOCK; $parser->setTarget(Target::TARGET_CLASS); $parser->parse($docblock,$context); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage @Target expects either a string value, or an array of strings, "NULL" given. */ public function testAnnotationWithTargetEmptyError() { $parser = $this->createTestParser(); $context = 'class ' . 'SomeClassName'; $docblock = <<<DOCBLOCK /** * @AnnotationWithTargetEmpty() */ DOCBLOCK; $parser->setTarget(Target::TARGET_CLASS); $parser->parse($docblock,$context); } /** * @group DDC-575 */ public function testRegressionDDC575() { $parser = $this->createTestParser(); $docblock = <<<DOCBLOCK /** * @Name * * Will trigger error. */ DOCBLOCK; $result = $parser->parse($docblock); $this->assertInstanceOf("Drupal\Tests\Component\Annotation\Doctrine\Name", $result[0]); $docblock = <<<DOCBLOCK /** * @Name * @Marker * * Will trigger error. */ DOCBLOCK; $result = $parser->parse($docblock); $this->assertInstanceOf("Drupal\Tests\Component\Annotation\Doctrine\Name", $result[0]); } /** * @group DDC-77 */ public function testAnnotationWithoutClassIsIgnoredWithoutWarning() { $parser = new DocParser(); $parser->setIgnoreNotImportedAnnotations(true); $result = $parser->parse("@param"); $this->assertEquals(0, count($result)); } /** * @group DCOM-168 */ public function testNotAnAnnotationClassIsIgnoredWithoutWarning() { $parser = new DocParser(); $parser->setIgnoreNotImportedAnnotations(true); $parser->setIgnoredAnnotationNames(array('PHPUnit_Framework_TestCase' => true)); $result = $parser->parse('@PHPUnit_Framework_TestCase'); $this->assertEquals(0, count($result)); } /** * @expectedException \Doctrine\Common\Annotations\AnnotationException * @expectedExceptionMessage Expected PlainValue, got ''' at position 10. */ public function testAnnotationDontAcceptSingleQuotes() { $parser = $this->createTestParser(); $parser->parse("@Name(foo='bar')"); } /** * @group DCOM-41 */ public function testAnnotationDoesntThrowExceptionWhenAtSignIsNotFollowedByIdentifier() { $parser = new DocParser(); $result = $parser->parse("'@'"); $this->assertEquals(0, count($result)); } /** * @group DCOM-41 * @expectedException \Doctrine\Common\Annotations\AnnotationException */ public function testAnnotationThrowsExceptionWhenAtSignIsNotFollowedByIdentifierInNestedAnnotation() { $parser = new DocParser(); $parser->parse("@Drupal\Tests\Component\Annotation\Doctrine\Name(@')"); } /** * @group DCOM-56 */ public function testAutoloadAnnotation() { $this->assertFalse(class_exists('Drupal\Tests\Component\Annotation\Doctrine\Fixture\Annotation\Autoload', false), 'Pre-condition: Drupal\Tests\Component\Annotation\Doctrine\Fixture\Annotation\Autoload not allowed to be loaded.'); $parser = new DocParser(); AnnotationRegistry::registerAutoloadNamespace('Drupal\Tests\Component\Annotation\Doctrine\Fixtures\Annotation', __DIR__ . '/../../../../'); $parser->setImports(array( 'autoload' => 'Drupal\Tests\Component\Annotation\Doctrine\Fixtures\Annotation\Autoload', )); $annotations = $parser->parse('@Autoload'); $this->assertEquals(1, count($annotations)); $this->assertInstanceOf('Drupal\Tests\Component\Annotation\Doctrine\Fixtures\Annotation\Autoload', $annotations[0]); } public function createTestParser() { $parser = new DocParser(); $parser->setIgnoreNotImportedAnnotations(true); $parser->setImports(array( 'name' => 'Drupal\Tests\Component\Annotation\Doctrine\Name', '__NAMESPACE__' => 'Drupal\Tests\Component\Annotation\Doctrine', )); return $parser; } /** * @group DDC-78 * @expectedException \Doctrine\Common\Annotations\AnnotationException * @expectedExceptionMessage Expected PlainValue, got ''' at position 10 in class \Drupal\Tests\Component\Annotation\Doctrine\Name */ public function testSyntaxErrorWithContextDescription() { $parser = $this->createTestParser(); $parser->parse("@Name(foo='bar')", "class \Drupal\Tests\Component\Annotation\Doctrine\Name"); } /** * @group DDC-183 */ public function testSyntaxErrorWithUnknownCharacters() { $docblock = <<<DOCBLOCK /** * @test at. */ class A { } DOCBLOCK; //$lexer = new \Doctrine\Common\Annotations\Lexer(); //$lexer->setInput(trim($docblock, '/ *')); //var_dump($lexer); try { $parser = $this->createTestParser(); $result = $parser->parse($docblock); $this->assertTrue(is_array($result) && empty($result)); } catch (\Exception $e) { $this->fail($e->getMessage()); } } /** * @group DCOM-14 */ public function testIgnorePHPDocThrowTag() { $docblock = <<<DOCBLOCK /** * @throws \RuntimeException */ class A { } DOCBLOCK; try { $parser = $this->createTestParser(); $result = $parser->parse($docblock); $this->assertTrue(is_array($result) && empty($result)); } catch (\Exception $e) { $this->fail($e->getMessage()); } } /** * @group DCOM-38 */ public function testCastInt() { $parser = $this->createTestParser(); $result = $parser->parse("@Name(foo=1234)"); $annot = $result[0]; $this->assertInternalType('int', $annot->foo); } /** * @group DCOM-38 */ public function testCastNegativeInt() { $parser = $this->createTestParser(); $result = $parser->parse("@Name(foo=-1234)"); $annot = $result[0]; $this->assertInternalType('int', $annot->foo); } /** * @group DCOM-38 */ public function testCastFloat() { $parser = $this->createTestParser(); $result = $parser->parse("@Name(foo=1234.345)"); $annot = $result[0]; $this->assertInternalType('float', $annot->foo); } /** * @group DCOM-38 */ public function testCastNegativeFloat() { $parser = $this->createTestParser(); $result = $parser->parse("@Name(foo=-1234.345)"); $annot = $result[0]; $this->assertInternalType('float', $annot->foo); $result = $parser->parse("@Marker(-1234.345)"); $annot = $result[0]; $this->assertInternalType('float', $annot->value); } public function testReservedKeywordsInAnnotations() { if (PHP_VERSION_ID >= 70000) { $this->markTestSkipped('This test requires PHP 5.6 or lower.'); } require 'ReservedKeywordsClasses.php'; $parser = $this->createTestParser(); $result = $parser->parse('@Drupal\Tests\Component\Annotation\Doctrine\True'); $this->assertTrue($result[0] instanceof True); $result = $parser->parse('@Drupal\Tests\Component\Annotation\Doctrine\False'); $this->assertTrue($result[0] instanceof False); $result = $parser->parse('@Drupal\Tests\Component\Annotation\Doctrine\Null'); $this->assertTrue($result[0] instanceof Null); $result = $parser->parse('@True'); $this->assertTrue($result[0] instanceof True); $result = $parser->parse('@False'); $this->assertTrue($result[0] instanceof False); $result = $parser->parse('@Null'); $this->assertTrue($result[0] instanceof Null); } /** * @expectedException \Doctrine\Common\Annotations\AnnotationException * @expectedExceptionMessage [Creation Error] The annotation @SomeAnnotationClassNameWithoutConstructor declared on some class does not have a property named "invalidaProperty". Available properties: data, name */ public function testSetValuesExeption() { $docblock = <<<DOCBLOCK /** * @SomeAnnotationClassNameWithoutConstructor(invalidaProperty = "Some val") */ DOCBLOCK; $this->createTestParser()->parse($docblock, 'some class'); } /** * @expectedException \Doctrine\Common\Annotations\AnnotationException * @expectedExceptionMessage [Syntax Error] Expected Doctrine\Common\Annotations\DocLexer::T_IDENTIFIER or Doctrine\Common\Annotations\DocLexer::T_TRUE or Doctrine\Common\Annotations\DocLexer::T_FALSE or Doctrine\Common\Annotations\DocLexer::T_NULL, got '3.42' at position 5. */ public function testInvalidIdentifierInAnnotation() { $parser = $this->createTestParser(); $parser->parse('@Foo\3.42'); } public function testTrailingCommaIsAllowed() { $parser = $this->createTestParser(); $annots = $parser->parse('@Name({ "Foo", "Bar", })'); $this->assertEquals(1, count($annots)); $this->assertEquals(array('Foo', 'Bar'), $annots[0]->value); } public function testDefaultAnnotationValueIsNotOverwritten() { $parser = $this->createTestParser(); $annots = $parser->parse('@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\Annotation\AnnotWithDefaultValue'); $this->assertEquals(1, count($annots)); $this->assertEquals('bar', $annots[0]->foo); } public function testArrayWithColon() { $parser = $this->createTestParser(); $annots = $parser->parse('@Name({"foo": "bar"})'); $this->assertEquals(1, count($annots)); $this->assertEquals(array('foo' => 'bar'), $annots[0]->value); } /** * @expectedException \Doctrine\Common\Annotations\AnnotationException * @expectedExceptionMessage [Semantical Error] Couldn't find constant foo. */ public function testInvalidContantName() { $parser = $this->createTestParser(); $parser->parse('@Name(foo: "bar")'); } /** * Tests parsing empty arrays. */ public function testEmptyArray() { $parser = $this->createTestParser(); $annots = $parser->parse('@Name({"foo": {}})'); $this->assertEquals(1, count($annots)); $this->assertEquals(array('foo' => array()), $annots[0]->value); } public function testKeyHasNumber() { $parser = $this->createTestParser(); $annots = $parser->parse('@SettingsAnnotation(foo="test", bar2="test")'); $this->assertEquals(1, count($annots)); $this->assertEquals(array('foo' => 'test', 'bar2' => 'test'), $annots[0]->settings); } /** * @group 44 */ public function testSupportsEscapedQuotedValues() { $result = $this->createTestParser()->parse('@Drupal\Tests\Component\Annotation\Doctrine\Name(foo="""bar""")'); $this->assertCount(1, $result); $this->assertTrue($result[0] instanceof Name); $this->assertEquals('"bar"', $result[0]->foo); } } /** @Annotation */ class SettingsAnnotation { public $settings; public function __construct($settings) { $this->settings = $settings; } } /** @Annotation */ class SomeAnnotationClassNameWithoutConstructor { public $data; public $name; } /** @Annotation */ class SomeAnnotationWithConstructorWithoutParams { function __construct() { $this->data = "Some data"; } public $data; public $name; } /** @Annotation */ class SomeAnnotationClassNameWithoutConstructorAndProperties{} /** * @Annotation * @Target("Foo") */ class AnnotationWithInvalidTargetDeclaration{} /** * @Annotation * @Target */ class AnnotationWithTargetEmpty{} /** @Annotation */ class AnnotationExtendsAnnotationTargetAll extends \Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAll { } /** @Annotation */ class Name extends \Doctrine\Common\Annotations\Annotation { public $foo; } /** @Annotation */ class Marker { public $value; } namespace Drupal\Tests\Component\Annotation\Doctrine\FooBar; /** @Annotation */ class Name extends \Doctrine\Common\Annotations\Annotation { }
Java
/* * Copyright (C) 2013-2015 DeathCore <http://www.noffearrdeathproject.net/> * Copyright (C) 2005-2011 MaNGOS <http://getmangos.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. * * 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 "MovementPacketBuilder.h" #include "MoveSpline.h" #include "ByteBuffer.h" namespace Movement { inline void operator << (ByteBuffer& b, const Vector3& v) { b << v.x << v.y << v.z; } inline void operator >> (ByteBuffer& b, Vector3& v) { b >> v.x >> v.y >> v.z; } enum MonsterMoveType { MonsterMoveNormal = 0, MonsterMoveStop = 1, MonsterMoveFacingSpot = 2, MonsterMoveFacingTarget = 3, MonsterMoveFacingAngle = 4 }; void PacketBuilder::WriteCommonMonsterMovePart(const MoveSpline& move_spline, ByteBuffer& data) { MoveSplineFlag splineflags = move_spline.splineflags; data << uint8(0); // sets/unsets MOVEMENTFLAG2_UNK7 (0x40) data << move_spline.spline.getPoint(move_spline.spline.first()); data << move_spline.GetId(); switch (splineflags & MoveSplineFlag::Mask_Final_Facing) { case MoveSplineFlag::Final_Target: data << uint8(MonsterMoveFacingTarget); data << move_spline.facing.target; break; case MoveSplineFlag::Final_Angle: data << uint8(MonsterMoveFacingAngle); data << move_spline.facing.angle; break; case MoveSplineFlag::Final_Point: data << uint8(MonsterMoveFacingSpot); data << move_spline.facing.f.x << move_spline.facing.f.y << move_spline.facing.f.z; break; default: data << uint8(MonsterMoveNormal); break; } // add fake Enter_Cycle flag - needed for client-side cyclic movement (client will erase first spline vertex after first cycle done) splineflags.enter_cycle = move_spline.isCyclic(); data << uint32(splineflags & uint32(~MoveSplineFlag::Mask_No_Monster_Move)); if (splineflags.animation) { data << splineflags.getAnimationId(); data << move_spline.effect_start_time; } data << move_spline.Duration(); if (splineflags.parabolic) { data << move_spline.vertical_acceleration; data << move_spline.effect_start_time; } } void PacketBuilder::WriteStopMovement(Vector3 const& pos, uint32 splineId, ByteBuffer& data) { data << uint8(0); // sets/unsets MOVEMENTFLAG2_UNK7 (0x40) data << pos; data << splineId; data << uint8(MonsterMoveStop); } void WriteLinearPath(const Spline<int32>& spline, ByteBuffer& data) { uint32 last_idx = spline.getPointCount() - 3; const Vector3 * real_path = &spline.getPoint(1); data << last_idx; data << real_path[last_idx]; // destination if (last_idx > 1) { Vector3 middle = (real_path[0] + real_path[last_idx]) / 2.f; Vector3 offset; // first and last points already appended for (uint32 i = 1; i < last_idx; ++i) { offset = middle - real_path[i]; data.appendPackXYZ(offset.x, offset.y, offset.z); } } } void WriteCatmullRomPath(const Spline<int32>& spline, ByteBuffer& data) { uint32 count = spline.getPointCount() - 3; data << count; data.append<Vector3>(&spline.getPoint(2), count); } void WriteCatmullRomCyclicPath(const Spline<int32>& spline, ByteBuffer& data) { uint32 count = spline.getPointCount() - 3; data << uint32(count + 1); data << spline.getPoint(1); // fake point, client will erase it from the spline after first cycle done data.append<Vector3>(&spline.getPoint(1), count); } void PacketBuilder::WriteMonsterMove(const MoveSpline& move_spline, ByteBuffer& data) { WriteCommonMonsterMovePart(move_spline, data); const Spline<int32>& spline = move_spline.spline; MoveSplineFlag splineflags = move_spline.splineflags; if (splineflags & MoveSplineFlag::Mask_CatmullRom) { if (splineflags.cyclic) WriteCatmullRomCyclicPath(spline, data); else WriteCatmullRomPath(spline, data); } else WriteLinearPath(spline, data); } void PacketBuilder::WriteCreate(const MoveSpline& move_spline, ByteBuffer& data) { //WriteClientStatus(mov, data); //data.append<float>(&mov.m_float_values[SpeedWalk], SpeedMaxCount); //if (mov.SplineEnabled()) { MoveSplineFlag const& splineFlags = move_spline.splineflags; data << splineFlags.raw(); if (splineFlags.final_angle) { data << move_spline.facing.angle; } else if (splineFlags.final_target) { data << move_spline.facing.target; } else if (splineFlags.final_point) { data << move_spline.facing.f.x << move_spline.facing.f.y << move_spline.facing.f.z; } data << move_spline.timePassed(); data << move_spline.Duration(); data << move_spline.GetId(); data << float(1.f); // splineInfo.duration_mod; added in 3.1 data << float(1.f); // splineInfo.duration_mod_next; added in 3.1 data << move_spline.vertical_acceleration; // added in 3.1 data << move_spline.effect_start_time; // added in 3.1 uint32 nodes = move_spline.getPath().size(); data << nodes; data.append<Vector3>(&move_spline.getPath()[0], nodes); data << uint8(move_spline.spline.mode()); // added in 3.1 data << (move_spline.isCyclic() ? Vector3::zero() : move_spline.FinalDestination()); } } }
Java
/* * Copyright (C) 2012 Spreadtrum Communications Inc. * * This software is licensed under the terms of the GNU General Public * License version 2, as published by the Free Software Foundation, and * may be copied, distributed, and modified under those terms. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #include <linux/kernel.h> #include <linux/init.h> #include <linux/platform_device.h> #include <asm/io.h> #include <asm/setup.h> #include <asm/mach/time.h> #include <asm/mach/arch.h> #include <asm/mach-types.h> #include <asm/hardware/gic.h> #include <asm/hardware/cache-l2x0.h> #include <asm/localtimer.h> #include <mach/hardware.h> #include <linux/i2c.h> #include <linux/i2c/ft5306_ts.h> #include <linux/i2c/lis3dh.h> #include <linux/i2c/ltr_558als.h> #include <linux/akm8975.h> #include <linux/spi/spi.h> #include <mach/board.h> #include <mach/serial_sprd.h> #include <mach/adi.h> #include <mach/adc.h> #include "../devices.h" #include <linux/gpio.h> #include <linux/mpu.h> #include <linux/akm8975.h> #include <linux/irq.h> #include <mach/sci.h> #include <mach/hardware.h> #include <mach/regs_glb.h> #include <mach/regs_ahb.h> #include <mach/pinmap.h> /* IRQ's for the multi sensor board */ #define MPUIRQ_GPIO 212 extern void __init sc8825_reserve(void); extern void __init sci_map_io(void); extern void __init sc8825_init_irq(void); extern void __init sc8825_timer_init(void); extern int __init sc8825_regulator_init(void); extern int __init sci_clock_init(void); #ifdef CONFIG_ANDROID_RAM_CONSOLE extern int __init sprd_ramconsole_init(void); #endif static struct platform_device rfkill_device; static struct platform_device kb_backlight_device; static struct platform_device *devices[] __initdata = { &sprd_serial_device0, &sprd_serial_device1, &sprd_serial_device2, &sprd_device_rtc, &sprd_nand_device, &sprd_lcd_device0, &sprd_backlight_device, &sprd_i2c_device0, &sprd_i2c_device1, &sprd_i2c_device2, &sprd_i2c_device3, &sprd_spi0_device, &sprd_spi1_device, &sprd_spi2_device, &sprd_keypad_device, &sprd_audio_platform_pcm_device, &sprd_audio_cpu_dai_vaudio_device, &sprd_audio_cpu_dai_vbc_device, &sprd_audio_codec_sprd_codec_device, &sprd_audio_cpu_dai_i2s_device, &sprd_audio_cpu_dai_i2s_device1, &sprd_audio_codec_null_codec_device, &sprd_battery_device, #ifdef CONFIG_ANDROID_PMEM &sprd_pmem_device, &sprd_pmem_adsp_device, #endif #ifdef CONFIG_ION &sprd_ion_dev, #endif &sprd_emmc_device, &sprd_sdio0_device, &sprd_sdio1_device, &sprd_sdio2_device, &sprd_vsp_device, &sprd_dcam_device, &sprd_scale_device, &sprd_rotation_device, &sprd_sensor_device, &sprd_isp_device, &sprd_ahb_bm0_device, &sprd_ahb_bm1_device, &sprd_ahb_bm2_device, &sprd_ahb_bm3_device, &sprd_ahb_bm4_device, &sprd_axi_bm0_device, &sprd_axi_bm1_device, &sprd_axi_bm2_device, #ifdef CONFIG_SIPC &sprd_cproc_td_device, &sprd_spipe_td_device, &sprd_slog_td_device, &sprd_stty_td_device, #endif &kb_backlight_device, &rfkill_device, }; /* RFKILL */ static struct resource rfkill_resources[] = { { .name = "bt_reset", .start = GPIO_BT_RESET, .end = GPIO_BT_RESET, .flags = IORESOURCE_IO, }, }; static struct platform_device rfkill_device = { .name = "rfkill", .id = -1, .num_resources = ARRAY_SIZE(rfkill_resources), .resource = rfkill_resources, }; /* keypad backlight */ static struct platform_device kb_backlight_device = { .name = "keyboard-backlight", .id = -1, }; static struct sys_timer sc8825_timer = { .init = sc8825_timer_init, }; static int calibration_mode = false; static int __init calibration_start(char *str) { if(str) pr_info("modem calibartion:%s\n", str); calibration_mode = true; return 1; } __setup("calibration=", calibration_start); int in_calibration(void) { return (calibration_mode == true); } EXPORT_SYMBOL(in_calibration); static void __init sprd_add_otg_device(void) { /* * if in calibrtaion mode, we do nothing, modem will handle everything */ if (calibration_mode) return; platform_device_register(&sprd_otg_device); } static struct serial_data plat_data0 = { .wakeup_type = BT_RTS_HIGH_WHEN_SLEEP, .clk = 48000000, }; static struct serial_data plat_data1 = { .wakeup_type = BT_RTS_HIGH_WHEN_SLEEP, .clk = 26000000, }; static struct serial_data plat_data2 = { .wakeup_type = BT_RTS_HIGH_WHEN_SLEEP, .clk = 26000000, }; static struct ft5x0x_ts_platform_data ft5x0x_ts_info = { .irq_gpio_number = GPIO_TOUCH_IRQ, .reset_gpio_number = GPIO_TOUCH_RESET, .vdd_name = "vdd28", }; static struct ltr558_pls_platform_data ltr558_pls_info = { .irq_gpio_number = GPIO_PLSENSOR_IRQ, }; static struct lis3dh_acc_platform_data lis3dh_plat_data = { .poll_interval = 10, .min_interval = 10, .g_range = LIS3DH_ACC_G_2G, .axis_map_x = 1, .axis_map_y = 0, .axis_map_z = 2, .negate_x = 0, .negate_y = 0, .negate_z = 1 }; struct akm8975_platform_data akm8975_platform_d = { .mag_low_x = -20480, .mag_high_x = 20479, .mag_low_y = -20480, .mag_high_y = 20479, .mag_low_z = -20480, .mag_high_z = 20479, }; static struct mpu_platform_data mpu9150_platform_data = { .int_config = 0x00, .level_shifter = 0, .orientation = { -1, 0, 0, 0, -1, 0, 0, 0, +1 }, .sec_slave_type = SECONDARY_SLAVE_TYPE_COMPASS, .sec_slave_id = COMPASS_ID_AK8963, .secondary_i2c_addr = 0x0C, .secondary_orientation = { 0, -1, 0, 1, 0, 0, 0, 0, 1 }, .key = {0xec, 0x06, 0x17, 0xdf, 0x77, 0xfc, 0xe6, 0xac, 0x7b, 0x6f, 0x12, 0x8a, 0x1d, 0x63, 0x67, 0x37}, }; static struct i2c_board_info i2c2_boardinfo[] = { { I2C_BOARD_INFO(LIS3DH_ACC_I2C_NAME, LIS3DH_ACC_I2C_ADDR), .platform_data = &lis3dh_plat_data, }, { I2C_BOARD_INFO("mpu9150", 0x68), .irq = MPUIRQ_GPIO, .platform_data = &mpu9150_platform_data, }, { I2C_BOARD_INFO(LTR558_I2C_NAME, LTR558_I2C_ADDR), .platform_data = &ltr558_pls_info, }, { I2C_BOARD_INFO("BEKEN_FM", 0x70), }, /* { I2C_BOARD_INFO(AKM8975_I2C_NAME, AKM8975_I2C_ADDR), .platform_data = &akm8975_platform_d, },*/ }; static struct i2c_board_info i2c1_boardinfo[] = { {I2C_BOARD_INFO("sensor_main",0x3C),}, {I2C_BOARD_INFO("sensor_sub",0x21),}, }; static struct i2c_board_info i2c0_boardinfo[] = { { I2C_BOARD_INFO(FT5206_TS_DEVICE, FT5206_TS_ADDR), .platform_data = &ft5x0x_ts_info, }, }; static int sc8810_add_i2c_devices(void) { i2c_register_board_info(2, i2c2_boardinfo, ARRAY_SIZE(i2c2_boardinfo)); i2c_register_board_info(1, i2c1_boardinfo, ARRAY_SIZE(i2c1_boardinfo)); i2c_register_board_info(0, i2c0_boardinfo, ARRAY_SIZE(i2c0_boardinfo)); return 0; } struct platform_device audio_pa_amplifier_device = { .name = "speaker-pa", .id = -1, }; static int audio_pa_amplifier_l(u32 cmd, void *data) { int ret = 0; if (cmd < 0) { /* get speaker amplifier status : enabled or disabled */ ret = 0; } else { /* set speaker amplifier */ } return ret; } const char * sc8825_regulator_map[] = { /*supply source, consumer0, consumer1, ..., NULL */ "vdd28", "iic_vdd", "ctp_vdd", NULL, "vddsd0", "tflash_vcc", NULL, "vddsim0", "nfc_vcc", NULL, "vddsim1", "sim_vcc", NULL, NULL, }; int __init sc8825_regulator_init(void) { static struct platform_device sc8825_regulator_device = { .name = "sprd-regulator", .id = -1, .dev = {.platform_data = sc8825_regulator_map}, }; return platform_device_register(&sc8825_regulator_device); } int __init sc8825_clock_init_early(void) { /* FIXME: Force disable all unused clocks */ sci_glb_clr(REG_AHB_AHB_CTL0, BIT_AXIBUSMON2_EB | BIT_AXIBUSMON1_EB | BIT_AXIBUSMON0_EB | // BIT_EMC_EB | // BIT_AHB_ARCH_EB | // BIT_SPINLOCK_EB | BIT_SDIO2_EB | BIT_EMMC_EB | // BIT_DISPC_EB | BIT_G3D_EB | BIT_SDIO1_EB | BIT_DRM_EB | BIT_BUSMON4_EB | BIT_BUSMON3_EB | BIT_BUSMON2_EB | BIT_ROT_EB | BIT_VSP_EB | BIT_ISP_EB | BIT_BUSMON1_EB | BIT_DCAM_MIPI_EB | BIT_CCIR_EB | BIT_NFC_EB | BIT_BUSMON0_EB | // BIT_DMA_EB | // BIT_USBD_EB | BIT_SDIO0_EB | // BIT_LCDC_EB | BIT_CCIR_IN_EB | BIT_DCAM_EB | 0); sci_glb_clr(REG_AHB_AHB_CTL2, // BIT_DISPMTX_CLK_EN | BIT_MMMTX_CLK_EN | // BIT_DISPC_CORE_CLK_EN| // BIT_LCDC_CORE_CLK_EN| BIT_ISP_CORE_CLK_EN | BIT_VSP_CORE_CLK_EN | BIT_DCAM_CORE_CLK_EN| 0); sci_glb_clr(REG_AHB_AHB_CTL3, // BIT_CLK_ULPI_EN | // BIT_CLK_USB_REF_EN | 0); sci_glb_clr(REG_GLB_GEN0, BIT_IC3_EB | BIT_IC2_EB | BIT_IC1_EB | // BIT_RTC_TMR_EB | // BIT_RTC_SYST0_EB | BIT_RTC_KPD_EB | BIT_IIS1_EB | // BIT_RTC_EIC_EB | BIT_UART2_EB | // BIT_UART1_EB | BIT_UART0_EB | // BIT_SYST0_EB | BIT_SPI1_EB | BIT_SPI0_EB | // BIT_SIM1_EB | // BIT_EPT_EB | BIT_CCIR_MCLK_EN | // BIT_PINREG_EB | BIT_IIS0_EB | // BIT_MCU_DSP_RST | // BIT_EIC_EB | BIT_KPD_EB | BIT_EFUSE_EB | // BIT_ADI_EB | // BIT_GPIO_EB | BIT_I2C0_EB | // BIT_SIM0_EB | // BIT_TMR_EB | BIT_SPI2_EB | BIT_UART3_EB | 0); sci_glb_clr(REG_AHB_CA5_CFG, // BIT_CA5_CLK_DBG_EN | 0); sci_glb_clr(REG_GLB_GEN1, BIT_AUDIF_AUTO_EN | BIT_VBC_EN | BIT_AUD_TOP_EB | BIT_AUD_IF_EB | BIT_CLK_AUX1_EN | BIT_CLK_AUX0_EN | 0); sci_glb_clr(REG_GLB_CLK_EN, BIT_PWM3_EB | //BIT_PWM2_EB | BIT_PWM1_EB | // BIT_PWM0_EB | 0); sci_glb_clr(REG_GLB_PCTRL, // BIT_MCU_MPLL_EN | // BIT_MCU_TDPLL_EN | // BIT_MCU_DPLL_EN | BIT_MCU_GPLL_EN); /* clk_gpu */ sci_glb_set(REG_GLB_TD_PLL_CTL, // BIT_TDPLL_DIV2OUT_FORCE_PD | /* clk_384m */ // BIT_TDPLL_DIV3OUT_FORCE_PD | /* clk_256m */ // BIT_TDPLL_DIV4OUT_FORCE_PD | /* clk_192m */ // BIT_TDPLL_DIV5OUT_FORCE_PD | /* clk_153p6m */ 0); printk("sc8825 clock module early init ok\n"); return 0; } static void __init sc8825_init_machine(void) { #ifdef CONFIG_ANDROID_RAM_CONSOLE sprd_ramconsole_init(); #endif sci_adc_init((void __iomem *)ADC_BASE); sc8825_regulator_init(); sprd_add_otg_device(); platform_device_add_data(&sprd_serial_device0,(const void*)&plat_data0,sizeof(plat_data0)); platform_device_add_data(&sprd_serial_device1,(const void*)&plat_data1,sizeof(plat_data1)); platform_device_add_data(&sprd_serial_device2,(const void*)&plat_data2,sizeof(plat_data2)); platform_add_devices(devices, ARRAY_SIZE(devices)); sc8810_add_i2c_devices(); } extern void sc8825_enable_timer_early(void); static void __init sc8825_init_early(void) { /* earlier init request than irq and timer */ sc8825_clock_init_early(); sc8825_enable_timer_early(); sci_adi_init(); } /* * Setup the memory banks. */ static void __init sc8825_fixup(struct machine_desc *desc, struct tag *tags, char **cmdline, struct meminfo *mi) { } MACHINE_START(SC8825OPENPHONE, "sc8825") .reserve = sc8825_reserve, .map_io = sci_map_io, .fixup = sc8825_fixup, .init_early = sc8825_init_early, .init_irq = sc8825_init_irq, .timer = &sc8825_timer, .init_machine = sc8825_init_machine, MACHINE_END
Java
/* * Secure Digital Host Controller Interface ACPI driver. * * Copyright (c) 2012, Intel Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #include <linux/init.h> #include <linux/export.h> #include <linux/module.h> #include <linux/device.h> #include <linux/platform_device.h> #include <linux/ioport.h> #include <linux/io.h> #include <linux/dma-mapping.h> #include <linux/compiler.h> #include <linux/stddef.h> #include <linux/bitops.h> #include <linux/types.h> #include <linux/err.h> #include <linux/gpio/consumer.h> #include <linux/interrupt.h> #include <linux/acpi.h> #include <linux/pm.h> #include <linux/pm_runtime.h> #include <linux/delay.h> #include <linux/mmc/host.h> #include <linux/mmc/pm.h> #include <linux/mmc/sdhci.h> #include "sdhci.h" enum { SDHCI_ACPI_SD_CD = BIT(0), SDHCI_ACPI_RUNTIME_PM = BIT(1), }; struct sdhci_acpi_chip { const struct sdhci_ops *ops; unsigned int quirks; unsigned int quirks2; unsigned long caps; unsigned int caps2; mmc_pm_flag_t pm_caps; }; struct sdhci_acpi_slot { const struct sdhci_acpi_chip *chip; unsigned int quirks; unsigned int quirks2; unsigned long caps; unsigned int caps2; mmc_pm_flag_t pm_caps; unsigned int flags; }; struct sdhci_acpi_host { struct sdhci_host *host; const struct sdhci_acpi_slot *slot; struct platform_device *pdev; bool use_runtime_pm; }; static inline bool sdhci_acpi_flag(struct sdhci_acpi_host *c, unsigned int flag) { return c->slot && (c->slot->flags & flag); } static int sdhci_acpi_enable_dma(struct sdhci_host *host) { return 0; } static void sdhci_acpi_int_hw_reset(struct sdhci_host *host) { u8 reg; reg = sdhci_readb(host, SDHCI_POWER_CONTROL); reg |= 0x10; sdhci_writeb(host, reg, SDHCI_POWER_CONTROL); /* For eMMC, minimum is 1us but give it 9us for good measure */ udelay(9); reg &= ~0x10; sdhci_writeb(host, reg, SDHCI_POWER_CONTROL); /* For eMMC, minimum is 200us but give it 300us for good measure */ usleep_range(300, 1000); } static const struct sdhci_ops sdhci_acpi_ops_dflt = { .enable_dma = sdhci_acpi_enable_dma, }; static const struct sdhci_ops sdhci_acpi_ops_int = { .enable_dma = sdhci_acpi_enable_dma, .hw_reset = sdhci_acpi_int_hw_reset, }; static const struct sdhci_acpi_chip sdhci_acpi_chip_int = { .ops = &sdhci_acpi_ops_int, }; static const struct sdhci_acpi_slot sdhci_acpi_slot_int_emmc = { .chip = &sdhci_acpi_chip_int, .caps = MMC_CAP_8_BIT_DATA | MMC_CAP_NONREMOVABLE | MMC_CAP_HW_RESET, .caps2 = MMC_CAP2_HC_ERASE_SZ, .flags = SDHCI_ACPI_RUNTIME_PM, }; static const struct sdhci_acpi_slot sdhci_acpi_slot_int_sdio = { .quirks2 = SDHCI_QUIRK2_HOST_OFF_CARD_ON, .caps = MMC_CAP_NONREMOVABLE | MMC_CAP_POWER_OFF_CARD, .flags = SDHCI_ACPI_RUNTIME_PM, .pm_caps = MMC_PM_KEEP_POWER, }; static const struct sdhci_acpi_slot sdhci_acpi_slot_int_sd = { .flags = SDHCI_ACPI_SD_CD | SDHCI_ACPI_RUNTIME_PM, .quirks2 = SDHCI_QUIRK2_CARD_ON_NEEDS_BUS_ON, }; struct sdhci_acpi_uid_slot { const char *hid; const char *uid; const struct sdhci_acpi_slot *slot; }; static const struct sdhci_acpi_uid_slot sdhci_acpi_uids[] = { { "80860F14" , "1" , &sdhci_acpi_slot_int_emmc }, { "80860F14" , "3" , &sdhci_acpi_slot_int_sd }, { "INT33BB" , "2" , &sdhci_acpi_slot_int_sdio }, { "INT33C6" , NULL, &sdhci_acpi_slot_int_sdio }, { "PNP0D40" }, { }, }; static const struct acpi_device_id sdhci_acpi_ids[] = { { "80860F14" }, { "INT33BB" }, { "INT33C6" }, { "PNP0D40" }, { }, }; MODULE_DEVICE_TABLE(acpi, sdhci_acpi_ids); static const struct sdhci_acpi_slot *sdhci_acpi_get_slot_by_ids(const char *hid, const char *uid) { const struct sdhci_acpi_uid_slot *u; for (u = sdhci_acpi_uids; u->hid; u++) { if (strcmp(u->hid, hid)) continue; if (!u->uid) return u->slot; if (uid && !strcmp(u->uid, uid)) return u->slot; } return NULL; } static const struct sdhci_acpi_slot *sdhci_acpi_get_slot(acpi_handle handle, const char *hid) { const struct sdhci_acpi_slot *slot; struct acpi_device_info *info; const char *uid = NULL; acpi_status status; status = acpi_get_object_info(handle, &info); if (!ACPI_FAILURE(status) && (info->valid & ACPI_VALID_UID)) uid = info->unique_id.string; slot = sdhci_acpi_get_slot_by_ids(hid, uid); kfree(info); return slot; } #ifdef CONFIG_PM_RUNTIME static irqreturn_t sdhci_acpi_sd_cd(int irq, void *dev_id) { mmc_detect_change(dev_id, msecs_to_jiffies(200)); return IRQ_HANDLED; } static int sdhci_acpi_add_own_cd(struct device *dev, struct mmc_host *mmc) { struct gpio_desc *desc; unsigned long flags; int err, irq; desc = devm_gpiod_get_index(dev, "sd_cd", 0); if (IS_ERR(desc)) { err = PTR_ERR(desc); goto out; } err = gpiod_direction_input(desc); if (err) goto out_free; irq = gpiod_to_irq(desc); if (irq < 0) { err = irq; goto out_free; } flags = IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING; err = devm_request_irq(dev, irq, sdhci_acpi_sd_cd, flags, "sd_cd", mmc); if (err) goto out_free; return 0; out_free: devm_gpiod_put(dev, desc); out: dev_warn(dev, "failed to setup card detect wake up\n"); return err; } #else static int sdhci_acpi_add_own_cd(struct device *dev, struct mmc_host *mmc) { return 0; } #endif static int sdhci_acpi_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; acpi_handle handle = ACPI_HANDLE(dev); struct acpi_device *device; struct sdhci_acpi_host *c; struct sdhci_host *host; struct resource *iomem; resource_size_t len; const char *hid; int err; if (acpi_bus_get_device(handle, &device)) return -ENODEV; if (acpi_bus_get_status(device) || !device->status.present) return -ENODEV; hid = acpi_device_hid(device); iomem = platform_get_resource(pdev, IORESOURCE_MEM, 0); if (!iomem) return -ENOMEM; len = resource_size(iomem); if (len < 0x100) dev_err(dev, "Invalid iomem size!\n"); if (!devm_request_mem_region(dev, iomem->start, len, dev_name(dev))) return -ENOMEM; host = sdhci_alloc_host(dev, sizeof(struct sdhci_acpi_host)); if (IS_ERR(host)) return PTR_ERR(host); c = sdhci_priv(host); c->host = host; c->slot = sdhci_acpi_get_slot(handle, hid); c->pdev = pdev; c->use_runtime_pm = sdhci_acpi_flag(c, SDHCI_ACPI_RUNTIME_PM); platform_set_drvdata(pdev, c); host->hw_name = "ACPI"; host->ops = &sdhci_acpi_ops_dflt; host->irq = platform_get_irq(pdev, 0); host->ioaddr = devm_ioremap_nocache(dev, iomem->start, resource_size(iomem)); if (host->ioaddr == NULL) { err = -ENOMEM; goto err_free; } if (!dev->dma_mask) { u64 dma_mask; if (sdhci_readl(host, SDHCI_CAPABILITIES) & SDHCI_CAN_64BIT) { /* 64-bit DMA is not supported at present */ dma_mask = DMA_BIT_MASK(32); } else { dma_mask = DMA_BIT_MASK(32); } err = dma_coerce_mask_and_coherent(dev, dma_mask); if (err) goto err_free; } if (c->slot) { if (c->slot->chip) { host->ops = c->slot->chip->ops; host->quirks |= c->slot->chip->quirks; host->quirks2 |= c->slot->chip->quirks2; host->mmc->caps |= c->slot->chip->caps; host->mmc->caps2 |= c->slot->chip->caps2; host->mmc->pm_caps |= c->slot->chip->pm_caps; } host->quirks |= c->slot->quirks; host->quirks2 |= c->slot->quirks2; host->mmc->caps |= c->slot->caps; host->mmc->caps2 |= c->slot->caps2; host->mmc->pm_caps |= c->slot->pm_caps; } host->mmc->caps2 |= MMC_CAP2_NO_PRESCAN_POWERUP; err = sdhci_add_host(host); if (err) goto err_free; if (sdhci_acpi_flag(c, SDHCI_ACPI_SD_CD)) { if (sdhci_acpi_add_own_cd(dev, host->mmc)) c->use_runtime_pm = false; } if (c->use_runtime_pm) { pm_runtime_set_active(dev); pm_suspend_ignore_children(dev, 1); pm_runtime_set_autosuspend_delay(dev, 50); pm_runtime_use_autosuspend(dev); pm_runtime_enable(dev); } return 0; err_free: sdhci_free_host(c->host); return err; } static int sdhci_acpi_remove(struct platform_device *pdev) { struct sdhci_acpi_host *c = platform_get_drvdata(pdev); struct device *dev = &pdev->dev; int dead; if (c->use_runtime_pm) { pm_runtime_get_sync(dev); pm_runtime_disable(dev); pm_runtime_put_noidle(dev); } dead = (sdhci_readl(c->host, SDHCI_INT_STATUS) == ~0); sdhci_remove_host(c->host, dead); sdhci_free_host(c->host); return 0; } #ifdef CONFIG_PM_SLEEP static int sdhci_acpi_suspend(struct device *dev) { struct sdhci_acpi_host *c = dev_get_drvdata(dev); return sdhci_suspend_host(c->host); } static int sdhci_acpi_resume(struct device *dev) { struct sdhci_acpi_host *c = dev_get_drvdata(dev); return sdhci_resume_host(c->host); } #else #define sdhci_acpi_suspend NULL #define sdhci_acpi_resume NULL #endif #ifdef CONFIG_PM_RUNTIME static int sdhci_acpi_runtime_suspend(struct device *dev) { struct sdhci_acpi_host *c = dev_get_drvdata(dev); return sdhci_runtime_suspend_host(c->host); } static int sdhci_acpi_runtime_resume(struct device *dev) { struct sdhci_acpi_host *c = dev_get_drvdata(dev); return sdhci_runtime_resume_host(c->host); } static int sdhci_acpi_runtime_idle(struct device *dev) { return 0; } #else #define sdhci_acpi_runtime_suspend NULL #define sdhci_acpi_runtime_resume NULL #define sdhci_acpi_runtime_idle NULL #endif static const struct dev_pm_ops sdhci_acpi_pm_ops = { .suspend = sdhci_acpi_suspend, .resume = sdhci_acpi_resume, .runtime_suspend = sdhci_acpi_runtime_suspend, .runtime_resume = sdhci_acpi_runtime_resume, .runtime_idle = sdhci_acpi_runtime_idle, }; static struct platform_driver sdhci_acpi_driver = { .driver = { .name = "sdhci-acpi", .owner = THIS_MODULE, .acpi_match_table = sdhci_acpi_ids, .pm = &sdhci_acpi_pm_ops, }, .probe = sdhci_acpi_probe, .remove = sdhci_acpi_remove, }; module_platform_driver(sdhci_acpi_driver); MODULE_DESCRIPTION("Secure Digital Host Controller Interface ACPI driver"); MODULE_AUTHOR("Adrian Hunter"); MODULE_LICENSE("GPL v2");
Java
/* * Copyright (C) 2008-2013 TrinityCore <http://www.trinitycore.org/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "RBAC.h" #include "AccountMgr.h" #include "DatabaseEnv.h" #include "Log.h" namespace rbac { std::string GetDebugPermissionString(RBACPermissionContainer const& perms) { std::string str = ""; if (!perms.empty()) { std::ostringstream o; RBACPermissionContainer::const_iterator itr = perms.begin(); o << (*itr); for (++itr; itr != perms.end(); ++itr) o << ", " << uint32(*itr); str = o.str(); } return str; } RBACCommandResult RBACData::GrantPermission(uint32 permissionId, int32 realmId /* = 0*/) { // Check if permission Id exists RBACPermission const* perm = sAccountMgr->GetRBACPermission(permissionId); if (!perm) { TC_LOG_TRACE("rbac", "RBACData::GrantPermission [Id: %u Name: %s] (Permission %u, RealmId %d). Permission does not exists", GetId(), GetName().c_str(), permissionId, realmId); return RBAC_ID_DOES_NOT_EXISTS; } // Check if already added in denied list if (HasDeniedPermission(permissionId)) { TC_LOG_TRACE("rbac", "RBACData::GrantPermission [Id: %u Name: %s] (Permission %u, RealmId %d). Permission in deny list", GetId(), GetName().c_str(), permissionId, realmId); return RBAC_IN_DENIED_LIST; } // Already added? if (HasGrantedPermission(permissionId)) { TC_LOG_TRACE("rbac", "RBACData::GrantPermission [Id: %u Name: %s] (Permission %u, RealmId %d). Permission already granted", GetId(), GetName().c_str(), permissionId, realmId); return RBAC_CANT_ADD_ALREADY_ADDED; } AddGrantedPermission(permissionId); // Do not save to db when loading data from DB (realmId = 0) if (realmId) { TC_LOG_TRACE("rbac", "RBACData::GrantPermission [Id: %u Name: %s] (Permission %u, RealmId %d). Ok and DB updated", GetId(), GetName().c_str(), permissionId, realmId); SavePermission(permissionId, true, realmId); CalculateNewPermissions(); } else TC_LOG_TRACE("rbac", "RBACData::GrantPermission [Id: %u Name: %s] (Permission %u, RealmId %d). Ok", GetId(), GetName().c_str(), permissionId, realmId); return RBAC_OK; } RBACCommandResult RBACData::DenyPermission(uint32 permissionId, int32 realmId /* = 0*/) { // Check if permission Id exists RBACPermission const* perm = sAccountMgr->GetRBACPermission(permissionId); if (!perm) { TC_LOG_TRACE("rbac", "RBACData::DenyPermission [Id: %u Name: %s] (Permission %u, RealmId %d). Permission does not exists", GetId(), GetName().c_str(), permissionId, realmId); return RBAC_ID_DOES_NOT_EXISTS; } // Check if already added in granted list if (HasGrantedPermission(permissionId)) { TC_LOG_TRACE("rbac", "RBACData::DenyPermission [Id: %u Name: %s] (Permission %u, RealmId %d). Permission in grant list", GetId(), GetName().c_str(), permissionId, realmId); return RBAC_IN_GRANTED_LIST; } // Already added? if (HasDeniedPermission(permissionId)) { TC_LOG_TRACE("rbac", "RBACData::DenyPermission [Id: %u Name: %s] (Permission %u, RealmId %d). Permission already denied", GetId(), GetName().c_str(), permissionId, realmId); return RBAC_CANT_ADD_ALREADY_ADDED; } AddDeniedPermission(permissionId); // Do not save to db when loading data from DB (realmId = 0) if (realmId) { TC_LOG_TRACE("rbac", "RBACData::DenyPermission [Id: %u Name: %s] (Permission %u, RealmId %d). Ok and DB updated", GetId(), GetName().c_str(), permissionId, realmId); SavePermission(permissionId, false, realmId); CalculateNewPermissions(); } else TC_LOG_TRACE("rbac", "RBACData::DenyPermission [Id: %u Name: %s] (Permission %u, RealmId %d). Ok", GetId(), GetName().c_str(), permissionId, realmId); return RBAC_OK; } void RBACData::SavePermission(uint32 permission, bool granted, int32 realmId) { PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_INS_RBAC_ACCOUNT_PERMISSION); stmt->setUInt32(0, GetId()); stmt->setUInt32(1, permission); stmt->setBool(2, granted); stmt->setInt32(3, realmId); LoginDatabase.Execute(stmt); } RBACCommandResult RBACData::RevokePermission(uint32 permissionId, int32 realmId /* = 0*/) { // Check if it's present in any list if (!HasGrantedPermission(permissionId) && !HasDeniedPermission(permissionId)) { TC_LOG_TRACE("rbac", "RBACData::RevokePermission [Id: %u Name: %s] (Permission %u, RealmId %d). Not granted or revoked", GetId(), GetName().c_str(), permissionId, realmId); return RBAC_CANT_REVOKE_NOT_IN_LIST; } RemoveGrantedPermission(permissionId); RemoveDeniedPermission(permissionId); // Do not save to db when loading data from DB (realmId = 0) if (realmId) { TC_LOG_TRACE("rbac", "RBACData::RevokePermission [Id: %u Name: %s] (Permission %u, RealmId %d). Ok and DB updated", GetId(), GetName().c_str(), permissionId, realmId); PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_DEL_RBAC_ACCOUNT_PERMISSION); stmt->setUInt32(0, GetId()); stmt->setUInt32(1, permissionId); stmt->setInt32(2, realmId); LoginDatabase.Execute(stmt); CalculateNewPermissions(); } else TC_LOG_TRACE("rbac", "RBACData::RevokePermission [Id: %u Name: %s] (Permission %u, RealmId %d). Ok", GetId(), GetName().c_str(), permissionId, realmId); return RBAC_OK; } void RBACData::LoadFromDB() { ClearData(); TC_LOG_DEBUG("rbac", "RBACData::LoadFromDB [Id: %u Name: %s]: Loading permissions", GetId(), GetName().c_str()); // Load account permissions (granted and denied) that affect current realm PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_RBAC_ACCOUNT_PERMISSIONS); stmt->setUInt32(0, GetId()); stmt->setInt32(1, GetRealmId()); PreparedQueryResult result = LoginDatabase.Query(stmt); if (result) { do { Field* fields = result->Fetch(); if (fields[1].GetBool()) GrantPermission(fields[0].GetUInt32()); else DenyPermission(fields[0].GetUInt32()); } while (result->NextRow()); } // Add default permissions RBACPermissionContainer const& permissions = sAccountMgr->GetRBACDefaultPermissions(_secLevel); for (RBACPermissionContainer::const_iterator itr = permissions.begin(); itr != permissions.end(); ++itr) GrantPermission(*itr); // Force calculation of permissions CalculateNewPermissions(); } void RBACData::CalculateNewPermissions() { TC_LOG_TRACE("rbac", "RBACData::CalculateNewPermissions [Id: %u Name: %s]", GetId(), GetName().c_str()); // Get the list of granted permissions _globalPerms = GetGrantedPermissions(); ExpandPermissions(_globalPerms); RBACPermissionContainer revoked = GetDeniedPermissions(); ExpandPermissions(revoked); RemovePermissions(_globalPerms, revoked); } void RBACData::AddPermissions(RBACPermissionContainer const& permsFrom, RBACPermissionContainer& permsTo) { for (RBACPermissionContainer::const_iterator itr = permsFrom.begin(); itr != permsFrom.end(); ++itr) permsTo.insert(*itr); } void RBACData::RemovePermissions(RBACPermissionContainer const& permsFrom, RBACPermissionContainer& permsTo) { for (RBACPermissionContainer::const_iterator itr = permsFrom.begin(); itr != permsFrom.end(); ++itr) permsTo.erase(*itr); } void RBACData::ExpandPermissions(RBACPermissionContainer& permissions) { RBACPermissionContainer toCheck = permissions; permissions.clear(); while (!toCheck.empty()) { // remove the permission from original list uint32 permissionId = *toCheck.begin(); toCheck.erase(toCheck.begin()); RBACPermission const* permission = sAccountMgr->GetRBACPermission(permissionId); if (!permission) continue; // insert into the final list (expanded list) permissions.insert(permissionId); // add all linked permissions (that are not already expanded) to the list of permissions to be checked RBACPermissionContainer const& linkedPerms = permission->GetLinkedPermissions(); for (RBACPermissionContainer::const_iterator itr = linkedPerms.begin(); itr != linkedPerms.end(); ++itr) if (permissions.find(*itr) == permissions.end()) toCheck.insert(*itr); } TC_LOG_DEBUG("rbac", "RBACData::ExpandPermissions: Expanded: %s", GetDebugPermissionString(permissions).c_str()); } void RBACData::ClearData() { _grantedPerms.clear(); _deniedPerms.clear(); _globalPerms.clear(); } }
Java
<?php /** * @file * Contains \Drupal\commerce\AvailabilityCheckerInterface. */ namespace Drupal\commerce; /** * Defines the interface for availability checkers. */ interface AvailabilityCheckerInterface { /** * Determines whether the checker applies to the given purchasable entity. * * @param \Drupal\commerce\PurchasableEntityInterface $entity * The purchasable entity. * * @return bool * TRUE if the checker applies to the given purchasable entity, FALSE * otherwise. */ public function applies(PurchasableEntityInterface $entity); /** * Checks the availability of the given purchasable entity. * * @param \Drupal\commerce\PurchasableEntityInterface $entity * The purchasable entity. * @param int $quantity * The quantity. * * @return bool|null * TRUE if the entity is available, FALSE if it's unavailable, * or NULL if it has no opinion. */ public function check(PurchasableEntityInterface $entity, $quantity = 1); }
Java
<?php /* ** Zabbix ** Copyright (C) 2001-2014 Zabbix SIA ** ** This program is free software; you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published by ** the Free Software Foundation; either version 2 of the License, or ** (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with this program; if not, write to the Free Software ** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. **/ /** * Class that holds processed (created and updated) host and template IDs during the current import. */ class CImportedObjectContainer { /** * @var array with created and updated hosts. */ protected $hostIds = array(); /** * @var array with created and updated templates. */ protected $templateIds = array(); /** * Add host IDs that have been created and updated. * * @param array $hostIds */ public function addHostIds(array $hostIds) { foreach ($hostIds as $hostId) { $this->hostIds[$hostId] = $hostId; } } /** * Add template IDs that have been created and updated. * * @param array $templateIds */ public function addTemplateIds(array $templateIds) { foreach ($templateIds as $templateId) { $this->templateIds[$templateId] = $templateId; } } /** * Checks if host has been created and updated during the current import. * * @param string $hostId * * @return bool */ public function isHostProcessed($hostId) { return isset($this->hostIds[$hostId]); } /** * Checks if template has been created and updated during the current import. * * @param string $templateId * * @return bool */ public function isTemplateProcessed($templateId) { return isset($this->templateIds[$templateId]); } /** * Get array of created and updated hosts IDs. * * @return array */ public function getHostIds() { return array_values($this->hostIds); } /** * Get array of created and updated template IDs. * * @return array */ public function getTemplateIds() { return array_values($this->templateIds); } }
Java
// SPDX-License-Identifier: GPL-2.0-or-later /* * * BlueZ - Bluetooth protocol stack for Linux * * Copyright (C) 2013 Intel Corporation. All rights reserved. * * */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <stdbool.h> #include <glib.h> #include "lib/bluetooth.h" #include "lib/sco.h" #include "lib/mgmt.h" #include "monitor/bt.h" #include "emulator/bthost.h" #include "emulator/hciemu.h" #include "src/shared/tester.h" #include "src/shared/mgmt.h" struct test_data { const void *test_data; struct mgmt *mgmt; uint16_t mgmt_index; struct hciemu *hciemu; enum hciemu_type hciemu_type; unsigned int io_id; bool disable_esco; bool enable_codecs; }; struct sco_client_data { int expect_err; const uint8_t *send_data; uint16_t data_len; }; static void print_debug(const char *str, void *user_data) { const char *prefix = user_data; tester_print("%s%s", prefix, str); } static void read_info_callback(uint8_t status, uint16_t length, const void *param, void *user_data) { struct test_data *data = tester_get_data(); const struct mgmt_rp_read_info *rp = param; char addr[18]; uint16_t manufacturer; uint32_t supported_settings, current_settings; tester_print("Read Info callback"); tester_print(" Status: 0x%02x", status); if (status || !param) { tester_pre_setup_failed(); return; } ba2str(&rp->bdaddr, addr); manufacturer = btohs(rp->manufacturer); supported_settings = btohl(rp->supported_settings); current_settings = btohl(rp->current_settings); tester_print(" Address: %s", addr); tester_print(" Version: 0x%02x", rp->version); tester_print(" Manufacturer: 0x%04x", manufacturer); tester_print(" Supported settings: 0x%08x", supported_settings); tester_print(" Current settings: 0x%08x", current_settings); tester_print(" Class: 0x%02x%02x%02x", rp->dev_class[2], rp->dev_class[1], rp->dev_class[0]); tester_print(" Name: %s", rp->name); tester_print(" Short name: %s", rp->short_name); if (strcmp(hciemu_get_address(data->hciemu), addr)) { tester_pre_setup_failed(); return; } tester_pre_setup_complete(); } static void index_added_callback(uint16_t index, uint16_t length, const void *param, void *user_data) { struct test_data *data = tester_get_data(); tester_print("Index Added callback"); tester_print(" Index: 0x%04x", index); data->mgmt_index = index; mgmt_send(data->mgmt, MGMT_OP_READ_INFO, data->mgmt_index, 0, NULL, read_info_callback, NULL, NULL); } static void index_removed_callback(uint16_t index, uint16_t length, const void *param, void *user_data) { struct test_data *data = tester_get_data(); tester_print("Index Removed callback"); tester_print(" Index: 0x%04x", index); if (index != data->mgmt_index) return; mgmt_unregister_index(data->mgmt, data->mgmt_index); mgmt_unref(data->mgmt); data->mgmt = NULL; tester_post_teardown_complete(); } static void enable_codec_callback(uint8_t status, uint16_t length, const void *param, void *user_data) { if (status != MGMT_STATUS_SUCCESS) { tester_warn("Failed to enable codecs"); tester_setup_failed(); return; } tester_print("Enabled codecs"); } static void read_index_list_callback(uint8_t status, uint16_t length, const void *param, void *user_data) { struct test_data *data = tester_get_data(); tester_print("Read Index List callback"); tester_print(" Status: 0x%02x", status); if (status || !param) { tester_pre_setup_failed(); return; } mgmt_register(data->mgmt, MGMT_EV_INDEX_ADDED, MGMT_INDEX_NONE, index_added_callback, NULL, NULL); mgmt_register(data->mgmt, MGMT_EV_INDEX_REMOVED, MGMT_INDEX_NONE, index_removed_callback, NULL, NULL); data->hciemu = hciemu_new(HCIEMU_TYPE_BREDRLE); if (!data->hciemu) { tester_warn("Failed to setup HCI emulation"); tester_pre_setup_failed(); return; } if (tester_use_debug()) hciemu_set_debug(data->hciemu, print_debug, "hciemu: ", NULL); tester_print("New hciemu instance created"); if (data->disable_esco) { uint8_t *features; tester_print("Disabling eSCO packet type support"); features = hciemu_get_features(data->hciemu); if (features) features[3] &= ~0x80; } } static void test_pre_setup(const void *test_data) { struct test_data *data = tester_get_data(); data->mgmt = mgmt_new_default(); if (!data->mgmt) { tester_warn("Failed to setup management interface"); tester_pre_setup_failed(); return; } if (tester_use_debug()) mgmt_set_debug(data->mgmt, print_debug, "mgmt: ", NULL); mgmt_send(data->mgmt, MGMT_OP_READ_INDEX_LIST, MGMT_INDEX_NONE, 0, NULL, read_index_list_callback, NULL, NULL); } static void test_post_teardown(const void *test_data) { struct test_data *data = tester_get_data(); hciemu_unref(data->hciemu); data->hciemu = NULL; } static void test_data_free(void *test_data) { struct test_data *data = test_data; if (data->io_id > 0) g_source_remove(data->io_id); free(data); } #define test_sco_full(name, data, setup, func, _disable_esco, _enable_codecs) \ do { \ struct test_data *user; \ user = malloc(sizeof(struct test_data)); \ if (!user) \ break; \ user->hciemu_type = HCIEMU_TYPE_BREDRLE; \ user->io_id = 0; \ user->test_data = data; \ user->disable_esco = _disable_esco; \ user->enable_codecs = _enable_codecs; \ tester_add_full(name, data, \ test_pre_setup, setup, func, NULL, \ test_post_teardown, 2, user, test_data_free); \ } while (0) #define test_sco(name, data, setup, func) \ test_sco_full(name, data, setup, func, false, false) #define test_sco_11(name, data, setup, func) \ test_sco_full(name, data, setup, func, true, false) #define test_offload_sco(name, data, setup, func) \ test_sco_full(name, data, setup, func, false, true) static const struct sco_client_data connect_success = { .expect_err = 0 }; static const struct sco_client_data connect_failure = { .expect_err = EOPNOTSUPP }; const uint8_t data[] = {0, 1, 2, 3, 4, 5, 6, 7, 8}; static const struct sco_client_data connect_send_success = { .expect_err = 0, .data_len = sizeof(data), .send_data = data }; static void client_connectable_complete(uint16_t opcode, uint8_t status, const void *param, uint8_t len, void *user_data) { if (opcode != BT_HCI_CMD_WRITE_SCAN_ENABLE) return; tester_print("Client set connectable status 0x%02x", status); if (status) tester_setup_failed(); else tester_setup_complete(); } static void setup_powered_callback(uint8_t status, uint16_t length, const void *param, void *user_data) { struct test_data *data = tester_get_data(); struct bthost *bthost; if (status != MGMT_STATUS_SUCCESS) { tester_setup_failed(); return; } tester_print("Controller powered on"); bthost = hciemu_client_get_host(data->hciemu); bthost_set_cmd_complete_cb(bthost, client_connectable_complete, data); bthost_write_scan_enable(bthost, 0x03); } static void setup_powered(const void *test_data) { struct test_data *data = tester_get_data(); unsigned char param[] = { 0x01 }; tester_print("Powering on controller"); mgmt_send(data->mgmt, MGMT_OP_SET_CONNECTABLE, data->mgmt_index, sizeof(param), param, NULL, NULL, NULL); mgmt_send(data->mgmt, MGMT_OP_SET_SSP, data->mgmt_index, sizeof(param), param, NULL, NULL, NULL); mgmt_send(data->mgmt, MGMT_OP_SET_LE, data->mgmt_index, sizeof(param), param, NULL, NULL, NULL); if (data->enable_codecs) { /* a6695ace-ee7f-4fb9-881a-5fac66c629af */ static const uint8_t uuid[16] = { 0xaf, 0x29, 0xc6, 0x66, 0xac, 0x5f, 0x1a, 0x88, 0xb9, 0x4f, 0x7f, 0xee, 0xce, 0x5a, 0x69, 0xa6, }; struct mgmt_cp_set_exp_feature cp; memset(&cp, 0, sizeof(cp)); memcpy(cp.uuid, uuid, 16); cp.action = 1; tester_print("Enabling codecs"); mgmt_send(data->mgmt, MGMT_OP_SET_EXP_FEATURE, data->mgmt_index, sizeof(cp), &cp, enable_codec_callback, NULL, NULL); } mgmt_send(data->mgmt, MGMT_OP_SET_POWERED, data->mgmt_index, sizeof(param), param, setup_powered_callback, NULL, NULL); } static void test_framework(const void *test_data) { tester_test_passed(); } static void test_socket(const void *test_data) { int sk; sk = socket(PF_BLUETOOTH, SOCK_SEQPACKET, BTPROTO_SCO); if (sk < 0) { tester_warn("Can't create socket: %s (%d)", strerror(errno), errno); tester_test_failed(); return; } close(sk); tester_test_passed(); } static void test_codecs_getsockopt(const void *test_data) { int sk, err; socklen_t len; char buffer[255]; sk = socket(PF_BLUETOOTH, SOCK_SEQPACKET, BTPROTO_SCO); if (sk < 0) { tester_warn("Can't create socket: %s (%d)", strerror(errno), errno); tester_test_failed(); return; } len = sizeof(buffer); memset(buffer, 0, len); err = getsockopt(sk, SOL_BLUETOOTH, BT_CODEC, buffer, &len); if (err < 0) { tester_warn("Can't get socket option : %s (%d)", strerror(errno), errno); tester_test_failed(); goto end; } tester_test_passed(); end: close(sk); } static void test_codecs_setsockopt(const void *test_data) { int sk, err; char buffer[255]; struct bt_codecs *codecs; sk = socket(PF_BLUETOOTH, SOCK_SEQPACKET, BTPROTO_SCO); if (sk < 0) { tester_warn("Can't create socket: %s (%d)", strerror(errno), errno); tester_test_failed(); return; } memset(buffer, 0, sizeof(buffer)); codecs = (void *)buffer; codecs->codecs[0].id = 0x05; codecs->num_codecs = 1; codecs->codecs[0].data_path_id = 1; codecs->codecs[0].num_caps = 0x00; err = setsockopt(sk, SOL_BLUETOOTH, BT_CODEC, codecs, sizeof(buffer)); if (err < 0) { tester_warn("Can't set socket option : %s (%d)", strerror(errno), errno); tester_test_failed(); goto end; } tester_test_passed(); end: close(sk); } static void test_getsockopt(const void *test_data) { int sk, err; socklen_t len; struct bt_voice voice; sk = socket(PF_BLUETOOTH, SOCK_SEQPACKET, BTPROTO_SCO); if (sk < 0) { tester_warn("Can't create socket: %s (%d)", strerror(errno), errno); tester_test_failed(); return; } len = sizeof(voice); memset(&voice, 0, len); err = getsockopt(sk, SOL_BLUETOOTH, BT_VOICE, &voice, &len); if (err < 0) { tester_warn("Can't get socket option : %s (%d)", strerror(errno), errno); tester_test_failed(); goto end; } if (voice.setting != BT_VOICE_CVSD_16BIT) { tester_warn("Invalid voice setting"); tester_test_failed(); goto end; } tester_test_passed(); end: close(sk); } static void test_setsockopt(const void *test_data) { int sk, err; socklen_t len; struct bt_voice voice; sk = socket(PF_BLUETOOTH, SOCK_SEQPACKET, BTPROTO_SCO); if (sk < 0) { tester_warn("Can't create socket: %s (%d)", strerror(errno), errno); tester_test_failed(); goto end; } len = sizeof(voice); memset(&voice, 0, len); err = getsockopt(sk, SOL_BLUETOOTH, BT_VOICE, &voice, &len); if (err < 0) { tester_warn("Can't get socket option : %s (%d)", strerror(errno), errno); tester_test_failed(); goto end; } if (voice.setting != BT_VOICE_CVSD_16BIT) { tester_warn("Invalid voice setting"); tester_test_failed(); goto end; } memset(&voice, 0, sizeof(voice)); voice.setting = BT_VOICE_TRANSPARENT; err = setsockopt(sk, SOL_BLUETOOTH, BT_VOICE, &voice, sizeof(voice)); if (err < 0) { tester_warn("Can't set socket option : %s (%d)", strerror(errno), errno); tester_test_failed(); goto end; } len = sizeof(voice); memset(&voice, 0, len); err = getsockopt(sk, SOL_BLUETOOTH, BT_VOICE, &voice, &len); if (err < 0) { tester_warn("Can't get socket option : %s (%d)", strerror(errno), errno); tester_test_failed(); goto end; } if (voice.setting != BT_VOICE_TRANSPARENT) { tester_warn("Invalid voice setting"); tester_test_failed(); goto end; } tester_test_passed(); end: close(sk); } static int create_sco_sock(struct test_data *data) { const uint8_t *central_bdaddr; struct sockaddr_sco addr; int sk, err; sk = socket(PF_BLUETOOTH, SOCK_SEQPACKET | SOCK_NONBLOCK, BTPROTO_SCO); if (sk < 0) { err = -errno; tester_warn("Can't create socket: %s (%d)", strerror(errno), errno); return err; } central_bdaddr = hciemu_get_central_bdaddr(data->hciemu); if (!central_bdaddr) { tester_warn("No central bdaddr"); return -ENODEV; } memset(&addr, 0, sizeof(addr)); addr.sco_family = AF_BLUETOOTH; bacpy(&addr.sco_bdaddr, (void *) central_bdaddr); if (bind(sk, (struct sockaddr *) &addr, sizeof(addr)) < 0) { err = -errno; tester_warn("Can't bind socket: %s (%d)", strerror(errno), errno); close(sk); return err; } return sk; } static int connect_sco_sock(struct test_data *data, int sk) { const uint8_t *client_bdaddr; struct sockaddr_sco addr; int err; client_bdaddr = hciemu_get_client_bdaddr(data->hciemu); if (!client_bdaddr) { tester_warn("No client bdaddr"); return -ENODEV; } memset(&addr, 0, sizeof(addr)); addr.sco_family = AF_BLUETOOTH; bacpy(&addr.sco_bdaddr, (void *) client_bdaddr); err = connect(sk, (struct sockaddr *) &addr, sizeof(addr)); if (err < 0 && !(errno == EAGAIN || errno == EINPROGRESS)) { err = -errno; tester_warn("Can't connect socket: %s (%d)", strerror(errno), errno); return err; } return 0; } static gboolean sco_connect_cb(GIOChannel *io, GIOCondition cond, gpointer user_data) { struct test_data *data = tester_get_data(); const struct sco_client_data *scodata = data->test_data; int err, sk_err, sk; socklen_t len = sizeof(sk_err); data->io_id = 0; sk = g_io_channel_unix_get_fd(io); if (getsockopt(sk, SOL_SOCKET, SO_ERROR, &sk_err, &len) < 0) err = -errno; else err = -sk_err; if (err < 0) tester_warn("Connect failed: %s (%d)", strerror(-err), -err); else tester_print("Successfully connected"); if (scodata->send_data) { ssize_t ret; tester_print("Writing %u bytes of data", scodata->data_len); ret = write(sk, scodata->send_data, scodata->data_len); if (scodata->data_len != ret) { tester_warn("Failed to write %u bytes: %zu %s (%d)", scodata->data_len, ret, strerror(errno), errno); err = -errno; } } if (-err != scodata->expect_err) tester_test_failed(); else tester_test_passed(); return FALSE; } static void test_connect(const void *test_data) { struct test_data *data = tester_get_data(); GIOChannel *io; int sk; sk = create_sco_sock(data); if (sk < 0) { tester_test_failed(); return; } if (connect_sco_sock(data, sk) < 0) { close(sk); tester_test_failed(); return; } io = g_io_channel_unix_new(sk); g_io_channel_set_close_on_unref(io, TRUE); data->io_id = g_io_add_watch(io, G_IO_OUT, sco_connect_cb, NULL); g_io_channel_unref(io); tester_print("Connect in progress"); } static void test_connect_transp(const void *test_data) { struct test_data *data = tester_get_data(); const struct sco_client_data *scodata = data->test_data; int sk, err; struct bt_voice voice; sk = create_sco_sock(data); if (sk < 0) { tester_test_failed(); return; } memset(&voice, 0, sizeof(voice)); voice.setting = BT_VOICE_TRANSPARENT; err = setsockopt(sk, SOL_BLUETOOTH, BT_VOICE, &voice, sizeof(voice)); if (err < 0) { tester_warn("Can't set socket option : %s (%d)", strerror(errno), errno); tester_test_failed(); goto end; } err = connect_sco_sock(data, sk); tester_warn("Connect returned %s (%d), expected %s (%d)", strerror(-err), -err, strerror(scodata->expect_err), scodata->expect_err); if (-err != scodata->expect_err) tester_test_failed(); else tester_test_passed(); end: close(sk); } static void test_connect_offload_msbc(const void *test_data) { struct test_data *data = tester_get_data(); const struct sco_client_data *scodata = data->test_data; int sk, err; int len; char buffer[255]; struct bt_codecs *codecs; sk = create_sco_sock(data); if (sk < 0) { tester_test_failed(); return; } len = sizeof(buffer); memset(buffer, 0, len); codecs = (void *)buffer; codecs->codecs[0].id = 0x05; codecs->num_codecs = 1; codecs->codecs[0].data_path_id = 1; codecs->codecs[0].num_caps = 0x00; err = setsockopt(sk, SOL_BLUETOOTH, BT_CODEC, codecs, sizeof(buffer)); if (err < 0) { tester_warn("Can't set socket option : %s (%d)", strerror(errno), errno); tester_test_failed(); goto end; } err = connect_sco_sock(data, sk); tester_warn("Connect returned %s (%d), expected %s (%d)", strerror(-err), -err, strerror(scodata->expect_err), scodata->expect_err); if (-err != scodata->expect_err) tester_test_failed(); else tester_test_passed(); end: close(sk); } int main(int argc, char *argv[]) { tester_init(&argc, &argv); test_sco("Basic Framework - Success", NULL, setup_powered, test_framework); test_sco("Basic SCO Socket - Success", NULL, setup_powered, test_socket); test_sco("Basic SCO Get Socket Option - Success", NULL, setup_powered, test_getsockopt); test_sco("Basic SCO Set Socket Option - Success", NULL, setup_powered, test_setsockopt); test_sco("eSCO CVSD - Success", &connect_success, setup_powered, test_connect); test_sco("eSCO mSBC - Success", &connect_success, setup_powered, test_connect_transp); test_sco_11("SCO CVSD 1.1 - Success", &connect_success, setup_powered, test_connect); test_sco_11("SCO mSBC 1.1 - Failure", &connect_failure, setup_powered, test_connect_transp); test_sco("SCO CVSD Send - Success", &connect_send_success, setup_powered, test_connect); test_offload_sco("Basic SCO Get Socket Option - Offload - Success", NULL, setup_powered, test_codecs_getsockopt); test_offload_sco("Basic SCO Set Socket Option - Offload - Success", NULL, setup_powered, test_codecs_setsockopt); test_offload_sco("eSCO mSBC - Offload - Success", &connect_success, setup_powered, test_connect_offload_msbc); return tester_run(); }
Java
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>DB_ENV-&gt;rep_get_clockskew()</title> <link rel="stylesheet" href="apiReference.css" type="text/css" /> <meta name="generator" content="DocBook XSL Stylesheets V1.73.2" /> <link rel="start" href="index.html" title="Berkeley DB C API Reference" /> <link rel="up" href="rep.html" title="Chapter 10.  Replication Methods" /> <link rel="prev" href="repelect.html" title="DB_ENV-&gt;rep_elect()" /> <link rel="next" href="repget_config.html" title="DB_ENV-&gt;rep_get_config()" /> </head> <body> <div class="navheader"> <table width="100%" summary="Navigation header"> <tr> <th colspan="3" align="center">DB_ENV-&gt;rep_get_clockskew()</th> </tr> <tr> <td width="20%" align="left"><a accesskey="p" href="repelect.html">Prev</a> </td> <th width="60%" align="center">Chapter 10.  Replication Methods </th> <td width="20%" align="right"> <a accesskey="n" href="repget_config.html">Next</a></td> </tr> </table> <hr /> </div> <div class="sect1" lang="en" xml:lang="en"> <div class="titlepage"> <div> <div> <h2 class="title" style="clear: both"><a id="repget_clockskew"></a>DB_ENV-&gt;rep_get_clockskew()</h2> </div> </div> </div> <pre class="programlisting">#include &lt;db.h&gt; int DB_ENV-&gt;rep_get_clockskew(DB_ENV *env, u_int32_t *fast_clockp, u_int32_t *slow_clockp); </pre> <p> The <code class="methodname">DB_ENV-&gt;rep_get_clockskew()</code> method returns the current clock skew ratio values, as set by the <a class="xref" href="repclockskew.html" title="DB_ENV-&gt;rep_set_clockskew()">DB_ENV-&gt;rep_set_clockskew()</a> method. </p> <p> The <code class="methodname">DB_ENV-&gt;rep_get_clockskew()</code> method may be called at any time during the life of the application. </p> <p> The <code class="methodname">DB_ENV-&gt;rep_get_clockskew()</code> <span> <span> method returns a non-zero error value on failure and 0 on success. </span> </span> </p> <div class="sect2" lang="en" xml:lang="en"> <div class="titlepage"> <div> <div> <h3 class="title"><a id="id3891622"></a>Parameters</h3> </div> </div> </div> <div class="sect3" lang="en" xml:lang="en"> <div class="titlepage"> <div> <div> <h4 class="title"><a id="id3891611"></a>fast_clockp</h4> </div> </div> </div> <p> The <span class="bold"><strong>fast_clockp</strong></span> parameter references memory into which the value for the fastest clock in the group of sites is copied. </p> </div> <div class="sect3" lang="en" xml:lang="en"> <div class="titlepage"> <div> <div> <h4 class="title"><a id="id3891226"></a>slow_clockp</h4> </div> </div> </div> <p> The <span class="bold"><strong>slow_clockp</strong></span> parameter references memory into which the value for the slowest clock in the group of sites is copied. </p> </div> </div> <div class="sect2" lang="en" xml:lang="en"> <div class="titlepage"> <div> <div> <h3 class="title"><a id="id3891280"></a>Class</h3> </div> </div> </div> <p> <a class="link" href="env.html" title="Chapter 5.  The DB_ENV Handle">DB_ENV</a> </p> </div> <div class="sect2" lang="en" xml:lang="en"> <div class="titlepage"> <div> <div> <h3 class="title"><a id="id3891071"></a>See Also</h3> </div> </div> </div> <p> <a class="xref" href="rep.html#replist" title="Replication and Related Methods">Replication and Related Methods</a>, <a class="xref" href="repclockskew.html" title="DB_ENV-&gt;rep_set_clockskew()">DB_ENV-&gt;rep_set_clockskew()</a> </p> </div> </div> <div class="navfooter"> <hr /> <table width="100%" summary="Navigation footer"> <tr> <td width="40%" align="left"><a accesskey="p" href="repelect.html">Prev</a> </td> <td width="20%" align="center"> <a accesskey="u" href="rep.html">Up</a> </td> <td width="40%" align="right"> <a accesskey="n" href="repget_config.html">Next</a></td> </tr> <tr> <td width="40%" align="left" valign="top">DB_ENV-&gt;rep_elect() </td> <td width="20%" align="center"> <a accesskey="h" href="index.html">Home</a> </td> <td width="40%" align="right" valign="top"> DB_ENV-&gt;rep_get_config()</td> </tr> </table> </div> </body> </html>
Java
/* * Soft: Keepalived is a failover program for the LVS project * <www.linuxvirtualserver.org>. It monitor & manipulate * a loadbalanced server pool using multi-layer checks. * * Part: NETLINK kernel command channel. * * Author: Alexandre Cassen, <[email protected]> * * 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. * * 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. * * Copyright (C) 2001-2012 Alexandre Cassen, <[email protected]> */ /* global include */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <syslog.h> #include <fcntl.h> #include <net/if_arp.h> #include <sys/socket.h> #include <netinet/in.h> #include <string.h> #include <errno.h> #include <time.h> #include <sys/uio.h> /* local include */ #include "check_api.h" #include "vrrp_netlink.h" #include "vrrp_if.h" #include "logger.h" #include "memory.h" #include "scheduler.h" #include "utils.h" /* Global vars */ nl_handle_t nl_kernel; /* Kernel reflection channel */ nl_handle_t nl_cmd; /* Command channel */ /* Create a socket to netlink interface_t */ int netlink_socket(nl_handle_t *nl, unsigned long groups) { socklen_t addr_len; int ret; memset(nl, 0, sizeof (*nl)); nl->fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE); if (nl->fd < 0) { log_message(LOG_INFO, "Netlink: Cannot open netlink socket : (%s)", strerror(errno)); return -1; } ret = fcntl(nl->fd, F_SETFL, O_NONBLOCK); if (ret < 0) { log_message(LOG_INFO, "Netlink: Cannot set netlink socket flags : (%s)", strerror(errno)); close(nl->fd); return -1; } memset(&nl->snl, 0, sizeof (nl->snl)); nl->snl.nl_family = AF_NETLINK; nl->snl.nl_groups = groups; ret = bind(nl->fd, (struct sockaddr *) &nl->snl, sizeof (nl->snl)); if (ret < 0) { log_message(LOG_INFO, "Netlink: Cannot bind netlink socket : (%s)", strerror(errno)); close(nl->fd); return -1; } addr_len = sizeof (nl->snl); ret = getsockname(nl->fd, (struct sockaddr *) &nl->snl, &addr_len); if (ret < 0 || addr_len != sizeof (nl->snl)) { log_message(LOG_INFO, "Netlink: Cannot getsockname : (%s)", strerror(errno)); close(nl->fd); return -1; } if (nl->snl.nl_family != AF_NETLINK) { log_message(LOG_INFO, "Netlink: Wrong address family %d", nl->snl.nl_family); close(nl->fd); return -1; } nl->seq = time(NULL); /* Set default rcvbuf size */ if_setsockopt_rcvbuf(&nl->fd, IF_DEFAULT_BUFSIZE); if (nl->fd < 0) return -1; return ret; } /* Close a netlink socket */ int netlink_close(nl_handle_t *nl) { /* First of all release pending thread */ thread_cancel(nl->thread); close(nl->fd); return 0; } /* Set netlink socket channel as blocking */ int netlink_set_block(nl_handle_t *nl, int *flags) { if ((*flags = fcntl(nl->fd, F_GETFL, 0)) < 0) { log_message(LOG_INFO, "Netlink: Cannot F_GETFL socket : (%s)", strerror(errno)); return -1; } *flags &= ~O_NONBLOCK; if (fcntl(nl->fd, F_SETFL, *flags) < 0) { log_message(LOG_INFO, "Netlink: Cannot F_SETFL socket : (%s)", strerror(errno)); return -1; } return 0; } /* Set netlink socket channel as non-blocking */ int netlink_set_nonblock(nl_handle_t *nl, int *flags) { *flags |= O_NONBLOCK; if (fcntl(nl->fd, F_SETFL, *flags) < 0) { log_message(LOG_INFO, "Netlink: Cannot F_SETFL socket : (%s)", strerror(errno)); return -1; } return 0; } /* iproute2 utility function */ int addattr32(struct nlmsghdr *n, int maxlen, int type, uint32_t data) { int len = RTA_LENGTH(4); struct rtattr *rta; if (NLMSG_ALIGN(n->nlmsg_len) + len > maxlen) return -1; rta = (struct rtattr*)(((char*)n) + NLMSG_ALIGN(n->nlmsg_len)); rta->rta_type = type; rta->rta_len = len; memcpy(RTA_DATA(rta), &data, 4); n->nlmsg_len = NLMSG_ALIGN(n->nlmsg_len) + len; return 0; } int addattr_l(struct nlmsghdr *n, int maxlen, int type, void *data, int alen) { int len = RTA_LENGTH(alen); struct rtattr *rta; if (NLMSG_ALIGN(n->nlmsg_len) + len > maxlen) return -1; rta = (struct rtattr *) (((char *) n) + NLMSG_ALIGN(n->nlmsg_len)); rta->rta_type = type; rta->rta_len = len; memcpy(RTA_DATA(rta), data, alen); n->nlmsg_len = NLMSG_ALIGN(n->nlmsg_len) + len; return 0; } int rta_addattr_l(struct rtattr *rta, int maxlen, int type, const void *data, int alen) { struct rtattr *subrta; int len = RTA_LENGTH(alen); if (RTA_ALIGN(rta->rta_len) + RTA_ALIGN(len) > maxlen) { return -1; } subrta = (struct rtattr*)(((char*)rta) + RTA_ALIGN(rta->rta_len)); subrta->rta_type = type; subrta->rta_len = len; memcpy(RTA_DATA(subrta), data, alen); rta->rta_len = NLMSG_ALIGN(rta->rta_len) + RTA_ALIGN(len); return 0; } static void parse_rtattr(struct rtattr **tb, int max, struct rtattr *rta, int len) { while (RTA_OK(rta, len)) { if (rta->rta_type <= max) tb[rta->rta_type] = rta; rta = RTA_NEXT(rta, len); } } char * netlink_scope_n2a(int scope) { if (scope == 0) return "global"; if (scope == 255) return "nowhere"; if (scope == 254) return "host"; if (scope == 253) return "link"; if (scope == 200) return "site"; return "unknown"; } int netlink_scope_a2n(char *scope) { if (!strcmp(scope, "global")) return 0; if (!strcmp(scope, "nowhere")) return 255; if (!strcmp(scope, "host")) return 254; if (!strcmp(scope, "link")) return 253; if (!strcmp(scope, "site")) return 200; return -1; } /* * Reflect base interface flags on VMAC interface. * VMAC interfaces should never update it own flags, only be reflected * by the base interface flags. */ static void vmac_reflect_flags(struct ifinfomsg *ifi) { interface_t *ifp; /* find the VMAC interface (if any) */ ifp = if_get_by_vmac_base_ifindex(ifi->ifi_index); /* if found, reflect base interface flags on VMAC interface */ if (ifp) { ifp->flags = ifi->ifi_flags; } } /* Our netlink parser */ static int netlink_parse_info(int (*filter) (struct sockaddr_nl *, struct nlmsghdr *), nl_handle_t *nl, struct nlmsghdr *n) { int status; int ret = 0; int error; while (1) { char buf[4096]; struct iovec iov = { buf, sizeof buf }; struct sockaddr_nl snl; struct msghdr msg = { (void *) &snl, sizeof snl, &iov, 1, NULL, 0, 0 }; struct nlmsghdr *h; status = recvmsg(nl->fd, &msg, 0); if (status < 0) { if (errno == EINTR) continue; if (errno == EWOULDBLOCK || errno == EAGAIN) break; log_message(LOG_INFO, "Netlink: Received message overrun (%m)"); continue; } if (status == 0) { log_message(LOG_INFO, "Netlink: EOF"); return -1; } if (msg.msg_namelen != sizeof snl) { log_message(LOG_INFO, "Netlink: Sender address length error: length %d", msg.msg_namelen); return -1; } for (h = (struct nlmsghdr *) buf; NLMSG_OK(h, status); h = NLMSG_NEXT(h, status)) { /* Finish of reading. */ if (h->nlmsg_type == NLMSG_DONE) return ret; /* Error handling. */ if (h->nlmsg_type == NLMSG_ERROR) { struct nlmsgerr *err = (struct nlmsgerr *) NLMSG_DATA(h); /* * If error == 0 then this is a netlink ACK. * return if not related to multipart message. */ if (err->error == 0) { if (!(h->nlmsg_flags & NLM_F_MULTI)) return 0; continue; } if (h->nlmsg_len < NLMSG_LENGTH(sizeof (struct nlmsgerr))) { log_message(LOG_INFO, "Netlink: error: message truncated"); return -1; } if (n && (err->error == -EEXIST) && ((n->nlmsg_type == RTM_NEWROUTE) || (n->nlmsg_type == RTM_NEWADDR))) return 0; log_message(LOG_INFO, "Netlink: error: %s, type=(%u), seq=%u, pid=%d", strerror(-err->error), err->msg.nlmsg_type, err->msg.nlmsg_seq, err->msg.nlmsg_pid); return -1; } /* Skip unsolicited messages from cmd channel */ if (nl != &nl_cmd && h->nlmsg_pid == nl_cmd.snl.nl_pid) continue; error = (*filter) (&snl, h); if (error < 0) { log_message(LOG_INFO, "Netlink: filter function error"); ret = error; } } /* After error care. */ if (msg.msg_flags & MSG_TRUNC) { log_message(LOG_INFO, "Netlink: error: message truncated"); continue; } if (status) { log_message(LOG_INFO, "Netlink: error: data remnant size %d", status); return -1; } } return ret; } /* Out talk filter */ static int netlink_talk_filter(struct sockaddr_nl *snl, struct nlmsghdr *h) { log_message(LOG_INFO, "Netlink: ignoring message type 0x%04x", h->nlmsg_type); return 0; } /* send message to netlink kernel socket, then receive response */ int netlink_talk(nl_handle_t *nl, struct nlmsghdr *n) { int status; int ret, flags; struct sockaddr_nl snl; struct iovec iov = { (void *) n, n->nlmsg_len }; struct msghdr msg = { (void *) &snl, sizeof snl, &iov, 1, NULL, 0, 0 }; memset(&snl, 0, sizeof snl); snl.nl_family = AF_NETLINK; n->nlmsg_seq = ++nl->seq; /* Request Netlink acknowledgement */ n->nlmsg_flags |= NLM_F_ACK; /* Send message to netlink interface. */ status = sendmsg(nl->fd, &msg, 0); if (status < 0) { log_message(LOG_INFO, "Netlink: sendmsg() error: %s", strerror(errno)); return -1; } /* Set blocking flag */ ret = netlink_set_block(nl, &flags); if (ret < 0) log_message(LOG_INFO, "Netlink: Warning, couldn't set " "blocking flag to netlink socket..."); status = netlink_parse_info(netlink_talk_filter, nl, n); /* Restore previous flags */ if (ret == 0) netlink_set_nonblock(nl, &flags); return status; } /* Fetch a specific type information from netlink kernel */ static int netlink_request(nl_handle_t *nl, int family, int type) { int status; struct sockaddr_nl snl; struct { struct nlmsghdr nlh; struct rtgenmsg g; } req; /* Cleanup the room */ memset(&snl, 0, sizeof (snl)); snl.nl_family = AF_NETLINK; req.nlh.nlmsg_len = sizeof (req); req.nlh.nlmsg_type = type; req.nlh.nlmsg_flags = NLM_F_ROOT | NLM_F_MATCH | NLM_F_REQUEST; req.nlh.nlmsg_pid = 0; req.nlh.nlmsg_seq = ++nl->seq; req.g.rtgen_family = family; status = sendto(nl->fd, (void *) &req, sizeof (req) , 0, (struct sockaddr *) &snl, sizeof (snl)); if (status < 0) { log_message(LOG_INFO, "Netlink: sendto() failed: %s", strerror(errno)); return -1; } return 0; } /* Netlink interface link lookup filter */ static int netlink_if_link_filter(struct sockaddr_nl *snl, struct nlmsghdr *h) { struct ifinfomsg *ifi; struct rtattr *tb[IFLA_MAX + 1]; interface_t *ifp; int i, len; char *name; ifi = NLMSG_DATA(h); if (h->nlmsg_type != RTM_NEWLINK) return 0; len = h->nlmsg_len - NLMSG_LENGTH(sizeof (struct ifinfomsg)); if (len < 0) return -1; /* Interface name lookup */ memset(tb, 0, sizeof (tb)); parse_rtattr(tb, IFLA_MAX, IFLA_RTA(ifi), len); if (tb[IFLA_IFNAME] == NULL) return -1; name = (char *) RTA_DATA(tb[IFLA_IFNAME]); /* Return if loopback */ if (ifi->ifi_type == ARPHRD_LOOPBACK) return 0; /* Skip it if already exist */ ifp = if_get_by_ifname(name); if (ifp) { if (!ifp->vmac) { vmac_reflect_flags(ifi); ifp->flags = ifi->ifi_flags; } return 0; } /* Fill the interface structure */ ifp = (interface_t *) MALLOC(sizeof(interface_t)); memcpy(ifp->ifname, name, strlen(name)); ifp->ifindex = ifi->ifi_index; ifp->mtu = *(int *) RTA_DATA(tb[IFLA_MTU]); ifp->hw_type = ifi->ifi_type; if (!ifp->vmac) { vmac_reflect_flags(ifi); ifp->flags = ifi->ifi_flags; ifp->base_ifindex = ifi->ifi_index; } if (tb[IFLA_ADDRESS]) { int hw_addr_len = RTA_PAYLOAD(tb[IFLA_ADDRESS]); if (hw_addr_len > IF_HWADDR_MAX) log_message(LOG_ERR, "MAC address for %s is too large: %d", name, hw_addr_len); else { ifp->hw_addr_len = hw_addr_len; memcpy(ifp->hw_addr, RTA_DATA(tb[IFLA_ADDRESS]), hw_addr_len); for (i = 0; i < hw_addr_len; i++) if (ifp->hw_addr[i] != 0) break; if (i == hw_addr_len) ifp->hw_addr_len = 0; else ifp->hw_addr_len = hw_addr_len; } } /* Queue this new interface_t */ if_add_queue(ifp); return 0; } /* * Netlink interface address lookup filter * We need to handle multiple primary address and * multiple secondary address to the same interface. */ static int netlink_if_address_filter(struct sockaddr_nl *snl, struct nlmsghdr *h) { struct ifaddrmsg *ifa; struct rtattr *tb[IFA_MAX + 1]; interface_t *ifp; int len; void *addr; ifa = NLMSG_DATA(h); /* Only IPV4 are valid us */ if (ifa->ifa_family != AF_INET && ifa->ifa_family != AF_INET6) return 0; if (h->nlmsg_type != RTM_NEWADDR && h->nlmsg_type != RTM_DELADDR) return 0; len = h->nlmsg_len - NLMSG_LENGTH(sizeof (struct ifaddrmsg)); if (len < 0) return -1; memset(tb, 0, sizeof (tb)); parse_rtattr(tb, IFA_MAX, IFA_RTA(ifa), len); /* Fetch interface_t */ ifp = if_get_by_ifindex(ifa->ifa_index); if (!ifp) return 0; if (tb[IFA_LOCAL] == NULL) tb[IFA_LOCAL] = tb[IFA_ADDRESS]; if (tb[IFA_ADDRESS] == NULL) tb[IFA_ADDRESS] = tb[IFA_LOCAL]; /* local interface address */ addr = (tb[IFA_LOCAL] ? RTA_DATA(tb[IFA_LOCAL]) : NULL); if (addr == NULL) return -1; /* If no address is set on interface then set the first time */ if (ifa->ifa_family == AF_INET) { if (!ifp->sin_addr.s_addr) ifp->sin_addr = *(struct in_addr *) addr; } else { if (!ifp->sin6_addr.s6_addr16[0] && ifa->ifa_scope == RT_SCOPE_LINK) ifp->sin6_addr = *(struct in6_addr *) addr; } #ifdef _WITH_LVS_ /* Refresh checkers state */ update_checker_activity(ifa->ifa_family, addr, (h->nlmsg_type == RTM_NEWADDR) ? 1 : 0); #endif return 0; } /* Interfaces lookup bootstrap function */ int netlink_interface_lookup(void) { nl_handle_t nlh; int status = 0; int ret, flags; if (netlink_socket(&nlh, 0) < 0) return -1; /* Set blocking flag */ ret = netlink_set_block(&nlh, &flags); if (ret < 0) log_message(LOG_INFO, "Netlink: Warning, couldn't set " "blocking flag to netlink socket..."); /* Interface lookup */ if (netlink_request(&nlh, AF_PACKET, RTM_GETLINK) < 0) { status = -1; goto end_int; } status = netlink_parse_info(netlink_if_link_filter, &nlh, NULL); end_int: netlink_close(&nlh); return status; } /* Adresses lookup bootstrap function */ static int netlink_address_lookup(void) { nl_handle_t nlh; int status = 0; int ret, flags; if (netlink_socket(&nlh, 0) < 0) return -1; /* Set blocking flag */ ret = netlink_set_block(&nlh, &flags); if (ret < 0) log_message(LOG_INFO, "Netlink: Warning, couldn't set " "blocking flag to netlink socket..."); /* IPv4 Address lookup */ if (netlink_request(&nlh, AF_INET, RTM_GETADDR) < 0) { status = -1; goto end_addr; } status = netlink_parse_info(netlink_if_address_filter, &nlh, NULL); /* IPv6 Address lookup */ if (netlink_request(&nlh, AF_INET6, RTM_GETADDR) < 0) { status = -1; goto end_addr; } status = netlink_parse_info(netlink_if_address_filter, &nlh, NULL); end_addr: netlink_close(&nlh); return status; } /* Netlink flag Link update */ static int netlink_reflect_filter(struct sockaddr_nl *snl, struct nlmsghdr *h) { struct ifinfomsg *ifi; struct rtattr *tb[IFLA_MAX + 1]; interface_t *ifp; int len; ifi = NLMSG_DATA(h); if (!(h->nlmsg_type == RTM_NEWLINK || h->nlmsg_type == RTM_DELLINK)) return 0; len = h->nlmsg_len - NLMSG_LENGTH(sizeof (struct ifinfomsg)); if (len < 0) return -1; /* Interface name lookup */ memset(tb, 0, sizeof (tb)); parse_rtattr(tb, IFLA_MAX, IFLA_RTA(ifi), len); if (tb[IFLA_IFNAME] == NULL) return -1; /* ignore loopback device */ if (ifi->ifi_type == ARPHRD_LOOPBACK) return 0; /* find the interface_t */ ifp = if_get_by_ifindex(ifi->ifi_index); if (!ifp) return -1; /* * Update flags. * VMAC interfaces should never update it own flags, only be reflected * by the base interface flags. */ if (!ifp->vmac) { vmac_reflect_flags(ifi); ifp->flags = ifi->ifi_flags; } return 0; } /* Netlink kernel message reflection */ static int netlink_broadcast_filter(struct sockaddr_nl *snl, struct nlmsghdr *h) { switch (h->nlmsg_type) { case RTM_NEWLINK: case RTM_DELLINK: return netlink_reflect_filter(snl, h); break; case RTM_NEWADDR: case RTM_DELADDR: return netlink_if_address_filter(snl, h); break; default: log_message(LOG_INFO, "Kernel is reflecting an unknown netlink nlmsg_type: %d", h->nlmsg_type); break; } return 0; } int kernel_netlink(thread_t * thread) { nl_handle_t *nl = THREAD_ARG(thread); if (thread->type != THREAD_READ_TIMEOUT) netlink_parse_info(netlink_broadcast_filter, nl, NULL); nl->thread = thread_add_read(master, kernel_netlink, nl, nl->fd, NETLINK_TIMER); return 0; } void kernel_netlink_init(void) { unsigned long groups; /* Start with a netlink address lookup */ netlink_address_lookup(); /* * Prepare netlink kernel broadcast channel * subscribtion. We subscribe to LINK and ADDR * netlink broadcast messages. */ groups = RTMGRP_LINK | RTMGRP_IPV4_IFADDR | RTMGRP_IPV6_IFADDR; netlink_socket(&nl_kernel, groups); if (nl_kernel.fd > 0) { log_message(LOG_INFO, "Registering Kernel netlink reflector"); nl_kernel.thread = thread_add_read(master, kernel_netlink, &nl_kernel, nl_kernel.fd, NETLINK_TIMER); } else log_message(LOG_INFO, "Error while registering Kernel netlink reflector channel"); /* Prepare netlink command channel. */ netlink_socket(&nl_cmd, 0); if (nl_cmd.fd > 0) log_message(LOG_INFO, "Registering Kernel netlink command channel"); else log_message(LOG_INFO, "Error while registering Kernel netlink cmd channel"); } void kernel_netlink_close(void) { netlink_close(&nl_kernel); netlink_close(&nl_cmd); }
Java
using System; using System.Collections.Generic; using System.Text; namespace BarcodeLib.Symbologies { class ISBN : BarcodeCommon, IBarcode { public ISBN(string input) { Raw_Data = input; } /// <summary> /// Encode the raw data using the Bookland/ISBN algorithm. /// </summary> private string Encode_ISBN_Bookland() { if (!BarcodeLib.Barcode.CheckNumericOnly(Raw_Data)) Error("EBOOKLANDISBN-1: Numeric Data Only"); string type = "UNKNOWN"; if (Raw_Data.Length == 10 || Raw_Data.Length == 9) { if (Raw_Data.Length == 10) Raw_Data = Raw_Data.Remove(9, 1); Raw_Data = "978" + Raw_Data; type = "ISBN"; }//if else if (Raw_Data.Length == 12 && Raw_Data.StartsWith("978")) { type = "BOOKLAND-NOCHECKDIGIT"; }//else if else if (Raw_Data.Length == 13 && Raw_Data.StartsWith("978")) { type = "BOOKLAND-CHECKDIGIT"; Raw_Data = Raw_Data.Remove(12, 1); }//else if //check to see if its an unknown type if (type == "UNKNOWN") Error("EBOOKLANDISBN-2: Invalid input. Must start with 978 and be length must be 9, 10, 12, 13 characters."); EAN13 ean13 = new EAN13(Raw_Data); return ean13.Encoded_Value; }//Encode_ISBN_Bookland #region IBarcode Members public string Encoded_Value { get { return Encode_ISBN_Bookland(); } } #endregion } }
Java
/* Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'basicstyles', 'en-gb', { bold: 'Bold', italic: 'Italic', strike: 'Strike Through', subscript: 'Subscript', superscript: 'Superscript', underline: 'Underline' } );
Java
/* * Note: this file originally auto-generated by mib2c using * : mib2c.int_watch.conf 13957 2005-12-20 15:33:08Z tanders $ */ #include <net-snmp/net-snmp-config.h> #include <net-snmp/net-snmp-includes.h> #include <net-snmp/agent/net-snmp-agent-includes.h> #include "statPPTP.h" #include "triton.h" /* * The variables we want to tie the relevant OIDs to. * The agent will handle all GET and (if applicable) SET requests * to these variables automatically, changing the values as needed. */ void pptp_get_stat(unsigned int **, unsigned int **); static unsigned int *stat_starting; static unsigned int *stat_active; /* * Our initialization routine, called automatically by the agent * (Note that the function name must match init_FILENAME()) */ void init_statPPTP(void) { netsnmp_handler_registration *reg; netsnmp_watcher_info *winfo; static oid statPPTPStarting_oid[] = { 1,3,6,1,4,1,8072,100,1,3,1 }; static oid statPPTPActive_oid[] = { 1,3,6,1,4,1,8072,100,1,3,2 }; /* * a debugging statement. Run the agent with -DstatPPTP to see * the output of this debugging statement. */ DEBUGMSGTL(("statPPTP", "Initializing the statPPTP module\n")); if (!triton_module_loaded("pptp")) return; pptp_get_stat(&stat_starting, &stat_active); /* * Register scalar watchers for each of the MIB objects. * The ASN type and RO/RW status are taken from the MIB definition, * but can be adjusted if needed. * * In most circumstances, the scalar watcher will handle all * of the necessary processing. But the NULL parameter in the * netsnmp_create_handler_registration() call can be used to * supply a user-provided handler if necessary. * * This approach can also be used to handle Counter64, string- * and OID-based watched scalars (although variable-sized writeable * objects will need some more specialised initialisation). */ DEBUGMSGTL(("statPPTP", "Initializing statPPTPStarting scalar integer. Default value = %d\n", 0)); reg = netsnmp_create_handler_registration( "statPPTPStarting", NULL, statPPTPStarting_oid, OID_LENGTH(statPPTPStarting_oid), HANDLER_CAN_RONLY); winfo = netsnmp_create_watcher_info( stat_starting, sizeof(*stat_starting), ASN_INTEGER, WATCHER_FIXED_SIZE); if (netsnmp_register_watched_scalar( reg, winfo ) < 0 ) { snmp_log( LOG_ERR, "Failed to register watched statPPTPStarting" ); } DEBUGMSGTL(("statPPTP", "Initializing statPPTPActive scalar integer. Default value = %d\n", 0)); reg = netsnmp_create_handler_registration( "statPPTPActive", NULL, statPPTPActive_oid, OID_LENGTH(statPPTPActive_oid), HANDLER_CAN_RONLY); winfo = netsnmp_create_watcher_info( stat_active, sizeof(*stat_active), ASN_INTEGER, WATCHER_FIXED_SIZE); if (netsnmp_register_watched_scalar( reg, winfo ) < 0 ) { snmp_log( LOG_ERR, "Failed to register watched statPPTPActive" ); } DEBUGMSGTL(("statPPTP", "Done initalizing statPPTP module\n")); }
Java
.ultb3-box { width: 100%; display: block; position: relative; background: #f2f2f2; overflow: hidden } img.ultb3-img { border: 0; -webkit-box-shadow: none; box-shadow: none; max-width: none; width: auto !important; float: none; margin: 0 auto; display: block; position: absolute; z-index: 1; -webkit-transition: all 300ms linear; transition: all 300ms linear } .ultb3-box-overlay { background: rgba(0, 0, 0, 0.5); position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 2 } .ultb3-info { padding: 25px; position: relative; z-index: 5 } .ultb3-info.ib3-info-center { text-align: center } .ultb3-info.ib3-info-right { text-align: right } img.ultb3-img.ultb3-img-top-center { left: 50%; -webkit-transform: translateX(-50%); -ms-transform: translateX(-50%); transform: translateX(-50%) } img.ultb3-img.ultb3-img-top-right { left: auto; right: 0 } img.ultb3-img.ultb3-img-center-left { top: 50%; -webkit-transform: translateY(-50%); -ms-transform: translateY(-50%); transform: translateY(-50%) } img.ultb3-img.ultb3-img-center { top: 50%; left: 50%; -webkit-transform: translate(-50%, -50%); -ms-transform: translate(-50%, -50%); transform: translate(-50%, -50%) } img.ultb3-img.ultb3-img-center-right { top: 50%; -webkit-transform: translateY(-50%); -ms-transform: translateY(-50%); transform: translateY(-50%); left: auto; right: 0 } img.ultb3-img.ultb3-img-bottom-left, img.ultb3-img.ultb3-img-bottom-center, img.ultb3-img.ultb3-img-bottom-right { top: auto; bottom: 0 } img.ultb3-img.ultb3-img-bottom-center { left: 50%; -webkit-transform: translateX(-50%); -ms-transform: translateX(-50%); transform: translateX(-50%) } img.ultb3-img.ultb3-img-bottom-right { right: 0; left: auto } .ultb3-title { font-size: 40px; color: #252525; line-height: 1.35em; margin-bottom: 5px } .ultb3-desc { font-size: 20px; line-height: 1.5em; margin-bottom: 10px } a.ultb3-btn { display: inline-block; color: #0483d9; text-align: center; font-size: 20px; padding: 15px 25px; -webkit-border-radius: 30px; border-radius: 30px; border: 2px solid #0483d9; position: relative; text-decoration: none; -webkit-transition: all .2s; transition: all .2s } a.ultb3-btn i { position: absolute; left: auto; right: 25px; top: 50%; opacity: 0; width: auto; height: auto; font-size: inherit !important; -webkit-transition: all .25s; transition: all .25s; -webkit-transform: translate(0, -50%); -ms-transform: translate(0, -50%); transform: translate(0, -50%) } a.ultb3-btn:hover i { right: 20px; opacity: 1 } a.ultb3-btn:hover { padding-right: 45px } a.ultb3-btn:hover; a.ultb3-btn:focus; a.ultb3-btn:active; a.ultb3-btn:visited { text-decoration: none; color: inherit; outline: 0 } .ultb3-hover-1 .ultb3-img.ultb3-img-top-left, .ultb3-hover-1 .ultb3-img.ultb3-img-top-center, .ultb3-hover-1 .ultb3-img.ultb3-img-top-right { top: -50px } .ultb3-hover-1:hover .ultb3-img.ultb3-img-top-left, .ultb3-hover-1:hover .ultb3-img.ultb3-img-top-center, .ultb3-hover-1:hover .ultb3-img.ultb3-img-top-right { top: 0 } .ultb3-hover-1 .ultb3-img.ultb3-img-center-left { -webkit-transform: translateY(-50%); -ms-transform: translateY(-50%); transform: translateY(-50%) } .ultb3-hover-1:hover .ultb3-img.ultb3-img-center-left { -webkit-transform: translateY(-25%); -ms-transform: translateY(-25%); transform: translateY(-25%) } .ultb3-hover-1 .ultb3-img.ultb3-img-center { -webkit-transform: translate(-50%, -50%); -ms-transform: translate(-50%, -50%); transform: translate(-50%, -50%) } .ultb3-hover-1:hover .ultb3-img.ultb3-img-center { -webkit-transform: translate(-50%, -25%); -ms-transform: translate(-50%, -25%); transform: translate(-50%, -25%) } .ultb3-hover-1 .ultb3-img.ultb3-img-center-right { -webkit-transform: translateY(-50%); -ms-transform: translateY(-50%); transform: translateY(-50%) } .ultb3-hover-1:hover .ultb3-img.ultb3-img-center-right { -webkit-transform: translateY(-25%); -ms-transform: translateY(-25%); transform: translateY(-25%) } .ultb3-hover-1 .ultb3-img.ultb3-img-bottom-left, .ultb3-hover-1 .ultb3-img.ultb3-img-bottom-center, .ultb3-hover-1 .ultb3-img.ultb3-img-bottom-right { bottom: 0 } .ultb3-hover-1:hover .ultb3-img.ultb3-img-bottom-left, .ultb3-hover-1:hover .ultb3-img.ultb3-img-bottom-center, .ultb3-hover-1:hover .ultb3-img.ultb3-img-bottom-right { bottom: -50px } .ultb3-hover-2 .ultb3-img.ultb3-img-top-left, .ultb3-hover-2 .ultb3-img.ultb3-img-top-center, .ultb3-hover-2 .ultb3-img.ultb3-img-top-right { top: 0 } .ultb3-hover-2:hover .ultb3-img.ultb3-img-top-left, .ultb3-hover-2:hover .ultb3-img.ultb3-img-top-center, .ultb3-hover-2:hover .ultb3-img.ultb3-img-top-right { top: -50px } .ultb3-hover-2 .ultb3-img.ultb3-img-center-left { -webkit-transform: translateY(-50%); -ms-transform: translateY(-50%); transform: translateY(-50%) } .ultb3-hover-2:hover .ultb3-img.ultb3-img-center-left { -webkit-transform: translateY(-75%); -ms-transform: translateY(-75%); transform: translateY(-75%) } .ultb3-hover-2 .ultb3-img.ultb3-img-center { -webkit-transform: translate(-50%, -50%); -ms-transform: translate(-50%, -50%); transform: translate(-50%, -50%) } .ultb3-hover-2:hover .ultb3-img.ultb3-img-center { -webkit-transform: translate(-50%, -75%); -ms-transform: translate(-50%, -75%); transform: translate(-50%, -75%) } .ultb3-hover-2 .ultb3-img.ultb3-img-center-right { -webkit-transform: translateY(-50%); -ms-transform: translateY(-50%); transform: translateY(-50%) } .ultb3-hover-2:hover .ultb3-img.ultb3-img-center-right { -webkit-transform: translateY(-75%); -ms-transform: translateY(-75%); transform: translateY(-75%) } .ultb3-hover-2 .ultb3-img.ultb3-img-bottom-left, .ultb3-hover-2 .ultb3-img.ultb3-img-bottom-center, .ultb3-hover-2 .ultb3-img.ultb3-img-bottom-right { bottom: -50px } .ultb3-hover-2:hover .ultb3-img.ultb3-img-bottom-left, .ultb3-hover-2:hover .ultb3-img.ultb3-img-bottom-center, .ultb3-hover-2:hover .ultb3-img.ultb3-img-bottom-right { bottom: 0 } .ultb3-hover-3 .ultb3-img.ultb3-img-top-left, .ultb3-hover-3 .ultb3-img.ultb3-img-center-left { left: 0 } .ultb3-hover-3:hover .ultb3-img.ultb3-img-top-left, .ultb3-hover-3:hover .ultb3-img.ultb3-img-center-left { left: -50px } .ultb3-hover-3 .ultb3-img.ultb3-img-top-center { -webkit-transform: translateX(-25%); -ms-transform: translateX(-25%); transform: translateX(-25%) } .ultb3-hover-3:hover .ultb3-img.ultb3-img-top-center { -webkit-transform: translateX(-50%); -ms-transform: translateX(-50%); transform: translateX(-50%) } .ultb3-hover-3 .ultb3-img.ultb3-img-top-right, .ultb3-hover-3 .ultb3-img.ultb3-img-bottom-right { right: -50px } .ultb3-hover-3:hover .ultb3-img.ultb3-img-top-right, .ultb3-hover-3:hover .ultb3-img.ultb3-img-bottom-right { right: 0 } .ultb3-hover-3 .ultb3-img.ultb3-img-center { -webkit-transform: translate(-50%, -50%); -ms-transform: translate(-50%, -50%); transform: translate(-50%, -50%) } .ultb3-hover-3:hover .ultb3-img.ultb3-img-center { -webkit-transform: translate(-75%, -50%); -ms-transform: translate(-75%, -50%); transform: translate(-75%, -50%) } .ultb3-hover-3 .ultb3-img.ultb3-img-center-right { -webkit-transform: translate(25%, -50%); -ms-transform: translate(25%, -50%); transform: translate(25%, -50%) } .ultb3-hover-3:hover .ultb3-img.ultb3-img-center-right { -webkit-transform: translate(0, -50%); -ms-transform: translate(0, -50%); transform: translate(0, -50%) } .ultb3-hover-3 .ultb3-img.ultb3-img-bottom-left { left: 0 } .ultb3-hover-3:hover .ultb3-img.ultb3-img-bottom-left { left: -50px } .ultb3-hover-3 .ultb3-img.ultb3-img-bottom-center { -webkit-transform: translate(-50%); -ms-transform: translate(-50%); transform: translate(-50%) } .ultb3-hover-3:hover .ultb3-img.ultb3-img-bottom-center { -webkit-transform: translate(-75%); -ms-transform: translate(-75%); transform: translate(-75%) } .ultb3-hover-4 .ultb3-img.ultb3-img-top-left, .ultb3-hover-4 .ultb3-img.ultb3-img-center-left { left: -50px } .ultb3-hover-4:hover .ultb3-img.ultb3-img-top-left, .ultb3-hover-4:hover .ultb3-img.ultb3-img-center-left { left: 0 } .ultb3-hover-4 .ultb3-img.ultb3-img-top-center { -webkit-transform: translateX(-75%); -ms-transform: translateX(-75%); transform: translateX(-75%) } .ultb3-hover-4:hover .ultb3-img.ultb3-img-top-center { -webkit-transform: translateX(-50%); -ms-transform: translateX(-50%); transform: translateX(-50%) } .ultb3-hover-4 .ultb3-img.ultb3-img-top-right, .ultb3-hover-4 .ultb3-img.ultb3-img-bottom-right { right: 0 } .ultb3-hover-4:hover .ultb3-img.ultb3-img-top-right, .ultb3-hover-4:hover .ultb3-img.ultb3-img-bottom-right { right: -50px } .ultb3-hover-4 .ultb3-img.ultb3-img-center { -webkit-transform: translate(-50%, -50%); -ms-transform: translate(-50%, -50%); transform: translate(-50%, -50%) } .ultb3-hover-4:hover .ultb3-img.ultb3-img-center { -webkit-transform: translate(-25%, -50%); -ms-transform: translate(-25%, -50%); transform: translate(-25%, -50%) } .ultb3-hover-4 .ultb3-img.ultb3-img-center-right { -webkit-transform: translate(0, -50%); -ms-transform: translate(0, -50%); transform: translate(0, -50%) } .ultb3-hover-4:hover .ultb3-img.ultb3-img-center-right { -webkit-transform: translate(25%, -50%); -ms-transform: translate(25%, -50%); transform: translate(25%, -50%) } .ultb3-hover-4 .ultb3-img.ultb3-img-bottom-left { left: -50px } .ultb3-hover-4:hover .ultb3-img.ultb3-img-bottom-left { left: 0 } .ultb3-hover-4 .ultb3-img.ultb3-img-bottom-center { -webkit-transform: translate(-50%); -ms-transform: translate(-50%); transform: translate(-50%) } .ultb3-hover-4:hover .ultb3-img.ultb3-img-bottom-center { transform: translate(-25%); -webkit-transform: translate(-25%); -moz-transform: translate(-25%); -ms-transform: translate(-25%); -o-transform: translate(-25%) } .ultb3-hover-5 .ultb3-img { -webkit-transform: scale(1); -ms-transform: scale(1); transform: scale(1) } .ultb3-hover-5:hover .ultb3-img { -webkit-transform: scale(1.1); -ms-transform: scale(1.1); transform: scale(1.1) } .ultb3-hover-6 .ultb3-img { -webkit-transform: scale(1); -ms-transform: scale(1); transform: scale(1); opacity: 1 } .ultb3-hover-6:hover .ultb3-img { -webkit-transform: scale(2.5); -ms-transform: scale(2.5); transform: scale(2.5); opacity: 0 }
Java
/* * #%L * Fork of MDB Tools (Java port). * %% * Copyright (C) 2008 - 2013 Open Microscopy Environment: * - Board of Regents of the University of Wisconsin-Madison * - Glencoe Software, Inc. * - University of Dundee * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This 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 Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ /* * Created on Jan 14, 2005 * * TODO To change the template for this generated file go to * Window - Preferences - Java - Code Style - Code Templates */ package mdbtools.libmdb06util; /** * @author calvin * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class mdbver { public static void main(String[] args) { } }
Java
/* * Copyright 1999-2001 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code 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 code 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 work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. * */ class Optimizer VALUE_OBJ_CLASS_SPEC { private: IR* _ir; public: Optimizer(IR* ir); IR* ir() const { return _ir; } // optimizations void eliminate_conditional_expressions(); void eliminate_blocks(); void eliminate_null_checks(); };
Java
namespace Server.Items { public class DestroyingAngel : BaseReagent, ICommodity { int ICommodity.DescriptionNumber { get { return LabelNumber; } } bool ICommodity.IsDeedable { get { return true; } } [Constructable] public DestroyingAngel() : this( 1 ) { } [Constructable] public DestroyingAngel( int amount ) : base( 0xE1F ) { Stackable = true; Weight = 0.0; Amount = amount; Name = "Destroying Angel"; Hue = 0x290; } public DestroyingAngel( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); } } public class PetrafiedWood : BaseReagent, ICommodity { int ICommodity.DescriptionNumber { get { return LabelNumber; } } bool ICommodity.IsDeedable { get { return true; } } [Constructable] public PetrafiedWood() : this( 1 ) { } [Constructable] public PetrafiedWood( int amount ) : base( 0x97A ) { Stackable = true; Weight = 0.0; Amount = amount; Name = "Petrafied Wood"; Hue = 0x46C; } public PetrafiedWood( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); } } public class SpringWater : BaseReagent, ICommodity { int ICommodity.DescriptionNumber { get { return LabelNumber; } } bool ICommodity.IsDeedable { get { return true; } } [Constructable] public SpringWater() : this( 1 ) { } [Constructable] public SpringWater( int amount ) : base( 0xE24 ) { Stackable = true; Weight = 0.0; Amount = amount; Name = "Spring Water"; Hue = 0x47F; } public SpringWater( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); } } }
Java
/** * Drupal-specific JS helper functions and utils. Not to be confused with the * Recline library, which should live in your libraries directory. */ ;(function ($) { // Constants. var MAX_LABEL_WIDTH = 77; var LABEL_MARGIN = 5; // Undefined variables. var dataset, views, datasetOptions, fileSize, fileType, router; var dataExplorerSettings, state, $explorer, dataExplorer, maxSizePreview; var datastoreStatus; // Create drupal behavior Drupal.behaviors.Recline = { attach: function (context) { $explorer = $('.data-explorer'); // Local scoped variables. Drupal.settings.recline = Drupal.settings.recline || {}; fileSize = Drupal.settings.recline.fileSize; fileType = Drupal.settings.recline.fileType; maxSizePreview = Drupal.settings.recline.maxSizePreview; datastoreStatus = Drupal.settings.recline.datastoreStatus; dataExplorerSettings = { grid: Drupal.settings.recline.grid, graph: Drupal.settings.recline.graph, map: Drupal.settings.recline.map }; // This is the very basic state collection. state = recline.View.parseQueryString(decodeURIComponent(window.location.hash)); if ('#map' in state) { state.currentView = 'map'; } else if ('#graph' in state) { state.currentView = 'graph'; } // Init the explorer. init(); // Attach toogle event. $('.recline-embed a.embed-link').on('click', function(){ $(this).parents('.recline-embed').find('.embed-code-wrapper').toggle(); return false; }); } } // make Explorer creation / initialization in a function so we can call it // again and again function createExplorer (dataset, state, settings) { // Remove existing data explorer view. dataExplorer && dataExplorer.remove(); var $el = $('<div />'); $el.appendTo($explorer); var views = []; if (settings.grid) { views.push({ id: 'grid', label: 'Grid', view: new recline.View.SlickGrid({ model: dataset }) }); } if (settings.graph) { state.graphOptions = { xaxis: { tickFormatter: tickFormatter(dataset), }, hooks:{ processOffset: [processOffset(dataset)], bindEvents: [bindEvents], } }; views.push({ id: 'graph', label: 'Graph', view: new recline.View.Graph({ model: dataset, state: state }) }); } if (settings.map) { views.push({ id: 'map', label: 'Map', view: new recline.View.Map({ model: dataset, options: { mapTilesURL: '//stamen-tiles-{s}.a.ssl.fastly.net/terrain/{z}/{x}/{y}.png', } }) }); } // Multiview settings var multiviewOptions = { model: dataset, el: $el, state: state, views: views }; // Getting base embed url. var urlBaseEmbed = $('.embed-code').text(); var iframeOptions = {src: urlBaseEmbed, width:850, height:400}; // Attaching router to dataexplorer state. dataExplorer = new recline.View.MultiView(multiviewOptions); router = new recline.DeepLink.Router(dataExplorer); // Adding router listeners. var changeEmbedCode = getEmbedCode(iframeOptions); router.on('init', changeEmbedCode); router.on('stateChange', changeEmbedCode); // Add map dependency just for map views. _.each(dataExplorer.pageViews, function(item, index){ if(item.id && item.id === 'map'){ var map = dataExplorer.pageViews[index].view.map; router.addDependency(new recline.DeepLink.Deps.Map(map, router)); } }); // Start to track state chages. router.start(); $.event.trigger('createDataExplorer'); return views; } // Returns the dataset configuration. function getDatasetOptions () { var datasetOptions = {}; var delimiter = Drupal.settings.recline.delimiter; var file = Drupal.settings.recline.file; var uuid = Drupal.settings.recline.uuid; // Get correct file location, make sure not local file = (getOrigin(window.location) !== getOrigin(file)) ? '/node/' + Drupal.settings.recline.uuid + '/data' : file; // Select the backend to use switch(getBackend(datastoreStatus, fileType)) { case 'csv': datasetOptions = { backend: 'csv', url: file, delimiter: delimiter }; break; case 'tsv': datasetOptions = { backend: 'csv', url: file, delimiter: delimiter }; break; case 'txt': datasetOptions = { backend: 'csv', url: file, delimiter: delimiter }; break; case 'ckan': datasetOptions = { endpoint: 'api', id: uuid, backend: 'ckan' }; break; case 'xls': datasetOptions = { backend: 'xls', url: file }; break; case 'dataproxy': datasetOptions = { url: file, backend: 'dataproxy' }; break; default: showError('File type ' + fileType + ' not supported for preview.'); break; } return datasetOptions; } // Correct for fact that IE does not provide .origin function getOrigin(u) { var url = parseURL(u); return url.protocol + '//' + url.hostname + (url.port ? (':' + url.port) : ''); } // Parse a simple URL string to get its properties function parseURL(url) { var parser = document.createElement('a'); parser.href = url; return { protocol: parser.protocol, hostname: parser.hostname, port: parser.port, pathname: parser.pathname, search: parser.search, hash: parser.hash, host: parser.host } } // Retrieve a backend given a file type and and a datastore status. function getBackend (datastoreStatus, fileType) { // If it's inside the datastore then we use the dkan API if (datastoreStatus) return 'ckan'; var formats = { 'csv': ['text/csv', 'csv'], 'xls': ['application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'], 'tsv': ['text/tab-separated-values', 'text/tsv', 'tsv', 'tab'], 'txt': ['text/plain', 'txt'], }; var backend = _.findKey(formats, function(format) { return _.include(format, fileType) }); // If the backend is a txt but the delimiter is not a tab, we don't need // to show it using the backend. if (Drupal.settings.recline.delimiter !== "\t" && backend === 'txt') {return '';} // If the backend is an xls but the browser version is prior 9 then // we need to fallback to dataproxy if (backend === 'xls' && document.documentMode < 9) return 'dataproxy'; return backend; } // Displays an error retrieved from the response object. function showRequestError (response) { // Actually dkan doesn't provide standarization over // error handling responses. For example: if you request // unexistent resources it will retrive an array with a // message inside. // Recline backends will return an object with an error. try { var ro = (typeof response === 'string') ? JSON.parse(response) : response; if(ro.error) { showError(ro.error.message) } else if(ro instanceof Array) { showError(ro[0]); } } catch (error) { showError(response); } } // Displays an error. function showError (message) { $explorer.html('<div class="messages error">' + message + '</div>'); } // Creates the embed code. function getEmbedCode (options){ return function(state){ var iframeOptions = _.clone(options); var iframeTmpl = _.template('<iframe width="<%= width %>" height="<%= height %>" src="<%= src %>" frameborder="0"></iframe>'); var previewTmpl = _.template('<%= src %>'); _.extend(iframeOptions, {src: iframeOptions.src + '#' + (state.serializedState || '')}); var html = iframeTmpl(iframeOptions); $('.embed-code').text(html); var preview = previewTmpl(iframeOptions); $('.preview-code').text(preview); }; } // Creates the preview url code. function getPreviewCode (options){ return function(state){ var previewOptions = _.clone(options); var previewTmpl = _.template('<%= src %>'); _.extend(previewOptions, {src: previewOptions.src + '#' + (state.serializedState || '')}); var html = previewTmpl(previewOptions); $('.preview-url').text(html); }; } // Check if a chart has their axis inverted. function isInverted (){ return dataExplorer.pageViews[1].view.state.attributes.graphType === 'bars'; } // Computes the width of a chart. function computeWidth (plot, labels) { var biggerLabel = ''; for( var i = 0; i < labels.length; i++){ if(labels[i].length > biggerLabel.length && !_.isUndefined(labels[i])){ biggerLabel = labels[i]; } } var canvas = plot.getCanvas(); var ctx = canvas.getContext('2d'); ctx.font = 'sans-serif smaller'; return ctx.measureText(biggerLabel).width; } // Resize a chart. function resize (plot) { var itemWidth = computeWidth(plot, _.pluck(plot.getXAxes()[0].ticks, 'label')); var graph = dataExplorer.pageViews[1]; if(!isInverted() && $('#prevent-label-overlapping').is(':checked')){ var canvasWidth = Math.min(itemWidth + LABEL_MARGIN, MAX_LABEL_WIDTH) * plot.getXAxes()[0].ticks.length; var canvasContainerWith = $('.panel.graph').parent().width(); if(canvasWidth < canvasContainerWith){ canvasWidth = canvasContainerWith; } $('.panel.graph').width(canvasWidth); $('.recline-flot').css({overflow:'auto'}); }else{ $('.recline-flot').css({overflow:'hidden'}); $('.panel.graph').css({width: '100%'}); } plot.resize(); plot.setupGrid(); plot.draw(); } // Bind events after chart resizes. function bindEvents (plot, eventHolder) { var p = plot || dataExplorer.pageViews[1].view.plot; resize(p); setTimeout(addCheckbox, 0); } // Compute the chart offset to display ticks properly. function processOffset (dataset) { return function(plot, offset) { if(dataExplorer.pageViews[1].view.xvaluesAreIndex){ var series = plot.getData(); for (var i = 0; i < series.length; i++) { var numTicks = Math.min(dataset.records.length, 200); var ticks = []; for (var j = 0; j < dataset.records.length; j++) { ticks.push(parseInt(j, 10)); } if(isInverted()){ series[i].yaxis.options.ticks = ticks; }else{ series[i].xaxis.options.ticks = ticks; } } } }; } // Format ticks base on previews computations. function tickFormatter (dataset){ return function (x) { x = parseInt(x, 10); try { if(isInverted()) return x; var field = dataExplorer.pageViews[1].view.state.get('group'); var label = dataset.records.models[x].get(field) || ''; if(!moment(String(label)).isValid() && !isNaN(parseInt(label, 10))){ label = parseInt(label, 10) - 1; } return label; } catch(e) { return x; } }; } // Add checkbox to control resize behavior. function addCheckbox () { $control = $('.form-stacked:visible').find('#prevent-label-overlapping'); if(!$control.length){ $form = $('.form-stacked'); $checkboxDiv = $('<div class="checkbox"></div>').appendTo($form); $label = $('<label />', { 'for': 'prevent-label-overlapping', text: 'Resize graph to prevent label overlapping' }).appendTo($checkboxDiv); $label.prepend($('<input />', { type: 'checkbox', id: 'prevent-label-overlapping', value: '' })); $control = $('#prevent-label-overlapping'); $control.on('change', function(){ resize(dataExplorer.pageViews[1].view.plot); }); } } // Init the multiview. function init () { if(fileSize < maxSizePreview || datastoreStatus) { dataset = new recline.Model.Dataset(getDatasetOptions()); dataset.fetch().fail(showRequestError); views = createExplorer(dataset, state, dataExplorerSettings); views.forEach(function(view) { view.id === 'map' && view.view.redraw('refresh') }); } else { showError('File was too large or unavailable for preview.'); } } })(jQuery);
Java
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <meta http-equiv="refresh" content="0;url=help.php?module=questionnaire&amp;file=fieldlength.html" /> <title>redirect</title> </head> <body> <p> しばらくお待ち下さい。 </p> </body> </html>
Java
/* * Copyright (C) 2011-2012 Freescale Semiconductor, Inc. All Rights Reserved. */ /* * Modifyed by: Edison Fernández <[email protected]> * Added support to use it with Nitrogen6x * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * */ #include <linux/module.h> #include <linux/init.h> #include <linux/slab.h> #include <linux/ctype.h> #include <linux/types.h> #include <linux/delay.h> #include <linux/device.h> #include <linux/clk.h> #include <linux/i2c.h> #include <linux/mfd/syscon.h> #include <linux/mfd/syscon/imx6q-iomuxc-gpr.h> #include <linux/of_gpio.h> #include <linux/regulator/consumer.h> #include <linux/fsl_devices.h> #include <linux/mutex.h> #include <linux/mipi_csi2.h> #include <linux/pwm.h> #include <media/v4l2-chip-ident.h> #include <media/v4l2-int-device.h> #include <sound/core.h> #include <sound/pcm.h> #include <sound/soc.h> #include <sound/jack.h> #include <sound/soc-dapm.h> #include <asm/mach-types.h> //#include <mach/audmux.h> #include <linux/slab.h> #include "mxc_v4l2_capture.h" #define CODEC_CLOCK 16500000 /* SSI clock sources */ #define IMX_SSP_SYS_CLK 0 #define TC358743_VOLTAGE_ANALOG 2800000 #define TC358743_VOLTAGE_DIGITAL_CORE 1500000 #define TC358743_VOLTAGE_DIGITAL_IO 1800000 #define MIN_FPS 30 #define MAX_FPS 60 #define DEFAULT_FPS 60 #define TC358743_XCLK_MIN 27000000 #define TC358743_XCLK_MAX 42000000 #define TC358743_CHIP_ID_HIGH_BYTE 0x0 #define TC358743_CHIP_ID_LOW_BYTE 0x0 #define TC3587430_HDMI_DETECT 0x0f //0x10 #define TC_VOLTAGE_ANALOG 2800000 #define TC_VOLTAGE_DIGITAL_CORE 1500000 #define TC_VOLTAGE_DIGITAL_IO 1800000 enum tc358743_mode { tc358743_mode_INIT, /*only for sensor init*/ tc358743_mode_INIT1, /*only for sensor init*/ tc358743_mode_480P_720_480, tc358743_mode_720P_60_1280_720, tc358743_mode_480P_640_480, tc358743_mode_1080P_1920_1080, tc358743_mode_INIT2, /*only for sensor init*/ tc358743_mode_INIT3, /*only for sensor init*/ tc358743_mode_INIT4, /*only for sensor init*/ tc358743_mode_INIT5, /*only for sensor init*/ tc358743_mode_INIT6, /*only for sensor init*/ tc358743_mode_720P_1280_720, tc358743_mode_MAX , }; enum tc358743_frame_rate { tc358743_60_fps, tc358743_30_fps, tc358743_max_fps }; struct reg_value { u16 u16RegAddr; u32 u32Val; u32 u32Mask; u8 u8Length; u32 u32Delay_ms; }; struct tc358743_mode_info { enum tc358743_mode mode; u32 width; u32 height; u32 vformat; u32 fps; u32 lanes; u32 freq; struct reg_value *init_data_ptr; u32 init_data_size; __u32 flags; }; static struct delayed_work det_work; static struct sensor_data tc358743_data; static int pwn_gpio, rst_gpio; static struct regulator *io_regulator; static struct regulator *core_regulator; static struct regulator *analog_regulator; static struct regulator *gpo_regulator; static u16 hpd_active = 1; #define DET_WORK_TIMEOUT_DEFAULT 100 #define DET_WORK_TIMEOUT_DEFERRED 2000 #define MAX_BOUNCE 5 static DEFINE_MUTEX(access_lock); static int det_work_disable = 0; static int det_work_timeout = DET_WORK_TIMEOUT_DEFAULT; static u32 hdmi_mode = 0, lock = 0, bounce = 0, fps = 0, audio = 2; static int tc358743_init_mode(enum tc358743_frame_rate frame_rate, enum tc358743_mode mode); static int tc358743_toggle_hpd(int active); static void tc_standby(s32 enable) { if (gpio_is_valid(pwn_gpio)) gpio_set_value(pwn_gpio, enable ? 1 : 0); pr_debug("tc_standby: powerdown=%x, power_gp=0x%x\n", enable, pwn_gpio); msleep(2); } static void tc_reset(void) { /* camera reset */ gpio_set_value(rst_gpio, 1); /* camera power dowmn */ if (gpio_is_valid(pwn_gpio)) { gpio_set_value(pwn_gpio, 1); msleep(5); gpio_set_value(pwn_gpio, 0); } msleep(5); gpio_set_value(rst_gpio, 0); msleep(1); gpio_set_value(rst_gpio, 1); msleep(20); if (gpio_is_valid(pwn_gpio)) gpio_set_value(pwn_gpio, 1); } static int tc_power_on(struct device *dev) { int ret = 0; io_regulator = devm_regulator_get(dev, "DOVDD"); if (!IS_ERR(io_regulator)) { regulator_set_voltage(io_regulator, TC_VOLTAGE_DIGITAL_IO, TC_VOLTAGE_DIGITAL_IO); ret = regulator_enable(io_regulator); if (ret) { pr_err("%s:io set voltage error\n", __func__); return ret; } else { dev_dbg(dev, "%s:io set voltage ok\n", __func__); } } else { pr_err("%s: cannot get io voltage error\n", __func__); io_regulator = NULL; } core_regulator = devm_regulator_get(dev, "DVDD"); if (!IS_ERR(core_regulator)) { regulator_set_voltage(core_regulator, TC_VOLTAGE_DIGITAL_CORE, TC_VOLTAGE_DIGITAL_CORE); ret = regulator_enable(core_regulator); if (ret) { pr_err("%s:core set voltage error\n", __func__); return ret; } else { dev_dbg(dev, "%s:core set voltage ok\n", __func__); } } else { core_regulator = NULL; pr_err("%s: cannot get core voltage error\n", __func__); } analog_regulator = devm_regulator_get(dev, "AVDD"); if (!IS_ERR(analog_regulator)) { regulator_set_voltage(analog_regulator, TC_VOLTAGE_ANALOG, TC_VOLTAGE_ANALOG); ret = regulator_enable(analog_regulator); if (ret) { pr_err("%s:analog set voltage error\n", __func__); return ret; } else { dev_dbg(dev, "%s:analog set voltage ok\n", __func__); } } else { analog_regulator = NULL; pr_err("%s: cannot get analog voltage error\n", __func__); } return ret; } static void det_work_enable(int i) { mutex_lock(&access_lock); if (i) { det_work_timeout = DET_WORK_TIMEOUT_DEFERRED; schedule_delayed_work(&(det_work), msecs_to_jiffies(det_work_timeout)); det_work_disable = 0; } else { det_work_disable = 1; det_work_timeout = DET_WORK_TIMEOUT_DEFERRED; } mutex_unlock(&access_lock); pr_debug("%s: %d %d\n", __func__, det_work_disable, det_work_timeout); } static u8 cHDMIEDID[256] = { /* FIXME! This is the edid that my ASUS HDMI monitor returns */ 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x04, 0x69, 0xf3, 0x24, 0xd6, 0x12, 0x00, 0x00, 0x16, 0x16, 0x01, 0x03, 0x80, 0x34, 0x1d, 0x78, 0x2a, 0xc7, 0x20, 0xa4, 0x55, 0x49, 0x99, 0x27, 0x13, 0x50, 0x54, 0xbf, 0xef, 0x00, 0x71, 0x4f, 0x81, 0x40, 0x81, 0x80, 0x95, 0x00, 0xb3, 0x00, 0xd1, 0xc0, 0x01, 0x01, 0x01, 0x01, 0x02, 0x3a, 0x80, 0x18, 0x71, 0x38, 0x2d, 0x40, 0x58, 0x2c, 0x45, 0x00, 0x09, 0x25, 0x21, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x00, 0xff, 0x00, 0x43, 0x36, 0x4c, 0x4d, 0x54, 0x46, 0x30, 0x30, 0x34, 0x38, 0x32, 0x32, 0x0a, 0x00, 0x00, 0x00, 0xfd, 0x00, 0x37, 0x4b, 0x1e, 0x55, 0x10, 0x00, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x00, 0x00, 0x00, 0xfc, 0x00, 0x41, 0x53, 0x55, 0x53, 0x20, 0x56, 0x48, 0x32, 0x34, 0x32, 0x48, 0x0a, 0x20, 0x01, 0x78, 0x02, 0x03, 0x22, 0x71, 0x4f, 0x01, 0x02, 0x03, 0x11, 0x12, 0x13, 0x04, 0x14, 0x05, 0x0e, 0x0f, 0x1d, 0x1e, 0x1f, 0x10, 0x23, 0x09, 0x07, 0x01, 0x83, 0x01, 0x00, 0x00, 0x65, 0x03, 0x0c, 0x00, 0x10, 0x00, 0x8c, 0x0a, 0xd0, 0x8a, 0x20, 0xe0, 0x2d, 0x10, 0x10, 0x3e, 0x96, 0x00, 0x09, 0x25, 0x21, 0x00, 0x00, 0x18, 0x01, 0x1d, 0x00, 0x72, 0x51, 0xd0, 0x1e, 0x20, 0x6e, 0x28, 0x55, 0x00, 0x09, 0x25, 0x21, 0x00, 0x00, 0x1e, 0x01, 0x1d, 0x00, 0xbc, 0x52, 0xd0, 0x1e, 0x20, 0xb8, 0x28, 0x55, 0x40, 0x09, 0x25, 0x21, 0x00, 0x00, 0x1e, 0x8c, 0x0a, 0xd0, 0x90, 0x20, 0x40, 0x31, 0x20, 0x0c, 0x40, 0x55, 0x00, 0x09, 0x25, 0x21, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x73, }; /*! * Maintains the information on the current state of the sesor. */ static struct reg_value tc358743_setting_YUV422_2lane_30fps_720P_1280_720_125MHz[] = { {0x7080, 0x00000000, 0x00000000, 2, 0}, {0x0004, 0x00000004, 0x00000000, 2, 0}, {0x0002, 0x00000f00, 0x00000000, 2, 100}, {0x0002, 0x00000000, 0x00000000, 2, 1000}, {0x0006, 0x00000040, 0x00000000, 2, 0}, {0x0014, 0x00000000, 0x00000000, 2, 0}, {0x0016, 0x000005ff, 0x00000000, 2, 0}, // Program CSI Tx PLL {0x0020, 0x0000402d, 0x00000000, 2, 0}, {0x0022, 0x00000213, 0x00000000, 2, 0}, // CSI Tx PHY (32-bit Registers) {0x0140, 0x00000000, 0x00000000, 4, 0}, {0x0144, 0x00000000, 0x00000000, 4, 0}, {0x0148, 0x00000000, 0x00000000, 4, 0}, {0x014c, 0x00000000, 0x00000000, 4, 0}, {0x0150, 0x00000000, 0x00000000, 4, 0}, // CSI Tx PPI (32-bit Registers) {0x0210, 0x00000e00, 0x00000000, 4, 0}, {0x0214, 0x00000001, 0x00000000, 4, 0}, {0x0218, 0x00000801, 0x00000000, 4, 0}, {0x021c, 0x00000001, 0x00000000, 4, 0}, {0x0220, 0x00000001, 0x00000000, 4, 0}, {0x0224, 0x00004800, 0x00000000, 4, 0}, {0x0228, 0x00000005, 0x00000000, 4, 0}, {0x022c, 0x00000000, 0x00000000, 4, 0}, {0x0234, 0x0000001f, 0x00000000, 4, 0}, {0x0238, 0x00000001, 0x00000000, 4, 0}, //non-continuous clock {0x0204, 0x00000001, 0x00000000, 4, 0}, {0x0518, 0x00000001, 0x00000000, 4, 0}, {0x0500, 0xa300be82, 0x00000000, 4, 0}, // HDMI Interrupt Mask {0x8502, 0x00000001, 0x00000000, 1, 0}, {0x8512, 0x000000fe, 0x00000000, 1, 0}, {0x8514, 0x00000000, 0x00000000, 1, 0}, {0x8515, 0x00000000, 0x00000000, 1, 0}, {0x8516, 0x00000000, 0x00000000, 1, 0}, // HDMI Audio RefClk (26 MHz) {0x8531, 0x00000001, 0x00000000, 1, 0}, {0x8540, 0x0000008c, 0x00000000, 1, 0}, {0x8541, 0x0000000a, 0x00000000, 1, 0}, {0x8630, 0x000000b0, 0x00000000, 1, 0}, {0x8631, 0x0000001e, 0x00000000, 1, 0}, {0x8632, 0x00000004, 0x00000000, 1, 0}, {0x8670, 0x00000001, 0x00000000, 1, 0}, // HDMI PHY {0x8532, 0x00000080, 0x00000000, 1, 0}, {0x8536, 0x00000040, 0x00000000, 1, 0}, {0x853f, 0x0000000a, 0x00000000, 1, 0}, // EDID {0x85c7, 0x00000001, 0x00000000, 1, 0}, {0x85cb, 0x00000001, 0x00000000, 1, 0}, // HDMI System {0x8543, 0x00000032, 0x00000000, 1, 0}, // {0x8544, 0x00000000, 0x00000000, 1, 1000}, // {0x8544, 0x00000001, 0x00000000, 1, 100}, {0x8545, 0x00000031, 0x00000000, 1, 0}, {0x8546, 0x0000002d, 0x00000000, 1, 0}, // HDCP Setting {0x85d1, 0x00000001, 0x00000000, 1, 0}, {0x8560, 0x00000024, 0x00000000, 1, 0}, {0x8563, 0x00000011, 0x00000000, 1, 0}, {0x8564, 0x0000000f, 0x00000000, 1, 0}, // Video settings {0x8573, 0x00000081, 0x00000000, 1, 0}, {0x8571, 0x00000002, 0x00000000, 1, 0}, // HDMI Audio In Setting {0x8600, 0x00000000, 0x00000000, 1, 0}, {0x8602, 0x000000f3, 0x00000000, 1, 0}, {0x8603, 0x00000002, 0x00000000, 1, 0}, {0x8604, 0x0000000c, 0x00000000, 1, 0}, {0x8606, 0x00000005, 0x00000000, 1, 0}, {0x8607, 0x00000000, 0x00000000, 1, 0}, {0x8620, 0x00000022, 0x00000000, 1, 0}, {0x8640, 0x00000001, 0x00000000, 1, 0}, {0x8641, 0x00000065, 0x00000000, 1, 0}, {0x8642, 0x00000007, 0x00000000, 1, 0}, // {0x8651, 0x00000003, 0x00000000, 1, 0}, // Inverted LRCK polarity - (Sony) format {0x8652, 0x00000002, 0x00000000, 1, 0}, // Left-justified I2S (Phillips) format // {0x8652, 0x00000000, 0x00000000, 1, 0}, // Right-justified (Sony) format {0x8665, 0x00000010, 0x00000000, 1, 0}, // InfoFrame Extraction {0x8709, 0x000000ff, 0x00000000, 1, 0}, {0x870b, 0x0000002c, 0x00000000, 1, 0}, {0x870c, 0x00000053, 0x00000000, 1, 0}, {0x870d, 0x00000001, 0x00000000, 1, 0}, {0x870e, 0x00000030, 0x00000000, 1, 0}, {0x9007, 0x00000010, 0x00000000, 1, 0}, {0x854a, 0x00000001, 0x00000000, 1, 0}, // Output Control {0x0004, 0x00000cf7, 0x00000000, 2, 0}, }; static struct reg_value tc358743_setting_YUV422_4lane_720P_60fps_1280_720_133Mhz[] = { {0x7080, 0x00000000, 0x00000000, 2, 0}, {0x0004, 0x00000004, 0x00000000, 2, 0}, {0x0002, 0x00000f00, 0x00000000, 2, 100}, {0x0002, 0x00000000, 0x00000000, 2, 1000}, {0x0006, 0x00000000, 0x00000000, 2, 0}, {0x0014, 0x0000ffff, 0x00000000, 2, 0}, {0x0016, 0x000005ff, 0x00000000, 2, 0}, // Program CSI Tx PLL {0x0020, 0x00004062, 0x00000000, 2, 0}, {0x0022, 0x00000613, 0x00000000, 2, 0}, // CSI Tx PHY (32-bit Registers) {0x0140, 0x00000000, 0x00000000, 4, 0}, {0x0144, 0x00000000, 0x00000000, 4, 0}, {0x0148, 0x00000000, 0x00000000, 4, 0}, {0x014c, 0x00000000, 0x00000000, 4, 0}, {0x0150, 0x00000000, 0x00000000, 4, 0}, // CSI Tx PPI (32-bit Registers) {0x0210, 0x00000d00, 0x00000000, 4, 0}, {0x0214, 0x00000001, 0x00000000, 4, 0}, {0x0218, 0x00000701, 0x00000000, 4, 0}, {0x021c, 0x00000000, 0x00000000, 4, 0}, {0x0220, 0x00000001, 0x00000000, 4, 0}, {0x0224, 0x00004000, 0x00000000, 4, 0}, {0x0228, 0x00000005, 0x00000000, 4, 0}, {0x022c, 0x00000000, 0x00000000, 4, 0}, {0x0234, 0x0000001f, 0x00000000, 4, 0}, {0x0238, 0x00000001, 0x00000000, 4, 0}, {0x0204, 0x00000001, 0x00000000, 4, 0}, {0x0518, 0x00000001, 0x00000000, 4, 0}, {0x0500, 0xa300be86, 0x00000000, 4, 0}, // HDMI Interrupt Mask {0x8502, 0x00000001, 0x00000000, 1, 0}, {0x8512, 0x000000fe, 0x00000000, 1, 0}, {0x8514, 0x00000000, 0x00000000, 1, 0}, {0x8515, 0x00000000, 0x00000000, 1, 0}, {0x8516, 0x00000000, 0x00000000, 1, 0}, // HDMI Audio RefClk (26 MHz) {0x8531, 0x00000001, 0x00000000, 1, 0}, {0x8540, 0x00000a8c, 0x00000000, 1, 0}, {0x8630, 0x00041eb0, 0x00000000, 1, 0}, {0x8670, 0x00000001, 0x00000000, 1, 0}, // HDMI PHY {0x8532, 0x00000080, 0x00000000, 1, 0}, {0x8536, 0x00000040, 0x00000000, 1, 0}, {0x853f, 0x0000000a, 0x00000000, 1, 0}, // HDMI System {0x8543, 0x00000032, 0x00000000, 1, 0}, {0x8544, 0x00000000, 0x00000000, 1, 0}, {0x8545, 0x00000031, 0x00000000, 1, 0}, {0x8546, 0x0000002d, 0x00000000, 1, 0}, // EDID {0x85c7, 0x00000001, 0x00000000, 1, 0}, {0x85cb, 0x00000001, 0x00000000, 1, 0}, // HDCP Setting {0x85d1, 0x00000001, 0x00000000, 1, 0}, {0x8560, 0x00000024, 0x00000000, 1, 0}, {0x8563, 0x00000011, 0x00000000, 1, 0}, {0x8564, 0x0000000f, 0x00000000, 1, 0}, // RGB --> YUV Conversion // {0x8574, 0x00000000, 0x00000000, 1, 0}, {0x8573, 0x00000081, 0x00000000, 1, 0}, {0x8571, 0x00000002, 0x00000000, 1, 0}, // HDMI Audio In Setting {0x8600, 0x00000000, 0x00000000, 1, 0}, {0x8602, 0x000000f3, 0x00000000, 1, 0}, {0x8603, 0x00000002, 0x00000000, 1, 0}, {0x8604, 0x0000000c, 0x00000000, 1, 0}, {0x8606, 0x00000005, 0x00000000, 1, 0}, {0x8607, 0x00000000, 0x00000000, 1, 0}, {0x8620, 0x00000022, 0x00000000, 1, 0}, {0x8640, 0x00000001, 0x00000000, 1, 0}, {0x8641, 0x00000065, 0x00000000, 1, 0}, {0x8642, 0x00000007, 0x00000000, 1, 0}, {0x8652, 0x00000002, 0x00000000, 1, 0}, {0x8665, 0x00000010, 0x00000000, 1, 0}, // InfoFrame Extraction {0x8709, 0x000000ff, 0x00000000, 1, 0}, {0x870b, 0x0000002c, 0x00000000, 1, 0}, {0x870c, 0x00000053, 0x00000000, 1, 0}, {0x870d, 0x00000001, 0x00000000, 1, 0}, {0x870e, 0x00000030, 0x00000000, 1, 0}, {0x9007, 0x00000010, 0x00000000, 1, 0}, {0x854a, 0x00000001, 0x00000000, 1, 0}, // Output Control {0x0004, 0x00000cf7, 0x00000000, 2, 0}, }; static struct reg_value tc358743_setting_YUV422_2lane_color_bar_1280_720_125MHz[] = { {0x7080, 0x00000000, 0x00000000, 2, 0}, {0x0002, 0x00000f00, 0x00000000, 2, 100}, {0x0002, 0x00000000, 0x00000000, 2, 1000}, {0x0006, 0x00000000, 0x00000000, 2, 0}, {0x0004, 0x00000084, 0x00000000, 2, 0}, {0x0010, 0x0000001e, 0x00000000, 2, 0}, // Program CSI Tx PLL {0x0020, 0x0000405c, 0x00000000, 2, 0}, {0x0022, 0x00000613, 0x00000000, 2, 0}, // CSI Tx PHY (32-bit Registers) {0x0140, 0x00000000, 0x00000000, 4, 0}, {0x0144, 0x00000000, 0x00000000, 4, 0}, {0x0148, 0x00000000, 0x00000000, 4, 0}, {0x014c, 0x00000000, 0x00000000, 4, 0}, {0x0150, 0x00000000, 0x00000000, 4, 0}, // CSI Tx PPI (32-bit Registers) {0x0210, 0x00000e00, 0x00000000, 4, 0}, {0x0214, 0x00000001, 0x00000000, 4, 0}, {0x0218, 0x00000801, 0x00000000, 4, 0}, {0x021c, 0x00000000, 0x00000000, 4, 0}, {0x0220, 0x00000001, 0x00000000, 4, 0}, {0x0224, 0x00004000, 0x00000000, 4, 0}, {0x0228, 0x00000006, 0x00000000, 4, 0}, {0x022c, 0x00000000, 0x00000000, 4, 0}, {0x0234, 0x00000007, 0x00000000, 4, 0}, {0x0238, 0x00000001, 0x00000000, 4, 0}, //non-continuous clock {0x0204, 0x00000001, 0x00000000, 4, 0}, {0x0518, 0x00000001, 0x00000000, 4, 0}, {0x0500, 0xa30080a2, 0x00000000, 4, 0}, // 1280x720 colorbar {0x000a, 0x00000a00, 0x00000000, 2, 0}, {0x7080, 0x00000082, 0x00000000, 2, 0}, // 128 pixel black - repeat 128 times {0x7000, 0x0000007f, 0x00000000, 2, (1<<24)|(128<<16)}, // 128 pixel blue - repeat 64 times {0x7000, 0x000000ff, 0x00000000, 2, 0}, {0x7000, 0x00000000, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel red - repeat 64 times {0x7000, 0x00000000, 0x00000000, 2, 0}, {0x7000, 0x000000ff, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel pink - repeat 64 times {0x7000, 0x00007fff, 0x00000000, 2, 0}, {0x7000, 0x00007fff, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel green - repeat 64 times {0x7000, 0x00007f00, 0x00000000, 2, 0}, {0x7000, 0x00007f00, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel light blue - repeat 64 times {0x7000, 0x0000c0ff, 0x00000000, 2, 0}, {0x7000, 0x0000c000, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel yellow - repeat 64 times {0x7000, 0x0000ff00, 0x00000000, 2, 0}, {0x7000, 0x0000ffff, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel white - repeat 64 times {0x7000, 0x0000ff7f, 0x00000000, 2, 0}, {0x7000, 0x0000ff7f, 0x00000000, 2, (2<<24)|(64<<16)}, // 720 lines {0x7090, 0x000002cf, 0x00000000, 2, 0}, {0x7092, 0x00000580, 0x00000000, 2, 0}, {0x7094, 0x00000010, 0x00000000, 2, 0}, {0x7080, 0x00000083, 0x00000000, 2, 0}, }; static struct reg_value tc358743_setting_YUV422_4lane_color_bar_1280_720_125MHz[] = { {0x7080, 0x00000000, 0x00000000, 2, 0}, {0x0002, 0x00000f00, 0x00000000, 2, 100}, {0x0002, 0x00000000, 0x00000000, 2, 1000}, {0x0006, 0x00000000, 0x00000000, 2, 0}, {0x0004, 0x00000084, 0x00000000, 2, 0}, {0x0010, 0x0000001e, 0x00000000, 2, 0}, // Program CSI Tx PLL {0x0020, 0x0000405c, 0x00000000, 2, 0}, {0x0022, 0x00000613, 0x00000000, 2, 0}, // CSI Tx PHY (32-bit Registers) {0x0140, 0x00000000, 0x00000000, 4, 0}, {0x0144, 0x00000000, 0x00000000, 4, 0}, {0x0148, 0x00000000, 0x00000000, 4, 0}, {0x014c, 0x00000000, 0x00000000, 4, 0}, {0x0150, 0x00000000, 0x00000000, 4, 0}, // CSI Tx PPI (32-bit Registers) {0x0210, 0x00000e00, 0x00000000, 4, 0}, {0x0214, 0x00000001, 0x00000000, 4, 0}, {0x0218, 0x00000801, 0x00000000, 4, 0}, {0x021c, 0x00000000, 0x00000000, 4, 0}, {0x0220, 0x00000001, 0x00000000, 4, 0}, {0x0224, 0x00004000, 0x00000000, 4, 0}, {0x0228, 0x00000006, 0x00000000, 4, 0}, {0x022c, 0x00000000, 0x00000000, 4, 0}, {0x0234, 0x0000001F, 0x00000000, 4, 0}, //{0x0234, 0x00000007, 0x00000000, 4, 0}, {0x0238, 0x00000001, 0x00000000, 4, 0}, //non-continuous clock {0x0204, 0x00000001, 0x00000000, 4, 0}, {0x0518, 0x00000001, 0x00000000, 4, 0}, {0x0500, 0xa30080a6, 0x00000000, 4, 0}, //{0x0500, 0xa30080a2, 0x00000000, 4, 0}, // 1280x720 colorbar {0x000a, 0x00000a00, 0x00000000, 2, 0}, {0x7080, 0x00000082, 0x00000000, 2, 0}, // 128 pixel black - repeat 128 times {0x7000, 0x0000007f, 0x00000000, 2, (1<<24)|(128<<16)}, // 128 pixel blue - repeat 64 times {0x7000, 0x000000ff, 0x00000000, 2, 0}, {0x7000, 0x00000000, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel red - repeat 64 times {0x7000, 0x00000000, 0x00000000, 2, 0}, {0x7000, 0x000000ff, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel pink - repeat 64 times {0x7000, 0x00007fff, 0x00000000, 2, 0}, {0x7000, 0x00007fff, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel green - repeat 64 times {0x7000, 0x00007f00, 0x00000000, 2, 0}, {0x7000, 0x00007f00, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel light blue - repeat 64 times {0x7000, 0x0000c0ff, 0x00000000, 2, 0}, {0x7000, 0x0000c000, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel yellow - repeat 64 times {0x7000, 0x0000ff00, 0x00000000, 2, 0}, {0x7000, 0x0000ffff, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel white - repeat 64 times {0x7000, 0x0000ff7f, 0x00000000, 2, 0}, {0x7000, 0x0000ff7f, 0x00000000, 2, (2<<24)|(64<<16)}, // 720 lines {0x7090, 0x000002cf, 0x00000000, 2, 0}, {0x7092, 0x00000300, 0x00000000, 2, 0}, //{0x7092, 0x00000580, 0x00000000, 2, 0}, {0x7094, 0x00000010, 0x00000000, 2, 0}, {0x7080, 0x00000083, 0x00000000, 2, 0}, }; static struct reg_value tc358743_setting_YUV422_4lane_color_bar_1024_720_200MHz[] = { {0x7080, 0x00000000, 0x00000000, 2, 0}, {0x0002, 0x00000f00, 0x00000000, 2, 100}, {0x0002, 0x00000000, 0x00000000, 2, 1000}, {0x0006, 0x00000000, 0x00000000, 2, 0}, {0x0004, 0x00000084, 0x00000000, 2, 0}, {0x0010, 0x0000001e, 0x00000000, 2, 0}, // Program CSI Tx PLL {0x0020, 0x00004050, 0x00000000, 2, 0}, {0x0022, 0x00000213, 0x00000000, 2, 0}, // CSI Tx PHY (32-bit Registers) {0x0140, 0x00000000, 0x00000000, 4, 0}, {0x0144, 0x00000000, 0x00000000, 4, 0}, {0x0148, 0x00000000, 0x00000000, 4, 0}, {0x014c, 0x00000000, 0x00000000, 4, 0}, {0x0150, 0x00000000, 0x00000000, 4, 0}, // CSI Tx PPI (32-bit Registers) {0x0210, 0x00001800, 0x00000000, 4, 0}, {0x0214, 0x00000002, 0x00000000, 4, 0}, {0x0218, 0x00001102, 0x00000000, 4, 0}, {0x021c, 0x00000000, 0x00000000, 4, 0}, {0x0220, 0x00000003, 0x00000000, 4, 0}, {0x0224, 0x00004000, 0x00000000, 4, 0}, {0x0228, 0x00000007, 0x00000000, 4, 0}, {0x022c, 0x00000001, 0x00000000, 4, 0}, {0x0234, 0x0000001f, 0x00000000, 4, 0}, {0x0238, 0x00000001, 0x00000000, 4, 0}, //non-continuous clock {0x0204, 0x00000001, 0x00000000, 4, 0}, {0x0518, 0x00000001, 0x00000000, 4, 0}, {0x0500, 0xa30080a6, 0x00000000, 4, 0}, // 1280x720 colorbar {0x000a, 0x00000800, 0x00000000, 2, 0}, {0x7080, 0x00000082, 0x00000000, 2, 0}, // 128 pixel black - repeat 128 times {0x7000, 0x0000007f, 0x00000000, 2, (1<<24)|(128<<16)}, // 128 pixel blue - repeat 64 times {0x7000, 0x000000ff, 0x00000000, 2, 0}, {0x7000, 0x00000000, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel red - repeat 64 times {0x7000, 0x00000000, 0x00000000, 2, 0}, {0x7000, 0x000000ff, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel pink - repeat 64 times {0x7000, 0x00007fff, 0x00000000, 2, 0}, {0x7000, 0x00007fff, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel green - repeat 64 times {0x7000, 0x00007f00, 0x00000000, 2, 0}, {0x7000, 0x00007f00, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel light blue - repeat 64 times {0x7000, 0x0000c0ff, 0x00000000, 2, 0}, {0x7000, 0x0000c000, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel yellow - repeat 64 times {0x7000, 0x0000ff00, 0x00000000, 2, 0}, {0x7000, 0x0000ffff, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel white - repeat 64 times {0x7000, 0x0000ff7f, 0x00000000, 2, 0}, {0x7000, 0x0000ff7f, 0x00000000, 2, (2<<24)|(64<<16)}, // 720 lines {0x0020, 0x0000406f, 0x00000000, 2, 100}, {0x7090, 0x000002cf, 0x00000000, 2, 0}, {0x7092, 0x00000540, 0x00000000, 2, 0}, {0x7094, 0x00000010, 0x00000000, 2, 0}, {0x7080, 0x00000083, 0x00000000, 2, 0}, }; static struct reg_value tc358743_setting_YUV422_4lane_color_bar_1280_720_300MHz[] = { {0x7080, 0x00000000, 0x00000000, 2, 0}, {0x0002, 0x00000f00, 0x00000000, 2, 100}, {0x0002, 0x00000000, 0x00000000, 2, 1000}, {0x0006, 0x00000000, 0x00000000, 2, 0}, {0x0004, 0x00000084, 0x00000000, 2, 0}, {0x0010, 0x0000001e, 0x00000000, 2, 0}, // Program CSI Tx PLL {0x0020, 0x000080c7, 0x00000000, 2, 0}, {0x0022, 0x00000213, 0x00000000, 2, 0}, // CSI Tx PHY (32-bit Registers) {0x0140, 0x00000000, 0x00000000, 4, 0}, {0x0144, 0x00000000, 0x00000000, 4, 0}, {0x0148, 0x00000000, 0x00000000, 4, 0}, {0x014c, 0x00000000, 0x00000000, 4, 0}, {0x0150, 0x00000000, 0x00000000, 4, 0}, // CSI Tx PPI (32-bit Registers) {0x0210, 0x00001e00, 0x00000000, 4, 0}, {0x0214, 0x00000003, 0x00000000, 4, 0}, {0x0218, 0x00001402, 0x00000000, 4, 0}, {0x021c, 0x00000000, 0x00000000, 4, 0}, {0x0220, 0x00000003, 0x00000000, 4, 0}, {0x0224, 0x00004a00, 0x00000000, 4, 0}, {0x0228, 0x00000008, 0x00000000, 4, 0}, {0x022c, 0x00000002, 0x00000000, 4, 0}, {0x0234, 0x0000001f, 0x00000000, 4, 0}, {0x0238, 0x00000001, 0x00000000, 4, 0}, //non-continuous clock {0x0204, 0x00000001, 0x00000000, 4, 0}, {0x0518, 0x00000001, 0x00000000, 4, 0}, {0x0500, 0xa30080a6, 0x00000000, 4, 0}, // 1280x720 colorbar {0x000a, 0x00000a00, 0x00000000, 2, 0}, {0x7080, 0x00000082, 0x00000000, 2, 0}, // 128 pixel black - repeat 128 times {0x7000, 0x0000007f, 0x00000000, 2, (1<<24)|(128<<16)}, // 128 pixel blue - repeat 64 times {0x7000, 0x000000ff, 0x00000000, 2, 0}, {0x7000, 0x00000000, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel red - repeat 64 times {0x7000, 0x00000000, 0x00000000, 2, 0}, {0x7000, 0x000000ff, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel pink - repeat 64 times {0x7000, 0x00007fff, 0x00000000, 2, 0}, {0x7000, 0x00007fff, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel green - repeat 64 times {0x7000, 0x00007f00, 0x00000000, 2, 0}, {0x7000, 0x00007f00, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel light blue - repeat 64 times {0x7000, 0x0000c0ff, 0x00000000, 2, 0}, {0x7000, 0x0000c000, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel yellow - repeat 64 times {0x7000, 0x0000ff00, 0x00000000, 2, 0}, {0x7000, 0x0000ffff, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel white - repeat 64 times {0x7000, 0x0000ff7f, 0x00000000, 2, 0}, {0x7000, 0x0000ff7f, 0x00000000, 2, (2<<24)|(64<<16)}, // 720 lines {0x7090, 0x000002cf, 0x00000000, 2, 0}, {0x7092, 0x000006b8, 0x00000000, 2, 0}, {0x7094, 0x00000010, 0x00000000, 2, 0}, {0x7080, 0x00000083, 0x00000000, 2, 0}, }; static struct reg_value tc358743_setting_YUV422_4lane_color_bar_1920_1023_300MHz[] = { {0x7080, 0x00000000, 0x00000000, 2, 0}, {0x0002, 0x00000f00, 0x00000000, 2, 100}, {0x0002, 0x00000000, 0x00000000, 2, 1000}, {0x0006, 0x00000000, 0x00000000, 2, 0}, {0x0004, 0x00000084, 0x00000000, 2, 0}, {0x0010, 0x0000001e, 0x00000000, 2, 0}, // Program CSI Tx PLL {0x0020, 0x000080c7, 0x00000000, 2, 0}, {0x0022, 0x00000213, 0x00000000, 2, 0}, // CSI Tx PHY (32-bit Registers) {0x0140, 0x00000000, 0x00000000, 4, 0}, {0x0144, 0x00000000, 0x00000000, 4, 0}, {0x0148, 0x00000000, 0x00000000, 4, 0}, {0x014c, 0x00000000, 0x00000000, 4, 0}, {0x0150, 0x00000000, 0x00000000, 4, 0}, // CSI Tx PPI (32-bit Registers) {0x0210, 0x00001e00, 0x00000000, 4, 0}, {0x0214, 0x00000003, 0x00000000, 4, 0}, {0x0218, 0x00001402, 0x00000000, 4, 0}, {0x021c, 0x00000000, 0x00000000, 4, 0}, {0x0220, 0x00000003, 0x00000000, 4, 0}, {0x0224, 0x00004a00, 0x00000000, 4, 0}, {0x0228, 0x00000008, 0x00000000, 4, 0}, {0x022c, 0x00000002, 0x00000000, 4, 0}, {0x0234, 0x0000001f, 0x00000000, 4, 0}, {0x0238, 0x00000001, 0x00000000, 4, 0}, //non-continuous clock {0x0204, 0x00000001, 0x00000000, 4, 0}, {0x0518, 0x00000001, 0x00000000, 4, 0}, {0x0500, 0xa30080a6, 0x00000000, 4, 0}, // 1920x1023 colorbar {0x000a, 0x00000f00, 0x00000000, 2, 0}, {0x7080, 0x00000082, 0x00000000, 2, 0}, // 128 pixel black - repeat 128 times {0x7000, 0x0000007f, 0x00000000, 2, (1<<24)|(128<<16)}, // 128 pixel blue - repeat 64 times {0x7000, 0x000000ff, 0x00000000, 2, 0}, {0x7000, 0x00000000, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel red - repeat 64 times {0x7000, 0x00000000, 0x00000000, 2, 0}, {0x7000, 0x000000ff, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel pink - repeat 64 times {0x7000, 0x00007fff, 0x00000000, 2, 0}, {0x7000, 0x00007fff, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel green - repeat 64 times {0x7000, 0x00007f00, 0x00000000, 2, 0}, {0x7000, 0x00007f00, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel light blue - repeat 64 times {0x7000, 0x0000c0ff, 0x00000000, 2, 0}, {0x7000, 0x0000c000, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel yellow - repeat 64 times {0x7000, 0x0000ff00, 0x00000000, 2, 0}, {0x7000, 0x0000ffff, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel white - repeat 64 times {0x7000, 0x0000ff7f, 0x00000000, 2, 0}, {0x7000, 0x0000ff7f, 0x00000000, 2, (2<<24)|(64<<16)}, // 1023 lines {0x7090, 0x000003fe, 0x00000000, 2, 0}, {0x7092, 0x000004d8, 0x00000000, 2, 0}, {0x7094, 0x0000002d, 0x00000000, 2, 0}, {0x7080, 0x00000083, 0x00000000, 2, 0}, }; static struct reg_value tc358743_setting_YUV422_2lane_color_bar_640_480_174MHz[] = { {0x7080, 0x00000000, 0x00000000, 2, 0}, {0x0002, 0x00000f00, 0x00000000, 2, 100}, {0x0002, 0x00000000, 0x00000000, 2, 1000}, {0x0006, 0x00000000, 0x00000000, 2, 0}, {0x0004, 0x00000084, 0x00000000, 2, 0}, {0x0010, 0x0000001e, 0x00000000, 2, 0}, // Program CSI Tx PLL {0x0020, 0x00008073, 0x00000000, 2, 0}, {0x0022, 0x00000213, 0x00000000, 2, 0}, // CSI Tx PHY (32-bit Registers) {0x0140, 0x00000000, 0x00000000, 4, 0}, {0x0144, 0x00000000, 0x00000000, 4, 0}, {0x0148, 0x00000000, 0x00000000, 4, 0}, // {0x014c, 0x00000000, 0x00000000, 4, 0}, // {0x0150, 0x00000000, 0x00000000, 4, 0}, // CSI Tx PPI (32-bit Registers) {0x0210, 0x00001200, 0x00000000, 4, 0}, {0x0214, 0x00000002, 0x00000000, 4, 0}, {0x0218, 0x00000b02, 0x00000000, 4, 0}, {0x021c, 0x00000001, 0x00000000, 4, 0}, {0x0220, 0x00000103, 0x00000000, 4, 0}, {0x0224, 0x00004000, 0x00000000, 4, 0}, {0x0228, 0x00000008, 0x00000000, 4, 0}, {0x022c, 0x00000002, 0x00000000, 4, 0}, {0x0234, 0x0000001f, 0x00000000, 4, 0}, {0x0238, 0x00000000, 0x00000000, 4, 0}, {0x0204, 0x00000001, 0x00000000, 4, 0}, {0x0518, 0x00000001, 0x00000000, 4, 0}, {0x0500, 0xA3008082, 0x00000000, 4, 0}, // 640x480 colorbar {0x000a, 0x00000500, 0x00000000, 2, 0}, {0x7080, 0x00000082, 0x00000000, 2, 0}, // 80 pixel black - repeate 80 times {0x7000, 0x0000007f, 0x00000000, 2, (1<<24)|(80<<16)}, // 80 pixel blue - repeate 40 times {0x7000, 0x000000ff, 0x00000000, 2, 0}, {0x7000, 0x00000000, 0x00000000, 2, (2<<24)|(40<<16)}, // 80 pixel red - repeate 40 times {0x7000, 0x00000000, 0x00000000, 2, 0}, {0x7000, 0x000000ff, 0x00000000, 2, (2<<24)|(40<<16)}, // 80 pixel pink - repeate 40 times {0x7000, 0x00007fff, 0x00000000, 2, 0}, {0x7000, 0x00007fff, 0x00000000, 2, (2<<24)|(40<<16)}, // 80 pixel green - repeate 40 times {0x7000, 0x00007f00, 0x00000000, 2, 0}, {0x7000, 0x00007f00, 0x00000000, 2, (2<<24)|(40<<16)}, // 80 pixel light blue - repeate 40 times {0x7000, 0x0000c0ff, 0x00000000, 2, 0}, {0x7000, 0x0000c000, 0x00000000, 2, (2<<24)|(40<<16)}, // 80 pixel yellow - repeate 40 times {0x7000, 0x0000ff00, 0x00000000, 2, 0}, {0x7000, 0x0000ffff, 0x00000000, 2, (2<<24)|(40<<16)}, // 80 pixel white - repeate 40 times {0x7000, 0x0000ff7f, 0x00000000, 2, 0}, {0x7000, 0x0000ff7f, 0x00000000, 2, (2<<24)|(40<<16)}, // 480 lines {0x7090, 0x000001df, 0x00000000, 2, 0}, {0x7092, 0x00000898, 0x00000000, 2, 0}, {0x7094, 0x00000285, 0x00000000, 2, 0}, {0x7080, 0x00000083, 0x00000000, 2, 0}, }; static struct reg_value tc358743_setting_YUV422_2lane_color_bar_640_480_108MHz_cont[] = { {0x7080, 0x00000000, 0x00000000, 2, 0}, {0x0002, 0x00000f00, 0x00000000, 2, 100}, {0x0002, 0x00000000, 0x00000000, 2, 1000}, {0x0006, 0x00000000, 0x00000000, 2, 0}, {0x0004, 0x00000084, 0x00000000, 2, 0}, {0x0010, 0x0000001e, 0x00000000, 2, 0}, // Program CSI Tx PLL {0x0020, 0x0000404F, 0x00000000, 2, 0}, {0x0022, 0x00000613, 0x00000000, 2, 0}, // CSI Tx PHY (32-bit Registers) {0x0140, 0x00000000, 0x00000000, 4, 0}, {0x0144, 0x00000000, 0x00000000, 4, 0}, {0x0148, 0x00000000, 0x00000000, 4, 0}, {0x014c, 0x00000000, 0x00000000, 4, 0}, {0x0150, 0x00000000, 0x00000000, 4, 0}, // CSI Tx PPI (32-bit Registers) {0x0210, 0x00001800, 0x00000000, 4, 0}, {0x0214, 0x00000002, 0x00000000, 4, 0}, {0x0218, 0x00001102, 0x00000000, 4, 0}, {0x021c, 0x00000000, 0x00000000, 4, 0}, {0x0220, 0x00000003, 0x00000000, 4, 0}, {0x0224, 0x00004000, 0x00000000, 4, 0}, {0x0228, 0x00000007, 0x00000000, 4, 0}, {0x022c, 0x00000001, 0x00000000, 4, 0}, {0x0234, 0x0000001f, 0x00000000, 4, 0}, {0x0238, 0x00000001, 0x00000000, 4, 0}, {0x0204, 0x00000001, 0x00000000, 4, 0}, {0x0518, 0x00000001, 0x00000000, 4, 0}, {0x0500, 0xA30080A2, 0x00000000, 4, 0}, // 640x480 colorbar {0x000a, 0x00000500, 0x00000000, 2, 0}, {0x7080, 0x00000082, 0x00000000, 2, 0}, // 80 pixel black - repeate 80 times {0x7000, 0x0000007f, 0x00000000, 2, (1<<24)|(80<<16)}, // 80 pixel blue - repeate 40 times {0x7000, 0x000000ff, 0x00000000, 2, 0}, {0x7000, 0x00000000, 0x00000000, 2, (2<<24)|(40<<16)}, // 80 pixel red - repeate 40 times {0x7000, 0x00000000, 0x00000000, 2, 0}, {0x7000, 0x000000ff, 0x00000000, 2, (2<<24)|(40<<16)}, // 80 pixel pink - repeate 40 times {0x7000, 0x00007fff, 0x00000000, 2, 0}, {0x7000, 0x00007fff, 0x00000000, 2, (2<<24)|(40<<16)}, // 80 pixel green - repeate 40 times {0x7000, 0x00007f00, 0x00000000, 2, 0}, {0x7000, 0x00007f00, 0x00000000, 2, (2<<24)|(40<<16)}, // 80 pixel light blue - repeate 40 times {0x7000, 0x0000c0ff, 0x00000000, 2, 0}, {0x7000, 0x0000c000, 0x00000000, 2, (2<<24)|(40<<16)}, // 80 pixel yellow - repeate 40 times {0x7000, 0x0000ff00, 0x00000000, 2, 0}, {0x7000, 0x0000ffff, 0x00000000, 2, (2<<24)|(40<<16)}, // 80 pixel white - repeate 40 times {0x7000, 0x0000ff7f, 0x00000000, 2, 0}, {0x7000, 0x0000ff7f, 0x00000000, 2, (2<<24)|(40<<16)}, // 480 lines {0x7090, 0x000001df, 0x00000000, 2, 0}, {0x7092, 0x00000700, 0x00000000, 2, 0}, {0x7094, 0x00000010, 0x00000000, 2, 0}, {0x7080, 0x00000083, 0x00000000, 2, 0}, }; //480p RGB2YUV442 static struct reg_value tc358743_setting_YUV422_2lane_60fps_640_480_125Mhz[] = { {0x7080, 0x00000000, 0x00000000, 2, 0}, {0x0004, 0x00000004, 0x00000000, 2, 0}, {0x0002, 0x00000f00, 0x00000000, 2, 100}, {0x0002, 0x00000000, 0x00000000, 2, 1000}, {0x0006, 0x00000040, 0x00000000, 2, 0}, // {0x000a, 0x000005a0, 0x00000000, 2, 0}, // {0x0010, 0x0000001e, 0x00000000, 2, 0}, {0x0014, 0x00000000, 0x00000000, 2, 0}, {0x0016, 0x000005ff, 0x00000000, 2, 0}, // Program CSI Tx PLL {0x0020, 0x0000405c, 0x00000000, 2, 0}, {0x0022, 0x00000613, 0x00000000, 2, 0}, // CSI Tx PHY (32-bit Registers) {0x0140, 0x00000000, 0x00000000, 4, 0}, {0x0144, 0x00000000, 0x00000000, 4, 0}, {0x0148, 0x00000000, 0x00000000, 4, 0}, {0x014c, 0x00000000, 0x00000000, 4, 0}, {0x0150, 0x00000000, 0x00000000, 4, 0}, // CSI Tx PPI (32-bit Registers) {0x0210, 0x00000d00, 0x00000000, 4, 0}, {0x0214, 0x00000001, 0x00000000, 4, 0}, {0x0218, 0x00000701, 0x00000000, 4, 0}, {0x021c, 0x00000000, 0x00000000, 4, 0}, {0x0220, 0x00000001, 0x00000000, 4, 0}, {0x0224, 0x00004000, 0x00000000, 4, 0}, {0x0228, 0x00000005, 0x00000000, 4, 0}, {0x022c, 0x00000000, 0x00000000, 4, 0}, {0x0234, 0x0000001f, 0x00000000, 4, 0}, {0x0238, 0x00000001, 0x00000000, 4, 0}, {0x0204, 0x00000001, 0x00000000, 4, 0}, {0x0518, 0x00000001, 0x00000000, 4, 0}, {0x0500, 0xA30080A2, 0x00000000, 4, 0}, // HDMI Interrupt Mask {0x8502, 0x00000001, 0x00000000, 1, 0}, {0x8512, 0x000000fe, 0x00000000, 1, 0}, {0x8514, 0x00000000, 0x00000000, 1, 0}, {0x8515, 0x00000000, 0x00000000, 1, 0}, {0x8516, 0x00000000, 0x00000000, 1, 0}, // HDMI Audio RefClk (26 MHz) {0x8531, 0x00000001, 0x00000000, 1, 0}, {0x8540, 0x00000a8c, 0x00000000, 1, 0}, {0x8630, 0x00041eb0, 0x00000000, 1, 0}, {0x8670, 0x00000001, 0x00000000, 1, 0}, // HDMI PHY {0x8532, 0x00000080, 0x00000000, 1, 0}, {0x8536, 0x00000040, 0x00000000, 1, 0}, {0x853f, 0x0000000a, 0x00000000, 1, 0}, // HDMI System {0x8543, 0x00000032, 0x00000000, 1, 0}, {0x8544, 0x00000000, 0x00000000, 1, 100}, // {0x8544, 0x00000001, 0x00000000, 1, 100}, {0x8545, 0x00000031, 0x00000000, 1, 0}, {0x8546, 0x0000002d, 0x00000000, 1, 0}, // EDID {0x85c7, 0x00000001, 0x00000000, 1, 0}, {0x85cb, 0x00000001, 0x00000000, 1, 0}, // HDCP Setting {0x85d1, 0x00000001, 0x00000000, 1, 0}, {0x8560, 0x00000024, 0x00000000, 1, 0}, {0x8563, 0x00000011, 0x00000000, 1, 0}, {0x8564, 0x0000000f, 0x00000000, 1, 0}, // RGB --> YUV Conversion {0x8573, 0x00000081, 0x00000000, 1, 0}, {0x8571, 0x00000002, 0x00000000, 1, 0}, // HDMI Audio In Setting {0x8600, 0x00000000, 0x00000000, 1, 0}, {0x8602, 0x000000f3, 0x00000000, 1, 0}, {0x8603, 0x00000002, 0x00000000, 1, 0}, {0x8604, 0x0000000c, 0x00000000, 1, 0}, {0x8606, 0x00000005, 0x00000000, 1, 0}, {0x8607, 0x00000000, 0x00000000, 1, 0}, {0x8620, 0x00000022, 0x00000000, 1, 0}, {0x8640, 0x00000001, 0x00000000, 1, 0}, {0x8641, 0x00000065, 0x00000000, 1, 0}, {0x8642, 0x00000007, 0x00000000, 1, 0}, {0x8652, 0x00000002, 0x00000000, 1, 0}, {0x8665, 0x00000010, 0x00000000, 1, 0}, // InfoFrame Extraction {0x8709, 0x000000ff, 0x00000000, 1, 0}, {0x870b, 0x0000002c, 0x00000000, 1, 0}, {0x870c, 0x00000053, 0x00000000, 1, 0}, {0x870d, 0x00000001, 0x00000000, 1, 0}, {0x870e, 0x00000030, 0x00000000, 1, 0}, {0x9007, 0x00000010, 0x00000000, 1, 0}, {0x854a, 0x00000001, 0x00000000, 1, 0}, // Output Control {0x0004, 0x00000cf7, 0x00000000, 2, 0}, }; //480p RGB2YUV442 static struct reg_value tc358743_setting_YUV422_2lane_60fps_720_480_125Mhz[] = { {0x7080, 0x00000000, 0x00000000, 2, 0}, {0x0004, 0x00000004, 0x00000000, 2, 0}, {0x0002, 0x00000f00, 0x00000000, 2, 100}, {0x0002, 0x00000000, 0x00000000, 2, 1000}, {0x0006, 0x00000040, 0x00000000, 2, 0}, {0x000a, 0x000005a0, 0x00000000, 2, 0}, // {0x0010, 0x0000001e, 0x00000000, 2, 0}, {0x0014, 0x00000000, 0x00000000, 2, 0}, {0x0016, 0x000005ff, 0x00000000, 2, 0}, // Program CSI Tx PLL {0x0020, 0x0000405b, 0x00000000, 2, 0}, {0x0022, 0x00000613, 0x00000000, 2, 0}, // CSI Tx PHY (32-bit Registers) {0x0140, 0x00000000, 0x00000000, 4, 0}, {0x0144, 0x00000000, 0x00000000, 4, 0}, {0x0148, 0x00000000, 0x00000000, 4, 0}, {0x014c, 0x00000000, 0x00000000, 4, 0}, {0x0150, 0x00000000, 0x00000000, 4, 0}, // CSI Tx PPI (32-bit Registers) {0x0210, 0x00000d00, 0x00000000, 4, 0}, {0x0214, 0x00000001, 0x00000000, 4, 0}, {0x0218, 0x00000701, 0x00000000, 4, 0}, {0x021c, 0x00000000, 0x00000000, 4, 0}, {0x0220, 0x00000001, 0x00000000, 4, 0}, {0x0224, 0x00004000, 0x00000000, 4, 0}, {0x0228, 0x00000005, 0x00000000, 4, 0}, {0x022c, 0x00000000, 0x00000000, 4, 0}, {0x0234, 0x0000001f, 0x00000000, 4, 0}, {0x0238, 0x00000001, 0x00000000, 4, 0}, {0x0204, 0x00000001, 0x00000000, 4, 0}, {0x0518, 0x00000001, 0x00000000, 4, 0}, {0x0500, 0xA30080A2, 0x00000000, 4, 0}, // HDMI Interrupt Mask {0x8502, 0x00000001, 0x00000000, 1, 0}, {0x8512, 0x000000fe, 0x00000000, 1, 0}, {0x8514, 0x00000000, 0x00000000, 1, 0}, {0x8515, 0x00000000, 0x00000000, 1, 0}, {0x8516, 0x00000000, 0x00000000, 1, 0}, // HDMI Audio RefClk (27 MHz) {0x8531, 0x00000001, 0x00000000, 1, 0}, {0x8540, 0x00000a8c, 0x00000000, 1, 0}, {0x8630, 0x00041eb0, 0x00000000, 1, 0}, {0x8670, 0x00000001, 0x00000000, 1, 0}, // HDMI PHY {0x8532, 0x00000080, 0x00000000, 1, 0}, {0x8536, 0x00000040, 0x00000000, 1, 0}, {0x853f, 0x0000000a, 0x00000000, 1, 0}, // HDMI System {0x8543, 0x00000032, 0x00000000, 1, 0}, {0x8544, 0x00000000, 0x00000000, 1, 100}, // {0x8544, 0x00000001, 0x00000000, 1, 100}, {0x8545, 0x00000031, 0x00000000, 1, 0}, {0x8546, 0x0000002d, 0x00000000, 1, 0}, // EDID {0x85c7, 0x00000001, 0x00000000, 1, 0}, {0x85cb, 0x00000001, 0x00000000, 1, 0}, // HDCP Setting {0x85d1, 0x00000001, 0x00000000, 1, 0}, {0x8560, 0x00000024, 0x00000000, 1, 0}, {0x8563, 0x00000011, 0x00000000, 1, 0}, {0x8564, 0x0000000f, 0x00000000, 1, 0}, // RGB --> YUV Conversion {0x8573, 0x00000081, 0x00000000, 1, 0}, {0x8571, 0x00000002, 0x00000000, 1, 0}, // HDMI Audio In Setting {0x8600, 0x00000000, 0x00000000, 1, 0}, {0x8602, 0x000000f3, 0x00000000, 1, 0}, {0x8603, 0x00000002, 0x00000000, 1, 0}, {0x8604, 0x0000000c, 0x00000000, 1, 0}, {0x8606, 0x00000005, 0x00000000, 1, 0}, {0x8607, 0x00000000, 0x00000000, 1, 0}, {0x8620, 0x00000022, 0x00000000, 1, 0}, {0x8640, 0x00000001, 0x00000000, 1, 0}, {0x8641, 0x00000065, 0x00000000, 1, 0}, {0x8642, 0x00000007, 0x00000000, 1, 0}, {0x8652, 0x00000002, 0x00000000, 1, 0}, {0x8665, 0x00000010, 0x00000000, 1, 0}, // InfoFrame Extraction {0x8709, 0x000000ff, 0x00000000, 1, 0}, {0x870b, 0x0000002c, 0x00000000, 1, 0}, {0x870c, 0x00000053, 0x00000000, 1, 0}, {0x870d, 0x00000001, 0x00000000, 1, 0}, {0x870e, 0x00000030, 0x00000000, 1, 0}, {0x9007, 0x00000010, 0x00000000, 1, 0}, {0x854a, 0x00000001, 0x00000000, 1, 0}, // Output Control {0x0004, 0x00000cf7, 0x00000000, 2, 0}, }; static struct reg_value tc358743_setting_YUV422_4lane_1080P_60fps_1920_1080_300MHz[] = { {0x7080, 0x00000000, 0x00000000, 2, 0}, {0x0004, 0x00000084, 0x00000000, 2, 0}, {0x0002, 0x00000f00, 0x00000000, 2, 100},//0}, {0x0002, 0x00000000, 0x00000000, 2, 1000},//0}, {0x0006, 0x00000000, 0x00000000, 2, 0}, {0x0014, 0x00000000, 0x00000000, 2, 0}, {0x0016, 0x000005ff, 0x00000000, 2, 0}, // Program CSI Tx PLL {0x0020, 0x000080c7, 0x00000000, 2, 0}, {0x0022, 0x00000213, 0x00000000, 2, 0}, // CSI Tx PHY (32-bit Registers) {0x0140, 0x00000000, 0x00000000, 4, 0}, {0x0144, 0x00000000, 0x00000000, 4, 0}, {0x0148, 0x00000000, 0x00000000, 4, 0}, {0x014c, 0x00000000, 0x00000000, 4, 0}, {0x0150, 0x00000000, 0x00000000, 4, 0}, // CSI Tx PPI (32-bit Registers) {0x0210, 0x00001e00, 0x00000000, 4, 0}, {0x0214, 0x00000003, 0x00000000, 4, 0}, {0x0218, 0x00001402, 0x00000000, 4, 0}, {0x021c, 0x00000000, 0x00000000, 4, 0}, {0x0220, 0x00000003, 0x00000000, 4, 0}, {0x0224, 0x00004a00, 0x00000000, 4, 0}, {0x0228, 0x00000008, 0x00000000, 4, 0}, {0x022c, 0x00000002, 0x00000000, 4, 0}, {0x0234, 0x0000001f, 0x00000000, 4, 0}, {0x0238, 0x00000001, 0x00000000, 4, 0}, {0x0204, 0x00000001, 0x00000000, 4, 0}, {0x0518, 0x00000001, 0x00000000, 4, 0}, {0x0500, 0xa30080a6, 0x00000000, 4, 0}, // HDMI Interrupt Mask {0x8502, 0x00000001, 0x00000000, 1, 0}, {0x8512, 0x000000fe, 0x00000000, 1, 0}, {0x8514, 0x00000000, 0x00000000, 1, 0}, {0x8515, 0x00000000, 0x00000000, 1, 0}, {0x8516, 0x00000000, 0x00000000, 1, 0}, // HDMI Audio RefClk (27 MHz) {0x8531, 0x00000001, 0x00000000, 1, 0}, {0x8540, 0x00000a8c, 0x00000000, 1, 0}, {0x8630, 0x00041eb0, 0x00000000, 1, 0}, {0x8670, 0x00000001, 0x00000000, 1, 0}, // HDMI PHY {0x8532, 0x00000080, 0x00000000, 1, 0}, {0x8536, 0x00000040, 0x00000000, 1, 0}, {0x853f, 0x0000000a, 0x00000000, 1, 0}, // HDMI System {0x8543, 0x00000032, 0x00000000, 1, 0}, {0x8544, 0x00000010, 0x00000000, 1, 100}, {0x8545, 0x00000031, 0x00000000, 1, 0}, {0x8546, 0x0000002d, 0x00000000, 1, 0}, // EDID {0x85c7, 0x00000001, 0x00000000, 1, 0}, {0x85cb, 0x00000001, 0x00000000, 1, 0}, // HDCP Setting {0x85d1, 0x00000001, 0x00000000, 1, 0}, {0x8560, 0x00000024, 0x00000000, 1, 0}, {0x8563, 0x00000011, 0x00000000, 1, 0}, {0x8564, 0x0000000f, 0x00000000, 1, 0}, // RGB --> YUV Conversion {0x8571, 0x00000002, 0x00000000, 1, 0}, {0x8573, 0x00000081, 0x00000000, 1, 0}, {0x8576, 0x00000060, 0x00000000, 1, 0}, // HDMI Audio In Setting {0x8600, 0x00000000, 0x00000000, 1, 0}, {0x8602, 0x000000f3, 0x00000000, 1, 0}, {0x8603, 0x00000002, 0x00000000, 1, 0}, {0x8604, 0x0000000c, 0x00000000, 1, 0}, {0x8606, 0x00000005, 0x00000000, 1, 0}, {0x8607, 0x00000000, 0x00000000, 1, 0}, {0x8620, 0x00000022, 0x00000000, 1, 0}, {0x8640, 0x00000001, 0x00000000, 1, 0}, {0x8641, 0x00000065, 0x00000000, 1, 0}, {0x8642, 0x00000007, 0x00000000, 1, 0}, {0x8652, 0x00000002, 0x00000000, 1, 0}, {0x8665, 0x00000010, 0x00000000, 1, 0}, // InfoFrame Extraction {0x8709, 0x000000ff, 0x00000000, 1, 0}, {0x870b, 0x0000002c, 0x00000000, 1, 0}, {0x870c, 0x00000053, 0x00000000, 1, 0}, {0x870d, 0x00000001, 0x00000000, 1, 0}, {0x870e, 0x00000030, 0x00000000, 1, 0}, {0x9007, 0x00000010, 0x00000000, 1, 0}, {0x854a, 0x00000001, 0x00000000, 1, 0}, // Output Control {0x0004, 0x00000cf7, 0x00000000, 2, 0}, }; static struct reg_value tc358743_setting_YUV422_4lane_1080P_30fps_1920_1080_300MHz[] = { {0x7080, 0x00000000, 0x00000000, 2, 0}, // IR control resister {0x0004, 0x00000084, 0x00000000, 2, 0}, // Internal Generated output pattern,Do not send InfoFrame data out to CSI2,Audio output to CSI2-TX i/f,I2C address index increments on every data byte transfer, disable audio and video TX buffers {0x0002, 0x00000f00, 0x00000000, 2, 100},//0}, // Reset devices and set normal operatio (not sleep) {0x0002, 0x00000000, 0x00000000, 2, 1000},//0}, // Clear reset bits {0x0006, 0x000001f8, 0x00000000, 2, 0}, // FIFO level = 1f8 = 504 {0x0014, 0x00000000, 0x00000000, 2, 0}, // Clear interrupt status bits {0x0016, 0x000005ff, 0x00000000, 2, 0}, // Mask audio mute, CSI-TX, and the other interrups // Program CSI Tx PLL //{0x0020, 0x000080c7, 0x00000000, 2, 0}, // Input divider setting = 0x8 -> Division ratio = (PRD3..0) + 1 = 9, Feedback divider setting = 0xc7 -> Division ratio = (FBD8...0) + 1 = 200 {0x0020, 0x000080c7, 0x00000000, 2, 0}, // Input divider setting = 0x8 -> Division ratio = (PRD3..0) + 1 = 9, Feedback divider setting = 0xc7 -> Division ratio = (FBD8...0) + 1 = 200 {0x0022, 0x00000213, 0x00000000, 2, 0}, // HSCK frequency = 500MHz – 1GHz HSCK frequency, Loop bandwidth setting = 50% of maximum loop bandwidth (default), REFCLK toggling –> normal operation, REFCLK stops -> no oscillation, Bypass clock = normal operation, clocks switched off (output LOW), PLL Reset normal operation, PLL Enable = PLL on // CSI Tx PHY (32-bit Registers) {0x0140, 0x00000000, 0x00000000, 4, 0}, // Clock Lane DPHY Control: Bypass Lane Enable from PPI Layer enable. {0x0144, 0x00000000, 0x00000000, 4, 0}, // Data Lane 0 DPHY Control: Bypass Lane Enable from PPI Layer enable. {0x0148, 0x00000000, 0x00000000, 4, 0}, // Data Lane 1 DPHY Control: Bypass Lane Enable from PPI Layer enable. {0x014c, 0x00000000, 0x00000000, 4, 0}, // Data Lane 2 DPHY Control: Bypass Lane Enable from PPI Layer enable. {0x0150, 0x00000000, 0x00000000, 4, 0}, // Data Lane 3 DPHY Control: Bypass Lane Enable from PPI Layer enable. // CSI Tx PPI (32-bit Registers) {0x0210, 0x00001e00, 0x00000000, 4, 0}, // LINEINITCNT: Line Initialization Wait Counter = 0x1e00 = 7680 {0x0214, 0x00000003, 0x00000000, 4, 0}, // LPTXTIMECNT: SYSLPTX Timing Generation Counter = 3 {0x0218, 0x00001402, 0x00000000, 4, 0}, // TCLK_HEADERCNT: TCLK_ZERO Counter = 0x14 = 20, TCLK_PREPARE Counter = 0x02 = 2 {0x021c, 0x00000000, 0x00000000, 4, 0}, // TCLK_TRAILCNT: TCLK_TRAIL Counter = 0 {0x0220, 0x00000003, 0x00000000, 4, 0}, // THS_HEADERCNT: THS_ZERO Counter = 0, THS_PREPARE Counter = 3 {0x0224, 0x00004a00, 0x00000000, 4, 0}, // TWAKEUP: TWAKEUP Counter = 0x4a00 = 18944 {0x0228, 0x00000008, 0x00000000, 4, 0}, // TCLK_POSTCNT: TCLK_POST Counter = 8 {0x022c, 0x00000002, 0x00000000, 4, 0}, // THS_TRAILCNT: THS_TRAIL Counter = 2 {0x0234, 0x0000001f, 0x00000000, 4, 0}, // HSTXVREGEN: Enable voltage regulators for lanes and clk {0x0238, 0x00000001, 0x00000000, 4, 0}, // TXOPTIONCNTRL: Set Continuous Clock Mode {0x0204, 0x00000001, 0x00000000, 4, 0}, // PPI STARTCNTRL: start PPI function {0x0518, 0x00000001, 0x00000000, 4, 0}, // CSI_START: start {0x0500, 0xa30080a6, 0x00000000, 4, 0}, // CSI Configuration Register: set register 0x040C with data 0x80a6 (CSI MOde, Disables the HTX_TO timer, High-Speed data transfer is performed to Tx, DSCClk Stays in HS mode when Data Lane goes to LP, 4 Data Lanes,The EOT packet is automatically granted at the end of HS transfer then is transmitted) // HDMI Interrupt Mask {0x8502, 0x00000001, 0x00000000, 1, 0}, // SYSTEM INTERRUPT: clear DDC power change detection interrupt {0x8512, 0x000000fe, 0x00000000, 1, 0}, // SYS INTERRUPT MASK: DDC power change detection interrupt not masked {0x8514, 0x00000000, 0x00000000, 1, 0}, // PACKET INTERRUPT MASK: unmask all {0x8515, 0x00000000, 0x00000000, 1, 0}, // CBIT INTERRUPT MASK: unmask all {0x8516, 0x00000000, 0x00000000, 1, 0}, // AUDIO INTERRUPT MASK: unmask all // HDMI Audio RefClk (27 MHz) {0x8531, 0x00000001, 0x00000000, 1, 0}, // PHY CONTROL0: 27MHz, DDC5V detection operation. {0x8540, 0x00000a8c, 0x00000000, 1, 0}, // SYS FREQ0 Register: 27MHz {0x8630, 0x00041eb0, 0x00000000, 1, 0}, // Audio FS Lock Detect Control: for 27MHz {0x8670, 0x00000001, 0x00000000, 1, 0}, // AUDIO PLL Setting: For REFCLK = 27MHz // HDMI PHY {0x8532, 0x00000080, 0x00000000, 1, 0}, // {0x8536, 0x00000040, 0x00000000, 1, 0}, // {0x853f, 0x0000000a, 0x00000000, 1, 0}, // // HDMI System {0x8543, 0x00000032, 0x00000000, 1, 0}, // DDC CONTROL: DDC_ACK output terminal H active, DDC5V_active detect delay 200ms {0x8544, 0x00000010, 0x00000000, 1, 100}, // HPD Control Register: HOTPLUG output ON/OFF control mode = DDC5V detection interlock {0x8545, 0x00000031, 0x00000000, 1, 0}, // ANA CONTROL: PLL charge pump setting for Audio = normal, DAC/PLL power ON/OFF setting for Audio = ON {0x8546, 0x0000002d, 0x00000000, 1, 0}, // AVMUTE CONTROL: AVM_CTL = 0x2d // EDID {0x85c7, 0x00000001, 0x00000000, 1, 0}, // EDID MODE REGISTER: nternal EDID-RAM & DDC2B mode {0x85cb, 0x00000001, 0x00000000, 1, 0}, // EDID Length REGISTER 2: EDID data size stored in RAM (upper address bits) = 0x1 (Size = 0x100 = 256) // HDCP Setting {0x85d1, 0x00000001, 0x00000000, 1, 0}, // {0x8560, 0x00000024, 0x00000000, 1, 0}, // HDCP MODE: HDCP automatic reset when DVI⇔HDMI switched = on, HDCP Line Rekey timing switch = 7clk mode (Data island delay ON), Bcaps[5] KSVINFO_READY(0x8840[5]) auto clear mode = Auto clear using AKSV write {0x8563, 0x00000011, 0x00000000, 1, 0}, // {0x8564, 0x0000000f, 0x00000000, 1, 0}, // // RGB --> YUV Conversion {0x8571, 0x00000002, 0x00000000, 1, 0}, // {0x8573, 0x000000c1, 0x00000000, 1, 0}, // VOUT SET2 REGISTER: 422 fixed output, Video Output 422 conversion mode selection 000: During 444 input, 3tap filter; during 422 input, simple decimation, Enable RGB888 to YUV422 Conversion (Fixed Color output) {0x8574, 0x00000008, 0x00000000, 1, 0}, // VOUT SET3 REGISTER (VOUT_SET3): Follow register bit 0x8573[7] setting {0x8576, 0x00000060, 0x00000000, 1, 0}, // VOUT_COLOR: Output Color = 601 YCbCr Limited, Input Pixel Repetition judgment = automatic, Input Pixel Repetition HOST setting = no repetition // HDMI Audio In Setting {0x8600, 0x00000000, 0x00000000, 1, 0}, {0x8602, 0x000000f3, 0x00000000, 1, 0}, {0x8603, 0x00000002, 0x00000000, 1, 0}, {0x8604, 0x0000000c, 0x00000000, 1, 0}, {0x8606, 0x00000005, 0x00000000, 1, 0}, {0x8607, 0x00000000, 0x00000000, 1, 0}, {0x8620, 0x00000022, 0x00000000, 1, 0}, {0x8640, 0x00000001, 0x00000000, 1, 0}, {0x8641, 0x00000065, 0x00000000, 1, 0}, {0x8642, 0x00000007, 0x00000000, 1, 0}, {0x8652, 0x00000002, 0x00000000, 1, 0}, {0x8665, 0x00000010, 0x00000000, 1, 0}, // InfoFrame Extraction {0x8709, 0x000000ff, 0x00000000, 1, 0}, // PACKET INTERRUPT MODE: all enable {0x870b, 0x0000002c, 0x00000000, 1, 0}, // NO PACKET LIMIT: NO_ACP_LIMIT = 0x2, NO_AVI_LIMIT = 0xC {0x870c, 0x00000053, 0x00000000, 1, 0}, // When VS receive interrupt is detected, VS storage register automatic clear, When ACP receive interrupt is detected, ACP storage register automatic clear, When AVI receive interrupt occurs, judge input video signal with RGB and no Repetition, When AVI receive interrupt is detected, AVI storage register automatic clear. {0x870d, 0x00000001, 0x00000000, 1, 0}, // ERROR PACKET LIMIT: Packet continuing receive error occurrence detection threshold = 1 {0x870e, 0x00000030, 0x00000000, 1, 0}, // NO PACKET LIMIT: {0x9007, 0x00000010, 0x00000000, 1, 0}, // {0x854a, 0x00000001, 0x00000000, 1, 0}, // Initialization completed flag // Output Control {0x0004, 0x00000cf7, 0x00000000, 2, 0}, // Configuration Control Register: Power Island Normal, I2S/TDM clock are free running, Enable 2 Audio channels, Audio channel number Auto detect by HW, I2S/TDM Data no delay, Select YCbCr422 8-bit (HDMI YCbCr422 12-bit data format), Send InfoFrame data out to CSI2, Audio output to I2S i/f (valid for 2 channel only), I2C address index increments on every data byte transfer, Audio and Video tx buffres enable. }; /* list of image formats supported by TCM825X sensor */ static const struct v4l2_fmtdesc tc358743_formats[] = { { .description = "RGB888 (RGB24)", .pixelformat = V4L2_PIX_FMT_RGB24, /* 24 RGB-8-8-8 */ .flags = MIPI_DT_RGB888 // 0x24 }, { .description = "RAW12 (Y/CbCr 4:2:0)", .pixelformat = V4L2_PIX_FMT_UYVY, /* 12 Y/CbCr 4:2:0 */ .flags = MIPI_DT_RAW12 // 0x2c }, { .description = "YUV 4:2:2 8-bit", .pixelformat = V4L2_PIX_FMT_YUYV, /* 8 8-bit color */ .flags = MIPI_DT_YUV422 // 0x1e /* UYVY... */ }, }; static struct tc358743_mode_info tc358743_mode_info_data[2][tc358743_mode_MAX] = { [0][tc358743_mode_720P_60_1280_720] = {tc358743_mode_720P_60_1280_720, 1280, 720, 12, 0, 4, 133, tc358743_setting_YUV422_4lane_720P_60fps_1280_720_133Mhz, ARRAY_SIZE(tc358743_setting_YUV422_4lane_720P_60fps_1280_720_133Mhz), MIPI_DT_YUV422 }, [0][tc358743_mode_1080P_1920_1080] = {tc358743_mode_1080P_1920_1080, 1920, 1080, 15, 0x0b, 4, 300, tc358743_setting_YUV422_4lane_1080P_60fps_1920_1080_300MHz, ARRAY_SIZE(tc358743_setting_YUV422_4lane_1080P_60fps_1920_1080_300MHz), MIPI_DT_YUV422 }, [0][tc358743_mode_INIT1] = {tc358743_mode_INIT1, 1280, 720, 12, 0, 2, 125, tc358743_setting_YUV422_2lane_color_bar_1280_720_125MHz, ARRAY_SIZE(tc358743_setting_YUV422_2lane_color_bar_1280_720_125MHz), MIPI_DT_YUV422 }, [0][tc358743_mode_INIT2] = {tc358743_mode_INIT2, 1280, 720, 12, 0, 4, 125, tc358743_setting_YUV422_4lane_color_bar_1280_720_125MHz, ARRAY_SIZE(tc358743_setting_YUV422_4lane_color_bar_1280_720_125MHz), MIPI_DT_YUV422 }, [0][tc358743_mode_INIT] = {tc358743_mode_INIT, 640, 480, 6, 1, 2, 108, tc358743_setting_YUV422_2lane_color_bar_640_480_108MHz_cont, ARRAY_SIZE(tc358743_setting_YUV422_2lane_color_bar_640_480_108MHz_cont), MIPI_DT_YUV422 }, [0][tc358743_mode_INIT4] = {tc358743_mode_INIT4, 640, 480, 6, 1, 2, 174, tc358743_setting_YUV422_2lane_color_bar_640_480_174MHz, ARRAY_SIZE(tc358743_setting_YUV422_2lane_color_bar_640_480_174MHz), MIPI_DT_YUV422 }, [0][tc358743_mode_INIT3] = {tc358743_mode_INIT3, 1024, 720, 6, 1, 4, 300, tc358743_setting_YUV422_4lane_color_bar_1024_720_200MHz, ARRAY_SIZE(tc358743_setting_YUV422_4lane_color_bar_1024_720_200MHz), MIPI_DT_YUV422 }, [0][tc358743_mode_720P_1280_720] = {tc358743_mode_720P_1280_720, 1280, 720, 12, (0x3e)<<8|(0x3c), 2, 125, tc358743_setting_YUV422_2lane_30fps_720P_1280_720_125MHz, ARRAY_SIZE(tc358743_setting_YUV422_2lane_30fps_720P_1280_720_125MHz), MIPI_DT_YUV422, }, [0][tc358743_mode_480P_720_480] = {tc358743_mode_480P_720_480, 720, 480, 6, (0x02)<<8|(0x00), 2, 125, tc358743_setting_YUV422_2lane_60fps_720_480_125Mhz, ARRAY_SIZE(tc358743_setting_YUV422_2lane_60fps_720_480_125Mhz), MIPI_DT_YUV422, }, [0][tc358743_mode_480P_640_480] = {tc358743_mode_480P_640_480, 640, 480, 6, (0x02)<<8|(0x00), 2, 125, tc358743_setting_YUV422_2lane_60fps_640_480_125Mhz, ARRAY_SIZE(tc358743_setting_YUV422_2lane_60fps_640_480_125Mhz), MIPI_DT_YUV422, }, [0][tc358743_mode_INIT5] = {tc358743_mode_INIT5, 1280, 720, 12, 0, 4, 300, tc358743_setting_YUV422_4lane_color_bar_1280_720_300MHz, ARRAY_SIZE(tc358743_setting_YUV422_4lane_color_bar_1280_720_300MHz), MIPI_DT_YUV422 }, [0][tc358743_mode_INIT6] = {tc358743_mode_INIT6, 1920, 1023, 15, 0, 4, 300, tc358743_setting_YUV422_4lane_color_bar_1920_1023_300MHz, ARRAY_SIZE(tc358743_setting_YUV422_4lane_color_bar_1920_1023_300MHz), MIPI_DT_YUV422 }, [1][tc358743_mode_720P_60_1280_720] = {tc358743_mode_720P_60_1280_720, 1280, 720, 12, 0, 4, 133, tc358743_setting_YUV422_4lane_720P_60fps_1280_720_133Mhz, ARRAY_SIZE(tc358743_setting_YUV422_4lane_720P_60fps_1280_720_133Mhz), MIPI_DT_YUV422 }, [1][tc358743_mode_1080P_1920_1080] = {tc358743_mode_1080P_1920_1080, 1920, 1080, 15, 0xa, 4, 300, tc358743_setting_YUV422_4lane_1080P_30fps_1920_1080_300MHz, ARRAY_SIZE(tc358743_setting_YUV422_4lane_1080P_30fps_1920_1080_300MHz), MIPI_DT_YUV422 }, [1][tc358743_mode_INIT1] = {tc358743_mode_INIT1, 1280, 720, 12, 0, 2, 125, tc358743_setting_YUV422_2lane_color_bar_1280_720_125MHz, ARRAY_SIZE(tc358743_setting_YUV422_2lane_color_bar_1280_720_125MHz), MIPI_DT_YUV422 }, [1][tc358743_mode_INIT2] = {tc358743_mode_INIT2, 1280, 720, 12, 0, 4, 125, tc358743_setting_YUV422_4lane_color_bar_1280_720_125MHz, ARRAY_SIZE(tc358743_setting_YUV422_4lane_color_bar_1280_720_125MHz), MIPI_DT_YUV422 }, [1][tc358743_mode_INIT] = {tc358743_mode_INIT, 640, 480, 6, 1, 2, 108, tc358743_setting_YUV422_2lane_color_bar_640_480_108MHz_cont, ARRAY_SIZE(tc358743_setting_YUV422_2lane_color_bar_640_480_108MHz_cont), MIPI_DT_YUV422 }, [1][tc358743_mode_INIT4] = {tc358743_mode_INIT4, 640, 480, 6, 1, 2, 174, tc358743_setting_YUV422_2lane_color_bar_640_480_174MHz, ARRAY_SIZE(tc358743_setting_YUV422_2lane_color_bar_640_480_174MHz), MIPI_DT_YUV422 }, [1][tc358743_mode_INIT3] = {tc358743_mode_INIT3, 1024, 720, 6, 1, 4, 300, tc358743_setting_YUV422_4lane_color_bar_1024_720_200MHz, ARRAY_SIZE(tc358743_setting_YUV422_4lane_color_bar_1024_720_200MHz), MIPI_DT_YUV422 }, [1][tc358743_mode_720P_1280_720] = {tc358743_mode_720P_1280_720, 1280, 720, 12, (0x3e)<<8|(0x3c), 2, 125, tc358743_setting_YUV422_2lane_30fps_720P_1280_720_125MHz, ARRAY_SIZE(tc358743_setting_YUV422_2lane_30fps_720P_1280_720_125MHz), MIPI_DT_YUV422, }, [1][tc358743_mode_480P_720_480] = {tc358743_mode_480P_720_480, 720, 480, 6, (0x02)<<8|(0x00), 2, 125, tc358743_setting_YUV422_2lane_60fps_720_480_125Mhz, ARRAY_SIZE(tc358743_setting_YUV422_2lane_60fps_720_480_125Mhz), MIPI_DT_YUV422, }, [0][tc358743_mode_480P_640_480] = {tc358743_mode_480P_640_480, 640, 480, 1, (0x02)<<8|(0x00), 2, 125, tc358743_setting_YUV422_2lane_60fps_640_480_125Mhz, ARRAY_SIZE(tc358743_setting_YUV422_2lane_60fps_640_480_125Mhz), MIPI_DT_YUV422, }, [1][tc358743_mode_INIT5] = {tc358743_mode_INIT5, 1280, 720, 12, 0, 4, 300, tc358743_setting_YUV422_4lane_color_bar_1280_720_300MHz, ARRAY_SIZE(tc358743_setting_YUV422_4lane_color_bar_1280_720_300MHz), MIPI_DT_YUV422 }, [1][tc358743_mode_INIT6] = {tc358743_mode_INIT6, 1920, 1023, 15, 0, 4, 300, tc358743_setting_YUV422_4lane_color_bar_1920_1023_300MHz, ARRAY_SIZE(tc358743_setting_YUV422_4lane_color_bar_1920_1023_300MHz), MIPI_DT_YUV422 }, }; static int tc358743_probe(struct i2c_client *adapter, const struct i2c_device_id *device_id); static int tc358743_remove(struct i2c_client *client); static s32 tc358743_read_reg(u16 reg, u32 *val); static s32 tc358743_write_reg(u16 reg, u32 val, int len); static const struct i2c_device_id tc358743_id[] = { {"tc358743_mipi", 0}, {}, }; MODULE_DEVICE_TABLE(i2c, tc358743_id); static struct i2c_driver tc358743_i2c_driver = { .driver = { .owner = THIS_MODULE, .name = "tc358743_mipi", }, .probe = tc358743_probe, .remove = tc358743_remove, .id_table = tc358743_id, }; struct _reg_size { u16 startaddr, endaddr; int size; } tc358743_read_reg_size [] = { {0x0000, 0x005a, 2}, {0x0140, 0x0150, 4}, {0x0204, 0x0238, 4}, {0x040c, 0x0418, 4}, {0x044c, 0x0454, 4}, {0x0500, 0x0518, 4}, {0x0600, 0x06cc, 4}, {0x7000, 0x7100, 2}, {0x8500, 0x8bff, 1}, {0x8c00, 0x8fff, 4}, {0x9000, 0x90ff, 1}, {0x9100, 0x92ff, 1}, {0, 0, 0}, }; static s32 tc358743_write_reg(u16 reg, u32 val, int len) { int i = 0; u32 data = val; u8 au8Buf[6] = {0}; int size = 0; while (0 != tc358743_read_reg_size[i].startaddr || 0 != tc358743_read_reg_size[i].endaddr || 0 != tc358743_read_reg_size[i].size) { if (tc358743_read_reg_size[i].startaddr <= reg && tc358743_read_reg_size[i].endaddr >= reg) { size = tc358743_read_reg_size[i].size; break; } i++; } if (!size) { pr_err("%s:write reg error:reg=%x is not found\n",__func__, reg); return -1; } if (size == 3) { size = 2; } else if (size != len) { pr_err("%s:write reg len error:reg=%x %d instead of %d\n", __func__, reg, len, size); return 0; } while (len > 0) { i = 0; au8Buf[i++] = (reg >> 8) & 0xff; au8Buf[i++] = reg & 0xff; while (size-- > 0) { au8Buf[i++] = (u8)data; data >>= 8; } if (i2c_master_send(tc358743_data.i2c_client, au8Buf, i) < 0) { pr_err("%s:write reg error:reg=%x,val=%x\n", __func__, reg, val); return -1; } len -= (u8)size; reg += (u16)size; } return 0; } static s32 tc358743_read_reg(u16 reg, u32 *val) { u8 au8RegBuf[2] = {0}; u32 u32RdVal = 0; int i=0; int size = 0; while (0 != tc358743_read_reg_size[i].startaddr || 0 != tc358743_read_reg_size[i].endaddr || 0 != tc358743_read_reg_size[i].size) { if (tc358743_read_reg_size[i].startaddr <= reg && tc358743_read_reg_size[i].endaddr >= reg) { size = tc358743_read_reg_size[i].size; break; } i++; } if (!size) return -1; au8RegBuf[0] = reg >> 8; au8RegBuf[1] = reg & 0xff; if (2 != i2c_master_send(tc358743_data.i2c_client, au8RegBuf, 2)) { pr_err("%s:read reg error:reg=%x\n", __func__, reg); return -1; } if (size /*of(u32RdVal)*/ != i2c_master_recv(tc358743_data.i2c_client, (char *)&u32RdVal, size /*of(u32RdVal)*/)) { pr_err("%s:read reg error:reg=%x,val=%x\n", __func__, reg, u32RdVal); return -1; } *val = u32RdVal; return size; } static int tc358743_write_edid(u8 *edid, int len) { int i = 0, off = 0; u8 au8Buf[8+2] = {0}; int size = 0; u16 reg; reg = 0x8C00; off = 0; size = ARRAY_SIZE(au8Buf)-2; pr_debug("Write EDID: %d (%d)\n", len, size); while (len > 0) { i = 0; au8Buf[i++] = (reg >> 8) & 0xff; au8Buf[i++] = reg & 0xff; while (i < ARRAY_SIZE(au8Buf)) { au8Buf[i++] = edid[off++]; } if (i2c_master_send(tc358743_data.i2c_client, au8Buf, i) < 0) { pr_err("%s:write reg error:reg=%x,val=%x\n", __func__, reg, off); return -1; } len -= (u8)size; reg += (u16)size; } pr_debug("Activate EDID\n"); tc358743_write_reg(0x85c7, 0x01, 1); tc358743_write_reg(0x85ca, 0x00, 1); tc358743_write_reg(0x85cb, 0x01, 1); return 0; } static int tc358743_reset(struct sensor_data *sensor) { u32 tgt_fps; /* target frames per secound */ enum tc358743_frame_rate frame_rate = tc358743_60_fps; int ret = -1; det_work_enable(0); while (ret) { tc_standby(1); mdelay(100); tc_standby(0); mdelay(1000); tgt_fps = sensor->streamcap.timeperframe.denominator / sensor->streamcap.timeperframe.numerator; if (tgt_fps == 60) frame_rate = tc358743_60_fps; else if (tgt_fps == 30) frame_rate = tc358743_30_fps; pr_debug("%s: capture mode: %d extended mode: %d fps: %d\n", __func__,sensor->streamcap.capturemode, sensor->streamcap.extendedmode, tgt_fps); ret = tc358743_init_mode(frame_rate, sensor->streamcap.capturemode); if (ret) pr_err("%s: Fail to init tc35874! - retry\n", __func__); } det_work_enable(1); return ret; } void mipi_csi2_swreset(struct mipi_csi2_info *info); #include "../../../../mxc/mipi/mxc_mipi_csi2.h" static int tc358743_init_mode(enum tc358743_frame_rate frame_rate, enum tc358743_mode mode) { struct reg_value *pModeSetting = NULL; s32 i = 0; s32 iModeSettingArySize = 0; register u32 RepeateLines = 0; register int RepeateTimes = 0; register u32 Delay_ms = 0; register u16 RegAddr = 0; register u32 Mask = 0; register u32 Val = 0; u8 Length; u32 RegVal = 0; int retval = 0; void *mipi_csi2_info; u32 mipi_reg; u32 mipi_reg_test[10]; pr_debug("%s rate: %d mode: %d\n", __func__, frame_rate, mode); if ((mode > tc358743_mode_MAX || mode < 0) && (mode != tc358743_mode_INIT)) { pr_debug("%s Wrong tc358743 mode detected! %d. Set mode 0\n", __func__, mode); mode = 0; } mipi_csi2_info = mipi_csi2_get_info(); pr_debug("%s rate: %d mode: %d, info %p\n", __func__, frame_rate, mode, mipi_csi2_info); /* initial mipi dphy */ tc358743_toggle_hpd(!hpd_active); if (mipi_csi2_info) { pr_debug("%s: mipi_csi2_info:\n" "mipi_en: %d\n" "ipu_id: %d\n" "csi_id: %d\n" "v_channel: %d\n" "lanes: %d\n" "datatype: %d\n" "dphy_clk: %p\n" "pixel_clk: %p\n" "mipi_csi2_base:%p\n" "pdev: %p\n" , __func__, ((struct mipi_csi2_info *)mipi_csi2_info)->mipi_en, ((struct mipi_csi2_info *)mipi_csi2_info)->ipu_id, ((struct mipi_csi2_info *)mipi_csi2_info)->csi_id, ((struct mipi_csi2_info *)mipi_csi2_info)->v_channel, ((struct mipi_csi2_info *)mipi_csi2_info)->lanes, ((struct mipi_csi2_info *)mipi_csi2_info)->datatype, ((struct mipi_csi2_info *)mipi_csi2_info)->dphy_clk, ((struct mipi_csi2_info *)mipi_csi2_info)->pixel_clk, ((struct mipi_csi2_info *)mipi_csi2_info)->mipi_csi2_base, ((struct mipi_csi2_info *)mipi_csi2_info)->pdev ); if (!mipi_csi2_get_status(mipi_csi2_info)) mipi_csi2_enable(mipi_csi2_info); if (mipi_csi2_get_status(mipi_csi2_info)) { int ifmt; if (tc358743_mode_info_data[frame_rate][mode].lanes != 0) { pr_debug("%s Change lanes: from %d to %d\n", __func__, ((struct mipi_csi2_info *)mipi_csi2_info)->lanes, tc358743_mode_info_data[frame_rate][mode].lanes); ((struct mipi_csi2_info *)mipi_csi2_info)->lanes = tc358743_mode_info_data[frame_rate][mode].lanes; ((struct mipi_csi2_info *)mipi_csi2_info)->lanes = tc358743_mode_info_data[frame_rate][mode].lanes; } pr_debug("Now Using %d lanes\n",mipi_csi2_set_lanes(mipi_csi2_info)); /*Only reset MIPI CSI2 HW at sensor initialize*/ if (!hdmi_mode) // is this during reset mipi_csi2_reset(mipi_csi2_info); pr_debug("%s format: %x\n", __func__, tc358743_data.pix.pixelformat); for (ifmt = 0; ifmt < ARRAY_SIZE(tc358743_formats); ifmt++) if (tc358743_mode_info_data[frame_rate][mode].flags == tc358743_formats[ifmt].flags) { tc358743_data.pix.pixelformat = tc358743_formats[ifmt].pixelformat; pr_debug("%s: %s (%x, %x)\n", __func__, tc358743_formats[ifmt].description, tc358743_data.pix.pixelformat, tc358743_formats[ifmt].flags); mipi_csi2_set_datatype(mipi_csi2_info, tc358743_formats[ifmt].flags); break; } if (ifmt >= ARRAY_SIZE(tc358743_formats)) { pr_err("currently this sensor format (0x%x) can not be supported!\n", tc358743_data.pix.pixelformat); return -1; } } else { pr_err("Can not enable mipi csi2 driver!\n"); return -1; } } else { pr_err("Fail to get mipi_csi2_info!\n"); return -1; } { pModeSetting = tc358743_mode_info_data[frame_rate][mode].init_data_ptr; iModeSettingArySize = tc358743_mode_info_data[frame_rate][mode].init_data_size; tc358743_data.pix.width = tc358743_mode_info_data[frame_rate][mode].width; tc358743_data.pix.height = tc358743_mode_info_data[frame_rate][mode].height; pr_debug("%s: Set %d regs from %p for frs %d mode %d with width %d height %d\n", __func__, iModeSettingArySize, pModeSetting, frame_rate, mode, tc358743_data.pix.width, tc358743_data.pix.height); for (i = 0; i < iModeSettingArySize; ++i) { pModeSetting = tc358743_mode_info_data[frame_rate][mode].init_data_ptr + i; Delay_ms = pModeSetting->u32Delay_ms & (0xffff); RegAddr = pModeSetting->u16RegAddr; Val = pModeSetting->u32Val; Mask = pModeSetting->u32Mask; Length = pModeSetting->u8Length; if (Mask) { retval = tc358743_read_reg(RegAddr, &RegVal); if (retval < 0) break; RegVal &= ~(u8)Mask; Val &= Mask; Val |= RegVal; } retval = tc358743_write_reg(RegAddr, Val, Length); if (retval < 0) break; if (Delay_ms) msleep(Delay_ms); if (0 != ((pModeSetting->u32Delay_ms>>16) & (0xff))) { if (!RepeateTimes) { RepeateTimes = (pModeSetting->u32Delay_ms>>16) & (0xff); RepeateLines = (pModeSetting->u32Delay_ms>>24) & (0xff); } if (--RepeateTimes > 0) { i -= RepeateLines; } } } if (retval < 0) { pr_err("%s: Fail to write REGS to tc35874!\n", __func__); goto err; } } if (!hdmi_mode) // is this during reset if ((retval = tc358743_write_edid(cHDMIEDID, ARRAY_SIZE(cHDMIEDID)))) pr_err("%s: Fail to write EDID to tc35874!\n", __func__); tc358743_toggle_hpd(hpd_active); if (mipi_csi2_info) { unsigned int i = 0; /* wait for mipi sensor ready */ mipi_reg = mipi_csi2_dphy_status(mipi_csi2_info); while ((mipi_reg == 0x200) && (i < 10)) { mipi_reg_test[i] = mipi_reg; mipi_reg = mipi_csi2_dphy_status(mipi_csi2_info); i++; msleep(10); } if (i >= 10) { pr_err("mipi csi2 can not receive sensor clk!\n"); return -1; } { int j; for (j = 0; j < i; j++) { pr_debug("%d mipi csi2 dphy status %x\n", j, mipi_reg_test[j]); } } i = 0; /* wait for mipi stable */ mipi_reg = mipi_csi2_get_error1(mipi_csi2_info); while ((mipi_reg != 0x0) && (i < 10)) { mipi_reg_test[i] = mipi_reg; mipi_reg = mipi_csi2_get_error1(mipi_csi2_info); i++; msleep(10); } if (i >= 10) { pr_err("mipi csi2 can not reveive data correctly!\n"); return -1; } { int j; for (j = 0; j < i; j++) { pr_debug("%d mipi csi2 err1 %x\n", j, mipi_reg_test[j]); } } } err: return (retval>0)?0:retval; } /* --------------- IOCTL functions from v4l2_int_ioctl_desc --------------- */ static int ioctl_g_ifparm(struct v4l2_int_device *s, struct v4l2_ifparm *p) { pr_debug("%s\n", __func__); if (s == NULL) { pr_err(" ERROR!! no slave device set!\n"); return -1; } memset(p, 0, sizeof(*p)); p->u.bt656.clock_curr = TC358743_XCLK_MIN; //tc358743_data.mclk; pr_debug("%s: clock_curr=mclk=%d\n", __func__, tc358743_data.mclk); p->if_type = V4L2_IF_TYPE_BT656; p->u.bt656.mode = V4L2_IF_TYPE_BT656_MODE_NOBT_8BIT; p->u.bt656.clock_min = TC358743_XCLK_MIN; p->u.bt656.clock_max = TC358743_XCLK_MAX; p->u.bt656.bt_sync_correct = 1; /* Indicate external vsync */ return 0; } /*! * ioctl_s_power - V4L2 sensor interface handler for VIDIOC_S_POWER ioctl * @s: pointer to standard V4L2 device structure * @on: indicates power mode (on or off) * * Turns the power on or off, depending on the value of on and returns the * appropriate error code. */ static int ioctl_s_power(struct v4l2_int_device *s, int on) { struct sensor_data *sensor = s->priv; pr_debug("%s: %d\n", __func__, on); if (on && !sensor->on) { if (io_regulator) if (regulator_enable(io_regulator) != 0) return -EIO; if (core_regulator) if (regulator_enable(core_regulator) != 0) return -EIO; if (gpo_regulator) if (regulator_enable(gpo_regulator) != 0) return -EIO; if (analog_regulator) if (regulator_enable(analog_regulator) != 0) return -EIO; /* Make sure power on */ tc_standby(0); } else if (!on && sensor->on) { if (analog_regulator) regulator_disable(analog_regulator); if (core_regulator) regulator_disable(core_regulator); if (io_regulator) regulator_disable(io_regulator); if (gpo_regulator) regulator_disable(gpo_regulator); if (!hdmi_mode) tc358743_reset(sensor); } sensor->on = on; return 0; } /*! * ioctl_g_parm - V4L2 sensor interface handler for VIDIOC_G_PARM ioctl * @s: pointer to standard V4L2 device structure * @a: pointer to standard V4L2 VIDIOC_G_PARM ioctl structure * * Returns the sensor's video CAPTURE parameters. */ static int ioctl_g_parm(struct v4l2_int_device *s, struct v4l2_streamparm *a) { struct sensor_data *sensor = s->priv; struct v4l2_captureparm *cparm = &a->parm.capture; int ret = 0; pr_debug("%s type: %x\n", __func__, a->type); switch (a->type) { /* This is the only case currently handled. */ case V4L2_BUF_TYPE_VIDEO_CAPTURE: memset(a, 0, sizeof(*a)); a->type = V4L2_BUF_TYPE_VIDEO_CAPTURE; cparm->capability = sensor->streamcap.capability; cparm->timeperframe = sensor->streamcap.timeperframe; cparm->capturemode = sensor->streamcap.capturemode; cparm->extendedmode = sensor->streamcap.extendedmode; ret = 0; break; /* These are all the possible cases. */ case V4L2_BUF_TYPE_VIDEO_OUTPUT: case V4L2_BUF_TYPE_VIDEO_OVERLAY: case V4L2_BUF_TYPE_VBI_CAPTURE: case V4L2_BUF_TYPE_VBI_OUTPUT: case V4L2_BUF_TYPE_SLICED_VBI_CAPTURE: case V4L2_BUF_TYPE_SLICED_VBI_OUTPUT: ret = -EINVAL; break; default: pr_debug(" type is unknown - %d\n", a->type); ret = -EINVAL; break; } det_work_enable(1); pr_debug("%s done %d\n", __func__, ret); return ret; } static int tc358743_toggle_hpd(int active) { int ret = 0; if (active) { ret += tc358743_write_reg(0x8544, 0x00, 1); mdelay(500); ret += tc358743_write_reg(0x8544, 0x10, 1); } else { ret += tc358743_write_reg(0x8544, 0x10, 1); mdelay(500); ret += tc358743_write_reg(0x8544, 0x00, 1); } return ret; } /*! * ioctl_s_parm - V4L2 sensor interface handler for VIDIOC_S_PARM ioctl * @s: pointer to standard V4L2 device structure * @a: pointer to standard V4L2 VIDIOC_S_PARM ioctl structure * * Configures the sensor to use the input parameters, if possible. If * not possible, reverts to the old parameters and returns the * appropriate error code. */ static int ioctl_s_parm(struct v4l2_int_device *s, struct v4l2_streamparm *a) { struct sensor_data *sensor = s->priv; struct v4l2_fract *timeperframe = &a->parm.capture.timeperframe; u32 tgt_fps; /* target frames per secound */ enum tc358743_frame_rate frame_rate = tc358743_60_fps, frame_rate_now = tc358743_60_fps; int ret = 0; pr_debug("%s\n", __func__); det_work_enable(0); /* Make sure power on */ tc_standby(0); switch (a->type) { /* This is the only case currently handled. */ case V4L2_BUF_TYPE_VIDEO_CAPTURE: /* Check that the new frame rate is allowed. */ if ((timeperframe->numerator == 0) || (timeperframe->denominator == 0)) { timeperframe->denominator = DEFAULT_FPS; timeperframe->numerator = 1; } tgt_fps = timeperframe->denominator / timeperframe->numerator; if (tgt_fps > MAX_FPS) { timeperframe->denominator = MAX_FPS; timeperframe->numerator = 1; } else if (tgt_fps < MIN_FPS) { timeperframe->denominator = MIN_FPS; timeperframe->numerator = 1; } /* Actual frame rate we use */ tgt_fps = timeperframe->denominator / timeperframe->numerator; if (tgt_fps == 60) frame_rate = tc358743_60_fps; else if (tgt_fps == 30) frame_rate = tc358743_30_fps; else { pr_err(" The camera frame rate is not supported!\n"); ret = -EINVAL; break; } if ((u32)a->parm.capture.capturemode > tc358743_mode_MAX) { a->parm.capture.capturemode = 0; pr_debug("%s: Forse extended mode: %d \n", __func__,(u32)a->parm.capture.capturemode); } tgt_fps = sensor->streamcap.timeperframe.denominator / sensor->streamcap.timeperframe.numerator; if (tgt_fps == 60) frame_rate_now = tc358743_60_fps; else if (tgt_fps == 30) frame_rate_now = tc358743_30_fps; if (frame_rate_now != frame_rate || sensor->streamcap.capturemode != (u32)a->parm.capture.capturemode || sensor->streamcap.extendedmode != (u32)a->parm.capture.extendedmode) { sensor->streamcap.timeperframe = *timeperframe; sensor->streamcap.capturemode = (u32)a->parm.capture.capturemode; sensor->streamcap.extendedmode = (u32)a->parm.capture.extendedmode; pr_debug("%s: capture mode: %d extended mode: %d \n", __func__,sensor->streamcap.capturemode, sensor->streamcap.extendedmode); ret = tc358743_init_mode(frame_rate, sensor->streamcap.capturemode); } else { pr_debug("%s: Keep current settings\n", __func__); } break; /* These are all the possible cases. */ case V4L2_BUF_TYPE_VIDEO_OUTPUT: case V4L2_BUF_TYPE_VIDEO_OVERLAY: case V4L2_BUF_TYPE_VBI_CAPTURE: case V4L2_BUF_TYPE_VBI_OUTPUT: case V4L2_BUF_TYPE_SLICED_VBI_CAPTURE: case V4L2_BUF_TYPE_SLICED_VBI_OUTPUT: pr_debug(" type is not " \ "V4L2_BUF_TYPE_VIDEO_CAPTURE but %d\n", a->type); ret = -EINVAL; break; default: pr_debug(" type is unknown - %d\n", a->type); ret = -EINVAL; break; } if (ret) det_work_enable(1); return ret; } /*! * ioctl_g_ctrl - V4L2 sensor interface handler for VIDIOC_G_CTRL ioctl * @s: pointer to standard V4L2 device structure * @vc: standard V4L2 VIDIOC_G_CTRL ioctl structure * * If the requested control is supported, returns the control's current * value from the video_control[] array. Otherwise, returns -EINVAL * if the control is not supported. */ static int ioctl_g_ctrl(struct v4l2_int_device *s, struct v4l2_control *vc) { int ret = 0; pr_debug("%s\n", __func__); switch (vc->id) { case V4L2_CID_BRIGHTNESS: vc->value = tc358743_data.brightness; break; case V4L2_CID_HUE: vc->value = tc358743_data.hue; break; case V4L2_CID_CONTRAST: vc->value = tc358743_data.contrast; break; case V4L2_CID_SATURATION: vc->value = tc358743_data.saturation; break; case V4L2_CID_RED_BALANCE: vc->value = tc358743_data.red; break; case V4L2_CID_BLUE_BALANCE: vc->value = tc358743_data.blue; break; case V4L2_CID_EXPOSURE: vc->value = tc358743_data.ae_mode; break; default: ret = -EINVAL; } return ret; } /*! * ioctl_s_ctrl - V4L2 sensor interface handler for VIDIOC_S_CTRL ioctl * @s: pointer to standard V4L2 device structure * @vc: standard V4L2 VIDIOC_S_CTRL ioctl structure * * If the requested control is supported, sets the control's current * value in HW (and updates the video_control[] array). Otherwise, * returns -EINVAL if the control is not supported. */ static int ioctl_s_ctrl(struct v4l2_int_device *s, struct v4l2_control *vc) { int retval = 0; pr_debug("In tc358743:ioctl_s_ctrl %d\n", vc->id); switch (vc->id) { case V4L2_CID_BRIGHTNESS: break; case V4L2_CID_CONTRAST: break; case V4L2_CID_SATURATION: break; case V4L2_CID_HUE: break; case V4L2_CID_AUTO_WHITE_BALANCE: break; case V4L2_CID_DO_WHITE_BALANCE: break; case V4L2_CID_RED_BALANCE: break; case V4L2_CID_BLUE_BALANCE: break; case V4L2_CID_GAMMA: break; case V4L2_CID_EXPOSURE: break; case V4L2_CID_AUTOGAIN: break; case V4L2_CID_GAIN: break; case V4L2_CID_HFLIP: break; case V4L2_CID_VFLIP: break; default: retval = -EPERM; break; } return retval; } int get_pixelformat(int index) { int ifmt; for (ifmt = 0; ifmt < ARRAY_SIZE(tc358743_formats); ifmt++) if (tc358743_mode_info_data[0][index].flags == tc358743_formats[ifmt].flags) break; if (ifmt == ARRAY_SIZE(tc358743_formats)) ifmt = 0; /* Default = RBG888 */ return ifmt; } /*! * ioctl_enum_framesizes - V4L2 sensor interface handler for * VIDIOC_ENUM_FRAMESIZES ioctl * @s: pointer to standard V4L2 device structure * @fsize: standard V4L2 VIDIOC_ENUM_FRAMESIZES ioctl structure * * Return 0 if successful, otherwise -EINVAL. */ static int ioctl_enum_framesizes(struct v4l2_int_device *s, struct v4l2_frmsizeenum *fsize) { pr_debug("%s, INDEX: %d\n", __func__,fsize->index); if (fsize->index > tc358743_mode_MAX) return -EINVAL; fsize->pixel_format = tc358743_formats[get_pixelformat(fsize->index)].pixelformat; fsize->discrete.width = tc358743_mode_info_data[0][fsize->index].width; fsize->discrete.height = tc358743_mode_info_data[0][fsize->index].height; pr_debug("%s %d:%d format: %x\n", __func__, fsize->discrete.width, fsize->discrete.height, fsize->pixel_format); return 0; } /*! * ioctl_g_chip_ident - V4L2 sensor interface handler for * VIDIOC_DBG_G_CHIP_IDENT ioctl * @s: pointer to standard V4L2 device structure * @id: pointer to int * * Return 0. */ static int ioctl_g_chip_ident(struct v4l2_int_device *s, int *id) { ((struct v4l2_dbg_chip_ident *)id)->match.type = V4L2_CHIP_MATCH_I2C_DRIVER; strcpy(((struct v4l2_dbg_chip_ident *)id)->match.name, "tc358743_mipi"); return 0; } /*! * ioctl_init - V4L2 sensor interface handler for VIDIOC_INT_INIT * @s: pointer to standard V4L2 device structure */ static int ioctl_init(struct v4l2_int_device *s) { pr_debug("%s\n", __func__); return 0; } /*! * ioctl_enum_fmt_cap - V4L2 sensor interface handler for VIDIOC_ENUM_FMT * @s: pointer to standard V4L2 device structure * @fmt: pointer to standard V4L2 fmt description structure * * Return 0. */ static int ioctl_enum_fmt_cap(struct v4l2_int_device *s, struct v4l2_fmtdesc *fmt) { pr_debug("%s\n", __func__); if (fmt->index > tc358743_mode_MAX) return -EINVAL; fmt->pixelformat = tc358743_formats[get_pixelformat(fmt->index)].pixelformat; pr_debug("%s: format: %x\n", __func__, fmt->pixelformat); return 0; } static int ioctl_try_fmt_cap(struct v4l2_int_device *s, struct v4l2_format *f) { struct sensor_data *sensor = s->priv; u32 tgt_fps; /* target frames per secound */ enum tc358743_frame_rate frame_rate; // enum image_size isize; int ifmt; struct v4l2_pix_format *pix = &f->fmt.pix; pr_debug("%s\n", __func__); tgt_fps = sensor->streamcap.timeperframe.denominator / sensor->streamcap.timeperframe.numerator; if (tgt_fps == 60) { frame_rate = tc358743_60_fps; } else if (tgt_fps == 30) { frame_rate = tc358743_30_fps; } else { pr_debug("%s: %d fps (%d,%d) is not supported\n", __func__, tgt_fps, sensor->streamcap.timeperframe.denominator,sensor->streamcap.timeperframe.numerator); return -EINVAL; } tc358743_data.pix.width = pix->width = tc358743_mode_info_data[frame_rate][sensor->streamcap.capturemode].width; tc358743_data.pix.height = pix->height = tc358743_mode_info_data[frame_rate][sensor->streamcap.capturemode].height; for (ifmt = 0; ifmt < ARRAY_SIZE(tc358743_formats); ifmt++) if (tc358743_mode_info_data[frame_rate][sensor->streamcap.capturemode].flags == tc358743_formats[ifmt].flags) break; if (ifmt == ARRAY_SIZE(tc358743_formats)) ifmt = 0; /* Default = RBG888 */ tc358743_data.pix.pixelformat = pix->pixelformat = tc358743_formats[ifmt].pixelformat; pix->field = V4L2_FIELD_NONE; pix->bytesperline = pix->width * 4; pix->sizeimage = pix->bytesperline * pix->height; pix->priv = 0; switch (pix->pixelformat) { case V4L2_PIX_FMT_UYVY: default: pix->colorspace = V4L2_COLORSPACE_SRGB; break; } { u32 u32val; int ret = tc358743_read_reg(0x8520,&u32val); pr_debug("SYS_STATUS: 0x%x, ret val: %d \n",u32val,ret); ret = tc358743_read_reg(0x8521,&u32val); pr_debug("VI_STATUS0: 0x%x, ret val: %d \n",u32val,ret); ret = tc358743_read_reg(0x8522,&u32val); pr_debug("VI_STATUS1: 0x%x, ret val: %d \n",u32val,ret); ret = tc358743_read_reg(0x8525,&u32val); pr_debug("VI_STATUS2: 0x%x, ret val: %d \n",u32val,ret); ret = tc358743_read_reg(0x8528,&u32val); pr_debug("VI_STATUS3: 0x%x, ret val: %d \n",u32val,ret); pr_debug("%s %d:%d format: %x\n", __func__, pix->width, pix->height, pix->pixelformat); } return 0; } /*! * ioctl_g_fmt_cap - V4L2 sensor interface handler for ioctl_g_fmt_cap * @s: pointer to standard V4L2 device structure * @f: pointer to standard V4L2 v4l2_format structure * * Returns the sensor's current pixel format in the v4l2_format * parameter. */ static int ioctl_g_fmt_cap(struct v4l2_int_device *s, struct v4l2_format *f) { pr_debug("%s\n", __func__); return ioctl_try_fmt_cap(s, f); } /*! * ioctl_dev_init - V4L2 sensor interface handler for vidioc_int_dev_init_num * @s: pointer to standard V4L2 device structure * * Initialise the device when slave attaches to the master. */ static int ioctl_dev_init(struct v4l2_int_device *s) { struct sensor_data *sensor = s->priv; u32 tgt_xclk; /* target xclk */ u32 tgt_fps; /* target frames per secound */ int ret = 0; enum tc358743_frame_rate frame_rate; void *mipi_csi2_info; pr_debug("%s\n", __func__); tc358743_data.on = true; /* mclk */ tgt_xclk = tc358743_data.mclk; tgt_xclk = min(tgt_xclk, (u32)TC358743_XCLK_MAX); tgt_xclk = max(tgt_xclk, (u32)TC358743_XCLK_MIN); tc358743_data.mclk = tgt_xclk; pr_debug("%s: Setting mclk to %d MHz\n", __func__, tc358743_data.mclk / 1000000); // set_mclk_rate(&tc358743_data.mclk, tc358743_data.mclk_source); // pr_debug("%s: After mclk to %d MHz\n", __func__, tc358743_data.mclk / 1000000); /* Default camera frame rate is set in probe */ tgt_fps = sensor->streamcap.timeperframe.denominator / sensor->streamcap.timeperframe.numerator; if (tgt_fps == 60) frame_rate = tc358743_60_fps; else if (tgt_fps == 30) frame_rate = tc358743_30_fps; else return -EINVAL; mipi_csi2_info = mipi_csi2_get_info(); /* enable mipi csi2 */ if (mipi_csi2_info) { mipi_csi2_enable(mipi_csi2_info); } else { pr_err("Fail to get mipi_csi2_info!\n"); return -EPERM; } pr_debug("%s done\n", __func__); return ret; } /*! * ioctl_dev_exit - V4L2 sensor interface handler for vidioc_int_dev_exit_num * @s: pointer to standard V4L2 device structure * * Delinitialise the device when slave detaches to the master. */ static int ioctl_dev_exit(struct v4l2_int_device *s) { void *mipi_csi2_info; mipi_csi2_info = mipi_csi2_get_info(); /* disable mipi csi2 */ if (mipi_csi2_info) if (mipi_csi2_get_status(mipi_csi2_info)) mipi_csi2_disable(mipi_csi2_info); return 0; } /*! * This structure defines all the ioctls for this module and links them to the * enumeration. */ static struct v4l2_int_ioctl_desc tc358743_ioctl_desc[] = { {vidioc_int_dev_init_num, (v4l2_int_ioctl_func*) ioctl_dev_init}, {vidioc_int_dev_exit_num, ioctl_dev_exit}, {vidioc_int_s_power_num, (v4l2_int_ioctl_func*) ioctl_s_power}, {vidioc_int_g_ifparm_num, (v4l2_int_ioctl_func*) ioctl_g_ifparm}, {vidioc_int_init_num, (v4l2_int_ioctl_func*) ioctl_init}, {vidioc_int_enum_fmt_cap_num, (v4l2_int_ioctl_func *) ioctl_enum_fmt_cap}, {vidioc_int_try_fmt_cap_num, (v4l2_int_ioctl_func *)ioctl_try_fmt_cap}, {vidioc_int_g_fmt_cap_num, (v4l2_int_ioctl_func *) ioctl_g_fmt_cap}, {vidioc_int_g_parm_num, (v4l2_int_ioctl_func *) ioctl_g_parm}, {vidioc_int_s_parm_num, (v4l2_int_ioctl_func *) ioctl_s_parm}, {vidioc_int_g_ctrl_num, (v4l2_int_ioctl_func *) ioctl_g_ctrl}, {vidioc_int_s_ctrl_num, (v4l2_int_ioctl_func *) ioctl_s_ctrl}, {vidioc_int_enum_framesizes_num, (v4l2_int_ioctl_func *) ioctl_enum_framesizes}, {vidioc_int_g_chip_ident_num, (v4l2_int_ioctl_func *) ioctl_g_chip_ident}, }; static struct v4l2_int_slave tc358743_slave = { .ioctls = tc358743_ioctl_desc, .num_ioctls = ARRAY_SIZE(tc358743_ioctl_desc), }; static struct v4l2_int_device tc358743_int_device = { .module = THIS_MODULE, .name = "tc358743", .type = v4l2_int_type_slave, .u = { .slave = &tc358743_slave, }, }; #ifdef AUDIO_ENABLE struct imx_ssi { struct platform_device *ac97_dev; struct snd_soc_dai *imx_ac97; struct clk *clk; void __iomem *base; int irq; int fiq_enable; unsigned int offset; unsigned int flags; void (*ac97_reset) (struct snd_ac97 *ac97); void (*ac97_warm_reset)(struct snd_ac97 *ac97); struct imx_pcm_dma_params dma_params_rx; struct imx_pcm_dma_params dma_params_tx; int enabled; struct platform_device *soc_platform_pdev; struct platform_device *soc_platform_pdev_fiq; }; #define SSI_SCR 0x10 #define SSI_SRCR 0x20 #define SSI_STCCR 0x24 #define SSI_SRCCR 0x28 #define SSI_SCR_I2S_MODE_NORM (0 << 5) #define SSI_SCR_I2S_MODE_MSTR (1 << 5) #define SSI_SCR_I2S_MODE_SLAVE (2 << 5) #define SSI_I2S_MODE_MASK (3 << 5) #define SSI_SCR_SYN (1 << 4) #define SSI_SRCR_RSHFD (1 << 4) #define SSI_SRCR_RSCKP (1 << 3) #define SSI_SRCR_RFSI (1 << 2) #define SSI_SRCR_REFS (1 << 0) #define SSI_STCCR_WL(x) ((((x) - 2) >> 1) << 13) #define SSI_STCCR_WL_MASK (0xf << 13) #define SSI_SRCCR_WL(x) ((((x) - 2) >> 1) << 13) #define SSI_SRCCR_WL_MASK (0xf << 13) /* Audio setup */ static int imxpac_tc358743_hw_params(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *params) { struct snd_soc_pcm_runtime *rtd = substream->private_data; struct snd_soc_dai *codec_dai = rtd->codec_dai; struct snd_soc_dai *cpu_dai = rtd->cpu_dai; int ret; ret = snd_soc_dai_set_fmt(cpu_dai, SND_SOC_DAIFMT_I2S | SND_SOC_DAIFMT_NB_IF | SND_SOC_DAIFMT_CBM_CFM); if (ret) { pr_err("%s: failed set cpu dai format\n", __func__); return ret; } ret = snd_soc_dai_set_fmt(codec_dai, SND_SOC_DAIFMT_I2S | SND_SOC_DAIFMT_NB_NF | SND_SOC_DAIFMT_CBM_CFM); if (ret) { pr_err("%s: failed set codec dai format\n", __func__); return ret; } ret = snd_soc_dai_set_sysclk(codec_dai, 0, CODEC_CLOCK, SND_SOC_CLOCK_OUT); if (ret) { pr_err("%s: failed setting codec sysclk\n", __func__); return ret; } snd_soc_dai_set_tdm_slot(cpu_dai, 0xffffffc, 0xffffffc, 2, 0); ret = snd_soc_dai_set_sysclk(cpu_dai, IMX_SSP_SYS_CLK, 0, SND_SOC_CLOCK_IN); if (ret) { pr_err("can't set CPU system clock IMX_SSP_SYS_CLK\n"); return ret; } #if 1 // clear SSI_SRCR_RXBIT0 and SSI_SRCR_RSHFD in order to push Right-justified MSB data fro { struct imx_ssi *ssi = snd_soc_dai_get_drvdata(cpu_dai); u32 scr = 0, srcr = 0, stccr = 0, srccr = 0; pr_debug("%s: base %p\n", __func__, (void *)ssi->base); scr = readl(ssi->base + SSI_SCR); pr_debug("%s: SSI_SCR before: %p\n", __func__, (void *)scr); writel(scr, ssi->base + SSI_SCR); pr_debug("%s: SSI_SCR after: %p\n", __func__, (void *)scr); srcr = readl(ssi->base + SSI_SRCR); pr_debug("%s: SSI_SRCR before: %p\n", __func__, (void *)srcr); writel(srcr, ssi->base + SSI_SRCR); pr_debug("%s: SSI_SRCR after: %p\n", __func__, (void *)srcr); stccr = readl(ssi->base + SSI_STCCR); pr_debug("%s: SSI_STCCR before: %p\n", __func__, (void *)stccr); stccr &= ~SSI_STCCR_WL_MASK; stccr |= SSI_STCCR_WL(16); writel(stccr, ssi->base + SSI_STCCR); pr_debug("%s: SSI_STCCR after: %p\n", __func__, (void *)stccr); srccr = readl(ssi->base + SSI_SRCCR); pr_debug("%s: SSI_SRCCR before: %p\n", __func__, (void *)srccr); srccr &= ~SSI_SRCCR_WL_MASK; srccr |= SSI_SRCCR_WL(16); writel(srccr, ssi->base + SSI_SRCCR); pr_debug("%s: SSI_SRCCR after: %p\n", __func__, (void *)srccr); } #endif return 0; } /* Headphones jack detection DAPM pins */ static struct snd_soc_jack_pin hs_jack_pins_a[] = { }; /* imx_3stack card dapm widgets */ static struct snd_soc_dapm_widget imx_3stack_dapm_widgets_a[] = { }; static struct snd_kcontrol_new tc358743_machine_controls_a[] = { }; /* imx_3stack machine connections to the codec pins */ static struct snd_soc_dapm_route audio_map_a[] = { }; static int imx_3stack_tc358743_init(struct snd_soc_pcm_runtime *rtd) { struct snd_soc_codec *codec = rtd->codec; int ret; struct snd_soc_jack *hs_jack; struct snd_soc_jack_pin *hs_jack_pins; int hs_jack_pins_size; struct snd_soc_dapm_widget *imx_3stack_dapm_widgets; int imx_3stack_dapm_widgets_size; struct snd_kcontrol_new *tc358743_machine_controls; int tc358743_machine_controls_size; struct snd_soc_dapm_route *audio_map; int audio_map_size; int gpio_num = -1; char *gpio_name; pr_debug("%s started\n", __func__); hs_jack_pins = hs_jack_pins_a; hs_jack_pins_size = ARRAY_SIZE(hs_jack_pins_a); imx_3stack_dapm_widgets = imx_3stack_dapm_widgets_a; imx_3stack_dapm_widgets_size = ARRAY_SIZE(imx_3stack_dapm_widgets_a); tc358743_machine_controls = tc358743_machine_controls_a; tc358743_machine_controls_size = ARRAY_SIZE(tc358743_machine_controls_a); audio_map = audio_map_a; audio_map_size = ARRAY_SIZE(audio_map_a); gpio_num = -1; //card_a_gpio_num; gpio_name = NULL; ret = snd_soc_add_controls(codec, tc358743_machine_controls, tc358743_machine_controls_size); if (ret) { pr_err("%s: snd_soc_add_controls failed. err = %d\n", __func__, ret); return ret; } /* Add imx_3stack specific widgets */ snd_soc_dapm_new_controls(&codec->dapm, imx_3stack_dapm_widgets, imx_3stack_dapm_widgets_size); /* Set up imx_3stack specific audio path audio_map */ snd_soc_dapm_add_routes(&codec->dapm, audio_map, audio_map_size); snd_soc_dapm_enable_pin(&codec->dapm, hs_jack_pins->pin); snd_soc_dapm_sync(&codec->dapm); hs_jack = kzalloc(sizeof(struct snd_soc_jack), GFP_KERNEL); ret = snd_soc_jack_new(codec, hs_jack_pins->pin, SND_JACK_HEADPHONE, hs_jack); if (ret) { pr_err("%s: snd_soc_jack_new failed. err = %d\n", __func__, ret); return ret; } ret = snd_soc_jack_add_pins(hs_jack,hs_jack_pins_size, hs_jack_pins); if (ret) { pr_err("%s: snd_soc_jack_add_pinsfailed. err = %d\n", __func__, ret); return ret; } return 0; } static struct snd_soc_ops imxpac_tc358743_snd_ops = { .hw_params = imxpac_tc358743_hw_params, }; static struct snd_soc_dai_link imxpac_tc358743_dai = { .name = "tc358743", .stream_name = "TC358743", .codec_dai_name = "tc358743-hifi", .platform_name = "imx-pcm-audio.2", .codec_name = "tc358743_mipi.1-000f", .cpu_dai_name = "imx-ssi.2", .init = imx_3stack_tc358743_init, .ops = &imxpac_tc358743_snd_ops, }; static struct snd_soc_card imxpac_tc358743 = { .name = "cpuimx-audio_hdmi_in", .dai_link = &imxpac_tc358743_dai, .num_links = 1, }; static struct platform_device *imxpac_tc358743_snd_device; static struct platform_device *imxpac_tc358743_snd_device; static int imx_audmux_config(int slave, int master) { unsigned int ptcr, pdcr; slave = slave - 1; master = master - 1; /* SSI0 mastered by port 5 */ ptcr = MXC_AUDMUX_V2_PTCR_SYN | MXC_AUDMUX_V2_PTCR_TFSDIR | MXC_AUDMUX_V2_PTCR_TFSEL(master | 0x8) | MXC_AUDMUX_V2_PTCR_TCLKDIR | MXC_AUDMUX_V2_PTCR_RFSDIR | MXC_AUDMUX_V2_PTCR_RFSEL(master | 0x8) | MXC_AUDMUX_V2_PTCR_RCLKDIR | MXC_AUDMUX_V2_PTCR_RCSEL(master | 0x8) | MXC_AUDMUX_V2_PTCR_TCSEL(master | 0x8); pdcr = MXC_AUDMUX_V2_PDCR_RXDSEL(master); mxc_audmux_v2_configure_port(slave, ptcr, pdcr); ptcr = MXC_AUDMUX_V2_PTCR_SYN; pdcr = MXC_AUDMUX_V2_PDCR_RXDSEL(master); mxc_audmux_v2_configure_port(master, ptcr, pdcr); return 0; } static int __devinit imx_tc358743_probe(struct platform_device *pdev) { struct mxc_audio_platform_data *plat = pdev->dev.platform_data; int ret = 0; imx_audmux_config(plat->src_port, plat->ext_port); ret = -EINVAL; if (plat->init && plat->init()) return ret; printk("%s %d %s\n",__func__,__LINE__,pdev->name); return 0; } static int imx_tc358743_remove(struct platform_device *pdev) { struct mxc_audio_platform_data *plat = pdev->dev.platform_data; if (plat->finit) plat->finit(); return 0; } static struct platform_driver imx_tc358743_audio1_driver = { .probe = imx_tc358743_probe, .remove = imx_tc358743_remove, .driver = { .name = "imx-tc358743", }, }; /* Codec setup */ static int tc358743_codec_probe(struct snd_soc_codec *codec) { return 0; } static int tc358743_codec_remove(struct snd_soc_codec *codec) { return 0; } static int tc358743_codec_suspend(struct snd_soc_codec *codec, pm_message_t state) { // tc358743_set_bias_level(codec, SND_SOC_BIAS_OFF); return 0; } static int tc358743_codec_resume(struct snd_soc_codec *codec) { // tc358743_set_bias_level(codec, SND_SOC_BIAS_STANDBY); return 0; } static int tc358743_set_bias_level(struct snd_soc_codec *codec, enum snd_soc_bias_level level) { return 0; } static const u8 tc358743_reg[0] = { }; static struct snd_soc_codec_driver soc_codec_dev_tc358743 = { .set_bias_level = tc358743_set_bias_level, .reg_cache_size = ARRAY_SIZE(tc358743_reg), .reg_word_size = sizeof(u8), .reg_cache_default = tc358743_reg, .probe = tc358743_codec_probe, .remove = tc358743_codec_remove, .suspend = tc358743_codec_suspend, .resume = tc358743_codec_resume, }; #define AIC3X_RATES SNDRV_PCM_RATE_8000_96000 #define AIC3X_FORMATS (SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_S20_3LE | \ SNDRV_PCM_FMTBIT_S24_LE) static int tc358743_hw_params(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *params, struct snd_soc_dai *dai) { return 0; } static int tc358743_mute(struct snd_soc_dai *dai, int mute) { return 0; } static int tc358743_set_dai_sysclk(struct snd_soc_dai *codec_dai, int clk_id, unsigned int freq, int dir) { return 0; } static int tc358743_set_dai_fmt(struct snd_soc_dai *codec_dai, unsigned int fmt) { return 0; } static struct snd_soc_dai_ops tc358743_dai_ops = { .hw_params = tc358743_hw_params, .digital_mute = tc358743_mute, .set_sysclk = tc358743_set_dai_sysclk, .set_fmt = tc358743_set_dai_fmt, }; static struct snd_soc_dai_driver tc358743_dai = { .name = "tc358743-hifi", .capture = { .stream_name = "Capture", .channels_min = 1, .channels_max = 2, .rates = AIC3X_RATES, .formats = AIC3X_FORMATS,}, .ops = &tc358743_dai_ops, .symmetric_rates = 1, }; #endif static char tc358743_mode_list[16][12] = { "None", "VGA", "240p/480i", "288p/576i", "W240p/480i", "W288p/576i", "480p", "576p", "W480p", "W576p", "WW480p", "WW576p", "720p", "1035i", "1080i", "1080p" }; static char tc358743_fps_list[tc358743_max_fps+1] = { [tc358743_60_fps] = 60, [tc358743_30_fps] = 30, [tc358743_max_fps] = 0 }; static int tc358743_audio_list[16] = { 44100, 0, 48000, 32000, 22050, 384000, 24000, 352800, 88200, 768000, 96000, 705600, 176400, 0, 192000, 0 }; static char str_on[80]; static void report_netlink(void) { char *envp[2]; envp[0] = &str_on[0]; envp[1] = NULL; sprintf(envp[0], "HDMI RX: %d (%s) %d %d", (unsigned char)hdmi_mode & 0xf, tc358743_mode_list[(unsigned char)hdmi_mode & 0xf], tc358743_fps_list[fps], tc358743_audio_list[audio]); kobject_uevent_env(&(tc358743_data.i2c_client->dev.kobj), KOBJ_CHANGE, envp); det_work_timeout = DET_WORK_TIMEOUT_DEFAULT; pr_debug("%s: HDMI RX (%d) mode: %s fps: %d (%d, %d) audio: %d\n", __func__, (unsigned char)hdmi_mode, tc358743_mode_list[(unsigned char)hdmi_mode & 0xf], fps, bounce, det_work_timeout, tc358743_audio_list[audio]); } static void det_worker(struct work_struct *work) { u32 u32val; u16 reg; int ret; mutex_lock(&access_lock); if (!det_work_disable) { reg = 0x8621; ret = tc358743_read_reg(reg, &u32val); if (ret > 0) { if (audio != (((unsigned char)u32val) & 0x0f)) { audio = ((unsigned char)u32val) & 0x0f; report_netlink(); } } reg = 0x852f; ret = tc358743_read_reg(reg, &u32val); if (ret > 0) { while (1) { if (u32val & TC3587430_HDMI_DETECT) { lock = u32val & TC3587430_HDMI_DETECT; reg = 0x8521; ret = tc358743_read_reg(reg, &u32val); if (ret < 0) { pr_err("%s: Error reading mode\n", __func__); } } else { if (lock) { // check if it is realy un-plug lock = 0; u32val = 0x0; hdmi_mode = 0xF0; // fake mode to detect un-plug if mode was not detected before. } } if ((unsigned char)hdmi_mode != (unsigned char)u32val) { if (u32val) det_work_timeout = DET_WORK_TIMEOUT_DEFERRED; else det_work_timeout = DET_WORK_TIMEOUT_DEFAULT; bounce = MAX_BOUNCE; pr_debug("%s: HDMI RX (%d != %d) mode: %s fps: %d (%d, %d)\n", __func__, (unsigned char)hdmi_mode, (unsigned char)u32val, tc358743_mode_list[(unsigned char)hdmi_mode & 0xf], fps, bounce, det_work_timeout); hdmi_mode = u32val; } else if (bounce) { bounce--; det_work_timeout = DET_WORK_TIMEOUT_DEFAULT; } if (1 == bounce) { if (hdmi_mode >= 0xe) { reg = 0x852f; ret = tc358743_read_reg(reg, &u32val); if (ret > 0) fps = ((((unsigned char)u32val) & 0x0f) > 0xa)? tc358743_60_fps: tc358743_30_fps; } reg = 0x8621; ret = tc358743_read_reg(reg, &u32val); if (ret > 0) { audio = ((unsigned char)u32val) & 0x0f; report_netlink(); } } break; } } else { pr_err("%s: Error reading lock\n", __func__); } } else { det_work_timeout = DET_WORK_TIMEOUT_DEFERRED; } mutex_unlock(&access_lock); schedule_delayed_work(&(det_work), msecs_to_jiffies(det_work_timeout)); } static irqreturn_t tc358743_detect_handler(int irq, void *data) { pr_debug("%s: IRQ %d\n", __func__, tc358743_data.i2c_client->irq); schedule_delayed_work(&(det_work), msecs_to_jiffies(det_work_timeout)); return IRQ_HANDLED; } /*! * tc358743 I2C probe function * * @param adapter struct i2c_adapter * * @return Error code indicating success or failure */ #define DUMP_LENGTH 256 static u16 regoffs = 0; static ssize_t tc358743_show_regdump(struct device *dev, struct device_attribute *attr, char *buf) { int i, len = 0; int retval; u32 u32val; mutex_lock(&access_lock); for (i=0; i<DUMP_LENGTH; ) { retval = tc358743_read_reg(regoffs+i, &u32val); if (retval < 0) { u32val =0xff; retval = 1; } while (retval-- > 0) { if (0 == (i & 0xf)) len += sprintf(buf+len, "\n%04X:", regoffs+i); len += sprintf(buf+len, " %02X", u32val&0xff); u32val >>= 8; i++; } } mutex_unlock(&access_lock); len += sprintf(buf+len, "\n"); return len; } static DEVICE_ATTR(regdump, S_IRUGO, tc358743_show_regdump, NULL); static ssize_t tc358743_store_regoffs(struct device *device, struct device_attribute *attr, const char *buf, size_t count) { u32 val; int retval; retval = sscanf(buf, "%x", &val); if (1 == retval) regoffs = (u16)val; return count; } static ssize_t tc358743_show_regoffs(struct device *dev, struct device_attribute *attr, char *buf) { int len = 0; len += sprintf(buf+len, "0x%04X\n", regoffs); return len; } static DEVICE_ATTR(regoffs, S_IRUGO|S_IWUSR, tc358743_show_regoffs, tc358743_store_regoffs); static ssize_t tc358743_store_hpd(struct device *device, struct device_attribute *attr, const char *buf, size_t count) { u32 val; int retval; retval = sscanf(buf, "%d", &val); if (1 == retval) hpd_active = (u16)val; return count; } static ssize_t tc358743_show_hpd(struct device *dev, struct device_attribute *attr, char *buf) { int len = 0; len += sprintf(buf+len, "%d\n", hpd_active); return len; } static DEVICE_ATTR(hpd, S_IRUGO|S_IWUSR, tc358743_show_hpd, tc358743_store_hpd); static ssize_t tc358743_show_hdmirx(struct device *dev, struct device_attribute *attr, char *buf) { int len = 0; len += sprintf(buf+len, "%d\n", hdmi_mode); return len; } static DEVICE_ATTR(hdmirx, S_IRUGO, tc358743_show_hdmirx, NULL); static ssize_t tc358743_show_fps(struct device *dev, struct device_attribute *attr, char *buf) { int len = 0; len += sprintf(buf+len, "%d\n", tc358743_fps_list[fps]); return len; } static DEVICE_ATTR(fps, S_IRUGO, tc358743_show_fps, NULL); #ifdef AUDIO_ENABLE static ssize_t tc358743_show_audio(struct device *dev, struct device_attribute *attr, char *buf) { int len = 0; len += sprintf(buf+len, "%d\n", tc358743_audio_list[audio]); return len; } static DEVICE_ATTR(audio, S_IRUGO, tc358743_show_audio, NULL); #endif static int tc358743_probe(struct i2c_client *client, const struct i2c_device_id *id) { struct pwm_device *pwm; struct device *dev = &client->dev; int retval; struct regmap *gpr; struct sensor_data *sensor = &tc358743_data; u32 u32val; /* request power down pin */ pwn_gpio = of_get_named_gpio(dev->of_node, "pwn-gpios", 0); if (!gpio_is_valid(pwn_gpio)) { dev_warn(dev, "no sensor pwdn pin available"); } else { retval = devm_gpio_request_one(dev, pwn_gpio, GPIOF_OUT_INIT_HIGH, "tc_mipi_pwdn"); if (retval < 0) { dev_warn(dev, "request of pwn_gpio failed"); return retval; } } /* request reset pin */ rst_gpio = of_get_named_gpio(dev->of_node, "rst-gpios", 0); if (!gpio_is_valid(rst_gpio)) { dev_warn(dev, "no sensor reset pin available"); return -EINVAL; } retval = devm_gpio_request_one(dev, rst_gpio, GPIOF_OUT_INIT_HIGH, "tc_mipi_reset"); if (retval < 0) { dev_warn(dev, "request of tc_mipi_reset failed"); return retval; } /* Set initial values for the sensor struct. */ memset(sensor, 0, sizeof(*sensor)); sensor->sensor_clk = devm_clk_get(dev, "csi_mclk"); if (IS_ERR(sensor->sensor_clk)) { /* assuming clock enabled by default */ sensor->sensor_clk = NULL; dev_err(dev, "clock-frequency missing or invalid\n"); return PTR_ERR(sensor->sensor_clk); } retval = of_property_read_u32(dev->of_node, "mclk", &(sensor->mclk)); if (retval) { dev_err(dev, "mclk missing or invalid\n"); return retval; } retval = of_property_read_u32(dev->of_node, "mclk_source", (u32 *) &(sensor->mclk_source)); if (retval) { dev_err(dev, "mclk_source missing or invalid\n"); return retval; } retval = of_property_read_u32(dev->of_node, "ipu_id", &sensor->ipu_id); if (retval) { dev_err(dev, "ipu_id missing or invalid\n"); return retval; } retval = of_property_read_u32(dev->of_node, "csi_id", &(sensor->csi)); if (retval) { dev_err(dev, "csi id missing or invalid\n"); return retval; } if (((unsigned)sensor->ipu_id > 1) || ((unsigned)sensor->csi > 1)) { dev_err(dev, "invalid ipu/csi\n"); return -EINVAL; } clk_prepare_enable(sensor->sensor_clk); sensor->io_init = tc_reset; sensor->i2c_client = client; sensor->pix.pixelformat = tc358743_formats[0].pixelformat; sensor->streamcap.capability = V4L2_MODE_HIGHQUALITY | V4L2_CAP_TIMEPERFRAME; sensor->streamcap.capturemode = 0; sensor->streamcap.extendedmode = tc358743_mode_1080P_1920_1080; sensor->streamcap.timeperframe.denominator = DEFAULT_FPS; sensor->streamcap.timeperframe.numerator = 1; sensor->pix.width = tc358743_mode_info_data[0][sensor->streamcap.capturemode].width; sensor->pix.height = tc358743_mode_info_data[0][sensor->streamcap.capturemode].height; pr_debug("%s: format: %x, capture mode: %d extended mode: %d fps: %d width: %d height: %d\n",__func__, sensor->pix.pixelformat, sensor->streamcap.capturemode, sensor->streamcap.extendedmode, sensor->streamcap.timeperframe.denominator * sensor->streamcap.timeperframe.numerator, sensor->pix.width, sensor->pix.height); pwm = pwm_get(dev, NULL); if (!IS_ERR(pwm)) { dev_info(dev, "found pwm%d, period=%d\n", pwm->pwm, pwm->period); pwm_config(pwm, pwm->period >> 1, pwm->period); pwm_enable(pwm); } tc_power_on(dev); tc_reset(); tc_standby(0); retval = tc358743_read_reg(TC358743_CHIP_ID_HIGH_BYTE, &u32val); if (retval < 0) { pr_err("%s:cannot find camera\n", __func__); retval = -ENODEV; goto err4; } gpr = syscon_regmap_lookup_by_compatible("fsl,imx6q-iomuxc-gpr"); if (!IS_ERR(gpr)) { if (of_machine_is_compatible("fsl,imx6q")) { if (sensor->csi == sensor->ipu_id) { int mask = sensor->csi ? (1 << 20) : (1 << 19); regmap_update_bits(gpr, IOMUXC_GPR1, mask, 0); } } else if (of_machine_is_compatible("fsl,imx6dl")) { int mask = sensor->csi ? (7 << 3) : (7 << 0); int val = sensor->csi ? (3 << 3) : (0 << 0); if (sensor->ipu_id) { dev_err(dev, "invalid ipu\n"); return -EINVAL; } regmap_update_bits(gpr, IOMUXC_GPR13, mask, val); } } else { pr_err("%s: failed to find fsl,imx6q-iomux-gpr regmap\n", __func__); } tc358743_int_device.priv = sensor; //retval = device_create_file(&client->dev, &dev_attr_audio); retval = device_create_file(&client->dev, &dev_attr_fps); retval = device_create_file(&client->dev, &dev_attr_hdmirx); retval = device_create_file(&client->dev, &dev_attr_hpd); retval = device_create_file(&client->dev, &dev_attr_regoffs); retval = device_create_file(&client->dev, &dev_attr_regdump); if (retval) { pr_err("%s: create bin file failed, error=%d\n", __func__, retval); goto err4; } #ifdef AUDIO_ENABLE /* Audio setup */ retval = snd_soc_register_codec(&client->dev, &soc_codec_dev_tc358743, &tc358743_dai, 1); if (retval) { pr_err("%s: register failed, error=%d\n", __func__, retval); goto err4; } retval = platform_driver_register(&imx_tc358743_audio1_driver); if (retval) { pr_err("%s: Platform driver register failed, error=%d\n", __func__, retval); goto err4; } imxpac_tc358743_snd_device = platform_device_alloc("soc-audio", 5); if (!imxpac_tc358743_snd_device) { pr_err("%s: Platform device allocation failed, error=%d\n", __func__, retval); goto err4; } platform_set_drvdata(imxpac_tc358743_snd_device, &imxpac_tc358743); retval = platform_device_add(imxpac_tc358743_snd_device); if (retval) { pr_err("%s: Platform device add failed, error=%d\n", __func__, retval); platform_device_put(imxpac_tc358743_snd_device); goto err4; } #endif #if 1 INIT_DELAYED_WORK(&(det_work), det_worker); if (sensor->i2c_client->irq) { retval = request_irq(sensor->i2c_client->irq, tc358743_detect_handler, IRQF_SHARED | IRQF_TRIGGER_FALLING, "tc358743_det", sensor); if (retval < 0) dev_warn(&sensor->i2c_client->dev, "cound not request det irq %d\n", sensor->i2c_client->irq); } schedule_delayed_work(&(det_work), msecs_to_jiffies(det_work_timeout)); #endif retval = tc358743_reset(sensor); tc_standby(1); retval = v4l2_int_device_register(&tc358743_int_device); if (retval) { pr_err("%s: v4l2_int_device_register failed, error=%d\n", __func__, retval); goto err4; } pr_debug("%s: finished, error=%d\n", __func__, retval); return retval; err4: pr_err("%s: failed, error=%d\n", __func__, retval); return retval; } /*! * tc358743 I2C detach function * * @param client struct i2c_client * * @return Error code indicating success or failure */ static int tc358743_remove(struct i2c_client *client) { // Stop delayed work cancel_delayed_work_sync(&(det_work)); // Remove IRQ if (tc358743_data.i2c_client->irq) { free_irq(tc358743_data.i2c_client->irq, &tc358743_data); } /*Remove sysfs entries*/ device_remove_file(&client->dev, &dev_attr_fps); device_remove_file(&client->dev, &dev_attr_hdmirx); device_remove_file(&client->dev, &dev_attr_hpd); device_remove_file(&client->dev, &dev_attr_regoffs); device_remove_file(&client->dev, &dev_attr_regdump); v4l2_int_device_unregister(&tc358743_int_device); if (gpo_regulator) { regulator_disable(gpo_regulator); regulator_put(gpo_regulator); } if (analog_regulator) { regulator_disable(analog_regulator); regulator_put(analog_regulator); } if (core_regulator) { regulator_disable(core_regulator); regulator_put(core_regulator); } if (io_regulator) { regulator_disable(io_regulator); regulator_put(io_regulator); } return 0; } /*! * tc358743 init function * Called by insmod tc358743_camera.ko. * * @return Error code indicating success or failure */ static __init int tc358743_init(void) { int err; err = i2c_add_driver(&tc358743_i2c_driver); if (err != 0) pr_err("%s:driver registration failed, error=%d\n", __func__, err); return err; } /*! * tc358743 cleanup function * Called on rmmod tc358743_camera.ko * * @return Error code indicating success or failure */ static void __exit tc358743_clean(void) { i2c_del_driver(&tc358743_i2c_driver); } module_init(tc358743_init); module_exit(tc358743_clean); MODULE_AUTHOR("Panasonic Avionics Corp."); MODULE_DESCRIPTION("Toshiba TC358743 HDMI-to-CSI2 Bridge MIPI Input Driver"); MODULE_LICENSE("GPL"); MODULE_VERSION("1.0"); MODULE_ALIAS("CSI");
Java
<?php /** * File containing the eZContentOperationCollection class. * * @copyright Copyright (C) eZ Systems AS. All rights reserved. * @license For full copyright and license information view LICENSE file distributed with this source code. * @version //autogentag// * @package kernel */ /*! \class eZContentOperationCollection ezcontentoperationcollection.php \brief The class eZContentOperationCollection does */ class eZContentOperationCollection { /** * Use by {@see beginTransaction()} and {@see commitTransaction()} to handle nested publish operations */ private static $operationsStack = 0; static public function readNode( $nodeID ) { } static public function readObject( $nodeID, $userID, $languageCode ) { if ( $languageCode != '' ) { $node = eZContentObjectTreeNode::fetch( $nodeID, $languageCode ); } else { $node = eZContentObjectTreeNode::fetch( $nodeID ); } if ( $node === null ) // return $Module->handleError( eZError::KERNEL_NOT_AVAILABLE, 'kernel' ); return false; $object = $node->attribute( 'object' ); if ( $object === null ) // return $Module->handleError( eZError::KERNEL_ACCESS_DENIED, 'kernel' ); { return false; } /* if ( !$object->attribute( 'can_read' ) ) { // return $Module->handleError( eZError::KERNEL_ACCESS_DENIED, 'kernel' ); return false; } */ return array( 'status' => true, 'object' => $object, 'node' => $node ); } static public function loopNodes( $nodeID ) { return array( 'parameters' => array( array( 'parent_node_id' => 3 ), array( 'parent_node_id' => 5 ), array( 'parent_node_id' => 12 ) ) ); } static public function loopNodeAssignment( $objectID, $versionNum ) { $object = eZContentObject::fetch( $objectID ); $version = $object->version( $versionNum ); $nodeAssignmentList = $version->attribute( 'node_assignments' ); $parameters = array(); foreach ( $nodeAssignmentList as $nodeAssignment ) { if ( $nodeAssignment->attribute( 'parent_node' ) > 0 ) { if ( $nodeAssignment->attribute( 'is_main' ) == 1 ) { $mainNodeID = self::publishNode( $nodeAssignment->attribute( 'parent_node' ), $objectID, $versionNum, false ); } else { $parameters[] = array( 'parent_node_id' => $nodeAssignment->attribute( 'parent_node' ) ); } } } for ( $i = 0; $i < count( $parameters ); $i++ ) { $parameters[$i]['main_node_id'] = $mainNodeID; } return array( 'parameters' => $parameters ); } function publishObjectExtensionHandler( $contentObjectID, $contentObjectVersion ) { eZContentObjectEditHandler::executePublish( $contentObjectID, $contentObjectVersion ); } /** * Starts a database transaction. */ static public function beginTransaction() { // We only start a transaction if another content publish operation hasn't been started if ( ++self::$operationsStack === 1 ) { eZDB::instance()->begin(); } } /** * Commit a previously started database transaction. */ static public function commitTransaction() { if ( --self::$operationsStack === 0 ) { eZDB::instance()->commit(); } } static public function setVersionStatus( $objectID, $versionNum, $status ) { $object = eZContentObject::fetch( $objectID ); if ( !$versionNum ) { $versionNum = $object->attribute( 'current_version' ); } $version = $object->version( $versionNum ); if ( !$version ) return; $version->setAttribute( 'status', $status ); $version->store(); } static public function setObjectStatusPublished( $objectID, $versionNum ) { $object = eZContentObject::fetch( $objectID ); $version = $object->version( $versionNum ); $db = eZDB::instance(); $db->begin(); $object->setAttribute( 'status', eZContentObject::STATUS_PUBLISHED ); $version->setAttribute( 'status', eZContentObjectVersion::STATUS_PUBLISHED ); $object->setAttribute( 'current_version', $versionNum ); $objectIsAlwaysAvailable = $object->isAlwaysAvailable(); $object->setAttribute( 'language_mask', eZContentLanguage::maskByLocale( $version->translationList( false, false ), $objectIsAlwaysAvailable ) ); if ( $object->attribute( 'published' ) == 0 ) { $object->setAttribute( 'published', time() ); } $object->setAttribute( 'modified', time() ); $classID = $object->attribute( 'contentclass_id' ); $class = eZContentClass::fetch( $classID ); $objectName = $class->contentObjectName( $object ); $object->setName( $objectName, $versionNum ); $existingTranslations = $version->translations( false ); foreach( $existingTranslations as $translation ) { $translatedName = $class->contentObjectName( $object, $versionNum, $translation ); $object->setName( $translatedName, $versionNum, $translation ); } if ( $objectIsAlwaysAvailable ) { $initialLanguageID = $object->attribute( 'initial_language_id' ); $object->setAlwaysAvailableLanguageID( $initialLanguageID ); } $version->store(); $object->store(); eZContentObjectTreeNode::setVersionByObjectID( $objectID, $versionNum ); $nodes = $object->assignedNodes(); foreach ( $nodes as $node ) { $node->setName( $object->attribute( 'name' ) ); $node->updateSubTreePath(); } $db->commit(); /* Check if current class is the user class, and if so, clean up the user-policy cache */ if ( in_array( $classID, eZUser::contentClassIDs() ) ) { eZUser::purgeUserCacheByUserId( $object->attribute( 'id' ) ); } } static public function attributePublishAction( $objectID, $versionNum ) { $object = eZContentObject::fetch( $objectID ); $nodes = $object->assignedNodes(); $version = $object->version( $versionNum ); $contentObjectAttributes = $object->contentObjectAttributes( true, $versionNum, $version->initialLanguageCode(), false ); foreach ( $contentObjectAttributes as $contentObjectAttribute ) { $contentObjectAttribute->onPublish( $object, $nodes ); } } /*! \static Generates the related viewcaches (PreGeneration) for the content object. It will only do this if [ContentSettings]/PreViewCache in site.ini is enabled. \param $objectID The ID of the content object to generate caches for. */ static public function generateObjectViewCache( $objectID ) { eZContentCacheManager::generateObjectViewCache( $objectID ); } /*! \static Clears the related viewcaches for the content object using the smart viewcache system. \param $objectID The ID of the content object to clear caches for \param $versionNum The version of the object to use or \c true for current version \param $additionalNodeList An array with node IDs to add to clear list, or \c false for no additional nodes. */ static public function clearObjectViewCache( $objectID, $versionNum = true, $additionalNodeList = false ) { eZContentCacheManager::clearContentCacheIfNeeded( $objectID, $versionNum, $additionalNodeList ); } static public function publishNode( $parentNodeID, $objectID, $versionNum, $mainNodeID ) { $object = eZContentObject::fetch( $objectID ); $nodeAssignment = eZNodeAssignment::fetch( $objectID, $versionNum, $parentNodeID ); $version = $object->version( $versionNum ); $fromNodeID = $nodeAssignment->attribute( 'from_node_id' ); $originalObjectID = $nodeAssignment->attribute( 'contentobject_id' ); $nodeID = $nodeAssignment->attribute( 'parent_node' ); $opCode = $nodeAssignment->attribute( 'op_code' ); $parentNode = eZContentObjectTreeNode::fetch( $nodeID ); // if parent doesn't exist, return. See issue #18320 if ( !$parentNode instanceof eZContentObjectTreeNode ) { eZDebug::writeError( "Parent node doesn't exist. object id: $objectID, node_assignment id: " . $nodeAssignment->attribute( 'id' ), __METHOD__ ); return; } $parentNodeID = $parentNode->attribute( 'node_id' ); $existingNode = null; $db = eZDB::instance(); $db->begin(); if ( strlen( $nodeAssignment->attribute( 'parent_remote_id' ) ) > 0 ) { $existingNode = eZContentObjectTreeNode::fetchByRemoteID( $nodeAssignment->attribute( 'parent_remote_id' ) ); } if ( !$existingNode ); { $existingNode = eZContentObjectTreeNode::findNode( $nodeID , $object->attribute( 'id' ), true ); } $updateSectionID = false; // now we check the op_code to see what to do if ( ( $opCode & 1 ) == eZNodeAssignment::OP_CODE_NOP ) { // There is nothing to do so just return $db->commit(); if ( $mainNodeID == false ) { return $object->attribute( 'main_node_id' ); } return; } $updateFields = false; if ( $opCode == eZNodeAssignment::OP_CODE_MOVE || $opCode == eZNodeAssignment::OP_CODE_CREATE ) { // if ( $fromNodeID == 0 || $fromNodeID == -1) if ( $opCode == eZNodeAssignment::OP_CODE_CREATE || $opCode == eZNodeAssignment::OP_CODE_SET ) { // If the node already exists it means we have a conflict (for 'CREATE'). // We resolve this by leaving node-assignment data be. if ( $existingNode == null ) { $parentNode = eZContentObjectTreeNode::fetch( $nodeID ); $user = eZUser::currentUser(); if ( !eZSys::isShellExecution() and !$user->isAnonymous() ) { eZContentBrowseRecent::createNew( $user->id(), $parentNode->attribute( 'node_id' ), $parentNode->attribute( 'name' ) ); } $updateFields = true; $existingNode = $parentNode->addChild( $object->attribute( 'id' ), true ); if ( $fromNodeID == -1 ) { $updateSectionID = true; } } elseif ( $opCode == eZNodeAssignment::OP_CODE_SET ) { $updateFields = true; } } elseif ( $opCode == eZNodeAssignment::OP_CODE_MOVE ) { if ( $fromNodeID == 0 || $fromNodeID == -1 ) { eZDebug::writeError( "NodeAssignment '" . $nodeAssignment->attribute( 'id' ) . "' is marked with op_code='$opCode' but has no data in from_node_id. Cannot use it for moving node.", __METHOD__ ); } else { // clear cache for old placement. $additionalNodeIDList = array( $fromNodeID ); eZContentCacheManager::clearContentCacheIfNeeded( $objectID, $versionNum, $additionalNodeIDList ); $originalNode = eZContentObjectTreeNode::fetchNode( $originalObjectID, $fromNodeID ); if ( $originalNode->attribute( 'main_node_id' ) == $originalNode->attribute( 'node_id' ) ) { $updateSectionID = true; } $originalNode->move( $parentNodeID ); $existingNode = eZContentObjectTreeNode::fetchNode( $originalObjectID, $parentNodeID ); $updateFields = true; } } } elseif ( $opCode == eZNodeAssignment::OP_CODE_REMOVE ) { $db->commit(); return; } if ( $updateFields ) { if ( strlen( $nodeAssignment->attribute( 'parent_remote_id' ) ) > 0 ) { $existingNode->setAttribute( 'remote_id', $nodeAssignment->attribute( 'parent_remote_id' ) ); } if ( $nodeAssignment->attribute( 'is_hidden' ) ) { $existingNode->setAttribute( 'is_hidden', 1 ); $existingNode->setAttribute( 'is_invisible', 1 ); } $existingNode->setAttribute( 'priority', $nodeAssignment->attribute( 'priority' ) ); $existingNode->setAttribute( 'sort_field', $nodeAssignment->attribute( 'sort_field' ) ); $existingNode->setAttribute( 'sort_order', $nodeAssignment->attribute( 'sort_order' ) ); } $existingNode->setAttribute( 'contentobject_is_published', 1 ); eZDebug::createAccumulatorGroup( 'nice_urls_total', 'Nice urls' ); if ( $mainNodeID > 0 ) { $existingNodeID = $existingNode->attribute( 'node_id' ); if ( $existingNodeID != $mainNodeID ) { eZContentBrowseRecent::updateNodeID( $existingNodeID, $mainNodeID ); } $existingNode->setAttribute( 'main_node_id', $mainNodeID ); } else { $existingNode->setAttribute( 'main_node_id', $existingNode->attribute( 'node_id' ) ); } $existingNode->store(); if ( $updateSectionID ) { eZContentOperationCollection::updateSectionID( $objectID, $versionNum ); } $db->commit(); if ( $mainNodeID == false ) { return $existingNode->attribute( 'node_id' ); } } static public function updateSectionID( $objectID, $versionNum ) { $object = eZContentObject::fetch( $objectID ); $version = $object->version( $versionNum ); if ( $versionNum == 1 or $object->attribute( 'current_version' ) == $versionNum ) { $newMainAssignment = null; $newMainAssignments = eZNodeAssignment::fetchForObject( $objectID, $versionNum, 1 ); if ( isset( $newMainAssignments[0] ) ) { $newMainAssignment = $newMainAssignments[0]; } // we should not update section id for toplevel nodes if ( $newMainAssignment && $newMainAssignment->attribute( 'parent_node' ) != 1 ) { // We should check if current object already has been updated for section_id // If yes we should not update object section_id by $parentNodeSectionID $sectionID = $object->attribute( 'section_id' ); if ( $sectionID > 0 ) return; $newParentObject = $newMainAssignment->getParentObject(); if ( !$newParentObject ) { return array( 'status' => eZModuleOperationInfo::STATUS_CANCELLED ); } $parentNodeSectionID = $newParentObject->attribute( 'section_id' ); $object->setAttribute( 'section_id', $parentNodeSectionID ); $object->store(); } return; } $newMainAssignmentList = eZNodeAssignment::fetchForObject( $objectID, $versionNum, 1 ); $newMainAssignment = ( count( $newMainAssignmentList ) ) ? array_pop( $newMainAssignmentList ) : null; $currentVersion = $object->attribute( 'current' ); // Here we need to fetch published nodes and not old node assignments. $oldMainNode = $object->mainNode(); if ( $newMainAssignment && $oldMainNode && $newMainAssignment->attribute( 'parent_node' ) != $oldMainNode->attribute( 'parent_node_id' ) ) { $oldMainParentNode = $oldMainNode->attribute( 'parent' ); if ( $oldMainParentNode ) { $oldParentObject = $oldMainParentNode->attribute( 'object' ); $oldParentObjectSectionID = $oldParentObject->attribute( 'section_id' ); if ( $oldParentObjectSectionID == $object->attribute( 'section_id' ) ) { $newParentNode = $newMainAssignment->attribute( 'parent_node_obj' ); if ( !$newParentNode ) return; $newParentObject = $newParentNode->attribute( 'object' ); if ( !$newParentObject ) return; $newSectionID = $newParentObject->attribute( 'section_id' ); if ( $newSectionID != $object->attribute( 'section_id' ) ) { $oldSectionID = $object->attribute( 'section_id' ); $object->setAttribute( 'section_id', $newSectionID ); $db = eZDB::instance(); $db->begin(); $object->store(); $mainNodeID = $object->attribute( 'main_node_id' ); if ( $mainNodeID > 0 ) { eZContentObjectTreeNode::assignSectionToSubTree( $mainNodeID, $newSectionID, $oldSectionID ); } $db->commit(); } } } } } static public function removeOldNodes( $objectID, $versionNum ) { $object = eZContentObject::fetch( $objectID ); if ( !$object instanceof eZContentObject ) { eZDebug::writeError( 'Unable to find object #' . $objectID, __METHOD__ ); return; } $version = $object->version( $versionNum ); if ( !$version instanceof eZContentObjectVersion ) { eZDebug::writeError( 'Unable to find version #' . $versionNum . ' for object #' . $objectID, __METHOD__ ); return; } $moveToTrash = true; $assignedExistingNodes = $object->attribute( 'assigned_nodes' ); $curentVersionNodeAssignments = $version->attribute( 'node_assignments' ); $removeParentNodeList = array(); $removeAssignmentsList = array(); foreach ( $curentVersionNodeAssignments as $nodeAssignment ) { $nodeAssignmentOpcode = $nodeAssignment->attribute( 'op_code' ); if ( $nodeAssignmentOpcode == eZNodeAssignment::OP_CODE_REMOVE || $nodeAssignmentOpcode == eZNodeAssignment::OP_CODE_REMOVE_NOP ) { $removeAssignmentsList[] = $nodeAssignment->attribute( 'id' ); if ( $nodeAssignmentOpcode == eZNodeAssignment::OP_CODE_REMOVE ) { $removeParentNodeList[] = $nodeAssignment->attribute( 'parent_node' ); } } } $db = eZDB::instance(); $db->begin(); foreach ( $assignedExistingNodes as $node ) { if ( in_array( $node->attribute( 'parent_node_id' ), $removeParentNodeList ) ) { eZContentObjectTreeNode::removeSubtrees( array( $node->attribute( 'node_id' ) ), $moveToTrash ); } } if ( count( $removeAssignmentsList ) > 0 ) { eZNodeAssignment::purgeByID( $removeAssignmentsList ); } $db->commit(); } // New function which resets the op_code field when the object is published. static public function resetNodeassignmentOpcodes( $objectID, $versionNum ) { $object = eZContentObject::fetch( $objectID ); $version = $object->version( $versionNum ); $nodeAssignments = $version->attribute( 'node_assignments' ); foreach ( $nodeAssignments as $nodeAssignment ) { if ( ( $nodeAssignment->attribute( 'op_code' ) & 1 ) == eZNodeAssignment::OP_CODE_EXECUTE ) { $nodeAssignment->setAttribute( 'op_code', ( $nodeAssignment->attribute( 'op_code' ) & ~1 ) ); $nodeAssignment->store(); } } } /** * Registers the object in search engine. * * @note Transaction unsafe. If you call several transaction unsafe methods you must enclose * the calls within a db transaction; thus within db->begin and db->commit. * * @param int $objectID Id of the object. * @param int $version Operation collection passes this default param. Not used in the method * @param bool $isMoved true if node is being moved */ static public function registerSearchObject( $objectID, $version = null, $isMoved = false ) { $objectID = (int)$objectID; eZDebug::createAccumulatorGroup( 'search_total', 'Search Total' ); $ini = eZINI::instance( 'site.ini' ); $insertPendingAction = false; $object = null; switch ( $ini->variable( 'SearchSettings', 'DelayedIndexing' ) ) { case 'enabled': $insertPendingAction = true; break; case 'classbased': $classList = $ini->variable( 'SearchSettings', 'DelayedIndexingClassList' ); $object = eZContentObject::fetch( $objectID ); if ( is_array( $classList ) && in_array( $object->attribute( 'class_identifier' ), $classList ) ) { $insertPendingAction = true; } } if ( $insertPendingAction ) { $action = $isMoved ? 'index_moved_node' : 'index_object'; eZDB::instance()->query( "INSERT INTO ezpending_actions( action, param ) VALUES ( '$action', '$objectID' )" ); return; } if ( $object === null ) $object = eZContentObject::fetch( $objectID ); // Register the object in the search engine. $needCommit = eZSearch::needCommit(); if ( eZSearch::needRemoveWithUpdate() ) { eZDebug::accumulatorStart( 'remove_object', 'search_total', 'remove object' ); eZSearch::removeObjectById( $objectID ); eZDebug::accumulatorStop( 'remove_object' ); } eZDebug::accumulatorStart( 'add_object', 'search_total', 'add object' ); if ( !eZSearch::addObject( $object, $needCommit ) ) { eZDebug::writeError( "Failed adding object ID {$object->attribute( 'id' )} in the search engine", __METHOD__ ); } eZDebug::accumulatorStop( 'add_object' ); } /*! \note Transaction unsafe. If you call several transaction unsafe methods you must enclose the calls within a db transaction; thus within db->begin and db->commit. */ static public function createNotificationEvent( $objectID, $versionNum ) { $event = eZNotificationEvent::create( 'ezpublish', array( 'object' => $objectID, 'version' => $versionNum ) ); $event->store(); } /*! Copies missing translations from published version to the draft. */ static public function copyTranslations( $objectID, $versionNum ) { $object = eZContentObject::fetch( $objectID ); if ( !$object instanceof eZContentObject ) { return array( 'status' => eZModuleOperationInfo::STATUS_CANCELLED ); } $publishedVersionNum = $object->attribute( 'current_version' ); if ( !$publishedVersionNum ) { return; } $publishedVersion = $object->version( $publishedVersionNum ); $publishedVersionTranslations = $publishedVersion->translations(); $publishedLanguages = eZContentLanguage::languagesByMask( $object->attribute( 'language_mask' ) ); $publishedLanguageCodes = array_keys( $publishedLanguages ); $version = $object->version( $versionNum ); $versionTranslationList = array_keys( eZContentLanguage::languagesByMask( $version->attribute( 'language_mask' ) ) ); foreach ( $publishedVersionTranslations as $translation ) { $translationLanguageCode = $translation->attribute( 'language_code' ); if ( in_array( $translationLanguageCode, $versionTranslationList ) || !in_array( $translationLanguageCode, $publishedLanguageCodes ) ) { continue; } foreach ( $translation->objectAttributes() as $attribute ) { $clonedAttribute = $attribute->cloneContentObjectAttribute( $versionNum, $publishedVersionNum, $objectID ); $clonedAttribute->sync(); } } $version->updateLanguageMask(); } /*! Updates non-translatable attributes. */ static public function updateNontranslatableAttributes( $objectID, $versionNum ) { $object = eZContentObject::fetch( $objectID ); $version = $object->version( $versionNum ); $nonTranslatableAttributes = $version->nonTranslatableAttributesToUpdate(); if ( $nonTranslatableAttributes ) { $attributes = $version->contentObjectAttributes( $version->initialLanguageCode() ); $attributeByClassAttrID = array(); foreach ( $attributes as $attribute ) { $attributeByClassAttrID[$attribute->attribute( 'contentclassattribute_id' )] = $attribute; } foreach ( $nonTranslatableAttributes as $attributeToUpdate ) { $originalAttribute =& $attributeByClassAttrID[$attributeToUpdate->attribute( 'contentclassattribute_id' )]; if ( $originalAttribute ) { unset( $tmp ); $tmp = $attributeToUpdate; $tmp->initialize( $attributeToUpdate->attribute( 'version' ), $originalAttribute ); $tmp->setAttribute( 'id', $attributeToUpdate->attribute( 'id' ) ); $tmp->setAttribute( 'language_code', $attributeToUpdate->attribute( 'language_code' ) ); $tmp->setAttribute( 'language_id', $attributeToUpdate->attribute( 'language_id' ) ); $tmp->setAttribute( 'attribute_original_id', $originalAttribute->attribute( 'id' ) ); $tmp->store(); $tmp->postInitialize( $attributeToUpdate->attribute( 'version' ), $originalAttribute ); } } } } static public function removeTemporaryDrafts( $objectID, $versionNum ) { $object = eZContentObject::fetch( $objectID ); $object->cleanupInternalDrafts( eZUser::currentUserID() ); } /** * Moves a node * * @param int $nodeID * @param int $objectID * @param int $newParentNodeID * * @return array An array with operation status, always true */ static public function moveNode( $nodeID, $objectID, $newParentNodeID ) { if( !eZContentObjectTreeNodeOperations::move( $nodeID, $newParentNodeID ) ) { eZDebug::writeError( "Failed to move node $nodeID as child of parent node $newParentNodeID", __METHOD__ ); return array( 'status' => false ); } eZContentObject::fixReverseRelations( $objectID, 'move' ); if ( !eZSearch::getEngine() instanceof eZSearchEngine ) { eZContentOperationCollection::registerSearchObject( $objectID ); } return array( 'status' => true ); } /** * Adds a new nodeAssignment * * @param int $nodeID * @param int $objectId * @param array $selectedNodeIDArray * * @return array An array with operation status, always true */ static public function addAssignment( $nodeID, $objectID, $selectedNodeIDArray ) { $userClassIDArray = eZUser::contentClassIDs(); $object = eZContentObject::fetch( $objectID ); $class = $object->contentClass(); $nodeAssignmentList = eZNodeAssignment::fetchForObject( $objectID, $object->attribute( 'current_version' ), 0, false ); $assignedNodes = $object->assignedNodes(); $parentNodeIDArray = array(); foreach ( $assignedNodes as $assignedNode ) { $append = false; foreach ( $nodeAssignmentList as $nodeAssignment ) { if ( $nodeAssignment['parent_node'] == $assignedNode->attribute( 'parent_node_id' ) ) { $append = true; break; } } if ( $append ) { $parentNodeIDArray[] = $assignedNode->attribute( 'parent_node_id' ); } } $db = eZDB::instance(); $db->begin(); $locationAdded = false; $node = eZContentObjectTreeNode::fetch( $nodeID ); foreach ( $selectedNodeIDArray as $selectedNodeID ) { if ( !in_array( $selectedNodeID, $parentNodeIDArray ) ) { $parentNode = eZContentObjectTreeNode::fetch( $selectedNodeID ); $parentNodeObject = $parentNode->attribute( 'object' ); $canCreate = ( ( $parentNode->checkAccess( 'create', $class->attribute( 'id' ), $parentNodeObject->attribute( 'contentclass_id' ) ) == 1 ) || ( $parentNode->canAddLocation() && $node->canRead() ) ); if ( $canCreate ) { $insertedNode = $object->addLocation( $selectedNodeID, true ); // Now set is as published and fix main_node_id $insertedNode->setAttribute( 'contentobject_is_published', 1 ); $insertedNode->setAttribute( 'main_node_id', $node->attribute( 'main_node_id' ) ); $insertedNode->setAttribute( 'contentobject_version', $node->attribute( 'contentobject_version' ) ); // Make sure the url alias is set updated. $insertedNode->updateSubTreePath(); $insertedNode->sync(); $locationAdded = true; } } } if ( $locationAdded ) { //call appropriate method from search engine eZSearch::addNodeAssignment( $nodeID, $objectID, $selectedNodeIDArray ); // clear user policy cache if this was a user object if ( in_array( $object->attribute( 'contentclass_id' ), $userClassIDArray ) ) { eZUser::purgeUserCacheByUserId( $object->attribute( 'id' ) ); } } $db->commit(); eZContentCacheManager::clearContentCacheIfNeeded( $objectID ); if ( !eZSearch::getEngine() instanceof eZSearchEngine ) { eZContentOperationCollection::registerSearchObject( $objectID ); } return array( 'status' => true ); } /** * Removes nodes * * This function does not check about permissions, this is the responsibility of the caller! * * @param array $removeNodeIdList Array of Node ID to remove * * @return array An array with operation status, always true */ static public function removeNodes( array $removeNodeIdList ) { $mainNodeChanged = array(); $nodeAssignmentIdList = array(); $objectIdList = array(); $db = eZDB::instance(); $db->begin(); foreach ( $removeNodeIdList as $nodeId ) { $node = eZContentObjectTreeNode::fetch($nodeId); $objectId = $node->attribute( 'contentobject_id' ); foreach ( eZNodeAssignment::fetchForObject( $objectId, eZContentObject::fetch( $objectId )->attribute( 'current_version' ), 0, false ) as $nodeAssignmentKey => $nodeAssignment ) { if ( $nodeAssignment['parent_node'] == $node->attribute( 'parent_node_id' ) ) { $nodeAssignmentIdList[$nodeAssignment['id']] = 1; } } if ( $nodeId == $node->attribute( 'main_node_id' ) ) $mainNodeChanged[$objectId] = 1; $node->removeThis(); if ( !isset( $objectIdList[$objectId] ) ) $objectIdList[$objectId] = eZContentObject::fetch( $objectId ); } eZNodeAssignment::purgeByID( array_keys( $nodeAssignmentIdList ) ); foreach ( array_keys( $mainNodeChanged ) as $objectId ) { $allNodes = $objectIdList[$objectId]->assignedNodes(); // Registering node that will be promoted as 'main' if ( isset( $allNodes[0] ) ) { $mainNodeChanged[$objectId] = $allNodes[0]; eZContentObjectTreeNode::updateMainNodeID( $allNodes[0]->attribute( 'node_id' ), $objectId, false, $allNodes[0]->attribute( 'parent_node_id' ) ); } } // Give other search engines that the default one a chance to reindex // when removing locations. if ( !eZSearch::getEngine() instanceof eZSearchEngine ) { foreach ( array_keys( $objectIdList ) as $objectId ) eZContentOperationCollection::registerSearchObject( $objectId ); } $db->commit(); //call appropriate method from search engine eZSearch::removeNodes( $removeNodeIdList ); $userClassIdList = eZUser::contentClassIDs(); foreach ( $objectIdList as $objectId => $object ) { eZContentCacheManager::clearObjectViewCacheIfNeeded( $objectId ); // clear user policy cache if this was a user object if ( in_array( $object->attribute( 'contentclass_id' ), $userClassIdList ) ) { eZUser::purgeUserCacheByUserId( $object->attribute( 'id' ) ); } // Give other search engines that the default one a chance to reindex // when removing locations. if ( !eZSearch::getEngine() instanceof eZSearchEngine ) { eZContentOperationCollection::registerSearchObject( $objectId ); } } // Triggering content/cache filter for Http cache purge ezpEvent::getInstance()->filter( 'content/cache', $removeNodeIdList, array_keys( $objectIdList ) ); // we don't clear template block cache here since it's cleared in eZContentObjectTreeNode::removeNode() return array( 'status' => true ); } /** * Deletes a content object, or a list of content objects * * @param array $deleteIDArray * @param bool $moveToTrash * * @return array An array with operation status, always true */ static public function deleteObject( $deleteIDArray, $moveToTrash = false ) { $ini = eZINI::instance(); $aNodes = eZContentObjectTreeNode::fetch( $deleteIDArray ); if( !is_array( $aNodes ) ) { $aNodes = array( $aNodes ); } $delayedIndexingValue = $ini->variable( 'SearchSettings', 'DelayedIndexing' ); if ( $delayedIndexingValue === 'enabled' || $delayedIndexingValue === 'classbased' ) { $pendingActionsToDelete = array(); $classList = $ini->variable( 'SearchSettings', 'DelayedIndexingClassList' ); // Will be used below if DelayedIndexing is classbased $assignedNodesByObject = array(); $nodesToDeleteByObject = array(); foreach ( $aNodes as $node ) { $object = $node->object(); $objectID = $object->attribute( 'id' ); $assignedNodes = $object->attribute( 'assigned_nodes' ); // Only delete pending action if this is the last object's node that is requested for deletion // But $deleteIDArray can also contain all the object's node (mainly if this method is called programmatically) // So if this is not the last node, then store its id in a temp array // This temp array will then be compared to the whole object's assigned nodes array if ( count( $assignedNodes ) > 1 ) { // $assignedNodesByObject will be used as a referent to check if we want to delete all lasting nodes if ( !isset( $assignedNodesByObject[$objectID] ) ) { $assignedNodesByObject[$objectID] = array(); foreach ( $assignedNodes as $assignedNode ) { $assignedNodesByObject[$objectID][] = $assignedNode->attribute( 'node_id' ); } } // Store the node assignment we want to delete // Then compare the array to the referent node assignment array $nodesToDeleteByObject[$objectID][] = $node->attribute( 'node_id' ); $diff = array_diff( $assignedNodesByObject[$objectID], $nodesToDeleteByObject[$objectID] ); if ( !empty( $diff ) ) // We still have more node assignments for object, pending action is not to be deleted considering this iteration { continue; } } if ( $delayedIndexingValue !== 'classbased' || ( is_array( $classList ) && in_array( $object->attribute( 'class_identifier' ), $classList ) ) ) { $pendingActionsToDelete[] = $objectID; } } if ( !empty( $pendingActionsToDelete ) ) { $filterConds = array( 'param' => array ( $pendingActionsToDelete ) ); eZPendingActions::removeByAction( 'index_object', $filterConds ); } } // Add assigned nodes to the clear cache list // This allows to clear assigned nodes separately (e.g. in reverse proxies) // as once content is removed, there is no more assigned nodes, and http cache clear is not possible any more. // See https://jira.ez.no/browse/EZP-22447 foreach ( $aNodes as $node ) { eZContentCacheManager::addAdditionalNodeIDPerObject( $node->attribute( 'contentobject_id' ), $node->attribute( 'node_id' ) ); } eZContentObjectTreeNode::removeSubtrees( $deleteIDArray, $moveToTrash ); return array( 'status' => true ); } /** * Changes an contentobject's status * * @param int $nodeID * * @return array An array with operation status, always true */ static public function changeHideStatus( $nodeID ) { $action = 'hide'; $curNode = eZContentObjectTreeNode::fetch( $nodeID ); if ( is_object( $curNode ) ) { if ( $curNode->attribute( 'is_hidden' ) ) { eZContentObjectTreeNode::unhideSubTree( $curNode ); $action = 'show'; } else eZContentObjectTreeNode::hideSubTree( $curNode ); } //call appropriate method from search engine eZSearch::updateNodeVisibility( $nodeID, $action ); return array( 'status' => true ); } /** * Swap a node with another one * * @param int $nodeID * @param int $selectedNodeID * @param array $nodeIdList * * @return array An array with operation status, always true */ static public function swapNode( $nodeID, $selectedNodeID, $nodeIdList = array() ) { $userClassIDArray = eZUser::contentClassIDs(); $node = eZContentObjectTreeNode::fetch( $nodeID ); $selectedNode = eZContentObjectTreeNode::fetch( $selectedNodeID ); $object = $node->object(); $nodeParentNodeID = $node->attribute( 'parent_node_id' ); $nodeParent = $node->attribute( 'parent' ); $objectID = $object->attribute( 'id' ); $objectVersion = $object->attribute( 'current_version' ); $selectedObject = $selectedNode->object(); $selectedObjectID = $selectedObject->attribute( 'id' ); $selectedObjectVersion = $selectedObject->attribute( 'current_version' ); $selectedNodeParentNodeID = $selectedNode->attribute( 'parent_node_id' ); $selectedNodeParent = $selectedNode->attribute( 'parent' ); $db = eZDB::instance(); $db->begin(); $node->setAttribute( 'contentobject_id', $selectedObjectID ); $node->setAttribute( 'contentobject_version', $selectedObjectVersion ); $selectedNode->setAttribute( 'contentobject_id', $objectID ); $selectedNode->setAttribute( 'contentobject_version', $objectVersion ); // fix main node id if ( $node->isMain() && !$selectedNode->isMain() ) { $node->setAttribute( 'main_node_id', $selectedNode->attribute( 'main_node_id' ) ); $selectedNode->setAttribute( 'main_node_id', $selectedNode->attribute( 'node_id' ) ); } else if ( $selectedNode->isMain() && !$node->isMain() ) { $selectedNode->setAttribute( 'main_node_id', $node->attribute( 'main_node_id' ) ); $node->setAttribute( 'main_node_id', $node->attribute( 'node_id' ) ); } $node->store(); $selectedNode->store(); // clear user policy cache if this was a user object if ( in_array( $object->attribute( 'contentclass_id' ), $userClassIDArray ) ) { eZUser::purgeUserCacheByUserId( $object->attribute( 'id' ) ); } if ( in_array( $selectedObject->attribute( 'contentclass_id' ), $userClassIDArray ) ) { eZUser::purgeUserCacheByUserId( $selectedObject->attribute( 'id' ) ); } // modify path string $changedOriginalNode = eZContentObjectTreeNode::fetch( $nodeID ); $changedOriginalNode->updateSubTreePath(); $changedTargetNode = eZContentObjectTreeNode::fetch( $selectedNodeID ); $changedTargetNode->updateSubTreePath(); // modify section if ( $changedOriginalNode->isMain() ) { $changedOriginalObject = $changedOriginalNode->object(); $parentObject = $nodeParent->object(); if ( $changedOriginalObject->attribute( 'section_id' ) != $parentObject->attribute( 'section_id' ) ) { eZContentObjectTreeNode::assignSectionToSubTree( $changedOriginalNode->attribute( 'main_node_id' ), $parentObject->attribute( 'section_id' ), $changedOriginalObject->attribute( 'section_id' ) ); } } if ( $changedTargetNode->isMain() ) { $changedTargetObject = $changedTargetNode->object(); $selectedParentObject = $selectedNodeParent->object(); if ( $changedTargetObject->attribute( 'section_id' ) != $selectedParentObject->attribute( 'section_id' ) ) { eZContentObjectTreeNode::assignSectionToSubTree( $changedTargetNode->attribute( 'main_node_id' ), $selectedParentObject->attribute( 'section_id' ), $changedTargetObject->attribute( 'section_id' ) ); } } eZContentObject::fixReverseRelations( $objectID, 'swap' ); eZContentObject::fixReverseRelations( $selectedObjectID, 'swap' ); $db->commit(); // clear cache for new placement. eZContentCacheManager::clearContentCacheIfNeeded( $objectID ); if ( !eZSearch::getEngine() instanceof eZSearchEngine ) { eZContentOperationCollection::registerSearchObject( $objectID ); } eZSearch::swapNode( $nodeID, $selectedNodeID, $nodeIdList = array() ); return array( 'status' => true ); } /** * Assigns a node to a section * * @param int $nodeID * @param int $selectedSectionID * @param bool $updateSearchIndexes * * @return void */ static public function updateSection( $nodeID, $selectedSectionID, $updateSearchIndexes = true ) { eZContentObjectTreeNode::assignSectionToSubTree( $nodeID, $selectedSectionID, false, $updateSearchIndexes ); } /** * Changes the status of a translation * * @param int $objectID * @param int $status * * @return array An array with operation status, always true */ static public function changeTranslationAvailableStatus( $objectID, $status = false ) { $object = eZContentObject::fetch( $objectID ); if ( !$object->canEdit() ) { return array( 'status' => false ); } if ( $object->isAlwaysAvailable() & $status == false ) { $object->setAlwaysAvailableLanguageID( false ); eZContentCacheManager::clearContentCacheIfNeeded( $objectID ); } else if ( !$object->isAlwaysAvailable() & $status == true ) { $object->setAlwaysAvailableLanguageID( $object->attribute( 'initial_language_id' ) ); eZContentCacheManager::clearContentCacheIfNeeded( $objectID ); } return array( 'status' => true ); } /** * Changes the sort order for a node * * @param int $nodeID * @param string $sortingField * @param bool $sortingOrder * * @return array An array with operation status, always true */ static public function changeSortOrder( $nodeID, $sortingField, $sortingOrder = false ) { $curNode = eZContentObjectTreeNode::fetch( $nodeID ); if ( is_object( $curNode ) ) { $db = eZDB::instance(); $db->begin(); $curNode->setAttribute( 'sort_field', $sortingField ); $curNode->setAttribute( 'sort_order', $sortingOrder ); $curNode->store(); $db->commit(); $object = $curNode->object(); eZContentCacheManager::clearContentCacheIfNeeded( $object->attribute( 'id' ) ); } return array( 'status' => true ); } /** * Updates the priority of a node * * @param int $parentNodeID * @param array $priorityArray * @param array $priorityIDArray * * @return array An array with operation status, always true */ static public function updatePriority( $parentNodeID, $priorityArray = array(), $priorityIDArray = array() ) { $curNode = eZContentObjectTreeNode::fetch( $parentNodeID ); if ( $curNode instanceof eZContentObjectTreeNode ) { $objectIDs = array(); $db = eZDB::instance(); $db->begin(); for ( $i = 0, $l = count( $priorityArray ); $i < $l; $i++ ) { $priority = (int) $priorityArray[$i]; $nodeID = (int) $priorityIDArray[$i]; $node = eZContentObjectTreeNode::fetch( $nodeID ); if ( !$node instanceof eZContentObjectTreeNode ) { continue; } $objectIDs[] = $node->attribute( 'contentobject_id' ); $db->query( "UPDATE ezcontentobject_tree SET priority={$priority} WHERE node_id={$nodeID} AND parent_node_id={$parentNodeID}" ); } $curNode->updateAndStoreModified(); $db->commit(); if ( !eZSearch::getEngine() instanceof eZSearchEngine ) { eZContentCacheManager::clearContentCacheIfNeeded( $objectIDs ); foreach ( $objectIDs as $objectID ) { eZContentOperationCollection::registerSearchObject( $objectID ); } } } return array( 'status' => true ); } /** * Update a node's main assignment * * @param int $mainAssignmentID * @param int $objectID * @param int $mainAssignmentParentID * * @return array An array with operation status, always true */ static public function updateMainAssignment( $mainAssignmentID, $objectID, $mainAssignmentParentID ) { eZContentObjectTreeNode::updateMainNodeID( $mainAssignmentID, $objectID, false, $mainAssignmentParentID ); eZContentCacheManager::clearContentCacheIfNeeded( $objectID ); if ( !eZSearch::getEngine() instanceof eZSearchEngine ) { eZContentOperationCollection::registerSearchObject( $objectID ); } return array( 'status' => true ); } /** * Updates an contentobject's initial language * * @param int $objectID * @param int $newInitialLanguageID * * @return array An array with operation status, always true */ static public function updateInitialLanguage( $objectID, $newInitialLanguageID ) { $object = eZContentObject::fetch( $objectID ); $language = eZContentLanguage::fetch( $newInitialLanguageID ); if ( $language and !$language->attribute( 'disabled' ) ) { $object->setAttribute( 'initial_language_id', $newInitialLanguageID ); $objectName = $object->name( false, $language->attribute( 'locale' ) ); $object->setAttribute( 'name', $objectName ); $object->store(); if ( $object->isAlwaysAvailable() ) { $object->setAlwaysAvailableLanguageID( $newInitialLanguageID ); } $nodes = $object->assignedNodes(); foreach ( $nodes as $node ) { $node->updateSubTreePath(); } } eZContentCacheManager::clearContentCacheIfNeeded( $objectID ); return array( 'status' => true ); } /** * Set the always available flag for a content object * * @param int $objectID * @param int $newAlwaysAvailable * @return array An array with operation status, always true */ static public function updateAlwaysAvailable( $objectID, $newAlwaysAvailable ) { $object = eZContentObject::fetch( $objectID ); $change = false; if ( $object->isAlwaysAvailable() & $newAlwaysAvailable == false ) { $object->setAlwaysAvailableLanguageID( false ); $change = true; } else if ( !$object->isAlwaysAvailable() & $newAlwaysAvailable == true ) { $object->setAlwaysAvailableLanguageID( $object->attribute( 'initial_language_id' ) ); $change = true; } if ( $change ) { eZContentCacheManager::clearContentCacheIfNeeded( $objectID ); if ( !eZSearch::getEngine() instanceof eZSearchEngine ) { eZContentOperationCollection::registerSearchObject( $objectID ); } } return array( 'status' => true ); } /** * Removes a translation for a contentobject * * @param int $objectID * @param array * @return array An array with operation status, always true */ static public function removeTranslation( $objectID, $languageIDArray ) { $object = eZContentObject::fetch( $objectID ); foreach( $languageIDArray as $languageID ) { if ( !$object->removeTranslation( $languageID ) ) { eZDebug::writeError( "Object with id $objectID: cannot remove the translation with language id $languageID!", __METHOD__ ); } } eZContentOperationCollection::registerSearchObject( $objectID ); eZContentCacheManager::clearContentCacheIfNeeded( $objectID ); return array( 'status' => true ); } /** * Update a contentobject's state * * @param int $objectID * @param int $selectedStateIDList * * @return array An array with operation status, always true */ static public function updateObjectState( $objectID, $selectedStateIDList ) { $object = eZContentObject::fetch( $objectID ); // we don't need to re-assign states the object currently already has assigned $currentStateIDArray = $object->attribute( 'state_id_array' ); $selectedStateIDList = array_diff( $selectedStateIDList, $currentStateIDArray ); // filter out any states the current user is not allowed to assign $canAssignStateIDList = $object->attribute( 'allowed_assign_state_id_list' ); $selectedStateIDList = array_intersect( $selectedStateIDList, $canAssignStateIDList ); foreach ( $selectedStateIDList as $selectedStateID ) { $state = eZContentObjectState::fetchById( $selectedStateID ); $object->assignState( $state ); } eZAudit::writeAudit( 'state-assign', array( 'Content object ID' => $object->attribute( 'id' ), 'Content object name' => $object->attribute( 'name' ), 'Selected State ID Array' => implode( ', ' , $selectedStateIDList ), 'Comment' => 'Updated states of the current object: eZContentOperationCollection::updateObjectState()' ) ); //call appropriate method from search engine eZSearch::updateObjectState($objectID, $selectedStateIDList); // Triggering content/state/assign event for persistence cache purge ezpEvent::getInstance()->notify( 'content/state/assign', array( $objectID, $selectedStateIDList ) ); eZContentCacheManager::clearContentCacheIfNeeded( $objectID ); return array( 'status' => true ); } /** * Executes the pre-publish trigger for this object, and handles * specific return statuses from the workflow * * @param int $objectID Object ID * @param int $version Version number * * @since 4.2 */ static public function executePrePublishTrigger( $objectID, $version ) { } /** * Creates a RSS/ATOM Feed export for a node * * @param int $nodeID Node ID * * @since 4.3 */ static public function createFeedForNode( $nodeID ) { $hasExport = eZRSSFunctionCollection::hasExportByNode( $nodeID ); if ( isset( $hasExport['result'] ) && $hasExport['result'] ) { eZDebug::writeError( 'There is already a rss/atom export feed for this node: ' . $nodeID, __METHOD__ ); return array( 'status' => false ); } $node = eZContentObjectTreeNode::fetch( $nodeID ); $currentClassIdentifier = $node->attribute( 'class_identifier' ); $config = eZINI::instance( 'site.ini' ); $feedItemClasses = $config->variable( 'RSSSettings', 'DefaultFeedItemClasses' ); if ( !$feedItemClasses || !isset( $feedItemClasses[ $currentClassIdentifier ] ) ) { eZDebug::writeError( "EnableRSS: content class $currentClassIdentifier is not defined in site.ini[RSSSettings]DefaultFeedItemClasses[<class_id>].", __METHOD__ ); return array( 'status' => false ); } $object = $node->object(); $objectID = $object->attribute('id'); $currentUserID = eZUser::currentUserID(); $rssExportItems = array(); $db = eZDB::instance(); $db->begin(); $rssExport = eZRSSExport::create( $currentUserID ); $rssExport->setAttribute( 'access_url', 'rss_feed_' . $nodeID ); $rssExport->setAttribute( 'node_id', $nodeID ); $rssExport->setAttribute( 'main_node_only', '1' ); $rssExport->setAttribute( 'number_of_objects', $config->variable( 'RSSSettings', 'NumberOfObjectsDefault' ) ); $rssExport->setAttribute( 'rss_version', $config->variable( 'RSSSettings', 'DefaultVersion' ) ); $rssExport->setAttribute( 'status', eZRSSExport::STATUS_VALID ); $rssExport->setAttribute( 'title', $object->name() ); $rssExport->store(); $rssExportID = $rssExport->attribute( 'id' ); foreach( explode( ';', $feedItemClasses[$currentClassIdentifier] ) as $classIdentifier ) { $iniSection = 'RSSSettings_' . $classIdentifier; if ( $config->hasVariable( $iniSection, 'FeedObjectAttributeMap' ) ) { $feedObjectAttributeMap = $config->variable( $iniSection, 'FeedObjectAttributeMap' ); $subNodesMap = $config->hasVariable( $iniSection, 'Subnodes' ) ? $config->variable( $iniSection, 'Subnodes' ) : array(); $rssExportItem = eZRSSExportItem::create( $rssExportID ); $rssExportItem->setAttribute( 'class_id', eZContentObjectTreeNode::classIDByIdentifier( $classIdentifier ) ); $rssExportItem->setAttribute( 'title', $feedObjectAttributeMap['title'] ); if ( isset( $feedObjectAttributeMap['description'] ) ) $rssExportItem->setAttribute( 'description', $feedObjectAttributeMap['description'] ); if ( isset( $feedObjectAttributeMap['category'] ) ) $rssExportItem->setAttribute( 'category', $feedObjectAttributeMap['category'] ); if ( isset( $feedObjectAttributeMap['enclosure'] ) ) $rssExportItem->setAttribute( 'enclosure', $feedObjectAttributeMap['enclosure'] ); $rssExportItem->setAttribute( 'source_node_id', $nodeID ); $rssExportItem->setAttribute( 'status', eZRSSExport::STATUS_VALID ); $rssExportItem->setAttribute( 'subnodes', isset( $subNodesMap[$currentClassIdentifier] ) && $subNodesMap[$currentClassIdentifier] === 'true' ); $rssExportItem->store(); } else { eZDebug::writeError( "site.ini[$iniSection]Source[] setting is not defined.", __METHOD__ ); } } $db->commit(); eZContentCacheManager::clearContentCacheIfNeeded( $objectID ); return array( 'status' => true ); } /** * Removes a RSS/ATOM Feed export for a node * * @param int $nodeID Node ID * * @since 4.3 */ static public function removeFeedForNode( $nodeID ) { $rssExport = eZPersistentObject::fetchObject( eZRSSExport::definition(), null, array( 'node_id' => $nodeID, 'status' => eZRSSExport::STATUS_VALID ), true ); if ( !$rssExport instanceof eZRSSExport ) { eZDebug::writeError( 'DisableRSS: There is no rss/atom feeds left to delete for this node: '. $nodeID, __METHOD__ ); return array( 'status' => false ); } $node = eZContentObjectTreeNode::fetch( $nodeID ); if ( !$node instanceof eZContentObjectTreeNode ) { eZDebug::writeError( 'DisableRSS: Could not fetch node: '. $nodeID, __METHOD__ ); return array( 'status' => false ); } $objectID = $node->attribute('contentobject_id'); $rssExport->removeThis(); eZContentCacheManager::clearContentCacheIfNeeded( $objectID ); return array( 'status' => true ); } /** * Sends the published object/version for publishing to the queue * Used by the content/publish operation * @param int $objectId * @param int $version * * @return array( status => int ) * @since 4.5 */ public static function sendToPublishingQueue( $objectId, $version ) { $behaviour = ezpContentPublishingBehaviour::getBehaviour(); if ( $behaviour->disableAsynchronousPublishing ) $asyncEnabled = false; else $asyncEnabled = ( eZINI::instance( 'content.ini' )->variable( 'PublishingSettings', 'AsynchronousPublishing' ) == 'enabled' ); $accepted = true; if ( $asyncEnabled === true ) { // Filter handlers $ini = eZINI::instance( 'content.ini' ); $filterHandlerClasses = $ini->variable( 'PublishingSettings', 'AsynchronousPublishingFilters' ); if ( count( $filterHandlerClasses ) ) { $versionObject = eZContentObjectVersion::fetchVersion( $version, $objectId ); foreach( $filterHandlerClasses as $filterHandlerClass ) { if ( !class_exists( $filterHandlerClass ) ) { eZDebug::writeError( "Unknown asynchronous publishing filter handler class '$filterHandlerClass'", __METHOD__ ); continue; } $handler = new $filterHandlerClass( $versionObject ); if ( !( $handler instanceof ezpAsynchronousPublishingFilterInterface ) ) { eZDebug::writeError( "Asynchronous publishing filter handler class '$filterHandlerClass' does not implement ezpAsynchronousPublishingFilterInterface", __METHOD__ ); continue; } $accepted = $handler->accept(); if ( !$accepted ) { eZDebugSetting::writeDebug( "Object #{$objectId}/{$version} was excluded from asynchronous publishing by $filterHandlerClass", __METHOD__ ); break; } } } unset( $filterHandlerClasses, $handler ); } if ( $asyncEnabled && $accepted ) { // if the object is already in the process queue, we move ahead // this test should NOT be necessary since http://issues.ez.no/17840 was fixed if ( ezpContentPublishingQueue::isQueued( $objectId, $version ) ) { return array( 'status' => eZModuleOperationInfo::STATUS_CONTINUE ); } // the object isn't in the process queue, this means this is the first time we execute this method // the object must be queued else { ezpContentPublishingQueue::add( $objectId, $version ); return array( 'status' => eZModuleOperationInfo::STATUS_HALTED, 'redirect_url' => "content/queued/{$objectId}/{$version}" ); } } else { return array( 'status' => eZModuleOperationInfo::STATUS_CONTINUE ); } } } ?>
Java
<?php /** * AliPay IPN Handler. * * Copyright: © 2009-2011 * {@link http://www.websharks-inc.com/ WebSharks, Inc.} * (coded in the USA) * * This WordPress plugin (s2Member Pro) is comprised of two parts: * * o (1) Its PHP code is licensed under the GPL license, as is WordPress. * You should have received a copy of the GNU General Public License, * along with this software. In the main directory, see: /licensing/ * If not, see: {@link http://www.gnu.org/licenses/}. * * o (2) All other parts of (s2Member Pro); including, but not limited to: * the CSS code, some JavaScript code, images, and design; * are licensed according to the license purchased. * See: {@link http://www.s2member.com/prices/} * * Unless you have our prior written consent, you must NOT directly or indirectly license, * sub-license, sell, resell, or provide for free; part (2) of the s2Member Pro Module; * or make an offer to do any of these things. All of these things are strictly * prohibited with part (2) of the s2Member Pro Module. * * Your purchase of s2Member Pro includes free lifetime upgrades via s2Member.com * (i.e. new features, bug fixes, updates, improvements); along with full access * to our video tutorial library: {@link http://www.s2member.com/videos/} * * @package s2Member\AliPay * @since 1.5 */ if (realpath (__FILE__) === realpath ($_SERVER["SCRIPT_FILENAME"])) exit("Do not access this file directly."); if (!class_exists ("c_ws_plugin__s2member_pro_alipay_notify")) { /** * AliPay IPN Handler. * * @package s2Member\AliPay * @since 1.5 */ class c_ws_plugin__s2member_pro_alipay_notify { /** * Handles AliPay IPN URL processing. * * @package s2Member\AliPay * @since 1.5 * * @attaches-to ``add_action("init");`` * * @return null|inner Return-value of inner routine. */ public static function alipay_notify () { if (!empty($_POST["notify_type"]) && preg_match ("/^trade_status_sync$/i", $_POST["notify_type"])) { return c_ws_plugin__s2member_pro_alipay_notify_in::alipay_notify (); } } } } ?>
Java
<?php /** * Preview class. * * @package WPForms * @author WPForms * @since 1.1.5 * @license GPL-2.0+ * @copyright Copyright (c) 2016, WPForms LLC */ class WPForms_Preview { /** * Primary class constructor. * * @since 1.1.5 */ public function __construct() { // Maybe load a preview page add_action( 'init', array( $this, 'init' ) ); // Hide preview page from admin add_action( 'pre_get_posts', array( $this, 'form_preview_hide' ) ); } /** * Determing if the user should see a preview page, if so, party on. * * @since 1.1.5 */ public function init() { // Check for preview param with allowed values if ( empty( $_GET['wpforms_preview'] ) || !in_array( $_GET['wpforms_preview'], array( 'print', 'form' ) ) ) { return; } // Check for authenticated user with correct capabilities if ( !is_user_logged_in() || !current_user_can( apply_filters( 'wpforms_manage_cap', 'manage_options' ) ) ) { return; } // Print preview if ( 'print' == $_GET['wpforms_preview'] && !empty( $_GET['entry_id'] ) ) { $this->print_preview(); } // Form preview if ( 'form' == $_GET['wpforms_preview'] && !empty( $_GET['form_id'] ) ) { $this->form_preview(); } } /** * Print Preview. * * @since 1.1.5 */ public function print_preview() { // Load entry details $entry = wpforms()->entry->get( absint( $_GET['entry_id'] ) ); // Double check that we found a real entry if ( ! $entry || empty( $entry ) ) { return; } // Get form details $form_data = wpforms()->form->get( $entry->form_id, array( 'content_only' => true ) ); // Double check that we found a valid entry if ( ! $form_data || empty( $form_data ) ) { return; } ?> <!doctype html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <title>WPForms Print Preview - <?php echo ucfirst( sanitize_text_field( $form_data['settings']['form_title'] ) ); ?> </title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="robots" content="noindex,nofollow,noarchive"> <link rel="stylesheet" href="<?php echo includes_url('css/buttons.min.css'); ?>" type="text/css"> <link rel="stylesheet" href="<?php echo WPFORMS_PLUGIN_URL; ?>assets/css/wpforms-preview.css" type="text/css"> <script type="text/javascript" src="<?php echo includes_url('js/jquery/jquery.js'); ?>"></script> <script type="text/javascript" src="<?php echo WPFORMS_PLUGIN_URL; ?>assets/js/wpforms-preview.js"></script> </head> <body class="wp-core-ui"> <div class="wpforms-preview" id="print"> <h1> <?php echo sanitize_text_field( $form_data['settings']['form_title'] ); ?> <span> - <?php printf( __( 'Entry #%d', 'wpforms' ), absint( $entry->entry_id ) ); ?></span> <div class="buttons"> <a href="" class="button button-secondary close-window">Close</a> <a href="" class="button button-primary print">Print</a> </div> </h1> <?php $fields = apply_filters( 'wpforms_entry_single_data', wpforms_decode( $entry->fields ), $entry, $form_data ); if ( empty( $fields ) ) { // Whoops, no fields! This shouldn't happen under normal use cases. echo '<p class="no-fields">' . __( 'This entry does not have any fields', 'wpforms' ) . '</p>'; } else { echo '<div class="fields">'; // Display the fields and their values foreach ( $fields as $key => $field ) { $field_value = apply_filters( 'wpforms_html_field_value', wp_strip_all_tags( $field['value'] ), $field, $form_data ); $field_class = sanitize_html_class( 'wpforms-field-' . $field['type'] ); $field_class .= empty( $field_value ) ? ' empty' : ''; echo '<div class="wpforms-entry-field ' . $field_class . '">'; // Field name echo '<p class="wpforms-entry-field-name">'; echo !empty( $field['name'] ) ? wp_strip_all_tags( $field['name'] ) : sprintf( __( 'Field ID #%d', 'wpforms' ), absint( $field['id'] ) ); echo '</p>'; // Field value echo '<p class="wpforms-entry-field-value">'; echo !empty( $field_value ) ? nl2br( make_clickable( $field_value ) ) : __( 'Empty', 'wpforms' ); echo '</p>'; echo '</div>'; } echo '</div>'; } ?> </div><!-- .wrap --> <p class="site"><a href="<?php echo home_url(); ?>"><?php echo get_bloginfo( 'name'); ?></a></p> </body> <?php exit(); } /** * Check if preview page exists, if not create it. * * @since 1.1.9 */ public function form_preview_check() { if ( !is_admin() ) return; // Verify page exits $preview = get_option( 'wpforms_preview_page' ); if ( $preview ) { $preview_page = get_post( $preview ); // Check to see if the visibility has been changed, if so correct it if ( !empty( $preview_page ) && 'private' != $preview_page->post_status ) { $preview_page->post_status = 'private'; wp_update_post( $preview_page ); return; } elseif ( !empty( $preview_page ) ) { return; } } // Create the custom preview page $content = '<p>' . __( 'This is the WPForms preview page. All your form previews will be handled on this page.', 'wpforms' ) . '</p>'; $content .= '<p>' . __( 'The page is set to private, so it is not publically accessible. Please do not delete this page :) .', 'wpforms' ) . '</p>'; $args = array( 'post_type' => 'page', 'post_name' => 'wpforms-preview', 'post_author' => 1, 'post_title' => __( 'WPForms Preview', 'wpforms' ), 'post_status' => 'private', 'post_content' => $content, 'comment_status' => 'closed' ); $id = wp_insert_post( $args ); if ( $id ) { update_option( 'wpforms_preview_page', $id ); } } /** * Preview page URL. * * @since 1.1.9 * @param int $form_id * @return string */ public function form_preview_url( $form_id ) { $id = get_option( 'wpforms_preview_page' ); if ( ! $id ) { return home_url(); } $url = get_permalink( $id ); if ( ! $url ) { return home_url(); } return add_query_arg( array( 'wpforms_preview' => 'form', 'form_id' => absint( $form_id ) ), $url ); } /** * Fires when form preview might be detected. * * @since 1.1.9 */ public function form_preview() { add_filter( 'the_posts', array( $this, 'form_preview_query' ), 10, 2 ); } /** * Tweak the page content for form preview page requests. * * @since 1.1.9 * @param array $posts * @param object $query * @return array */ public function form_preview_query( $posts, $query ) { // One last cap check, just for fun. if ( !is_user_logged_in() || !current_user_can( apply_filters( 'wpforms_manage_cap', 'manage_options' ) ) ) { return $posts; } // Only target main query if ( ! $query->is_main_query() ) { return $posts; } // If our queried object ID does not match the preview page ID, return early. $preview_id = absint( get_option( 'wpforms_preview_page' ) ); $queried = $query->get_queried_object_id(); if ( $queried && $queried != $preview_id && isset( $query->query_vars['page_id'] ) && $preview_id != $query->query_vars['page_id'] ) { return $posts; } // Get the form details $form = wpforms()->form->get( absint( $_GET['form_id'] ), array( 'content_only' => true ) ); if ( ! $form || empty( $form ) ) { return $posts; } // Customize the page content $title = sanitize_text_field( $form['settings']['form_title'] ); $shortcode = '[wpforms id="' . absint( $form['id'] ) . '"]'; $content = __( 'This is a preview of your form. This page not publically accessible.', 'wpforms' ); if ( !empty( $_GET['new_window'] ) ) { $content .= ' <a href="javascript:window.close();">' . __( 'Close this window', 'wpforms' ) . '.</a>'; } $posts[0]->post_title = $title . __( ' Preview', 'wpforms' ); $posts[0]->post_content = $content . $shortcode; $posts[0]->post_status = 'public'; return $posts; } /** * Hide the preview page from admin * * @since 1.2.3 * @param object $query */ function form_preview_hide( $query ) { if( $query->is_main_query() && is_admin() && isset( $query->query_vars['post_type'] ) && 'page' == $query->query_vars['post_type'] ) { $wpforms_preview = intval( get_option( 'wpforms_preview_page' ) ); if( $wpforms_preview ) { $exclude = $query->query_vars['post__not_in']; $exclude[] = $wpforms_preview; $query->set( 'post__not_in', $exclude ); } } } }
Java
package raw import ( "fmt" "../../platforms/common" ) type FieldMacros struct {} func (FieldMacros) DecodeDW0() { macro := common.GetMacro() // Do not decode, print as is. macro.Add(fmt.Sprintf("0x%0.8x", macro.Register(common.PAD_CFG_DW0).ValueGet())) } func (FieldMacros) DecodeDW1() { macro := common.GetMacro() // Do not decode, print as is. macro.Add(fmt.Sprintf("0x%0.8x", macro.Register(common.PAD_CFG_DW1).ValueGet())) } // GenerateString - generates the entire string of bitfield macros. func (bitfields FieldMacros) GenerateString() { macro := common.GetMacro() macro.Add("_PAD_CFG_STRUCT(").Id().Add(", ") bitfields.DecodeDW0() macro.Add(", ") bitfields.DecodeDW1() macro.Add("),") }
Java
#ifndef __SOUND_PCM_H #define __SOUND_PCM_H /* * Digital Audio (PCM) abstract layer * Copyright (c) by Jaroslav Kysela <[email protected]> * Abramo Bagnara <[email protected]> * * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 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 <sound/asound.h> #include <sound/memalloc.h> #include <sound/minors.h> #include <linux/poll.h> #include <linux/mm.h> #include <linux/bitops.h> #include <linux/pm_qos.h> #define snd_pcm_substream_chip(substream) ((substream)->private_data) #define snd_pcm_chip(pcm) ((pcm)->private_data) #if defined(CONFIG_SND_PCM_OSS) || defined(CONFIG_SND_PCM_OSS_MODULE) #include <sound/pcm_oss.h> #endif /* * Hardware (lowlevel) section */ struct snd_pcm_hardware { unsigned int info; /* SNDRV_PCM_INFO_* */ u64 formats; /* SNDRV_PCM_FMTBIT_* */ unsigned int rates; /* SNDRV_PCM_RATE_* */ unsigned int rate_min; /* min rate */ unsigned int rate_max; /* max rate */ unsigned int channels_min; /* min channels */ unsigned int channels_max; /* max channels */ size_t buffer_bytes_max; /* max buffer size */ size_t period_bytes_min; /* min period size */ size_t period_bytes_max; /* max period size */ unsigned int periods_min; /* min # of periods */ unsigned int periods_max; /* max # of periods */ size_t fifo_size; /* fifo size in bytes */ }; struct snd_pcm_substream; struct snd_pcm_ops { int (*open)(struct snd_pcm_substream *substream); int (*close)(struct snd_pcm_substream *substream); int (*ioctl)(struct snd_pcm_substream * substream, unsigned int cmd, void *arg); int (*hw_params)(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *params); int (*hw_free)(struct snd_pcm_substream *substream); int (*prepare)(struct snd_pcm_substream *substream); int (*trigger)(struct snd_pcm_substream *substream, int cmd); snd_pcm_uframes_t (*pointer)(struct snd_pcm_substream *substream); int (*wall_clock)(struct snd_pcm_substream *substream, struct timespec *audio_ts); int (*copy)(struct snd_pcm_substream *substream, int channel, snd_pcm_uframes_t pos, void __user *buf, snd_pcm_uframes_t count); int (*silence)(struct snd_pcm_substream *substream, int channel, snd_pcm_uframes_t pos, snd_pcm_uframes_t count); struct page *(*page)(struct snd_pcm_substream *substream, unsigned long offset); int (*mmap)(struct snd_pcm_substream *substream, struct vm_area_struct *vma); int (*ack)(struct snd_pcm_substream *substream); }; /* * */ #if defined(CONFIG_SND_DYNAMIC_MINORS) #define SNDRV_PCM_DEVICES (SNDRV_OS_MINORS-2) #else #define SNDRV_PCM_DEVICES 8 #endif #define SNDRV_PCM_IOCTL1_FALSE ((void *)0) #define SNDRV_PCM_IOCTL1_TRUE ((void *)1) #define SNDRV_PCM_IOCTL1_RESET 0 #define SNDRV_PCM_IOCTL1_INFO 1 #define SNDRV_PCM_IOCTL1_CHANNEL_INFO 2 #define SNDRV_PCM_IOCTL1_GSTATE 3 #define SNDRV_PCM_IOCTL1_FIFO_SIZE 4 #define SNDRV_PCM_TRIGGER_STOP 0 #define SNDRV_PCM_TRIGGER_START 1 #define SNDRV_PCM_TRIGGER_PAUSE_PUSH 3 #define SNDRV_PCM_TRIGGER_PAUSE_RELEASE 4 #define SNDRV_PCM_TRIGGER_SUSPEND 5 #define SNDRV_PCM_TRIGGER_RESUME 6 #define SNDRV_PCM_POS_XRUN ((snd_pcm_uframes_t)-1) /* If you change this don't forget to change rates[] table in pcm_native.c */ #define SNDRV_PCM_RATE_5512 (1<<0) /* 5512Hz */ #define SNDRV_PCM_RATE_8000 (1<<1) /* 8000Hz */ #define SNDRV_PCM_RATE_11025 (1<<2) /* 11025Hz */ #define SNDRV_PCM_RATE_16000 (1<<3) /* 16000Hz */ #define SNDRV_PCM_RATE_22050 (1<<4) /* 22050Hz */ #define SNDRV_PCM_RATE_32000 (1<<5) /* 32000Hz */ #define SNDRV_PCM_RATE_44100 (1<<6) /* 44100Hz */ #define SNDRV_PCM_RATE_48000 (1<<7) /* 48000Hz */ #define SNDRV_PCM_RATE_64000 (1<<8) /* 64000Hz */ #define SNDRV_PCM_RATE_88200 (1<<9) /* 88200Hz */ #define SNDRV_PCM_RATE_96000 (1<<10) /* 96000Hz */ #define SNDRV_PCM_RATE_176400 (1<<11) /* 176400Hz */ #define SNDRV_PCM_RATE_192000 (1<<12) /* 192000Hz */ #define SNDRV_PCM_RATE_352800 (1<<13) /* 352800Hz */ #define SNDRV_PCM_RATE_384000 (1<<14) /* 384000Hz */ #define SNDRV_PCM_RATE_CONTINUOUS (1<<30) /* continuous range */ #define SNDRV_PCM_RATE_KNOT (1<<31) /* supports more non-continuos rates */ #define SNDRV_PCM_RATE_8000_44100 (SNDRV_PCM_RATE_8000|SNDRV_PCM_RATE_11025|\ SNDRV_PCM_RATE_16000|SNDRV_PCM_RATE_22050|\ SNDRV_PCM_RATE_32000|SNDRV_PCM_RATE_44100) #define SNDRV_PCM_RATE_8000_48000 (SNDRV_PCM_RATE_8000_44100|SNDRV_PCM_RATE_48000) #define SNDRV_PCM_RATE_8000_96000 (SNDRV_PCM_RATE_8000_48000|SNDRV_PCM_RATE_64000|\ SNDRV_PCM_RATE_88200|SNDRV_PCM_RATE_96000) #define SNDRV_PCM_RATE_8000_192000 (SNDRV_PCM_RATE_8000_96000|SNDRV_PCM_RATE_176400|\ SNDRV_PCM_RATE_192000) #define SNDRV_PCM_RATE_8000_384000 (SNDRV_PCM_RATE_8000_192000|\ SNDRV_PCM_RATE_352800|\ SNDRV_PCM_RATE_384000) #define _SNDRV_PCM_FMTBIT(fmt) (1ULL << (__force int)SNDRV_PCM_FORMAT_##fmt) #define SNDRV_PCM_FMTBIT_S8 _SNDRV_PCM_FMTBIT(S8) #define SNDRV_PCM_FMTBIT_U8 _SNDRV_PCM_FMTBIT(U8) #define SNDRV_PCM_FMTBIT_S16_LE _SNDRV_PCM_FMTBIT(S16_LE) #define SNDRV_PCM_FMTBIT_S16_BE _SNDRV_PCM_FMTBIT(S16_BE) #define SNDRV_PCM_FMTBIT_U16_LE _SNDRV_PCM_FMTBIT(U16_LE) #define SNDRV_PCM_FMTBIT_U16_BE _SNDRV_PCM_FMTBIT(U16_BE) #define SNDRV_PCM_FMTBIT_S24_LE _SNDRV_PCM_FMTBIT(S24_LE) #define SNDRV_PCM_FMTBIT_S24_BE _SNDRV_PCM_FMTBIT(S24_BE) #define SNDRV_PCM_FMTBIT_U24_LE _SNDRV_PCM_FMTBIT(U24_LE) #define SNDRV_PCM_FMTBIT_U24_BE _SNDRV_PCM_FMTBIT(U24_BE) #define SNDRV_PCM_FMTBIT_S32_LE _SNDRV_PCM_FMTBIT(S32_LE) #define SNDRV_PCM_FMTBIT_S32_BE _SNDRV_PCM_FMTBIT(S32_BE) #define SNDRV_PCM_FMTBIT_U32_LE _SNDRV_PCM_FMTBIT(U32_LE) #define SNDRV_PCM_FMTBIT_U32_BE _SNDRV_PCM_FMTBIT(U32_BE) #define SNDRV_PCM_FMTBIT_FLOAT_LE _SNDRV_PCM_FMTBIT(FLOAT_LE) #define SNDRV_PCM_FMTBIT_FLOAT_BE _SNDRV_PCM_FMTBIT(FLOAT_BE) #define SNDRV_PCM_FMTBIT_FLOAT64_LE _SNDRV_PCM_FMTBIT(FLOAT64_LE) #define SNDRV_PCM_FMTBIT_FLOAT64_BE _SNDRV_PCM_FMTBIT(FLOAT64_BE) #define SNDRV_PCM_FMTBIT_IEC958_SUBFRAME_LE _SNDRV_PCM_FMTBIT(IEC958_SUBFRAME_LE) #define SNDRV_PCM_FMTBIT_IEC958_SUBFRAME_BE _SNDRV_PCM_FMTBIT(IEC958_SUBFRAME_BE) #define SNDRV_PCM_FMTBIT_MU_LAW _SNDRV_PCM_FMTBIT(MU_LAW) #define SNDRV_PCM_FMTBIT_A_LAW _SNDRV_PCM_FMTBIT(A_LAW) #define SNDRV_PCM_FMTBIT_IMA_ADPCM _SNDRV_PCM_FMTBIT(IMA_ADPCM) #define SNDRV_PCM_FMTBIT_MPEG _SNDRV_PCM_FMTBIT(MPEG) #define SNDRV_PCM_FMTBIT_GSM _SNDRV_PCM_FMTBIT(GSM) #define SNDRV_PCM_FMTBIT_SPECIAL _SNDRV_PCM_FMTBIT(SPECIAL) #define SNDRV_PCM_FMTBIT_S24_3LE _SNDRV_PCM_FMTBIT(S24_3LE) #define SNDRV_PCM_FMTBIT_U24_3LE _SNDRV_PCM_FMTBIT(U24_3LE) #define SNDRV_PCM_FMTBIT_S24_3BE _SNDRV_PCM_FMTBIT(S24_3BE) #define SNDRV_PCM_FMTBIT_U24_3BE _SNDRV_PCM_FMTBIT(U24_3BE) #define SNDRV_PCM_FMTBIT_S20_3LE _SNDRV_PCM_FMTBIT(S20_3LE) #define SNDRV_PCM_FMTBIT_U20_3LE _SNDRV_PCM_FMTBIT(U20_3LE) #define SNDRV_PCM_FMTBIT_S20_3BE _SNDRV_PCM_FMTBIT(S20_3BE) #define SNDRV_PCM_FMTBIT_U20_3BE _SNDRV_PCM_FMTBIT(U20_3BE) #define SNDRV_PCM_FMTBIT_S18_3LE _SNDRV_PCM_FMTBIT(S18_3LE) #define SNDRV_PCM_FMTBIT_U18_3LE _SNDRV_PCM_FMTBIT(U18_3LE) #define SNDRV_PCM_FMTBIT_S18_3BE _SNDRV_PCM_FMTBIT(S18_3BE) #define SNDRV_PCM_FMTBIT_U18_3BE _SNDRV_PCM_FMTBIT(U18_3BE) #define SNDRV_PCM_FMTBIT_G723_24 _SNDRV_PCM_FMTBIT(G723_24) #define SNDRV_PCM_FMTBIT_G723_24_1B _SNDRV_PCM_FMTBIT(G723_24_1B) #define SNDRV_PCM_FMTBIT_G723_40 _SNDRV_PCM_FMTBIT(G723_40) #define SNDRV_PCM_FMTBIT_G723_40_1B _SNDRV_PCM_FMTBIT(G723_40_1B) #define SNDRV_PCM_FMTBIT_DSD_U8 _SNDRV_PCM_FMTBIT(DSD_U8) #define SNDRV_PCM_FMTBIT_DSD_U16_LE _SNDRV_PCM_FMTBIT(DSD_U16_LE) #define SNDRV_PCM_FMTBIT_DSD_U32_LE _SNDRV_PCM_FMTBIT(DSD_U32_LE) #define SNDRV_PCM_FMTBIT_DSD_U16_BE _SNDRV_PCM_FMTBIT(DSD_U16_BE) #define SNDRV_PCM_FMTBIT_DSD_U32_BE _SNDRV_PCM_FMTBIT(DSD_U32_BE) #ifdef SNDRV_LITTLE_ENDIAN #define SNDRV_PCM_FMTBIT_S16 SNDRV_PCM_FMTBIT_S16_LE #define SNDRV_PCM_FMTBIT_U16 SNDRV_PCM_FMTBIT_U16_LE #define SNDRV_PCM_FMTBIT_S24 SNDRV_PCM_FMTBIT_S24_LE #define SNDRV_PCM_FMTBIT_U24 SNDRV_PCM_FMTBIT_U24_LE #define SNDRV_PCM_FMTBIT_S32 SNDRV_PCM_FMTBIT_S32_LE #define SNDRV_PCM_FMTBIT_U32 SNDRV_PCM_FMTBIT_U32_LE #define SNDRV_PCM_FMTBIT_FLOAT SNDRV_PCM_FMTBIT_FLOAT_LE #define SNDRV_PCM_FMTBIT_FLOAT64 SNDRV_PCM_FMTBIT_FLOAT64_LE #define SNDRV_PCM_FMTBIT_IEC958_SUBFRAME SNDRV_PCM_FMTBIT_IEC958_SUBFRAME_LE //#define SNDRV_PCM_FMTBIT_DSD_U16 SNRV_PCM_FMTBIT_DSD_U16_BE //#define SNDRV_PCM_FMTBIT_DSD_U32 SNRV_PCM_FMTBIT_DSD_U32_BE #endif #ifdef SNDRV_BIG_ENDIAN #define SNDRV_PCM_FMTBIT_S16 SNDRV_PCM_FMTBIT_S16_BE #define SNDRV_PCM_FMTBIT_U16 SNDRV_PCM_FMTBIT_U16_BE #define SNDRV_PCM_FMTBIT_S24 SNDRV_PCM_FMTBIT_S24_BE #define SNDRV_PCM_FMTBIT_U24 SNDRV_PCM_FMTBIT_U24_BE #define SNDRV_PCM_FMTBIT_S32 SNDRV_PCM_FMTBIT_S32_BE #define SNDRV_PCM_FMTBIT_U32 SNDRV_PCM_FMTBIT_U32_BE #define SNDRV_PCM_FMTBIT_FLOAT SNDRV_PCM_FMTBIT_FLOAT_BE #define SNDRV_PCM_FMTBIT_FLOAT64 SNDRV_PCM_FMTBIT_FLOAT64_BE #define SNDRV_PCM_FMTBIT_IEC958_SUBFRAME SNDRV_PCM_FMTBIT_IEC958_SUBFRAME_BE #endif struct snd_pcm_file { struct snd_pcm_substream *substream; int no_compat_mmap; }; struct snd_pcm_hw_rule; typedef int (*snd_pcm_hw_rule_func_t)(struct snd_pcm_hw_params *params, struct snd_pcm_hw_rule *rule); struct snd_pcm_hw_rule { unsigned int cond; snd_pcm_hw_rule_func_t func; int var; int deps[4]; void *private; }; struct snd_pcm_hw_constraints { struct snd_mask masks[SNDRV_PCM_HW_PARAM_LAST_MASK - SNDRV_PCM_HW_PARAM_FIRST_MASK + 1]; struct snd_interval intervals[SNDRV_PCM_HW_PARAM_LAST_INTERVAL - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL + 1]; unsigned int rules_num; unsigned int rules_all; struct snd_pcm_hw_rule *rules; }; static inline struct snd_mask *constrs_mask(struct snd_pcm_hw_constraints *constrs, snd_pcm_hw_param_t var) { return &constrs->masks[var - SNDRV_PCM_HW_PARAM_FIRST_MASK]; } static inline struct snd_interval *constrs_interval(struct snd_pcm_hw_constraints *constrs, snd_pcm_hw_param_t var) { return &constrs->intervals[var - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL]; } struct snd_ratnum { unsigned int num; unsigned int den_min, den_max, den_step; }; struct snd_ratden { unsigned int num_min, num_max, num_step; unsigned int den; }; struct snd_pcm_hw_constraint_ratnums { int nrats; struct snd_ratnum *rats; }; struct snd_pcm_hw_constraint_ratdens { int nrats; struct snd_ratden *rats; }; struct snd_pcm_hw_constraint_list { unsigned int count; const unsigned int *list; unsigned int mask; }; struct snd_pcm_hwptr_log; struct snd_pcm_runtime { /* -- Status -- */ struct snd_pcm_substream *trigger_master; struct timespec trigger_tstamp; /* trigger timestamp */ int overrange; snd_pcm_uframes_t avail_max; snd_pcm_uframes_t hw_ptr_base; /* Position at buffer restart */ snd_pcm_uframes_t hw_ptr_interrupt; /* Position at interrupt time */ unsigned long hw_ptr_jiffies; /* Time when hw_ptr is updated */ unsigned long hw_ptr_buffer_jiffies; /* buffer time in jiffies */ snd_pcm_sframes_t delay; /* extra delay; typically FIFO size */ u64 hw_ptr_wrap; /* offset for hw_ptr due to boundary wrap-around */ /* -- HW params -- */ snd_pcm_access_t access; /* access mode */ snd_pcm_format_t format; /* SNDRV_PCM_FORMAT_* */ snd_pcm_subformat_t subformat; /* subformat */ unsigned int rate; /* rate in Hz */ unsigned int channels; /* channels */ snd_pcm_uframes_t period_size; /* period size */ unsigned int periods; /* periods */ snd_pcm_uframes_t buffer_size; /* buffer size */ snd_pcm_uframes_t min_align; /* Min alignment for the format */ size_t byte_align; unsigned int frame_bits; unsigned int sample_bits; unsigned int info; unsigned int rate_num; unsigned int rate_den; unsigned int no_period_wakeup: 1; /* -- SW params -- */ int tstamp_mode; /* mmap timestamp is updated */ unsigned int period_step; snd_pcm_uframes_t start_threshold; snd_pcm_uframes_t stop_threshold; snd_pcm_uframes_t silence_threshold; /* Silence filling happens when noise is nearest than this */ snd_pcm_uframes_t silence_size; /* Silence filling size */ snd_pcm_uframes_t boundary; /* pointers wrap point */ snd_pcm_uframes_t silence_start; /* starting pointer to silence area */ snd_pcm_uframes_t silence_filled; /* size filled with silence */ union snd_pcm_sync_id sync; /* hardware synchronization ID */ /* -- mmap -- */ struct snd_pcm_mmap_status *status; struct snd_pcm_mmap_control *control; /* -- locking / scheduling -- */ snd_pcm_uframes_t twake; /* do transfer (!poll) wakeup if non-zero */ wait_queue_head_t sleep; /* poll sleep */ wait_queue_head_t tsleep; /* transfer sleep */ struct fasync_struct *fasync; /* -- private section -- */ void *private_data; void (*private_free)(struct snd_pcm_runtime *runtime); /* -- hardware description -- */ struct snd_pcm_hardware hw; struct snd_pcm_hw_constraints hw_constraints; /* -- interrupt callbacks -- */ void (*transfer_ack_begin)(struct snd_pcm_substream *substream); void (*transfer_ack_end)(struct snd_pcm_substream *substream); /* -- timer -- */ unsigned int timer_resolution; /* timer resolution */ int tstamp_type; /* timestamp type */ /* -- DMA -- */ unsigned char *dma_area; /* DMA area */ dma_addr_t dma_addr; /* physical bus address (not accessible from main CPU) */ size_t dma_bytes; /* size of DMA area */ struct snd_dma_buffer *dma_buffer_p; /* allocated buffer */ #if defined(CONFIG_SND_PCM_OSS) || defined(CONFIG_SND_PCM_OSS_MODULE) /* -- OSS things -- */ struct snd_pcm_oss_runtime oss; #endif #ifdef CONFIG_SND_PCM_XRUN_DEBUG struct snd_pcm_hwptr_log *hwptr_log; #endif }; struct snd_pcm_group { /* keep linked substreams */ spinlock_t lock; struct list_head substreams; int count; }; struct pid; struct snd_pcm_substream { struct snd_pcm *pcm; struct snd_pcm_str *pstr; void *private_data; /* copied from pcm->private_data */ int number; char name[32]; /* substream name */ int stream; /* stream (direction) */ struct pm_qos_request latency_pm_qos_req; /* pm_qos request */ size_t buffer_bytes_max; /* limit ring buffer size */ struct snd_dma_buffer dma_buffer; size_t dma_max; /* -- hardware operations -- */ const struct snd_pcm_ops *ops; /* -- runtime information -- */ struct snd_pcm_runtime *runtime; /* -- timer section -- */ struct snd_timer *timer; /* timer */ unsigned timer_running: 1; /* time is running */ /* -- next substream -- */ struct snd_pcm_substream *next; /* -- linked substreams -- */ struct list_head link_list; /* linked list member */ struct snd_pcm_group self_group; /* fake group for non linked substream (with substream lock inside) */ struct snd_pcm_group *group; /* pointer to current group */ /* -- assigned files -- */ void *file; int ref_count; atomic_t mmap_count; unsigned int f_flags; void (*pcm_release)(struct snd_pcm_substream *); struct pid *pid; #if defined(CONFIG_SND_PCM_OSS) || defined(CONFIG_SND_PCM_OSS_MODULE) /* -- OSS things -- */ struct snd_pcm_oss_substream oss; #endif #ifdef CONFIG_SND_VERBOSE_PROCFS struct snd_info_entry *proc_root; struct snd_info_entry *proc_info_entry; struct snd_info_entry *proc_hw_params_entry; struct snd_info_entry *proc_sw_params_entry; struct snd_info_entry *proc_status_entry; struct snd_info_entry *proc_prealloc_entry; struct snd_info_entry *proc_prealloc_max_entry; #endif /* misc flags */ unsigned int hw_opened: 1; }; #define SUBSTREAM_BUSY(substream) ((substream)->ref_count > 0) struct snd_pcm_str { int stream; /* stream (direction) */ struct snd_pcm *pcm; /* -- substreams -- */ unsigned int substream_count; unsigned int substream_opened; struct snd_pcm_substream *substream; #if defined(CONFIG_SND_PCM_OSS) || defined(CONFIG_SND_PCM_OSS_MODULE) /* -- OSS things -- */ struct snd_pcm_oss_stream oss; #endif #ifdef CONFIG_SND_VERBOSE_PROCFS struct snd_info_entry *proc_root; struct snd_info_entry *proc_info_entry; #ifdef CONFIG_SND_PCM_XRUN_DEBUG unsigned int xrun_debug; /* 0 = disabled, 1 = verbose, 2 = stacktrace */ struct snd_info_entry *proc_xrun_debug_entry; #endif #endif struct snd_kcontrol *chmap_kctl; /* channel-mapping controls */ }; struct snd_pcm { struct snd_card *card; struct list_head list; int device; /* device number */ unsigned int info_flags; unsigned short dev_class; unsigned short dev_subclass; char id[64]; char name[80]; struct snd_pcm_str streams[2]; struct mutex open_mutex; wait_queue_head_t open_wait; void *private_data; void (*private_free) (struct snd_pcm *pcm); struct device *dev; /* actual hw device this belongs to */ bool internal; /* pcm is for internal use only */ #if defined(CONFIG_SND_PCM_OSS) || defined(CONFIG_SND_PCM_OSS_MODULE) struct snd_pcm_oss oss; #endif }; struct snd_pcm_notify { int (*n_register) (struct snd_pcm * pcm); int (*n_disconnect) (struct snd_pcm * pcm); int (*n_unregister) (struct snd_pcm * pcm); struct list_head list; }; /* * Registering */ extern const struct file_operations snd_pcm_f_ops[2]; int snd_pcm_new(struct snd_card *card, const char *id, int device, int playback_count, int capture_count, struct snd_pcm **rpcm); int snd_pcm_new_internal(struct snd_card *card, const char *id, int device, int playback_count, int capture_count, struct snd_pcm **rpcm); int snd_pcm_new_stream(struct snd_pcm *pcm, int stream, int substream_count); int snd_pcm_notify(struct snd_pcm_notify *notify, int nfree); /* * Native I/O */ extern rwlock_t snd_pcm_link_rwlock; int snd_pcm_info(struct snd_pcm_substream *substream, struct snd_pcm_info *info); int snd_pcm_info_user(struct snd_pcm_substream *substream, struct snd_pcm_info __user *info); int snd_pcm_status(struct snd_pcm_substream *substream, struct snd_pcm_status *status); int snd_pcm_start(struct snd_pcm_substream *substream); int snd_pcm_stop(struct snd_pcm_substream *substream, snd_pcm_state_t status); int snd_pcm_drain_done(struct snd_pcm_substream *substream); #ifdef CONFIG_PM int snd_pcm_suspend(struct snd_pcm_substream *substream); int snd_pcm_suspend_all(struct snd_pcm *pcm); #endif int snd_pcm_kernel_ioctl(struct snd_pcm_substream *substream, unsigned int cmd, void *arg); int snd_pcm_open_substream(struct snd_pcm *pcm, int stream, struct file *file, struct snd_pcm_substream **rsubstream); void snd_pcm_release_substream(struct snd_pcm_substream *substream); int snd_pcm_attach_substream(struct snd_pcm *pcm, int stream, struct file *file, struct snd_pcm_substream **rsubstream); void snd_pcm_detach_substream(struct snd_pcm_substream *substream); void snd_pcm_vma_notify_data(void *client, void *data); int snd_pcm_mmap_data(struct snd_pcm_substream *substream, struct file *file, struct vm_area_struct *area); #ifdef CONFIG_SND_DEBUG void snd_pcm_debug_name(struct snd_pcm_substream *substream, char *name, size_t len); #else static inline void snd_pcm_debug_name(struct snd_pcm_substream *substream, char *buf, size_t size) { *buf = 0; } #endif /* * PCM library */ static inline int snd_pcm_stream_linked(struct snd_pcm_substream *substream) { return substream->group != &substream->self_group; } static inline void snd_pcm_stream_lock(struct snd_pcm_substream *substream) { read_lock(&snd_pcm_link_rwlock); spin_lock(&substream->self_group.lock); } static inline void snd_pcm_stream_unlock(struct snd_pcm_substream *substream) { spin_unlock(&substream->self_group.lock); read_unlock(&snd_pcm_link_rwlock); } static inline void snd_pcm_stream_lock_irq(struct snd_pcm_substream *substream) { read_lock_irq(&snd_pcm_link_rwlock); spin_lock(&substream->self_group.lock); } static inline void snd_pcm_stream_unlock_irq(struct snd_pcm_substream *substream) { spin_unlock(&substream->self_group.lock); read_unlock_irq(&snd_pcm_link_rwlock); } #define snd_pcm_stream_lock_irqsave(substream, flags) \ do { \ read_lock_irqsave(&snd_pcm_link_rwlock, (flags)); \ spin_lock(&substream->self_group.lock); \ } while (0) #define snd_pcm_stream_unlock_irqrestore(substream, flags) \ do { \ spin_unlock(&substream->self_group.lock); \ read_unlock_irqrestore(&snd_pcm_link_rwlock, (flags)); \ } while (0) #define snd_pcm_group_for_each_entry(s, substream) \ list_for_each_entry(s, &substream->group->substreams, link_list) static inline int snd_pcm_running(struct snd_pcm_substream *substream) { return (substream->runtime->status->state == SNDRV_PCM_STATE_RUNNING || (substream->runtime->status->state == SNDRV_PCM_STATE_DRAINING && substream->stream == SNDRV_PCM_STREAM_PLAYBACK)); } static inline ssize_t bytes_to_samples(struct snd_pcm_runtime *runtime, ssize_t size) { return size * 8 / runtime->sample_bits; } static inline snd_pcm_sframes_t bytes_to_frames(struct snd_pcm_runtime *runtime, ssize_t size) { return size * 8 / runtime->frame_bits; } static inline ssize_t samples_to_bytes(struct snd_pcm_runtime *runtime, ssize_t size) { return size * runtime->sample_bits / 8; } static inline ssize_t frames_to_bytes(struct snd_pcm_runtime *runtime, snd_pcm_sframes_t size) { return size * runtime->frame_bits / 8; } static inline int frame_aligned(struct snd_pcm_runtime *runtime, ssize_t bytes) { return bytes % runtime->byte_align == 0; } static inline size_t snd_pcm_lib_buffer_bytes(struct snd_pcm_substream *substream) { struct snd_pcm_runtime *runtime = substream->runtime; return frames_to_bytes(runtime, runtime->buffer_size); } static inline size_t snd_pcm_lib_period_bytes(struct snd_pcm_substream *substream) { struct snd_pcm_runtime *runtime = substream->runtime; return frames_to_bytes(runtime, runtime->period_size); } /* * result is: 0 ... (boundary - 1) */ static inline snd_pcm_uframes_t snd_pcm_playback_avail(struct snd_pcm_runtime *runtime) { snd_pcm_sframes_t avail = runtime->status->hw_ptr + runtime->buffer_size - runtime->control->appl_ptr; if (avail < 0) avail += runtime->boundary; else if ((snd_pcm_uframes_t) avail >= runtime->boundary) avail -= runtime->boundary; return avail; } /* * result is: 0 ... (boundary - 1) */ static inline snd_pcm_uframes_t snd_pcm_capture_avail(struct snd_pcm_runtime *runtime) { snd_pcm_sframes_t avail = runtime->status->hw_ptr - runtime->control->appl_ptr; if (avail < 0) avail += runtime->boundary; return avail; } static inline snd_pcm_sframes_t snd_pcm_playback_hw_avail(struct snd_pcm_runtime *runtime) { return runtime->buffer_size - snd_pcm_playback_avail(runtime); } static inline snd_pcm_sframes_t snd_pcm_capture_hw_avail(struct snd_pcm_runtime *runtime) { return runtime->buffer_size - snd_pcm_capture_avail(runtime); } /** * snd_pcm_playback_ready - check whether the playback buffer is available * @substream: the pcm substream instance * * Checks whether enough free space is available on the playback buffer. * * Return: Non-zero if available, or zero if not. */ static inline int snd_pcm_playback_ready(struct snd_pcm_substream *substream) { struct snd_pcm_runtime *runtime = substream->runtime; return snd_pcm_playback_avail(runtime) >= runtime->control->avail_min; } /** * snd_pcm_capture_ready - check whether the capture buffer is available * @substream: the pcm substream instance * * Checks whether enough capture data is available on the capture buffer. * * Return: Non-zero if available, or zero if not. */ static inline int snd_pcm_capture_ready(struct snd_pcm_substream *substream) { struct snd_pcm_runtime *runtime = substream->runtime; return snd_pcm_capture_avail(runtime) >= runtime->control->avail_min; } /** * snd_pcm_playback_data - check whether any data exists on the playback buffer * @substream: the pcm substream instance * * Checks whether any data exists on the playback buffer. * * Return: Non-zero if any data exists, or zero if not. If stop_threshold * is bigger or equal to boundary, then this function returns always non-zero. */ static inline int snd_pcm_playback_data(struct snd_pcm_substream *substream) { struct snd_pcm_runtime *runtime = substream->runtime; if (runtime->stop_threshold >= runtime->boundary) return 1; return snd_pcm_playback_avail(runtime) < runtime->buffer_size; } /** * snd_pcm_playback_empty - check whether the playback buffer is empty * @substream: the pcm substream instance * * Checks whether the playback buffer is empty. * * Return: Non-zero if empty, or zero if not. */ static inline int snd_pcm_playback_empty(struct snd_pcm_substream *substream) { struct snd_pcm_runtime *runtime = substream->runtime; return snd_pcm_playback_avail(runtime) >= runtime->buffer_size; } /** * snd_pcm_capture_empty - check whether the capture buffer is empty * @substream: the pcm substream instance * * Checks whether the capture buffer is empty. * * Return: Non-zero if empty, or zero if not. */ static inline int snd_pcm_capture_empty(struct snd_pcm_substream *substream) { struct snd_pcm_runtime *runtime = substream->runtime; return snd_pcm_capture_avail(runtime) == 0; } static inline void snd_pcm_trigger_done(struct snd_pcm_substream *substream, struct snd_pcm_substream *master) { substream->runtime->trigger_master = master; } static inline int hw_is_mask(int var) { return var >= SNDRV_PCM_HW_PARAM_FIRST_MASK && var <= SNDRV_PCM_HW_PARAM_LAST_MASK; } static inline int hw_is_interval(int var) { return var >= SNDRV_PCM_HW_PARAM_FIRST_INTERVAL && var <= SNDRV_PCM_HW_PARAM_LAST_INTERVAL; } static inline struct snd_mask *hw_param_mask(struct snd_pcm_hw_params *params, snd_pcm_hw_param_t var) { return &params->masks[var - SNDRV_PCM_HW_PARAM_FIRST_MASK]; } static inline struct snd_interval *hw_param_interval(struct snd_pcm_hw_params *params, snd_pcm_hw_param_t var) { return &params->intervals[var - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL]; } static inline const struct snd_mask *hw_param_mask_c(const struct snd_pcm_hw_params *params, snd_pcm_hw_param_t var) { return &params->masks[var - SNDRV_PCM_HW_PARAM_FIRST_MASK]; } static inline const struct snd_interval *hw_param_interval_c(const struct snd_pcm_hw_params *params, snd_pcm_hw_param_t var) { return &params->intervals[var - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL]; } #define params_channels(p) \ (hw_param_interval_c((p), SNDRV_PCM_HW_PARAM_CHANNELS)->min) #define params_rate(p) \ (hw_param_interval_c((p), SNDRV_PCM_HW_PARAM_RATE)->min) #define params_period_size(p) \ (hw_param_interval_c((p), SNDRV_PCM_HW_PARAM_PERIOD_SIZE)->min) #define params_periods(p) \ (hw_param_interval_c((p), SNDRV_PCM_HW_PARAM_PERIODS)->min) #define params_buffer_size(p) \ (hw_param_interval_c((p), SNDRV_PCM_HW_PARAM_BUFFER_SIZE)->min) #define params_buffer_bytes(p) \ (hw_param_interval_c((p), SNDRV_PCM_HW_PARAM_BUFFER_BYTES)->min) int snd_interval_refine(struct snd_interval *i, const struct snd_interval *v); void snd_interval_mul(const struct snd_interval *a, const struct snd_interval *b, struct snd_interval *c); void snd_interval_div(const struct snd_interval *a, const struct snd_interval *b, struct snd_interval *c); void snd_interval_muldivk(const struct snd_interval *a, const struct snd_interval *b, unsigned int k, struct snd_interval *c); void snd_interval_mulkdiv(const struct snd_interval *a, unsigned int k, const struct snd_interval *b, struct snd_interval *c); int snd_interval_list(struct snd_interval *i, unsigned int count, const unsigned int *list, unsigned int mask); int snd_interval_ratnum(struct snd_interval *i, unsigned int rats_count, struct snd_ratnum *rats, unsigned int *nump, unsigned int *denp); void _snd_pcm_hw_params_any(struct snd_pcm_hw_params *params); void _snd_pcm_hw_param_setempty(struct snd_pcm_hw_params *params, snd_pcm_hw_param_t var); int snd_pcm_hw_params_choose(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *params); int snd_pcm_hw_refine(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *params); int snd_pcm_hw_constraints_init(struct snd_pcm_substream *substream); int snd_pcm_hw_constraints_complete(struct snd_pcm_substream *substream); int snd_pcm_hw_constraint_mask(struct snd_pcm_runtime *runtime, snd_pcm_hw_param_t var, u_int32_t mask); int snd_pcm_hw_constraint_mask64(struct snd_pcm_runtime *runtime, snd_pcm_hw_param_t var, u_int64_t mask); int snd_pcm_hw_constraint_minmax(struct snd_pcm_runtime *runtime, snd_pcm_hw_param_t var, unsigned int min, unsigned int max); int snd_pcm_hw_constraint_integer(struct snd_pcm_runtime *runtime, snd_pcm_hw_param_t var); int snd_pcm_hw_constraint_list(struct snd_pcm_runtime *runtime, unsigned int cond, snd_pcm_hw_param_t var, const struct snd_pcm_hw_constraint_list *l); int snd_pcm_hw_constraint_ratnums(struct snd_pcm_runtime *runtime, unsigned int cond, snd_pcm_hw_param_t var, struct snd_pcm_hw_constraint_ratnums *r); int snd_pcm_hw_constraint_ratdens(struct snd_pcm_runtime *runtime, unsigned int cond, snd_pcm_hw_param_t var, struct snd_pcm_hw_constraint_ratdens *r); int snd_pcm_hw_constraint_msbits(struct snd_pcm_runtime *runtime, unsigned int cond, unsigned int width, unsigned int msbits); int snd_pcm_hw_constraint_step(struct snd_pcm_runtime *runtime, unsigned int cond, snd_pcm_hw_param_t var, unsigned long step); int snd_pcm_hw_constraint_pow2(struct snd_pcm_runtime *runtime, unsigned int cond, snd_pcm_hw_param_t var); int snd_pcm_hw_rule_noresample(struct snd_pcm_runtime *runtime, unsigned int base_rate); int snd_pcm_hw_rule_add(struct snd_pcm_runtime *runtime, unsigned int cond, int var, snd_pcm_hw_rule_func_t func, void *private, int dep, ...); int snd_pcm_format_signed(snd_pcm_format_t format); int snd_pcm_format_unsigned(snd_pcm_format_t format); int snd_pcm_format_linear(snd_pcm_format_t format); int snd_pcm_format_little_endian(snd_pcm_format_t format); int snd_pcm_format_big_endian(snd_pcm_format_t format); #if 0 /* just for DocBook */ /** * snd_pcm_format_cpu_endian - Check the PCM format is CPU-endian * @format: the format to check * * Return: 1 if the given PCM format is CPU-endian, 0 if * opposite, or a negative error code if endian not specified. */ int snd_pcm_format_cpu_endian(snd_pcm_format_t format); #endif /* DocBook */ #ifdef SNDRV_LITTLE_ENDIAN #define snd_pcm_format_cpu_endian(format) snd_pcm_format_little_endian(format) #else #define snd_pcm_format_cpu_endian(format) snd_pcm_format_big_endian(format) #endif int snd_pcm_format_width(snd_pcm_format_t format); /* in bits */ int snd_pcm_format_physical_width(snd_pcm_format_t format); /* in bits */ ssize_t snd_pcm_format_size(snd_pcm_format_t format, size_t samples); const unsigned char *snd_pcm_format_silence_64(snd_pcm_format_t format); int snd_pcm_format_set_silence(snd_pcm_format_t format, void *buf, unsigned int frames); snd_pcm_format_t snd_pcm_build_linear_format(int width, int unsigned, int big_endian); void snd_pcm_set_ops(struct snd_pcm * pcm, int direction, const struct snd_pcm_ops *ops); void snd_pcm_set_sync(struct snd_pcm_substream *substream); int snd_pcm_lib_interleave_len(struct snd_pcm_substream *substream); int snd_pcm_lib_ioctl(struct snd_pcm_substream *substream, unsigned int cmd, void *arg); int snd_pcm_update_state(struct snd_pcm_substream *substream, struct snd_pcm_runtime *runtime); int snd_pcm_update_hw_ptr(struct snd_pcm_substream *substream); int snd_pcm_playback_xrun_check(struct snd_pcm_substream *substream); int snd_pcm_capture_xrun_check(struct snd_pcm_substream *substream); int snd_pcm_playback_xrun_asap(struct snd_pcm_substream *substream); int snd_pcm_capture_xrun_asap(struct snd_pcm_substream *substream); void snd_pcm_playback_silence(struct snd_pcm_substream *substream, snd_pcm_uframes_t new_hw_ptr); void snd_pcm_period_elapsed(struct snd_pcm_substream *substream); snd_pcm_sframes_t snd_pcm_lib_write(struct snd_pcm_substream *substream, const void __user *buf, snd_pcm_uframes_t frames); snd_pcm_sframes_t snd_pcm_lib_read(struct snd_pcm_substream *substream, void __user *buf, snd_pcm_uframes_t frames); snd_pcm_sframes_t snd_pcm_lib_writev(struct snd_pcm_substream *substream, void __user **bufs, snd_pcm_uframes_t frames); snd_pcm_sframes_t snd_pcm_lib_readv(struct snd_pcm_substream *substream, void __user **bufs, snd_pcm_uframes_t frames); extern const struct snd_pcm_hw_constraint_list snd_pcm_known_rates; int snd_pcm_limit_hw_rates(struct snd_pcm_runtime *runtime); unsigned int snd_pcm_rate_to_rate_bit(unsigned int rate); unsigned int snd_pcm_rate_bit_to_rate(unsigned int rate_bit); unsigned int snd_pcm_rate_mask_intersect(unsigned int rates_a, unsigned int rates_b); static inline void snd_pcm_set_runtime_buffer(struct snd_pcm_substream *substream, struct snd_dma_buffer *bufp) { struct snd_pcm_runtime *runtime = substream->runtime; if (bufp) { runtime->dma_buffer_p = bufp; runtime->dma_area = bufp->area; runtime->dma_addr = bufp->addr; runtime->dma_bytes = bufp->bytes; } else { runtime->dma_buffer_p = NULL; runtime->dma_area = NULL; runtime->dma_addr = 0; runtime->dma_bytes = 0; } } /* * Timer interface */ void snd_pcm_timer_resolution_change(struct snd_pcm_substream *substream); void snd_pcm_timer_init(struct snd_pcm_substream *substream); void snd_pcm_timer_done(struct snd_pcm_substream *substream); static inline void snd_pcm_gettime(struct snd_pcm_runtime *runtime, struct timespec *tv) { if (runtime->tstamp_type == SNDRV_PCM_TSTAMP_TYPE_MONOTONIC) do_posix_clock_monotonic_gettime(tv); else getnstimeofday(tv); } /* * Memory */ int snd_pcm_lib_preallocate_free(struct snd_pcm_substream *substream); int snd_pcm_lib_preallocate_free_for_all(struct snd_pcm *pcm); int snd_pcm_lib_preallocate_pages(struct snd_pcm_substream *substream, int type, struct device *data, size_t size, size_t max); int snd_pcm_lib_preallocate_pages_for_all(struct snd_pcm *pcm, int type, void *data, size_t size, size_t max); int snd_pcm_lib_malloc_pages(struct snd_pcm_substream *substream, size_t size); int snd_pcm_lib_free_pages(struct snd_pcm_substream *substream); int _snd_pcm_lib_alloc_vmalloc_buffer(struct snd_pcm_substream *substream, size_t size, gfp_t gfp_flags); int snd_pcm_lib_free_vmalloc_buffer(struct snd_pcm_substream *substream); struct page *snd_pcm_lib_get_vmalloc_page(struct snd_pcm_substream *substream, unsigned long offset); #if 0 /* for kernel-doc */ /** * snd_pcm_lib_alloc_vmalloc_buffer - allocate virtual DMA buffer * @substream: the substream to allocate the buffer to * @size: the requested buffer size, in bytes * * Allocates the PCM substream buffer using vmalloc(), i.e., the memory is * contiguous in kernel virtual space, but not in physical memory. Use this * if the buffer is accessed by kernel code but not by device DMA. * * Return: 1 if the buffer was changed, 0 if not changed, or a negative error * code. */ static int snd_pcm_lib_alloc_vmalloc_buffer (struct snd_pcm_substream *substream, size_t size); /** * snd_pcm_lib_alloc_vmalloc_32_buffer - allocate 32-bit-addressable buffer * @substream: the substream to allocate the buffer to * @size: the requested buffer size, in bytes * * This function works like snd_pcm_lib_alloc_vmalloc_buffer(), but uses * vmalloc_32(), i.e., the pages are allocated from 32-bit-addressable memory. * * Return: 1 if the buffer was changed, 0 if not changed, or a negative error * code. */ static int snd_pcm_lib_alloc_vmalloc_32_buffer (struct snd_pcm_substream *substream, size_t size); #endif #define snd_pcm_lib_alloc_vmalloc_buffer(subs, size) \ _snd_pcm_lib_alloc_vmalloc_buffer \ (subs, size, GFP_KERNEL | __GFP_HIGHMEM | __GFP_ZERO) #define snd_pcm_lib_alloc_vmalloc_32_buffer(subs, size) \ _snd_pcm_lib_alloc_vmalloc_buffer \ (subs, size, GFP_KERNEL | GFP_DMA32 | __GFP_ZERO) #define snd_pcm_get_dma_buf(substream) ((substream)->runtime->dma_buffer_p) #ifdef CONFIG_SND_DMA_SGBUF /* * SG-buffer handling */ #define snd_pcm_substream_sgbuf(substream) \ snd_pcm_get_dma_buf(substream)->private_data struct page *snd_pcm_sgbuf_ops_page(struct snd_pcm_substream *substream, unsigned long offset); #else /* !SND_DMA_SGBUF */ /* * fake using a continuous buffer */ #define snd_pcm_sgbuf_ops_page NULL #endif /* SND_DMA_SGBUF */ static inline dma_addr_t snd_pcm_sgbuf_get_addr(struct snd_pcm_substream *substream, unsigned int ofs) { return snd_sgbuf_get_addr(snd_pcm_get_dma_buf(substream), ofs); } static inline void * snd_pcm_sgbuf_get_ptr(struct snd_pcm_substream *substream, unsigned int ofs) { return snd_sgbuf_get_ptr(snd_pcm_get_dma_buf(substream), ofs); } static inline unsigned int snd_pcm_sgbuf_get_chunk_size(struct snd_pcm_substream *substream, unsigned int ofs, unsigned int size) { return snd_sgbuf_get_chunk_size(snd_pcm_get_dma_buf(substream), ofs, size); } /* handle mmap counter - PCM mmap callback should handle this counter properly */ static inline void snd_pcm_mmap_data_open(struct vm_area_struct *area) { struct snd_pcm_substream *substream = (struct snd_pcm_substream *)area->vm_private_data; atomic_inc(&substream->mmap_count); } static inline void snd_pcm_mmap_data_close(struct vm_area_struct *area) { struct snd_pcm_substream *substream = (struct snd_pcm_substream *)area->vm_private_data; atomic_dec(&substream->mmap_count); } int snd_pcm_lib_default_mmap(struct snd_pcm_substream *substream, struct vm_area_struct *area); /* mmap for io-memory area */ #if defined(CONFIG_X86) || defined(CONFIG_PPC) || defined(CONFIG_ALPHA) #define SNDRV_PCM_INFO_MMAP_IOMEM SNDRV_PCM_INFO_MMAP int snd_pcm_lib_mmap_iomem(struct snd_pcm_substream *substream, struct vm_area_struct *area); #else #define SNDRV_PCM_INFO_MMAP_IOMEM 0 #define snd_pcm_lib_mmap_iomem NULL #endif #define snd_pcm_lib_mmap_vmalloc NULL static inline void snd_pcm_limit_isa_dma_size(int dma, size_t *max) { *max = dma < 4 ? 64 * 1024 : 128 * 1024; } /* * Misc */ #define SNDRV_PCM_DEFAULT_CON_SPDIF (IEC958_AES0_CON_EMPHASIS_NONE|\ (IEC958_AES1_CON_ORIGINAL<<8)|\ (IEC958_AES1_CON_PCM_CODER<<8)|\ (IEC958_AES3_CON_FS_48000<<24)) #define PCM_RUNTIME_CHECK(sub) snd_BUG_ON(!(sub) || !(sub)->runtime) const char *snd_pcm_format_name(snd_pcm_format_t format); /** * snd_pcm_stream_str - Get a string naming the direction of a stream * @substream: the pcm substream instance * * Return: A string naming the direction of the stream. */ static inline const char *snd_pcm_stream_str(struct snd_pcm_substream *substream) { if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) return "Playback"; else return "Capture"; } /* * PCM channel-mapping control API */ /* array element of channel maps */ struct snd_pcm_chmap_elem { unsigned char channels; unsigned char map[15]; }; /* channel map information; retrieved via snd_kcontrol_chip() */ struct snd_pcm_chmap { struct snd_pcm *pcm; /* assigned PCM instance */ int stream; /* PLAYBACK or CAPTURE */ struct snd_kcontrol *kctl; const struct snd_pcm_chmap_elem *chmap; unsigned int max_channels; unsigned int channel_mask; /* optional: active channels bitmask */ void *private_data; /* optional: private data pointer */ }; /* get the PCM substream assigned to the given chmap info */ static inline struct snd_pcm_substream * snd_pcm_chmap_substream(struct snd_pcm_chmap *info, unsigned int idx) { struct snd_pcm_substream *s; for (s = info->pcm->streams[info->stream].substream; s; s = s->next) if (s->number == idx) return s; return NULL; } /* ALSA-standard channel maps (RL/RR prior to C/LFE) */ extern const struct snd_pcm_chmap_elem snd_pcm_std_chmaps[]; /* Other world's standard channel maps (C/LFE prior to RL/RR) */ extern const struct snd_pcm_chmap_elem snd_pcm_alt_chmaps[]; /* bit masks to be passed to snd_pcm_chmap.channel_mask field */ #define SND_PCM_CHMAP_MASK_24 ((1U << 2) | (1U << 4)) #define SND_PCM_CHMAP_MASK_246 (SND_PCM_CHMAP_MASK_24 | (1U << 6)) #define SND_PCM_CHMAP_MASK_2468 (SND_PCM_CHMAP_MASK_246 | (1U << 8)) int snd_pcm_add_chmap_ctls(struct snd_pcm *pcm, int stream, const struct snd_pcm_chmap_elem *chmap, int max_channels, unsigned long private_value, struct snd_pcm_chmap **info_ret); /* Strong-typed conversion of pcm_format to bitwise */ static inline u64 pcm_format_to_bits(snd_pcm_format_t pcm_format) { return 1ULL << (__force int) pcm_format; } #endif /* __SOUND_PCM_H */
Java
<?php /** * Magento * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to [email protected] so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade Magento to newer * versions in the future. If you wish to customize Magento for your * needs please refer to http://www.magento.com for more information. * * @category Mage * @package Mage_Tax * @copyright Copyright (c) 2006-2017 X.commerce, Inc. and affiliates (http://www.magento.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ /** * Tax rate resource model * * @category Mage * @package Mage_Tax * @author Magento Core Team <[email protected]> */ class Mage_Tax_Model_Mysql4_Calculation_Rule extends Mage_Tax_Model_Resource_Calculation_Rule { }
Java
/* StreamHandler.java -- A class for publishing log messages to instances of java.io.OutputStream Copyright (C) 2002 Free Software Foundation, Inc. This file is part of GNU Classpath. GNU Classpath is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. GNU Classpath is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GNU Classpath; see the file COPYING. If not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions of the GNU General Public License cover the whole combination. As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ package java.util.logging; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.io.Writer; /** * A <code>StreamHandler</code> publishes <code>LogRecords</code> to * a instances of <code>java.io.OutputStream</code>. * * @author Sascha Brawer ([email protected]) */ public class StreamHandler extends Handler { private OutputStream out; private Writer writer; /** * Indicates the current state of this StreamHandler. The value * should be one of STATE_FRESH, STATE_PUBLISHED, or STATE_CLOSED. */ private int streamState = STATE_FRESH; /** * streamState having this value indicates that the StreamHandler * has been created, but the publish(LogRecord) method has not been * called yet. If the StreamHandler has been constructed without an * OutputStream, writer will be null, otherwise it is set to a * freshly created OutputStreamWriter. */ private static final int STATE_FRESH = 0; /** * streamState having this value indicates that the publish(LocRecord) * method has been called at least once. */ private static final int STATE_PUBLISHED = 1; /** * streamState having this value indicates that the close() method * has been called. */ private static final int STATE_CLOSED = 2; /** * Creates a <code>StreamHandler</code> without an output stream. * Subclasses can later use {@link * #setOutputStream(java.io.OutputStream)} to associate an output * stream with this StreamHandler. */ public StreamHandler() { this(null, null); } /** * Creates a <code>StreamHandler</code> that formats log messages * with the specified Formatter and publishes them to the specified * output stream. * * @param out the output stream to which the formatted log messages * are published. * * @param formatter the <code>Formatter</code> that will be used * to format log messages. */ public StreamHandler(OutputStream out, Formatter formatter) { this(out, "java.util.logging.StreamHandler", Level.INFO, formatter, SimpleFormatter.class); } StreamHandler( OutputStream out, String propertyPrefix, Level defaultLevel, Formatter formatter, Class defaultFormatterClass) { this.level = LogManager.getLevelProperty(propertyPrefix + ".level", defaultLevel); this.filter = (Filter) LogManager.getInstanceProperty( propertyPrefix + ".filter", /* must be instance of */ Filter.class, /* default: new instance of */ null); if (formatter != null) this.formatter = formatter; else this.formatter = (Formatter) LogManager.getInstanceProperty( propertyPrefix + ".formatter", /* must be instance of */ Formatter.class, /* default: new instance of */ defaultFormatterClass); try { String enc = LogManager.getLogManager().getProperty(propertyPrefix + ".encoding"); /* make sure enc actually is a valid encoding */ if ((enc != null) && (enc.length() > 0)) new String(new byte[0], enc); this.encoding = enc; } catch (Exception _) { } if (out != null) { try { changeWriter(out, getEncoding()); } catch (UnsupportedEncodingException uex) { /* This should never happen, since the validity of the encoding * name has been checked above. */ throw new RuntimeException(uex.getMessage()); } } } private void checkOpen() { if (streamState == STATE_CLOSED) throw new IllegalStateException(this.toString() + " has been closed"); } private void checkFresh() { checkOpen(); if (streamState != STATE_FRESH) throw new IllegalStateException("some log records have been published to " + this); } private void changeWriter(OutputStream out, String encoding) throws UnsupportedEncodingException { OutputStreamWriter writer; /* The logging API says that a null encoding means the default * platform encoding. However, java.io.OutputStreamWriter needs * another constructor for the default platform encoding, * passing null would throw an exception. */ if (encoding == null) writer = new OutputStreamWriter(out); else writer = new OutputStreamWriter(out, encoding); /* Closing the stream has side effects -- do this only after * creating a new writer has been successful. */ if ((streamState != STATE_FRESH) || (this.writer != null)) close(); this.writer = writer; this.out = out; this.encoding = encoding; streamState = STATE_FRESH; } /** * Sets the character encoding which this handler uses for publishing * log records. The encoding of a <code>StreamHandler</code> must be * set before any log records have been published. * * @param encoding the name of a character encoding, or <code>null</code> * for the default encoding. * * @throws SecurityException if a security manager exists and * the caller is not granted the permission to control the * the logging infrastructure. * * @exception IllegalStateException if any log records have been * published to this <code>StreamHandler</code> before. Please * be aware that this is a pecularity of the GNU implementation. * While the API specification indicates that it is an error * if the encoding is set after records have been published, * it does not mandate any specific behavior for that case. */ public void setEncoding(String encoding) throws SecurityException, UnsupportedEncodingException { /* The inherited implementation first checks whether the invoking * code indeed has the permission to control the logging infra- * structure, and throws a SecurityException if this was not the * case. * * Next, it verifies that the encoding is supported and throws * an UnsupportedEncodingExcpetion otherwise. Finally, it remembers * the name of the encoding. */ super.setEncoding(encoding); checkFresh(); /* If out is null, setEncoding is being called before an output * stream has been set. In that case, we need to check that the * encoding is valid, and remember it if this is the case. Since * this is exactly what the inherited implementation of * Handler.setEncoding does, we can delegate. */ if (out != null) { /* The logging API says that a null encoding means the default * platform encoding. However, java.io.OutputStreamWriter needs * another constructor for the default platform encoding, passing * null would throw an exception. */ if (encoding == null) writer = new OutputStreamWriter(out); else writer = new OutputStreamWriter(out, encoding); } } /** * Changes the output stream to which this handler publishes * logging records. * * @throws SecurityException if a security manager exists and * the caller is not granted the permission to control * the logging infrastructure. * * @throws NullPointerException if <code>out</code> * is <code>null</code>. */ protected void setOutputStream(OutputStream out) throws SecurityException { LogManager.getLogManager().checkAccess(); /* Throw a NullPointerException if out is null. */ out.getClass(); try { changeWriter(out, getEncoding()); } catch (UnsupportedEncodingException ex) { /* This seems quite unlikely to happen, unless the underlying * implementation of java.io.OutputStreamWriter changes its * mind (at runtime) about the set of supported character * encodings. */ throw new RuntimeException(ex.getMessage()); } } /** * Publishes a <code>LogRecord</code> to the associated output * stream, provided the record passes all tests for being loggable. * The <code>StreamHandler</code> will localize the message of the * log record and substitute any message parameters. * * <p>Most applications do not need to call this method directly. * Instead, they will use use a {@link Logger}, which will create * LogRecords and distribute them to registered handlers. * * <p>In case of an I/O failure, the <code>ErrorManager</code> * of this <code>Handler</code> will be informed, but the caller * of this method will not receive an exception. * * <p>If a log record is being published to a * <code>StreamHandler</code> that has been closed earlier, the Sun * J2SE 1.4 reference can be observed to silently ignore the * call. The GNU implementation, however, intentionally behaves * differently by informing the <code>ErrorManager</code> associated * with this <code>StreamHandler</code>. Since the condition * indicates a programming error, the programmer should be * informed. It also seems extremely unlikely that any application * would depend on the exact behavior in this rather obscure, * erroneous case -- especially since the API specification does not * prescribe what is supposed to happen. * * @param record the log event to be published. */ public void publish(LogRecord record) { String formattedMessage; if (!isLoggable(record)) return; if (streamState == STATE_FRESH) { try { writer.write(formatter.getHead(this)); } catch (java.io.IOException ex) { reportError(null, ex, ErrorManager.WRITE_FAILURE); return; } catch (Exception ex) { reportError(null, ex, ErrorManager.GENERIC_FAILURE); return; } streamState = STATE_PUBLISHED; } try { formattedMessage = formatter.format(record); } catch (Exception ex) { reportError(null, ex, ErrorManager.FORMAT_FAILURE); return; } try { writer.write(formattedMessage); } catch (Exception ex) { reportError(null, ex, ErrorManager.WRITE_FAILURE); } } /** * Checks whether or not a <code>LogRecord</code> would be logged * if it was passed to this <code>StreamHandler</code> for publication. * * <p>The <code>StreamHandler</code> implementation first checks * whether a writer is present and the handler's level is greater * than or equal to the severity level threshold. In a second step, * if a {@link Filter} has been installed, its {@link * Filter#isLoggable(LogRecord) isLoggable} method is * invoked. Subclasses of <code>StreamHandler</code> can override * this method to impose their own constraints. * * @param record the <code>LogRecord</code> to be checked. * * @return <code>true</code> if <code>record</code> would * be published by {@link #publish(LogRecord) publish}, * <code>false</code> if it would be discarded. * * @see #setLevel(Level) * @see #setFilter(Filter) * @see Filter#isLoggable(LogRecord) * * @throws NullPointerException if <code>record</code> is * <code>null</code>. */ public boolean isLoggable(LogRecord record) { return (writer != null) && super.isLoggable(record); } /** * Forces any data that may have been buffered to the underlying * output device. * * <p>In case of an I/O failure, the <code>ErrorManager</code> * of this <code>Handler</code> will be informed, but the caller * of this method will not receive an exception. * * <p>If a <code>StreamHandler</code> that has been closed earlier * is closed a second time, the Sun J2SE 1.4 reference can be * observed to silently ignore the call. The GNU implementation, * however, intentionally behaves differently by informing the * <code>ErrorManager</code> associated with this * <code>StreamHandler</code>. Since the condition indicates a * programming error, the programmer should be informed. It also * seems extremely unlikely that any application would depend on the * exact behavior in this rather obscure, erroneous case -- * especially since the API specification does not prescribe what is * supposed to happen. */ public void flush() { try { checkOpen(); if (writer != null) writer.flush(); } catch (Exception ex) { reportError(null, ex, ErrorManager.FLUSH_FAILURE); } } /** * Closes this <code>StreamHandler</code> after having forced any * data that may have been buffered to the underlying output * device. * * <p>As soon as <code>close</code> has been called, * a <code>Handler</code> should not be used anymore. Attempts * to publish log records, to flush buffers, or to modify the * <code>Handler</code> in any other way may throw runtime * exceptions after calling <code>close</code>.</p> * * <p>In case of an I/O failure, the <code>ErrorManager</code> * of this <code>Handler</code> will be informed, but the caller * of this method will not receive an exception.</p> * * <p>If a <code>StreamHandler</code> that has been closed earlier * is closed a second time, the Sun J2SE 1.4 reference can be * observed to silently ignore the call. The GNU implementation, * however, intentionally behaves differently by informing the * <code>ErrorManager</code> associated with this * <code>StreamHandler</code>. Since the condition indicates a * programming error, the programmer should be informed. It also * seems extremely unlikely that any application would depend on the * exact behavior in this rather obscure, erroneous case -- * especially since the API specification does not prescribe what is * supposed to happen. * * @throws SecurityException if a security manager exists and * the caller is not granted the permission to control * the logging infrastructure. */ public void close() throws SecurityException { LogManager.getLogManager().checkAccess(); try { /* Although flush also calls checkOpen, it catches * any exceptions and reports them to the ErrorManager * as flush failures. However, we want to report * a closed stream as a close failure, not as a * flush failure here. Therefore, we call checkOpen() * before flush(). */ checkOpen(); flush(); if (writer != null) { if (formatter != null) { /* Even if the StreamHandler has never published a record, * it emits head and tail upon closing. An earlier version * of the GNU Classpath implementation did not emitted * anything. However, this had caused XML log files to be * entirely empty instead of containing no log records. */ if (streamState == STATE_FRESH) writer.write(formatter.getHead(this)); if (streamState != STATE_CLOSED) writer.write(formatter.getTail(this)); } streamState = STATE_CLOSED; writer.close(); } } catch (Exception ex) { reportError(null, ex, ErrorManager.CLOSE_FAILURE); } } }
Java
.njg-tooltip{ background: rgba(0, 0, 0, 0.5); border-radius: 3px; color: #fff; font-family: sans-serif; font-size: 13px; padding: 5px 10px; padding: 5px 10px; position: absolute; top: -2000px; } .njg-overlay{ background: #fbfbfb; border-radius: 2px; border: 1px solid #ccc; color: #6d6357; font-family: Arial, sans-serif; font-family: sans-serif; font-size: 14px; height: auto; max-width: 400px; min-width: 200px; padding: 0 15px; right: 10px; top: 10px; width: auto; } .njg-metadata{ background: #fbfbfb; border-radius: 2px; border: 1px solid #ccc; color: #6d6357; display: none; font-family: Arial, sans-serif; font-family: sans-serif; font-size: 14px; height: auto; left: 10px; max-width: 500px; min-width: 200px; padding: 0 15px; top: 10px; width: auto; } .njg-node{ stroke-opacity: 0.5; stroke-width: 7px; stroke: #fff; } .njg-node:hover, .njg-node.njg-open { stroke: rgba(0, 0, 0, 0.2); } .njg-link{ cursor: pointer; stroke: #999; stroke-width: 2; stroke-opacity: 0.25; } .njg-link:hover, .njg-link.njg-open{ stroke-width: 4 !important; stroke-opacity: 0.5; }
Java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code 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. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package test.css.controls.api; import org.junit.Test; import client.test.Keywords; import client.test.Smoke; import org.junit.BeforeClass; import org.junit.Before; import test.javaclient.shared.TestBase; import static test.css.controls.ControlPage.ScrollPanes; import test.javaclient.shared.screenshots.ScreenshotUtils; /** * Generated test */ public class ScrollPanesAPICssTest extends TestBase { { ScreenshotUtils.setComparatorDistance(0.003f); } @BeforeClass public static void runUI() { test.css.controls.api.APIStylesApp.main(null); } @Before public void createPage () { ((test.css.controls.api.APIStylesApp)getApplication()).open(ScrollPanes); } /** * test ScrollPane with css: -fx-border-color */ @Test public void ScrollPanes_BORDER_COLOR() throws Exception { testAdditionalAction(ScrollPanes.name(), "BORDER-COLOR", true); } /** * test ScrollPane with css: -fx-border-width */ @Test public void ScrollPanes_BORDER_WIDTH() throws Exception { testAdditionalAction(ScrollPanes.name(), "BORDER-WIDTH", true); } /** * test ScrollPane with css: -fx-border-width-dotted */ @Test public void ScrollPanes_BORDER_WIDTH_dotted() throws Exception { testAdditionalAction(ScrollPanes.name(), "BORDER-WIDTH-dotted", true); } /** * test ScrollPane with css: -fx-border-width-dashed */ @Test public void ScrollPanes_BORDER_WIDTH_dashed() throws Exception { testAdditionalAction(ScrollPanes.name(), "BORDER-WIDTH-dashed", true); } /** * test ScrollPane with css: -fx-border-inset */ @Test public void ScrollPanes_BORDER_INSET() throws Exception { testAdditionalAction(ScrollPanes.name(), "BORDER-INSET", true); } /** * test ScrollPane with css: -fx-border-style-dashed */ @Test public void ScrollPanes_BORDER_STYLE_DASHED() throws Exception { testAdditionalAction(ScrollPanes.name(), "BORDER-STYLE-DASHED", true); } /** * test ScrollPane with css: -fx-border-style-dotted */ @Test public void ScrollPanes_BORDER_STYLE_DOTTED() throws Exception { testAdditionalAction(ScrollPanes.name(), "BORDER-STYLE-DOTTED", true); } /** * test ScrollPane with css: -fx-image-border */ @Test public void ScrollPanes_IMAGE_BORDER() throws Exception { testAdditionalAction(ScrollPanes.name(), "IMAGE-BORDER", true); } /** * test ScrollPane with css: -fx-image-border-insets */ @Test public void ScrollPanes_IMAGE_BORDER_INSETS() throws Exception { testAdditionalAction(ScrollPanes.name(), "IMAGE-BORDER-INSETS", true); } /** * test ScrollPane with css: -fx-image-border-no-repeat */ @Test public void ScrollPanes_IMAGE_BORDER_NO_REPEAT() throws Exception { testAdditionalAction(ScrollPanes.name(), "IMAGE-BORDER-NO-REPEAT", true); } /** * test ScrollPane with css: -fx-image-border-repeat-x */ @Test public void ScrollPanes_IMAGE_BORDER_REPEAT_X() throws Exception { testAdditionalAction(ScrollPanes.name(), "IMAGE-BORDER-REPEAT-X", true); } /** * test ScrollPane with css: -fx-image-border-repeat-y */ @Test public void ScrollPanes_IMAGE_BORDER_REPEAT_Y() throws Exception { testAdditionalAction(ScrollPanes.name(), "IMAGE-BORDER-REPEAT-Y", true); } /** * test ScrollPane with css: -fx-image-border-round */ @Test public void ScrollPanes_IMAGE_BORDER_ROUND() throws Exception { testAdditionalAction(ScrollPanes.name(), "IMAGE-BORDER-ROUND", true); } /** * test ScrollPane with css: -fx-image-border-space */ @Test public void ScrollPanes_IMAGE_BORDER_SPACE() throws Exception { testAdditionalAction(ScrollPanes.name(), "IMAGE-BORDER-SPACE", true); } public String getName() { return "ControlCss"; } }
Java
-- -- PacketFence SQL schema upgrade from 5.0.0 to 5.1.0 -- -- -- Setting the major/minor/sub-minor version of the DB -- SET @MAJOR_VERSION = 5; SET @MINOR_VERSION = 1; SET @SUBMINOR_VERSION = 0; -- -- The VERSION_INT to ensure proper ordering of the version in queries -- SET @VERSION_INT = @MAJOR_VERSION << 16 | @MINOR_VERSION << 8 | @SUBMINOR_VERSION; -- -- Alter Class for external_command -- ALTER TABLE class ADD `external_command` varchar(255) DEFAULT NULL; -- -- Insert new sms carrier -- INSERT INTO sms_carrier (id, name, email_pattern, created) VALUES (100119, 'Swisscom', '%[email protected]', now()), (100120, 'Orange (CH)', '%[email protected]', now()), (100121, 'Sunrise', '%[email protected]', now()); -- -- Add a column to radius_nas to order the nas list -- ALTER TABLE radius_nas ADD start_ip INT UNSIGNED DEFAULT 0, ADD end_ip INT UNSIGNED DEFAULT 0, ADD range_length INT DEFAULT 0; -- -- Table structure for table 'pf_version' -- CREATE TABLE pf_version ( `id` INT NOT NULL PRIMARY KEY, `version` VARCHAR(11) NOT NULL UNIQUE KEY); -- -- Updating to current version -- INSERT INTO pf_version (id, version) VALUES (@VERSION_INT, CONCAT_WS('.', @MAJOR_VERSION, @MINOR_VERSION, @SUBMINOR_VERSION)); -- IMPORTANT: KEEP THIS AT THE BOTTOM OF THIS FILE. -- TO BE EXECUTED AFTER EVERYTHING ELSE. CREATE DATABASE pf_graphite; use pf_graphite; GRANT ALL PRIVILEGES ON `pf_graphite`.* TO 'pf'@'%'; GRANT ALL PRIVILEGES ON `pf_graphite`.* TO 'pf'@'localhost'; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; /*!40103 SET TIME_ZONE='+00:00' */; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; -- -- Table structure for table `account_mygraph` -- DROP TABLE IF EXISTS `account_mygraph`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `account_mygraph` ( `id` int(11) NOT NULL AUTO_INCREMENT, `profile_id` int(11) NOT NULL, `name` varchar(64) NOT NULL, `url` longtext NOT NULL, PRIMARY KEY (`id`), KEY `account_mygraph_141c6eec` (`profile_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `account_profile` -- DROP TABLE IF EXISTS `account_profile`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `account_profile` ( `id` int(11) NOT NULL AUTO_INCREMENT, `user_id` int(11) NOT NULL, `history` longtext NOT NULL, `advancedUI` tinyint(1) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `user_id` (`user_id`) ) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `account_variable` -- DROP TABLE IF EXISTS `account_variable`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `account_variable` ( `id` int(11) NOT NULL AUTO_INCREMENT, `profile_id` int(11) NOT NULL, `name` varchar(64) NOT NULL, `value` varchar(64) NOT NULL, PRIMARY KEY (`id`), KEY `account_variable_141c6eec` (`profile_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `account_view` -- DROP TABLE IF EXISTS `account_view`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `account_view` ( `id` int(11) NOT NULL AUTO_INCREMENT, `profile_id` int(11) NOT NULL, `name` varchar(64) NOT NULL, PRIMARY KEY (`id`), KEY `account_view_141c6eec` (`profile_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `account_window` -- DROP TABLE IF EXISTS `account_window`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `account_window` ( `id` int(11) NOT NULL AUTO_INCREMENT, `view_id` int(11) NOT NULL, `name` varchar(64) NOT NULL, `top` int(11) NOT NULL, `left` int(11) NOT NULL, `width` int(11) NOT NULL, `height` int(11) NOT NULL, `url` longtext NOT NULL, `interval` int(11) DEFAULT NULL, PRIMARY KEY (`id`), KEY `account_window_189a3b91` (`view_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `auth_group` -- DROP TABLE IF EXISTS `auth_group`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `auth_group` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(80) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `name` (`name`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `auth_group_permissions` -- DROP TABLE IF EXISTS `auth_group_permissions`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `auth_group_permissions` ( `id` int(11) NOT NULL AUTO_INCREMENT, `group_id` int(11) NOT NULL, `permission_id` int(11) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `group_id` (`group_id`,`permission_id`), KEY `auth_group_permissions_bda51c3c` (`group_id`), KEY `auth_group_permissions_1e014c8f` (`permission_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `auth_permission` -- DROP TABLE IF EXISTS `auth_permission`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `auth_permission` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(50) NOT NULL, `content_type_id` int(11) NOT NULL, `codename` varchar(100) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `content_type_id` (`content_type_id`,`codename`), KEY `auth_permission_e4470c6e` (`content_type_id`) ) ENGINE=MyISAM AUTO_INCREMENT=46 DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `auth_user` -- DROP TABLE IF EXISTS `auth_user`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `auth_user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(30) NOT NULL, `first_name` varchar(30) NOT NULL, `last_name` varchar(30) NOT NULL, `email` varchar(75) NOT NULL, `password` varchar(128) NOT NULL, `is_staff` tinyint(1) NOT NULL, `is_active` tinyint(1) NOT NULL, `is_superuser` tinyint(1) NOT NULL, `last_login` datetime NOT NULL, `date_joined` datetime NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `username` (`username`) ) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `auth_user_groups` -- DROP TABLE IF EXISTS `auth_user_groups`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `auth_user_groups` ( `id` int(11) NOT NULL AUTO_INCREMENT, `user_id` int(11) NOT NULL, `group_id` int(11) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `user_id` (`user_id`,`group_id`), KEY `auth_user_groups_fbfc09f1` (`user_id`), KEY `auth_user_groups_bda51c3c` (`group_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `auth_user_user_permissions` -- DROP TABLE IF EXISTS `auth_user_user_permissions`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `auth_user_user_permissions` ( `id` int(11) NOT NULL AUTO_INCREMENT, `user_id` int(11) NOT NULL, `permission_id` int(11) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `user_id` (`user_id`,`permission_id`), KEY `auth_user_user_permissions_fbfc09f1` (`user_id`), KEY `auth_user_user_permissions_1e014c8f` (`permission_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `dashboard_dashboard` -- DROP TABLE IF EXISTS `dashboard_dashboard`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `dashboard_dashboard` ( `name` varchar(128) NOT NULL, `state` longtext NOT NULL, PRIMARY KEY (`name`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `dashboard_dashboard_owners` -- DROP TABLE IF EXISTS `dashboard_dashboard_owners`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `dashboard_dashboard_owners` ( `id` int(11) NOT NULL AUTO_INCREMENT, `dashboard_id` varchar(128) NOT NULL, `profile_id` int(11) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `dashboard_id` (`dashboard_id`,`profile_id`), KEY `dashboard_dashboard_owners_b26c2633` (`dashboard_id`), KEY `dashboard_dashboard_owners_141c6eec` (`profile_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `django_admin_log` -- DROP TABLE IF EXISTS `django_admin_log`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `django_admin_log` ( `id` int(11) NOT NULL AUTO_INCREMENT, `action_time` datetime NOT NULL, `user_id` int(11) NOT NULL, `content_type_id` int(11) DEFAULT NULL, `object_id` longtext, `object_repr` varchar(200) NOT NULL, `action_flag` smallint(5) unsigned NOT NULL, `change_message` longtext NOT NULL, PRIMARY KEY (`id`), KEY `django_admin_log_fbfc09f1` (`user_id`), KEY `django_admin_log_e4470c6e` (`content_type_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `django_content_type` -- DROP TABLE IF EXISTS `django_content_type`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `django_content_type` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(100) NOT NULL, `app_label` varchar(100) NOT NULL, `model` varchar(100) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `app_label` (`app_label`,`model`) ) ENGINE=MyISAM AUTO_INCREMENT=16 DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `django_session` -- DROP TABLE IF EXISTS `django_session`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `django_session` ( `session_key` varchar(40) NOT NULL, `session_data` longtext NOT NULL, `expire_date` datetime NOT NULL, PRIMARY KEY (`session_key`), KEY `django_session_c25c2c28` (`expire_date`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `events_event` -- DROP TABLE IF EXISTS `events_event`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `events_event` ( `id` int(11) NOT NULL AUTO_INCREMENT, `when` datetime NOT NULL, `what` varchar(255) NOT NULL, `data` longtext NOT NULL, `tags` varchar(255) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `tagging_tag` -- DROP TABLE IF EXISTS `tagging_tag`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `tagging_tag` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(50) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `name` (`name`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `tagging_taggeditem` -- DROP TABLE IF EXISTS `tagging_taggeditem`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `tagging_taggeditem` ( `id` int(11) NOT NULL AUTO_INCREMENT, `tag_id` int(11) NOT NULL, `content_type_id` int(11) NOT NULL, `object_id` int(10) unsigned NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `tag_id` (`tag_id`,`content_type_id`,`object_id`), KEY `tagging_taggeditem_3747b463` (`tag_id`), KEY `tagging_taggeditem_e4470c6e` (`content_type_id`), KEY `tagging_taggeditem_829e37fd` (`object_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
Java
<?php /** * @file * Contains \Drupal\Console\Command\Debug\UpdateCommand. */ namespace Drupal\Console\Command\Debug; use Drupal\Console\Command\Shared\UpdateTrait; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Drupal\Console\Core\Command\Command; use Drupal\Core\Update\UpdateRegistry; use Drupal\Console\Utils\Site; class UpdateCommand extends Command { use UpdateTrait; /** * @var Site */ protected $site; /** * @var UpdateRegistry */ protected $postUpdateRegistry; /** * DebugCommand constructor. * * @param Site $site * @param UpdateRegistry $postUpdateRegistry */ public function __construct( Site $site, UpdateRegistry $postUpdateRegistry ) { $this->site = $site; $this->postUpdateRegistry = $postUpdateRegistry; parent::__construct(); } /** * @inheritdoc */ protected function configure() { $this ->setName('debug:update') ->setDescription($this->trans('commands.debug.update.description')) ->setAliases(['du']); } /** * @inheritdoc */ protected function execute(InputInterface $input, OutputInterface $output) { $this->site->loadLegacyFile('/core/includes/update.inc'); $this->site->loadLegacyFile('/core/includes/install.inc'); drupal_load_updates(); update_fix_compatibility(); $requirements = update_check_requirements(); $severity = drupal_requirements_severity($requirements); $updates = update_get_update_list(); $postUpdates = $this->postUpdateRegistry->getPendingUpdateInformation(); $this->getIo()->newLine(); if ($severity == REQUIREMENT_ERROR || ($severity == REQUIREMENT_WARNING)) { $this->populateRequirements($requirements); } elseif (empty($updates) && empty($postUpdates)) { $this->getIo()->info($this->trans('commands.debug.update.messages.no-updates')); } else { $this->showUpdateTable($updates, $this->trans('commands.debug.update.messages.module-list')); $this->showPostUpdateTable($postUpdates, $this->trans('commands.debug.update.messages.module-list-post-update')); } } /** * @param $requirements */ private function populateRequirements($requirements) { $this->getIo()->info($this->trans('commands.debug.update.messages.requirements-error')); $tableHeader = [ $this->trans('commands.debug.update.messages.severity'), $this->trans('commands.debug.update.messages.title'), $this->trans('commands.debug.update.messages.value'), $this->trans('commands.debug.update.messages.description'), ]; $tableRows = []; foreach ($requirements as $requirement) { $minimum = in_array( $requirement['minimum schema'], [REQUIREMENT_ERROR, REQUIREMENT_WARNING] ); if ((isset($requirement['minimum schema'])) && ($minimum)) { $tableRows[] = [ $requirement['severity'], $requirement['title'], $requirement['value'], $requirement['description'], ]; } } $this->getIo()->table($tableHeader, $tableRows); } }
Java
/* This file is automatically generated. DO NOT EDIT! */ #ifndef _newfile_h #define _newfile_h off_t sf_byte (sf_file file); /*< Count the file data size (in bytes) >*/ /*------------------------------------------------------------*/ sf_file sf_tmpfile(char *format); /*< Create an temporary (rw mode) file structure. Lives within the program >*/ /*------------------------------------------------------------*/ void sf_filefresh(sf_file file); /*< used for temporary file only to recover the dataname >*/ void sf_filecopy(sf_file file, sf_file src, sf_datatype type); /*< copy the content in src->stream to file->stream >*/ void sf_tmpfileclose (sf_file file); /*< close a file and free allocated space >*/ #endif
Java
<?php /** * @package SP Page Builder * @author JoomShaper http://www.joomshaper.com * @copyright Copyright (c) 2010 - 2016 JoomShaper * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 or later */ //no direct accees defined ('_JEXEC') or die ('restricted aceess'); class SppagebuilderAddonEmpty_space extends SppagebuilderAddons{ public function render() { $class = (isset($this->addon->settings->class) && $this->addon->settings->class) ? $this->addon->settings->class : ''; return '<div class="sppb-empty-space ' . $class . ' clearfix"></div>'; } public function css() { $addon_id = '#sppb-addon-' . $this->addon->id; $gap = (isset($this->addon->settings->gap) && $this->addon->settings->gap) ? 'padding-bottom: ' . (int) $this->addon->settings->gap . 'px;': ''; if($gap) { $css = $addon_id . ' .sppb-empty-space {'; $css .= $gap; $css .= '}'; } return $css; } }
Java
/********************************************************************** * * * Voreen - The Volume Rendering Engine * * * * Created between 2005 and 2012 by The Voreen Team * * as listed in CREDITS.TXT <http://www.voreen.org> * * * * This file is part of the Voreen software package. Voreen 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. * * * * Voreen 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 * * in the file "LICENSE.txt" along with this program. * * If not, see <http://www.gnu.org/licenses/>. * * * * The authors reserve all rights not expressly granted herein. For * * non-commercial academic use see the license exception specified in * * the file "LICENSE-academic.txt". To get information about * * commercial licensing please contact the authors. * * * **********************************************************************/ #ifndef VRN_EVENTPROPERTYWIDGET_H #define VRN_EVENTPROPERTYWIDGET_H class QBoxLayout; #include "voreen/core/properties/propertywidget.h" #include <QWidget> class QCheckBox; class QComboBox; class QCheckBox; namespace voreen { class EventPropertyBase; class ModifierDetectorWidget; class KeyDetectorWidget; class EventPropertyWidget : public QWidget, public PropertyWidget { Q_OBJECT public: EventPropertyWidget(EventPropertyBase* property, QWidget* parent = 0); ~EventPropertyWidget(); virtual void setEnabled(bool enabled); virtual void setVisible(bool state); virtual void disconnect(); virtual void updateFromProperty(); public slots: void modifierChanged(Qt::KeyboardModifiers modifier); void keyChanged(int key); void buttonChanged(int button); void enabledChanged(bool enabled); void sharingChanged(bool shared); protected: void createEnabledBox(); void createSharingBox(); void createMouseWidgets(); void createKeyWidgets(); void adjustWidgetState(); QBoxLayout* layout_; EventPropertyBase* property_; QCheckBox* checkEnabled_; ModifierDetectorWidget* modifierWidget_; KeyDetectorWidget* keyWidget_; QComboBox* buttonBox_; QCheckBox* checkSharing_; bool disconnected_; }; } // namespace #endif // VRN_EVENTPROPERTYWIDGET_H
Java
<? require_once("../../lib/bd/basedatosAdo.php"); class mysreportes { var $rep; var $bd; function mysreportes() { $this->rep=""; $this->bd=new basedatosAdo(); } function sqlreporte() { $sql="select refcom as referencia, codpre as codigo_presupuestario, monimp as monto from cpimpcom order by refcom"; return $sql; } function getAncho($pos) { $anchos=array(); $anchos[0]=75; $anchos[1]=60; $anchos[2]=20; $anchos[3]=30; $anchos[4]=30; $anchos[5]=30; $anchos[6]=30; /* $anchos[7]=30; $anchos[8]=30; $anchos[9]=30; $anchos[10]=30; $anchos[11]=30;*/ return $anchos[$pos]; } function getAncho2($pos) { $anchos2=array(); $anchos2[0]=20; $anchos2[1]=20; $anchos2[2]=20; $anchos2[3]=20; $anchos2[4]=40; $anchos2[5]=30; $anchos2[6]=30; $anchos2[7]=30; $anchos2[8]=30; $anchos2[9]=30; $anchos2[10]=30; $anchos2[11]=30; return $anchos2[$pos]; } } ?>
Java
const express = require('express'); const path = require('path'); const compression = require('compression'); const webpackDevMiddleware = require('webpack-dev-middleware'); const webpackHotMiddleware = require('webpack-hot-middleware'); const webpack = require('webpack'); // Dev middleware const addDevMiddlewares = (app, options) => { const compiler = webpack(options); const middleware = webpackDevMiddleware(compiler, { noInfo: true, publicPath: options.output.publicPath, silent: true, }); app.use(middleware); app.use(webpackHotMiddleware(compiler)); // Since webpackDevMiddleware uses memory-fs internally to store build // artifacts, we use it instead const fs = middleware.fileSystem; app.get('*', (req, res) => { const file = fs.readFileSync(path.join(compiler.outputPath, 'index.html')); res.send(file.toString()); }); }; // Production middlewares const addProdMiddlewares = (app, options) => { // compression middleware compresses your server responses which makes them // smaller (applies also to assets). You can read more about that technique // and other good practices on official Express.js docs http://mxs.is/googmy app.use(compression()); app.use(options.output.publicPath, express.static(options.output.path)); app.get('*', (req, res) => res.sendFile(path.join(options.output.path, 'index.html'))); }; /** * Front-end middleware */ module.exports = (options) => { const isProd = process.env.NODE_ENV === 'production'; const app = express(); if (isProd) { addProdMiddlewares(app, options); } else { addDevMiddlewares(app, options); } return app; };
Java
import unittest from PyFoam.Basics.MatplotlibTimelines import MatplotlibTimelines theSuite=unittest.TestSuite()
Java
/* $Id: VBoxUsbRt.cpp $ */ /** @file * VBox USB R0 runtime */ /* * Copyright (C) 2011 Oracle Corporation * * This file is part of VirtualBox Open Source Edition (OSE), as * available from http://www.virtualbox.org. This file is free software; * you can redistribute it and/or modify it under the terms of the GNU * General Public License (GPL) as published by the Free Software * Foundation, in version 2 as it comes in the "COPYING" file of the * VirtualBox OSE distribution. VirtualBox OSE is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. */ #include "VBoxUsbCmn.h" #include "../cmn/VBoxUsbIdc.h" #include "../cmn/VBoxUsbTool.h" #include <VBox/usblib-win.h> #include <iprt/assert.h> #include <VBox/log.h> #define _USBD_ #define USBD_DEFAULT_PIPE_TRANSFER 0x00000008 #define VBOXUSB_MAGIC 0xABCF1423 typedef struct VBOXUSB_URB_CONTEXT { PURB pUrb; PMDL pMdlBuf; PVBOXUSBDEV_EXT pDevExt; PVOID pOut; ULONG ulTransferType; ULONG ulMagic; } VBOXUSB_URB_CONTEXT, * PVBOXUSB_URB_CONTEXT; typedef struct VBOXUSB_SETUP { uint8_t bmRequestType; uint8_t bRequest; uint16_t wValue; uint16_t wIndex; uint16_t wLength; } VBOXUSB_SETUP, *PVBOXUSB_SETUP; static bool vboxUsbRtCtxSetOwner(PVBOXUSBDEV_EXT pDevExt, PFILE_OBJECT pFObj) { bool bRc = ASMAtomicCmpXchgPtr(&pDevExt->Rt.pOwner, pFObj, NULL); if (bRc) { Log((__FUNCTION__": pDevExt (0x%x) Owner(0x%x) acquired\n", pFObj)); } else { Log((__FUNCTION__": pDevExt (0x%x) Owner(0x%x) FAILED!!\n", pFObj)); } return bRc; } static bool vboxUsbRtCtxReleaseOwner(PVBOXUSBDEV_EXT pDevExt, PFILE_OBJECT pFObj) { bool bRc = ASMAtomicCmpXchgPtr(&pDevExt->Rt.pOwner, NULL, pFObj); if (bRc) { Log((__FUNCTION__": pDevExt (0x%x) Owner(0x%x) released\n", pFObj)); } else { Log((__FUNCTION__": pDevExt (0x%x) Owner(0x%x) release: is NOT an owner\n", pFObj)); } return bRc; } static bool vboxUsbRtCtxIsOwner(PVBOXUSBDEV_EXT pDevExt, PFILE_OBJECT pFObj) { PFILE_OBJECT pOwner = (PFILE_OBJECT)ASMAtomicReadPtr((void *volatile *)(&pDevExt->Rt.pOwner)); return pOwner == pFObj; } static NTSTATUS vboxUsbRtIdcSubmit(ULONG uCtl, void *pvBuffer) { /* we just reuse the standard usb tooling for simplicity here */ NTSTATUS Status = VBoxUsbToolIoInternalCtlSendSync(g_VBoxUsbGlobals.RtIdc.pDevice, uCtl, pvBuffer, NULL); Assert(Status == STATUS_SUCCESS); return Status; } static NTSTATUS vboxUsbRtIdcInit() { UNICODE_STRING UniName; RtlInitUnicodeString(&UniName, USBMON_DEVICE_NAME_NT); NTSTATUS Status = IoGetDeviceObjectPointer(&UniName, FILE_ALL_ACCESS, &g_VBoxUsbGlobals.RtIdc.pFile, &g_VBoxUsbGlobals.RtIdc.pDevice); if (NT_SUCCESS(Status)) { VBOXUSBIDC_VERSION Version; vboxUsbRtIdcSubmit(VBOXUSBIDC_INTERNAL_IOCTL_GET_VERSION, &Version); if (NT_SUCCESS(Status)) { if (Version.u32Major == VBOXUSBIDC_VERSION_MAJOR && Version.u32Minor >= VBOXUSBIDC_VERSION_MINOR) return STATUS_SUCCESS; AssertFailed(); } else { AssertFailed(); } /* this will as well dereference the dev obj */ ObDereferenceObject(g_VBoxUsbGlobals.RtIdc.pFile); } else { AssertFailed(); } memset(&g_VBoxUsbGlobals.RtIdc, 0, sizeof (g_VBoxUsbGlobals.RtIdc)); return Status; } static VOID vboxUsbRtIdcTerm() { Assert(g_VBoxUsbGlobals.RtIdc.pFile); Assert(g_VBoxUsbGlobals.RtIdc.pDevice); ObDereferenceObject(g_VBoxUsbGlobals.RtIdc.pFile); memset(&g_VBoxUsbGlobals.RtIdc, 0, sizeof (g_VBoxUsbGlobals.RtIdc)); } static NTSTATUS vboxUsbRtIdcReportDevStart(PDEVICE_OBJECT pPDO, HVBOXUSBIDCDEV *phDev) { VBOXUSBIDC_PROXY_STARTUP Start; Start.u.pPDO = pPDO; *phDev = NULL; NTSTATUS Status = vboxUsbRtIdcSubmit(VBOXUSBIDC_INTERNAL_IOCTL_PROXY_STARTUP, &Start); Assert(Status == STATUS_SUCCESS); if (!NT_SUCCESS(Status)) return Status; *phDev = Start.u.hDev; return STATUS_SUCCESS; } static NTSTATUS vboxUsbRtIdcReportDevStop(HVBOXUSBIDCDEV hDev) { VBOXUSBIDC_PROXY_TEARDOWN Stop; Stop.hDev = hDev; NTSTATUS Status = vboxUsbRtIdcSubmit(VBOXUSBIDC_INTERNAL_IOCTL_PROXY_TEARDOWN, &Stop); Assert(Status == STATUS_SUCCESS); return Status; } DECLHIDDEN(NTSTATUS) vboxUsbRtGlobalsInit() { return vboxUsbRtIdcInit(); } DECLHIDDEN(VOID) vboxUsbRtGlobalsTerm() { vboxUsbRtIdcTerm(); } DECLHIDDEN(NTSTATUS) vboxUsbRtInit(PVBOXUSBDEV_EXT pDevExt) { RtlZeroMemory(&pDevExt->Rt, sizeof (pDevExt->Rt)); NTSTATUS Status = IoRegisterDeviceInterface(pDevExt->pPDO, &GUID_CLASS_VBOXUSB, NULL, /* IN PUNICODE_STRING ReferenceString OPTIONAL */ &pDevExt->Rt.IfName); Assert(Status == STATUS_SUCCESS); if (NT_SUCCESS(Status)) { Status = vboxUsbRtIdcReportDevStart(pDevExt->pPDO, &pDevExt->Rt.hMonDev); Assert(Status == STATUS_SUCCESS); if (NT_SUCCESS(Status)) { Assert(pDevExt->Rt.hMonDev); return STATUS_SUCCESS; } NTSTATUS tmpStatus = IoSetDeviceInterfaceState(&pDevExt->Rt.IfName, FALSE); Assert(tmpStatus == STATUS_SUCCESS); if (NT_SUCCESS(tmpStatus)) { RtlFreeUnicodeString(&pDevExt->Rt.IfName); } } return Status; } /** * Free cached USB device/configuration descriptors * * @param pDevExt USB DevExt pointer */ static void vboxUsbRtFreeCachedDescriptors(PVBOXUSBDEV_EXT pDevExt) { if (pDevExt->Rt.devdescr) { vboxUsbMemFree(pDevExt->Rt.devdescr); pDevExt->Rt.devdescr = NULL; } for (ULONG i = 0; i < VBOXUSBRT_MAX_CFGS; ++i) { if (pDevExt->Rt.cfgdescr[i]) { vboxUsbMemFree(pDevExt->Rt.cfgdescr[i]); pDevExt->Rt.cfgdescr[i] = NULL; } } } /** * Free per-device interface info * * @param pDevExt USB DevExt pointer * @param fAbortPipes If true, also abort any open pipes */ static void vboxUsbRtFreeInterfaces(PVBOXUSBDEV_EXT pDevExt, BOOLEAN fAbortPipes) { unsigned i; unsigned j; /* * Free old interface info */ if (pDevExt->Rt.pVBIfaceInfo) { for (i=0;i<pDevExt->Rt.uNumInterfaces;i++) { if (pDevExt->Rt.pVBIfaceInfo[i].pInterfaceInfo) { if (fAbortPipes) { for(j=0; j<pDevExt->Rt.pVBIfaceInfo[i].pInterfaceInfo->NumberOfPipes; j++) { Log(("Aborting Pipe %d handle %x address %x\n", j, pDevExt->Rt.pVBIfaceInfo[i].pInterfaceInfo->Pipes[j].PipeHandle, pDevExt->Rt.pVBIfaceInfo[i].pInterfaceInfo->Pipes[j].EndpointAddress)); VBoxUsbToolPipeClear(pDevExt->pLowerDO, pDevExt->Rt.pVBIfaceInfo[i].pInterfaceInfo->Pipes[j].PipeHandle, FALSE); } } vboxUsbMemFree(pDevExt->Rt.pVBIfaceInfo[i].pInterfaceInfo); } pDevExt->Rt.pVBIfaceInfo[i].pInterfaceInfo = NULL; if (pDevExt->Rt.pVBIfaceInfo[i].pPipeInfo) vboxUsbMemFree(pDevExt->Rt.pVBIfaceInfo[i].pPipeInfo); pDevExt->Rt.pVBIfaceInfo[i].pPipeInfo = NULL; } vboxUsbMemFree(pDevExt->Rt.pVBIfaceInfo); pDevExt->Rt.pVBIfaceInfo = NULL; } } DECLHIDDEN(VOID) vboxUsbRtClear(PVBOXUSBDEV_EXT pDevExt) { vboxUsbRtFreeCachedDescriptors(pDevExt); vboxUsbRtFreeInterfaces(pDevExt, FALSE); } DECLHIDDEN(NTSTATUS) vboxUsbRtRm(PVBOXUSBDEV_EXT pDevExt) { if (!pDevExt->Rt.IfName.Buffer) return STATUS_SUCCESS; NTSTATUS Status = vboxUsbRtIdcReportDevStop(pDevExt->Rt.hMonDev); Assert(Status == STATUS_SUCCESS); Status = IoSetDeviceInterfaceState(&pDevExt->Rt.IfName, FALSE); Assert(Status == STATUS_SUCCESS); if (NT_SUCCESS(Status)) { RtlFreeUnicodeString(&pDevExt->Rt.IfName); pDevExt->Rt.IfName.Buffer = NULL; } return Status; } DECLHIDDEN(NTSTATUS) vboxUsbRtStart(PVBOXUSBDEV_EXT pDevExt) { NTSTATUS Status = IoSetDeviceInterfaceState(&pDevExt->Rt.IfName, TRUE); Assert(Status == STATUS_SUCCESS); return Status; } static NTSTATUS vboxUsbRtCacheDescriptors(PVBOXUSBDEV_EXT pDevExt) { NTSTATUS Status = STATUS_INSUFFICIENT_RESOURCES; // uint32_t uTotalLength; // unsigned i; /* Read device descriptor */ Assert(!pDevExt->Rt.devdescr); pDevExt->Rt.devdescr = (PUSB_DEVICE_DESCRIPTOR)vboxUsbMemAlloc(sizeof (USB_DEVICE_DESCRIPTOR)); if (pDevExt->Rt.devdescr) { memset(pDevExt->Rt.devdescr, 0, sizeof (USB_DEVICE_DESCRIPTOR)); Status = VBoxUsbToolGetDescriptor(pDevExt->pLowerDO, pDevExt->Rt.devdescr, sizeof (USB_DEVICE_DESCRIPTOR), USB_DEVICE_DESCRIPTOR_TYPE, 0, 0, RT_INDEFINITE_WAIT); if (NT_SUCCESS(Status)) { Assert(pDevExt->Rt.devdescr->bNumConfigurations > 0); PUSB_CONFIGURATION_DESCRIPTOR pDr = (PUSB_CONFIGURATION_DESCRIPTOR)vboxUsbMemAlloc(sizeof (USB_CONFIGURATION_DESCRIPTOR)); Assert(pDr); if (pDr) { UCHAR i = 0; for (; i < pDevExt->Rt.devdescr->bNumConfigurations; ++i) { Status = VBoxUsbToolGetDescriptor(pDevExt->pLowerDO, pDr, sizeof (USB_CONFIGURATION_DESCRIPTOR), USB_CONFIGURATION_DESCRIPTOR_TYPE, i, 0, RT_INDEFINITE_WAIT); if (!NT_SUCCESS(Status)) { break; } USHORT uTotalLength = pDr->wTotalLength; pDevExt->Rt.cfgdescr[i] = (PUSB_CONFIGURATION_DESCRIPTOR)vboxUsbMemAlloc(uTotalLength); if (!pDevExt->Rt.cfgdescr[i]) { Status = STATUS_INSUFFICIENT_RESOURCES; break; } Status = VBoxUsbToolGetDescriptor(pDevExt->pLowerDO, pDevExt->Rt.cfgdescr[i], uTotalLength, USB_CONFIGURATION_DESCRIPTOR_TYPE, i, 0, RT_INDEFINITE_WAIT); if (!NT_SUCCESS(Status)) { break; } } vboxUsbMemFree(pDr); if (NT_SUCCESS(Status)) return Status; /* recources will be freed in vboxUsbRtFreeCachedDescriptors below */ } } vboxUsbRtFreeCachedDescriptors(pDevExt); } /* shoud be only on fail here */ Assert(!NT_SUCCESS(Status)); return Status; } static NTSTATUS vboxUsbRtDispatchClaimDevice(PVBOXUSBDEV_EXT pDevExt, PIRP pIrp) { PIO_STACK_LOCATION pSl = IoGetCurrentIrpStackLocation(pIrp); PFILE_OBJECT pFObj = pSl->FileObject; PUSBSUP_CLAIMDEV pDev = (PUSBSUP_CLAIMDEV)pIrp->AssociatedIrp.SystemBuffer; ULONG cbOut = 0; NTSTATUS Status = STATUS_SUCCESS; do { if (!pFObj) { AssertFailed(); Status = STATUS_INVALID_PARAMETER; break; } if ( !pDev || pSl->Parameters.DeviceIoControl.InputBufferLength != sizeof (*pDev) || pSl->Parameters.DeviceIoControl.OutputBufferLength != sizeof (*pDev)) { AssertFailed(); Status = STATUS_INVALID_PARAMETER; break; } if (!vboxUsbRtCtxSetOwner(pDevExt, pFObj)) { AssertFailed(); pDev->fClaimed = false; cbOut = sizeof (*pDev); break; } vboxUsbRtFreeCachedDescriptors(pDevExt); Status = vboxUsbRtCacheDescriptors(pDevExt); if (NT_SUCCESS(Status)) { pDev->fClaimed = true; cbOut = sizeof (*pDev); } } while (0); Assert(Status != STATUS_PENDING); VBoxDrvToolIoComplete(pIrp, Status, cbOut); vboxUsbDdiStateRelease(pDevExt); return Status; } static NTSTATUS vboxUsbRtDispatchReleaseDevice(PVBOXUSBDEV_EXT pDevExt, PIRP pIrp) { PIO_STACK_LOCATION pSl = IoGetCurrentIrpStackLocation(pIrp); PFILE_OBJECT pFObj = pSl->FileObject; NTSTATUS Status= STATUS_SUCCESS; if (vboxUsbRtCtxIsOwner(pDevExt, pFObj)) { vboxUsbRtFreeCachedDescriptors(pDevExt); bool bRc = vboxUsbRtCtxReleaseOwner(pDevExt, pFObj); Assert(bRc); } else { AssertFailed(); Status = STATUS_ACCESS_DENIED; } VBoxDrvToolIoComplete(pIrp, STATUS_SUCCESS, 0); vboxUsbDdiStateRelease(pDevExt); return STATUS_SUCCESS; } static NTSTATUS vboxUsbRtGetDeviceDescription(PVBOXUSBDEV_EXT pDevExt) { NTSTATUS Status = STATUS_INSUFFICIENT_RESOURCES; PUSB_DEVICE_DESCRIPTOR pDr = (PUSB_DEVICE_DESCRIPTOR)vboxUsbMemAllocZ(sizeof (USB_DEVICE_DESCRIPTOR)); if (pDr) { Status = VBoxUsbToolGetDescriptor(pDevExt->pLowerDO, pDr, sizeof(*pDr), USB_DEVICE_DESCRIPTOR_TYPE, 0, 0, RT_INDEFINITE_WAIT); if (NT_SUCCESS(Status)) { pDevExt->Rt.idVendor = pDr->idVendor; pDevExt->Rt.idProduct = pDr->idProduct; pDevExt->Rt.bcdDevice = pDr->bcdDevice; pDevExt->Rt.szSerial[0] = 0; if (pDr->iSerialNumber #ifdef DEBUG || pDr->iProduct || pDr->iManufacturer #endif ) { int langId; Status = VBoxUsbToolGetLangID(pDevExt->pLowerDO, &langId, RT_INDEFINITE_WAIT); if (NT_SUCCESS(Status)) { Status = VBoxUsbToolGetStringDescriptorA(pDevExt->pLowerDO, pDevExt->Rt.szSerial, sizeof (pDevExt->Rt.szSerial), pDr->iSerialNumber, langId, RT_INDEFINITE_WAIT); } else { Status = STATUS_SUCCESS; } } } vboxUsbMemFree(pDr); } return Status; } static NTSTATUS vboxUsbRtDispatchGetDevice(PVBOXUSBDEV_EXT pDevExt, PIRP pIrp) { PIO_STACK_LOCATION pSl = IoGetCurrentIrpStackLocation(pIrp); PUSBSUP_GETDEV pDev = (PUSBSUP_GETDEV)pIrp->AssociatedIrp.SystemBuffer; NTSTATUS Status = STATUS_SUCCESS; ULONG cbOut = 0; /* don't check for owner since this request is allowed for non-owners as well */ if (pDev && pSl->Parameters.DeviceIoControl.InputBufferLength == sizeof (*pDev) && pSl->Parameters.DeviceIoControl.OutputBufferLength == sizeof (*pDev)) { Status = VBoxUsbToolGetDeviceSpeed(pDevExt->pLowerDO, &pDevExt->Rt.fIsHighSpeed); if (NT_SUCCESS(Status)) { pDev->hDevice = pDevExt->Rt.hMonDev; pDev->fAttached = true; pDev->fHiSpeed = pDevExt->Rt.fIsHighSpeed; cbOut = sizeof (*pDev); } } else { Status = STATUS_INVALID_PARAMETER; } Assert(Status != STATUS_PENDING); VBoxDrvToolIoComplete(pIrp, Status, cbOut); vboxUsbDdiStateRelease(pDevExt); return Status; } static NTSTATUS vboxUsbRtDispatchUsbReset(PVBOXUSBDEV_EXT pDevExt, PIRP pIrp) { PIO_STACK_LOCATION pSl = IoGetCurrentIrpStackLocation(pIrp); PFILE_OBJECT pFObj = pSl->FileObject; PUSBSUP_GETDEV pDev = (PUSBSUP_GETDEV)pIrp->AssociatedIrp.SystemBuffer; NTSTATUS Status = STATUS_SUCCESS; do { if (!pFObj) { AssertFailed(); Status = STATUS_INVALID_PARAMETER; break; } if (!vboxUsbRtCtxIsOwner(pDevExt, pFObj)) { AssertFailed(); Status = STATUS_ACCESS_DENIED; break; } if (pIrp->AssociatedIrp.SystemBuffer || pSl->Parameters.DeviceIoControl.InputBufferLength || pSl->Parameters.DeviceIoControl.OutputBufferLength) { AssertFailed(); Status = STATUS_INVALID_PARAMETER; break; } Status = VBoxUsbToolIoInternalCtlSendSync(pDevExt->pLowerDO, IOCTL_INTERNAL_USB_RESET_PORT, NULL, NULL); Assert(NT_SUCCESS(Status)); } while (0); Assert(Status != STATUS_PENDING); VBoxDrvToolIoComplete(pIrp, Status, 0); vboxUsbDdiStateRelease(pDevExt); return Status; } static PUSB_CONFIGURATION_DESCRIPTOR vboxUsbRtFindConfigDesc(PVBOXUSBDEV_EXT pDevExt, uint8_t uConfiguration) { PUSB_CONFIGURATION_DESCRIPTOR pCfgDr = NULL; for (ULONG i = 0; i < VBOXUSBRT_MAX_CFGS; ++i) { if (pDevExt->Rt.cfgdescr[i]) { if (pDevExt->Rt.cfgdescr[i]->bConfigurationValue == uConfiguration) { pCfgDr = pDevExt->Rt.cfgdescr[i]; break; } } } return pCfgDr; } static NTSTATUS vboxUsbRtSetConfig(PVBOXUSBDEV_EXT pDevExt, uint8_t uConfiguration) { PURB pUrb = NULL; NTSTATUS Status = STATUS_SUCCESS; uint32_t i; if (!uConfiguration) { pUrb = VBoxUsbToolUrbAllocZ(URB_FUNCTION_SELECT_CONFIGURATION, sizeof (struct _URB_SELECT_CONFIGURATION)); if(!pUrb) { AssertMsgFailed((__FUNCTION__": VBoxUsbToolUrbAlloc failed\n")); return STATUS_INSUFFICIENT_RESOURCES; } vboxUsbRtFreeInterfaces(pDevExt, TRUE); pUrb->UrbSelectConfiguration.ConfigurationDescriptor = NULL; Status = VBoxUsbToolUrbPost(pDevExt->pLowerDO, pUrb, RT_INDEFINITE_WAIT); if(NT_SUCCESS(Status) && USBD_SUCCESS(pUrb->UrbHeader.Status)) { pDevExt->Rt.hConfiguration = pUrb->UrbSelectConfiguration.ConfigurationHandle; pDevExt->Rt.uConfigValue = uConfiguration; } else { AssertMsgFailed((__FUNCTION__": VBoxUsbToolUrbPost failed Status (0x%x), usb Status (0x%x)\n", Status, pUrb->UrbHeader.Status)); } VBoxUsbToolUrbFree(pUrb); return Status; } PUSB_CONFIGURATION_DESCRIPTOR pCfgDr = vboxUsbRtFindConfigDesc(pDevExt, uConfiguration); if (!pCfgDr) { AssertMsgFailed((__FUNCTION__": VBoxUSBFindConfigDesc did not find cfg (%d)\n", uConfiguration)); return STATUS_INVALID_PARAMETER; } PUSBD_INTERFACE_LIST_ENTRY pIfLe = (PUSBD_INTERFACE_LIST_ENTRY)vboxUsbMemAllocZ((pCfgDr->bNumInterfaces + 1) * sizeof(USBD_INTERFACE_LIST_ENTRY)); if (!pIfLe) { AssertMsgFailed((__FUNCTION__": vboxUsbMemAllocZ for pIfLe failed\n")); return STATUS_INSUFFICIENT_RESOURCES; } for (i = 0; i < pCfgDr->bNumInterfaces; i++) { pIfLe[i].InterfaceDescriptor = USBD_ParseConfigurationDescriptorEx(pCfgDr, pCfgDr, i, 0, -1, -1, -1); if (!pIfLe[i].InterfaceDescriptor) { AssertMsgFailed((__FUNCTION__": interface %d not found\n", i)); Status = STATUS_INVALID_PARAMETER; break; } } if (NT_SUCCESS(Status)) { pUrb = USBD_CreateConfigurationRequestEx(pCfgDr, pIfLe); if (pUrb) { Status = VBoxUsbToolUrbPost(pDevExt->pLowerDO, pUrb, RT_INDEFINITE_WAIT); if (NT_SUCCESS(Status) && USBD_SUCCESS(pUrb->UrbHeader.Status)) { vboxUsbRtFreeInterfaces(pDevExt, FALSE); pDevExt->Rt.hConfiguration = pUrb->UrbSelectConfiguration.ConfigurationHandle; pDevExt->Rt.uConfigValue = uConfiguration; pDevExt->Rt.uNumInterfaces = pCfgDr->bNumInterfaces; pDevExt->Rt.pVBIfaceInfo = (VBOXUSB_IFACE_INFO*)vboxUsbMemAllocZ(pDevExt->Rt.uNumInterfaces * sizeof (VBOXUSB_IFACE_INFO)); if (pDevExt->Rt.pVBIfaceInfo) { Assert(NT_SUCCESS(Status)); for (i = 0; i < pDevExt->Rt.uNumInterfaces; i++) { uint32_t uTotalIfaceInfoLength = sizeof (struct _URB_SELECT_INTERFACE) + ((pIfLe[i].Interface->NumberOfPipes > 0) ? (pIfLe[i].Interface->NumberOfPipes - 1) : 0) * sizeof(USBD_PIPE_INFORMATION); pDevExt->Rt.pVBIfaceInfo[i].pInterfaceInfo = (PUSBD_INTERFACE_INFORMATION)vboxUsbMemAlloc(uTotalIfaceInfoLength); if (!pDevExt->Rt.pVBIfaceInfo[i].pInterfaceInfo) { AssertMsgFailed((__FUNCTION__": vboxUsbMemAlloc failed\n")); Status = STATUS_INSUFFICIENT_RESOURCES; break; } if (pIfLe[i].Interface->NumberOfPipes > 0) { pDevExt->Rt.pVBIfaceInfo[i].pPipeInfo = (VBOXUSB_PIPE_INFO *)vboxUsbMemAlloc(pIfLe[i].Interface->NumberOfPipes * sizeof(VBOXUSB_PIPE_INFO)); if (!pDevExt->Rt.pVBIfaceInfo[i].pPipeInfo) { AssertMsgFailed((__FUNCTION__": vboxUsbMemAlloc failed\n")); Status = STATUS_NO_MEMORY; break; } } else { pDevExt->Rt.pVBIfaceInfo[i].pPipeInfo = NULL; } *pDevExt->Rt.pVBIfaceInfo[i].pInterfaceInfo = *pIfLe[i].Interface; for (ULONG j = 0; j < pIfLe[i].Interface->NumberOfPipes; j++) { pDevExt->Rt.pVBIfaceInfo[i].pInterfaceInfo->Pipes[j] = pIfLe[i].Interface->Pipes[j]; pDevExt->Rt.pVBIfaceInfo[i].pPipeInfo[j].EndpointAddress = pIfLe[i].Interface->Pipes[j].EndpointAddress; pDevExt->Rt.pVBIfaceInfo[i].pPipeInfo[j].NextScheduledFrame = 0; } } // if (NT_SUCCESS(Status)) // { // // } } else { AssertMsgFailed((__FUNCTION__": vboxUsbMemAllocZ failed\n")); Status = STATUS_NO_MEMORY; } } else { AssertMsgFailed((__FUNCTION__": VBoxUsbToolUrbPost failed Status (0x%x), usb Status (0x%x)\n", Status, pUrb->UrbHeader.Status)); } ExFreePool(pUrb); } else { AssertMsgFailed((__FUNCTION__": USBD_CreateConfigurationRequestEx failed\n")); Status = STATUS_INSUFFICIENT_RESOURCES; } } vboxUsbMemFree(pIfLe); return Status; } static NTSTATUS vboxUsbRtDispatchUsbSetConfig(PVBOXUSBDEV_EXT pDevExt, PIRP pIrp) { PIO_STACK_LOCATION pSl = IoGetCurrentIrpStackLocation(pIrp); PFILE_OBJECT pFObj = pSl->FileObject; PUSBSUP_SET_CONFIG pCfg = (PUSBSUP_SET_CONFIG)pIrp->AssociatedIrp.SystemBuffer; NTSTATUS Status = STATUS_SUCCESS; do { if (!pFObj) { AssertFailed(); Status = STATUS_INVALID_PARAMETER; break; } if (!vboxUsbRtCtxIsOwner(pDevExt, pFObj)) { AssertFailed(); Status = STATUS_ACCESS_DENIED; break; } if ( !pCfg || pSl->Parameters.DeviceIoControl.InputBufferLength != sizeof (*pCfg) || pSl->Parameters.DeviceIoControl.OutputBufferLength != 0) { AssertMsgFailed((__FUNCTION__": STATUS_INVALID_PARAMETER\n")); Status = STATUS_INVALID_PARAMETER; break; } Status = vboxUsbRtSetConfig(pDevExt, pCfg->bConfigurationValue); } while (0); Assert(Status != STATUS_PENDING); VBoxDrvToolIoComplete(pIrp, Status, 0); vboxUsbDdiStateRelease(pDevExt); return Status; } static NTSTATUS vboxUsbRtSetInterface(PVBOXUSBDEV_EXT pDevExt, uint32_t InterfaceNumber, int AlternateSetting) { if (!pDevExt->Rt.uConfigValue) { AssertMsgFailed((__FUNCTION__": Can't select an interface without an active configuration\n")); return STATUS_INVALID_PARAMETER; } if (InterfaceNumber >= pDevExt->Rt.uNumInterfaces) { AssertMsgFailed((__FUNCTION__": InterfaceNumber %d too high!!\n", InterfaceNumber)); return STATUS_INVALID_PARAMETER; } PUSB_CONFIGURATION_DESCRIPTOR pCfgDr = vboxUsbRtFindConfigDesc(pDevExt, pDevExt->Rt.uConfigValue); if (!pCfgDr) { AssertMsgFailed((__FUNCTION__": configuration %d not found!!\n", pDevExt->Rt.uConfigValue)); return STATUS_INVALID_PARAMETER; } PUSB_INTERFACE_DESCRIPTOR pIfDr = USBD_ParseConfigurationDescriptorEx(pCfgDr, pCfgDr, InterfaceNumber, AlternateSetting, -1, -1, -1); if (!pIfDr) { AssertMsgFailed((__FUNCTION__": invalid interface %d or alternate setting %d\n", InterfaceNumber, AlternateSetting)); return STATUS_UNSUCCESSFUL; } USHORT uUrbSize = GET_SELECT_INTERFACE_REQUEST_SIZE(pIfDr->bNumEndpoints); ULONG uTotalIfaceInfoLength = GET_USBD_INTERFACE_SIZE(pIfDr->bNumEndpoints); NTSTATUS Status = STATUS_SUCCESS; PURB pUrb = VBoxUsbToolUrbAllocZ(0, uUrbSize); if (!pUrb) { AssertMsgFailed((__FUNCTION__": VBoxUsbToolUrbAlloc failed\n")); return STATUS_NO_MEMORY; } /* * Free old interface and pipe info, allocate new again */ if (pDevExt->Rt.pVBIfaceInfo[InterfaceNumber].pInterfaceInfo) { /* Clear pipes associated with the interface, else Windows may hang. */ for(ULONG i = 0; i < pDevExt->Rt.pVBIfaceInfo[InterfaceNumber].pInterfaceInfo->NumberOfPipes; i++) { VBoxUsbToolPipeClear(pDevExt->pLowerDO, pDevExt->Rt.pVBIfaceInfo[InterfaceNumber].pInterfaceInfo->Pipes[i].PipeHandle, FALSE); } vboxUsbMemFree(pDevExt->Rt.pVBIfaceInfo[InterfaceNumber].pInterfaceInfo); } if (pDevExt->Rt.pVBIfaceInfo[InterfaceNumber].pPipeInfo) { vboxUsbMemFree(pDevExt->Rt.pVBIfaceInfo[InterfaceNumber].pPipeInfo); } pDevExt->Rt.pVBIfaceInfo[InterfaceNumber].pInterfaceInfo = (PUSBD_INTERFACE_INFORMATION)vboxUsbMemAlloc(uTotalIfaceInfoLength); if (pDevExt->Rt.pVBIfaceInfo[InterfaceNumber].pInterfaceInfo) { if (pIfDr->bNumEndpoints > 0) { pDevExt->Rt.pVBIfaceInfo[InterfaceNumber].pPipeInfo = (VBOXUSB_PIPE_INFO*)vboxUsbMemAlloc(pIfDr->bNumEndpoints * sizeof(VBOXUSB_PIPE_INFO)); if (!pDevExt->Rt.pVBIfaceInfo[InterfaceNumber].pPipeInfo) { AssertMsgFailed(("VBoxUSBSetInterface: ExAllocatePool failed!\n")); Status = STATUS_NO_MEMORY; } } else { pDevExt->Rt.pVBIfaceInfo[InterfaceNumber].pPipeInfo = NULL; } if (NT_SUCCESS(Status)) { UsbBuildSelectInterfaceRequest(pUrb, uUrbSize, pDevExt->Rt.hConfiguration, InterfaceNumber, AlternateSetting); pUrb->UrbSelectInterface.Interface.Length = GET_USBD_INTERFACE_SIZE(pIfDr->bNumEndpoints); Status = VBoxUsbToolUrbPost(pDevExt->pLowerDO, pUrb, RT_INDEFINITE_WAIT); if (NT_SUCCESS(Status) && USBD_SUCCESS(pUrb->UrbHeader.Status)) { USBD_INTERFACE_INFORMATION *pIfInfo = &pUrb->UrbSelectInterface.Interface; memcpy(pDevExt->Rt.pVBIfaceInfo[InterfaceNumber].pInterfaceInfo, pIfInfo, GET_USBD_INTERFACE_SIZE(pIfDr->bNumEndpoints)); Assert(pIfInfo->NumberOfPipes == pIfDr->bNumEndpoints); for(ULONG i = 0; i < pIfInfo->NumberOfPipes; i++) { pDevExt->Rt.pVBIfaceInfo[InterfaceNumber].pInterfaceInfo->Pipes[i] = pIfInfo->Pipes[i]; pDevExt->Rt.pVBIfaceInfo[InterfaceNumber].pPipeInfo[i].EndpointAddress = pIfInfo->Pipes[i].EndpointAddress; pDevExt->Rt.pVBIfaceInfo[InterfaceNumber].pPipeInfo[i].NextScheduledFrame = 0; } } else { AssertMsgFailed((__FUNCTION__": VBoxUsbToolUrbPost failed Status (0x%x) usb Status (0x%x)\n", Status, pUrb->UrbHeader.Status)); } } } else { AssertMsgFailed(("VBoxUSBSetInterface: ExAllocatePool failed!\n")); Status = STATUS_NO_MEMORY; } VBoxUsbToolUrbFree(pUrb); return Status; } static NTSTATUS vboxUsbRtDispatchUsbSelectInterface(PVBOXUSBDEV_EXT pDevExt, PIRP pIrp) { PIO_STACK_LOCATION pSl = IoGetCurrentIrpStackLocation(pIrp); PFILE_OBJECT pFObj = pSl->FileObject; PUSBSUP_SELECT_INTERFACE pIf = (PUSBSUP_SELECT_INTERFACE)pIrp->AssociatedIrp.SystemBuffer; NTSTATUS Status; do { if (!pFObj) { AssertFailed(); Status = STATUS_INVALID_PARAMETER; break; } if (!vboxUsbRtCtxIsOwner(pDevExt, pFObj)) { AssertFailed(); Status = STATUS_ACCESS_DENIED; break; } if ( !pIf || pSl->Parameters.DeviceIoControl.InputBufferLength != sizeof (*pIf) || pSl->Parameters.DeviceIoControl.OutputBufferLength != 0) { AssertMsgFailed((__FUNCTION__": STATUS_INVALID_PARAMETER\n")); Status = STATUS_INVALID_PARAMETER; break; } Status = vboxUsbRtSetInterface(pDevExt, pIf->bInterfaceNumber, pIf->bAlternateSetting); } while (0); Assert(Status != STATUS_PENDING); VBoxDrvToolIoComplete(pIrp, Status, 0); vboxUsbDdiStateRelease(pDevExt); return Status; } static HANDLE vboxUsbRtGetPipeHandle(PVBOXUSBDEV_EXT pDevExt, uint32_t EndPointAddress) { for (ULONG i = 0; i < pDevExt->Rt.uNumInterfaces; i++) { for (ULONG j = 0; j < pDevExt->Rt.pVBIfaceInfo[i].pInterfaceInfo->NumberOfPipes; j++) { /* Note that bit 7 determines pipe direction, but is still significant * because endpoints may be numbered like 0x01, 0x81, 0x02, 0x82 etc. */ if (pDevExt->Rt.pVBIfaceInfo[i].pInterfaceInfo->Pipes[j].EndpointAddress == EndPointAddress) return pDevExt->Rt.pVBIfaceInfo[i].pInterfaceInfo->Pipes[j].PipeHandle; } } return 0; } static VBOXUSB_PIPE_INFO* vboxUsbRtGetPipeInfo(PVBOXUSBDEV_EXT pDevExt, uint32_t EndPointAddress) { for (ULONG i = 0; i < pDevExt->Rt.uNumInterfaces; i++) { for (ULONG j = 0; j < pDevExt->Rt.pVBIfaceInfo[i].pInterfaceInfo->NumberOfPipes; j++) { if (pDevExt->Rt.pVBIfaceInfo[i].pPipeInfo[j].EndpointAddress == EndPointAddress) return &pDevExt->Rt.pVBIfaceInfo[i].pPipeInfo[j]; } } return NULL; } static NTSTATUS vboxUsbRtClearEndpoint(PVBOXUSBDEV_EXT pDevExt, uint32_t EndPointAddress, bool fReset) { NTSTATUS Status = VBoxUsbToolPipeClear(pDevExt->pLowerDO, vboxUsbRtGetPipeHandle(pDevExt, EndPointAddress), fReset); if (!NT_SUCCESS(Status)) { AssertMsgFailed((__FUNCTION__": VBoxUsbToolPipeClear failed Status (0x%x)\n", Status)); } return Status; } static NTSTATUS vboxUsbRtDispatchUsbClearEndpoint(PVBOXUSBDEV_EXT pDevExt, PIRP pIrp) { PIO_STACK_LOCATION pSl = IoGetCurrentIrpStackLocation(pIrp); PFILE_OBJECT pFObj = pSl->FileObject; PUSBSUP_CLEAR_ENDPOINT pCe = (PUSBSUP_CLEAR_ENDPOINT)pIrp->AssociatedIrp.SystemBuffer; NTSTATUS Status; do { if (!pFObj) { AssertFailed(); Status = STATUS_INVALID_PARAMETER; break; } if (!vboxUsbRtCtxIsOwner(pDevExt, pFObj)) { AssertFailed(); Status = STATUS_ACCESS_DENIED; break; } if ( !pCe || pSl->Parameters.DeviceIoControl.InputBufferLength != sizeof (*pCe) || pSl->Parameters.DeviceIoControl.OutputBufferLength != 0) { AssertMsgFailed((__FUNCTION__": STATUS_INVALID_PARAMETER\n")); Status = STATUS_INVALID_PARAMETER; break; } Status = vboxUsbRtClearEndpoint(pDevExt, pCe->bEndpoint, TRUE); } while (0); Assert(Status != STATUS_PENDING); VBoxDrvToolIoComplete(pIrp, Status, 0); vboxUsbDdiStateRelease(pDevExt); return Status; } static NTSTATUS vboxUsbRtDispatchUsbAbortEndpoint(PVBOXUSBDEV_EXT pDevExt, PIRP pIrp) { PIO_STACK_LOCATION pSl = IoGetCurrentIrpStackLocation(pIrp); PFILE_OBJECT pFObj = pSl->FileObject; PUSBSUP_CLEAR_ENDPOINT pCe = (PUSBSUP_CLEAR_ENDPOINT)pIrp->AssociatedIrp.SystemBuffer; NTSTATUS Status; do { if (!pFObj) { AssertFailed(); Status = STATUS_INVALID_PARAMETER; break; } if (!vboxUsbRtCtxIsOwner(pDevExt, pFObj)) { AssertFailed(); Status = STATUS_ACCESS_DENIED; break; } if ( !pCe || pSl->Parameters.DeviceIoControl.InputBufferLength != sizeof (*pCe) || pSl->Parameters.DeviceIoControl.OutputBufferLength != 0) { AssertMsgFailed((__FUNCTION__": STATUS_INVALID_PARAMETER\n")); Status = STATUS_INVALID_PARAMETER; break; } Status = vboxUsbRtClearEndpoint(pDevExt, pCe->bEndpoint, FALSE); } while (0); Assert(Status != STATUS_PENDING); VBoxDrvToolIoComplete(pIrp, Status, 0); vboxUsbDdiStateRelease(pDevExt); return Status; } static NTSTATUS vboxUsbRtUrbSendCompletion(PDEVICE_OBJECT pDevObj, IRP *pIrp, void *pvContext) { if (!pvContext) { AssertMsgFailed((__FUNCTION__": context is NULL\n")); pIrp->IoStatus.Information = 0; return STATUS_CONTINUE_COMPLETION; } PVBOXUSB_URB_CONTEXT pContext = (PVBOXUSB_URB_CONTEXT)pvContext; if (pContext->ulMagic != VBOXUSB_MAGIC) { AssertMsgFailed((__FUNCTION__": Invalid context magic\n")); pIrp->IoStatus.Information = 0; return STATUS_CONTINUE_COMPLETION; } PURB pUrb = pContext->pUrb; PMDL pMdlBuf = pContext->pMdlBuf; PUSBSUP_URB pUrbInfo = (PUSBSUP_URB)pContext->pOut; PVBOXUSBDEV_EXT pDevExt = pContext->pDevExt; if (!pUrb || !pMdlBuf || !pUrbInfo | !pDevExt) { AssertMsgFailed((__FUNCTION__": Invalid args\n")); if (pDevExt) vboxUsbDdiStateRelease(pDevExt); pIrp->IoStatus.Information = 0; return STATUS_CONTINUE_COMPLETION; } NTSTATUS Status = pIrp->IoStatus.Status; if (Status == STATUS_SUCCESS) { switch(pUrb->UrbHeader.Status) { case USBD_STATUS_CRC: pUrbInfo->error = USBSUP_XFER_CRC; break; case USBD_STATUS_SUCCESS: pUrbInfo->error = USBSUP_XFER_OK; break; case USBD_STATUS_STALL_PID: pUrbInfo->error = USBSUP_XFER_STALL; break; case USBD_STATUS_INVALID_URB_FUNCTION: case USBD_STATUS_INVALID_PARAMETER: AssertMsgFailed((__FUNCTION__": sw error, urb Status (0x%x)\n", pUrb->UrbHeader.Status)); case USBD_STATUS_DEV_NOT_RESPONDING: default: pUrbInfo->error = USBSUP_XFER_DNR; break; } switch(pContext->ulTransferType) { case USBSUP_TRANSFER_TYPE_CTRL: case USBSUP_TRANSFER_TYPE_MSG: pUrbInfo->len = pUrb->UrbControlTransfer.TransferBufferLength; if (pContext->ulTransferType == USBSUP_TRANSFER_TYPE_MSG) { /* QUSB_TRANSFER_TYPE_MSG is a control transfer, but it is special * the first 8 bytes of the buffer is the setup packet so the real * data length is therefore urb->len - 8 */ pUrbInfo->len += sizeof (pUrb->UrbControlTransfer.SetupPacket); } break; case USBSUP_TRANSFER_TYPE_ISOC: pUrbInfo->len = pUrb->UrbIsochronousTransfer.TransferBufferLength; break; case USBSUP_TRANSFER_TYPE_BULK: case USBSUP_TRANSFER_TYPE_INTR: if (pUrbInfo->dir == USBSUP_DIRECTION_IN && pUrbInfo->error == USBSUP_XFER_OK && !(pUrbInfo->flags & USBSUP_FLAG_SHORT_OK) && pUrbInfo->len > pUrb->UrbBulkOrInterruptTransfer.TransferBufferLength ) { /* If we don't use the USBD_SHORT_TRANSFER_OK flag, the returned buffer lengths are * wrong for short transfers (always a multiple of max packet size?). So we just figure * out if this was a data underrun on our own. */ pUrbInfo->error = USBSUP_XFER_UNDERRUN; } pUrbInfo->len = pUrb->UrbBulkOrInterruptTransfer.TransferBufferLength; break; default: break; } } else { pUrbInfo->len = 0; Log((__FUNCTION__": URB failed Status (0x%x) urb Status (0x%x)\n", Status, pUrb->UrbHeader.Status)); #ifdef DEBUG switch(pContext->ulTransferType) { case USBSUP_TRANSFER_TYPE_CTRL: case USBSUP_TRANSFER_TYPE_MSG: LogRel(("Ctrl/Msg length=%d\n", pUrb->UrbControlTransfer.TransferBufferLength)); break; case USBSUP_TRANSFER_TYPE_ISOC: LogRel(("ISOC length=%d\n", pUrb->UrbIsochronousTransfer.TransferBufferLength)); break; case USBSUP_TRANSFER_TYPE_BULK: case USBSUP_TRANSFER_TYPE_INTR: LogRel(("BULK/INTR length=%d\n", pUrb->UrbBulkOrInterruptTransfer.TransferBufferLength)); break; } #endif switch(pUrb->UrbHeader.Status) { case USBD_STATUS_CRC: pUrbInfo->error = USBSUP_XFER_CRC; Status = STATUS_SUCCESS; break; case USBD_STATUS_STALL_PID: pUrbInfo->error = USBSUP_XFER_STALL; Status = STATUS_SUCCESS; break; case USBD_STATUS_DEV_NOT_RESPONDING: pUrbInfo->error = USBSUP_XFER_DNR; Status = STATUS_SUCCESS; break; case ((USBD_STATUS)0xC0010000L): // USBD_STATUS_CANCELED - too bad usbdi.h and usb.h aren't consistent! // TODO: What the heck are we really supposed to do here? pUrbInfo->error = USBSUP_XFER_STALL; Status = STATUS_SUCCESS; break; case USBD_STATUS_BAD_START_FRAME: // This one really shouldn't happen case USBD_STATUS_ISOCH_REQUEST_FAILED: pUrbInfo->error = USBSUP_XFER_NAC; Status = STATUS_SUCCESS; break; default: AssertMsgFailed((__FUNCTION__": err Status (0x%x) (0x%x)\n", Status, pUrb->UrbHeader.Status)); pUrbInfo->error = USBSUP_XFER_DNR; Status = STATUS_SUCCESS; break; } } // For isochronous transfers, always update the individual packets if (pContext->ulTransferType == USBSUP_TRANSFER_TYPE_ISOC) { Assert(pUrbInfo->numIsoPkts == pUrb->UrbIsochronousTransfer.NumberOfPackets); for (ULONG i = 0; i < pUrbInfo->numIsoPkts; ++i) { Assert(pUrbInfo->aIsoPkts[i].off == pUrb->UrbIsochronousTransfer.IsoPacket[i].Offset); pUrbInfo->aIsoPkts[i].cb = (uint16_t)pUrb->UrbIsochronousTransfer.IsoPacket[i].Length; switch (pUrb->UrbIsochronousTransfer.IsoPacket[i].Status) { case USBD_STATUS_SUCCESS: pUrbInfo->aIsoPkts[i].stat = USBSUP_XFER_OK; break; case USBD_STATUS_NOT_ACCESSED: pUrbInfo->aIsoPkts[i].stat = USBSUP_XFER_NAC; break; default: pUrbInfo->aIsoPkts[i].stat = USBSUP_XFER_STALL; break; } } } MmUnlockPages(pMdlBuf); IoFreeMdl(pMdlBuf); vboxUsbMemFree(pContext); vboxUsbDdiStateRelease(pDevExt); Assert(pIrp->IoStatus.Status != STATUS_IO_TIMEOUT); pIrp->IoStatus.Information = sizeof(*pUrbInfo); pIrp->IoStatus.Status = Status; return STATUS_CONTINUE_COMPLETION; } static NTSTATUS vboxUsbRtUrbSend(PVBOXUSBDEV_EXT pDevExt, PIRP pIrp, PUSBSUP_URB pUrbInfo) { NTSTATUS Status = STATUS_SUCCESS; PVBOXUSB_URB_CONTEXT pContext = NULL; PMDL pMdlBuf = NULL; ULONG cbUrb; Assert(pUrbInfo); if (pUrbInfo->type == USBSUP_TRANSFER_TYPE_ISOC) { Assert(pUrbInfo->numIsoPkts <= 8); cbUrb = GET_ISO_URB_SIZE(pUrbInfo->numIsoPkts); } else cbUrb = sizeof (URB); do { pContext = (PVBOXUSB_URB_CONTEXT)vboxUsbMemAllocZ(cbUrb + sizeof (VBOXUSB_URB_CONTEXT)); if (!pContext) { AssertMsgFailed((__FUNCTION__": vboxUsbMemAlloc failed\n")); Status = STATUS_INSUFFICIENT_RESOURCES; break; } PURB pUrb = (PURB)(pContext + 1); HANDLE hPipe = NULL; if (pUrbInfo->ep) { hPipe = vboxUsbRtGetPipeHandle(pDevExt, pUrbInfo->ep | ((pUrbInfo->dir == USBSUP_DIRECTION_IN) ? 0x80 : 0x00)); if (!hPipe) { AssertMsgFailed((__FUNCTION__": vboxUsbRtGetPipeHandle failed for endpoint (0x%x)\n", pUrbInfo->ep)); Status = STATUS_INVALID_PARAMETER; break; } } pMdlBuf = IoAllocateMdl(pUrbInfo->buf, (ULONG)pUrbInfo->len, FALSE, FALSE, NULL); if (!pMdlBuf) { AssertMsgFailed((__FUNCTION__": IoAllocateMdl failed for buffer (0x%p) length (%d)\n", pUrbInfo->buf, pUrbInfo->len)); Status = STATUS_INSUFFICIENT_RESOURCES; break; } __try { MmProbeAndLockPages(pMdlBuf, KernelMode, IoModifyAccess); } __except(EXCEPTION_EXECUTE_HANDLER) { Status = GetExceptionCode(); IoFreeMdl(pMdlBuf); pMdlBuf = NULL; AssertMsgFailed((__FUNCTION__": Exception Code (0x%x)\n", Status)); break; } /* For some reason, passing a MDL in the URB does not work reliably. Notably * the iPhone when used with iTunes fails. */ PVOID pBuffer = MmGetSystemAddressForMdlSafe(pMdlBuf, NormalPagePriority); if (!pBuffer) { AssertMsgFailed((__FUNCTION__": MmGetSystemAddressForMdlSafe failed\n")); Status = STATUS_INSUFFICIENT_RESOURCES; break; } switch (pUrbInfo->type) { case USBSUP_TRANSFER_TYPE_CTRL: case USBSUP_TRANSFER_TYPE_MSG: { pUrb->UrbHeader.Function = URB_FUNCTION_CONTROL_TRANSFER; pUrb->UrbHeader.Length = sizeof (struct _URB_CONTROL_TRANSFER); pUrb->UrbControlTransfer.PipeHandle = hPipe; pUrb->UrbControlTransfer.TransferBufferLength = (ULONG)pUrbInfo->len; pUrb->UrbControlTransfer.TransferFlags = ((pUrbInfo->dir == USBSUP_DIRECTION_IN) ? USBD_TRANSFER_DIRECTION_IN : USBD_TRANSFER_DIRECTION_OUT); pUrb->UrbControlTransfer.UrbLink = 0; if (!hPipe) pUrb->UrbControlTransfer.TransferFlags |= USBD_DEFAULT_PIPE_TRANSFER; if (pUrbInfo->type == USBSUP_TRANSFER_TYPE_MSG) { /* QUSB_TRANSFER_TYPE_MSG is a control transfer, but it is special * the first 8 bytes of the buffer is the setup packet so the real * data length is therefore pUrb->len - 8 */ PVBOXUSB_SETUP pSetup = (PVBOXUSB_SETUP)pUrb->UrbControlTransfer.SetupPacket; memcpy(pUrb->UrbControlTransfer.SetupPacket, pBuffer, min(sizeof (pUrb->UrbControlTransfer.SetupPacket), pUrbInfo->len)); if (pUrb->UrbControlTransfer.TransferBufferLength <= sizeof (pUrb->UrbControlTransfer.SetupPacket)) pUrb->UrbControlTransfer.TransferBufferLength = 0; else pUrb->UrbControlTransfer.TransferBufferLength -= sizeof (pUrb->UrbControlTransfer.SetupPacket); pUrb->UrbControlTransfer.TransferBuffer = (uint8_t *)pBuffer + sizeof(pUrb->UrbControlTransfer.SetupPacket); pUrb->UrbControlTransfer.TransferBufferMDL = 0; pUrb->UrbControlTransfer.TransferFlags |= USBD_SHORT_TRANSFER_OK; } else { pUrb->UrbControlTransfer.TransferBuffer = 0; pUrb->UrbControlTransfer.TransferBufferMDL = pMdlBuf; } break; } case USBSUP_TRANSFER_TYPE_ISOC: { Assert(pUrbInfo->dir == USBSUP_DIRECTION_IN || pUrbInfo->type == USBSUP_TRANSFER_TYPE_BULK); Assert(hPipe); VBOXUSB_PIPE_INFO *pPipeInfo = vboxUsbRtGetPipeInfo(pDevExt, pUrbInfo->ep | ((pUrbInfo->dir == USBSUP_DIRECTION_IN) ? 0x80 : 0x00)); if (pPipeInfo == NULL) { /* Can happen if the isoc request comes in too early or late. */ AssertMsgFailed((__FUNCTION__": pPipeInfo not found\n")); Status = STATUS_INVALID_PARAMETER; break; } pUrb->UrbHeader.Function = URB_FUNCTION_ISOCH_TRANSFER; pUrb->UrbHeader.Length = (USHORT)cbUrb; pUrb->UrbIsochronousTransfer.PipeHandle = hPipe; pUrb->UrbIsochronousTransfer.TransferBufferLength = (ULONG)pUrbInfo->len; pUrb->UrbIsochronousTransfer.TransferBufferMDL = 0; pUrb->UrbIsochronousTransfer.TransferBuffer = pBuffer; pUrb->UrbIsochronousTransfer.TransferFlags = ((pUrbInfo->dir == USBSUP_DIRECTION_IN) ? USBD_TRANSFER_DIRECTION_IN : USBD_TRANSFER_DIRECTION_OUT); pUrb->UrbIsochronousTransfer.TransferFlags |= USBD_SHORT_TRANSFER_OK; // May be implied already pUrb->UrbIsochronousTransfer.NumberOfPackets = pUrbInfo->numIsoPkts; pUrb->UrbIsochronousTransfer.ErrorCount = 0; pUrb->UrbIsochronousTransfer.UrbLink = 0; Assert(pUrbInfo->numIsoPkts == pUrb->UrbIsochronousTransfer.NumberOfPackets); for (ULONG i = 0; i < pUrbInfo->numIsoPkts; ++i) { pUrb->UrbIsochronousTransfer.IsoPacket[i].Offset = pUrbInfo->aIsoPkts[i].off; pUrb->UrbIsochronousTransfer.IsoPacket[i].Length = pUrbInfo->aIsoPkts[i].cb; } /* We have to schedule the URBs ourselves. There is an ASAP flag but * that can only be reliably used after pipe creation/reset, ie. it's * almost completely useless. */ ULONG iFrame, iStartFrame; VBoxUsbToolCurrentFrame(pDevExt->pLowerDO, pIrp, &iFrame); iFrame += 2; iStartFrame = pPipeInfo->NextScheduledFrame; if ((iFrame < iStartFrame) || (iStartFrame > iFrame + 512)) iFrame = iStartFrame; pPipeInfo->NextScheduledFrame = iFrame + pUrbInfo->numIsoPkts; pUrb->UrbIsochronousTransfer.StartFrame = iFrame; break; } case USBSUP_TRANSFER_TYPE_BULK: case USBSUP_TRANSFER_TYPE_INTR: { Assert(pUrbInfo->dir != USBSUP_DIRECTION_SETUP); Assert(pUrbInfo->dir == USBSUP_DIRECTION_IN || pUrbInfo->type == USBSUP_TRANSFER_TYPE_BULK); Assert(hPipe); pUrb->UrbHeader.Function = URB_FUNCTION_BULK_OR_INTERRUPT_TRANSFER; pUrb->UrbHeader.Length = sizeof (struct _URB_BULK_OR_INTERRUPT_TRANSFER); pUrb->UrbBulkOrInterruptTransfer.PipeHandle = hPipe; pUrb->UrbBulkOrInterruptTransfer.TransferBufferLength = (ULONG)pUrbInfo->len; pUrb->UrbBulkOrInterruptTransfer.TransferBufferMDL = 0; pUrb->UrbBulkOrInterruptTransfer.TransferBuffer = pBuffer; pUrb->UrbBulkOrInterruptTransfer.TransferFlags = ((pUrbInfo->dir == USBSUP_DIRECTION_IN) ? USBD_TRANSFER_DIRECTION_IN : USBD_TRANSFER_DIRECTION_OUT); if (pUrb->UrbBulkOrInterruptTransfer.TransferFlags & USBD_TRANSFER_DIRECTION_IN) pUrb->UrbBulkOrInterruptTransfer.TransferFlags |= (USBD_SHORT_TRANSFER_OK); pUrb->UrbBulkOrInterruptTransfer.UrbLink = 0; break; } default: { AssertFailed(); Status = STATUS_INVALID_PARAMETER; break; } } if (!NT_SUCCESS(Status)) { break; } pContext->pDevExt = pDevExt; pContext->pMdlBuf = pMdlBuf; pContext->pUrb = pUrb; pContext->pOut = pUrbInfo; pContext->ulTransferType = pUrbInfo->type; pContext->ulMagic = VBOXUSB_MAGIC; PIO_STACK_LOCATION pSl = IoGetNextIrpStackLocation(pIrp); pSl->MajorFunction = IRP_MJ_INTERNAL_DEVICE_CONTROL; pSl->Parameters.DeviceIoControl.IoControlCode = IOCTL_INTERNAL_USB_SUBMIT_URB; pSl->Parameters.Others.Argument1 = pUrb; pSl->Parameters.Others.Argument2 = NULL; IoSetCompletionRoutine(pIrp, vboxUsbRtUrbSendCompletion, pContext, TRUE, TRUE, TRUE); IoMarkIrpPending(pIrp); Status = IoCallDriver(pDevExt->pLowerDO, pIrp); AssertMsg(NT_SUCCESS(Status), (__FUNCTION__": IoCallDriver failed Status (0x%x)\n", Status)); return STATUS_PENDING; } while (0); Assert(!NT_SUCCESS(Status)); if (pMdlBuf) { MmUnlockPages(pMdlBuf); IoFreeMdl(pMdlBuf); } if (pContext) vboxUsbMemFree(pContext); VBoxDrvToolIoComplete(pIrp, Status, 0); vboxUsbDdiStateRelease(pDevExt); return Status; } static NTSTATUS vboxUsbRtDispatchSendUrb(PVBOXUSBDEV_EXT pDevExt, PIRP pIrp) { PIO_STACK_LOCATION pSl = IoGetCurrentIrpStackLocation(pIrp); PFILE_OBJECT pFObj = pSl->FileObject; PUSBSUP_URB pUrbInfo = (PUSBSUP_URB)pIrp->AssociatedIrp.SystemBuffer; NTSTATUS Status; do { if (!pFObj) { AssertFailed(); Status = STATUS_INVALID_PARAMETER; break; } if (!vboxUsbRtCtxIsOwner(pDevExt, pFObj)) { AssertFailed(); Status = STATUS_ACCESS_DENIED; break; } if ( !pUrbInfo || pSl->Parameters.DeviceIoControl.InputBufferLength != sizeof (*pUrbInfo) || pSl->Parameters.DeviceIoControl.OutputBufferLength != sizeof (*pUrbInfo)) { AssertMsgFailed((__FUNCTION__": STATUS_INVALID_PARAMETER\n")); Status = STATUS_INVALID_PARAMETER; break; } return vboxUsbRtUrbSend(pDevExt, pIrp, pUrbInfo); } while (0); Assert(Status != STATUS_PENDING); VBoxDrvToolIoComplete(pIrp, Status, 0); vboxUsbDdiStateRelease(pDevExt); return Status; } static NTSTATUS vboxUsbRtDispatchIsOperational(PVBOXUSBDEV_EXT pDevExt, PIRP pIrp) { VBoxDrvToolIoComplete(pIrp, STATUS_SUCCESS, 0); vboxUsbDdiStateRelease(pDevExt); return STATUS_SUCCESS; } static NTSTATUS vboxUsbRtDispatchGetVersion(PVBOXUSBDEV_EXT pDevExt, PIRP pIrp) { PIO_STACK_LOCATION pSl = IoGetCurrentIrpStackLocation(pIrp); PUSBSUP_VERSION pVer= (PUSBSUP_VERSION)pIrp->AssociatedIrp.SystemBuffer; NTSTATUS Status = STATUS_SUCCESS; if (pVer && pSl->Parameters.DeviceIoControl.InputBufferLength == 0 && pSl->Parameters.DeviceIoControl.OutputBufferLength == sizeof (*pVer)) { pVer->u32Major = USBDRV_MAJOR_VERSION; pVer->u32Minor = USBDRV_MINOR_VERSION; } else { AssertMsgFailed((__FUNCTION__": STATUS_INVALID_PARAMETER\n")); Status = STATUS_INVALID_PARAMETER; } Assert(Status != STATUS_PENDING); VBoxDrvToolIoComplete(pIrp, Status, sizeof (*pVer)); vboxUsbDdiStateRelease(pDevExt); return Status; } static NTSTATUS vboxUsbRtDispatchDefault(PVBOXUSBDEV_EXT pDevExt, PIRP pIrp) { VBoxDrvToolIoComplete(pIrp, STATUS_INVALID_DEVICE_REQUEST, 0); vboxUsbDdiStateRelease(pDevExt); return STATUS_INVALID_DEVICE_REQUEST; } DECLHIDDEN(NTSTATUS) vboxUsbRtCreate(PVBOXUSBDEV_EXT pDevExt, PIRP pIrp) { PIO_STACK_LOCATION pSl = IoGetCurrentIrpStackLocation(pIrp); PFILE_OBJECT pFObj = pSl->FileObject; if (!pFObj) { AssertFailed(); return STATUS_INVALID_PARAMETER; } return STATUS_SUCCESS; } DECLHIDDEN(NTSTATUS) vboxUsbRtClose(PVBOXUSBDEV_EXT pDevExt, PIRP pIrp) { PIO_STACK_LOCATION pSl = IoGetCurrentIrpStackLocation(pIrp); PFILE_OBJECT pFObj = pSl->FileObject; Assert(pFObj); vboxUsbRtCtxReleaseOwner(pDevExt, pFObj); return STATUS_SUCCESS; } DECLHIDDEN(NTSTATUS) vboxUsbRtDispatch(PVBOXUSBDEV_EXT pDevExt, PIRP pIrp) { PIO_STACK_LOCATION pSl = IoGetCurrentIrpStackLocation(pIrp); switch (pSl->Parameters.DeviceIoControl.IoControlCode) { case SUPUSB_IOCTL_USB_CLAIM_DEVICE: { return vboxUsbRtDispatchClaimDevice(pDevExt, pIrp); } case SUPUSB_IOCTL_USB_RELEASE_DEVICE: { return vboxUsbRtDispatchReleaseDevice(pDevExt, pIrp); } case SUPUSB_IOCTL_GET_DEVICE: { return vboxUsbRtDispatchGetDevice(pDevExt, pIrp); } case SUPUSB_IOCTL_USB_RESET: { return vboxUsbRtDispatchUsbReset(pDevExt, pIrp); } case SUPUSB_IOCTL_USB_SET_CONFIG: { return vboxUsbRtDispatchUsbSetConfig(pDevExt, pIrp); } case SUPUSB_IOCTL_USB_SELECT_INTERFACE: { return vboxUsbRtDispatchUsbSelectInterface(pDevExt, pIrp); } case SUPUSB_IOCTL_USB_CLEAR_ENDPOINT: { return vboxUsbRtDispatchUsbClearEndpoint(pDevExt, pIrp); } case SUPUSB_IOCTL_USB_ABORT_ENDPOINT: { return vboxUsbRtDispatchUsbAbortEndpoint(pDevExt, pIrp); } case SUPUSB_IOCTL_SEND_URB: { return vboxUsbRtDispatchSendUrb(pDevExt, pIrp); } case SUPUSB_IOCTL_IS_OPERATIONAL: { return vboxUsbRtDispatchIsOperational(pDevExt, pIrp); } case SUPUSB_IOCTL_GET_VERSION: { return vboxUsbRtDispatchGetVersion(pDevExt, pIrp); } default: { return vboxUsbRtDispatchDefault(pDevExt, pIrp); } } }
Java
#ifndef _ASM_X86_ELF_H #define _ASM_X86_ELF_H /* * ELF register definitions.. */ #include <asm/ptrace.h> #include <asm/user.h> #include <asm/auxvec.h> typedef unsigned long elf_greg_t; #define ELF_NGREG (sizeof(struct user_regs_struct) / sizeof(elf_greg_t)) typedef elf_greg_t elf_gregset_t[ELF_NGREG]; typedef struct user_i387_struct elf_fpregset_t; #ifdef __i386__ typedef struct user_fxsr_struct elf_fpxregset_t; #define R_386_NONE 0 #define R_386_32 1 #define R_386_PC32 2 #define R_386_GOT32 3 #define R_386_PLT32 4 #define R_386_COPY 5 #define R_386_GLOB_DAT 6 #define R_386_JMP_SLOT 7 #define R_386_RELATIVE 8 #define R_386_GOTOFF 9 #define R_386_GOTPC 10 #define R_386_NUM 11 /* * These are used to set parameters in the core dumps. */ #define ELF_CLASS ELFCLASS32 #define ELF_DATA ELFDATA2LSB #define ELF_ARCH EM_386 #else /* x86-64 relocation types */ #define R_X86_64_NONE 0 /* No reloc */ #define R_X86_64_64 1 /* Direct 64 bit */ #define R_X86_64_PC32 2 /* PC relative 32 bit signed */ #define R_X86_64_GOT32 3 /* 32 bit GOT entry */ #define R_X86_64_PLT32 4 /* 32 bit PLT address */ #define R_X86_64_COPY 5 /* Copy symbol at runtime */ #define R_X86_64_GLOB_DAT 6 /* Create GOT entry */ #define R_X86_64_JUMP_SLOT 7 /* Create PLT entry */ #define R_X86_64_RELATIVE 8 /* Adjust by program base */ #define R_X86_64_GOTPCREL 9 /* 32 bit signed pc relative offset to GOT */ #define R_X86_64_32 10 /* Direct 32 bit zero extended */ #define R_X86_64_32S 11 /* Direct 32 bit sign extended */ #define R_X86_64_16 12 /* Direct 16 bit zero extended */ #define R_X86_64_PC16 13 /* 16 bit sign extended pc relative */ #define R_X86_64_8 14 /* Direct 8 bit sign extended */ #define R_X86_64_PC8 15 /* 8 bit sign extended pc relative */ #define R_X86_64_NUM 16 /* * These are used to set parameters in the core dumps. */ #define ELF_CLASS ELFCLASS64 #define ELF_DATA ELFDATA2LSB #define ELF_ARCH EM_X86_64 #endif #include <asm/vdso.h> extern unsigned int vdso_enabled; /* * This is used to ensure we don't load something for the wrong architecture. */ #define elf_check_arch_ia32(x) \ (((x)->e_machine == EM_386) || ((x)->e_machine == EM_486)) #include <asm/processor.h> #include <asm/system.h> #ifdef CONFIG_X86_32 #include <asm/desc.h> #define elf_check_arch(x) elf_check_arch_ia32(x) /* SVR4/i386 ABI (pages 3-31, 3-32) says that when the program starts %edx contains a pointer to a function which might be registered using `atexit'. This provides a mean for the dynamic linker to call DT_FINI functions for shared libraries that have been loaded before the code runs. A value of 0 tells we have no such handler. We might as well make sure everything else is cleared too (except for %esp), just to make things more deterministic. */ #define ELF_PLAT_INIT(_r, load_addr) \ do { \ _r->bx = 0; _r->cx = 0; _r->dx = 0; \ _r->si = 0; _r->di = 0; _r->bp = 0; \ _r->ax = 0; \ } while (0) /* * regs is struct pt_regs, pr_reg is elf_gregset_t (which is * now struct_user_regs, they are different) */ #define ELF_CORE_COPY_REGS_COMMON(pr_reg, regs) \ do { \ pr_reg[0] = regs->bx; \ pr_reg[1] = regs->cx; \ pr_reg[2] = regs->dx; \ pr_reg[3] = regs->si; \ pr_reg[4] = regs->di; \ pr_reg[5] = regs->bp; \ pr_reg[6] = regs->ax; \ pr_reg[7] = regs->ds & 0xffff; \ pr_reg[8] = regs->es & 0xffff; \ pr_reg[9] = regs->fs & 0xffff; \ pr_reg[11] = regs->orig_ax; \ pr_reg[12] = regs->ip; \ pr_reg[13] = regs->cs & 0xffff; \ pr_reg[14] = regs->flags; \ pr_reg[15] = regs->sp; \ pr_reg[16] = regs->ss & 0xffff; \ } while (0); #define ELF_CORE_COPY_REGS(pr_reg, regs) \ do { \ ELF_CORE_COPY_REGS_COMMON(pr_reg, regs);\ pr_reg[10] = get_user_gs(regs); \ } while (0); #define ELF_CORE_COPY_KERNEL_REGS(pr_reg, regs) \ do { \ ELF_CORE_COPY_REGS_COMMON(pr_reg, regs);\ savesegment(gs, pr_reg[10]); \ } while (0); #define ELF_PLATFORM (utsname()->machine) #define set_personality_64bit() do { } while (0) #else /* CONFIG_X86_32 */ /* * This is used to ensure we don't load something for the wrong architecture. */ #define elf_check_arch(x) \ ((x)->e_machine == EM_X86_64) #define compat_elf_check_arch(x) elf_check_arch_ia32(x) static inline void elf_common_init(struct thread_struct *t, struct pt_regs *regs, const u16 ds) { regs->ax = regs->bx = regs->cx = regs->dx = 0; regs->si = regs->di = regs->bp = 0; regs->r8 = regs->r9 = regs->r10 = regs->r11 = 0; regs->r12 = regs->r13 = regs->r14 = regs->r15 = 0; t->fs = t->gs = 0; t->fsindex = t->gsindex = 0; t->ds = t->es = ds; } #define ELF_PLAT_INIT(_r, load_addr) \ elf_common_init(&current->thread, _r, 0) #define COMPAT_ELF_PLAT_INIT(regs, load_addr) \ elf_common_init(&current->thread, regs, __USER_DS) void start_thread_ia32(struct pt_regs *regs, u32 new_ip, u32 new_sp); #define compat_start_thread start_thread_ia32 void set_personality_ia32(void); #define COMPAT_SET_PERSONALITY(ex) set_personality_ia32() #define COMPAT_ELF_PLATFORM ("i686") /* * regs is struct pt_regs, pr_reg is elf_gregset_t (which is * now struct_user_regs, they are different). Assumes current is the process * getting dumped. */ #define ELF_CORE_COPY_REGS(pr_reg, regs) \ do { \ unsigned v; \ (pr_reg)[0] = (regs)->r15; \ (pr_reg)[1] = (regs)->r14; \ (pr_reg)[2] = (regs)->r13; \ (pr_reg)[3] = (regs)->r12; \ (pr_reg)[4] = (regs)->bp; \ (pr_reg)[5] = (regs)->bx; \ (pr_reg)[6] = (regs)->r11; \ (pr_reg)[7] = (regs)->r10; \ (pr_reg)[8] = (regs)->r9; \ (pr_reg)[9] = (regs)->r8; \ (pr_reg)[10] = (regs)->ax; \ (pr_reg)[11] = (regs)->cx; \ (pr_reg)[12] = (regs)->dx; \ (pr_reg)[13] = (regs)->si; \ (pr_reg)[14] = (regs)->di; \ (pr_reg)[15] = (regs)->orig_ax; \ (pr_reg)[16] = (regs)->ip; \ (pr_reg)[17] = (regs)->cs; \ (pr_reg)[18] = (regs)->flags; \ (pr_reg)[19] = (regs)->sp; \ (pr_reg)[20] = (regs)->ss; \ (pr_reg)[21] = current->thread.fs; \ (pr_reg)[22] = current->thread.gs; \ asm("movl %%ds,%0" : "=r" (v)); (pr_reg)[23] = v; \ asm("movl %%es,%0" : "=r" (v)); (pr_reg)[24] = v; \ asm("movl %%fs,%0" : "=r" (v)); (pr_reg)[25] = v; \ asm("movl %%gs,%0" : "=r" (v)); (pr_reg)[26] = v; \ } while (0); /* I'm not sure if we can use '-' here */ #define ELF_PLATFORM ("x86_64") extern void set_personality_64bit(void); extern unsigned int sysctl_vsyscall32; extern int force_personality32; #endif /* !CONFIG_X86_32 */ #define CORE_DUMP_USE_REGSET #define ELF_EXEC_PAGESIZE 4096 /* This is the location that an ET_DYN program is loaded if exec'ed. Typical use of this is to invoke "./ld.so someprog" to test out a new version of the loader. We need to make sure that it is out of the way of the program that it will "exec", and that there is sufficient room for the brk. */ #ifdef CONFIG_PAX_SEGMEXEC #define ELF_ET_DYN_BASE ((current->mm->pax_flags & MF_PAX_SEGMEXEC) ? SEGMEXEC_TASK_SIZE/3*2 : TASK_SIZE/3*2) #else #define ELF_ET_DYN_BASE (TASK_SIZE / 3 * 2) #endif #ifdef CONFIG_PAX_ASLR #ifdef CONFIG_X86_32 #define PAX_ELF_ET_DYN_BASE 0x10000000UL #define PAX_DELTA_MMAP_LEN (current->mm->pax_flags & MF_PAX_SEGMEXEC ? 15 : 16) #define PAX_DELTA_STACK_LEN (current->mm->pax_flags & MF_PAX_SEGMEXEC ? 15 : 16) #else #define PAX_ELF_ET_DYN_BASE 0x400000UL #define PAX_DELTA_MMAP_LEN ((test_thread_flag(TIF_IA32)) ? 16 : TASK_SIZE_MAX_SHIFT - PAGE_SHIFT - 3) #define PAX_DELTA_STACK_LEN ((test_thread_flag(TIF_IA32)) ? 16 : TASK_SIZE_MAX_SHIFT - PAGE_SHIFT - 3) #endif #endif /* This yields a mask that user programs can use to figure out what instruction set this CPU supports. This could be done in user space, but it's not easy, and we've already done it here. */ #define ELF_HWCAP (boot_cpu_data.x86_capability[0]) /* This yields a string that ld.so will use to load implementation specific libraries for optimization. This is more specific in intent than poking at uname or /proc/cpuinfo. For the moment, we have only optimizations for the Intel generations, but that could change... */ #define SET_PERSONALITY(ex) set_personality_64bit() /* * An executable for which elf_read_implies_exec() returns TRUE will * have the READ_IMPLIES_EXEC personality flag set automatically. */ #define elf_read_implies_exec(ex, executable_stack) \ (executable_stack != EXSTACK_DISABLE_X) struct task_struct; #define ARCH_DLINFO_IA32(vdso_enabled) \ do { \ if (vdso_enabled) { \ NEW_AUX_ENT(AT_SYSINFO, VDSO_ENTRY); \ NEW_AUX_ENT(AT_SYSINFO_EHDR, VDSO_CURRENT_BASE); \ } \ } while (0) #ifdef CONFIG_X86_32 #define STACK_RND_MASK (0x7ff) #define VDSO_HIGH_BASE (__fix_to_virt(FIX_VDSO)) #define ARCH_DLINFO ARCH_DLINFO_IA32(vdso_enabled) /* update AT_VECTOR_SIZE_ARCH if the number of NEW_AUX_ENT entries changes */ #else /* CONFIG_X86_32 */ #define VDSO_HIGH_BASE 0xffffe000U /* CONFIG_COMPAT_VDSO address */ /* 1GB for 64bit, 8MB for 32bit */ #define STACK_RND_MASK (test_thread_flag(TIF_IA32) ? 0x7ff : 0x3fffff) #define ARCH_DLINFO \ do { \ NEW_AUX_ENT(AT_SYSINFO_EHDR, current->mm->context.vdso); \ } while (0) #define AT_SYSINFO 32 #define COMPAT_ARCH_DLINFO ARCH_DLINFO_IA32(sysctl_vsyscall32) #define COMPAT_ELF_ET_DYN_BASE (TASK_UNMAPPED_BASE + 0x1000000) #endif /* !CONFIG_X86_32 */ #define VDSO_CURRENT_BASE (current->mm->context.vdso) #define VDSO_ENTRY \ ((unsigned long)VDSO32_SYMBOL(VDSO_CURRENT_BASE, vsyscall)) struct linux_binprm; #define ARCH_HAS_SETUP_ADDITIONAL_PAGES 1 extern int arch_setup_additional_pages(struct linux_binprm *bprm, int uses_interp); extern int syscall32_setup_pages(struct linux_binprm *, int exstack); #define compat_arch_setup_additional_pages syscall32_setup_pages #endif /* _ASM_X86_ELF_H */
Java
//----------------------------------------------------------------------------- // // Vampire - A code for atomistic simulation of magnetic materials // // Copyright (C) 2009-2012 R.F.L.Evans // // Email:[email protected] // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 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. // // ---------------------------------------------------------------------------- // // Headers #include "errors.hpp" #include "demag.hpp" #include "voronoi.hpp" #include "material.hpp" #include "sim.hpp" #include "random.hpp" #include "vio.hpp" #include "vmath.hpp" #include "vmpi.hpp" #include <cmath> #include <iostream> #include <sstream> //========================================================== // Namespace material_parameters //========================================================== namespace mp{ //---------------------------------- // Material Container //---------------------------------- //const int max_materials=100; int num_materials=1; std::vector <materials_t> material(1); //---------------------------------- //Input Integration parameters //---------------------------------- double dt_SI; double gamma_SI = 1.76E11; //---------------------------------- //Derived Integration parameters //---------------------------------- double dt; double half_dt; // Unrolled material parameters for speed std::vector <double> MaterialMuSSIArray(0); std::vector <zkval_t> MaterialScalarAnisotropyArray(0); std::vector <zkten_t> MaterialTensorAnisotropyArray(0); std::vector <double> material_second_order_anisotropy_constant_array(0); std::vector <double> material_sixth_order_anisotropy_constant_array(0); std::vector <double> material_spherical_harmonic_constants_array(0); std::vector <double> MaterialCubicAnisotropyArray(0); /// /// @brief Function to initialise program variables prior to system creation. /// /// @section License /// Use of this code, either in source or compiled form, is subject to license from the authors. /// Copyright \htmlonly &copy \endhtmlonly Richard Evans, 2009-2010. All Rights Reserved. /// /// @section Information /// @author Richard Evans, [email protected] /// @version 1.0 /// @date 19/01/2010 /// /// @param[in] infile Main input file name for system initialisation /// @return EXIT_SUCCESS /// /// @internal /// Created: 19/01/2010 /// Revision: --- ///===================================================================================== /// int initialise(std::string const infile){ //---------------------------------------------------------- // check calling of routine if error checking is activated //---------------------------------------------------------- if(err::check==true){std::cout << "initialise_variables has been called" << std::endl;} if(vmpi::my_rank==0){ std::cout << "================================================================================" << std::endl; std::cout << "Initialising system variables" << std::endl; } // Setup default system settings mp::default_system(); // Read values from input files int iostat = vin::read(infile); if(iostat==EXIT_FAILURE){ terminaltextcolor(RED); std::cerr << "Error - input file \'" << infile << "\' not found, exiting" << std::endl; terminaltextcolor(WHITE); err::vexit(); } // Print out material properties //mp::material[0].print(); // Check for keyword parameter overide if(cs::single_spin==true){ mp::single_spin_system(); } // Set derived system parameters mp::set_derived_parameters(); // Return return EXIT_SUCCESS; } int default_system(){ // Initialise system creation flags to zero for (int i=0;i<10;i++){ cs::system_creation_flags[i] = 0; sim::hamiltonian_simulation_flags[i] = 0; } // Set system dimensions !Angstroms cs::unit_cell_size[0] = 3.0; cs::unit_cell_size[1] = 3.0; cs::unit_cell_size[2] = 3.0; cs::system_dimensions[0] = 100.0; cs::system_dimensions[1] = 100.0; cs::system_dimensions[2] = 100.0; cs::particle_scale = 50.0; cs::particle_spacing = 10.0; cs::particle_creation_parity=0; cs::crystal_structure = "sc"; // Voronoi Variables create_voronoi::voronoi_sd=0.1; create_voronoi::parity=0; // Setup Hamiltonian Flags sim::hamiltonian_simulation_flags[0] = 1; /// Exchange sim::hamiltonian_simulation_flags[1] = 1; /// Anisotropy sim::hamiltonian_simulation_flags[2] = 1; /// Applied sim::hamiltonian_simulation_flags[3] = 1; /// Thermal sim::hamiltonian_simulation_flags[4] = 0; /// Dipolar //Integration parameters dt_SI = 1.0e-15; // seconds dt = dt_SI*mp::gamma_SI; // Must be set before Hth half_dt = 0.5*dt; //------------------------------------------------------------------------------ // Material Definitions //------------------------------------------------------------------------------ num_materials=1; material.resize(num_materials); //------------------------------------------------------- // Material 0 //------------------------------------------------------- material[0].name="Co"; material[0].alpha=0.1; material[0].Jij_matrix_SI[0]=-11.2e-21; material[0].mu_s_SI=1.5*9.27400915e-24; material[0].Ku1_SI=-4.644e-24; material[0].gamma_rel=1.0; material[0].element="Ag "; // Disable Error Checking err::check=false; // Initialise random number generator mtrandom::grnd.seed(2106975519); return EXIT_SUCCESS; } int single_spin_system(){ // Reset system creation flags to zero for (int i=0;i<10;i++){ cs::system_creation_flags[i] = 0; } // Set system dimensions !Angstroms cs::unit_cell_size[0] = 3.0; cs::unit_cell_size[1] = 3.0; cs::unit_cell_size[2] = 3.0; cs::system_dimensions[0] = 2.0; cs::system_dimensions[1] = 2.0; cs::system_dimensions[2] = 2.0; cs::particle_scale = 50.0; cs::particle_spacing = 10.0; cs::particle_creation_parity=0; cs::crystal_structure = "sc"; // Turn off multi-spin Flags sim::hamiltonian_simulation_flags[0] = 0; /// Exchange sim::hamiltonian_simulation_flags[4] = 0; /// Dipolar // MPI Mode (Homogeneous execution) //vmpi::mpi_mode=0; //mpi_create_variables::mpi_interaction_range=2; // Unit cells //mpi_create_variables::mpi_comms_identify=false; return EXIT_SUCCESS; } // Simple function to check for valid input for hysteresis loop parameters void check_hysteresis_loop_parameters(){ // Only applies to hysteresis loop programs, all others return if(sim::program!=12) return; double min=sim::Hmin; double max=sim::Hmax; double inc=sim::Hinc; // + + + if(min>=0 && max>=0 && inc>0){ if(max<min){ if(vmpi::my_rank==0){ terminaltextcolor(RED); std::cout << "Error in hysteresis-loop parameters:" << std::endl; std::cout << "\t sim:minimum-applied-field-strength = " << min << std::endl; std::cout << "\t sim:maximum-applied-field-strength = " << max << std::endl; std::cout << "\t sim:applied-field-strength-increment = " << inc << std::endl; std::cout << "Minimum and maximum fields are both positive, but minimum > maximum with a positive increment, causing an infinite loop. Exiting." << std::endl; terminaltextcolor(WHITE); zlog << zTs() << "Error in hysteresis-loop parameters:" << std::endl; zlog << zTs() << "\t sim:minimum-applied-field-strength = " << min << std::endl; zlog << zTs() << "\t sim:maximum-applied-field-strength = " << max << std::endl; zlog << zTs() << "\t sim:applied-field-strength-increment = " << inc << std::endl; zlog << zTs() << "Minimum and maximum fields are both positive, but minimum > maximum with a positive increment, causing an infinite loop. Exiting." << std::endl; err::vexit(); } } } // + + - else if(min>=0 && max>=0 && inc<0){ if(max>min){ if(vmpi::my_rank==0){ terminaltextcolor(RED); std::cout << "Error in hysteresis-loop parameters:" << std::endl; std::cout << "\t sim:minimum-applied-field-strength = " << min << std::endl; std::cout << "\t sim:maximum-applied-field-strength = " << max << std::endl; std::cout << "\t sim:applied-field-strength-increment = " << inc << std::endl; std::cout << "Minimum and maximum fields are both positive, but maximum > minimum with a negative increment, causing an infinite loop. Exiting." << std::endl; terminaltextcolor(WHITE); zlog << zTs() << "Error in hysteresis-loop parameters:" << std::endl; zlog << zTs() << "\t sim:minimum-applied-field-strength = " << min << std::endl; zlog << zTs() << "\t sim:maximum-applied-field-strength = " << max << std::endl; zlog << zTs() << "\t sim:applied-field-strength-increment = " << inc << std::endl; zlog << zTs() << "Minimum and maximum fields are both positive, but maximum > minimum with a negative increment, causing an infinite loop. Exiting." << std::endl; err::vexit(); } } } // + - + else if(min>=0 && max<0 && inc>0){ if(vmpi::my_rank==0){ terminaltextcolor(RED); std::cout << "Error in hysteresis-loop parameters:" << std::endl; std::cout << "\t sim:minimum-applied-field-strength = " << min << std::endl; std::cout << "\t sim:maximum-applied-field-strength = " << max << std::endl; std::cout << "\t sim:applied-field-strength-increment = " << inc << std::endl; std::cout << "Minimum field is positive and maximum field is negative with a positive increment, causing an infinite loop. Exiting." << std::endl; terminaltextcolor(WHITE); zlog << zTs() << "Error in hysteresis-loop parameters:" << std::endl; zlog << zTs() << "\t sim:minimum-applied-field-strength = " << min << std::endl; zlog << zTs() << "\t sim:maximum-applied-field-strength = " << max << std::endl; zlog << zTs() << "\t sim:applied-field-strength-increment = " << inc << std::endl; zlog << zTs() << "Minimum field is positive and maximum field is negative with a positive increment, causing an infinite loop. Exiting." << std::endl; err::vexit(); } } // - + - else if(min<0 && max>=0 && inc<0){ if(vmpi::my_rank==0){ terminaltextcolor(RED); std::cout << "Error in hysteresis-loop parameters:" << std::endl; std::cout << "\t sim:minimum-applied-field-strength = " << min << std::endl; std::cout << "\t sim:maximum-applied-field-strength = " << max << std::endl; std::cout << "\t sim:applied-field-strength-increment = " << inc << std::endl; std::cout << "Minimum field is negative and maximum field is positive with a negative increment, causing an infinite loop. Exiting." << std::endl; terminaltextcolor(WHITE); zlog << zTs() << "Error in hysteresis-loop parameters:" << std::endl; zlog << zTs() << "\t sim:minimum-applied-field-strength = " << min << std::endl; zlog << zTs() << "\t sim:maximum-applied-field-strength = " << max << std::endl; zlog << zTs() << "\t sim:applied-field-strength-increment = " << inc << std::endl; zlog << zTs() << "Minimum field is negative and maximum field is positive with a negative increment, causing an infinite loop. Exiting." << std::endl; err::vexit(); } } // - - - else if(min<0 && max<0 && inc<0){ if(max>min){ if(vmpi::my_rank==0){ terminaltextcolor(RED); std::cout << "Error in hysteresis-loop parameters:" << std::endl; std::cout << "\t sim:minimum-applied-field-strength = " << min << std::endl; std::cout << "\t sim:maximum-applied-field-strength = " << max << std::endl; std::cout << "\t sim:applied-field-strength-increment = " << inc << std::endl; std::cout << "Minimum and maximum fields are both negative, but minimum < maximum with a negative increment, causing an infinite loop. Exiting." << std::endl; terminaltextcolor(WHITE); zlog << zTs() << "Error in hysteresis-loop parameters:" << std::endl; zlog << zTs() << "\t sim:minimum-applied-field-strength = " << min << std::endl; zlog << zTs() << "\t sim:maximum-applied-field-strength = " << max << std::endl; zlog << zTs() << "\t sim:applied-field-strength-increment = " << inc << std::endl; zlog << zTs() << "Minimum and maximum fields are both negative, but minimum < maximum with a negative increment, causing an infinite loop. Exiting." << std::endl; err::vexit(); } } } // - - + else if(min<0 && max<0 && inc>0){ if(max<min){ if(vmpi::my_rank==0){ terminaltextcolor(RED); std::cout << "Error in hysteresis-loop parameters:" << std::endl; std::cout << "\t sim:minimum-applied-field-strength = " << min << std::endl; std::cout << "\t sim:maximum-applied-field-strength = " << max << std::endl; std::cout << "\t sim:applied-field-strength-increment = " << inc << std::endl; std::cout << "Minimum and maximum fields are both negative, but maximum < minimum with a positive increment, causing an infinite loop. Exiting." << std::endl; terminaltextcolor(WHITE); zlog << zTs() << "Error in hysteresis-loop parameters:" << std::endl; zlog << zTs() << "\t sim:minimum-applied-field-strength = " << min << std::endl; zlog << zTs() << "\t sim:maximum-applied-field-strength = " << max << std::endl; zlog << zTs() << "\t sim:applied-field-strength-increment = " << inc << std::endl; zlog << zTs() << "Minimum and maximum fields are both positive, but maximum < minimum with a positive increment, causing an infinite loop. Exiting." << std::endl; err::vexit(); } } } return; } int set_derived_parameters(){ // Set integration constants mp::dt = mp::dt_SI*mp::gamma_SI; // Must be set before Hth mp::half_dt = 0.5*mp::dt; // Check to see if field direction is set by angle if(sim::applied_field_set_by_angle){ sim::H_vec[0]=sin(sim::applied_field_angle_phi*M_PI/180.0)*cos(sim::applied_field_angle_theta*M_PI/180.0); sim::H_vec[1]=sin(sim::applied_field_angle_phi*M_PI/180.0)*sin(sim::applied_field_angle_theta*M_PI/180.0); sim::H_vec[2]=cos(sim::applied_field_angle_phi*M_PI/180.0); } // Check for valid particle array offsets if(cs::particle_array_offset_x >= cs::system_dimensions[0]){ terminaltextcolor(RED); std::cerr << "Warning: requested particle-array-offset-x is greater than system dimensions." << std::endl; std::cerr << "Info: This will probably lead to no particles being created and generate an error." << std::endl; terminaltextcolor(WHITE); zlog << zTs() << "Warning: requested particle-array-offset-x is greater than system dimensions." << std::endl; zlog << zTs() << "Info: This will probably lead to no particles being created and generate an error." << std::endl; } if(cs::particle_array_offset_y >= cs::system_dimensions[1]){ terminaltextcolor(RED); std::cerr << "Warning: requested particle-array-offset-y is greater than system dimensions." << std::endl; std::cerr << "Info: This will probably lead to no particles being created and generate an error." << std::endl; terminaltextcolor(WHITE); zlog << zTs() << "Warning: requested particle-array-offset-y is greater than system dimensions." << std::endl; zlog << zTs() << "Info: This will probably lead to no particles being created and generate an error." << std::endl; } check_hysteresis_loop_parameters(); // Ensure H vector is unit length // **RE edit 21.11.12 - no longer necessary as value checked on user input** //double mod_H=1.0/sqrt(sim::H_vec[0]*sim::H_vec[0]+sim::H_vec[1]*sim::H_vec[1]+sim::H_vec[2]*sim::H_vec[2]); //sim::H_vec[0]*=mod_H; //sim::H_vec[1]*=mod_H; //sim::H_vec[2]*=mod_H; // Calculate moment, magnetisation, and anisotropy constants /*for(int mat=0;mat<mp::num_materials;mat++){ double V=cs::unit_cell_size[0]*cs::unit_cell_size[1]*cs::unit_cell_size[2]; // Set magnetisation from mu_s and a if(material[mat].moment_flag==true){ //material[mat].magnetisation=num_atoms_per_unit_cell*material[mat].mu_s_SI/V; } // Set mu_s from magnetisation and a else { //material[mat].mu_s_SI=material[mat].magnetisation*V/num_atoms_per_unit_cell; } // Set K as energy/atom if(material[mat].anis_flag==false){ material[mat].Ku1_SI=material[mat].Ku1_SI*V/num_atoms_per_unit_cell; std::cout << "setting " << material[mat].Ku1_SI << std::endl; } }*/ const string blank=""; // Check for symmetry of exchange matrix for(int mi = 0; mi < mp::num_materials; mi++){ for(int mj = 0; mj < mp::num_materials; mj++){ // Check for non-zero value (avoids divide by zero) if(fabs(material[mi].Jij_matrix_SI[mj]) > 0.0){ // Calculate ratio of i->j / j-> exchange constants double ratio = material[mj].Jij_matrix_SI[mi]/material[mi].Jij_matrix_SI[mj]; // Check that ratio ~ 1.0 for symmetric exchange interactions if( (ratio < 0.99999) || (ratio > 1.00001) ){ // Error found - report to user and terminate program terminaltextcolor(RED); std::cerr << "Error! Non-symmetric exchange interactions for materials " << mi+1 << " and " << mj+1 << ". Exiting" << std::endl; terminaltextcolor(WHITE); zlog << zTs() << "Error! Non-symmetric exchange interactions for materials " << mi+1 << " and " << mj+1 << std::endl; zlog << zTs() << "\tmaterial[" << mi+1 << "]:exchange-matrix[" << mj+1 << "] = " << material[mi].Jij_matrix_SI[mj] << std::endl; zlog << zTs() << "\tmaterial[" << mj+1 << "]:exchange-matrix[" << mi+1 << "] = " << material[mj].Jij_matrix_SI[mi] << std::endl; zlog << zTs() << "\tThe definition of Heisenberg exchange requires that these values are the same. Exiting." << std::endl; err::vexit(); } } } } // Set derived material parameters for(int mat=0;mat<mp::num_materials;mat++){ mp::material[mat].one_oneplusalpha_sq = -mp::material[mat].gamma_rel/(1.0+mp::material[mat].alpha*mp::material[mat].alpha); mp::material[mat].alpha_oneplusalpha_sq = mp::material[mat].alpha*mp::material[mat].one_oneplusalpha_sq; for(int j=0;j<mp::num_materials;j++){ material[mat].Jij_matrix[j] = mp::material[mat].Jij_matrix_SI[j]/mp::material[mat].mu_s_SI; } mp::material[mat].Ku = mp::material[mat].Ku1_SI/mp::material[mat].mu_s_SI; mp::material[mat].Ku2 = mp::material[mat].Ku2_SI/mp::material[mat].mu_s_SI; mp::material[mat].Ku3 = mp::material[mat].Ku3_SI/mp::material[mat].mu_s_SI; mp::material[mat].Klatt = mp::material[mat].Klatt_SI/mp::material[mat].mu_s_SI; mp::material[mat].Kc = mp::material[mat].Kc1_SI/mp::material[mat].mu_s_SI; mp::material[mat].Ks = mp::material[mat].Ks_SI/mp::material[mat].mu_s_SI; mp::material[mat].H_th_sigma = sqrt(2.0*mp::material[mat].alpha*1.3806503e-23/ (mp::material[mat].mu_s_SI*mp::material[mat].gamma_rel*dt)); // Rename un-named materials with material id std::string defname="material#n"; if(mp::material[mat].name==defname){ std::stringstream newname; newname << "material" << mat+1; mp::material[mat].name=newname.str(); } // initialise lattice anisotropy initialisation if(sim::lattice_anisotropy_flag==true) mp::material[mat].lattice_anisotropy.set_interpolation_table(); // output interpolated data to file //mp::material[mat].lattice_anisotropy.output_interpolated_function(mat); } // Check for which anisotropy function(s) are to be used if(sim::TensorAnisotropy==true){ sim::UniaxialScalarAnisotropy=false; // turn off scalar anisotropy calculation // loop over materials and convert all scalar anisotropy to tensor (along z) for(int mat=0;mat<mp::num_materials; mat++){ const double one_o_mu=1.0/mp::material[mat].mu_s_SI; // If tensor is unset if(mp::material.at(mat).KuVec_SI.size()==0){ const double ex = mp::material.at(mat).UniaxialAnisotropyUnitVector.at(0); const double ey = mp::material.at(mat).UniaxialAnisotropyUnitVector.at(1); const double ez = mp::material.at(mat).UniaxialAnisotropyUnitVector.at(2); mp::material.at(mat).KuVec.push_back(mp::material[mat].Ku*ex*ex); mp::material.at(mat).KuVec.push_back(mp::material[mat].Ku*ex*ey); mp::material.at(mat).KuVec.push_back(mp::material[mat].Ku*ex*ez); mp::material.at(mat).KuVec.push_back(mp::material[mat].Ku*ey*ex); mp::material.at(mat).KuVec.push_back(mp::material[mat].Ku*ey*ey); mp::material.at(mat).KuVec.push_back(mp::material[mat].Ku*ey*ez); mp::material.at(mat).KuVec.push_back(mp::material[mat].Ku*ez*ex); mp::material.at(mat).KuVec.push_back(mp::material[mat].Ku*ez*ey); mp::material.at(mat).KuVec.push_back(mp::material[mat].Ku*ez*ez); } else if(mp::material.at(mat).KuVec_SI.size()==9){ mp::material.at(mat).KuVec.push_back(mp::material.at(mat).KuVec_SI.at(0)*one_o_mu); mp::material.at(mat).KuVec.push_back(mp::material.at(mat).KuVec_SI.at(1)*one_o_mu); mp::material.at(mat).KuVec.push_back(mp::material.at(mat).KuVec_SI.at(2)*one_o_mu); mp::material.at(mat).KuVec.push_back(mp::material.at(mat).KuVec_SI.at(3)*one_o_mu); mp::material.at(mat).KuVec.push_back(mp::material.at(mat).KuVec_SI.at(4)*one_o_mu); mp::material.at(mat).KuVec.push_back(mp::material.at(mat).KuVec_SI.at(5)*one_o_mu); mp::material.at(mat).KuVec.push_back(mp::material.at(mat).KuVec_SI.at(6)*one_o_mu); mp::material.at(mat).KuVec.push_back(mp::material.at(mat).KuVec_SI.at(7)*one_o_mu); mp::material.at(mat).KuVec.push_back(mp::material.at(mat).KuVec_SI.at(8)*one_o_mu); } } } // Unroll anisotropy values for speed if(sim::UniaxialScalarAnisotropy==true){ zlog << zTs() << "Setting scalar uniaxial anisotropy." << std::endl; // Set global anisotropy type sim::AnisotropyType=0; MaterialScalarAnisotropyArray.resize(mp::num_materials); for(int mat=0;mat<mp::num_materials; mat++) MaterialScalarAnisotropyArray[mat].K=mp::material[mat].Ku; } else if(sim::TensorAnisotropy==true){ zlog << zTs() << "Setting tensor uniaxial anisotropy." << std::endl; // Set global anisotropy type sim::AnisotropyType=1; MaterialTensorAnisotropyArray.resize(mp::num_materials); for(int mat=0;mat<mp::num_materials; mat++){ MaterialTensorAnisotropyArray[mat].K[0][0]=mp::material.at(mat).KuVec.at(0); MaterialTensorAnisotropyArray[mat].K[0][1]=mp::material.at(mat).KuVec.at(1); MaterialTensorAnisotropyArray[mat].K[0][2]=mp::material.at(mat).KuVec.at(2); MaterialTensorAnisotropyArray[mat].K[1][0]=mp::material.at(mat).KuVec.at(3); MaterialTensorAnisotropyArray[mat].K[1][1]=mp::material.at(mat).KuVec.at(4); MaterialTensorAnisotropyArray[mat].K[1][2]=mp::material.at(mat).KuVec.at(5); MaterialTensorAnisotropyArray[mat].K[2][0]=mp::material.at(mat).KuVec.at(6); MaterialTensorAnisotropyArray[mat].K[2][1]=mp::material.at(mat).KuVec.at(7); MaterialTensorAnisotropyArray[mat].K[2][2]=mp::material.at(mat).KuVec.at(8); } } // Unroll second order uniaxial anisotropy values for speed if(sim::second_order_uniaxial_anisotropy==true){ zlog << zTs() << "Setting scalar second order uniaxial anisotropy." << std::endl; mp::material_second_order_anisotropy_constant_array.resize(mp::num_materials); for(int mat=0;mat<mp::num_materials; mat++) mp::material_second_order_anisotropy_constant_array.at(mat)=mp::material[mat].Ku2; } // Unroll sixth order uniaxial anisotropy values for speed if(sim::second_order_uniaxial_anisotropy==true){ zlog << zTs() << "Setting scalar sixth order uniaxial anisotropy." << std::endl; mp::material_sixth_order_anisotropy_constant_array.resize(mp::num_materials); for(int mat=0;mat<mp::num_materials; mat++) mp::material_sixth_order_anisotropy_constant_array.at(mat)=mp::material[mat].Ku3; } // Unroll spherical harmonic anisotropy constants for speed if(sim::spherical_harmonics==true){ zlog << zTs() << "Setting spherical harmonics for uniaxial anisotropy" << std::endl; mp::material_spherical_harmonic_constants_array.resize(3*mp::num_materials); for(int mat=0; mat<mp::num_materials; mat++){ mp::material_spherical_harmonic_constants_array.at(3*mat+0)=mp::material[mat].sh2/mp::material[mat].mu_s_SI; mp::material_spherical_harmonic_constants_array.at(3*mat+1)=mp::material[mat].sh4/mp::material[mat].mu_s_SI; mp::material_spherical_harmonic_constants_array.at(3*mat+2)=mp::material[mat].sh6/mp::material[mat].mu_s_SI; } } // Unroll cubic anisotropy values for speed if(sim::CubicScalarAnisotropy==true){ zlog << zTs() << "Setting scalar cubic anisotropy." << std::endl; MaterialCubicAnisotropyArray.resize(mp::num_materials); for(int mat=0;mat<mp::num_materials; mat++) MaterialCubicAnisotropyArray.at(mat)=mp::material[mat].Kc; } // Loop over materials to check for invalid input and warn appropriately for(int mat=0;mat<mp::num_materials;mat++){ const double lmin=material[mat].min; const double lmax=material[mat].max; for(int nmat=0;nmat<mp::num_materials;nmat++){ if(nmat!=mat){ double min=material[nmat].min; double max=material[nmat].max; if(((lmin>min) && (lmin<max)) || ((lmax>min) && (lmax<max))){ terminaltextcolor(RED); std::cerr << "Warning: Overlapping material heights found. Check log for details." << std::endl; terminaltextcolor(WHITE); zlog << zTs() << "Warning: material " << mat+1 << " overlaps material " << nmat+1 << "." << std::endl; zlog << zTs() << "If you have defined geometry then this may be OK, or possibly you meant to specify alloy keyword instead." << std::endl; zlog << zTs() << "----------------------------------------------------" << std::endl; zlog << zTs() << " Material "<< mat+1 << ":minimum-height = " << lmin << std::endl; zlog << zTs() << " Material "<< mat+1 << ":maximum-height = " << lmax << std::endl; zlog << zTs() << " Material "<< nmat+1 << ":minimum-height = " << min << std::endl; zlog << zTs() << " Material "<< nmat+1 << ":maximum-height = " << max << std::endl; } } } } return EXIT_SUCCESS; } } // end of namespace mp
Java
--DDD死偉王ヘル・アーマゲドン function c47198668.initial_effect(c) --pendulum summon aux.EnablePendulumAttribute(c) --atk up local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_IGNITION) e2:SetRange(LOCATION_PZONE) e2:SetProperty(EFFECT_FLAG_CARD_TARGET) e2:SetCountLimit(1) e2:SetTarget(c47198668.atktg1) e2:SetOperation(c47198668.atkop1) c:RegisterEffect(e2) --atk up local e3=Effect.CreateEffect(c) e3:SetCategory(CATEGORY_ATKCHANGE) e3:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O) e3:SetCode(EVENT_DESTROYED) e3:SetRange(LOCATION_MZONE) e3:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DAMAGE_STEP) e3:SetCountLimit(1) e3:SetCost(c47198668.atkcost) e3:SetTarget(c47198668.atktg2) e3:SetOperation(c47198668.atkop2) c:RegisterEffect(e3) --indes local e4=Effect.CreateEffect(c) e4:SetType(EFFECT_TYPE_SINGLE) e4:SetCode(EFFECT_INDESTRUCTABLE_EFFECT) e4:SetProperty(EFFECT_FLAG_SINGLE_RANGE) e4:SetRange(LOCATION_MZONE) e4:SetValue(c47198668.efilter) c:RegisterEffect(e4) end function c47198668.filter1(c) return c:IsFaceup() and c:IsSetCard(0xaf) end function c47198668.atktg1(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(tp) and c47198668.filter1(chkc) end if chk==0 then return Duel.IsExistingTarget(c47198668.filter1,tp,LOCATION_MZONE,0,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP) Duel.SelectTarget(tp,c47198668.filter1,tp,LOCATION_MZONE,0,1,1,nil) end function c47198668.atkop1(e,tp,eg,ep,ev,re,r,rp) if not e:GetHandler():IsRelateToEffect(e) then return end local tc=Duel.GetFirstTarget() if tc:IsFaceup() and tc:IsRelateToEffect(e) then local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE) e1:SetCode(EFFECT_UPDATE_ATTACK) e1:SetValue(800) e1:SetReset(RESET_EVENT+RESETS_STANDARD+RESET_PHASE+PHASE_END) tc:RegisterEffect(e1) end end function c47198668.filter2(c,e,tp) return c:IsReason(REASON_BATTLE+REASON_EFFECT) and c:IsType(TYPE_MONSTER) and c:IsPreviousLocation(LOCATION_MZONE) and c:GetPreviousControler()==tp and c:IsLocation(LOCATION_GRAVE+LOCATION_REMOVED) and c:IsCanBeEffectTarget(e) end function c47198668.atkcost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return not e:GetHandler():IsDirectAttacked() end local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_OATH) e1:SetCode(EFFECT_CANNOT_DIRECT_ATTACK) e1:SetReset(RESET_EVENT+RESETS_STANDARD+RESET_PHASE+PHASE_END) e:GetHandler():RegisterEffect(e1) end function c47198668.atktg2(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return eg:IsContains(chkc) and c47198668.filter2(chkc,e,tp) end if chk==0 then return eg:IsExists(c47198668.filter2,1,nil,e,tp) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TARGET) local g=eg:FilterSelect(tp,c47198668.filter2,1,1,nil,e,tp) Duel.SetTargetCard(g) end function c47198668.atkop2(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() local tc=Duel.GetFirstTarget() if c:IsFaceup() and c:IsRelateToEffect(e) and tc:IsRelateToEffect(e) then local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_UPDATE_ATTACK) e1:SetValue(tc:GetBaseAttack()) e1:SetReset(RESET_EVENT+RESETS_STANDARD+RESET_DISABLE+RESET_PHASE+PHASE_END) c:RegisterEffect(e1) end end function c47198668.efilter(e,re,rp) if not re:IsActiveType(TYPE_SPELL+TYPE_TRAP) then return false end if not re:IsHasProperty(EFFECT_FLAG_CARD_TARGET) then return true end local g=Duel.GetChainInfo(0,CHAININFO_TARGET_CARDS) return not g:IsContains(e:GetHandler()) end
Java
/****************************************************************** iLBC Speech Coder ANSI-C Source Code LPC_decode.h Copyright (C) The Internet Society (2004). All Rights Reserved. ******************************************************************/ #ifndef __iLBC_LPC_DECODE_H #define __iLBC_LPC_DECODE_H void LSFinterpolate2a_dec( float *a, /* (o) lpc coefficients for a sub-frame */ float *lsf1, /* (i) first lsf coefficient vector */ float *lsf2, /* (i) second lsf coefficient vector */ float coef, /* (i) interpolation weight */ int length /* (i) length of lsf vectors */ ); void SimplelsfDEQ( float *lsfdeq, /* (o) dequantized lsf coefficients */ int *index, /* (i) quantization index */ int lpc_n /* (i) number of LPCs */ ); void DecoderInterpolateLSF( float *syntdenum, /* (o) synthesis filter coefficients */ float *weightdenum, /* (o) weighting denumerator coefficients */ float *lsfdeq, /* (i) dequantized lsf coefficients */ int length, /* (i) length of lsf coefficient vector */ iLBC_Dec_Inst_t *iLBCdec_inst /* (i) the decoder state structure */ ); #endif
Java
(function( $ ) { wp.customize( 'blogname', function( value ) { value.bind( function( to ) { $( '.site-title a' ).text( to ); } ); } ); wp.customize( 'blogdescription', function( value ) { value.bind( function( to ) { $( '.site-description' ).text( to ); } ); } ); })( jQuery );
Java
#!/bin/python import os, subprocess import logging from autotest.client import test from autotest.client.shared import error, software_manager sm = software_manager.SoftwareManager() class sblim_sfcb(test.test): """ Autotest module for testing basic functionality of sblim_sfcb @author Wang Tao <[email protected]> """ version = 1 nfail = 0 path = '' def initialize(self, test_path=''): """ Sets the overall failure counter for the test. """ self.nfail = 0 if not sm.check_installed('gcc'): logging.debug("gcc missing - trying to install") sm.install('gcc') ret_val = subprocess.Popen(['make', 'all'], cwd="%s/sblim_sfcb" %(test_path)) ret_val.communicate() if ret_val.returncode != 0: self.nfail += 1 logging.info('\n Test initialize successfully') def run_once(self, test_path=''): """ Trigger test run """ try: os.environ["LTPBIN"] = "%s/shared" %(test_path) ret_val = subprocess.Popen(['./sblim-sfcb-test.sh'], cwd="%s/sblim_sfcb" %(test_path)) ret_val.communicate() if ret_val.returncode != 0: self.nfail += 1 except error.CmdError, e: self.nfail += 1 logging.error("Test Failed: %s", e) def postprocess(self): if self.nfail != 0: logging.info('\n nfails is non-zero') raise error.TestError('\nTest failed') else: logging.info('\n Test completed successfully ')
Java