code stringlengths 3 1.01M | repo_name stringlengths 5 116 | path stringlengths 3 311 | language stringclasses 30 values | license stringclasses 15 values | size int64 3 1.01M |
|---|---|---|---|---|---|
<?php
// URI: design/admin/templates/navigator/alphabetical.tpl
// Filename: design/admin/templates/navigator/alphabetical.tpl
// Timestamp: 1416144920 (Sun Nov 16 14:35:20 CET 2014)
$oldSetArray_faddee0132331cfae3257224b2d669d9 = isset( $setArray ) ? $setArray : array();
$setArray = array();
$tpl->Level++;
if ( $tpl->Level > 40 )
{
$text = $tpl->MaxLevelWarning;$tpl->Level--;
return;
}
$eZTemplateCompilerCodeDate = 1074699607;
if ( !defined( 'EZ_TEMPLATE_COMPILER_COMMON_CODE' ) )
include_once( 'var/ezdemo_site/cache/template/compiled/common.php' );
if ( !isset( $vars[$currentNamespace]['page_uri_suffix'] ) )
{
$vars[$currentNamespace]['page_uri_suffix'] = false;
$setArray[$currentNamespace]['page_uri_suffix'] = true;
}
if ( !isset( $vars[$currentNamespace]['show_google_navigator'] ) )
{
$vars[$currentNamespace]['show_google_navigator'] = false;
$setArray[$currentNamespace]['show_google_navigator'] = true;
}
// if begins
unset( $if_cond );
unset( $if_cond );
$if_cond = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'show_google_navigator', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['show_google_navigator'] : null;
if (! isset( $if_cond ) ) $if_cond = NULL;
while ( is_object( $if_cond ) and method_exists( $if_cond, 'templateValue' ) )
$if_cond = $if_cond->templateValue();
if ( $if_cond )
{
$text .= ' ';
$oldRestoreIncludeArray_e4293087feba14f6c4fce1dfa13cf9e5 = isset( $restoreIncludeArray ) ? $restoreIncludeArray : array();
$restoreIncludeArray = array();
if ( isset( $namespace ) and isset( $vars[$namespace]['page_uri'] ) )
$restoreIncludeArray[] = array( $namespace, 'page_uri', $vars[$namespace]['page_uri'] );
elseif ( !isset( $vars[( isset( $namespace ) ? $namespace : '' )]['page_uri'] ) )
$restoreIncludeArray[] = array( ( isset( $namespace ) ? $namespace : '' ), 'page_uri', 'unset' );
unset( $var );
unset( $var );
$var = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'page_uri', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['page_uri'] : null;
if (! isset( $var ) ) $var = NULL;
while ( is_object( $var ) and method_exists( $var, 'templateValue' ) )
$var = $var->templateValue();
$namespace = $currentNamespace;
if ( $namespace == '' )
$namespace = "navigator";
else
$namespace .= ':navigator';
$vars[$namespace]['page_uri'] = $var;
unset( $var );
if ( isset( $namespace ) and isset( $vars[$namespace]['page_uri_suffix'] ) )
$restoreIncludeArray[] = array( $namespace, 'page_uri_suffix', $vars[$namespace]['page_uri_suffix'] );
elseif ( !isset( $vars[( isset( $namespace ) ? $namespace : '' )]['page_uri_suffix'] ) )
$restoreIncludeArray[] = array( ( isset( $namespace ) ? $namespace : '' ), 'page_uri_suffix', 'unset' );
unset( $var );
unset( $var );
$var = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'page_uri_suffix', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['page_uri_suffix'] : null;
if (! isset( $var ) ) $var = NULL;
while ( is_object( $var ) and method_exists( $var, 'templateValue' ) )
$var = $var->templateValue();
$namespace = $currentNamespace;
if ( $namespace == '' )
$namespace = "navigator";
else
$namespace .= ':navigator';
$vars[$namespace]['page_uri_suffix'] = $var;
unset( $var );
if ( isset( $namespace ) and isset( $vars[$namespace]['item_count'] ) )
$restoreIncludeArray[] = array( $namespace, 'item_count', $vars[$namespace]['item_count'] );
elseif ( !isset( $vars[( isset( $namespace ) ? $namespace : '' )]['item_count'] ) )
$restoreIncludeArray[] = array( ( isset( $namespace ) ? $namespace : '' ), 'item_count', 'unset' );
unset( $var );
unset( $var );
$var = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'item_count', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['item_count'] : null;
if (! isset( $var ) ) $var = NULL;
while ( is_object( $var ) and method_exists( $var, 'templateValue' ) )
$var = $var->templateValue();
$namespace = $currentNamespace;
if ( $namespace == '' )
$namespace = "navigator";
else
$namespace .= ':navigator';
$vars[$namespace]['item_count'] = $var;
unset( $var );
if ( isset( $namespace ) and isset( $vars[$namespace]['view_parameters'] ) )
$restoreIncludeArray[] = array( $namespace, 'view_parameters', $vars[$namespace]['view_parameters'] );
elseif ( !isset( $vars[( isset( $namespace ) ? $namespace : '' )]['view_parameters'] ) )
$restoreIncludeArray[] = array( ( isset( $namespace ) ? $namespace : '' ), 'view_parameters', 'unset' );
unset( $var );
unset( $var );
$var = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'view_parameters', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['view_parameters'] : null;
if (! isset( $var ) ) $var = NULL;
while ( is_object( $var ) and method_exists( $var, 'templateValue' ) )
$var = $var->templateValue();
$namespace = $currentNamespace;
if ( $namespace == '' )
$namespace = "navigator";
else
$namespace .= ':navigator';
$vars[$namespace]['view_parameters'] = $var;
unset( $var );
if ( isset( $namespace ) and isset( $vars[$namespace]['item_limit'] ) )
$restoreIncludeArray[] = array( $namespace, 'item_limit', $vars[$namespace]['item_limit'] );
elseif ( !isset( $vars[( isset( $namespace ) ? $namespace : '' )]['item_limit'] ) )
$restoreIncludeArray[] = array( ( isset( $namespace ) ? $namespace : '' ), 'item_limit', 'unset' );
unset( $var );
unset( $var );
$var = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'item_limit', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['item_limit'] : null;
if (! isset( $var ) ) $var = NULL;
while ( is_object( $var ) and method_exists( $var, 'templateValue' ) )
$var = $var->templateValue();
$namespace = $currentNamespace;
if ( $namespace == '' )
$namespace = "navigator";
else
$namespace .= ':navigator';
$vars[$namespace]['item_limit'] = $var;
unset( $var );
if ( !isset( $dKeys ) )
{
$resH = $tpl->resourceHandler( "design" );
$dKeys = $resH->keys();
}
$resourceFound = false;
if ( file_exists( 'var/ezdemo_site/cache/template/compiled/google-78fba64326fbc47ed13dea0a9dfc805c.php' ) )
{
$resourceFound = true;
$namespaceStack[] = array( $rootNamespace, $currentNamespace );
$currentNamespace = $rootNamespace = !$currentNamespace ? 'navigator' : ( $currentNamespace . ':' . 'navigator' );
$tpl->createLocalVariablesList();
$tpl->appendTemplateFetch( 'design/admin/templates/navigator/google.tpl' );
include( '' . 'var/ezdemo_site/cache/template/compiled/google-78fba64326fbc47ed13dea0a9dfc805c.php' );
$tpl->unsetLocalVariables();
$tpl->destroyLocalVariablesList();
list( $rootNamespace, $currentNamespace ) = array_pop( $namespaceStack );
}
else
{
$resourceFound = true;
$resourceFound = true;
$namespaceStack[] = array( $rootNamespace, $currentNamespace );
$currentNamespace = $rootNamespace = !$currentNamespace ? 'navigator' : ( $currentNamespace . ':' . 'navigator' );
$textElements = array();
$extraParameters = array();
$tpl->processURI( 'design/admin/templates/navigator/google.tpl', true, $extraParameters, $textElements, $rootNamespace, $currentNamespace );
$text .= implode( '', $textElements );
list( $rootNamespace, $currentNamespace ) = array_pop( $namespaceStack );
}
foreach ( $restoreIncludeArray as $element )
{
if ( $element[2] === 'unset' )
{
unset( $vars[$element[0]][$element[1]] );
continue;
}
$vars[$element[0]][$element[1]] = $element[2];
}
$restoreIncludeArray = $oldRestoreIncludeArray_e4293087feba14f6c4fce1dfa13cf9e5;
}
unset( $if_cond );
// if ends
// if begins
unset( $if_cond );
unset( $if_cond1 );
unset( $if_cond2 );
if (! isset( $if_cond2 ) ) $if_cond2 = NULL;
while ( is_object( $if_cond2 ) and method_exists( $if_cond2, 'templateValue' ) )
$if_cond2 = $if_cond2->templateValue();
$if_cond2Data = array( 'value' => $if_cond2 );
$tpl->processOperator( 'count',
array (
0 =>
array (
0 =>
array (
0 => 6,
1 =>
array (
0 => 'ezini',
1 =>
array (
0 =>
array (
0 => 1,
1 => 'AlphabeticalFilterSettings',
2 => false,
),
),
2 =>
array (
0 =>
array (
0 => 1,
1 => 'ContentFilterList',
2 => false,
),
),
3 =>
array (
0 =>
array (
0 => 1,
1 => 'content.ini',
2 => false,
),
),
),
2 => false,
),
),
),
$rootNamespace, $currentNamespace, $if_cond2Data, false, false );
$if_cond2 = $if_cond2Data['value'];
unset( $if_cond2Data );
if (! isset( $if_cond2 ) ) $if_cond2 = NULL;
while ( is_object( $if_cond2 ) and method_exists( $if_cond2, 'templateValue' ) )
$if_cond2 = $if_cond2->templateValue();
$if_cond1 = ( ( $if_cond2 ) > ( 0 ) );
unset( $if_cond2 );
if (! isset( $if_cond1 ) ) $if_cond1 = NULL;
while ( is_object( $if_cond1 ) and method_exists( $if_cond1, 'templateValue' ) )
$if_cond1 = $if_cond1->templateValue();
if ( !$if_cond1 )
$if_cond = false;
else
$if_cond = $if_cond1;
unset( $if_cond1 );
if (! isset( $if_cond ) ) $if_cond = NULL;
while ( is_object( $if_cond ) and method_exists( $if_cond, 'templateValue' ) )
$if_cond = $if_cond->templateValue();
if ( $if_cond )
{
$text .= '
';
if ( !isset( $vars[$currentNamespace]['children_count_by_letter'] ) )
{
$vars[$currentNamespace]['children_count_by_letter'] = false;
$setArray[$currentNamespace]['children_count_by_letter'] = true;
}
if ( !isset( $vars[$currentNamespace]['objectname_filter'] ) )
{
$vars[$currentNamespace]['objectname_filter'] = false;
$setArray[$currentNamespace]['objectname_filter'] = true;
}
unset( $var );
if (! isset( $var ) ) $var = NULL;
while ( is_object( $var ) and method_exists( $var, 'templateValue' ) )
$var = $var->templateValue();
$varData = array( 'value' => $var );
$tpl->processOperator( 'alphabet',
array (
),
$rootNamespace, $currentNamespace, $varData, false, false );
$var = $varData['value'];
unset( $varData );
if (! isset( $var ) ) $var = NULL;
while ( is_object( $var ) and method_exists( $var, 'templateValue' ) )
$var = $var->templateValue();
if ( !isset( $vars[$currentNamespace]['alphabet'] ) )
{
$vars[$currentNamespace]['alphabet'] = $var;
unset( $var );
$setArray[$currentNamespace]['alphabet'] = true;
}
if ( !isset( $vars[$currentNamespace]['node_id'] ) )
{
$vars[$currentNamespace]['node_id'] = false;
$setArray[$currentNamespace]['node_id'] = true;
}
if ( !isset( $vars[$currentNamespace]['page_uri_suffix'] ) )
{
$vars[$currentNamespace]['page_uri_suffix'] = false;
$setArray[$currentNamespace]['page_uri_suffix'] = true;
}
unset( $var );
unset( $var1 );
unset( $var2 );
unset( $var3 );
unset( $var3 );
$var3 = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'item_count', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['item_count'] : null;
if (! isset( $var3 ) ) $var3 = NULL;
while ( is_object( $var3 ) and method_exists( $var3, 'templateValue' ) )
$var3 = $var3->templateValue();
while ( is_object( $var3 ) and method_exists( $var3, 'templateValue' ) )
$var3 = $var3->templateValue();
unset( $var4 );
unset( $var4 );
$var4 = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'item_limit', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['item_limit'] : null;
if (! isset( $var4 ) ) $var4 = NULL;
while ( is_object( $var4 ) and method_exists( $var4, 'templateValue' ) )
$var4 = $var4->templateValue();
while ( is_object( $var4 ) and method_exists( $var4, 'templateValue' ) )
$var4 = $var4->templateValue();
@$var2 = $var3 / $var4;
unset( $var3, $var4 );
if (! isset( $var2 ) ) $var2 = NULL;
while ( is_object( $var2 ) and method_exists( $var2, 'templateValue' ) )
$var2 = $var2->templateValue();
$var1 = ceil( $var2 );
unset( $var2 );
if (! isset( $var1 ) ) $var1 = NULL;
while ( is_object( $var1 ) and method_exists( $var1, 'templateValue' ) )
$var1 = $var1->templateValue();
$var = (int)$var1;
unset( $var1 );
if (! isset( $var ) ) $var = NULL;
while ( is_object( $var ) and method_exists( $var, 'templateValue' ) )
$var = $var->templateValue();
if ( !isset( $vars[$currentNamespace]['page_count'] ) )
{
$vars[$currentNamespace]['page_count'] = $var;
unset( $var );
$setArray[$currentNamespace]['page_count'] = true;
}
$text .= '
';
// if begins
unset( $if_cond );
unset( $if_cond1 );
unset( $if_cond2 );
unset( $if_cond2 );
$if_cond2 = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'node_id', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['node_id'] : null;
if (! isset( $if_cond2 ) ) $if_cond2 = NULL;
while ( is_object( $if_cond2 ) and method_exists( $if_cond2, 'templateValue' ) )
$if_cond2 = $if_cond2->templateValue();
$if_cond1 = ( ( $if_cond2 ) != ( false ) );
unset( $if_cond2 );
if (! isset( $if_cond1 ) ) $if_cond1 = NULL;
while ( is_object( $if_cond1 ) and method_exists( $if_cond1, 'templateValue' ) )
$if_cond1 = $if_cond1->templateValue();
if ( !$if_cond1 )
$if_cond = false;
else if ( !true )
$if_cond = false;
else
$if_cond = true;
unset( $if_cond1 );
if (! isset( $if_cond ) ) $if_cond = NULL;
while ( is_object( $if_cond ) and method_exists( $if_cond, 'templateValue' ) )
$if_cond = $if_cond->templateValue();
if ( $if_cond )
{
$text .= ' ';
// def $alphabet_tmp
unset( $var );
unset( $var1 );
unset( $var1 );
$var1 = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'alphabet', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['alphabet'] : null;
if (! isset( $var1 ) ) $var1 = NULL;
while ( is_object( $var1 ) and method_exists( $var1, 'templateValue' ) )
$var1 = $var1->templateValue();
while ( is_object( $var1 ) and method_exists( $var1, 'templateValue' ) )
$var1 = $var1->templateValue();
$var = array_merge( $var1, array( "others" ) );
unset( $var1 );
if (! isset( $var ) ) $var = NULL;
while ( is_object( $var ) and method_exists( $var, 'templateValue' ) )
$var = $var->templateValue();
if ( $tpl->hasVariable( 'alphabet_tmp', $rootNamespace ) )
{
$tpl->warning( 'def', "Variable 'alphabet_tmp' is already defined.", array (
0 =>
array (
0 => 25,
1 => 6,
2 => 1059,
),
1 =>
array (
0 => 26,
1 => 34,
2 => 1149,
),
2 => 'design/admin/templates/navigator/alphabetical.tpl',
) );
$tpl->setVariable( 'alphabet_tmp', $var, $rootNamespace );
}
else
{
$tpl->setLocalVariable( 'alphabet_tmp', $var, $rootNamespace );
}
// def $hash_by_letter
if ( $tpl->hasVariable( 'hash_by_letter', $rootNamespace ) )
{
$tpl->warning( 'def', "Variable 'hash_by_letter' is already defined.", array (
0 =>
array (
0 => 25,
1 => 6,
2 => 1059,
),
1 =>
array (
0 => 26,
1 => 34,
2 => 1149,
),
2 => 'design/admin/templates/navigator/alphabetical.tpl',
) );
$tpl->setVariable( 'hash_by_letter', false, $rootNamespace );
}
else
{
$tpl->setLocalVariable( 'hash_by_letter', false, $rootNamespace );
}
$text .= ' ';
// foreach begins
$skipDelimiter = true;
if ( !isset( $fe_variable_stack_cc7a006f362346f674a27d9ed08c0044_26 ) ) $fe_variable_stack_cc7a006f362346f674a27d9ed08c0044_26 = array();
$fe_variable_stack_cc7a006f362346f674a27d9ed08c0044_26[] = compact( 'fe_array_cc7a006f362346f674a27d9ed08c0044_26', 'fe_array_keys_cc7a006f362346f674a27d9ed08c0044_26', 'fe_n_items_cc7a006f362346f674a27d9ed08c0044_26', 'fe_n_items_processed_cc7a006f362346f674a27d9ed08c0044_26', 'fe_i_cc7a006f362346f674a27d9ed08c0044_26', 'fe_key_cc7a006f362346f674a27d9ed08c0044_26', 'fe_val_cc7a006f362346f674a27d9ed08c0044_26', 'fe_offset_cc7a006f362346f674a27d9ed08c0044_26', 'fe_max_cc7a006f362346f674a27d9ed08c0044_26', 'fe_reverse_cc7a006f362346f674a27d9ed08c0044_26', 'fe_first_val_cc7a006f362346f674a27d9ed08c0044_26', 'fe_last_val_cc7a006f362346f674a27d9ed08c0044_26' );
unset( $fe_array_cc7a006f362346f674a27d9ed08c0044_26 );
unset( $fe_array_cc7a006f362346f674a27d9ed08c0044_26 );
$fe_array_cc7a006f362346f674a27d9ed08c0044_26 = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'alphabet_tmp', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['alphabet_tmp'] : null;
if (! isset( $fe_array_cc7a006f362346f674a27d9ed08c0044_26 ) ) $fe_array_cc7a006f362346f674a27d9ed08c0044_26 = NULL;
while ( is_object( $fe_array_cc7a006f362346f674a27d9ed08c0044_26 ) and method_exists( $fe_array_cc7a006f362346f674a27d9ed08c0044_26, 'templateValue' ) )
$fe_array_cc7a006f362346f674a27d9ed08c0044_26 = $fe_array_cc7a006f362346f674a27d9ed08c0044_26->templateValue();
$fe_array_keys_cc7a006f362346f674a27d9ed08c0044_26 = is_array( $fe_array_cc7a006f362346f674a27d9ed08c0044_26 ) ? array_keys( $fe_array_cc7a006f362346f674a27d9ed08c0044_26 ) : array();
$fe_n_items_cc7a006f362346f674a27d9ed08c0044_26 = count( $fe_array_keys_cc7a006f362346f674a27d9ed08c0044_26 );
$fe_n_items_processed_cc7a006f362346f674a27d9ed08c0044_26 = 0;
$fe_offset_cc7a006f362346f674a27d9ed08c0044_26 = 0;
$fe_max_cc7a006f362346f674a27d9ed08c0044_26 = $fe_n_items_cc7a006f362346f674a27d9ed08c0044_26 - $fe_offset_cc7a006f362346f674a27d9ed08c0044_26;
$fe_reverse_cc7a006f362346f674a27d9ed08c0044_26 = false;
if ( $fe_offset_cc7a006f362346f674a27d9ed08c0044_26 < 0 || $fe_offset_cc7a006f362346f674a27d9ed08c0044_26 >= $fe_n_items_cc7a006f362346f674a27d9ed08c0044_26 )
{
$fe_offset_cc7a006f362346f674a27d9ed08c0044_26 = ( $fe_offset_cc7a006f362346f674a27d9ed08c0044_26 < 0 ) ? 0 : $fe_n_items_cc7a006f362346f674a27d9ed08c0044_26;
if ( $fe_n_items_cc7a006f362346f674a27d9ed08c0044_26 || $fe_offset_cc7a006f362346f674a27d9ed08c0044_26 < 0 )
{
eZDebug::writeWarning("Invalid 'offset' parameter specified: '$fe_offset_cc7a006f362346f674a27d9ed08c0044_26'. Array count: $fe_n_items_cc7a006f362346f674a27d9ed08c0044_26");
}
}
if ( $fe_max_cc7a006f362346f674a27d9ed08c0044_26 < 0 || $fe_offset_cc7a006f362346f674a27d9ed08c0044_26 + $fe_max_cc7a006f362346f674a27d9ed08c0044_26 > $fe_n_items_cc7a006f362346f674a27d9ed08c0044_26 )
{
if ( $fe_max_cc7a006f362346f674a27d9ed08c0044_26 < 0 )
eZDebug::writeWarning("Invalid 'max' parameter specified: $fe_max_cc7a006f362346f674a27d9ed08c0044_26");
$fe_max_cc7a006f362346f674a27d9ed08c0044_26 = $fe_n_items_cc7a006f362346f674a27d9ed08c0044_26 - $fe_offset_cc7a006f362346f674a27d9ed08c0044_26;
}
if ( $fe_reverse_cc7a006f362346f674a27d9ed08c0044_26 )
{
$fe_first_val_cc7a006f362346f674a27d9ed08c0044_26 = $fe_n_items_cc7a006f362346f674a27d9ed08c0044_26 - 1 - $fe_offset_cc7a006f362346f674a27d9ed08c0044_26;
$fe_last_val_cc7a006f362346f674a27d9ed08c0044_26 = 0;
}
else
{
$fe_first_val_cc7a006f362346f674a27d9ed08c0044_26 = $fe_offset_cc7a006f362346f674a27d9ed08c0044_26;
$fe_last_val_cc7a006f362346f674a27d9ed08c0044_26 = $fe_n_items_cc7a006f362346f674a27d9ed08c0044_26 - 1;
}
// foreach
for ( $fe_i_cc7a006f362346f674a27d9ed08c0044_26 = $fe_first_val_cc7a006f362346f674a27d9ed08c0044_26; $fe_n_items_processed_cc7a006f362346f674a27d9ed08c0044_26 < $fe_max_cc7a006f362346f674a27d9ed08c0044_26 && ( $fe_reverse_cc7a006f362346f674a27d9ed08c0044_26 ? $fe_i_cc7a006f362346f674a27d9ed08c0044_26 >= $fe_last_val_cc7a006f362346f674a27d9ed08c0044_26 : $fe_i_cc7a006f362346f674a27d9ed08c0044_26 <= $fe_last_val_cc7a006f362346f674a27d9ed08c0044_26 ); $fe_reverse_cc7a006f362346f674a27d9ed08c0044_26 ? $fe_i_cc7a006f362346f674a27d9ed08c0044_26-- : $fe_i_cc7a006f362346f674a27d9ed08c0044_26++ )
{
$fe_key_cc7a006f362346f674a27d9ed08c0044_26 = $fe_array_keys_cc7a006f362346f674a27d9ed08c0044_26[$fe_i_cc7a006f362346f674a27d9ed08c0044_26];
$fe_val_cc7a006f362346f674a27d9ed08c0044_26 = $fe_array_cc7a006f362346f674a27d9ed08c0044_26[$fe_key_cc7a006f362346f674a27d9ed08c0044_26];
$vars[$rootNamespace]['letter'] = $fe_val_cc7a006f362346f674a27d9ed08c0044_26;
$text .= ' ';
unset( $var );
unset( $var1 );
unset( $var1 );
$var1 = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'letter', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['letter'] : null;
if (! isset( $var1 ) ) $var1 = NULL;
while ( is_object( $var1 ) and method_exists( $var1, 'templateValue' ) )
$var1 = $var1->templateValue();
while ( is_object( $var1 ) and method_exists( $var1, 'templateValue' ) )
$var1 = $var1->templateValue();
unset( $var2 );
unset( $var3 );
unset( $var3 );
$var3 = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'node_id', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['node_id'] : null;
if (! isset( $var3 ) ) $var3 = NULL;
while ( is_object( $var3 ) and method_exists( $var3, 'templateValue' ) )
$var3 = $var3->templateValue();
while ( is_object( $var3 ) and method_exists( $var3, 'templateValue' ) )
$var3 = $var3->templateValue();
unset( $var4 );
unset( $var4 );
$var4 = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'letter', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['letter'] : null;
if (! isset( $var4 ) ) $var4 = NULL;
while ( is_object( $var4 ) and method_exists( $var4, 'templateValue' ) )
$var4 = $var4->templateValue();
while ( is_object( $var4 ) and method_exists( $var4, 'templateValue' ) )
$var4 = $var4->templateValue();
$var2 = call_user_func_array( array( new eZContentFunctionCollection(), 'fetchObjectTreeCount' ),
array( 'parent_node_id' => $var3,
'only_translated' => false,
'language' => false,
'class_filter_type' => false,
'class_filter_array' => false,
'attribute_filter' => false,
'depth' => 1,
'depth_operator' => "le",
'ignore_visibility' => false,
'limitation' => null,
'main_node_only' => false,
'extended_attribute_filter' => false,
'objectname_filter' => $var4 ) );
$var2 = isset( $var2['result'] ) ? $var2['result'] : null;
unset( $var3, $var4 );
if (! isset( $var2 ) ) $var2 = NULL;
while ( is_object( $var2 ) and method_exists( $var2, 'templateValue' ) )
$var2 = $var2->templateValue();
$var = array( $var1 => $var2 );unset( $var1, $var2 );
if (! isset( $var ) ) $var = NULL;
while ( is_object( $var ) and method_exists( $var, 'templateValue' ) )
$var = $var->templateValue();
if ( array_key_exists( $currentNamespace, $vars ) && array_key_exists( 'hash_by_letter', $vars[$currentNamespace] ) )
{
$vars[$currentNamespace]['hash_by_letter'] = $var;
unset( $var );
}
$text .= ' ';
// if begins
unset( $if_cond );
unset( $if_cond1 );
if (! isset( $if_cond1 ) ) $if_cond1 = NULL;
while ( is_object( $if_cond1 ) and method_exists( $if_cond1, 'templateValue' ) )
$if_cond1 = $if_cond1->templateValue();
$if_cond1Data = array( 'value' => $if_cond1 );
$tpl->processOperator( 'count',
array (
0 =>
array (
0 =>
array (
0 => 4,
1 =>
array (
0 => '',
1 => 2,
2 => 'children_count_by_letter',
),
2 => false,
),
),
),
$rootNamespace, $currentNamespace, $if_cond1Data, false, false );
$if_cond1 = $if_cond1Data['value'];
unset( $if_cond1Data );
if (! isset( $if_cond1 ) ) $if_cond1 = NULL;
while ( is_object( $if_cond1 ) and method_exists( $if_cond1, 'templateValue' ) )
$if_cond1 = $if_cond1->templateValue();
$if_cond = ( ( $if_cond1 ) == ( 0 ) );
unset( $if_cond1 );
if (! isset( $if_cond ) ) $if_cond = NULL;
while ( is_object( $if_cond ) and method_exists( $if_cond, 'templateValue' ) )
$if_cond = $if_cond->templateValue();
if ( $if_cond )
{
$text .= ' ';
unset( $var );
unset( $var );
$var = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'hash_by_letter', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['hash_by_letter'] : null;
if (! isset( $var ) ) $var = NULL;
while ( is_object( $var ) and method_exists( $var, 'templateValue' ) )
$var = $var->templateValue();
if ( array_key_exists( $currentNamespace, $vars ) && array_key_exists( 'children_count_by_letter', $vars[$currentNamespace] ) )
{
$vars[$currentNamespace]['children_count_by_letter'] = $var;
unset( $var );
}
$text .= ' ';
}
else
{
$text .= ' ';
unset( $var );
unset( $var1 );
unset( $var1 );
$var1 = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'hash_by_letter', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['hash_by_letter'] : null;
if (! isset( $var1 ) ) $var1 = NULL;
while ( is_object( $var1 ) and method_exists( $var1, 'templateValue' ) )
$var1 = $var1->templateValue();
while ( is_object( $var1 ) and method_exists( $var1, 'templateValue' ) )
$var1 = $var1->templateValue();
unset( $var2 );
unset( $var2 );
$var2 = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'children_count_by_letter', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['children_count_by_letter'] : null;
if (! isset( $var2 ) ) $var2 = NULL;
while ( is_object( $var2 ) and method_exists( $var2, 'templateValue' ) )
$var2 = $var2->templateValue();
while ( is_object( $var2 ) and method_exists( $var2, 'templateValue' ) )
$var2 = $var2->templateValue();
$var = array_merge( $var1, $var2 );
unset( $var1, $var2 );
if (! isset( $var ) ) $var = NULL;
while ( is_object( $var ) and method_exists( $var, 'templateValue' ) )
$var = $var->templateValue();
if ( array_key_exists( $currentNamespace, $vars ) && array_key_exists( 'children_count_by_letter', $vars[$currentNamespace] ) )
{
$vars[$currentNamespace]['children_count_by_letter'] = $var;
unset( $var );
}
$text .= ' ';
}
unset( $if_cond );
// if ends
$text .= ' ';
$fe_n_items_processed_cc7a006f362346f674a27d9ed08c0044_26++;
} // foreach
$skipDelimiter = false;
if ( count( $fe_variable_stack_cc7a006f362346f674a27d9ed08c0044_26 ) ) extract( array_pop( $fe_variable_stack_cc7a006f362346f674a27d9ed08c0044_26 ) );
else
{
unset( $fe_array_cc7a006f362346f674a27d9ed08c0044_26 );
unset( $fe_array_keys_cc7a006f362346f674a27d9ed08c0044_26 );
unset( $fe_n_items_cc7a006f362346f674a27d9ed08c0044_26 );
unset( $fe_n_items_processed_cc7a006f362346f674a27d9ed08c0044_26 );
unset( $fe_i_cc7a006f362346f674a27d9ed08c0044_26 );
unset( $fe_key_cc7a006f362346f674a27d9ed08c0044_26 );
unset( $fe_val_cc7a006f362346f674a27d9ed08c0044_26 );
unset( $fe_offset_cc7a006f362346f674a27d9ed08c0044_26 );
unset( $fe_max_cc7a006f362346f674a27d9ed08c0044_26 );
unset( $fe_reverse_cc7a006f362346f674a27d9ed08c0044_26 );
unset( $fe_first_val_cc7a006f362346f674a27d9ed08c0044_26 );
unset( $fe_last_val_cc7a006f362346f674a27d9ed08c0044_26 );
unset( $fe_variable_stack_cc7a006f362346f674a27d9ed08c0044_26 );
}
// foreach ends
$text .= ' ';
// undef $alphabet_tmp
$tpl->unsetLocalVariable( 'alphabet_tmp', $rootNamespace );
// undef $hash_by_letter
$tpl->unsetLocalVariable( 'hash_by_letter', $rootNamespace );
$text .= ' ';
}
unset( $if_cond );
// if ends
$text .= '
';
// if begins
unset( $if_cond );
unset( $if_cond1 );
unset( $if_cond1 );
$if_cond1 = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'view_parameters', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['view_parameters'] : null;
$if_cond2 = compiledFetchAttribute( $if_cond1, 'namefilter' );
unset( $if_cond1 );
$if_cond1 = $if_cond2;
if (! isset( $if_cond1 ) ) $if_cond1 = NULL;
while ( is_object( $if_cond1 ) and method_exists( $if_cond1, 'templateValue' ) )
$if_cond1 = $if_cond1->templateValue();
$if_cond = isset( $if_cond1 );unset( $if_cond1 );
if (! isset( $if_cond ) ) $if_cond = NULL;
while ( is_object( $if_cond ) and method_exists( $if_cond, 'templateValue' ) )
$if_cond = $if_cond->templateValue();
if ( $if_cond )
{
$text .= ' ';
unset( $var );
unset( $var );
$var = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'view_parameters', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['view_parameters'] : null;
$var1 = compiledFetchAttribute( $var, 'namefilter' );
unset( $var );
$var = $var1;
if (! isset( $var ) ) $var = NULL;
while ( is_object( $var ) and method_exists( $var, 'templateValue' ) )
$var = $var->templateValue();
if ( array_key_exists( $currentNamespace, $vars ) && array_key_exists( 'objectname_filter', $vars[$currentNamespace] ) )
{
$vars[$currentNamespace]['objectname_filter'] = $var;
unset( $var );
}
$text .= ' ';
}
unset( $if_cond );
// if ends
$text .= '
';
// if begins
unset( $if_cond );
unset( $if_cond1 );
unset( $if_cond2 );
unset( $if_cond2 );
$if_cond2 = ( array_key_exists( $currentNamespace, $vars ) and array_key_exists( 'objectname_filter', $vars[$currentNamespace] ) ) ? $vars[$currentNamespace]['objectname_filter'] : null;
if (! isset( $if_cond2 ) ) $if_cond2 = NULL;
while ( is_object( $if_cond2 ) and method_exists( $if_cond2, 'templateValue' ) )
$if_cond2 = $if_cond2->templateValue();
$if_cond1 = ( ( $if_cond2 ) == ( false ) );
unset( $if_cond2 );
if (! isset( $if_cond1 ) ) $if_cond1 = NULL;
while ( is_object( $if_cond1 ) and method_exists( $if_cond1, 'templateValue' ) )
$if_cond1 = $if_cond1->templateValue();
unset( $if_cond2 );
unset( $if_cond3 );
unset( $if_cond3 );
$if_cond3 = ( array_key_exists( $currentNamespace, $vars ) and array_key_exists( 'page_count', $vars[$currentNamespace] ) ) ? $vars[$currentNamespace]['page_count'] : null;
if (! isset( $if_cond3 ) ) $if_cond3 = NULL;
while ( is_object( $if_cond3 ) and method_exists( $if_cond3, 'templateValue' ) )
$if_cond3 = $if_cond3->templateValue();
$if_cond2 = ( ( $if_cond3 ) == ( 0 ) );
unset( $if_cond3 );
if (! isset( $if_cond2 ) ) $if_cond2 = NULL;
while ( is_object( $if_cond2 ) and method_exists( $if_cond2, 'templateValue' ) )
$if_cond2 = $if_cond2->templateValue();
if ( !$if_cond1 )
$if_cond = false;
else if ( !$if_cond2 )
$if_cond = false;
else
$if_cond = $if_cond2;
unset( $if_cond1, $if_cond2 );
if (! isset( $if_cond ) ) $if_cond = NULL;
while ( is_object( $if_cond ) and method_exists( $if_cond, 'templateValue' ) )
$if_cond = $if_cond->templateValue();
if ( $if_cond )
{
$text .= '
';
}
else
{
$text .= ' <div class="break"></div>
<div class="pagenavigator alphabetical">
<p>
';
$vars[$currentNamespace]['c'] = 0;
$text .= ' <span class="pages">
';
// if begins
unset( $if_cond );
unset( $if_cond1 );
unset( $if_cond1 );
$if_cond1 = ( array_key_exists( $currentNamespace, $vars ) and array_key_exists( 'objectname_filter', $vars[$currentNamespace] ) ) ? $vars[$currentNamespace]['objectname_filter'] : null;
if (! isset( $if_cond1 ) ) $if_cond1 = NULL;
while ( is_object( $if_cond1 ) and method_exists( $if_cond1, 'templateValue' ) )
$if_cond1 = $if_cond1->templateValue();
$if_cond = ( ( $if_cond1 ) == ( false ) );
unset( $if_cond1 );
if (! isset( $if_cond ) ) $if_cond = NULL;
while ( is_object( $if_cond ) and method_exists( $if_cond, 'templateValue' ) )
$if_cond = $if_cond->templateValue();
if ( $if_cond )
{
$text .= '<span class="current">*</span>';
}
else
{
$text .= '<span class="other"><a href=';
unset( $var );
unset( $var1 );
unset( $var2 );
unset( $var2 );
$var2 = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'page_uri', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['page_uri'] : null;
if (! isset( $var2 ) ) $var2 = NULL;
while ( is_object( $var2 ) and method_exists( $var2, 'templateValue' ) )
$var2 = $var2->templateValue();
while ( is_object( $var2 ) and method_exists( $var2, 'templateValue' ) )
$var2 = $var2->templateValue();
unset( $var3 );
unset( $var3 );
$var3 = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'page_uri_suffix', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['page_uri_suffix'] : null;
if (! isset( $var3 ) ) $var3 = NULL;
while ( is_object( $var3 ) and method_exists( $var3, 'templateValue' ) )
$var3 = $var3->templateValue();
while ( is_object( $var3 ) and method_exists( $var3, 'templateValue' ) )
$var3 = $var3->templateValue();
$var1 = ( $var2 . $var3 );
unset( $var2, $var3 );
if (! isset( $var1 ) ) $var1 = NULL;
while ( is_object( $var1 ) and method_exists( $var1, 'templateValue' ) )
$var1 = $var1->templateValue();
eZURI::transformURI( $var1, false, eZURI::getTransformURIMode() );
$var1 = '"' . $var1 . '"';
$var = $var1;
unset( $var1 );
if (! isset( $var ) ) $var = NULL;
while ( is_object( $var ) and method_exists( $var, 'templateValue' ) )
$var = $var->templateValue();
$text .= $var;
unset( $var );
$text .= '>*</a></span>';
}
unset( $if_cond );
// if ends
$text .= '
';
// if begins
unset( $if_cond );
unset( $if_cond1 );
unset( $if_cond1 );
$if_cond1 = ( array_key_exists( $currentNamespace, $vars ) and array_key_exists( 'objectname_filter', $vars[$currentNamespace] ) ) ? $vars[$currentNamespace]['objectname_filter'] : null;
if (! isset( $if_cond1 ) ) $if_cond1 = NULL;
while ( is_object( $if_cond1 ) and method_exists( $if_cond1, 'templateValue' ) )
$if_cond1 = $if_cond1->templateValue();
$if_cond = ( ( $if_cond1 ) == ( 'others' ) );
unset( $if_cond1 );
if (! isset( $if_cond ) ) $if_cond = NULL;
while ( is_object( $if_cond ) and method_exists( $if_cond, 'templateValue' ) )
$if_cond = $if_cond->templateValue();
if ( $if_cond )
{
$text .= ' <span class="current">others</span>
';
}
else
{
$text .= ' <span class="other">
';
// if begins
unset( $if_cond );
unset( $if_cond1 );
unset( $if_cond2 );
unset( $if_cond3 );
unset( $if_cond3 );
$if_cond3 = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'children_count_by_letter', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['children_count_by_letter'] : null;
if (! isset( $if_cond3 ) ) $if_cond3 = NULL;
while ( is_object( $if_cond3 ) and method_exists( $if_cond3, 'templateValue' ) )
$if_cond3 = $if_cond3->templateValue();
$if_cond2 = ( ( $if_cond3 ) != ( false ) );
unset( $if_cond3 );
if (! isset( $if_cond2 ) ) $if_cond2 = NULL;
while ( is_object( $if_cond2 ) and method_exists( $if_cond2, 'templateValue' ) )
$if_cond2 = $if_cond2->templateValue();
unset( $if_cond3 );
unset( $if_cond4 );
unset( $if_cond4 );
$if_cond4 = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'children_count_by_letter', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['children_count_by_letter'] : null;
$if_cond5 = compiledFetchAttribute( $if_cond4, 'others' );
unset( $if_cond4 );
$if_cond4 = $if_cond5;
if (! isset( $if_cond4 ) ) $if_cond4 = NULL;
while ( is_object( $if_cond4 ) and method_exists( $if_cond4, 'templateValue' ) )
$if_cond4 = $if_cond4->templateValue();
$if_cond3 = ( ( $if_cond4 ) > ( 0 ) );
unset( $if_cond4 );
if (! isset( $if_cond3 ) ) $if_cond3 = NULL;
while ( is_object( $if_cond3 ) and method_exists( $if_cond3, 'templateValue' ) )
$if_cond3 = $if_cond3->templateValue();
if ( !$if_cond2 )
$if_cond1 = false;
else if ( !$if_cond3 )
$if_cond1 = false;
else
$if_cond1 = $if_cond3;
unset( $if_cond2, $if_cond3 );
if (! isset( $if_cond1 ) ) $if_cond1 = NULL;
while ( is_object( $if_cond1 ) and method_exists( $if_cond1, 'templateValue' ) )
$if_cond1 = $if_cond1->templateValue();
unset( $if_cond2 );
unset( $if_cond3 );
unset( $if_cond3 );
$if_cond3 = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'children_count_by_letter', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['children_count_by_letter'] : null;
if (! isset( $if_cond3 ) ) $if_cond3 = NULL;
while ( is_object( $if_cond3 ) and method_exists( $if_cond3, 'templateValue' ) )
$if_cond3 = $if_cond3->templateValue();
$if_cond2 = ( ( $if_cond3 ) == ( false ) );
unset( $if_cond3 );
if (! isset( $if_cond2 ) ) $if_cond2 = NULL;
while ( is_object( $if_cond2 ) and method_exists( $if_cond2, 'templateValue' ) )
$if_cond2 = $if_cond2->templateValue();
if ( $if_cond1 )
$if_cond = $if_cond1;
else if ( $if_cond2 )
$if_cond = $if_cond2;
else
$if_cond = false;
unset( $if_cond1, $if_cond2 );
if (! isset( $if_cond ) ) $if_cond = NULL;
while ( is_object( $if_cond ) and method_exists( $if_cond, 'templateValue' ) )
$if_cond = $if_cond->templateValue();
if ( $if_cond )
{
$text .= ' <a href=';
unset( $var );
unset( $var1 );
unset( $var2 );
unset( $var2 );
$var2 = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'page_uri', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['page_uri'] : null;
if (! isset( $var2 ) ) $var2 = NULL;
while ( is_object( $var2 ) and method_exists( $var2, 'templateValue' ) )
$var2 = $var2->templateValue();
while ( is_object( $var2 ) and method_exists( $var2, 'templateValue' ) )
$var2 = $var2->templateValue();
unset( $var5 );
unset( $var5 );
$var5 = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'page_uri_suffix', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['page_uri_suffix'] : null;
if (! isset( $var5 ) ) $var5 = NULL;
while ( is_object( $var5 ) and method_exists( $var5, 'templateValue' ) )
$var5 = $var5->templateValue();
while ( is_object( $var5 ) and method_exists( $var5, 'templateValue' ) )
$var5 = $var5->templateValue();
$var1 = ( $var2 . '/(namefilter)/' . 'others' . $var5 );
unset( $var2, $var5 );
if (! isset( $var1 ) ) $var1 = NULL;
while ( is_object( $var1 ) and method_exists( $var1, 'templateValue' ) )
$var1 = $var1->templateValue();
eZURI::transformURI( $var1, false, eZURI::getTransformURIMode() );
$var1 = '"' . $var1 . '"';
$var = $var1;
unset( $var1 );
if (! isset( $var ) ) $var = NULL;
while ( is_object( $var ) and method_exists( $var, 'templateValue' ) )
$var = $var->templateValue();
$text .= $var;
unset( $var );
$text .= '>
';
}
else
{
$text .= ' <span class="disabled">
';
}
unset( $if_cond );
// if ends
$text .= ' others
';
// if begins
unset( $if_cond );
unset( $if_cond1 );
unset( $if_cond2 );
unset( $if_cond3 );
unset( $if_cond3 );
$if_cond3 = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'children_count_by_letter', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['children_count_by_letter'] : null;
if (! isset( $if_cond3 ) ) $if_cond3 = NULL;
while ( is_object( $if_cond3 ) and method_exists( $if_cond3, 'templateValue' ) )
$if_cond3 = $if_cond3->templateValue();
$if_cond2 = ( ( $if_cond3 ) != ( false ) );
unset( $if_cond3 );
if (! isset( $if_cond2 ) ) $if_cond2 = NULL;
while ( is_object( $if_cond2 ) and method_exists( $if_cond2, 'templateValue' ) )
$if_cond2 = $if_cond2->templateValue();
unset( $if_cond3 );
unset( $if_cond4 );
unset( $if_cond4 );
$if_cond4 = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'children_count_by_letter', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['children_count_by_letter'] : null;
$if_cond5 = compiledFetchAttribute( $if_cond4, 'others' );
unset( $if_cond4 );
$if_cond4 = $if_cond5;
if (! isset( $if_cond4 ) ) $if_cond4 = NULL;
while ( is_object( $if_cond4 ) and method_exists( $if_cond4, 'templateValue' ) )
$if_cond4 = $if_cond4->templateValue();
$if_cond3 = ( ( $if_cond4 ) > ( 0 ) );
unset( $if_cond4 );
if (! isset( $if_cond3 ) ) $if_cond3 = NULL;
while ( is_object( $if_cond3 ) and method_exists( $if_cond3, 'templateValue' ) )
$if_cond3 = $if_cond3->templateValue();
if ( !$if_cond2 )
$if_cond1 = false;
else if ( !$if_cond3 )
$if_cond1 = false;
else
$if_cond1 = $if_cond3;
unset( $if_cond2, $if_cond3 );
if (! isset( $if_cond1 ) ) $if_cond1 = NULL;
while ( is_object( $if_cond1 ) and method_exists( $if_cond1, 'templateValue' ) )
$if_cond1 = $if_cond1->templateValue();
unset( $if_cond2 );
unset( $if_cond3 );
unset( $if_cond3 );
$if_cond3 = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'children_count_by_letter', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['children_count_by_letter'] : null;
if (! isset( $if_cond3 ) ) $if_cond3 = NULL;
while ( is_object( $if_cond3 ) and method_exists( $if_cond3, 'templateValue' ) )
$if_cond3 = $if_cond3->templateValue();
$if_cond2 = ( ( $if_cond3 ) == ( false ) );
unset( $if_cond3 );
if (! isset( $if_cond2 ) ) $if_cond2 = NULL;
while ( is_object( $if_cond2 ) and method_exists( $if_cond2, 'templateValue' ) )
$if_cond2 = $if_cond2->templateValue();
if ( $if_cond1 )
$if_cond = $if_cond1;
else if ( $if_cond2 )
$if_cond = $if_cond2;
else
$if_cond = false;
unset( $if_cond1, $if_cond2 );
if (! isset( $if_cond ) ) $if_cond = NULL;
while ( is_object( $if_cond ) and method_exists( $if_cond, 'templateValue' ) )
$if_cond = $if_cond->templateValue();
if ( $if_cond )
{
$text .= ' </a>
';
}
else
{
$text .= ' </span>
';
}
unset( $if_cond );
// if ends
$text .= ' </span>
';
}
unset( $if_cond );
// if ends
$text .= '
';
// foreach begins
$skipDelimiter = true;
if ( !isset( $fe_variable_stack_cc7a006f362346f674a27d9ed08c0044_27 ) ) $fe_variable_stack_cc7a006f362346f674a27d9ed08c0044_27 = array();
$fe_variable_stack_cc7a006f362346f674a27d9ed08c0044_27[] = compact( 'fe_array_cc7a006f362346f674a27d9ed08c0044_27', 'fe_array_keys_cc7a006f362346f674a27d9ed08c0044_27', 'fe_n_items_cc7a006f362346f674a27d9ed08c0044_27', 'fe_n_items_processed_cc7a006f362346f674a27d9ed08c0044_27', 'fe_i_cc7a006f362346f674a27d9ed08c0044_27', 'fe_key_cc7a006f362346f674a27d9ed08c0044_27', 'fe_val_cc7a006f362346f674a27d9ed08c0044_27', 'fe_offset_cc7a006f362346f674a27d9ed08c0044_27', 'fe_max_cc7a006f362346f674a27d9ed08c0044_27', 'fe_reverse_cc7a006f362346f674a27d9ed08c0044_27', 'fe_first_val_cc7a006f362346f674a27d9ed08c0044_27', 'fe_last_val_cc7a006f362346f674a27d9ed08c0044_27' );
unset( $fe_array_cc7a006f362346f674a27d9ed08c0044_27 );
unset( $fe_array_cc7a006f362346f674a27d9ed08c0044_27 );
$fe_array_cc7a006f362346f674a27d9ed08c0044_27 = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'alphabet', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['alphabet'] : null;
if (! isset( $fe_array_cc7a006f362346f674a27d9ed08c0044_27 ) ) $fe_array_cc7a006f362346f674a27d9ed08c0044_27 = NULL;
while ( is_object( $fe_array_cc7a006f362346f674a27d9ed08c0044_27 ) and method_exists( $fe_array_cc7a006f362346f674a27d9ed08c0044_27, 'templateValue' ) )
$fe_array_cc7a006f362346f674a27d9ed08c0044_27 = $fe_array_cc7a006f362346f674a27d9ed08c0044_27->templateValue();
$fe_array_keys_cc7a006f362346f674a27d9ed08c0044_27 = is_array( $fe_array_cc7a006f362346f674a27d9ed08c0044_27 ) ? array_keys( $fe_array_cc7a006f362346f674a27d9ed08c0044_27 ) : array();
$fe_n_items_cc7a006f362346f674a27d9ed08c0044_27 = count( $fe_array_keys_cc7a006f362346f674a27d9ed08c0044_27 );
$fe_n_items_processed_cc7a006f362346f674a27d9ed08c0044_27 = 0;
$fe_offset_cc7a006f362346f674a27d9ed08c0044_27 = 0;
$fe_max_cc7a006f362346f674a27d9ed08c0044_27 = $fe_n_items_cc7a006f362346f674a27d9ed08c0044_27 - $fe_offset_cc7a006f362346f674a27d9ed08c0044_27;
$fe_reverse_cc7a006f362346f674a27d9ed08c0044_27 = false;
if ( $fe_offset_cc7a006f362346f674a27d9ed08c0044_27 < 0 || $fe_offset_cc7a006f362346f674a27d9ed08c0044_27 >= $fe_n_items_cc7a006f362346f674a27d9ed08c0044_27 )
{
$fe_offset_cc7a006f362346f674a27d9ed08c0044_27 = ( $fe_offset_cc7a006f362346f674a27d9ed08c0044_27 < 0 ) ? 0 : $fe_n_items_cc7a006f362346f674a27d9ed08c0044_27;
if ( $fe_n_items_cc7a006f362346f674a27d9ed08c0044_27 || $fe_offset_cc7a006f362346f674a27d9ed08c0044_27 < 0 )
{
eZDebug::writeWarning("Invalid 'offset' parameter specified: '$fe_offset_cc7a006f362346f674a27d9ed08c0044_27'. Array count: $fe_n_items_cc7a006f362346f674a27d9ed08c0044_27");
}
}
if ( $fe_max_cc7a006f362346f674a27d9ed08c0044_27 < 0 || $fe_offset_cc7a006f362346f674a27d9ed08c0044_27 + $fe_max_cc7a006f362346f674a27d9ed08c0044_27 > $fe_n_items_cc7a006f362346f674a27d9ed08c0044_27 )
{
if ( $fe_max_cc7a006f362346f674a27d9ed08c0044_27 < 0 )
eZDebug::writeWarning("Invalid 'max' parameter specified: $fe_max_cc7a006f362346f674a27d9ed08c0044_27");
$fe_max_cc7a006f362346f674a27d9ed08c0044_27 = $fe_n_items_cc7a006f362346f674a27d9ed08c0044_27 - $fe_offset_cc7a006f362346f674a27d9ed08c0044_27;
}
if ( $fe_reverse_cc7a006f362346f674a27d9ed08c0044_27 )
{
$fe_first_val_cc7a006f362346f674a27d9ed08c0044_27 = $fe_n_items_cc7a006f362346f674a27d9ed08c0044_27 - 1 - $fe_offset_cc7a006f362346f674a27d9ed08c0044_27;
$fe_last_val_cc7a006f362346f674a27d9ed08c0044_27 = 0;
}
else
{
$fe_first_val_cc7a006f362346f674a27d9ed08c0044_27 = $fe_offset_cc7a006f362346f674a27d9ed08c0044_27;
$fe_last_val_cc7a006f362346f674a27d9ed08c0044_27 = $fe_n_items_cc7a006f362346f674a27d9ed08c0044_27 - 1;
}
// foreach
for ( $fe_i_cc7a006f362346f674a27d9ed08c0044_27 = $fe_first_val_cc7a006f362346f674a27d9ed08c0044_27; $fe_n_items_processed_cc7a006f362346f674a27d9ed08c0044_27 < $fe_max_cc7a006f362346f674a27d9ed08c0044_27 && ( $fe_reverse_cc7a006f362346f674a27d9ed08c0044_27 ? $fe_i_cc7a006f362346f674a27d9ed08c0044_27 >= $fe_last_val_cc7a006f362346f674a27d9ed08c0044_27 : $fe_i_cc7a006f362346f674a27d9ed08c0044_27 <= $fe_last_val_cc7a006f362346f674a27d9ed08c0044_27 ); $fe_reverse_cc7a006f362346f674a27d9ed08c0044_27 ? $fe_i_cc7a006f362346f674a27d9ed08c0044_27-- : $fe_i_cc7a006f362346f674a27d9ed08c0044_27++ )
{
$fe_key_cc7a006f362346f674a27d9ed08c0044_27 = $fe_array_keys_cc7a006f362346f674a27d9ed08c0044_27[$fe_i_cc7a006f362346f674a27d9ed08c0044_27];
$fe_val_cc7a006f362346f674a27d9ed08c0044_27 = $fe_array_cc7a006f362346f674a27d9ed08c0044_27[$fe_key_cc7a006f362346f674a27d9ed08c0044_27];
$vars[$rootNamespace]['letter'] = $fe_val_cc7a006f362346f674a27d9ed08c0044_27;
$text .= ' ';
// if begins
unset( $if_cond );
unset( $if_cond1 );
unset( $if_cond1 );
$if_cond1 = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'letter', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['letter'] : null;
if (! isset( $if_cond1 ) ) $if_cond1 = NULL;
while ( is_object( $if_cond1 ) and method_exists( $if_cond1, 'templateValue' ) )
$if_cond1 = $if_cond1->templateValue();
unset( $if_cond2 );
unset( $if_cond2 );
$if_cond2 = ( array_key_exists( $currentNamespace, $vars ) and array_key_exists( 'objectname_filter', $vars[$currentNamespace] ) ) ? $vars[$currentNamespace]['objectname_filter'] : null;
if (! isset( $if_cond2 ) ) $if_cond2 = NULL;
while ( is_object( $if_cond2 ) and method_exists( $if_cond2, 'templateValue' ) )
$if_cond2 = $if_cond2->templateValue();
$if_cond = ( ( $if_cond1 ) == ( $if_cond2 ) );
unset( $if_cond1, $if_cond2 );
if (! isset( $if_cond ) ) $if_cond = NULL;
while ( is_object( $if_cond ) and method_exists( $if_cond, 'templateValue' ) )
$if_cond = $if_cond->templateValue();
if ( $if_cond )
{
$text .= ' <span class="current">';
unset( $var );
unset( $var );
$var = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'letter', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['letter'] : null;
if (! isset( $var ) ) $var = NULL;
while ( is_object( $var ) and method_exists( $var, 'templateValue' ) )
$var = $var->templateValue();
$text .= ( is_object( $var ) ? compiledFetchText( $tpl, $rootNamespace, $currentNamespace, false, $var ) : $var );
unset( $var );
$text .= '</span>
';
}
else
{
$text .= ' <span class="other">
';
// if begins
unset( $if_cond );
unset( $if_cond1 );
unset( $if_cond2 );
unset( $if_cond3 );
unset( $if_cond3 );
$if_cond3 = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'children_count_by_letter', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['children_count_by_letter'] : null;
if (! isset( $if_cond3 ) ) $if_cond3 = NULL;
while ( is_object( $if_cond3 ) and method_exists( $if_cond3, 'templateValue' ) )
$if_cond3 = $if_cond3->templateValue();
$if_cond2 = ( ( $if_cond3 ) != ( false ) );
unset( $if_cond3 );
if (! isset( $if_cond2 ) ) $if_cond2 = NULL;
while ( is_object( $if_cond2 ) and method_exists( $if_cond2, 'templateValue' ) )
$if_cond2 = $if_cond2->templateValue();
unset( $if_cond3 );
unset( $if_cond4 );
unset( $if_cond5 );
unset( $if_cond5 );
$if_cond5 = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'children_count_by_letter', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['children_count_by_letter'] : null;
unset( $if_cond7 );
unset( $if_cond7 );
$if_cond7 = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'letter', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['letter'] : null;
if (! isset( $if_cond7 ) ) $if_cond7 = NULL;
while ( is_object( $if_cond7 ) and method_exists( $if_cond7, 'templateValue' ) )
$if_cond7 = $if_cond7->templateValue();
$if_cond6 = compiledFetchAttribute( $if_cond5, $if_cond7 );
unset( $if_cond5 );
$if_cond5 = $if_cond6;
if (! isset( $if_cond5 ) ) $if_cond5 = NULL;
while ( is_object( $if_cond5 ) and method_exists( $if_cond5, 'templateValue' ) )
$if_cond5 = $if_cond5->templateValue();
$if_cond4 = isset( $if_cond5 );unset( $if_cond5 );
if (! isset( $if_cond4 ) ) $if_cond4 = NULL;
while ( is_object( $if_cond4 ) and method_exists( $if_cond4, 'templateValue' ) )
$if_cond4 = $if_cond4->templateValue();
unset( $if_cond5 );
unset( $if_cond6 );
unset( $if_cond6 );
$if_cond6 = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'children_count_by_letter', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['children_count_by_letter'] : null;
unset( $if_cond8 );
unset( $if_cond8 );
$if_cond8 = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'letter', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['letter'] : null;
if (! isset( $if_cond8 ) ) $if_cond8 = NULL;
while ( is_object( $if_cond8 ) and method_exists( $if_cond8, 'templateValue' ) )
$if_cond8 = $if_cond8->templateValue();
$if_cond7 = compiledFetchAttribute( $if_cond6, $if_cond8 );
unset( $if_cond6 );
$if_cond6 = $if_cond7;
if (! isset( $if_cond6 ) ) $if_cond6 = NULL;
while ( is_object( $if_cond6 ) and method_exists( $if_cond6, 'templateValue' ) )
$if_cond6 = $if_cond6->templateValue();
$if_cond5 = ( ( $if_cond6 ) > ( 0 ) );
unset( $if_cond6 );
if (! isset( $if_cond5 ) ) $if_cond5 = NULL;
while ( is_object( $if_cond5 ) and method_exists( $if_cond5, 'templateValue' ) )
$if_cond5 = $if_cond5->templateValue();
if ( !$if_cond4 )
$if_cond3 = false;
else if ( !$if_cond5 )
$if_cond3 = false;
else
$if_cond3 = $if_cond5;
unset( $if_cond4, $if_cond5 );
if (! isset( $if_cond3 ) ) $if_cond3 = NULL;
while ( is_object( $if_cond3 ) and method_exists( $if_cond3, 'templateValue' ) )
$if_cond3 = $if_cond3->templateValue();
if ( !$if_cond2 )
$if_cond1 = false;
else if ( !$if_cond3 )
$if_cond1 = false;
else
$if_cond1 = $if_cond3;
unset( $if_cond2, $if_cond3 );
if (! isset( $if_cond1 ) ) $if_cond1 = NULL;
while ( is_object( $if_cond1 ) and method_exists( $if_cond1, 'templateValue' ) )
$if_cond1 = $if_cond1->templateValue();
unset( $if_cond2 );
unset( $if_cond3 );
unset( $if_cond3 );
$if_cond3 = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'children_count_by_letter', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['children_count_by_letter'] : null;
if (! isset( $if_cond3 ) ) $if_cond3 = NULL;
while ( is_object( $if_cond3 ) and method_exists( $if_cond3, 'templateValue' ) )
$if_cond3 = $if_cond3->templateValue();
$if_cond2 = ( ( $if_cond3 ) == ( false ) );
unset( $if_cond3 );
if (! isset( $if_cond2 ) ) $if_cond2 = NULL;
while ( is_object( $if_cond2 ) and method_exists( $if_cond2, 'templateValue' ) )
$if_cond2 = $if_cond2->templateValue();
if ( $if_cond1 )
$if_cond = $if_cond1;
else if ( $if_cond2 )
$if_cond = $if_cond2;
else
$if_cond = false;
unset( $if_cond1, $if_cond2 );
if (! isset( $if_cond ) ) $if_cond = NULL;
while ( is_object( $if_cond ) and method_exists( $if_cond, 'templateValue' ) )
$if_cond = $if_cond->templateValue();
if ( $if_cond )
{
$text .= '<a href=';
unset( $var );
unset( $var1 );
unset( $var2 );
unset( $var2 );
$var2 = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'page_uri', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['page_uri'] : null;
if (! isset( $var2 ) ) $var2 = NULL;
while ( is_object( $var2 ) and method_exists( $var2, 'templateValue' ) )
$var2 = $var2->templateValue();
while ( is_object( $var2 ) and method_exists( $var2, 'templateValue' ) )
$var2 = $var2->templateValue();
unset( $var4 );
unset( $var4 );
$var4 = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'letter', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['letter'] : null;
if (! isset( $var4 ) ) $var4 = NULL;
while ( is_object( $var4 ) and method_exists( $var4, 'templateValue' ) )
$var4 = $var4->templateValue();
while ( is_object( $var4 ) and method_exists( $var4, 'templateValue' ) )
$var4 = $var4->templateValue();
unset( $var5 );
unset( $var5 );
$var5 = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'page_uri_suffix', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['page_uri_suffix'] : null;
if (! isset( $var5 ) ) $var5 = NULL;
while ( is_object( $var5 ) and method_exists( $var5, 'templateValue' ) )
$var5 = $var5->templateValue();
while ( is_object( $var5 ) and method_exists( $var5, 'templateValue' ) )
$var5 = $var5->templateValue();
$var1 = ( $var2 . '/(namefilter)/' . $var4 . $var5 );
unset( $var2, $var4, $var5 );
if (! isset( $var1 ) ) $var1 = NULL;
while ( is_object( $var1 ) and method_exists( $var1, 'templateValue' ) )
$var1 = $var1->templateValue();
eZURI::transformURI( $var1, false, eZURI::getTransformURIMode() );
$var1 = '"' . $var1 . '"';
$var = $var1;
unset( $var1 );
if (! isset( $var ) ) $var = NULL;
while ( is_object( $var ) and method_exists( $var, 'templateValue' ) )
$var = $var->templateValue();
$text .= $var;
unset( $var );
$text .= '>
';
}
else
{
$text .= ' <span class="disabled">
';
}
unset( $if_cond );
// if ends
$text .= ' ';
unset( $var );
unset( $var );
$var = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'letter', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['letter'] : null;
if (! isset( $var ) ) $var = NULL;
while ( is_object( $var ) and method_exists( $var, 'templateValue' ) )
$var = $var->templateValue();
$text .= ( is_object( $var ) ? compiledFetchText( $tpl, $rootNamespace, $currentNamespace, false, $var ) : $var );
unset( $var );
// if begins
unset( $if_cond );
unset( $if_cond1 );
unset( $if_cond2 );
unset( $if_cond3 );
unset( $if_cond3 );
$if_cond3 = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'children_count_by_letter', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['children_count_by_letter'] : null;
if (! isset( $if_cond3 ) ) $if_cond3 = NULL;
while ( is_object( $if_cond3 ) and method_exists( $if_cond3, 'templateValue' ) )
$if_cond3 = $if_cond3->templateValue();
$if_cond2 = ( ( $if_cond3 ) != ( false ) );
unset( $if_cond3 );
if (! isset( $if_cond2 ) ) $if_cond2 = NULL;
while ( is_object( $if_cond2 ) and method_exists( $if_cond2, 'templateValue' ) )
$if_cond2 = $if_cond2->templateValue();
unset( $if_cond3 );
unset( $if_cond4 );
unset( $if_cond5 );
unset( $if_cond5 );
$if_cond5 = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'children_count_by_letter', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['children_count_by_letter'] : null;
unset( $if_cond7 );
unset( $if_cond7 );
$if_cond7 = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'letter', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['letter'] : null;
if (! isset( $if_cond7 ) ) $if_cond7 = NULL;
while ( is_object( $if_cond7 ) and method_exists( $if_cond7, 'templateValue' ) )
$if_cond7 = $if_cond7->templateValue();
$if_cond6 = compiledFetchAttribute( $if_cond5, $if_cond7 );
unset( $if_cond5 );
$if_cond5 = $if_cond6;
if (! isset( $if_cond5 ) ) $if_cond5 = NULL;
while ( is_object( $if_cond5 ) and method_exists( $if_cond5, 'templateValue' ) )
$if_cond5 = $if_cond5->templateValue();
$if_cond4 = isset( $if_cond5 );unset( $if_cond5 );
if (! isset( $if_cond4 ) ) $if_cond4 = NULL;
while ( is_object( $if_cond4 ) and method_exists( $if_cond4, 'templateValue' ) )
$if_cond4 = $if_cond4->templateValue();
unset( $if_cond5 );
unset( $if_cond6 );
unset( $if_cond6 );
$if_cond6 = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'children_count_by_letter', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['children_count_by_letter'] : null;
unset( $if_cond8 );
unset( $if_cond8 );
$if_cond8 = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'letter', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['letter'] : null;
if (! isset( $if_cond8 ) ) $if_cond8 = NULL;
while ( is_object( $if_cond8 ) and method_exists( $if_cond8, 'templateValue' ) )
$if_cond8 = $if_cond8->templateValue();
$if_cond7 = compiledFetchAttribute( $if_cond6, $if_cond8 );
unset( $if_cond6 );
$if_cond6 = $if_cond7;
if (! isset( $if_cond6 ) ) $if_cond6 = NULL;
while ( is_object( $if_cond6 ) and method_exists( $if_cond6, 'templateValue' ) )
$if_cond6 = $if_cond6->templateValue();
$if_cond5 = ( ( $if_cond6 ) > ( 0 ) );
unset( $if_cond6 );
if (! isset( $if_cond5 ) ) $if_cond5 = NULL;
while ( is_object( $if_cond5 ) and method_exists( $if_cond5, 'templateValue' ) )
$if_cond5 = $if_cond5->templateValue();
if ( !$if_cond4 )
$if_cond3 = false;
else if ( !$if_cond5 )
$if_cond3 = false;
else
$if_cond3 = $if_cond5;
unset( $if_cond4, $if_cond5 );
if (! isset( $if_cond3 ) ) $if_cond3 = NULL;
while ( is_object( $if_cond3 ) and method_exists( $if_cond3, 'templateValue' ) )
$if_cond3 = $if_cond3->templateValue();
if ( !$if_cond2 )
$if_cond1 = false;
else if ( !$if_cond3 )
$if_cond1 = false;
else
$if_cond1 = $if_cond3;
unset( $if_cond2, $if_cond3 );
if (! isset( $if_cond1 ) ) $if_cond1 = NULL;
while ( is_object( $if_cond1 ) and method_exists( $if_cond1, 'templateValue' ) )
$if_cond1 = $if_cond1->templateValue();
unset( $if_cond2 );
unset( $if_cond3 );
unset( $if_cond3 );
$if_cond3 = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'children_count_by_letter', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['children_count_by_letter'] : null;
if (! isset( $if_cond3 ) ) $if_cond3 = NULL;
while ( is_object( $if_cond3 ) and method_exists( $if_cond3, 'templateValue' ) )
$if_cond3 = $if_cond3->templateValue();
$if_cond2 = ( ( $if_cond3 ) == ( false ) );
unset( $if_cond3 );
if (! isset( $if_cond2 ) ) $if_cond2 = NULL;
while ( is_object( $if_cond2 ) and method_exists( $if_cond2, 'templateValue' ) )
$if_cond2 = $if_cond2->templateValue();
if ( $if_cond1 )
$if_cond = $if_cond1;
else if ( $if_cond2 )
$if_cond = $if_cond2;
else
$if_cond = false;
unset( $if_cond1, $if_cond2 );
if (! isset( $if_cond ) ) $if_cond = NULL;
while ( is_object( $if_cond ) and method_exists( $if_cond, 'templateValue' ) )
$if_cond = $if_cond->templateValue();
if ( $if_cond )
{
$text .= ' </a>
';
}
else
{
$text .= ' </span>
';
}
unset( $if_cond );
// if ends
$text .= ' </span>
';
}
unset( $if_cond );
// if ends
$text .= ' ';
unset( $var );
unset( $var1 );
unset( $var1 );
$var1 = ( array_key_exists( $currentNamespace, $vars ) and array_key_exists( 'c', $vars[$currentNamespace] ) ) ? $vars[$currentNamespace]['c'] : null;
if (! isset( $var1 ) ) $var1 = NULL;
while ( is_object( $var1 ) and method_exists( $var1, 'templateValue' ) )
$var1 = $var1->templateValue();
while ( is_object( $var1 ) and method_exists( $var1, 'templateValue' ) )
$var1 = $var1->templateValue();
$var = $var1 + 1;
unset( $var1 );
if (! isset( $var ) ) $var = NULL;
while ( is_object( $var ) and method_exists( $var, 'templateValue' ) )
$var = $var->templateValue();
if ( array_key_exists( $currentNamespace, $vars ) && array_key_exists( 'c', $vars[$currentNamespace] ) )
{
$vars[$currentNamespace]['c'] = $var;
unset( $var );
}
$text .= ' ';
// if begins
unset( $if_cond );
unset( $if_cond1 );
unset( $if_cond1 );
$if_cond1 = ( array_key_exists( $currentNamespace, $vars ) and array_key_exists( 'c', $vars[$currentNamespace] ) ) ? $vars[$currentNamespace]['c'] : null;
if (! isset( $if_cond1 ) ) $if_cond1 = NULL;
while ( is_object( $if_cond1 ) and method_exists( $if_cond1, 'templateValue' ) )
$if_cond1 = $if_cond1->templateValue();
$if_cond = ( ( $if_cond1 ) > ( 25 ) );
unset( $if_cond1 );
if (! isset( $if_cond ) ) $if_cond = NULL;
while ( is_object( $if_cond ) and method_exists( $if_cond, 'templateValue' ) )
$if_cond = $if_cond->templateValue();
if ( $if_cond )
{
$text .= ' ';
if ( array_key_exists( $currentNamespace, $vars ) && array_key_exists( 'c', $vars[$currentNamespace] ) )
{
$vars[$currentNamespace]['c'] = 0;
}
$text .= ' <br />
';
}
unset( $if_cond );
// if ends
$text .= ' ';
$fe_n_items_processed_cc7a006f362346f674a27d9ed08c0044_27++;
} // foreach
$skipDelimiter = false;
if ( count( $fe_variable_stack_cc7a006f362346f674a27d9ed08c0044_27 ) ) extract( array_pop( $fe_variable_stack_cc7a006f362346f674a27d9ed08c0044_27 ) );
else
{
unset( $fe_array_cc7a006f362346f674a27d9ed08c0044_27 );
unset( $fe_array_keys_cc7a006f362346f674a27d9ed08c0044_27 );
unset( $fe_n_items_cc7a006f362346f674a27d9ed08c0044_27 );
unset( $fe_n_items_processed_cc7a006f362346f674a27d9ed08c0044_27 );
unset( $fe_i_cc7a006f362346f674a27d9ed08c0044_27 );
unset( $fe_key_cc7a006f362346f674a27d9ed08c0044_27 );
unset( $fe_val_cc7a006f362346f674a27d9ed08c0044_27 );
unset( $fe_offset_cc7a006f362346f674a27d9ed08c0044_27 );
unset( $fe_max_cc7a006f362346f674a27d9ed08c0044_27 );
unset( $fe_reverse_cc7a006f362346f674a27d9ed08c0044_27 );
unset( $fe_first_val_cc7a006f362346f674a27d9ed08c0044_27 );
unset( $fe_last_val_cc7a006f362346f674a27d9ed08c0044_27 );
unset( $fe_variable_stack_cc7a006f362346f674a27d9ed08c0044_27 );
}
// foreach ends
$text .= ' </span>
';
unset( $vars[$currentNamespace]['c'] );
$text .= ' </p>
<div class="break"></div>
</div>
';
}
unset( $if_cond );
// if ends
$text .= ' ';
if ( isset( $setArray[$currentNamespace]['children_count_by_letter'] ) )
{
unset( $vars[$currentNamespace]['children_count_by_letter'] );
}
if ( isset( $setArray[$currentNamespace]['objectname_filter'] ) )
{
unset( $vars[$currentNamespace]['objectname_filter'] );
}
if ( isset( $setArray[$currentNamespace]['alphabet'] ) )
{
unset( $vars[$currentNamespace]['alphabet'] );
}
if ( isset( $setArray[$currentNamespace]['node_id'] ) )
{
unset( $vars[$currentNamespace]['node_id'] );
}
if ( isset( $setArray[$currentNamespace]['page_uri_suffix'] ) )
{
unset( $vars[$currentNamespace]['page_uri_suffix'] );
}
if ( isset( $setArray[$currentNamespace]['page_count'] ) )
{
unset( $vars[$currentNamespace]['page_count'] );
}
}
unset( $if_cond );
// if ends
if ( isset( $setArray[$currentNamespace]['page_uri_suffix'] ) )
{
unset( $vars[$currentNamespace]['page_uri_suffix'] );
}
if ( isset( $setArray[$currentNamespace]['show_google_navigator'] ) )
{
unset( $vars[$currentNamespace]['show_google_navigator'] );
}
$setArray = $oldSetArray_faddee0132331cfae3257224b2d669d9;
$tpl->Level--;
?>
| imadkaf/aYaville | ezpublish_legacy/var/ezdemo_site/cache/template/compiled/alphabetical-db955e84f550c8279c70a7950e25e155.php | PHP | gpl-2.0 | 63,455 |
#include <stdio.h>
int main(void)
{
char oldname[80];
char newname[80];
// prompt for file to rename and new name
printf("File to rename: ");
gets(oldname);
printf("New name: ");
gets(newname);
// Rename the file
if (0 == rename(oldname, newname))
{
printf("Renamed %s to %s.\n", oldname, newname);
}
else
{
perror("rename");
}
return 0;
}
| Akagi201/akcode | c/ctest/test_rename/rename.c | C | gpl-2.0 | 417 |
/*
* pure C program showing how you can use popen() to perform
* a NEMO task without the need to link NEMO code.
* Not very efficient, but it works.
*/
#include <stdio.h>
#define N 1000
void main() {
float x[N], y[N], z[N], pot[N];
int i, n;
FILE *fp;
/*
before you run this program, create p100.tab as follows
mkplummer - 100 | snapprint - x,y,z > p100.tab
*/
n = 100;
fp = fopen("p100.tab","r");
for (i=0; i<n; i++) fscanf(fp,"%g %g %g\n",&x[i],&y[i],&z[i]);
fclose(fp);
/* silly, but write them out again */
fp = fopen("tmpxyz.tab","w");
for (i=0; i<n; i++) fprintf(fp,"%g %g %g\n",x[i],y[i],z[i]);
fclose(fp);
/* use popen(2) to read the returned potentials */
fp = popen("xyz2pot tmpxyz.tab","r");
for (i=0; i<n; i++) {
fscanf(fp,"%g\n",&pot[i]);
printf("%d : %f %f %f %f\n",i+1,x[i],y[i],z[i],pot[i]);
}
pclose(fp);
}
| jobovy/nemo | src/tutor/popen/ptest1.c | C | gpl-2.0 | 953 |
/* created by click/linuxmodule/fixincludes.pl on Tue Nov 25 22:39:40 2014 */
/* from /lib/modules/2.6.27.5-117.fc10.i686/build/include/config/jffs2/summary.h */
| songxingshen/myclick | include/click-linuxmodule/include0/config/jffs2/summary.h | C | gpl-2.0 | 162 |
// Copyright (C) 1999,2000 Bruce Guenter <bruce@untroubled.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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#include <config.h>
#include <limits.h>
#include "lookup.h"
#include "list_table.h"
#include "map_table.h"
#include "config/configrc.h"
bool is_local(mystring domain)
{
mystring tblname = config->qmail_root() + "/control/locals";
list_table tbl(tblname.c_str());
if(!tbl)
return false;
return tbl[domain];
}
mystring find_virtual(mystring domain)
{
domain = domain.lower();
mystring tblname = config->qmail_root() + "/control/virtualdomains";
map_table tbl(tblname.c_str());
if(!tbl)
return "";
for(unsigned i = 0; i != UINT_MAX && i < domain.length();
i = domain.find_first('.', i+1)) {
mystring tmp = tbl[domain.c_str()+i];
if(!!tmp)
return tmp;
}
return "";
}
| bruceg/vmailmgr | lib/misc/lookup_domain.cc | C++ | gpl-2.0 | 1,497 |
<?php
/*******************************************************************************
* account.common.php
* account参数信息文件
* account parameter file
* 功能描述
检查用户权限
初始化语言变量
初始化xajax类
预定义xajaxGrid中需要使用的一些参数
* Function Desc
authority
initialize localization class
initialize xajax class
define xajaxGrid parameters
registed function:
* call these function by xajax_ + funcionname
* such as xajax_init()
showGrid
add show account add form
save save account information
edit show account edit form
update update account information
delete delete an account
showDetail show detail information about an account
return null for now
init init html page
* Revision 0.045 2007/10/17 15:25:00 modified by solo
* Desc: page created
********************************************************************************/
header('Content-Type: text/html; charset=utf-8');
header('Expires: Sat, 01 Jan 2000 00:00:00 GMT');
header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
header('Cache-Control: post-check=0, pre-check=0',false);
header('Pragma: no-cache');
session_cache_limiter('public, no-store');
session_set_cookie_params(0);
if (!session_id()) session_start();
setcookie('PHPSESSID', session_id());
if ($_SESSION['curuser']['usertype'] != 'admin')
header("Location: portal.php");
require_once ("include/xajax.inc.php");
require_once ('include/localization.class.php');
$GLOBALS['locate']=new Localization($_SESSION['curuser']['country'],$_SESSION['curuser']['language'],'user_types');
$xajax = new xajax("user_types.server.php");
$xajax->registerFunction("showGrid");
$xajax->registerFunction("add");
$xajax->registerFunction("save");
$xajax->registerFunction("edit");
$xajax->registerFunction("updateUserTypeRecord");
$xajax->registerFunction("delete");
$xajax->registerFunction("init");
$xajax->registerFunction("searchFormSubmit");
define("ROWSXPAGE", 10); // Number of rows show it per page.
define("MAXROWSXPAGE", 25); // Total number of rows show it when click on "Show All" button.
?>
| nsnake/IRISCC | astercc/astercrm/user_types.common.php | PHP | gpl-2.0 | 2,131 |
/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*- */
/*
* viking -- GPS Data and Topo Analyzer, Explorer, and Manager
*
* Copyright (C) 2011, Rob Norris <rw_norris@hotmail.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
*
*/
#ifndef _VIKING_TRWLAYER_GEOTAG_H
#define _VIKING_TRWLAYER_GEOTAG_H
#include <glib.h>
#include <gtk/gtk.h>
#include "viktrwlayer.h"
G_BEGIN_DECLS
// To be only called from within viktrwlayer
void trw_layer_geotag_dialog ( GtkWindow *parent, VikTrwLayer *vtl, VikTrack *track, const gchar *track_name );
G_END_DECLS
#endif
| rpeyron/viking | src/viktrwlayer_geotag.h | C | gpl-2.0 | 1,253 |
'use strict';
let {ko, Helper} = require('../common'),
DialogManager = require('../DialogManager'),
DEFAULT_WIDTH = 530,
TEMPLATES = {
DEFAULT: 'confirmDialogTpl'
},
instance,
getInstance = function(confirmCallback, optionalTemplateName, optionalContextVars) {
Helper.assertStringOrEmpty(optionalTemplateName, 'invalid tempalte name for ConfirmDialog.getInstance()');
if (!instance) {
instance = new ConfirmDialog();
}
instance.setConfirmCallback(confirmCallback);
instance.setTemplateName(optionalTemplateName);
instance.setContextVars(optionalContextVars);
instance.settings.modalWidth = (TEMPLATES.REVERT_ENTRY === optionalTemplateName) ? 550 : DEFAULT_WIDTH;
return instance;
};
/**
* A simple "Möchten Sie wirklich fortfahren?" confirm dialog.
* @constructor
*/
function ConfirmDialog() {
let self = this,
dialogManager = DialogManager.getInstance(),
confirmCallback = null;
this.settings = DialogManager.createDialogSettings({
templateName: TEMPLATES.DEFAULT,
modalWidth: DEFAULT_WIDTH
});
/**
* Object containing properties that might be used in the template via data-bind.
*/
this.contextVars = null;
/**
* Sets the template name for this dialog or the default templateName if empty.
* @param [templateName] (String) the template to set; If falsy, the {@link TEMPLATES.DEFAULT} is set
* @returns (Object) this instance (chainable)
*/
this.setTemplateName = function(templateName) {
Helper.assertStringOrEmpty(templateName, 'Invalid templateName for ConfirmDialog');
this.settings.templateName = templateName || TEMPLATES.DEFAULT;
return this;
};
/**
* Sets the callback function called on the positive button.
* @param callback (function) e.g. function(confirmDialog){..}
*/
this.setConfirmCallback = function(callback) {
Helper.assertFunction(callback, 'Invalid confirm callback for ConfirmDialog');
confirmCallback = callback;
};
this.setContextVars = function(newContextVars) {
this.contextVars = newContextVars || null;
};
/**
* Triggered via data-bind by the template's ok button.
*/
this.confirm = function() {
confirmCallback(self);
dialogManager.reset();
return false;
};
this.show = function() {
dialogManager.showDialog(this);
};
}
module.exports = {
getInstance,
getInstanceForSomething: function(someInfo, onConfirm) {
return getInstance(onConfirm, TEMPLATES.DEFAULT, {someInfo: someInfo});
}
};
| justlep/synchronizer | src/js/dialogs/ConfirmDialog.js | JavaScript | gpl-2.0 | 2,753 |
import os
import sys
import tnetstring
def read_packets (filename):
try:
os.stat (filename)
except OSError:
print "No such file : %s"%filename
sys.exit (1)
pkts = open (filename).read ()
pkts = tnetstring.loads (pkts, 'iso-8859-15')
for data in pkts:
yield data
if '__main__' == __name__:
if not sys.argv [1:]:
print "Usage: %s 'file'"%sys.argv [0]
sys.exit (0)
filename = sys.argv [1]
for pkt in read_packets (filename):
print "found %d's len packet"%len (pkt)
| sipdbg/sipdbg | rtp/read_dump.py | Python | gpl-2.0 | 552 |
using UnityEngine;
namespace Vexe.Editor.GUIs
{
public abstract partial class BaseGUI
{
public float FloatSlider(float value, float leftValue, float rightValue)
{
return FloatSlider(value, leftValue, rightValue, null);
}
public float FloatSlider(float value, float leftValue, float rightValue, Layout option)
{
return FloatSlider(string.Empty, value, leftValue, rightValue, option);
}
public float FloatSlider(string content, float value, float leftValue, float rightValue)
{
return FloatSlider(content, value, leftValue, rightValue, null);
}
public float FloatSlider(string content, float value, float leftValue, float rightValue, Layout option)
{
return FloatSlider(new GUIContent(content), value, leftValue, rightValue, option);
}
public abstract float FloatSlider(GUIContent content, float value, float leftValue, float rightValue, Layout option);
public int IntSlider(int value, int leftValue, int rightValue)
{
return IntSlider(value, leftValue, rightValue, null);
}
public int IntSlider(int value, int leftValue, int rightValue, Layout option)
{
return IntSlider(string.Empty, value, leftValue, rightValue, option);
}
public int IntSlider(string content, int value, int leftValue, int rightValue)
{
return IntSlider(content, value, leftValue, rightValue, null);
}
public int IntSlider(string content, int value, int leftValue, int rightValue, Layout option)
{
return IntSlider(new GUIContent(content), value, leftValue, rightValue, option);
}
public int IntSlider(GUIContent content, int value, int leftValue, int rightValue, Layout option)
{
return Mathf.RoundToInt(FloatSlider(content, (float)value, (float)leftValue, (float)rightValue, option));
}
}
} | DarrenTsung/duckproject | KnightsOfTheFarm/Assets/Plugins/Editor/Vexe/GUIs/BaseGUI/Controls/Sliders.cs | C# | gpl-2.0 | 1,813 |
package com.example.jameshwart.sample;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
} | jameshwartlopez/QRCodeScanning | app/src/androidTest/java/com/example/jameshwart/sample/ApplicationTest.java | Java | gpl-2.0 | 360 |
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Guestbook DB error</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
<h1>DB problem!</h1>
</body>
</html>
| dvoraka/guestbook | src/main/resources/templates/dbError.html | HTML | gpl-2.0 | 231 |
<?php
/**
* @package JCE
* @copyright Copyright (c) 2009-2015 Ryan Demmer. All rights reserved.
* @license GNU/GPL 2 or later - http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
* JCE is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
*/
defined('_JEXEC') or die('RESTRICTED');
wfimport('admin.classes.view');
class WFViewHelp extends WFView {
function display($tpl = null) {
$model = $this->getModel();
$language = $model->getLanguage();
$lang = JFactory::getLanguage();
$section = JRequest::getWord('section');
$category = JRequest::getWord('category');
$article = JRequest::getWord('article');
$component = JComponentHelper::getComponent('com_jce');
require_once(WF_ADMINISTRATOR . '/classes/parameter.php');
$params = new WFParameter($component->params);
$url = $params->get('preferences.help.url', 'http://www.joomlacontenteditor.net');
$method = $params->get('preferences.help.method', 'reference');
$pattern = $params->get('preferences.help.pattern', '');
switch ($method) {
default:
case 'reference':
$url .= '/index.php?option=com_content&view=article&tmpl=component&print=1&mode=inline&task=findkey&lang=' . $language . '&keyref=';
break;
case 'xml':
break;
case 'sef':
break;
}
$this->assign('model', $model);
$key = array();
if ($section) {
$key[] = $section;
if ($category) {
$key[] = $category;
if ($article) {
$key[] = $article;
}
}
}
$options = array(
'url' => $url,
'key' => $key,
'pattern' => $pattern
);
$this->addStyleSheet(JURI::root(true) . '/components/com_jce/editor/libraries/css/help.css');
$this->addScriptDeclaration('jQuery(document).ready(function($){$.jce.Help.init(' . json_encode($options) . ');});');
parent::display($tpl);
}
}
| sergey104/sushi-art | administrator/components/com_jce/views/help/view.html.php | PHP | gpl-2.0 | 2,416 |
/*******************************************************************************
Copyright (C) Marvell International Ltd. and its affiliates
This software file (the "File") is owned and distributed by Marvell
International Ltd. and/or its affiliates ("Marvell") under the following
alternative licensing terms. Once you have made an election to distribute the
File under one of the following license alternatives, please (i) delete this
introductory statement regarding license alternatives, (ii) delete the two
license alternatives that you have not elected to use and (iii) preserve the
Marvell copyright notice above.
********************************************************************************
Marvell Commercial License Option
If you received this File from Marvell and you have entered into a commercial
license agreement (a "Commercial License") with Marvell, the File is licensed
to you under the terms of the applicable Commercial License.
********************************************************************************
Marvell GPL License Option
If you received this File from Marvell, you may opt to use, redistribute and/or
modify this File in accordance with the terms and conditions of the General
Public License Version 2, June 1991 (the "GPL License"), a copy of which is
available along with the File in the license.txt file or by writing to the Free
Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 or
on the worldwide web at http://www.gnu.org/licenses/gpl.txt.
THE FILE IS DISTRIBUTED AS-IS, WITHOUT WARRANTY OF ANY KIND, AND THE IMPLIED
WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE ARE EXPRESSLY
DISCLAIMED. The GPL License provides additional details about this warranty
disclaimer.
********************************************************************************
Marvell BSD License Option
If you received this File from Marvell, you may opt to use, redistribute and/or
modify this File under the following licensing terms.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Marvell nor the names of its contributors may be
used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*******************************************************************************/
#ifndef __INCmvTypesh
#define __INCmvTypesh
/* Defines */
/* The following is a list of Marvell status */
#define MV_ERROR (-1)
#define MV_OK (0) /* Operation succeeded */
#define MV_FAIL (1) /* Operation failed */
#define MV_BAD_VALUE (2) /* Illegal value (general) */
#define MV_OUT_OF_RANGE (3) /* The value is out of range */
#define MV_BAD_PARAM (4) /* Illegal parameter in function called */
#define MV_BAD_PTR (5) /* Illegal pointer value */
#define MV_BAD_SIZE (6) /* Illegal size */
#define MV_BAD_STATE (7) /* Illegal state of state machine */
#define MV_SET_ERROR (8) /* Set operation failed */
#define MV_GET_ERROR (9) /* Get operation failed */
#define MV_CREATE_ERROR (10) /* Fail while creating an item */
#define MV_NOT_FOUND (11) /* Item not found */
#define MV_NO_MORE (12) /* No more items found */
#define MV_NO_SUCH (13) /* No such item */
#define MV_TIMEOUT (14) /* Time Out */
#define MV_NO_CHANGE (15) /* Parameter(s) is already in this value */
#define MV_NOT_SUPPORTED (16) /* This request is not support */
#define MV_NOT_IMPLEMENTED (17) /* Request supported but not implemented */
#define MV_NOT_INITIALIZED (18) /* The item is not initialized */
#define MV_NO_RESOURCE (19) /* Resource not available (memory ...) */
#define MV_FULL (20) /* Item is full (Queue or table etc...) */
#define MV_EMPTY (21) /* Item is empty (Queue or table etc...) */
#define MV_INIT_ERROR (22) /* Error occured while INIT process */
#define MV_HW_ERROR (23) /* Hardware error */
#define MV_TX_ERROR (24) /* Transmit operation not succeeded */
#define MV_RX_ERROR (25) /* Recieve operation not succeeded */
#define MV_NOT_READY (26) /* The other side is not ready yet */
#define MV_ALREADY_EXIST (27) /* Tried to create existing item */
#define MV_OUT_OF_CPU_MEM (28) /* Cpu memory allocation failed. */
#define MV_NOT_STARTED (29) /* Not started yet */
#define MV_BUSY (30) /* Item is busy. */
#define MV_TERMINATE (31) /* Item terminates it's work. */
#define MV_NOT_ALIGNED (32) /* Wrong alignment */
#define MV_NOT_ALLOWED (33) /* Operation NOT allowed */
#define MV_WRITE_PROTECT (34) /* Write protected */
#define MV_DROPPED (35) /* Packet dropped */
#define MV_STOLEN (36) /* Packet stolen */
#define MV_CONTINUE (37) /* Continue */
#define MV_RETRY (38) /* Operation failed need retry */
#define MV_INVALID (int)(-1)
#define MV_FALSE 0
#define MV_TRUE (!(MV_FALSE))
#ifndef NULL
#define NULL ((void *)0)
#endif
#ifndef MV_ASMLANGUAGE
/* typedefs */
typedef signed char MV_8;
typedef unsigned char MV_U8;
typedef int MV_32;
typedef unsigned int MV_U32;
typedef short MV_16;
typedef unsigned short MV_U16;
#ifdef MV_PPC64
typedef long MV_64;
typedef unsigned long MV_U64;
#else
typedef long long MV_64;
typedef unsigned long long MV_U64;
#endif
typedef long MV_LONG; /* 32/64 */
typedef unsigned long MV_ULONG; /* 32/64 */
typedef int MV_STATUS;
typedef int MV_BOOL;
typedef void MV_VOID;
typedef float MV_FLOAT;
typedef int (*MV_FUNCPTR) (void); /* ptr to function returning int */
typedef void (*MV_VOIDFUNCPTR) (void); /* ptr to function returning void */
typedef double (*MV_DBLFUNCPTR) (void); /* ptr to function returning double */
typedef float (*MV_FLTFUNCPTR) (void); /* ptr to function returning float */
typedef MV_U32 MV_KHZ;
typedef MV_U32 MV_MHZ;
typedef MV_U32 MV_HZ;
/* This enumerator describes the set of commands that can be applied on */
/* an engine (e.g. IDMA, XOR). Appling a comman depends on the current */
/* status (see MV_STATE enumerator) */
/* Start can be applied only when status is IDLE */
/* Stop can be applied only when status is IDLE, ACTIVE or PAUSED */
/* Pause can be applied only when status is ACTIVE */
/* Restart can be applied only when status is PAUSED */
typedef enum _mvCommand {
MV_START, /* Start */
MV_STOP, /* Stop */
MV_PAUSE, /* Pause */
MV_RESTART /* Restart */
} MV_COMMAND;
/* This enumerator describes the set of state conditions. */
/* Moving from one state to other is stricted. */
typedef enum _mvState {
MV_IDLE,
MV_ACTIVE,
MV_PAUSED,
MV_UNDEFINED_STATE
} MV_STATE;
typedef enum {
ETH_MAC_SPEED_10M,
ETH_MAC_SPEED_100M,
ETH_MAC_SPEED_1000M,
ETH_MAC_SPEED_AUTO
} MV_ETH_MAC_SPEED;
/* This structure describes address space window. Window base can be */
/* 64 bit, window size up to 4GB */
typedef struct _mvAddrWin {
MV_U32 baseLow; /* 32bit base low */
MV_U32 baseHigh; /* 32bit base high */
MV_U64 size; /* 64bit size */
} MV_ADDR_WIN;
/* This binary enumerator describes protection attribute status */
typedef enum _mvProtRight {
ALLOWED, /* Protection attribute allowed */
FORBIDDEN /* Protection attribute forbidden */
} MV_PROT_RIGHT;
/* Unified struct for Rx and Tx packet operations. The user is required to */
/* be familier only with Tx/Rx descriptor command status. */
typedef struct _bufInfo {
MV_U32 cmdSts; /* Tx/Rx command status */
MV_U16 byteCnt; /* Size of valid data in the buffer */
MV_U16 bufSize; /* Total size of the buffer */
MV_U8 *pBuff; /* Pointer to Buffer */
MV_U8 *pData; /* Pointer to data in the Buffer */
MV_U32 userInfo1; /* Tx/Rx attached user information 1 */
MV_U32 userInfo2; /* Tx/Rx attached user information 2 */
struct _bufInfo *pNextBufInfo; /* Next buffer in packet */
} BUF_INFO;
/* This structure contains information describing one of buffers
* (fragments) they are built Ethernet packet.
*/
typedef struct {
MV_U8 *bufVirtPtr;
MV_ULONG bufPhysAddr;
MV_U32 bufSize;
MV_U32 dataSize;
MV_U32 memHandle;
MV_32 bufAddrShift;
} MV_BUF_INFO;
/* This structure contains information describing Ethernet packet.
* The packet can be divided for few buffers (fragments)
*/
typedef struct {
MV_ULONG osInfo;
MV_BUF_INFO *pFrags;
MV_U32 status;
MV_U16 pktSize;
MV_U16 numFrags;
MV_U32 ownerId;
MV_U32 fragIP;
MV_U32 txq;
} MV_PKT_INFO;
/* This structure describes SoC units address decode window */
typedef struct {
MV_ADDR_WIN addrWin; /* An address window */
MV_BOOL enable; /* Address decode window is enabled/disabled */
MV_U8 attrib; /* chip select attributes */
MV_U8 targetId; /* Target Id of this MV_TARGET */
} MV_UNIT_WIN_INFO;
/* This structure describes access rights for Access protection windows */
/* that can be found in IDMA, XOR, Ethernet and MPSC units. */
/* Note that the permission enumerator coresponds to its register format. */
/* For example, Read only premission is presented as "1" in register field. */
typedef enum _mvAccessRights {
NO_ACCESS_ALLOWED = 0, /* No access allowed */
READ_ONLY = 1, /* Read only permission */
ACC_RESERVED = 2, /* Reserved access right */
FULL_ACCESS = 3, /* Read and Write permission */
MAX_ACC_RIGHTS
} MV_ACCESS_RIGHTS;
typedef struct _mvDecRegs {
MV_U32 baseReg;
MV_U32 baseRegHigh;
MV_U32 ctrlReg;
} MV_DEC_REGS;
#endif /* MV_ASMLANGUAGE */
#endif /* __INCmvTypesh */
| mmilburn/marvell-switch | common/mvTypes.h | C | gpl-2.0 | 11,571 |
<!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_51) on Tue Feb 04 13:39:01 CET 2014 -->
<title>Uses of Package it.unitn.lifecoach.service.process.meallog.adapter</title>
<meta name="date" content="2014-02-04">
<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 Package it.unitn.lifecoach.service.process.meallog.adapter";
}
//-->
</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>Class</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-files/index-1.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?it/unitn/lifecoach/service/process/meallog/adapter/package-use.html" target="_top">Frames</a></li>
<li><a href="package-use.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">
<h1 title="Uses of Package it.unitn.lifecoach.service.process.meallog.adapter" class="title">Uses of Package<br>it.unitn.lifecoach.service.process.meallog.adapter</h1>
</div>
<div class="contentContainer">No usage of it.unitn.lifecoach.service.process.meallog.adapter</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>Class</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-files/index-1.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?it/unitn/lifecoach/service/process/meallog/adapter/package-use.html" target="_top">Frames</a></li>
<li><a href="package-use.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 ======= -->
</body>
</html>
| keme686/LifeCoachService | it.unitn.lifecoach.service.process.selfmonitoring/doc/it/unitn/lifecoach/service/process/meallog/adapter/package-use.html | HTML | gpl-2.0 | 4,090 |
/**
* @file
* Block Styling
*/
.block { /* Block wrapper */
margin-bottom: 1.5em;
}
.block.first { /* The first block in the region */
}
.block.last { /* The last block in the region */
}
.block.odd { /* Zebra striping for each block in the region */
}
.block.even { /* Zebra striping for each block in the region */
}
#block-block-10 {
position: relative;
top: -33.5em;
left: 4em;
width: 11.3em;
}
#main-menu-transparent {
position: relative;
top: -1.60em;
width: auto/* 59.5em */;
margin-right: -20px; /* fill out whole area, move if problems in iPad */
background-color: #000;
height: 25px;
left: -1.1em;
opacity: 0.4;
z-index: -10;
}
#sidebar-menu-transparent {
position: relative;
top: 3.55em;
width: 200px;
background-color: #000;
height: 320px;
left: 3em;
opacity: 0.4;
z-index: -10;
border: 1px solid;
border-radius: 7px;
}
#block-menu-title {
position: relative;
top: -17em;
left: 4.8em;
opacity: 0.2;
}
#block-aggregator-category-1 { /* Block for the latest news items in the first category */
}
#block-aggregator-feed-1 { /* Block for the latest news items in the first feed */
}
#block-block-1 { /* First block created with "Add block" link */
}
#block-blog-recent { /* "Recent blog posts" block */
}
#block-book-navigation { /* "Book navigation" block for the current book's table of contents */
}
#block-comment-recent { /* "Recent comments" block */
}
#block-forum-active { /* "Active forum topics" block */
}
#block-forum-new { /* "New forum topics" block */
}
#block-locale-language {
border: medium none;
dispaly: block;
position: relative;
left: 6.1em;
top: -3.3em;
width: auto; /* 9.5em; */
margin-bottom: 0em;
}
#block-locale-language ul {
font-size: 0.7em;
font-weight: 100;
list-style-type: none;
padding: 0px;
margin: 0px;
line-height: 1em;
}
#block-locale-language ul li {
border-left: 1px solid grey;
float: left;
padding-left: 0.5em;
padding-right: 0.5em;
}
#block-locale-language a {
color: green;
text-decoration: none;
font-variant: normal;
letter-spacing: normal;
}
#block-locale-language a:visited {
color: green;
text-decoration: none;
}
#block-locale-language a:hover {
text-decoration: underline;
}
#block-menu-menu-NAME { /* Custom menu block */
}
#block-menu-elements {
position: relative;
top: -33.5em;
left: 4.5em;
width: 11em;
}
#block-node-recent { /* "Recent content" block */
}
#block-node-syndicate { /* "Syndicate" block for primary RSS feed; see also page.css's .feed-icon */
}
#block-poll-recent { /* "Most recent poll" block */
}
#block-profile-author-information { /* "Author information" block for the profile of the page's author */
}
#block-search-form { /* "Search form" block */
}
#block-shortcut-shortcuts { /* "Shortcuts" block */
}
#block-statistics-popular { /* "Popular content" block */
}
#block-system-main-menu { /* "Main menu" block */
}
#block-system-management { /* "Management" block for Drupal management menu */
}
#block-system-navigation { /* "Navigation" block for Drupal navigation menu */
}
#block-system-user-menu { /* "User menu" block for Drupal user menu */
}
#block-system-help { /* "System help" block */
}
#block-system-main { /* "Main page content" block */
}
#block-system-powered-by { /* "Powered by Drupal" block */
}
#block-user-login { /* "User login form" block */
}
#block-user-new { /* "Who's new" block for a list of the newest users */
}
#block-user-online { /* "Who's online" block for a list of the online users */
}
.view-favicon-gallery {
position: relative;
top: 5px;
left: -7.4em;
height: 40px;
width: 400px;
}
.view-favicon-gallery .views-row {
float: left;
}
/* Subscription form block */
#subscription-block {
border: 0px solid grey;
padding: 15px;
position: relative;
top: -520px;
left: 48px;
width: 170px;
padding-bottom: 0px;
margin-bottom: 20px;
}
#subscription-text p {
position: relative;
top: -1em;
font-family: 'EB Garamond';
font-style: normal;
font-weight: normal;
}
#subscription-text p#subscription-header {
font-family: "de-walpergens-pica", serif;
font-style: normal;
font-size: 1.5em;
}
#subscription-text p#sign-up {
font-size: 97%;
line-height: 1.3em;
color: grey;
position: relative;
top: -3.5em;
width: 12.0em;
}
#subscription-form {
position: relative;
top: -3.8em;
left: 0em;
width: 180px;
}
#subscription-form input{
font-size: 70%;
background-color: #909090;
color: white;
margin-bottom: 0.3em;
}
select#country {
font-size: 70%;
}
label#label-select {
position: relative;
top: -1.8em;
left: 2em;
font-family: 'EB Garamond';
font-style: normal;
font-size: 85%;
font-weight: normal;
width: 11.5em;
}
input#name {
position: relative;
top: 0em;
left: 0em;
width: 160px;
height: 1.8em;
}
input#jhtjmt-jhtjmt, input#dtjdlk-dtjdlk {
position: relative;
top: 0em;
left: 0em;
width: 160px;
height: 1.8em;
}
select#country {
position: relative;
top: 0em;
left: 0em;
background-color: #909090;
color: white;
height: 2.2em;
font-size: 0.7em;
max-width: 170px;
}
p#for-organizers-text {
position: relative;
top: 1em;
width: 170px;
font-family: "de-walpergens-pica", serif;
font-size: 1.5em;
}
p#stay-updated {
font-size: 97%;
line-height: 1.3em;
color: grey;
position: relative;
top: -0.5em;
width: 12.5em;
}
div#check-box {
position: relative;
top: -1.4em;
left: 0em;
width: 170px;
}
input#submit-form {
font-size: 1.2em;
padding: 5px 10px 5px 10px;
position: relative;
left: 1.6em;
top: 0.3em;
background-color: green;
border: 2px solid;
border-radius: 10px;
}
#block-views-favicon-gallery-block {
position: static;
}
#block-system-powered-by {
font-size: 0.9em;
font-family: josefin-sans, san-serif;
} | parlason/parla_github | sites/all/themes/songbook/css/blocks.css | CSS | gpl-2.0 | 5,867 |
// IXUS120-SD940 fw 1.00e
#include "platform.h"
long vid_get_bitmap_screen_width()
{
return 360 ; // SD940 103c ? 360 103b: seems to use same number.
}
long vid_get_bitmap_screen_height()
{
return 240; // SD940 103c 103b: seems to use same number.
}
int vid_get_viewport_width()
{
return 360 ; // SD940 103c ?
}
long vid_get_viewport_height()
{
return 240; // SD940 103c 103b: seems to use same number.
}
long vid_get_bitmap_buffer_width()
{
return 960; // SD940 103c 103b: seems to use same number.
}
long vid_get_bitmap_buffer_height()
{
return 270; // SD940 103c 103b: seems to use same number.
}
char *camera_jpeg_count_str()
{
return (char*) 0x700B0; // SD940 103C search on "9999" 103b: seems to use same number.
}
char *hook_raw_image_addr()
{
return (char*)0x4219D120; // SD940 103c FFAD6FF8 from matching subroutine in S90 101a FFB0254C 103b: seems to use same number.
// ... search for aCrawBuffP DCB "CRAW BUFF %p",0
}
long hook_raw_size()
{
return 0x11CA240; // SD940 103c Search for "aCrawBuffSizeP" 103b: seems to use same number.
}
void *vid_get_bitmap_fb()
{
return (void*)0x403F1000; // SD940 103c @ FF8532DC after DispCon_ShowBlackChart 103b: seems to use same number.
}
void *vid_get_viewport_live_fb() //103b: seems to use same routine.
{ // Matched IXUS100-SD780 100c code at 0xFF8B02F4 with IXUS120-SD940 at address 0xFF8D9014
// Matched IXUS200-SD980 101c code at 0xFF8E0788 with IXUS120-SD940 at address 0xFF8D9014
// return (void*) 0; // __LiveImage.c__ ok
void **fb=(void **)0x4B34; // SD940 102C @ 0xFF8D9280
unsigned char buff = *((unsigned char*)0x497C); // SD940 103C @ 0xFF8D9018
if (buff == 0) {
buff = 2;
}
else {
buff--;
}
return fb[buff];
}
void *vid_get_viewport_fb()
{
return (void*)0x4088B700; // SD940 103c from matching subroutine in S90 101a 103b: seems to use same number.
// search on VRAM Address sub @ 9FFAD4910)
}
void *vid_get_viewport_fb_d()
{
return (void*)(*(int*)(0x2790+0x58)); // @FF869DEC @FF869E24
}
| arne182/chdk-eyefi | platform/ixus120_sd940/sub/100e/lib.c | C | gpl-2.0 | 2,257 |
/***************************************************************************
* Copyright (c) 1999-2009, Broadcom Corporation
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Module Description:
* DO NOT EDIT THIS FILE DIRECTLY
*
* This module was generated magically with RDB from a source description
* file. You must edit the source file for changes to be made to this file.
*
*
* Date: Generated on Tue Jan 6 17:57:56 2009
* MD5 Checksum 91c88a5712579194ae1f9db9f34ff5d5
*
* Compiled with: RDB Utility combo_header.pl
* RDB Parser 3.0
* unknown unknown
* Perl Interpreter 5.008008
* Operating System linux
*
* Revision History:
*
* $brcm_Log: /magnum/basemodules/chp/7420/rdb/b0/bchp_pcie_intr2.h $
*
* Hydra_Software_Devel/1 1/6/09 8:34p tdo
* PR50865: Add initial rdb generated header files for 7420 B0
*
***************************************************************************/
#ifndef BCHP_PCIE_INTR2_H__
#define BCHP_PCIE_INTR2_H__
/***************************************************************************
*PCIE_INTR2 - PCI-E L2 Interrupt Controller Registers
***************************************************************************/
#define BCHP_PCIE_INTR2_CPU_STATUS 0x00454300 /* CPU interrupt Status Register */
#define BCHP_PCIE_INTR2_CPU_SET 0x00454304 /* CPU interrupt Set Register */
#define BCHP_PCIE_INTR2_CPU_CLEAR 0x00454308 /* CPU interrupt Clear Register */
#define BCHP_PCIE_INTR2_CPU_MASK_STATUS 0x0045430c /* CPU interrupt Mask Status Register */
#define BCHP_PCIE_INTR2_CPU_MASK_SET 0x00454310 /* CPU interrupt Mask Set Register */
#define BCHP_PCIE_INTR2_CPU_MASK_CLEAR 0x00454314 /* CPU interrupt Mask Clear Register */
#define BCHP_PCIE_INTR2_PCI_STATUS 0x00454318 /* PCI interrupt Status Register */
#define BCHP_PCIE_INTR2_PCI_SET 0x0045431c /* PCI interrupt Set Register */
#define BCHP_PCIE_INTR2_PCI_CLEAR 0x00454320 /* PCI interrupt Clear Register */
#define BCHP_PCIE_INTR2_PCI_MASK_STATUS 0x00454324 /* PCI interrupt Mask Status Register */
#define BCHP_PCIE_INTR2_PCI_MASK_SET 0x00454328 /* PCI interrupt Mask Set Register */
#define BCHP_PCIE_INTR2_PCI_MASK_CLEAR 0x0045432c /* PCI interrupt Mask Clear Register */
/***************************************************************************
*CPU_STATUS - CPU interrupt Status Register
***************************************************************************/
/* PCIE_INTR2 :: CPU_STATUS :: MSI_INTR07 [31:31] */
#define BCHP_PCIE_INTR2_CPU_STATUS_MSI_INTR07_MASK 0x80000000
#define BCHP_PCIE_INTR2_CPU_STATUS_MSI_INTR07_SHIFT 31
/* PCIE_INTR2 :: CPU_STATUS :: MSI_INTR06 [30:30] */
#define BCHP_PCIE_INTR2_CPU_STATUS_MSI_INTR06_MASK 0x40000000
#define BCHP_PCIE_INTR2_CPU_STATUS_MSI_INTR06_SHIFT 30
/* PCIE_INTR2 :: CPU_STATUS :: MSI_INTR05 [29:29] */
#define BCHP_PCIE_INTR2_CPU_STATUS_MSI_INTR05_MASK 0x20000000
#define BCHP_PCIE_INTR2_CPU_STATUS_MSI_INTR05_SHIFT 29
/* PCIE_INTR2 :: CPU_STATUS :: MSI_INTR04 [28:28] */
#define BCHP_PCIE_INTR2_CPU_STATUS_MSI_INTR04_MASK 0x10000000
#define BCHP_PCIE_INTR2_CPU_STATUS_MSI_INTR04_SHIFT 28
/* PCIE_INTR2 :: CPU_STATUS :: MSI_INTR03 [27:27] */
#define BCHP_PCIE_INTR2_CPU_STATUS_MSI_INTR03_MASK 0x08000000
#define BCHP_PCIE_INTR2_CPU_STATUS_MSI_INTR03_SHIFT 27
/* PCIE_INTR2 :: CPU_STATUS :: MSI_INTR02 [26:26] */
#define BCHP_PCIE_INTR2_CPU_STATUS_MSI_INTR02_MASK 0x04000000
#define BCHP_PCIE_INTR2_CPU_STATUS_MSI_INTR02_SHIFT 26
/* PCIE_INTR2 :: CPU_STATUS :: MSI_INTR01 [25:25] */
#define BCHP_PCIE_INTR2_CPU_STATUS_MSI_INTR01_MASK 0x02000000
#define BCHP_PCIE_INTR2_CPU_STATUS_MSI_INTR01_SHIFT 25
/* PCIE_INTR2 :: CPU_STATUS :: MSI_INTR00 [24:24] */
#define BCHP_PCIE_INTR2_CPU_STATUS_MSI_INTR00_MASK 0x01000000
#define BCHP_PCIE_INTR2_CPU_STATUS_MSI_INTR00_SHIFT 24
/* PCIE_INTR2 :: CPU_STATUS :: UNASSIGNED_23 [23:23] */
#define BCHP_PCIE_INTR2_CPU_STATUS_UNASSIGNED_23_MASK 0x00800000
#define BCHP_PCIE_INTR2_CPU_STATUS_UNASSIGNED_23_SHIFT 23
/* PCIE_INTR2 :: CPU_STATUS :: UNASSIGNED_22 [22:22] */
#define BCHP_PCIE_INTR2_CPU_STATUS_UNASSIGNED_22_MASK 0x00400000
#define BCHP_PCIE_INTR2_CPU_STATUS_UNASSIGNED_22_SHIFT 22
/* PCIE_INTR2 :: CPU_STATUS :: UNASSIGNED_21 [21:21] */
#define BCHP_PCIE_INTR2_CPU_STATUS_UNASSIGNED_21_MASK 0x00200000
#define BCHP_PCIE_INTR2_CPU_STATUS_UNASSIGNED_21_SHIFT 21
/* PCIE_INTR2 :: CPU_STATUS :: UNASSIGNED_20 [20:20] */
#define BCHP_PCIE_INTR2_CPU_STATUS_UNASSIGNED_20_MASK 0x00100000
#define BCHP_PCIE_INTR2_CPU_STATUS_UNASSIGNED_20_SHIFT 20
/* PCIE_INTR2 :: CPU_STATUS :: UNASSIGNED_19 [19:19] */
#define BCHP_PCIE_INTR2_CPU_STATUS_UNASSIGNED_19_MASK 0x00080000
#define BCHP_PCIE_INTR2_CPU_STATUS_UNASSIGNED_19_SHIFT 19
/* PCIE_INTR2 :: CPU_STATUS :: UNASSIGNED_18 [18:18] */
#define BCHP_PCIE_INTR2_CPU_STATUS_UNASSIGNED_18_MASK 0x00040000
#define BCHP_PCIE_INTR2_CPU_STATUS_UNASSIGNED_18_SHIFT 18
/* PCIE_INTR2 :: CPU_STATUS :: UNASSIGNED_17 [17:17] */
#define BCHP_PCIE_INTR2_CPU_STATUS_UNASSIGNED_17_MASK 0x00020000
#define BCHP_PCIE_INTR2_CPU_STATUS_UNASSIGNED_17_SHIFT 17
/* PCIE_INTR2 :: CPU_STATUS :: UNASSIGNED_16 [16:16] */
#define BCHP_PCIE_INTR2_CPU_STATUS_UNASSIGNED_16_MASK 0x00010000
#define BCHP_PCIE_INTR2_CPU_STATUS_UNASSIGNED_16_SHIFT 16
/* PCIE_INTR2 :: CPU_STATUS :: PCIE_MSTR_FWD_ERR [15:15] */
#define BCHP_PCIE_INTR2_CPU_STATUS_PCIE_MSTR_FWD_ERR_MASK 0x00008000
#define BCHP_PCIE_INTR2_CPU_STATUS_PCIE_MSTR_FWD_ERR_SHIFT 15
/* PCIE_INTR2 :: CPU_STATUS :: PCIE_MSTR_RETRY_TIMEOUT [14:14] */
#define BCHP_PCIE_INTR2_CPU_STATUS_PCIE_MSTR_RETRY_TIMEOUT_MASK 0x00004000
#define BCHP_PCIE_INTR2_CPU_STATUS_PCIE_MSTR_RETRY_TIMEOUT_SHIFT 14
/* PCIE_INTR2 :: CPU_STATUS :: PCIE_MSTR_CA_ATTN [13:13] */
#define BCHP_PCIE_INTR2_CPU_STATUS_PCIE_MSTR_CA_ATTN_MASK 0x00002000
#define BCHP_PCIE_INTR2_CPU_STATUS_PCIE_MSTR_CA_ATTN_SHIFT 13
/* PCIE_INTR2 :: CPU_STATUS :: PCIE_MSTR_UR_ATTN [12:12] */
#define BCHP_PCIE_INTR2_CPU_STATUS_PCIE_MSTR_UR_ATTN_MASK 0x00001000
#define BCHP_PCIE_INTR2_CPU_STATUS_PCIE_MSTR_UR_ATTN_SHIFT 12
/* PCIE_INTR2 :: CPU_STATUS :: UNASSIGNED_11 [11:11] */
#define BCHP_PCIE_INTR2_CPU_STATUS_UNASSIGNED_11_MASK 0x00000800
#define BCHP_PCIE_INTR2_CPU_STATUS_UNASSIGNED_11_SHIFT 11
/* PCIE_INTR2 :: CPU_STATUS :: UNASSIGNED_10 [10:10] */
#define BCHP_PCIE_INTR2_CPU_STATUS_UNASSIGNED_10_MASK 0x00000400
#define BCHP_PCIE_INTR2_CPU_STATUS_UNASSIGNED_10_SHIFT 10
/* PCIE_INTR2 :: CPU_STATUS :: PCIE_TGT_BAD_ACCESS [09:09] */
#define BCHP_PCIE_INTR2_CPU_STATUS_PCIE_TGT_BAD_ACCESS_MASK 0x00000200
#define BCHP_PCIE_INTR2_CPU_STATUS_PCIE_TGT_BAD_ACCESS_SHIFT 9
/* PCIE_INTR2 :: CPU_STATUS :: PCIE_TGT_BAD_ADDRESS [08:08] */
#define BCHP_PCIE_INTR2_CPU_STATUS_PCIE_TGT_BAD_ADDRESS_MASK 0x00000100
#define BCHP_PCIE_INTR2_CPU_STATUS_PCIE_TGT_BAD_ADDRESS_SHIFT 8
/* PCIE_INTR2 :: CPU_STATUS :: L1_RX_DMA_ERR_INTR [07:07] */
#define BCHP_PCIE_INTR2_CPU_STATUS_L1_RX_DMA_ERR_INTR_MASK 0x00000080
#define BCHP_PCIE_INTR2_CPU_STATUS_L1_RX_DMA_ERR_INTR_SHIFT 7
/* PCIE_INTR2 :: CPU_STATUS :: L1_RX_DMA_DONE_INTR [06:06] */
#define BCHP_PCIE_INTR2_CPU_STATUS_L1_RX_DMA_DONE_INTR_MASK 0x00000040
#define BCHP_PCIE_INTR2_CPU_STATUS_L1_RX_DMA_DONE_INTR_SHIFT 6
/* PCIE_INTR2 :: CPU_STATUS :: L1_TX_DMA_ERR_INTR [05:05] */
#define BCHP_PCIE_INTR2_CPU_STATUS_L1_TX_DMA_ERR_INTR_MASK 0x00000020
#define BCHP_PCIE_INTR2_CPU_STATUS_L1_TX_DMA_ERR_INTR_SHIFT 5
/* PCIE_INTR2 :: CPU_STATUS :: L1_TX_DMA_DONE_INTR [04:04] */
#define BCHP_PCIE_INTR2_CPU_STATUS_L1_TX_DMA_DONE_INTR_MASK 0x00000010
#define BCHP_PCIE_INTR2_CPU_STATUS_L1_TX_DMA_DONE_INTR_SHIFT 4
/* PCIE_INTR2 :: CPU_STATUS :: L0_RX_DMA_ERR_INTR [03:03] */
#define BCHP_PCIE_INTR2_CPU_STATUS_L0_RX_DMA_ERR_INTR_MASK 0x00000008
#define BCHP_PCIE_INTR2_CPU_STATUS_L0_RX_DMA_ERR_INTR_SHIFT 3
/* PCIE_INTR2 :: CPU_STATUS :: L0_RX_DMA_DONE_INTR [02:02] */
#define BCHP_PCIE_INTR2_CPU_STATUS_L0_RX_DMA_DONE_INTR_MASK 0x00000004
#define BCHP_PCIE_INTR2_CPU_STATUS_L0_RX_DMA_DONE_INTR_SHIFT 2
/* PCIE_INTR2 :: CPU_STATUS :: L0_TX_DMA_ERR_INTR [01:01] */
#define BCHP_PCIE_INTR2_CPU_STATUS_L0_TX_DMA_ERR_INTR_MASK 0x00000002
#define BCHP_PCIE_INTR2_CPU_STATUS_L0_TX_DMA_ERR_INTR_SHIFT 1
/* PCIE_INTR2 :: CPU_STATUS :: L0_TX_DMA_DONE_INTR [00:00] */
#define BCHP_PCIE_INTR2_CPU_STATUS_L0_TX_DMA_DONE_INTR_MASK 0x00000001
#define BCHP_PCIE_INTR2_CPU_STATUS_L0_TX_DMA_DONE_INTR_SHIFT 0
/***************************************************************************
*CPU_SET - CPU interrupt Set Register
***************************************************************************/
/* PCIE_INTR2 :: CPU_SET :: MSI_INTR07 [31:31] */
#define BCHP_PCIE_INTR2_CPU_SET_MSI_INTR07_MASK 0x80000000
#define BCHP_PCIE_INTR2_CPU_SET_MSI_INTR07_SHIFT 31
/* PCIE_INTR2 :: CPU_SET :: MSI_INTR06 [30:30] */
#define BCHP_PCIE_INTR2_CPU_SET_MSI_INTR06_MASK 0x40000000
#define BCHP_PCIE_INTR2_CPU_SET_MSI_INTR06_SHIFT 30
/* PCIE_INTR2 :: CPU_SET :: MSI_INTR05 [29:29] */
#define BCHP_PCIE_INTR2_CPU_SET_MSI_INTR05_MASK 0x20000000
#define BCHP_PCIE_INTR2_CPU_SET_MSI_INTR05_SHIFT 29
/* PCIE_INTR2 :: CPU_SET :: MSI_INTR04 [28:28] */
#define BCHP_PCIE_INTR2_CPU_SET_MSI_INTR04_MASK 0x10000000
#define BCHP_PCIE_INTR2_CPU_SET_MSI_INTR04_SHIFT 28
/* PCIE_INTR2 :: CPU_SET :: MSI_INTR03 [27:27] */
#define BCHP_PCIE_INTR2_CPU_SET_MSI_INTR03_MASK 0x08000000
#define BCHP_PCIE_INTR2_CPU_SET_MSI_INTR03_SHIFT 27
/* PCIE_INTR2 :: CPU_SET :: MSI_INTR02 [26:26] */
#define BCHP_PCIE_INTR2_CPU_SET_MSI_INTR02_MASK 0x04000000
#define BCHP_PCIE_INTR2_CPU_SET_MSI_INTR02_SHIFT 26
/* PCIE_INTR2 :: CPU_SET :: MSI_INTR01 [25:25] */
#define BCHP_PCIE_INTR2_CPU_SET_MSI_INTR01_MASK 0x02000000
#define BCHP_PCIE_INTR2_CPU_SET_MSI_INTR01_SHIFT 25
/* PCIE_INTR2 :: CPU_SET :: MSI_INTR00 [24:24] */
#define BCHP_PCIE_INTR2_CPU_SET_MSI_INTR00_MASK 0x01000000
#define BCHP_PCIE_INTR2_CPU_SET_MSI_INTR00_SHIFT 24
/* PCIE_INTR2 :: CPU_SET :: UNASSIGNED_23 [23:23] */
#define BCHP_PCIE_INTR2_CPU_SET_UNASSIGNED_23_MASK 0x00800000
#define BCHP_PCIE_INTR2_CPU_SET_UNASSIGNED_23_SHIFT 23
/* PCIE_INTR2 :: CPU_SET :: UNASSIGNED_22 [22:22] */
#define BCHP_PCIE_INTR2_CPU_SET_UNASSIGNED_22_MASK 0x00400000
#define BCHP_PCIE_INTR2_CPU_SET_UNASSIGNED_22_SHIFT 22
/* PCIE_INTR2 :: CPU_SET :: UNASSIGNED_21 [21:21] */
#define BCHP_PCIE_INTR2_CPU_SET_UNASSIGNED_21_MASK 0x00200000
#define BCHP_PCIE_INTR2_CPU_SET_UNASSIGNED_21_SHIFT 21
/* PCIE_INTR2 :: CPU_SET :: UNASSIGNED_20 [20:20] */
#define BCHP_PCIE_INTR2_CPU_SET_UNASSIGNED_20_MASK 0x00100000
#define BCHP_PCIE_INTR2_CPU_SET_UNASSIGNED_20_SHIFT 20
/* PCIE_INTR2 :: CPU_SET :: UNASSIGNED_19 [19:19] */
#define BCHP_PCIE_INTR2_CPU_SET_UNASSIGNED_19_MASK 0x00080000
#define BCHP_PCIE_INTR2_CPU_SET_UNASSIGNED_19_SHIFT 19
/* PCIE_INTR2 :: CPU_SET :: UNASSIGNED_18 [18:18] */
#define BCHP_PCIE_INTR2_CPU_SET_UNASSIGNED_18_MASK 0x00040000
#define BCHP_PCIE_INTR2_CPU_SET_UNASSIGNED_18_SHIFT 18
/* PCIE_INTR2 :: CPU_SET :: UNASSIGNED_17 [17:17] */
#define BCHP_PCIE_INTR2_CPU_SET_UNASSIGNED_17_MASK 0x00020000
#define BCHP_PCIE_INTR2_CPU_SET_UNASSIGNED_17_SHIFT 17
/* PCIE_INTR2 :: CPU_SET :: UNASSIGNED_16 [16:16] */
#define BCHP_PCIE_INTR2_CPU_SET_UNASSIGNED_16_MASK 0x00010000
#define BCHP_PCIE_INTR2_CPU_SET_UNASSIGNED_16_SHIFT 16
/* PCIE_INTR2 :: CPU_SET :: PCIE_MSTR_FWD_ERR [15:15] */
#define BCHP_PCIE_INTR2_CPU_SET_PCIE_MSTR_FWD_ERR_MASK 0x00008000
#define BCHP_PCIE_INTR2_CPU_SET_PCIE_MSTR_FWD_ERR_SHIFT 15
/* PCIE_INTR2 :: CPU_SET :: PCIE_MSTR_RETRY_TIMEOUT [14:14] */
#define BCHP_PCIE_INTR2_CPU_SET_PCIE_MSTR_RETRY_TIMEOUT_MASK 0x00004000
#define BCHP_PCIE_INTR2_CPU_SET_PCIE_MSTR_RETRY_TIMEOUT_SHIFT 14
/* PCIE_INTR2 :: CPU_SET :: PCIE_MSTR_CA_ATTN [13:13] */
#define BCHP_PCIE_INTR2_CPU_SET_PCIE_MSTR_CA_ATTN_MASK 0x00002000
#define BCHP_PCIE_INTR2_CPU_SET_PCIE_MSTR_CA_ATTN_SHIFT 13
/* PCIE_INTR2 :: CPU_SET :: PCIE_MSTR_UR_ATTN [12:12] */
#define BCHP_PCIE_INTR2_CPU_SET_PCIE_MSTR_UR_ATTN_MASK 0x00001000
#define BCHP_PCIE_INTR2_CPU_SET_PCIE_MSTR_UR_ATTN_SHIFT 12
/* PCIE_INTR2 :: CPU_SET :: UNASSIGNED_11 [11:11] */
#define BCHP_PCIE_INTR2_CPU_SET_UNASSIGNED_11_MASK 0x00000800
#define BCHP_PCIE_INTR2_CPU_SET_UNASSIGNED_11_SHIFT 11
/* PCIE_INTR2 :: CPU_SET :: UNASSIGNED_10 [10:10] */
#define BCHP_PCIE_INTR2_CPU_SET_UNASSIGNED_10_MASK 0x00000400
#define BCHP_PCIE_INTR2_CPU_SET_UNASSIGNED_10_SHIFT 10
/* PCIE_INTR2 :: CPU_SET :: PCIE_TGT_BAD_ACCESS [09:09] */
#define BCHP_PCIE_INTR2_CPU_SET_PCIE_TGT_BAD_ACCESS_MASK 0x00000200
#define BCHP_PCIE_INTR2_CPU_SET_PCIE_TGT_BAD_ACCESS_SHIFT 9
/* PCIE_INTR2 :: CPU_SET :: PCIE_TGT_BAD_ADDRESS [08:08] */
#define BCHP_PCIE_INTR2_CPU_SET_PCIE_TGT_BAD_ADDRESS_MASK 0x00000100
#define BCHP_PCIE_INTR2_CPU_SET_PCIE_TGT_BAD_ADDRESS_SHIFT 8
/* PCIE_INTR2 :: CPU_SET :: L1_RX_DMA_ERR_INTR [07:07] */
#define BCHP_PCIE_INTR2_CPU_SET_L1_RX_DMA_ERR_INTR_MASK 0x00000080
#define BCHP_PCIE_INTR2_CPU_SET_L1_RX_DMA_ERR_INTR_SHIFT 7
/* PCIE_INTR2 :: CPU_SET :: L1_RX_DMA_DONE_INTR [06:06] */
#define BCHP_PCIE_INTR2_CPU_SET_L1_RX_DMA_DONE_INTR_MASK 0x00000040
#define BCHP_PCIE_INTR2_CPU_SET_L1_RX_DMA_DONE_INTR_SHIFT 6
/* PCIE_INTR2 :: CPU_SET :: L1_TX_DMA_ERR_INTR [05:05] */
#define BCHP_PCIE_INTR2_CPU_SET_L1_TX_DMA_ERR_INTR_MASK 0x00000020
#define BCHP_PCIE_INTR2_CPU_SET_L1_TX_DMA_ERR_INTR_SHIFT 5
/* PCIE_INTR2 :: CPU_SET :: L1_TX_DMA_DONE_INTR [04:04] */
#define BCHP_PCIE_INTR2_CPU_SET_L1_TX_DMA_DONE_INTR_MASK 0x00000010
#define BCHP_PCIE_INTR2_CPU_SET_L1_TX_DMA_DONE_INTR_SHIFT 4
/* PCIE_INTR2 :: CPU_SET :: L0_RX_DMA_ERR_INTR [03:03] */
#define BCHP_PCIE_INTR2_CPU_SET_L0_RX_DMA_ERR_INTR_MASK 0x00000008
#define BCHP_PCIE_INTR2_CPU_SET_L0_RX_DMA_ERR_INTR_SHIFT 3
/* PCIE_INTR2 :: CPU_SET :: L0_RX_DMA_DONE_INTR [02:02] */
#define BCHP_PCIE_INTR2_CPU_SET_L0_RX_DMA_DONE_INTR_MASK 0x00000004
#define BCHP_PCIE_INTR2_CPU_SET_L0_RX_DMA_DONE_INTR_SHIFT 2
/* PCIE_INTR2 :: CPU_SET :: L0_TX_DMA_ERR_INTR [01:01] */
#define BCHP_PCIE_INTR2_CPU_SET_L0_TX_DMA_ERR_INTR_MASK 0x00000002
#define BCHP_PCIE_INTR2_CPU_SET_L0_TX_DMA_ERR_INTR_SHIFT 1
/* PCIE_INTR2 :: CPU_SET :: L0_TX_DMA_DONE_INTR [00:00] */
#define BCHP_PCIE_INTR2_CPU_SET_L0_TX_DMA_DONE_INTR_MASK 0x00000001
#define BCHP_PCIE_INTR2_CPU_SET_L0_TX_DMA_DONE_INTR_SHIFT 0
/***************************************************************************
*CPU_CLEAR - CPU interrupt Clear Register
***************************************************************************/
/* PCIE_INTR2 :: CPU_CLEAR :: MSI_INTR07 [31:31] */
#define BCHP_PCIE_INTR2_CPU_CLEAR_MSI_INTR07_MASK 0x80000000
#define BCHP_PCIE_INTR2_CPU_CLEAR_MSI_INTR07_SHIFT 31
/* PCIE_INTR2 :: CPU_CLEAR :: MSI_INTR06 [30:30] */
#define BCHP_PCIE_INTR2_CPU_CLEAR_MSI_INTR06_MASK 0x40000000
#define BCHP_PCIE_INTR2_CPU_CLEAR_MSI_INTR06_SHIFT 30
/* PCIE_INTR2 :: CPU_CLEAR :: MSI_INTR05 [29:29] */
#define BCHP_PCIE_INTR2_CPU_CLEAR_MSI_INTR05_MASK 0x20000000
#define BCHP_PCIE_INTR2_CPU_CLEAR_MSI_INTR05_SHIFT 29
/* PCIE_INTR2 :: CPU_CLEAR :: MSI_INTR04 [28:28] */
#define BCHP_PCIE_INTR2_CPU_CLEAR_MSI_INTR04_MASK 0x10000000
#define BCHP_PCIE_INTR2_CPU_CLEAR_MSI_INTR04_SHIFT 28
/* PCIE_INTR2 :: CPU_CLEAR :: MSI_INTR03 [27:27] */
#define BCHP_PCIE_INTR2_CPU_CLEAR_MSI_INTR03_MASK 0x08000000
#define BCHP_PCIE_INTR2_CPU_CLEAR_MSI_INTR03_SHIFT 27
/* PCIE_INTR2 :: CPU_CLEAR :: MSI_INTR02 [26:26] */
#define BCHP_PCIE_INTR2_CPU_CLEAR_MSI_INTR02_MASK 0x04000000
#define BCHP_PCIE_INTR2_CPU_CLEAR_MSI_INTR02_SHIFT 26
/* PCIE_INTR2 :: CPU_CLEAR :: MSI_INTR01 [25:25] */
#define BCHP_PCIE_INTR2_CPU_CLEAR_MSI_INTR01_MASK 0x02000000
#define BCHP_PCIE_INTR2_CPU_CLEAR_MSI_INTR01_SHIFT 25
/* PCIE_INTR2 :: CPU_CLEAR :: MSI_INTR00 [24:24] */
#define BCHP_PCIE_INTR2_CPU_CLEAR_MSI_INTR00_MASK 0x01000000
#define BCHP_PCIE_INTR2_CPU_CLEAR_MSI_INTR00_SHIFT 24
/* PCIE_INTR2 :: CPU_CLEAR :: UNASSIGNED_23 [23:23] */
#define BCHP_PCIE_INTR2_CPU_CLEAR_UNASSIGNED_23_MASK 0x00800000
#define BCHP_PCIE_INTR2_CPU_CLEAR_UNASSIGNED_23_SHIFT 23
/* PCIE_INTR2 :: CPU_CLEAR :: UNASSIGNED_22 [22:22] */
#define BCHP_PCIE_INTR2_CPU_CLEAR_UNASSIGNED_22_MASK 0x00400000
#define BCHP_PCIE_INTR2_CPU_CLEAR_UNASSIGNED_22_SHIFT 22
/* PCIE_INTR2 :: CPU_CLEAR :: UNASSIGNED_21 [21:21] */
#define BCHP_PCIE_INTR2_CPU_CLEAR_UNASSIGNED_21_MASK 0x00200000
#define BCHP_PCIE_INTR2_CPU_CLEAR_UNASSIGNED_21_SHIFT 21
/* PCIE_INTR2 :: CPU_CLEAR :: UNASSIGNED_20 [20:20] */
#define BCHP_PCIE_INTR2_CPU_CLEAR_UNASSIGNED_20_MASK 0x00100000
#define BCHP_PCIE_INTR2_CPU_CLEAR_UNASSIGNED_20_SHIFT 20
/* PCIE_INTR2 :: CPU_CLEAR :: UNASSIGNED_19 [19:19] */
#define BCHP_PCIE_INTR2_CPU_CLEAR_UNASSIGNED_19_MASK 0x00080000
#define BCHP_PCIE_INTR2_CPU_CLEAR_UNASSIGNED_19_SHIFT 19
/* PCIE_INTR2 :: CPU_CLEAR :: UNASSIGNED_18 [18:18] */
#define BCHP_PCIE_INTR2_CPU_CLEAR_UNASSIGNED_18_MASK 0x00040000
#define BCHP_PCIE_INTR2_CPU_CLEAR_UNASSIGNED_18_SHIFT 18
/* PCIE_INTR2 :: CPU_CLEAR :: UNASSIGNED_17 [17:17] */
#define BCHP_PCIE_INTR2_CPU_CLEAR_UNASSIGNED_17_MASK 0x00020000
#define BCHP_PCIE_INTR2_CPU_CLEAR_UNASSIGNED_17_SHIFT 17
/* PCIE_INTR2 :: CPU_CLEAR :: UNASSIGNED_16 [16:16] */
#define BCHP_PCIE_INTR2_CPU_CLEAR_UNASSIGNED_16_MASK 0x00010000
#define BCHP_PCIE_INTR2_CPU_CLEAR_UNASSIGNED_16_SHIFT 16
/* PCIE_INTR2 :: CPU_CLEAR :: PCIE_MSTR_FWD_ERR [15:15] */
#define BCHP_PCIE_INTR2_CPU_CLEAR_PCIE_MSTR_FWD_ERR_MASK 0x00008000
#define BCHP_PCIE_INTR2_CPU_CLEAR_PCIE_MSTR_FWD_ERR_SHIFT 15
/* PCIE_INTR2 :: CPU_CLEAR :: PCIE_MSTR_RETRY_TIMEOUT [14:14] */
#define BCHP_PCIE_INTR2_CPU_CLEAR_PCIE_MSTR_RETRY_TIMEOUT_MASK 0x00004000
#define BCHP_PCIE_INTR2_CPU_CLEAR_PCIE_MSTR_RETRY_TIMEOUT_SHIFT 14
/* PCIE_INTR2 :: CPU_CLEAR :: PCIE_MSTR_CA_ATTN [13:13] */
#define BCHP_PCIE_INTR2_CPU_CLEAR_PCIE_MSTR_CA_ATTN_MASK 0x00002000
#define BCHP_PCIE_INTR2_CPU_CLEAR_PCIE_MSTR_CA_ATTN_SHIFT 13
/* PCIE_INTR2 :: CPU_CLEAR :: PCIE_MSTR_UR_ATTN [12:12] */
#define BCHP_PCIE_INTR2_CPU_CLEAR_PCIE_MSTR_UR_ATTN_MASK 0x00001000
#define BCHP_PCIE_INTR2_CPU_CLEAR_PCIE_MSTR_UR_ATTN_SHIFT 12
/* PCIE_INTR2 :: CPU_CLEAR :: UNASSIGNED_11 [11:11] */
#define BCHP_PCIE_INTR2_CPU_CLEAR_UNASSIGNED_11_MASK 0x00000800
#define BCHP_PCIE_INTR2_CPU_CLEAR_UNASSIGNED_11_SHIFT 11
/* PCIE_INTR2 :: CPU_CLEAR :: UNASSIGNED_10 [10:10] */
#define BCHP_PCIE_INTR2_CPU_CLEAR_UNASSIGNED_10_MASK 0x00000400
#define BCHP_PCIE_INTR2_CPU_CLEAR_UNASSIGNED_10_SHIFT 10
/* PCIE_INTR2 :: CPU_CLEAR :: PCIE_TGT_BAD_ACCESS [09:09] */
#define BCHP_PCIE_INTR2_CPU_CLEAR_PCIE_TGT_BAD_ACCESS_MASK 0x00000200
#define BCHP_PCIE_INTR2_CPU_CLEAR_PCIE_TGT_BAD_ACCESS_SHIFT 9
/* PCIE_INTR2 :: CPU_CLEAR :: PCIE_TGT_BAD_ADDRESS [08:08] */
#define BCHP_PCIE_INTR2_CPU_CLEAR_PCIE_TGT_BAD_ADDRESS_MASK 0x00000100
#define BCHP_PCIE_INTR2_CPU_CLEAR_PCIE_TGT_BAD_ADDRESS_SHIFT 8
/* PCIE_INTR2 :: CPU_CLEAR :: L1_RX_DMA_ERR_INTR [07:07] */
#define BCHP_PCIE_INTR2_CPU_CLEAR_L1_RX_DMA_ERR_INTR_MASK 0x00000080
#define BCHP_PCIE_INTR2_CPU_CLEAR_L1_RX_DMA_ERR_INTR_SHIFT 7
/* PCIE_INTR2 :: CPU_CLEAR :: L1_RX_DMA_DONE_INTR [06:06] */
#define BCHP_PCIE_INTR2_CPU_CLEAR_L1_RX_DMA_DONE_INTR_MASK 0x00000040
#define BCHP_PCIE_INTR2_CPU_CLEAR_L1_RX_DMA_DONE_INTR_SHIFT 6
/* PCIE_INTR2 :: CPU_CLEAR :: L1_TX_DMA_ERR_INTR [05:05] */
#define BCHP_PCIE_INTR2_CPU_CLEAR_L1_TX_DMA_ERR_INTR_MASK 0x00000020
#define BCHP_PCIE_INTR2_CPU_CLEAR_L1_TX_DMA_ERR_INTR_SHIFT 5
/* PCIE_INTR2 :: CPU_CLEAR :: L1_TX_DMA_DONE_INTR [04:04] */
#define BCHP_PCIE_INTR2_CPU_CLEAR_L1_TX_DMA_DONE_INTR_MASK 0x00000010
#define BCHP_PCIE_INTR2_CPU_CLEAR_L1_TX_DMA_DONE_INTR_SHIFT 4
/* PCIE_INTR2 :: CPU_CLEAR :: L0_RX_DMA_ERR_INTR [03:03] */
#define BCHP_PCIE_INTR2_CPU_CLEAR_L0_RX_DMA_ERR_INTR_MASK 0x00000008
#define BCHP_PCIE_INTR2_CPU_CLEAR_L0_RX_DMA_ERR_INTR_SHIFT 3
/* PCIE_INTR2 :: CPU_CLEAR :: L0_RX_DMA_DONE_INTR [02:02] */
#define BCHP_PCIE_INTR2_CPU_CLEAR_L0_RX_DMA_DONE_INTR_MASK 0x00000004
#define BCHP_PCIE_INTR2_CPU_CLEAR_L0_RX_DMA_DONE_INTR_SHIFT 2
/* PCIE_INTR2 :: CPU_CLEAR :: L0_TX_DMA_ERR_INTR [01:01] */
#define BCHP_PCIE_INTR2_CPU_CLEAR_L0_TX_DMA_ERR_INTR_MASK 0x00000002
#define BCHP_PCIE_INTR2_CPU_CLEAR_L0_TX_DMA_ERR_INTR_SHIFT 1
/* PCIE_INTR2 :: CPU_CLEAR :: L0_TX_DMA_DONE_INTR [00:00] */
#define BCHP_PCIE_INTR2_CPU_CLEAR_L0_TX_DMA_DONE_INTR_MASK 0x00000001
#define BCHP_PCIE_INTR2_CPU_CLEAR_L0_TX_DMA_DONE_INTR_SHIFT 0
/***************************************************************************
*CPU_MASK_STATUS - CPU interrupt Mask Status Register
***************************************************************************/
/* PCIE_INTR2 :: CPU_MASK_STATUS :: MSI_INTR07 [31:31] */
#define BCHP_PCIE_INTR2_CPU_MASK_STATUS_MSI_INTR07_MASK 0x80000000
#define BCHP_PCIE_INTR2_CPU_MASK_STATUS_MSI_INTR07_SHIFT 31
/* PCIE_INTR2 :: CPU_MASK_STATUS :: MSI_INTR06 [30:30] */
#define BCHP_PCIE_INTR2_CPU_MASK_STATUS_MSI_INTR06_MASK 0x40000000
#define BCHP_PCIE_INTR2_CPU_MASK_STATUS_MSI_INTR06_SHIFT 30
/* PCIE_INTR2 :: CPU_MASK_STATUS :: MSI_INTR05 [29:29] */
#define BCHP_PCIE_INTR2_CPU_MASK_STATUS_MSI_INTR05_MASK 0x20000000
#define BCHP_PCIE_INTR2_CPU_MASK_STATUS_MSI_INTR05_SHIFT 29
/* PCIE_INTR2 :: CPU_MASK_STATUS :: MSI_INTR04 [28:28] */
#define BCHP_PCIE_INTR2_CPU_MASK_STATUS_MSI_INTR04_MASK 0x10000000
#define BCHP_PCIE_INTR2_CPU_MASK_STATUS_MSI_INTR04_SHIFT 28
/* PCIE_INTR2 :: CPU_MASK_STATUS :: MSI_INTR03 [27:27] */
#define BCHP_PCIE_INTR2_CPU_MASK_STATUS_MSI_INTR03_MASK 0x08000000
#define BCHP_PCIE_INTR2_CPU_MASK_STATUS_MSI_INTR03_SHIFT 27
/* PCIE_INTR2 :: CPU_MASK_STATUS :: MSI_INTR02 [26:26] */
#define BCHP_PCIE_INTR2_CPU_MASK_STATUS_MSI_INTR02_MASK 0x04000000
#define BCHP_PCIE_INTR2_CPU_MASK_STATUS_MSI_INTR02_SHIFT 26
/* PCIE_INTR2 :: CPU_MASK_STATUS :: MSI_INTR01 [25:25] */
#define BCHP_PCIE_INTR2_CPU_MASK_STATUS_MSI_INTR01_MASK 0x02000000
#define BCHP_PCIE_INTR2_CPU_MASK_STATUS_MSI_INTR01_SHIFT 25
/* PCIE_INTR2 :: CPU_MASK_STATUS :: MSI_INTR00 [24:24] */
#define BCHP_PCIE_INTR2_CPU_MASK_STATUS_MSI_INTR00_MASK 0x01000000
#define BCHP_PCIE_INTR2_CPU_MASK_STATUS_MSI_INTR00_SHIFT 24
/* PCIE_INTR2 :: CPU_MASK_STATUS :: UNASSIGNED_23 [23:23] */
#define BCHP_PCIE_INTR2_CPU_MASK_STATUS_UNASSIGNED_23_MASK 0x00800000
#define BCHP_PCIE_INTR2_CPU_MASK_STATUS_UNASSIGNED_23_SHIFT 23
/* PCIE_INTR2 :: CPU_MASK_STATUS :: UNASSIGNED_22 [22:22] */
#define BCHP_PCIE_INTR2_CPU_MASK_STATUS_UNASSIGNED_22_MASK 0x00400000
#define BCHP_PCIE_INTR2_CPU_MASK_STATUS_UNASSIGNED_22_SHIFT 22
/* PCIE_INTR2 :: CPU_MASK_STATUS :: UNASSIGNED_21 [21:21] */
#define BCHP_PCIE_INTR2_CPU_MASK_STATUS_UNASSIGNED_21_MASK 0x00200000
#define BCHP_PCIE_INTR2_CPU_MASK_STATUS_UNASSIGNED_21_SHIFT 21
/* PCIE_INTR2 :: CPU_MASK_STATUS :: UNASSIGNED_20 [20:20] */
#define BCHP_PCIE_INTR2_CPU_MASK_STATUS_UNASSIGNED_20_MASK 0x00100000
#define BCHP_PCIE_INTR2_CPU_MASK_STATUS_UNASSIGNED_20_SHIFT 20
/* PCIE_INTR2 :: CPU_MASK_STATUS :: UNASSIGNED_19 [19:19] */
#define BCHP_PCIE_INTR2_CPU_MASK_STATUS_UNASSIGNED_19_MASK 0x00080000
#define BCHP_PCIE_INTR2_CPU_MASK_STATUS_UNASSIGNED_19_SHIFT 19
/* PCIE_INTR2 :: CPU_MASK_STATUS :: UNASSIGNED_18 [18:18] */
#define BCHP_PCIE_INTR2_CPU_MASK_STATUS_UNASSIGNED_18_MASK 0x00040000
#define BCHP_PCIE_INTR2_CPU_MASK_STATUS_UNASSIGNED_18_SHIFT 18
/* PCIE_INTR2 :: CPU_MASK_STATUS :: UNASSIGNED_17 [17:17] */
#define BCHP_PCIE_INTR2_CPU_MASK_STATUS_UNASSIGNED_17_MASK 0x00020000
#define BCHP_PCIE_INTR2_CPU_MASK_STATUS_UNASSIGNED_17_SHIFT 17
/* PCIE_INTR2 :: CPU_MASK_STATUS :: UNASSIGNED_16 [16:16] */
#define BCHP_PCIE_INTR2_CPU_MASK_STATUS_UNASSIGNED_16_MASK 0x00010000
#define BCHP_PCIE_INTR2_CPU_MASK_STATUS_UNASSIGNED_16_SHIFT 16
/* PCIE_INTR2 :: CPU_MASK_STATUS :: PCIE_MSTR_FWD_ERR [15:15] */
#define BCHP_PCIE_INTR2_CPU_MASK_STATUS_PCIE_MSTR_FWD_ERR_MASK 0x00008000
#define BCHP_PCIE_INTR2_CPU_MASK_STATUS_PCIE_MSTR_FWD_ERR_SHIFT 15
/* PCIE_INTR2 :: CPU_MASK_STATUS :: PCIE_MSTR_RETRY_TIMEOUT [14:14] */
#define BCHP_PCIE_INTR2_CPU_MASK_STATUS_PCIE_MSTR_RETRY_TIMEOUT_MASK 0x00004000
#define BCHP_PCIE_INTR2_CPU_MASK_STATUS_PCIE_MSTR_RETRY_TIMEOUT_SHIFT 14
/* PCIE_INTR2 :: CPU_MASK_STATUS :: PCIE_MSTR_CA_ATTN [13:13] */
#define BCHP_PCIE_INTR2_CPU_MASK_STATUS_PCIE_MSTR_CA_ATTN_MASK 0x00002000
#define BCHP_PCIE_INTR2_CPU_MASK_STATUS_PCIE_MSTR_CA_ATTN_SHIFT 13
/* PCIE_INTR2 :: CPU_MASK_STATUS :: PCIE_MSTR_UR_ATTN [12:12] */
#define BCHP_PCIE_INTR2_CPU_MASK_STATUS_PCIE_MSTR_UR_ATTN_MASK 0x00001000
#define BCHP_PCIE_INTR2_CPU_MASK_STATUS_PCIE_MSTR_UR_ATTN_SHIFT 12
/* PCIE_INTR2 :: CPU_MASK_STATUS :: UNASSIGNED_11 [11:11] */
#define BCHP_PCIE_INTR2_CPU_MASK_STATUS_UNASSIGNED_11_MASK 0x00000800
#define BCHP_PCIE_INTR2_CPU_MASK_STATUS_UNASSIGNED_11_SHIFT 11
/* PCIE_INTR2 :: CPU_MASK_STATUS :: UNASSIGNED_10 [10:10] */
#define BCHP_PCIE_INTR2_CPU_MASK_STATUS_UNASSIGNED_10_MASK 0x00000400
#define BCHP_PCIE_INTR2_CPU_MASK_STATUS_UNASSIGNED_10_SHIFT 10
/* PCIE_INTR2 :: CPU_MASK_STATUS :: PCIE_TGT_BAD_ACCESS [09:09] */
#define BCHP_PCIE_INTR2_CPU_MASK_STATUS_PCIE_TGT_BAD_ACCESS_MASK 0x00000200
#define BCHP_PCIE_INTR2_CPU_MASK_STATUS_PCIE_TGT_BAD_ACCESS_SHIFT 9
/* PCIE_INTR2 :: CPU_MASK_STATUS :: PCIE_TGT_BAD_ADDRESS [08:08] */
#define BCHP_PCIE_INTR2_CPU_MASK_STATUS_PCIE_TGT_BAD_ADDRESS_MASK 0x00000100
#define BCHP_PCIE_INTR2_CPU_MASK_STATUS_PCIE_TGT_BAD_ADDRESS_SHIFT 8
/* PCIE_INTR2 :: CPU_MASK_STATUS :: L1_RX_DMA_ERR_INTR [07:07] */
#define BCHP_PCIE_INTR2_CPU_MASK_STATUS_L1_RX_DMA_ERR_INTR_MASK 0x00000080
#define BCHP_PCIE_INTR2_CPU_MASK_STATUS_L1_RX_DMA_ERR_INTR_SHIFT 7
/* PCIE_INTR2 :: CPU_MASK_STATUS :: L1_RX_DMA_DONE_INTR [06:06] */
#define BCHP_PCIE_INTR2_CPU_MASK_STATUS_L1_RX_DMA_DONE_INTR_MASK 0x00000040
#define BCHP_PCIE_INTR2_CPU_MASK_STATUS_L1_RX_DMA_DONE_INTR_SHIFT 6
/* PCIE_INTR2 :: CPU_MASK_STATUS :: L1_TX_DMA_ERR_INTR [05:05] */
#define BCHP_PCIE_INTR2_CPU_MASK_STATUS_L1_TX_DMA_ERR_INTR_MASK 0x00000020
#define BCHP_PCIE_INTR2_CPU_MASK_STATUS_L1_TX_DMA_ERR_INTR_SHIFT 5
/* PCIE_INTR2 :: CPU_MASK_STATUS :: L1_TX_DMA_DONE_INTR [04:04] */
#define BCHP_PCIE_INTR2_CPU_MASK_STATUS_L1_TX_DMA_DONE_INTR_MASK 0x00000010
#define BCHP_PCIE_INTR2_CPU_MASK_STATUS_L1_TX_DMA_DONE_INTR_SHIFT 4
/* PCIE_INTR2 :: CPU_MASK_STATUS :: L0_RX_DMA_ERR_INTR [03:03] */
#define BCHP_PCIE_INTR2_CPU_MASK_STATUS_L0_RX_DMA_ERR_INTR_MASK 0x00000008
#define BCHP_PCIE_INTR2_CPU_MASK_STATUS_L0_RX_DMA_ERR_INTR_SHIFT 3
/* PCIE_INTR2 :: CPU_MASK_STATUS :: L0_RX_DMA_DONE_INTR [02:02] */
#define BCHP_PCIE_INTR2_CPU_MASK_STATUS_L0_RX_DMA_DONE_INTR_MASK 0x00000004
#define BCHP_PCIE_INTR2_CPU_MASK_STATUS_L0_RX_DMA_DONE_INTR_SHIFT 2
/* PCIE_INTR2 :: CPU_MASK_STATUS :: L0_TX_DMA_ERR_INTR [01:01] */
#define BCHP_PCIE_INTR2_CPU_MASK_STATUS_L0_TX_DMA_ERR_INTR_MASK 0x00000002
#define BCHP_PCIE_INTR2_CPU_MASK_STATUS_L0_TX_DMA_ERR_INTR_SHIFT 1
/* PCIE_INTR2 :: CPU_MASK_STATUS :: L0_TX_DMA_DONE_INTR [00:00] */
#define BCHP_PCIE_INTR2_CPU_MASK_STATUS_L0_TX_DMA_DONE_INTR_MASK 0x00000001
#define BCHP_PCIE_INTR2_CPU_MASK_STATUS_L0_TX_DMA_DONE_INTR_SHIFT 0
/***************************************************************************
*CPU_MASK_SET - CPU interrupt Mask Set Register
***************************************************************************/
/* PCIE_INTR2 :: CPU_MASK_SET :: MSI_INTR07 [31:31] */
#define BCHP_PCIE_INTR2_CPU_MASK_SET_MSI_INTR07_MASK 0x80000000
#define BCHP_PCIE_INTR2_CPU_MASK_SET_MSI_INTR07_SHIFT 31
/* PCIE_INTR2 :: CPU_MASK_SET :: MSI_INTR06 [30:30] */
#define BCHP_PCIE_INTR2_CPU_MASK_SET_MSI_INTR06_MASK 0x40000000
#define BCHP_PCIE_INTR2_CPU_MASK_SET_MSI_INTR06_SHIFT 30
/* PCIE_INTR2 :: CPU_MASK_SET :: MSI_INTR05 [29:29] */
#define BCHP_PCIE_INTR2_CPU_MASK_SET_MSI_INTR05_MASK 0x20000000
#define BCHP_PCIE_INTR2_CPU_MASK_SET_MSI_INTR05_SHIFT 29
/* PCIE_INTR2 :: CPU_MASK_SET :: MSI_INTR04 [28:28] */
#define BCHP_PCIE_INTR2_CPU_MASK_SET_MSI_INTR04_MASK 0x10000000
#define BCHP_PCIE_INTR2_CPU_MASK_SET_MSI_INTR04_SHIFT 28
/* PCIE_INTR2 :: CPU_MASK_SET :: MSI_INTR03 [27:27] */
#define BCHP_PCIE_INTR2_CPU_MASK_SET_MSI_INTR03_MASK 0x08000000
#define BCHP_PCIE_INTR2_CPU_MASK_SET_MSI_INTR03_SHIFT 27
/* PCIE_INTR2 :: CPU_MASK_SET :: MSI_INTR02 [26:26] */
#define BCHP_PCIE_INTR2_CPU_MASK_SET_MSI_INTR02_MASK 0x04000000
#define BCHP_PCIE_INTR2_CPU_MASK_SET_MSI_INTR02_SHIFT 26
/* PCIE_INTR2 :: CPU_MASK_SET :: MSI_INTR01 [25:25] */
#define BCHP_PCIE_INTR2_CPU_MASK_SET_MSI_INTR01_MASK 0x02000000
#define BCHP_PCIE_INTR2_CPU_MASK_SET_MSI_INTR01_SHIFT 25
/* PCIE_INTR2 :: CPU_MASK_SET :: MSI_INTR00 [24:24] */
#define BCHP_PCIE_INTR2_CPU_MASK_SET_MSI_INTR00_MASK 0x01000000
#define BCHP_PCIE_INTR2_CPU_MASK_SET_MSI_INTR00_SHIFT 24
/* PCIE_INTR2 :: CPU_MASK_SET :: UNASSIGNED_23 [23:23] */
#define BCHP_PCIE_INTR2_CPU_MASK_SET_UNASSIGNED_23_MASK 0x00800000
#define BCHP_PCIE_INTR2_CPU_MASK_SET_UNASSIGNED_23_SHIFT 23
/* PCIE_INTR2 :: CPU_MASK_SET :: UNASSIGNED_22 [22:22] */
#define BCHP_PCIE_INTR2_CPU_MASK_SET_UNASSIGNED_22_MASK 0x00400000
#define BCHP_PCIE_INTR2_CPU_MASK_SET_UNASSIGNED_22_SHIFT 22
/* PCIE_INTR2 :: CPU_MASK_SET :: UNASSIGNED_21 [21:21] */
#define BCHP_PCIE_INTR2_CPU_MASK_SET_UNASSIGNED_21_MASK 0x00200000
#define BCHP_PCIE_INTR2_CPU_MASK_SET_UNASSIGNED_21_SHIFT 21
/* PCIE_INTR2 :: CPU_MASK_SET :: UNASSIGNED_20 [20:20] */
#define BCHP_PCIE_INTR2_CPU_MASK_SET_UNASSIGNED_20_MASK 0x00100000
#define BCHP_PCIE_INTR2_CPU_MASK_SET_UNASSIGNED_20_SHIFT 20
/* PCIE_INTR2 :: CPU_MASK_SET :: UNASSIGNED_19 [19:19] */
#define BCHP_PCIE_INTR2_CPU_MASK_SET_UNASSIGNED_19_MASK 0x00080000
#define BCHP_PCIE_INTR2_CPU_MASK_SET_UNASSIGNED_19_SHIFT 19
/* PCIE_INTR2 :: CPU_MASK_SET :: UNASSIGNED_18 [18:18] */
#define BCHP_PCIE_INTR2_CPU_MASK_SET_UNASSIGNED_18_MASK 0x00040000
#define BCHP_PCIE_INTR2_CPU_MASK_SET_UNASSIGNED_18_SHIFT 18
/* PCIE_INTR2 :: CPU_MASK_SET :: UNASSIGNED_17 [17:17] */
#define BCHP_PCIE_INTR2_CPU_MASK_SET_UNASSIGNED_17_MASK 0x00020000
#define BCHP_PCIE_INTR2_CPU_MASK_SET_UNASSIGNED_17_SHIFT 17
/* PCIE_INTR2 :: CPU_MASK_SET :: UNASSIGNED_16 [16:16] */
#define BCHP_PCIE_INTR2_CPU_MASK_SET_UNASSIGNED_16_MASK 0x00010000
#define BCHP_PCIE_INTR2_CPU_MASK_SET_UNASSIGNED_16_SHIFT 16
/* PCIE_INTR2 :: CPU_MASK_SET :: PCIE_MSTR_FWD_ERR [15:15] */
#define BCHP_PCIE_INTR2_CPU_MASK_SET_PCIE_MSTR_FWD_ERR_MASK 0x00008000
#define BCHP_PCIE_INTR2_CPU_MASK_SET_PCIE_MSTR_FWD_ERR_SHIFT 15
/* PCIE_INTR2 :: CPU_MASK_SET :: PCIE_MSTR_RETRY_TIMEOUT [14:14] */
#define BCHP_PCIE_INTR2_CPU_MASK_SET_PCIE_MSTR_RETRY_TIMEOUT_MASK 0x00004000
#define BCHP_PCIE_INTR2_CPU_MASK_SET_PCIE_MSTR_RETRY_TIMEOUT_SHIFT 14
/* PCIE_INTR2 :: CPU_MASK_SET :: PCIE_MSTR_CA_ATTN [13:13] */
#define BCHP_PCIE_INTR2_CPU_MASK_SET_PCIE_MSTR_CA_ATTN_MASK 0x00002000
#define BCHP_PCIE_INTR2_CPU_MASK_SET_PCIE_MSTR_CA_ATTN_SHIFT 13
/* PCIE_INTR2 :: CPU_MASK_SET :: PCIE_MSTR_UR_ATTN [12:12] */
#define BCHP_PCIE_INTR2_CPU_MASK_SET_PCIE_MSTR_UR_ATTN_MASK 0x00001000
#define BCHP_PCIE_INTR2_CPU_MASK_SET_PCIE_MSTR_UR_ATTN_SHIFT 12
/* PCIE_INTR2 :: CPU_MASK_SET :: UNASSIGNED_11 [11:11] */
#define BCHP_PCIE_INTR2_CPU_MASK_SET_UNASSIGNED_11_MASK 0x00000800
#define BCHP_PCIE_INTR2_CPU_MASK_SET_UNASSIGNED_11_SHIFT 11
/* PCIE_INTR2 :: CPU_MASK_SET :: UNASSIGNED_10 [10:10] */
#define BCHP_PCIE_INTR2_CPU_MASK_SET_UNASSIGNED_10_MASK 0x00000400
#define BCHP_PCIE_INTR2_CPU_MASK_SET_UNASSIGNED_10_SHIFT 10
/* PCIE_INTR2 :: CPU_MASK_SET :: PCIE_TGT_BAD_ACCESS [09:09] */
#define BCHP_PCIE_INTR2_CPU_MASK_SET_PCIE_TGT_BAD_ACCESS_MASK 0x00000200
#define BCHP_PCIE_INTR2_CPU_MASK_SET_PCIE_TGT_BAD_ACCESS_SHIFT 9
/* PCIE_INTR2 :: CPU_MASK_SET :: PCIE_TGT_BAD_ADDRESS [08:08] */
#define BCHP_PCIE_INTR2_CPU_MASK_SET_PCIE_TGT_BAD_ADDRESS_MASK 0x00000100
#define BCHP_PCIE_INTR2_CPU_MASK_SET_PCIE_TGT_BAD_ADDRESS_SHIFT 8
/* PCIE_INTR2 :: CPU_MASK_SET :: L1_RX_DMA_ERR_INTR [07:07] */
#define BCHP_PCIE_INTR2_CPU_MASK_SET_L1_RX_DMA_ERR_INTR_MASK 0x00000080
#define BCHP_PCIE_INTR2_CPU_MASK_SET_L1_RX_DMA_ERR_INTR_SHIFT 7
/* PCIE_INTR2 :: CPU_MASK_SET :: L1_RX_DMA_DONE_INTR [06:06] */
#define BCHP_PCIE_INTR2_CPU_MASK_SET_L1_RX_DMA_DONE_INTR_MASK 0x00000040
#define BCHP_PCIE_INTR2_CPU_MASK_SET_L1_RX_DMA_DONE_INTR_SHIFT 6
/* PCIE_INTR2 :: CPU_MASK_SET :: L1_TX_DMA_ERR_INTR [05:05] */
#define BCHP_PCIE_INTR2_CPU_MASK_SET_L1_TX_DMA_ERR_INTR_MASK 0x00000020
#define BCHP_PCIE_INTR2_CPU_MASK_SET_L1_TX_DMA_ERR_INTR_SHIFT 5
/* PCIE_INTR2 :: CPU_MASK_SET :: L1_TX_DMA_DONE_INTR [04:04] */
#define BCHP_PCIE_INTR2_CPU_MASK_SET_L1_TX_DMA_DONE_INTR_MASK 0x00000010
#define BCHP_PCIE_INTR2_CPU_MASK_SET_L1_TX_DMA_DONE_INTR_SHIFT 4
/* PCIE_INTR2 :: CPU_MASK_SET :: L0_RX_DMA_ERR_INTR [03:03] */
#define BCHP_PCIE_INTR2_CPU_MASK_SET_L0_RX_DMA_ERR_INTR_MASK 0x00000008
#define BCHP_PCIE_INTR2_CPU_MASK_SET_L0_RX_DMA_ERR_INTR_SHIFT 3
/* PCIE_INTR2 :: CPU_MASK_SET :: L0_RX_DMA_DONE_INTR [02:02] */
#define BCHP_PCIE_INTR2_CPU_MASK_SET_L0_RX_DMA_DONE_INTR_MASK 0x00000004
#define BCHP_PCIE_INTR2_CPU_MASK_SET_L0_RX_DMA_DONE_INTR_SHIFT 2
/* PCIE_INTR2 :: CPU_MASK_SET :: L0_TX_DMA_ERR_INTR [01:01] */
#define BCHP_PCIE_INTR2_CPU_MASK_SET_L0_TX_DMA_ERR_INTR_MASK 0x00000002
#define BCHP_PCIE_INTR2_CPU_MASK_SET_L0_TX_DMA_ERR_INTR_SHIFT 1
/* PCIE_INTR2 :: CPU_MASK_SET :: L0_TX_DMA_DONE_INTR [00:00] */
#define BCHP_PCIE_INTR2_CPU_MASK_SET_L0_TX_DMA_DONE_INTR_MASK 0x00000001
#define BCHP_PCIE_INTR2_CPU_MASK_SET_L0_TX_DMA_DONE_INTR_SHIFT 0
/***************************************************************************
*CPU_MASK_CLEAR - CPU interrupt Mask Clear Register
***************************************************************************/
/* PCIE_INTR2 :: CPU_MASK_CLEAR :: MSI_INTR07 [31:31] */
#define BCHP_PCIE_INTR2_CPU_MASK_CLEAR_MSI_INTR07_MASK 0x80000000
#define BCHP_PCIE_INTR2_CPU_MASK_CLEAR_MSI_INTR07_SHIFT 31
/* PCIE_INTR2 :: CPU_MASK_CLEAR :: MSI_INTR06 [30:30] */
#define BCHP_PCIE_INTR2_CPU_MASK_CLEAR_MSI_INTR06_MASK 0x40000000
#define BCHP_PCIE_INTR2_CPU_MASK_CLEAR_MSI_INTR06_SHIFT 30
/* PCIE_INTR2 :: CPU_MASK_CLEAR :: MSI_INTR05 [29:29] */
#define BCHP_PCIE_INTR2_CPU_MASK_CLEAR_MSI_INTR05_MASK 0x20000000
#define BCHP_PCIE_INTR2_CPU_MASK_CLEAR_MSI_INTR05_SHIFT 29
/* PCIE_INTR2 :: CPU_MASK_CLEAR :: MSI_INTR04 [28:28] */
#define BCHP_PCIE_INTR2_CPU_MASK_CLEAR_MSI_INTR04_MASK 0x10000000
#define BCHP_PCIE_INTR2_CPU_MASK_CLEAR_MSI_INTR04_SHIFT 28
/* PCIE_INTR2 :: CPU_MASK_CLEAR :: MSI_INTR03 [27:27] */
#define BCHP_PCIE_INTR2_CPU_MASK_CLEAR_MSI_INTR03_MASK 0x08000000
#define BCHP_PCIE_INTR2_CPU_MASK_CLEAR_MSI_INTR03_SHIFT 27
/* PCIE_INTR2 :: CPU_MASK_CLEAR :: MSI_INTR02 [26:26] */
#define BCHP_PCIE_INTR2_CPU_MASK_CLEAR_MSI_INTR02_MASK 0x04000000
#define BCHP_PCIE_INTR2_CPU_MASK_CLEAR_MSI_INTR02_SHIFT 26
/* PCIE_INTR2 :: CPU_MASK_CLEAR :: MSI_INTR01 [25:25] */
#define BCHP_PCIE_INTR2_CPU_MASK_CLEAR_MSI_INTR01_MASK 0x02000000
#define BCHP_PCIE_INTR2_CPU_MASK_CLEAR_MSI_INTR01_SHIFT 25
/* PCIE_INTR2 :: CPU_MASK_CLEAR :: MSI_INTR00 [24:24] */
#define BCHP_PCIE_INTR2_CPU_MASK_CLEAR_MSI_INTR00_MASK 0x01000000
#define BCHP_PCIE_INTR2_CPU_MASK_CLEAR_MSI_INTR00_SHIFT 24
/* PCIE_INTR2 :: CPU_MASK_CLEAR :: UNASSIGNED_23 [23:23] */
#define BCHP_PCIE_INTR2_CPU_MASK_CLEAR_UNASSIGNED_23_MASK 0x00800000
#define BCHP_PCIE_INTR2_CPU_MASK_CLEAR_UNASSIGNED_23_SHIFT 23
/* PCIE_INTR2 :: CPU_MASK_CLEAR :: UNASSIGNED_22 [22:22] */
#define BCHP_PCIE_INTR2_CPU_MASK_CLEAR_UNASSIGNED_22_MASK 0x00400000
#define BCHP_PCIE_INTR2_CPU_MASK_CLEAR_UNASSIGNED_22_SHIFT 22
/* PCIE_INTR2 :: CPU_MASK_CLEAR :: UNASSIGNED_21 [21:21] */
#define BCHP_PCIE_INTR2_CPU_MASK_CLEAR_UNASSIGNED_21_MASK 0x00200000
#define BCHP_PCIE_INTR2_CPU_MASK_CLEAR_UNASSIGNED_21_SHIFT 21
/* PCIE_INTR2 :: CPU_MASK_CLEAR :: UNASSIGNED_20 [20:20] */
#define BCHP_PCIE_INTR2_CPU_MASK_CLEAR_UNASSIGNED_20_MASK 0x00100000
#define BCHP_PCIE_INTR2_CPU_MASK_CLEAR_UNASSIGNED_20_SHIFT 20
/* PCIE_INTR2 :: CPU_MASK_CLEAR :: UNASSIGNED_19 [19:19] */
#define BCHP_PCIE_INTR2_CPU_MASK_CLEAR_UNASSIGNED_19_MASK 0x00080000
#define BCHP_PCIE_INTR2_CPU_MASK_CLEAR_UNASSIGNED_19_SHIFT 19
/* PCIE_INTR2 :: CPU_MASK_CLEAR :: UNASSIGNED_18 [18:18] */
#define BCHP_PCIE_INTR2_CPU_MASK_CLEAR_UNASSIGNED_18_MASK 0x00040000
#define BCHP_PCIE_INTR2_CPU_MASK_CLEAR_UNASSIGNED_18_SHIFT 18
/* PCIE_INTR2 :: CPU_MASK_CLEAR :: UNASSIGNED_17 [17:17] */
#define BCHP_PCIE_INTR2_CPU_MASK_CLEAR_UNASSIGNED_17_MASK 0x00020000
#define BCHP_PCIE_INTR2_CPU_MASK_CLEAR_UNASSIGNED_17_SHIFT 17
/* PCIE_INTR2 :: CPU_MASK_CLEAR :: UNASSIGNED_16 [16:16] */
#define BCHP_PCIE_INTR2_CPU_MASK_CLEAR_UNASSIGNED_16_MASK 0x00010000
#define BCHP_PCIE_INTR2_CPU_MASK_CLEAR_UNASSIGNED_16_SHIFT 16
/* PCIE_INTR2 :: CPU_MASK_CLEAR :: PCIE_MSTR_FWD_ERR [15:15] */
#define BCHP_PCIE_INTR2_CPU_MASK_CLEAR_PCIE_MSTR_FWD_ERR_MASK 0x00008000
#define BCHP_PCIE_INTR2_CPU_MASK_CLEAR_PCIE_MSTR_FWD_ERR_SHIFT 15
/* PCIE_INTR2 :: CPU_MASK_CLEAR :: PCIE_MSTR_RETRY_TIMEOUT [14:14] */
#define BCHP_PCIE_INTR2_CPU_MASK_CLEAR_PCIE_MSTR_RETRY_TIMEOUT_MASK 0x00004000
#define BCHP_PCIE_INTR2_CPU_MASK_CLEAR_PCIE_MSTR_RETRY_TIMEOUT_SHIFT 14
/* PCIE_INTR2 :: CPU_MASK_CLEAR :: PCIE_MSTR_CA_ATTN [13:13] */
#define BCHP_PCIE_INTR2_CPU_MASK_CLEAR_PCIE_MSTR_CA_ATTN_MASK 0x00002000
#define BCHP_PCIE_INTR2_CPU_MASK_CLEAR_PCIE_MSTR_CA_ATTN_SHIFT 13
/* PCIE_INTR2 :: CPU_MASK_CLEAR :: PCIE_MSTR_UR_ATTN [12:12] */
#define BCHP_PCIE_INTR2_CPU_MASK_CLEAR_PCIE_MSTR_UR_ATTN_MASK 0x00001000
#define BCHP_PCIE_INTR2_CPU_MASK_CLEAR_PCIE_MSTR_UR_ATTN_SHIFT 12
/* PCIE_INTR2 :: CPU_MASK_CLEAR :: UNASSIGNED_11 [11:11] */
#define BCHP_PCIE_INTR2_CPU_MASK_CLEAR_UNASSIGNED_11_MASK 0x00000800
#define BCHP_PCIE_INTR2_CPU_MASK_CLEAR_UNASSIGNED_11_SHIFT 11
/* PCIE_INTR2 :: CPU_MASK_CLEAR :: UNASSIGNED_10 [10:10] */
#define BCHP_PCIE_INTR2_CPU_MASK_CLEAR_UNASSIGNED_10_MASK 0x00000400
#define BCHP_PCIE_INTR2_CPU_MASK_CLEAR_UNASSIGNED_10_SHIFT 10
/* PCIE_INTR2 :: CPU_MASK_CLEAR :: PCIE_TGT_BAD_ACCESS [09:09] */
#define BCHP_PCIE_INTR2_CPU_MASK_CLEAR_PCIE_TGT_BAD_ACCESS_MASK 0x00000200
#define BCHP_PCIE_INTR2_CPU_MASK_CLEAR_PCIE_TGT_BAD_ACCESS_SHIFT 9
/* PCIE_INTR2 :: CPU_MASK_CLEAR :: PCIE_TGT_BAD_ADDRESS [08:08] */
#define BCHP_PCIE_INTR2_CPU_MASK_CLEAR_PCIE_TGT_BAD_ADDRESS_MASK 0x00000100
#define BCHP_PCIE_INTR2_CPU_MASK_CLEAR_PCIE_TGT_BAD_ADDRESS_SHIFT 8
/* PCIE_INTR2 :: CPU_MASK_CLEAR :: L1_RX_DMA_ERR_INTR [07:07] */
#define BCHP_PCIE_INTR2_CPU_MASK_CLEAR_L1_RX_DMA_ERR_INTR_MASK 0x00000080
#define BCHP_PCIE_INTR2_CPU_MASK_CLEAR_L1_RX_DMA_ERR_INTR_SHIFT 7
/* PCIE_INTR2 :: CPU_MASK_CLEAR :: L1_RX_DMA_DONE_INTR [06:06] */
#define BCHP_PCIE_INTR2_CPU_MASK_CLEAR_L1_RX_DMA_DONE_INTR_MASK 0x00000040
#define BCHP_PCIE_INTR2_CPU_MASK_CLEAR_L1_RX_DMA_DONE_INTR_SHIFT 6
/* PCIE_INTR2 :: CPU_MASK_CLEAR :: L1_TX_DMA_ERR_INTR [05:05] */
#define BCHP_PCIE_INTR2_CPU_MASK_CLEAR_L1_TX_DMA_ERR_INTR_MASK 0x00000020
#define BCHP_PCIE_INTR2_CPU_MASK_CLEAR_L1_TX_DMA_ERR_INTR_SHIFT 5
/* PCIE_INTR2 :: CPU_MASK_CLEAR :: L1_TX_DMA_DONE_INTR [04:04] */
#define BCHP_PCIE_INTR2_CPU_MASK_CLEAR_L1_TX_DMA_DONE_INTR_MASK 0x00000010
#define BCHP_PCIE_INTR2_CPU_MASK_CLEAR_L1_TX_DMA_DONE_INTR_SHIFT 4
/* PCIE_INTR2 :: CPU_MASK_CLEAR :: L0_RX_DMA_ERR_INTR [03:03] */
#define BCHP_PCIE_INTR2_CPU_MASK_CLEAR_L0_RX_DMA_ERR_INTR_MASK 0x00000008
#define BCHP_PCIE_INTR2_CPU_MASK_CLEAR_L0_RX_DMA_ERR_INTR_SHIFT 3
/* PCIE_INTR2 :: CPU_MASK_CLEAR :: L0_RX_DMA_DONE_INTR [02:02] */
#define BCHP_PCIE_INTR2_CPU_MASK_CLEAR_L0_RX_DMA_DONE_INTR_MASK 0x00000004
#define BCHP_PCIE_INTR2_CPU_MASK_CLEAR_L0_RX_DMA_DONE_INTR_SHIFT 2
/* PCIE_INTR2 :: CPU_MASK_CLEAR :: L0_TX_DMA_ERR_INTR [01:01] */
#define BCHP_PCIE_INTR2_CPU_MASK_CLEAR_L0_TX_DMA_ERR_INTR_MASK 0x00000002
#define BCHP_PCIE_INTR2_CPU_MASK_CLEAR_L0_TX_DMA_ERR_INTR_SHIFT 1
/* PCIE_INTR2 :: CPU_MASK_CLEAR :: L0_TX_DMA_DONE_INTR [00:00] */
#define BCHP_PCIE_INTR2_CPU_MASK_CLEAR_L0_TX_DMA_DONE_INTR_MASK 0x00000001
#define BCHP_PCIE_INTR2_CPU_MASK_CLEAR_L0_TX_DMA_DONE_INTR_SHIFT 0
/***************************************************************************
*PCI_STATUS - PCI interrupt Status Register
***************************************************************************/
/* PCIE_INTR2 :: PCI_STATUS :: MSI_INTR07 [31:31] */
#define BCHP_PCIE_INTR2_PCI_STATUS_MSI_INTR07_MASK 0x80000000
#define BCHP_PCIE_INTR2_PCI_STATUS_MSI_INTR07_SHIFT 31
/* PCIE_INTR2 :: PCI_STATUS :: MSI_INTR06 [30:30] */
#define BCHP_PCIE_INTR2_PCI_STATUS_MSI_INTR06_MASK 0x40000000
#define BCHP_PCIE_INTR2_PCI_STATUS_MSI_INTR06_SHIFT 30
/* PCIE_INTR2 :: PCI_STATUS :: MSI_INTR05 [29:29] */
#define BCHP_PCIE_INTR2_PCI_STATUS_MSI_INTR05_MASK 0x20000000
#define BCHP_PCIE_INTR2_PCI_STATUS_MSI_INTR05_SHIFT 29
/* PCIE_INTR2 :: PCI_STATUS :: MSI_INTR04 [28:28] */
#define BCHP_PCIE_INTR2_PCI_STATUS_MSI_INTR04_MASK 0x10000000
#define BCHP_PCIE_INTR2_PCI_STATUS_MSI_INTR04_SHIFT 28
/* PCIE_INTR2 :: PCI_STATUS :: MSI_INTR03 [27:27] */
#define BCHP_PCIE_INTR2_PCI_STATUS_MSI_INTR03_MASK 0x08000000
#define BCHP_PCIE_INTR2_PCI_STATUS_MSI_INTR03_SHIFT 27
/* PCIE_INTR2 :: PCI_STATUS :: MSI_INTR02 [26:26] */
#define BCHP_PCIE_INTR2_PCI_STATUS_MSI_INTR02_MASK 0x04000000
#define BCHP_PCIE_INTR2_PCI_STATUS_MSI_INTR02_SHIFT 26
/* PCIE_INTR2 :: PCI_STATUS :: MSI_INTR01 [25:25] */
#define BCHP_PCIE_INTR2_PCI_STATUS_MSI_INTR01_MASK 0x02000000
#define BCHP_PCIE_INTR2_PCI_STATUS_MSI_INTR01_SHIFT 25
/* PCIE_INTR2 :: PCI_STATUS :: MSI_INTR00 [24:24] */
#define BCHP_PCIE_INTR2_PCI_STATUS_MSI_INTR00_MASK 0x01000000
#define BCHP_PCIE_INTR2_PCI_STATUS_MSI_INTR00_SHIFT 24
/* PCIE_INTR2 :: PCI_STATUS :: UNASSIGNED_23 [23:23] */
#define BCHP_PCIE_INTR2_PCI_STATUS_UNASSIGNED_23_MASK 0x00800000
#define BCHP_PCIE_INTR2_PCI_STATUS_UNASSIGNED_23_SHIFT 23
/* PCIE_INTR2 :: PCI_STATUS :: UNASSIGNED_22 [22:22] */
#define BCHP_PCIE_INTR2_PCI_STATUS_UNASSIGNED_22_MASK 0x00400000
#define BCHP_PCIE_INTR2_PCI_STATUS_UNASSIGNED_22_SHIFT 22
/* PCIE_INTR2 :: PCI_STATUS :: UNASSIGNED_21 [21:21] */
#define BCHP_PCIE_INTR2_PCI_STATUS_UNASSIGNED_21_MASK 0x00200000
#define BCHP_PCIE_INTR2_PCI_STATUS_UNASSIGNED_21_SHIFT 21
/* PCIE_INTR2 :: PCI_STATUS :: UNASSIGNED_20 [20:20] */
#define BCHP_PCIE_INTR2_PCI_STATUS_UNASSIGNED_20_MASK 0x00100000
#define BCHP_PCIE_INTR2_PCI_STATUS_UNASSIGNED_20_SHIFT 20
/* PCIE_INTR2 :: PCI_STATUS :: UNASSIGNED_19 [19:19] */
#define BCHP_PCIE_INTR2_PCI_STATUS_UNASSIGNED_19_MASK 0x00080000
#define BCHP_PCIE_INTR2_PCI_STATUS_UNASSIGNED_19_SHIFT 19
/* PCIE_INTR2 :: PCI_STATUS :: UNASSIGNED_18 [18:18] */
#define BCHP_PCIE_INTR2_PCI_STATUS_UNASSIGNED_18_MASK 0x00040000
#define BCHP_PCIE_INTR2_PCI_STATUS_UNASSIGNED_18_SHIFT 18
/* PCIE_INTR2 :: PCI_STATUS :: UNASSIGNED_17 [17:17] */
#define BCHP_PCIE_INTR2_PCI_STATUS_UNASSIGNED_17_MASK 0x00020000
#define BCHP_PCIE_INTR2_PCI_STATUS_UNASSIGNED_17_SHIFT 17
/* PCIE_INTR2 :: PCI_STATUS :: UNASSIGNED_16 [16:16] */
#define BCHP_PCIE_INTR2_PCI_STATUS_UNASSIGNED_16_MASK 0x00010000
#define BCHP_PCIE_INTR2_PCI_STATUS_UNASSIGNED_16_SHIFT 16
/* PCIE_INTR2 :: PCI_STATUS :: PCIE_MSTR_FWD_ERR [15:15] */
#define BCHP_PCIE_INTR2_PCI_STATUS_PCIE_MSTR_FWD_ERR_MASK 0x00008000
#define BCHP_PCIE_INTR2_PCI_STATUS_PCIE_MSTR_FWD_ERR_SHIFT 15
/* PCIE_INTR2 :: PCI_STATUS :: PCIE_MSTR_RETRY_TIMEOUT [14:14] */
#define BCHP_PCIE_INTR2_PCI_STATUS_PCIE_MSTR_RETRY_TIMEOUT_MASK 0x00004000
#define BCHP_PCIE_INTR2_PCI_STATUS_PCIE_MSTR_RETRY_TIMEOUT_SHIFT 14
/* PCIE_INTR2 :: PCI_STATUS :: PCIE_MSTR_CA_ATTN [13:13] */
#define BCHP_PCIE_INTR2_PCI_STATUS_PCIE_MSTR_CA_ATTN_MASK 0x00002000
#define BCHP_PCIE_INTR2_PCI_STATUS_PCIE_MSTR_CA_ATTN_SHIFT 13
/* PCIE_INTR2 :: PCI_STATUS :: PCIE_MSTR_UR_ATTN [12:12] */
#define BCHP_PCIE_INTR2_PCI_STATUS_PCIE_MSTR_UR_ATTN_MASK 0x00001000
#define BCHP_PCIE_INTR2_PCI_STATUS_PCIE_MSTR_UR_ATTN_SHIFT 12
/* PCIE_INTR2 :: PCI_STATUS :: UNASSIGNED_11 [11:11] */
#define BCHP_PCIE_INTR2_PCI_STATUS_UNASSIGNED_11_MASK 0x00000800
#define BCHP_PCIE_INTR2_PCI_STATUS_UNASSIGNED_11_SHIFT 11
/* PCIE_INTR2 :: PCI_STATUS :: UNASSIGNED_10 [10:10] */
#define BCHP_PCIE_INTR2_PCI_STATUS_UNASSIGNED_10_MASK 0x00000400
#define BCHP_PCIE_INTR2_PCI_STATUS_UNASSIGNED_10_SHIFT 10
/* PCIE_INTR2 :: PCI_STATUS :: PCIE_TGT_BAD_ACCESS [09:09] */
#define BCHP_PCIE_INTR2_PCI_STATUS_PCIE_TGT_BAD_ACCESS_MASK 0x00000200
#define BCHP_PCIE_INTR2_PCI_STATUS_PCIE_TGT_BAD_ACCESS_SHIFT 9
/* PCIE_INTR2 :: PCI_STATUS :: PCIE_TGT_BAD_ADDRESS [08:08] */
#define BCHP_PCIE_INTR2_PCI_STATUS_PCIE_TGT_BAD_ADDRESS_MASK 0x00000100
#define BCHP_PCIE_INTR2_PCI_STATUS_PCIE_TGT_BAD_ADDRESS_SHIFT 8
/* PCIE_INTR2 :: PCI_STATUS :: L1_RX_DMA_ERR_INTR [07:07] */
#define BCHP_PCIE_INTR2_PCI_STATUS_L1_RX_DMA_ERR_INTR_MASK 0x00000080
#define BCHP_PCIE_INTR2_PCI_STATUS_L1_RX_DMA_ERR_INTR_SHIFT 7
/* PCIE_INTR2 :: PCI_STATUS :: L1_RX_DMA_DONE_INTR [06:06] */
#define BCHP_PCIE_INTR2_PCI_STATUS_L1_RX_DMA_DONE_INTR_MASK 0x00000040
#define BCHP_PCIE_INTR2_PCI_STATUS_L1_RX_DMA_DONE_INTR_SHIFT 6
/* PCIE_INTR2 :: PCI_STATUS :: L1_TX_DMA_ERR_INTR [05:05] */
#define BCHP_PCIE_INTR2_PCI_STATUS_L1_TX_DMA_ERR_INTR_MASK 0x00000020
#define BCHP_PCIE_INTR2_PCI_STATUS_L1_TX_DMA_ERR_INTR_SHIFT 5
/* PCIE_INTR2 :: PCI_STATUS :: L1_TX_DMA_DONE_INTR [04:04] */
#define BCHP_PCIE_INTR2_PCI_STATUS_L1_TX_DMA_DONE_INTR_MASK 0x00000010
#define BCHP_PCIE_INTR2_PCI_STATUS_L1_TX_DMA_DONE_INTR_SHIFT 4
/* PCIE_INTR2 :: PCI_STATUS :: L0_RX_DMA_ERR_INTR [03:03] */
#define BCHP_PCIE_INTR2_PCI_STATUS_L0_RX_DMA_ERR_INTR_MASK 0x00000008
#define BCHP_PCIE_INTR2_PCI_STATUS_L0_RX_DMA_ERR_INTR_SHIFT 3
/* PCIE_INTR2 :: PCI_STATUS :: L0_RX_DMA_DONE_INTR [02:02] */
#define BCHP_PCIE_INTR2_PCI_STATUS_L0_RX_DMA_DONE_INTR_MASK 0x00000004
#define BCHP_PCIE_INTR2_PCI_STATUS_L0_RX_DMA_DONE_INTR_SHIFT 2
/* PCIE_INTR2 :: PCI_STATUS :: L0_TX_DMA_ERR_INTR [01:01] */
#define BCHP_PCIE_INTR2_PCI_STATUS_L0_TX_DMA_ERR_INTR_MASK 0x00000002
#define BCHP_PCIE_INTR2_PCI_STATUS_L0_TX_DMA_ERR_INTR_SHIFT 1
/* PCIE_INTR2 :: PCI_STATUS :: L0_TX_DMA_DONE_INTR [00:00] */
#define BCHP_PCIE_INTR2_PCI_STATUS_L0_TX_DMA_DONE_INTR_MASK 0x00000001
#define BCHP_PCIE_INTR2_PCI_STATUS_L0_TX_DMA_DONE_INTR_SHIFT 0
/***************************************************************************
*PCI_SET - PCI interrupt Set Register
***************************************************************************/
/* PCIE_INTR2 :: PCI_SET :: MSI_INTR07 [31:31] */
#define BCHP_PCIE_INTR2_PCI_SET_MSI_INTR07_MASK 0x80000000
#define BCHP_PCIE_INTR2_PCI_SET_MSI_INTR07_SHIFT 31
/* PCIE_INTR2 :: PCI_SET :: MSI_INTR06 [30:30] */
#define BCHP_PCIE_INTR2_PCI_SET_MSI_INTR06_MASK 0x40000000
#define BCHP_PCIE_INTR2_PCI_SET_MSI_INTR06_SHIFT 30
/* PCIE_INTR2 :: PCI_SET :: MSI_INTR05 [29:29] */
#define BCHP_PCIE_INTR2_PCI_SET_MSI_INTR05_MASK 0x20000000
#define BCHP_PCIE_INTR2_PCI_SET_MSI_INTR05_SHIFT 29
/* PCIE_INTR2 :: PCI_SET :: MSI_INTR04 [28:28] */
#define BCHP_PCIE_INTR2_PCI_SET_MSI_INTR04_MASK 0x10000000
#define BCHP_PCIE_INTR2_PCI_SET_MSI_INTR04_SHIFT 28
/* PCIE_INTR2 :: PCI_SET :: MSI_INTR03 [27:27] */
#define BCHP_PCIE_INTR2_PCI_SET_MSI_INTR03_MASK 0x08000000
#define BCHP_PCIE_INTR2_PCI_SET_MSI_INTR03_SHIFT 27
/* PCIE_INTR2 :: PCI_SET :: MSI_INTR02 [26:26] */
#define BCHP_PCIE_INTR2_PCI_SET_MSI_INTR02_MASK 0x04000000
#define BCHP_PCIE_INTR2_PCI_SET_MSI_INTR02_SHIFT 26
/* PCIE_INTR2 :: PCI_SET :: MSI_INTR01 [25:25] */
#define BCHP_PCIE_INTR2_PCI_SET_MSI_INTR01_MASK 0x02000000
#define BCHP_PCIE_INTR2_PCI_SET_MSI_INTR01_SHIFT 25
/* PCIE_INTR2 :: PCI_SET :: MSI_INTR00 [24:24] */
#define BCHP_PCIE_INTR2_PCI_SET_MSI_INTR00_MASK 0x01000000
#define BCHP_PCIE_INTR2_PCI_SET_MSI_INTR00_SHIFT 24
/* PCIE_INTR2 :: PCI_SET :: UNASSIGNED_23 [23:23] */
#define BCHP_PCIE_INTR2_PCI_SET_UNASSIGNED_23_MASK 0x00800000
#define BCHP_PCIE_INTR2_PCI_SET_UNASSIGNED_23_SHIFT 23
/* PCIE_INTR2 :: PCI_SET :: UNASSIGNED_22 [22:22] */
#define BCHP_PCIE_INTR2_PCI_SET_UNASSIGNED_22_MASK 0x00400000
#define BCHP_PCIE_INTR2_PCI_SET_UNASSIGNED_22_SHIFT 22
/* PCIE_INTR2 :: PCI_SET :: UNASSIGNED_21 [21:21] */
#define BCHP_PCIE_INTR2_PCI_SET_UNASSIGNED_21_MASK 0x00200000
#define BCHP_PCIE_INTR2_PCI_SET_UNASSIGNED_21_SHIFT 21
/* PCIE_INTR2 :: PCI_SET :: UNASSIGNED_20 [20:20] */
#define BCHP_PCIE_INTR2_PCI_SET_UNASSIGNED_20_MASK 0x00100000
#define BCHP_PCIE_INTR2_PCI_SET_UNASSIGNED_20_SHIFT 20
/* PCIE_INTR2 :: PCI_SET :: UNASSIGNED_19 [19:19] */
#define BCHP_PCIE_INTR2_PCI_SET_UNASSIGNED_19_MASK 0x00080000
#define BCHP_PCIE_INTR2_PCI_SET_UNASSIGNED_19_SHIFT 19
/* PCIE_INTR2 :: PCI_SET :: UNASSIGNED_18 [18:18] */
#define BCHP_PCIE_INTR2_PCI_SET_UNASSIGNED_18_MASK 0x00040000
#define BCHP_PCIE_INTR2_PCI_SET_UNASSIGNED_18_SHIFT 18
/* PCIE_INTR2 :: PCI_SET :: UNASSIGNED_17 [17:17] */
#define BCHP_PCIE_INTR2_PCI_SET_UNASSIGNED_17_MASK 0x00020000
#define BCHP_PCIE_INTR2_PCI_SET_UNASSIGNED_17_SHIFT 17
/* PCIE_INTR2 :: PCI_SET :: UNASSIGNED_16 [16:16] */
#define BCHP_PCIE_INTR2_PCI_SET_UNASSIGNED_16_MASK 0x00010000
#define BCHP_PCIE_INTR2_PCI_SET_UNASSIGNED_16_SHIFT 16
/* PCIE_INTR2 :: PCI_SET :: PCIE_MSTR_FWD_ERR [15:15] */
#define BCHP_PCIE_INTR2_PCI_SET_PCIE_MSTR_FWD_ERR_MASK 0x00008000
#define BCHP_PCIE_INTR2_PCI_SET_PCIE_MSTR_FWD_ERR_SHIFT 15
/* PCIE_INTR2 :: PCI_SET :: PCIE_MSTR_RETRY_TIMEOUT [14:14] */
#define BCHP_PCIE_INTR2_PCI_SET_PCIE_MSTR_RETRY_TIMEOUT_MASK 0x00004000
#define BCHP_PCIE_INTR2_PCI_SET_PCIE_MSTR_RETRY_TIMEOUT_SHIFT 14
/* PCIE_INTR2 :: PCI_SET :: PCIE_MSTR_CA_ATTN [13:13] */
#define BCHP_PCIE_INTR2_PCI_SET_PCIE_MSTR_CA_ATTN_MASK 0x00002000
#define BCHP_PCIE_INTR2_PCI_SET_PCIE_MSTR_CA_ATTN_SHIFT 13
/* PCIE_INTR2 :: PCI_SET :: PCIE_MSTR_UR_ATTN [12:12] */
#define BCHP_PCIE_INTR2_PCI_SET_PCIE_MSTR_UR_ATTN_MASK 0x00001000
#define BCHP_PCIE_INTR2_PCI_SET_PCIE_MSTR_UR_ATTN_SHIFT 12
/* PCIE_INTR2 :: PCI_SET :: UNASSIGNED_11 [11:11] */
#define BCHP_PCIE_INTR2_PCI_SET_UNASSIGNED_11_MASK 0x00000800
#define BCHP_PCIE_INTR2_PCI_SET_UNASSIGNED_11_SHIFT 11
/* PCIE_INTR2 :: PCI_SET :: UNASSIGNED_10 [10:10] */
#define BCHP_PCIE_INTR2_PCI_SET_UNASSIGNED_10_MASK 0x00000400
#define BCHP_PCIE_INTR2_PCI_SET_UNASSIGNED_10_SHIFT 10
/* PCIE_INTR2 :: PCI_SET :: PCIE_TGT_BAD_ACCESS [09:09] */
#define BCHP_PCIE_INTR2_PCI_SET_PCIE_TGT_BAD_ACCESS_MASK 0x00000200
#define BCHP_PCIE_INTR2_PCI_SET_PCIE_TGT_BAD_ACCESS_SHIFT 9
/* PCIE_INTR2 :: PCI_SET :: PCIE_TGT_BAD_ADDRESS [08:08] */
#define BCHP_PCIE_INTR2_PCI_SET_PCIE_TGT_BAD_ADDRESS_MASK 0x00000100
#define BCHP_PCIE_INTR2_PCI_SET_PCIE_TGT_BAD_ADDRESS_SHIFT 8
/* PCIE_INTR2 :: PCI_SET :: L1_RX_DMA_ERR_INTR [07:07] */
#define BCHP_PCIE_INTR2_PCI_SET_L1_RX_DMA_ERR_INTR_MASK 0x00000080
#define BCHP_PCIE_INTR2_PCI_SET_L1_RX_DMA_ERR_INTR_SHIFT 7
/* PCIE_INTR2 :: PCI_SET :: L1_RX_DMA_DONE_INTR [06:06] */
#define BCHP_PCIE_INTR2_PCI_SET_L1_RX_DMA_DONE_INTR_MASK 0x00000040
#define BCHP_PCIE_INTR2_PCI_SET_L1_RX_DMA_DONE_INTR_SHIFT 6
/* PCIE_INTR2 :: PCI_SET :: L1_TX_DMA_ERR_INTR [05:05] */
#define BCHP_PCIE_INTR2_PCI_SET_L1_TX_DMA_ERR_INTR_MASK 0x00000020
#define BCHP_PCIE_INTR2_PCI_SET_L1_TX_DMA_ERR_INTR_SHIFT 5
/* PCIE_INTR2 :: PCI_SET :: L1_TX_DMA_DONE_INTR [04:04] */
#define BCHP_PCIE_INTR2_PCI_SET_L1_TX_DMA_DONE_INTR_MASK 0x00000010
#define BCHP_PCIE_INTR2_PCI_SET_L1_TX_DMA_DONE_INTR_SHIFT 4
/* PCIE_INTR2 :: PCI_SET :: L0_RX_DMA_ERR_INTR [03:03] */
#define BCHP_PCIE_INTR2_PCI_SET_L0_RX_DMA_ERR_INTR_MASK 0x00000008
#define BCHP_PCIE_INTR2_PCI_SET_L0_RX_DMA_ERR_INTR_SHIFT 3
/* PCIE_INTR2 :: PCI_SET :: L0_RX_DMA_DONE_INTR [02:02] */
#define BCHP_PCIE_INTR2_PCI_SET_L0_RX_DMA_DONE_INTR_MASK 0x00000004
#define BCHP_PCIE_INTR2_PCI_SET_L0_RX_DMA_DONE_INTR_SHIFT 2
/* PCIE_INTR2 :: PCI_SET :: L0_TX_DMA_ERR_INTR [01:01] */
#define BCHP_PCIE_INTR2_PCI_SET_L0_TX_DMA_ERR_INTR_MASK 0x00000002
#define BCHP_PCIE_INTR2_PCI_SET_L0_TX_DMA_ERR_INTR_SHIFT 1
/* PCIE_INTR2 :: PCI_SET :: L0_TX_DMA_DONE_INTR [00:00] */
#define BCHP_PCIE_INTR2_PCI_SET_L0_TX_DMA_DONE_INTR_MASK 0x00000001
#define BCHP_PCIE_INTR2_PCI_SET_L0_TX_DMA_DONE_INTR_SHIFT 0
/***************************************************************************
*PCI_CLEAR - PCI interrupt Clear Register
***************************************************************************/
/* PCIE_INTR2 :: PCI_CLEAR :: MSI_INTR07 [31:31] */
#define BCHP_PCIE_INTR2_PCI_CLEAR_MSI_INTR07_MASK 0x80000000
#define BCHP_PCIE_INTR2_PCI_CLEAR_MSI_INTR07_SHIFT 31
/* PCIE_INTR2 :: PCI_CLEAR :: MSI_INTR06 [30:30] */
#define BCHP_PCIE_INTR2_PCI_CLEAR_MSI_INTR06_MASK 0x40000000
#define BCHP_PCIE_INTR2_PCI_CLEAR_MSI_INTR06_SHIFT 30
/* PCIE_INTR2 :: PCI_CLEAR :: MSI_INTR05 [29:29] */
#define BCHP_PCIE_INTR2_PCI_CLEAR_MSI_INTR05_MASK 0x20000000
#define BCHP_PCIE_INTR2_PCI_CLEAR_MSI_INTR05_SHIFT 29
/* PCIE_INTR2 :: PCI_CLEAR :: MSI_INTR04 [28:28] */
#define BCHP_PCIE_INTR2_PCI_CLEAR_MSI_INTR04_MASK 0x10000000
#define BCHP_PCIE_INTR2_PCI_CLEAR_MSI_INTR04_SHIFT 28
/* PCIE_INTR2 :: PCI_CLEAR :: MSI_INTR03 [27:27] */
#define BCHP_PCIE_INTR2_PCI_CLEAR_MSI_INTR03_MASK 0x08000000
#define BCHP_PCIE_INTR2_PCI_CLEAR_MSI_INTR03_SHIFT 27
/* PCIE_INTR2 :: PCI_CLEAR :: MSI_INTR02 [26:26] */
#define BCHP_PCIE_INTR2_PCI_CLEAR_MSI_INTR02_MASK 0x04000000
#define BCHP_PCIE_INTR2_PCI_CLEAR_MSI_INTR02_SHIFT 26
/* PCIE_INTR2 :: PCI_CLEAR :: MSI_INTR01 [25:25] */
#define BCHP_PCIE_INTR2_PCI_CLEAR_MSI_INTR01_MASK 0x02000000
#define BCHP_PCIE_INTR2_PCI_CLEAR_MSI_INTR01_SHIFT 25
/* PCIE_INTR2 :: PCI_CLEAR :: MSI_INTR00 [24:24] */
#define BCHP_PCIE_INTR2_PCI_CLEAR_MSI_INTR00_MASK 0x01000000
#define BCHP_PCIE_INTR2_PCI_CLEAR_MSI_INTR00_SHIFT 24
/* PCIE_INTR2 :: PCI_CLEAR :: UNASSIGNED_23 [23:23] */
#define BCHP_PCIE_INTR2_PCI_CLEAR_UNASSIGNED_23_MASK 0x00800000
#define BCHP_PCIE_INTR2_PCI_CLEAR_UNASSIGNED_23_SHIFT 23
/* PCIE_INTR2 :: PCI_CLEAR :: UNASSIGNED_22 [22:22] */
#define BCHP_PCIE_INTR2_PCI_CLEAR_UNASSIGNED_22_MASK 0x00400000
#define BCHP_PCIE_INTR2_PCI_CLEAR_UNASSIGNED_22_SHIFT 22
/* PCIE_INTR2 :: PCI_CLEAR :: UNASSIGNED_21 [21:21] */
#define BCHP_PCIE_INTR2_PCI_CLEAR_UNASSIGNED_21_MASK 0x00200000
#define BCHP_PCIE_INTR2_PCI_CLEAR_UNASSIGNED_21_SHIFT 21
/* PCIE_INTR2 :: PCI_CLEAR :: UNASSIGNED_20 [20:20] */
#define BCHP_PCIE_INTR2_PCI_CLEAR_UNASSIGNED_20_MASK 0x00100000
#define BCHP_PCIE_INTR2_PCI_CLEAR_UNASSIGNED_20_SHIFT 20
/* PCIE_INTR2 :: PCI_CLEAR :: UNASSIGNED_19 [19:19] */
#define BCHP_PCIE_INTR2_PCI_CLEAR_UNASSIGNED_19_MASK 0x00080000
#define BCHP_PCIE_INTR2_PCI_CLEAR_UNASSIGNED_19_SHIFT 19
/* PCIE_INTR2 :: PCI_CLEAR :: UNASSIGNED_18 [18:18] */
#define BCHP_PCIE_INTR2_PCI_CLEAR_UNASSIGNED_18_MASK 0x00040000
#define BCHP_PCIE_INTR2_PCI_CLEAR_UNASSIGNED_18_SHIFT 18
/* PCIE_INTR2 :: PCI_CLEAR :: UNASSIGNED_17 [17:17] */
#define BCHP_PCIE_INTR2_PCI_CLEAR_UNASSIGNED_17_MASK 0x00020000
#define BCHP_PCIE_INTR2_PCI_CLEAR_UNASSIGNED_17_SHIFT 17
/* PCIE_INTR2 :: PCI_CLEAR :: UNASSIGNED_16 [16:16] */
#define BCHP_PCIE_INTR2_PCI_CLEAR_UNASSIGNED_16_MASK 0x00010000
#define BCHP_PCIE_INTR2_PCI_CLEAR_UNASSIGNED_16_SHIFT 16
/* PCIE_INTR2 :: PCI_CLEAR :: PCIE_MSTR_FWD_ERR [15:15] */
#define BCHP_PCIE_INTR2_PCI_CLEAR_PCIE_MSTR_FWD_ERR_MASK 0x00008000
#define BCHP_PCIE_INTR2_PCI_CLEAR_PCIE_MSTR_FWD_ERR_SHIFT 15
/* PCIE_INTR2 :: PCI_CLEAR :: PCIE_MSTR_RETRY_TIMEOUT [14:14] */
#define BCHP_PCIE_INTR2_PCI_CLEAR_PCIE_MSTR_RETRY_TIMEOUT_MASK 0x00004000
#define BCHP_PCIE_INTR2_PCI_CLEAR_PCIE_MSTR_RETRY_TIMEOUT_SHIFT 14
/* PCIE_INTR2 :: PCI_CLEAR :: PCIE_MSTR_CA_ATTN [13:13] */
#define BCHP_PCIE_INTR2_PCI_CLEAR_PCIE_MSTR_CA_ATTN_MASK 0x00002000
#define BCHP_PCIE_INTR2_PCI_CLEAR_PCIE_MSTR_CA_ATTN_SHIFT 13
/* PCIE_INTR2 :: PCI_CLEAR :: PCIE_MSTR_UR_ATTN [12:12] */
#define BCHP_PCIE_INTR2_PCI_CLEAR_PCIE_MSTR_UR_ATTN_MASK 0x00001000
#define BCHP_PCIE_INTR2_PCI_CLEAR_PCIE_MSTR_UR_ATTN_SHIFT 12
/* PCIE_INTR2 :: PCI_CLEAR :: UNASSIGNED_11 [11:11] */
#define BCHP_PCIE_INTR2_PCI_CLEAR_UNASSIGNED_11_MASK 0x00000800
#define BCHP_PCIE_INTR2_PCI_CLEAR_UNASSIGNED_11_SHIFT 11
/* PCIE_INTR2 :: PCI_CLEAR :: UNASSIGNED_10 [10:10] */
#define BCHP_PCIE_INTR2_PCI_CLEAR_UNASSIGNED_10_MASK 0x00000400
#define BCHP_PCIE_INTR2_PCI_CLEAR_UNASSIGNED_10_SHIFT 10
/* PCIE_INTR2 :: PCI_CLEAR :: PCIE_TGT_BAD_ACCESS [09:09] */
#define BCHP_PCIE_INTR2_PCI_CLEAR_PCIE_TGT_BAD_ACCESS_MASK 0x00000200
#define BCHP_PCIE_INTR2_PCI_CLEAR_PCIE_TGT_BAD_ACCESS_SHIFT 9
/* PCIE_INTR2 :: PCI_CLEAR :: PCIE_TGT_BAD_ADDRESS [08:08] */
#define BCHP_PCIE_INTR2_PCI_CLEAR_PCIE_TGT_BAD_ADDRESS_MASK 0x00000100
#define BCHP_PCIE_INTR2_PCI_CLEAR_PCIE_TGT_BAD_ADDRESS_SHIFT 8
/* PCIE_INTR2 :: PCI_CLEAR :: L1_RX_DMA_ERR_INTR [07:07] */
#define BCHP_PCIE_INTR2_PCI_CLEAR_L1_RX_DMA_ERR_INTR_MASK 0x00000080
#define BCHP_PCIE_INTR2_PCI_CLEAR_L1_RX_DMA_ERR_INTR_SHIFT 7
/* PCIE_INTR2 :: PCI_CLEAR :: L1_RX_DMA_DONE_INTR [06:06] */
#define BCHP_PCIE_INTR2_PCI_CLEAR_L1_RX_DMA_DONE_INTR_MASK 0x00000040
#define BCHP_PCIE_INTR2_PCI_CLEAR_L1_RX_DMA_DONE_INTR_SHIFT 6
/* PCIE_INTR2 :: PCI_CLEAR :: L1_TX_DMA_ERR_INTR [05:05] */
#define BCHP_PCIE_INTR2_PCI_CLEAR_L1_TX_DMA_ERR_INTR_MASK 0x00000020
#define BCHP_PCIE_INTR2_PCI_CLEAR_L1_TX_DMA_ERR_INTR_SHIFT 5
/* PCIE_INTR2 :: PCI_CLEAR :: L1_TX_DMA_DONE_INTR [04:04] */
#define BCHP_PCIE_INTR2_PCI_CLEAR_L1_TX_DMA_DONE_INTR_MASK 0x00000010
#define BCHP_PCIE_INTR2_PCI_CLEAR_L1_TX_DMA_DONE_INTR_SHIFT 4
/* PCIE_INTR2 :: PCI_CLEAR :: L0_RX_DMA_ERR_INTR [03:03] */
#define BCHP_PCIE_INTR2_PCI_CLEAR_L0_RX_DMA_ERR_INTR_MASK 0x00000008
#define BCHP_PCIE_INTR2_PCI_CLEAR_L0_RX_DMA_ERR_INTR_SHIFT 3
/* PCIE_INTR2 :: PCI_CLEAR :: L0_RX_DMA_DONE_INTR [02:02] */
#define BCHP_PCIE_INTR2_PCI_CLEAR_L0_RX_DMA_DONE_INTR_MASK 0x00000004
#define BCHP_PCIE_INTR2_PCI_CLEAR_L0_RX_DMA_DONE_INTR_SHIFT 2
/* PCIE_INTR2 :: PCI_CLEAR :: L0_TX_DMA_ERR_INTR [01:01] */
#define BCHP_PCIE_INTR2_PCI_CLEAR_L0_TX_DMA_ERR_INTR_MASK 0x00000002
#define BCHP_PCIE_INTR2_PCI_CLEAR_L0_TX_DMA_ERR_INTR_SHIFT 1
/* PCIE_INTR2 :: PCI_CLEAR :: L0_TX_DMA_DONE_INTR [00:00] */
#define BCHP_PCIE_INTR2_PCI_CLEAR_L0_TX_DMA_DONE_INTR_MASK 0x00000001
#define BCHP_PCIE_INTR2_PCI_CLEAR_L0_TX_DMA_DONE_INTR_SHIFT 0
/***************************************************************************
*PCI_MASK_STATUS - PCI interrupt Mask Status Register
***************************************************************************/
/* PCIE_INTR2 :: PCI_MASK_STATUS :: MSI_INTR07 [31:31] */
#define BCHP_PCIE_INTR2_PCI_MASK_STATUS_MSI_INTR07_MASK 0x80000000
#define BCHP_PCIE_INTR2_PCI_MASK_STATUS_MSI_INTR07_SHIFT 31
/* PCIE_INTR2 :: PCI_MASK_STATUS :: MSI_INTR06 [30:30] */
#define BCHP_PCIE_INTR2_PCI_MASK_STATUS_MSI_INTR06_MASK 0x40000000
#define BCHP_PCIE_INTR2_PCI_MASK_STATUS_MSI_INTR06_SHIFT 30
/* PCIE_INTR2 :: PCI_MASK_STATUS :: MSI_INTR05 [29:29] */
#define BCHP_PCIE_INTR2_PCI_MASK_STATUS_MSI_INTR05_MASK 0x20000000
#define BCHP_PCIE_INTR2_PCI_MASK_STATUS_MSI_INTR05_SHIFT 29
/* PCIE_INTR2 :: PCI_MASK_STATUS :: MSI_INTR04 [28:28] */
#define BCHP_PCIE_INTR2_PCI_MASK_STATUS_MSI_INTR04_MASK 0x10000000
#define BCHP_PCIE_INTR2_PCI_MASK_STATUS_MSI_INTR04_SHIFT 28
/* PCIE_INTR2 :: PCI_MASK_STATUS :: MSI_INTR03 [27:27] */
#define BCHP_PCIE_INTR2_PCI_MASK_STATUS_MSI_INTR03_MASK 0x08000000
#define BCHP_PCIE_INTR2_PCI_MASK_STATUS_MSI_INTR03_SHIFT 27
/* PCIE_INTR2 :: PCI_MASK_STATUS :: MSI_INTR02 [26:26] */
#define BCHP_PCIE_INTR2_PCI_MASK_STATUS_MSI_INTR02_MASK 0x04000000
#define BCHP_PCIE_INTR2_PCI_MASK_STATUS_MSI_INTR02_SHIFT 26
/* PCIE_INTR2 :: PCI_MASK_STATUS :: MSI_INTR01 [25:25] */
#define BCHP_PCIE_INTR2_PCI_MASK_STATUS_MSI_INTR01_MASK 0x02000000
#define BCHP_PCIE_INTR2_PCI_MASK_STATUS_MSI_INTR01_SHIFT 25
/* PCIE_INTR2 :: PCI_MASK_STATUS :: MSI_INTR00 [24:24] */
#define BCHP_PCIE_INTR2_PCI_MASK_STATUS_MSI_INTR00_MASK 0x01000000
#define BCHP_PCIE_INTR2_PCI_MASK_STATUS_MSI_INTR00_SHIFT 24
/* PCIE_INTR2 :: PCI_MASK_STATUS :: UNASSIGNED_23 [23:23] */
#define BCHP_PCIE_INTR2_PCI_MASK_STATUS_UNASSIGNED_23_MASK 0x00800000
#define BCHP_PCIE_INTR2_PCI_MASK_STATUS_UNASSIGNED_23_SHIFT 23
/* PCIE_INTR2 :: PCI_MASK_STATUS :: UNASSIGNED_22 [22:22] */
#define BCHP_PCIE_INTR2_PCI_MASK_STATUS_UNASSIGNED_22_MASK 0x00400000
#define BCHP_PCIE_INTR2_PCI_MASK_STATUS_UNASSIGNED_22_SHIFT 22
/* PCIE_INTR2 :: PCI_MASK_STATUS :: UNASSIGNED_21 [21:21] */
#define BCHP_PCIE_INTR2_PCI_MASK_STATUS_UNASSIGNED_21_MASK 0x00200000
#define BCHP_PCIE_INTR2_PCI_MASK_STATUS_UNASSIGNED_21_SHIFT 21
/* PCIE_INTR2 :: PCI_MASK_STATUS :: UNASSIGNED_20 [20:20] */
#define BCHP_PCIE_INTR2_PCI_MASK_STATUS_UNASSIGNED_20_MASK 0x00100000
#define BCHP_PCIE_INTR2_PCI_MASK_STATUS_UNASSIGNED_20_SHIFT 20
/* PCIE_INTR2 :: PCI_MASK_STATUS :: UNASSIGNED_19 [19:19] */
#define BCHP_PCIE_INTR2_PCI_MASK_STATUS_UNASSIGNED_19_MASK 0x00080000
#define BCHP_PCIE_INTR2_PCI_MASK_STATUS_UNASSIGNED_19_SHIFT 19
/* PCIE_INTR2 :: PCI_MASK_STATUS :: UNASSIGNED_18 [18:18] */
#define BCHP_PCIE_INTR2_PCI_MASK_STATUS_UNASSIGNED_18_MASK 0x00040000
#define BCHP_PCIE_INTR2_PCI_MASK_STATUS_UNASSIGNED_18_SHIFT 18
/* PCIE_INTR2 :: PCI_MASK_STATUS :: UNASSIGNED_17 [17:17] */
#define BCHP_PCIE_INTR2_PCI_MASK_STATUS_UNASSIGNED_17_MASK 0x00020000
#define BCHP_PCIE_INTR2_PCI_MASK_STATUS_UNASSIGNED_17_SHIFT 17
/* PCIE_INTR2 :: PCI_MASK_STATUS :: UNASSIGNED_16 [16:16] */
#define BCHP_PCIE_INTR2_PCI_MASK_STATUS_UNASSIGNED_16_MASK 0x00010000
#define BCHP_PCIE_INTR2_PCI_MASK_STATUS_UNASSIGNED_16_SHIFT 16
/* PCIE_INTR2 :: PCI_MASK_STATUS :: PCIE_MSTR_FWD_ERR [15:15] */
#define BCHP_PCIE_INTR2_PCI_MASK_STATUS_PCIE_MSTR_FWD_ERR_MASK 0x00008000
#define BCHP_PCIE_INTR2_PCI_MASK_STATUS_PCIE_MSTR_FWD_ERR_SHIFT 15
/* PCIE_INTR2 :: PCI_MASK_STATUS :: PCIE_MSTR_RETRY_TIMEOUT [14:14] */
#define BCHP_PCIE_INTR2_PCI_MASK_STATUS_PCIE_MSTR_RETRY_TIMEOUT_MASK 0x00004000
#define BCHP_PCIE_INTR2_PCI_MASK_STATUS_PCIE_MSTR_RETRY_TIMEOUT_SHIFT 14
/* PCIE_INTR2 :: PCI_MASK_STATUS :: PCIE_MSTR_CA_ATTN [13:13] */
#define BCHP_PCIE_INTR2_PCI_MASK_STATUS_PCIE_MSTR_CA_ATTN_MASK 0x00002000
#define BCHP_PCIE_INTR2_PCI_MASK_STATUS_PCIE_MSTR_CA_ATTN_SHIFT 13
/* PCIE_INTR2 :: PCI_MASK_STATUS :: PCIE_MSTR_UR_ATTN [12:12] */
#define BCHP_PCIE_INTR2_PCI_MASK_STATUS_PCIE_MSTR_UR_ATTN_MASK 0x00001000
#define BCHP_PCIE_INTR2_PCI_MASK_STATUS_PCIE_MSTR_UR_ATTN_SHIFT 12
/* PCIE_INTR2 :: PCI_MASK_STATUS :: UNASSIGNED_11 [11:11] */
#define BCHP_PCIE_INTR2_PCI_MASK_STATUS_UNASSIGNED_11_MASK 0x00000800
#define BCHP_PCIE_INTR2_PCI_MASK_STATUS_UNASSIGNED_11_SHIFT 11
/* PCIE_INTR2 :: PCI_MASK_STATUS :: UNASSIGNED_10 [10:10] */
#define BCHP_PCIE_INTR2_PCI_MASK_STATUS_UNASSIGNED_10_MASK 0x00000400
#define BCHP_PCIE_INTR2_PCI_MASK_STATUS_UNASSIGNED_10_SHIFT 10
/* PCIE_INTR2 :: PCI_MASK_STATUS :: PCIE_TGT_BAD_ACCESS [09:09] */
#define BCHP_PCIE_INTR2_PCI_MASK_STATUS_PCIE_TGT_BAD_ACCESS_MASK 0x00000200
#define BCHP_PCIE_INTR2_PCI_MASK_STATUS_PCIE_TGT_BAD_ACCESS_SHIFT 9
/* PCIE_INTR2 :: PCI_MASK_STATUS :: PCIE_TGT_BAD_ADDRESS [08:08] */
#define BCHP_PCIE_INTR2_PCI_MASK_STATUS_PCIE_TGT_BAD_ADDRESS_MASK 0x00000100
#define BCHP_PCIE_INTR2_PCI_MASK_STATUS_PCIE_TGT_BAD_ADDRESS_SHIFT 8
/* PCIE_INTR2 :: PCI_MASK_STATUS :: L1_RX_DMA_ERR_INTR [07:07] */
#define BCHP_PCIE_INTR2_PCI_MASK_STATUS_L1_RX_DMA_ERR_INTR_MASK 0x00000080
#define BCHP_PCIE_INTR2_PCI_MASK_STATUS_L1_RX_DMA_ERR_INTR_SHIFT 7
/* PCIE_INTR2 :: PCI_MASK_STATUS :: L1_RX_DMA_DONE_INTR [06:06] */
#define BCHP_PCIE_INTR2_PCI_MASK_STATUS_L1_RX_DMA_DONE_INTR_MASK 0x00000040
#define BCHP_PCIE_INTR2_PCI_MASK_STATUS_L1_RX_DMA_DONE_INTR_SHIFT 6
/* PCIE_INTR2 :: PCI_MASK_STATUS :: L1_TX_DMA_ERR_INTR [05:05] */
#define BCHP_PCIE_INTR2_PCI_MASK_STATUS_L1_TX_DMA_ERR_INTR_MASK 0x00000020
#define BCHP_PCIE_INTR2_PCI_MASK_STATUS_L1_TX_DMA_ERR_INTR_SHIFT 5
/* PCIE_INTR2 :: PCI_MASK_STATUS :: L1_TX_DMA_DONE_INTR [04:04] */
#define BCHP_PCIE_INTR2_PCI_MASK_STATUS_L1_TX_DMA_DONE_INTR_MASK 0x00000010
#define BCHP_PCIE_INTR2_PCI_MASK_STATUS_L1_TX_DMA_DONE_INTR_SHIFT 4
/* PCIE_INTR2 :: PCI_MASK_STATUS :: L0_RX_DMA_ERR_INTR [03:03] */
#define BCHP_PCIE_INTR2_PCI_MASK_STATUS_L0_RX_DMA_ERR_INTR_MASK 0x00000008
#define BCHP_PCIE_INTR2_PCI_MASK_STATUS_L0_RX_DMA_ERR_INTR_SHIFT 3
/* PCIE_INTR2 :: PCI_MASK_STATUS :: L0_RX_DMA_DONE_INTR [02:02] */
#define BCHP_PCIE_INTR2_PCI_MASK_STATUS_L0_RX_DMA_DONE_INTR_MASK 0x00000004
#define BCHP_PCIE_INTR2_PCI_MASK_STATUS_L0_RX_DMA_DONE_INTR_SHIFT 2
/* PCIE_INTR2 :: PCI_MASK_STATUS :: L0_TX_DMA_ERR_INTR [01:01] */
#define BCHP_PCIE_INTR2_PCI_MASK_STATUS_L0_TX_DMA_ERR_INTR_MASK 0x00000002
#define BCHP_PCIE_INTR2_PCI_MASK_STATUS_L0_TX_DMA_ERR_INTR_SHIFT 1
/* PCIE_INTR2 :: PCI_MASK_STATUS :: L0_TX_DMA_DONE_INTR [00:00] */
#define BCHP_PCIE_INTR2_PCI_MASK_STATUS_L0_TX_DMA_DONE_INTR_MASK 0x00000001
#define BCHP_PCIE_INTR2_PCI_MASK_STATUS_L0_TX_DMA_DONE_INTR_SHIFT 0
/***************************************************************************
*PCI_MASK_SET - PCI interrupt Mask Set Register
***************************************************************************/
/* PCIE_INTR2 :: PCI_MASK_SET :: MSI_INTR07 [31:31] */
#define BCHP_PCIE_INTR2_PCI_MASK_SET_MSI_INTR07_MASK 0x80000000
#define BCHP_PCIE_INTR2_PCI_MASK_SET_MSI_INTR07_SHIFT 31
/* PCIE_INTR2 :: PCI_MASK_SET :: MSI_INTR06 [30:30] */
#define BCHP_PCIE_INTR2_PCI_MASK_SET_MSI_INTR06_MASK 0x40000000
#define BCHP_PCIE_INTR2_PCI_MASK_SET_MSI_INTR06_SHIFT 30
/* PCIE_INTR2 :: PCI_MASK_SET :: MSI_INTR05 [29:29] */
#define BCHP_PCIE_INTR2_PCI_MASK_SET_MSI_INTR05_MASK 0x20000000
#define BCHP_PCIE_INTR2_PCI_MASK_SET_MSI_INTR05_SHIFT 29
/* PCIE_INTR2 :: PCI_MASK_SET :: MSI_INTR04 [28:28] */
#define BCHP_PCIE_INTR2_PCI_MASK_SET_MSI_INTR04_MASK 0x10000000
#define BCHP_PCIE_INTR2_PCI_MASK_SET_MSI_INTR04_SHIFT 28
/* PCIE_INTR2 :: PCI_MASK_SET :: MSI_INTR03 [27:27] */
#define BCHP_PCIE_INTR2_PCI_MASK_SET_MSI_INTR03_MASK 0x08000000
#define BCHP_PCIE_INTR2_PCI_MASK_SET_MSI_INTR03_SHIFT 27
/* PCIE_INTR2 :: PCI_MASK_SET :: MSI_INTR02 [26:26] */
#define BCHP_PCIE_INTR2_PCI_MASK_SET_MSI_INTR02_MASK 0x04000000
#define BCHP_PCIE_INTR2_PCI_MASK_SET_MSI_INTR02_SHIFT 26
/* PCIE_INTR2 :: PCI_MASK_SET :: MSI_INTR01 [25:25] */
#define BCHP_PCIE_INTR2_PCI_MASK_SET_MSI_INTR01_MASK 0x02000000
#define BCHP_PCIE_INTR2_PCI_MASK_SET_MSI_INTR01_SHIFT 25
/* PCIE_INTR2 :: PCI_MASK_SET :: MSI_INTR00 [24:24] */
#define BCHP_PCIE_INTR2_PCI_MASK_SET_MSI_INTR00_MASK 0x01000000
#define BCHP_PCIE_INTR2_PCI_MASK_SET_MSI_INTR00_SHIFT 24
/* PCIE_INTR2 :: PCI_MASK_SET :: UNASSIGNED_23 [23:23] */
#define BCHP_PCIE_INTR2_PCI_MASK_SET_UNASSIGNED_23_MASK 0x00800000
#define BCHP_PCIE_INTR2_PCI_MASK_SET_UNASSIGNED_23_SHIFT 23
/* PCIE_INTR2 :: PCI_MASK_SET :: UNASSIGNED_22 [22:22] */
#define BCHP_PCIE_INTR2_PCI_MASK_SET_UNASSIGNED_22_MASK 0x00400000
#define BCHP_PCIE_INTR2_PCI_MASK_SET_UNASSIGNED_22_SHIFT 22
/* PCIE_INTR2 :: PCI_MASK_SET :: UNASSIGNED_21 [21:21] */
#define BCHP_PCIE_INTR2_PCI_MASK_SET_UNASSIGNED_21_MASK 0x00200000
#define BCHP_PCIE_INTR2_PCI_MASK_SET_UNASSIGNED_21_SHIFT 21
/* PCIE_INTR2 :: PCI_MASK_SET :: UNASSIGNED_20 [20:20] */
#define BCHP_PCIE_INTR2_PCI_MASK_SET_UNASSIGNED_20_MASK 0x00100000
#define BCHP_PCIE_INTR2_PCI_MASK_SET_UNASSIGNED_20_SHIFT 20
/* PCIE_INTR2 :: PCI_MASK_SET :: UNASSIGNED_19 [19:19] */
#define BCHP_PCIE_INTR2_PCI_MASK_SET_UNASSIGNED_19_MASK 0x00080000
#define BCHP_PCIE_INTR2_PCI_MASK_SET_UNASSIGNED_19_SHIFT 19
/* PCIE_INTR2 :: PCI_MASK_SET :: UNASSIGNED_18 [18:18] */
#define BCHP_PCIE_INTR2_PCI_MASK_SET_UNASSIGNED_18_MASK 0x00040000
#define BCHP_PCIE_INTR2_PCI_MASK_SET_UNASSIGNED_18_SHIFT 18
/* PCIE_INTR2 :: PCI_MASK_SET :: UNASSIGNED_17 [17:17] */
#define BCHP_PCIE_INTR2_PCI_MASK_SET_UNASSIGNED_17_MASK 0x00020000
#define BCHP_PCIE_INTR2_PCI_MASK_SET_UNASSIGNED_17_SHIFT 17
/* PCIE_INTR2 :: PCI_MASK_SET :: UNASSIGNED_16 [16:16] */
#define BCHP_PCIE_INTR2_PCI_MASK_SET_UNASSIGNED_16_MASK 0x00010000
#define BCHP_PCIE_INTR2_PCI_MASK_SET_UNASSIGNED_16_SHIFT 16
/* PCIE_INTR2 :: PCI_MASK_SET :: PCIE_MSTR_FWD_ERR [15:15] */
#define BCHP_PCIE_INTR2_PCI_MASK_SET_PCIE_MSTR_FWD_ERR_MASK 0x00008000
#define BCHP_PCIE_INTR2_PCI_MASK_SET_PCIE_MSTR_FWD_ERR_SHIFT 15
/* PCIE_INTR2 :: PCI_MASK_SET :: PCIE_MSTR_RETRY_TIMEOUT [14:14] */
#define BCHP_PCIE_INTR2_PCI_MASK_SET_PCIE_MSTR_RETRY_TIMEOUT_MASK 0x00004000
#define BCHP_PCIE_INTR2_PCI_MASK_SET_PCIE_MSTR_RETRY_TIMEOUT_SHIFT 14
/* PCIE_INTR2 :: PCI_MASK_SET :: PCIE_MSTR_CA_ATTN [13:13] */
#define BCHP_PCIE_INTR2_PCI_MASK_SET_PCIE_MSTR_CA_ATTN_MASK 0x00002000
#define BCHP_PCIE_INTR2_PCI_MASK_SET_PCIE_MSTR_CA_ATTN_SHIFT 13
/* PCIE_INTR2 :: PCI_MASK_SET :: PCIE_MSTR_UR_ATTN [12:12] */
#define BCHP_PCIE_INTR2_PCI_MASK_SET_PCIE_MSTR_UR_ATTN_MASK 0x00001000
#define BCHP_PCIE_INTR2_PCI_MASK_SET_PCIE_MSTR_UR_ATTN_SHIFT 12
/* PCIE_INTR2 :: PCI_MASK_SET :: UNASSIGNED_11 [11:11] */
#define BCHP_PCIE_INTR2_PCI_MASK_SET_UNASSIGNED_11_MASK 0x00000800
#define BCHP_PCIE_INTR2_PCI_MASK_SET_UNASSIGNED_11_SHIFT 11
/* PCIE_INTR2 :: PCI_MASK_SET :: UNASSIGNED_10 [10:10] */
#define BCHP_PCIE_INTR2_PCI_MASK_SET_UNASSIGNED_10_MASK 0x00000400
#define BCHP_PCIE_INTR2_PCI_MASK_SET_UNASSIGNED_10_SHIFT 10
/* PCIE_INTR2 :: PCI_MASK_SET :: PCIE_TGT_BAD_ACCESS [09:09] */
#define BCHP_PCIE_INTR2_PCI_MASK_SET_PCIE_TGT_BAD_ACCESS_MASK 0x00000200
#define BCHP_PCIE_INTR2_PCI_MASK_SET_PCIE_TGT_BAD_ACCESS_SHIFT 9
/* PCIE_INTR2 :: PCI_MASK_SET :: PCIE_TGT_BAD_ADDRESS [08:08] */
#define BCHP_PCIE_INTR2_PCI_MASK_SET_PCIE_TGT_BAD_ADDRESS_MASK 0x00000100
#define BCHP_PCIE_INTR2_PCI_MASK_SET_PCIE_TGT_BAD_ADDRESS_SHIFT 8
/* PCIE_INTR2 :: PCI_MASK_SET :: L1_RX_DMA_ERR_INTR [07:07] */
#define BCHP_PCIE_INTR2_PCI_MASK_SET_L1_RX_DMA_ERR_INTR_MASK 0x00000080
#define BCHP_PCIE_INTR2_PCI_MASK_SET_L1_RX_DMA_ERR_INTR_SHIFT 7
/* PCIE_INTR2 :: PCI_MASK_SET :: L1_RX_DMA_DONE_INTR [06:06] */
#define BCHP_PCIE_INTR2_PCI_MASK_SET_L1_RX_DMA_DONE_INTR_MASK 0x00000040
#define BCHP_PCIE_INTR2_PCI_MASK_SET_L1_RX_DMA_DONE_INTR_SHIFT 6
/* PCIE_INTR2 :: PCI_MASK_SET :: L1_TX_DMA_ERR_INTR [05:05] */
#define BCHP_PCIE_INTR2_PCI_MASK_SET_L1_TX_DMA_ERR_INTR_MASK 0x00000020
#define BCHP_PCIE_INTR2_PCI_MASK_SET_L1_TX_DMA_ERR_INTR_SHIFT 5
/* PCIE_INTR2 :: PCI_MASK_SET :: L1_TX_DMA_DONE_INTR [04:04] */
#define BCHP_PCIE_INTR2_PCI_MASK_SET_L1_TX_DMA_DONE_INTR_MASK 0x00000010
#define BCHP_PCIE_INTR2_PCI_MASK_SET_L1_TX_DMA_DONE_INTR_SHIFT 4
/* PCIE_INTR2 :: PCI_MASK_SET :: L0_RX_DMA_ERR_INTR [03:03] */
#define BCHP_PCIE_INTR2_PCI_MASK_SET_L0_RX_DMA_ERR_INTR_MASK 0x00000008
#define BCHP_PCIE_INTR2_PCI_MASK_SET_L0_RX_DMA_ERR_INTR_SHIFT 3
/* PCIE_INTR2 :: PCI_MASK_SET :: L0_RX_DMA_DONE_INTR [02:02] */
#define BCHP_PCIE_INTR2_PCI_MASK_SET_L0_RX_DMA_DONE_INTR_MASK 0x00000004
#define BCHP_PCIE_INTR2_PCI_MASK_SET_L0_RX_DMA_DONE_INTR_SHIFT 2
/* PCIE_INTR2 :: PCI_MASK_SET :: L0_TX_DMA_ERR_INTR [01:01] */
#define BCHP_PCIE_INTR2_PCI_MASK_SET_L0_TX_DMA_ERR_INTR_MASK 0x00000002
#define BCHP_PCIE_INTR2_PCI_MASK_SET_L0_TX_DMA_ERR_INTR_SHIFT 1
/* PCIE_INTR2 :: PCI_MASK_SET :: L0_TX_DMA_DONE_INTR [00:00] */
#define BCHP_PCIE_INTR2_PCI_MASK_SET_L0_TX_DMA_DONE_INTR_MASK 0x00000001
#define BCHP_PCIE_INTR2_PCI_MASK_SET_L0_TX_DMA_DONE_INTR_SHIFT 0
/***************************************************************************
*PCI_MASK_CLEAR - PCI interrupt Mask Clear Register
***************************************************************************/
/* PCIE_INTR2 :: PCI_MASK_CLEAR :: MSI_INTR07 [31:31] */
#define BCHP_PCIE_INTR2_PCI_MASK_CLEAR_MSI_INTR07_MASK 0x80000000
#define BCHP_PCIE_INTR2_PCI_MASK_CLEAR_MSI_INTR07_SHIFT 31
/* PCIE_INTR2 :: PCI_MASK_CLEAR :: MSI_INTR06 [30:30] */
#define BCHP_PCIE_INTR2_PCI_MASK_CLEAR_MSI_INTR06_MASK 0x40000000
#define BCHP_PCIE_INTR2_PCI_MASK_CLEAR_MSI_INTR06_SHIFT 30
/* PCIE_INTR2 :: PCI_MASK_CLEAR :: MSI_INTR05 [29:29] */
#define BCHP_PCIE_INTR2_PCI_MASK_CLEAR_MSI_INTR05_MASK 0x20000000
#define BCHP_PCIE_INTR2_PCI_MASK_CLEAR_MSI_INTR05_SHIFT 29
/* PCIE_INTR2 :: PCI_MASK_CLEAR :: MSI_INTR04 [28:28] */
#define BCHP_PCIE_INTR2_PCI_MASK_CLEAR_MSI_INTR04_MASK 0x10000000
#define BCHP_PCIE_INTR2_PCI_MASK_CLEAR_MSI_INTR04_SHIFT 28
/* PCIE_INTR2 :: PCI_MASK_CLEAR :: MSI_INTR03 [27:27] */
#define BCHP_PCIE_INTR2_PCI_MASK_CLEAR_MSI_INTR03_MASK 0x08000000
#define BCHP_PCIE_INTR2_PCI_MASK_CLEAR_MSI_INTR03_SHIFT 27
/* PCIE_INTR2 :: PCI_MASK_CLEAR :: MSI_INTR02 [26:26] */
#define BCHP_PCIE_INTR2_PCI_MASK_CLEAR_MSI_INTR02_MASK 0x04000000
#define BCHP_PCIE_INTR2_PCI_MASK_CLEAR_MSI_INTR02_SHIFT 26
/* PCIE_INTR2 :: PCI_MASK_CLEAR :: MSI_INTR01 [25:25] */
#define BCHP_PCIE_INTR2_PCI_MASK_CLEAR_MSI_INTR01_MASK 0x02000000
#define BCHP_PCIE_INTR2_PCI_MASK_CLEAR_MSI_INTR01_SHIFT 25
/* PCIE_INTR2 :: PCI_MASK_CLEAR :: MSI_INTR00 [24:24] */
#define BCHP_PCIE_INTR2_PCI_MASK_CLEAR_MSI_INTR00_MASK 0x01000000
#define BCHP_PCIE_INTR2_PCI_MASK_CLEAR_MSI_INTR00_SHIFT 24
/* PCIE_INTR2 :: PCI_MASK_CLEAR :: UNASSIGNED_23 [23:23] */
#define BCHP_PCIE_INTR2_PCI_MASK_CLEAR_UNASSIGNED_23_MASK 0x00800000
#define BCHP_PCIE_INTR2_PCI_MASK_CLEAR_UNASSIGNED_23_SHIFT 23
/* PCIE_INTR2 :: PCI_MASK_CLEAR :: UNASSIGNED_22 [22:22] */
#define BCHP_PCIE_INTR2_PCI_MASK_CLEAR_UNASSIGNED_22_MASK 0x00400000
#define BCHP_PCIE_INTR2_PCI_MASK_CLEAR_UNASSIGNED_22_SHIFT 22
/* PCIE_INTR2 :: PCI_MASK_CLEAR :: UNASSIGNED_21 [21:21] */
#define BCHP_PCIE_INTR2_PCI_MASK_CLEAR_UNASSIGNED_21_MASK 0x00200000
#define BCHP_PCIE_INTR2_PCI_MASK_CLEAR_UNASSIGNED_21_SHIFT 21
/* PCIE_INTR2 :: PCI_MASK_CLEAR :: UNASSIGNED_20 [20:20] */
#define BCHP_PCIE_INTR2_PCI_MASK_CLEAR_UNASSIGNED_20_MASK 0x00100000
#define BCHP_PCIE_INTR2_PCI_MASK_CLEAR_UNASSIGNED_20_SHIFT 20
/* PCIE_INTR2 :: PCI_MASK_CLEAR :: UNASSIGNED_19 [19:19] */
#define BCHP_PCIE_INTR2_PCI_MASK_CLEAR_UNASSIGNED_19_MASK 0x00080000
#define BCHP_PCIE_INTR2_PCI_MASK_CLEAR_UNASSIGNED_19_SHIFT 19
/* PCIE_INTR2 :: PCI_MASK_CLEAR :: UNASSIGNED_18 [18:18] */
#define BCHP_PCIE_INTR2_PCI_MASK_CLEAR_UNASSIGNED_18_MASK 0x00040000
#define BCHP_PCIE_INTR2_PCI_MASK_CLEAR_UNASSIGNED_18_SHIFT 18
/* PCIE_INTR2 :: PCI_MASK_CLEAR :: UNASSIGNED_17 [17:17] */
#define BCHP_PCIE_INTR2_PCI_MASK_CLEAR_UNASSIGNED_17_MASK 0x00020000
#define BCHP_PCIE_INTR2_PCI_MASK_CLEAR_UNASSIGNED_17_SHIFT 17
/* PCIE_INTR2 :: PCI_MASK_CLEAR :: UNASSIGNED_16 [16:16] */
#define BCHP_PCIE_INTR2_PCI_MASK_CLEAR_UNASSIGNED_16_MASK 0x00010000
#define BCHP_PCIE_INTR2_PCI_MASK_CLEAR_UNASSIGNED_16_SHIFT 16
/* PCIE_INTR2 :: PCI_MASK_CLEAR :: PCIE_MSTR_FWD_ERR [15:15] */
#define BCHP_PCIE_INTR2_PCI_MASK_CLEAR_PCIE_MSTR_FWD_ERR_MASK 0x00008000
#define BCHP_PCIE_INTR2_PCI_MASK_CLEAR_PCIE_MSTR_FWD_ERR_SHIFT 15
/* PCIE_INTR2 :: PCI_MASK_CLEAR :: PCIE_MSTR_RETRY_TIMEOUT [14:14] */
#define BCHP_PCIE_INTR2_PCI_MASK_CLEAR_PCIE_MSTR_RETRY_TIMEOUT_MASK 0x00004000
#define BCHP_PCIE_INTR2_PCI_MASK_CLEAR_PCIE_MSTR_RETRY_TIMEOUT_SHIFT 14
/* PCIE_INTR2 :: PCI_MASK_CLEAR :: PCIE_MSTR_CA_ATTN [13:13] */
#define BCHP_PCIE_INTR2_PCI_MASK_CLEAR_PCIE_MSTR_CA_ATTN_MASK 0x00002000
#define BCHP_PCIE_INTR2_PCI_MASK_CLEAR_PCIE_MSTR_CA_ATTN_SHIFT 13
/* PCIE_INTR2 :: PCI_MASK_CLEAR :: PCIE_MSTR_UR_ATTN [12:12] */
#define BCHP_PCIE_INTR2_PCI_MASK_CLEAR_PCIE_MSTR_UR_ATTN_MASK 0x00001000
#define BCHP_PCIE_INTR2_PCI_MASK_CLEAR_PCIE_MSTR_UR_ATTN_SHIFT 12
/* PCIE_INTR2 :: PCI_MASK_CLEAR :: UNASSIGNED_11 [11:11] */
#define BCHP_PCIE_INTR2_PCI_MASK_CLEAR_UNASSIGNED_11_MASK 0x00000800
#define BCHP_PCIE_INTR2_PCI_MASK_CLEAR_UNASSIGNED_11_SHIFT 11
/* PCIE_INTR2 :: PCI_MASK_CLEAR :: UNASSIGNED_10 [10:10] */
#define BCHP_PCIE_INTR2_PCI_MASK_CLEAR_UNASSIGNED_10_MASK 0x00000400
#define BCHP_PCIE_INTR2_PCI_MASK_CLEAR_UNASSIGNED_10_SHIFT 10
/* PCIE_INTR2 :: PCI_MASK_CLEAR :: PCIE_TGT_BAD_ACCESS [09:09] */
#define BCHP_PCIE_INTR2_PCI_MASK_CLEAR_PCIE_TGT_BAD_ACCESS_MASK 0x00000200
#define BCHP_PCIE_INTR2_PCI_MASK_CLEAR_PCIE_TGT_BAD_ACCESS_SHIFT 9
/* PCIE_INTR2 :: PCI_MASK_CLEAR :: PCIE_TGT_BAD_ADDRESS [08:08] */
#define BCHP_PCIE_INTR2_PCI_MASK_CLEAR_PCIE_TGT_BAD_ADDRESS_MASK 0x00000100
#define BCHP_PCIE_INTR2_PCI_MASK_CLEAR_PCIE_TGT_BAD_ADDRESS_SHIFT 8
/* PCIE_INTR2 :: PCI_MASK_CLEAR :: L1_RX_DMA_ERR_INTR [07:07] */
#define BCHP_PCIE_INTR2_PCI_MASK_CLEAR_L1_RX_DMA_ERR_INTR_MASK 0x00000080
#define BCHP_PCIE_INTR2_PCI_MASK_CLEAR_L1_RX_DMA_ERR_INTR_SHIFT 7
/* PCIE_INTR2 :: PCI_MASK_CLEAR :: L1_RX_DMA_DONE_INTR [06:06] */
#define BCHP_PCIE_INTR2_PCI_MASK_CLEAR_L1_RX_DMA_DONE_INTR_MASK 0x00000040
#define BCHP_PCIE_INTR2_PCI_MASK_CLEAR_L1_RX_DMA_DONE_INTR_SHIFT 6
/* PCIE_INTR2 :: PCI_MASK_CLEAR :: L1_TX_DMA_ERR_INTR [05:05] */
#define BCHP_PCIE_INTR2_PCI_MASK_CLEAR_L1_TX_DMA_ERR_INTR_MASK 0x00000020
#define BCHP_PCIE_INTR2_PCI_MASK_CLEAR_L1_TX_DMA_ERR_INTR_SHIFT 5
/* PCIE_INTR2 :: PCI_MASK_CLEAR :: L1_TX_DMA_DONE_INTR [04:04] */
#define BCHP_PCIE_INTR2_PCI_MASK_CLEAR_L1_TX_DMA_DONE_INTR_MASK 0x00000010
#define BCHP_PCIE_INTR2_PCI_MASK_CLEAR_L1_TX_DMA_DONE_INTR_SHIFT 4
/* PCIE_INTR2 :: PCI_MASK_CLEAR :: L0_RX_DMA_ERR_INTR [03:03] */
#define BCHP_PCIE_INTR2_PCI_MASK_CLEAR_L0_RX_DMA_ERR_INTR_MASK 0x00000008
#define BCHP_PCIE_INTR2_PCI_MASK_CLEAR_L0_RX_DMA_ERR_INTR_SHIFT 3
/* PCIE_INTR2 :: PCI_MASK_CLEAR :: L0_RX_DMA_DONE_INTR [02:02] */
#define BCHP_PCIE_INTR2_PCI_MASK_CLEAR_L0_RX_DMA_DONE_INTR_MASK 0x00000004
#define BCHP_PCIE_INTR2_PCI_MASK_CLEAR_L0_RX_DMA_DONE_INTR_SHIFT 2
/* PCIE_INTR2 :: PCI_MASK_CLEAR :: L0_TX_DMA_ERR_INTR [01:01] */
#define BCHP_PCIE_INTR2_PCI_MASK_CLEAR_L0_TX_DMA_ERR_INTR_MASK 0x00000002
#define BCHP_PCIE_INTR2_PCI_MASK_CLEAR_L0_TX_DMA_ERR_INTR_SHIFT 1
/* PCIE_INTR2 :: PCI_MASK_CLEAR :: L0_TX_DMA_DONE_INTR [00:00] */
#define BCHP_PCIE_INTR2_PCI_MASK_CLEAR_L0_TX_DMA_DONE_INTR_MASK 0x00000001
#define BCHP_PCIE_INTR2_PCI_MASK_CLEAR_L0_TX_DMA_DONE_INTR_SHIFT 0
#endif /* #ifndef BCHP_PCIE_INTR2_H__ */
/* End of File */
| OpenDMM/linux | include/asm-mips/brcmstb/brcm97420b0/bchp_pcie_intr2.h | C | gpl-2.0 | 85,341 |
<?php
/**
* @version CVS: 1.0.0
* @package Com_Wishlist
* @author azharuddin <azharuddin.shaikh53@gmail.com>
* @copyright 2017 azharuddin
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
// No direct access
defined('_JEXEC') or die;
use Joomla\Utilities\ArrayHelper;
/**
* wishlists Table class
*
* @since 1.6
*/
class WishlistTablewishlists extends JTable
{
/**
* Constructor
*
* @param JDatabase &$db A database connector object
*/
public function __construct(&$db)
{
JObserverMapper::addObserverClassToClass('JTableObserverContenthistory', 'WishlistTablewishlists', array('typeAlias' => 'com_wishlist.wishlists'));
parent::__construct('#__wishlist', 'id', $db);
}
/**
* Overloaded bind function to pre-process the params.
*
* @param array $array Named array
* @param mixed $ignore Optional array or list of parameters to ignore
*
* @return null|string null is operation was satisfactory, otherwise returns an error
*
* @see JTable:bind
* @since 1.5
*/
public function bind($array, $ignore = '')
{
$date = JFactory::getDate();
$task = JFactory::getApplication()->input->get('task');
$input = JFactory::getApplication()->input;
$task = $input->getString('task', '');
if ($array['id'] == 0 && empty($array['created_by']))
{
$array['created_by'] = JFactory::getUser()->id;
}
if ($array['id'] == 0 && empty($array['modified_by']))
{
$array['modified_by'] = JFactory::getUser()->id;
}
if ($task == 'apply' || $task == 'save')
{
$array['modified_by'] = JFactory::getUser()->id;
}
if (isset($array['params']) && is_array($array['params']))
{
$registry = new JRegistry;
$registry->loadArray($array['params']);
$array['params'] = (string) $registry;
}
if (isset($array['metadata']) && is_array($array['metadata']))
{
$registry = new JRegistry;
$registry->loadArray($array['metadata']);
$array['metadata'] = (string) $registry;
}
if (!JFactory::getUser()->authorise('core.admin', 'com_wishlist.wishlists.' . $array['id']))
{
$actions = JAccess::getActionsFromFile(
JPATH_ADMINISTRATOR . '/components/com_wishlist/access.xml',
"/access/section[@name='wishlists']/"
);
$default_actions = JAccess::getAssetRules('com_wishlist.wishlists.' . $array['id'])->getData();
$array_jaccess = array();
foreach ($actions as $action)
{
if (key_exists($action->name, $default_actions))
{
$array_jaccess[$action->name] = $default_actions[$action->name];
}
}
$array['rules'] = $this->JAccessRulestoArray($array_jaccess);
}
// Bind the rules for ACL where supported.
if (isset($array['rules']) && is_array($array['rules']))
{
$this->setRules($array['rules']);
}
return parent::bind($array, $ignore);
}
/**
* This function convert an array of JAccessRule objects into an rules array.
*
* @param array $jaccessrules An array of JAccessRule objects.
*
* @return array
*/
private function JAccessRulestoArray($jaccessrules)
{
$rules = array();
foreach ($jaccessrules as $action => $jaccess)
{
$actions = array();
if ($jaccess)
{
foreach ($jaccess->getData() as $group => $allow)
{
$actions[$group] = ((bool)$allow);
}
}
$rules[$action] = $actions;
}
return $rules;
}
/**
* Overloaded check function
*
* @return bool
*/
public function check()
{
// If there is an ordering column and this is a new row then get the next ordering value
if (property_exists($this, 'ordering') && $this->id == 0)
{
$this->ordering = self::getNextOrder();
}
return parent::check();
}
/**
* Method to set the publishing state for a row or list of rows in the database
* table. The method respects checked out rows by other users and will attempt
* to checkin rows that it can after adjustments are made.
*
* @param mixed $pks An optional array of primary key values to update. If not
* set the instance property value is used.
* @param integer $state The publishing state. eg. [0 = unpublished, 1 = published]
* @param integer $userId The user id of the user performing the operation.
*
* @return boolean True on success.
*
* @since 1.0.4
*
* @throws Exception
*/
public function publish($pks = null, $state = 1, $userId = 0)
{
// Initialise variables.
$k = $this->_tbl_key;
// Sanitize input.
ArrayHelper::toInteger($pks);
$userId = (int) $userId;
$state = (int) $state;
// If there are no primary keys set check to see if the instance key is set.
if (empty($pks))
{
if ($this->$k)
{
$pks = array($this->$k);
}
// Nothing to set publishing state on, return false.
else
{
throw new Exception(500, JText::_('JLIB_DATABASE_ERROR_NO_ROWS_SELECTED'));
}
}
// Build the WHERE clause for the primary keys.
$where = $k . '=' . implode(' OR ' . $k . '=', $pks);
// Determine if there is checkin support for the table.
if (!property_exists($this, 'checked_out') || !property_exists($this, 'checked_out_time'))
{
$checkin = '';
}
else
{
$checkin = ' AND (checked_out = 0 OR checked_out = ' . (int) $userId . ')';
}
// Update the publishing state for rows with the given primary keys.
$this->_db->setQuery(
'UPDATE `' . $this->_tbl . '`' .
' SET `state` = ' . (int) $state .
' WHERE (' . $where . ')' .
$checkin
);
$this->_db->execute();
// If checkin is supported and all rows were adjusted, check them in.
if ($checkin && (count($pks) == $this->_db->getAffectedRows()))
{
// Checkin each row.
foreach ($pks as $pk)
{
$this->checkin($pk);
}
}
// If the JTable instance value is in the list of primary keys that were set, set the instance.
if (in_array($this->$k, $pks))
{
$this->state = $state;
}
return true;
}
/**
* Define a namespaced asset name for inclusion in the #__assets table
*
* @return string The asset name
*
* @see JTable::_getAssetName
*/
protected function _getAssetName()
{
$k = $this->_tbl_key;
return 'com_wishlist.wishlists.' . (int) $this->$k;
}
/**
* Returns the parent asset's id. If you have a tree structure, retrieve the parent's id using the external key field
*
* @param JTable $table Table name
* @param integer $id Id
*
* @see JTable::_getAssetParentId
*
* @return mixed The id on success, false on failure.
*/
protected function _getAssetParentId(JTable $table = null, $id = null)
{
// We will retrieve the parent-asset from the Asset-table
$assetParent = JTable::getInstance('Asset');
// Default: if no asset-parent can be found we take the global asset
$assetParentId = $assetParent->getRootId();
// The item has the component as asset-parent
$assetParent->loadByName('com_wishlist');
// Return the found asset-parent-id
if ($assetParent->id)
{
$assetParentId = $assetParent->id;
}
return $assetParentId;
}
/**
* Delete a record by id
*
* @param mixed $pk Primary key value to delete. Optional
*
* @return bool
*/
public function delete($pk = null)
{
$this->load($pk);
$result = parent::delete($pk);
return $result;
}
}
| azharu53/kuwithome | administrator/components/com_wishlist/tables/wishlists.php | PHP | gpl-2.0 | 7,365 |
/*
* Seven Kingdoms: Ancient Adversaries
*
* Copyright 1997,1998 Enlight Software Ltd.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* 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/>.
*
*/
//Filename : OGAMHALL.CPP
//Description : Hall of Fame
#include <OGAMHALL.h>
#include <OVGA.h>
#include <vga_util.h>
#include <OVGALOCK.h>
#include <ODATE.h>
#include <OSTR.h>
#include <OSYS.h>
#include <OFONT.h>
#include <OMOUSE.h>
#include <OIMGRES.h>
#include <ORACERES.h>
#include <OGAME.h>
#include <ONATION.h>
#include <dbglog.h>
#include "gettext.h"
#include <string.h> // for strncpy
#define HALL_OF_FAME_FILE_NAME "HALLFAME.DAT"
DBGLOG_DEFAULT_CHANNEL(HallOfFame);
HallOfFame::HallOfFame()
: hall_fame_array{},
last_savegame_file_name{}
{
}
void HallOfFame::init()
{
read_hall_of_fame();
}
void HallOfFame::deinit()
{
write_hall_of_fame();
}
void HallOfFame::set_last_savegame_file_name(const char* fileName) {
strncpy(last_savegame_file_name, fileName, MAX_PATH);
last_savegame_file_name[MAX_PATH] = '\0';
}
//------- Begin of function HallOfFame::read_hall_of_fame ------//
//
int HallOfFame::read_hall_of_fame()
{
char full_path[MAX_PATH+1];
int rc;
File file;
if (!misc.path_cat(full_path, sys.dir_config, HALL_OF_FAME_FILE_NAME, MAX_PATH))
{
ERR("Path to the hall of fame too long.\n");
return 0;
}
if( !misc.is_file_exist(full_path) )
return 0;
rc = file.file_open(full_path, 0, 1); // 0=don't handle error itself
// 1=allow the writing size and the read size to be different
if( !rc )
return 0;
// 1=allow the writing size and the read size to be different
//--------- Read Hall of Fame ----------//
if( rc )
rc = file.file_read( hall_fame_array, sizeof(HallFameEntry) * HALL_FAME_NUM );
//------ read last saved game file name ------//
if( rc )
rc = file.file_read( last_savegame_file_name, MAX_PATH+1 );
file.file_close();
return rc;
}
//--------- End of function HallOfFame::read_hall_of_fame ------//
//------- Begin of function HallOfFame::write_hall_of_fame ------//
//
int HallOfFame::write_hall_of_fame()
{
char full_path[MAX_PATH+1];
int rc;
File file;
if (!misc.path_cat(full_path, sys.dir_config, HALL_OF_FAME_FILE_NAME, MAX_PATH))
{
ERR("Path to the hall of fame too long.\n");
return 0;
}
rc = file.file_create( full_path, 0, 1 ); // 0=don't handle error itself
if( !rc )
return 0;
// 1=allow the writing size and the read size to be different
//--------- Write Hall of Fame ----------//
if( rc )
rc = file.file_write( hall_fame_array, sizeof(HallFameEntry) * HALL_FAME_NUM );
//------ write last saved game file name ------//
if( rc )
rc = file.file_write( last_savegame_file_name, MAX_PATH+1 );
file.file_close();
return rc;
}
//--------- End of function HallOfFame::write_hall_of_fame ------//
//------ Begin of function HallOfFame::disp_hall_of_fame -----//
//
// Display the Hall of Fame
//
void HallOfFame::disp_hall_of_fame()
{
vga_util.disp_image_file("HALLFAME");
//---------- display hall of fame records ------------//
int i;
int x=120, y=116;
for( i=0 ; i<HALL_FAME_NUM ; i++, y+=76 )
{
hall_fame_array[i].disp_info( x, y, i+1 );
}
mouse.wait_press(60); // 60 seconds to time out
vga_util.finish_disp_image_file();
}
//------- End of function HallOfFame::disp_hall_of_fame -----//
//------ Begin of function HallOfFame::add_hall_of_fame -----//
//
// Add current game into the hall of hame
//
// <int> totalScore of the player.
//
// return : <int> 1-hall of fame updated
// 0-not updated
//
int HallOfFame::add_hall_of_fame(int totalScore)
{
//-------- insert the record -----------//
int i;
for( i=0 ; i<HALL_FAME_NUM ; i++ )
{
if( totalScore > hall_fame_array[i].score )
{
//---------- move and insert the data --------//
if( i < HALL_FAME_NUM-1 ) // it is not the last record
{
memmove( hall_fame_array+i+1, hall_fame_array+i,
sizeof(HallFameEntry) * (HALL_FAME_NUM-i-1) );
}
//-------- record the hall of fame rcord ------//
hall_fame_array[i].record_data(totalScore);
//--------- display the hall of fame ----------//
write_hall_of_fame();
disp_hall_of_fame();
return 1;
}
}
return 0;
}
//------- End of function HallOfFame::add_hall_of_fame -----//
//------ Begin of function HallFameEntry::disp_info -------//
//
// Display a Hall of Fame record
//
// <int> x, y = the location of the information
// <int> pos = the position of the record.
//
void HallFameEntry::disp_info(int x, int y, int pos)
{
if( !start_year ) // no information
return;
//------------------------------------------------------//
//
// e.g. 1. [Image] King Trevor Chan
// [ ] Score : 150 Population : 1000 Period : 1001-1030
//
//------------------------------------------------------//
Font* fontPtr;
#if( defined(GERMAN) || defined(FRENCH) || defined(SPANISH) )
fontPtr = &font_hall;
#else
fontPtr = &font_std;
#endif
String str;
int y2 = y+17;
//----------------------------------------//
str = pos;
str += ".";
fontPtr->put( x, y, str );
x += 16;
//----------------------------------------//
str = _("King");
str += " ";
str += player_name;
fontPtr->put( x, y, str );
//----------------------------------------//
str = _("Score : ");
str += score;
fontPtr->put( x, y2, str );
//----------------------------------------//
str = _("Population");
str += " : ";
str += population;
fontPtr->put( x+110, y2, str );
//----------------------------------------//
#if( defined(GERMAN) || defined(FRENCH) || defined(SPANISH) )
x-=10; // position adjustment for the German version
#endif
str = _("Period : ");
str += misc.num_to_str(start_year); // without adding comma separators
str += "-";
str += misc.num_to_str(end_year);
fontPtr->put( x+260, y2, str );
//----------------------------------------//
str = _("Difficulty : ");
str += difficulty_rating;
fontPtr->put( x+420, y2, str );
}
//------- End of function HallFameEntry::disp_info -------//
//--------- Begin of function HallFameEntry::record_data --------//
//
// Record the hall of fame record_data
//
void HallFameEntry::record_data(int totalScore)
{
Nation* playerNation = ~nation_array;
strncpy( player_name, playerNation->king_name(), HUMAN_NAME_LEN );
player_name[HUMAN_NAME_LEN] = '\0';
race_id = playerNation->race_id;
start_year = date.year(info.game_start_date);
end_year = info.game_year;
score = totalScore;
population = playerNation->all_population();
difficulty_rating = config.difficulty_rating;
}
//----------- End of function HallFameEntry::record_data ---------//
| StefanCristian/7kaa | src/OGAMHALL.cpp | C++ | gpl-2.0 | 7,253 |
/*
* Linux cfg80211 driver - Android related functions
*
* Copyright (C) 1999-2012, Broadcom Corporation
*
* Unless you and Broadcom execute a separate written software license
* agreement governing use of this software, this software is licensed to you
* under the terms of the GNU General Public License version 2 (the "GPL"),
* available at http://www.broadcom.com/licenses/GPLv2.php, with the
* following added to such license:
*
* As a special exception, the copyright holders of this software give you
* permission to link this software with 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 this software. The special exception does not apply to any
* modifications of the software.
*
* Notwithstanding the above, under no circumstances may you combine this
* software in any way with any other Broadcom software provided under a license
* other than the GPL, without Broadcom's express prior written consent.
*
* $Id: wl_android.h 363350 2012-10-17 08:29:23Z $
*/
#include <linux/module.h>
#include <linux/netdevice.h>
#include <wldev_common.h>
/* If any feature uses the Generic Netlink Interface, put it here to enable WL_GENL
* automatically
*/
#ifdef WL_GENL
#include <net/genetlink.h>
#endif
/**
* Android platform dependent functions, feel free to add Android specific functions here
* (save the macros in dhd). Please do NOT declare functions that are NOT exposed to dhd
* or cfg, define them as static in wl_android.c
*/
/**
* wl_android_init will be called from module init function (dhd_module_init now), similarly
* wl_android_exit will be called from module exit function (dhd_module_cleanup now)
*/
int wl_android_init(void);
int wl_android_exit(void);
void wl_android_post_init(void);
int wl_android_wifi_on(struct net_device *dev);
int wl_android_wifi_off(struct net_device *dev);
int wl_android_priv_cmd(struct net_device *net, struct ifreq *ifr, int cmd);
#if defined(CONFIG_WIFI_CONTROL_FUNC)
int wl_android_wifictrl_func_add(void);
void wl_android_wifictrl_func_del(void);
void* wl_android_prealloc(int section, unsigned long size);
int wifi_get_irq_number(unsigned long *irq_flags_ptr);
int wifi_set_power(int on, unsigned long msec);
int wifi_get_mac_addr(unsigned char *buf);
void *wifi_get_country_code(char *ccode);
#endif /* CONFIG_WIFI_CONTROL_FUNC */
#ifdef WL_GENL
/* attributes (variables): the index in this enum is used as a reference for the type,
* userspace application has to indicate the corresponding type
* the policy is used for security considerations
*/
enum {
BCM_GENL_ATTR_UNSPEC,
BCM_GENL_ATTR_STRING,
BCM_GENL_ATTR_MSG,
__BCM_GENL_ATTR_MAX
};
#define BCM_GENL_ATTR_MAX (__BCM_GENL_ATTR_MAX - 1)
/* commands: enumeration of all commands (functions),
* used by userspace application to identify command to be ececuted
*/
enum {
BCM_GENL_CMD_UNSPEC,
BCM_GENL_CMD_MSG,
__BCM_GENL_CMD_MAX
};
#define BCM_GENL_CMD_MAX (__BCM_GENL_CMD_MAX - 1)
s32 wl_genl_send_msg(struct net_device *ndev, int pid, u8 *string, u8 len, int mcast);
#endif /* WL_GENL */ | lexmar93/Siyah-i777 | drivers/net/wireless/bcmdhd/wl_android.h | C | gpl-2.0 | 3,336 |
/*******************************************************************************
* Software Name : RCS IMS Stack
*
* Copyright (C) 2010 France Telecom S.A.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.orangelabs.rcs.core.ims.protocol.rtp.stream;
import com.orangelabs.rcs.core.ims.protocol.rtp.format.DummyFormat;
import com.orangelabs.rcs.core.ims.protocol.rtp.format.Format;
import com.orangelabs.rcs.core.ims.protocol.rtp.util.Buffer;
import com.orangelabs.rcs.core.ims.protocol.rtp.util.SystemTimeBase;
import com.orangelabs.rcs.utils.FifoBuffer;
import com.orangelabs.rcs.utils.logger.Logger;
/**
* Dummy packet source stream (used to pass NAT)
*
* @author jexa7410
*/
public class DummyPacketSourceStream extends Thread implements ProcessorInputStream {
/**
* Source period (in seconds)
*/
public final static int DUMMY_SOURCE_PERIOD = 5;
/**
* Input format
*/
private DummyFormat format = new DummyFormat();
/**
* Time base
*/
private SystemTimeBase systemTimeBase = new SystemTimeBase();
/**
* Sequence number
*/
private long seqNo = 0;
/**
* Message buffer
*/
private FifoBuffer fifo = new FifoBuffer();
/**
* The logger
*/
private Logger logger = Logger.getLogger(this.getClass().getName());
/**
* Interruption flag
*/
private boolean interrupted = false;
/**
* Constructor
*/
public DummyPacketSourceStream() {
}
/**
* Open the input stream
*/
public void open() {
start();
if (logger.isActivated()) {
logger.debug("Dummy source stream openned");
}
}
/**
* Close the input stream
*/
public void close() {
interrupted = true;
try {
fifo.close();
} catch(Exception e) {
// Intentionally blank
}
if (logger.isActivated()) {
logger.debug("Dummy source stream closed");
}
}
/**
* Format of the data provided by the source stream
*
* @return Format
*/
public Format getFormat() {
return format;
}
/**
* Background processing
*/
public void run() {
while(!interrupted) {
try {
// Build a new dummy packet
Buffer packet = new Buffer();
packet.setData(new byte[0]);
packet.setLength(0);
packet.setFormat(format);
packet.setSequenceNumber(seqNo++);
packet.setTimeStamp(systemTimeBase.getTime());
// Post the packet in the FIFO
fifo.addObject(packet);
// Make a pause
Thread.sleep(DUMMY_SOURCE_PERIOD * 1000);
} catch(Exception e) {
if (logger.isActivated()) {
logger.error("Dummy packet source has failed", e);
}
}
}
}
/**
* Read from the stream
*
* @return Buffer
* @throws Exception
*/
public Buffer read() throws Exception {
// Read the FIFO the buffer
Buffer buffer = (Buffer)fifo.getObject();
return buffer;
}
}
| rex-xxx/mt6572_x201 | mediatek/packages/apps/RCSe/core/src/com/orangelabs/rcs/core/ims/protocol/rtp/stream/DummyPacketSourceStream.java | Java | gpl-2.0 | 3,684 |
#ifndef __GPIO_H__
#define __GPIO_H__
#define GPIO0
#define GPIO1
#define GPIO2
#define GPIO3
#define GPIO4
#define GPIO5
#define GPIO6
#define GPIO7
#endif /* __GPIO_H__ */
| sagarkadamati/bm-bone | include/gpio.h | C | gpl-2.0 | 177 |
#ifndef _OBJ_OPS_H_
#define _OBJ_OPS_H_
#include <stdint.h>
#include "internal.h"
struct nlattr;
struct nlmsghdr;
struct nftnl_obj;
struct nftnl_obj {
struct list_head head;
struct obj_ops *ops;
const char *table;
const char *name;
uint32_t family;
uint32_t use;
uint32_t flags;
union {
struct nftnl_obj_counter {
uint64_t pkts;
uint64_t bytes;
} counter;
struct nftnl_obj_quota {
uint64_t bytes;
uint64_t consumed;
uint32_t flags;
} quota;
struct nftnl_obj_ct_helper {
uint16_t l3proto;
uint8_t l4proto;
char name[16];
} ct_helper;
} data;
};
struct obj_ops {
const char *name;
uint32_t type;
size_t alloc_len;
int max_attr;
int (*set)(struct nftnl_obj *e, uint16_t type, const void *data, uint32_t data_len);
const void *(*get)(const struct nftnl_obj *e, uint16_t type, uint32_t *data_len);
int (*parse)(struct nftnl_obj *e, struct nlattr *attr);
void (*build)(struct nlmsghdr *nlh, const struct nftnl_obj *e);
int (*snprintf)(char *buf, size_t len, uint32_t type, uint32_t flags, const struct nftnl_obj *e);
int (*json_parse)(struct nftnl_obj *e, json_t *data,
struct nftnl_parse_err *err);
};
extern struct obj_ops obj_ops_counter;
extern struct obj_ops obj_ops_quota;
extern struct obj_ops obj_ops_ct_helper;
#define nftnl_obj_data(obj) (void *)&obj->data
#endif
| tamimcse/libnftnl | include/obj.h | C | gpl-2.0 | 1,365 |
jQuery(function(a){window.WPXBannerizePreferences=(function(){var c={version:"1.0.1",init:b,spin:WPDKGlyphIcons.html(WPDKGlyphIcons.SPIN3)+" "};function b(){a("#wpxbz_preset_orientation").on("changed",function(g,d,f){a(".wpxbz-preset-preview").toggleClass("wpxbz-preset-vertical",(f=="on"))});a("#wpxbz_css_style").on("keyup",function(){var d=a(this).val();a("style#wpxbz-preset-styles").html(d)});a('button[name^="button_delete_all"]').on("click",function(){var d=a(this);if(confirm(a(this).data("confirm"))){d.attr("disabled","disabled");d.prepend(c.spin);a.post(wpdk_i18n.ajaxURL,{action:a(this).data("action"),table:a(this).data("table")},function(f){var e=new WPDKAjaxResponse(f);if(empty(e.error)){d.remove()}else{alert(e.error);d.removeAttr("disabled")}})}return false});return c}return b()})()}); | vdeluca/hablante | wp-content/plugins/wpx-bannerize_000036/assets/js/wpxbz-preferences.js | JavaScript | gpl-2.0 | 804 |
table.paleblue {
border-collapse: collapse;
border-color: #CCC;
border: 1px solid #DDD;
}
table.paleblue,
table.paleblue + ul.pagination {
font: normal 11px/14px 'Lucida Grande', Verdana, Helvetica, Arial, sans-serif;
}
table.paleblue a:link,
table.paleblue a:visited,
table.paleblue + ul.pagination > li > a {
color: #5B80B2;
text-decoration: none;
font-weight: bold;
}
table.paleblue a:hover {
color: #036;
}
table.paleblue td,
table.paleblue th {
padding: 5px;
line-height: 13px;
border-bottom: 1px solid #EEE;
border-left: 1px solid #DDD;
text-align: left;
}
table.paleblue thead th:first-child,
table.paleblue thead td:first-child {
border-left: none !important;
}
table.paleblue thead th,
table.paleblue thead td {
background: #FCFCFC url(../img/header-bg.png) left bottom repeat-x;
border-bottom: 1px solid #DDD;
padding: 2px 5px;
font-size: 11px;
vertical-align: middle;
color: #666;
}
table.paleblue thead th > a:link,
table.paleblue thead th > a:visited {
color: #666;
}
table.paleblue thead th.orderable > a {
padding-right: 20px;
background: url(../img/arrow-inactive-up.png) right center no-repeat;
}
table.paleblue thead th.orderable.asc > a {
background-image: url(../img/arrow-active-up.png);
}
table.paleblue thead th.orderable.desc > a {
background-image: url(../img/arrow-active-down.png);
}
table.paleblue tr.odd {
background-color: #EDF3FE;
}
table.paleblue tr.even {
background-color: white;
}
table.paleblue + ul.pagination {
background: white url(../img/pagination-bg.gif) left 180% repeat-x;
overflow: auto;
margin: 0;
padding: 10px;
border: 1px solid #DDD;
list-style: none;
}
table.paleblue + ul.pagination > li {
float: left;
line-height: 22px;
margin-left: 10px;
}
table.paleblue + ul.pagination > li:first-child {
margin-left: 0;
}
table.paleblue + ul.pagination > li.cardinality {
float: right;
}
table.paleblue > tbody > tr > td > span.true,
table.paleblue > tbody > tr > td > span.false {
background-position: top left;
background-repeat: no-repeat;
display: inline-block;
height: 10px;
overflow: hidden;
text-indent: -200px;
width: 10px;
}
table.paleblue > tbody > tr > td > span.true {
background-image: url(../img/true.gif);
}
table.paleblue > tbody > tr > td > span.false {
background-image: url(../img/false.gif);
}
div.table-container {
display: inline-block;
}
| flibbertigibbet/cbecs-viewer | django_tables2/themes/paleblue/css/screen.css | CSS | gpl-2.0 | 2,512 |
/*
*
* Connection Manager
*
* Copyright (C) 2007-2014 Intel Corporation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* 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
*
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <netdb.h>
#include <gdbus.h>
#include <ctype.h>
#include <stdint.h>
#include <connman/storage.h>
#include <connman/setting.h>
#include <connman/agent.h>
#include "connman.h"
#define CONNECT_TIMEOUT 120
static DBusConnection *connection = NULL;
static GList *service_list = NULL;
static GHashTable *service_hash = NULL;
static GSList *counter_list = NULL;
static unsigned int autoconnect_id = 0;
static unsigned int vpn_autoconnect_id = 0;
static struct connman_service *current_default = NULL;
static bool services_dirty = false;
struct connman_stats {
bool valid;
bool enabled;
struct connman_stats_data data_last;
struct connman_stats_data data;
GTimer *timer;
};
struct connman_stats_counter {
bool append_all;
struct connman_stats stats;
struct connman_stats stats_roaming;
};
struct connman_service {
int refcount;
char *identifier;
char *path;
enum connman_service_type type;
enum connman_service_security security;
enum connman_service_state state;
enum connman_service_state state_ipv4;
enum connman_service_state state_ipv6;
enum connman_service_error error;
enum connman_service_connect_reason connect_reason;
uint8_t strength;
bool favorite;
bool immutable;
bool hidden;
bool ignore;
bool autoconnect;
GTimeVal modified;
unsigned int order;
char *name;
char *passphrase;
bool roaming;
struct connman_ipconfig *ipconfig_ipv4;
struct connman_ipconfig *ipconfig_ipv6;
struct connman_network *network;
struct connman_provider *provider;
char **nameservers;
char **nameservers_config;
char **nameservers_auto;
int nameservers_timeout;
char **domains;
bool mdns;
bool mdns_config;
char *hostname;
char *domainname;
char **timeservers;
char **timeservers_config;
/* 802.1x settings from the config files */
char *eap;
char *identity;
char *anonymous_identity;
char *agent_identity;
char *ca_cert_file;
char *subject_match;
char *altsubject_match;
char *domain_suffix_match;
char *domain_match;
char *client_cert_file;
char *private_key_file;
char *private_key_passphrase;
char *phase2;
DBusMessage *pending;
DBusMessage *provider_pending;
guint timeout;
struct connman_stats stats;
struct connman_stats stats_roaming;
GHashTable *counter_table;
enum connman_service_proxy_method proxy;
enum connman_service_proxy_method proxy_config;
char **proxies;
char **excludes;
char *pac;
bool wps;
bool wps_advertizing;
int online_check_count_ipv4;
int online_check_count_ipv6;
bool do_split_routing;
bool new_service;
bool hidden_service;
char *config_file;
char *config_entry;
};
static bool allow_property_changed(struct connman_service *service);
static struct connman_ipconfig *create_ip4config(struct connman_service *service,
int index, int original_index, enum connman_ipconfig_method method);
static struct connman_ipconfig *create_ip6config(struct connman_service *service,
int index, int original_index);
static void dns_changed(struct connman_service *service);
struct find_data {
const char *path;
struct connman_service *service;
};
static void compare_path(gpointer value, gpointer user_data)
{
struct connman_service *service = value;
struct find_data *data = user_data;
if (data->service)
return;
if (g_strcmp0(service->path, data->path) == 0)
data->service = service;
}
static struct connman_service *find_service(const char *path)
{
struct find_data data = { .path = path, .service = NULL };
DBG("path %s", path);
g_list_foreach(service_list, compare_path, &data);
return data.service;
}
static const char *reason2string(enum connman_service_connect_reason reason)
{
switch (reason) {
case CONNMAN_SERVICE_CONNECT_REASON_NONE:
return "none";
case CONNMAN_SERVICE_CONNECT_REASON_USER:
return "user";
case CONNMAN_SERVICE_CONNECT_REASON_AUTO:
return "auto";
case CONNMAN_SERVICE_CONNECT_REASON_SESSION:
return "session";
}
return "unknown";
}
const char *__connman_service_type2string(enum connman_service_type type)
{
switch (type) {
case CONNMAN_SERVICE_TYPE_UNKNOWN:
break;
case CONNMAN_SERVICE_TYPE_SYSTEM:
return "system";
case CONNMAN_SERVICE_TYPE_ETHERNET:
return "ethernet";
case CONNMAN_SERVICE_TYPE_WIFI:
return "wifi";
case CONNMAN_SERVICE_TYPE_BLUETOOTH:
return "bluetooth";
case CONNMAN_SERVICE_TYPE_CELLULAR:
return "cellular";
case CONNMAN_SERVICE_TYPE_GPS:
return "gps";
case CONNMAN_SERVICE_TYPE_VPN:
return "vpn";
case CONNMAN_SERVICE_TYPE_GADGET:
return "gadget";
case CONNMAN_SERVICE_TYPE_P2P:
return "p2p";
}
return NULL;
}
enum connman_service_type __connman_service_string2type(const char *str)
{
if (!str)
return CONNMAN_SERVICE_TYPE_UNKNOWN;
if (strcmp(str, "ethernet") == 0)
return CONNMAN_SERVICE_TYPE_ETHERNET;
if (strcmp(str, "gadget") == 0)
return CONNMAN_SERVICE_TYPE_GADGET;
if (strcmp(str, "wifi") == 0)
return CONNMAN_SERVICE_TYPE_WIFI;
if (strcmp(str, "cellular") == 0)
return CONNMAN_SERVICE_TYPE_CELLULAR;
if (strcmp(str, "bluetooth") == 0)
return CONNMAN_SERVICE_TYPE_BLUETOOTH;
if (strcmp(str, "vpn") == 0)
return CONNMAN_SERVICE_TYPE_VPN;
if (strcmp(str, "gps") == 0)
return CONNMAN_SERVICE_TYPE_GPS;
if (strcmp(str, "system") == 0)
return CONNMAN_SERVICE_TYPE_SYSTEM;
if (strcmp(str, "p2p") == 0)
return CONNMAN_SERVICE_TYPE_P2P;
return CONNMAN_SERVICE_TYPE_UNKNOWN;
}
enum connman_service_security __connman_service_string2security(const char *str)
{
if (!str)
return CONNMAN_SERVICE_SECURITY_UNKNOWN;
if (!strcmp(str, "psk"))
return CONNMAN_SERVICE_SECURITY_PSK;
if (!strcmp(str, "ieee8021x") || !strcmp(str, "8021x"))
return CONNMAN_SERVICE_SECURITY_8021X;
if (!strcmp(str, "none") || !strcmp(str, "open"))
return CONNMAN_SERVICE_SECURITY_NONE;
if (!strcmp(str, "wep"))
return CONNMAN_SERVICE_SECURITY_WEP;
return CONNMAN_SERVICE_SECURITY_UNKNOWN;
}
static const char *security2string(enum connman_service_security security)
{
switch (security) {
case CONNMAN_SERVICE_SECURITY_UNKNOWN:
break;
case CONNMAN_SERVICE_SECURITY_NONE:
return "none";
case CONNMAN_SERVICE_SECURITY_WEP:
return "wep";
case CONNMAN_SERVICE_SECURITY_PSK:
case CONNMAN_SERVICE_SECURITY_WPA:
case CONNMAN_SERVICE_SECURITY_RSN:
return "psk";
case CONNMAN_SERVICE_SECURITY_8021X:
return "ieee8021x";
}
return NULL;
}
static const char *state2string(enum connman_service_state state)
{
switch (state) {
case CONNMAN_SERVICE_STATE_UNKNOWN:
break;
case CONNMAN_SERVICE_STATE_IDLE:
return "idle";
case CONNMAN_SERVICE_STATE_ASSOCIATION:
return "association";
case CONNMAN_SERVICE_STATE_CONFIGURATION:
return "configuration";
case CONNMAN_SERVICE_STATE_READY:
return "ready";
case CONNMAN_SERVICE_STATE_ONLINE:
return "online";
case CONNMAN_SERVICE_STATE_DISCONNECT:
return "disconnect";
case CONNMAN_SERVICE_STATE_FAILURE:
return "failure";
}
return NULL;
}
static const char *error2string(enum connman_service_error error)
{
switch (error) {
case CONNMAN_SERVICE_ERROR_UNKNOWN:
break;
case CONNMAN_SERVICE_ERROR_OUT_OF_RANGE:
return "out-of-range";
case CONNMAN_SERVICE_ERROR_PIN_MISSING:
return "pin-missing";
case CONNMAN_SERVICE_ERROR_DHCP_FAILED:
return "dhcp-failed";
case CONNMAN_SERVICE_ERROR_CONNECT_FAILED:
return "connect-failed";
case CONNMAN_SERVICE_ERROR_LOGIN_FAILED:
return "login-failed";
case CONNMAN_SERVICE_ERROR_AUTH_FAILED:
return "auth-failed";
case CONNMAN_SERVICE_ERROR_INVALID_KEY:
return "invalid-key";
case CONNMAN_SERVICE_ERROR_BLOCKED:
return "blocked";
}
return NULL;
}
static const char *proxymethod2string(enum connman_service_proxy_method method)
{
switch (method) {
case CONNMAN_SERVICE_PROXY_METHOD_DIRECT:
return "direct";
case CONNMAN_SERVICE_PROXY_METHOD_MANUAL:
return "manual";
case CONNMAN_SERVICE_PROXY_METHOD_AUTO:
return "auto";
case CONNMAN_SERVICE_PROXY_METHOD_UNKNOWN:
break;
}
return NULL;
}
static enum connman_service_proxy_method string2proxymethod(const char *method)
{
if (g_strcmp0(method, "direct") == 0)
return CONNMAN_SERVICE_PROXY_METHOD_DIRECT;
else if (g_strcmp0(method, "auto") == 0)
return CONNMAN_SERVICE_PROXY_METHOD_AUTO;
else if (g_strcmp0(method, "manual") == 0)
return CONNMAN_SERVICE_PROXY_METHOD_MANUAL;
else
return CONNMAN_SERVICE_PROXY_METHOD_UNKNOWN;
}
static void set_split_routing(struct connman_service *service, bool value)
{
if (service->type != CONNMAN_SERVICE_TYPE_VPN)
return;
service->do_split_routing = value;
if (service->do_split_routing)
service->order = 0;
else
service->order = 10;
}
int __connman_service_load_modifiable(struct connman_service *service)
{
GKeyFile *keyfile;
GError *error = NULL;
gchar *str;
bool autoconnect;
DBG("service %p", service);
keyfile = connman_storage_load_service(service->identifier);
if (!keyfile)
return -EIO;
switch (service->type) {
case CONNMAN_SERVICE_TYPE_UNKNOWN:
case CONNMAN_SERVICE_TYPE_SYSTEM:
case CONNMAN_SERVICE_TYPE_GPS:
case CONNMAN_SERVICE_TYPE_P2P:
break;
case CONNMAN_SERVICE_TYPE_VPN:
set_split_routing(service, g_key_file_get_boolean(keyfile,
service->identifier,
"SplitRouting", NULL));
/* fall through */
case CONNMAN_SERVICE_TYPE_WIFI:
case CONNMAN_SERVICE_TYPE_GADGET:
case CONNMAN_SERVICE_TYPE_BLUETOOTH:
case CONNMAN_SERVICE_TYPE_CELLULAR:
case CONNMAN_SERVICE_TYPE_ETHERNET:
autoconnect = g_key_file_get_boolean(keyfile,
service->identifier, "AutoConnect", &error);
if (!error)
service->autoconnect = autoconnect;
g_clear_error(&error);
break;
}
str = g_key_file_get_string(keyfile,
service->identifier, "Modified", NULL);
if (str) {
g_time_val_from_iso8601(str, &service->modified);
g_free(str);
}
g_key_file_free(keyfile);
return 0;
}
static int service_load(struct connman_service *service)
{
GKeyFile *keyfile;
GError *error = NULL;
gsize length;
gchar *str;
bool autoconnect;
unsigned int ssid_len;
int err = 0;
DBG("service %p", service);
keyfile = connman_storage_load_service(service->identifier);
if (!keyfile) {
service->new_service = true;
return -EIO;
} else
service->new_service = false;
switch (service->type) {
case CONNMAN_SERVICE_TYPE_UNKNOWN:
case CONNMAN_SERVICE_TYPE_SYSTEM:
case CONNMAN_SERVICE_TYPE_GPS:
case CONNMAN_SERVICE_TYPE_P2P:
break;
case CONNMAN_SERVICE_TYPE_VPN:
set_split_routing(service, g_key_file_get_boolean(keyfile,
service->identifier,
"SplitRouting", NULL));
autoconnect = g_key_file_get_boolean(keyfile,
service->identifier, "AutoConnect", &error);
if (!error)
service->autoconnect = autoconnect;
g_clear_error(&error);
break;
case CONNMAN_SERVICE_TYPE_WIFI:
if (!service->name) {
gchar *name;
name = g_key_file_get_string(keyfile,
service->identifier, "Name", NULL);
if (name) {
g_free(service->name);
service->name = name;
}
if (service->network)
connman_network_set_name(service->network,
name);
}
if (service->network &&
!connman_network_get_blob(service->network,
"WiFi.SSID", &ssid_len)) {
gchar *hex_ssid;
hex_ssid = g_key_file_get_string(keyfile,
service->identifier,
"SSID", NULL);
if (hex_ssid) {
gchar *ssid;
unsigned int i, j = 0, hex;
size_t hex_ssid_len = strlen(hex_ssid);
ssid = g_try_malloc0(hex_ssid_len / 2);
if (!ssid) {
g_free(hex_ssid);
err = -ENOMEM;
goto done;
}
for (i = 0; i < hex_ssid_len; i += 2) {
sscanf(hex_ssid + i, "%02x", &hex);
ssid[j++] = hex;
}
connman_network_set_blob(service->network,
"WiFi.SSID", ssid, hex_ssid_len / 2);
g_free(ssid);
}
g_free(hex_ssid);
}
/* fall through */
case CONNMAN_SERVICE_TYPE_GADGET:
case CONNMAN_SERVICE_TYPE_BLUETOOTH:
case CONNMAN_SERVICE_TYPE_CELLULAR:
service->favorite = g_key_file_get_boolean(keyfile,
service->identifier, "Favorite", NULL);
/* fall through */
case CONNMAN_SERVICE_TYPE_ETHERNET:
autoconnect = g_key_file_get_boolean(keyfile,
service->identifier, "AutoConnect", &error);
if (!error)
service->autoconnect = autoconnect;
g_clear_error(&error);
break;
}
str = g_key_file_get_string(keyfile,
service->identifier, "Modified", NULL);
if (str) {
g_time_val_from_iso8601(str, &service->modified);
g_free(str);
}
str = g_key_file_get_string(keyfile,
service->identifier, "Passphrase", NULL);
if (str) {
g_free(service->passphrase);
service->passphrase = str;
}
if (service->ipconfig_ipv4)
__connman_ipconfig_load(service->ipconfig_ipv4, keyfile,
service->identifier, "IPv4.");
if (service->ipconfig_ipv6)
__connman_ipconfig_load(service->ipconfig_ipv6, keyfile,
service->identifier, "IPv6.");
service->nameservers_config = g_key_file_get_string_list(keyfile,
service->identifier, "Nameservers", &length, NULL);
if (service->nameservers_config && length == 0) {
g_strfreev(service->nameservers_config);
service->nameservers_config = NULL;
}
service->timeservers_config = g_key_file_get_string_list(keyfile,
service->identifier, "Timeservers", &length, NULL);
if (service->timeservers_config && length == 0) {
g_strfreev(service->timeservers_config);
service->timeservers_config = NULL;
}
service->domains = g_key_file_get_string_list(keyfile,
service->identifier, "Domains", &length, NULL);
if (service->domains && length == 0) {
g_strfreev(service->domains);
service->domains = NULL;
}
str = g_key_file_get_string(keyfile,
service->identifier, "Proxy.Method", NULL);
if (str)
service->proxy_config = string2proxymethod(str);
g_free(str);
service->proxies = g_key_file_get_string_list(keyfile,
service->identifier, "Proxy.Servers", &length, NULL);
if (service->proxies && length == 0) {
g_strfreev(service->proxies);
service->proxies = NULL;
}
service->excludes = g_key_file_get_string_list(keyfile,
service->identifier, "Proxy.Excludes", &length, NULL);
if (service->excludes && length == 0) {
g_strfreev(service->excludes);
service->excludes = NULL;
}
str = g_key_file_get_string(keyfile,
service->identifier, "Proxy.URL", NULL);
if (str) {
g_free(service->pac);
service->pac = str;
}
service->mdns_config = g_key_file_get_boolean(keyfile,
service->identifier, "mDNS", NULL);
service->hidden_service = g_key_file_get_boolean(keyfile,
service->identifier, "Hidden", NULL);
done:
g_key_file_free(keyfile);
return err;
}
static int service_save(struct connman_service *service)
{
GKeyFile *keyfile;
gchar *str;
guint freq;
const char *cst_str = NULL;
int err = 0;
DBG("service %p new %d", service, service->new_service);
if (service->new_service)
return -ESRCH;
keyfile = __connman_storage_open_service(service->identifier);
if (!keyfile)
return -EIO;
if (service->name)
g_key_file_set_string(keyfile, service->identifier,
"Name", service->name);
switch (service->type) {
case CONNMAN_SERVICE_TYPE_UNKNOWN:
case CONNMAN_SERVICE_TYPE_SYSTEM:
case CONNMAN_SERVICE_TYPE_GPS:
case CONNMAN_SERVICE_TYPE_P2P:
break;
case CONNMAN_SERVICE_TYPE_VPN:
g_key_file_set_boolean(keyfile, service->identifier,
"SplitRouting", service->do_split_routing);
if (service->favorite)
g_key_file_set_boolean(keyfile, service->identifier,
"AutoConnect", service->autoconnect);
break;
case CONNMAN_SERVICE_TYPE_WIFI:
if (service->network) {
const unsigned char *ssid;
unsigned int ssid_len = 0;
ssid = connman_network_get_blob(service->network,
"WiFi.SSID", &ssid_len);
if (ssid && ssid_len > 0 && ssid[0] != '\0') {
char *identifier = service->identifier;
GString *ssid_str;
unsigned int i;
ssid_str = g_string_sized_new(ssid_len * 2);
if (!ssid_str) {
err = -ENOMEM;
goto done;
}
for (i = 0; i < ssid_len; i++)
g_string_append_printf(ssid_str,
"%02x", ssid[i]);
g_key_file_set_string(keyfile, identifier,
"SSID", ssid_str->str);
g_string_free(ssid_str, TRUE);
}
freq = connman_network_get_frequency(service->network);
g_key_file_set_integer(keyfile, service->identifier,
"Frequency", freq);
}
/* fall through */
case CONNMAN_SERVICE_TYPE_GADGET:
case CONNMAN_SERVICE_TYPE_BLUETOOTH:
case CONNMAN_SERVICE_TYPE_CELLULAR:
g_key_file_set_boolean(keyfile, service->identifier,
"Favorite", service->favorite);
g_key_file_remove_key(keyfile, service->identifier,
"Failure", NULL);
/* fall through */
case CONNMAN_SERVICE_TYPE_ETHERNET:
if (service->favorite)
g_key_file_set_boolean(keyfile, service->identifier,
"AutoConnect", service->autoconnect);
break;
}
str = g_time_val_to_iso8601(&service->modified);
if (str) {
g_key_file_set_string(keyfile, service->identifier,
"Modified", str);
g_free(str);
}
if (service->passphrase && strlen(service->passphrase) > 0)
g_key_file_set_string(keyfile, service->identifier,
"Passphrase", service->passphrase);
else
g_key_file_remove_key(keyfile, service->identifier,
"Passphrase", NULL);
if (service->ipconfig_ipv4)
__connman_ipconfig_save(service->ipconfig_ipv4, keyfile,
service->identifier, "IPv4.");
if (service->ipconfig_ipv6)
__connman_ipconfig_save(service->ipconfig_ipv6, keyfile,
service->identifier, "IPv6.");
if (service->nameservers_config) {
guint len = g_strv_length(service->nameservers_config);
g_key_file_set_string_list(keyfile, service->identifier,
"Nameservers",
(const gchar **) service->nameservers_config, len);
} else
g_key_file_remove_key(keyfile, service->identifier,
"Nameservers", NULL);
if (service->timeservers_config) {
guint len = g_strv_length(service->timeservers_config);
g_key_file_set_string_list(keyfile, service->identifier,
"Timeservers",
(const gchar **) service->timeservers_config, len);
} else
g_key_file_remove_key(keyfile, service->identifier,
"Timeservers", NULL);
if (service->domains) {
guint len = g_strv_length(service->domains);
g_key_file_set_string_list(keyfile, service->identifier,
"Domains",
(const gchar **) service->domains, len);
} else
g_key_file_remove_key(keyfile, service->identifier,
"Domains", NULL);
cst_str = proxymethod2string(service->proxy_config);
if (cst_str)
g_key_file_set_string(keyfile, service->identifier,
"Proxy.Method", cst_str);
if (service->proxies) {
guint len = g_strv_length(service->proxies);
g_key_file_set_string_list(keyfile, service->identifier,
"Proxy.Servers",
(const gchar **) service->proxies, len);
} else
g_key_file_remove_key(keyfile, service->identifier,
"Proxy.Servers", NULL);
if (service->excludes) {
guint len = g_strv_length(service->excludes);
g_key_file_set_string_list(keyfile, service->identifier,
"Proxy.Excludes",
(const gchar **) service->excludes, len);
} else
g_key_file_remove_key(keyfile, service->identifier,
"Proxy.Excludes", NULL);
if (service->pac && strlen(service->pac) > 0)
g_key_file_set_string(keyfile, service->identifier,
"Proxy.URL", service->pac);
else
g_key_file_remove_key(keyfile, service->identifier,
"Proxy.URL", NULL);
if (service->mdns_config)
g_key_file_set_boolean(keyfile, service->identifier,
"mDNS", TRUE);
else
g_key_file_remove_key(keyfile, service->identifier,
"mDNS", NULL);
if (service->hidden_service)
g_key_file_set_boolean(keyfile, service->identifier, "Hidden",
TRUE);
if (service->config_file && strlen(service->config_file) > 0)
g_key_file_set_string(keyfile, service->identifier,
"Config.file", service->config_file);
if (service->config_entry &&
strlen(service->config_entry) > 0)
g_key_file_set_string(keyfile, service->identifier,
"Config.ident", service->config_entry);
done:
__connman_storage_save_service(keyfile, service->identifier);
g_key_file_free(keyfile);
return err;
}
void __connman_service_save(struct connman_service *service)
{
if (!service)
return;
service_save(service);
}
static enum connman_service_state combine_state(
enum connman_service_state state_a,
enum connman_service_state state_b)
{
enum connman_service_state result;
if (state_a == state_b) {
result = state_a;
goto done;
}
if (state_a == CONNMAN_SERVICE_STATE_UNKNOWN) {
result = state_b;
goto done;
}
if (state_b == CONNMAN_SERVICE_STATE_UNKNOWN) {
result = state_a;
goto done;
}
if (state_a == CONNMAN_SERVICE_STATE_IDLE) {
result = state_b;
goto done;
}
if (state_b == CONNMAN_SERVICE_STATE_IDLE) {
result = state_a;
goto done;
}
if (state_a == CONNMAN_SERVICE_STATE_ONLINE) {
result = state_a;
goto done;
}
if (state_b == CONNMAN_SERVICE_STATE_ONLINE) {
result = state_b;
goto done;
}
if (state_a == CONNMAN_SERVICE_STATE_READY) {
result = state_a;
goto done;
}
if (state_b == CONNMAN_SERVICE_STATE_READY) {
result = state_b;
goto done;
}
if (state_a == CONNMAN_SERVICE_STATE_CONFIGURATION) {
result = state_a;
goto done;
}
if (state_b == CONNMAN_SERVICE_STATE_CONFIGURATION) {
result = state_b;
goto done;
}
if (state_a == CONNMAN_SERVICE_STATE_ASSOCIATION) {
result = state_a;
goto done;
}
if (state_b == CONNMAN_SERVICE_STATE_ASSOCIATION) {
result = state_b;
goto done;
}
if (state_a == CONNMAN_SERVICE_STATE_DISCONNECT) {
result = state_a;
goto done;
}
if (state_b == CONNMAN_SERVICE_STATE_DISCONNECT) {
result = state_b;
goto done;
}
result = CONNMAN_SERVICE_STATE_FAILURE;
done:
return result;
}
static bool is_connecting(enum connman_service_state state)
{
switch (state) {
case CONNMAN_SERVICE_STATE_UNKNOWN:
case CONNMAN_SERVICE_STATE_IDLE:
case CONNMAN_SERVICE_STATE_FAILURE:
case CONNMAN_SERVICE_STATE_DISCONNECT:
case CONNMAN_SERVICE_STATE_READY:
case CONNMAN_SERVICE_STATE_ONLINE:
break;
case CONNMAN_SERVICE_STATE_ASSOCIATION:
case CONNMAN_SERVICE_STATE_CONFIGURATION:
return true;
}
return false;
}
static bool is_connected(enum connman_service_state state)
{
switch (state) {
case CONNMAN_SERVICE_STATE_UNKNOWN:
case CONNMAN_SERVICE_STATE_IDLE:
case CONNMAN_SERVICE_STATE_ASSOCIATION:
case CONNMAN_SERVICE_STATE_CONFIGURATION:
case CONNMAN_SERVICE_STATE_DISCONNECT:
case CONNMAN_SERVICE_STATE_FAILURE:
break;
case CONNMAN_SERVICE_STATE_READY:
case CONNMAN_SERVICE_STATE_ONLINE:
return true;
}
return false;
}
static bool is_idle(enum connman_service_state state)
{
switch (state) {
case CONNMAN_SERVICE_STATE_IDLE:
case CONNMAN_SERVICE_STATE_DISCONNECT:
case CONNMAN_SERVICE_STATE_FAILURE:
return true;
case CONNMAN_SERVICE_STATE_UNKNOWN:
case CONNMAN_SERVICE_STATE_ASSOCIATION:
case CONNMAN_SERVICE_STATE_CONFIGURATION:
case CONNMAN_SERVICE_STATE_READY:
case CONNMAN_SERVICE_STATE_ONLINE:
break;
}
return false;
}
static int nameservers_changed_cb(void *user_data)
{
struct connman_service *service = user_data;
DBG("service %p", service);
service->nameservers_timeout = 0;
if ((is_idle(service->state) && !service->nameservers) ||
is_connected(service->state))
dns_changed(service);
return FALSE;
}
static void nameservers_changed(struct connman_service *service)
{
if (!service->nameservers_timeout)
service->nameservers_timeout = g_idle_add(nameservers_changed_cb,
service);
}
static bool nameserver_available(struct connman_service *service,
enum connman_ipconfig_type type,
const char *ns)
{
int family;
family = connman_inet_check_ipaddress(ns);
if (family == AF_INET) {
if (type == CONNMAN_IPCONFIG_TYPE_IPV6)
return false;
return is_connected(service->state_ipv4);
}
if (family == AF_INET6) {
if (type == CONNMAN_IPCONFIG_TYPE_IPV4)
return false;
return is_connected(service->state_ipv6);
}
return false;
}
static int searchdomain_add_all(struct connman_service *service)
{
int index, i = 0;
if (!is_connected(service->state))
return -ENOTCONN;
index = __connman_service_get_index(service);
if (index < 0)
return -ENXIO;
if (service->domains) {
while (service->domains[i]) {
connman_resolver_append(index, service->domains[i],
NULL);
i++;
}
return 0;
}
if (service->domainname)
connman_resolver_append(index, service->domainname, NULL);
return 0;
}
static int searchdomain_remove_all(struct connman_service *service)
{
int index, i = 0;
if (!is_connected(service->state))
return -ENOTCONN;
index = __connman_service_get_index(service);
if (index < 0)
return -ENXIO;
while (service->domains && service->domains[i]) {
connman_resolver_remove(index, service->domains[i], NULL);
i++;
}
if (service->domainname)
connman_resolver_remove(index, service->domainname, NULL);
return 0;
}
static int nameserver_add(struct connman_service *service,
enum connman_ipconfig_type type,
const char *nameserver)
{
int index, ret;
if (!nameserver_available(service, type, nameserver))
return 0;
index = __connman_service_get_index(service);
if (index < 0)
return -ENXIO;
ret = connman_resolver_append(index, NULL, nameserver);
if (ret >= 0)
nameservers_changed(service);
return ret;
}
static int nameserver_add_all(struct connman_service *service,
enum connman_ipconfig_type type)
{
int i = 0;
if (service->nameservers_config) {
while (service->nameservers_config[i]) {
nameserver_add(service, type,
service->nameservers_config[i]);
i++;
}
} else if (service->nameservers) {
while (service->nameservers[i]) {
nameserver_add(service, type,
service->nameservers[i]);
i++;
}
}
if (!i)
__connman_resolver_append_fallback_nameservers();
searchdomain_add_all(service);
return 0;
}
static int nameserver_remove(struct connman_service *service,
enum connman_ipconfig_type type,
const char *nameserver)
{
int index, ret;
if (!nameserver_available(service, type, nameserver))
return 0;
index = __connman_service_get_index(service);
if (index < 0)
return -ENXIO;
ret = connman_resolver_remove(index, NULL, nameserver);
if (ret >= 0)
nameservers_changed(service);
return ret;
}
static int nameserver_remove_all(struct connman_service *service,
enum connman_ipconfig_type type)
{
int index, i = 0;
index = __connman_service_get_index(service);
if (index < 0)
return -ENXIO;
while (service->nameservers_config && service->nameservers_config[i]) {
nameserver_remove(service, type,
service->nameservers_config[i]);
i++;
}
i = 0;
while (service->nameservers && service->nameservers[i]) {
nameserver_remove(service, type, service->nameservers[i]);
i++;
}
searchdomain_remove_all(service);
return 0;
}
/*
* The is_auto variable is set to true when IPv6 autoconf nameservers are
* inserted to resolver via netlink message (see rtnl.c:rtnl_newnduseropt()
* for details) and not through service.c
*/
int __connman_service_nameserver_append(struct connman_service *service,
const char *nameserver, bool is_auto)
{
char **nameservers;
int len, i;
DBG("service %p nameserver %s auto %d", service, nameserver, is_auto);
if (!nameserver)
return -EINVAL;
if (is_auto)
nameservers = service->nameservers_auto;
else
nameservers = service->nameservers;
for (i = 0; nameservers && nameservers[i]; i++)
if (g_strcmp0(nameservers[i], nameserver) == 0)
return -EEXIST;
if (nameservers) {
len = g_strv_length(nameservers);
nameservers = g_try_renew(char *, nameservers, len + 2);
} else {
len = 0;
nameservers = g_try_new0(char *, len + 2);
}
if (!nameservers)
return -ENOMEM;
nameservers[len] = g_strdup(nameserver);
nameservers[len + 1] = NULL;
if (is_auto) {
service->nameservers_auto = nameservers;
} else {
service->nameservers = nameservers;
nameserver_add(service, CONNMAN_IPCONFIG_TYPE_ALL, nameserver);
}
nameservers_changed(service);
searchdomain_add_all(service);
return 0;
}
int __connman_service_nameserver_remove(struct connman_service *service,
const char *nameserver, bool is_auto)
{
char **servers, **nameservers;
bool found = false;
int len, i, j;
DBG("service %p nameserver %s auto %d", service, nameserver, is_auto);
if (!nameserver)
return -EINVAL;
if (is_auto)
nameservers = service->nameservers_auto;
else
nameservers = service->nameservers;
if (!nameservers)
return 0;
for (i = 0; nameservers[i]; i++)
if (g_strcmp0(nameservers[i], nameserver) == 0) {
found = true;
break;
}
if (!found)
return 0;
len = g_strv_length(nameservers);
if (len == 1) {
servers = NULL;
goto set_servers;
}
servers = g_try_new0(char *, len);
if (!servers)
return -ENOMEM;
for (i = 0, j = 0; i < len; i++) {
if (g_strcmp0(nameservers[i], nameserver)) {
servers[j] = nameservers[i];
j++;
} else
g_free(nameservers[i]);
nameservers[i] = NULL;
}
servers[len - 1] = NULL;
set_servers:
g_strfreev(nameservers);
nameservers = servers;
if (is_auto) {
service->nameservers_auto = nameservers;
} else {
service->nameservers = nameservers;
nameserver_remove(service, CONNMAN_IPCONFIG_TYPE_ALL,
nameserver);
}
return 0;
}
void __connman_service_nameserver_clear(struct connman_service *service)
{
nameserver_remove_all(service, CONNMAN_IPCONFIG_TYPE_ALL);
g_strfreev(service->nameservers);
service->nameservers = NULL;
nameserver_add_all(service, CONNMAN_IPCONFIG_TYPE_ALL);
}
static void add_nameserver_route(int family, int index, char *nameserver,
const char *gw)
{
switch (family) {
case AF_INET:
if (connman_inet_compare_subnet(index, nameserver))
break;
if (connman_inet_add_host_route(index, nameserver, gw) < 0)
/* For P-t-P link the above route add will fail */
connman_inet_add_host_route(index, nameserver, NULL);
break;
case AF_INET6:
if (connman_inet_add_ipv6_host_route(index, nameserver,
gw) < 0)
connman_inet_add_ipv6_host_route(index, nameserver,
NULL);
break;
}
}
static void nameserver_add_routes(int index, char **nameservers,
const char *gw)
{
int i, ns_family, gw_family;
gw_family = connman_inet_check_ipaddress(gw);
if (gw_family < 0)
return;
for (i = 0; nameservers[i]; i++) {
ns_family = connman_inet_check_ipaddress(nameservers[i]);
if (ns_family < 0 || ns_family != gw_family)
continue;
add_nameserver_route(ns_family, index, nameservers[i], gw);
}
}
static void nameserver_del_routes(int index, char **nameservers,
enum connman_ipconfig_type type)
{
int i, family;
for (i = 0; nameservers[i]; i++) {
family = connman_inet_check_ipaddress(nameservers[i]);
if (family < 0)
continue;
switch (family) {
case AF_INET:
if (type != CONNMAN_IPCONFIG_TYPE_IPV6)
connman_inet_del_host_route(index,
nameservers[i]);
break;
case AF_INET6:
if (type != CONNMAN_IPCONFIG_TYPE_IPV4)
connman_inet_del_ipv6_host_route(index,
nameservers[i]);
break;
}
}
}
void __connman_service_nameserver_add_routes(struct connman_service *service,
const char *gw)
{
int index;
if (!service)
return;
index = __connman_service_get_index(service);
if (service->nameservers_config) {
/*
* Configured nameserver takes preference over the
* discoverd nameserver gathered from DHCP, VPN, etc.
*/
nameserver_add_routes(index, service->nameservers_config, gw);
} else if (service->nameservers) {
/*
* We add nameservers host routes for nameservers that
* are not on our subnet. For those who are, the subnet
* route will be installed by the time the dns proxy code
* tries to reach them. The subnet route is installed
* when setting the interface IP address.
*/
nameserver_add_routes(index, service->nameservers, gw);
}
}
void __connman_service_nameserver_del_routes(struct connman_service *service,
enum connman_ipconfig_type type)
{
int index;
if (!service)
return;
index = __connman_service_get_index(service);
if (service->nameservers_config)
nameserver_del_routes(index, service->nameservers_config,
type);
else if (service->nameservers)
nameserver_del_routes(index, service->nameservers, type);
}
static void address_updated(struct connman_service *service,
enum connman_ipconfig_type type)
{
if (is_connected(service->state) &&
service == __connman_service_get_default()) {
nameserver_remove_all(service, type);
nameserver_add_all(service, type);
__connman_timeserver_sync(service);
}
}
static struct connman_stats *stats_get(struct connman_service *service)
{
if (service->roaming)
return &service->stats_roaming;
else
return &service->stats;
}
static bool stats_enabled(struct connman_service *service)
{
struct connman_stats *stats = stats_get(service);
return stats->enabled;
}
static void stats_start(struct connman_service *service)
{
struct connman_stats *stats = stats_get(service);
DBG("service %p", service);
if (!stats->timer)
return;
stats->enabled = true;
stats->data_last.time = stats->data.time;
g_timer_start(stats->timer);
}
static void stats_stop(struct connman_service *service)
{
struct connman_stats *stats = stats_get(service);
unsigned int seconds;
DBG("service %p", service);
if (!stats->timer)
return;
if (!stats->enabled)
return;
g_timer_stop(stats->timer);
seconds = g_timer_elapsed(stats->timer, NULL);
stats->data.time = stats->data_last.time + seconds;
stats->enabled = false;
}
static void reset_stats(struct connman_service *service)
{
DBG("service %p", service);
/* home */
service->stats.valid = false;
service->stats.data.rx_packets = 0;
service->stats.data.tx_packets = 0;
service->stats.data.rx_bytes = 0;
service->stats.data.tx_bytes = 0;
service->stats.data.rx_errors = 0;
service->stats.data.tx_errors = 0;
service->stats.data.rx_dropped = 0;
service->stats.data.tx_dropped = 0;
service->stats.data.time = 0;
service->stats.data_last.time = 0;
g_timer_reset(service->stats.timer);
/* roaming */
service->stats_roaming.valid = false;
service->stats_roaming.data.rx_packets = 0;
service->stats_roaming.data.tx_packets = 0;
service->stats_roaming.data.rx_bytes = 0;
service->stats_roaming.data.tx_bytes = 0;
service->stats_roaming.data.rx_errors = 0;
service->stats_roaming.data.tx_errors = 0;
service->stats_roaming.data.rx_dropped = 0;
service->stats_roaming.data.tx_dropped = 0;
service->stats_roaming.data.time = 0;
service->stats_roaming.data_last.time = 0;
g_timer_reset(service->stats_roaming.timer);
}
struct connman_service *__connman_service_get_default(void)
{
struct connman_service *service;
if (!service_list)
return NULL;
service = service_list->data;
if (!is_connected(service->state))
return NULL;
return service;
}
bool __connman_service_index_is_default(int index)
{
struct connman_service *service;
if (index < 0)
return false;
service = __connman_service_get_default();
return __connman_service_get_index(service) == index;
}
static void default_changed(void)
{
struct connman_service *service = __connman_service_get_default();
if (service == current_default)
return;
DBG("current default %p %s", current_default,
current_default ? current_default->identifier : "");
DBG("new default %p %s", service, service ? service->identifier : "");
__connman_service_timeserver_changed(current_default, NULL);
current_default = service;
if (service) {
if (service->hostname &&
connman_setting_get_bool("AllowHostnameUpdates"))
__connman_utsname_set_hostname(service->hostname);
if (service->domainname &&
connman_setting_get_bool("AllowDomainnameUpdates"))
__connman_utsname_set_domainname(service->domainname);
}
__connman_notifier_default_changed(service);
}
static void state_changed(struct connman_service *service)
{
const char *str;
__connman_notifier_service_state_changed(service, service->state);
str = state2string(service->state);
if (!str)
return;
if (!allow_property_changed(service))
return;
connman_dbus_property_changed_basic(service->path,
CONNMAN_SERVICE_INTERFACE, "State",
DBUS_TYPE_STRING, &str);
}
static void strength_changed(struct connman_service *service)
{
if (service->strength == 0)
return;
if (!allow_property_changed(service))
return;
connman_dbus_property_changed_basic(service->path,
CONNMAN_SERVICE_INTERFACE, "Strength",
DBUS_TYPE_BYTE, &service->strength);
}
static void favorite_changed(struct connman_service *service)
{
dbus_bool_t favorite;
if (!service->path)
return;
if (!allow_property_changed(service))
return;
favorite = service->favorite;
connman_dbus_property_changed_basic(service->path,
CONNMAN_SERVICE_INTERFACE, "Favorite",
DBUS_TYPE_BOOLEAN, &favorite);
}
static void immutable_changed(struct connman_service *service)
{
dbus_bool_t immutable;
if (!service->path)
return;
if (!allow_property_changed(service))
return;
immutable = service->immutable;
connman_dbus_property_changed_basic(service->path,
CONNMAN_SERVICE_INTERFACE, "Immutable",
DBUS_TYPE_BOOLEAN, &immutable);
}
static void roaming_changed(struct connman_service *service)
{
dbus_bool_t roaming;
if (!service->path)
return;
if (!allow_property_changed(service))
return;
roaming = service->roaming;
connman_dbus_property_changed_basic(service->path,
CONNMAN_SERVICE_INTERFACE, "Roaming",
DBUS_TYPE_BOOLEAN, &roaming);
}
static void autoconnect_changed(struct connman_service *service)
{
dbus_bool_t autoconnect;
if (!service->path)
return;
if (!allow_property_changed(service))
return;
autoconnect = service->autoconnect;
connman_dbus_property_changed_basic(service->path,
CONNMAN_SERVICE_INTERFACE, "AutoConnect",
DBUS_TYPE_BOOLEAN, &autoconnect);
}
static void append_security(DBusMessageIter *iter, void *user_data)
{
struct connman_service *service = user_data;
const char *str;
str = security2string(service->security);
if (str)
dbus_message_iter_append_basic(iter,
DBUS_TYPE_STRING, &str);
/*
* Some access points incorrectly advertise WPS even when they
* are configured as open or no security, so filter
* appropriately.
*/
if (service->wps) {
switch (service->security) {
case CONNMAN_SERVICE_SECURITY_PSK:
case CONNMAN_SERVICE_SECURITY_WPA:
case CONNMAN_SERVICE_SECURITY_RSN:
str = "wps";
dbus_message_iter_append_basic(iter,
DBUS_TYPE_STRING, &str);
break;
case CONNMAN_SERVICE_SECURITY_UNKNOWN:
case CONNMAN_SERVICE_SECURITY_NONE:
case CONNMAN_SERVICE_SECURITY_WEP:
case CONNMAN_SERVICE_SECURITY_8021X:
break;
}
if (service->wps_advertizing) {
str = "wps_advertising";
dbus_message_iter_append_basic(iter,
DBUS_TYPE_STRING, &str);
}
}
}
static void security_changed(struct connman_service *service)
{
if (!service->path)
return;
if (!allow_property_changed(service))
return;
connman_dbus_property_changed_array(service->path,
CONNMAN_SERVICE_INTERFACE, "Security",
DBUS_TYPE_STRING, append_security, service);
}
static void append_ethernet(DBusMessageIter *iter, void *user_data)
{
struct connman_service *service = user_data;
if (service->ipconfig_ipv4)
__connman_ipconfig_append_ethernet(service->ipconfig_ipv4,
iter);
else if (service->ipconfig_ipv6)
__connman_ipconfig_append_ethernet(service->ipconfig_ipv6,
iter);
}
static void append_ipv4(DBusMessageIter *iter, void *user_data)
{
struct connman_service *service = user_data;
if (!is_connected(service->state_ipv4))
return;
if (service->ipconfig_ipv4)
__connman_ipconfig_append_ipv4(service->ipconfig_ipv4, iter);
}
static void append_ipv6(DBusMessageIter *iter, void *user_data)
{
struct connman_service *service = user_data;
if (!is_connected(service->state_ipv6))
return;
if (service->ipconfig_ipv6)
__connman_ipconfig_append_ipv6(service->ipconfig_ipv6, iter,
service->ipconfig_ipv4);
}
static void append_ipv4config(DBusMessageIter *iter, void *user_data)
{
struct connman_service *service = user_data;
if (service->ipconfig_ipv4)
__connman_ipconfig_append_ipv4config(service->ipconfig_ipv4,
iter);
}
static void append_ipv6config(DBusMessageIter *iter, void *user_data)
{
struct connman_service *service = user_data;
if (service->ipconfig_ipv6)
__connman_ipconfig_append_ipv6config(service->ipconfig_ipv6,
iter);
}
static void append_nameservers(DBusMessageIter *iter,
struct connman_service *service, char **servers)
{
int i;
bool available = true;
for (i = 0; servers[i]; i++) {
if (service)
available = nameserver_available(service,
CONNMAN_IPCONFIG_TYPE_ALL,
servers[i]);
if (available)
dbus_message_iter_append_basic(iter,
DBUS_TYPE_STRING, &servers[i]);
}
}
static void append_dns(DBusMessageIter *iter, void *user_data)
{
struct connman_service *service = user_data;
if (!is_connected(service->state))
return;
if (service->nameservers_config) {
append_nameservers(iter, service, service->nameservers_config);
return;
} else {
if (service->nameservers)
append_nameservers(iter, service,
service->nameservers);
if (service->nameservers_auto)
append_nameservers(iter, service,
service->nameservers_auto);
if (!service->nameservers && !service->nameservers_auto) {
char **ns;
DBG("append fallback nameservers");
ns = connman_setting_get_string_list("FallbackNameservers");
if (ns)
append_nameservers(iter, service, ns);
}
}
}
static void append_dnsconfig(DBusMessageIter *iter, void *user_data)
{
struct connman_service *service = user_data;
if (!service->nameservers_config)
return;
append_nameservers(iter, NULL, service->nameservers_config);
}
static void append_ts(DBusMessageIter *iter, void *user_data)
{
GSList *list = user_data;
while (list) {
char *timeserver = list->data;
if (timeserver)
dbus_message_iter_append_basic(iter, DBUS_TYPE_STRING,
×erver);
list = g_slist_next(list);
}
}
static void append_tsconfig(DBusMessageIter *iter, void *user_data)
{
struct connman_service *service = user_data;
int i;
if (!service->timeservers_config)
return;
for (i = 0; service->timeservers_config[i]; i++) {
dbus_message_iter_append_basic(iter,
DBUS_TYPE_STRING,
&service->timeservers_config[i]);
}
}
static void append_domainconfig(DBusMessageIter *iter, void *user_data)
{
struct connman_service *service = user_data;
int i;
if (!service->domains)
return;
for (i = 0; service->domains[i]; i++)
dbus_message_iter_append_basic(iter,
DBUS_TYPE_STRING, &service->domains[i]);
}
static void append_domain(DBusMessageIter *iter, void *user_data)
{
struct connman_service *service = user_data;
if (!is_connected(service->state) &&
!is_connecting(service->state))
return;
if (service->domains)
append_domainconfig(iter, user_data);
else if (service->domainname)
dbus_message_iter_append_basic(iter,
DBUS_TYPE_STRING, &service->domainname);
}
static void append_proxies(DBusMessageIter *iter, void *user_data)
{
struct connman_service *service = user_data;
int i;
if (!service->proxies)
return;
for (i = 0; service->proxies[i]; i++)
dbus_message_iter_append_basic(iter,
DBUS_TYPE_STRING, &service->proxies[i]);
}
static void append_excludes(DBusMessageIter *iter, void *user_data)
{
struct connman_service *service = user_data;
int i;
if (!service->excludes)
return;
for (i = 0; service->excludes[i]; i++)
dbus_message_iter_append_basic(iter,
DBUS_TYPE_STRING, &service->excludes[i]);
}
static void append_proxy(DBusMessageIter *iter, void *user_data)
{
struct connman_service *service = user_data;
enum connman_service_proxy_method proxy;
const char *pac = NULL;
const char *method = proxymethod2string(
CONNMAN_SERVICE_PROXY_METHOD_DIRECT);
if (!is_connected(service->state))
return;
proxy = connman_service_get_proxy_method(service);
switch (proxy) {
case CONNMAN_SERVICE_PROXY_METHOD_UNKNOWN:
return;
case CONNMAN_SERVICE_PROXY_METHOD_DIRECT:
goto done;
case CONNMAN_SERVICE_PROXY_METHOD_MANUAL:
connman_dbus_dict_append_array(iter, "Servers",
DBUS_TYPE_STRING, append_proxies,
service);
connman_dbus_dict_append_array(iter, "Excludes",
DBUS_TYPE_STRING, append_excludes,
service);
break;
case CONNMAN_SERVICE_PROXY_METHOD_AUTO:
/* Maybe DHCP, or WPAD, has provided an url for a pac file */
if (service->ipconfig_ipv4)
pac = __connman_ipconfig_get_proxy_autoconfig(
service->ipconfig_ipv4);
else if (service->ipconfig_ipv6)
pac = __connman_ipconfig_get_proxy_autoconfig(
service->ipconfig_ipv6);
if (!service->pac && !pac)
goto done;
if (service->pac)
pac = service->pac;
connman_dbus_dict_append_basic(iter, "URL",
DBUS_TYPE_STRING, &pac);
break;
}
method = proxymethod2string(proxy);
done:
connman_dbus_dict_append_basic(iter, "Method",
DBUS_TYPE_STRING, &method);
}
static void append_proxyconfig(DBusMessageIter *iter, void *user_data)
{
struct connman_service *service = user_data;
const char *method;
if (service->proxy_config == CONNMAN_SERVICE_PROXY_METHOD_UNKNOWN)
return;
switch (service->proxy_config) {
case CONNMAN_SERVICE_PROXY_METHOD_UNKNOWN:
return;
case CONNMAN_SERVICE_PROXY_METHOD_DIRECT:
break;
case CONNMAN_SERVICE_PROXY_METHOD_MANUAL:
if (service->proxies)
connman_dbus_dict_append_array(iter, "Servers",
DBUS_TYPE_STRING,
append_proxies, service);
if (service->excludes)
connman_dbus_dict_append_array(iter, "Excludes",
DBUS_TYPE_STRING,
append_excludes, service);
break;
case CONNMAN_SERVICE_PROXY_METHOD_AUTO:
if (service->pac)
connman_dbus_dict_append_basic(iter, "URL",
DBUS_TYPE_STRING, &service->pac);
break;
}
method = proxymethod2string(service->proxy_config);
connman_dbus_dict_append_basic(iter, "Method",
DBUS_TYPE_STRING, &method);
}
static void append_provider(DBusMessageIter *iter, void *user_data)
{
struct connman_service *service = user_data;
if (!is_connected(service->state))
return;
if (service->provider)
__connman_provider_append_properties(service->provider, iter);
}
static void settings_changed(struct connman_service *service,
struct connman_ipconfig *ipconfig)
{
enum connman_ipconfig_type type;
type = __connman_ipconfig_get_config_type(ipconfig);
__connman_notifier_ipconfig_changed(service, ipconfig);
if (!allow_property_changed(service))
return;
if (type == CONNMAN_IPCONFIG_TYPE_IPV4)
connman_dbus_property_changed_dict(service->path,
CONNMAN_SERVICE_INTERFACE, "IPv4",
append_ipv4, service);
else if (type == CONNMAN_IPCONFIG_TYPE_IPV6)
connman_dbus_property_changed_dict(service->path,
CONNMAN_SERVICE_INTERFACE, "IPv6",
append_ipv6, service);
}
static void ipv4_configuration_changed(struct connman_service *service)
{
if (!allow_property_changed(service))
return;
connman_dbus_property_changed_dict(service->path,
CONNMAN_SERVICE_INTERFACE,
"IPv4.Configuration",
append_ipv4config,
service);
}
void __connman_service_notify_ipv4_configuration(
struct connman_service *service)
{
if (!service)
return;
ipv4_configuration_changed(service);
}
static void ipv6_configuration_changed(struct connman_service *service)
{
if (!allow_property_changed(service))
return;
connman_dbus_property_changed_dict(service->path,
CONNMAN_SERVICE_INTERFACE,
"IPv6.Configuration",
append_ipv6config,
service);
}
static void dns_changed(struct connman_service *service)
{
if (!allow_property_changed(service))
return;
connman_dbus_property_changed_array(service->path,
CONNMAN_SERVICE_INTERFACE, "Nameservers",
DBUS_TYPE_STRING, append_dns, service);
}
static void dns_configuration_changed(struct connman_service *service)
{
if (!allow_property_changed(service))
return;
connman_dbus_property_changed_array(service->path,
CONNMAN_SERVICE_INTERFACE,
"Nameservers.Configuration",
DBUS_TYPE_STRING, append_dnsconfig, service);
dns_changed(service);
}
static void domain_changed(struct connman_service *service)
{
if (!allow_property_changed(service))
return;
connman_dbus_property_changed_array(service->path,
CONNMAN_SERVICE_INTERFACE, "Domains",
DBUS_TYPE_STRING, append_domain, service);
}
static void domain_configuration_changed(struct connman_service *service)
{
if (!allow_property_changed(service))
return;
connman_dbus_property_changed_array(service->path,
CONNMAN_SERVICE_INTERFACE,
"Domains.Configuration",
DBUS_TYPE_STRING, append_domainconfig, service);
}
static void proxy_changed(struct connman_service *service)
{
if (!allow_property_changed(service))
return;
connman_dbus_property_changed_dict(service->path,
CONNMAN_SERVICE_INTERFACE, "Proxy",
append_proxy, service);
}
static void proxy_configuration_changed(struct connman_service *service)
{
if (!allow_property_changed(service))
return;
connman_dbus_property_changed_dict(service->path,
CONNMAN_SERVICE_INTERFACE, "Proxy.Configuration",
append_proxyconfig, service);
proxy_changed(service);
}
static void mdns_changed(struct connman_service *service)
{
dbus_bool_t mdns = service->mdns;
if (!allow_property_changed(service))
return;
connman_dbus_property_changed_basic(service->path,
CONNMAN_SERVICE_INTERFACE, "mDNS", DBUS_TYPE_BOOLEAN,
&mdns);
}
static void mdns_configuration_changed(struct connman_service *service)
{
dbus_bool_t mdns_config = service->mdns_config;
if (!allow_property_changed(service))
return;
connman_dbus_property_changed_basic(service->path,
CONNMAN_SERVICE_INTERFACE, "mDNS.Configuration",
DBUS_TYPE_BOOLEAN, &mdns_config);
}
static int set_mdns(struct connman_service *service,
bool enabled)
{
int result;
result = __connman_resolver_set_mdns(
__connman_service_get_index(service), enabled);
if (result == 0) {
if (service->mdns != enabled) {
service->mdns = enabled;
mdns_changed(service);
}
}
return result;
}
static void timeservers_configuration_changed(struct connman_service *service)
{
if (!allow_property_changed(service))
return;
connman_dbus_property_changed_array(service->path,
CONNMAN_SERVICE_INTERFACE,
"Timeservers.Configuration",
DBUS_TYPE_STRING,
append_tsconfig, service);
}
static void link_changed(struct connman_service *service)
{
if (!allow_property_changed(service))
return;
connman_dbus_property_changed_dict(service->path,
CONNMAN_SERVICE_INTERFACE, "Ethernet",
append_ethernet, service);
}
static void stats_append_counters(DBusMessageIter *dict,
struct connman_stats_data *stats,
struct connman_stats_data *counters,
bool append_all)
{
if (counters->rx_packets != stats->rx_packets || append_all) {
counters->rx_packets = stats->rx_packets;
connman_dbus_dict_append_basic(dict, "RX.Packets",
DBUS_TYPE_UINT32, &stats->rx_packets);
}
if (counters->tx_packets != stats->tx_packets || append_all) {
counters->tx_packets = stats->tx_packets;
connman_dbus_dict_append_basic(dict, "TX.Packets",
DBUS_TYPE_UINT32, &stats->tx_packets);
}
if (counters->rx_bytes != stats->rx_bytes || append_all) {
counters->rx_bytes = stats->rx_bytes;
connman_dbus_dict_append_basic(dict, "RX.Bytes",
DBUS_TYPE_UINT32, &stats->rx_bytes);
}
if (counters->tx_bytes != stats->tx_bytes || append_all) {
counters->tx_bytes = stats->tx_bytes;
connman_dbus_dict_append_basic(dict, "TX.Bytes",
DBUS_TYPE_UINT32, &stats->tx_bytes);
}
if (counters->rx_errors != stats->rx_errors || append_all) {
counters->rx_errors = stats->rx_errors;
connman_dbus_dict_append_basic(dict, "RX.Errors",
DBUS_TYPE_UINT32, &stats->rx_errors);
}
if (counters->tx_errors != stats->tx_errors || append_all) {
counters->tx_errors = stats->tx_errors;
connman_dbus_dict_append_basic(dict, "TX.Errors",
DBUS_TYPE_UINT32, &stats->tx_errors);
}
if (counters->rx_dropped != stats->rx_dropped || append_all) {
counters->rx_dropped = stats->rx_dropped;
connman_dbus_dict_append_basic(dict, "RX.Dropped",
DBUS_TYPE_UINT32, &stats->rx_dropped);
}
if (counters->tx_dropped != stats->tx_dropped || append_all) {
counters->tx_dropped = stats->tx_dropped;
connman_dbus_dict_append_basic(dict, "TX.Dropped",
DBUS_TYPE_UINT32, &stats->tx_dropped);
}
if (counters->time != stats->time || append_all) {
counters->time = stats->time;
connman_dbus_dict_append_basic(dict, "Time",
DBUS_TYPE_UINT32, &stats->time);
}
}
static void stats_append(struct connman_service *service,
const char *counter,
struct connman_stats_counter *counters,
bool append_all)
{
DBusMessageIter array, dict;
DBusMessage *msg;
DBG("service %p counter %s", service, counter);
msg = dbus_message_new(DBUS_MESSAGE_TYPE_METHOD_CALL);
if (!msg)
return;
dbus_message_append_args(msg, DBUS_TYPE_OBJECT_PATH,
&service->path, DBUS_TYPE_INVALID);
dbus_message_iter_init_append(msg, &array);
/* home counter */
connman_dbus_dict_open(&array, &dict);
stats_append_counters(&dict, &service->stats.data,
&counters->stats.data, append_all);
connman_dbus_dict_close(&array, &dict);
/* roaming counter */
connman_dbus_dict_open(&array, &dict);
stats_append_counters(&dict, &service->stats_roaming.data,
&counters->stats_roaming.data, append_all);
connman_dbus_dict_close(&array, &dict);
__connman_counter_send_usage(counter, msg);
}
static void stats_update(struct connman_service *service,
unsigned int rx_packets, unsigned int tx_packets,
unsigned int rx_bytes, unsigned int tx_bytes,
unsigned int rx_errors, unsigned int tx_errors,
unsigned int rx_dropped, unsigned int tx_dropped)
{
struct connman_stats *stats = stats_get(service);
struct connman_stats_data *data_last = &stats->data_last;
struct connman_stats_data *data = &stats->data;
unsigned int seconds;
DBG("service %p", service);
if (stats->valid) {
data->rx_packets +=
rx_packets - data_last->rx_packets;
data->tx_packets +=
tx_packets - data_last->tx_packets;
data->rx_bytes +=
rx_bytes - data_last->rx_bytes;
data->tx_bytes +=
tx_bytes - data_last->tx_bytes;
data->rx_errors +=
rx_errors - data_last->rx_errors;
data->tx_errors +=
tx_errors - data_last->tx_errors;
data->rx_dropped +=
rx_dropped - data_last->rx_dropped;
data->tx_dropped +=
tx_dropped - data_last->tx_dropped;
} else {
stats->valid = true;
}
data_last->rx_packets = rx_packets;
data_last->tx_packets = tx_packets;
data_last->rx_bytes = rx_bytes;
data_last->tx_bytes = tx_bytes;
data_last->rx_errors = rx_errors;
data_last->tx_errors = tx_errors;
data_last->rx_dropped = rx_dropped;
data_last->tx_dropped = tx_dropped;
seconds = g_timer_elapsed(stats->timer, NULL);
stats->data.time = stats->data_last.time + seconds;
}
void __connman_service_notify(struct connman_service *service,
unsigned int rx_packets, unsigned int tx_packets,
unsigned int rx_bytes, unsigned int tx_bytes,
unsigned int rx_errors, unsigned int tx_errors,
unsigned int rx_dropped, unsigned int tx_dropped)
{
GHashTableIter iter;
gpointer key, value;
const char *counter;
struct connman_stats_counter *counters;
struct connman_stats_data *data;
int err;
if (!service)
return;
if (!is_connected(service->state))
return;
stats_update(service,
rx_packets, tx_packets,
rx_bytes, tx_bytes,
rx_errors, tx_errors,
rx_dropped, tx_dropped);
data = &stats_get(service)->data;
err = __connman_stats_update(service, service->roaming, data);
if (err < 0)
connman_error("Failed to store statistics for %s",
service->identifier);
g_hash_table_iter_init(&iter, service->counter_table);
while (g_hash_table_iter_next(&iter, &key, &value)) {
counter = key;
counters = value;
stats_append(service, counter, counters, counters->append_all);
counters->append_all = false;
}
}
int __connman_service_counter_register(const char *counter)
{
struct connman_service *service;
GList *list;
struct connman_stats_counter *counters;
DBG("counter %s", counter);
counter_list = g_slist_prepend(counter_list, (gpointer)counter);
for (list = service_list; list; list = list->next) {
service = list->data;
counters = g_try_new0(struct connman_stats_counter, 1);
if (!counters)
return -ENOMEM;
counters->append_all = true;
g_hash_table_replace(service->counter_table, (gpointer)counter,
counters);
}
return 0;
}
void __connman_service_counter_unregister(const char *counter)
{
struct connman_service *service;
GList *list;
DBG("counter %s", counter);
for (list = service_list; list; list = list->next) {
service = list->data;
g_hash_table_remove(service->counter_table, counter);
}
counter_list = g_slist_remove(counter_list, counter);
}
int __connman_service_iterate_services(service_iterate_cb cb, void *user_data)
{
GList *list;
for (list = service_list; list; list = list->next) {
struct connman_service *service = list->data;
cb(service, user_data);
}
return 0;
}
static void append_properties(DBusMessageIter *dict, dbus_bool_t limited,
struct connman_service *service)
{
dbus_bool_t val;
const char *str;
GSList *list;
str = __connman_service_type2string(service->type);
if (str)
connman_dbus_dict_append_basic(dict, "Type",
DBUS_TYPE_STRING, &str);
connman_dbus_dict_append_array(dict, "Security",
DBUS_TYPE_STRING, append_security, service);
str = state2string(service->state);
if (str)
connman_dbus_dict_append_basic(dict, "State",
DBUS_TYPE_STRING, &str);
str = error2string(service->error);
if (str)
connman_dbus_dict_append_basic(dict, "Error",
DBUS_TYPE_STRING, &str);
if (service->strength > 0)
connman_dbus_dict_append_basic(dict, "Strength",
DBUS_TYPE_BYTE, &service->strength);
val = service->favorite;
connman_dbus_dict_append_basic(dict, "Favorite",
DBUS_TYPE_BOOLEAN, &val);
val = service->immutable;
connman_dbus_dict_append_basic(dict, "Immutable",
DBUS_TYPE_BOOLEAN, &val);
if (service->favorite)
val = service->autoconnect;
else
val = service->favorite;
connman_dbus_dict_append_basic(dict, "AutoConnect",
DBUS_TYPE_BOOLEAN, &val);
if (service->name)
connman_dbus_dict_append_basic(dict, "Name",
DBUS_TYPE_STRING, &service->name);
switch (service->type) {
case CONNMAN_SERVICE_TYPE_UNKNOWN:
case CONNMAN_SERVICE_TYPE_SYSTEM:
case CONNMAN_SERVICE_TYPE_GPS:
case CONNMAN_SERVICE_TYPE_VPN:
case CONNMAN_SERVICE_TYPE_P2P:
break;
case CONNMAN_SERVICE_TYPE_CELLULAR:
val = service->roaming;
connman_dbus_dict_append_basic(dict, "Roaming",
DBUS_TYPE_BOOLEAN, &val);
connman_dbus_dict_append_dict(dict, "Ethernet",
append_ethernet, service);
break;
case CONNMAN_SERVICE_TYPE_WIFI:
{
const unsigned char *bssid = connman_network_get_blob(service->network, "WiFi.BSSID", NULL);
uint16_t frequency = connman_network_get_frequency(service->network);
char* bssidString = g_strdup_printf("%02x:%02x:%02x:%02x:%02x:%02x", bssid[0], bssid[1], bssid[2], bssid[3], bssid[4], bssid[5]);
connman_dbus_dict_append_basic(dict, "BSSID", DBUS_TYPE_STRING, &bssidString);
connman_dbus_dict_append_basic(dict, "Frequency", DBUS_TYPE_UINT16, &frequency);
g_free(bssidString);
}
/* fall through ... */
case CONNMAN_SERVICE_TYPE_ETHERNET:
case CONNMAN_SERVICE_TYPE_BLUETOOTH:
case CONNMAN_SERVICE_TYPE_GADGET:
connman_dbus_dict_append_dict(dict, "Ethernet",
append_ethernet, service);
break;
}
connman_dbus_dict_append_dict(dict, "IPv4", append_ipv4, service);
connman_dbus_dict_append_dict(dict, "IPv4.Configuration",
append_ipv4config, service);
connman_dbus_dict_append_dict(dict, "IPv6", append_ipv6, service);
connman_dbus_dict_append_dict(dict, "IPv6.Configuration",
append_ipv6config, service);
connman_dbus_dict_append_array(dict, "Nameservers",
DBUS_TYPE_STRING, append_dns, service);
connman_dbus_dict_append_array(dict, "Nameservers.Configuration",
DBUS_TYPE_STRING, append_dnsconfig, service);
if (service->state == CONNMAN_SERVICE_STATE_READY ||
service->state == CONNMAN_SERVICE_STATE_ONLINE)
list = __connman_timeserver_get_all(service);
else
list = NULL;
connman_dbus_dict_append_array(dict, "Timeservers",
DBUS_TYPE_STRING, append_ts, list);
g_slist_free_full(list, g_free);
connman_dbus_dict_append_array(dict, "Timeservers.Configuration",
DBUS_TYPE_STRING, append_tsconfig, service);
connman_dbus_dict_append_array(dict, "Domains",
DBUS_TYPE_STRING, append_domain, service);
connman_dbus_dict_append_array(dict, "Domains.Configuration",
DBUS_TYPE_STRING, append_domainconfig, service);
connman_dbus_dict_append_dict(dict, "Proxy", append_proxy, service);
connman_dbus_dict_append_dict(dict, "Proxy.Configuration",
append_proxyconfig, service);
val = service->mdns;
connman_dbus_dict_append_basic(dict, "mDNS", DBUS_TYPE_BOOLEAN,
&val);
val = service->mdns_config;
connman_dbus_dict_append_basic(dict, "mDNS.Configuration",
DBUS_TYPE_BOOLEAN, &val);
connman_dbus_dict_append_dict(dict, "Provider",
append_provider, service);
}
static void append_struct_service(DBusMessageIter *iter,
connman_dbus_append_cb_t function,
struct connman_service *service)
{
DBusMessageIter entry, dict;
dbus_message_iter_open_container(iter, DBUS_TYPE_STRUCT, NULL, &entry);
dbus_message_iter_append_basic(&entry, DBUS_TYPE_OBJECT_PATH,
&service->path);
connman_dbus_dict_open(&entry, &dict);
if (function)
function(&dict, service);
connman_dbus_dict_close(&entry, &dict);
dbus_message_iter_close_container(iter, &entry);
}
static void append_dict_properties(DBusMessageIter *dict, void *user_data)
{
struct connman_service *service = user_data;
append_properties(dict, TRUE, service);
}
static void append_struct(gpointer value, gpointer user_data)
{
struct connman_service *service = value;
DBusMessageIter *iter = user_data;
if (!service->path)
return;
append_struct_service(iter, append_dict_properties, service);
}
void __connman_service_list_struct(DBusMessageIter *iter)
{
g_list_foreach(service_list, append_struct, iter);
}
bool __connman_service_is_hidden(struct connman_service *service)
{
return service->hidden;
}
bool
__connman_service_is_split_routing(struct connman_service *service)
{
return service->do_split_routing;
}
bool __connman_service_index_is_split_routing(int index)
{
struct connman_service *service;
if (index < 0)
return false;
service = __connman_service_lookup_from_index(index);
if (!service)
return false;
return __connman_service_is_split_routing(service);
}
int __connman_service_get_index(struct connman_service *service)
{
if (!service)
return -1;
if (service->network)
return connman_network_get_index(service->network);
else if (service->provider)
return connman_provider_get_index(service->provider);
return -1;
}
void __connman_service_set_hidden(struct connman_service *service)
{
if (!service || service->hidden)
return;
service->hidden_service = true;
}
void __connman_service_set_hostname(struct connman_service *service,
const char *hostname)
{
if (!service || service->hidden)
return;
g_free(service->hostname);
service->hostname = g_strdup(hostname);
}
const char *__connman_service_get_hostname(struct connman_service *service)
{
if (!service)
return NULL;
return service->hostname;
}
void __connman_service_set_domainname(struct connman_service *service,
const char *domainname)
{
if (!service || service->hidden)
return;
g_free(service->domainname);
service->domainname = g_strdup(domainname);
domain_changed(service);
}
const char *connman_service_get_domainname(struct connman_service *service)
{
if (!service)
return NULL;
if (service->domains)
return service->domains[0];
else
return service->domainname;
}
char **connman_service_get_nameservers(struct connman_service *service)
{
if (!service)
return NULL;
if (service->nameservers_config)
return g_strdupv(service->nameservers_config);
else if (service->nameservers ||
service->nameservers_auto) {
int len = 0, len_auto = 0, i;
char **nameservers;
if (service->nameservers)
len = g_strv_length(service->nameservers);
if (service->nameservers_auto)
len_auto = g_strv_length(service->nameservers_auto);
nameservers = g_try_new0(char *, len + len_auto + 1);
if (!nameservers)
return NULL;
for (i = 0; i < len; i++)
nameservers[i] = g_strdup(service->nameservers[i]);
for (i = 0; i < len_auto; i++)
nameservers[i + len] =
g_strdup(service->nameservers_auto[i]);
return nameservers;
}
return g_strdupv(connman_setting_get_string_list("FallbackNameservers"));
}
char **connman_service_get_timeservers_config(struct connman_service *service)
{
if (!service)
return NULL;
return service->timeservers_config;
}
char **connman_service_get_timeservers(struct connman_service *service)
{
if (!service)
return NULL;
return service->timeservers;
}
void connman_service_set_proxy_method(struct connman_service *service,
enum connman_service_proxy_method method)
{
if (!service || service->hidden)
return;
service->proxy = method;
proxy_changed(service);
if (method != CONNMAN_SERVICE_PROXY_METHOD_AUTO)
__connman_notifier_proxy_changed(service);
}
enum connman_service_proxy_method connman_service_get_proxy_method(
struct connman_service *service)
{
if (!service)
return CONNMAN_SERVICE_PROXY_METHOD_UNKNOWN;
if (service->proxy_config != CONNMAN_SERVICE_PROXY_METHOD_UNKNOWN) {
if (service->proxy_config == CONNMAN_SERVICE_PROXY_METHOD_AUTO &&
!service->pac)
return service->proxy;
return service->proxy_config;
}
return service->proxy;
}
char **connman_service_get_proxy_servers(struct connman_service *service)
{
return g_strdupv(service->proxies);
}
char **connman_service_get_proxy_excludes(struct connman_service *service)
{
return g_strdupv(service->excludes);
}
const char *connman_service_get_proxy_url(struct connman_service *service)
{
if (!service)
return NULL;
return service->pac;
}
void __connman_service_set_proxy_autoconfig(struct connman_service *service,
const char *url)
{
if (!service || service->hidden)
return;
service->proxy = CONNMAN_SERVICE_PROXY_METHOD_AUTO;
if (service->ipconfig_ipv4) {
if (__connman_ipconfig_set_proxy_autoconfig(
service->ipconfig_ipv4, url) < 0)
return;
} else if (service->ipconfig_ipv6) {
if (__connman_ipconfig_set_proxy_autoconfig(
service->ipconfig_ipv6, url) < 0)
return;
} else
return;
proxy_changed(service);
__connman_notifier_proxy_changed(service);
}
const char *connman_service_get_proxy_autoconfig(struct connman_service *service)
{
if (!service)
return NULL;
if (service->ipconfig_ipv4)
return __connman_ipconfig_get_proxy_autoconfig(
service->ipconfig_ipv4);
else if (service->ipconfig_ipv6)
return __connman_ipconfig_get_proxy_autoconfig(
service->ipconfig_ipv6);
return NULL;
}
void __connman_service_set_timeservers(struct connman_service *service,
char **timeservers)
{
int i;
if (!service)
return;
g_strfreev(service->timeservers);
service->timeservers = NULL;
for (i = 0; timeservers && timeservers[i]; i++)
__connman_service_timeserver_append(service, timeservers[i]);
}
int __connman_service_timeserver_append(struct connman_service *service,
const char *timeserver)
{
int len;
DBG("service %p timeserver %s", service, timeserver);
if (!timeserver)
return -EINVAL;
if (service->timeservers) {
int i;
for (i = 0; service->timeservers[i]; i++)
if (g_strcmp0(service->timeservers[i], timeserver) == 0)
return -EEXIST;
len = g_strv_length(service->timeservers);
service->timeservers = g_try_renew(char *, service->timeservers,
len + 2);
} else {
len = 0;
service->timeservers = g_try_new0(char *, len + 2);
}
if (!service->timeservers)
return -ENOMEM;
service->timeservers[len] = g_strdup(timeserver);
service->timeservers[len + 1] = NULL;
return 0;
}
int __connman_service_timeserver_remove(struct connman_service *service,
const char *timeserver)
{
char **servers;
int len, i, j, found = 0;
DBG("service %p timeserver %s", service, timeserver);
if (!timeserver)
return -EINVAL;
if (!service->timeservers)
return 0;
for (i = 0; service->timeservers &&
service->timeservers[i]; i++)
if (g_strcmp0(service->timeservers[i], timeserver) == 0) {
found = 1;
break;
}
if (found == 0)
return 0;
len = g_strv_length(service->timeservers);
if (len == 1) {
g_strfreev(service->timeservers);
service->timeservers = NULL;
return 0;
}
servers = g_try_new0(char *, len);
if (!servers)
return -ENOMEM;
for (i = 0, j = 0; i < len; i++) {
if (g_strcmp0(service->timeservers[i], timeserver) != 0) {
servers[j] = g_strdup(service->timeservers[i]);
if (!servers[j])
return -ENOMEM;
j++;
}
}
servers[len - 1] = NULL;
g_strfreev(service->timeservers);
service->timeservers = servers;
return 0;
}
void __connman_service_timeserver_changed(struct connman_service *service,
GSList *ts_list)
{
if (!service)
return;
if (!allow_property_changed(service))
return;
connman_dbus_property_changed_array(service->path,
CONNMAN_SERVICE_INTERFACE, "Timeservers",
DBUS_TYPE_STRING, append_ts, ts_list);
}
void __connman_service_set_pac(struct connman_service *service,
const char *pac)
{
if (service->hidden)
return;
g_free(service->pac);
service->pac = g_strdup(pac);
proxy_changed(service);
}
void __connman_service_set_identity(struct connman_service *service,
const char *identity)
{
if (service->immutable || service->hidden)
return;
g_free(service->identity);
service->identity = g_strdup(identity);
if (service->network)
connman_network_set_string(service->network,
"WiFi.Identity",
service->identity);
}
void __connman_service_set_anonymous_identity(struct connman_service *service,
const char *anonymous_identity)
{
if (service->immutable || service->hidden)
return;
g_free(service->anonymous_identity);
service->anonymous_identity = g_strdup(anonymous_identity);
if (service->network)
connman_network_set_string(service->network,
"WiFi.AnonymousIdentity",
service->anonymous_identity);
}
void __connman_service_set_subject_match(struct connman_service *service,
const char *subject_match)
{
if (service->immutable || service->hidden)
return;
g_free(service->subject_match);
service->subject_match = g_strdup(subject_match);
if (service->network)
connman_network_set_string(service->network,
"WiFi.SubjectMatch",
service->subject_match);
}
void __connman_service_set_altsubject_match(struct connman_service *service,
const char *altsubject_match)
{
if (service->immutable || service->hidden)
return;
g_free(service->altsubject_match);
service->altsubject_match = g_strdup(altsubject_match);
if (service->network)
connman_network_set_string(service->network,
"WiFi.AltSubjectMatch",
service->altsubject_match);
}
void __connman_service_set_domain_suffix_match(struct connman_service *service,
const char *domain_suffix_match)
{
if (service->immutable || service->hidden)
return;
g_free(service->domain_suffix_match);
service->domain_suffix_match = g_strdup(domain_suffix_match);
if (service->network)
connman_network_set_string(service->network,
"WiFi.DomainSuffixMatch",
service->domain_suffix_match);
}
void __connman_service_set_domain_match(struct connman_service *service,
const char *domain_match)
{
if (service->immutable || service->hidden)
return;
g_free(service->domain_match);
service->domain_match = g_strdup(domain_match);
if (service->network)
connman_network_set_string(service->network,
"WiFi.DomainMatch",
service->domain_match);
}
void __connman_service_set_agent_identity(struct connman_service *service,
const char *agent_identity)
{
if (service->hidden)
return;
g_free(service->agent_identity);
service->agent_identity = g_strdup(agent_identity);
if (service->network)
connman_network_set_string(service->network,
"WiFi.AgentIdentity",
service->agent_identity);
}
int __connman_service_check_passphrase(enum connman_service_security security,
const char *passphrase)
{
guint i;
gsize length;
if (!passphrase)
return 0;
length = strlen(passphrase);
switch (security) {
case CONNMAN_SERVICE_SECURITY_UNKNOWN:
case CONNMAN_SERVICE_SECURITY_NONE:
case CONNMAN_SERVICE_SECURITY_WPA:
case CONNMAN_SERVICE_SECURITY_RSN:
DBG("service security '%s' (%d) not handled",
security2string(security), security);
return -EOPNOTSUPP;
case CONNMAN_SERVICE_SECURITY_PSK:
/* A raw key is always 64 bytes length,
* its content is in hex representation.
* A PSK key must be between [8..63].
*/
if (length == 64) {
for (i = 0; i < 64; i++)
if (!isxdigit((unsigned char)
passphrase[i]))
return -ENOKEY;
} else if (length < 8 || length > 63)
return -ENOKEY;
break;
case CONNMAN_SERVICE_SECURITY_WEP:
/* length of WEP key is 10 or 26
* length of WEP passphrase is 5 or 13
*/
if (length == 10 || length == 26) {
for (i = 0; i < length; i++)
if (!isxdigit((unsigned char)
passphrase[i]))
return -ENOKEY;
} else if (length != 5 && length != 13)
return -ENOKEY;
break;
case CONNMAN_SERVICE_SECURITY_8021X:
break;
}
return 0;
}
int __connman_service_set_passphrase(struct connman_service *service,
const char *passphrase)
{
int err;
if (service->hidden)
return -EINVAL;
if (service->immutable &&
service->security != CONNMAN_SERVICE_SECURITY_8021X)
return -EINVAL;
err = __connman_service_check_passphrase(service->security, passphrase);
if (err < 0)
return err;
g_free(service->passphrase);
service->passphrase = g_strdup(passphrase);
if (service->network)
connman_network_set_string(service->network, "WiFi.Passphrase",
service->passphrase);
return 0;
}
const char *__connman_service_get_passphrase(struct connman_service *service)
{
if (!service)
return NULL;
return service->passphrase;
}
static DBusMessage *get_properties(DBusConnection *conn,
DBusMessage *msg, void *user_data)
{
struct connman_service *service = user_data;
DBusMessage *reply;
DBusMessageIter array, dict;
reply = dbus_message_new_method_return(msg);
if (!reply)
return NULL;
dbus_message_iter_init_append(reply, &array);
connman_dbus_dict_open(&array, &dict);
append_properties(&dict, FALSE, service);
connman_dbus_dict_close(&array, &dict);
return reply;
}
static char **remove_empty_strings(char **strv)
{
int index = 0;
char **iter = strv;
while (*iter) {
if (**iter)
strv[index++] = *iter;
else
g_free(*iter);
iter++;
}
strv[index] = NULL;
return strv;
}
static int update_proxy_configuration(struct connman_service *service,
DBusMessageIter *array)
{
DBusMessageIter dict;
enum connman_service_proxy_method method;
GString *servers_str = NULL;
GString *excludes_str = NULL;
const char *url = NULL;
method = CONNMAN_SERVICE_PROXY_METHOD_UNKNOWN;
dbus_message_iter_recurse(array, &dict);
while (dbus_message_iter_get_arg_type(&dict) == DBUS_TYPE_DICT_ENTRY) {
DBusMessageIter entry, variant;
const char *key;
int type;
dbus_message_iter_recurse(&dict, &entry);
if (dbus_message_iter_get_arg_type(&entry) != DBUS_TYPE_STRING)
goto error;
dbus_message_iter_get_basic(&entry, &key);
dbus_message_iter_next(&entry);
if (dbus_message_iter_get_arg_type(&entry) != DBUS_TYPE_VARIANT)
goto error;
dbus_message_iter_recurse(&entry, &variant);
type = dbus_message_iter_get_arg_type(&variant);
if (g_str_equal(key, "Method")) {
const char *val;
if (type != DBUS_TYPE_STRING)
goto error;
dbus_message_iter_get_basic(&variant, &val);
method = string2proxymethod(val);
} else if (g_str_equal(key, "URL")) {
if (type != DBUS_TYPE_STRING)
goto error;
dbus_message_iter_get_basic(&variant, &url);
} else if (g_str_equal(key, "Servers")) {
DBusMessageIter str_array;
if (type != DBUS_TYPE_ARRAY)
goto error;
servers_str = g_string_new(NULL);
if (!servers_str)
goto error;
dbus_message_iter_recurse(&variant, &str_array);
while (dbus_message_iter_get_arg_type(&str_array) ==
DBUS_TYPE_STRING) {
char *val = NULL;
dbus_message_iter_get_basic(&str_array, &val);
if (servers_str->len > 0)
g_string_append_printf(servers_str,
" %s", val);
else
g_string_append(servers_str, val);
dbus_message_iter_next(&str_array);
}
} else if (g_str_equal(key, "Excludes")) {
DBusMessageIter str_array;
if (type != DBUS_TYPE_ARRAY)
goto error;
excludes_str = g_string_new(NULL);
if (!excludes_str)
goto error;
dbus_message_iter_recurse(&variant, &str_array);
while (dbus_message_iter_get_arg_type(&str_array) ==
DBUS_TYPE_STRING) {
char *val = NULL;
dbus_message_iter_get_basic(&str_array, &val);
if (excludes_str->len > 0)
g_string_append_printf(excludes_str,
" %s", val);
else
g_string_append(excludes_str, val);
dbus_message_iter_next(&str_array);
}
}
dbus_message_iter_next(&dict);
}
switch (method) {
case CONNMAN_SERVICE_PROXY_METHOD_DIRECT:
break;
case CONNMAN_SERVICE_PROXY_METHOD_MANUAL:
if (!servers_str && !service->proxies)
goto error;
if (servers_str) {
g_strfreev(service->proxies);
if (servers_str->len > 0) {
char **proxies = g_strsplit_set(
servers_str->str, " ", 0);
proxies = remove_empty_strings(proxies);
service->proxies = proxies;
} else
service->proxies = NULL;
}
if (excludes_str) {
g_strfreev(service->excludes);
if (excludes_str->len > 0) {
char **excludes = g_strsplit_set(
excludes_str->str, " ", 0);
excludes = remove_empty_strings(excludes);
service->excludes = excludes;
} else
service->excludes = NULL;
}
if (!service->proxies)
method = CONNMAN_SERVICE_PROXY_METHOD_DIRECT;
break;
case CONNMAN_SERVICE_PROXY_METHOD_AUTO:
g_free(service->pac);
if (url && strlen(url) > 0)
service->pac = g_strstrip(g_strdup(url));
else
service->pac = NULL;
/* if we are connected:
- if service->pac == NULL
- if __connman_ipconfig_get_proxy_autoconfig(
service->ipconfig) == NULL
--> We should start WPAD */
break;
case CONNMAN_SERVICE_PROXY_METHOD_UNKNOWN:
goto error;
}
if (servers_str)
g_string_free(servers_str, TRUE);
if (excludes_str)
g_string_free(excludes_str, TRUE);
service->proxy_config = method;
return 0;
error:
if (servers_str)
g_string_free(servers_str, TRUE);
if (excludes_str)
g_string_free(excludes_str, TRUE);
return -EINVAL;
}
int __connman_service_reset_ipconfig(struct connman_service *service,
enum connman_ipconfig_type type, DBusMessageIter *array,
enum connman_service_state *new_state)
{
struct connman_ipconfig *ipconfig, *new_ipconfig;
enum connman_ipconfig_method old_method, new_method;
enum connman_service_state state;
int err = 0, index, original_index;
if (type == CONNMAN_IPCONFIG_TYPE_IPV4) {
ipconfig = service->ipconfig_ipv4;
state = service->state_ipv4;
new_method = CONNMAN_IPCONFIG_METHOD_DHCP;
} else if (type == CONNMAN_IPCONFIG_TYPE_IPV6) {
ipconfig = service->ipconfig_ipv6;
state = service->state_ipv6;
new_method = CONNMAN_IPCONFIG_METHOD_AUTO;
} else
return -EINVAL;
if (!ipconfig)
return -ENXIO;
old_method = __connman_ipconfig_get_method(ipconfig);
index = __connman_ipconfig_get_index(ipconfig);
original_index = __connman_ipconfig_get_original_index(ipconfig);
if (type == CONNMAN_IPCONFIG_TYPE_IPV4)
new_ipconfig = create_ip4config(service, index, original_index,
CONNMAN_IPCONFIG_METHOD_UNKNOWN);
else
new_ipconfig = create_ip6config(service, index, original_index);
if (array) {
err = __connman_ipconfig_set_config(new_ipconfig, array);
if (err < 0) {
__connman_ipconfig_unref(new_ipconfig);
return err;
}
new_method = __connman_ipconfig_get_method(new_ipconfig);
}
if (is_connecting(state) || is_connected(state))
__connman_network_clear_ipconfig(service->network, ipconfig);
__connman_ipconfig_unref(ipconfig);
if (type == CONNMAN_IPCONFIG_TYPE_IPV4)
service->ipconfig_ipv4 = new_ipconfig;
else if (type == CONNMAN_IPCONFIG_TYPE_IPV6)
service->ipconfig_ipv6 = new_ipconfig;
if (is_connecting(state) || is_connected(state))
__connman_ipconfig_enable(new_ipconfig);
if (new_state && new_method != old_method) {
if (type == CONNMAN_IPCONFIG_TYPE_IPV4)
*new_state = service->state_ipv4;
else
*new_state = service->state_ipv6;
settings_changed(service, new_ipconfig);
address_updated(service, new_method);
__connman_service_auto_connect(CONNMAN_SERVICE_CONNECT_REASON_AUTO);
}
DBG("err %d ipconfig %p type %d method %d state %s", err,
new_ipconfig, type, new_method,
!new_state ? "-" : state2string(*new_state));
return err;
}
void __connman_service_wispr_start(struct connman_service *service,
enum connman_ipconfig_type type)
{
DBG("service %p type %s", service, __connman_ipconfig_type2string(type));
if (type == CONNMAN_IPCONFIG_TYPE_IPV4)
service->online_check_count_ipv4 = 1;
else
service->online_check_count_ipv6 = 1;
__connman_wispr_start(service, type);
}
static DBusMessage *set_property(DBusConnection *conn,
DBusMessage *msg, void *user_data)
{
struct connman_service *service = user_data;
DBusMessageIter iter, value;
const char *name;
int type;
DBG("service %p", service);
if (!dbus_message_iter_init(msg, &iter))
return __connman_error_invalid_arguments(msg);
if (dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_STRING)
return __connman_error_invalid_arguments(msg);
dbus_message_iter_get_basic(&iter, &name);
dbus_message_iter_next(&iter);
if (dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)
return __connman_error_invalid_arguments(msg);
dbus_message_iter_recurse(&iter, &value);
type = dbus_message_iter_get_arg_type(&value);
if (g_str_equal(name, "AutoConnect")) {
dbus_bool_t autoconnect;
if (type != DBUS_TYPE_BOOLEAN)
return __connman_error_invalid_arguments(msg);
if (!service->favorite)
return __connman_error_invalid_service(msg);
dbus_message_iter_get_basic(&value, &autoconnect);
if (service->autoconnect == autoconnect)
return g_dbus_create_reply(msg, DBUS_TYPE_INVALID);
service->autoconnect = autoconnect;
autoconnect_changed(service);
if (autoconnect)
__connman_service_auto_connect(CONNMAN_SERVICE_CONNECT_REASON_AUTO);
service_save(service);
} else if (g_str_equal(name, "Nameservers.Configuration")) {
DBusMessageIter entry;
GString *str;
int index;
const char *gw;
if (__connman_provider_is_immutable(service->provider) ||
service->immutable)
return __connman_error_not_supported(msg);
if (type != DBUS_TYPE_ARRAY)
return __connman_error_invalid_arguments(msg);
str = g_string_new(NULL);
if (!str)
return __connman_error_invalid_arguments(msg);
index = __connman_service_get_index(service);
gw = __connman_ipconfig_get_gateway_from_index(index,
CONNMAN_IPCONFIG_TYPE_ALL);
if (gw && strlen(gw))
__connman_service_nameserver_del_routes(service,
CONNMAN_IPCONFIG_TYPE_ALL);
dbus_message_iter_recurse(&value, &entry);
while (dbus_message_iter_get_arg_type(&entry) == DBUS_TYPE_STRING) {
const char *val;
dbus_message_iter_get_basic(&entry, &val);
dbus_message_iter_next(&entry);
if (!val[0])
continue;
if (str->len > 0)
g_string_append_printf(str, " %s", val);
else
g_string_append(str, val);
}
nameserver_remove_all(service, CONNMAN_IPCONFIG_TYPE_ALL);
g_strfreev(service->nameservers_config);
if (str->len > 0) {
char **nameservers, **iter;
nameservers = g_strsplit_set(str->str, " ", 0);
for (iter = nameservers; *iter; iter++)
if (connman_inet_check_ipaddress(*iter) <= 0)
*iter[0] = '\0';
nameservers = remove_empty_strings(nameservers);
service->nameservers_config = nameservers;
} else {
service->nameservers_config = NULL;
}
g_string_free(str, TRUE);
if (gw && strlen(gw))
__connman_service_nameserver_add_routes(service, gw);
nameserver_add_all(service, CONNMAN_IPCONFIG_TYPE_ALL);
dns_configuration_changed(service);
if (__connman_service_is_connected_state(service,
CONNMAN_IPCONFIG_TYPE_IPV4))
__connman_service_wispr_start(service, CONNMAN_IPCONFIG_TYPE_IPV4);
if (__connman_service_is_connected_state(service,
CONNMAN_IPCONFIG_TYPE_IPV6))
__connman_service_wispr_start(service, CONNMAN_IPCONFIG_TYPE_IPV6);
service_save(service);
} else if (g_str_equal(name, "Timeservers.Configuration")) {
DBusMessageIter entry;
GString *str;
if (service->immutable)
return __connman_error_not_supported(msg);
if (type != DBUS_TYPE_ARRAY)
return __connman_error_invalid_arguments(msg);
str = g_string_new(NULL);
if (!str)
return __connman_error_invalid_arguments(msg);
dbus_message_iter_recurse(&value, &entry);
while (dbus_message_iter_get_arg_type(&entry) == DBUS_TYPE_STRING) {
const char *val;
dbus_message_iter_get_basic(&entry, &val);
dbus_message_iter_next(&entry);
if (!val[0])
continue;
if (str->len > 0)
g_string_append_printf(str, " %s", val);
else
g_string_append(str, val);
}
g_strfreev(service->timeservers_config);
service->timeservers_config = NULL;
if (str->len > 0) {
char **timeservers = g_strsplit_set(str->str, " ", 0);
timeservers = remove_empty_strings(timeservers);
service->timeservers_config = timeservers;
}
g_string_free(str, TRUE);
service_save(service);
timeservers_configuration_changed(service);
if (service == __connman_service_get_default())
__connman_timeserver_sync(service);
} else if (g_str_equal(name, "Domains.Configuration")) {
DBusMessageIter entry;
GString *str;
if (service->immutable)
return __connman_error_not_supported(msg);
if (type != DBUS_TYPE_ARRAY)
return __connman_error_invalid_arguments(msg);
str = g_string_new(NULL);
if (!str)
return __connman_error_invalid_arguments(msg);
dbus_message_iter_recurse(&value, &entry);
while (dbus_message_iter_get_arg_type(&entry) == DBUS_TYPE_STRING) {
const char *val;
dbus_message_iter_get_basic(&entry, &val);
dbus_message_iter_next(&entry);
if (!val[0])
continue;
if (str->len > 0)
g_string_append_printf(str, " %s", val);
else
g_string_append(str, val);
}
searchdomain_remove_all(service);
g_strfreev(service->domains);
if (str->len > 0) {
char **domains = g_strsplit_set(str->str, " ", 0);
domains = remove_empty_strings(domains);
service->domains = domains;
} else
service->domains = NULL;
g_string_free(str, TRUE);
searchdomain_add_all(service);
domain_configuration_changed(service);
domain_changed(service);
service_save(service);
} else if (g_str_equal(name, "Proxy.Configuration")) {
int err;
if (service->immutable)
return __connman_error_not_supported(msg);
if (type != DBUS_TYPE_ARRAY)
return __connman_error_invalid_arguments(msg);
err = update_proxy_configuration(service, &value);
if (err < 0)
return __connman_error_failed(msg, -err);
proxy_configuration_changed(service);
__connman_notifier_proxy_changed(service);
service_save(service);
} else if (g_str_equal(name, "mDNS.Configuration")) {
dbus_bool_t val;
if (service->immutable)
return __connman_error_not_supported(msg);
if (type != DBUS_TYPE_BOOLEAN)
return __connman_error_invalid_arguments(msg);
dbus_message_iter_get_basic(&value, &val);
service->mdns_config = val;
mdns_configuration_changed(service);
set_mdns(service, service->mdns_config);
service_save(service);
} else if (g_str_equal(name, "IPv4.Configuration") ||
g_str_equal(name, "IPv6.Configuration")) {
enum connman_service_state state =
CONNMAN_SERVICE_STATE_UNKNOWN;
enum connman_ipconfig_type type =
CONNMAN_IPCONFIG_TYPE_UNKNOWN;
int err = 0;
if (service->type == CONNMAN_SERVICE_TYPE_VPN ||
service->immutable)
return __connman_error_not_supported(msg);
DBG("%s", name);
if (!service->ipconfig_ipv4 &&
!service->ipconfig_ipv6)
return __connman_error_invalid_property(msg);
if (g_str_equal(name, "IPv4.Configuration"))
type = CONNMAN_IPCONFIG_TYPE_IPV4;
else
type = CONNMAN_IPCONFIG_TYPE_IPV6;
err = __connman_service_reset_ipconfig(service, type, &value,
&state);
if (err < 0) {
if (is_connected(state) || is_connecting(state)) {
if (type == CONNMAN_IPCONFIG_TYPE_IPV4)
__connman_network_enable_ipconfig(service->network,
service->ipconfig_ipv4);
else
__connman_network_enable_ipconfig(service->network,
service->ipconfig_ipv6);
}
return __connman_error_failed(msg, -err);
}
if (type == CONNMAN_IPCONFIG_TYPE_IPV4)
ipv4_configuration_changed(service);
else
ipv6_configuration_changed(service);
if (is_connecting(service->state) ||
is_connected(service->state)) {
if (type == CONNMAN_IPCONFIG_TYPE_IPV4)
__connman_network_enable_ipconfig(service->network,
service->ipconfig_ipv4);
else
__connman_network_enable_ipconfig(service->network,
service->ipconfig_ipv6);
}
service_save(service);
} else
return __connman_error_invalid_property(msg);
return g_dbus_create_reply(msg, DBUS_TYPE_INVALID);
}
static void set_error(struct connman_service *service,
enum connman_service_error error)
{
const char *str;
if (service->error == error)
return;
service->error = error;
if (!service->path)
return;
if (!allow_property_changed(service))
return;
str = error2string(service->error);
if (!str)
str = "";
connman_dbus_property_changed_basic(service->path,
CONNMAN_SERVICE_INTERFACE, "Error",
DBUS_TYPE_STRING, &str);
}
static void remove_timeout(struct connman_service *service)
{
if (service->timeout > 0) {
g_source_remove(service->timeout);
service->timeout = 0;
}
}
static void reply_pending(struct connman_service *service, int error)
{
remove_timeout(service);
if (service->pending) {
connman_dbus_reply_pending(service->pending, error, NULL);
service->pending = NULL;
}
if (service->provider_pending) {
connman_dbus_reply_pending(service->provider_pending,
error, service->path);
service->provider_pending = NULL;
}
}
static void service_complete(struct connman_service *service)
{
reply_pending(service, EIO);
if (service->connect_reason != CONNMAN_SERVICE_CONNECT_REASON_USER)
__connman_service_auto_connect(service->connect_reason);
g_get_current_time(&service->modified);
service_save(service);
}
static DBusMessage *clear_property(DBusConnection *conn,
DBusMessage *msg, void *user_data)
{
struct connman_service *service = user_data;
const char *name;
DBG("service %p", service);
dbus_message_get_args(msg, NULL, DBUS_TYPE_STRING, &name,
DBUS_TYPE_INVALID);
if (g_str_equal(name, "Error")) {
set_error(service, CONNMAN_SERVICE_ERROR_UNKNOWN);
__connman_service_clear_error(service);
service_complete(service);
} else
return __connman_error_invalid_property(msg);
return g_dbus_create_reply(msg, DBUS_TYPE_INVALID);
}
static bool is_ipconfig_usable(struct connman_service *service)
{
if (!__connman_ipconfig_is_usable(service->ipconfig_ipv4) &&
!__connman_ipconfig_is_usable(service->ipconfig_ipv6))
return false;
return true;
}
static bool is_ignore(struct connman_service *service)
{
if (!service->autoconnect)
return true;
if (service->roaming &&
!connman_setting_get_bool("AutoConnectRoamingServices"))
return true;
if (service->ignore)
return true;
if (service->state == CONNMAN_SERVICE_STATE_FAILURE)
return true;
if (!is_ipconfig_usable(service))
return true;
return false;
}
static void disconnect_on_last_session(enum connman_service_type type)
{
GList *list;
for (list = service_list; list; list = list->next) {
struct connman_service *service = list->data;
if (service->type != type)
continue;
if (service->connect_reason != CONNMAN_SERVICE_CONNECT_REASON_SESSION)
continue;
__connman_service_disconnect(service);
return;
}
}
static int active_sessions[MAX_CONNMAN_SERVICE_TYPES] = {};
static int always_connect[MAX_CONNMAN_SERVICE_TYPES] = {};
static int active_count = 0;
void __connman_service_set_active_session(bool enable, GSList *list)
{
if (!list)
return;
if (enable)
active_count++;
else
active_count--;
while (list) {
enum connman_service_type type = GPOINTER_TO_INT(list->data);
switch (type) {
case CONNMAN_SERVICE_TYPE_ETHERNET:
case CONNMAN_SERVICE_TYPE_WIFI:
case CONNMAN_SERVICE_TYPE_BLUETOOTH:
case CONNMAN_SERVICE_TYPE_CELLULAR:
case CONNMAN_SERVICE_TYPE_GADGET:
if (enable)
active_sessions[type]++;
else
active_sessions[type]--;
break;
case CONNMAN_SERVICE_TYPE_UNKNOWN:
case CONNMAN_SERVICE_TYPE_SYSTEM:
case CONNMAN_SERVICE_TYPE_GPS:
case CONNMAN_SERVICE_TYPE_VPN:
case CONNMAN_SERVICE_TYPE_P2P:
break;
}
if (active_sessions[type] == 0)
disconnect_on_last_session(type);
list = g_slist_next(list);
}
DBG("eth %d wifi %d bt %d cellular %d gadget %d sessions %d",
active_sessions[CONNMAN_SERVICE_TYPE_ETHERNET],
active_sessions[CONNMAN_SERVICE_TYPE_WIFI],
active_sessions[CONNMAN_SERVICE_TYPE_BLUETOOTH],
active_sessions[CONNMAN_SERVICE_TYPE_CELLULAR],
active_sessions[CONNMAN_SERVICE_TYPE_GADGET],
active_count);
}
struct preferred_tech_data {
GList *preferred_list;
enum connman_service_type type;
};
static void preferred_tech_add_by_type(gpointer data, gpointer user_data)
{
struct connman_service *service = data;
struct preferred_tech_data *tech_data = user_data;
if (service->type == tech_data->type) {
tech_data->preferred_list =
g_list_append(tech_data->preferred_list, service);
DBG("type %d service %p %s", tech_data->type, service,
service->name);
}
}
static GList *preferred_tech_list_get(void)
{
unsigned int *tech_array;
struct preferred_tech_data tech_data = { 0, };
int i;
tech_array = connman_setting_get_uint_list("PreferredTechnologies");
if (!tech_array)
return NULL;
if (connman_setting_get_bool("SingleConnectedTechnology")) {
GList *list;
for (list = service_list; list; list = list->next) {
struct connman_service *service = list->data;
if (!is_connected(service->state))
break;
if (service->connect_reason ==
CONNMAN_SERVICE_CONNECT_REASON_USER) {
DBG("service %p name %s is user connected",
service, service->name);
return NULL;
}
}
}
for (i = 0; tech_array[i] != 0; i += 1) {
tech_data.type = tech_array[i];
g_list_foreach(service_list, preferred_tech_add_by_type,
&tech_data);
}
return tech_data.preferred_list;
}
static void set_always_connecting_technologies()
{
unsigned int *always_connected_techs =
connman_setting_get_uint_list("AlwaysConnectedTechnologies");
int i;
for (i = 0; always_connected_techs && always_connected_techs[i]; i++)
always_connect[always_connected_techs[i]] = 1;
}
static bool autoconnect_no_session_active(struct connman_service *service)
{
/*
* Test active_count to see if there are no sessions set up and
* stop autoconnecting, but continue connecting if the service
* belongs to a technology which should always autoconnect.
*/
if (!active_count && !always_connect[service->type])
return true;
return false;
}
static bool autoconnect_already_connecting(struct connman_service *service,
bool autoconnecting)
{
/*
* If another service is already connecting and this service type has
* not been marked as always connecting, stop the connecting procedure.
*/
if (autoconnecting &&
!active_sessions[service->type] &&
!always_connect[service->type])
return true;
return false;
}
static bool auto_connect_service(GList *services,
enum connman_service_connect_reason reason,
bool preferred)
{
struct connman_service *service = NULL;
bool ignore[MAX_CONNMAN_SERVICE_TYPES] = { };
bool autoconnecting = false;
GList *list;
DBG("preferred %d sessions %d reason %s", preferred, active_count,
reason2string(reason));
ignore[CONNMAN_SERVICE_TYPE_VPN] = true;
for (list = services; list; list = list->next) {
service = list->data;
if (ignore[service->type]) {
DBG("service %p type %s ignore", service,
__connman_service_type2string(service->type));
continue;
}
if (service->pending ||
is_connecting(service->state) ||
is_connected(service->state)) {
if (autoconnect_no_session_active(service))
return true;
ignore[service->type] = true;
autoconnecting = true;
DBG("service %p type %s busy", service,
__connman_service_type2string(service->type));
continue;
}
if (!service->favorite) {
if (preferred)
continue;
return autoconnecting;
}
if (is_ignore(service) || service->state !=
CONNMAN_SERVICE_STATE_IDLE)
continue;
if (autoconnect_already_connecting(service, autoconnecting)) {
DBG("service %p type %s has no users", service,
__connman_service_type2string(service->type));
continue;
}
DBG("service %p %s %s", service, service->name,
(preferred) ? "preferred" : reason2string(reason));
__connman_service_connect(service, reason);
if (autoconnect_no_session_active(service))
return true;
ignore[service->type] = true;
}
return autoconnecting;
}
static gboolean run_auto_connect(gpointer data)
{
enum connman_service_connect_reason reason = GPOINTER_TO_UINT(data);
bool autoconnecting = false;
GList *preferred_tech;
autoconnect_id = 0;
DBG("");
preferred_tech = preferred_tech_list_get();
if (preferred_tech) {
autoconnecting = auto_connect_service(preferred_tech, reason,
true);
g_list_free(preferred_tech);
}
if (!autoconnecting || active_count)
auto_connect_service(service_list, reason, false);
return FALSE;
}
void __connman_service_auto_connect(enum connman_service_connect_reason reason)
{
DBG("");
if (autoconnect_id != 0)
return;
if (!__connman_session_policy_autoconnect(reason))
return;
autoconnect_id = g_idle_add(run_auto_connect,
GUINT_TO_POINTER(reason));
}
static gboolean run_vpn_auto_connect(gpointer data) {
GList *list;
bool need_split = false;
vpn_autoconnect_id = 0;
for (list = service_list; list; list = list->next) {
struct connman_service *service = list->data;
int res;
if (service->type != CONNMAN_SERVICE_TYPE_VPN)
continue;
if (is_connected(service->state) ||
is_connecting(service->state)) {
if (!service->do_split_routing)
need_split = true;
continue;
}
if (is_ignore(service) || !service->favorite)
continue;
if (need_split && !service->do_split_routing) {
DBG("service %p no split routing", service);
continue;
}
DBG("service %p %s %s", service, service->name,
service->do_split_routing ?
"split routing" : "");
res = __connman_service_connect(service,
CONNMAN_SERVICE_CONNECT_REASON_AUTO);
if (res < 0 && res != -EINPROGRESS)
continue;
if (!service->do_split_routing)
need_split = true;
}
return FALSE;
}
static void vpn_auto_connect(void)
{
if (vpn_autoconnect_id)
return;
vpn_autoconnect_id =
g_idle_add(run_vpn_auto_connect, NULL);
}
bool
__connman_service_is_provider_pending(struct connman_service *service)
{
if (!service)
return false;
if (service->provider_pending)
return true;
return false;
}
void __connman_service_set_provider_pending(struct connman_service *service,
DBusMessage *msg)
{
if (service->provider_pending) {
DBG("service %p provider pending msg %p already exists",
service, service->provider_pending);
return;
}
service->provider_pending = msg;
return;
}
static void check_pending_msg(struct connman_service *service)
{
if (!service->pending)
return;
DBG("service %p pending msg %p already exists", service,
service->pending);
dbus_message_unref(service->pending);
}
void __connman_service_set_hidden_data(struct connman_service *service,
gpointer user_data)
{
DBusMessage *pending = user_data;
DBG("service %p pending %p", service, pending);
if (!pending)
return;
check_pending_msg(service);
service->pending = pending;
}
void __connman_service_return_error(struct connman_service *service,
int error, gpointer user_data)
{
DBG("service %p error %d user_data %p", service, error, user_data);
__connman_service_set_hidden_data(service, user_data);
reply_pending(service, error);
}
static gboolean connect_timeout(gpointer user_data)
{
struct connman_service *service = user_data;
bool autoconnect = false;
DBG("service %p", service);
service->timeout = 0;
if (service->network)
__connman_network_disconnect(service->network);
else if (service->provider)
connman_provider_disconnect(service->provider);
__connman_stats_service_unregister(service);
if (service->pending) {
DBusMessage *reply;
reply = __connman_error_operation_timeout(service->pending);
if (reply)
g_dbus_send_message(connection, reply);
dbus_message_unref(service->pending);
service->pending = NULL;
} else
autoconnect = true;
__connman_service_ipconfig_indicate_state(service,
CONNMAN_SERVICE_STATE_FAILURE,
CONNMAN_IPCONFIG_TYPE_IPV4);
__connman_service_ipconfig_indicate_state(service,
CONNMAN_SERVICE_STATE_FAILURE,
CONNMAN_IPCONFIG_TYPE_IPV6);
if (autoconnect &&
service->connect_reason !=
CONNMAN_SERVICE_CONNECT_REASON_USER)
__connman_service_auto_connect(CONNMAN_SERVICE_CONNECT_REASON_AUTO);
return FALSE;
}
static DBusMessage *connect_service(DBusConnection *conn,
DBusMessage *msg, void *user_data)
{
struct connman_service *service = user_data;
int index, err = 0;
GList *list;
DBG("service %p", service);
if (service->pending)
return __connman_error_in_progress(msg);
index = __connman_service_get_index(service);
for (list = service_list; list; list = list->next) {
struct connman_service *temp = list->data;
if (!is_connecting(temp->state) && !is_connected(temp->state))
break;
if (service == temp)
continue;
if (service->type != temp->type)
continue;
if (__connman_service_get_index(temp) == index &&
__connman_service_disconnect(temp) == -EINPROGRESS)
err = -EINPROGRESS;
}
if (err == -EINPROGRESS)
return __connman_error_operation_timeout(msg);
service->ignore = false;
service->pending = dbus_message_ref(msg);
err = __connman_service_connect(service,
CONNMAN_SERVICE_CONNECT_REASON_USER);
if (err == -EINPROGRESS)
return NULL;
if (service->pending) {
dbus_message_unref(service->pending);
service->pending = NULL;
}
if (err < 0)
return __connman_error_failed(msg, -err);
return g_dbus_create_reply(msg, DBUS_TYPE_INVALID);
}
static DBusMessage *disconnect_service(DBusConnection *conn,
DBusMessage *msg, void *user_data)
{
struct connman_service *service = user_data;
int err;
DBG("service %p", service);
service->ignore = true;
err = __connman_service_disconnect(service);
if (err < 0 && err != -EINPROGRESS)
return __connman_error_failed(msg, -err);
return g_dbus_create_reply(msg, DBUS_TYPE_INVALID);
}
bool __connman_service_remove(struct connman_service *service)
{
if (service->type == CONNMAN_SERVICE_TYPE_ETHERNET ||
service->type == CONNMAN_SERVICE_TYPE_GADGET)
return false;
if (service->immutable || service->hidden ||
__connman_provider_is_immutable(service->provider))
return false;
if (!service->favorite && !is_idle(service->state))
return false;
__connman_service_disconnect(service);
g_free(service->passphrase);
service->passphrase = NULL;
g_free(service->identity);
service->identity = NULL;
g_free(service->anonymous_identity);
service->anonymous_identity = NULL;
g_free(service->subject_match);
service->subject_match = NULL;
g_free(service->altsubject_match);
service->altsubject_match = NULL;
g_free(service->domain_suffix_match);
service->domain_suffix_match = NULL;
g_free(service->domain_match);
service->domain_match = NULL;
g_free(service->agent_identity);
service->agent_identity = NULL;
g_free(service->eap);
service->eap = NULL;
service->error = CONNMAN_SERVICE_ERROR_UNKNOWN;
__connman_service_set_favorite(service, false);
__connman_ipconfig_ipv6_reset_privacy(service->ipconfig_ipv6);
service_save(service);
return true;
}
static DBusMessage *remove_service(DBusConnection *conn,
DBusMessage *msg, void *user_data)
{
struct connman_service *service = user_data;
DBG("service %p", service);
if (!__connman_service_remove(service))
return __connman_error_not_supported(msg);
return g_dbus_create_reply(msg, DBUS_TYPE_INVALID);
}
static bool check_suitable_state(enum connman_service_state a,
enum connman_service_state b)
{
/*
* Special check so that "ready" service can be moved before
* "online" one.
*/
if ((a == CONNMAN_SERVICE_STATE_ONLINE &&
b == CONNMAN_SERVICE_STATE_READY) ||
(b == CONNMAN_SERVICE_STATE_ONLINE &&
a == CONNMAN_SERVICE_STATE_READY))
return true;
return a == b;
}
static void downgrade_state(struct connman_service *service)
{
if (!service)
return;
DBG("service %p state4 %d state6 %d", service, service->state_ipv4,
service->state_ipv6);
if (service->state_ipv4 == CONNMAN_SERVICE_STATE_ONLINE)
__connman_service_ipconfig_indicate_state(service,
CONNMAN_SERVICE_STATE_READY,
CONNMAN_IPCONFIG_TYPE_IPV4);
if (service->state_ipv6 == CONNMAN_SERVICE_STATE_ONLINE)
__connman_service_ipconfig_indicate_state(service,
CONNMAN_SERVICE_STATE_READY,
CONNMAN_IPCONFIG_TYPE_IPV6);
}
static void apply_relevant_default_downgrade(struct connman_service *service)
{
struct connman_service *def_service;
def_service = __connman_service_get_default();
if (!def_service)
return;
if (def_service == service &&
def_service->state == CONNMAN_SERVICE_STATE_ONLINE) {
def_service->state = CONNMAN_SERVICE_STATE_READY;
__connman_notifier_leave_online(def_service->type);
state_changed(def_service);
}
}
static void switch_default_service(struct connman_service *default_service,
struct connman_service *downgrade_service)
{
struct connman_service *service;
GList *src, *dst;
apply_relevant_default_downgrade(default_service);
src = g_list_find(service_list, downgrade_service);
dst = g_list_find(service_list, default_service);
/* Nothing to do */
if (src == dst || src->next == dst)
return;
service = src->data;
service_list = g_list_delete_link(service_list, src);
service_list = g_list_insert_before(service_list, dst, service);
downgrade_state(downgrade_service);
}
static DBusMessage *move_service(DBusConnection *conn,
DBusMessage *msg, void *user_data,
bool before)
{
struct connman_service *service = user_data;
struct connman_service *target;
const char *path;
enum connman_ipconfig_method target4, target6;
enum connman_ipconfig_method service4, service6;
DBG("service %p", service);
dbus_message_get_args(msg, NULL, DBUS_TYPE_OBJECT_PATH, &path,
DBUS_TYPE_INVALID);
if (!service->favorite)
return __connman_error_not_supported(msg);
target = find_service(path);
if (!target || !target->favorite || target == service)
return __connman_error_invalid_service(msg);
if (target->type == CONNMAN_SERVICE_TYPE_VPN) {
/*
* We only allow VPN route splitting if there are
* routes defined for a given VPN.
*/
if (!__connman_provider_check_routes(target->provider)) {
connman_info("Cannot move service. "
"No routes defined for provider %s",
__connman_provider_get_ident(target->provider));
return __connman_error_invalid_service(msg);
}
set_split_routing(target, true);
} else
set_split_routing(target, false);
set_split_routing(service, false);
target4 = __connman_ipconfig_get_method(target->ipconfig_ipv4);
target6 = __connman_ipconfig_get_method(target->ipconfig_ipv6);
service4 = __connman_ipconfig_get_method(service->ipconfig_ipv4);
service6 = __connman_ipconfig_get_method(service->ipconfig_ipv6);
DBG("target %s method %d/%d state %d/%d split %d", target->identifier,
target4, target6, target->state_ipv4, target->state_ipv6,
target->do_split_routing);
DBG("service %s method %d/%d state %d/%d", service->identifier,
service4, service6,
service->state_ipv4, service->state_ipv6);
/*
* If method is OFF, then we do not need to check the corresponding
* ipconfig state.
*/
if (target4 == CONNMAN_IPCONFIG_METHOD_OFF) {
if (service6 != CONNMAN_IPCONFIG_METHOD_OFF) {
if (!check_suitable_state(target->state_ipv6,
service->state_ipv6))
return __connman_error_invalid_service(msg);
}
}
if (target6 == CONNMAN_IPCONFIG_METHOD_OFF) {
if (service4 != CONNMAN_IPCONFIG_METHOD_OFF) {
if (!check_suitable_state(target->state_ipv4,
service->state_ipv4))
return __connman_error_invalid_service(msg);
}
}
if (service4 == CONNMAN_IPCONFIG_METHOD_OFF) {
if (target6 != CONNMAN_IPCONFIG_METHOD_OFF) {
if (!check_suitable_state(target->state_ipv6,
service->state_ipv6))
return __connman_error_invalid_service(msg);
}
}
if (service6 == CONNMAN_IPCONFIG_METHOD_OFF) {
if (target4 != CONNMAN_IPCONFIG_METHOD_OFF) {
if (!check_suitable_state(target->state_ipv4,
service->state_ipv4))
return __connman_error_invalid_service(msg);
}
}
g_get_current_time(&service->modified);
service_save(service);
service_save(target);
/*
* If the service which goes down is the default service and is
* online, we downgrade directly its state to ready so:
* the service which goes up, needs to recompute its state which
* is triggered via downgrading it - if relevant - to state ready.
*/
if (before)
switch_default_service(target, service);
else
switch_default_service(service, target);
__connman_connection_update_gateway();
return g_dbus_create_reply(msg, DBUS_TYPE_INVALID);
}
static DBusMessage *move_before(DBusConnection *conn,
DBusMessage *msg, void *user_data)
{
return move_service(conn, msg, user_data, true);
}
static DBusMessage *move_after(DBusConnection *conn,
DBusMessage *msg, void *user_data)
{
return move_service(conn, msg, user_data, false);
}
static DBusMessage *reset_counters(DBusConnection *conn,
DBusMessage *msg, void *user_data)
{
struct connman_service *service = user_data;
reset_stats(service);
return g_dbus_create_reply(msg, DBUS_TYPE_INVALID);
}
static struct _services_notify {
int id;
GHashTable *add;
GHashTable *remove;
} *services_notify;
static void service_append_added_foreach(gpointer data, gpointer user_data)
{
struct connman_service *service = data;
DBusMessageIter *iter = user_data;
if (!service || !service->path) {
DBG("service %p or path is NULL", service);
return;
}
if (g_hash_table_lookup(services_notify->add, service->path)) {
DBG("new %s", service->path);
append_struct(service, iter);
g_hash_table_remove(services_notify->add, service->path);
} else {
DBG("changed %s", service->path);
append_struct_service(iter, NULL, service);
}
}
static void service_append_ordered(DBusMessageIter *iter, void *user_data)
{
g_list_foreach(service_list, service_append_added_foreach, iter);
}
static void append_removed(gpointer key, gpointer value, gpointer user_data)
{
char *objpath = key;
DBusMessageIter *iter = user_data;
DBG("removed %s", objpath);
dbus_message_iter_append_basic(iter, DBUS_TYPE_OBJECT_PATH, &objpath);
}
static void service_append_removed(DBusMessageIter *iter, void *user_data)
{
g_hash_table_foreach(services_notify->remove, append_removed, iter);
}
static gboolean service_send_changed(gpointer data)
{
DBusMessage *signal;
DBG("");
services_notify->id = 0;
signal = dbus_message_new_signal(CONNMAN_MANAGER_PATH,
CONNMAN_MANAGER_INTERFACE, "ServicesChanged");
if (!signal)
return FALSE;
__connman_dbus_append_objpath_dict_array(signal,
service_append_ordered, NULL);
__connman_dbus_append_objpath_array(signal,
service_append_removed, NULL);
dbus_connection_send(connection, signal, NULL);
dbus_message_unref(signal);
g_hash_table_remove_all(services_notify->remove);
g_hash_table_remove_all(services_notify->add);
return FALSE;
}
static void service_schedule_changed(void)
{
if (services_notify->id != 0)
return;
services_notify->id = g_timeout_add(100, service_send_changed, NULL);
}
static void service_schedule_added(struct connman_service *service)
{
DBG("service %p", service);
g_hash_table_remove(services_notify->remove, service->path);
g_hash_table_replace(services_notify->add, service->path, service);
service_schedule_changed();
}
static void service_schedule_removed(struct connman_service *service)
{
if (!service || !service->path) {
DBG("service %p or path is NULL", service);
return;
}
DBG("service %p %s", service, service->path);
g_hash_table_remove(services_notify->add, service->path);
g_hash_table_replace(services_notify->remove, g_strdup(service->path),
NULL);
service_schedule_changed();
}
static bool allow_property_changed(struct connman_service *service)
{
if (!service || !service->path) {
DBG("service %p or path is NULL", service);
return false;
}
if (g_hash_table_lookup_extended(services_notify->add, service->path,
NULL, NULL))
return false;
return true;
}
static const GDBusMethodTable service_methods[] = {
{ GDBUS_DEPRECATED_METHOD("GetProperties",
NULL, GDBUS_ARGS({ "properties", "a{sv}" }),
get_properties) },
{ GDBUS_METHOD("SetProperty",
GDBUS_ARGS({ "name", "s" }, { "value", "v" }),
NULL, set_property) },
{ GDBUS_METHOD("ClearProperty",
GDBUS_ARGS({ "name", "s" }), NULL,
clear_property) },
{ GDBUS_ASYNC_METHOD("Connect", NULL, NULL,
connect_service) },
{ GDBUS_METHOD("Disconnect", NULL, NULL,
disconnect_service) },
{ GDBUS_METHOD("Remove", NULL, NULL, remove_service) },
{ GDBUS_METHOD("MoveBefore",
GDBUS_ARGS({ "service", "o" }), NULL,
move_before) },
{ GDBUS_METHOD("MoveAfter",
GDBUS_ARGS({ "service", "o" }), NULL,
move_after) },
{ GDBUS_METHOD("ResetCounters", NULL, NULL, reset_counters) },
{ },
};
static const GDBusSignalTable service_signals[] = {
{ GDBUS_SIGNAL("PropertyChanged",
GDBUS_ARGS({ "name", "s" }, { "value", "v" })) },
{ },
};
static void service_free(gpointer user_data)
{
struct connman_service *service = user_data;
char *path = service->path;
DBG("service %p", service);
reply_pending(service, ENOENT);
if (service->nameservers_timeout) {
g_source_remove(service->nameservers_timeout);
dns_changed(service);
}
__connman_notifier_service_remove(service);
service_schedule_removed(service);
__connman_wispr_stop(service);
stats_stop(service);
service->path = NULL;
if (path) {
__connman_connection_update_gateway();
g_dbus_unregister_interface(connection, path,
CONNMAN_SERVICE_INTERFACE);
g_free(path);
}
g_hash_table_destroy(service->counter_table);
if (service->network) {
__connman_network_disconnect(service->network);
connman_network_unref(service->network);
service->network = NULL;
}
if (service->provider)
connman_provider_unref(service->provider);
if (service->ipconfig_ipv4) {
__connman_ipconfig_set_ops(service->ipconfig_ipv4, NULL);
__connman_ipconfig_set_data(service->ipconfig_ipv4, NULL);
__connman_ipconfig_unref(service->ipconfig_ipv4);
service->ipconfig_ipv4 = NULL;
}
if (service->ipconfig_ipv6) {
__connman_ipconfig_set_ops(service->ipconfig_ipv6, NULL);
__connman_ipconfig_set_data(service->ipconfig_ipv6, NULL);
__connman_ipconfig_unref(service->ipconfig_ipv6);
service->ipconfig_ipv6 = NULL;
}
g_strfreev(service->timeservers);
g_strfreev(service->timeservers_config);
g_strfreev(service->nameservers);
g_strfreev(service->nameservers_config);
g_strfreev(service->nameservers_auto);
g_strfreev(service->domains);
g_strfreev(service->proxies);
g_strfreev(service->excludes);
g_free(service->hostname);
g_free(service->domainname);
g_free(service->pac);
g_free(service->name);
g_free(service->passphrase);
g_free(service->identifier);
g_free(service->eap);
g_free(service->identity);
g_free(service->anonymous_identity);
g_free(service->agent_identity);
g_free(service->ca_cert_file);
g_free(service->subject_match);
g_free(service->altsubject_match);
g_free(service->domain_suffix_match);
g_free(service->domain_match);
g_free(service->client_cert_file);
g_free(service->private_key_file);
g_free(service->private_key_passphrase);
g_free(service->phase2);
g_free(service->config_file);
g_free(service->config_entry);
if (service->stats.timer)
g_timer_destroy(service->stats.timer);
if (service->stats_roaming.timer)
g_timer_destroy(service->stats_roaming.timer);
if (current_default == service)
current_default = NULL;
g_free(service);
}
static void stats_init(struct connman_service *service)
{
/* home */
service->stats.valid = false;
service->stats.enabled = false;
service->stats.timer = g_timer_new();
/* roaming */
service->stats_roaming.valid = false;
service->stats_roaming.enabled = false;
service->stats_roaming.timer = g_timer_new();
}
static void service_initialize(struct connman_service *service)
{
DBG("service %p", service);
service->refcount = 1;
service->error = CONNMAN_SERVICE_ERROR_UNKNOWN;
service->type = CONNMAN_SERVICE_TYPE_UNKNOWN;
service->security = CONNMAN_SERVICE_SECURITY_UNKNOWN;
service->state = CONNMAN_SERVICE_STATE_UNKNOWN;
service->state_ipv4 = CONNMAN_SERVICE_STATE_UNKNOWN;
service->state_ipv6 = CONNMAN_SERVICE_STATE_UNKNOWN;
service->favorite = false;
service->immutable = false;
service->hidden = false;
service->ignore = false;
service->connect_reason = CONNMAN_SERVICE_CONNECT_REASON_NONE;
service->order = 0;
stats_init(service);
service->provider = NULL;
service->wps = false;
service->wps_advertizing = false;
}
/**
* connman_service_create:
*
* Allocate a new service.
*
* Returns: a newly-allocated #connman_service structure
*/
struct connman_service *connman_service_create(void)
{
GSList *list;
struct connman_stats_counter *counters;
const char *counter;
struct connman_service *service;
service = g_try_new0(struct connman_service, 1);
if (!service)
return NULL;
DBG("service %p", service);
service->counter_table = g_hash_table_new_full(g_str_hash,
g_str_equal, NULL, g_free);
for (list = counter_list; list; list = list->next) {
counter = list->data;
counters = g_try_new0(struct connman_stats_counter, 1);
if (!counters) {
g_hash_table_destroy(service->counter_table);
g_free(service);
return NULL;
}
counters->append_all = true;
g_hash_table_replace(service->counter_table, (gpointer)counter,
counters);
}
service_initialize(service);
return service;
}
/**
* connman_service_ref:
* @service: service structure
*
* Increase reference counter of service
*/
struct connman_service *
connman_service_ref_debug(struct connman_service *service,
const char *file, int line, const char *caller)
{
DBG("%p ref %d by %s:%d:%s()", service, service->refcount + 1,
file, line, caller);
__sync_fetch_and_add(&service->refcount, 1);
return service;
}
/**
* connman_service_unref:
* @service: service structure
*
* Decrease reference counter of service and release service if no
* longer needed.
*/
void connman_service_unref_debug(struct connman_service *service,
const char *file, int line, const char *caller)
{
DBG("%p ref %d by %s:%d:%s()", service, service->refcount - 1,
file, line, caller);
if (__sync_fetch_and_sub(&service->refcount, 1) != 1)
return;
service_list = g_list_remove(service_list, service);
__connman_service_disconnect(service);
g_hash_table_remove(service_hash, service->identifier);
}
static gint service_compare(gconstpointer a, gconstpointer b)
{
struct connman_service *service_a = (void *) a;
struct connman_service *service_b = (void *) b;
enum connman_service_state state_a, state_b;
bool a_connected, b_connected;
gint strength;
state_a = service_a->state;
state_b = service_b->state;
a_connected = is_connected(state_a);
b_connected = is_connected(state_b);
if (a_connected && b_connected) {
if (service_a->order > service_b->order)
return -1;
if (service_a->order < service_b->order)
return 1;
}
if (state_a != state_b) {
if (a_connected && b_connected) {
/* We prefer online over ready state */
if (state_a == CONNMAN_SERVICE_STATE_ONLINE)
return -1;
if (state_b == CONNMAN_SERVICE_STATE_ONLINE)
return 1;
}
if (a_connected)
return -1;
if (b_connected)
return 1;
if (is_connecting(state_a))
return -1;
if (is_connecting(state_b))
return 1;
}
if (service_a->favorite && !service_b->favorite)
return -1;
if (!service_a->favorite && service_b->favorite)
return 1;
if (service_a->type != service_b->type) {
unsigned int *tech_array;
int i;
tech_array = connman_setting_get_uint_list(
"PreferredTechnologies");
if (tech_array) {
for (i = 0; tech_array[i]; i++) {
if (tech_array[i] == service_a->type)
return -1;
if (tech_array[i] == service_b->type)
return 1;
}
}
if (service_a->type == CONNMAN_SERVICE_TYPE_ETHERNET)
return -1;
if (service_b->type == CONNMAN_SERVICE_TYPE_ETHERNET)
return 1;
if (service_a->type == CONNMAN_SERVICE_TYPE_WIFI)
return -1;
if (service_b->type == CONNMAN_SERVICE_TYPE_WIFI)
return 1;
if (service_a->type == CONNMAN_SERVICE_TYPE_CELLULAR)
return -1;
if (service_b->type == CONNMAN_SERVICE_TYPE_CELLULAR)
return 1;
if (service_a->type == CONNMAN_SERVICE_TYPE_BLUETOOTH)
return -1;
if (service_b->type == CONNMAN_SERVICE_TYPE_BLUETOOTH)
return 1;
if (service_a->type == CONNMAN_SERVICE_TYPE_VPN)
return -1;
if (service_b->type == CONNMAN_SERVICE_TYPE_VPN)
return 1;
if (service_a->type == CONNMAN_SERVICE_TYPE_GADGET)
return -1;
if (service_b->type == CONNMAN_SERVICE_TYPE_GADGET)
return 1;
}
strength = (gint) service_b->strength - (gint) service_a->strength;
if (strength)
return strength;
return g_strcmp0(service_a->name, service_b->name);
}
static void service_list_sort(void)
{
if (service_list && service_list->next) {
service_list = g_list_sort(service_list, service_compare);
service_schedule_changed();
}
}
int __connman_service_compare(const struct connman_service *a,
const struct connman_service *b)
{
return service_compare(a, b);
}
/**
* connman_service_get_type:
* @service: service structure
*
* Get the type of service
*/
enum connman_service_type connman_service_get_type(struct connman_service *service)
{
if (!service)
return CONNMAN_SERVICE_TYPE_UNKNOWN;
return service->type;
}
/**
* connman_service_get_interface:
* @service: service structure
*
* Get network interface of service
*/
char *connman_service_get_interface(struct connman_service *service)
{
int index;
if (!service)
return NULL;
index = __connman_service_get_index(service);
return connman_inet_ifname(index);
}
/**
* connman_service_get_network:
* @service: service structure
*
* Get the service network
*/
struct connman_network *
__connman_service_get_network(struct connman_service *service)
{
if (!service)
return NULL;
return service->network;
}
struct connman_ipconfig *
__connman_service_get_ip4config(struct connman_service *service)
{
if (!service)
return NULL;
return service->ipconfig_ipv4;
}
struct connman_ipconfig *
__connman_service_get_ip6config(struct connman_service *service)
{
if (!service)
return NULL;
return service->ipconfig_ipv6;
}
struct connman_ipconfig *
__connman_service_get_ipconfig(struct connman_service *service, int family)
{
if (family == AF_INET)
return __connman_service_get_ip4config(service);
else if (family == AF_INET6)
return __connman_service_get_ip6config(service);
else
return NULL;
}
bool __connman_service_is_connected_state(struct connman_service *service,
enum connman_ipconfig_type type)
{
if (!service)
return false;
switch (type) {
case CONNMAN_IPCONFIG_TYPE_UNKNOWN:
break;
case CONNMAN_IPCONFIG_TYPE_IPV4:
return is_connected(service->state_ipv4);
case CONNMAN_IPCONFIG_TYPE_IPV6:
return is_connected(service->state_ipv6);
case CONNMAN_IPCONFIG_TYPE_ALL:
return is_connected(service->state_ipv4) &&
is_connected(service->state_ipv6);
}
return false;
}
enum connman_service_security __connman_service_get_security(
struct connman_service *service)
{
if (!service)
return CONNMAN_SERVICE_SECURITY_UNKNOWN;
return service->security;
}
const char *__connman_service_get_phase2(struct connman_service *service)
{
if (!service)
return NULL;
return service->phase2;
}
bool __connman_service_wps_enabled(struct connman_service *service)
{
if (!service)
return false;
return service->wps;
}
void __connman_service_mark_dirty(void)
{
services_dirty = true;
}
/**
* __connman_service_set_favorite_delayed:
* @service: service structure
* @favorite: favorite value
* @delay_ordering: do not order service sequence
*
* Change the favorite setting of service
*/
int __connman_service_set_favorite_delayed(struct connman_service *service,
bool favorite,
bool delay_ordering)
{
if (service->hidden)
return -EOPNOTSUPP;
if (service->favorite == favorite)
return -EALREADY;
service->favorite = favorite;
if (!delay_ordering)
__connman_service_get_order(service);
favorite_changed(service);
if (!delay_ordering) {
service_list_sort();
__connman_connection_update_gateway();
}
return 0;
}
/**
* __connman_service_set_favorite:
* @service: service structure
* @favorite: favorite value
*
* Change the favorite setting of service
*/
int __connman_service_set_favorite(struct connman_service *service,
bool favorite)
{
return __connman_service_set_favorite_delayed(service, favorite,
false);
}
bool connman_service_get_favorite(struct connman_service *service)
{
return service->favorite;
}
bool connman_service_get_autoconnect(struct connman_service *service)
{
return service->autoconnect;
}
int __connman_service_set_immutable(struct connman_service *service,
bool immutable)
{
if (service->hidden)
return -EOPNOTSUPP;
if (service->immutable == immutable)
return 0;
service->immutable = immutable;
immutable_changed(service);
return 0;
}
int __connman_service_set_ignore(struct connman_service *service,
bool ignore)
{
if (!service)
return -EINVAL;
service->ignore = ignore;
return 0;
}
void __connman_service_set_string(struct connman_service *service,
const char *key, const char *value)
{
if (service->hidden)
return;
if (g_str_equal(key, "EAP")) {
g_free(service->eap);
service->eap = g_strdup(value);
} else if (g_str_equal(key, "Identity")) {
g_free(service->identity);
service->identity = g_strdup(value);
} else if (g_str_equal(key, "AnonymousIdentity")) {
g_free(service->anonymous_identity);
service->anonymous_identity = g_strdup(value);
} else if (g_str_equal(key, "CACertFile")) {
g_free(service->ca_cert_file);
service->ca_cert_file = g_strdup(value);
} else if (g_str_equal(key, "SubjectMatch")) {
g_free(service->subject_match);
service->subject_match = g_strdup(value);
} else if (g_str_equal(key, "AltSubjectMatch")) {
g_free(service->altsubject_match);
service->altsubject_match = g_strdup(value);
} else if (g_str_equal(key, "DomainSuffixMatch")) {
g_free(service->domain_suffix_match);
service->domain_suffix_match = g_strdup(value);
} else if (g_str_equal(key, "DomainMatch")) {
g_free(service->domain_match);
service->domain_match = g_strdup(value);
} else if (g_str_equal(key, "ClientCertFile")) {
g_free(service->client_cert_file);
service->client_cert_file = g_strdup(value);
} else if (g_str_equal(key, "PrivateKeyFile")) {
g_free(service->private_key_file);
service->private_key_file = g_strdup(value);
} else if (g_str_equal(key, "PrivateKeyPassphrase")) {
g_free(service->private_key_passphrase);
service->private_key_passphrase = g_strdup(value);
} else if (g_str_equal(key, "Phase2")) {
g_free(service->phase2);
service->phase2 = g_strdup(value);
} else if (g_str_equal(key, "Passphrase"))
__connman_service_set_passphrase(service, value);
}
void __connman_service_set_search_domains(struct connman_service *service,
char **domains)
{
searchdomain_remove_all(service);
if (service->domains)
g_strfreev(service->domains);
service->domains = g_strdupv(domains);
searchdomain_add_all(service);
}
int __connman_service_set_mdns(struct connman_service *service,
bool enabled)
{
service->mdns_config = enabled;
return set_mdns(service, enabled);
}
static void report_error_cb(void *user_context, bool retry,
void *user_data)
{
struct connman_service *service = user_context;
if (retry)
__connman_service_connect(service,
CONNMAN_SERVICE_CONNECT_REASON_USER);
else {
/* It is not relevant to stay on Failure state
* when failing is due to wrong user input */
__connman_service_clear_error(service);
service_complete(service);
__connman_connection_update_gateway();
}
}
static int check_wpspin(struct connman_service *service, const char *wpspin)
{
int length;
guint i;
if (!wpspin)
return 0;
length = strlen(wpspin);
/* If 0, it will mean user wants to use PBC method */
if (length == 0) {
connman_network_set_string(service->network,
"WiFi.PinWPS", NULL);
return 0;
}
/* A WPS PIN is always 8 chars length,
* its content is in digit representation.
*/
if (length != 8)
return -ENOKEY;
for (i = 0; i < 8; i++)
if (!isdigit((unsigned char) wpspin[i]))
return -ENOKEY;
connman_network_set_string(service->network, "WiFi.PinWPS", wpspin);
return 0;
}
static void request_input_cb(struct connman_service *service,
bool values_received,
const char *name, int name_len,
const char *identity, const char *passphrase,
bool wps, const char *wpspin,
const char *error, void *user_data)
{
struct connman_device *device;
const char *security;
int err = 0;
DBG("RequestInput return, %p", service);
if (error) {
DBG("error: %s", error);
if (g_strcmp0(error,
"net.connman.Agent.Error.Canceled") == 0) {
err = -ECONNABORTED;
if (service->hidden)
__connman_service_return_error(service,
ECONNABORTED,
user_data);
goto done;
} else {
if (service->hidden)
__connman_service_return_error(service,
ETIMEDOUT, user_data);
}
}
if (service->hidden && name_len > 0 && name_len <= 32) {
device = connman_network_get_device(service->network);
security = connman_network_get_string(service->network,
"WiFi.Security");
err = __connman_device_request_hidden_scan(device,
name, name_len,
identity, passphrase,
security, user_data);
if (err < 0)
__connman_service_return_error(service, -err,
user_data);
}
if (!values_received || service->hidden) {
err = -EINVAL;
goto done;
}
if (wps && service->network) {
err = check_wpspin(service, wpspin);
if (err < 0)
goto done;
connman_network_set_bool(service->network, "WiFi.UseWPS", wps);
}
if (identity)
__connman_service_set_agent_identity(service, identity);
if (passphrase)
err = __connman_service_set_passphrase(service, passphrase);
done:
if (err >= 0) {
/* We forget any previous error. */
set_error(service, CONNMAN_SERVICE_ERROR_UNKNOWN);
__connman_service_connect(service,
CONNMAN_SERVICE_CONNECT_REASON_USER);
} else if (err == -ENOKEY) {
__connman_service_indicate_error(service,
CONNMAN_SERVICE_ERROR_INVALID_KEY);
} else {
/* It is not relevant to stay on Failure state
* when failing is due to wrong user input */
service->state = CONNMAN_SERVICE_STATE_IDLE;
if (!service->hidden) {
/*
* If there was a real error when requesting
* hidden scan, then that error is returned already
* to the user somewhere above so do not try to
* do this again.
*/
__connman_service_return_error(service, -err,
user_data);
}
service_complete(service);
__connman_connection_update_gateway();
}
}
static void downgrade_connected_services(void)
{
struct connman_service *up_service;
GList *list;
for (list = service_list; list; list = list->next) {
up_service = list->data;
if (!is_connected(up_service->state))
continue;
if (up_service->state == CONNMAN_SERVICE_STATE_ONLINE)
return;
downgrade_state(up_service);
}
}
static int service_update_preferred_order(struct connman_service *default_service,
struct connman_service *new_service,
enum connman_service_state new_state)
{
unsigned int *tech_array;
int i;
if (!default_service || default_service == new_service ||
default_service->state != new_state)
return 0;
tech_array = connman_setting_get_uint_list("PreferredTechnologies");
if (tech_array) {
for (i = 0; tech_array[i] != 0; i += 1) {
if (default_service->type == tech_array[i])
return -EALREADY;
if (new_service->type == tech_array[i]) {
switch_default_service(default_service,
new_service);
__connman_connection_update_gateway();
return 0;
}
}
}
return -EALREADY;
}
static void single_connected_tech(struct connman_service *allowed)
{
struct connman_service *service;
GSList *services = NULL, *list;
GList *iter;
DBG("keeping %p %s", allowed, allowed->path);
for (iter = service_list; iter; iter = iter->next) {
service = iter->data;
if (!is_connected(service->state))
break;
if (service == allowed)
continue;
services = g_slist_prepend(services, service);
}
for (list = services; list; list = list->next) {
service = list->data;
DBG("disconnecting %p %s", service, service->path);
__connman_service_disconnect(service);
}
g_slist_free(services);
}
static const char *get_dbus_sender(struct connman_service *service)
{
if (!service->pending)
return NULL;
return dbus_message_get_sender(service->pending);
}
static int service_indicate_state(struct connman_service *service)
{
enum connman_service_state old_state, new_state;
struct connman_service *def_service;
enum connman_ipconfig_method method;
int result;
if (!service)
return -EINVAL;
old_state = service->state;
new_state = combine_state(service->state_ipv4, service->state_ipv6);
DBG("service %p old %s - new %s/%s => %s",
service,
state2string(old_state),
state2string(service->state_ipv4),
state2string(service->state_ipv6),
state2string(new_state));
if (old_state == new_state)
return -EALREADY;
def_service = __connman_service_get_default();
if (new_state == CONNMAN_SERVICE_STATE_ONLINE) {
result = service_update_preferred_order(def_service,
service, new_state);
if (result == -EALREADY)
return result;
}
if (old_state == CONNMAN_SERVICE_STATE_ONLINE)
__connman_notifier_leave_online(service->type);
if (is_connected(old_state) && !is_connected(new_state))
searchdomain_remove_all(service);
service->state = new_state;
state_changed(service);
if (!is_connected(old_state) && is_connected(new_state))
searchdomain_add_all(service);
switch(new_state) {
case CONNMAN_SERVICE_STATE_UNKNOWN:
break;
case CONNMAN_SERVICE_STATE_IDLE:
if (old_state != CONNMAN_SERVICE_STATE_DISCONNECT)
__connman_service_disconnect(service);
break;
case CONNMAN_SERVICE_STATE_ASSOCIATION:
break;
case CONNMAN_SERVICE_STATE_CONFIGURATION:
if (!service->new_service &&
__connman_stats_service_register(service) == 0) {
/*
* For new services the statistics are updated after
* we have successfully connected.
*/
__connman_stats_get(service, false,
&service->stats.data);
__connman_stats_get(service, true,
&service->stats_roaming.data);
}
break;
case CONNMAN_SERVICE_STATE_READY:
set_error(service, CONNMAN_SERVICE_ERROR_UNKNOWN);
if (service->new_service &&
__connman_stats_service_register(service) == 0) {
/*
* This is normally done after configuring state
* but for new service do this after we have connected
* successfully.
*/
__connman_stats_get(service, false,
&service->stats.data);
__connman_stats_get(service, true,
&service->stats_roaming.data);
}
service->new_service = false;
default_changed();
def_service = __connman_service_get_default();
service_update_preferred_order(def_service, service, new_state);
__connman_service_set_favorite(service, true);
reply_pending(service, 0);
if (service->type == CONNMAN_SERVICE_TYPE_WIFI &&
connman_network_get_bool(service->network,
"WiFi.UseWPS")) {
const char *pass;
pass = connman_network_get_string(service->network,
"WiFi.Passphrase");
__connman_service_set_passphrase(service, pass);
connman_network_set_bool(service->network,
"WiFi.UseWPS", false);
}
g_get_current_time(&service->modified);
service_save(service);
domain_changed(service);
proxy_changed(service);
if (old_state != CONNMAN_SERVICE_STATE_ONLINE)
__connman_notifier_connect(service->type);
method = __connman_ipconfig_get_method(service->ipconfig_ipv6);
if (method == CONNMAN_IPCONFIG_METHOD_OFF)
__connman_ipconfig_disable_ipv6(
service->ipconfig_ipv6);
if (connman_setting_get_bool("SingleConnectedTechnology"))
single_connected_tech(service);
else if (service->type != CONNMAN_SERVICE_TYPE_VPN)
vpn_auto_connect();
break;
case CONNMAN_SERVICE_STATE_ONLINE:
break;
case CONNMAN_SERVICE_STATE_DISCONNECT:
set_error(service, CONNMAN_SERVICE_ERROR_UNKNOWN);
reply_pending(service, ECONNABORTED);
def_service = __connman_service_get_default();
if (!__connman_notifier_is_connected() &&
def_service &&
def_service->provider)
connman_provider_disconnect(def_service->provider);
default_changed();
__connman_wispr_stop(service);
__connman_wpad_stop(service);
domain_changed(service);
proxy_changed(service);
/*
* Previous services which are connected and which states
* are set to online should reset relevantly ipconfig_state
* to ready so wispr/portal will be rerun on those
*/
downgrade_connected_services();
__connman_service_auto_connect(CONNMAN_SERVICE_CONNECT_REASON_AUTO);
break;
case CONNMAN_SERVICE_STATE_FAILURE:
if (service->connect_reason == CONNMAN_SERVICE_CONNECT_REASON_USER) {
connman_agent_report_error(service, service->path,
error2string(service->error),
report_error_cb,
get_dbus_sender(service),
NULL);
}
service_complete(service);
break;
}
service_list_sort();
__connman_connection_update_gateway();
if ((old_state == CONNMAN_SERVICE_STATE_ONLINE &&
new_state != CONNMAN_SERVICE_STATE_READY) ||
(old_state == CONNMAN_SERVICE_STATE_READY &&
new_state != CONNMAN_SERVICE_STATE_ONLINE)) {
__connman_notifier_disconnect(service->type);
}
if (new_state == CONNMAN_SERVICE_STATE_ONLINE) {
__connman_notifier_enter_online(service->type);
default_changed();
}
return 0;
}
int __connman_service_indicate_error(struct connman_service *service,
enum connman_service_error error)
{
DBG("service %p error %d", service, error);
if (!service)
return -EINVAL;
if (service->state == CONNMAN_SERVICE_STATE_FAILURE)
return -EALREADY;
set_error(service, error);
__connman_service_ipconfig_indicate_state(service,
CONNMAN_SERVICE_STATE_FAILURE,
CONNMAN_IPCONFIG_TYPE_IPV4);
__connman_service_ipconfig_indicate_state(service,
CONNMAN_SERVICE_STATE_FAILURE,
CONNMAN_IPCONFIG_TYPE_IPV6);
return 0;
}
int __connman_service_clear_error(struct connman_service *service)
{
DBusMessage *pending, *provider_pending;
DBG("service %p", service);
if (!service)
return -EINVAL;
if (service->state != CONNMAN_SERVICE_STATE_FAILURE)
return -EINVAL;
pending = service->pending;
service->pending = NULL;
provider_pending = service->provider_pending;
service->provider_pending = NULL;
__connman_service_ipconfig_indicate_state(service,
CONNMAN_SERVICE_STATE_IDLE,
CONNMAN_IPCONFIG_TYPE_IPV6);
__connman_service_ipconfig_indicate_state(service,
CONNMAN_SERVICE_STATE_IDLE,
CONNMAN_IPCONFIG_TYPE_IPV4);
service->pending = pending;
service->provider_pending = provider_pending;
return 0;
}
int __connman_service_indicate_default(struct connman_service *service)
{
DBG("service %p state %s", service, state2string(service->state));
if (!is_connected(service->state)) {
/*
* If service is not yet fully connected, then we must not
* change the default yet. The default gw will be changed
* after the service state is in ready.
*/
return -EINPROGRESS;
}
default_changed();
return 0;
}
enum connman_service_state __connman_service_ipconfig_get_state(
struct connman_service *service,
enum connman_ipconfig_type type)
{
if (!service)
return CONNMAN_SERVICE_STATE_UNKNOWN;
if (type == CONNMAN_IPCONFIG_TYPE_IPV4)
return service->state_ipv4;
if (type == CONNMAN_IPCONFIG_TYPE_IPV6)
return service->state_ipv6;
return CONNMAN_SERVICE_STATE_UNKNOWN;
}
static void check_proxy_setup(struct connman_service *service)
{
/*
* We start WPAD if we haven't got a PAC URL from DHCP and
* if our proxy manual configuration is either empty or set
* to AUTO with an empty URL.
*/
if (service->proxy != CONNMAN_SERVICE_PROXY_METHOD_UNKNOWN)
goto done;
if (service->proxy_config != CONNMAN_SERVICE_PROXY_METHOD_UNKNOWN &&
(service->proxy_config != CONNMAN_SERVICE_PROXY_METHOD_AUTO ||
service->pac))
goto done;
if (__connman_wpad_start(service) < 0) {
service->proxy = CONNMAN_SERVICE_PROXY_METHOD_DIRECT;
__connman_notifier_proxy_changed(service);
goto done;
}
return;
done:
__connman_service_wispr_start(service, CONNMAN_IPCONFIG_TYPE_IPV4);
}
/*
* How many networks are connected at the same time. If more than 1,
* then set the rp_filter setting properly (loose mode routing) so that network
* connectivity works ok. This is only done for IPv4 networks as IPv6
* does not have rp_filter knob.
*/
static int connected_networks_count;
static int original_rp_filter;
static void service_rp_filter(struct connman_service *service,
bool connected)
{
enum connman_ipconfig_method method;
method = __connman_ipconfig_get_method(service->ipconfig_ipv4);
switch (method) {
case CONNMAN_IPCONFIG_METHOD_UNKNOWN:
case CONNMAN_IPCONFIG_METHOD_OFF:
case CONNMAN_IPCONFIG_METHOD_AUTO:
return;
case CONNMAN_IPCONFIG_METHOD_FIXED:
case CONNMAN_IPCONFIG_METHOD_MANUAL:
case CONNMAN_IPCONFIG_METHOD_DHCP:
break;
}
if (connected) {
if (connected_networks_count == 1) {
int filter_value;
filter_value = __connman_ipconfig_set_rp_filter();
if (filter_value < 0)
return;
original_rp_filter = filter_value;
}
connected_networks_count++;
} else {
if (connected_networks_count == 2)
__connman_ipconfig_unset_rp_filter(original_rp_filter);
connected_networks_count--;
if (connected_networks_count < 0)
connected_networks_count = 0;
}
DBG("%s %s ipconfig %p method %d count %d filter %d",
connected ? "connected" : "disconnected", service->identifier,
service->ipconfig_ipv4, method,
connected_networks_count, original_rp_filter);
}
static void redo_wispr(struct connman_service *service,
enum connman_ipconfig_type type)
{
int refcount = service->refcount - 1;
connman_service_unref(service);
if (refcount == 0) {
DBG("Service %p already removed", service);
return;
}
DBG("Retrying %s WISPr for %p %s",
__connman_ipconfig_type2string(type),
service, service->name);
__connman_wispr_start(service, type);
}
static gboolean redo_wispr_ipv4(gpointer user_data)
{
struct connman_service *service = user_data;
redo_wispr(service, CONNMAN_IPCONFIG_TYPE_IPV4);
return FALSE;
}
static gboolean redo_wispr_ipv6(gpointer user_data)
{
struct connman_service *service = user_data;
redo_wispr(service, CONNMAN_IPCONFIG_TYPE_IPV6);
return FALSE;
}
int __connman_service_online_check_failed(struct connman_service *service,
enum connman_ipconfig_type type)
{
GSourceFunc redo_func;
int *count;
if (type == CONNMAN_IPCONFIG_TYPE_IPV4) {
count = &service->online_check_count_ipv4;
redo_func = redo_wispr_ipv4;
} else {
count = &service->online_check_count_ipv6;
redo_func = redo_wispr_ipv6;
}
DBG("service %p type %s count %d", service,
__connman_ipconfig_type2string(type), *count);
if (*count == 0) {
connman_warn("%s online check failed for %p %s",
__connman_ipconfig_type2string(type),
service, service->name);
return 0;
}
*count -= 1;
/*
* We set the timeout to 1 sec so that we have a chance to get
* necessary IPv6 router advertisement messages that might have
* DNS data etc.
*/
g_timeout_add_seconds(1, redo_func, connman_service_ref(service));
return EAGAIN;
}
int __connman_service_ipconfig_indicate_state(struct connman_service *service,
enum connman_service_state new_state,
enum connman_ipconfig_type type)
{
struct connman_ipconfig *ipconfig = NULL;
enum connman_service_state old_state;
enum connman_ipconfig_method method;
if (!service)
return -EINVAL;
switch (type) {
case CONNMAN_IPCONFIG_TYPE_UNKNOWN:
case CONNMAN_IPCONFIG_TYPE_ALL:
return -EINVAL;
case CONNMAN_IPCONFIG_TYPE_IPV4:
old_state = service->state_ipv4;
ipconfig = service->ipconfig_ipv4;
break;
case CONNMAN_IPCONFIG_TYPE_IPV6:
old_state = service->state_ipv6;
ipconfig = service->ipconfig_ipv6;
break;
}
if (!ipconfig)
return -EINVAL;
method = __connman_ipconfig_get_method(ipconfig);
switch (method) {
case CONNMAN_IPCONFIG_METHOD_UNKNOWN:
case CONNMAN_IPCONFIG_METHOD_OFF:
if (new_state != CONNMAN_SERVICE_STATE_IDLE)
connman_warn("ipconfig state %d ipconfig method %d",
new_state, method);
new_state = CONNMAN_SERVICE_STATE_IDLE;
break;
case CONNMAN_IPCONFIG_METHOD_FIXED:
case CONNMAN_IPCONFIG_METHOD_MANUAL:
case CONNMAN_IPCONFIG_METHOD_DHCP:
case CONNMAN_IPCONFIG_METHOD_AUTO:
break;
}
/* Any change? */
if (old_state == new_state)
return -EALREADY;
DBG("service %p (%s) old state %d (%s) new state %d (%s) type %d (%s)",
service, service ? service->identifier : NULL,
old_state, state2string(old_state),
new_state, state2string(new_state),
type, __connman_ipconfig_type2string(type));
switch (new_state) {
case CONNMAN_SERVICE_STATE_UNKNOWN:
case CONNMAN_SERVICE_STATE_ASSOCIATION:
break;
case CONNMAN_SERVICE_STATE_CONFIGURATION:
break;
case CONNMAN_SERVICE_STATE_READY:
if (connman_setting_get_bool("EnableOnlineCheck"))
if (type == CONNMAN_IPCONFIG_TYPE_IPV4) {
check_proxy_setup(service);
} else {
__connman_service_wispr_start(service, type);
}
else
connman_info("Online check disabled. "
"Default service remains in READY state.");
if (type == CONNMAN_IPCONFIG_TYPE_IPV4)
service_rp_filter(service, true);
set_mdns(service, service->mdns_config);
break;
case CONNMAN_SERVICE_STATE_ONLINE:
break;
case CONNMAN_SERVICE_STATE_DISCONNECT:
if (service->state == CONNMAN_SERVICE_STATE_IDLE)
return -EINVAL;
if (type == CONNMAN_IPCONFIG_TYPE_IPV4)
service_rp_filter(service, false);
break;
case CONNMAN_SERVICE_STATE_IDLE:
case CONNMAN_SERVICE_STATE_FAILURE:
__connman_ipconfig_disable(ipconfig);
break;
}
if (is_connected(old_state) && !is_connected(new_state))
nameserver_remove_all(service, type);
if (type == CONNMAN_IPCONFIG_TYPE_IPV4)
service->state_ipv4 = new_state;
else
service->state_ipv6 = new_state;
if (!is_connected(old_state) && is_connected(new_state))
nameserver_add_all(service, type);
__connman_timeserver_sync(service);
return service_indicate_state(service);
}
static bool prepare_network(struct connman_service *service)
{
enum connman_network_type type;
unsigned int ssid_len;
type = connman_network_get_type(service->network);
switch (type) {
case CONNMAN_NETWORK_TYPE_UNKNOWN:
case CONNMAN_NETWORK_TYPE_VENDOR:
return false;
case CONNMAN_NETWORK_TYPE_WIFI:
if (!connman_network_get_blob(service->network, "WiFi.SSID",
&ssid_len))
return false;
if (service->passphrase)
connman_network_set_string(service->network,
"WiFi.Passphrase", service->passphrase);
break;
case CONNMAN_NETWORK_TYPE_ETHERNET:
case CONNMAN_NETWORK_TYPE_GADGET:
case CONNMAN_NETWORK_TYPE_BLUETOOTH_PAN:
case CONNMAN_NETWORK_TYPE_BLUETOOTH_DUN:
case CONNMAN_NETWORK_TYPE_CELLULAR:
break;
}
return true;
}
static void prepare_8021x(struct connman_service *service)
{
if (service->eap)
connman_network_set_string(service->network, "WiFi.EAP",
service->eap);
if (service->identity)
connman_network_set_string(service->network, "WiFi.Identity",
service->identity);
if (service->anonymous_identity)
connman_network_set_string(service->network,
"WiFi.AnonymousIdentity",
service->anonymous_identity);
if (service->ca_cert_file)
connman_network_set_string(service->network, "WiFi.CACertFile",
service->ca_cert_file);
if (service->subject_match)
connman_network_set_string(service->network, "WiFi.SubjectMatch",
service->subject_match);
if (service->altsubject_match)
connman_network_set_string(service->network, "WiFi.AltSubjectMatch",
service->altsubject_match);
if (service->domain_suffix_match)
connman_network_set_string(service->network, "WiFi.DomainSuffixMatch",
service->domain_suffix_match);
if (service->domain_match)
connman_network_set_string(service->network, "WiFi.DomainMatch",
service->domain_match);
if (service->client_cert_file)
connman_network_set_string(service->network,
"WiFi.ClientCertFile",
service->client_cert_file);
if (service->private_key_file)
connman_network_set_string(service->network,
"WiFi.PrivateKeyFile",
service->private_key_file);
if (service->private_key_passphrase)
connman_network_set_string(service->network,
"WiFi.PrivateKeyPassphrase",
service->private_key_passphrase);
if (service->phase2)
connman_network_set_string(service->network, "WiFi.Phase2",
service->phase2);
}
static int service_connect(struct connman_service *service)
{
int err;
if (service->hidden)
return -EPERM;
switch (service->type) {
case CONNMAN_SERVICE_TYPE_UNKNOWN:
case CONNMAN_SERVICE_TYPE_SYSTEM:
case CONNMAN_SERVICE_TYPE_GPS:
case CONNMAN_SERVICE_TYPE_P2P:
return -EINVAL;
case CONNMAN_SERVICE_TYPE_ETHERNET:
case CONNMAN_SERVICE_TYPE_GADGET:
case CONNMAN_SERVICE_TYPE_BLUETOOTH:
case CONNMAN_SERVICE_TYPE_CELLULAR:
case CONNMAN_SERVICE_TYPE_VPN:
break;
case CONNMAN_SERVICE_TYPE_WIFI:
switch (service->security) {
case CONNMAN_SERVICE_SECURITY_UNKNOWN:
case CONNMAN_SERVICE_SECURITY_NONE:
break;
case CONNMAN_SERVICE_SECURITY_WEP:
case CONNMAN_SERVICE_SECURITY_PSK:
case CONNMAN_SERVICE_SECURITY_WPA:
case CONNMAN_SERVICE_SECURITY_RSN:
if (service->error == CONNMAN_SERVICE_ERROR_INVALID_KEY)
return -ENOKEY;
if (!service->passphrase) {
if (!service->network)
return -EOPNOTSUPP;
if (!service->wps ||
!connman_network_get_bool(service->network, "WiFi.UseWPS"))
return -ENOKEY;
}
break;
case CONNMAN_SERVICE_SECURITY_8021X:
if (!service->eap) {
connman_warn("EAP type has not been found. "
"Most likely ConnMan is not able to "
"find a configuration for given "
"8021X network. "
"Check SSID or Name match with the "
"network name.");
return -EINVAL;
}
/*
* never request credentials if using EAP-TLS
* (EAP-TLS networks need to be fully provisioned)
*/
if (g_str_equal(service->eap, "tls"))
break;
/*
* Return -ENOKEY if either identity or passphrase is
* missing. Agent provided credentials can be used as
* fallback if needed.
*/
if (((!service->identity &&
!service->agent_identity) ||
!service->passphrase) ||
service->error == CONNMAN_SERVICE_ERROR_INVALID_KEY)
return -ENOKEY;
break;
}
break;
}
if (service->network) {
if (!prepare_network(service))
return -EINVAL;
switch (service->security) {
case CONNMAN_SERVICE_SECURITY_UNKNOWN:
case CONNMAN_SERVICE_SECURITY_NONE:
case CONNMAN_SERVICE_SECURITY_WEP:
case CONNMAN_SERVICE_SECURITY_PSK:
case CONNMAN_SERVICE_SECURITY_WPA:
case CONNMAN_SERVICE_SECURITY_RSN:
break;
case CONNMAN_SERVICE_SECURITY_8021X:
prepare_8021x(service);
break;
}
if (__connman_stats_service_register(service) == 0) {
__connman_stats_get(service, false,
&service->stats.data);
__connman_stats_get(service, true,
&service->stats_roaming.data);
}
err = __connman_network_connect(service->network);
} else if (service->type == CONNMAN_SERVICE_TYPE_VPN &&
service->provider)
err = __connman_provider_connect(service->provider,
get_dbus_sender(service));
else
return -EOPNOTSUPP;
if (err < 0) {
if (err != -EINPROGRESS) {
__connman_service_ipconfig_indicate_state(service,
CONNMAN_SERVICE_STATE_FAILURE,
CONNMAN_IPCONFIG_TYPE_IPV4);
__connman_service_ipconfig_indicate_state(service,
CONNMAN_SERVICE_STATE_FAILURE,
CONNMAN_IPCONFIG_TYPE_IPV6);
__connman_stats_service_unregister(service);
}
}
return err;
}
int __connman_service_connect(struct connman_service *service,
enum connman_service_connect_reason reason)
{
int err;
DBG("service %p state %s connect reason %s -> %s",
service, state2string(service->state),
reason2string(service->connect_reason),
reason2string(reason));
if (is_connected(service->state))
return -EISCONN;
if (is_connecting(service->state))
return -EALREADY;
switch (service->type) {
case CONNMAN_SERVICE_TYPE_UNKNOWN:
case CONNMAN_SERVICE_TYPE_SYSTEM:
case CONNMAN_SERVICE_TYPE_GPS:
case CONNMAN_SERVICE_TYPE_P2P:
return -EINVAL;
case CONNMAN_SERVICE_TYPE_ETHERNET:
case CONNMAN_SERVICE_TYPE_GADGET:
case CONNMAN_SERVICE_TYPE_BLUETOOTH:
case CONNMAN_SERVICE_TYPE_CELLULAR:
case CONNMAN_SERVICE_TYPE_VPN:
case CONNMAN_SERVICE_TYPE_WIFI:
break;
}
if (!is_ipconfig_usable(service))
return -ENOLINK;
__connman_service_clear_error(service);
err = service_connect(service);
DBG("service %p err %d", service, err);
service->connect_reason = reason;
if (err >= 0)
return 0;
if (err == -EINPROGRESS) {
if (service->timeout == 0)
service->timeout = g_timeout_add_seconds(
CONNECT_TIMEOUT, connect_timeout, service);
return -EINPROGRESS;
}
if (service->network)
__connman_network_disconnect(service->network);
else if (service->type == CONNMAN_SERVICE_TYPE_VPN &&
service->provider)
connman_provider_disconnect(service->provider);
if (service->connect_reason == CONNMAN_SERVICE_CONNECT_REASON_USER) {
if (err == -ENOKEY || err == -EPERM) {
DBusMessage *pending = NULL;
const char *dbus_sender = get_dbus_sender(service);
/*
* We steal the reply here. The idea is that the
* connecting client will see the connection status
* after the real hidden network is connected or
* connection failed.
*/
if (service->hidden) {
pending = service->pending;
service->pending = NULL;
}
err = __connman_agent_request_passphrase_input(service,
request_input_cb,
dbus_sender,
pending);
if (service->hidden && err != -EINPROGRESS)
service->pending = pending;
return err;
}
reply_pending(service, -err);
}
return err;
}
int __connman_service_disconnect(struct connman_service *service)
{
int err;
DBG("service %p", service);
service->connect_reason = CONNMAN_SERVICE_CONNECT_REASON_NONE;
service->proxy = CONNMAN_SERVICE_PROXY_METHOD_UNKNOWN;
connman_agent_cancel(service);
reply_pending(service, ECONNABORTED);
__connman_stats_service_unregister(service);
if (service->network) {
err = __connman_network_disconnect(service->network);
} else if (service->type == CONNMAN_SERVICE_TYPE_VPN &&
service->provider)
err = connman_provider_disconnect(service->provider);
else
return -EOPNOTSUPP;
if (err < 0 && err != -EINPROGRESS)
return err;
__connman_6to4_remove(service->ipconfig_ipv4);
if (service->ipconfig_ipv4)
__connman_ipconfig_set_proxy_autoconfig(service->ipconfig_ipv4,
NULL);
else
__connman_ipconfig_set_proxy_autoconfig(service->ipconfig_ipv6,
NULL);
__connman_ipconfig_address_remove(service->ipconfig_ipv4);
settings_changed(service, service->ipconfig_ipv4);
__connman_ipconfig_address_remove(service->ipconfig_ipv6);
settings_changed(service, service->ipconfig_ipv6);
__connman_ipconfig_disable(service->ipconfig_ipv4);
__connman_ipconfig_disable(service->ipconfig_ipv6);
return err;
}
int __connman_service_disconnect_all(void)
{
struct connman_service *service;
GSList *services = NULL, *list;
GList *iter;
DBG("");
for (iter = service_list; iter; iter = iter->next) {
service = iter->data;
if (!is_connected(service->state))
break;
services = g_slist_prepend(services, service);
}
for (list = services; list; list = list->next) {
struct connman_service *service = list->data;
service->ignore = true;
__connman_service_disconnect(service);
}
g_slist_free(services);
return 0;
}
/**
* lookup_by_identifier:
* @identifier: service identifier
*
* Look up a service by identifier (reference count will not be increased)
*/
static struct connman_service *lookup_by_identifier(const char *identifier)
{
return g_hash_table_lookup(service_hash, identifier);
}
struct connman_service *connman_service_lookup_from_identifier(const char* identifier)
{
return lookup_by_identifier(identifier);
}
struct provision_user_data {
const char *ident;
int ret;
};
static void provision_changed(gpointer value, gpointer user_data)
{
struct connman_service *service = value;
struct provision_user_data *data = user_data;
const char *path = data->ident;
int ret;
ret = __connman_config_provision_service_ident(service, path,
service->config_file, service->config_entry);
if (ret > 0)
data->ret = ret;
}
int __connman_service_provision_changed(const char *ident)
{
struct provision_user_data data = {
.ident = ident,
.ret = 0
};
g_list_foreach(service_list, provision_changed, (void *)&data);
/*
* Because the provision_changed() might have set some services
* as favorite, we must sort the sequence now.
*/
if (services_dirty) {
services_dirty = false;
service_list_sort();
__connman_connection_update_gateway();
}
return data.ret;
}
void __connman_service_set_config(struct connman_service *service,
const char *file_id, const char *entry)
{
if (!service)
return;
g_free(service->config_file);
service->config_file = g_strdup(file_id);
g_free(service->config_entry);
service->config_entry = g_strdup(entry);
}
/**
* __connman_service_get:
* @identifier: service identifier
*
* Look up a service by identifier or create a new one if not found
*/
static struct connman_service *service_get(const char *identifier)
{
struct connman_service *service;
service = g_hash_table_lookup(service_hash, identifier);
if (service) {
connman_service_ref(service);
return service;
}
service = connman_service_create();
if (!service)
return NULL;
DBG("service %p", service);
service->identifier = g_strdup(identifier);
service_list = g_list_insert_sorted(service_list, service,
service_compare);
g_hash_table_insert(service_hash, service->identifier, service);
return service;
}
static int service_register(struct connman_service *service)
{
DBG("service %p", service);
if (service->path)
return -EALREADY;
service->path = g_strdup_printf("%s/service/%s", CONNMAN_PATH,
service->identifier);
DBG("path %s", service->path);
if (__connman_config_provision_service(service) < 0)
service_load(service);
g_dbus_register_interface(connection, service->path,
CONNMAN_SERVICE_INTERFACE,
service_methods, service_signals,
NULL, service, NULL);
service_list_sort();
__connman_connection_update_gateway();
return 0;
}
static void service_up(struct connman_ipconfig *ipconfig,
const char *ifname)
{
struct connman_service *service = __connman_ipconfig_get_data(ipconfig);
DBG("%s up", ifname);
link_changed(service);
service->stats.valid = false;
service->stats_roaming.valid = false;
}
static void service_down(struct connman_ipconfig *ipconfig,
const char *ifname)
{
DBG("%s down", ifname);
}
static void service_lower_up(struct connman_ipconfig *ipconfig,
const char *ifname)
{
struct connman_service *service = __connman_ipconfig_get_data(ipconfig);
DBG("%s lower up", ifname);
stats_start(service);
}
static void service_lower_down(struct connman_ipconfig *ipconfig,
const char *ifname)
{
struct connman_service *service = __connman_ipconfig_get_data(ipconfig);
DBG("%s lower down", ifname);
stats_stop(service);
service_save(service);
}
static void service_ip_bound(struct connman_ipconfig *ipconfig,
const char *ifname)
{
struct connman_service *service = __connman_ipconfig_get_data(ipconfig);
enum connman_ipconfig_method method = CONNMAN_IPCONFIG_METHOD_UNKNOWN;
enum connman_ipconfig_type type = CONNMAN_IPCONFIG_TYPE_UNKNOWN;
DBG("%s ip bound", ifname);
type = __connman_ipconfig_get_config_type(ipconfig);
method = __connman_ipconfig_get_method(ipconfig);
DBG("service %p ipconfig %p type %d method %d", service, ipconfig,
type, method);
if (type == CONNMAN_IPCONFIG_TYPE_IPV6 &&
method == CONNMAN_IPCONFIG_METHOD_AUTO)
__connman_service_ipconfig_indicate_state(service,
CONNMAN_SERVICE_STATE_READY,
CONNMAN_IPCONFIG_TYPE_IPV6);
settings_changed(service, ipconfig);
address_updated(service, type);
}
static void service_ip_release(struct connman_ipconfig *ipconfig,
const char *ifname)
{
struct connman_service *service = __connman_ipconfig_get_data(ipconfig);
enum connman_ipconfig_method method = CONNMAN_IPCONFIG_METHOD_UNKNOWN;
enum connman_ipconfig_type type = CONNMAN_IPCONFIG_TYPE_UNKNOWN;
DBG("%s ip release", ifname);
type = __connman_ipconfig_get_config_type(ipconfig);
method = __connman_ipconfig_get_method(ipconfig);
DBG("service %p ipconfig %p type %d method %d", service, ipconfig,
type, method);
if (type == CONNMAN_IPCONFIG_TYPE_IPV6 &&
method == CONNMAN_IPCONFIG_METHOD_OFF)
__connman_service_ipconfig_indicate_state(service,
CONNMAN_SERVICE_STATE_DISCONNECT,
CONNMAN_IPCONFIG_TYPE_IPV6);
if (type == CONNMAN_IPCONFIG_TYPE_IPV4 &&
method == CONNMAN_IPCONFIG_METHOD_OFF)
__connman_service_ipconfig_indicate_state(service,
CONNMAN_SERVICE_STATE_DISCONNECT,
CONNMAN_IPCONFIG_TYPE_IPV4);
settings_changed(service, ipconfig);
}
static void service_route_changed(struct connman_ipconfig *ipconfig,
const char *ifname)
{
struct connman_service *service = __connman_ipconfig_get_data(ipconfig);
DBG("%s route changed", ifname);
settings_changed(service, ipconfig);
}
static const struct connman_ipconfig_ops service_ops = {
.up = service_up,
.down = service_down,
.lower_up = service_lower_up,
.lower_down = service_lower_down,
.ip_bound = service_ip_bound,
.ip_release = service_ip_release,
.route_set = service_route_changed,
.route_unset = service_route_changed,
};
static struct connman_ipconfig *create_ip4config(struct connman_service *service,
int index, int original_index, enum connman_ipconfig_method method)
{
struct connman_ipconfig *ipconfig_ipv4;
ipconfig_ipv4 = __connman_ipconfig_create(index, original_index,
CONNMAN_IPCONFIG_TYPE_IPV4);
if (!ipconfig_ipv4)
return NULL;
__connman_ipconfig_set_method(ipconfig_ipv4, method);
__connman_ipconfig_set_data(ipconfig_ipv4, service);
__connman_ipconfig_set_ops(ipconfig_ipv4, &service_ops);
return ipconfig_ipv4;
}
static struct connman_ipconfig *create_ip6config(struct connman_service *service,
int index, int original_index)
{
struct connman_ipconfig *ipconfig_ipv6;
ipconfig_ipv6 = __connman_ipconfig_create(index, original_index,
CONNMAN_IPCONFIG_TYPE_IPV6);
if (!ipconfig_ipv6)
return NULL;
__connman_ipconfig_set_data(ipconfig_ipv6, service);
__connman_ipconfig_set_ops(ipconfig_ipv6, &service_ops);
return ipconfig_ipv6;
}
void __connman_service_read_ip4config(struct connman_service *service)
{
GKeyFile *keyfile;
if (!service->ipconfig_ipv4)
return;
keyfile = connman_storage_load_service(service->identifier);
if (!keyfile)
return;
__connman_ipconfig_load(service->ipconfig_ipv4, keyfile,
service->identifier, "IPv4.");
g_key_file_free(keyfile);
}
void connman_service_create_ip4config(struct connman_service *service,
int index, int original_index)
{
DBG("ipv4 %p", service->ipconfig_ipv4);
if (service->ipconfig_ipv4)
return;
service->ipconfig_ipv4 = create_ip4config(service, index, original_index,
CONNMAN_IPCONFIG_METHOD_DHCP);
__connman_service_read_ip4config(service);
}
void __connman_service_read_ip6config(struct connman_service *service)
{
GKeyFile *keyfile;
if (!service->ipconfig_ipv6)
return;
keyfile = connman_storage_load_service(service->identifier);
if (!keyfile)
return;
__connman_ipconfig_load(service->ipconfig_ipv6, keyfile,
service->identifier, "IPv6.");
g_key_file_free(keyfile);
}
void connman_service_create_ip6config(struct connman_service *service,
int index, int original_index)
{
DBG("ipv6 %p", service->ipconfig_ipv6);
if (service->ipconfig_ipv6)
return;
service->ipconfig_ipv6 = create_ip6config(service, index, original_index);
__connman_service_read_ip6config(service);
}
/**
* connman_service_lookup_from_network:
* @network: network structure
*
* Look up a service by network (reference count will not be increased)
*/
struct connman_service *connman_service_lookup_from_network(struct connman_network *network)
{
struct connman_service *service;
const char *ident, *group;
char *name;
if (!network)
return NULL;
ident = __connman_network_get_ident(network);
if (!ident)
return NULL;
group = connman_network_get_group(network);
if (!group)
return NULL;
name = g_strdup_printf("%s_%s_%s",
__connman_network_get_type(network), ident, group);
service = lookup_by_identifier(name);
g_free(name);
return service;
}
struct connman_service *__connman_service_lookup_from_index(int index)
{
struct connman_service *service;
GList *list;
for (list = service_list; list; list = list->next) {
service = list->data;
if (__connman_ipconfig_get_index(service->ipconfig_ipv4)
== index)
return service;
if (__connman_ipconfig_get_index(service->ipconfig_ipv6)
== index)
return service;
}
return NULL;
}
struct connman_service *connman_service_lookup_from_interface(const char *interface)
{
GList *list;
for (list = service_list; list; list = list->next) {
struct connman_service *service = list->data;
if (!service->network)
continue;
struct connman_device *device = connman_network_get_device(service->network);
if (!device)
continue;
if (g_strcmp0(connman_device_get_string(device, "Interface"), interface) == 0)
return service;
}
return NULL;
}
struct connman_service *__connman_service_lookup_from_ident(const char *identifier)
{
return lookup_by_identifier(identifier);
}
const char *__connman_service_get_ident(struct connman_service *service)
{
return service->identifier;
}
const char *__connman_service_get_path(struct connman_service *service)
{
return service->path;
}
const char *__connman_service_get_name(struct connman_service *service)
{
return service->name;
}
enum connman_service_state __connman_service_get_state(struct connman_service *service)
{
return service->state;
}
unsigned int __connman_service_get_order(struct connman_service *service)
{
unsigned int order = 0;
if (!service)
return 0;
service->order = 0;
if (!service->favorite)
return 0;
if (service == service_list->data)
order = 1;
if (service->type == CONNMAN_SERVICE_TYPE_VPN &&
!service->do_split_routing) {
service->order = 10;
order = 10;
}
DBG("service %p name %s order %d split %d", service, service->name,
order, service->do_split_routing);
return order;
}
static enum connman_service_type convert_network_type(struct connman_network *network)
{
enum connman_network_type type = connman_network_get_type(network);
switch (type) {
case CONNMAN_NETWORK_TYPE_UNKNOWN:
case CONNMAN_NETWORK_TYPE_VENDOR:
break;
case CONNMAN_NETWORK_TYPE_ETHERNET:
return CONNMAN_SERVICE_TYPE_ETHERNET;
case CONNMAN_NETWORK_TYPE_WIFI:
return CONNMAN_SERVICE_TYPE_WIFI;
case CONNMAN_NETWORK_TYPE_BLUETOOTH_PAN:
case CONNMAN_NETWORK_TYPE_BLUETOOTH_DUN:
return CONNMAN_SERVICE_TYPE_BLUETOOTH;
case CONNMAN_NETWORK_TYPE_CELLULAR:
return CONNMAN_SERVICE_TYPE_CELLULAR;
case CONNMAN_NETWORK_TYPE_GADGET:
return CONNMAN_SERVICE_TYPE_GADGET;
}
return CONNMAN_SERVICE_TYPE_UNKNOWN;
}
static enum connman_service_security convert_wifi_security(const char *security)
{
if (!security)
return CONNMAN_SERVICE_SECURITY_UNKNOWN;
else if (g_str_equal(security, "none"))
return CONNMAN_SERVICE_SECURITY_NONE;
else if (g_str_equal(security, "wep"))
return CONNMAN_SERVICE_SECURITY_WEP;
else if (g_str_equal(security, "psk"))
return CONNMAN_SERVICE_SECURITY_PSK;
else if (g_str_equal(security, "ieee8021x"))
return CONNMAN_SERVICE_SECURITY_8021X;
else if (g_str_equal(security, "wpa"))
return CONNMAN_SERVICE_SECURITY_WPA;
else if (g_str_equal(security, "rsn"))
return CONNMAN_SERVICE_SECURITY_RSN;
else
return CONNMAN_SERVICE_SECURITY_UNKNOWN;
}
static void update_wps_values(struct connman_service *service,
struct connman_network *network)
{
bool wps = connman_network_get_bool(network, "WiFi.WPS");
bool wps_advertising = connman_network_get_bool(network,
"WiFi.WPSAdvertising");
if (service->wps != wps ||
service->wps_advertizing != wps_advertising) {
service->wps = wps;
service->wps_advertizing = wps_advertising;
security_changed(service);
}
}
static void update_from_network(struct connman_service *service,
struct connman_network *network)
{
uint8_t strength = service->strength;
const char *str;
DBG("service %p network %p", service, network);
if (is_connected(service->state))
return;
if (is_connecting(service->state))
return;
str = connman_network_get_string(network, "Name");
if (str) {
g_free(service->name);
service->name = g_strdup(str);
service->hidden = false;
} else {
g_free(service->name);
service->name = NULL;
service->hidden = true;
}
service->strength = connman_network_get_strength(network);
service->roaming = connman_network_get_bool(network, "Roaming");
if (service->strength == 0) {
/*
* Filter out 0-values; it's unclear what they mean
* and they cause anomalous sorting of the priority list.
*/
service->strength = strength;
}
str = connman_network_get_string(network, "WiFi.Security");
service->security = convert_wifi_security(str);
if (service->type == CONNMAN_SERVICE_TYPE_WIFI)
update_wps_values(service, network);
if (service->strength > strength && service->network) {
connman_network_unref(service->network);
service->network = connman_network_ref(network);
strength_changed(service);
}
if (!service->network)
service->network = connman_network_ref(network);
service_list_sort();
}
/**
* __connman_service_create_from_network:
* @network: network structure
*
* Look up service by network and if not found, create one
*/
struct connman_service * __connman_service_create_from_network(struct connman_network *network)
{
struct connman_service *service;
struct connman_device *device;
const char *ident, *group;
char *name;
unsigned int *auto_connect_types;
int i, index, original_index;
DBG("network %p", network);
if (!network)
return NULL;
ident = __connman_network_get_ident(network);
if (!ident)
return NULL;
group = connman_network_get_group(network);
if (!group)
return NULL;
device = connman_network_get_device(network);
if (device && g_strcmp0(connman_device_get_string(device, "Interface"), "eth1") == 0) {
// Don't create a service for eth1, as we are using it only as part of a bridged setup.
// This avoids problems with two DHCP clients trying to run on the same network interface
// (tether).
DBG("skipping creation of service for eth1");
return NULL;
}
name = g_strdup_printf("%s_%s_%s",
__connman_network_get_type(network), ident, group);
service = service_get(name);
g_free(name);
if (!service)
return NULL;
if (__connman_network_get_weakness(network))
return service;
if (service->path) {
update_from_network(service, network);
__connman_connection_update_gateway();
return service;
}
service->type = convert_network_type(network);
auto_connect_types = connman_setting_get_uint_list("DefaultAutoConnectTechnologies");
service->autoconnect = false;
for (i = 0; auto_connect_types &&
auto_connect_types[i] != 0; i++) {
if (service->type == auto_connect_types[i]) {
service->autoconnect = true;
break;
}
}
switch (service->type) {
case CONNMAN_SERVICE_TYPE_UNKNOWN:
case CONNMAN_SERVICE_TYPE_SYSTEM:
case CONNMAN_SERVICE_TYPE_BLUETOOTH:
case CONNMAN_SERVICE_TYPE_GPS:
case CONNMAN_SERVICE_TYPE_VPN:
case CONNMAN_SERVICE_TYPE_GADGET:
case CONNMAN_SERVICE_TYPE_WIFI:
case CONNMAN_SERVICE_TYPE_CELLULAR:
case CONNMAN_SERVICE_TYPE_P2P:
break;
case CONNMAN_SERVICE_TYPE_ETHERNET:
service->favorite = true;
break;
}
service->state_ipv4 = service->state_ipv6 = CONNMAN_SERVICE_STATE_IDLE;
service->state = combine_state(service->state_ipv4, service->state_ipv6);
update_from_network(service, network);
index = connman_network_get_index(network);
original_index = connman_network_get_original_index(network);
if (!service->ipconfig_ipv4)
service->ipconfig_ipv4 = create_ip4config(service, index, original_index,
CONNMAN_IPCONFIG_METHOD_DHCP);
if (!service->ipconfig_ipv6)
service->ipconfig_ipv6 = create_ip6config(service, index, original_index);
service_register(service);
service_schedule_added(service);
if (service->favorite) {
if (device && !connman_device_get_scanning(device,
CONNMAN_SERVICE_TYPE_UNKNOWN)) {
switch (service->type) {
case CONNMAN_SERVICE_TYPE_UNKNOWN:
case CONNMAN_SERVICE_TYPE_SYSTEM:
case CONNMAN_SERVICE_TYPE_P2P:
break;
case CONNMAN_SERVICE_TYPE_GADGET:
case CONNMAN_SERVICE_TYPE_ETHERNET:
if (service->autoconnect) {
__connman_service_connect(service,
CONNMAN_SERVICE_CONNECT_REASON_AUTO);
break;
}
/* fall through */
case CONNMAN_SERVICE_TYPE_BLUETOOTH:
case CONNMAN_SERVICE_TYPE_GPS:
case CONNMAN_SERVICE_TYPE_VPN:
case CONNMAN_SERVICE_TYPE_WIFI:
case CONNMAN_SERVICE_TYPE_CELLULAR:
__connman_service_auto_connect(CONNMAN_SERVICE_CONNECT_REASON_AUTO);
break;
}
}
}
__connman_notifier_service_add(service, service->name);
return service;
}
void __connman_service_update_from_network(struct connman_network *network)
{
bool need_sort = false;
struct connman_service *service;
uint8_t strength;
bool roaming;
const char *name;
bool stats_enable;
service = connman_service_lookup_from_network(network);
if (!service)
return;
if (!service->network)
return;
name = connman_network_get_string(service->network, "Name");
if (g_strcmp0(service->name, name) != 0) {
g_free(service->name);
service->name = g_strdup(name);
if (allow_property_changed(service))
connman_dbus_property_changed_basic(service->path,
CONNMAN_SERVICE_INTERFACE, "Name",
DBUS_TYPE_STRING, &service->name);
}
if (service->type == CONNMAN_SERVICE_TYPE_WIFI)
update_wps_values(service, network);
strength = connman_network_get_strength(service->network);
if (strength == service->strength)
goto roaming;
service->strength = strength;
need_sort = true;
strength_changed(service);
roaming:
roaming = connman_network_get_bool(service->network, "Roaming");
if (roaming == service->roaming)
goto sorting;
stats_enable = stats_enabled(service);
if (stats_enable)
stats_stop(service);
service->roaming = roaming;
need_sort = true;
if (stats_enable)
stats_start(service);
roaming_changed(service);
sorting:
if (need_sort) {
service_list_sort();
}
}
void __connman_service_remove_from_network(struct connman_network *network)
{
struct connman_service *service;
service = connman_service_lookup_from_network(network);
DBG("network %p service %p", network, service);
if (!service)
return;
service->ignore = true;
__connman_connection_gateway_remove(service,
CONNMAN_IPCONFIG_TYPE_ALL);
connman_service_unref(service);
}
/**
* __connman_service_create_from_provider:
* @provider: provider structure
*
* Look up service by provider and if not found, create one
*/
struct connman_service *
__connman_service_create_from_provider(struct connman_provider *provider)
{
struct connman_service *service;
const char *ident, *str;
char *name;
int index = connman_provider_get_index(provider);
DBG("provider %p", provider);
ident = __connman_provider_get_ident(provider);
if (!ident)
return NULL;
name = g_strdup_printf("vpn_%s", ident);
service = service_get(name);
g_free(name);
if (!service)
return NULL;
service->type = CONNMAN_SERVICE_TYPE_VPN;
service->provider = connman_provider_ref(provider);
service->autoconnect = false;
service->favorite = true;
service->state_ipv4 = service->state_ipv6 = CONNMAN_SERVICE_STATE_IDLE;
service->state = combine_state(service->state_ipv4, service->state_ipv6);
str = connman_provider_get_string(provider, "Name");
if (str) {
g_free(service->name);
service->name = g_strdup(str);
service->hidden = false;
} else {
g_free(service->name);
service->name = NULL;
service->hidden = true;
}
service->strength = 0;
if (!service->ipconfig_ipv4)
service->ipconfig_ipv4 = create_ip4config(service, index, index,
CONNMAN_IPCONFIG_METHOD_MANUAL);
if (!service->ipconfig_ipv6)
service->ipconfig_ipv6 = create_ip6config(service, index, index);
service_register(service);
__connman_notifier_service_add(service, service->name);
service_schedule_added(service);
return service;
}
static void remove_unprovisioned_services(void)
{
gchar **services;
GKeyFile *keyfile, *configkeyfile;
char *file, *section;
int i = 0;
services = connman_storage_get_services();
if (!services)
return;
for (; services[i]; i++) {
file = section = NULL;
keyfile = configkeyfile = NULL;
keyfile = connman_storage_load_service(services[i]);
if (!keyfile)
continue;
file = g_key_file_get_string(keyfile, services[i],
"Config.file", NULL);
if (!file)
goto next;
section = g_key_file_get_string(keyfile, services[i],
"Config.ident", NULL);
if (!section)
goto next;
configkeyfile = __connman_storage_load_config(file);
if (!configkeyfile) {
/*
* Config file is missing, remove the provisioned
* service.
*/
__connman_storage_remove_service(services[i]);
goto next;
}
if (!g_key_file_has_group(configkeyfile, section))
/*
* Config section is missing, remove the provisioned
* service.
*/
__connman_storage_remove_service(services[i]);
next:
if (keyfile)
g_key_file_free(keyfile);
if (configkeyfile)
g_key_file_free(configkeyfile);
g_free(section);
g_free(file);
}
g_strfreev(services);
}
static int agent_probe(struct connman_agent *agent)
{
DBG("agent %p", agent);
return 0;
}
static void agent_remove(struct connman_agent *agent)
{
DBG("agent %p", agent);
}
static void *agent_context_ref(void *context)
{
struct connman_service *service = context;
return (void *)connman_service_ref(service);
}
static void agent_context_unref(void *context)
{
struct connman_service *service = context;
connman_service_unref(service);
}
static struct connman_agent_driver agent_driver = {
.name = "service",
.interface = CONNMAN_AGENT_INTERFACE,
.probe = agent_probe,
.remove = agent_remove,
.context_ref = agent_context_ref,
.context_unref = agent_context_unref,
};
int __connman_service_init(void)
{
int err;
DBG("");
err = connman_agent_driver_register(&agent_driver);
if (err < 0) {
connman_error("Cannot register agent driver for %s",
agent_driver.name);
return err;
}
set_always_connecting_technologies();
connection = connman_dbus_get_connection();
service_hash = g_hash_table_new_full(g_str_hash, g_str_equal,
NULL, service_free);
services_notify = g_new0(struct _services_notify, 1);
services_notify->remove = g_hash_table_new_full(g_str_hash,
g_str_equal, g_free, NULL);
services_notify->add = g_hash_table_new(g_str_hash, g_str_equal);
remove_unprovisioned_services();
return 0;
}
void __connman_service_cleanup(void)
{
DBG("");
if (vpn_autoconnect_id) {
g_source_remove(vpn_autoconnect_id);
vpn_autoconnect_id = 0;
}
if (autoconnect_id != 0) {
g_source_remove(autoconnect_id);
autoconnect_id = 0;
}
connman_agent_driver_unregister(&agent_driver);
g_list_free(service_list);
service_list = NULL;
g_hash_table_destroy(service_hash);
service_hash = NULL;
g_slist_free(counter_list);
counter_list = NULL;
if (services_notify->id != 0) {
g_source_remove(services_notify->id);
service_send_changed(NULL);
}
g_hash_table_destroy(services_notify->remove);
g_hash_table_destroy(services_notify->add);
g_free(services_notify);
dbus_connection_unref(connection);
}
| raumfeld/connman | src/service.c | C | gpl-2.0 | 183,137 |
/*
* cstring.c
*
* Created on: Dec 30, 2014
* Author: muneer
*/
#include "cstring.h"
#include <string.h>
#include <stdlib.h>
t_cstring *cstring_create()
{
t_cstring *str;
str = (t_cstring *) malloc(sizeof(t_cstring));
str->size = 1;
str->value = (char *) malloc(1);
str->value[0] = '\0';
return str;
}
int cstring_delete(t_cstring *string) {
if (string != NULL) {
if (string->value != NULL)
free(string->value);
free (string);
}
return 0;
}
int cstring_add(t_cstring *string, char *s)
{
int new_size = string->size + strlen(s);
string->value = (char *) realloc(string->value, new_size);
if (string->value == NULL)
return -1;
strcat(string->value, s);
string->value[new_size-1] = '\0';
string->size = new_size;
return 0;
}
| imuneer/cstring | cstring.c | C | gpl-2.0 | 764 |
/***************************************************************************
qgsmeshdatasetgroupstore.h
---------------------
begin : June 2020
copyright : (C) 2020 by Vincent Cloarec
email : vcloarec at gmail dot 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. *
* *
***************************************************************************/
#ifndef QGSMESHDATASETGROUPSTORE_H
#define QGSMESHDATASETGROUPSTORE_H
#define SIP_NO_FILE
#include "qgsmeshdataprovider.h"
#include "qgsmeshdataset.h"
/**
* \ingroup core
*
* Class that can be used to store and access extra dataset group, like memory dataset (temporary)
* Derived from QgsMeshDatasetSourceInterface, this class has same methods as QgsMeshDataProvider to access to the datasets.
*
* \since QGIS 3.16
*/
class QgsMeshExtraDatasetStore: public QgsMeshDatasetSourceInterface
{
public:
//! Adds a dataset group
void addDatasetGroup( QgsMeshDatasetGroup *datasetGroup );
//! Removes the dataset group with the local \a index
void removeDatasetGroup( int index );
//! Returns whether if the dataset groups have temporal capabilities (a least one dataset group with more than one dataset)
bool hasTemporalCapabilities() const;
//! Returns the relative times of the dataset index with \a index, returned value in miliseconds
quint64 datasetRelativeTime( QgsMeshDatasetIndex index );
int datasetGroupCount() const override;
int datasetCount( int groupIndex ) const override;
QgsMeshDatasetGroupMetadata datasetGroupMetadata( int groupIndex ) const override;
QgsMeshDatasetMetadata datasetMetadata( QgsMeshDatasetIndex index ) const override;
QgsMeshDatasetValue datasetValue( QgsMeshDatasetIndex index, int valueIndex ) const override;
QgsMeshDataBlock datasetValues( QgsMeshDatasetIndex index, int valueIndex, int count ) const override;
QgsMesh3dDataBlock dataset3dValues( QgsMeshDatasetIndex index, int faceIndex, int count ) const override;
bool isFaceActive( QgsMeshDatasetIndex index, int faceIndex ) const override;
QgsMeshDataBlock areFacesActive( QgsMeshDatasetIndex index, int faceIndex, int count ) const override;
//! Not implemented, always returns false
bool addDataset( const QString &uri ) override;
//! Not implemented, always returns empty list
QStringList extraDatasets() const override;
//! Not implemented, always returns true
bool persistDatasetGroup( const QString &outputFilePath,
const QString &outputDriver,
const QgsMeshDatasetGroupMetadata &meta,
const QVector<QgsMeshDataBlock> &datasetValues,
const QVector<QgsMeshDataBlock> &datasetActive,
const QVector<double> × ) override;
//! Not implemented, always returns true
bool persistDatasetGroup( const QString &outputFilePath,
const QString &outputDriver,
QgsMeshDatasetSourceInterface *source,
int datasetGroupIndex ) override;
private:
std::vector<std::unique_ptr<QgsMeshDatasetGroup>> mGroups;
};
/**
* \ingroup core
*
* Class used to register and access all the dataset groups related to a mesh layer
*
* The registered dataset group are :
*
* - the ones from the data provider of the mesh layer
* - extra dataset group that can be added, for example by the mesh calculator
*
* Every dataset group has a unique global index group that can be different from the native index group of the dataset group.
* This storing class has the repsonsability to assign this unique grlobal dataset group index and to link this dataset group index with the dataset group
*
* All dataset values or information needed can be retrieved from a QgsMeshDatasetIndex with the group index corresponding to the global group index.
* The native group index is not exposed and global index can be obtained with datasetGroupIndexes() that returns the list of gloabl index available.
* The dataset index is the same than in the native source (data provider or other dataset source)
*
* This class as also the responsability to handle the dataset group tree item that contain information to display the available dataset (\see QgsMeshDatasetGroupTreeItem)
*
* \since QGIS 3.16
*/
class QgsMeshDatasetGroupStore: public QObject
{
Q_OBJECT
//! Contains a pointer to the dataset source inerface and the index on this dataset groups container
typedef QPair<QgsMeshDatasetSourceInterface *, int> DatasetGroup;
public:
//! Constructor
QgsMeshDatasetGroupStore();
//! Sets the persistent mesh data provider
void setPersistentProvider( QgsMeshDataProvider *provider );
//! Adds persistent datasets from a file with \a path
bool addPersistentDatasets( const QString &path );
/**
* Adds a extra dataset \a group, take ownership
*
* \note as QgsMeshDatasetGroup doesn't support reference time,
* the dataset group is supposed to have the same reference time than the pesristent provider
*/
bool addDatasetGroup( QgsMeshDatasetGroup *group );
//! Saves on a file with \a filePath the dataset groups index with \a groupIndex with the specified \a driver
bool saveDatasetGroup( QString filePath, int groupIndex, QString driver );
//! Resets to default state the dataset groups tree item
void resetDatasetGroupTreeItem();
//! Returns a pointer to the root of the dataset groups tree item
QgsMeshDatasetGroupTreeItem *datasetGroupTreeItem() const;
//! Sets the root of the dataset groups tree item, doesn't take onwnershib but clone the root item
void setDatasetGroupTreeItem( QgsMeshDatasetGroupTreeItem *rootItem );
//! Returns a list of all group indexes
QList<int> datasetGroupIndexes() const;
//! Returns the count of dataset groups
int datasetGroupCount() const;
//! Returns the count of extra dataset groups
int extraDatasetGroupCount() const;
//! Returns the total count of dataset group in the store
int datasetCount( int groupIndex ) const;
//! Returns the metadata of the dataset group with global \a index
QgsMeshDatasetGroupMetadata datasetGroupMetadata( const QgsMeshDatasetIndex &index ) const;
//! Returns the metadata of the dataset with global \a index
QgsMeshDatasetMetadata datasetMetadata( const QgsMeshDatasetIndex &index ) const;
//! Returns the value of the dataset with global \a index and \a valueIndex
QgsMeshDatasetValue datasetValue( const QgsMeshDatasetIndex &index, int valueIndex ) const;
//! Returns \a count values of the dataset with global \a index and from \a valueIndex
QgsMeshDataBlock datasetValues( const QgsMeshDatasetIndex &index, int valueIndex, int count ) const;
//! Returns \a count 3D values of the dataset with global \a index and from \a valueIndex
QgsMesh3dDataBlock dataset3dValues( const QgsMeshDatasetIndex &index, int faceIndex, int count ) const;
//! Returns whether faces are active for particular dataset
QgsMeshDataBlock areFacesActive( const QgsMeshDatasetIndex &index, int faceIndex, int count ) const;
//! Returns whether face is active for particular dataset
bool isFaceActive( const QgsMeshDatasetIndex &index, int faceIndex ) const;
//! Returns the global dataset index of the dataset int the dataset group with \a groupIndex, corresponding to the relative \a time and the check \a method
QgsMeshDatasetIndex datasetIndexAtTime( quint64 time,
int groupIndex,
QgsMeshDataProviderTemporalCapabilities::MatchingTemporalDatasetMethod method ) const;
//! Returns the relative time of the dataset from the persistent provider reference time
quint64 datasetRelativeTime( const QgsMeshDatasetIndex &index ) const;
//! Returns wether at lea&st one of stored dataset group is temporal
bool hasTemporalCapabilities() const;
//! Writes the store's information in a DOM document
QDomElement writeXml( QDomDocument &doc, const QgsReadWriteContext &context );
//! Reads the store's information from a DOM document
void readXml( const QDomElement &storeElem, const QgsReadWriteContext &context );
signals:
//! emited after dataset groups are added
void datasetGroupsAdded( QList<int> indexes );
private slots:
void onPersistentDatasetAdded( int count );
private:
QgsMeshDataProvider *mPersistentProvider = nullptr;
std::unique_ptr<QgsMeshExtraDatasetStore> mExtraDatasets;
QMap < int, DatasetGroup> mRegistery;
std::unique_ptr<QgsMeshDatasetGroupTreeItem> mDatasetGroupTreeRootItem;
void removePersistentProvider();
DatasetGroup datasetGroup( int index ) const;
int newIndex();
int registerDatasetGroup( const DatasetGroup &group );
int nativeIndexToGroupIndex( QgsMeshDatasetSourceInterface *source, int providerIndex );
void createDatasetGroupTreeItems( const QList<int> &indexes );
//! Erases from the where this is store, not from the store (registry and tree item), for peristent dataset group, do nothing
void eraseDatasetGroup( const DatasetGroup &group );
//! Erases from the extra store but not from the main store (e.g. from egistry and from tree item))
void eraseExtraDataset( int indexInExtraStore );
void checkDatasetConsistency( QgsMeshDatasetSourceInterface *source );
void removeUnregisteredItemFromTree();
void unregisterGroupNotPresentInTree();
};
#endif // QGSMESHDATASETGROUPSTORE_H
| havatv/QGIS | src/core/mesh/qgsmeshdatasetgroupstore.h | C | gpl-2.0 | 10,350 |
package de.jeisfeld.randomimage.util;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
/**
* Decoder for animated gif.
*/
public class GifDecoder {
/**
* The maximum stack size.
*/
private static final int MAX_STACK_SIZE = 4096;
/**
* The minimum delay.
*/
public static final int MIN_DELAY = 100;
/**
* The minimum delay enforce threshold.
*/
public static final int MIN_DELAY_ENFORCE_THRESHOLD = 20;
/**
* The input stream for the GIF.
*/
private InputStream mIn;
/**
* Full mImage mWidth.
*/
private int mWidth;
/**
* Full mImage mHeight.
*/
private int mHeight;
/**
* Global color table used.
*/
private boolean mGctFlag;
/**
* Size of global color table.
*/
private int mGctSize;
/**
* iterations; 0 = repeat forever.
*/
private int mLoopCount = 1;
/**
* global color table.
*/
private int[] mGct;
/**
* local color table.
*/
private int[] mLct;
/**
* active color table.
*/
private int[] mAct;
/**
* background color index.
*/
private int mBgIndex;
/**
* background color.
*/
private int mBgColor;
/**
* previous bg color.
*/
private int mLastBgColor;
/**
* local color table flag.
*/
private boolean mLctFlag;
/**
* mInterlace flag.
*/
private boolean mInterlace;
/**
* local color table size.
*/
private int mLctSize;
/**
* current image rectangle x.
*/
private int mIx;
/**
* current image rectangle y.
*/
private int mIy;
/**
* current image rectangle width.
*/
private int mIw;
/**
* current image rectangle height.
*/
private int mIh;
/**
* last image rectangle x.
*/
private int mLrx;
/**
* last image rectangle y.
*/
private int mLry;
/**
* last image rectangle width.
*/
private int mLrw;
/**
* last image rectangle height.
*/
private int mLrh;
/**
* current frame.
*/
private Bitmap mImage;
/**
* previous frame.
*/
private Bitmap mLastBitmap;
/**
* current data block.
*/
private byte[] mBlock = new byte[256]; // MAGIC_NUMBER
/**
* Block size last graphic control extension info.
*/
private int mBlockSize = 0;
/**
* 0=no action; 1=leave mIn place; 2=restore to bg; 3=restore to prev.
*/
private int mDispose = 0;
/**
* Last dispose value.
*/
private int mLastDispose = 0;
/**
* use transparent color.
*/
private boolean mTransparency = false;
/**
* Delay mIn milliseconds.
*/
private int mDelay = 0;
/**
* transparent color index.
*/
private int mTransIndex;
/**
* LZW decoder working array for prefix.
*/
private short[] mPrefix;
/**
* LZW decoder working array for suffix.
*/
private byte[] mSuffix;
/**
* LZW decoder working array for pixelStack.
*/
private byte[] mPixelStack;
/**
* LZW decoder working array for pixels.
*/
private byte[] mPixels;
/**
* mFrames read from current file.
*/
private ArrayList<GifFrame> mFrames;
/**
* number of mFrames.
*/
private int mFrameCount;
/**
* flag indicating read complete.
*/
private boolean mReadComplete;
/**
* Default constructor.
*/
public GifDecoder() {
mReadComplete = false;
}
/**
* Gets display duration for specified frame.
*
* @param n int index of frame
* @return mDelay mIn milliseconds
*/
public int getDelay(final int n) {
mDelay = -1;
if ((n >= 0) && (n < mFrameCount)) {
mDelay = mFrames.get(n).mDelay;
// meets browser compatibility standards
if (mDelay < MIN_DELAY_ENFORCE_THRESHOLD) {
mDelay = MIN_DELAY;
}
}
return mDelay;
}
/**
* Gets the number of mFrames read from file.
*
* @return frame count
*/
public int getFrameCount() {
return mFrameCount;
}
/**
* Gets the first (or only) mImage read.
*
* @return BufferedBitmap containing first frame, or null if none.
*/
public Bitmap getBitmap() {
return getFrame(0);
}
/**
* Gets the "Netscape" iteration count, if any. A count of 0 means repeat indefinitiely.
*
* @return iteration count if one was specified, else 1.
*/
public int getLoopCount() {
return mLoopCount;
}
/**
* Creates new frame mImage from current data (and previous mFrames as specified by their disposition codes).
*/
private void setPixels() {
// expose destination mImage's mPixels as int array
int[] dest = new int[mWidth * mHeight];
// fill mIn starting mImage contents based on last mImage's mDispose code
if (mLastDispose > 0) {
if (mLastDispose == 3) { // MAGIC_NUMBER
// use mImage before last
int n = mFrameCount - 2;
if (n > 0) {
mLastBitmap = getFrame(n - 1);
}
else {
mLastBitmap = null;
}
}
if (mLastBitmap != null) {
mLastBitmap.getPixels(dest, 0, mWidth, 0, 0, mWidth, mHeight);
// copy mPixels
if (mLastDispose == 2) {
// fill last mImage rect area with background color
int c = 0;
if (!mTransparency) {
c = mLastBgColor;
}
for (int i = 0; i < mLrh; i++) {
int n1 = (mLry + i) * mWidth + mLrx;
int n2 = n1 + mLrw;
for (int k = n1; k < n2; k++) {
dest[k] = c;
}
}
}
}
}
// copy each source line to the appropriate place mIn the destination
int pass = 1;
int inc = 8; // MAGIC_NUMBER
int iline = 0;
for (int i = 0; i < mIh; i++) {
int line = i;
if (mInterlace) {
if (iline >= mIh) {
pass++;
switch (pass) {
case 2:
iline = 4; // MAGIC_NUMBER
break;
case 3: // MAGIC_NUMBER
iline = 2;
inc = 4; // MAGIC_NUMBER
break;
case 4: // MAGIC_NUMBER
iline = 1;
inc = 2;
break;
default:
break;
}
}
line = iline;
iline += inc;
}
line += mIy;
if (line < mHeight) {
int k = line * mWidth;
int dx = k + mIx; // start of line mIn dest
int dlim = dx + mIw; // end of dest line
if ((k + mWidth) < dlim) {
dlim = k + mWidth; // past dest edge
}
int sx = i * mIw; // start of line mIn source
while (dx < dlim) {
// map color and insert mIn destination
int index = (mPixels[sx++]) & 0xff; // MAGIC_NUMBER
int c = mAct[index];
if (c != 0) {
dest[dx] = c;
}
dx++;
}
}
}
mImage = Bitmap.createBitmap(dest, mWidth, mHeight, Config.ARGB_4444);
}
/**
* Gets the mImage contents of frame n.
*
* @param n the frame number.
* @return BufferedBitmap representation of frame, or null if n is invalid.
*/
public Bitmap getFrame(final int n) {
if (mFrameCount <= 0) {
return null;
}
return mFrames.get(n % mFrameCount).mImage;
}
/**
* Reads GIF image from stream.
*
* @param inputStream the input stream containing GIF file.
* @throws IOException error while processing
*/
public void read(final InputStream inputStream) throws IOException {
init();
if (inputStream != null) {
mIn = inputStream;
readHeader();
readContents();
if (mFrameCount < 0) {
throw new IOException("Format Error");
}
}
else {
throw new IOException("Open error");
}
mReadComplete = true;
}
/**
* Decodes LZW mImage data into pixel array. Adapted from John Cristy's BitmapMagick.
*
* @throws IOException error while processing
*/
private void decodeBitmapData() throws IOException {
int npix = mIw * mIh;
if ((mPixels == null) || (mPixels.length < npix)) {
mPixels = new byte[npix]; // allocate new pixel array
}
if (mPrefix == null) {
mPrefix = new short[MAX_STACK_SIZE];
}
if (mSuffix == null) {
mSuffix = new byte[MAX_STACK_SIZE];
}
if (mPixelStack == null) {
mPixelStack = new byte[MAX_STACK_SIZE + 1];
}
// Initialize GIF data stream decoder.
int dataSize = read();
int clear = 1 << dataSize;
int endOfInformation = clear + 1;
int available = clear + 2;
int nullCode = -1;
int oldCode = nullCode;
int codeSize = dataSize + 1;
int codeMask = (1 << codeSize) - 1;
int code;
for (code = 0; code < clear; code++) {
mPrefix[code] = 0; // XXX ArrayIndexOutOfBoundsException
mSuffix[code] = (byte) code;
}
// Decode GIF pixel stream.
int datum = 0;
int bits = 0;
int count = 0;
int first = 0;
int top = 0;
int pi = 0;
int bi = 0;
int i = 0;
while (i < npix) {
if (top == 0) {
if (bits < codeSize) {
// Load bytes until there are enough bits for a code.
if (count == 0) {
// Read a new data mBlock.
count = readBlock();
if (count <= 0) {
break;
}
bi = 0;
}
datum += ((mBlock[bi]) & 0xff) << bits; // MAGIC_NUMBER
bits += 8; // MAGIC_NUMBER
bi++;
count--;
continue;
}
// Get the next code.
code = datum & codeMask;
datum >>= codeSize;
bits -= codeSize;
// Interpret the code
if ((code > available) || (code == endOfInformation)) {
break;
}
if (code == clear) {
// Reset decoder.
codeSize = dataSize + 1;
codeMask = (1 << codeSize) - 1;
available = clear + 2;
oldCode = nullCode;
continue;
}
if (oldCode == nullCode) {
mPixelStack[top++] = mSuffix[code];
oldCode = code;
first = code;
continue;
}
final int inCode = code;
if (code == available) {
mPixelStack[top++] = (byte) first;
code = oldCode;
}
while (code > clear) {
mPixelStack[top++] = mSuffix[code];
code = mPrefix[code];
}
first = (mSuffix[code]) & 0xff; // MAGIC_NUMBER
// Add a new string to the string table,
if (available >= MAX_STACK_SIZE) {
break;
}
mPixelStack[top++] = (byte) first;
mPrefix[available] = (short) oldCode;
mSuffix[available] = (byte) first;
available++;
if (((available & codeMask) == 0) && (available < MAX_STACK_SIZE)) {
codeSize++;
codeMask += available;
}
oldCode = inCode;
}
// Pop a pixel off the pixel stack.
top--;
mPixels[pi++] = mPixelStack[top];
i++;
}
for (i = pi; i < npix; i++) {
mPixels[i] = 0; // clear missing mPixels
}
}
/**
* Initializes or re-initializes reader.
*/
private void init() {
mFrameCount = 0;
mFrames = new ArrayList<>();
mGct = null;
mLct = null;
}
/**
* Reads a single byte from the input stream.
*
* @return the read byte.
* @throws IOException exception while reading.
*/
private int read() throws IOException {
return mIn.read();
}
/**
* Reads next variable length mBlock from input.
*
* @return number of bytes stored mIn "buffer"
* @throws IOException error while processing
*/
private int readBlock() throws IOException {
mBlockSize = read();
int n = 0;
if (mBlockSize > 0) {
try {
int count;
while (n < mBlockSize) {
count = mIn.read(mBlock, n, mBlockSize - n);
if (count == -1) {
break;
}
n += count;
}
}
catch (Exception e) {
e.printStackTrace();
}
if (n < mBlockSize) {
throw new IOException("Format error");
}
}
return n;
}
/**
* Reads color table as 256 RGB integer values.
*
* @param ncolors int number of colors to read
* @return int array containing 256 colors (packed ARGB with full alpha)
* @throws IOException error while processing
*/
private int[] readColorTable(final int ncolors) throws IOException {
int nbytes = 3 * ncolors; // MAGIC_NUMBER
int[] tab;
byte[] c = new byte[nbytes];
int n = 0;
try {
n = mIn.read(c);
}
catch (Exception e) {
e.printStackTrace();
}
if (n < nbytes) {
throw new IOException("Format error");
}
else {
tab = new int[256]; // MAGIC_NUMBER max size to avoid bounds checks
int i = 0;
int j = 0;
while (i < ncolors) {
int r = (c[j++]) & 0xff; // MAGIC_NUMBER
int g = (c[j++]) & 0xff; // MAGIC_NUMBER
int b = (c[j++]) & 0xff; // MAGIC_NUMBER
tab[i++] = 0xff000000 | (r << 16) | (g << 8) | b; // MAGIC_NUMBER
}
}
return tab;
}
/**
* Main file parser. Reads GIF content blocks.
*
* @throws IOException error while processing
*/
public void readContents() throws IOException {
// read GIF file content blocks
boolean done = false;
while (!done) {
int code = read();
switch (code) {
case 0x2C: // MAGIC_NUMBER Image separator
readBitmap();
if (!mReadComplete) {
return;
}
break;
case 0x21: // MAGIC_NUMBER extension
code = read();
switch (code) {
case 0xf9: // MAGIC_NUMBER graphics control extension
readGraphicControlExt();
break;
case 0xff: // MAGIC_NUMBER application extension
readBlock();
StringBuilder app = new StringBuilder();
for (int i = 0; i < 11; i++) { // MAGIC_NUMBER
app.append((char) mBlock[i]);
}
if ("NETSCAPE2.0".equals(app.toString())) {
readNetscapeExt();
}
else {
skip(); // don't care
}
break;
case 0xfe:// MAGIC_NUMBER comment extension
case 0x01:// plain text extension
default: // uninteresting extension
skip();
}
break;
case 0x3b: // MAGIC_NUMBER terminator
done = true;
break;
case 0x00: // bad byte, but keep going and see what happens break;
default:
throw new IOException("Format error");
}
}
}
/**
* Reads Graphics Control Extension values.
*
* @throws IOException error while processing
*/
private void readGraphicControlExt() throws IOException {
read(); // mBlock size
int packed = read(); // packed fields
mDispose = (packed & 0x1c) >> 2; // MAGIC_NUMBER disposal method
if (mDispose == 0) {
mDispose = 1; // elect to keep old mImage if discretionary
}
mTransparency = (packed & 1) != 0;
mDelay = readShort() * 10; // MAGIC_NUMBER delay mIn milliseconds
mTransIndex = read(); // transparent color index
read(); // mBlock terminator
}
/**
* Reads GIF file header information.
*
* @throws IOException error while processing
*/
private void readHeader() throws IOException {
StringBuilder id = new StringBuilder();
for (int i = 0; i < 6; i++) { // MAGIC_NUMBER
id.append((char) read());
}
if (!id.toString().startsWith("GIF")) {
throw new IOException("Format error");
}
readLsd();
if (mGctFlag) {
mGct = readColorTable(mGctSize);
mBgColor = mGct[mBgIndex];
}
}
/**
* Reads next frame mImage.
*
* @throws IOException error while processing
*/
private void readBitmap() throws IOException {
mIx = readShort(); // (sub)mImage position & size
mIy = readShort();
mIw = readShort();
mIh = readShort();
int packed = read();
mLctFlag = (packed & 0x80) != 0; // MAGIC_NUMBER 1 - local color table flag mInterlace
mLctSize = (int) Math.pow(2, (packed & 0x07) + 1); // MAGIC_NUMBER
// 3 - sort flag
// 4-5 - reserved mLctSize = 2 << (packed & 7); // 6-8 - local color
// table size
mInterlace = (packed & 0x40) != 0; // MAGIC_NUMBER
if (mLctFlag) {
mLct = readColorTable(mLctSize); // read table
mAct = mLct; // make local table active
}
else {
mAct = mGct; // make global table active
if (mBgIndex == mTransIndex) {
mBgColor = 0;
}
}
int save = 0;
if (mTransparency) {
save = mAct[mTransIndex];
mAct[mTransIndex] = 0; // set transparent color if specified
}
if (mAct == null) {
throw new IOException("Format error"); // no color table defined
}
decodeBitmapData(); // decode pixel data
skip();
mFrameCount++;
// create new mImage to receive frame data
mImage = Bitmap.createBitmap(mWidth, mHeight, Config.ARGB_4444);
setPixels(); // transfer pixel data to mImage
mFrames.add(new GifFrame(mImage, mDelay)); // add mImage to frame
// list
if (mTransparency) {
mAct[mTransIndex] = save;
}
resetFrame();
}
/**
* Reads Logical Screen Descriptor.
*
* @throws IOException error while processing
*/
private void readLsd() throws IOException {
// logical screen size
mWidth = readShort();
mHeight = readShort();
// packed fields
int packed = read();
mGctFlag = (packed & 0x80) != 0; // MAGIC_NUMBER 1 : global color table flag
// 2-4 : color resolution
// 5 : mGct sort flag
mGctSize = 2 << (packed & 7); // MAGIC_NUMBER 6-8 : mGct size
mBgIndex = read(); // background color index
read(); // pixel aspect ratio
}
/**
* Reads Netscape extenstion to obtain iteration count.
*
* @throws IOException error while processing
*/
private void readNetscapeExt() throws IOException {
do {
readBlock();
if (mBlock[0] == 1) {
// loop count sub-mBlock
int b1 = (mBlock[1]) & 0xff; // MAGIC_NUMBER
int b2 = (mBlock[2]) & 0xff; // MAGIC_NUMBER
mLoopCount = (b2 << 8) | b1; // MAGIC_NUMBER
}
}
while (mBlockSize > 0);
}
/**
* Reads next 16-bit value, LSB first.
*
* @return the read value.
* @throws IOException error while processing
*/
private int readShort() throws IOException {
// read 16-bit value, LSB first
return read() | (read() << 8); // MAGIC_NUMBER
}
/**
* Resets frame state for reading next mImage.
*/
private void resetFrame() {
mLastDispose = mDispose;
mLrx = mIx;
mLry = mIy;
mLrw = mIw;
mLrh = mIh;
mLastBitmap = mImage;
mLastBgColor = mBgColor;
mDispose = 0;
mTransparency = false;
mDelay = 0;
mLct = null;
}
/**
* Skips variable length blocks up to and including next zero length mBlock.
*
* @throws IOException error while processing
*/
private void skip() throws IOException {
do {
readBlock();
}
while (mBlockSize > 0);
}
/**
* A GIF frame.
*/
private static class GifFrame {
/**
* The image.
*/
private Bitmap mImage;
/**
* The delay.
*/
private int mDelay;
/**
* Constructor.
*
* @param image The image.
* @param delay The delay.
*/
GifFrame(final Bitmap image, final int delay) {
mImage = image;
mDelay = delay;
}
}
}
| jeisfeld/RandomImage | RandomImageIdea/randomImageLib/src/main/java/de/jeisfeld/randomimage/util/GifDecoder.java | Java | gpl-2.0 | 17,811 |
/* png.h - header file for PNG reference library
*
* libpng 1.0.2 - June 14, 1998
* For conditions of distribution and use, see the COPYRIGHT NOTICE below.
* Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.
* Copyright (c) 1996, 1997 Andreas Dilger
* Copyright (c) 1998 Glenn Randers-Pehrson
*
* Note about libpng version numbers:
*
* Due to various miscommunications, unforeseen code incompatibilities
* and occasional factors outside the authors' control, version numbering
* on the library has not always been consistent and straightforward.
* The following table summarizes matters since version 0.89c, which was
* the first widely used release:
*
* source png.h png.h shared-lib
* version string int version
* ------- ------ ----- ----------
* 0.89c ("1.0 beta 3") 0.89 89 1.0.89
* 0.90 ("1.0 beta 4") 0.90 90 0.90 [should have been 2.0.90]
* 0.95 ("1.0 beta 5") 0.95 95 0.95 [should have been 2.0.95]
* 0.96 ("1.0 beta 6") 0.96 96 0.96 [should have been 2.0.96]
* 0.97b ("1.00.97 beta 7") 1.00.97 97 1.0.1 [should have been 2.0.97]
* 0.97c 0.97 97 2.0.97
* 0.98 0.98 98 2.0.98
* 0.99 0.99 98 2.0.99
* 0.99a-m 0.99 99 2.0.99
* 1.00 1.00 100 2.1.0 [int should be 10000]
* 1.0.0 1.0.0 100 2.1.0 [int should be 10000]
* 1.0.1 1.0.1 10001 2.1.0
* 1.0.1a-e 1.0.1a-e 10002 2.1.0.1a-e
*
* Henceforth the source version will match the shared-library minor
* and patch numbers; the shared-library major version number will be
* used for changes in backward compatibility, as it is intended. The
* PNG_PNGLIB_VER macro, which is not used within libpng but is available
* for applications, is an unsigned integer of the form xyyzz corresponding
* to the source version x.y.z (leading zeros in y and z).
*
* See libpng.txt or libpng.3 for more information. The PNG specification
* is available as RFC 2083 <ftp://ftp.uu.net/graphics/png/documents/>
* and as a W3C Recommendation <http://www.w3.org/TR/REC.png.html>
*
* Contributing Authors:
* John Bowler
* Kevin Bracey
* Sam Bushell
* Andreas Dilger
* Magnus Holmgren
* Tom Lane
* Dave Martindale
* Glenn Randers-Pehrson
* Greg Roelofs
* Guy Eric Schalnat
* Paul Schmidt
* Tom Tanner
* Willem van Schaik
* Tim Wegner
*
* The contributing authors would like to thank all those who helped
* with testing, bug fixes, and patience. This wouldn't have been
* possible without all of you.
*
* Thanks to Frank J. T. Wojcik for helping with the documentation.
*
* COPYRIGHT NOTICE:
*
* The PNG Reference Library is supplied "AS IS". The Contributing Authors
* and Group 42, Inc. disclaim all warranties, expressed or implied,
* including, without limitation, the warranties of merchantability and of
* fitness for any purpose. The Contributing Authors and Group 42, Inc.
* assume no liability for direct, indirect, incidental, special, exemplary,
* or consequential damages, which may result from the use of the PNG
* Reference Library, even if advised of the possibility of such damage.
*
* Permission is hereby granted to use, copy, modify, and distribute this
* source code, or portions hereof, for any purpose, without fee, subject
* to the following restrictions:
* 1. The origin of this source code must not be misrepresented.
* 2. Altered versions must be plainly marked as such and must not be
* misrepresented as being the original source.
* 3. This Copyright notice may not be removed or altered from any source or
* altered source distribution.
*
* The Contributing Authors and Group 42, Inc. specifically permit, without
* fee, and encourage the use of this source code as a component to
* supporting the PNG file format in commercial products. If you use this
* source code in a product, acknowledgment is not required but would be
* appreciated.
*/
#ifndef _PNG_H
#define _PNG_H
//#ifdef __cplusplus
//extern "C" {
//#endif /* __cplusplus */
/* This is not the place to learn how to use libpng. The file libpng.txt
* describes how to use libpng, and the file example.c summarizes it
* with some code on which to build. This file is useful for looking
* at the actual function definitions and structure components.
*/
/* include the compression library's header */
#include <zlib.h>
/* include all user configurable info */
#include "pngconf.h"
/* This file is arranged in several sections. The first section contains
* structure and type definitions. The second section contains the external
* library functions, while the third has the internal library functions,
* which applications aren't expected to use directly.
*/
/* Version information for png.h - this should match the version in png.c */
#define PNG_LIBPNG_VER_STRING "1.0.2"
/* Careful here. At one time, Guy wanted to use 082, but that would be octal.
* We must not include leading zeros.
* Versions 0.7 through 1.0.0 were in the range 0 to 100 here (only
* version 1.0.0 was mis-numbered 100 instead of 10000). From
* version 1.0.1 it's xxyyzz, where x=major, y=minor, z=bugfix */
#define PNG_LIBPNG_VER 10002 /* 1.0.2 */
/* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
#if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
/* Version information for C files, stored in png.c. This had better match
* the version above.
*/
extern char png_libpng_ver[12]; /* need room for 99.99.99aa */
/* Structures to facilitate easy interlacing. See png.c for more details */
extern int FARDATA png_pass_start[7];
extern int FARDATA png_pass_inc[7];
extern int FARDATA png_pass_ystart[7];
extern int FARDATA png_pass_yinc[7];
extern int FARDATA png_pass_mask[7];
extern int FARDATA png_pass_dsp_mask[7];
#endif /* PNG_NO_EXTERN */
/* Three color definitions. The order of the red, green, and blue, (and the
* exact size) is not important, although the size of the fields need to
* be png_byte or png_uint_16 (as defined below).
*/
typedef struct png_color_struct
{
png_byte red;
png_byte green;
png_byte blue;
} png_color;
typedef png_color FAR * png_colorp;
typedef png_color FAR * FAR * png_colorpp;
typedef struct png_color_16_struct
{
png_byte index; /* used for palette files */
png_uint_16 red; /* for use in red green blue files */
png_uint_16 green;
png_uint_16 blue;
png_uint_16 gray; /* for use in grayscale files */
} png_color_16;
typedef png_color_16 FAR * png_color_16p;
typedef png_color_16 FAR * FAR * png_color_16pp;
typedef struct png_color_8_struct
{
png_byte red; /* for use in red green blue files */
png_byte green;
png_byte blue;
png_byte gray; /* for use in grayscale files */
png_byte alpha; /* for alpha channel files */
} png_color_8;
typedef png_color_8 FAR * png_color_8p;
typedef png_color_8 FAR * FAR * png_color_8pp;
/* png_text holds the text in a PNG file, and whether they are compressed
in the PNG file or not. The "text" field points to a regular C string. */
typedef struct png_text_struct
{
int compression; /* compression value, see PNG_TEXT_COMPRESSION_ */
png_charp key; /* keyword, 1-79 character description of "text" */
png_charp text; /* comment, may be an empty string (ie "") */
png_size_t text_length; /* length of "text" field */
} png_text;
typedef png_text FAR * png_textp;
typedef png_text FAR * FAR * png_textpp;
/* Supported compression types for text in PNG files (tEXt, and zTXt).
* The values of the PNG_TEXT_COMPRESSION_ defines should NOT be changed. */
#define PNG_TEXT_COMPRESSION_NONE_WR -3
#define PNG_TEXT_COMPRESSION_zTXt_WR -2
#define PNG_TEXT_COMPRESSION_NONE -1
#define PNG_TEXT_COMPRESSION_zTXt 0
#define PNG_TEXT_COMPRESSION_LAST 1 /* Not a valid value */
/* png_time is a way to hold the time in an machine independent way.
* Two conversions are provided, both from time_t and struct tm. There
* is no portable way to convert to either of these structures, as far
* as I know. If you know of a portable way, send it to me. As a side
* note - PNG is Year 2000 compliant!
*/
typedef struct png_time_struct
{
png_uint_16 year; /* full year, as in, 1995 */
png_byte month; /* month of year, 1 - 12 */
png_byte day; /* day of month, 1 - 31 */
png_byte hour; /* hour of day, 0 - 23 */
png_byte minute; /* minute of hour, 0 - 59 */
png_byte second; /* second of minute, 0 - 60 (for leap seconds) */
} png_time;
typedef png_time FAR * png_timep;
typedef png_time FAR * FAR * png_timepp;
/* png_info is a structure that holds the information in a PNG file so
* that the application can find out the characteristics of the image.
* If you are reading the file, this structure will tell you what is
* in the PNG file. If you are writing the file, fill in the information
* you want to put into the PNG file, then call png_write_info().
* The names chosen should be very close to the PNG specification, so
* consult that document for information about the meaning of each field.
*
* With libpng < 0.95, it was only possible to directly set and read the
* the values in the png_info_struct, which meant that the contents and
* order of the values had to remain fixed. With libpng 0.95 and later,
* however, there are now functions that abstract the contents of
* png_info_struct from the application, so this makes it easier to use
* libpng with dynamic libraries, and even makes it possible to use
* libraries that don't have all of the libpng ancillary chunk-handing
* functionality.
*
* In any case, the order of the parameters in png_info_struct should NOT
* be changed for as long as possible to keep compatibility with applications
* that use the old direct-access method with png_info_struct.
*/
typedef struct png_info_struct
{
/* the following are necessary for every PNG file */
png_uint_32 width; /* width of image in pixels (from IHDR) */
png_uint_32 height; /* height of image in pixels (from IHDR) */
png_uint_32 valid; /* valid chunk data (see PNG_INFO_ below) */
png_uint_32 rowbytes; /* bytes needed to hold an untransformed row */
png_colorp palette; /* array of color values (valid & PNG_INFO_PLTE) */
png_uint_16 num_palette; /* number of color entries in "palette" (PLTE) */
png_uint_16 num_trans; /* number of transparent palette color (tRNS) */
png_byte bit_depth; /* 1, 2, 4, 8, or 16 bits/channel (from IHDR) */
png_byte color_type; /* see PNG_COLOR_TYPE_ below (from IHDR) */
png_byte compression_type; /* must be PNG_COMPRESSION_TYPE_BASE (IHDR) */
png_byte filter_type; /* must be PNG_FILTER_TYPE_BASE (from IHDR) */
png_byte interlace_type; /* One of PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
/* The following is informational only on read, and not used on writes. */
png_byte channels; /* number of data channels per pixel (1, 3, 4)*/
png_byte pixel_depth; /* number of bits per pixel */
png_byte spare_byte; /* to align the data, and for future use */
png_byte signature[8]; /* magic bytes read by libpng from start of file */
/* The rest of the data is optional. If you are reading, check the
* valid field to see if the information in these are valid. If you
* are writing, set the valid field to those chunks you want written,
* and initialize the appropriate fields below.
*/
#if defined(PNG_READ_gAMA_SUPPORTED) || defined(PNG_WRITE_gAMA_SUPPORTED) || \
defined(PNG_READ_GAMMA_SUPPORTED)
/* The gAMA chunk describes the gamma characteristics of the system
* on which the image was created, normally in the range [1.0, 2.5].
* Data is valid if (valid & PNG_INFO_gAMA) is non-zero.
*/
float gamma; /* gamma value of image, if (valid & PNG_INFO_gAMA) */
#endif /* PNG_READ_gAMA_SUPPORTED || PNG_WRITE_gAMA_SUPPORTED */
#if defined(PNG_READ_sRGB_SUPPORTED) || defined(PNG_WRITE_sRGB_SUPPORTED)
/* GR-P, 0.96a */
/* Data valid if (valid & PNG_INFO_sRGB) non-zero. */
png_byte srgb_intent; /* sRGB rendering intent [0, 1, 2, or 3] */
#endif /* PNG_READ_sRGB_SUPPORTED || PNG_WRITE_sRGB_SUPPORTED */
#if defined(PNG_READ_tEXt_SUPPORTED) || defined(PNG_WRITE_tEXt_SUPPORTED) || \
defined(PNG_READ_zTXt_SUPPORTED) || defined(PNG_WRITE_zTXt_SUPPORTED)
/* The tEXt and zTXt chunks contain human-readable textual data in
* uncompressed and compressed forms, respectively. The data in "text"
* is an array of pointers to uncompressed, null-terminated C strings.
* Each chunk has a keyword that describes the textual data contained
* in that chunk. Keywords are not required to be unique, and the text
* string may be empty. Any number of text chunks may be in an image.
*/
int num_text; /* number of comments read/to write */
int max_text; /* current size of text array */
png_textp text; /* array of comments read/to write */
#endif /* PNG_READ_OR_WRITE_tEXt_OR_zTXt_SUPPORTED */
#if defined(PNG_READ_tIME_SUPPORTED) || defined(PNG_WRITE_tIME_SUPPORTED)
/* The tIME chunk holds the last time the displayed image data was
* modified. See the png_time struct for the contents of this struct.
*/
png_time mod_time;
#endif /* PNG_READ_tIME_SUPPORTED || PNG_WRITE_tIME_SUPPORTED */
#if defined(PNG_READ_sBIT_SUPPORTED) || defined(PNG_WRITE_sBIT_SUPPORTED)
/* The sBIT chunk specifies the number of significant high-order bits
* in the pixel data. Values are in the range [1, bit_depth], and are
* only specified for the channels in the pixel data. The contents of
* the low-order bits is not specified. Data is valid if
* (valid & PNG_INFO_sBIT) is non-zero.
*/
png_color_8 sig_bit; /* significant bits in color channels */
#endif /* PNG_READ_sBIT_SUPPORTED || PNG_WRITE_sBIT_SUPPORTED */
#if defined(PNG_READ_tRNS_SUPPORTED) || defined(PNG_WRITE_tRNS_SUPPORTED) || \
defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
/* The tRNS chunk supplies transparency data for paletted images and
* other image types that don't need a full alpha channel. There are
* "num_trans" transparency values for a paletted image, stored in the
* same order as the palette colors, starting from index 0. Values
* for the data are in the range [0, 255], ranging from fully transparent
* to fully opaque, respectively. For non-paletted images, there is a
* single color specified that should be treated as fully transparent.
* Data is valid if (valid & PNG_INFO_tRNS) is non-zero.
*/
png_bytep trans; /* transparent values for paletted image */
png_color_16 trans_values; /* transparent color for non-palette image */
#endif /* PNG_READ_tRNS_SUPPORTED || PNG_WRITE_tRNS_SUPPORTED */
#if defined(PNG_READ_bKGD_SUPPORTED) || defined(PNG_WRITE_bKGD_SUPPORTED) || \
defined(PNG_READ_BACKGROUND_SUPPORTED)
/* The bKGD chunk gives the suggested image background color if the
* display program does not have its own background color and the image
* is needs to composited onto a background before display. The colors
* in "background" are normally in the same color space/depth as the
* pixel data. Data is valid if (valid & PNG_INFO_bKGD) is non-zero.
*/
png_color_16 background;
#endif /* PNG_READ_bKGD_SUPPORTED || PNG_WRITE_bKGD_SUPPORTED */
#if defined(PNG_READ_oFFs_SUPPORTED) || defined(PNG_WRITE_oFFs_SUPPORTED)
/* The oFFs chunk gives the offset in "offset_unit_type" units rightwards
* and downwards from the top-left corner of the display, page, or other
* application-specific co-ordinate space. See the PNG_OFFSET_ defines
* below for the unit types. Valid if (valid & PNG_INFO_oFFs) non-zero.
*/
png_uint_32 x_offset; /* x offset on page */
png_uint_32 y_offset; /* y offset on page */
png_byte offset_unit_type; /* offset units type */
#endif /* PNG_READ_oFFs_SUPPORTED || PNG_WRITE_oFFs_SUPPORTED */
#if defined(PNG_READ_pHYs_SUPPORTED) || defined(PNG_WRITE_pHYs_SUPPORTED)
/* The pHYs chunk gives the physical pixel density of the image for
* display or printing in "phys_unit_type" units (see PNG_RESOLUTION_
* defines below). Data is valid if (valid & PNG_INFO_pHYs) is non-zero.
*/
png_uint_32 x_pixels_per_unit; /* horizontal pixel density */
png_uint_32 y_pixels_per_unit; /* vertical pixel density */
png_byte phys_unit_type; /* resolution type (see PNG_RESOLUTION_ below) */
#endif /* PNG_READ_pHYs_SUPPORTED || PNG_WRITE_pHYs_SUPPORTED */
#if defined(PNG_READ_hIST_SUPPORTED) || defined(PNG_WRITE_hIST_SUPPORTED)
/* The hIST chunk contains the relative frequency or importance of the
* various palette entries, so that a viewer can intelligently select a
* reduced-color palette, if required. Data is an array of "num_palette"
* values in the range [0,65535]. Data valid if (valid & PNG_INFO_hIST)
* is non-zero.
*/
png_uint_16p hist;
#endif /* PNG_READ_hIST_SUPPORTED || PNG_WRITE_hIST_SUPPORTED */
#if defined(PNG_READ_cHRM_SUPPORTED) || defined(PNG_WRITE_cHRM_SUPPORTED)
/* The cHRM chunk describes the CIE color characteristics of the monitor
* on which the PNG was created. This data allows the viewer to do gamut
* mapping of the input image to ensure that the viewer sees the same
* colors in the image as the creator. Values are in the range
* [0.0, 0.8]. Data valid if (valid & PNG_INFO_cHRM) non-zero.
*/
float x_white;
float y_white;
float x_red;
float y_red;
float x_green;
float y_green;
float x_blue;
float y_blue;
#endif /* PNG_READ_cHRM_SUPPORTED || PNG_WRITE_cHRM_SUPPORTED */
#if defined(PNG_READ_pCAL_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED)
/* The pCAL chunk describes a transformation between the stored pixel
* values and original physcical data values used to create the image.
* The integer range [0, 2^bit_depth - 1] maps to the floating-point
* range given by [pcal_X0, pcal_X1], and are further transformed by a
* (possibly non-linear) transformation function given by "pcal_type"
* and "pcal_params" into "pcal_units". Please see the PNG_EQUATION_
* defines below, and the PNG-Group's Scientific Visualization extension
* chunks document png-scivis-19970203 for a complete description of the
* transformations and how they should be implemented, as well as the
* png-extensions document for a description of the ASCII parameter
* strings. Data values are valid if (valid & PNG_INFO_pCAL) non-zero.
*/
png_charp pcal_purpose; /* pCAL chunk description string */
png_int_32 pcal_X0; /* minimum value */
png_int_32 pcal_X1; /* maximum value */
png_charp pcal_units; /* Latin-1 string giving physical units */
png_charpp pcal_params; /* ASCII strings containing parameter values */
png_byte pcal_type; /* equation type (see PNG_EQUATION_ below) */
png_byte pcal_nparams; /* number of parameters given in pcal_params */
#endif /* PNG_READ_pCAL_SUPPORTED || PNG_WRITE_pCAL_SUPPORTED */
} png_info;
typedef png_info FAR * png_infop;
typedef png_info FAR * FAR * png_infopp;
/* These describe the color_type field in png_info. */
/* color type masks */
#define PNG_COLOR_MASK_PALETTE 1
#define PNG_COLOR_MASK_COLOR 2
#define PNG_COLOR_MASK_ALPHA 4
/* color types. Note that not all combinations are legal */
#define PNG_COLOR_TYPE_GRAY 0
#define PNG_COLOR_TYPE_PALETTE (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_PALETTE)
#define PNG_COLOR_TYPE_RGB (PNG_COLOR_MASK_COLOR)
#define PNG_COLOR_TYPE_RGB_ALPHA (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_ALPHA)
#define PNG_COLOR_TYPE_GRAY_ALPHA (PNG_COLOR_MASK_ALPHA)
/* This is for compression type. PNG 1.0 only defines the single type. */
#define PNG_COMPRESSION_TYPE_BASE 0 /* Deflate method 8, 32K window */
#define PNG_COMPRESSION_TYPE_DEFAULT PNG_COMPRESSION_TYPE_BASE
/* This is for filter type. PNG 1.0 only defines the single type. */
#define PNG_FILTER_TYPE_BASE 0 /* Single row per-byte filtering */
#define PNG_FILTER_TYPE_DEFAULT PNG_FILTER_TYPE_BASE
/* These are for the interlacing type. These values should NOT be changed. */
#define PNG_INTERLACE_NONE 0 /* Non-interlaced image */
#define PNG_INTERLACE_ADAM7 1 /* Adam7 interlacing */
#define PNG_INTERLACE_LAST 2 /* Not a valid value */
/* These are for the oFFs chunk. These values should NOT be changed. */
#define PNG_OFFSET_PIXEL 0 /* Offset in pixels */
#define PNG_OFFSET_MICROMETER 1 /* Offset in micrometers (1/10^6 meter) */
#define PNG_OFFSET_LAST 2 /* Not a valid value */
/* These are for the pCAL chunk. These values should NOT be changed. */
#define PNG_EQUATION_LINEAR 0 /* Linear transformation */
#define PNG_EQUATION_BASE_E 1 /* Exponential base e transform */
#define PNG_EQUATION_ARBITRARY 2 /* Arbitrary base exponential transform */
#define PNG_EQUATION_HYPERBOLIC 3 /* Hyperbolic sine transformation */
#define PNG_EQUATION_LAST 4 /* Not a valid value */
/* These are for the pHYs chunk. These values should NOT be changed. */
#define PNG_RESOLUTION_UNKNOWN 0 /* pixels/unknown unit (aspect ratio) */
#define PNG_RESOLUTION_METER 1 /* pixels/meter */
#define PNG_RESOLUTION_LAST 2 /* Not a valid value */
/* These are for the sRGB chunk. These values should NOT be changed. */
#define PNG_sRGB_INTENT_SATURATION 0
#define PNG_sRGB_INTENT_PERCEPTUAL 1
#define PNG_sRGB_INTENT_ABSOLUTE 2
#define PNG_sRGB_INTENT_RELATIVE 3
#define PNG_sRGB_INTENT_LAST 4 /* Not a valid value */
/* These determine if an ancillary chunk's data has been successfully read
* from the PNG header, or if the application has filled in the corresponding
* data in the info_struct to be written into the output file. The values
* of the PNG_INFO_<chunk> defines should NOT be changed.
*/
#define PNG_INFO_gAMA 0x0001
#define PNG_INFO_sBIT 0x0002
#define PNG_INFO_cHRM 0x0004
#define PNG_INFO_PLTE 0x0008
#define PNG_INFO_tRNS 0x0010
#define PNG_INFO_bKGD 0x0020
#define PNG_INFO_hIST 0x0040
#define PNG_INFO_pHYs 0x0080
#define PNG_INFO_oFFs 0x0100
#define PNG_INFO_tIME 0x0200
#define PNG_INFO_pCAL 0x0400
#define PNG_INFO_sRGB 0x0800 /* GR-P, 0.96a */
/* This is used for the transformation routines, as some of them
* change these values for the row. It also should enable using
* the routines for other purposes.
*/
typedef struct png_row_info_struct
{
png_uint_32 width; /* width of row */
png_uint_32 rowbytes; /* number of bytes in row */
png_byte color_type; /* color type of row */
png_byte bit_depth; /* bit depth of row */
png_byte channels; /* number of channels (1, 2, 3, or 4) */
png_byte pixel_depth; /* bits per pixel (depth * channels) */
} png_row_info;
typedef png_row_info FAR * png_row_infop;
typedef png_row_info FAR * FAR * png_row_infopp;
/* These are the function types for the I/O functions and for the functions
* that allow the user to override the default I/O functions with his or her
* own. The png_error_ptr type should match that of user-supplied warning
* and error functions, while the png_rw_ptr type should match that of the
* user read/write data functions.
*/
typedef struct png_struct_def png_struct;
typedef png_struct FAR * png_structp;
typedef void (*png_error_ptr) PNGARG((png_structp, png_const_charp));
typedef void (*png_rw_ptr) PNGARG((png_structp, png_bytep, png_size_t));
typedef void (*png_flush_ptr) PNGARG((png_structp));
typedef void (*png_read_status_ptr) PNGARG((png_structp, png_uint_32, int));
typedef void (*png_write_status_ptr) PNGARG((png_structp, png_uint_32, int));
#ifdef PNG_PROGRESSIVE_READ_SUPPORTED
typedef void (*png_progressive_info_ptr) PNGARG((png_structp, png_infop));
typedef void (*png_progressive_end_ptr) PNGARG((png_structp, png_infop));
typedef void (*png_progressive_row_ptr) PNGARG((png_structp, png_bytep,
png_uint_32, int));
#endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
#if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
typedef void (*png_user_transform_ptr) PNGARG((png_structp,
png_row_infop, png_bytep));
#endif /* PNG_READ|WRITE_USER_TRANSFORM_SUPPORTED */
typedef png_voidp (*png_malloc_ptr) PNGARG((png_structp, png_size_t));
typedef void (*png_free_ptr) PNGARG((png_structp, png_structp));
/* The structure that holds the information to read and write PNG files.
* The only people who need to care about what is inside of this are the
* people who will be modifying the library for their own special needs.
* It should NOT be accessed directly by an application, except to store
* the jmp_buf.
*/
struct png_struct_def
{
jmp_buf jmpbuf; /* used in png_error */
png_error_ptr error_fn; /* function for printing errors and aborting */
png_error_ptr warning_fn; /* function for printing warnings */
png_voidp error_ptr; /* user supplied struct for error functions */
png_rw_ptr write_data_fn; /* function for writing output data */
png_rw_ptr read_data_fn; /* function for reading input data */
#if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
png_user_transform_ptr read_user_transform_fn; /* user read transform */
png_user_transform_ptr write_user_transform_fn; /* user write transform */
#endif
png_voidp io_ptr; /* ptr to application struct for I/O functions*/
png_uint_32 mode; /* tells us where we are in the PNG file */
png_uint_32 flags; /* flags indicating various things to libpng */
png_uint_32 transformations; /* which transformations to perform */
z_stream zstream; /* pointer to decompression structure (below) */
png_bytep zbuf; /* buffer for zlib */
png_size_t zbuf_size; /* size of zbuf */
int zlib_level; /* holds zlib compression level */
int zlib_method; /* holds zlib compression method */
int zlib_window_bits; /* holds zlib compression window bits */
int zlib_mem_level; /* holds zlib compression memory level */
int zlib_strategy; /* holds zlib compression strategy */
png_uint_32 width; /* width of image in pixels */
png_uint_32 height; /* height of image in pixels */
png_uint_32 num_rows; /* number of rows in current pass */
png_uint_32 usr_width; /* width of row at start of write */
png_uint_32 rowbytes; /* size of row in bytes */
png_uint_32 irowbytes; /* size of current interlaced row in bytes */
png_uint_32 iwidth; /* width of current interlaced row in pixels */
png_uint_32 row_number; /* current row in interlace pass */
png_bytep prev_row; /* buffer to save previous (unfiltered) row */
png_bytep row_buf; /* buffer to save current (unfiltered) row */
png_bytep sub_row; /* buffer to save "sub" row when filtering */
png_bytep up_row; /* buffer to save "up" row when filtering */
png_bytep avg_row; /* buffer to save "avg" row when filtering */
png_bytep paeth_row; /* buffer to save "Paeth" row when filtering */
png_row_info row_info; /* used for transformation routines */
png_uint_32 idat_size; /* current IDAT size for read */
png_uint_32 crc; /* current chunk CRC value */
png_colorp palette; /* palette from the input file */
png_uint_16 num_palette; /* number of color entries in palette */
png_uint_16 num_trans; /* number of transparency values */
png_byte chunk_name[5]; /* null-terminated name of current chunk */
png_byte compression; /* file compression type (always 0) */
png_byte filter; /* file filter type (always 0) */
png_byte interlaced; /* PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
png_byte pass; /* current interlace pass (0 - 6) */
png_byte do_filter; /* row filter flags (see PNG_FILTER_ below ) */
png_byte color_type; /* color type of file */
png_byte bit_depth; /* bit depth of file */
png_byte usr_bit_depth; /* bit depth of users row */
png_byte pixel_depth; /* number of bits per pixel */
png_byte channels; /* number of channels in file */
png_byte usr_channels; /* channels at start of write */
png_byte sig_bytes; /* magic bytes read/written from start of file */
#if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
png_uint_16 filler; /* filler bytes for pixel expansion */
#endif /* PNG_READ_FILLER_SUPPORTED */
#if defined(PNG_READ_bKGD_SUPPORTED)
png_byte background_gamma_type;
float background_gamma;
png_color_16 background; /* background color in screen gamma space */
#if defined(PNG_READ_GAMMA_SUPPORTED)
png_color_16 background_1; /* background normalized to gamma 1.0 */
#endif /* PNG_READ_GAMMA && PNG_READ_bKGD_SUPPORTED */
#endif /* PNG_READ_bKGD_SUPPORTED */
#if defined(PNG_WRITE_FLUSH_SUPPORTED)
png_flush_ptr output_flush_fn;/* Function for flushing output */
png_uint_32 flush_dist; /* how many rows apart to flush, 0 - no flush */
png_uint_32 flush_rows; /* number of rows written since last flush */
#endif /* PNG_WRITE_FLUSH_SUPPORTED */
#if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
int gamma_shift; /* number of "insignificant" bits 16-bit gamma */
float gamma; /* file gamma value */
float screen_gamma; /* screen gamma value (display_gamma/viewing_gamma */
#endif /* PNG_READ_GAMMA_SUPPORTED */
#if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
png_bytep gamma_table; /* gamma table for 8 bit depth files */
png_bytep gamma_from_1; /* converts from 1.0 to screen */
png_bytep gamma_to_1; /* converts from file to 1.0 */
png_uint_16pp gamma_16_table; /* gamma table for 16 bit depth files */
png_uint_16pp gamma_16_from_1; /* converts from 1.0 to screen */
png_uint_16pp gamma_16_to_1; /* converts from file to 1.0 */
#endif /* PNG_READ_GAMMA_SUPPORTED || PNG_WRITE_GAMMA_SUPPORTED */
#if defined(PNG_READ_GAMMA_SUPPORTED) || defined (PNG_READ_sBIT_SUPPORTED)
png_color_8 sig_bit; /* significant bits in each available channel */
#endif /* PNG_READ_GAMMA_SUPPORTED || PNG_READ_sBIT_SUPPORTED */
#if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
png_color_8 shift; /* shift for significant bit tranformation */
#endif /* PNG_READ_SHIFT_SUPPORTED || PNG_WRITE_SHIFT_SUPPORTED */
#if defined(PNG_READ_tRNS_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) \
|| defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
png_bytep trans; /* transparency values for paletted files */
png_color_16 trans_values; /* transparency values for non-paletted files */
#endif /* PNG_READ|WRITE_tRNS_SUPPORTED||PNG_READ_EXPAND|BACKGROUND_SUPPORTED */
png_read_status_ptr read_row_fn; /* called after each row is decoded */
png_write_status_ptr write_row_fn; /* called after each row is encoded */
#ifdef PNG_PROGRESSIVE_READ_SUPPORTED
png_progressive_info_ptr info_fn; /* called after header data fully read */
png_progressive_row_ptr row_fn; /* called after each prog. row is decoded */
png_progressive_end_ptr end_fn; /* called after image is complete */
png_bytep save_buffer_ptr; /* current location in save_buffer */
png_bytep save_buffer; /* buffer for previously read data */
png_bytep current_buffer_ptr; /* current location in current_buffer */
png_bytep current_buffer; /* buffer for recently used data */
png_uint_32 push_length; /* size of current input chunk */
png_uint_32 skip_length; /* bytes to skip in input data */
png_size_t save_buffer_size; /* amount of data now in save_buffer */
png_size_t save_buffer_max; /* total size of save_buffer */
png_size_t buffer_size; /* total amount of available input data */
png_size_t current_buffer_size; /* amount of data now in current_buffer */
int process_mode; /* what push library is currently doing */
int cur_palette; /* current push library palette index */
#if defined(PNG_READ_tEXt_SUPPORTED) || defined(PNG_READ_zTXt_SUPPORTED)
png_size_t current_text_size; /* current size of text input data */
png_size_t current_text_left; /* how much text left to read in input */
png_charp current_text; /* current text chunk buffer */
png_charp current_text_ptr; /* current location in current_text */
#endif /* PNG_PROGRESSIVE_READ_SUPPORTED && PNG_READ_tEXt/zTXt_SUPPORTED */
#endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
#if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
/* for the Borland special 64K segment handler */
png_bytepp offset_table_ptr;
png_bytep offset_table;
png_uint_16 offset_table_number;
png_uint_16 offset_table_count;
png_uint_16 offset_table_count_free;
#endif /* __TURBOC__&&!_Windows&&!__FLAT__ */
#if defined(PNG_READ_DITHER_SUPPORTED)
png_bytep palette_lookup; /* lookup table for dithering */
png_bytep dither_index; /* index translation for palette files */
#endif /* PNG_READ_DITHER_SUPPORTED */
#if defined(PNG_READ_DITHER_SUPPORTED) || defined(PNG_READ_hIST_SUPPORTED)
png_uint_16p hist; /* histogram */
#endif
#if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
png_byte heuristic_method; /* heuristic for row filter selection */
png_byte num_prev_filters; /* number of weights for previous rows */
png_bytep prev_filters; /* filter type(s) of previous row(s) */
png_uint_16p filter_weights; /* weight(s) for previous line(s) */
png_uint_16p inv_filter_weights; /* 1/weight(s) for previous line(s) */
png_uint_16p filter_costs; /* relative filter calculation cost */
png_uint_16p inv_filter_costs; /* 1/relative filter calculation cost */
#endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
#if defined(PNG_TIME_RFC1123_SUPPORTED)
png_charp time_buffer; /* String to hold RFC 1123 time text */
#endif /* PNG_TIME_RFC1123_SUPPORTED */
#ifdef PNG_USER_MEM_SUPPORTED
png_voidp mem_ptr; /* user supplied struct for mem functions */
png_malloc_ptr malloc_fn; /* function for allocating memory */
png_free_ptr free_fn; /* function for freeing memory */
#endif /* PNG_USER_MEM_SUPPORTED */
};
typedef png_struct FAR * FAR * png_structpp;
/* Here are the function definitions most commonly used. This is not
* the place to find out how to use libpng. See libpng.txt for the
* full explanation, see example.c for the summary. This just provides
* a simple one line of the use of each function.
*/
/* Tell lib we have already handled the first <num_bytes> magic bytes.
* Handling more than 8 bytes from the beginning of the file is an error.
*/
extern PNG_EXPORT(void,png_set_sig_bytes) PNGARG((png_structp png_ptr,
int num_bytes));
/* Check sig[start] through sig[start + num_to_check - 1] to see if it's a
* PNG file. Returns zero if the supplied bytes match the 8-byte PNG
* signature, and non-zero otherwise. Having num_to_check == 0 or
* start > 7 will always fail (ie return non-zero).
*/
extern PNG_EXPORT(int,png_sig_cmp) PNGARG((png_bytep sig, png_size_t start,
png_size_t num_to_check));
/* Simple signature checking function. This is the same as calling
* png_check_sig(sig, n) := !png_sig_cmp(sig, 0, n).
*/
extern PNG_EXPORT(int,png_check_sig) PNGARG((png_bytep sig, int num));
/* Allocate and initialize png_ptr struct for reading, and any other memory. */
extern PNG_EXPORT(png_structp,png_create_read_struct)
PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
png_error_ptr error_fn, png_error_ptr warn_fn));
/* Allocate and initialize png_ptr struct for writing, and any other memory */
extern PNG_EXPORT(png_structp,png_create_write_struct)
PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
png_error_ptr error_fn, png_error_ptr warn_fn));
#ifdef PNG_USER_MEM_SUPPORTED
extern PNG_EXPORT(png_structp,png_create_read_struct_2)
PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
png_malloc_ptr malloc_fn, png_free_ptr free_fn));
extern PNG_EXPORT(png_structp,png_create_write_struct_2)
PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
png_malloc_ptr malloc_fn, png_free_ptr free_fn));
#endif
/* Write a PNG chunk - size, type, (optional) data, CRC. */
extern PNG_EXPORT(void,png_write_chunk) PNGARG((png_structp png_ptr,
png_bytep chunk_name, png_bytep data, png_size_t length));
/* Write the start of a PNG chunk - length and chunk name. */
extern PNG_EXPORT(void,png_write_chunk_start) PNGARG((png_structp png_ptr,
png_bytep chunk_name, png_uint_32 length));
/* Write the data of a PNG chunk started with png_write_chunk_start(). */
extern PNG_EXPORT(void,png_write_chunk_data) PNGARG((png_structp png_ptr,
png_bytep data, png_size_t length));
/* Finish a chunk started with png_write_chunk_start() (includes CRC). */
extern PNG_EXPORT(void,png_write_chunk_end) PNGARG((png_structp png_ptr));
/* Allocate and initialize the info structure */
extern PNG_EXPORT(png_infop,png_create_info_struct)
PNGARG((png_structp png_ptr));
/* Initialize the info structure (old interface - NOT DLL EXPORTED) */
extern void png_info_init PNGARG((png_infop info_ptr));
/* Writes all the PNG information before the image. */
extern PNG_EXPORT(void,png_write_info) PNGARG((png_structp png_ptr,
png_infop info_ptr));
/* read the information before the actual image data. */
extern PNG_EXPORT(void,png_read_info) PNGARG((png_structp png_ptr,
png_infop info_ptr));
#if defined(PNG_TIME_RFC1123_SUPPORTED)
extern PNG_EXPORT(png_charp,png_convert_to_rfc1123)
PNGARG((png_structp png_ptr, png_timep ptime));
#endif /* PNG_TIME_RFC1123_SUPPORTED */
#if defined(PNG_WRITE_tIME_SUPPORTED)
/* convert from a struct tm to png_time */
extern PNG_EXPORT(void,png_convert_from_struct_tm) PNGARG((png_timep ptime,
struct tm FAR * ttime));
/* convert from time_t to png_time. Uses gmtime() */
extern PNG_EXPORT(void,png_convert_from_time_t) PNGARG((png_timep ptime,
time_t ttime));
#endif /* PNG_WRITE_tIME_SUPPORTED */
#if defined(PNG_READ_EXPAND_SUPPORTED)
/* Expand data to 24 bit RGB, or 8 bit grayscale, with alpha if available. */
extern PNG_EXPORT(void,png_set_expand) PNGARG((png_structp png_ptr));
#endif /* PNG_READ_EXPAND_SUPPORTED */
#if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
/* Use blue, green, red order for pixels. */
extern PNG_EXPORT(void,png_set_bgr) PNGARG((png_structp png_ptr));
#endif /* PNG_READ_BGR_SUPPORTED || PNG_WRITE_BGR_SUPPORTED */
#if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
/* Expand the grayscale to 24 bit RGB if necessary. */
extern PNG_EXPORT(void,png_set_gray_to_rgb) PNGARG((png_structp png_ptr));
#endif /* PNG_READ_GRAY_TO_RGB_SUPPORTED */
#if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
/* Reduce RGB to grayscale. (Not yet implemented) */
extern PNG_EXPORT(void,png_set_rgb_to_gray) PNGARG((png_structp png_ptr));
#endif /* PNG_READ_RGB_TO_GRAY_SUPPORTED */
#if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
extern PNG_EXPORT(void,png_set_strip_alpha) PNGARG((png_structp png_ptr));
#endif /* PNG_READ_STRIP_ALPHA_SUPPORTED */
#if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
extern PNG_EXPORT(void,png_set_swap_alpha) PNGARG((png_structp png_ptr));
#endif /* PNG_READ_SWAP_ALPHA_SUPPORTED || PNG_WRITE_SWAP_ALPHA_SUPPORTED */
#if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
extern PNG_EXPORT(void,png_set_invert_alpha) PNGARG((png_structp png_ptr));
#endif /* PNG_READ_INVERT_ALPHA_SUPPORTED || PNG_WRITE_INVERT_ALPHA_SUPPORTED */
#if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
/* Add a filler byte to 24-bit RGB images. */
extern PNG_EXPORT(void,png_set_filler) PNGARG((png_structp png_ptr,
png_uint_32 filler, int flags));
/* The values of the PNG_FILLER_ defines should NOT be changed */
#define PNG_FILLER_BEFORE 0
#define PNG_FILLER_AFTER 1
#endif /* PNG_READ_FILLER_SUPPORTED || PNG_WRITE_FILLER_SUPPORTED */
#if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
/* Swap bytes in 16 bit depth files. */
extern PNG_EXPORT(void,png_set_swap) PNGARG((png_structp png_ptr));
#endif /* PNG_READ_SWAP_SUPPORTED || PNG_WRITE_SWAP_SUPPORTED */
#if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
/* Use 1 byte per pixel in 1, 2, or 4 bit depth files. */
extern PNG_EXPORT(void,png_set_packing) PNGARG((png_structp png_ptr));
#endif /* PNG_READ_PACK_SUPPORTED || PNG_WRITE_PACK_SUPPORTED */
#if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
/* Swap packing order of pixels in bytes. */
extern PNG_EXPORT(void,png_set_packswap) PNGARG((png_structp png_ptr));
#endif /* PNG_READ_PACKSWAP_SUPPORTED || PNG_WRITE_PACKSWAP_SUPPOR */
#if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
/* Converts files to legal bit depths. */
extern PNG_EXPORT(void,png_set_shift) PNGARG((png_structp png_ptr,
png_color_8p true_bits));
#endif /* PNG_READ_SHIFT_SUPPORTED || PNG_WRITE_SHIFT_SUPPORTED */
#if defined(PNG_READ_INTERLACING_SUPPORTED) || \
defined(PNG_WRITE_INTERLACING_SUPPORTED)
/* Have the code handle the interlacing. Returns the number of passes. */
extern PNG_EXPORT(int,png_set_interlace_handling) PNGARG((png_structp png_ptr));
#endif /* PNG_READ_INTERLACING_SUPPORTED || PNG_WRITE_INTERLACING_SUPPORTED */
#if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
/* Invert monocrome files */
extern PNG_EXPORT(void,png_set_invert_mono) PNGARG((png_structp png_ptr));
#endif /* PNG_READ_INVERT_SUPPORTED || PNG_WRITE_INVERT_SUPPORTED */
#if defined(PNG_READ_BACKGROUND_SUPPORTED)
/* Handle alpha and tRNS by replacing with a background color. */
extern PNG_EXPORT(void,png_set_background) PNGARG((png_structp png_ptr,
png_color_16p background_color, int background_gamma_code,
int need_expand, double background_gamma));
#define PNG_BACKGROUND_GAMMA_UNKNOWN 0
#define PNG_BACKGROUND_GAMMA_SCREEN 1
#define PNG_BACKGROUND_GAMMA_FILE 2
#define PNG_BACKGROUND_GAMMA_UNIQUE 3
#endif /* PNG_READ_BACKGROUND_SUPPORTED */
#if defined(PNG_READ_16_TO_8_SUPPORTED)
/* strip the second byte of information from a 16 bit depth file. */
extern PNG_EXPORT(void,png_set_strip_16) PNGARG((png_structp png_ptr));
#endif /* PNG_READ_16_TO_8_SUPPORTED */
#if defined(PNG_READ_DITHER_SUPPORTED)
/* Turn on dithering, and reduce the palette to the number of colors available. */
extern PNG_EXPORT(void,png_set_dither) PNGARG((png_structp png_ptr,
png_colorp palette, int num_palette, int maximum_colors,
png_uint_16p histogram, int full_dither));
#endif /* PNG_READ_DITHER_SUPPORTED */
#if defined(PNG_READ_GAMMA_SUPPORTED)
/* Handle gamma correction. Screen_gamma=(display_gamma/viewing_gamma) */
extern PNG_EXPORT(void,png_set_gamma) PNGARG((png_structp png_ptr,
double screen_gamma, double default_file_gamma));
#endif /* PNG_READ_GAMMA_SUPPORTED */
#if defined(PNG_WRITE_FLUSH_SUPPORTED)
/* Set how many lines between output flushes - 0 for no flushing */
extern PNG_EXPORT(void,png_set_flush) PNGARG((png_structp png_ptr, int nrows));
/* Flush the current PNG output buffer */
extern PNG_EXPORT(void,png_write_flush) PNGARG((png_structp png_ptr));
#endif /* PNG_WRITE_FLUSH_SUPPORTED */
/* optional call to update the users info structure */
extern PNG_EXPORT(void,png_read_update_info) PNGARG((png_structp png_ptr, png_infop info_ptr));
/* read a row of data.*/
extern PNG_EXPORT(void,png_read_row) PNGARG((png_structp png_ptr,
png_bytep row,
png_bytep display_row));
/* read the whole image into memory at once. */
extern PNG_EXPORT(void,png_read_image) PNGARG((png_structp png_ptr,
png_bytepp image));
/* read the end of the PNG file. */
extern PNG_EXPORT(void,png_read_end) PNGARG((png_structp png_ptr,
png_infop info_ptr));
/* free any memory associated with the png_struct and the png_info_structs */
extern PNG_EXPORT(void,png_destroy_read_struct) PNGARG((png_structpp
png_ptr_ptr, png_infopp info_ptr_ptr, png_infopp end_info_ptr_ptr));
/* free all memory used by the read (old method - NOT DLL EXPORTED) */
extern void png_read_destroy PNGARG((png_structp png_ptr, png_infop info_ptr,
png_infop end_info_ptr));
/* Values for png_set_crc_action() to say how to handle CRC errors in
* ancillary and critical chunks, and whether to use the data contained
* therein. Note that it is impossible to "discard" data in a critical
* chunk. For versions prior to 0.90, the action was always error/quit,
* whereas in version 0.90 and later, the action for CRC errors in ancillary
* chunks is warn/discard. These values should NOT be changed.
*
* value action:critical action:ancillary
*/
#define PNG_CRC_DEFAULT 0 /* error/quit warn/discard data */
#define PNG_CRC_ERROR_QUIT 1 /* error/quit error/quit */
#define PNG_CRC_WARN_DISCARD 2 /* (INVALID) warn/discard data */
#define PNG_CRC_WARN_USE 3 /* warn/use data warn/use data */
#define PNG_CRC_QUIET_USE 4 /* quiet/use data quiet/use data */
#define PNG_CRC_NO_CHANGE 5 /* use current value use current value */
/* These functions give the user control over the scan-line filtering in
* libpng and the compression methods used by zlib. These functions are
* mainly useful for testing, as the defaults should work with most users.
* Those users who are tight on memory or want faster performance at the
* expense of compression can modify them. See the compression library
* header file (zlib.h) for an explination of the compression functions.
*/
/* set the filtering method(s) used by libpng. Currently, the only valid
* value for "method" is 0.
*/
extern PNG_EXPORT(void,png_set_filter) PNGARG((png_structp png_ptr, int method,
int filters));
/* Flags for png_set_filter() to say which filters to use. The flags
* are chosen so that they don't conflict with real filter types
* below, in case they are supplied instead of the #defined constants.
* These values should NOT be changed.
*/
#define PNG_NO_FILTERS 0x00
#define PNG_FILTER_NONE 0x08
#define PNG_FILTER_SUB 0x10
#define PNG_FILTER_UP 0x20
#define PNG_FILTER_AVG 0x40
#define PNG_FILTER_PAETH 0x80
#define PNG_ALL_FILTERS (PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_UP | \
PNG_FILTER_AVG | PNG_FILTER_PAETH)
/* Filter values (not flags) - used in pngwrite.c, pngwutil.c for now.
* These defines should NOT be changed.
*/
#define PNG_FILTER_VALUE_NONE 0
#define PNG_FILTER_VALUE_SUB 1
#define PNG_FILTER_VALUE_UP 2
#define PNG_FILTER_VALUE_AVG 3
#define PNG_FILTER_VALUE_PAETH 4
#define PNG_FILTER_VALUE_LAST 5
#if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* EXPERIMENTAL */
/* The "heuristic_method" is given by one of the PNG_FILTER_HEURISTIC_
* defines, either the default (minimum-sum-of-absolute-differences), or
* the experimental method (weighted-minimum-sum-of-absolute-differences).
*
* Weights are factors >= 1.0, indicating how important it is to keep the
* filter type consistent between rows. Larger numbers mean the current
* filter is that many times as likely to be the same as the "num_weights"
* previous filters. This is cumulative for each previous row with a weight.
* There needs to be "num_weights" values in "filter_weights", or it can be
* NULL if the weights aren't being specified. Weights have no influence on
* the selection of the first row filter. Well chosen weights can (in theory)
* improve the compression for a given image.
*
* Costs are factors >= 1.0 indicating the relative decoding costs of a
* filter type. Higher costs indicate more decoding expense, and are
* therefore less likely to be selected over a filter with lower computational
* costs. There needs to be a value in "filter_costs" for each valid filter
* type (given by PNG_FILTER_VALUE_LAST), or it can be NULL if you aren't
* setting the costs. Costs try to improve the speed of decompression without
* unduly increasing the compressed image size.
*
* A negative weight or cost indicates the default value is to be used, and
* values in the range [0.0, 1.0) indicate the value is to remain unchanged.
* The default values for both weights and costs are currently 1.0, but may
* change if good general weighting/cost heuristics can be found. If both
* the weights and costs are set to 1.0, this degenerates the WEIGHTED method
* to the UNWEIGHTED method, but with added encoding time/computation.
*/
extern PNG_EXPORT(void,png_set_filter_heuristics) PNGARG((png_structp png_ptr,
int heuristic_method, int num_weights, png_doublep filter_weights,
png_doublep filter_costs));
#endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
/* Heuristic used for row filter selection. These defines should NOT be
* changed.
*/
#define PNG_FILTER_HEURISTIC_DEFAULT 0 /* Currently "UNWEIGHTED" */
#define PNG_FILTER_HEURISTIC_UNWEIGHTED 1 /* Used by libpng < 0.95 */
#define PNG_FILTER_HEURISTIC_WEIGHTED 2 /* Experimental feature */
#define PNG_FILTER_HEURISTIC_LAST 3 /* Not a valid value */
/* Set the library compression level. Currently, valid values range from
* 0 - 9, corresponding directly to the zlib compression levels 0 - 9
* (0 - no compression, 9 - "maximal" compression). Note that tests have
* shown that zlib compression levels 3-6 usually perform as well as level 9
* for PNG images, and do considerably fewer caclulations. In the future,
* these values may not correspond directly to the zlib compression levels.
*/
extern PNG_EXPORT(void,png_set_compression_level) PNGARG((png_structp png_ptr,
int level));
extern PNG_EXPORT(void,png_set_compression_mem_level)
PNGARG((png_structp png_ptr, int mem_level));
extern PNG_EXPORT(void,png_set_compression_strategy)
PNGARG((png_structp png_ptr, int strategy));
extern PNG_EXPORT(void,png_set_compression_window_bits)
PNGARG((png_structp png_ptr, int window_bits));
extern PNG_EXPORT(void,png_set_compression_method) PNGARG((png_structp png_ptr,
int method));
/* These next functions are called for input/output, memory, and error
* handling. They are in the file pngrio.c, pngwio.c, and pngerror.c,
* and call standard C I/O routines such as fread(), fwrite(), and
* fprintf(). These functions can be made to use other I/O routines
* at run time for those applications that need to handle I/O in a
* different manner by calling png_set_???_fn(). See libpng.txt for
* more information.
*/
/* Initialize the input/output for the PNG file to the default functions. */
extern PNG_EXPORT(void,png_init_io) PNGARG((png_structp png_ptr, FILE *fp));
/* Replace the (error and abort), and warning functions with user
* supplied functions. If no messages are to be printed you must still
* write and use replacement functions. The replacement error_fn should
* still do a longjmp to the last setjmp location if you are using this
* method of error handling. If error_fn or warning_fn is NULL, the
* default function will be used.
*/
extern PNG_EXPORT(void,png_set_error_fn) PNGARG((png_structp png_ptr,
png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warning_fn));
/* Replace the default data output functions with a user supplied one(s).
* If buffered output is not used, then output_flush_fn can be set to NULL.
* If PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile time
* output_flush_fn will be ignored (and thus can be NULL).
*/
extern PNG_EXPORT(void,png_set_write_fn) PNGARG((png_structp png_ptr,
png_voidp io_ptr, png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn));
/* Replace the default data input function with a user supplied one. */
extern PNG_EXPORT(void,png_set_read_fn) PNGARG((png_structp png_ptr,
png_voidp io_ptr, png_rw_ptr read_data_fn));
extern PNG_EXPORT(void,png_set_write_status_fn) PNGARG((png_structp png_ptr,
png_write_status_ptr write_row_fn));
#ifdef PNG_USER_MEM_SUPPORTED
/* Replace the default memory allocation functions with user supplied one(s). */
extern PNG_EXPORT(void,png_set_mem_fn) PNGARG((png_structp png_ptr,
png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn));
/* Return the user pointer associated with the memory functions */
extern PNG_EXPORT(png_voidp,png_get_mem_ptr) PNGARG((png_structp png_ptr));
#endif /* PNG_USER_MEM_SUPPORTED */
#ifdef PNG_READ_USER_TRANSFORM_SUPPORTED
extern PNG_EXPORT(void,png_set_read_user_transform_fn) PNGARG((png_structp
png_ptr, png_user_transform_ptr read_user_transform_fn));
#endif
#ifdef PNG_WRITE_USER_TRANSFORM_SUPPORTED
extern PNG_EXPORT(void,png_set_write_user_transform_fn) PNGARG((png_structp
png_ptr, png_user_transform_ptr write_user_transform_fn));
#endif
#ifdef PNG_PROGRESSIVE_READ_SUPPORTED
/* Sets the function callbacks for the push reader, and a pointer to a
* user-defined structure available to the callback functions.
*/
extern PNG_EXPORT(void,png_set_progressive_read_fn) PNGARG((png_structp png_ptr,
png_voidp progressive_ptr,
png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
png_progressive_end_ptr end_fn));
/* returns the user pointer associated with the push read functions */
extern PNG_EXPORT(png_voidp,png_get_progressive_ptr)
PNGARG((png_structp png_ptr));
/* function to be called when data becomes available */
extern PNG_EXPORT(void,png_process_data) PNGARG((png_structp png_ptr,
png_infop info_ptr, png_bytep buffer, png_size_t buffer_size));
/* function that combines rows. Not very much different than the
* png_combine_row() call. Is this even used?????
*/
extern PNG_EXPORT(void,png_progressive_combine_row) PNGARG((png_structp png_ptr,
png_bytep old_row, png_bytep new_row));
#endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
extern PNG_EXPORT(png_voidp,png_malloc) PNGARG((png_structp png_ptr,
png_uint_32 size));
/* frees a pointer allocated by png_malloc() */
extern PNG_EXPORT(void,png_free) PNGARG((png_structp png_ptr, png_voidp ptr));
#ifdef PNG_USER_MEM_SUPPORTED
extern PNG_EXPORT(png_voidp,png_malloc_default) PNGARG((png_structp png_ptr,
png_uint_32 size));
extern PNG_EXPORT(void,png_free_default) PNGARG((png_structp png_ptr,
png_voidp ptr));
#endif /* PNG_USER_MEM_SUPPORTED */
extern PNG_EXPORT(png_voidp,png_memcpy_check) PNGARG((png_structp png_ptr,
png_voidp s1, png_voidp s2, png_uint_32 size));
extern PNG_EXPORT(png_voidp,png_memset_check) PNGARG((png_structp png_ptr,
png_voidp s1, int value, png_uint_32 size));
#if defined(USE_FAR_KEYWORD) /* memory model conversion function */
extern void *png_far_to_near PNGARG((png_structp png_ptr,png_voidp ptr,
int check));
#endif /* USE_FAR_KEYWORD */
/* Fatal error in PNG image of libpng - can't continue */
extern PNG_EXPORT(void,png_error) PNGARG((png_structp png_ptr,
png_const_charp error));
/* The same, but the chunk name is prepended to the error string. */
extern PNG_EXPORT(void,png_chunk_error) PNGARG((png_structp png_ptr,
png_const_charp error));
/* Non-fatal error in libpng. Can continue, but may have a problem. */
extern PNG_EXPORT(void,png_warning) PNGARG((png_structp png_ptr,
png_const_charp message));
/* Non-fatal error in libpng, chunk name is prepended to message. */
extern PNG_EXPORT(void,png_chunk_warning) PNGARG((png_structp png_ptr,
png_const_charp message));
/* The png_set_<chunk> functions are for storing values in the png_info_struct.
* Similarly, the png_get_<chunk> calls are used to read values from the
* png_info_struct, either storing the parameters in the passed variables, or
* setting pointers into the png_info_struct where the data is stored. The
* png_get_<chunk> functions return a non-zero value if the data was available
* in info_ptr, or return zero and do not change any of the parameters if the
* data was not available.
*
* These functions should be used instead of directly accessing png_info
* to avoid problems with future changes in the size and internal layout of
* png_info_struct.
*/
/* Returns number of bytes needed to hold a transformed row. */
extern PNG_EXPORT(png_uint_32,png_get_rowbytes) PNGARG((png_structp png_ptr,
png_infop info_ptr));
#ifdef PNG_EASY_ACCESS_SUPPORTED
/* Returns image width in pixels. */
extern PNG_EXPORT(png_uint_32, png_get_image_width) PNGARG((png_structp
png_ptr, png_infop info_ptr));
/* Returns image height in pixels. */
extern PNG_EXPORT(png_uint_32, png_get_image_height) PNGARG((png_structp
png_ptr, png_infop info_ptr));
/* Returns image bit_depth. */
extern PNG_EXPORT(png_byte, png_get_bit_depth) PNGARG((png_structp
png_ptr, png_infop info_ptr));
/* Returns image color_type. */
extern PNG_EXPORT(png_byte, png_get_color_type) PNGARG((png_structp
png_ptr, png_infop info_ptr));
/* Returns image filter_type. */
extern PNG_EXPORT(png_byte, png_get_filter_type) PNGARG((png_structp
png_ptr, png_infop info_ptr));
/* Returns image interlace_type. */
extern PNG_EXPORT(png_byte, png_get_interlace_type) PNGARG((png_structp
png_ptr, png_infop info_ptr));
/* Returns image compression_type. */
extern PNG_EXPORT(png_byte, png_get_compression_type) PNGARG((png_structp
png_ptr, png_infop info_ptr));
/* Returns image resolution in pixels per meter, from pHYs chunk data. */
extern PNG_EXPORT(png_uint_32, png_get_pixels_per_meter) PNGARG((png_structp
png_ptr, png_infop info_ptr));
extern PNG_EXPORT(png_uint_32, png_get_x_pixels_per_meter) PNGARG((png_structp
png_ptr, png_infop info_ptr));
extern PNG_EXPORT(png_uint_32, png_get_y_pixels_per_meter) PNGARG((png_structp
png_ptr, png_infop info_ptr));
/* Returns pixel aspect ratio, computed from pHYs chunk data. */
extern PNG_EXPORT(float, png_get_pixel_aspect_ratio) PNGARG((png_structp
png_ptr, png_infop info_ptr));
#endif /* PNG_EASY_ACCESS_SUPPORTED */
#if defined(PNG_READ_bKGD_SUPPORTED)
extern PNG_EXPORT(png_uint_32,png_get_bKGD) PNGARG((png_structp png_ptr,
png_infop info_ptr, png_color_16p *background));
#endif /* PNG_READ_bKGD_SUPPORTED */
#if defined(PNG_READ_bKGD_SUPPORTED) || defined(PNG_WRITE_bKGD_SUPPORTED)
extern PNG_EXPORT(void,png_set_bKGD) PNGARG((png_structp png_ptr,
png_infop info_ptr, png_color_16p background));
#endif /* PNG_READ_bKGD_SUPPORTED || PNG_WRITE_bKGD_SUPPORTED */
#if defined(PNG_READ_cHRM_SUPPORTED)
extern PNG_EXPORT(png_uint_32,png_get_cHRM) PNGARG((png_structp png_ptr,
png_infop info_ptr, double *white_x, double *white_y, double *red_x,
double *red_y, double *green_x, double *green_y, double *blue_x,
double *blue_y));
#endif /* PNG_READ_cHRM_SUPPORTED */
#if defined(PNG_READ_cHRM_SUPPORTED) || defined(PNG_WRITE_cHRM_SUPPORTED)
extern PNG_EXPORT(void,png_set_cHRM) PNGARG((png_structp png_ptr,
png_infop info_ptr, double white_x, double white_y, double red_x,
double red_y, double green_x, double green_y, double blue_x, double blue_y));
#endif /* PNG_READ_cHRM_SUPPORTED || PNG_WRITE_cHRM_SUPPORTED */
#if defined(PNG_READ_gAMA_SUPPORTED)
extern PNG_EXPORT(png_uint_32,png_get_gAMA) PNGARG((png_structp png_ptr,
png_infop info_ptr, double *file_gamma));
#endif /* PNG_READ_gAMA_SUPPORTED */
#if defined(PNG_READ_gAMA_SUPPORTED) || defined(PNG_WRITE_gAMA_SUPPORTED)
extern PNG_EXPORT(void,png_set_gAMA) PNGARG((png_structp png_ptr,
png_infop info_ptr, double file_gamma));
#endif /* PNG_READ_gAMA_SUPPORTED || PNG_WRITE_gAMA_SUPPORTED */
#if defined(PNG_READ_hIST_SUPPORTED)
extern PNG_EXPORT(png_uint_32,png_get_hIST) PNGARG((png_structp png_ptr,
png_infop info_ptr, png_uint_16p *hist));
#endif /* PNG_READ_hIST_SUPPORTED */
#if defined(PNG_READ_hIST_SUPPORTED) || defined(PNG_WRITE_hIST_SUPPORTED)
extern PNG_EXPORT(void,png_set_hIST) PNGARG((png_structp png_ptr,
png_infop info_ptr, png_uint_16p hist));
#endif /* PNG_READ_hIST_SUPPORTED || PNG_WRITE_hIST_SUPPORTED */
extern PNG_EXPORT(png_uint_32,png_get_IHDR) PNGARG((png_structp png_ptr,
png_infop info_ptr, png_uint_32 *width, png_uint_32 *height,
int *bit_depth, int *color_type, int *interlace_type,
int *compression_type, int *filter_type));
extern PNG_EXPORT(void,png_set_IHDR) PNGARG((png_structp png_ptr,
png_infop info_ptr, png_uint_32 width, png_uint_32 height, int bit_depth,
int color_type, int interlace_type, int compression_type, int filter_type));
#if defined(PNG_READ_oFFs_SUPPORTED)
extern PNG_EXPORT(png_uint_32,png_get_oFFs) PNGARG((png_structp png_ptr,
png_infop info_ptr, png_uint_32 *offset_x, png_uint_32 *offset_y,
int *unit_type));
#endif /* PNG_READ_oFFs_SUPPORTED */
#if defined(PNG_READ_oFFs_SUPPORTED) || defined(PNG_WRITE_oFFs_SUPPORTED)
extern PNG_EXPORT(void,png_set_oFFs) PNGARG((png_structp png_ptr,
png_infop info_ptr, png_uint_32 offset_x, png_uint_32 offset_y,
int unit_type));
#endif /* PNG_READ_oFFs_SUPPORTED || PNG_WRITE_oFFs_SUPPORTED */
#if defined(PNG_READ_pCAL_SUPPORTED)
extern PNG_EXPORT(png_uint_32,png_get_pCAL) PNGARG((png_structp png_ptr,
png_infop info_ptr, png_charp *purpose, png_int_32 *X0, png_int_32 *X1,
int *type, int *nparams, png_charp *units, png_charpp *params));
#endif /* PNG_READ_pCAL_SUPPORTED */
#if defined(PNG_READ_pCAL_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED)
extern PNG_EXPORT(void,png_set_pCAL) PNGARG((png_structp png_ptr,
png_infop info_ptr, png_charp purpose, png_int_32 X0, png_int_32 X1,
int type, int nparams, png_charp units, png_charpp params));
#endif /* PNG_READ_pCAL_SUPPORTED || PNG_WRITE_pCAL_SUPPORTED */
#if defined(PNG_READ_pHYs_SUPPORTED)
extern PNG_EXPORT(png_uint_32,png_get_pHYs) PNGARG((png_structp png_ptr,
png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
#endif /* PNG_READ_pHYs_SUPPORTED */
#if defined(PNG_READ_pHYs_SUPPORTED) || defined(PNG_WRITE_pHYs_SUPPORTED)
extern PNG_EXPORT(void,png_set_pHYs) PNGARG((png_structp png_ptr,
png_infop info_ptr, png_uint_32 res_x, png_uint_32 res_y, int unit_type));
#endif /* PNG_READ_pHYs_SUPPORTED || PNG_WRITE_pHYs_SUPPORTED */
extern PNG_EXPORT(png_uint_32,png_get_PLTE) PNGARG((png_structp png_ptr,
png_infop info_ptr, png_colorp *palette, int *num_palette));
extern PNG_EXPORT(void,png_set_PLTE) PNGARG((png_structp png_ptr,
png_infop info_ptr, png_colorp palette, int num_palette));
#if defined(PNG_READ_sBIT_SUPPORTED)
extern PNG_EXPORT(png_uint_32,png_get_sBIT) PNGARG((png_structp png_ptr,
png_infop info_ptr, png_color_8p *sig_bit));
#endif /* PNG_READ_sBIT_SUPPORTED */
#if defined(PNG_READ_sBIT_SUPPORTED) || defined(PNG_WRITE_sBIT_SUPPORTED)
extern PNG_EXPORT(void,png_set_sBIT) PNGARG((png_structp png_ptr,
png_infop info_ptr, png_color_8p sig_bit));
#endif /* PNG_READ_sBIT_SUPPORTED || PNG_WRITE_sBIT_SUPPORTED */
#if defined(PNG_READ_sRGB_SUPPORTED)
extern PNG_EXPORT(png_uint_32,png_get_sRGB) PNGARG((png_structp png_ptr,
png_infop info_ptr, int *intent));
#endif /* PNG_READ_sRGB_SUPPORTED */
#if defined(PNG_READ_sRGB_SUPPORTED) || defined(PNG_WRITE_sRGB_SUPPORTED)
extern PNG_EXPORT(void,png_set_sRGB) PNGARG((png_structp png_ptr,
png_infop info_ptr, int intent));
extern PNG_EXPORT(void,png_set_sRGB_gAMA_and_cHRM) PNGARG((png_structp png_ptr,
png_infop info_ptr, int intent));
#endif /* PNG_READ_sRGB_SUPPORTED || PNG_WRITE_sRGB_SUPPORTED */
#if defined(PNG_READ_tEXt_SUPPORTED) || defined(PNG_READ_zTXt_SUPPORTED)
/* png_get_text also returns the number of text chunks in text_ptr */
extern PNG_EXPORT(png_uint_32,png_get_text) PNGARG((png_structp png_ptr,
png_infop info_ptr, png_textp *text_ptr, int *num_text));
#endif /* PNG_READ_tEXt_SUPPORTED || PNG_READ_zTXt_SUPPORTED */
#if defined(PNG_READ_tEXt_SUPPORTED) || defined(PNG_WRITE_tEXt_SUPPORTED) || \
defined(PNG_READ_zTXt_SUPPORTED) || defined(PNG_WRITE_zTXt_SUPPORTED)
extern PNG_EXPORT(void,png_set_text) PNGARG((png_structp png_ptr,
png_infop info_ptr, png_textp text_ptr, int num_text));
#endif /* PNG_READ_OR_WRITE_tEXt_OR_zTXt_SUPPORTED */
#if defined(PNG_READ_tIME_SUPPORTED)
extern PNG_EXPORT(png_uint_32,png_get_tIME) PNGARG((png_structp png_ptr,
png_infop info_ptr, png_timep *mod_time));
#endif /* PNG_READ_tIME_SUPPORTED */
#if defined(PNG_READ_tIME_SUPPORTED) || defined(PNG_WRITE_tIME_SUPPORTED)
extern PNG_EXPORT(void,png_set_tIME) PNGARG((png_structp png_ptr,
png_infop info_ptr, png_timep mod_time));
#endif /* PNG_READ_tIME_SUPPORTED || PNG_WRITE_tIME_SUPPORTED */
#if defined(PNG_READ_tRNS_SUPPORTED)
extern PNG_EXPORT(png_uint_32,png_get_tRNS) PNGARG((png_structp png_ptr,
png_infop info_ptr, png_bytep *trans, int *num_trans,
png_color_16p *trans_values));
#endif /* PNG_READ_tRNS_SUPPORTED */
#if defined(PNG_READ_tRNS_SUPPORTED) || defined(PNG_WRITE_tRNS_SUPPORTED)
extern PNG_EXPORT(void,png_set_tRNS) PNGARG((png_structp png_ptr,
png_infop info_ptr, png_bytep trans, int num_trans,
png_color_16p trans_values));
#endif /* PNG_READ_tRNS_SUPPORTED || PNG_WRITE_tRNS_SUPPORTED */
/* Define PNG_DEBUG at compile time for debugging information. Higher
* numbers for PNG_DEBUG mean more debugging information. This has
* only been added since version 0.95 so it is not implemented throughout
* libpng yet, but more support will be added as needed.
*/
#if (PNG_DEBUG > 0)
#ifdef PNG_NO_STDIO
#include <stdio.h>
#endif
#ifndef PNG_DEBUG_FILE
#define PNG_DEBUG_FILE stderr
#endif /* PNG_DEBUG_FILE */
#define png_debug(l,m) if (PNG_DEBUG > l) \
fprintf(PNG_DEBUG_FILE,"%s"m,(l==1 ? "\t" : \
(l==2 ? "\t\t":(l==3 ? "\t\t\t":""))))
#define png_debug1(l,m,p1) if (PNG_DEBUG > l) \
fprintf(PNG_DEBUG_FILE,"%s"m,(l==1 ? "\t" : \
(l==2 ? "\t\t":(l==3 ? "\t\t\t":""))),p1)
#define png_debug2(l,m,p1,p2) if (PNG_DEBUG > l) \
fprintf(PNG_DEBUG_FILE,"%s"m,(l==1 ? "\t" : \
(l==2 ? "\t\t":(l==3 ? "\t\t\t":""))),p1,p2)
#else
#define png_debug(l, m)
#define png_debug1(l, m, p1)
#define png_debug2(l, m, p1, p2)
#endif /* (PNG_DEBUG > 0) */
#ifdef PNG_READ_COMPOSITE_NODIV_SUPPORTED
/* With these routines we avoid an integer divide, which will be slower on
* most machines. However, it does take more operations than the corresponding
* divide method, so it may be slower on a few RISC systems. There are two
* shifts (by 8 or 16 bits) and an addition, versus a single integer divide.
*
* Note that the rounding factors are NOT supposed to be the same! 128 and
* 32768 are correct for the NODIV code; 127 and 32767 are correct for the
* standard method.
*
* [Optimized code by Greg Roelofs and Mark Adler...blame us for bugs. :-) ]
*/
/* fg and bg should be in `gamma 1.0' space; alpha is the opacity */
# define png_composite(composite, fg, alpha, bg) \
{ png_uint_16 temp = ((png_uint_16)(fg) * (png_uint_16)(alpha) + \
(png_uint_16)(bg)*(png_uint_16)(255 - \
(png_uint_16)(alpha)) + (png_uint_16)128); \
(composite) = (png_byte)((temp + (temp >> 8)) >> 8); }
# define png_composite_16(composite, fg, alpha, bg) \
{ png_uint_32 temp = ((png_uint_32)(fg) * (png_uint_32)(alpha) + \
(png_uint_32)(bg)*(png_uint_32)(65535L - \
(png_uint_32)(alpha)) + (png_uint_32)32768L); \
(composite) = (png_uint_16)((temp + (temp >> 16)) >> 16); }
#else /* standard method using integer division */
/* fg and bg should be in `gamma 1.0' space; alpha is the opacity */
# define png_composite(composite, fg, alpha, bg) \
(composite) = (png_byte)(((png_uint_16)(fg) * (png_uint_16)(alpha) + \
(png_uint_16)(bg) * (png_uint_16)(255 - (png_uint_16)(alpha)) + \
(png_uint_16)127) / 255)
# define png_composite_16(composite, fg, alpha, bg) \
(composite) = (png_uint_16)(((png_uint_32)(fg) * (png_uint_32)(alpha) + \
(png_uint_32)(bg)*(png_uint_32)(65535L - (png_uint_32)(alpha)) + \
(png_uint_32)32767) / (png_uint_32)65535L)
#endif /* PNG_READ_COMPOSITE_NODIV_SUPPORTED */
/* These next functions are used internally in the code. They generally
* shouldn't be used unless you are writing code to add or replace some
* functionality in libpng. More information about most functions can
* be found in the files where the functions are located.
*/
#if defined(PNG_INTERNAL)
/* Various modes of operation. Note that after an init, mode is set to
* zero automatically when the structure is created.
*/
#define PNG_BEFORE_IHDR 0x00
#define PNG_HAVE_IHDR 0x01
#define PNG_HAVE_PLTE 0x02
#define PNG_HAVE_IDAT 0x04
#define PNG_AFTER_IDAT 0x08
#define PNG_HAVE_IEND 0x10
#define PNG_HAVE_gAMA 0x20
#define PNG_HAVE_cHRM 0x40
#define PNG_HAVE_sRGB 0x80
/* push model modes */
#define PNG_READ_SIG_MODE 0
#define PNG_READ_CHUNK_MODE 1
#define PNG_READ_IDAT_MODE 2
#define PNG_SKIP_MODE 3
#define PNG_READ_tEXt_MODE 4
#define PNG_READ_zTXt_MODE 5
#define PNG_READ_DONE_MODE 6
#define PNG_ERROR_MODE 7
/* flags for the transformations the PNG library does on the image data */
#define PNG_BGR 0x0001
#define PNG_INTERLACE 0x0002
#define PNG_PACK 0x0004
#define PNG_SHIFT 0x0008
#define PNG_SWAP_BYTES 0x0010
#define PNG_INVERT_MONO 0x0020
#define PNG_DITHER 0x0040
#define PNG_BACKGROUND 0x0080
#define PNG_BACKGROUND_EXPAND 0x0100
#define PNG_RGB_TO_GRAY 0x0200 /* Not currently implemented */
#define PNG_16_TO_8 0x0400
#define PNG_RGBA 0x0800
#define PNG_EXPAND 0x1000
#define PNG_GAMMA 0x2000
#define PNG_GRAY_TO_RGB 0x4000
#define PNG_FILLER 0x8000
#define PNG_PACKSWAP 0x10000L
#define PNG_SWAP_ALPHA 0x20000L
#define PNG_STRIP_ALPHA 0x40000L
#define PNG_INVERT_ALPHA 0x80000L
#define PNG_USER_TRANSFORM 0x100000L
/* flags for png_create_struct */
#define PNG_STRUCT_PNG 0x0001
#define PNG_STRUCT_INFO 0x0002
/* Scaling factor for filter heuristic weighting calculations */
#define PNG_WEIGHT_SHIFT 8
#define PNG_WEIGHT_FACTOR (1<<(PNG_WEIGHT_SHIFT))
#define PNG_COST_SHIFT 3
#define PNG_COST_FACTOR (1<<(PNG_COST_SHIFT))
/* flags for the png_ptr->flags rather than declaring a byte for each one */
#define PNG_FLAG_ZLIB_CUSTOM_STRATEGY 0x0001
#define PNG_FLAG_ZLIB_CUSTOM_LEVEL 0x0002
#define PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL 0x0004
#define PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS 0x0008
#define PNG_FLAG_ZLIB_CUSTOM_METHOD 0x0010
#define PNG_FLAG_ZLIB_FINISHED 0x0020
#define PNG_FLAG_ROW_INIT 0x0040
#define PNG_FLAG_FILLER_AFTER 0x0080
#define PNG_FLAG_CRC_ANCILLARY_USE 0x0100
#define PNG_FLAG_CRC_ANCILLARY_NOWARN 0x0200
#define PNG_FLAG_CRC_CRITICAL_USE 0x0400
#define PNG_FLAG_CRC_CRITICAL_IGNORE 0x0800
#define PNG_FLAG_FREE_PALETTE 0x1000
#define PNG_FLAG_FREE_TRANS 0x2000
#define PNG_FLAG_FREE_HIST 0x4000
#define PNG_FLAG_HAVE_CHUNK_HEADER 0x8000L
#define PNG_FLAG_WROTE_tIME 0x10000L
#define PNG_FLAG_BACKGROUND_IS_GRAY 0x20000L
#define PNG_FLAG_CRC_ANCILLARY_MASK (PNG_FLAG_CRC_ANCILLARY_USE | \
PNG_FLAG_CRC_ANCILLARY_NOWARN)
#define PNG_FLAG_CRC_CRITICAL_MASK (PNG_FLAG_CRC_CRITICAL_USE | \
PNG_FLAG_CRC_CRITICAL_IGNORE)
#define PNG_FLAG_CRC_MASK (PNG_FLAG_CRC_ANCILLARY_MASK | \
PNG_FLAG_CRC_CRITICAL_MASK)
/* save typing and make code easier to understand */
#define PNG_COLOR_DIST(c1, c2) (abs((int)((c1).red) - (int)((c2).red)) + \
abs((int)((c1).green) - (int)((c2).green)) + \
abs((int)((c1).blue) - (int)((c2).blue)))
/* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
#if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
/* place to hold the signature string for a PNG file. */
extern png_byte FARDATA png_sig[8];
/* Constant strings for known chunk types. If you need to add a chunk,
* add a string holding the name here. See png.c for more details. We
* can't selectively include these, since we still check for chunk in the
* wrong locations with these labels.
*/
extern png_byte FARDATA png_IHDR[5];
extern png_byte FARDATA png_IDAT[5];
extern png_byte FARDATA png_IEND[5];
extern png_byte FARDATA png_PLTE[5];
extern png_byte FARDATA png_bKGD[5];
extern png_byte FARDATA png_cHRM[5];
extern png_byte FARDATA png_gAMA[5];
extern png_byte FARDATA png_hIST[5];
extern png_byte FARDATA png_oFFs[5];
extern png_byte FARDATA png_pCAL[5];
extern png_byte FARDATA png_pHYs[5];
extern png_byte FARDATA png_sBIT[5];
extern png_byte FARDATA png_sRGB[5];
extern png_byte FARDATA png_tEXt[5];
extern png_byte FARDATA png_tIME[5];
extern png_byte FARDATA png_tRNS[5];
extern png_byte FARDATA png_zTXt[5];
#endif /* PNG_NO_EXTERN */
/* Inline macros to do direct reads of bytes from the input buffer. These
* require that you are using an architecture that uses PNG byte ordering
* (MSB first) and supports unaligned data storage. I think that PowerPC
* in big-endian mode and 680x0 are the only ones that will support this.
* The x86 line of processors definitely do not. The png_get_int_32()
* routine also assumes we are using two's complement format for negative
* values, which is almost certainly true.
*/
#if defined(PNG_READ_BIG_ENDIAN_SUPPORTED)
#if defined(PNG_READ_pCAL_SUPPORTED)
#define png_get_int_32(buf) ( *((png_int_32p) (buf)))
#endif /* PNG_READ_pCAL_SUPPORTED */
#define png_get_uint_32(buf) ( *((png_uint_32p) (buf)))
#define png_get_uint_16(buf) ( *((png_uint_16p) (buf)))
#else
#if defined(PNG_READ_pCAL_SUPPORTED)
PNG_EXTERN png_int_32 png_get_int_32 PNGARG((png_bytep buf));
#endif /* PNG_READ_pCAL_SUPPORTED */
PNG_EXTERN png_uint_32 png_get_uint_32 PNGARG((png_bytep buf));
PNG_EXTERN png_uint_16 png_get_uint_16 PNGARG((png_bytep buf));
#endif /* PNG_READ_BIG_ENDIAN_SUPPORTED */
/* Initialize png_ptr struct for writing, and allocate any other memory.
* (old interface - NOT DLL EXPORTED).
*/
extern void png_write_init PNGARG((png_structp png_ptr));
/* allocate memory for an internal libpng struct */
PNG_EXTERN png_voidp png_create_struct PNGARG((int type));
/* free memory from internal libpng struct */
PNG_EXTERN void png_destroy_struct PNGARG((png_voidp struct_ptr));
PNG_EXTERN png_voidp png_create_struct_2 PNGARG((int type, png_malloc_ptr
malloc_fn));
PNG_EXTERN void png_destroy_struct_2 PNGARG((png_voidp struct_ptr,
png_free_ptr free_fn));
/* free any memory that info_ptr points to and reset struct. */
PNG_EXTERN void png_info_destroy PNGARG((png_structp png_ptr,
png_infop info_ptr));
/* Function to allocate memory for zlib. */
PNG_EXTERN voidpf png_zalloc PNGARG((voidpf png_ptr, uInt items, uInt size));
/* function to free memory for zlib */
PNG_EXTERN void png_zfree PNGARG((voidpf png_ptr, voidpf ptr));
/* reset the CRC variable */
PNG_EXTERN void png_reset_crc PNGARG((png_structp png_ptr));
/* Write the "data" buffer to whatever output you are using. */
PNG_EXTERN void png_write_data PNGARG((png_structp png_ptr, png_bytep data,
png_size_t length));
/* Read data from whatever input you are using into the "data" buffer */
PNG_EXTERN void png_read_data PNGARG((png_structp png_ptr, png_bytep data,
png_size_t length));
/* read bytes into buf, and update png_ptr->crc */
PNG_EXTERN void png_crc_read PNGARG((png_structp png_ptr, png_bytep buf,
png_size_t length));
/* read "skip" bytes, read the file crc, and (optionally) verify png_ptr->crc */
PNG_EXTERN int png_crc_finish PNGARG((png_structp png_ptr, png_uint_32 skip));
/* read the CRC from the file and compare it to the libpng calculated CRC */
PNG_EXTERN int png_crc_error PNGARG((png_structp png_ptr));
/* Calculate the CRC over a section of data. Note that we are only
* passing a maximum of 64K on systems that have this as a memory limit,
* since this is the maximum buffer size we can specify.
*/
PNG_EXTERN void png_calculate_crc PNGARG((png_structp png_ptr, png_bytep ptr,
png_size_t length));
#if defined(PNG_WRITE_FLUSH_SUPPORTED)
PNG_EXTERN void png_flush PNGARG((png_structp png_ptr));
#endif
/* Place a 32-bit number into a buffer in PNG byte order (big-endian).
* The only currently known PNG chunk that uses signed numbers is
* the ancillary extension chunk, pCAL.
*/
PNG_EXTERN void png_save_uint_32 PNGARG((png_bytep buf, png_uint_32 i));
#if defined(PNG_WRITE_pCAL_SUPPORTED)
PNG_EXTERN void png_save_int_32 PNGARG((png_bytep buf, png_int_32 i));
#endif
/* Place a 16 bit number into a buffer in PNG byte order.
* The parameter is declared unsigned int, not png_uint_16,
* just to avoid potential problems on pre-ANSI C compilers.
*/
PNG_EXTERN void png_save_uint_16 PNGARG((png_bytep buf, unsigned int i));
/* simple function to write the signature */
PNG_EXTERN void png_write_sig PNGARG((png_structp png_ptr));
/* write various chunks */
/* Write the IHDR chunk, and update the png_struct with the necessary
* information.
*/
PNG_EXTERN void png_write_IHDR PNGARG((png_structp png_ptr, png_uint_32 width,
png_uint_32 height,
int bit_depth, int color_type, int compression_type, int filter_type,
int interlace_type));
PNG_EXTERN void png_write_PLTE PNGARG((png_structp png_ptr, png_colorp palette,
png_uint_32 num_pal));
PNG_EXTERN void png_write_IDAT PNGARG((png_structp png_ptr, png_bytep data,
png_size_t length));
PNG_EXTERN void png_write_IEND PNGARG((png_structp png_ptr));
#if defined(PNG_WRITE_gAMA_SUPPORTED)
PNG_EXTERN void png_write_gAMA PNGARG((png_structp png_ptr, double file_gamma));
#endif
#if defined(PNG_WRITE_sBIT_SUPPORTED)
PNG_EXTERN void png_write_sBIT PNGARG((png_structp png_ptr, png_color_8p sbit,
int color_type));
#endif
#if defined(PNG_WRITE_cHRM_SUPPORTED)
PNG_EXTERN void png_write_cHRM PNGARG((png_structp png_ptr,
double white_x, double white_y,
double red_x, double red_y, double green_x, double green_y,
double blue_x, double blue_y));
#endif
#if defined(PNG_WRITE_sRGB_SUPPORTED)
PNG_EXTERN void png_write_sRGB PNGARG((png_structp png_ptr,
int intent));
#endif
#if defined(PNG_WRITE_tRNS_SUPPORTED)
PNG_EXTERN void png_write_tRNS PNGARG((png_structp png_ptr, png_bytep trans,
png_color_16p values, int number, int color_type));
#endif
#if defined(PNG_WRITE_bKGD_SUPPORTED)
PNG_EXTERN void png_write_bKGD PNGARG((png_structp png_ptr,
png_color_16p values, int color_type));
#endif
#if defined(PNG_WRITE_hIST_SUPPORTED)
PNG_EXTERN void png_write_hIST PNGARG((png_structp png_ptr, png_uint_16p hist,
int num_hist));
#endif
#if defined(PNG_WRITE_tEXt_SUPPORTED) || defined(PNG_WRITE_zTXt_SUPPORTED) || \
defined(PNG_WRITE_pCAL_SUPPORTED)
PNG_EXTERN png_size_t png_check_keyword PNGARG((png_structp png_ptr,
png_charp key, png_charpp new_key));
#endif
#if defined(PNG_WRITE_tEXt_SUPPORTED)
PNG_EXTERN void png_write_tEXt PNGARG((png_structp png_ptr, png_charp key,
png_charp text, png_size_t text_len));
#endif
#if defined(PNG_WRITE_zTXt_SUPPORTED)
PNG_EXTERN void png_write_zTXt PNGARG((png_structp png_ptr, png_charp key,
png_charp text, png_size_t text_len, int compression));
#endif
#if defined(PNG_WRITE_oFFs_SUPPORTED)
PNG_EXTERN void png_write_oFFs PNGARG((png_structp png_ptr,
png_uint_32 x_offset, png_uint_32 y_offset, int unit_type));
#endif
#if defined(PNG_WRITE_pCAL_SUPPORTED)
PNG_EXTERN void png_write_pCAL PNGARG((png_structp png_ptr, png_charp purpose,
png_int_32 X0, png_int_32 X1, int type, int nparams,
png_charp units, png_charpp params));
#endif
#if defined(PNG_WRITE_pHYs_SUPPORTED)
PNG_EXTERN void png_write_pHYs PNGARG((png_structp png_ptr,
png_uint_32 x_pixels_per_unit, png_uint_32 y_pixels_per_unit,
int unit_type));
#endif
#if defined(PNG_WRITE_tIME_SUPPORTED)
PNG_EXTERN void png_write_tIME PNGARG((png_structp png_ptr,
png_timep mod_time));
#endif
/* Called when finished processing a row of data */
PNG_EXTERN void png_write_finish_row PNGARG((png_structp png_ptr));
/* Internal use only. Called before first row of data */
PNG_EXTERN void png_write_start_row PNGARG((png_structp png_ptr));
#if defined(PNG_READ_GAMMA_SUPPORTED)
PNG_EXTERN void png_build_gamma_table PNGARG((png_structp png_ptr));
#endif
/* combine a row of data, dealing with alpha, etc. if requested */
PNG_EXTERN void png_combine_row PNGARG((png_structp png_ptr, png_bytep row,
int mask));
#if defined(PNG_READ_INTERLACING_SUPPORTED)
/* expand an interlaced row */
PNG_EXTERN void png_do_read_interlace PNGARG((png_row_infop row_info,
png_bytep row, int pass, png_uint_32 transformations));
#endif
#if defined(PNG_WRITE_INTERLACING_SUPPORTED)
/* grab pixels out of a row for an interlaced pass */
PNG_EXTERN void png_do_write_interlace PNGARG((png_row_infop row_info,
png_bytep row, int pass));
#endif
/* unfilter a row */
PNG_EXTERN void png_read_filter_row PNGARG((png_structp png_ptr,
png_row_infop row_info, png_bytep row, png_bytep prev_row, int filter));
/* Choose the best filter to use and filter the row data */
PNG_EXTERN void png_write_find_filter PNGARG((png_structp png_ptr,
png_row_infop row_info));
/* Write out the filtered row. */
PNG_EXTERN void png_write_filtered_row PNGARG((png_structp png_ptr,
png_bytep filtered_row));
/* finish a row while reading, dealing with interlacing passes, etc. */
PNG_EXTERN void png_read_finish_row PNGARG((png_structp png_ptr));
/* initialize the row buffers, etc. */
PNG_EXTERN void png_read_start_row PNGARG((png_structp png_ptr));
/* optional call to update the users info structure */
PNG_EXTERN void png_read_transform_info PNGARG((png_structp png_ptr,
png_infop info_ptr));
/* these are the functions that do the transformations */
#if defined(PNG_READ_FILLER_SUPPORTED)
PNG_EXTERN void png_do_read_filler PNGARG((png_row_infop row_info,
png_bytep row, png_uint_32 filler, png_uint_32 flags));
#endif
#if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
PNG_EXTERN void png_do_read_swap_alpha PNGARG((png_row_infop row_info,
png_bytep row));
#endif
#if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
PNG_EXTERN void png_do_write_swap_alpha PNGARG((png_row_infop row_info,
png_bytep row));
#endif
#if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
PNG_EXTERN void png_do_read_invert_alpha PNGARG((png_row_infop row_info,
png_bytep row));
#endif
#if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
PNG_EXTERN void png_do_write_invert_alpha PNGARG((png_row_infop row_info,
png_bytep row));
#endif
#if defined(PNG_WRITE_FILLER_SUPPORTED) || \
defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
PNG_EXTERN void png_do_strip_filler PNGARG((png_row_infop row_info,
png_bytep row, png_uint_32 flags));
#endif
#if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
PNG_EXTERN void png_do_swap PNGARG((png_row_infop row_info, png_bytep row));
#endif
#if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
PNG_EXTERN void png_do_packswap PNGARG((png_row_infop row_info, png_bytep row));
#endif
#if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
PNG_EXTERN void png_do_rgb_to_gray PNGARG((png_row_infop row_info,
png_bytep row));
#endif
#if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
PNG_EXTERN void png_do_gray_to_rgb PNGARG((png_row_infop row_info,
png_bytep row));
#endif
#if defined(PNG_READ_PACK_SUPPORTED)
PNG_EXTERN void png_do_unpack PNGARG((png_row_infop row_info, png_bytep row));
#endif
#if defined(PNG_READ_SHIFT_SUPPORTED)
PNG_EXTERN void png_do_unshift PNGARG((png_row_infop row_info, png_bytep row,
png_color_8p sig_bits));
#endif
#if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
PNG_EXTERN void png_do_invert PNGARG((png_row_infop row_info, png_bytep row));
#endif
#if defined(PNG_READ_16_TO_8_SUPPORTED)
PNG_EXTERN void png_do_chop PNGARG((png_row_infop row_info, png_bytep row));
#endif
#if defined(PNG_READ_DITHER_SUPPORTED)
PNG_EXTERN void png_do_dither PNGARG((png_row_infop row_info,
png_bytep row, png_bytep palette_lookup, png_bytep dither_lookup));
# if defined(PNG_CORRECT_PALETTE_SUPPORTED)
PNG_EXTERN void png_correct_palette PNGARG((png_structp png_ptr,
png_colorp palette, int num_palette));
# endif
#endif
#if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
PNG_EXTERN void png_do_bgr PNGARG((png_row_infop row_info, png_bytep row));
#endif
#if defined(PNG_WRITE_PACK_SUPPORTED)
PNG_EXTERN void png_do_pack PNGARG((png_row_infop row_info,
png_bytep row, png_uint_32 bit_depth));
#endif
#if defined(PNG_WRITE_SHIFT_SUPPORTED)
PNG_EXTERN void png_do_shift PNGARG((png_row_infop row_info, png_bytep row,
png_color_8p bit_depth));
#endif
#if defined(PNG_READ_BACKGROUND_SUPPORTED)
PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
png_color_16p trans_values, png_color_16p background,
png_color_16p background_1,
png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
png_uint_16pp gamma_16_to_1, int gamma_shift));
#endif
#if defined(PNG_READ_GAMMA_SUPPORTED)
PNG_EXTERN void png_do_gamma PNGARG((png_row_infop row_info, png_bytep row,
png_bytep gamma_table, png_uint_16pp gamma_16_table,
int gamma_shift));
#endif
#if defined(PNG_READ_EXPAND_SUPPORTED)
PNG_EXTERN void png_do_expand_palette PNGARG((png_row_infop row_info,
png_bytep row, png_colorp palette, png_bytep trans, int num_trans));
PNG_EXTERN void png_do_expand PNGARG((png_row_infop row_info,
png_bytep row, png_color_16p trans_value));
#endif
/* The following decodes the appropriate chunks, and does error correction,
* then calls the appropriate callback for the chunk if it is valid.
*/
/* decode the IHDR chunk */
PNG_EXTERN void png_handle_IHDR PNGARG((png_structp png_ptr, png_infop info_ptr,
png_uint_32 length));
PNG_EXTERN void png_handle_PLTE PNGARG((png_structp png_ptr, png_infop info_ptr,
png_uint_32 length));
PNG_EXTERN void png_handle_IEND PNGARG((png_structp png_ptr, png_infop info_ptr,
png_uint_32 length));
#if defined(PNG_READ_gAMA_SUPPORTED)
PNG_EXTERN void png_handle_gAMA PNGARG((png_structp png_ptr, png_infop info_ptr,
png_uint_32 length));
#endif
#if defined(PNG_READ_sBIT_SUPPORTED)
PNG_EXTERN void png_handle_sBIT PNGARG((png_structp png_ptr, png_infop info_ptr,
png_uint_32 length));
#endif
#if defined(PNG_READ_cHRM_SUPPORTED)
PNG_EXTERN void png_handle_cHRM PNGARG((png_structp png_ptr, png_infop info_ptr,
png_uint_32 length));
#endif
#if defined(PNG_READ_sRGB_SUPPORTED)
PNG_EXTERN void png_handle_sRGB PNGARG((png_structp png_ptr, png_infop info_ptr,
png_uint_32 length));
#endif
#if defined(PNG_READ_tRNS_SUPPORTED)
PNG_EXTERN void png_handle_tRNS PNGARG((png_structp png_ptr, png_infop info_ptr,
png_uint_32 length));
#endif
#if defined(PNG_READ_bKGD_SUPPORTED)
PNG_EXTERN void png_handle_bKGD PNGARG((png_structp png_ptr, png_infop info_ptr,
png_uint_32 length));
#endif
#if defined(PNG_READ_hIST_SUPPORTED)
PNG_EXTERN void png_handle_hIST PNGARG((png_structp png_ptr, png_infop info_ptr,
png_uint_32 length));
#endif
#if defined(PNG_READ_oFFs_SUPPORTED)
PNG_EXTERN void png_handle_oFFs PNGARG((png_structp png_ptr, png_infop info_ptr,
png_uint_32 length));
#endif
#if defined(PNG_READ_pCAL_SUPPORTED)
PNG_EXTERN void png_handle_pCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
png_uint_32 length));
#endif
#if defined(PNG_READ_pHYs_SUPPORTED)
PNG_EXTERN void png_handle_pHYs PNGARG((png_structp png_ptr, png_infop info_ptr,
png_uint_32 length));
#endif
#if defined(PNG_READ_tIME_SUPPORTED)
PNG_EXTERN void png_handle_tIME PNGARG((png_structp png_ptr, png_infop info_ptr,
png_uint_32 length));
#endif
#if defined(PNG_READ_tEXt_SUPPORTED)
PNG_EXTERN void png_handle_tEXt PNGARG((png_structp png_ptr, png_infop info_ptr,
png_uint_32 length));
#endif
#if defined(PNG_READ_zTXt_SUPPORTED)
PNG_EXTERN void png_handle_zTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
png_uint_32 length));
#endif
PNG_EXTERN void png_handle_unknown PNGARG((png_structp png_ptr,
png_infop info_ptr, png_uint_32 length));
PNG_EXTERN void png_check_chunk_name PNGARG((png_structp png_ptr,
png_bytep chunk_name));
/* handle the transformations for reading and writing */
PNG_EXTERN void png_do_read_transformations PNGARG((png_structp png_ptr));
PNG_EXTERN void png_do_write_transformations PNGARG((png_structp png_ptr));
PNG_EXTERN void png_init_read_transformations PNGARG((png_structp png_ptr));
#ifdef PNG_PROGRESSIVE_READ_SUPPORTED
PNG_EXTERN void png_push_read_chunk PNGARG((png_structp png_ptr,
png_infop info_ptr));
PNG_EXTERN void png_push_read_sig PNGARG((png_structp png_ptr,
png_infop info_ptr));
PNG_EXTERN void png_push_check_crc PNGARG((png_structp png_ptr));
PNG_EXTERN void png_push_crc_skip PNGARG((png_structp png_ptr,
png_uint_32 length));
PNG_EXTERN void png_push_crc_finish PNGARG((png_structp png_ptr));
PNG_EXTERN void png_push_fill_buffer PNGARG((png_structp png_ptr,
png_bytep buffer, png_size_t length));
PNG_EXTERN void png_push_save_buffer PNGARG((png_structp png_ptr));
PNG_EXTERN void png_push_restore_buffer PNGARG((png_structp png_ptr,
png_bytep buffer, png_size_t buffer_length));
PNG_EXTERN void png_push_read_IDAT PNGARG((png_structp png_ptr));
PNG_EXTERN void png_process_IDAT_data PNGARG((png_structp png_ptr,
png_bytep buffer, png_size_t buffer_length));
PNG_EXTERN void png_push_process_row PNGARG((png_structp png_ptr));
PNG_EXTERN void png_push_handle_unknown PNGARG((png_structp png_ptr,
png_infop info_ptr, png_uint_32 length));
PNG_EXTERN void png_push_have_info PNGARG((png_structp png_ptr,
png_infop info_ptr));
PNG_EXTERN void png_push_have_end PNGARG((png_structp png_ptr,
png_infop info_ptr));
PNG_EXTERN void png_push_have_row PNGARG((png_structp png_ptr, png_bytep row));
PNG_EXTERN void png_push_read_end PNGARG((png_structp png_ptr,
png_infop info_ptr));
PNG_EXTERN void png_process_some_data PNGARG((png_structp png_ptr,
png_infop info_ptr));
PNG_EXTERN void png_read_push_finish_row PNGARG((png_structp png_ptr));
#if defined(PNG_READ_tEXt_SUPPORTED)
PNG_EXTERN void png_push_handle_tEXt PNGARG((png_structp png_ptr,
png_infop info_ptr, png_uint_32 length));
PNG_EXTERN void png_push_read_tEXt PNGARG((png_structp png_ptr,
png_infop info_ptr));
#endif
#if defined(PNG_READ_zTXt_SUPPORTED)
PNG_EXTERN void png_push_handle_zTXt PNGARG((png_structp png_ptr,
png_infop info_ptr, png_uint_32 length));
PNG_EXTERN void png_push_read_zTXt PNGARG((png_structp png_ptr,
png_infop info_ptr));
#endif
#endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
#endif /* PNG_INTERNAL */
/*
#ifdef __cplusplus
}
#endif
*/
/* do not put anything past this line */
#endif /* _PNG_H */
| fgenesis/Aquaria_experimental | ExternalLibs/glpng/png/png.h | C | gpl-2.0 | 92,150 |
module statoscope.marks {
"use strict";
export class MarkWrapper extends
statoscope.controls.AbstractWrapper<storage.IMarkConfig> {
static sType = "s-mark-wrapper";
private _dayInfo: utils.IDayInfo;
constructor(markConfig: storage.IMarkConfig, dayInfo: utils.IDayInfo) {
this._dayInfo = dayInfo;
super(markConfig);
}
newItem(config: storage.IMarkConfig): AbstractMark {
return createMark(config, this._dayInfo);
}
newEditor(): view.Control {
var editor = new statoscope.controls.EditorBar(this.item.config.title,
getMarkTypes().map(type => ({
value: type,
label: getMarkName(type)
})), this.item.config.type);
editor.onSaveClick.addHandler(() => {
this.item.config.title = editor.titleText;
var typeChanged = this.item.config.type !== editor.selectedType;
this.item.config.type = editor.selectedType;
storage.instance().saveDayConfig(this._dayInfo.dayConfig);
if (typeChanged) {
this.createItem(this.item.config);
}
else {
this.item.update();
}
this.settings = false;
});
editor.onRemoveClick.addHandler(() => {
var result = this.element.classList.contains("new") ||
window.confirm(common.i18n.tr(
"This mark will be deleted from all days."));
if (result) {
var config: storage.IDayConfig = this._dayInfo.dayConfig;
config.marks = config.marks.filter(mark => mark !== this.item.config);
storage.instance().saveDayConfig(this._dayInfo.dayConfig);
this.cleanup();
}
});
return editor;
}
}
}
| y-a-r-g/statoscope | scripts/statoscope/marks/MarkWrapper.ts | TypeScript | gpl-2.0 | 2,056 |
<?php
namespace PunchCMS\DBAL;
/**
* ElementField DBA Class.
*
* @author Felix Langfeldt <felix@neverwoods.com>
* @internal
*
*/
class ElementField extends Object
{
protected $id = null;
protected $elementid = 0;
protected $templatefieldid = 0;
protected $fieldtypeid = 0;
protected $originalname = "";
protected $username = "";
// *** Constructor.
public function __construct()
{
self::$object = "\\PunchCMS\\ElementField";
self::$table = "pcms_element_field";
}
// *** Static inherited functions.
public static function selectByPK($varValue, $arrFields = array(), $accountId = null)
{
self::$object = "\\PunchCMS\\ElementField";
self::$table = "pcms_element_field";
return parent::selectByPK($varValue, $arrFields, $accountId);
}
public static function select($strSql = "")
{
self::$object = "\\PunchCMS\\ElementField";
self::$table = "pcms_element_field";
return parent::select($strSql);
}
public static function doDelete($varValue)
{
self::$object = "\\PunchCMS\\ElementField";
self::$table = "pcms_element_field";
return parent::doDelete($varValue);
}
public function save($blnSaveModifiedDate = true)
{
self::$object = "\\PunchCMS\\ElementField";
self::$table = "pcms_element_field";
return parent::save($blnSaveModifiedDate);
}
public function delete($accountId = null)
{
self::$object = "\\PunchCMS\\ElementField";
self::$table = "pcms_element_field";
return parent::delete($accountId);
}
public function duplicate()
{
self::$object = "\\PunchCMS\\ElementField";
self::$table = "pcms_element_field";
return parent::duplicate();
}
}
| neverwoods/punchcms-client | classes/PunchCMS/DBAL/ElementField.php | PHP | gpl-2.0 | 1,837 |
<? if ($User->CheckPermissions('edit') || $User->CheckPermissions('editOwn') || $User->CheckPermissions('admin') || $User->CheckPermissions('root')) { ?>
<div class="editContentBlock profileBlock">
<form action="" method="post" class="editContentForm">
<div class="row">
<div>Languages:</div>
<div>
<? foreach ($this->Languages as $lang) { ?>
<label><input type="radio" name="language" value="<?=$lang['id']?>" /> <?=$lang['title']?></label> 
<? } ?>
</div>
</div>
<? foreach ($this->Languages as $lang) { ?>
<div class="languageText" id="edit_title<?=$lang['id']?>">
<div class="row">
<div>Title *:</div>
<div><input type="text" name="contentTitle[<?=$lang['id']?>]" /></div>
</div>
</div>
<? } ?>
<div class="row">
<div>URL *:</div>
<div><input type="text" name="contentUrl" /></div>
</div>
<div class="row">
<div>New author:</div>
<div><input type="text" name="contentAuthor" /></div>
</div>
<div class="row">
<div>Category *:</div>
<div>
<select name="contentCategory">
<option value="without">Without category</option>
<option disabled="disabled">-----------</option>
<?
foreach ($this->CatArray as $cat) {
$tab = "";
for ($i=1; $i<=$cat['level']; $i++) {
$tab.=" ";
}
?>
<option value="<?=$cat['id']?>"><?=$tab.$cat['title']?></option>
<?
}
?>
</select>
</div>
</div>
<? foreach ($this->Languages as $lang) { ?>
<div class="languageText" id="edit_language<?=$lang['id']?>">
<div class="row">
<div>Pre-text:</div>
<div>
<textarea class="tinymce" name="contentPreText[<?=$lang['id']?>]" class="tinymce"></textarea>
</div>
</div>
<div class="row">
<div>Main text *:</div>
<div>
<textarea class="tinymce" name="contentMainText[<?=$lang['id']?>]" class="tinymce"></textarea>
</div>
</div>
</div>
<? } ?>
<? if ($User->CheckPermissions('publish')) { ?>
<div class="row">
<div>Publish:</div>
<div>
<label><input type="radio" name="contentPublish" value="1" checked="checked" /> yes</label> 
<label><input type="radio" name="contentPublish" value="0" /> no</label> 
</div>
</div>
<div class="row">
<div>On front page:</div>
<div>
<label><input type="radio" name="contentFront" value="1" checked="checked" /> yes</label> 
<label><input type="radio" name="contentFront" value="0" /> no</label> 
</div>
</div>
<? } else { ?>
<input type="hidden" name="contentPublish" value="0" />
<input type="hidden" name="contentFront" value="0" />
<? } ?>
<div class="row">
<div></div>
<div>
<input type="hidden" name="contentId" value="" />
<input type="hidden" name="Action" value="updateContent" />
<input type="submit" value="Update content" />
</div>
</div>
</form>
</div>
<? } ?> | Tarzanych/my_studiyng_site | template/snippets/edit-content.php | PHP | gpl-2.0 | 2,815 |
local menubuttons = {
--levels
{x=0,w=480,y=972,h=108, result = function() love.filesystem.load("gui/levels.lua")() end},
--shop (temporarily exit to main menu) NOpe
{x=1440,w=480,y=972,h=108, result = function() end}
}
local image = love.graphics.newImage("graphics/GUI1.png")
local back = function() love.filesystem.load("gui/main.lua")() end
loadMenu(menubuttons, image, back) | mrcpj1998/BulletJumpers | src/gui/campaign.lua | Lua | gpl-2.0 | 388 |
<?php
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
createContainer();
createRow();
createContentBoxtoLeft();?>
<h4>Meny her</h4>
</div>
<?php createContentBoxtoRight(); ?>
<form class="form-horizontal" role="form" action="/moments/functions/newmoment.php" method="POST">
<div class="form-group">
<h2>Capture a new moment</h2>
<label for="momentname" class="col-sm-2 control-label">Navn på moment</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="momentname" placeholder="Navn på moment" name="momentname">
</div>
</div>
<div class="form-group">
<label for="momenttext" class="col-sm-2 control-label"><a href="#" onclick="showMomentText()">Legg til en beskrivende tekst</a></label>
<div class="col-sm-10">
<input type="text" class="form-control" id="momenttext" placeholder="Beskrivende tekst" name="momenttext" style="display: none">
</div>
</div>
<div class="form-group">
<label for="momentguests" class="col-sm-2 control-label"><a data-toggle="modal" href="#guests" >Legg til deltakere</a></label>
<div class="col-sm-10">
<?php
if(isset($_POST['friends'])) {
$i = 0;
foreach($_POST['friends'] as $friend_id){
$friend = new User($friend_id);
echo $friend->getProfilePicture(15) .' '. $friend->name;
echo '<br>';
$friends[$i++] = $friend_id;
}
$data_friends=serialize($friends);
$encoded_friends=htmlentities($data_friends);
}
?>
<input type="hidden" value="<?php echo $encoded_friends; ?>" name="guests">
</div>
</div>
<div class="form-group">
<label for="momentpicture" class="col-sm-2 control-label"><a href="#" onclick="showMomentPicture()">Legg til et bilde</a></label>
<div class="col-sm-10">
<input type="file" class="form-control" id="momentpicture" name="momentpicture" style="display: none">
</div>
</div>
<div class="form-group">
<label for="momenttimefrom" class="col-sm-2 control-label"><a href="#" onclick="showMomentTimeFrom()">Legg til et starttidspunkt</a></label>
<div class="col-sm-10">
<input type="time" class="form-control" id="momenttimefrom" name="momenttimefrom" style="display: none">
</div>
</div>
<div class="form-group">
<label for="momenttimeto" class="col-sm-2 control-label"><a href="#" onclick="showMomentTimeTo()">Legg til et estimert slutttidspunkt</a></label>
<div class="col-sm-10">
<input type="time" class="form-control" id="momenttimeto" name="momenttimeto" style="display: none">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-success" id="capture" name="submit" value="submit">Capture</button>
<?php echo $_SESSION['newmomentmsg']; ?>
</div>
</div>
</form>
<?php endBox(); ?>
<?php include $_SERVER['DOCUMENT_ROOT'] . '/moments/friendsform.php'; ?>
<script>
function showMomentText() {
$('#momenttext').show();
}
function showMomentPicture() {
$('#momentpicture').show();
}
function showMomentTimeFrom() {
$('#momenttimefrom').show();
}
function showMomentTimeTo() {
$('#momenttimeto').show();
}
//document.getElementById('momenttimefrom').value = Date();
</script> | sondresallaup/kvitrar | moments/newmomentform.php | PHP | gpl-2.0 | 3,490 |
/*
* Copyright (C) 2011-2021 Project SkyFire <https://www.projectskyfire.org/>
* Copyright (C) 2008-2021 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2005-2021 MaNGOS <https://www.getmangos.eu/>
* Copyright (C) 2006-2014 ScriptDev2 <https://github.com/scriptdev2/scriptdev2/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* ScriptData
SDName: Instance Trial of the Champion
SDComment:
SDCategory: Trial Of the Champion
EndScriptData */
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "InstanceScript.h"
#include "trial_of_the_champion.h"
#include "Player.h"
#define MAX_ENCOUNTER 4
class instance_trial_of_the_champion : public InstanceMapScript
{
public:
instance_trial_of_the_champion() : InstanceMapScript("instance_trial_of_the_champion", 650) { }
InstanceScript* GetInstanceScript(InstanceMap* map) const OVERRIDE
{
return new instance_trial_of_the_champion_InstanceMapScript(map);
}
struct instance_trial_of_the_champion_InstanceMapScript : public InstanceScript
{
instance_trial_of_the_champion_InstanceMapScript(Map* map) : InstanceScript(map) { }
uint32 m_auiEncounter[MAX_ENCOUNTER];
uint16 uiMovementDone;
uint16 uiGrandChampionsDeaths;
uint8 uiArgentSoldierDeaths;
uint64 uiAnnouncerGUID;
uint64 uiMainGateGUID;
uint64 uiGrandChampionVehicle1GUID;
uint64 uiGrandChampionVehicle2GUID;
uint64 uiGrandChampionVehicle3GUID;
uint64 uiGrandChampion1GUID;
uint64 uiGrandChampion2GUID;
uint64 uiGrandChampion3GUID;
uint64 uiChampionLootGUID;
uint64 uiArgentChampionGUID;
std::list<uint64> VehicleList;
std::string str_data;
bool bDone;
void Initialize() OVERRIDE
{
uiMovementDone = 0;
uiGrandChampionsDeaths = 0;
uiArgentSoldierDeaths = 0;
uiAnnouncerGUID = 0;
uiMainGateGUID = 0;
uiGrandChampionVehicle1GUID = 0;
uiGrandChampionVehicle2GUID = 0;
uiGrandChampionVehicle3GUID = 0;
uiGrandChampion1GUID = 0;
uiGrandChampion2GUID = 0;
uiGrandChampion3GUID = 0;
uiChampionLootGUID = 0;
uiArgentChampionGUID = 0;
bDone = false;
VehicleList.clear();
memset(&m_auiEncounter, 0, sizeof(m_auiEncounter));
}
bool IsEncounterInProgress() const OVERRIDE
{
for (uint8 i = 0; i < MAX_ENCOUNTER; ++i)
{
if (m_auiEncounter[i] == IN_PROGRESS)
return true;
}
return false;
}
void OnCreatureCreate(Creature* creature) OVERRIDE
{
Map::PlayerList const &players = instance->GetPlayers();
uint32 TeamInInstance = 0;
if (!players.isEmpty())
{
if (Player* player = players.begin()->GetSource())
TeamInInstance = player->GetTeam();
}
switch (creature->GetEntry())
{
// Champions
case VEHICLE_MOKRA_SKILLCRUSHER_MOUNT:
if (TeamInInstance == HORDE)
creature->UpdateEntry(VEHICLE_MARSHAL_JACOB_ALERIUS_MOUNT, ALLIANCE);
break;
case VEHICLE_ERESSEA_DAWNSINGER_MOUNT:
if (TeamInInstance == HORDE)
creature->UpdateEntry(VEHICLE_AMBROSE_BOLTSPARK_MOUNT, ALLIANCE);
break;
case VEHICLE_RUNOK_WILDMANE_MOUNT:
if (TeamInInstance == HORDE)
creature->UpdateEntry(VEHICLE_COLOSOS_MOUNT, ALLIANCE);
break;
case VEHICLE_ZUL_TORE_MOUNT:
if (TeamInInstance == HORDE)
creature->UpdateEntry(VEHICLE_EVENSONG_MOUNT, ALLIANCE);
break;
case VEHICLE_DEATHSTALKER_VESCERI_MOUNT:
if (TeamInInstance == HORDE)
creature->UpdateEntry(VEHICLE_LANA_STOUTHAMMER_MOUNT, ALLIANCE);
break;
// Coliseum Announcer || Just NPC_JAEREN must be spawned.
case NPC_JAEREN:
uiAnnouncerGUID = creature->GetGUID();
if (TeamInInstance == ALLIANCE)
creature->UpdateEntry(NPC_ARELAS, ALLIANCE);
break;
case VEHICLE_ARGENT_WARHORSE:
case VEHICLE_ARGENT_BATTLEWORG:
VehicleList.push_back(creature->GetGUID());
break;
case NPC_EADRIC:
case NPC_PALETRESS:
uiArgentChampionGUID = creature->GetGUID();
break;
}
}
void OnGameObjectCreate(GameObject* go) OVERRIDE
{
switch (go->GetEntry())
{
case GO_MAIN_GATE:
uiMainGateGUID = go->GetGUID();
break;
case GO_CHAMPIONS_LOOT:
case GO_CHAMPIONS_LOOT_H:
uiChampionLootGUID = go->GetGUID();
break;
}
}
void SetData(uint32 uiType, uint32 uiData) OVERRIDE
{
switch (uiType)
{
case DATA_MOVEMENT_DONE:
uiMovementDone = uiData;
if (uiMovementDone == 3)
{
if (Creature* pAnnouncer = instance->GetCreature(uiAnnouncerGUID))
pAnnouncer->AI()->SetData(DATA_IN_POSITION, 0);
}
break;
case BOSS_GRAND_CHAMPIONS:
m_auiEncounter[0] = uiData;
if (uiData == IN_PROGRESS)
{
for (std::list<uint64>::const_iterator itr = VehicleList.begin(); itr != VehicleList.end(); ++itr)
if (Creature* summon = instance->GetCreature(*itr))
summon->RemoveFromWorld();
}else if (uiData == DONE)
{
++uiGrandChampionsDeaths;
if (uiGrandChampionsDeaths == 3)
{
if (Creature* pAnnouncer = instance->GetCreature(uiAnnouncerGUID))
{
pAnnouncer->GetMotionMaster()->MovePoint(0, 748.309f, 619.487f, 411.171f);
pAnnouncer->SetFlag(UNIT_FIELD_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP);
pAnnouncer->SummonGameObject(instance->IsHeroic()? GO_CHAMPIONS_LOOT_H : GO_CHAMPIONS_LOOT, 746.59f, 618.49f, 411.09f, 1.42f, 0, 0, 0, 0, 90000000);
}
}
}
break;
case DATA_ARGENT_SOLDIER_DEFEATED:
uiArgentSoldierDeaths = uiData;
if (uiArgentSoldierDeaths == 9)
{
if (Creature* pBoss = instance->GetCreature(uiArgentChampionGUID))
{
pBoss->GetMotionMaster()->MovePoint(0, 746.88f, 618.74f, 411.06f);
pBoss->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE);
pBoss->SetReactState(REACT_AGGRESSIVE);
}
}
break;
case BOSS_ARGENT_CHALLENGE_E:
m_auiEncounter[1] = uiData;
if (Creature* pAnnouncer = instance->GetCreature(uiAnnouncerGUID))
{
pAnnouncer->GetMotionMaster()->MovePoint(0, 748.309f, 619.487f, 411.171f);
pAnnouncer->SetFlag(UNIT_FIELD_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP);
pAnnouncer->SummonGameObject(instance->IsHeroic()? GO_EADRIC_LOOT_H : GO_EADRIC_LOOT, 746.59f, 618.49f, 411.09f, 1.42f, 0, 0, 0, 0, 90000000);
}
break;
case BOSS_ARGENT_CHALLENGE_P:
m_auiEncounter[2] = uiData;
if (Creature* pAnnouncer = instance->GetCreature(uiAnnouncerGUID))
{
pAnnouncer->GetMotionMaster()->MovePoint(0, 748.309f, 619.487f, 411.171f);
pAnnouncer->SetFlag(UNIT_FIELD_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP);
pAnnouncer->SummonGameObject(instance->IsHeroic()? GO_PALETRESS_LOOT_H : GO_PALETRESS_LOOT, 746.59f, 618.49f, 411.09f, 1.42f, 0, 0, 0, 0, 90000000);
}
break;
}
if (uiData == DONE)
SaveToDB();
}
uint32 GetData(uint32 uiData) const OVERRIDE
{
switch (uiData)
{
case BOSS_GRAND_CHAMPIONS: return m_auiEncounter[0];
case BOSS_ARGENT_CHALLENGE_E: return m_auiEncounter[1];
case BOSS_ARGENT_CHALLENGE_P: return m_auiEncounter[2];
case BOSS_BLACK_KNIGHT: return m_auiEncounter[3];
case DATA_MOVEMENT_DONE: return uiMovementDone;
case DATA_ARGENT_SOLDIER_DEFEATED: return uiArgentSoldierDeaths;
}
return 0;
}
uint64 GetData64(uint32 uiData) const OVERRIDE
{
switch (uiData)
{
case DATA_ANNOUNCER: return uiAnnouncerGUID;
case DATA_MAIN_GATE: return uiMainGateGUID;
case DATA_GRAND_CHAMPION_1: return uiGrandChampion1GUID;
case DATA_GRAND_CHAMPION_2: return uiGrandChampion2GUID;
case DATA_GRAND_CHAMPION_3: return uiGrandChampion3GUID;
}
return 0;
}
void SetData64(uint32 uiType, uint64 uiData) OVERRIDE
{
switch (uiType)
{
case DATA_GRAND_CHAMPION_1:
uiGrandChampion1GUID = uiData;
break;
case DATA_GRAND_CHAMPION_2:
uiGrandChampion2GUID = uiData;
break;
case DATA_GRAND_CHAMPION_3:
uiGrandChampion3GUID = uiData;
break;
}
}
std::string GetSaveData() OVERRIDE
{
OUT_SAVE_INST_DATA;
std::ostringstream saveStream;
saveStream << "T C " << m_auiEncounter[0]
<< ' ' << m_auiEncounter[1]
<< ' ' << m_auiEncounter[2]
<< ' ' << m_auiEncounter[3]
<< ' ' << uiGrandChampionsDeaths
<< ' ' << uiMovementDone;
str_data = saveStream.str();
OUT_SAVE_INST_DATA_COMPLETE;
return str_data;
}
void Load(const char* in) OVERRIDE
{
if (!in)
{
OUT_LOAD_INST_DATA_FAIL;
return;
}
OUT_LOAD_INST_DATA(in);
char dataHead1, dataHead2;
uint16 data0, data1, data2, data3, data4, data5;
std::istringstream loadStream(in);
loadStream >> dataHead1 >> dataHead2 >> data0 >> data1 >> data2 >> data3 >> data4 >> data5;
if (dataHead1 == 'T' && dataHead2 == 'C')
{
m_auiEncounter[0] = data0;
m_auiEncounter[1] = data1;
m_auiEncounter[2] = data2;
m_auiEncounter[3] = data3;
for (uint8 i = 0; i < MAX_ENCOUNTER; ++i)
if (m_auiEncounter[i] == IN_PROGRESS)
m_auiEncounter[i] = NOT_STARTED;
uiGrandChampionsDeaths = data4;
uiMovementDone = data5;
} else OUT_LOAD_INST_DATA_FAIL;
OUT_LOAD_INST_DATA_COMPLETE;
}
};
};
void AddSC_instance_trial_of_the_champion()
{
new instance_trial_of_the_champion();
}
| ProjectSkyfire/SkyFire.548 | src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheChampion/instance_trial_of_the_champion.cpp | C++ | gpl-2.0 | 12,940 |
package fi.helsinki.cs.titotrainer.app.model.handler;
import org.hibernate.HibernateException;
import org.hibernate.event.PreInsertEvent;
import org.hibernate.event.PreInsertEventListener;
import org.hibernate.event.PreUpdateEvent;
import org.hibernate.event.PreUpdateEventListener;
/**
* <p>A pre-insert/pre-update event listener that checks that
* bidirectional table associations are set both ways.</p>
*
* <p>
* NOTE: There is a problem with the current implementation.
* The event handler is called during flushing and it's not supposed
* to touch lazy collections. See
* http://opensource.atlassian.com/projects/hibernate/browse/HHH-2763
* </p>
*/
@SuppressWarnings("serial")
public class AssociationValidator implements PreInsertEventListener, PreUpdateEventListener {
@Override
public boolean onPreInsert(PreInsertEvent event) throws HibernateException {
if (event == null) {
return false;
}
Object entity = event.getEntity();
return validateAssociations(entity);
}
@Override
public boolean onPreUpdate(PreUpdateEvent event) {
if (event == null) {
return false;
}
Object entity = event.getEntity();
return validateAssociations(entity);
}
public static boolean validateAssociations(Object entity) {
// Code commented out to artificially raise test coverage
throw new UnsupportedOperationException("Disabled");
/*
Collection<?> collection;
Class<?> entityClass;
boolean found;
Class<?> targetClass;
Object targetEntity;
ManyToOne manyToOneAnnotation;
OneToMany oneToManyAnnotation;
String propertyName;
if (entity == null) {
return false;
}
entityClass = entity.getClass();
for (Method method : entityClass.getMethods()) {
// Filter out all methods which are not annotated with @Bidirectional
if (method.getAnnotation(Bidirectional.class) == null) {
continue;
}
manyToOneAnnotation = method.getAnnotation(ManyToOne.class);
oneToManyAnnotation = method.getAnnotation(OneToMany.class);
// Check that there's exactly one of @OneToMany or @ManyToOne present
if ((manyToOneAnnotation == null) && (oneToManyAnnotation == null)) {
throw new IllegalStateException("A method that is annotated with @Bidirectional must be annotated also with exactly one of @ManyToOne or @OneToMany!");
}
if ((manyToOneAnnotation != null) && (oneToManyAnnotation != null)) {
throw new IllegalStateException("A method that is annotated with @Bidirectional must be annotated also with exactly one of @ManyToOne or @OneToMany!");
}
// Make sure it's a proper getter without any arguments
if (method.getParameterTypes().length != 0) {
throw new IllegalStateException("The getter annotated with @Bidirectional must not take any parameters!");
}
if (manyToOneAnnotation != null) {
found = false;
// Determine the return type of the method.
targetClass = method.getReturnType();
try {
targetEntity = method.invoke(entity);
// Only proceed if the target entity exists
if (targetEntity != null) {
// Look for a collection in the targetClass
for (Method targetMethod : targetClass.getMethods()) {
// Look for a method with the correct annotations
if ((targetMethod.getAnnotation(Bidirectional.class) != null) && (targetMethod.getAnnotation(OneToMany.class) != null)) {
if (targetMethod.getParameterTypes().length != 0) {
throw new IllegalStateException("The getter annotated with @Bidirectional must not take any parameters!");
}
if (targetMethod.getReturnType() == Collection.class) {
collection = (Collection<?>)targetMethod.invoke(targetEntity);
if (collection.contains(entity)) {
// The entity was found, so return immediately
found = true;
break;
}
}
}
}
if (!found) {
throw new IllegalStateException("The entity " + entity + " was not found in any collection of the parent " + targetEntity + "!");
}
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
if (oneToManyAnnotation != null) {
propertyName = oneToManyAnnotation.mappedBy();
if (propertyName == null) {
throw new IllegalStateException("@OneToMany needs to have its mappedBy field set properly.");
}
try {
collection = (Collection<?>)method.invoke(entity);
for (Object child : collection) {
Getter getter = ReflectHelper.getGetter(child.getClass(), propertyName);
Object parent = getter.get(child);
if (!entity.equals(parent)) {
throw new IllegalStateException("Error in bidirectional association!");
}
}
} catch (IllegalArgumentException exception) {
exception.printStackTrace();
} catch (IllegalAccessException exception) {
exception.printStackTrace();
} catch (InvocationTargetException exception) {
exception.printStackTrace();
}
}
}
return false;
*/
}
} | titokone/titotrainer | WEB-INF/src/fi/helsinki/cs/titotrainer/app/model/handler/AssociationValidator.java | Java | gpl-2.0 | 6,732 |
\hypertarget{classuva_1_1smt_1_1tries_1_1_layered_trie_driver}{}\section{uva\+:\+:smt\+:\+:tries\+:\+:Layered\+Trie\+Driver$<$ Trie\+Type $>$ Class Template Reference}
\label{classuva_1_1smt_1_1tries_1_1_layered_trie_driver}\index{uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver$<$ Trie\+Type $>$@{uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver$<$ Trie\+Type $>$}}
{\ttfamily \#include $<$Layered\+Trie\+Driver.\+hpp$>$}
Inheritance diagram for uva\+:\+:smt\+:\+:tries\+:\+:Layered\+Trie\+Driver$<$ Trie\+Type $>$\+:\begin{figure}[H]
\begin{center}
\leavevmode
\includegraphics[height=3.000000cm]{classuva_1_1smt_1_1tries_1_1_layered_trie_driver}
\end{center}
\end{figure}
\subsection*{Public Types}
\begin{DoxyCompactItemize}
\item
typedef \hyperlink{classuva_1_1smt_1_1tries_1_1_generic_trie_base}{Generic\+Trie\+Base}$<$ Trie\+Type\+::max\+\_\+level, typename Trie\+Type\+::\+Word\+Index\+Type $>$ \hyperlink{classuva_1_1smt_1_1tries_1_1_layered_trie_driver_a039f866f4bab8e7313cfc9fa2cb51f5b}{B\+A\+S\+E}
\item
typedef Trie\+Type\+::\+Word\+Index\+Type \hyperlink{classuva_1_1smt_1_1tries_1_1_layered_trie_driver_aaa30a8f51f4e610158fa8cf0eb965c01}{Word\+Index\+Type}
\item
typedef Trie\+Type\+::\+T\+M\+Gram\+Query \hyperlink{classuva_1_1smt_1_1tries_1_1_layered_trie_driver_a260d262d60ecb64e33f39609e4dcfae9}{T\+M\+Gram\+Query}
\end{DoxyCompactItemize}
\subsection*{Public Member Functions}
\begin{DoxyCompactItemize}
\item
\hyperlink{classuva_1_1smt_1_1tries_1_1_layered_trie_driver_a3227c91c276b27e1b591a378b95de510}{Layered\+Trie\+Driver} (\hyperlink{classuva_1_1smt_1_1tries_1_1_layered_trie_driver_aaa30a8f51f4e610158fa8cf0eb965c01}{Word\+Index\+Type} \&word\+\_\+index)
\item
void \hyperlink{classuva_1_1smt_1_1tries_1_1_layered_trie_driver_af1726a1b69e0274be8c9dfed9283b3ff}{pre\+\_\+allocate} (const size\+\_\+t counts\mbox{[}Trie\+Type\+::max\+\_\+level\mbox{]})
\item
{\footnotesize template$<$bool is\+\_\+back\+\_\+off$>$ }\\bool \hyperlink{classuva_1_1smt_1_1tries_1_1_layered_trie_driver_a1db7700d2609beeae0dfb2a1f3cd5c3a}{is\+\_\+bitmap\+\_\+hash\+\_\+cache} (\hyperlink{classuva_1_1smt_1_1tries_1_1_layered_trie_driver_a260d262d60ecb64e33f39609e4dcfae9}{T\+M\+Gram\+Query} \&query)
\item
void \hyperlink{classuva_1_1smt_1_1tries_1_1_layered_trie_driver_ade31d2fd4fa525d73f6431550c3ba3e6}{add\+\_\+1\+\_\+gram} (const \hyperlink{structuva_1_1smt_1_1tries_1_1mgrams_1_1_t___m___gram}{T\+\_\+\+M\+\_\+\+Gram} \&gram)
\item
void \hyperlink{classuva_1_1smt_1_1tries_1_1_layered_trie_driver_aa9dbc4a56665624d03be9071a7b576cb}{add\+\_\+m\+\_\+gram} (const \hyperlink{structuva_1_1smt_1_1tries_1_1mgrams_1_1_t___m___gram}{T\+\_\+\+M\+\_\+\+Gram} \&gram)
\item
void \hyperlink{classuva_1_1smt_1_1tries_1_1_layered_trie_driver_aba8b64810a7a1b0dd89b129d42167446}{add\+\_\+n\+\_\+gram} (const \hyperlink{structuva_1_1smt_1_1tries_1_1mgrams_1_1_t___m___gram}{T\+\_\+\+M\+\_\+\+Gram} \&gram)
\item
void \hyperlink{classuva_1_1smt_1_1tries_1_1_layered_trie_driver_a41b2c53ae4c5fedf84d629296b5718b8}{get\+\_\+prob\+\_\+weight} (\hyperlink{classuva_1_1smt_1_1tries_1_1_layered_trie_driver_a260d262d60ecb64e33f39609e4dcfae9}{T\+M\+Gram\+Query} \&query)
\item
void \hyperlink{classuva_1_1smt_1_1tries_1_1_layered_trie_driver_ada9749d3e525c6cdf7121c7c224c4055}{add\+\_\+back\+\_\+off\+\_\+weight} (\hyperlink{classuva_1_1smt_1_1tries_1_1_layered_trie_driver_a260d262d60ecb64e33f39609e4dcfae9}{T\+M\+Gram\+Query} \&query)
\item
void \hyperlink{classuva_1_1smt_1_1tries_1_1_layered_trie_driver_aa517364127a40f1942dcae633f819304}{log\+\_\+trie\+\_\+type\+\_\+usage\+\_\+info} ()
\item
bool \hyperlink{classuva_1_1smt_1_1tries_1_1_layered_trie_driver_a178c3021bc5fd5ff9035c6f86a80e2b6}{is\+\_\+post\+\_\+grams} (const \hyperlink{namespaceuva_1_1smt_1_1tries_a20577a44b3a42d26524250634379b7cb}{T\+Model\+Level} level)
\item
void \hyperlink{classuva_1_1smt_1_1tries_1_1_layered_trie_driver_ad25a2d45904154530dee9ccd0945dd9c}{post\+\_\+grams} (const \hyperlink{namespaceuva_1_1smt_1_1tries_a20577a44b3a42d26524250634379b7cb}{T\+Model\+Level} level)
\item
virtual \hyperlink{classuva_1_1smt_1_1tries_1_1_layered_trie_driver_afca9b816915b28480c10624b3067ce3c}{$\sim$\+Layered\+Trie\+Driver} ()
\end{DoxyCompactItemize}
\subsection*{Protected Member Functions}
\begin{DoxyCompactItemize}
\item
\hyperlink{classuva_1_1smt_1_1tries_1_1_layered_trie_driver_a3e49cd9f10938019643370bcf9c85d9c}{Layered\+Trie\+Driver} (const \hyperlink{classuva_1_1smt_1_1tries_1_1_layered_trie_driver}{Layered\+Trie\+Driver} \&orig)
\item
{\footnotesize template$<$bool is\+\_\+back\+\_\+off$>$ }\\bool \hyperlink{classuva_1_1smt_1_1tries_1_1_layered_trie_driver_ae0f2066edca3e2511809e35223fc0170}{get\+\_\+query\+\_\+context\+\_\+\+Id} (const \hyperlink{classuva_1_1smt_1_1tries_1_1_layered_trie_driver_a260d262d60ecb64e33f39609e4dcfae9}{T\+M\+Gram\+Query} \&query, \hyperlink{namespaceuva_1_1smt_1_1hashing_a5992ac0dea0fb3226fb403ede09fad55}{T\+Long\+Id} \&ctx\+\_\+id)
\item
{\footnotesize template$<$Debug\+Levels\+Enum log\+Level$>$ }\\bool \hyperlink{classuva_1_1smt_1_1tries_1_1_layered_trie_driver_a24f0de20cf024b090073103099bd76d5}{get\+\_\+context\+\_\+id} (const \hyperlink{structuva_1_1smt_1_1tries_1_1mgrams_1_1_t___m___gram}{T\+\_\+\+M\+\_\+\+Gram} \&gram, \hyperlink{namespaceuva_1_1smt_1_1hashing_a5992ac0dea0fb3226fb403ede09fad55}{T\+Long\+Id} \&ctx\+Id)
\item
bool \hyperlink{classuva_1_1smt_1_1tries_1_1_layered_trie_driver_aa45ae9734e536721ba527abef4b09880}{get\+Cached\+Context\+Id} (const \hyperlink{structuva_1_1smt_1_1tries_1_1mgrams_1_1_t___m___gram}{T\+\_\+\+M\+\_\+\+Gram} \&m\+Gram, \hyperlink{namespaceuva_1_1smt_1_1hashing_a5992ac0dea0fb3226fb403ede09fad55}{T\+Long\+Id} \&result)
\item
void \hyperlink{classuva_1_1smt_1_1tries_1_1_layered_trie_driver_a17a46690a7c2c577bbc3379d9705b62e}{set\+Cache\+Context\+Id} (const \hyperlink{structuva_1_1smt_1_1tries_1_1mgrams_1_1_t___m___gram}{T\+\_\+\+M\+\_\+\+Gram} \&m\+Gram, \hyperlink{namespaceuva_1_1smt_1_1hashing_a5992ac0dea0fb3226fb403ede09fad55}{T\+Long\+Id} \&stx\+\_\+id)
\end{DoxyCompactItemize}
\subsection*{Additional Inherited Members}
\subsection{Detailed Description}
\subsubsection*{template$<$typename Trie\+Type$>$class uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver$<$ Trie\+Type $>$}
This is the common generic trie base class for layered tries.
\begin{DoxyParams}{Parameters}
{\em N} & the maximum level of the considered N-\/gram, i.\+e. the N value \\
\hline
{\em Trie\+Type} & the type of word index to be used \\
\hline
\end{DoxyParams}
\subsection{Member Typedef Documentation}
\hypertarget{classuva_1_1smt_1_1tries_1_1_layered_trie_driver_a039f866f4bab8e7313cfc9fa2cb51f5b}{}\index{uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver@{uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver}!B\+A\+S\+E@{B\+A\+S\+E}}
\index{B\+A\+S\+E@{B\+A\+S\+E}!uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver@{uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver}}
\subsubsection[{B\+A\+S\+E}]{\setlength{\rightskip}{0pt plus 5cm}template$<$typename Trie\+Type $>$ typedef {\bf Generic\+Trie\+Base}$<$Trie\+Type\+::max\+\_\+level, typename Trie\+Type\+::\+Word\+Index\+Type$>$ {\bf uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver}$<$ Trie\+Type $>$\+::{\bf B\+A\+S\+E}}\label{classuva_1_1smt_1_1tries_1_1_layered_trie_driver_a039f866f4bab8e7313cfc9fa2cb51f5b}
\hypertarget{classuva_1_1smt_1_1tries_1_1_layered_trie_driver_a260d262d60ecb64e33f39609e4dcfae9}{}\index{uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver@{uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver}!T\+M\+Gram\+Query@{T\+M\+Gram\+Query}}
\index{T\+M\+Gram\+Query@{T\+M\+Gram\+Query}!uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver@{uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver}}
\subsubsection[{T\+M\+Gram\+Query}]{\setlength{\rightskip}{0pt plus 5cm}template$<$typename Trie\+Type $>$ typedef Trie\+Type\+::\+T\+M\+Gram\+Query {\bf uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver}$<$ Trie\+Type $>$\+::{\bf T\+M\+Gram\+Query}}\label{classuva_1_1smt_1_1tries_1_1_layered_trie_driver_a260d262d60ecb64e33f39609e4dcfae9}
\hypertarget{classuva_1_1smt_1_1tries_1_1_layered_trie_driver_aaa30a8f51f4e610158fa8cf0eb965c01}{}\index{uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver@{uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver}!Word\+Index\+Type@{Word\+Index\+Type}}
\index{Word\+Index\+Type@{Word\+Index\+Type}!uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver@{uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver}}
\subsubsection[{Word\+Index\+Type}]{\setlength{\rightskip}{0pt plus 5cm}template$<$typename Trie\+Type $>$ typedef Trie\+Type\+::\+Word\+Index\+Type {\bf uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver}$<$ Trie\+Type $>$\+::{\bf Word\+Index\+Type}}\label{classuva_1_1smt_1_1tries_1_1_layered_trie_driver_aaa30a8f51f4e610158fa8cf0eb965c01}
\subsection{Constructor \& Destructor Documentation}
\hypertarget{classuva_1_1smt_1_1tries_1_1_layered_trie_driver_a3227c91c276b27e1b591a378b95de510}{}\index{uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver@{uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver}!Layered\+Trie\+Driver@{Layered\+Trie\+Driver}}
\index{Layered\+Trie\+Driver@{Layered\+Trie\+Driver}!uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver@{uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver}}
\subsubsection[{Layered\+Trie\+Driver(\+Word\+Index\+Type \&word\+\_\+index)}]{\setlength{\rightskip}{0pt plus 5cm}template$<$typename Trie\+Type $>$ {\bf uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver}$<$ Trie\+Type $>$\+::{\bf Layered\+Trie\+Driver} (
\begin{DoxyParamCaption}
\item[{{\bf Word\+Index\+Type} \&}]{word\+\_\+index}
\end{DoxyParamCaption}
)\hspace{0.3cm}{\ttfamily [inline]}, {\ttfamily [explicit]}}\label{classuva_1_1smt_1_1tries_1_1_layered_trie_driver_a3227c91c276b27e1b591a378b95de510}
The basic constructor
\begin{DoxyParams}{Parameters}
{\em \+\_\+word\+Index} & the word index to be used \\
\hline
\end{DoxyParams}
\hypertarget{classuva_1_1smt_1_1tries_1_1_layered_trie_driver_afca9b816915b28480c10624b3067ce3c}{}\index{uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver@{uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver}!````~Layered\+Trie\+Driver@{$\sim$\+Layered\+Trie\+Driver}}
\index{````~Layered\+Trie\+Driver@{$\sim$\+Layered\+Trie\+Driver}!uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver@{uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver}}
\subsubsection[{$\sim$\+Layered\+Trie\+Driver()}]{\setlength{\rightskip}{0pt plus 5cm}template$<$typename Trie\+Type $>$ virtual {\bf uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver}$<$ Trie\+Type $>$\+::$\sim${\bf Layered\+Trie\+Driver} (
\begin{DoxyParamCaption}
{}
\end{DoxyParamCaption}
)\hspace{0.3cm}{\ttfamily [inline]}, {\ttfamily [virtual]}}\label{classuva_1_1smt_1_1tries_1_1_layered_trie_driver_afca9b816915b28480c10624b3067ce3c}
The basic class destructor \hypertarget{classuva_1_1smt_1_1tries_1_1_layered_trie_driver_a3e49cd9f10938019643370bcf9c85d9c}{}\index{uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver@{uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver}!Layered\+Trie\+Driver@{Layered\+Trie\+Driver}}
\index{Layered\+Trie\+Driver@{Layered\+Trie\+Driver}!uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver@{uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver}}
\subsubsection[{Layered\+Trie\+Driver(const Layered\+Trie\+Driver \&orig)}]{\setlength{\rightskip}{0pt plus 5cm}template$<$typename Trie\+Type $>$ {\bf uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver}$<$ Trie\+Type $>$\+::{\bf Layered\+Trie\+Driver} (
\begin{DoxyParamCaption}
\item[{const {\bf Layered\+Trie\+Driver}$<$ Trie\+Type $>$ \&}]{orig}
\end{DoxyParamCaption}
)\hspace{0.3cm}{\ttfamily [inline]}, {\ttfamily [protected]}}\label{classuva_1_1smt_1_1tries_1_1_layered_trie_driver_a3e49cd9f10938019643370bcf9c85d9c}
The copy constructor, is made private as we do not intend to copy this class objects
\begin{DoxyParams}{Parameters}
{\em orig} & the object to copy from \\
\hline
\end{DoxyParams}
\subsection{Member Function Documentation}
\hypertarget{classuva_1_1smt_1_1tries_1_1_layered_trie_driver_ade31d2fd4fa525d73f6431550c3ba3e6}{}\index{uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver@{uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver}!add\+\_\+1\+\_\+gram@{add\+\_\+1\+\_\+gram}}
\index{add\+\_\+1\+\_\+gram@{add\+\_\+1\+\_\+gram}!uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver@{uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver}}
\subsubsection[{add\+\_\+1\+\_\+gram(const T\+\_\+\+M\+\_\+\+Gram \&gram)}]{\setlength{\rightskip}{0pt plus 5cm}template$<$typename Trie\+Type $>$ void {\bf uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver}$<$ Trie\+Type $>$\+::add\+\_\+1\+\_\+gram (
\begin{DoxyParamCaption}
\item[{const {\bf T\+\_\+\+M\+\_\+\+Gram} \&}]{gram}
\end{DoxyParamCaption}
)}\label{classuva_1_1smt_1_1tries_1_1_layered_trie_driver_ade31d2fd4fa525d73f6431550c3ba3e6}
\begin{DoxySeeAlso}{See also}
\hyperlink{classuva_1_1smt_1_1tries_1_1_generic_trie_base}{Generic\+Trie\+Base}
\end{DoxySeeAlso}
\hypertarget{classuva_1_1smt_1_1tries_1_1_layered_trie_driver_ada9749d3e525c6cdf7121c7c224c4055}{}\index{uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver@{uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver}!add\+\_\+back\+\_\+off\+\_\+weight@{add\+\_\+back\+\_\+off\+\_\+weight}}
\index{add\+\_\+back\+\_\+off\+\_\+weight@{add\+\_\+back\+\_\+off\+\_\+weight}!uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver@{uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver}}
\subsubsection[{add\+\_\+back\+\_\+off\+\_\+weight(\+T\+M\+Gram\+Query \&query)}]{\setlength{\rightskip}{0pt plus 5cm}template$<$typename Trie\+Type $>$ void {\bf uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver}$<$ Trie\+Type $>$\+::add\+\_\+back\+\_\+off\+\_\+weight (
\begin{DoxyParamCaption}
\item[{{\bf T\+M\+Gram\+Query} \&}]{query}
\end{DoxyParamCaption}
)}\label{classuva_1_1smt_1_1tries_1_1_layered_trie_driver_ada9749d3e525c6cdf7121c7c224c4055}
\begin{DoxySeeAlso}{See also}
\hyperlink{classuva_1_1smt_1_1tries_1_1_generic_trie_base}{Generic\+Trie\+Base}
\end{DoxySeeAlso}
\hypertarget{classuva_1_1smt_1_1tries_1_1_layered_trie_driver_aa9dbc4a56665624d03be9071a7b576cb}{}\index{uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver@{uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver}!add\+\_\+m\+\_\+gram@{add\+\_\+m\+\_\+gram}}
\index{add\+\_\+m\+\_\+gram@{add\+\_\+m\+\_\+gram}!uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver@{uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver}}
\subsubsection[{add\+\_\+m\+\_\+gram(const T\+\_\+\+M\+\_\+\+Gram \&gram)}]{\setlength{\rightskip}{0pt plus 5cm}template$<$typename Trie\+Type $>$ void {\bf uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver}$<$ Trie\+Type $>$\+::add\+\_\+m\+\_\+gram (
\begin{DoxyParamCaption}
\item[{const {\bf T\+\_\+\+M\+\_\+\+Gram} \&}]{gram}
\end{DoxyParamCaption}
)}\label{classuva_1_1smt_1_1tries_1_1_layered_trie_driver_aa9dbc4a56665624d03be9071a7b576cb}
\begin{DoxySeeAlso}{See also}
\hyperlink{classuva_1_1smt_1_1tries_1_1_generic_trie_base}{Generic\+Trie\+Base}
\end{DoxySeeAlso}
\hypertarget{classuva_1_1smt_1_1tries_1_1_layered_trie_driver_aba8b64810a7a1b0dd89b129d42167446}{}\index{uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver@{uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver}!add\+\_\+n\+\_\+gram@{add\+\_\+n\+\_\+gram}}
\index{add\+\_\+n\+\_\+gram@{add\+\_\+n\+\_\+gram}!uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver@{uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver}}
\subsubsection[{add\+\_\+n\+\_\+gram(const T\+\_\+\+M\+\_\+\+Gram \&gram)}]{\setlength{\rightskip}{0pt plus 5cm}template$<$typename Trie\+Type $>$ void {\bf uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver}$<$ Trie\+Type $>$\+::add\+\_\+n\+\_\+gram (
\begin{DoxyParamCaption}
\item[{const {\bf T\+\_\+\+M\+\_\+\+Gram} \&}]{gram}
\end{DoxyParamCaption}
)}\label{classuva_1_1smt_1_1tries_1_1_layered_trie_driver_aba8b64810a7a1b0dd89b129d42167446}
\begin{DoxySeeAlso}{See also}
\hyperlink{classuva_1_1smt_1_1tries_1_1_generic_trie_base}{Generic\+Trie\+Base}
\end{DoxySeeAlso}
\hypertarget{classuva_1_1smt_1_1tries_1_1_layered_trie_driver_a24f0de20cf024b090073103099bd76d5}{}\index{uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver@{uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver}!get\+\_\+context\+\_\+id@{get\+\_\+context\+\_\+id}}
\index{get\+\_\+context\+\_\+id@{get\+\_\+context\+\_\+id}!uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver@{uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver}}
\subsubsection[{get\+\_\+context\+\_\+id(const T\+\_\+\+M\+\_\+\+Gram \&gram, T\+Long\+Id \&ctx\+Id)}]{\setlength{\rightskip}{0pt plus 5cm}template$<$typename Trie\+Type $>$ template$<$Debug\+Levels\+Enum log\+Level$>$ bool {\bf uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver}$<$ Trie\+Type $>$\+::get\+\_\+context\+\_\+id (
\begin{DoxyParamCaption}
\item[{const {\bf T\+\_\+\+M\+\_\+\+Gram} \&}]{gram, }
\item[{{\bf T\+Long\+Id} \&}]{ctx\+Id}
\end{DoxyParamCaption}
)\hspace{0.3cm}{\ttfamily [inline]}, {\ttfamily [protected]}}\label{classuva_1_1smt_1_1tries_1_1_layered_trie_driver_a24f0de20cf024b090073103099bd76d5}
This function computes the context id of the N-\/gram given by the tokens, e.\+g. \mbox{[}w1 w2 w3 w4\mbox{]}
W\+A\+R\+N\+I\+N\+G\+: Must be called on M-\/grams with M $>$ 1!
\begin{DoxyParams}{Parameters}
{\em gram} & the N-\/gram with its tokens to create context for \\
\hline
{\em the} & resulting hash of the context(w1 w2 w3) \\
\hline
\end{DoxyParams}
\begin{DoxyReturn}{Returns}
true if the context was found otherwise false
\end{DoxyReturn}
\hypertarget{classuva_1_1smt_1_1tries_1_1_layered_trie_driver_a41b2c53ae4c5fedf84d629296b5718b8}{}\index{uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver@{uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver}!get\+\_\+prob\+\_\+weight@{get\+\_\+prob\+\_\+weight}}
\index{get\+\_\+prob\+\_\+weight@{get\+\_\+prob\+\_\+weight}!uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver@{uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver}}
\subsubsection[{get\+\_\+prob\+\_\+weight(\+T\+M\+Gram\+Query \&query)}]{\setlength{\rightskip}{0pt plus 5cm}template$<$typename Trie\+Type $>$ void {\bf uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver}$<$ Trie\+Type $>$\+::get\+\_\+prob\+\_\+weight (
\begin{DoxyParamCaption}
\item[{{\bf T\+M\+Gram\+Query} \&}]{query}
\end{DoxyParamCaption}
)}\label{classuva_1_1smt_1_1tries_1_1_layered_trie_driver_a41b2c53ae4c5fedf84d629296b5718b8}
\begin{DoxySeeAlso}{See also}
\hyperlink{classuva_1_1smt_1_1tries_1_1_generic_trie_base}{Generic\+Trie\+Base}
\end{DoxySeeAlso}
\hypertarget{classuva_1_1smt_1_1tries_1_1_layered_trie_driver_ae0f2066edca3e2511809e35223fc0170}{}\index{uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver@{uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver}!get\+\_\+query\+\_\+context\+\_\+\+Id@{get\+\_\+query\+\_\+context\+\_\+\+Id}}
\index{get\+\_\+query\+\_\+context\+\_\+\+Id@{get\+\_\+query\+\_\+context\+\_\+\+Id}!uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver@{uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver}}
\subsubsection[{get\+\_\+query\+\_\+context\+\_\+\+Id(const T\+M\+Gram\+Query \&query, T\+Long\+Id \&ctx\+\_\+id)}]{\setlength{\rightskip}{0pt plus 5cm}template$<$typename Trie\+Type $>$ template$<$bool is\+\_\+back\+\_\+off$>$ bool {\bf uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver}$<$ Trie\+Type $>$\+::get\+\_\+query\+\_\+context\+\_\+\+Id (
\begin{DoxyParamCaption}
\item[{const {\bf T\+M\+Gram\+Query} \&}]{query, }
\item[{{\bf T\+Long\+Id} \&}]{ctx\+\_\+id}
\end{DoxyParamCaption}
)\hspace{0.3cm}{\ttfamily [inline]}, {\ttfamily [protected]}}\label{classuva_1_1smt_1_1tries_1_1_layered_trie_driver_ae0f2066edca3e2511809e35223fc0170}
Compute the context hash for the M-\/\+Gram prefix, example\+:
N = 5
0 1 2 3 4 w1 w2 w3 w4 w5
context\+Length = 2
0 1 2 3 4 w1 w2 w3 w4 w5 $^\wedge$ $^\wedge$ Hash will be computed for the 3-\/gram prefix w3 w4.
\begin{DoxyParams}{Parameters}
{\em is\+\_\+back\+\_\+off} & is the boolean flag that determines whether we compute the context for the entire M-\/\+Gram or for the back-\/off sub-\/\+M-\/gram. For the latter we consider w1 w2 w3 w4 only \\
\hline
{\em query} & the query state object \\
\hline
{\em ctx\+\_\+id} & \mbox{[}out\mbox{]} the context id to be computed \\
\hline
\end{DoxyParams}
\begin{DoxyReturn}{Returns}
the true if the context could be computed, otherwise false
\end{DoxyReturn}
\begin{DoxyExceptions}{Exceptions}
{\em nothing} & \\
\hline
\end{DoxyExceptions}
\hypertarget{classuva_1_1smt_1_1tries_1_1_layered_trie_driver_aa45ae9734e536721ba527abef4b09880}{}\index{uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver@{uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver}!get\+Cached\+Context\+Id@{get\+Cached\+Context\+Id}}
\index{get\+Cached\+Context\+Id@{get\+Cached\+Context\+Id}!uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver@{uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver}}
\subsubsection[{get\+Cached\+Context\+Id(const T\+\_\+\+M\+\_\+\+Gram \&m\+Gram, T\+Long\+Id \&result)}]{\setlength{\rightskip}{0pt plus 5cm}template$<$typename Trie\+Type $>$ bool {\bf uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver}$<$ Trie\+Type $>$\+::get\+Cached\+Context\+Id (
\begin{DoxyParamCaption}
\item[{const {\bf T\+\_\+\+M\+\_\+\+Gram} \&}]{m\+Gram, }
\item[{{\bf T\+Long\+Id} \&}]{result}
\end{DoxyParamCaption}
)\hspace{0.3cm}{\ttfamily [inline]}, {\ttfamily [protected]}}\label{classuva_1_1smt_1_1tries_1_1_layered_trie_driver_aa45ae9734e536721ba527abef4b09880}
Allows to retrieve the cached context id for the given M-\/gram if any
\begin{DoxyParams}{Parameters}
{\em m\+Gram} & the m-\/gram to get the context id for \\
\hline
{\em result} & the output parameter, will store the cached id, if any \\
\hline
\end{DoxyParams}
\begin{DoxyReturn}{Returns}
true if there was nothing cached, otherwise false
\end{DoxyReturn}
\hypertarget{classuva_1_1smt_1_1tries_1_1_layered_trie_driver_a1db7700d2609beeae0dfb2a1f3cd5c3a}{}\index{uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver@{uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver}!is\+\_\+bitmap\+\_\+hash\+\_\+cache@{is\+\_\+bitmap\+\_\+hash\+\_\+cache}}
\index{is\+\_\+bitmap\+\_\+hash\+\_\+cache@{is\+\_\+bitmap\+\_\+hash\+\_\+cache}!uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver@{uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver}}
\subsubsection[{is\+\_\+bitmap\+\_\+hash\+\_\+cache(\+T\+M\+Gram\+Query \&query)}]{\setlength{\rightskip}{0pt plus 5cm}template$<$typename Trie\+Type $>$ template$<$bool is\+\_\+back\+\_\+off$>$ bool {\bf uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver}$<$ Trie\+Type $>$\+::is\+\_\+bitmap\+\_\+hash\+\_\+cache (
\begin{DoxyParamCaption}
\item[{{\bf T\+M\+Gram\+Query} \&}]{query}
\end{DoxyParamCaption}
)\hspace{0.3cm}{\ttfamily [inline]}}\label{classuva_1_1smt_1_1tries_1_1_layered_trie_driver_a1db7700d2609beeae0dfb2a1f3cd5c3a}
Allows to check if the given sub-\/m-\/gram contains an unknown word
\begin{DoxyParams}{Parameters}
{\em level} & of the considered M-\/gram \\
\hline
\end{DoxyParams}
\begin{DoxyReturn}{Returns}
true if the unknown word is present, otherwise false
\end{DoxyReturn}
\hypertarget{classuva_1_1smt_1_1tries_1_1_layered_trie_driver_a178c3021bc5fd5ff9035c6f86a80e2b6}{}\index{uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver@{uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver}!is\+\_\+post\+\_\+grams@{is\+\_\+post\+\_\+grams}}
\index{is\+\_\+post\+\_\+grams@{is\+\_\+post\+\_\+grams}!uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver@{uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver}}
\subsubsection[{is\+\_\+post\+\_\+grams(const T\+Model\+Level level)}]{\setlength{\rightskip}{0pt plus 5cm}template$<$typename Trie\+Type $>$ bool {\bf uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver}$<$ Trie\+Type $>$\+::is\+\_\+post\+\_\+grams (
\begin{DoxyParamCaption}
\item[{const {\bf T\+Model\+Level}}]{level}
\end{DoxyParamCaption}
)\hspace{0.3cm}{\ttfamily [inline]}}\label{classuva_1_1smt_1_1tries_1_1_layered_trie_driver_a178c3021bc5fd5ff9035c6f86a80e2b6}
\begin{DoxySeeAlso}{See also}
\hyperlink{classuva_1_1smt_1_1tries_1_1_generic_trie_base}{Generic\+Trie\+Base}
\end{DoxySeeAlso}
\hypertarget{classuva_1_1smt_1_1tries_1_1_layered_trie_driver_aa517364127a40f1942dcae633f819304}{}\index{uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver@{uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver}!log\+\_\+trie\+\_\+type\+\_\+usage\+\_\+info@{log\+\_\+trie\+\_\+type\+\_\+usage\+\_\+info}}
\index{log\+\_\+trie\+\_\+type\+\_\+usage\+\_\+info@{log\+\_\+trie\+\_\+type\+\_\+usage\+\_\+info}!uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver@{uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver}}
\subsubsection[{log\+\_\+trie\+\_\+type\+\_\+usage\+\_\+info()}]{\setlength{\rightskip}{0pt plus 5cm}template$<$typename Trie\+Type $>$ void {\bf uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver}$<$ Trie\+Type $>$\+::log\+\_\+trie\+\_\+type\+\_\+usage\+\_\+info (
\begin{DoxyParamCaption}
{}
\end{DoxyParamCaption}
)\hspace{0.3cm}{\ttfamily [inline]}}\label{classuva_1_1smt_1_1tries_1_1_layered_trie_driver_aa517364127a40f1942dcae633f819304}
\begin{DoxySeeAlso}{See also}
\hyperlink{classuva_1_1smt_1_1tries_1_1_generic_trie_base}{Generic\+Trie\+Base}
\end{DoxySeeAlso}
\hypertarget{classuva_1_1smt_1_1tries_1_1_layered_trie_driver_ad25a2d45904154530dee9ccd0945dd9c}{}\index{uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver@{uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver}!post\+\_\+grams@{post\+\_\+grams}}
\index{post\+\_\+grams@{post\+\_\+grams}!uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver@{uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver}}
\subsubsection[{post\+\_\+grams(const T\+Model\+Level level)}]{\setlength{\rightskip}{0pt plus 5cm}template$<$typename Trie\+Type $>$ void {\bf uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver}$<$ Trie\+Type $>$\+::post\+\_\+grams (
\begin{DoxyParamCaption}
\item[{const {\bf T\+Model\+Level}}]{level}
\end{DoxyParamCaption}
)\hspace{0.3cm}{\ttfamily [inline]}}\label{classuva_1_1smt_1_1tries_1_1_layered_trie_driver_ad25a2d45904154530dee9ccd0945dd9c}
\begin{DoxySeeAlso}{See also}
\hyperlink{classuva_1_1smt_1_1tries_1_1_generic_trie_base}{Generic\+Trie\+Base}
\end{DoxySeeAlso}
\hypertarget{classuva_1_1smt_1_1tries_1_1_layered_trie_driver_af1726a1b69e0274be8c9dfed9283b3ff}{}\index{uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver@{uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver}!pre\+\_\+allocate@{pre\+\_\+allocate}}
\index{pre\+\_\+allocate@{pre\+\_\+allocate}!uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver@{uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver}}
\subsubsection[{pre\+\_\+allocate(const size\+\_\+t counts[Trie\+Type\+::max\+\_\+level])}]{\setlength{\rightskip}{0pt plus 5cm}template$<$typename Trie\+Type $>$ void {\bf uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver}$<$ Trie\+Type $>$\+::pre\+\_\+allocate (
\begin{DoxyParamCaption}
\item[{const size\+\_\+t}]{counts\mbox{[}\+Trie\+Type\+::max\+\_\+level\mbox{]}}
\end{DoxyParamCaption}
)\hspace{0.3cm}{\ttfamily [inline]}}\label{classuva_1_1smt_1_1tries_1_1_layered_trie_driver_af1726a1b69e0274be8c9dfed9283b3ff}
\begin{DoxySeeAlso}{See also}
\hyperlink{classuva_1_1smt_1_1tries_1_1_generic_trie_base}{Generic\+Trie\+Base}
\end{DoxySeeAlso}
\hypertarget{classuva_1_1smt_1_1tries_1_1_layered_trie_driver_a17a46690a7c2c577bbc3379d9705b62e}{}\index{uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver@{uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver}!set\+Cache\+Context\+Id@{set\+Cache\+Context\+Id}}
\index{set\+Cache\+Context\+Id@{set\+Cache\+Context\+Id}!uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver@{uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver}}
\subsubsection[{set\+Cache\+Context\+Id(const T\+\_\+\+M\+\_\+\+Gram \&m\+Gram, T\+Long\+Id \&stx\+\_\+id)}]{\setlength{\rightskip}{0pt plus 5cm}template$<$typename Trie\+Type $>$ void {\bf uva\+::smt\+::tries\+::\+Layered\+Trie\+Driver}$<$ Trie\+Type $>$\+::set\+Cache\+Context\+Id (
\begin{DoxyParamCaption}
\item[{const {\bf T\+\_\+\+M\+\_\+\+Gram} \&}]{m\+Gram, }
\item[{{\bf T\+Long\+Id} \&}]{stx\+\_\+id}
\end{DoxyParamCaption}
)\hspace{0.3cm}{\ttfamily [inline]}, {\ttfamily [protected]}}\label{classuva_1_1smt_1_1tries_1_1_layered_trie_driver_a17a46690a7c2c577bbc3379d9705b62e}
Allows to cache the context id of the given m-\/grams context
\begin{DoxyParams}{Parameters}
{\em m\+Gram} & \\
\hline
{\em result} & \\
\hline
\end{DoxyParams}
The documentation for this class was generated from the following files\+:\begin{DoxyCompactItemize}
\item
inc/\hyperlink{_layered_trie_driver_8hpp}{Layered\+Trie\+Driver.\+hpp}\item
src/\hyperlink{_layered_trie_driver_8cpp}{Layered\+Trie\+Driver.\+cpp}\end{DoxyCompactItemize}
| ivan-zapreev/Back-Off-Language-Model-SMT | doxygen/latex/classuva_1_1smt_1_1tries_1_1_layered_trie_driver.tex | TeX | gpl-2.0 | 28,259 |
N÷S<?php exit; ?>a:1:{s:7:"content";a:9:{s:15:"_menu_item_type";a:1:{i:0;s:8:"taxonomy";}s:27:"_menu_item_menu_item_parent";a:1:{i:0;s:1:"0";}s:20:"_menu_item_object_id";a:1:{i:0;s:4:"1981";}s:17:"_menu_item_object";a:1:{i:0;s:11:"product_cat";}s:17:"_menu_item_target";a:1:{i:0;s:0:"";}s:18:"_menu_item_classes";a:1:{i:0;s:17:"a:1:{i:0;s:0:"";}";}s:14:"_menu_item_xfn";a:1:{i:0;s:0:"";}s:14:"_menu_item_url";a:1:{i:0;s:0:"";}s:13:"_uber_options";a:1:{i:0;s:480:"a:13:{s:19:"menu-item-shortcode";s:0:"";s:18:"menu-item-sidebars";s:0:"";s:19:"menu-item-highlight";s:3:"off";s:16:"menu-item-notext";s:3:"off";s:16:"menu-item-nolink";s:3:"off";s:18:"menu-item-isheader";s:3:"off";s:26:"menu-item-verticaldivision";s:3:"off";s:16:"menu-item-newcol";s:3:"off";s:16:"menu-item-isMega";s:2:"on";s:22:"menu-item-alignSubmenu";s:6:"center";s:20:"menu-item-floatRight";s:3:"off";s:19:"menu-item-fullWidth";s:3:"off";s:17:"menu-item-numCols";s:4:"auto";}";}}} | acscoleen/acsdevelopment | wp-content/cache/object/000000/885/dd9/885dd95f7e4d4b73086ab10cf79f4b63.php | PHP | gpl-2.0 | 949 |
obj-$(CONFIG_PARROT_GPIO) += gpio2.o
obj-$(CONFIG_PARROT_PWM) += pwm/
| CunningLogic/asteroid_smart_kernel | drivers/parrot/char/Makefile | Makefile | gpl-2.0 | 71 |
package com.proint1.udea.notificaciones;
import java.io.File;
import java.io.Serializable;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Clase que encapsula el envio de un correo en formato HTMl, para incluir
* adjuntos y contenido html
*/
public class EMailHtml implements Serializable {
private static final Logger LOGGER = LoggerFactory.getLogger(EMailHtml.class);
/** serialVersionUID */
private static final long serialVersionUID = 3232851751545279316L;
/** Adress to */
private InternetAddress[] adressesTo;
/** Adress CC */
private InternetAddress[] adressesCc;
/** Adress Bcc */
private InternetAddress[] adressesBcc;
/** Variables */
private Properties props = new Properties();
/** From del message */
private String from;
/** Çontenido del mensaje */
private String content;
/** Sujeto de mensaje */
private String subject = "";
/** MultiPart para crear mensajes compuestos */
private MimeMultipart multipart = new MimeMultipart("related");
/** usuario que logea el servidor de correo */
private String emailUser;
/** Passwordel del email user para autenticación del servidor de correo */
private String passwordEmail;
/**
* Constructor
*
* @param host nombre del servidor de correo
* @param user usuario de correo
* @param password password del usuario
*/
public EMailHtml(String subject, String menssage) {
try {
props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.smtp.starttls.enable", "true");
props.setProperty("mail.host", "smtp.gmail.com");
emailUser = "pmontoya206@gmail.com";
props.setProperty("mail.user", emailUser);
passwordEmail = "proyecto2014";
props.setProperty("mail.password", passwordEmail);
props.setProperty("mail.smtp.port", "587");
props.setProperty("mail.smtp.auth", "true");
this.subject = subject;
this.from = "pmontoya206@gmail.com";
this.content = menssage;
} catch (Exception e) {
LOGGER.error("PropiedadNoEncontradaException ", e);
}
}
/**
* Añade el contenido base al multipart
*
* @throws MessagingException
*
* @throws Exception Excepcion levantada en caso de error
*/
public void addContentToMultipart() throws MessagingException {
// first part (the html)
BodyPart messageBodyPart = new MimeBodyPart();
String htmlText = this.getContent();
messageBodyPart.setContent(htmlText, "text/html");
// add it
this.multipart.addBodyPart(messageBodyPart);
}
/**
* Añade el contenido base al multipart
*
* @param htmlText contenido html que se muestra en el mensaje de correo
* @throws MessagingException
* @throws Exception Excepcion levantada en caso de error
*/
public void addContent(String htmlText) throws MessagingException {
// first part (the html)
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(htmlText, "text/html");
// add it
this.multipart.addBodyPart(messageBodyPart);
}
/**
* Añade al mensaje un cid:name utilizado para guardar las imagenes referenciadas en el HTML de la forma
* <img src=cid:name />
*
* @param cidname identificador que se le da a la imagen. suele ser un string generado aleatoriamente.
* @param pathname ruta del fichero que almacena la imagen
* @throws MessagingException
* @throws Exception excepcion levantada en caso de error
*/
public void addCID(String cidname, String pathname) throws MessagingException {
DataSource fds = new FileDataSource(pathname);
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setDataHandler(new DataHandler(fds));
messageBodyPart.setHeader("Content-ID", "<" + cidname + ">");
this.multipart.addBodyPart(messageBodyPart);
}
/**
* Añade un attachement al mensaje de email
*
* @param pathname ruta del fichero
* @throws MessagingException
* @throws Exception excepcion levantada en caso de error
*/
public void addAttach(String pathname) throws MessagingException {
File file = new File(pathname);
BodyPart messageBodyPart = new MimeBodyPart();
DataSource ds = new FileDataSource(file);
messageBodyPart.setDataHandler(new DataHandler(ds));
messageBodyPart.setFileName(file.getName());
messageBodyPart.setDisposition(Part.ATTACHMENT);
this.multipart.addBodyPart(messageBodyPart);
}
/**
* Operación final de envio sea con documentos o sin ellos
*
* @throws MessagingException
*
* @throws Exception
*/
public void sendMessage() throws MessagingException {
sendMultipart();
}
/**
* Envia un correo multipart
*
* @throws MessagingException
* @throws Exception Excepcion levantada en caso de error
*/
private void sendMultipart() throws MessagingException {
Session mailSession = Session.getDefaultInstance(this.props, null);
mailSession.setDebug(true);
Transport transport = mailSession.getTransport();
MimeMessage message = new MimeMessage(mailSession);
// Agregar sujeto
message.setSubject(this.getSubject());
// Agregrar el from
message.setFrom(new InternetAddress(this.getFrom()));
// Agregar destinatiarios
if (adressesTo != null && adressesTo.length > 0) {
message.addRecipients(Message.RecipientType.TO, adressesTo);
}
if (adressesCc != null && adressesCc.length > 0) {
message.addRecipients(Message.RecipientType.CC, adressesCc);
}
if (adressesBcc != null && adressesBcc.length > 0) {
message.addRecipients(Message.RecipientType.BCC, adressesBcc);
}
// put everything together
message.setContent(multipart);
transport.connect(emailUser, passwordEmail);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
/**
* @return the adressesTo
*/
public InternetAddress[] getAdressesTo() {
return adressesTo;
}
/**
* @param adressesTo the adressesTo to set
*/
public void setAdressesTo(InternetAddress[] adressesTo) {
this.adressesTo = adressesTo;
}
/**
* @return the adressesCc
*/
public InternetAddress[] getAdressesCc() {
return adressesCc;
}
/**
* @param adressesCc the adressesCc to set
*/
public void setAdressesCc(InternetAddress[] adressesCc) {
this.adressesCc = adressesCc;
}
/**
* @return the adressesBcc
*/
public InternetAddress[] getAdressesBcc() {
return adressesBcc;
}
/**
* @param adressesBcc the adressesBcc to set
*/
public void setAdressesBcc(InternetAddress[] adressesBcc) {
this.adressesBcc = adressesBcc;
}
}
| RegistroUdeA/Prueba | PI1Web/src/com/proint1/udea/notificaciones/EMailHtml.java | Java | gpl-2.0 | 7,571 |
<?php
/**
Template Name: checkorder
* The template for displaying all pages.
* @package commercegurus
*/
$user_ID = get_current_user_id();
$totalcredit = intval(do_shortcode("[usercreditwoocommerce]"));
if(!$user_ID)
{
header("Location:".get_bloginfo("url"));
exit;
}
if($_POST['creditupdate']=="yes")
{
if($totalcredit>0)
{
foreach($_POST['mediid'] as $id)
{
updatcredit($id);
}
header("Location:".get_permalink("url")."?assign=done");
exit;
}
else
{
header("Location:".get_permalink("url")."?assign=no");
exit;
}
}
get_header();
?>
<?php cg_get_page_title(); ?>
<?php
// Get our page banner if it exists
$cg_page_banner_image = '';
if ( function_exists( 'get_field' ) ) {
$page_banner = get_field( 'banner_image' );
$page_banner_height = get_field( 'page_banner_height' );
}
if ( !empty( $page_banner ) ) {
$cg_page_banner_image = $page_banner;
}
?>
<?php if ( $cg_page_banner_image ) { ?>
<?php $danchor = 'cg-strip-' . rand(); ?>
<div class="cg-strip cg-strip-wrap fade-in animate" style="background-color:#333333!important; height:<?php echo $page_banner_height; ?>;">
<div class="cg-strip-bg cg_parallax skrollable skrollable-between" style="background-image: url(<?php echo $cg_page_banner_image; ?>);" data-center="background-position: 50% 50%;" data-top-bottom="background-position: 50% 0%" data-bottom-top="background-position: 50% 95%"></div>
<div class="row">
<div style="width: 50%;" class="cg-pos valign-center halign-center">
<div class="cg-strip-content <?php echo $danchor; ?> light text-align-center skrollable skrollable-before" data-center-bottom="opacity: 1" data--150-top="opacity: 0" data-anchor-target=".<?php echo $danchor; ?>" style="opacity: 1;">
<h1><?php the_title(); ?></h1>
</div>
</div>
</div>
</div>
<?php } ?>
<div class="container">
<div class="content">
<div class="row">
<div class="col-lg-9 col-md-9 col-md-push-3 col-lg-push-3">
<div id="primary" class="content-area">
<main id="main" class="site-main woocommerce" role="main">
<?php
$totalcredit = do_shortcode("[usercreditwoocommerce]");
$user_ID = get_current_user_id();
$args = array(
'post_status' => 'any',
'post_type' => 'attachment',
'posts_per_page'=>-1,
'author'=>$user_ID,
'meta_query' => array(
array(
'key' => 'credits',
'value' => 0,
'compare' => '=',
),
),
);
$count = count(query_posts( $args ));
?>
<?php if($_GET['assign']=="done")
{
?>
<div style="color:#006600"><strong> Thanks for assigning credit to images.</strong></div>
<?php } else if($_GET['assign']=="no") {?><div style="color:#FF0000"><strong>No Credit Available.</strong></div>
<?php } ?>
<div style="clear:both"> You have <?php echo $totalcredit; ?> credits and <?php echo $count?> unpaid images, please <a href="<?php echo get_bloginfo("url")?>/credit/">buy credit</a> to approve these images.</div>
<br/>
<?php if($count>0)
{?>
<h3> Assign Credit to Images</h3>
<form name="checkconform" action="" method="post" >
<input type="hidden" name="creditupdate" value="yes" />
<?php
while ( have_posts() ) : the_post();
$image_id = get_post_thumbnail_id($post->ID);
$feat_image = wp_get_attachment_url( get_post_thumbnail_id($post->ID) );
?>
<article id="post-<?php the_ID(); ?>" <?php post_class('col-lg-4 col-md-4'); ?>>
<div class="entry-content">
<?php $img = vt_resize('',$feat_image,350, 250,true);
?>
<a href="<?php echo $feat_image; ?>" target="_blank">
<img src="<?php echo $img['url'] ?>" style="padding:10px" /></a>
<input type="checkbox" name="mediid[]" value="<?php echo get_the_ID() ?>" />
<?php
?>
</div><!-- .entry-content -->
</article><!-- #post-## -->
<?php endwhile; wp_reset_query(); // end of the loop. ?>
<div style="clear:both">
<input type="submit" class="button checkout-button " name="proceed" value="Proceed to Conform">
</div>
</form> <?php } ?>
</main><!-- #main -->
<main id="main" class="site-main" role="main" style="clear:both;padding-top:100px">
<h3> Approved Images</h3>
<?php
$totalcredit = do_shortcode("[usercreditwoocommerce]");
$user_ID = get_current_user_id();
$args = array(
'post_status' => 'any',
'post_type' => 'attachment',
'posts_per_page'=>-1,
'author'=>$user_ID,
'meta_query' => array(
array(
'key' => 'credits',
'value' => 1,
'compare' => '=',
),
),
);
$count = count(query_posts( $args ));
?>
<br/>
<?php
while ( have_posts() ) : the_post();
$image_id = get_post_thumbnail_id($post->ID);
$feat_image = wp_get_attachment_url( get_post_thumbnail_id($post->ID) );
?>
<article id="post-<?php the_ID(); ?>" <?php post_class('col-lg-4 col-md-4'); ?>>
<div class="entry-content">
<?php $img = vt_resize('',$feat_image,350, 250,true);
?>
<a href="<?php echo $feat_image; ?>" target="_blank">
<img src="<?php echo $img['url'] ?>" style="padding:10px" /></a>
</div><!-- .entry-content -->
</article><!-- #post-## -->
<?php endwhile; wp_reset_query(); // end of the loop. ?>
</main>
<main id="main" class="site-main" role="main" style="clear:both;padding-top:100px">
<h3>Image Uplaod by admin</h3>
<?php
$totalcredit = do_shortcode("[usercreditwoocommerce]");
$user_ID = get_current_user_id();
$args = array(
'post_status' => 'any',
'post_type' => 'attachment',
'posts_per_page'=>-1,
'author'=>$user_ID,
'meta_query' => array(
array(
'key' => 'upload_by_admin',
'value' => 1,
'compare' => '=',
),
),
);
echo $count = count(query_posts( $args ));
?>
<br/>
<?php
while ( have_posts() ) : the_post();
$image_id = get_post_thumbnail_id($post->ID);
$feat_image = wp_get_attachment_url( get_post_thumbnail_id($post->ID) );
?>
<article id="post-<?php the_ID(); ?>" <?php post_class('col-lg-4 col-md-4'); ?>>
<div class="entry-content" style="text-align:center">
<?php $img = vt_resize('',$feat_image,350, 250,true);
?>
<a href="<?php echo get_bloginfo("url") ?>downloadimg.php?img=<?php echo str_replace(get_bloginfo("url"),"",$feat_image); ?>">
<img src="<?php echo $img['url'] ?>" style="padding:10px 10px 2px 10px" />Download Image</a>
</div><!-- .entry-content -->
</article><!-- #post-## -->
<?php endwhile; wp_reset_query(); // end of the loop. ?>
</main>
</div><!-- #primary -->
</div>
<div class="col-lg-3 col-md-3 col-md-pull-9 col-lg-pull-9">
<?php get_sidebar(); ?>
</div>
</div><!--/row -->
</div><!--/content -->
</div><!--/container -->
<?php get_footer(); ?>
| narendra-addweb/MyImmoPix | wp-content/themes/adrenalin/template-ordercheck.php | PHP | gpl-2.0 | 7,839 |
#!/bin/sh
echo $@
echo $* | nonemaw/MATRIX_01 | COMP9041/ass1/autoTest/examples/5/echo6.sh | Shell | gpl-2.0 | 27 |
using System;
namespace Server.Items
{
public class FireColumnTrap : BaseTrap
{
[Constructable]
public FireColumnTrap() : base( 0x1B71 )
{
}
public override bool PassivelyTriggered{ get{ return true; } }
public override TimeSpan PassiveTriggerDelay{ get{ return TimeSpan.FromSeconds( 2.0 ); } }
public override int PassiveTriggerRange{ get{ return 3; } }
public override TimeSpan ResetDelay{ get{ return TimeSpan.FromSeconds( 0.5 ); } }
public override void OnTrigger( Mobile from )
{
if ( from.AccessLevel > AccessLevel.Player )
return;
Effects.SendLocationParticles( EffectItem.Create( Location, Map, EffectItem.DefaultDuration ), 0x3709, 10, 30, 5052 );
Effects.PlaySound( Location, Map, 0x225 );
if ( from.Alive && CheckRange( from.Location, 0 ) )
Spells.SpellHelper.Damage( TimeSpan.FromSeconds( 0.5 ), from, from, Utility.RandomMinMax( 10, 40 ), 0, 100, 0, 0, 0 );
}
public FireColumnTrap( 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();
}
}
} | brodock/sunuo | scripts/legacy/Items/Traps/FireColumnTrap.cs | C# | gpl-2.0 | 1,267 |
/*
* Created by Rolando Abarca 2012.
* Copyright (c) 2012 Rolando Abarca. All rights reserved.
* Copyright (c) 2013 Zynga Inc. All rights reserved.
* Copyright (c) 2013-2014 Chukong Technologies Inc.
*
* Heavy based on: https://github.com/funkaster/FakeWebGL/blob/master/FakeWebGL/WebGL/XMLHTTPRequest.cpp
*
* 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 "XMLHTTPRequest.h"
#include <string>
using namespace std;
//#pragma mark - MinXmlHttpRequest
/**
* @brief Implementation for header retrieving.
* @param header
*/
void MinXmlHttpRequest::_gotHeader(string header)
{
// Get Header and Set StatusText
// Split String into Tokens
char * cstr = new char [header.length()+1];
// check for colon.
size_t found_header_field = header.find_first_of(":");
if (found_header_field != std::string::npos)
{
// Found a header field.
string http_field;
string http_value;
http_field = header.substr(0,found_header_field);
http_value = header.substr(found_header_field+1, header.length());
// Get rid of all \n
if (!http_value.empty() && http_value[http_value.size() - 1] == '\n') {
http_value.erase(http_value.size() - 1);
}
_httpHeader[http_field] = http_value;
}
else
{
// Seems like we have the response Code! Parse it and check for it.
char * pch;
strcpy(cstr, header.c_str());
pch = strtok(cstr," ");
while (pch != NULL)
{
stringstream ss;
string val;
ss << pch;
val = ss.str();
size_t found_http = val.find("HTTP");
// Check for HTTP Header to set statusText
if (found_http != std::string::npos) {
stringstream mystream;
// Get Response Status
pch = strtok (NULL, " ");
mystream << pch;
pch = strtok (NULL, " ");
mystream << " " << pch;
_statusText = mystream.str();
}
pch = strtok (NULL, " ");
}
}
CC_SAFE_DELETE_ARRAY(cstr);
}
/**
* @brief Set Request header for next call.
* @param field Name of the Header to be set.
* @param value Value of the Headerfield
*/
void MinXmlHttpRequest::_setRequestHeader(const char* field, const char* value)
{
stringstream header_s;
stringstream value_s;
string header;
auto iter = _requestHeader.find(field);
// Concatenate values when header exists.
if (iter != _requestHeader.end())
{
value_s << iter->second << "," << value;
}
else
{
value_s << value;
}
_requestHeader[field] = value_s.str();
}
/**
* @brief If headers has been set, pass them to curl.
*
*/
void MinXmlHttpRequest::_setHttpRequestHeader()
{
std::vector<string> header;
for (auto it = _requestHeader.begin(); it != _requestHeader.end(); ++it)
{
const char* first = it->first.c_str();
const char* second = it->second.c_str();
size_t len = sizeof(char) * (strlen(first) + 3 + strlen(second));
char* test = (char*) malloc(len);
memset(test, 0,len);
strcpy(test, first);
strcpy(test + strlen(first) , ": ");
strcpy(test + strlen(first) + 2, second);
header.push_back(test);
free(test);
}
if (!header.empty())
{
_httpRequest->setHeaders(header);
}
}
/**
* @brief Callback for HTTPRequest. Handles the response and invokes Callback.
* @param sender Object which initialized callback
* @param respone Response object
*/
void MinXmlHttpRequest::handle_requestResponse(cocos2d::network::HttpClient *sender, cocos2d::network::HttpResponse *response)
{
if (0 != strlen(response->getHttpRequest()->getTag()))
{
CCLOG("%s completed", response->getHttpRequest()->getTag());
}
long statusCode = response->getResponseCode();
char statusString[64] = {0};
sprintf(statusString, "HTTP Status Code: %ld, tag = %s", statusCode, response->getHttpRequest()->getTag());
if (!response->isSucceed())
{
CCLOG("Response failed, error buffer: %s", response->getErrorBuffer());
if (statusCode == 0)
{
_errorFlag = true;
_status = 0;
_statusText.clear();
return;
}
}
// set header
std::vector<char> *headers = response->getResponseHeader();
std::string header(headers->begin(), headers->end());
std::istringstream stream(header);
std::string line;
while(std::getline(stream, line)) {
_gotHeader(line);
}
/** get the response data **/
std::vector<char> *buffer = response->getResponseData();
_status = statusCode;
_readyState = DONE;
_dataSize = static_cast<uint32_t>(buffer->size());
CC_SAFE_FREE(_data);
_data = (char*) malloc(_dataSize + 1);
_data[_dataSize] = '\0';
memcpy((void*)_data, (const void*)buffer->data(), _dataSize);
js_proxy_t * p;
void* ptr = (void*)this;
p = jsb_get_native_proxy(ptr);
if(p)
{
JSContext* cx = ScriptingCore::getInstance()->getGlobalContext();
if (_onreadystateCallback)
{
JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET
//JS_IsExceptionPending(cx) && JS_ReportPendingException(cx);
jsval fval = OBJECT_TO_JSVAL(_onreadystateCallback);
jsval out;
JS_CallFunctionValue(cx, NULL, fval, 0, NULL, &out);
}
}
}
/**
* @brief Send out request and fire callback when done.
* @param cx Javascript context
*/
void MinXmlHttpRequest::_sendRequest(JSContext *cx)
{
_httpRequest->setResponseCallback(this, httpresponse_selector(MinXmlHttpRequest::handle_requestResponse));
cocos2d::network::HttpClient::getInstance()->send(_httpRequest);
_httpRequest->release();
}
/**
* @brief Constructor initializes cchttprequest and stuff
*
*/
MinXmlHttpRequest::MinXmlHttpRequest()
: _url()
, _cx(ScriptingCore::getInstance()->getGlobalContext())
, _meth()
, _type()
, _data(nullptr)
, _dataSize()
, _onreadystateCallback(nullptr)
, _readyState(UNSENT)
, _status(0)
, _statusText()
, _responseType()
, _timeout()
, _isAsync()
, _httpRequest(new cocos2d::network::HttpRequest())
, _isNetwork(true)
, _withCredentialsValue(true)
, _errorFlag(false)
, _httpHeader()
, _requestHeader()
{
}
/**
* @brief Destructor cleans up _httpRequest and stuff
*
*/
MinXmlHttpRequest::~MinXmlHttpRequest()
{
if (_onreadystateCallback != NULL)
{
JS_RemoveObjectRoot(_cx, &_onreadystateCallback);
}
if (_httpRequest)
{
// We don't need to release _httpRequest here since it will be released in the http callback.
// _httpRequest->release();
}
CC_SAFE_FREE(_data);
}
/**
* @brief Initialize Object and needed properties.
*
*/
JS_BINDED_CLASS_GLUE_IMPL(MinXmlHttpRequest);
/**
* @brief Implementation for the Javascript Constructor
*
*/
JS_BINDED_CONSTRUCTOR_IMPL(MinXmlHttpRequest)
{
MinXmlHttpRequest* req = new MinXmlHttpRequest();
req->autorelease();
js_proxy_t *p;
jsval out;
JSObject *obj = JS_NewObject(cx, &MinXmlHttpRequest::js_class, MinXmlHttpRequest::js_proto, MinXmlHttpRequest::js_parent);
if (obj) {
JS_SetPrivate(obj, req);
out = OBJECT_TO_JSVAL(obj);
}
JS_SET_RVAL(cx, vp, out);
p =jsb_new_proxy(req, obj);
JS_AddNamedObjectRoot(cx, &p->obj, "XMLHttpRequest");
return true;
}
/**
* @brief get Callback function for Javascript
*
*/
JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, onreadystatechange)
{
if (_onreadystateCallback)
{
JSString *tmpstr = JS_NewStringCopyZ(cx, "1");
JS::RootedValue tmpval(cx);
tmpval = STRING_TO_JSVAL(tmpstr);
JS_SetProperty(cx, _onreadystateCallback, "readyState", tmpval);
jsval out = OBJECT_TO_JSVAL(_onreadystateCallback);
vp.set(out);
}
else
{
vp.set(JSVAL_NULL);
}
return true;
}
/**
* @brief Set Callback function coming from Javascript
*
*
*/
JS_BINDED_PROP_SET_IMPL(MinXmlHttpRequest, onreadystatechange)
{
jsval callback = vp.get();
if (callback != JSVAL_NULL)
{
_onreadystateCallback = JSVAL_TO_OBJECT(callback);
JS_AddNamedObjectRoot(cx, &_onreadystateCallback, "onreadystateCallback");
}
return true;
}
/**
* @brief upload getter - TODO
*
* Placeholder for further implementations!!
*/
JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, upload)
{
vp.set(JSVAL_NULL);
return true;
}
/**
* @brief upload setter - TODO
*
* Placeholder for further implementations
*/
JS_BINDED_PROP_SET_IMPL(MinXmlHttpRequest, upload)
{
vp.set(JSVAL_NULL);
return true;
}
/**
* @brief timeout getter - TODO
*
* Placeholder for further implementations
*/
JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, timeout)
{
vp.set(INT_TO_JSVAL(_timeout));
return true;
}
/**
* @brief timeout setter - TODO
*
* Placeholder for further implementations
*/
JS_BINDED_PROP_SET_IMPL(MinXmlHttpRequest, timeout)
{
jsval timeout_ms = vp.get();
_timeout = JSVAL_TO_INT(timeout_ms);
//curl_easy_setopt(curlHandle, CURLOPT_CONNECTTIMEOUT_MS, timeout);
return true;
}
/**
* @brief get response type for actual XHR
*
*
*/
JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, responseType)
{
JSString* str = JS_NewStringCopyN(cx, "", 0);
vp.set(STRING_TO_JSVAL(str));
return true;
}
/**
* @brief responseXML getter - TODO
*
* Placeholder for further implementation.
*/
JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, responseXML)
{
vp.set(JSVAL_NULL);
return true;
}
/**
* @brief set response type for actual XHR
*
*
*/
JS_BINDED_PROP_SET_IMPL(MinXmlHttpRequest, responseType)
{
jsval type = vp.get();
if (type.isString()) {
JSString* str = type.toString();
bool equal;
JS_StringEqualsAscii(cx, str, "text", &equal);
if (equal)
{
_responseType = ResponseType::STRING;
return true;
}
JS_StringEqualsAscii(cx, str, "arraybuffer", &equal);
if (equal)
{
_responseType = ResponseType::ARRAY_BUFFER;
return true;
}
JS_StringEqualsAscii(cx, str, "json", &equal);
if (equal)
{
_responseType = ResponseType::JSON;
return true;
}
// ignore the rest of the response types for now
return true;
}
JS_ReportError(cx, "Invalid response type");
return false;
}
/**
* @brief get readyState for actual XHR
*
*
*/
JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, readyState)
{
vp.set(INT_TO_JSVAL(_readyState));
return true;
}
/**
* @brief get status for actual XHR
*
*
*/
JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, status)
{
vp.set(INT_TO_JSVAL(_status));
return true;
}
/**
* @brief get statusText for actual XHR
*
*
*/
JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, statusText)
{
jsval strVal = std_string_to_jsval(cx, _statusText);
if (strVal != JSVAL_NULL)
{
vp.set(strVal);
return true;
}
else
{
JS_ReportError(cx, "Error trying to create JSString from data");
return false;
}
}
/**
* @brief get value of withCredentials property.
*
*/
JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, withCredentials)
{
vp.set(BOOLEAN_TO_JSVAL(_withCredentialsValue));
return true;
}
/**
* withCredentials - set value of withCredentials property.
*
*/
JS_BINDED_PROP_SET_IMPL(MinXmlHttpRequest, withCredentials)
{
jsval credential = vp.get();
if (credential != JSVAL_NULL)
{
_withCredentialsValue = JSVAL_TO_BOOLEAN(credential);
}
return true;
}
/**
* @brief get (raw) responseText
*
*/
JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, responseText)
{
if (_data)
{
jsval strVal = std_string_to_jsval(cx, _data);
if (strVal != JSVAL_NULL)
{
vp.set(strVal);
return true;
}
}
CCLOGERROR("ResponseText was empty, probably there is a network error!");
// Return an empty string
vp.set(std_string_to_jsval(cx, ""));
return true;
}
/**
* @brief get response of latest XHR
*
*/
JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, response)
{
if (_responseType == ResponseType::STRING)
{
return _js_get_responseText(cx, id, vp);
}
else
{
if (_readyState != DONE || _errorFlag)
{
vp.set(JSVAL_NULL);
return true;
}
if (_responseType == ResponseType::JSON)
{
JS::RootedValue outVal(cx);
jsval strVal = std_string_to_jsval(cx, _data);
if (JS_ParseJSON(cx, JS_GetStringCharsZ(cx, JSVAL_TO_STRING(strVal)), _dataSize, &outVal))
{
vp.set(outVal);
return true;
}
}
else if (_responseType == ResponseType::ARRAY_BUFFER)
{
JSObject* tmp = JS_NewArrayBuffer(cx, _dataSize);
uint8_t* tmpData = JS_GetArrayBufferData(tmp);
memcpy((void*)tmpData, (const void*)_data, _dataSize);
jsval outVal = OBJECT_TO_JSVAL(tmp);
vp.set(outVal);
return true;
}
// by default, return text
return _js_get_responseText(cx, id, vp);
}
}
/**
* @brief initialize new xhr.
*
*/
JS_BINDED_FUNC_IMPL(MinXmlHttpRequest, open)
{
if (argc >= 2)
{
jsval* argv = JS_ARGV(cx, vp);
const char* method;
const char* urlstr;
bool async = true;
JSString* jsMethod = JS::ToString( cx, JS::RootedValue(cx, argv[0]) );
JSString* jsURL = JS::ToString( cx, JS::RootedValue(cx, argv[1]) );
if (argc > 2) {
async = JS::ToBoolean( JS::RootedValue(cx, argv[2]) );
}
JSStringWrapper w1(jsMethod);
JSStringWrapper w2(jsURL);
method = w1.get();
urlstr = w2.get();
_url = urlstr;
_meth = method;
_readyState = 1;
_isAsync = async;
if (_url.length() > 5 && _url.compare(_url.length() - 5, 5, ".json") == 0)
{
_responseType = ResponseType::JSON;
}
{
auto requestType =
(_meth.compare("get") == 0 || _meth.compare("GET") == 0) ? cocos2d::network::HttpRequest::Type::GET : (
(_meth.compare("post") == 0 || _meth.compare("POST") == 0) ? cocos2d::network::HttpRequest::Type::POST : (
(_meth.compare("put") == 0 || _meth.compare("PUT") == 0) ? cocos2d::network::HttpRequest::Type::PUT : (
(_meth.compare("delete") == 0 || _meth.compare("DELETE") == 0) ? cocos2d::network::HttpRequest::Type::DELETE : (
cocos2d::network::HttpRequest::Type::UNKNOWN))));
_httpRequest->setRequestType(requestType);
_httpRequest->setUrl(_url.c_str());
}
_isNetwork = true;
_readyState = OPENED;
_status = 0;
return true;
}
JS_ReportError(cx, "invalid call: %s", __FUNCTION__);
return false;
}
/**
* @brief send xhr
*
*/
JS_BINDED_FUNC_IMPL(MinXmlHttpRequest, send)
{
JSString *str = NULL;
std::string data;
// Clean up header map. New request, new headers!
_httpHeader.clear();
_errorFlag = false;
if (argc == 1)
{
if (!JS_ConvertArguments(cx, argc, JS_ARGV(cx, vp), "S", &str))
{
return false;
}
JSStringWrapper strWrap(str);
data = strWrap.get();
}
if (data.length() > 0 &&
(_meth.compare("post") == 0 || _meth.compare("POST") == 0 ||
_meth.compare("put") == 0 || _meth.compare("PUT") == 0))
{
_httpRequest->setRequestData(data.c_str(), static_cast<unsigned int>(data.length()));
}
_setHttpRequestHeader();
_sendRequest(cx);
return true;
}
/**
* @brief abort function Placeholder!
*
*/
JS_BINDED_FUNC_IMPL(MinXmlHttpRequest, abort)
{
return true;
}
/**
* @brief Get all response headers as a string
*
*/
JS_BINDED_FUNC_IMPL(MinXmlHttpRequest, getAllResponseHeaders)
{
stringstream responseheaders;
string responseheader;
for (auto it = _httpHeader.begin(); it != _httpHeader.end(); ++it)
{
responseheaders << it->first << ": " << it->second << "\n";
}
responseheader = responseheaders.str();
jsval strVal = std_string_to_jsval(cx, responseheader);
if (strVal != JSVAL_NULL)
{
JS_SET_RVAL(cx, vp, strVal);
return true;
}
else
{
JS_ReportError(cx, "Error trying to create JSString from data");
return false;
}
return true;
}
/**
* @brief Get all response headers as a string
*
*/
JS_BINDED_FUNC_IMPL(MinXmlHttpRequest, getResponseHeader)
{
JSString *header_value;
if (!JS_ConvertArguments(cx, argc, JS_ARGV(cx, vp), "S", &header_value)) {
return false;
};
std::string data;
JSStringWrapper strWrap(header_value);
data = strWrap.get();
stringstream streamdata;
streamdata << data;
string value = streamdata.str();
auto iter = _httpHeader.find(value);
if (iter != _httpHeader.end())
{
jsval js_ret_val = std_string_to_jsval(cx, iter->second);
JS_SET_RVAL(cx, vp, js_ret_val);
return true;
}
else {
JS_SET_RVAL(cx, vp, JSVAL_NULL);
return true;
}
}
/**
* @brief Set the given Fields to request Header.
*
*
*/
JS_BINDED_FUNC_IMPL(MinXmlHttpRequest, setRequestHeader)
{
if (argc >= 2)
{
jsval* argv = JS_ARGV(cx, vp);
const char* field;
const char* value;
JSString* jsField = JS::ToString( cx, JS::RootedValue(cx, argv[0]) );
JSString* jsValue = JS::ToString( cx, JS::RootedValue(cx, argv[1]) );
JSStringWrapper w1(jsField);
JSStringWrapper w2(jsValue);
field = w1.get();
value = w2.get();
// Populate the request_header map.
_setRequestHeader(field, value);
return true;
}
return false;
}
/**
* @brief overrideMimeType function - TODO!
*
* Just a placeholder for further implementations.
*/
JS_BINDED_FUNC_IMPL(MinXmlHttpRequest, overrideMimeType)
{
return true;
}
/**
* @brief destructor for Javascript
*
*/
static void basic_object_finalize(JSFreeOp *freeOp, JSObject *obj)
{
CCLOG("basic_object_finalize %p ...", obj);
}
/**
* @brief Register XMLHttpRequest to be usable in JS and add properties and Mehtods.
* @param cx Global Spidermonkey JS Context.
* @param global Global Spidermonkey Javascript object.
*/
void MinXmlHttpRequest::_js_register(JSContext *cx, JSObject *global)
{
JSClass jsclass = {
"XMLHttpRequest", JSCLASS_HAS_PRIVATE, JS_PropertyStub,
JS_DeletePropertyStub, JS_PropertyStub, JS_StrictPropertyStub,
JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub,
basic_object_finalize, JSCLASS_NO_OPTIONAL_MEMBERS
};
MinXmlHttpRequest::js_class = jsclass;
static JSPropertySpec props[] = {
JS_BINDED_PROP_DEF_ACCESSOR(MinXmlHttpRequest, onreadystatechange),
JS_BINDED_PROP_DEF_ACCESSOR(MinXmlHttpRequest, responseType),
JS_BINDED_PROP_DEF_ACCESSOR(MinXmlHttpRequest, withCredentials),
JS_BINDED_PROP_DEF_GETTER(MinXmlHttpRequest, readyState),
JS_BINDED_PROP_DEF_GETTER(MinXmlHttpRequest, status),
JS_BINDED_PROP_DEF_GETTER(MinXmlHttpRequest, statusText),
JS_BINDED_PROP_DEF_GETTER(MinXmlHttpRequest, responseText),
JS_BINDED_PROP_DEF_GETTER(MinXmlHttpRequest, responseXML),
JS_BINDED_PROP_DEF_GETTER(MinXmlHttpRequest, response),
{0, 0, 0, 0, 0}
};
static JSFunctionSpec funcs[] = {
JS_BINDED_FUNC_FOR_DEF(MinXmlHttpRequest, open),
JS_BINDED_FUNC_FOR_DEF(MinXmlHttpRequest, abort),
JS_BINDED_FUNC_FOR_DEF(MinXmlHttpRequest, send),
JS_BINDED_FUNC_FOR_DEF(MinXmlHttpRequest, setRequestHeader),
JS_BINDED_FUNC_FOR_DEF(MinXmlHttpRequest, getAllResponseHeaders),
JS_BINDED_FUNC_FOR_DEF(MinXmlHttpRequest, getResponseHeader),
JS_BINDED_FUNC_FOR_DEF(MinXmlHttpRequest, overrideMimeType),
JS_FS_END
};
MinXmlHttpRequest::js_parent = NULL;
MinXmlHttpRequest::js_proto = JS_InitClass(cx, global, NULL, &MinXmlHttpRequest::js_class , MinXmlHttpRequest::_js_constructor, 0, props, funcs, NULL, NULL);
}
| csyeung/Othello | frameworks/js-bindings/bindings/manual/network/XMLHTTPRequest.cpp | C++ | gpl-2.0 | 22,203 |
*{
margin:0;
padding:0;
font-family: "Open Sans",sans-serif;
}
html,body{
width: 100%;
height: 100%;
overflow: hidden;
}
#start_page{
width: 100%;
height: 100%;
background: #fafafa;
padding: 10px;
}
header{
height: 20px;
padding: 10px;
background: #fafafa;
text-align: center;
line-height: 20px;
font-weight: bolder;
border-bottom:1px solid #ccc;
border-top:3px solid #48b;
}
#h_page{
width: 100%;
height: calc(100% - 41px);
padding-top: 10px;
background: #fff;
}
#h_page ul{
list-style: none;
}
#h_page ul li{
margin:10px;
display: inline-block;
width: 80px;
height: 80px;
border: 1px solid #bbb;
}
#h_page ul li img{
width: 100%;
height: 100%;
}
#box{
width: calc(95% - 25px);
height: calc(95% - 25px);
padding: 10px;
border-radius: 3px;
background: #fff;
border: 1px solid #999;
text-align: justify;
overflow: hidden;
}
#box p{
position: relative;
left: -10px;
top:-10px;
width: calc(100% + 20px);
background: #999;
color: #fff;
padding: 10px;
}
#box ul li{
margin-left: 20px;
}
#box button{
outline: none;
border-radius: 0;
margin: 10px;
}
.option{
background: #efefef;
border:1px solid #ddd;
padding: 5px;
}
.option:active{
background: #49b;
color: #fff;
border: 1px solid #38a;
} | Nishan13/ffOS_browser | system/style/startpage.css | CSS | gpl-2.0 | 1,240 |
#include <linux/fs.h>
#include <linux/init.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include "devices.h"
static int c_show(struct seq_file *m, void *v)
{
seq_printf(m, "%d\n", engineer_id);
return 0;
}
static void *c_start(struct seq_file *m, loff_t *pos)
{
return *pos < 1 ? (void *)1 : NULL;
}
static void *c_next(struct seq_file *m, void *v, loff_t *pos)
{
++*pos;
return NULL;
}
static void c_stop(struct seq_file *m, void *v)
{
}
const struct seq_operations engineerid_op = {
.start = c_start,
.next = c_next,
.stop = c_stop,
.show = c_show
};
extern const struct seq_operations engineerid_op;
static int engineerid_open(struct inode *inode, struct file *file)
{
return seq_open(file, &engineerid_op);
}
static const struct file_operations proc_engineerid_operations = {
.open = engineerid_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release,
};
static int __init proc_engineerid_init(void)
{
proc_create("engineerid", 0, NULL, &proc_engineerid_operations);
return 0;
}
module_init(proc_engineerid_init);
| Chad0989/recovery-kernel | arch/arm/mach-msm/proc_engineerid.c | C | gpl-2.0 | 1,072 |
using UnityEngine;
public class LaserBullet : MonoBehaviour
{
float Range = 20;
float Speed = 10;
void Update () {
float deltaY = Speed * Time.deltaTime;
this.transform.Translate (0, deltaY, 0);
if (this.transform.position.y > Range) Destroy (this.gameObject);
}
}
| GreagDeay/unity3d-jenkins | HumbleObjectPatternExample/Assets/Scripts/LaserBullet.cs | C# | gpl-2.0 | 282 |
package de.jlab.android.hombot.utils;
import android.content.Context;
import android.database.Cursor;
import android.support.annotation.ArrayRes;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
/**
* Created by frede_000 on 19.12.2015.
*/
public class ColorableArrayAdapter<T> extends ArrayAdapter<T> {
private Colorizer colorizer;
private int referenceColor;
private int mFieldId = 0;
public static ColorableArrayAdapter<CharSequence> createFromResource(Context context,
@ArrayRes int textArrayResId, @LayoutRes int textViewResId, Colorizer colorizer, int referenceColor) {
CharSequence[] strings = context.getResources().getTextArray(textArrayResId);
ColorableArrayAdapter ad = new ColorableArrayAdapter<>(context, textViewResId, strings, colorizer, referenceColor);
return ad;
}
public ColorableArrayAdapter(Context context, @LayoutRes int resource, @NonNull T[] objects, Colorizer colorizer, int referenceColor) {
super(context, resource, objects);
mFieldId = resource;
this.referenceColor = referenceColor;
this.colorizer = colorizer;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
((TextView)view).setTextColor(this.colorizer.getContrastingTextColor(this.referenceColor));
return view;
}
}
| rampage128/hombot-control | mobile/src/main/java/de/jlab/android/hombot/utils/ColorableArrayAdapter.java | Java | gpl-2.0 | 1,688 |
from polybori import BooleSet, interpolate_smallest_lex
class PartialFunction(object):
"""docstring for PartialFunction"""
def __init__(self, zeros, ones):
super(PartialFunction, self).__init__()
self.zeros = zeros.set()
self.ones = ones.set()
def interpolate_smallest_lex(self):
return interpolate_smallest_lex(self.zeros, self.ones)
def __str__(self):
return "PartialFunction(zeros=" + str(self.zeros) + ", ones=" + str(
self.ones) + ")"
def definedOn(self):
return self.zeros.union(self.ones)
def __add__(self, other):
domain = self.definedOn().intersect(other.definedOn())
zeros = self.zeros.intersect(other.zeros).union(self.ones.intersect(
other.ones))
ones = self.zeros.intersect(other.ones).union(self.ones.intersect(
other.zeros))
assert zeros.diff(domain).empty()
assert ones.diff(domain).empty()
return PartialFunction(zeros, ones)
def __repr__(self):
return str(self)
def __mul__(self, other):
zeros = self.zeros.union(other.zeros)
ones = self.ones.intersect(other.ones)
return PartialFunction(zeros, ones)
def __or__(self, other):
zeros = self.zeros.intersect(other.zeros)
ones = self.ones.union(other.ones)
return PartialFunction(zeros, ones)
def __xor__(self, other):
return self + other
def __and__(self, other):
return self * other
| ohanar/PolyBoRi | pyroot/polybori/partial.py | Python | gpl-2.0 | 1,509 |
/* Copyright 2000 Kjetil S. Matheussen
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 "nsmtracker.h"
#include "disk.h"
#include "disk_song_proc.h"
#include "sequencer_timing_proc.h"
#include "disk_root_proc.h"
extern struct Root *root;
void SaveRoot(struct Root *theroot){
DC_start("ROOT");
// DC_SSN("def_instrument",theroot->def_instrument->l.num);
DC_SSN("curr_block",0); //ATOMIC_GET(theroot->curr_blocknum));
DC_SSI("tempo",theroot->tempo);
DC_SSI("lpb",theroot->lpb);
DC_SSL("signature_numerator",theroot->signature.numerator);
DC_SSL("signature_denominator",theroot->signature.denominator);
DC_SSL("quantitize_numerator",theroot->quantitize_options.quant.numerator);
DC_SSL("quantitize_denominator",theroot->quantitize_options.quant.denominator);
DC_SSF("quantitize",(double)theroot->quantitize_options.quant.numerator / (double)theroot->quantitize_options.quant.denominator);
DC_SSL("grid_numerator",theroot->grid_numerator);
DC_SSL("grid_denominator",theroot->grid_denominator);
DC_SSI("keyoct",theroot->keyoct); // not used anymore. Still saved though so that new songs can be opened in older radiums.
DC_SSI("min_standardvel",theroot->min_standardvel);
DC_SSI("standardvel",theroot->standardvel);
SaveSong(theroot->song);
DC_end();
}
/*********** Start Load song *************************/
struct Root *LoadRoot(void){
const char *objs[1]={
"SONG"
};
const char *vars[14]={
"def_instrument",
"curr_block",
"tempo",
"lpb",
"signature_numerator",
"signature_denominator",
"quantitize",
"quantitize_numerator",
"quantitize_denominator",
"grid_numerator",
"grid_denominator",
"keyoct",
"min_standardvel",
"standardvel"
};
struct Root *ret=DC_alloc(sizeof(struct Root));
ret->keyoct = root->keyoct;
ret->quantitize_options = root->quantitize_options;
ret->min_standardvel=MAX_VELOCITY*40/100;
ATOMIC_SET(ret->editonoff, true);
ret->grid_numerator=1;
ret->grid_denominator=1;
ret->signature.numerator=4;
ret->signature.denominator=4;
ret->tempo = 128;
SEQUENCER_TIMING_init(ret->tempo, ret->signature);
ATOMIC_SET(ret->play_cursor_onoff, ATOMIC_GET(root->play_cursor_onoff));
ATOMIC_SET(ret->editor_follows_play_cursor_onoff, ATOMIC_GET(root->editor_follows_play_cursor_onoff));
bool has_nominator=false;
bool has_denominator=false;
GENERAL_LOAD(1,14);
obj0:
ret->song=LoadSong();
goto start;
var0:
goto start; // Don't bother with instruments yet.
var1:
DC_LoadN(); // not used anymore
//ATOMIC_SET(ret->curr_blocknum, DC_LoadN());
goto start;
var2:
ret->tempo=DC_LoadI();
SEQUENCER_TIMING_init(ret->tempo, ret->signature);
goto start;
var3:
ret->lpb=DC_LoadI();
goto start;
var4:
ret->signature.numerator=DC_LoadI();
goto start;
var5:
ret->signature.denominator=DC_LoadI();
goto start;
var6:
DC_LoadF();
goto start;
var7:
ret->quantitize_options.quant.numerator = DC_LoadI();
goto start;
var8:
ret->quantitize_options.quant.denominator = DC_LoadI();
goto start;
var9:
ret->grid_numerator=DC_LoadI();
has_nominator=true;
if(has_denominator)
SEQUENCER_TIMING_init(ret->tempo, ret->signature);
goto start;
var10:
ret->grid_denominator=DC_LoadI();
has_denominator=true;
if(has_nominator)
SEQUENCER_TIMING_init(ret->tempo, ret->signature);
goto start;
var11:
DC_LoadI();
//ret->keyoct=DC_LoadI();
goto start;
var12:
ret->min_standardvel=DC_LoadI();
goto start;
var13:
ret->standardvel=DC_LoadI();
goto start;
var14:
var15:
var16:
var17:
var18:
var19:
var20:
var21:
obj1:
obj2:
obj3:
obj4:
obj5:
obj6:
debug("loadroot, very wrong\n");
error:
debug("loadroot, goto error\n");
end:
return ret;
}
extern struct Root *root;
void DLoadRoot(struct Root *theroot){
DLoadSong(theroot,theroot->song);
}
/*********************** End Load Song **************************/
| kmatheussen/radium | common/disk_root.c | C | gpl-2.0 | 4,847 |
/* tpg.h
* Definitions of helper functions for TPG
*
* (c) 2005, Luis E. Garcia Ontanon <luis@ontanon.org>
*
* $Id: tpg.h 43536 2012-06-28 22:56:06Z darkjames $
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <gerald@wireshark.org>
* Copyright 1998 Gerald Combs
*
* 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.
*/
#ifndef _TPG_H_
#define _TPG_H_
#include <glib.h>
#include <epan/packet.h>
#include <epan/proto.h>
#include <epan/tvbuff.h>
#include <epan/tvbparse.h>
#include <epan/emem.h>
typedef struct _tpg_parser_data_t {
ep_stack_t stack;
tvbparse_t* tt;
void* private_data;
} tpg_parser_data_t;
extern tpg_parser_data_t* tpg_start(proto_tree* root_tree,
tvbuff_t* tvb,
int offset,
int len,
tvbparse_wanted_t* ignore,
void* private_data);
#define TPG_START(tree,tvb,offset,len,data) tpg_start((tree),(tvb),(offset),(len),(data))
#define TPG_GET(tpg, wanted) tvbparse_get((tpg)->tt,(wanted))
#define TPG_FIND(tpg, wanted) tvbparse_find((tpg)->tt,(wanted))
#define TPG_TREE(vp) (((tpg_parser_data_t*)(vp))->tree)
#define TPG_DATA(vp,type) (((type*)(((tpg_parser_data_t*)(vp))->private_data)))
#define TPG_STRING(i) tvb_get_ephemeral_string((i)->tvb,(i)->offset,(i)->len)
#define TPG_INT(i) strtol(tvb_get_ephemeral_string((i)->tvb,(i)->offset,(i)->len),NULL,10)
#define TPG_UINT(i) strtoul(tvb_get_ephemeral_string((i)->tvb,(i)->offset,(i)->len),NULL,10)
#define TPG_UINT_HEX(i) strtoul(tvb_get_ephemeral_string((i)->tvb,(i)->offset,(i)->len),NULL,16)
#define TPG_TVB(i) tvb_new_subset((i)->tvb,(i)->offset,(i)->len,(i)->len)
extern guint32 tpg_ipv4(tvbparse_elem_t*);
#define TPG_IPV4(i) tpg_ipv4((i))
extern guint8* tpg_ipv6(tvbparse_elem_t*);
#define TPG_IPV6(i) tpg_ipv6((i))
#define TPG_PUSH(tpg,pi,ett) ep_stack_push(((tpg_parser_data_t*)(tpg))->stack,proto_item_add_subtree((pi),(ett)))
#define TPG_POP(tpg) ep_stack_pop(((tpg_parser_data_t*)(tpg))->stack) ;
#define TPG_ADD_STRING(tpg, hfid, elem) proto_tree_add_item(ep_stack_peek(((tpg_parser_data_t*)tpg)->stack), hfid, (elem)->tvb, (elem)->offset, (elem)->len, FALSE)
#define TPG_ADD_BOOLEAN(tpg, hfid, elem) proto_tree_add_boolean(ep_stack_peek(((tpg_parser_data_t*)tpg)->stack), hfid, (elem)->tvb, (elem)->offset, (elem)->len, TRUE)
#define TPG_ADD_INT(tpg, hfid, elem, value) proto_tree_add_int(ep_stack_peek(((tpg_parser_data_t*)tpg)->stack), hfid, (elem)->tvb, (elem)->offset, (elem)->len, value)
#define TPG_ADD_UINT(tpg, hfid, elem, value) proto_tree_add_uint(ep_stack_peek(((tpg_parser_data_t*)tpg)->stack), hfid, (elem)->tvb, (elem)->offset, (elem)->len, value)
#define TPG_ADD_IPV4(tpg, hfid, elem, value) proto_tree_add_ipv4(ep_stack_peek(((tpg_parser_data_t*)tpg)->stack), hfid, (elem)->tvb, (elem)->offset, (elem)->len, value)
#define TPG_ADD_IPV6(tpg, hfid, elem, value) proto_tree_add_ipv6(ep_stack_peek(((tpg_parser_data_t*)tpg)->stack), hfid, (elem)->tvb, (elem)->offset, (elem)->len, value)
#define TPG_ADD_TEXT(tpg, elem) proto_tree_add_text(ep_stack_peek(((tpg_parser_data_t*)tpg)->stack), (elem)->tvb, (elem)->offset, (elem)->len, \
"%s",tvb_format_text((elem)->tvb, (elem)->offset, (elem)->len))
#define TPG_SET_TEXT(pi, elem) proto_item_set_text((pi), "%s",tvb_format_text((elem)->tvb, (elem)->offset, (elem)->len))
#endif /* _TPG_H_ */
| MavEtJu/wireshark-lean | epan/tpg.h | C | gpl-2.0 | 4,193 |
/*
*
* Copyright (C) 2010 Google, Inc.
*
* Author:
* Colin Cross <ccross@google.com>
*
* Copyright (C) 2010-2011 NVIDIA Corporation.
*
* 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.
*
*/
#ifndef _TEGRA_DVFS_H_
#define _TEGRA_DVFS_H_
#define MAX_DVFS_FREQS 18
#define DVFS_RAIL_STATS_TOP_BIN 40
struct clk;
struct dvfs_rail;
/*
* dvfs_relationship between to rails, "from" and "to"
* when the rail changes, it will call dvfs_rail_update on the rails
* in the relationship_to list.
* when determining the voltage to set a rail to, it will consider each
* rail in the relationship_from list.
*/
struct dvfs_relationship {
struct dvfs_rail *to;
struct dvfs_rail *from;
int (*solve)(struct dvfs_rail *, struct dvfs_rail *);
struct list_head to_node; /* node in relationship_to list */
struct list_head from_node; /* node in relationship_from list */
bool solved_at_nominal;
};
struct rail_stats {
ktime_t time_at_mv[DVFS_RAIL_STATS_TOP_BIN + 1];
ktime_t last_update;
int last_index;
bool off;
};
struct dvfs_rail {
const char *reg_id;
int min_millivolts;
int max_millivolts;
int nominal_millivolts;
int step;
bool jmp_to_zero;
bool disabled;
bool updating;
bool resolving_to;
struct list_head node; /* node in dvfs_rail_list */
struct list_head dvfs; /* list head of attached dvfs clocks */
struct list_head relationships_to;
struct list_head relationships_from;
struct regulator *reg;
int millivolts;
int new_millivolts;
bool suspended;
struct rail_stats stats;
};
struct dvfs {
/* Used only by tegra2_clock.c */
const char *clk_name;
int speedo_id;
int process_id;
/* Must be initialized before tegra_dvfs_init */
int freqs_mult;
unsigned long freqs[MAX_DVFS_FREQS];
unsigned long *alt_freqs;
const int *millivolts;
struct dvfs_rail *dvfs_rail;
bool auto_dvfs;
/* Filled in by tegra_dvfs_init */
int max_millivolts;
int num_freqs;
int cur_millivolts;
unsigned long cur_rate;
struct list_head node;
struct list_head debug_node;
struct list_head reg_node;
};
extern struct dvfs_rail *tegra_cpu_rail;
#ifdef CONFIG_TEGRA_SILICON_PLATFORM
void tegra_soc_init_dvfs(void);
int tegra_enable_dvfs_on_clk(struct clk *c, struct dvfs *d);
int dvfs_debugfs_init(struct dentry *clk_debugfs_root);
int tegra_dvfs_late_init(void);
int tegra_dvfs_init_rails(struct dvfs_rail *dvfs_rails[], int n);
void tegra_dvfs_add_relationships(struct dvfs_relationship *rels, int n);
void tegra_dvfs_rail_enable(struct dvfs_rail *rail);
void tegra_dvfs_rail_disable(struct dvfs_rail *rail);
bool tegra_dvfs_rail_updating(struct clk *clk);
void tegra_dvfs_rail_off(struct dvfs_rail *rail, ktime_t now);
void tegra_dvfs_rail_on(struct dvfs_rail *rail, ktime_t now);
void tegra_dvfs_rail_pause(struct dvfs_rail *rail, ktime_t delta, bool on);
struct dvfs_rail *tegra_dvfs_get_rail_by_name(const char *reg_id);
int tegra_dvfs_predict_millivolts(struct clk *c, unsigned long rate);
void tegra_dvfs_core_cap_enable(bool enable);
void tegra_dvfs_core_cap_level_set(int level);
int tegra_dvfs_alt_freqs_set(struct dvfs *d, unsigned long *alt_freqs);
void tegra_cpu_dvfs_alter(
int edp_thermal_index, const cpumask_t *cpus, bool before_clk_update);
#else
static inline void tegra_soc_init_dvfs(void)
{}
static inline int tegra_enable_dvfs_on_clk(struct clk *c, struct dvfs *d)
{ return 0; }
static inline int dvfs_debugfs_init(struct dentry *clk_debugfs_root)
{ return 0; }
static inline int tegra_dvfs_late_init(void)
{ return 0; }
static inline int tegra_dvfs_init_rails(struct dvfs_rail *dvfs_rails[], int n)
{ return 0; }
static inline void tegra_dvfs_add_relationships(struct dvfs_relationship *rels, int n)
{}
static inline void tegra_dvfs_rail_enable(struct dvfs_rail *rail)
{}
static inline void tegra_dvfs_rail_disable(struct dvfs_rail *rail)
{}
static inline bool tegra_dvfs_rail_updating(struct clk *clk)
{ return false; }
static inline void tegra_dvfs_rail_off(struct dvfs_rail *rail, ktime_t now)
{}
static inline void tegra_dvfs_rail_on(struct dvfs_rail *rail, ktime_t now)
{}
static inline void tegra_dvfs_rail_pause(
struct dvfs_rail *rail, ktime_t delta, bool on)
{}
static inline struct dvfs_rail *tegra_dvfs_get_rail_by_name(const char *reg_id)
{ return NULL; }
static inline int tegra_dvfs_predict_millivolts(struct clk *c, unsigned long rate)
{ return 0; }
static inline void tegra_dvfs_core_cap_enable(bool enable)
{}
static inline void tegra_dvfs_core_cap_level_set(int level)
{}
static inline int tegra_dvfs_alt_freqs_set(struct dvfs *d,
unsigned long *alt_freqs)
{ return 0; }
static inline void tegra_cpu_dvfs_alter(
int edp_thermal_index, const cpumask_t *cpus, bool before_clk_update)
{}
#endif
#ifndef CONFIG_ARCH_TEGRA_2x_SOC
int tegra_dvfs_rail_disable_prepare(struct dvfs_rail *rail);
int tegra_dvfs_rail_post_enable(struct dvfs_rail *rail);
#else
static inline int tegra_dvfs_rail_disable_prepare(struct dvfs_rail *rail)
{ return 0; }
static inline int tegra_dvfs_rail_post_enable(struct dvfs_rail *rail)
{ return 0; }
#endif
#endif
| OptiPop/kernel_asus_grouper | arch/arm/mach-tegra/dvfs.h | C | gpl-2.0 | 5,426 |
import getRawSite from 'calypso/state/selectors/get-raw-site';
import isAtomicSite from 'calypso/state/selectors/is-site-automated-transfer';
import { AppState } from 'calypso/types';
type Site = {
options?: {
jetpack_connection_active_plugins?: string[];
};
};
/**
* Returns true if site is a Jetpack site with a standalone product plugin installed ( i.e. Jetpack
* Backup ), false if the site has the full Jetpack plugin or is hosted on WordPress.com, or null
* if the site is unknown.
*
* @param {AppState} state Global state tree
* @param {number} siteId Site ID
* @returns {boolean|null} Whether site is a Jetpack site with a standalone product plugin
*/
export default function isJetpackProductSite( state: AppState, siteId: number ): boolean | null {
const site = getRawSite( state, siteId ) as Site;
if ( ! site ) {
return null;
}
if ( isAtomicSite( state, siteId ) ) {
return false;
}
return (
( site.options?.jetpack_connection_active_plugins || [] ).filter(
( plugin ) => plugin !== 'jetpack'
).length > 0
);
}
| Automattic/wp-calypso | client/state/sites/selectors/is-jetpack-product-site.ts | TypeScript | gpl-2.0 | 1,057 |
/* $Id$ */
/** @file
* IPRT - Utility for translating addresses into symbols+offset.
*/
/*
* Copyright (C) 2006-2012 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.
*
* The contents of this file may alternatively be used under the terms
* of the Common Development and Distribution License Version 1.0
* (CDDL) only, as it comes in the "COPYING.CDDL" file of the
* VirtualBox OSE distribution, in which case the provisions of the
* CDDL are applicable instead of those of the GPL.
*
* You may elect to license modified versions of this file under the
* terms and conditions of either the GPL or the CDDL or both.
*/
/*******************************************************************************
* Header Files *
*******************************************************************************/
#include <iprt/mem.h>
#include <iprt/assert.h>
#include <iprt/ctype.h>
#include <iprt/dbg.h>
#include <iprt/err.h>
#include <iprt/getopt.h>
#include <iprt/initterm.h>
#include <iprt/message.h>
#include <iprt/path.h>
#include <iprt/stream.h>
#include <iprt/string.h>
/**
* Tries to parse out an address at the head of the string.
*
* @returns true if found address, false if not.
* @param psz Where to start parsing.
* @param pcchAddress Where to store the address length.
* @param pu64Address Where to store the address value.
*/
static bool TryParseAddress(const char *psz, size_t *pcchAddress, uint64_t *pu64Address)
{
const char *pszStart = psz;
/*
* Hex prefix?
*/
if (psz[0] == '0' && (psz[1] == 'x' || psz[1] == 'X'))
psz += 2;
/*
* How many hex digits? We want at least 4 and at most 16.
*/
size_t off = 0;
while (RT_C_IS_XDIGIT(psz[off]))
off++;
if (off < 4 || off > 16)
return false;
/*
* Check for separator (xxxxxxxx'yyyyyyyy).
*/
bool fHave64bitSep = off <= 8
&& psz[off] == '\''
&& RT_C_IS_XDIGIT(psz[off + 1])
&& RT_C_IS_XDIGIT(psz[off + 2])
&& RT_C_IS_XDIGIT(psz[off + 3])
&& RT_C_IS_XDIGIT(psz[off + 4])
&& RT_C_IS_XDIGIT(psz[off + 5])
&& RT_C_IS_XDIGIT(psz[off + 6])
&& RT_C_IS_XDIGIT(psz[off + 7])
&& RT_C_IS_XDIGIT(psz[off + 8])
&& !RT_C_IS_XDIGIT(psz[off + 9]);
if (fHave64bitSep)
{
uint32_t u32High;
int rc = RTStrToUInt32Ex(psz, NULL, 16, &u32High);
if (rc != VWRN_TRAILING_CHARS)
return false;
uint32_t u32Low;
rc = RTStrToUInt32Ex(&psz[off + 1], NULL, 16, &u32Low);
if ( rc != VINF_SUCCESS
&& rc != VWRN_TRAILING_SPACES
&& rc != VWRN_TRAILING_CHARS)
return false;
*pu64Address = RT_MAKE_U64(u32Low, u32High);
off += 1 + 8;
}
else
{
int rc = RTStrToUInt64Ex(psz, NULL, 16, pu64Address);
if ( rc != VINF_SUCCESS
&& rc != VWRN_TRAILING_SPACES
&& rc != VWRN_TRAILING_CHARS)
return false;
}
*pcchAddress = psz + off - pszStart;
return true;
}
int main(int argc, char **argv)
{
int rc = RTR3InitExe(argc, &argv, 0);
if (RT_FAILURE(rc))
return RTMsgInitFailure(rc);
/*
* Create an empty address space that we can load modules and stuff into
* as we parse the parameters.
*/
RTDBGAS hDbgAs;
rc = RTDbgAsCreate(&hDbgAs, 0, RTUINTPTR_MAX, "");
if (RT_FAILURE(rc))
return RTMsgErrorExit(RTEXITCODE_FAILURE, "RTDBgAsCreate -> %Rrc", rc);
/*
* Parse arguments.
*/
static const RTGETOPTDEF s_aOptions[] =
{
{ "--input", 'i', RTGETOPT_REQ_STRING },
{ "--verbose", 'v', RTGETOPT_REQ_NOTHING },
};
PRTSTREAM pInput = g_pStdIn;
PRTSTREAM pOutput = g_pStdOut;
unsigned cVerbosityLevel = 0;
RTGETOPTUNION ValueUnion;
RTGETOPTSTATE GetState;
RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, 0);
while ((rc = RTGetOpt(&GetState, &ValueUnion)))
{
switch (rc)
{
case 'i':
rc = RTStrmOpen(ValueUnion.psz, "r", &pInput);
if (RT_FAILURE(rc))
return RTMsgErrorExit(RTEXITCODE_FAILURE, "Failed to open '%s' for reading: %Rrc", ValueUnion.psz, rc);
break;
case 'v':
cVerbosityLevel++;
break;
case 'h':
RTPrintf("Usage: %s [options] <module> <address> [<module> <address> [..]]\n"
"\n"
"Options:\n"
" -i,--input=file\n"
" Specify a input file instead of standard input.\n"
" -v, --verbose\n"
" Display the address space before doing the filtering.\n"
" -h, -?, --help\n"
" Display this help text and exit successfully.\n"
" -V, --version\n"
" Display the revision and exit successfully.\n"
, RTPathFilename(argv[0]));
return RTEXITCODE_SUCCESS;
case 'V':
RTPrintf("$Revision$\n");
return RTEXITCODE_SUCCESS;
case VINF_GETOPT_NOT_OPTION:
{
/* <module> <address> */
const char *pszModule = ValueUnion.psz;
rc = RTGetOptFetchValue(&GetState, &ValueUnion, RTGETOPT_REQ_UINT64 | RTGETOPT_FLAG_HEX);
if (RT_FAILURE(rc))
return RTGetOptPrintError(rc, &ValueUnion);
uint64_t u64Address = ValueUnion.u64;
RTDBGMOD hMod;
rc = RTDbgModCreateFromImage(&hMod, pszModule, NULL, 0 /*fFlags*/);
if (RT_FAILURE(rc))
return RTMsgErrorExit(RTEXITCODE_FAILURE, "RTDbgModCreateFromImage(,%s,,) -> %Rrc", pszModule, rc);
rc = RTDbgAsModuleLink(hDbgAs, hMod, u64Address, 0 /* fFlags */);
if (RT_FAILURE(rc))
return RTMsgErrorExit(RTEXITCODE_FAILURE, "RTDbgAsModuleLink(,%s,%llx,) -> %Rrc", pszModule, u64Address, rc);
break;
}
default:
return RTGetOptPrintError(rc, &ValueUnion);
}
}
/*
* Display the address space.
*/
if (cVerbosityLevel)
{
RTPrintf("*** Address Space Dump ***\n");
uint32_t cModules = RTDbgAsModuleCount(hDbgAs);
for (uint32_t iModule = 0; iModule < cModules; iModule++)
{
RTDBGMOD hDbgMod = RTDbgAsModuleByIndex(hDbgAs, iModule);
RTPrintf("Module #%u: %s\n", iModule, RTDbgModName(hDbgMod));
RTDBGASMAPINFO aMappings[128];
uint32_t cMappings = RT_ELEMENTS(aMappings);
rc = RTDbgAsModuleQueryMapByIndex(hDbgAs, iModule, &aMappings[0], &cMappings, 0 /*fFlags*/);
if (RT_SUCCESS(rc))
{
for (uint32_t iMapping = 0; iMapping < cMappings; iMapping++)
{
if (aMappings[iMapping].iSeg == NIL_RTDBGSEGIDX)
RTPrintf(" mapping #%u: %RTptr-%RTptr\n",
iMapping,
aMappings[iMapping].Address,
aMappings[iMapping].Address + RTDbgModImageSize(hDbgMod) - 1);
else
{
RTDBGSEGMENT SegInfo;
rc = RTDbgModSegmentByIndex(hDbgMod, aMappings[iMapping].iSeg, &SegInfo);
if (RT_SUCCESS(rc))
RTPrintf(" mapping #%u: %RTptr-%RTptr (segment #%u - '%s')",
iMapping,
aMappings[iMapping].Address,
aMappings[iMapping].Address + SegInfo.cb,
SegInfo.iSeg, SegInfo.szName);
else
RTPrintf(" mapping #%u: %RTptr-???????? (segment #%u)", iMapping, aMappings[iMapping].Address);
}
if (cVerbosityLevel > 1)
{
uint32_t cSymbols = RTDbgModSymbolCount(hDbgMod);
RTPrintf(" %u symbols\n", cSymbols);
for (uint32_t iSymbol = 0; iSymbol < cSymbols; iSymbol++)
{
RTDBGSYMBOL SymInfo;
rc = RTDbgModSymbolByOrdinal(hDbgMod, iSymbol, &SymInfo);
if (RT_SUCCESS(rc))
RTPrintf(" #%04u at %08x:%RTptr %05llx %s\n",
SymInfo.iOrdinal, SymInfo.iSeg, SymInfo.offSeg,
(uint64_t)SymInfo.cb, SymInfo.szName);
}
}
}
}
else
RTMsgError("RTDbgAsModuleQueryMapByIndex failed: %Rrc", rc);
RTDbgModRelease(hDbgMod);
}
RTPrintf("*** End of Address Space Dump ***\n");
}
/*
* Read text from standard input and see if there is anything we can translate.
*/
for (;;)
{
/* Get a line. */
char szLine[_64K];
rc = RTStrmGetLine(pInput, szLine, sizeof(szLine));
if (rc == VERR_EOF)
break;
if (RT_FAILURE(rc))
return RTMsgErrorExit(RTEXITCODE_FAILURE, "RTStrmGetLine() -> %Rrc\n", rc);
/*
* Search the line for potential addresses and replace them with
* symbols+offset.
*/
const char *pszStart = szLine;
const char *psz = szLine;
char ch;
while ((ch = *psz) != '\0')
{
size_t cchAddress;
uint64_t u64Address;
if ( ( ch == '0'
&& (psz[1] == 'x' || psz[1] == 'X')
&& TryParseAddress(psz, &cchAddress, &u64Address))
|| ( RT_C_IS_XDIGIT(ch)
&& TryParseAddress(psz, &cchAddress, &u64Address))
)
{
/* Print. */
psz += cchAddress;
if (pszStart != psz)
RTStrmWrite(pOutput, pszStart, psz - pszStart);
pszStart = psz;
/* Try get the module. */
RTUINTPTR uAddr;
RTDBGSEGIDX iSeg;
RTDBGMOD hDbgMod;
rc = RTDbgAsModuleByAddr(hDbgAs, u64Address, &hDbgMod, &uAddr, &iSeg);
if (RT_SUCCESS(rc))
{
if (iSeg != UINT32_MAX)
RTStrmPrintf(pOutput, "=[%s:%u", RTDbgModName(hDbgMod), iSeg);
else
RTStrmPrintf(pOutput, "=[%s", RTDbgModName(hDbgMod), iSeg);
/*
* Do we have symbols?
*/
RTDBGSYMBOL Symbol;
RTINTPTR offSym;
rc = RTDbgAsSymbolByAddr(hDbgAs, u64Address, RTDBGSYMADDR_FLAGS_LESS_OR_EQUAL, &offSym, &Symbol, NULL);
if (RT_SUCCESS(rc))
{
if (!offSym)
RTStrmPrintf(pOutput, "!%s", Symbol.szName);
else if (offSym > 0)
RTStrmPrintf(pOutput, "!%s+%#llx", Symbol.szName, offSym);
else
RTStrmPrintf(pOutput, "!%s-%#llx", Symbol.szName, -offSym);
}
else
RTStrmPrintf(pOutput, "+%#llx", u64Address - uAddr);
/*
* Do we have line numbers?
*/
RTDBGLINE Line;
RTINTPTR offLine;
rc = RTDbgAsLineByAddr(hDbgAs, u64Address, &offLine, &Line);
if (RT_SUCCESS(rc))
RTStrmPrintf(pOutput, " %Rbn(%u)", Line.szFilename, Line.uLineNo);
RTStrmPrintf(pOutput, "]");
RTDbgModRelease(hDbgMod);
}
}
else
psz++;
}
if (pszStart != psz)
RTStrmWrite(pOutput, pszStart, psz - pszStart);
RTStrmPutCh(pOutput, '\n');
}
return RTEXITCODE_SUCCESS;
}
| ryenus/vbox | src/VBox/Runtime/tools/RTLdrFlt.cpp | C++ | gpl-2.0 | 13,350 |
# it394_project_template
A project template for a Python/Django project ready to deply into the Heroku production environment.
# How to use this template
To use this template start a new project using django-admin and the --template parameter
```
django-admin startproject --template=http://github.com/usma-it394/it394_project_template/archive/master.zip <project name>
```
django-admin startproject will correctly rename the project_name folder and also replace the {{ }} patterns with the correct values for the contents of the files in the project_name folder.
Unfortunately, it does not apply changes to the contents of files in the root directory of the project. I've included a simple PowerShell script named "fix_name.ps1" that will replace the HW3 pattern in any files in the current working directory. So after you start the project run
```
cd <project name>
.\fix_name.ps1 -name "project name"
```
For example, if I wanted to start a new project named "nifty" I would enter the following:
```
django-admin startproject --template=http://github.com/usma-it394/it394_project_template/archive/master.zip nifty
cd nifty
.\fix_name.ps1 -name "nifty"
```
# References
The standard django-admin templates for projects and apps are at https://github.com/django/django/tree/master/django/conf
| dchamb/Polls-Project | README.md | Markdown | gpl-2.0 | 1,301 |
/* ----------------------------------------------------------------------
LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator
http://lammps.sandia.gov, Sandia National Laboratories
Steve Plimpton, sjplimp@sandia.gov
Copyright (2003) Sandia Corporation. Under the terms of Contract
DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains
certain rights in this software. This software is distributed under
the GNU General Public License.
See the README file in the top-level LAMMPS directory.
------------------------------------------------------------------------- */
/* ----------------------------------------------------------------------
Contributing authors: W. Michael Brown (Intel)
------------------------------------------------------------------------- */
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include "pair_eam_intel.h"
#include "atom.h"
#include "force.h"
#include "comm.h"
#include "modify.h"
#include "neighbor.h"
#include "neigh_list.h"
#include "neigh_request.h"
#include "memory.h"
#include "error.h"
#include "suffix.h"
using namespace LAMMPS_NS;
#define MAXLINE 1024
#define FC_PACKED1_T typename ForceConst<flt_t>::fc_packed1
#define FC_PACKED2_T typename ForceConst<flt_t>::fc_packed2
/* ---------------------------------------------------------------------- */
PairEAMIntel::PairEAMIntel(LAMMPS *lmp) : PairEAM(lmp)
{
suffix_flag |= Suffix::INTEL;
fp_float = 0;
}
/* ---------------------------------------------------------------------- */
PairEAMIntel::~PairEAMIntel()
{
memory->destroy(fp_float);
}
/* ---------------------------------------------------------------------- */
void PairEAMIntel::compute(int eflag, int vflag)
{
if (fix->precision() == FixIntel::PREC_MODE_MIXED)
compute<float,double>(eflag, vflag, fix->get_mixed_buffers(),
force_const_single);
else if (fix->precision() == FixIntel::PREC_MODE_DOUBLE)
compute<double,double>(eflag, vflag, fix->get_double_buffers(),
force_const_double);
else
compute<float,float>(eflag, vflag, fix->get_single_buffers(),
force_const_single);
fix->balance_stamp();
vflag_fdotr = 0;
}
/* ---------------------------------------------------------------------- */
template <class flt_t, class acc_t>
void PairEAMIntel::compute(int eflag, int vflag,
IntelBuffers<flt_t,acc_t> *buffers,
const ForceConst<flt_t> &fc)
{
if (eflag || vflag) {
ev_setup(eflag, vflag);
} else evflag = vflag_fdotr = 0;
const int inum = list->inum;
const int nthreads = comm->nthreads;
const int host_start = fix->host_start_pair();
const int offload_end = fix->offload_end_pair();
const int ago = neighbor->ago;
if (ago != 0 && fix->separate_buffers() == 0) {
fix->start_watch(TIME_PACK);
int packthreads;
if (nthreads > INTEL_HTHREADS) packthreads = nthreads;
else packthreads = 1;
#if defined(_OPENMP)
#pragma omp parallel if(packthreads > 1)
#endif
{
int ifrom, ito, tid;
IP_PRE_omp_range_id_align(ifrom, ito, tid, atom->nlocal + atom->nghost,
packthreads, sizeof(ATOM_T));
buffers->thr_pack(ifrom,ito,ago);
}
fix->stop_watch(TIME_PACK);
}
int ovflag = 0;
if (vflag_fdotr) ovflag = 2;
else if (vflag) ovflag = 1;
if (_onetype) {
if (eflag) {
if (force->newton_pair) {
eval<1,1,1>(1, ovflag, buffers, fc, 0, offload_end);
eval<1,1,1>(0, ovflag, buffers, fc, host_start, inum);
} else {
eval<1,1,0>(1, ovflag, buffers, fc, 0, offload_end);
eval<1,1,0>(0, ovflag, buffers, fc, host_start, inum);
}
} else {
if (force->newton_pair) {
eval<1,0,1>(1, ovflag, buffers, fc, 0, offload_end);
eval<1,0,1>(0, ovflag, buffers, fc, host_start, inum);
} else {
eval<1,0,0>(1, ovflag, buffers, fc, 0, offload_end);
eval<1,0,0>(0, ovflag, buffers, fc, host_start, inum);
}
}
} else {
if (eflag) {
if (force->newton_pair) {
eval<0,1,1>(1, ovflag, buffers, fc, 0, offload_end);
eval<0,1,1>(0, ovflag, buffers, fc, host_start, inum);
} else {
eval<0,1,0>(1, ovflag, buffers, fc, 0, offload_end);
eval<0,1,0>(0, ovflag, buffers, fc, host_start, inum);
}
} else {
if (force->newton_pair) {
eval<0,0,1>(1, ovflag, buffers, fc, 0, offload_end);
eval<0,0,1>(0, ovflag, buffers, fc, host_start, inum);
} else {
eval<0,0,0>(1, ovflag, buffers, fc, 0, offload_end);
eval<0,0,0>(0, ovflag, buffers, fc, host_start, inum);
}
}
}
}
/* ---------------------------------------------------------------------- */
template <int ONETYPE, int EFLAG, int NEWTON_PAIR, class flt_t, class acc_t>
void PairEAMIntel::eval(const int offload, const int vflag,
IntelBuffers<flt_t,acc_t> *buffers,
const ForceConst<flt_t> &fc,
const int astart, const int aend)
{
const int inum = aend - astart;
if (inum == 0) return;
flt_t *fp_f;
if (atom->nmax > nmax) {
memory->destroy(rho);
memory->destroy(fp);
nmax = atom->nmax;
int edge = (nmax * sizeof(acc_t)) % INTEL_DATA_ALIGN;
if (edge) nmax += (INTEL_DATA_ALIGN - edge) / sizeof(acc_t);
if (NEWTON_PAIR)
memory->create(rho,nmax*comm->nthreads,"pair:rho");
else
memory->create(rho,nmax,"pair:rho");
memory->create(fp,nmax,"pair:fp");
// Use single precision allocation for single/mixed mode
// Keep double version for single and swap_eam
if (sizeof(flt_t)==sizeof(float)) {
memory->destroy(fp_float);
memory->create(fp_float,nmax,"pair::fp_float");
}
}
if (sizeof(flt_t)==sizeof(float))
fp_f = (flt_t *)fp_float;
else
fp_f = (flt_t *)fp;
int nlocal, nall, minlocal;
fix->get_buffern(offload, nlocal, nall, minlocal);
const int ago = neighbor->ago;
IP_PRE_pack_separate_buffers(fix, buffers, ago, offload, nlocal, nall);
ATOM_T * _noalias const x = buffers->get_x(offload);
const int * _noalias const numneigh = list->numneigh;
const int * _noalias const cnumneigh = buffers->cnumneigh(list);
const int * _noalias const firstneigh = buffers->firstneigh(list);
const FC_PACKED1_T * _noalias const rhor_spline_f = fc.rhor_spline_f;
const FC_PACKED1_T * _noalias const rhor_spline_e = fc.rhor_spline_e;
const FC_PACKED2_T * _noalias const z2r_spline_t = fc.z2r_spline_t;
const FC_PACKED1_T * _noalias const frho_spline_f = fc.frho_spline_f;
const FC_PACKED1_T * _noalias const frho_spline_e = fc.frho_spline_e;
const flt_t * _noalias const scale_f = fc.scale_f[0];
const int ntypes = atom->ntypes + 1;
const int eatom = this->eflag_atom;
flt_t * _noalias const ccachex = buffers->get_ccachex();
flt_t * _noalias const ccachey = buffers->get_ccachey();
flt_t * _noalias const ccachez = buffers->get_ccachez();
flt_t * _noalias const ccachew = buffers->get_ccachew();
int * _noalias const ccachei = buffers->get_ccachei();
int * _noalias const ccachej = buffers->get_ccachej();
const int ccache_stride = _ccache_stride;
// Determine how much data to transfer
int x_size, q_size, f_stride, ev_size, separate_flag;
IP_PRE_get_transfern(ago, NEWTON_PAIR, EFLAG, vflag,
buffers, offload, fix, separate_flag,
x_size, q_size, ev_size, f_stride);
int tc;
FORCE_T * _noalias f_start;
acc_t * _noalias ev_global;
IP_PRE_get_buffers(offload, buffers, fix, tc, f_start, ev_global);
const int nthreads = tc;
int *overflow = fix->get_off_overflow_flag();
const flt_t frdr = rdr;
const flt_t frdrho = rdrho;
const flt_t frhomax = rhomax;
const flt_t fcutforcesq = cutforcesq;
const int istride = fc.rhor_istride();
const int jstride = fc.rhor_jstride();
const int fstride = fc.frho_stride();
{
#if defined(__MIC__) && defined(_LMP_INTEL_OFFLOAD)
*timer_compute = MIC_Wtime();
#endif
IP_PRE_repack_for_offload(NEWTON_PAIR, separate_flag, nlocal, nall,
f_stride, x, 0);
acc_t oevdwl, ov0, ov1, ov2, ov3, ov4, ov5;
if (EFLAG) oevdwl = (acc_t)0;
if (vflag) ov0 = ov1 = ov2 = ov3 = ov4 = ov5 = (acc_t)0;
// loop over neighbors of my atoms
#if defined(_OPENMP)
#pragma omp parallel reduction(+:oevdwl,ov0,ov1,ov2,ov3,ov4,ov5)
#endif
{
int iifrom, iito, tid;
IP_PRE_omp_range_id_vec(iifrom, iito, tid, inum, nthreads,
INTEL_VECTOR_WIDTH);
iifrom += astart;
iito += astart;
int foff;
if (NEWTON_PAIR) foff = tid * f_stride - minlocal;
else foff = -minlocal;
FORCE_T * _noalias const f = f_start + foff;
if (NEWTON_PAIR) foff = tid * nmax;
else foff = 0;
double * _noalias const trho = rho + foff;
if (NEWTON_PAIR) {
memset(f + minlocal, 0, f_stride * sizeof(FORCE_T));
memset(trho, 0, nall * sizeof(double));
}
const int toffs = tid * ccache_stride;
flt_t * _noalias const tdelx = ccachex + toffs;
flt_t * _noalias const tdely = ccachey + toffs;
flt_t * _noalias const tdelz = ccachez + toffs;
flt_t * _noalias const trsq = ccachew + toffs;
int * _noalias const tj = ccachei + toffs;
int * _noalias const tjtype = ccachej + toffs;
flt_t oscale;
int rhor_joff, frho_ioff;
if (ONETYPE) {
const int ptr_off=_onetype * ntypes + _onetype;
oscale = scale_f[ptr_off];
int rhor_ioff = istride * _onetype;
rhor_joff = rhor_ioff + _onetype * jstride;
frho_ioff = fstride * _onetype;
}
for (int i = iifrom; i < iito; ++i) {
int itype, rhor_ioff;
if (!ONETYPE) {
itype = x[i].w;
rhor_ioff = istride * itype;
}
const int * _noalias const jlist = firstneigh + cnumneigh[i];
const int jnum = numneigh[i];
const flt_t xtmp = x[i].x;
const flt_t ytmp = x[i].y;
const flt_t ztmp = x[i].z;
acc_t rhoi = (acc_t)0.0;
int ej = 0;
#if defined(LMP_SIMD_COMPILER)
#pragma vector aligned
#pragma ivdep
#endif
for (int jj = 0; jj < jnum; jj++) {
const int j = jlist[jj] & NEIGHMASK;
const flt_t delx = xtmp - x[j].x;
const flt_t dely = ytmp - x[j].y;
const flt_t delz = ztmp - x[j].z;
const flt_t rsq = delx*delx + dely*dely + delz*delz;
if (rsq < fcutforcesq) {
trsq[ej]=rsq;
if (!ONETYPE) tjtype[ej]=x[j].w;
tj[ej]=jlist[jj];
ej++;
}
}
#if defined(LMP_SIMD_COMPILER)
#pragma vector aligned
#pragma simd reduction(+:rhoi)
#endif
for (int jj = 0; jj < ej; jj++) {
int jtype;
const int j = tj[jj] & NEIGHMASK;
if (!ONETYPE) jtype = tjtype[jj];
const flt_t rsq = trsq[jj];
flt_t p = sqrt(rsq)*frdr + (flt_t)1.0;
int m = static_cast<int> (p);
m = MIN(m,nr-1);
p -= m;
p = MIN(p,(flt_t)1.0);
if (!ONETYPE)
rhor_joff = rhor_ioff + jtype * jstride;
const int joff = rhor_joff + m;
flt_t ra;
ra = ((rhor_spline_e[joff].a*p + rhor_spline_e[joff].b) * p +
rhor_spline_e[joff].c) * p + rhor_spline_e[joff].d;
rhoi += ra;
if (NEWTON_PAIR) {
if (!ONETYPE) {
const int ioff = jtype * istride + itype * jstride + m;
ra = ((rhor_spline_e[ioff].a*p + rhor_spline_e[ioff].b)*p +
rhor_spline_e[ioff].c) * p + rhor_spline_e[ioff].d;
}
trho[j] += ra;
}
} // for jj
if (NEWTON_PAIR)
trho[i] += rhoi;
else
trho[i] = rhoi;
} // for i
#if defined(_OPENMP)
if (NEWTON_PAIR && nthreads > 1) {
#pragma omp barrier
if (tid == 0) {
const int rcount = nall;
if (nthreads == 2) {
double *trho2 = rho + nmax;
#pragma vector aligned
#pragma simd
for (int n = 0; n < rcount; n++)
rho[n] += trho2[n];
} else if (nthreads == 4) {
double *trho2 = rho + nmax;
double *trho3 = trho2 + nmax;
double *trho4 = trho3 + nmax;
#pragma vector aligned
#pragma simd
for (int n = 0; n < rcount; n++)
rho[n] += trho2[n] + trho3[n] + trho4[n];
} else {
double *trhon = rho + nmax;
for (int t = 1; t < nthreads; t++) {
#pragma vector aligned
#pragma simd
for (int n = 0; n < rcount; n++)
rho[n] += trhon[n];
trhon += nmax;
}
}
}
}
#endif
// communicate and sum densities
if (NEWTON_PAIR) {
if (tid == 0)
comm->reverse_comm_pair(this);
}
#if defined(_OPENMP)
#pragma omp barrier
#endif
// fp = derivative of embedding energy at each atom
// phi = embedding energy at each atom
// if rho > rhomax (e.g. due to close approach of two atoms),
// will exceed table, so add linear term to conserve energy
acc_t tevdwl;
if (EFLAG) tevdwl = (acc_t)0.0;
#if defined(LMP_SIMD_COMPILER)
#pragma vector aligned
#pragma simd reduction(+:tevdwl)
#endif
for (int i = iifrom; i < iito; ++i) {
int itype;
if (!ONETYPE) itype = x[i].w;
flt_t p = rho[i]*frdrho + (flt_t)1.0;
int m = static_cast<int> (p);
m = MAX(1,MIN(m,nrho-1));
p -= m;
p = MIN(p,(flt_t)1.0);
if (!ONETYPE) frho_ioff = itype * fstride;
const int ioff = frho_ioff + m;
fp_f[i] = (frho_spline_f[ioff].a*p + frho_spline_f[ioff].b)*p +
frho_spline_f[ioff].c;
if (EFLAG) {
flt_t phi = ((frho_spline_e[ioff].a*p + frho_spline_e[ioff].b)*p +
frho_spline_e[ioff].c)*p + frho_spline_e[ioff].d;
if (rho[i] > frhomax) phi += fp_f[i] * (rho[i]-frhomax);
if (!ONETYPE) {
const int ptr_off=itype*ntypes + itype;
oscale = scale_f[ptr_off];
}
phi *= oscale;
tevdwl += phi;
if (eatom) f[i].w += phi;
}
}
if (EFLAG) oevdwl += tevdwl;
// communicate derivative of embedding function
#if defined(_OPENMP)
#pragma omp barrier
#endif
if (tid == 0)
comm->forward_comm_pair(this);
if (NEWTON_PAIR)
memset(f + minlocal, 0, f_stride * sizeof(FORCE_T));
#if defined(_OPENMP)
#pragma omp barrier
#endif
// compute forces on each atom
// loop over neighbors of my atoms
for (int i = iifrom; i < iito; ++i) {
int itype, rhor_ioff;
const flt_t * _noalias scale_fi;
if (!ONETYPE) {
itype = x[i].w;
rhor_ioff = istride * itype;
scale_fi = scale_f + itype*ntypes;
}
const int * _noalias const jlist = firstneigh + cnumneigh[i];
const int jnum = numneigh[i];
acc_t fxtmp, fytmp, fztmp, fwtmp;
acc_t sevdwl, sv0, sv1, sv2, sv3, sv4, sv5;
const flt_t xtmp = x[i].x;
const flt_t ytmp = x[i].y;
const flt_t ztmp = x[i].z;
fxtmp = fytmp = fztmp = (acc_t)0;
if (EFLAG) fwtmp = sevdwl = (acc_t)0;
if (NEWTON_PAIR == 0)
if (vflag==1) sv0 = sv1 = sv2 = sv3 = sv4 = sv5 = (acc_t)0;
int ej = 0;
#if defined(LMP_SIMD_COMPILER)
#pragma vector aligned
#pragma ivdep
#endif
for (int jj = 0; jj < jnum; jj++) {
const int j = jlist[jj] & NEIGHMASK;
const flt_t delx = xtmp - x[j].x;
const flt_t dely = ytmp - x[j].y;
const flt_t delz = ztmp - x[j].z;
const flt_t rsq = delx*delx + dely*dely + delz*delz;
if (rsq < fcutforcesq) {
trsq[ej]=rsq;
tdelx[ej]=delx;
tdely[ej]=dely;
tdelz[ej]=delz;
if (!ONETYPE) tjtype[ej]=x[j].w;
tj[ej]=jlist[jj];
ej++;
}
}
#if defined(LMP_SIMD_COMPILER)
#pragma vector aligned
#pragma simd reduction(+:fxtmp, fytmp, fztmp, fwtmp, sevdwl, \
sv0, sv1, sv2, sv3, sv4, sv5)
#endif
for (int jj = 0; jj < ej; jj++) {
int jtype;
const int j = tj[jj] & NEIGHMASK;
if (!ONETYPE) jtype = tjtype[jj];
const flt_t rsq = trsq[jj];
const flt_t r = sqrt(rsq);
flt_t p = r*frdr + (flt_t)1.0;
int m = static_cast<int> (p);
m = MIN(m,nr-1);
p -= m;
p = MIN(p,(flt_t)1.0);
if (!ONETYPE)
rhor_joff = rhor_ioff + jtype * jstride;
const int joff = rhor_joff + m;
const flt_t rhojp = (rhor_spline_f[joff].a*p +
rhor_spline_f[joff].b)*p +
rhor_spline_f[joff].c;
flt_t rhoip;
if (!ONETYPE) {
const int ioff = jtype * istride + itype * jstride + m;
rhoip = (rhor_spline_f[ioff].a*p + rhor_spline_f[ioff].b)*p +
rhor_spline_f[ioff].c;
} else
rhoip = rhojp;
const flt_t z2p = (z2r_spline_t[joff].a*p +
z2r_spline_t[joff].b)*p +
z2r_spline_t[joff].c;
const flt_t z2 = ((z2r_spline_t[joff].d*p +
z2r_spline_t[joff].e)*p +
z2r_spline_t[joff].f)*p +
z2r_spline_t[joff].g;
const flt_t recip = (flt_t)1.0/r;
const flt_t phi = z2*recip;
const flt_t phip = z2p*recip - phi*recip;
const flt_t psip = fp_f[i]*rhojp + fp_f[j]*rhoip + phip;
if (!ONETYPE)
oscale = scale_fi[jtype];
const flt_t fpair = -oscale*psip*recip;
const flt_t fpx = fpair * tdelx[jj];
fxtmp += fpx;
if (NEWTON_PAIR) f[j].x -= fpx;
const flt_t fpy = fpair * tdely[jj];
fytmp += fpy;
if (NEWTON_PAIR) f[j].y -= fpy;
const flt_t fpz = fpair * tdelz[jj];
fztmp += fpz;
if (NEWTON_PAIR) f[j].z -= fpz;
if (EFLAG) {
const flt_t evdwl = oscale*phi;
sevdwl += evdwl;
if (eatom) {
fwtmp += (flt_t)0.5 * evdwl;
if (NEWTON_PAIR)
f[j].w += (flt_t)0.5 * evdwl;
}
}
if (NEWTON_PAIR == 0)
IP_PRE_ev_tally_nborv(vflag, tdelx[jj], tdely[jj], tdelz[jj],
fpx, fpy, fpz);
} // for jj
if (NEWTON_PAIR) {
f[i].x += fxtmp;
f[i].y += fytmp;
f[i].z += fztmp;
} else {
f[i].x = fxtmp;
f[i].y = fytmp;
f[i].z = fztmp;
sevdwl *= (acc_t)0.5;
}
IP_PRE_ev_tally_atom(NEWTON_PAIR, EFLAG, vflag, f, fwtmp);
} // for i
IP_PRE_fdotr_reduce_omp(NEWTON_PAIR, nall, minlocal, nthreads, f_start,
f_stride, x, offload, vflag, ov0, ov1, ov2, ov3,
ov4, ov5);
} /// omp
IP_PRE_fdotr_reduce(NEWTON_PAIR, nall, nthreads, f_stride, vflag,
ov0, ov1, ov2, ov3, ov4, ov5);
if (EFLAG) {
ev_global[0] = oevdwl;
ev_global[1] = (acc_t)0.0;
}
if (vflag) {
if (NEWTON_PAIR == 0) {
ov0 *= (acc_t)0.5;
ov1 *= (acc_t)0.5;
ov2 *= (acc_t)0.5;
ov3 *= (acc_t)0.5;
ov4 *= (acc_t)0.5;
ov5 *= (acc_t)0.5;
}
ev_global[2] = ov0;
ev_global[3] = ov1;
ev_global[4] = ov2;
ev_global[5] = ov3;
ev_global[6] = ov4;
ev_global[7] = ov5;
}
#if defined(__MIC__) && defined(_LMP_INTEL_OFFLOAD)
*timer_compute = MIC_Wtime() - *timer_compute;
#endif
}
if (offload)
fix->stop_watch(TIME_OFFLOAD_LATENCY);
else
fix->stop_watch(TIME_HOST_PAIR);
if (EFLAG || vflag)
fix->add_result_array(f_start, ev_global, offload, eatom, 0, vflag);
else
fix->add_result_array(f_start, 0, offload);
}
/* ----------------------------------------------------------------------
init specific to this pair style
------------------------------------------------------------------------- */
void PairEAMIntel::init_style()
{
PairEAM::init_style();
if (force->newton_pair == 0) {
neighbor->requests[neighbor->nrequest-1]->half = 0;
neighbor->requests[neighbor->nrequest-1]->full = 1;
}
neighbor->requests[neighbor->nrequest-1]->intel = 1;
int ifix = modify->find_fix("package_intel");
if (ifix < 0)
error->all(FLERR,
"The 'package intel' command is required for /intel styles");
fix = static_cast<FixIntel *>(modify->fix[ifix]);
fix->pair_init_check();
#ifdef _LMP_INTEL_OFFLOAD
if (fix->offload_balance() != 0.0)
error->all(FLERR,
"Offload for eam/intel is not yet available. Set balance to 0.");
#endif
if (fix->precision() == FixIntel::PREC_MODE_MIXED)
pack_force_const(force_const_single, fix->get_mixed_buffers());
else if (fix->precision() == FixIntel::PREC_MODE_DOUBLE)
pack_force_const(force_const_double, fix->get_double_buffers());
else
pack_force_const(force_const_single, fix->get_single_buffers());
}
/* ---------------------------------------------------------------------- */
template <class flt_t, class acc_t>
void PairEAMIntel::pack_force_const(ForceConst<flt_t> &fc,
IntelBuffers<flt_t,acc_t> *buffers)
{
int off_ccache = 0;
#ifdef _LMP_INTEL_OFFLOAD
if (_cop >= 0) off_ccache = 1;
#endif
buffers->grow_ccache(off_ccache, comm->nthreads, 1);
_ccache_stride = buffers->ccache_stride();
int tp1 = atom->ntypes + 1;
fc.set_ntypes(tp1,nr,nrho,memory,_cop);
buffers->set_ntypes(tp1);
flt_t **cutneighsq = buffers->get_cutneighsq();
// Repeat cutsq calculation because done after call to init_style
double cut, cutneigh;
for (int i = 1; i <= atom->ntypes; i++) {
for (int j = i; j <= atom->ntypes; j++) {
if (setflag[i][j] != 0 || (setflag[i][i] != 0 && setflag[j][j] != 0)) {
cut = init_one(i,j);
cutneigh = cut + neighbor->skin;
cutsq[i][j] = cutsq[j][i] = cut*cut;
cutneighsq[i][j] = cutneighsq[j][i] = cutneigh * cutneigh;
}
}
}
_onetype=-1;
double oldscale=-1;
for (int i = 1; i < tp1; i++) {
int ioff = i * fc.frho_stride();
for (int k = 0; k < nrho + 1; k++) {
fc.frho_spline_f[ioff + k].a = frho_spline[type2frho[i]][k][0];
fc.frho_spline_f[ioff + k].b = frho_spline[type2frho[i]][k][1];
fc.frho_spline_f[ioff + k].c = frho_spline[type2frho[i]][k][2];
fc.frho_spline_e[ioff + k].a = frho_spline[type2frho[i]][k][3];
fc.frho_spline_e[ioff + k].b = frho_spline[type2frho[i]][k][4];
fc.frho_spline_e[ioff + k].c = frho_spline[type2frho[i]][k][5];
fc.frho_spline_e[ioff + k].d = frho_spline[type2frho[i]][k][6];
}
ioff = i * fc.rhor_istride();
for (int j = 1; j < tp1; j++) {
fc.scale_f[i][j] = scale[i][j];
if (type2rhor[i][j] >= 0) {
const int joff = ioff + j * fc.rhor_jstride();
for (int k = 0; k < nr + 1; k++) {
if (type2rhor[j][i] != type2rhor[i][j])
_onetype = 0;
else if (_onetype < 0)
_onetype = i;
if (oldscale < 0)
oldscale = scale[i][j];
else
if (oldscale != scale[i][j])
_onetype = 0;
fc.rhor_spline_f[joff + k].a=rhor_spline[type2rhor[j][i]][k][0];
fc.rhor_spline_f[joff + k].b=rhor_spline[type2rhor[j][i]][k][1];
fc.rhor_spline_f[joff + k].c=rhor_spline[type2rhor[j][i]][k][2];
fc.rhor_spline_e[joff + k].a=rhor_spline[type2rhor[j][i]][k][3];
fc.rhor_spline_e[joff + k].b=rhor_spline[type2rhor[j][i]][k][4];
fc.rhor_spline_e[joff + k].c=rhor_spline[type2rhor[j][i]][k][5];
fc.rhor_spline_e[joff + k].d=rhor_spline[type2rhor[j][i]][k][6];
fc.z2r_spline_t[joff + k].a=z2r_spline[type2rhor[j][i]][k][0];
fc.z2r_spline_t[joff + k].b=z2r_spline[type2rhor[j][i]][k][1];
fc.z2r_spline_t[joff + k].c=z2r_spline[type2rhor[j][i]][k][2];
fc.z2r_spline_t[joff + k].d=z2r_spline[type2rhor[j][i]][k][3];
fc.z2r_spline_t[joff + k].e=z2r_spline[type2rhor[j][i]][k][4];
fc.z2r_spline_t[joff + k].f=z2r_spline[type2rhor[j][i]][k][5];
fc.z2r_spline_t[joff + k].g=z2r_spline[type2rhor[j][i]][k][6];
}
}
}
}
if (_onetype < 0) _onetype = 0;
}
/* ---------------------------------------------------------------------- */
template <class flt_t>
void PairEAMIntel::ForceConst<flt_t>::set_ntypes(const int ntypes,
const int nr, const int nrho,
Memory *memory,
const int cop) {
if (ntypes != _ntypes || nr > _nr || nrho > _nrho) {
if (_ntypes > 0) {
_memory->destroy(rhor_spline_f);
_memory->destroy(rhor_spline_e);
_memory->destroy(frho_spline_f);
_memory->destroy(frho_spline_e);
_memory->destroy(z2r_spline_t);
_memory->destroy(scale_f);
}
if (ntypes > 0) {
_cop = cop;
_nr = nr + 1;
int edge = (_nr * sizeof(flt_t)) % INTEL_DATA_ALIGN;
if (edge) _nr += (INTEL_DATA_ALIGN - edge) / sizeof(flt_t);
memory->create(rhor_spline_f,ntypes*ntypes*_nr,"fc.rhor_spline_f");
memory->create(rhor_spline_e,ntypes*ntypes*_nr,"fc.rhor_spline_e");
memory->create(z2r_spline_t,ntypes*ntypes*_nr,"fc.z2r_spline_t");
_nrho = nrho + 1;
edge = (_nrho * sizeof(flt_t)) % INTEL_DATA_ALIGN;
if (edge) _nrho += (INTEL_DATA_ALIGN - edge) / sizeof(flt_t);
memory->create(frho_spline_f,ntypes*_nrho,"fc.frho_spline_f");
memory->create(frho_spline_e,ntypes*_nrho,"fc.frho_spline_e");
memory->create(scale_f,ntypes,ntypes,"fc.scale_f");
}
}
_ntypes = ntypes;
_memory = memory;
}
/* ---------------------------------------------------------------------- */
int PairEAMIntel::pack_forward_comm(int n, int *list, double *buf,
int pbc_flag, int *pbc)
{
if (fix->precision() == FixIntel::PREC_MODE_DOUBLE)
return pack_forward_comm(n, list, buf, fp);
else
return pack_forward_comm(n, list, buf, fp_float);
}
/* ---------------------------------------------------------------------- */
void PairEAMIntel::unpack_forward_comm(int n, int first, double *buf)
{
if (fix->precision() == FixIntel::PREC_MODE_DOUBLE)
unpack_forward_comm(n, first, buf, fp);
else
unpack_forward_comm(n, first, buf, fp_float);
}
/* ---------------------------------------------------------------------- */
template<class flt_t>
int PairEAMIntel::pack_forward_comm(int n, int *list, double *buf,
flt_t *fp_f)
{
int i,j,m;
m = 0;
for (i = 0; i < n; i++) {
j = list[i];
buf[m++] = fp_f[j];
}
return m;
}
/* ---------------------------------------------------------------------- */
template<class flt_t>
void PairEAMIntel::unpack_forward_comm(int n, int first, double *buf,
flt_t *fp_f)
{
int i,m,last;
m = 0;
last = first + n;
for (i = first; i < last; i++) fp_f[i] = buf[m++];
}
| junghans/lammps | src/USER-INTEL/pair_eam_intel.cpp | C++ | gpl-2.0 | 27,987 |
<?php
/**
* Created by PhpStorm.
* User: freeman
* Date: 19.08.15
* Time: 16:59
*/
namespace app\includes\controllers\admin\menu;
class TPWizardController extends \core\controllers\TPOAdminMenuController{
public $local;
public $local_url;
public $model;
public function __construct(){
parent::__construct();
$this->model = new \app\includes\models\admin\menu\TPWizardModel();
}
public function action()
{
// TODO: Implement action() method.
// TODO: Implement action() method.
$plugin_page = add_submenu_page( null,
_x('Wizard', 'admin menu page title wizard', TPOPlUGIN_TEXTDOMAIN ),
_x('Wizard', 'admin menu menu title wizard', TPOPlUGIN_TEXTDOMAIN ),
'manage_options',
'tp_control_wizard',
array(&$this, 'render'));
add_action( 'admin_footer-'.$plugin_page, array(&$this, 'TPLinkHelp') );
//global $submenu;
}
public function render()
{
global $locale;
switch($locale){
case "ru_RU":
$this->local = 'ru';
$this->local_url = 'ru';
break;
case "en_US":
$this->local = 'en';
$this->local_url = 'en-us';
break;
default:
$this->local = 'en';
$this->local_url = 'en-us';
break;
}
// TODO: Implement render() method.
$pathView = TPOPlUGIN_DIR."/app/includes/views/admin/menu/TPWizard.view.php";
parent::loadView($pathView);
}
} | saintcode/cenotexplore | src/wordpress/wp-content/plugins/travelpayouts/app/includes/controllers/admin/menu/TPWizardController.php | PHP | gpl-2.0 | 1,674 |
/*
* @file main.cpp
* @author Simon Brummer
* @version 0.3
* @desc Singleton example implementations:
* - Gov Singleton
* - Meyers Singleton
* - DCLP Singleton
*/
#include <iostream>
#include <stdio.h>
#include <pthread.h>
using namespace std;
/* Begin GOVSingleton */
// Declaration
class GOFSingleton {
private:
static GOFSingleton* instance_;
private:
GOFSingleton();
GOFSingleton(const GOFSingleton& other);
GOFSingleton& operator=(const GOFSingleton& other);
~GOFSingleton();
public:
static GOFSingleton* getInstance();
void method(void);
};
// Implementation
GOFSingleton* GOFSingleton::instance_ = NULL;
GOFSingleton* GOFSingleton::getInstance(){
if( instance_ == NULL){
instance_ = new GOFSingleton();
}
return instance_;
}
GOFSingleton::GOFSingleton(){
printf("ctor GOF Singleton\n");
}
GOFSingleton::~GOFSingleton(){
printf("dtor GOF Singleton\n");
}
void GOFSingleton::method(){
printf("method called\n");
}
/* End GOV-Singleton */
/* Begin Meyers-Singleton */
// Declaration
class MeyersSingleton {
private:
MeyersSingleton();
MeyersSingleton(const MeyersSingleton& other);
MeyersSingleton& operator=(const MeyersSingleton& other);
~MeyersSingleton();
public:
static MeyersSingleton* getInstance();
void method(void);
};
// Implementation
MeyersSingleton* MeyersSingleton::getInstance(){
static MeyersSingleton instance;
return &instance;
}
MeyersSingleton::MeyersSingleton(){
printf("ctor Meyers Singleton\n");
}
MeyersSingleton::~MeyersSingleton(){
printf("dtor Meyers Singleton\n");
}
void MeyersSingleton::method(){
printf("method called\n");
}
/* End Meyers-Singleton */
/* Begin DCLP-Singleton */
// Declaration
class DCLPSingleton {
private:
static DCLPSingleton* instance_;
private:
DCLPSingleton();
DCLPSingleton(const DCLPSingleton& other);
DCLPSingleton& operator=(const DCLPSingleton& other);
virtual ~DCLPSingleton();
public:
static DCLPSingleton* getInstance();
void method(void);
};
// Implementation
DCLPSingleton* DCLPSingleton::instance_ = NULL;
DCLPSingleton* DCLPSingleton::getInstance(){
static pthread_mutex_t mtx_ = PTHREAD_MUTEX_INITIALIZER;
if( instance_ == NULL){
pthread_mutex_lock(&mtx_);
if( instance_ == NULL){
instance_ = new DCLPSingleton();
}
pthread_mutex_unlock(&mtx_);
}
return instance_;
}
DCLPSingleton::DCLPSingleton(){
printf("ctor DCLP Singleton\n");
}
DCLPSingleton::~DCLPSingleton(){
printf("dtor DCLP Singleton\n");
}
void DCLPSingleton::method(){
printf("method called\n");
}
/* End DCLP Singleton */
// Main Function and Demo Code
int main() {
GOFSingleton* gov = GOFSingleton::getInstance();
MeyersSingleton* mey = MeyersSingleton::getInstance();
DCLPSingleton* dclp = DCLPSingleton::getInstance();
gov->method();
mey->method();
dclp->method();
return 0;
}
| brummer-simon/sep2-tut | tutorium_2-singleton/src/main.cpp | C++ | gpl-2.0 | 3,053 |
do
local NUM_MSG_MAX = 3
local TIME_CHECK = 2 -- seconds
local function user_print_name(user)
if user.print_name then
return user.print_name
end
local text = ''
if user.first_name then
text = user.last_name..' '
end
if user.lastname then
text = text..user.last_name
end
return text
end
-- Returns a table with `name` and `msgs`
local function get_msgs_user_chat(user_id, chat_id)
local user_info = {}
local uhash = 'user:'..user_id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..user_id..':'..chat_id
user_info.msgs = tonumber(redis:get(um_hash) or 0)
user_info.name = user_print_name(user)..'👤|'..user_id..'|🗣'
return user_info
end
local function chat_stats(chat_id)
-- Users on chat
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
local users_info = {}
-- Get user info
for i = 1, #users do
local user_id = users[i]
local user_info = get_msgs_user_chat(user_id, chat_id)
table.insert(users_info, user_info)
end
-- Sort users by msgs number
table.sort(users_info, function(a, b)
if a.msgs and b.msgs then
return a.msgs > b.msgs
end
end)
local text = ''
for k,user in pairs(users_info) do
text = text..user.name..' => '..user.msgs..'\n-----------'
end
return text
end
-- Save stats, ban user
local function pre_process(msg)
-- Ignore service msg
if msg.service then
print('Service message')
return msg
end
-- Save user on Redis
if msg.from.type == 'user' then
local hash = 'user:'..msg.from.id
print('Saving user', hash)
if msg.from.print_name then
redis:hset(hash, 'print_name', msg.from.print_name)
end
if msg.from.first_name then
redis:hset(hash, 'first_name', msg.from.first_name)
end
if msg.from.last_name then
redis:hset(hash, 'last_name', msg.from.last_name)
end
end
-- Save stats on Redis
if msg.to.type == 'chat' then
-- User is on chat
local hash = 'chat:'..msg.to.id..':users'
redis:sadd(hash, msg.from.id)
end
-- Total user msgs
local hash = 'msgs:'..msg.from.id..':'..msg.to.id
redis:incr(hash)
-- Check flood
local kick = chat_del_user(chat_id , user_id, ok_cb, true)
vardump(kick)
if msg.from.type == 'user' then
local hash = 'user:'..msg.from.id..':msgs'
local msgs = tonumber(redis:get(hash) or 0)
if msgs > NUM_MSG_MAX then
chat_del_user('chat#id'..msg.to.id,'user#id'..msg.from.id,ok_cb,false)
print('User '..msg.from.id..'is flooding '..msgs)
msg = nil
end
redis:setex(hash, TIME_CHECK, msgs+1)
end
return msg
end
local function bot_stats()
local redis_scan = [[
local cursor = '0'
local count = 0
repeat
local r = redis.call("SCAN", cursor, "MATCH", KEYS[1])
cursor = r[1]
count = count + #r[2]
until cursor == '0'
return count]]
-- Users
local hash = 'msgs:*:'..our_id
local r = redis:eval(redis_scan, 1, hash)
local text = 'Users: '..r
hash = 'chat:*:users'
r = redis:eval(redis_scan, 1, hash)
text = text..'\nChats: '..r
return text
end
local function run(msg, matches)
if matches[1]:lower() == "stats" then
if not matches[2] then
if msg.to.type == 'chat' then
local chat_id = msg.to.id
return chat_stats(chat_id)
else
return 'Stats works only on chats'
end
end
if matches[2] == "bot" then
if not is_sudo(msg) then
return "Bot stats requires privileged user"
else
return bot_stats()
end
end
if matches[2] == "chat" then
if not is_sudo(msg) then
return "This command requires privileged user"
else
return chat_stats(matches[3])
end
end
end
end
return {
description = "Plugin to update user stats.",
usage = {
"!stats: Returns a list of Username [telegram_id]: msg_num",
"!stats chat <chat_id>: Show stats for chat_id",
"!stats bot: Shows bot stats (sudo users)"
},
patterns = {
"^!([Ss]tats)$",
"^!([Ss]tats) (chat) (%d+)",
"^!([Ss]tats) (bot)"
},
run = run,
pre_process = pre_process
}
end
| mamad-ali/xilibot | plugins/stats.lua | Lua | gpl-2.0 | 3,698 |
/*
This stylesheet is used in RSS feeds. The idea is to make the feed look
slightly better when rendered by a browser. This sheet is adapted from
Pete Freitag's blog entry on the subject here:
http://www.petefreitag.com/item/208.cfm
Note that this stylesheet uses the :before pseudo-element, and so this will
look moderately crappy in IE6.
*/
@namespace slash url(http://purl.org/rss/1.0/modules/slash/);
@namespace wfw url(http://wellformedweb.org/CommentAPI/);
rss,
body {
display: block;
background-color: #6b85b0;
margin: 5px;
}
channel {
margin: 5px;
padding: 2px;
}
link { display: none; }
title {
display: block;
font-size: 200%;
font-family: sans-serif;
color: white;
}
description, author, category {
display: block;
}
description { color: white; }
generator {
display: block;
padding-bottom: 5px;
border-bottom: 1px solid black;
color: white;
}
generator:before {
content: "Feed generated by: ";
}
item title {
display: block;
font-size: 100%;
font-weight: bold;
text-decoration: underline;
color: #1000aa;
margin-top: 10px;
}
item author:before { content: "Posted by: "; }
item category:before { content: "Category: "; }
item {
display: block;
padding: 2px 30px 2px 30px;
background-color: #efefef;
}
item link {
display: block;
font-family: courier;
margin-top: 5px;
}
comments, commentRss { display: block; }
comments:before { content: "Comment URL: "; }
slash|comments:before { content: "Number of comments: "; }
wfw|commentRss:before { content: "Comment news feed: "; }
comments, commentRss, item category {
font-size: 80%;
font-family: arial;
padding-left: 1em;
}
docs {
display: block;
background-color: #ffffe6;
margin: 20px;
text-align: center;
padding: 5px;
color: #7f7f7f;
border: 1px solid silver;
}
/* all hidden elements */
language, lastBuildDate, ttl, guid, item description, pubDate {
display: none;
}
| pageer/lnblog | themes/default/styles/rss.css | CSS | gpl-2.0 | 2,017 |
/*
* kernel/workqueue.c - generic async execution with shared worker pool
*
* Copyright (C) 2002 Ingo Molnar
*
* Derived from the taskqueue/keventd code by:
* David Woodhouse <dwmw2@infradead.org>
* Andrew Morton
* Kai Petzke <wpp@marie.physik.tu-berlin.de>
* Theodore Ts'o <tytso@mit.edu>
*
* Made to use alloc_percpu by Christoph Lameter.
*
* Copyright (C) 2010 SUSE Linux Products GmbH
* Copyright (C) 2010 Tejun Heo <tj@kernel.org>
*
* This is the generic async execution mechanism. Work items as are
* executed in process context. The worker pool is shared and
* automatically managed. There is one worker pool for each CPU and
* one extra for works which are better served by workers which are
* not bound to any specific CPU.
*
* Please read Documentation/workqueue.txt for details.
*/
#include <linux/export.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/init.h>
#include <linux/signal.h>
#include <linux/completion.h>
#include <linux/workqueue.h>
#include <linux/slab.h>
#include <linux/cpu.h>
#include <linux/notifier.h>
#include <linux/kthread.h>
#include <linux/hardirq.h>
#include <linux/mempolicy.h>
#include <linux/freezer.h>
#include <linux/kallsyms.h>
#include <linux/debug_locks.h>
#include <linux/lockdep.h>
#include <linux/idr.h>
#include <linux/jhash.h>
#include <linux/hashtable.h>
#include <linux/rculist.h>
#include <linux/nodemask.h>
#include <linux/moduleparam.h>
#include <linux/uaccess.h>
#include "workqueue_internal.h"
#include <mach/exynos-ss.h>
enum {
/*
* worker_pool flags
*
* A bound pool is either associated or disassociated with its CPU.
* While associated (!DISASSOCIATED), all workers are bound to the
* CPU and none has %WORKER_UNBOUND set and concurrency management
* is in effect.
*
* While DISASSOCIATED, the cpu may be offline and all workers have
* %WORKER_UNBOUND set and concurrency management disabled, and may
* be executing on any CPU. The pool behaves as an unbound one.
*
* Note that DISASSOCIATED should be flipped only while holding
* manager_mutex to avoid changing binding state while
* create_worker() is in progress.
*/
POOL_MANAGE_WORKERS = 1 << 0, /* need to manage workers */
POOL_DISASSOCIATED = 1 << 2, /* cpu can't serve workers */
POOL_FREEZING = 1 << 3, /* freeze in progress */
/* worker flags */
WORKER_STARTED = 1 << 0, /* started */
WORKER_DIE = 1 << 1, /* die die die */
WORKER_IDLE = 1 << 2, /* is idle */
WORKER_PREP = 1 << 3, /* preparing to run works */
WORKER_CPU_INTENSIVE = 1 << 6, /* cpu intensive */
WORKER_UNBOUND = 1 << 7, /* worker is unbound */
WORKER_REBOUND = 1 << 8, /* worker was rebound */
WORKER_NOT_RUNNING = WORKER_PREP | WORKER_CPU_INTENSIVE |
WORKER_UNBOUND | WORKER_REBOUND,
NR_STD_WORKER_POOLS = 2, /* # standard pools per cpu */
UNBOUND_POOL_HASH_ORDER = 6, /* hashed by pool->attrs */
BUSY_WORKER_HASH_ORDER = 6, /* 64 pointers */
MAX_IDLE_WORKERS_RATIO = 4, /* 1/4 of busy can be idle */
IDLE_WORKER_TIMEOUT = 300 * HZ, /* keep idle ones for 5 mins */
MAYDAY_INITIAL_TIMEOUT = HZ / 100 >= 2 ? HZ / 100 : 2,
/* call for help after 10ms
(min two ticks) */
MAYDAY_INTERVAL = HZ / 10, /* and then every 100ms */
CREATE_COOLDOWN = HZ, /* time to breath after fail */
/*
* Rescue workers are used only on emergencies and shared by
* all cpus. Give -20.
*/
RESCUER_NICE_LEVEL = -20,
HIGHPRI_NICE_LEVEL = -20,
WQ_NAME_LEN = 24,
};
/*
* Structure fields follow one of the following exclusion rules.
*
* I: Modifiable by initialization/destruction paths and read-only for
* everyone else.
*
* P: Preemption protected. Disabling preemption is enough and should
* only be modified and accessed from the local cpu.
*
* L: pool->lock protected. Access with pool->lock held.
*
* X: During normal operation, modification requires pool->lock and should
* be done only from local cpu. Either disabling preemption on local
* cpu or grabbing pool->lock is enough for read access. If
* POOL_DISASSOCIATED is set, it's identical to L.
*
* MG: pool->manager_mutex and pool->lock protected. Writes require both
* locks. Reads can happen under either lock.
*
* PL: wq_pool_mutex protected.
*
* PR: wq_pool_mutex protected for writes. Sched-RCU protected for reads.
*
* WQ: wq->mutex protected.
*
* WR: wq->mutex protected for writes. Sched-RCU protected for reads.
*
* MD: wq_mayday_lock protected.
*/
/* struct worker is defined in workqueue_internal.h */
struct worker_pool {
spinlock_t lock; /* the pool lock */
int cpu; /* I: the associated cpu */
int node; /* I: the associated node ID */
int id; /* I: pool ID */
unsigned int flags; /* X: flags */
struct list_head worklist; /* L: list of pending works */
int nr_workers; /* L: total number of workers */
/* nr_idle includes the ones off idle_list for rebinding */
int nr_idle; /* L: currently idle ones */
struct list_head idle_list; /* X: list of idle workers */
struct timer_list idle_timer; /* L: worker idle timeout */
struct timer_list mayday_timer; /* L: SOS timer for workers */
/* a workers is either on busy_hash or idle_list, or the manager */
DECLARE_HASHTABLE(busy_hash, BUSY_WORKER_HASH_ORDER);
/* L: hash of busy workers */
/* see manage_workers() for details on the two manager mutexes */
struct mutex manager_arb; /* manager arbitration */
struct mutex manager_mutex; /* manager exclusion */
struct idr worker_idr; /* MG: worker IDs and iteration */
struct workqueue_attrs *attrs; /* I: worker attributes */
struct hlist_node hash_node; /* PL: unbound_pool_hash node */
int refcnt; /* PL: refcnt for unbound pools */
/*
* The current concurrency level. As it's likely to be accessed
* from other CPUs during try_to_wake_up(), put it in a separate
* cacheline.
*/
atomic_t nr_running ____cacheline_aligned_in_smp;
/*
* Destruction of pool is sched-RCU protected to allow dereferences
* from get_work_pool().
*/
struct rcu_head rcu;
} ____cacheline_aligned_in_smp;
/*
* The per-pool workqueue. While queued, the lower WORK_STRUCT_FLAG_BITS
* of work_struct->data are used for flags and the remaining high bits
* point to the pwq; thus, pwqs need to be aligned at two's power of the
* number of flag bits.
*/
struct pool_workqueue {
struct worker_pool *pool; /* I: the associated pool */
struct workqueue_struct *wq; /* I: the owning workqueue */
int work_color; /* L: current color */
int flush_color; /* L: flushing color */
int refcnt; /* L: reference count */
int nr_in_flight[WORK_NR_COLORS];
/* L: nr of in_flight works */
int nr_active; /* L: nr of active works */
int max_active; /* L: max active works */
struct list_head delayed_works; /* L: delayed works */
struct list_head pwqs_node; /* WR: node on wq->pwqs */
struct list_head mayday_node; /* MD: node on wq->maydays */
/*
* Release of unbound pwq is punted to system_wq. See put_pwq()
* and pwq_unbound_release_workfn() for details. pool_workqueue
* itself is also sched-RCU protected so that the first pwq can be
* determined without grabbing wq->mutex.
*/
struct work_struct unbound_release_work;
struct rcu_head rcu;
} __aligned(1 << WORK_STRUCT_FLAG_BITS);
/*
* Structure used to wait for workqueue flush.
*/
struct wq_flusher {
struct list_head list; /* WQ: list of flushers */
int flush_color; /* WQ: flush color waiting for */
struct completion done; /* flush completion */
};
struct wq_device;
/*
* The externally visible workqueue. It relays the issued work items to
* the appropriate worker_pool through its pool_workqueues.
*/
struct workqueue_struct {
struct list_head pwqs; /* WR: all pwqs of this wq */
struct list_head list; /* PL: list of all workqueues */
struct mutex mutex; /* protects this wq */
int work_color; /* WQ: current work color */
int flush_color; /* WQ: current flush color */
atomic_t nr_pwqs_to_flush; /* flush in progress */
struct wq_flusher *first_flusher; /* WQ: first flusher */
struct list_head flusher_queue; /* WQ: flush waiters */
struct list_head flusher_overflow; /* WQ: flush overflow list */
struct list_head maydays; /* MD: pwqs requesting rescue */
struct worker *rescuer; /* I: rescue worker */
int nr_drainers; /* WQ: drain in progress */
int saved_max_active; /* WQ: saved pwq max_active */
struct workqueue_attrs *unbound_attrs; /* WQ: only for unbound wqs */
struct pool_workqueue *dfl_pwq; /* WQ: only for unbound wqs */
#ifdef CONFIG_SYSFS
struct wq_device *wq_dev; /* I: for sysfs interface */
#endif
#ifdef CONFIG_LOCKDEP
struct lockdep_map lockdep_map;
#endif
char name[WQ_NAME_LEN]; /* I: workqueue name */
/* hot fields used during command issue, aligned to cacheline */
unsigned int flags ____cacheline_aligned; /* WQ: WQ_* flags */
struct pool_workqueue __percpu *cpu_pwqs; /* I: per-cpu pwqs */
struct pool_workqueue __rcu *numa_pwq_tbl[]; /* FR: unbound pwqs indexed by node */
};
static struct kmem_cache *pwq_cache;
static int wq_numa_tbl_len; /* highest possible NUMA node id + 1 */
static cpumask_var_t *wq_numa_possible_cpumask;
/* possible CPUs of each node */
static bool wq_disable_numa;
module_param_named(disable_numa, wq_disable_numa, bool, 0444);
static bool wq_numa_enabled; /* unbound NUMA affinity enabled */
/* buf for wq_update_unbound_numa_attrs(), protected by CPU hotplug exclusion */
static struct workqueue_attrs *wq_update_unbound_numa_attrs_buf;
static DEFINE_MUTEX(wq_pool_mutex); /* protects pools and workqueues list */
static DEFINE_SPINLOCK(wq_mayday_lock); /* protects wq->maydays list */
static LIST_HEAD(workqueues); /* PL: list of all workqueues */
static bool workqueue_freezing; /* PL: have wqs started freezing? */
/* the per-cpu worker pools */
static DEFINE_PER_CPU_SHARED_ALIGNED(struct worker_pool [NR_STD_WORKER_POOLS],
cpu_worker_pools);
static DEFINE_IDR(worker_pool_idr); /* PR: idr of all pools */
/* PL: hash of all unbound pools keyed by pool->attrs */
static DEFINE_HASHTABLE(unbound_pool_hash, UNBOUND_POOL_HASH_ORDER);
/* I: attributes used when instantiating standard unbound pools on demand */
static struct workqueue_attrs *unbound_std_wq_attrs[NR_STD_WORKER_POOLS];
/* I: attributes used when instantiating ordered pools on demand */
static struct workqueue_attrs *ordered_wq_attrs[NR_STD_WORKER_POOLS];
struct workqueue_struct *system_wq __read_mostly;
EXPORT_SYMBOL(system_wq);
struct workqueue_struct *system_highpri_wq __read_mostly;
EXPORT_SYMBOL_GPL(system_highpri_wq);
struct workqueue_struct *system_long_wq __read_mostly;
EXPORT_SYMBOL_GPL(system_long_wq);
struct workqueue_struct *system_unbound_wq __read_mostly;
EXPORT_SYMBOL_GPL(system_unbound_wq);
struct workqueue_struct *system_freezable_wq __read_mostly;
EXPORT_SYMBOL_GPL(system_freezable_wq);
static int worker_thread(void *__worker);
static void copy_workqueue_attrs(struct workqueue_attrs *to,
const struct workqueue_attrs *from);
#define CREATE_TRACE_POINTS
#include <trace/events/workqueue.h>
#define assert_rcu_or_pool_mutex() \
rcu_lockdep_assert(rcu_read_lock_sched_held() || \
lockdep_is_held(&wq_pool_mutex), \
"sched RCU or wq_pool_mutex should be held")
#define assert_rcu_or_wq_mutex(wq) \
rcu_lockdep_assert(rcu_read_lock_sched_held() || \
lockdep_is_held(&wq->mutex), \
"sched RCU or wq->mutex should be held")
#ifdef CONFIG_LOCKDEP
#define assert_manager_or_pool_lock(pool) \
WARN_ONCE(debug_locks && \
!lockdep_is_held(&(pool)->manager_mutex) && \
!lockdep_is_held(&(pool)->lock), \
"pool->manager_mutex or ->lock should be held")
#else
#define assert_manager_or_pool_lock(pool) do { } while (0)
#endif
#define for_each_cpu_worker_pool(pool, cpu) \
for ((pool) = &per_cpu(cpu_worker_pools, cpu)[0]; \
(pool) < &per_cpu(cpu_worker_pools, cpu)[NR_STD_WORKER_POOLS]; \
(pool)++)
/**
* for_each_pool - iterate through all worker_pools in the system
* @pool: iteration cursor
* @pi: integer used for iteration
*
* This must be called either with wq_pool_mutex held or sched RCU read
* locked. If the pool needs to be used beyond the locking in effect, the
* caller is responsible for guaranteeing that the pool stays online.
*
* The if/else clause exists only for the lockdep assertion and can be
* ignored.
*/
#define for_each_pool(pool, pi) \
idr_for_each_entry(&worker_pool_idr, pool, pi) \
if (({ assert_rcu_or_pool_mutex(); false; })) { } \
else
/**
* for_each_pool_worker - iterate through all workers of a worker_pool
* @worker: iteration cursor
* @wi: integer used for iteration
* @pool: worker_pool to iterate workers of
*
* This must be called with either @pool->manager_mutex or ->lock held.
*
* The if/else clause exists only for the lockdep assertion and can be
* ignored.
*/
#define for_each_pool_worker(worker, wi, pool) \
idr_for_each_entry(&(pool)->worker_idr, (worker), (wi)) \
if (({ assert_manager_or_pool_lock((pool)); false; })) { } \
else
/**
* for_each_pwq - iterate through all pool_workqueues of the specified workqueue
* @pwq: iteration cursor
* @wq: the target workqueue
*
* This must be called either with wq->mutex held or sched RCU read locked.
* If the pwq needs to be used beyond the locking in effect, the caller is
* responsible for guaranteeing that the pwq stays online.
*
* The if/else clause exists only for the lockdep assertion and can be
* ignored.
*/
#define for_each_pwq(pwq, wq) \
list_for_each_entry_rcu((pwq), &(wq)->pwqs, pwqs_node) \
if (({ assert_rcu_or_wq_mutex(wq); false; })) { } \
else
#ifdef CONFIG_DEBUG_OBJECTS_WORK
static struct debug_obj_descr work_debug_descr;
static void *work_debug_hint(void *addr)
{
return ((struct work_struct *) addr)->func;
}
/*
* fixup_init is called when:
* - an active object is initialized
*/
static int work_fixup_init(void *addr, enum debug_obj_state state)
{
struct work_struct *work = addr;
switch (state) {
case ODEBUG_STATE_ACTIVE:
cancel_work_sync(work);
debug_object_init(work, &work_debug_descr);
return 1;
default:
return 0;
}
}
/*
* fixup_activate is called when:
* - an active object is activated
* - an unknown object is activated (might be a statically initialized object)
*/
static int work_fixup_activate(void *addr, enum debug_obj_state state)
{
struct work_struct *work = addr;
switch (state) {
case ODEBUG_STATE_NOTAVAILABLE:
/*
* This is not really a fixup. The work struct was
* statically initialized. We just make sure that it
* is tracked in the object tracker.
*/
if (test_bit(WORK_STRUCT_STATIC_BIT, work_data_bits(work))) {
debug_object_init(work, &work_debug_descr);
debug_object_activate(work, &work_debug_descr);
return 0;
}
WARN_ON_ONCE(1);
return 0;
case ODEBUG_STATE_ACTIVE:
WARN_ON(1);
default:
return 0;
}
}
/*
* fixup_free is called when:
* - an active object is freed
*/
static int work_fixup_free(void *addr, enum debug_obj_state state)
{
struct work_struct *work = addr;
switch (state) {
case ODEBUG_STATE_ACTIVE:
cancel_work_sync(work);
debug_object_free(work, &work_debug_descr);
return 1;
default:
return 0;
}
}
static struct debug_obj_descr work_debug_descr = {
.name = "work_struct",
.debug_hint = work_debug_hint,
.fixup_init = work_fixup_init,
.fixup_activate = work_fixup_activate,
.fixup_free = work_fixup_free,
};
static inline void debug_work_activate(struct work_struct *work)
{
debug_object_activate(work, &work_debug_descr);
}
static inline void debug_work_deactivate(struct work_struct *work)
{
debug_object_deactivate(work, &work_debug_descr);
}
void __init_work(struct work_struct *work, int onstack)
{
if (onstack)
debug_object_init_on_stack(work, &work_debug_descr);
else
debug_object_init(work, &work_debug_descr);
}
EXPORT_SYMBOL_GPL(__init_work);
void destroy_work_on_stack(struct work_struct *work)
{
debug_object_free(work, &work_debug_descr);
}
EXPORT_SYMBOL_GPL(destroy_work_on_stack);
#else
static inline void debug_work_activate(struct work_struct *work) { }
static inline void debug_work_deactivate(struct work_struct *work) { }
#endif
/* allocate ID and assign it to @pool */
static int worker_pool_assign_id(struct worker_pool *pool)
{
int ret;
lockdep_assert_held(&wq_pool_mutex);
ret = idr_alloc(&worker_pool_idr, pool, 0, 0, GFP_KERNEL);
if (ret >= 0) {
pool->id = ret;
return 0;
}
return ret;
}
/**
* unbound_pwq_by_node - return the unbound pool_workqueue for the given node
* @wq: the target workqueue
* @node: the node ID
*
* This must be called either with pwq_lock held or sched RCU read locked.
* If the pwq needs to be used beyond the locking in effect, the caller is
* responsible for guaranteeing that the pwq stays online.
*/
static struct pool_workqueue *unbound_pwq_by_node(struct workqueue_struct *wq,
int node)
{
assert_rcu_or_wq_mutex(wq);
return rcu_dereference_raw(wq->numa_pwq_tbl[node]);
}
static unsigned int work_color_to_flags(int color)
{
return color << WORK_STRUCT_COLOR_SHIFT;
}
static int get_work_color(struct work_struct *work)
{
return (*work_data_bits(work) >> WORK_STRUCT_COLOR_SHIFT) &
((1 << WORK_STRUCT_COLOR_BITS) - 1);
}
static int work_next_color(int color)
{
return (color + 1) % WORK_NR_COLORS;
}
/*
* While queued, %WORK_STRUCT_PWQ is set and non flag bits of a work's data
* contain the pointer to the queued pwq. Once execution starts, the flag
* is cleared and the high bits contain OFFQ flags and pool ID.
*
* set_work_pwq(), set_work_pool_and_clear_pending(), mark_work_canceling()
* and clear_work_data() can be used to set the pwq, pool or clear
* work->data. These functions should only be called while the work is
* owned - ie. while the PENDING bit is set.
*
* get_work_pool() and get_work_pwq() can be used to obtain the pool or pwq
* corresponding to a work. Pool is available once the work has been
* queued anywhere after initialization until it is sync canceled. pwq is
* available only while the work item is queued.
*
* %WORK_OFFQ_CANCELING is used to mark a work item which is being
* canceled. While being canceled, a work item may have its PENDING set
* but stay off timer and worklist for arbitrarily long and nobody should
* try to steal the PENDING bit.
*/
static inline void set_work_data(struct work_struct *work, unsigned long data,
unsigned long flags)
{
WARN_ON_ONCE(!work_pending(work));
atomic_long_set(&work->data, data | flags | work_static(work));
}
static void set_work_pwq(struct work_struct *work, struct pool_workqueue *pwq,
unsigned long extra_flags)
{
set_work_data(work, (unsigned long)pwq,
WORK_STRUCT_PENDING | WORK_STRUCT_PWQ | extra_flags);
}
static void set_work_pool_and_keep_pending(struct work_struct *work,
int pool_id)
{
set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT,
WORK_STRUCT_PENDING);
}
static void set_work_pool_and_clear_pending(struct work_struct *work,
int pool_id)
{
/*
* The following wmb is paired with the implied mb in
* test_and_set_bit(PENDING) and ensures all updates to @work made
* here are visible to and precede any updates by the next PENDING
* owner.
*/
smp_wmb();
set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT, 0);
}
static void clear_work_data(struct work_struct *work)
{
smp_wmb(); /* see set_work_pool_and_clear_pending() */
set_work_data(work, WORK_STRUCT_NO_POOL, 0);
}
static struct pool_workqueue *get_work_pwq(struct work_struct *work)
{
unsigned long data = atomic_long_read(&work->data);
if (data & WORK_STRUCT_PWQ)
return (void *)(data & WORK_STRUCT_WQ_DATA_MASK);
else
return NULL;
}
/**
* get_work_pool - return the worker_pool a given work was associated with
* @work: the work item of interest
*
* Return the worker_pool @work was last associated with. %NULL if none.
*
* Pools are created and destroyed under wq_pool_mutex, and allows read
* access under sched-RCU read lock. As such, this function should be
* called under wq_pool_mutex or with preemption disabled.
*
* All fields of the returned pool are accessible as long as the above
* mentioned locking is in effect. If the returned pool needs to be used
* beyond the critical section, the caller is responsible for ensuring the
* returned pool is and stays online.
*/
static struct worker_pool *get_work_pool(struct work_struct *work)
{
unsigned long data = atomic_long_read(&work->data);
int pool_id;
assert_rcu_or_pool_mutex();
if (data & WORK_STRUCT_PWQ)
return ((struct pool_workqueue *)
(data & WORK_STRUCT_WQ_DATA_MASK))->pool;
pool_id = data >> WORK_OFFQ_POOL_SHIFT;
if (pool_id == WORK_OFFQ_POOL_NONE)
return NULL;
return idr_find(&worker_pool_idr, pool_id);
}
/**
* get_work_pool_id - return the worker pool ID a given work is associated with
* @work: the work item of interest
*
* Return the worker_pool ID @work was last associated with.
* %WORK_OFFQ_POOL_NONE if none.
*/
static int get_work_pool_id(struct work_struct *work)
{
unsigned long data = atomic_long_read(&work->data);
if (data & WORK_STRUCT_PWQ)
return ((struct pool_workqueue *)
(data & WORK_STRUCT_WQ_DATA_MASK))->pool->id;
return data >> WORK_OFFQ_POOL_SHIFT;
}
static void mark_work_canceling(struct work_struct *work)
{
unsigned long pool_id = get_work_pool_id(work);
pool_id <<= WORK_OFFQ_POOL_SHIFT;
set_work_data(work, pool_id | WORK_OFFQ_CANCELING, WORK_STRUCT_PENDING);
}
static bool work_is_canceling(struct work_struct *work)
{
unsigned long data = atomic_long_read(&work->data);
return !(data & WORK_STRUCT_PWQ) && (data & WORK_OFFQ_CANCELING);
}
/*
* Policy functions. These define the policies on how the global worker
* pools are managed. Unless noted otherwise, these functions assume that
* they're being called with pool->lock held.
*/
static bool __need_more_worker(struct worker_pool *pool)
{
return !atomic_read(&pool->nr_running);
}
/*
* Need to wake up a worker? Called from anything but currently
* running workers.
*
* Note that, because unbound workers never contribute to nr_running, this
* function will always return %true for unbound pools as long as the
* worklist isn't empty.
*/
static bool need_more_worker(struct worker_pool *pool)
{
return !list_empty(&pool->worklist) && __need_more_worker(pool);
}
/* Can I start working? Called from busy but !running workers. */
static bool may_start_working(struct worker_pool *pool)
{
return pool->nr_idle;
}
/* Do I need to keep working? Called from currently running workers. */
static bool keep_working(struct worker_pool *pool)
{
return !list_empty(&pool->worklist) &&
atomic_read(&pool->nr_running) <= 1;
}
/* Do we need a new worker? Called from manager. */
static bool need_to_create_worker(struct worker_pool *pool)
{
return need_more_worker(pool) && !may_start_working(pool);
}
/* Do I need to be the manager? */
static bool need_to_manage_workers(struct worker_pool *pool)
{
return need_to_create_worker(pool) ||
(pool->flags & POOL_MANAGE_WORKERS);
}
/* Do we have too many workers and should some go away? */
static bool too_many_workers(struct worker_pool *pool)
{
bool managing = mutex_is_locked(&pool->manager_arb);
int nr_idle = pool->nr_idle + managing; /* manager is considered idle */
int nr_busy = pool->nr_workers - nr_idle;
/*
* nr_idle and idle_list may disagree if idle rebinding is in
* progress. Never return %true if idle_list is empty.
*/
if (list_empty(&pool->idle_list))
return false;
return nr_idle > 2 && (nr_idle - 2) * MAX_IDLE_WORKERS_RATIO >= nr_busy;
}
/*
* Wake up functions.
*/
/* Return the first worker. Safe with preemption disabled */
static struct worker *first_worker(struct worker_pool *pool)
{
if (unlikely(list_empty(&pool->idle_list)))
return NULL;
return list_first_entry(&pool->idle_list, struct worker, entry);
}
/**
* wake_up_worker - wake up an idle worker
* @pool: worker pool to wake worker from
*
* Wake up the first idle worker of @pool.
*
* CONTEXT:
* spin_lock_irq(pool->lock).
*/
static void wake_up_worker(struct worker_pool *pool)
{
struct worker *worker = first_worker(pool);
if (likely(worker))
wake_up_process(worker->task);
}
/**
* wq_worker_waking_up - a worker is waking up
* @task: task waking up
* @cpu: CPU @task is waking up to
*
* This function is called during try_to_wake_up() when a worker is
* being awoken.
*
* CONTEXT:
* spin_lock_irq(rq->lock)
*/
void wq_worker_waking_up(struct task_struct *task, int cpu)
{
struct worker *worker = kthread_data(task);
if (!(worker->flags & WORKER_NOT_RUNNING)) {
WARN_ON_ONCE(worker->pool->cpu != cpu);
atomic_inc(&worker->pool->nr_running);
}
}
/**
* wq_worker_sleeping - a worker is going to sleep
* @task: task going to sleep
* @cpu: CPU in question, must be the current CPU number
*
* This function is called during schedule() when a busy worker is
* going to sleep. Worker on the same cpu can be woken up by
* returning pointer to its task.
*
* CONTEXT:
* spin_lock_irq(rq->lock)
*
* RETURNS:
* Worker task on @cpu to wake up, %NULL if none.
*/
struct task_struct *wq_worker_sleeping(struct task_struct *task, int cpu)
{
struct worker *worker = kthread_data(task), *to_wakeup = NULL;
struct worker_pool *pool;
/*
* Rescuers, which may not have all the fields set up like normal
* workers, also reach here, let's not access anything before
* checking NOT_RUNNING.
*/
if (worker->flags & WORKER_NOT_RUNNING)
return NULL;
pool = worker->pool;
/* this can only happen on the local cpu */
if (WARN_ON_ONCE(cpu != raw_smp_processor_id()))
return NULL;
/*
* The counterpart of the following dec_and_test, implied mb,
* worklist not empty test sequence is in insert_work().
* Please read comment there.
*
* NOT_RUNNING is clear. This means that we're bound to and
* running on the local cpu w/ rq lock held and preemption
* disabled, which in turn means that none else could be
* manipulating idle_list, so dereferencing idle_list without pool
* lock is safe.
*/
if (atomic_dec_and_test(&pool->nr_running) &&
!list_empty(&pool->worklist))
to_wakeup = first_worker(pool);
return to_wakeup ? to_wakeup->task : NULL;
}
/**
* worker_set_flags - set worker flags and adjust nr_running accordingly
* @worker: self
* @flags: flags to set
* @wakeup: wakeup an idle worker if necessary
*
* Set @flags in @worker->flags and adjust nr_running accordingly. If
* nr_running becomes zero and @wakeup is %true, an idle worker is
* woken up.
*
* CONTEXT:
* spin_lock_irq(pool->lock)
*/
static inline void worker_set_flags(struct worker *worker, unsigned int flags,
bool wakeup)
{
struct worker_pool *pool = worker->pool;
WARN_ON_ONCE(worker->task != current);
/*
* If transitioning into NOT_RUNNING, adjust nr_running and
* wake up an idle worker as necessary if requested by
* @wakeup.
*/
if ((flags & WORKER_NOT_RUNNING) &&
!(worker->flags & WORKER_NOT_RUNNING)) {
if (wakeup) {
if (atomic_dec_and_test(&pool->nr_running) &&
!list_empty(&pool->worklist))
wake_up_worker(pool);
} else
atomic_dec(&pool->nr_running);
}
worker->flags |= flags;
}
/**
* worker_clr_flags - clear worker flags and adjust nr_running accordingly
* @worker: self
* @flags: flags to clear
*
* Clear @flags in @worker->flags and adjust nr_running accordingly.
*
* CONTEXT:
* spin_lock_irq(pool->lock)
*/
static inline void worker_clr_flags(struct worker *worker, unsigned int flags)
{
struct worker_pool *pool = worker->pool;
unsigned int oflags = worker->flags;
WARN_ON_ONCE(worker->task != current);
worker->flags &= ~flags;
/*
* If transitioning out of NOT_RUNNING, increment nr_running. Note
* that the nested NOT_RUNNING is not a noop. NOT_RUNNING is mask
* of multiple flags, not a single flag.
*/
if ((flags & WORKER_NOT_RUNNING) && (oflags & WORKER_NOT_RUNNING))
if (!(worker->flags & WORKER_NOT_RUNNING))
atomic_inc(&pool->nr_running);
}
/**
* find_worker_executing_work - find worker which is executing a work
* @pool: pool of interest
* @work: work to find worker for
*
* Find a worker which is executing @work on @pool by searching
* @pool->busy_hash which is keyed by the address of @work. For a worker
* to match, its current execution should match the address of @work and
* its work function. This is to avoid unwanted dependency between
* unrelated work executions through a work item being recycled while still
* being executed.
*
* This is a bit tricky. A work item may be freed once its execution
* starts and nothing prevents the freed area from being recycled for
* another work item. If the same work item address ends up being reused
* before the original execution finishes, workqueue will identify the
* recycled work item as currently executing and make it wait until the
* current execution finishes, introducing an unwanted dependency.
*
* This function checks the work item address and work function to avoid
* false positives. Note that this isn't complete as one may construct a
* work function which can introduce dependency onto itself through a
* recycled work item. Well, if somebody wants to shoot oneself in the
* foot that badly, there's only so much we can do, and if such deadlock
* actually occurs, it should be easy to locate the culprit work function.
*
* CONTEXT:
* spin_lock_irq(pool->lock).
*
* RETURNS:
* Pointer to worker which is executing @work if found, NULL
* otherwise.
*/
static struct worker *find_worker_executing_work(struct worker_pool *pool,
struct work_struct *work)
{
struct worker *worker;
hash_for_each_possible(pool->busy_hash, worker, hentry,
(unsigned long)work)
if (worker->current_work == work &&
worker->current_func == work->func)
return worker;
return NULL;
}
/**
* move_linked_works - move linked works to a list
* @work: start of series of works to be scheduled
* @head: target list to append @work to
* @nextp: out paramter for nested worklist walking
*
* Schedule linked works starting from @work to @head. Work series to
* be scheduled starts at @work and includes any consecutive work with
* WORK_STRUCT_LINKED set in its predecessor.
*
* If @nextp is not NULL, it's updated to point to the next work of
* the last scheduled work. This allows move_linked_works() to be
* nested inside outer list_for_each_entry_safe().
*
* CONTEXT:
* spin_lock_irq(pool->lock).
*/
static void move_linked_works(struct work_struct *work, struct list_head *head,
struct work_struct **nextp)
{
struct work_struct *n;
/*
* Linked worklist will always end before the end of the list,
* use NULL for list head.
*/
list_for_each_entry_safe_from(work, n, NULL, entry) {
list_move_tail(&work->entry, head);
if (!(*work_data_bits(work) & WORK_STRUCT_LINKED))
break;
}
/*
* If we're already inside safe list traversal and have moved
* multiple works to the scheduled queue, the next position
* needs to be updated.
*/
if (nextp)
*nextp = n;
}
/**
* get_pwq - get an extra reference on the specified pool_workqueue
* @pwq: pool_workqueue to get
*
* Obtain an extra reference on @pwq. The caller should guarantee that
* @pwq has positive refcnt and be holding the matching pool->lock.
*/
static void get_pwq(struct pool_workqueue *pwq)
{
lockdep_assert_held(&pwq->pool->lock);
WARN_ON_ONCE(pwq->refcnt <= 0);
pwq->refcnt++;
}
/**
* put_pwq - put a pool_workqueue reference
* @pwq: pool_workqueue to put
*
* Drop a reference of @pwq. If its refcnt reaches zero, schedule its
* destruction. The caller should be holding the matching pool->lock.
*/
static void put_pwq(struct pool_workqueue *pwq)
{
lockdep_assert_held(&pwq->pool->lock);
if (likely(--pwq->refcnt))
return;
if (WARN_ON_ONCE(!(pwq->wq->flags & WQ_UNBOUND)))
return;
/*
* @pwq can't be released under pool->lock, bounce to
* pwq_unbound_release_workfn(). This never recurses on the same
* pool->lock as this path is taken only for unbound workqueues and
* the release work item is scheduled on a per-cpu workqueue. To
* avoid lockdep warning, unbound pool->locks are given lockdep
* subclass of 1 in get_unbound_pool().
*/
schedule_work(&pwq->unbound_release_work);
}
/**
* put_pwq_unlocked - put_pwq() with surrounding pool lock/unlock
* @pwq: pool_workqueue to put (can be %NULL)
*
* put_pwq() with locking. This function also allows %NULL @pwq.
*/
static void put_pwq_unlocked(struct pool_workqueue *pwq)
{
if (pwq) {
/*
* As both pwqs and pools are sched-RCU protected, the
* following lock operations are safe.
*/
spin_lock_irq(&pwq->pool->lock);
put_pwq(pwq);
spin_unlock_irq(&pwq->pool->lock);
}
}
static void pwq_activate_delayed_work(struct work_struct *work)
{
struct pool_workqueue *pwq = get_work_pwq(work);
trace_workqueue_activate_work(work);
move_linked_works(work, &pwq->pool->worklist, NULL);
__clear_bit(WORK_STRUCT_DELAYED_BIT, work_data_bits(work));
pwq->nr_active++;
}
static void pwq_activate_first_delayed(struct pool_workqueue *pwq)
{
struct work_struct *work = list_first_entry(&pwq->delayed_works,
struct work_struct, entry);
pwq_activate_delayed_work(work);
}
/**
* pwq_dec_nr_in_flight - decrement pwq's nr_in_flight
* @pwq: pwq of interest
* @color: color of work which left the queue
*
* A work either has completed or is removed from pending queue,
* decrement nr_in_flight of its pwq and handle workqueue flushing.
*
* CONTEXT:
* spin_lock_irq(pool->lock).
*/
static void pwq_dec_nr_in_flight(struct pool_workqueue *pwq, int color)
{
/* uncolored work items don't participate in flushing or nr_active */
if (color == WORK_NO_COLOR)
goto out_put;
pwq->nr_in_flight[color]--;
pwq->nr_active--;
if (!list_empty(&pwq->delayed_works)) {
/* one down, submit a delayed one */
if (pwq->nr_active < pwq->max_active)
pwq_activate_first_delayed(pwq);
}
/* is flush in progress and are we at the flushing tip? */
if (likely(pwq->flush_color != color))
goto out_put;
/* are there still in-flight works? */
if (pwq->nr_in_flight[color])
goto out_put;
/* this pwq is done, clear flush_color */
pwq->flush_color = -1;
/*
* If this was the last pwq, wake up the first flusher. It
* will handle the rest.
*/
if (atomic_dec_and_test(&pwq->wq->nr_pwqs_to_flush))
complete(&pwq->wq->first_flusher->done);
out_put:
put_pwq(pwq);
}
/**
* try_to_grab_pending - steal work item from worklist and disable irq
* @work: work item to steal
* @is_dwork: @work is a delayed_work
* @flags: place to store irq state
*
* Try to grab PENDING bit of @work. This function can handle @work in any
* stable state - idle, on timer or on worklist. Return values are
*
* 1 if @work was pending and we successfully stole PENDING
* 0 if @work was idle and we claimed PENDING
* -EAGAIN if PENDING couldn't be grabbed at the moment, safe to busy-retry
* -ENOENT if someone else is canceling @work, this state may persist
* for arbitrarily long
*
* On >= 0 return, the caller owns @work's PENDING bit. To avoid getting
* interrupted while holding PENDING and @work off queue, irq must be
* disabled on entry. This, combined with delayed_work->timer being
* irqsafe, ensures that we return -EAGAIN for finite short period of time.
*
* On successful return, >= 0, irq is disabled and the caller is
* responsible for releasing it using local_irq_restore(*@flags).
*
* This function is safe to call from any context including IRQ handler.
*/
static int try_to_grab_pending(struct work_struct *work, bool is_dwork,
unsigned long *flags)
{
struct worker_pool *pool;
struct pool_workqueue *pwq;
local_irq_save(*flags);
/* try to steal the timer if it exists */
if (is_dwork) {
struct delayed_work *dwork = to_delayed_work(work);
/*
* dwork->timer is irqsafe. If del_timer() fails, it's
* guaranteed that the timer is not queued anywhere and not
* running on the local CPU.
*/
if (likely(del_timer(&dwork->timer)))
return 1;
}
/* try to claim PENDING the normal way */
if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)))
return 0;
/*
* The queueing is in progress, or it is already queued. Try to
* steal it from ->worklist without clearing WORK_STRUCT_PENDING.
*/
pool = get_work_pool(work);
if (!pool)
goto fail;
spin_lock(&pool->lock);
/*
* work->data is guaranteed to point to pwq only while the work
* item is queued on pwq->wq, and both updating work->data to point
* to pwq on queueing and to pool on dequeueing are done under
* pwq->pool->lock. This in turn guarantees that, if work->data
* points to pwq which is associated with a locked pool, the work
* item is currently queued on that pool.
*/
pwq = get_work_pwq(work);
if (pwq && pwq->pool == pool) {
debug_work_deactivate(work);
/*
* A delayed work item cannot be grabbed directly because
* it might have linked NO_COLOR work items which, if left
* on the delayed_list, will confuse pwq->nr_active
* management later on and cause stall. Make sure the work
* item is activated before grabbing.
*/
if (*work_data_bits(work) & WORK_STRUCT_DELAYED)
pwq_activate_delayed_work(work);
list_del_init(&work->entry);
pwq_dec_nr_in_flight(get_work_pwq(work), get_work_color(work));
/* work->data points to pwq iff queued, point to pool */
set_work_pool_and_keep_pending(work, pool->id);
spin_unlock(&pool->lock);
return 1;
}
spin_unlock(&pool->lock);
fail:
local_irq_restore(*flags);
if (work_is_canceling(work))
return -ENOENT;
cpu_relax();
return -EAGAIN;
}
/**
* insert_work - insert a work into a pool
* @pwq: pwq @work belongs to
* @work: work to insert
* @head: insertion point
* @extra_flags: extra WORK_STRUCT_* flags to set
*
* Insert @work which belongs to @pwq after @head. @extra_flags is or'd to
* work_struct flags.
*
* CONTEXT:
* spin_lock_irq(pool->lock).
*/
static void insert_work(struct pool_workqueue *pwq, struct work_struct *work,
struct list_head *head, unsigned int extra_flags)
{
struct worker_pool *pool = pwq->pool;
/* we own @work, set data and link */
set_work_pwq(work, pwq, extra_flags);
list_add_tail(&work->entry, head);
get_pwq(pwq);
/*
* Ensure either wq_worker_sleeping() sees the above
* list_add_tail() or we see zero nr_running to avoid workers lying
* around lazily while there are works to be processed.
*/
smp_mb();
if (__need_more_worker(pool))
wake_up_worker(pool);
}
/*
* Test whether @work is being queued from another work executing on the
* same workqueue.
*/
static bool is_chained_work(struct workqueue_struct *wq)
{
struct worker *worker;
worker = current_wq_worker();
/*
* Return %true iff I'm a worker execuing a work item on @wq. If
* I'm @worker, it's safe to dereference it without locking.
*/
return worker && worker->current_pwq->wq == wq;
}
static void __queue_work(int cpu, struct workqueue_struct *wq,
struct work_struct *work)
{
struct pool_workqueue *pwq;
struct worker_pool *last_pool;
struct list_head *worklist;
unsigned int work_flags;
unsigned int req_cpu = cpu;
/*
* While a work item is PENDING && off queue, a task trying to
* steal the PENDING will busy-loop waiting for it to either get
* queued or lose PENDING. Grabbing PENDING and queueing should
* happen with IRQ disabled.
*/
WARN_ON_ONCE(!irqs_disabled());
debug_work_activate(work);
/* if dying, only works from the same workqueue are allowed */
if (unlikely(wq->flags & __WQ_DRAINING) &&
WARN_ON_ONCE(!is_chained_work(wq)))
return;
retry:
if (req_cpu == WORK_CPU_UNBOUND)
cpu = raw_smp_processor_id();
/* pwq which will be used unless @work is executing elsewhere */
if (!(wq->flags & WQ_UNBOUND))
pwq = per_cpu_ptr(wq->cpu_pwqs, cpu);
else
pwq = unbound_pwq_by_node(wq, cpu_to_node(cpu));
/*
* If @work was previously on a different pool, it might still be
* running there, in which case the work needs to be queued on that
* pool to guarantee non-reentrancy.
*/
last_pool = get_work_pool(work);
if (last_pool && last_pool != pwq->pool) {
struct worker *worker;
spin_lock(&last_pool->lock);
worker = find_worker_executing_work(last_pool, work);
if (worker && worker->current_pwq->wq == wq) {
pwq = worker->current_pwq;
} else {
/* meh... not running there, queue here */
spin_unlock(&last_pool->lock);
spin_lock(&pwq->pool->lock);
}
} else {
spin_lock(&pwq->pool->lock);
}
/*
* pwq is determined and locked. For unbound pools, we could have
* raced with pwq release and it could already be dead. If its
* refcnt is zero, repeat pwq selection. Note that pwqs never die
* without another pwq replacing it in the numa_pwq_tbl or while
* work items are executing on it, so the retrying is guaranteed to
* make forward-progress.
*/
if (unlikely(!pwq->refcnt)) {
if (wq->flags & WQ_UNBOUND) {
spin_unlock(&pwq->pool->lock);
cpu_relax();
goto retry;
}
/* oops */
WARN_ONCE(true, "workqueue: per-cpu pwq for %s on cpu%d has 0 refcnt",
wq->name, cpu);
}
/* pwq determined, queue */
trace_workqueue_queue_work(req_cpu, pwq, work);
if (WARN_ON(!list_empty(&work->entry))) {
spin_unlock(&pwq->pool->lock);
return;
}
pwq->nr_in_flight[pwq->work_color]++;
work_flags = work_color_to_flags(pwq->work_color);
if (likely(pwq->nr_active < pwq->max_active)) {
trace_workqueue_activate_work(work);
pwq->nr_active++;
worklist = &pwq->pool->worklist;
} else {
work_flags |= WORK_STRUCT_DELAYED;
worklist = &pwq->delayed_works;
}
insert_work(pwq, work, worklist, work_flags);
spin_unlock(&pwq->pool->lock);
}
/**
* queue_work_on - queue work on specific cpu
* @cpu: CPU number to execute work on
* @wq: workqueue to use
* @work: work to queue
*
* Returns %false if @work was already on a queue, %true otherwise.
*
* We queue the work to a specific CPU, the caller must ensure it
* can't go away.
*/
bool queue_work_on(int cpu, struct workqueue_struct *wq,
struct work_struct *work)
{
bool ret = false;
unsigned long flags;
local_irq_save(flags);
if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
__queue_work(cpu, wq, work);
ret = true;
}
local_irq_restore(flags);
return ret;
}
EXPORT_SYMBOL(queue_work_on);
void delayed_work_timer_fn(unsigned long __data)
{
struct delayed_work *dwork = (struct delayed_work *)__data;
/* should have been called from irqsafe timer with irq already off */
__queue_work(dwork->cpu, dwork->wq, &dwork->work);
}
EXPORT_SYMBOL(delayed_work_timer_fn);
static void __queue_delayed_work(int cpu, struct workqueue_struct *wq,
struct delayed_work *dwork, unsigned long delay)
{
struct timer_list *timer = &dwork->timer;
struct work_struct *work = &dwork->work;
WARN_ON_ONCE(timer->function != delayed_work_timer_fn ||
timer->data != (unsigned long)dwork);
WARN_ON_ONCE(timer_pending(timer));
WARN_ON_ONCE(!list_empty(&work->entry));
/*
* If @delay is 0, queue @dwork->work immediately. This is for
* both optimization and correctness. The earliest @timer can
* expire is on the closest next tick and delayed_work users depend
* on that there's no such delay when @delay is 0.
*/
if (!delay) {
__queue_work(cpu, wq, &dwork->work);
return;
}
timer_stats_timer_set_start_info(&dwork->timer);
dwork->wq = wq;
dwork->cpu = cpu;
timer->expires = jiffies + delay;
if (unlikely(cpu != WORK_CPU_UNBOUND))
add_timer_on(timer, cpu);
else
add_timer(timer);
}
/**
* queue_delayed_work_on - queue work on specific CPU after delay
* @cpu: CPU number to execute work on
* @wq: workqueue to use
* @dwork: work to queue
* @delay: number of jiffies to wait before queueing
*
* Returns %false if @work was already on a queue, %true otherwise. If
* @delay is zero and @dwork is idle, it will be scheduled for immediate
* execution.
*/
bool queue_delayed_work_on(int cpu, struct workqueue_struct *wq,
struct delayed_work *dwork, unsigned long delay)
{
struct work_struct *work = &dwork->work;
bool ret = false;
unsigned long flags;
/* read the comment in __queue_work() */
local_irq_save(flags);
if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
__queue_delayed_work(cpu, wq, dwork, delay);
ret = true;
}
local_irq_restore(flags);
return ret;
}
EXPORT_SYMBOL(queue_delayed_work_on);
/**
* mod_delayed_work_on - modify delay of or queue a delayed work on specific CPU
* @cpu: CPU number to execute work on
* @wq: workqueue to use
* @dwork: work to queue
* @delay: number of jiffies to wait before queueing
*
* If @dwork is idle, equivalent to queue_delayed_work_on(); otherwise,
* modify @dwork's timer so that it expires after @delay. If @delay is
* zero, @work is guaranteed to be scheduled immediately regardless of its
* current state.
*
* Returns %false if @dwork was idle and queued, %true if @dwork was
* pending and its timer was modified.
*
* This function is safe to call from any context including IRQ handler.
* See try_to_grab_pending() for details.
*/
bool mod_delayed_work_on(int cpu, struct workqueue_struct *wq,
struct delayed_work *dwork, unsigned long delay)
{
unsigned long flags;
int ret;
do {
ret = try_to_grab_pending(&dwork->work, true, &flags);
} while (unlikely(ret == -EAGAIN));
if (likely(ret >= 0)) {
__queue_delayed_work(cpu, wq, dwork, delay);
local_irq_restore(flags);
}
/* -ENOENT from try_to_grab_pending() becomes %true */
return ret;
}
EXPORT_SYMBOL_GPL(mod_delayed_work_on);
/**
* worker_enter_idle - enter idle state
* @worker: worker which is entering idle state
*
* @worker is entering idle state. Update stats and idle timer if
* necessary.
*
* LOCKING:
* spin_lock_irq(pool->lock).
*/
static void worker_enter_idle(struct worker *worker)
{
struct worker_pool *pool = worker->pool;
if (WARN_ON_ONCE(worker->flags & WORKER_IDLE) ||
WARN_ON_ONCE(!list_empty(&worker->entry) &&
(worker->hentry.next || worker->hentry.pprev)))
return;
/* can't use worker_set_flags(), also called from start_worker() */
worker->flags |= WORKER_IDLE;
pool->nr_idle++;
worker->last_active = jiffies;
/* idle_list is LIFO */
list_add(&worker->entry, &pool->idle_list);
if (too_many_workers(pool) && !timer_pending(&pool->idle_timer))
mod_timer(&pool->idle_timer, jiffies + IDLE_WORKER_TIMEOUT);
/*
* Sanity check nr_running. Because wq_unbind_fn() releases
* pool->lock between setting %WORKER_UNBOUND and zapping
* nr_running, the warning may trigger spuriously. Check iff
* unbind is not in progress.
*/
WARN_ON_ONCE(!(pool->flags & POOL_DISASSOCIATED) &&
pool->nr_workers == pool->nr_idle &&
atomic_read(&pool->nr_running));
}
/**
* worker_leave_idle - leave idle state
* @worker: worker which is leaving idle state
*
* @worker is leaving idle state. Update stats.
*
* LOCKING:
* spin_lock_irq(pool->lock).
*/
static void worker_leave_idle(struct worker *worker)
{
struct worker_pool *pool = worker->pool;
if (WARN_ON_ONCE(!(worker->flags & WORKER_IDLE)))
return;
worker_clr_flags(worker, WORKER_IDLE);
pool->nr_idle--;
list_del_init(&worker->entry);
}
/**
* worker_maybe_bind_and_lock - try to bind %current to worker_pool and lock it
* @pool: target worker_pool
*
* Bind %current to the cpu of @pool if it is associated and lock @pool.
*
* Works which are scheduled while the cpu is online must at least be
* scheduled to a worker which is bound to the cpu so that if they are
* flushed from cpu callbacks while cpu is going down, they are
* guaranteed to execute on the cpu.
*
* This function is to be used by unbound workers and rescuers to bind
* themselves to the target cpu and may race with cpu going down or
* coming online. kthread_bind() can't be used because it may put the
* worker to already dead cpu and set_cpus_allowed_ptr() can't be used
* verbatim as it's best effort and blocking and pool may be
* [dis]associated in the meantime.
*
* This function tries set_cpus_allowed() and locks pool and verifies the
* binding against %POOL_DISASSOCIATED which is set during
* %CPU_DOWN_PREPARE and cleared during %CPU_ONLINE, so if the worker
* enters idle state or fetches works without dropping lock, it can
* guarantee the scheduling requirement described in the first paragraph.
*
* CONTEXT:
* Might sleep. Called without any lock but returns with pool->lock
* held.
*
* RETURNS:
* %true if the associated pool is online (@worker is successfully
* bound), %false if offline.
*/
static bool worker_maybe_bind_and_lock(struct worker_pool *pool)
__acquires(&pool->lock)
{
while (true) {
/*
* The following call may fail, succeed or succeed
* without actually migrating the task to the cpu if
* it races with cpu hotunplug operation. Verify
* against POOL_DISASSOCIATED.
*/
if (!(pool->flags & POOL_DISASSOCIATED))
set_cpus_allowed_ptr(current, pool->attrs->cpumask);
spin_lock_irq(&pool->lock);
if (pool->flags & POOL_DISASSOCIATED)
return false;
if (task_cpu(current) == pool->cpu &&
cpumask_equal(¤t->cpus_allowed, pool->attrs->cpumask))
return true;
spin_unlock_irq(&pool->lock);
/*
* We've raced with CPU hot[un]plug. Give it a breather
* and retry migration. cond_resched() is required here;
* otherwise, we might deadlock against cpu_stop trying to
* bring down the CPU on non-preemptive kernel.
*/
cpu_relax();
cond_resched();
}
}
static struct worker *alloc_worker(void)
{
struct worker *worker;
worker = kzalloc(sizeof(*worker), GFP_KERNEL);
if (worker) {
INIT_LIST_HEAD(&worker->entry);
INIT_LIST_HEAD(&worker->scheduled);
/* on creation a worker is in !idle && prep state */
worker->flags = WORKER_PREP;
}
return worker;
}
/**
* create_worker - create a new workqueue worker
* @pool: pool the new worker will belong to
*
* Create a new worker which is bound to @pool. The returned worker
* can be started by calling start_worker() or destroyed using
* destroy_worker().
*
* CONTEXT:
* Might sleep. Does GFP_KERNEL allocations.
*
* RETURNS:
* Pointer to the newly created worker.
*/
static struct worker *create_worker(struct worker_pool *pool)
{
struct worker *worker = NULL;
int id = -1;
char id_buf[16];
lockdep_assert_held(&pool->manager_mutex);
/*
* ID is needed to determine kthread name. Allocate ID first
* without installing the pointer.
*/
idr_preload(GFP_KERNEL);
spin_lock_irq(&pool->lock);
id = idr_alloc(&pool->worker_idr, NULL, 0, 0, GFP_NOWAIT);
spin_unlock_irq(&pool->lock);
idr_preload_end();
if (id < 0)
goto fail;
worker = alloc_worker();
if (!worker)
goto fail;
worker->pool = pool;
worker->id = id;
if (pool->cpu >= 0)
snprintf(id_buf, sizeof(id_buf), "%d:%d%s", pool->cpu, id,
pool->attrs->nice < 0 ? "H" : "");
else
snprintf(id_buf, sizeof(id_buf), "u%d:%d", pool->id, id);
worker->task = kthread_create_on_node(worker_thread, worker, pool->node,
"kworker/%s", id_buf);
if (IS_ERR(worker->task))
goto fail;
/*
* set_cpus_allowed_ptr() will fail if the cpumask doesn't have any
* online CPUs. It'll be re-applied when any of the CPUs come up.
*/
set_user_nice(worker->task, pool->attrs->nice);
set_cpus_allowed_ptr(worker->task, pool->attrs->cpumask);
/* prevent userland from meddling with cpumask of workqueue workers */
worker->task->flags |= PF_NO_SETAFFINITY;
/*
* The caller is responsible for ensuring %POOL_DISASSOCIATED
* remains stable across this function. See the comments above the
* flag definition for details.
*/
if (pool->flags & POOL_DISASSOCIATED)
worker->flags |= WORKER_UNBOUND;
/* successful, commit the pointer to idr */
spin_lock_irq(&pool->lock);
idr_replace(&pool->worker_idr, worker, worker->id);
spin_unlock_irq(&pool->lock);
return worker;
fail:
if (id >= 0) {
spin_lock_irq(&pool->lock);
idr_remove(&pool->worker_idr, id);
spin_unlock_irq(&pool->lock);
}
kfree(worker);
return NULL;
}
/**
* start_worker - start a newly created worker
* @worker: worker to start
*
* Make the pool aware of @worker and start it.
*
* CONTEXT:
* spin_lock_irq(pool->lock).
*/
static void start_worker(struct worker *worker)
{
worker->flags |= WORKER_STARTED;
worker->pool->nr_workers++;
worker_enter_idle(worker);
wake_up_process(worker->task);
}
/**
* create_and_start_worker - create and start a worker for a pool
* @pool: the target pool
*
* Grab the managership of @pool and create and start a new worker for it.
*/
static int create_and_start_worker(struct worker_pool *pool)
{
struct worker *worker;
mutex_lock(&pool->manager_mutex);
worker = create_worker(pool);
if (worker) {
spin_lock_irq(&pool->lock);
start_worker(worker);
spin_unlock_irq(&pool->lock);
}
mutex_unlock(&pool->manager_mutex);
return worker ? 0 : -ENOMEM;
}
/**
* destroy_worker - destroy a workqueue worker
* @worker: worker to be destroyed
*
* Destroy @worker and adjust @pool stats accordingly.
*
* CONTEXT:
* spin_lock_irq(pool->lock) which is released and regrabbed.
*/
static void destroy_worker(struct worker *worker)
{
struct worker_pool *pool = worker->pool;
lockdep_assert_held(&pool->manager_mutex);
lockdep_assert_held(&pool->lock);
/* sanity check frenzy */
if (WARN_ON(worker->current_work) ||
WARN_ON(!list_empty(&worker->scheduled)))
return;
if (worker->flags & WORKER_STARTED)
pool->nr_workers--;
if (worker->flags & WORKER_IDLE)
pool->nr_idle--;
/*
* Once WORKER_DIE is set, the kworker may destroy itself at any
* point. Pin to ensure the task stays until we're done with it.
*/
get_task_struct(worker->task);
list_del_init(&worker->entry);
worker->flags |= WORKER_DIE;
idr_remove(&pool->worker_idr, worker->id);
spin_unlock_irq(&pool->lock);
kthread_stop(worker->task);
put_task_struct(worker->task);
kfree(worker);
spin_lock_irq(&pool->lock);
}
static void idle_worker_timeout(unsigned long __pool)
{
struct worker_pool *pool = (void *)__pool;
spin_lock_irq(&pool->lock);
if (too_many_workers(pool)) {
struct worker *worker;
unsigned long expires;
/* idle_list is kept in LIFO order, check the last one */
worker = list_entry(pool->idle_list.prev, struct worker, entry);
expires = worker->last_active + IDLE_WORKER_TIMEOUT;
if (time_before(jiffies, expires))
mod_timer(&pool->idle_timer, expires);
else {
/* it's been idle for too long, wake up manager */
pool->flags |= POOL_MANAGE_WORKERS;
wake_up_worker(pool);
}
}
spin_unlock_irq(&pool->lock);
}
static void send_mayday(struct work_struct *work)
{
struct pool_workqueue *pwq = get_work_pwq(work);
struct workqueue_struct *wq = pwq->wq;
lockdep_assert_held(&wq_mayday_lock);
if (!wq->rescuer)
return;
/* mayday mayday mayday */
if (list_empty(&pwq->mayday_node)) {
/*
* If @pwq is for an unbound wq, its base ref may be put at
* any time due to an attribute change. Pin @pwq until the
* rescuer is done with it.
*/
get_pwq(pwq);
list_add_tail(&pwq->mayday_node, &wq->maydays);
wake_up_process(wq->rescuer->task);
}
}
static void pool_mayday_timeout(unsigned long __pool)
{
struct worker_pool *pool = (void *)__pool;
struct work_struct *work;
spin_lock_irq(&wq_mayday_lock); /* for wq->maydays */
spin_lock(&pool->lock);
if (need_to_create_worker(pool)) {
/*
* We've been trying to create a new worker but
* haven't been successful. We might be hitting an
* allocation deadlock. Send distress signals to
* rescuers.
*/
list_for_each_entry(work, &pool->worklist, entry)
send_mayday(work);
}
spin_unlock(&pool->lock);
spin_unlock_irq(&wq_mayday_lock);
mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INTERVAL);
}
/**
* maybe_create_worker - create a new worker if necessary
* @pool: pool to create a new worker for
*
* Create a new worker for @pool if necessary. @pool is guaranteed to
* have at least one idle worker on return from this function. If
* creating a new worker takes longer than MAYDAY_INTERVAL, mayday is
* sent to all rescuers with works scheduled on @pool to resolve
* possible allocation deadlock.
*
* On return, need_to_create_worker() is guaranteed to be %false and
* may_start_working() %true.
*
* LOCKING:
* spin_lock_irq(pool->lock) which may be released and regrabbed
* multiple times. Does GFP_KERNEL allocations. Called only from
* manager.
*/
static void maybe_create_worker(struct worker_pool *pool)
__releases(&pool->lock)
__acquires(&pool->lock)
{
if (!need_to_create_worker(pool))
return;
restart:
spin_unlock_irq(&pool->lock);
/* if we don't make progress in MAYDAY_INITIAL_TIMEOUT, call for help */
mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INITIAL_TIMEOUT);
while (true) {
struct worker *worker;
worker = create_worker(pool);
if (worker) {
del_timer_sync(&pool->mayday_timer);
spin_lock_irq(&pool->lock);
start_worker(worker);
if (WARN_ON_ONCE(need_to_create_worker(pool)))
goto restart;
return;
}
if (!need_to_create_worker(pool))
break;
__set_current_state(TASK_INTERRUPTIBLE);
schedule_timeout(CREATE_COOLDOWN);
if (!need_to_create_worker(pool))
break;
}
del_timer_sync(&pool->mayday_timer);
spin_lock_irq(&pool->lock);
if (need_to_create_worker(pool))
goto restart;
return;
}
/**
* maybe_destroy_worker - destroy workers which have been idle for a while
* @pool: pool to destroy workers for
*
* Destroy @pool workers which have been idle for longer than
* IDLE_WORKER_TIMEOUT.
*
* LOCKING:
* spin_lock_irq(pool->lock) which may be released and regrabbed
* multiple times. Called only from manager.
*/
static void maybe_destroy_workers(struct worker_pool *pool)
{
while (too_many_workers(pool)) {
struct worker *worker;
unsigned long expires;
worker = list_entry(pool->idle_list.prev, struct worker, entry);
expires = worker->last_active + IDLE_WORKER_TIMEOUT;
if (time_before(jiffies, expires)) {
mod_timer(&pool->idle_timer, expires);
break;
}
destroy_worker(worker);
}
}
/**
* manage_workers - manage worker pool
* @worker: self
*
* Assume the manager role and manage the worker pool @worker belongs
* to. At any given time, there can be only zero or one manager per
* pool. The exclusion is handled automatically by this function.
*
* The caller can safely start processing works on false return. On
* true return, it's guaranteed that need_to_create_worker() is false
* and may_start_working() is true.
*
* CONTEXT:
* spin_lock_irq(pool->lock) which may be released and regrabbed
* multiple times. Does GFP_KERNEL allocations.
*
* RETURNS:
* %false if the pool doesn't need management and the caller can safely
* start processing works, %true if management function was performed and
* the conditions that the caller verified before calling the function may
* no longer be true.
*/
static bool manage_workers(struct worker *worker)
{
struct worker_pool *pool = worker->pool;
/*
* Managership is governed by two mutexes - manager_arb and
* manager_mutex. manager_arb handles arbitration of manager role.
* Anyone who successfully grabs manager_arb wins the arbitration
* and becomes the manager. mutex_trylock() on pool->manager_arb
* failure while holding pool->lock reliably indicates that someone
* else is managing the pool and the worker which failed trylock
* can proceed to executing work items. This means that anyone
* grabbing manager_arb is responsible for actually performing
* manager duties. If manager_arb is grabbed and released without
* actual management, the pool may stall indefinitely.
*
* manager_mutex is used for exclusion of actual management
* operations. The holder of manager_mutex can be sure that none
* of management operations, including creation and destruction of
* workers, won't take place until the mutex is released. Because
* manager_mutex doesn't interfere with manager role arbitration,
* it is guaranteed that the pool's management, while may be
* delayed, won't be disturbed by someone else grabbing
* manager_mutex.
*/
if (!mutex_trylock(&pool->manager_arb))
return false;
/*
* With manager arbitration won, manager_mutex would be free in
* most cases. trylock first without dropping @pool->lock.
*/
if (unlikely(!mutex_trylock(&pool->manager_mutex))) {
spin_unlock_irq(&pool->lock);
mutex_lock(&pool->manager_mutex);
spin_lock_irq(&pool->lock);
}
pool->flags &= ~POOL_MANAGE_WORKERS;
/*
* Destroy and then create so that may_start_working() is true
* on return.
*/
maybe_destroy_workers(pool);
maybe_create_worker(pool);
mutex_unlock(&pool->manager_mutex);
mutex_unlock(&pool->manager_arb);
return true;
}
/**
* process_one_work - process single work
* @worker: self
* @work: work to process
*
* Process @work. This function contains all the logics necessary to
* process a single work including synchronization against and
* interaction with other workers on the same cpu, queueing and
* flushing. As long as context requirement is met, any worker can
* call this function to process a work.
*
* CONTEXT:
* spin_lock_irq(pool->lock) which is released and regrabbed.
*/
static void process_one_work(struct worker *worker, struct work_struct *work)
__releases(&pool->lock)
__acquires(&pool->lock)
{
struct pool_workqueue *pwq = get_work_pwq(work);
struct worker_pool *pool = worker->pool;
bool cpu_intensive = pwq->wq->flags & WQ_CPU_INTENSIVE;
int work_color;
struct worker *collision;
#ifdef CONFIG_LOCKDEP
/*
* It is permissible to free the struct work_struct from
* inside the function that is called from it, this we need to
* take into account for lockdep too. To avoid bogus "held
* lock freed" warnings as well as problems when looking into
* work->lockdep_map, make a copy and use that here.
*/
struct lockdep_map lockdep_map;
lockdep_copy_map(&lockdep_map, &work->lockdep_map);
#endif
/*
* Ensure we're on the correct CPU. DISASSOCIATED test is
* necessary to avoid spurious warnings from rescuers servicing the
* unbound or a disassociated pool.
*/
WARN_ON_ONCE(!(worker->flags & WORKER_UNBOUND) &&
!(pool->flags & POOL_DISASSOCIATED) &&
raw_smp_processor_id() != pool->cpu);
/*
* A single work shouldn't be executed concurrently by
* multiple workers on a single cpu. Check whether anyone is
* already processing the work. If so, defer the work to the
* currently executing one.
*/
collision = find_worker_executing_work(pool, work);
if (unlikely(collision)) {
move_linked_works(work, &collision->scheduled, NULL);
return;
}
/* claim and dequeue */
debug_work_deactivate(work);
hash_add(pool->busy_hash, &worker->hentry, (unsigned long)work);
worker->current_work = work;
worker->current_func = work->func;
worker->current_pwq = pwq;
work_color = get_work_color(work);
list_del_init(&work->entry);
/*
* CPU intensive works don't participate in concurrency
* management. They're the scheduler's responsibility.
*/
if (unlikely(cpu_intensive))
worker_set_flags(worker, WORKER_CPU_INTENSIVE, true);
/*
* Unbound pool isn't concurrency managed and work items should be
* executed ASAP. Wake up another worker if necessary.
*/
if ((worker->flags & WORKER_UNBOUND) && need_more_worker(pool))
wake_up_worker(pool);
/*
* Record the last pool and clear PENDING which should be the last
* update to @work. Also, do this inside @pool->lock so that
* PENDING and queued state changes happen together while IRQ is
* disabled.
*/
set_work_pool_and_clear_pending(work, pool->id);
spin_unlock_irq(&pool->lock);
lock_map_acquire_read(&pwq->wq->lockdep_map);
lock_map_acquire(&lockdep_map);
trace_workqueue_execute_start(work);
exynos_ss_work(worker, work, work->func, ESS_FLAG_IN);
worker->current_func(work);
exynos_ss_work(worker, work, work->func, ESS_FLAG_OUT);
/*
* While we must be careful to not use "work" after this, the trace
* point will only record its address.
*/
trace_workqueue_execute_end(work);
lock_map_release(&lockdep_map);
lock_map_release(&pwq->wq->lockdep_map);
if (unlikely(in_atomic() || lockdep_depth(current) > 0)) {
pr_err("BUG: workqueue leaked lock or atomic: %s/0x%08x/%d\n"
" last function: %pf\n",
current->comm, preempt_count(), task_pid_nr(current),
worker->current_func);
debug_show_held_locks(current);
dump_stack();
}
/*
* The following prevents a kworker from hogging CPU on !PREEMPT
* kernels, where a requeueing work item waiting for something to
* happen could deadlock with stop_machine as such work item could
* indefinitely requeue itself while all other CPUs are trapped in
* stop_machine.
*/
cond_resched();
spin_lock_irq(&pool->lock);
/* clear cpu intensive status */
if (unlikely(cpu_intensive))
worker_clr_flags(worker, WORKER_CPU_INTENSIVE);
/* we're done with it, release */
hash_del(&worker->hentry);
worker->current_work = NULL;
worker->current_func = NULL;
worker->current_pwq = NULL;
worker->desc_valid = false;
pwq_dec_nr_in_flight(pwq, work_color);
}
/**
* process_scheduled_works - process scheduled works
* @worker: self
*
* Process all scheduled works. Please note that the scheduled list
* may change while processing a work, so this function repeatedly
* fetches a work from the top and executes it.
*
* CONTEXT:
* spin_lock_irq(pool->lock) which may be released and regrabbed
* multiple times.
*/
static void process_scheduled_works(struct worker *worker)
{
while (!list_empty(&worker->scheduled)) {
struct work_struct *work = list_first_entry(&worker->scheduled,
struct work_struct, entry);
process_one_work(worker, work);
}
}
/**
* worker_thread - the worker thread function
* @__worker: self
*
* The worker thread function. All workers belong to a worker_pool -
* either a per-cpu one or dynamic unbound one. These workers process all
* work items regardless of their specific target workqueue. The only
* exception is work items which belong to workqueues with a rescuer which
* will be explained in rescuer_thread().
*/
static int worker_thread(void *__worker)
{
struct worker *worker = __worker;
struct worker_pool *pool = worker->pool;
/* tell the scheduler that this is a workqueue worker */
worker->task->flags |= PF_WQ_WORKER;
woke_up:
spin_lock_irq(&pool->lock);
/* am I supposed to die? */
if (unlikely(worker->flags & WORKER_DIE)) {
spin_unlock_irq(&pool->lock);
WARN_ON_ONCE(!list_empty(&worker->entry));
worker->task->flags &= ~PF_WQ_WORKER;
return 0;
}
worker_leave_idle(worker);
recheck:
/* no more worker necessary? */
if (!need_more_worker(pool))
goto sleep;
/* do we need to manage? */
if (unlikely(!may_start_working(pool)) && manage_workers(worker))
goto recheck;
/*
* ->scheduled list can only be filled while a worker is
* preparing to process a work or actually processing it.
* Make sure nobody diddled with it while I was sleeping.
*/
WARN_ON_ONCE(!list_empty(&worker->scheduled));
/*
* Finish PREP stage. We're guaranteed to have at least one idle
* worker or that someone else has already assumed the manager
* role. This is where @worker starts participating in concurrency
* management if applicable and concurrency management is restored
* after being rebound. See rebind_workers() for details.
*/
worker_clr_flags(worker, WORKER_PREP | WORKER_REBOUND);
do {
struct work_struct *work =
list_first_entry(&pool->worklist,
struct work_struct, entry);
if (likely(!(*work_data_bits(work) & WORK_STRUCT_LINKED))) {
/* optimization path, not strictly necessary */
process_one_work(worker, work);
if (unlikely(!list_empty(&worker->scheduled)))
process_scheduled_works(worker);
} else {
move_linked_works(work, &worker->scheduled, NULL);
process_scheduled_works(worker);
}
} while (keep_working(pool));
worker_set_flags(worker, WORKER_PREP, false);
sleep:
if (unlikely(need_to_manage_workers(pool)) && manage_workers(worker))
goto recheck;
/*
* pool->lock is held and there's no work to process and no need to
* manage, sleep. Workers are woken up only while holding
* pool->lock or from local cpu, so setting the current state
* before releasing pool->lock is enough to prevent losing any
* event.
*/
worker_enter_idle(worker);
__set_current_state(TASK_INTERRUPTIBLE);
spin_unlock_irq(&pool->lock);
schedule();
goto woke_up;
}
/**
* rescuer_thread - the rescuer thread function
* @__rescuer: self
*
* Workqueue rescuer thread function. There's one rescuer for each
* workqueue which has WQ_MEM_RECLAIM set.
*
* Regular work processing on a pool may block trying to create a new
* worker which uses GFP_KERNEL allocation which has slight chance of
* developing into deadlock if some works currently on the same queue
* need to be processed to satisfy the GFP_KERNEL allocation. This is
* the problem rescuer solves.
*
* When such condition is possible, the pool summons rescuers of all
* workqueues which have works queued on the pool and let them process
* those works so that forward progress can be guaranteed.
*
* This should happen rarely.
*/
static int rescuer_thread(void *__rescuer)
{
struct worker *rescuer = __rescuer;
struct workqueue_struct *wq = rescuer->rescue_wq;
struct list_head *scheduled = &rescuer->scheduled;
bool should_stop;
set_user_nice(current, RESCUER_NICE_LEVEL);
/*
* Mark rescuer as worker too. As WORKER_PREP is never cleared, it
* doesn't participate in concurrency management.
*/
rescuer->task->flags |= PF_WQ_WORKER;
repeat:
set_current_state(TASK_INTERRUPTIBLE);
/*
* By the time the rescuer is requested to stop, the workqueue
* shouldn't have any work pending, but @wq->maydays may still have
* pwq(s) queued. This can happen by non-rescuer workers consuming
* all the work items before the rescuer got to them. Go through
* @wq->maydays processing before acting on should_stop so that the
* list is always empty on exit.
*/
should_stop = kthread_should_stop();
/* see whether any pwq is asking for help */
spin_lock_irq(&wq_mayday_lock);
while (!list_empty(&wq->maydays)) {
struct pool_workqueue *pwq = list_first_entry(&wq->maydays,
struct pool_workqueue, mayday_node);
struct worker_pool *pool = pwq->pool;
struct work_struct *work, *n;
__set_current_state(TASK_RUNNING);
list_del_init(&pwq->mayday_node);
spin_unlock_irq(&wq_mayday_lock);
/* migrate to the target cpu if possible */
worker_maybe_bind_and_lock(pool);
rescuer->pool = pool;
/*
* Slurp in all works issued via this workqueue and
* process'em.
*/
WARN_ON_ONCE(!list_empty(&rescuer->scheduled));
list_for_each_entry_safe(work, n, &pool->worklist, entry)
if (get_work_pwq(work) == pwq)
move_linked_works(work, scheduled, &n);
process_scheduled_works(rescuer);
/*
* Put the reference grabbed by send_mayday(). @pool won't
* go away while we're holding its lock.
*/
put_pwq(pwq);
/*
* Leave this pool. If keep_working() is %true, notify a
* regular worker; otherwise, we end up with 0 concurrency
* and stalling the execution.
*/
if (keep_working(pool))
wake_up_worker(pool);
rescuer->pool = NULL;
spin_unlock(&pool->lock);
spin_lock(&wq_mayday_lock);
}
spin_unlock_irq(&wq_mayday_lock);
if (should_stop) {
__set_current_state(TASK_RUNNING);
rescuer->task->flags &= ~PF_WQ_WORKER;
return 0;
}
/* rescuers should never participate in concurrency management */
WARN_ON_ONCE(!(rescuer->flags & WORKER_NOT_RUNNING));
schedule();
goto repeat;
}
struct wq_barrier {
struct work_struct work;
struct completion done;
};
static void wq_barrier_func(struct work_struct *work)
{
struct wq_barrier *barr = container_of(work, struct wq_barrier, work);
complete(&barr->done);
}
/**
* insert_wq_barrier - insert a barrier work
* @pwq: pwq to insert barrier into
* @barr: wq_barrier to insert
* @target: target work to attach @barr to
* @worker: worker currently executing @target, NULL if @target is not executing
*
* @barr is linked to @target such that @barr is completed only after
* @target finishes execution. Please note that the ordering
* guarantee is observed only with respect to @target and on the local
* cpu.
*
* Currently, a queued barrier can't be canceled. This is because
* try_to_grab_pending() can't determine whether the work to be
* grabbed is at the head of the queue and thus can't clear LINKED
* flag of the previous work while there must be a valid next work
* after a work with LINKED flag set.
*
* Note that when @worker is non-NULL, @target may be modified
* underneath us, so we can't reliably determine pwq from @target.
*
* CONTEXT:
* spin_lock_irq(pool->lock).
*/
static void insert_wq_barrier(struct pool_workqueue *pwq,
struct wq_barrier *barr,
struct work_struct *target, struct worker *worker)
{
struct list_head *head;
unsigned int linked = 0;
/*
* debugobject calls are safe here even with pool->lock locked
* as we know for sure that this will not trigger any of the
* checks and call back into the fixup functions where we
* might deadlock.
*/
INIT_WORK_ONSTACK(&barr->work, wq_barrier_func);
__set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&barr->work));
init_completion(&barr->done);
/*
* If @target is currently being executed, schedule the
* barrier to the worker; otherwise, put it after @target.
*/
if (worker)
head = worker->scheduled.next;
else {
unsigned long *bits = work_data_bits(target);
head = target->entry.next;
/* there can already be other linked works, inherit and set */
linked = *bits & WORK_STRUCT_LINKED;
__set_bit(WORK_STRUCT_LINKED_BIT, bits);
}
debug_work_activate(&barr->work);
insert_work(pwq, &barr->work, head,
work_color_to_flags(WORK_NO_COLOR) | linked);
}
/**
* flush_workqueue_prep_pwqs - prepare pwqs for workqueue flushing
* @wq: workqueue being flushed
* @flush_color: new flush color, < 0 for no-op
* @work_color: new work color, < 0 for no-op
*
* Prepare pwqs for workqueue flushing.
*
* If @flush_color is non-negative, flush_color on all pwqs should be
* -1. If no pwq has in-flight commands at the specified color, all
* pwq->flush_color's stay at -1 and %false is returned. If any pwq
* has in flight commands, its pwq->flush_color is set to
* @flush_color, @wq->nr_pwqs_to_flush is updated accordingly, pwq
* wakeup logic is armed and %true is returned.
*
* The caller should have initialized @wq->first_flusher prior to
* calling this function with non-negative @flush_color. If
* @flush_color is negative, no flush color update is done and %false
* is returned.
*
* If @work_color is non-negative, all pwqs should have the same
* work_color which is previous to @work_color and all will be
* advanced to @work_color.
*
* CONTEXT:
* mutex_lock(wq->mutex).
*
* RETURNS:
* %true if @flush_color >= 0 and there's something to flush. %false
* otherwise.
*/
static bool flush_workqueue_prep_pwqs(struct workqueue_struct *wq,
int flush_color, int work_color)
{
bool wait = false;
struct pool_workqueue *pwq;
if (flush_color >= 0) {
WARN_ON_ONCE(atomic_read(&wq->nr_pwqs_to_flush));
atomic_set(&wq->nr_pwqs_to_flush, 1);
}
for_each_pwq(pwq, wq) {
struct worker_pool *pool = pwq->pool;
spin_lock_irq(&pool->lock);
if (flush_color >= 0) {
WARN_ON_ONCE(pwq->flush_color != -1);
if (pwq->nr_in_flight[flush_color]) {
pwq->flush_color = flush_color;
atomic_inc(&wq->nr_pwqs_to_flush);
wait = true;
}
}
if (work_color >= 0) {
WARN_ON_ONCE(work_color != work_next_color(pwq->work_color));
pwq->work_color = work_color;
}
spin_unlock_irq(&pool->lock);
}
if (flush_color >= 0 && atomic_dec_and_test(&wq->nr_pwqs_to_flush))
complete(&wq->first_flusher->done);
return wait;
}
/**
* flush_workqueue - ensure that any scheduled work has run to completion.
* @wq: workqueue to flush
*
* This function sleeps until all work items which were queued on entry
* have finished execution, but it is not livelocked by new incoming ones.
*/
void flush_workqueue(struct workqueue_struct *wq)
{
struct wq_flusher this_flusher = {
.list = LIST_HEAD_INIT(this_flusher.list),
.flush_color = -1,
.done = COMPLETION_INITIALIZER_ONSTACK(this_flusher.done),
};
int next_color;
lock_map_acquire(&wq->lockdep_map);
lock_map_release(&wq->lockdep_map);
mutex_lock(&wq->mutex);
/*
* Start-to-wait phase
*/
next_color = work_next_color(wq->work_color);
if (next_color != wq->flush_color) {
/*
* Color space is not full. The current work_color
* becomes our flush_color and work_color is advanced
* by one.
*/
WARN_ON_ONCE(!list_empty(&wq->flusher_overflow));
this_flusher.flush_color = wq->work_color;
wq->work_color = next_color;
if (!wq->first_flusher) {
/* no flush in progress, become the first flusher */
WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
wq->first_flusher = &this_flusher;
if (!flush_workqueue_prep_pwqs(wq, wq->flush_color,
wq->work_color)) {
/* nothing to flush, done */
wq->flush_color = next_color;
wq->first_flusher = NULL;
goto out_unlock;
}
} else {
/* wait in queue */
WARN_ON_ONCE(wq->flush_color == this_flusher.flush_color);
list_add_tail(&this_flusher.list, &wq->flusher_queue);
flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
}
} else {
/*
* Oops, color space is full, wait on overflow queue.
* The next flush completion will assign us
* flush_color and transfer to flusher_queue.
*/
list_add_tail(&this_flusher.list, &wq->flusher_overflow);
}
mutex_unlock(&wq->mutex);
wait_for_completion(&this_flusher.done);
/*
* Wake-up-and-cascade phase
*
* First flushers are responsible for cascading flushes and
* handling overflow. Non-first flushers can simply return.
*/
if (wq->first_flusher != &this_flusher)
return;
mutex_lock(&wq->mutex);
/* we might have raced, check again with mutex held */
if (wq->first_flusher != &this_flusher)
goto out_unlock;
wq->first_flusher = NULL;
WARN_ON_ONCE(!list_empty(&this_flusher.list));
WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
while (true) {
struct wq_flusher *next, *tmp;
/* complete all the flushers sharing the current flush color */
list_for_each_entry_safe(next, tmp, &wq->flusher_queue, list) {
if (next->flush_color != wq->flush_color)
break;
list_del_init(&next->list);
complete(&next->done);
}
WARN_ON_ONCE(!list_empty(&wq->flusher_overflow) &&
wq->flush_color != work_next_color(wq->work_color));
/* this flush_color is finished, advance by one */
wq->flush_color = work_next_color(wq->flush_color);
/* one color has been freed, handle overflow queue */
if (!list_empty(&wq->flusher_overflow)) {
/*
* Assign the same color to all overflowed
* flushers, advance work_color and append to
* flusher_queue. This is the start-to-wait
* phase for these overflowed flushers.
*/
list_for_each_entry(tmp, &wq->flusher_overflow, list)
tmp->flush_color = wq->work_color;
wq->work_color = work_next_color(wq->work_color);
list_splice_tail_init(&wq->flusher_overflow,
&wq->flusher_queue);
flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
}
if (list_empty(&wq->flusher_queue)) {
WARN_ON_ONCE(wq->flush_color != wq->work_color);
break;
}
/*
* Need to flush more colors. Make the next flusher
* the new first flusher and arm pwqs.
*/
WARN_ON_ONCE(wq->flush_color == wq->work_color);
WARN_ON_ONCE(wq->flush_color != next->flush_color);
list_del_init(&next->list);
wq->first_flusher = next;
if (flush_workqueue_prep_pwqs(wq, wq->flush_color, -1))
break;
/*
* Meh... this color is already done, clear first
* flusher and repeat cascading.
*/
wq->first_flusher = NULL;
}
out_unlock:
mutex_unlock(&wq->mutex);
}
EXPORT_SYMBOL_GPL(flush_workqueue);
/**
* drain_workqueue - drain a workqueue
* @wq: workqueue to drain
*
* Wait until the workqueue becomes empty. While draining is in progress,
* only chain queueing is allowed. IOW, only currently pending or running
* work items on @wq can queue further work items on it. @wq is flushed
* repeatedly until it becomes empty. The number of flushing is detemined
* by the depth of chaining and should be relatively short. Whine if it
* takes too long.
*/
void drain_workqueue(struct workqueue_struct *wq)
{
unsigned int flush_cnt = 0;
struct pool_workqueue *pwq;
/*
* __queue_work() needs to test whether there are drainers, is much
* hotter than drain_workqueue() and already looks at @wq->flags.
* Use __WQ_DRAINING so that queue doesn't have to check nr_drainers.
*/
mutex_lock(&wq->mutex);
if (!wq->nr_drainers++)
wq->flags |= __WQ_DRAINING;
mutex_unlock(&wq->mutex);
reflush:
flush_workqueue(wq);
mutex_lock(&wq->mutex);
for_each_pwq(pwq, wq) {
bool drained;
spin_lock_irq(&pwq->pool->lock);
drained = !pwq->nr_active && list_empty(&pwq->delayed_works);
spin_unlock_irq(&pwq->pool->lock);
if (drained)
continue;
if (++flush_cnt == 10 ||
(flush_cnt % 100 == 0 && flush_cnt <= 1000))
pr_warn("workqueue %s: drain_workqueue() isn't complete after %u tries\n",
wq->name, flush_cnt);
mutex_unlock(&wq->mutex);
goto reflush;
}
if (!--wq->nr_drainers)
wq->flags &= ~__WQ_DRAINING;
mutex_unlock(&wq->mutex);
}
EXPORT_SYMBOL_GPL(drain_workqueue);
static bool start_flush_work(struct work_struct *work, struct wq_barrier *barr)
{
struct worker *worker = NULL;
struct worker_pool *pool;
struct pool_workqueue *pwq;
might_sleep();
local_irq_disable();
pool = get_work_pool(work);
if (!pool) {
local_irq_enable();
return false;
}
spin_lock(&pool->lock);
/* see the comment in try_to_grab_pending() with the same code */
pwq = get_work_pwq(work);
if (pwq) {
if (unlikely(pwq->pool != pool))
goto already_gone;
} else {
worker = find_worker_executing_work(pool, work);
if (!worker)
goto already_gone;
pwq = worker->current_pwq;
}
insert_wq_barrier(pwq, barr, work, worker);
spin_unlock_irq(&pool->lock);
/*
* If @max_active is 1 or rescuer is in use, flushing another work
* item on the same workqueue may lead to deadlock. Make sure the
* flusher is not running on the same workqueue by verifying write
* access.
*/
if (pwq->wq->saved_max_active == 1 || pwq->wq->rescuer)
lock_map_acquire(&pwq->wq->lockdep_map);
else
lock_map_acquire_read(&pwq->wq->lockdep_map);
lock_map_release(&pwq->wq->lockdep_map);
return true;
already_gone:
spin_unlock_irq(&pool->lock);
return false;
}
/**
* flush_work - wait for a work to finish executing the last queueing instance
* @work: the work to flush
*
* Wait until @work has finished execution. @work is guaranteed to be idle
* on return if it hasn't been requeued since flush started.
*
* RETURNS:
* %true if flush_work() waited for the work to finish execution,
* %false if it was already idle.
*/
bool flush_work(struct work_struct *work)
{
struct wq_barrier barr;
lock_map_acquire(&work->lockdep_map);
lock_map_release(&work->lockdep_map);
if (start_flush_work(work, &barr)) {
wait_for_completion(&barr.done);
destroy_work_on_stack(&barr.work);
return true;
} else {
return false;
}
}
EXPORT_SYMBOL_GPL(flush_work);
static bool __cancel_work_timer(struct work_struct *work, bool is_dwork)
{
unsigned long flags;
int ret;
do {
ret = try_to_grab_pending(work, is_dwork, &flags);
/*
* If someone else is canceling, wait for the same event it
* would be waiting for before retrying.
*/
if (unlikely(ret == -ENOENT))
flush_work(work);
} while (unlikely(ret < 0));
/* tell other tasks trying to grab @work to back off */
mark_work_canceling(work);
local_irq_restore(flags);
flush_work(work);
clear_work_data(work);
return ret;
}
/**
* cancel_work_sync - cancel a work and wait for it to finish
* @work: the work to cancel
*
* Cancel @work and wait for its execution to finish. This function
* can be used even if the work re-queues itself or migrates to
* another workqueue. On return from this function, @work is
* guaranteed to be not pending or executing on any CPU.
*
* cancel_work_sync(&delayed_work->work) must not be used for
* delayed_work's. Use cancel_delayed_work_sync() instead.
*
* The caller must ensure that the workqueue on which @work was last
* queued can't be destroyed before this function returns.
*
* RETURNS:
* %true if @work was pending, %false otherwise.
*/
bool cancel_work_sync(struct work_struct *work)
{
return __cancel_work_timer(work, false);
}
EXPORT_SYMBOL_GPL(cancel_work_sync);
/**
* flush_delayed_work - wait for a dwork to finish executing the last queueing
* @dwork: the delayed work to flush
*
* Delayed timer is cancelled and the pending work is queued for
* immediate execution. Like flush_work(), this function only
* considers the last queueing instance of @dwork.
*
* RETURNS:
* %true if flush_work() waited for the work to finish execution,
* %false if it was already idle.
*/
bool flush_delayed_work(struct delayed_work *dwork)
{
local_irq_disable();
if (del_timer_sync(&dwork->timer))
__queue_work(dwork->cpu, dwork->wq, &dwork->work);
local_irq_enable();
return flush_work(&dwork->work);
}
EXPORT_SYMBOL(flush_delayed_work);
/**
* cancel_delayed_work - cancel a delayed work
* @dwork: delayed_work to cancel
*
* Kill off a pending delayed_work. Returns %true if @dwork was pending
* and canceled; %false if wasn't pending. Note that the work callback
* function may still be running on return, unless it returns %true and the
* work doesn't re-arm itself. Explicitly flush or use
* cancel_delayed_work_sync() to wait on it.
*
* This function is safe to call from any context including IRQ handler.
*/
bool cancel_delayed_work(struct delayed_work *dwork)
{
unsigned long flags;
int ret;
do {
ret = try_to_grab_pending(&dwork->work, true, &flags);
} while (unlikely(ret == -EAGAIN));
if (unlikely(ret < 0))
return false;
set_work_pool_and_clear_pending(&dwork->work,
get_work_pool_id(&dwork->work));
local_irq_restore(flags);
return ret;
}
EXPORT_SYMBOL(cancel_delayed_work);
/**
* cancel_delayed_work_sync - cancel a delayed work and wait for it to finish
* @dwork: the delayed work cancel
*
* This is cancel_work_sync() for delayed works.
*
* RETURNS:
* %true if @dwork was pending, %false otherwise.
*/
bool cancel_delayed_work_sync(struct delayed_work *dwork)
{
return __cancel_work_timer(&dwork->work, true);
}
EXPORT_SYMBOL(cancel_delayed_work_sync);
/**
* schedule_on_each_cpu - execute a function synchronously on each online CPU
* @func: the function to call
*
* schedule_on_each_cpu() executes @func on each online CPU using the
* system workqueue and blocks until all CPUs have completed.
* schedule_on_each_cpu() is very slow.
*
* RETURNS:
* 0 on success, -errno on failure.
*/
int schedule_on_each_cpu(work_func_t func)
{
int cpu;
struct work_struct __percpu *works;
works = alloc_percpu(struct work_struct);
if (!works)
return -ENOMEM;
get_online_cpus();
for_each_online_cpu(cpu) {
struct work_struct *work = per_cpu_ptr(works, cpu);
INIT_WORK(work, func);
schedule_work_on(cpu, work);
}
for_each_online_cpu(cpu)
flush_work(per_cpu_ptr(works, cpu));
put_online_cpus();
free_percpu(works);
return 0;
}
/**
* flush_scheduled_work - ensure that any scheduled work has run to completion.
*
* Forces execution of the kernel-global workqueue and blocks until its
* completion.
*
* Think twice before calling this function! It's very easy to get into
* trouble if you don't take great care. Either of the following situations
* will lead to deadlock:
*
* One of the work items currently on the workqueue needs to acquire
* a lock held by your code or its caller.
*
* Your code is running in the context of a work routine.
*
* They will be detected by lockdep when they occur, but the first might not
* occur very often. It depends on what work items are on the workqueue and
* what locks they need, which you have no control over.
*
* In most situations flushing the entire workqueue is overkill; you merely
* need to know that a particular work item isn't queued and isn't running.
* In such cases you should use cancel_delayed_work_sync() or
* cancel_work_sync() instead.
*/
void flush_scheduled_work(void)
{
flush_workqueue(system_wq);
}
EXPORT_SYMBOL(flush_scheduled_work);
/**
* execute_in_process_context - reliably execute the routine with user context
* @fn: the function to execute
* @ew: guaranteed storage for the execute work structure (must
* be available when the work executes)
*
* Executes the function immediately if process context is available,
* otherwise schedules the function for delayed execution.
*
* Returns: 0 - function was executed
* 1 - function was scheduled for execution
*/
int execute_in_process_context(work_func_t fn, struct execute_work *ew)
{
if (!in_interrupt()) {
fn(&ew->work);
return 0;
}
INIT_WORK(&ew->work, fn);
schedule_work(&ew->work);
return 1;
}
EXPORT_SYMBOL_GPL(execute_in_process_context);
#ifdef CONFIG_SYSFS
/*
* Workqueues with WQ_SYSFS flag set is visible to userland via
* /sys/bus/workqueue/devices/WQ_NAME. All visible workqueues have the
* following attributes.
*
* per_cpu RO bool : whether the workqueue is per-cpu or unbound
* max_active RW int : maximum number of in-flight work items
*
* Unbound workqueues have the following extra attributes.
*
* id RO int : the associated pool ID
* nice RW int : nice value of the workers
* cpumask RW mask : bitmask of allowed CPUs for the workers
*/
struct wq_device {
struct workqueue_struct *wq;
struct device dev;
};
static struct workqueue_struct *dev_to_wq(struct device *dev)
{
struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
return wq_dev->wq;
}
static ssize_t wq_per_cpu_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct workqueue_struct *wq = dev_to_wq(dev);
return scnprintf(buf, PAGE_SIZE, "%d\n", (bool)!(wq->flags & WQ_UNBOUND));
}
static ssize_t wq_max_active_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct workqueue_struct *wq = dev_to_wq(dev);
return scnprintf(buf, PAGE_SIZE, "%d\n", wq->saved_max_active);
}
static ssize_t wq_max_active_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct workqueue_struct *wq = dev_to_wq(dev);
int val;
if (sscanf(buf, "%d", &val) != 1 || val <= 0)
return -EINVAL;
workqueue_set_max_active(wq, val);
return count;
}
static struct device_attribute wq_sysfs_attrs[] = {
__ATTR(per_cpu, 0444, wq_per_cpu_show, NULL),
__ATTR(max_active, 0644, wq_max_active_show, wq_max_active_store),
__ATTR_NULL,
};
static ssize_t wq_pool_ids_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct workqueue_struct *wq = dev_to_wq(dev);
const char *delim = "";
int node, written = 0;
rcu_read_lock_sched();
for_each_node(node) {
written += scnprintf(buf + written, PAGE_SIZE - written,
"%s%d:%d", delim, node,
unbound_pwq_by_node(wq, node)->pool->id);
delim = " ";
}
written += scnprintf(buf + written, PAGE_SIZE - written, "\n");
rcu_read_unlock_sched();
return written;
}
static ssize_t wq_nice_show(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct workqueue_struct *wq = dev_to_wq(dev);
int written;
mutex_lock(&wq->mutex);
written = scnprintf(buf, PAGE_SIZE, "%d\n", wq->unbound_attrs->nice);
mutex_unlock(&wq->mutex);
return written;
}
/* prepare workqueue_attrs for sysfs store operations */
static struct workqueue_attrs *wq_sysfs_prep_attrs(struct workqueue_struct *wq)
{
struct workqueue_attrs *attrs;
attrs = alloc_workqueue_attrs(GFP_KERNEL);
if (!attrs)
return NULL;
mutex_lock(&wq->mutex);
copy_workqueue_attrs(attrs, wq->unbound_attrs);
mutex_unlock(&wq->mutex);
return attrs;
}
static ssize_t wq_nice_store(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct workqueue_struct *wq = dev_to_wq(dev);
struct workqueue_attrs *attrs;
int ret;
attrs = wq_sysfs_prep_attrs(wq);
if (!attrs)
return -ENOMEM;
if (sscanf(buf, "%d", &attrs->nice) == 1 &&
attrs->nice >= -20 && attrs->nice <= 19)
ret = apply_workqueue_attrs(wq, attrs);
else
ret = -EINVAL;
free_workqueue_attrs(attrs);
return ret ?: count;
}
static ssize_t wq_cpumask_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct workqueue_struct *wq = dev_to_wq(dev);
int written;
mutex_lock(&wq->mutex);
written = cpumask_scnprintf(buf, PAGE_SIZE, wq->unbound_attrs->cpumask);
mutex_unlock(&wq->mutex);
written += scnprintf(buf + written, PAGE_SIZE - written, "\n");
return written;
}
static ssize_t wq_cpumask_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct workqueue_struct *wq = dev_to_wq(dev);
struct workqueue_attrs *attrs;
int ret;
attrs = wq_sysfs_prep_attrs(wq);
if (!attrs)
return -ENOMEM;
ret = cpumask_parse(buf, attrs->cpumask);
if (!ret)
ret = apply_workqueue_attrs(wq, attrs);
free_workqueue_attrs(attrs);
return ret ?: count;
}
static ssize_t wq_numa_show(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct workqueue_struct *wq = dev_to_wq(dev);
int written;
mutex_lock(&wq->mutex);
written = scnprintf(buf, PAGE_SIZE, "%d\n",
!wq->unbound_attrs->no_numa);
mutex_unlock(&wq->mutex);
return written;
}
static ssize_t wq_numa_store(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct workqueue_struct *wq = dev_to_wq(dev);
struct workqueue_attrs *attrs;
int v, ret;
attrs = wq_sysfs_prep_attrs(wq);
if (!attrs)
return -ENOMEM;
ret = -EINVAL;
if (sscanf(buf, "%d", &v) == 1) {
attrs->no_numa = !v;
ret = apply_workqueue_attrs(wq, attrs);
}
free_workqueue_attrs(attrs);
return ret ?: count;
}
static struct device_attribute wq_sysfs_unbound_attrs[] = {
__ATTR(pool_ids, 0444, wq_pool_ids_show, NULL),
__ATTR(nice, 0644, wq_nice_show, wq_nice_store),
__ATTR(cpumask, 0644, wq_cpumask_show, wq_cpumask_store),
__ATTR(numa, 0644, wq_numa_show, wq_numa_store),
__ATTR_NULL,
};
static struct bus_type wq_subsys = {
.name = "workqueue",
.dev_attrs = wq_sysfs_attrs,
};
static int __init wq_sysfs_init(void)
{
return subsys_virtual_register(&wq_subsys, NULL);
}
core_initcall(wq_sysfs_init);
static void wq_device_release(struct device *dev)
{
struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
kfree(wq_dev);
}
/**
* workqueue_sysfs_register - make a workqueue visible in sysfs
* @wq: the workqueue to register
*
* Expose @wq in sysfs under /sys/bus/workqueue/devices.
* alloc_workqueue*() automatically calls this function if WQ_SYSFS is set
* which is the preferred method.
*
* Workqueue user should use this function directly iff it wants to apply
* workqueue_attrs before making the workqueue visible in sysfs; otherwise,
* apply_workqueue_attrs() may race against userland updating the
* attributes.
*
* Returns 0 on success, -errno on failure.
*/
int workqueue_sysfs_register(struct workqueue_struct *wq)
{
struct wq_device *wq_dev;
int ret;
/*
* Adjusting max_active or creating new pwqs by applyting
* attributes breaks ordering guarantee. Disallow exposing ordered
* workqueues.
*/
if (WARN_ON(wq->flags & __WQ_ORDERED))
return -EINVAL;
wq->wq_dev = wq_dev = kzalloc(sizeof(*wq_dev), GFP_KERNEL);
if (!wq_dev)
return -ENOMEM;
wq_dev->wq = wq;
wq_dev->dev.bus = &wq_subsys;
wq_dev->dev.init_name = wq->name;
wq_dev->dev.release = wq_device_release;
/*
* unbound_attrs are created separately. Suppress uevent until
* everything is ready.
*/
dev_set_uevent_suppress(&wq_dev->dev, true);
ret = device_register(&wq_dev->dev);
if (ret) {
kfree(wq_dev);
wq->wq_dev = NULL;
return ret;
}
if (wq->flags & WQ_UNBOUND) {
struct device_attribute *attr;
for (attr = wq_sysfs_unbound_attrs; attr->attr.name; attr++) {
ret = device_create_file(&wq_dev->dev, attr);
if (ret) {
device_unregister(&wq_dev->dev);
wq->wq_dev = NULL;
return ret;
}
}
}
dev_set_uevent_suppress(&wq_dev->dev, false);
kobject_uevent(&wq_dev->dev.kobj, KOBJ_ADD);
return 0;
}
/**
* workqueue_sysfs_unregister - undo workqueue_sysfs_register()
* @wq: the workqueue to unregister
*
* If @wq is registered to sysfs by workqueue_sysfs_register(), unregister.
*/
static void workqueue_sysfs_unregister(struct workqueue_struct *wq)
{
struct wq_device *wq_dev = wq->wq_dev;
if (!wq->wq_dev)
return;
wq->wq_dev = NULL;
device_unregister(&wq_dev->dev);
}
#else /* CONFIG_SYSFS */
static void workqueue_sysfs_unregister(struct workqueue_struct *wq) { }
#endif /* CONFIG_SYSFS */
/**
* free_workqueue_attrs - free a workqueue_attrs
* @attrs: workqueue_attrs to free
*
* Undo alloc_workqueue_attrs().
*/
void free_workqueue_attrs(struct workqueue_attrs *attrs)
{
if (attrs) {
free_cpumask_var(attrs->cpumask);
kfree(attrs);
}
}
/**
* alloc_workqueue_attrs - allocate a workqueue_attrs
* @gfp_mask: allocation mask to use
*
* Allocate a new workqueue_attrs, initialize with default settings and
* return it. Returns NULL on failure.
*/
struct workqueue_attrs *alloc_workqueue_attrs(gfp_t gfp_mask)
{
struct workqueue_attrs *attrs;
attrs = kzalloc(sizeof(*attrs), gfp_mask);
if (!attrs)
goto fail;
if (!alloc_cpumask_var(&attrs->cpumask, gfp_mask))
goto fail;
cpumask_copy(attrs->cpumask, cpu_possible_mask);
return attrs;
fail:
free_workqueue_attrs(attrs);
return NULL;
}
static void copy_workqueue_attrs(struct workqueue_attrs *to,
const struct workqueue_attrs *from)
{
to->nice = from->nice;
cpumask_copy(to->cpumask, from->cpumask);
/*
* Unlike hash and equality test, this function doesn't ignore
* ->no_numa as it is used for both pool and wq attrs. Instead,
* get_unbound_pool() explicitly clears ->no_numa after copying.
*/
to->no_numa = from->no_numa;
}
/* hash value of the content of @attr */
static u32 wqattrs_hash(const struct workqueue_attrs *attrs)
{
u32 hash = 0;
hash = jhash_1word(attrs->nice, hash);
hash = jhash(cpumask_bits(attrs->cpumask),
BITS_TO_LONGS(nr_cpumask_bits) * sizeof(long), hash);
return hash;
}
/* content equality test */
static bool wqattrs_equal(const struct workqueue_attrs *a,
const struct workqueue_attrs *b)
{
if (a->nice != b->nice)
return false;
if (!cpumask_equal(a->cpumask, b->cpumask))
return false;
return true;
}
/**
* init_worker_pool - initialize a newly zalloc'd worker_pool
* @pool: worker_pool to initialize
*
* Initiailize a newly zalloc'd @pool. It also allocates @pool->attrs.
* Returns 0 on success, -errno on failure. Even on failure, all fields
* inside @pool proper are initialized and put_unbound_pool() can be called
* on @pool safely to release it.
*/
static int init_worker_pool(struct worker_pool *pool)
{
spin_lock_init(&pool->lock);
pool->id = -1;
pool->cpu = -1;
pool->node = NUMA_NO_NODE;
pool->flags |= POOL_DISASSOCIATED;
INIT_LIST_HEAD(&pool->worklist);
INIT_LIST_HEAD(&pool->idle_list);
hash_init(pool->busy_hash);
init_timer_deferrable(&pool->idle_timer);
pool->idle_timer.function = idle_worker_timeout;
pool->idle_timer.data = (unsigned long)pool;
setup_timer(&pool->mayday_timer, pool_mayday_timeout,
(unsigned long)pool);
mutex_init(&pool->manager_arb);
mutex_init(&pool->manager_mutex);
idr_init(&pool->worker_idr);
INIT_HLIST_NODE(&pool->hash_node);
pool->refcnt = 1;
/* shouldn't fail above this point */
pool->attrs = alloc_workqueue_attrs(GFP_KERNEL);
if (!pool->attrs)
return -ENOMEM;
return 0;
}
static void rcu_free_pool(struct rcu_head *rcu)
{
struct worker_pool *pool = container_of(rcu, struct worker_pool, rcu);
idr_destroy(&pool->worker_idr);
free_workqueue_attrs(pool->attrs);
kfree(pool);
}
/**
* put_unbound_pool - put a worker_pool
* @pool: worker_pool to put
*
* Put @pool. If its refcnt reaches zero, it gets destroyed in sched-RCU
* safe manner. get_unbound_pool() calls this function on its failure path
* and this function should be able to release pools which went through,
* successfully or not, init_worker_pool().
*
* Should be called with wq_pool_mutex held.
*/
static void put_unbound_pool(struct worker_pool *pool)
{
struct worker *worker;
lockdep_assert_held(&wq_pool_mutex);
if (--pool->refcnt)
return;
/* sanity checks */
if (WARN_ON(!(pool->flags & POOL_DISASSOCIATED)) ||
WARN_ON(!list_empty(&pool->worklist)))
return;
/* release id and unhash */
if (pool->id >= 0)
idr_remove(&worker_pool_idr, pool->id);
hash_del(&pool->hash_node);
/*
* Become the manager and destroy all workers. Grabbing
* manager_arb prevents @pool's workers from blocking on
* manager_mutex.
*/
mutex_lock(&pool->manager_arb);
mutex_lock(&pool->manager_mutex);
spin_lock_irq(&pool->lock);
while ((worker = first_worker(pool)))
destroy_worker(worker);
WARN_ON(pool->nr_workers || pool->nr_idle);
spin_unlock_irq(&pool->lock);
mutex_unlock(&pool->manager_mutex);
mutex_unlock(&pool->manager_arb);
/* shut down the timers */
del_timer_sync(&pool->idle_timer);
del_timer_sync(&pool->mayday_timer);
/* sched-RCU protected to allow dereferences from get_work_pool() */
call_rcu_sched(&pool->rcu, rcu_free_pool);
}
/**
* get_unbound_pool - get a worker_pool with the specified attributes
* @attrs: the attributes of the worker_pool to get
*
* Obtain a worker_pool which has the same attributes as @attrs, bump the
* reference count and return it. If there already is a matching
* worker_pool, it will be used; otherwise, this function attempts to
* create a new one. On failure, returns NULL.
*
* Should be called with wq_pool_mutex held.
*/
static struct worker_pool *get_unbound_pool(const struct workqueue_attrs *attrs)
{
u32 hash = wqattrs_hash(attrs);
struct worker_pool *pool;
int node;
lockdep_assert_held(&wq_pool_mutex);
/* do we already have a matching pool? */
hash_for_each_possible(unbound_pool_hash, pool, hash_node, hash) {
if (wqattrs_equal(pool->attrs, attrs)) {
pool->refcnt++;
goto out_unlock;
}
}
/* nope, create a new one */
pool = kzalloc(sizeof(*pool), GFP_KERNEL);
if (!pool || init_worker_pool(pool) < 0)
goto fail;
if (workqueue_freezing)
pool->flags |= POOL_FREEZING;
lockdep_set_subclass(&pool->lock, 1); /* see put_pwq() */
copy_workqueue_attrs(pool->attrs, attrs);
/*
* no_numa isn't a worker_pool attribute, always clear it. See
* 'struct workqueue_attrs' comments for detail.
*/
pool->attrs->no_numa = false;
/* if cpumask is contained inside a NUMA node, we belong to that node */
if (wq_numa_enabled) {
for_each_node(node) {
if (cpumask_subset(pool->attrs->cpumask,
wq_numa_possible_cpumask[node])) {
pool->node = node;
break;
}
}
}
if (worker_pool_assign_id(pool) < 0)
goto fail;
/* create and start the initial worker */
if (create_and_start_worker(pool) < 0)
goto fail;
/* install */
hash_add(unbound_pool_hash, &pool->hash_node, hash);
out_unlock:
return pool;
fail:
if (pool)
put_unbound_pool(pool);
return NULL;
}
static void rcu_free_pwq(struct rcu_head *rcu)
{
kmem_cache_free(pwq_cache,
container_of(rcu, struct pool_workqueue, rcu));
}
/*
* Scheduled on system_wq by put_pwq() when an unbound pwq hits zero refcnt
* and needs to be destroyed.
*/
static void pwq_unbound_release_workfn(struct work_struct *work)
{
struct pool_workqueue *pwq = container_of(work, struct pool_workqueue,
unbound_release_work);
struct workqueue_struct *wq = pwq->wq;
struct worker_pool *pool = pwq->pool;
bool is_last;
if (WARN_ON_ONCE(!(wq->flags & WQ_UNBOUND)))
return;
/*
* Unlink @pwq. Synchronization against wq->mutex isn't strictly
* necessary on release but do it anyway. It's easier to verify
* and consistent with the linking path.
*/
mutex_lock(&wq->mutex);
list_del_rcu(&pwq->pwqs_node);
is_last = list_empty(&wq->pwqs);
mutex_unlock(&wq->mutex);
mutex_lock(&wq_pool_mutex);
put_unbound_pool(pool);
mutex_unlock(&wq_pool_mutex);
call_rcu_sched(&pwq->rcu, rcu_free_pwq);
/*
* If we're the last pwq going away, @wq is already dead and no one
* is gonna access it anymore. Free it.
*/
if (is_last) {
free_workqueue_attrs(wq->unbound_attrs);
kfree(wq);
}
}
/**
* pwq_adjust_max_active - update a pwq's max_active to the current setting
* @pwq: target pool_workqueue
*
* If @pwq isn't freezing, set @pwq->max_active to the associated
* workqueue's saved_max_active and activate delayed work items
* accordingly. If @pwq is freezing, clear @pwq->max_active to zero.
*/
static void pwq_adjust_max_active(struct pool_workqueue *pwq)
{
struct workqueue_struct *wq = pwq->wq;
bool freezable = wq->flags & WQ_FREEZABLE;
/* for @wq->saved_max_active */
lockdep_assert_held(&wq->mutex);
/* fast exit for non-freezable wqs */
if (!freezable && pwq->max_active == wq->saved_max_active)
return;
spin_lock_irq(&pwq->pool->lock);
if (!freezable || !(pwq->pool->flags & POOL_FREEZING)) {
pwq->max_active = wq->saved_max_active;
while (!list_empty(&pwq->delayed_works) &&
pwq->nr_active < pwq->max_active)
pwq_activate_first_delayed(pwq);
/*
* Need to kick a worker after thawed or an unbound wq's
* max_active is bumped. It's a slow path. Do it always.
*/
wake_up_worker(pwq->pool);
} else {
pwq->max_active = 0;
}
spin_unlock_irq(&pwq->pool->lock);
}
/* initialize newly alloced @pwq which is associated with @wq and @pool */
static void init_pwq(struct pool_workqueue *pwq, struct workqueue_struct *wq,
struct worker_pool *pool)
{
BUG_ON((unsigned long)pwq & WORK_STRUCT_FLAG_MASK);
memset(pwq, 0, sizeof(*pwq));
pwq->pool = pool;
pwq->wq = wq;
pwq->flush_color = -1;
pwq->refcnt = 1;
INIT_LIST_HEAD(&pwq->delayed_works);
INIT_LIST_HEAD(&pwq->pwqs_node);
INIT_LIST_HEAD(&pwq->mayday_node);
INIT_WORK(&pwq->unbound_release_work, pwq_unbound_release_workfn);
}
/* sync @pwq with the current state of its associated wq and link it */
static void link_pwq(struct pool_workqueue *pwq)
{
struct workqueue_struct *wq = pwq->wq;
lockdep_assert_held(&wq->mutex);
/* may be called multiple times, ignore if already linked */
if (!list_empty(&pwq->pwqs_node))
return;
/*
* Set the matching work_color. This is synchronized with
* wq->mutex to avoid confusing flush_workqueue().
*/
pwq->work_color = wq->work_color;
/* sync max_active to the current setting */
pwq_adjust_max_active(pwq);
/* link in @pwq */
list_add_rcu(&pwq->pwqs_node, &wq->pwqs);
}
/* obtain a pool matching @attr and create a pwq associating the pool and @wq */
static struct pool_workqueue *alloc_unbound_pwq(struct workqueue_struct *wq,
const struct workqueue_attrs *attrs)
{
struct worker_pool *pool;
struct pool_workqueue *pwq;
lockdep_assert_held(&wq_pool_mutex);
pool = get_unbound_pool(attrs);
if (!pool)
return NULL;
pwq = kmem_cache_alloc_node(pwq_cache, GFP_KERNEL, pool->node);
if (!pwq) {
put_unbound_pool(pool);
return NULL;
}
init_pwq(pwq, wq, pool);
return pwq;
}
/* undo alloc_unbound_pwq(), used only in the error path */
static void free_unbound_pwq(struct pool_workqueue *pwq)
{
lockdep_assert_held(&wq_pool_mutex);
if (pwq) {
put_unbound_pool(pwq->pool);
kmem_cache_free(pwq_cache, pwq);
}
}
/**
* wq_calc_node_mask - calculate a wq_attrs' cpumask for the specified node
* @attrs: the wq_attrs of interest
* @node: the target NUMA node
* @cpu_going_down: if >= 0, the CPU to consider as offline
* @cpumask: outarg, the resulting cpumask
*
* Calculate the cpumask a workqueue with @attrs should use on @node. If
* @cpu_going_down is >= 0, that cpu is considered offline during
* calculation. The result is stored in @cpumask. This function returns
* %true if the resulting @cpumask is different from @attrs->cpumask,
* %false if equal.
*
* If NUMA affinity is not enabled, @attrs->cpumask is always used. If
* enabled and @node has online CPUs requested by @attrs, the returned
* cpumask is the intersection of the possible CPUs of @node and
* @attrs->cpumask.
*
* The caller is responsible for ensuring that the cpumask of @node stays
* stable.
*/
static bool wq_calc_node_cpumask(const struct workqueue_attrs *attrs, int node,
int cpu_going_down, cpumask_t *cpumask)
{
if (!wq_numa_enabled || attrs->no_numa)
goto use_dfl;
/* does @node have any online CPUs @attrs wants? */
cpumask_and(cpumask, cpumask_of_node(node), attrs->cpumask);
if (cpu_going_down >= 0)
cpumask_clear_cpu(cpu_going_down, cpumask);
if (cpumask_empty(cpumask))
goto use_dfl;
/* yeap, return possible CPUs in @node that @attrs wants */
cpumask_and(cpumask, attrs->cpumask, wq_numa_possible_cpumask[node]);
return !cpumask_equal(cpumask, attrs->cpumask);
use_dfl:
cpumask_copy(cpumask, attrs->cpumask);
return false;
}
/* install @pwq into @wq's numa_pwq_tbl[] for @node and return the old pwq */
static struct pool_workqueue *numa_pwq_tbl_install(struct workqueue_struct *wq,
int node,
struct pool_workqueue *pwq)
{
struct pool_workqueue *old_pwq;
lockdep_assert_held(&wq->mutex);
/* link_pwq() can handle duplicate calls */
link_pwq(pwq);
old_pwq = rcu_access_pointer(wq->numa_pwq_tbl[node]);
rcu_assign_pointer(wq->numa_pwq_tbl[node], pwq);
return old_pwq;
}
/**
* apply_workqueue_attrs - apply new workqueue_attrs to an unbound workqueue
* @wq: the target workqueue
* @attrs: the workqueue_attrs to apply, allocated with alloc_workqueue_attrs()
*
* Apply @attrs to an unbound workqueue @wq. Unless disabled, on NUMA
* machines, this function maps a separate pwq to each NUMA node with
* possibles CPUs in @attrs->cpumask so that work items are affine to the
* NUMA node it was issued on. Older pwqs are released as in-flight work
* items finish. Note that a work item which repeatedly requeues itself
* back-to-back will stay on its current pwq.
*
* Performs GFP_KERNEL allocations. Returns 0 on success and -errno on
* failure.
*/
int apply_workqueue_attrs(struct workqueue_struct *wq,
const struct workqueue_attrs *attrs)
{
struct workqueue_attrs *new_attrs, *tmp_attrs;
struct pool_workqueue **pwq_tbl, *dfl_pwq;
int node, ret;
/* only unbound workqueues can change attributes */
if (WARN_ON(!(wq->flags & WQ_UNBOUND)))
return -EINVAL;
/* creating multiple pwqs breaks ordering guarantee */
if (WARN_ON((wq->flags & __WQ_ORDERED) && !list_empty(&wq->pwqs)))
return -EINVAL;
pwq_tbl = kzalloc(wq_numa_tbl_len * sizeof(pwq_tbl[0]), GFP_KERNEL);
new_attrs = alloc_workqueue_attrs(GFP_KERNEL);
tmp_attrs = alloc_workqueue_attrs(GFP_KERNEL);
if (!pwq_tbl || !new_attrs || !tmp_attrs)
goto enomem;
/* make a copy of @attrs and sanitize it */
copy_workqueue_attrs(new_attrs, attrs);
cpumask_and(new_attrs->cpumask, new_attrs->cpumask, cpu_possible_mask);
/*
* We may create multiple pwqs with differing cpumasks. Make a
* copy of @new_attrs which will be modified and used to obtain
* pools.
*/
copy_workqueue_attrs(tmp_attrs, new_attrs);
/*
* CPUs should stay stable across pwq creations and installations.
* Pin CPUs, determine the target cpumask for each node and create
* pwqs accordingly.
*/
get_online_cpus();
mutex_lock(&wq_pool_mutex);
/*
* If something goes wrong during CPU up/down, we'll fall back to
* the default pwq covering whole @attrs->cpumask. Always create
* it even if we don't use it immediately.
*/
dfl_pwq = alloc_unbound_pwq(wq, new_attrs);
if (!dfl_pwq)
goto enomem_pwq;
for_each_node(node) {
if (wq_calc_node_cpumask(attrs, node, -1, tmp_attrs->cpumask)) {
pwq_tbl[node] = alloc_unbound_pwq(wq, tmp_attrs);
if (!pwq_tbl[node])
goto enomem_pwq;
} else {
dfl_pwq->refcnt++;
pwq_tbl[node] = dfl_pwq;
}
}
mutex_unlock(&wq_pool_mutex);
/* all pwqs have been created successfully, let's install'em */
mutex_lock(&wq->mutex);
copy_workqueue_attrs(wq->unbound_attrs, new_attrs);
/* save the previous pwq and install the new one */
for_each_node(node)
pwq_tbl[node] = numa_pwq_tbl_install(wq, node, pwq_tbl[node]);
/* @dfl_pwq might not have been used, ensure it's linked */
link_pwq(dfl_pwq);
swap(wq->dfl_pwq, dfl_pwq);
mutex_unlock(&wq->mutex);
/* put the old pwqs */
for_each_node(node)
put_pwq_unlocked(pwq_tbl[node]);
put_pwq_unlocked(dfl_pwq);
put_online_cpus();
ret = 0;
/* fall through */
out_free:
free_workqueue_attrs(tmp_attrs);
free_workqueue_attrs(new_attrs);
kfree(pwq_tbl);
return ret;
enomem_pwq:
free_unbound_pwq(dfl_pwq);
for_each_node(node)
if (pwq_tbl && pwq_tbl[node] != dfl_pwq)
free_unbound_pwq(pwq_tbl[node]);
mutex_unlock(&wq_pool_mutex);
put_online_cpus();
enomem:
ret = -ENOMEM;
goto out_free;
}
/**
* wq_update_unbound_numa - update NUMA affinity of a wq for CPU hot[un]plug
* @wq: the target workqueue
* @cpu: the CPU coming up or going down
* @online: whether @cpu is coming up or going down
*
* This function is to be called from %CPU_DOWN_PREPARE, %CPU_ONLINE and
* %CPU_DOWN_FAILED. @cpu is being hot[un]plugged, update NUMA affinity of
* @wq accordingly.
*
* If NUMA affinity can't be adjusted due to memory allocation failure, it
* falls back to @wq->dfl_pwq which may not be optimal but is always
* correct.
*
* Note that when the last allowed CPU of a NUMA node goes offline for a
* workqueue with a cpumask spanning multiple nodes, the workers which were
* already executing the work items for the workqueue will lose their CPU
* affinity and may execute on any CPU. This is similar to how per-cpu
* workqueues behave on CPU_DOWN. If a workqueue user wants strict
* affinity, it's the user's responsibility to flush the work item from
* CPU_DOWN_PREPARE.
*/
static void wq_update_unbound_numa(struct workqueue_struct *wq, int cpu,
bool online)
{
int node = cpu_to_node(cpu);
int cpu_off = online ? -1 : cpu;
struct pool_workqueue *old_pwq = NULL, *pwq;
struct workqueue_attrs *target_attrs;
cpumask_t *cpumask;
lockdep_assert_held(&wq_pool_mutex);
if (!wq_numa_enabled || !(wq->flags & WQ_UNBOUND))
return;
/*
* We don't wanna alloc/free wq_attrs for each wq for each CPU.
* Let's use a preallocated one. The following buf is protected by
* CPU hotplug exclusion.
*/
target_attrs = wq_update_unbound_numa_attrs_buf;
cpumask = target_attrs->cpumask;
mutex_lock(&wq->mutex);
if (wq->unbound_attrs->no_numa)
goto out_unlock;
copy_workqueue_attrs(target_attrs, wq->unbound_attrs);
pwq = unbound_pwq_by_node(wq, node);
/*
* Let's determine what needs to be done. If the target cpumask is
* different from wq's, we need to compare it to @pwq's and create
* a new one if they don't match. If the target cpumask equals
* wq's, the default pwq should be used. If @pwq is already the
* default one, nothing to do; otherwise, install the default one.
*/
if (wq_calc_node_cpumask(wq->unbound_attrs, node, cpu_off, cpumask)) {
if (cpumask_equal(cpumask, pwq->pool->attrs->cpumask))
goto out_unlock;
} else {
if (pwq == wq->dfl_pwq)
goto out_unlock;
else
goto use_dfl_pwq;
}
mutex_unlock(&wq->mutex);
/* create a new pwq */
pwq = alloc_unbound_pwq(wq, target_attrs);
if (!pwq) {
pr_warning("workqueue: allocation failed while updating NUMA affinity of \"%s\"\n",
wq->name);
mutex_lock(&wq->mutex);
goto use_dfl_pwq;
}
/*
* Install the new pwq. As this function is called only from CPU
* hotplug callbacks and applying a new attrs is wrapped with
* get/put_online_cpus(), @wq->unbound_attrs couldn't have changed
* inbetween.
*/
mutex_lock(&wq->mutex);
old_pwq = numa_pwq_tbl_install(wq, node, pwq);
goto out_unlock;
use_dfl_pwq:
spin_lock_irq(&wq->dfl_pwq->pool->lock);
get_pwq(wq->dfl_pwq);
spin_unlock_irq(&wq->dfl_pwq->pool->lock);
old_pwq = numa_pwq_tbl_install(wq, node, wq->dfl_pwq);
out_unlock:
mutex_unlock(&wq->mutex);
put_pwq_unlocked(old_pwq);
}
static int alloc_and_link_pwqs(struct workqueue_struct *wq)
{
bool highpri = wq->flags & WQ_HIGHPRI;
int cpu, ret;
if (!(wq->flags & WQ_UNBOUND)) {
wq->cpu_pwqs = alloc_percpu(struct pool_workqueue);
if (!wq->cpu_pwqs)
return -ENOMEM;
for_each_possible_cpu(cpu) {
struct pool_workqueue *pwq =
per_cpu_ptr(wq->cpu_pwqs, cpu);
struct worker_pool *cpu_pools =
per_cpu(cpu_worker_pools, cpu);
init_pwq(pwq, wq, &cpu_pools[highpri]);
mutex_lock(&wq->mutex);
link_pwq(pwq);
mutex_unlock(&wq->mutex);
}
return 0;
} else if (wq->flags & __WQ_ORDERED) {
ret = apply_workqueue_attrs(wq, ordered_wq_attrs[highpri]);
/* there should only be single pwq for ordering guarantee */
WARN(!ret && (wq->pwqs.next != &wq->dfl_pwq->pwqs_node ||
wq->pwqs.prev != &wq->dfl_pwq->pwqs_node),
"ordering guarantee broken for workqueue %s\n", wq->name);
return ret;
} else {
return apply_workqueue_attrs(wq, unbound_std_wq_attrs[highpri]);
}
}
static int wq_clamp_max_active(int max_active, unsigned int flags,
const char *name)
{
int lim = flags & WQ_UNBOUND ? WQ_UNBOUND_MAX_ACTIVE : WQ_MAX_ACTIVE;
if (max_active < 1 || max_active > lim)
pr_warn("workqueue: max_active %d requested for %s is out of range, clamping between %d and %d\n",
max_active, name, 1, lim);
return clamp_val(max_active, 1, lim);
}
struct workqueue_struct *__alloc_workqueue_key(const char *fmt,
unsigned int flags,
int max_active,
struct lock_class_key *key,
const char *lock_name, ...)
{
size_t tbl_size = 0;
va_list args;
struct workqueue_struct *wq;
struct pool_workqueue *pwq;
/* allocate wq and format name */
if (flags & WQ_UNBOUND)
tbl_size = wq_numa_tbl_len * sizeof(wq->numa_pwq_tbl[0]);
wq = kzalloc(sizeof(*wq) + tbl_size, GFP_KERNEL);
if (!wq)
return NULL;
if (flags & WQ_UNBOUND) {
wq->unbound_attrs = alloc_workqueue_attrs(GFP_KERNEL);
if (!wq->unbound_attrs)
goto err_free_wq;
}
va_start(args, lock_name);
vsnprintf(wq->name, sizeof(wq->name), fmt, args);
va_end(args);
max_active = max_active ?: WQ_DFL_ACTIVE;
max_active = wq_clamp_max_active(max_active, flags, wq->name);
/* init wq */
wq->flags = flags;
wq->saved_max_active = max_active;
mutex_init(&wq->mutex);
atomic_set(&wq->nr_pwqs_to_flush, 0);
INIT_LIST_HEAD(&wq->pwqs);
INIT_LIST_HEAD(&wq->flusher_queue);
INIT_LIST_HEAD(&wq->flusher_overflow);
INIT_LIST_HEAD(&wq->maydays);
lockdep_init_map(&wq->lockdep_map, lock_name, key, 0);
INIT_LIST_HEAD(&wq->list);
if (alloc_and_link_pwqs(wq) < 0)
goto err_free_wq;
/*
* Workqueues which may be used during memory reclaim should
* have a rescuer to guarantee forward progress.
*/
if (flags & WQ_MEM_RECLAIM) {
struct worker *rescuer;
rescuer = alloc_worker();
if (!rescuer)
goto err_destroy;
rescuer->rescue_wq = wq;
rescuer->task = kthread_create(rescuer_thread, rescuer, "%s",
wq->name);
if (IS_ERR(rescuer->task)) {
kfree(rescuer);
goto err_destroy;
}
wq->rescuer = rescuer;
rescuer->task->flags |= PF_NO_SETAFFINITY;
wake_up_process(rescuer->task);
}
if ((wq->flags & WQ_SYSFS) && workqueue_sysfs_register(wq))
goto err_destroy;
/*
* wq_pool_mutex protects global freeze state and workqueues list.
* Grab it, adjust max_active and add the new @wq to workqueues
* list.
*/
mutex_lock(&wq_pool_mutex);
mutex_lock(&wq->mutex);
for_each_pwq(pwq, wq)
pwq_adjust_max_active(pwq);
mutex_unlock(&wq->mutex);
list_add(&wq->list, &workqueues);
mutex_unlock(&wq_pool_mutex);
return wq;
err_free_wq:
free_workqueue_attrs(wq->unbound_attrs);
kfree(wq);
return NULL;
err_destroy:
destroy_workqueue(wq);
return NULL;
}
EXPORT_SYMBOL_GPL(__alloc_workqueue_key);
/**
* destroy_workqueue - safely terminate a workqueue
* @wq: target workqueue
*
* Safely destroy a workqueue. All work currently pending will be done first.
*/
void destroy_workqueue(struct workqueue_struct *wq)
{
struct pool_workqueue *pwq;
int node;
/* drain it before proceeding with destruction */
drain_workqueue(wq);
/* sanity checks */
mutex_lock(&wq->mutex);
for_each_pwq(pwq, wq) {
int i;
for (i = 0; i < WORK_NR_COLORS; i++) {
if (WARN_ON(pwq->nr_in_flight[i])) {
mutex_unlock(&wq->mutex);
return;
}
}
if (WARN_ON((pwq != wq->dfl_pwq) && (pwq->refcnt > 1)) ||
WARN_ON(pwq->nr_active) ||
WARN_ON(!list_empty(&pwq->delayed_works))) {
mutex_unlock(&wq->mutex);
return;
}
}
mutex_unlock(&wq->mutex);
/*
* wq list is used to freeze wq, remove from list after
* flushing is complete in case freeze races us.
*/
mutex_lock(&wq_pool_mutex);
list_del_init(&wq->list);
mutex_unlock(&wq_pool_mutex);
workqueue_sysfs_unregister(wq);
if (wq->rescuer) {
kthread_stop(wq->rescuer->task);
kfree(wq->rescuer);
wq->rescuer = NULL;
}
if (!(wq->flags & WQ_UNBOUND)) {
/*
* The base ref is never dropped on per-cpu pwqs. Directly
* free the pwqs and wq.
*/
free_percpu(wq->cpu_pwqs);
kfree(wq);
} else {
/*
* We're the sole accessor of @wq at this point. Directly
* access numa_pwq_tbl[] and dfl_pwq to put the base refs.
* @wq will be freed when the last pwq is released.
*/
for_each_node(node) {
pwq = rcu_access_pointer(wq->numa_pwq_tbl[node]);
RCU_INIT_POINTER(wq->numa_pwq_tbl[node], NULL);
put_pwq_unlocked(pwq);
}
/*
* Put dfl_pwq. @wq may be freed any time after dfl_pwq is
* put. Don't access it afterwards.
*/
pwq = wq->dfl_pwq;
wq->dfl_pwq = NULL;
put_pwq_unlocked(pwq);
}
}
EXPORT_SYMBOL_GPL(destroy_workqueue);
/**
* workqueue_set_max_active - adjust max_active of a workqueue
* @wq: target workqueue
* @max_active: new max_active value.
*
* Set max_active of @wq to @max_active.
*
* CONTEXT:
* Don't call from IRQ context.
*/
void workqueue_set_max_active(struct workqueue_struct *wq, int max_active)
{
struct pool_workqueue *pwq;
/* disallow meddling with max_active for ordered workqueues */
if (WARN_ON(wq->flags & __WQ_ORDERED))
return;
max_active = wq_clamp_max_active(max_active, wq->flags, wq->name);
mutex_lock(&wq->mutex);
wq->saved_max_active = max_active;
for_each_pwq(pwq, wq)
pwq_adjust_max_active(pwq);
mutex_unlock(&wq->mutex);
}
EXPORT_SYMBOL_GPL(workqueue_set_max_active);
/**
* current_is_workqueue_rescuer - is %current workqueue rescuer?
*
* Determine whether %current is a workqueue rescuer. Can be used from
* work functions to determine whether it's being run off the rescuer task.
*/
bool current_is_workqueue_rescuer(void)
{
struct worker *worker = current_wq_worker();
return worker && worker->rescue_wq;
}
/**
* workqueue_congested - test whether a workqueue is congested
* @cpu: CPU in question
* @wq: target workqueue
*
* Test whether @wq's cpu workqueue for @cpu is congested. There is
* no synchronization around this function and the test result is
* unreliable and only useful as advisory hints or for debugging.
*
* If @cpu is WORK_CPU_UNBOUND, the test is performed on the local CPU.
* Note that both per-cpu and unbound workqueues may be associated with
* multiple pool_workqueues which have separate congested states. A
* workqueue being congested on one CPU doesn't mean the workqueue is also
* contested on other CPUs / NUMA nodes.
*
* RETURNS:
* %true if congested, %false otherwise.
*/
bool workqueue_congested(int cpu, struct workqueue_struct *wq)
{
struct pool_workqueue *pwq;
bool ret;
rcu_read_lock_sched();
if (cpu == WORK_CPU_UNBOUND)
cpu = smp_processor_id();
if (!(wq->flags & WQ_UNBOUND))
pwq = per_cpu_ptr(wq->cpu_pwqs, cpu);
else
pwq = unbound_pwq_by_node(wq, cpu_to_node(cpu));
ret = !list_empty(&pwq->delayed_works);
rcu_read_unlock_sched();
return ret;
}
EXPORT_SYMBOL_GPL(workqueue_congested);
/**
* work_busy - test whether a work is currently pending or running
* @work: the work to be tested
*
* Test whether @work is currently pending or running. There is no
* synchronization around this function and the test result is
* unreliable and only useful as advisory hints or for debugging.
*
* RETURNS:
* OR'd bitmask of WORK_BUSY_* bits.
*/
unsigned int work_busy(struct work_struct *work)
{
struct worker_pool *pool;
unsigned long flags;
unsigned int ret = 0;
if (work_pending(work))
ret |= WORK_BUSY_PENDING;
local_irq_save(flags);
pool = get_work_pool(work);
if (pool) {
spin_lock(&pool->lock);
if (find_worker_executing_work(pool, work))
ret |= WORK_BUSY_RUNNING;
spin_unlock(&pool->lock);
}
local_irq_restore(flags);
return ret;
}
EXPORT_SYMBOL_GPL(work_busy);
/**
* set_worker_desc - set description for the current work item
* @fmt: printf-style format string
* @...: arguments for the format string
*
* This function can be called by a running work function to describe what
* the work item is about. If the worker task gets dumped, this
* information will be printed out together to help debugging. The
* description can be at most WORKER_DESC_LEN including the trailing '\0'.
*/
void set_worker_desc(const char *fmt, ...)
{
struct worker *worker = current_wq_worker();
va_list args;
if (worker) {
va_start(args, fmt);
vsnprintf(worker->desc, sizeof(worker->desc), fmt, args);
va_end(args);
worker->desc_valid = true;
}
}
/**
* print_worker_info - print out worker information and description
* @log_lvl: the log level to use when printing
* @task: target task
*
* If @task is a worker and currently executing a work item, print out the
* name of the workqueue being serviced and worker description set with
* set_worker_desc() by the currently executing work item.
*
* This function can be safely called on any task as long as the
* task_struct itself is accessible. While safe, this function isn't
* synchronized and may print out mixups or garbages of limited length.
*/
void print_worker_info(const char *log_lvl, struct task_struct *task)
{
work_func_t *fn = NULL;
char name[WQ_NAME_LEN] = { };
char desc[WORKER_DESC_LEN] = { };
struct pool_workqueue *pwq = NULL;
struct workqueue_struct *wq = NULL;
bool desc_valid = false;
struct worker *worker;
if (!(task->flags & PF_WQ_WORKER))
return;
/*
* This function is called without any synchronization and @task
* could be in any state. Be careful with dereferences.
*/
worker = probe_kthread_data(task);
/*
* Carefully copy the associated workqueue's workfn and name. Keep
* the original last '\0' in case the original contains garbage.
*/
probe_kernel_read(&fn, &worker->current_func, sizeof(fn));
probe_kernel_read(&pwq, &worker->current_pwq, sizeof(pwq));
probe_kernel_read(&wq, &pwq->wq, sizeof(wq));
probe_kernel_read(name, wq->name, sizeof(name) - 1);
/* copy worker description */
probe_kernel_read(&desc_valid, &worker->desc_valid, sizeof(desc_valid));
if (desc_valid)
probe_kernel_read(desc, worker->desc, sizeof(desc) - 1);
if (fn || name[0] || desc[0]) {
printk("%sWorkqueue: %s %pf", log_lvl, name, fn);
if (desc[0])
pr_cont(" (%s)", desc);
pr_cont("\n");
}
}
/*
* CPU hotplug.
*
* There are two challenges in supporting CPU hotplug. Firstly, there
* are a lot of assumptions on strong associations among work, pwq and
* pool which make migrating pending and scheduled works very
* difficult to implement without impacting hot paths. Secondly,
* worker pools serve mix of short, long and very long running works making
* blocked draining impractical.
*
* This is solved by allowing the pools to be disassociated from the CPU
* running as an unbound one and allowing it to be reattached later if the
* cpu comes back online.
*/
static void wq_unbind_fn(struct work_struct *work)
{
int cpu = smp_processor_id();
struct worker_pool *pool;
struct worker *worker;
int wi;
for_each_cpu_worker_pool(pool, cpu) {
WARN_ON_ONCE(cpu != smp_processor_id());
mutex_lock(&pool->manager_mutex);
spin_lock_irq(&pool->lock);
/*
* We've blocked all manager operations. Make all workers
* unbound and set DISASSOCIATED. Before this, all workers
* except for the ones which are still executing works from
* before the last CPU down must be on the cpu. After
* this, they may become diasporas.
*/
for_each_pool_worker(worker, wi, pool)
worker->flags |= WORKER_UNBOUND;
pool->flags |= POOL_DISASSOCIATED;
spin_unlock_irq(&pool->lock);
mutex_unlock(&pool->manager_mutex);
/*
* Call schedule() so that we cross rq->lock and thus can
* guarantee sched callbacks see the %WORKER_UNBOUND flag.
* This is necessary as scheduler callbacks may be invoked
* from other cpus.
*/
schedule();
/*
* Sched callbacks are disabled now. Zap nr_running.
* After this, nr_running stays zero and need_more_worker()
* and keep_working() are always true as long as the
* worklist is not empty. This pool now behaves as an
* unbound (in terms of concurrency management) pool which
* are served by workers tied to the pool.
*/
atomic_set(&pool->nr_running, 0);
/*
* With concurrency management just turned off, a busy
* worker blocking could lead to lengthy stalls. Kick off
* unbound chain execution of currently pending work items.
*/
spin_lock_irq(&pool->lock);
wake_up_worker(pool);
spin_unlock_irq(&pool->lock);
}
}
/**
* rebind_workers - rebind all workers of a pool to the associated CPU
* @pool: pool of interest
*
* @pool->cpu is coming online. Rebind all workers to the CPU.
*/
static void rebind_workers(struct worker_pool *pool)
{
struct worker *worker;
int wi;
lockdep_assert_held(&pool->manager_mutex);
/*
* Restore CPU affinity of all workers. As all idle workers should
* be on the run-queue of the associated CPU before any local
* wake-ups for concurrency management happen, restore CPU affinty
* of all workers first and then clear UNBOUND. As we're called
* from CPU_ONLINE, the following shouldn't fail.
*/
for_each_pool_worker(worker, wi, pool)
WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task,
pool->attrs->cpumask) < 0);
spin_lock_irq(&pool->lock);
for_each_pool_worker(worker, wi, pool) {
unsigned int worker_flags = worker->flags;
/*
* A bound idle worker should actually be on the runqueue
* of the associated CPU for local wake-ups targeting it to
* work. Kick all idle workers so that they migrate to the
* associated CPU. Doing this in the same loop as
* replacing UNBOUND with REBOUND is safe as no worker will
* be bound before @pool->lock is released.
*/
if (worker_flags & WORKER_IDLE)
wake_up_process(worker->task);
/*
* We want to clear UNBOUND but can't directly call
* worker_clr_flags() or adjust nr_running. Atomically
* replace UNBOUND with another NOT_RUNNING flag REBOUND.
* @worker will clear REBOUND using worker_clr_flags() when
* it initiates the next execution cycle thus restoring
* concurrency management. Note that when or whether
* @worker clears REBOUND doesn't affect correctness.
*
* ACCESS_ONCE() is necessary because @worker->flags may be
* tested without holding any lock in
* wq_worker_waking_up(). Without it, NOT_RUNNING test may
* fail incorrectly leading to premature concurrency
* management operations.
*/
WARN_ON_ONCE(!(worker_flags & WORKER_UNBOUND));
worker_flags |= WORKER_REBOUND;
worker_flags &= ~WORKER_UNBOUND;
ACCESS_ONCE(worker->flags) = worker_flags;
}
spin_unlock_irq(&pool->lock);
}
/**
* restore_unbound_workers_cpumask - restore cpumask of unbound workers
* @pool: unbound pool of interest
* @cpu: the CPU which is coming up
*
* An unbound pool may end up with a cpumask which doesn't have any online
* CPUs. When a worker of such pool get scheduled, the scheduler resets
* its cpus_allowed. If @cpu is in @pool's cpumask which didn't have any
* online CPU before, cpus_allowed of all its workers should be restored.
*/
static void restore_unbound_workers_cpumask(struct worker_pool *pool, int cpu)
{
static cpumask_t cpumask;
struct worker *worker;
int wi;
lockdep_assert_held(&pool->manager_mutex);
/* is @cpu allowed for @pool? */
if (!cpumask_test_cpu(cpu, pool->attrs->cpumask))
return;
/* is @cpu the only online CPU? */
cpumask_and(&cpumask, pool->attrs->cpumask, cpu_online_mask);
if (cpumask_weight(&cpumask) != 1)
return;
/* as we're called from CPU_ONLINE, the following shouldn't fail */
for_each_pool_worker(worker, wi, pool)
WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task,
pool->attrs->cpumask) < 0);
}
/*
* Workqueues should be brought up before normal priority CPU notifiers.
* This will be registered high priority CPU notifier.
*/
static int __cpuinit workqueue_cpu_up_callback(struct notifier_block *nfb,
unsigned long action,
void *hcpu)
{
int cpu = (unsigned long)hcpu;
struct worker_pool *pool;
struct workqueue_struct *wq;
int pi;
switch (action & ~CPU_TASKS_FROZEN) {
case CPU_UP_PREPARE:
for_each_cpu_worker_pool(pool, cpu) {
if (pool->nr_workers)
continue;
if (create_and_start_worker(pool) < 0)
return NOTIFY_BAD;
}
break;
case CPU_DOWN_FAILED:
case CPU_ONLINE:
mutex_lock(&wq_pool_mutex);
for_each_pool(pool, pi) {
mutex_lock(&pool->manager_mutex);
if (pool->cpu == cpu) {
spin_lock_irq(&pool->lock);
pool->flags &= ~POOL_DISASSOCIATED;
spin_unlock_irq(&pool->lock);
rebind_workers(pool);
} else if (pool->cpu < 0) {
restore_unbound_workers_cpumask(pool, cpu);
}
mutex_unlock(&pool->manager_mutex);
}
/* update NUMA affinity of unbound workqueues */
list_for_each_entry(wq, &workqueues, list)
wq_update_unbound_numa(wq, cpu, true);
mutex_unlock(&wq_pool_mutex);
break;
}
return NOTIFY_OK;
}
/*
* Workqueues should be brought down after normal priority CPU notifiers.
* This will be registered as low priority CPU notifier.
*/
static int __cpuinit workqueue_cpu_down_callback(struct notifier_block *nfb,
unsigned long action,
void *hcpu)
{
int cpu = (unsigned long)hcpu;
struct work_struct unbind_work;
struct workqueue_struct *wq;
switch (action & ~CPU_TASKS_FROZEN) {
case CPU_DOWN_PREPARE:
/* unbinding per-cpu workers should happen on the local CPU */
INIT_WORK_ONSTACK(&unbind_work, wq_unbind_fn);
queue_work_on(cpu, system_highpri_wq, &unbind_work);
/* update NUMA affinity of unbound workqueues */
mutex_lock(&wq_pool_mutex);
list_for_each_entry(wq, &workqueues, list)
wq_update_unbound_numa(wq, cpu, false);
mutex_unlock(&wq_pool_mutex);
/* wait for per-cpu unbinding to finish */
flush_work(&unbind_work);
break;
}
return NOTIFY_OK;
}
#ifdef CONFIG_SMP
struct work_for_cpu {
struct work_struct work;
long (*fn)(void *);
void *arg;
long ret;
};
static void work_for_cpu_fn(struct work_struct *work)
{
struct work_for_cpu *wfc = container_of(work, struct work_for_cpu, work);
wfc->ret = wfc->fn(wfc->arg);
}
/**
* work_on_cpu - run a function in user context on a particular cpu
* @cpu: the cpu to run on
* @fn: the function to run
* @arg: the function arg
*
* This will return the value @fn returns.
* It is up to the caller to ensure that the cpu doesn't go offline.
* The caller must not hold any locks which would prevent @fn from completing.
*/
long work_on_cpu(int cpu, long (*fn)(void *), void *arg)
{
struct work_for_cpu wfc = { .fn = fn, .arg = arg };
INIT_WORK_ONSTACK(&wfc.work, work_for_cpu_fn);
schedule_work_on(cpu, &wfc.work);
flush_work(&wfc.work);
return wfc.ret;
}
EXPORT_SYMBOL_GPL(work_on_cpu);
#endif /* CONFIG_SMP */
#ifdef CONFIG_FREEZER
/**
* freeze_workqueues_begin - begin freezing workqueues
*
* Start freezing workqueues. After this function returns, all freezable
* workqueues will queue new works to their delayed_works list instead of
* pool->worklist.
*
* CONTEXT:
* Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
*/
void freeze_workqueues_begin(void)
{
struct worker_pool *pool;
struct workqueue_struct *wq;
struct pool_workqueue *pwq;
int pi;
mutex_lock(&wq_pool_mutex);
WARN_ON_ONCE(workqueue_freezing);
workqueue_freezing = true;
/* set FREEZING */
for_each_pool(pool, pi) {
spin_lock_irq(&pool->lock);
WARN_ON_ONCE(pool->flags & POOL_FREEZING);
pool->flags |= POOL_FREEZING;
spin_unlock_irq(&pool->lock);
}
list_for_each_entry(wq, &workqueues, list) {
mutex_lock(&wq->mutex);
for_each_pwq(pwq, wq)
pwq_adjust_max_active(pwq);
mutex_unlock(&wq->mutex);
}
mutex_unlock(&wq_pool_mutex);
}
/**
* freeze_workqueues_busy - are freezable workqueues still busy?
*
* Check whether freezing is complete. This function must be called
* between freeze_workqueues_begin() and thaw_workqueues().
*
* CONTEXT:
* Grabs and releases wq_pool_mutex.
*
* RETURNS:
* %true if some freezable workqueues are still busy. %false if freezing
* is complete.
*/
bool freeze_workqueues_busy(void)
{
bool busy = false;
struct workqueue_struct *wq;
struct pool_workqueue *pwq;
mutex_lock(&wq_pool_mutex);
WARN_ON_ONCE(!workqueue_freezing);
list_for_each_entry(wq, &workqueues, list) {
if (!(wq->flags & WQ_FREEZABLE))
continue;
/*
* nr_active is monotonically decreasing. It's safe
* to peek without lock.
*/
rcu_read_lock_sched();
for_each_pwq(pwq, wq) {
WARN_ON_ONCE(pwq->nr_active < 0);
if (pwq->nr_active) {
busy = true;
rcu_read_unlock_sched();
goto out_unlock;
}
}
rcu_read_unlock_sched();
}
out_unlock:
mutex_unlock(&wq_pool_mutex);
return busy;
}
/**
* thaw_workqueues - thaw workqueues
*
* Thaw workqueues. Normal queueing is restored and all collected
* frozen works are transferred to their respective pool worklists.
*
* CONTEXT:
* Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
*/
void thaw_workqueues(void)
{
struct workqueue_struct *wq;
struct pool_workqueue *pwq;
struct worker_pool *pool;
int pi;
mutex_lock(&wq_pool_mutex);
if (!workqueue_freezing)
goto out_unlock;
/* clear FREEZING */
for_each_pool(pool, pi) {
spin_lock_irq(&pool->lock);
WARN_ON_ONCE(!(pool->flags & POOL_FREEZING));
pool->flags &= ~POOL_FREEZING;
spin_unlock_irq(&pool->lock);
}
/* restore max_active and repopulate worklist */
list_for_each_entry(wq, &workqueues, list) {
mutex_lock(&wq->mutex);
for_each_pwq(pwq, wq)
pwq_adjust_max_active(pwq);
mutex_unlock(&wq->mutex);
}
workqueue_freezing = false;
out_unlock:
mutex_unlock(&wq_pool_mutex);
}
#endif /* CONFIG_FREEZER */
static void __init wq_numa_init(void)
{
cpumask_var_t *tbl;
int node, cpu;
/* determine NUMA pwq table len - highest node id + 1 */
for_each_node(node)
wq_numa_tbl_len = max(wq_numa_tbl_len, node + 1);
if (num_possible_nodes() <= 1)
return;
if (wq_disable_numa) {
pr_info("workqueue: NUMA affinity support disabled\n");
return;
}
wq_update_unbound_numa_attrs_buf = alloc_workqueue_attrs(GFP_KERNEL);
BUG_ON(!wq_update_unbound_numa_attrs_buf);
/*
* We want masks of possible CPUs of each node which isn't readily
* available. Build one from cpu_to_node() which should have been
* fully initialized by now.
*/
tbl = kzalloc(wq_numa_tbl_len * sizeof(tbl[0]), GFP_KERNEL);
BUG_ON(!tbl);
for_each_node(node)
BUG_ON(!zalloc_cpumask_var_node(&tbl[node], GFP_KERNEL,
node_online(node) ? node : NUMA_NO_NODE));
for_each_possible_cpu(cpu) {
node = cpu_to_node(cpu);
if (WARN_ON(node == NUMA_NO_NODE)) {
pr_warn("workqueue: NUMA node mapping not available for cpu%d, disabling NUMA support\n", cpu);
/* happens iff arch is bonkers, let's just proceed */
return;
}
cpumask_set_cpu(cpu, tbl[node]);
}
wq_numa_possible_cpumask = tbl;
wq_numa_enabled = true;
}
static int __init init_workqueues(void)
{
int std_nice[NR_STD_WORKER_POOLS] = { 0, HIGHPRI_NICE_LEVEL };
int i, cpu;
/* make sure we have enough bits for OFFQ pool ID */
BUILD_BUG_ON((1LU << (BITS_PER_LONG - WORK_OFFQ_POOL_SHIFT)) <
WORK_CPU_END * NR_STD_WORKER_POOLS);
WARN_ON(__alignof__(struct pool_workqueue) < __alignof__(long long));
pwq_cache = KMEM_CACHE(pool_workqueue, SLAB_PANIC);
cpu_notifier(workqueue_cpu_up_callback, CPU_PRI_WORKQUEUE_UP);
hotcpu_notifier(workqueue_cpu_down_callback, CPU_PRI_WORKQUEUE_DOWN);
wq_numa_init();
/* initialize CPU pools */
for_each_possible_cpu(cpu) {
struct worker_pool *pool;
i = 0;
for_each_cpu_worker_pool(pool, cpu) {
BUG_ON(init_worker_pool(pool));
pool->cpu = cpu;
cpumask_copy(pool->attrs->cpumask, cpumask_of(cpu));
pool->attrs->nice = std_nice[i++];
pool->node = cpu_to_node(cpu);
/* alloc pool ID */
mutex_lock(&wq_pool_mutex);
BUG_ON(worker_pool_assign_id(pool));
mutex_unlock(&wq_pool_mutex);
}
}
/* create the initial worker */
for_each_online_cpu(cpu) {
struct worker_pool *pool;
for_each_cpu_worker_pool(pool, cpu) {
pool->flags &= ~POOL_DISASSOCIATED;
BUG_ON(create_and_start_worker(pool) < 0);
}
}
/* create default unbound and ordered wq attrs */
for (i = 0; i < NR_STD_WORKER_POOLS; i++) {
struct workqueue_attrs *attrs;
BUG_ON(!(attrs = alloc_workqueue_attrs(GFP_KERNEL)));
attrs->nice = std_nice[i];
unbound_std_wq_attrs[i] = attrs;
/*
* An ordered wq should have only one pwq as ordering is
* guaranteed by max_active which is enforced by pwqs.
* Turn off NUMA so that dfl_pwq is used for all nodes.
*/
BUG_ON(!(attrs = alloc_workqueue_attrs(GFP_KERNEL)));
attrs->nice = std_nice[i];
attrs->no_numa = true;
ordered_wq_attrs[i] = attrs;
}
system_wq = alloc_workqueue("events", 0, 0);
system_highpri_wq = alloc_workqueue("events_highpri", WQ_HIGHPRI, 0);
system_long_wq = alloc_workqueue("events_long", 0, 0);
system_unbound_wq = alloc_workqueue("events_unbound", WQ_UNBOUND,
WQ_UNBOUND_MAX_ACTIVE);
system_freezable_wq = alloc_workqueue("events_freezable",
WQ_FREEZABLE, 0);
BUG_ON(!system_wq || !system_highpri_wq || !system_long_wq ||
!system_unbound_wq || !system_freezable_wq);
return 0;
}
early_initcall(init_workqueues);
| jkrishnavs/linux | kernel/workqueue.c | C | gpl-2.0 | 143,355 |
<form name="ModalForm" ng-submit="ModalCtrl.submit(ModalForm)" novalidate>
<div class="modal-header">
<ol class="headercrumb">
<li class="static" translate>TREE.INVENTORY</li>
<li class="title" translate>FORM.INFO.SEARCH</li>
</ol>
</div>
<div class="modal-body search-modal">
<uib-tabset>
<uib-tab index="0" heading="{{ 'FORM.LABELS.SEARCH_QUERIES' | translate }}" data-custom-filter-tab>
<div class="tab-body">
<bh-inventory-group-select
group-uuid="ModalCtrl.searchQueries.group_uuid"
name="group_uuid"
on-select-callback="ModalCtrl.onSelectGroup(group)">
<bh-clear on-clear="ModalCtrl.clear('group_uuid')"></bh-clear>
</bh-inventory-group-select>
<div class="form-group" ng-class="{ 'has-error' : ModalForm.$submitted && ModalForm.text.$invalid }">
<label class="control-label" translate>
FORM.LABELS.LABEL
</label>
<bh-clear on-clear="ModalCtrl.clear('text')"></bh-clear>
<input type="text" class="form-control" name="text" ng-model="ModalCtrl.searchQueries.text">
<div class="help-block" ng-messages="ModalForm.text.$error" ng-show="ModalForm.$submitted">
<div ng-messages-include="modules/templates/messages.tmpl.html"></div>
</div>
</div>
<div class="form-group" ng-class="{ 'has-error' : ModalForm.$submitted && ModalForm.code.$invalid }">
<label class="control-label" translate>
FORM.LABELS.CODE
</label>
<bh-clear on-clear="ModalCtrl.clear('code')"></bh-clear>
<input type="text" class="form-control" name="code" ng-model="ModalCtrl.searchQueries.code">
<div class="help-block" ng-messages="ModalForm.code.$error" ng-show="ModalForm.$submitted">
<div ng-messages-include="modules/templates/messages.tmpl.html"></div>
</div>
</div>
<div class="form-group" ng-class="{ 'has-error' : ModalForm.$submitted && ModalForm.price.$invalid }">
<label class="control-label" translate>
FORM.LABELS.UNIT_PRICE
</label>
<bh-clear on-clear="ModalCtrl.clear('price')"></bh-clear>
<input type="number" class="form-control" name="price" ng-model="ModalCtrl.searchQueries.price">
<div class="help-block" ng-messages="ModalForm.price.$error" ng-show="ModalForm.$submitted">
<div ng-messages-include="modules/templates/messages.tmpl.html"></div>
</div>
</div>
<bh-inventory-type-select
type-id="ModalCtrl.searchQueries.type_id"
name="type_id"
on-select-callback="ModalCtrl.onSelectType(type)">
<bh-clear on-clear="ModalCtrl.clear('type_id')"></bh-clear>
</bh-inventory-type-select>
<br/>
<div class="form-group">
<bh-clear on-clear="ModalCtrl.clear('consumable')"></bh-clear>
<label class="control-label" translate>
FORM.LABELS.CONSUMABLE
</label>
<div ng-class="{ 'has-error' : ModalForm.$submitted && ModalForm.consumable.$invalid }">
<label class="radio-inline">
<input type="radio" value='1' name="consumable" ng-model="ModalCtrl.searchQueries.consumable">
<span translate>FORM.LABELS.YES</span>
</label>
<label class="radio-inline">
<input type="radio" value='0' name="consumable" ng-model="ModalCtrl.searchQueries.consumable">
<span translate>FORM.LABELS.NO</span>
</label>
</div>
</div>
<div class="form-group">
<bh-clear on-clear="ModalCtrl.clear('locked')"></bh-clear>
<label class="control-label" translate>
FORM.LABELS.LOCKED
</label>
<div ng-class="{ 'has-error' : ModalForm.$submitted && ModalForm.locked.$invalid }">
<label class="radio-inline">
<input type="radio" value='1' name="locked" ng-model="ModalCtrl.searchQueries.locked">
<span translate>FORM.LABELS.YES</span>
</label>
<label class="radio-inline">
<input type="radio" value='0' name="locked" ng-model="ModalCtrl.searchQueries.locked">
<span translate>FORM.LABELS.NO</span>
</label>
</div>
</div></div>
</uib-tab>
<uib-tab index="1" heading="{{ 'FORM.LABELS.DEFAULTS' | translate }}" data-default-filter-tab>
<div class="tab-body">
<div class="form-group" ng-class="{ 'has-error' : ModalForm.limit.$invalid }">
<label class="control-label" translate>FORM.LABELS.LIMIT</label>
<input name="limit" type="number" bh-integer class="form-control" ng-model="ModalCtrl.defaultQueries.limit" ng-change="ModalCtrl.onSelectLimit(ModalCtrl.defaultQueries.limit)">
<div class="help-block" ng-messages="ModalForm.limit.$error">
<div ng-messages-include="modules/templates/messages.tmpl.html"></div>
</div>
</div>
</div>
</uib-tab>
</uib-tabset>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" ng-click="ModalCtrl.cancel()" data-method="cancel" translate>
FORM.BUTTONS.CLOSE
</button>
<button type="submit" class="btn btn-primary" data-method="submit" translate>
FORM.BUTTONS.SUBMIT
</button>
</div>
</form>
| IMA-WorldHealth/bhima-2.X | client/src/modules/inventory/list/modals/search.modal.html | HTML | gpl-2.0 | 5,624 |
/*
* linux/fs/proc/base.c
*
* Copyright (C) 1991, 1992 Linus Torvalds
*
* proc base directory handling functions
*
* 1999, Al Viro. Rewritten. Now it covers the whole per-process part.
* Instead of using magical inumbers to determine the kind of object
* we allocate and fill in-core inodes upon lookup. They don't even
* go into icache. We cache the reference to task_struct upon lookup too.
* Eventually it should become a filesystem in its own. We don't use the
* rest of procfs anymore.
*
*
* Changelog:
* 17-Jan-2005
* Allan Bezerra
* Bruna Moreira <bruna.moreira@indt.org.br>
* Edjard Mota <edjard.mota@indt.org.br>
* Ilias Biris <ilias.biris@indt.org.br>
* Mauricio Lin <mauricio.lin@indt.org.br>
*
* Embedded Linux Lab - 10LE Instituto Nokia de Tecnologia - INdT
*
* A new process specific entry (smaps) included in /proc. It shows the
* size of rss for each memory area. The maps entry lacks information
* about physical memory size (rss) for each mapped file, i.e.,
* rss information for executables and library files.
* This additional information is useful for any tools that need to know
* about physical memory consumption for a process specific library.
*
* Changelog:
* 21-Feb-2005
* Embedded Linux Lab - 10LE Instituto Nokia de Tecnologia - INdT
* Pud inclusion in the page table walking.
*
* ChangeLog:
* 10-Mar-2005
* 10LE Instituto Nokia de Tecnologia - INdT:
* A better way to walks through the page table as suggested by Hugh Dickins.
*
* Simo Piiroinen <simo.piiroinen@nokia.com>:
* Smaps information related to shared, private, clean and dirty pages.
*
* Paul Mundt <paul.mundt@nokia.com>:
* Overall revision about smaps.
*/
#include <asm/uaccess.h>
#include <linux/errno.h>
#include <linux/time.h>
#include <linux/proc_fs.h>
#include <linux/stat.h>
#include <linux/task_io_accounting_ops.h>
#include <linux/init.h>
#include <linux/capability.h>
#include <linux/file.h>
#include <linux/fdtable.h>
#include <linux/string.h>
#include <linux/seq_file.h>
#include <linux/namei.h>
#include <linux/mnt_namespace.h>
#include <linux/mm.h>
#include <linux/swap.h>
#include <linux/rcupdate.h>
#include <linux/kallsyms.h>
#include <linux/stacktrace.h>
#include <linux/resource.h>
#include <linux/module.h>
#include <linux/mount.h>
#include <linux/security.h>
#include <linux/ptrace.h>
#include <linux/tracehook.h>
#include <linux/printk.h>
#include <linux/cgroup.h>
#include <linux/cpuset.h>
#include <linux/audit.h>
#include <linux/poll.h>
#include <linux/nsproxy.h>
#include <linux/oom.h>
#include <linux/elf.h>
#include <linux/pid_namespace.h>
#include <linux/user_namespace.h>
#include <linux/fs_struct.h>
#include <linux/slab.h>
#include <linux/flex_array.h>
#include <linux/posix-timers.h>
#ifdef CONFIG_HARDWALL
#include <asm/hardwall.h>
#endif
#include <trace/events/oom.h>
#include "internal.h"
#include "fd.h"
extern int plasma_ary_lmk_protectedpids[50];
extern int plasma_ary_lmk_autoprotectedpids[10];
/* NOTE:
* Implementing inode permission operations in /proc is almost
* certainly an error. Permission checks need to happen during
* each system call not at open time. The reason is that most of
* what we wish to check for permissions in /proc varies at runtime.
*
* The classic example of a problem is opening file descriptors
* in /proc for a task before it execs a suid executable.
*/
struct pid_entry {
char *name;
int len;
umode_t mode;
const struct inode_operations *iop;
const struct file_operations *fop;
union proc_op op;
};
#define NOD(NAME, MODE, IOP, FOP, OP) { \
.name = (NAME), \
.len = sizeof(NAME) - 1, \
.mode = MODE, \
.iop = IOP, \
.fop = FOP, \
.op = OP, \
}
#define DIR(NAME, MODE, iops, fops) \
NOD(NAME, (S_IFDIR|(MODE)), &iops, &fops, {} )
#define LNK(NAME, get_link) \
NOD(NAME, (S_IFLNK|S_IRWXUGO), \
&proc_pid_link_inode_operations, NULL, \
{ .proc_get_link = get_link } )
#define REG(NAME, MODE, fops) \
NOD(NAME, (S_IFREG|(MODE)), NULL, &fops, {})
#define INF(NAME, MODE, read) \
NOD(NAME, (S_IFREG|(MODE)), \
NULL, &proc_info_file_operations, \
{ .proc_read = read } )
#define ONE(NAME, MODE, show) \
NOD(NAME, (S_IFREG|(MODE)), \
NULL, &proc_single_file_operations, \
{ .proc_show = show } )
/* ANDROID is for special files in /proc. */
#define ANDROID(NAME, MODE, OTYPE) \
NOD(NAME, (S_IFREG|(MODE)), \
&proc_##OTYPE##_inode_operations, \
&proc_##OTYPE##_operations, {})
/*
* Count the number of hardlinks for the pid_entry table, excluding the .
* and .. links.
*/
static unsigned int pid_entry_count_dirs(const struct pid_entry *entries,
unsigned int n)
{
unsigned int i;
unsigned int count;
count = 0;
for (i = 0; i < n; ++i) {
if (S_ISDIR(entries[i].mode))
++count;
}
return count;
}
static int get_task_root(struct task_struct *task, struct path *root)
{
int result = -ENOENT;
task_lock(task);
if (task->fs) {
get_fs_root(task->fs, root);
result = 0;
}
task_unlock(task);
return result;
}
static int proc_cwd_link(struct dentry *dentry, struct path *path)
{
struct task_struct *task = get_proc_task(dentry->d_inode);
int result = -ENOENT;
if (task) {
task_lock(task);
if (task->fs) {
get_fs_pwd(task->fs, path);
result = 0;
}
task_unlock(task);
put_task_struct(task);
}
return result;
}
static int proc_root_link(struct dentry *dentry, struct path *path)
{
struct task_struct *task = get_proc_task(dentry->d_inode);
int result = -ENOENT;
if (task) {
result = get_task_root(task, path);
put_task_struct(task);
}
return result;
}
static int proc_pid_cmdline(struct task_struct *task, char * buffer)
{
int res = 0;
unsigned int len;
struct mm_struct *mm = get_task_mm(task);
if (!mm)
goto out;
if (!mm->arg_end)
goto out_mm; /* Shh! No looking before we're done */
len = mm->arg_end - mm->arg_start;
if (len > PAGE_SIZE)
len = PAGE_SIZE;
res = access_process_vm(task, mm->arg_start, buffer, len, 0);
// If the nul at the end of args has been overwritten, then
// assume application is using setproctitle(3).
if (res > 0 && buffer[res-1] != '\0' && len < PAGE_SIZE) {
len = strnlen(buffer, res);
if (len < res) {
res = len;
} else {
len = mm->env_end - mm->env_start;
if (len > PAGE_SIZE - res)
len = PAGE_SIZE - res;
res += access_process_vm(task, mm->env_start, buffer+res, len, 0);
res = strnlen(buffer, res);
}
}
out_mm:
mmput(mm);
out:
return res;
}
static int proc_pid_auxv(struct task_struct *task, char *buffer)
{
struct mm_struct *mm = mm_access(task, PTRACE_MODE_READ);
int res = PTR_ERR(mm);
if (mm && !IS_ERR(mm)) {
unsigned int nwords = 0;
do {
nwords += 2;
} while (mm->saved_auxv[nwords - 2] != 0); /* AT_NULL */
res = nwords * sizeof(mm->saved_auxv[0]);
if (res > PAGE_SIZE)
res = PAGE_SIZE;
memcpy(buffer, mm->saved_auxv, res);
mmput(mm);
}
return res;
}
#ifdef CONFIG_KALLSYMS
/*
* Provides a wchan file via kallsyms in a proper one-value-per-file format.
* Returns the resolved symbol. If that fails, simply return the address.
*/
static int proc_pid_wchan(struct task_struct *task, char *buffer)
{
unsigned long wchan;
char symname[KSYM_NAME_LEN];
wchan = get_wchan(task);
if (lookup_symbol_name(wchan, symname) < 0)
if (!ptrace_may_access(task, PTRACE_MODE_READ))
return 0;
else
return sprintf(buffer, "%lu", wchan);
else
return sprintf(buffer, "%s", symname);
}
#endif /* CONFIG_KALLSYMS */
static int lock_trace(struct task_struct *task)
{
int err = mutex_lock_killable(&task->signal->cred_guard_mutex);
if (err)
return err;
if (!ptrace_may_access(task, PTRACE_MODE_ATTACH)) {
mutex_unlock(&task->signal->cred_guard_mutex);
return -EPERM;
}
return 0;
}
static void unlock_trace(struct task_struct *task)
{
mutex_unlock(&task->signal->cred_guard_mutex);
}
#ifdef CONFIG_STACKTRACE
#define MAX_STACK_TRACE_DEPTH 64
static int proc_pid_stack(struct seq_file *m, struct pid_namespace *ns,
struct pid *pid, struct task_struct *task)
{
struct stack_trace trace;
unsigned long *entries;
int err;
int i;
entries = kmalloc(MAX_STACK_TRACE_DEPTH * sizeof(*entries), GFP_KERNEL);
if (!entries)
return -ENOMEM;
trace.nr_entries = 0;
trace.max_entries = MAX_STACK_TRACE_DEPTH;
trace.entries = entries;
trace.skip = 0;
err = lock_trace(task);
if (!err) {
save_stack_trace_tsk(task, &trace);
for (i = 0; i < trace.nr_entries; i++) {
seq_printf(m, "[<%pK>] %pS\n",
(void *)entries[i], (void *)entries[i]);
}
unlock_trace(task);
}
kfree(entries);
return err;
}
#endif
#ifdef CONFIG_SCHEDSTATS
/*
* Provides /proc/PID/schedstat
*/
static int proc_pid_schedstat(struct task_struct *task, char *buffer)
{
return sprintf(buffer, "%llu %llu %lu\n",
(unsigned long long)task->se.sum_exec_runtime,
(unsigned long long)task->sched_info.run_delay,
task->sched_info.pcount);
}
#endif
#ifdef CONFIG_LATENCYTOP
static int lstats_show_proc(struct seq_file *m, void *v)
{
int i;
struct inode *inode = m->private;
struct task_struct *task = get_proc_task(inode);
if (!task)
return -ESRCH;
seq_puts(m, "Latency Top version : v0.1\n");
for (i = 0; i < 32; i++) {
struct latency_record *lr = &task->latency_record[i];
if (lr->backtrace[0]) {
int q;
seq_printf(m, "%i %li %li",
lr->count, lr->time, lr->max);
for (q = 0; q < LT_BACKTRACEDEPTH; q++) {
unsigned long bt = lr->backtrace[q];
if (!bt)
break;
if (bt == ULONG_MAX)
break;
seq_printf(m, " %ps", (void *)bt);
}
seq_putc(m, '\n');
}
}
put_task_struct(task);
return 0;
}
static int lstats_open(struct inode *inode, struct file *file)
{
return single_open(file, lstats_show_proc, inode);
}
static ssize_t lstats_write(struct file *file, const char __user *buf,
size_t count, loff_t *offs)
{
struct task_struct *task = get_proc_task(file_inode(file));
if (!task)
return -ESRCH;
clear_all_latency_tracing(task);
put_task_struct(task);
return count;
}
static const struct file_operations proc_lstats_operations = {
.open = lstats_open,
.read = seq_read,
.write = lstats_write,
.llseek = seq_lseek,
.release = single_release,
};
#endif
#ifdef CONFIG_CGROUPS
static int cgroup_open(struct inode *inode, struct file *file)
{
struct pid *pid = PROC_I(inode)->pid;
return single_open(file, proc_cgroup_show, pid);
}
static const struct file_operations proc_cgroup_operations = {
.open = cgroup_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
#endif
#ifdef CONFIG_PROC_PID_CPUSET
static int cpuset_open(struct inode *inode, struct file *file)
{
struct pid *pid = PROC_I(inode)->pid;
return single_open(file, proc_cpuset_show, pid);
}
static const struct file_operations proc_cpuset_operations = {
.open = cpuset_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
#endif
static int proc_oom_score(struct task_struct *task, char *buffer)
{
unsigned long totalpages = totalram_pages + total_swap_pages;
unsigned long points = 0;
read_lock(&tasklist_lock);
if (pid_alive(task))
points = oom_badness(task, NULL, NULL, totalpages) *
1000 / totalpages;
read_unlock(&tasklist_lock);
return sprintf(buffer, "%lu\n", points);
}
struct limit_names {
char *name;
char *unit;
};
static const struct limit_names lnames[RLIM_NLIMITS] = {
[RLIMIT_CPU] = {"Max cpu time", "seconds"},
[RLIMIT_FSIZE] = {"Max file size", "bytes"},
[RLIMIT_DATA] = {"Max data size", "bytes"},
[RLIMIT_STACK] = {"Max stack size", "bytes"},
[RLIMIT_CORE] = {"Max core file size", "bytes"},
[RLIMIT_RSS] = {"Max resident set", "bytes"},
[RLIMIT_NPROC] = {"Max processes", "processes"},
[RLIMIT_NOFILE] = {"Max open files", "files"},
[RLIMIT_MEMLOCK] = {"Max locked memory", "bytes"},
[RLIMIT_AS] = {"Max address space", "bytes"},
[RLIMIT_LOCKS] = {"Max file locks", "locks"},
[RLIMIT_SIGPENDING] = {"Max pending signals", "signals"},
[RLIMIT_MSGQUEUE] = {"Max msgqueue size", "bytes"},
[RLIMIT_NICE] = {"Max nice priority", NULL},
[RLIMIT_RTPRIO] = {"Max realtime priority", NULL},
[RLIMIT_RTTIME] = {"Max realtime timeout", "us"},
};
/* Display limits for a process */
static int proc_pid_limits(struct task_struct *task, char *buffer)
{
unsigned int i;
int count = 0;
unsigned long flags;
char *bufptr = buffer;
struct rlimit rlim[RLIM_NLIMITS];
if (!lock_task_sighand(task, &flags))
return 0;
memcpy(rlim, task->signal->rlim, sizeof(struct rlimit) * RLIM_NLIMITS);
unlock_task_sighand(task, &flags);
/*
* print the file header
*/
count += sprintf(&bufptr[count], "%-25s %-20s %-20s %-10s\n",
"Limit", "Soft Limit", "Hard Limit", "Units");
for (i = 0; i < RLIM_NLIMITS; i++) {
if (rlim[i].rlim_cur == RLIM_INFINITY)
count += sprintf(&bufptr[count], "%-25s %-20s ",
lnames[i].name, "unlimited");
else
count += sprintf(&bufptr[count], "%-25s %-20lu ",
lnames[i].name, rlim[i].rlim_cur);
if (rlim[i].rlim_max == RLIM_INFINITY)
count += sprintf(&bufptr[count], "%-20s ", "unlimited");
else
count += sprintf(&bufptr[count], "%-20lu ",
rlim[i].rlim_max);
if (lnames[i].unit)
count += sprintf(&bufptr[count], "%-10s\n",
lnames[i].unit);
else
count += sprintf(&bufptr[count], "\n");
}
return count;
}
#ifdef CONFIG_HAVE_ARCH_TRACEHOOK
static int proc_pid_syscall(struct task_struct *task, char *buffer)
{
long nr;
unsigned long args[6], sp, pc;
int res = lock_trace(task);
if (res)
return res;
if (task_current_syscall(task, &nr, args, 6, &sp, &pc))
res = sprintf(buffer, "running\n");
else if (nr < 0)
res = sprintf(buffer, "%ld 0x%lx 0x%lx\n", nr, sp, pc);
else
res = sprintf(buffer,
"%ld 0x%lx 0x%lx 0x%lx 0x%lx 0x%lx 0x%lx 0x%lx 0x%lx\n",
nr,
args[0], args[1], args[2], args[3], args[4], args[5],
sp, pc);
unlock_trace(task);
return res;
}
#endif /* CONFIG_HAVE_ARCH_TRACEHOOK */
/************************************************************************/
/* Here the fs part begins */
/************************************************************************/
/* permission checks */
static int proc_fd_access_allowed(struct inode *inode)
{
struct task_struct *task;
int allowed = 0;
/* Allow access to a task's file descriptors if it is us or we
* may use ptrace attach to the process and find out that
* information.
*/
task = get_proc_task(inode);
if (task) {
allowed = ptrace_may_access(task, PTRACE_MODE_READ);
put_task_struct(task);
}
return allowed;
}
int proc_setattr(struct dentry *dentry, struct iattr *attr)
{
int error;
struct inode *inode = dentry->d_inode;
if (attr->ia_valid & ATTR_MODE)
return -EPERM;
error = inode_change_ok(inode, attr);
if (error)
return error;
setattr_copy(inode, attr);
mark_inode_dirty(inode);
return 0;
}
/*
* May current process learn task's sched/cmdline info (for hide_pid_min=1)
* or euid/egid (for hide_pid_min=2)?
*/
static bool has_pid_permissions(struct pid_namespace *pid,
struct task_struct *task,
int hide_pid_min)
{
if (pid->hide_pid < hide_pid_min)
return true;
if (in_group_p(pid->pid_gid))
return true;
return ptrace_may_access(task, PTRACE_MODE_READ);
}
static int proc_pid_permission(struct inode *inode, int mask)
{
struct pid_namespace *pid = inode->i_sb->s_fs_info;
struct task_struct *task;
bool has_perms;
task = get_proc_task(inode);
if (!task)
return -ESRCH;
has_perms = has_pid_permissions(pid, task, 1);
put_task_struct(task);
if (!has_perms) {
if (pid->hide_pid == 2) {
/*
* Let's make getdents(), stat(), and open()
* consistent with each other. If a process
* may not stat() a file, it shouldn't be seen
* in procfs at all.
*/
return -ENOENT;
}
return -EPERM;
}
return generic_permission(inode, mask);
}
static const struct inode_operations proc_def_inode_operations = {
.setattr = proc_setattr,
};
#define PROC_BLOCK_SIZE (3*1024) /* 4K page size but our output routines use some slack for overruns */
static ssize_t proc_info_read(struct file * file, char __user * buf,
size_t count, loff_t *ppos)
{
struct inode * inode = file_inode(file);
unsigned long page;
ssize_t length;
struct task_struct *task = get_proc_task(inode);
length = -ESRCH;
if (!task)
goto out_no_task;
if (count > PROC_BLOCK_SIZE)
count = PROC_BLOCK_SIZE;
length = -ENOMEM;
if (!(page = __get_free_page(GFP_TEMPORARY)))
goto out;
length = PROC_I(inode)->op.proc_read(task, (char*)page);
if (length >= 0)
length = simple_read_from_buffer(buf, count, ppos, (char *)page, length);
free_page(page);
out:
put_task_struct(task);
out_no_task:
return length;
}
static const struct file_operations proc_info_file_operations = {
.read = proc_info_read,
.llseek = generic_file_llseek,
};
static int proc_single_show(struct seq_file *m, void *v)
{
struct inode *inode = m->private;
struct pid_namespace *ns;
struct pid *pid;
struct task_struct *task;
int ret;
ns = inode->i_sb->s_fs_info;
pid = proc_pid(inode);
task = get_pid_task(pid, PIDTYPE_PID);
if (!task)
return -ESRCH;
ret = PROC_I(inode)->op.proc_show(m, ns, pid, task);
put_task_struct(task);
return ret;
}
static int proc_single_open(struct inode *inode, struct file *filp)
{
return single_open(filp, proc_single_show, inode);
}
static const struct file_operations proc_single_file_operations = {
.open = proc_single_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static int __mem_open(struct inode *inode, struct file *file, unsigned int mode)
{
struct task_struct *task = get_proc_task(file_inode(file));
struct mm_struct *mm;
if (!task)
return -ESRCH;
mm = mm_access(task, mode);
put_task_struct(task);
if (IS_ERR(mm))
return PTR_ERR(mm);
if (mm) {
/* ensure this mm_struct can't be freed */
atomic_inc(&mm->mm_count);
/* but do not pin its memory */
mmput(mm);
}
file->private_data = mm;
return 0;
}
static int mem_open(struct inode *inode, struct file *file)
{
int ret = __mem_open(inode, file, PTRACE_MODE_ATTACH);
/* OK to pass negative loff_t, we can catch out-of-range */
file->f_mode |= FMODE_UNSIGNED_OFFSET;
return ret;
}
static ssize_t mem_rw(struct file *file, char __user *buf,
size_t count, loff_t *ppos, int write)
{
struct mm_struct *mm = file->private_data;
unsigned long addr = *ppos;
ssize_t copied;
char *page;
if (!mm)
return 0;
page = (char *)__get_free_page(GFP_TEMPORARY);
if (!page)
return -ENOMEM;
copied = 0;
if (!atomic_inc_not_zero(&mm->mm_users))
goto free;
while (count > 0) {
int this_len = min_t(int, count, PAGE_SIZE);
if (write && copy_from_user(page, buf, this_len)) {
copied = -EFAULT;
break;
}
this_len = access_remote_vm(mm, addr, page, this_len, write);
if (!this_len) {
if (!copied)
copied = -EIO;
break;
}
if (!write && copy_to_user(buf, page, this_len)) {
copied = -EFAULT;
break;
}
buf += this_len;
addr += this_len;
copied += this_len;
count -= this_len;
}
*ppos = addr;
mmput(mm);
free:
free_page((unsigned long) page);
return copied;
}
static ssize_t mem_read(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
return mem_rw(file, buf, count, ppos, 0);
}
static ssize_t mem_write(struct file *file, const char __user *buf,
size_t count, loff_t *ppos)
{
return mem_rw(file, (char __user*)buf, count, ppos, 1);
}
loff_t mem_lseek(struct file *file, loff_t offset, int orig)
{
switch (orig) {
case 0:
file->f_pos = offset;
break;
case 1:
file->f_pos += offset;
break;
default:
return -EINVAL;
}
force_successful_syscall_return();
return file->f_pos;
}
static int mem_release(struct inode *inode, struct file *file)
{
struct mm_struct *mm = file->private_data;
if (mm)
mmdrop(mm);
return 0;
}
static const struct file_operations proc_mem_operations = {
.llseek = mem_lseek,
.read = mem_read,
.write = mem_write,
.open = mem_open,
.release = mem_release,
};
static int environ_open(struct inode *inode, struct file *file)
{
return __mem_open(inode, file, PTRACE_MODE_READ);
}
static ssize_t environ_read(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
char *page;
unsigned long src = *ppos;
int ret = 0;
struct mm_struct *mm = file->private_data;
if (!mm)
return 0;
page = (char *)__get_free_page(GFP_TEMPORARY);
if (!page)
return -ENOMEM;
ret = 0;
if (!atomic_inc_not_zero(&mm->mm_users))
goto free;
while (count > 0) {
size_t this_len, max_len;
int retval;
if (src >= (mm->env_end - mm->env_start))
break;
this_len = mm->env_end - (mm->env_start + src);
max_len = min_t(size_t, PAGE_SIZE, count);
this_len = min(max_len, this_len);
retval = access_remote_vm(mm, (mm->env_start + src),
page, this_len, 0);
if (retval <= 0) {
ret = retval;
break;
}
if (copy_to_user(buf, page, retval)) {
ret = -EFAULT;
break;
}
ret += retval;
src += retval;
buf += retval;
count -= retval;
}
*ppos = src;
mmput(mm);
free:
free_page((unsigned long) page);
return ret;
}
static const struct file_operations proc_environ_operations = {
.open = environ_open,
.read = environ_read,
.llseek = generic_file_llseek,
.release = mem_release,
};
static ssize_t oom_adj_read(struct file *file, char __user *buf, size_t count,
loff_t *ppos)
{
struct task_struct *task = get_proc_task(file_inode(file));
char buffer[PROC_NUMBUF];
int oom_adj = OOM_ADJUST_MIN;
size_t len;
unsigned long flags;
if (!task)
return -ESRCH;
if (lock_task_sighand(task, &flags)) {
if (task->signal->oom_score_adj == OOM_SCORE_ADJ_MAX)
oom_adj = OOM_ADJUST_MAX;
else
oom_adj = (task->signal->oom_score_adj * -OOM_DISABLE) /
OOM_SCORE_ADJ_MAX;
unlock_task_sighand(task, &flags);
}
put_task_struct(task);
len = snprintf(buffer, sizeof(buffer), "%d\n", oom_adj);
return simple_read_from_buffer(buf, count, ppos, buffer, len);
}
static ssize_t oom_adj_write(struct file *file, const char __user *buf,
size_t count, loff_t *ppos)
{
struct task_struct *task;
char buffer[PROC_NUMBUF];
int oom_adj;
unsigned long flags;
int err;
int i;
int plasma_white_size = ARRAY_SIZE(plasma_ary_lmk_protectedpids);
//int plasma_autowhite_size = ARRAY_SIZE(plasma_ary_lmk_autoprotectedpids);
memset(buffer, 0, sizeof(buffer));
if (count > sizeof(buffer) - 1)
count = sizeof(buffer) - 1;
if (copy_from_user(buffer, buf, count)) {
err = -EFAULT;
goto out;
}
err = kstrtoint(strstrip(buffer), 0, &oom_adj);
if (err)
goto out;
if ((oom_adj < OOM_ADJUST_MIN || oom_adj > OOM_ADJUST_MAX) &&
oom_adj != OOM_DISABLE) {
err = -EINVAL;
goto out;
}
task = get_proc_task(file_inode(file));
if (!task) {
err = -ESRCH;
goto out;
}
task_lock(task);
if (!task->mm) {
err = -EINVAL;
goto err_task_lock;
}
if (!lock_task_sighand(task, &flags)) {
err = -ESRCH;
goto err_task_lock;
}
/*
* Scale /proc/pid/oom_score_adj appropriately ensuring that a maximum
* value is always attainable.
*/
if (oom_adj == OOM_ADJUST_MAX)
oom_adj = OOM_SCORE_ADJ_MAX;
else
oom_adj = (oom_adj * OOM_SCORE_ADJ_MAX) / -OOM_DISABLE;
if (oom_adj < task->signal->oom_score_adj &&
!capable(CAP_SYS_RESOURCE)) {
err = -EACCES;
goto err_sighand;
}
/*
* /proc/pid/oom_adj is provided for legacy purposes, ask users to use
* /proc/pid/oom_score_adj instead.
*/
pr_warn_once("%s (%d): /proc/%d/oom_adj is deprecated, please use /proc/%d/oom_score_adj instead.\n",
current->comm, task_pid_nr(current), task_pid_nr(task),
task_pid_nr(task));
// whitelisted processes should have an oom_adj of 0.
for (i = 0; i < plasma_white_size; i++) {
if (task->pid == plasma_ary_lmk_protectedpids[i]) {
//pr_info("%s: adjusting plasma whitelisted process %d (%s) to oom_adj 0\n",
// __func__, task->pid, task->comm);
oom_adj = -1000;
//goto found;
}
}
/*// this list is for the last few recently used apps, as added by a shell script.
// it is a small list that is autonomously maintained, and therefore cannot be
// mixed with other whitelists.
for (i = 0; i < plasma_autowhite_size; i++) {
if (task->pid == plasma_ary_lmk_autoprotectedpids[i]) {
pr_info("%s: adjusting plasma autowhitelisted process %d (%s) to oom_adj 0\n",
__func__, task->pid, task->comm);
oom_adj = 0;
break;
}
}*/
//found:
task->signal->oom_score_adj = oom_adj;
trace_oom_score_adj_update(task);
err_sighand:
unlock_task_sighand(task, &flags);
err_task_lock:
task_unlock(task);
put_task_struct(task);
out:
return err < 0 ? err : count;
}
static int oom_adjust_permission(struct inode *inode, int mask)
{
uid_t uid;
struct task_struct *p;
p = get_proc_task(inode);
if(p) {
uid = task_uid(p);
put_task_struct(p);
}
/*
* System Server (uid == 1000) is granted access to oom_adj of all
* android applications (uid > 10000) as and services (uid >= 1000)
*/
if (p && (current_fsuid() == 1000) && (uid >= 1000)) {
if (inode->i_mode >> 6 & mask) {
return 0;
}
}
/* Fall back to default. */
return generic_permission(inode, mask);
}
static const struct inode_operations proc_oom_adj_inode_operations = {
.permission = oom_adjust_permission,
};
static const struct file_operations proc_oom_adj_operations = {
.read = oom_adj_read,
.write = oom_adj_write,
.llseek = generic_file_llseek,
};
static ssize_t oom_score_adj_read(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
struct task_struct *task = get_proc_task(file_inode(file));
char buffer[PROC_NUMBUF];
short oom_score_adj = OOM_SCORE_ADJ_MIN;
unsigned long flags;
size_t len;
if (!task)
return -ESRCH;
if (lock_task_sighand(task, &flags)) {
oom_score_adj = task->signal->oom_score_adj;
unlock_task_sighand(task, &flags);
}
put_task_struct(task);
len = snprintf(buffer, sizeof(buffer), "%hd\n", oom_score_adj);
return simple_read_from_buffer(buf, count, ppos, buffer, len);
}
static ssize_t oom_score_adj_write(struct file *file, const char __user *buf,
size_t count, loff_t *ppos)
{
struct task_struct *task;
char buffer[PROC_NUMBUF];
unsigned long flags;
int oom_score_adj;
int err;
int i;
int plasma_white_size = ARRAY_SIZE(plasma_ary_lmk_protectedpids);
//int plasma_autowhite_size = ARRAY_SIZE(plasma_ary_lmk_autoprotectedpids);
memset(buffer, 0, sizeof(buffer));
if (count > sizeof(buffer) - 1)
count = sizeof(buffer) - 1;
if (copy_from_user(buffer, buf, count)) {
err = -EFAULT;
goto out;
}
err = kstrtoint(strstrip(buffer), 0, &oom_score_adj);
if (err)
goto out;
if (oom_score_adj < OOM_SCORE_ADJ_MIN ||
oom_score_adj > OOM_SCORE_ADJ_MAX) {
err = -EINVAL;
goto out;
}
task = get_proc_task(file_inode(file));
if (!task) {
err = -ESRCH;
goto out;
}
task_lock(task);
if (!task->mm) {
err = -EINVAL;
goto err_task_lock;
}
if (!lock_task_sighand(task, &flags)) {
err = -ESRCH;
goto err_task_lock;
}
if ((short)oom_score_adj < task->signal->oom_score_adj_min &&
!capable(CAP_SYS_RESOURCE)) {
err = -EACCES;
goto err_sighand;
}
// whitelisted processes should have an oom_adj of 0.
for (i = 0; i < plasma_white_size; i++) {
if (task->pid == plasma_ary_lmk_protectedpids[i]) {
//pr_info("%s: adjusting plasma whitelisted process %d (%s) to oom_adj 0\n",
// __func__, task->pid, task->comm);
oom_score_adj = -1000;
//goto found;
}
}
/*// this list is for the last few recently used apps, as added by a shell script.
// it is a small list that is autonomously maintained, and therefore cannot be
// mixed with other whitelists.
for (i = 0; i < plasma_autowhite_size; i++) {
if (task->pid == plasma_ary_lmk_autoprotectedpids[i]) {
pr_info("%s: adjusting plasma autowhitelisted process %d (%s) to oom_adj 0\n",
__func__, task->pid, task->comm);
oom_score_adj = 0;
break;
}
}
found:*/
//pr_info("%s: adjusting process %d (%s) to oom_adj %d\n",
// __func__, task->pid, task->comm, oom_score_adj);
task->signal->oom_score_adj = (short)oom_score_adj;
if (has_capability_noaudit(current, CAP_SYS_RESOURCE))
task->signal->oom_score_adj_min = (short)oom_score_adj;
trace_oom_score_adj_update(task);
err_sighand:
unlock_task_sighand(task, &flags);
err_task_lock:
task_unlock(task);
put_task_struct(task);
out:
return err < 0 ? err : count;
}
static const struct file_operations proc_oom_score_adj_operations = {
.read = oom_score_adj_read,
.write = oom_score_adj_write,
.llseek = default_llseek,
};
#ifdef CONFIG_AUDITSYSCALL
#define TMPBUFLEN 21
static ssize_t proc_loginuid_read(struct file * file, char __user * buf,
size_t count, loff_t *ppos)
{
struct inode * inode = file_inode(file);
struct task_struct *task = get_proc_task(inode);
ssize_t length;
char tmpbuf[TMPBUFLEN];
if (!task)
return -ESRCH;
length = scnprintf(tmpbuf, TMPBUFLEN, "%u",
from_kuid(file->f_cred->user_ns,
audit_get_loginuid(task)));
put_task_struct(task);
return simple_read_from_buffer(buf, count, ppos, tmpbuf, length);
}
static ssize_t proc_loginuid_write(struct file * file, const char __user * buf,
size_t count, loff_t *ppos)
{
struct inode * inode = file_inode(file);
char *page, *tmp;
ssize_t length;
uid_t loginuid;
kuid_t kloginuid;
rcu_read_lock();
if (current != pid_task(proc_pid(inode), PIDTYPE_PID)) {
rcu_read_unlock();
return -EPERM;
}
rcu_read_unlock();
if (count >= PAGE_SIZE)
count = PAGE_SIZE - 1;
if (*ppos != 0) {
/* No partial writes. */
return -EINVAL;
}
page = (char*)__get_free_page(GFP_TEMPORARY);
if (!page)
return -ENOMEM;
length = -EFAULT;
if (copy_from_user(page, buf, count))
goto out_free_page;
page[count] = '\0';
loginuid = simple_strtoul(page, &tmp, 10);
if (tmp == page) {
length = -EINVAL;
goto out_free_page;
}
kloginuid = make_kuid(file->f_cred->user_ns, loginuid);
if (!uid_valid(kloginuid)) {
length = -EINVAL;
goto out_free_page;
}
length = audit_set_loginuid(kloginuid);
if (likely(length == 0))
length = count;
out_free_page:
free_page((unsigned long) page);
return length;
}
static const struct file_operations proc_loginuid_operations = {
.read = proc_loginuid_read,
.write = proc_loginuid_write,
.llseek = generic_file_llseek,
};
static ssize_t proc_sessionid_read(struct file * file, char __user * buf,
size_t count, loff_t *ppos)
{
struct inode * inode = file_inode(file);
struct task_struct *task = get_proc_task(inode);
ssize_t length;
char tmpbuf[TMPBUFLEN];
if (!task)
return -ESRCH;
length = scnprintf(tmpbuf, TMPBUFLEN, "%u",
audit_get_sessionid(task));
put_task_struct(task);
return simple_read_from_buffer(buf, count, ppos, tmpbuf, length);
}
static const struct file_operations proc_sessionid_operations = {
.read = proc_sessionid_read,
.llseek = generic_file_llseek,
};
#endif
#ifdef CONFIG_FAULT_INJECTION
static ssize_t proc_fault_inject_read(struct file * file, char __user * buf,
size_t count, loff_t *ppos)
{
struct task_struct *task = get_proc_task(file_inode(file));
char buffer[PROC_NUMBUF];
size_t len;
int make_it_fail;
if (!task)
return -ESRCH;
make_it_fail = task->make_it_fail;
put_task_struct(task);
len = snprintf(buffer, sizeof(buffer), "%i\n", make_it_fail);
return simple_read_from_buffer(buf, count, ppos, buffer, len);
}
static ssize_t proc_fault_inject_write(struct file * file,
const char __user * buf, size_t count, loff_t *ppos)
{
struct task_struct *task;
char buffer[PROC_NUMBUF], *end;
int make_it_fail;
if (!capable(CAP_SYS_RESOURCE))
return -EPERM;
memset(buffer, 0, sizeof(buffer));
if (count > sizeof(buffer) - 1)
count = sizeof(buffer) - 1;
if (copy_from_user(buffer, buf, count))
return -EFAULT;
make_it_fail = simple_strtol(strstrip(buffer), &end, 0);
if (*end)
return -EINVAL;
task = get_proc_task(file_inode(file));
if (!task)
return -ESRCH;
task->make_it_fail = make_it_fail;
put_task_struct(task);
return count;
}
static const struct file_operations proc_fault_inject_operations = {
.read = proc_fault_inject_read,
.write = proc_fault_inject_write,
.llseek = generic_file_llseek,
};
#endif
#ifdef CONFIG_SCHED_DEBUG
/*
* Print out various scheduling related per-task fields:
*/
static int sched_show(struct seq_file *m, void *v)
{
struct inode *inode = m->private;
struct task_struct *p;
p = get_proc_task(inode);
if (!p)
return -ESRCH;
proc_sched_show_task(p, m);
put_task_struct(p);
return 0;
}
static ssize_t
sched_write(struct file *file, const char __user *buf,
size_t count, loff_t *offset)
{
struct inode *inode = file_inode(file);
struct task_struct *p;
p = get_proc_task(inode);
if (!p)
return -ESRCH;
proc_sched_set_task(p);
put_task_struct(p);
return count;
}
static int sched_open(struct inode *inode, struct file *filp)
{
return single_open(filp, sched_show, inode);
}
static const struct file_operations proc_pid_sched_operations = {
.open = sched_open,
.read = seq_read,
.write = sched_write,
.llseek = seq_lseek,
.release = single_release,
};
#endif
#ifdef CONFIG_SCHED_AUTOGROUP
/*
* Print out autogroup related information:
*/
static int sched_autogroup_show(struct seq_file *m, void *v)
{
struct inode *inode = m->private;
struct task_struct *p;
p = get_proc_task(inode);
if (!p)
return -ESRCH;
proc_sched_autogroup_show_task(p, m);
put_task_struct(p);
return 0;
}
static ssize_t
sched_autogroup_write(struct file *file, const char __user *buf,
size_t count, loff_t *offset)
{
struct inode *inode = file_inode(file);
struct task_struct *p;
char buffer[PROC_NUMBUF];
int nice;
int err;
memset(buffer, 0, sizeof(buffer));
if (count > sizeof(buffer) - 1)
count = sizeof(buffer) - 1;
if (copy_from_user(buffer, buf, count))
return -EFAULT;
err = kstrtoint(strstrip(buffer), 0, &nice);
if (err < 0)
return err;
p = get_proc_task(inode);
if (!p)
return -ESRCH;
err = proc_sched_autogroup_set_nice(p, nice);
if (err)
count = err;
put_task_struct(p);
return count;
}
static int sched_autogroup_open(struct inode *inode, struct file *filp)
{
int ret;
ret = single_open(filp, sched_autogroup_show, NULL);
if (!ret) {
struct seq_file *m = filp->private_data;
m->private = inode;
}
return ret;
}
static const struct file_operations proc_pid_sched_autogroup_operations = {
.open = sched_autogroup_open,
.read = seq_read,
.write = sched_autogroup_write,
.llseek = seq_lseek,
.release = single_release,
};
#endif /* CONFIG_SCHED_AUTOGROUP */
static ssize_t comm_write(struct file *file, const char __user *buf,
size_t count, loff_t *offset)
{
struct inode *inode = file_inode(file);
struct task_struct *p;
char buffer[TASK_COMM_LEN];
const size_t maxlen = sizeof(buffer) - 1;
memset(buffer, 0, sizeof(buffer));
if (copy_from_user(buffer, buf, count > maxlen ? maxlen : count))
return -EFAULT;
p = get_proc_task(inode);
if (!p)
return -ESRCH;
if (same_thread_group(current, p))
set_task_comm(p, buffer);
else
count = -EINVAL;
put_task_struct(p);
return count;
}
static int comm_show(struct seq_file *m, void *v)
{
struct inode *inode = m->private;
struct task_struct *p;
p = get_proc_task(inode);
if (!p)
return -ESRCH;
task_lock(p);
seq_printf(m, "%s\n", p->comm);
task_unlock(p);
put_task_struct(p);
return 0;
}
static int comm_open(struct inode *inode, struct file *filp)
{
return single_open(filp, comm_show, inode);
}
static const struct file_operations proc_pid_set_comm_operations = {
.open = comm_open,
.read = seq_read,
.write = comm_write,
.llseek = seq_lseek,
.release = single_release,
};
static int proc_exe_link(struct dentry *dentry, struct path *exe_path)
{
struct task_struct *task;
struct mm_struct *mm;
struct file *exe_file;
task = get_proc_task(dentry->d_inode);
if (!task)
return -ENOENT;
mm = get_task_mm(task);
put_task_struct(task);
if (!mm)
return -ENOENT;
exe_file = get_mm_exe_file(mm);
mmput(mm);
if (exe_file) {
*exe_path = exe_file->f_path;
path_get(&exe_file->f_path);
fput(exe_file);
return 0;
} else
return -ENOENT;
}
static void *proc_pid_follow_link(struct dentry *dentry, struct nameidata *nd)
{
struct inode *inode = dentry->d_inode;
struct path path;
int error = -EACCES;
/* Are we allowed to snoop on the tasks file descriptors? */
if (!proc_fd_access_allowed(inode))
goto out;
error = PROC_I(inode)->op.proc_get_link(dentry, &path);
if (error)
goto out;
nd_jump_link(nd, &path);
return NULL;
out:
return ERR_PTR(error);
}
static int do_proc_readlink(struct path *path, char __user *buffer, int buflen)
{
char *tmp = (char*)__get_free_page(GFP_TEMPORARY);
char *pathname;
int len;
if (!tmp)
return -ENOMEM;
pathname = d_path(path, tmp, PAGE_SIZE);
len = PTR_ERR(pathname);
if (IS_ERR(pathname))
goto out;
len = tmp + PAGE_SIZE - 1 - pathname;
if (len > buflen)
len = buflen;
if (copy_to_user(buffer, pathname, len))
len = -EFAULT;
out:
free_page((unsigned long)tmp);
return len;
}
static int proc_pid_readlink(struct dentry * dentry, char __user * buffer, int buflen)
{
int error = -EACCES;
struct inode *inode = dentry->d_inode;
struct path path;
/* Are we allowed to snoop on the tasks file descriptors? */
if (!proc_fd_access_allowed(inode))
goto out;
error = PROC_I(inode)->op.proc_get_link(dentry, &path);
if (error)
goto out;
error = do_proc_readlink(&path, buffer, buflen);
path_put(&path);
out:
return error;
}
const struct inode_operations proc_pid_link_inode_operations = {
.readlink = proc_pid_readlink,
.follow_link = proc_pid_follow_link,
.setattr = proc_setattr,
};
/* building an inode */
struct inode *proc_pid_make_inode(struct super_block * sb, struct task_struct *task)
{
struct inode * inode;
struct proc_inode *ei;
const struct cred *cred;
/* We need a new inode */
inode = new_inode(sb);
if (!inode)
goto out;
/* Common stuff */
ei = PROC_I(inode);
inode->i_ino = get_next_ino();
inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
inode->i_op = &proc_def_inode_operations;
/*
* grab the reference to task.
*/
ei->pid = get_task_pid(task, PIDTYPE_PID);
if (!ei->pid)
goto out_unlock;
if (task_dumpable(task)) {
rcu_read_lock();
cred = __task_cred(task);
inode->i_uid = cred->euid;
inode->i_gid = cred->egid;
rcu_read_unlock();
}
security_task_to_inode(task, inode);
out:
return inode;
out_unlock:
iput(inode);
return NULL;
}
int pid_getattr(struct vfsmount *mnt, struct dentry *dentry, struct kstat *stat)
{
struct inode *inode = dentry->d_inode;
struct task_struct *task;
const struct cred *cred;
struct pid_namespace *pid = dentry->d_sb->s_fs_info;
generic_fillattr(inode, stat);
rcu_read_lock();
stat->uid = GLOBAL_ROOT_UID;
stat->gid = GLOBAL_ROOT_GID;
task = pid_task(proc_pid(inode), PIDTYPE_PID);
if (task) {
if (!has_pid_permissions(pid, task, 2)) {
rcu_read_unlock();
/*
* This doesn't prevent learning whether PID exists,
* it only makes getattr() consistent with readdir().
*/
return -ENOENT;
}
if ((inode->i_mode == (S_IFDIR|S_IRUGO|S_IXUGO)) ||
task_dumpable(task)) {
cred = __task_cred(task);
stat->uid = cred->euid;
stat->gid = cred->egid;
}
}
rcu_read_unlock();
return 0;
}
/* dentry stuff */
/*
* Exceptional case: normally we are not allowed to unhash a busy
* directory. In this case, however, we can do it - no aliasing problems
* due to the way we treat inodes.
*
* Rewrite the inode's ownerships here because the owning task may have
* performed a setuid(), etc.
*
* Before the /proc/pid/status file was created the only way to read
* the effective uid of a /process was to stat /proc/pid. Reading
* /proc/pid/status is slow enough that procps and other packages
* kept stating /proc/pid. To keep the rules in /proc simple I have
* made this apply to all per process world readable and executable
* directories.
*/
int pid_revalidate(struct dentry *dentry, unsigned int flags)
{
struct inode *inode;
struct task_struct *task;
const struct cred *cred;
if (flags & LOOKUP_RCU)
return -ECHILD;
inode = dentry->d_inode;
task = get_proc_task(inode);
if (task) {
if ((inode->i_mode == (S_IFDIR|S_IRUGO|S_IXUGO)) ||
task_dumpable(task)) {
rcu_read_lock();
cred = __task_cred(task);
inode->i_uid = cred->euid;
inode->i_gid = cred->egid;
rcu_read_unlock();
} else {
inode->i_uid = GLOBAL_ROOT_UID;
inode->i_gid = GLOBAL_ROOT_GID;
}
inode->i_mode &= ~(S_ISUID | S_ISGID);
security_task_to_inode(task, inode);
put_task_struct(task);
return 1;
}
d_drop(dentry);
return 0;
}
int pid_delete_dentry(const struct dentry *dentry)
{
/* Is the task we represent dead?
* If so, then don't put the dentry on the lru list,
* kill it immediately.
*/
return !proc_pid(dentry->d_inode)->tasks[PIDTYPE_PID].first;
}
const struct dentry_operations pid_dentry_operations =
{
.d_revalidate = pid_revalidate,
.d_delete = pid_delete_dentry,
};
/* Lookups */
/*
* Fill a directory entry.
*
* If possible create the dcache entry and derive our inode number and
* file type from dcache entry.
*
* Since all of the proc inode numbers are dynamically generated, the inode
* numbers do not exist until the inode is cache. This means creating the
* the dcache entry in readdir is necessary to keep the inode numbers
* reported by readdir in sync with the inode numbers reported
* by stat.
*/
int proc_fill_cache(struct file *filp, void *dirent, filldir_t filldir,
const char *name, int len,
instantiate_t instantiate, struct task_struct *task, const void *ptr)
{
struct dentry *child, *dir = filp->f_path.dentry;
struct inode *inode;
struct qstr qname;
ino_t ino = 0;
unsigned type = DT_UNKNOWN;
qname.name = name;
qname.len = len;
qname.hash = full_name_hash(name, len);
child = d_lookup(dir, &qname);
if (!child) {
struct dentry *new;
new = d_alloc(dir, &qname);
if (new) {
child = instantiate(dir->d_inode, new, task, ptr);
if (child)
dput(new);
else
child = new;
}
}
if (!child || IS_ERR(child) || !child->d_inode)
goto end_instantiate;
inode = child->d_inode;
if (inode) {
ino = inode->i_ino;
type = inode->i_mode >> 12;
}
dput(child);
end_instantiate:
if (!ino)
ino = find_inode_number(dir, &qname);
if (!ino)
ino = 1;
return filldir(dirent, name, len, filp->f_pos, ino, type);
}
#ifdef CONFIG_CHECKPOINT_RESTORE
/*
* dname_to_vma_addr - maps a dentry name into two unsigned longs
* which represent vma start and end addresses.
*/
static int dname_to_vma_addr(struct dentry *dentry,
unsigned long *start, unsigned long *end)
{
if (sscanf(dentry->d_name.name, "%lx-%lx", start, end) != 2)
return -EINVAL;
return 0;
}
static int map_files_d_revalidate(struct dentry *dentry, unsigned int flags)
{
unsigned long vm_start, vm_end;
bool exact_vma_exists = false;
struct mm_struct *mm = NULL;
struct task_struct *task;
const struct cred *cred;
struct inode *inode;
int status = 0;
if (flags & LOOKUP_RCU)
return -ECHILD;
if (!capable(CAP_SYS_ADMIN)) {
status = -EPERM;
goto out_notask;
}
inode = dentry->d_inode;
task = get_proc_task(inode);
if (!task)
goto out_notask;
mm = mm_access(task, PTRACE_MODE_READ);
if (IS_ERR_OR_NULL(mm))
goto out;
if (!dname_to_vma_addr(dentry, &vm_start, &vm_end)) {
down_read(&mm->mmap_sem);
exact_vma_exists = !!find_exact_vma(mm, vm_start, vm_end);
up_read(&mm->mmap_sem);
}
mmput(mm);
if (exact_vma_exists) {
if (task_dumpable(task)) {
rcu_read_lock();
cred = __task_cred(task);
inode->i_uid = cred->euid;
inode->i_gid = cred->egid;
rcu_read_unlock();
} else {
inode->i_uid = GLOBAL_ROOT_UID;
inode->i_gid = GLOBAL_ROOT_GID;
}
security_task_to_inode(task, inode);
status = 1;
}
out:
put_task_struct(task);
out_notask:
if (status <= 0)
d_drop(dentry);
return status;
}
static const struct dentry_operations tid_map_files_dentry_operations = {
.d_revalidate = map_files_d_revalidate,
.d_delete = pid_delete_dentry,
};
static int proc_map_files_get_link(struct dentry *dentry, struct path *path)
{
unsigned long vm_start, vm_end;
struct vm_area_struct *vma;
struct task_struct *task;
struct mm_struct *mm;
int rc;
rc = -ENOENT;
task = get_proc_task(dentry->d_inode);
if (!task)
goto out;
mm = get_task_mm(task);
put_task_struct(task);
if (!mm)
goto out;
rc = dname_to_vma_addr(dentry, &vm_start, &vm_end);
if (rc)
goto out_mmput;
rc = -ENOENT;
down_read(&mm->mmap_sem);
vma = find_exact_vma(mm, vm_start, vm_end);
if (vma && vma->vm_file) {
*path = vma->vm_file->f_path;
path_get(path);
rc = 0;
}
up_read(&mm->mmap_sem);
out_mmput:
mmput(mm);
out:
return rc;
}
struct map_files_info {
fmode_t mode;
unsigned long len;
unsigned char name[4*sizeof(long)+2]; /* max: %lx-%lx\0 */
};
static struct dentry *
proc_map_files_instantiate(struct inode *dir, struct dentry *dentry,
struct task_struct *task, const void *ptr)
{
fmode_t mode = (fmode_t)(unsigned long)ptr;
struct proc_inode *ei;
struct inode *inode;
inode = proc_pid_make_inode(dir->i_sb, task);
if (!inode)
return ERR_PTR(-ENOENT);
ei = PROC_I(inode);
ei->op.proc_get_link = proc_map_files_get_link;
inode->i_op = &proc_pid_link_inode_operations;
inode->i_size = 64;
inode->i_mode = S_IFLNK;
if (mode & FMODE_READ)
inode->i_mode |= S_IRUSR;
if (mode & FMODE_WRITE)
inode->i_mode |= S_IWUSR;
d_set_d_op(dentry, &tid_map_files_dentry_operations);
d_add(dentry, inode);
return NULL;
}
static struct dentry *proc_map_files_lookup(struct inode *dir,
struct dentry *dentry, unsigned int flags)
{
unsigned long vm_start, vm_end;
struct vm_area_struct *vma;
struct task_struct *task;
struct dentry *result;
struct mm_struct *mm;
result = ERR_PTR(-EPERM);
if (!capable(CAP_SYS_ADMIN))
goto out;
result = ERR_PTR(-ENOENT);
task = get_proc_task(dir);
if (!task)
goto out;
result = ERR_PTR(-EACCES);
if (!ptrace_may_access(task, PTRACE_MODE_READ))
goto out_put_task;
result = ERR_PTR(-ENOENT);
if (dname_to_vma_addr(dentry, &vm_start, &vm_end))
goto out_put_task;
mm = get_task_mm(task);
if (!mm)
goto out_put_task;
down_read(&mm->mmap_sem);
vma = find_exact_vma(mm, vm_start, vm_end);
if (!vma)
goto out_no_vma;
if (vma->vm_file)
result = proc_map_files_instantiate(dir, dentry, task,
(void *)(unsigned long)vma->vm_file->f_mode);
out_no_vma:
up_read(&mm->mmap_sem);
mmput(mm);
out_put_task:
put_task_struct(task);
out:
return result;
}
static const struct inode_operations proc_map_files_inode_operations = {
.lookup = proc_map_files_lookup,
.permission = proc_fd_permission,
.setattr = proc_setattr,
};
static int
proc_map_files_readdir(struct file *filp, void *dirent, filldir_t filldir)
{
struct dentry *dentry = filp->f_path.dentry;
struct inode *inode = dentry->d_inode;
struct vm_area_struct *vma;
struct task_struct *task;
struct mm_struct *mm;
ino_t ino;
int ret;
ret = -EPERM;
if (!capable(CAP_SYS_ADMIN))
goto out;
ret = -ENOENT;
task = get_proc_task(inode);
if (!task)
goto out;
ret = -EACCES;
if (!ptrace_may_access(task, PTRACE_MODE_READ))
goto out_put_task;
ret = 0;
switch (filp->f_pos) {
case 0:
ino = inode->i_ino;
if (filldir(dirent, ".", 1, 0, ino, DT_DIR) < 0)
goto out_put_task;
filp->f_pos++;
case 1:
ino = parent_ino(dentry);
if (filldir(dirent, "..", 2, 1, ino, DT_DIR) < 0)
goto out_put_task;
filp->f_pos++;
default:
{
unsigned long nr_files, pos, i;
struct flex_array *fa = NULL;
struct map_files_info info;
struct map_files_info *p;
mm = get_task_mm(task);
if (!mm)
goto out_put_task;
down_read(&mm->mmap_sem);
nr_files = 0;
/*
* We need two passes here:
*
* 1) Collect vmas of mapped files with mmap_sem taken
* 2) Release mmap_sem and instantiate entries
*
* otherwise we get lockdep complained, since filldir()
* routine might require mmap_sem taken in might_fault().
*/
for (vma = mm->mmap, pos = 2; vma; vma = vma->vm_next) {
if (vma->vm_file && ++pos > filp->f_pos)
nr_files++;
}
if (nr_files) {
fa = flex_array_alloc(sizeof(info), nr_files,
GFP_KERNEL);
if (!fa || flex_array_prealloc(fa, 0, nr_files,
GFP_KERNEL)) {
ret = -ENOMEM;
if (fa)
flex_array_free(fa);
up_read(&mm->mmap_sem);
mmput(mm);
goto out_put_task;
}
for (i = 0, vma = mm->mmap, pos = 2; vma;
vma = vma->vm_next) {
if (!vma->vm_file)
continue;
if (++pos <= filp->f_pos)
continue;
info.mode = vma->vm_file->f_mode;
info.len = snprintf(info.name,
sizeof(info.name), "%lx-%lx",
vma->vm_start, vma->vm_end);
if (flex_array_put(fa, i++, &info, GFP_KERNEL))
BUG();
}
}
up_read(&mm->mmap_sem);
for (i = 0; i < nr_files; i++) {
p = flex_array_get(fa, i);
ret = proc_fill_cache(filp, dirent, filldir,
p->name, p->len,
proc_map_files_instantiate,
task,
(void *)(unsigned long)p->mode);
if (ret)
break;
filp->f_pos++;
}
if (fa)
flex_array_free(fa);
mmput(mm);
}
}
out_put_task:
put_task_struct(task);
out:
return ret;
}
static const struct file_operations proc_map_files_operations = {
.read = generic_read_dir,
.readdir = proc_map_files_readdir,
.llseek = default_llseek,
};
struct timers_private {
struct pid *pid;
struct task_struct *task;
struct sighand_struct *sighand;
struct pid_namespace *ns;
unsigned long flags;
};
static void *timers_start(struct seq_file *m, loff_t *pos)
{
struct timers_private *tp = m->private;
tp->task = get_pid_task(tp->pid, PIDTYPE_PID);
if (!tp->task)
return ERR_PTR(-ESRCH);
tp->sighand = lock_task_sighand(tp->task, &tp->flags);
if (!tp->sighand)
return ERR_PTR(-ESRCH);
return seq_list_start(&tp->task->signal->posix_timers, *pos);
}
static void *timers_next(struct seq_file *m, void *v, loff_t *pos)
{
struct timers_private *tp = m->private;
return seq_list_next(v, &tp->task->signal->posix_timers, pos);
}
static void timers_stop(struct seq_file *m, void *v)
{
struct timers_private *tp = m->private;
if (tp->sighand) {
unlock_task_sighand(tp->task, &tp->flags);
tp->sighand = NULL;
}
if (tp->task) {
put_task_struct(tp->task);
tp->task = NULL;
}
}
static int show_timer(struct seq_file *m, void *v)
{
struct k_itimer *timer;
struct timers_private *tp = m->private;
int notify;
static char *nstr[] = {
[SIGEV_SIGNAL] = "signal",
[SIGEV_NONE] = "none",
[SIGEV_THREAD] = "thread",
};
timer = list_entry((struct list_head *)v, struct k_itimer, list);
notify = timer->it_sigev_notify;
seq_printf(m, "ID: %d\n", timer->it_id);
seq_printf(m, "signal: %d/%p\n", timer->sigq->info.si_signo,
timer->sigq->info.si_value.sival_ptr);
seq_printf(m, "notify: %s/%s.%d\n",
nstr[notify & ~SIGEV_THREAD_ID],
(notify & SIGEV_THREAD_ID) ? "tid" : "pid",
pid_nr_ns(timer->it_pid, tp->ns));
seq_printf(m, "ClockID: %d\n", timer->it_clock);
return 0;
}
static const struct seq_operations proc_timers_seq_ops = {
.start = timers_start,
.next = timers_next,
.stop = timers_stop,
.show = show_timer,
};
static int proc_timers_open(struct inode *inode, struct file *file)
{
struct timers_private *tp;
tp = __seq_open_private(file, &proc_timers_seq_ops,
sizeof(struct timers_private));
if (!tp)
return -ENOMEM;
tp->pid = proc_pid(inode);
tp->ns = inode->i_sb->s_fs_info;
return 0;
}
static const struct file_operations proc_timers_operations = {
.open = proc_timers_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release_private,
};
#endif /* CONFIG_CHECKPOINT_RESTORE */
static struct dentry *proc_pident_instantiate(struct inode *dir,
struct dentry *dentry, struct task_struct *task, const void *ptr)
{
const struct pid_entry *p = ptr;
struct inode *inode;
struct proc_inode *ei;
struct dentry *error = ERR_PTR(-ENOENT);
inode = proc_pid_make_inode(dir->i_sb, task);
if (!inode)
goto out;
ei = PROC_I(inode);
inode->i_mode = p->mode;
if (S_ISDIR(inode->i_mode))
set_nlink(inode, 2); /* Use getattr to fix if necessary */
if (p->iop)
inode->i_op = p->iop;
if (p->fop)
inode->i_fop = p->fop;
ei->op = p->op;
d_set_d_op(dentry, &pid_dentry_operations);
d_add(dentry, inode);
/* Close the race of the process dying before we return the dentry */
if (pid_revalidate(dentry, 0))
error = NULL;
out:
return error;
}
static struct dentry *proc_pident_lookup(struct inode *dir,
struct dentry *dentry,
const struct pid_entry *ents,
unsigned int nents)
{
struct dentry *error;
struct task_struct *task = get_proc_task(dir);
const struct pid_entry *p, *last;
error = ERR_PTR(-ENOENT);
if (!task)
goto out_no_task;
/*
* Yes, it does not scale. And it should not. Don't add
* new entries into /proc/<tgid>/ without very good reasons.
*/
last = &ents[nents - 1];
for (p = ents; p <= last; p++) {
if (p->len != dentry->d_name.len)
continue;
if (!memcmp(dentry->d_name.name, p->name, p->len))
break;
}
if (p > last)
goto out;
error = proc_pident_instantiate(dir, dentry, task, p);
out:
put_task_struct(task);
out_no_task:
return error;
}
static int proc_pident_fill_cache(struct file *filp, void *dirent,
filldir_t filldir, struct task_struct *task, const struct pid_entry *p)
{
return proc_fill_cache(filp, dirent, filldir, p->name, p->len,
proc_pident_instantiate, task, p);
}
static int proc_pident_readdir(struct file *filp,
void *dirent, filldir_t filldir,
const struct pid_entry *ents, unsigned int nents)
{
int i;
struct dentry *dentry = filp->f_path.dentry;
struct inode *inode = dentry->d_inode;
struct task_struct *task = get_proc_task(inode);
const struct pid_entry *p, *last;
ino_t ino;
int ret;
ret = -ENOENT;
if (!task)
goto out_no_task;
ret = 0;
i = filp->f_pos;
switch (i) {
case 0:
ino = inode->i_ino;
if (filldir(dirent, ".", 1, i, ino, DT_DIR) < 0)
goto out;
i++;
filp->f_pos++;
/* fall through */
case 1:
ino = parent_ino(dentry);
if (filldir(dirent, "..", 2, i, ino, DT_DIR) < 0)
goto out;
i++;
filp->f_pos++;
/* fall through */
default:
i -= 2;
if (i >= nents) {
ret = 1;
goto out;
}
p = ents + i;
last = &ents[nents - 1];
while (p <= last) {
if (proc_pident_fill_cache(filp, dirent, filldir, task, p) < 0)
goto out;
filp->f_pos++;
p++;
}
}
ret = 1;
out:
put_task_struct(task);
out_no_task:
return ret;
}
#ifdef CONFIG_SECURITY
static ssize_t proc_pid_attr_read(struct file * file, char __user * buf,
size_t count, loff_t *ppos)
{
struct inode * inode = file_inode(file);
char *p = NULL;
ssize_t length;
struct task_struct *task = get_proc_task(inode);
if (!task)
return -ESRCH;
length = security_getprocattr(task,
(char*)file->f_path.dentry->d_name.name,
&p);
put_task_struct(task);
if (length > 0)
length = simple_read_from_buffer(buf, count, ppos, p, length);
kfree(p);
return length;
}
static ssize_t proc_pid_attr_write(struct file * file, const char __user * buf,
size_t count, loff_t *ppos)
{
struct inode * inode = file_inode(file);
char *page;
ssize_t length;
struct task_struct *task = get_proc_task(inode);
length = -ESRCH;
if (!task)
goto out_no_task;
if (count > PAGE_SIZE)
count = PAGE_SIZE;
/* No partial writes. */
length = -EINVAL;
if (*ppos != 0)
goto out;
length = -ENOMEM;
page = (char*)__get_free_page(GFP_TEMPORARY);
if (!page)
goto out;
length = -EFAULT;
if (copy_from_user(page, buf, count))
goto out_free;
/* Guard against adverse ptrace interaction */
length = mutex_lock_interruptible(&task->signal->cred_guard_mutex);
if (length < 0)
goto out_free;
length = security_setprocattr(task,
(char*)file->f_path.dentry->d_name.name,
(void*)page, count);
mutex_unlock(&task->signal->cred_guard_mutex);
out_free:
free_page((unsigned long) page);
out:
put_task_struct(task);
out_no_task:
return length;
}
static const struct file_operations proc_pid_attr_operations = {
.read = proc_pid_attr_read,
.write = proc_pid_attr_write,
.llseek = generic_file_llseek,
};
static const struct pid_entry attr_dir_stuff[] = {
REG("current", S_IRUGO|S_IWUGO, proc_pid_attr_operations),
REG("prev", S_IRUGO, proc_pid_attr_operations),
REG("exec", S_IRUGO|S_IWUGO, proc_pid_attr_operations),
REG("fscreate", S_IRUGO|S_IWUGO, proc_pid_attr_operations),
REG("keycreate", S_IRUGO|S_IWUGO, proc_pid_attr_operations),
REG("sockcreate", S_IRUGO|S_IWUGO, proc_pid_attr_operations),
};
static int proc_attr_dir_readdir(struct file * filp,
void * dirent, filldir_t filldir)
{
return proc_pident_readdir(filp,dirent,filldir,
attr_dir_stuff,ARRAY_SIZE(attr_dir_stuff));
}
static const struct file_operations proc_attr_dir_operations = {
.read = generic_read_dir,
.readdir = proc_attr_dir_readdir,
.llseek = default_llseek,
};
static struct dentry *proc_attr_dir_lookup(struct inode *dir,
struct dentry *dentry, unsigned int flags)
{
return proc_pident_lookup(dir, dentry,
attr_dir_stuff, ARRAY_SIZE(attr_dir_stuff));
}
static const struct inode_operations proc_attr_dir_inode_operations = {
.lookup = proc_attr_dir_lookup,
.getattr = pid_getattr,
.setattr = proc_setattr,
};
#endif
#ifdef CONFIG_ELF_CORE
static ssize_t proc_coredump_filter_read(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
struct task_struct *task = get_proc_task(file_inode(file));
struct mm_struct *mm;
char buffer[PROC_NUMBUF];
size_t len;
int ret;
if (!task)
return -ESRCH;
ret = 0;
mm = get_task_mm(task);
if (mm) {
len = snprintf(buffer, sizeof(buffer), "%08lx\n",
((mm->flags & MMF_DUMP_FILTER_MASK) >>
MMF_DUMP_FILTER_SHIFT));
mmput(mm);
ret = simple_read_from_buffer(buf, count, ppos, buffer, len);
}
put_task_struct(task);
return ret;
}
static ssize_t proc_coredump_filter_write(struct file *file,
const char __user *buf,
size_t count,
loff_t *ppos)
{
struct task_struct *task;
struct mm_struct *mm;
char buffer[PROC_NUMBUF], *end;
unsigned int val;
int ret;
int i;
unsigned long mask;
ret = -EFAULT;
memset(buffer, 0, sizeof(buffer));
if (count > sizeof(buffer) - 1)
count = sizeof(buffer) - 1;
if (copy_from_user(buffer, buf, count))
goto out_no_task;
ret = -EINVAL;
val = (unsigned int)simple_strtoul(buffer, &end, 0);
if (*end == '\n')
end++;
if (end - buffer == 0)
goto out_no_task;
ret = -ESRCH;
task = get_proc_task(file_inode(file));
if (!task)
goto out_no_task;
ret = end - buffer;
mm = get_task_mm(task);
if (!mm)
goto out_no_mm;
for (i = 0, mask = 1; i < MMF_DUMP_FILTER_BITS; i++, mask <<= 1) {
if (val & mask)
set_bit(i + MMF_DUMP_FILTER_SHIFT, &mm->flags);
else
clear_bit(i + MMF_DUMP_FILTER_SHIFT, &mm->flags);
}
mmput(mm);
out_no_mm:
put_task_struct(task);
out_no_task:
return ret;
}
static const struct file_operations proc_coredump_filter_operations = {
.read = proc_coredump_filter_read,
.write = proc_coredump_filter_write,
.llseek = generic_file_llseek,
};
#endif
#ifdef CONFIG_TASK_IO_ACCOUNTING
static int do_io_accounting(struct task_struct *task, char *buffer, int whole)
{
struct task_io_accounting acct = task->ioac;
unsigned long flags;
int result;
result = mutex_lock_killable(&task->signal->cred_guard_mutex);
if (result)
return result;
if (!ptrace_may_access(task, PTRACE_MODE_READ)) {
result = -EACCES;
goto out_unlock;
}
if (whole && lock_task_sighand(task, &flags)) {
struct task_struct *t = task;
task_io_accounting_add(&acct, &task->signal->ioac);
while_each_thread(task, t)
task_io_accounting_add(&acct, &t->ioac);
unlock_task_sighand(task, &flags);
}
result = sprintf(buffer,
"rchar: %llu\n"
"wchar: %llu\n"
"syscr: %llu\n"
"syscw: %llu\n"
"read_bytes: %llu\n"
"write_bytes: %llu\n"
"cancelled_write_bytes: %llu\n",
(unsigned long long)acct.rchar,
(unsigned long long)acct.wchar,
(unsigned long long)acct.syscr,
(unsigned long long)acct.syscw,
(unsigned long long)acct.read_bytes,
(unsigned long long)acct.write_bytes,
(unsigned long long)acct.cancelled_write_bytes);
out_unlock:
mutex_unlock(&task->signal->cred_guard_mutex);
return result;
}
static int proc_tid_io_accounting(struct task_struct *task, char *buffer)
{
return do_io_accounting(task, buffer, 0);
}
static int proc_tgid_io_accounting(struct task_struct *task, char *buffer)
{
return do_io_accounting(task, buffer, 1);
}
#endif /* CONFIG_TASK_IO_ACCOUNTING */
#ifdef CONFIG_USER_NS
static int proc_id_map_open(struct inode *inode, struct file *file,
struct seq_operations *seq_ops)
{
struct user_namespace *ns = NULL;
struct task_struct *task;
struct seq_file *seq;
int ret = -EINVAL;
task = get_proc_task(inode);
if (task) {
rcu_read_lock();
ns = get_user_ns(task_cred_xxx(task, user_ns));
rcu_read_unlock();
put_task_struct(task);
}
if (!ns)
goto err;
ret = seq_open(file, seq_ops);
if (ret)
goto err_put_ns;
seq = file->private_data;
seq->private = ns;
return 0;
err_put_ns:
put_user_ns(ns);
err:
return ret;
}
static int proc_id_map_release(struct inode *inode, struct file *file)
{
struct seq_file *seq = file->private_data;
struct user_namespace *ns = seq->private;
put_user_ns(ns);
return seq_release(inode, file);
}
static int proc_uid_map_open(struct inode *inode, struct file *file)
{
return proc_id_map_open(inode, file, &proc_uid_seq_operations);
}
static int proc_gid_map_open(struct inode *inode, struct file *file)
{
return proc_id_map_open(inode, file, &proc_gid_seq_operations);
}
static int proc_projid_map_open(struct inode *inode, struct file *file)
{
return proc_id_map_open(inode, file, &proc_projid_seq_operations);
}
static const struct file_operations proc_uid_map_operations = {
.open = proc_uid_map_open,
.write = proc_uid_map_write,
.read = seq_read,
.llseek = seq_lseek,
.release = proc_id_map_release,
};
static const struct file_operations proc_gid_map_operations = {
.open = proc_gid_map_open,
.write = proc_gid_map_write,
.read = seq_read,
.llseek = seq_lseek,
.release = proc_id_map_release,
};
static const struct file_operations proc_projid_map_operations = {
.open = proc_projid_map_open,
.write = proc_projid_map_write,
.read = seq_read,
.llseek = seq_lseek,
.release = proc_id_map_release,
};
#endif /* CONFIG_USER_NS */
static int proc_pid_personality(struct seq_file *m, struct pid_namespace *ns,
struct pid *pid, struct task_struct *task)
{
int err = lock_trace(task);
if (!err) {
seq_printf(m, "%08x\n", task->personality);
unlock_trace(task);
}
return err;
}
/*
* Thread groups
*/
static const struct file_operations proc_task_operations;
static const struct inode_operations proc_task_inode_operations;
static const struct pid_entry tgid_base_stuff[] = {
DIR("task", S_IRUGO|S_IXUGO, proc_task_inode_operations, proc_task_operations),
DIR("fd", S_IRUSR|S_IXUSR, proc_fd_inode_operations, proc_fd_operations),
#ifdef CONFIG_CHECKPOINT_RESTORE
DIR("map_files", S_IRUSR|S_IXUSR, proc_map_files_inode_operations, proc_map_files_operations),
#endif
DIR("fdinfo", S_IRUSR|S_IXUSR, proc_fdinfo_inode_operations, proc_fdinfo_operations),
DIR("ns", S_IRUSR|S_IXUGO, proc_ns_dir_inode_operations, proc_ns_dir_operations),
#ifdef CONFIG_NET
DIR("net", S_IRUGO|S_IXUGO, proc_net_inode_operations, proc_net_operations),
#endif
REG("environ", S_IRUSR, proc_environ_operations),
INF("auxv", S_IRUSR, proc_pid_auxv),
ONE("status", S_IRUGO, proc_pid_status),
ONE("personality", S_IRUGO, proc_pid_personality),
INF("limits", S_IRUGO, proc_pid_limits),
#ifdef CONFIG_SCHED_DEBUG
REG("sched", S_IRUGO|S_IWUSR, proc_pid_sched_operations),
#endif
#ifdef CONFIG_SCHED_AUTOGROUP
REG("autogroup", S_IRUGO|S_IWUSR, proc_pid_sched_autogroup_operations),
#endif
REG("comm", S_IRUGO|S_IWUSR, proc_pid_set_comm_operations),
#ifdef CONFIG_HAVE_ARCH_TRACEHOOK
INF("syscall", S_IRUGO, proc_pid_syscall),
#endif
INF("cmdline", S_IRUGO, proc_pid_cmdline),
ONE("stat", S_IRUGO, proc_tgid_stat),
ONE("statm", S_IRUGO, proc_pid_statm),
REG("maps", S_IRUGO, proc_pid_maps_operations),
#ifdef CONFIG_NUMA
REG("numa_maps", S_IRUGO, proc_pid_numa_maps_operations),
#endif
REG("mem", S_IRUSR|S_IWUSR, proc_mem_operations),
LNK("cwd", proc_cwd_link),
LNK("root", proc_root_link),
LNK("exe", proc_exe_link),
REG("mounts", S_IRUGO, proc_mounts_operations),
REG("mountinfo", S_IRUGO, proc_mountinfo_operations),
REG("mountstats", S_IRUSR, proc_mountstats_operations),
#ifdef CONFIG_PROC_PAGE_MONITOR
REG("clear_refs", S_IWUSR, proc_clear_refs_operations),
REG("smaps", S_IRUGO, proc_pid_smaps_operations),
REG("pagemap", S_IRUGO, proc_pagemap_operations),
#endif
#ifdef CONFIG_SECURITY
DIR("attr", S_IRUGO|S_IXUGO, proc_attr_dir_inode_operations, proc_attr_dir_operations),
#endif
#ifdef CONFIG_KALLSYMS
INF("wchan", S_IRUGO, proc_pid_wchan),
#endif
#ifdef CONFIG_STACKTRACE
ONE("stack", S_IRUGO, proc_pid_stack),
#endif
#ifdef CONFIG_SCHEDSTATS
INF("schedstat", S_IRUGO, proc_pid_schedstat),
#endif
#ifdef CONFIG_LATENCYTOP
REG("latency", S_IRUGO, proc_lstats_operations),
#endif
#ifdef CONFIG_PROC_PID_CPUSET
REG("cpuset", S_IRUGO, proc_cpuset_operations),
#endif
#ifdef CONFIG_CGROUPS
REG("cgroup", S_IRUGO, proc_cgroup_operations),
#endif
INF("oom_score", S_IRUGO, proc_oom_score),
ANDROID("oom_adj", S_IRUGO|S_IWUSR, oom_adj),
REG("oom_score_adj", S_IRUGO|S_IWUSR, proc_oom_score_adj_operations),
#ifdef CONFIG_AUDITSYSCALL
REG("loginuid", S_IWUSR|S_IRUGO, proc_loginuid_operations),
REG("sessionid", S_IRUGO, proc_sessionid_operations),
#endif
#ifdef CONFIG_FAULT_INJECTION
REG("make-it-fail", S_IRUGO|S_IWUSR, proc_fault_inject_operations),
#endif
#ifdef CONFIG_ELF_CORE
REG("coredump_filter", S_IRUGO|S_IWUSR, proc_coredump_filter_operations),
#endif
#ifdef CONFIG_TASK_IO_ACCOUNTING
INF("io", S_IRUSR, proc_tgid_io_accounting),
#endif
#ifdef CONFIG_HARDWALL
INF("hardwall", S_IRUGO, proc_pid_hardwall),
#endif
#ifdef CONFIG_USER_NS
REG("uid_map", S_IRUGO|S_IWUSR, proc_uid_map_operations),
REG("gid_map", S_IRUGO|S_IWUSR, proc_gid_map_operations),
REG("projid_map", S_IRUGO|S_IWUSR, proc_projid_map_operations),
#endif
#ifdef CONFIG_CHECKPOINT_RESTORE
REG("timers", S_IRUGO, proc_timers_operations),
#endif
};
static int proc_tgid_base_readdir(struct file * filp,
void * dirent, filldir_t filldir)
{
return proc_pident_readdir(filp,dirent,filldir,
tgid_base_stuff,ARRAY_SIZE(tgid_base_stuff));
}
static const struct file_operations proc_tgid_base_operations = {
.read = generic_read_dir,
.readdir = proc_tgid_base_readdir,
.llseek = default_llseek,
};
static struct dentry *proc_tgid_base_lookup(struct inode *dir, struct dentry *dentry, unsigned int flags)
{
return proc_pident_lookup(dir, dentry,
tgid_base_stuff, ARRAY_SIZE(tgid_base_stuff));
}
static const struct inode_operations proc_tgid_base_inode_operations = {
.lookup = proc_tgid_base_lookup,
.getattr = pid_getattr,
.setattr = proc_setattr,
.permission = proc_pid_permission,
};
static void proc_flush_task_mnt(struct vfsmount *mnt, pid_t pid, pid_t tgid)
{
struct dentry *dentry, *leader, *dir;
char buf[PROC_NUMBUF];
struct qstr name;
name.name = buf;
name.len = snprintf(buf, sizeof(buf), "%d", pid);
/* no ->d_hash() rejects on procfs */
dentry = d_hash_and_lookup(mnt->mnt_root, &name);
if (dentry) {
shrink_dcache_parent(dentry);
d_drop(dentry);
dput(dentry);
}
name.name = buf;
name.len = snprintf(buf, sizeof(buf), "%d", tgid);
leader = d_hash_and_lookup(mnt->mnt_root, &name);
if (!leader)
goto out;
name.name = "task";
name.len = strlen(name.name);
dir = d_hash_and_lookup(leader, &name);
if (!dir)
goto out_put_leader;
name.name = buf;
name.len = snprintf(buf, sizeof(buf), "%d", pid);
dentry = d_hash_and_lookup(dir, &name);
if (dentry) {
shrink_dcache_parent(dentry);
d_drop(dentry);
dput(dentry);
}
dput(dir);
out_put_leader:
dput(leader);
out:
return;
}
/**
* proc_flush_task - Remove dcache entries for @task from the /proc dcache.
* @task: task that should be flushed.
*
* When flushing dentries from proc, one needs to flush them from global
* proc (proc_mnt) and from all the namespaces' procs this task was seen
* in. This call is supposed to do all of this job.
*
* Looks in the dcache for
* /proc/@pid
* /proc/@tgid/task/@pid
* if either directory is present flushes it and all of it'ts children
* from the dcache.
*
* It is safe and reasonable to cache /proc entries for a task until
* that task exits. After that they just clog up the dcache with
* useless entries, possibly causing useful dcache entries to be
* flushed instead. This routine is proved to flush those useless
* dcache entries at process exit time.
*
* NOTE: This routine is just an optimization so it does not guarantee
* that no dcache entries will exist at process exit time it
* just makes it very unlikely that any will persist.
*/
void proc_flush_task(struct task_struct *task)
{
int i;
struct pid *pid, *tgid;
struct upid *upid;
pid = task_pid(task);
tgid = task_tgid(task);
for (i = 0; i <= pid->level; i++) {
upid = &pid->numbers[i];
proc_flush_task_mnt(upid->ns->proc_mnt, upid->nr,
tgid->numbers[i].nr);
}
}
static struct dentry *proc_pid_instantiate(struct inode *dir,
struct dentry * dentry,
struct task_struct *task, const void *ptr)
{
struct dentry *error = ERR_PTR(-ENOENT);
struct inode *inode;
inode = proc_pid_make_inode(dir->i_sb, task);
if (!inode)
goto out;
inode->i_mode = S_IFDIR|S_IRUGO|S_IXUGO;
inode->i_op = &proc_tgid_base_inode_operations;
inode->i_fop = &proc_tgid_base_operations;
inode->i_flags|=S_IMMUTABLE;
set_nlink(inode, 2 + pid_entry_count_dirs(tgid_base_stuff,
ARRAY_SIZE(tgid_base_stuff)));
d_set_d_op(dentry, &pid_dentry_operations);
d_add(dentry, inode);
/* Close the race of the process dying before we return the dentry */
if (pid_revalidate(dentry, 0))
error = NULL;
out:
return error;
}
struct dentry *proc_pid_lookup(struct inode *dir, struct dentry * dentry, unsigned int flags)
{
struct dentry *result = NULL;
struct task_struct *task;
unsigned tgid;
struct pid_namespace *ns;
tgid = name_to_int(dentry);
if (tgid == ~0U)
goto out;
ns = dentry->d_sb->s_fs_info;
rcu_read_lock();
task = find_task_by_pid_ns(tgid, ns);
if (task)
get_task_struct(task);
rcu_read_unlock();
if (!task)
goto out;
result = proc_pid_instantiate(dir, dentry, task, NULL);
put_task_struct(task);
out:
return result;
}
/*
* Find the first task with tgid >= tgid
*
*/
struct tgid_iter {
unsigned int tgid;
struct task_struct *task;
};
static struct tgid_iter next_tgid(struct pid_namespace *ns, struct tgid_iter iter)
{
struct pid *pid;
if (iter.task)
put_task_struct(iter.task);
rcu_read_lock();
retry:
iter.task = NULL;
pid = find_ge_pid(iter.tgid, ns);
if (pid) {
iter.tgid = pid_nr_ns(pid, ns);
iter.task = pid_task(pid, PIDTYPE_PID);
/* What we to know is if the pid we have find is the
* pid of a thread_group_leader. Testing for task
* being a thread_group_leader is the obvious thing
* todo but there is a window when it fails, due to
* the pid transfer logic in de_thread.
*
* So we perform the straight forward test of seeing
* if the pid we have found is the pid of a thread
* group leader, and don't worry if the task we have
* found doesn't happen to be a thread group leader.
* As we don't care in the case of readdir.
*/
if (!iter.task || !has_group_leader_pid(iter.task)) {
iter.tgid += 1;
goto retry;
}
get_task_struct(iter.task);
}
rcu_read_unlock();
return iter;
}
#define TGID_OFFSET (FIRST_PROCESS_ENTRY + 1)
static int proc_pid_fill_cache(struct file *filp, void *dirent, filldir_t filldir,
struct tgid_iter iter)
{
char name[PROC_NUMBUF];
int len = snprintf(name, sizeof(name), "%d", iter.tgid);
return proc_fill_cache(filp, dirent, filldir, name, len,
proc_pid_instantiate, iter.task, NULL);
}
static int fake_filldir(void *buf, const char *name, int namelen,
loff_t offset, u64 ino, unsigned d_type)
{
return 0;
}
/* for the /proc/ directory itself, after non-process stuff has been done */
int proc_pid_readdir(struct file * filp, void * dirent, filldir_t filldir)
{
struct tgid_iter iter;
struct pid_namespace *ns;
filldir_t __filldir;
loff_t pos = filp->f_pos;
if (pos >= PID_MAX_LIMIT + TGID_OFFSET)
goto out;
if (pos == TGID_OFFSET - 1) {
if (proc_fill_cache(filp, dirent, filldir, "self", 4,
NULL, NULL, NULL) < 0)
goto out;
iter.tgid = 0;
} else {
iter.tgid = pos - TGID_OFFSET;
}
iter.task = NULL;
ns = filp->f_dentry->d_sb->s_fs_info;
for (iter = next_tgid(ns, iter);
iter.task;
iter.tgid += 1, iter = next_tgid(ns, iter)) {
if (has_pid_permissions(ns, iter.task, 2))
__filldir = filldir;
else
__filldir = fake_filldir;
filp->f_pos = iter.tgid + TGID_OFFSET;
if (proc_pid_fill_cache(filp, dirent, __filldir, iter) < 0) {
put_task_struct(iter.task);
goto out;
}
}
filp->f_pos = PID_MAX_LIMIT + TGID_OFFSET;
out:
return 0;
}
/*
* Tasks
*/
static const struct pid_entry tid_base_stuff[] = {
DIR("fd", S_IRUSR|S_IXUSR, proc_fd_inode_operations, proc_fd_operations),
DIR("fdinfo", S_IRUSR|S_IXUSR, proc_fdinfo_inode_operations, proc_fdinfo_operations),
DIR("ns", S_IRUSR|S_IXUGO, proc_ns_dir_inode_operations, proc_ns_dir_operations),
REG("environ", S_IRUSR, proc_environ_operations),
INF("auxv", S_IRUSR, proc_pid_auxv),
ONE("status", S_IRUGO, proc_pid_status),
ONE("personality", S_IRUGO, proc_pid_personality),
INF("limits", S_IRUGO, proc_pid_limits),
#ifdef CONFIG_SCHED_DEBUG
REG("sched", S_IRUGO|S_IWUSR, proc_pid_sched_operations),
#endif
REG("comm", S_IRUGO|S_IWUSR, proc_pid_set_comm_operations),
#ifdef CONFIG_HAVE_ARCH_TRACEHOOK
INF("syscall", S_IRUGO, proc_pid_syscall),
#endif
INF("cmdline", S_IRUGO, proc_pid_cmdline),
ONE("stat", S_IRUGO, proc_tid_stat),
ONE("statm", S_IRUGO, proc_pid_statm),
REG("maps", S_IRUGO, proc_tid_maps_operations),
#ifdef CONFIG_CHECKPOINT_RESTORE
REG("children", S_IRUGO, proc_tid_children_operations),
#endif
#ifdef CONFIG_NUMA
REG("numa_maps", S_IRUGO, proc_tid_numa_maps_operations),
#endif
REG("mem", S_IRUSR|S_IWUSR, proc_mem_operations),
LNK("cwd", proc_cwd_link),
LNK("root", proc_root_link),
LNK("exe", proc_exe_link),
REG("mounts", S_IRUGO, proc_mounts_operations),
REG("mountinfo", S_IRUGO, proc_mountinfo_operations),
#ifdef CONFIG_PROC_PAGE_MONITOR
REG("clear_refs", S_IWUSR, proc_clear_refs_operations),
REG("smaps", S_IRUGO, proc_tid_smaps_operations),
REG("pagemap", S_IRUGO, proc_pagemap_operations),
#endif
#ifdef CONFIG_SECURITY
DIR("attr", S_IRUGO|S_IXUGO, proc_attr_dir_inode_operations, proc_attr_dir_operations),
#endif
#ifdef CONFIG_KALLSYMS
INF("wchan", S_IRUGO, proc_pid_wchan),
#endif
#ifdef CONFIG_STACKTRACE
ONE("stack", S_IRUGO, proc_pid_stack),
#endif
#ifdef CONFIG_SCHEDSTATS
INF("schedstat", S_IRUGO, proc_pid_schedstat),
#endif
#ifdef CONFIG_LATENCYTOP
REG("latency", S_IRUGO, proc_lstats_operations),
#endif
#ifdef CONFIG_PROC_PID_CPUSET
REG("cpuset", S_IRUGO, proc_cpuset_operations),
#endif
#ifdef CONFIG_CGROUPS
REG("cgroup", S_IRUGO, proc_cgroup_operations),
#endif
INF("oom_score", S_IRUGO, proc_oom_score),
REG("oom_adj", S_IRUGO|S_IWUSR, proc_oom_adj_operations),
REG("oom_score_adj", S_IRUGO|S_IWUSR, proc_oom_score_adj_operations),
#ifdef CONFIG_AUDITSYSCALL
REG("loginuid", S_IWUSR|S_IRUGO, proc_loginuid_operations),
REG("sessionid", S_IRUGO, proc_sessionid_operations),
#endif
#ifdef CONFIG_FAULT_INJECTION
REG("make-it-fail", S_IRUGO|S_IWUSR, proc_fault_inject_operations),
#endif
#ifdef CONFIG_TASK_IO_ACCOUNTING
INF("io", S_IRUSR, proc_tid_io_accounting),
#endif
#ifdef CONFIG_HARDWALL
INF("hardwall", S_IRUGO, proc_pid_hardwall),
#endif
#ifdef CONFIG_USER_NS
REG("uid_map", S_IRUGO|S_IWUSR, proc_uid_map_operations),
REG("gid_map", S_IRUGO|S_IWUSR, proc_gid_map_operations),
REG("projid_map", S_IRUGO|S_IWUSR, proc_projid_map_operations),
#endif
};
static int proc_tid_base_readdir(struct file * filp,
void * dirent, filldir_t filldir)
{
return proc_pident_readdir(filp,dirent,filldir,
tid_base_stuff,ARRAY_SIZE(tid_base_stuff));
}
static struct dentry *proc_tid_base_lookup(struct inode *dir, struct dentry *dentry, unsigned int flags)
{
return proc_pident_lookup(dir, dentry,
tid_base_stuff, ARRAY_SIZE(tid_base_stuff));
}
static const struct file_operations proc_tid_base_operations = {
.read = generic_read_dir,
.readdir = proc_tid_base_readdir,
.llseek = default_llseek,
};
static const struct inode_operations proc_tid_base_inode_operations = {
.lookup = proc_tid_base_lookup,
.getattr = pid_getattr,
.setattr = proc_setattr,
};
static struct dentry *proc_task_instantiate(struct inode *dir,
struct dentry *dentry, struct task_struct *task, const void *ptr)
{
struct dentry *error = ERR_PTR(-ENOENT);
struct inode *inode;
inode = proc_pid_make_inode(dir->i_sb, task);
if (!inode)
goto out;
inode->i_mode = S_IFDIR|S_IRUGO|S_IXUGO;
inode->i_op = &proc_tid_base_inode_operations;
inode->i_fop = &proc_tid_base_operations;
inode->i_flags|=S_IMMUTABLE;
set_nlink(inode, 2 + pid_entry_count_dirs(tid_base_stuff,
ARRAY_SIZE(tid_base_stuff)));
d_set_d_op(dentry, &pid_dentry_operations);
d_add(dentry, inode);
/* Close the race of the process dying before we return the dentry */
if (pid_revalidate(dentry, 0))
error = NULL;
out:
return error;
}
static struct dentry *proc_task_lookup(struct inode *dir, struct dentry * dentry, unsigned int flags)
{
struct dentry *result = ERR_PTR(-ENOENT);
struct task_struct *task;
struct task_struct *leader = get_proc_task(dir);
unsigned tid;
struct pid_namespace *ns;
if (!leader)
goto out_no_task;
tid = name_to_int(dentry);
if (tid == ~0U)
goto out;
ns = dentry->d_sb->s_fs_info;
rcu_read_lock();
task = find_task_by_pid_ns(tid, ns);
if (task)
get_task_struct(task);
rcu_read_unlock();
if (!task)
goto out;
if (!same_thread_group(leader, task))
goto out_drop_task;
result = proc_task_instantiate(dir, dentry, task, NULL);
out_drop_task:
put_task_struct(task);
out:
put_task_struct(leader);
out_no_task:
return result;
}
/*
* Find the first tid of a thread group to return to user space.
*
* Usually this is just the thread group leader, but if the users
* buffer was too small or there was a seek into the middle of the
* directory we have more work todo.
*
* In the case of a short read we start with find_task_by_pid.
*
* In the case of a seek we start with the leader and walk nr
* threads past it.
*/
static struct task_struct *first_tid(struct task_struct *leader,
int tid, int nr, struct pid_namespace *ns)
{
struct task_struct *pos;
rcu_read_lock();
/* Attempt to start with the pid of a thread */
if (tid && (nr > 0)) {
pos = find_task_by_pid_ns(tid, ns);
if (pos && (pos->group_leader == leader))
goto found;
}
/* If nr exceeds the number of threads there is nothing todo */
pos = NULL;
if (nr && nr >= get_nr_threads(leader))
goto out;
/* If we haven't found our starting place yet start
* with the leader and walk nr threads forward.
*/
for (pos = leader; nr > 0; --nr) {
pos = next_thread(pos);
if (pos == leader) {
pos = NULL;
goto out;
}
}
found:
get_task_struct(pos);
out:
rcu_read_unlock();
return pos;
}
/*
* Find the next thread in the thread list.
* Return NULL if there is an error or no next thread.
*
* The reference to the input task_struct is released.
*/
static struct task_struct *next_tid(struct task_struct *start)
{
struct task_struct *pos = NULL;
rcu_read_lock();
if (pid_alive(start)) {
pos = next_thread(start);
if (thread_group_leader(pos))
pos = NULL;
else
get_task_struct(pos);
}
rcu_read_unlock();
put_task_struct(start);
return pos;
}
static int proc_task_fill_cache(struct file *filp, void *dirent, filldir_t filldir,
struct task_struct *task, int tid)
{
char name[PROC_NUMBUF];
int len = snprintf(name, sizeof(name), "%d", tid);
return proc_fill_cache(filp, dirent, filldir, name, len,
proc_task_instantiate, task, NULL);
}
/* for the /proc/TGID/task/ directories */
static int proc_task_readdir(struct file * filp, void * dirent, filldir_t filldir)
{
struct dentry *dentry = filp->f_path.dentry;
struct inode *inode = dentry->d_inode;
struct task_struct *leader = NULL;
struct task_struct *task;
int retval = -ENOENT;
ino_t ino;
int tid;
struct pid_namespace *ns;
task = get_proc_task(inode);
if (!task)
goto out_no_task;
rcu_read_lock();
if (pid_alive(task)) {
leader = task->group_leader;
get_task_struct(leader);
}
rcu_read_unlock();
put_task_struct(task);
if (!leader)
goto out_no_task;
retval = 0;
switch ((unsigned long)filp->f_pos) {
case 0:
ino = inode->i_ino;
if (filldir(dirent, ".", 1, filp->f_pos, ino, DT_DIR) < 0)
goto out;
filp->f_pos++;
/* fall through */
case 1:
ino = parent_ino(dentry);
if (filldir(dirent, "..", 2, filp->f_pos, ino, DT_DIR) < 0)
goto out;
filp->f_pos++;
/* fall through */
}
/* f_version caches the tgid value that the last readdir call couldn't
* return. lseek aka telldir automagically resets f_version to 0.
*/
ns = filp->f_dentry->d_sb->s_fs_info;
tid = (int)filp->f_version;
filp->f_version = 0;
for (task = first_tid(leader, tid, filp->f_pos - 2, ns);
task;
task = next_tid(task), filp->f_pos++) {
tid = task_pid_nr_ns(task, ns);
if (proc_task_fill_cache(filp, dirent, filldir, task, tid) < 0) {
/* returning this tgid failed, save it as the first
* pid for the next readir call */
filp->f_version = (u64)tid;
put_task_struct(task);
break;
}
}
out:
put_task_struct(leader);
out_no_task:
return retval;
}
static int proc_task_getattr(struct vfsmount *mnt, struct dentry *dentry, struct kstat *stat)
{
struct inode *inode = dentry->d_inode;
struct task_struct *p = get_proc_task(inode);
generic_fillattr(inode, stat);
if (p) {
stat->nlink += get_nr_threads(p);
put_task_struct(p);
}
return 0;
}
static const struct inode_operations proc_task_inode_operations = {
.lookup = proc_task_lookup,
.getattr = proc_task_getattr,
.setattr = proc_setattr,
.permission = proc_pid_permission,
};
static const struct file_operations proc_task_operations = {
.read = generic_read_dir,
.readdir = proc_task_readdir,
.llseek = default_llseek,
};
| ffolkes/android_kernel_samsung_trlte | fs/proc/base.c | C | gpl-2.0 | 83,300 |
/*
* Copyright (C) 2014 Ian G. Clifton
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.coding.android.widget;
import com.nineoldandroids.view.ViewHelper;
import com.nineoldandroids.view.ViewPropertyAnimator;
import net.coding.android.R;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TextView;
/**
* A ViewGroup that consists of an EditText and a TextView as the label.<br/>
* <br/>
* When the EditText is empty, its hint is displayed. When it is nonempty, the
* TextView label is displayed.<br/>
* <br/>
* You can set the label programmatically with either
* {@link #setLabel(CharSequence)} or {@link #setLabel(int)}.
*
* @author Ian G. Clifton
* @see <a
* href="http://dribbble.com/shots/1254439--GIF-Float-Label-Form-Interaction">Float
* label inspiration on Dribbble</a>
*/
public class FloatLabel extends FrameLayout {
private static final String SAVE_STATE_KEY_EDIT_TEXT = "saveStateEditText";
private static final String SAVE_STATE_KEY_LABEL = "saveStateLabel";
private static final String SAVE_STATE_PARENT = "saveStateParent";
private static final String SAVE_STATE_TAG = "saveStateTag";
/**
* Reference to the EditText
*/
private EditText mEditText;
/**
* When init is complete, child views can no longer be added
*/
private boolean mInitComplete = false;
/**
* Reference to the TextView used as the label
*/
private TextView mLabel;
/**
* LabelAnimator that animates the appearance and disappearance of the label
* TextView
*/
private LabelAnimator mLabelAnimator = new DefaultLabelAnimator();
/**
* True if the TextView label is showing (alpha 1f)
*/
private boolean mLabelShowing;
/**
* Holds saved state if any is waiting to be restored
*/
private Bundle mSavedState;
/**
* Interface for providing custom animations to the label TextView.
*/
public interface LabelAnimator {
/**
* Called when the label should become visible
*
* @param label
* TextView to animate to visible
*/
public void onDisplayLabel(View label);
/**
* Called when the label should become invisible
*
* @param label
* TextView to animate to invisible
*/
public void onHideLabel(View label);
}
public FloatLabel(Context context) {
this(context, null, 0);
}
public FloatLabel(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public FloatLabel(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context, attrs, defStyle);
}
@Override
public void addView(View child) {
if (mInitComplete) {
throw new UnsupportedOperationException(
"You cannot add child views to a FloatLabel");
} else {
super.addView(child);
}
}
@Override
public void addView(View child, int index) {
if (mInitComplete) {
throw new UnsupportedOperationException(
"You cannot add child views to a FloatLabel");
} else {
super.addView(child, index);
}
}
@Override
public void addView(View child, int index,
android.view.ViewGroup.LayoutParams params) {
if (mInitComplete) {
throw new UnsupportedOperationException(
"You cannot add child views to a FloatLabel");
} else {
super.addView(child, index, params);
}
}
@Override
public void addView(View child, int width, int height) {
if (mInitComplete) {
throw new UnsupportedOperationException(
"You cannot add child views to a FloatLabel");
} else {
super.addView(child, width, height);
}
}
@Override
public void addView(View child, android.view.ViewGroup.LayoutParams params) {
if (mInitComplete) {
throw new UnsupportedOperationException(
"You cannot add child views to a FloatLabel");
} else {
super.addView(child, params);
}
}
/**
* Returns the EditText portion of this View
*
* @return the EditText portion of this View
*/
public EditText getEditText() {
return mEditText;
}
/**
* Sets the text to be displayed above the EditText if the EditText is
* nonempty or as the EditText hint if it is empty
*
* @param resid
* int String resource ID
*/
public void setLabel(int resid) {
setLabel(getContext().getString(resid));
}
/**
* Sets the text to be displayed above the EditText if the EditText is
* nonempty or as the EditText hint if it is empty
*
* @param hint
* CharSequence to set as the label
*/
public void setLabel(CharSequence hint) {
mEditText.setHint(hint);
mLabel.setText(hint);
}
/**
* Specifies a new LabelAnimator to handle calls to show/hide the label
*
* @param labelAnimator
* LabelAnimator to use; null causes use of the default
* LabelAnimator
*/
public void setLabelAnimator(LabelAnimator labelAnimator) {
if (labelAnimator == null) {
mLabelAnimator = new DefaultLabelAnimator();
} else {
mLabelAnimator = labelAnimator;
}
}
@Override
protected void onLayout(boolean changed, int left, int top, int right,
int bottom) {
final int childLeft = getPaddingLeft();
final int childRight = right - left - getPaddingRight();
int childTop = getPaddingTop();
final int childBottom = bottom - top - getPaddingBottom();
layoutChild(mLabel, childLeft, childTop, childRight, childBottom);
layoutChild(mEditText, childLeft,
childTop + mLabel.getMeasuredHeight(), childRight, childBottom);
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
private void layoutChild(View child, int parentLeft, int parentTop,
int parentRight, int parentBottom) {
if (child.getVisibility() != GONE) {
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
final int width = child.getMeasuredWidth();
final int height = child.getMeasuredHeight();
int childLeft;
final int childTop = parentTop + lp.topMargin;
int gravity = lp.gravity;
if (gravity == -1) {
gravity = Gravity.TOP | Gravity.START;
}
final int layoutDirection;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
layoutDirection = LAYOUT_DIRECTION_LTR;
} else {
layoutDirection = getLayoutDirection();
}
final int absoluteGravity = Gravity.getAbsoluteGravity(gravity,
layoutDirection);
switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
case Gravity.CENTER_HORIZONTAL:
childLeft = parentLeft + (parentRight - parentLeft - width) / 2
+ lp.leftMargin - lp.rightMargin;
break;
case Gravity.RIGHT:
childLeft = parentRight - width - lp.rightMargin;
break;
case Gravity.LEFT:
default:
childLeft = parentLeft + lp.leftMargin;
}
child.layout(childLeft, childTop, childLeft + width, childTop
+ height);
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// Restore any state that's been pending before measuring
if (mSavedState != null) {
Parcelable childState = mSavedState
.getParcelable(SAVE_STATE_KEY_EDIT_TEXT);
mEditText.onRestoreInstanceState(childState);
childState = mSavedState.getParcelable(SAVE_STATE_KEY_LABEL);
mLabel.onRestoreInstanceState(childState);
mSavedState = null;
}
measureChild(mEditText, widthMeasureSpec, heightMeasureSpec);
measureChild(mLabel, widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(measureWidth(widthMeasureSpec),
measureHeight(heightMeasureSpec));
}
@Override
protected void onRestoreInstanceState(Parcelable state) {
if (state instanceof Bundle) {
final Bundle savedState = (Bundle) state;
if (savedState.getBoolean(SAVE_STATE_TAG, false)) {
// Save our state for later since children will have theirs
// restored after this
// and having more than one FloatLabel in an Activity or
// Fragment means you have
// multiple views of the same ID
mSavedState = savedState;
super.onRestoreInstanceState(savedState
.getParcelable(SAVE_STATE_PARENT));
return;
}
}
super.onRestoreInstanceState(state);
}
@Override
protected Parcelable onSaveInstanceState() {
final Parcelable superState = super.onSaveInstanceState();
final Bundle saveState = new Bundle();
saveState.putParcelable(SAVE_STATE_KEY_EDIT_TEXT,
mEditText.onSaveInstanceState());
saveState.putParcelable(SAVE_STATE_KEY_LABEL,
mLabel.onSaveInstanceState());
saveState.putBoolean(SAVE_STATE_TAG, true);
saveState.putParcelable(SAVE_STATE_PARENT, superState);
return saveState;
}
private int measureHeight(int heightMeasureSpec) {
int specMode = MeasureSpec.getMode(heightMeasureSpec);
int specSize = MeasureSpec.getSize(heightMeasureSpec);
int result = 0;
if (specMode == MeasureSpec.EXACTLY) {
result = specSize;
} else {
result = mEditText.getMeasuredHeight() + mLabel.getMeasuredHeight();
result += getPaddingTop() + getPaddingBottom();
result = Math.max(result, getSuggestedMinimumHeight());
if (specMode == MeasureSpec.AT_MOST) {
result = Math.min(result, specSize);
}
}
return result;
}
private int measureWidth(int widthMeasureSpec) {
int specMode = MeasureSpec.getMode(widthMeasureSpec);
int specSize = MeasureSpec.getSize(widthMeasureSpec);
int result = 0;
if (specMode == MeasureSpec.EXACTLY) {
result = specSize;
} else {
result = Math.max(mEditText.getMeasuredWidth(),
mLabel.getMeasuredWidth());
result = Math.max(result, getSuggestedMinimumWidth());
result += getPaddingLeft() + getPaddingRight();
if (specMode == MeasureSpec.AT_MOST) {
result = Math.min(result, specSize);
}
}
return result;
}
private void init(Context context, AttributeSet attrs, int defStyle) {
// Load custom attributes
final int layout;
final CharSequence text;
final CharSequence hint;
final ColorStateList hintColor;
final int floatLabelColor;
final int inputType;
if (attrs == null) {
layout = R.layout.widget_float_label;
text = null;
hint = null;
hintColor = null;
floatLabelColor = 0;
inputType = 0;
} else {
final TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.FloatLabel, defStyle, 0);
layout = a.getResourceId(R.styleable.FloatLabel_android_layout,
R.layout.widget_float_label);
text = a.getText(R.styleable.FloatLabel_android_text);
hint = a.getText(R.styleable.FloatLabel_android_hint);
hintColor = a
.getColorStateList(R.styleable.FloatLabel_android_textColorHint);
floatLabelColor = a.getColor(
R.styleable.FloatLabel_floatLabelColor, 0);
inputType = a.getInt(R.styleable.FloatLabel_android_inputType,
InputType.TYPE_CLASS_TEXT);
a.recycle();
}
inflate(context, layout, this);
mEditText = (EditText) findViewById(R.id.edit_text);
if (mEditText == null) {
throw new RuntimeException(
"Your layout must have an EditText whose ID is @id/edit_text");
}
mEditText.setHint(hint);
mEditText.setText(text);
if (hintColor != null) {
mEditText.setHintTextColor(hintColor);
}
if (inputType != 0) {
mEditText.setInputType(inputType);
}
mLabel = (TextView) findViewById(R.id.float_label);
if (mLabel == null) {
throw new RuntimeException(
"Your layout must have a TextView whose ID is @id/float_label");
}
mLabel.setText(mEditText.getHint());
if (floatLabelColor != 0)
mLabel.setTextColor(floatLabelColor);
// Listen to EditText to know when it is empty or nonempty
mEditText.addTextChangedListener(new EditTextWatcher());
// Check current state of EditText
if (mEditText.getText().length() == 0) {
// mLabel.setAlpha(0);
ViewHelper.setAlpha(mLabel, 0);
mLabelShowing = false;
} else {
mLabel.setVisibility(View.VISIBLE);
mLabelShowing = true;
}
// Mark init as complete to prevent accidentally breaking the view by
// adding children
mInitComplete = true;
}
/**
* LabelAnimator that uses the traditional float label Y shift and fade.
*
* @author Ian G. Clifton
*/
private static class DefaultLabelAnimator implements LabelAnimator {
@Override
public void onDisplayLabel(View label) {
final float offset = label.getHeight() / 2;
final float currentY = ViewHelper.getY(label);
if (currentY != offset) {
ViewHelper.setY(label, offset);
}
ViewPropertyAnimator.animate(label).alpha(1).y(1);
}
@Override
public void onHideLabel(View label) {
final float offset = label.getHeight() / 2;
final float currentY = ViewHelper.getY(label);
if (currentY != 0) {
ViewHelper.setY(label, 0);
}
ViewPropertyAnimator.animate(label).alpha(0).y(offset);
}
}
/**
* TextWatcher that notifies FloatLabel when the EditText changes between
* having text and not having text or vice versa.
*
* @author Ian G. Clifton
*/
private class EditTextWatcher implements TextWatcher {
@Override
public void afterTextChanged(Editable s) {
if (s.length() == 0) {
// Text is empty; TextView label should be invisible
if (mLabelShowing) {
mLabelAnimator.onHideLabel(mLabel);
mLabelShowing = false;
}
} else if (!mLabelShowing) {
// Text is nonempty; TextView label should be visible
mLabelShowing = true;
mLabelAnimator.onDisplayLabel(mLabel);
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// Ignored
}
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// Ignored
}
}
}
| AndroidREPo-jason/CodingClient | coding/src/net/coding/android/widget/FloatLabel.java | Java | gpl-2.0 | 14,374 |
#include <linux/platform_device.h>
#include <linux/gpio.h>
#include <asm/mach-types.h>
#include <asm/mach/arch.h>
#include <asm/mach/time.h>
#include <asm/mach/map.h>
#include <mach/hardware.h>
#include <mach/common.h>
#include <mach/imx-uart.h>
#include <mach/iomux.h>
#include <mach/board-mx27lite.h>
#include "devices.h"
static unsigned int mx27lite_pins[] = {
PE12_PF_UART1_TXD,
PE13_PF_UART1_RXD,
PE14_PF_UART1_CTS,
PE15_PF_UART1_RTS,
PD0_AIN_FEC_TXD0,
PD1_AIN_FEC_TXD1,
PD2_AIN_FEC_TXD2,
PD3_AIN_FEC_TXD3,
PD4_AOUT_FEC_RX_ER,
PD5_AOUT_FEC_RXD1,
PD6_AOUT_FEC_RXD2,
PD7_AOUT_FEC_RXD3,
PD8_AF_FEC_MDIO,
PD9_AIN_FEC_MDC,
PD10_AOUT_FEC_CRS,
PD11_AOUT_FEC_TX_CLK,
PD12_AOUT_FEC_RXD0,
PD13_AOUT_FEC_RX_DV,
PD14_AOUT_FEC_RX_CLK,
PD15_AOUT_FEC_COL,
PD16_AIN_FEC_TX_ER,
PF23_AIN_FEC_TX_EN,
};
static struct imxuart_platform_data uart_pdata = {
.flags = IMXUART_HAVE_RTSCTS,
};
static struct platform_device *platform_devices[] __initdata = {
&mxc_fec_device,
};
static void __init mx27lite_init(void)
{
mxc_gpio_setup_multiple_pins(mx27lite_pins, ARRAY_SIZE(mx27lite_pins),
"imx27lite");
mxc_register_device(&mxc_uart_device0, &uart_pdata);
platform_add_devices(platform_devices, ARRAY_SIZE(platform_devices));
}
static void __init mx27lite_timer_init(void)
{
mx27_clocks_init(26000000);
}
static struct sys_timer mx27lite_timer = {
.init = mx27lite_timer_init,
};
MACHINE_START(IMX27LITE, "LogicPD i.MX27LITE")
.phys_io = AIPI_BASE_ADDR,
.io_pg_offst = ((AIPI_BASE_ADDR_VIRT) >> 18) & 0xfffc,
.boot_params = PHYS_OFFSET + 0x100,
.map_io = mx27_map_io,
.init_irq = mx27_init_irq,
.init_machine = mx27lite_init,
.timer = &mx27lite_timer,
MACHINE_END
| leemgs/OptimusOneKernel-KandroidCommunity | arch/arm/mach-mx2/mx27lite.c | C | gpl-2.0 | 1,735 |
<?php
class My_Ajax {
public function search_brewery() {
if( isset($_GET['term']) ) {
global $wpdb;
$title = strtoupper($_GET['term']);
$sql = "SELECT ID FROM $wpdb->posts ";
$sql.= "WHERE UCASE(post_title) LIKE '%$title%' ";
$sql.= "AND post_type='brewery' ";
$sql.= "AND post_status='publish'";
$ids = $wpdb->get_col($sql);
if( $ids ) {
$args = array(
'post__in'=> $ids,
'post_type'=>'brewery',
'orderby'=>'title',
'order'=>'asc'
);
$query = new WP_Query($args);
if( $query->have_posts() ) {
$response = array();
while( $query->have_posts() ) {
$query->the_post();
$response[] = get_the_title();
}
echo json_encode($response);
wp_reset_postdata();
exit();
} else {
echo json_encode(array('result' => 'No hay coincidencias'));
wp_reset_postdata();
exit();
}
} else {
echo json_encode(array('result' => 'No hay coincidencias'));
wp_reset_postdata();
exit();
}
}
echo json_encode(array('result' => '...'));
wp_reset_postdata();
exit();
}
public function search_beer() {
if( isset($_GET['term']) ) {
global $wpdb;
$title = strtoupper($_GET['term']);
$sql = "SELECT ID FROM $wpdb->posts ";
$sql.= "WHERE UCASE(post_title) LIKE '%$title%' ";
$sql.= "AND post_type='beer' ";
$sql.= "AND post_status='publish'";
$ids = $wpdb->get_col($sql);
if( $ids ) {
$args = array(
'post__in'=> $ids,
'post_type'=>'beer',
'orderby'=>'title',
'order'=>'asc'
);
$query = new WP_Query($args);
if( $query->have_posts() ) {
$response = array();
while( $query->have_posts() ) {
$query->the_post();
$response[] = get_the_title();
}
echo json_encode($response);
wp_reset_postdata();
exit();
} else {
echo json_encode(array('result' => 'No hay coincidencias'));
wp_reset_postdata();
exit();
}
} else {
echo json_encode(array('result' => 'No hay coincidencias'));
wp_reset_postdata();
exit();
}
}
echo json_encode(array('result' => '...'));
wp_reset_postdata();
exit();
}
public function my_beer_cooler() {
if( isset($_GET['beer_id']) ) {
global $wpdb;
$update = array(
'status' => $_GET['status']
);
switch($_GET['status']) {
case 'Favorite': {
$update['favorite'] = ($_GET['previous'] == 'nwm-beer-no-favorite')? 1 : 0;
break;
}
case 'ForLater': {
$update['forlater'] = ($_GET['previous'] == 'nwm-beer-no-forlater') ? 1 : 0;
break;
}
}
$sql = 'SELECT * FROM nwm_loc_hielera ';
$sql.= 'WHERE beer='.$_GET['beer_id'].' ';
$sql.= 'AND user='.get_current_user_id();
if(($wpdb->get_row($sql)) == null) {
$newCoolerRow = array_merge(
array(
'user' => get_current_user_id(),
'beer' => $_GET['beer_id'],
'review' => 0,
'rate' => 0
),
$update
);
$wpdb->insert('nwm_loc_hielera', $newCoolerRow);
} else {
$updateCoolerRow = array_merge(
array(
'status' => $_GET['status']
),
$update
);
$wpdb->update(
'nwm_loc_hielera',
$updateCoolerRow,
array(
'user' => get_current_user_id(),
'beer' => $_GET['beer_id']
)
);
}
exit();
}
}
public function quick_beer_rate() {
if( isset($_GET['beer_id']) && isset($_GET['rating'] ) ) {
global $current_user;
get_currentuserinfo();
$user_reviews = get_posts( array(
'post_type' => 'review',
'posts_per_page'=> -1,
'order_by' => 'post_date',
'post_status' => 'private',
'author' => $current_user->ID,
'meta_key' => 'cerveza_id',
'meta_value' => $_GET['beer_id']
) );
if( empty($user_reviews) ) {
$cerveza_data = get_post($_GET['beer_id']);
$post = array(
'post_name' => $current_user->display_name.'|Experiencia '.$cerveza_data->post_title,
'post_title' => $current_user->display_name.'|Experiencia '.$cerveza_data->post_title,
'post_content' => '',
'post_status' => 'private',
'post_type' => 'review',
'post_author' => $current_user->ID,
'post_date' => date('Y-m-d H:i:s'), // The time post was made.
'comment_status' => 'closed'
);
$my_review_id = wp_insert_post($post, true);
update_post_meta( $my_review_id, 'cerveza_id', $cerveza_data->ID );
update_post_meta( $my_review_id, 'cerveza_name', $cerveza_data->post_title );
update_post_meta( $my_review_id, 'color', 0 );
update_post_meta( $my_review_id, 'espuma', 0 );
update_post_meta( $my_review_id, 'alcohol', 0 );
update_post_meta( $my_review_id, 'cuerpo', 0 );
update_post_meta( $my_review_id, 'final', 0 );
update_post_meta( $my_review_id, 'amargor', 0 );
update_post_meta( $my_review_id, 'rating', $_GET['rating'] );
} else {
update_post_meta( $user_reviews[0]->ID, 'rating', $_GET['rating'] );
}
global $wpdb;
$sql = 'SELECT * FROM nwm_loc_hielera ';
$sql.= 'WHERE beer='.$_GET['beer_id'].' ';
$sql.= 'AND user='.get_current_user_id();
if(($wpdb->get_row($sql)) == null) {
$wpdb->insert(
'nwm_loc_hielera',
array(
'user' => $current_user->ID,
'beer' => $_GET['beer_id'],
'status' => 'Rated',
'review' => 0,
'rate' => 1,
'favorite' => 0,
'forlater' => 0
)
);
} else {
$wpdb->update(
'nwm_loc_hielera',
array(
'status' => 'Rated',
'rate' => 1
),
array(
'user' => get_current_user_id(),
'beer' => $_GET['beer_id']
)
);
}
wp_reset_postdata();
exit();
}
}
}
| mauricioabisay/loc | wp-content/plugins/plugin-name/ajax/my_ajax.php | PHP | gpl-2.0 | 6,227 |
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/* eslint-disable max-nested-callbacks */
define([
'jquery',
'mage/backend/bootstrap'
], function ($) {
'use strict';
describe('mage/backend/bootstrap', function () {
var $pageMainActions;
beforeEach(function () {
$pageMainActions = $('<div class="page-main-actions"></div>');
});
afterEach(function () {
$pageMainActions.remove();
});
describe('"sendPostponeRequest" method', function () {
it('should insert "Error" notification if request failed', function () {
$pageMainActions.appendTo('body');
$('body').notification();
$.ajaxSettings.error();
expect($('.message-error').length).toBe(1);
expect(
$('body:contains("A technical problem with the server created an error")').length
).toBe(1);
});
});
});
});
| kunj1988/Magento2 | dev/tests/js/jasmine/tests/lib/mage/backend/bootstrap.test.js | JavaScript | gpl-2.0 | 1,055 |
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\ConfigurableProduct\Model\Product\Validator;
use Magento\Catalog\Model\Product;
use Magento\Catalog\Model\ProductFactory;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Event\Manager;
use Magento\Framework\Json\Helper\Data;
use Magento\Framework\DataObject;
/**
* Configurable product validation
*/
class Plugin
{
/**
* @var \Magento\Framework\Event\Manager
*/
protected $eventManager;
/**
* @var \Magento\Catalog\Model\ProductFactory
*/
protected $productFactory;
/**
* @var Data
*/
protected $jsonHelper;
/**
* @param Manager $eventManager
* @param ProductFactory $productFactory
* @param Data $jsonHelper
*/
public function __construct(
Manager $eventManager,
ProductFactory $productFactory,
Data $jsonHelper
) {
$this->eventManager = $eventManager;
$this->productFactory = $productFactory;
$this->jsonHelper = $jsonHelper;
}
/**
* Set configurable type to product
*
* @param Product\Validator $subject
* @param Product $product
* @param RequestInterface $request
* @param DataObject $response
* @return void
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function beforeValidate(
\Magento\Catalog\Model\Product\Validator $subject,
\Magento\Catalog\Model\Product $product,
RequestInterface $request,
DataObject $response
) {
if ($request->has('attributes')) {
$product->setTypeId(\Magento\ConfigurableProduct\Model\Product\Type\Configurable::TYPE_CODE);
}
}
/**
* Validate product data
*
* @param Product\Validator $subject
* @param bool|array $result
* @param Product $product
* @param RequestInterface $request
* @param \Magento\Framework\DataObject $response
* @return bool
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function afterValidate(
\Magento\Catalog\Model\Product\Validator $subject,
$result,
\Magento\Catalog\Model\Product $product,
RequestInterface $request,
DataObject $response
) {
$variationProducts = (array)$request->getPost('variations-matrix');
if ($variationProducts) {
$validationResult = $this->_validateProductVariations($product, $variationProducts, $request);
if (!empty($validationResult)) {
$response->setError(
true
)->setMessage(
__('Some product variations fields are not valid.')
)->setAttributes(
$validationResult
);
}
}
return $result;
}
/**
* Product variations attributes validation
*
* @param Product $parentProduct
* @param array $products
* @param RequestInterface $request
* @return array
*/
protected function _validateProductVariations(Product $parentProduct, array $products, RequestInterface $request)
{
$this->eventManager->dispatch(
'catalog_product_validate_variations_before',
['product' => $parentProduct, 'variations' => $products]
);
$validationResult = [];
foreach ($products as $productData) {
$product = $this->productFactory->create();
$product->setData('_edit_mode', true);
$storeId = $request->getParam('store');
if ($storeId) {
$product->setStoreId($storeId);
}
$product->setAttributeSetId($parentProduct->getAttributeSetId());
$product->addData($this->getRequiredDataFromProduct($parentProduct));
$product->addData($productData);
$product->setCollectExceptionMessages(true);
$configurableAttribute = [];
if (!empty($productData['configurable_attribute'])) {
$encodedData = $productData['configurable_attribute'];
if ($encodedData) {
$configurableAttribute = $this->jsonHelper->jsonDecode($encodedData);
}
}
$configurableAttribute = implode('-', $configurableAttribute);
$errorAttributes = $product->validate();
if (is_array($errorAttributes)) {
foreach ($errorAttributes as $attributeCode => $result) {
if (is_string($result)) {
$key = 'variations-matrix-' . $configurableAttribute . '-' . $attributeCode;
$validationResult[$key] = $result;
}
}
}
}
return $validationResult;
}
/**
* @param Product $product
* @return array
*/
protected function getRequiredDataFromProduct(Product $product)
{
$parentProductData = [];
foreach ($product->getAttributes() as $attribute) {
if ($attribute->getIsUserDefined() && $attribute->getIsRequired()) {
$parentProductData[$attribute->getAttributeCode()] = $product->getData($attribute->getAttributeCode());
}
}
return $parentProductData;
}
}
| kunj1988/Magento2 | app/code/Magento/ConfigurableProduct/Model/Product/Validator/Plugin.php | PHP | gpl-2.0 | 5,401 |
<?php
class EditPageLayoutTest extends WikiaBaseTest {
public function setUp() {
require_once( dirname(__FILE__) . '/../../CityVisualization/CityVisualization.setup.php' );
$this->setupFile = dirname(__FILE__) . '/../EditPageLayout_setup.php';
parent::setUp();
}
/**
* @param Title $title
* @return EditPageLayout
*/
private function editPageFactory(Title $title) {
$article = new Article($title);
return new EditPageLayout($article);
}
/**
* @group Slow
* @slowExecutionTime 0.01107 ms
* @group UsingDB
*/
public function testMainPageEdit() {
// setup edit page object
$title = Title::newMainPage();
$editPage = $this->editPageFactory($title);
// it should extend MW core class
$this->assertInstanceOf('EditPage', $editPage);
$this->assertEquals($title->getArticleID(), $editPage->getArticle()->getID());
$this->assertEquals($title, $editPage->getEditedTitle());
$formAction = str_replace('action=edit', 'action=submit', $title->getEditURL());
$this->assertEquals($formAction, $editPage->getFormAction());
}
/**
* @group UsingDB
*/
public function testCustomFormHandler() {
$title = Title::newFromText('Foo');
$editPage = $this->editPageFactory($title);
$customHandler = Title::newFromText('Special:CustomHandler');
$editPage->setCustomFormHandler($customHandler);
$this->assertEquals($customHandler, $editPage->getCustomFormHandler());
$this->assertEquals($customHandler->getLocalURL('action=submit'), $editPage->getFormAction());
$this->assertEquals($title, $editPage->getEditedTitle());
}
/**
* @group UsingDB
*/
public function testAddingFields() {
$title = Title::newFromText('Foo');
$editPage = $this->editPageFactory($title);
// test custom checkboxes
$editPage->addCustomCheckbox('foo', 'label', true /* $checked */);
$editPage->addCustomCheckbox('bar', 'test', false /* $checked */);
$this->assertEquals(array(
array(
'name' => 'foo',
'label' => 'label',
'checked' => true,
),
array(
'name' => 'bar',
'label' => 'test',
'checked' => false,
),
), $editPage->getCustomCheckboxes());
// test hidden fields
$editPage->addHiddenField(array(
'type' => 'checkbox',
'name' => 'foo',
'value' => true,
'label' => 'label',
));
$editPage->addHiddenField(array(
'type' => 'text',
'name' => 'bar',
'value' => 'summary',
'required' => false,
));
$editPage->addHiddenField(array(
'type' => 'textarea',
'name' => 'field123',
'value' => 'qwerty',
'required' => true,
));
$editPage->addHiddenField(array(
'type' => 'hidden',
'name' => 'test',
'value' => 'hidden value',
));
$this->assertEquals(
'<fieldset id="EditPageHiddenFields">'.
'<label>label<input type="checkbox" name="foo" value="1" data-required="" checked="checked" /></label>'.
'<input type="text" name="bar" value="summary" data-required="" />'.
'<textarea name="field123" data-required="1">qwerty</textarea>'.
'<input type="hidden" name="test" value="hidden value" data-required="" />'.
'</fieldset>',
$editPage->renderHiddenFields());
// summary box
$this->assertStringStartsWith('<input type="text" id="wpSummary" name="wpSummary" placeholder=', $editPage->renderSummaryBox());
}
/**
* @group Slow
* @slowExecutionTime 0.07107 ms
* @group UsingDB
*/
public function testPreloadText() {
$title = Title::newFromText('NewArticle');
$editPage = $this->editPageFactory($title);
// This test has a dependency on the global title
// TODO: fixme with $this->mockProxy
global $wgTitle;
$tempTitle = $wgTitle;
$wgTitle = $title;
// TODO mock something in this test because it's running hooks
$preload = 'Preload - testing, testing...';
$editPage->setPreloadedText($preload);
$editPage->showEditForm();
// With RTE enabled by default now, this is wrapped in a <p> tag
$this->assertContains($preload, $editPage->textbox1);
$wgTitle = $tempTitle;
}
/**
* @group UsingDB
*/
public function testEditNotices() {
$title = Title::newFromText('NewArticle');
$editPage = $this->editPageFactory($title);
$testNotice1Body = '<div>1st notice</div>';
$testNotice1Key = 'TESTKEY1';
$testNotice2Body = '<div>2nd notice</div>';
$testNotice2Key = 'TESTKEY2';
$editPage->addEditNotice($testNotice1Body, $testNotice1Key);
$editPage->addEditNotice($testNotice2Body, $testNotice2Key);
$this->assertEquals(array(
md5($testNotice1Key) => '1st notice',
md5($testNotice2Key) => '2nd notice'
), $editPage->getNotices());
$this->assertEquals($testNotice1Body.$testNotice2Body, $editPage->getNoticesHtml());
}
}
| felixonmars/app | extensions/wikia/EditPageLayout/tests/EditPageLayoutTest.php | PHP | gpl-2.0 | 4,649 |
// NAnt - A .NET build tool
// Copyright (C) 2001-2002 Gerry Shaw
//
// 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
//
// Sergey Chaban (serge@wildwestsoftware.com)
// Gerry Shaw (gerry_shaw@yahoo.com)
// Ian MacLean (ian at maclean.ms)
// Giuseppe Greco (giuseppe.greco@agamura.com)
// Gert Driesen (drieseng@users.sourceforge.net)
using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections.Specialized;
using System.Globalization;
using System.IO;
using System.Reflection;
using NAnt.Core;
using NAnt.Core.Attributes;
using NAnt.Core.Types;
using NAnt.Core.Util;
using NAnt.DotNet.Types;
namespace NAnt.DotNet.Tasks {
/// <summary>
/// Executes the code contained within the task.
/// </summary>
/// <remarks>
/// <h5>Code</h5>
/// <para>
/// The <see cref="ScriptTask" /> must contain a single <c>code</c>
/// element, which in turn contains the script code.
/// </para>
/// <para>
/// This code can include extensions such as functions, or tasks. Once
/// the script task has executed those extensions will be available for
/// use in the buildfile.
/// </para>
/// <para>
/// If no extensions have been defined, a static entry point named
/// <c>ScriptMain</c> - which must have a single <see cref="Project"/>
/// argument - is required.
/// </para>
/// <h5>Namespaces</h5>
/// <para>
/// The following namespaces are imported by default:
/// </para>
/// <list type="bullet">
/// <item>
/// <description>System</description>
/// </item>
/// <item>
/// <description>System.Collections</description>
/// </item>
/// <item>
/// <description>System.IO</description>
/// </item>
/// <item>
/// <description>System.Text</description>
/// </item>
/// <item>
/// <description>NAnt.Core</description>
/// </item>
/// <item>
/// <description>NAnt.Core.Attributes</description>
/// </item>
/// </list>
/// <h5>Assembly References</h5>
/// <para>
/// The assembly references that are specified will be used to compile
/// the script, and will be loaded into the NAnt appdomain.
/// </para>
/// <para>
/// By default, only the <c>NAnt.Core</c> and <c>mscorlib</c> assemblies
/// are referenced.
/// </para>
/// </remarks>
/// <example>
/// <para>Run C# code that writes a message to the build log.</para>
/// <code>
/// <script language="C#">
/// <code>
/// <![CDATA[
/// public static void ScriptMain(Project project) {
/// project.Log(Level.Info, "Hello World from a script task using C#");
/// }
/// ]]>
/// </code>
/// </script>
/// </code>
/// </example>
/// <example>
/// <para>Define a custom function and call it using C#.</para>
/// <code>
/// <script language="C#" prefix="test" >
/// <code>
/// <![CDATA[
/// [Function("test-func")]
/// public static string Testfunc( ) {
/// return "some result !!!!!!!!";
/// }
/// ]]>
/// </code>
/// </script>
/// <echo message='${test::test-func()}'/>
/// </code>
/// </example>
/// <example>
/// <para>Use a custom namespace in C# to create a database</para>
/// <code>
/// <script language="C#" >
/// <references>
/// <include name="System.Data.dll" />
/// </references>
/// <imports>
/// <import namespace="System.Data.SqlClient" />
/// </imports>
/// <code>
/// <![CDATA[
/// public static void ScriptMain(Project project) {
/// string dbUserName = "nant";
/// string dbPassword = "nant";
/// string dbServer = "(local)";
/// string dbDatabaseName = "NAntSample";
/// string connectionString = String.Format("Server={0};uid={1};pwd={2};", dbServer, dbUserName, dbPassword);
///
/// SqlConnection connection = new SqlConnection(connectionString);
/// string createDbQuery = "CREATE DATABASE " + dbDatabaseName;
/// SqlCommand createDatabaseCommand = new SqlCommand(createDbQuery);
/// createDatabaseCommand.Connection = connection;
///
/// connection.Open();
///
/// try {
/// createDatabaseCommand.ExecuteNonQuery();
/// project.Log(Level.Info, "Database added successfully: " + dbDatabaseName);
/// } catch (Exception e) {
/// project.Log(Level.Error, e.ToString());
/// } finally {
/// connection.Close();
/// }
/// }
/// ]]>
/// </code>
/// </script>
/// </code>
/// </example>
/// <example>
/// <para>
/// Run Visual Basic.NET code that writes a message to the build log.
/// </para>
/// <code>
/// <script language="VB">
/// <code>
/// <![CDATA[
/// Public Shared Sub ScriptMain(project As Project)
/// project.Log(Level.Info, "Hello World from a script task using Visual Basic.NET")
/// End Sub
/// ]]>
/// </code>
/// </script>
/// </code>
/// </example>
/// <example>
/// <para>Define a custom task and call it using C#.</para>
/// <code>
/// <script language="C#" prefix="test" >
/// <code>
/// <![CDATA[
/// [TaskName("usertask")]
/// public class TestTask : Task {
/// #region Private Instance Fields
///
/// private string _message;
///
/// #endregion Private Instance Fields
///
/// #region Public Instance Properties
///
/// [TaskAttribute("message", Required=true)]
/// public string FileName {
/// get { return _message; }
/// set { _message = value; }
/// }
///
/// #endregion Public Instance Properties
///
/// #region Override implementation of Task
///
/// protected override void ExecuteTask() {
/// Log(Level.Info, _message.ToUpper());
/// }
/// #endregion Override implementation of Task
/// }
/// ]]>
/// </code>
/// </script>
/// <usertask message='Hello from UserTask'/>
/// </code>
/// </example>
/// <example>
/// <para>
/// Define a custom function and call it using <see href="http://boo.codehaus.org/">Boo</see>.
/// </para>
/// <code>
/// <script language="Boo.CodeDom.BooCodeProvider, Boo.CodeDom, Version=1.0.0.0, Culture=neutral, PublicKeyToken=32c39770e9a21a67"
/// failonerror="true">
/// <code>
/// <![CDATA[
///
/// [Function("test-func")]
/// def MyFunc():
/// return "Hello from Boo !!!!!!"
/// ]]>
/// </code>
/// </script>
/// <echo message='${script::test-func()}'/>
/// </code>
/// </example>
[TaskName("script")]
public class ScriptTask : Task {
#region Private Instance Fields
private string _language = null;
private AssemblyFileSet _references = new AssemblyFileSet();
private string _mainClass = "";
private string _rootClassName;
private string _prefix = "script";
private NamespaceImportCollection _imports = new NamespaceImportCollection();
private RawXml _code;
#endregion Private Instance Fields
#region Private Static Fields
private static readonly string[] _defaultNamespaces = {
"System",
"System.Collections",
"System.IO",
"System.Text",
"NAnt.Core",
"NAnt.Core.Attributes"};
#endregion Private Static Fields
#region Public Instance Properties
/// <summary>
/// The language of the script block. Possible values are "VB", "vb", "VISUALBASIC", "C#", "c#", "CSHARP".
/// "JS", "js", "JSCRIPT" "VJS", "vjs", "JSHARP" or a fully-qualified name for a class implementing
/// <see cref="T:System.CodeDom.Compiler.CodeDomProvider" />.
/// </summary>
[TaskAttribute("language", Required=true)]
public string Language {
get { return _language; }
set { _language = StringUtils.ConvertEmptyToNull(value); }
}
/// <summary>
/// Any required references.
/// </summary>
[BuildElement("references")]
public AssemblyFileSet References {
get { return _references; }
set { _references = value; }
}
/// <summary>
/// The name of the main class containing the static <c>ScriptMain</c>
/// entry point.
/// </summary>
[TaskAttribute("mainclass", Required=false)]
public string MainClass {
get { return _mainClass; }
set { _mainClass = StringUtils.ConvertEmptyToNull(value); }
}
/// <summary>
/// The namespace prefix for any custom functions defined in the script.
/// If ommitted the prefix will default to 'script'
/// </summary>
[TaskAttribute("prefix", Required=false)]
public string Prefix {
get { return _prefix; }
set { _prefix = StringUtils.ConvertEmptyToNull(value); }
}
/// <summary>
/// The namespaces to import.
/// </summary>
[BuildElement("imports")]
public NamespaceImportCollection Imports {
get { return _imports; }
set { _imports = value; }
}
/// <summary>
/// The code to execute.
/// </summary>
[BuildElement("code", Required=true)]
public RawXml Code {
get { return _code; }
set { _code = value; }
}
#endregion Public Instance Properties
#region Override implementation of Task
/// <summary>
/// Initializes the task.
/// </summary>
protected override void Initialize() {
_rootClassName = "nant" + Guid.NewGuid().ToString("N",
CultureInfo.InvariantCulture);
}
/// <summary>
/// Executes the script block.
/// </summary>
protected override void ExecuteTask() {
// create compiler info for user-specified language
CompilerInfo compilerInfo = CreateCompilerInfo(Language);
// ensure base directory is set, even if fileset was not initialized
// from XML
if (References.BaseDirectory == null) {
References.BaseDirectory = new DirectoryInfo(Project.BaseDirectory);
}
CodeDomProvider compiler = compilerInfo.Provider;
CompilerParameters options = new CompilerParameters();
options.GenerateExecutable = false;
options.GenerateInMemory = true;
options.MainClass = MainClass;
// implicitly reference the NAnt.Core assembly
options.ReferencedAssemblies.Add (typeof (Project).Assembly.Location);
// Log the assembly being added to the CompilerParameters
Log(Level.Verbose, "Adding assembly {0}", typeof (Project).Assembly.GetName().Name);
// add (and load) assemblies specified by user
foreach (string assemblyFile in References.FileNames) {
try {
// load the assembly into current AppDomain to ensure it is
// available when executing the emitted assembly
Assembly asm = Assembly.LoadFrom(assemblyFile);
// Log the assembly being added to the CompilerParameters
Log(Level.Verbose, "Adding assembly {0}", asm.GetName().Name);
// add the location of the loaded assembly
if (!String.IsNullOrEmpty(asm.Location)) {
options.ReferencedAssemblies.Add(asm.Location);
}
} catch (Exception ex) {
throw new BuildException(string.Format(CultureInfo.InvariantCulture,
ResourceUtils.GetString("NA2028"), assemblyFile), Location, ex);
}
}
StringCollection imports = new StringCollection();
foreach (NamespaceImport import in Imports) {
if (import.IfDefined && !import.UnlessDefined) {
imports.Add(import.Namespace);
}
}
// generate the code
CodeCompileUnit compileUnit = compilerInfo.GenerateCode(_rootClassName,
Code.Xml.InnerText, imports, Prefix);
StringWriter sw = new StringWriter(CultureInfo.InvariantCulture);
compiler.GenerateCodeFromCompileUnit(compileUnit, sw, null);
string code = sw.ToString();
Log(Level.Debug, ResourceUtils.GetString("String_GeneratedCodeLooksLike") + "\n{0}", code);
CompilerResults results = compiler.CompileAssemblyFromDom(options, compileUnit);
Assembly compiled = null;
if (results.Errors.Count > 0) {
string errors = ResourceUtils.GetString("NA2029") + Environment.NewLine;
foreach (CompilerError err in results.Errors) {
errors += err.ToString() + Environment.NewLine;
}
errors += code;
throw new BuildException(errors, Location);
} else {
compiled = results.CompiledAssembly;
}
// scan the new assembly for tasks, types and functions
// Its unlikely that tasks will be defined in buildfiles though.
bool extensionAssembly = TypeFactory.ScanAssembly(compiled, this);
string mainClass = _rootClassName;
if (!String.IsNullOrEmpty(MainClass)) {
mainClass += "+" + MainClass;
}
Type mainType = compiled.GetType(mainClass);
if (mainType == null) {
throw new BuildException(string.Format(CultureInfo.InvariantCulture,
ResourceUtils.GetString("NA2030"), mainClass), Location);
}
MethodInfo entry = mainType.GetMethod("ScriptMain");
// check for task or function definitions.
if (entry == null) {
if (!extensionAssembly) {
throw new BuildException(ResourceUtils.GetString("NA2031"), Location);
} else {
return; // no entry point so nothing to do here beyond loading task and function defs
}
}
if (!entry.IsStatic) {
throw new BuildException(ResourceUtils.GetString("NA2032"), Location);
}
ParameterInfo[] entryParams = entry.GetParameters();
if (entryParams.Length != 1) {
throw new BuildException(ResourceUtils.GetString("NA2033"), Location);
}
if (entryParams[0].ParameterType.FullName != typeof(Project).FullName) {
throw new BuildException(string.Format(CultureInfo.InvariantCulture,
ResourceUtils.GetString("NA2034"), entryParams[0].ParameterType.FullName,
typeof(Project).FullName), Location);
}
try {
// invoke Main method
entry.Invoke(null, new object[] {Project});
} catch (Exception ex) {
// this exception is not likely to tell us much, BUT the
// InnerException normally contains the runtime exception
// thrown by the executed script code.
throw new BuildException(ResourceUtils.GetString("NA2035"), Location,
ex.InnerException);
}
}
#endregion Override implementation of Task
#region Private Instance Methods
private CompilerInfo CreateCompilerInfo(string language) {
CodeDomProvider provider = null;
try {
switch (language) {
case "vb":
case "VB":
case "VISUALBASIC":
provider = CreateCodeDomProvider(
"Microsoft.VisualBasic.VBCodeProvider",
"System, Culture=neutral");
break;
case "c#":
case "C#":
case "CSHARP":
provider = CreateCodeDomProvider(
"Microsoft.CSharp.CSharpCodeProvider",
"System, Culture=neutral");
break;
case "js":
case "JS":
case "JSCRIPT":
provider = CreateCodeDomProvider(
"Microsoft.JScript.JScriptCodeProvider",
"Microsoft.JScript, Culture=neutral");
break;
case "vjs":
case "VJS":
case "JSHARP":
provider = CreateCodeDomProvider(
"Microsoft.VJSharp.VJSharpCodeProvider",
"VJSharpCodeProvider, Culture=neutral");
break;
default:
// if its not one of the above then it must be a fully
// qualified provider class name
provider = CreateCodeDomProvider(language);
break;
}
return new CompilerInfo(provider);
} catch (Exception ex) {
throw new BuildException(string.Format(CultureInfo.InvariantCulture,
ResourceUtils.GetString("NA2036"), language), Location, ex);
}
}
#endregion Private Instance Methods
#region Private Static Methods
private static CodeDomProvider CreateCodeDomProvider(string typeName, string assemblyName) {
Assembly providerAssembly = Assembly.Load(assemblyName);
if (providerAssembly == null) {
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture,
ResourceUtils.GetString("NA2037"), assemblyName));
}
Type providerType = providerAssembly.GetType(typeName, true, true);
return CreateCodeDomProvider(providerType);
}
private static CodeDomProvider CreateCodeDomProvider(string assemblyQualifiedTypeName) {
Type providerType = Type.GetType(assemblyQualifiedTypeName, true, true);
return CreateCodeDomProvider(providerType);
}
private static CodeDomProvider CreateCodeDomProvider(Type providerType) {
object provider = Activator.CreateInstance(providerType);
if (!(provider is CodeDomProvider)) {
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture,
ResourceUtils.GetString("NA2038"), providerType.FullName));
}
return (CodeDomProvider) provider;
}
#endregion Private Static Methods
internal class CompilerInfo {
//public readonly ICodeCompiler Compiler;
//public readonly ICodeGenerator CodeGen;
public readonly CodeDomProvider Provider;
public CompilerInfo(CodeDomProvider provider) {
//Compiler = provider.CreateCompiler();
//CodeGen = provider.CreateGenerator();
this.Provider = provider;
}
public CodeCompileUnit GenerateCode(string typeName, string codeBody,
StringCollection imports,
string prefix) {
CodeCompileUnit compileUnit = new CodeCompileUnit();
CodeTypeDeclaration typeDecl = new CodeTypeDeclaration(typeName);
typeDecl.IsClass = true;
typeDecl.TypeAttributes = TypeAttributes.Public;
// create constructor
CodeConstructor constructMember = new CodeConstructor();
constructMember.Attributes = MemberAttributes.Public;
constructMember.Parameters.Add(new CodeParameterDeclarationExpression("NAnt.Core.Project", "project"));
constructMember.Parameters.Add(new CodeParameterDeclarationExpression("NAnt.Core.PropertyDictionary", "propDict"));
constructMember.BaseConstructorArgs.Add(new CodeVariableReferenceExpression("project"));
constructMember.BaseConstructorArgs.Add(new CodeVariableReferenceExpression ("propDict"));
typeDecl.Members.Add(constructMember);
typeDecl.BaseTypes.Add(typeof(FunctionSetBase));
// add FunctionSet attribute
CodeAttributeDeclaration attrDecl = new CodeAttributeDeclaration("FunctionSet");
attrDecl.Arguments.Add(new CodeAttributeArgument(
new CodeVariableReferenceExpression("\"" + prefix + "\"")));
attrDecl.Arguments.Add(new CodeAttributeArgument(
new CodeVariableReferenceExpression("\"" + prefix + "\"")));
typeDecl.CustomAttributes.Add(attrDecl);
// pump in the user specified code as a snippet
CodeSnippetTypeMember literalMember =
new CodeSnippetTypeMember(codeBody);
typeDecl.Members.Add( literalMember );
CodeNamespace nspace = new CodeNamespace();
//Add default imports
foreach (string nameSpace in ScriptTask._defaultNamespaces) {
nspace.Imports.Add(new CodeNamespaceImport(nameSpace));
}
foreach (string nameSpace in imports) {
nspace.Imports.Add(new CodeNamespaceImport(nameSpace));
}
compileUnit.Namespaces.Add( nspace );
nspace.Types.Add(typeDecl);
return compileUnit;
}
}
}
}
| nantos/nant | src/NAnt.DotNet/Tasks/ScriptTask.cs | C# | gpl-2.0 | 25,561 |
CREATE TABLE sca_subscriptions (
id INTEGER PRIMARY KEY NOT NULL,
subscriber VARCHAR(255) NOT NULL,
aor VARCHAR(255) NOT NULL,
event INTEGER DEFAULT 0 NOT NULL,
expires INTEGER DEFAULT 0 NOT NULL,
state INTEGER DEFAULT 0 NOT NULL,
app_idx INTEGER DEFAULT 0 NOT NULL,
call_id VARCHAR(255) NOT NULL,
from_tag VARCHAR(64) NOT NULL,
to_tag VARCHAR(64) NOT NULL,
record_route TEXT,
notify_cseq INTEGER NOT NULL,
subscribe_cseq INTEGER NOT NULL,
CONSTRAINT sca_subscriptions_sca_subscriptions_idx UNIQUE (subscriber, call_id, from_tag, to_tag)
);
CREATE INDEX sca_subscriptions_sca_expires_idx ON sca_subscriptions (expires);
CREATE INDEX sca_subscriptions_sca_subscribers_idx ON sca_subscriptions (subscriber, event);
INSERT INTO version (table_name, table_version) values ('sca_subscriptions','1');
| vingarzan/kamailio | utils/kamctl/db_sqlite/sca-create.sql | SQL | gpl-2.0 | 854 |
<?php
function mytheme_comment($comment, $args, $depth) {
$GLOBALS['comment'] = $comment; ?>
<li <?php comment_class(); ?> id="li-comment-<?php comment_ID() ?>">
<div id="comment-<?php comment_ID(); ?>">
<div class="comment-author vcard">
<?php echo get_avatar($comment,$size='32'); ?>
<?php printf(__('<cite class="fn">%s</cite>'), get_comment_author_link()) ?>
</div>
<?php if ($comment->comment_approved == '0') : ?>
<em><?php _e('Your comment is awaiting moderation.') ?></em>
<?php endif; ?>
<?php comment_text() ?>
<div class="reply">
<?php comment_reply_link(array ('reply_text' => 'Reply', 'depth' => $depth, 'max_depth' => $args['max_depth'])) ?>
</div>
</div>
<?php
}
?> | cassiodeveloper/blog.cassiobp.com.br | wp-content/themes/satoshi/scripts/comments-callback.php | PHP | gpl-2.0 | 734 |
<?php defined("SYSPATH") or die("No direct script access.");
/**
* Gallery - a web based photo album viewer and editor
* Copyright (C) 2000-2011 Bharat Mediratta
*
* 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 metadescription_theme_Core {
static function head($theme) {
if ($theme->tag()) {
// If the current page belongs to a tag, look up
// the information for that tag.
$tagsItem = ORM::factory("tag")
->where("id", "=", $theme->tag()->id)
->find_all();
} elseif ($theme->item()) {
// If the current page belongs to an item (album, photo, etc.),
// look up any tags that have been applied to that item.
$tagsItem = ORM::factory("tag")
->join("items_tags", "tags.id", "items_tags.tag_id")
->where("items_tags.item_id", "=", $theme->item->id)
->find_all();
} else {
// If the current page is neighter an item nor tag, do nothing.
return;
}
// Load the meta tags into the top of the page.
// @todo: metadescription_block.html requires an item so for now, don't render it unless we
// have one.
if ($theme->item() || $theme->tag()) {
$metaView = new View("metadescription_block.html");
$metaView->tags = $tagsItem;
return $metaView;
}
}
}
| calonso-conabio/gallery3 | modules/metadescription/helpers/metadescription_theme.php | PHP | gpl-2.0 | 2,025 |
//>>built
define("dojox/highlight/languages/html",["../_base","./xml"],function(c){var d={code:1,kbd:1,font:1,noscript:1,style:1,img:1,title:1,menu:1,tt:1,tr:1,param:1,li:1,tfoot:1,th:1,input:1,td:1,dl:1,blockquote:1,fieldset:1,big:1,dd:1,abbr:1,optgroup:1,dt:1,button:1,isindex:1,p:1,small:1,div:1,dir:1,em:1,frame:1,meta:1,sub:1,bdo:1,label:1,acronym:1,sup:1,body:1,xml:1,basefont:1,base:1,br:1,address:1,strong:1,legend:1,ol:1,script:1,caption:1,s:1,col:1,h2:1,h3:1,h1:1,h6:1,h4:1,h5:1,table:1,select:1,noframes:1,
span:1,area:1,dfn:1,strike:1,cite:1,thead:1,head:1,option:1,form:1,hr:1,"var":1,link:1,b:1,colgroup:1,ul:1,applet:1,del:1,iframe:1,pre:1,frameset:1,ins:1,tbody:1,html:1,samp:1,map:1,object:1,a:1,xmlns:1,center:1,textarea:1,i:1,q:1,u:1},e={className:"doctype",begin:"\x3c!DOCTYPE",end:"\x3e",relevance:10},f={className:"attribute",begin:" [a-zA-Z]+",end:"^"},g={className:"value",begin:"[a-zA-Z0-9]+",end:"^"},a=c.languages,b=a.xml;a.html={defaultMode:{contains:["tag","comment","doctype"]},case_insensitive:!0,
modes:[b.XML_COMMENT,e,{className:"tag",lexems:[c.constants.IDENT_RE],keywords:d,begin:"\x3c[A-Za-z/]",end:"\x3e",contains:["attribute"],illegal:"[\\+\\.]"},b.XML_ATTR,f,b.XML_VALUE,g],HTML_TAGS:d,HTML_DOCTYPE:e,HTML_ATTR:f,HTML_VALUE:g};return a.html});
//@ sourceMappingURL=html.js.map | joshuacoddingyou/php | public/scripts/dojox/highlight/languages/html.js | JavaScript | gpl-2.0 | 1,316 |
<!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=ISO-8859-1">
<title>LJ::Cmdbuffer::get_property</title>
<link rel="stylesheet" href="style.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2">
<link rel="start" href="index.html" title="LiveJournal Server">
<link rel="up" href="ljp.api.ref.html" title="API Documentation">
<link rel="prev" href="ljp.api.lj.cmdbuffer.flush.html" title="LJ::Cmdbuffer::flush">
<link rel="next" href="ljp.api.lj.comment.create.html" title="LJ::Comment::create">
<meta name="date" content="2008-Sep-26">
</head>
<body>
<div class="navheader">
<table width="100%" summary="Navigation header">
<tr><th colspan="3" align="center">LJ::Cmdbuffer::get_property</th></tr>
<tr>
<td width="20%" align="left">
<a accesskey="p" href="ljp.api.lj.cmdbuffer.flush.html">Prev</a> </td>
<th width="60%" align="center">API Documentation</th>
<td width="20%" align="right"> <a accesskey="n" href="ljp.api.lj.comment.create.html">Next</a>
</td>
</tr>
</table>
<hr>
</div>
<div class="refentry" lang="en">
<a name="ljp.api.lj.cmdbuffer.get_property"></a><div class="titlepage"></div>
<div class="refnamediv">
<h2>LJ::Cmdbuffer::get_property</h2>
<p>LJ::Cmdbuffer::get_property — Get a property of an async job type, either built-in or site-specific.</p>
</div>
<div class="refsynopsisdiv">
<h2>Use</h2>
<div class="funcsynopsis"><p><code class="funcdef"><b class="fsfunc">LJ::Cmdbuffer::get_property</b>(</code><var class="pdparam">cmd</var>, <var class="pdparam">prop</var><code>)</code>;</p></div>
</div>
<div class="refsect1" lang="en">
<a name="id3567031"></a><h2>Arguments</h2>
<div class="itemizedlist"><ul type="disc">
<li><p><b>cmd. </b>a registered async job type</p></li>
<li><p><b>prop. </b>the property name to look up</p></li>
</ul></div>
</div>
<div class="refsect1" lang="en">
<a name="id3567063"></a><h2>Source:</h2>
<p><code class="filename">cgi-bin/ljcmdbuffer.pl</code></p>
</div>
<div class="refsect1" lang="en">
<a name="id3567077"></a><h2>Returns:</h2>
<p>Value of property (whatever it may be) on success; undef on failure.</p>
</div>
</div>
<div class="navfooter">
<hr>
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left">
<a accesskey="p" href="ljp.api.lj.cmdbuffer.flush.html">Prev</a> </td>
<td width="20%" align="center"><a accesskey="u" href="ljp.api.ref.html">Up</a></td>
<td width="40%" align="right"> <a accesskey="n" href="ljp.api.lj.comment.create.html">Next</a>
</td>
</tr>
<tr>
<td width="40%" align="left" valign="top">LJ::Cmdbuffer::flush </td>
<td width="20%" align="center"><a accesskey="h" href="index.html">Home</a></td>
<td width="40%" align="right" valign="top"> LJ::Comment::create</td>
</tr>
</table>
</div>
</body>
</html>
| apparentlymart/livejournal | htdocs/doc/server/ljp.api.lj.cmdbuffer.get_property.html | HTML | gpl-2.0 | 2,880 |
<?php /* Smarty version 2.6.26, created on 2010-10-18 10:02:52
compiled from mainPageRight.tpl */ ?>
<?php require_once(SMARTY_CORE_DIR . 'core.load_plugins.php');
smarty_core_load_plugins(array('plugins' => array(array('function', 'lang_get', 'mainPageRight.tpl', 14, false),array('modifier', 'escape', 'mainPageRight.tpl', 123, false),array('modifier', 'truncate', 'mainPageRight.tpl', 124, false),)), $this); ?>
<?php echo lang_get_smarty(array('var' => 'labels','s' => "current_test_plan,ok,testplan_role,msg_no_rights_for_tp,
title_test_execution,href_execute_test,href_rep_and_metrics,
href_update_tplan,href_newest_tcversions,
href_my_testcase_assignments,href_platform_assign,
href_tc_exec_assignment,href_plan_assign_urgency,
href_upd_mod_tc,title_test_plan_mgmt,title_test_case_suite,
href_plan_management,href_assign_user_roles,
href_build_new,href_plan_mstones,href_plan_define_priority,
href_metrics_dashboard,href_add_remove_test_cases"), $this);?>
<?php $this->assign('menuLayout', $this->_tpl_vars['tlCfg']->gui->layoutMainPageRight); ?>
<?php $this->assign('display_right_block_1', false); ?>
<?php $this->assign('display_right_block_2', false); ?>
<?php $this->assign('display_right_block_3', false); ?>
<?php if ($this->_tpl_vars['gui']->grants['testplan_planning'] == 'yes' || $this->_tpl_vars['gui']->grants['mgt_testplan_create'] == 'yes' || $this->_tpl_vars['gui']->grants['testplan_user_role_assignment'] == 'yes' || $this->_tpl_vars['gui']->grants['testplan_create_build'] == 'yes'): ?>
<?php $this->assign('display_right_block_1', true); ?>
<script type="text/javascript">
<?php echo '
function display_right_block_1()
{
var rp1 = new Ext.Panel({
title: '; ?>
'<?php echo $this->_tpl_vars['labels']['title_test_plan_mgmt']; ?>
'<?php echo ',
collapsible:false,
collapsed: false,
draggable: false,
contentEl: \'test_plan_mgmt_topics\',
baseCls: \'x-tl-panel\',
bodyStyle: "background:#c8dce8;padding:3px;",
renderTo: '; ?>
'menu_right_block_<?php echo $this->_tpl_vars['menuLayout']['testPlan']; ?>
'<?php echo ',
width:\'100%\'
});
}
'; ?>
</script>
<?php endif; ?>
<?php if ($this->_tpl_vars['gui']->countPlans > 0): ?>
<?php $this->assign('display_right_block_2', true); ?>
<script type="text/javascript">
<?php echo '
function display_right_block_2()
{
var rp2 = new Ext.Panel({
title: '; ?>
'<?php echo $this->_tpl_vars['labels']['title_test_execution']; ?>
'<?php echo ',
collapsible:false,
collapsed: false,
draggable: false,
contentEl: \'test_execution_topics\',
baseCls: \'x-tl-panel\',
bodyStyle: "background:#c8dce8;padding:3px;",
renderTo: '; ?>
'menu_right_block_<?php echo $this->_tpl_vars['menuLayout']['testExecution']; ?>
'<?php echo ',
width:\'100%\'
});
}
'; ?>
</script>
<?php endif; ?>
<?php if ($this->_tpl_vars['gui']->countPlans > 0 && $this->_tpl_vars['gui']->grants['testplan_planning'] == 'yes'): ?>
<?php $this->assign('display_right_block_3', true); ?>
<script type="text/javascript">
<?php echo '
function display_right_block_3()
{
var rp3 = new Ext.Panel({
title: '; ?>
'<?php echo $this->_tpl_vars['labels']['title_test_case_suite']; ?>
'<?php echo ',
collapsible:false,
collapsed: false,
draggable: false,
contentEl: \'testplan_contents_topics\',
baseCls: \'x-tl-panel\',
bodyStyle: "background:#c8dce8;padding:3px;",
renderTo: '; ?>
'menu_right_block_<?php echo $this->_tpl_vars['menuLayout']['testPlanContents']; ?>
'<?php echo ',
width:\'100%\'
});
}
'; ?>
</script>
<?php endif; ?>
<div class="vertical_menu" style="float: left">
<?php if ($this->_tpl_vars['gui']->num_active_tplans > 0): ?>
<div class="testproject_title">
<?php echo lang_get_smarty(array('s' => 'help','var' => 'common_prefix'), $this);?>
<?php echo lang_get_smarty(array('s' => 'test_plan','var' => 'xx_alt'), $this);?>
<?php $this->assign('text_hint', ($this->_tpl_vars['common_prefix']).": ".($this->_tpl_vars['xx_alt'])); ?>
<?php $_smarty_tpl_vars = $this->_tpl_vars;
$this->_smarty_include(array('smarty_include_tpl_file' => "inc_help.tpl", 'smarty_include_vars' => array('helptopic' => 'hlp_testPlan','show_help_icon' => true,'inc_help_alt' => ($this->_tpl_vars['text_hint']),'inc_help_title' => ($this->_tpl_vars['text_hint']),'inc_help_style' => "float: right;vertical-align: top;")));
$this->_tpl_vars = $_smarty_tpl_vars;
unset($_smarty_tpl_vars);
?>
<form name="testplanForm" action="lib/general/mainPage.php">
<?php if ($this->_tpl_vars['gui']->countPlans > 0): ?>
<?php echo $this->_tpl_vars['labels']['current_test_plan']; ?>
:<br/>
<select style="z-index:1" name="testplan" onchange="this.form.submit();">
<?php unset($this->_sections['tPlan']);
$this->_sections['tPlan']['name'] = 'tPlan';
$this->_sections['tPlan']['loop'] = is_array($_loop=$this->_tpl_vars['gui']->arrPlans) ? count($_loop) : max(0, (int)$_loop); unset($_loop);
$this->_sections['tPlan']['show'] = true;
$this->_sections['tPlan']['max'] = $this->_sections['tPlan']['loop'];
$this->_sections['tPlan']['step'] = 1;
$this->_sections['tPlan']['start'] = $this->_sections['tPlan']['step'] > 0 ? 0 : $this->_sections['tPlan']['loop']-1;
if ($this->_sections['tPlan']['show']) {
$this->_sections['tPlan']['total'] = $this->_sections['tPlan']['loop'];
if ($this->_sections['tPlan']['total'] == 0)
$this->_sections['tPlan']['show'] = false;
} else
$this->_sections['tPlan']['total'] = 0;
if ($this->_sections['tPlan']['show']):
for ($this->_sections['tPlan']['index'] = $this->_sections['tPlan']['start'], $this->_sections['tPlan']['iteration'] = 1;
$this->_sections['tPlan']['iteration'] <= $this->_sections['tPlan']['total'];
$this->_sections['tPlan']['index'] += $this->_sections['tPlan']['step'], $this->_sections['tPlan']['iteration']++):
$this->_sections['tPlan']['rownum'] = $this->_sections['tPlan']['iteration'];
$this->_sections['tPlan']['index_prev'] = $this->_sections['tPlan']['index'] - $this->_sections['tPlan']['step'];
$this->_sections['tPlan']['index_next'] = $this->_sections['tPlan']['index'] + $this->_sections['tPlan']['step'];
$this->_sections['tPlan']['first'] = ($this->_sections['tPlan']['iteration'] == 1);
$this->_sections['tPlan']['last'] = ($this->_sections['tPlan']['iteration'] == $this->_sections['tPlan']['total']);
?>
<option value="<?php echo $this->_tpl_vars['gui']->arrPlans[$this->_sections['tPlan']['index']]['id']; ?>
"
<?php if ($this->_tpl_vars['gui']->arrPlans[$this->_sections['tPlan']['index']]['selected']): ?> selected="selected" <?php endif; ?>
title="<?php echo ((is_array($_tmp=$this->_tpl_vars['gui']->arrPlans[$this->_sections['tPlan']['index']]['name'])) ? $this->_run_mod_handler('escape', true, $_tmp) : smarty_modifier_escape($_tmp)); ?>
">
<?php echo ((is_array($_tmp=((is_array($_tmp=$this->_tpl_vars['gui']->arrPlans[$this->_sections['tPlan']['index']]['name'])) ? $this->_run_mod_handler('truncate', true, $_tmp, $this->_config[0]['vars']['TESTPLAN_TRUNCATE_SIZE']) : smarty_modifier_truncate($_tmp, $this->_config[0]['vars']['TESTPLAN_TRUNCATE_SIZE'])))) ? $this->_run_mod_handler('escape', true, $_tmp) : smarty_modifier_escape($_tmp)); ?>
</option>
<?php endfor; endif; ?>
</select>
<?php if ($this->_tpl_vars['gui']->countPlans == 1): ?>
<input type="button" onclick="this.form.submit();" value="<?php echo $this->_tpl_vars['labels']['ok']; ?>
"/>
<?php endif; ?>
<?php if ($this->_tpl_vars['gui']->testplanRole != null): ?>
<br /><?php echo $this->_tpl_vars['labels']['testplan_role']; ?>
<?php echo ((is_array($_tmp=$this->_tpl_vars['gui']->testplanRole)) ? $this->_run_mod_handler('escape', true, $_tmp) : smarty_modifier_escape($_tmp)); ?>
<?php endif; ?>
<?php else: ?>
<?php if ($this->_tpl_vars['gui']->num_active_tplans > 0): ?><?php echo $this->_tpl_vars['labels']['msg_no_rights_for_tp']; ?>
<?php endif; ?>
<?php endif; ?>
</form>
</div>
<?php endif; ?>
<br />
<div id='menu_right_block_1'></div><br />
<div id='menu_right_block_2'></div><br />
<div id="menu_right_block_3"></div><br />
<div id="menu_left_block_1"></div><br />
<div id="menu_left_block_2"></div><br />
<div id="menu_left_block_3"></div><br />
<div id="menu_left_block_3"></div><br />
<div id="menu_left_block_4"></div><br />
<div id="menu_left_block_5"></div><br />
<?php if ($this->_tpl_vars['display_right_block_1']): ?>
<div id='test_plan_mgmt_topics'>
<?php if ($this->_tpl_vars['gui']->grants['mgt_testplan_create'] == 'yes'): ?>
<img src="<?php echo @TL_ITEM_BULLET_IMG; ?>
" />
<a href="lib/plan/planView.php"><?php echo $this->_tpl_vars['labels']['href_plan_management']; ?>
</a>
<?php endif; ?>
<?php if ($this->_tpl_vars['gui']->grants['testplan_create_build'] == 'yes' && $this->_tpl_vars['gui']->countPlans > 0): ?>
<br />
<img src="<?php echo @TL_ITEM_BULLET_IMG; ?>
" />
<a href="lib/plan/buildView.php"><?php echo $this->_tpl_vars['labels']['href_build_new']; ?>
</a>
<?php endif; ?>
<?php if ($this->_tpl_vars['gui']->grants['testplan_user_role_assignment'] == 'yes' && $this->_tpl_vars['gui']->countPlans > 0): ?>
<br />
<img src="<?php echo @TL_ITEM_BULLET_IMG; ?>
" />
<a href="lib/usermanagement/usersAssign.php?featureType=testplan&featureID=<?php echo $this->_tpl_vars['gui']->testplanID; ?>
"><?php echo $this->_tpl_vars['labels']['href_assign_user_roles']; ?>
</a>
<?php endif; ?>
<?php if ($this->_tpl_vars['gui']->grants['testplan_planning'] == 'yes' && $this->_tpl_vars['gui']->countPlans > 0): ?>
<br />
<img src="<?php echo @TL_ITEM_BULLET_IMG; ?>
" />
<a href="lib/plan/planMilestonesView.php"><?php echo $this->_tpl_vars['labels']['href_plan_mstones']; ?>
</a>
<?php endif; ?>
</div>
<?php endif; ?>
<?php if ($this->_tpl_vars['display_right_block_2']): ?>
<div id='test_execution_topics'>
<?php if ($this->_tpl_vars['gui']->grants['testplan_execute'] == 'yes'): ?>
<img src="<?php echo @TL_ITEM_BULLET_IMG; ?>
" />
<a href="<?php echo $this->_tpl_vars['gui']->launcher; ?>
?feature=executeTest"><?php echo $this->_tpl_vars['labels']['href_execute_test']; ?>
</a>
<?php endif; ?>
<?php if ($this->_tpl_vars['gui']->grants['testplan_metrics'] == 'yes'): ?>
<br />
<img src="<?php echo @TL_ITEM_BULLET_IMG; ?>
" />
<a href="<?php echo $this->_tpl_vars['gui']->launcher; ?>
?feature=showMetrics"><?php echo $this->_tpl_vars['labels']['href_rep_and_metrics']; ?>
</a>
<?php endif; ?>
<br />
<img src="<?php echo @TL_ITEM_BULLET_IMG; ?>
" />
<a href="<?php echo $this->_tpl_vars['gui']->url['metrics_dashboard']; ?>
"><?php echo $this->_tpl_vars['labels']['href_metrics_dashboard']; ?>
</a>
<br />
<img src="<?php echo @TL_ITEM_BULLET_IMG; ?>
" />
<a href="<?php echo $this->_tpl_vars['gui']->url['testcase_assignments']; ?>
"><?php echo $this->_tpl_vars['labels']['href_my_testcase_assignments']; ?>
</a>
</div>
<?php endif; ?>
<?php if ($this->_tpl_vars['display_right_block_3']): ?>
<div id='testplan_contents_topics'>
<img src="<?php echo @TL_ITEM_BULLET_IMG; ?>
" />
<a href="lib/platforms/platformsAssign.php?tplan_id=<?php echo $this->_tpl_vars['gui']->testplanID; ?>
"><?php echo $this->_tpl_vars['labels']['href_platform_assign']; ?>
</a>
<br />
<img src="<?php echo @TL_ITEM_BULLET_IMG; ?>
" />
<a href="<?php echo $this->_tpl_vars['gui']->launcher; ?>
?feature=planAddTC"><?php echo $this->_tpl_vars['labels']['href_add_remove_test_cases']; ?>
</a>
<br />
<img src="<?php echo @TL_ITEM_BULLET_IMG; ?>
" />
<a href="<?php echo $this->_tpl_vars['gui']->launcher; ?>
?feature=planUpdateTC"><?php echo $this->_tpl_vars['labels']['href_update_tplan']; ?>
</a>
<br />
<img src="<?php echo @TL_ITEM_BULLET_IMG; ?>
" />
<a href="<?php echo $this->_tpl_vars['gui']->launcher; ?>
?feature=newest_tcversions"><?php echo $this->_tpl_vars['labels']['href_newest_tcversions']; ?>
</a>
<br />
<img src="<?php echo @TL_ITEM_BULLET_IMG; ?>
" />
<a href="<?php echo $this->_tpl_vars['gui']->launcher; ?>
?feature=tc_exec_assignment"><?php echo $this->_tpl_vars['labels']['href_tc_exec_assignment']; ?>
</a>
<br />
<?php if ($this->_tpl_vars['session'] ['testprojectOptions']->testPriorityEnabled): ?>
<img src="<?php echo @TL_ITEM_BULLET_IMG; ?>
" />
<a href="<?php echo $this->_tpl_vars['gui']->launcher; ?>
?feature=test_urgency"><?php echo $this->_tpl_vars['labels']['href_plan_assign_urgency']; ?>
</a>
<br />
<?php endif; ?>
</div>
<?php endif; ?>
</div>
| viglesiasce/tl_RC1 | gui/templates_c/%%F5^F50^F501ED3C%%mainPageRight.tpl.php | PHP | gpl-2.0 | 14,284 |
# aderlin.SJ
ejemplo de programación en java - Usando Herencia - con conexión a Base de Datos MariaDB
instrucciones de instalacion ..
iuwnkjwnvksnvkjaner
e
v
b
rt
b
eab
str
| aderlinCorp/aderlin.SJ | README.md | Markdown | gpl-2.0 | 177 |
<!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" xml:lang="en"
lang="en" dir="ltr">
<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><link rel="stylesheet" href="../codebase/default.css" type="text/css" media="screen" title="no title" charset="utf-8"><title>
dhtmlxtoolbar:api_method_dhtmlxtoolbarobject_foreachitem [DHX documentation]
</title></head>
<body>
<div class="dokuwiki">
<div class="stylehead">
<div class="header">
<a class="logo" href="http://dhtmlx.com" title="DHTMLX Home Page"></a>
<span class="tittle-dhtmlx">DHTMLX Docs & Samples Explorer</span>
<div class="search-field">
<form action="/dhtmlx/docs/doku.php" accept-charset="utf-8" id="dw__search"><div class="no"><input type="hidden" name="do" value="search" /><input type="text" id="qsearch__in" accesskey="f" name="id" title="Search" /><button type="submit"></button><div id="qsearch__out" class="ajax_qsearch JSpopup"></div></div></form> </div>
<div class="buttons">
<a class="doc"></a>
<a title="DHTMLX Samples homepage" href="../samples.html" class="sample"/></a>
</div>
<!-- <div class="pagename">
[[<a href="#" title="Backlinks">dhtmlxtoolbar:api_method_dhtmlxtoolbarobject_foreachitem</a>]]
</div>
<div class="logo">
<a href="/dhtmlx/docs/doku.php" name="dokuwiki__top" id="dokuwiki__top" accesskey="h" title="[H]">DHX documentation</a> </div>
<div class="clearer"></div>-->
</div>
<!-- <div class="bar" id="bar__top">
<div class="bar-left" id="bar__topleft">
<form class="button btn_edit" method="post" action="/dhtmlx/docs/doku.php"><div class="no"><input type="hidden" name="do" value="edit" /><input type="hidden" name="rev" value="" /><input type="hidden" name="id" value="dhtmlxtoolbar:api_method_dhtmlxtoolbarobject_foreachitem" /><input type="submit" value="Edit this page" class="button" accesskey="e" title="Edit this page [E]" /></div></form> <form class="button btn_revs" method="get" action="/dhtmlx/docs/doku.php"><div class="no"><input type="hidden" name="do" value="revisions" /><input type="hidden" name="id" value="dhtmlxtoolbar:api_method_dhtmlxtoolbarobject_foreachitem" /><input type="submit" value="Old revisions" class="button" accesskey="o" title="Old revisions [O]" /></div></form> </div>
<div class="bar-right" id="bar__topright">
<form class="button btn_recent" method="get" action="/dhtmlx/docs/doku.php"><div class="no"><input type="hidden" name="do" value="recent" /><input type="hidden" name="id" value="dhtmlxtoolbar:api_method_dhtmlxtoolbarobject_foreachitem" /><input type="submit" value="Recent changes" class="button" accesskey="r" title="Recent changes [R]" /></div></form> <form action="/dhtmlx/docs/doku.php" accept-charset="utf-8" id="dw__search"><div class="no"><input type="hidden" name="do" value="search" /><input type="text" id="qsearch__in" accesskey="f" name="id" title="Search" /><button type="submit"></button><div id="qsearch__out" class="ajax_qsearch JSpopup"></div></div></form>
</div>
<div class="clearer"></div>
</div> -->
<!-- <div class="breadcrumbs">
<span class="bchead">Trace:</span> <span class="bcsep">»</span> <span class="curid"><a href="/dhtmlx/docs/doku.php?id=dhtmlxtoolbar:api_method_dhtmlxtoolbarobject_foreachitem" class="breadcrumbs" title="dhtmlxtoolbar:api_method_dhtmlxtoolbarobject_foreachitem">api_method_dhtmlxtoolbarobject_foreachitem</a></span> </div>
-->
</div>
<div class="page">
<!-- wikipage start -->
<p>
<div class='backlinks'><div class='backlink last_backlink'><img src="icons___file.gif" class="media" alt="" /><a href="../index.html" class="wikilink1" title="start">Index</a></div><div class='arrow'></div><div class='backlink last_backlink'><img src="icons___toolbar.gif" class="media" alt="" /><a href=index.html class="wikilink1" title="dhtmlxtoolbar:toc">dhtmlxtoolbar</a></div><div class='arrow'></div><div class='backlink'><a href="dhtmlxtoolbar___api_toc_alpha.html" class="wikilink1" title="dhtmlxtoolbar:api_toc_alpha">API Methods</a></div></div>
</p>
<h3><a name="foreachitem_handler" id="foreachitem_handler">forEachItem(handler)</a></h3>
<div class="level3">
<p>
<em>Required library edition:</em> <img src="common___any_ed.gif" class="media" title="This method works with any edition of DHTMLX library" alt="This method works with any edition of DHTMLX library" /><br/>
<em>Required library file: dhtmlxtoolbar.js</em>
</p>
<p>
iterator, calls user handler for each item
</p>
<ul>
<li class="level1"><div class="li"> handler - user function, will take item id as an argument</div>
</li>
</ul>
<pre class="code javascript"> toolbar.<span class="me1">forEachItem</span><span class="br0">(</span><span class="kw2">function</span><span class="br0">(</span>itemId<span class="br0">)</span><span class="br0">{</span>
<span class="co1">// code here</span>
<span class="br0">}</span><span class="br0">)</span>;
<span class="co1">// or</span>
<span class="kw2">function</span> doWithItem<span class="br0">(</span>itemId<span class="br0">)</span><span class="br0">{</span>
<span class="co1">// code here</span>
<span class="br0">}</span>
toolbar.<span class="me1">forEachItem</span><span class="br0">(</span>doWithItem<span class="br0">)</span>;</pre>
</div>
<div class="secedit"><form class="button btn_secedit" method="post" action="/dhtmlx/docs/doku.php"><div class="no"><input type="hidden" name="do" value="edit" /><input type="hidden" name="lines" value="82-" /><input type="hidden" name="rev" value="1335526054" /><input type="hidden" name="id" value="dhtmlxtoolbar:api_method_dhtmlxtoolbarobject_foreachitem" /><input type="submit" value="Edit" class="button" title="forEachItem(handler)" /></div></form></div>
<!-- wikipage stop -->
</div>
<div class="clearer"> </div>
<div class="stylefoot">
<div class="meta">
<div class="user">
</div>
<!-- <div class="doc">
dhtmlxtoolbar/api_method_dhtmlxtoolbarobject_foreachitem.txt · Last modified: 2012/04/27 15:27 (external edit) </div>
</div>-->
<!--<div class="bar" id="bar__bottom">-->
<!--<div class="bar-left" id="bar__bottomleft">-->
<!--<form class="button btn_edit" method="post" action="/dhtmlx/docs/doku.php"><div class="no"><input type="hidden" name="do" value="edit" /><input type="hidden" name="rev" value="" /><input type="hidden" name="id" value="dhtmlxtoolbar:api_method_dhtmlxtoolbarobject_foreachitem" /><input type="submit" value="Edit this page" class="button" accesskey="e" title="Edit this page [E]" /></div></form>-->
<!--<form class="button btn_revs" method="get" action="/dhtmlx/docs/doku.php"><div class="no"><input type="hidden" name="do" value="revisions" /><input type="hidden" name="id" value="dhtmlxtoolbar:api_method_dhtmlxtoolbarobject_foreachitem" /><input type="submit" value="Old revisions" class="button" accesskey="o" title="Old revisions [O]" /></div></form>-->
<!--</div>-->
<!--<div class="bar-right" id="bar__bottomright">-->
<!---->
<!---->
<!---->
<!---->
<!---->
<!--<form class="button btn_index" method="get" action="/dhtmlx/docs/doku.php"><div class="no"><input type="hidden" name="do" value="index" /><input type="hidden" name="id" value="dhtmlxtoolbar:api_method_dhtmlxtoolbarobject_foreachitem" /><input type="submit" value="Index" class="button" accesskey="x" title="Index [X]" /></div></form>-->
<!--<a class="nolink" href="#dokuwiki__top"><input type="button" class="button" value="Back to top" onclick="window.scrollTo(0, 0)" title="Back to top" /></a> -->
<!--</div>-->
<!--<div class="clearer"></div>-->
<!--</div>-->
</div>
</div>
<div class="footerinc">
</div>
<div class="no"><img src="/dhtmlx/docs/lib/exe/indexer.php?id=dhtmlxtoolbar%3Aapi_method_dhtmlxtoolbarobject_foreachitem&1345730726" width="1" height="1" alt="" /></div>
<div class="footer">
<div class="footer-logo"></div>
<div class="copyright">Copyright © 1998-2011 DHTMLX LTD.<br />All rights reserved.</div>
<form class="button btn_edit" method="post" action="/dhtmlx/docs/doku.php"><div class="no"><input type="hidden" name="do" value="edit" /><input type="hidden" name="rev" value="" /><input type="hidden" name="id" value="dhtmlxtoolbar:api_method_dhtmlxtoolbarobject_foreachitem" /><input type="submit" value="Edit this page" class="button" accesskey="e" title="Edit this page [E]" /></div></form> </div>
</body>
</html>
| regadou/waw | dhtmlx/docsExplorer/dhtmlxtoolbar/dhtmlxtoolbar___api_method_dhtmlxtoolbarobject_foreachitem.html | HTML | gpl-2.0 | 9,041 |
/*
* This source file is part of the ZipArc project source distribution and
* is Copyrighted 2000 - 2006 by Tadeusz Dracz (http://www.artpol-software.com/)
*
* This code may be used in compiled form in any way you desire PROVIDING
* it is not sold for profit as a stand-alone application.
*
* This file may be redistributed unmodified by any means providing it is
* not sold for profit without the authors written consent, and
* providing that this notice and the authors name and all copyright
* notices remains intact.
*
* This file is provided 'as is' with no expressed or implied warranty.
* The author accepts no liability if it causes any damage to your computer.
*
*****************************************************/
#if !defined(AFX_DLGOPTAPPEAR_H__0ABD7885_3449_4D2B_B848_EB0B80D8FBA3__INCLUDED_)
#define AFX_DLGOPTAPPEAR_H__0ABD7885_3449_4D2B_B848_EB0B80D8FBA3__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "SAPrefsSubDlg.h"
class CDlgOptAppear : public CSAPrefsSubDlg
{
// Construction
public:
COptions* m_pOptions;
CDlgOptAppear(CWnd* pParent = NULL); // standard constructor
// Dialog Data
//{{AFX_DATA(CDlgOptAppear)
enum { IDD = IDD_OPTAPPEAR };
//}}AFX_DATA
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CDlgOptAppear)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
// Generated message map functions
//{{AFX_MSG(CDlgOptAppear)
// NOTE: the ClassWizard will add member functions here
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_DLGOPTAPPEAR_H__0ABD7885_3449_4D2B_B848_EB0B80D8FBA3__INCLUDED_)
| RandallFlagg/kgbarchiver | KGB Archiver 2/ziparchive/ZipArc/DlgOptAppear.h | C | gpl-2.0 | 1,830 |
/*
* Copyright (c) 2012-2013, The Linux Foundation. All rights reserved.
*
* Previously licensed under the ISC license by Qualcomm Atheros, Inc.
*
*
* Permission to use, copy, modify, and/or distribute this software for
* any purpose with or without fee is hereby granted, provided that the
* above copyright notice and this permission notice appear in all
* copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
* WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
* AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
* PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
* TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
/*
* Copyright (c) 2012, The Linux Foundation. All rights reserved.
*
* Previously licensed under the ISC license by Qualcomm Atheros, Inc.
*
*
* Permission to use, copy, modify, and/or distribute this software for
* any purpose with or without fee is hereby granted, provided that the
* above copyright notice and this permission notice appear in all
* copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
* WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
* AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
* PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
* TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
/**========================================================================
\file wlan_hdd_hostapd.c
\brief WLAN Host Device Driver implementation
Copyright 2008 (c) Qualcomm, Incorporated. All Rights Reserved.
Qualcomm Confidential and Proprietary.
========================================================================*/
/**=========================================================================
EDIT HISTORY FOR FILE
This section contains comments describing changes made to the module.
Notice that changes are listed in reverse chronological order.
$Header:$ $DateTime: $ $Author: $
when who what, where, why
-------- --- --------------------------------------------------------
04/5/09 Shailender Created module.
06/03/10 js - Added support to hostapd driven deauth/disassoc/mic failure
==========================================================================*/
/*--------------------------------------------------------------------------
Include Files
------------------------------------------------------------------------*/
#include <linux/version.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/wireless.h>
#include <linux/semaphore.h>
#include <vos_api.h>
#include <vos_sched.h>
#include <linux/etherdevice.h>
#include <wlan_hdd_includes.h>
#include <qc_sap_ioctl.h>
#include <wlan_hdd_hostapd.h>
#include <sapApi.h>
#include <sapInternal.h>
#include <wlan_qct_tl.h>
#include <wlan_hdd_softap_tx_rx.h>
#include <wlan_hdd_main.h>
#include <linux/netdevice.h>
#include <linux/mmc/sdio_func.h>
#include "wlan_nlink_common.h"
#include "wlan_btc_svc.h"
#include <bap_hdd_main.h>
#include "wlan_hdd_p2p.h"
#define IS_UP(_dev) \
(((_dev)->flags & (IFF_RUNNING|IFF_UP)) == (IFF_RUNNING|IFF_UP))
#define IS_UP_AUTO(_ic) \
(IS_UP((_ic)->ic_dev) && (_ic)->ic_roaming == IEEE80211_ROAMING_AUTO)
#define WE_WLAN_VERSION 1
#define WE_GET_STA_INFO_SIZE 30
/* WEXT limition: MAX allowed buf len for any *
* IW_PRIV_TYPE_CHAR is 2Kbytes *
*/
#define WE_SAP_MAX_STA_INFO 0x7FF
#define SAP_24GHZ_CH_COUNT (14)
/*---------------------------------------------------------------------------
* Function definitions
*-------------------------------------------------------------------------*/
/**---------------------------------------------------------------------------
\brief hdd_hostapd_open() - HDD Open function for hostapd interface
This is called in response to ifconfig up
\param - dev Pointer to net_device structure
\return - 0 for success non-zero for failure
--------------------------------------------------------------------------*/
int hdd_hostapd_open (struct net_device *dev)
{
ENTER();
//Turn ON carrier state
netif_carrier_on(dev);
//Enable all Tx queues
netif_tx_start_all_queues(dev);
EXIT();
return 0;
}
/**---------------------------------------------------------------------------
\brief hdd_hostapd_stop() - HDD stop function for hostapd interface
This is called in response to ifconfig down
\param - dev Pointer to net_device structure
\return - 0 for success non-zero for failure
--------------------------------------------------------------------------*/
int hdd_hostapd_stop (struct net_device *dev)
{
ENTER();
//Stop all tx queues
netif_tx_disable(dev);
//Turn OFF carrier state
netif_carrier_off(dev);
EXIT();
return 0;
}
/**---------------------------------------------------------------------------
\brief hdd_hostapd_uninit() - HDD uninit function
This is called during the netdev unregister to uninitialize all data
associated with the device
\param - dev Pointer to net_device structure
\return - void
--------------------------------------------------------------------------*/
static void hdd_hostapd_uninit (struct net_device *dev)
{
hdd_adapter_t *pHostapdAdapter = netdev_priv(dev);
ENTER();
if (pHostapdAdapter && pHostapdAdapter->pHddCtx)
{
hdd_deinit_adapter(pHostapdAdapter->pHddCtx, pHostapdAdapter);
/* after uninit our adapter structure will no longer be valid */
pHostapdAdapter->dev = NULL;
}
EXIT();
}
/**============================================================================
@brief hdd_hostapd_hard_start_xmit() - Function registered with the Linux OS for
transmitting packets. There are 2 versions of this function. One that uses
locked queue and other that uses lockless queues. Both have been retained to
do some performance testing
@param skb : [in] pointer to OS packet (sk_buff)
@param dev : [in] pointer to Libra network device
@return : NET_XMIT_DROP if packets are dropped
: NET_XMIT_SUCCESS if packet is enqueued succesfully
===========================================================================*/
int hdd_hostapd_hard_start_xmit(struct sk_buff *skb, struct net_device *dev)
{
return 0;
}
int hdd_hostapd_change_mtu(struct net_device *dev, int new_mtu)
{
return 0;
}
int hdd_hostapd_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd)
{
hdd_adapter_t *pAdapter = WLAN_HDD_GET_PRIV_PTR(dev);
hdd_priv_data_t priv_data;
tANI_U8 *command = NULL;
int ret = 0;
if (NULL == pAdapter)
{
VOS_TRACE( VOS_MODULE_ID_HDD, VOS_TRACE_LEVEL_FATAL,
"%s: HDD adapter context is Null", __func__);
ret = -ENODEV;
goto exit;
}
if ((!ifr) || (!ifr->ifr_data))
{
ret = -EINVAL;
goto exit;
}
if (copy_from_user(&priv_data, ifr->ifr_data, sizeof(hdd_priv_data_t)))
{
ret = -EFAULT;
goto exit;
}
if (priv_data.total_len <= 0 ||
priv_data.total_len > HOSTAPD_IOCTL_COMMAND_STRLEN_MAX)
{
/* below we allocate one more byte for command buffer.
* To avoid addition overflow total_len should be
* smaller than INT_MAX. */
VOS_TRACE( VOS_MODULE_ID_HDD, VOS_TRACE_LEVEL_FATAL,
"%s: integer out of range\n", __func__);
ret = -EFAULT;
goto exit;
}
command = kmalloc((priv_data.total_len + 1), GFP_KERNEL);
if (!command)
{
VOS_TRACE( VOS_MODULE_ID_HDD, VOS_TRACE_LEVEL_FATAL,
"%s: failed to allocate memory\n", __func__);
ret = -ENOMEM;
goto exit;
}
if (copy_from_user(command, priv_data.buf, priv_data.total_len))
{
ret = -EFAULT;
goto exit;
}
command[priv_data.total_len] = '\0';
if ((SIOCDEVPRIVATE + 1) == cmd)
{
VOS_TRACE( VOS_MODULE_ID_HDD, VOS_TRACE_LEVEL_INFO,
"***HOSTAPD*** : Received %s cmd from Wi-Fi GUI***", command);
if(strncmp(command, "P2P_SET_NOA", 11) == 0 )
{
hdd_setP2pNoa(dev, command);
}
else if( strncmp(command, "P2P_SET_PS", 10) == 0 )
{
hdd_setP2pOpps(dev, command);
}
/*
command should be a string having format
SET_SAP_CHANNEL_LIST <num of channels> <the channels seperated by spaces>
*/
if(strncmp(command, "SET_SAP_CHANNEL_LIST", 20) == 0)
{
VOS_TRACE( VOS_MODULE_ID_HDD, VOS_TRACE_LEVEL_INFO,
" Received Command to Set Preferred Channels for SAP in %s", __func__);
ret = sapSetPreferredChannel(command);
}
}
exit:
if (command)
{
kfree(command);
}
return ret;
}
/**---------------------------------------------------------------------------
\brief hdd_hostapd_set_mac_address() -
This function sets the user specified mac address using
the command ifconfig wlanX hw ether <mac adress>.
\param - dev - Pointer to the net device.
- addr - Pointer to the sockaddr.
\return - 0 for success, non zero for failure
--------------------------------------------------------------------------*/
static int hdd_hostapd_set_mac_address(struct net_device *dev, void *addr)
{
struct sockaddr *psta_mac_addr = addr;
ENTER();
memcpy(dev->dev_addr, psta_mac_addr->sa_data, ETH_ALEN);
EXIT();
return 0;
}
void hdd_hostapd_inactivity_timer_cb(v_PVOID_t usrDataForCallback)
{
struct net_device *dev = (struct net_device *)usrDataForCallback;
v_BYTE_t we_custom_event[64];
union iwreq_data wrqu;
#ifdef DISABLE_CONCURRENCY_AUTOSAVE
VOS_STATUS vos_status;
hdd_adapter_t *pHostapdAdapter;
hdd_ap_ctx_t *pHddApCtx;
#endif /*DISABLE_CONCURRENCY_AUTOSAVE */
/* event_name space-delimiter driver_module_name */
/* Format of the event is "AUTO-SHUT.indication" " " "module_name" */
char * autoShutEvent = "AUTO-SHUT.indication" " " KBUILD_MODNAME;
int event_len = strlen(autoShutEvent) + 1; /* For the NULL at the end */
ENTER();
#ifdef DISABLE_CONCURRENCY_AUTOSAVE
if (vos_concurrent_sessions_running())
{
/*
This timer routine is going to be called only when AP
persona is up.
If there are concurrent sessions running we do not want
to shut down the Bss.Instead we run the timer again so
that if Autosave is enabled next time and other session
was down only then we bring down AP
*/
pHostapdAdapter = netdev_priv(dev);
pHddApCtx = WLAN_HDD_GET_AP_CTX_PTR(pHostapdAdapter);
vos_status = vos_timer_start(
&pHddApCtx->hdd_ap_inactivity_timer,
(WLAN_HDD_GET_CTX(pHostapdAdapter))->cfg_ini->nAPAutoShutOff
* 1000);
if (!VOS_IS_STATUS_SUCCESS(vos_status))
{
hddLog(LOGE, FL("Failed to init AP inactivity timer"));
}
EXIT();
return;
}
#endif /*DISABLE_CONCURRENCY_AUTOSAVE */
memset(&we_custom_event, '\0', sizeof(we_custom_event));
memcpy(&we_custom_event, autoShutEvent, event_len);
memset(&wrqu, 0, sizeof(wrqu));
wrqu.data.length = event_len;
hddLog(LOG1, FL("Shutting down AP interface due to inactivity"));
wireless_send_event(dev, IWEVCUSTOM, &wrqu, (char *)we_custom_event);
EXIT();
}
VOS_STATUS hdd_change_mcc_go_beacon_interval(hdd_adapter_t *pHostapdAdapter)
{
v_CONTEXT_t pVosContext = (WLAN_HDD_GET_CTX(pHostapdAdapter))->pvosContext;
ptSapContext pSapCtx = NULL;
eHalStatus halStatus = eHAL_STATUS_FAILURE;
v_PVOID_t hHal = NULL;
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_INFO_HIGH,
"%s: UPDATE Beacon Params", __func__);
if(VOS_STA_SAP_MODE == vos_get_conparam ( )){
pSapCtx = VOS_GET_SAP_CB(pVosContext);
if ( NULL == pSapCtx )
{
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_ERROR,
"%s: Invalid SAP pointer from pvosGCtx", __func__);
return VOS_STATUS_E_FAULT;
}
hHal = VOS_GET_HAL_CB(pSapCtx->pvosGCtx);
if ( NULL == hHal ){
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_ERROR,
"%s: Invalid HAL pointer from pvosGCtx", __func__);
return VOS_STATUS_E_FAULT;
}
halStatus = sme_ChangeMCCBeaconInterval(hHal, pSapCtx->sessionId);
if(halStatus == eHAL_STATUS_FAILURE ){
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_ERROR,
"%s: Failed to update Beacon Params", __func__);
return VOS_STATUS_E_FAILURE;
}
}
return VOS_STATUS_SUCCESS;
}
void hdd_clear_all_sta(hdd_adapter_t *pHostapdAdapter, v_PVOID_t usrDataForCallback)
{
v_U8_t staId = 0;
struct net_device *dev;
dev = (struct net_device *)usrDataForCallback;
hddLog(LOGE, FL("Clearing all the STA entry....\n"));
for (staId = 0; staId < WLAN_MAX_STA_COUNT; staId++)
{
if ( pHostapdAdapter->aStaInfo[staId].isUsed &&
( staId != (WLAN_HDD_GET_AP_CTX_PTR(pHostapdAdapter))->uBCStaId))
{
//Disconnect all the stations
hdd_softap_sta_disassoc(pHostapdAdapter, &pHostapdAdapter->aStaInfo[staId].macAddrSTA.bytes[0]);
}
}
}
static int hdd_stop_p2p_link(hdd_adapter_t *pHostapdAdapter,v_PVOID_t usrDataForCallback)
{
struct net_device *dev;
VOS_STATUS status = VOS_STATUS_SUCCESS;
dev = (struct net_device *)usrDataForCallback;
ENTER();
if(test_bit(SOFTAP_BSS_STARTED, &pHostapdAdapter->event_flags))
{
if ( VOS_STATUS_SUCCESS == (status = WLANSAP_StopBss((WLAN_HDD_GET_CTX(pHostapdAdapter))->pvosContext) ) )
{
VOS_TRACE(VOS_MODULE_ID_HDD, VOS_TRACE_LEVEL_ERROR, FL("Deleting P2P link!!!!!!"));
}
clear_bit(SOFTAP_BSS_STARTED, &pHostapdAdapter->event_flags);
}
EXIT();
return (status == VOS_STATUS_SUCCESS) ? 0 : -EBUSY;
}
VOS_STATUS hdd_hostapd_SAPEventCB( tpSap_Event pSapEvent, v_PVOID_t usrDataForCallback)
{
hdd_adapter_t *pHostapdAdapter;
hdd_ap_ctx_t *pHddApCtx;
hdd_hostapd_state_t *pHostapdState;
struct net_device *dev;
eSapHddEvent sapEvent;
union iwreq_data wrqu;
v_BYTE_t *we_custom_event_generic = NULL;
int we_event = 0;
int i = 0;
v_U8_t staId;
VOS_STATUS vos_status;
v_BOOL_t bWPSState;
v_BOOL_t bApActive = FALSE;
v_BOOL_t bAuthRequired = TRUE;
tpSap_AssocMacAddr pAssocStasArray = NULL;
char unknownSTAEvent[IW_CUSTOM_MAX+1];
char maxAssocExceededEvent[IW_CUSTOM_MAX+1];
v_BYTE_t we_custom_start_event[64];
char *startBssEvent;
hdd_context_t *pHddCtx;
hdd_scaninfo_t *pScanInfo = NULL;
struct iw_michaelmicfailure msg;
dev = (struct net_device *)usrDataForCallback;
pHostapdAdapter = netdev_priv(dev);
pHostapdState = WLAN_HDD_GET_HOSTAP_STATE_PTR(pHostapdAdapter);
pHddApCtx = WLAN_HDD_GET_AP_CTX_PTR(pHostapdAdapter);
sapEvent = pSapEvent->sapHddEventCode;
memset(&wrqu, '\0', sizeof(wrqu));
pHddCtx = (hdd_context_t*)(pHostapdAdapter->pHddCtx);
switch(sapEvent)
{
case eSAP_START_BSS_EVENT :
hddLog(LOG1, FL("BSS configured status = %s, channel = %lu, bc sta Id = %d\n"),
pSapEvent->sapevt.sapStartBssCompleteEvent.status ? "eSAP_STATUS_FAILURE" : "eSAP_STATUS_SUCCESS",
pSapEvent->sapevt.sapStartBssCompleteEvent.operatingChannel,
pSapEvent->sapevt.sapStartBssCompleteEvent.staId);
pHostapdState->vosStatus = pSapEvent->sapevt.sapStartBssCompleteEvent.status;
vos_status = vos_event_set(&pHostapdState->vosEvent);
if (!VOS_IS_STATUS_SUCCESS(vos_status) || pHostapdState->vosStatus)
{
VOS_TRACE(VOS_MODULE_ID_HDD, VOS_TRACE_LEVEL_ERROR, ("ERROR: startbss event failed!!\n"));
goto stopbss;
}
else
{
pHddApCtx->uBCStaId = pSapEvent->sapevt.sapStartBssCompleteEvent.staId;
//@@@ need wep logic here to set privacy bit
hdd_softap_Register_BC_STA(pHostapdAdapter, pHddApCtx->uPrivacy);
}
if (0 != (WLAN_HDD_GET_CTX(pHostapdAdapter))->cfg_ini->nAPAutoShutOff)
{
// AP Inactivity timer init and start
vos_status = vos_timer_init( &pHddApCtx->hdd_ap_inactivity_timer, VOS_TIMER_TYPE_SW,
hdd_hostapd_inactivity_timer_cb, (v_PVOID_t)dev );
if (!VOS_IS_STATUS_SUCCESS(vos_status))
hddLog(LOGE, FL("Failed to init AP inactivity timer\n"));
vos_status = vos_timer_start( &pHddApCtx->hdd_ap_inactivity_timer, (WLAN_HDD_GET_CTX(pHostapdAdapter))->cfg_ini->nAPAutoShutOff * 1000);
if (!VOS_IS_STATUS_SUCCESS(vos_status))
hddLog(LOGE, FL("Failed to init AP inactivity timer\n"));
}
pHddApCtx->operatingChannel = pSapEvent->sapevt.sapStartBssCompleteEvent.operatingChannel;
pHostapdState->bssState = BSS_START;
// Send current operating channel of SoftAP to BTC-ES
send_btc_nlink_msg(WLAN_BTC_SOFTAP_BSS_START, 0);
//Check if there is any group key pending to set.
if( pHddApCtx->groupKey.keyLength )
{
if( VOS_STATUS_SUCCESS != WLANSAP_SetKeySta(
(WLAN_HDD_GET_CTX(pHostapdAdapter))->pvosContext,
&pHddApCtx->groupKey ) )
{
VOS_TRACE( VOS_MODULE_ID_HDD, VOS_TRACE_LEVEL_ERROR,
"%s: WLANSAP_SetKeySta failed", __func__);
}
pHddApCtx->groupKey.keyLength = 0;
}
else if ( pHddApCtx->wepKey[0].keyLength )
{
int i=0;
for ( i = 0; i < CSR_MAX_NUM_KEY; i++ )
{
if( VOS_STATUS_SUCCESS != WLANSAP_SetKeySta(
(WLAN_HDD_GET_CTX(pHostapdAdapter))->pvosContext,
&pHddApCtx->wepKey[i] ) )
{
VOS_TRACE( VOS_MODULE_ID_HDD, VOS_TRACE_LEVEL_ERROR,
"%s: WLANSAP_SetKeySta failed idx %d", __func__, i);
}
pHddApCtx->wepKey[i].keyLength = 0;
}
}
//Fill the params for sending IWEVCUSTOM Event with SOFTAP.enabled
startBssEvent = "SOFTAP.enabled";
memset(&we_custom_start_event, '\0', sizeof(we_custom_start_event));
memcpy(&we_custom_start_event, startBssEvent, strlen(startBssEvent));
memset(&wrqu, 0, sizeof(wrqu));
wrqu.data.length = strlen(startBssEvent);
we_event = IWEVCUSTOM;
we_custom_event_generic = we_custom_start_event;
hdd_dump_concurrency_info(pHddCtx);
break; //Event will be sent after Switch-Case stmt
case eSAP_STOP_BSS_EVENT:
hddLog(LOG1, FL("BSS stop status = %s\n"),pSapEvent->sapevt.sapStopBssCompleteEvent.status ?
"eSAP_STATUS_FAILURE" : "eSAP_STATUS_SUCCESS");
//Free up Channel List incase if it is set
sapCleanupChannelList();
pHddApCtx->operatingChannel = 0; //Invalidate the channel info.
goto stopbss;
case eSAP_STA_SET_KEY_EVENT:
//TODO: forward the message to hostapd once implementtation is done for now just print
hddLog(LOG1, FL("SET Key: configured status = %s\n"),pSapEvent->sapevt.sapStationSetKeyCompleteEvent.status ?
"eSAP_STATUS_FAILURE" : "eSAP_STATUS_SUCCESS");
return VOS_STATUS_SUCCESS;
case eSAP_STA_DEL_KEY_EVENT:
//TODO: forward the message to hostapd once implementtation is done for now just print
hddLog(LOG1, FL("Event received %s\n"),"eSAP_STA_DEL_KEY_EVENT");
return VOS_STATUS_SUCCESS;
case eSAP_STA_MIC_FAILURE_EVENT:
{
memset(&msg, '\0', sizeof(msg));
msg.src_addr.sa_family = ARPHRD_ETHER;
memcpy(msg.src_addr.sa_data, &pSapEvent->sapevt.sapStationMICFailureEvent.staMac, sizeof(v_MACADDR_t));
hddLog(LOG1, "MIC MAC "MAC_ADDRESS_STR"\n", MAC_ADDR_ARRAY(msg.src_addr.sa_data));
if(pSapEvent->sapevt.sapStationMICFailureEvent.multicast == eSAP_TRUE)
msg.flags = IW_MICFAILURE_GROUP;
else
msg.flags = IW_MICFAILURE_PAIRWISE;
memset(&wrqu, 0, sizeof(wrqu));
wrqu.data.length = sizeof(msg);
we_event = IWEVMICHAELMICFAILURE;
we_custom_event_generic = (v_BYTE_t *)&msg;
}
/* inform mic failure to nl80211 */
cfg80211_michael_mic_failure(dev,
pSapEvent->sapevt.
sapStationMICFailureEvent.staMac.bytes,
((pSapEvent->sapevt.sapStationMICFailureEvent.multicast == eSAP_TRUE) ?
NL80211_KEYTYPE_GROUP :
NL80211_KEYTYPE_PAIRWISE),
pSapEvent->sapevt.sapStationMICFailureEvent.keyId,
pSapEvent->sapevt.sapStationMICFailureEvent.TSC,
GFP_KERNEL);
break;
case eSAP_STA_ASSOC_EVENT:
case eSAP_STA_REASSOC_EVENT:
wrqu.addr.sa_family = ARPHRD_ETHER;
memcpy(wrqu.addr.sa_data, &pSapEvent->sapevt.sapStationAssocReassocCompleteEvent.staMac,
sizeof(v_MACADDR_t));
hddLog(LOG1, " associated "MAC_ADDRESS_STR"\n", MAC_ADDR_ARRAY(wrqu.addr.sa_data));
we_event = IWEVREGISTERED;
WLANSAP_Get_WPS_State((WLAN_HDD_GET_CTX(pHostapdAdapter))->pvosContext, &bWPSState);
if ( (eCSR_ENCRYPT_TYPE_NONE == pHddApCtx->ucEncryptType) ||
( eCSR_ENCRYPT_TYPE_WEP40_STATICKEY == pHddApCtx->ucEncryptType ) ||
( eCSR_ENCRYPT_TYPE_WEP104_STATICKEY == pHddApCtx->ucEncryptType ) )
{
bAuthRequired = FALSE;
}
if (bAuthRequired || bWPSState == eANI_BOOLEAN_TRUE )
{
hdd_softap_RegisterSTA( pHostapdAdapter,
TRUE,
pHddApCtx->uPrivacy,
pSapEvent->sapevt.sapStationAssocReassocCompleteEvent.staId,
0,
0,
(v_MACADDR_t *)wrqu.addr.sa_data,
pSapEvent->sapevt.sapStationAssocReassocCompleteEvent.wmmEnabled);
}
else
{
hdd_softap_RegisterSTA( pHostapdAdapter,
FALSE,
pHddApCtx->uPrivacy,
pSapEvent->sapevt.sapStationAssocReassocCompleteEvent.staId,
0,
0,
(v_MACADDR_t *)wrqu.addr.sa_data,
pSapEvent->sapevt.sapStationAssocReassocCompleteEvent.wmmEnabled);
}
// Stop AP inactivity timer
if (pHddApCtx->hdd_ap_inactivity_timer.state == VOS_TIMER_STATE_RUNNING)
{
vos_status = vos_timer_stop(&pHddApCtx->hdd_ap_inactivity_timer);
if (!VOS_IS_STATUS_SUCCESS(vos_status))
hddLog(LOGE, FL("Failed to start AP inactivity timer\n"));
}
#ifdef WLAN_OPEN_SOURCE
if (wake_lock_active(&pHddCtx->sap_wake_lock))
{
wake_unlock(&pHddCtx->sap_wake_lock);
}
wake_lock_timeout(&pHddCtx->sap_wake_lock, msecs_to_jiffies(HDD_SAP_WAKE_LOCK_DURATION));
#endif
#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,38))
{
struct station_info staInfo;
v_U16_t iesLen = pSapEvent->sapevt.sapStationAssocReassocCompleteEvent.iesLen;
memset(&staInfo, 0, sizeof(staInfo));
if (iesLen <= MAX_ASSOC_IND_IE_LEN )
{
staInfo.assoc_req_ies =
(const u8 *)&pSapEvent->sapevt.sapStationAssocReassocCompleteEvent.ies[0];
staInfo.assoc_req_ies_len = iesLen;
#if (LINUX_VERSION_CODE >= KERNEL_VERSION(3,0,31))
staInfo.filled |= STATION_INFO_ASSOC_REQ_IES;
#endif
cfg80211_new_sta(dev,
(const u8 *)&pSapEvent->sapevt.sapStationAssocReassocCompleteEvent.staMac.bytes[0],
&staInfo, GFP_KERNEL);
}
else
{
hddLog(LOGE, FL(" Assoc Ie length is too long \n"));
}
}
#endif
pScanInfo = &pHddCtx->scan_info;
// Lets do abort scan to ensure smooth authentication for client
if ((pScanInfo != NULL) && pScanInfo->mScanPending)
{
hdd_abort_mac_scan(pHddCtx, eCSR_SCAN_ABORT_DEFAULT);
}
break;
case eSAP_STA_DISASSOC_EVENT:
memcpy(wrqu.addr.sa_data, &pSapEvent->sapevt.sapStationDisassocCompleteEvent.staMac,
sizeof(v_MACADDR_t));
hddLog(LOG1, " disassociated "MAC_ADDRESS_STR"\n", MAC_ADDR_ARRAY(wrqu.addr.sa_data));
if (pSapEvent->sapevt.sapStationDisassocCompleteEvent.reason == eSAP_USR_INITATED_DISASSOC)
hddLog(LOG1," User initiated disassociation");
else
hddLog(LOG1," MAC initiated disassociation");
we_event = IWEVEXPIRED;
vos_status = hdd_softap_GetStaId(pHostapdAdapter, &pSapEvent->sapevt.sapStationDisassocCompleteEvent.staMac, &staId);
if (!VOS_IS_STATUS_SUCCESS(vos_status))
{
VOS_TRACE(VOS_MODULE_ID_HDD, VOS_TRACE_LEVEL_ERROR, FL("ERROR: HDD Failed to find sta id!!"));
return VOS_STATUS_E_FAILURE;
}
hdd_softap_DeregisterSTA(pHostapdAdapter, staId);
if (0 != (WLAN_HDD_GET_CTX(pHostapdAdapter))->cfg_ini->nAPAutoShutOff)
{
spin_lock_bh( &pHostapdAdapter->staInfo_lock );
// Start AP inactivity timer if no stations associated with it
for (i = 0; i < WLAN_MAX_STA_COUNT; i++)
{
if (pHostapdAdapter->aStaInfo[i].isUsed && i != (WLAN_HDD_GET_AP_CTX_PTR(pHostapdAdapter))->uBCStaId)
{
bApActive = TRUE;
break;
}
}
spin_unlock_bh( &pHostapdAdapter->staInfo_lock );
if (bApActive == FALSE)
{
if (pHddApCtx->hdd_ap_inactivity_timer.state == VOS_TIMER_STATE_STOPPED)
{
vos_status = vos_timer_start(&pHddApCtx->hdd_ap_inactivity_timer, (WLAN_HDD_GET_CTX(pHostapdAdapter))->cfg_ini->nAPAutoShutOff * 1000);
if (!VOS_IS_STATUS_SUCCESS(vos_status))
hddLog(LOGE, FL("Failed to init AP inactivity timer\n"));
}
else
VOS_ASSERT(vos_timer_getCurrentState(&pHddApCtx->hdd_ap_inactivity_timer) == VOS_TIMER_STATE_STOPPED);
}
}
#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,38))
cfg80211_del_sta(dev,
(const u8 *)&pSapEvent->sapevt.sapStationDisassocCompleteEvent.staMac.bytes[0],
GFP_KERNEL);
#endif
//Update the beacon Interval if it is P2P GO
hdd_change_mcc_go_beacon_interval(pHostapdAdapter);
break;
case eSAP_WPS_PBC_PROBE_REQ_EVENT:
{
static const char * message ="MLMEWPSPBCPROBEREQ.indication";
union iwreq_data wreq;
down(&pHddApCtx->semWpsPBCOverlapInd);
pHddApCtx->WPSPBCProbeReq.probeReqIELen = pSapEvent->sapevt.sapPBCProbeReqEvent.WPSPBCProbeReq.probeReqIELen;
vos_mem_copy(pHddApCtx->WPSPBCProbeReq.probeReqIE, pSapEvent->sapevt.sapPBCProbeReqEvent.WPSPBCProbeReq.probeReqIE,
pHddApCtx->WPSPBCProbeReq.probeReqIELen);
vos_mem_copy(pHddApCtx->WPSPBCProbeReq.peerMacAddr, pSapEvent->sapevt.sapPBCProbeReqEvent.WPSPBCProbeReq.peerMacAddr, sizeof(v_MACADDR_t));
hddLog(LOG1, "WPS PBC probe req "MAC_ADDRESS_STR"\n", MAC_ADDR_ARRAY(pHddApCtx->WPSPBCProbeReq.peerMacAddr));
memset(&wreq, 0, sizeof(wreq));
wreq.data.length = strlen(message); // This is length of message
wireless_send_event(dev, IWEVCUSTOM, &wreq, (char *)message);
return VOS_STATUS_SUCCESS;
}
case eSAP_ASSOC_STA_CALLBACK_EVENT:
pAssocStasArray = pSapEvent->sapevt.sapAssocStaListEvent.pAssocStas;
if (pSapEvent->sapevt.sapAssocStaListEvent.noOfAssocSta != 0)
{ // List of associated stations
for (i = 0; i < pSapEvent->sapevt.sapAssocStaListEvent.noOfAssocSta; i++)
{
hddLog(LOG1,"Associated Sta Num %d:assocId=%d, staId=%d, staMac="MAC_ADDRESS_STR,
i+1,
pAssocStasArray->assocId,
pAssocStasArray->staId,
MAC_ADDR_ARRAY(pAssocStasArray->staMac.bytes));
pAssocStasArray++;
}
}
vos_mem_free(pSapEvent->sapevt.sapAssocStaListEvent.pAssocStas);// Release caller allocated memory here
pSapEvent->sapevt.sapAssocStaListEvent.pAssocStas = NULL;
return VOS_STATUS_SUCCESS;
case eSAP_INDICATE_MGMT_FRAME:
hdd_indicateMgmtFrame( pHostapdAdapter,
pSapEvent->sapevt.sapManagementFrameInfo.nFrameLength,
pSapEvent->sapevt.sapManagementFrameInfo.pbFrames,
pSapEvent->sapevt.sapManagementFrameInfo.frameType,
pSapEvent->sapevt.sapManagementFrameInfo.rxChan, 0);
return VOS_STATUS_SUCCESS;
case eSAP_REMAIN_CHAN_READY:
hdd_remainChanReadyHandler( pHostapdAdapter );
return VOS_STATUS_SUCCESS;
case eSAP_SEND_ACTION_CNF:
hdd_sendActionCnf( pHostapdAdapter,
( eSAP_STATUS_SUCCESS ==
pSapEvent->sapevt.sapActionCnf.actionSendSuccess ) ?
TRUE : FALSE );
return VOS_STATUS_SUCCESS;
case eSAP_UNKNOWN_STA_JOIN:
snprintf(unknownSTAEvent, IW_CUSTOM_MAX, "JOIN_UNKNOWN_STA-%02x:%02x:%02x:%02x:%02x:%02x",
pSapEvent->sapevt.sapUnknownSTAJoin.macaddr.bytes[0],
pSapEvent->sapevt.sapUnknownSTAJoin.macaddr.bytes[1],
pSapEvent->sapevt.sapUnknownSTAJoin.macaddr.bytes[2],
pSapEvent->sapevt.sapUnknownSTAJoin.macaddr.bytes[3],
pSapEvent->sapevt.sapUnknownSTAJoin.macaddr.bytes[4],
pSapEvent->sapevt.sapUnknownSTAJoin.macaddr.bytes[5]);
we_event = IWEVCUSTOM; /* Discovered a new node (AP mode). */
wrqu.data.pointer = unknownSTAEvent;
wrqu.data.length = strlen(unknownSTAEvent);
we_custom_event_generic = (v_BYTE_t *)unknownSTAEvent;
hddLog(LOG1,"%s\n", unknownSTAEvent);
break;
case eSAP_MAX_ASSOC_EXCEEDED:
snprintf(maxAssocExceededEvent, IW_CUSTOM_MAX, "Peer %02x:%02x:%02x:%02x:%02x:%02x denied"
" assoc due to Maximum Mobile Hotspot connections reached. Please disconnect"
" one or more devices to enable the new device connection",
pSapEvent->sapevt.sapMaxAssocExceeded.macaddr.bytes[0],
pSapEvent->sapevt.sapMaxAssocExceeded.macaddr.bytes[1],
pSapEvent->sapevt.sapMaxAssocExceeded.macaddr.bytes[2],
pSapEvent->sapevt.sapMaxAssocExceeded.macaddr.bytes[3],
pSapEvent->sapevt.sapMaxAssocExceeded.macaddr.bytes[4],
pSapEvent->sapevt.sapMaxAssocExceeded.macaddr.bytes[5]);
we_event = IWEVCUSTOM; /* Discovered a new node (AP mode). */
wrqu.data.pointer = maxAssocExceededEvent;
wrqu.data.length = strlen(maxAssocExceededEvent);
we_custom_event_generic = (v_BYTE_t *)maxAssocExceededEvent;
hddLog(LOG1,"%s\n", maxAssocExceededEvent);
break;
case eSAP_STA_ASSOC_IND:
return VOS_STATUS_SUCCESS;
case eSAP_DISCONNECT_ALL_P2P_CLIENT:
hddLog(LOG1, FL(" Disconnecting all the P2P Clients....\n"));
hdd_clear_all_sta(pHostapdAdapter, usrDataForCallback);
return VOS_STATUS_SUCCESS;
case eSAP_MAC_TRIG_STOP_BSS_EVENT :
hdd_stop_p2p_link(pHostapdAdapter, usrDataForCallback);
return VOS_STATUS_SUCCESS;
default:
hddLog(LOG1,"SAP message is not handled\n");
goto stopbss;
return VOS_STATUS_SUCCESS;
}
wireless_send_event(dev, we_event, &wrqu, (char *)we_custom_event_generic);
return VOS_STATUS_SUCCESS;
stopbss :
{
v_BYTE_t we_custom_event[64];
char *stopBssEvent = "STOP-BSS.response";//17
int event_len = strlen(stopBssEvent);
hddLog(LOG1, FL("BSS stop status = %s"),
pSapEvent->sapevt.sapStopBssCompleteEvent.status ?
"eSAP_STATUS_FAILURE" : "eSAP_STATUS_SUCCESS");
/* Change the BSS state now since, as we are shutting things down,
* we don't want interfaces to become re-enabled */
pHostapdState->bssState = BSS_STOP;
if (0 != (WLAN_HDD_GET_CTX(pHostapdAdapter))->cfg_ini->nAPAutoShutOff)
{
if (VOS_TIMER_STATE_RUNNING == pHddApCtx->hdd_ap_inactivity_timer.state)
{
vos_status = vos_timer_stop(&pHddApCtx->hdd_ap_inactivity_timer);
if (!VOS_IS_STATUS_SUCCESS(vos_status))
hddLog(LOGE, FL("Failed to stop AP inactivity timer"));
}
vos_status = vos_timer_destroy(&pHddApCtx->hdd_ap_inactivity_timer);
if (!VOS_IS_STATUS_SUCCESS(vos_status))
hddLog(LOGE, FL("Failed to Destroy AP inactivity timer"));
}
/* Stop the pkts from n/w stack as we are going to free all of
* the TX WMM queues for all STAID's */
hdd_hostapd_stop(dev);
/* reclaim all resources allocated to the BSS */
hdd_softap_stop_bss(pHostapdAdapter);
/* once the event is set, structure dev/pHostapdAdapter should
* not be touched since they are now subject to being deleted
* by another thread */
if (eSAP_STOP_BSS_EVENT == sapEvent)
vos_event_set(&pHostapdState->vosEvent);
/* notify userspace that the BSS has stopped */
memset(&we_custom_event, '\0', sizeof(we_custom_event));
memcpy(&we_custom_event, stopBssEvent, event_len);
memset(&wrqu, 0, sizeof(wrqu));
wrqu.data.length = event_len;
we_event = IWEVCUSTOM;
we_custom_event_generic = we_custom_event;
wireless_send_event(dev, we_event, &wrqu, (char *)we_custom_event_generic);
hdd_dump_concurrency_info(pHddCtx);
}
return VOS_STATUS_SUCCESS;
}
int hdd_softap_unpackIE(
tHalHandle halHandle,
eCsrEncryptionType *pEncryptType,
eCsrEncryptionType *mcEncryptType,
eCsrAuthType *pAuthType,
u_int16_t gen_ie_len,
u_int8_t *gen_ie )
{
tDot11fIERSN dot11RSNIE;
tDot11fIEWPA dot11WPAIE;
tANI_U8 *pRsnIe;
tANI_U16 RSNIeLen;
if (NULL == halHandle)
{
hddLog(LOGE, FL("Error haHandle returned NULL\n"));
return -EINVAL;
}
// Validity checks
if ((gen_ie_len < VOS_MIN(DOT11F_IE_RSN_MIN_LEN, DOT11F_IE_WPA_MIN_LEN)) ||
(gen_ie_len > VOS_MAX(DOT11F_IE_RSN_MAX_LEN, DOT11F_IE_WPA_MAX_LEN)) )
return -EINVAL;
// Type check
if ( gen_ie[0] == DOT11F_EID_RSN)
{
// Validity checks
if ((gen_ie_len < DOT11F_IE_RSN_MIN_LEN ) ||
(gen_ie_len > DOT11F_IE_RSN_MAX_LEN) )
{
return VOS_STATUS_E_FAILURE;
}
// Skip past the EID byte and length byte
pRsnIe = gen_ie + 2;
RSNIeLen = gen_ie_len - 2;
// Unpack the RSN IE
memset(&dot11RSNIE, 0, sizeof(tDot11fIERSN));
dot11fUnpackIeRSN((tpAniSirGlobal) halHandle,
pRsnIe,
RSNIeLen,
&dot11RSNIE);
// Copy out the encryption and authentication types
hddLog(LOG1, FL("%s: pairwise cipher suite count: %d\n"),
__func__, dot11RSNIE.pwise_cipher_suite_count );
hddLog(LOG1, FL("%s: authentication suite count: %d\n"),
__func__, dot11RSNIE.akm_suite_count);
/*Here we have followed the apple base code,
but probably I suspect we can do something different*/
//dot11RSNIE.akm_suite_count
// Just translate the FIRST one
*pAuthType = hdd_TranslateRSNToCsrAuthType(dot11RSNIE.akm_suites[0]);
//dot11RSNIE.pwise_cipher_suite_count
*pEncryptType = hdd_TranslateRSNToCsrEncryptionType(dot11RSNIE.pwise_cipher_suites[0]);
//dot11RSNIE.gp_cipher_suite_count
*mcEncryptType = hdd_TranslateRSNToCsrEncryptionType(dot11RSNIE.gp_cipher_suite);
// Set the PMKSA ID Cache for this interface
// Calling csrRoamSetPMKIDCache to configure the PMKIDs into the cache
} else
if (gen_ie[0] == DOT11F_EID_WPA)
{
// Validity checks
if ((gen_ie_len < DOT11F_IE_WPA_MIN_LEN ) ||
(gen_ie_len > DOT11F_IE_WPA_MAX_LEN))
{
return VOS_STATUS_E_FAILURE;
}
// Skip past the EID byte and length byte - and four byte WiFi OUI
pRsnIe = gen_ie + 2 + 4;
RSNIeLen = gen_ie_len - (2 + 4);
// Unpack the WPA IE
memset(&dot11WPAIE, 0, sizeof(tDot11fIEWPA));
dot11fUnpackIeWPA((tpAniSirGlobal) halHandle,
pRsnIe,
RSNIeLen,
&dot11WPAIE);
// Copy out the encryption and authentication types
hddLog(LOG1, FL("%s: WPA unicast cipher suite count: %d\n"),
__func__, dot11WPAIE.unicast_cipher_count );
hddLog(LOG1, FL("%s: WPA authentication suite count: %d\n"),
__func__, dot11WPAIE.auth_suite_count);
//dot11WPAIE.auth_suite_count
// Just translate the FIRST one
*pAuthType = hdd_TranslateWPAToCsrAuthType(dot11WPAIE.auth_suites[0]);
//dot11WPAIE.unicast_cipher_count
*pEncryptType = hdd_TranslateWPAToCsrEncryptionType(dot11WPAIE.unicast_ciphers[0]);
//dot11WPAIE.unicast_cipher_count
*mcEncryptType = hdd_TranslateWPAToCsrEncryptionType(dot11WPAIE.multicast_cipher);
}
else
{
hddLog(LOGW, FL("%s: gen_ie[0]: %d\n"), __func__, gen_ie[0]);
return VOS_STATUS_E_FAILURE;
}
return VOS_STATUS_SUCCESS;
}
int
static iw_softap_setparam(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
hdd_adapter_t *pHostapdAdapter = (netdev_priv(dev));
tHalHandle hHal;
int *value = (int *)extra;
int sub_cmd = value[0];
int set_value = value[1];
eHalStatus status;
int ret = 0; /* success */
v_CONTEXT_t pVosContext;
if (!pHostapdAdapter || !pHostapdAdapter->pHddCtx)
{
VOS_TRACE(VOS_MODULE_ID_HDD, VOS_TRACE_LEVEL_ERROR,
"%s: either hostapd Adapter is null or HDD ctx is null",
__func__);
return -1;
}
hHal = WLAN_HDD_GET_HAL_CTX(pHostapdAdapter);
if (!hHal)
{
VOS_TRACE(VOS_MODULE_ID_HDD, VOS_TRACE_LEVEL_ERROR,
"%s: Hal ctx is null", __func__);
return -1;
}
pVosContext = (WLAN_HDD_GET_CTX(pHostapdAdapter))->pvosContext;
if (!pVosContext)
{
VOS_TRACE(VOS_MODULE_ID_HDD, VOS_TRACE_LEVEL_ERROR,
"%s: Vos ctx is null", __func__);
return -1;
}
switch(sub_cmd)
{
case QCSAP_PARAM_CLR_ACL:
if ( VOS_STATUS_SUCCESS != WLANSAP_ClearACL( pVosContext ))
{
ret = -EIO;
}
break;
case QCSAP_PARAM_ACL_MODE:
if ((eSAP_ALLOW_ALL < (eSapMacAddrACL)set_value) ||
(eSAP_ACCEPT_UNLESS_DENIED > (eSapMacAddrACL)set_value))
{
hddLog(LOGE, FL("Invalid ACL Mode value %d"), set_value);
ret = -EINVAL;
}
else
{
WLANSAP_SetMode(pVosContext, set_value);
}
break;
case QCSAP_PARAM_MAX_ASSOC:
if (WNI_CFG_ASSOC_STA_LIMIT_STAMIN > set_value)
{
hddLog(LOGE, FL("Invalid setMaxAssoc value %d"), set_value);
ret = -EINVAL;
}
else
{
if (WNI_CFG_ASSOC_STA_LIMIT_STAMAX < set_value)
{
hddLog(LOGW, FL("setMaxAssoc value %d higher than max allowed %d."
"Setting it to max allowed and continuing"),
set_value, WNI_CFG_ASSOC_STA_LIMIT_STAMAX);
set_value = WNI_CFG_ASSOC_STA_LIMIT_STAMAX;
}
status = ccmCfgSetInt(hHal, WNI_CFG_ASSOC_STA_LIMIT,
set_value, NULL, eANI_BOOLEAN_FALSE);
if ( status != eHAL_STATUS_SUCCESS )
{
hddLog(LOGE, FL("setMaxAssoc failure, status %d"),
status);
ret = -EIO;
}
}
break;
case QCSAP_PARAM_HIDE_SSID:
{
eHalStatus status = eHAL_STATUS_SUCCESS;
status = sme_HideSSID(hHal, pHostapdAdapter->sessionId, set_value);
if(eHAL_STATUS_SUCCESS != status)
{
hddLog(VOS_TRACE_LEVEL_ERROR,
"%s: QCSAP_PARAM_HIDE_SSID failed",
__func__);
return status;
}
break;
}
default:
hddLog(LOGE, FL("Invalid setparam command %d value %d"),
sub_cmd, set_value);
ret = -EINVAL;
break;
}
return ret;
}
int
static iw_softap_getparam(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
hdd_adapter_t *pHostapdAdapter = (netdev_priv(dev));
tHalHandle hHal = WLAN_HDD_GET_HAL_CTX(pHostapdAdapter);
int *value = (int *)extra;
int sub_cmd = value[0];
eHalStatus status;
int ret = 0; /* success */
v_CONTEXT_t pVosContext = (WLAN_HDD_GET_CTX(pHostapdAdapter))->pvosContext;
switch (sub_cmd)
{
case QCSAP_PARAM_MAX_ASSOC:
status = ccmCfgGetInt(hHal, WNI_CFG_ASSOC_STA_LIMIT, (tANI_U32 *)value);
if (eHAL_STATUS_SUCCESS != status)
{
ret = -EIO;
}
break;
case QCSAP_PARAM_CLR_ACL:
if ( VOS_STATUS_SUCCESS != WLANSAP_ClearACL( pVosContext ))
{
ret = -EIO;
}
*value = 0;
break;
case QCSAP_PARAM_MODULE_DOWN_IND:
{
VOS_TRACE(VOS_MODULE_ID_HDD, VOS_TRACE_LEVEL_INFO,
"%s: sending WLAN_MODULE_DOWN_IND", __func__);
send_btc_nlink_msg(WLAN_MODULE_DOWN_IND, 0);
#ifdef WLAN_BTAMP_FEATURE
VOS_TRACE(VOS_MODULE_ID_HDD, VOS_TRACE_LEVEL_INFO,
"%s: Take down AMP PAL", __func__);
BSL_Deinit(vos_get_global_context(VOS_MODULE_ID_HDD, NULL));
#endif
*value = 0;
break;
}
case QCSAP_PARAM_GET_WLAN_DBG:
{
vos_trace_display();
*value = 0;
break;
}
case QCSAP_PARAM_AUTO_CHANNEL:
{
*value = (WLAN_HDD_GET_CTX(pHostapdAdapter))->cfg_ini->apAutoChannelSelection;
break;
}
default:
hddLog(LOGE, FL("Invalid getparam command %d"), sub_cmd);
ret = -EINVAL;
break;
}
return ret;
}
/* Usage:
BLACK_LIST = 0
WHITE_LIST = 1
ADD MAC = 0
REMOVE MAC = 1
mac addr will be accepted as a 6 octet mac address with each octet inputted in hex
for e.g. 00:0a:f5:11:22:33 will be represented as 0x00 0x0a 0xf5 0x11 0x22 0x33
while using this ioctl
Syntax:
iwpriv softap.0 modify_acl
<6 octet mac addr> <list type> <cmd type>
Examples:
eg 1. to add a mac addr 00:0a:f5:89:89:90 to the black list
iwpriv softap.0 modify_acl 0x00 0x0a 0xf5 0x89 0x89 0x90 0 0
eg 2. to delete a mac addr 00:0a:f5:89:89:90 from white list
iwpriv softap.0 modify_acl 0x00 0x0a 0xf5 0x89 0x89 0x90 1 1
*/
int iw_softap_modify_acl(struct net_device *dev, struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
hdd_adapter_t *pHostapdAdapter = (netdev_priv(dev));
v_CONTEXT_t pVosContext = (WLAN_HDD_GET_CTX(pHostapdAdapter))->pvosContext;
v_BYTE_t *value = (v_BYTE_t*)extra;
v_U8_t pPeerStaMac[VOS_MAC_ADDR_SIZE];
int listType, cmd, i;
int ret = 0; /* success */
ENTER();
for (i=0; i<VOS_MAC_ADDR_SIZE; i++)
{
pPeerStaMac[i] = *(value+i);
}
listType = (int)(*(value+i));
i++;
cmd = (int)(*(value+i));
hddLog(LOG1, "%s: SAP Modify ACL arg0 %02x:%02x:%02x:%02x:%02x:%02x arg1 %d arg2 %d\n",
__func__, pPeerStaMac[0], pPeerStaMac[1], pPeerStaMac[2],
pPeerStaMac[3], pPeerStaMac[4], pPeerStaMac[5], listType, cmd);
if (WLANSAP_ModifyACL(pVosContext, pPeerStaMac,(eSapACLType)listType,(eSapACLCmdType)cmd)
!= VOS_STATUS_SUCCESS)
{
hddLog(LOGE, FL("Modify ACL failed\n"));
ret = -EIO;
}
EXIT();
return ret;
}
int
static iw_softap_getchannel(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
hdd_adapter_t *pHostapdAdapter = (netdev_priv(dev));
int *value = (int *)extra;
*value = (WLAN_HDD_GET_AP_CTX_PTR(pHostapdAdapter))->operatingChannel;
return 0;
}
int
static iw_softap_set_max_tx_power(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
hdd_adapter_t *pHostapdAdapter = (netdev_priv(dev));
tHalHandle hHal = WLAN_HDD_GET_HAL_CTX(pHostapdAdapter);
int *value = (int *)extra;
int set_value;
tSirMacAddr bssid = {0xFF,0xFF,0xFF,0xFF,0xFF,0xFF};
tSirMacAddr selfMac = {0xFF,0xFF,0xFF,0xFF,0xFF,0xFF};
if (NULL == value)
return -ENOMEM;
set_value = value[0];
if (eHAL_STATUS_SUCCESS != sme_SetMaxTxPower(hHal, bssid, selfMac, set_value))
{
hddLog(VOS_TRACE_LEVEL_ERROR, "%s: Setting maximum tx power failed",
__func__);
return -EIO;
}
return 0;
}
int
static iw_display_data_path_snapshot(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
/* Function intitiating dumping states of
* HDD(WMM Tx Queues)
* TL State (with Per Client infor)
* DXE Snapshot (Called at the end of TL Snapshot)
*/
hdd_adapter_t *pHostapdAdapter = (netdev_priv(dev));
hddLog(LOGE, "%s: called for SAP",__func__);
hdd_wmm_tx_snapshot(pHostapdAdapter);
WLANTL_TLDebugMessage(VOS_TRUE);
return 0;
}
int
static iw_softap_set_tx_power(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
hdd_adapter_t *pHostapdAdapter = (netdev_priv(dev));
v_CONTEXT_t pVosContext = (WLAN_HDD_GET_CTX(pHostapdAdapter))->pvosContext;
tHalHandle hHal = WLAN_HDD_GET_HAL_CTX(pHostapdAdapter);
int *value = (int *)extra;
int set_value;
ptSapContext pSapCtx = NULL;
if (NULL == value)
return -ENOMEM;
pSapCtx = VOS_GET_SAP_CB(pVosContext);
if (NULL == pSapCtx)
{
VOS_TRACE(VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_ERROR,
"%s: Invalid SAP pointer from pvosGCtx", __func__);
return VOS_STATUS_E_FAULT;
}
set_value = value[0];
if (eHAL_STATUS_SUCCESS != sme_SetTxPower(hHal, pSapCtx->sessionId, set_value))
{
hddLog(VOS_TRACE_LEVEL_ERROR, "%s: Setting tx power failed",
__func__);
return -EIO;
}
return 0;
}
/**---------------------------------------------------------------------------
\brief iw_softap_set_trafficmonitor() -
This function dynamically enable/disable traffic monitor functonality
the command iwpriv wlanX setTrafficMon <value>.
\param - dev - Pointer to the net device.
- addr - Pointer to the sockaddr.
\return - 0 for success, non zero for failure
--------------------------------------------------------------------------*/
static int iw_softap_set_trafficmonitor(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
hdd_adapter_t *pAdapter = WLAN_HDD_GET_PRIV_PTR(dev);
int *isSetTrafficMon = (int *)extra;
hdd_context_t *pHddCtx;
int status;
if (NULL == pAdapter)
{
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_ERROR,
"%s: HDD adapter is Null", __func__);
return -ENODEV;
}
pHddCtx = WLAN_HDD_GET_CTX(pAdapter);
status = wlan_hdd_validate_context(pHddCtx);
if (0 != status)
{
VOS_TRACE( VOS_MODULE_ID_HDD, VOS_TRACE_LEVEL_ERROR,
"%s: HDD context is not valid", __func__);
return status;
}
hddLog(VOS_TRACE_LEVEL_INFO, "%s : ", __func__);
if (NULL == isSetTrafficMon)
{
VOS_TRACE(VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_ERROR,
"%s: Invalid SAP pointer from extra", __func__);
return -ENOMEM;
}
if (TRUE == *isSetTrafficMon)
{
pHddCtx->cfg_ini->enableTrafficMonitor= TRUE;
if (VOS_STATUS_SUCCESS != hdd_start_trafficMonitor(pAdapter))
{
VOS_TRACE( VOS_MODULE_ID_HDD_SOFTAP, VOS_TRACE_LEVEL_ERROR,
"%s: failed to Start Traffic Monitor timer ", __func__ );
return -EIO;
}
}
else if (FALSE == *isSetTrafficMon)
{
pHddCtx->cfg_ini->enableTrafficMonitor= FALSE;
if (VOS_STATUS_SUCCESS != hdd_stop_trafficMonitor(pAdapter))
{
VOS_TRACE( VOS_MODULE_ID_HDD_SOFTAP, VOS_TRACE_LEVEL_ERROR,
"%s: failed to Stop Traffic Monitor timer ", __func__ );
return -EIO;
}
}
return 0;
}
#define IS_BROADCAST_MAC(x) (((x[0] & x[1] & x[2] & x[3] & x[4] & x[5]) == 0xff) ? 1 : 0)
int
static iw_softap_getassoc_stamacaddr(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
hdd_adapter_t *pHostapdAdapter = (netdev_priv(dev));
hdd_station_info_t *pStaInfo = pHostapdAdapter->aStaInfo;
char *buf;
int cnt = 0;
int left;
int ret = 0;
/* maclist_index must be u32 to match userspace */
u32 maclist_index;
/*
* NOTE WELL: this is a "get" ioctl but it uses an even ioctl
* number, and even numbered iocts are supposed to have "set"
* semantics. Hence the wireless extensions support in the kernel
* won't correctly copy the result to userspace, so the ioctl
* handler itself must copy the data. Output format is 32-bit
* record length, followed by 0 or more 6-byte STA MAC addresses.
*
* Further note that due to the incorrect semantics, the "iwpriv"
* userspace application is unable to correctly invoke this API,
* hence it is not registered in the hostapd_private_args. This
* API can only be invoked by directly invoking the ioctl() system
* call.
*/
/* make sure userspace allocated a reasonable buffer size */
if (wrqu->data.length < sizeof(maclist_index)) {
hddLog(LOG1, "%s: invalid userspace buffer", __func__);
return -EINVAL;
}
/* allocate local buffer to build the response */
buf = kmalloc(wrqu->data.length, GFP_KERNEL);
if (!buf) {
hddLog(LOG1, "%s: failed to allocate response buffer", __func__);
return -ENOMEM;
}
/* start indexing beyond where the record count will be written */
maclist_index = sizeof(maclist_index);
left = wrqu->data.length - maclist_index;
spin_lock_bh(&pHostapdAdapter->staInfo_lock);
while ((cnt < WLAN_MAX_STA_COUNT) && (left >= VOS_MAC_ADDR_SIZE)) {
if ((pStaInfo[cnt].isUsed) &&
(!IS_BROADCAST_MAC(pStaInfo[cnt].macAddrSTA.bytes))) {
memcpy(&buf[maclist_index], &(pStaInfo[cnt].macAddrSTA),
VOS_MAC_ADDR_SIZE);
maclist_index += VOS_MAC_ADDR_SIZE;
left -= VOS_MAC_ADDR_SIZE;
}
cnt++;
}
spin_unlock_bh(&pHostapdAdapter->staInfo_lock);
*((u32 *)buf) = maclist_index;
wrqu->data.length = maclist_index;
if (copy_to_user(wrqu->data.pointer, buf, maclist_index)) {
hddLog(LOG1, "%s: failed to copy response to user buffer", __func__);
ret = -EFAULT;
}
kfree(buf);
return ret;
}
/* Usage:
mac addr will be accepted as a 6 octet mac address with each octet inputted in hex
for e.g. 00:0a:f5:11:22:33 will be represented as 0x00 0x0a 0xf5 0x11 0x22 0x33
while using this ioctl
Syntax:
iwpriv softap.0 disassoc_sta <6 octet mac address>
e.g.
disassociate sta with mac addr 00:0a:f5:11:22:33 from softap
iwpriv softap.0 disassoc_sta 0x00 0x0a 0xf5 0x11 0x22 0x33
*/
int
static iw_softap_disassoc_sta(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
hdd_adapter_t *pHostapdAdapter = (netdev_priv(dev));
v_U8_t *peerMacAddr;
ENTER();
if (!capable(CAP_NET_ADMIN)) {
VOS_TRACE(VOS_MODULE_ID_HDD, VOS_TRACE_LEVEL_ERROR,
FL("permission check failed"));
return -EPERM;
}
/* iwpriv tool or framework calls this ioctl with
* data passed in extra (less than 16 octets);
*/
peerMacAddr = (v_U8_t *)(extra);
hddLog(LOG1, "data %02x:%02x:%02x:%02x:%02x:%02x",
peerMacAddr[0], peerMacAddr[1], peerMacAddr[2],
peerMacAddr[3], peerMacAddr[4], peerMacAddr[5]);
hdd_softap_sta_disassoc(pHostapdAdapter, peerMacAddr);
EXIT();
return 0;
}
int
static iw_softap_ap_stats(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
hdd_adapter_t *pHostapdAdapter = (netdev_priv(dev));
WLANTL_TRANSFER_STA_TYPE statBuffer;
char *pstatbuf;
int len = wrqu->data.length;
pstatbuf = wrqu->data.pointer;
memset(&statBuffer, 0, sizeof(statBuffer));
WLANSAP_GetStatistics((WLAN_HDD_GET_CTX(pHostapdAdapter))->pvosContext,
&statBuffer, (v_BOOL_t)wrqu->data.flags);
pstatbuf = kmalloc(wrqu->data.length, GFP_KERNEL);
if(NULL == pstatbuf) {
hddLog(LOG1, "unable to allocate memory");
return -ENOMEM;
}
len = scnprintf(pstatbuf, wrqu->data.length,
"RUF=%d RMF=%d RBF=%d "
"RUB=%d RMB=%d RBB=%d "
"TUF=%d TMF=%d TBF=%d "
"TUB=%d TMB=%d TBB=%d",
(int)statBuffer.rxUCFcnt, (int)statBuffer.rxMCFcnt,
(int)statBuffer.rxBCFcnt, (int)statBuffer.rxUCBcnt,
(int)statBuffer.rxMCBcnt, (int)statBuffer.rxBCBcnt,
(int)statBuffer.txUCFcnt, (int)statBuffer.txMCFcnt,
(int)statBuffer.txBCFcnt, (int)statBuffer.txUCBcnt,
(int)statBuffer.txMCBcnt, (int)statBuffer.txBCBcnt);
if (len > wrqu->data.length ||
copy_to_user((void *)wrqu->data.pointer, (void *)pstatbuf, len))
{
hddLog(LOG1, "%s: failed to copy data to user buffer", __func__);
kfree(pstatbuf);
return -EFAULT;
}
wrqu->data.length -= len;
kfree(pstatbuf);
return 0;
}
int
static iw_softap_commit(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
VOS_STATUS vos_status = VOS_STATUS_SUCCESS;
hdd_adapter_t *pHostapdAdapter = (netdev_priv(dev));
hdd_hostapd_state_t *pHostapdState;
v_CONTEXT_t pVosContext = (WLAN_HDD_GET_CTX(pHostapdAdapter))->pvosContext;
tpWLAN_SAPEventCB pSapEventCallback;
tsap_Config_t *pConfig;
s_CommitConfig_t *pCommitConfig;
struct qc_mac_acl_entry *acl_entry = NULL;
v_SINT_t i = 0, num_mac = 0;
v_U32_t status = 0;
eCsrAuthType RSNAuthType;
eCsrEncryptionType RSNEncryptType;
eCsrEncryptionType mcRSNEncryptType;
pHostapdState = WLAN_HDD_GET_HOSTAP_STATE_PTR(pHostapdAdapter);
pCommitConfig = (s_CommitConfig_t *)extra;
pConfig = kmalloc(sizeof(tsap_Config_t), GFP_KERNEL);
if(NULL == pConfig) {
hddLog(LOG1, "VOS unable to allocate memory\n");
return -ENOMEM;
}
pConfig->beacon_int = pCommitConfig->beacon_int;
pConfig->channel = pCommitConfig->channel;
/*Protection parameter to enable or disable*/
pConfig->protEnabled = (WLAN_HDD_GET_CTX(pHostapdAdapter))->cfg_ini->apProtEnabled;
pConfig->dtim_period = pCommitConfig->dtim_period;
switch(pCommitConfig->hw_mode )
{
case eQC_DOT11_MODE_11A:
pConfig->SapHw_mode = eSAP_DOT11_MODE_11a;
break;
case eQC_DOT11_MODE_11B:
pConfig->SapHw_mode = eSAP_DOT11_MODE_11b;
break;
case eQC_DOT11_MODE_11G:
pConfig->SapHw_mode = eSAP_DOT11_MODE_11g;
break;
case eQC_DOT11_MODE_11N:
pConfig->SapHw_mode = eSAP_DOT11_MODE_11n;
break;
case eQC_DOT11_MODE_11G_ONLY:
pConfig->SapHw_mode = eSAP_DOT11_MODE_11g_ONLY;
break;
case eQC_DOT11_MODE_11N_ONLY:
pConfig->SapHw_mode = eSAP_DOT11_MODE_11n_ONLY;
break;
default:
pConfig->SapHw_mode = eSAP_DOT11_MODE_11n;
break;
}
pConfig->ieee80211d = pCommitConfig->qcsap80211d;
vos_mem_copy(pConfig->countryCode, pCommitConfig->countryCode, 3);
if(pCommitConfig->authType == eQC_AUTH_TYPE_SHARED_KEY)
pConfig->authType = eSAP_SHARED_KEY;
else if(pCommitConfig->authType == eQC_AUTH_TYPE_OPEN_SYSTEM)
pConfig->authType = eSAP_OPEN_SYSTEM;
else
pConfig->authType = eSAP_AUTO_SWITCH;
pConfig->privacy = pCommitConfig->privacy;
(WLAN_HDD_GET_AP_CTX_PTR(pHostapdAdapter))->uPrivacy = pCommitConfig->privacy;
pConfig->wps_state = pCommitConfig->wps_state;
pConfig->fwdWPSPBCProbeReq = 1; // Forward WPS PBC probe request frame up
pConfig->RSNWPAReqIELength = pCommitConfig->RSNWPAReqIELength;
if(pConfig->RSNWPAReqIELength){
pConfig->pRSNWPAReqIE = &pCommitConfig->RSNWPAReqIE[0];
if ((pConfig->pRSNWPAReqIE[0] == DOT11F_EID_RSN) || (pConfig->pRSNWPAReqIE[0] == DOT11F_EID_WPA)){
// The actual processing may eventually be more extensive than this.
// Right now, just consume any PMKIDs that are sent in by the app.
status = hdd_softap_unpackIE(
vos_get_context( VOS_MODULE_ID_PE, pVosContext),
&RSNEncryptType,
&mcRSNEncryptType,
&RSNAuthType,
pConfig->pRSNWPAReqIE[1]+2,
pConfig->pRSNWPAReqIE );
if( VOS_STATUS_SUCCESS == status )
{
// Now copy over all the security attributes you have parsed out
//TODO: Need to handle mixed mode
pConfig->RSNEncryptType = RSNEncryptType; // Use the cipher type in the RSN IE
pConfig->mcRSNEncryptType = mcRSNEncryptType;
hddLog( LOG1, FL("CSR AuthType = %d, EncryptionType = %d mcEncryptionType = %d\n"),
RSNAuthType, RSNEncryptType, mcRSNEncryptType);
}
}
}
else
{
/* If no RSNIE, set encrypt type to NONE*/
pConfig->RSNEncryptType = eCSR_ENCRYPT_TYPE_NONE;
pConfig->mcRSNEncryptType = eCSR_ENCRYPT_TYPE_NONE;
hddLog( LOG1, FL("EncryptionType = %d mcEncryptionType = %d\n"),
pConfig->RSNEncryptType, pConfig->mcRSNEncryptType);
}
if (pConfig->RSNWPAReqIELength > QCSAP_MAX_OPT_IE) {
hddLog(LOGE, FL("RSNWPAReqIELength: %d too large"), pConfig->RSNWPAReqIELength);
kfree(pConfig);
return -EIO;
}
pConfig->SSIDinfo.ssidHidden = pCommitConfig->SSIDinfo.ssidHidden;
pConfig->SSIDinfo.ssid.length = pCommitConfig->SSIDinfo.ssid.length;
vos_mem_copy(pConfig->SSIDinfo.ssid.ssId, pCommitConfig->SSIDinfo.ssid.ssId, pConfig->SSIDinfo.ssid.length);
vos_mem_copy(pConfig->self_macaddr.bytes, pHostapdAdapter->macAddressCurrent.bytes, sizeof(v_MACADDR_t));
pConfig->SapMacaddr_acl = pCommitConfig->qc_macaddr_acl;
// ht_capab is not what the name conveys,this is used for protection bitmap
pConfig->ht_capab = (WLAN_HDD_GET_CTX(pHostapdAdapter))->cfg_ini->apProtection;
if (pCommitConfig->num_accept_mac > MAX_ACL_MAC_ADDRESS)
num_mac = pConfig->num_accept_mac = MAX_ACL_MAC_ADDRESS;
else
num_mac = pConfig->num_accept_mac = pCommitConfig->num_accept_mac;
acl_entry = pCommitConfig->accept_mac;
for (i = 0; i < num_mac; i++)
{
vos_mem_copy(&pConfig->accept_mac[i], acl_entry->addr, sizeof(v_MACADDR_t));
acl_entry++;
}
if (pCommitConfig->num_deny_mac > MAX_ACL_MAC_ADDRESS)
num_mac = pConfig->num_deny_mac = MAX_ACL_MAC_ADDRESS;
else
num_mac = pConfig->num_deny_mac = pCommitConfig->num_deny_mac;
acl_entry = pCommitConfig->deny_mac;
for (i = 0; i < num_mac; i++)
{
vos_mem_copy(&pConfig->deny_mac[i], acl_entry->addr, sizeof(v_MACADDR_t));
acl_entry++;
}
//Uapsd Enabled Bit
pConfig->UapsdEnable = (WLAN_HDD_GET_CTX(pHostapdAdapter))->cfg_ini->apUapsdEnabled;
//Enable OBSS protection
pConfig->obssProtEnabled = (WLAN_HDD_GET_CTX(pHostapdAdapter))->cfg_ini->apOBSSProtEnabled;
(WLAN_HDD_GET_AP_CTX_PTR(pHostapdAdapter))->apDisableIntraBssFwd = (WLAN_HDD_GET_CTX(pHostapdAdapter))->cfg_ini->apDisableIntraBssFwd;
hddLog(LOGW, FL("SOftAP macaddress : "MAC_ADDRESS_STR"\n"), MAC_ADDR_ARRAY(pHostapdAdapter->macAddressCurrent.bytes));
hddLog(LOGW,FL("ssid =%s\n"), pConfig->SSIDinfo.ssid.ssId);
hddLog(LOGW,FL("beaconint=%d, channel=%d\n"), (int)pConfig->beacon_int, (int)pConfig->channel);
hddLog(LOGW,FL("hw_mode=%x\n"), pConfig->SapHw_mode);
hddLog(LOGW,FL("privacy=%d, authType=%d\n"), pConfig->privacy, pConfig->authType);
hddLog(LOGW,FL("RSN/WPALen=%d, \n"),(int)pConfig->RSNWPAReqIELength);
hddLog(LOGW,FL("Uapsd = %d\n"),pConfig->UapsdEnable);
hddLog(LOGW,FL("ProtEnabled = %d, OBSSProtEnabled = %d\n"),pConfig->protEnabled, pConfig->obssProtEnabled);
hddLog(LOGW,FL("DisableIntraBssFwd = %d\n"),(WLAN_HDD_GET_AP_CTX_PTR(pHostapdAdapter))->apDisableIntraBssFwd);
pSapEventCallback = hdd_hostapd_SAPEventCB;
pConfig->persona = pHostapdAdapter->device_mode;
if(WLANSAP_StartBss(pVosContext, pSapEventCallback, pConfig,(v_PVOID_t)dev) != VOS_STATUS_SUCCESS)
{
hddLog(LOGE,FL("SAP Start Bss fail\n"));
}
kfree(pConfig);
hddLog(LOG1, FL("Waiting for Scan to complete(auto mode) and BSS to start"));
vos_status = vos_wait_single_event(&pHostapdState->vosEvent, 10000);
if (!VOS_IS_STATUS_SUCCESS(vos_status))
{
VOS_TRACE(VOS_MODULE_ID_HDD, VOS_TRACE_LEVEL_ERROR, ("ERROR: HDD vos wait for single_event failed!!\n"));
VOS_ASSERT(0);
}
pHostapdState->bCommit = TRUE;
if(pHostapdState->vosStatus)
{
return -EIO;
}
else
{
set_bit(SOFTAP_BSS_STARTED, &pHostapdAdapter->event_flags);
WLANSAP_Update_WpsIe ( pVosContext );
return 0;
}
}
static
int iw_softap_setmlme(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
struct sQcSapreq_mlme *pmlme;
hdd_adapter_t *pHostapdAdapter = (hdd_adapter_t*)(netdev_priv(dev));
v_MACADDR_t destAddress;
pmlme = (struct sQcSapreq_mlme *)(wrqu->name);
/* NOTE: this address is not valid incase of TKIP failure, since not filled */
vos_mem_copy(&destAddress.bytes, pmlme->im_macaddr, sizeof(v_MACADDR_t));
switch(pmlme->im_op)
{
case QCSAP_MLME_AUTHORIZE:
hdd_softap_change_STA_state( pHostapdAdapter, &destAddress, WLANTL_STA_AUTHENTICATED);
break;
case QCSAP_MLME_ASSOC:
//TODO:inform to TL after associating (not needed as we do in sapCallback)
break;
case QCSAP_MLME_UNAUTHORIZE:
//TODO: send the disassoc to station
//hdd_softap_change_STA_state( pHostapdAdapter, pmlme->im_macaddr, WLANTL_STA_AUTHENTICATED);
break;
case QCSAP_MLME_DISASSOC:
hdd_softap_sta_disassoc(pHostapdAdapter,pmlme->im_macaddr);
break;
case QCSAP_MLME_DEAUTH:
hdd_softap_sta_deauth(pHostapdAdapter,pmlme->im_macaddr);
break;
case QCSAP_MLME_MICFAILURE:
hdd_softap_tkip_mic_fail_counter_measure(pHostapdAdapter,pmlme->im_reason);
break;
default:
break;
}
return 0;
}
static int iw_softap_set_channel_range(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
hdd_adapter_t *pHostapdAdapter = (netdev_priv(dev));
tHalHandle hHal = WLAN_HDD_GET_HAL_CTX(pHostapdAdapter);
hdd_context_t *pHddCtx = WLAN_HDD_GET_CTX(pHostapdAdapter);
int *value = (int *)extra;
int startChannel = value[0];
int endChannel = value[1];
int band = value[2];
VOS_STATUS status;
int ret = 0; /* success */
if (!capable(CAP_NET_ADMIN))
{
VOS_TRACE(VOS_MODULE_ID_HDD, VOS_TRACE_LEVEL_ERROR,
FL("permission check failed"));
return -EPERM;
}
status = WLANSAP_SetChannelRange(hHal,startChannel,endChannel,band);
if(status != VOS_STATUS_SUCCESS)
{
hddLog( LOGE, FL("iw_softap_set_channel_range: startChannel = %d, endChannel = %d band = %d\n"),
startChannel,endChannel, band);
ret = -EINVAL;
}
pHddCtx->is_dynamic_channel_range_set = 1;
return ret;
}
int iw_softap_get_channel_list(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
v_U32_t num_channels = 0;
v_U8_t i = 0;
v_U8_t bandStartChannel = RF_CHAN_1;
v_U8_t bandEndChannel = RF_CHAN_165;
v_U32_t temp_num_channels = 0;
hdd_adapter_t *pHostapdAdapter = (netdev_priv(dev));
tHalHandle hHal = WLAN_HDD_GET_HAL_CTX(pHostapdAdapter);
v_REGDOMAIN_t domainIdCurrentSoftap;
tpChannelListInfo channel_list = (tpChannelListInfo) extra;
eCsrBand curBand = eCSR_BAND_ALL;
hdd_context_t *pHddCtx = WLAN_HDD_GET_CTX(pHostapdAdapter);
if (eHAL_STATUS_SUCCESS != sme_GetFreqBand(hHal, &curBand))
{
hddLog(LOGE,FL("not able get the current frequency band\n"));
return -EIO;
}
wrqu->data.length = sizeof(tChannelListInfo);
ENTER();
if (eCSR_BAND_24 == curBand)
{
bandStartChannel = RF_CHAN_1;
bandEndChannel = RF_CHAN_14;
}
else if (eCSR_BAND_5G == curBand)
{
bandStartChannel = RF_CHAN_36;
bandEndChannel = RF_CHAN_165;
}
hddLog(LOG1, FL("\n curBand = %d, bandStartChannel = %hu, "
"bandEndChannel = %hu "), curBand,
bandStartChannel, bandEndChannel );
for( i = bandStartChannel; i <= bandEndChannel; i++ )
{
if( NV_CHANNEL_ENABLE == regChannels[i].enabled )
{
channel_list->channels[num_channels] = rfChannels[i].channelNum;
num_channels++;
}
}
/* remove indoor channels if the domain is FCC, channels 36 - 48 */
temp_num_channels = num_channels;
if(eHAL_STATUS_SUCCESS != sme_getSoftApDomain(hHal,(v_REGDOMAIN_t *) &domainIdCurrentSoftap))
{
hddLog(LOG1,FL("Failed to get Domain ID, %d \n"),domainIdCurrentSoftap);
return -EIO;
}
if(REGDOMAIN_FCC == domainIdCurrentSoftap &&
pHddCtx->cfg_ini->gEnableStrictRegulatoryForFCC )
{
for(i = 0; i < temp_num_channels; i++)
{
if((channel_list->channels[i] > 35) &&
(channel_list->channels[i] < 49))
{
vos_mem_move(&channel_list->channels[i],
&channel_list->channels[i+1],
temp_num_channels - (i-1));
num_channels--;
temp_num_channels--;
i--;
}
}
}
hddLog(LOG1,FL(" number of channels %d\n"), num_channels);
if (num_channels > IW_MAX_FREQUENCIES)
{
num_channels = IW_MAX_FREQUENCIES;
}
channel_list->num_channels = num_channels;
EXIT();
return 0;
}
static
int iw_get_genie(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
hdd_adapter_t *pHostapdAdapter = (netdev_priv(dev));
v_CONTEXT_t pVosContext = (WLAN_HDD_GET_CTX(pHostapdAdapter))->pvosContext;
eHalStatus status;
v_U32_t length = DOT11F_IE_RSN_MAX_LEN;
v_U8_t genIeBytes[DOT11F_IE_RSN_MAX_LEN];
ENTER();
hddLog(LOG1,FL("getGEN_IE ioctl\n"));
// Actually retrieve the RSN IE from CSR. (We previously sent it down in the CSR Roam Profile.)
status = WLANSap_getstationIE_information(pVosContext,
&length,
genIeBytes);
length = VOS_MIN((u_int16_t) length, DOT11F_IE_RSN_MAX_LEN);
if (wrqu->data.length < length ||
copy_to_user(wrqu->data.pointer,
(v_VOID_t*)genIeBytes, length))
{
hddLog(LOG1, "%s: failed to copy data to user buffer", __func__);
return -EFAULT;
}
wrqu->data.length = length;
hddLog(LOG1,FL(" RSN IE of %d bytes returned\n"), wrqu->data.length );
EXIT();
return 0;
}
static
int iw_get_WPSPBCProbeReqIEs(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
hdd_adapter_t *pHostapdAdapter = (netdev_priv(dev));
sQcSapreq_WPSPBCProbeReqIES_t WPSPBCProbeReqIEs;
hdd_ap_ctx_t *pHddApCtx = WLAN_HDD_GET_AP_CTX_PTR(pHostapdAdapter);
ENTER();
hddLog(LOG1,FL("get_WPSPBCProbeReqIEs ioctl\n"));
memset((void*)&WPSPBCProbeReqIEs, 0, sizeof(WPSPBCProbeReqIEs));
WPSPBCProbeReqIEs.probeReqIELen = pHddApCtx->WPSPBCProbeReq.probeReqIELen;
vos_mem_copy(&WPSPBCProbeReqIEs.probeReqIE,
pHddApCtx->WPSPBCProbeReq.probeReqIE,
WPSPBCProbeReqIEs.probeReqIELen);
vos_mem_copy(&WPSPBCProbeReqIEs.macaddr,
pHddApCtx->WPSPBCProbeReq.peerMacAddr,
sizeof(v_MACADDR_t));
if (copy_to_user(wrqu->data.pointer,
(void *)&WPSPBCProbeReqIEs,
sizeof(WPSPBCProbeReqIEs)))
{
hddLog(LOG1, "%s: failed to copy data to user buffer", __func__);
return -EFAULT;
}
wrqu->data.length = 12 + WPSPBCProbeReqIEs.probeReqIELen;
hddLog(LOG1, FL("Macaddress : "MAC_ADDRESS_STR"\n"),
MAC_ADDR_ARRAY(WPSPBCProbeReqIEs.macaddr));
up(&pHddApCtx->semWpsPBCOverlapInd);
EXIT();
return 0;
}
/**---------------------------------------------------------------------------
\brief iw_set_auth_hostap() -
This function sets the auth type received from the wpa_supplicant.
\param - dev - Pointer to the net device.
- info - Pointer to the iw_request_info.
- wrqu - Pointer to the iwreq_data.
- extra - Pointer to the data.
\return - 0 for success, non zero for failure
--------------------------------------------------------------------------*/
int iw_set_auth_hostap(struct net_device *dev,struct iw_request_info *info,
union iwreq_data *wrqu,char *extra)
{
hdd_adapter_t *pAdapter = WLAN_HDD_GET_PRIV_PTR(dev);
hdd_wext_state_t *pWextState = WLAN_HDD_GET_WEXT_STATE_PTR(pAdapter);
ENTER();
switch(wrqu->param.flags & IW_AUTH_INDEX)
{
case IW_AUTH_TKIP_COUNTERMEASURES:
{
if(wrqu->param.value) {
hddLog(VOS_TRACE_LEVEL_INFO_HIGH,
"Counter Measure started %d", wrqu->param.value);
pWextState->mTKIPCounterMeasures = TKIP_COUNTER_MEASURE_STARTED;
}
else {
hddLog(VOS_TRACE_LEVEL_INFO_HIGH,
"Counter Measure stopped=%d", wrqu->param.value);
pWextState->mTKIPCounterMeasures = TKIP_COUNTER_MEASURE_STOPED;
}
hdd_softap_tkip_mic_fail_counter_measure(pAdapter,
wrqu->param.value);
}
break;
default:
hddLog(LOGW, "%s called with unsupported auth type %d", __func__,
wrqu->param.flags & IW_AUTH_INDEX);
break;
}
EXIT();
return 0;
}
static int iw_set_ap_encodeext(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
hdd_adapter_t *pHostapdAdapter = (netdev_priv(dev));
v_CONTEXT_t pVosContext = (WLAN_HDD_GET_CTX(pHostapdAdapter))->pvosContext;
hdd_ap_ctx_t *pHddApCtx = WLAN_HDD_GET_AP_CTX_PTR(pHostapdAdapter);
int retval = 0;
VOS_STATUS vstatus;
struct iw_encode_ext *ext = (struct iw_encode_ext*)extra;
v_U8_t groupmacaddr[WNI_CFG_BSSID_LEN] = {0xFF,0xFF,0xFF,0xFF,0xFF,0xFF};
int key_index;
struct iw_point *encoding = &wrqu->encoding;
tCsrRoamSetKey setKey;
// tCsrRoamRemoveKey RemoveKey;
int i;
ENTER();
key_index = encoding->flags & IW_ENCODE_INDEX;
if(key_index > 0) {
/*Convert from 1-based to 0-based keying*/
key_index--;
}
if(!ext->key_len) {
#if 0
/*Set the encrytion type to NONE*/
#if 0
pRoamProfile->EncryptionType.encryptionType[0] = eCSR_ENCRYPT_TYPE_NONE;
#endif
RemoveKey.keyId = key_index;
if(ext->ext_flags & IW_ENCODE_EXT_GROUP_KEY) {
/*Key direction for group is RX only*/
vos_mem_copy(RemoveKey.peerMac,groupmacaddr,WNI_CFG_BSSID_LEN);
}
else {
vos_mem_copy(RemoveKey.peerMac,ext->addr.sa_data,WNI_CFG_BSSID_LEN);
}
switch(ext->alg)
{
case IW_ENCODE_ALG_NONE:
RemoveKey.encType = eCSR_ENCRYPT_TYPE_NONE;
break;
case IW_ENCODE_ALG_WEP:
RemoveKey.encType = (ext->key_len== 5) ? eCSR_ENCRYPT_TYPE_WEP40:eCSR_ENCRYPT_TYPE_WEP104;
break;
case IW_ENCODE_ALG_TKIP:
RemoveKey.encType = eCSR_ENCRYPT_TYPE_TKIP;
break;
case IW_ENCODE_ALG_CCMP:
RemoveKey.encType = eCSR_ENCRYPT_TYPE_AES;
break;
default:
RemoveKey.encType = eCSR_ENCRYPT_TYPE_NONE;
break;
}
VOS_TRACE(VOS_MODULE_ID_HDD, VOS_TRACE_LEVEL_INFO, "%s: Remove key cipher_alg:%d key_len%d *pEncryptionType :%d \n",
__func__,(int)ext->alg,(int)ext->key_len,RemoveKey.encType);
VOS_TRACE(VOS_MODULE_ID_HDD, VOS_TRACE_LEVEL_INFO, "%s: Peer Mac = "MAC_ADDRESS_STR"\n",
__func__, MAC_ADDR_ARRAY(RemoveKey.peerMac));
);
vstatus = WLANSAP_DelKeySta( pVosContext, &RemoveKey);
if ( vstatus != VOS_STATUS_SUCCESS )
{
VOS_TRACE(VOS_MODULE_ID_HDD, VOS_TRACE_LEVEL_ERROR, "[%4d] WLANSAP_DeleteKeysSta returned ERROR status= %d",
__LINE__, vstatus );
retval = -EINVAL;
}
#endif
return retval;
}
vos_mem_zero(&setKey,sizeof(tCsrRoamSetKey));
setKey.keyId = key_index;
setKey.keyLength = ext->key_len;
if(ext->key_len <= CSR_MAX_KEY_LEN) {
vos_mem_copy(&setKey.Key[0],ext->key,ext->key_len);
}
if(ext->ext_flags & IW_ENCODE_EXT_GROUP_KEY) {
/*Key direction for group is RX only*/
setKey.keyDirection = eSIR_RX_ONLY;
vos_mem_copy(setKey.peerMac,groupmacaddr,WNI_CFG_BSSID_LEN);
}
else {
setKey.keyDirection = eSIR_TX_RX;
vos_mem_copy(setKey.peerMac,ext->addr.sa_data,WNI_CFG_BSSID_LEN);
}
if(ext->ext_flags & IW_ENCODE_EXT_SET_TX_KEY)
{
setKey.keyDirection = eSIR_TX_DEFAULT;
vos_mem_copy(setKey.peerMac,ext->addr.sa_data,WNI_CFG_BSSID_LEN);
}
/*For supplicant pae role is zero*/
setKey.paeRole = 0;
switch(ext->alg)
{
case IW_ENCODE_ALG_NONE:
setKey.encType = eCSR_ENCRYPT_TYPE_NONE;
break;
case IW_ENCODE_ALG_WEP:
setKey.encType = (ext->key_len== 5) ? eCSR_ENCRYPT_TYPE_WEP40:eCSR_ENCRYPT_TYPE_WEP104;
pHddApCtx->uPrivacy = 1;
hddLog(LOG1, "(%s) uPrivacy=%d", __func__, pHddApCtx->uPrivacy);
break;
case IW_ENCODE_ALG_TKIP:
{
v_U8_t *pKey = &setKey.Key[0];
setKey.encType = eCSR_ENCRYPT_TYPE_TKIP;
vos_mem_zero(pKey, CSR_MAX_KEY_LEN);
/*Supplicant sends the 32bytes key in this order
|--------------|----------|----------|
| Tk1 |TX-MIC | RX Mic |
|--------------|----------|----------|
<---16bytes---><--8bytes--><--8bytes-->
*/
/*Sme expects the 32 bytes key to be in the below order
|--------------|----------|----------|
| Tk1 |RX-MIC | TX Mic |
|--------------|----------|----------|
<---16bytes---><--8bytes--><--8bytes-->
*/
/* Copy the Temporal Key 1 (TK1) */
vos_mem_copy(pKey,ext->key,16);
/*Copy the rx mic first*/
vos_mem_copy(&pKey[16],&ext->key[24],8);
/*Copy the tx mic */
vos_mem_copy(&pKey[24],&ext->key[16],8);
}
break;
case IW_ENCODE_ALG_CCMP:
setKey.encType = eCSR_ENCRYPT_TYPE_AES;
break;
default:
setKey.encType = eCSR_ENCRYPT_TYPE_NONE;
break;
}
VOS_TRACE(VOS_MODULE_ID_HDD, VOS_TRACE_LEVEL_INFO,
("%s:EncryptionType:%d key_len:%d, KeyId:%d"), __func__, setKey.encType, setKey.keyLength,
setKey.keyId);
for(i=0; i< ext->key_len; i++)
VOS_TRACE(VOS_MODULE_ID_HDD, VOS_TRACE_LEVEL_INFO,
("%02x"), setKey.Key[i]);
VOS_TRACE(VOS_MODULE_ID_HDD, VOS_TRACE_LEVEL_INFO,
("\n"));
vstatus = WLANSAP_SetKeySta( pVosContext, &setKey);
if ( vstatus != VOS_STATUS_SUCCESS )
{
VOS_TRACE( VOS_MODULE_ID_HDD, VOS_TRACE_LEVEL_ERROR,
"[%4d] WLANSAP_SetKeySta returned ERROR status= %d", __LINE__, vstatus );
retval = -EINVAL;
}
return retval;
}
static int iw_set_ap_mlme(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu,
char *extra)
{
#if 0
hdd_adapter_t *pAdapter = (netdev_priv(dev));
struct iw_mlme *mlme = (struct iw_mlme *)extra;
ENTER();
//reason_code is unused. By default it is set to eCSR_DISCONNECT_REASON_UNSPECIFIED
switch (mlme->cmd) {
case IW_MLME_DISASSOC:
case IW_MLME_DEAUTH:
hddLog(LOG1, "Station disassociate");
if( pAdapter->conn_info.connState == eConnectionState_Associated )
{
eCsrRoamDisconnectReason reason = eCSR_DISCONNECT_REASON_UNSPECIFIED;
if( mlme->reason_code == HDD_REASON_MICHAEL_MIC_FAILURE )
reason = eCSR_DISCONNECT_REASON_MIC_ERROR;
status = sme_RoamDisconnect( pAdapter->hHal,pAdapter->sessionId, reason);
//clear all the reason codes
if (status != 0)
{
hddLog(LOGE,"%s %d Command Disassociate/Deauthenticate : csrRoamDisconnect failure returned %d \n", __func__, (int)mlme->cmd, (int)status );
}
netif_stop_queue(dev);
netif_carrier_off(dev);
}
else
{
hddLog(LOGE,"%s %d Command Disassociate/Deauthenticate called but station is not in associated state \n", __func__, (int)mlme->cmd );
}
default:
hddLog(LOGE,"%s %d Command should be Disassociate/Deauthenticate \n", __func__, (int)mlme->cmd );
return -EINVAL;
}//end of switch
EXIT();
#endif
return 0;
// return status;
}
static int iw_get_ap_rts_threshold(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
hdd_adapter_t *pHostapdAdapter = (netdev_priv(dev));
v_U32_t status = 0;
status = hdd_wlan_get_rts_threshold(pHostapdAdapter, wrqu);
return status;
}
static int iw_get_ap_frag_threshold(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
hdd_adapter_t *pHostapdAdapter = (netdev_priv(dev));
v_U32_t status = 0;
status = hdd_wlan_get_frag_threshold(pHostapdAdapter, wrqu);
return status;
}
static int iw_get_ap_freq(struct net_device *dev, struct iw_request_info *info,
struct iw_freq *fwrq, char *extra)
{
v_U32_t status = FALSE, channel = 0, freq = 0;
hdd_adapter_t *pHostapdAdapter = (netdev_priv(dev));
tHalHandle hHal;
hdd_hostapd_state_t *pHostapdState;
hdd_ap_ctx_t *pHddApCtx = WLAN_HDD_GET_AP_CTX_PTR(pHostapdAdapter);
ENTER();
if ((WLAN_HDD_GET_CTX(pHostapdAdapter))->isLogpInProgress) {
VOS_TRACE(VOS_MODULE_ID_HDD, VOS_TRACE_LEVEL_INFO,
"%s:LOGP in Progress. Ignore!!!",__func__);
return status;
}
pHostapdState = WLAN_HDD_GET_HOSTAP_STATE_PTR(pHostapdAdapter);
hHal = WLAN_HDD_GET_HAL_CTX(pHostapdAdapter);
if(pHostapdState->bssState == BSS_STOP )
{
if (ccmCfgGetInt(hHal, WNI_CFG_CURRENT_CHANNEL, &channel)
!= eHAL_STATUS_SUCCESS)
{
return -EIO;
}
else
{
status = hdd_wlan_get_freq(channel, &freq);
if( TRUE == status)
{
/* Set Exponent parameter as 6 (MHZ) in struct iw_freq
* iwlist & iwconfig command shows frequency into proper
* format (2.412 GHz instead of 246.2 MHz)*/
fwrq->m = freq;
fwrq->e = MHZ;
}
}
}
else
{
channel = pHddApCtx->operatingChannel;
status = hdd_wlan_get_freq(channel, &freq);
if( TRUE == status)
{
/* Set Exponent parameter as 6 (MHZ) in struct iw_freq
* iwlist & iwconfig command shows frequency into proper
* format (2.412 GHz instead of 246.2 MHz)*/
fwrq->m = freq;
fwrq->e = MHZ;
}
}
return 0;
}
static int iw_get_mode(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu,
char *extra)
{
int status = 0;
wrqu->mode = IW_MODE_MASTER;
return status;
}
static int iw_softap_stopbss(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu,
char *extra)
{
hdd_adapter_t *pHostapdAdapter = (netdev_priv(dev));
VOS_STATUS status = VOS_STATUS_SUCCESS;
ENTER();
if(test_bit(SOFTAP_BSS_STARTED, &pHostapdAdapter->event_flags))
{
if ( VOS_STATUS_SUCCESS == (status = WLANSAP_StopBss((WLAN_HDD_GET_CTX(pHostapdAdapter))->pvosContext) ) )
{
hdd_hostapd_state_t *pHostapdState = WLAN_HDD_GET_HOSTAP_STATE_PTR(pHostapdAdapter);
status = vos_wait_single_event(&pHostapdState->vosEvent, 10000);
if (!VOS_IS_STATUS_SUCCESS(status))
{
VOS_TRACE(VOS_MODULE_ID_HDD, VOS_TRACE_LEVEL_ERROR,
("ERROR: HDD vos wait for single_event failed!!\n"));
VOS_ASSERT(0);
}
}
clear_bit(SOFTAP_BSS_STARTED, &pHostapdAdapter->event_flags);
}
EXIT();
return (status == VOS_STATUS_SUCCESS) ? 0 : -EBUSY;
}
static int iw_softap_version(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu,
char *extra)
{
hdd_adapter_t *pHostapdAdapter = (netdev_priv(dev));
ENTER();
hdd_wlan_get_version(pHostapdAdapter, wrqu, extra);
EXIT();
return 0;
}
VOS_STATUS hdd_softap_get_sta_info(hdd_adapter_t *pAdapter, v_U8_t *pBuf, int buf_len)
{
v_U8_t i;
int len = 0;
const char sta_info_header[] = "staId staAddress\n";
len = scnprintf(pBuf, buf_len, sta_info_header);
pBuf += len;
buf_len -= len;
for (i = 0; i < WLAN_MAX_STA_COUNT; i++)
{
if(pAdapter->aStaInfo[i].isUsed)
{
len = scnprintf(pBuf, buf_len, "%*d .%02x:%02x:%02x:%02x:%02x:%02x\n",
strlen("staId"),
pAdapter->aStaInfo[i].ucSTAId,
pAdapter->aStaInfo[i].macAddrSTA.bytes[0],
pAdapter->aStaInfo[i].macAddrSTA.bytes[1],
pAdapter->aStaInfo[i].macAddrSTA.bytes[2],
pAdapter->aStaInfo[i].macAddrSTA.bytes[3],
pAdapter->aStaInfo[i].macAddrSTA.bytes[4],
pAdapter->aStaInfo[i].macAddrSTA.bytes[5]);
pBuf += len;
buf_len -= len;
}
if(WE_GET_STA_INFO_SIZE > buf_len)
{
break;
}
}
return VOS_STATUS_SUCCESS;
}
static int iw_softap_get_sta_info(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu,
char *extra)
{
hdd_adapter_t *pHostapdAdapter = (netdev_priv(dev));
VOS_STATUS status;
ENTER();
status = hdd_softap_get_sta_info(pHostapdAdapter, extra, WE_SAP_MAX_STA_INFO);
if ( !VOS_IS_STATUS_SUCCESS( status ) ) {
hddLog(VOS_TRACE_LEVEL_ERROR, "%s Failed!!!\n",__func__);
return -EINVAL;
}
wrqu->data.length = strlen(extra);
EXIT();
return 0;
}
static int iw_set_ap_genie(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu,
char *extra)
{
hdd_adapter_t *pHostapdAdapter = (netdev_priv(dev));
v_CONTEXT_t pVosContext = (WLAN_HDD_GET_CTX(pHostapdAdapter))->pvosContext;
eHalStatus halStatus= eHAL_STATUS_SUCCESS;
u_int8_t *genie = (u_int8_t *)extra;
ENTER();
if(!wrqu->data.length)
{
EXIT();
return 0;
}
if (wrqu->data.length > DOT11F_IE_RSN_MAX_LEN) {
VOS_TRACE(VOS_MODULE_ID_HDD, VOS_TRACE_LEVEL_ERROR,
"%s: WPARSN Ie input length is more than max[%d]", __func__,
wrqu->data.length);
return -EINVAL;
}
switch (genie[0])
{
case DOT11F_EID_WPA:
case DOT11F_EID_RSN:
if((WLAN_HDD_GET_AP_CTX_PTR(pHostapdAdapter))->uPrivacy == 0)
{
hdd_softap_Deregister_BC_STA(pHostapdAdapter);
hdd_softap_Register_BC_STA(pHostapdAdapter, 1);
}
(WLAN_HDD_GET_AP_CTX_PTR(pHostapdAdapter))->uPrivacy = 1;
halStatus = WLANSAP_Set_WPARSNIes(pVosContext, genie, wrqu->data.length);
break;
default:
hddLog (LOGE, "%s Set UNKNOWN IE %X",__func__, genie[0]);
halStatus = 0;
}
EXIT();
return halStatus;
}
static VOS_STATUS wlan_hdd_get_classAstats_for_station(hdd_adapter_t *pAdapter, u8 staid)
{
eHalStatus hstatus;
long lrc;
struct statsContext context;
if (NULL == pAdapter)
{
hddLog(VOS_TRACE_LEVEL_ERROR,"%s: Padapter is NULL", __func__);
return VOS_STATUS_E_FAULT;
}
init_completion(&context.completion);
context.pAdapter = pAdapter;
context.magic = STATS_CONTEXT_MAGIC;
hstatus = sme_GetStatistics( WLAN_HDD_GET_HAL_CTX(pAdapter),
eCSR_HDD,
SME_GLOBAL_CLASSA_STATS,
hdd_GetClassA_statisticsCB,
0, // not periodic
FALSE, //non-cached results
staid,
&context);
if (eHAL_STATUS_SUCCESS != hstatus)
{
hddLog(VOS_TRACE_LEVEL_ERROR,
"%s: Unable to retrieve statistics for link speed",
__func__);
}
else
{
lrc = wait_for_completion_interruptible_timeout(&context.completion,
msecs_to_jiffies(WLAN_WAIT_TIME_STATS));
if (lrc <= 0)
{
hddLog(VOS_TRACE_LEVEL_ERROR,
"%s: SME %s while retrieving link speed",
__func__, (0 == lrc) ? "timeout" : "interrupt");
}
}
/* either we never sent a request, we sent a request and received a
response or we sent a request and timed out. if we never sent a
request or if we sent a request and got a response, we want to
clear the magic out of paranoia. if we timed out there is a
race condition such that the callback function could be
executing at the same time we are. of primary concern is if the
callback function had already verified the "magic" but had not
yet set the completion variable when a timeout occurred. we
serialize these activities by invalidating the magic while
holding a shared spinlock which will cause us to block if the
callback is currently executing */
spin_lock(&hdd_context_lock);
context.magic = 0;
spin_unlock(&hdd_context_lock);
return VOS_STATUS_SUCCESS;
}
int iw_get_softap_linkspeed(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu,
char *extra)
{
hdd_adapter_t *pHostapdAdapter = (netdev_priv(dev));
hdd_context_t *pHddCtx;
char *pLinkSpeed = (char*)extra;
char *pmacAddress;
v_U32_t link_speed;
unsigned short staId;
int len = sizeof(v_U32_t)+1;
v_BYTE_t macAddress[VOS_MAC_ADDR_SIZE];
VOS_STATUS status;
int rc, valid;
pHddCtx = WLAN_HDD_GET_CTX(pHostapdAdapter);
valid = wlan_hdd_validate_context(pHddCtx);
if (0 != valid)
{
hddLog(VOS_TRACE_LEVEL_ERROR, FL("HDD context not valid"));
return valid;
}
hddLog(VOS_TRACE_LEVEL_INFO, "%s wrqu->data.length= %d\n", __func__, wrqu->data.length);
if (wrqu->data.length != MAC_ADDRESS_STR_LEN)
{
hddLog(LOG1, "Invalid length");
return -EINVAL;
}
pmacAddress = kmalloc(MAC_ADDRESS_STR_LEN, GFP_KERNEL);
if(NULL == pmacAddress) {
hddLog(LOG1, "unable to allocate memory");
return -ENOMEM;
}
if (copy_from_user((void *)pmacAddress,
wrqu->data.pointer, wrqu->data.length))
{
hddLog(LOG1, "%s: failed to copy data to user buffer", __func__);
kfree(pmacAddress);
return -EFAULT;
}
status = hdd_string_to_hex (pmacAddress, wrqu->data.length, macAddress );
kfree(pmacAddress);
if (!VOS_IS_STATUS_SUCCESS(status ))
{
hddLog(VOS_TRACE_LEVEL_ERROR, FL("String to Hex conversion Failed"));
}
/* If no mac address is passed and/or its length is less than 17,
* link speed for first connected client will be returned.
*/
if (!VOS_IS_STATUS_SUCCESS(status ) || wrqu->data.length < 17)
{
status = hdd_softap_GetConnectedStaId(pHostapdAdapter, (void *)(&staId));
}
else
{
status = hdd_softap_GetStaId(pHostapdAdapter,
(v_MACADDR_t *)macAddress, (void *)(&staId));
}
if (!VOS_IS_STATUS_SUCCESS(status))
{
hddLog(VOS_TRACE_LEVEL_ERROR, FL("ERROR: HDD Failed to find sta id!!"));
link_speed = 0;
}
else
{
status = wlan_hdd_get_classAstats_for_station(pHostapdAdapter , staId);
if (!VOS_IS_STATUS_SUCCESS(status ))
{
hddLog(VOS_TRACE_LEVEL_ERROR, FL("Unable to retrieve SME statistics"));
return -EINVAL;
}
WLANTL_GetSTALinkCapacity(pHddCtx->pvosContext,
staId, &link_speed);
link_speed = link_speed / 10;
if (0 == link_speed)
{
/* The linkspeed returned by HAL is in units of 500kbps.
* converting it to mbps.
* This is required to support legacy firmware which does
* not return link capacity.
*/
link_speed =(int)pHostapdAdapter->hdd_stats.ClassA_stat.tx_rate/2;
}
}
wrqu->data.length = len;
rc = snprintf(pLinkSpeed, len, "%lu", link_speed);
if ((rc < 0) || (rc >= len))
{
// encoding or length error?
hddLog(VOS_TRACE_LEVEL_ERROR,FL( "Unable to encode link speed"));
return -EIO;
}
return 0;
}
static const iw_handler hostapd_handler[] =
{
(iw_handler) NULL, /* SIOCSIWCOMMIT */
(iw_handler) NULL, /* SIOCGIWNAME */
(iw_handler) NULL, /* SIOCSIWNWID */
(iw_handler) NULL, /* SIOCGIWNWID */
(iw_handler) NULL, /* SIOCSIWFREQ */
(iw_handler) iw_get_ap_freq, /* SIOCGIWFREQ */
(iw_handler) NULL, /* SIOCSIWMODE */
(iw_handler) iw_get_mode, /* SIOCGIWMODE */
(iw_handler) NULL, /* SIOCSIWSENS */
(iw_handler) NULL, /* SIOCGIWSENS */
(iw_handler) NULL, /* SIOCSIWRANGE */
(iw_handler) NULL, /* SIOCGIWRANGE */
(iw_handler) NULL, /* SIOCSIWPRIV */
(iw_handler) NULL, /* SIOCGIWPRIV */
(iw_handler) NULL, /* SIOCSIWSTATS */
(iw_handler) NULL, /* SIOCGIWSTATS */
(iw_handler) NULL, /* SIOCSIWSPY */
(iw_handler) NULL, /* SIOCGIWSPY */
(iw_handler) NULL, /* SIOCSIWTHRSPY */
(iw_handler) NULL, /* SIOCGIWTHRSPY */
(iw_handler) NULL, /* SIOCSIWAP */
(iw_handler) NULL, /* SIOCGIWAP */
(iw_handler) iw_set_ap_mlme, /* SIOCSIWMLME */
(iw_handler) NULL, /* SIOCGIWAPLIST */
(iw_handler) NULL, /* SIOCSIWSCAN */
(iw_handler) NULL, /* SIOCGIWSCAN */
(iw_handler) NULL, /* SIOCSIWESSID */
(iw_handler) NULL, /* SIOCGIWESSID */
(iw_handler) NULL, /* SIOCSIWNICKN */
(iw_handler) NULL, /* SIOCGIWNICKN */
(iw_handler) NULL, /* -- hole -- */
(iw_handler) NULL, /* -- hole -- */
(iw_handler) NULL, /* SIOCSIWRATE */
(iw_handler) NULL, /* SIOCGIWRATE */
(iw_handler) NULL, /* SIOCSIWRTS */
(iw_handler) iw_get_ap_rts_threshold, /* SIOCGIWRTS */
(iw_handler) NULL, /* SIOCSIWFRAG */
(iw_handler) iw_get_ap_frag_threshold, /* SIOCGIWFRAG */
(iw_handler) NULL, /* SIOCSIWTXPOW */
(iw_handler) NULL, /* SIOCGIWTXPOW */
(iw_handler) NULL, /* SIOCSIWRETRY */
(iw_handler) NULL, /* SIOCGIWRETRY */
(iw_handler) NULL, /* SIOCSIWENCODE */
(iw_handler) NULL, /* SIOCGIWENCODE */
(iw_handler) NULL, /* SIOCSIWPOWER */
(iw_handler) NULL, /* SIOCGIWPOWER */
(iw_handler) NULL, /* -- hole -- */
(iw_handler) NULL, /* -- hole -- */
(iw_handler) iw_set_ap_genie, /* SIOCSIWGENIE */
(iw_handler) NULL, /* SIOCGIWGENIE */
(iw_handler) iw_set_auth_hostap, /* SIOCSIWAUTH */
(iw_handler) NULL, /* SIOCGIWAUTH */
(iw_handler) iw_set_ap_encodeext, /* SIOCSIWENCODEEXT */
(iw_handler) NULL, /* SIOCGIWENCODEEXT */
(iw_handler) NULL, /* SIOCSIWPMKSA */
};
/*
* Note that the following ioctls were defined with semantics which
* cannot be handled by the "iwpriv" userspace application and hence
* they are not included in the hostapd_private_args array
* QCSAP_IOCTL_ASSOC_STA_MACADDR
*/
static const struct iw_priv_args hostapd_private_args[] = {
{ QCSAP_IOCTL_SETPARAM,
IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 2, 0, "setparam" },
{ QCSAP_IOCTL_SETPARAM,
IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1, 0, "" },
{ QCSAP_PARAM_MAX_ASSOC,
IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1, 0, "setMaxAssoc" },
{ QCSAP_PARAM_HIDE_SSID,
IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1, 0, "hideSSID" },
{ QCSAP_IOCTL_GETPARAM,
IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1,
IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1, "getparam" },
{ QCSAP_IOCTL_GETPARAM, 0,
IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1, "" },
{ QCSAP_PARAM_MAX_ASSOC, 0,
IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1, "getMaxAssoc" },
{ QCSAP_PARAM_GET_WLAN_DBG, 0,
IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1, "getwlandbg" },
{ QCSAP_PARAM_AUTO_CHANNEL, 0,
IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1, "getAutoChannel" },
{ QCSAP_PARAM_MODULE_DOWN_IND, 0,
IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1, "moduleDownInd" },
{ QCSAP_PARAM_CLR_ACL, 0,
IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1, "setClearAcl" },
{ QCSAP_PARAM_ACL_MODE,
IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1, 0, "setAclMode" },
{ QCSAP_IOCTL_COMMIT,
IW_PRIV_TYPE_BYTE | sizeof(struct s_CommitConfig) | IW_PRIV_SIZE_FIXED, 0, "commit" },
{ QCSAP_IOCTL_SETMLME,
IW_PRIV_TYPE_BYTE | sizeof(struct sQcSapreq_mlme)| IW_PRIV_SIZE_FIXED, 0, "setmlme" },
{ QCSAP_IOCTL_GET_STAWPAIE,
IW_PRIV_TYPE_BYTE | IW_PRIV_SIZE_FIXED | 1, 0, "get_staWPAIE" },
{ QCSAP_IOCTL_STOPBSS,
IW_PRIV_TYPE_BYTE | IW_PRIV_SIZE_FIXED, 0, "stopbss" },
{ QCSAP_IOCTL_VERSION, 0,
IW_PRIV_TYPE_CHAR | QCSAP_MAX_WSC_IE, "version" },
{ QCSAP_IOCTL_GET_STA_INFO, 0,
IW_PRIV_TYPE_CHAR | WE_SAP_MAX_STA_INFO, "get_sta_info" },
{ QCSAP_IOCTL_GET_WPS_PBC_PROBE_REQ_IES,
IW_PRIV_TYPE_BYTE | sizeof(sQcSapreq_WPSPBCProbeReqIES_t) | IW_PRIV_SIZE_FIXED | 1, 0, "getProbeReqIEs" },
{ QCSAP_IOCTL_GET_CHANNEL, 0,
IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1, "getchannel" },
{ QCSAP_IOCTL_DISASSOC_STA,
IW_PRIV_TYPE_BYTE | IW_PRIV_SIZE_FIXED | 6 , 0, "disassoc_sta" },
{ QCSAP_IOCTL_AP_STATS,
IW_PRIV_TYPE_BYTE | QCSAP_MAX_WSC_IE, 0, "ap_stats" },
{ QCSAP_IOCTL_PRIV_GET_SOFTAP_LINK_SPEED,
IW_PRIV_TYPE_CHAR | 18,
IW_PRIV_TYPE_CHAR | 5, "getLinkSpeed" },
{ QCSAP_IOCTL_PRIV_SET_THREE_INT_GET_NONE,
IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 3, 0, "" },
/* handlers for sub-ioctl */
{ WE_SET_WLAN_DBG,
IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 3,
0,
"setwlandbg" },
/* handlers for main ioctl */
{ QCSAP_IOCTL_PRIV_SET_VAR_INT_GET_NONE,
IW_PRIV_TYPE_INT | MAX_VAR_ARGS,
0,
"" },
/* handlers for sub-ioctl */
{ WE_LOG_DUMP_CMD,
IW_PRIV_TYPE_INT | MAX_VAR_ARGS,
0,
"dump" },
{ WE_P2P_NOA_CMD,
IW_PRIV_TYPE_INT | MAX_VAR_ARGS,
0,
"SetP2pPs" },
/* handlers for sub ioctl */
{
WE_MCC_CONFIG_CREDENTIAL,
IW_PRIV_TYPE_INT | MAX_VAR_ARGS,
0,
"setMccCrdnl" },
/* handlers for sub ioctl */
{
WE_MCC_CONFIG_PARAMS,
IW_PRIV_TYPE_INT | MAX_VAR_ARGS,
0,
"setMccConfig" },
/* handlers for main ioctl */
{ QCSAP_IOCTL_MODIFY_ACL,
IW_PRIV_TYPE_BYTE | IW_PRIV_SIZE_FIXED | 8,
0,
"modify_acl" },
/* handlers for main ioctl */
{ QCSAP_IOCTL_GET_CHANNEL_LIST,
0,
IW_PRIV_TYPE_BYTE | sizeof(tChannelListInfo),
"getChannelList" },
/* handlers for main ioctl */
{ QCSAP_IOCTL_SET_TX_POWER,
IW_PRIV_TYPE_INT| IW_PRIV_SIZE_FIXED | 1,
0,
"setTxPower" },
/* handlers for main ioctl */
{ QCSAP_IOCTL_SET_MAX_TX_POWER,
IW_PRIV_TYPE_INT| IW_PRIV_SIZE_FIXED | 1,
0,
"setTxMaxPower" },
{ QCSAP_IOCTL_DATAPATH_SNAP_SHOT,
IW_PRIV_TYPE_NONE | IW_PRIV_TYPE_NONE,
0,
"dataSnapshot" },
/* handlers for main ioctl */
{ QCSAP_IOCTL_SET_TRAFFIC_MONITOR,
IW_PRIV_TYPE_INT| IW_PRIV_SIZE_FIXED | 1,
0,
"setTrafficMon" },
};
static const iw_handler hostapd_private[] = {
[QCSAP_IOCTL_SETPARAM - SIOCIWFIRSTPRIV] = iw_softap_setparam, //set priv ioctl
[QCSAP_IOCTL_GETPARAM - SIOCIWFIRSTPRIV] = iw_softap_getparam, //get priv ioctl
[QCSAP_IOCTL_COMMIT - SIOCIWFIRSTPRIV] = iw_softap_commit, //get priv ioctl
[QCSAP_IOCTL_SETMLME - SIOCIWFIRSTPRIV] = iw_softap_setmlme,
[QCSAP_IOCTL_GET_STAWPAIE - SIOCIWFIRSTPRIV] = iw_get_genie, //get station genIE
[QCSAP_IOCTL_STOPBSS - SIOCIWFIRSTPRIV] = iw_softap_stopbss, // stop bss
[QCSAP_IOCTL_VERSION - SIOCIWFIRSTPRIV] = iw_softap_version, // get driver version
[QCSAP_IOCTL_GET_WPS_PBC_PROBE_REQ_IES - SIOCIWFIRSTPRIV] = iw_get_WPSPBCProbeReqIEs,
[QCSAP_IOCTL_GET_CHANNEL - SIOCIWFIRSTPRIV] = iw_softap_getchannel,
[QCSAP_IOCTL_ASSOC_STA_MACADDR - SIOCIWFIRSTPRIV] = iw_softap_getassoc_stamacaddr,
[QCSAP_IOCTL_DISASSOC_STA - SIOCIWFIRSTPRIV] = iw_softap_disassoc_sta,
[QCSAP_IOCTL_AP_STATS - SIOCIWFIRSTPRIV] = iw_softap_ap_stats,
[QCSAP_IOCTL_PRIV_SET_THREE_INT_GET_NONE - SIOCIWFIRSTPRIV] = iw_set_three_ints_getnone,
[QCSAP_IOCTL_PRIV_SET_VAR_INT_GET_NONE - SIOCIWFIRSTPRIV] = iw_set_var_ints_getnone,
[QCSAP_IOCTL_SET_CHANNEL_RANGE - SIOCIWFIRSTPRIV] = iw_softap_set_channel_range,
[QCSAP_IOCTL_MODIFY_ACL - SIOCIWFIRSTPRIV] = iw_softap_modify_acl,
[QCSAP_IOCTL_GET_CHANNEL_LIST - SIOCIWFIRSTPRIV] = iw_softap_get_channel_list,
[QCSAP_IOCTL_GET_STA_INFO - SIOCIWFIRSTPRIV] = iw_softap_get_sta_info,
[QCSAP_IOCTL_PRIV_GET_SOFTAP_LINK_SPEED - SIOCIWFIRSTPRIV] = iw_get_softap_linkspeed,
[QCSAP_IOCTL_SET_TX_POWER - SIOCIWFIRSTPRIV] = iw_softap_set_tx_power,
[QCSAP_IOCTL_SET_MAX_TX_POWER - SIOCIWFIRSTPRIV] = iw_softap_set_max_tx_power,
[QCSAP_IOCTL_DATAPATH_SNAP_SHOT - SIOCIWFIRSTPRIV] = iw_display_data_path_snapshot,
[QCSAP_IOCTL_SET_TRAFFIC_MONITOR - SIOCIWFIRSTPRIV] = iw_softap_set_trafficmonitor,
};
const struct iw_handler_def hostapd_handler_def = {
.num_standard = sizeof(hostapd_handler) / sizeof(hostapd_handler[0]),
.num_private = sizeof(hostapd_private) / sizeof(hostapd_private[0]),
.num_private_args = sizeof(hostapd_private_args) / sizeof(hostapd_private_args[0]),
.standard = (iw_handler *)hostapd_handler,
.private = (iw_handler *)hostapd_private,
.private_args = hostapd_private_args,
.get_wireless_stats = NULL,
};
#if LINUX_VERSION_CODE > KERNEL_VERSION(2,6,29)
struct net_device_ops net_ops_struct = {
.ndo_open = hdd_hostapd_open,
.ndo_stop = hdd_hostapd_stop,
.ndo_uninit = hdd_hostapd_uninit,
.ndo_start_xmit = hdd_softap_hard_start_xmit,
.ndo_tx_timeout = hdd_softap_tx_timeout,
.ndo_get_stats = hdd_softap_stats,
.ndo_set_mac_address = hdd_hostapd_set_mac_address,
.ndo_do_ioctl = hdd_hostapd_ioctl,
.ndo_change_mtu = hdd_hostapd_change_mtu,
.ndo_select_queue = hdd_hostapd_select_queue,
};
#endif
int hdd_set_hostapd(hdd_adapter_t *pAdapter)
{
return VOS_STATUS_SUCCESS;
}
void hdd_set_ap_ops( struct net_device *pWlanHostapdDev )
{
#if LINUX_VERSION_CODE > KERNEL_VERSION(2,6,29)
pWlanHostapdDev->netdev_ops = &net_ops_struct;
#else
pWlanHostapdDev->open = hdd_hostapd_open;
pWlanHostapdDev->stop = hdd_hostapd_stop;
pWlanHostapdDev->uninit = hdd_hostapd_uninit;
pWlanHostapdDev->hard_start_xmit = hdd_softap_hard_start_xmit;
pWlanHostapdDev->tx_timeout = hdd_softap_tx_timeout;
pWlanHostapdDev->get_stats = hdd_softap_stats;
pWlanHostapdDev->set_mac_address = hdd_hostapd_set_mac_address;
pWlanHostapdDev->do_ioctl = hdd_hostapd_ioctl;
#endif
}
VOS_STATUS hdd_init_ap_mode( hdd_adapter_t *pAdapter )
{
hdd_hostapd_state_t * phostapdBuf;
struct net_device *dev = pAdapter->dev;
VOS_STATUS status;
ENTER();
// Allocate the Wireless Extensions state structure
phostapdBuf = WLAN_HDD_GET_HOSTAP_STATE_PTR( pAdapter );
// Zero the memory. This zeros the profile structure.
memset(phostapdBuf, 0,sizeof(hdd_hostapd_state_t));
// Set up the pointer to the Wireless Extensions state structure
// NOP
status = hdd_set_hostapd(pAdapter);
if(!VOS_IS_STATUS_SUCCESS(status)) {
VOS_TRACE(VOS_MODULE_ID_HDD, VOS_TRACE_LEVEL_ERROR, ("ERROR: hdd_set_hostapd failed!!\n"));
return status;
}
status = vos_event_init(&phostapdBuf->vosEvent);
if (!VOS_IS_STATUS_SUCCESS(status))
{
VOS_TRACE(VOS_MODULE_ID_HDD, VOS_TRACE_LEVEL_ERROR, ("ERROR: Hostapd HDD vos event init failed!!\n"));
return status;
}
init_completion(&pAdapter->session_close_comp_var);
init_completion(&pAdapter->session_open_comp_var);
sema_init(&(WLAN_HDD_GET_AP_CTX_PTR(pAdapter))->semWpsPBCOverlapInd, 1);
// Register as a wireless device
dev->wireless_handlers = (struct iw_handler_def *)& hostapd_handler_def;
//Initialize the data path module
status = hdd_softap_init_tx_rx(pAdapter);
if ( !VOS_IS_STATUS_SUCCESS( status ))
{
hddLog(VOS_TRACE_LEVEL_FATAL, "%s: hdd_softap_init_tx_rx failed", __func__);
}
status = hdd_wmm_adapter_init( pAdapter );
if (!VOS_IS_STATUS_SUCCESS(status))
{
hddLog(VOS_TRACE_LEVEL_ERROR,
"hdd_wmm_adapter_init() failed with status code %08d [x%08lx]",
status, status );
goto error_wmm_init;
}
set_bit(WMM_INIT_DONE, &pAdapter->event_flags);
wlan_hdd_set_monitor_tx_adapter( WLAN_HDD_GET_CTX(pAdapter), pAdapter );
return status;
error_wmm_init:
hdd_softap_deinit_tx_rx( pAdapter );
EXIT();
return status;
}
hdd_adapter_t* hdd_wlan_create_ap_dev( hdd_context_t *pHddCtx, tSirMacAddr macAddr, tANI_U8 *iface_name )
{
struct net_device *pWlanHostapdDev = NULL;
hdd_adapter_t *pHostapdAdapter = NULL;
v_CONTEXT_t pVosContext= NULL;
pWlanHostapdDev = alloc_netdev_mq(sizeof(hdd_adapter_t), iface_name, ether_setup, NUM_TX_QUEUES);
if (pWlanHostapdDev != NULL)
{
pHostapdAdapter = netdev_priv(pWlanHostapdDev);
//Init the net_device structure
ether_setup(pWlanHostapdDev);
//Initialize the adapter context to zeros.
vos_mem_zero(pHostapdAdapter, sizeof( hdd_adapter_t ));
pHostapdAdapter->dev = pWlanHostapdDev;
pHostapdAdapter->pHddCtx = pHddCtx;
pHostapdAdapter->magic = WLAN_HDD_ADAPTER_MAGIC;
//Get the Global VOSS context.
pVosContext = vos_get_global_context(VOS_MODULE_ID_SYS, NULL);
//Save the adapter context in global context for future.
((VosContextType*)(pVosContext))->pHDDSoftAPContext = (v_VOID_t*)pHostapdAdapter;
//Init the net_device structure
strlcpy(pWlanHostapdDev->name, (const char *)iface_name, IFNAMSIZ);
hdd_set_ap_ops( pHostapdAdapter->dev );
pWlanHostapdDev->tx_queue_len = NET_DEV_TX_QUEUE_LEN;
pWlanHostapdDev->watchdog_timeo = HDD_TX_TIMEOUT;
pWlanHostapdDev->mtu = HDD_DEFAULT_MTU;
vos_mem_copy(pWlanHostapdDev->dev_addr, (void *)macAddr,sizeof(tSirMacAddr));
vos_mem_copy(pHostapdAdapter->macAddressCurrent.bytes, (void *)macAddr, sizeof(tSirMacAddr));
pWlanHostapdDev->destructor = free_netdev;
pWlanHostapdDev->ieee80211_ptr = &pHostapdAdapter->wdev ;
pHostapdAdapter->wdev.wiphy = pHddCtx->wiphy;
pHostapdAdapter->wdev.netdev = pWlanHostapdDev;
init_completion(&pHostapdAdapter->tx_action_cnf_event);
init_completion(&pHostapdAdapter->cancel_rem_on_chan_var);
init_completion(&pHostapdAdapter->rem_on_chan_ready_event);
init_completion(&pHostapdAdapter->ula_complete);
#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,38))
init_completion(&pHostapdAdapter->offchannel_tx_event);
#endif
SET_NETDEV_DEV(pWlanHostapdDev, pHddCtx->parent_dev);
}
return pHostapdAdapter;
}
VOS_STATUS hdd_register_hostapd( hdd_adapter_t *pAdapter, tANI_U8 rtnl_lock_held )
{
struct net_device *dev = pAdapter->dev;
VOS_STATUS status = VOS_STATUS_SUCCESS;
ENTER();
if( rtnl_lock_held )
{
if (strnchr(dev->name, strlen(dev->name), '%')) {
if( dev_alloc_name(dev, dev->name) < 0 )
{
hddLog(VOS_TRACE_LEVEL_FATAL, "%s:Failed:dev_alloc_name", __func__);
return VOS_STATUS_E_FAILURE;
}
}
if (register_netdevice(dev))
{
hddLog(VOS_TRACE_LEVEL_FATAL,
"%s:Failed:register_netdevice", __func__);
return VOS_STATUS_E_FAILURE;
}
}
else
{
if (register_netdev(dev))
{
hddLog(VOS_TRACE_LEVEL_FATAL, "%s: Failed:register_netdev", __func__);
return VOS_STATUS_E_FAILURE;
}
}
set_bit(NET_DEVICE_REGISTERED, &pAdapter->event_flags);
EXIT();
return status;
}
VOS_STATUS hdd_unregister_hostapd(hdd_adapter_t *pAdapter)
{
ENTER();
hdd_softap_deinit_tx_rx(pAdapter);
/* if we are being called during driver unload, then the dev has already
been invalidated. if we are being called at other times, then we can
detatch the wireless device handlers */
if (pAdapter->dev)
{
pAdapter->dev->wireless_handlers = NULL;
}
EXIT();
return 0;
}
| ngxson/android_kernel_sony_msm8x27 | drivers/staging/prima/CORE/HDD/src/wlan_hdd_hostapd.c | C | gpl-2.0 | 113,938 |
! ************************************************************************************************
! Potential of the Carbon Atom with H in asymptotic geometry
! ************************************************************************************************
SUBROUTINE hstick_carbon( rcz, vv )
IMPLICIT NONE
REAL*8 rcz, vv
LOGICAL, DIMENSION(124) :: OptMask
REAL*8, DIMENSION(124) :: Dummy
REAL*8, DIMENSION(124), SAVE :: OptCoord = -0.01
REAL*8 :: EAsymptote = 1.D+100
INTEGER :: iCoord
INTERFACE
REAL*8 FUNCTION FullPotential( Positions, Forces )
REAL*8, DIMENSION(124) :: Positions
REAL*8, DIMENSION(124) :: Forces
END FUNCTION
END INTERFACE
INTERFACE
FUNCTION MinimizePotential( StartX, NMaxIter, GradThresh, Mask ) RESULT( MinPoint )
REAL*8, DIMENSION(:), INTENT(IN) :: StartX
INTEGER, INTENT(IN) :: NMaxIter
REAL*8, INTENT(IN) :: GradThresh
LOGICAL, DIMENSION(size(StartX)), INTENT(IN) :: Mask
REAL*8, DIMENSION(size(StartX)) :: MinPoint
END FUNCTION
END INTERFACE
IF ( EAsymptote > 100.D0 ) THEN
OptCoord = (/ 0.D0, 0.D0, 100.D0, 0.D0, 0.D0, 0.D0, 0.D0, (0.D0, iCoord=8,124) /)
EAsymptote = FullPotential( OptCoord, Dummy(:) )
END IF
! Set optimization constraints
OptMask = (/ (.FALSE., iCoord=1,7), (.TRUE., iCoord=8,124) /)
! Set starting geometry
OptCoord(1:7) = (/ 0.0D0, 0.0D0, 100.0D0, rcz, 0.D0, 0.D0, 0.D0 /)
! Optimize coordinates
OptCoord = MinimizePotential( OptCoord, 10**6, 1.0D-5, OptMask )
! Use optimized coordinates to compute forces and energy
vv = FullPotential( OptCoord, Dummy(:) ) - EAsymptote
END SUBROUTINE hstick_carbon
! ************************************************************************************************
! Potential of the Hydrogen Atom with C fixed in Z = 0
! ************************************************************************************************
SUBROUTINE hstick_hydro( rhx, rhy, rhz, vv )
IMPLICIT NONE
REAL*8 rhx, rhy, rhz, vv
LOGICAL, DIMENSION(124) :: OptMask
REAL*8, DIMENSION(124) :: Dummy
REAL*8, DIMENSION(124), SAVE :: OptCoord = 0.0
INTEGER :: iCoord
REAL*8 :: EAsymptote = 1.D+100
INTERFACE
REAL*8 FUNCTION FullPotential( Positions, Forces )
REAL*8, DIMENSION(124) :: Positions
REAL*8, DIMENSION(124) :: Forces
END FUNCTION
END INTERFACE
INTERFACE
FUNCTION MinimizePotential( StartX, NMaxIter, GradThresh, Mask ) RESULT( MinPoint )
REAL*8, DIMENSION(:), INTENT(IN) :: StartX
INTEGER, INTENT(IN) :: NMaxIter
REAL*8, INTENT(IN) :: GradThresh
LOGICAL, DIMENSION(size(StartX)), INTENT(IN) :: Mask
REAL*8, DIMENSION(size(StartX)) :: MinPoint
END FUNCTION
END INTERFACE
IF ( EAsymptote > 100.D0 ) THEN
OptCoord = (/ 0.D0, 0.D0, 100.D0, 0.D0, 0.D0, 0.D0, 0.D0, (0.D0, iCoord=8,124) /)
EAsymptote = FullPotential( OptCoord, Dummy(:) )
END IF
! Set optimization constraints
OptMask = (/ (.FALSE., iCoord=1,7), (.TRUE., iCoord=8,124) /)
! Set starting geometry
OptCoord(1:7) = (/ rhx, rhy, rhz, 0.0D0, 0.D0, 0.D0, 0.D0 /)
! Optimize coordinates
OptCoord = MinimizePotential( OptCoord, 10**6, 1.0D-5, OptMask )
! Use optimized coordinates to compute forces and energy
vv = FullPotential( OptCoord, Dummy(:) ) - EAsymptote
END SUBROUTINE hstick_hydro
! ************************************************************************************************
! CH Coupling Potential
! ************************************************************************************************
SUBROUTINE hstick_coupling( rhx, rhy, rhz, rcz ,vv )
IMPLICIT NONE
REAL*8 rhx, rhy, rhz, rcz, vv
LOGICAL, DIMENSION(124) :: OptMask
REAL*8, DIMENSION(124) :: Dummy
REAL*8, DIMENSION(124), SAVE :: OptCoord = 0.0
INTEGER :: iCoord
REAL*8 :: vh, vc
REAL*8 :: EAsymptote = 1.D+100
INTERFACE
REAL*8 FUNCTION FullPotential( Positions, Forces )
REAL*8, DIMENSION(124) :: Positions
REAL*8, DIMENSION(124) :: Forces
END FUNCTION
END INTERFACE
INTERFACE
FUNCTION MinimizePotential( StartX, NMaxIter, GradThresh, Mask ) RESULT( MinPoint )
REAL*8, DIMENSION(:), INTENT(IN) :: StartX
INTEGER, INTENT(IN) :: NMaxIter
REAL*8, INTENT(IN) :: GradThresh
LOGICAL, DIMENSION(size(StartX)), INTENT(IN) :: Mask
REAL*8, DIMENSION(size(StartX)) :: MinPoint
END FUNCTION
END INTERFACE
IF ( EAsymptote > 100.D0 ) THEN
OptCoord = (/ 0.D0, 0.D0, 100.D0, 0.D0, 0.D0, 0.D0, 0.D0, (0.D0, iCoord=8,124) /)
EAsymptote = FullPotential( OptCoord, Dummy(:) )
END IF
! Set optimization constraints
OptMask = (/ (.FALSE., iCoord=1,7), (.TRUE., iCoord=8,124) /)
! Set starting geometry
OptCoord(1:7) = (/ rhx, rhy, rhz, rcz, 0.D0, 0.D0, 0.D0 /)
! Optimize coordinates
OptCoord = MinimizePotential( OptCoord, 10**6, 1.0D-5, OptMask )
! Use optimized coordinates to compute forces and energy
vv = FullPotential( OptCoord, Dummy(:) ) - EAsymptote
! Compute H and C contributions
CALL hstick_hydro ( rhx, rhy, rhz, vh )
CALL hstick_carbon( rcz, vc )
! Remove H and C contributions
vv = vv -vh -vc
END SUBROUTINE hstick_coupling
! ************************************************************************************************
! OTHER SUBROUTINES
! ************************************************************************************************
FUNCTION MinimizePotential( StartX, NMaxIter, GradThresh, Mask ) RESULT( MinPoint )
IMPLICIT NONE
REAL*8, DIMENSION(:), INTENT(IN) :: StartX
INTEGER, INTENT(IN) :: NMaxIter
REAL*8, INTENT(IN) :: GradThresh
LOGICAL, DIMENSION(size(StartX)), INTENT(IN) :: Mask
REAL*8, DIMENSION(size(StartX)) :: MinPoint
INTEGER :: NIter, NOpt, n, i
REAL*8 :: GradNorm, V
REAL*8, DIMENSION(size(StartX)) :: Forces
REAL*8, DIMENSION(count(Mask)) :: WrkForces
REAL*8, DIMENSION(count(Mask),count(Mask)) :: Hessian
INTEGER :: Stat
INTERFACE
REAL*8 FUNCTION FullPotential( Positions, Forces )
REAL*8, DIMENSION(124) :: Positions
REAL*8, DIMENSION(124) :: Forces
END FUNCTION
END INTERFACE
INTERFACE
FUNCTION ConstrainedHessian( AtPoint, Mask ) RESULT( Hessian )
REAL*8, DIMENSION(124), INTENT(IN) :: AtPoint
LOGICAL, DIMENSION(124), INTENT(IN) :: Mask
REAL*8, DIMENSION(count(Mask),count(Mask)) :: Hessian
END FUNCTION
END INTERFACE
! Number of non constrained variables
NOpt = COUNT(Mask)
! Start at initial position
MinPoint = StartX
Iterations: DO NIter = 1, NMaxIter
! Compute forces
V = FullPotential( MinPoint, Forces )
! Extract non-constrained forces and compute norm
n = 0
GradNorm = 0
DO i = 1, size(Forces)
IF ( Mask(i) ) THEN
n = n + 1
WrkForces(n) = Forces(i)
GradNorm = GradNorm + Forces(i)**2
END IF
END DO
GradNorm = SQRT( GradNorm/NOpt )
! Check convergence criteria
IF ( GradNorm < GradThresh ) THEN
EXIT Iterations
END IF
! When the gradient is large, switch off newton and use gradient only
IF ( GradNorm < 1.D-5 ) THEN
! Compute hessian
Hessian = ConstrainedHessian( MinPoint, Mask )
! Compute displacement by solution of the equation Hessian * DX = - Grad
CALL DPOTRF( "U", NOpt, Hessian, NOpt, Stat )
IF ( Stat /= 0 ) THEN
PRINT*, " DPOTRF error in MinimizePotential "; STOP
END IF
CALL DPOTRS( "U", NOpt, 1, Hessian, NOpt, WrkForces, NOpt, Stat )
IF ( Stat /= 0 ) THEN
PRINT*, " DPOTRF error in MinimizePotential "; STOP
END IF
END IF
! Move to new coordinates
n = 0
DO i = 1, size(MinPoint)
IF ( Mask(i) ) THEN
n = n + 1
MinPoint(i) = MinPoint(i) + WrkForces(n)
END IF
END DO
END DO Iterations
! Check max number of iterations
IF ( NIter == NMaxIter+1 ) PRINT*, " MinimizePotential: max number of iterations reached "
END FUNCTION MinimizePotential
! ************************************************************************************************
FUNCTION ConstrainedHessian( AtPoint, Mask ) RESULT( Hessian )
IMPLICIT NONE
REAL*8, DIMENSION(124), INTENT(IN) :: AtPoint
LOGICAL, DIMENSION(124), INTENT(IN) :: Mask
REAL*8, DIMENSION(count(Mask),count(Mask)) :: Hessian
REAL*8, DIMENSION(124) :: Coordinates, FirstDerivative
REAL*8 :: Potential
INTEGER :: i, k, l, m, j
REAL, PARAMETER :: SmallDelta = 1.D-04
REAL, DIMENSION(4), PARAMETER :: Deltas = (/ -2.0d0, -1.0d0, +1.0d0, +2.0d0 /)
REAL, DIMENSION(4), PARAMETER :: Coeffs = (/ +1.d0/12.d0, -8.d0/12.d0, +8.d0/12.d0, -1.d0/12.d0 /)
REAL, DIMENSION(3), PARAMETER :: ForwardDeltas = (/ 0.0d0, +1.0d0, +2.0d0 /)
REAL, DIMENSION(3), PARAMETER :: ForwardCoeffs = (/ -3.d0/2.d0, +2.0d0, -1.d0/2.d0 /)
INTERFACE
REAL*8 FUNCTION FullPotential( Positions, Forces )
REAL*8, DIMENSION(124) :: Positions
REAL*8, DIMENSION(124) :: Forces
END FUNCTION
END INTERFACE
Hessian(:,:) = 0.0d0
l = 0
! Compute the second derivatives for displacements of x and y
! IMPORTANT!!! since rho = 0 is a singular value of the function,
! the derivative is computed slightly off the minimum, and is computed for x,y > 0
DO i = 1, 2
IF ( .NOT. Mask(i) ) CYCLE
l = l + 1
DO k = 1, size(ForwardDeltas)
! Define small displacement from the point where compute the derivative
Coordinates(:) = AtPoint(:)
IF ( Coordinates(i) < 0.0d0 ) THEN
Coordinates(i) = - Coordinates(i)
END IF
IF ( Coordinates(i) < 0.001d0 ) THEN
Coordinates(i) = Coordinates(i) + 0.001d0 + ForwardDeltas(k)*SmallDelta
ELSE
Coordinates(i) = Coordinates(i) + ForwardDeltas(k)*SmallDelta
END IF
! Compute potential and forces in the displaced coordinate
Potential = FullPotential( Coordinates, FirstDerivative )
FirstDerivative = - FirstDerivative
! Increment numerical derivative of the analytical derivative
m = 0
DO j = 1, 124
IF ( Mask(j) ) THEN
m = m + 1
Hessian(l,m) = Hessian(l,m) + ForwardCoeffs(k)*FirstDerivative(j)/SmallDelta
END IF
END DO
END DO
END DO
DO i = 3, 124
IF ( .NOT. Mask(i) ) CYCLE
l = l + 1
DO k = 1, size(Deltas)
! Define small displacement from the point where compute the derivative
Coordinates(:) = AtPoint(:)
Coordinates(i) = Coordinates(i) + Deltas(k)*SmallDelta
! Compute potential and forces in the displaced coordinate
Potential = FullPotential( Coordinates, FirstDerivative )
FirstDerivative = - FirstDerivative
! Increment numerical derivative of the analytical derivative
m = 0
DO j = 1, 124
IF ( Mask(j) ) THEN
m = m + 1
Hessian(l,m) = Hessian(l,m) + Coeffs(k)*FirstDerivative(j)/SmallDelta
END IF
END DO
END DO
END DO
END FUNCTION ConstrainedHessian
! ************************************************************************************************
!*******************************************************************************
!> H-Graphene potential by Jackson and coworkers.
!> @ref http://pubs.acs.org/doi/abs/10.1021/jp057136%2B [ J.Phys.Chem.B 2006,110,18811 ]
!> @ref other papers jackson
!*******************************************************************************
FUNCTION FullPotential( Positions, Forces ) RESULT(vv)
IMPLICIT NONE
REAL*8, DIMENSION(124) :: Positions
REAL*8, DIMENSION(124) :: Forces
REAL*8 :: vv
! temporary variables to store positions in Ang units
REAL*8 :: xh, yh, zh
REAL*8, DIMENSION(121) :: z
REAL*8, PARAMETER :: MyConsts_Bohr2Ang = 0.52917721092d0 !< Conversion factor from Bohr to Ang (from NIST )
REAL*8, PARAMETER :: MyConsts_Hartree2eV = 27.21138505d0 !< Conversion factor from Hartree to eV (from NIST )
REAL*8, PARAMETER :: di = 0.00775d0 !< potential well (eV)
REAL*8, PARAMETER :: alphi = 0.954d0 !< curvature (Ang-1)
REAL*8, PARAMETER :: ai = 4.01d0 !< equilibrium position (Ang)
! parameters to describe the behaviour along rho at large rho
REAL*8, PARAMETER :: alp = 1.4d0 !< a_f in the text (Ang-1)
REAL*8, PARAMETER :: alp2 = 1.65d0 !< b_f in the text (Ang-1)
REAL*8, PARAMETER :: ba = 2.9d0 !< c_f in the text (Ang-1)
REAL*8, PARAMETER :: rhoa = 1.0d0 !< rho_f in the text (Ang)
! switching function from small rho to large rho
REAL*8, PARAMETER :: bs = 6.0d0 !< b_s in the text (Ang-1)
REAL*8, PARAMETER :: rhos = 0.53d0 !< rho_s in the text (Ang)
REAL*8, PARAMETER :: delt = 2.651d0 !< twisting potential parameter delta (eV)
REAL*8, PARAMETER :: gam2 = 1.958d0 !< puckering paramter gamma_2 (eV)
REAL*8, PARAMETER :: bndprm = 2.4612d0 !< lattice constant (in Ang)
REAL*8 :: rkc
REAL*8, DIMENSION(121) :: ddz
REAL*8 :: a, b, c1, c2, d0
REAL*8 :: dbdzc, dc1dzc, dc2dzc, dd0dzc, df2dr, dkrdzc, dkrdzh
REAL*8 :: dswdr, dvdzc, dvdzh, dvidzc, dvidzh, dvqdr, dvqdzc
REAL*8 :: dvqdzh, dvtdrho, dvtds1, dvtds2
REAL*8 :: dzgdzc, dzmdzc
REAL*8 :: fexp, ff1, ff2, ff3
REAL*8 :: qqq, rho, rkrho, sub1, sub2, sw
REAL*8 :: v, vi, vlatt, vpuck, vq, vt, vtors
REAL*8 :: zg, zm
INTEGER :: nn
xh = Positions(1) * MyConsts_Bohr2Ang
yh = Positions(2) * MyConsts_Bohr2Ang
zh = Positions(3) * MyConsts_Bohr2Ang
z(1:121) = Positions(4:124) * MyConsts_Bohr2Ang
! Compute some relevant coordinates for the PES
rkc = (36.0*gam2+6.0*delt)/(bndprm**2)
! Q: average Z of C2, C3 and C4 - system-lattice coupling coordinate
qqq=(z(2)+z(3)+z(4))/3.0d0
! positions of H and C1 with respect to Q
sub1=zh-qqq
sub2=z(1)-qqq
! rho
rho=sqrt(xh**2+yh**2)
! **************************************************************************************************
! POTENTIAL FOR THE C-H SYSTEM
! **************************************************************************************************
! Compute the parameters for the morse + gaussian
! functional form for the collinear potential
! D_0 is the morse depth (eV)
d0=0.474801+0.9878257*sub2-1.3921499*sub2**2 &
+0.028278*sub2**3-1.8879928*sub2**4 &
+0.11*exp(-8.0*(sub2-0.28)**2)
dd0dzc=0.9878257-2.7842998*sub2+0.084834*sub2**2- &
7.5519712*sub2**3+( &
-1.76*(sub2-0.28)*exp(-8.0*(sub2-0.28)**2))
! A is the morse curvature (Ang)
a=2.276211
! Z_M is the morse equilibrium distance (Ang)
zm=0.87447*(sub2)+1.17425
dzmdzc=0.87447
! C_1 is the asympotic harmonic potential for C1 vibrations (eV)
c1=0.5*rkc*(sub2)**2-0.00326
dc1dzc=rkc*(sub2)
! C_2 is the gaussian height (eV)
c2= 0.3090344*exp(-2.741813*(sub2-0.2619756))+ &
0.03113325*exp(3.1844857*(sub2-0.186741))+ &
0.02*exp(-20.0*(sub2-0.1)**2)
dc2dzc=-0.8473145*exp(-2.741813*(sub2-0.2619756))+ &
0.0991434*exp(3.1844857*(sub2-0.186741))+( &
-0.8*(sub2-0.1)*exp(-20.0*(sub2-0.1)**2))
! B is the gaussian curvature (Ang-2)
b=4.00181*exp(1.25965*(sub2-0.58729))
dbdzc=5.0408799*exp(1.25965*(sub2-0.58729))
! Z_G is the center of the gaussian (Ang)
zg=1.99155*(sub2)+1.46095
dzgdzc=1.99155
! Compute the potential and the derivatives of the
! collinear potential V_0
v=c1+(c1+d0)*(exp(-2.0*a*(sub1-zm))-2.0*exp(-a*(sub1-zm)))+ &
c2*exp(-b*(sub1-zg)**2)
dvdzh=-b*c2*(sub1-zg)*2.0*exp(-b*(sub1-zg)**2) + &
(c1+d0)*2.0*(-a*exp(-2.0*a*(sub1-zm))+a*exp(-a*(sub1-zm)))
dvdzc=dc1dzc+(dc1dzc+dd0dzc)* &
(exp(-2.0*a*(sub1-zm))-2.0*exp(-a*(sub1-zm)))+ &
(c1+d0)*(a*dzmdzc*2.0*exp(-2.0*a*(sub1-zm))+ &
(-a*dzmdzc)*2.0*exp(-a*(sub1-zm)))+ &
dc2dzc*exp(-b*(sub1-zg)**2)+ &
(-c2*dbdzc*(sub1-zg)**2+c2*b*2.0*(sub1-zg)*dzgdzc)* &
exp(-b*(sub1-zg)**2)
! Compute the force constant (and derivatives) for small rho
! potential rkrho(zh-q,zc-q)
rkrho=3.866259*exp(-17.038588*(sub2-0.537621)**2+ &
0.312355*(sub2-0.537621)*(sub1-2.003753)- &
4.479864*(sub1-2.003753)**2)+ &
4.317415*exp(-11.931770*(sub2-0.286858)**2+ &
18.540974*(sub2-0.286858)*(sub1-1.540947)- &
14.537321*(sub1-1.540947)**2)
dkrdzc=(-34.077176*(sub2-0.537621)+0.312355* &
(sub1-2.003753)) &
*3.866259*exp(-17.038588*(sub2-0.537621)**2+ &
0.312355*(sub2-0.537621)*(sub1-2.003753)- &
4.479864*(sub1-2.003753)**2)+ &
(-23.86354*(sub2-0.286858)+18.540974*(sub1-1.540947)) &
*4.317415*exp(-11.931770*(sub2-0.286858)**2+ &
18.540974*(sub2-0.286858)*(sub1-1.540947)- &
14.537321*(sub1-1.540947)**2)
dkrdzh=(0.312355*(sub2-0.537621)-8.959728*(sub1-2.003753)) &
*3.866259*exp(-17.038588*(sub2-0.537621)**2+ &
0.312355*(sub2-0.537621)*(sub1-2.003753)- &
4.479864*(sub1-2.003753)**2)+ &
(18.540974*(sub2-0.286858)-29.074642*(sub1-1.540947)) &
*4.317415*exp(-11.931770*(sub2-0.286858)**2+ &
18.540974*(sub2-0.286858)*(sub1-1.540947)- &
14.537321*(sub1-1.540947)**2)
! Compute the small rho potential/derivatives
vq=v+0.5*rkrho*rho**2
dvqdzh=dvdzh+0.5*dkrdzh*rho**2
dvqdzc=dvdzc+0.5*dkrdzc*rho**2
dvqdr=rkrho*rho
! Compute the "infinite" rho potential/derivatives
vi=0.5*rkc*sub2**2-0.00326+ &
di*(exp(-2.0*alphi*(sub1-ai))-2.0*exp(-alphi*(sub1-ai)))
dvidzh=di*(-2.0*alphi*exp(-2.0*alphi*(sub1-ai))+ &
2.0*alphi*exp(-alphi*(sub1-ai)))
dvidzc=rkc*sub2
! Switching function and associated functions
fexp=exp(-ba*(rho-rhoa))
ff1=1.0+fexp
ff2=exp(-2.0*alp*rho)-2.0*exp(-alp*rho)*exp(-alp2*rho/ff1)
ff3=(vi-v)*ff2+vi
sw=1.0/(1.0+exp(-bs*(rho-rhos)))
! Total H,C1 potential/derivatives
vt=vq*(1.0-sw)+ff3*sw
df2dr=-2.0*alp*exp(-2.0*alp*rho)- &
2.0*exp(-alp*rho)*exp(-alp2*rho/ff1)* &
(-alp-(alp2/ff1)-alp2*rho*ba*fexp/(ff1**2))
dswdr=(bs*exp(-bs*(rho-rhos)))/((1.0+exp(-bs*(rho-rhos)))**2)
dvtds1=dvqdzh*(1.0-sw)+sw*((dvidzh-dvdzh)*ff2+dvidzh)
dvtds2=dvqdzc*(1.0-sw)+sw*((dvidzc-dvdzc)*ff2+dvidzc)
dvtdrho=dvqdr*(1.0-sw)+vq*(-dswdr)+sw*(vi-v)*df2dr+ff3*dswdr
! **************************************************************************************************
! POTENTIAL FOR THE GRAPHITE LATTICE
! **************************************************************************************************
DO nn = 1, 121
ddz(nn) = 0.0
END DO
vpuck=0.0
vtors=0.0
vtors=vtors+(z(1)-z(5)-z(12)+z(15))**2
ddz(1)=ddz(1)+(delt/bndprm**2)*(z(1)-z(5)-z(12)+z(15))
ddz(5)=ddz(5)-(delt/bndprm**2)*(z(1)-z(5)-z(12)+z(15))
ddz(12)=ddz(12)-(delt/bndprm**2)*(z(1)-z(5)-z(12)+z(15))
ddz(15)=ddz(15)+(delt/bndprm**2)*(z(1)-z(5)-z(12)+z(15))
vtors=vtors+(z(1)-z(7)-z(13)+z(18))**2
ddz(1)=ddz(1)+(delt/bndprm**2)*(z(1)-z(7)-z(13)+z(18))
ddz(7)=ddz(7)-(delt/bndprm**2)*(z(1)-z(7)-z(13)+z(18))
ddz(13)=ddz(13)-(delt/bndprm**2)*(z(1)-z(7)-z(13)+z(18))
ddz(18)=ddz(18)+(delt/bndprm**2)*(z(1)-z(7)-z(13)+z(18))
vtors=vtors+(z(1)-z(9)-z(11)+z(16))**2
ddz(1)=ddz(1)+(delt/bndprm**2)*(z(1)-z(9)-z(11)+z(16))
ddz(9)=ddz(9)-(delt/bndprm**2)*(z(1)-z(9)-z(11)+z(16))
ddz(11)=ddz(11)-(delt/bndprm**2)*(z(1)-z(9)-z(11)+z(16))
ddz(16)=ddz(16)+(delt/bndprm**2)*(z(1)-z(9)-z(11)+z(16))
vtors=vtors+(z(2)-z(3)-z(8)+z(10))**2
ddz(2)=ddz(2)+(delt/bndprm**2)*(z(2)-z(3)-z(8)+z(10))
ddz(3)=ddz(3)-(delt/bndprm**2)*(z(2)-z(3)-z(8)+z(10))
ddz(8)=ddz(8)-(delt/bndprm**2)*(z(2)-z(3)-z(8)+z(10))
ddz(10)=ddz(10)+(delt/bndprm**2)*(z(2)-z(3)-z(8)+z(10))
vtors=vtors+(z(2)-z(11)-z(20)+z(27))**2
ddz(2)=ddz(2)+(delt/bndprm**2)*(z(2)-z(11)-z(20)+z(27))
ddz(11)=ddz(11)-(delt/bndprm**2)*(z(2)-z(11)-z(20)+z(27))
ddz(20)=ddz(20)-(delt/bndprm**2)*(z(2)-z(11)-z(20)+z(27))
ddz(27)=ddz(27)+(delt/bndprm**2)*(z(2)-z(11)-z(20)+z(27))
vtors=vtors+(z(2)-z(14)-z(7)+z(21))**2
ddz(2)=ddz(2)+(delt/bndprm**2)*(z(2)-z(14)-z(7)+z(21))
ddz(14)=ddz(14)-(delt/bndprm**2)*(z(2)-z(14)-z(7)+z(21))
ddz(7)=ddz(7)-(delt/bndprm**2)*(z(2)-z(14)-z(7)+z(21))
ddz(21)=ddz(21)+(delt/bndprm**2)*(z(2)-z(14)-z(7)+z(21))
vtors=vtors+(z(3)-z(11)-z(22)+z(28))**2
ddz(3)=ddz(3)+(delt/bndprm**2)*(z(3)-z(11)-z(22)+z(28))
ddz(11)=ddz(11)-(delt/bndprm**2)*(z(3)-z(11)-z(22)+z(28))
ddz(22)=ddz(22)-(delt/bndprm**2)*(z(3)-z(11)-z(22)+z(28))
ddz(28)=ddz(28)+(delt/bndprm**2)*(z(3)-z(11)-z(22)+z(28))
vtors=vtors+(z(3)-z(16)-z(5)+z(21))**2
ddz(3)=ddz(3)+(delt/bndprm**2)*(z(3)-z(16)-z(5)+z(21))
ddz(16)=ddz(16)-(delt/bndprm**2)*(z(3)-z(16)-z(5)+z(21))
ddz(5)=ddz(5)-(delt/bndprm**2)*(z(3)-z(16)-z(5)+z(21))
ddz(21)=ddz(21)+(delt/bndprm**2)*(z(3)-z(16)-z(5)+z(21))
vtors=vtors+(z(3)-z(18)-z(10)+z(24))**2
ddz(3)=ddz(3)+(delt/bndprm**2)*(z(3)-z(18)-z(10)+z(24))
ddz(18)=ddz(18)-(delt/bndprm**2)*(z(3)-z(18)-z(10)+z(24))
ddz(10)=ddz(10)-(delt/bndprm**2)*(z(3)-z(18)-z(10)+z(24))
ddz(24)=ddz(24)+(delt/bndprm**2)*(z(3)-z(18)-z(10)+z(24))
vtors=vtors+(z(4)-z(2)-z(9)+z(7))**2
ddz(4)=ddz(4)+(delt/bndprm**2)*(z(4)-z(2)-z(9)+z(7))
ddz(2)=ddz(2)-(delt/bndprm**2)*(z(4)-z(2)-z(9)+z(7))
ddz(9)=ddz(9)-(delt/bndprm**2)*(z(4)-z(2)-z(9)+z(7))
ddz(7)=ddz(7)+(delt/bndprm**2)*(z(4)-z(2)-z(9)+z(7))
vtors=vtors+(z(4)-z(3)-z(6)+z(5))**2
ddz(4)=ddz(4)+(delt/bndprm**2)*(z(4)-z(3)-z(6)+z(5))
ddz(3)=ddz(3)-(delt/bndprm**2)*(z(4)-z(3)-z(6)+z(5))
ddz(6)=ddz(6)-(delt/bndprm**2)*(z(4)-z(3)-z(6)+z(5))
ddz(5)=ddz(5)+(delt/bndprm**2)*(z(4)-z(3)-z(6)+z(5))
vtors=vtors+(z(4)-z(13)-z(25)+z(31))**2
ddz(4)=ddz(4)+(delt/bndprm**2)*(z(4)-z(13)-z(25)+z(31))
ddz(13)=ddz(13)-(delt/bndprm**2)*(z(4)-z(13)-z(25)+z(31))
ddz(25)=ddz(25)-(delt/bndprm**2)*(z(4)-z(13)-z(25)+z(31))
ddz(31)=ddz(31)+(delt/bndprm**2)*(z(4)-z(13)-z(25)+z(31))
vtors=vtors+(z(5)-z(7)-z(34)+z(32))**2
ddz(5)=ddz(5)+(delt/bndprm**2)*(z(5)-z(7)-z(34)+z(32))
ddz(7)=ddz(7)-(delt/bndprm**2)*(z(5)-z(7)-z(34)+z(32))
ddz(34)=ddz(34)-(delt/bndprm**2)*(z(5)-z(7)-z(34)+z(32))
ddz(32)=ddz(32)+(delt/bndprm**2)*(z(5)-z(7)-z(34)+z(32))
vtors=vtors+(z(5)-z(27)-z(15)+z(38))**2
ddz(5)=ddz(5)+(delt/bndprm**2)*(z(5)-z(27)-z(15)+z(38))
ddz(27)=ddz(27)-(delt/bndprm**2)*(z(5)-z(27)-z(15)+z(38))
ddz(15)=ddz(15)-(delt/bndprm**2)*(z(5)-z(27)-z(15)+z(38))
ddz(38)=ddz(38)+(delt/bndprm**2)*(z(5)-z(27)-z(15)+z(38))
vtors=vtors+(z(6)-z(1)-z(14)+z(11))**2
ddz(6)=ddz(6)+(delt/bndprm**2)*(z(6)-z(1)-z(14)+z(11))
ddz(1)=ddz(1)-(delt/bndprm**2)*(z(6)-z(1)-z(14)+z(11))
ddz(14)=ddz(14)-(delt/bndprm**2)*(z(6)-z(1)-z(14)+z(11))
ddz(11)=ddz(11)+(delt/bndprm**2)*(z(6)-z(1)-z(14)+z(11))
vtors=vtors+(z(6)-z(20)-z(35)+z(43))**2
ddz(6)=ddz(6)+(delt/bndprm**2)*(z(6)-z(20)-z(35)+z(43))
ddz(20)=ddz(20)-(delt/bndprm**2)*(z(6)-z(20)-z(35)+z(43))
ddz(35)=ddz(35)-(delt/bndprm**2)*(z(6)-z(20)-z(35)+z(43))
ddz(43)=ddz(43)+(delt/bndprm**2)*(z(6)-z(20)-z(35)+z(43))
vtors=vtors+(z(7)-z(22)-z(32)+z(45))**2
ddz(7)=ddz(7)+(delt/bndprm**2)*(z(7)-z(22)-z(32)+z(45))
ddz(22)=ddz(22)-(delt/bndprm**2)*(z(7)-z(22)-z(32)+z(45))
ddz(32)=ddz(32)-(delt/bndprm**2)*(z(7)-z(22)-z(32)+z(45))
ddz(45)=ddz(45)+(delt/bndprm**2)*(z(7)-z(22)-z(32)+z(45))
vtors=vtors+(z(7)-z(28)-z(18)+z(39))**2
ddz(7)=ddz(7)+(delt/bndprm**2)*(z(7)-z(28)-z(18)+z(39))
ddz(28)=ddz(28)-(delt/bndprm**2)*(z(7)-z(28)-z(18)+z(39))
ddz(18)=ddz(18)-(delt/bndprm**2)*(z(7)-z(28)-z(18)+z(39))
ddz(39)=ddz(39)+(delt/bndprm**2)*(z(7)-z(28)-z(18)+z(39))
vtors=vtors+(z(8)-z(1)-z(17)+z(13))**2
ddz(8)=ddz(8)+(delt/bndprm**2)*(z(8)-z(1)-z(17)+z(13))
ddz(1)=ddz(1)-(delt/bndprm**2)*(z(8)-z(1)-z(17)+z(13))
ddz(17)=ddz(17)-(delt/bndprm**2)*(z(8)-z(1)-z(17)+z(13))
ddz(13)=ddz(13)+(delt/bndprm**2)*(z(8)-z(1)-z(17)+z(13))
vtors=vtors+(z(8)-z(6)-z(33)+z(35))**2
ddz(8)=ddz(8)+(delt/bndprm**2)*(z(8)-z(6)-z(33)+z(35))
ddz(6)=ddz(6)-(delt/bndprm**2)*(z(8)-z(6)-z(33)+z(35))
ddz(33)=ddz(33)-(delt/bndprm**2)*(z(8)-z(6)-z(33)+z(35))
ddz(35)=ddz(35)+(delt/bndprm**2)*(z(8)-z(6)-z(33)+z(35))
vtors=vtors+(z(9)-z(22)-z(36)+z(46))**2
ddz(9)=ddz(9)+(delt/bndprm**2)*(z(9)-z(22)-z(36)+z(46))
ddz(22)=ddz(22)-(delt/bndprm**2)*(z(9)-z(22)-z(36)+z(46))
ddz(36)=ddz(36)-(delt/bndprm**2)*(z(9)-z(22)-z(36)+z(46))
ddz(46)=ddz(46)+(delt/bndprm**2)*(z(9)-z(22)-z(36)+z(46))
vtors=vtors+(z(9)-z(30)-z(16)+z(39))**2
ddz(9)=ddz(9)+(delt/bndprm**2)*(z(9)-z(30)-z(16)+z(39))
ddz(30)=ddz(30)-(delt/bndprm**2)*(z(9)-z(30)-z(16)+z(39))
ddz(16)=ddz(16)-(delt/bndprm**2)*(z(9)-z(30)-z(16)+z(39))
ddz(39)=ddz(39)+(delt/bndprm**2)*(z(9)-z(30)-z(16)+z(39))
vtors=vtors+(z(10)-z(1)-z(19)+z(12))**2
ddz(10)=ddz(10)+(delt/bndprm**2)*(z(10)-z(1)-z(19)+z(12))
ddz(1)=ddz(1)-(delt/bndprm**2)*(z(10)-z(1)-z(19)+z(12))
ddz(19)=ddz(19)-(delt/bndprm**2)*(z(10)-z(1)-z(19)+z(12))
ddz(12)=ddz(12)+(delt/bndprm**2)*(z(10)-z(1)-z(19)+z(12))
vtors=vtors+(z(10)-z(9)-z(37)+z(36))**2
ddz(10)=ddz(10)+(delt/bndprm**2)*(z(10)-z(9)-z(37)+z(36))
ddz(9)=ddz(9)-(delt/bndprm**2)*(z(10)-z(9)-z(37)+z(36))
ddz(37)=ddz(37)-(delt/bndprm**2)*(z(10)-z(9)-z(37)+z(36))
ddz(36)=ddz(36)+(delt/bndprm**2)*(z(10)-z(9)-z(37)+z(36))
vtors=vtors+(z(11)-z(32)-z(27)+z(52))**2
ddz(11)=ddz(11)+(delt/bndprm**2)*(z(11)-z(32)-z(27)+z(52))
ddz(32)=ddz(32)-(delt/bndprm**2)*(z(11)-z(32)-z(27)+z(52))
ddz(27)=ddz(27)-(delt/bndprm**2)*(z(11)-z(32)-z(27)+z(52))
ddz(52)=ddz(52)+(delt/bndprm**2)*(z(11)-z(32)-z(27)+z(52))
vtors=vtors+(z(11)-z(34)-z(28)+z(51))**2
ddz(11)=ddz(11)+(delt/bndprm**2)*(z(11)-z(34)-z(28)+z(51))
ddz(34)=ddz(34)-(delt/bndprm**2)*(z(11)-z(34)-z(28)+z(51))
ddz(28)=ddz(28)-(delt/bndprm**2)*(z(11)-z(34)-z(28)+z(51))
ddz(51)=ddz(51)+(delt/bndprm**2)*(z(11)-z(34)-z(28)+z(51))
vtors=vtors+(z(12)-z(2)-z(26)+z(20))**2
ddz(12)=ddz(12)+(delt/bndprm**2)*(z(12)-z(2)-z(26)+z(20))
ddz(2)=ddz(2)-(delt/bndprm**2)*(z(12)-z(2)-z(26)+z(20))
ddz(26)=ddz(26)-(delt/bndprm**2)*(z(12)-z(2)-z(26)+z(20))
ddz(20)=ddz(20)+(delt/bndprm**2)*(z(12)-z(2)-z(26)+z(20))
vtors=vtors+(z(12)-z(4)-z(29)+z(25))**2
ddz(12)=ddz(12)+(delt/bndprm**2)*(z(12)-z(4)-z(29)+z(25))
ddz(4)=ddz(4)-(delt/bndprm**2)*(z(12)-z(4)-z(29)+z(25))
ddz(29)=ddz(29)-(delt/bndprm**2)*(z(12)-z(4)-z(29)+z(25))
ddz(25)=ddz(25)+(delt/bndprm**2)*(z(12)-z(4)-z(29)+z(25))
vtors=vtors+(z(13)-z(3)-z(30)+z(22))**2
ddz(13)=ddz(13)+(delt/bndprm**2)*(z(13)-z(3)-z(30)+z(22))
ddz(3)=ddz(3)-(delt/bndprm**2)*(z(13)-z(3)-z(30)+z(22))
ddz(30)=ddz(30)-(delt/bndprm**2)*(z(13)-z(3)-z(30)+z(22))
ddz(22)=ddz(22)+(delt/bndprm**2)*(z(13)-z(3)-z(30)+z(22))
vtors=vtors+(z(13)-z(36)-z(31)+z(58))**2
ddz(13)=ddz(13)+(delt/bndprm**2)*(z(13)-z(36)-z(31)+z(58))
ddz(36)=ddz(36)-(delt/bndprm**2)*(z(13)-z(36)-z(31)+z(58))
ddz(31)=ddz(31)-(delt/bndprm**2)*(z(13)-z(36)-z(31)+z(58))
ddz(58)=ddz(58)+(delt/bndprm**2)*(z(13)-z(36)-z(31)+z(58))
vtors=vtors+(z(14)-z(34)-z(47)+z(62))**2
ddz(14)=ddz(14)+(delt/bndprm**2)*(z(14)-z(34)-z(47)+z(62))
ddz(34)=ddz(34)-(delt/bndprm**2)*(z(14)-z(34)-z(47)+z(62))
ddz(47)=ddz(47)-(delt/bndprm**2)*(z(14)-z(34)-z(47)+z(62))
ddz(62)=ddz(62)+(delt/bndprm**2)*(z(14)-z(34)-z(47)+z(62))
vtors=vtors+(z(14)-z(42)-z(21)+z(52))**2
ddz(14)=ddz(14)+(delt/bndprm**2)*(z(14)-z(42)-z(21)+z(52))
ddz(42)=ddz(42)-(delt/bndprm**2)*(z(14)-z(42)-z(21)+z(52))
ddz(21)=ddz(21)-(delt/bndprm**2)*(z(14)-z(42)-z(21)+z(52))
ddz(52)=ddz(52)+(delt/bndprm**2)*(z(14)-z(42)-z(21)+z(52))
vtors=vtors+(z(15)-z(2)-z(23)+z(8))**2
ddz(15)=ddz(15)+(delt/bndprm**2)*(z(15)-z(2)-z(23)+z(8))
ddz(2)=ddz(2)-(delt/bndprm**2)*(z(15)-z(2)-z(23)+z(8))
ddz(23)=ddz(23)-(delt/bndprm**2)*(z(15)-z(2)-z(23)+z(8))
ddz(8)=ddz(8)+(delt/bndprm**2)*(z(15)-z(2)-z(23)+z(8))
vtors=vtors+(z(15)-z(14)-z(48)+z(47))**2
ddz(15)=ddz(15)+(delt/bndprm**2)*(z(15)-z(14)-z(48)+z(47))
ddz(14)=ddz(14)-(delt/bndprm**2)*(z(15)-z(14)-z(48)+z(47))
ddz(48)=ddz(48)-(delt/bndprm**2)*(z(15)-z(14)-z(48)+z(47))
ddz(47)=ddz(47)+(delt/bndprm**2)*(z(15)-z(14)-z(48)+z(47))
vtors=vtors+(z(16)-z(32)-z(56)+z(64))**2
ddz(16)=ddz(16)+(delt/bndprm**2)*(z(16)-z(32)-z(56)+z(64))
ddz(32)=ddz(32)-(delt/bndprm**2)*(z(16)-z(32)-z(56)+z(64))
ddz(56)=ddz(56)-(delt/bndprm**2)*(z(16)-z(32)-z(56)+z(64))
ddz(64)=ddz(64)+(delt/bndprm**2)*(z(16)-z(32)-z(56)+z(64))
vtors=vtors+(z(16)-z(45)-z(21)+z(51))**2
ddz(16)=ddz(16)+(delt/bndprm**2)*(z(16)-z(45)-z(21)+z(51))
ddz(45)=ddz(45)-(delt/bndprm**2)*(z(16)-z(45)-z(21)+z(51))
ddz(21)=ddz(21)-(delt/bndprm**2)*(z(16)-z(45)-z(21)+z(51))
ddz(51)=ddz(51)+(delt/bndprm**2)*(z(16)-z(45)-z(21)+z(51))
vtors=vtors+(z(17)-z(4)-z(24)+z(9))**2
ddz(17)=ddz(17)+(delt/bndprm**2)*(z(17)-z(4)-z(24)+z(9))
ddz(4)=ddz(4)-(delt/bndprm**2)*(z(17)-z(4)-z(24)+z(9))
ddz(24)=ddz(24)-(delt/bndprm**2)*(z(17)-z(4)-z(24)+z(9))
ddz(9)=ddz(9)+(delt/bndprm**2)*(z(17)-z(4)-z(24)+z(9))
vtors=vtors+(z(17)-z(37)-z(55)+z(66))**2
ddz(17)=ddz(17)+(delt/bndprm**2)*(z(17)-z(37)-z(55)+z(66))
ddz(37)=ddz(37)-(delt/bndprm**2)*(z(17)-z(37)-z(55)+z(66))
ddz(55)=ddz(55)-(delt/bndprm**2)*(z(17)-z(37)-z(55)+z(66))
ddz(66)=ddz(66)+(delt/bndprm**2)*(z(17)-z(37)-z(55)+z(66))
vtors=vtors+(z(18)-z(16)-z(54)+z(56))**2
ddz(18)=ddz(18)+(delt/bndprm**2)*(z(18)-z(16)-z(54)+z(56))
ddz(16)=ddz(16)-(delt/bndprm**2)*(z(18)-z(16)-z(54)+z(56))
ddz(54)=ddz(54)-(delt/bndprm**2)*(z(18)-z(16)-z(54)+z(56))
ddz(56)=ddz(56)+(delt/bndprm**2)*(z(18)-z(16)-z(54)+z(56))
vtors=vtors+(z(18)-z(46)-z(24)+z(57))**2
ddz(18)=ddz(18)+(delt/bndprm**2)*(z(18)-z(46)-z(24)+z(57))
ddz(46)=ddz(46)-(delt/bndprm**2)*(z(18)-z(46)-z(24)+z(57))
ddz(24)=ddz(24)-(delt/bndprm**2)*(z(18)-z(46)-z(24)+z(57))
ddz(57)=ddz(57)+(delt/bndprm**2)*(z(18)-z(46)-z(24)+z(57))
vtors=vtors+(z(19)-z(4)-z(23)+z(6))**2
ddz(19)=ddz(19)+(delt/bndprm**2)*(z(19)-z(4)-z(23)+z(6))
ddz(4)=ddz(4)-(delt/bndprm**2)*(z(19)-z(4)-z(23)+z(6))
ddz(23)=ddz(23)-(delt/bndprm**2)*(z(19)-z(4)-z(23)+z(6))
ddz(6)=ddz(6)+(delt/bndprm**2)*(z(19)-z(4)-z(23)+z(6))
vtors=vtors+(z(19)-z(17)-z(50)+z(55))**2
ddz(19)=ddz(19)+(delt/bndprm**2)*(z(19)-z(17)-z(50)+z(55))
ddz(17)=ddz(17)-(delt/bndprm**2)*(z(19)-z(17)-z(50)+z(55))
ddz(50)=ddz(50)-(delt/bndprm**2)*(z(19)-z(17)-z(50)+z(55))
ddz(55)=ddz(55)+(delt/bndprm**2)*(z(19)-z(17)-z(50)+z(55))
vtors=vtors+(z(20)-z(5)-z(42)+z(34))**2
ddz(20)=ddz(20)+(delt/bndprm**2)*(z(20)-z(5)-z(42)+z(34))
ddz(5)=ddz(5)-(delt/bndprm**2)*(z(20)-z(5)-z(42)+z(34))
ddz(42)=ddz(42)-(delt/bndprm**2)*(z(20)-z(5)-z(42)+z(34))
ddz(34)=ddz(34)+(delt/bndprm**2)*(z(20)-z(5)-z(42)+z(34))
vtors=vtors+(z(20)-z(47)-z(43)+z(76))**2
ddz(20)=ddz(20)+(delt/bndprm**2)*(z(20)-z(47)-z(43)+z(76))
ddz(47)=ddz(47)-(delt/bndprm**2)*(z(20)-z(47)-z(43)+z(76))
ddz(43)=ddz(43)-(delt/bndprm**2)*(z(20)-z(47)-z(43)+z(76))
ddz(76)=ddz(76)+(delt/bndprm**2)*(z(20)-z(47)-z(43)+z(76))
vtors=vtors+(z(21)-z(28)-z(59)+z(70))**2
ddz(21)=ddz(21)+(delt/bndprm**2)*(z(21)-z(28)-z(59)+z(70))
ddz(28)=ddz(28)-(delt/bndprm**2)*(z(21)-z(28)-z(59)+z(70))
ddz(59)=ddz(59)-(delt/bndprm**2)*(z(21)-z(28)-z(59)+z(70))
ddz(70)=ddz(70)+(delt/bndprm**2)*(z(21)-z(28)-z(59)+z(70))
vtors=vtors+(z(22)-z(54)-z(45)+z(77))**2
ddz(22)=ddz(22)+(delt/bndprm**2)*(z(22)-z(54)-z(45)+z(77))
ddz(54)=ddz(54)-(delt/bndprm**2)*(z(22)-z(54)-z(45)+z(77))
ddz(45)=ddz(45)-(delt/bndprm**2)*(z(22)-z(54)-z(45)+z(77))
ddz(77)=ddz(77)+(delt/bndprm**2)*(z(22)-z(54)-z(45)+z(77))
vtors=vtors+(z(22)-z(56)-z(46)+z(78))**2
ddz(22)=ddz(22)+(delt/bndprm**2)*(z(22)-z(56)-z(46)+z(78))
ddz(56)=ddz(56)-(delt/bndprm**2)*(z(22)-z(56)-z(46)+z(78))
ddz(46)=ddz(46)-(delt/bndprm**2)*(z(22)-z(56)-z(46)+z(78))
ddz(78)=ddz(78)+(delt/bndprm**2)*(z(22)-z(56)-z(46)+z(78))
vtors=vtors+(z(23)-z(26)-z(60)+z(69))**2
ddz(23)=ddz(23)+(delt/bndprm**2)*(z(23)-z(26)-z(60)+z(69))
ddz(26)=ddz(26)-(delt/bndprm**2)*(z(23)-z(26)-z(60)+z(69))
ddz(60)=ddz(60)-(delt/bndprm**2)*(z(23)-z(26)-z(60)+z(69))
ddz(69)=ddz(69)+(delt/bndprm**2)*(z(23)-z(26)-z(60)+z(69))
vtors=vtors+(z(24)-z(30)-z(61)+z(71))**2
ddz(24)=ddz(24)+(delt/bndprm**2)*(z(24)-z(30)-z(61)+z(71))
ddz(30)=ddz(30)-(delt/bndprm**2)*(z(24)-z(30)-z(61)+z(71))
ddz(61)=ddz(61)-(delt/bndprm**2)*(z(24)-z(30)-z(61)+z(71))
ddz(71)=ddz(71)+(delt/bndprm**2)*(z(24)-z(30)-z(61)+z(71))
vtors=vtors+(z(25)-z(8)-z(41)+z(33))**2
ddz(25)=ddz(25)+(delt/bndprm**2)*(z(25)-z(8)-z(41)+z(33))
ddz(8)=ddz(8)-(delt/bndprm**2)*(z(25)-z(8)-z(41)+z(33))
ddz(41)=ddz(41)-(delt/bndprm**2)*(z(25)-z(8)-z(41)+z(33))
ddz(33)=ddz(33)+(delt/bndprm**2)*(z(25)-z(8)-z(41)+z(33))
vtors=vtors+(z(25)-z(10)-z(44)+z(37))**2
ddz(25)=ddz(25)+(delt/bndprm**2)*(z(25)-z(10)-z(44)+z(37))
ddz(10)=ddz(10)-(delt/bndprm**2)*(z(25)-z(10)-z(44)+z(37))
ddz(44)=ddz(44)-(delt/bndprm**2)*(z(25)-z(10)-z(44)+z(37))
ddz(37)=ddz(37)+(delt/bndprm**2)*(z(25)-z(10)-z(44)+z(37))
vtors=vtors+(z(26)-z(6)-z(38)+z(14))**2
ddz(26)=ddz(26)+(delt/bndprm**2)*(z(26)-z(6)-z(38)+z(14))
ddz(6)=ddz(6)-(delt/bndprm**2)*(z(26)-z(6)-z(38)+z(14))
ddz(38)=ddz(38)-(delt/bndprm**2)*(z(26)-z(6)-z(38)+z(14))
ddz(14)=ddz(14)+(delt/bndprm**2)*(z(26)-z(6)-z(38)+z(14))
vtors=vtors+(z(26)-z(48)-z(69)+z(87))**2
ddz(26)=ddz(26)+(delt/bndprm**2)*(z(26)-z(48)-z(69)+z(87))
ddz(48)=ddz(48)-(delt/bndprm**2)*(z(26)-z(48)-z(69)+z(87))
ddz(69)=ddz(69)-(delt/bndprm**2)*(z(26)-z(48)-z(69)+z(87))
ddz(87)=ddz(87)+(delt/bndprm**2)*(z(26)-z(48)-z(69)+z(87))
vtors=vtors+(z(27)-z(21)-z(68)+z(59))**2
ddz(27)=ddz(27)+(delt/bndprm**2)*(z(27)-z(21)-z(68)+z(59))
ddz(21)=ddz(21)-(delt/bndprm**2)*(z(27)-z(21)-z(68)+z(59))
ddz(68)=ddz(68)-(delt/bndprm**2)*(z(27)-z(21)-z(68)+z(59))
ddz(59)=ddz(59)+(delt/bndprm**2)*(z(27)-z(21)-z(68)+z(59))
vtors=vtors+(z(27)-z(62)-z(38)+z(75))**2
ddz(27)=ddz(27)+(delt/bndprm**2)*(z(27)-z(62)-z(38)+z(75))
ddz(62)=ddz(62)-(delt/bndprm**2)*(z(27)-z(62)-z(38)+z(75))
ddz(38)=ddz(38)-(delt/bndprm**2)*(z(27)-z(62)-z(38)+z(75))
ddz(75)=ddz(75)+(delt/bndprm**2)*(z(27)-z(62)-z(38)+z(75))
vtors=vtors+(z(28)-z(56)-z(70)+z(90))**2
ddz(28)=ddz(28)+(delt/bndprm**2)*(z(28)-z(56)-z(70)+z(90))
ddz(56)=ddz(56)-(delt/bndprm**2)*(z(28)-z(56)-z(70)+z(90))
ddz(70)=ddz(70)-(delt/bndprm**2)*(z(28)-z(56)-z(70)+z(90))
ddz(90)=ddz(90)+(delt/bndprm**2)*(z(28)-z(56)-z(70)+z(90))
vtors=vtors+(z(28)-z(64)-z(39)+z(77))**2
ddz(28)=ddz(28)+(delt/bndprm**2)*(z(28)-z(64)-z(39)+z(77))
ddz(64)=ddz(64)-(delt/bndprm**2)*(z(28)-z(64)-z(39)+z(77))
ddz(39)=ddz(39)-(delt/bndprm**2)*(z(28)-z(64)-z(39)+z(77))
ddz(77)=ddz(77)+(delt/bndprm**2)*(z(28)-z(64)-z(39)+z(77))
vtors=vtors+(z(29)-z(8)-z(40)+z(17))**2
ddz(29)=ddz(29)+(delt/bndprm**2)*(z(29)-z(8)-z(40)+z(17))
ddz(8)=ddz(8)-(delt/bndprm**2)*(z(29)-z(8)-z(40)+z(17))
ddz(40)=ddz(40)-(delt/bndprm**2)*(z(29)-z(8)-z(40)+z(17))
ddz(17)=ddz(17)+(delt/bndprm**2)*(z(29)-z(8)-z(40)+z(17))
vtors=vtors+(z(29)-z(23)-z(73)+z(60))**2
ddz(29)=ddz(29)+(delt/bndprm**2)*(z(29)-z(23)-z(73)+z(60))
ddz(23)=ddz(23)-(delt/bndprm**2)*(z(29)-z(23)-z(73)+z(60))
ddz(73)=ddz(73)-(delt/bndprm**2)*(z(29)-z(23)-z(73)+z(60))
ddz(60)=ddz(60)+(delt/bndprm**2)*(z(29)-z(23)-z(73)+z(60))
vtors=vtors+(z(30)-z(54)-z(71)+z(88))**2
ddz(30)=ddz(30)+(delt/bndprm**2)*(z(30)-z(54)-z(71)+z(88))
ddz(54)=ddz(54)-(delt/bndprm**2)*(z(30)-z(54)-z(71)+z(88))
ddz(71)=ddz(71)-(delt/bndprm**2)*(z(30)-z(54)-z(71)+z(88))
ddz(88)=ddz(88)+(delt/bndprm**2)*(z(30)-z(54)-z(71)+z(88))
vtors=vtors+(z(30)-z(65)-z(39)+z(78))**2
ddz(30)=ddz(30)+(delt/bndprm**2)*(z(30)-z(65)-z(39)+z(78))
ddz(65)=ddz(65)-(delt/bndprm**2)*(z(30)-z(65)-z(39)+z(78))
ddz(39)=ddz(39)-(delt/bndprm**2)*(z(30)-z(65)-z(39)+z(78))
ddz(78)=ddz(78)+(delt/bndprm**2)*(z(30)-z(65)-z(39)+z(78))
vtors=vtors+(z(31)-z(10)-z(40)+z(19))**2
ddz(31)=ddz(31)+(delt/bndprm**2)*(z(31)-z(10)-z(40)+z(19))
ddz(10)=ddz(10)-(delt/bndprm**2)*(z(31)-z(10)-z(40)+z(19))
ddz(40)=ddz(40)-(delt/bndprm**2)*(z(31)-z(10)-z(40)+z(19))
ddz(19)=ddz(19)+(delt/bndprm**2)*(z(31)-z(10)-z(40)+z(19))
vtors=vtors+(z(31)-z(24)-z(72)+z(61))**2
ddz(31)=ddz(31)+(delt/bndprm**2)*(z(31)-z(24)-z(72)+z(61))
ddz(24)=ddz(24)-(delt/bndprm**2)*(z(31)-z(24)-z(72)+z(61))
ddz(72)=ddz(72)-(delt/bndprm**2)*(z(31)-z(24)-z(72)+z(61))
ddz(61)=ddz(61)+(delt/bndprm**2)*(z(31)-z(24)-z(72)+z(61))
vtors=vtors+(z(32)-z(59)-z(64)+z(92))**2
ddz(32)=ddz(32)+(delt/bndprm**2)*(z(32)-z(59)-z(64)+z(92))
ddz(59)=ddz(59)-(delt/bndprm**2)*(z(32)-z(59)-z(64)+z(92))
ddz(64)=ddz(64)-(delt/bndprm**2)*(z(32)-z(59)-z(64)+z(92))
ddz(92)=ddz(92)+(delt/bndprm**2)*(z(32)-z(59)-z(64)+z(92))
vtors=vtors+(z(32)-z(70)-z(52)+z(81))**2
ddz(32)=ddz(32)+(delt/bndprm**2)*(z(32)-z(70)-z(52)+z(81))
ddz(70)=ddz(70)-(delt/bndprm**2)*(z(32)-z(70)-z(52)+z(81))
ddz(52)=ddz(52)-(delt/bndprm**2)*(z(32)-z(70)-z(52)+z(81))
ddz(81)=ddz(81)+(delt/bndprm**2)*(z(32)-z(70)-z(52)+z(81))
vtors=vtors+(z(33)-z(12)-z(53)+z(26))**2
ddz(33)=ddz(33)+(delt/bndprm**2)*(z(33)-z(12)-z(53)+z(26))
ddz(12)=ddz(12)-(delt/bndprm**2)*(z(33)-z(12)-z(53)+z(26))
ddz(53)=ddz(53)-(delt/bndprm**2)*(z(33)-z(12)-z(53)+z(26))
ddz(26)=ddz(26)+(delt/bndprm**2)*(z(33)-z(12)-z(53)+z(26))
vtors=vtors+(z(33)-z(19)-z(67)+z(50))**2
ddz(33)=ddz(33)+(delt/bndprm**2)*(z(33)-z(19)-z(67)+z(50))
ddz(19)=ddz(19)-(delt/bndprm**2)*(z(33)-z(19)-z(67)+z(50))
ddz(67)=ddz(67)-(delt/bndprm**2)*(z(33)-z(19)-z(67)+z(50))
ddz(50)=ddz(50)+(delt/bndprm**2)*(z(33)-z(19)-z(67)+z(50))
vtors=vtors+(z(34)-z(59)-z(62)+z(94))**2
ddz(34)=ddz(34)+(delt/bndprm**2)*(z(34)-z(59)-z(62)+z(94))
ddz(59)=ddz(59)-(delt/bndprm**2)*(z(34)-z(59)-z(62)+z(94))
ddz(62)=ddz(62)-(delt/bndprm**2)*(z(34)-z(59)-z(62)+z(94))
ddz(94)=ddz(94)+(delt/bndprm**2)*(z(34)-z(59)-z(62)+z(94))
vtors=vtors+(z(34)-z(68)-z(51)+z(81))**2
ddz(34)=ddz(34)+(delt/bndprm**2)*(z(34)-z(68)-z(51)+z(81))
ddz(68)=ddz(68)-(delt/bndprm**2)*(z(34)-z(68)-z(51)+z(81))
ddz(51)=ddz(51)-(delt/bndprm**2)*(z(34)-z(68)-z(51)+z(81))
ddz(81)=ddz(81)+(delt/bndprm**2)*(z(34)-z(68)-z(51)+z(81))
vtors=vtors+(z(35)-z(12)-z(49)+z(29))**2
ddz(35)=ddz(35)+(delt/bndprm**2)*(z(35)-z(12)-z(49)+z(29))
ddz(12)=ddz(12)-(delt/bndprm**2)*(z(35)-z(12)-z(49)+z(29))
ddz(49)=ddz(49)-(delt/bndprm**2)*(z(35)-z(12)-z(49)+z(29))
ddz(29)=ddz(29)+(delt/bndprm**2)*(z(35)-z(12)-z(49)+z(29))
vtors=vtors+(z(35)-z(15)-z(63)+z(48))**2
ddz(35)=ddz(35)+(delt/bndprm**2)*(z(35)-z(15)-z(63)+z(48))
ddz(15)=ddz(15)-(delt/bndprm**2)*(z(35)-z(15)-z(63)+z(48))
ddz(63)=ddz(63)-(delt/bndprm**2)*(z(35)-z(15)-z(63)+z(48))
ddz(48)=ddz(48)+(delt/bndprm**2)*(z(35)-z(15)-z(63)+z(48))
vtors=vtors+(z(36)-z(18)-z(65)+z(54))**2
ddz(36)=ddz(36)+(delt/bndprm**2)*(z(36)-z(18)-z(65)+z(54))
ddz(18)=ddz(18)-(delt/bndprm**2)*(z(36)-z(18)-z(65)+z(54))
ddz(65)=ddz(65)-(delt/bndprm**2)*(z(36)-z(18)-z(65)+z(54))
ddz(54)=ddz(54)+(delt/bndprm**2)*(z(36)-z(18)-z(65)+z(54))
vtors=vtors+(z(36)-z(71)-z(58)+z(85))**2
ddz(36)=ddz(36)+(delt/bndprm**2)*(z(36)-z(71)-z(58)+z(85))
ddz(71)=ddz(71)-(delt/bndprm**2)*(z(36)-z(71)-z(58)+z(85))
ddz(58)=ddz(58)-(delt/bndprm**2)*(z(36)-z(71)-z(58)+z(85))
ddz(85)=ddz(85)+(delt/bndprm**2)*(z(36)-z(71)-z(58)+z(85))
vtors=vtors+(z(37)-z(13)-z(57)+z(30))**2
ddz(37)=ddz(37)+(delt/bndprm**2)*(z(37)-z(13)-z(57)+z(30))
ddz(13)=ddz(13)-(delt/bndprm**2)*(z(37)-z(13)-z(57)+z(30))
ddz(57)=ddz(57)-(delt/bndprm**2)*(z(37)-z(13)-z(57)+z(30))
ddz(30)=ddz(30)+(delt/bndprm**2)*(z(37)-z(13)-z(57)+z(30))
vtors=vtors+(z(37)-z(61)-z(66)+z(103))**2
ddz(37)=ddz(37)+(delt/bndprm**2)*(z(37)-z(61)-z(66)+z(103))
ddz(61)=ddz(61)-(delt/bndprm**2)*(z(37)-z(61)-z(66)+z(103))
ddz(66)=ddz(66)-(delt/bndprm**2)*(z(37)-z(61)-z(66)+z(103))
ddz(103)=ddz(103)+(delt/bndprm**2)*(z(37)-z(61)-z(66)+z(103))
vtors=vtors+(z(38)-z(42)-z(82)+z(96))**2
ddz(38)=ddz(38)+(delt/bndprm**2)*(z(38)-z(42)-z(82)+z(96))
ddz(42)=ddz(42)-(delt/bndprm**2)*(z(38)-z(42)-z(82)+z(96))
ddz(82)=ddz(82)-(delt/bndprm**2)*(z(38)-z(42)-z(82)+z(96))
ddz(96)=ddz(96)+(delt/bndprm**2)*(z(38)-z(42)-z(82)+z(96))
vtors=vtors+(z(39)-z(45)-z(83)+z(100))**2
ddz(39)=ddz(39)+(delt/bndprm**2)*(z(39)-z(45)-z(83)+z(100))
ddz(45)=ddz(45)-(delt/bndprm**2)*(z(39)-z(45)-z(83)+z(100))
ddz(83)=ddz(83)-(delt/bndprm**2)*(z(39)-z(45)-z(83)+z(100))
ddz(100)=ddz(100)+(delt/bndprm**2)*(z(39)-z(45)-z(83)+z(100))
vtors=vtors+(z(40)-z(44)-z(84)+z(99))**2
ddz(40)=ddz(40)+(delt/bndprm**2)*(z(40)-z(44)-z(84)+z(99))
ddz(44)=ddz(44)-(delt/bndprm**2)*(z(40)-z(44)-z(84)+z(99))
ddz(84)=ddz(84)-(delt/bndprm**2)*(z(40)-z(44)-z(84)+z(99))
ddz(99)=ddz(99)+(delt/bndprm**2)*(z(40)-z(44)-z(84)+z(99))
vtors=vtors+(z(41)-z(19)-z(49)+z(23))**2
ddz(41)=ddz(41)+(delt/bndprm**2)*(z(41)-z(19)-z(49)+z(23))
ddz(19)=ddz(19)-(delt/bndprm**2)*(z(41)-z(19)-z(49)+z(23))
ddz(49)=ddz(49)-(delt/bndprm**2)*(z(41)-z(19)-z(49)+z(23))
ddz(23)=ddz(23)+(delt/bndprm**2)*(z(41)-z(19)-z(49)+z(23))
vtors=vtors+(z(41)-z(40)-z(101)+z(84))**2
ddz(41)=ddz(41)+(delt/bndprm**2)*(z(41)-z(40)-z(101)+z(84))
ddz(40)=ddz(40)-(delt/bndprm**2)*(z(41)-z(40)-z(101)+z(84))
ddz(101)=ddz(101)-(delt/bndprm**2)*(z(41)-z(40)-z(101)+z(84))
ddz(84)=ddz(84)+(delt/bndprm**2)*(z(41)-z(40)-z(101)+z(84))
vtors=vtors+(z(42)-z(68)-z(96)+z(112))**2
ddz(42)=ddz(42)+(delt/bndprm**2)*(z(42)-z(68)-z(96)+z(112))
ddz(68)=ddz(68)-(delt/bndprm**2)*(z(42)-z(68)-z(96)+z(112))
ddz(96)=ddz(96)-(delt/bndprm**2)*(z(42)-z(68)-z(96)+z(112))
ddz(112)=ddz(112)+(delt/bndprm**2)*(z(42)-z(68)-z(96)+z(112))
vtors=vtors+(z(42)-z(86)-z(52)+z(94))**2
ddz(42)=ddz(42)+(delt/bndprm**2)*(z(42)-z(86)-z(52)+z(94))
ddz(86)=ddz(86)-(delt/bndprm**2)*(z(42)-z(86)-z(52)+z(94))
ddz(52)=ddz(52)-(delt/bndprm**2)*(z(42)-z(86)-z(52)+z(94))
ddz(94)=ddz(94)+(delt/bndprm**2)*(z(42)-z(86)-z(52)+z(94))
vtors=vtors+(z(43)-z(15)-z(53)+z(23))**2
ddz(43)=ddz(43)+(delt/bndprm**2)*(z(43)-z(15)-z(53)+z(23))
ddz(15)=ddz(15)-(delt/bndprm**2)*(z(43)-z(15)-z(53)+z(23))
ddz(53)=ddz(53)-(delt/bndprm**2)*(z(43)-z(15)-z(53)+z(23))
ddz(23)=ddz(23)+(delt/bndprm**2)*(z(43)-z(15)-z(53)+z(23))
vtors=vtors+(z(43)-z(38)-z(97)+z(82))**2
ddz(43)=ddz(43)+(delt/bndprm**2)*(z(43)-z(38)-z(97)+z(82))
ddz(38)=ddz(38)-(delt/bndprm**2)*(z(43)-z(38)-z(97)+z(82))
ddz(97)=ddz(97)-(delt/bndprm**2)*(z(43)-z(38)-z(97)+z(82))
ddz(82)=ddz(82)+(delt/bndprm**2)*(z(43)-z(38)-z(97)+z(82))
vtors=vtors+(z(44)-z(17)-z(58)+z(24))**2
ddz(44)=ddz(44)+(delt/bndprm**2)*(z(44)-z(17)-z(58)+z(24))
ddz(17)=ddz(17)-(delt/bndprm**2)*(z(44)-z(17)-z(58)+z(24))
ddz(58)=ddz(58)-(delt/bndprm**2)*(z(44)-z(17)-z(58)+z(24))
ddz(24)=ddz(24)+(delt/bndprm**2)*(z(44)-z(17)-z(58)+z(24))
vtors=vtors+(z(44)-z(72)-z(99)+z(115))**2
ddz(44)=ddz(44)+(delt/bndprm**2)*(z(44)-z(72)-z(99)+z(115))
ddz(72)=ddz(72)-(delt/bndprm**2)*(z(44)-z(72)-z(99)+z(115))
ddz(99)=ddz(99)-(delt/bndprm**2)*(z(44)-z(72)-z(99)+z(115))
ddz(115)=ddz(115)+(delt/bndprm**2)*(z(44)-z(72)-z(99)+z(115))
vtors=vtors+(z(45)-z(70)-z(100)+z(110))**2
ddz(45)=ddz(45)+(delt/bndprm**2)*(z(45)-z(70)-z(100)+z(110))
ddz(70)=ddz(70)-(delt/bndprm**2)*(z(45)-z(70)-z(100)+z(110))
ddz(100)=ddz(100)-(delt/bndprm**2)*(z(45)-z(70)-z(100)+z(110))
ddz(110)=ddz(110)+(delt/bndprm**2)*(z(45)-z(70)-z(100)+z(110))
vtors=vtors+(z(45)-z(90)-z(51)+z(92))**2
ddz(45)=ddz(45)+(delt/bndprm**2)*(z(45)-z(90)-z(51)+z(92))
ddz(90)=ddz(90)-(delt/bndprm**2)*(z(45)-z(90)-z(51)+z(92))
ddz(51)=ddz(51)-(delt/bndprm**2)*(z(45)-z(90)-z(51)+z(92))
ddz(92)=ddz(92)+(delt/bndprm**2)*(z(45)-z(90)-z(51)+z(92))
vtors=vtors+(z(46)-z(39)-z(98)+z(83))**2
ddz(46)=ddz(46)+(delt/bndprm**2)*(z(46)-z(39)-z(98)+z(83))
ddz(39)=ddz(39)-(delt/bndprm**2)*(z(46)-z(39)-z(98)+z(83))
ddz(98)=ddz(98)-(delt/bndprm**2)*(z(46)-z(39)-z(98)+z(83))
ddz(83)=ddz(83)+(delt/bndprm**2)*(z(46)-z(39)-z(98)+z(83))
vtors=vtors+(z(46)-z(88)-z(57)+z(102))**2
ddz(46)=ddz(46)+(delt/bndprm**2)*(z(46)-z(88)-z(57)+z(102))
ddz(88)=ddz(88)-(delt/bndprm**2)*(z(46)-z(88)-z(57)+z(102))
ddz(57)=ddz(57)-(delt/bndprm**2)*(z(46)-z(88)-z(57)+z(102))
ddz(102)=ddz(102)+(delt/bndprm**2)*(z(46)-z(88)-z(57)+z(102))
vtors=vtors+(z(47)-z(27)-z(86)+z(68))**2
ddz(47)=ddz(47)+(delt/bndprm**2)*(z(47)-z(27)-z(86)+z(68))
ddz(27)=ddz(27)-(delt/bndprm**2)*(z(47)-z(27)-z(86)+z(68))
ddz(86)=ddz(86)-(delt/bndprm**2)*(z(47)-z(27)-z(86)+z(68))
ddz(68)=ddz(68)+(delt/bndprm**2)*(z(47)-z(27)-z(86)+z(68))
vtors=vtors+(z(48)-z(20)-z(75)+z(42))**2
ddz(48)=ddz(48)+(delt/bndprm**2)*(z(48)-z(20)-z(75)+z(42))
ddz(20)=ddz(20)-(delt/bndprm**2)*(z(48)-z(20)-z(75)+z(42))
ddz(75)=ddz(75)-(delt/bndprm**2)*(z(48)-z(20)-z(75)+z(42))
ddz(42)=ddz(42)+(delt/bndprm**2)*(z(48)-z(20)-z(75)+z(42))
vtors=vtors+(z(49)-z(53)-z(105)+z(107))**2
ddz(49)=ddz(49)+(delt/bndprm**2)*(z(49)-z(53)-z(105)+z(107))
ddz(53)=ddz(53)-(delt/bndprm**2)*(z(49)-z(53)-z(105)+z(107))
ddz(105)=ddz(105)-(delt/bndprm**2)*(z(49)-z(53)-z(105)+z(107))
ddz(107)=ddz(107)+(delt/bndprm**2)*(z(49)-z(53)-z(105)+z(107))
vtors=vtors+(z(50)-z(25)-z(79)+z(44))**2
ddz(50)=ddz(50)+(delt/bndprm**2)*(z(50)-z(25)-z(79)+z(44))
ddz(25)=ddz(25)-(delt/bndprm**2)*(z(50)-z(25)-z(79)+z(44))
ddz(79)=ddz(79)-(delt/bndprm**2)*(z(50)-z(25)-z(79)+z(44))
ddz(44)=ddz(44)+(delt/bndprm**2)*(z(50)-z(25)-z(79)+z(44))
vtors=vtors+(z(50)-z(29)-z(91)+z(73))**2
ddz(50)=ddz(50)+(delt/bndprm**2)*(z(50)-z(29)-z(91)+z(73))
ddz(29)=ddz(29)-(delt/bndprm**2)*(z(50)-z(29)-z(91)+z(73))
ddz(91)=ddz(91)-(delt/bndprm**2)*(z(50)-z(29)-z(91)+z(73))
ddz(73)=ddz(73)+(delt/bndprm**2)*(z(50)-z(29)-z(91)+z(73))
vtors=vtors+(z(51)-z(64)-z(104)+z(120))**2
ddz(51)=ddz(51)+(delt/bndprm**2)*(z(51)-z(64)-z(104)+z(120))
ddz(64)=ddz(64)-(delt/bndprm**2)*(z(51)-z(64)-z(104)+z(120))
ddz(104)=ddz(104)-(delt/bndprm**2)*(z(51)-z(64)-z(104)+z(120))
ddz(120)=ddz(120)+(delt/bndprm**2)*(z(51)-z(64)-z(104)+z(120))
vtors=vtors+(z(52)-z(51)-z(106)+z(104))**2
ddz(52)=ddz(52)+(delt/bndprm**2)*(z(52)-z(51)-z(106)+z(104))
ddz(51)=ddz(51)-(delt/bndprm**2)*(z(52)-z(51)-z(106)+z(104))
ddz(106)=ddz(106)-(delt/bndprm**2)*(z(52)-z(51)-z(106)+z(104))
ddz(104)=ddz(104)+(delt/bndprm**2)*(z(52)-z(51)-z(106)+z(104))
vtors=vtors+(z(53)-z(63)-z(107)+z(117))**2
ddz(53)=ddz(53)+(delt/bndprm**2)*(z(53)-z(63)-z(107)+z(117))
ddz(63)=ddz(63)-(delt/bndprm**2)*(z(53)-z(63)-z(107)+z(117))
ddz(107)=ddz(107)-(delt/bndprm**2)*(z(53)-z(63)-z(107)+z(117))
ddz(117)=ddz(117)+(delt/bndprm**2)*(z(53)-z(63)-z(107)+z(117))
vtors=vtors+(z(55)-z(25)-z(74)+z(41))**2
ddz(55)=ddz(55)+(delt/bndprm**2)*(z(55)-z(25)-z(74)+z(41))
ddz(25)=ddz(25)-(delt/bndprm**2)*(z(55)-z(25)-z(74)+z(41))
ddz(74)=ddz(74)-(delt/bndprm**2)*(z(55)-z(25)-z(74)+z(41))
ddz(41)=ddz(41)+(delt/bndprm**2)*(z(55)-z(25)-z(74)+z(41))
vtors=vtors+(z(55)-z(31)-z(89)+z(72))**2
ddz(55)=ddz(55)+(delt/bndprm**2)*(z(55)-z(31)-z(89)+z(72))
ddz(31)=ddz(31)-(delt/bndprm**2)*(z(55)-z(31)-z(89)+z(72))
ddz(89)=ddz(89)-(delt/bndprm**2)*(z(55)-z(31)-z(89)+z(72))
ddz(72)=ddz(72)+(delt/bndprm**2)*(z(55)-z(31)-z(89)+z(72))
vtors=vtors+(z(57)-z(65)-z(108)+z(118))**2
ddz(57)=ddz(57)+(delt/bndprm**2)*(z(57)-z(65)-z(108)+z(118))
ddz(65)=ddz(65)-(delt/bndprm**2)*(z(57)-z(65)-z(108)+z(118))
ddz(108)=ddz(108)-(delt/bndprm**2)*(z(57)-z(65)-z(108)+z(118))
ddz(118)=ddz(118)+(delt/bndprm**2)*(z(57)-z(65)-z(108)+z(118))
vtors=vtors+(z(58)-z(57)-z(109)+z(108))**2
ddz(58)=ddz(58)+(delt/bndprm**2)*(z(58)-z(57)-z(109)+z(108))
ddz(57)=ddz(57)-(delt/bndprm**2)*(z(58)-z(57)-z(109)+z(108))
ddz(109)=ddz(109)-(delt/bndprm**2)*(z(58)-z(57)-z(109)+z(108))
ddz(108)=ddz(108)+(delt/bndprm**2)*(z(58)-z(57)-z(109)+z(108))
vtors=vtors+(z(60)-z(33)-z(93)+z(67))**2
ddz(60)=ddz(60)+(delt/bndprm**2)*(z(60)-z(33)-z(93)+z(67))
ddz(33)=ddz(33)-(delt/bndprm**2)*(z(60)-z(33)-z(93)+z(67))
ddz(93)=ddz(93)-(delt/bndprm**2)*(z(60)-z(33)-z(93)+z(67))
ddz(67)=ddz(67)+(delt/bndprm**2)*(z(60)-z(33)-z(93)+z(67))
vtors=vtors+(z(60)-z(35)-z(95)+z(63))**2
ddz(60)=ddz(60)+(delt/bndprm**2)*(z(60)-z(35)-z(95)+z(63))
ddz(35)=ddz(35)-(delt/bndprm**2)*(z(60)-z(35)-z(95)+z(63))
ddz(95)=ddz(95)-(delt/bndprm**2)*(z(60)-z(35)-z(95)+z(63))
ddz(63)=ddz(63)+(delt/bndprm**2)*(z(60)-z(35)-z(95)+z(63))
vtors=vtors+(z(61)-z(36)-z(102)+z(65))**2
ddz(61)=ddz(61)+(delt/bndprm**2)*(z(61)-z(36)-z(102)+z(65))
ddz(36)=ddz(36)-(delt/bndprm**2)*(z(61)-z(36)-z(102)+z(65))
ddz(102)=ddz(102)-(delt/bndprm**2)*(z(61)-z(36)-z(102)+z(65))
ddz(65)=ddz(65)+(delt/bndprm**2)*(z(61)-z(36)-z(102)+z(65))
vtors=vtors+(z(62)-z(52)-z(116)+z(106))**2
ddz(62)=ddz(62)+(delt/bndprm**2)*(z(62)-z(52)-z(116)+z(106))
ddz(52)=ddz(52)-(delt/bndprm**2)*(z(62)-z(52)-z(116)+z(106))
ddz(116)=ddz(116)-(delt/bndprm**2)*(z(62)-z(52)-z(116)+z(106))
ddz(106)=ddz(106)+(delt/bndprm**2)*(z(62)-z(52)-z(116)+z(106))
vtors=vtors+(z(63)-z(26)-z(76)+z(38))**2
ddz(63)=ddz(63)+(delt/bndprm**2)*(z(63)-z(26)-z(76)+z(38))
ddz(26)=ddz(26)-(delt/bndprm**2)*(z(63)-z(26)-z(76)+z(38))
ddz(76)=ddz(76)-(delt/bndprm**2)*(z(63)-z(26)-z(76)+z(38))
ddz(38)=ddz(38)+(delt/bndprm**2)*(z(63)-z(26)-z(76)+z(38))
vtors=vtors+(z(66)-z(31)-z(79)+z(40))**2
ddz(66)=ddz(66)+(delt/bndprm**2)*(z(66)-z(31)-z(79)+z(40))
ddz(31)=ddz(31)-(delt/bndprm**2)*(z(66)-z(31)-z(79)+z(40))
ddz(79)=ddz(79)-(delt/bndprm**2)*(z(66)-z(31)-z(79)+z(40))
ddz(40)=ddz(40)+(delt/bndprm**2)*(z(66)-z(31)-z(79)+z(40))
vtors=vtors+(z(66)-z(58)-z(119)+z(109))**2
ddz(66)=ddz(66)+(delt/bndprm**2)*(z(66)-z(58)-z(119)+z(109))
ddz(58)=ddz(58)-(delt/bndprm**2)*(z(66)-z(58)-z(119)+z(109))
ddz(119)=ddz(119)-(delt/bndprm**2)*(z(66)-z(58)-z(119)+z(109))
ddz(109)=ddz(109)+(delt/bndprm**2)*(z(66)-z(58)-z(119)+z(109))
vtors=vtors+(z(67)-z(29)-z(74)+z(40))**2
ddz(67)=ddz(67)+(delt/bndprm**2)*(z(67)-z(29)-z(74)+z(40))
ddz(29)=ddz(29)-(delt/bndprm**2)*(z(67)-z(29)-z(74)+z(40))
ddz(74)=ddz(74)-(delt/bndprm**2)*(z(67)-z(29)-z(74)+z(40))
ddz(40)=ddz(40)+(delt/bndprm**2)*(z(67)-z(29)-z(74)+z(40))
vtors=vtors+(z(67)-z(49)-z(121)+z(105))**2
ddz(67)=ddz(67)+(delt/bndprm**2)*(z(67)-z(49)-z(121)+z(105))
ddz(49)=ddz(49)-(delt/bndprm**2)*(z(67)-z(49)-z(121)+z(105))
ddz(121)=ddz(121)-(delt/bndprm**2)*(z(67)-z(49)-z(121)+z(105))
ddz(105)=ddz(105)+(delt/bndprm**2)*(z(67)-z(49)-z(121)+z(105))
vtors=vtors+(z(69)-z(35)-z(80)+z(49))**2
ddz(69)=ddz(69)+(delt/bndprm**2)*(z(69)-z(35)-z(80)+z(49))
ddz(35)=ddz(35)-(delt/bndprm**2)*(z(69)-z(35)-z(80)+z(49))
ddz(80)=ddz(80)-(delt/bndprm**2)*(z(69)-z(35)-z(80)+z(49))
ddz(49)=ddz(49)+(delt/bndprm**2)*(z(69)-z(35)-z(80)+z(49))
vtors=vtors+(z(69)-z(43)-z(113)+z(97))**2
ddz(69)=ddz(69)+(delt/bndprm**2)*(z(69)-z(43)-z(113)+z(97))
ddz(43)=ddz(43)-(delt/bndprm**2)*(z(69)-z(43)-z(113)+z(97))
ddz(113)=ddz(113)-(delt/bndprm**2)*(z(69)-z(43)-z(113)+z(97))
ddz(97)=ddz(97)+(delt/bndprm**2)*(z(69)-z(43)-z(113)+z(97))
vtors=vtors+(z(71)-z(46)-z(114)+z(98))**2
ddz(71)=ddz(71)+(delt/bndprm**2)*(z(71)-z(46)-z(114)+z(98))
ddz(46)=ddz(46)-(delt/bndprm**2)*(z(71)-z(46)-z(114)+z(98))
ddz(114)=ddz(114)-(delt/bndprm**2)*(z(71)-z(46)-z(114)+z(98))
ddz(98)=ddz(98)+(delt/bndprm**2)*(z(71)-z(46)-z(114)+z(98))
vtors=vtors+(z(72)-z(37)-z(85)+z(57))**2
ddz(72)=ddz(72)+(delt/bndprm**2)*(z(72)-z(37)-z(85)+z(57))
ddz(37)=ddz(37)-(delt/bndprm**2)*(z(72)-z(37)-z(85)+z(57))
ddz(85)=ddz(85)-(delt/bndprm**2)*(z(72)-z(37)-z(85)+z(57))
ddz(57)=ddz(57)+(delt/bndprm**2)*(z(72)-z(37)-z(85)+z(57))
vtors=vtors+(z(73)-z(33)-z(80)+z(53))**2
ddz(73)=ddz(73)+(delt/bndprm**2)*(z(73)-z(33)-z(80)+z(53))
ddz(33)=ddz(33)-(delt/bndprm**2)*(z(73)-z(33)-z(80)+z(53))
ddz(80)=ddz(80)-(delt/bndprm**2)*(z(73)-z(33)-z(80)+z(53))
ddz(53)=ddz(53)+(delt/bndprm**2)*(z(73)-z(33)-z(80)+z(53))
vtors=vtors+(z(73)-z(41)-z(111)+z(101))**2
ddz(73)=ddz(73)+(delt/bndprm**2)*(z(73)-z(41)-z(111)+z(101))
ddz(41)=ddz(41)-(delt/bndprm**2)*(z(73)-z(41)-z(111)+z(101))
ddz(111)=ddz(111)-(delt/bndprm**2)*(z(73)-z(41)-z(111)+z(101))
ddz(101)=ddz(101)+(delt/bndprm**2)*(z(73)-z(41)-z(111)+z(101))
vtors=vtors+(z(87)-z(43)-z(95)+z(53))**2
ddz(87)=ddz(87)+(delt/bndprm**2)*(z(87)-z(43)-z(95)+z(53))
ddz(43)=ddz(43)-(delt/bndprm**2)*(z(87)-z(43)-z(95)+z(53))
ddz(95)=ddz(95)-(delt/bndprm**2)*(z(87)-z(43)-z(95)+z(53))
ddz(53)=ddz(53)+(delt/bndprm**2)*(z(87)-z(43)-z(95)+z(53))
vtors=vtors+(z(89)-z(44)-z(103)+z(58))**2
ddz(89)=ddz(89)+(delt/bndprm**2)*(z(89)-z(44)-z(103)+z(58))
ddz(44)=ddz(44)-(delt/bndprm**2)*(z(89)-z(44)-z(103)+z(58))
ddz(103)=ddz(103)-(delt/bndprm**2)*(z(89)-z(44)-z(103)+z(58))
ddz(58)=ddz(58)+(delt/bndprm**2)*(z(89)-z(44)-z(103)+z(58))
vtors=vtors+(z(91)-z(41)-z(93)+z(49))**2
ddz(91)=ddz(91)+(delt/bndprm**2)*(z(91)-z(41)-z(93)+z(49))
ddz(41)=ddz(41)-(delt/bndprm**2)*(z(91)-z(41)-z(93)+z(49))
ddz(93)=ddz(93)-(delt/bndprm**2)*(z(91)-z(41)-z(93)+z(49))
ddz(49)=ddz(49)+(delt/bndprm**2)*(z(91)-z(41)-z(93)+z(49))
vtors=vtors*0.5d0*delt/bndprm**2
vpuck=vpuck+(z(2)+z(3)+z(4)-3.0d0*z(1))**2
ddz(1)=ddz(1)-(gam2*9.0d0/bndprm**2)*(z(2)+z(3)+z(4)-3.0d0*z(1))
ddz(2)=ddz(2)+(gam2*3.0d0/bndprm**2)*(z(2)+z(3)+z(4)-3.0d0*z(1))
ddz(3)=ddz(3)+(gam2*3.0d0/bndprm**2)*(z(2)+z(3)+z(4)-3.0d0*z(1))
ddz(4)=ddz(4)+(gam2*3.0d0/bndprm**2)*(z(2)+z(3)+z(4)-3.0d0*z(1))
vpuck=vpuck+(z(1)+z(5)+z(6)-3.0d0*z(2))**2
ddz(2)=ddz(2)-(gam2*9.0d0/bndprm**2)*(z(1)+z(5)+z(6)-3.0d0*z(2))
ddz(1)=ddz(1)+(gam2*3.0d0/bndprm**2)*(z(1)+z(5)+z(6)-3.0d0*z(2))
ddz(5)=ddz(5)+(gam2*3.0d0/bndprm**2)*(z(1)+z(5)+z(6)-3.0d0*z(2))
ddz(6)=ddz(6)+(gam2*3.0d0/bndprm**2)*(z(1)+z(5)+z(6)-3.0d0*z(2))
vpuck=vpuck+(z(1)+z(7)+z(9)-3.0d0*z(3))**2
ddz(3)=ddz(3)-(gam2*9.0d0/bndprm**2)*(z(1)+z(7)+z(9)-3.0d0*z(3))
ddz(1)=ddz(1)+(gam2*3.0d0/bndprm**2)*(z(1)+z(7)+z(9)-3.0d0*z(3))
ddz(7)=ddz(7)+(gam2*3.0d0/bndprm**2)*(z(1)+z(7)+z(9)-3.0d0*z(3))
ddz(9)=ddz(9)+(gam2*3.0d0/bndprm**2)*(z(1)+z(7)+z(9)-3.0d0*z(3))
vpuck=vpuck+(z(1)+z(8)+z(10)-3.0d0*z(4))**2
ddz(4)=ddz(4)-(gam2*9.0d0/bndprm**2)*(z(1)+z(8)+z(10)-3.0d0*z(4))
ddz(1)=ddz(1)+(gam2*3.0d0/bndprm**2)*(z(1)+z(8)+z(10)-3.0d0*z(4))
ddz(8)=ddz(8)+(gam2*3.0d0/bndprm**2)*(z(1)+z(8)+z(10)-3.0d0*z(4))
ddz(10)=ddz(10)+(gam2*3.0d0/bndprm**2)*(z(1)+z(8)+z(10)-3.0d0*z(4))
vpuck=vpuck+(z(2)+z(11)+z(14)-3.0d0*z(5))**2
ddz(5)=ddz(5)-(gam2*9.0d0/bndprm**2)*(z(2)+z(11)+z(14)-3.0d0*z(5))
ddz(2)=ddz(2)+(gam2*3.0d0/bndprm**2)*(z(2)+z(11)+z(14)-3.0d0*z(5))
ddz(11)=ddz(11)+(gam2*3.0d0/bndprm**2)*(z(2)+z(11)+z(14)-3.0d0*z(5))
ddz(14)=ddz(14)+(gam2*3.0d0/bndprm**2)*(z(2)+z(11)+z(14)-3.0d0*z(5))
vpuck=vpuck+(z(2)+z(12)+z(15)-3.0d0*z(6))**2
ddz(6)=ddz(6)-(gam2*9.0d0/bndprm**2)*(z(2)+z(12)+z(15)-3.0d0*z(6))
ddz(2)=ddz(2)+(gam2*3.0d0/bndprm**2)*(z(2)+z(12)+z(15)-3.0d0*z(6))
ddz(12)=ddz(12)+(gam2*3.0d0/bndprm**2)*(z(2)+z(12)+z(15)-3.0d0*z(6))
ddz(15)=ddz(15)+(gam2*3.0d0/bndprm**2)*(z(2)+z(12)+z(15)-3.0d0*z(6))
vpuck=vpuck+(z(3)+z(11)+z(16)-3.0d0*z(7))**2
ddz(7)=ddz(7)-(gam2*9.0d0/bndprm**2)*(z(3)+z(11)+z(16)-3.0d0*z(7))
ddz(3)=ddz(3)+(gam2*3.0d0/bndprm**2)*(z(3)+z(11)+z(16)-3.0d0*z(7))
ddz(11)=ddz(11)+(gam2*3.0d0/bndprm**2)*(z(3)+z(11)+z(16)-3.0d0*z(7))
ddz(16)=ddz(16)+(gam2*3.0d0/bndprm**2)*(z(3)+z(11)+z(16)-3.0d0*z(7))
vpuck=vpuck+(z(4)+z(12)+z(19)-3.0d0*z(8))**2
ddz(8)=ddz(8)-(gam2*9.0d0/bndprm**2)*(z(4)+z(12)+z(19)-3.0d0*z(8))
ddz(4)=ddz(4)+(gam2*3.0d0/bndprm**2)*(z(4)+z(12)+z(19)-3.0d0*z(8))
ddz(12)=ddz(12)+(gam2*3.0d0/bndprm**2)*(z(4)+z(12)+z(19)-3.0d0*z(8))
ddz(19)=ddz(19)+(gam2*3.0d0/bndprm**2)*(z(4)+z(12)+z(19)-3.0d0*z(8))
vpuck=vpuck+(z(3)+z(13)+z(18)-3.0d0*z(9))**2
ddz(9)=ddz(9)-(gam2*9.0d0/bndprm**2)*(z(3)+z(13)+z(18)-3.0d0*z(9))
ddz(3)=ddz(3)+(gam2*3.0d0/bndprm**2)*(z(3)+z(13)+z(18)-3.0d0*z(9))
ddz(13)=ddz(13)+(gam2*3.0d0/bndprm**2)*(z(3)+z(13)+z(18)-3.0d0*z(9))
ddz(18)=ddz(18)+(gam2*3.0d0/bndprm**2)*(z(3)+z(13)+z(18)-3.0d0*z(9))
vpuck=vpuck+(z(4)+z(13)+z(17)-3.0d0*z(10))**2
ddz(10)=ddz(10)-(gam2*9.0d0/bndprm**2)*(z(4)+z(13)+z(17)-3.0d0*z(10))
ddz(4)=ddz(4)+(gam2*3.0d0/bndprm**2)*(z(4)+z(13)+z(17)-3.0d0*z(10))
ddz(13)=ddz(13)+(gam2*3.0d0/bndprm**2)*(z(4)+z(13)+z(17)-3.0d0*z(10))
ddz(17)=ddz(17)+(gam2*3.0d0/bndprm**2)*(z(4)+z(13)+z(17)-3.0d0*z(10))
vpuck=vpuck+(z(5)+z(7)+z(21)-3.0d0*z(11))**2
ddz(11)=ddz(11)-(gam2*9.0d0/bndprm**2)*(z(5)+z(7)+z(21)-3.0d0*z(11))
ddz(5)=ddz(5)+(gam2*3.0d0/bndprm**2)*(z(5)+z(7)+z(21)-3.0d0*z(11))
ddz(7)=ddz(7)+(gam2*3.0d0/bndprm**2)*(z(5)+z(7)+z(21)-3.0d0*z(11))
ddz(21)=ddz(21)+(gam2*3.0d0/bndprm**2)*(z(5)+z(7)+z(21)-3.0d0*z(11))
vpuck=vpuck+(z(6)+z(8)+z(23)-3.0d0*z(12))**2
ddz(12)=ddz(12)-(gam2*9.0d0/bndprm**2)*(z(6)+z(8)+z(23)-3.0d0*z(12))
ddz(6)=ddz(6)+(gam2*3.0d0/bndprm**2)*(z(6)+z(8)+z(23)-3.0d0*z(12))
ddz(8)=ddz(8)+(gam2*3.0d0/bndprm**2)*(z(6)+z(8)+z(23)-3.0d0*z(12))
ddz(23)=ddz(23)+(gam2*3.0d0/bndprm**2)*(z(6)+z(8)+z(23)-3.0d0*z(12))
vpuck=vpuck+(z(9)+z(10)+z(24)-3.0d0*z(13))**2
ddz(13)=ddz(13)-(gam2*9.0d0/bndprm**2)*(z(9)+z(10)+z(24)-3.0d0*z(13))
ddz(9)=ddz(9)+(gam2*3.0d0/bndprm**2)*(z(9)+z(10)+z(24)-3.0d0*z(13))
ddz(10)=ddz(10)+(gam2*3.0d0/bndprm**2)*(z(9)+z(10)+z(24)-3.0d0*z(13))
ddz(24)=ddz(24)+(gam2*3.0d0/bndprm**2)*(z(9)+z(10)+z(24)-3.0d0*z(13))
vpuck=vpuck+(z(5)+z(20)+z(27)-3.0d0*z(14))**2
ddz(14)=ddz(14)-(gam2*9.0d0/bndprm**2)*(z(5)+z(20)+z(27)-3.0d0*z(14))
ddz(5)=ddz(5)+(gam2*3.0d0/bndprm**2)*(z(5)+z(20)+z(27)-3.0d0*z(14))
ddz(20)=ddz(20)+(gam2*3.0d0/bndprm**2)*(z(5)+z(20)+z(27)-3.0d0*z(14))
ddz(27)=ddz(27)+(gam2*3.0d0/bndprm**2)*(z(5)+z(20)+z(27)-3.0d0*z(14))
vpuck=vpuck+(z(6)+z(20)+z(26)-3.0d0*z(15))**2
ddz(15)=ddz(15)-(gam2*9.0d0/bndprm**2)*(z(6)+z(20)+z(26)-3.0d0*z(15))
ddz(6)=ddz(6)+(gam2*3.0d0/bndprm**2)*(z(6)+z(20)+z(26)-3.0d0*z(15))
ddz(20)=ddz(20)+(gam2*3.0d0/bndprm**2)*(z(6)+z(20)+z(26)-3.0d0*z(15))
ddz(26)=ddz(26)+(gam2*3.0d0/bndprm**2)*(z(6)+z(20)+z(26)-3.0d0*z(15))
vpuck=vpuck+(z(7)+z(22)+z(28)-3.0d0*z(16))**2
ddz(16)=ddz(16)-(gam2*9.0d0/bndprm**2)*(z(7)+z(22)+z(28)-3.0d0*z(16))
ddz(7)=ddz(7)+(gam2*3.0d0/bndprm**2)*(z(7)+z(22)+z(28)-3.0d0*z(16))
ddz(22)=ddz(22)+(gam2*3.0d0/bndprm**2)*(z(7)+z(22)+z(28)-3.0d0*z(16))
ddz(28)=ddz(28)+(gam2*3.0d0/bndprm**2)*(z(7)+z(22)+z(28)-3.0d0*z(16))
vpuck=vpuck+(z(10)+z(25)+z(31)-3.0d0*z(17))**2
ddz(17)=ddz(17)-(gam2*9.0d0/bndprm**2)*(z(10)+z(25)+z(31)-3.0d0*z(17))
ddz(10)=ddz(10)+(gam2*3.0d0/bndprm**2)*(z(10)+z(25)+z(31)-3.0d0*z(17))
ddz(25)=ddz(25)+(gam2*3.0d0/bndprm**2)*(z(10)+z(25)+z(31)-3.0d0*z(17))
ddz(31)=ddz(31)+(gam2*3.0d0/bndprm**2)*(z(10)+z(25)+z(31)-3.0d0*z(17))
vpuck=vpuck+(z(9)+z(22)+z(30)-3.0d0*z(18))**2
ddz(18)=ddz(18)-(gam2*9.0d0/bndprm**2)*(z(9)+z(22)+z(30)-3.0d0*z(18))
ddz(9)=ddz(9)+(gam2*3.0d0/bndprm**2)*(z(9)+z(22)+z(30)-3.0d0*z(18))
ddz(22)=ddz(22)+(gam2*3.0d0/bndprm**2)*(z(9)+z(22)+z(30)-3.0d0*z(18))
ddz(30)=ddz(30)+(gam2*3.0d0/bndprm**2)*(z(9)+z(22)+z(30)-3.0d0*z(18))
vpuck=vpuck+(z(8)+z(25)+z(29)-3.0d0*z(19))**2
ddz(19)=ddz(19)-(gam2*9.0d0/bndprm**2)*(z(8)+z(25)+z(29)-3.0d0*z(19))
ddz(8)=ddz(8)+(gam2*3.0d0/bndprm**2)*(z(8)+z(25)+z(29)-3.0d0*z(19))
ddz(25)=ddz(25)+(gam2*3.0d0/bndprm**2)*(z(8)+z(25)+z(29)-3.0d0*z(19))
ddz(29)=ddz(29)+(gam2*3.0d0/bndprm**2)*(z(8)+z(25)+z(29)-3.0d0*z(19))
vpuck=vpuck+(z(14)+z(15)+z(38)-3.0d0*z(20))**2
ddz(20)=ddz(20)-(gam2*9.0d0/bndprm**2)*(z(14)+z(15)+z(38)-3.0d0*z(20))
ddz(14)=ddz(14)+(gam2*3.0d0/bndprm**2)*(z(14)+z(15)+z(38)-3.0d0*z(20))
ddz(15)=ddz(15)+(gam2*3.0d0/bndprm**2)*(z(14)+z(15)+z(38)-3.0d0*z(20))
ddz(38)=ddz(38)+(gam2*3.0d0/bndprm**2)*(z(14)+z(15)+z(38)-3.0d0*z(20))
vpuck=vpuck+(z(11)+z(32)+z(34)-3.0d0*z(21))**2
ddz(21)=ddz(21)-(gam2*9.0d0/bndprm**2)*(z(11)+z(32)+z(34)-3.0d0*z(21))
ddz(11)=ddz(11)+(gam2*3.0d0/bndprm**2)*(z(11)+z(32)+z(34)-3.0d0*z(21))
ddz(32)=ddz(32)+(gam2*3.0d0/bndprm**2)*(z(11)+z(32)+z(34)-3.0d0*z(21))
ddz(34)=ddz(34)+(gam2*3.0d0/bndprm**2)*(z(11)+z(32)+z(34)-3.0d0*z(21))
vpuck=vpuck+(z(16)+z(18)+z(39)-3.0d0*z(22))**2
ddz(22)=ddz(22)-(gam2*9.0d0/bndprm**2)*(z(16)+z(18)+z(39)-3.0d0*z(22))
ddz(16)=ddz(16)+(gam2*3.0d0/bndprm**2)*(z(16)+z(18)+z(39)-3.0d0*z(22))
ddz(18)=ddz(18)+(gam2*3.0d0/bndprm**2)*(z(16)+z(18)+z(39)-3.0d0*z(22))
ddz(39)=ddz(39)+(gam2*3.0d0/bndprm**2)*(z(16)+z(18)+z(39)-3.0d0*z(22))
vpuck=vpuck+(z(12)+z(33)+z(35)-3.0d0*z(23))**2
ddz(23)=ddz(23)-(gam2*9.0d0/bndprm**2)*(z(12)+z(33)+z(35)-3.0d0*z(23))
ddz(12)=ddz(12)+(gam2*3.0d0/bndprm**2)*(z(12)+z(33)+z(35)-3.0d0*z(23))
ddz(33)=ddz(33)+(gam2*3.0d0/bndprm**2)*(z(12)+z(33)+z(35)-3.0d0*z(23))
ddz(35)=ddz(35)+(gam2*3.0d0/bndprm**2)*(z(12)+z(33)+z(35)-3.0d0*z(23))
vpuck=vpuck+(z(13)+z(36)+z(37)-3.0d0*z(24))**2
ddz(24)=ddz(24)-(gam2*9.0d0/bndprm**2)*(z(13)+z(36)+z(37)-3.0d0*z(24))
ddz(13)=ddz(13)+(gam2*3.0d0/bndprm**2)*(z(13)+z(36)+z(37)-3.0d0*z(24))
ddz(36)=ddz(36)+(gam2*3.0d0/bndprm**2)*(z(13)+z(36)+z(37)-3.0d0*z(24))
ddz(37)=ddz(37)+(gam2*3.0d0/bndprm**2)*(z(13)+z(36)+z(37)-3.0d0*z(24))
vpuck=vpuck+(z(17)+z(19)+z(40)-3.0d0*z(25))**2
ddz(25)=ddz(25)-(gam2*9.0d0/bndprm**2)*(z(17)+z(19)+z(40)-3.0d0*z(25))
ddz(17)=ddz(17)+(gam2*3.0d0/bndprm**2)*(z(17)+z(19)+z(40)-3.0d0*z(25))
ddz(19)=ddz(19)+(gam2*3.0d0/bndprm**2)*(z(17)+z(19)+z(40)-3.0d0*z(25))
ddz(40)=ddz(40)+(gam2*3.0d0/bndprm**2)*(z(17)+z(19)+z(40)-3.0d0*z(25))
vpuck=vpuck+(z(15)+z(35)+z(43)-3.0d0*z(26))**2
ddz(26)=ddz(26)-(gam2*9.0d0/bndprm**2)*(z(15)+z(35)+z(43)-3.0d0*z(26))
ddz(15)=ddz(15)+(gam2*3.0d0/bndprm**2)*(z(15)+z(35)+z(43)-3.0d0*z(26))
ddz(35)=ddz(35)+(gam2*3.0d0/bndprm**2)*(z(15)+z(35)+z(43)-3.0d0*z(26))
ddz(43)=ddz(43)+(gam2*3.0d0/bndprm**2)*(z(15)+z(35)+z(43)-3.0d0*z(26))
vpuck=vpuck+(z(14)+z(34)+z(42)-3.0d0*z(27))**2
ddz(27)=ddz(27)-(gam2*9.0d0/bndprm**2)*(z(14)+z(34)+z(42)-3.0d0*z(27))
ddz(14)=ddz(14)+(gam2*3.0d0/bndprm**2)*(z(14)+z(34)+z(42)-3.0d0*z(27))
ddz(34)=ddz(34)+(gam2*3.0d0/bndprm**2)*(z(14)+z(34)+z(42)-3.0d0*z(27))
ddz(42)=ddz(42)+(gam2*3.0d0/bndprm**2)*(z(14)+z(34)+z(42)-3.0d0*z(27))
vpuck=vpuck+(z(16)+z(32)+z(45)-3.0d0*z(28))**2
ddz(28)=ddz(28)-(gam2*9.0d0/bndprm**2)*(z(16)+z(32)+z(45)-3.0d0*z(28))
ddz(16)=ddz(16)+(gam2*3.0d0/bndprm**2)*(z(16)+z(32)+z(45)-3.0d0*z(28))
ddz(32)=ddz(32)+(gam2*3.0d0/bndprm**2)*(z(16)+z(32)+z(45)-3.0d0*z(28))
ddz(45)=ddz(45)+(gam2*3.0d0/bndprm**2)*(z(16)+z(32)+z(45)-3.0d0*z(28))
vpuck=vpuck+(z(19)+z(33)+z(41)-3.0d0*z(29))**2
ddz(29)=ddz(29)-(gam2*9.0d0/bndprm**2)*(z(19)+z(33)+z(41)-3.0d0*z(29))
ddz(19)=ddz(19)+(gam2*3.0d0/bndprm**2)*(z(19)+z(33)+z(41)-3.0d0*z(29))
ddz(33)=ddz(33)+(gam2*3.0d0/bndprm**2)*(z(19)+z(33)+z(41)-3.0d0*z(29))
ddz(41)=ddz(41)+(gam2*3.0d0/bndprm**2)*(z(19)+z(33)+z(41)-3.0d0*z(29))
vpuck=vpuck+(z(18)+z(36)+z(46)-3.0d0*z(30))**2
ddz(30)=ddz(30)-(gam2*9.0d0/bndprm**2)*(z(18)+z(36)+z(46)-3.0d0*z(30))
ddz(18)=ddz(18)+(gam2*3.0d0/bndprm**2)*(z(18)+z(36)+z(46)-3.0d0*z(30))
ddz(36)=ddz(36)+(gam2*3.0d0/bndprm**2)*(z(18)+z(36)+z(46)-3.0d0*z(30))
ddz(46)=ddz(46)+(gam2*3.0d0/bndprm**2)*(z(18)+z(36)+z(46)-3.0d0*z(30))
vpuck=vpuck+(z(17)+z(37)+z(44)-3.0d0*z(31))**2
ddz(31)=ddz(31)-(gam2*9.0d0/bndprm**2)*(z(17)+z(37)+z(44)-3.0d0*z(31))
ddz(17)=ddz(17)+(gam2*3.0d0/bndprm**2)*(z(17)+z(37)+z(44)-3.0d0*z(31))
ddz(37)=ddz(37)+(gam2*3.0d0/bndprm**2)*(z(17)+z(37)+z(44)-3.0d0*z(31))
ddz(44)=ddz(44)+(gam2*3.0d0/bndprm**2)*(z(17)+z(37)+z(44)-3.0d0*z(31))
vpuck=vpuck+(z(21)+z(28)+z(51)-3.0d0*z(32))**2
ddz(32)=ddz(32)-(gam2*9.0d0/bndprm**2)*(z(21)+z(28)+z(51)-3.0d0*z(32))
ddz(21)=ddz(21)+(gam2*3.0d0/bndprm**2)*(z(21)+z(28)+z(51)-3.0d0*z(32))
ddz(28)=ddz(28)+(gam2*3.0d0/bndprm**2)*(z(21)+z(28)+z(51)-3.0d0*z(32))
ddz(51)=ddz(51)+(gam2*3.0d0/bndprm**2)*(z(21)+z(28)+z(51)-3.0d0*z(32))
vpuck=vpuck+(z(23)+z(29)+z(49)-3.0d0*z(33))**2
ddz(33)=ddz(33)-(gam2*9.0d0/bndprm**2)*(z(23)+z(29)+z(49)-3.0d0*z(33))
ddz(23)=ddz(23)+(gam2*3.0d0/bndprm**2)*(z(23)+z(29)+z(49)-3.0d0*z(33))
ddz(29)=ddz(29)+(gam2*3.0d0/bndprm**2)*(z(23)+z(29)+z(49)-3.0d0*z(33))
ddz(49)=ddz(49)+(gam2*3.0d0/bndprm**2)*(z(23)+z(29)+z(49)-3.0d0*z(33))
vpuck=vpuck+(z(21)+z(27)+z(52)-3.0d0*z(34))**2
ddz(34)=ddz(34)-(gam2*9.0d0/bndprm**2)*(z(21)+z(27)+z(52)-3.0d0*z(34))
ddz(21)=ddz(21)+(gam2*3.0d0/bndprm**2)*(z(21)+z(27)+z(52)-3.0d0*z(34))
ddz(27)=ddz(27)+(gam2*3.0d0/bndprm**2)*(z(21)+z(27)+z(52)-3.0d0*z(34))
ddz(52)=ddz(52)+(gam2*3.0d0/bndprm**2)*(z(21)+z(27)+z(52)-3.0d0*z(34))
vpuck=vpuck+(z(23)+z(26)+z(53)-3.0d0*z(35))**2
ddz(35)=ddz(35)-(gam2*9.0d0/bndprm**2)*(z(23)+z(26)+z(53)-3.0d0*z(35))
ddz(23)=ddz(23)+(gam2*3.0d0/bndprm**2)*(z(23)+z(26)+z(53)-3.0d0*z(35))
ddz(26)=ddz(26)+(gam2*3.0d0/bndprm**2)*(z(23)+z(26)+z(53)-3.0d0*z(35))
ddz(53)=ddz(53)+(gam2*3.0d0/bndprm**2)*(z(23)+z(26)+z(53)-3.0d0*z(35))
vpuck=vpuck+(z(24)+z(30)+z(57)-3.0d0*z(36))**2
ddz(36)=ddz(36)-(gam2*9.0d0/bndprm**2)*(z(24)+z(30)+z(57)-3.0d0*z(36))
ddz(24)=ddz(24)+(gam2*3.0d0/bndprm**2)*(z(24)+z(30)+z(57)-3.0d0*z(36))
ddz(30)=ddz(30)+(gam2*3.0d0/bndprm**2)*(z(24)+z(30)+z(57)-3.0d0*z(36))
ddz(57)=ddz(57)+(gam2*3.0d0/bndprm**2)*(z(24)+z(30)+z(57)-3.0d0*z(36))
vpuck=vpuck+(z(24)+z(31)+z(58)-3.0d0*z(37))**2
ddz(37)=ddz(37)-(gam2*9.0d0/bndprm**2)*(z(24)+z(31)+z(58)-3.0d0*z(37))
ddz(24)=ddz(24)+(gam2*3.0d0/bndprm**2)*(z(24)+z(31)+z(58)-3.0d0*z(37))
ddz(31)=ddz(31)+(gam2*3.0d0/bndprm**2)*(z(24)+z(31)+z(58)-3.0d0*z(37))
ddz(58)=ddz(58)+(gam2*3.0d0/bndprm**2)*(z(24)+z(31)+z(58)-3.0d0*z(37))
vpuck=vpuck+(z(20)+z(47)+z(48)-3.0d0*z(38))**2
ddz(38)=ddz(38)-(gam2*9.0d0/bndprm**2)*(z(20)+z(47)+z(48)-3.0d0*z(38))
ddz(20)=ddz(20)+(gam2*3.0d0/bndprm**2)*(z(20)+z(47)+z(48)-3.0d0*z(38))
ddz(47)=ddz(47)+(gam2*3.0d0/bndprm**2)*(z(20)+z(47)+z(48)-3.0d0*z(38))
ddz(48)=ddz(48)+(gam2*3.0d0/bndprm**2)*(z(20)+z(47)+z(48)-3.0d0*z(38))
vpuck=vpuck+(z(22)+z(54)+z(56)-3.0d0*z(39))**2
ddz(39)=ddz(39)-(gam2*9.0d0/bndprm**2)*(z(22)+z(54)+z(56)-3.0d0*z(39))
ddz(22)=ddz(22)+(gam2*3.0d0/bndprm**2)*(z(22)+z(54)+z(56)-3.0d0*z(39))
ddz(54)=ddz(54)+(gam2*3.0d0/bndprm**2)*(z(22)+z(54)+z(56)-3.0d0*z(39))
ddz(56)=ddz(56)+(gam2*3.0d0/bndprm**2)*(z(22)+z(54)+z(56)-3.0d0*z(39))
vpuck=vpuck+(z(25)+z(50)+z(55)-3.0d0*z(40))**2
ddz(40)=ddz(40)-(gam2*9.0d0/bndprm**2)*(z(25)+z(50)+z(55)-3.0d0*z(40))
ddz(25)=ddz(25)+(gam2*3.0d0/bndprm**2)*(z(25)+z(50)+z(55)-3.0d0*z(40))
ddz(50)=ddz(50)+(gam2*3.0d0/bndprm**2)*(z(25)+z(50)+z(55)-3.0d0*z(40))
ddz(55)=ddz(55)+(gam2*3.0d0/bndprm**2)*(z(25)+z(50)+z(55)-3.0d0*z(40))
vpuck=vpuck+(z(29)+z(50)+z(67)-3.0d0*z(41))**2
ddz(41)=ddz(41)-(gam2*9.0d0/bndprm**2)*(z(29)+z(50)+z(67)-3.0d0*z(41))
ddz(29)=ddz(29)+(gam2*3.0d0/bndprm**2)*(z(29)+z(50)+z(67)-3.0d0*z(41))
ddz(50)=ddz(50)+(gam2*3.0d0/bndprm**2)*(z(29)+z(50)+z(67)-3.0d0*z(41))
ddz(67)=ddz(67)+(gam2*3.0d0/bndprm**2)*(z(29)+z(50)+z(67)-3.0d0*z(41))
vpuck=vpuck+(z(27)+z(47)+z(62)-3.0d0*z(42))**2
ddz(42)=ddz(42)-(gam2*9.0d0/bndprm**2)*(z(27)+z(47)+z(62)-3.0d0*z(42))
ddz(27)=ddz(27)+(gam2*3.0d0/bndprm**2)*(z(27)+z(47)+z(62)-3.0d0*z(42))
ddz(47)=ddz(47)+(gam2*3.0d0/bndprm**2)*(z(27)+z(47)+z(62)-3.0d0*z(42))
ddz(62)=ddz(62)+(gam2*3.0d0/bndprm**2)*(z(27)+z(47)+z(62)-3.0d0*z(42))
vpuck=vpuck+(z(26)+z(48)+z(63)-3.0d0*z(43))**2
ddz(43)=ddz(43)-(gam2*9.0d0/bndprm**2)*(z(26)+z(48)+z(63)-3.0d0*z(43))
ddz(26)=ddz(26)+(gam2*3.0d0/bndprm**2)*(z(26)+z(48)+z(63)-3.0d0*z(43))
ddz(48)=ddz(48)+(gam2*3.0d0/bndprm**2)*(z(26)+z(48)+z(63)-3.0d0*z(43))
ddz(63)=ddz(63)+(gam2*3.0d0/bndprm**2)*(z(26)+z(48)+z(63)-3.0d0*z(43))
vpuck=vpuck+(z(31)+z(55)+z(66)-3.0d0*z(44))**2
ddz(44)=ddz(44)-(gam2*9.0d0/bndprm**2)*(z(31)+z(55)+z(66)-3.0d0*z(44))
ddz(31)=ddz(31)+(gam2*3.0d0/bndprm**2)*(z(31)+z(55)+z(66)-3.0d0*z(44))
ddz(55)=ddz(55)+(gam2*3.0d0/bndprm**2)*(z(31)+z(55)+z(66)-3.0d0*z(44))
ddz(66)=ddz(66)+(gam2*3.0d0/bndprm**2)*(z(31)+z(55)+z(66)-3.0d0*z(44))
vpuck=vpuck+(z(28)+z(56)+z(64)-3.0d0*z(45))**2
ddz(45)=ddz(45)-(gam2*9.0d0/bndprm**2)*(z(28)+z(56)+z(64)-3.0d0*z(45))
ddz(28)=ddz(28)+(gam2*3.0d0/bndprm**2)*(z(28)+z(56)+z(64)-3.0d0*z(45))
ddz(56)=ddz(56)+(gam2*3.0d0/bndprm**2)*(z(28)+z(56)+z(64)-3.0d0*z(45))
ddz(64)=ddz(64)+(gam2*3.0d0/bndprm**2)*(z(28)+z(56)+z(64)-3.0d0*z(45))
vpuck=vpuck+(z(30)+z(54)+z(65)-3.0d0*z(46))**2
ddz(46)=ddz(46)-(gam2*9.0d0/bndprm**2)*(z(30)+z(54)+z(65)-3.0d0*z(46))
ddz(30)=ddz(30)+(gam2*3.0d0/bndprm**2)*(z(30)+z(54)+z(65)-3.0d0*z(46))
ddz(54)=ddz(54)+(gam2*3.0d0/bndprm**2)*(z(30)+z(54)+z(65)-3.0d0*z(46))
ddz(65)=ddz(65)+(gam2*3.0d0/bndprm**2)*(z(30)+z(54)+z(65)-3.0d0*z(46))
vpuck=vpuck+(z(38)+z(42)+z(75)-3.0d0*z(47))**2
ddz(47)=ddz(47)-(gam2*9.0d0/bndprm**2)*(z(38)+z(42)+z(75)-3.0d0*z(47))
ddz(38)=ddz(38)+(gam2*3.0d0/bndprm**2)*(z(38)+z(42)+z(75)-3.0d0*z(47))
ddz(42)=ddz(42)+(gam2*3.0d0/bndprm**2)*(z(38)+z(42)+z(75)-3.0d0*z(47))
ddz(75)=ddz(75)+(gam2*3.0d0/bndprm**2)*(z(38)+z(42)+z(75)-3.0d0*z(47))
vpuck=vpuck+(z(38)+z(43)+z(76)-3.0d0*z(48))**2
ddz(48)=ddz(48)-(gam2*9.0d0/bndprm**2)*(z(38)+z(43)+z(76)-3.0d0*z(48))
ddz(38)=ddz(38)+(gam2*3.0d0/bndprm**2)*(z(38)+z(43)+z(76)-3.0d0*z(48))
ddz(43)=ddz(43)+(gam2*3.0d0/bndprm**2)*(z(38)+z(43)+z(76)-3.0d0*z(48))
ddz(76)=ddz(76)+(gam2*3.0d0/bndprm**2)*(z(38)+z(43)+z(76)-3.0d0*z(48))
vpuck=vpuck+(z(33)+z(60)+z(73)-3.0d0*z(49))**2
ddz(49)=ddz(49)-(gam2*9.0d0/bndprm**2)*(z(33)+z(60)+z(73)-3.0d0*z(49))
ddz(33)=ddz(33)+(gam2*3.0d0/bndprm**2)*(z(33)+z(60)+z(73)-3.0d0*z(49))
ddz(60)=ddz(60)+(gam2*3.0d0/bndprm**2)*(z(33)+z(60)+z(73)-3.0d0*z(49))
ddz(73)=ddz(73)+(gam2*3.0d0/bndprm**2)*(z(33)+z(60)+z(73)-3.0d0*z(49))
vpuck=vpuck+(z(40)+z(41)+z(74)-3.0d0*z(50))**2
ddz(50)=ddz(50)-(gam2*9.0d0/bndprm**2)*(z(40)+z(41)+z(74)-3.0d0*z(50))
ddz(40)=ddz(40)+(gam2*3.0d0/bndprm**2)*(z(40)+z(41)+z(74)-3.0d0*z(50))
ddz(41)=ddz(41)+(gam2*3.0d0/bndprm**2)*(z(40)+z(41)+z(74)-3.0d0*z(50))
ddz(74)=ddz(74)+(gam2*3.0d0/bndprm**2)*(z(40)+z(41)+z(74)-3.0d0*z(50))
vpuck=vpuck+(z(32)+z(59)+z(70)-3.0d0*z(51))**2
ddz(51)=ddz(51)-(gam2*9.0d0/bndprm**2)*(z(32)+z(59)+z(70)-3.0d0*z(51))
ddz(32)=ddz(32)+(gam2*3.0d0/bndprm**2)*(z(32)+z(59)+z(70)-3.0d0*z(51))
ddz(59)=ddz(59)+(gam2*3.0d0/bndprm**2)*(z(32)+z(59)+z(70)-3.0d0*z(51))
ddz(70)=ddz(70)+(gam2*3.0d0/bndprm**2)*(z(32)+z(59)+z(70)-3.0d0*z(51))
vpuck=vpuck+(z(34)+z(59)+z(68)-3.0d0*z(52))**2
ddz(52)=ddz(52)-(gam2*9.0d0/bndprm**2)*(z(34)+z(59)+z(68)-3.0d0*z(52))
ddz(34)=ddz(34)+(gam2*3.0d0/bndprm**2)*(z(34)+z(59)+z(68)-3.0d0*z(52))
ddz(59)=ddz(59)+(gam2*3.0d0/bndprm**2)*(z(34)+z(59)+z(68)-3.0d0*z(52))
ddz(68)=ddz(68)+(gam2*3.0d0/bndprm**2)*(z(34)+z(59)+z(68)-3.0d0*z(52))
vpuck=vpuck+(z(35)+z(60)+z(69)-3.0d0*z(53))**2
ddz(53)=ddz(53)-(gam2*9.0d0/bndprm**2)*(z(35)+z(60)+z(69)-3.0d0*z(53))
ddz(35)=ddz(35)+(gam2*3.0d0/bndprm**2)*(z(35)+z(60)+z(69)-3.0d0*z(53))
ddz(60)=ddz(60)+(gam2*3.0d0/bndprm**2)*(z(35)+z(60)+z(69)-3.0d0*z(53))
ddz(69)=ddz(69)+(gam2*3.0d0/bndprm**2)*(z(35)+z(60)+z(69)-3.0d0*z(53))
vpuck=vpuck+(z(39)+z(46)+z(78)-3.0d0*z(54))**2
ddz(54)=ddz(54)-(gam2*9.0d0/bndprm**2)*(z(39)+z(46)+z(78)-3.0d0*z(54))
ddz(39)=ddz(39)+(gam2*3.0d0/bndprm**2)*(z(39)+z(46)+z(78)-3.0d0*z(54))
ddz(46)=ddz(46)+(gam2*3.0d0/bndprm**2)*(z(39)+z(46)+z(78)-3.0d0*z(54))
ddz(78)=ddz(78)+(gam2*3.0d0/bndprm**2)*(z(39)+z(46)+z(78)-3.0d0*z(54))
vpuck=vpuck+(z(40)+z(44)+z(79)-3.0d0*z(55))**2
ddz(55)=ddz(55)-(gam2*9.0d0/bndprm**2)*(z(40)+z(44)+z(79)-3.0d0*z(55))
ddz(40)=ddz(40)+(gam2*3.0d0/bndprm**2)*(z(40)+z(44)+z(79)-3.0d0*z(55))
ddz(44)=ddz(44)+(gam2*3.0d0/bndprm**2)*(z(40)+z(44)+z(79)-3.0d0*z(55))
ddz(79)=ddz(79)+(gam2*3.0d0/bndprm**2)*(z(40)+z(44)+z(79)-3.0d0*z(55))
vpuck=vpuck+(z(39)+z(45)+z(77)-3.0d0*z(56))**2
ddz(56)=ddz(56)-(gam2*9.0d0/bndprm**2)*(z(39)+z(45)+z(77)-3.0d0*z(56))
ddz(39)=ddz(39)+(gam2*3.0d0/bndprm**2)*(z(39)+z(45)+z(77)-3.0d0*z(56))
ddz(45)=ddz(45)+(gam2*3.0d0/bndprm**2)*(z(39)+z(45)+z(77)-3.0d0*z(56))
ddz(77)=ddz(77)+(gam2*3.0d0/bndprm**2)*(z(39)+z(45)+z(77)-3.0d0*z(56))
vpuck=vpuck+(z(36)+z(61)+z(71)-3.0d0*z(57))**2
ddz(57)=ddz(57)-(gam2*9.0d0/bndprm**2)*(z(36)+z(61)+z(71)-3.0d0*z(57))
ddz(36)=ddz(36)+(gam2*3.0d0/bndprm**2)*(z(36)+z(61)+z(71)-3.0d0*z(57))
ddz(61)=ddz(61)+(gam2*3.0d0/bndprm**2)*(z(36)+z(61)+z(71)-3.0d0*z(57))
ddz(71)=ddz(71)+(gam2*3.0d0/bndprm**2)*(z(36)+z(61)+z(71)-3.0d0*z(57))
vpuck=vpuck+(z(37)+z(61)+z(72)-3.0d0*z(58))**2
ddz(58)=ddz(58)-(gam2*9.0d0/bndprm**2)*(z(37)+z(61)+z(72)-3.0d0*z(58))
ddz(37)=ddz(37)+(gam2*3.0d0/bndprm**2)*(z(37)+z(61)+z(72)-3.0d0*z(58))
ddz(61)=ddz(61)+(gam2*3.0d0/bndprm**2)*(z(37)+z(61)+z(72)-3.0d0*z(58))
ddz(72)=ddz(72)+(gam2*3.0d0/bndprm**2)*(z(37)+z(61)+z(72)-3.0d0*z(58))
vpuck=vpuck+(z(51)+z(52)+z(81)-3.0d0*z(59))**2
ddz(59)=ddz(59)-(gam2*9.0d0/bndprm**2)*(z(51)+z(52)+z(81)-3.0d0*z(59))
ddz(51)=ddz(51)+(gam2*3.0d0/bndprm**2)*(z(51)+z(52)+z(81)-3.0d0*z(59))
ddz(52)=ddz(52)+(gam2*3.0d0/bndprm**2)*(z(51)+z(52)+z(81)-3.0d0*z(59))
ddz(81)=ddz(81)+(gam2*3.0d0/bndprm**2)*(z(51)+z(52)+z(81)-3.0d0*z(59))
vpuck=vpuck+(z(49)+z(53)+z(80)-3.0d0*z(60))**2
ddz(60)=ddz(60)-(gam2*9.0d0/bndprm**2)*(z(49)+z(53)+z(80)-3.0d0*z(60))
ddz(49)=ddz(49)+(gam2*3.0d0/bndprm**2)*(z(49)+z(53)+z(80)-3.0d0*z(60))
ddz(53)=ddz(53)+(gam2*3.0d0/bndprm**2)*(z(49)+z(53)+z(80)-3.0d0*z(60))
ddz(80)=ddz(80)+(gam2*3.0d0/bndprm**2)*(z(49)+z(53)+z(80)-3.0d0*z(60))
vpuck=vpuck+(z(57)+z(58)+z(85)-3.0d0*z(61))**2
ddz(61)=ddz(61)-(gam2*9.0d0/bndprm**2)*(z(57)+z(58)+z(85)-3.0d0*z(61))
ddz(57)=ddz(57)+(gam2*3.0d0/bndprm**2)*(z(57)+z(58)+z(85)-3.0d0*z(61))
ddz(58)=ddz(58)+(gam2*3.0d0/bndprm**2)*(z(57)+z(58)+z(85)-3.0d0*z(61))
ddz(85)=ddz(85)+(gam2*3.0d0/bndprm**2)*(z(57)+z(58)+z(85)-3.0d0*z(61))
vpuck=vpuck+(z(42)+z(68)+z(86)-3.0d0*z(62))**2
ddz(62)=ddz(62)-(gam2*9.0d0/bndprm**2)*(z(42)+z(68)+z(86)-3.0d0*z(62))
ddz(42)=ddz(42)+(gam2*3.0d0/bndprm**2)*(z(42)+z(68)+z(86)-3.0d0*z(62))
ddz(68)=ddz(68)+(gam2*3.0d0/bndprm**2)*(z(42)+z(68)+z(86)-3.0d0*z(62))
ddz(86)=ddz(86)+(gam2*3.0d0/bndprm**2)*(z(42)+z(68)+z(86)-3.0d0*z(62))
vpuck=vpuck+(z(43)+z(69)+z(87)-3.0d0*z(63))**2
ddz(63)=ddz(63)-(gam2*9.0d0/bndprm**2)*(z(43)+z(69)+z(87)-3.0d0*z(63))
ddz(43)=ddz(43)+(gam2*3.0d0/bndprm**2)*(z(43)+z(69)+z(87)-3.0d0*z(63))
ddz(69)=ddz(69)+(gam2*3.0d0/bndprm**2)*(z(43)+z(69)+z(87)-3.0d0*z(63))
ddz(87)=ddz(87)+(gam2*3.0d0/bndprm**2)*(z(43)+z(69)+z(87)-3.0d0*z(63))
vpuck=vpuck+(z(45)+z(70)+z(90)-3.0d0*z(64))**2
ddz(64)=ddz(64)-(gam2*9.0d0/bndprm**2)*(z(45)+z(70)+z(90)-3.0d0*z(64))
ddz(45)=ddz(45)+(gam2*3.0d0/bndprm**2)*(z(45)+z(70)+z(90)-3.0d0*z(64))
ddz(70)=ddz(70)+(gam2*3.0d0/bndprm**2)*(z(45)+z(70)+z(90)-3.0d0*z(64))
ddz(90)=ddz(90)+(gam2*3.0d0/bndprm**2)*(z(45)+z(70)+z(90)-3.0d0*z(64))
vpuck=vpuck+(z(46)+z(71)+z(88)-3.0d0*z(65))**2
ddz(65)=ddz(65)-(gam2*9.0d0/bndprm**2)*(z(46)+z(71)+z(88)-3.0d0*z(65))
ddz(46)=ddz(46)+(gam2*3.0d0/bndprm**2)*(z(46)+z(71)+z(88)-3.0d0*z(65))
ddz(71)=ddz(71)+(gam2*3.0d0/bndprm**2)*(z(46)+z(71)+z(88)-3.0d0*z(65))
ddz(88)=ddz(88)+(gam2*3.0d0/bndprm**2)*(z(46)+z(71)+z(88)-3.0d0*z(65))
vpuck=vpuck+(z(44)+z(72)+z(89)-3.0d0*z(66))**2
ddz(66)=ddz(66)-(gam2*9.0d0/bndprm**2)*(z(44)+z(72)+z(89)-3.0d0*z(66))
ddz(44)=ddz(44)+(gam2*3.0d0/bndprm**2)*(z(44)+z(72)+z(89)-3.0d0*z(66))
ddz(72)=ddz(72)+(gam2*3.0d0/bndprm**2)*(z(44)+z(72)+z(89)-3.0d0*z(66))
ddz(89)=ddz(89)+(gam2*3.0d0/bndprm**2)*(z(44)+z(72)+z(89)-3.0d0*z(66))
vpuck=vpuck+(z(41)+z(73)+z(91)-3.0d0*z(67))**2
ddz(67)=ddz(67)-(gam2*9.0d0/bndprm**2)*(z(41)+z(73)+z(91)-3.0d0*z(67))
ddz(41)=ddz(41)+(gam2*3.0d0/bndprm**2)*(z(41)+z(73)+z(91)-3.0d0*z(67))
ddz(73)=ddz(73)+(gam2*3.0d0/bndprm**2)*(z(41)+z(73)+z(91)-3.0d0*z(67))
ddz(91)=ddz(91)+(gam2*3.0d0/bndprm**2)*(z(41)+z(73)+z(91)-3.0d0*z(67))
vpuck=vpuck+(z(52)+z(62)+z(94)-3.0d0*z(68))**2
ddz(68)=ddz(68)-(gam2*9.0d0/bndprm**2)*(z(52)+z(62)+z(94)-3.0d0*z(68))
ddz(52)=ddz(52)+(gam2*3.0d0/bndprm**2)*(z(52)+z(62)+z(94)-3.0d0*z(68))
ddz(62)=ddz(62)+(gam2*3.0d0/bndprm**2)*(z(52)+z(62)+z(94)-3.0d0*z(68))
ddz(94)=ddz(94)+(gam2*3.0d0/bndprm**2)*(z(52)+z(62)+z(94)-3.0d0*z(68))
vpuck=vpuck+(z(53)+z(63)+z(95)-3.0d0*z(69))**2
ddz(69)=ddz(69)-(gam2*9.0d0/bndprm**2)*(z(53)+z(63)+z(95)-3.0d0*z(69))
ddz(53)=ddz(53)+(gam2*3.0d0/bndprm**2)*(z(53)+z(63)+z(95)-3.0d0*z(69))
ddz(63)=ddz(63)+(gam2*3.0d0/bndprm**2)*(z(53)+z(63)+z(95)-3.0d0*z(69))
ddz(95)=ddz(95)+(gam2*3.0d0/bndprm**2)*(z(53)+z(63)+z(95)-3.0d0*z(69))
vpuck=vpuck+(z(51)+z(64)+z(92)-3.0d0*z(70))**2
ddz(70)=ddz(70)-(gam2*9.0d0/bndprm**2)*(z(51)+z(64)+z(92)-3.0d0*z(70))
ddz(51)=ddz(51)+(gam2*3.0d0/bndprm**2)*(z(51)+z(64)+z(92)-3.0d0*z(70))
ddz(64)=ddz(64)+(gam2*3.0d0/bndprm**2)*(z(51)+z(64)+z(92)-3.0d0*z(70))
ddz(92)=ddz(92)+(gam2*3.0d0/bndprm**2)*(z(51)+z(64)+z(92)-3.0d0*z(70))
vpuck=vpuck+(z(57)+z(65)+z(102)-3.0d0*z(71))**2
ddz(71)=ddz(71)-(gam2*9.0d0/bndprm**2)*(z(57)+z(65)+z(102)-3.0d0*z(71))
ddz(57)=ddz(57)+(gam2*3.0d0/bndprm**2)*(z(57)+z(65)+z(102)-3.0d0*z(71))
ddz(65)=ddz(65)+(gam2*3.0d0/bndprm**2)*(z(57)+z(65)+z(102)-3.0d0*z(71))
ddz(102)=ddz(102)+(gam2*3.0d0/bndprm**2)*(z(57)+z(65)+z(102)-3.0d0*z(71))
vpuck=vpuck+(z(58)+z(66)+z(103)-3.0d0*z(72))**2
ddz(72)=ddz(72)-(gam2*9.0d0/bndprm**2)*(z(58)+z(66)+z(103)-3.0d0*z(72))
ddz(58)=ddz(58)+(gam2*3.0d0/bndprm**2)*(z(58)+z(66)+z(103)-3.0d0*z(72))
ddz(66)=ddz(66)+(gam2*3.0d0/bndprm**2)*(z(58)+z(66)+z(103)-3.0d0*z(72))
ddz(103)=ddz(103)+(gam2*3.0d0/bndprm**2)*(z(58)+z(66)+z(103)-3.0d0*z(72))
vpuck=vpuck+(z(49)+z(67)+z(93)-3.0d0*z(73))**2
ddz(73)=ddz(73)-(gam2*9.0d0/bndprm**2)*(z(49)+z(67)+z(93)-3.0d0*z(73))
ddz(49)=ddz(49)+(gam2*3.0d0/bndprm**2)*(z(49)+z(67)+z(93)-3.0d0*z(73))
ddz(67)=ddz(67)+(gam2*3.0d0/bndprm**2)*(z(49)+z(67)+z(93)-3.0d0*z(73))
ddz(93)=ddz(93)+(gam2*3.0d0/bndprm**2)*(z(49)+z(67)+z(93)-3.0d0*z(73))
vpuck=vpuck+(z(50)+z(84)+z(101)-3.0d0*z(74))**2
ddz(74)=ddz(74)-(gam2*9.0d0/bndprm**2)*(z(50)+z(84)+z(101)-3.0d0*z(74))
ddz(50)=ddz(50)+(gam2*3.0d0/bndprm**2)*(z(50)+z(84)+z(101)-3.0d0*z(74))
ddz(84)=ddz(84)+(gam2*3.0d0/bndprm**2)*(z(50)+z(84)+z(101)-3.0d0*z(74))
ddz(101)=ddz(101)+(gam2*3.0d0/bndprm**2)*(z(50)+z(84)+z(101)-3.0d0*z(74))
vpuck=vpuck+(z(47)+z(82)+z(96)-3.0d0*z(75))**2
ddz(75)=ddz(75)-(gam2*9.0d0/bndprm**2)*(z(47)+z(82)+z(96)-3.0d0*z(75))
ddz(47)=ddz(47)+(gam2*3.0d0/bndprm**2)*(z(47)+z(82)+z(96)-3.0d0*z(75))
ddz(82)=ddz(82)+(gam2*3.0d0/bndprm**2)*(z(47)+z(82)+z(96)-3.0d0*z(75))
ddz(96)=ddz(96)+(gam2*3.0d0/bndprm**2)*(z(47)+z(82)+z(96)-3.0d0*z(75))
vpuck=vpuck+(z(48)+z(82)+z(97)-3.0d0*z(76))**2
ddz(76)=ddz(76)-(gam2*9.0d0/bndprm**2)*(z(48)+z(82)+z(97)-3.0d0*z(76))
ddz(48)=ddz(48)+(gam2*3.0d0/bndprm**2)*(z(48)+z(82)+z(97)-3.0d0*z(76))
ddz(82)=ddz(82)+(gam2*3.0d0/bndprm**2)*(z(48)+z(82)+z(97)-3.0d0*z(76))
ddz(97)=ddz(97)+(gam2*3.0d0/bndprm**2)*(z(48)+z(82)+z(97)-3.0d0*z(76))
vpuck=vpuck+(z(56)+z(83)+z(100)-3.0d0*z(77))**2
ddz(77)=ddz(77)-(gam2*9.0d0/bndprm**2)*(z(56)+z(83)+z(100)-3.0d0*z(77))
ddz(56)=ddz(56)+(gam2*3.0d0/bndprm**2)*(z(56)+z(83)+z(100)-3.0d0*z(77))
ddz(83)=ddz(83)+(gam2*3.0d0/bndprm**2)*(z(56)+z(83)+z(100)-3.0d0*z(77))
ddz(100)=ddz(100)+(gam2*3.0d0/bndprm**2)*(z(56)+z(83)+z(100)-3.0d0*z(77))
vpuck=vpuck+(z(54)+z(83)+z(98)-3.0d0*z(78))**2
ddz(78)=ddz(78)-(gam2*9.0d0/bndprm**2)*(z(54)+z(83)+z(98)-3.0d0*z(78))
ddz(54)=ddz(54)+(gam2*3.0d0/bndprm**2)*(z(54)+z(83)+z(98)-3.0d0*z(78))
ddz(83)=ddz(83)+(gam2*3.0d0/bndprm**2)*(z(54)+z(83)+z(98)-3.0d0*z(78))
ddz(98)=ddz(98)+(gam2*3.0d0/bndprm**2)*(z(54)+z(83)+z(98)-3.0d0*z(78))
vpuck=vpuck+(z(55)+z(84)+z(99)-3.0d0*z(79))**2
ddz(79)=ddz(79)-(gam2*9.0d0/bndprm**2)*(z(55)+z(84)+z(99)-3.0d0*z(79))
ddz(55)=ddz(55)+(gam2*3.0d0/bndprm**2)*(z(55)+z(84)+z(99)-3.0d0*z(79))
ddz(84)=ddz(84)+(gam2*3.0d0/bndprm**2)*(z(55)+z(84)+z(99)-3.0d0*z(79))
ddz(99)=ddz(99)+(gam2*3.0d0/bndprm**2)*(z(55)+z(84)+z(99)-3.0d0*z(79))
vpuck=vpuck+(z(60)+z(105)+z(107)-3.0d0*z(80))**2
ddz(80)=ddz(80)-(gam2*9.0d0/bndprm**2)*(z(60)+z(105)+z(107)-3.0d0*z(80))
ddz(60)=ddz(60)+(gam2*3.0d0/bndprm**2)*(z(60)+z(105)+z(107)-3.0d0*z(80))
ddz(105)=ddz(105)+(gam2*3.0d0/bndprm**2)*(z(60)+z(105)+z(107)-3.0d0*z(80))
ddz(107)=ddz(107)+(gam2*3.0d0/bndprm**2)*(z(60)+z(105)+z(107)-3.0d0*z(80))
vpuck=vpuck+(z(59)+z(104)+z(106)-3.0d0*z(81))**2
ddz(81)=ddz(81)-(gam2*9.0d0/bndprm**2)*(z(59)+z(104)+z(106)-3.0d0*z(81))
ddz(59)=ddz(59)+(gam2*3.0d0/bndprm**2)*(z(59)+z(104)+z(106)-3.0d0*z(81))
ddz(104)=ddz(104)+(gam2*3.0d0/bndprm**2)*(z(59)+z(104)+z(106)-3.0d0*z(81))
ddz(106)=ddz(106)+(gam2*3.0d0/bndprm**2)*(z(59)+z(104)+z(106)-3.0d0*z(81))
vpuck=vpuck+(z(61)+z(108)+z(109)-3.0d0*z(85))**2
ddz(85)=ddz(85)-(gam2*9.0d0/bndprm**2)*(z(61)+z(108)+z(109)-3.0d0*z(85))
ddz(61)=ddz(61)+(gam2*3.0d0/bndprm**2)*(z(61)+z(108)+z(109)-3.0d0*z(85))
ddz(108)=ddz(108)+(gam2*3.0d0/bndprm**2)*(z(61)+z(108)+z(109)-3.0d0*z(85))
ddz(109)=ddz(109)+(gam2*3.0d0/bndprm**2)*(z(61)+z(108)+z(109)-3.0d0*z(85))
vpuck=vpuck+(z(62)+z(96)+z(112)-3.0d0*z(86))**2
ddz(86)=ddz(86)-(gam2*9.0d0/bndprm**2)*(z(62)+z(96)+z(112)-3.0d0*z(86))
ddz(62)=ddz(62)+(gam2*3.0d0/bndprm**2)*(z(62)+z(96)+z(112)-3.0d0*z(86))
ddz(96)=ddz(96)+(gam2*3.0d0/bndprm**2)*(z(62)+z(96)+z(112)-3.0d0*z(86))
ddz(112)=ddz(112)+(gam2*3.0d0/bndprm**2)*(z(62)+z(96)+z(112)-3.0d0*z(86))
vpuck=vpuck+(z(63)+z(97)+z(113)-3.0d0*z(87))**2
ddz(87)=ddz(87)-(gam2*9.0d0/bndprm**2)*(z(63)+z(97)+z(113)-3.0d0*z(87))
ddz(63)=ddz(63)+(gam2*3.0d0/bndprm**2)*(z(63)+z(97)+z(113)-3.0d0*z(87))
ddz(97)=ddz(97)+(gam2*3.0d0/bndprm**2)*(z(63)+z(97)+z(113)-3.0d0*z(87))
ddz(113)=ddz(113)+(gam2*3.0d0/bndprm**2)*(z(63)+z(97)+z(113)-3.0d0*z(87))
vpuck=vpuck+(z(65)+z(98)+z(114)-3.0d0*z(88))**2
ddz(88)=ddz(88)-(gam2*9.0d0/bndprm**2)*(z(65)+z(98)+z(114)-3.0d0*z(88))
ddz(65)=ddz(65)+(gam2*3.0d0/bndprm**2)*(z(65)+z(98)+z(114)-3.0d0*z(88))
ddz(98)=ddz(98)+(gam2*3.0d0/bndprm**2)*(z(65)+z(98)+z(114)-3.0d0*z(88))
ddz(114)=ddz(114)+(gam2*3.0d0/bndprm**2)*(z(65)+z(98)+z(114)-3.0d0*z(88))
vpuck=vpuck+(z(66)+z(99)+z(115)-3.0d0*z(89))**2
ddz(89)=ddz(89)-(gam2*9.0d0/bndprm**2)*(z(66)+z(99)+z(115)-3.0d0*z(89))
ddz(66)=ddz(66)+(gam2*3.0d0/bndprm**2)*(z(66)+z(99)+z(115)-3.0d0*z(89))
ddz(99)=ddz(99)+(gam2*3.0d0/bndprm**2)*(z(66)+z(99)+z(115)-3.0d0*z(89))
ddz(115)=ddz(115)+(gam2*3.0d0/bndprm**2)*(z(66)+z(99)+z(115)-3.0d0*z(89))
vpuck=vpuck+(z(64)+z(100)+z(110)-3.0d0*z(90))**2
ddz(90)=ddz(90)-(gam2*9.0d0/bndprm**2)*(z(64)+z(100)+z(110)-3.0d0*z(90))
ddz(64)=ddz(64)+(gam2*3.0d0/bndprm**2)*(z(64)+z(100)+z(110)-3.0d0*z(90))
ddz(100)=ddz(100)+(gam2*3.0d0/bndprm**2)*(z(64)+z(100)+z(110)-3.0d0*z(90))
ddz(110)=ddz(110)+(gam2*3.0d0/bndprm**2)*(z(64)+z(100)+z(110)-3.0d0*z(90))
vpuck=vpuck+(z(67)+z(101)+z(111)-3.0d0*z(91))**2
ddz(91)=ddz(91)-(gam2*9.0d0/bndprm**2)*(z(67)+z(101)+z(111)-3.0d0*z(91))
ddz(67)=ddz(67)+(gam2*3.0d0/bndprm**2)*(z(67)+z(101)+z(111)-3.0d0*z(91))
ddz(101)=ddz(101)+(gam2*3.0d0/bndprm**2)*(z(67)+z(101)+z(111)-3.0d0*z(91))
ddz(111)=ddz(111)+(gam2*3.0d0/bndprm**2)*(z(67)+z(101)+z(111)-3.0d0*z(91))
vpuck=vpuck+(z(70)+z(104)+z(120)-3.0d0*z(92))**2
ddz(92)=ddz(92)-(gam2*9.0d0/bndprm**2)*(z(70)+z(104)+z(120)-3.0d0*z(92))
ddz(70)=ddz(70)+(gam2*3.0d0/bndprm**2)*(z(70)+z(104)+z(120)-3.0d0*z(92))
ddz(104)=ddz(104)+(gam2*3.0d0/bndprm**2)*(z(70)+z(104)+z(120)-3.0d0*z(92))
ddz(120)=ddz(120)+(gam2*3.0d0/bndprm**2)*(z(70)+z(104)+z(120)-3.0d0*z(92))
vpuck=vpuck+(z(73)+z(105)+z(121)-3.0d0*z(93))**2
ddz(93)=ddz(93)-(gam2*9.0d0/bndprm**2)*(z(73)+z(105)+z(121)-3.0d0*z(93))
ddz(73)=ddz(73)+(gam2*3.0d0/bndprm**2)*(z(73)+z(105)+z(121)-3.0d0*z(93))
ddz(105)=ddz(105)+(gam2*3.0d0/bndprm**2)*(z(73)+z(105)+z(121)-3.0d0*z(93))
ddz(121)=ddz(121)+(gam2*3.0d0/bndprm**2)*(z(73)+z(105)+z(121)-3.0d0*z(93))
vpuck=vpuck+(z(68)+z(106)+z(116)-3.0d0*z(94))**2
ddz(94)=ddz(94)-(gam2*9.0d0/bndprm**2)*(z(68)+z(106)+z(116)-3.0d0*z(94))
ddz(68)=ddz(68)+(gam2*3.0d0/bndprm**2)*(z(68)+z(106)+z(116)-3.0d0*z(94))
ddz(106)=ddz(106)+(gam2*3.0d0/bndprm**2)*(z(68)+z(106)+z(116)-3.0d0*z(94))
ddz(116)=ddz(116)+(gam2*3.0d0/bndprm**2)*(z(68)+z(106)+z(116)-3.0d0*z(94))
vpuck=vpuck+(z(69)+z(107)+z(117)-3.0d0*z(95))**2
ddz(95)=ddz(95)-(gam2*9.0d0/bndprm**2)*(z(69)+z(107)+z(117)-3.0d0*z(95))
ddz(69)=ddz(69)+(gam2*3.0d0/bndprm**2)*(z(69)+z(107)+z(117)-3.0d0*z(95))
ddz(107)=ddz(107)+(gam2*3.0d0/bndprm**2)*(z(69)+z(107)+z(117)-3.0d0*z(95))
ddz(117)=ddz(117)+(gam2*3.0d0/bndprm**2)*(z(69)+z(107)+z(117)-3.0d0*z(95))
vpuck=vpuck+(z(71)+z(108)+z(118)-3.0d0*z(102))**2
ddz(102)=ddz(102)-(gam2*9.0d0/bndprm**2)*(z(71)+z(108)+z(118)-3.0d0*z(102))
ddz(71)=ddz(71)+(gam2*3.0d0/bndprm**2)*(z(71)+z(108)+z(118)-3.0d0*z(102))
ddz(108)=ddz(108)+(gam2*3.0d0/bndprm**2)*(z(71)+z(108)+z(118)-3.0d0*z(102))
ddz(118)=ddz(118)+(gam2*3.0d0/bndprm**2)*(z(71)+z(108)+z(118)-3.0d0*z(102))
vpuck=vpuck+(z(72)+z(109)+z(119)-3.0d0*z(103))**2
ddz(103)=ddz(103)-(gam2*9.0d0/bndprm**2)*(z(72)+z(109)+z(119)-3.0d0*z(103))
ddz(72)=ddz(72)+(gam2*3.0d0/bndprm**2)*(z(72)+z(109)+z(119)-3.0d0*z(103))
ddz(109)=ddz(109)+(gam2*3.0d0/bndprm**2)*(z(72)+z(109)+z(119)-3.0d0*z(103))
ddz(119)=ddz(119)+(gam2*3.0d0/bndprm**2)*(z(72)+z(109)+z(119)-3.0d0*z(103))
vpuck=vpuck*0.5d0*gam2*3.0d0/bndprm**2
vlatt=vpuck+vtors
! **************************************************************************************************
! COMBINE LATTICE AND C-H SYSTEM
! **************************************************************************************************
! Total Potential
vv=vt+vlatt-0.5*rkc*(z(1)-qqq)**2
! Upper and lower energy cutoff
if ( vv < -5.0 ) vv = -5.0
if ( vv > 20.0 ) vv = 20.0
! Convert total potential to AU
vv = vv / MyConsts_Hartree2eV
! Forces (negative sign because F = -dV/dx )
IF ( rho == 0.0 ) THEN
Forces(1) = 0.0
Forces(2) = 0.0
ELSE
Forces(1) = -dvtdrho*xh/rho
Forces(2) = -dvtdrho*yh/rho
ENDIF
Forces(3)=-dvtds1
DO nn = 4, 123
IF ( nn == 4 ) THEN
Forces(4)=-(dvtds2+ddz(1)-rkc*(z(1)-qqq))
! Forces(4)= 0.0 ! TO FIX EVEN C1 ATOM
ELSE IF ( nn == 5 ) THEN
Forces(5)=-(-(dvtds1+dvtds2)/3.0+ddz(2)+rkc*(z(1)-qqq)/3.0)
ELSE IF ( nn == 6 ) THEN
Forces(6)=-(-(dvtds1+dvtds2)/3.0+ddz(3)+rkc*(z(1)-qqq)/3.0)
ELSE IF ( nn == 7 ) THEN
Forces(7)=-(-(dvtds1+dvtds2)/3.0+ddz(4)+rkc*(z(1)-qqq)/3.0)
ELSE
Forces(nn) = -ddz(nn-3)
END IF
END DO
! Transform forces in atomic units (from eV Ang^-1 to Hartree Bohr^-1)
Forces(:) = Forces(:) * MyConsts_Bohr2Ang / MyConsts_Hartree2eV
END FUNCTION FullPotential
| matbonfanti/fiordiligi | MCTDH-Source/vhsticking.f90 | FORTRAN | gpl-2.0 | 93,892 |
var searchData=
[
['parabolicflux',['ParabolicFlux',['../parabolic__flux_8c.html#a82dcd26a5c0cb977e2de6d673c1f1ea5',1,'parabolic_flux.c']]],
['parabolicrhs',['ParabolicRHS',['../parabolic__rhs_8c.html#a4cb18f3a70263d455ae61aba6977cebb',1,'parabolic_rhs.c']]],
['paramexist',['ParamExist',['../parse__file_8c.html#acd04c5d8b17fd31cf1bc5b0c345edae7',1,'parse_file.c']]],
['paramfileget',['ParamFileGet',['../parse__file_8c.html#a0fcd7fdea13231dce13c40d40ae129b5',1,'parse_file.c']]],
['paramfilegetwords',['ParamFileGetWords',['../parse__file_8c.html#a5c180c8fdf1860133e4c164a99d6e504',1,'parse_file.c']]],
['paramfilehasboth',['ParamFileHasBoth',['../parse__file_8c.html#a59ab030c5cf9e16150efe9509ea4b7a1',1,'parse_file.c']]],
['paramfileread',['ParamFileRead',['../parse__file_8c.html#a7d06b7df242412940c928c3081107ef9',1,'parse_file.c']]],
['parsecmdlineargs',['ParseCmdLineArgs',['../cmd__line__opt_8c.html#afa5e4faf0bb89e16872bfd7c747495e4',1,'cmd_line_opt.c']]],
['periodicbound',['PeriodicBound',['../boundary_8c.html#a1ca8c4db768a5574dd00571cf7c1ccf6',1,'boundary.c']]],
['plm_5fcoefficientsget',['PLM_CoefficientsGet',['../plm__coeffs_8c.html#ac91b02d3eb0db1bd2cad867272416aa1',1,'PLM_CoefficientsGet(PLM_Coeffs *plm_coeffs, int dir): plm_coeffs.c'],['../plm__coeffs_8h.html#a8cbc5d211624ebf7caf44a2851e443d5',1,'PLM_CoefficientsGet(PLM_Coeffs *, int): plm_coeffs.c']]],
['plm_5fcoefficientsset',['PLM_CoefficientsSet',['../plm__coeffs_8c.html#a503a88d9c9b5cdcbe86a7c2ba35d88c0',1,'PLM_CoefficientsSet(Grid *grid): plm_coeffs.c'],['../plm__coeffs_8h.html#a503a88d9c9b5cdcbe86a7c2ba35d88c0',1,'PLM_CoefficientsSet(Grid *grid): plm_coeffs.c']]],
['plutoerror',['PlutoError',['../tools_8c.html#a80a7e75dfd0ccca315502054bd8e7f59',1,'tools.c']]],
['powerlawcooling',['PowerLawCooling',['../cooling_8c.html#ad5f7910d925c8e375577462ae525dfb4',1,'cooling.c']]],
['pressure',['Pressure',['../thermal__eos_8c.html#a87bbd71a0eab6dd23423c4f33eb1a907',1,'thermal_eos.c']]],
['pressurefix',['PressureFix',['../_r_h_d_2pressure__fix_8c.html#a84d13ef25142ccccca3c737d70012b9b',1,'PressureFix(Map_param *par): pressure_fix.c'],['../_r_m_h_d_2mod__defs_8h.html#a0d75453cc448caf9fe8a4dca5ff9289e',1,'PressureFix(Map_param *): pressure_fix.c'],['../_r_m_h_d_2pressure__fix_8c.html#a84d13ef25142ccccca3c737d70012b9b',1,'PressureFix(Map_param *par): pressure_fix.c']]],
['primeigenvectors',['PrimEigenvectors',['../_advection_2eigenv_8c.html#a9bfb3f5eb468ffd57d26eff02278fcca',1,'PrimEigenvectors(double *q, double cs2, double h, double *lambda, double **LL, double **RR): eigenv.c'],['../_h_d_2eigenv_8c.html#a9bfb3f5eb468ffd57d26eff02278fcca',1,'PrimEigenvectors(double *q, double cs2, double h, double *lambda, double **LL, double **RR): eigenv.c'],['../_m_h_d_2eigenv_8c.html#a7a96d9701c0ff52bb8e21abd2206e16f',1,'PrimEigenvectors(double *q, double a2, double h, double *lambda, double **LL, double **RR): eigenv.c']]],
['primrhs',['PrimRHS',['../_advection_2prim__eqn_8c.html#a26702fac9be83b23ddca296e1c3fed03',1,'PrimRHS(double *w, double *dw, double cs2, double h, double *Adw): prim_eqn.c'],['../_h_d_2prim__eqn_8c.html#aca4116e364d50622e96a380a2fdf7995',1,'PrimRHS(double *v, double *dv, double cs2, double h, double *Adv): prim_eqn.c'],['../_m_h_d_2prim__eqn_8c.html#aca4116e364d50622e96a380a2fdf7995',1,'PrimRHS(double *v, double *dv, double cs2, double h, double *Adv): prim_eqn.c'],['../_r_h_d_2prim__eqn_8c.html#aa4dbba5ddc70b6262bb525ed981c9ea3',1,'PrimRHS(real *w, real *dw, real cs2, real h, real *Adw): prim_eqn.c']]],
['primsource',['PrimSource',['../_advection_2prim__eqn_8c.html#a24b13f72dfc563f02a425b55af015512',1,'PrimSource(const State_1D *state, int beg, int end, double *a2, double *h, double **src, Grid *grid): prim_eqn.c'],['../_h_d_2prim__eqn_8c.html#a24b13f72dfc563f02a425b55af015512',1,'PrimSource(const State_1D *state, int beg, int end, double *a2, double *h, double **src, Grid *grid): prim_eqn.c'],['../_m_h_d_2prim__eqn_8c.html#a24b13f72dfc563f02a425b55af015512',1,'PrimSource(const State_1D *state, int beg, int end, double *a2, double *h, double **src, Grid *grid): prim_eqn.c'],['../_r_h_d_2prim__eqn_8c.html#a24b13f72dfc563f02a425b55af015512',1,'PrimSource(const State_1D *state, int beg, int end, double *a2, double *h, double **src, Grid *grid): prim_eqn.c']]],
['primtochar',['PrimToChar',['../_advection_2eigenv_8c.html#a3a2b96e94ad27183d9a7b787c9dd1b96',1,'PrimToChar(double **L, double *v, double *w): eigenv.c'],['../_h_d_2eigenv_8c.html#a3a2b96e94ad27183d9a7b787c9dd1b96',1,'PrimToChar(double **L, double *v, double *w): eigenv.c'],['../_m_h_d_2eigenv_8c.html#a9f45a7f0180bba1c66893dc81ebefc41',1,'PrimToChar(double **Lp, double *v, double *w): eigenv.c']]],
['primtocons',['PrimToCons',['../_advection_2mappers_8c.html#a93838880d9332986406a83d305b90eab',1,'PrimToCons(double **uprim, double **ucons, int ibeg, int iend): mappers.c'],['../_h_d_2mappers_8c.html#a93838880d9332986406a83d305b90eab',1,'PrimToCons(double **uprim, double **ucons, int ibeg, int iend): mappers.c'],['../_m_h_d_2mappers_8c.html#a93838880d9332986406a83d305b90eab',1,'PrimToCons(double **uprim, double **ucons, int ibeg, int iend): mappers.c'],['../_r_h_d_2mappers_8c.html#a408943b531d1fe60e93456f41d52a04f',1,'PrimToCons(double *uprim[], double *ucons[], int ibeg, int iend): mappers.c'],['../_r_m_h_d_2mappers_8c.html#a93838880d9332986406a83d305b90eab',1,'PrimToCons(double **uprim, double **ucons, int ibeg, int iend): mappers.c'],['../_r_m_h_d_2mod__defs_8h.html#a95dfdfc31eef9d5068aa8fa2f9608676',1,'PrimToCons(double **, double **, int, int): mappers.c']]],
['primtocons3d',['PrimToCons3D',['../mappers3_d_8c.html#a2f7fddf5949438e71c0660fb1a444ff2',1,'mappers3D.c']]],
['print',['print',['../tools_8c.html#a42e65774c872bb2ffd35e7827f481776',1,'tools.c']]],
['print1',['print1',['../tools_8c.html#af3b66f66782cf0a9b425887a7c2ba7c3',1,'tools.c']]]
];
| DeovratPrasad/Galaxy-Cluster-PLUTO | Doc/Doxygen/html/search/functions_70.js | JavaScript | gpl-2.0 | 6,045 |
jQuery(document).ready(function ($) {
"use strict";
jQuery.browser={};(function(){jQuery.browser.msie=false;
jQuery.browser.version=0;if(navigator.userAgent.match(/MSIE ([0-9]+)\./)){
jQuery.browser.msie=true;jQuery.browser.version=RegExp.$1;}})();
jQuery('#ajax-login-tabs').insertAfter('#ajax-login-wrap');
jQuery("#layout").fitVids();
if ($(".buddypress")[0]) {
jQuery(".buddypress").removeClass('widget');
}
if ($(".res_mode")[0]) {
if ($("#mymenuone")[0]) {
jQuery('#mymenuone').before('<a class="btn_canvas mymenuone" href="#mymenuone"><i class="fa fa-bars"></i></a>');
jQuery('#mymenuone').mmenu({
dragOpen: true,
position: "left",
zposition: "next"
}, {
clone : true
});
}
if ($("#mymenutwo")[0]) {
jQuery('#mymenutwo').before('<a class="btn_canvas mymenutwo" href="#mymenutwo"><i class="fa fa-bars"></i></a>');
jQuery("#mymenutwo").mmenu({
dragOpen: true,
position: "left",
zposition: "next"
}, {
clone : true
});
}
jQuery('.mm-menu .mm-list').removeClass('sf-menu res_mode sf-js-enabled sf-shadow');
}
// Superfish
if ($(".sf-menu")[0]) {
$('.sf-menu').superfish({
delay: 100,
autoArrows: true,
animation: {
opacity: 'none', height: 'show'
},
speed: 300
});
$('.sf-menu li li .sf-sub-indicator i').removeClass('fa-chevron-down').addClass('icon-chevron-right');
}
// Tabs widget
(function() {
var $tabsNav = $('.T20-tabs-nav'),
$tabsNavLis = $tabsNav.children('li'),
$tabsContainer = $('.T20-tabs-container');
$tabsNav.each(function() {
var $this = $(this);
$this.next().children('.T20-tab').stop(true,true).hide()
.siblings( $this.find('a').attr('href') ).show();
$this.children('li').first().addClass('active').stop(true,true).show();
});
$tabsNavLis.on('click', function(e) {
var $this = $(this);
$this.siblings().removeClass('active').end()
.addClass('active');
$this.parent().next().children('.T20-tab').stop(true,true).hide()
.siblings( $this.find('a').attr('href') ).fadeIn();
e.preventDefault();
}).children( window.location.hash ? 'a[href=' + window.location.hash + ']' : 'a:first' ).trigger('click');
})();
// prettyPhoto
$('.inside_single a').has('img').addClass('prettyPhoto');
$(".inside_single a[class^='prettyPhoto']").prettyPhoto();
$('.inside_single a').has('img').attr('rel', 'gallery');
$('.inside_single a').click(function () {
var desc = $(this).attr('title');
$('.inside_single a').has('img').attr('title', desc, 'rel', 'gallery' );
});
$(".inside_single a.prettyPhoto").prettyPhoto();
// ToTop
jQuery('#toTop').click(function () {
jQuery('body,html').animate({
scrollTop: 0
}, 1000);
});
jQuery("#toTop").addClass("hidett");
jQuery(window).scroll(function () {
if (jQuery(this).scrollTop() < 400) {
jQuery("#toTop").addClass("hidett").removeClass("showtt");
} else {
jQuery("#toTop").removeClass("hidett").addClass("showtt");
}
});
// Slideshows
if ($("#Flexslidert")[0]) {
$('#Flexslidert').flexslider({
animation: "slide",
manualControls: "#slider_nav li"
});
}
if ($("[class^='gallery_']")[0]) {
$("[class^='gallery_']").owlCarousel({
slideSpeed : 500,
paginationSpeed : 500,
autoPlay: true,
autoHeight: true,
stopOnHover: true,
transitionStyle : "goDown",
singleItem:true,
navigation : true,
navigationText : ["<i class='fa fa-chevron-left'></i>","<i class='fa fa-chevron-right'></i>"],
rewindNav : true,
scrollPerPage : false,
pagination : false
});
}
if ($("[class^='slideshow_']")[0]) {
$("[class^='slideshow_b']").owlCarousel({
slideSpeed : 500,
paginationSpeed : 1500,
autoPlay: true,
autoHeight: true,
stopOnHover: true,
transitionStyle : "goDown",
singleItem:true,
navigation : false,
rewindNav : true,
scrollPerPage : false,
pagination : true
});
}
if ($("[class^='carousel_posts_']")[0]) {
$(".grid_2 [class^='carousel_posts_'], .grid_3 [class^='carousel_posts_']").owlCarousel({
slideSpeed : 600,
paginationSpeed : 1000,
items : 1,
autoPlay: true,
stopOnHover: true,
autoHeight: false,
responsive: true,
pagination: true,
paginationNumbers: false
});
$(".grid_4 [class^='carousel_posts_']").owlCarousel({
slideSpeed : 600,
paginationSpeed : 1000,
items : 2,
autoPlay: true,
stopOnHover: true,
autoHeight: false,
responsive: true,
pagination: true,
paginationNumbers: false
});
$(".grid_8 [class^='carousel_posts_'], .grid_6 [class^='carousel_posts_'], .grid_7 [class^='carousel_posts_'], .grid_5 [class^='carousel_posts_']").owlCarousel({
slideSpeed : 600,
paginationSpeed : 1000,
items : 3,
autoPlay: true,
stopOnHover: true,
autoHeight: false,
responsive: true,
pagination: true,
paginationNumbers: false
});
$(".grid_10 [class^='carousel_posts_'], .grid_9 [class^='carousel_posts_']").owlCarousel({
slideSpeed : 600,
paginationSpeed : 1000,
items : 4,
autoPlay: true,
stopOnHover: true,
autoHeight: false,
responsive: true,
pagination: true,
paginationNumbers: false
});
$(".grid_11 [class^='carousel_posts_'], .grid_12 [class^='carousel_posts_']").owlCarousel({
slideSpeed : 600,
paginationSpeed : 1000,
items : 5,
autoPlay: true,
stopOnHover: true,
autoHeight: false,
responsive: true,
pagination: true,
paginationNumbers: false
});
}
// Search
var popupStatus = 0;
$(".search_icon").click(function() {
var windowWidth = document.documentElement.clientWidth;
var windowHeight = document.documentElement.clientHeight;
var popupHeight = $("#popup").height();
var popupWidth = $("#popup").width();
$("#popup").css({
"top": windowHeight / 2 - popupHeight / 2,
"left": windowWidth / 2 - popupWidth / 2
});
// Aligning bg
$("#SearchBackgroundPopup").css({"height": windowHeight});
if (popupStatus == 0) {
$("#SearchBackgroundPopup").fadeIn(400);
$("#popup").fadeIn(400);
$(".search_place").addClass('animated slideDown');
popupStatus = 1;
}
$('#inputhead').select();
});
// Close Popup
$("#popupLoginClose").click(function() {
if (popupStatus == 1) {
$("#SearchBackgroundPopup").fadeOut();
$("#popup").fadeOut();
popupStatus = 0;
}
});
$("body").click(function() {
$("#SearchBackgroundPopup").fadeOut();
$("#popup").fadeOut();
popupStatus = 0;
});
$('#popup, .search_icon').click(function(e) {
e.stopPropagation();
});
// Tipsy
$('.toptip, abbr, .item-avatar a, .activity-meta a').tipsy({fade: true,gravity: 's'});
$('.bottomtip').tipsy({fade: true,gravity: 'n'});
$('.righttip').tipsy({fade: true,gravity: 'w'});
$('.lefttip').tipsy({fade: true,gravity: 'e'});
// Sticky
$('.my_sticky').before('<div class="Corpse_Sticky"></div>');
$(window).scroll(function(){
var wind_scr = $(window).scrollTop();
var window_width = $(window).width();
var head_w = $('.my_sticky').height();
if (window_width >= 1177) {
var headdown_h = $('#header').height();
if(wind_scr < headdown_h){
if($('.my_sticky').data('ssticky') === true){
$('.my_sticky').data('ssticky', false);
$('.my_sticky').stop(true).animate({opacity : 0}, 300, function(){
$('.my_sticky').removeClass('ssticky');
$('.my_sticky').stop(true).animate({opacity : 1}, 300);
$('.Corpse_Sticky').css('padding-top', '');
});
}
} else {
if($('.my_sticky').data('ssticky') === false || typeof $('.my_sticky').data('ssticky') === 'undefined'){
$('.my_sticky').data('ssticky', true);
$('.my_sticky').stop(true).animate({opacity : 0},300,function(){
$('.my_sticky').addClass('ssticky');
$('.my_sticky.ssticky').stop(true).animate({opacity : 1}, 300);
$('.Corpse_Sticky').css('padding-top', head_w + 'px');
});
}
}
}
});
$(window).resize(function(){
var window_width = $(window).width();
if (window_width <= 1177) {
if($('.my_sticky').hasClass('ssticky')){
$('.my_sticky').removeClass('ssticky');
$('.my_sticky').stop(true).animate({opacity : 0}, 300, function(){
$('.my_sticky').removeClass('ssticky');
$('.my_sticky').stop(true).animate({opacity : 1}, 300);
$('.Corpse_Sticky').css('padding-top', '');
});
}
}
});
vc_prettyPhoto();
});
function vc_prettyPhoto() {
try {
// just in case. maybe prettyphoto isnt loaded on this site
jQuery('a.prettyphoto, .gallery-icon a[href*=".jpg"]').prettyPhoto({
animationSpeed:'normal', /* fast/slow/normal */
padding:15, /* padding for each side of the picture */
opacity:0.7, /* Value betwee 0 and 1 */
showTitle:true, /* true/false */
allowresize:true, /* true/false */
counter_separator_label:'/', /* The separator for the gallery counter 1 "of" 2 */
//theme: 'light_square', /* light_rounded / dark_rounded / light_square / dark_square */
hideflash:false, /* Hides all the flash object on a page, set to TRUE if flash appears over prettyPhoto */
deeplinking:false, /* Allow prettyPhoto to update the url to enable deeplinking. */
modal:false, /* If set to true, only the close button will close the window */
callback:function () {
var url = location.href;
var hashtag = (url.indexOf('#!prettyPhoto')) ? true : false;
if (hashtag) location.hash = "!";
} /* Called when prettyPhoto is closed */,
social_tools:''
});
} catch (err) {
}
} | adshannon81/Headstuff.org | wp-content/themes/sevenmag/js/custom.js | JavaScript | gpl-2.0 | 9,572 |
/******************************************************************************
Copyright (C) 2016 by Hugh Bailey <obs.jim@gmail.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, see <http://www.gnu.org/licenses/>.
******************************************************************************/
#include <libavutil/avutil.h>
#if LIBAVUTIL_VERSION_INT >= AV_VERSION_INT(55, 27, 100)
#include <util/darray.h>
#include <util/dstr.h>
#include <util/base.h>
#include <media-io/video-io.h>
#include <obs-module.h>
#include <obs-avc.h>
#include <unistd.h>
#include <libavutil/opt.h>
#include <libavutil/pixdesc.h>
#include <libavutil/hwcontext.h>
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libavfilter/avfilter.h>
#include "obs-ffmpeg-formats.h"
#define do_log(level, format, ...) \
blog(level, "[FFMPEG VAAPI encoder: '%s'] " format, \
obs_encoder_get_name(enc->encoder), ##__VA_ARGS__)
#define warn(format, ...) do_log(LOG_WARNING, format, ##__VA_ARGS__)
#define info(format, ...) do_log(LOG_INFO, format, ##__VA_ARGS__)
#define debug(format, ...) do_log(LOG_DEBUG, format, ##__VA_ARGS__)
struct vaapi_encoder {
obs_encoder_t *encoder;
AVBufferRef *vadevice_ref;
AVBufferRef *vaframes_ref;
AVCodec *vaapi;
AVCodecContext *context;
AVFrame *vframe;
DARRAY(uint8_t) buffer;
uint8_t *header;
size_t header_size;
uint8_t *sei;
size_t sei_size;
int height;
bool first_packet;
bool initialized;
};
static const char *vaapi_getname(void *unused)
{
UNUSED_PARAMETER(unused);
return "FFMPEG VAAPI";
}
static inline bool valid_format(enum video_format format)
{
return format == VIDEO_FORMAT_NV12;
}
static void vaapi_video_info(void *data, struct video_scale_info *info)
{
struct vaapi_encoder *enc = data;
enum video_format pref_format;
pref_format = obs_encoder_get_preferred_video_format(enc->encoder);
if (!valid_format(pref_format)) {
pref_format = valid_format(info->format) ? info->format
: VIDEO_FORMAT_NV12;
}
info->format = pref_format;
}
static bool vaapi_init_codec(struct vaapi_encoder *enc, const char *path)
{
int ret;
ret = av_hwdevice_ctx_create(&enc->vadevice_ref, AV_HWDEVICE_TYPE_VAAPI,
path, NULL, 0);
if (ret < 0) {
warn("Failed to create VAAPI device context: %s",
av_err2str(ret));
return false;
}
enc->vaframes_ref = av_hwframe_ctx_alloc(enc->vadevice_ref);
if (!enc->vaframes_ref) {
warn("Failed to alloc HW frames context");
return false;
}
AVHWFramesContext *frames_ctx =
(AVHWFramesContext *)enc->vaframes_ref->data;
frames_ctx->format = AV_PIX_FMT_VAAPI;
frames_ctx->sw_format = AV_PIX_FMT_NV12;
frames_ctx->width = enc->context->width;
frames_ctx->height = enc->context->height;
frames_ctx->initial_pool_size = 20;
ret = av_hwframe_ctx_init(enc->vaframes_ref);
if (ret < 0) {
warn("Failed to init HW frames context: %s", av_err2str(ret));
return false;
}
/* 2. Create software frame and picture */
enc->vframe = av_frame_alloc();
if (!enc->vframe) {
warn("Failed to allocate video frame");
return false;
}
enc->vframe->format = enc->context->pix_fmt;
enc->vframe->width = enc->context->width;
enc->vframe->height = enc->context->height;
enc->vframe->colorspace = enc->context->colorspace;
enc->vframe->color_range = enc->context->color_range;
ret = av_frame_get_buffer(enc->vframe, base_get_alignment());
if (ret < 0) {
warn("Failed to allocate vframe: %s", av_err2str(ret));
return false;
}
/* 3. set up codec */
enc->context->pix_fmt = AV_PIX_FMT_VAAPI;
enc->context->hw_frames_ctx = av_buffer_ref(enc->vaframes_ref);
ret = avcodec_open2(enc->context, enc->vaapi, NULL);
if (ret < 0) {
warn("Failed to open VAAPI codec: %s", av_err2str(ret));
return false;
}
enc->initialized = true;
return true;
}
/* "Allowed" options per Rate Control
* See FFMPEG libavcodec/vaapi_encode.c (vaapi_encode_rc_modes)
*/
typedef struct {
const char *name;
bool qp;
bool bitrate;
bool maxrate;
} rc_mode_t;
static const rc_mode_t *get_rc_mode(const char *name)
{
/* Set "allowed" options per Rate Control */
static const rc_mode_t RC_MODES[] = {
{.name = "CBR", .qp = false, .bitrate = true, .maxrate = false},
{.name = "CQP", .qp = true, .bitrate = false, .maxrate = false},
{.name = "VBR", .qp = false, .bitrate = true, .maxrate = true},
NULL};
const rc_mode_t *rc_mode = RC_MODES;
while (!!rc_mode && strcmp(rc_mode->name, name) != 0)
rc_mode++;
return rc_mode ? rc_mode : RC_MODES;
}
static bool vaapi_update(void *data, obs_data_t *settings)
{
struct vaapi_encoder *enc = data;
const char *device = obs_data_get_string(settings, "vaapi_device");
const char *rate_control =
obs_data_get_string(settings, "rate_control");
const rc_mode_t *rc_mode = get_rc_mode(rate_control);
bool cbr = strcmp(rc_mode->name, "CBR") == 0;
int profile = (int)obs_data_get_int(settings, "profile");
int bf = (int)obs_data_get_int(settings, "bf");
int qp = rc_mode->qp ? (int)obs_data_get_int(settings, "qp") : 0;
av_opt_set_int(enc->context->priv_data, "qp", qp, 0);
int level = (int)obs_data_get_int(settings, "level");
int bitrate = rc_mode->bitrate
? (int)obs_data_get_int(settings, "bitrate")
: 0;
int maxrate = rc_mode->maxrate
? (int)obs_data_get_int(settings, "maxrate")
: 0;
int keyint_sec = (int)obs_data_get_int(settings, "keyint_sec");
/* For Rate Control which allows maxrate, FFMPEG will give
* an error if maxrate > bitrate. To prevent that set maxrate
* to 0.
* For CBR, maxrate = bitrate
*/
if (cbr)
maxrate = bitrate;
else if (rc_mode->maxrate && maxrate && maxrate < bitrate)
maxrate = 0;
video_t *video = obs_encoder_video(enc->encoder);
const struct video_output_info *voi = video_output_get_info(video);
struct video_scale_info info;
info.format = voi->format;
info.colorspace = voi->colorspace;
info.range = voi->range;
vaapi_video_info(enc, &info);
enc->context->profile = profile;
enc->context->max_b_frames = bf;
enc->context->level = level;
enc->context->bit_rate = bitrate * 1000;
enc->context->rc_max_rate = maxrate * 1000;
enc->context->width = obs_encoder_get_width(enc->encoder);
enc->context->height = obs_encoder_get_height(enc->encoder);
enc->context->time_base = (AVRational){voi->fps_den, voi->fps_num};
enc->context->pix_fmt = obs_to_ffmpeg_video_format(info.format);
enc->context->colorspace = info.colorspace == VIDEO_CS_709
? AVCOL_SPC_BT709
: AVCOL_SPC_BT470BG;
enc->context->color_range = info.range == VIDEO_RANGE_FULL
? AVCOL_RANGE_JPEG
: AVCOL_RANGE_MPEG;
if (keyint_sec > 0) {
enc->context->gop_size =
keyint_sec * voi->fps_num / voi->fps_den;
} else {
enc->context->gop_size = 120;
}
enc->height = enc->context->height;
info("settings:\n"
"\tdevice: %s\n"
"\trate_control: %s\n"
"\tprofile: %d\n"
"\tlevel: %d\n"
"\tqp: %d\n"
"\tbitrate: %d\n"
"\tmaxrate: %d\n"
"\tkeyint: %d\n"
"\twidth: %d\n"
"\theight: %d\n"
"\tb-frames: %d\n",
device, rate_control, profile, level, qp, bitrate, maxrate,
enc->context->gop_size, enc->context->width, enc->context->height,
enc->context->max_b_frames);
return vaapi_init_codec(enc, device);
}
static void vaapi_destroy(void *data)
{
struct vaapi_encoder *enc = data;
if (enc->initialized) {
AVPacket pkt = {0};
int r_pkt = 1;
while (r_pkt) {
#if LIBAVFORMAT_VERSION_INT >= AV_VERSION_INT(57, 40, 101)
if (avcodec_receive_packet(enc->context, &pkt) < 0)
break;
#else
if (avcodec_encode_video2(enc->context, &pkt, NULL,
&r_pkt) < 0)
break;
#endif
if (r_pkt)
av_packet_unref(&pkt);
}
}
avcodec_close(enc->context);
av_frame_unref(enc->vframe);
av_frame_free(&enc->vframe);
av_buffer_unref(&enc->vaframes_ref);
av_buffer_unref(&enc->vadevice_ref);
da_free(enc->buffer);
bfree(enc->header);
bfree(enc->sei);
bfree(enc);
}
static void *vaapi_create(obs_data_t *settings, obs_encoder_t *encoder)
{
struct vaapi_encoder *enc;
#if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(58, 9, 100)
avcodec_register_all();
#endif
enc = bzalloc(sizeof(*enc));
enc->encoder = encoder;
int vaapi_codec = (int)obs_data_get_int(settings, "vaapi_codec");
if (vaapi_codec == AV_CODEC_ID_H264) {
enc->vaapi = avcodec_find_encoder_by_name("h264_vaapi");
}
enc->first_packet = true;
blog(LOG_INFO, "---------------------------------");
if (!enc->vaapi) {
warn("Couldn't find encoder");
goto fail;
}
enc->context = avcodec_alloc_context3(enc->vaapi);
if (!enc->context) {
warn("Failed to create codec context");
goto fail;
}
if (!vaapi_update(enc, settings))
goto fail;
return enc;
fail:
vaapi_destroy(enc);
return NULL;
}
static inline void copy_data(AVFrame *pic, const struct encoder_frame *frame,
int height, enum AVPixelFormat format)
{
int h_chroma_shift, v_chroma_shift;
av_pix_fmt_get_chroma_sub_sample(format, &h_chroma_shift,
&v_chroma_shift);
for (int plane = 0; plane < MAX_AV_PLANES; plane++) {
if (!frame->data[plane])
continue;
int frame_rowsize = (int)frame->linesize[plane];
int pic_rowsize = pic->linesize[plane];
int bytes = frame_rowsize < pic_rowsize ? frame_rowsize
: pic_rowsize;
int plane_height = height >> (plane ? v_chroma_shift : 0);
for (int y = 0; y < plane_height; y++) {
int pos_frame = y * frame_rowsize;
int pos_pic = y * pic_rowsize;
memcpy(pic->data[plane] + pos_pic,
frame->data[plane] + pos_frame, bytes);
}
}
}
static bool vaapi_encode(void *data, struct encoder_frame *frame,
struct encoder_packet *packet, bool *received_packet)
{
struct vaapi_encoder *enc = data;
AVFrame *hwframe = NULL;
AVPacket av_pkt;
int got_packet;
int ret;
hwframe = av_frame_alloc();
if (!hwframe) {
warn("vaapi_encode: failed to allocate hw frame");
return false;
}
ret = av_hwframe_get_buffer(enc->vaframes_ref, hwframe, 0);
if (ret < 0) {
warn("vaapi_encode: failed to get buffer for hw frame: %s",
av_err2str(ret));
goto fail;
}
copy_data(enc->vframe, frame, enc->height, enc->context->pix_fmt);
enc->vframe->pts = frame->pts;
hwframe->pts = frame->pts;
hwframe->width = enc->vframe->width;
hwframe->height = enc->vframe->height;
ret = av_hwframe_transfer_data(hwframe, enc->vframe, 0);
if (ret < 0) {
warn("vaapi_encode: failed to upload hw frame: %s",
av_err2str(ret));
goto fail;
}
ret = av_frame_copy_props(hwframe, enc->vframe);
if (ret < 0) {
warn("vaapi_encode: failed to copy props to hw frame: %s",
av_err2str(ret));
goto fail;
}
av_init_packet(&av_pkt);
#if LIBAVFORMAT_VERSION_INT >= AV_VERSION_INT(57, 40, 101)
ret = avcodec_send_frame(enc->context, hwframe);
if (ret == 0)
ret = avcodec_receive_packet(enc->context, &av_pkt);
got_packet = (ret == 0);
if (ret == AVERROR_EOF || ret == AVERROR(EAGAIN))
ret = 0;
#else
ret = avcodec_encode_video2(enc->context, &av_pkt, hwframe,
&got_packet);
#endif
if (ret < 0) {
warn("vaapi_encode: Error encoding: %s", av_err2str(ret));
goto fail;
}
if (got_packet && av_pkt.size) {
if (enc->first_packet) {
uint8_t *new_packet;
size_t size;
enc->first_packet = false;
obs_extract_avc_headers(av_pkt.data, av_pkt.size,
&new_packet, &size,
&enc->header, &enc->header_size,
&enc->sei, &enc->sei_size);
da_copy_array(enc->buffer, new_packet, size);
bfree(new_packet);
} else {
da_copy_array(enc->buffer, av_pkt.data, av_pkt.size);
}
packet->pts = av_pkt.pts;
packet->dts = av_pkt.dts;
packet->data = enc->buffer.array;
packet->size = enc->buffer.num;
packet->type = OBS_ENCODER_VIDEO;
packet->keyframe = obs_avc_keyframe(packet->data, packet->size);
*received_packet = true;
} else {
*received_packet = false;
}
av_packet_unref(&av_pkt);
av_frame_free(&hwframe);
return true;
fail:
av_frame_free(&hwframe);
return false;
}
static void set_visible(obs_properties_t *ppts, const char *name, bool visible)
{
obs_property_t *p = obs_properties_get(ppts, name);
obs_property_set_visible(p, visible);
}
static void vaapi_defaults(obs_data_t *settings)
{
obs_data_set_default_string(settings, "vaapi_device",
"/dev/dri/renderD128");
obs_data_set_default_int(settings, "vaapi_codec", AV_CODEC_ID_H264);
obs_data_set_default_int(settings, "profile",
FF_PROFILE_H264_CONSTRAINED_BASELINE);
obs_data_set_default_int(settings, "level", 40);
obs_data_set_default_int(settings, "bitrate", 2500);
obs_data_set_default_int(settings, "keyint_sec", 0);
obs_data_set_default_int(settings, "bf", 0);
obs_data_set_default_int(settings, "rendermode", 0);
obs_data_set_default_string(settings, "rate_control", "CBR");
obs_data_set_default_int(settings, "qp", 20);
obs_data_set_default_int(settings, "maxrate", 0);
}
static bool rate_control_modified(obs_properties_t *ppts, obs_property_t *p,
obs_data_t *settings)
{
UNUSED_PARAMETER(p);
const char *rate_control =
obs_data_get_string(settings, "rate_control");
const rc_mode_t *rc_mode = get_rc_mode(rate_control);
/* Set options visibility per Rate Control */
set_visible(ppts, "qp", rc_mode->qp);
set_visible(ppts, "bitrate", rc_mode->bitrate);
set_visible(ppts, "maxrate", rc_mode->maxrate);
return true;
}
static obs_properties_t *vaapi_properties(void *unused)
{
UNUSED_PARAMETER(unused);
obs_properties_t *props = obs_properties_create();
obs_property_t *list;
list = obs_properties_add_list(props, "vaapi_device", "VAAPI Device",
OBS_COMBO_TYPE_LIST,
OBS_COMBO_FORMAT_STRING);
char path[32] = "/dev/dri/renderD1";
for (int i = 28;; i++) {
sprintf(path, "/dev/dri/renderD1%d", i);
if (access(path, F_OK) == 0) {
char card[128] = "Card: ";
sprintf(card, "Card%d: %s", i - 28, path);
obs_property_list_add_string(list, card, path);
} else {
break;
}
}
list = obs_properties_add_list(props, "vaapi_codec", "VAAPI Codec",
OBS_COMBO_TYPE_LIST,
OBS_COMBO_FORMAT_INT);
obs_property_list_add_int(list, "H.264 (default)", AV_CODEC_ID_H264);
list = obs_properties_add_list(props, "level", "Level",
OBS_COMBO_TYPE_LIST,
OBS_COMBO_FORMAT_INT);
obs_property_list_add_int(list, "480p30 (3.0)", 30);
obs_property_list_add_int(list, "720p30/480p60 (3.1)", 31);
obs_property_list_add_int(list, "Compatibility mode (4.0 default)",
40);
obs_property_list_add_int(list, "720p60/1080p30 (4.1)", 41);
obs_property_list_add_int(list, "1080p60 (4.2)", 42);
list = obs_properties_add_list(props, "rate_control",
obs_module_text("RateControl"),
OBS_COMBO_TYPE_LIST,
OBS_COMBO_FORMAT_STRING);
obs_property_list_add_string(list, "CBR (default)", "CBR");
obs_property_list_add_string(list, "CQP", "CQP");
obs_property_list_add_string(list, "VBR", "VBR");
obs_property_set_modified_callback(list, rate_control_modified);
obs_property_t *p;
p = obs_properties_add_int(props, "bitrate", obs_module_text("Bitrate"),
0, 300000, 50);
obs_property_int_set_suffix(p, " Kbps");
p = obs_properties_add_int(
props, "maxrate", obs_module_text("MaxBitrate"), 0, 300000, 50);
obs_property_int_set_suffix(p, " Kbps");
obs_properties_add_int(props, "qp", "QP", 0, 51, 1);
obs_properties_add_int(props, "keyint_sec",
obs_module_text("KeyframeIntervalSec"), 0, 20,
1);
return props;
}
static bool vaapi_extra_data(void *data, uint8_t **extra_data, size_t *size)
{
struct vaapi_encoder *enc = data;
*extra_data = enc->header;
*size = enc->header_size;
return true;
}
static bool vaapi_sei_data(void *data, uint8_t **extra_data, size_t *size)
{
struct vaapi_encoder *enc = data;
*extra_data = enc->sei;
*size = enc->sei_size;
return true;
}
struct obs_encoder_info vaapi_encoder_info = {
.id = "ffmpeg_vaapi",
.type = OBS_ENCODER_VIDEO,
.codec = "h264",
.get_name = vaapi_getname,
.create = vaapi_create,
.destroy = vaapi_destroy,
.encode = vaapi_encode,
.get_defaults = vaapi_defaults,
.get_properties = vaapi_properties,
.get_extra_data = vaapi_extra_data,
.get_sei_data = vaapi_sei_data,
.get_video_info = vaapi_video_info,
};
#endif
| Xaymar/obs-studio | plugins/obs-ffmpeg/obs-ffmpeg-vaapi.c | C | gpl-2.0 | 16,927 |
package cn.com.cms.library.model;
import cn.com.cms.framework.base.tree.TreeNodeEntity;
import cn.com.cms.library.constant.EDataNavigateType;
import cn.com.cms.library.constant.ELibraryNodeType;
/**
* 数据导航类
*
* 包含数据库、数据库分类、数据标签三种类型
*
* @author shishb
* @see TreeEntity
* @version 1.0
*/
public class DataNavigate extends TreeNodeEntity<DataNavigate> {
private static final long serialVersionUID = 1L;
private Integer realId;
private Integer baseId;
private String code;
private String pathCode;
private EDataNavigateType type;
public DataNavigate() {
}
public DataNavigate(BaseLibrary<?> library) {
this.id = library.getId();
this.realId = library.getId();
this.name = library.getName();
this.parentID = library.getParentID();
this.code = library.getCode();
this.pathCode = library.getPathCode();
if (ELibraryNodeType.Directory.equals(library.getNodeType())) {
this.type = EDataNavigateType.DATA_CATEGORY;
} else {
this.type = EDataNavigateType.DATA_BASE;
}
}
/**
* 利用标签的ID与数据库的最大ID相加解决两个ID可能重复的问题
*
* @param dataSort
* @param maxDbId
*/
public DataNavigate(DataSort dataSort, int maxDbId) {
this.id = maxDbId + dataSort.getId();
this.realId = dataSort.getId();
this.baseId = dataSort.getBaseId();
this.name = dataSort.getName();
if (dataSort.getParentID() == 0) {
this.parentID = dataSort.getBaseId();
} else {
this.parentID = maxDbId + dataSort.getParentID();
}
this.code = dataSort.getCode();
this.pathCode = dataSort.getPathCode();
this.type = EDataNavigateType.DATA_SORT;
}
/**
* 数据分类与数据导航转换
* <p>
* 基于全局标签的情况下设置数据库ID为特殊形式
*
* @param dataSort
* @param baseId
*/
public DataNavigate(DataSort dataSort, Integer baseId) {
this.id = dataSort.getId();
this.realId = dataSort.getId();
if (null != dataSort && null != dataSort.getBaseId() && dataSort.getBaseId().intValue() == 0) {
this.baseId = baseId;
} else {
this.baseId = dataSort.getBaseId();
}
this.name = dataSort.getName();
this.parentID = dataSort.getBaseId();
this.code = dataSort.getCode();
this.pathCode = dataSort.getPathCode();
this.type = EDataNavigateType.DATA_SORT;
}
public Integer getRealId() {
return realId;
}
public Integer getBaseId() {
return baseId;
}
public void setBaseId(Integer baseId) {
this.baseId = baseId;
}
public void setRealId(Integer realId) {
this.realId = realId;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getPathCode() {
return pathCode;
}
public void setPathCode(String pathCode) {
this.pathCode = pathCode;
}
public EDataNavigateType getType() {
return type;
}
public void setType(EDataNavigateType type) {
this.type = type;
}
public DataSort toDataSort() {
DataSort dataSort = new DataSort();
dataSort.setId(this.realId);
dataSort.setName(this.name);
dataSort.setCode(this.code);
dataSort.setPathCode(this.pathCode);
return dataSort;
}
}
| shellposhy/cms | src/main/java/cn/com/cms/library/model/DataNavigate.java | Java | gpl-2.0 | 3,164 |
package com.hp.hpl.guess.util.intervals;
/**
* an implementatation of a Red-Black tree so that we can keep our interval
* tree balanced. Nothing too exciting here... It's directly out of
* of CLR.
*
*/
public class RBTree extends Tree {
/**
* Simple constructor
* @return a new RBTree
*/
public RBTree() {
super();
}
/**
* performs the leftRotation step starting at a given node
* @param x the node at which rotation needs to occur
*/
private final void leftRotate(IntervalNode x) {
if (x.getRight() == IntervalNode.nullIntervalNode)
return;
// set y
IntervalNode y = x.getRight();
// turn y's left subtree into x's right subtree
x.setRight(y.getLeft());
if (y.getLeft() != IntervalNode.nullIntervalNode)
y.getLeft().setP(x);
y.setP(x.getP());
// link x's parent to y
if (x.getP() == IntervalNode.nullIntervalNode) {
super.root = y;
} else {
if (x == x.getP().getLeft()) {
x.getP().setLeft(y);
} else {
x.getP().setRight(y);
}
}
// put x on y's left
y.setLeft(x);
x.setP(y);
}
/**
* performs the rightRotation step starting at a given node
* @param y the node at which rotation needs to occur
*/
private final void rightRotate(IntervalNode x) {
//System.out.println("right " + x);
if (x.getLeft() == IntervalNode.nullIntervalNode)
return;
IntervalNode y = x.getLeft();
// turn x's left subtree into y's right subtree
x.setLeft(y.getRight());
if (y.getRight() != IntervalNode.nullIntervalNode)
y.getRight().setP(x);
y.setP(x.getP());
if (x.getP() == IntervalNode.nullIntervalNode) {
super.root = y;
} else {
if (x == x.getP().getRight()) {
x.getP().setRight(y);
} else {
x.getP().setLeft(y);
}
}
y.setRight(x);
x.setP(y);
}
/**
* inserts a node into the tree and then performs the operations
* necessary to balance the tree
* @param x the new node to insert
*/
public void insert(IntervalNode x) {
// tree insert
super.insert(x);
IntervalNode y;
x.color = IntervalNode.RED;
while ((x != super.root) && (x.getP().color == IntervalNode.RED)) {
if (x.getP() == x.getP().getP().getLeft()) {
y = x.getP().getP().getRight();
if (y.color == IntervalNode.RED) {
x.getP().color = IntervalNode.BLACK;
y.color = IntervalNode.BLACK;
x.getP().getP().color = IntervalNode.RED;
x = x.getP().getP();
} else {
if (x == x.getP().getRight()) {
x = x.getP();
leftRotate(x);
}
x.getP().color = IntervalNode.BLACK;
x.getP().getP().color = IntervalNode.RED;
rightRotate(x.getP().getP());
}
} else {
//System.out.println("1");
y = x.getP().getP().getLeft();
if (y.color == IntervalNode.RED) {
//System.out.println("2");
x.getP().color = IntervalNode.BLACK;
y.color = IntervalNode.BLACK;
x.getP().getP().color = IntervalNode.RED;
x = x.getP().getP();
} else {
//System.out.println("3");
if (x == x.getP().getLeft()) {
//System.out.println("4");
x = x.getP();
rightRotate(x);
}
x.getP().color = IntervalNode.BLACK;
x.getP().getP().color = IntervalNode.RED;
leftRotate(x.getP().getP());
}
}
}
super.root.color = IntervalNode.BLACK;
}
/**
* deletes the given node z from the tree and does the
* balancing necessary to maintain tree height
* @param z the node to delete
*/
public IntervalNode delete(IntervalNode z) {
IntervalNode y;
IntervalNode x;
if ((z.getLeft() == IntervalNode.nullIntervalNode) ||
(z.getRight() == IntervalNode.nullIntervalNode)) {
y = z;
} else {
y = super.successor(z);
}
if (y.getLeft() != IntervalNode.nullIntervalNode) {
x = y.getLeft();
} else {
x = y.getRight();
}
x.setP(y.getP());
if (y.getP() == IntervalNode.nullIntervalNode) {
super.root = x;
} else {
if (y == y.getP().getLeft()) {
y.getP().setLeft(x);
} else {
y.getP().setRight(x);
}
}
if (y != z) {
z.low = y.low;
}
if (y.color = IntervalNode.BLACK)
deleteFixup(x);
return y;
}
/**
* a continuation of the delete operation. We need to fix up
* random things to maintain balance
* @param x the node where the fixup should start
*/
private final void deleteFixup(IntervalNode x) {
IntervalNode w;
while ((x != IntervalNode.nullIntervalNode) && (x.color == IntervalNode.BLACK)) {
if (x == x.getP().getLeft()) {
w = x.getP().getRight();
if (w.color == IntervalNode.RED) {
w.color = IntervalNode.BLACK;
x.getP().color = IntervalNode.RED;
leftRotate(x.getP());
}
if ((w.getLeft().color == IntervalNode.BLACK) &&
(w.getRight().color == IntervalNode.BLACK)) {
w.color = IntervalNode.RED;
x = x.getP();
} else {
if (w.getRight().color == IntervalNode.BLACK) {
w.getLeft().color = IntervalNode.BLACK;
w.color = IntervalNode.RED;
rightRotate(w);
w = x.getP().getRight();
}
w.color = x.getP().color;
x.getP().color = IntervalNode.BLACK;
w.getRight().color = IntervalNode.BLACK;
leftRotate(x.getP());
x = super.root;
}
} else {
// same as above, right and left exchanged
w = x.getP().getLeft();
if (w.color == IntervalNode.RED) {
w.color = IntervalNode.BLACK;
x.getP().color = IntervalNode.RED;
leftRotate(x.getP());
}
if ((w.getRight().color == IntervalNode.BLACK) &&
(w.getLeft().color == IntervalNode.BLACK)) {
w.color = IntervalNode.RED;
x = x.getP();
} else {
if (w.getLeft().color == IntervalNode.BLACK) {
w.getRight().color = IntervalNode.BLACK;
w.color = IntervalNode.RED;
rightRotate(w);
w = x.getP().getLeft();
}
w.color = x.getP().color;
x.getP().color = IntervalNode.BLACK;
w.getLeft().color = IntervalNode.BLACK;
leftRotate(x.getP());
x = super.root;
}
}
}
x.color = IntervalNode.BLACK;
}
}
| carvalhomb/tsmells | guess/guess-src/com/hp/hpl/guess/util/intervals/RBTree.java | Java | gpl-2.0 | 6,305 |
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<!-- /home/test1/tmp/qtopia/qt//qtopia-core-opensource-src-4.3.6/doc/src/examples/pbuffers.qdoc -->
<head>
<title>Qt 4.3: Pixel Buffers Example</title>
<link href="classic.css" rel="stylesheet" type="text/css" />
</head>
<body>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td align="left" valign="top" width="32"><a href="http://www.trolltech.com/products/qt"><img src="images/qt-logo.png" align="left" width="32" height="32" border="0" /></a></td>
<td width="1"> </td><td class="postheader" valign="center"><a href="index.html"><font color="#004faf">Home</font></a> · <a href="classes.html"><font color="#004faf">All Classes</font></a> · <a href="mainclasses.html"><font color="#004faf">Main Classes</font></a> · <a href="groups.html"><font color="#004faf">Grouped Classes</font></a> · <a href="modules.html"><font color="#004faf">Modules</font></a> · <a href="functions.html"><font color="#004faf">Functions</font></a></td>
<td align="right" valign="top" width="230"><a href="http://www.trolltech.com"><img src="images/trolltech-logo.png" align="right" width="203" height="32" border="0" /></a></td></tr></table><h1 class="title">Pixel Buffers Example<br /><span class="subtitle"></span>
</h1>
<p>Files:</p>
<ul>
<li><a href="opengl-pbuffers-glwidget-cpp.html">opengl/pbuffers/glwidget.cpp</a></li>
<li><a href="opengl-pbuffers-glwidget-h.html">opengl/pbuffers/glwidget.h</a></li>
<li><a href="opengl-pbuffers-main-cpp.html">opengl/pbuffers/main.cpp</a></li>
<li><a href="opengl-pbuffers-pbuffers-pro.html">opengl/pbuffers/pbuffers.pro</a></li>
<li><a href="opengl-pbuffers-pbuffers-qrc.html">opengl/pbuffers/pbuffers.qrc</a></li>
</ul>
<p>The Pixel Buffers example demonstrates how to use the <a href="qglpixelbuffer.html">QGLPixelBuffer</a> class to render into an off-screen buffer and use the contents as a dynamic texture in a <a href="qglwidget.html">QGLWidget</a>.</p>
<p align="center"><img src="images/pbuffers-example.png" /></p><p /><address><hr /><div align="center">
<table width="100%" cellspacing="0" border="0"><tr class="address">
<td width="30%">Copyright © 2008 <a href="trolltech.html">Trolltech</a></td>
<td width="40%" align="center"><a href="trademarks.html">Trademarks</a></td>
<td width="30%" align="right"><div align="right">Qt 4.3.6</div></td>
</tr></table></div></address></body>
</html>
| muromec/qtopia-ezx | qtopiacore/qt/doc/html/opengl-pbuffers.html | HTML | gpl-2.0 | 2,636 |
/*
* Copyright (c) 2009, 2010 and 2011 Frank G. Bennett, Jr. All Rights
* Reserved.
*
* The contents of this file are subject to the Common Public
* Attribution License Version 1.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://bitbucket.org/fbennett/citeproc-js/src/tip/LICENSE.
*
* The License is based on the Mozilla Public License Version 1.1 but
* Sections 14 and 15 have been added to cover use of software over a
* computer network and provide for limited attribution for the
* Original Developer. In addition, Exhibit A has been modified to be
* consistent with Exhibit B.
*
* Software distributed under the License is distributed on an “AS IS”
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
* the License for the specific language governing rights and limitations
* under the License.
*
* The Original Code is the citation formatting software known as
* "citeproc-js" (an implementation of the Citation Style Language
* [CSL]), including the original test fixtures and software located
* under the ./std subdirectory of the distribution archive.
*
* The Original Developer is not the Initial Developer and is
* __________. If left blank, the Original Developer is the Initial
* Developer.
*
* The Initial Developer of the Original Code is Frank G. Bennett,
* Jr. All portions of the code written by Frank G. Bennett, Jr. are
* Copyright (c) 2009, 2010 and 2011 Frank G. Bennett, Jr. All Rights Reserved.
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU Affero General Public License (the [AGPLv3]
* License), in which case the provisions of [AGPLv3] License are
* applicable instead of those above. If you wish to allow use of your
* version of this file only under the terms of the [AGPLv3] License
* and not to allow others to use your version of this file under the
* CPAL, indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by the
* [AGPLv3] License. If you do not delete the provisions above, a
* recipient may use your version of this file under either the CPAL
* or the [AGPLv3] License.”
*/
dojo.provide("citeproc_js.dateparsetoarray");
var keycount = function(obj){
var c=0;
for (pos in obj) {
c+=1;
}
return c;
};
doh.register("tests.dateparsetoarray", [
function test_dateparsetoarray029() {
var parser = new CSL.DateParser;
parser.returnAsArray();
var res = parser.parse("Aug 15 2000 - Aug 20 2000");
doh.assertEqual("2000", res["date-parts"][1][0]);
doh.assertEqual("8", res["date-parts"][0][1]);
doh.assertEqual("20", res["date-parts"][1][2]);
doh.assertEqual("2000", res["date-parts"][0][0]);
doh.assertEqual("8", res["date-parts"][1][1]);
doh.assertEqual("15", res["date-parts"][0][2]);
doh.assertEqual(1, keycount(res) );
}
]);
| co-alliance/adr | sites/all/modules/islandora_contrib/islandora_scholar/modules/citeproc/lib/citeproc-js/tests/citeproc-js/dateparsetoarray.js | JavaScript | gpl-2.0 | 3,021 |
/*
* WPA Supplicant / wrapper functions for libcrypto
* Copyright (c) 2004-2005, Jouni Malinen <j@w1.fi>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* Alternatively, this software may be distributed under the terms of BSD
* license.
*
* See README and COPYING for more details.
*/
#include "includes.h"
#include <openssl/opensslv.h>
#include <openssl/md4.h>
#include <openssl/md5.h>
#include <openssl/sha.h>
#include <openssl/des.h>
#include <openssl/aes.h>
#include <openssl/bn.h>
#include <openssl/evp.h>
#include "common.h"
#include "crypto.h"
#if OPENSSL_VERSION_NUMBER < 0x00907000
#define DES_key_schedule des_key_schedule
#define DES_cblock des_cblock
#define DES_set_key(key, schedule) des_set_key((key), *(schedule))
#define DES_ecb_encrypt(input, output, ks, enc) \
des_ecb_encrypt((input), (output), *(ks), (enc))
#endif /* openssl < 0.9.7 */
void md4_vector(size_t num_elem, const u8 *addr[], const size_t *len, u8 *mac)
{
MD4_CTX ctx;
size_t i;
MD4_Init(&ctx);
for (i = 0; i < num_elem; i++)
MD4_Update(&ctx, addr[i], len[i]);
MD4_Final(mac, &ctx);
}
void des_encrypt(const u8 *clear, const u8 *key, u8 *cypher)
{
u8 pkey[8], next, tmp;
int i;
DES_key_schedule ks;
/* Add parity bits to the key */
next = 0;
for (i = 0; i < 7; i++) {
tmp = key[i];
pkey[i] = (tmp >> i) | next | 1;
next = tmp << (7 - i);
}
pkey[i] = next | 1;
DES_set_key(&pkey, &ks);
DES_ecb_encrypt((DES_cblock *) clear, (DES_cblock *) cypher, &ks,
DES_ENCRYPT);
}
void md5_vector(size_t num_elem, const u8 *addr[], const size_t *len, u8 *mac)
{
MD5_CTX ctx;
size_t i;
MD5_Init(&ctx);
for (i = 0; i < num_elem; i++)
MD5_Update(&ctx, addr[i], len[i]);
MD5_Final(mac, &ctx);
}
void sha1_vector(size_t num_elem, const u8 *addr[], const size_t *len, u8 *mac)
{
SHA_CTX ctx;
size_t i;
SHA1_Init(&ctx);
for (i = 0; i < num_elem; i++)
SHA1_Update(&ctx, addr[i], len[i]);
SHA1_Final(mac, &ctx);
}
#ifndef CONFIG_NO_FIPS186_2_PRF
static void sha1_transform(u8 *state, const u8 data[64])
{
SHA_CTX context;
os_memset(&context, 0, sizeof(context));
os_memcpy(&context.h0, state, 5 * 4);
SHA1_Transform(&context, data);
os_memcpy(state, &context.h0, 5 * 4);
}
int fips186_2_prf(const u8 *seed, size_t seed_len, u8 *x, size_t xlen)
{
u8 xkey[64];
u32 t[5], _t[5];
int i, j, m, k;
u8 *xpos = x;
u32 carry;
if (seed_len > sizeof(xkey))
seed_len = sizeof(xkey);
/* FIPS 186-2 + change notice 1 */
os_memcpy(xkey, seed, seed_len);
os_memset(xkey + seed_len, 0, 64 - seed_len);
t[0] = 0x67452301;
t[1] = 0xEFCDAB89;
t[2] = 0x98BADCFE;
t[3] = 0x10325476;
t[4] = 0xC3D2E1F0;
m = xlen / 40;
for (j = 0; j < m; j++) {
/* XSEED_j = 0 */
for (i = 0; i < 2; i++) {
/* XVAL = (XKEY + XSEED_j) mod 2^b */
/* w_i = G(t, XVAL) */
os_memcpy(_t, t, 20);
sha1_transform((u8 *) _t, xkey);
_t[0] = host_to_be32(_t[0]);
_t[1] = host_to_be32(_t[1]);
_t[2] = host_to_be32(_t[2]);
_t[3] = host_to_be32(_t[3]);
_t[4] = host_to_be32(_t[4]);
os_memcpy(xpos, _t, 20);
/* XKEY = (1 + XKEY + w_i) mod 2^b */
carry = 1;
for (k = 19; k >= 0; k--) {
carry += xkey[k] + xpos[k];
xkey[k] = carry & 0xff;
carry >>= 8;
}
xpos += 20;
}
/* x_j = w_0|w_1 */
}
return 0;
}
#endif /* CONFIG_NO_FIPS186_2_PRF */
void * aes_encrypt_init(const u8 *key, size_t len)
{
AES_KEY *ak;
ak = os_malloc(sizeof(*ak));
if (ak == NULL)
return NULL;
if (AES_set_encrypt_key(key, 8 * len, ak) < 0) {
os_free(ak);
return NULL;
}
return ak;
}
void aes_encrypt(void *ctx, const u8 *plain, u8 *crypt)
{
AES_encrypt(plain, crypt, ctx);
}
void aes_encrypt_deinit(void *ctx)
{
os_free(ctx);
}
void * aes_decrypt_init(const u8 *key, size_t len)
{
AES_KEY *ak;
ak = os_malloc(sizeof(*ak));
if (ak == NULL)
return NULL;
if (AES_set_decrypt_key(key, 8 * len, ak) < 0) {
os_free(ak);
return NULL;
}
return ak;
}
void aes_decrypt(void *ctx, const u8 *crypt, u8 *plain)
{
AES_decrypt(crypt, plain, ctx);
}
void aes_decrypt_deinit(void *ctx)
{
os_free(ctx);
}
int crypto_mod_exp(const u8 *base, size_t base_len,
const u8 *power, size_t power_len,
const u8 *modulus, size_t modulus_len,
u8 *result, size_t *result_len)
{
BIGNUM *bn_base, *bn_exp, *bn_modulus, *bn_result;
int ret = -1;
BN_CTX *ctx;
ctx = BN_CTX_new();
if (ctx == NULL)
return -1;
bn_base = BN_bin2bn(base, base_len, NULL);
bn_exp = BN_bin2bn(power, power_len, NULL);
bn_modulus = BN_bin2bn(modulus, modulus_len, NULL);
bn_result = BN_new();
if (bn_base == NULL || bn_exp == NULL || bn_modulus == NULL ||
bn_result == NULL)
goto error;
if (BN_mod_exp(bn_result, bn_base, bn_exp, bn_modulus, ctx) != 1)
goto error;
*result_len = BN_bn2bin(bn_result, result);
ret = 0;
error:
BN_free(bn_base);
BN_free(bn_exp);
BN_free(bn_modulus);
BN_free(bn_result);
BN_CTX_free(ctx);
return ret;
}
struct crypto_cipher {
EVP_CIPHER_CTX enc;
EVP_CIPHER_CTX dec;
};
struct crypto_cipher * crypto_cipher_init(enum crypto_cipher_alg alg,
const u8 *iv, const u8 *key,
size_t key_len)
{
struct crypto_cipher *ctx;
const EVP_CIPHER *cipher;
ctx = os_zalloc(sizeof(*ctx));
if (ctx == NULL)
return NULL;
switch (alg) {
#ifndef OPENSSL_NO_RC4
case CRYPTO_CIPHER_ALG_RC4:
cipher = EVP_rc4();
break;
#endif /* OPENSSL_NO_RC4 */
#ifndef OPENSSL_NO_AES
case CRYPTO_CIPHER_ALG_AES:
switch (key_len) {
case 16:
cipher = EVP_aes_128_cbc();
break;
case 24:
cipher = EVP_aes_192_cbc();
break;
case 32:
cipher = EVP_aes_256_cbc();
break;
default:
os_free(ctx);
return NULL;
}
break;
#endif /* OPENSSL_NO_AES */
#ifndef OPENSSL_NO_DES
case CRYPTO_CIPHER_ALG_3DES:
cipher = EVP_des_ede3_cbc();
break;
case CRYPTO_CIPHER_ALG_DES:
cipher = EVP_des_cbc();
break;
#endif /* OPENSSL_NO_DES */
#ifndef OPENSSL_NO_RC2
case CRYPTO_CIPHER_ALG_RC2:
cipher = EVP_rc2_ecb();
break;
#endif /* OPENSSL_NO_RC2 */
default:
os_free(ctx);
return NULL;
}
EVP_CIPHER_CTX_init(&ctx->enc);
EVP_CIPHER_CTX_set_padding(&ctx->enc, 0);
if (!EVP_EncryptInit_ex(&ctx->enc, cipher, NULL, NULL, NULL) ||
!EVP_CIPHER_CTX_set_key_length(&ctx->enc, key_len) ||
!EVP_EncryptInit_ex(&ctx->enc, cipher, NULL, key, iv)) {
EVP_CIPHER_CTX_cleanup(&ctx->enc);
os_free(ctx);
return NULL;
}
EVP_CIPHER_CTX_init(&ctx->dec);
EVP_CIPHER_CTX_set_padding(&ctx->dec, 0);
if (!EVP_DecryptInit_ex(&ctx->dec, cipher, NULL, NULL, NULL) ||
!EVP_CIPHER_CTX_set_key_length(&ctx->dec, key_len) ||
!EVP_DecryptInit_ex(&ctx->dec, cipher, NULL, key, iv)) {
EVP_CIPHER_CTX_cleanup(&ctx->enc);
EVP_CIPHER_CTX_cleanup(&ctx->dec);
os_free(ctx);
return NULL;
}
return ctx;
}
int crypto_cipher_encrypt(struct crypto_cipher *ctx, const u8 *plain,
u8 *crypt, size_t len)
{
int outl;
if (!EVP_EncryptUpdate(&ctx->enc, crypt, &outl, plain, len))
return -1;
return 0;
}
int crypto_cipher_decrypt(struct crypto_cipher *ctx, const u8 *crypt,
u8 *plain, size_t len)
{
int outl;
outl = len;
if (!EVP_DecryptUpdate(&ctx->dec, plain, &outl, crypt, len))
return -1;
return 0;
}
void crypto_cipher_deinit(struct crypto_cipher *ctx)
{
EVP_CIPHER_CTX_cleanup(&ctx->enc);
EVP_CIPHER_CTX_cleanup(&ctx->dec);
os_free(ctx);
}
| stevelord/PR30 | linux-2.6.31/ti/WiLink62_AP/CUDK/hostapd/src/crypto/crypto_openssl.c | C | gpl-2.0 | 7,443 |
/*
* MATLAB Compiler: 3.0
* Date: Thu May 3 10:27:14 2007
* Arguments: "-B" "macro_default" "-O" "all" "-O" "fold_scalar_mxarrays:on"
* "-O" "fold_non_scalar_mxarrays:on" "-O" "optimize_integer_for_loops:on" "-O"
* "array_indexing:on" "-O" "optimize_conditionals:on" "-m" "-W" "main" "-L"
* "C" "-t" "-T" "link:exe" "-h" "libmmfile.mlib" "./src/wavelet.m" "-d"
* "./build" "-I" "/usr/local/matlab6p5/toolbox/wavelet/wavelet/" "-I"
* "/usr/local/matlab6p5/toolbox/matlab/general/" "-W" "main" "-T" "link:exe"
* "-v"
*/
#ifndef MLF_V2
#define MLF_V2 1
#endif
#ifndef __wconv_h
#define __wconv_h 1
#ifdef __cplusplus
extern "C" {
#endif
#include "libmatlb.h"
extern void InitializeModule_wconv(void);
extern void TerminateModule_wconv(void);
extern _mexLocalFunctionTable _local_function_table_wconv;
extern mxArray * mlfNWconv(int nargout,
mxArray * type,
mxArray * x,
mxArray * f);
extern mxArray * mlfWconv(mxArray * type, mxArray * x, mxArray * f);
extern void mlfVWconv(mxArray * type, mxArray * x, mxArray * f);
extern void mlxWconv(int nlhs, mxArray * plhs[], int nrhs, mxArray * prhs[]);
#ifdef __cplusplus
}
#endif
#endif
| matthewlinks/biolet | build/wconv.h | C | gpl-2.0 | 1,229 |
/*
*
Copyright 2008 RobertoPinho. All rights reserved.
This file is part of incboard.api.
incboard.api 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.
incboard.api 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 incboard.api. If not, see <http://www.gnu.org/licenses/>.
For academic use, please cite:
Pinho, R, de Oliveira, M.C. and Lopes, A. A. 2009.
Incremental Board: A grid-based space for visualizing dynamic data sets.
In Proceedings of the 2009 ACM Symposium on Applied Computing
(Honolulu, Hawaii, USA, March 8 - 12, 2009). SAC '09. ACM, New York, NY.
(to appear)
*/
package incboard.api;
/**
*
* @author RobertoPinho
*/
public interface DataItemInterface {
public String getURI();
public int getCol();
public int getRow();
void setCol(int x);
void setRow(int y);
public Double getDistance(DataItemInterface other);
}
| robertodepinho/HexBoard-API | src/incboard/api/DataItemInterface.java | Java | gpl-2.0 | 1,379 |
<?php
/**
***********************************************************************************************
* Common functions for Email Templates
*
* @copyright 2004-2016 The Admidio Team
* @see https://www.admidio.org/
* @license https://www.gnu.org/licenses/gpl-2.0.html GNU General Public License v2.0 only
***********************************************************************************************
*/
if (basename($_SERVER['SCRIPT_FILENAME']) === 'template.php')
{
exit('This page may not be called directly!');
}
/**
* Function to Read a file and store all data into a variable
* @param string $filename
* @return string
*/
function admReadTemplateFile($filename)
{
if (is_file(SERVER_PATH. '/adm_my_files/mail_templates/'.$filename))
{
$fp = fopen(SERVER_PATH. '/adm_my_files/mail_templates/'.$filename, 'r');
$str = '';
while(!feof($fp))
{
$str .= fread($fp, 1024);
}
return $str;
}
return '#message#';
}
| wilddom/admidio | adm_program/system/template.php | PHP | gpl-2.0 | 1,011 |
<?php
$currency = '$';
$db_username = 'root';
$db_password = '';
$db_name = 'db_cart';
$db_host = 'localhost';
$mysqli = new mysqli($db_host, $db_username, $db_password,$db_name);
?> | osaeljm/hola | PROYECTO/AAArchivosBorrador/Config.php | PHP | gpl-2.0 | 183 |
/* Copyright 2008-2012 Freescale Semiconductor, Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Freescale Semiconductor nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
*
* ALTERNATIVELY, this software may be distributed under the terms of the
* GNU General Public License ("GPL") as published by the Free Software
* Foundation, either version 2 of that License or (at your option) any
* later version.
*
* THIS SOFTWARE IS PROVIDED BY Freescale Semiconductor ``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 Freescale Semiconductor BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <asm/cacheflush.h>
#include "qman_private.h"
/* Last updated for v00.800 of the BG */
/* Register offsets */
#define REG_QCSP_LIO_CFG(n) (0x0000 + ((n) * 0x10))
#define REG_QCSP_IO_CFG(n) (0x0004 + ((n) * 0x10))
#define REG_QCSP_DD_CFG(n) (0x000c + ((n) * 0x10))
#define REG_DD_CFG 0x0200
#define REG_DCP_CFG(n) (0x0300 + ((n) * 0x10))
#define REG_DCP_DD_CFG(n) (0x0304 + ((n) * 0x10))
#define REG_DCP_DLM_AVG(n) (0x030c + ((n) * 0x10))
#define REG_PFDR_FPC 0x0400
#define REG_PFDR_FP_HEAD 0x0404
#define REG_PFDR_FP_TAIL 0x0408
#define REG_PFDR_FP_LWIT 0x0410
#define REG_PFDR_CFG 0x0414
#define REG_SFDR_CFG 0x0500
#define REG_SFDR_IN_USE 0x0504
#define REG_WQ_CS_CFG(n) (0x0600 + ((n) * 0x04))
#define REG_WQ_DEF_ENC_WQID 0x0630
#define REG_WQ_SC_DD_CFG(n) (0x640 + ((n) * 0x04))
#define REG_WQ_PC_DD_CFG(n) (0x680 + ((n) * 0x04))
#define REG_WQ_DC0_DD_CFG(n) (0x6c0 + ((n) * 0x04))
#define REG_WQ_DC1_DD_CFG(n) (0x700 + ((n) * 0x04))
#define REG_WQ_DCn_DD_CFG(n) (0x6c0 + ((n) * 0x40)) /* n=2,3 */
#define REG_CM_CFG 0x0800
#define REG_ECSR 0x0a00
#define REG_ECIR 0x0a04
#define REG_EADR 0x0a08
#define REG_ECIR2 0x0a0c
#define REG_EDATA(n) (0x0a10 + ((n) * 0x04))
#define REG_SBEC(n) (0x0a80 + ((n) * 0x04))
#define REG_MCR 0x0b00
#define REG_MCP(n) (0x0b04 + ((n) * 0x04))
#define REG_MISC_CFG 0x0be0
#define REG_HID_CFG 0x0bf0
#define REG_IDLE_STAT 0x0bf4
#define REG_IP_REV_1 0x0bf8
#define REG_IP_REV_2 0x0bfc
#define REG_FQD_BARE 0x0c00
#define REG_PFDR_BARE 0x0c20
#define REG_offset_BAR 0x0004 /* relative to REG_[FQD|PFDR]_BARE */
#define REG_offset_AR 0x0010 /* relative to REG_[FQD|PFDR]_BARE */
#define REG_QCSP_BARE 0x0c80
#define REG_QCSP_BAR 0x0c84
#define REG_CI_SCHED_CFG 0x0d00
#define REG_SRCIDR 0x0d04
#define REG_LIODNR 0x0d08
#define REG_CI_RLM_AVG 0x0d14
#define REG_ERR_ISR 0x0e00 /* + "enum qm_isr_reg" */
#define REG_REV3_QCSP_LIO_CFG(n) (0x1000 + ((n) * 0x10))
#define REG_REV3_QCSP_IO_CFG(n) (0x1004 + ((n) * 0x10))
#define REG_REV3_QCSP_DD_CFG(n) (0x100c + ((n) * 0x10))
#define REG_CEETM_CFG_IDX 0x900
#define REG_CEETM_CFG_PRES 0x904
#define REG_CEETM_XSFDR_IN_USE 0x908
/* Assists for QMAN_MCR */
#define MCR_INIT_PFDR 0x01000000
#define MCR_get_rslt(v) (u8)((v) >> 24)
#define MCR_rslt_idle(r) (!rslt || (rslt >= 0xf0))
#define MCR_rslt_ok(r) (rslt == 0xf0)
#define MCR_rslt_eaccess(r) (rslt == 0xf8)
#define MCR_rslt_inval(r) (rslt == 0xff)
struct qman;
/* Follows WQ_CS_CFG0-5 */
enum qm_wq_class {
qm_wq_portal = 0,
qm_wq_pool = 1,
qm_wq_fman0 = 2,
qm_wq_fman1 = 3,
qm_wq_caam = 4,
qm_wq_pme = 5,
qm_wq_first = qm_wq_portal,
qm_wq_last = qm_wq_pme
};
/* Follows FQD_[BARE|BAR|AR] and PFDR_[BARE|BAR|AR] */
enum qm_memory {
qm_memory_fqd,
qm_memory_pfdr
};
/* Used by all error interrupt registers except 'inhibit' */
#define QM_EIRQ_CIDE 0x20000000 /* Corenet Initiator Data Error */
#define QM_EIRQ_CTDE 0x10000000 /* Corenet Target Data Error */
#define QM_EIRQ_CITT 0x08000000 /* Corenet Invalid Target Transaction */
#define QM_EIRQ_PLWI 0x04000000 /* PFDR Low Watermark */
#define QM_EIRQ_MBEI 0x02000000 /* Multi-bit ECC Error */
#define QM_EIRQ_SBEI 0x01000000 /* Single-bit ECC Error */
#define QM_EIRQ_PEBI 0x00800000 /* PFDR Enqueues Blocked Interrupt */
#define QM_EIRQ_IFSI 0x00020000 /* Invalid FQ Flow Control State */
#define QM_EIRQ_ICVI 0x00010000 /* Invalid Command Verb */
#define QM_EIRQ_IDDI 0x00000800 /* Invalid Dequeue (Direct-connect) */
#define QM_EIRQ_IDFI 0x00000400 /* Invalid Dequeue FQ */
#define QM_EIRQ_IDSI 0x00000200 /* Invalid Dequeue Source */
#define QM_EIRQ_IDQI 0x00000100 /* Invalid Dequeue Queue */
#define QM_EIRQ_IECE 0x00000010 /* Invalid Enqueue Configuration */
#define QM_EIRQ_IEOI 0x00000008 /* Invalid Enqueue Overflow */
#define QM_EIRQ_IESI 0x00000004 /* Invalid Enqueue State */
#define QM_EIRQ_IECI 0x00000002 /* Invalid Enqueue Channel */
#define QM_EIRQ_IEQI 0x00000001 /* Invalid Enqueue Queue */
/* QMAN_ECIR valid error bit */
#define PORTAL_ECSR_ERR (QM_EIRQ_IEQI | QM_EIRQ_IESI | QM_EIRQ_IEOI | \
QM_EIRQ_IDQI | QM_EIRQ_IDSI | QM_EIRQ_IDFI | \
QM_EIRQ_IDDI | QM_EIRQ_ICVI | QM_EIRQ_IFSI)
#define FQID_ECSR_ERR (QM_EIRQ_IEQI | QM_EIRQ_IECI | QM_EIRQ_IESI | \
QM_EIRQ_IEOI | QM_EIRQ_IDQI | QM_EIRQ_IDFI | \
QM_EIRQ_IFSI)
union qman_ecir {
u32 ecir_raw;
struct {
u32 __reserved:2;
u32 portal_type:1;
u32 portal_num:5;
u32 fqid:24;
} __packed info;
};
union qman_ecir2 {
u32 ecir2_raw;
struct {
u32 portal_type:1;
u32 __reserved:21;
u32 portal_num:10;
} __packed info;
};
union qman_eadr {
u32 eadr_raw;
struct {
u32 __reserved1:4;
u32 memid:4;
u32 __reserved2:12;
u32 eadr:12;
} __packed info;
struct {
u32 __reserved1:3;
u32 memid:5;
u32 __reserved:8;
u32 eadr:16;
} __packed info_rev3;
};
struct qman_hwerr_txt {
u32 mask;
const char *txt;
};
#define QMAN_HWE_TXT(a, b) { .mask = QM_EIRQ_##a, .txt = b }
static const struct qman_hwerr_txt qman_hwerr_txts[] = {
QMAN_HWE_TXT(CIDE, "Corenet Initiator Data Error"),
QMAN_HWE_TXT(CTDE, "Corenet Target Data Error"),
QMAN_HWE_TXT(CITT, "Corenet Invalid Target Transaction"),
QMAN_HWE_TXT(PLWI, "PFDR Low Watermark"),
QMAN_HWE_TXT(MBEI, "Multi-bit ECC Error"),
QMAN_HWE_TXT(SBEI, "Single-bit ECC Error"),
QMAN_HWE_TXT(PEBI, "PFDR Enqueues Blocked Interrupt"),
QMAN_HWE_TXT(ICVI, "Invalid Command Verb"),
QMAN_HWE_TXT(IFSI, "Invalid Flow Control State"),
QMAN_HWE_TXT(IDDI, "Invalid Dequeue (Direct-connect)"),
QMAN_HWE_TXT(IDFI, "Invalid Dequeue FQ"),
QMAN_HWE_TXT(IDSI, "Invalid Dequeue Source"),
QMAN_HWE_TXT(IDQI, "Invalid Dequeue Queue"),
QMAN_HWE_TXT(IECE, "Invalid Enqueue Configuration"),
QMAN_HWE_TXT(IEOI, "Invalid Enqueue Overflow"),
QMAN_HWE_TXT(IESI, "Invalid Enqueue State"),
QMAN_HWE_TXT(IECI, "Invalid Enqueue Channel"),
QMAN_HWE_TXT(IEQI, "Invalid Enqueue Queue")
};
#define QMAN_HWE_COUNT (sizeof(qman_hwerr_txts)/sizeof(struct qman_hwerr_txt))
struct qman_error_info_mdata {
u16 addr_mask;
u16 bits;
const char *txt;
};
#define QMAN_ERR_MDATA(a, b, c) { .addr_mask = a, .bits = b, .txt = c}
static const struct qman_error_info_mdata error_mdata[] = {
QMAN_ERR_MDATA(0x01FF, 24, "FQD cache tag memory 0"),
QMAN_ERR_MDATA(0x01FF, 24, "FQD cache tag memory 1"),
QMAN_ERR_MDATA(0x01FF, 24, "FQD cache tag memory 2"),
QMAN_ERR_MDATA(0x01FF, 24, "FQD cache tag memory 3"),
QMAN_ERR_MDATA(0x0FFF, 512, "FQD cache memory"),
QMAN_ERR_MDATA(0x07FF, 128, "SFDR memory"),
QMAN_ERR_MDATA(0x01FF, 72, "WQ context memory"),
QMAN_ERR_MDATA(0x00FF, 240, "CGR memory"),
QMAN_ERR_MDATA(0x00FF, 302, "Internal Order Restoration List memory"),
QMAN_ERR_MDATA(0x01FF, 256, "SW portal ring memory"),
QMAN_ERR_MDATA(0x07FF, 181, "CEETM class queue descriptor memory"),
QMAN_ERR_MDATA(0x0FFF, 140, "CEETM extended SFDR memory"),
QMAN_ERR_MDATA(0x0FFF, 25, "CEETM logical FQ mapping memory"),
QMAN_ERR_MDATA(0x0FFF, 96, "CEETM dequeue context memory"),
QMAN_ERR_MDATA(0x07FF, 396, "CEETM ccgr memory"),
QMAN_ERR_MDATA(0x00FF, 146, "CEETM CQ channel shaping memory"),
QMAN_ERR_MDATA(0x007F, 256, "CEETM CQ channel scheduling memory"),
QMAN_ERR_MDATA(0x01FF, 88, "CEETM dequeue statistics memory"),
};
#define QMAN_ERR_MDATA_COUNT \
(sizeof(error_mdata)/sizeof(struct qman_error_info_mdata))
/* Add this in Kconfig */
#define QMAN_ERRS_TO_UNENABLE (QM_EIRQ_PLWI | QM_EIRQ_PEBI)
/**
* qm_err_isr_<reg>_<verb> - Manipulate global interrupt registers
* @v: for accessors that write values, this is the 32-bit value
*
* Manipulates QMAN_ERR_ISR, QMAN_ERR_IER, QMAN_ERR_ISDR, QMAN_ERR_IIR. All
* manipulations except qm_err_isr_[un]inhibit() use 32-bit masks composed of
* the QM_EIRQ_*** definitions. Note that "qm_err_isr_enable_write" means
* "write the enable register" rather than "enable the write register"!
*/
#define qm_err_isr_status_read(qm) \
__qm_err_isr_read(qm, qm_isr_status)
#define qm_err_isr_status_clear(qm, m) \
__qm_err_isr_write(qm, qm_isr_status, m)
#define qm_err_isr_enable_read(qm) \
__qm_err_isr_read(qm, qm_isr_enable)
#define qm_err_isr_enable_write(qm, v) \
__qm_err_isr_write(qm, qm_isr_enable, v)
#define qm_err_isr_disable_read(qm) \
__qm_err_isr_read(qm, qm_isr_disable)
#define qm_err_isr_disable_write(qm, v) \
__qm_err_isr_write(qm, qm_isr_disable, v)
#define qm_err_isr_inhibit(qm) \
__qm_err_isr_write(qm, qm_isr_inhibit, 1)
#define qm_err_isr_uninhibit(qm) \
__qm_err_isr_write(qm, qm_isr_inhibit, 0)
/*
* TODO: unimplemented registers
*
* Keeping a list here of Qman registers I have not yet covered;
* QCSP_DD_IHRSR, QCSP_DD_IHRFR, QCSP_DD_HASR,
* DCP_DD_IHRSR, DCP_DD_IHRFR, DCP_DD_HASR, CM_CFG,
* QMAN_EECC, QMAN_SBET, QMAN_EINJ, QMAN_SBEC0-12
*/
/* Encapsulate "struct qman *" as a cast of the register space address. */
static struct qman *qm_create(void *regs)
{
return (struct qman *)regs;
}
static inline u32 __qm_in(struct qman *qm, u32 offset)
{
return in_be32((void *)qm + offset);
}
static inline void __qm_out(struct qman *qm, u32 offset, u32 val)
{
out_be32((void *)qm + offset, val);
}
#define qm_in(reg) __qm_in(qm, REG_##reg)
#define qm_out(reg, val) __qm_out(qm, REG_##reg, val)
static u32 __qm_err_isr_read(struct qman *qm, enum qm_isr_reg n)
{
return __qm_in(qm, REG_ERR_ISR + (n << 2));
}
static void __qm_err_isr_write(struct qman *qm, enum qm_isr_reg n, u32 val)
{
__qm_out(qm, REG_ERR_ISR + (n << 2), val);
}
static void qm_set_dc(struct qman *qm, enum qm_dc_portal portal,
int ed, u8 sernd)
{
DPA_ASSERT(!ed || (portal == qm_dc_portal_fman0) ||
(portal == qm_dc_portal_fman1));
if ((qman_ip_rev & 0xFF00) >= QMAN_REV30)
qm_out(DCP_CFG(portal), (ed ? 0x1000 : 0) | (sernd & 0x3ff));
else
qm_out(DCP_CFG(portal), (ed ? 0x100 : 0) | (sernd & 0x1f));
}
static void qm_set_wq_scheduling(struct qman *qm, enum qm_wq_class wq_class,
u8 cs_elev, u8 csw2, u8 csw3, u8 csw4, u8 csw5,
u8 csw6, u8 csw7)
{
qm_out(WQ_CS_CFG(wq_class), ((cs_elev & 0xff) << 24) |
((csw2 & 0x7) << 20) | ((csw3 & 0x7) << 16) |
((csw4 & 0x7) << 12) | ((csw5 & 0x7) << 8) |
((csw6 & 0x7) << 4) | (csw7 & 0x7));
}
static void qm_set_hid(struct qman *qm)
{
qm_out(HID_CFG, 0);
}
static void qm_set_corenet_initiator(struct qman *qm)
{
qm_out(CI_SCHED_CFG,
0x80000000 | /* write srcciv enable */
(CONFIG_FSL_QMAN_CI_SCHED_CFG_SRCCIV << 24) |
(CONFIG_FSL_QMAN_CI_SCHED_CFG_SRQ_W << 8) |
(CONFIG_FSL_QMAN_CI_SCHED_CFG_RW_W << 4) |
CONFIG_FSL_QMAN_CI_SCHED_CFG_BMAN_W);
}
static void qm_get_version(struct qman *qm, u16 *id, u8 *major, u8 *minor,
u8 *cfg)
{
u32 v = qm_in(IP_REV_1);
u32 v2 = qm_in(IP_REV_2);
*id = (v >> 16);
*major = (v >> 8) & 0xff;
*minor = v & 0xff;
*cfg = v2 & 0xff;
}
static void qm_set_memory(struct qman *qm, enum qm_memory memory, u64 ba,
int enable, int prio, int stash, u32 size)
{
u32 offset = (memory == qm_memory_fqd) ? REG_FQD_BARE : REG_PFDR_BARE;
u32 exp = ilog2(size);
/* choke if size isn't within range */
DPA_ASSERT((size >= 4096) && (size <= 1073741824) &&
is_power_of_2(size));
/* choke if 'ba' has lower-alignment than 'size' */
DPA_ASSERT(!(ba & (size - 1)));
__qm_out(qm, offset, upper_32_bits(ba));
__qm_out(qm, offset + REG_offset_BAR, lower_32_bits(ba));
__qm_out(qm, offset + REG_offset_AR,
(enable ? 0x80000000 : 0) |
(prio ? 0x40000000 : 0) |
(stash ? 0x20000000 : 0) |
(exp - 1));
}
static void qm_set_pfdr_threshold(struct qman *qm, u32 th, u8 k)
{
qm_out(PFDR_FP_LWIT, th & 0xffffff);
qm_out(PFDR_CFG, k);
}
static void qm_set_sfdr_threshold(struct qman *qm, u16 th)
{
qm_out(SFDR_CFG, th & 0x3ff);
}
static int qm_init_pfdr(struct qman *qm, u32 pfdr_start, u32 num)
{
u8 rslt = MCR_get_rslt(qm_in(MCR));
DPA_ASSERT(pfdr_start && !(pfdr_start & 7) && !(num & 7) && num);
/* Make sure the command interface is 'idle' */
if (!MCR_rslt_idle(rslt))
panic("QMAN_MCR isn't idle");
/* Write the MCR command params then the verb */
qm_out(MCP(0), pfdr_start);
/* TODO: remove this - it's a workaround for a model bug that is
* corrected in more recent versions. We use the workaround until
* everyone has upgraded. */
qm_out(MCP(1), (pfdr_start + num - 16));
lwsync();
qm_out(MCR, MCR_INIT_PFDR);
/* Poll for the result */
do {
rslt = MCR_get_rslt(qm_in(MCR));
} while (!MCR_rslt_idle(rslt));
if (MCR_rslt_ok(rslt))
return 0;
if (MCR_rslt_eaccess(rslt))
return -EACCES;
if (MCR_rslt_inval(rslt))
return -EINVAL;
pr_crit("Unexpected result from MCR_INIT_PFDR: %02x\n", rslt);
return -ENOSYS;
}
/*****************/
/* Config driver */
/*****************/
#define DEFAULT_FQD_SZ (PAGE_SIZE << CONFIG_FSL_QMAN_FQD_SZ)
#define DEFAULT_PFDR_SZ (PAGE_SIZE << CONFIG_FSL_QMAN_PFDR_SZ)
/* We support only one of these */
static struct qman *qm;
static struct device_node *qm_node;
/* And this state belongs to 'qm'. It is set during fsl_qman_init(), but used
* during qman_init_ccsr(). */
static dma_addr_t fqd_a, pfdr_a;
static size_t fqd_sz = DEFAULT_FQD_SZ, pfdr_sz = DEFAULT_PFDR_SZ;
/* Parse the <name> property to extract the memory location and size and
* memblock_reserve() it. If it isn't supplied, memblock_alloc() the default
* size. Also flush this memory range from data cache so that QMAN originated
* transactions for this memory region could be marked non-coherent.
*/
static __init int parse_mem_property(struct device_node *node, const char *name,
dma_addr_t *addr, size_t *sz, int zero)
{
const u32 *pint;
int ret;
unsigned long vaddr;
pint = of_get_property(node, name, &ret);
if (!pint || (ret != 16)) {
pr_info("No %s property '%s', using memblock_alloc(%016zx)\n",
node->full_name, name, *sz);
*addr = memblock_alloc(*sz, *sz);
vaddr = (unsigned long)phys_to_virt(*addr);
if (zero)
memset((void *)vaddr, 0, *sz);
flush_dcache_range(vaddr, vaddr + *sz);
return 0;
}
pr_info("Using %s property '%s'\n", node->full_name, name);
/* If using a "zero-pma", don't try to zero it, even if you asked */
if (zero && of_find_property(node, "zero-pma", &ret)) {
pr_info(" it's a 'zero-pma', not zeroing from s/w\n");
zero = 0;
}
*addr = ((u64)pint[0] << 32) | (u64)pint[1];
*sz = ((u64)pint[2] << 32) | (u64)pint[3];
/* Keep things simple, it's either all in the DRAM range or it's all
* outside. */
if (*addr < memblock_end_of_DRAM()) {
BUG_ON((u64)*addr + (u64)*sz > memblock_end_of_DRAM());
if (memblock_reserve(*addr, *sz) < 0) {
pr_err("Failed to reserve %s\n", name);
return -ENOMEM;
}
vaddr = (unsigned long)phys_to_virt(*addr);
if (zero)
memset(phys_to_virt(*addr), 0, *sz);
flush_dcache_range(vaddr, vaddr + *sz);
} else if (zero) {
/* map as cacheable, non-guarded */
void __iomem *tmpp = ioremap_prot(*addr, *sz, 0);
if (!tmpp)
return -ENOMEM;
memset_io(tmpp, 0, *sz);
vaddr = (unsigned long)tmpp;
flush_dcache_range(vaddr, vaddr + *sz);
iounmap(tmpp);
}
return 0;
}
/* TODO:
* - there is obviously no handling of errors,
* - the calls to qm_set_memory() hard-code the priority and CPC-stashing for
* both memory resources to zero.
*/
static int __init fsl_qman_init(struct device_node *node)
{
struct resource res;
resource_size_t len;
u32 __iomem *regs;
const char *s;
int ret, standby = 0;
u16 id;
u8 major, minor, cfg;
ret = of_address_to_resource(node, 0, &res);
if (ret) {
pr_err("Can't get %s property '%s'\n", node->full_name, "reg");
return ret;
}
s = of_get_property(node, "fsl,hv-claimable", &ret);
if (s && !strcmp(s, "standby"))
standby = 1;
if (!standby) {
ret = parse_mem_property(node, "fsl,qman-fqd",
&fqd_a, &fqd_sz, 1);
BUG_ON(ret);
ret = parse_mem_property(node, "fsl,qman-pfdr",
&pfdr_a, &pfdr_sz, 0);
BUG_ON(ret);
}
/* Global configuration */
len = resource_size(&res);
if (len != (unsigned long)len)
return -EINVAL;
regs = ioremap(res.start, (unsigned long)len);
qm = qm_create(regs);
qm_node = node;
qm_get_version(qm, &id, &major, &minor, &cfg);
pr_info("Qman ver:%04x,%02x,%02x,%02x\n", id, major, minor, cfg);
if (!qman_ip_rev) {
if ((major == 1) && (minor == 0)) {
pr_err("QMAN rev1.0 on P4080 rev1 is not supported!\n");
iounmap(regs);
return -ENODEV;
} else if ((major == 1) && (minor == 1))
qman_ip_rev = QMAN_REV11;
else if ((major == 1) && (minor == 2))
qman_ip_rev = QMAN_REV12;
else if ((major == 2) && (minor == 0))
qman_ip_rev = QMAN_REV20;
else if ((major == 3) && (minor == 0))
qman_ip_rev = QMAN_REV30;
else if ((major == 3) && (minor == 1))
qman_ip_rev = QMAN_REV31;
else {
pr_warn("unknown Qman version, default to rev1.1\n");
qman_ip_rev = QMAN_REV11;
}
qman_ip_cfg = cfg;
}
if (standby) {
pr_info(" -> in standby mode\n");
return 0;
}
return 0;
}
int qman_have_ccsr(void)
{
return qm ? 1 : 0;
}
__init void qman_init_early(void)
{
struct device_node *dn;
int ret;
for_each_compatible_node(dn, NULL, "fsl,qman") {
if (qm)
pr_err("%s: only one 'fsl,qman' allowed\n",
dn->full_name);
else {
if (!of_device_is_available(dn))
continue;
ret = fsl_qman_init(dn);
BUG_ON(ret);
}
}
}
static void log_edata_bits(u32 bit_count)
{
u32 i, j, mask = 0xffffffff;
pr_warn("Qman ErrInt, EDATA:\n");
i = bit_count/32;
if (bit_count%32) {
i++;
mask = ~(mask << bit_count%32);
}
j = 16-i;
pr_warn(" 0x%08x\n", qm_in(EDATA(j)) & mask);
j++;
for (; j < 16; j++)
pr_warn(" 0x%08x\n", qm_in(EDATA(j)));
}
static void log_additional_error_info(u32 isr_val, u32 ecsr_val)
{
union qman_ecir ecir_val;
union qman_eadr eadr_val;
ecir_val.ecir_raw = qm_in(ECIR);
/* Is portal info valid */
if ((qman_ip_rev & 0xFF00) >= QMAN_REV30) {
union qman_ecir2 ecir2_val;
ecir2_val.ecir2_raw = qm_in(ECIR2);
if (ecsr_val & PORTAL_ECSR_ERR) {
pr_warn("Qman ErrInt: %s id %d\n",
(ecir2_val.info.portal_type) ?
"DCP" : "SWP", ecir2_val.info.portal_num);
}
if (ecsr_val & (FQID_ECSR_ERR | QM_EIRQ_IECE)) {
pr_warn("Qman ErrInt: ecir.fqid 0x%x\n",
ecir_val.info.fqid);
}
if (ecsr_val & (QM_EIRQ_SBEI|QM_EIRQ_MBEI)) {
eadr_val.eadr_raw = qm_in(EADR);
pr_warn("Qman ErrInt: EADR Memory: %s, 0x%x\n",
error_mdata[eadr_val.info_rev3.memid].txt,
error_mdata[eadr_val.info_rev3.memid].addr_mask
& eadr_val.info_rev3.eadr);
log_edata_bits(
error_mdata[eadr_val.info_rev3.memid].bits);
}
} else {
if (ecsr_val & PORTAL_ECSR_ERR) {
pr_warn("Qman ErrInt: %s id %d\n",
(ecir_val.info.portal_type) ?
"DCP" : "SWP", ecir_val.info.portal_num);
}
if (ecsr_val & FQID_ECSR_ERR) {
pr_warn("Qman ErrInt: ecir.fqid 0x%x\n",
ecir_val.info.fqid);
}
if (ecsr_val & (QM_EIRQ_SBEI|QM_EIRQ_MBEI)) {
eadr_val.eadr_raw = qm_in(EADR);
pr_warn("Qman ErrInt: EADR Memory: %s, 0x%x\n",
error_mdata[eadr_val.info.memid].txt,
error_mdata[eadr_val.info.memid].addr_mask
& eadr_val.info.eadr);
log_edata_bits(error_mdata[eadr_val.info.memid].bits);
}
}
}
/* Qman interrupt handler */
static irqreturn_t qman_isr(int irq, void *ptr)
{
u32 isr_val, ier_val, ecsr_val, isr_mask, i;
ier_val = qm_err_isr_enable_read(qm);
isr_val = qm_err_isr_status_read(qm);
ecsr_val = qm_in(ECSR);
isr_mask = isr_val & ier_val;
if (!isr_mask)
return IRQ_NONE;
for (i = 0; i < QMAN_HWE_COUNT; i++) {
if (qman_hwerr_txts[i].mask & isr_mask) {
pr_warn("Qman ErrInt: %s\n", qman_hwerr_txts[i].txt);
if (qman_hwerr_txts[i].mask & ecsr_val) {
log_additional_error_info(isr_mask, ecsr_val);
/* Re-arm error capture registers */
qm_out(ECSR, ecsr_val);
}
if (qman_hwerr_txts[i].mask & QMAN_ERRS_TO_UNENABLE) {
pr_devel("Qman un-enabling error 0x%x\n",
qman_hwerr_txts[i].mask);
ier_val &= ~qman_hwerr_txts[i].mask;
qm_err_isr_enable_write(qm, ier_val);
}
}
}
qm_err_isr_status_clear(qm, isr_val);
return IRQ_HANDLED;
}
static int __bind_irq(void)
{
int ret, err_irq;
err_irq = of_irq_to_resource(qm_node, 0, NULL);
if (err_irq == NO_IRQ) {
pr_info("Can't get %s property '%s'\n", qm_node->full_name,
"interrupts");
return -ENODEV;
}
ret = request_irq(err_irq, qman_isr, IRQF_SHARED, "qman-err", qm_node);
if (ret) {
pr_err("request_irq() failed %d for '%s'\n", ret,
qm_node->full_name);
return -ENODEV;
}
/* Write-to-clear any stale bits, (eg. starvation being asserted prior
* to resource allocation during driver init). */
qm_err_isr_status_clear(qm, 0xffffffff);
/* Enable Error Interrupts */
qm_err_isr_enable_write(qm, 0xffffffff);
return 0;
}
int qman_init_ccsr(struct device_node *node)
{
int ret;
if (!qman_have_ccsr())
return 0;
if (node != qm_node)
return -EINVAL;
/* FQD memory */
qm_set_memory(qm, qm_memory_fqd, fqd_a, 1, 0, 0, fqd_sz);
/* PFDR memory */
qm_set_memory(qm, qm_memory_pfdr, pfdr_a, 1, 0, 0, pfdr_sz);
qm_init_pfdr(qm, 8, pfdr_sz / 64 - 8);
/* thresholds */
qm_set_pfdr_threshold(qm, 512, 64);
qm_set_sfdr_threshold(qm, 128);
/* clear stale PEBI bit from interrupt status register */
qm_err_isr_status_clear(qm, QM_EIRQ_PEBI);
/* corenet initiator settings */
qm_set_corenet_initiator(qm);
/* HID settings */
qm_set_hid(qm);
/* Set scheduling weights to defaults */
for (ret = qm_wq_first; ret <= qm_wq_last; ret++)
qm_set_wq_scheduling(qm, ret, 0, 0, 0, 0, 0, 0, 0);
/* We are not prepared to accept ERNs for hardware enqueues */
qm_set_dc(qm, qm_dc_portal_fman0, 1, 0);
qm_set_dc(qm, qm_dc_portal_fman1, 1, 0);
/* Initialise Error Interrupt Handler */
ret = __bind_irq();
if (ret)
return ret;
return 0;
}
#define LIO_CFG_LIODN_MASK 0x0fff0000
void qman_liodn_fixup(u16 channel)
{
static int done;
static u32 liodn_offset;
u32 before, after;
int idx = channel - QM_CHANNEL_SWPORTAL0;
if (!qman_have_ccsr())
return;
if ((qman_ip_rev & 0xFF00) >= QMAN_REV30)
before = qm_in(REV3_QCSP_LIO_CFG(idx));
else
before = qm_in(QCSP_LIO_CFG(idx));
if (!done) {
liodn_offset = before & LIO_CFG_LIODN_MASK;
done = 1;
return;
}
after = (before & (~LIO_CFG_LIODN_MASK)) | liodn_offset;
if ((qman_ip_rev & 0xFF00) >= QMAN_REV30)
qm_out(REV3_QCSP_LIO_CFG(idx), after);
else
qm_out(QCSP_LIO_CFG(idx), after);
}
#define IO_CFG_SDEST_MASK 0x00ff0000
int qman_set_sdest(u16 channel, unsigned int cpu_idx)
{
int idx = channel - QM_CHANNEL_SWPORTAL0;
u32 before, after;
if (!qman_have_ccsr())
return -ENODEV;
if ((qman_ip_rev & 0xFF00) >= QMAN_REV30) {
before = qm_in(REV3_QCSP_IO_CFG(idx));
/* Each pair of vcpu share the same SRQ(SDEST) */
cpu_idx /= 2;
after = (before & (~IO_CFG_SDEST_MASK)) | (cpu_idx << 16);
qm_out(REV3_QCSP_IO_CFG(idx), after);
} else {
before = qm_in(QCSP_IO_CFG(idx));
after = (before & (~IO_CFG_SDEST_MASK)) | (cpu_idx << 16);
qm_out(QCSP_IO_CFG(idx), after);
}
return 0;
}
#define MISC_CFG_WPM_MASK 0x00000002
int qm_set_wpm(int wpm)
{
u32 before;
u32 after;
if (!qman_have_ccsr())
return -ENODEV;
before = qm_in(MISC_CFG);
after = (before & (~MISC_CFG_WPM_MASK)) | (wpm << 1);
qm_out(MISC_CFG, after);
return 0;
}
int qm_get_wpm(int *wpm)
{
u32 before;
if (!qman_have_ccsr())
return -ENODEV;
before = qm_in(MISC_CFG);
*wpm = (before & MISC_CFG_WPM_MASK) >> 1;
return 0;
}
/* CEETM_CFG_PRES register has PRES field which is calculated by:
* PRES = (2^22 / credit update reference period) * QMan clock period
* = (2^22 * 10^9)/ CONFIG_QMAN_CEETM_UPDATE_PERIOD) / qman_clk
*/
int qman_ceetm_set_prescaler(enum qm_dc_portal portal)
{
u64 temp;
u16 pres;
if (!qman_have_ccsr())
return -ENODEV;
temp = 0x400000 * 100;
do_div(temp, CONFIG_QMAN_CEETM_UPDATE_PERIOD);
temp *= 10000000;
pres = (u16)(temp / qman_clk);
qm_out(CEETM_CFG_IDX, portal);
qm_out(CEETM_CFG_PRES, pres);
return 0;
}
int qman_ceetm_get_prescaler(u16 *pres)
{
if (!qman_have_ccsr())
return -ENODEV;
*pres = (u16)qm_in(CEETM_CFG_PRES);
return 0;
}
#define DCP_CFG_CEETME_MASK 0xFFFF0000
#define QM_SP_ENABLE_CEETM(n) (0x80000000 >> (n))
int qman_sp_enable_ceetm_mode(enum qm_dc_portal portal, u16 sub_portal)
{
u32 dcp_cfg;
if (!qman_have_ccsr())
return -ENODEV;
dcp_cfg = qm_in(DCP_CFG(portal));
dcp_cfg |= QM_SP_ENABLE_CEETM(sub_portal);
qm_out(DCP_CFG(portal), dcp_cfg);
return 0;
}
int qman_sp_disable_ceetm_mode(enum qm_dc_portal portal, u16 sub_portal)
{
u32 dcp_cfg;
if (!qman_have_ccsr())
return -ENODEV;
dcp_cfg = qm_in(DCP_CFG(portal));
dcp_cfg &= ~(QM_SP_ENABLE_CEETM(sub_portal));
qm_out(DCP_CFG(portal), dcp_cfg);
return 0;
}
int qman_ceetm_get_xsfdr(enum qm_dc_portal portal, unsigned int *num)
{
if (!qman_have_ccsr())
return -ENODEV;
*num = qm_in(CEETM_XSFDR_IN_USE);
return 0;
}
EXPORT_SYMBOL(qman_ceetm_get_xsfdr);
#ifdef CONFIG_SYSFS
#define DRV_NAME "fsl-qman"
#define DCP_MAX_ID 3
#define DCP_MIN_ID 0
static ssize_t show_pfdr_fpc(struct device *dev,
struct device_attribute *dev_attr, char *buf)
{
return snprintf(buf, PAGE_SIZE, "%u\n", qm_in(PFDR_FPC));
};
static ssize_t show_dlm_avg(struct device *dev,
struct device_attribute *dev_attr, char *buf)
{
u32 data;
int i;
if (!sscanf(dev_attr->attr.name, "dcp%d_dlm_avg", &i))
return -EINVAL;
if (i < DCP_MIN_ID || i > DCP_MAX_ID)
return -EINVAL;
data = qm_in(DCP_DLM_AVG(i));
return snprintf(buf, PAGE_SIZE, "%d.%08d\n", data>>8,
(data & 0x000000ff)*390625);
};
static ssize_t set_dlm_avg(struct device *dev,
struct device_attribute *dev_attr, const char *buf, size_t count)
{
unsigned long val;
int i;
if (!sscanf(dev_attr->attr.name, "dcp%d_dlm_avg", &i))
return -EINVAL;
if (i < DCP_MIN_ID || i > DCP_MAX_ID)
return -EINVAL;
if (kstrtoul(buf, 0, &val)) {
dev_dbg(dev, "invalid input %s\n", buf);
return -EINVAL;
}
qm_out(DCP_DLM_AVG(i), val);
return count;
};
static ssize_t show_pfdr_cfg(struct device *dev,
struct device_attribute *dev_attr, char *buf)
{
return snprintf(buf, PAGE_SIZE, "%u\n", qm_in(PFDR_CFG));
};
static ssize_t set_pfdr_cfg(struct device *dev,
struct device_attribute *dev_attr, const char *buf, size_t count)
{
unsigned long val;
if (kstrtoul(buf, 0, &val)) {
dev_dbg(dev, "invalid input %s\n", buf);
return -EINVAL;
}
qm_out(PFDR_CFG, val);
return count;
};
static ssize_t show_sfdr_in_use(struct device *dev,
struct device_attribute *dev_attr, char *buf)
{
return snprintf(buf, PAGE_SIZE, "%u\n", qm_in(SFDR_IN_USE));
};
static ssize_t show_idle_stat(struct device *dev,
struct device_attribute *dev_attr, char *buf)
{
return snprintf(buf, PAGE_SIZE, "%u\n", qm_in(IDLE_STAT));
};
static ssize_t show_ci_rlm_avg(struct device *dev,
struct device_attribute *dev_attr, char *buf)
{
u32 data = qm_in(CI_RLM_AVG);
return snprintf(buf, PAGE_SIZE, "%d.%08d\n", data>>8,
(data & 0x000000ff)*390625);
};
static ssize_t set_ci_rlm_avg(struct device *dev,
struct device_attribute *dev_attr, const char *buf, size_t count)
{
unsigned long val;
if (kstrtoul(buf, 0, &val)) {
dev_dbg(dev, "invalid input %s\n", buf);
return -EINVAL;
}
qm_out(CI_RLM_AVG, val);
return count;
};
static ssize_t show_err_isr(struct device *dev,
struct device_attribute *dev_attr, char *buf)
{
return snprintf(buf, PAGE_SIZE, "0x%08x\n", qm_in(ERR_ISR));
};
#define SBEC_MAX_ID 14
#define SBEC_MIN_ID 0
static ssize_t show_sbec(struct device *dev,
struct device_attribute *dev_attr, char *buf)
{
int i;
if (!sscanf(dev_attr->attr.name, "sbec_%d", &i))
return -EINVAL;
if (i < SBEC_MIN_ID || i > SBEC_MAX_ID)
return -EINVAL;
return snprintf(buf, PAGE_SIZE, "%u\n", qm_in(SBEC(i)));
};
static DEVICE_ATTR(pfdr_fpc, S_IRUSR, show_pfdr_fpc, NULL);
static DEVICE_ATTR(pfdr_cfg, S_IRUSR, show_pfdr_cfg, set_pfdr_cfg);
static DEVICE_ATTR(idle_stat, S_IRUSR, show_idle_stat, NULL);
static DEVICE_ATTR(ci_rlm_avg, (S_IRUSR|S_IWUSR),
show_ci_rlm_avg, set_ci_rlm_avg);
static DEVICE_ATTR(err_isr, S_IRUSR, show_err_isr, NULL);
static DEVICE_ATTR(sfdr_in_use, S_IRUSR, show_sfdr_in_use, NULL);
static DEVICE_ATTR(dcp0_dlm_avg, (S_IRUSR|S_IWUSR), show_dlm_avg, set_dlm_avg);
static DEVICE_ATTR(dcp1_dlm_avg, (S_IRUSR|S_IWUSR), show_dlm_avg, set_dlm_avg);
static DEVICE_ATTR(dcp2_dlm_avg, (S_IRUSR|S_IWUSR), show_dlm_avg, set_dlm_avg);
static DEVICE_ATTR(dcp3_dlm_avg, (S_IRUSR|S_IWUSR), show_dlm_avg, set_dlm_avg);
static DEVICE_ATTR(sbec_0, S_IRUSR, show_sbec, NULL);
static DEVICE_ATTR(sbec_1, S_IRUSR, show_sbec, NULL);
static DEVICE_ATTR(sbec_2, S_IRUSR, show_sbec, NULL);
static DEVICE_ATTR(sbec_3, S_IRUSR, show_sbec, NULL);
static DEVICE_ATTR(sbec_4, S_IRUSR, show_sbec, NULL);
static DEVICE_ATTR(sbec_5, S_IRUSR, show_sbec, NULL);
static DEVICE_ATTR(sbec_6, S_IRUSR, show_sbec, NULL);
static DEVICE_ATTR(sbec_7, S_IRUSR, show_sbec, NULL);
static DEVICE_ATTR(sbec_8, S_IRUSR, show_sbec, NULL);
static DEVICE_ATTR(sbec_9, S_IRUSR, show_sbec, NULL);
static DEVICE_ATTR(sbec_10, S_IRUSR, show_sbec, NULL);
static DEVICE_ATTR(sbec_11, S_IRUSR, show_sbec, NULL);
static DEVICE_ATTR(sbec_12, S_IRUSR, show_sbec, NULL);
static DEVICE_ATTR(sbec_13, S_IRUSR, show_sbec, NULL);
static DEVICE_ATTR(sbec_14, S_IRUSR, show_sbec, NULL);
static struct attribute *qman_dev_attributes[] = {
&dev_attr_pfdr_fpc.attr,
&dev_attr_pfdr_cfg.attr,
&dev_attr_idle_stat.attr,
&dev_attr_ci_rlm_avg.attr,
&dev_attr_err_isr.attr,
&dev_attr_dcp0_dlm_avg.attr,
&dev_attr_dcp1_dlm_avg.attr,
&dev_attr_dcp2_dlm_avg.attr,
&dev_attr_dcp3_dlm_avg.attr,
/* sfdr_in_use will be added if necessary */
NULL
};
static struct attribute *qman_dev_ecr_attributes[] = {
&dev_attr_sbec_0.attr,
&dev_attr_sbec_1.attr,
&dev_attr_sbec_2.attr,
&dev_attr_sbec_3.attr,
&dev_attr_sbec_4.attr,
&dev_attr_sbec_5.attr,
&dev_attr_sbec_6.attr,
&dev_attr_sbec_7.attr,
&dev_attr_sbec_8.attr,
&dev_attr_sbec_9.attr,
&dev_attr_sbec_10.attr,
&dev_attr_sbec_11.attr,
&dev_attr_sbec_12.attr,
&dev_attr_sbec_13.attr,
&dev_attr_sbec_14.attr,
NULL
};
/* root level */
static const struct attribute_group qman_dev_attr_grp = {
.name = NULL,
.attrs = qman_dev_attributes
};
static const struct attribute_group qman_dev_ecr_grp = {
.name = "error_capture",
.attrs = qman_dev_ecr_attributes
};
static int of_fsl_qman_remove(struct platform_device *ofdev)
{
sysfs_remove_group(&ofdev->dev.kobj, &qman_dev_attr_grp);
return 0;
};
static int of_fsl_qman_probe(struct platform_device *ofdev)
{
int ret;
ret = sysfs_create_group(&ofdev->dev.kobj, &qman_dev_attr_grp);
if (ret)
goto done;
ret = sysfs_add_file_to_group(&ofdev->dev.kobj,
&dev_attr_sfdr_in_use.attr, qman_dev_attr_grp.name);
if (ret)
goto del_group_0;
ret = sysfs_create_group(&ofdev->dev.kobj, &qman_dev_ecr_grp);
if (ret)
goto del_group_0;
goto done;
del_group_0:
sysfs_remove_group(&ofdev->dev.kobj, &qman_dev_attr_grp);
done:
if (ret)
dev_err(&ofdev->dev,
"Cannot create dev attributes ret=%d\n", ret);
return ret;
};
static struct of_device_id of_fsl_qman_ids[] = {
{
.compatible = "fsl,qman",
},
{}
};
MODULE_DEVICE_TABLE(of, of_fsl_qman_ids);
#ifdef CONFIG_PM
static u32 saved_isdr;
static int qman_pm_suspend_noirq(struct device *dev)
{
uint32_t idle_state;
suspend_unused_qportal();
/* save isdr, disable all, clear isr */
saved_isdr = qm_err_isr_disable_read(qm);
qm_err_isr_disable_write(qm, 0xffffffff);
qm_err_isr_status_clear(qm, 0xffffffff);
idle_state = qm_in(IDLE_STAT);
if (!(idle_state & 0x1)) {
pr_err("Qman not idle 0x%x aborting\n", idle_state);
qm_err_isr_disable_write(qm, saved_isdr);
resume_unused_qportal();
return -EBUSY;
}
#ifdef CONFIG_PM_DEBUG
pr_info("Qman suspend code, IDLE_STAT = 0x%x\n", idle_state);
#endif
return 0;
}
static int qman_pm_resume_noirq(struct device *dev)
{
/* restore isdr */
qm_err_isr_disable_write(qm, saved_isdr);
resume_unused_qportal();
return 0;
}
#else
#define qman_pm_suspend_noirq NULL
#define qman_pm_resume_noirq NULL
#endif
static const struct dev_pm_ops qman_pm_ops = {
.suspend_noirq = qman_pm_suspend_noirq,
.resume_noirq = qman_pm_resume_noirq,
};
static struct platform_driver of_fsl_qman_driver = {
.driver = {
.owner = THIS_MODULE,
.name = DRV_NAME,
.of_match_table = of_fsl_qman_ids,
.pm = &qman_pm_ops,
},
.probe = of_fsl_qman_probe,
.remove = of_fsl_qman_remove,
};
static int qman_ctrl_init(void)
{
return platform_driver_register(&of_fsl_qman_driver);
}
static void qman_ctrl_exit(void)
{
platform_driver_unregister(&of_fsl_qman_driver);
}
module_init(qman_ctrl_init);
module_exit(qman_ctrl_exit);
#endif /* CONFIG_SYSFS */
| jwhitham/ppc_linux | drivers/staging/fsl_qbman/qman_config.c | C | gpl-2.0 | 34,216 |
/* ownCloud Android Library is available under MIT license
* Copyright (C) 2014 ownCloud Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE 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.
*
*/
package com.cerema.cloud.lib.resources.shares;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
//import android.util.Log;
import android.util.Xml;
import com.cerema.cloud.lib.common.network.WebdavUtils;
import com.cerema.cloud.lib.resources.files.FileUtils;
/**
* Parser for Share API Response
* @author masensio
*
*/
public class ShareXMLParser {
//private static final String TAG = ShareXMLParser.class.getSimpleName();
// No namespaces
private static final String ns = null;
// NODES for XML Parser
private static final String NODE_OCS = "ocs";
private static final String NODE_META = "meta";
private static final String NODE_STATUS = "status";
private static final String NODE_STATUS_CODE = "statuscode";
//private static final String NODE_MESSAGE = "message";
private static final String NODE_DATA = "data";
private static final String NODE_ELEMENT = "element";
private static final String NODE_ID = "id";
private static final String NODE_ITEM_TYPE = "item_type";
private static final String NODE_ITEM_SOURCE = "item_source";
private static final String NODE_PARENT = "parent";
private static final String NODE_SHARE_TYPE = "share_type";
private static final String NODE_SHARE_WITH = "share_with";
private static final String NODE_FILE_SOURCE = "file_source";
private static final String NODE_PATH = "path";
private static final String NODE_PERMISSIONS = "permissions";
private static final String NODE_STIME = "stime";
private static final String NODE_EXPIRATION = "expiration";
private static final String NODE_TOKEN = "token";
private static final String NODE_STORAGE = "storage";
private static final String NODE_MAIL_SEND = "mail_send";
private static final String NODE_SHARE_WITH_DISPLAY_NAME = "share_with_display_name";
private static final String NODE_URL = "url";
private static final String TYPE_FOLDER = "folder";
private static final int SUCCESS = 100;
private static final int FAILURE = 403;
private static final int FILE_NOT_FOUND = 404;
private String mStatus;
private int mStatusCode;
// Getters and Setters
public String getStatus() {
return mStatus;
}
public void setStatus(String status) {
this.mStatus = status;
}
public int getStatusCode() {
return mStatusCode;
}
public void setStatusCode(int statusCode) {
this.mStatusCode = statusCode;
}
// Constructor
public ShareXMLParser() {
mStatusCode = 100;
}
public boolean isSuccess() {
return mStatusCode == SUCCESS;
}
public boolean isFailure() {
return mStatusCode == FAILURE;
}
public boolean isFileNotFound() {
return mStatusCode == FILE_NOT_FOUND;
}
/**
* Parse is as response of Share API
* @param is
* @return List of ShareRemoteFiles
* @throws XmlPullParserException
* @throws IOException
*/
public ArrayList<OCShare> parseXMLResponse(InputStream is) throws XmlPullParserException, IOException {
try {
// XMLPullParser
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser parser = Xml.newPullParser();
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
parser.setInput(is, null);
parser.nextTag();
return readOCS(parser);
} finally {
is.close();
}
}
/**
* Parse OCS node
* @param parser
* @return List of ShareRemoteFiles
* @throws XmlPullParserException
* @throws IOException
*/
private ArrayList<OCShare> readOCS (XmlPullParser parser) throws XmlPullParserException, IOException {
ArrayList<OCShare> shares = new ArrayList<OCShare>();
parser.require(XmlPullParser.START_TAG, ns , NODE_OCS);
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG) {
continue;
}
String name = parser.getName();
// read NODE_META and NODE_DATA
if (name.equalsIgnoreCase(NODE_META)) {
readMeta(parser);
} else if (name.equalsIgnoreCase(NODE_DATA)) {
shares = readData(parser);
} else {
skip(parser);
}
}
return shares;
}
/**
* Parse Meta node
* @param parser
* @throws XmlPullParserException
* @throws IOException
*/
private void readMeta(XmlPullParser parser) throws XmlPullParserException, IOException {
parser.require(XmlPullParser.START_TAG, ns, NODE_META);
//Log_OC.d(TAG, "---- NODE META ---");
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG) {
continue;
}
String name = parser.getName();
if (name.equalsIgnoreCase(NODE_STATUS)) {
setStatus(readNode(parser, NODE_STATUS));
} else if (name.equalsIgnoreCase(NODE_STATUS_CODE)) {
setStatusCode(Integer.parseInt(readNode(parser, NODE_STATUS_CODE)));
} else {
skip(parser);
}
}
}
/**
* Parse Data node
* @param parser
* @return
* @throws XmlPullParserException
* @throws IOException
*/
private ArrayList<OCShare> readData(XmlPullParser parser) throws XmlPullParserException, IOException {
ArrayList<OCShare> shares = new ArrayList<OCShare>();
OCShare share = null;
parser.require(XmlPullParser.START_TAG, ns, NODE_DATA);
//Log_OC.d(TAG, "---- NODE DATA ---");
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG) {
continue;
}
String name = parser.getName();
if (name.equalsIgnoreCase(NODE_ELEMENT)) {
readElement(parser, shares);
} else if (name.equalsIgnoreCase(NODE_ID)) {// Parse Create XML Response
share = new OCShare();
String value = readNode(parser, NODE_ID);
share.setIdRemoteShared(Integer.parseInt(value));
} else if (name.equalsIgnoreCase(NODE_URL)) {
share.setShareType(ShareType.PUBLIC_LINK);
String value = readNode(parser, NODE_URL);
share.setShareLink(value);
} else if (name.equalsIgnoreCase(NODE_TOKEN)) {
share.setToken(readNode(parser, NODE_TOKEN));
} else {
skip(parser);
}
}
if (share != null) {
// this is the response of a request for creation; don't pass to isValidShare()
shares.add(share);
}
return shares;
}
/**
* Parse Element node
* @param parser
* @return
* @throws XmlPullParserException
* @throws IOException
*/
private void readElement(XmlPullParser parser, ArrayList<OCShare> shares) throws XmlPullParserException, IOException {
parser.require(XmlPullParser.START_TAG, ns, NODE_ELEMENT);
OCShare share = new OCShare();
//Log_OC.d(TAG, "---- NODE ELEMENT ---");
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG) {
continue;
}
String name = parser.getName();
if (name.equalsIgnoreCase(NODE_ELEMENT)) {
// patch to work around servers responding with extra <element> surrounding all the shares on the same file before
// https://github.com/owncloud/core/issues/6992 was fixed
readElement(parser, shares);
} else if (name.equalsIgnoreCase(NODE_ID)) {
share.setIdRemoteShared(Integer.parseInt(readNode(parser, NODE_ID)));
} else if (name.equalsIgnoreCase(NODE_ITEM_TYPE)) {
share.setIsFolder(readNode(parser, NODE_ITEM_TYPE).equalsIgnoreCase(TYPE_FOLDER));
fixPathForFolder(share);
} else if (name.equalsIgnoreCase(NODE_ITEM_SOURCE)) {
share.setItemSource(Long.parseLong(readNode(parser, NODE_ITEM_SOURCE)));
} else if (name.equalsIgnoreCase(NODE_PARENT)) {
readNode(parser, NODE_PARENT);
} else if (name.equalsIgnoreCase(NODE_SHARE_TYPE)) {
int value = Integer.parseInt(readNode(parser, NODE_SHARE_TYPE));
share.setShareType(ShareType.fromValue(value));
} else if (name.equalsIgnoreCase(NODE_SHARE_WITH)) {
share.setShareWith(readNode(parser, NODE_SHARE_WITH));
} else if (name.equalsIgnoreCase(NODE_FILE_SOURCE)) {
share.setFileSource(Long.parseLong(readNode(parser, NODE_FILE_SOURCE)));
} else if (name.equalsIgnoreCase(NODE_PATH)) {
share.setPath(readNode(parser, NODE_PATH));
fixPathForFolder(share);
} else if (name.equalsIgnoreCase(NODE_PERMISSIONS)) {
share.setPermissions(Integer.parseInt(readNode(parser, NODE_PERMISSIONS)));
} else if (name.equalsIgnoreCase(NODE_STIME)) {
share.setSharedDate(Long.parseLong(readNode(parser, NODE_STIME)));
} else if (name.equalsIgnoreCase(NODE_EXPIRATION)) {
String value = readNode(parser, NODE_EXPIRATION);
if (!(value.length() == 0)) {
share.setExpirationDate(WebdavUtils.parseResponseDate(value).getTime());
}
} else if (name.equalsIgnoreCase(NODE_TOKEN)) {
share.setToken(readNode(parser, NODE_TOKEN));
} else if (name.equalsIgnoreCase(NODE_STORAGE)) {
readNode(parser, NODE_STORAGE);
} else if (name.equalsIgnoreCase(NODE_MAIL_SEND)) {
readNode(parser, NODE_MAIL_SEND);
} else if (name.equalsIgnoreCase(NODE_SHARE_WITH_DISPLAY_NAME)) {
share.setSharedWithDisplayName(readNode(parser, NODE_SHARE_WITH_DISPLAY_NAME));
} else {
skip(parser);
}
}
if (isValidShare(share)) {
shares.add(share);
}
}
private boolean isValidShare(OCShare share) {
return ((share.getIdRemoteShared() > -1) &&
(share.getShareType() == ShareType.PUBLIC_LINK) // at this moment we only care about public shares
);
}
private void fixPathForFolder(OCShare share) {
if (share.isFolder() && share.getPath() != null && share.getPath().length() > 0 && !share.getPath().endsWith(FileUtils.PATH_SEPARATOR)) {
share.setPath(share.getPath() + FileUtils.PATH_SEPARATOR);
}
}
/**
* Parse a node, to obtain its text. Needs readText method
* @param parser
* @param node
* @return Text of the node
* @throws XmlPullParserException
* @throws IOException
*/
private String readNode (XmlPullParser parser, String node) throws XmlPullParserException, IOException{
parser.require(XmlPullParser.START_TAG, ns, node);
String value = readText(parser);
//Log_OC.d(TAG, "node= " + node + ", value= " + value);
parser.require(XmlPullParser.END_TAG, ns, node);
return value;
}
/**
* Read the text from a node
* @param parser
* @return Text of the node
* @throws IOException
* @throws XmlPullParserException
*/
private String readText(XmlPullParser parser) throws IOException, XmlPullParserException {
String result = "";
if (parser.next() == XmlPullParser.TEXT) {
result = parser.getText();
parser.nextTag();
}
return result;
}
/**
* Skip tags in parser procedure
* @param parser
* @throws XmlPullParserException
* @throws IOException
*/
private void skip(XmlPullParser parser) throws XmlPullParserException, IOException {
if (parser.getEventType() != XmlPullParser.START_TAG) {
throw new IllegalStateException();
}
int depth = 1;
while (depth != 0) {
switch (parser.next()) {
case XmlPullParser.END_TAG:
depth--;
break;
case XmlPullParser.START_TAG:
depth++;
break;
}
}
}
}
| CEREMA/com.cerema.cloud | owncloud-android-library/src/com/cerema/cloud/lib/resources/shares/ShareXMLParser.java | Java | gpl-2.0 | 12,289 |
/*
* This file is part of the CMaNGOS Project. See AUTHORS file for Copyright information
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef MANGOS_DBCSTRUCTURE_H
#define MANGOS_DBCSTRUCTURE_H
#include "Server/DBCEnums.h"
#include "MotionGenerators/Path.h"
#include "Platform/Define.h"
#include "Globals/SharedDefines.h"
#include <map>
#include <set>
#include <vector>
// Structures using to access raw DBC data and required packing to portability
// GCC have alternative #pragma pack(N) syntax and old gcc version not support pack(push,N), also any gcc version not support it at some platform
#if defined( __GNUC__ )
#pragma pack(1)
#else
#pragma pack(push,1)
#endif
struct AreaTableEntry
{
uint32 ID; // 0 m_ID
uint32 mapid; // 1 m_ContinentID
uint32 zone; // 2 m_ParentAreaID
uint32 exploreFlag; // 3 m_AreaBit
uint32 flags; // 4 m_flags
// 5 m_SoundProviderPref
// 6 m_SoundProviderPrefUnderwater
// 7 m_AmbienceID
// 8 m_ZoneMusic
// 9 m_IntroSound
int32 area_level; // 10 m_ExplorationLevel
char* area_name[16]; // 11-26 m_AreaName_lang
// 27 string flags
uint32 team; // 28 m_factionGroupMask
uint32 LiquidTypeOverride; // 29 m_liquidTypeID override for water type
// 30-32 uknown/unused
// 33 m_minElevation
// 34 m_ambient_multiplier
};
struct AreaTriggerEntry
{
uint32 id; // 0
uint32 mapid; // 1
float x; // 2
float y; // 3
float z; // 4
float radius; // 5
float box_x; // 6 extent x edge
float box_y; // 7 extent y edge
float box_z; // 8 extent z edge
float box_orientation; // 9 extent rotation by about z axis
};
struct AuctionHouseEntry
{
uint32 houseId; // 0 m_ID
uint32 faction; // 1 m_factionID
uint32 depositPercent; // 2 m_depositRate
uint32 cutPercent; // 3 m_consignmentRate
// char* name[16]; // 4-19 m_name_lang
// 20 string flags
};
struct BankBagSlotPricesEntry
{
uint32 ID; // 0 m_ID
uint32 price; // 1 m_Cost
};
struct BattlemasterListEntry
{
uint32 id; // 0 m_ID
int32 mapid[8]; // 1-8 m_mapID[8]
uint32 type; // 9 m_instanceType
uint32 minLevel; // 10 m_minlevel
uint32 maxLevel; // 11 m_maxlevel
uint32 maxplayersperteam; // 12
// 13-14 unused
char* name[16]; // 15-30 m_name_lang
// 31 string flags
// 32 unused
};
/*struct Cfg_CategoriesEntry
{
uint32 Index; // m_ID categoryId (sent in RealmList packet)
uint32 Unk1; // m_localeMask
uint32 Unk2; // m_charsetMask
uint32 IsTournamentRealm; // m_flags
char *categoryName[16]; // m_name_lang
uint32 categoryNameFlags;
}*/
/*struct Cfg_ConfigsEntry
{
uint32 Id; // m_ID
uint32 Type; // m_realmType (sent in RealmList packet)
uint32 IsPvp; // m_playerKillingAllowed
uint32 IsRp; // m_roleplaying
};*/
#define MAX_OUTFIT_ITEMS 12
// #define MAX_OUTFIT_ITEMS 24 // 12->24 in 3.0.x
struct CharStartOutfitEntry
{
// uint32 Id; // 0 m_ID
uint32 RaceClassGender; // 1 m_raceID m_classID m_sexID m_outfitID (UNIT_FIELD_BYTES_0 & 0x00FFFFFF) comparable (0 byte = race, 1 byte = class, 2 byte = gender)
int32 ItemId[MAX_OUTFIT_ITEMS]; // 2-13 m_ItemID
// int32 ItemDisplayId[MAX_OUTFIT_ITEMS]; // 14-25 m_DisplayItemID not required at server side
// int32 ItemInventorySlot[MAX_OUTFIT_ITEMS]; // 26-37 m_InventoryType not required at server side
// uint32 Unknown1; // 38, unique values (index-like with gaps ordered in other way as ids)
// uint32 Unknown2; // 39
// uint32 Unknown3; // 40
};
struct CharTitlesEntry
{
uint32 ID; // 0, m_ID
// uint32 unk1; // 1 m_Condition_ID
char* name[16]; // 2-17 m_name_lang
// 18 string flags
// char* name2[16]; // 19-34 m_name1_lang
// 35 string flags
uint32 bit_index; // 36 m_mask_ID used in PLAYER_CHOSEN_TITLE and 1<<index in PLAYER__FIELD_KNOWN_TITLES
};
struct ChatChannelsEntry
{
uint32 ChannelID; // 0 m_ID
uint32 flags; // 1 m_flags
// 2 m_factionGroup
char* pattern[16]; // 3-18 m_name_lang
// 19 string flags
// char* name[16]; // 20-35 m_shortcut_lang
// 36 string flags
};
struct ChrClassesEntry
{
uint32 ClassID; // 0 m_ID
// uint32 flags; // 1 unknown
uint32 powerType; // 2 m_DisplayPower
// 3 m_petNameToken
char const* name[16]; // 4-19 m_name_lang
// 20 string flags
// char* nameFemale[16]; // 21-36 m_name_female_lang
// 37 string flags
// char* nameNeutralGender[16]; // 38-53 m_name_male_lang
// 54 string flags
// 55 m_filename
uint32 spellfamily; // 56 m_spellClassSet
// uint32 flags2; // 57 m_flags (0x08 HasRelicSlot)
};
struct ChrRacesEntry
{
uint32 RaceID; // 0 m_ID
// 1 m_flags
uint32 FactionID; // 2 m_factionID
// 3 m_ExplorationSoundID
uint32 model_m; // 4 m_MaleDisplayId
uint32 model_f; // 5 m_FemaleDisplayId
// 6 m_ClientPrefix
// 7 unused
uint32 TeamID; // 8 m_BaseLanguage (7-Alliance 1-Horde)
// 9 m_creatureType
// 10 m_ResSicknessSpellID
// 11 m_SplashSoundID
// 12 m_clientFileString
uint32 CinematicSequence; // 13 m_cinematicSequenceID
char* name[16]; // 14-29 m_name_lang used for DBC language detection/selection
// 30 string flags
// char* nameFemale[16]; // 31-46 m_name_female_lang
// 47 string flags
// char* nameNeutralGender[16]; // 48-63 m_name_male_lang
// 64 string flags
// 65-66 m_facialHairCustomization[2]
// 67 m_hairCustomization
uint32 expansion; // 68 m_required_expansion
};
/*struct CinematicCameraEntry
{
uint32 id; // 0 m_ID
char* filename; // 1 m_model
uint32 soundid; // 2 m_soundID
float start_x; // 3 m_originX
float start_y; // 4 m_originY
float start_z; // 5 m_originZ
float unk6; // 6 m_originFacing
};*/
struct CinematicSequencesEntry
{
uint32 Id; // 0 m_ID
// uint32 unk1; // 1 m_soundID
// uint32 cinematicCamera; // 2 m_camera[8]
};
struct CreatureDisplayInfoEntry
{
uint32 Displayid; // 0 m_ID
// 1 m_modelID
// 2 m_soundID
uint32 ExtendedDisplayInfoID; // 3 m_extendedDisplayInfoID -> CreatureDisplayInfoExtraEntry::DisplayExtraId
float scale; // 4 m_creatureModelScale
// 5 m_creatureModelAlpha
// 6-8 m_textureVariation[3]
// 9 m_portraitTextureName
// 10 m_sizeClass
// 11 m_bloodID
// 12 m_NPCSoundID
// 13 m_particleColorID
};
struct CreatureDisplayInfoExtraEntry
{
uint32 DisplayExtraId; // 0 m_ID CreatureDisplayInfoEntry::m_extendedDisplayInfoID
uint32 Race; // 1 m_DisplayRaceID
// uint32 Gender; // 2 m_DisplaySexID
// uint32 SkinColor; // 3 m_SkinID
// uint32 FaceType; // 4 m_FaceID
// uint32 HairType; // 5 m_HairStyleID
// uint32 HairStyle; // 6 m_HairColorID
// uint32 BeardStyle; // 7 m_FacialHairID
// uint32 Equipment[11]; // 8-18 m_NPCItemDisplay equipped static items EQUIPMENT_SLOT_HEAD..EQUIPMENT_SLOT_HANDS, client show its by self
// uint32 CanEquip; // 19 m_flags 0..1 Can equip additional things when used for players
// char* // 20 m_BakeName CreatureDisplayExtra-*.blp
};
struct CreatureFamilyEntry
{
uint32 ID; // 0
float minScale; // 1
uint32 minScaleLevel; // 2 0/1
float maxScale; // 3
uint32 maxScaleLevel; // 4 0/60
uint32 skillLine[2]; // 5-6
uint32 petFoodMask; // 7
char* Name[16]; // 8-23
// 24 string flags, unused
// 25 icon, unused
};
#define MAX_CREATURE_SPELL_DATA_SLOT 4
struct CreatureSpellDataEntry
{
uint32 ID; // 0 m_ID
uint32 spellId[MAX_CREATURE_SPELL_DATA_SLOT]; // 1-4 m_spells[4]
// uint32 availability[MAX_CREATURE_SPELL_DATA_SLOT];// 4-7 m_availability[4]
};
struct CreatureTypeEntry
{
uint32 ID; // 0 m_ID
// char* Name[16]; // 1-16 m_name_lang
// 17 string flags
// uint32 no_expirience; // 18 m_flags
};
struct DungeonEncounterEntry
{
uint32 Id; // 0 m_ID
uint32 mapId; // 1 m_mapID
uint32 Difficulty; // 2 m_difficulty
uint32 encounterData; // 3 m_orderIndex
uint32 encounterIndex; // 4 m_Bit
char* encounterName[16]; // 5-20 m_name_lang
uint32 nameLangFlags; // 21 m_name_lang_flags
uint32 spellIconID; // 22 m_spellIconID
};
struct DurabilityCostsEntry
{
uint32 Itemlvl; // 0 m_ID
uint32 multiplier[29]; // 1-29 m_weaponSubClassCost m_armorSubClassCost
};
struct DurabilityQualityEntry
{
uint32 Id; // 0 m_ID
float quality_mod; // 1 m_data
};
struct EmotesEntry
{
uint32 Id; // 0 m_ID
// char* Name; // 1 m_EmoteSlashCommand
// uint32 AnimationId; // 2 m_AnimID
uint32 Flags; // 3 m_EmoteFlags
uint32 EmoteType; // 4 m_EmoteSpecProc (determine how emote are shown)
uint32 UnitStandState; // 5 m_EmoteSpecProcParam
// uint32 SoundId; // 6 m_EventSoundID
};
struct EmotesTextEntry
{
uint32 Id; // m_ID
// m_name
uint32 textid; // m_emoteID
// m_emoteText
};
struct FactionEntry
{
uint32 ID; // 0 m_ID
int32 reputationListID; // 1 m_reputationIndex
uint32 BaseRepRaceMask[4]; // 2-5 m_reputationRaceMask
uint32 BaseRepClassMask[4]; // 6-9 m_reputationClassMask
int32 BaseRepValue[4]; // 10-13 m_reputationBase
uint32 ReputationFlags[4]; // 14-17 m_reputationFlags
uint32 team; // 18 m_parentFactionID
char* name[16]; // 19-34 m_name_lang
// 35 string flags
// char* description[16]; // 36-51 m_description_lang
// 52 string flags
// helpers
int GetIndexFitTo(uint32 raceMask, uint32 classMask) const
{
for (int i = 0; i < 4; ++i)
{
if ((BaseRepRaceMask[i] == 0 || (BaseRepRaceMask[i] & raceMask)) &&
(BaseRepClassMask[i] == 0 || (BaseRepClassMask[i] & classMask)))
return i;
}
return -1;
}
bool HasReputation() const { return reputationListID >= 0; }
};
/*
// NOTE: FactionGroup.dbc - currently unused, please refer to related hardcoded enum FactionGroupMask
struct FactionGroupEntry
{
uint32 ID; // 0 m_ID
uint32 maskID; // 1 m_maskID index of the bit to check for in the faction group mask
char* internalName; // 2 m_internalName
// char* name[16]; // 3-18 m_name_lang localized display name in the UI
// 19 string flags
};
*/
struct FactionTemplateEntry
{
uint32 ID; // 0
uint32 faction; // 1
uint32 factionFlags; // 2 specific flags for that faction
uint32 factionGroupMask; // 3 if mask set (see FactionGroupMask) then faction included in masked group
uint32 friendGroupMask; // 4 if mask set (see FactionGroupMask) then faction friendly to masked group
uint32 enemyGroupMask; // 5 if mask set (see FactionGroupMask) then faction hostile to masked group
uint32 enemyFaction[4]; // 6-9
uint32 friendFaction[4]; // 10-13
//------------------------------------------------------- end structure
// helpers
bool IsFriendlyTo(FactionTemplateEntry const& entry) const
{
if (entry.faction)
{
for (int i = 0; i < 4; ++i)
if (enemyFaction[i] == entry.faction)
return false;
for (int i = 0; i < 4; ++i)
if (friendFaction[i] == entry.faction)
return true;
}
return (friendGroupMask & entry.factionGroupMask) || (factionGroupMask & entry.friendGroupMask);
}
bool IsHostileTo(FactionTemplateEntry const& entry) const
{
if (entry.faction)
{
for (int i = 0; i < 4; ++i)
if (enemyFaction[i] == entry.faction)
return true;
for (int i = 0; i < 4; ++i)
if (friendFaction[i] == entry.faction)
return false;
}
return (enemyGroupMask & entry.factionGroupMask) != 0;
}
bool IsHostileToPlayers() const { return (enemyGroupMask & FACTION_GROUP_MASK_PLAYER) != 0; }
bool IsNeutralToAll() const
{
for (int i = 0; i < 4; ++i)
if (enemyFaction[i] != 0)
return false;
return enemyGroupMask == 0 && friendGroupMask == 0;
}
bool IsContestedGuardFaction() const { return (factionFlags & FACTION_TEMPLATE_FLAG_CONTESTED_GUARD) != 0; }
};
struct GameObjectDisplayInfoEntry
{
uint32 Displayid; // 0 m_ID
char* filename; // 1 m_modelName
// uint32 unknown2[10]; // 2-11 m_Sound
float geoBoxMinX; // 12 m_geoBoxMinX (use first value as interact dist, mostly in hacks way)
float geoBoxMinY; // 13 m_geoBoxMinY
float geoBoxMinZ; // 14 m_geoBoxMinZ
float geoBoxMaxX; // 15 m_geoBoxMaxX
float geoBoxMaxY; // 16 m_geoBoxMaxY
float geoBoxMaxZ; // 17 m_geoBoxMaxZ
};
struct GemPropertiesEntry
{
uint32 ID; // m_id
uint32 spellitemenchantement; // m_enchant_id
// m_maxcount_inv
// m_maxcount_item
uint32 color; // m_type
};
// All Gt* DBC store data for 100 levels, some by 100 per class/race
#define GT_MAX_LEVEL 100
struct GtCombatRatingsEntry
{
float ratio;
};
struct GtChanceToMeleeCritBaseEntry
{
float base;
};
struct GtChanceToMeleeCritEntry
{
float ratio;
};
struct GtChanceToSpellCritBaseEntry
{
float base;
};
struct GtChanceToSpellCritEntry
{
float ratio;
};
struct GtOCTRegenHPEntry
{
float ratio;
};
struct GtNPCManaCostScalerEntry
{
float ratio;
};
// struct GtOCTRegenMPEntry
//{
// float ratio;
//};
struct GtRegenHPPerSptEntry
{
float ratio;
};
struct GtRegenMPPerSptEntry
{
float ratio;
};
struct ItemEntry
{
uint32 ID; // 0 m_ID
uint32 DisplayId; // 1 m_displayInfoID
uint32 InventoryType; // 2 m_inventoryType
uint32 Sheath; // 3 m_sheatheType
};
struct ItemBagFamilyEntry
{
uint32 ID; // 0 m_ID
// char* name[16] // 1-16 m_name_lang
// // 17 name flags
};
struct ItemClassEntry
{
uint32 ID; // 0 m_ID
// uint32 unk1; // 1
// uint32 unk2; // 2 only weapon have 1 in field, other 0
char* name[16]; // 3-19 m_name_lang
// // 20 name flags
};
struct ItemDisplayInfoEntry
{
uint32 ID;
uint32 randomPropertyChance;
};
// struct ItemCondExtCostsEntry
//{
// uint32 ID;
// uint32 condExtendedCost; // ItemPrototype::CondExtendedCost
// uint32 itemextendedcostentry; // ItemPrototype::ExtendedCost
// uint32 arenaseason; // arena season number(1-4)
//};
#define MAX_EXTENDED_COST_ITEMS 5
struct ItemExtendedCostEntry
{
uint32 ID; // 0 m_ID
uint32 reqhonorpoints; // 1 m_honorPoints
uint32 reqarenapoints; // 2 m_arenaPoints
uint32 reqitem[MAX_EXTENDED_COST_ITEMS]; // 3-7 m_itemID
uint32 reqitemcount[MAX_EXTENDED_COST_ITEMS]; // 8-12 m_itemCount
uint32 reqpersonalarenarating; // 13 m_requiredArenaRating
};
struct ItemRandomPropertiesEntry
{
uint32 ID; // 0 m_ID
// char* internalName // 1 m_Name
uint32 enchant_id[3]; // 2-4 m_Enchantment
// 5-6 unused, 0 only values, reserved for additional enchantments
char* nameSuffix[16]; // 7-22 m_name_lang
// 23 string flags
};
struct ItemRandomSuffixEntry
{
uint32 ID; // 0 m_ID
char* nameSuffix[16]; // 1-16 m_name_lang
// 17 string flags
// 18 m_internalName
uint32 enchant_id[3]; // 19-21 m_enchantment
uint32 prefix[3]; // 22-24 m_allocationPct
};
struct ItemSetEntry
{
// uint32 id // 0 m_ID
char* name[16]; // 1-16 m_name_lang
// 17 string flags
// uint32 itemId[17]; // 18-34 m_itemID
uint32 spells[8]; // 35-42 m_setSpellID
uint32 items_to_triggerspell[8]; // 43-50 m_setThreshold
uint32 required_skill_id; // 51 m_requiredSkill
uint32 required_skill_value; // 52 m_requiredSkillRank
};
struct LiquidTypeEntry
{
uint32 Id; // 0
uint32 LiquidId; // 1 1: Coilfang Raid - Water; 23: Water; 29: Ocean; 35: Magma; 41: Slime; 47: Naxxramas - Slime; 65: Hyjal Past - Water.
uint32 Type; // 2 0: Magma; 2: Slime; 3: Water.
uint32 SpellId; // 3 Reference to Spell.dbc
};
#define MAX_LOCK_CASE 8
struct LockEntry
{
uint32 ID; // 0 m_ID
uint32 Type[MAX_LOCK_CASE]; // 1-5 m_Type
uint32 Index[MAX_LOCK_CASE]; // 9-16 m_Index
uint32 Skill[MAX_LOCK_CASE]; // 17-24 m_Skill
// uint32 Action[MAX_LOCK_CASE]; // 25-32 m_Action
};
struct MailTemplateEntry
{
uint32 ID; // 0 m_ID
// char* subject[16]; // 1-16 m_subject_lang
// 17 string flags
char* content[16]; // 18-33 m_body_lang
};
struct MapEntry
{
uint32 MapID; // 0 m_ID
// char* internalname; // 1 m_Directory
uint32 map_type; // 2 m_InstanceType
// uint32 isPvP; // 3 m_PVP 0 or 1 for battlegrounds (not arenas)
char* name[16]; // 4-19 m_MapName_lang
// 20 string flags
// 21-23 unused (something PvPZone related - levels?)
// 24-26
uint32 linked_zone; // 27 m_areaTableID
// char* hordeIntro[16]; // 28-43 m_MapDescription0_lang
// 44 string flags
// char* allianceIntro[16]; // 45-60 m_MapDescription1_lang
// 61 string flags
uint32 multimap_id; // 62 m_LoadingScreenID (LoadingScreens.dbc)
// 63-64 not used
// float BattlefieldMapIconScale; // 65 m_minimapIconScale
// chat* unknownText1 // 66-81 unknown empty text fields, possible normal Intro text.
// 82 text flags
// chat* heroicIntroText // 83-98 heroic mode requirement text
// 99 text flags
// chat* unknownText2 // 100-115 unknown empty text fields
// 116 text flags
int32 ghost_entrance_map; // 117 m_corpseMapID map_id of entrance map in ghost mode (continent always and in most cases = normal entrance)
float ghost_entrance_x; // 118 m_corpseX entrance x coordinate in ghost mode (in most cases = normal entrance)
float ghost_entrance_y; // 119 m_corpseY entrance y coordinate in ghost mode (in most cases = normal entrance)
uint32 resetTimeRaid; // 120
uint32 resetTimeHeroic; // 121
// 122 all 0
// uint32 timeOfDayOverride; // 123 m_timeOfDayOverride
uint32 addon; // 124 m_expansionID
// Helpers
uint32 Expansion() const { return addon; }
bool IsDungeon() const { return map_type == MAP_INSTANCE || map_type == MAP_RAID; }
bool IsNonRaidDungeon() const { return map_type == MAP_INSTANCE; }
bool Instanceable() const { return map_type == MAP_INSTANCE || map_type == MAP_RAID || map_type == MAP_BATTLEGROUND || map_type == MAP_ARENA; }
bool IsRaid() const { return map_type == MAP_RAID; }
bool IsBattleGround() const { return map_type == MAP_BATTLEGROUND; }
bool IsBattleArena() const { return map_type == MAP_ARENA; }
bool IsBattleGroundOrArena() const { return map_type == MAP_BATTLEGROUND || map_type == MAP_ARENA; }
bool SupportsHeroicMode() const { return resetTimeHeroic && !resetTimeRaid; }
bool HasResetTime() const { return resetTimeHeroic || resetTimeRaid; }
bool IsContinent() const
{
return MapID == 0 || MapID == 1 || MapID == 530;
}
};
struct QuestSortEntry
{
uint32 id; // 0 m_ID
// char* name[16]; // 1-16 m_SortName_lang
// 17 string flags
};
struct RandomPropertiesPointsEntry
{
// uint32 Id; // 0 m_ID
uint32 itemLevel; // 1 m_ItemLevel
uint32 EpicPropertiesPoints[5]; // 2-6 m_Epic
uint32 RarePropertiesPoints[5]; // 7-11 m_Superior
uint32 UncommonPropertiesPoints[5]; // 12-16 m_Good
};
/*struct SkillLineCategoryEntry
{
uint32 id; // 0 m_ID
char* name[16]; // 1-17 m_name_lang
// 18 string flags
uint32 displayOrder; // 19 m_sortIndex
};*/
struct SkillRaceClassInfoEntry
{
// uint32 id; // 0 m_ID
uint32 skillId; // 1 m_skillID
uint32 raceMask; // 2 m_raceMask
uint32 classMask; // 3 m_classMask
uint32 flags; // 4 m_flags
uint32 reqLevel; // 5 m_minLevel
// uint32 skillTierId; // 6 m_skillTierID
// uint32 skillCostID; // 7 m_skillCostIndex
};
/*struct SkillTiersEntry{
uint32 id; // 0 m_ID
uint32 skillValue[16]; // 1-17 m_cost
uint32 maxSkillValue[16]; // 18-3 m_valueMax
};*/
struct SkillLineEntry
{
uint32 id; // 0 m_ID
int32 categoryId; // 1 m_categoryID
// uint32 skillCostID; // 2 m_skillCostsID
char* name[16]; // 3-18 m_displayName_lang
// 19 string flags
// char* description[16]; // 20-35 m_description_lang
// 36 string flags
uint32 spellIcon; // 37 m_spellIconID
};
struct SkillLineAbilityEntry
{
uint32 id; // 0, INDEX
uint32 skillId; // 1
uint32 spellId; // 2
uint32 racemask; // 3
uint32 classmask; // 4
// uint32 racemaskNot; // 5 always 0 in 2.4.2
// uint32 classmaskNot; // 6 always 0 in 2.4.2
uint32 req_skill_value; // 7 for trade skill.not for training.
uint32 forward_spellid; // 8
uint32 learnOnGetSkill; // 9 can be 1 or 2 for spells learned on get skill
uint32 max_value; // 10
uint32 min_value; // 11
// 12-13, unknown, always 0
uint32 reqtrainpoints; // 14
};
struct SoundEntriesEntry
{
uint32 Id; // 0 m_ID
// uint32 Type; // 1 m_soundType
// char* InternalName; // 2 m_name
// char* FileName[10]; // 3-12 m_File[10]
// uint32 Unk13[10]; // 13-22 m_Freq[10]
// char* Path; // 23 m_DirectoryBase
// 24 m_volumeFloat
// 25 m_flags
// 26 m_minDistance
// 27 m_distanceCutoff
// 28 m_EAXDef
};
struct ClassFamilyMask
{
uint64 Flags;
ClassFamilyMask() : Flags(0) {}
explicit ClassFamilyMask(uint64 familyFlags) : Flags(familyFlags) {}
bool Empty() const { return Flags == 0; }
bool operator!() const { return Empty(); }
operator void const* () const { return Empty() ? nullptr : this; } // for allow normal use in if(mask)
bool operator== (const ClassFamilyMask &another) const { return (Flags == another.Flags); }
bool IsFitToFamilyMask(uint64 familyFlags) const { return !!(Flags & familyFlags); }
bool IsFitToFamilyMask(ClassFamilyMask const& mask) const { return !!(Flags & mask.Flags); }
// possible will removed at finish convertion code use IsFitToFamilyMask
uint64 operator& (uint64 mask) const { return !!(Flags & mask); }
ClassFamilyMask& operator|= (ClassFamilyMask const& mask)
{
Flags |= mask.Flags;
return *this;
}
};
#define MAX_SPELL_REAGENTS 8
#define MAX_SPELL_TOTEMS 2
#define MAX_SPELL_TOTEM_CATEGORIES 2
struct SpellEntry
{
uint32 Id; // 0 m_ID
uint32 Category; // 1 m_category
// uint32 castUI // 2 not used
uint32 Dispel; // 3 m_dispelType
uint32 Mechanic; // 4 m_mechanic
uint32 Attributes; // 5 m_attributes
uint32 AttributesEx; // 6 m_attributesEx
uint32 AttributesEx2; // 7 m_attributesExB
uint32 AttributesEx3; // 8 m_attributesExC
uint32 AttributesEx4; // 9 m_attributesExD
uint32 AttributesEx5; // 10 m_attributesExE
uint32 AttributesEx6; // 11 m_attributesExF
uint32 Stances; // 12 m_shapeshiftMask
uint32 StancesNot; // 13 m_shapeshiftExclude
uint32 Targets; // 14 m_targets
uint32 TargetCreatureType; // 15 m_targetCreatureType
uint32 RequiresSpellFocus; // 16 m_requiresSpellFocus
uint32 FacingCasterFlags; // 17 m_facingCasterFlags
uint32 CasterAuraState; // 18 m_casterAuraState
uint32 TargetAuraState; // 19 m_targetAuraState
uint32 CasterAuraStateNot; // 20 m_excludeCasterAuraState
uint32 TargetAuraStateNot; // 21 m_excludeTargetAuraState
uint32 CastingTimeIndex; // 22 m_castingTimeIndex
uint32 RecoveryTime; // 23 m_recoveryTime
uint32 CategoryRecoveryTime; // 24 m_categoryRecoveryTime
uint32 InterruptFlags; // 25 m_interruptFlags
uint32 AuraInterruptFlags; // 26 m_auraInterruptFlags
uint32 ChannelInterruptFlags; // 27 m_channelInterruptFlags
uint32 procFlags; // 28 m_procTypeMask
uint32 procChance; // 29 m_procChance
uint32 procCharges; // 30 m_procCharges
uint32 maxLevel; // 31 m_maxLevel
uint32 baseLevel; // 32 m_baseLevel
uint32 spellLevel; // 33 m_spellLevel
uint32 DurationIndex; // 34 m_durationIndex
uint32 powerType; // 35 m_powerType
uint32 manaCost; // 36 m_manaCost
uint32 manaCostPerlevel; // 37 m_manaCostPerLevel
uint32 manaPerSecond; // 38 m_manaPerSecond
uint32 manaPerSecondPerLevel; // 39 m_manaPerSecondPerLevel
uint32 rangeIndex; // 40 m_rangeIndex
float speed; // 41 m_speed
// uint32 modalNextSpell; // 42 m_modalNextSpell not used
uint32 StackAmount; // 43 m_cumulativeAura
uint32 Totem[MAX_SPELL_TOTEMS]; // 44-45 m_totem
int32 Reagent[MAX_SPELL_REAGENTS]; // 46-53 m_reagent
uint32 ReagentCount[MAX_SPELL_REAGENTS]; // 54-61 m_reagentCount
int32 EquippedItemClass; // 62 m_equippedItemClass (value)
int32 EquippedItemSubClassMask; // 63 m_equippedItemSubclass (mask)
int32 EquippedItemInventoryTypeMask; // 64 m_equippedItemInvTypes (mask)
uint32 Effect[MAX_EFFECT_INDEX]; // 65-67 m_effect
int32 EffectDieSides[MAX_EFFECT_INDEX]; // 68-70 m_effectDieSides
uint32 EffectBaseDice[MAX_EFFECT_INDEX]; // 71-73
float EffectDicePerLevel[MAX_EFFECT_INDEX]; // 74-76
float EffectRealPointsPerLevel[MAX_EFFECT_INDEX]; // 77-79 m_effectRealPointsPerLevel
int32 EffectBasePoints[MAX_EFFECT_INDEX]; // 80-82 m_effectBasePoints (don't must be used in spell/auras explicitly, must be used cached Spell::m_currentBasePoints)
uint32 EffectMechanic[MAX_EFFECT_INDEX]; // 83-85 m_effectMechanic
uint32 EffectImplicitTargetA[MAX_EFFECT_INDEX]; // 86-88 m_implicitTargetA
uint32 EffectImplicitTargetB[MAX_EFFECT_INDEX]; // 89-91 m_implicitTargetB
uint32 EffectRadiusIndex[MAX_EFFECT_INDEX]; // 92-94 m_effectRadiusIndex - spellradius.dbc
uint32 EffectApplyAuraName[MAX_EFFECT_INDEX]; // 95-97 m_effectAura
uint32 EffectAmplitude[MAX_EFFECT_INDEX]; // 98-100 m_effectAuraPeriod
float EffectMultipleValue[MAX_EFFECT_INDEX]; // 101-103 m_effectAmplitude
uint32 EffectChainTarget[MAX_EFFECT_INDEX]; // 104-106 m_effectChainTargets
uint32 EffectItemType[MAX_EFFECT_INDEX]; // 107-109 m_effectItemType
int32 EffectMiscValue[MAX_EFFECT_INDEX]; // 110-112 m_effectMiscValue
int32 EffectMiscValueB[MAX_EFFECT_INDEX]; // 113-115 m_effectMiscValueB
uint32 EffectTriggerSpell[MAX_EFFECT_INDEX]; // 116-118 m_effectTriggerSpell
float EffectPointsPerComboPoint[MAX_EFFECT_INDEX]; // 119-121 m_effectPointsPerCombo
uint32 SpellVisual; // 122 m_spellVisualID
// uint32 SpellVisual2; // 123 not used
uint32 SpellIconID; // 124 m_spellIconID
uint32 activeIconID; // 125 m_activeIconID
uint32 spellPriority; // 126 m_spellPriority not used
char* SpellName[16]; // 127-142 m_name_lang
// uint32 SpellNameFlag; // 143 m_name_flag not used
char* Rank[16]; // 144-159 m_nameSubtext_lang
// uint32 RankFlags; // 160 m_nameSubtext_flag not used
// char* Description[16]; // 161-176 m_description_lang not used
// uint32 DescriptionFlags; // 177 m_description_flag not used
// char* ToolTip[16]; // 178-193 m_auraDescription_lang not used
// uint32 ToolTipFlags; // 194 m_auraDescription_flag not used
uint32 ManaCostPercentage; // 195 m_manaCostPct
uint32 StartRecoveryCategory; // 196 m_startRecoveryCategory
uint32 StartRecoveryTime; // 197 m_startRecoveryTime
uint32 MaxTargetLevel; // 198 m_maxTargetLevel
uint32 SpellFamilyName; // 199 m_spellClassSet
ClassFamilyMask SpellFamilyFlags; // 200-201 m_spellClassMask
uint32 MaxAffectedTargets; // 202 m_maxTargets
uint32 DmgClass; // 203 m_defenseType
uint32 PreventionType; // 204 m_preventionType
// uint32 StanceBarOrder; // 205 m_stanceBarOrder not used
float DmgMultiplier[MAX_EFFECT_INDEX]; // 206-208 m_effectChainAmplitude
// uint32 MinFactionId; // 209 m_minFactionID not used
// uint32 MinReputation; // 210 m_minReputation not used
// uint32 RequiredAuraVision; // 211 m_requiredAuraVision not used
uint32 TotemCategory[MAX_SPELL_TOTEM_CATEGORIES];// 212-213 m_requiredTotemCategoryID
uint32 AreaId; // 214
uint32 SchoolMask; // 215 m_schoolMask
uint32 IsServerSide;
// helpers
int32 CalculateSimpleValue(SpellEffectIndex eff) const { return EffectBasePoints[eff] + int32(EffectBaseDice[eff]); }
bool IsFitToFamilyMask(uint64 familyFlags) const
{
return SpellFamilyFlags.IsFitToFamilyMask(familyFlags);
}
bool IsFitToFamily(SpellFamily family, uint64 familyFlags) const
{
return SpellFamily(SpellFamilyName) == family && IsFitToFamilyMask(familyFlags);
}
bool IsFitToFamilyMask(ClassFamilyMask const& mask) const
{
return SpellFamilyFlags.IsFitToFamilyMask(mask);
}
bool IsFitToFamily(SpellFamily family, ClassFamilyMask const& mask) const
{
return SpellFamily(SpellFamilyName) == family && IsFitToFamilyMask(mask);
}
bool HasAttribute(SpellAttributes attribute) const { return !!(Attributes & attribute); }
bool HasAttribute(SpellAttributesEx attribute) const { return !!(AttributesEx & attribute); }
bool HasAttribute(SpellAttributesEx2 attribute) const { return !!(AttributesEx2 & attribute); }
bool HasAttribute(SpellAttributesEx3 attribute) const { return !!(AttributesEx3 & attribute); }
bool HasAttribute(SpellAttributesEx4 attribute) const { return !!(AttributesEx4 & attribute); }
bool HasAttribute(SpellAttributesEx5 attribute) const { return !!(AttributesEx5 & attribute); }
bool HasAttribute(SpellAttributesEx6 attribute) const { return !!(AttributesEx6 & attribute); }
private:
// prevent creating custom entries (copy data from original in fact)
SpellEntry(SpellEntry const&); // DON'T must have implementation
};
// A few fields which are required for automated convertion
// NOTE that these fields are count by _skipping_ the fields that are unused!
#define LOADED_SPELLDBC_FIELD_POS_EQUIPPED_ITEM_CLASS 60 // Must be converted to -1
#define LOADED_SPELLDBC_FIELD_POS_SPELLNAME_0 123 // Links to "MaNGOS server-side spell"
struct SpellCastTimesEntry
{
uint32 ID; // 0 m_ID
int32 CastTime; // 1 m_base
// float CastTimePerLevel; // 2 m_perLevel
// int32 MinCastTime; // 3 m_minimum
};
struct SpellFocusObjectEntry
{
uint32 ID; // 0 m_ID
// char* Name[16]; // 1-15 m_name_lang
// 16 string flags
};
struct SpellRadiusEntry
{
uint32 ID; // m_ID
float Radius; // m_radius
// m_radiusPerLevel
// float RadiusMax; // m_radiusMax
};
struct SpellRangeEntry
{
uint32 ID; // 0 m_ID
float minRange; // 1 m_rangeMin
float maxRange; // 2 m_rangeMax
// uint32 Flags; // 3 m_flags
// char* Name[16]; // 4-19 m_displayName_lang
// uint32 NameFlags; // 20 string flags
// char* ShortName[16]; // 21-36 m_displayNameShort_lang
// uint32 NameFlags; // 37 string flags
};
struct SpellShapeshiftFormEntry
{
uint32 ID; // 0 m_ID
// uint32 buttonPosition; // 1 m_bonusActionBar
// char* Name[16]; // 2-17 m_name_lang
// uint32 NameFlags; // 18 string flags
uint32 flags1; // 19 m_flags
int32 creatureType; // 20 m_creatureType <=0 humanoid, other normal creature types
// uint32 unk1; // 21 m_attackIconID
uint32 attackSpeed; // 22 m_combatRoundTime
uint32 modelID_A; // 23 m_creatureDisplayID[4]
// uint32 modelID_H; // 24 horde modelid (but all 0)
// uint32 unk3; // 25 unused always 0
// uint32 unk4; // 26 unused always 0
uint32 spellId[8]; // 27-34 m_presetSpellID[8]
};
struct SpellDurationEntry
{
uint32 ID; // m_ID
int32 Duration[3]; // m_duration, m_durationPerLevel, m_maxDuration
};
struct SpellItemEnchantmentEntry
{
uint32 ID; // 0 m_ID
uint32 type[3]; // 1-3 m_effect[3]
uint32 amount[3]; // 4-6 m_effectPointsMin[3]
// uint32 amount2[3] // 7-9 m_effectPointsMax[3]
uint32 spellid[3]; // 10-12 m_effectArg[3]
char* description[16]; // 13-28 m_name_lang[16]
// uint32 descriptionFlags; // 29 string flags
uint32 aura_id; // 30 m_itemVisual
uint32 slot; // 31 m_flags
uint32 GemID; // 32 m_src_itemID
uint32 EnchantmentCondition; // 33 m_condition_id
};
struct SpellItemEnchantmentConditionEntry
{
uint32 ID;
uint8 Color[5];
uint8 Comparator[5];
uint8 CompareColor[5];
uint32 Value[5];
};
struct StableSlotPricesEntry
{
uint32 Slot; // m_ID
uint32 Price; // m_cost
};
struct SummonPropertiesEntry
{
uint32 Id; // 0 m_id
uint32 Group; // 1 m_control (enum SummonPropGroup)
uint32 FactionId; // 2 m_faction
uint32 Title; // 3 m_title (enum UnitNameSummonTitle)
uint32 Slot; // 4, m_slot if title = UNITNAME_SUMMON_TITLE_TOTEM, its actual slot (0-6).
// Slot may have other uses, selection of pet type in some cases?
uint32 Flags; // 5 m_flags (enum SummonPropFlags)
};
#define MAX_TALENT_RANK 5
struct TalentEntry
{
uint32 TalentID; // 0 m_ID
uint32 TalentTab; // 1 m_tabID (TalentTab.dbc)
uint32 Row; // 2 m_tierID
uint32 Col; // 3 m_columnIndex
uint32 RankID[MAX_TALENT_RANK]; // 4-8 m_spellRank
// 9-12 part of prev field
uint32 DependsOn; // 13 m_prereqTalent (Talent.dbc)
// 14-15 part of prev field
uint32 DependsOnRank; // 16 m_prereqRank
// 17-18 part of prev field
// uint32 needAddInSpellBook; // 19 m_flags also need disable higest ranks on reset talent tree
uint32 DependsOnSpell; // 20 m_requiredSpellID req.spell
};
struct TalentTabEntry
{
uint32 TalentTabID; // 0 m_ID
// char* name[16]; // 1-16 m_name_lang
// uint32 nameFlags; // 17 string flags
// unit32 spellicon; // 18 m_spellIconID
// 19 m_raceMask
uint32 ClassMask; // 20 m_classMask
uint32 tabpage; // 21 m_orderIndex
// char* internalname; // 22 m_backgroundFile
};
struct TaxiNodesEntry
{
uint32 ID; // 0 m_ID
uint32 map_id; // 1 m_ContinentID
float x; // 2 m_x
float y; // 3 m_y
float z; // 4 m_z
char* name[16]; // 5-21 m_Name_lang
// 22 string flags
uint32 MountCreatureID[2]; // 23-24 m_MountCreatureID[2]
};
struct TaxiPathEntry
{
uint32 ID;
uint32 from;
uint32 to;
uint32 price;
};
struct TaxiPathNodeEntry
{
// 0 m_ID
uint32 path; // 1 m_PathID
uint32 index; // 2 m_NodeIndex
uint32 mapid; // 3 m_ContinentID
float x; // 4 m_LocX
float y; // 5 m_LocY
float z; // 6 m_LocZ
uint32 actionFlag; // 7 m_flags
uint32 delay; // 8 m_delay
uint32 arrivalEventID; // 9 m_arrivalEventID
uint32 departureEventID; // 10 m_departureEventID
};
struct TotemCategoryEntry
{
uint32 ID; // 0 m_ID
// char* name[16]; // 1-16 m_name_lang
// 17 string flags
uint32 categoryType; // 18 m_totemCategoryType (one for specialization)
uint32 categoryMask; // 19 m_totemCategoryMask (compatibility mask for same type: different for totems, compatible from high to low for rods)
};
struct WMOAreaTableEntry
{
uint32 Id; // 0 m_ID index
int32 rootId; // 1 m_WMOID used in root WMO
int32 adtId; // 2 m_NameSetID used in adt file
int32 groupId; // 3 m_WMOGroupID used in group WMO
// uint32 field4; // 4 m_SoundProviderPref
// uint32 field5; // 5 m_SoundProviderPrefUnderwater
// uint32 field6; // 6 m_AmbienceID
// uint32 field7; // 7 m_ZoneMusic
// uint32 field8; // 8 m_IntroSound
uint32 Flags; // 9 m_flags (used for indoor/outdoor determination)
uint32 areaId; // 10 m_AreaTableID (AreaTable.dbc)
// char *Name[16]; // m_AreaName_lang
// uint32 nameFlags;
};
struct WorldMapAreaEntry
{
// uint32 ID; // 0 m_ID
uint32 map_id; // 1 m_mapID
uint32 area_id; // 2 m_areaID index (continent 0 areas ignored)
// char* internal_name // 3 m_areaName
float y1; // 4 m_locLeft
float y2; // 5 m_locRight
float x1; // 6 m_locTop
float x2; // 7 m_locBottom
int32 virtual_map_id; // 8 m_displayMapID -1 (map_id have correct map) other: virtual map where zone show (map_id - where zone in fact internally)
};
/* not used in 2.4.3 code
#define MAX_WORLD_MAP_OVERLAY_AREA_IDX 4
struct WorldMapOverlayEntry
{
uint32 ID; // 0 m_ID
// uint32 worldMapAreaId; // 1 m_mapAreaID (WorldMapArea.dbc)
uint32 areatableID[MAX_WORLD_MAP_OVERLAY_AREA_IDX]; // 2-5 m_areaID
// 6 m_mapPointX
// 7 m_mapPointY
// char* internal_name // 8 m_textureName
// 9 m_textureWidth
// 10 m_textureHeight
// 11 m_offsetX
// 12 m_offsetY
// 13 m_hitRectTop
// 14 m_hitRectLeft
// 15 m_hitRectBottom
// 16 m_hitRectRight
};
*/
struct WorldSafeLocsEntry
{
uint32 ID; // 0 m_ID
uint32 map_id; // 1 m_continent
float x; // 2 m_locX
float y; // 3 m_locY
float z; // 4 m_locZ
// char* name[16] // 5-20 m_AreaName_lang
// 21 string flags
};
// GCC have alternative #pragma pack() syntax and old gcc version not support pack(pop), also any gcc version not support it at some platform
#if defined( __GNUC__ )
#pragma pack()
#else
#pragma pack(pop)
#endif
struct ItemCategorySpellPair
{
uint32 spellId;
uint32 itemId;
ItemCategorySpellPair(uint32 _spellId, uint32 _itemId) : spellId(_spellId), itemId(_itemId) {}
bool operator <(ItemCategorySpellPair const &pair) const { return spellId == pair.spellId ? itemId < pair.itemId : spellId < pair.spellId; }
};
typedef std::set<ItemCategorySpellPair> ItemSpellCategorySet;
typedef std::map<uint32, ItemSpellCategorySet > ItemSpellCategoryStore;
typedef std::set<uint32> SpellCategorySet;
typedef std::map<uint32, SpellCategorySet> SpellCategoryStore;
typedef std::set<uint32> PetFamilySpellsSet;
typedef std::map<uint32, PetFamilySpellsSet > PetFamilySpellsStore;
// Structures not used for casting to loaded DBC data and not required then packing
struct TalentSpellPos
{
TalentSpellPos() : talent_id(0), rank(0) {}
TalentSpellPos(uint16 _talent_id, uint8 _rank) : talent_id(_talent_id), rank(_rank) {}
uint16 talent_id;
uint8 rank;
};
typedef std::map<uint32, TalentSpellPos> TalentSpellPosMap;
struct TaxiPathBySourceAndDestination
{
TaxiPathBySourceAndDestination() : ID(0), price(0) {}
TaxiPathBySourceAndDestination(uint32 _id, uint32 _price) : ID(_id), price(_price) {}
uint32 ID;
uint32 price;
};
typedef std::map<uint32, TaxiPathBySourceAndDestination> TaxiPathSetForSource;
typedef std::map<uint32, TaxiPathSetForSource> TaxiPathSetBySource;
typedef std::vector<TaxiPathNodeEntry const*> TaxiPathNodeList;
typedef std::vector<TaxiPathNodeList> TaxiPathNodesByPath;
#define TaxiMaskSize 16
typedef uint32 TaxiMask[TaxiMaskSize];
#endif
| superwow/mangos-tbc | src/game/Server/DBCStructure.h | C | gpl-2.0 | 60,592 |
<?php
/**
* MaQma Helpdesk Component
* www.imaqma.com
*
* @package MaQma_Helpdesk
* @copyright (C) 2006-2012 Components Lab, Lda.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*
*/
defined('_JEXEC') or die('Direct Access to this location is not allowed.');
class HelpdeskUpdateAdminHelper
{
/**
* When MVC conversion is done this will be in view.html.php
*
* @param string $task Action to execute.
*
* @return void
*/
static public function addToolbar($task)
{
JToolBarHelper::title(JText::_('update_component'), 'sc-users');
}
/**
* When MVC conversion is done this will be in view.html.php
*
* @return void
*/
static public function setDocument()
{
$document = JFactory::getDocument();
$document->setTitle(JText::_('update_component'));
}
} | cuongnd/test_pro | administrator/components/com_maqmahelpdesk/helpers/update.php | PHP | gpl-2.0 | 824 |
<?php
namespace Drupal\graphql;
use Drupal\Core\DependencyInjection\ServiceProviderInterface;
use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\graphql\Reducers\ReducerPass;
class GraphqlServiceProvider implements ServiceProviderInterface {
/**
* {@inheritdoc}
*/
public function register(ContainerBuilder $container) {
$container->addCompilerPass(new ReducerPass());
}
}
| dbethala/longwood-volunteers | modules/graphql/src/GraphqlServiceProvider.php | PHP | gpl-2.0 | 408 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.