code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 3
942
| language
stringclasses 30
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
<ul class="tw">
<?php foreach ($rows as $id => $row) { ?>
<li><?php print $row; ?></li>
<?php } ?>
</ul> | allen12345/miqa | sites/all/themes/questionsanswers/views-view-unformatted--tweets--block.tpl.php | PHP | gpl-2.0 | 104 |
(function($) {
function ACFTableField() {
var t = this;
t.version = '1.3.4';
t.param = {};
// DIFFERENT IN ACF VERSION 4 and 5 {
t.param.classes = {
btn_small: 'acf-icon small',
// "acf-icon-plus" becomes "-plus" since ACF Pro Version 5.3.2
btn_add_row: 'acf-icon-plus -plus',
btn_add_col: 'acf-icon-plus -plus',
btn_remove_row: 'acf-icon-minus -minus',
btn_remove_col: 'acf-icon-minus -minus',
};
t.param.htmlbuttons = {
add_row: '<a href="#" class="acf-table-add-row ' + t.param.classes.btn_small + ' ' + t.param.classes.btn_add_row + '"></a>',
remove_row: '<a href="#" class="acf-table-remove-row ' + t.param.classes.btn_small + ' ' + t.param.classes.btn_remove_row + '"></a>',
add_col: '<a href="#" class="acf-table-add-col ' + t.param.classes.btn_small + ' ' + t.param.classes.btn_add_col + '"></a>',
remove_col: '<a href="#" class="acf-table-remove-col ' + t.param.classes.btn_small + ' ' + t.param.classes.btn_remove_row + '"></a>',
};
// }
t.param.htmltable = {
body_row: '<div class="acf-table-body-row">' +
'<div class="acf-table-body-left">' +
t.param.htmlbuttons.add_row +
'<div class="acf-table-body-cont"><!--ph--></div>' +
'</div>' +
'<div class="acf-table-body-right">' +
t.param.htmlbuttons.remove_row +
'</div>' +
'</div>',
top_cell: '<div class="acf-table-top-cell" data-colparam="">' +
t.param.htmlbuttons.add_col +
'<div class="acf-table-top-cont"><!--ph--></div>' +
'</div>',
header_cell: '<div class="acf-table-header-cell">' +
'<div class="acf-table-header-cont"><!--ph--></div>' +
'</div>',
body_cell: '<div class="acf-table-body-cell">' +
'<div class="acf-table-body-cont"><!--ph--></div>' +
'</div>',
bottom_cell: '<div class="acf-table-bottom-cell">' +
t.param.htmlbuttons.remove_col +
'</div>',
table: '<div class="acf-table-wrap">' +
'<div class="acf-table-table">' + // acf-table-hide-header acf-table-hide-left acf-table-hide-top
'<div class="acf-table-top-row">' +
'<div class="acf-table-top-left">' +
t.param.htmlbuttons.add_col +
'</div>' +
'<div class="acf-table-top-right"></div>' +
'</div>' +
'<div class="acf-table-header-row acf-table-header-hide-off">' +
'<div class="acf-table-header-left">' +
t.param.htmlbuttons.add_row +
'</div>' +
'<div class="acf-table-header-right"></div>' +
'</div>' +
'<div class="acf-table-bottom-row">' +
'<div class="acf-table-bottom-left"></div>' +
'<div class="acf-table-bottom-right"></div>' +
'</div>' +
'</div>' +
'</div>',
};
t.param.htmleditor = '<div class="acf-table-cell-editor">' +
'<textarea name="acf-table-cell-editor-textarea" class="acf-table-cell-editor-textarea"></textarea>' +
'</div>';
t.obj = {
body: $( 'body' ),
};
t.var = {
ajax: false,
};
t.state = {
'current_cell_obj': false,
'cell_editor_cell': false,
'cell_editor_last_keycode': false
};
t.init = function() {
t.init_workflow();
};
t.init_workflow = function() {
t.each_table();
t.table_add_col_event();
t.table_remove_col();
t.table_add_row_event();
t.table_remove_row();
t.cell_editor();
t.cell_editor_tab_navigation();
t.prevent_cell_links();
t.sortable_row();
t.sortable_col();
t.ui_event_use_header();
t.ui_event_caption();
t.ui_event_new_flex_field();
t.ui_event_change_location_rule();
t.ui_event_ajax();
};
t.ui_event_ajax = function() {
$( document ).ajaxComplete( function( event ) {
t.each_table();
});
}
t.ui_event_change_location_rule = function() {
t.obj.body.on( 'change', '[name="post_category[]"], [name="post_format"], [name="page_template"], [name="parent_id"], [name="role"], [name^="tax_input"]', function() {
var interval = setInterval( function() {
var table_fields = $( '.field_type-table' );
if ( table_fields.length > 0 ) {
t.each_table();
clearInterval( interval );
}
}, 100 );
} );
};
t.each_table = function( ) {
$( '.acf-field-table .acf-table-root' ).not( '.acf-table-rendered' ).each( function() {
var p = {};
p.obj_root = $( this ),
table = p.obj_root.find( '.acf-table-wrap' );
if ( table.length > 0 ) {
return;
}
p.obj_root.addClass( 'acf-table-rendered' );
t.data_get( p );
t.data_default( p );
t.field_options_get( p );
t.table_render( p );
t.misc_render( p );
if ( typeof p.data.b[ 1 ] === 'undefined' && typeof p.data.b[ 0 ][ 1 ] === 'undefined' && p.data.b[ 0 ][ 0 ].c === '' ) {
p.obj_root.find( '.acf-table-remove-col' ).hide(),
p.obj_root.find( '.acf-table-remove-row' ).hide();
}
} );
};
t.field_options_get = function( p ) {
try {
p.field_options = $.parseJSON( decodeURIComponent( p.obj_root.find( '[data-field-options]' ).data( 'field-options' ) ) );
}
catch (e) {
p.field_options = {
use_header: 2
};
console.log( 'The tablefield options value is not a valid JSON string:', decodeURIComponent( p.obj_root.find( '[data-field-options]' ).data( 'field-options' ) ) );
console.log( 'The parsing error:', e );
}
};
t.ui_event_use_header = function() {
// HEADER: SELECT FIELD ACTIONS {
t.obj.body.on( 'change', '.acf-table-fc-opt-use-header', function() {
var that = $( this ),
p = {};
p.obj_root = that.parents( '.acf-table-root' );
p.obj_table = p.obj_root.find( '.acf-table-table' );
t.data_get( p );
t.data_default( p );
if ( that.val() === '1' ) {
p.obj_table.removeClass( 'acf-table-hide-header' );
p.data.p.o.uh = 1;
t.update_table_data_field( p );
}
else {
p.obj_table.addClass( 'acf-table-hide-header' );
p.data.p.o.uh = 0;
t.update_table_data_field( p );
}
} );
// }
};
t.ui_event_caption = function() {
// CAPTION: INPUT FIELD ACTIONS {
t.obj.body.on( 'change', '.acf-table-fc-opt-caption', function() {
var that = $( this ),
p = {};
p.obj_root = that.parents( '.acf-table-root' );
p.obj_table = p.obj_root.find( '.acf-table-table' );
t.data_get( p );
t.data_default( p );
p.data.p.ca = that.val();
t.update_table_data_field( p );
} );
// }
};
t.ui_event_new_flex_field = function() {
t.obj.body.on( 'click', '.acf-fc-popup', function() {
// SORTABLE {
$( '.acf-table-table' )
.sortable('destroy')
.unbind();
window.setTimeout( function() {
t.sortable_row();
}, 300 );
// }
} );
};
t.data_get = function( p ) {
// DATA FROM FIELD {
var val = p.obj_root.find( 'input.table' ).val();
p.data = false;
// CHECK FIELD CONTEXT {
if ( p.obj_root.closest( '.acf-fields' ).hasClass( 'acf-block-fields' ) ) {
p.field_context = 'block';
}
else {
p.field_context = 'box';
}
// }
if ( val !== '' ) {
try {
if ( p.field_context === 'box' ) {
p.data = $.parseJSON( decodeURIComponent( val.replace(/\+/g, '%20') ) );
}
if ( p.field_context === 'block' ) {
p.data = $.parseJSON( decodeURIComponent( decodeURIComponent( val.replace(/\+/g, '%20') ) ) );
}
}
catch (e) {
if ( p.field_context === 'box' ) {
console.log( 'The tablefield value is not a valid JSON string:', decodeURIComponent( val.replace(/\+/g, '%20') ) );
console.log( 'The parsing error:', e );
}
if ( p.field_context === 'block' ) {
console.log( 'The tablefield value is not a valid JSON string:', decodeURIComponent( decodeURIComponent( val.replace(/\+/g, '%20') ) ) );
console.log( 'The tablefield value is not a valid JSON string:', decodeURIComponent( decodeURIComponent( decodeURIComponent( val.replace(/\+/g, '%20') ) ) ) );
console.log( 'The parsing error:', e );
}
}
}
return p.data;
// }
};
t.data_default = function( p ) {
// DEFINE DEFAULT DATA {
p.data_defaults = {
acftf: {
v: t.version,
},
p: {
o: {
uh: 0, // use header
},
ca: '', // caption content
},
// from data-colparam
c: [
{
c: '',
},
],
// header
h: [
{
c: '',
},
],
// body
b: [
[
{
c: '',
},
],
],
};
// }
// MERGE DEFAULT DATA {
if ( p.data ) {
if ( typeof p.data.b === 'array' ) {
$.extend( true, p.data, p.data_defaults );
}
}
else {
p.data = p.data_defaults;
}
// }
};
t.table_render = function( p ) {
// TABLE HTML MAIN {
p.obj_root.find( '.acf-table-wrap' ).remove();
p.obj_root.append( t.param.htmltable.table );
// }
// TABLE GET OBJECTS {
p.obj_table = p.obj_root.find( '.acf-table-table' );
p.obj_top_row = p.obj_root.find( '.acf-table-top-row' ),
p.obj_top_insert = p.obj_top_row.find( '.acf-table-top-right' ),
p.obj_header_row = p.obj_root.find( '.acf-table-header-row' ),
p.obj_header_insert = p.obj_header_row.find( '.acf-table-header-right' ),
p.obj_bottom_row = p.obj_root.find( '.acf-table-bottom-row' ),
p.obj_bottom_insert = p.obj_bottom_row.find( '.acf-table-bottom-right' );
// }
// TOP CELLS {
if ( p.data.c ) {
for ( i in p.data.c ) {
p.obj_top_insert.before( t.param.htmltable.top_cell );
}
}
t.table_top_labels( p );
// }
// HEADER CELLS {
if ( p.data.h ) {
for ( i in p.data.h ) {
p.obj_header_insert.before( t.param.htmltable.header_cell.replace( '<!--ph-->', p.data.h[ i ].c.replace( /xxx"/g, '"' ) ) );
}
}
// }
// BODY ROWS {
if ( p.data.b ) {
for ( i in p.data.b ) {
p.obj_bottom_row.before( t.param.htmltable.body_row.replace( '<!--ph-->', parseInt(i) + 1 ) );
}
}
// }
// BODY ROWS CELLS {
var body_rows = p.obj_root.find( '.acf-table-body-row'),
row_i = 0;
if ( body_rows ) {
body_rows.each( function() {
var body_row = $( this ),
row_insert = body_row.find( '.acf-table-body-right' );
for( i in p.data.b[ row_i ] ) {
row_insert.before( t.param.htmltable.body_cell.replace( '<!--ph-->', p.data.b[ row_i ][ i ].c.replace( /xxx"/g, '"' ) ) );
}
row_i = row_i + 1
} );
}
// }
// TABLE BOTTOM {
if ( p.data.c ) {
for ( i in p.data.c ) {
p.obj_bottom_insert.before( t.param.htmltable.bottom_cell );
}
}
// }
};
t.misc_render = function( p ) {
t.init_option_use_header( p );
t.init_option_caption( p );
};
t.init_option_use_header = function( p ) {
// VARS {
var v = {};
v.obj_use_header = p.obj_root.find( '.acf-table-fc-opt-use-header' );
// }
// HEADER {
// HEADER: FIELD OPTIONS, THAT AFFECTS DATA {
// HEADER IS NOT ALLOWED
if ( p.field_options.use_header === 2 ) {
p.obj_table.addClass( 'acf-table-hide-header' );
p.data.p.o.uh = 0;
t.update_table_data_field( p );
}
// HEADER IS REQUIRED
if ( p.field_options.use_header === 1 ) {
p.data.p.o.uh = 1;
t.update_table_data_field( p );
}
// }
// HEADER: SET CHECKBOX STATUS {
if ( p.data.p.o.uh === 1 ) {
v.obj_use_header.val( '1' );
}
if ( p.data.p.o.uh === 0 ) {
v.obj_use_header.val( '0' );
}
// }
// HEADER: SET HEADER VISIBILITY {
if ( p.data.p.o.uh === 1 ) {
p.obj_table.removeClass( 'acf-table-hide-header' );
}
if ( p.data.p.o.uh === 0 ) {
p.obj_table.addClass( 'acf-table-hide-header' );
}
// }
// }
};
t.init_option_caption = function( p ) {
if (
typeof p.field_options.use_caption !== 'number' ||
p.field_options.use_caption === 2
) {
return;
}
// VARS {
var v = {};
v.obj_caption = p.obj_root.find( '.acf-table-fc-opt-caption' );
// }
// SET CAPTION VALUE {
v.obj_caption.val( p.data.p.ca );
// }
};
t.table_add_col_event = function() {
t.obj.body.on( 'click', '.acf-table-add-col', function( e ) {
e.preventDefault();
var that = $( this ),
p = {};
p.obj_col = that.parent();
t.table_add_col( p );
} );
};
t.table_add_col = function( p ) {
// requires
// p.obj_col
var that_index = p.obj_col.index();
p.obj_root = p.obj_col.parents( '.acf-table-root' );
p.obj_table = p.obj_root.find( '.acf-table-table' );
$( p.obj_table.find( '.acf-table-top-row' ).children()[ that_index ] ).after( t.param.htmltable.top_cell.replace( '<!--ph-->', '' ) );
$( p.obj_table.find( '.acf-table-header-row' ).children()[ that_index ] ).after( t.param.htmltable.header_cell.replace( '<!--ph-->', '' ) );
p.obj_table.find( '.acf-table-body-row' ).each( function() {
$( $( this ).children()[ that_index ] ).after( t.param.htmltable.body_cell.replace( '<!--ph-->', '' ) );
} );
$( p.obj_table.find( '.acf-table-bottom-row' ).children()[ that_index ] ).after( t.param.htmltable.bottom_cell.replace( '<!--ph-->', '' ) );
t.table_top_labels( p );
p.obj_table.find( '.acf-table-remove-col' ).show();
p.obj_table.find( '.acf-table-remove-row' ).show();
t.table_build_json( p );
};
t.table_remove_col = function() {
t.obj.body.on( 'click', '.acf-table-remove-col', function( e ) {
e.preventDefault();
var p = {},
that = $( this ),
that_index = that.parent().index(),
obj_rows = undefined,
cols_count = false;
p.obj_root = that.parents( '.acf-table-root' );
p.obj_table = p.obj_root.find( '.acf-table-table' );
p.obj_top = p.obj_root.find( '.acf-table-top-row' );
obj_rows = p.obj_table.find( '.acf-table-body-row' );
cols_count = p.obj_top.find( '.acf-table-top-cell' ).length;
$( p.obj_table.find( '.acf-table-top-row' ).children()[ that_index ] ).remove();
$( p.obj_table.find( '.acf-table-header-row' ).children()[ that_index ] ).remove();
if ( cols_count == 1 ) {
obj_rows.remove();
t.table_add_col( {
obj_col: p.obj_table.find( '.acf-table-top-left' )
} );
t.table_add_row( {
obj_row: p.obj_table.find( '.acf-table-header-row' )
} );
p.obj_table.find( '.acf-table-remove-col' ).hide();
p.obj_table.find( '.acf-table-remove-row' ).hide();
}
else {
obj_rows.each( function() {
$( $( this ).children()[ that_index ] ).remove();
} );
}
$( p.obj_table.find( '.acf-table-bottom-row' ).children()[ that_index ] ).remove();
t.table_top_labels( p );
t.table_build_json( p );
} );
};
t.table_add_row_event = function() {
t.obj.body.on( 'click', '.acf-table-add-row', function( e ) {
e.preventDefault();
var that = $( this ),
p = {};
p.obj_row = that.parent().parent();
t.table_add_row( p );
});
};
t.table_add_row = function( p ) {
// requires
// p.obj_row
var that_index = 0,
col_amount = 0,
body_cells_html = '';
p.obj_root = p.obj_row.parents( '.acf-table-root' );
p.obj_table = p.obj_root.find( '.acf-table-table' );
p.obj_table_rows = p.obj_table.children();
col_amount = p.obj_table.find( '.acf-table-top-cell' ).size();
that_index = p.obj_row.index();
for ( i = 0; i < col_amount; i++ ) {
body_cells_html = body_cells_html + t.param.htmltable.body_cell.replace( '<!--ph-->', '' );
}
$( p.obj_table_rows[ that_index ] )
.after( t.param.htmltable.body_row )
.next()
.find('.acf-table-body-left')
.after( body_cells_html );
t.table_left_labels( p );
p.obj_table.find( '.acf-table-remove-col' ).show();
p.obj_table.find( '.acf-table-remove-row' ).show();
t.table_build_json( p );
};
t.table_remove_row = function() {
t.obj.body.on( 'click', '.acf-table-remove-row', function( e ) {
e.preventDefault();
var p = {},
that = $( this ),
rows_count = false;
p.obj_root = that.parents( '.acf-table-root' );
p.obj_table = p.obj_root.find( '.acf-table-table' );
p.obj_rows = p.obj_root.find( '.acf-table-body-row' );
rows_count = p.obj_rows.length;
that.parent().parent().remove();
if ( rows_count == 1 ) {
t.table_add_row( {
obj_row: p.obj_table.find( '.acf-table-header-row' )
} );
p.obj_table.find( '.acf-table-remove-row' ).hide();
}
t.table_left_labels( p );
t.table_build_json( p );
} );
};
t.table_top_labels = function( p ) {
var letter_i_1 = 'A'.charCodeAt( 0 ),
letter_i_2 = 'A'.charCodeAt( 0 ),
use_2 = false;
p.obj_table.find( '.acf-table-top-cont' ).each( function() {
var string = '';
if ( !use_2 ) {
string = String.fromCharCode( letter_i_1 );
if ( letter_i_1 === 'Z'.charCodeAt( 0 ) ) {
letter_i_1 = 'A'.charCodeAt( 0 );
use_2 = true;
}
else {
letter_i_1 = letter_i_1 + 1;
}
}
else {
string = String.fromCharCode( letter_i_1 ) + String.fromCharCode( letter_i_2 );
if ( letter_i_2 === 'Z'.charCodeAt( 0 ) ) {
letter_i_1 = letter_i_1 + 1;
letter_i_2 = 'A'.charCodeAt( 0 );
}
else {
letter_i_2 = letter_i_2 + 1;
}
}
$( this ).text( string );
} );
};
t.table_left_labels = function( p ) {
var i = 0;
p.obj_table.find( '.acf-table-body-left' ).each( function() {
i = i + 1;
$( this ).find( '.acf-table-body-cont' ).text( i );
} );
};
t.table_build_json = function( p ) {
var i = 0,
i2 = 0;
p.data = t.data_get( p );
t.data_default( p );
p.data.c = [];
p.data.h = [];
p.data.b = [];
// TOP {
i = 0;
p.obj_table.find( '.acf-table-top-cont' ).each( function() {
p.data.c[ i ] = {};
p.data.c[ i ].p = $( this ).parent().data( 'colparam' );
i = i + 1;
} );
// }
// HEADER {
i = 0;
p.obj_table.find( '.acf-table-header-cont' ).each( function() {
p.data.h[ i ] = {};
p.data.h[ i ].c = $( this ).html();
i = i + 1;
} );
// }
// BODY {
i = 0;
i2 = 0;
p.obj_table.find( '.acf-table-body-row' ).each( function() {
p.data.b[ i ] = [];
$( this ).find( '.acf-table-body-cell .acf-table-body-cont' ).each( function() {
p.data.b[ i ][ i2 ] = {};
p.data.b[ i ][ i2 ].c = $( this ).html();
i2 = i2 + 1;
} );
i2 = 0;
i = i + 1;
} );
// }
// UPDATE INPUT WITH NEW DATA {
t.update_table_data_field( p );
// }
};
t.update_table_data_field = function( p ) {
// UPDATE INPUT WITH NEW DATA {
p.data = t.update_table_data_version( p.data );
// makes json string from data object
var data = JSON.stringify( p.data );
// adds backslash to all \" in JSON string because encodeURIComponent() strippes backslashes
data.replace( /\\"/g, '\\"' );
// encodes the JSON string to URI component, the format, the JSON string is saved to the database
data = encodeURIComponent( data )
p.obj_root.find( 'input.table' ).val( data );
t.field_changed( p );
// }
};
t.update_table_data_version = function( data ) {
if ( typeof data.acftf === 'undefined' ) {
data.acftf = {};
}
data.acftf.v = t.version;
return data;
}
t.cell_editor = function() {
t.obj.body.on( 'click', '.acf-table-body-cell, .acf-table-header-cell', function( e ) {
e.stopImmediatePropagation();
t.cell_editor_save();
var that = $( this );
t.cell_editor_add_editor({
'that': that
});
} );
t.obj.body.on( 'click', '.acf-table-cell-editor-textarea', function( e ) {
e.stopImmediatePropagation();
} );
t.obj.body.on( 'click', function( e ) {
t.cell_editor_save();
} );
};
t.cell_editor_add_editor = function( p ) {
var defaults = {
'that': false
};
p = $.extend( true, defaults, p );
if ( p['that'] ) {
var that_val = p['that'].find( '.acf-table-body-cont, .acf-table-header-cont' ).html();
t.state.current_cell_obj = p['that'];
t.state.cell_editor_is_open = true;
p['that'].prepend( t.param.htmleditor ).find( '.acf-table-cell-editor-textarea' ).html( that_val ).focus();
}
};
t.get_next_table_cell = function( p ) {
var defaults = {
'key': false
};
p = $.extend( true, defaults, p );
// next cell of current row
var next_cell = t.state.current_cell_obj
.next( '.acf-table-body-cell, .acf-table-header-cell' );
// else if get next row
if ( next_cell.length === 0 ) {
next_cell = t.state.current_cell_obj
.parent()
.next( '.acf-table-body-row' )
.find( '.acf-table-body-cell')
.first();
}
// if next row, get first cell of that row
if ( next_cell.length !== 0 ) {
t.state.current_cell_obj = next_cell;
}
else {
t.state.current_cell_obj = false;
}
};
t.get_prev_table_cell = function( p ) {
var defaults = {
'key': false
};
p = $.extend( true, defaults, p );
// prev cell of current row
var table_obj = t.state.current_cell_obj.closest( '.acf-table-table' ),
no_header = table_obj.hasClass( 'acf-table-hide-header' );
prev_cell = t.state.current_cell_obj
.prev( '.acf-table-body-cell, .acf-table-header-cell' );
// else if get prev row
if ( prev_cell.length === 0 ) {
var row_selectors = [ '.acf-table-body-row' ];
// prevents going to header cell if table header is hidden
if ( no_header === false ) {
row_selectors.push( '.acf-table-header-row' );
}
prev_cell = t.state.current_cell_obj
.parent()
.prev( row_selectors.join( ',' ) )
.find( '.acf-table-body-cell, .acf-table-header-cell' )
.last();
}
// if next row, get first cell of that row
if ( prev_cell.length !== 0 ) {
t.state.current_cell_obj = prev_cell;
}
else {
t.state.current_cell_obj = false;
}
};
t.cell_editor_save = function() {
var cell_editor = t.obj.body.find( '.acf-table-cell-editor' ),
cell_editor_textarea = cell_editor.find( '.acf-table-cell-editor-textarea' ),
p = {},
cell_editor_val = '';
if ( typeof cell_editor_textarea.val() !== 'undefined' ) {
p.obj_root = cell_editor.parents( '.acf-table-root' );
p.obj_table = p.obj_root.find( '.acf-table-table' );
var cell_editor_val = cell_editor_textarea.val();
// prevent XSS injection
cell_editor_val = cell_editor_val.replace( /\<(script)/ig, '<$1' );
cell_editor_val = cell_editor_val.replace( /\<\/(script)/ig, '</$1' );
cell_editor.next().html( cell_editor_val );
t.table_build_json( p );
cell_editor.remove();
t.state.cell_editor_is_open = false;
p.obj_root.find( '.acf-table-remove-col' ).show(),
p.obj_root.find( '.acf-table-remove-row' ).show();
}
};
t.cell_editor_tab_navigation = function() {
t.obj.body.on( 'keydown', '.acf-table-cell-editor', function( e ) {
var keyCode = e.keyCode || e.which;
if ( keyCode == 9 ) {
e.preventDefault();
t.cell_editor_save();
if ( t.state.cell_editor_last_keycode === 16 ) {
t.get_prev_table_cell();
}
else {
t.get_next_table_cell();
}
t.cell_editor_add_editor({
'that': t.state.current_cell_obj
});
}
t.state.cell_editor_last_keycode = keyCode;
});
};
t.prevent_cell_links = function() {
t.obj.body.on( 'click', '.acf-table-body-cont a, .acf-table-header-cont a', function( e ) {
e.preventDefault();
} );
};
t.sortable_fix_width = function(e, ui) {
ui.children().each( function() {
var that = $( this );
that.width( that.width() );
} );
return ui;
};
t.sortable_row = function() {
var param = {
axis: 'y',
items: '> .acf-table-body-row',
containment: 'parent',
handle: '.acf-table-body-left',
helper: t.sortable_fix_width,
update: function( event, ui ) {
var p = {};
p.obj_root = ui.item.parents( '.acf-table-root' );
p.obj_table = p.obj_root.find( '.acf-table-table' );
t.table_left_labels( p );
t.table_build_json( p );
},
};
$( '.acf-table-table' ).sortable( param );
};
t.sortable_col = function() {
var p = {};
p.start_index = 0;
p.end_index = 0;
var param = {
axis: 'x',
items: '> .acf-table-top-cell',
containment: 'parent',
helper: t.sortable_fix_width,
start: function(event, ui) {
p.start_index = ui.item.index();
},
update: function( event, ui ) {
p.end_index = ui.item.index();
p.obj_root = ui.item.parents( '.acf-table-root' );
p.obj_table = p.obj_root.find( '.acf-table-table' );
t.table_top_labels( p );
t.sort_cols( p );
t.table_build_json( p );
},
};
$( '.acf-table-top-row' ).sortable( param );
t.obj.body.on( 'click', '.acf-fc-popup', function() {
$( '.acf-table-top-row' )
.sortable('destroy')
.unbind();
window.setTimeout( function() {
$( '.acf-table-top-row' ).sortable( param );
}, 300 );
} );
};
t.field_changed = function( p ) {
if ( p.field_context === 'block' ) {
p.obj_root.change();
}
};
t.sort_cols = function( p ) {
p.obj_table.find('.acf-table-header-row').each( function() {
p.header_row = $(this),
p.header_row_children = p.header_row.children();
if ( p.end_index < p.start_index ) {
$( p.header_row_children[ p.end_index ] ).before( $( p.header_row_children[ p.start_index ] ) );
}
if ( p.end_index > p.start_index ) {
$( p.header_row_children[ p.end_index ] ).after( $( p.header_row_children[ p.start_index ] ) );
}
} );
p.obj_table.find('.acf-table-body-row').each( function() {
p.body_row = $(this),
p.body_row_children = p.body_row.children();
if ( p.end_index < p.start_index ) {
$( p.body_row_children[ p.end_index ] ).before( $( p.body_row_children[ p.start_index ] ) );
}
if ( p.end_index > p.start_index ) {
$( p.body_row_children[ p.end_index ] ).after( $( p.body_row_children[ p.start_index ] ) );
}
} );
};
t.helper = {
getLength: function( o ) {
var len = o.length ? --o.length : -1;
for (var k in o) {
len++;
}
return len;
},
};
};
var acf_table_field = new ACFTableField();
acf_table_field.init();
})( jQuery );
| johannheyne/acf-table | advanced-custom-fields-table-field/tags/1.3.4/js/input-v5.js | JavaScript | gpl-2.0 | 26,869 |
FROM kucing/node:latest
MAINTAINER Ivan <[email protected]>
RUN npm install -g bower gulp phantomjs eslint node-gyp
WORKDIR /app
| ivanp/dockerbuilds | node-tools/Dockerfile | Dockerfile | gpl-2.0 | 134 |
/*
* minimum data types for MIPS and the Ultra64 RCP
*
* No copyright is intended on this file. :)
*
* To work with features of the RCP hardware, we need at the very least:
* 1. a 64-bit type or a type which can encompass 64-bit operations
* 2. signed and unsigned 32-or-more-bit types (s32, u32)
* 3. signed and unsigned 16-or-more-bit types (s16, u16)
* 4. signed and unsigned 8-or-more-bit types (s8, u8)
*
* This tends to coincide with the regulations of <stdint.h> and even most of
* what is guaranteed by simple preprocessor logic and the C89 standard, so
* the deduction of RCP hardware types will have the following priority:
* 1. compiler implementation of the <stdint.h> extension
* 2. 64-bit ABI detection by the preprocessor
* 3. preprocessor derivation of literal integer interpretation
* 4. the presumption of C89 conformance for 8-, 16-, and 32-bit types
* and the presumption of `long long` support for 64-bit types
*
* In situations where the compiler's implementation chooses to control these
* arbitrary sizes on its own or to exchange portability with C99 compliance,
* the standard types (either built-in or external <stdint.h>) will be preferred.
*/
/*
* Rather than call it "n64_types.h" or "my_stdint.h", the idea is that this
* header should be maintainable to any independent implementation's needs,
* especially in the event that one decides that type requirements should be
* mandated by the user and not permanently merged into the C specifications.
*
* Compilers always have had, always should have, and always will have the
* right to choose whether it is the programmer's job to establish the
* arbitrary sizes they prefer to have or whether the C language should
* be complicated enough to specify additional built-in criteria such as
* this, such that it should be able to depend on a system header for it.
*/
#ifndef _MY_TYPES_H_
#define _MY_TYPES_H_
/*
* Until proven otherwise, there are no standard integer types.
*/
#undef HAVE_STANDARD_INTEGER_TYPES
/*
* an optional facility which could be used as an external alternative to
* deducing minimum-width types (if the compiler agrees to rely on this level
* of the language specifications to have it)
*
* Because no standard system is required to have any exact-width type, the
* C99 enforcement of <stdint.h> is more of an early initiative (as in,
* "better early than late" or "better early than never at all") rather than
* a fully portable resource available or even possible all of the time.
*/
#if defined(__STDC_VERSION__) && (__STDC_VERSION__ < 199901L)
/*
* Something which strictly emphasizes pre-C99 standard compliance likely
* does not have any <stdint.h> that we could include (nor built-in types).
*/
#elif defined(_XBOX) || defined(_XENON)
/*
* Since the Microsoft APIs frequently use `long` instead of `int` to ensure
* a minimum of 32-bit DWORD size, they were forced to propose a "LLP64" ABI.
*/
#define MICROSOFT_ABI
#elif defined(_MSC_VER) && (_MSC_VER < 1600)
/*
* In some better, older versions of MSVC, there often was no <stdint.h>.
* We can still use the built-in MSVC types to create the <stdint.h> types.
*/
#define MICROSOFT_ABI
#else
#include <stdint.h>
#endif
/*
* With or without external or internal support for <stdint.h>, we need to
* confirm the level of support for RCP data types on the Nintendo 64.
*
* We only need minimum-width data types, not exact-width types.
* Systems on which there is no 16- or 32-bit type, for example, can easily
* be accounted for by the code itself using optimizable AND bit-masks.
*/
#if defined(INT8_MIN) && defined(INT8_MAX)
#define HAVE_INT8_EXACT
#endif
#if defined(INT_FAST8_MIN) && defined(INT_FAST8_MAX)
#define HAVE_INT8_FAST
#endif
#if defined(INT_LEAST8_MIN) && defined(INT_LEAST8_MAX)
#define HAVE_INT8_MINIMUM
#endif
#if defined(INT16_MIN) && defined(INT16_MAX)
#define HAVE_INT16_EXACT
#endif
#if defined(INT_FAST16_MIN) && defined(INT_FAST16_MAX)
#define HAVE_INT16_FAST
#endif
#if defined(INT_LEAST16_MIN) && defined(INT_LEAST16_MAX)
#define HAVE_INT16_MINIMUM
#endif
#if defined(INT32_MIN) && defined(INT32_MAX)
#define HAVE_INT32_EXACT
#endif
#if defined(INT_FAST32_MIN) && defined(INT_FAST32_MAX)
#define HAVE_INT32_FAST
#endif
#if defined(INT_LEAST32_MIN) && defined(INT_LEAST32_MAX)
#define HAVE_INT32_MINIMUM
#endif
#if defined(INT64_MIN) && defined(INT64_MAX)
#define HAVE_INT64_EXACT
#endif
#if defined(INT_FAST64_MIN) && defined(INT_FAST64_MAX)
#define HAVE_INT64_FAST
#endif
#if defined(INT_LEAST64_MIN) && defined(INT_LEAST64_MAX)
#define HAVE_INT64_MINIMUM
#endif
#if defined(HAVE_INT8_EXACT)\
|| defined(HAVE_INT8_FAST) \
|| defined(HAVE_INT8_MINIMUM)
#define HAVE_INT8
#endif
#if defined(HAVE_INT16_EXACT)\
|| defined(HAVE_INT16_FAST) \
|| defined(HAVE_INT16_MINIMUM)
#define HAVE_INT16
#endif
#if defined(HAVE_INT32_EXACT)\
|| defined(HAVE_INT32_FAST) \
|| defined(HAVE_INT32_MINIMUM)
#define HAVE_INT32
#endif
#if defined(HAVE_INT64_EXACT)\
|| defined(HAVE_INT64_FAST) \
|| defined(HAVE_INT64_MINIMUM)
#define HAVE_INT64
#endif
/*
* This determines whether or not it is possible to use the evolution of the
* C standards for compiler advice on how to define the types or whether we
* will instead rely on preprocessor logic and ABI detection or C89 rules to
* define each of the types.
*/
#if defined(HAVE_INT8) \
&& defined(HAVE_INT16)\
&& defined(HAVE_INT32)\
&& defined(HAVE_INT64)
#define HAVE_STANDARD_INTEGER_TYPES
#endif
#if defined(HAVE_INT8_EXACT)
typedef int8_t s8;
typedef uint8_t u8;
typedef s8 i8;
#elif defined(HAVE_INT8_FAST)
typedef int_fast8_t s8;
typedef uint_fast8_t u8;
typedef s8 i8;
#elif defined(HAVE_INT8_MINIMUM)
typedef int_least8_t s8;
typedef uint_least8_t u8;
typedef s8 i8;
#elif defined(MICROSOFT_ABI)
typedef signed __int8 s8;
typedef unsigned __int8 u8;
typedef __int8 i8;
#else
typedef signed char s8;
typedef unsigned char u8;
typedef char i8;
#endif
#if defined(HAVE_INT16_EXACT)
typedef int16_t s16;
typedef uint16_t u16;
#elif defined(HAVE_INT16_FAST)
typedef int_fast16_t s16;
typedef uint_fast16_t u16;
#elif defined(HAVE_INT16_MINIMUM)
typedef int_least16_t s16;
typedef uint_least16_t u16;
#elif defined(MICROSOFT_ABI)
typedef signed __int16 s16;
typedef unsigned __int16 u16;
#else
typedef signed short s16;
typedef unsigned short u16;
#endif
#if defined(HAVE_INT32_EXACT)
typedef int32_t s32;
typedef uint32_t u32;
#elif defined(HAVE_INT32_FAST)
typedef int_fast32_t s32;
typedef uint_fast32_t u32;
#elif defined(HAVE_INT32_MINIMUM)
typedef int_least32_t s32;
typedef uint_least32_t u32;
#elif defined(MICROSOFT_ABI)
typedef signed __int32 s32;
typedef unsigned __int32 u32;
#elif !defined(__LP64__) && (0xFFFFFFFFL < 0xFFFFFFFFUL)
typedef signed long s32;
typedef unsigned long u32;
#else
typedef signed int s32;
typedef unsigned int u32;
#endif
#if defined(HAVE_INT64_EXACT)
typedef int64_t s64;
typedef uint64_t u64;
#elif defined(HAVE_INT64_FAST)
typedef int_fast64_t s64;
typedef uint_fast64_t u64;
#elif defined(HAVE_INT64_MINIMUM)
typedef int_least64_t s64;
typedef uint_least64_t u64;
#elif defined(MICROSOFT_ABI)
typedef signed __int64 s64;
typedef unsigned __int64 u64;
#elif defined(__LP64__) && (0x00000000FFFFFFFFUL < ~0UL)
typedef signed long s64;
typedef unsigned long u64;
#else
typedef signed long long s64;
typedef unsigned long long u64;
#endif
/*
* Although most types are signed by default, using `int' instead of `signed
* int' and `i32' instead of `s32' can be preferable to denote cases where
* the signedness of something operated on is irrelevant to the algorithm.
*/
typedef s16 i16;
typedef s32 i32;
typedef s64 i64;
/*
* If <stdint.h> was unavailable or not included (should be included before
* "my_types.h" if it is ever to be included), then perhaps this is the
* right opportunity to try defining the <stdint.h> types ourselves.
*
* Due to sole popularity, code can sometimes be easier to read when saying
* things like "int8_t" instead of "i8", just because more people are more
* likely to understand the <stdint.h> type names in generic C code. To be
* as neutral as possible, people will have every right to sometimes prefer
* saying "uint32_t" instead of "u32" for the sake of modern standards.
*
* The below macro just means whether or not we had access to <stdint.h>
* material to deduce any of our 8-, 16-, 32-, or 64-bit type definitions.
*/
#ifndef HAVE_STANDARD_INTEGER_TYPES
typedef s8 int8_t;
typedef u8 uint8_t;
typedef s16 int16_t;
typedef u16 uint16_t;
typedef s32 int32_t;
typedef u32 uint32_t;
typedef s64 int64_t;
typedef u64 uint64_t;
#define HAVE_STANDARD_INTEGER_TYPES
#endif
/*
* Single- and double-precision floating-point data types have a little less
* room for maintenance across different CPU processors, as the C standard
* just provides `float' and `[long] double'. However, if we are going to
* need 32- and 64-bit floating-point precision (which MIPS emulation does
* require), then it could be nice to have these names just to be consistent.
*/
typedef float f32;
typedef double f64;
/*
* Pointer types, serving as the memory reference address to the actual type.
* I thought this was useful to have due to the various reasons for declaring
* or using variable pointers in various styles and complex scenarios.
* ex) i32* pointer;
* ex) i32 * pointer;
* ex) i32 *a, *b, *c;
* neutral: `pi32 pointer;' or `pi32 a, b, c;'
*/
typedef i8* pi8;
typedef i16* pi16;
typedef i32* pi32;
typedef i64* pi64;
typedef s8* ps8;
typedef s16* ps16;
typedef s32* ps32;
typedef s64* ps64;
typedef u8* pu8;
typedef u16* pu16;
typedef u32* pu32;
typedef u64* pu64;
typedef f32* pf32;
typedef f64* pf64;
typedef void* p_void;
typedef void(*p_func)(void);
/*
* helper macros with exporting functions for shared objects or dynamically
* loaded libraries
*/
#if defined(_XBOX)
#define EXPORT
#define CALL
#elif defined(_WIN32)
#define EXPORT __declspec(dllexport)
#define CALL __cdecl
#elif (__GNUC__)
#define EXPORT __attribute__((visibility("default")))
#define CALL
#endif
/*
* Optimizing compilers aren't necessarily perfect compilers, but they do
* have that extra chance of supporting explicit [anti-]inline instructions.
*/
#ifdef _MSC_VER
#define INLINE __inline
#define NOINLINE __declspec(noinline)
#define ALIGNED _declspec(align(16))
#elif defined(__GNUC__)
#define INLINE inline
#define NOINLINE __attribute__((noinline))
#define ALIGNED __attribute__((aligned(16)))
#else
#define INLINE
#define NOINLINE
#define ALIGNED
#endif
/*
* aliasing helpers
* Strictly put, this may be unspecified behavior, but it's nice to have!
*/
typedef union {
u8 B[2];
s8 SB[2];
i16 W;
u16 UW;
s16 SW; /* Here, again, explicitly writing "signed" may help clarity. */
} word_16;
typedef union {
u8 B[4];
s8 SB[4];
i16 H[2];
u16 UH[2];
s16 SH[2];
i32 W;
u32 UW;
s32 SW;
} word_32;
typedef union {
u8 B[8];
s8 SB[8];
i16 F[4];
u16 UF[4];
s16 SF[4];
i32 H[2];
u32 UH[2];
s32 SH[2];
i64 W;
u64 UW;
s64 SW;
} word_64;
/*
* helper macros for indexing memory in the above unions
* EEP! Currently concentrates mostly on 32-bit endianness.
*/
#ifndef ENDIAN_M
#if defined(__BIG_ENDIAN__) | (__BYTE_ORDER != __LITTLE_ENDIAN)
#define ENDIAN_M ( 0)
#else
#define ENDIAN_M (~0)
#endif
#endif
#define ENDIAN_SWAP_BYTE (ENDIAN_M & 0x7 & 3)
#define ENDIAN_SWAP_HALF (ENDIAN_M & 0x6 & 2)
#define ENDIAN_SWAP_BIMI (ENDIAN_M & 0x5 & 1)
#define ENDIAN_SWAP_WORD (ENDIAN_M & 0x4 & 0)
#define BES(address) ((address) ^ ENDIAN_SWAP_BYTE)
#define HES(address) ((address) ^ ENDIAN_SWAP_HALF)
#define MES(address) ((address) ^ ENDIAN_SWAP_BIMI)
#define WES(address) ((address) ^ ENDIAN_SWAP_WORD)
/*
* extra types of encoding for the well-known MIPS RISC architecture
* Possibly implement other machine types in future versions of this header.
*/
typedef struct {
unsigned opcode: 6;
unsigned rs: 5;
unsigned rt: 5;
unsigned rd: 5;
unsigned sa: 5;
unsigned function: 6;
} MIPS_type_R;
typedef struct {
unsigned opcode: 6;
unsigned rs: 5;
unsigned rt: 5;
unsigned imm: 16;
} MIPS_type_I;
/*
* Maybe worth including, maybe not.
* It's sketchy since bit-fields pertain to `int' type, of which the size is
* not necessarily going to be even 4 bytes. On C compilers for MIPS itself,
* almost certainly, but is this really important to have?
*/
#if 0
typedef struct {
unsigned opcode: 6;
unsigned target: 26;
} MIPS_type_J;
#endif
/*
* Saying "int" all the time for variables of true/false meaning can be sort
* of misleading. (So can adding dumb features to C99, like "bool".)
*
* Boolean is a proper noun, so the correct name has a capital 'B'.
*/
typedef int Boolean;
#if !defined(FALSE) && !defined(TRUE)
#define FALSE 0
#define TRUE 1
#endif
#endif
| LegendOfDragoon/AziAudio | AziAudio/my_types.h | C | gpl-2.0 | 14,081 |
/*
* Rasengan - Manga and Comic Downloader
* Copyright (C) 2013 Sauriel
*
* 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/>.
*/
package de.sauriel.rasengan.ui;
import java.awt.BorderLayout;
import javax.swing.JDialog;
import javax.swing.JProgressBar;
import javax.swing.JLabel;
import java.util.Observable;
import java.util.Observer;
public class DownloadDialog extends JDialog implements Observer {
private static final long serialVersionUID = 4251447351437107605L;
JProgressBar progressBar;
public DownloadDialog() {
// Configure Dialog
setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
setAlwaysOnTop(true);
setModal(true);
setModalityType(ModalityType.MODELESS);
setResizable(false);
setTitle("Downloading: " + RasenganMainFrame.comic.getName());
setBounds(100, 100, 300, 60);
setLayout(new BorderLayout(0, 0));
// Set Content
JLabel labelDownload = new JLabel("Downloading: " + RasenganMainFrame.comic.getName());
add(labelDownload, BorderLayout.NORTH);
progressBar = new JProgressBar();
add(progressBar, BorderLayout.CENTER);
}
@Override
public void update(Observable comicService, Object imagesCount) {
int[] newImagesCount= (int[]) imagesCount;
progressBar.setMaximum(newImagesCount[1]);
progressBar.setValue(newImagesCount[0]);
if (newImagesCount[0] == newImagesCount[1]) {
dispose();
}
}
}
| Sauriel/rasengan | src/de/sauriel/rasengan/ui/DownloadDialog.java | Java | gpl-2.0 | 2,082 |
% To rebuild the .pdf from this source, use something like the following
% latex quickref.tex
% dvips -t letter -f -Pcmz < quickref.dvi >| quickref.ps
% ps2pdf -sPAPERSIZE=letter quickref.ps
\documentclass[12pt]{article}
\usepackage[utf-8]{inputenc}
\usepackage{lscape}
\usepackage{setspace}
\usepackage{graphicx}
\usepackage{multicol}
\usepackage[normalem]{ulem}
\usepackage[english]{babel}
\usepackage{color}
\usepackage{hyperref}
\usepackage[T1]{fontenc}
\textheight=9in
\textwidth=7.5in
\headheight=0pt
\headsep=0pt
\topmargin=0in
\oddsidemargin=-0.4in
\evensidemargin=-0.6in
\parindent=0pt
\parsep=1pt
\pagestyle{empty}
\date {}
\makeatother
\begin{document}
\begin{landscape}
% \textit{Dan Kuester's all-leather}
\begin{center}
\begin{minipage}[m]
{1in}\includegraphics[height=0.9in]{../evolution-logo.eps}\hspace{5mm}
\end{minipage}
\hspace{5mm}
\textbf{\Huge{Skedë referimi e shpejtë për Evolution}}
\end{center}
\begin{center}
\begin{multicols}{2}
\section*{Globale}
\begin{tabular*}{4in}{rp{1.5in}}
\textit{\textbf{Përbërës}} & \\
Posta & \textbf{Ctrl+1} \\
Kontakte & \textbf{Ctrl+2} \\
Kalendari & \textbf{Ctrl+3} \\
Aktivitete & \textbf{Ctrl+4} \\
\vspace{1.5mm}
Shënime & \textbf{Ctrl+5} \\
\textit{\textbf{Kontrolle}} & \\
Element i ri në modalitetin aktual & \textbf{Ctrl+N} \\
Shkëmbe fokusin midis panelëve & \textbf{F6} \\
Pastro fushën e kërkimit & \textbf{Shift+Ctrl+Q} \\
Mbyll dritaren & \textbf{Ctrl+W} \\
Hap një dritare të re & \textbf{Shift+Ctrl+W} \\
\vspace{1.5mm}
Mbyll evolution & \textbf{Ctrl+Q} \\
\textit{\textbf{Zgjedhja}} & \\
Printo zgjedhjen & \textbf{Ctrl+P} \\
Ruaj zgjedhjen & \textbf{Ctrl+S} \\
Elemino zgjedhjen & \textbf{Del} ose \textbf{Backspace} \\
Lëviz mesazhe/kontakte tek kartela & \textbf{Shift+Ctrl+V} \\
Kopjo mesazhe/kontakte tek kartela & \textbf{Shift+Ctrl+Y} \\
\end{tabular*}
\section*{Përbërsit e kontakteve/Shënime}
\begin{tabular*}{4in}{rp{1.5in}}
\textit{\textbf{Komandat e përgjithshme}} & \\
Kontakt i ri & \textbf{Shift+Ctrl+C} \\
Listë e re kontaktesh & \textbf{Shift+Ctrl+L} \\
Shënim i ri & \textbf{Shift+Ctrl+O} \\
\end{tabular*}
% {\\ \vspace{5mm} \footnotesize \textit{* denotes the feature may not be implemented yet}}
\section*{Komponenti i postës}
\begin{tabular*}{4in}{rp{1.5in}}
\textit{\textbf{Komandat e përgjithshme}} & \\
Mesazh i ri & \textbf{Shift+Ctrl+M} \\
\vspace{1.5mm}
Dërgo/Merr mesazhe & \textbf{F9} \\
\textit{\textbf{Zgjedhja}} & \\
Apliko filtrat & \textbf{Ctrl+Y} \\
Hap në një dritare të re & \textbf{Return} ose \textbf{Ctrl+O} \\
\vspace{1.5mm}
Përcill zgjedhjen & \textbf{Ctrl+F} \\
\textit{\textbf{Paneli i listës së mesazheve}} & \\
Mesazhi në vijim i palexuar & \textbf{.} ose \textbf{]} \\
\vspace{1.5mm}
Mesazhi paraardhës i palexuar & \textbf{,} ose \textbf{[} \\
\textit{\textbf{Paneli i pamjes së parë}} & \\
Përgjigju dërguesit & \textbf{Ctrl+R} \\
Përgjigju në listë & \textbf{Ctrl+L} \\
Përgjigju të gjithë dërguesve & \textbf{Shift+Ctrl+R} \\
Rrotullo për sipër & \textbf{Backspace} \\
Rrotullo për poshtë & \textbf{Space} \\
\end{tabular*}
\section*{Përbërsit Kalendari/Aktivitete}
\begin{tabular*}{4in}{rp{1.5in}}
\textit{\textbf{Komandat e përgjithshme}} & \\
Takim i ri & \textbf{Shift+Ctrl+A} \\
Mbledhje e re & \textbf{Shift+Ctrl+E} \\
\vspace{1.5mm}
Aktivitet i ri & \textbf{Shift+Ctrl+T} \\
% \vspace{1.5mm}
% Expunge/Purge old schedules & \textbf{Ctrl+E} \\
\textit{\textbf{Lundrimi}} & \\
Shko tek dita e sotme & \textbf{Ctrl+T} \\
Shko tek data & \textbf{Ctrl+G} \\
\end{tabular*}
\end{multicols}
\end{center}
\end{landscape}
\end{document}
| johnnyjacob/evolution | help/quickref/sq/quickref.tex | TeX | gpl-2.0 | 3,964 |
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
/* NetworkManager Connection editor -- Connection editor for NetworkManager
*
* 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.
*
* Copyright 2012 Red Hat, Inc.
*/
#ifndef __PAGE_MASTER_H__
#define __PAGE_MASTER_H__
#include <nm-connection.h>
#include <glib.h>
#include <glib-object.h>
#include "ce-page.h"
#include "connection-helpers.h"
#define CE_TYPE_PAGE_MASTER (ce_page_master_get_type ())
#define CE_PAGE_MASTER(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), CE_TYPE_PAGE_MASTER, CEPageMaster))
#define CE_PAGE_MASTER_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), CE_TYPE_PAGE_MASTER, CEPageMasterClass))
#define CE_IS_PAGE_MASTER(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), CE_TYPE_PAGE_MASTER))
#define CE_IS_PAGE_MASTER_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), CE_TYPE_PAGE_MASTER))
#define CE_PAGE_MASTER_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS ((obj), CE_TYPE_PAGE_MASTER, CEPageMasterClass))
typedef struct {
CEPage parent;
gboolean aggregating;
} CEPageMaster;
typedef struct {
CEPageClass parent;
/* signals */
void (*create_connection) (CEPageMaster *self, NMConnection *connection);
void (*connection_added) (CEPageMaster *self, NMConnection *connection);
void (*connection_removed) (CEPageMaster *self, NMConnection *connection);
/* methods */
void (*add_slave) (CEPageMaster *self, NewConnectionResultFunc result_func);
} CEPageMasterClass;
GType ce_page_master_get_type (void);
gboolean ce_page_master_has_slaves (CEPageMaster *self);
#endif /* __PAGE_MASTER_H__ */
| pavlix/nm-applet | src/connection-editor/page-master.h | C | gpl-2.0 | 2,296 |
/**
* App Control
*
* Central controller attached to the top level <html>
* element
*/
"use strict";
( function ( angular, app ) {
// get user profile data
app.controller( "AppCtrl", [ '$rootScope', '$scope', '$state', 'UserService',
function ( $rootScope, $scope, $state, UserService ) {
//
// bodyClass definitions
//
// in a larger project this would be abstracted to allow for multiple
// classes to easily be added or removed
//
// current state
$rootScope.$on( '$stateChangeStart',
function ( event, toState, toParams, fromState, fromParams ) {
var currentState = toState.name.replace( '.', '-' );
$scope.bodyClass = 'state-' + currentState;
}
);
/**
* Format Avatar
*/
$scope.currentUserAvatar = function ( src, size ) {
return UserService.getCurrentUserAvatar( size );
};
}
] );
} )( angular, SimplySocial ); | Kevinlearynet/angular-trial-app | scripts/controllers/app-controller.js | JavaScript | gpl-2.0 | 901 |
package org.openzal.zal.ldap;
import javax.annotation.Nonnull;
public class LdapServerType
{
@Nonnull
private final com.zimbra.cs.ldap.LdapServerType mLdapServerType;
public final static LdapServerType MASTER = new LdapServerType(com.zimbra.cs.ldap.LdapServerType.MASTER);
public final static LdapServerType REPLICA = new LdapServerType(com.zimbra.cs.ldap.LdapServerType.REPLICA);
public LdapServerType(@Nonnull Object ldapServerType)
{
mLdapServerType = (com.zimbra.cs.ldap.LdapServerType)ldapServerType;
}
protected <T> T toZimbra(Class<T> cls)
{
return cls.cast(mLdapServerType);
}
public boolean isMaster() {
return mLdapServerType.isMaster();
}
}
| ZeXtras/OpenZAL | src/java/org/openzal/zal/ldap/LdapServerType.java | Java | gpl-2.0 | 694 |
package Opsview::Schema::Useragents;
use strict;
use warnings;
use base 'Opsview::DBIx::Class';
__PACKAGE__->load_components(qw/InflateColumn::DateTime Core/);
__PACKAGE__->table( __PACKAGE__->opsviewdb . ".useragents" );
__PACKAGE__->add_columns(
"id",
{
data_type => "VARCHAR",
default_value => undef,
is_nullable => 0,
size => 255
},
"last_update",
{
data_type => "DATETIME",
timezone => "UTC",
default_value => undef,
is_nullable => 0
}
);
__PACKAGE__->set_primary_key( "id" );
# Created by DBIx::Class::Schema::Loader v0.04005 @ 2008-09-17 13:24:37
# DO NOT MODIFY THIS OR ANYTHING ABOVE! md5sum:24E+L+rBEoeFJ5x/7Y4nUQ
#
# AUTHORS:
# Copyright (C) 2003-2013 Opsview Limited. All rights reserved
#
# This file is part of Opsview
#
# Opsview 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.
#
# Opsview 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 Opsview; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#
# You can replace this text with custom content, and it will be preserved on regeneration
1;
| ruo91/opsview-core-3.20131016.0.14175.utf8 | lib/Opsview/Schema/Useragents.pm | Perl | gpl-2.0 | 1,671 |
'use strict';
/**
* @ngdoc function
* @name quickNewsApp.controller:CbcCtrl
* @description
* # CbcCtrl
* Controller of the quickNewsApp
*/
angular.module('quickNewsApp')
.controller('CbcCtrl', function ($scope, $http) {
this.awesomeThings = [
'HTML5 Boilerplate',
'AngularJS',
'Karma'
];
$scope.postLimit = 10;
$scope.showMorePosts = function() {
$scope.postLimit += 5;
};
$scope.isSet = function(checkTab) {
return this.tab === checkTab;
};
$scope.setTab = function(activeTab) {
this.tab = activeTab;
$scope.postLimit = 10;
$scope.getFeed(activeTab);
};
$scope.getActiveTab = function() {
return this.tab;
};
$scope.getFeed = function(category) {
/*jshint unused: false */
$scope.loading = true;
var url = '//quicknews.amanuppal.ca:5000/cbc?url=' + category;
$http.get(url)
.success(function(data, status, headers, config) {
$scope.entries = data.items;
console.log($scope.entries);
$scope.numEntries = Object.keys($scope.entries).length;
$scope.loading = false;
})
.error(function(data, status, headers, config) {
console.log('Error loading feed: ' + url + ', status: ' + status);
});
};
});
| amtux/quick-news | app/scripts/controllers/cbc.js | JavaScript | gpl-2.0 | 1,204 |
package org.hectordam.proyectohector;
import java.util.ArrayList;
import org.hectordam.proyectohector.R;
import org.hectordam.proyectohector.base.Bar;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
public class Mapa extends FragmentActivity implements LocationListener,ConnectionCallbacks, OnConnectionFailedListener{
private GoogleMap mapa;
private LocationClient locationClient;
private CameraUpdate camara;
private static final LocationRequest LOC_REQUEST = LocationRequest.create()
.setInterval(5000)
.setFastestInterval(16)
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mapa);
try {
MapsInitializer.initialize(this);
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
mapa = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
ArrayList<Bar> bares = getIntent().getParcelableArrayListExtra("bares");
if (bares != null) {
//marcarBares(bares);
}
mapa.setMyLocationEnabled(true);
configuraLocalizador();
camara = CameraUpdateFactory.newLatLng(new LatLng(41.6561, -0.8773));
mapa.moveCamera(camara);
mapa.animateCamera(CameraUpdateFactory.zoomTo(11.0f), 2000, null);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.mapa, menu);
return true;
}
/**
* Añade las marcas de todas las gasolineras
* @param gasolineras
*/
private void marcarBares(ArrayList<Bar> bares) {
if (bares.size() > 0) {
for (Bar bar : bares) {
mapa.addMarker(new MarkerOptions()
.position(new LatLng(bar.getLatitud(), bar.getLongitud()))
.title(bar.getNombre()));
}
}
}
/**
* Se muestra la Activity
*/
@Override
protected void onStart() {
super.onStart();
locationClient.connect();
}
@Override
protected void onStop() {
super.onStop();
locationClient.disconnect();
}
private void configuraLocalizador() {
if (locationClient == null) {
locationClient = new LocationClient(this, this, this);
}
}
@Override
public void onConnected(Bundle arg0) {
locationClient.requestLocationUpdates(LOC_REQUEST, this);
}
@Override
public void onConnectionFailed(ConnectionResult arg0) {
}
@Override
public void onDisconnected() {
}
@Override
public void onLocationChanged(Location arg0) {
}
}
| gilmh/PracticaAndroid | AgenBar/src/org/hectordam/proyectohector/Mapa.java | Java | gpl-2.0 | 3,630 |
/*
* mms_ts.c - Touchscreen driver for Melfas MMS-series touch controllers
*
* Copyright (C) 2011 Google Inc.
* Author: Dima Zavin <[email protected]>
* Simon Wilson <[email protected]>
*
* ISP reflashing code based on original code from Melfas.
*
* 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.
*
*/
#define DEBUG
/* #define VERBOSE_DEBUG */
/*#define SEC_TSP_DEBUG*/
/* #define SEC_TSP_VERBOSE_DEBUG */
/* #define FORCE_FW_FLASH */
/* #define FORCE_FW_PASS */
/* #define ESD_DEBUG */
#define SEC_TSP_FACTORY_TEST
#define SEC_TSP_FW_UPDATE
#define TSP_BUF_SIZE 1024
#define FAIL -1
#include <linux/delay.h>
#include <linux/earlysuspend.h>
#include <linux/firmware.h>
#include <linux/gpio.h>
#include <linux/i2c.h>
#include <linux/init.h>
#include <linux/input.h>
#include <linux/input/mt.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/module.h>
#include <linux/mutex.h>
#include <linux/slab.h>
#include <mach/gpio.h>
#include <linux/uaccess.h>
#include <mach/cpufreq.h>
#include <mach/dev.h>
#include <linux/platform_data/mms_ts.h>
#include <asm/unaligned.h>
#define MAX_FINGERS 10
#define MAX_WIDTH 30
#define MAX_PRESSURE 255
#define MAX_ANGLE 90
#define MIN_ANGLE -90
/* Registers */
#define MMS_MODE_CONTROL 0x01
#define MMS_XYRES_HI 0x02
#define MMS_XRES_LO 0x03
#define MMS_YRES_LO 0x04
#define MMS_INPUT_EVENT_PKT_SZ 0x0F
#define MMS_INPUT_EVENT0 0x10
#define FINGER_EVENT_SZ 8
#define MMS_TSP_REVISION 0xF0
#define MMS_HW_REVISION 0xF1
#define MMS_COMPAT_GROUP 0xF2
#define MMS_FW_VERSION 0xF3
enum {
ISP_MODE_FLASH_ERASE = 0x59F3,
ISP_MODE_FLASH_WRITE = 0x62CD,
ISP_MODE_FLASH_READ = 0x6AC9,
};
/* each address addresses 4-byte words */
#define ISP_MAX_FW_SIZE (0x1F00 * 4)
#define ISP_IC_INFO_ADDR 0x1F00
#ifdef SEC_TSP_FW_UPDATE
#define WORD_SIZE 4
#define ISC_PKT_SIZE 1029
#define ISC_PKT_DATA_SIZE 1024
#define ISC_PKT_HEADER_SIZE 3
#define ISC_PKT_NUM 31
#define ISC_ENTER_ISC_CMD 0x5F
#define ISC_ENTER_ISC_DATA 0x01
#define ISC_CMD 0xAE
#define ISC_ENTER_UPDATE_DATA 0x55
#define ISC_ENTER_UPDATE_DATA_LEN 9
#define ISC_DATA_WRITE_SUB_CMD 0xF1
#define ISC_EXIT_ISC_SUB_CMD 0x0F
#define ISC_EXIT_ISC_SUB_CMD2 0xF0
#define ISC_CHECK_STATUS_CMD 0xAF
#define ISC_CONFIRM_CRC 0x03
#define ISC_DEFAULT_CRC 0xFFFF
#endif
#ifdef SEC_TSP_FACTORY_TEST
#define TX_NUM 26
#define RX_NUM 14
#define NODE_NUM 364 /* 26x14 */
/* VSC(Vender Specific Command) */
#define MMS_VSC_CMD 0xB0 /* vendor specific command */
#define MMS_VSC_MODE 0x1A /* mode of vendor */
#define MMS_VSC_CMD_ENTER 0X01
#define MMS_VSC_CMD_CM_DELTA 0X02
#define MMS_VSC_CMD_CM_ABS 0X03
#define MMS_VSC_CMD_EXIT 0X05
#define MMS_VSC_CMD_INTENSITY 0X04
#define MMS_VSC_CMD_RAW 0X06
#define MMS_VSC_CMD_REFER 0X07
#define TSP_CMD_STR_LEN 32
#define TSP_CMD_RESULT_STR_LEN 512
#define TSP_CMD_PARAM_NUM 8
#endif /* SEC_TSP_FACTORY_TEST */
/* Touch booster */
#if defined(CONFIG_EXYNOS4_CPUFREQ) &&\
defined(CONFIG_BUSFREQ_OPP)
#define TOUCH_BOOSTER 1
#define TOUCH_BOOSTER_OFF_TIME 100
#define TOUCH_BOOSTER_CHG_TIME 200
#else
#define TOUCH_BOOSTER 0
#endif
struct device *sec_touchscreen;
static struct device *bus_dev;
int touch_is_pressed = 0;
#define ISC_DL_MODE 1
/* 4.8" OCTA LCD */
#define FW_VERSION_4_8 0xBD
#define MAX_FW_PATH 255
#define TSP_FW_FILENAME "melfas_fw.bin"
#if ISC_DL_MODE /* ISC_DL_MODE start */
/*
* Default configuration of ISC mode
*/
#define DEFAULT_SLAVE_ADDR 0x48
#define SECTION_NUM 4
#define SECTION_NAME_LEN 5
#define PAGE_HEADER 3
#define PAGE_DATA 1024
#define PAGE_TAIL 2
#define PACKET_SIZE (PAGE_HEADER + PAGE_DATA + PAGE_TAIL)
#define TS_WRITE_REGS_LEN 1030
#define TIMEOUT_CNT 10
#define STRING_BUF_LEN 100
/* State Registers */
#define MIP_ADDR_INPUT_INFORMATION 0x01
#define ISC_ADDR_VERSION 0xE1
#define ISC_ADDR_SECTION_PAGE_INFO 0xE5
/* Config Update Commands */
#define ISC_CMD_ENTER_ISC 0x5F
#define ISC_CMD_ENTER_ISC_PARA1 0x01
#define ISC_CMD_UPDATE_MODE 0xAE
#define ISC_SUBCMD_ENTER_UPDATE 0x55
#define ISC_SUBCMD_DATA_WRITE 0XF1
#define ISC_SUBCMD_LEAVE_UPDATE_PARA1 0x0F
#define ISC_SUBCMD_LEAVE_UPDATE_PARA2 0xF0
#define ISC_CMD_CONFIRM_STATUS 0xAF
#define ISC_STATUS_UPDATE_MODE 0x01
#define ISC_STATUS_CRC_CHECK_SUCCESS 0x03
#define ISC_CHAR_2_BCD(num) (((num/10)<<4) + (num%10))
#define ISC_MAX(x, y) (((x) > (y)) ? (x) : (y))
static const char section_name[SECTION_NUM][SECTION_NAME_LEN] = {
"BOOT", "CORE", "PRIV", "PUBL"
};
static const unsigned char crc0_buf[31] = {
0x1D, 0x2C, 0x05, 0x34, 0x95, 0xA4, 0x8D, 0xBC,
0x59, 0x68, 0x41, 0x70, 0xD1, 0xE0, 0xC9, 0xF8,
0x3F, 0x0E, 0x27, 0x16, 0xB7, 0x86, 0xAF, 0x9E,
0x7B, 0x4A, 0x63, 0x52, 0xF3, 0xC2, 0xEB
};
static const unsigned char crc1_buf[31] = {
0x1E, 0x9C, 0xDF, 0x5D, 0x76, 0xF4, 0xB7, 0x35,
0x2A, 0xA8, 0xEB, 0x69, 0x42, 0xC0, 0x83, 0x01,
0x04, 0x86, 0xC5, 0x47, 0x6C, 0xEE, 0xAD, 0x2F,
0x30, 0xB2, 0xF1, 0x73, 0x58, 0xDA, 0x99
};
static tISCFWInfo_t mbin_info[SECTION_NUM];
static tISCFWInfo_t ts_info[SECTION_NUM]; /* read F/W version from IC */
static bool section_update_flag[SECTION_NUM];
const struct firmware *fw_mbin[SECTION_NUM];
static unsigned char g_wr_buf[1024 + 3 + 2];
#endif
enum fw_flash_mode {
ISP_FLASH,
ISC_FLASH,
};
enum {
BUILT_IN = 0,
UMS,
REQ_FW,
};
struct tsp_callbacks {
void (*inform_charger)(struct tsp_callbacks *tsp_cb, bool mode);
};
struct mms_ts_info {
struct i2c_client *client;
struct input_dev *input_dev;
char phys[32];
int max_x;
int max_y;
bool invert_x;
bool invert_y;
const u8 *config_fw_version;
int irq;
int (*power) (bool on);
struct melfas_tsi_platform_data *pdata;
struct early_suspend early_suspend;
/* protects the enabled flag */
struct mutex lock;
bool enabled;
void (*register_cb)(void *);
struct tsp_callbacks callbacks;
bool ta_status;
bool noise_mode;
unsigned char finger_state[MAX_FINGERS];
#if defined(SEC_TSP_FW_UPDATE)
u8 fw_update_state;
#endif
u8 fw_ic_ver;
enum fw_flash_mode fw_flash_mode;
#if TOUCH_BOOSTER
struct delayed_work work_dvfs_off;
struct delayed_work work_dvfs_chg;
bool dvfs_lock_status;
int cpufreq_level;
struct mutex dvfs_lock;
#endif
#if defined(SEC_TSP_FACTORY_TEST)
struct list_head cmd_list_head;
u8 cmd_state;
char cmd[TSP_CMD_STR_LEN];
int cmd_param[TSP_CMD_PARAM_NUM];
char cmd_result[TSP_CMD_RESULT_STR_LEN];
struct mutex cmd_lock;
bool cmd_is_running;
unsigned int reference[NODE_NUM];
unsigned int raw[NODE_NUM]; /* CM_ABS */
unsigned int inspection[NODE_NUM];/* CM_DELTA */
unsigned int intensity[NODE_NUM];
bool ft_flag;
#endif /* SEC_TSP_FACTORY_TEST */
};
struct mms_fw_image {
__le32 hdr_len;
__le32 data_len;
__le32 fw_ver;
__le32 hdr_ver;
u8 data[0];
} __packed;
#ifdef CONFIG_HAS_EARLYSUSPEND
static void mms_ts_early_suspend(struct early_suspend *h);
static void mms_ts_late_resume(struct early_suspend *h);
#endif
#if TOUCH_BOOSTER
static bool dvfs_lock_status = false;
static bool press_status = false;
#endif
#if defined(SEC_TSP_FACTORY_TEST)
#define TSP_CMD(name, func) .cmd_name = name, .cmd_func = func
struct tsp_cmd {
struct list_head list;
const char *cmd_name;
void (*cmd_func)(void *device_data);
};
static void fw_update(void *device_data);
static void get_fw_ver_bin(void *device_data);
static void get_fw_ver_ic(void *device_data);
static void get_config_ver(void *device_data);
static void get_threshold(void *device_data);
static void module_off_master(void *device_data);
static void module_on_master(void *device_data);
static void module_off_slave(void *device_data);
static void module_on_slave(void *device_data);
static void get_chip_vendor(void *device_data);
static void get_chip_name(void *device_data);
static void get_reference(void *device_data);
static void get_cm_abs(void *device_data);
static void get_cm_delta(void *device_data);
static void get_intensity(void *device_data);
static void get_x_num(void *device_data);
static void get_y_num(void *device_data);
static void run_reference_read(void *device_data);
static void run_cm_abs_read(void *device_data);
static void run_cm_delta_read(void *device_data);
static void run_intensity_read(void *device_data);
static void not_support_cmd(void *device_data);
struct tsp_cmd tsp_cmds[] = {
{TSP_CMD("fw_update", fw_update),},
{TSP_CMD("get_fw_ver_bin", get_fw_ver_bin),},
{TSP_CMD("get_fw_ver_ic", get_fw_ver_ic),},
{TSP_CMD("get_config_ver", get_config_ver),},
{TSP_CMD("get_threshold", get_threshold),},
/* {TSP_CMD("module_off_master", module_off_master),},
{TSP_CMD("module_on_master", module_on_master),},
{TSP_CMD("module_off_slave", not_support_cmd),},
{TSP_CMD("module_on_slave", not_support_cmd),}, */
{TSP_CMD("get_chip_vendor", get_chip_vendor),},
{TSP_CMD("get_chip_name", get_chip_name),},
{TSP_CMD("get_x_num", get_x_num),},
{TSP_CMD("get_y_num", get_y_num),},
{TSP_CMD("get_reference", get_reference),},
{TSP_CMD("get_cm_abs", get_cm_abs),},
{TSP_CMD("get_cm_delta", get_cm_delta),},
{TSP_CMD("get_intensity", get_intensity),},
{TSP_CMD("run_reference_read", run_reference_read),},
{TSP_CMD("run_cm_abs_read", run_cm_abs_read),},
{TSP_CMD("run_cm_delta_read", run_cm_delta_read),},
{TSP_CMD("run_intensity_read", run_intensity_read),},
{TSP_CMD("not_support_cmd", not_support_cmd),},
};
#endif
#if TOUCH_BOOSTER
static void change_dvfs_lock(struct work_struct *work)
{
struct mms_ts_info *info = container_of(work,
struct mms_ts_info, work_dvfs_chg.work);
int ret;
mutex_lock(&info->dvfs_lock);
ret = dev_lock(bus_dev, sec_touchscreen, 267160); /* 266 Mhz setting */
if (ret < 0)
pr_err("%s: dev change bud lock failed(%d)\n",\
__func__, __LINE__);
else
pr_info("[TSP] change_dvfs_lock");
mutex_unlock(&info->dvfs_lock);
}
static void set_dvfs_off(struct work_struct *work)
{
struct mms_ts_info *info = container_of(work,
struct mms_ts_info, work_dvfs_off.work);
int ret;
mutex_lock(&info->dvfs_lock);
ret = dev_unlock(bus_dev, sec_touchscreen);
if (ret < 0)
pr_err("%s: dev unlock failed(%d)\n",
__func__, __LINE__);
exynos_cpufreq_lock_free(DVFS_LOCK_ID_TSP);
info->dvfs_lock_status = false;
pr_info("[TSP] DVFS Off!");
mutex_unlock(&info->dvfs_lock);
}
static void set_dvfs_lock(struct mms_ts_info *info, uint32_t on)
{
int ret;
mutex_lock(&info->dvfs_lock);
if (info->cpufreq_level <= 0) {
ret = exynos_cpufreq_get_level(800000, &info->cpufreq_level);
if (ret < 0)
pr_err("[TSP] exynos_cpufreq_get_level error");
goto out;
}
if (on == 0) {
if (info->dvfs_lock_status) {
cancel_delayed_work(&info->work_dvfs_chg);
schedule_delayed_work(&info->work_dvfs_off,
msecs_to_jiffies(TOUCH_BOOSTER_OFF_TIME));
}
} else if (on == 1) {
cancel_delayed_work(&info->work_dvfs_off);
if (!info->dvfs_lock_status) {
ret = dev_lock(bus_dev, sec_touchscreen, 400200);
if (ret < 0) {
pr_err("%s: dev lock failed(%d)\n",\
__func__, __LINE__);
}
ret = exynos_cpufreq_lock(DVFS_LOCK_ID_TSP,
info->cpufreq_level);
if (ret < 0)
pr_err("%s: cpu lock failed(%d)\n",\
__func__, __LINE__);
schedule_delayed_work(&info->work_dvfs_chg,
msecs_to_jiffies(TOUCH_BOOSTER_CHG_TIME));
info->dvfs_lock_status = true;
pr_info("[TSP] DVFS On![%d]", info->cpufreq_level);
}
} else if (on == 2) {
cancel_delayed_work(&info->work_dvfs_off);
cancel_delayed_work(&info->work_dvfs_chg);
schedule_work(&info->work_dvfs_off.work);
}
out:
mutex_unlock(&info->dvfs_lock);
}
#endif
static inline void mms_pwr_on_reset(struct mms_ts_info *info)
{
struct i2c_adapter *adapter = to_i2c_adapter(info->client->dev.parent);
if (!info->pdata->mux_fw_flash) {
dev_info(&info->client->dev,
"missing platform data, can't do power-on-reset\n");
return;
}
i2c_lock_adapter(adapter);
info->pdata->mux_fw_flash(true);
info->pdata->power(false);
gpio_direction_output(info->pdata->gpio_sda, 0);
gpio_direction_output(info->pdata->gpio_scl, 0);
gpio_direction_output(info->pdata->gpio_int, 0);
msleep(50);
info->pdata->power(true);
msleep(200);
info->pdata->mux_fw_flash(false);
i2c_unlock_adapter(adapter);
/* TODO: Seems long enough for the firmware to boot.
* Find the right value */
msleep(250);
}
static void release_all_fingers(struct mms_ts_info *info)
{
struct i2c_client *client = info->client;
int i;
pr_debug(KERN_DEBUG "[TSP] %s\n", __func__);
for (i = 0; i < MAX_FINGERS; i++) {
if (info->finger_state[i] == 1) {
dev_notice(&client->dev, "finger %d up(force)\n", i);
}
info->finger_state[i] = 0;
input_mt_slot(info->input_dev, i);
input_mt_report_slot_state(info->input_dev, MT_TOOL_FINGER,
false);
}
input_sync(info->input_dev);
#if TOUCH_BOOSTER
set_dvfs_lock(info, 2);
pr_info("[TSP] dvfs_lock free.\n ");
#endif
}
static void mms_set_noise_mode(struct mms_ts_info *info)
{
struct i2c_client *client = info->client;
if (!(info->noise_mode && info->enabled))
return;
dev_notice(&client->dev, "%s\n", __func__);
if (info->ta_status) {
dev_notice(&client->dev, "noise_mode & TA connect!!!\n");
i2c_smbus_write_byte_data(info->client, 0x30, 0x1);
} else {
dev_notice(&client->dev, "noise_mode & TA disconnect!!!\n");
i2c_smbus_write_byte_data(info->client, 0x30, 0x2);
}
}
static void reset_mms_ts(struct mms_ts_info *info)
{
struct i2c_client *client = info->client;
if (info->enabled == false)
return;
dev_notice(&client->dev, "%s++\n", __func__);
disable_irq_nosync(info->irq);
info->enabled = false;
touch_is_pressed = 0;
release_all_fingers(info);
mms_pwr_on_reset(info);
enable_irq(info->irq);
info->enabled = true;
if (info->ta_status) {
dev_notice(&client->dev, "TA connect!!!\n");
i2c_smbus_write_byte_data(info->client, 0x33, 0x1);
} else {
dev_notice(&client->dev, "TA disconnect!!!\n");
i2c_smbus_write_byte_data(info->client, 0x33, 0x2);
}
mms_set_noise_mode(info);
dev_notice(&client->dev, "%s--\n", __func__);
}
static void melfas_ta_cb(struct tsp_callbacks *cb, bool ta_status)
{
struct mms_ts_info *info =
container_of(cb, struct mms_ts_info, callbacks);
struct i2c_client *client = info->client;
dev_notice(&client->dev, "%s\n", __func__);
info->ta_status = ta_status;
if (info->enabled) {
if (info->ta_status) {
dev_notice(&client->dev, "TA connect!!!\n");
i2c_smbus_write_byte_data(info->client, 0x33, 0x1);
} else {
dev_notice(&client->dev, "TA disconnect!!!\n");
i2c_smbus_write_byte_data(info->client, 0x33, 0x2);
}
mms_set_noise_mode(info);
}
}
static irqreturn_t mms_ts_interrupt(int irq, void *dev_id)
{
struct mms_ts_info *info = dev_id;
struct i2c_client *client = info->client;
u8 buf[MAX_FINGERS * FINGER_EVENT_SZ] = { 0 };
int ret;
int i;
int sz;
u8 reg = MMS_INPUT_EVENT0;
struct i2c_msg msg[] = {
{
.addr = client->addr,
.flags = 0,
.buf = ®,
.len = 1,
}, {
.addr = client->addr,
.flags = I2C_M_RD,
.buf = buf,
},
};
sz = i2c_smbus_read_byte_data(client, MMS_INPUT_EVENT_PKT_SZ);
if (sz < 0) {
dev_err(&client->dev, "%s bytes=%d\n", __func__, sz);
for (i = 0; i < 50; i++) {
sz = i2c_smbus_read_byte_data(client,
MMS_INPUT_EVENT_PKT_SZ);
if (sz > 0)
break;
}
if (i == 50) {
dev_dbg(&client->dev, "i2c failed... reset!!\n");
reset_mms_ts(info);
goto out;
}
}
/* BUG_ON(sz > MAX_FINGERS*FINGER_EVENT_SZ); */
if (sz == 0)
goto out;
if (sz > MAX_FINGERS*FINGER_EVENT_SZ) {
dev_err(&client->dev, "[TSP] abnormal data inputed.\n");
goto out;
}
msg[1].len = sz;
ret = i2c_transfer(client->adapter, msg, ARRAY_SIZE(msg));
if (ret != ARRAY_SIZE(msg)) {
dev_err(&client->dev,
"failed to read %d bytes of touch data (%d)\n",
sz, ret);
goto out;
}
#if defined(VERBOSE_DEBUG)
print_hex_dump(KERN_DEBUG, "mms_ts raw: ",
DUMP_PREFIX_OFFSET, 32, 1, buf, sz, false);
#endif
if (buf[0] == 0x0F) { /* ESD */
dev_dbg(&client->dev, "ESD DETECT.... reset!!\n");
reset_mms_ts(info);
goto out;
}
if (buf[0] == 0x0E) { /* NOISE MODE */
dev_dbg(&client->dev, "[TSP] noise mode enter!!\n");
info->noise_mode = 1 ;
mms_set_noise_mode(info);
goto out;
}
for (i = 0; i < sz; i += FINGER_EVENT_SZ) {
u8 *tmp = &buf[i];
int id = (tmp[0] & 0xf) - 1;
int x = tmp[2] | ((tmp[1] & 0xf) << 8);
int y = tmp[3] | (((tmp[1] >> 4) & 0xf) << 8);
int angle = (tmp[5] >= 127) ? (-(256 - tmp[5])) : tmp[5];
int palm = (tmp[0] & 0x10) >> 4;
if (info->invert_x) {
x = info->max_x - x;
if (x < 0)
x = 0;
}
if (info->invert_y) {
y = info->max_y - y;
if (y < 0)
y = 0;
}
if (id >= MAX_FINGERS) {
dev_notice(&client->dev, \
"finger id error [%d]\n", id);
reset_mms_ts(info);
goto out;
}
if ((tmp[0] & 0x80) == 0) {
#if defined(SEC_TSP_DEBUG)
dev_dbg(&client->dev,
"finger id[%d]: x=%d y=%d p=%d w=%d major=%d minor=%d angle=%d palm=%d\n",
id, x, y, tmp[5], tmp[4], tmp[6], tmp[7]
, angle, palm);
#else
if (info->finger_state[id] != 0) {
dev_notice(&client->dev,
"finger [%d] up, palm %d\n", id, palm);
}
#endif
input_mt_slot(info->input_dev, id);
input_mt_report_slot_state(info->input_dev,
MT_TOOL_FINGER, false);
info->finger_state[id] = 0;
continue;
}
input_mt_slot(info->input_dev, id);
input_mt_report_slot_state(info->input_dev,
MT_TOOL_FINGER, true);
input_report_abs(info->input_dev, ABS_MT_WIDTH_MAJOR, tmp[4]);
input_report_abs(info->input_dev, ABS_MT_POSITION_X, x);
input_report_abs(info->input_dev, ABS_MT_POSITION_Y, y);
input_report_abs(info->input_dev, ABS_MT_TOUCH_MAJOR, tmp[6]);
input_report_abs(info->input_dev, ABS_MT_TOUCH_MINOR, tmp[7]);
input_report_abs(info->input_dev, ABS_MT_ANGLE, angle);
input_report_abs(info->input_dev, ABS_MT_PALM, palm);
#if defined(SEC_TSP_DEBUG)
if (info->finger_state[id] == 0) {
info->finger_state[id] = 1;
dev_dbg(&client->dev,
"finger id[%d]: x=%d y=%d w=%d major=%d minor=%d angle=%d palm=%d\n",
id, x, y, tmp[4], tmp[6], tmp[7]
, angle, palm);
if (finger_event_sz == 10)
dev_dbg(&client->dev, \
"pressure = %d\n", tmp[8]);
}
#else
if (info->finger_state[id] == 0) {
info->finger_state[id] = 1;
dev_notice(&client->dev,
"finger [%d] down, palm %d\n", id, palm);
}
#endif
}
input_sync(info->input_dev);
touch_is_pressed = 0;
for (i = 0; i < MAX_FINGERS; i++) {
if (info->finger_state[i] == 1)
touch_is_pressed++;
}
#if TOUCH_BOOSTER
set_dvfs_lock(info, !!touch_is_pressed);
#endif
out:
return IRQ_HANDLED;
}
int get_tsp_status(void)
{
return touch_is_pressed;
}
EXPORT_SYMBOL(get_tsp_status);
#if ISC_DL_MODE
static int mms100_i2c_read(struct i2c_client *client,
u16 addr, u16 length, u8 *value)
{
struct i2c_adapter *adapter = client->adapter;
struct i2c_msg msg;
int ret = -1;
msg.addr = client->addr;
msg.flags = 0x00;
msg.len = 1;
msg.buf = (u8 *) &addr;
ret = i2c_transfer(adapter, &msg, 1);
if (ret >= 0) {
msg.addr = client->addr;
msg.flags = I2C_M_RD;
msg.len = length;
msg.buf = (u8 *) value;
ret = i2c_transfer(adapter, &msg, 1);
}
if (ret < 0)
pr_err("[TSP] : read error : [%d]", ret);
return ret;
}
static int mms100_reset(struct mms_ts_info *info)
{
info->pdata->power(false);
msleep(30);
info->pdata->power(true);
msleep(300);
return ISC_SUCCESS;
}
/*
static int mms100_check_operating_mode(struct i2c_client *_client,
const int _error_code)
{
int ret;
unsigned char rd_buf = 0x00;
unsigned char count = 0;
if(_client == NULL)
pr_err("[TSP ISC] _client is null");
ret = mms100_i2c_read(_client, ISC_ADDR_VERSION, 1, &rd_buf);
if (ret<0) {
pr_info("[TSP ISC] %s,%d: i2c read fail[%d]\n",
__func__, __LINE__, ret);
return _error_code;
}
return ISC_SUCCESS;
}
*/
static int mms100_get_version_info(struct i2c_client *_client)
{
int i, ret;
unsigned char rd_buf[8];
/* config version brust read (core, private, public) */
ret = mms100_i2c_read(_client, ISC_ADDR_VERSION, 4, rd_buf);
if (ret < 0) {
pr_info("[TSP ISC] %s,%d: i2c read fail[%d]\n",
__func__, __LINE__, ret);
return ISC_I2C_ERROR;
}
for (i = 0; i < SECTION_NUM; i++)
ts_info[i].version = rd_buf[i];
ts_info[SEC_CORE].compatible_version =
ts_info[SEC_BOOTLOADER].version;
ts_info[SEC_PRIVATE_CONFIG].compatible_version =
ts_info[SEC_PUBLIC_CONFIG].compatible_version =
ts_info[SEC_CORE].version;
ret = mms100_i2c_read(_client, ISC_ADDR_SECTION_PAGE_INFO, 8, rd_buf);
if (ret < 0) {
pr_info("[TSP ISC] %s,%d: i2c read fail[%d]\n",
__func__, __LINE__, ret);
return ISC_I2C_ERROR;
}
for (i = 0; i < SECTION_NUM; i++) {
ts_info[i].start_addr = rd_buf[i];
ts_info[i].end_addr = rd_buf[i + SECTION_NUM];
}
for (i = 0; i < SECTION_NUM; i++) {
pr_info("TS : Section(%d) version: 0x%02X\n",
i, ts_info[i].version);
pr_info("TS : Section(%d) Start Address: 0x%02X\n",
i, ts_info[i].start_addr);
pr_info("TS : Section(%d) End Address: 0x%02X\n",
i, ts_info[i].end_addr);
pr_info("TS : Section(%d) Compatibility: 0x%02X\n",
i, ts_info[i].compatible_version);
}
return ISC_SUCCESS;
}
static int mms100_seek_section_info(void)
{
int i;
char str_buf[STRING_BUF_LEN];
char name_buf[SECTION_NAME_LEN];
int version;
int page_num;
const unsigned char *buf;
int next_ptr;
for (i = 0; i < SECTION_NUM; i++) {
if (fw_mbin[i] == NULL) {
buf = NULL;
pr_info("[TSP ISC] fw_mbin[%d]->data is NULL", i);
} else {
buf = fw_mbin[i]->data;
}
if (buf == NULL) {
mbin_info[i].version = ts_info[i].version;
mbin_info[i].compatible_version =
ts_info[i].compatible_version;
mbin_info[i].start_addr = ts_info[i].start_addr;
mbin_info[i].end_addr = ts_info[i].end_addr;
} else {
next_ptr = 0;
do {
sscanf(buf + next_ptr, "%s", str_buf);
next_ptr += strlen(str_buf) + 1;
} while (!strstr(str_buf, "SECTION_NAME"));
sscanf(buf + next_ptr, "%s%s", str_buf, name_buf);
if (strncmp(section_name[i], name_buf,
SECTION_NAME_LEN))
return ISC_FILE_FORMAT_ERROR;
do {
sscanf(buf + next_ptr, "%s", str_buf);
next_ptr += strlen(str_buf) + 1;
} while (!strstr(str_buf, "SECTION_VERSION"));
sscanf(buf + next_ptr, "%s%d", str_buf, &version);
mbin_info[i].version = ISC_CHAR_2_BCD(version);
do {
sscanf(buf + next_ptr, "%s", str_buf);
next_ptr += strlen(str_buf) + 1;
} while (!strstr(str_buf, "START_PAGE_ADDR"));
sscanf(buf + next_ptr, "%s%d", str_buf, &page_num);
mbin_info[i].start_addr = page_num;
do {
sscanf(buf + next_ptr, "%s", str_buf);
next_ptr += strlen(str_buf) + 1;
} while (!strstr(str_buf, "END_PAGE_ADDR"));
sscanf(buf + next_ptr, "%s%d", str_buf, &page_num);
mbin_info[i].end_addr = page_num;
do {
sscanf(buf + next_ptr, "%s", str_buf);
next_ptr += strlen(str_buf) + 1;
} while (!strstr(str_buf, "COMPATIBLE_VERSION"));
sscanf(buf + next_ptr, "%s%d", str_buf, &version);
mbin_info[i].compatible_version =
ISC_CHAR_2_BCD(version);
do {
sscanf(buf + next_ptr, "%s", str_buf);
next_ptr += strlen(str_buf) + 1;
} while (!strstr(str_buf, "[Binary]"));
if (mbin_info[i].version == 0xFF)
return ISC_FILE_FORMAT_ERROR;
}
}
for (i = 0; i < SECTION_NUM; i++) {
pr_info("[TSP ISC] MBin : Section(%d) Version: 0x%02X\n",
i, mbin_info[i].version);
pr_info("[TSP ISC] MBin : Section(%d) Start Address: 0x%02X\n",
i, mbin_info[i].start_addr);
pr_info("[TSP ISC] MBin : Section(%d) End Address: 0x%02X\n",
i, mbin_info[i].end_addr);
pr_info("[TSP ISC] MBin : Section(%d) Compatibility: 0x%02X\n",
i, mbin_info[i].compatible_version);
}
return ISC_SUCCESS;
}
static eISCRet_t mms100_compare_version_info(struct i2c_client *_client)
{
int i, ret;
unsigned char expected_compatibility[SECTION_NUM];
if (mms100_get_version_info(_client) != ISC_SUCCESS)
return ISC_I2C_ERROR;
ret = mms100_seek_section_info();
/* Check update areas , 0 : bootloader 1: core 2: private 3: public */
for (i = 0; i < SECTION_NUM; i++) {
if ((mbin_info[i].version == 0) ||
(mbin_info[i].version != ts_info[i].version)) {
section_update_flag[i] = true;
pr_info("[TSP ISC] [%d] section will be updated!", i);
}
}
section_update_flag[0] = false;
pr_info("[TSP ISC] [%d] [%d] [%d]", section_update_flag[1],
section_update_flag[2], section_update_flag[3]);
if (section_update_flag[SEC_BOOTLOADER]) {
expected_compatibility[SEC_CORE] =
mbin_info[SEC_BOOTLOADER].version;
} else {
expected_compatibility[SEC_CORE] =
ts_info[SEC_BOOTLOADER].version;
}
if (section_update_flag[SEC_CORE]) {
expected_compatibility[SEC_PUBLIC_CONFIG] =
expected_compatibility[SEC_PRIVATE_CONFIG] =
mbin_info[SEC_CORE].version;
} else {
expected_compatibility[SEC_PUBLIC_CONFIG] =
expected_compatibility[SEC_PRIVATE_CONFIG] =
ts_info[SEC_CORE].version;
}
for (i = SEC_CORE; i < SEC_PUBLIC_CONFIG; i++) {
if (section_update_flag[i]) {
pr_info("[TSP ISC] section_update_flag(%d), 0x%02x, 0x%02x\n",
i, expected_compatibility[i],
mbin_info[i].compatible_version);
if (expected_compatibility[i] !=
mbin_info[i].compatible_version)
return ISC_COMPATIVILITY_ERROR;
} else {
pr_info("[TSP ISC] !section_update_flag(%d), 0x%02x, 0x%02x\n",
i, expected_compatibility[i],
ts_info[i].compatible_version);
if (expected_compatibility[i] !=
ts_info[i].compatible_version)
return ISC_COMPATIVILITY_ERROR;
}
}
return ISC_SUCCESS;
}
static int mms100_enter_ISC_mode(struct i2c_client *_client)
{
int ret;
unsigned char wr_buf[2];
pr_info("[TSP ISC] %s\n", __func__);
wr_buf[0] = ISC_CMD_ENTER_ISC;
wr_buf[1] = ISC_CMD_ENTER_ISC_PARA1;
ret = i2c_master_send(_client, wr_buf, 2);
if (ret < 0) {
pr_info("[TSP ISC] %s,%d: i2c write fail[%d]\n",
__func__, __LINE__, ret);
return ISC_I2C_ERROR;
}
msleep(50);
return ISC_SUCCESS;
}
static int mms100_enter_config_update(struct i2c_client *_client)
{
int ret;
unsigned char wr_buf[10] = {0,};
unsigned char rd_buf;
wr_buf[0] = ISC_CMD_UPDATE_MODE;
wr_buf[1] = ISC_SUBCMD_ENTER_UPDATE;
ret = i2c_master_send(_client, wr_buf, 10);
if (ret < 0) {
pr_info("[TSP ISC] %s,%d: i2c write fail[%d]\n",
__func__, __LINE__, ret);
return ISC_I2C_ERROR;
}
ret = mms100_i2c_read(_client, ISC_CMD_CONFIRM_STATUS, 1, &rd_buf);
if (ret < 0) {
pr_info("[TSP ISC] %s,%d: i2c read fail[%d]\n",
__func__, __LINE__, ret);
return ISC_I2C_ERROR;
}
if (rd_buf != ISC_STATUS_UPDATE_MODE)
return ISC_UPDATE_MODE_ENTER_ERROR;
pr_info("[TSP ISC]End mms100_enter_config_update()\n");
return ISC_SUCCESS;
}
static int mms100_ISC_clear_page(struct i2c_client *_client,
unsigned char _page_addr)
{
int ret;
unsigned char rd_buf;
memset(&g_wr_buf[3], 0xFF, PAGE_DATA);
g_wr_buf[0] = ISC_CMD_UPDATE_MODE; /* command */
g_wr_buf[1] = ISC_SUBCMD_DATA_WRITE; /* sub_command */
g_wr_buf[2] = _page_addr;
g_wr_buf[PAGE_HEADER + PAGE_DATA] = crc0_buf[_page_addr];
g_wr_buf[PAGE_HEADER + PAGE_DATA + 1] = crc1_buf[_page_addr];
ret = i2c_master_send(_client, g_wr_buf, PACKET_SIZE);
if (ret < 0) {
pr_info("[TSP ISC] %s,%d: i2c write fail[%d]\n",
__func__, __LINE__, ret);
return ISC_I2C_ERROR;
}
ret = mms100_i2c_read(_client, ISC_CMD_CONFIRM_STATUS, 1, &rd_buf);
if (ret < 0) {
pr_info("[TSP ISC] %s,%d: i2c read fail[%d]\n",
__func__, __LINE__, ret);
return ISC_I2C_ERROR;
}
if (rd_buf != ISC_STATUS_CRC_CHECK_SUCCESS)
return ISC_UPDATE_MODE_ENTER_ERROR;
pr_info("[TSP ISC]End mms100_ISC_clear_page()\n");
return ISC_SUCCESS;
}
static int mms100_ISC_clear_validate_markers(struct i2c_client *_client)
{
int ret_msg;
int i, j;
bool is_matched_address;
for (i = SEC_CORE; i <= SEC_PUBLIC_CONFIG; i++) {
if (section_update_flag[i]) {
if (ts_info[i].end_addr <= 30 &&
ts_info[i].end_addr > 0) {
ret_msg = mms100_ISC_clear_page(_client,
ts_info[i].end_addr);
if (ret_msg != ISC_SUCCESS)
return ret_msg;
}
}
}
for (i = SEC_CORE; i <= SEC_PUBLIC_CONFIG; i++) {
if (section_update_flag[i]) {
is_matched_address = false;
for (j = SEC_CORE; j <= SEC_PUBLIC_CONFIG; j++) {
if (mbin_info[i].end_addr ==
ts_info[i].end_addr) {
is_matched_address = true;
break;
}
}
if (!is_matched_address) {
if (mbin_info[i].end_addr <= 30 &&
mbin_info[i].end_addr > 0) {
ret_msg = mms100_ISC_clear_page(_client,
mbin_info[i].end_addr);
if (ret_msg != ISC_SUCCESS)
return ret_msg;
}
}
}
}
return ISC_SUCCESS;
}
static int mms100_update_section_data(struct i2c_client *_client)
{
int i, ret, next_ptr;
unsigned char rd_buf;
const unsigned char *ptr_fw;
char str_buf[STRING_BUF_LEN];
int page_addr;
for (i = 0; i < SECTION_NUM; i++) {
if (section_update_flag[i]) {
pr_info("[TSP ISC] section data i2c flash : [%d]", i);
next_ptr = 0;
ptr_fw = fw_mbin[i]->data;
do {
sscanf(ptr_fw + next_ptr, "%s", str_buf);
next_ptr += strlen(str_buf) + 1;
} while (!strstr(str_buf, "[Binary]"));
ptr_fw = ptr_fw + next_ptr + 2;
for (page_addr = mbin_info[i].start_addr;
page_addr <= mbin_info[i].end_addr;
page_addr++) {
if (page_addr - mbin_info[i].start_addr > 0)
ptr_fw += PACKET_SIZE;
if ((ptr_fw[0] != ISC_CMD_UPDATE_MODE) ||
(ptr_fw[1] != ISC_SUBCMD_DATA_WRITE) ||
(ptr_fw[2] != page_addr))
return ISC_WRITE_BUFFER_ERROR;
ret = i2c_master_send(_client,
ptr_fw, PACKET_SIZE);
if (ret < 0) {
pr_info("[TSP ISC] %s,%d: i2c write fail[%d]\n",
__func__, __LINE__, ret);
return ISC_I2C_ERROR;
}
ret = mms100_i2c_read(_client,
ISC_CMD_CONFIRM_STATUS, 1, &rd_buf);
if (ret < 0) {
pr_info("[TSP ISC] %s,%d: i2c read fail[%d]\n",
__func__, __LINE__, ret);
return ISC_I2C_ERROR;
}
if (rd_buf != ISC_STATUS_CRC_CHECK_SUCCESS)
return ISC_CRC_ERROR;
section_update_flag[i] = false;
}
}
}
pr_info("[TSP ISC]End mms100_update_section_data()\n");
return ISC_SUCCESS;
}
static eISCRet_t mms100_open_mbinary(struct i2c_client *_client)
{
int i;
char file_name[64];
int ret = 0;
ret += request_firmware(&(fw_mbin[1]),\
"tsp_melfas/CORE.fw", &_client->dev);
ret += request_firmware(&(fw_mbin[2]),\
"tsp_melfas/PRIV.fw", &_client->dev);
ret += request_firmware(&(fw_mbin[3]),\
"tsp_melfas/PUBL.fw", &_client->dev);
if (!ret)
return ISC_SUCCESS;
else {
pr_info("[TSP ISC] request_firmware fail");
return ret;
}
}
static eISCRet_t mms100_close_mbinary(void)
{
int i;
for (i = 0; i < SECTION_NUM; i++) {
if (fw_mbin[i] != NULL)
release_firmware(fw_mbin[i]);
}
return ISC_SUCCESS;
}
eISCRet_t mms100_ISC_download_mbinary(struct mms_ts_info *info)
{
struct i2c_client *_client = info->client;
eISCRet_t ret_msg = ISC_NONE;
pr_info("[TSP ISC] %s\n", __func__);
mms100_reset(info);
/* ret_msg = mms100_check_operating_mode(_client, EC_BOOT_ON_SUCCEEDED);
if (ret_msg != ISC_SUCCESS)
goto ISC_ERROR_HANDLE;
*/
ret_msg = mms100_open_mbinary(_client);
if (ret_msg != ISC_SUCCESS)
goto ISC_ERROR_HANDLE;
/*Config version Check*/
ret_msg = mms100_compare_version_info(_client);
if (ret_msg != ISC_SUCCESS)
goto ISC_ERROR_HANDLE;
ret_msg = mms100_enter_ISC_mode(_client);
if (ret_msg != ISC_SUCCESS)
goto ISC_ERROR_HANDLE;
ret_msg = mms100_enter_config_update(_client);
if (ret_msg != ISC_SUCCESS)
goto ISC_ERROR_HANDLE;
ret_msg = mms100_ISC_clear_validate_markers(_client);
if (ret_msg != ISC_SUCCESS)
goto ISC_ERROR_HANDLE;
pr_info("[TSP ISC]mms100_update_section_data start");
ret_msg = mms100_update_section_data(_client);
if (ret_msg != ISC_SUCCESS)
goto ISC_ERROR_HANDLE;
pr_info("[TSP ISC]mms100_update_section_data end");
/* mms100_reset(info); */
pr_info("[TSP ISC]FIRMWARE_UPDATE_FINISHED!!!\n");
ret_msg = ISC_SUCCESS;
ISC_ERROR_HANDLE:
if (ret_msg != ISC_SUCCESS)
pr_info("[TSP ISC]ISC_ERROR_CODE: %d\n", ret_msg);
mms100_reset(info);
mms100_close_mbinary();
return ret_msg;
}
#endif /* ISC_DL_MODE start */
static void hw_reboot(struct mms_ts_info *info, bool bootloader)
{
info->pdata->power(false);
gpio_direction_output(info->pdata->gpio_sda, bootloader ? 0 : 1);
gpio_direction_output(info->pdata->gpio_scl, bootloader ? 0 : 1);
gpio_direction_output(info->pdata->gpio_int, 0);
msleep(30);
info->pdata->power(true);
msleep(30);
if (bootloader) {
gpio_set_value(info->pdata->gpio_scl, 0);
gpio_set_value(info->pdata->gpio_sda, 1);
} else {
gpio_set_value(info->pdata->gpio_int, 1);
gpio_direction_input(info->pdata->gpio_int);
gpio_direction_input(info->pdata->gpio_scl);
gpio_direction_input(info->pdata->gpio_sda);
}
msleep(40);
}
static inline void hw_reboot_bootloader(struct mms_ts_info *info)
{
hw_reboot(info, true);
}
static inline void hw_reboot_normal(struct mms_ts_info *info)
{
hw_reboot(info, false);
}
static void isp_toggle_clk(struct mms_ts_info *info, int start_lvl, int end_lvl,
int hold_us)
{
gpio_set_value(info->pdata->gpio_scl, start_lvl);
udelay(hold_us);
gpio_set_value(info->pdata->gpio_scl, end_lvl);
udelay(hold_us);
}
/* 1 <= cnt <= 32 bits to write */
static void isp_send_bits(struct mms_ts_info *info, u32 data, int cnt)
{
gpio_direction_output(info->pdata->gpio_int, 0);
gpio_direction_output(info->pdata->gpio_scl, 0);
gpio_direction_output(info->pdata->gpio_sda, 0);
/* clock out the bits, msb first */
while (cnt--) {
gpio_set_value(info->pdata->gpio_sda, (data >> cnt) & 1);
udelay(3);
isp_toggle_clk(info, 1, 0, 3);
}
}
/* 1 <= cnt <= 32 bits to read */
static u32 isp_recv_bits(struct mms_ts_info *info, int cnt)
{
u32 data = 0;
gpio_direction_output(info->pdata->gpio_int, 0);
gpio_direction_output(info->pdata->gpio_scl, 0);
gpio_set_value(info->pdata->gpio_sda, 0);
gpio_direction_input(info->pdata->gpio_sda);
/* clock in the bits, msb first */
while (cnt--) {
isp_toggle_clk(info, 0, 1, 1);
data = (data << 1) | (!!gpio_get_value(info->pdata->gpio_sda));
}
gpio_direction_output(info->pdata->gpio_sda, 0);
return data;
}
static void isp_enter_mode(struct mms_ts_info *info, u32 mode)
{
int cnt;
unsigned long flags;
local_irq_save(flags);
gpio_direction_output(info->pdata->gpio_int, 0);
gpio_direction_output(info->pdata->gpio_scl, 0);
gpio_direction_output(info->pdata->gpio_sda, 1);
mode &= 0xffff;
for (cnt = 15; cnt >= 0; cnt--) {
gpio_set_value(info->pdata->gpio_int, (mode >> cnt) & 1);
udelay(3);
isp_toggle_clk(info, 1, 0, 3);
}
gpio_set_value(info->pdata->gpio_int, 0);
local_irq_restore(flags);
}
static void isp_exit_mode(struct mms_ts_info *info)
{
int i;
unsigned long flags;
local_irq_save(flags);
gpio_direction_output(info->pdata->gpio_int, 0);
udelay(3);
for (i = 0; i < 10; i++)
isp_toggle_clk(info, 1, 0, 3);
local_irq_restore(flags);
}
static void flash_set_address(struct mms_ts_info *info, u16 addr)
{
/* Only 13 bits of addr are valid.
* The addr is in bits 13:1 of cmd */
isp_send_bits(info, (u32) (addr & 0x1fff) << 1, 18);
}
static void flash_erase(struct mms_ts_info *info)
{
isp_enter_mode(info, ISP_MODE_FLASH_ERASE);
gpio_direction_output(info->pdata->gpio_int, 0);
gpio_direction_output(info->pdata->gpio_scl, 0);
gpio_direction_output(info->pdata->gpio_sda, 1);
/* 4 clock cycles with different timings for the erase to
* get processed, clk is already 0 from above */
udelay(7);
isp_toggle_clk(info, 1, 0, 3);
udelay(7);
isp_toggle_clk(info, 1, 0, 3);
usleep_range(25000, 35000);
isp_toggle_clk(info, 1, 0, 3);
usleep_range(150, 200);
isp_toggle_clk(info, 1, 0, 3);
gpio_set_value(info->pdata->gpio_sda, 0);
isp_exit_mode(info);
}
static u32 flash_readl(struct mms_ts_info *info, u16 addr)
{
int i;
u32 val;
unsigned long flags;
local_irq_save(flags);
isp_enter_mode(info, ISP_MODE_FLASH_READ);
flash_set_address(info, addr);
gpio_direction_output(info->pdata->gpio_scl, 0);
gpio_direction_output(info->pdata->gpio_sda, 0);
udelay(40);
/* data load cycle */
for (i = 0; i < 6; i++)
isp_toggle_clk(info, 1, 0, 10);
val = isp_recv_bits(info, 32);
isp_exit_mode(info);
local_irq_restore(flags);
return val;
}
static void flash_writel(struct mms_ts_info *info, u16 addr, u32 val)
{
unsigned long flags;
local_irq_save(flags);
isp_enter_mode(info, ISP_MODE_FLASH_WRITE);
flash_set_address(info, addr);
isp_send_bits(info, val, 32);
gpio_direction_output(info->pdata->gpio_sda, 1);
/* 6 clock cycles with different timings for the data to get written
* into flash */
isp_toggle_clk(info, 0, 1, 3);
isp_toggle_clk(info, 0, 1, 3);
isp_toggle_clk(info, 0, 1, 6);
isp_toggle_clk(info, 0, 1, 12);
isp_toggle_clk(info, 0, 1, 3);
isp_toggle_clk(info, 0, 1, 3);
isp_toggle_clk(info, 1, 0, 1);
gpio_direction_output(info->pdata->gpio_sda, 0);
isp_exit_mode(info);
local_irq_restore(flags);
usleep_range(300, 400);
}
static bool flash_is_erased(struct mms_ts_info *info)
{
struct i2c_client *client = info->client;
u32 val;
u16 addr;
for (addr = 0; addr < (ISP_MAX_FW_SIZE / 4); addr++) {
udelay(40);
val = flash_readl(info, addr);
if (val != 0xffffffff) {
dev_dbg(&client->dev,
"addr 0x%x not erased: 0x%08x != 0xffffffff\n",
addr, val);
return false;
}
}
return true;
}
static int fw_write_image(struct mms_ts_info *info, const u8 * data, size_t len)
{
struct i2c_client *client = info->client;
u16 addr = 0;
for (addr = 0; addr < (len / 4); addr++, data += 4) {
u32 val = get_unaligned_le32(data);
u32 verify_val;
int retries = 3;
while (retries--) {
flash_writel(info, addr, val);
verify_val = flash_readl(info, addr);
if (val == verify_val)
break;
dev_err(&client->dev,
"mismatch @ addr 0x%x: 0x%x != 0x%x\n",
addr, verify_val, val);
continue;
}
if (retries < 0)
return -ENXIO;
}
return 0;
}
static int fw_download(struct mms_ts_info *info, const u8 * data, size_t len)
{
struct i2c_client *client = info->client;
u32 val;
int ret = 0;
if (len % 4) {
dev_err(&client->dev,
"fw image size (%d) must be a multiple of 4 bytes\n",
len);
return -EINVAL;
} else if (len > ISP_MAX_FW_SIZE) {
dev_err(&client->dev,
"fw image is too big, %d > %d\n", len, ISP_MAX_FW_SIZE);
return -EINVAL;
}
dev_info(&client->dev, "fw download start\n");
info->pdata->power(false);
gpio_direction_output(info->pdata->gpio_sda, 0);
gpio_direction_output(info->pdata->gpio_scl, 0);
gpio_direction_output(info->pdata->gpio_int, 0);
hw_reboot_bootloader(info);
val = flash_readl(info, ISP_IC_INFO_ADDR);
dev_info(&client->dev, "IC info: 0x%02x (%x)\n", val & 0xff, val);
dev_info(&client->dev, "fw erase...\n");
flash_erase(info);
if (!flash_is_erased(info)) {
ret = -ENXIO;
goto err;
}
dev_info(&client->dev, "fw write...\n");
/* XXX: what does this do?! */
flash_writel(info, ISP_IC_INFO_ADDR, 0xffffff00 | (val & 0xff));
usleep_range(1000, 1500);
ret = fw_write_image(info, data, len);
if (ret)
goto err;
usleep_range(1000, 1500);
hw_reboot_normal(info);
usleep_range(1000, 1500);
dev_info(&client->dev, "fw download done...\n");
return 0;
err:
dev_err(&client->dev, "fw download failed...\n");
hw_reboot_normal(info);
return ret;
}
#if defined(SEC_TSP_ISC_FW_UPDATE)
static u16 gen_crc(u8 data, u16 pre_crc)
{
u16 crc;
u16 cur;
u16 temp;
u16 bit_1;
u16 bit_2;
int i;
crc = pre_crc;
for (i = 7; i >= 0; i--) {
cur = ((data >> i) & 0x01) ^ (crc & 0x0001);
bit_1 = cur ^ (crc >> 11 & 0x01);
bit_2 = cur ^ (crc >> 4 & 0x01);
temp = (cur << 4) | (crc >> 12 & 0x0F);
temp = (temp << 7) | (bit_1 << 6) | (crc >> 5 & 0x3F);
temp = (temp << 4) | (bit_2 << 3) | (crc >> 1 & 0x0007);
crc = temp;
}
return crc;
}
static int isc_fw_download(struct mms_ts_info *info, const u8 * data,
size_t len)
{
u8 *buff;
u16 crc_buf;
int src_idx;
int dest_idx;
int ret;
int i, j;
buff = kzalloc(ISC_PKT_SIZE, GFP_KERNEL);
if (!buff) {
dev_err(&info->client->dev, "%s: failed to allocate memory\n",
__func__);
ret = -1;
goto err_mem_alloc;
}
/* enterring ISC mode */
*buff = ISC_ENTER_ISC_DATA;
ret = i2c_smbus_write_byte_data(info->client,
ISC_ENTER_ISC_CMD, *buff);
if (ret < 0) {
dev_err(&info->client->dev,
"fail to enter ISC mode(err=%d)\n", ret);
goto fail_to_isc_enter;
}
usleep_range(10000, 20000);
dev_info(&info->client->dev, "Enter ISC mode\n");
/*enter ISC update mode */
*buff = ISC_ENTER_UPDATE_DATA;
ret = i2c_smbus_write_i2c_block_data(info->client,
ISC_CMD,
ISC_ENTER_UPDATE_DATA_LEN, buff);
if (ret < 0) {
dev_err(&info->client->dev,
"fail to enter ISC update mode(err=%d)\n", ret);
goto fail_to_isc_update;
}
dev_info(&info->client->dev, "Enter ISC update mode\n");
/* firmware write */
*buff = ISC_CMD;
*(buff + 1) = ISC_DATA_WRITE_SUB_CMD;
for (i = 0; i < ISC_PKT_NUM; i++) {
*(buff + 2) = i;
crc_buf = gen_crc(*(buff + 2), ISC_DEFAULT_CRC);
for (j = 0; j < ISC_PKT_DATA_SIZE; j++) {
dest_idx = ISC_PKT_HEADER_SIZE + j;
src_idx = i * ISC_PKT_DATA_SIZE +
((int)(j / WORD_SIZE)) * WORD_SIZE -
(j % WORD_SIZE) + 3;
*(buff + dest_idx) = *(data + src_idx);
crc_buf = gen_crc(*(buff + dest_idx), crc_buf);
}
*(buff + ISC_PKT_DATA_SIZE + ISC_PKT_HEADER_SIZE + 1) =
crc_buf & 0xFF;
*(buff + ISC_PKT_DATA_SIZE + ISC_PKT_HEADER_SIZE) =
crc_buf >> 8 & 0xFF;
ret = i2c_master_send(info->client, buff, ISC_PKT_SIZE);
if (ret < 0) {
dev_err(&info->client->dev,
"fail to firmware writing on packet %d.(%d)\n",
i, ret);
goto fail_to_fw_write;
}
usleep_range(1, 5);
/* confirm CRC */
ret = i2c_smbus_read_byte_data(info->client,
ISC_CHECK_STATUS_CMD);
if (ret == ISC_CONFIRM_CRC) {
dev_info(&info->client->dev,
"updating %dth firmware data packet.\n", i);
} else {
dev_err(&info->client->dev,
"fail to firmware update on %dth (%X).\n",
i, ret);
ret = -1;
goto fail_to_confirm_crc;
}
}
ret = 0;
fail_to_confirm_crc:
fail_to_fw_write:
/* exit ISC mode */
*buff = ISC_EXIT_ISC_SUB_CMD;
*(buff + 1) = ISC_EXIT_ISC_SUB_CMD2;
i2c_smbus_write_i2c_block_data(info->client, ISC_CMD, 2, buff);
usleep_range(10000, 20000);
fail_to_isc_update:
hw_reboot_normal(info);
fail_to_isc_enter:
kfree(buff);
err_mem_alloc:
return ret;
}
#endif /* SEC_TSP_ISC_FW_UPDATE */
static int get_fw_version(struct mms_ts_info *info)
{
int ret;
int retries = 3;
/* this seems to fail sometimes after a reset.. retry a few times */
do {
ret = i2c_smbus_read_byte_data(info->client, MMS_FW_VERSION);
} while (ret < 0 && retries-- > 0);
return ret;
}
static int get_hw_version(struct mms_ts_info *info)
{
int ret;
int retries = 3;
/* this seems to fail sometimes after a reset.. retry a few times */
do {
ret = i2c_smbus_read_byte_data(info->client, MMS_HW_REVISION);
} while (ret < 0 && retries-- > 0);
return ret;
}
static int mms_ts_enable(struct mms_ts_info *info, int wakeupcmd)
{
mutex_lock(&info->lock);
if (info->enabled)
goto out;
/* wake up the touch controller. */
if (wakeupcmd == 1) {
i2c_smbus_write_byte_data(info->client, 0, 0);
usleep_range(3000, 5000);
}
info->enabled = true;
enable_irq(info->irq);
out:
mutex_unlock(&info->lock);
return 0;
}
static int mms_ts_disable(struct mms_ts_info *info, int sleepcmd)
{
mutex_lock(&info->lock);
if (!info->enabled)
goto out;
disable_irq_nosync(info->irq);
if (sleepcmd == 1) {
i2c_smbus_write_byte_data(info->client, MMS_MODE_CONTROL, 0);
usleep_range(10000, 12000);
}
info->enabled = false;
touch_is_pressed = 0;
out:
mutex_unlock(&info->lock);
return 0;
}
static int mms_ts_finish_config(struct mms_ts_info *info)
{
struct i2c_client *client = info->client;
int ret;
ret = request_threaded_irq(client->irq, NULL, mms_ts_interrupt,
IRQF_TRIGGER_LOW | IRQF_ONESHOT,
MELFAS_TS_NAME, info);
if (ret < 0) {
ret = 1;
dev_err(&client->dev, "Failed to register interrupt\n");
goto err_req_irq;
}
info->irq = client->irq;
barrier();
dev_info(&client->dev,
"Melfas MMS-series touch controller initialized\n");
return 0;
err_req_irq:
return ret;
}
static int mms_ts_fw_info(struct mms_ts_info *info)
{
struct i2c_client *client = info->client;
struct i2c_adapter *adapter = to_i2c_adapter(client->dev.parent);
int ret = 0;
int ver, hw_rev;
ver = get_fw_version(info);
info->fw_ic_ver = ver;
dev_info(&client->dev,
"[TSP]fw version 0x%02x !!!!\n", ver);
hw_rev = get_hw_version(info);
dev_info(&client->dev,
"[TSP] hw rev = %x\n", hw_rev);
if (ver < 0 || hw_rev < 0) {
ret = 1;
dev_err(&client->dev,
"i2c fail...tsp driver unload.\n");
return ret;
}
if (!info->pdata || !info->pdata->mux_fw_flash) {
ret = 1;
dev_err(&client->dev,
"fw cannot be updated, missing platform data\n");
return ret;
}
ret = mms_ts_finish_config(info);
return ret;
}
static int mms_ts_fw_load(struct mms_ts_info *info)
{
struct i2c_client *client = info->client;
struct i2c_adapter *adapter = to_i2c_adapter(client->dev.parent);
int ret = 0;
int ver, hw_rev;
int retries = 3;
ver = get_fw_version(info);
info->fw_ic_ver = ver;
dev_info(&client->dev,
"[TSP]fw version 0x%02x !!!!\n", ver);
hw_rev = get_hw_version(info);
dev_info(&client->dev,
"[TSP]hw rev = 0x%02x\n", hw_rev);
pr_err("[TSP] ISC Ver [0x%02x] [0x%02x] [0x%02x]",
i2c_smbus_read_byte_data(info->client, 0xF3),
i2c_smbus_read_byte_data(info->client, 0xF4),
i2c_smbus_read_byte_data(info->client, 0xF5));
if (!info->pdata || !info->pdata->mux_fw_flash) {
ret = 1;
dev_err(&client->dev,
"fw cannot be updated, missing platform data\n");
goto out;
}
/* 4.8" OCTA LCD FW */
if (ver >= FW_VERSION_4_8 && ver != 0xFF\
&& ver != 0x00 && ver != 0x45) {
dev_info(&client->dev,
"4.8 fw version update does not need\n");
goto done;
}
while (retries--) {
ret = mms100_ISC_download_mbinary(info);
ver = get_fw_version(info);
info->fw_ic_ver = ver;
if (ret == 0) {
pr_err("[TSP] mms100_ISC_download_mbinary success");
goto done;
} else {
pr_err("[TSP] mms100_ISC_download_mbinary fail [%d]",
ret);
ret = 1;
}
dev_err(&client->dev, "retrying flashing\n");
}
out:
return ret;
done:
#if ISC_DL_MODE /* ISC_DL_MODE start */
pr_err("[TSP] ISC Ver [0x%02x] [0x%02x] [0x%02x]",
i2c_smbus_read_byte_data(info->client, 0xF3),
i2c_smbus_read_byte_data(info->client, 0xF4),
i2c_smbus_read_byte_data(info->client, 0xF5));
#endif
ret = mms_ts_finish_config(info);
return ret;
}
#ifdef SEC_TSP_FACTORY_TEST
static void set_cmd_result(struct mms_ts_info *info, char *buff, int len)
{
strncat(info->cmd_result, buff, len);
}
static void get_raw_data_all(struct mms_ts_info *info, u8 cmd)
{
u8 w_buf[6];
u8 read_buffer[2]; /* 52 */
int gpio;
int ret;
int i, j;
u32 max_value = 0, min_value = 0;
u32 raw_data;
char buff[TSP_CMD_STR_LEN] = {0};
gpio = info->pdata->gpio_int;
/* gpio = msm_irq_to_gpio(info->irq); */
disable_irq(info->irq);
w_buf[0] = MMS_VSC_CMD; /* vendor specific command id */
w_buf[1] = MMS_VSC_MODE; /* mode of vendor */
w_buf[2] = 0; /* tx line */
w_buf[3] = 0; /* rx line */
w_buf[4] = 0; /* reserved */
w_buf[5] = 0; /* sub command */
if (cmd == MMS_VSC_CMD_EXIT) {
w_buf[5] = MMS_VSC_CMD_EXIT; /* exit test mode */
ret = i2c_smbus_write_i2c_block_data(info->client,
w_buf[0], 5, &w_buf[1]);
if (ret < 0)
goto err_i2c;
enable_irq(info->irq);
msleep(200);
return;
}
/* MMS_VSC_CMD_CM_DELTA or MMS_VSC_CMD_CM_ABS
* this two mode need to enter the test mode
* exit command must be followed by testing.
*/
if (cmd == MMS_VSC_CMD_CM_DELTA || cmd == MMS_VSC_CMD_CM_ABS) {
/* enter the debug mode */
w_buf[2] = 0x0; /* tx */
w_buf[3] = 0x0; /* rx */
w_buf[5] = MMS_VSC_CMD_ENTER;
ret = i2c_smbus_write_i2c_block_data(info->client,
w_buf[0], 5, &w_buf[1]);
if (ret < 0)
goto err_i2c;
/* wating for the interrupt */
while (gpio_get_value(gpio))
udelay(100);
}
for (i = 0; i < RX_NUM; i++) {
for (j = 0; j < TX_NUM; j++) {
w_buf[2] = j; /* tx */
w_buf[3] = i; /* rx */
w_buf[5] = cmd;
ret = i2c_smbus_write_i2c_block_data(info->client,
w_buf[0], 5, &w_buf[1]);
if (ret < 0)
goto err_i2c;
usleep_range(1, 5);
ret = i2c_smbus_read_i2c_block_data(info->client, 0xBF,
2, read_buffer);
if (ret < 0)
goto err_i2c;
raw_data = ((u16) read_buffer[1] << 8) | read_buffer[0];
if (i == 0 && j == 0) {
max_value = min_value = raw_data;
} else {
max_value = max(max_value, raw_data);
min_value = min(min_value, raw_data);
}
if (cmd == MMS_VSC_CMD_INTENSITY) {
info->intensity[i * TX_NUM + j] = raw_data;
dev_dbg(&info->client->dev, "[TSP] intensity[%d][%d] = %d\n",
j, i, info->intensity[i * TX_NUM + j]);
} else if (cmd == MMS_VSC_CMD_CM_DELTA) {
info->inspection[i * TX_NUM + j] = raw_data;
dev_dbg(&info->client->dev, "[TSP] delta[%d][%d] = %d\n",
j, i, info->inspection[i * TX_NUM + j]);
} else if (cmd == MMS_VSC_CMD_CM_ABS) {
info->raw[i * TX_NUM + j] = raw_data;
dev_dbg(&info->client->dev, "[TSP] raw[%d][%d] = %d\n",
j, i, info->raw[i * TX_NUM + j]);
} else if (cmd == MMS_VSC_CMD_REFER) {
info->reference[i * TX_NUM + j] =
raw_data >> 3;
dev_dbg(&info->client->dev, "[TSP] reference[%d][%d] = %d\n",
j, i, info->reference[i * TX_NUM + j]);
}
}
}
snprintf(buff, sizeof(buff), "%d,%d", min_value, max_value);
set_cmd_result(info, buff, strnlen(buff, sizeof(buff)));
enable_irq(info->irq);
err_i2c:
dev_err(&info->client->dev, "%s: fail to i2c (cmd=%d)\n",
__func__, cmd);
}
static u32 get_raw_data_one(struct mms_ts_info *info, u16 rx_idx, u16 tx_idx,
u8 cmd)
{
u8 w_buf[6];
u8 read_buffer[2];
int ret;
u32 raw_data;
w_buf[0] = MMS_VSC_CMD; /* vendor specific command id */
w_buf[1] = MMS_VSC_MODE; /* mode of vendor */
w_buf[2] = 0; /* tx line */
w_buf[3] = 0; /* rx line */
w_buf[4] = 0; /* reserved */
w_buf[5] = 0; /* sub command */
if (cmd != MMS_VSC_CMD_INTENSITY && cmd != MMS_VSC_CMD_RAW &&
cmd != MMS_VSC_CMD_REFER) {
dev_err(&info->client->dev, "%s: not profer command(cmd=%d)\n",
__func__, cmd);
return FAIL;
}
w_buf[2] = tx_idx; /* tx */
w_buf[3] = rx_idx; /* rx */
w_buf[5] = cmd; /* sub command */
ret = i2c_smbus_write_i2c_block_data(info->client, w_buf[0], 5,
&w_buf[1]);
if (ret < 0)
goto err_i2c;
ret = i2c_smbus_read_i2c_block_data(info->client, 0xBF, 2, read_buffer);
if (ret < 0)
goto err_i2c;
raw_data = ((u16) read_buffer[1] << 8) | read_buffer[0];
if (cmd == MMS_VSC_CMD_REFER)
raw_data = raw_data >> 4;
return raw_data;
err_i2c:
dev_err(&info->client->dev, "%s: fail to i2c (cmd=%d)\n",
__func__, cmd);
return FAIL;
}
static ssize_t show_close_tsp_test(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct mms_ts_info *info = dev_get_drvdata(dev);
get_raw_data_all(info, MMS_VSC_CMD_EXIT);
info->ft_flag = 0;
return snprintf(buf, TSP_BUF_SIZE, "%u\n", 0);
}
static void set_default_result(struct mms_ts_info *info)
{
char delim = ':';
memset(info->cmd_result, 0x00, ARRAY_SIZE(info->cmd_result));
memcpy(info->cmd_result, info->cmd, strlen(info->cmd));
strncat(info->cmd_result, &delim, 1);
}
static int check_rx_tx_num(void *device_data)
{
struct mms_ts_info *info = (struct mms_ts_info *)device_data;
char buff[TSP_CMD_STR_LEN] = {0};
int node;
if (info->cmd_param[0] < 0 ||
info->cmd_param[0] >= TX_NUM ||
info->cmd_param[1] < 0 ||
info->cmd_param[1] >= RX_NUM) {
snprintf(buff, sizeof(buff) , "%s", "NG");
set_cmd_result(info, buff, strnlen(buff, sizeof(buff)));
info->cmd_state = 3;
dev_info(&info->client->dev, "%s: parameter error: %u,%u\n",
__func__, info->cmd_param[0],
info->cmd_param[1]);
node = -1;
return node;
}
node = info->cmd_param[1] * TX_NUM + info->cmd_param[0];
dev_info(&info->client->dev, "%s: node = %d\n", __func__,
node);
return node;
}
static void not_support_cmd(void *device_data)
{
struct mms_ts_info *info = (struct mms_ts_info *)device_data;
char buff[16] = {0};
set_default_result(info);
sprintf(buff, "%s", "NA");
set_cmd_result(info, buff, strnlen(buff, sizeof(buff)));
info->cmd_state = 4;
dev_info(&info->client->dev, "%s: \"%s(%d)\"\n", __func__,
buff, strnlen(buff, sizeof(buff)));
return;
}
static void fw_update(void *device_data)
{
struct mms_ts_info *info = (struct mms_ts_info *)device_data;
struct i2c_client *client = info->client;
struct i2c_adapter *adapter = to_i2c_adapter(client->dev.parent);
int ret = 0;
int ver = 0, fw_bin_ver = 0;
int retries = 5;
const u8 *buff = 0;
mm_segment_t old_fs = {0};
struct file *fp = NULL;
long fsize = 0, nread = 0;
char fw_path[MAX_FW_PATH+1];
char result[16] = {0};
set_default_result(info);
dev_info(&client->dev,
"fw_ic_ver = 0x%02x, fw_bin_ver = 0x%02x\n",
info->fw_ic_ver, fw_bin_ver);
switch (info->cmd_param[0]) {
case BUILT_IN:
dev_info(&client->dev, "built in 4.8 fw is loaded!!\n");
while (retries--) {
ret = mms100_ISC_download_mbinary(info);
ver = get_fw_version(info);
info->fw_ic_ver = ver;
if (ret == 0) {
pr_err("[TSP] mms100_ISC_download_mbinary success");
info->cmd_state = 2;
return;
} else {
pr_err("[TSP] mms100_ISC_download_mbinary fail[%d]",
ret);
info->cmd_state = 3;
}
}
return;
break;
case UMS:
old_fs = get_fs();
set_fs(get_ds());
snprintf(fw_path, MAX_FW_PATH, "/sdcard/%s", TSP_FW_FILENAME);
fp = filp_open(fw_path, O_RDONLY, 0);
if (IS_ERR(fp)) {
dev_err(&client->dev,
"file %s open error:%d\n", fw_path, (s32)fp);
info->cmd_state = 3;
goto err_open;
}
fsize = fp->f_path.dentry->d_inode->i_size;
buff = kzalloc((size_t)fsize, GFP_KERNEL);
if (!buff) {
dev_err(&client->dev, "fail to alloc buffer for fw\n");
info->cmd_state = 3;
goto err_alloc;
}
nread = vfs_read(fp, (char __user *)buff, fsize, &fp->f_pos);
if (nread != fsize) {
/*dev_err("fail to read file %s (nread = %d)\n",
fw_path, nread);*/
info->cmd_state = 3;
goto err_fw_size;
}
filp_close(fp, current->files);
set_fs(old_fs);
dev_info(&client->dev, "ums fw is loaded!!\n");
break;
default:
dev_err(&client->dev, "invalid fw file type!!\n");
goto not_support;
}
disable_irq(info->irq);
while (retries--) {
i2c_lock_adapter(adapter);
info->pdata->mux_fw_flash(true);
ret = fw_download(info, (const u8 *)buff,
(const size_t)fsize);
info->pdata->mux_fw_flash(false);
i2c_unlock_adapter(adapter);
if (ret < 0) {
dev_err(&client->dev, "retrying flashing\n");
continue;
}
ver = get_fw_version(info);
info->fw_ic_ver = ver;
if (info->cmd_param[0] == 1 || info->cmd_param[0] == 2) {
dev_info(&client->dev,
"fw update done. ver = 0x%02x\n", ver);
info->cmd_state = 2;
snprintf(result, sizeof(result) , "%s", "OK");
set_cmd_result(info, result,
strnlen(result, sizeof(result)));
enable_irq(info->irq);
kfree(buff);
return;
} else if (ver == fw_bin_ver) {
dev_info(&client->dev,
"fw update done. ver = 0x%02x\n", ver);
info->cmd_state = 2;
snprintf(result, sizeof(result) , "%s", "OK");
set_cmd_result(info, result,
strnlen(result, sizeof(result)));
enable_irq(info->irq);
return;
} else {
dev_err(&client->dev,
"ERROR : fw version is still wrong (0x%x != 0x%x)\n",
ver, fw_bin_ver);
}
dev_err(&client->dev, "retrying flashing\n");
}
if (fp != NULL) {
err_fw_size:
kfree(buff);
err_alloc:
filp_close(fp, NULL);
err_open:
set_fs(old_fs);
}
not_support:
do_not_need_update:
snprintf(result, sizeof(result) , "%s", "NG");
set_cmd_result(info, result, strnlen(result, sizeof(result)));
return;
}
static void get_fw_ver_bin(void *device_data)
{
struct mms_ts_info *info = (struct mms_ts_info *)device_data;
char buff[16] = {0};
int hw_rev;
set_default_result(info);
snprintf(buff, sizeof(buff), "%#02x", FW_VERSION_4_8);
set_cmd_result(info, buff, strnlen(buff, sizeof(buff)));
info->cmd_state = 2;
dev_info(&info->client->dev, "%s: %s(%d)\n", __func__,
buff, strnlen(buff, sizeof(buff)));
}
static void get_fw_ver_ic(void *device_data)
{
struct mms_ts_info *info = (struct mms_ts_info *)device_data;
char buff[16] = {0};
int ver;
set_default_result(info);
ver = info->fw_ic_ver;
snprintf(buff, sizeof(buff), "%#02x", ver);
set_cmd_result(info, buff, strnlen(buff, sizeof(buff)));
info->cmd_state = 2;
dev_info(&info->client->dev, "%s: %s(%d)\n", __func__,
buff, strnlen(buff, sizeof(buff)));
}
static void get_config_ver(void *device_data)
{
struct mms_ts_info *info = (struct mms_ts_info *)device_data;
char buff[20] = {0};
set_default_result(info);
snprintf(buff, sizeof(buff), "%s", info->config_fw_version);
set_cmd_result(info, buff, strnlen(buff, sizeof(buff)));
info->cmd_state = 2;
dev_info(&info->client->dev, "%s: %s(%d)\n", __func__,
buff, strnlen(buff, sizeof(buff)));
}
static void get_threshold(void *device_data)
{
struct mms_ts_info *info = (struct mms_ts_info *)device_data;
char buff[16] = {0};
int threshold;
set_default_result(info);
threshold = i2c_smbus_read_byte_data(info->client, 0x05);
if (threshold < 0) {
snprintf(buff, sizeof(buff), "%s", "NG");
set_cmd_result(info, buff, strnlen(buff, sizeof(buff)));
info->cmd_state = 3;
return;
}
snprintf(buff, sizeof(buff), "%d", threshold);
set_cmd_result(info, buff, strnlen(buff, sizeof(buff)));
info->cmd_state = 2;
dev_info(&info->client->dev, "%s: %s(%d)\n", __func__,
buff, strnlen(buff, sizeof(buff)));
}
/*
static void module_off_master(void *device_data)
{
struct mms_ts_info *info = (struct mms_ts_info *)device_data;
char buff[3] = {0};
mutex_lock(&info->lock);
if (info->enabled) {
disable_irq(info->irq);
info->enabled = false;
touch_is_pressed = 0;
}
mutex_unlock(&info->lock);
info->pdata->power(0);
if (info->pdata->is_vdd_on() == 0)
snprintf(buff, sizeof(buff), "%s", "OK");
else
snprintf(buff, sizeof(buff), "%s", "NG");
set_default_result(info);
set_cmd_result(info, buff, strnlen(buff, sizeof(buff)));
if (strncmp(buff, "OK", 2) == 0)
info->cmd_state = 2;
else
info->cmd_state = 3;
dev_info(&info->client->dev, "%s: %s\n", __func__, buff);
}
static void module_on_master(void *device_data)
{
struct mms_ts_info *info = (struct mms_ts_info *)device_data;
char buff[3] = {0};
mms_pwr_on_reset(info);
mutex_lock(&info->lock);
if (!info->enabled) {
enable_irq(info->irq);
info->enabled = true;
}
mutex_unlock(&info->lock);
if (info->pdata->is_vdd_on() == 1)
snprintf(buff, sizeof(buff), "%s", "OK");
else
snprintf(buff, sizeof(buff), "%s", "NG");
set_default_result(info);
set_cmd_result(info, buff, strnlen(buff, sizeof(buff)));
if (strncmp(buff, "OK", 2) == 0)
info->cmd_state = 2;
else
info->cmd_state = 3;
dev_info(&info->client->dev, "%s: %s\n", __func__, buff);
}
static void module_off_slave(void *device_data)
{
struct mms_ts_info *info = (struct mms_ts_info *)device_data;
not_support_cmd(info);
}
static void module_on_slave(void *device_data)
{
struct mms_ts_info *info = (struct mms_ts_info *)device_data;
not_support_cmd(info);
}
*/
static void get_chip_vendor(void *device_data)
{
struct mms_ts_info *info = (struct mms_ts_info *)device_data;
char buff[16] = {0};
set_default_result(info);
snprintf(buff, sizeof(buff), "%s", "MELFAS");
set_cmd_result(info, buff, strnlen(buff, sizeof(buff)));
info->cmd_state = 2;
dev_info(&info->client->dev, "%s: %s(%d)\n", __func__,
buff, strnlen(buff, sizeof(buff)));
}
static void get_chip_name(void *device_data)
{
struct mms_ts_info *info = (struct mms_ts_info *)device_data;
char buff[16] = {0};
set_default_result(info);
snprintf(buff, sizeof(buff), "%s", "MMS144");
set_cmd_result(info, buff, strnlen(buff, sizeof(buff)));
info->cmd_state = 2;
dev_info(&info->client->dev, "%s: %s(%d)\n", __func__,
buff, strnlen(buff, sizeof(buff)));
}
static void get_reference(void *device_data)
{
struct mms_ts_info *info = (struct mms_ts_info *)device_data;
char buff[16] = {0};
unsigned int val;
int node;
set_default_result(info);
node = check_rx_tx_num(info);
if (node < 0)
return;
val = info->reference[node];
snprintf(buff, sizeof(buff), "%u", val);
set_cmd_result(info, buff, strnlen(buff, sizeof(buff)));
info->cmd_state = 2;
dev_info(&info->client->dev, "%s: %s(%d)\n", __func__,
buff, strnlen(buff, sizeof(buff)));
}
static void get_cm_abs(void *device_data)
{
struct mms_ts_info *info = (struct mms_ts_info *)device_data;
char buff[16] = {0};
unsigned int val;
int node;
set_default_result(info);
node = check_rx_tx_num(info);
if (node < 0)
return;
val = info->raw[node];
snprintf(buff, sizeof(buff), "%u", val);
set_cmd_result(info, buff, strnlen(buff, sizeof(buff)));
info->cmd_state = 2;
dev_info(&info->client->dev, "%s: %s(%d)\n", __func__, buff,
strnlen(buff, sizeof(buff)));
}
static void get_cm_delta(void *device_data)
{
struct mms_ts_info *info = (struct mms_ts_info *)device_data;
char buff[16] = {0};
unsigned int val;
int node;
set_default_result(info);
node = check_rx_tx_num(info);
if (node < 0)
return;
val = info->inspection[node];
snprintf(buff, sizeof(buff), "%u", val);
set_cmd_result(info, buff, strnlen(buff, sizeof(buff)));
info->cmd_state = 2;
dev_info(&info->client->dev, "%s: %s(%d)\n", __func__, buff,
strnlen(buff, sizeof(buff)));
}
static void get_intensity(void *device_data)
{
struct mms_ts_info *info = (struct mms_ts_info *)device_data;
char buff[16] = {0};
unsigned int val;
int node;
set_default_result(info);
node = check_rx_tx_num(info);
if (node < 0)
return;
val = info->intensity[node];
snprintf(buff, sizeof(buff), "%u", val);
set_cmd_result(info, buff, strnlen(buff, sizeof(buff)));
info->cmd_state = 2;
dev_info(&info->client->dev, "%s: %s(%d)\n", __func__, buff,
strnlen(buff, sizeof(buff)));
}
static void get_x_num(void *device_data)
{
struct mms_ts_info *info = (struct mms_ts_info *)device_data;
char buff[16] = {0};
int val;
set_default_result(info);
val = i2c_smbus_read_byte_data(info->client, 0xEF);
if (val < 0) {
snprintf(buff, sizeof(buff), "%s", "NG");
set_cmd_result(info, buff, strnlen(buff, sizeof(buff)));
info->cmd_state = 3;
dev_info(&info->client->dev,
"%s: fail to read num of x (%d).\n", __func__, val);
return;
}
snprintf(buff, sizeof(buff), "%u", val);
set_cmd_result(info, buff, strnlen(buff, sizeof(buff)));
info->cmd_state = 2;
dev_info(&info->client->dev, "%s: %s(%d)\n", __func__, buff,
strnlen(buff, sizeof(buff)));
}
static void get_y_num(void *device_data)
{
struct mms_ts_info *info = (struct mms_ts_info *)device_data;
char buff[16] = {0};
int val;
set_default_result(info);
val = i2c_smbus_read_byte_data(info->client, 0xEE);
if (val < 0) {
snprintf(buff, sizeof(buff), "%s", "NG");
set_cmd_result(info, buff, strnlen(buff, sizeof(buff)));
info->cmd_state = 3;
dev_info(&info->client->dev,
"%s: fail to read num of y (%d).\n", __func__, val);
return;
}
snprintf(buff, sizeof(buff), "%u", val);
set_cmd_result(info, buff, strnlen(buff, sizeof(buff)));
info->cmd_state = 2;
dev_info(&info->client->dev, "%s: %s(%d)\n", __func__, buff,
strnlen(buff, sizeof(buff)));
}
static void run_reference_read(void *device_data)
{
struct mms_ts_info *info = (struct mms_ts_info *)device_data;
set_default_result(info);
get_raw_data_all(info, MMS_VSC_CMD_REFER);
info->cmd_state = 2;
/* dev_info(&info->client->dev, "%s: %s(%d)\n", __func__); */
}
static void run_cm_abs_read(void *device_data)
{
struct mms_ts_info *info = (struct mms_ts_info *)device_data;
set_default_result(info);
get_raw_data_all(info, MMS_VSC_CMD_CM_ABS);
get_raw_data_all(info, MMS_VSC_CMD_EXIT);
info->cmd_state = 2;
/* dev_info(&info->client->dev, "%s: %s(%d)\n", __func__); */
}
static void run_cm_delta_read(void *device_data)
{
struct mms_ts_info *info = (struct mms_ts_info *)device_data;
set_default_result(info);
get_raw_data_all(info, MMS_VSC_CMD_CM_DELTA);
get_raw_data_all(info, MMS_VSC_CMD_EXIT);
info->cmd_state = 2;
/* dev_info(&info->client->dev, "%s: %s(%d)\n", __func__); */
}
static void run_intensity_read(void *device_data)
{
struct mms_ts_info *info = (struct mms_ts_info *)device_data;
set_default_result(info);
get_raw_data_all(info, MMS_VSC_CMD_INTENSITY);
info->cmd_state = 2;
/* dev_info(&info->client->dev, "%s: %s(%d)\n", __func__); */
}
static ssize_t store_cmd(struct device *dev, struct device_attribute
*devattr, const char *buf, size_t count)
{
struct mms_ts_info *info = dev_get_drvdata(dev);
struct i2c_client *client = info->client;
char *cur, *start, *end;
char buff[TSP_CMD_STR_LEN] = {0};
int len, i;
struct tsp_cmd *tsp_cmd_ptr = NULL;
char delim = ',';
bool cmd_found = false;
int param_cnt = 0;
int ret;
if (info->cmd_is_running == true) {
dev_err(&info->client->dev, "tsp_cmd: other cmd is running.\n");
goto err_out;
}
/* check lock */
mutex_lock(&info->cmd_lock);
info->cmd_is_running = true;
mutex_unlock(&info->cmd_lock);
info->cmd_state = 1;
for (i = 0; i < ARRAY_SIZE(info->cmd_param); i++)
info->cmd_param[i] = 0;
len = (int)count;
if (*(buf + len - 1) == '\n')
len--;
memset(info->cmd, 0x00, ARRAY_SIZE(info->cmd));
memcpy(info->cmd, buf, len);
cur = strchr(buf, (int)delim);
if (cur)
memcpy(buff, buf, cur - buf);
else
memcpy(buff, buf, len);
/* find command */
list_for_each_entry(tsp_cmd_ptr, &info->cmd_list_head, list) {
if (!strcmp(buff, tsp_cmd_ptr->cmd_name)) {
cmd_found = true;
break;
}
}
/* set not_support_cmd */
if (!cmd_found) {
list_for_each_entry(tsp_cmd_ptr, &info->cmd_list_head, list) {
if (!strcmp("not_support_cmd", tsp_cmd_ptr->cmd_name))
break;
}
}
/* parsing parameters */
if (cur && cmd_found) {
cur++;
start = cur;
memset(buff, 0x00, ARRAY_SIZE(buff));
do {
if (*cur == delim || cur - buf == len) {
end = cur;
memcpy(buff, start, end - start);
*(buff + strlen(buff)) = '\0';
ret = kstrtoint(buff, 10,\
info->cmd_param + param_cnt);
start = cur + 1;
memset(buff, 0x00, ARRAY_SIZE(buff));
param_cnt++;
}
cur++;
} while (cur - buf <= len);
}
dev_info(&client->dev, "cmd = %s\n", tsp_cmd_ptr->cmd_name);
for (i = 0; i < param_cnt; i++)
dev_info(&client->dev, "cmd param %d= %d\n", i,
info->cmd_param[i]);
tsp_cmd_ptr->cmd_func(info);
err_out:
return count;
}
static ssize_t show_cmd_status(struct device *dev,
struct device_attribute *devattr, char *buf)
{
struct mms_ts_info *info = dev_get_drvdata(dev);
char buff[16] = {0};
dev_info(&info->client->dev, "tsp cmd: status:%d\n",
info->cmd_state);
if (info->cmd_state == 0)
snprintf(buff, sizeof(buff), "WAITING");
else if (info->cmd_state == 1)
snprintf(buff, sizeof(buff), "RUNNING");
else if (info->cmd_state == 2)
snprintf(buff, sizeof(buff), "OK");
else if (info->cmd_state == 3)
snprintf(buff, sizeof(buff), "FAIL");
else if (info->cmd_state == 4)
snprintf(buff, sizeof(buff), "NOT_APPLICABLE");
return snprintf(buf, TSP_BUF_SIZE, "%s\n", buff);
}
static ssize_t show_cmd_result(struct device *dev, struct device_attribute
*devattr, char *buf)
{
struct mms_ts_info *info = dev_get_drvdata(dev);
dev_info(&info->client->dev, "tsp cmd: result: %s\n", info->cmd_result);
mutex_lock(&info->cmd_lock);
info->cmd_is_running = false;
mutex_unlock(&info->cmd_lock);
info->cmd_state = 0;
return snprintf(buf, TSP_BUF_SIZE, "%s\n", info->cmd_result);
}
#ifdef ESD_DEBUG
static bool intensity_log_flag;
static ssize_t show_intensity_logging_on(struct device *dev,
struct device_attribute *devattr, char *buf)
{
struct mms_ts_info *info = dev_get_drvdata(dev);
struct i2c_client *client = info->client;
struct file *fp;
char log_data[160] = { 0, };
char buff[16] = { 0, };
mm_segment_t old_fs;
long nwrite;
u32 val;
int i, y, c;
old_fs = get_fs();
set_fs(KERNEL_DS);
#define MELFAS_DEBUG_LOG_PATH "/sdcard/melfas_log"
dev_info(&client->dev, "%s: start.\n", __func__);
fp = filp_open(MELFAS_DEBUG_LOG_PATH, O_RDWR | O_CREAT,
S_IRWXU | S_IRWXG | S_IRWXO);
if (IS_ERR(fp)) {
dev_err(&client->dev, "%s: fail to open log file\n", __func__);
goto open_err;
}
intensity_log_flag = 1;
do {
for (y = 0; y < 3; y++) {
/* for tx chanel 0~2 */
memset(log_data, 0x00, 160);
snprintf(buff, 16, "%1u: ", y);
strncat(log_data, buff, strnlen(buff, 16));
for (i = 0; i < RX_NUM; i++) {
val = get_raw_data_one(info, i, y,
MMS_VSC_CMD_INTENSITY);
snprintf(buff, 16, "%5u, ", val);
strncat(log_data, buff, strnlen(buff, 16));
}
memset(buff, '\n', 2);
c = (y == 2) ? 2 : 1;
strncat(log_data, buff, c);
nwrite = vfs_write(fp, (const char __user *)log_data,
strnlen(log_data, 160), &fp->f_pos);
}
usleep_range(5000);
} while (intensity_log_flag);
filp_close(fp, current->files);
set_fs(old_fs);
return 0;
open_err:
set_fs(old_fs);
return FAIL;
}
static ssize_t show_intensity_logging_off(struct device *dev,
struct device_attribute *devattr, char *buf)
{
struct mms_ts_info *info = dev_get_drvdata(dev);
intensity_log_flag = 0;
usleep_range(10000);
get_raw_data_all(info, MMS_VSC_CMD_EXIT);
return 0;
}
#endif
static DEVICE_ATTR(close_tsp_test, S_IRUGO, show_close_tsp_test, NULL);
static DEVICE_ATTR(cmd, S_IWUSR | S_IWGRP, NULL, store_cmd);
static DEVICE_ATTR(cmd_status, S_IRUGO, show_cmd_status, NULL);
static DEVICE_ATTR(cmd_result, S_IRUGO, show_cmd_result, NULL);
#ifdef ESD_DEBUG
static DEVICE_ATTR(intensity_logging_on, S_IRUGO, show_intensity_logging_on,
NULL);
static DEVICE_ATTR(intensity_logging_off, S_IRUGO, show_intensity_logging_off,
NULL);
#endif
static struct attribute *sec_touch_facotry_attributes[] = {
&dev_attr_close_tsp_test.attr,
&dev_attr_cmd.attr,
&dev_attr_cmd_status.attr,
&dev_attr_cmd_result.attr,
#ifdef ESD_DEBUG
&dev_attr_intensity_logging_on.attr,
&dev_attr_intensity_logging_off.attr,
#endif
NULL,
};
static struct attribute_group sec_touch_factory_attr_group = {
.attrs = sec_touch_facotry_attributes,
};
#endif /* SEC_TSP_FACTORY_TEST */
static int __devinit mms_ts_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct i2c_adapter *adapter = to_i2c_adapter(client->dev.parent);
struct mms_ts_info *info;
struct input_dev *input_dev;
int ret = 0;
char buf[4] = { 0, };
#ifdef SEC_TSP_FACTORY_TEST
int i;
struct device *fac_dev_ts;
#endif
touch_is_pressed = 0;
#if 0
gpio_request(GPIO_OLED_DET, "OLED_DET");
ret = gpio_get_value(GPIO_OLED_DET);
printk(KERN_DEBUG
"[TSP] OLED_DET = %d\n", ret);
if (ret == 0) {
printk(KERN_DEBUG
"[TSP] device wasn't connected to board\n");
return -EIO;
}
#endif
if (!i2c_check_functionality(adapter, I2C_FUNC_I2C))
return -EIO;
info = kzalloc(sizeof(struct mms_ts_info), GFP_KERNEL);
if (!info) {
dev_err(&client->dev, "Failed to allocate memory\n");
ret = -ENOMEM;
goto err_alloc;
}
input_dev = input_allocate_device();
if (!input_dev) {
dev_err(&client->dev, "Failed to allocate memory for input device\n");
ret = -ENOMEM;
goto err_input_alloc;
}
info->client = client;
info->input_dev = input_dev;
info->pdata = client->dev.platform_data;
if (NULL == info->pdata) {
pr_err("failed to get platform data\n");
goto err_reg_input_dev;
}
info->irq = -1;
mutex_init(&info->lock);
if (info->pdata) {
info->max_x = info->pdata->max_x;
info->max_y = info->pdata->max_y;
info->invert_x = info->pdata->invert_x;
info->invert_y = info->pdata->invert_y;
info->config_fw_version = info->pdata->config_fw_version;
info->register_cb = info->pdata->register_cb;
} else {
info->max_x = 720;
info->max_y = 1280;
}
snprintf(info->phys, sizeof(info->phys),
"%s/input0", dev_name(&client->dev));
input_dev->name = "sec_touchscreen"; /*= "Melfas MMSxxx Touchscreen";*/
input_dev->phys = info->phys;
input_dev->id.bustype = BUS_I2C;
input_dev->dev.parent = &client->dev;
__set_bit(EV_ABS, input_dev->evbit);
__set_bit(INPUT_PROP_DIRECT, input_dev->propbit);
input_mt_init_slots(input_dev, MAX_FINGERS);
input_set_abs_params(input_dev, ABS_MT_WIDTH_MAJOR,
0, MAX_WIDTH, 0, 0);
input_set_abs_params(input_dev, ABS_MT_POSITION_X,
0, (info->max_x)-1, 0, 0);
input_set_abs_params(input_dev, ABS_MT_POSITION_Y,
0, (info->max_y)-1, 0, 0);
input_set_abs_params(input_dev, ABS_MT_TOUCH_MAJOR,
0, MAX_PRESSURE, 0, 0);
input_set_abs_params(input_dev, ABS_MT_TOUCH_MINOR,
0, MAX_PRESSURE, 0, 0);
input_set_abs_params(input_dev, ABS_MT_ANGLE,
MIN_ANGLE, MAX_ANGLE, 0, 0);
input_set_abs_params(input_dev, ABS_MT_PALM,
0, 1, 0, 0);
input_set_drvdata(input_dev, info);
ret = input_register_device(input_dev);
if (ret) {
dev_err(&client->dev, "failed to register input dev (%d)\n",
ret);
goto err_reg_input_dev;
}
#if TOUCH_BOOSTER
mutex_init(&info->dvfs_lock);
INIT_DELAYED_WORK(&info->work_dvfs_off, set_dvfs_off);
INIT_DELAYED_WORK(&info->work_dvfs_chg, change_dvfs_lock);
bus_dev = dev_get("exynos-busfreq");
info->cpufreq_level = -1;
info->dvfs_lock_status = false;
#endif
i2c_set_clientdata(client, info);
info->pdata->power(true);
msleep(100);
ret = i2c_master_recv(client, buf, 1);
if (ret < 0) { /* tsp connect check */
pr_err("%s: i2c fail...tsp driver unload [%d], Add[%d]\n",
__func__, ret, info->client->addr);
goto err_config;
}
ret = mms_ts_fw_load(info);
/* ret = mms_ts_fw_info(info); */
if (ret) {
dev_err(&client->dev, "failed to initialize (%d)\n", ret);
goto err_config;
}
info->enabled = true;
info->callbacks.inform_charger = melfas_ta_cb;
if (info->register_cb)
info->register_cb(&info->callbacks);
#ifdef CONFIG_HAS_EARLYSUSPEND
info->early_suspend.level = EARLY_SUSPEND_LEVEL_BLANK_SCREEN + 1;
info->early_suspend.suspend = mms_ts_early_suspend;
info->early_suspend.resume = mms_ts_late_resume;
register_early_suspend(&info->early_suspend);
#endif
sec_touchscreen = device_create(sec_class,
NULL, 0, info, "sec_touchscreen");
if (IS_ERR(sec_touchscreen)) {
dev_err(&client->dev,
"Failed to create device for the sysfs1\n");
ret = -ENODEV;
}
#ifdef SEC_TSP_FACTORY_TEST
INIT_LIST_HEAD(&info->cmd_list_head);
for (i = 0; i < ARRAY_SIZE(tsp_cmds); i++)
list_add_tail(&tsp_cmds[i].list, &info->cmd_list_head);
mutex_init(&info->cmd_lock);
info->cmd_is_running = false;
fac_dev_ts = device_create(sec_class,
NULL, 0, info, "tsp");
if (IS_ERR(fac_dev_ts))
dev_err(&client->dev, "Failed to create device for the sysfs\n");
ret = sysfs_create_group(&fac_dev_ts->kobj,
&sec_touch_factory_attr_group);
if (ret)
dev_err(&client->dev, "Failed to create sysfs group\n");
#endif
return 0;
err_config:
input_unregister_device(input_dev);
err_reg_input_dev:
input_free_device(input_dev);
err_input_alloc:
input_dev = NULL;
kfree(info);
err_alloc:
return ret;
}
static int __devexit mms_ts_remove(struct i2c_client *client)
{
struct mms_ts_info *info = i2c_get_clientdata(client);
unregister_early_suspend(&info->early_suspend);
if (info->irq >= 0)
free_irq(info->irq, info);
input_unregister_device(info->input_dev);
kfree(info);
return 0;
}
#if defined(CONFIG_PM) || defined(CONFIG_HAS_EARLYSUSPEND)
static int mms_ts_suspend(struct device *dev)
{
struct i2c_client *client = to_i2c_client(dev);
struct mms_ts_info *info = i2c_get_clientdata(client);
if (!info->enabled)
return 0;
dev_notice(&info->client->dev, "%s: users=%d\n", __func__,
info->input_dev->users);
disable_irq(info->irq);
info->enabled = false;
touch_is_pressed = 0;
release_all_fingers(info);
info->pdata->power(false);
/* This delay needs to prevent unstable POR by
rapid frequently pressing of PWR key. */
msleep(50);
return 0;
}
static int mms_ts_resume(struct device *dev)
{
struct i2c_client *client = to_i2c_client(dev);
struct mms_ts_info *info = i2c_get_clientdata(client);
int ret = 0;
if (info->enabled)
return 0;
dev_notice(&info->client->dev, "%s: users=%d\n", __func__,
info->input_dev->users);
info->pdata->power(true);
msleep(120);
if (info->ta_status) {
dev_notice(&client->dev, "TA connect!!!\n");
i2c_smbus_write_byte_data(info->client, 0x33, 0x1);
} else {
dev_notice(&client->dev, "TA disconnect!!!\n");
i2c_smbus_write_byte_data(info->client, 0x33, 0x2);
}
/* Because irq_type by EXT_INTxCON register is changed to low_level
* after wakeup, irq_type set to falling edge interrupt again.
*/
enable_irq(info->irq);
info->enabled = true;
mms_set_noise_mode(info);
return 0;
}
#endif
#ifdef CONFIG_HAS_EARLYSUSPEND
static void mms_ts_early_suspend(struct early_suspend *h)
{
struct mms_ts_info *info;
info = container_of(h, struct mms_ts_info, early_suspend);
mms_ts_suspend(&info->client->dev);
}
static void mms_ts_late_resume(struct early_suspend *h)
{
struct mms_ts_info *info;
info = container_of(h, struct mms_ts_info, early_suspend);
mms_ts_resume(&info->client->dev);
}
#endif
#if defined(CONFIG_PM) && !defined(CONFIG_HAS_EARLYSUSPEND)
static const struct dev_pm_ops mms_ts_pm_ops = {
.suspend = mms_ts_suspend,
.resume = mms_ts_resume,
#ifdef CONFIG_HIBERNATION
.freeze = mms_ts_suspend,
.thaw = mms_ts_resume,
.restore = mms_ts_resume,
#endif
};
#endif
static const struct i2c_device_id mms_ts_id[] = {
{MELFAS_TS_NAME, 0},
{}
};
MODULE_DEVICE_TABLE(i2c, mms_ts_id);
static struct i2c_driver mms_ts_driver = {
.probe = mms_ts_probe,
.remove = __devexit_p(mms_ts_remove),
.driver = {
.name = MELFAS_TS_NAME,
#if defined(CONFIG_PM) && !defined(CONFIG_HAS_EARLYSUSPEND)
.pm = &mms_ts_pm_ops,
#endif
},
.id_table = mms_ts_id,
};
static int __init mms_ts_init(void)
{
return i2c_add_driver(&mms_ts_driver);
}
static void __exit mms_ts_exit(void)
{
i2c_del_driver(&mms_ts_driver);
}
module_init(mms_ts_init);
module_exit(mms_ts_exit);
/* Module information */
MODULE_DESCRIPTION("Touchscreen driver for Melfas MMS-series controllers");
MODULE_LICENSE("GPL");
| kunato/s3-u6 | drivers/input/touchscreen/mms_ts.c | C | gpl-2.0 | 78,817 |
<html lang="en">
<head>
<title>Expressions - Using as</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="Using as">
<meta name="generator" content="makeinfo 4.8">
<link title="Top" rel="start" href="index.html#Top">
<link rel="prev" href="Symbols.html#Symbols" title="Symbols">
<link rel="next" href="Pseudo-Ops.html#Pseudo-Ops" title="Pseudo Ops">
<link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage">
<!--
This file documents the GNU Assembler "as".
Copyright (C) 1991-2018 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3
or any later version published by the Free Software Foundation;
with no Invariant Sections, with no Front-Cover Texts, and with no
Back-Cover Texts. A copy of the license is included in the
section entitled ``GNU Free Documentation License''.
-->
<meta http-equiv="Content-Style-Type" content="text/css">
<style type="text/css"><!--
pre.display { font-family:inherit }
pre.format { font-family:inherit }
pre.smalldisplay { font-family:inherit; font-size:smaller }
pre.smallformat { font-family:inherit; font-size:smaller }
pre.smallexample { font-size:smaller }
pre.smalllisp { font-size:smaller }
span.sc { font-variant:small-caps }
span.roman { font-family:serif; font-weight:normal; }
span.sansserif { font-family:sans-serif; font-weight:normal; }
--></style>
</head>
<body>
<div class="node">
<p>
<a name="Expressions"></a>
Next: <a rel="next" accesskey="n" href="Pseudo-Ops.html#Pseudo-Ops">Pseudo Ops</a>,
Previous: <a rel="previous" accesskey="p" href="Symbols.html#Symbols">Symbols</a>,
Up: <a rel="up" accesskey="u" href="index.html#Top">Top</a>
<hr>
</div>
<h2 class="chapter">6 Expressions</h2>
<p><a name="index-expressions-243"></a><a name="index-addresses-244"></a><a name="index-numeric-values-245"></a>An <dfn>expression</dfn> specifies an address or numeric value.
Whitespace may precede and/or follow an expression.
<p>The result of an expression must be an absolute number, or else an offset into
a particular section. If an expression is not absolute, and there is not
enough information when <samp><span class="command">as</span></samp> sees the expression to know its
section, a second pass over the source program might be necessary to interpret
the expression—but the second pass is currently not implemented.
<samp><span class="command">as</span></samp> aborts with an error message in this situation.
<ul class="menu">
<li><a accesskey="1" href="Empty-Exprs.html#Empty-Exprs">Empty Exprs</a>: Empty Expressions
<li><a accesskey="2" href="Integer-Exprs.html#Integer-Exprs">Integer Exprs</a>: Integer Expressions
</ul>
</body></html>
| jocelynmass/nrf51 | toolchain/arm_cm0/share/doc/gcc-arm-none-eabi/html/as.html/Expressions.html | HTML | gpl-2.0 | 2,889 |
#userIcon.hear {
-fx-image: url(../img/eye.png);
}
#userIcon.me {
-fx-image: url(../img/eye.png);
-fx-opacity: 0.1;
}
#userIcon.me:hover {
-fx-image: url(../img/eye.png);
-fx-opacity: 0.3;
}
#userIcon.master {
-fx-image: url(../img/crown.png);
}
#userItem {
-fx-background-color: #E4F6F9;
-fx-background-radius: 10;
}
Label {
-fx-text-fill: #8EBDC4;
} | bdh92123/share_all | src/main/resources/css/userCell.css | CSS | gpl-2.0 | 364 |
#!/bin/sh
# Copyright (C) 2012 Red Hat, Inc. All rights reserved.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions
# of the GNU General Public License v.2.
#
# 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
. lib/inittest
test -e LOCAL_LVMETAD || skip
aux prepare_devs 2
pvcreate --metadatatype 1 "$dev1"
should vgscan --cache
pvs | should grep "$dev1"
vgcreate --metadatatype 1 $vg1 "$dev1"
should vgscan --cache
vgs | should grep $vg1
pvs | should grep "$dev1"
# check for RHBZ 1080189 -- SEGV in lvremove/vgremove
pvcreate -ff -y --metadatatype 1 "$dev1" "$dev2"
vgcreate --metadatatype 1 $vg1 "$dev1" "$dev2"
lvcreate -l1 $vg1
pvremove -ff -y "$dev2"
vgchange -an $vg1
not lvremove $vg1
not vgremove -ff -y $vg1
| twitter/bittern | lvm2/test/shell/lvmetad-lvm1.sh | Shell | gpl-2.0 | 972 |
/* $Id$ */
/*
Copyright (C) 2003 - 2013 by David White <[email protected]>
Part of the Battle for Wesnoth Project http://www.wesnoth.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.
See the COPYING file for more details.
*/
#ifndef VIDEO_HPP_INCLUDED
#define VIDEO_HPP_INCLUDED
#include "events.hpp"
#include "exceptions.hpp"
#include "lua_jailbreak_exception.hpp"
#include <boost/utility.hpp>
struct surface;
//possible flags when setting video modes
#define FULL_SCREEN SDL_FULLSCREEN
surface display_format_alpha(surface surf);
surface get_video_surface();
SDL_Rect screen_area();
bool non_interactive();
//which areas of the screen will be updated when the buffer is flipped?
void update_rect(size_t x, size_t y, size_t w, size_t h);
void update_rect(const SDL_Rect& rect);
void update_whole_screen();
class CVideo : private boost::noncopyable {
public:
enum FAKE_TYPES {
NO_FAKE,
FAKE,
FAKE_TEST
};
CVideo(FAKE_TYPES type = NO_FAKE);
~CVideo();
int bppForMode( int x, int y, int flags);
int modePossible( int x, int y, int bits_per_pixel, int flags, bool current_screen_optimal=false);
int setMode( int x, int y, int bits_per_pixel, int flags );
//did the mode change, since the last call to the modeChanged() method?
bool modeChanged();
//functions to get the dimensions of the current video-mode
int getx() const;
int gety() const;
//blits a surface with black as alpha
void blit_surface(int x, int y, surface surf, SDL_Rect* srcrect=NULL, SDL_Rect* clip_rect=NULL);
void flip();
surface& getSurface();
bool isFullScreen() const;
struct error : public game::error
{
error() : game::error("Video initialization failed") {}
};
class quit
: public tlua_jailbreak_exception
{
public:
quit()
: tlua_jailbreak_exception()
{
}
private:
IMPLEMENT_LUA_JAILBREAK_EXCEPTION(quit)
};
//functions to allow changing video modes when 16BPP is emulated
void setBpp( int bpp );
int getBpp();
void make_fake();
/**
* Creates a fake frame buffer for the unit tests.
*
* @param width The width of the buffer.
* @param height The height of the buffer.
* @param bpp The bpp of the buffer.
*/
void make_test_fake(const unsigned width = 1024,
const unsigned height = 768, const unsigned bpp = 32);
bool faked() const { return fake_screen_; }
//functions to set and clear 'help strings'. A 'help string' is like a tooltip, but it appears
//at the bottom of the screen, so as to not be intrusive. Setting a help string sets what
//is currently displayed there.
int set_help_string(const std::string& str);
void clear_help_string(int handle);
void clear_all_help_strings();
//function to stop the screen being redrawn. Anything that happens while
//the update is locked will be hidden from the user's view.
//note that this function is re-entrant, meaning that if lock_updates(true)
//is called twice, lock_updates(false) must be called twice to unlock
//updates.
void lock_updates(bool value);
bool update_locked() const;
private:
void initSDL();
bool mode_changed_;
int bpp_; // Store real bits per pixel
//if there is no display at all, but we 'fake' it for clients
bool fake_screen_;
//variables for help strings
int help_string_;
int updatesLocked_;
};
//an object which will lock the display for the duration of its lifetime.
struct update_locker
{
update_locker(CVideo& v, bool lock=true) : video(v), unlock(lock) {
if(lock) {
video.lock_updates(true);
}
}
~update_locker() {
unlock_update();
}
void unlock_update() {
if(unlock) {
video.lock_updates(false);
unlock = false;
}
}
private:
CVideo& video;
bool unlock;
};
class resize_monitor : public events::pump_monitor {
void process(events::pump_info &info);
};
//an object which prevents resizing of the screen occurring during
//its lifetime.
struct resize_lock {
resize_lock();
~resize_lock();
};
#endif
| battle-for-wesnoth/svn | src/video.hpp | C++ | gpl-2.0 | 4,277 |
/*
* Fast Userspace Mutexes (which I call "Futexes!").
* (C) Rusty Russell, IBM 2002
*
* Generalized futexes, futex requeueing, misc fixes by Ingo Molnar
* (C) Copyright 2003 Red Hat Inc, All Rights Reserved
*
* Removed page pinning, fix privately mapped COW pages and other cleanups
* (C) Copyright 2003, 2004 Jamie Lokier
*
* Robust futex support started by Ingo Molnar
* (C) Copyright 2006 Red Hat Inc, All Rights Reserved
* Thanks to Thomas Gleixner for suggestions, analysis and fixes.
*
* PI-futex support started by Ingo Molnar and Thomas Gleixner
* Copyright (C) 2006 Red Hat, Inc., Ingo Molnar <[email protected]>
* Copyright (C) 2006 Timesys Corp., Thomas Gleixner <[email protected]>
*
* PRIVATE futexes by Eric Dumazet
* Copyright (C) 2007 Eric Dumazet <[email protected]>
*
* Requeue-PI support by Darren Hart <[email protected]>
* Copyright (C) IBM Corporation, 2009
* Thanks to Thomas Gleixner for conceptual design and careful reviews.
*
* Thanks to Ben LaHaise for yelling "hashed waitqueues" loudly
* enough at me, Linus for the original (flawed) idea, Matthew
* Kirkwood for proof-of-concept implementation.
*
* "The futexes are also cursed."
* "But they come in a choice of three flavours!"
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/slab.h>
#include <linux/poll.h>
#include <linux/fs.h>
#include <linux/file.h>
#include <linux/jhash.h>
#include <linux/init.h>
#include <linux/futex.h>
#include <linux/mount.h>
#include <linux/pagemap.h>
#include <linux/syscalls.h>
#include <linux/signal.h>
#include <linux/export.h>
#include <linux/magic.h>
#include <linux/pid.h>
#include <linux/nsproxy.h>
#include <linux/ptrace.h>
#include <linux/sched/rt.h>
#include <linux/freezer.h>
#include <linux/hugetlb.h>
#include <asm/futex.h>
#include "rtmutex_common.h"
#ifndef CONFIG_HAVE_FUTEX_CMPXCHG
int __read_mostly futex_cmpxchg_enabled;
#endif
#define FUTEX_HASHBITS (CONFIG_BASE_SMALL ? 4 : 8)
/*
* Futex flags used to encode options to functions and preserve them across
* restarts.
*/
#define FLAGS_SHARED 0x01
#define FLAGS_CLOCKRT 0x02
#define FLAGS_HAS_TIMEOUT 0x04
/*
* Priority Inheritance state:
*/
struct futex_pi_state {
/*
* list of 'owned' pi_state instances - these have to be
* cleaned up in do_exit() if the task exits prematurely:
*/
struct list_head list;
/*
* The PI object:
*/
struct rt_mutex pi_mutex;
struct task_struct *owner;
atomic_t refcount;
union futex_key key;
};
/**
* struct futex_q - The hashed futex queue entry, one per waiting task
* @list: priority-sorted list of tasks waiting on this futex
* @task: the task waiting on the futex
* @lock_ptr: the hash bucket lock
* @key: the key the futex is hashed on
* @pi_state: optional priority inheritance state
* @rt_waiter: rt_waiter storage for use with requeue_pi
* @requeue_pi_key: the requeue_pi target futex key
* @bitset: bitset for the optional bitmasked wakeup
*
* We use this hashed waitqueue, instead of a normal wait_queue_t, so
* we can wake only the relevant ones (hashed queues may be shared).
*
* A futex_q has a woken state, just like tasks have TASK_RUNNING.
* It is considered woken when plist_node_empty(&q->list) || q->lock_ptr == 0.
* The order of wakeup is always to make the first condition true, then
* the second.
*
* PI futexes are typically woken before they are removed from the hash list via
* the rt_mutex code. See unqueue_me_pi().
*/
struct futex_q {
struct plist_node list;
struct task_struct *task;
spinlock_t *lock_ptr;
union futex_key key;
struct futex_pi_state *pi_state;
struct rt_mutex_waiter *rt_waiter;
union futex_key *requeue_pi_key;
u32 bitset;
};
static const struct futex_q futex_q_init = {
/* list gets initialized in queue_me()*/
.key = FUTEX_KEY_INIT,
.bitset = FUTEX_BITSET_MATCH_ANY
};
/*
* Hash buckets are shared by all the futex_keys that hash to the same
* location. Each key may have multiple futex_q structures, one for each task
* waiting on a futex.
*/
struct futex_hash_bucket {
spinlock_t lock;
struct plist_head chain;
};
static struct futex_hash_bucket futex_queues[1<<FUTEX_HASHBITS];
/*
* We hash on the keys returned from get_futex_key (see below).
*/
static struct futex_hash_bucket *hash_futex(union futex_key *key)
{
u32 hash = jhash2((u32*)&key->both.word,
(sizeof(key->both.word)+sizeof(key->both.ptr))/4,
key->both.offset);
return &futex_queues[hash & ((1 << FUTEX_HASHBITS)-1)];
}
/*
* Return 1 if two futex_keys are equal, 0 otherwise.
*/
static inline int match_futex(union futex_key *key1, union futex_key *key2)
{
return (key1 && key2
&& key1->both.word == key2->both.word
&& key1->both.ptr == key2->both.ptr
&& key1->both.offset == key2->both.offset);
}
/*
* Take a reference to the resource addressed by a key.
* Can be called while holding spinlocks.
*
*/
static void get_futex_key_refs(union futex_key *key)
{
if (!key->both.ptr)
return;
switch (key->both.offset & (FUT_OFF_INODE|FUT_OFF_MMSHARED)) {
case FUT_OFF_INODE:
ihold(key->shared.inode);
break;
case FUT_OFF_MMSHARED:
atomic_inc(&key->private.mm->mm_count);
break;
}
}
/*
* Drop a reference to the resource addressed by a key.
* The hash bucket spinlock must not be held.
*/
static void drop_futex_key_refs(union futex_key *key)
{
if (!key->both.ptr) {
/* If we're here then we tried to put a key we failed to get */
WARN_ON_ONCE(1);
return;
}
switch (key->both.offset & (FUT_OFF_INODE|FUT_OFF_MMSHARED)) {
case FUT_OFF_INODE:
iput(key->shared.inode);
break;
case FUT_OFF_MMSHARED:
mmdrop(key->private.mm);
break;
}
}
/**
* get_futex_key() - Get parameters which are the keys for a futex
* @uaddr: virtual address of the futex
* @fshared: 0 for a PROCESS_PRIVATE futex, 1 for PROCESS_SHARED
* @key: address where result is stored.
* @rw: mapping needs to be read/write (values: VERIFY_READ,
* VERIFY_WRITE)
*
* Return: a negative error code or 0
*
* The key words are stored in *key on success.
*
* For shared mappings, it's (page->index, file_inode(vma->vm_file),
* offset_within_page). For private mappings, it's (uaddr, current->mm).
* We can usually work out the index without swapping in the page.
*
* lock_page() might sleep, the caller should not hold a spinlock.
*/
static int
get_futex_key(u32 __user *uaddr, int fshared, union futex_key *key, int rw)
{
unsigned long address = (unsigned long)uaddr;
struct mm_struct *mm = current->mm;
struct page *page, *page_head;
int err, ro = 0;
/*
* The futex address must be "naturally" aligned.
*/
key->both.offset = address % PAGE_SIZE;
if (unlikely((address % sizeof(u32)) != 0))
return -EINVAL;
address -= key->both.offset;
/*
* PROCESS_PRIVATE futexes are fast.
* As the mm cannot disappear under us and the 'key' only needs
* virtual address, we dont even have to find the underlying vma.
* Note : We do have to check 'uaddr' is a valid user address,
* but access_ok() should be faster than find_vma()
*/
if (!fshared) {
if (unlikely(!access_ok(VERIFY_WRITE, uaddr, sizeof(u32))))
return -EFAULT;
key->private.mm = mm;
key->private.address = address;
get_futex_key_refs(key);
return 0;
}
again:
err = get_user_pages_fast(address, 1, 1, &page);
/*
* If write access is not required (eg. FUTEX_WAIT), try
* and get read-only access.
*/
if (err == -EFAULT && rw == VERIFY_READ) {
err = get_user_pages_fast(address, 1, 0, &page);
ro = 1;
}
if (err < 0)
return err;
else
err = 0;
#ifdef CONFIG_TRANSPARENT_HUGEPAGE
page_head = page;
if (unlikely(PageTail(page))) {
put_page(page);
/* serialize against __split_huge_page_splitting() */
local_irq_disable();
if (likely(__get_user_pages_fast(address, 1, !ro, &page) == 1)) {
page_head = compound_head(page);
/*
* page_head is valid pointer but we must pin
* it before taking the PG_lock and/or
* PG_compound_lock. The moment we re-enable
* irqs __split_huge_page_splitting() can
* return and the head page can be freed from
* under us. We can't take the PG_lock and/or
* PG_compound_lock on a page that could be
* freed from under us.
*/
if (page != page_head) {
get_page(page_head);
put_page(page);
}
local_irq_enable();
} else {
local_irq_enable();
goto again;
}
}
#else
page_head = compound_head(page);
if (page != page_head) {
get_page(page_head);
put_page(page);
}
#endif
lock_page(page_head);
/*
* If page_head->mapping is NULL, then it cannot be a PageAnon
* page; but it might be the ZERO_PAGE or in the gate area or
* in a special mapping (all cases which we are happy to fail);
* or it may have been a good file page when get_user_pages_fast
* found it, but truncated or holepunched or subjected to
* invalidate_complete_page2 before we got the page lock (also
* cases which we are happy to fail). And we hold a reference,
* so refcount care in invalidate_complete_page's remove_mapping
* prevents drop_caches from setting mapping to NULL beneath us.
*
* The case we do have to guard against is when memory pressure made
* shmem_writepage move it from filecache to swapcache beneath us:
* an unlikely race, but we do need to retry for page_head->mapping.
*/
if (!page_head->mapping) {
int shmem_swizzled = PageSwapCache(page_head);
unlock_page(page_head);
put_page(page_head);
if (shmem_swizzled)
goto again;
return -EFAULT;
}
/*
* Private mappings are handled in a simple way.
*
* NOTE: When userspace waits on a MAP_SHARED mapping, even if
* it's a read-only handle, it's expected that futexes attach to
* the object not the particular process.
*/
if (PageAnon(page_head)) {
/*
* A RO anonymous page will never change and thus doesn't make
* sense for futex operations.
*/
if (ro) {
err = -EFAULT;
goto out;
}
key->both.offset |= FUT_OFF_MMSHARED; /* ref taken on mm */
key->private.mm = mm;
key->private.address = address;
} else {
key->both.offset |= FUT_OFF_INODE; /* inode-based key */
key->shared.inode = page_head->mapping->host;
key->shared.pgoff = basepage_index(page);
}
get_futex_key_refs(key);
out:
unlock_page(page_head);
put_page(page_head);
return err;
}
static inline void put_futex_key(union futex_key *key)
{
drop_futex_key_refs(key);
}
/**
* fault_in_user_writeable() - Fault in user address and verify RW access
* @uaddr: pointer to faulting user space address
*
* Slow path to fixup the fault we just took in the atomic write
* access to @uaddr.
*
* We have no generic implementation of a non-destructive write to the
* user address. We know that we faulted in the atomic pagefault
* disabled section so we can as well avoid the #PF overhead by
* calling get_user_pages() right away.
*/
static int fault_in_user_writeable(u32 __user *uaddr)
{
struct mm_struct *mm = current->mm;
int ret;
down_read(&mm->mmap_sem);
ret = fixup_user_fault(current, mm, (unsigned long)uaddr,
FAULT_FLAG_WRITE);
up_read(&mm->mmap_sem);
return ret < 0 ? ret : 0;
}
/**
* futex_top_waiter() - Return the highest priority waiter on a futex
* @hb: the hash bucket the futex_q's reside in
* @key: the futex key (to distinguish it from other futex futex_q's)
*
* Must be called with the hb lock held.
*/
static struct futex_q *futex_top_waiter(struct futex_hash_bucket *hb,
union futex_key *key)
{
struct futex_q *this;
plist_for_each_entry(this, &hb->chain, list) {
if (match_futex(&this->key, key))
return this;
}
return NULL;
}
static int cmpxchg_futex_value_locked(u32 *curval, u32 __user *uaddr,
u32 uval, u32 newval)
{
int ret;
pagefault_disable();
ret = futex_atomic_cmpxchg_inatomic(curval, uaddr, uval, newval);
pagefault_enable();
return ret;
}
static int get_futex_value_locked(u32 *dest, u32 __user *from)
{
int ret;
pagefault_disable();
ret = __copy_from_user_inatomic(dest, from, sizeof(u32));
pagefault_enable();
return ret ? -EFAULT : 0;
}
/*
* PI code:
*/
static int refill_pi_state_cache(void)
{
struct futex_pi_state *pi_state;
if (likely(current->pi_state_cache))
return 0;
pi_state = kzalloc(sizeof(*pi_state), GFP_KERNEL);
if (!pi_state)
return -ENOMEM;
INIT_LIST_HEAD(&pi_state->list);
/* pi_mutex gets initialized later */
pi_state->owner = NULL;
atomic_set(&pi_state->refcount, 1);
pi_state->key = FUTEX_KEY_INIT;
current->pi_state_cache = pi_state;
return 0;
}
static struct futex_pi_state * alloc_pi_state(void)
{
struct futex_pi_state *pi_state = current->pi_state_cache;
WARN_ON(!pi_state);
current->pi_state_cache = NULL;
return pi_state;
}
static void free_pi_state(struct futex_pi_state *pi_state)
{
if (!atomic_dec_and_test(&pi_state->refcount))
return;
/*
* If pi_state->owner is NULL, the owner is most probably dying
* and has cleaned up the pi_state already
*/
if (pi_state->owner) {
raw_spin_lock_irq(&pi_state->owner->pi_lock);
list_del_init(&pi_state->list);
raw_spin_unlock_irq(&pi_state->owner->pi_lock);
rt_mutex_proxy_unlock(&pi_state->pi_mutex, pi_state->owner);
}
if (current->pi_state_cache)
kfree(pi_state);
else {
/*
* pi_state->list is already empty.
* clear pi_state->owner.
* refcount is at 0 - put it back to 1.
*/
pi_state->owner = NULL;
atomic_set(&pi_state->refcount, 1);
current->pi_state_cache = pi_state;
}
}
/*
* Look up the task based on what TID userspace gave us.
* We dont trust it.
*/
static struct task_struct * futex_find_get_task(pid_t pid)
{
struct task_struct *p;
rcu_read_lock();
p = find_task_by_vpid(pid);
if (p)
get_task_struct(p);
rcu_read_unlock();
return p;
}
/*
* This task is holding PI mutexes at exit time => bad.
* Kernel cleans up PI-state, but userspace is likely hosed.
* (Robust-futex cleanup is separate and might save the day for userspace.)
*/
void exit_pi_state_list(struct task_struct *curr)
{
struct list_head *next, *head = &curr->pi_state_list;
struct futex_pi_state *pi_state;
struct futex_hash_bucket *hb;
union futex_key key = FUTEX_KEY_INIT;
if (!futex_cmpxchg_enabled)
return;
/*
* We are a ZOMBIE and nobody can enqueue itself on
* pi_state_list anymore, but we have to be careful
* versus waiters unqueueing themselves:
*/
raw_spin_lock_irq(&curr->pi_lock);
while (!list_empty(head)) {
next = head->next;
pi_state = list_entry(next, struct futex_pi_state, list);
key = pi_state->key;
hb = hash_futex(&key);
raw_spin_unlock_irq(&curr->pi_lock);
spin_lock(&hb->lock);
raw_spin_lock_irq(&curr->pi_lock);
/*
* We dropped the pi-lock, so re-check whether this
* task still owns the PI-state:
*/
if (head->next != next) {
spin_unlock(&hb->lock);
continue;
}
WARN_ON(pi_state->owner != curr);
WARN_ON(list_empty(&pi_state->list));
list_del_init(&pi_state->list);
pi_state->owner = NULL;
raw_spin_unlock_irq(&curr->pi_lock);
rt_mutex_unlock(&pi_state->pi_mutex);
spin_unlock(&hb->lock);
raw_spin_lock_irq(&curr->pi_lock);
}
raw_spin_unlock_irq(&curr->pi_lock);
}
/*
* We need to check the following states:
*
* Waiter | pi_state | pi->owner | uTID | uODIED | ?
*
* [1] NULL | --- | --- | 0 | 0/1 | Valid
* [2] NULL | --- | --- | >0 | 0/1 | Valid
*
* [3] Found | NULL | -- | Any | 0/1 | Invalid
*
* [4] Found | Found | NULL | 0 | 1 | Valid
* [5] Found | Found | NULL | >0 | 1 | Invalid
*
* [6] Found | Found | task | 0 | 1 | Valid
*
* [7] Found | Found | NULL | Any | 0 | Invalid
*
* [8] Found | Found | task | ==taskTID | 0/1 | Valid
* [9] Found | Found | task | 0 | 0 | Invalid
* [10] Found | Found | task | !=taskTID | 0/1 | Invalid
*
* [1] Indicates that the kernel can acquire the futex atomically. We
* came came here due to a stale FUTEX_WAITERS/FUTEX_OWNER_DIED bit.
*
* [2] Valid, if TID does not belong to a kernel thread. If no matching
* thread is found then it indicates that the owner TID has died.
*
* [3] Invalid. The waiter is queued on a non PI futex
*
* [4] Valid state after exit_robust_list(), which sets the user space
* value to FUTEX_WAITERS | FUTEX_OWNER_DIED.
*
* [5] The user space value got manipulated between exit_robust_list()
* and exit_pi_state_list()
*
* [6] Valid state after exit_pi_state_list() which sets the new owner in
* the pi_state but cannot access the user space value.
*
* [7] pi_state->owner can only be NULL when the OWNER_DIED bit is set.
*
* [8] Owner and user space value match
*
* [9] There is no transient state which sets the user space TID to 0
* except exit_robust_list(), but this is indicated by the
* FUTEX_OWNER_DIED bit. See [4]
*
* [10] There is no transient state which leaves owner and user space
* TID out of sync.
*/
static int
lookup_pi_state(u32 uval, struct futex_hash_bucket *hb,
union futex_key *key, struct futex_pi_state **ps)
{
struct futex_pi_state *pi_state = NULL;
struct futex_q *this, *next;
struct plist_head *head;
struct task_struct *p;
pid_t pid = uval & FUTEX_TID_MASK;
head = &hb->chain;
plist_for_each_entry_safe(this, next, head, list) {
if (match_futex(&this->key, key)) {
/*
* Sanity check the waiter before increasing
* the refcount and attaching to it.
*/
pi_state = this->pi_state;
/*
* Userspace might have messed up non-PI and
* PI futexes [3]
*/
if (unlikely(!pi_state))
return -EINVAL;
WARN_ON(!atomic_read(&pi_state->refcount));
/*
* Handle the owner died case:
*/
if (uval & FUTEX_OWNER_DIED) {
/*
* exit_pi_state_list sets owner to NULL and
* wakes the topmost waiter. The task which
* acquires the pi_state->rt_mutex will fixup
* owner.
*/
if (!pi_state->owner) {
/*
* No pi state owner, but the user
* space TID is not 0. Inconsistent
* state. [5]
*/
if (pid)
return -EINVAL;
/*
* Take a ref on the state and
* return. [4]
*/
goto out_state;
}
/*
* If TID is 0, then either the dying owner
* has not yet executed exit_pi_state_list()
* or some waiter acquired the rtmutex in the
* pi state, but did not yet fixup the TID in
* user space.
*
* Take a ref on the state and return. [6]
*/
if (!pid)
goto out_state;
} else {
/*
* If the owner died bit is not set,
* then the pi_state must have an
* owner. [7]
*/
if (!pi_state->owner)
return -EINVAL;
}
/*
* Bail out if user space manipulated the
* futex value. If pi state exists then the
* owner TID must be the same as the user
* space TID. [9/10]
*/
if (pid != task_pid_vnr(pi_state->owner))
return -EINVAL;
out_state:
atomic_inc(&pi_state->refcount);
*ps = pi_state;
return 0;
}
}
/*
* We are the first waiter - try to look up the real owner and attach
* the new pi_state to it, but bail out when TID = 0 [1]
*/
if (!pid)
return -ESRCH;
p = futex_find_get_task(pid);
if (!p)
return -ESRCH;
if (!p->mm) {
put_task_struct(p);
return -EPERM;
}
/*
* We need to look at the task state flags to figure out,
* whether the task is exiting. To protect against the do_exit
* change of the task flags, we do this protected by
* p->pi_lock:
*/
raw_spin_lock_irq(&p->pi_lock);
if (unlikely(p->flags & PF_EXITING)) {
/*
* The task is on the way out. When PF_EXITPIDONE is
* set, we know that the task has finished the
* cleanup:
*/
int ret = (p->flags & PF_EXITPIDONE) ? -ESRCH : -EAGAIN;
raw_spin_unlock_irq(&p->pi_lock);
put_task_struct(p);
return ret;
}
/*
* No existing pi state. First waiter. [2]
*/
pi_state = alloc_pi_state();
/*
* Initialize the pi_mutex in locked state and make 'p'
* the owner of it:
*/
rt_mutex_init_proxy_locked(&pi_state->pi_mutex, p);
/* Store the key for possible exit cleanups: */
pi_state->key = *key;
WARN_ON(!list_empty(&pi_state->list));
list_add(&pi_state->list, &p->pi_state_list);
pi_state->owner = p;
raw_spin_unlock_irq(&p->pi_lock);
put_task_struct(p);
*ps = pi_state;
return 0;
}
/**
* futex_lock_pi_atomic() - Atomic work required to acquire a pi aware futex
* @uaddr: the pi futex user address
* @hb: the pi futex hash bucket
* @key: the futex key associated with uaddr and hb
* @ps: the pi_state pointer where we store the result of the
* lookup
* @task: the task to perform the atomic lock work for. This will
* be "current" except in the case of requeue pi.
* @set_waiters: force setting the FUTEX_WAITERS bit (1) or not (0)
*
* Return:
* 0 - ready to wait;
* 1 - acquired the lock;
* <0 - error
*
* The hb->lock and futex_key refs shall be held by the caller.
*/
static int futex_lock_pi_atomic(u32 __user *uaddr, struct futex_hash_bucket *hb,
union futex_key *key,
struct futex_pi_state **ps,
struct task_struct *task, int set_waiters)
{
int lock_taken, ret, force_take = 0;
u32 uval, newval, curval, vpid = task_pid_vnr(task);
retry:
ret = lock_taken = 0;
/*
* To avoid races, we attempt to take the lock here again
* (by doing a 0 -> TID atomic cmpxchg), while holding all
* the locks. It will most likely not succeed.
*/
newval = vpid;
if (set_waiters)
newval |= FUTEX_WAITERS;
if (unlikely(cmpxchg_futex_value_locked(&curval, uaddr, 0, newval)))
return -EFAULT;
/*
* Detect deadlocks.
*/
if ((unlikely((curval & FUTEX_TID_MASK) == vpid)))
return -EDEADLK;
/*
* Surprise - we got the lock, but we do not trust user space at all.
*/
if (unlikely(!curval)) {
/*
* We verify whether there is kernel state for this
* futex. If not, we can safely assume, that the 0 ->
* TID transition is correct. If state exists, we do
* not bother to fixup the user space state as it was
* corrupted already.
*/
return futex_top_waiter(hb, key) ? -EINVAL : 1;
}
uval = curval;
/*
* Set the FUTEX_WAITERS flag, so the owner will know it has someone
* to wake at the next unlock.
*/
newval = curval | FUTEX_WAITERS;
/*
* Should we force take the futex? See below.
*/
if (unlikely(force_take)) {
/*
* Keep the OWNER_DIED and the WAITERS bit and set the
* new TID value.
*/
newval = (curval & ~FUTEX_TID_MASK) | vpid;
force_take = 0;
lock_taken = 1;
}
if (unlikely(cmpxchg_futex_value_locked(&curval, uaddr, uval, newval)))
return -EFAULT;
if (unlikely(curval != uval))
goto retry;
/*
* We took the lock due to forced take over.
*/
if (unlikely(lock_taken))
return 1;
/*
* We dont have the lock. Look up the PI state (or create it if
* we are the first waiter):
*/
ret = lookup_pi_state(uval, hb, key, ps);
if (unlikely(ret)) {
switch (ret) {
case -ESRCH:
/*
* We failed to find an owner for this
* futex. So we have no pi_state to block
* on. This can happen in two cases:
*
* 1) The owner died
* 2) A stale FUTEX_WAITERS bit
*
* Re-read the futex value.
*/
if (get_futex_value_locked(&curval, uaddr))
return -EFAULT;
/*
* If the owner died or we have a stale
* WAITERS bit the owner TID in the user space
* futex is 0.
*/
if (!(curval & FUTEX_TID_MASK)) {
force_take = 1;
goto retry;
}
default:
break;
}
}
return ret;
}
/**
* __unqueue_futex() - Remove the futex_q from its futex_hash_bucket
* @q: The futex_q to unqueue
*
* The q->lock_ptr must not be NULL and must be held by the caller.
*/
static void __unqueue_futex(struct futex_q *q)
{
struct futex_hash_bucket *hb;
if (WARN_ON_SMP(!q->lock_ptr || !spin_is_locked(q->lock_ptr))
|| WARN_ON(plist_node_empty(&q->list)))
return;
hb = container_of(q->lock_ptr, struct futex_hash_bucket, lock);
plist_del(&q->list, &hb->chain);
}
/*
* The hash bucket lock must be held when this is called.
* Afterwards, the futex_q must not be accessed.
*/
static void wake_futex(struct futex_q *q)
{
struct task_struct *p = q->task;
if (WARN(q->pi_state || q->rt_waiter, "refusing to wake PI futex\n"))
return;
/*
* We set q->lock_ptr = NULL _before_ we wake up the task. If
* a non-futex wake up happens on another CPU then the task
* might exit and p would dereference a non-existing task
* struct. Prevent this by holding a reference on p across the
* wake up.
*/
get_task_struct(p);
__unqueue_futex(q);
/*
* The waiting task can free the futex_q as soon as
* q->lock_ptr = NULL is written, without taking any locks. A
* memory barrier is required here to prevent the following
* store to lock_ptr from getting ahead of the plist_del.
*/
smp_wmb();
q->lock_ptr = NULL;
wake_up_state(p, TASK_NORMAL);
put_task_struct(p);
}
static int wake_futex_pi(u32 __user *uaddr, u32 uval, struct futex_q *this)
{
struct task_struct *new_owner;
struct futex_pi_state *pi_state = this->pi_state;
u32 uninitialized_var(curval), newval;
int ret = 0;
if (!pi_state)
return -EINVAL;
/*
* If current does not own the pi_state then the futex is
* inconsistent and user space fiddled with the futex value.
*/
if (pi_state->owner != current)
return -EINVAL;
raw_spin_lock(&pi_state->pi_mutex.wait_lock);
new_owner = rt_mutex_next_owner(&pi_state->pi_mutex);
/*
* It is possible that the next waiter (the one that brought
* this owner to the kernel) timed out and is no longer
* waiting on the lock.
*/
if (!new_owner)
new_owner = this->task;
/*
* We pass it to the next owner. The WAITERS bit is always
* kept enabled while there is PI state around. We cleanup the
* owner died bit, because we are the owner.
*/
newval = FUTEX_WAITERS | task_pid_vnr(new_owner);
if (cmpxchg_futex_value_locked(&curval, uaddr, uval, newval))
ret = -EFAULT;
else if (curval != uval)
ret = -EINVAL;
if (ret) {
raw_spin_unlock(&pi_state->pi_mutex.wait_lock);
return ret;
}
raw_spin_lock_irq(&pi_state->owner->pi_lock);
WARN_ON(list_empty(&pi_state->list));
list_del_init(&pi_state->list);
raw_spin_unlock_irq(&pi_state->owner->pi_lock);
raw_spin_lock_irq(&new_owner->pi_lock);
WARN_ON(!list_empty(&pi_state->list));
list_add(&pi_state->list, &new_owner->pi_state_list);
pi_state->owner = new_owner;
raw_spin_unlock_irq(&new_owner->pi_lock);
raw_spin_unlock(&pi_state->pi_mutex.wait_lock);
rt_mutex_unlock(&pi_state->pi_mutex);
return 0;
}
static int unlock_futex_pi(u32 __user *uaddr, u32 uval)
{
u32 uninitialized_var(oldval);
/*
* There is no waiter, so we unlock the futex. The owner died
* bit has not to be preserved here. We are the owner:
*/
if (cmpxchg_futex_value_locked(&oldval, uaddr, uval, 0))
return -EFAULT;
if (oldval != uval)
return -EAGAIN;
return 0;
}
/*
* Express the locking dependencies for lockdep:
*/
static inline void
double_lock_hb(struct futex_hash_bucket *hb1, struct futex_hash_bucket *hb2)
{
if (hb1 <= hb2) {
spin_lock(&hb1->lock);
if (hb1 < hb2)
spin_lock_nested(&hb2->lock, SINGLE_DEPTH_NESTING);
} else { /* hb1 > hb2 */
spin_lock(&hb2->lock);
spin_lock_nested(&hb1->lock, SINGLE_DEPTH_NESTING);
}
}
static inline void
double_unlock_hb(struct futex_hash_bucket *hb1, struct futex_hash_bucket *hb2)
{
spin_unlock(&hb1->lock);
if (hb1 != hb2)
spin_unlock(&hb2->lock);
}
/*
* Wake up waiters matching bitset queued on this futex (uaddr).
*/
static int
futex_wake(u32 __user *uaddr, unsigned int flags, int nr_wake, u32 bitset)
{
struct futex_hash_bucket *hb;
struct futex_q *this, *next;
struct plist_head *head;
union futex_key key = FUTEX_KEY_INIT;
int ret;
if (!bitset)
return -EINVAL;
ret = get_futex_key(uaddr, flags & FLAGS_SHARED, &key, VERIFY_READ);
if (unlikely(ret != 0))
goto out;
hb = hash_futex(&key);
spin_lock(&hb->lock);
head = &hb->chain;
plist_for_each_entry_safe(this, next, head, list) {
if (match_futex (&this->key, &key)) {
if (this->pi_state || this->rt_waiter) {
ret = -EINVAL;
break;
}
/* Check if one of the bits is set in both bitsets */
if (!(this->bitset & bitset))
continue;
wake_futex(this);
if (++ret >= nr_wake)
break;
}
}
spin_unlock(&hb->lock);
put_futex_key(&key);
out:
return ret;
}
/*
* Wake up all waiters hashed on the physical page that is mapped
* to this virtual address:
*/
static int
futex_wake_op(u32 __user *uaddr1, unsigned int flags, u32 __user *uaddr2,
int nr_wake, int nr_wake2, int op)
{
union futex_key key1 = FUTEX_KEY_INIT, key2 = FUTEX_KEY_INIT;
struct futex_hash_bucket *hb1, *hb2;
struct plist_head *head;
struct futex_q *this, *next;
int ret, op_ret;
retry:
ret = get_futex_key(uaddr1, flags & FLAGS_SHARED, &key1, VERIFY_READ);
if (unlikely(ret != 0))
goto out;
ret = get_futex_key(uaddr2, flags & FLAGS_SHARED, &key2, VERIFY_WRITE);
if (unlikely(ret != 0))
goto out_put_key1;
hb1 = hash_futex(&key1);
hb2 = hash_futex(&key2);
retry_private:
double_lock_hb(hb1, hb2);
op_ret = futex_atomic_op_inuser(op, uaddr2);
if (unlikely(op_ret < 0)) {
double_unlock_hb(hb1, hb2);
#ifndef CONFIG_MMU
/*
* we don't get EFAULT from MMU faults if we don't have an MMU,
* but we might get them from range checking
*/
ret = op_ret;
goto out_put_keys;
#endif
if (unlikely(op_ret != -EFAULT)) {
ret = op_ret;
goto out_put_keys;
}
ret = fault_in_user_writeable(uaddr2);
if (ret)
goto out_put_keys;
if (!(flags & FLAGS_SHARED))
goto retry_private;
put_futex_key(&key2);
put_futex_key(&key1);
goto retry;
}
head = &hb1->chain;
plist_for_each_entry_safe(this, next, head, list) {
if (match_futex (&this->key, &key1)) {
if (this->pi_state || this->rt_waiter) {
ret = -EINVAL;
goto out_unlock;
}
wake_futex(this);
if (++ret >= nr_wake)
break;
}
}
if (op_ret > 0) {
head = &hb2->chain;
op_ret = 0;
plist_for_each_entry_safe(this, next, head, list) {
if (match_futex (&this->key, &key2)) {
if (this->pi_state || this->rt_waiter) {
ret = -EINVAL;
goto out_unlock;
}
wake_futex(this);
if (++op_ret >= nr_wake2)
break;
}
}
ret += op_ret;
}
out_unlock:
double_unlock_hb(hb1, hb2);
out_put_keys:
put_futex_key(&key2);
out_put_key1:
put_futex_key(&key1);
out:
return ret;
}
/**
* requeue_futex() - Requeue a futex_q from one hb to another
* @q: the futex_q to requeue
* @hb1: the source hash_bucket
* @hb2: the target hash_bucket
* @key2: the new key for the requeued futex_q
*/
static inline
void requeue_futex(struct futex_q *q, struct futex_hash_bucket *hb1,
struct futex_hash_bucket *hb2, union futex_key *key2)
{
/*
* If key1 and key2 hash to the same bucket, no need to
* requeue.
*/
if (likely(&hb1->chain != &hb2->chain)) {
plist_del(&q->list, &hb1->chain);
plist_add(&q->list, &hb2->chain);
q->lock_ptr = &hb2->lock;
}
get_futex_key_refs(key2);
q->key = *key2;
}
/**
* requeue_pi_wake_futex() - Wake a task that acquired the lock during requeue
* @q: the futex_q
* @key: the key of the requeue target futex
* @hb: the hash_bucket of the requeue target futex
*
* During futex_requeue, with requeue_pi=1, it is possible to acquire the
* target futex if it is uncontended or via a lock steal. Set the futex_q key
* to the requeue target futex so the waiter can detect the wakeup on the right
* futex, but remove it from the hb and NULL the rt_waiter so it can detect
* atomic lock acquisition. Set the q->lock_ptr to the requeue target hb->lock
* to protect access to the pi_state to fixup the owner later. Must be called
* with both q->lock_ptr and hb->lock held.
*/
static inline
void requeue_pi_wake_futex(struct futex_q *q, union futex_key *key,
struct futex_hash_bucket *hb)
{
get_futex_key_refs(key);
q->key = *key;
__unqueue_futex(q);
WARN_ON(!q->rt_waiter);
q->rt_waiter = NULL;
q->lock_ptr = &hb->lock;
wake_up_state(q->task, TASK_NORMAL);
}
/**
* futex_proxy_trylock_atomic() - Attempt an atomic lock for the top waiter
* @pifutex: the user address of the to futex
* @hb1: the from futex hash bucket, must be locked by the caller
* @hb2: the to futex hash bucket, must be locked by the caller
* @key1: the from futex key
* @key2: the to futex key
* @ps: address to store the pi_state pointer
* @set_waiters: force setting the FUTEX_WAITERS bit (1) or not (0)
*
* Try and get the lock on behalf of the top waiter if we can do it atomically.
* Wake the top waiter if we succeed. If the caller specified set_waiters,
* then direct futex_lock_pi_atomic() to force setting the FUTEX_WAITERS bit.
* hb1 and hb2 must be held by the caller.
*
* Return:
* 0 - failed to acquire the lock atomically;
* >0 - acquired the lock, return value is vpid of the top_waiter
* <0 - error
*/
static int futex_proxy_trylock_atomic(u32 __user *pifutex,
struct futex_hash_bucket *hb1,
struct futex_hash_bucket *hb2,
union futex_key *key1, union futex_key *key2,
struct futex_pi_state **ps, int set_waiters)
{
struct futex_q *top_waiter = NULL;
u32 curval;
int ret, vpid;
if (get_futex_value_locked(&curval, pifutex))
return -EFAULT;
/*
* Find the top_waiter and determine if there are additional waiters.
* If the caller intends to requeue more than 1 waiter to pifutex,
* force futex_lock_pi_atomic() to set the FUTEX_WAITERS bit now,
* as we have means to handle the possible fault. If not, don't set
* the bit unecessarily as it will force the subsequent unlock to enter
* the kernel.
*/
top_waiter = futex_top_waiter(hb1, key1);
/* There are no waiters, nothing for us to do. */
if (!top_waiter)
return 0;
/* Ensure we requeue to the expected futex. */
if (!match_futex(top_waiter->requeue_pi_key, key2))
return -EINVAL;
/*
* Try to take the lock for top_waiter. Set the FUTEX_WAITERS bit in
* the contended case or if set_waiters is 1. The pi_state is returned
* in ps in contended cases.
*/
vpid = task_pid_vnr(top_waiter->task);
ret = futex_lock_pi_atomic(pifutex, hb2, key2, ps, top_waiter->task,
set_waiters);
if (ret == 1) {
requeue_pi_wake_futex(top_waiter, key2, hb2);
return vpid;
}
return ret;
}
/**
* futex_requeue() - Requeue waiters from uaddr1 to uaddr2
* @uaddr1: source futex user address
* @flags: futex flags (FLAGS_SHARED, etc.)
* @uaddr2: target futex user address
* @nr_wake: number of waiters to wake (must be 1 for requeue_pi)
* @nr_requeue: number of waiters to requeue (0-INT_MAX)
* @cmpval: @uaddr1 expected value (or %NULL)
* @requeue_pi: if we are attempting to requeue from a non-pi futex to a
* pi futex (pi to pi requeue is not supported)
*
* Requeue waiters on uaddr1 to uaddr2. In the requeue_pi case, try to acquire
* uaddr2 atomically on behalf of the top waiter.
*
* Return:
* >=0 - on success, the number of tasks requeued or woken;
* <0 - on error
*/
static int futex_requeue(u32 __user *uaddr1, unsigned int flags,
u32 __user *uaddr2, int nr_wake, int nr_requeue,
u32 *cmpval, int requeue_pi)
{
union futex_key key1 = FUTEX_KEY_INIT, key2 = FUTEX_KEY_INIT;
int drop_count = 0, task_count = 0, ret;
struct futex_pi_state *pi_state = NULL;
struct futex_hash_bucket *hb1, *hb2;
struct plist_head *head1;
struct futex_q *this, *next;
u32 curval2;
if (requeue_pi) {
/*
* Requeue PI only works on two distinct uaddrs. This
* check is only valid for private futexes. See below.
*/
if (uaddr1 == uaddr2)
return -EINVAL;
/*
* requeue_pi requires a pi_state, try to allocate it now
* without any locks in case it fails.
*/
if (refill_pi_state_cache())
return -ENOMEM;
/*
* requeue_pi must wake as many tasks as it can, up to nr_wake
* + nr_requeue, since it acquires the rt_mutex prior to
* returning to userspace, so as to not leave the rt_mutex with
* waiters and no owner. However, second and third wake-ups
* cannot be predicted as they involve race conditions with the
* first wake and a fault while looking up the pi_state. Both
* pthread_cond_signal() and pthread_cond_broadcast() should
* use nr_wake=1.
*/
if (nr_wake != 1)
return -EINVAL;
}
retry:
if (pi_state != NULL) {
/*
* We will have to lookup the pi_state again, so free this one
* to keep the accounting correct.
*/
free_pi_state(pi_state);
pi_state = NULL;
}
ret = get_futex_key(uaddr1, flags & FLAGS_SHARED, &key1, VERIFY_READ);
if (unlikely(ret != 0))
goto out;
ret = get_futex_key(uaddr2, flags & FLAGS_SHARED, &key2,
requeue_pi ? VERIFY_WRITE : VERIFY_READ);
if (unlikely(ret != 0))
goto out_put_key1;
/*
* The check above which compares uaddrs is not sufficient for
* shared futexes. We need to compare the keys:
*/
if (requeue_pi && match_futex(&key1, &key2)) {
ret = -EINVAL;
goto out_put_keys;
}
/*
* The check above which compares uaddrs is not sufficient for
* shared futexes. We need to compare the keys:
*/
if (requeue_pi && match_futex(&key1, &key2)) {
ret = -EINVAL;
goto out_put_keys;
}
hb1 = hash_futex(&key1);
hb2 = hash_futex(&key2);
retry_private:
double_lock_hb(hb1, hb2);
if (likely(cmpval != NULL)) {
u32 curval;
ret = get_futex_value_locked(&curval, uaddr1);
if (unlikely(ret)) {
double_unlock_hb(hb1, hb2);
ret = get_user(curval, uaddr1);
if (ret)
goto out_put_keys;
if (!(flags & FLAGS_SHARED))
goto retry_private;
put_futex_key(&key2);
put_futex_key(&key1);
goto retry;
}
if (curval != *cmpval) {
ret = -EAGAIN;
goto out_unlock;
}
}
if (requeue_pi && (task_count - nr_wake < nr_requeue)) {
/*
* Attempt to acquire uaddr2 and wake the top waiter. If we
* intend to requeue waiters, force setting the FUTEX_WAITERS
* bit. We force this here where we are able to easily handle
* faults rather in the requeue loop below.
*/
ret = futex_proxy_trylock_atomic(uaddr2, hb1, hb2, &key1,
&key2, &pi_state, nr_requeue);
/*
* At this point the top_waiter has either taken uaddr2 or is
* waiting on it. If the former, then the pi_state will not
* exist yet, look it up one more time to ensure we have a
* reference to it. If the lock was taken, ret contains the
* vpid of the top waiter task.
*/
if (ret > 0) {
WARN_ON(pi_state);
drop_count++;
task_count++;
/*
* If we acquired the lock, then the user
* space value of uaddr2 should be vpid. It
* cannot be changed by the top waiter as it
* is blocked on hb2 lock if it tries to do
* so. If something fiddled with it behind our
* back the pi state lookup might unearth
* it. So we rather use the known value than
* rereading and handing potential crap to
* lookup_pi_state.
*/
ret = lookup_pi_state(ret, hb2, &key2, &pi_state);
}
switch (ret) {
case 0:
break;
case -EFAULT:
double_unlock_hb(hb1, hb2);
put_futex_key(&key2);
put_futex_key(&key1);
ret = fault_in_user_writeable(uaddr2);
if (!ret)
goto retry;
goto out;
case -EAGAIN:
/* The owner was exiting, try again. */
double_unlock_hb(hb1, hb2);
put_futex_key(&key2);
put_futex_key(&key1);
cond_resched();
goto retry;
default:
goto out_unlock;
}
}
head1 = &hb1->chain;
plist_for_each_entry_safe(this, next, head1, list) {
if (task_count - nr_wake >= nr_requeue)
break;
if (!match_futex(&this->key, &key1))
continue;
/*
* FUTEX_WAIT_REQEUE_PI and FUTEX_CMP_REQUEUE_PI should always
* be paired with each other and no other futex ops.
*
* We should never be requeueing a futex_q with a pi_state,
* which is awaiting a futex_unlock_pi().
*/
if ((requeue_pi && !this->rt_waiter) ||
(!requeue_pi && this->rt_waiter) ||
this->pi_state) {
ret = -EINVAL;
break;
}
/*
* Wake nr_wake waiters. For requeue_pi, if we acquired the
* lock, we already woke the top_waiter. If not, it will be
* woken by futex_unlock_pi().
*/
if (++task_count <= nr_wake && !requeue_pi) {
wake_futex(this);
continue;
}
/* Ensure we requeue to the expected futex for requeue_pi. */
if (requeue_pi && !match_futex(this->requeue_pi_key, &key2)) {
ret = -EINVAL;
break;
}
/*
* Requeue nr_requeue waiters and possibly one more in the case
* of requeue_pi if we couldn't acquire the lock atomically.
*/
if (requeue_pi) {
/* Prepare the waiter to take the rt_mutex. */
atomic_inc(&pi_state->refcount);
this->pi_state = pi_state;
ret = rt_mutex_start_proxy_lock(&pi_state->pi_mutex,
this->rt_waiter,
this->task, 1);
if (ret == 1) {
/* We got the lock. */
requeue_pi_wake_futex(this, &key2, hb2);
drop_count++;
continue;
} else if (ret) {
/* -EDEADLK */
this->pi_state = NULL;
free_pi_state(pi_state);
goto out_unlock;
}
}
requeue_futex(this, hb1, hb2, &key2);
drop_count++;
}
out_unlock:
double_unlock_hb(hb1, hb2);
/*
* drop_futex_key_refs() must be called outside the spinlocks. During
* the requeue we moved futex_q's from the hash bucket at key1 to the
* one at key2 and updated their key pointer. We no longer need to
* hold the references to key1.
*/
while (--drop_count >= 0)
drop_futex_key_refs(&key1);
out_put_keys:
put_futex_key(&key2);
out_put_key1:
put_futex_key(&key1);
out:
if (pi_state != NULL)
free_pi_state(pi_state);
return ret ? ret : task_count;
}
/* The key must be already stored in q->key. */
static inline struct futex_hash_bucket *queue_lock(struct futex_q *q)
__acquires(&hb->lock)
{
struct futex_hash_bucket *hb;
hb = hash_futex(&q->key);
q->lock_ptr = &hb->lock;
spin_lock(&hb->lock);
return hb;
}
static inline void
queue_unlock(struct futex_q *q, struct futex_hash_bucket *hb)
__releases(&hb->lock)
{
spin_unlock(&hb->lock);
}
/**
* queue_me() - Enqueue the futex_q on the futex_hash_bucket
* @q: The futex_q to enqueue
* @hb: The destination hash bucket
*
* The hb->lock must be held by the caller, and is released here. A call to
* queue_me() is typically paired with exactly one call to unqueue_me(). The
* exceptions involve the PI related operations, which may use unqueue_me_pi()
* or nothing if the unqueue is done as part of the wake process and the unqueue
* state is implicit in the state of woken task (see futex_wait_requeue_pi() for
* an example).
*/
static inline void queue_me(struct futex_q *q, struct futex_hash_bucket *hb)
__releases(&hb->lock)
{
int prio;
/*
* The priority used to register this element is
* - either the real thread-priority for the real-time threads
* (i.e. threads with a priority lower than MAX_RT_PRIO)
* - or MAX_RT_PRIO for non-RT threads.
* Thus, all RT-threads are woken first in priority order, and
* the others are woken last, in FIFO order.
*/
prio = min(current->normal_prio, MAX_RT_PRIO);
plist_node_init(&q->list, prio);
plist_add(&q->list, &hb->chain);
q->task = current;
spin_unlock(&hb->lock);
}
/**
* unqueue_me() - Remove the futex_q from its futex_hash_bucket
* @q: The futex_q to unqueue
*
* The q->lock_ptr must not be held by the caller. A call to unqueue_me() must
* be paired with exactly one earlier call to queue_me().
*
* Return:
* 1 - if the futex_q was still queued (and we removed unqueued it);
* 0 - if the futex_q was already removed by the waking thread
*/
static int unqueue_me(struct futex_q *q)
{
spinlock_t *lock_ptr;
int ret = 0;
/* In the common case we don't take the spinlock, which is nice. */
retry:
lock_ptr = q->lock_ptr;
barrier();
if (lock_ptr != NULL) {
spin_lock(lock_ptr);
/*
* q->lock_ptr can change between reading it and
* spin_lock(), causing us to take the wrong lock. This
* corrects the race condition.
*
* Reasoning goes like this: if we have the wrong lock,
* q->lock_ptr must have changed (maybe several times)
* between reading it and the spin_lock(). It can
* change again after the spin_lock() but only if it was
* already changed before the spin_lock(). It cannot,
* however, change back to the original value. Therefore
* we can detect whether we acquired the correct lock.
*/
if (unlikely(lock_ptr != q->lock_ptr)) {
spin_unlock(lock_ptr);
goto retry;
}
__unqueue_futex(q);
BUG_ON(q->pi_state);
spin_unlock(lock_ptr);
ret = 1;
}
drop_futex_key_refs(&q->key);
return ret;
}
/*
* PI futexes can not be requeued and must remove themself from the
* hash bucket. The hash bucket lock (i.e. lock_ptr) is held on entry
* and dropped here.
*/
static void unqueue_me_pi(struct futex_q *q)
__releases(q->lock_ptr)
{
__unqueue_futex(q);
BUG_ON(!q->pi_state);
free_pi_state(q->pi_state);
q->pi_state = NULL;
spin_unlock(q->lock_ptr);
}
/*
* Fixup the pi_state owner with the new owner.
*
* Must be called with hash bucket lock held and mm->sem held for non
* private futexes.
*/
static int fixup_pi_state_owner(u32 __user *uaddr, struct futex_q *q,
struct task_struct *newowner)
{
u32 newtid = task_pid_vnr(newowner) | FUTEX_WAITERS;
struct futex_pi_state *pi_state = q->pi_state;
struct task_struct *oldowner = pi_state->owner;
u32 uval, uninitialized_var(curval), newval;
int ret;
/* Owner died? */
if (!pi_state->owner)
newtid |= FUTEX_OWNER_DIED;
/*
* We are here either because we stole the rtmutex from the
* previous highest priority waiter or we are the highest priority
* waiter but failed to get the rtmutex the first time.
* We have to replace the newowner TID in the user space variable.
* This must be atomic as we have to preserve the owner died bit here.
*
* Note: We write the user space value _before_ changing the pi_state
* because we can fault here. Imagine swapped out pages or a fork
* that marked all the anonymous memory readonly for cow.
*
* Modifying pi_state _before_ the user space value would
* leave the pi_state in an inconsistent state when we fault
* here, because we need to drop the hash bucket lock to
* handle the fault. This might be observed in the PID check
* in lookup_pi_state.
*/
retry:
if (get_futex_value_locked(&uval, uaddr))
goto handle_fault;
while (1) {
newval = (uval & FUTEX_OWNER_DIED) | newtid;
if (cmpxchg_futex_value_locked(&curval, uaddr, uval, newval))
goto handle_fault;
if (curval == uval)
break;
uval = curval;
}
/*
* We fixed up user space. Now we need to fix the pi_state
* itself.
*/
if (pi_state->owner != NULL) {
raw_spin_lock_irq(&pi_state->owner->pi_lock);
WARN_ON(list_empty(&pi_state->list));
list_del_init(&pi_state->list);
raw_spin_unlock_irq(&pi_state->owner->pi_lock);
}
pi_state->owner = newowner;
raw_spin_lock_irq(&newowner->pi_lock);
WARN_ON(!list_empty(&pi_state->list));
list_add(&pi_state->list, &newowner->pi_state_list);
raw_spin_unlock_irq(&newowner->pi_lock);
return 0;
/*
* To handle the page fault we need to drop the hash bucket
* lock here. That gives the other task (either the highest priority
* waiter itself or the task which stole the rtmutex) the
* chance to try the fixup of the pi_state. So once we are
* back from handling the fault we need to check the pi_state
* after reacquiring the hash bucket lock and before trying to
* do another fixup. When the fixup has been done already we
* simply return.
*/
handle_fault:
spin_unlock(q->lock_ptr);
ret = fault_in_user_writeable(uaddr);
spin_lock(q->lock_ptr);
/*
* Check if someone else fixed it for us:
*/
if (pi_state->owner != oldowner)
return 0;
if (ret)
return ret;
goto retry;
}
static long futex_wait_restart(struct restart_block *restart);
/**
* fixup_owner() - Post lock pi_state and corner case management
* @uaddr: user address of the futex
* @q: futex_q (contains pi_state and access to the rt_mutex)
* @locked: if the attempt to take the rt_mutex succeeded (1) or not (0)
*
* After attempting to lock an rt_mutex, this function is called to cleanup
* the pi_state owner as well as handle race conditions that may allow us to
* acquire the lock. Must be called with the hb lock held.
*
* Return:
* 1 - success, lock taken;
* 0 - success, lock not taken;
* <0 - on error (-EFAULT)
*/
static int fixup_owner(u32 __user *uaddr, struct futex_q *q, int locked)
{
struct task_struct *owner;
int ret = 0;
if (locked) {
/*
* Got the lock. We might not be the anticipated owner if we
* did a lock-steal - fix up the PI-state in that case:
*/
if (q->pi_state->owner != current)
ret = fixup_pi_state_owner(uaddr, q, current);
goto out;
}
/*
* Catch the rare case, where the lock was released when we were on the
* way back before we locked the hash bucket.
*/
if (q->pi_state->owner == current) {
/*
* Try to get the rt_mutex now. This might fail as some other
* task acquired the rt_mutex after we removed ourself from the
* rt_mutex waiters list.
*/
if (rt_mutex_trylock(&q->pi_state->pi_mutex)) {
locked = 1;
goto out;
}
/*
* pi_state is incorrect, some other task did a lock steal and
* we returned due to timeout or signal without taking the
* rt_mutex. Too late.
*/
raw_spin_lock(&q->pi_state->pi_mutex.wait_lock);
owner = rt_mutex_owner(&q->pi_state->pi_mutex);
if (!owner)
owner = rt_mutex_next_owner(&q->pi_state->pi_mutex);
raw_spin_unlock(&q->pi_state->pi_mutex.wait_lock);
ret = fixup_pi_state_owner(uaddr, q, owner);
goto out;
}
/*
* Paranoia check. If we did not take the lock, then we should not be
* the owner of the rt_mutex.
*/
if (rt_mutex_owner(&q->pi_state->pi_mutex) == current)
printk(KERN_ERR "fixup_owner: ret = %d pi-mutex: %p "
"pi-state %p\n", ret,
q->pi_state->pi_mutex.owner,
q->pi_state->owner);
out:
return ret ? ret : locked;
}
/**
* futex_wait_queue_me() - queue_me() and wait for wakeup, timeout, or signal
* @hb: the futex hash bucket, must be locked by the caller
* @q: the futex_q to queue up on
* @timeout: the prepared hrtimer_sleeper, or null for no timeout
*/
static void futex_wait_queue_me(struct futex_hash_bucket *hb, struct futex_q *q,
struct hrtimer_sleeper *timeout)
{
/*
* The task state is guaranteed to be set before another task can
* wake it. set_current_state() is implemented using set_mb() and
* queue_me() calls spin_unlock() upon completion, both serializing
* access to the hash list and forcing another memory barrier.
*/
set_current_state(TASK_INTERRUPTIBLE);
queue_me(q, hb);
/* Arm the timer */
if (timeout) {
hrtimer_start_expires(&timeout->timer, HRTIMER_MODE_ABS);
if (!hrtimer_active(&timeout->timer))
timeout->task = NULL;
}
/*
* If we have been removed from the hash list, then another task
* has tried to wake us, and we can skip the call to schedule().
*/
if (likely(!plist_node_empty(&q->list))) {
/*
* If the timer has already expired, current will already be
* flagged for rescheduling. Only call schedule if there
* is no timeout, or if it has yet to expire.
*/
if (!timeout || timeout->task)
freezable_schedule();
}
__set_current_state(TASK_RUNNING);
}
/**
* futex_wait_setup() - Prepare to wait on a futex
* @uaddr: the futex userspace address
* @val: the expected value
* @flags: futex flags (FLAGS_SHARED, etc.)
* @q: the associated futex_q
* @hb: storage for hash_bucket pointer to be returned to caller
*
* Setup the futex_q and locate the hash_bucket. Get the futex value and
* compare it with the expected value. Handle atomic faults internally.
* Return with the hb lock held and a q.key reference on success, and unlocked
* with no q.key reference on failure.
*
* Return:
* 0 - uaddr contains val and hb has been locked;
* <1 - -EFAULT or -EWOULDBLOCK (uaddr does not contain val) and hb is unlocked
*/
static int futex_wait_setup(u32 __user *uaddr, u32 val, unsigned int flags,
struct futex_q *q, struct futex_hash_bucket **hb)
{
u32 uval;
int ret;
/*
* Access the page AFTER the hash-bucket is locked.
* Order is important:
*
* Userspace waiter: val = var; if (cond(val)) futex_wait(&var, val);
* Userspace waker: if (cond(var)) { var = new; futex_wake(&var); }
*
* The basic logical guarantee of a futex is that it blocks ONLY
* if cond(var) is known to be true at the time of blocking, for
* any cond. If we locked the hash-bucket after testing *uaddr, that
* would open a race condition where we could block indefinitely with
* cond(var) false, which would violate the guarantee.
*
* On the other hand, we insert q and release the hash-bucket only
* after testing *uaddr. This guarantees that futex_wait() will NOT
* absorb a wakeup if *uaddr does not match the desired values
* while the syscall executes.
*/
retry:
ret = get_futex_key(uaddr, flags & FLAGS_SHARED, &q->key, VERIFY_READ);
if (unlikely(ret != 0))
return ret;
retry_private:
*hb = queue_lock(q);
ret = get_futex_value_locked(&uval, uaddr);
if (ret) {
queue_unlock(q, *hb);
ret = get_user(uval, uaddr);
if (ret)
goto out;
if (!(flags & FLAGS_SHARED))
goto retry_private;
put_futex_key(&q->key);
goto retry;
}
if (uval != val) {
queue_unlock(q, *hb);
ret = -EWOULDBLOCK;
}
out:
if (ret)
put_futex_key(&q->key);
return ret;
}
static int futex_wait(u32 __user *uaddr, unsigned int flags, u32 val,
ktime_t *abs_time, u32 bitset)
{
struct hrtimer_sleeper timeout, *to = NULL;
struct restart_block *restart;
struct futex_hash_bucket *hb;
struct futex_q q = futex_q_init;
int ret;
if (!bitset)
return -EINVAL;
q.bitset = bitset;
if (abs_time) {
to = &timeout;
hrtimer_init_on_stack(&to->timer, (flags & FLAGS_CLOCKRT) ?
CLOCK_REALTIME : CLOCK_MONOTONIC,
HRTIMER_MODE_ABS);
hrtimer_init_sleeper(to, current);
hrtimer_set_expires_range_ns(&to->timer, *abs_time,
current->timer_slack_ns);
}
retry:
/*
* Prepare to wait on uaddr. On success, holds hb lock and increments
* q.key refs.
*/
ret = futex_wait_setup(uaddr, val, flags, &q, &hb);
if (ret)
goto out;
/* queue_me and wait for wakeup, timeout, or a signal. */
futex_wait_queue_me(hb, &q, to);
/* If we were woken (and unqueued), we succeeded, whatever. */
ret = 0;
/* unqueue_me() drops q.key ref */
if (!unqueue_me(&q))
goto out;
ret = -ETIMEDOUT;
if (to && !to->task)
goto out;
/*
* We expect signal_pending(current), but we might be the
* victim of a spurious wakeup as well.
*/
if (!signal_pending(current))
goto retry;
ret = -ERESTARTSYS;
if (!abs_time)
goto out;
restart = ¤t_thread_info()->restart_block;
restart->fn = futex_wait_restart;
restart->futex.uaddr = uaddr;
restart->futex.val = val;
restart->futex.time = abs_time->tv64;
restart->futex.bitset = bitset;
restart->futex.flags = flags | FLAGS_HAS_TIMEOUT;
ret = -ERESTART_RESTARTBLOCK;
out:
if (to) {
hrtimer_cancel(&to->timer);
destroy_hrtimer_on_stack(&to->timer);
}
return ret;
}
static long futex_wait_restart(struct restart_block *restart)
{
u32 __user *uaddr = restart->futex.uaddr;
ktime_t t, *tp = NULL;
if (restart->futex.flags & FLAGS_HAS_TIMEOUT) {
t.tv64 = restart->futex.time;
tp = &t;
}
restart->fn = do_no_restart_syscall;
return (long)futex_wait(uaddr, restart->futex.flags,
restart->futex.val, tp, restart->futex.bitset);
}
/*
* Userspace tried a 0 -> TID atomic transition of the futex value
* and failed. The kernel side here does the whole locking operation:
* if there are waiters then it will block, it does PI, etc. (Due to
* races the kernel might see a 0 value of the futex too.)
*/
static int futex_lock_pi(u32 __user *uaddr, unsigned int flags, int detect,
ktime_t *time, int trylock)
{
struct hrtimer_sleeper timeout, *to = NULL;
struct futex_hash_bucket *hb;
struct futex_q q = futex_q_init;
int res, ret;
if (refill_pi_state_cache())
return -ENOMEM;
if (time) {
to = &timeout;
hrtimer_init_on_stack(&to->timer, CLOCK_REALTIME,
HRTIMER_MODE_ABS);
hrtimer_init_sleeper(to, current);
hrtimer_set_expires(&to->timer, *time);
}
retry:
ret = get_futex_key(uaddr, flags & FLAGS_SHARED, &q.key, VERIFY_WRITE);
if (unlikely(ret != 0))
goto out;
retry_private:
hb = queue_lock(&q);
ret = futex_lock_pi_atomic(uaddr, hb, &q.key, &q.pi_state, current, 0);
if (unlikely(ret)) {
switch (ret) {
case 1:
/* We got the lock. */
ret = 0;
goto out_unlock_put_key;
case -EFAULT:
goto uaddr_faulted;
case -EAGAIN:
/*
* Task is exiting and we just wait for the
* exit to complete.
*/
queue_unlock(&q, hb);
put_futex_key(&q.key);
cond_resched();
goto retry;
default:
goto out_unlock_put_key;
}
}
/*
* Only actually queue now that the atomic ops are done:
*/
queue_me(&q, hb);
WARN_ON(!q.pi_state);
/*
* Block on the PI mutex:
*/
if (!trylock)
ret = rt_mutex_timed_lock(&q.pi_state->pi_mutex, to, 1);
else {
ret = rt_mutex_trylock(&q.pi_state->pi_mutex);
/* Fixup the trylock return value: */
ret = ret ? 0 : -EWOULDBLOCK;
}
spin_lock(q.lock_ptr);
/*
* Fixup the pi_state owner and possibly acquire the lock if we
* haven't already.
*/
res = fixup_owner(uaddr, &q, !ret);
/*
* If fixup_owner() returned an error, proprogate that. If it acquired
* the lock, clear our -ETIMEDOUT or -EINTR.
*/
if (res)
ret = (res < 0) ? res : 0;
/*
* If fixup_owner() faulted and was unable to handle the fault, unlock
* it and return the fault to userspace.
*/
if (ret && (rt_mutex_owner(&q.pi_state->pi_mutex) == current))
rt_mutex_unlock(&q.pi_state->pi_mutex);
/* Unqueue and drop the lock */
unqueue_me_pi(&q);
goto out_put_key;
out_unlock_put_key:
queue_unlock(&q, hb);
out_put_key:
put_futex_key(&q.key);
out:
if (to)
destroy_hrtimer_on_stack(&to->timer);
return ret != -EINTR ? ret : -ERESTARTNOINTR;
uaddr_faulted:
queue_unlock(&q, hb);
ret = fault_in_user_writeable(uaddr);
if (ret)
goto out_put_key;
if (!(flags & FLAGS_SHARED))
goto retry_private;
put_futex_key(&q.key);
goto retry;
}
/*
* Userspace attempted a TID -> 0 atomic transition, and failed.
* This is the in-kernel slowpath: we look up the PI state (if any),
* and do the rt-mutex unlock.
*/
static int futex_unlock_pi(u32 __user *uaddr, unsigned int flags)
{
struct futex_hash_bucket *hb;
struct futex_q *this, *next;
struct plist_head *head;
union futex_key key = FUTEX_KEY_INIT;
u32 uval, vpid = task_pid_vnr(current);
int ret;
retry:
if (get_user(uval, uaddr))
return -EFAULT;
/*
* We release only a lock we actually own:
*/
if ((uval & FUTEX_TID_MASK) != vpid)
return -EPERM;
ret = get_futex_key(uaddr, flags & FLAGS_SHARED, &key, VERIFY_WRITE);
if (unlikely(ret != 0))
goto out;
hb = hash_futex(&key);
spin_lock(&hb->lock);
/*
* To avoid races, try to do the TID -> 0 atomic transition
* again. If it succeeds then we can return without waking
* anyone else up. We only try this if neither the waiters nor
* the owner died bit are set.
*/
if (!(uval & ~FUTEX_TID_MASK) &&
cmpxchg_futex_value_locked(&uval, uaddr, vpid, 0))
goto pi_faulted;
/*
* Rare case: we managed to release the lock atomically,
* no need to wake anyone else up:
*/
if (unlikely(uval == vpid))
goto out_unlock;
/*
* Ok, other tasks may need to be woken up - check waiters
* and do the wakeup if necessary:
*/
head = &hb->chain;
plist_for_each_entry_safe(this, next, head, list) {
if (!match_futex (&this->key, &key))
continue;
ret = wake_futex_pi(uaddr, uval, this);
/*
* The atomic access to the futex value
* generated a pagefault, so retry the
* user-access and the wakeup:
*/
if (ret == -EFAULT)
goto pi_faulted;
goto out_unlock;
}
/*
* No waiters - kernel unlocks the futex:
*/
ret = unlock_futex_pi(uaddr, uval);
if (ret == -EFAULT)
goto pi_faulted;
out_unlock:
spin_unlock(&hb->lock);
put_futex_key(&key);
out:
return ret;
pi_faulted:
spin_unlock(&hb->lock);
put_futex_key(&key);
ret = fault_in_user_writeable(uaddr);
if (!ret)
goto retry;
return ret;
}
/**
* handle_early_requeue_pi_wakeup() - Detect early wakeup on the initial futex
* @hb: the hash_bucket futex_q was original enqueued on
* @q: the futex_q woken while waiting to be requeued
* @key2: the futex_key of the requeue target futex
* @timeout: the timeout associated with the wait (NULL if none)
*
* Detect if the task was woken on the initial futex as opposed to the requeue
* target futex. If so, determine if it was a timeout or a signal that caused
* the wakeup and return the appropriate error code to the caller. Must be
* called with the hb lock held.
*
* Return:
* 0 = no early wakeup detected;
* <0 = -ETIMEDOUT or -ERESTARTNOINTR
*/
static inline
int handle_early_requeue_pi_wakeup(struct futex_hash_bucket *hb,
struct futex_q *q, union futex_key *key2,
struct hrtimer_sleeper *timeout)
{
int ret = 0;
/*
* With the hb lock held, we avoid races while we process the wakeup.
* We only need to hold hb (and not hb2) to ensure atomicity as the
* wakeup code can't change q.key from uaddr to uaddr2 if we hold hb.
* It can't be requeued from uaddr2 to something else since we don't
* support a PI aware source futex for requeue.
*/
if (!match_futex(&q->key, key2)) {
WARN_ON(q->lock_ptr && (&hb->lock != q->lock_ptr));
/*
* We were woken prior to requeue by a timeout or a signal.
* Unqueue the futex_q and determine which it was.
*/
plist_del(&q->list, &hb->chain);
/* Handle spurious wakeups gracefully */
ret = -EWOULDBLOCK;
if (timeout && !timeout->task)
ret = -ETIMEDOUT;
else if (signal_pending(current))
ret = -ERESTARTNOINTR;
}
return ret;
}
/**
* futex_wait_requeue_pi() - Wait on uaddr and take uaddr2
* @uaddr: the futex we initially wait on (non-pi)
* @flags: futex flags (FLAGS_SHARED, FLAGS_CLOCKRT, etc.), they must be
* the same type, no requeueing from private to shared, etc.
* @val: the expected value of uaddr
* @abs_time: absolute timeout
* @bitset: 32 bit wakeup bitset set by userspace, defaults to all
* @uaddr2: the pi futex we will take prior to returning to user-space
*
* The caller will wait on uaddr and will be requeued by futex_requeue() to
* uaddr2 which must be PI aware and unique from uaddr. Normal wakeup will wake
* on uaddr2 and complete the acquisition of the rt_mutex prior to returning to
* userspace. This ensures the rt_mutex maintains an owner when it has waiters;
* without one, the pi logic would not know which task to boost/deboost, if
* there was a need to.
*
* We call schedule in futex_wait_queue_me() when we enqueue and return there
* via the following--
* 1) wakeup on uaddr2 after an atomic lock acquisition by futex_requeue()
* 2) wakeup on uaddr2 after a requeue
* 3) signal
* 4) timeout
*
* If 3, cleanup and return -ERESTARTNOINTR.
*
* If 2, we may then block on trying to take the rt_mutex and return via:
* 5) successful lock
* 6) signal
* 7) timeout
* 8) other lock acquisition failure
*
* If 6, return -EWOULDBLOCK (restarting the syscall would do the same).
*
* If 4 or 7, we cleanup and return with -ETIMEDOUT.
*
* Return:
* 0 - On success;
* <0 - On error
*/
static int futex_wait_requeue_pi(u32 __user *uaddr, unsigned int flags,
u32 val, ktime_t *abs_time, u32 bitset,
u32 __user *uaddr2)
{
struct hrtimer_sleeper timeout, *to = NULL;
struct rt_mutex_waiter rt_waiter;
struct rt_mutex *pi_mutex = NULL;
struct futex_hash_bucket *hb;
union futex_key key2 = FUTEX_KEY_INIT;
struct futex_q q = futex_q_init;
int res, ret;
if (uaddr == uaddr2)
return -EINVAL;
if (!bitset)
return -EINVAL;
if (abs_time) {
to = &timeout;
hrtimer_init_on_stack(&to->timer, (flags & FLAGS_CLOCKRT) ?
CLOCK_REALTIME : CLOCK_MONOTONIC,
HRTIMER_MODE_ABS);
hrtimer_init_sleeper(to, current);
hrtimer_set_expires_range_ns(&to->timer, *abs_time,
current->timer_slack_ns);
}
/*
* The waiter is allocated on our stack, manipulated by the requeue
* code while we sleep on uaddr.
*/
debug_rt_mutex_init_waiter(&rt_waiter);
rt_waiter.task = NULL;
ret = get_futex_key(uaddr2, flags & FLAGS_SHARED, &key2, VERIFY_WRITE);
if (unlikely(ret != 0))
goto out;
q.bitset = bitset;
q.rt_waiter = &rt_waiter;
q.requeue_pi_key = &key2;
/*
* Prepare to wait on uaddr. On success, increments q.key (key1) ref
* count.
*/
ret = futex_wait_setup(uaddr, val, flags, &q, &hb);
if (ret)
goto out_key2;
/*
* The check above which compares uaddrs is not sufficient for
* shared futexes. We need to compare the keys:
*/
if (match_futex(&q.key, &key2)) {
ret = -EINVAL;
goto out_put_keys;
}
/*
* The check above which compares uaddrs is not sufficient for
* shared futexes. We need to compare the keys:
*/
if (match_futex(&q.key, &key2)) {
ret = -EINVAL;
goto out_put_keys;
}
/* Queue the futex_q, drop the hb lock, wait for wakeup. */
futex_wait_queue_me(hb, &q, to);
spin_lock(&hb->lock);
ret = handle_early_requeue_pi_wakeup(hb, &q, &key2, to);
spin_unlock(&hb->lock);
if (ret)
goto out_put_keys;
/*
* In order for us to be here, we know our q.key == key2, and since
* we took the hb->lock above, we also know that futex_requeue() has
* completed and we no longer have to concern ourselves with a wakeup
* race with the atomic proxy lock acquisition by the requeue code. The
* futex_requeue dropped our key1 reference and incremented our key2
* reference count.
*/
/* Check if the requeue code acquired the second futex for us. */
if (!q.rt_waiter) {
/*
* Got the lock. We might not be the anticipated owner if we
* did a lock-steal - fix up the PI-state in that case.
*/
if (q.pi_state && (q.pi_state->owner != current)) {
spin_lock(q.lock_ptr);
ret = fixup_pi_state_owner(uaddr2, &q, current);
spin_unlock(q.lock_ptr);
}
} else {
/*
* We have been woken up by futex_unlock_pi(), a timeout, or a
* signal. futex_unlock_pi() will not destroy the lock_ptr nor
* the pi_state.
*/
WARN_ON(!q.pi_state);
pi_mutex = &q.pi_state->pi_mutex;
ret = rt_mutex_finish_proxy_lock(pi_mutex, to, &rt_waiter, 1);
debug_rt_mutex_free_waiter(&rt_waiter);
spin_lock(q.lock_ptr);
/*
* Fixup the pi_state owner and possibly acquire the lock if we
* haven't already.
*/
res = fixup_owner(uaddr2, &q, !ret);
/*
* If fixup_owner() returned an error, proprogate that. If it
* acquired the lock, clear -ETIMEDOUT or -EINTR.
*/
if (res)
ret = (res < 0) ? res : 0;
/* Unqueue and drop the lock. */
unqueue_me_pi(&q);
}
/*
* If fixup_pi_state_owner() faulted and was unable to handle the
* fault, unlock the rt_mutex and return the fault to userspace.
*/
if (ret == -EFAULT) {
if (pi_mutex && rt_mutex_owner(pi_mutex) == current)
rt_mutex_unlock(pi_mutex);
} else if (ret == -EINTR) {
/*
* We've already been requeued, but cannot restart by calling
* futex_lock_pi() directly. We could restart this syscall, but
* it would detect that the user space "val" changed and return
* -EWOULDBLOCK. Save the overhead of the restart and return
* -EWOULDBLOCK directly.
*/
ret = -EWOULDBLOCK;
}
out_put_keys:
put_futex_key(&q.key);
out_key2:
put_futex_key(&key2);
out:
if (to) {
hrtimer_cancel(&to->timer);
destroy_hrtimer_on_stack(&to->timer);
}
return ret;
}
/*
* Support for robust futexes: the kernel cleans up held futexes at
* thread exit time.
*
* Implementation: user-space maintains a per-thread list of locks it
* is holding. Upon do_exit(), the kernel carefully walks this list,
* and marks all locks that are owned by this thread with the
* FUTEX_OWNER_DIED bit, and wakes up a waiter (if any). The list is
* always manipulated with the lock held, so the list is private and
* per-thread. Userspace also maintains a per-thread 'list_op_pending'
* field, to allow the kernel to clean up if the thread dies after
* acquiring the lock, but just before it could have added itself to
* the list. There can only be one such pending lock.
*/
/**
* sys_set_robust_list() - Set the robust-futex list head of a task
* @head: pointer to the list-head
* @len: length of the list-head, as userspace expects
*/
SYSCALL_DEFINE2(set_robust_list, struct robust_list_head __user *, head,
size_t, len)
{
if (!futex_cmpxchg_enabled)
return -ENOSYS;
/*
* The kernel knows only one size for now:
*/
if (unlikely(len != sizeof(*head)))
return -EINVAL;
current->robust_list = head;
return 0;
}
/**
* sys_get_robust_list() - Get the robust-futex list head of a task
* @pid: pid of the process [zero for current task]
* @head_ptr: pointer to a list-head pointer, the kernel fills it in
* @len_ptr: pointer to a length field, the kernel fills in the header size
*/
SYSCALL_DEFINE3(get_robust_list, int, pid,
struct robust_list_head __user * __user *, head_ptr,
size_t __user *, len_ptr)
{
struct robust_list_head __user *head;
unsigned long ret;
struct task_struct *p;
if (!futex_cmpxchg_enabled)
return -ENOSYS;
rcu_read_lock();
ret = -ESRCH;
if (!pid)
p = current;
else {
p = find_task_by_vpid(pid);
if (!p)
goto err_unlock;
}
ret = -EPERM;
if (!ptrace_may_access(p, PTRACE_MODE_READ))
goto err_unlock;
head = p->robust_list;
rcu_read_unlock();
if (put_user(sizeof(*head), len_ptr))
return -EFAULT;
return put_user(head, head_ptr);
err_unlock:
rcu_read_unlock();
return ret;
}
/*
* Process a futex-list entry, check whether it's owned by the
* dying task, and do notification if so:
*/
int handle_futex_death(u32 __user *uaddr, struct task_struct *curr, int pi)
{
u32 uval, uninitialized_var(nval), mval;
retry:
if (get_user(uval, uaddr))
return -1;
if ((uval & FUTEX_TID_MASK) == task_pid_vnr(curr)) {
/*
* Ok, this dying thread is truly holding a futex
* of interest. Set the OWNER_DIED bit atomically
* via cmpxchg, and if the value had FUTEX_WAITERS
* set, wake up a waiter (if any). (We have to do a
* futex_wake() even if OWNER_DIED is already set -
* to handle the rare but possible case of recursive
* thread-death.) The rest of the cleanup is done in
* userspace.
*/
mval = (uval & FUTEX_WAITERS) | FUTEX_OWNER_DIED;
/*
* We are not holding a lock here, but we want to have
* the pagefault_disable/enable() protection because
* we want to handle the fault gracefully. If the
* access fails we try to fault in the futex with R/W
* verification via get_user_pages. get_user() above
* does not guarantee R/W access. If that fails we
* give up and leave the futex locked.
*/
if (cmpxchg_futex_value_locked(&nval, uaddr, uval, mval)) {
if (fault_in_user_writeable(uaddr))
return -1;
goto retry;
}
if (nval != uval)
goto retry;
/*
* Wake robust non-PI futexes here. The wakeup of
* PI futexes happens in exit_pi_state():
*/
if (!pi && (uval & FUTEX_WAITERS))
futex_wake(uaddr, 1, 1, FUTEX_BITSET_MATCH_ANY);
}
return 0;
}
/*
* Fetch a robust-list pointer. Bit 0 signals PI futexes:
*/
static inline int fetch_robust_entry(struct robust_list __user **entry,
struct robust_list __user * __user *head,
unsigned int *pi)
{
unsigned long uentry;
if (get_user(uentry, (unsigned long __user *)head))
return -EFAULT;
*entry = (void __user *)(uentry & ~1UL);
*pi = uentry & 1;
return 0;
}
/*
* Walk curr->robust_list (very carefully, it's a userspace list!)
* and mark any locks found there dead, and notify any waiters.
*
* We silently return on any sign of list-walking problem.
*/
void exit_robust_list(struct task_struct *curr)
{
struct robust_list_head __user *head = curr->robust_list;
struct robust_list __user *entry, *next_entry, *pending;
unsigned int limit = ROBUST_LIST_LIMIT, pi, pip;
unsigned int uninitialized_var(next_pi);
unsigned long futex_offset;
int rc;
if (!futex_cmpxchg_enabled)
return;
/*
* Fetch the list head (which was registered earlier, via
* sys_set_robust_list()):
*/
if (fetch_robust_entry(&entry, &head->list.next, &pi))
return;
/*
* Fetch the relative futex offset:
*/
if (get_user(futex_offset, &head->futex_offset))
return;
/*
* Fetch any possibly pending lock-add first, and handle it
* if it exists:
*/
if (fetch_robust_entry(&pending, &head->list_op_pending, &pip))
return;
next_entry = NULL; /* avoid warning with gcc */
while (entry != &head->list) {
/*
* Fetch the next entry in the list before calling
* handle_futex_death:
*/
rc = fetch_robust_entry(&next_entry, &entry->next, &next_pi);
/*
* A pending lock might already be on the list, so
* don't process it twice:
*/
if (entry != pending)
if (handle_futex_death((void __user *)entry + futex_offset,
curr, pi))
return;
if (rc)
return;
entry = next_entry;
pi = next_pi;
/*
* Avoid excessively long or circular lists:
*/
if (!--limit)
break;
cond_resched();
}
if (pending)
handle_futex_death((void __user *)pending + futex_offset,
curr, pip);
}
long do_futex(u32 __user *uaddr, int op, u32 val, ktime_t *timeout,
u32 __user *uaddr2, u32 val2, u32 val3)
{
int cmd = op & FUTEX_CMD_MASK;
unsigned int flags = 0;
if (!(op & FUTEX_PRIVATE_FLAG))
flags |= FLAGS_SHARED;
if (op & FUTEX_CLOCK_REALTIME) {
flags |= FLAGS_CLOCKRT;
if (cmd != FUTEX_WAIT_BITSET && cmd != FUTEX_WAIT_REQUEUE_PI)
return -ENOSYS;
}
switch (cmd) {
case FUTEX_LOCK_PI:
case FUTEX_UNLOCK_PI:
case FUTEX_TRYLOCK_PI:
case FUTEX_WAIT_REQUEUE_PI:
case FUTEX_CMP_REQUEUE_PI:
if (!futex_cmpxchg_enabled)
return -ENOSYS;
}
switch (cmd) {
case FUTEX_WAIT:
val3 = FUTEX_BITSET_MATCH_ANY;
case FUTEX_WAIT_BITSET:
return futex_wait(uaddr, flags, val, timeout, val3);
case FUTEX_WAKE:
val3 = FUTEX_BITSET_MATCH_ANY;
case FUTEX_WAKE_BITSET:
return futex_wake(uaddr, flags, val, val3);
case FUTEX_REQUEUE:
return futex_requeue(uaddr, flags, uaddr2, val, val2, NULL, 0);
case FUTEX_CMP_REQUEUE:
return futex_requeue(uaddr, flags, uaddr2, val, val2, &val3, 0);
case FUTEX_WAKE_OP:
return futex_wake_op(uaddr, flags, uaddr2, val, val2, val3);
case FUTEX_LOCK_PI:
return futex_lock_pi(uaddr, flags, val, timeout, 0);
case FUTEX_UNLOCK_PI:
return futex_unlock_pi(uaddr, flags);
case FUTEX_TRYLOCK_PI:
return futex_lock_pi(uaddr, flags, 0, timeout, 1);
case FUTEX_WAIT_REQUEUE_PI:
val3 = FUTEX_BITSET_MATCH_ANY;
return futex_wait_requeue_pi(uaddr, flags, val, timeout, val3,
uaddr2);
case FUTEX_CMP_REQUEUE_PI:
return futex_requeue(uaddr, flags, uaddr2, val, val2, &val3, 1);
}
return -ENOSYS;
}
SYSCALL_DEFINE6(futex, u32 __user *, uaddr, int, op, u32, val,
struct timespec __user *, utime, u32 __user *, uaddr2,
u32, val3)
{
struct timespec ts;
ktime_t t, *tp = NULL;
u32 val2 = 0;
int cmd = op & FUTEX_CMD_MASK;
if (utime && (cmd == FUTEX_WAIT || cmd == FUTEX_LOCK_PI ||
cmd == FUTEX_WAIT_BITSET ||
cmd == FUTEX_WAIT_REQUEUE_PI)) {
if (copy_from_user(&ts, utime, sizeof(ts)) != 0)
return -EFAULT;
if (!timespec_valid(&ts))
return -EINVAL;
t = timespec_to_ktime(ts);
if (cmd == FUTEX_WAIT)
t = ktime_add_safe(ktime_get(), t);
tp = &t;
}
/*
* requeue parameter in 'utime' if cmd == FUTEX_*_REQUEUE_*.
* number of waiters to wake in 'utime' if cmd == FUTEX_WAKE_OP.
*/
if (cmd == FUTEX_REQUEUE || cmd == FUTEX_CMP_REQUEUE ||
cmd == FUTEX_CMP_REQUEUE_PI || cmd == FUTEX_WAKE_OP)
val2 = (u32) (unsigned long) utime;
return do_futex(uaddr, op, val, tp, uaddr2, val2, val3);
}
static void __init futex_detect_cmpxchg(void)
{
#ifndef CONFIG_HAVE_FUTEX_CMPXCHG
u32 curval;
/*
* This will fail and we want it. Some arch implementations do
* runtime detection of the futex_atomic_cmpxchg_inatomic()
* functionality. We want to know that before we call in any
* of the complex code paths. Also we want to prevent
* registration of robust lists in that case. NULL is
* guaranteed to fault and we get -EFAULT on functional
* implementation, the non-functional ones will return
* -ENOSYS.
*/
if (cmpxchg_futex_value_locked(&curval, NULL, 0, 0) == -EFAULT)
futex_cmpxchg_enabled = 1;
#endif
}
static int __init futex_init(void)
{
int i;
futex_detect_cmpxchg();
for (i = 0; i < ARRAY_SIZE(futex_queues); i++) {
plist_head_init(&futex_queues[i].chain);
spin_lock_init(&futex_queues[i].lock);
}
return 0;
}
__initcall(futex_init);
| Psycho666/Simplicity_trlte_kernel | kernel/futex.c | C | gpl-2.0 | 77,612 |
/* Automatically generated from ../src/remote/remote_protocol.x by gendispatch.pl.
* Do not edit this file. Any changes you make will be lost.
*/
static int remoteDispatchAuthList(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_auth_list_ret *ret);
static int remoteDispatchAuthListHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args ATTRIBUTE_UNUSED,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchAuthList(server, client, msg, rerr, ret);
}
/* remoteDispatchAuthList body has to be implemented manually */
static int remoteDispatchAuthPolkit(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_auth_polkit_ret *ret);
static int remoteDispatchAuthPolkitHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args ATTRIBUTE_UNUSED,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchAuthPolkit(server, client, msg, rerr, ret);
}
/* remoteDispatchAuthPolkit body has to be implemented manually */
static int remoteDispatchAuthSaslInit(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_auth_sasl_init_ret *ret);
static int remoteDispatchAuthSaslInitHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args ATTRIBUTE_UNUSED,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchAuthSaslInit(server, client, msg, rerr, ret);
}
/* remoteDispatchAuthSaslInit body has to be implemented manually */
static int remoteDispatchAuthSaslStart(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_auth_sasl_start_args *args,
remote_auth_sasl_start_ret *ret);
static int remoteDispatchAuthSaslStartHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchAuthSaslStart(server, client, msg, rerr, args, ret);
}
/* remoteDispatchAuthSaslStart body has to be implemented manually */
static int remoteDispatchAuthSaslStep(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_auth_sasl_step_args *args,
remote_auth_sasl_step_ret *ret);
static int remoteDispatchAuthSaslStepHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchAuthSaslStep(server, client, msg, rerr, args, ret);
}
/* remoteDispatchAuthSaslStep body has to be implemented manually */
static int remoteDispatchConnectBaselineCPU(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_connect_baseline_cpu_args *args,
remote_connect_baseline_cpu_ret *ret);
static int remoteDispatchConnectBaselineCPUHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchConnectBaselineCPU(server, client, msg, rerr, args, ret);
}
static int remoteDispatchConnectBaselineCPU(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_connect_baseline_cpu_args *args,
remote_connect_baseline_cpu_ret *ret)
{
int rv = -1;
char *cpu;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if ((cpu = virConnectBaselineCPU(priv->conn, (const char **) args->xmlCPUs.xmlCPUs_val, args->xmlCPUs.xmlCPUs_len, args->flags)) == NULL)
goto cleanup;
ret->cpu = cpu;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
return rv;
}
static int remoteDispatchConnectClose(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr);
static int remoteDispatchConnectCloseHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args ATTRIBUTE_UNUSED,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchConnectClose(server, client, msg, rerr);
}
/* remoteDispatchConnectClose body has to be implemented manually */
static int remoteDispatchConnectCompareCPU(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_connect_compare_cpu_args *args,
remote_connect_compare_cpu_ret *ret);
static int remoteDispatchConnectCompareCPUHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchConnectCompareCPU(server, client, msg, rerr, args, ret);
}
static int remoteDispatchConnectCompareCPU(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_connect_compare_cpu_args *args,
remote_connect_compare_cpu_ret *ret)
{
int rv = -1;
int result;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if ((result = virConnectCompareCPU(priv->conn, args->xml, args->flags)) < 0)
goto cleanup;
ret->result = result;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
return rv;
}
static int remoteDispatchConnectDomainEventCallbackDeregisterAny(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_connect_domain_event_callback_deregister_any_args *args);
static int remoteDispatchConnectDomainEventCallbackDeregisterAnyHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchConnectDomainEventCallbackDeregisterAny(server, client, msg, rerr, args);
}
/* remoteDispatchConnectDomainEventCallbackDeregisterAny body has to be implemented manually */
static int remoteDispatchConnectDomainEventCallbackRegisterAny(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_connect_domain_event_callback_register_any_args *args,
remote_connect_domain_event_callback_register_any_ret *ret);
static int remoteDispatchConnectDomainEventCallbackRegisterAnyHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchConnectDomainEventCallbackRegisterAny(server, client, msg, rerr, args, ret);
}
/* remoteDispatchConnectDomainEventCallbackRegisterAny body has to be implemented manually */
static int remoteDispatchConnectDomainEventDeregister(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_connect_domain_event_deregister_ret *ret);
static int remoteDispatchConnectDomainEventDeregisterHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args ATTRIBUTE_UNUSED,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchConnectDomainEventDeregister(server, client, msg, rerr, ret);
}
/* remoteDispatchConnectDomainEventDeregister body has to be implemented manually */
static int remoteDispatchConnectDomainEventDeregisterAny(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_connect_domain_event_deregister_any_args *args);
static int remoteDispatchConnectDomainEventDeregisterAnyHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchConnectDomainEventDeregisterAny(server, client, msg, rerr, args);
}
/* remoteDispatchConnectDomainEventDeregisterAny body has to be implemented manually */
static int remoteDispatchConnectDomainEventRegister(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_connect_domain_event_register_ret *ret);
static int remoteDispatchConnectDomainEventRegisterHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args ATTRIBUTE_UNUSED,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchConnectDomainEventRegister(server, client, msg, rerr, ret);
}
/* remoteDispatchConnectDomainEventRegister body has to be implemented manually */
static int remoteDispatchConnectDomainEventRegisterAny(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_connect_domain_event_register_any_args *args);
static int remoteDispatchConnectDomainEventRegisterAnyHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchConnectDomainEventRegisterAny(server, client, msg, rerr, args);
}
/* remoteDispatchConnectDomainEventRegisterAny body has to be implemented manually */
static int remoteDispatchConnectDomainXMLFromNative(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_connect_domain_xml_from_native_args *args,
remote_connect_domain_xml_from_native_ret *ret);
static int remoteDispatchConnectDomainXMLFromNativeHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchConnectDomainXMLFromNative(server, client, msg, rerr, args, ret);
}
static int remoteDispatchConnectDomainXMLFromNative(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_connect_domain_xml_from_native_args *args,
remote_connect_domain_xml_from_native_ret *ret)
{
int rv = -1;
char *domainXml;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if ((domainXml = virConnectDomainXMLFromNative(priv->conn, args->nativeFormat, args->nativeConfig, args->flags)) == NULL)
goto cleanup;
ret->domainXml = domainXml;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
return rv;
}
static int remoteDispatchConnectDomainXMLToNative(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_connect_domain_xml_to_native_args *args,
remote_connect_domain_xml_to_native_ret *ret);
static int remoteDispatchConnectDomainXMLToNativeHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchConnectDomainXMLToNative(server, client, msg, rerr, args, ret);
}
static int remoteDispatchConnectDomainXMLToNative(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_connect_domain_xml_to_native_args *args,
remote_connect_domain_xml_to_native_ret *ret)
{
int rv = -1;
char *nativeConfig;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if ((nativeConfig = virConnectDomainXMLToNative(priv->conn, args->nativeFormat, args->domainXml, args->flags)) == NULL)
goto cleanup;
ret->nativeConfig = nativeConfig;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
return rv;
}
static int remoteDispatchConnectFindStoragePoolSources(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_connect_find_storage_pool_sources_args *args,
remote_connect_find_storage_pool_sources_ret *ret);
static int remoteDispatchConnectFindStoragePoolSourcesHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchConnectFindStoragePoolSources(server, client, msg, rerr, args, ret);
}
static int remoteDispatchConnectFindStoragePoolSources(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_connect_find_storage_pool_sources_args *args,
remote_connect_find_storage_pool_sources_ret *ret)
{
int rv = -1;
char *srcSpec;
char *xml;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
srcSpec = args->srcSpec ? *args->srcSpec : NULL;
if ((xml = virConnectFindStoragePoolSources(priv->conn, args->type, srcSpec, args->flags)) == NULL)
goto cleanup;
ret->xml = xml;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
return rv;
}
static int remoteDispatchConnectGetCapabilities(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_connect_get_capabilities_ret *ret);
static int remoteDispatchConnectGetCapabilitiesHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args ATTRIBUTE_UNUSED,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchConnectGetCapabilities(server, client, msg, rerr, ret);
}
static int remoteDispatchConnectGetCapabilities(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_connect_get_capabilities_ret *ret)
{
int rv = -1;
char *capabilities;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if ((capabilities = virConnectGetCapabilities(priv->conn)) == NULL)
goto cleanup;
ret->capabilities = capabilities;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
return rv;
}
static int remoteDispatchConnectGetCPUModelNames(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_connect_get_cpu_model_names_args *args,
remote_connect_get_cpu_model_names_ret *ret);
static int remoteDispatchConnectGetCPUModelNamesHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchConnectGetCPUModelNames(server, client, msg, rerr, args, ret);
}
/* remoteDispatchConnectGetCPUModelNames body has to be implemented manually */
static int remoteDispatchConnectGetHostname(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_connect_get_hostname_ret *ret);
static int remoteDispatchConnectGetHostnameHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args ATTRIBUTE_UNUSED,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchConnectGetHostname(server, client, msg, rerr, ret);
}
static int remoteDispatchConnectGetHostname(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_connect_get_hostname_ret *ret)
{
int rv = -1;
char *hostname;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if ((hostname = virConnectGetHostname(priv->conn)) == NULL)
goto cleanup;
ret->hostname = hostname;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
return rv;
}
static int remoteDispatchConnectGetLibVersion(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_connect_get_lib_version_ret *ret);
static int remoteDispatchConnectGetLibVersionHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args ATTRIBUTE_UNUSED,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchConnectGetLibVersion(server, client, msg, rerr, ret);
}
static int remoteDispatchConnectGetLibVersion(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_connect_get_lib_version_ret *ret)
{
int rv = -1;
unsigned long lib_ver;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (virConnectGetLibVersion(priv->conn, &lib_ver) < 0)
goto cleanup;
HYPER_TO_ULONG(ret->lib_ver, lib_ver);
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
return rv;
}
static int remoteDispatchConnectGetMaxVcpus(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_connect_get_max_vcpus_args *args,
remote_connect_get_max_vcpus_ret *ret);
static int remoteDispatchConnectGetMaxVcpusHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchConnectGetMaxVcpus(server, client, msg, rerr, args, ret);
}
static int remoteDispatchConnectGetMaxVcpus(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_connect_get_max_vcpus_args *args,
remote_connect_get_max_vcpus_ret *ret)
{
int rv = -1;
char *type;
int max_vcpus;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
type = args->type ? *args->type : NULL;
if ((max_vcpus = virConnectGetMaxVcpus(priv->conn, type)) < 0)
goto cleanup;
ret->max_vcpus = max_vcpus;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
return rv;
}
static int remoteDispatchConnectGetSysinfo(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_connect_get_sysinfo_args *args,
remote_connect_get_sysinfo_ret *ret);
static int remoteDispatchConnectGetSysinfoHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchConnectGetSysinfo(server, client, msg, rerr, args, ret);
}
static int remoteDispatchConnectGetSysinfo(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_connect_get_sysinfo_args *args,
remote_connect_get_sysinfo_ret *ret)
{
int rv = -1;
char *sysinfo;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if ((sysinfo = virConnectGetSysinfo(priv->conn, args->flags)) == NULL)
goto cleanup;
ret->sysinfo = sysinfo;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
return rv;
}
static int remoteDispatchConnectGetType(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_connect_get_type_ret *ret);
static int remoteDispatchConnectGetTypeHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args ATTRIBUTE_UNUSED,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchConnectGetType(server, client, msg, rerr, ret);
}
static int remoteDispatchConnectGetType(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_connect_get_type_ret *ret)
{
int rv = -1;
const char *type;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if ((type = virConnectGetType(priv->conn)) == NULL)
goto cleanup;
/* We have to VIR_STRDUP because remoteDispatchClientRequest will
* free this string after it's been serialised. */
if (VIR_STRDUP(ret->type, type) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
return rv;
}
static int remoteDispatchConnectGetURI(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_connect_get_uri_ret *ret);
static int remoteDispatchConnectGetURIHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args ATTRIBUTE_UNUSED,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchConnectGetURI(server, client, msg, rerr, ret);
}
static int remoteDispatchConnectGetURI(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_connect_get_uri_ret *ret)
{
int rv = -1;
char *uri;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if ((uri = virConnectGetURI(priv->conn)) == NULL)
goto cleanup;
ret->uri = uri;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
return rv;
}
static int remoteDispatchConnectGetVersion(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_connect_get_version_ret *ret);
static int remoteDispatchConnectGetVersionHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args ATTRIBUTE_UNUSED,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchConnectGetVersion(server, client, msg, rerr, ret);
}
static int remoteDispatchConnectGetVersion(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_connect_get_version_ret *ret)
{
int rv = -1;
unsigned long hv_ver;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (virConnectGetVersion(priv->conn, &hv_ver) < 0)
goto cleanup;
HYPER_TO_ULONG(ret->hv_ver, hv_ver);
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
return rv;
}
static int remoteDispatchConnectIsSecure(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_connect_is_secure_ret *ret);
static int remoteDispatchConnectIsSecureHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args ATTRIBUTE_UNUSED,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchConnectIsSecure(server, client, msg, rerr, ret);
}
static int remoteDispatchConnectIsSecure(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_connect_is_secure_ret *ret)
{
int rv = -1;
int secure;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if ((secure = virConnectIsSecure(priv->conn)) < 0)
goto cleanup;
ret->secure = secure;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
return rv;
}
static int remoteDispatchConnectListAllDomains(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_connect_list_all_domains_args *args,
remote_connect_list_all_domains_ret *ret);
static int remoteDispatchConnectListAllDomainsHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchConnectListAllDomains(server, client, msg, rerr, args, ret);
}
/* remoteDispatchConnectListAllDomains body has to be implemented manually */
static int remoteDispatchConnectListAllInterfaces(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_connect_list_all_interfaces_args *args,
remote_connect_list_all_interfaces_ret *ret);
static int remoteDispatchConnectListAllInterfacesHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchConnectListAllInterfaces(server, client, msg, rerr, args, ret);
}
/* remoteDispatchConnectListAllInterfaces body has to be implemented manually */
static int remoteDispatchConnectListAllNetworks(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_connect_list_all_networks_args *args,
remote_connect_list_all_networks_ret *ret);
static int remoteDispatchConnectListAllNetworksHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchConnectListAllNetworks(server, client, msg, rerr, args, ret);
}
/* remoteDispatchConnectListAllNetworks body has to be implemented manually */
static int remoteDispatchConnectListAllNodeDevices(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_connect_list_all_node_devices_args *args,
remote_connect_list_all_node_devices_ret *ret);
static int remoteDispatchConnectListAllNodeDevicesHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchConnectListAllNodeDevices(server, client, msg, rerr, args, ret);
}
/* remoteDispatchConnectListAllNodeDevices body has to be implemented manually */
static int remoteDispatchConnectListAllNWFilters(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_connect_list_all_nwfilters_args *args,
remote_connect_list_all_nwfilters_ret *ret);
static int remoteDispatchConnectListAllNWFiltersHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchConnectListAllNWFilters(server, client, msg, rerr, args, ret);
}
/* remoteDispatchConnectListAllNWFilters body has to be implemented manually */
static int remoteDispatchConnectListAllSecrets(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_connect_list_all_secrets_args *args,
remote_connect_list_all_secrets_ret *ret);
static int remoteDispatchConnectListAllSecretsHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchConnectListAllSecrets(server, client, msg, rerr, args, ret);
}
/* remoteDispatchConnectListAllSecrets body has to be implemented manually */
static int remoteDispatchConnectListAllStoragePools(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_connect_list_all_storage_pools_args *args,
remote_connect_list_all_storage_pools_ret *ret);
static int remoteDispatchConnectListAllStoragePoolsHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchConnectListAllStoragePools(server, client, msg, rerr, args, ret);
}
/* remoteDispatchConnectListAllStoragePools body has to be implemented manually */
static int remoteDispatchConnectListDefinedDomains(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_connect_list_defined_domains_args *args,
remote_connect_list_defined_domains_ret *ret);
static int remoteDispatchConnectListDefinedDomainsHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchConnectListDefinedDomains(server, client, msg, rerr, args, ret);
}
static int remoteDispatchConnectListDefinedDomains(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_connect_list_defined_domains_args *args,
remote_connect_list_defined_domains_ret *ret)
{
int rv = -1;
int len;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (args->maxnames > REMOTE_DOMAIN_LIST_MAX) {
virReportError(VIR_ERR_INTERNAL_ERROR,
"%s", _("maxnames > REMOTE_DOMAIN_LIST_MAX"));
goto cleanup;
}
/* Allocate return buffer. */
if (VIR_ALLOC_N(ret->names.names_val, args->maxnames) < 0)
goto cleanup;
if ((len = virConnectListDefinedDomains(priv->conn, ret->names.names_val, args->maxnames)) < 0)
goto cleanup;
ret->names.names_len = len;
rv = 0;
cleanup:
if (rv < 0) {
virNetMessageSaveError(rerr);
VIR_FREE(ret->names.names_val);
}
return rv;
}
static int remoteDispatchConnectListDefinedInterfaces(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_connect_list_defined_interfaces_args *args,
remote_connect_list_defined_interfaces_ret *ret);
static int remoteDispatchConnectListDefinedInterfacesHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchConnectListDefinedInterfaces(server, client, msg, rerr, args, ret);
}
static int remoteDispatchConnectListDefinedInterfaces(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_connect_list_defined_interfaces_args *args,
remote_connect_list_defined_interfaces_ret *ret)
{
int rv = -1;
int len;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (args->maxnames > REMOTE_INTERFACE_LIST_MAX) {
virReportError(VIR_ERR_INTERNAL_ERROR,
"%s", _("maxnames > REMOTE_INTERFACE_LIST_MAX"));
goto cleanup;
}
/* Allocate return buffer. */
if (VIR_ALLOC_N(ret->names.names_val, args->maxnames) < 0)
goto cleanup;
if ((len = virConnectListDefinedInterfaces(priv->conn, ret->names.names_val, args->maxnames)) < 0)
goto cleanup;
ret->names.names_len = len;
rv = 0;
cleanup:
if (rv < 0) {
virNetMessageSaveError(rerr);
VIR_FREE(ret->names.names_val);
}
return rv;
}
static int remoteDispatchConnectListDefinedNetworks(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_connect_list_defined_networks_args *args,
remote_connect_list_defined_networks_ret *ret);
static int remoteDispatchConnectListDefinedNetworksHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchConnectListDefinedNetworks(server, client, msg, rerr, args, ret);
}
static int remoteDispatchConnectListDefinedNetworks(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_connect_list_defined_networks_args *args,
remote_connect_list_defined_networks_ret *ret)
{
int rv = -1;
int len;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (args->maxnames > REMOTE_NETWORK_LIST_MAX) {
virReportError(VIR_ERR_INTERNAL_ERROR,
"%s", _("maxnames > REMOTE_NETWORK_LIST_MAX"));
goto cleanup;
}
/* Allocate return buffer. */
if (VIR_ALLOC_N(ret->names.names_val, args->maxnames) < 0)
goto cleanup;
if ((len = virConnectListDefinedNetworks(priv->conn, ret->names.names_val, args->maxnames)) < 0)
goto cleanup;
ret->names.names_len = len;
rv = 0;
cleanup:
if (rv < 0) {
virNetMessageSaveError(rerr);
VIR_FREE(ret->names.names_val);
}
return rv;
}
static int remoteDispatchConnectListDefinedStoragePools(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_connect_list_defined_storage_pools_args *args,
remote_connect_list_defined_storage_pools_ret *ret);
static int remoteDispatchConnectListDefinedStoragePoolsHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchConnectListDefinedStoragePools(server, client, msg, rerr, args, ret);
}
static int remoteDispatchConnectListDefinedStoragePools(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_connect_list_defined_storage_pools_args *args,
remote_connect_list_defined_storage_pools_ret *ret)
{
int rv = -1;
int len;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (args->maxnames > REMOTE_STORAGE_POOL_LIST_MAX) {
virReportError(VIR_ERR_INTERNAL_ERROR,
"%s", _("maxnames > REMOTE_STORAGE_POOL_LIST_MAX"));
goto cleanup;
}
/* Allocate return buffer. */
if (VIR_ALLOC_N(ret->names.names_val, args->maxnames) < 0)
goto cleanup;
if ((len = virConnectListDefinedStoragePools(priv->conn, ret->names.names_val, args->maxnames)) < 0)
goto cleanup;
ret->names.names_len = len;
rv = 0;
cleanup:
if (rv < 0) {
virNetMessageSaveError(rerr);
VIR_FREE(ret->names.names_val);
}
return rv;
}
static int remoteDispatchConnectListDomains(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_connect_list_domains_args *args,
remote_connect_list_domains_ret *ret);
static int remoteDispatchConnectListDomainsHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchConnectListDomains(server, client, msg, rerr, args, ret);
}
static int remoteDispatchConnectListDomains(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_connect_list_domains_args *args,
remote_connect_list_domains_ret *ret)
{
int rv = -1;
int len;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (args->maxids > REMOTE_DOMAIN_LIST_MAX) {
virReportError(VIR_ERR_INTERNAL_ERROR,
"%s", _("maxids > REMOTE_DOMAIN_LIST_MAX"));
goto cleanup;
}
/* Allocate return buffer. */
if (VIR_ALLOC_N(ret->ids.ids_val, args->maxids) < 0)
goto cleanup;
if ((len = virConnectListDomains(priv->conn, ret->ids.ids_val, args->maxids)) < 0)
goto cleanup;
ret->ids.ids_len = len;
rv = 0;
cleanup:
if (rv < 0) {
virNetMessageSaveError(rerr);
VIR_FREE(ret->ids.ids_val);
}
return rv;
}
static int remoteDispatchConnectListInterfaces(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_connect_list_interfaces_args *args,
remote_connect_list_interfaces_ret *ret);
static int remoteDispatchConnectListInterfacesHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchConnectListInterfaces(server, client, msg, rerr, args, ret);
}
static int remoteDispatchConnectListInterfaces(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_connect_list_interfaces_args *args,
remote_connect_list_interfaces_ret *ret)
{
int rv = -1;
int len;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (args->maxnames > REMOTE_INTERFACE_LIST_MAX) {
virReportError(VIR_ERR_INTERNAL_ERROR,
"%s", _("maxnames > REMOTE_INTERFACE_LIST_MAX"));
goto cleanup;
}
/* Allocate return buffer. */
if (VIR_ALLOC_N(ret->names.names_val, args->maxnames) < 0)
goto cleanup;
if ((len = virConnectListInterfaces(priv->conn, ret->names.names_val, args->maxnames)) < 0)
goto cleanup;
ret->names.names_len = len;
rv = 0;
cleanup:
if (rv < 0) {
virNetMessageSaveError(rerr);
VIR_FREE(ret->names.names_val);
}
return rv;
}
static int remoteDispatchConnectListNetworks(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_connect_list_networks_args *args,
remote_connect_list_networks_ret *ret);
static int remoteDispatchConnectListNetworksHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchConnectListNetworks(server, client, msg, rerr, args, ret);
}
static int remoteDispatchConnectListNetworks(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_connect_list_networks_args *args,
remote_connect_list_networks_ret *ret)
{
int rv = -1;
int len;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (args->maxnames > REMOTE_NETWORK_LIST_MAX) {
virReportError(VIR_ERR_INTERNAL_ERROR,
"%s", _("maxnames > REMOTE_NETWORK_LIST_MAX"));
goto cleanup;
}
/* Allocate return buffer. */
if (VIR_ALLOC_N(ret->names.names_val, args->maxnames) < 0)
goto cleanup;
if ((len = virConnectListNetworks(priv->conn, ret->names.names_val, args->maxnames)) < 0)
goto cleanup;
ret->names.names_len = len;
rv = 0;
cleanup:
if (rv < 0) {
virNetMessageSaveError(rerr);
VIR_FREE(ret->names.names_val);
}
return rv;
}
static int remoteDispatchConnectListNWFilters(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_connect_list_nwfilters_args *args,
remote_connect_list_nwfilters_ret *ret);
static int remoteDispatchConnectListNWFiltersHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchConnectListNWFilters(server, client, msg, rerr, args, ret);
}
static int remoteDispatchConnectListNWFilters(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_connect_list_nwfilters_args *args,
remote_connect_list_nwfilters_ret *ret)
{
int rv = -1;
int len;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (args->maxnames > REMOTE_NWFILTER_LIST_MAX) {
virReportError(VIR_ERR_INTERNAL_ERROR,
"%s", _("maxnames > REMOTE_NWFILTER_LIST_MAX"));
goto cleanup;
}
/* Allocate return buffer. */
if (VIR_ALLOC_N(ret->names.names_val, args->maxnames) < 0)
goto cleanup;
if ((len = virConnectListNWFilters(priv->conn, ret->names.names_val, args->maxnames)) < 0)
goto cleanup;
ret->names.names_len = len;
rv = 0;
cleanup:
if (rv < 0) {
virNetMessageSaveError(rerr);
VIR_FREE(ret->names.names_val);
}
return rv;
}
static int remoteDispatchConnectListSecrets(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_connect_list_secrets_args *args,
remote_connect_list_secrets_ret *ret);
static int remoteDispatchConnectListSecretsHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchConnectListSecrets(server, client, msg, rerr, args, ret);
}
static int remoteDispatchConnectListSecrets(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_connect_list_secrets_args *args,
remote_connect_list_secrets_ret *ret)
{
int rv = -1;
int len;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (args->maxuuids > REMOTE_SECRET_LIST_MAX) {
virReportError(VIR_ERR_INTERNAL_ERROR,
"%s", _("maxuuids > REMOTE_SECRET_LIST_MAX"));
goto cleanup;
}
/* Allocate return buffer. */
if (VIR_ALLOC_N(ret->uuids.uuids_val, args->maxuuids) < 0)
goto cleanup;
if ((len = virConnectListSecrets(priv->conn, ret->uuids.uuids_val, args->maxuuids)) < 0)
goto cleanup;
ret->uuids.uuids_len = len;
rv = 0;
cleanup:
if (rv < 0) {
virNetMessageSaveError(rerr);
VIR_FREE(ret->uuids.uuids_val);
}
return rv;
}
static int remoteDispatchConnectListStoragePools(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_connect_list_storage_pools_args *args,
remote_connect_list_storage_pools_ret *ret);
static int remoteDispatchConnectListStoragePoolsHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchConnectListStoragePools(server, client, msg, rerr, args, ret);
}
static int remoteDispatchConnectListStoragePools(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_connect_list_storage_pools_args *args,
remote_connect_list_storage_pools_ret *ret)
{
int rv = -1;
int len;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (args->maxnames > REMOTE_STORAGE_POOL_LIST_MAX) {
virReportError(VIR_ERR_INTERNAL_ERROR,
"%s", _("maxnames > REMOTE_STORAGE_POOL_LIST_MAX"));
goto cleanup;
}
/* Allocate return buffer. */
if (VIR_ALLOC_N(ret->names.names_val, args->maxnames) < 0)
goto cleanup;
if ((len = virConnectListStoragePools(priv->conn, ret->names.names_val, args->maxnames)) < 0)
goto cleanup;
ret->names.names_len = len;
rv = 0;
cleanup:
if (rv < 0) {
virNetMessageSaveError(rerr);
VIR_FREE(ret->names.names_val);
}
return rv;
}
static int remoteDispatchConnectNetworkEventDeregisterAny(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_connect_network_event_deregister_any_args *args);
static int remoteDispatchConnectNetworkEventDeregisterAnyHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchConnectNetworkEventDeregisterAny(server, client, msg, rerr, args);
}
/* remoteDispatchConnectNetworkEventDeregisterAny body has to be implemented manually */
static int remoteDispatchConnectNetworkEventRegisterAny(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_connect_network_event_register_any_args *args,
remote_connect_network_event_register_any_ret *ret);
static int remoteDispatchConnectNetworkEventRegisterAnyHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchConnectNetworkEventRegisterAny(server, client, msg, rerr, args, ret);
}
/* remoteDispatchConnectNetworkEventRegisterAny body has to be implemented manually */
static int remoteDispatchConnectNumOfDefinedDomains(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_connect_num_of_defined_domains_ret *ret);
static int remoteDispatchConnectNumOfDefinedDomainsHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args ATTRIBUTE_UNUSED,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchConnectNumOfDefinedDomains(server, client, msg, rerr, ret);
}
static int remoteDispatchConnectNumOfDefinedDomains(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_connect_num_of_defined_domains_ret *ret)
{
int rv = -1;
int num;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if ((num = virConnectNumOfDefinedDomains(priv->conn)) < 0)
goto cleanup;
ret->num = num;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
return rv;
}
static int remoteDispatchConnectNumOfDefinedInterfaces(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_connect_num_of_defined_interfaces_ret *ret);
static int remoteDispatchConnectNumOfDefinedInterfacesHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args ATTRIBUTE_UNUSED,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchConnectNumOfDefinedInterfaces(server, client, msg, rerr, ret);
}
static int remoteDispatchConnectNumOfDefinedInterfaces(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_connect_num_of_defined_interfaces_ret *ret)
{
int rv = -1;
int num;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if ((num = virConnectNumOfDefinedInterfaces(priv->conn)) < 0)
goto cleanup;
ret->num = num;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
return rv;
}
static int remoteDispatchConnectNumOfDefinedNetworks(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_connect_num_of_defined_networks_ret *ret);
static int remoteDispatchConnectNumOfDefinedNetworksHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args ATTRIBUTE_UNUSED,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchConnectNumOfDefinedNetworks(server, client, msg, rerr, ret);
}
static int remoteDispatchConnectNumOfDefinedNetworks(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_connect_num_of_defined_networks_ret *ret)
{
int rv = -1;
int num;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if ((num = virConnectNumOfDefinedNetworks(priv->conn)) < 0)
goto cleanup;
ret->num = num;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
return rv;
}
static int remoteDispatchConnectNumOfDefinedStoragePools(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_connect_num_of_defined_storage_pools_ret *ret);
static int remoteDispatchConnectNumOfDefinedStoragePoolsHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args ATTRIBUTE_UNUSED,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchConnectNumOfDefinedStoragePools(server, client, msg, rerr, ret);
}
static int remoteDispatchConnectNumOfDefinedStoragePools(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_connect_num_of_defined_storage_pools_ret *ret)
{
int rv = -1;
int num;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if ((num = virConnectNumOfDefinedStoragePools(priv->conn)) < 0)
goto cleanup;
ret->num = num;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
return rv;
}
static int remoteDispatchConnectNumOfDomains(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_connect_num_of_domains_ret *ret);
static int remoteDispatchConnectNumOfDomainsHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args ATTRIBUTE_UNUSED,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchConnectNumOfDomains(server, client, msg, rerr, ret);
}
static int remoteDispatchConnectNumOfDomains(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_connect_num_of_domains_ret *ret)
{
int rv = -1;
int num;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if ((num = virConnectNumOfDomains(priv->conn)) < 0)
goto cleanup;
ret->num = num;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
return rv;
}
static int remoteDispatchConnectNumOfInterfaces(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_connect_num_of_interfaces_ret *ret);
static int remoteDispatchConnectNumOfInterfacesHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args ATTRIBUTE_UNUSED,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchConnectNumOfInterfaces(server, client, msg, rerr, ret);
}
static int remoteDispatchConnectNumOfInterfaces(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_connect_num_of_interfaces_ret *ret)
{
int rv = -1;
int num;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if ((num = virConnectNumOfInterfaces(priv->conn)) < 0)
goto cleanup;
ret->num = num;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
return rv;
}
static int remoteDispatchConnectNumOfNetworks(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_connect_num_of_networks_ret *ret);
static int remoteDispatchConnectNumOfNetworksHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args ATTRIBUTE_UNUSED,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchConnectNumOfNetworks(server, client, msg, rerr, ret);
}
static int remoteDispatchConnectNumOfNetworks(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_connect_num_of_networks_ret *ret)
{
int rv = -1;
int num;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if ((num = virConnectNumOfNetworks(priv->conn)) < 0)
goto cleanup;
ret->num = num;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
return rv;
}
static int remoteDispatchConnectNumOfNWFilters(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_connect_num_of_nwfilters_ret *ret);
static int remoteDispatchConnectNumOfNWFiltersHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args ATTRIBUTE_UNUSED,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchConnectNumOfNWFilters(server, client, msg, rerr, ret);
}
static int remoteDispatchConnectNumOfNWFilters(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_connect_num_of_nwfilters_ret *ret)
{
int rv = -1;
int num;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if ((num = virConnectNumOfNWFilters(priv->conn)) < 0)
goto cleanup;
ret->num = num;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
return rv;
}
static int remoteDispatchConnectNumOfSecrets(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_connect_num_of_secrets_ret *ret);
static int remoteDispatchConnectNumOfSecretsHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args ATTRIBUTE_UNUSED,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchConnectNumOfSecrets(server, client, msg, rerr, ret);
}
static int remoteDispatchConnectNumOfSecrets(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_connect_num_of_secrets_ret *ret)
{
int rv = -1;
int num;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if ((num = virConnectNumOfSecrets(priv->conn)) < 0)
goto cleanup;
ret->num = num;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
return rv;
}
static int remoteDispatchConnectNumOfStoragePools(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_connect_num_of_storage_pools_ret *ret);
static int remoteDispatchConnectNumOfStoragePoolsHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args ATTRIBUTE_UNUSED,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchConnectNumOfStoragePools(server, client, msg, rerr, ret);
}
static int remoteDispatchConnectNumOfStoragePools(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_connect_num_of_storage_pools_ret *ret)
{
int rv = -1;
int num;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if ((num = virConnectNumOfStoragePools(priv->conn)) < 0)
goto cleanup;
ret->num = num;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
return rv;
}
static int remoteDispatchConnectOpen(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_connect_open_args *args);
static int remoteDispatchConnectOpenHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchConnectOpen(server, client, msg, rerr, args);
}
/* remoteDispatchConnectOpen body has to be implemented manually */
static int remoteDispatchConnectSupportsFeature(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_connect_supports_feature_args *args,
remote_connect_supports_feature_ret *ret);
static int remoteDispatchConnectSupportsFeatureHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchConnectSupportsFeature(server, client, msg, rerr, args, ret);
}
/* remoteDispatchConnectSupportsFeature body has to be implemented manually */
static int remoteDispatchDomainAbortJob(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_abort_job_args *args);
static int remoteDispatchDomainAbortJobHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainAbortJob(server, client, msg, rerr, args);
}
static int remoteDispatchDomainAbortJob(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_abort_job_args *args)
{
int rv = -1;
virDomainPtr dom = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
if (virDomainAbortJob(dom) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainAttachDevice(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_attach_device_args *args);
static int remoteDispatchDomainAttachDeviceHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainAttachDevice(server, client, msg, rerr, args);
}
static int remoteDispatchDomainAttachDevice(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_attach_device_args *args)
{
int rv = -1;
virDomainPtr dom = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
if (virDomainAttachDevice(dom, args->xml) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainAttachDeviceFlags(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_attach_device_flags_args *args);
static int remoteDispatchDomainAttachDeviceFlagsHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainAttachDeviceFlags(server, client, msg, rerr, args);
}
static int remoteDispatchDomainAttachDeviceFlags(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_attach_device_flags_args *args)
{
int rv = -1;
virDomainPtr dom = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
if (virDomainAttachDeviceFlags(dom, args->xml, args->flags) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainBlockCommit(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_block_commit_args *args);
static int remoteDispatchDomainBlockCommitHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainBlockCommit(server, client, msg, rerr, args);
}
static int remoteDispatchDomainBlockCommit(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_block_commit_args *args)
{
int rv = -1;
virDomainPtr dom = NULL;
char *base;
char *top;
unsigned long bandwidth;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
HYPER_TO_ULONG(bandwidth, args->bandwidth);
base = args->base ? *args->base : NULL;
top = args->top ? *args->top : NULL;
if (virDomainBlockCommit(dom, args->disk, base, top, bandwidth, args->flags) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainBlockJobAbort(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_block_job_abort_args *args);
static int remoteDispatchDomainBlockJobAbortHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainBlockJobAbort(server, client, msg, rerr, args);
}
static int remoteDispatchDomainBlockJobAbort(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_block_job_abort_args *args)
{
int rv = -1;
virDomainPtr dom = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
if (virDomainBlockJobAbort(dom, args->path, args->flags) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainBlockJobSetSpeed(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_block_job_set_speed_args *args);
static int remoteDispatchDomainBlockJobSetSpeedHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainBlockJobSetSpeed(server, client, msg, rerr, args);
}
static int remoteDispatchDomainBlockJobSetSpeed(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_block_job_set_speed_args *args)
{
int rv = -1;
virDomainPtr dom = NULL;
unsigned long bandwidth;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
HYPER_TO_ULONG(bandwidth, args->bandwidth);
if (virDomainBlockJobSetSpeed(dom, args->path, bandwidth, args->flags) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainBlockPeek(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_block_peek_args *args,
remote_domain_block_peek_ret *ret);
static int remoteDispatchDomainBlockPeekHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainBlockPeek(server, client, msg, rerr, args, ret);
}
/* remoteDispatchDomainBlockPeek body has to be implemented manually */
static int remoteDispatchDomainBlockPull(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_block_pull_args *args);
static int remoteDispatchDomainBlockPullHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainBlockPull(server, client, msg, rerr, args);
}
static int remoteDispatchDomainBlockPull(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_block_pull_args *args)
{
int rv = -1;
virDomainPtr dom = NULL;
unsigned long bandwidth;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
HYPER_TO_ULONG(bandwidth, args->bandwidth);
if (virDomainBlockPull(dom, args->path, bandwidth, args->flags) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainBlockRebase(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_block_rebase_args *args);
static int remoteDispatchDomainBlockRebaseHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainBlockRebase(server, client, msg, rerr, args);
}
static int remoteDispatchDomainBlockRebase(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_block_rebase_args *args)
{
int rv = -1;
virDomainPtr dom = NULL;
char *base;
unsigned long bandwidth;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
HYPER_TO_ULONG(bandwidth, args->bandwidth);
base = args->base ? *args->base : NULL;
if (virDomainBlockRebase(dom, args->path, base, bandwidth, args->flags) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainBlockResize(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_block_resize_args *args);
static int remoteDispatchDomainBlockResizeHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainBlockResize(server, client, msg, rerr, args);
}
static int remoteDispatchDomainBlockResize(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_block_resize_args *args)
{
int rv = -1;
virDomainPtr dom = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
if (virDomainBlockResize(dom, args->disk, args->size, args->flags) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainBlockStats(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_block_stats_args *args,
remote_domain_block_stats_ret *ret);
static int remoteDispatchDomainBlockStatsHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainBlockStats(server, client, msg, rerr, args, ret);
}
static int remoteDispatchDomainBlockStats(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_block_stats_args *args,
remote_domain_block_stats_ret *ret)
{
int rv = -1;
virDomainPtr dom = NULL;
virDomainBlockStatsStruct tmp;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
if (virDomainBlockStats(dom, args->path, &tmp, sizeof(tmp)) < 0)
goto cleanup;
ret->rd_req = tmp.rd_req;
ret->rd_bytes = tmp.rd_bytes;
ret->wr_req = tmp.wr_req;
ret->wr_bytes = tmp.wr_bytes;
ret->errs = tmp.errs;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainBlockStatsFlags(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_block_stats_flags_args *args,
remote_domain_block_stats_flags_ret *ret);
static int remoteDispatchDomainBlockStatsFlagsHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainBlockStatsFlags(server, client, msg, rerr, args, ret);
}
/* remoteDispatchDomainBlockStatsFlags body has to be implemented manually */
static int remoteDispatchDomainCoreDump(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_core_dump_args *args);
static int remoteDispatchDomainCoreDumpHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainCoreDump(server, client, msg, rerr, args);
}
static int remoteDispatchDomainCoreDump(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_core_dump_args *args)
{
int rv = -1;
virDomainPtr dom = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
if (virDomainCoreDump(dom, args->to, args->flags) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainCoreDumpWithFormat(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_core_dump_with_format_args *args);
static int remoteDispatchDomainCoreDumpWithFormatHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainCoreDumpWithFormat(server, client, msg, rerr, args);
}
static int remoteDispatchDomainCoreDumpWithFormat(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_core_dump_with_format_args *args)
{
int rv = -1;
virDomainPtr dom = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
if (virDomainCoreDumpWithFormat(dom, args->to, args->dumpformat, args->flags) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainCreate(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_create_args *args);
static int remoteDispatchDomainCreateHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainCreate(server, client, msg, rerr, args);
}
static int remoteDispatchDomainCreate(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_create_args *args)
{
int rv = -1;
virDomainPtr dom = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
if (virDomainCreate(dom) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainCreateWithFiles(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_create_with_files_args *args,
remote_domain_create_with_files_ret *ret);
static int remoteDispatchDomainCreateWithFilesHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainCreateWithFiles(server, client, msg, rerr, args, ret);
}
/* remoteDispatchDomainCreateWithFiles body has to be implemented manually */
static int remoteDispatchDomainCreateWithFlags(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_create_with_flags_args *args,
remote_domain_create_with_flags_ret *ret);
static int remoteDispatchDomainCreateWithFlagsHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainCreateWithFlags(server, client, msg, rerr, args, ret);
}
static int remoteDispatchDomainCreateWithFlags(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_create_with_flags_args *args,
remote_domain_create_with_flags_ret *ret)
{
int rv = -1;
virDomainPtr dom = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
if (virDomainCreateWithFlags(dom, args->flags) < 0)
goto cleanup;
make_nonnull_domain(&ret->dom, dom);
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainCreateXML(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_create_xml_args *args,
remote_domain_create_xml_ret *ret);
static int remoteDispatchDomainCreateXMLHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainCreateXML(server, client, msg, rerr, args, ret);
}
static int remoteDispatchDomainCreateXML(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_create_xml_args *args,
remote_domain_create_xml_ret *ret)
{
int rv = -1;
virDomainPtr dom = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if ((dom = virDomainCreateXML(priv->conn, args->xml_desc, args->flags)) == NULL)
goto cleanup;
make_nonnull_domain(&ret->dom, dom);
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainCreateXMLWithFiles(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_create_xml_with_files_args *args,
remote_domain_create_xml_with_files_ret *ret);
static int remoteDispatchDomainCreateXMLWithFilesHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainCreateXMLWithFiles(server, client, msg, rerr, args, ret);
}
/* remoteDispatchDomainCreateXMLWithFiles body has to be implemented manually */
static int remoteDispatchDomainDefineXML(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_define_xml_args *args,
remote_domain_define_xml_ret *ret);
static int remoteDispatchDomainDefineXMLHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainDefineXML(server, client, msg, rerr, args, ret);
}
static int remoteDispatchDomainDefineXML(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_define_xml_args *args,
remote_domain_define_xml_ret *ret)
{
int rv = -1;
virDomainPtr dom = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if ((dom = virDomainDefineXML(priv->conn, args->xml)) == NULL)
goto cleanup;
make_nonnull_domain(&ret->dom, dom);
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainDestroy(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_destroy_args *args);
static int remoteDispatchDomainDestroyHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainDestroy(server, client, msg, rerr, args);
}
static int remoteDispatchDomainDestroy(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_destroy_args *args)
{
int rv = -1;
virDomainPtr dom = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
if (virDomainDestroy(dom) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainDestroyFlags(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_destroy_flags_args *args);
static int remoteDispatchDomainDestroyFlagsHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainDestroyFlags(server, client, msg, rerr, args);
}
static int remoteDispatchDomainDestroyFlags(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_destroy_flags_args *args)
{
int rv = -1;
virDomainPtr dom = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
if (virDomainDestroyFlags(dom, args->flags) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainDetachDevice(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_detach_device_args *args);
static int remoteDispatchDomainDetachDeviceHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainDetachDevice(server, client, msg, rerr, args);
}
static int remoteDispatchDomainDetachDevice(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_detach_device_args *args)
{
int rv = -1;
virDomainPtr dom = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
if (virDomainDetachDevice(dom, args->xml) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainDetachDeviceFlags(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_detach_device_flags_args *args);
static int remoteDispatchDomainDetachDeviceFlagsHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainDetachDeviceFlags(server, client, msg, rerr, args);
}
static int remoteDispatchDomainDetachDeviceFlags(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_detach_device_flags_args *args)
{
int rv = -1;
virDomainPtr dom = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
if (virDomainDetachDeviceFlags(dom, args->xml, args->flags) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainFSTrim(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_fstrim_args *args);
static int remoteDispatchDomainFSTrimHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainFSTrim(server, client, msg, rerr, args);
}
static int remoteDispatchDomainFSTrim(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_fstrim_args *args)
{
int rv = -1;
virDomainPtr dom = NULL;
char *mountPoint;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
mountPoint = args->mountPoint ? *args->mountPoint : NULL;
if (virDomainFSTrim(dom, mountPoint, args->minimum, args->flags) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainGetAutostart(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_get_autostart_args *args,
remote_domain_get_autostart_ret *ret);
static int remoteDispatchDomainGetAutostartHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainGetAutostart(server, client, msg, rerr, args, ret);
}
static int remoteDispatchDomainGetAutostart(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_get_autostart_args *args,
remote_domain_get_autostart_ret *ret)
{
int rv = -1;
virDomainPtr dom = NULL;
int autostart;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
if (virDomainGetAutostart(dom, &autostart) < 0)
goto cleanup;
ret->autostart = autostart;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainGetBlkioParameters(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_get_blkio_parameters_args *args,
remote_domain_get_blkio_parameters_ret *ret);
static int remoteDispatchDomainGetBlkioParametersHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainGetBlkioParameters(server, client, msg, rerr, args, ret);
}
/* remoteDispatchDomainGetBlkioParameters body has to be implemented manually */
static int remoteDispatchDomainGetBlockInfo(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_get_block_info_args *args,
remote_domain_get_block_info_ret *ret);
static int remoteDispatchDomainGetBlockInfoHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainGetBlockInfo(server, client, msg, rerr, args, ret);
}
static int remoteDispatchDomainGetBlockInfo(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_get_block_info_args *args,
remote_domain_get_block_info_ret *ret)
{
int rv = -1;
virDomainPtr dom = NULL;
virDomainBlockInfo tmp;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
if (virDomainGetBlockInfo(dom, args->path, &tmp, args->flags) < 0)
goto cleanup;
ret->allocation = tmp.allocation;
ret->capacity = tmp.capacity;
ret->physical = tmp.physical;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainGetBlockIoTune(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_get_block_io_tune_args *args,
remote_domain_get_block_io_tune_ret *ret);
static int remoteDispatchDomainGetBlockIoTuneHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainGetBlockIoTune(server, client, msg, rerr, args, ret);
}
/* remoteDispatchDomainGetBlockIoTune body has to be implemented manually */
static int remoteDispatchDomainGetBlockJobInfo(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_get_block_job_info_args *args,
remote_domain_get_block_job_info_ret *ret);
static int remoteDispatchDomainGetBlockJobInfoHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainGetBlockJobInfo(server, client, msg, rerr, args, ret);
}
/* remoteDispatchDomainGetBlockJobInfo body has to be implemented manually */
static int remoteDispatchDomainGetControlInfo(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_get_control_info_args *args,
remote_domain_get_control_info_ret *ret);
static int remoteDispatchDomainGetControlInfoHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainGetControlInfo(server, client, msg, rerr, args, ret);
}
static int remoteDispatchDomainGetControlInfo(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_get_control_info_args *args,
remote_domain_get_control_info_ret *ret)
{
int rv = -1;
virDomainPtr dom = NULL;
virDomainControlInfo tmp;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
if (virDomainGetControlInfo(dom, &tmp, args->flags) < 0)
goto cleanup;
ret->state = tmp.state;
ret->details = tmp.details;
ret->stateTime = tmp.stateTime;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainGetCPUStats(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_get_cpu_stats_args *args,
remote_domain_get_cpu_stats_ret *ret);
static int remoteDispatchDomainGetCPUStatsHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainGetCPUStats(server, client, msg, rerr, args, ret);
}
/* remoteDispatchDomainGetCPUStats body has to be implemented manually */
static int remoteDispatchDomainGetDiskErrors(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_get_disk_errors_args *args,
remote_domain_get_disk_errors_ret *ret);
static int remoteDispatchDomainGetDiskErrorsHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainGetDiskErrors(server, client, msg, rerr, args, ret);
}
/* remoteDispatchDomainGetDiskErrors body has to be implemented manually */
static int remoteDispatchDomainGetEmulatorPinInfo(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_get_emulator_pin_info_args *args,
remote_domain_get_emulator_pin_info_ret *ret);
static int remoteDispatchDomainGetEmulatorPinInfoHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainGetEmulatorPinInfo(server, client, msg, rerr, args, ret);
}
/* remoteDispatchDomainGetEmulatorPinInfo body has to be implemented manually */
static int remoteDispatchDomainGetHostname(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_get_hostname_args *args,
remote_domain_get_hostname_ret *ret);
static int remoteDispatchDomainGetHostnameHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainGetHostname(server, client, msg, rerr, args, ret);
}
static int remoteDispatchDomainGetHostname(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_get_hostname_args *args,
remote_domain_get_hostname_ret *ret)
{
int rv = -1;
virDomainPtr dom = NULL;
char *hostname;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
if ((hostname = virDomainGetHostname(dom, args->flags)) == NULL)
goto cleanup;
ret->hostname = hostname;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainGetInfo(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_get_info_args *args,
remote_domain_get_info_ret *ret);
static int remoteDispatchDomainGetInfoHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainGetInfo(server, client, msg, rerr, args, ret);
}
static int remoteDispatchDomainGetInfo(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_get_info_args *args,
remote_domain_get_info_ret *ret)
{
int rv = -1;
virDomainPtr dom = NULL;
virDomainInfo tmp;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
if (virDomainGetInfo(dom, &tmp) < 0)
goto cleanup;
ret->state = tmp.state;
ret->maxMem = tmp.maxMem;
ret->memory = tmp.memory;
ret->nrVirtCpu = tmp.nrVirtCpu;
ret->cpuTime = tmp.cpuTime;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainGetInterfaceParameters(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_get_interface_parameters_args *args,
remote_domain_get_interface_parameters_ret *ret);
static int remoteDispatchDomainGetInterfaceParametersHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainGetInterfaceParameters(server, client, msg, rerr, args, ret);
}
/* remoteDispatchDomainGetInterfaceParameters body has to be implemented manually */
static int remoteDispatchDomainGetJobInfo(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_get_job_info_args *args,
remote_domain_get_job_info_ret *ret);
static int remoteDispatchDomainGetJobInfoHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainGetJobInfo(server, client, msg, rerr, args, ret);
}
static int remoteDispatchDomainGetJobInfo(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_get_job_info_args *args,
remote_domain_get_job_info_ret *ret)
{
int rv = -1;
virDomainPtr dom = NULL;
virDomainJobInfo tmp;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
if (virDomainGetJobInfo(dom, &tmp) < 0)
goto cleanup;
ret->type = tmp.type;
ret->timeElapsed = tmp.timeElapsed;
ret->timeRemaining = tmp.timeRemaining;
ret->dataTotal = tmp.dataTotal;
ret->dataProcessed = tmp.dataProcessed;
ret->dataRemaining = tmp.dataRemaining;
ret->memTotal = tmp.memTotal;
ret->memProcessed = tmp.memProcessed;
ret->memRemaining = tmp.memRemaining;
ret->fileTotal = tmp.fileTotal;
ret->fileProcessed = tmp.fileProcessed;
ret->fileRemaining = tmp.fileRemaining;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainGetJobStats(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_get_job_stats_args *args,
remote_domain_get_job_stats_ret *ret);
static int remoteDispatchDomainGetJobStatsHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainGetJobStats(server, client, msg, rerr, args, ret);
}
/* remoteDispatchDomainGetJobStats body has to be implemented manually */
static int remoteDispatchDomainGetMaxMemory(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_get_max_memory_args *args,
remote_domain_get_max_memory_ret *ret);
static int remoteDispatchDomainGetMaxMemoryHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainGetMaxMemory(server, client, msg, rerr, args, ret);
}
static int remoteDispatchDomainGetMaxMemory(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_get_max_memory_args *args,
remote_domain_get_max_memory_ret *ret)
{
int rv = -1;
virDomainPtr dom = NULL;
unsigned long long memory;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
if ((memory = virDomainGetMaxMemory(dom)) == 0)
goto cleanup;
ret->memory = memory;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainGetMaxVcpus(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_get_max_vcpus_args *args,
remote_domain_get_max_vcpus_ret *ret);
static int remoteDispatchDomainGetMaxVcpusHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainGetMaxVcpus(server, client, msg, rerr, args, ret);
}
static int remoteDispatchDomainGetMaxVcpus(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_get_max_vcpus_args *args,
remote_domain_get_max_vcpus_ret *ret)
{
int rv = -1;
virDomainPtr dom = NULL;
int num;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
if ((num = virDomainGetMaxVcpus(dom)) < 0)
goto cleanup;
ret->num = num;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainGetMemoryParameters(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_get_memory_parameters_args *args,
remote_domain_get_memory_parameters_ret *ret);
static int remoteDispatchDomainGetMemoryParametersHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainGetMemoryParameters(server, client, msg, rerr, args, ret);
}
/* remoteDispatchDomainGetMemoryParameters body has to be implemented manually */
static int remoteDispatchDomainGetMetadata(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_get_metadata_args *args,
remote_domain_get_metadata_ret *ret);
static int remoteDispatchDomainGetMetadataHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainGetMetadata(server, client, msg, rerr, args, ret);
}
static int remoteDispatchDomainGetMetadata(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_get_metadata_args *args,
remote_domain_get_metadata_ret *ret)
{
int rv = -1;
virDomainPtr dom = NULL;
char *uri;
char *metadata;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
uri = args->uri ? *args->uri : NULL;
if ((metadata = virDomainGetMetadata(dom, args->type, uri, args->flags)) == NULL)
goto cleanup;
ret->metadata = metadata;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainGetNumaParameters(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_get_numa_parameters_args *args,
remote_domain_get_numa_parameters_ret *ret);
static int remoteDispatchDomainGetNumaParametersHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainGetNumaParameters(server, client, msg, rerr, args, ret);
}
/* remoteDispatchDomainGetNumaParameters body has to be implemented manually */
static int remoteDispatchDomainGetOSType(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_get_os_type_args *args,
remote_domain_get_os_type_ret *ret);
static int remoteDispatchDomainGetOSTypeHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainGetOSType(server, client, msg, rerr, args, ret);
}
static int remoteDispatchDomainGetOSType(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_get_os_type_args *args,
remote_domain_get_os_type_ret *ret)
{
int rv = -1;
virDomainPtr dom = NULL;
char *type;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
if ((type = virDomainGetOSType(dom)) == NULL)
goto cleanup;
ret->type = type;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainGetSchedulerParameters(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_get_scheduler_parameters_args *args,
remote_domain_get_scheduler_parameters_ret *ret);
static int remoteDispatchDomainGetSchedulerParametersHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainGetSchedulerParameters(server, client, msg, rerr, args, ret);
}
/* remoteDispatchDomainGetSchedulerParameters body has to be implemented manually */
static int remoteDispatchDomainGetSchedulerParametersFlags(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_get_scheduler_parameters_flags_args *args,
remote_domain_get_scheduler_parameters_flags_ret *ret);
static int remoteDispatchDomainGetSchedulerParametersFlagsHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainGetSchedulerParametersFlags(server, client, msg, rerr, args, ret);
}
/* remoteDispatchDomainGetSchedulerParametersFlags body has to be implemented manually */
static int remoteDispatchDomainGetSchedulerType(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_get_scheduler_type_args *args,
remote_domain_get_scheduler_type_ret *ret);
static int remoteDispatchDomainGetSchedulerTypeHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainGetSchedulerType(server, client, msg, rerr, args, ret);
}
/* remoteDispatchDomainGetSchedulerType body has to be implemented manually */
static int remoteDispatchDomainGetSecurityLabel(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_get_security_label_args *args,
remote_domain_get_security_label_ret *ret);
static int remoteDispatchDomainGetSecurityLabelHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainGetSecurityLabel(server, client, msg, rerr, args, ret);
}
/* remoteDispatchDomainGetSecurityLabel body has to be implemented manually */
static int remoteDispatchDomainGetSecurityLabelList(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_get_security_label_list_args *args,
remote_domain_get_security_label_list_ret *ret);
static int remoteDispatchDomainGetSecurityLabelListHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainGetSecurityLabelList(server, client, msg, rerr, args, ret);
}
/* remoteDispatchDomainGetSecurityLabelList body has to be implemented manually */
static int remoteDispatchDomainGetState(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_get_state_args *args,
remote_domain_get_state_ret *ret);
static int remoteDispatchDomainGetStateHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainGetState(server, client, msg, rerr, args, ret);
}
/* remoteDispatchDomainGetState body has to be implemented manually */
static int remoteDispatchDomainGetVcpuPinInfo(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_get_vcpu_pin_info_args *args,
remote_domain_get_vcpu_pin_info_ret *ret);
static int remoteDispatchDomainGetVcpuPinInfoHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainGetVcpuPinInfo(server, client, msg, rerr, args, ret);
}
/* remoteDispatchDomainGetVcpuPinInfo body has to be implemented manually */
static int remoteDispatchDomainGetVcpus(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_get_vcpus_args *args,
remote_domain_get_vcpus_ret *ret);
static int remoteDispatchDomainGetVcpusHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainGetVcpus(server, client, msg, rerr, args, ret);
}
/* remoteDispatchDomainGetVcpus body has to be implemented manually */
static int remoteDispatchDomainGetVcpusFlags(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_get_vcpus_flags_args *args,
remote_domain_get_vcpus_flags_ret *ret);
static int remoteDispatchDomainGetVcpusFlagsHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainGetVcpusFlags(server, client, msg, rerr, args, ret);
}
static int remoteDispatchDomainGetVcpusFlags(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_get_vcpus_flags_args *args,
remote_domain_get_vcpus_flags_ret *ret)
{
int rv = -1;
virDomainPtr dom = NULL;
int num;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
if ((num = virDomainGetVcpusFlags(dom, args->flags)) < 0)
goto cleanup;
ret->num = num;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainGetXMLDesc(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_get_xml_desc_args *args,
remote_domain_get_xml_desc_ret *ret);
static int remoteDispatchDomainGetXMLDescHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainGetXMLDesc(server, client, msg, rerr, args, ret);
}
static int remoteDispatchDomainGetXMLDesc(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_get_xml_desc_args *args,
remote_domain_get_xml_desc_ret *ret)
{
int rv = -1;
virDomainPtr dom = NULL;
char *xml;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
if ((xml = virDomainGetXMLDesc(dom, args->flags)) == NULL)
goto cleanup;
ret->xml = xml;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainHasCurrentSnapshot(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_has_current_snapshot_args *args,
remote_domain_has_current_snapshot_ret *ret);
static int remoteDispatchDomainHasCurrentSnapshotHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainHasCurrentSnapshot(server, client, msg, rerr, args, ret);
}
static int remoteDispatchDomainHasCurrentSnapshot(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_has_current_snapshot_args *args,
remote_domain_has_current_snapshot_ret *ret)
{
int rv = -1;
virDomainPtr dom = NULL;
int result;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
if ((result = virDomainHasCurrentSnapshot(dom, args->flags)) < 0)
goto cleanup;
ret->result = result;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainHasManagedSaveImage(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_has_managed_save_image_args *args,
remote_domain_has_managed_save_image_ret *ret);
static int remoteDispatchDomainHasManagedSaveImageHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainHasManagedSaveImage(server, client, msg, rerr, args, ret);
}
static int remoteDispatchDomainHasManagedSaveImage(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_has_managed_save_image_args *args,
remote_domain_has_managed_save_image_ret *ret)
{
int rv = -1;
virDomainPtr dom = NULL;
int result;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
if ((result = virDomainHasManagedSaveImage(dom, args->flags)) < 0)
goto cleanup;
ret->result = result;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainInjectNMI(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_inject_nmi_args *args);
static int remoteDispatchDomainInjectNMIHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainInjectNMI(server, client, msg, rerr, args);
}
static int remoteDispatchDomainInjectNMI(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_inject_nmi_args *args)
{
int rv = -1;
virDomainPtr dom = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
if (virDomainInjectNMI(dom, args->flags) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainInterfaceStats(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_interface_stats_args *args,
remote_domain_interface_stats_ret *ret);
static int remoteDispatchDomainInterfaceStatsHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainInterfaceStats(server, client, msg, rerr, args, ret);
}
static int remoteDispatchDomainInterfaceStats(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_interface_stats_args *args,
remote_domain_interface_stats_ret *ret)
{
int rv = -1;
virDomainPtr dom = NULL;
virDomainInterfaceStatsStruct tmp;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
if (virDomainInterfaceStats(dom, args->path, &tmp, sizeof(tmp)) < 0)
goto cleanup;
ret->rx_bytes = tmp.rx_bytes;
ret->rx_packets = tmp.rx_packets;
ret->rx_errs = tmp.rx_errs;
ret->rx_drop = tmp.rx_drop;
ret->tx_bytes = tmp.tx_bytes;
ret->tx_packets = tmp.tx_packets;
ret->tx_errs = tmp.tx_errs;
ret->tx_drop = tmp.tx_drop;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainIsActive(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_is_active_args *args,
remote_domain_is_active_ret *ret);
static int remoteDispatchDomainIsActiveHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainIsActive(server, client, msg, rerr, args, ret);
}
static int remoteDispatchDomainIsActive(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_is_active_args *args,
remote_domain_is_active_ret *ret)
{
int rv = -1;
virDomainPtr dom = NULL;
int active;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
if ((active = virDomainIsActive(dom)) < 0)
goto cleanup;
ret->active = active;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainIsPersistent(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_is_persistent_args *args,
remote_domain_is_persistent_ret *ret);
static int remoteDispatchDomainIsPersistentHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainIsPersistent(server, client, msg, rerr, args, ret);
}
static int remoteDispatchDomainIsPersistent(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_is_persistent_args *args,
remote_domain_is_persistent_ret *ret)
{
int rv = -1;
virDomainPtr dom = NULL;
int persistent;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
if ((persistent = virDomainIsPersistent(dom)) < 0)
goto cleanup;
ret->persistent = persistent;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainIsUpdated(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_is_updated_args *args,
remote_domain_is_updated_ret *ret);
static int remoteDispatchDomainIsUpdatedHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainIsUpdated(server, client, msg, rerr, args, ret);
}
static int remoteDispatchDomainIsUpdated(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_is_updated_args *args,
remote_domain_is_updated_ret *ret)
{
int rv = -1;
virDomainPtr dom = NULL;
int updated;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
if ((updated = virDomainIsUpdated(dom)) < 0)
goto cleanup;
ret->updated = updated;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainListAllSnapshots(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_list_all_snapshots_args *args,
remote_domain_list_all_snapshots_ret *ret);
static int remoteDispatchDomainListAllSnapshotsHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainListAllSnapshots(server, client, msg, rerr, args, ret);
}
/* remoteDispatchDomainListAllSnapshots body has to be implemented manually */
static int remoteDispatchDomainLookupByID(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_lookup_by_id_args *args,
remote_domain_lookup_by_id_ret *ret);
static int remoteDispatchDomainLookupByIDHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainLookupByID(server, client, msg, rerr, args, ret);
}
static int remoteDispatchDomainLookupByID(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_lookup_by_id_args *args,
remote_domain_lookup_by_id_ret *ret)
{
int rv = -1;
virDomainPtr dom = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if ((dom = virDomainLookupByID(priv->conn, args->id)) == NULL)
goto cleanup;
make_nonnull_domain(&ret->dom, dom);
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainLookupByName(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_lookup_by_name_args *args,
remote_domain_lookup_by_name_ret *ret);
static int remoteDispatchDomainLookupByNameHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainLookupByName(server, client, msg, rerr, args, ret);
}
static int remoteDispatchDomainLookupByName(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_lookup_by_name_args *args,
remote_domain_lookup_by_name_ret *ret)
{
int rv = -1;
virDomainPtr dom = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if ((dom = virDomainLookupByName(priv->conn, args->name)) == NULL)
goto cleanup;
make_nonnull_domain(&ret->dom, dom);
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainLookupByUUID(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_lookup_by_uuid_args *args,
remote_domain_lookup_by_uuid_ret *ret);
static int remoteDispatchDomainLookupByUUIDHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainLookupByUUID(server, client, msg, rerr, args, ret);
}
static int remoteDispatchDomainLookupByUUID(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_lookup_by_uuid_args *args,
remote_domain_lookup_by_uuid_ret *ret)
{
int rv = -1;
virDomainPtr dom = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if ((dom = virDomainLookupByUUID(priv->conn, (unsigned char *) args->uuid)) == NULL)
goto cleanup;
make_nonnull_domain(&ret->dom, dom);
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainManagedSave(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_managed_save_args *args);
static int remoteDispatchDomainManagedSaveHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainManagedSave(server, client, msg, rerr, args);
}
static int remoteDispatchDomainManagedSave(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_managed_save_args *args)
{
int rv = -1;
virDomainPtr dom = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
if (virDomainManagedSave(dom, args->flags) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainManagedSaveRemove(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_managed_save_remove_args *args);
static int remoteDispatchDomainManagedSaveRemoveHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainManagedSaveRemove(server, client, msg, rerr, args);
}
static int remoteDispatchDomainManagedSaveRemove(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_managed_save_remove_args *args)
{
int rv = -1;
virDomainPtr dom = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
if (virDomainManagedSaveRemove(dom, args->flags) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainMemoryPeek(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_memory_peek_args *args,
remote_domain_memory_peek_ret *ret);
static int remoteDispatchDomainMemoryPeekHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainMemoryPeek(server, client, msg, rerr, args, ret);
}
/* remoteDispatchDomainMemoryPeek body has to be implemented manually */
static int remoteDispatchDomainMemoryStats(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_memory_stats_args *args,
remote_domain_memory_stats_ret *ret);
static int remoteDispatchDomainMemoryStatsHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainMemoryStats(server, client, msg, rerr, args, ret);
}
/* remoteDispatchDomainMemoryStats body has to be implemented manually */
static int remoteDispatchDomainMigrateBegin3(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_migrate_begin3_args *args,
remote_domain_migrate_begin3_ret *ret);
static int remoteDispatchDomainMigrateBegin3Helper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainMigrateBegin3(server, client, msg, rerr, args, ret);
}
/* remoteDispatchDomainMigrateBegin3 body has to be implemented manually */
static int remoteDispatchDomainMigrateBegin3Params(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_migrate_begin3_params_args *args,
remote_domain_migrate_begin3_params_ret *ret);
static int remoteDispatchDomainMigrateBegin3ParamsHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainMigrateBegin3Params(server, client, msg, rerr, args, ret);
}
/* remoteDispatchDomainMigrateBegin3Params body has to be implemented manually */
static int remoteDispatchDomainMigrateConfirm3(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_migrate_confirm3_args *args);
static int remoteDispatchDomainMigrateConfirm3Helper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainMigrateConfirm3(server, client, msg, rerr, args);
}
/* remoteDispatchDomainMigrateConfirm3 body has to be implemented manually */
static int remoteDispatchDomainMigrateConfirm3Params(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_migrate_confirm3_params_args *args);
static int remoteDispatchDomainMigrateConfirm3ParamsHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainMigrateConfirm3Params(server, client, msg, rerr, args);
}
/* remoteDispatchDomainMigrateConfirm3Params body has to be implemented manually */
static int remoteDispatchDomainMigrateFinish(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_migrate_finish_args *args,
remote_domain_migrate_finish_ret *ret);
static int remoteDispatchDomainMigrateFinishHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainMigrateFinish(server, client, msg, rerr, args, ret);
}
static int remoteDispatchDomainMigrateFinish(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_migrate_finish_args *args,
remote_domain_migrate_finish_ret *ret)
{
int rv = -1;
unsigned long flags;
virDomainPtr ddom = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
HYPER_TO_ULONG(flags, args->flags);
if ((ddom = virDomainMigrateFinish(priv->conn, args->dname, args->cookie.cookie_val, args->cookie.cookie_len, args->uri, flags)) == NULL)
goto cleanup;
make_nonnull_domain(&ret->ddom, ddom);
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (ddom)
virDomainFree(ddom);
return rv;
}
static int remoteDispatchDomainMigrateFinish2(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_migrate_finish2_args *args,
remote_domain_migrate_finish2_ret *ret);
static int remoteDispatchDomainMigrateFinish2Helper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainMigrateFinish2(server, client, msg, rerr, args, ret);
}
static int remoteDispatchDomainMigrateFinish2(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_migrate_finish2_args *args,
remote_domain_migrate_finish2_ret *ret)
{
int rv = -1;
unsigned long flags;
virDomainPtr ddom = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
HYPER_TO_ULONG(flags, args->flags);
if ((ddom = virDomainMigrateFinish2(priv->conn, args->dname, args->cookie.cookie_val, args->cookie.cookie_len, args->uri, flags, args->retcode)) == NULL)
goto cleanup;
make_nonnull_domain(&ret->ddom, ddom);
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (ddom)
virDomainFree(ddom);
return rv;
}
static int remoteDispatchDomainMigrateFinish3(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_migrate_finish3_args *args,
remote_domain_migrate_finish3_ret *ret);
static int remoteDispatchDomainMigrateFinish3Helper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainMigrateFinish3(server, client, msg, rerr, args, ret);
}
/* remoteDispatchDomainMigrateFinish3 body has to be implemented manually */
static int remoteDispatchDomainMigrateFinish3Params(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_migrate_finish3_params_args *args,
remote_domain_migrate_finish3_params_ret *ret);
static int remoteDispatchDomainMigrateFinish3ParamsHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainMigrateFinish3Params(server, client, msg, rerr, args, ret);
}
/* remoteDispatchDomainMigrateFinish3Params body has to be implemented manually */
static int remoteDispatchDomainMigrateGetCompressionCache(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_migrate_get_compression_cache_args *args,
remote_domain_migrate_get_compression_cache_ret *ret);
static int remoteDispatchDomainMigrateGetCompressionCacheHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainMigrateGetCompressionCache(server, client, msg, rerr, args, ret);
}
static int remoteDispatchDomainMigrateGetCompressionCache(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_migrate_get_compression_cache_args *args,
remote_domain_migrate_get_compression_cache_ret *ret)
{
int rv = -1;
virDomainPtr dom = NULL;
unsigned long long cacheSize;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
if (virDomainMigrateGetCompressionCache(dom, &cacheSize, args->flags) < 0)
goto cleanup;
ret->cacheSize = cacheSize;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainMigrateGetMaxSpeed(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_migrate_get_max_speed_args *args,
remote_domain_migrate_get_max_speed_ret *ret);
static int remoteDispatchDomainMigrateGetMaxSpeedHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainMigrateGetMaxSpeed(server, client, msg, rerr, args, ret);
}
static int remoteDispatchDomainMigrateGetMaxSpeed(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_migrate_get_max_speed_args *args,
remote_domain_migrate_get_max_speed_ret *ret)
{
int rv = -1;
virDomainPtr dom = NULL;
unsigned long bandwidth;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
if (virDomainMigrateGetMaxSpeed(dom, &bandwidth, args->flags) < 0)
goto cleanup;
HYPER_TO_ULONG(ret->bandwidth, bandwidth);
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainMigratePerform(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_migrate_perform_args *args);
static int remoteDispatchDomainMigratePerformHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainMigratePerform(server, client, msg, rerr, args);
}
static int remoteDispatchDomainMigratePerform(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_migrate_perform_args *args)
{
int rv = -1;
virDomainPtr dom = NULL;
unsigned long flags;
char *dname;
unsigned long resource;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
HYPER_TO_ULONG(flags, args->flags);
HYPER_TO_ULONG(resource, args->resource);
dname = args->dname ? *args->dname : NULL;
if (virDomainMigratePerform(dom, args->cookie.cookie_val, args->cookie.cookie_len, args->uri, flags, dname, resource) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainMigratePerform3(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_migrate_perform3_args *args,
remote_domain_migrate_perform3_ret *ret);
static int remoteDispatchDomainMigratePerform3Helper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainMigratePerform3(server, client, msg, rerr, args, ret);
}
/* remoteDispatchDomainMigratePerform3 body has to be implemented manually */
static int remoteDispatchDomainMigratePerform3Params(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_migrate_perform3_params_args *args,
remote_domain_migrate_perform3_params_ret *ret);
static int remoteDispatchDomainMigratePerform3ParamsHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainMigratePerform3Params(server, client, msg, rerr, args, ret);
}
/* remoteDispatchDomainMigratePerform3Params body has to be implemented manually */
static int remoteDispatchDomainMigratePrepare(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_migrate_prepare_args *args,
remote_domain_migrate_prepare_ret *ret);
static int remoteDispatchDomainMigratePrepareHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainMigratePrepare(server, client, msg, rerr, args, ret);
}
/* remoteDispatchDomainMigratePrepare body has to be implemented manually */
static int remoteDispatchDomainMigratePrepare2(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_migrate_prepare2_args *args,
remote_domain_migrate_prepare2_ret *ret);
static int remoteDispatchDomainMigratePrepare2Helper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainMigratePrepare2(server, client, msg, rerr, args, ret);
}
/* remoteDispatchDomainMigratePrepare2 body has to be implemented manually */
static int remoteDispatchDomainMigratePrepare3(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_migrate_prepare3_args *args,
remote_domain_migrate_prepare3_ret *ret);
static int remoteDispatchDomainMigratePrepare3Helper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainMigratePrepare3(server, client, msg, rerr, args, ret);
}
/* remoteDispatchDomainMigratePrepare3 body has to be implemented manually */
static int remoteDispatchDomainMigratePrepare3Params(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_migrate_prepare3_params_args *args,
remote_domain_migrate_prepare3_params_ret *ret);
static int remoteDispatchDomainMigratePrepare3ParamsHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainMigratePrepare3Params(server, client, msg, rerr, args, ret);
}
/* remoteDispatchDomainMigratePrepare3Params body has to be implemented manually */
static int remoteDispatchDomainMigratePrepareTunnel(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_migrate_prepare_tunnel_args *args);
static int remoteDispatchDomainMigratePrepareTunnelHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainMigratePrepareTunnel(server, client, msg, rerr, args);
}
static int remoteDispatchDomainMigratePrepareTunnel(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_migrate_prepare_tunnel_args *args)
{
int rv = -1;
unsigned long flags;
char *dname;
unsigned long resource;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
virStreamPtr st = NULL;
daemonClientStreamPtr stream = NULL;
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
HYPER_TO_ULONG(flags, args->flags);
HYPER_TO_ULONG(resource, args->resource);
dname = args->dname ? *args->dname : NULL;
if (!(st = virStreamNew(priv->conn, VIR_STREAM_NONBLOCK)))
goto cleanup;
if (!(stream = daemonCreateClientStream(client, st, remoteProgram, &msg->header)))
goto cleanup;
if (virDomainMigratePrepareTunnel(priv->conn, st, flags, dname, resource, args->dom_xml) < 0)
goto cleanup;
if (daemonAddClientStream(client, stream, false) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0) {
virNetMessageSaveError(rerr);
if (stream) {
virStreamAbort(st);
daemonFreeClientStream(client, stream);
} else {
virStreamFree(st);
}
}
return rv;
}
static int remoteDispatchDomainMigratePrepareTunnel3(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_migrate_prepare_tunnel3_args *args,
remote_domain_migrate_prepare_tunnel3_ret *ret);
static int remoteDispatchDomainMigratePrepareTunnel3Helper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainMigratePrepareTunnel3(server, client, msg, rerr, args, ret);
}
static int remoteDispatchDomainMigratePrepareTunnel3(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_migrate_prepare_tunnel3_args *args,
remote_domain_migrate_prepare_tunnel3_ret *ret)
{
int rv = -1;
unsigned long flags;
char *dname;
unsigned long resource;
char *cookie_out = NULL;
int cookie_out_len = 0;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
virStreamPtr st = NULL;
daemonClientStreamPtr stream = NULL;
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
HYPER_TO_ULONG(flags, args->flags);
HYPER_TO_ULONG(resource, args->resource);
dname = args->dname ? *args->dname : NULL;
if (!(st = virStreamNew(priv->conn, VIR_STREAM_NONBLOCK)))
goto cleanup;
if (!(stream = daemonCreateClientStream(client, st, remoteProgram, &msg->header)))
goto cleanup;
if (virDomainMigratePrepareTunnel3(priv->conn, st, args->cookie_in.cookie_in_val, args->cookie_in.cookie_in_len, &cookie_out, &cookie_out_len, flags, dname, resource, args->dom_xml) < 0)
goto cleanup;
if (daemonAddClientStream(client, stream, false) < 0)
goto cleanup;
ret->cookie_out.cookie_out_val = cookie_out;
ret->cookie_out.cookie_out_len = cookie_out_len;
rv = 0;
cleanup:
if (rv < 0) {
virNetMessageSaveError(rerr);
VIR_FREE(cookie_out);
if (stream) {
virStreamAbort(st);
daemonFreeClientStream(client, stream);
} else {
virStreamFree(st);
}
}
return rv;
}
static int remoteDispatchDomainMigratePrepareTunnel3Params(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_migrate_prepare_tunnel3_params_args *args,
remote_domain_migrate_prepare_tunnel3_params_ret *ret);
static int remoteDispatchDomainMigratePrepareTunnel3ParamsHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainMigratePrepareTunnel3Params(server, client, msg, rerr, args, ret);
}
/* remoteDispatchDomainMigratePrepareTunnel3Params body has to be implemented manually */
static int remoteDispatchDomainMigrateSetCompressionCache(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_migrate_set_compression_cache_args *args);
static int remoteDispatchDomainMigrateSetCompressionCacheHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainMigrateSetCompressionCache(server, client, msg, rerr, args);
}
static int remoteDispatchDomainMigrateSetCompressionCache(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_migrate_set_compression_cache_args *args)
{
int rv = -1;
virDomainPtr dom = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
if (virDomainMigrateSetCompressionCache(dom, args->cacheSize, args->flags) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainMigrateSetMaxDowntime(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_migrate_set_max_downtime_args *args);
static int remoteDispatchDomainMigrateSetMaxDowntimeHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainMigrateSetMaxDowntime(server, client, msg, rerr, args);
}
static int remoteDispatchDomainMigrateSetMaxDowntime(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_migrate_set_max_downtime_args *args)
{
int rv = -1;
virDomainPtr dom = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
if (virDomainMigrateSetMaxDowntime(dom, args->downtime, args->flags) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainMigrateSetMaxSpeed(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_migrate_set_max_speed_args *args);
static int remoteDispatchDomainMigrateSetMaxSpeedHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainMigrateSetMaxSpeed(server, client, msg, rerr, args);
}
static int remoteDispatchDomainMigrateSetMaxSpeed(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_migrate_set_max_speed_args *args)
{
int rv = -1;
virDomainPtr dom = NULL;
unsigned long bandwidth;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
HYPER_TO_ULONG(bandwidth, args->bandwidth);
if (virDomainMigrateSetMaxSpeed(dom, bandwidth, args->flags) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainOpenChannel(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_open_channel_args *args);
static int remoteDispatchDomainOpenChannelHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainOpenChannel(server, client, msg, rerr, args);
}
static int remoteDispatchDomainOpenChannel(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_open_channel_args *args)
{
int rv = -1;
virDomainPtr dom = NULL;
char *name;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
virStreamPtr st = NULL;
daemonClientStreamPtr stream = NULL;
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
name = args->name ? *args->name : NULL;
if (!(st = virStreamNew(priv->conn, VIR_STREAM_NONBLOCK)))
goto cleanup;
if (!(stream = daemonCreateClientStream(client, st, remoteProgram, &msg->header)))
goto cleanup;
if (virDomainOpenChannel(dom, name, st, args->flags) < 0)
goto cleanup;
if (daemonAddClientStream(client, stream, true) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0) {
virNetMessageSaveError(rerr);
if (stream) {
virStreamAbort(st);
daemonFreeClientStream(client, stream);
} else {
virStreamFree(st);
}
}
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainOpenConsole(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_open_console_args *args);
static int remoteDispatchDomainOpenConsoleHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainOpenConsole(server, client, msg, rerr, args);
}
static int remoteDispatchDomainOpenConsole(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_open_console_args *args)
{
int rv = -1;
virDomainPtr dom = NULL;
char *dev_name;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
virStreamPtr st = NULL;
daemonClientStreamPtr stream = NULL;
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
dev_name = args->dev_name ? *args->dev_name : NULL;
if (!(st = virStreamNew(priv->conn, VIR_STREAM_NONBLOCK)))
goto cleanup;
if (!(stream = daemonCreateClientStream(client, st, remoteProgram, &msg->header)))
goto cleanup;
if (virDomainOpenConsole(dom, dev_name, st, args->flags) < 0)
goto cleanup;
if (daemonAddClientStream(client, stream, true) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0) {
virNetMessageSaveError(rerr);
if (stream) {
virStreamAbort(st);
daemonFreeClientStream(client, stream);
} else {
virStreamFree(st);
}
}
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainOpenGraphics(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_open_graphics_args *args);
static int remoteDispatchDomainOpenGraphicsHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainOpenGraphics(server, client, msg, rerr, args);
}
/* remoteDispatchDomainOpenGraphics body has to be implemented manually */
static int remoteDispatchDomainPinEmulator(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_pin_emulator_args *args);
static int remoteDispatchDomainPinEmulatorHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainPinEmulator(server, client, msg, rerr, args);
}
/* remoteDispatchDomainPinEmulator body has to be implemented manually */
static int remoteDispatchDomainPinVcpu(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_pin_vcpu_args *args);
static int remoteDispatchDomainPinVcpuHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainPinVcpu(server, client, msg, rerr, args);
}
static int remoteDispatchDomainPinVcpu(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_pin_vcpu_args *args)
{
int rv = -1;
virDomainPtr dom = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
if (virDomainPinVcpu(dom, args->vcpu, (unsigned char *) args->cpumap.cpumap_val, args->cpumap.cpumap_len) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainPinVcpuFlags(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_pin_vcpu_flags_args *args);
static int remoteDispatchDomainPinVcpuFlagsHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainPinVcpuFlags(server, client, msg, rerr, args);
}
static int remoteDispatchDomainPinVcpuFlags(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_pin_vcpu_flags_args *args)
{
int rv = -1;
virDomainPtr dom = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
if (virDomainPinVcpuFlags(dom, args->vcpu, (unsigned char *) args->cpumap.cpumap_val, args->cpumap.cpumap_len, args->flags) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainPMSuspendForDuration(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_pm_suspend_for_duration_args *args);
static int remoteDispatchDomainPMSuspendForDurationHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainPMSuspendForDuration(server, client, msg, rerr, args);
}
static int remoteDispatchDomainPMSuspendForDuration(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_pm_suspend_for_duration_args *args)
{
int rv = -1;
virDomainPtr dom = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
if (virDomainPMSuspendForDuration(dom, args->target, args->duration, args->flags) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainPMWakeup(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_pm_wakeup_args *args);
static int remoteDispatchDomainPMWakeupHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainPMWakeup(server, client, msg, rerr, args);
}
static int remoteDispatchDomainPMWakeup(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_pm_wakeup_args *args)
{
int rv = -1;
virDomainPtr dom = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
if (virDomainPMWakeup(dom, args->flags) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainReboot(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_reboot_args *args);
static int remoteDispatchDomainRebootHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainReboot(server, client, msg, rerr, args);
}
static int remoteDispatchDomainReboot(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_reboot_args *args)
{
int rv = -1;
virDomainPtr dom = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
if (virDomainReboot(dom, args->flags) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainReset(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_reset_args *args);
static int remoteDispatchDomainResetHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainReset(server, client, msg, rerr, args);
}
static int remoteDispatchDomainReset(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_reset_args *args)
{
int rv = -1;
virDomainPtr dom = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
if (virDomainReset(dom, args->flags) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainRestore(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_restore_args *args);
static int remoteDispatchDomainRestoreHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainRestore(server, client, msg, rerr, args);
}
static int remoteDispatchDomainRestore(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_restore_args *args)
{
int rv = -1;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (virDomainRestore(priv->conn, args->from) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
return rv;
}
static int remoteDispatchDomainRestoreFlags(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_restore_flags_args *args);
static int remoteDispatchDomainRestoreFlagsHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainRestoreFlags(server, client, msg, rerr, args);
}
static int remoteDispatchDomainRestoreFlags(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_restore_flags_args *args)
{
int rv = -1;
char *dxml;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
dxml = args->dxml ? *args->dxml : NULL;
if (virDomainRestoreFlags(priv->conn, args->from, dxml, args->flags) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
return rv;
}
static int remoteDispatchDomainResume(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_resume_args *args);
static int remoteDispatchDomainResumeHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainResume(server, client, msg, rerr, args);
}
static int remoteDispatchDomainResume(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_resume_args *args)
{
int rv = -1;
virDomainPtr dom = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
if (virDomainResume(dom) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainRevertToSnapshot(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_revert_to_snapshot_args *args);
static int remoteDispatchDomainRevertToSnapshotHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainRevertToSnapshot(server, client, msg, rerr, args);
}
static int remoteDispatchDomainRevertToSnapshot(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_revert_to_snapshot_args *args)
{
int rv = -1;
virDomainPtr dom = NULL;
virDomainSnapshotPtr snapshot = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->snap.dom)))
goto cleanup;
if (!(snapshot = get_nonnull_domain_snapshot(dom, args->snap)))
goto cleanup;
if (virDomainRevertToSnapshot(snapshot, args->flags) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (snapshot)
virDomainSnapshotFree(snapshot);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainSave(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_save_args *args);
static int remoteDispatchDomainSaveHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainSave(server, client, msg, rerr, args);
}
static int remoteDispatchDomainSave(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_save_args *args)
{
int rv = -1;
virDomainPtr dom = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
if (virDomainSave(dom, args->to) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainSaveFlags(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_save_flags_args *args);
static int remoteDispatchDomainSaveFlagsHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainSaveFlags(server, client, msg, rerr, args);
}
static int remoteDispatchDomainSaveFlags(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_save_flags_args *args)
{
int rv = -1;
virDomainPtr dom = NULL;
char *dxml;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
dxml = args->dxml ? *args->dxml : NULL;
if (virDomainSaveFlags(dom, args->to, dxml, args->flags) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainSaveImageDefineXML(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_save_image_define_xml_args *args);
static int remoteDispatchDomainSaveImageDefineXMLHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainSaveImageDefineXML(server, client, msg, rerr, args);
}
static int remoteDispatchDomainSaveImageDefineXML(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_save_image_define_xml_args *args)
{
int rv = -1;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (virDomainSaveImageDefineXML(priv->conn, args->file, args->dxml, args->flags) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
return rv;
}
static int remoteDispatchDomainSaveImageGetXMLDesc(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_save_image_get_xml_desc_args *args,
remote_domain_save_image_get_xml_desc_ret *ret);
static int remoteDispatchDomainSaveImageGetXMLDescHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainSaveImageGetXMLDesc(server, client, msg, rerr, args, ret);
}
static int remoteDispatchDomainSaveImageGetXMLDesc(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_save_image_get_xml_desc_args *args,
remote_domain_save_image_get_xml_desc_ret *ret)
{
int rv = -1;
char *xml;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if ((xml = virDomainSaveImageGetXMLDesc(priv->conn, args->file, args->flags)) == NULL)
goto cleanup;
ret->xml = xml;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
return rv;
}
static int remoteDispatchDomainScreenshot(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_screenshot_args *args,
remote_domain_screenshot_ret *ret);
static int remoteDispatchDomainScreenshotHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainScreenshot(server, client, msg, rerr, args, ret);
}
static int remoteDispatchDomainScreenshot(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_screenshot_args *args,
remote_domain_screenshot_ret *ret)
{
int rv = -1;
virDomainPtr dom = NULL;
char *mime = NULL;
char **mime_p = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
virStreamPtr st = NULL;
daemonClientStreamPtr stream = NULL;
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
if (!(st = virStreamNew(priv->conn, VIR_STREAM_NONBLOCK)))
goto cleanup;
if (!(stream = daemonCreateClientStream(client, st, remoteProgram, &msg->header)))
goto cleanup;
if ((mime = virDomainScreenshot(dom, st, args->screen, args->flags)) == NULL)
goto cleanup;
if (daemonAddClientStream(client, stream, true) < 0)
goto cleanup;
if (VIR_ALLOC(mime_p) < 0)
goto cleanup;
if (VIR_STRDUP(*mime_p, mime) < 0)
goto cleanup;
ret->mime = mime_p;
rv = 0;
cleanup:
if (rv < 0) {
virNetMessageSaveError(rerr);
VIR_FREE(mime_p);
if (stream) {
virStreamAbort(st);
daemonFreeClientStream(client, stream);
} else {
virStreamFree(st);
}
}
if (dom)
virDomainFree(dom);
VIR_FREE(mime);
return rv;
}
static int remoteDispatchDomainSendKey(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_send_key_args *args);
static int remoteDispatchDomainSendKeyHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainSendKey(server, client, msg, rerr, args);
}
static int remoteDispatchDomainSendKey(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_send_key_args *args)
{
int rv = -1;
virDomainPtr dom = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
if (virDomainSendKey(dom, args->codeset, args->holdtime, args->keycodes.keycodes_val, args->keycodes.keycodes_len, args->flags) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainSendProcessSignal(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_send_process_signal_args *args);
static int remoteDispatchDomainSendProcessSignalHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainSendProcessSignal(server, client, msg, rerr, args);
}
static int remoteDispatchDomainSendProcessSignal(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_send_process_signal_args *args)
{
int rv = -1;
virDomainPtr dom = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
if (virDomainSendProcessSignal(dom, args->pid_value, args->signum, args->flags) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainSetAutostart(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_set_autostart_args *args);
static int remoteDispatchDomainSetAutostartHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainSetAutostart(server, client, msg, rerr, args);
}
static int remoteDispatchDomainSetAutostart(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_set_autostart_args *args)
{
int rv = -1;
virDomainPtr dom = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
if (virDomainSetAutostart(dom, args->autostart) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainSetBlkioParameters(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_set_blkio_parameters_args *args);
static int remoteDispatchDomainSetBlkioParametersHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainSetBlkioParameters(server, client, msg, rerr, args);
}
static int remoteDispatchDomainSetBlkioParameters(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_set_blkio_parameters_args *args)
{
int rv = -1;
virDomainPtr dom = NULL;
virTypedParameterPtr params = NULL;
int nparams = 0;;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
if ((params = remoteDeserializeTypedParameters(args->params.params_val,
args->params.params_len,
REMOTE_DOMAIN_BLKIO_PARAMETERS_MAX,
&nparams)) == NULL)
goto cleanup;
if (virDomainSetBlkioParameters(dom, params, nparams, args->flags) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
virTypedParamsFree(params, nparams);
return rv;
}
static int remoteDispatchDomainSetBlockIoTune(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_set_block_io_tune_args *args);
static int remoteDispatchDomainSetBlockIoTuneHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainSetBlockIoTune(server, client, msg, rerr, args);
}
static int remoteDispatchDomainSetBlockIoTune(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_set_block_io_tune_args *args)
{
int rv = -1;
virDomainPtr dom = NULL;
virTypedParameterPtr params = NULL;
int nparams = 0;;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
if ((params = remoteDeserializeTypedParameters(args->params.params_val,
args->params.params_len,
REMOTE_DOMAIN_BLOCK_IO_TUNE_PARAMETERS_MAX,
&nparams)) == NULL)
goto cleanup;
if (virDomainSetBlockIoTune(dom, args->disk, params, nparams, args->flags) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
virTypedParamsFree(params, nparams);
return rv;
}
static int remoteDispatchDomainSetInterfaceParameters(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_set_interface_parameters_args *args);
static int remoteDispatchDomainSetInterfaceParametersHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainSetInterfaceParameters(server, client, msg, rerr, args);
}
static int remoteDispatchDomainSetInterfaceParameters(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_set_interface_parameters_args *args)
{
int rv = -1;
virDomainPtr dom = NULL;
virTypedParameterPtr params = NULL;
int nparams = 0;;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
if ((params = remoteDeserializeTypedParameters(args->params.params_val,
args->params.params_len,
REMOTE_DOMAIN_INTERFACE_PARAMETERS_MAX,
&nparams)) == NULL)
goto cleanup;
if (virDomainSetInterfaceParameters(dom, args->device, params, nparams, args->flags) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
virTypedParamsFree(params, nparams);
return rv;
}
static int remoteDispatchDomainSetMaxMemory(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_set_max_memory_args *args);
static int remoteDispatchDomainSetMaxMemoryHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainSetMaxMemory(server, client, msg, rerr, args);
}
static int remoteDispatchDomainSetMaxMemory(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_set_max_memory_args *args)
{
int rv = -1;
virDomainPtr dom = NULL;
unsigned long memory;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
HYPER_TO_ULONG(memory, args->memory);
if (virDomainSetMaxMemory(dom, memory) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainSetMemory(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_set_memory_args *args);
static int remoteDispatchDomainSetMemoryHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainSetMemory(server, client, msg, rerr, args);
}
static int remoteDispatchDomainSetMemory(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_set_memory_args *args)
{
int rv = -1;
virDomainPtr dom = NULL;
unsigned long memory;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
HYPER_TO_ULONG(memory, args->memory);
if (virDomainSetMemory(dom, memory) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainSetMemoryFlags(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_set_memory_flags_args *args);
static int remoteDispatchDomainSetMemoryFlagsHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainSetMemoryFlags(server, client, msg, rerr, args);
}
static int remoteDispatchDomainSetMemoryFlags(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_set_memory_flags_args *args)
{
int rv = -1;
virDomainPtr dom = NULL;
unsigned long memory;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
HYPER_TO_ULONG(memory, args->memory);
if (virDomainSetMemoryFlags(dom, memory, args->flags) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainSetMemoryParameters(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_set_memory_parameters_args *args);
static int remoteDispatchDomainSetMemoryParametersHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainSetMemoryParameters(server, client, msg, rerr, args);
}
static int remoteDispatchDomainSetMemoryParameters(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_set_memory_parameters_args *args)
{
int rv = -1;
virDomainPtr dom = NULL;
virTypedParameterPtr params = NULL;
int nparams = 0;;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
if ((params = remoteDeserializeTypedParameters(args->params.params_val,
args->params.params_len,
REMOTE_DOMAIN_MEMORY_PARAMETERS_MAX,
&nparams)) == NULL)
goto cleanup;
if (virDomainSetMemoryParameters(dom, params, nparams, args->flags) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
virTypedParamsFree(params, nparams);
return rv;
}
static int remoteDispatchDomainSetMemoryStatsPeriod(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_set_memory_stats_period_args *args);
static int remoteDispatchDomainSetMemoryStatsPeriodHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainSetMemoryStatsPeriod(server, client, msg, rerr, args);
}
static int remoteDispatchDomainSetMemoryStatsPeriod(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_set_memory_stats_period_args *args)
{
int rv = -1;
virDomainPtr dom = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
if (virDomainSetMemoryStatsPeriod(dom, args->period, args->flags) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainSetMetadata(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_set_metadata_args *args);
static int remoteDispatchDomainSetMetadataHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainSetMetadata(server, client, msg, rerr, args);
}
static int remoteDispatchDomainSetMetadata(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_set_metadata_args *args)
{
int rv = -1;
virDomainPtr dom = NULL;
char *metadata;
char *key;
char *uri;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
metadata = args->metadata ? *args->metadata : NULL;
key = args->key ? *args->key : NULL;
uri = args->uri ? *args->uri : NULL;
if (virDomainSetMetadata(dom, args->type, metadata, key, uri, args->flags) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainSetNumaParameters(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_set_numa_parameters_args *args);
static int remoteDispatchDomainSetNumaParametersHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainSetNumaParameters(server, client, msg, rerr, args);
}
static int remoteDispatchDomainSetNumaParameters(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_set_numa_parameters_args *args)
{
int rv = -1;
virDomainPtr dom = NULL;
virTypedParameterPtr params = NULL;
int nparams = 0;;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
if ((params = remoteDeserializeTypedParameters(args->params.params_val,
args->params.params_len,
REMOTE_DOMAIN_NUMA_PARAMETERS_MAX,
&nparams)) == NULL)
goto cleanup;
if (virDomainSetNumaParameters(dom, params, nparams, args->flags) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
virTypedParamsFree(params, nparams);
return rv;
}
static int remoteDispatchDomainSetSchedulerParameters(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_set_scheduler_parameters_args *args);
static int remoteDispatchDomainSetSchedulerParametersHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainSetSchedulerParameters(server, client, msg, rerr, args);
}
static int remoteDispatchDomainSetSchedulerParameters(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_set_scheduler_parameters_args *args)
{
int rv = -1;
virDomainPtr dom = NULL;
virTypedParameterPtr params = NULL;
int nparams = 0;;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
if ((params = remoteDeserializeTypedParameters(args->params.params_val,
args->params.params_len,
REMOTE_DOMAIN_SCHEDULER_PARAMETERS_MAX,
&nparams)) == NULL)
goto cleanup;
if (virDomainSetSchedulerParameters(dom, params, nparams) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
virTypedParamsFree(params, nparams);
return rv;
}
static int remoteDispatchDomainSetSchedulerParametersFlags(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_set_scheduler_parameters_flags_args *args);
static int remoteDispatchDomainSetSchedulerParametersFlagsHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainSetSchedulerParametersFlags(server, client, msg, rerr, args);
}
static int remoteDispatchDomainSetSchedulerParametersFlags(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_set_scheduler_parameters_flags_args *args)
{
int rv = -1;
virDomainPtr dom = NULL;
virTypedParameterPtr params = NULL;
int nparams = 0;;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
if ((params = remoteDeserializeTypedParameters(args->params.params_val,
args->params.params_len,
REMOTE_DOMAIN_SCHEDULER_PARAMETERS_MAX,
&nparams)) == NULL)
goto cleanup;
if (virDomainSetSchedulerParametersFlags(dom, params, nparams, args->flags) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
virTypedParamsFree(params, nparams);
return rv;
}
static int remoteDispatchDomainSetVcpus(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_set_vcpus_args *args);
static int remoteDispatchDomainSetVcpusHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainSetVcpus(server, client, msg, rerr, args);
}
static int remoteDispatchDomainSetVcpus(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_set_vcpus_args *args)
{
int rv = -1;
virDomainPtr dom = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
if (virDomainSetVcpus(dom, args->nvcpus) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainSetVcpusFlags(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_set_vcpus_flags_args *args);
static int remoteDispatchDomainSetVcpusFlagsHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainSetVcpusFlags(server, client, msg, rerr, args);
}
static int remoteDispatchDomainSetVcpusFlags(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_set_vcpus_flags_args *args)
{
int rv = -1;
virDomainPtr dom = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
if (virDomainSetVcpusFlags(dom, args->nvcpus, args->flags) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainShutdown(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_shutdown_args *args);
static int remoteDispatchDomainShutdownHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainShutdown(server, client, msg, rerr, args);
}
static int remoteDispatchDomainShutdown(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_shutdown_args *args)
{
int rv = -1;
virDomainPtr dom = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
if (virDomainShutdown(dom) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainShutdownFlags(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_shutdown_flags_args *args);
static int remoteDispatchDomainShutdownFlagsHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainShutdownFlags(server, client, msg, rerr, args);
}
static int remoteDispatchDomainShutdownFlags(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_shutdown_flags_args *args)
{
int rv = -1;
virDomainPtr dom = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
if (virDomainShutdownFlags(dom, args->flags) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainSnapshotCreateXML(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_snapshot_create_xml_args *args,
remote_domain_snapshot_create_xml_ret *ret);
static int remoteDispatchDomainSnapshotCreateXMLHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainSnapshotCreateXML(server, client, msg, rerr, args, ret);
}
static int remoteDispatchDomainSnapshotCreateXML(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_snapshot_create_xml_args *args,
remote_domain_snapshot_create_xml_ret *ret)
{
int rv = -1;
virDomainPtr dom = NULL;
virDomainSnapshotPtr snap = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
if ((snap = virDomainSnapshotCreateXML(dom, args->xml_desc, args->flags)) == NULL)
goto cleanup;
make_nonnull_domain_snapshot(&ret->snap, snap);
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
if (snap)
virDomainSnapshotFree(snap);
return rv;
}
static int remoteDispatchDomainSnapshotCurrent(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_snapshot_current_args *args,
remote_domain_snapshot_current_ret *ret);
static int remoteDispatchDomainSnapshotCurrentHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainSnapshotCurrent(server, client, msg, rerr, args, ret);
}
static int remoteDispatchDomainSnapshotCurrent(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_snapshot_current_args *args,
remote_domain_snapshot_current_ret *ret)
{
int rv = -1;
virDomainPtr dom = NULL;
virDomainSnapshotPtr snap = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
if ((snap = virDomainSnapshotCurrent(dom, args->flags)) == NULL)
goto cleanup;
make_nonnull_domain_snapshot(&ret->snap, snap);
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
if (snap)
virDomainSnapshotFree(snap);
return rv;
}
static int remoteDispatchDomainSnapshotDelete(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_snapshot_delete_args *args);
static int remoteDispatchDomainSnapshotDeleteHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainSnapshotDelete(server, client, msg, rerr, args);
}
static int remoteDispatchDomainSnapshotDelete(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_snapshot_delete_args *args)
{
int rv = -1;
virDomainPtr dom = NULL;
virDomainSnapshotPtr snapshot = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->snap.dom)))
goto cleanup;
if (!(snapshot = get_nonnull_domain_snapshot(dom, args->snap)))
goto cleanup;
if (virDomainSnapshotDelete(snapshot, args->flags) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (snapshot)
virDomainSnapshotFree(snapshot);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainSnapshotGetParent(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_snapshot_get_parent_args *args,
remote_domain_snapshot_get_parent_ret *ret);
static int remoteDispatchDomainSnapshotGetParentHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainSnapshotGetParent(server, client, msg, rerr, args, ret);
}
static int remoteDispatchDomainSnapshotGetParent(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_snapshot_get_parent_args *args,
remote_domain_snapshot_get_parent_ret *ret)
{
int rv = -1;
virDomainPtr dom = NULL;
virDomainSnapshotPtr snapshot = NULL;
virDomainSnapshotPtr snap = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->snap.dom)))
goto cleanup;
if (!(snapshot = get_nonnull_domain_snapshot(dom, args->snap)))
goto cleanup;
if ((snap = virDomainSnapshotGetParent(snapshot, args->flags)) == NULL)
goto cleanup;
make_nonnull_domain_snapshot(&ret->snap, snap);
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (snapshot)
virDomainSnapshotFree(snapshot);
if (dom)
virDomainFree(dom);
if (snap)
virDomainSnapshotFree(snap);
return rv;
}
static int remoteDispatchDomainSnapshotGetXMLDesc(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_snapshot_get_xml_desc_args *args,
remote_domain_snapshot_get_xml_desc_ret *ret);
static int remoteDispatchDomainSnapshotGetXMLDescHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainSnapshotGetXMLDesc(server, client, msg, rerr, args, ret);
}
static int remoteDispatchDomainSnapshotGetXMLDesc(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_snapshot_get_xml_desc_args *args,
remote_domain_snapshot_get_xml_desc_ret *ret)
{
int rv = -1;
virDomainPtr dom = NULL;
virDomainSnapshotPtr snapshot = NULL;
char *xml;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->snap.dom)))
goto cleanup;
if (!(snapshot = get_nonnull_domain_snapshot(dom, args->snap)))
goto cleanup;
if ((xml = virDomainSnapshotGetXMLDesc(snapshot, args->flags)) == NULL)
goto cleanup;
ret->xml = xml;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (snapshot)
virDomainSnapshotFree(snapshot);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainSnapshotHasMetadata(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_snapshot_has_metadata_args *args,
remote_domain_snapshot_has_metadata_ret *ret);
static int remoteDispatchDomainSnapshotHasMetadataHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainSnapshotHasMetadata(server, client, msg, rerr, args, ret);
}
static int remoteDispatchDomainSnapshotHasMetadata(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_snapshot_has_metadata_args *args,
remote_domain_snapshot_has_metadata_ret *ret)
{
int rv = -1;
virDomainPtr dom = NULL;
virDomainSnapshotPtr snapshot = NULL;
int metadata;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->snap.dom)))
goto cleanup;
if (!(snapshot = get_nonnull_domain_snapshot(dom, args->snap)))
goto cleanup;
if ((metadata = virDomainSnapshotHasMetadata(snapshot, args->flags)) < 0)
goto cleanup;
ret->metadata = metadata;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (snapshot)
virDomainSnapshotFree(snapshot);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainSnapshotIsCurrent(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_snapshot_is_current_args *args,
remote_domain_snapshot_is_current_ret *ret);
static int remoteDispatchDomainSnapshotIsCurrentHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainSnapshotIsCurrent(server, client, msg, rerr, args, ret);
}
static int remoteDispatchDomainSnapshotIsCurrent(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_snapshot_is_current_args *args,
remote_domain_snapshot_is_current_ret *ret)
{
int rv = -1;
virDomainPtr dom = NULL;
virDomainSnapshotPtr snapshot = NULL;
int current;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->snap.dom)))
goto cleanup;
if (!(snapshot = get_nonnull_domain_snapshot(dom, args->snap)))
goto cleanup;
if ((current = virDomainSnapshotIsCurrent(snapshot, args->flags)) < 0)
goto cleanup;
ret->current = current;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (snapshot)
virDomainSnapshotFree(snapshot);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainSnapshotListAllChildren(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_snapshot_list_all_children_args *args,
remote_domain_snapshot_list_all_children_ret *ret);
static int remoteDispatchDomainSnapshotListAllChildrenHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainSnapshotListAllChildren(server, client, msg, rerr, args, ret);
}
/* remoteDispatchDomainSnapshotListAllChildren body has to be implemented manually */
static int remoteDispatchDomainSnapshotListChildrenNames(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_snapshot_list_children_names_args *args,
remote_domain_snapshot_list_children_names_ret *ret);
static int remoteDispatchDomainSnapshotListChildrenNamesHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainSnapshotListChildrenNames(server, client, msg, rerr, args, ret);
}
static int remoteDispatchDomainSnapshotListChildrenNames(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_snapshot_list_children_names_args *args,
remote_domain_snapshot_list_children_names_ret *ret)
{
int rv = -1;
virDomainPtr dom = NULL;
virDomainSnapshotPtr snapshot = NULL;
int len;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (args->maxnames > REMOTE_DOMAIN_SNAPSHOT_LIST_MAX) {
virReportError(VIR_ERR_INTERNAL_ERROR,
"%s", _("maxnames > REMOTE_DOMAIN_SNAPSHOT_LIST_MAX"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->snap.dom)))
goto cleanup;
if (!(snapshot = get_nonnull_domain_snapshot(dom, args->snap)))
goto cleanup;
/* Allocate return buffer. */
if (VIR_ALLOC_N(ret->names.names_val, args->maxnames) < 0)
goto cleanup;
if ((len = virDomainSnapshotListChildrenNames(snapshot, ret->names.names_val, args->maxnames, args->flags)) < 0)
goto cleanup;
ret->names.names_len = len;
rv = 0;
cleanup:
if (rv < 0) {
virNetMessageSaveError(rerr);
VIR_FREE(ret->names.names_val);
}
if (snapshot)
virDomainSnapshotFree(snapshot);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainSnapshotListNames(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_snapshot_list_names_args *args,
remote_domain_snapshot_list_names_ret *ret);
static int remoteDispatchDomainSnapshotListNamesHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainSnapshotListNames(server, client, msg, rerr, args, ret);
}
static int remoteDispatchDomainSnapshotListNames(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_snapshot_list_names_args *args,
remote_domain_snapshot_list_names_ret *ret)
{
int rv = -1;
virDomainPtr dom = NULL;
int len;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (args->maxnames > REMOTE_DOMAIN_SNAPSHOT_LIST_MAX) {
virReportError(VIR_ERR_INTERNAL_ERROR,
"%s", _("maxnames > REMOTE_DOMAIN_SNAPSHOT_LIST_MAX"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
/* Allocate return buffer. */
if (VIR_ALLOC_N(ret->names.names_val, args->maxnames) < 0)
goto cleanup;
if ((len = virDomainSnapshotListNames(dom, ret->names.names_val, args->maxnames, args->flags)) < 0)
goto cleanup;
ret->names.names_len = len;
rv = 0;
cleanup:
if (rv < 0) {
virNetMessageSaveError(rerr);
VIR_FREE(ret->names.names_val);
}
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainSnapshotLookupByName(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_snapshot_lookup_by_name_args *args,
remote_domain_snapshot_lookup_by_name_ret *ret);
static int remoteDispatchDomainSnapshotLookupByNameHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainSnapshotLookupByName(server, client, msg, rerr, args, ret);
}
static int remoteDispatchDomainSnapshotLookupByName(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_snapshot_lookup_by_name_args *args,
remote_domain_snapshot_lookup_by_name_ret *ret)
{
int rv = -1;
virDomainPtr dom = NULL;
virDomainSnapshotPtr snap = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
if ((snap = virDomainSnapshotLookupByName(dom, args->name, args->flags)) == NULL)
goto cleanup;
make_nonnull_domain_snapshot(&ret->snap, snap);
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
if (snap)
virDomainSnapshotFree(snap);
return rv;
}
static int remoteDispatchDomainSnapshotNum(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_snapshot_num_args *args,
remote_domain_snapshot_num_ret *ret);
static int remoteDispatchDomainSnapshotNumHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainSnapshotNum(server, client, msg, rerr, args, ret);
}
static int remoteDispatchDomainSnapshotNum(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_snapshot_num_args *args,
remote_domain_snapshot_num_ret *ret)
{
int rv = -1;
virDomainPtr dom = NULL;
int num;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
if ((num = virDomainSnapshotNum(dom, args->flags)) < 0)
goto cleanup;
ret->num = num;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainSnapshotNumChildren(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_snapshot_num_children_args *args,
remote_domain_snapshot_num_children_ret *ret);
static int remoteDispatchDomainSnapshotNumChildrenHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainSnapshotNumChildren(server, client, msg, rerr, args, ret);
}
static int remoteDispatchDomainSnapshotNumChildren(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_snapshot_num_children_args *args,
remote_domain_snapshot_num_children_ret *ret)
{
int rv = -1;
virDomainPtr dom = NULL;
virDomainSnapshotPtr snapshot = NULL;
int num;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->snap.dom)))
goto cleanup;
if (!(snapshot = get_nonnull_domain_snapshot(dom, args->snap)))
goto cleanup;
if ((num = virDomainSnapshotNumChildren(snapshot, args->flags)) < 0)
goto cleanup;
ret->num = num;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (snapshot)
virDomainSnapshotFree(snapshot);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainSuspend(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_suspend_args *args);
static int remoteDispatchDomainSuspendHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainSuspend(server, client, msg, rerr, args);
}
static int remoteDispatchDomainSuspend(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_suspend_args *args)
{
int rv = -1;
virDomainPtr dom = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
if (virDomainSuspend(dom) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainUndefine(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_undefine_args *args);
static int remoteDispatchDomainUndefineHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainUndefine(server, client, msg, rerr, args);
}
static int remoteDispatchDomainUndefine(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_undefine_args *args)
{
int rv = -1;
virDomainPtr dom = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
if (virDomainUndefine(dom) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainUndefineFlags(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_undefine_flags_args *args);
static int remoteDispatchDomainUndefineFlagsHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainUndefineFlags(server, client, msg, rerr, args);
}
static int remoteDispatchDomainUndefineFlags(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_undefine_flags_args *args)
{
int rv = -1;
virDomainPtr dom = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
if (virDomainUndefineFlags(dom, args->flags) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchDomainUpdateDeviceFlags(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_domain_update_device_flags_args *args);
static int remoteDispatchDomainUpdateDeviceFlagsHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchDomainUpdateDeviceFlags(server, client, msg, rerr, args);
}
static int remoteDispatchDomainUpdateDeviceFlags(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_domain_update_device_flags_args *args)
{
int rv = -1;
virDomainPtr dom = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dom = get_nonnull_domain(priv->conn, args->dom)))
goto cleanup;
if (virDomainUpdateDeviceFlags(dom, args->xml, args->flags) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dom)
virDomainFree(dom);
return rv;
}
static int remoteDispatchInterfaceChangeBegin(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_interface_change_begin_args *args);
static int remoteDispatchInterfaceChangeBeginHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchInterfaceChangeBegin(server, client, msg, rerr, args);
}
static int remoteDispatchInterfaceChangeBegin(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_interface_change_begin_args *args)
{
int rv = -1;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (virInterfaceChangeBegin(priv->conn, args->flags) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
return rv;
}
static int remoteDispatchInterfaceChangeCommit(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_interface_change_commit_args *args);
static int remoteDispatchInterfaceChangeCommitHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchInterfaceChangeCommit(server, client, msg, rerr, args);
}
static int remoteDispatchInterfaceChangeCommit(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_interface_change_commit_args *args)
{
int rv = -1;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (virInterfaceChangeCommit(priv->conn, args->flags) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
return rv;
}
static int remoteDispatchInterfaceChangeRollback(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_interface_change_rollback_args *args);
static int remoteDispatchInterfaceChangeRollbackHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchInterfaceChangeRollback(server, client, msg, rerr, args);
}
static int remoteDispatchInterfaceChangeRollback(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_interface_change_rollback_args *args)
{
int rv = -1;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (virInterfaceChangeRollback(priv->conn, args->flags) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
return rv;
}
static int remoteDispatchInterfaceCreate(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_interface_create_args *args);
static int remoteDispatchInterfaceCreateHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchInterfaceCreate(server, client, msg, rerr, args);
}
static int remoteDispatchInterfaceCreate(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_interface_create_args *args)
{
int rv = -1;
virInterfacePtr iface = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(iface = get_nonnull_interface(priv->conn, args->iface)))
goto cleanup;
if (virInterfaceCreate(iface, args->flags) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (iface)
virInterfaceFree(iface);
return rv;
}
static int remoteDispatchInterfaceDefineXML(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_interface_define_xml_args *args,
remote_interface_define_xml_ret *ret);
static int remoteDispatchInterfaceDefineXMLHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchInterfaceDefineXML(server, client, msg, rerr, args, ret);
}
static int remoteDispatchInterfaceDefineXML(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_interface_define_xml_args *args,
remote_interface_define_xml_ret *ret)
{
int rv = -1;
virInterfacePtr iface = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if ((iface = virInterfaceDefineXML(priv->conn, args->xml, args->flags)) == NULL)
goto cleanup;
make_nonnull_interface(&ret->iface, iface);
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (iface)
virInterfaceFree(iface);
return rv;
}
static int remoteDispatchInterfaceDestroy(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_interface_destroy_args *args);
static int remoteDispatchInterfaceDestroyHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchInterfaceDestroy(server, client, msg, rerr, args);
}
static int remoteDispatchInterfaceDestroy(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_interface_destroy_args *args)
{
int rv = -1;
virInterfacePtr iface = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(iface = get_nonnull_interface(priv->conn, args->iface)))
goto cleanup;
if (virInterfaceDestroy(iface, args->flags) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (iface)
virInterfaceFree(iface);
return rv;
}
static int remoteDispatchInterfaceGetXMLDesc(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_interface_get_xml_desc_args *args,
remote_interface_get_xml_desc_ret *ret);
static int remoteDispatchInterfaceGetXMLDescHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchInterfaceGetXMLDesc(server, client, msg, rerr, args, ret);
}
static int remoteDispatchInterfaceGetXMLDesc(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_interface_get_xml_desc_args *args,
remote_interface_get_xml_desc_ret *ret)
{
int rv = -1;
virInterfacePtr iface = NULL;
char *xml;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(iface = get_nonnull_interface(priv->conn, args->iface)))
goto cleanup;
if ((xml = virInterfaceGetXMLDesc(iface, args->flags)) == NULL)
goto cleanup;
ret->xml = xml;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (iface)
virInterfaceFree(iface);
return rv;
}
static int remoteDispatchInterfaceIsActive(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_interface_is_active_args *args,
remote_interface_is_active_ret *ret);
static int remoteDispatchInterfaceIsActiveHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchInterfaceIsActive(server, client, msg, rerr, args, ret);
}
static int remoteDispatchInterfaceIsActive(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_interface_is_active_args *args,
remote_interface_is_active_ret *ret)
{
int rv = -1;
virInterfacePtr iface = NULL;
int active;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(iface = get_nonnull_interface(priv->conn, args->iface)))
goto cleanup;
if ((active = virInterfaceIsActive(iface)) < 0)
goto cleanup;
ret->active = active;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (iface)
virInterfaceFree(iface);
return rv;
}
static int remoteDispatchInterfaceLookupByMACString(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_interface_lookup_by_mac_string_args *args,
remote_interface_lookup_by_mac_string_ret *ret);
static int remoteDispatchInterfaceLookupByMACStringHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchInterfaceLookupByMACString(server, client, msg, rerr, args, ret);
}
static int remoteDispatchInterfaceLookupByMACString(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_interface_lookup_by_mac_string_args *args,
remote_interface_lookup_by_mac_string_ret *ret)
{
int rv = -1;
virInterfacePtr iface = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if ((iface = virInterfaceLookupByMACString(priv->conn, args->mac)) == NULL)
goto cleanup;
make_nonnull_interface(&ret->iface, iface);
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (iface)
virInterfaceFree(iface);
return rv;
}
static int remoteDispatchInterfaceLookupByName(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_interface_lookup_by_name_args *args,
remote_interface_lookup_by_name_ret *ret);
static int remoteDispatchInterfaceLookupByNameHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchInterfaceLookupByName(server, client, msg, rerr, args, ret);
}
static int remoteDispatchInterfaceLookupByName(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_interface_lookup_by_name_args *args,
remote_interface_lookup_by_name_ret *ret)
{
int rv = -1;
virInterfacePtr iface = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if ((iface = virInterfaceLookupByName(priv->conn, args->name)) == NULL)
goto cleanup;
make_nonnull_interface(&ret->iface, iface);
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (iface)
virInterfaceFree(iface);
return rv;
}
static int remoteDispatchInterfaceUndefine(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_interface_undefine_args *args);
static int remoteDispatchInterfaceUndefineHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchInterfaceUndefine(server, client, msg, rerr, args);
}
static int remoteDispatchInterfaceUndefine(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_interface_undefine_args *args)
{
int rv = -1;
virInterfacePtr iface = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(iface = get_nonnull_interface(priv->conn, args->iface)))
goto cleanup;
if (virInterfaceUndefine(iface) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (iface)
virInterfaceFree(iface);
return rv;
}
static int remoteDispatchNetworkCreate(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_network_create_args *args);
static int remoteDispatchNetworkCreateHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchNetworkCreate(server, client, msg, rerr, args);
}
static int remoteDispatchNetworkCreate(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_network_create_args *args)
{
int rv = -1;
virNetworkPtr net = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(net = get_nonnull_network(priv->conn, args->net)))
goto cleanup;
if (virNetworkCreate(net) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (net)
virNetworkFree(net);
return rv;
}
static int remoteDispatchNetworkCreateXML(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_network_create_xml_args *args,
remote_network_create_xml_ret *ret);
static int remoteDispatchNetworkCreateXMLHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchNetworkCreateXML(server, client, msg, rerr, args, ret);
}
static int remoteDispatchNetworkCreateXML(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_network_create_xml_args *args,
remote_network_create_xml_ret *ret)
{
int rv = -1;
virNetworkPtr net = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if ((net = virNetworkCreateXML(priv->conn, args->xml)) == NULL)
goto cleanup;
make_nonnull_network(&ret->net, net);
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (net)
virNetworkFree(net);
return rv;
}
static int remoteDispatchNetworkDefineXML(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_network_define_xml_args *args,
remote_network_define_xml_ret *ret);
static int remoteDispatchNetworkDefineXMLHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchNetworkDefineXML(server, client, msg, rerr, args, ret);
}
static int remoteDispatchNetworkDefineXML(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_network_define_xml_args *args,
remote_network_define_xml_ret *ret)
{
int rv = -1;
virNetworkPtr net = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if ((net = virNetworkDefineXML(priv->conn, args->xml)) == NULL)
goto cleanup;
make_nonnull_network(&ret->net, net);
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (net)
virNetworkFree(net);
return rv;
}
static int remoteDispatchNetworkDestroy(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_network_destroy_args *args);
static int remoteDispatchNetworkDestroyHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchNetworkDestroy(server, client, msg, rerr, args);
}
static int remoteDispatchNetworkDestroy(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_network_destroy_args *args)
{
int rv = -1;
virNetworkPtr net = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(net = get_nonnull_network(priv->conn, args->net)))
goto cleanup;
if (virNetworkDestroy(net) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (net)
virNetworkFree(net);
return rv;
}
static int remoteDispatchNetworkGetAutostart(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_network_get_autostart_args *args,
remote_network_get_autostart_ret *ret);
static int remoteDispatchNetworkGetAutostartHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchNetworkGetAutostart(server, client, msg, rerr, args, ret);
}
static int remoteDispatchNetworkGetAutostart(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_network_get_autostart_args *args,
remote_network_get_autostart_ret *ret)
{
int rv = -1;
virNetworkPtr net = NULL;
int autostart;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(net = get_nonnull_network(priv->conn, args->net)))
goto cleanup;
if (virNetworkGetAutostart(net, &autostart) < 0)
goto cleanup;
ret->autostart = autostart;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (net)
virNetworkFree(net);
return rv;
}
static int remoteDispatchNetworkGetBridgeName(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_network_get_bridge_name_args *args,
remote_network_get_bridge_name_ret *ret);
static int remoteDispatchNetworkGetBridgeNameHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchNetworkGetBridgeName(server, client, msg, rerr, args, ret);
}
static int remoteDispatchNetworkGetBridgeName(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_network_get_bridge_name_args *args,
remote_network_get_bridge_name_ret *ret)
{
int rv = -1;
virNetworkPtr net = NULL;
char *name;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(net = get_nonnull_network(priv->conn, args->net)))
goto cleanup;
if ((name = virNetworkGetBridgeName(net)) == NULL)
goto cleanup;
ret->name = name;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (net)
virNetworkFree(net);
return rv;
}
static int remoteDispatchNetworkGetXMLDesc(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_network_get_xml_desc_args *args,
remote_network_get_xml_desc_ret *ret);
static int remoteDispatchNetworkGetXMLDescHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchNetworkGetXMLDesc(server, client, msg, rerr, args, ret);
}
static int remoteDispatchNetworkGetXMLDesc(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_network_get_xml_desc_args *args,
remote_network_get_xml_desc_ret *ret)
{
int rv = -1;
virNetworkPtr net = NULL;
char *xml;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(net = get_nonnull_network(priv->conn, args->net)))
goto cleanup;
if ((xml = virNetworkGetXMLDesc(net, args->flags)) == NULL)
goto cleanup;
ret->xml = xml;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (net)
virNetworkFree(net);
return rv;
}
static int remoteDispatchNetworkIsActive(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_network_is_active_args *args,
remote_network_is_active_ret *ret);
static int remoteDispatchNetworkIsActiveHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchNetworkIsActive(server, client, msg, rerr, args, ret);
}
static int remoteDispatchNetworkIsActive(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_network_is_active_args *args,
remote_network_is_active_ret *ret)
{
int rv = -1;
virNetworkPtr net = NULL;
int active;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(net = get_nonnull_network(priv->conn, args->net)))
goto cleanup;
if ((active = virNetworkIsActive(net)) < 0)
goto cleanup;
ret->active = active;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (net)
virNetworkFree(net);
return rv;
}
static int remoteDispatchNetworkIsPersistent(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_network_is_persistent_args *args,
remote_network_is_persistent_ret *ret);
static int remoteDispatchNetworkIsPersistentHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchNetworkIsPersistent(server, client, msg, rerr, args, ret);
}
static int remoteDispatchNetworkIsPersistent(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_network_is_persistent_args *args,
remote_network_is_persistent_ret *ret)
{
int rv = -1;
virNetworkPtr net = NULL;
int persistent;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(net = get_nonnull_network(priv->conn, args->net)))
goto cleanup;
if ((persistent = virNetworkIsPersistent(net)) < 0)
goto cleanup;
ret->persistent = persistent;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (net)
virNetworkFree(net);
return rv;
}
static int remoteDispatchNetworkLookupByName(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_network_lookup_by_name_args *args,
remote_network_lookup_by_name_ret *ret);
static int remoteDispatchNetworkLookupByNameHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchNetworkLookupByName(server, client, msg, rerr, args, ret);
}
static int remoteDispatchNetworkLookupByName(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_network_lookup_by_name_args *args,
remote_network_lookup_by_name_ret *ret)
{
int rv = -1;
virNetworkPtr net = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if ((net = virNetworkLookupByName(priv->conn, args->name)) == NULL)
goto cleanup;
make_nonnull_network(&ret->net, net);
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (net)
virNetworkFree(net);
return rv;
}
static int remoteDispatchNetworkLookupByUUID(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_network_lookup_by_uuid_args *args,
remote_network_lookup_by_uuid_ret *ret);
static int remoteDispatchNetworkLookupByUUIDHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchNetworkLookupByUUID(server, client, msg, rerr, args, ret);
}
static int remoteDispatchNetworkLookupByUUID(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_network_lookup_by_uuid_args *args,
remote_network_lookup_by_uuid_ret *ret)
{
int rv = -1;
virNetworkPtr net = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if ((net = virNetworkLookupByUUID(priv->conn, (unsigned char *) args->uuid)) == NULL)
goto cleanup;
make_nonnull_network(&ret->net, net);
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (net)
virNetworkFree(net);
return rv;
}
static int remoteDispatchNetworkSetAutostart(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_network_set_autostart_args *args);
static int remoteDispatchNetworkSetAutostartHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchNetworkSetAutostart(server, client, msg, rerr, args);
}
static int remoteDispatchNetworkSetAutostart(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_network_set_autostart_args *args)
{
int rv = -1;
virNetworkPtr net = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(net = get_nonnull_network(priv->conn, args->net)))
goto cleanup;
if (virNetworkSetAutostart(net, args->autostart) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (net)
virNetworkFree(net);
return rv;
}
static int remoteDispatchNetworkUndefine(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_network_undefine_args *args);
static int remoteDispatchNetworkUndefineHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchNetworkUndefine(server, client, msg, rerr, args);
}
static int remoteDispatchNetworkUndefine(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_network_undefine_args *args)
{
int rv = -1;
virNetworkPtr net = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(net = get_nonnull_network(priv->conn, args->net)))
goto cleanup;
if (virNetworkUndefine(net) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (net)
virNetworkFree(net);
return rv;
}
static int remoteDispatchNetworkUpdate(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_network_update_args *args);
static int remoteDispatchNetworkUpdateHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchNetworkUpdate(server, client, msg, rerr, args);
}
static int remoteDispatchNetworkUpdate(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_network_update_args *args)
{
int rv = -1;
virNetworkPtr net = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(net = get_nonnull_network(priv->conn, args->net)))
goto cleanup;
if (virNetworkUpdate(net, args->command, args->section, args->parentIndex, args->xml, args->flags) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (net)
virNetworkFree(net);
return rv;
}
static int remoteDispatchNodeDeviceCreateXML(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_node_device_create_xml_args *args,
remote_node_device_create_xml_ret *ret);
static int remoteDispatchNodeDeviceCreateXMLHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchNodeDeviceCreateXML(server, client, msg, rerr, args, ret);
}
static int remoteDispatchNodeDeviceCreateXML(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_node_device_create_xml_args *args,
remote_node_device_create_xml_ret *ret)
{
int rv = -1;
virNodeDevicePtr dev = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if ((dev = virNodeDeviceCreateXML(priv->conn, args->xml_desc, args->flags)) == NULL)
goto cleanup;
make_nonnull_node_device(&ret->dev, dev);
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dev)
virNodeDeviceFree(dev);
return rv;
}
static int remoteDispatchNodeDeviceDestroy(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_node_device_destroy_args *args);
static int remoteDispatchNodeDeviceDestroyHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchNodeDeviceDestroy(server, client, msg, rerr, args);
}
static int remoteDispatchNodeDeviceDestroy(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_node_device_destroy_args *args)
{
int rv = -1;
virNodeDevicePtr dev = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dev = virNodeDeviceLookupByName(priv->conn, args->name)))
goto cleanup;
if (virNodeDeviceDestroy(dev) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dev)
virNodeDeviceFree(dev);
return rv;
}
static int remoteDispatchNodeDeviceDetachFlags(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_node_device_detach_flags_args *args);
static int remoteDispatchNodeDeviceDetachFlagsHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchNodeDeviceDetachFlags(server, client, msg, rerr, args);
}
static int remoteDispatchNodeDeviceDetachFlags(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_node_device_detach_flags_args *args)
{
int rv = -1;
virNodeDevicePtr dev = NULL;
char *driverName;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dev = virNodeDeviceLookupByName(priv->conn, args->name)))
goto cleanup;
driverName = args->driverName ? *args->driverName : NULL;
if (virNodeDeviceDetachFlags(dev, driverName, args->flags) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dev)
virNodeDeviceFree(dev);
return rv;
}
static int remoteDispatchNodeDeviceDettach(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_node_device_dettach_args *args);
static int remoteDispatchNodeDeviceDettachHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchNodeDeviceDettach(server, client, msg, rerr, args);
}
static int remoteDispatchNodeDeviceDettach(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_node_device_dettach_args *args)
{
int rv = -1;
virNodeDevicePtr dev = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dev = virNodeDeviceLookupByName(priv->conn, args->name)))
goto cleanup;
if (virNodeDeviceDettach(dev) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dev)
virNodeDeviceFree(dev);
return rv;
}
static int remoteDispatchNodeDeviceGetParent(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_node_device_get_parent_args *args,
remote_node_device_get_parent_ret *ret);
static int remoteDispatchNodeDeviceGetParentHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchNodeDeviceGetParent(server, client, msg, rerr, args, ret);
}
/* remoteDispatchNodeDeviceGetParent body has to be implemented manually */
static int remoteDispatchNodeDeviceGetXMLDesc(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_node_device_get_xml_desc_args *args,
remote_node_device_get_xml_desc_ret *ret);
static int remoteDispatchNodeDeviceGetXMLDescHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchNodeDeviceGetXMLDesc(server, client, msg, rerr, args, ret);
}
static int remoteDispatchNodeDeviceGetXMLDesc(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_node_device_get_xml_desc_args *args,
remote_node_device_get_xml_desc_ret *ret)
{
int rv = -1;
virNodeDevicePtr dev = NULL;
char *xml;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dev = virNodeDeviceLookupByName(priv->conn, args->name)))
goto cleanup;
if ((xml = virNodeDeviceGetXMLDesc(dev, args->flags)) == NULL)
goto cleanup;
ret->xml = xml;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dev)
virNodeDeviceFree(dev);
return rv;
}
static int remoteDispatchNodeDeviceListCaps(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_node_device_list_caps_args *args,
remote_node_device_list_caps_ret *ret);
static int remoteDispatchNodeDeviceListCapsHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchNodeDeviceListCaps(server, client, msg, rerr, args, ret);
}
static int remoteDispatchNodeDeviceListCaps(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_node_device_list_caps_args *args,
remote_node_device_list_caps_ret *ret)
{
int rv = -1;
virNodeDevicePtr dev = NULL;
int len;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (args->maxnames > REMOTE_NODE_DEVICE_CAPS_LIST_MAX) {
virReportError(VIR_ERR_INTERNAL_ERROR,
"%s", _("maxnames > REMOTE_NODE_DEVICE_CAPS_LIST_MAX"));
goto cleanup;
}
if (!(dev = virNodeDeviceLookupByName(priv->conn, args->name)))
goto cleanup;
/* Allocate return buffer. */
if (VIR_ALLOC_N(ret->names.names_val, args->maxnames) < 0)
goto cleanup;
if ((len = virNodeDeviceListCaps(dev, ret->names.names_val, args->maxnames)) < 0)
goto cleanup;
ret->names.names_len = len;
rv = 0;
cleanup:
if (rv < 0) {
virNetMessageSaveError(rerr);
VIR_FREE(ret->names.names_val);
}
if (dev)
virNodeDeviceFree(dev);
return rv;
}
static int remoteDispatchNodeDeviceLookupByName(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_node_device_lookup_by_name_args *args,
remote_node_device_lookup_by_name_ret *ret);
static int remoteDispatchNodeDeviceLookupByNameHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchNodeDeviceLookupByName(server, client, msg, rerr, args, ret);
}
static int remoteDispatchNodeDeviceLookupByName(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_node_device_lookup_by_name_args *args,
remote_node_device_lookup_by_name_ret *ret)
{
int rv = -1;
virNodeDevicePtr dev = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if ((dev = virNodeDeviceLookupByName(priv->conn, args->name)) == NULL)
goto cleanup;
make_nonnull_node_device(&ret->dev, dev);
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dev)
virNodeDeviceFree(dev);
return rv;
}
static int remoteDispatchNodeDeviceLookupSCSIHostByWWN(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_node_device_lookup_scsi_host_by_wwn_args *args,
remote_node_device_lookup_scsi_host_by_wwn_ret *ret);
static int remoteDispatchNodeDeviceLookupSCSIHostByWWNHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchNodeDeviceLookupSCSIHostByWWN(server, client, msg, rerr, args, ret);
}
static int remoteDispatchNodeDeviceLookupSCSIHostByWWN(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_node_device_lookup_scsi_host_by_wwn_args *args,
remote_node_device_lookup_scsi_host_by_wwn_ret *ret)
{
int rv = -1;
virNodeDevicePtr dev = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if ((dev = virNodeDeviceLookupSCSIHostByWWN(priv->conn, args->wwnn, args->wwpn, args->flags)) == NULL)
goto cleanup;
make_nonnull_node_device(&ret->dev, dev);
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dev)
virNodeDeviceFree(dev);
return rv;
}
static int remoteDispatchNodeDeviceNumOfCaps(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_node_device_num_of_caps_args *args,
remote_node_device_num_of_caps_ret *ret);
static int remoteDispatchNodeDeviceNumOfCapsHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchNodeDeviceNumOfCaps(server, client, msg, rerr, args, ret);
}
static int remoteDispatchNodeDeviceNumOfCaps(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_node_device_num_of_caps_args *args,
remote_node_device_num_of_caps_ret *ret)
{
int rv = -1;
virNodeDevicePtr dev = NULL;
int num;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dev = virNodeDeviceLookupByName(priv->conn, args->name)))
goto cleanup;
if ((num = virNodeDeviceNumOfCaps(dev)) < 0)
goto cleanup;
ret->num = num;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dev)
virNodeDeviceFree(dev);
return rv;
}
static int remoteDispatchNodeDeviceReAttach(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_node_device_re_attach_args *args);
static int remoteDispatchNodeDeviceReAttachHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchNodeDeviceReAttach(server, client, msg, rerr, args);
}
static int remoteDispatchNodeDeviceReAttach(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_node_device_re_attach_args *args)
{
int rv = -1;
virNodeDevicePtr dev = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dev = virNodeDeviceLookupByName(priv->conn, args->name)))
goto cleanup;
if (virNodeDeviceReAttach(dev) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dev)
virNodeDeviceFree(dev);
return rv;
}
static int remoteDispatchNodeDeviceReset(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_node_device_reset_args *args);
static int remoteDispatchNodeDeviceResetHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchNodeDeviceReset(server, client, msg, rerr, args);
}
static int remoteDispatchNodeDeviceReset(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_node_device_reset_args *args)
{
int rv = -1;
virNodeDevicePtr dev = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(dev = virNodeDeviceLookupByName(priv->conn, args->name)))
goto cleanup;
if (virNodeDeviceReset(dev) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (dev)
virNodeDeviceFree(dev);
return rv;
}
static int remoteDispatchNodeGetCellsFreeMemory(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_node_get_cells_free_memory_args *args,
remote_node_get_cells_free_memory_ret *ret);
static int remoteDispatchNodeGetCellsFreeMemoryHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchNodeGetCellsFreeMemory(server, client, msg, rerr, args, ret);
}
static int remoteDispatchNodeGetCellsFreeMemory(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_node_get_cells_free_memory_args *args,
remote_node_get_cells_free_memory_ret *ret)
{
int rv = -1;
int len;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (args->maxcells > REMOTE_NODE_MAX_CELLS) {
virReportError(VIR_ERR_INTERNAL_ERROR,
"%s", _("maxcells > REMOTE_NODE_MAX_CELLS"));
goto cleanup;
}
/* Allocate return buffer. */
if (VIR_ALLOC_N(ret->cells.cells_val, args->maxcells) < 0)
goto cleanup;
if ((len = virNodeGetCellsFreeMemory(priv->conn, (unsigned long long *)ret->cells.cells_val, args->startCell, args->maxcells)) <= 0)
goto cleanup;
ret->cells.cells_len = len;
rv = 0;
cleanup:
if (rv < 0) {
virNetMessageSaveError(rerr);
VIR_FREE(ret->cells.cells_val);
}
return rv;
}
static int remoteDispatchNodeGetCPUMap(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_node_get_cpu_map_args *args,
remote_node_get_cpu_map_ret *ret);
static int remoteDispatchNodeGetCPUMapHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchNodeGetCPUMap(server, client, msg, rerr, args, ret);
}
/* remoteDispatchNodeGetCPUMap body has to be implemented manually */
static int remoteDispatchNodeGetCPUStats(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_node_get_cpu_stats_args *args,
remote_node_get_cpu_stats_ret *ret);
static int remoteDispatchNodeGetCPUStatsHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchNodeGetCPUStats(server, client, msg, rerr, args, ret);
}
/* remoteDispatchNodeGetCPUStats body has to be implemented manually */
static int remoteDispatchNodeGetFreeMemory(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_node_get_free_memory_ret *ret);
static int remoteDispatchNodeGetFreeMemoryHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args ATTRIBUTE_UNUSED,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchNodeGetFreeMemory(server, client, msg, rerr, ret);
}
static int remoteDispatchNodeGetFreeMemory(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_node_get_free_memory_ret *ret)
{
int rv = -1;
unsigned long long freeMem;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if ((freeMem = virNodeGetFreeMemory(priv->conn)) == 0)
goto cleanup;
ret->freeMem = freeMem;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
return rv;
}
static int remoteDispatchNodeGetInfo(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_node_get_info_ret *ret);
static int remoteDispatchNodeGetInfoHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args ATTRIBUTE_UNUSED,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchNodeGetInfo(server, client, msg, rerr, ret);
}
static int remoteDispatchNodeGetInfo(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_node_get_info_ret *ret)
{
int rv = -1;
virNodeInfo tmp;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (virNodeGetInfo(priv->conn, &tmp) < 0)
goto cleanup;
memcpy(ret->model, tmp.model, sizeof(ret->model));
ret->memory = tmp.memory;
ret->cpus = tmp.cpus;
ret->mhz = tmp.mhz;
ret->nodes = tmp.nodes;
ret->sockets = tmp.sockets;
ret->cores = tmp.cores;
ret->threads = tmp.threads;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
return rv;
}
static int remoteDispatchNodeGetMemoryParameters(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_node_get_memory_parameters_args *args,
remote_node_get_memory_parameters_ret *ret);
static int remoteDispatchNodeGetMemoryParametersHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchNodeGetMemoryParameters(server, client, msg, rerr, args, ret);
}
/* remoteDispatchNodeGetMemoryParameters body has to be implemented manually */
static int remoteDispatchNodeGetMemoryStats(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_node_get_memory_stats_args *args,
remote_node_get_memory_stats_ret *ret);
static int remoteDispatchNodeGetMemoryStatsHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchNodeGetMemoryStats(server, client, msg, rerr, args, ret);
}
/* remoteDispatchNodeGetMemoryStats body has to be implemented manually */
static int remoteDispatchNodeGetSecurityModel(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_node_get_security_model_ret *ret);
static int remoteDispatchNodeGetSecurityModelHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args ATTRIBUTE_UNUSED,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchNodeGetSecurityModel(server, client, msg, rerr, ret);
}
/* remoteDispatchNodeGetSecurityModel body has to be implemented manually */
static int remoteDispatchNodeListDevices(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_node_list_devices_args *args,
remote_node_list_devices_ret *ret);
static int remoteDispatchNodeListDevicesHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchNodeListDevices(server, client, msg, rerr, args, ret);
}
static int remoteDispatchNodeListDevices(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_node_list_devices_args *args,
remote_node_list_devices_ret *ret)
{
int rv = -1;
char *cap;
int len;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (args->maxnames > REMOTE_NODE_DEVICE_LIST_MAX) {
virReportError(VIR_ERR_INTERNAL_ERROR,
"%s", _("maxnames > REMOTE_NODE_DEVICE_LIST_MAX"));
goto cleanup;
}
cap = args->cap ? *args->cap : NULL;
/* Allocate return buffer. */
if (VIR_ALLOC_N(ret->names.names_val, args->maxnames) < 0)
goto cleanup;
if ((len = virNodeListDevices(priv->conn, cap, ret->names.names_val, args->maxnames, args->flags)) < 0)
goto cleanup;
ret->names.names_len = len;
rv = 0;
cleanup:
if (rv < 0) {
virNetMessageSaveError(rerr);
VIR_FREE(ret->names.names_val);
}
return rv;
}
static int remoteDispatchNodeNumOfDevices(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_node_num_of_devices_args *args,
remote_node_num_of_devices_ret *ret);
static int remoteDispatchNodeNumOfDevicesHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchNodeNumOfDevices(server, client, msg, rerr, args, ret);
}
static int remoteDispatchNodeNumOfDevices(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_node_num_of_devices_args *args,
remote_node_num_of_devices_ret *ret)
{
int rv = -1;
char *cap;
int num;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
cap = args->cap ? *args->cap : NULL;
if ((num = virNodeNumOfDevices(priv->conn, cap, args->flags)) < 0)
goto cleanup;
ret->num = num;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
return rv;
}
static int remoteDispatchNodeSetMemoryParameters(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_node_set_memory_parameters_args *args);
static int remoteDispatchNodeSetMemoryParametersHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchNodeSetMemoryParameters(server, client, msg, rerr, args);
}
static int remoteDispatchNodeSetMemoryParameters(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_node_set_memory_parameters_args *args)
{
int rv = -1;
virTypedParameterPtr params = NULL;
int nparams = 0;;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if ((params = remoteDeserializeTypedParameters(args->params.params_val,
args->params.params_len,
REMOTE_NODE_MEMORY_PARAMETERS_MAX,
&nparams)) == NULL)
goto cleanup;
if (virNodeSetMemoryParameters(priv->conn, params, nparams, args->flags) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
virTypedParamsFree(params, nparams);
return rv;
}
static int remoteDispatchNodeSuspendForDuration(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_node_suspend_for_duration_args *args);
static int remoteDispatchNodeSuspendForDurationHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchNodeSuspendForDuration(server, client, msg, rerr, args);
}
static int remoteDispatchNodeSuspendForDuration(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_node_suspend_for_duration_args *args)
{
int rv = -1;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (virNodeSuspendForDuration(priv->conn, args->target, args->duration, args->flags) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
return rv;
}
static int remoteDispatchNWFilterDefineXML(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_nwfilter_define_xml_args *args,
remote_nwfilter_define_xml_ret *ret);
static int remoteDispatchNWFilterDefineXMLHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchNWFilterDefineXML(server, client, msg, rerr, args, ret);
}
static int remoteDispatchNWFilterDefineXML(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_nwfilter_define_xml_args *args,
remote_nwfilter_define_xml_ret *ret)
{
int rv = -1;
virNWFilterPtr nwfilter = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if ((nwfilter = virNWFilterDefineXML(priv->conn, args->xml)) == NULL)
goto cleanup;
make_nonnull_nwfilter(&ret->nwfilter, nwfilter);
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (nwfilter)
virNWFilterFree(nwfilter);
return rv;
}
static int remoteDispatchNWFilterGetXMLDesc(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_nwfilter_get_xml_desc_args *args,
remote_nwfilter_get_xml_desc_ret *ret);
static int remoteDispatchNWFilterGetXMLDescHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchNWFilterGetXMLDesc(server, client, msg, rerr, args, ret);
}
static int remoteDispatchNWFilterGetXMLDesc(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_nwfilter_get_xml_desc_args *args,
remote_nwfilter_get_xml_desc_ret *ret)
{
int rv = -1;
virNWFilterPtr nwfilter = NULL;
char *xml;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(nwfilter = get_nonnull_nwfilter(priv->conn, args->nwfilter)))
goto cleanup;
if ((xml = virNWFilterGetXMLDesc(nwfilter, args->flags)) == NULL)
goto cleanup;
ret->xml = xml;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (nwfilter)
virNWFilterFree(nwfilter);
return rv;
}
static int remoteDispatchNWFilterLookupByName(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_nwfilter_lookup_by_name_args *args,
remote_nwfilter_lookup_by_name_ret *ret);
static int remoteDispatchNWFilterLookupByNameHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchNWFilterLookupByName(server, client, msg, rerr, args, ret);
}
static int remoteDispatchNWFilterLookupByName(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_nwfilter_lookup_by_name_args *args,
remote_nwfilter_lookup_by_name_ret *ret)
{
int rv = -1;
virNWFilterPtr nwfilter = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if ((nwfilter = virNWFilterLookupByName(priv->conn, args->name)) == NULL)
goto cleanup;
make_nonnull_nwfilter(&ret->nwfilter, nwfilter);
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (nwfilter)
virNWFilterFree(nwfilter);
return rv;
}
static int remoteDispatchNWFilterLookupByUUID(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_nwfilter_lookup_by_uuid_args *args,
remote_nwfilter_lookup_by_uuid_ret *ret);
static int remoteDispatchNWFilterLookupByUUIDHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchNWFilterLookupByUUID(server, client, msg, rerr, args, ret);
}
static int remoteDispatchNWFilterLookupByUUID(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_nwfilter_lookup_by_uuid_args *args,
remote_nwfilter_lookup_by_uuid_ret *ret)
{
int rv = -1;
virNWFilterPtr nwfilter = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if ((nwfilter = virNWFilterLookupByUUID(priv->conn, (unsigned char *) args->uuid)) == NULL)
goto cleanup;
make_nonnull_nwfilter(&ret->nwfilter, nwfilter);
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (nwfilter)
virNWFilterFree(nwfilter);
return rv;
}
static int remoteDispatchNWFilterUndefine(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_nwfilter_undefine_args *args);
static int remoteDispatchNWFilterUndefineHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchNWFilterUndefine(server, client, msg, rerr, args);
}
static int remoteDispatchNWFilterUndefine(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_nwfilter_undefine_args *args)
{
int rv = -1;
virNWFilterPtr nwfilter = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(nwfilter = get_nonnull_nwfilter(priv->conn, args->nwfilter)))
goto cleanup;
if (virNWFilterUndefine(nwfilter) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (nwfilter)
virNWFilterFree(nwfilter);
return rv;
}
static int remoteDispatchSecretDefineXML(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_secret_define_xml_args *args,
remote_secret_define_xml_ret *ret);
static int remoteDispatchSecretDefineXMLHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchSecretDefineXML(server, client, msg, rerr, args, ret);
}
static int remoteDispatchSecretDefineXML(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_secret_define_xml_args *args,
remote_secret_define_xml_ret *ret)
{
int rv = -1;
virSecretPtr secret = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if ((secret = virSecretDefineXML(priv->conn, args->xml, args->flags)) == NULL)
goto cleanup;
make_nonnull_secret(&ret->secret, secret);
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (secret)
virSecretFree(secret);
return rv;
}
static int remoteDispatchSecretGetValue(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_secret_get_value_args *args,
remote_secret_get_value_ret *ret);
static int remoteDispatchSecretGetValueHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchSecretGetValue(server, client, msg, rerr, args, ret);
}
/* remoteDispatchSecretGetValue body has to be implemented manually */
static int remoteDispatchSecretGetXMLDesc(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_secret_get_xml_desc_args *args,
remote_secret_get_xml_desc_ret *ret);
static int remoteDispatchSecretGetXMLDescHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchSecretGetXMLDesc(server, client, msg, rerr, args, ret);
}
static int remoteDispatchSecretGetXMLDesc(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_secret_get_xml_desc_args *args,
remote_secret_get_xml_desc_ret *ret)
{
int rv = -1;
virSecretPtr secret = NULL;
char *xml;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(secret = get_nonnull_secret(priv->conn, args->secret)))
goto cleanup;
if ((xml = virSecretGetXMLDesc(secret, args->flags)) == NULL)
goto cleanup;
ret->xml = xml;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (secret)
virSecretFree(secret);
return rv;
}
static int remoteDispatchSecretLookupByUsage(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_secret_lookup_by_usage_args *args,
remote_secret_lookup_by_usage_ret *ret);
static int remoteDispatchSecretLookupByUsageHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchSecretLookupByUsage(server, client, msg, rerr, args, ret);
}
static int remoteDispatchSecretLookupByUsage(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_secret_lookup_by_usage_args *args,
remote_secret_lookup_by_usage_ret *ret)
{
int rv = -1;
virSecretPtr secret = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if ((secret = virSecretLookupByUsage(priv->conn, args->usageType, args->usageID)) == NULL)
goto cleanup;
make_nonnull_secret(&ret->secret, secret);
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (secret)
virSecretFree(secret);
return rv;
}
static int remoteDispatchSecretLookupByUUID(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_secret_lookup_by_uuid_args *args,
remote_secret_lookup_by_uuid_ret *ret);
static int remoteDispatchSecretLookupByUUIDHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchSecretLookupByUUID(server, client, msg, rerr, args, ret);
}
static int remoteDispatchSecretLookupByUUID(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_secret_lookup_by_uuid_args *args,
remote_secret_lookup_by_uuid_ret *ret)
{
int rv = -1;
virSecretPtr secret = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if ((secret = virSecretLookupByUUID(priv->conn, (unsigned char *) args->uuid)) == NULL)
goto cleanup;
make_nonnull_secret(&ret->secret, secret);
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (secret)
virSecretFree(secret);
return rv;
}
static int remoteDispatchSecretSetValue(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_secret_set_value_args *args);
static int remoteDispatchSecretSetValueHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchSecretSetValue(server, client, msg, rerr, args);
}
static int remoteDispatchSecretSetValue(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_secret_set_value_args *args)
{
int rv = -1;
virSecretPtr secret = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(secret = get_nonnull_secret(priv->conn, args->secret)))
goto cleanup;
if (virSecretSetValue(secret, (const unsigned char *) args->value.value_val, args->value.value_len, args->flags) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (secret)
virSecretFree(secret);
return rv;
}
static int remoteDispatchSecretUndefine(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_secret_undefine_args *args);
static int remoteDispatchSecretUndefineHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchSecretUndefine(server, client, msg, rerr, args);
}
static int remoteDispatchSecretUndefine(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_secret_undefine_args *args)
{
int rv = -1;
virSecretPtr secret = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(secret = get_nonnull_secret(priv->conn, args->secret)))
goto cleanup;
if (virSecretUndefine(secret) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (secret)
virSecretFree(secret);
return rv;
}
static int remoteDispatchStoragePoolBuild(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_storage_pool_build_args *args);
static int remoteDispatchStoragePoolBuildHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchStoragePoolBuild(server, client, msg, rerr, args);
}
static int remoteDispatchStoragePoolBuild(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_storage_pool_build_args *args)
{
int rv = -1;
virStoragePoolPtr pool = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(pool = get_nonnull_storage_pool(priv->conn, args->pool)))
goto cleanup;
if (virStoragePoolBuild(pool, args->flags) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (pool)
virStoragePoolFree(pool);
return rv;
}
static int remoteDispatchStoragePoolCreate(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_storage_pool_create_args *args);
static int remoteDispatchStoragePoolCreateHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchStoragePoolCreate(server, client, msg, rerr, args);
}
static int remoteDispatchStoragePoolCreate(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_storage_pool_create_args *args)
{
int rv = -1;
virStoragePoolPtr pool = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(pool = get_nonnull_storage_pool(priv->conn, args->pool)))
goto cleanup;
if (virStoragePoolCreate(pool, args->flags) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (pool)
virStoragePoolFree(pool);
return rv;
}
static int remoteDispatchStoragePoolCreateXML(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_storage_pool_create_xml_args *args,
remote_storage_pool_create_xml_ret *ret);
static int remoteDispatchStoragePoolCreateXMLHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchStoragePoolCreateXML(server, client, msg, rerr, args, ret);
}
static int remoteDispatchStoragePoolCreateXML(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_storage_pool_create_xml_args *args,
remote_storage_pool_create_xml_ret *ret)
{
int rv = -1;
virStoragePoolPtr pool = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if ((pool = virStoragePoolCreateXML(priv->conn, args->xml, args->flags)) == NULL)
goto cleanup;
make_nonnull_storage_pool(&ret->pool, pool);
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (pool)
virStoragePoolFree(pool);
return rv;
}
static int remoteDispatchStoragePoolDefineXML(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_storage_pool_define_xml_args *args,
remote_storage_pool_define_xml_ret *ret);
static int remoteDispatchStoragePoolDefineXMLHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchStoragePoolDefineXML(server, client, msg, rerr, args, ret);
}
static int remoteDispatchStoragePoolDefineXML(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_storage_pool_define_xml_args *args,
remote_storage_pool_define_xml_ret *ret)
{
int rv = -1;
virStoragePoolPtr pool = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if ((pool = virStoragePoolDefineXML(priv->conn, args->xml, args->flags)) == NULL)
goto cleanup;
make_nonnull_storage_pool(&ret->pool, pool);
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (pool)
virStoragePoolFree(pool);
return rv;
}
static int remoteDispatchStoragePoolDelete(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_storage_pool_delete_args *args);
static int remoteDispatchStoragePoolDeleteHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchStoragePoolDelete(server, client, msg, rerr, args);
}
static int remoteDispatchStoragePoolDelete(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_storage_pool_delete_args *args)
{
int rv = -1;
virStoragePoolPtr pool = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(pool = get_nonnull_storage_pool(priv->conn, args->pool)))
goto cleanup;
if (virStoragePoolDelete(pool, args->flags) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (pool)
virStoragePoolFree(pool);
return rv;
}
static int remoteDispatchStoragePoolDestroy(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_storage_pool_destroy_args *args);
static int remoteDispatchStoragePoolDestroyHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchStoragePoolDestroy(server, client, msg, rerr, args);
}
static int remoteDispatchStoragePoolDestroy(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_storage_pool_destroy_args *args)
{
int rv = -1;
virStoragePoolPtr pool = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(pool = get_nonnull_storage_pool(priv->conn, args->pool)))
goto cleanup;
if (virStoragePoolDestroy(pool) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (pool)
virStoragePoolFree(pool);
return rv;
}
static int remoteDispatchStoragePoolGetAutostart(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_storage_pool_get_autostart_args *args,
remote_storage_pool_get_autostart_ret *ret);
static int remoteDispatchStoragePoolGetAutostartHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchStoragePoolGetAutostart(server, client, msg, rerr, args, ret);
}
static int remoteDispatchStoragePoolGetAutostart(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_storage_pool_get_autostart_args *args,
remote_storage_pool_get_autostart_ret *ret)
{
int rv = -1;
virStoragePoolPtr pool = NULL;
int autostart;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(pool = get_nonnull_storage_pool(priv->conn, args->pool)))
goto cleanup;
if (virStoragePoolGetAutostart(pool, &autostart) < 0)
goto cleanup;
ret->autostart = autostart;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (pool)
virStoragePoolFree(pool);
return rv;
}
static int remoteDispatchStoragePoolGetInfo(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_storage_pool_get_info_args *args,
remote_storage_pool_get_info_ret *ret);
static int remoteDispatchStoragePoolGetInfoHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchStoragePoolGetInfo(server, client, msg, rerr, args, ret);
}
static int remoteDispatchStoragePoolGetInfo(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_storage_pool_get_info_args *args,
remote_storage_pool_get_info_ret *ret)
{
int rv = -1;
virStoragePoolPtr pool = NULL;
virStoragePoolInfo tmp;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(pool = get_nonnull_storage_pool(priv->conn, args->pool)))
goto cleanup;
if (virStoragePoolGetInfo(pool, &tmp) < 0)
goto cleanup;
ret->state = tmp.state;
ret->capacity = tmp.capacity;
ret->allocation = tmp.allocation;
ret->available = tmp.available;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (pool)
virStoragePoolFree(pool);
return rv;
}
static int remoteDispatchStoragePoolGetXMLDesc(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_storage_pool_get_xml_desc_args *args,
remote_storage_pool_get_xml_desc_ret *ret);
static int remoteDispatchStoragePoolGetXMLDescHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchStoragePoolGetXMLDesc(server, client, msg, rerr, args, ret);
}
static int remoteDispatchStoragePoolGetXMLDesc(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_storage_pool_get_xml_desc_args *args,
remote_storage_pool_get_xml_desc_ret *ret)
{
int rv = -1;
virStoragePoolPtr pool = NULL;
char *xml;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(pool = get_nonnull_storage_pool(priv->conn, args->pool)))
goto cleanup;
if ((xml = virStoragePoolGetXMLDesc(pool, args->flags)) == NULL)
goto cleanup;
ret->xml = xml;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (pool)
virStoragePoolFree(pool);
return rv;
}
static int remoteDispatchStoragePoolIsActive(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_storage_pool_is_active_args *args,
remote_storage_pool_is_active_ret *ret);
static int remoteDispatchStoragePoolIsActiveHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchStoragePoolIsActive(server, client, msg, rerr, args, ret);
}
static int remoteDispatchStoragePoolIsActive(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_storage_pool_is_active_args *args,
remote_storage_pool_is_active_ret *ret)
{
int rv = -1;
virStoragePoolPtr pool = NULL;
int active;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(pool = get_nonnull_storage_pool(priv->conn, args->pool)))
goto cleanup;
if ((active = virStoragePoolIsActive(pool)) < 0)
goto cleanup;
ret->active = active;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (pool)
virStoragePoolFree(pool);
return rv;
}
static int remoteDispatchStoragePoolIsPersistent(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_storage_pool_is_persistent_args *args,
remote_storage_pool_is_persistent_ret *ret);
static int remoteDispatchStoragePoolIsPersistentHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchStoragePoolIsPersistent(server, client, msg, rerr, args, ret);
}
static int remoteDispatchStoragePoolIsPersistent(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_storage_pool_is_persistent_args *args,
remote_storage_pool_is_persistent_ret *ret)
{
int rv = -1;
virStoragePoolPtr pool = NULL;
int persistent;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(pool = get_nonnull_storage_pool(priv->conn, args->pool)))
goto cleanup;
if ((persistent = virStoragePoolIsPersistent(pool)) < 0)
goto cleanup;
ret->persistent = persistent;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (pool)
virStoragePoolFree(pool);
return rv;
}
static int remoteDispatchStoragePoolListAllVolumes(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_storage_pool_list_all_volumes_args *args,
remote_storage_pool_list_all_volumes_ret *ret);
static int remoteDispatchStoragePoolListAllVolumesHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchStoragePoolListAllVolumes(server, client, msg, rerr, args, ret);
}
/* remoteDispatchStoragePoolListAllVolumes body has to be implemented manually */
static int remoteDispatchStoragePoolListVolumes(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_storage_pool_list_volumes_args *args,
remote_storage_pool_list_volumes_ret *ret);
static int remoteDispatchStoragePoolListVolumesHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchStoragePoolListVolumes(server, client, msg, rerr, args, ret);
}
static int remoteDispatchStoragePoolListVolumes(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_storage_pool_list_volumes_args *args,
remote_storage_pool_list_volumes_ret *ret)
{
int rv = -1;
virStoragePoolPtr pool = NULL;
int len;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (args->maxnames > REMOTE_STORAGE_VOL_LIST_MAX) {
virReportError(VIR_ERR_INTERNAL_ERROR,
"%s", _("maxnames > REMOTE_STORAGE_VOL_LIST_MAX"));
goto cleanup;
}
if (!(pool = get_nonnull_storage_pool(priv->conn, args->pool)))
goto cleanup;
/* Allocate return buffer. */
if (VIR_ALLOC_N(ret->names.names_val, args->maxnames) < 0)
goto cleanup;
if ((len = virStoragePoolListVolumes(pool, ret->names.names_val, args->maxnames)) < 0)
goto cleanup;
ret->names.names_len = len;
rv = 0;
cleanup:
if (rv < 0) {
virNetMessageSaveError(rerr);
VIR_FREE(ret->names.names_val);
}
if (pool)
virStoragePoolFree(pool);
return rv;
}
static int remoteDispatchStoragePoolLookupByName(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_storage_pool_lookup_by_name_args *args,
remote_storage_pool_lookup_by_name_ret *ret);
static int remoteDispatchStoragePoolLookupByNameHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchStoragePoolLookupByName(server, client, msg, rerr, args, ret);
}
static int remoteDispatchStoragePoolLookupByName(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_storage_pool_lookup_by_name_args *args,
remote_storage_pool_lookup_by_name_ret *ret)
{
int rv = -1;
virStoragePoolPtr pool = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if ((pool = virStoragePoolLookupByName(priv->conn, args->name)) == NULL)
goto cleanup;
make_nonnull_storage_pool(&ret->pool, pool);
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (pool)
virStoragePoolFree(pool);
return rv;
}
static int remoteDispatchStoragePoolLookupByUUID(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_storage_pool_lookup_by_uuid_args *args,
remote_storage_pool_lookup_by_uuid_ret *ret);
static int remoteDispatchStoragePoolLookupByUUIDHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchStoragePoolLookupByUUID(server, client, msg, rerr, args, ret);
}
static int remoteDispatchStoragePoolLookupByUUID(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_storage_pool_lookup_by_uuid_args *args,
remote_storage_pool_lookup_by_uuid_ret *ret)
{
int rv = -1;
virStoragePoolPtr pool = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if ((pool = virStoragePoolLookupByUUID(priv->conn, (unsigned char *) args->uuid)) == NULL)
goto cleanup;
make_nonnull_storage_pool(&ret->pool, pool);
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (pool)
virStoragePoolFree(pool);
return rv;
}
static int remoteDispatchStoragePoolLookupByVolume(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_storage_pool_lookup_by_volume_args *args,
remote_storage_pool_lookup_by_volume_ret *ret);
static int remoteDispatchStoragePoolLookupByVolumeHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchStoragePoolLookupByVolume(server, client, msg, rerr, args, ret);
}
static int remoteDispatchStoragePoolLookupByVolume(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_storage_pool_lookup_by_volume_args *args,
remote_storage_pool_lookup_by_volume_ret *ret)
{
int rv = -1;
virStorageVolPtr vol = NULL;
virStoragePoolPtr pool = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(vol = get_nonnull_storage_vol(priv->conn, args->vol)))
goto cleanup;
if ((pool = virStoragePoolLookupByVolume(vol)) == NULL)
goto cleanup;
make_nonnull_storage_pool(&ret->pool, pool);
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (vol)
virStorageVolFree(vol);
if (pool)
virStoragePoolFree(pool);
return rv;
}
static int remoteDispatchStoragePoolNumOfVolumes(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_storage_pool_num_of_volumes_args *args,
remote_storage_pool_num_of_volumes_ret *ret);
static int remoteDispatchStoragePoolNumOfVolumesHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchStoragePoolNumOfVolumes(server, client, msg, rerr, args, ret);
}
static int remoteDispatchStoragePoolNumOfVolumes(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_storage_pool_num_of_volumes_args *args,
remote_storage_pool_num_of_volumes_ret *ret)
{
int rv = -1;
virStoragePoolPtr pool = NULL;
int num;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(pool = get_nonnull_storage_pool(priv->conn, args->pool)))
goto cleanup;
if ((num = virStoragePoolNumOfVolumes(pool)) < 0)
goto cleanup;
ret->num = num;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (pool)
virStoragePoolFree(pool);
return rv;
}
static int remoteDispatchStoragePoolRefresh(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_storage_pool_refresh_args *args);
static int remoteDispatchStoragePoolRefreshHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchStoragePoolRefresh(server, client, msg, rerr, args);
}
static int remoteDispatchStoragePoolRefresh(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_storage_pool_refresh_args *args)
{
int rv = -1;
virStoragePoolPtr pool = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(pool = get_nonnull_storage_pool(priv->conn, args->pool)))
goto cleanup;
if (virStoragePoolRefresh(pool, args->flags) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (pool)
virStoragePoolFree(pool);
return rv;
}
static int remoteDispatchStoragePoolSetAutostart(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_storage_pool_set_autostart_args *args);
static int remoteDispatchStoragePoolSetAutostartHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchStoragePoolSetAutostart(server, client, msg, rerr, args);
}
static int remoteDispatchStoragePoolSetAutostart(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_storage_pool_set_autostart_args *args)
{
int rv = -1;
virStoragePoolPtr pool = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(pool = get_nonnull_storage_pool(priv->conn, args->pool)))
goto cleanup;
if (virStoragePoolSetAutostart(pool, args->autostart) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (pool)
virStoragePoolFree(pool);
return rv;
}
static int remoteDispatchStoragePoolUndefine(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_storage_pool_undefine_args *args);
static int remoteDispatchStoragePoolUndefineHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchStoragePoolUndefine(server, client, msg, rerr, args);
}
static int remoteDispatchStoragePoolUndefine(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_storage_pool_undefine_args *args)
{
int rv = -1;
virStoragePoolPtr pool = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(pool = get_nonnull_storage_pool(priv->conn, args->pool)))
goto cleanup;
if (virStoragePoolUndefine(pool) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (pool)
virStoragePoolFree(pool);
return rv;
}
static int remoteDispatchStorageVolCreateXML(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_storage_vol_create_xml_args *args,
remote_storage_vol_create_xml_ret *ret);
static int remoteDispatchStorageVolCreateXMLHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchStorageVolCreateXML(server, client, msg, rerr, args, ret);
}
static int remoteDispatchStorageVolCreateXML(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_storage_vol_create_xml_args *args,
remote_storage_vol_create_xml_ret *ret)
{
int rv = -1;
virStoragePoolPtr pool = NULL;
virStorageVolPtr vol = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(pool = get_nonnull_storage_pool(priv->conn, args->pool)))
goto cleanup;
if ((vol = virStorageVolCreateXML(pool, args->xml, args->flags)) == NULL)
goto cleanup;
make_nonnull_storage_vol(&ret->vol, vol);
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (pool)
virStoragePoolFree(pool);
if (vol)
virStorageVolFree(vol);
return rv;
}
static int remoteDispatchStorageVolCreateXMLFrom(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_storage_vol_create_xml_from_args *args,
remote_storage_vol_create_xml_from_ret *ret);
static int remoteDispatchStorageVolCreateXMLFromHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchStorageVolCreateXMLFrom(server, client, msg, rerr, args, ret);
}
static int remoteDispatchStorageVolCreateXMLFrom(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_storage_vol_create_xml_from_args *args,
remote_storage_vol_create_xml_from_ret *ret)
{
int rv = -1;
virStoragePoolPtr pool = NULL;
virStorageVolPtr clonevol = NULL;
virStorageVolPtr vol = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(pool = get_nonnull_storage_pool(priv->conn, args->pool)))
goto cleanup;
if (!(clonevol = get_nonnull_storage_vol(priv->conn, args->clonevol)))
goto cleanup;
if ((vol = virStorageVolCreateXMLFrom(pool, args->xml, clonevol, args->flags)) == NULL)
goto cleanup;
make_nonnull_storage_vol(&ret->vol, vol);
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (pool)
virStoragePoolFree(pool);
if (clonevol)
virStorageVolFree(clonevol);
if (vol)
virStorageVolFree(vol);
return rv;
}
static int remoteDispatchStorageVolDelete(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_storage_vol_delete_args *args);
static int remoteDispatchStorageVolDeleteHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchStorageVolDelete(server, client, msg, rerr, args);
}
static int remoteDispatchStorageVolDelete(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_storage_vol_delete_args *args)
{
int rv = -1;
virStorageVolPtr vol = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(vol = get_nonnull_storage_vol(priv->conn, args->vol)))
goto cleanup;
if (virStorageVolDelete(vol, args->flags) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (vol)
virStorageVolFree(vol);
return rv;
}
static int remoteDispatchStorageVolDownload(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_storage_vol_download_args *args);
static int remoteDispatchStorageVolDownloadHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchStorageVolDownload(server, client, msg, rerr, args);
}
static int remoteDispatchStorageVolDownload(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_storage_vol_download_args *args)
{
int rv = -1;
virStorageVolPtr vol = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
virStreamPtr st = NULL;
daemonClientStreamPtr stream = NULL;
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(vol = get_nonnull_storage_vol(priv->conn, args->vol)))
goto cleanup;
if (!(st = virStreamNew(priv->conn, VIR_STREAM_NONBLOCK)))
goto cleanup;
if (!(stream = daemonCreateClientStream(client, st, remoteProgram, &msg->header)))
goto cleanup;
if (virStorageVolDownload(vol, st, args->offset, args->length, args->flags) < 0)
goto cleanup;
if (daemonAddClientStream(client, stream, true) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0) {
virNetMessageSaveError(rerr);
if (stream) {
virStreamAbort(st);
daemonFreeClientStream(client, stream);
} else {
virStreamFree(st);
}
}
if (vol)
virStorageVolFree(vol);
return rv;
}
static int remoteDispatchStorageVolGetInfo(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_storage_vol_get_info_args *args,
remote_storage_vol_get_info_ret *ret);
static int remoteDispatchStorageVolGetInfoHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchStorageVolGetInfo(server, client, msg, rerr, args, ret);
}
static int remoteDispatchStorageVolGetInfo(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_storage_vol_get_info_args *args,
remote_storage_vol_get_info_ret *ret)
{
int rv = -1;
virStorageVolPtr vol = NULL;
virStorageVolInfo tmp;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(vol = get_nonnull_storage_vol(priv->conn, args->vol)))
goto cleanup;
if (virStorageVolGetInfo(vol, &tmp) < 0)
goto cleanup;
ret->type = tmp.type;
ret->capacity = tmp.capacity;
ret->allocation = tmp.allocation;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (vol)
virStorageVolFree(vol);
return rv;
}
static int remoteDispatchStorageVolGetPath(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_storage_vol_get_path_args *args,
remote_storage_vol_get_path_ret *ret);
static int remoteDispatchStorageVolGetPathHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchStorageVolGetPath(server, client, msg, rerr, args, ret);
}
static int remoteDispatchStorageVolGetPath(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_storage_vol_get_path_args *args,
remote_storage_vol_get_path_ret *ret)
{
int rv = -1;
virStorageVolPtr vol = NULL;
char *name;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(vol = get_nonnull_storage_vol(priv->conn, args->vol)))
goto cleanup;
if ((name = virStorageVolGetPath(vol)) == NULL)
goto cleanup;
ret->name = name;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (vol)
virStorageVolFree(vol);
return rv;
}
static int remoteDispatchStorageVolGetXMLDesc(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_storage_vol_get_xml_desc_args *args,
remote_storage_vol_get_xml_desc_ret *ret);
static int remoteDispatchStorageVolGetXMLDescHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchStorageVolGetXMLDesc(server, client, msg, rerr, args, ret);
}
static int remoteDispatchStorageVolGetXMLDesc(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_storage_vol_get_xml_desc_args *args,
remote_storage_vol_get_xml_desc_ret *ret)
{
int rv = -1;
virStorageVolPtr vol = NULL;
char *xml;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(vol = get_nonnull_storage_vol(priv->conn, args->vol)))
goto cleanup;
if ((xml = virStorageVolGetXMLDesc(vol, args->flags)) == NULL)
goto cleanup;
ret->xml = xml;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (vol)
virStorageVolFree(vol);
return rv;
}
static int remoteDispatchStorageVolLookupByKey(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_storage_vol_lookup_by_key_args *args,
remote_storage_vol_lookup_by_key_ret *ret);
static int remoteDispatchStorageVolLookupByKeyHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchStorageVolLookupByKey(server, client, msg, rerr, args, ret);
}
static int remoteDispatchStorageVolLookupByKey(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_storage_vol_lookup_by_key_args *args,
remote_storage_vol_lookup_by_key_ret *ret)
{
int rv = -1;
virStorageVolPtr vol = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if ((vol = virStorageVolLookupByKey(priv->conn, args->key)) == NULL)
goto cleanup;
make_nonnull_storage_vol(&ret->vol, vol);
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (vol)
virStorageVolFree(vol);
return rv;
}
static int remoteDispatchStorageVolLookupByName(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_storage_vol_lookup_by_name_args *args,
remote_storage_vol_lookup_by_name_ret *ret);
static int remoteDispatchStorageVolLookupByNameHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchStorageVolLookupByName(server, client, msg, rerr, args, ret);
}
static int remoteDispatchStorageVolLookupByName(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_storage_vol_lookup_by_name_args *args,
remote_storage_vol_lookup_by_name_ret *ret)
{
int rv = -1;
virStoragePoolPtr pool = NULL;
virStorageVolPtr vol = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(pool = get_nonnull_storage_pool(priv->conn, args->pool)))
goto cleanup;
if ((vol = virStorageVolLookupByName(pool, args->name)) == NULL)
goto cleanup;
make_nonnull_storage_vol(&ret->vol, vol);
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (pool)
virStoragePoolFree(pool);
if (vol)
virStorageVolFree(vol);
return rv;
}
static int remoteDispatchStorageVolLookupByPath(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_storage_vol_lookup_by_path_args *args,
remote_storage_vol_lookup_by_path_ret *ret);
static int remoteDispatchStorageVolLookupByPathHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchStorageVolLookupByPath(server, client, msg, rerr, args, ret);
}
static int remoteDispatchStorageVolLookupByPath(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_storage_vol_lookup_by_path_args *args,
remote_storage_vol_lookup_by_path_ret *ret)
{
int rv = -1;
virStorageVolPtr vol = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if ((vol = virStorageVolLookupByPath(priv->conn, args->path)) == NULL)
goto cleanup;
make_nonnull_storage_vol(&ret->vol, vol);
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (vol)
virStorageVolFree(vol);
return rv;
}
static int remoteDispatchStorageVolResize(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_storage_vol_resize_args *args);
static int remoteDispatchStorageVolResizeHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchStorageVolResize(server, client, msg, rerr, args);
}
static int remoteDispatchStorageVolResize(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_storage_vol_resize_args *args)
{
int rv = -1;
virStorageVolPtr vol = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(vol = get_nonnull_storage_vol(priv->conn, args->vol)))
goto cleanup;
if (virStorageVolResize(vol, args->capacity, args->flags) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (vol)
virStorageVolFree(vol);
return rv;
}
static int remoteDispatchStorageVolUpload(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_storage_vol_upload_args *args);
static int remoteDispatchStorageVolUploadHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchStorageVolUpload(server, client, msg, rerr, args);
}
static int remoteDispatchStorageVolUpload(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_storage_vol_upload_args *args)
{
int rv = -1;
virStorageVolPtr vol = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
virStreamPtr st = NULL;
daemonClientStreamPtr stream = NULL;
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(vol = get_nonnull_storage_vol(priv->conn, args->vol)))
goto cleanup;
if (!(st = virStreamNew(priv->conn, VIR_STREAM_NONBLOCK)))
goto cleanup;
if (!(stream = daemonCreateClientStream(client, st, remoteProgram, &msg->header)))
goto cleanup;
if (virStorageVolUpload(vol, st, args->offset, args->length, args->flags) < 0)
goto cleanup;
if (daemonAddClientStream(client, stream, false) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0) {
virNetMessageSaveError(rerr);
if (stream) {
virStreamAbort(st);
daemonFreeClientStream(client, stream);
} else {
virStreamFree(st);
}
}
if (vol)
virStorageVolFree(vol);
return rv;
}
static int remoteDispatchStorageVolWipe(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_storage_vol_wipe_args *args);
static int remoteDispatchStorageVolWipeHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchStorageVolWipe(server, client, msg, rerr, args);
}
static int remoteDispatchStorageVolWipe(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_storage_vol_wipe_args *args)
{
int rv = -1;
virStorageVolPtr vol = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(vol = get_nonnull_storage_vol(priv->conn, args->vol)))
goto cleanup;
if (virStorageVolWipe(vol, args->flags) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (vol)
virStorageVolFree(vol);
return rv;
}
static int remoteDispatchStorageVolWipePattern(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
remote_storage_vol_wipe_pattern_args *args);
static int remoteDispatchStorageVolWipePatternHelper(
virNetServerPtr server,
virNetServerClientPtr client,
virNetMessagePtr msg,
virNetMessageErrorPtr rerr,
void *args,
void *ret ATTRIBUTE_UNUSED)
{
VIR_DEBUG("server=%p client=%p msg=%p rerr=%p args=%p ret=%p", server, client, msg, rerr, args, ret);
return remoteDispatchStorageVolWipePattern(server, client, msg, rerr, args);
}
static int remoteDispatchStorageVolWipePattern(
virNetServerPtr server ATTRIBUTE_UNUSED,
virNetServerClientPtr client,
virNetMessagePtr msg ATTRIBUTE_UNUSED,
virNetMessageErrorPtr rerr,
remote_storage_vol_wipe_pattern_args *args)
{
int rv = -1;
virStorageVolPtr vol = NULL;
struct daemonClientPrivate *priv =
virNetServerClientGetPrivateData(client);
if (!priv->conn) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("connection not open"));
goto cleanup;
}
if (!(vol = get_nonnull_storage_vol(priv->conn, args->vol)))
goto cleanup;
if (virStorageVolWipePattern(vol, args->algorithm, args->flags) < 0)
goto cleanup;
rv = 0;
cleanup:
if (rv < 0)
virNetMessageSaveError(rerr);
if (vol)
virStorageVolFree(vol);
return rv;
}
virNetServerProgramProc remoteProcs[] = {
{ /* Unused 0 */
NULL,
0,
(xdrproc_t)xdr_void,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method ConnectOpen => 1 */
remoteDispatchConnectOpenHelper,
sizeof(remote_connect_open_args),
(xdrproc_t)xdr_remote_connect_open_args,
0,
(xdrproc_t)xdr_void,
true,
1
},
{ /* Method ConnectClose => 2 */
remoteDispatchConnectCloseHelper,
0,
(xdrproc_t)xdr_void,
0,
(xdrproc_t)xdr_void,
true,
1
},
{ /* Method ConnectGetType => 3 */
remoteDispatchConnectGetTypeHelper,
0,
(xdrproc_t)xdr_void,
sizeof(remote_connect_get_type_ret),
(xdrproc_t)xdr_remote_connect_get_type_ret,
true,
1
},
{ /* Method ConnectGetVersion => 4 */
remoteDispatchConnectGetVersionHelper,
0,
(xdrproc_t)xdr_void,
sizeof(remote_connect_get_version_ret),
(xdrproc_t)xdr_remote_connect_get_version_ret,
true,
1
},
{ /* Method ConnectGetMaxVcpus => 5 */
remoteDispatchConnectGetMaxVcpusHelper,
sizeof(remote_connect_get_max_vcpus_args),
(xdrproc_t)xdr_remote_connect_get_max_vcpus_args,
sizeof(remote_connect_get_max_vcpus_ret),
(xdrproc_t)xdr_remote_connect_get_max_vcpus_ret,
true,
1
},
{ /* Method NodeGetInfo => 6 */
remoteDispatchNodeGetInfoHelper,
0,
(xdrproc_t)xdr_void,
sizeof(remote_node_get_info_ret),
(xdrproc_t)xdr_remote_node_get_info_ret,
true,
1
},
{ /* Method ConnectGetCapabilities => 7 */
remoteDispatchConnectGetCapabilitiesHelper,
0,
(xdrproc_t)xdr_void,
sizeof(remote_connect_get_capabilities_ret),
(xdrproc_t)xdr_remote_connect_get_capabilities_ret,
true,
0
},
{ /* Method DomainAttachDevice => 8 */
remoteDispatchDomainAttachDeviceHelper,
sizeof(remote_domain_attach_device_args),
(xdrproc_t)xdr_remote_domain_attach_device_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method DomainCreate => 9 */
remoteDispatchDomainCreateHelper,
sizeof(remote_domain_create_args),
(xdrproc_t)xdr_remote_domain_create_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method DomainCreateXML => 10 */
remoteDispatchDomainCreateXMLHelper,
sizeof(remote_domain_create_xml_args),
(xdrproc_t)xdr_remote_domain_create_xml_args,
sizeof(remote_domain_create_xml_ret),
(xdrproc_t)xdr_remote_domain_create_xml_ret,
true,
0
},
{ /* Method DomainDefineXML => 11 */
remoteDispatchDomainDefineXMLHelper,
sizeof(remote_domain_define_xml_args),
(xdrproc_t)xdr_remote_domain_define_xml_args,
sizeof(remote_domain_define_xml_ret),
(xdrproc_t)xdr_remote_domain_define_xml_ret,
true,
1
},
{ /* Method DomainDestroy => 12 */
remoteDispatchDomainDestroyHelper,
sizeof(remote_domain_destroy_args),
(xdrproc_t)xdr_remote_domain_destroy_args,
0,
(xdrproc_t)xdr_void,
true,
1
},
{ /* Method DomainDetachDevice => 13 */
remoteDispatchDomainDetachDeviceHelper,
sizeof(remote_domain_detach_device_args),
(xdrproc_t)xdr_remote_domain_detach_device_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method DomainGetXMLDesc => 14 */
remoteDispatchDomainGetXMLDescHelper,
sizeof(remote_domain_get_xml_desc_args),
(xdrproc_t)xdr_remote_domain_get_xml_desc_args,
sizeof(remote_domain_get_xml_desc_ret),
(xdrproc_t)xdr_remote_domain_get_xml_desc_ret,
true,
0
},
{ /* Method DomainGetAutostart => 15 */
remoteDispatchDomainGetAutostartHelper,
sizeof(remote_domain_get_autostart_args),
(xdrproc_t)xdr_remote_domain_get_autostart_args,
sizeof(remote_domain_get_autostart_ret),
(xdrproc_t)xdr_remote_domain_get_autostart_ret,
true,
1
},
{ /* Method DomainGetInfo => 16 */
remoteDispatchDomainGetInfoHelper,
sizeof(remote_domain_get_info_args),
(xdrproc_t)xdr_remote_domain_get_info_args,
sizeof(remote_domain_get_info_ret),
(xdrproc_t)xdr_remote_domain_get_info_ret,
true,
0
},
{ /* Method DomainGetMaxMemory => 17 */
remoteDispatchDomainGetMaxMemoryHelper,
sizeof(remote_domain_get_max_memory_args),
(xdrproc_t)xdr_remote_domain_get_max_memory_args,
sizeof(remote_domain_get_max_memory_ret),
(xdrproc_t)xdr_remote_domain_get_max_memory_ret,
true,
1
},
{ /* Method DomainGetMaxVcpus => 18 */
remoteDispatchDomainGetMaxVcpusHelper,
sizeof(remote_domain_get_max_vcpus_args),
(xdrproc_t)xdr_remote_domain_get_max_vcpus_args,
sizeof(remote_domain_get_max_vcpus_ret),
(xdrproc_t)xdr_remote_domain_get_max_vcpus_ret,
true,
1
},
{ /* Method DomainGetOSType => 19 */
remoteDispatchDomainGetOSTypeHelper,
sizeof(remote_domain_get_os_type_args),
(xdrproc_t)xdr_remote_domain_get_os_type_args,
sizeof(remote_domain_get_os_type_ret),
(xdrproc_t)xdr_remote_domain_get_os_type_ret,
true,
1
},
{ /* Method DomainGetVcpus => 20 */
remoteDispatchDomainGetVcpusHelper,
sizeof(remote_domain_get_vcpus_args),
(xdrproc_t)xdr_remote_domain_get_vcpus_args,
sizeof(remote_domain_get_vcpus_ret),
(xdrproc_t)xdr_remote_domain_get_vcpus_ret,
true,
1
},
{ /* Method ConnectListDefinedDomains => 21 */
remoteDispatchConnectListDefinedDomainsHelper,
sizeof(remote_connect_list_defined_domains_args),
(xdrproc_t)xdr_remote_connect_list_defined_domains_args,
sizeof(remote_connect_list_defined_domains_ret),
(xdrproc_t)xdr_remote_connect_list_defined_domains_ret,
true,
1
},
{ /* Method DomainLookupByID => 22 */
remoteDispatchDomainLookupByIDHelper,
sizeof(remote_domain_lookup_by_id_args),
(xdrproc_t)xdr_remote_domain_lookup_by_id_args,
sizeof(remote_domain_lookup_by_id_ret),
(xdrproc_t)xdr_remote_domain_lookup_by_id_ret,
true,
1
},
{ /* Method DomainLookupByName => 23 */
remoteDispatchDomainLookupByNameHelper,
sizeof(remote_domain_lookup_by_name_args),
(xdrproc_t)xdr_remote_domain_lookup_by_name_args,
sizeof(remote_domain_lookup_by_name_ret),
(xdrproc_t)xdr_remote_domain_lookup_by_name_ret,
true,
1
},
{ /* Method DomainLookupByUUID => 24 */
remoteDispatchDomainLookupByUUIDHelper,
sizeof(remote_domain_lookup_by_uuid_args),
(xdrproc_t)xdr_remote_domain_lookup_by_uuid_args,
sizeof(remote_domain_lookup_by_uuid_ret),
(xdrproc_t)xdr_remote_domain_lookup_by_uuid_ret,
true,
1
},
{ /* Method ConnectNumOfDefinedDomains => 25 */
remoteDispatchConnectNumOfDefinedDomainsHelper,
0,
(xdrproc_t)xdr_void,
sizeof(remote_connect_num_of_defined_domains_ret),
(xdrproc_t)xdr_remote_connect_num_of_defined_domains_ret,
true,
1
},
{ /* Method DomainPinVcpu => 26 */
remoteDispatchDomainPinVcpuHelper,
sizeof(remote_domain_pin_vcpu_args),
(xdrproc_t)xdr_remote_domain_pin_vcpu_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method DomainReboot => 27 */
remoteDispatchDomainRebootHelper,
sizeof(remote_domain_reboot_args),
(xdrproc_t)xdr_remote_domain_reboot_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method DomainResume => 28 */
remoteDispatchDomainResumeHelper,
sizeof(remote_domain_resume_args),
(xdrproc_t)xdr_remote_domain_resume_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method DomainSetAutostart => 29 */
remoteDispatchDomainSetAutostartHelper,
sizeof(remote_domain_set_autostart_args),
(xdrproc_t)xdr_remote_domain_set_autostart_args,
0,
(xdrproc_t)xdr_void,
true,
1
},
{ /* Method DomainSetMaxMemory => 30 */
remoteDispatchDomainSetMaxMemoryHelper,
sizeof(remote_domain_set_max_memory_args),
(xdrproc_t)xdr_remote_domain_set_max_memory_args,
0,
(xdrproc_t)xdr_void,
true,
1
},
{ /* Method DomainSetMemory => 31 */
remoteDispatchDomainSetMemoryHelper,
sizeof(remote_domain_set_memory_args),
(xdrproc_t)xdr_remote_domain_set_memory_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method DomainSetVcpus => 32 */
remoteDispatchDomainSetVcpusHelper,
sizeof(remote_domain_set_vcpus_args),
(xdrproc_t)xdr_remote_domain_set_vcpus_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method DomainShutdown => 33 */
remoteDispatchDomainShutdownHelper,
sizeof(remote_domain_shutdown_args),
(xdrproc_t)xdr_remote_domain_shutdown_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method DomainSuspend => 34 */
remoteDispatchDomainSuspendHelper,
sizeof(remote_domain_suspend_args),
(xdrproc_t)xdr_remote_domain_suspend_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method DomainUndefine => 35 */
remoteDispatchDomainUndefineHelper,
sizeof(remote_domain_undefine_args),
(xdrproc_t)xdr_remote_domain_undefine_args,
0,
(xdrproc_t)xdr_void,
true,
1
},
{ /* Method ConnectListDefinedNetworks => 36 */
remoteDispatchConnectListDefinedNetworksHelper,
sizeof(remote_connect_list_defined_networks_args),
(xdrproc_t)xdr_remote_connect_list_defined_networks_args,
sizeof(remote_connect_list_defined_networks_ret),
(xdrproc_t)xdr_remote_connect_list_defined_networks_ret,
true,
1
},
{ /* Method ConnectListDomains => 37 */
remoteDispatchConnectListDomainsHelper,
sizeof(remote_connect_list_domains_args),
(xdrproc_t)xdr_remote_connect_list_domains_args,
sizeof(remote_connect_list_domains_ret),
(xdrproc_t)xdr_remote_connect_list_domains_ret,
true,
1
},
{ /* Method ConnectListNetworks => 38 */
remoteDispatchConnectListNetworksHelper,
sizeof(remote_connect_list_networks_args),
(xdrproc_t)xdr_remote_connect_list_networks_args,
sizeof(remote_connect_list_networks_ret),
(xdrproc_t)xdr_remote_connect_list_networks_ret,
true,
1
},
{ /* Method NetworkCreate => 39 */
remoteDispatchNetworkCreateHelper,
sizeof(remote_network_create_args),
(xdrproc_t)xdr_remote_network_create_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method NetworkCreateXML => 40 */
remoteDispatchNetworkCreateXMLHelper,
sizeof(remote_network_create_xml_args),
(xdrproc_t)xdr_remote_network_create_xml_args,
sizeof(remote_network_create_xml_ret),
(xdrproc_t)xdr_remote_network_create_xml_ret,
true,
0
},
{ /* Method NetworkDefineXML => 41 */
remoteDispatchNetworkDefineXMLHelper,
sizeof(remote_network_define_xml_args),
(xdrproc_t)xdr_remote_network_define_xml_args,
sizeof(remote_network_define_xml_ret),
(xdrproc_t)xdr_remote_network_define_xml_ret,
true,
1
},
{ /* Method NetworkDestroy => 42 */
remoteDispatchNetworkDestroyHelper,
sizeof(remote_network_destroy_args),
(xdrproc_t)xdr_remote_network_destroy_args,
0,
(xdrproc_t)xdr_void,
true,
1
},
{ /* Method NetworkGetXMLDesc => 43 */
remoteDispatchNetworkGetXMLDescHelper,
sizeof(remote_network_get_xml_desc_args),
(xdrproc_t)xdr_remote_network_get_xml_desc_args,
sizeof(remote_network_get_xml_desc_ret),
(xdrproc_t)xdr_remote_network_get_xml_desc_ret,
true,
1
},
{ /* Method NetworkGetAutostart => 44 */
remoteDispatchNetworkGetAutostartHelper,
sizeof(remote_network_get_autostart_args),
(xdrproc_t)xdr_remote_network_get_autostart_args,
sizeof(remote_network_get_autostart_ret),
(xdrproc_t)xdr_remote_network_get_autostart_ret,
true,
1
},
{ /* Method NetworkGetBridgeName => 45 */
remoteDispatchNetworkGetBridgeNameHelper,
sizeof(remote_network_get_bridge_name_args),
(xdrproc_t)xdr_remote_network_get_bridge_name_args,
sizeof(remote_network_get_bridge_name_ret),
(xdrproc_t)xdr_remote_network_get_bridge_name_ret,
true,
1
},
{ /* Method NetworkLookupByName => 46 */
remoteDispatchNetworkLookupByNameHelper,
sizeof(remote_network_lookup_by_name_args),
(xdrproc_t)xdr_remote_network_lookup_by_name_args,
sizeof(remote_network_lookup_by_name_ret),
(xdrproc_t)xdr_remote_network_lookup_by_name_ret,
true,
1
},
{ /* Method NetworkLookupByUUID => 47 */
remoteDispatchNetworkLookupByUUIDHelper,
sizeof(remote_network_lookup_by_uuid_args),
(xdrproc_t)xdr_remote_network_lookup_by_uuid_args,
sizeof(remote_network_lookup_by_uuid_ret),
(xdrproc_t)xdr_remote_network_lookup_by_uuid_ret,
true,
1
},
{ /* Method NetworkSetAutostart => 48 */
remoteDispatchNetworkSetAutostartHelper,
sizeof(remote_network_set_autostart_args),
(xdrproc_t)xdr_remote_network_set_autostart_args,
0,
(xdrproc_t)xdr_void,
true,
1
},
{ /* Method NetworkUndefine => 49 */
remoteDispatchNetworkUndefineHelper,
sizeof(remote_network_undefine_args),
(xdrproc_t)xdr_remote_network_undefine_args,
0,
(xdrproc_t)xdr_void,
true,
1
},
{ /* Method ConnectNumOfDefinedNetworks => 50 */
remoteDispatchConnectNumOfDefinedNetworksHelper,
0,
(xdrproc_t)xdr_void,
sizeof(remote_connect_num_of_defined_networks_ret),
(xdrproc_t)xdr_remote_connect_num_of_defined_networks_ret,
true,
1
},
{ /* Method ConnectNumOfDomains => 51 */
remoteDispatchConnectNumOfDomainsHelper,
0,
(xdrproc_t)xdr_void,
sizeof(remote_connect_num_of_domains_ret),
(xdrproc_t)xdr_remote_connect_num_of_domains_ret,
true,
1
},
{ /* Method ConnectNumOfNetworks => 52 */
remoteDispatchConnectNumOfNetworksHelper,
0,
(xdrproc_t)xdr_void,
sizeof(remote_connect_num_of_networks_ret),
(xdrproc_t)xdr_remote_connect_num_of_networks_ret,
true,
1
},
{ /* Method DomainCoreDump => 53 */
remoteDispatchDomainCoreDumpHelper,
sizeof(remote_domain_core_dump_args),
(xdrproc_t)xdr_remote_domain_core_dump_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method DomainRestore => 54 */
remoteDispatchDomainRestoreHelper,
sizeof(remote_domain_restore_args),
(xdrproc_t)xdr_remote_domain_restore_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method DomainSave => 55 */
remoteDispatchDomainSaveHelper,
sizeof(remote_domain_save_args),
(xdrproc_t)xdr_remote_domain_save_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method DomainGetSchedulerType => 56 */
remoteDispatchDomainGetSchedulerTypeHelper,
sizeof(remote_domain_get_scheduler_type_args),
(xdrproc_t)xdr_remote_domain_get_scheduler_type_args,
sizeof(remote_domain_get_scheduler_type_ret),
(xdrproc_t)xdr_remote_domain_get_scheduler_type_ret,
true,
0
},
{ /* Method DomainGetSchedulerParameters => 57 */
remoteDispatchDomainGetSchedulerParametersHelper,
sizeof(remote_domain_get_scheduler_parameters_args),
(xdrproc_t)xdr_remote_domain_get_scheduler_parameters_args,
sizeof(remote_domain_get_scheduler_parameters_ret),
(xdrproc_t)xdr_remote_domain_get_scheduler_parameters_ret,
true,
0
},
{ /* Method DomainSetSchedulerParameters => 58 */
remoteDispatchDomainSetSchedulerParametersHelper,
sizeof(remote_domain_set_scheduler_parameters_args),
(xdrproc_t)xdr_remote_domain_set_scheduler_parameters_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method ConnectGetHostname => 59 */
remoteDispatchConnectGetHostnameHelper,
0,
(xdrproc_t)xdr_void,
sizeof(remote_connect_get_hostname_ret),
(xdrproc_t)xdr_remote_connect_get_hostname_ret,
true,
1
},
{ /* Method ConnectSupportsFeature => 60 */
remoteDispatchConnectSupportsFeatureHelper,
sizeof(remote_connect_supports_feature_args),
(xdrproc_t)xdr_remote_connect_supports_feature_args,
sizeof(remote_connect_supports_feature_ret),
(xdrproc_t)xdr_remote_connect_supports_feature_ret,
true,
1
},
{ /* Method DomainMigratePrepare => 61 */
remoteDispatchDomainMigratePrepareHelper,
sizeof(remote_domain_migrate_prepare_args),
(xdrproc_t)xdr_remote_domain_migrate_prepare_args,
sizeof(remote_domain_migrate_prepare_ret),
(xdrproc_t)xdr_remote_domain_migrate_prepare_ret,
true,
0
},
{ /* Method DomainMigratePerform => 62 */
remoteDispatchDomainMigratePerformHelper,
sizeof(remote_domain_migrate_perform_args),
(xdrproc_t)xdr_remote_domain_migrate_perform_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method DomainMigrateFinish => 63 */
remoteDispatchDomainMigrateFinishHelper,
sizeof(remote_domain_migrate_finish_args),
(xdrproc_t)xdr_remote_domain_migrate_finish_args,
sizeof(remote_domain_migrate_finish_ret),
(xdrproc_t)xdr_remote_domain_migrate_finish_ret,
true,
0
},
{ /* Method DomainBlockStats => 64 */
remoteDispatchDomainBlockStatsHelper,
sizeof(remote_domain_block_stats_args),
(xdrproc_t)xdr_remote_domain_block_stats_args,
sizeof(remote_domain_block_stats_ret),
(xdrproc_t)xdr_remote_domain_block_stats_ret,
true,
0
},
{ /* Method DomainInterfaceStats => 65 */
remoteDispatchDomainInterfaceStatsHelper,
sizeof(remote_domain_interface_stats_args),
(xdrproc_t)xdr_remote_domain_interface_stats_args,
sizeof(remote_domain_interface_stats_ret),
(xdrproc_t)xdr_remote_domain_interface_stats_ret,
true,
1
},
{ /* Method AuthList => 66 */
remoteDispatchAuthListHelper,
0,
(xdrproc_t)xdr_void,
sizeof(remote_auth_list_ret),
(xdrproc_t)xdr_remote_auth_list_ret,
true,
1
},
{ /* Method AuthSaslInit => 67 */
remoteDispatchAuthSaslInitHelper,
0,
(xdrproc_t)xdr_void,
sizeof(remote_auth_sasl_init_ret),
(xdrproc_t)xdr_remote_auth_sasl_init_ret,
true,
1
},
{ /* Method AuthSaslStart => 68 */
remoteDispatchAuthSaslStartHelper,
sizeof(remote_auth_sasl_start_args),
(xdrproc_t)xdr_remote_auth_sasl_start_args,
sizeof(remote_auth_sasl_start_ret),
(xdrproc_t)xdr_remote_auth_sasl_start_ret,
true,
1
},
{ /* Method AuthSaslStep => 69 */
remoteDispatchAuthSaslStepHelper,
sizeof(remote_auth_sasl_step_args),
(xdrproc_t)xdr_remote_auth_sasl_step_args,
sizeof(remote_auth_sasl_step_ret),
(xdrproc_t)xdr_remote_auth_sasl_step_ret,
true,
1
},
{ /* Method AuthPolkit => 70 */
remoteDispatchAuthPolkitHelper,
0,
(xdrproc_t)xdr_void,
sizeof(remote_auth_polkit_ret),
(xdrproc_t)xdr_remote_auth_polkit_ret,
true,
1
},
{ /* Method ConnectNumOfStoragePools => 71 */
remoteDispatchConnectNumOfStoragePoolsHelper,
0,
(xdrproc_t)xdr_void,
sizeof(remote_connect_num_of_storage_pools_ret),
(xdrproc_t)xdr_remote_connect_num_of_storage_pools_ret,
true,
1
},
{ /* Method ConnectListStoragePools => 72 */
remoteDispatchConnectListStoragePoolsHelper,
sizeof(remote_connect_list_storage_pools_args),
(xdrproc_t)xdr_remote_connect_list_storage_pools_args,
sizeof(remote_connect_list_storage_pools_ret),
(xdrproc_t)xdr_remote_connect_list_storage_pools_ret,
true,
1
},
{ /* Method ConnectNumOfDefinedStoragePools => 73 */
remoteDispatchConnectNumOfDefinedStoragePoolsHelper,
0,
(xdrproc_t)xdr_void,
sizeof(remote_connect_num_of_defined_storage_pools_ret),
(xdrproc_t)xdr_remote_connect_num_of_defined_storage_pools_ret,
true,
1
},
{ /* Method ConnectListDefinedStoragePools => 74 */
remoteDispatchConnectListDefinedStoragePoolsHelper,
sizeof(remote_connect_list_defined_storage_pools_args),
(xdrproc_t)xdr_remote_connect_list_defined_storage_pools_args,
sizeof(remote_connect_list_defined_storage_pools_ret),
(xdrproc_t)xdr_remote_connect_list_defined_storage_pools_ret,
true,
1
},
{ /* Method ConnectFindStoragePoolSources => 75 */
remoteDispatchConnectFindStoragePoolSourcesHelper,
sizeof(remote_connect_find_storage_pool_sources_args),
(xdrproc_t)xdr_remote_connect_find_storage_pool_sources_args,
sizeof(remote_connect_find_storage_pool_sources_ret),
(xdrproc_t)xdr_remote_connect_find_storage_pool_sources_ret,
true,
0
},
{ /* Method StoragePoolCreateXML => 76 */
remoteDispatchStoragePoolCreateXMLHelper,
sizeof(remote_storage_pool_create_xml_args),
(xdrproc_t)xdr_remote_storage_pool_create_xml_args,
sizeof(remote_storage_pool_create_xml_ret),
(xdrproc_t)xdr_remote_storage_pool_create_xml_ret,
true,
0
},
{ /* Method StoragePoolDefineXML => 77 */
remoteDispatchStoragePoolDefineXMLHelper,
sizeof(remote_storage_pool_define_xml_args),
(xdrproc_t)xdr_remote_storage_pool_define_xml_args,
sizeof(remote_storage_pool_define_xml_ret),
(xdrproc_t)xdr_remote_storage_pool_define_xml_ret,
true,
1
},
{ /* Method StoragePoolCreate => 78 */
remoteDispatchStoragePoolCreateHelper,
sizeof(remote_storage_pool_create_args),
(xdrproc_t)xdr_remote_storage_pool_create_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method StoragePoolBuild => 79 */
remoteDispatchStoragePoolBuildHelper,
sizeof(remote_storage_pool_build_args),
(xdrproc_t)xdr_remote_storage_pool_build_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method StoragePoolDestroy => 80 */
remoteDispatchStoragePoolDestroyHelper,
sizeof(remote_storage_pool_destroy_args),
(xdrproc_t)xdr_remote_storage_pool_destroy_args,
0,
(xdrproc_t)xdr_void,
true,
1
},
{ /* Method StoragePoolDelete => 81 */
remoteDispatchStoragePoolDeleteHelper,
sizeof(remote_storage_pool_delete_args),
(xdrproc_t)xdr_remote_storage_pool_delete_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method StoragePoolUndefine => 82 */
remoteDispatchStoragePoolUndefineHelper,
sizeof(remote_storage_pool_undefine_args),
(xdrproc_t)xdr_remote_storage_pool_undefine_args,
0,
(xdrproc_t)xdr_void,
true,
1
},
{ /* Method StoragePoolRefresh => 83 */
remoteDispatchStoragePoolRefreshHelper,
sizeof(remote_storage_pool_refresh_args),
(xdrproc_t)xdr_remote_storage_pool_refresh_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method StoragePoolLookupByName => 84 */
remoteDispatchStoragePoolLookupByNameHelper,
sizeof(remote_storage_pool_lookup_by_name_args),
(xdrproc_t)xdr_remote_storage_pool_lookup_by_name_args,
sizeof(remote_storage_pool_lookup_by_name_ret),
(xdrproc_t)xdr_remote_storage_pool_lookup_by_name_ret,
true,
1
},
{ /* Method StoragePoolLookupByUUID => 85 */
remoteDispatchStoragePoolLookupByUUIDHelper,
sizeof(remote_storage_pool_lookup_by_uuid_args),
(xdrproc_t)xdr_remote_storage_pool_lookup_by_uuid_args,
sizeof(remote_storage_pool_lookup_by_uuid_ret),
(xdrproc_t)xdr_remote_storage_pool_lookup_by_uuid_ret,
true,
1
},
{ /* Method StoragePoolLookupByVolume => 86 */
remoteDispatchStoragePoolLookupByVolumeHelper,
sizeof(remote_storage_pool_lookup_by_volume_args),
(xdrproc_t)xdr_remote_storage_pool_lookup_by_volume_args,
sizeof(remote_storage_pool_lookup_by_volume_ret),
(xdrproc_t)xdr_remote_storage_pool_lookup_by_volume_ret,
true,
1
},
{ /* Method StoragePoolGetInfo => 87 */
remoteDispatchStoragePoolGetInfoHelper,
sizeof(remote_storage_pool_get_info_args),
(xdrproc_t)xdr_remote_storage_pool_get_info_args,
sizeof(remote_storage_pool_get_info_ret),
(xdrproc_t)xdr_remote_storage_pool_get_info_ret,
true,
1
},
{ /* Method StoragePoolGetXMLDesc => 88 */
remoteDispatchStoragePoolGetXMLDescHelper,
sizeof(remote_storage_pool_get_xml_desc_args),
(xdrproc_t)xdr_remote_storage_pool_get_xml_desc_args,
sizeof(remote_storage_pool_get_xml_desc_ret),
(xdrproc_t)xdr_remote_storage_pool_get_xml_desc_ret,
true,
1
},
{ /* Method StoragePoolGetAutostart => 89 */
remoteDispatchStoragePoolGetAutostartHelper,
sizeof(remote_storage_pool_get_autostart_args),
(xdrproc_t)xdr_remote_storage_pool_get_autostart_args,
sizeof(remote_storage_pool_get_autostart_ret),
(xdrproc_t)xdr_remote_storage_pool_get_autostart_ret,
true,
1
},
{ /* Method StoragePoolSetAutostart => 90 */
remoteDispatchStoragePoolSetAutostartHelper,
sizeof(remote_storage_pool_set_autostart_args),
(xdrproc_t)xdr_remote_storage_pool_set_autostart_args,
0,
(xdrproc_t)xdr_void,
true,
1
},
{ /* Method StoragePoolNumOfVolumes => 91 */
remoteDispatchStoragePoolNumOfVolumesHelper,
sizeof(remote_storage_pool_num_of_volumes_args),
(xdrproc_t)xdr_remote_storage_pool_num_of_volumes_args,
sizeof(remote_storage_pool_num_of_volumes_ret),
(xdrproc_t)xdr_remote_storage_pool_num_of_volumes_ret,
true,
1
},
{ /* Method StoragePoolListVolumes => 92 */
remoteDispatchStoragePoolListVolumesHelper,
sizeof(remote_storage_pool_list_volumes_args),
(xdrproc_t)xdr_remote_storage_pool_list_volumes_args,
sizeof(remote_storage_pool_list_volumes_ret),
(xdrproc_t)xdr_remote_storage_pool_list_volumes_ret,
true,
1
},
{ /* Method StorageVolCreateXML => 93 */
remoteDispatchStorageVolCreateXMLHelper,
sizeof(remote_storage_vol_create_xml_args),
(xdrproc_t)xdr_remote_storage_vol_create_xml_args,
sizeof(remote_storage_vol_create_xml_ret),
(xdrproc_t)xdr_remote_storage_vol_create_xml_ret,
true,
0
},
{ /* Method StorageVolDelete => 94 */
remoteDispatchStorageVolDeleteHelper,
sizeof(remote_storage_vol_delete_args),
(xdrproc_t)xdr_remote_storage_vol_delete_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method StorageVolLookupByName => 95 */
remoteDispatchStorageVolLookupByNameHelper,
sizeof(remote_storage_vol_lookup_by_name_args),
(xdrproc_t)xdr_remote_storage_vol_lookup_by_name_args,
sizeof(remote_storage_vol_lookup_by_name_ret),
(xdrproc_t)xdr_remote_storage_vol_lookup_by_name_ret,
true,
1
},
{ /* Method StorageVolLookupByKey => 96 */
remoteDispatchStorageVolLookupByKeyHelper,
sizeof(remote_storage_vol_lookup_by_key_args),
(xdrproc_t)xdr_remote_storage_vol_lookup_by_key_args,
sizeof(remote_storage_vol_lookup_by_key_ret),
(xdrproc_t)xdr_remote_storage_vol_lookup_by_key_ret,
true,
1
},
{ /* Method StorageVolLookupByPath => 97 */
remoteDispatchStorageVolLookupByPathHelper,
sizeof(remote_storage_vol_lookup_by_path_args),
(xdrproc_t)xdr_remote_storage_vol_lookup_by_path_args,
sizeof(remote_storage_vol_lookup_by_path_ret),
(xdrproc_t)xdr_remote_storage_vol_lookup_by_path_ret,
true,
1
},
{ /* Method StorageVolGetInfo => 98 */
remoteDispatchStorageVolGetInfoHelper,
sizeof(remote_storage_vol_get_info_args),
(xdrproc_t)xdr_remote_storage_vol_get_info_args,
sizeof(remote_storage_vol_get_info_ret),
(xdrproc_t)xdr_remote_storage_vol_get_info_ret,
true,
1
},
{ /* Method StorageVolGetXMLDesc => 99 */
remoteDispatchStorageVolGetXMLDescHelper,
sizeof(remote_storage_vol_get_xml_desc_args),
(xdrproc_t)xdr_remote_storage_vol_get_xml_desc_args,
sizeof(remote_storage_vol_get_xml_desc_ret),
(xdrproc_t)xdr_remote_storage_vol_get_xml_desc_ret,
true,
1
},
{ /* Method StorageVolGetPath => 100 */
remoteDispatchStorageVolGetPathHelper,
sizeof(remote_storage_vol_get_path_args),
(xdrproc_t)xdr_remote_storage_vol_get_path_args,
sizeof(remote_storage_vol_get_path_ret),
(xdrproc_t)xdr_remote_storage_vol_get_path_ret,
true,
1
},
{ /* Method NodeGetCellsFreeMemory => 101 */
remoteDispatchNodeGetCellsFreeMemoryHelper,
sizeof(remote_node_get_cells_free_memory_args),
(xdrproc_t)xdr_remote_node_get_cells_free_memory_args,
sizeof(remote_node_get_cells_free_memory_ret),
(xdrproc_t)xdr_remote_node_get_cells_free_memory_ret,
true,
1
},
{ /* Method NodeGetFreeMemory => 102 */
remoteDispatchNodeGetFreeMemoryHelper,
0,
(xdrproc_t)xdr_void,
sizeof(remote_node_get_free_memory_ret),
(xdrproc_t)xdr_remote_node_get_free_memory_ret,
true,
1
},
{ /* Method DomainBlockPeek => 103 */
remoteDispatchDomainBlockPeekHelper,
sizeof(remote_domain_block_peek_args),
(xdrproc_t)xdr_remote_domain_block_peek_args,
sizeof(remote_domain_block_peek_ret),
(xdrproc_t)xdr_remote_domain_block_peek_ret,
true,
0
},
{ /* Method DomainMemoryPeek => 104 */
remoteDispatchDomainMemoryPeekHelper,
sizeof(remote_domain_memory_peek_args),
(xdrproc_t)xdr_remote_domain_memory_peek_args,
sizeof(remote_domain_memory_peek_ret),
(xdrproc_t)xdr_remote_domain_memory_peek_ret,
true,
0
},
{ /* Method ConnectDomainEventRegister => 105 */
remoteDispatchConnectDomainEventRegisterHelper,
0,
(xdrproc_t)xdr_void,
sizeof(remote_connect_domain_event_register_ret),
(xdrproc_t)xdr_remote_connect_domain_event_register_ret,
true,
1
},
{ /* Method ConnectDomainEventDeregister => 106 */
remoteDispatchConnectDomainEventDeregisterHelper,
0,
(xdrproc_t)xdr_void,
sizeof(remote_connect_domain_event_deregister_ret),
(xdrproc_t)xdr_remote_connect_domain_event_deregister_ret,
true,
1
},
{ /* Async event DomainEventLifecycle => 107 */
NULL,
0,
(xdrproc_t)xdr_void,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method DomainMigratePrepare2 => 108 */
remoteDispatchDomainMigratePrepare2Helper,
sizeof(remote_domain_migrate_prepare2_args),
(xdrproc_t)xdr_remote_domain_migrate_prepare2_args,
sizeof(remote_domain_migrate_prepare2_ret),
(xdrproc_t)xdr_remote_domain_migrate_prepare2_ret,
true,
0
},
{ /* Method DomainMigrateFinish2 => 109 */
remoteDispatchDomainMigrateFinish2Helper,
sizeof(remote_domain_migrate_finish2_args),
(xdrproc_t)xdr_remote_domain_migrate_finish2_args,
sizeof(remote_domain_migrate_finish2_ret),
(xdrproc_t)xdr_remote_domain_migrate_finish2_ret,
true,
0
},
{ /* Method ConnectGetURI => 110 */
remoteDispatchConnectGetURIHelper,
0,
(xdrproc_t)xdr_void,
sizeof(remote_connect_get_uri_ret),
(xdrproc_t)xdr_remote_connect_get_uri_ret,
true,
1
},
{ /* Method NodeNumOfDevices => 111 */
remoteDispatchNodeNumOfDevicesHelper,
sizeof(remote_node_num_of_devices_args),
(xdrproc_t)xdr_remote_node_num_of_devices_args,
sizeof(remote_node_num_of_devices_ret),
(xdrproc_t)xdr_remote_node_num_of_devices_ret,
true,
1
},
{ /* Method NodeListDevices => 112 */
remoteDispatchNodeListDevicesHelper,
sizeof(remote_node_list_devices_args),
(xdrproc_t)xdr_remote_node_list_devices_args,
sizeof(remote_node_list_devices_ret),
(xdrproc_t)xdr_remote_node_list_devices_ret,
true,
1
},
{ /* Method NodeDeviceLookupByName => 113 */
remoteDispatchNodeDeviceLookupByNameHelper,
sizeof(remote_node_device_lookup_by_name_args),
(xdrproc_t)xdr_remote_node_device_lookup_by_name_args,
sizeof(remote_node_device_lookup_by_name_ret),
(xdrproc_t)xdr_remote_node_device_lookup_by_name_ret,
true,
1
},
{ /* Method NodeDeviceGetXMLDesc => 114 */
remoteDispatchNodeDeviceGetXMLDescHelper,
sizeof(remote_node_device_get_xml_desc_args),
(xdrproc_t)xdr_remote_node_device_get_xml_desc_args,
sizeof(remote_node_device_get_xml_desc_ret),
(xdrproc_t)xdr_remote_node_device_get_xml_desc_ret,
true,
0
},
{ /* Method NodeDeviceGetParent => 115 */
remoteDispatchNodeDeviceGetParentHelper,
sizeof(remote_node_device_get_parent_args),
(xdrproc_t)xdr_remote_node_device_get_parent_args,
sizeof(remote_node_device_get_parent_ret),
(xdrproc_t)xdr_remote_node_device_get_parent_ret,
true,
1
},
{ /* Method NodeDeviceNumOfCaps => 116 */
remoteDispatchNodeDeviceNumOfCapsHelper,
sizeof(remote_node_device_num_of_caps_args),
(xdrproc_t)xdr_remote_node_device_num_of_caps_args,
sizeof(remote_node_device_num_of_caps_ret),
(xdrproc_t)xdr_remote_node_device_num_of_caps_ret,
true,
1
},
{ /* Method NodeDeviceListCaps => 117 */
remoteDispatchNodeDeviceListCapsHelper,
sizeof(remote_node_device_list_caps_args),
(xdrproc_t)xdr_remote_node_device_list_caps_args,
sizeof(remote_node_device_list_caps_ret),
(xdrproc_t)xdr_remote_node_device_list_caps_ret,
true,
1
},
{ /* Method NodeDeviceDettach => 118 */
remoteDispatchNodeDeviceDettachHelper,
sizeof(remote_node_device_dettach_args),
(xdrproc_t)xdr_remote_node_device_dettach_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method NodeDeviceReAttach => 119 */
remoteDispatchNodeDeviceReAttachHelper,
sizeof(remote_node_device_re_attach_args),
(xdrproc_t)xdr_remote_node_device_re_attach_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method NodeDeviceReset => 120 */
remoteDispatchNodeDeviceResetHelper,
sizeof(remote_node_device_reset_args),
(xdrproc_t)xdr_remote_node_device_reset_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method DomainGetSecurityLabel => 121 */
remoteDispatchDomainGetSecurityLabelHelper,
sizeof(remote_domain_get_security_label_args),
(xdrproc_t)xdr_remote_domain_get_security_label_args,
sizeof(remote_domain_get_security_label_ret),
(xdrproc_t)xdr_remote_domain_get_security_label_ret,
true,
1
},
{ /* Method NodeGetSecurityModel => 122 */
remoteDispatchNodeGetSecurityModelHelper,
0,
(xdrproc_t)xdr_void,
sizeof(remote_node_get_security_model_ret),
(xdrproc_t)xdr_remote_node_get_security_model_ret,
true,
1
},
{ /* Method NodeDeviceCreateXML => 123 */
remoteDispatchNodeDeviceCreateXMLHelper,
sizeof(remote_node_device_create_xml_args),
(xdrproc_t)xdr_remote_node_device_create_xml_args,
sizeof(remote_node_device_create_xml_ret),
(xdrproc_t)xdr_remote_node_device_create_xml_ret,
true,
0
},
{ /* Method NodeDeviceDestroy => 124 */
remoteDispatchNodeDeviceDestroyHelper,
sizeof(remote_node_device_destroy_args),
(xdrproc_t)xdr_remote_node_device_destroy_args,
0,
(xdrproc_t)xdr_void,
true,
1
},
{ /* Method StorageVolCreateXMLFrom => 125 */
remoteDispatchStorageVolCreateXMLFromHelper,
sizeof(remote_storage_vol_create_xml_from_args),
(xdrproc_t)xdr_remote_storage_vol_create_xml_from_args,
sizeof(remote_storage_vol_create_xml_from_ret),
(xdrproc_t)xdr_remote_storage_vol_create_xml_from_ret,
true,
0
},
{ /* Method ConnectNumOfInterfaces => 126 */
remoteDispatchConnectNumOfInterfacesHelper,
0,
(xdrproc_t)xdr_void,
sizeof(remote_connect_num_of_interfaces_ret),
(xdrproc_t)xdr_remote_connect_num_of_interfaces_ret,
true,
1
},
{ /* Method ConnectListInterfaces => 127 */
remoteDispatchConnectListInterfacesHelper,
sizeof(remote_connect_list_interfaces_args),
(xdrproc_t)xdr_remote_connect_list_interfaces_args,
sizeof(remote_connect_list_interfaces_ret),
(xdrproc_t)xdr_remote_connect_list_interfaces_ret,
true,
1
},
{ /* Method InterfaceLookupByName => 128 */
remoteDispatchInterfaceLookupByNameHelper,
sizeof(remote_interface_lookup_by_name_args),
(xdrproc_t)xdr_remote_interface_lookup_by_name_args,
sizeof(remote_interface_lookup_by_name_ret),
(xdrproc_t)xdr_remote_interface_lookup_by_name_ret,
true,
1
},
{ /* Method InterfaceLookupByMACString => 129 */
remoteDispatchInterfaceLookupByMACStringHelper,
sizeof(remote_interface_lookup_by_mac_string_args),
(xdrproc_t)xdr_remote_interface_lookup_by_mac_string_args,
sizeof(remote_interface_lookup_by_mac_string_ret),
(xdrproc_t)xdr_remote_interface_lookup_by_mac_string_ret,
true,
1
},
{ /* Method InterfaceGetXMLDesc => 130 */
remoteDispatchInterfaceGetXMLDescHelper,
sizeof(remote_interface_get_xml_desc_args),
(xdrproc_t)xdr_remote_interface_get_xml_desc_args,
sizeof(remote_interface_get_xml_desc_ret),
(xdrproc_t)xdr_remote_interface_get_xml_desc_ret,
true,
0
},
{ /* Method InterfaceDefineXML => 131 */
remoteDispatchInterfaceDefineXMLHelper,
sizeof(remote_interface_define_xml_args),
(xdrproc_t)xdr_remote_interface_define_xml_args,
sizeof(remote_interface_define_xml_ret),
(xdrproc_t)xdr_remote_interface_define_xml_ret,
true,
1
},
{ /* Method InterfaceUndefine => 132 */
remoteDispatchInterfaceUndefineHelper,
sizeof(remote_interface_undefine_args),
(xdrproc_t)xdr_remote_interface_undefine_args,
0,
(xdrproc_t)xdr_void,
true,
1
},
{ /* Method InterfaceCreate => 133 */
remoteDispatchInterfaceCreateHelper,
sizeof(remote_interface_create_args),
(xdrproc_t)xdr_remote_interface_create_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method InterfaceDestroy => 134 */
remoteDispatchInterfaceDestroyHelper,
sizeof(remote_interface_destroy_args),
(xdrproc_t)xdr_remote_interface_destroy_args,
0,
(xdrproc_t)xdr_void,
true,
1
},
{ /* Method ConnectDomainXMLFromNative => 135 */
remoteDispatchConnectDomainXMLFromNativeHelper,
sizeof(remote_connect_domain_xml_from_native_args),
(xdrproc_t)xdr_remote_connect_domain_xml_from_native_args,
sizeof(remote_connect_domain_xml_from_native_ret),
(xdrproc_t)xdr_remote_connect_domain_xml_from_native_ret,
true,
0
},
{ /* Method ConnectDomainXMLToNative => 136 */
remoteDispatchConnectDomainXMLToNativeHelper,
sizeof(remote_connect_domain_xml_to_native_args),
(xdrproc_t)xdr_remote_connect_domain_xml_to_native_args,
sizeof(remote_connect_domain_xml_to_native_ret),
(xdrproc_t)xdr_remote_connect_domain_xml_to_native_ret,
true,
0
},
{ /* Method ConnectNumOfDefinedInterfaces => 137 */
remoteDispatchConnectNumOfDefinedInterfacesHelper,
0,
(xdrproc_t)xdr_void,
sizeof(remote_connect_num_of_defined_interfaces_ret),
(xdrproc_t)xdr_remote_connect_num_of_defined_interfaces_ret,
true,
1
},
{ /* Method ConnectListDefinedInterfaces => 138 */
remoteDispatchConnectListDefinedInterfacesHelper,
sizeof(remote_connect_list_defined_interfaces_args),
(xdrproc_t)xdr_remote_connect_list_defined_interfaces_args,
sizeof(remote_connect_list_defined_interfaces_ret),
(xdrproc_t)xdr_remote_connect_list_defined_interfaces_ret,
true,
1
},
{ /* Method ConnectNumOfSecrets => 139 */
remoteDispatchConnectNumOfSecretsHelper,
0,
(xdrproc_t)xdr_void,
sizeof(remote_connect_num_of_secrets_ret),
(xdrproc_t)xdr_remote_connect_num_of_secrets_ret,
true,
1
},
{ /* Method ConnectListSecrets => 140 */
remoteDispatchConnectListSecretsHelper,
sizeof(remote_connect_list_secrets_args),
(xdrproc_t)xdr_remote_connect_list_secrets_args,
sizeof(remote_connect_list_secrets_ret),
(xdrproc_t)xdr_remote_connect_list_secrets_ret,
true,
1
},
{ /* Method SecretLookupByUUID => 141 */
remoteDispatchSecretLookupByUUIDHelper,
sizeof(remote_secret_lookup_by_uuid_args),
(xdrproc_t)xdr_remote_secret_lookup_by_uuid_args,
sizeof(remote_secret_lookup_by_uuid_ret),
(xdrproc_t)xdr_remote_secret_lookup_by_uuid_ret,
true,
1
},
{ /* Method SecretDefineXML => 142 */
remoteDispatchSecretDefineXMLHelper,
sizeof(remote_secret_define_xml_args),
(xdrproc_t)xdr_remote_secret_define_xml_args,
sizeof(remote_secret_define_xml_ret),
(xdrproc_t)xdr_remote_secret_define_xml_ret,
true,
1
},
{ /* Method SecretGetXMLDesc => 143 */
remoteDispatchSecretGetXMLDescHelper,
sizeof(remote_secret_get_xml_desc_args),
(xdrproc_t)xdr_remote_secret_get_xml_desc_args,
sizeof(remote_secret_get_xml_desc_ret),
(xdrproc_t)xdr_remote_secret_get_xml_desc_ret,
true,
1
},
{ /* Method SecretSetValue => 144 */
remoteDispatchSecretSetValueHelper,
sizeof(remote_secret_set_value_args),
(xdrproc_t)xdr_remote_secret_set_value_args,
0,
(xdrproc_t)xdr_void,
true,
1
},
{ /* Method SecretGetValue => 145 */
remoteDispatchSecretGetValueHelper,
sizeof(remote_secret_get_value_args),
(xdrproc_t)xdr_remote_secret_get_value_args,
sizeof(remote_secret_get_value_ret),
(xdrproc_t)xdr_remote_secret_get_value_ret,
true,
1
},
{ /* Method SecretUndefine => 146 */
remoteDispatchSecretUndefineHelper,
sizeof(remote_secret_undefine_args),
(xdrproc_t)xdr_remote_secret_undefine_args,
0,
(xdrproc_t)xdr_void,
true,
1
},
{ /* Method SecretLookupByUsage => 147 */
remoteDispatchSecretLookupByUsageHelper,
sizeof(remote_secret_lookup_by_usage_args),
(xdrproc_t)xdr_remote_secret_lookup_by_usage_args,
sizeof(remote_secret_lookup_by_usage_ret),
(xdrproc_t)xdr_remote_secret_lookup_by_usage_ret,
true,
1
},
{ /* Method DomainMigratePrepareTunnel => 148 */
remoteDispatchDomainMigratePrepareTunnelHelper,
sizeof(remote_domain_migrate_prepare_tunnel_args),
(xdrproc_t)xdr_remote_domain_migrate_prepare_tunnel_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method ConnectIsSecure => 149 */
remoteDispatchConnectIsSecureHelper,
0,
(xdrproc_t)xdr_void,
sizeof(remote_connect_is_secure_ret),
(xdrproc_t)xdr_remote_connect_is_secure_ret,
true,
1
},
{ /* Method DomainIsActive => 150 */
remoteDispatchDomainIsActiveHelper,
sizeof(remote_domain_is_active_args),
(xdrproc_t)xdr_remote_domain_is_active_args,
sizeof(remote_domain_is_active_ret),
(xdrproc_t)xdr_remote_domain_is_active_ret,
true,
1
},
{ /* Method DomainIsPersistent => 151 */
remoteDispatchDomainIsPersistentHelper,
sizeof(remote_domain_is_persistent_args),
(xdrproc_t)xdr_remote_domain_is_persistent_args,
sizeof(remote_domain_is_persistent_ret),
(xdrproc_t)xdr_remote_domain_is_persistent_ret,
true,
1
},
{ /* Method NetworkIsActive => 152 */
remoteDispatchNetworkIsActiveHelper,
sizeof(remote_network_is_active_args),
(xdrproc_t)xdr_remote_network_is_active_args,
sizeof(remote_network_is_active_ret),
(xdrproc_t)xdr_remote_network_is_active_ret,
true,
1
},
{ /* Method NetworkIsPersistent => 153 */
remoteDispatchNetworkIsPersistentHelper,
sizeof(remote_network_is_persistent_args),
(xdrproc_t)xdr_remote_network_is_persistent_args,
sizeof(remote_network_is_persistent_ret),
(xdrproc_t)xdr_remote_network_is_persistent_ret,
true,
1
},
{ /* Method StoragePoolIsActive => 154 */
remoteDispatchStoragePoolIsActiveHelper,
sizeof(remote_storage_pool_is_active_args),
(xdrproc_t)xdr_remote_storage_pool_is_active_args,
sizeof(remote_storage_pool_is_active_ret),
(xdrproc_t)xdr_remote_storage_pool_is_active_ret,
true,
1
},
{ /* Method StoragePoolIsPersistent => 155 */
remoteDispatchStoragePoolIsPersistentHelper,
sizeof(remote_storage_pool_is_persistent_args),
(xdrproc_t)xdr_remote_storage_pool_is_persistent_args,
sizeof(remote_storage_pool_is_persistent_ret),
(xdrproc_t)xdr_remote_storage_pool_is_persistent_ret,
true,
1
},
{ /* Method InterfaceIsActive => 156 */
remoteDispatchInterfaceIsActiveHelper,
sizeof(remote_interface_is_active_args),
(xdrproc_t)xdr_remote_interface_is_active_args,
sizeof(remote_interface_is_active_ret),
(xdrproc_t)xdr_remote_interface_is_active_ret,
true,
1
},
{ /* Method ConnectGetLibVersion => 157 */
remoteDispatchConnectGetLibVersionHelper,
0,
(xdrproc_t)xdr_void,
sizeof(remote_connect_get_lib_version_ret),
(xdrproc_t)xdr_remote_connect_get_lib_version_ret,
true,
1
},
{ /* Method ConnectCompareCPU => 158 */
remoteDispatchConnectCompareCPUHelper,
sizeof(remote_connect_compare_cpu_args),
(xdrproc_t)xdr_remote_connect_compare_cpu_args,
sizeof(remote_connect_compare_cpu_ret),
(xdrproc_t)xdr_remote_connect_compare_cpu_ret,
true,
1
},
{ /* Method DomainMemoryStats => 159 */
remoteDispatchDomainMemoryStatsHelper,
sizeof(remote_domain_memory_stats_args),
(xdrproc_t)xdr_remote_domain_memory_stats_args,
sizeof(remote_domain_memory_stats_ret),
(xdrproc_t)xdr_remote_domain_memory_stats_ret,
true,
0
},
{ /* Method DomainAttachDeviceFlags => 160 */
remoteDispatchDomainAttachDeviceFlagsHelper,
sizeof(remote_domain_attach_device_flags_args),
(xdrproc_t)xdr_remote_domain_attach_device_flags_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method DomainDetachDeviceFlags => 161 */
remoteDispatchDomainDetachDeviceFlagsHelper,
sizeof(remote_domain_detach_device_flags_args),
(xdrproc_t)xdr_remote_domain_detach_device_flags_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method ConnectBaselineCPU => 162 */
remoteDispatchConnectBaselineCPUHelper,
sizeof(remote_connect_baseline_cpu_args),
(xdrproc_t)xdr_remote_connect_baseline_cpu_args,
sizeof(remote_connect_baseline_cpu_ret),
(xdrproc_t)xdr_remote_connect_baseline_cpu_ret,
true,
0
},
{ /* Method DomainGetJobInfo => 163 */
remoteDispatchDomainGetJobInfoHelper,
sizeof(remote_domain_get_job_info_args),
(xdrproc_t)xdr_remote_domain_get_job_info_args,
sizeof(remote_domain_get_job_info_ret),
(xdrproc_t)xdr_remote_domain_get_job_info_ret,
true,
0
},
{ /* Method DomainAbortJob => 164 */
remoteDispatchDomainAbortJobHelper,
sizeof(remote_domain_abort_job_args),
(xdrproc_t)xdr_remote_domain_abort_job_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method StorageVolWipe => 165 */
remoteDispatchStorageVolWipeHelper,
sizeof(remote_storage_vol_wipe_args),
(xdrproc_t)xdr_remote_storage_vol_wipe_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method DomainMigrateSetMaxDowntime => 166 */
remoteDispatchDomainMigrateSetMaxDowntimeHelper,
sizeof(remote_domain_migrate_set_max_downtime_args),
(xdrproc_t)xdr_remote_domain_migrate_set_max_downtime_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method ConnectDomainEventRegisterAny => 167 */
remoteDispatchConnectDomainEventRegisterAnyHelper,
sizeof(remote_connect_domain_event_register_any_args),
(xdrproc_t)xdr_remote_connect_domain_event_register_any_args,
0,
(xdrproc_t)xdr_void,
true,
1
},
{ /* Method ConnectDomainEventDeregisterAny => 168 */
remoteDispatchConnectDomainEventDeregisterAnyHelper,
sizeof(remote_connect_domain_event_deregister_any_args),
(xdrproc_t)xdr_remote_connect_domain_event_deregister_any_args,
0,
(xdrproc_t)xdr_void,
true,
1
},
{ /* Async event DomainEventReboot => 169 */
NULL,
0,
(xdrproc_t)xdr_void,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Async event DomainEventRtcChange => 170 */
NULL,
0,
(xdrproc_t)xdr_void,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Async event DomainEventWatchdog => 171 */
NULL,
0,
(xdrproc_t)xdr_void,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Async event DomainEventIoError => 172 */
NULL,
0,
(xdrproc_t)xdr_void,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Async event DomainEventGraphics => 173 */
NULL,
0,
(xdrproc_t)xdr_void,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method DomainUpdateDeviceFlags => 174 */
remoteDispatchDomainUpdateDeviceFlagsHelper,
sizeof(remote_domain_update_device_flags_args),
(xdrproc_t)xdr_remote_domain_update_device_flags_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method NWFilterLookupByName => 175 */
remoteDispatchNWFilterLookupByNameHelper,
sizeof(remote_nwfilter_lookup_by_name_args),
(xdrproc_t)xdr_remote_nwfilter_lookup_by_name_args,
sizeof(remote_nwfilter_lookup_by_name_ret),
(xdrproc_t)xdr_remote_nwfilter_lookup_by_name_ret,
true,
1
},
{ /* Method NWFilterLookupByUUID => 176 */
remoteDispatchNWFilterLookupByUUIDHelper,
sizeof(remote_nwfilter_lookup_by_uuid_args),
(xdrproc_t)xdr_remote_nwfilter_lookup_by_uuid_args,
sizeof(remote_nwfilter_lookup_by_uuid_ret),
(xdrproc_t)xdr_remote_nwfilter_lookup_by_uuid_ret,
true,
1
},
{ /* Method NWFilterGetXMLDesc => 177 */
remoteDispatchNWFilterGetXMLDescHelper,
sizeof(remote_nwfilter_get_xml_desc_args),
(xdrproc_t)xdr_remote_nwfilter_get_xml_desc_args,
sizeof(remote_nwfilter_get_xml_desc_ret),
(xdrproc_t)xdr_remote_nwfilter_get_xml_desc_ret,
true,
1
},
{ /* Method ConnectNumOfNWFilters => 178 */
remoteDispatchConnectNumOfNWFiltersHelper,
0,
(xdrproc_t)xdr_void,
sizeof(remote_connect_num_of_nwfilters_ret),
(xdrproc_t)xdr_remote_connect_num_of_nwfilters_ret,
true,
1
},
{ /* Method ConnectListNWFilters => 179 */
remoteDispatchConnectListNWFiltersHelper,
sizeof(remote_connect_list_nwfilters_args),
(xdrproc_t)xdr_remote_connect_list_nwfilters_args,
sizeof(remote_connect_list_nwfilters_ret),
(xdrproc_t)xdr_remote_connect_list_nwfilters_ret,
true,
1
},
{ /* Method NWFilterDefineXML => 180 */
remoteDispatchNWFilterDefineXMLHelper,
sizeof(remote_nwfilter_define_xml_args),
(xdrproc_t)xdr_remote_nwfilter_define_xml_args,
sizeof(remote_nwfilter_define_xml_ret),
(xdrproc_t)xdr_remote_nwfilter_define_xml_ret,
true,
1
},
{ /* Method NWFilterUndefine => 181 */
remoteDispatchNWFilterUndefineHelper,
sizeof(remote_nwfilter_undefine_args),
(xdrproc_t)xdr_remote_nwfilter_undefine_args,
0,
(xdrproc_t)xdr_void,
true,
1
},
{ /* Method DomainManagedSave => 182 */
remoteDispatchDomainManagedSaveHelper,
sizeof(remote_domain_managed_save_args),
(xdrproc_t)xdr_remote_domain_managed_save_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method DomainHasManagedSaveImage => 183 */
remoteDispatchDomainHasManagedSaveImageHelper,
sizeof(remote_domain_has_managed_save_image_args),
(xdrproc_t)xdr_remote_domain_has_managed_save_image_args,
sizeof(remote_domain_has_managed_save_image_ret),
(xdrproc_t)xdr_remote_domain_has_managed_save_image_ret,
true,
0
},
{ /* Method DomainManagedSaveRemove => 184 */
remoteDispatchDomainManagedSaveRemoveHelper,
sizeof(remote_domain_managed_save_remove_args),
(xdrproc_t)xdr_remote_domain_managed_save_remove_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method DomainSnapshotCreateXML => 185 */
remoteDispatchDomainSnapshotCreateXMLHelper,
sizeof(remote_domain_snapshot_create_xml_args),
(xdrproc_t)xdr_remote_domain_snapshot_create_xml_args,
sizeof(remote_domain_snapshot_create_xml_ret),
(xdrproc_t)xdr_remote_domain_snapshot_create_xml_ret,
true,
0
},
{ /* Method DomainSnapshotGetXMLDesc => 186 */
remoteDispatchDomainSnapshotGetXMLDescHelper,
sizeof(remote_domain_snapshot_get_xml_desc_args),
(xdrproc_t)xdr_remote_domain_snapshot_get_xml_desc_args,
sizeof(remote_domain_snapshot_get_xml_desc_ret),
(xdrproc_t)xdr_remote_domain_snapshot_get_xml_desc_ret,
true,
1
},
{ /* Method DomainSnapshotNum => 187 */
remoteDispatchDomainSnapshotNumHelper,
sizeof(remote_domain_snapshot_num_args),
(xdrproc_t)xdr_remote_domain_snapshot_num_args,
sizeof(remote_domain_snapshot_num_ret),
(xdrproc_t)xdr_remote_domain_snapshot_num_ret,
true,
1
},
{ /* Method DomainSnapshotListNames => 188 */
remoteDispatchDomainSnapshotListNamesHelper,
sizeof(remote_domain_snapshot_list_names_args),
(xdrproc_t)xdr_remote_domain_snapshot_list_names_args,
sizeof(remote_domain_snapshot_list_names_ret),
(xdrproc_t)xdr_remote_domain_snapshot_list_names_ret,
true,
1
},
{ /* Method DomainSnapshotLookupByName => 189 */
remoteDispatchDomainSnapshotLookupByNameHelper,
sizeof(remote_domain_snapshot_lookup_by_name_args),
(xdrproc_t)xdr_remote_domain_snapshot_lookup_by_name_args,
sizeof(remote_domain_snapshot_lookup_by_name_ret),
(xdrproc_t)xdr_remote_domain_snapshot_lookup_by_name_ret,
true,
1
},
{ /* Method DomainHasCurrentSnapshot => 190 */
remoteDispatchDomainHasCurrentSnapshotHelper,
sizeof(remote_domain_has_current_snapshot_args),
(xdrproc_t)xdr_remote_domain_has_current_snapshot_args,
sizeof(remote_domain_has_current_snapshot_ret),
(xdrproc_t)xdr_remote_domain_has_current_snapshot_ret,
true,
0
},
{ /* Method DomainSnapshotCurrent => 191 */
remoteDispatchDomainSnapshotCurrentHelper,
sizeof(remote_domain_snapshot_current_args),
(xdrproc_t)xdr_remote_domain_snapshot_current_args,
sizeof(remote_domain_snapshot_current_ret),
(xdrproc_t)xdr_remote_domain_snapshot_current_ret,
true,
0
},
{ /* Method DomainRevertToSnapshot => 192 */
remoteDispatchDomainRevertToSnapshotHelper,
sizeof(remote_domain_revert_to_snapshot_args),
(xdrproc_t)xdr_remote_domain_revert_to_snapshot_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method DomainSnapshotDelete => 193 */
remoteDispatchDomainSnapshotDeleteHelper,
sizeof(remote_domain_snapshot_delete_args),
(xdrproc_t)xdr_remote_domain_snapshot_delete_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method DomainGetBlockInfo => 194 */
remoteDispatchDomainGetBlockInfoHelper,
sizeof(remote_domain_get_block_info_args),
(xdrproc_t)xdr_remote_domain_get_block_info_args,
sizeof(remote_domain_get_block_info_ret),
(xdrproc_t)xdr_remote_domain_get_block_info_ret,
true,
0
},
{ /* Async event DomainEventIoErrorReason => 195 */
NULL,
0,
(xdrproc_t)xdr_void,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method DomainCreateWithFlags => 196 */
remoteDispatchDomainCreateWithFlagsHelper,
sizeof(remote_domain_create_with_flags_args),
(xdrproc_t)xdr_remote_domain_create_with_flags_args,
sizeof(remote_domain_create_with_flags_ret),
(xdrproc_t)xdr_remote_domain_create_with_flags_ret,
true,
0
},
{ /* Method DomainSetMemoryParameters => 197 */
remoteDispatchDomainSetMemoryParametersHelper,
sizeof(remote_domain_set_memory_parameters_args),
(xdrproc_t)xdr_remote_domain_set_memory_parameters_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method DomainGetMemoryParameters => 198 */
remoteDispatchDomainGetMemoryParametersHelper,
sizeof(remote_domain_get_memory_parameters_args),
(xdrproc_t)xdr_remote_domain_get_memory_parameters_args,
sizeof(remote_domain_get_memory_parameters_ret),
(xdrproc_t)xdr_remote_domain_get_memory_parameters_ret,
true,
0
},
{ /* Method DomainSetVcpusFlags => 199 */
remoteDispatchDomainSetVcpusFlagsHelper,
sizeof(remote_domain_set_vcpus_flags_args),
(xdrproc_t)xdr_remote_domain_set_vcpus_flags_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method DomainGetVcpusFlags => 200 */
remoteDispatchDomainGetVcpusFlagsHelper,
sizeof(remote_domain_get_vcpus_flags_args),
(xdrproc_t)xdr_remote_domain_get_vcpus_flags_args,
sizeof(remote_domain_get_vcpus_flags_ret),
(xdrproc_t)xdr_remote_domain_get_vcpus_flags_ret,
true,
0
},
{ /* Method DomainOpenConsole => 201 */
remoteDispatchDomainOpenConsoleHelper,
sizeof(remote_domain_open_console_args),
(xdrproc_t)xdr_remote_domain_open_console_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method DomainIsUpdated => 202 */
remoteDispatchDomainIsUpdatedHelper,
sizeof(remote_domain_is_updated_args),
(xdrproc_t)xdr_remote_domain_is_updated_args,
sizeof(remote_domain_is_updated_ret),
(xdrproc_t)xdr_remote_domain_is_updated_ret,
true,
1
},
{ /* Method ConnectGetSysinfo => 203 */
remoteDispatchConnectGetSysinfoHelper,
sizeof(remote_connect_get_sysinfo_args),
(xdrproc_t)xdr_remote_connect_get_sysinfo_args,
sizeof(remote_connect_get_sysinfo_ret),
(xdrproc_t)xdr_remote_connect_get_sysinfo_ret,
true,
1
},
{ /* Method DomainSetMemoryFlags => 204 */
remoteDispatchDomainSetMemoryFlagsHelper,
sizeof(remote_domain_set_memory_flags_args),
(xdrproc_t)xdr_remote_domain_set_memory_flags_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method DomainSetBlkioParameters => 205 */
remoteDispatchDomainSetBlkioParametersHelper,
sizeof(remote_domain_set_blkio_parameters_args),
(xdrproc_t)xdr_remote_domain_set_blkio_parameters_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method DomainGetBlkioParameters => 206 */
remoteDispatchDomainGetBlkioParametersHelper,
sizeof(remote_domain_get_blkio_parameters_args),
(xdrproc_t)xdr_remote_domain_get_blkio_parameters_args,
sizeof(remote_domain_get_blkio_parameters_ret),
(xdrproc_t)xdr_remote_domain_get_blkio_parameters_ret,
true,
0
},
{ /* Method DomainMigrateSetMaxSpeed => 207 */
remoteDispatchDomainMigrateSetMaxSpeedHelper,
sizeof(remote_domain_migrate_set_max_speed_args),
(xdrproc_t)xdr_remote_domain_migrate_set_max_speed_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method StorageVolUpload => 208 */
remoteDispatchStorageVolUploadHelper,
sizeof(remote_storage_vol_upload_args),
(xdrproc_t)xdr_remote_storage_vol_upload_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method StorageVolDownload => 209 */
remoteDispatchStorageVolDownloadHelper,
sizeof(remote_storage_vol_download_args),
(xdrproc_t)xdr_remote_storage_vol_download_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method DomainInjectNMI => 210 */
remoteDispatchDomainInjectNMIHelper,
sizeof(remote_domain_inject_nmi_args),
(xdrproc_t)xdr_remote_domain_inject_nmi_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method DomainScreenshot => 211 */
remoteDispatchDomainScreenshotHelper,
sizeof(remote_domain_screenshot_args),
(xdrproc_t)xdr_remote_domain_screenshot_args,
sizeof(remote_domain_screenshot_ret),
(xdrproc_t)xdr_remote_domain_screenshot_ret,
true,
0
},
{ /* Method DomainGetState => 212 */
remoteDispatchDomainGetStateHelper,
sizeof(remote_domain_get_state_args),
(xdrproc_t)xdr_remote_domain_get_state_args,
sizeof(remote_domain_get_state_ret),
(xdrproc_t)xdr_remote_domain_get_state_ret,
true,
1
},
{ /* Method DomainMigrateBegin3 => 213 */
remoteDispatchDomainMigrateBegin3Helper,
sizeof(remote_domain_migrate_begin3_args),
(xdrproc_t)xdr_remote_domain_migrate_begin3_args,
sizeof(remote_domain_migrate_begin3_ret),
(xdrproc_t)xdr_remote_domain_migrate_begin3_ret,
true,
0
},
{ /* Method DomainMigratePrepare3 => 214 */
remoteDispatchDomainMigratePrepare3Helper,
sizeof(remote_domain_migrate_prepare3_args),
(xdrproc_t)xdr_remote_domain_migrate_prepare3_args,
sizeof(remote_domain_migrate_prepare3_ret),
(xdrproc_t)xdr_remote_domain_migrate_prepare3_ret,
true,
0
},
{ /* Method DomainMigratePrepareTunnel3 => 215 */
remoteDispatchDomainMigratePrepareTunnel3Helper,
sizeof(remote_domain_migrate_prepare_tunnel3_args),
(xdrproc_t)xdr_remote_domain_migrate_prepare_tunnel3_args,
sizeof(remote_domain_migrate_prepare_tunnel3_ret),
(xdrproc_t)xdr_remote_domain_migrate_prepare_tunnel3_ret,
true,
0
},
{ /* Method DomainMigratePerform3 => 216 */
remoteDispatchDomainMigratePerform3Helper,
sizeof(remote_domain_migrate_perform3_args),
(xdrproc_t)xdr_remote_domain_migrate_perform3_args,
sizeof(remote_domain_migrate_perform3_ret),
(xdrproc_t)xdr_remote_domain_migrate_perform3_ret,
true,
0
},
{ /* Method DomainMigrateFinish3 => 217 */
remoteDispatchDomainMigrateFinish3Helper,
sizeof(remote_domain_migrate_finish3_args),
(xdrproc_t)xdr_remote_domain_migrate_finish3_args,
sizeof(remote_domain_migrate_finish3_ret),
(xdrproc_t)xdr_remote_domain_migrate_finish3_ret,
true,
0
},
{ /* Method DomainMigrateConfirm3 => 218 */
remoteDispatchDomainMigrateConfirm3Helper,
sizeof(remote_domain_migrate_confirm3_args),
(xdrproc_t)xdr_remote_domain_migrate_confirm3_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method DomainSetSchedulerParametersFlags => 219 */
remoteDispatchDomainSetSchedulerParametersFlagsHelper,
sizeof(remote_domain_set_scheduler_parameters_flags_args),
(xdrproc_t)xdr_remote_domain_set_scheduler_parameters_flags_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method InterfaceChangeBegin => 220 */
remoteDispatchInterfaceChangeBeginHelper,
sizeof(remote_interface_change_begin_args),
(xdrproc_t)xdr_remote_interface_change_begin_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method InterfaceChangeCommit => 221 */
remoteDispatchInterfaceChangeCommitHelper,
sizeof(remote_interface_change_commit_args),
(xdrproc_t)xdr_remote_interface_change_commit_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method InterfaceChangeRollback => 222 */
remoteDispatchInterfaceChangeRollbackHelper,
sizeof(remote_interface_change_rollback_args),
(xdrproc_t)xdr_remote_interface_change_rollback_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method DomainGetSchedulerParametersFlags => 223 */
remoteDispatchDomainGetSchedulerParametersFlagsHelper,
sizeof(remote_domain_get_scheduler_parameters_flags_args),
(xdrproc_t)xdr_remote_domain_get_scheduler_parameters_flags_args,
sizeof(remote_domain_get_scheduler_parameters_flags_ret),
(xdrproc_t)xdr_remote_domain_get_scheduler_parameters_flags_ret,
true,
0
},
{ /* Async event DomainEventControlError => 224 */
NULL,
0,
(xdrproc_t)xdr_void,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method DomainPinVcpuFlags => 225 */
remoteDispatchDomainPinVcpuFlagsHelper,
sizeof(remote_domain_pin_vcpu_flags_args),
(xdrproc_t)xdr_remote_domain_pin_vcpu_flags_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method DomainSendKey => 226 */
remoteDispatchDomainSendKeyHelper,
sizeof(remote_domain_send_key_args),
(xdrproc_t)xdr_remote_domain_send_key_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method NodeGetCPUStats => 227 */
remoteDispatchNodeGetCPUStatsHelper,
sizeof(remote_node_get_cpu_stats_args),
(xdrproc_t)xdr_remote_node_get_cpu_stats_args,
sizeof(remote_node_get_cpu_stats_ret),
(xdrproc_t)xdr_remote_node_get_cpu_stats_ret,
true,
1
},
{ /* Method NodeGetMemoryStats => 228 */
remoteDispatchNodeGetMemoryStatsHelper,
sizeof(remote_node_get_memory_stats_args),
(xdrproc_t)xdr_remote_node_get_memory_stats_args,
sizeof(remote_node_get_memory_stats_ret),
(xdrproc_t)xdr_remote_node_get_memory_stats_ret,
true,
1
},
{ /* Method DomainGetControlInfo => 229 */
remoteDispatchDomainGetControlInfoHelper,
sizeof(remote_domain_get_control_info_args),
(xdrproc_t)xdr_remote_domain_get_control_info_args,
sizeof(remote_domain_get_control_info_ret),
(xdrproc_t)xdr_remote_domain_get_control_info_ret,
true,
1
},
{ /* Method DomainGetVcpuPinInfo => 230 */
remoteDispatchDomainGetVcpuPinInfoHelper,
sizeof(remote_domain_get_vcpu_pin_info_args),
(xdrproc_t)xdr_remote_domain_get_vcpu_pin_info_args,
sizeof(remote_domain_get_vcpu_pin_info_ret),
(xdrproc_t)xdr_remote_domain_get_vcpu_pin_info_ret,
true,
0
},
{ /* Method DomainUndefineFlags => 231 */
remoteDispatchDomainUndefineFlagsHelper,
sizeof(remote_domain_undefine_flags_args),
(xdrproc_t)xdr_remote_domain_undefine_flags_args,
0,
(xdrproc_t)xdr_void,
true,
1
},
{ /* Method DomainSaveFlags => 232 */
remoteDispatchDomainSaveFlagsHelper,
sizeof(remote_domain_save_flags_args),
(xdrproc_t)xdr_remote_domain_save_flags_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method DomainRestoreFlags => 233 */
remoteDispatchDomainRestoreFlagsHelper,
sizeof(remote_domain_restore_flags_args),
(xdrproc_t)xdr_remote_domain_restore_flags_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method DomainDestroyFlags => 234 */
remoteDispatchDomainDestroyFlagsHelper,
sizeof(remote_domain_destroy_flags_args),
(xdrproc_t)xdr_remote_domain_destroy_flags_args,
0,
(xdrproc_t)xdr_void,
true,
1
},
{ /* Method DomainSaveImageGetXMLDesc => 235 */
remoteDispatchDomainSaveImageGetXMLDescHelper,
sizeof(remote_domain_save_image_get_xml_desc_args),
(xdrproc_t)xdr_remote_domain_save_image_get_xml_desc_args,
sizeof(remote_domain_save_image_get_xml_desc_ret),
(xdrproc_t)xdr_remote_domain_save_image_get_xml_desc_ret,
true,
1
},
{ /* Method DomainSaveImageDefineXML => 236 */
remoteDispatchDomainSaveImageDefineXMLHelper,
sizeof(remote_domain_save_image_define_xml_args),
(xdrproc_t)xdr_remote_domain_save_image_define_xml_args,
0,
(xdrproc_t)xdr_void,
true,
1
},
{ /* Method DomainBlockJobAbort => 237 */
remoteDispatchDomainBlockJobAbortHelper,
sizeof(remote_domain_block_job_abort_args),
(xdrproc_t)xdr_remote_domain_block_job_abort_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method DomainGetBlockJobInfo => 238 */
remoteDispatchDomainGetBlockJobInfoHelper,
sizeof(remote_domain_get_block_job_info_args),
(xdrproc_t)xdr_remote_domain_get_block_job_info_args,
sizeof(remote_domain_get_block_job_info_ret),
(xdrproc_t)xdr_remote_domain_get_block_job_info_ret,
true,
0
},
{ /* Method DomainBlockJobSetSpeed => 239 */
remoteDispatchDomainBlockJobSetSpeedHelper,
sizeof(remote_domain_block_job_set_speed_args),
(xdrproc_t)xdr_remote_domain_block_job_set_speed_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method DomainBlockPull => 240 */
remoteDispatchDomainBlockPullHelper,
sizeof(remote_domain_block_pull_args),
(xdrproc_t)xdr_remote_domain_block_pull_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Async event DomainEventBlockJob => 241 */
NULL,
0,
(xdrproc_t)xdr_void,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method DomainMigrateGetMaxSpeed => 242 */
remoteDispatchDomainMigrateGetMaxSpeedHelper,
sizeof(remote_domain_migrate_get_max_speed_args),
(xdrproc_t)xdr_remote_domain_migrate_get_max_speed_args,
sizeof(remote_domain_migrate_get_max_speed_ret),
(xdrproc_t)xdr_remote_domain_migrate_get_max_speed_ret,
true,
0
},
{ /* Method DomainBlockStatsFlags => 243 */
remoteDispatchDomainBlockStatsFlagsHelper,
sizeof(remote_domain_block_stats_flags_args),
(xdrproc_t)xdr_remote_domain_block_stats_flags_args,
sizeof(remote_domain_block_stats_flags_ret),
(xdrproc_t)xdr_remote_domain_block_stats_flags_ret,
true,
0
},
{ /* Method DomainSnapshotGetParent => 244 */
remoteDispatchDomainSnapshotGetParentHelper,
sizeof(remote_domain_snapshot_get_parent_args),
(xdrproc_t)xdr_remote_domain_snapshot_get_parent_args,
sizeof(remote_domain_snapshot_get_parent_ret),
(xdrproc_t)xdr_remote_domain_snapshot_get_parent_ret,
true,
1
},
{ /* Method DomainReset => 245 */
remoteDispatchDomainResetHelper,
sizeof(remote_domain_reset_args),
(xdrproc_t)xdr_remote_domain_reset_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method DomainSnapshotNumChildren => 246 */
remoteDispatchDomainSnapshotNumChildrenHelper,
sizeof(remote_domain_snapshot_num_children_args),
(xdrproc_t)xdr_remote_domain_snapshot_num_children_args,
sizeof(remote_domain_snapshot_num_children_ret),
(xdrproc_t)xdr_remote_domain_snapshot_num_children_ret,
true,
1
},
{ /* Method DomainSnapshotListChildrenNames => 247 */
remoteDispatchDomainSnapshotListChildrenNamesHelper,
sizeof(remote_domain_snapshot_list_children_names_args),
(xdrproc_t)xdr_remote_domain_snapshot_list_children_names_args,
sizeof(remote_domain_snapshot_list_children_names_ret),
(xdrproc_t)xdr_remote_domain_snapshot_list_children_names_ret,
true,
1
},
{ /* Async event DomainEventDiskChange => 248 */
NULL,
0,
(xdrproc_t)xdr_void,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method DomainOpenGraphics => 249 */
remoteDispatchDomainOpenGraphicsHelper,
sizeof(remote_domain_open_graphics_args),
(xdrproc_t)xdr_remote_domain_open_graphics_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method NodeSuspendForDuration => 250 */
remoteDispatchNodeSuspendForDurationHelper,
sizeof(remote_node_suspend_for_duration_args),
(xdrproc_t)xdr_remote_node_suspend_for_duration_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method DomainBlockResize => 251 */
remoteDispatchDomainBlockResizeHelper,
sizeof(remote_domain_block_resize_args),
(xdrproc_t)xdr_remote_domain_block_resize_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method DomainSetBlockIoTune => 252 */
remoteDispatchDomainSetBlockIoTuneHelper,
sizeof(remote_domain_set_block_io_tune_args),
(xdrproc_t)xdr_remote_domain_set_block_io_tune_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method DomainGetBlockIoTune => 253 */
remoteDispatchDomainGetBlockIoTuneHelper,
sizeof(remote_domain_get_block_io_tune_args),
(xdrproc_t)xdr_remote_domain_get_block_io_tune_args,
sizeof(remote_domain_get_block_io_tune_ret),
(xdrproc_t)xdr_remote_domain_get_block_io_tune_ret,
true,
0
},
{ /* Method DomainSetNumaParameters => 254 */
remoteDispatchDomainSetNumaParametersHelper,
sizeof(remote_domain_set_numa_parameters_args),
(xdrproc_t)xdr_remote_domain_set_numa_parameters_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method DomainGetNumaParameters => 255 */
remoteDispatchDomainGetNumaParametersHelper,
sizeof(remote_domain_get_numa_parameters_args),
(xdrproc_t)xdr_remote_domain_get_numa_parameters_args,
sizeof(remote_domain_get_numa_parameters_ret),
(xdrproc_t)xdr_remote_domain_get_numa_parameters_ret,
true,
0
},
{ /* Method DomainSetInterfaceParameters => 256 */
remoteDispatchDomainSetInterfaceParametersHelper,
sizeof(remote_domain_set_interface_parameters_args),
(xdrproc_t)xdr_remote_domain_set_interface_parameters_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method DomainGetInterfaceParameters => 257 */
remoteDispatchDomainGetInterfaceParametersHelper,
sizeof(remote_domain_get_interface_parameters_args),
(xdrproc_t)xdr_remote_domain_get_interface_parameters_args,
sizeof(remote_domain_get_interface_parameters_ret),
(xdrproc_t)xdr_remote_domain_get_interface_parameters_ret,
true,
0
},
{ /* Method DomainShutdownFlags => 258 */
remoteDispatchDomainShutdownFlagsHelper,
sizeof(remote_domain_shutdown_flags_args),
(xdrproc_t)xdr_remote_domain_shutdown_flags_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method StorageVolWipePattern => 259 */
remoteDispatchStorageVolWipePatternHelper,
sizeof(remote_storage_vol_wipe_pattern_args),
(xdrproc_t)xdr_remote_storage_vol_wipe_pattern_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method StorageVolResize => 260 */
remoteDispatchStorageVolResizeHelper,
sizeof(remote_storage_vol_resize_args),
(xdrproc_t)xdr_remote_storage_vol_resize_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method DomainPMSuspendForDuration => 261 */
remoteDispatchDomainPMSuspendForDurationHelper,
sizeof(remote_domain_pm_suspend_for_duration_args),
(xdrproc_t)xdr_remote_domain_pm_suspend_for_duration_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method DomainGetCPUStats => 262 */
remoteDispatchDomainGetCPUStatsHelper,
sizeof(remote_domain_get_cpu_stats_args),
(xdrproc_t)xdr_remote_domain_get_cpu_stats_args,
sizeof(remote_domain_get_cpu_stats_ret),
(xdrproc_t)xdr_remote_domain_get_cpu_stats_ret,
true,
0
},
{ /* Method DomainGetDiskErrors => 263 */
remoteDispatchDomainGetDiskErrorsHelper,
sizeof(remote_domain_get_disk_errors_args),
(xdrproc_t)xdr_remote_domain_get_disk_errors_args,
sizeof(remote_domain_get_disk_errors_ret),
(xdrproc_t)xdr_remote_domain_get_disk_errors_ret,
true,
0
},
{ /* Method DomainSetMetadata => 264 */
remoteDispatchDomainSetMetadataHelper,
sizeof(remote_domain_set_metadata_args),
(xdrproc_t)xdr_remote_domain_set_metadata_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method DomainGetMetadata => 265 */
remoteDispatchDomainGetMetadataHelper,
sizeof(remote_domain_get_metadata_args),
(xdrproc_t)xdr_remote_domain_get_metadata_args,
sizeof(remote_domain_get_metadata_ret),
(xdrproc_t)xdr_remote_domain_get_metadata_ret,
true,
0
},
{ /* Method DomainBlockRebase => 266 */
remoteDispatchDomainBlockRebaseHelper,
sizeof(remote_domain_block_rebase_args),
(xdrproc_t)xdr_remote_domain_block_rebase_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method DomainPMWakeup => 267 */
remoteDispatchDomainPMWakeupHelper,
sizeof(remote_domain_pm_wakeup_args),
(xdrproc_t)xdr_remote_domain_pm_wakeup_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Async event DomainEventTrayChange => 268 */
NULL,
0,
(xdrproc_t)xdr_void,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Async event DomainEventPMwakeup => 269 */
NULL,
0,
(xdrproc_t)xdr_void,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Async event DomainEventPMsuspend => 270 */
NULL,
0,
(xdrproc_t)xdr_void,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method DomainSnapshotIsCurrent => 271 */
remoteDispatchDomainSnapshotIsCurrentHelper,
sizeof(remote_domain_snapshot_is_current_args),
(xdrproc_t)xdr_remote_domain_snapshot_is_current_args,
sizeof(remote_domain_snapshot_is_current_ret),
(xdrproc_t)xdr_remote_domain_snapshot_is_current_ret,
true,
0
},
{ /* Method DomainSnapshotHasMetadata => 272 */
remoteDispatchDomainSnapshotHasMetadataHelper,
sizeof(remote_domain_snapshot_has_metadata_args),
(xdrproc_t)xdr_remote_domain_snapshot_has_metadata_args,
sizeof(remote_domain_snapshot_has_metadata_ret),
(xdrproc_t)xdr_remote_domain_snapshot_has_metadata_ret,
true,
0
},
{ /* Method ConnectListAllDomains => 273 */
remoteDispatchConnectListAllDomainsHelper,
sizeof(remote_connect_list_all_domains_args),
(xdrproc_t)xdr_remote_connect_list_all_domains_args,
sizeof(remote_connect_list_all_domains_ret),
(xdrproc_t)xdr_remote_connect_list_all_domains_ret,
true,
1
},
{ /* Method DomainListAllSnapshots => 274 */
remoteDispatchDomainListAllSnapshotsHelper,
sizeof(remote_domain_list_all_snapshots_args),
(xdrproc_t)xdr_remote_domain_list_all_snapshots_args,
sizeof(remote_domain_list_all_snapshots_ret),
(xdrproc_t)xdr_remote_domain_list_all_snapshots_ret,
true,
1
},
{ /* Method DomainSnapshotListAllChildren => 275 */
remoteDispatchDomainSnapshotListAllChildrenHelper,
sizeof(remote_domain_snapshot_list_all_children_args),
(xdrproc_t)xdr_remote_domain_snapshot_list_all_children_args,
sizeof(remote_domain_snapshot_list_all_children_ret),
(xdrproc_t)xdr_remote_domain_snapshot_list_all_children_ret,
true,
1
},
{ /* Async event DomainEventBalloonChange => 276 */
NULL,
0,
(xdrproc_t)xdr_void,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method DomainGetHostname => 277 */
remoteDispatchDomainGetHostnameHelper,
sizeof(remote_domain_get_hostname_args),
(xdrproc_t)xdr_remote_domain_get_hostname_args,
sizeof(remote_domain_get_hostname_ret),
(xdrproc_t)xdr_remote_domain_get_hostname_ret,
true,
0
},
{ /* Method DomainGetSecurityLabelList => 278 */
remoteDispatchDomainGetSecurityLabelListHelper,
sizeof(remote_domain_get_security_label_list_args),
(xdrproc_t)xdr_remote_domain_get_security_label_list_args,
sizeof(remote_domain_get_security_label_list_ret),
(xdrproc_t)xdr_remote_domain_get_security_label_list_ret,
true,
1
},
{ /* Method DomainPinEmulator => 279 */
remoteDispatchDomainPinEmulatorHelper,
sizeof(remote_domain_pin_emulator_args),
(xdrproc_t)xdr_remote_domain_pin_emulator_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method DomainGetEmulatorPinInfo => 280 */
remoteDispatchDomainGetEmulatorPinInfoHelper,
sizeof(remote_domain_get_emulator_pin_info_args),
(xdrproc_t)xdr_remote_domain_get_emulator_pin_info_args,
sizeof(remote_domain_get_emulator_pin_info_ret),
(xdrproc_t)xdr_remote_domain_get_emulator_pin_info_ret,
true,
0
},
{ /* Method ConnectListAllStoragePools => 281 */
remoteDispatchConnectListAllStoragePoolsHelper,
sizeof(remote_connect_list_all_storage_pools_args),
(xdrproc_t)xdr_remote_connect_list_all_storage_pools_args,
sizeof(remote_connect_list_all_storage_pools_ret),
(xdrproc_t)xdr_remote_connect_list_all_storage_pools_ret,
true,
1
},
{ /* Method StoragePoolListAllVolumes => 282 */
remoteDispatchStoragePoolListAllVolumesHelper,
sizeof(remote_storage_pool_list_all_volumes_args),
(xdrproc_t)xdr_remote_storage_pool_list_all_volumes_args,
sizeof(remote_storage_pool_list_all_volumes_ret),
(xdrproc_t)xdr_remote_storage_pool_list_all_volumes_ret,
true,
1
},
{ /* Method ConnectListAllNetworks => 283 */
remoteDispatchConnectListAllNetworksHelper,
sizeof(remote_connect_list_all_networks_args),
(xdrproc_t)xdr_remote_connect_list_all_networks_args,
sizeof(remote_connect_list_all_networks_ret),
(xdrproc_t)xdr_remote_connect_list_all_networks_ret,
true,
1
},
{ /* Method ConnectListAllInterfaces => 284 */
remoteDispatchConnectListAllInterfacesHelper,
sizeof(remote_connect_list_all_interfaces_args),
(xdrproc_t)xdr_remote_connect_list_all_interfaces_args,
sizeof(remote_connect_list_all_interfaces_ret),
(xdrproc_t)xdr_remote_connect_list_all_interfaces_ret,
true,
1
},
{ /* Method ConnectListAllNodeDevices => 285 */
remoteDispatchConnectListAllNodeDevicesHelper,
sizeof(remote_connect_list_all_node_devices_args),
(xdrproc_t)xdr_remote_connect_list_all_node_devices_args,
sizeof(remote_connect_list_all_node_devices_ret),
(xdrproc_t)xdr_remote_connect_list_all_node_devices_ret,
true,
1
},
{ /* Method ConnectListAllNWFilters => 286 */
remoteDispatchConnectListAllNWFiltersHelper,
sizeof(remote_connect_list_all_nwfilters_args),
(xdrproc_t)xdr_remote_connect_list_all_nwfilters_args,
sizeof(remote_connect_list_all_nwfilters_ret),
(xdrproc_t)xdr_remote_connect_list_all_nwfilters_ret,
true,
1
},
{ /* Method ConnectListAllSecrets => 287 */
remoteDispatchConnectListAllSecretsHelper,
sizeof(remote_connect_list_all_secrets_args),
(xdrproc_t)xdr_remote_connect_list_all_secrets_args,
sizeof(remote_connect_list_all_secrets_ret),
(xdrproc_t)xdr_remote_connect_list_all_secrets_ret,
true,
1
},
{ /* Method NodeSetMemoryParameters => 288 */
remoteDispatchNodeSetMemoryParametersHelper,
sizeof(remote_node_set_memory_parameters_args),
(xdrproc_t)xdr_remote_node_set_memory_parameters_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method NodeGetMemoryParameters => 289 */
remoteDispatchNodeGetMemoryParametersHelper,
sizeof(remote_node_get_memory_parameters_args),
(xdrproc_t)xdr_remote_node_get_memory_parameters_args,
sizeof(remote_node_get_memory_parameters_ret),
(xdrproc_t)xdr_remote_node_get_memory_parameters_ret,
true,
0
},
{ /* Method DomainBlockCommit => 290 */
remoteDispatchDomainBlockCommitHelper,
sizeof(remote_domain_block_commit_args),
(xdrproc_t)xdr_remote_domain_block_commit_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method NetworkUpdate => 291 */
remoteDispatchNetworkUpdateHelper,
sizeof(remote_network_update_args),
(xdrproc_t)xdr_remote_network_update_args,
0,
(xdrproc_t)xdr_void,
true,
1
},
{ /* Async event DomainEventPMsuspendDisk => 292 */
NULL,
0,
(xdrproc_t)xdr_void,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method NodeGetCPUMap => 293 */
remoteDispatchNodeGetCPUMapHelper,
sizeof(remote_node_get_cpu_map_args),
(xdrproc_t)xdr_remote_node_get_cpu_map_args,
sizeof(remote_node_get_cpu_map_ret),
(xdrproc_t)xdr_remote_node_get_cpu_map_ret,
true,
0
},
{ /* Method DomainFSTrim => 294 */
remoteDispatchDomainFSTrimHelper,
sizeof(remote_domain_fstrim_args),
(xdrproc_t)xdr_remote_domain_fstrim_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method DomainSendProcessSignal => 295 */
remoteDispatchDomainSendProcessSignalHelper,
sizeof(remote_domain_send_process_signal_args),
(xdrproc_t)xdr_remote_domain_send_process_signal_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method DomainOpenChannel => 296 */
remoteDispatchDomainOpenChannelHelper,
sizeof(remote_domain_open_channel_args),
(xdrproc_t)xdr_remote_domain_open_channel_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method NodeDeviceLookupSCSIHostByWWN => 297 */
remoteDispatchNodeDeviceLookupSCSIHostByWWNHelper,
sizeof(remote_node_device_lookup_scsi_host_by_wwn_args),
(xdrproc_t)xdr_remote_node_device_lookup_scsi_host_by_wwn_args,
sizeof(remote_node_device_lookup_scsi_host_by_wwn_ret),
(xdrproc_t)xdr_remote_node_device_lookup_scsi_host_by_wwn_ret,
true,
1
},
{ /* Method DomainGetJobStats => 298 */
remoteDispatchDomainGetJobStatsHelper,
sizeof(remote_domain_get_job_stats_args),
(xdrproc_t)xdr_remote_domain_get_job_stats_args,
sizeof(remote_domain_get_job_stats_ret),
(xdrproc_t)xdr_remote_domain_get_job_stats_ret,
true,
0
},
{ /* Method DomainMigrateGetCompressionCache => 299 */
remoteDispatchDomainMigrateGetCompressionCacheHelper,
sizeof(remote_domain_migrate_get_compression_cache_args),
(xdrproc_t)xdr_remote_domain_migrate_get_compression_cache_args,
sizeof(remote_domain_migrate_get_compression_cache_ret),
(xdrproc_t)xdr_remote_domain_migrate_get_compression_cache_ret,
true,
0
},
{ /* Method DomainMigrateSetCompressionCache => 300 */
remoteDispatchDomainMigrateSetCompressionCacheHelper,
sizeof(remote_domain_migrate_set_compression_cache_args),
(xdrproc_t)xdr_remote_domain_migrate_set_compression_cache_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method NodeDeviceDetachFlags => 301 */
remoteDispatchNodeDeviceDetachFlagsHelper,
sizeof(remote_node_device_detach_flags_args),
(xdrproc_t)xdr_remote_node_device_detach_flags_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method DomainMigrateBegin3Params => 302 */
remoteDispatchDomainMigrateBegin3ParamsHelper,
sizeof(remote_domain_migrate_begin3_params_args),
(xdrproc_t)xdr_remote_domain_migrate_begin3_params_args,
sizeof(remote_domain_migrate_begin3_params_ret),
(xdrproc_t)xdr_remote_domain_migrate_begin3_params_ret,
true,
0
},
{ /* Method DomainMigratePrepare3Params => 303 */
remoteDispatchDomainMigratePrepare3ParamsHelper,
sizeof(remote_domain_migrate_prepare3_params_args),
(xdrproc_t)xdr_remote_domain_migrate_prepare3_params_args,
sizeof(remote_domain_migrate_prepare3_params_ret),
(xdrproc_t)xdr_remote_domain_migrate_prepare3_params_ret,
true,
0
},
{ /* Method DomainMigratePrepareTunnel3Params => 304 */
remoteDispatchDomainMigratePrepareTunnel3ParamsHelper,
sizeof(remote_domain_migrate_prepare_tunnel3_params_args),
(xdrproc_t)xdr_remote_domain_migrate_prepare_tunnel3_params_args,
sizeof(remote_domain_migrate_prepare_tunnel3_params_ret),
(xdrproc_t)xdr_remote_domain_migrate_prepare_tunnel3_params_ret,
true,
0
},
{ /* Method DomainMigratePerform3Params => 305 */
remoteDispatchDomainMigratePerform3ParamsHelper,
sizeof(remote_domain_migrate_perform3_params_args),
(xdrproc_t)xdr_remote_domain_migrate_perform3_params_args,
sizeof(remote_domain_migrate_perform3_params_ret),
(xdrproc_t)xdr_remote_domain_migrate_perform3_params_ret,
true,
0
},
{ /* Method DomainMigrateFinish3Params => 306 */
remoteDispatchDomainMigrateFinish3ParamsHelper,
sizeof(remote_domain_migrate_finish3_params_args),
(xdrproc_t)xdr_remote_domain_migrate_finish3_params_args,
sizeof(remote_domain_migrate_finish3_params_ret),
(xdrproc_t)xdr_remote_domain_migrate_finish3_params_ret,
true,
0
},
{ /* Method DomainMigrateConfirm3Params => 307 */
remoteDispatchDomainMigrateConfirm3ParamsHelper,
sizeof(remote_domain_migrate_confirm3_params_args),
(xdrproc_t)xdr_remote_domain_migrate_confirm3_params_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method DomainSetMemoryStatsPeriod => 308 */
remoteDispatchDomainSetMemoryStatsPeriodHelper,
sizeof(remote_domain_set_memory_stats_period_args),
(xdrproc_t)xdr_remote_domain_set_memory_stats_period_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method DomainCreateXMLWithFiles => 309 */
remoteDispatchDomainCreateXMLWithFilesHelper,
sizeof(remote_domain_create_xml_with_files_args),
(xdrproc_t)xdr_remote_domain_create_xml_with_files_args,
sizeof(remote_domain_create_xml_with_files_ret),
(xdrproc_t)xdr_remote_domain_create_xml_with_files_ret,
true,
0
},
{ /* Method DomainCreateWithFiles => 310 */
remoteDispatchDomainCreateWithFilesHelper,
sizeof(remote_domain_create_with_files_args),
(xdrproc_t)xdr_remote_domain_create_with_files_args,
sizeof(remote_domain_create_with_files_ret),
(xdrproc_t)xdr_remote_domain_create_with_files_ret,
true,
0
},
{ /* Async event DomainEventDeviceRemoved => 311 */
NULL,
0,
(xdrproc_t)xdr_void,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method ConnectGetCPUModelNames => 312 */
remoteDispatchConnectGetCPUModelNamesHelper,
sizeof(remote_connect_get_cpu_model_names_args),
(xdrproc_t)xdr_remote_connect_get_cpu_model_names_args,
sizeof(remote_connect_get_cpu_model_names_ret),
(xdrproc_t)xdr_remote_connect_get_cpu_model_names_ret,
true,
0
},
{ /* Method ConnectNetworkEventRegisterAny => 313 */
remoteDispatchConnectNetworkEventRegisterAnyHelper,
sizeof(remote_connect_network_event_register_any_args),
(xdrproc_t)xdr_remote_connect_network_event_register_any_args,
sizeof(remote_connect_network_event_register_any_ret),
(xdrproc_t)xdr_remote_connect_network_event_register_any_ret,
true,
1
},
{ /* Method ConnectNetworkEventDeregisterAny => 314 */
remoteDispatchConnectNetworkEventDeregisterAnyHelper,
sizeof(remote_connect_network_event_deregister_any_args),
(xdrproc_t)xdr_remote_connect_network_event_deregister_any_args,
0,
(xdrproc_t)xdr_void,
true,
1
},
{ /* Async event NetworkEventLifecycle => 315 */
NULL,
0,
(xdrproc_t)xdr_void,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method ConnectDomainEventCallbackRegisterAny => 316 */
remoteDispatchConnectDomainEventCallbackRegisterAnyHelper,
sizeof(remote_connect_domain_event_callback_register_any_args),
(xdrproc_t)xdr_remote_connect_domain_event_callback_register_any_args,
sizeof(remote_connect_domain_event_callback_register_any_ret),
(xdrproc_t)xdr_remote_connect_domain_event_callback_register_any_ret,
true,
1
},
{ /* Method ConnectDomainEventCallbackDeregisterAny => 317 */
remoteDispatchConnectDomainEventCallbackDeregisterAnyHelper,
sizeof(remote_connect_domain_event_callback_deregister_any_args),
(xdrproc_t)xdr_remote_connect_domain_event_callback_deregister_any_args,
0,
(xdrproc_t)xdr_void,
true,
1
},
{ /* Async event DomainEventCallbackLifecycle => 318 */
NULL,
0,
(xdrproc_t)xdr_void,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Async event DomainEventCallbackReboot => 319 */
NULL,
0,
(xdrproc_t)xdr_void,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Async event DomainEventCallbackRtcChange => 320 */
NULL,
0,
(xdrproc_t)xdr_void,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Async event DomainEventCallbackWatchdog => 321 */
NULL,
0,
(xdrproc_t)xdr_void,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Async event DomainEventCallbackIoError => 322 */
NULL,
0,
(xdrproc_t)xdr_void,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Async event DomainEventCallbackGraphics => 323 */
NULL,
0,
(xdrproc_t)xdr_void,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Async event DomainEventCallbackIoErrorReason => 324 */
NULL,
0,
(xdrproc_t)xdr_void,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Async event DomainEventCallbackControlError => 325 */
NULL,
0,
(xdrproc_t)xdr_void,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Async event DomainEventCallbackBlockJob => 326 */
NULL,
0,
(xdrproc_t)xdr_void,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Async event DomainEventCallbackDiskChange => 327 */
NULL,
0,
(xdrproc_t)xdr_void,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Async event DomainEventCallbackTrayChange => 328 */
NULL,
0,
(xdrproc_t)xdr_void,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Async event DomainEventCallbackPMwakeup => 329 */
NULL,
0,
(xdrproc_t)xdr_void,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Async event DomainEventCallbackPMsuspend => 330 */
NULL,
0,
(xdrproc_t)xdr_void,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Async event DomainEventCallbackBalloonChange => 331 */
NULL,
0,
(xdrproc_t)xdr_void,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Async event DomainEventCallbackPMsuspendDisk => 332 */
NULL,
0,
(xdrproc_t)xdr_void,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Async event DomainEventCallbackDeviceRemoved => 333 */
NULL,
0,
(xdrproc_t)xdr_void,
0,
(xdrproc_t)xdr_void,
true,
0
},
{ /* Method DomainCoreDumpWithFormat => 334 */
remoteDispatchDomainCoreDumpWithFormatHelper,
sizeof(remote_domain_core_dump_with_format_args),
(xdrproc_t)xdr_remote_domain_core_dump_with_format_args,
0,
(xdrproc_t)xdr_void,
true,
0
},
};
size_t remoteNProcs = ARRAY_CARDINALITY(remoteProcs);
| vikhyath/libvirt-hyperv-r2-2012 | daemon/remote_dispatch.h | C | gpl-2.0 | 498,216 |
<?php
namespace Bookly\Backend;
use Bookly\Backend\Modules;
use Bookly\Frontend;
use Bookly\Lib;
/**
* Class Backend
* @package Bookly\Backend
*/
class Backend
{
public function __construct()
{
// Backend controllers.
$this->apearanceController = Modules\Appearance\Controller::getInstance();
$this->calendarController = Modules\Calendar\Controller::getInstance();
$this->customerController = Modules\Customers\Controller::getInstance();
$this->notificationsController = Modules\Notifications\Controller::getInstance();
$this->paymentController = Modules\Payments\Controller::getInstance();
$this->serviceController = Modules\Services\Controller::getInstance();
$this->smsController = Modules\Sms\Controller::getInstance();
$this->settingsController = Modules\Settings\Controller::getInstance();
$this->staffController = Modules\Staff\Controller::getInstance();
$this->couponsController = Modules\Coupons\Controller::getInstance();
$this->customFieldsController = Modules\CustomFields\Controller::getInstance();
$this->appointmentsController = Modules\Appointments\Controller::getInstance();
$this->debugController = Modules\Debug\Controller::getInstance();
// Frontend controllers that work via admin-ajax.php.
$this->bookingController = Frontend\Modules\Booking\Controller::getInstance();
$this->customerProfileController = Frontend\Modules\CustomerProfile\Controller::getInstance();
if ( ! Lib\Config::isPaymentDisabled( Lib\Entities\Payment::TYPE_AUTHORIZENET ) ) {
$this->authorizeNetController = Frontend\Modules\AuthorizeNet\Controller::getInstance();
}
if ( ! Lib\Config::isPaymentDisabled( Lib\Entities\Payment::TYPE_PAYULATAM ) ) {
$this->payulatamController = Frontend\Modules\PayuLatam\Controller::getInstance();
}
if ( ! Lib\Config::isPaymentDisabled( Lib\Entities\Payment::TYPE_STRIPE ) ) {
$this->stripeController = Frontend\Modules\Stripe\Controller::getInstance();
}
$this->wooCommerceController = Frontend\Modules\WooCommerce\Controller::getInstance();
add_action( 'admin_menu', array( $this, 'addAdminMenu' ) );
add_action( 'wp_loaded', array( $this, 'init' ) );
add_action( 'admin_init', array( $this, 'addTinyMCEPlugin' ) );
}
public function init()
{
if ( ! session_id() ) {
@session_start();
}
}
public function addTinyMCEPlugin()
{
new Modules\TinyMce\Plugin();
}
public function addAdminMenu()
{
/** @var \WP_User $current_user */
global $current_user;
// Translated submenu pages.
$calendar = __( 'Calendar', 'bookly' );
$appointments = __( 'Appointments', 'bookly' );
$staff_members = __( 'Staff Members', 'bookly' );
$services = __( 'Services', 'bookly' );
$sms = __( 'SMS Notifications', 'bookly' );
$notifications = __( 'Email Notifications', 'bookly' );
$customers = __( 'Customers', 'bookly' );
$payments = __( 'Payments', 'bookly' );
$appearance = __( 'Appearance', 'bookly' );
$settings = __( 'Settings', 'bookly' );
$coupons = __( 'Coupons', 'bookly' );
$custom_fields = __( 'Custom Fields', 'bookly' );
if ( $current_user->has_cap( 'administrator' ) || Lib\Entities\Staff::query()->where( 'wp_user_id', $current_user->ID )->count() ) {
if ( function_exists( 'add_options_page' ) ) {
$dynamic_position = '80.0000001' . mt_rand( 1, 1000 ); // position always is under `Settings`
add_menu_page( 'Bookly', 'Bookly', 'read', 'ab-system', '',
plugins_url( 'resources/images/menu.png', __FILE__ ), $dynamic_position );
add_submenu_page( 'ab-system', $calendar, $calendar, 'read', 'ab-calendar',
array( $this->calendarController, 'index' ) );
add_submenu_page( 'ab-system', $appointments, $appointments, 'manage_options', 'ab-appointments',
array( $this->appointmentsController, 'index' ) );
do_action( 'bookly_render_menu_after_appointments' );
if ( $current_user->has_cap( 'administrator' ) ) {
add_submenu_page( 'ab-system', $staff_members, $staff_members, 'manage_options', Modules\Staff\Controller::page_slug,
array( $this->staffController, 'index' ) );
} else {
if ( get_option( 'ab_settings_allow_staff_members_edit_profile' ) == 1 ) {
add_submenu_page( 'ab-system', __( 'Profile', 'bookly' ), __( 'Profile', 'bookly' ), 'read', Modules\Staff\Controller::page_slug,
array( $this->staffController, 'index' ) );
}
}
add_submenu_page( 'ab-system', $services, $services, 'manage_options', Modules\Services\Controller::page_slug,
array( $this->serviceController, 'index' ) );
add_submenu_page( 'ab-system', $customers, $customers, 'manage_options', Modules\Customers\Controller::page_slug,
array( $this->customerController, 'index' ) );
add_submenu_page( 'ab-system', $notifications, $notifications, 'manage_options', 'ab-notifications',
array( $this->notificationsController, 'index' ) );
add_submenu_page( 'ab-system', $sms, $sms, 'manage_options', Modules\Sms\Controller::page_slug,
array( $this->smsController, 'index' ) );
add_submenu_page( 'ab-system', $payments, $payments, 'manage_options', 'ab-payments',
array( $this->paymentController, 'index' ) );
add_submenu_page( 'ab-system', $appearance, $appearance, 'manage_options', 'ab-appearance',
array( $this->apearanceController, 'index' ) );
add_submenu_page( 'ab-system', $custom_fields, $custom_fields, 'manage_options', 'ab-custom-fields',
array( $this->customFieldsController, 'index' ) );
add_submenu_page( 'ab-system', $coupons, $coupons, 'manage_options', 'ab-coupons',
array( $this->couponsController, 'index' ) );
add_submenu_page( 'ab-system', $settings, $settings, 'manage_options', Modules\Settings\Controller::page_slug,
array( $this->settingsController, 'index' ) );
if ( isset ( $_GET['page'] ) && $_GET['page'] == 'ab-debug' ) {
add_submenu_page( 'ab-system', 'Debug', 'Debug', 'manage_options', 'ab-debug',
array( $this->debugController, 'index' ) );
}
global $submenu;
do_action( 'bookly_admin_menu', 'ab-system' );
unset ( $submenu['ab-system'][0] );
}
}
}
} | Tjdowdell/Susan_Batchelor_Website | wp-content/plugins/appointment-booking/backend/Backend.php | PHP | gpl-2.0 | 7,231 |
## See "d_bankfull" in update_flow_depth() ######## (2/21/13)
## See "(5/13/10)" for a temporary fix.
#------------------------------------------------------------------------
# Copyright (c) 2001-2014, Scott D. Peckham
#
# Sep 2014. Wrote new update_diversions().
# New standard names and BMI updates and testing.
# Nov 2013. Converted TopoFlow to a Python package.
# Feb 2013. Adapted to use EMELI framework.
# Jan 2013. Shared scalar doubles are now 0D numpy arrays.
# This makes them mutable and allows components with
# a reference to them to see them change.
# So far: Q_outlet, Q_peak, Q_min...
# Jan 2013. Revised handling of input/output names.
# Oct 2012. CSDMS Standard Names and BMI.
# May 2012. Commented out diversions.update() for now. #######
# May 2012. Shared scalar doubles are now 1-element 1D numpy arrays.
# This makes them mutable and allows components with
# a reference to them to see them change.
# So far: Q_outlet, Q_peak, Q_min...
# May 2010. Changes to initialize() and read_cfg_file()
# Mar 2010. Changed codes to code, widths to width,
# angles to angle, nvals to nval, z0vals to z0val,
# slopes to slope (for GUI tools and consistency
# across all process components)
# Aug 2009. Updates.
# Jul 2009. Updates.
# May 2009. Updates.
# Jan 2009. Converted from IDL.
#-----------------------------------------------------------------------
# NB! In the CFG file, change MANNING and LAW_OF_WALL flags to
# a single string entry like "friction method". #########
#-----------------------------------------------------------------------
# Notes: Set self.u in manning and law_of_wall functions ??
# Update friction factor in manning() and law_of_wall() ?
# Double check how Rh is used in law_of_the_wall().
# d8_flow has "flow_grids", but this one has "codes".
# Make sure values are not stored twice.
#-----------------------------------------------------------------------
#-----------------------------------------------------------------------
# NOTES: This file defines a "base class" for channelized flow
# components as well as functions used by most or
# all channel flow methods. The methods of this class
# (especially "update_velocity") should be over-ridden as
# necessary for different methods of modeling channelized
# flow. See channels_kinematic_wave.py,
# channels_diffusive_wave.py and channels_dynamic_wave.py.
#-----------------------------------------------------------------------
# NOTES: update_free_surface_slope() is called by the
# update_velocity() methods of channels_diffusive_wave.py
# and channels_dynamic_wave.py.
#-----------------------------------------------------------------------
#
# class channels_component
#
# ## get_attribute() # (defined in each channel component)
# get_input_var_names() # (5/15/12)
# get_output_var_names() # (5/15/12)
# get_var_name() # (5/15/12)
# get_var_units() # (5/15/12)
#-----------------------------
# set_constants()
# initialize()
# update()
# finalize()
# set_computed_input_vars() # (5/11/10)
#----------------------------------
# initialize_d8_vars() ########
# initialize_computed_vars()
# initialize_diversion_vars() # (9/22/14)
# initialize_outlet_values()
# initialize_peak_values()
# initialize_min_and_max_values() # (2/3/13)
#-------------------------------------
# update_R()
# update_R_integral()
# update_discharge()
# update_diversions() # (9/22/14)
# update_flow_volume()
# update_flow_depth()
# update_free_surface_slope()
# update_shear_stress() # (9/9/14, depth-slope product)
# update_shear_speed() # (9/9/14)
# update_trapezoid_Rh()
# update_friction_factor() # (9/9/14)
#----------------------------------
# update_velocity() # (override as needed)
# update_velocity_on_edges()
# update_froude_number() # (9/9/14)
#----------------------------------
# update_outlet_values()
# update_peak_values() # (at the main outlet)
# update_Q_out_integral() # (moved here from basins.py)
# update_mins_and_maxes() # (don't add into update())
# check_flow_depth()
# check_flow_velocity()
#----------------------------------
# open_input_files()
# read_input_files()
# close_input_files()
#----------------------------------
# update_outfile_names()
# bundle_output_files() # (9/21/14. Not used yet)
# open_output_files()
# write_output_files()
# close_output_files()
# save_grids()
# save_pixel_values()
#----------------------------------
# manning_formula()
# law_of_the_wall()
# print_status_report()
# remove_bad_slopes()
# Functions: # (stand-alone versions of these)
# Trapezoid_Rh()
# Manning_Formula()
# Law_of_the_Wall()
#-----------------------------------------------------------------------
import numpy as np
import os, os.path
from topoflow.utils import BMI_base
# from topoflow.utils import d8_base
from topoflow.utils import file_utils ###
from topoflow.utils import model_input
from topoflow.utils import model_output
from topoflow.utils import ncgs_files ###
from topoflow.utils import ncts_files ###
from topoflow.utils import rtg_files ###
from topoflow.utils import text_ts_files ###
from topoflow.utils import tf_d8_base as d8_base
from topoflow.utils import tf_utils
#-----------------------------------------------------------------------
class channels_component( BMI_base.BMI_component ):
#-----------------------------------------------------------
# Note: rainfall_volume_flux *must* be liquid-only precip.
#-----------------------------------------------------------
_input_var_names = [
'atmosphere_water__rainfall_volume_flux', # (P_rain)
'glacier_ice__melt_volume_flux', # (MR)
## 'land_surface__elevation',
## 'land_surface__slope',
'land_surface_water__baseflow_volume_flux', # (GW)
'land_surface_water__evaporation_volume_flux', # (ET)
'soil_surface_water__infiltration_volume_flux', # (IN)
'snowpack__melt_volume_flux', # (SM)
'water-liquid__mass-per-volume_density' ] # (rho_H2O)
#------------------------------------------------------------------
# 'canals__count', # n_canals
# 'canals_entrance__x_coordinate', # canals_in_x
# 'canals_entrance__y_coordinate', # canals_in_y
# 'canals_entrance_water__volume_fraction', # Q_canals_fraction
# 'canals_exit__x_coordinate', # canals_out_x
# 'canals_exit__y_coordinate', # canals_out_y
# 'canals_exit_water__volume_flow_rate', # Q_canals_out
# 'sinks__count', # n_sinks
# 'sinks__x_coordinate', # sinks_x
# 'sinks__y_coordinate', # sinks_y
# 'sinks_water__volume_flow_rate', # Q_sinks
# 'sources__count', # n_sources
# 'sources__x_coordinate', # sources_x
# 'sources__y_coordinate', # sources_y
# 'sources_water__volume_flow_rate' ] # Q_sources
#----------------------------------
# Maybe add these out_vars later.
#----------------------------------
# ['time_sec', 'time_min' ]
_output_var_names = [
'basin_outlet_water_flow__half_of_fanning_friction_factor', # f_outlet
'basin_outlet_water_x-section__mean_depth', # d_outlet
'basin_outlet_water_x-section__peak_time_of_depth', # Td_peak
'basin_outlet_water_x-section__peak_time_of_volume_flow_rate', # T_peak
'basin_outlet_water_x-section__peak_time_of_volume_flux', # Tu_peak
'basin_outlet_water_x-section__time_integral_of_volume_flow_rate', # vol_Q
'basin_outlet_water_x-section__time_max_of_mean_depth', # d_peak
'basin_outlet_water_x-section__time_max_of_volume_flow_rate', # Q_peak
'basin_outlet_water_x-section__time_max_of_volume_flux', # u_peak
'basin_outlet_water_x-section__volume_flow_rate', # Q_outlet
'basin_outlet_water_x-section__volume_flux', # u_outlet
#--------------------------------------------------
'canals_entrance_water__volume_flow_rate', # Q_canals_in
#--------------------------------------------------
'channel_bottom_surface__slope', # S_bed
'channel_bottom_water_flow__domain_max_of_log_law_roughness_length', # z0val_max
'channel_bottom_water_flow__domain_min_of_log_law_roughness_length', # z0val_min
'channel_bottom_water_flow__log_law_roughness_length', # z0val
'channel_bottom_water_flow__magnitude_of_shear_stress', # tau
'channel_bottom_water_flow__shear_speed', # u_star
'channel_centerline__sinuosity', # sinu
'channel_water__volume', # vol
'channel_water_flow__froude_number', # froude
'channel_water_flow__half_of_fanning_friction_factor', # f
'channel_water_flow__domain_max_of_manning_n_parameter', # nval_max
'channel_water_flow__domain_min_of_manning_n_parameter', # nval_min
'channel_water_flow__manning_n_parameter', # nval
'channel_water_surface__slope', # S_free
#---------------------------------------------------
# These might only be available at the end of run.
#---------------------------------------------------
'channel_water_x-section__domain_max_of_mean_depth', # d_max
'channel_water_x-section__domain_min_of_mean_depth', # d_min
'channel_water_x-section__domain_max_of_volume_flow_rate', # Q_max
'channel_water_x-section__domain_min_of_volume_flow_rate', # Q_min
'channel_water_x-section__domain_max_of_volume_flux', # u_max
'channel_water_x-section__domain_min_of_volume_flux', # u_min
#---------------------------------------------------------------------
'channel_water_x-section__hydraulic_radius', # Rh
'channel_water_x-section__initial_mean_depth', # d0
'channel_water_x-section__mean_depth', # d
'channel_water_x-section__volume_flow_rate', # Q
'channel_water_x-section__volume_flux', # u
'channel_water_x-section__wetted_area', # A_wet
'channel_water_x-section__wetted_perimeter', # P_wet
## 'channel_water_x-section_top__width', # (not used)
'channel_x-section_trapezoid_bottom__width', # width
'channel_x-section_trapezoid_side__flare_angle', # angle
'land_surface_water__runoff_volume_flux', # R
'land_surface_water__domain_time_integral_of_runoff_volume_flux', # vol_R
'model__time_step', # dt
'model_grid_cell__area' ] # da
_var_name_map = {
'atmosphere_water__rainfall_volume_flux': 'P_rain',
'glacier_ice__melt_volume_flux': 'MR',
## 'land_surface__elevation': 'DEM',
## 'land_surface__slope': 'S_bed',
'land_surface_water__baseflow_volume_flux': 'GW',
'land_surface_water__evaporation_volume_flux': 'ET',
'soil_surface_water__infiltration_volume_flux': 'IN',
'snowpack__melt_volume_flux': 'SM',
'water-liquid__mass-per-volume_density': 'rho_H2O',
#------------------------------------------------------------------------
'basin_outlet_water_flow__half_of_fanning_friction_factor':'f_outlet',
'basin_outlet_water_x-section__mean_depth': 'd_outlet',
'basin_outlet_water_x-section__peak_time_of_depth': 'Td_peak',
'basin_outlet_water_x-section__peak_time_of_volume_flow_rate': 'T_peak',
'basin_outlet_water_x-section__peak_time_of_volume_flux': 'Tu_peak',
'basin_outlet_water_x-section__volume_flow_rate': 'Q_outlet',
'basin_outlet_water_x-section__volume_flux': 'u_outlet',
'basin_outlet_water_x-section__time_integral_of_volume_flow_rate': 'vol_Q',
'basin_outlet_water_x-section__time_max_of_mean_depth': 'd_peak',
'basin_outlet_water_x-section__time_max_of_volume_flow_rate':'Q_peak',
'basin_outlet_water_x-section__time_max_of_volume_flux': 'u_peak',
#--------------------------------------------------------------------------
'canals_entrance_water__volume_flow_rate': 'Q_canals_in',
#--------------------------------------------------------------------------
'channel_bottom_surface__slope': 'S_bed',
'channel_bottom_water_flow__domain_max_of_log_law_roughness_length': 'z0val_max',
'channel_bottom_water_flow__domain_min_of_log_law_roughness_length': 'z0val_min',
'channel_bottom_water_flow__log_law_roughness_length': 'z0val',
'channel_bottom_water_flow__magnitude_of_shear_stress': 'tau',
'channel_bottom_water_flow__shear_speed': 'u_star',
'channel_centerline__sinuosity': 'sinu',
'channel_water__volume': 'vol',
'channel_water_flow__domain_max_of_manning_n_parameter': 'nval_max',
'channel_water_flow__domain_min_of_manning_n_parameter': 'nval_min',
'channel_water_flow__froude_number': 'froude',
'channel_water_flow__half_of_fanning_friction_factor': 'f',
'channel_water_flow__manning_n_parameter': 'nval',
'channel_water_surface__slope': 'S_free',
#-----------------------------------------------------------------------
'channel_water_x-section__domain_max_of_mean_depth': 'd_max',
'channel_water_x-section__domain_min_of_mean_depth': 'd_min',
'channel_water_x-section__domain_max_of_volume_flow_rate': 'Q_max',
'channel_water_x-section__domain_min_of_volume_flow_rate': 'Q_min',
'channel_water_x-section__domain_max_of_volume_flux': 'u_max',
'channel_water_x-section__domain_min_of_volume_flux': 'u_min',
#-----------------------------------------------------------------------
'channel_water_x-section__hydraulic_radius': 'Rh',
'channel_water_x-section__initial_mean_depth': 'd0',
'channel_water_x-section__mean_depth': 'd',
'channel_water_x-section__volume_flow_rate': 'Q',
'channel_water_x-section__volume_flux': 'u',
'channel_water_x-section__wetted_area': 'A_wet',
'channel_water_x-section__wetted_perimeter': 'P_wet',
## 'channel_water_x-section_top__width': # (not used)
'channel_x-section_trapezoid_bottom__width': 'width', ####
'channel_x-section_trapezoid_side__flare_angle': 'angle', ####
'land_surface_water__domain_time_integral_of_runoff_volume_flux': 'vol_R',
'land_surface_water__runoff_volume_flux': 'R',
'model__time_step': 'dt',
'model_grid_cell__area': 'da',
#------------------------------------------------------------------
'canals__count': 'n_canals',
'canals_entrance__x_coordinate': 'canals_in_x',
'canals_entrance__y_coordinate': 'canals_in_y',
'canals_entrance_water__volume_fraction': 'Q_canals_fraction',
'canals_exit__x_coordinate': 'canals_out_x',
'canals_exit__y_coordinate': 'canals_out_y',
'canals_exit_water__volume_flow_rate': 'Q_canals_out',
'sinks__count': 'n_sinks',
'sinks__x_coordinate': 'sinks_x',
'sinks__y_coordinate': 'sinks_y',
'sinks_water__volume_flow_rate': 'Q_sinks',
'sources__count': 'n_sources',
'sources__x_coordinate': 'sources_x',
'sources__y_coordinate': 'sources_y',
'sources_water__volume_flow_rate': 'Q_sources' }
#------------------------------------------------
# Create an "inverse var name map"
# inv_map = dict(zip(map.values(), map.keys()))
#------------------------------------------------
## _long_name_map = dict( zip(_var_name_map.values(),
## _var_name_map.keys() ) )
_var_units_map = {
'atmosphere_water__rainfall_volume_flux': 'm s-1',
'glacier_ice__melt_volume_flux': 'm s-1',
## 'land_surface__elevation': 'm',
## 'land_surface__slope': '1',
'land_surface_water__baseflow_volume_flux': 'm s-1',
'land_surface_water__evaporation_volume_flux': 'm s-1',
'soil_surface_water__infiltration_volume_flux': 'm s-1',
'snowpack__melt_volume_flux': 'm s-1',
'water-liquid__mass-per-volume_density': 'kg m-3',
#---------------------------------------------------------------------------
'basin_outlet_water_flow__half_of_fanning_friction_factor': '1',
'basin_outlet_water_x-section__mean_depth': 'm',
'basin_outlet_water_x-section__peak_time_of_depth': 'min',
'basin_outlet_water_x-section__peak_time_of_volume_flow_rate': 'min',
'basin_outlet_water_x-section__peak_time_of_volume_flux': 'min',
'basin_outlet_water_x-section__time_integral_of_volume_flow_rate': 'm3',
'basin_outlet_water_x-section__time_max_of_mean_depth': 'm',
'basin_outlet_water_x-section__time_max_of_volume_flow_rate': 'm3 s-1',
'basin_outlet_water_x-section__time_max_of_volume_flux': 'm s-1',
'basin_outlet_water_x-section__volume_flow_rate': 'm3',
'basin_outlet_water_x-section__volume_flux': 'm s-1',
#---------------------------------------------------------------------------
'canals_entrance_water__volume_flow_rate': 'm3 s-1',
#---------------------------------------------------------------------------
'channel_bottom_surface__slope': '1',
'channel_bottom_water_flow__domain_max_of_log_law_roughness_length': 'm',
'channel_bottom_water_flow__domain_min_of_log_law_roughness_length': 'm',
'channel_bottom_water_flow__log_law_roughness_length': 'm',
'channel_bottom_water_flow__magnitude_of_shear_stress': 'kg m-1 s-2',
'channel_bottom_water_flow__shear_speed': 'm s-1',
'channel_centerline__sinuosity': '1',
'channel_water__volume': 'm3',
'channel_water_flow__froude_number': '1',
'channel_water_flow__half_of_fanning_friction_factor': '1',
'channel_water_flow__manning_n_parameter': 'm-1/3 s',
'channel_water_flow__domain_max_of_manning_n_parameter': 'm-1/3 s',
'channel_water_flow__domain_min_of_manning_n_parameter': 'm-1/3 s',
'channel_water_surface__slope': '1',
#--------------------------------------------------------------------
'channel_water_x-section__domain_max_of_mean_depth': 'm',
'channel_water_x-section__domain_min_of_mean_depth': 'm',
'channel_water_x-section__domain_max_of_volume_flow_rate': 'm3 s-1',
'channel_water_x-section__domain_min_of_volume_flow_rate': 'm3 s-1',
'channel_water_x-section__domain_max_of_volume_flux': 'm s-1',
'channel_water_x-section__domain_min_of_volume_flux': 'm s-1',
#--------------------------------------------------------------------
'channel_water_x-section__hydraulic_radius': 'm',
'channel_water_x-section__initial_mean_depth': 'm',
'channel_water_x-section__mean_depth': 'm',
'channel_water_x-section__volume_flow_rate': 'm3 s-1',
'channel_water_x-section__volume_flux': 'm s-1',
'channel_water_x-section__wetted_area': 'm2',
'channel_water_x-section__wetted_perimeter': 'm',
'channel_x-section_trapezoid_bottom__width': 'm',
'channel_x-section_trapezoid_side__flare_angle': 'rad', # CHECKED
'land_surface_water__domain_time_integral_of_runoff_volume_flux': 'm3',
'land_surface_water__runoff_volume_flux': 'm s-1',
'model__time_step': 's',
'model_grid_cell__area': 'm2',
#------------------------------------------------------------------
'canals__count': '1',
'canals_entrance__x_coordinate': 'm',
'canals_entrance__y_coordinate': 'm',
'canals_entrance_water__volume_fraction': '1',
'canals_exit__x_coordinate': 'm',
'canals_exit__y_coordinate': 'm',
'canals_exit_water__volume_flow_rate': 'm3 s-1',
'sinks__count': '1',
'sinks__x_coordinate': 'm',
'sinks__y_coordinate': 'm',
'sinks_water__volume_flow_rate': 'm3 s-1',
'sources__count': '1',
'sources__x_coordinate': 'm',
'sources__y_coordinate': 'm',
'sources_water__volume_flow_rate': 'm3 s-1' }
#------------------------------------------------
# Return NumPy string arrays vs. Python lists ?
#------------------------------------------------
## _input_var_names = np.array( _input_var_names )
## _output_var_names = np.array( _output_var_names )
#-------------------------------------------------------------------
def get_input_var_names(self):
#--------------------------------------------------------
# Note: These are currently variables needed from other
# components vs. those read from files or GUI.
#--------------------------------------------------------
return self._input_var_names
# get_input_var_names()
#-------------------------------------------------------------------
def get_output_var_names(self):
return self._output_var_names
# get_output_var_names()
#-------------------------------------------------------------------
def get_var_name(self, long_var_name):
return self._var_name_map[ long_var_name ]
# get_var_name()
#-------------------------------------------------------------------
def get_var_units(self, long_var_name):
return self._var_units_map[ long_var_name ]
# get_var_units()
#-------------------------------------------------------------------
## def get_var_type(self, long_var_name):
##
## #---------------------------------------
## # So far, all vars have type "double",
## # but use the one in BMI_base instead.
## #---------------------------------------
## return 'float64'
##
## # get_var_type()
#-------------------------------------------------------------------
def set_constants(self):
#------------------------
# Define some constants
#------------------------
self.g = np.float64(9.81) # (gravitation const.)
self.aval = np.float64(0.476) # (integration const.)
self.kappa = np.float64(0.408) # (von Karman's const.)
self.law_const = np.sqrt(self.g) / self.kappa
self.one_third = np.float64(1.0) / 3.0
self.two_thirds = np.float64(2.0) / 3.0
self.deg_to_rad = np.pi / 180.0
# set_constants()
#-------------------------------------------------------------------
def initialize(self, cfg_file=None, mode="nondriver", SILENT=False):
if not(SILENT):
print ' '
print 'Channels component: Initializing...'
self.status = 'initializing' # (OpenMI 2.0 convention)
self.mode = mode
self.cfg_file = cfg_file
#-----------------------------------------------
# Load component parameters from a config file
#-----------------------------------------------
self.set_constants() # (12/7/09)
# print 'CHANNELS calling initialize_config_vars()...'
self.initialize_config_vars()
# print 'CHANNELS calling read_grid_info()...'
self.read_grid_info()
#print 'CHANNELS calling initialize_basin_vars()...'
self.initialize_basin_vars() # (5/14/10)
#-----------------------------------------
# This must come before "Disabled" test.
#-----------------------------------------
# print 'CHANNELS calling initialize_time_vars()...'
self.initialize_time_vars()
#----------------------------------
# Has component been turned off ?
#----------------------------------
if (self.comp_status == 'Disabled'):
if not(SILENT):
print 'Channels component: Disabled.'
self.SAVE_Q_GRIDS = False # (It is True by default.)
self.SAVE_Q_PIXELS = False # (It is True by default.)
self.DONE = True
self.status = 'initialized' # (OpenMI 2.0 convention)
return
## print '################################################'
## print 'min(d0), max(d0) =', self.d0.min(), self.d0.max()
## print '################################################'
#---------------------------------------------
# Open input files needed to initialize vars
#---------------------------------------------
# Can't move read_input_files() to start of
# update(), since initial values needed here.
#---------------------------------------------
# print 'CHANNELS calling open_input_files()...'
self.open_input_files()
print 'CHANNELS calling read_input_files()...'
self.read_input_files()
#-----------------------
# Initialize variables
#-----------------------
print 'CHANNELS calling initialize_d8_vars()...'
self.initialize_d8_vars() # (depend on D8 flow grid)
print 'CHANNELS calling initialize_computed_vars()...'
self.initialize_computed_vars()
#--------------------------------------------------
# (5/12/10) I think this is obsolete now.
#--------------------------------------------------
# Make sure self.Q_ts_file is not NULL (12/22/05)
# This is only output file that is set by default
# and is still NULL if user hasn't opened the
# output var dialog for the channel process.
#--------------------------------------------------
## if (self.SAVE_Q_PIXELS and (self.Q_ts_file == '')):
## self.Q_ts_file = (self.case_prefix + '_0D-Q.txt')
self.open_output_files()
self.status = 'initialized' # (OpenMI 2.0 convention)
# initialize()
#-------------------------------------------------------------------
## def update(self, dt=-1.0, time_seconds=None):
def update(self, dt=-1.0):
#---------------------------------------------
# Note that u and d from previous time step
# must be used on RHS of the equations here.
#---------------------------------------------
self.status = 'updating' # (OpenMI 2.0 convention)
#-------------------------------------------------------
# There may be times where we want to call this method
# even if component is not the driver. But note that
# the TopoFlow driver also makes this same call.
#-------------------------------------------------------
if (self.mode == 'driver'):
self.print_time_and_value(self.Q_outlet, 'Q_out', '[m^3/s]')
### interval=0.5) # [seconds]
# For testing (5/19/12)
# self.print_time_and_value(self.Q_outlet, 'Q_out', '[m^3/s] CHANNEL')
## DEBUG = True
DEBUG = False
#-------------------------
# Update computed values
#-------------------------
if (DEBUG): print '#### Calling update_R()...'
self.update_R()
if (DEBUG): print '#### Calling update_R_integral()...'
self.update_R_integral()
if (DEBUG): print '#### Calling update_discharge()...'
self.update_discharge()
if (DEBUG): print '#### Calling update_diversions()...'
self.update_diversions()
if (DEBUG): print '#### Calling update_flow_volume()...'
self.update_flow_volume()
if (DEBUG): print '#### Calling update_flow_depth()...'
self.update_flow_depth()
#-----------------------------------------------------------------
if not(self.DYNAMIC_WAVE):
if (DEBUG): print '#### Calling update_trapezoid_Rh()...'
self.update_trapezoid_Rh()
# print 'Rhmin, Rhmax =', self.Rh.min(), self.Rh.max()a
#-----------------------------------------------------------------
# (9/9/14) Moved this here from update_velocity() methods.
#-----------------------------------------------------------------
if not(self.KINEMATIC_WAVE):
if (DEBUG): print '#### Calling update_free_surface_slope()...'
self.update_free_surface_slope()
if (DEBUG): print '#### Calling update_shear_stress()...'
self.update_shear_stress()
if (DEBUG): print '#### Calling update_shear_speed()...'
self.update_shear_speed()
#-----------------------------------------------------------------
# Must update friction factor before velocity for DYNAMIC_WAVE.
#-----------------------------------------------------------------
if (DEBUG): print '#### Calling update_friction_factor()...'
self.update_friction_factor()
#-----------------------------------------------------------------
if (DEBUG): print '#### Calling update_velocity()...'
self.update_velocity()
self.update_velocity_on_edges() # (set to zero)
if (DEBUG): print '#### Calling update_froude_number()...'
self.update_froude_number()
#-----------------------------------------------------------------
## print 'Rmin, Rmax =', self.R.min(), self.R.max()
## print 'Qmin, Qmax =', self.Q.min(), self.Q.max()
## print 'umin, umax =', self.u.min(), self.u.max()
## print 'dmin, dmax =', self.d.min(), self.d.max()
## print 'nmin, nmax =', self.nval.min(), self.nval.max()
## print 'Rhmin, Rhmax =', self.Rh.min(), self.Rh.max()
## print 'Smin, Smax =', self.S_bed.min(), self.S_bed.max()
if (DEBUG): print '#### Calling update_outlet_values()...'
self.update_outlet_values()
if (DEBUG): print '#### Calling update peak values()...'
self.update_peak_values()
if (DEBUG): print '#### Calling update_Q_out_integral()...'
self.update_Q_out_integral()
#---------------------------------------------
# This takes extra time and is now done
# only at the end, in finalize(). (8/19/13)
#---------------------------------------------
# But then "topoflow_driver" doesn't get
# correctly updated values for some reason.
#---------------------------------------------
## self.update_mins_and_maxes()
#------------------------
# Check computed values
#------------------------
D_OK = self.check_flow_depth()
U_OK = self.check_flow_velocity()
OK = (D_OK and U_OK)
#-------------------------------------------
# Read from files as needed to update vars
#-----------------------------------------------------
# NB! This is currently not needed for the "channel
# process" because values don't change over time and
# read_input_files() is called by initialize().
#-----------------------------------------------------
# if (self.time_index > 0):
# self.read_input_files()
#----------------------------------------------
# Write user-specified data to output files ?
#----------------------------------------------
# Components use own self.time_sec by default.
#-----------------------------------------------
if (DEBUG): print '#### Calling write_output_files()...'
self.write_output_files()
## self.write_output_files( time_seconds )
#-----------------------------
# Update internal clock
# after write_output_files()
#-----------------------------
if (DEBUG): print '#### Calling update_time()'
self.update_time( dt )
if (OK):
self.status = 'updated' # (OpenMI 2.0 convention)
else:
self.status = 'failed'
self.DONE = True
# update()
#-------------------------------------------------------------------
def finalize(self):
#---------------------------------------------------
# We can compute mins and maxes in the final grids
# here, but the framework will not then pass them
# to any component (e.g. topoflow_driver) that may
# need them.
#---------------------------------------------------
REPORT = True
self.update_mins_and_maxes( REPORT=REPORT ) ## (2/6/13)
self.print_final_report(comp_name='Channels component')
self.status = 'finalizing' # (OpenMI)
self.close_input_files() # TopoFlow input "data streams"
self.close_output_files()
self.status = 'finalized' # (OpenMI)
#---------------------------
# Release all of the ports
#----------------------------------------
# Make this call in "finalize()" method
# of the component's CCA Imple file
#----------------------------------------
# self.release_cca_ports( d_services )
# finalize()
#-------------------------------------------------------------------
def set_computed_input_vars(self):
#---------------------------------------------------------------
# Note: The initialize() method calls initialize_config_vars()
# (in BMI_base.py), which calls this method at the end.
#--------------------------------------------------------------
cfg_extension = self.get_attribute( 'cfg_extension' ).lower()
# cfg_extension = self.get_cfg_extension().lower()
self.KINEMATIC_WAVE = ("kinematic" in cfg_extension)
self.DIFFUSIVE_WAVE = ("diffusive" in cfg_extension)
self.DYNAMIC_WAVE = ("dynamic" in cfg_extension)
##########################################################
# (5/17/12) If MANNING, we need to set z0vals to -1 so
# they are always defined for use with new framework.
##########################################################
if (self.MANNING):
if (self.nval != None):
self.nval = np.float64( self.nval ) #### 10/9/10, NEED
self.nval_min = self.nval.min()
self.nval_max = self.nval.max()
#-----------------------------------
self.z0val = np.float64(-1)
self.z0val_min = np.float64(-1)
self.z0val_max = np.float64(-1)
if (self.LAW_OF_WALL):
if (self.z0val != None):
self.z0val = np.float64( self.z0val ) #### (10/9/10)
self.z0val_min = self.z0val.min()
self.z0val_max = self.z0val.max()
#-----------------------------------
self.nval = np.float64(-1)
self.nval_min = np.float64(-1)
self.nval_max = np.float64(-1)
#-------------------------------------------
# These currently can't be set to anything
# else in the GUI, but need to be defined.
#-------------------------------------------
self.code_type = 'Grid'
self.slope_type = 'Grid'
#---------------------------------------------------------
# Make sure that all "save_dts" are larger or equal to
# the specified process dt. There is no point in saving
# results more often than they change.
# Issue a message to this effect if any are smaller ??
#---------------------------------------------------------
self.save_grid_dt = np.maximum(self.save_grid_dt, self.dt)
self.save_pixels_dt = np.maximum(self.save_pixels_dt, self.dt)
#---------------------------------------------------
# This is now done in CSDMS_base.read_config_gui()
# for any var_name that starts with "SAVE_".
#---------------------------------------------------
# self.SAVE_Q_GRID = (self.SAVE_Q_GRID == 'Yes')
# set_computed_input_vars()
#-------------------------------------------------------------------
def initialize_d8_vars(self):
#---------------------------------------------
# Compute and store a variety of (static) D8
# flow grid variables. Embed structure into
# the "channel_base" component.
#---------------------------------------------
self.d8 = d8_base.d8_component()
###############################################
# (5/13/10) Do next line here for now, until
# the d8 cfg_file includes static prefix.
# Same is done in GW_base.py.
###############################################
# tf_d8_base.read_grid_info() also needs
# in_directory to be set. (10/27/11)
###############################################
#--------------------------------------------------
# D8 component builds its cfg filename from these
#--------------------------------------------------
self.d8.site_prefix = self.site_prefix
self.d8.in_directory = self.in_directory
self.d8.initialize( cfg_file=None,
SILENT=self.SILENT,
REPORT=self.REPORT )
## self.code = self.d8.code # Don't need this.
#-------------------------------------------
# We'll need this once we shift from using
# "tf_d8_base.py" to the new "d8_base.py"
#-------------------------------------------
# self.d8.update(self.time, SILENT=False, REPORT=True)
# initialize_d8_vars()
#-------------------------------------------------------------
def initialize_computed_vars(self):
#-----------------------------------------------
# Convert bank angles from degrees to radians.
#-----------------------------------------------
self.angle = self.angle * self.deg_to_rad # [radians]
#------------------------------------------------
# 8/29/05. Multiply ds by (unitless) sinuosity
# Orig. ds is used by subsurface flow
#------------------------------------------------
# NB! We should also divide slopes in S_bed by
# the sinuosity, as now done here.
#----------------------------------------------------
# NB! This saves a modified version of ds that
# is only used within the "channels" component.
# The original "ds" is stored within the
# topoflow model component and is used for
# subsurface flow, etc.
#----------------------------------------------------
### self.d8.ds_chan = (self.sinu * ds)
### self.ds = (self.sinu * self.d8.ds)
self.d8.ds = (self.sinu * self.d8.ds) ### USE LESS MEMORY
###################################################
###################################################
### S_bed = (S_bed / self.sinu) #*************
self.slope = (self.slope / self.sinu)
self.S_bed = self.slope
###################################################
###################################################
#---------------------------
# Initialize spatial grids
#-----------------------------------------------
# NB! It is not a good idea to initialize the
# water depth grid to a nonzero scalar value.
#-----------------------------------------------
print 'Initializing u, f, d grids...'
self.u = np.zeros([self.ny, self.nx], dtype='Float64')
self.f = np.zeros([self.ny, self.nx], dtype='Float64')
self.d = np.zeros([self.ny, self.nx], dtype='Float64') + self.d0
#########################################################
# Add this on (2/3/13) so make the TF driver happy
# during its initialize when it gets reference to R.
# But in "update_R()", be careful not to break the ref.
# "Q" may be subject to the same issue.
#########################################################
self.Q = np.zeros([self.ny, self.nx], dtype='Float64')
self.R = np.zeros([self.ny, self.nx], dtype='Float64')
#---------------------------------------------------
# Initialize new grids. Is this needed? (9/13/14)
#---------------------------------------------------
self.tau = np.zeros([self.ny, self.nx], dtype='Float64')
self.u_star = np.zeros([self.ny, self.nx], dtype='Float64')
self.froude = np.zeros([self.ny, self.nx], dtype='Float64')
#---------------------------------------
# These are used to check mass balance
#---------------------------------------
self.vol_R = self.initialize_scalar( 0, dtype='float64')
self.vol_Q = self.initialize_scalar( 0, dtype='float64')
#-------------------------------------------
# Make sure all slopes are valid & nonzero
# since otherwise flow will accumulate
#-------------------------------------------
if (self.KINEMATIC_WAVE):
self.remove_bad_slopes() #(3/8/07. Only Kin Wave case)
#----------------------------------------
# Initial volume of water in each pixel
#-----------------------------------------------------------
# Note: angles were read as degrees & converted to radians
#-----------------------------------------------------------
L2 = self.d * np.tan(self.angle)
self.A_wet = self.d * (self.width + L2)
self.P_wet = self.width + (np.float64(2) * self.d / np.cos(self.angle) )
self.vol = self.A_wet * self.d8.ds # [m3]
#-------------------------------------------------------
# Note: depth is often zero at the start of a run, and
# both width and then P_wet are also zero in places.
# Therefore initialize Rh as shown.
#-------------------------------------------------------
self.Rh = np.zeros([self.ny, self.nx], dtype='Float64')
## self.Rh = self.A_wet / self.P_wet # [m]
## print 'P_wet.min() =', self.P_wet.min()
## print 'width.min() =', self.width.min()
## self.initialize_diversion_vars() # (9/22/14)
self.initialize_outlet_values()
self.initialize_peak_values()
self.initialize_min_and_max_values() ## (2/3/13)
#########################################
# Maybe save all refs in a dictionary
# called "self_values" here ? (2/19/13)
# Use a "reverse" var_name mapping?
# inv_map = dict(zip(map.values(), map.keys()))
#########################################
## w = np.where( self.width <= 0 )
## nw = np.size( w[0] ) # (This is correct for 1D or 2D.)
## if (nw > 0):
## print 'WARNING:'
## print 'Number of locations where width==0 =', nw
## if (nw < 10):
## print 'locations =', w
## print ' '
# initialize_computed_vars()
#-------------------------------------------------------------
def initialize_diversion_vars(self):
#-----------------------------------------
# Compute source IDs from xy coordinates
#-----------------------------------------
source_rows = np.int32( self.sources_y / self.ny )
source_cols = np.int32( self.sources_x / self.nx )
self.source_IDs = (source_rows, source_cols)
## self.source_IDs = (source_rows * self.nx) + source_cols
#---------------------------------------
# Compute sink IDs from xy coordinates
#---------------------------------------
sink_rows = np.int32( self.sinks_y / self.ny )
sink_cols = np.int32( self.sinks_x / self.nx )
self.sink_IDs = (sink_rows, sink_cols)
## self.sink_IDs = (sink_rows * self.nx) + sink_cols
#-------------------------------------------------
# Compute canal entrance IDs from xy coordinates
#-------------------------------------------------
canal_in_rows = np.int32( self.canals_in_y / self.ny )
canal_in_cols = np.int32( self.canals_in_x / self.nx )
self.canal_in_IDs = (canal_in_rows, canal_in_cols)
## self.canal_in_IDs = (canal_in_rows * self.nx) + canal_in_cols
#---------------------------------------------
# Compute canal exit IDs from xy coordinates
#---------------------------------------------
canal_out_rows = np.int32( self.canals_out_y / self.ny )
canal_out_cols = np.int32( self.canals_out_x / self.nx )
self.canal_out_IDs = (canal_out_rows, canal_out_cols)
## self.canal_out_IDs = (canal_out_rows * self.nx) + canal_out_cols
#--------------------------------------------------
# This will be computed from Q_canal_fraction and
# self.Q and then passed back to Diversions
#--------------------------------------------------
self.Q_canals_in = np.array( self.n_sources, dtype='float64' )
# initialize_diversion_vars()
#-------------------------------------------------------------------
def initialize_outlet_values(self):
#---------------------------------------------------
# Note: These are retrieved and used by TopoFlow
# for the stopping condition. TopoFlow
# receives a reference to these, but in
# order to see the values change they need
# to be stored as mutable, 1D numpy arrays.
#---------------------------------------------------
# Note: Q_last is internal to TopoFlow.
#---------------------------------------------------
# self.Q_outlet = self.Q[ self.outlet_ID ]
self.Q_outlet = self.initialize_scalar(0, dtype='float64')
self.u_outlet = self.initialize_scalar(0, dtype='float64')
self.d_outlet = self.initialize_scalar(0, dtype='float64')
self.f_outlet = self.initialize_scalar(0, dtype='float64')
# initialize_outlet_values()
#-------------------------------------------------------------------
def initialize_peak_values(self):
#-------------------------
# Initialize peak values
#-------------------------
self.Q_peak = self.initialize_scalar(0, dtype='float64')
self.T_peak = self.initialize_scalar(0, dtype='float64')
self.u_peak = self.initialize_scalar(0, dtype='float64')
self.Tu_peak = self.initialize_scalar(0, dtype='float64')
self.d_peak = self.initialize_scalar(0, dtype='float64')
self.Td_peak = self.initialize_scalar(0, dtype='float64')
# initialize_peak_values()
#-------------------------------------------------------------------
def initialize_min_and_max_values(self):
#-------------------------------
# Initialize min & max values
# (2/3/13), for new framework.
#-------------------------------
v = 1e6
self.Q_min = self.initialize_scalar(v, dtype='float64')
self.Q_max = self.initialize_scalar(-v, dtype='float64')
self.u_min = self.initialize_scalar(v, dtype='float64')
self.u_max = self.initialize_scalar(-v, dtype='float64')
self.d_min = self.initialize_scalar(v, dtype='float64')
self.d_max = self.initialize_scalar(-v, dtype='float64')
# initialize_min_and_max_values()
#-------------------------------------------------------------------
# def update_excess_rainrate(self):
def update_R(self):
#----------------------------------------
# Compute the "excess rainrate", R.
# Each term must have same units: [m/s]
# Sum = net gain/loss rate over pixel.
#----------------------------------------------------
# R can be positive or negative. If negative, then
# water is removed from the surface at rate R until
# surface water is consumed.
#--------------------------------------------------------------
# P = precip_rate [m/s] (converted by read_input_data()).
# SM = snowmelt rate [m/s]
# GW = seep rate [m/s] (water_table intersects surface)
# ET = evap rate [m/s]
# IN = infil rate [m/s]
# MR = icemelt rate [m/s]
#------------------------------------------------------------
# Use refs to other comp vars from new framework. (5/18/12)
#------------------------------------------------------------
P = self.P_rain # (This is now liquid-only precip. 9/14/14)
SM = self.SM
GW = self.GW
ET = self.ET
IN = self.IN
MR = self.MR
## if (self.DEBUG):
## print 'At time:', self.time_min, ', P =', P, '[m/s]'
#--------------
# For testing
#--------------
## print '(Pmin, Pmax) =', P.min(), P.max()
## print '(SMmin, SMmax) =', SM.min(), SM.max()
## print '(GWmin, GWmax) =', GW.min(), GW.max()
## print '(ETmin, ETmax) =', ET.min(), ET.max()
## print '(INmin, INmax) =', IN.min(), IN.max()
## print '(MRmin, MRmax) =', MR.min(), MR.max()
## # print '(Hmin, Hmax) =', H.min(), H.max()
## print ' '
self.R = (P + SM + GW + MR) - (ET + IN)
# update_R()
#-------------------------------------------------------------------
def update_R_integral(self):
#-----------------------------------------------
# Update mass total for R, sum over all pixels
#-----------------------------------------------
volume = np.double(self.R * self.da * self.dt) # [m^3]
if (np.size(volume) == 1):
self.vol_R += (volume * self.rti.n_pixels)
else:
self.vol_R += np.sum(volume)
# update_R_integral()
#-------------------------------------------------------------------
def update_discharge(self):
#---------------------------------------------------------
# The discharge grid, Q, gives the flux of water _out_
# of each grid cell. This entire amount then flows
# into one of the 8 neighbor grid cells, as indicated
# by the D8 flow code. The update_flow_volume() function
# is called right after this one in update() and uses
# the Q grid.
#---------------------------------------------------------
# 7/15/05. The cross-sectional area of a trapezoid is
# given by: Ac = d * (w + (d * tan(theta))),
# where w is the bottom width. If we were to
# use: Ac = w * d, then we'd have Ac=0 when w=0.
# We also need angle units to be radians.
#---------------------------------------------------------
#-----------------------------
# Compute the discharge grid
#------------------------------------------------------
# A_wet is initialized in initialize_computed_vars().
# A_wet is updated in update_trapezoid_Rh().
#------------------------------------------------------
### self.Q = np.float64(self.u * A_wet)
self.Q[:] = self.u * self.A_wet ## (2/19/13, in place)
#--------------
# For testing
#--------------
## print '(umin, umax) =', self.u.min(), self.u.max()
## print '(d0min, d0max) =', self.d0.min(), self.d0.max()
## print '(dmin, dmax) =', self.d.min(), self.d.max()
## print '(amin, amax) =', self.angle.min(), self.angle.max()
## print '(wmin, wmax) =', self.width.min(), self.width.max()
## print '(Qmin, Qmax) =', self.Q.min(), self.Q.max()
## print '(L2min, L2max) =', L2.min(), L2.max()
## print '(Qmin, Qmax) =', self.Q.min(), self.Q.max()
#--------------
# For testing
#--------------
# print 'dmin, dmax =', self.d.min(), self.d.max()
# print 'umin, umax =', self.u.min(), self.u.max()
# print 'Qmin, Qmax =', self.Q.min(), self.Q.max()
# print ' '
# print 'u(outlet) =', self.u[self.outlet_ID]
# print 'Q(outlet) =', self.Q[self.outlet_ID] ########
#----------------------------------------------------
# Wherever depth is less than z0, assume that water
# is not flowing and set u and Q to zero.
# However, we also need (d gt 0) to avoid a divide
# by zero problem, even when numerators are zero.
#----------------------------------------------------
# FLOWING = (d > (z0/aval))
#*** FLOWING[self.d8.noflow_IDs] = False ;******
# u = (u * FLOWING)
# Q = (Q * FLOWING)
# d = np.maximum(d, 0.0) ;(allow depths lt z0, if gt 0.)
# update_discharge()
#-------------------------------------------------------------------
def update_diversions(self):
#--------------------------------------------------------------
# Note: The Channel component requests the following input
# vars from the Diversions component by including
# them in its "get_input_vars()":
# (1) Q_sources, Q_sources_x, Q_sources_y
# (2) Q_sinks, Q_sinks_x, Q_sinks_y
# (3) Q_canals_out, Q_canals_out_x, Q_canals_out_y
# (4) Q_canals_fraction, Q_canals_in_x, Q_canals_in_y.
# source_IDs are computed from (x,y) coordinates during
# initialize().
#
# Diversions component needs to get Q_canals_in from the
# Channel component.
#--------------------------------------------------------------
# Note: This *must* be called after update_discharge() and
# before update_flow_volume().
#--------------------------------------------------------------
# Note: The Q grid stores the volume flow rate *leaving* each
# grid cell in the domain. For sources, an extra amount
# is leaving the cell which can flow into its D8 parent
# cell. For sinks, a lesser amount is leaving the cell
# toward the D8 parent.
#--------------------------------------------------------------
# Note: It is not enough to just update Q and then call the
# update_flow_volume() method. This is because it
# won't update the volume in the channels in the grid
# cells that the extra discharge is leaving from.
#--------------------------------------------------------------
# If a grid cell contains a "source", then an additional Q
# will flow *into* that grid cell and increase flow volume.
#--------------------------------------------------------------
#-------------------------------------------------------------
# This is not fully tested but runs. However, the Diversion
# vars are still computed even when Diversions component is
# disabled. So it slows things down somewhat.
#-------------------------------------------------------------
return
########################
########################
#----------------------------------------
# Update Q and vol due to point sources
#----------------------------------------
## if (hasattr(self, 'source_IDs')):
if (self.n_sources > 0):
self.Q[ self.source_IDs ] += self.Q_sources
self.vol[ self.source_IDs ] += (self.Q_sources * self.dt)
#--------------------------------------
# Update Q and vol due to point sinks
#--------------------------------------
## if (hasattr(self, 'sink_IDs')):
if (self.n_sinks > 0):
self.Q[ self.sink_IDs ] -= self.Q_sinks
self.vol[ self.sink_IDs ] -= (self.Q_sinks * self.dt)
#---------------------------------------
# Update Q and vol due to point canals
#---------------------------------------
## if (hasattr(self, 'canal_in_IDs')):
if (self.n_canals > 0):
#-----------------------------------------------------------------
# Q grid was just modified. Apply the canal diversion fractions
# to compute the volume flow rate into upstream ends of canals.
#-----------------------------------------------------------------
Q_canals_in = self.Q_canals_fraction * self.Q[ self.canal_in_IDs ]
self.Q_canals_in = Q_canals_in
#----------------------------------------------------
# Update Q and vol due to losses at canal entrances
#----------------------------------------------------
self.Q[ self.canal_in_IDs ] -= Q_canals_in
self.vol[ self.canal_in_IDs ] -= (Q_canals_in * self.dt)
#-------------------------------------------------
# Update Q and vol due to gains at canal exits.
# Diversions component accounts for travel time.
#-------------------------------------------------
self.Q[ self.canal_out_IDs ] += self.Q_canals_out
self.vol[ self.canal_out_IDs ] += (self.Q_canals_out * self.dt)
# update_diversions()
#-------------------------------------------------------------------
def update_flow_volume(self):
#-----------------------------------------------------------
# Notes: This function must be called after
# update_discharge() and update_diversions().
#-----------------------------------------------------------
# Notes: Q = surface discharge [m^3/s]
# R = excess precip. rate [m/s]
# da = pixel area [m^2]
# dt = channel flow timestep [s]
# vol = total volume of water in pixel [m^3]
# v2 = temp version of vol
# w1 = IDs of pixels that...
# p1 = IDs of parent pixels that...
#-----------------------------------------------------------
dt = self.dt # [seconds]
#----------------------------------------------------
# Add contribution (or loss ?) from excess rainrate
#----------------------------------------------------
# Contributions over entire grid cell from rainfall,
# snowmelt, icemelt and baseflow (minus losses from
# evaporation and infiltration) are assumed to flow
# into the channel within the grid cell.
# Note that R is allowed to be negative.
#----------------------------------------------------
self.vol += (self.R * self.da) * dt # (in place)
#-----------------------------------------
# Add contributions from neighbor pixels
#-------------------------------------------------------------
# Each grid cell passes flow to *one* downstream neighbor.
# Note that multiple grid cells can flow toward a given grid
# cell, so a grid cell ID may occur in d8.p1 and d8.p2, etc.
#-------------------------------------------------------------
# (2/16/10) RETEST THIS. Before, a copy called "v2" was
# used but this doesn't seem to be necessary.
#-------------------------------------------------------------
if (self.d8.p1_OK):
self.vol[ self.d8.p1 ] += (dt * self.Q[self.d8.w1])
if (self.d8.p2_OK):
self.vol[ self.d8.p2 ] += (dt * self.Q[self.d8.w2])
if (self.d8.p3_OK):
self.vol[ self.d8.p3 ] += (dt * self.Q[self.d8.w3])
if (self.d8.p4_OK):
self.vol[ self.d8.p4 ] += (dt * self.Q[self.d8.w4])
if (self.d8.p5_OK):
self.vol[ self.d8.p5 ] += (dt * self.Q[self.d8.w5])
if (self.d8.p6_OK):
self.vol[ self.d8.p6 ] += (dt * self.Q[self.d8.w6])
if (self.d8.p7_OK):
self.vol[ self.d8.p7 ] += (dt * self.Q[self.d8.w7])
if (self.d8.p8_OK):
self.vol[ self.d8.p8 ] += (dt * self.Q[self.d8.w8])
#----------------------------------------------------
# Subtract the amount that flows out to D8 neighbor
#----------------------------------------------------
self.vol -= (self.Q * dt) # (in place)
#--------------------------------------------------------
# While R can be positive or negative, the surface flow
# volume must always be nonnegative. This also ensures
# that the flow depth is nonnegative. (7/13/06)
#--------------------------------------------------------
## self.vol = np.maximum(self.vol, 0.0)
## self.vol[:] = np.maximum(self.vol, 0.0) # (2/19/13)
np.maximum( self.vol, 0.0, self.vol ) # (in place)
# update_flow_volume
#-------------------------------------------------------------------
def update_flow_depth(self):
#-----------------------------------------------------------
# Notes: 7/18/05. Modified to use the equation for volume
# of a trapezoidal channel: vol = Ac * ds, where
# Ac=d*[w + d*tan(t)], and to solve the resulting
# quadratic (discarding neg. root) for new depth, d.
# 8/29/05. Now original ds is used for subsurface
# flow and there is a ds_chan which can include a
# sinuosity greater than 1. This may be especially
# important for larger pixel sizes.
# Removed (ds > 1) here which was only meant to
# avoid a "divide by zero" error at pixels where
# (ds eq 0). This isn't necessary since the
# Flow_Lengths function in utils_TF.pro never
# returns a value of zero.
#----------------------------------------------------------
# Modified to avoid double where calls, which
# reduced cProfile run time for this method from
# 1.391 to 0.644. (9/23/14)
#----------------------------------------------------------
# Commented this out on (2/18/10) because it doesn't
# seem to be used anywhere now. Checked all
# of the Channels components.
#----------------------------------------------------------
# self.d_last = self.d.copy()
#-----------------------------------
# Make some local aliases and vars
#-----------------------------------------------------------
# Note: angles were read as degrees & converted to radians
#-----------------------------------------------------------
d = self.d
width = self.width ###
angle = self.angle
SCALAR_ANGLES = (np.size(angle) == 1)
#------------------------------------------------------
# (2/18/10) New code to deal with case where the flow
# depth exceeds a bankfull depth.
# For now, d_bankfull is hard-coded.
#
# CHANGE Manning's n here, too?
#------------------------------------------------------
d_bankfull = 4.0 # [meters]
################################
wb = (self.d > d_bankfull) # (array of True or False)
self.width[ wb ] = self.d8.dw[ wb ]
if not(SCALAR_ANGLES):
self.angle[ wb ] = 0.0
# w_overbank = np.where( d > d_bankfull )
# n_overbank = np.size( w_overbank[0] )
# if (n_overbank != 0):
# width[ w_overbank ] = self.d8.dw[ w_overbank ]
# if not(SCALAR_ANGLES): angle[w_overbank] = 0.0
#------------------------------------------------------
# (2/18/10) New code to deal with case where the top
# width exceeds the grid cell width, dw.
#------------------------------------------------------
top_width = width + (2.0 * d * np.sin(self.angle))
wb = (top_width > self.d8.dw) # (array of True or False)
self.width[ wb ] = self.d8.dw[ wb ]
if not(SCALAR_ANGLES):
self.angle[ wb ] = 0.0
# wb = np.where(top_width > self.d8.dw)
# nb = np.size(w_bad[0])
# if (nb != 0):
# width[ wb ] = self.d8.dw[ wb ]
# if not(SCALAR_ANGLES): angle[ wb ] = 0.0
#----------------------------------
# Is "angle" a scalar or a grid ?
#----------------------------------
if (SCALAR_ANGLES):
if (angle == 0.0):
d = self.vol / (width * self.d8.ds)
else:
denom = 2.0 * np.tan(angle)
arg = 2.0 * denom * self.vol / self.d8.ds
arg += width**(2.0)
d = (np.sqrt(arg) - width) / denom
else:
#-----------------------------------------------------
# Pixels where angle is 0 must be handled separately
#-----------------------------------------------------
w1 = ( angle == 0 ) # (arrays of True or False)
w2 = np.invert( w1 )
#-----------------------------------
A_top = width[w1] * self.d8.ds[w1]
d[w1] = self.vol[w1] / A_top
#-----------------------------------
denom = 2.0 * np.tan(angle[w2])
arg = 2.0 * denom * self.vol[w2] / self.d8.ds[w2]
arg += width[w2]**(2.0)
d[w2] = (np.sqrt(arg) - width[w2]) / denom
#-----------------------------------------------------
# Pixels where angle is 0 must be handled separately
#-----------------------------------------------------
# wz = np.where( angle == 0 )
# nwz = np.size( wz[0] )
# wzc = np.where( angle != 0 )
# nwzc = np.size( wzc[0] )
#
# if (nwz != 0):
# A_top = width[wz] * self.d8.ds[wz]
# ## A_top = self.width[wz] * self.d8.ds_chan[wz]
# d[wz] = self.vol[wz] / A_top
#
# if (nwzc != 0):
# term1 = 2.0 * np.tan(angle[wzc])
# arg = 2.0 * term1 * self.vol[wzc] / self.d8.ds[wzc]
# arg += width[wzc]**(2.0)
# d[wzc] = (np.sqrt(arg) - width[wzc]) / term1
#------------------------------------------
# Set depth values on edges to zero since
# they become spikes (no outflow) 7/15/06
#------------------------------------------
d[ self.d8.noflow_IDs ] = 0.0
#------------------------------------------------
# 4/19/06. Force flow depth to be positive ?
#------------------------------------------------
# This seems to be needed with the non-Richards
# infiltration routines when starting with zero
# depth everywhere, since all water infiltrates
# for some period of time. It also seems to be
# needed more for short rainfall records to
# avoid a negative flow depth error.
#------------------------------------------------
# 7/13/06. Still needed for Richards method
#------------------------------------------------
## self.d = np.maximum(d, 0.0)
np.maximum(d, 0.0, self.d) # (2/19/13, in place)
#-------------------------------------------------
# Find where d <= 0 and save for later (9/23/14)
#-------------------------------------------------
self.d_is_pos = (self.d > 0)
self.d_is_neg = np.invert( self.d_is_pos )
# update_flow_depth
#-------------------------------------------------------------------
def update_free_surface_slope(self):
#-----------------------------------------------------------
# Notes: It is assumed that the flow directions don't
# change even though the free surface is changing.
#-----------------------------------------------------------
delta_d = (self.d - self.d[self.d8.parent_IDs])
self.S_free[:] = self.S_bed + (delta_d / self.d8.ds)
#--------------------------------------------
# Don't do this; negative slopes are needed
# to decelerate flow in dynamic wave case
# and for backwater effects.
#--------------------------------------------
# Set negative slopes to zero
#------------------------------
### self.S_free = np.maximum(self.S_free, 0)
# update_free_surface_slope()
#-------------------------------------------------------------------
def update_shear_stress(self):
#--------------------------------------------------------
# Notes: 9/9/14. Added so shear stress could be shared.
# This uses the depth-slope product.
#--------------------------------------------------------
if (self.KINEMATIC_WAVE):
slope = self.S_bed
else:
slope = self.S_free
self.tau[:] = self.rho_H2O * self.g * self.d * slope
# update_shear_stress()
#-------------------------------------------------------------------
def update_shear_speed(self):
#--------------------------------------------------------
# Notes: 9/9/14. Added so shear speed could be shared.
#--------------------------------------------------------
self.u_star[:] = np.sqrt( self.tau / self.rho_H2O )
# update_shear_speed()
#-------------------------------------------------------------------
def update_trapezoid_Rh(self):
#-------------------------------------------------------------
# Notes: Compute the hydraulic radius of a trapezoid that:
# (1) has a bed width of wb >= 0 (0 for triangular)
# (2) has a bank angle of theta (0 for rectangular)
# (3) is filled with water to a depth of d.
# The units of wb and d are meters. The units of
# theta are assumed to be degrees and are converted.
#-------------------------------------------------------------
# NB! wb should never be zero, so P_wet can never be 0,
# which would produce a NaN (divide by zero).
#-------------------------------------------------------------
# See Notes for TF_Tan function in utils_TF.pro
# AW = d * (wb + (d * TF_Tan(theta_rad)) )
#-------------------------------------------------------------
# 9/9/14. Bug fix. Angles were already in radians but
# were converted to radians again.
#--------------------------------------------------------------
#---------------------------------------------------------
# Compute hydraulic radius grid for trapezoidal channels
#-----------------------------------------------------------
# Note: angles were read as degrees & converted to radians
#-----------------------------------------------------------
d = self.d # (local synonyms)
wb = self.width # (trapezoid bottom width)
L2 = d * np.tan( self.angle )
A_wet = d * (wb + L2)
P_wet = wb + (np.float64(2) * d / np.cos(self.angle) )
#---------------------------------------------------
# At noflow_IDs (e.g. edges) P_wet may be zero
# so do this to avoid "divide by zero". (10/29/11)
#---------------------------------------------------
P_wet[ self.d8.noflow_IDs ] = np.float64(1)
Rh = (A_wet / P_wet)
#--------------------------------
# w = np.where(P_wet == 0)
# print 'In update_trapezoid_Rh():'
# print ' P_wet= 0 at', w[0].size, 'cells'
#------------------------------------
# Force edge pixels to have Rh = 0.
# This will make u = 0 there also.
#------------------------------------
Rh[ self.d8.noflow_IDs ] = np.float64(0)
## w = np.where(wb <= 0)
## nw = np.size(w[0])
## if (nw > 0): Rh[w] = np.float64(0)
self.Rh[:] = Rh
self.A_wet[:] = A_wet ## (Now shared: 9/9/14)
self.P_wet[:] = P_wet ## (Now shared: 9/9/14)
#---------------
# For testing
#--------------
## print 'dmin, dmax =', d.min(), d.max()
## print 'wmin, wmax =', wb.min(), wb.max()
## print 'amin, amax =', self.angle.min(), self.angle.max()
# update_trapezoid_Rh()
#-------------------------------------------------------------------
def update_friction_factor(self):
#----------------------------------------
# Note: Added on 9/9/14 to streamline.
#----------------------------------------------------------
# Note: f = half of the Fanning friction factor
# d = flow depth [m]
# z0 = roughness length
# S = bed slope (assumed equal to friction slope)
# g = 9.81 = gravitation constant [m/s^2]
#---------------------------------------------------------
# For law of the wall:
# kappa = 0.41 = von Karman's constant
# aval = 0.48 = integration constant
# law_const = sqrt(g)/kappa = 7.6393d
# smoothness = (aval / z0) * d
# f = (kappa / alog(smoothness))^2d
# tau_bed = rho_w * f * u^2 = rho_w * g * d * S
# d, S, and z0 can be arrays.
# To make default z0 correspond to default
# Manning's n, can use this approximation:
# z0 = a * (2.34 * sqrt(9.81) * n / kappa)^6d
# For n=0.03, this gives: z0 = 0.011417
#########################################################
# However, for n=0.3, it gives: z0 = 11417.413
# which is 11.4 km! So the approximation only
# holds within some range of values.
#--------------------------------------------------------
###############################################################
# cProfile: This method took: 0.369 secs for topoflow_test()
###############################################################
#--------------------------------------
# Find where (d <= 0). g=good, b=bad
#--------------------------------------
wg = self.d_is_pos
wb = self.d_is_neg
# wg = ( self.d > 0 )
# wb = np.invert( wg )
#-----------------------------
# Compute f for Manning case
#-----------------------------------------
# This makes f=0 and du=0 where (d <= 0)
#-----------------------------------------
if (self.MANNING):
n2 = self.nval ** np.float64(2)
self.f[ wg ] = self.g * (n2[wg] / (self.d[wg] ** self.one_third))
self.f[ wb ] = np.float64(0)
#---------------------------------
# Compute f for Law of Wall case
#---------------------------------
if (self.LAW_OF_WALL):
#------------------------------------------------
# Make sure (smoothness > 1) before taking log.
# Should issue a warning if this is used.
#------------------------------------------------
smoothness = (self.aval / self.z0val) * self.d
np.maximum(smoothness, np.float64(1.1), smoothness) # (in place)
self.f[wg] = (self.kappa / np.log(smoothness[wg])) ** np.float64(2)
self.f[wb] = np.float64(0)
##############################################################
# cProfile: This method took: 0.93 secs for topoflow_test()
##############################################################
# #--------------------------------------
# # Find where (d <= 0). g=good, b=bad
# #--------------------------------------
# wg = np.where( self.d > 0 )
# ng = np.size( wg[0])
# wb = np.where( self.d <= 0 )
# nb = np.size( wb[0] )
#
# #-----------------------------
# # Compute f for Manning case
# #-----------------------------------------
# # This makes f=0 and du=0 where (d <= 0)
# #-----------------------------------------
# if (self.MANNING):
# n2 = self.nval ** np.float64(2)
# if (ng != 0):
# self.f[wg] = self.g * (n2[wg] / (self.d[wg] ** self.one_third))
# if (nb != 0):
# self.f[wb] = np.float64(0)
#
# #---------------------------------
# # Compute f for Law of Wall case
# #---------------------------------
# if (self.LAW_OF_WALL):
# #------------------------------------------------
# # Make sure (smoothness > 1) before taking log.
# # Should issue a warning if this is used.
# #------------------------------------------------
# smoothness = (self.aval / self.z0val) * self.d
# np.maximum(smoothness, np.float64(1.1), smoothness) # (in place)
# ## smoothness = np.maximum(smoothness, np.float64(1.1))
# if (ng != 0):
# self.f[wg] = (self.kappa / np.log(smoothness[wg])) ** np.float64(2)
# if (nb != 0):
# self.f[wb] = np.float64(0)
#---------------------------------------------
# We could share the Fanning friction factor
#---------------------------------------------
### self.fanning = (np.float64(2) * self.f)
# update_friction_factor()
#-------------------------------------------------------------------
def update_velocity(self):
#---------------------------------------------------------
# Note: Do nothing now unless this method is overridden
# by a particular method of computing velocity.
#---------------------------------------------------------
print "Warning: update_velocity() method is inactive."
# print 'KINEMATIC WAVE =', self.KINEMATIC_WAVE
# print 'DIFFUSIVE WAVE =', self.DIFFUSIVE_WAVE
# print 'DYNAMIC WAVE =', self.DYNAMIC_WAVE
# update_velocity()
#-------------------------------------------------------------------
def update_velocity_on_edges(self):
#---------------------------------
# Force edge pixels to have u=0.
#----------------------------------------
# Large slope around 1 flows into small
# slope & leads to a negative velocity.
#----------------------------------------
self.u[ self.d8.noflow_IDs ] = np.float64(0)
# update_velocity_on_edges()
#-------------------------------------------------------------------
def update_froude_number(self):
#----------------------------------------------------------
# Notes: 9/9/14. Added so Froude number could be shared.
# This use of wg & wb reduced cProfile time from:
# 0.644 sec to: 0.121. (9/23/14)
#----------------------------------------------------------
# g = good, b = bad
#--------------------
wg = self.d_is_pos
wb = self.d_is_neg
self.froude[ wg ] = self.u[wg] / np.sqrt( self.g * self.d[wg] )
self.froude[ wb ] = np.float64(0)
# update_froude_number()
#-------------------------------------------------------------
def update_outlet_values(self):
#-------------------------------------------------
# Save computed values at outlet, which are used
# by the TopoFlow driver.
#-----------------------------------------------------
# Note that Q_outlet, etc. are defined as 0D numpy
# arrays to make them "mutable scalars" (i.e.
# this allows changes to be seen by other components
# who have a reference. To preserver the reference,
# however, we must use fill() to assign a new value.
#-----------------------------------------------------
Q_outlet = self.Q[ self.outlet_ID ]
u_outlet = self.u[ self.outlet_ID ]
d_outlet = self.d[ self.outlet_ID ]
f_outlet = self.f[ self.outlet_ID ]
self.Q_outlet.fill( Q_outlet )
self.u_outlet.fill( u_outlet )
self.d_outlet.fill( d_outlet )
self.f_outlet.fill( f_outlet )
## self.Q_outlet.fill( self.Q[ self.outlet_ID ] )
## self.u_outlet.fill( self.u[ self.outlet_ID ] )
## self.d_outlet.fill( self.d[ self.outlet_ID ] )
## self.f_outlet.fill( self.f[ self.outlet_ID ] )
## self.Q_outlet = self.Q[ self.outlet_ID ]
## self.u_outlet = self.u[ self.outlet_ID ]
## self.d_outlet = self.d[ self.outlet_ID ]
## self.f_outlet = self.f[ self.outlet_ID ]
## self.Q_outlet = self.Q.flat[self.outlet_ID]
## self.u_outlet = self.u.flat[self.outlet_ID]
## self.d_outlet = self.d.flat[self.outlet_ID]
## self.f_outlet = self.f.flat[self.outlet_ID]
# update_outlet_values()
#-------------------------------------------------------------
def update_peak_values(self):
if (self.Q_outlet > self.Q_peak):
self.Q_peak.fill( self.Q_outlet )
self.T_peak.fill( self.time_min ) # (time to peak)
#---------------------------------------
if (self.u_outlet > self.u_peak):
self.u_peak.fill( self.u_outlet )
self.Tu_peak.fill( self.time_min )
#---------------------------------------
if (self.d_outlet > self.d_peak):
self.d_peak.fill( self.d_outlet )
self.Td_peak.fill( self.time_min )
## if (self.Q_outlet > self.Q_peak):
## self.Q_peak = self.Q_outlet
## self.T_peak = self.time_min # (time to peak)
## #-----------------------------------
## if (self.u_outlet > self.u_peak):
## self.u_peak = self.u_outlet
## self.Tu_peak = self.time_min
## #-----------------------------------
## if (self.d_outlet > self.d_peak):
## self.d_peak = self.d_outlet
## self.Td_peak = self.time_min
# update_peak_values()
#-------------------------------------------------------------
def update_Q_out_integral(self):
#--------------------------------------------------------
# Note: Renamed "volume_out" to "vol_Q" for consistency
# with vol_P, vol_SM, vol_IN, vol_ET, etc. (5/18/12)
#--------------------------------------------------------
self.vol_Q += (self.Q_outlet * self.dt) ## Experiment: 5/19/12.
## self.vol_Q += (self.Q[self.outlet_ID] * self.dt)
# update_Q_out_integral()
#-------------------------------------------------------------
def update_mins_and_maxes(self, REPORT=False):
#--------------------------------------
# Get mins and max over entire domain
#--------------------------------------
## Q_min = self.Q.min()
## Q_max = self.Q.max()
## #---------------------
## u_min = self.u.min()
## u_max = self.u.max()
## #---------------------
## d_min = self.d.min()
## d_max = self.d.max()
#--------------------------------------------
# Exclude edges where mins are always zero.
#--------------------------------------------
nx = self.nx
ny = self.ny
Q_min = self.Q[1:(ny - 2)+1,1:(nx - 2)+1].min()
Q_max = self.Q[1:(ny - 2)+1,1:(nx - 2)+1].max()
#-------------------------------------------------
u_min = self.u[1:(ny - 2)+1,1:(nx - 2)+1].min()
u_max = self.u[1:(ny - 2)+1,1:(nx - 2)+1].max()
#-------------------------------------------------
d_min = self.d[1:(ny - 2)+1,1:(nx - 2)+1].min()
d_max = self.d[1:(ny - 2)+1,1:(nx - 2)+1].max()
#-------------------------------------------------
# (2/6/13) This preserves "mutable scalars" that
# can be accessed as refs by other components.
#-------------------------------------------------
if (Q_min < self.Q_min):
self.Q_min.fill( Q_min )
if (Q_max > self.Q_max):
self.Q_max.fill( Q_max )
#------------------------------
if (u_min < self.u_min):
self.u_min.fill( u_min )
if (u_max > self.u_max):
self.u_max.fill( u_max )
#------------------------------
if (d_min < self.d_min):
self.d_min.fill( d_min )
if (d_max > self.d_max):
self.d_max.fill( d_max )
#-------------------------------------------------
# (2/6/13) This preserves "mutable scalars" that
# can be accessed as refs by other components.
#-------------------------------------------------
## self.Q_min.fill( np.minimum( self.Q_min, Q_min ) )
## self.Q_max.fill( np.maximum( self.Q_max, Q_max ) )
## #---------------------------------------------------
## self.u_min.fill( np.minimum( self.u_min, u_min ) )
## self.u_max.fill( np.maximum( self.u_max, u_max ) )
## #---------------------------------------------------
## self.d_min.fill( np.minimum( self.d_min, d_min ) )
## self.d_max.fill( np.maximum( self.d_max, d_max ) )
#-------------------------------------------------
# (2/6/13) This preserves "mutable scalars" that
# can be accessed as refs by other components.
#-------------------------------------------------
## self.Q_min.fill( min( self.Q_min, Q_min ) )
## self.Q_max.fill( max( self.Q_max, Q_max ) )
## #---------------------------------------------------
## self.u_min.fill( min( self.u_min, u_min ) )
## self.u_max.fill( max( self.u_max, u_max ) )
## #---------------------------------------------------
## self.d_min.fill( min( self.d_min, d_min ) )
## self.d_max.fill( max( self.d_max, d_max ) )
#----------------------------------------------
# (2/6/13) This produces "immutable scalars".
#----------------------------------------------
## self.Q_min = self.Q.min()
## self.Q_max = self.Q.max()
## self.u_min = self.u.min()
## self.u_max = self.u.max()
## self.d_min = self.d.min()
## self.d_max = self.d.max()
if (REPORT):
print 'In channels_base.update_mins_and_maxes():'
print '(dmin, dmax) =', self.d_min, self.d_max
print '(umin, umax) =', self.u_min, self.u_max
print '(Qmin, Qmax) =', self.Q_min, self.Q_max
print ' '
# update_mins_and_maxes()
#-------------------------------------------------------------------
def check_flow_depth(self):
OK = True
d = self.d
dt = self.dt
nx = self.nx #################
#---------------------------------
# All all flow depths positive ?
#---------------------------------
wbad = np.where( np.logical_or( d < 0.0, np.logical_not(np.isfinite(d)) ))
nbad = np.size( wbad[0] )
if (nbad == 0):
return OK
OK = False
dmin = d[wbad].min()
star_line = '*******************************************'
msg = [ star_line, \
'ERROR: Simulation aborted.', ' ', \
'Negative depth found: ' + str(dmin), \
'Time step may be too large.', \
'Time step: ' + str(dt) + ' [s]', ' ']
for k in xrange(len(msg)):
print msg[k]
#-------------------------------------------
# If not too many, print actual velocities
#-------------------------------------------
if (nbad < 30):
brow = wbad[0][0]
bcol = wbad[1][0]
## badi = wbad[0]
## bcol = (badi % nx)
## brow = (badi / nx)
crstr = str(bcol) + ', ' + str(brow)
msg = ['(Column, Row): ' + crstr, \
'Flow depth: ' + str(d[brow, bcol])]
for k in xrange(len(msg)):
print msg[k]
print star_line
print ' '
return OK
# check_flow_depth
#-------------------------------------------------------------------
def check_flow_velocity(self):
OK = True
u = self.u
dt = self.dt
nx = self.nx
#--------------------------------
# Are all velocities positive ?
#--------------------------------
wbad = np.where( np.logical_or( u < 0.0, np.logical_not(np.isfinite(u)) ))
nbad = np.size( wbad[0] )
if (nbad == 0):
return OK
OK = False
umin = u[wbad].min()
star_line = '*******************************************'
msg = [ star_line, \
'ERROR: Simulation aborted.', ' ', \
'Negative or NaN velocity found: ' + str(umin), \
'Time step may be too large.', \
'Time step: ' + str(dt) + ' [s]', ' ']
for k in xrange(len(msg)):
print msg[k]
#-------------------------------------------
# If not too many, print actual velocities
#-------------------------------------------
if (nbad < 30):
brow = wbad[0][0]
bcol = wbad[1][0]
## badi = wbad[0]
## bcol = (badi % nx)
## brow = (badi / nx)
crstr = str(bcol) + ', ' + str(brow)
msg = ['(Column, Row): ' + crstr, \
'Velocity: ' + str(u[brow, bcol])]
for k in xrange(len(msg)):
print msg[k]
print star_line
print ' '
return OK
## umin = u[wbad].min()
## badi = wbad[0]
## bcol = (badi % nx)
## brow = (badi / nx)
## crstr = str(bcol) + ', ' + str(brow)
## msg = np.array([' ', \
## '*******************************************', \
## 'ERROR: Simulation aborted.', ' ', \
## 'Negative velocity found: ' + str(umin), \
## 'Time step may be too large.', ' ', \
## '(Column, Row): ' + crstr, \
## 'Velocity: ' + str(u[badi]), \
## 'Time step: ' + str(dt) + ' [s]', \
## '*******************************************', ' '])
## for k in xrange( np.size(msg) ):
## print msg[k]
## return OK
# check_flow_velocity
#-------------------------------------------------------------------
def open_input_files(self):
# This doesn't work, because file_unit doesn't get full path. (10/28/11)
# start_dir = os.getcwd()
# os.chdir( self.in_directory )
# print '### start_dir =', start_dir
# print '### in_directory =', self.in_directory
in_files = ['slope_file', 'nval_file', 'z0val_file',
'width_file', 'angle_file', 'sinu_file', 'd0_file']
self.prepend_directory( in_files, INPUT=True )
# self.slope_file = self.in_directory + self.slope_file
# self.nval_file = self.in_directory + self.nval_file
# self.z0val_file = self.in_directory + self.z0val_file
# self.width_file = self.in_directory + self.width_file
# self.angle_file = self.in_directory + self.angle_file
# self.sinu_file = self.in_directory + self.sinu_file
# self.d0_file = self.in_directory + self.d0_file
#self.code_unit = model_input.open_file(self.code_type, self.code_file)
self.slope_unit = model_input.open_file(self.slope_type, self.slope_file)
if (self.MANNING):
self.nval_unit = model_input.open_file(self.nval_type, self.nval_file)
if (self.LAW_OF_WALL):
self.z0val_unit = model_input.open_file(self.z0val_type, self.z0val_file)
self.width_unit = model_input.open_file(self.width_type, self.width_file)
self.angle_unit = model_input.open_file(self.angle_type, self.angle_file)
self.sinu_unit = model_input.open_file(self.sinu_type, self.sinu_file)
self.d0_unit = model_input.open_file(self.d0_type, self.d0_file)
# os.chdir( start_dir )
# open_input_files()
#-------------------------------------------------------------------
def read_input_files(self):
#---------------------------------------------------
# The flow codes are always a grid, size of DEM.
#---------------------------------------------------
# NB! model_input.py also has a read_grid() function.
#---------------------------------------------------
rti = self.rti
## print 'Reading D8 flow grid (in CHANNELS)...'
## self.code = rtg_files.read_grid(self.code_file, rti,
## RTG_type='BYTE')
## print ' '
#-------------------------------------------------------
# All grids are assumed to have a data type of Float32.
#-------------------------------------------------------
slope = model_input.read_next(self.slope_unit, self.slope_type, rti)
if (slope != None): self.slope = slope
# If EOF was reached, hopefully numpy's "fromfile"
# returns None, so that the stored value will be
# the last value that was read.
if (self.MANNING):
nval = model_input.read_next(self.nval_unit, self.nval_type, rti)
if (nval != None):
self.nval = nval
self.nval_min = nval.min()
self.nval_max = nval.max()
if (self.LAW_OF_WALL):
z0val = model_input.read_next(self.z0val_unit, self.z0val_type, rti)
if (z0val != None):
self.z0val = z0val
self.z0val_min = z0val.min()
self.z0val_max = z0val.max()
width = model_input.read_next(self.width_unit, self.width_type, rti)
if (width != None): self.width = width
angle = model_input.read_next(self.angle_unit, self.angle_type, rti)
if (angle != None):
#-----------------------------------------------
# Convert bank angles from degrees to radians.
#-----------------------------------------------
self.angle = angle * self.deg_to_rad # [radians]
### self.angle = angle # (before 9/9/14)
sinu = model_input.read_next(self.sinu_unit, self.sinu_type, rti)
if (sinu != None): self.sinu = sinu
d0 = model_input.read_next(self.d0_unit, self.d0_type, rti)
if (d0 != None): self.d0 = d0
## code = model_input.read_grid(self.code_unit, \
## self.code_type, rti, dtype='UInt8')
## if (code != None): self.code = code
# read_input_files()
#-------------------------------------------------------------------
def close_input_files(self):
# if not(self.slope_unit.closed):
# if (self.slope_unit != None):
#-------------------------------------------------
# NB! self.code_unit was never defined as read.
#-------------------------------------------------
# if (self.code_type != 'scalar'): self.code_unit.close()
if (self.slope_type != 'Scalar'): self.slope_unit.close()
if (self.MANNING):
if (self.nval_type != 'Scalar'): self.nval_unit.close()
if (self.LAW_OF_WALL):
if (self.z0val_type != 'Scalar'): self.z0val_unit.close()
if (self.width_type != 'Scalar'): self.width_unit.close()
if (self.angle_type != 'Scalar'): self.angle_unit.close()
if (self.sinu_type != 'Scalar'): self.sinu_unit.close()
if (self.d0_type != 'Scalar'): self.d0_unit.close()
## if (self.slope_file != ''): self.slope_unit.close()
## if (self.MANNING):
## if (self.nval_file != ''): self.nval_unit.close()
## if (self.LAW_OF_WALL):
## if (self.z0val_file != ''): self.z0val_unit.close()
## if (self.width_file != ''): self.width_unit.close()
## if (self.angle_file != ''): self.angle_unit.close()
## if (self.sinu_file != ''): self.sinu_unit.close()
## if (self.d0_file != ''): self.d0_unit.close()
# close_input_files()
#-------------------------------------------------------------------
def update_outfile_names(self):
#-------------------------------------------------
# Notes: Append out_directory to outfile names.
#-------------------------------------------------
self.Q_gs_file = (self.out_directory + self.Q_gs_file)
self.u_gs_file = (self.out_directory + self.u_gs_file)
self.d_gs_file = (self.out_directory + self.d_gs_file)
self.f_gs_file = (self.out_directory + self.f_gs_file)
#--------------------------------------------------------
self.Q_ts_file = (self.out_directory + self.Q_ts_file)
self.u_ts_file = (self.out_directory + self.u_ts_file)
self.d_ts_file = (self.out_directory + self.d_ts_file)
self.f_ts_file = (self.out_directory + self.f_ts_file)
# update_outfile_names()
#-------------------------------------------------------------------
def bundle_output_files(self):
###################################################
# NOT READY YET. Need "get_long_name()" and a new
# version of "get_var_units". (9/21/14)
###################################################
#-------------------------------------------------------------
# Bundle the output file info into an array for convenience.
# Then we just need one open_output_files(), in BMI_base.py,
# and one close_output_files(). Less to maintain. (9/21/14)
#-------------------------------------------------------------
# gs = grid stack, ts = time series, ps = profile series.
#-------------------------------------------------------------
self.out_files = [
{var_name:'Q',
save_gs:self.SAVE_Q_GRIDS, gs_file:self.Q_gs_file,
save_ts:self.SAVE_Q_PIXELS, ts_file:self.Q_ts_file,
long_name:get_long_name('Q'), units_name:get_var_units('Q')},
#-----------------------------------------------------------------
{var_name:'u',
save_gs:self.SAVE_U_GRIDS, gs_file:self.u_gs_file,
save_ts:self.SAVE_U_PIXELS, ts_file:self.u_ts_file,
long_name:get_long_name('u'), units_name:get_var_units('u')},
#-----------------------------------------------------------------
{var_name:'d',
save_gs:self.SAVE_D_GRIDS, gs_file:self.d_gs_file,
save_ts:self.SAVE_D_PIXELS, ts_file:self.d_ts_file,
long_name:get_long_name('d'), units_name:get_var_units('d')},
#-----------------------------------------------------------------
{var_name:'f',
save_gs:self.SAVE_F_GRIDS, gs_file:self.f_gs_file,
save_ts:self.SAVE_F_PIXELS, ts_file:self.f_ts_file,
long_name:get_long_name('f'), units_name:get_var_units('f')} ]
# bundle_output_files
#-------------------------------------------------------------------
def open_output_files(self):
model_output.check_netcdf()
self.update_outfile_names()
## self.bundle_output_files()
## print 'self.SAVE_Q_GRIDS =', self.SAVE_Q_GRIDS
## print 'self.SAVE_U_GRIDS =', self.SAVE_U_GRIDS
## print 'self.SAVE_D_GRIDS =', self.SAVE_D_GRIDS
## print 'self.SAVE_F_GRIDS =', self.SAVE_F_GRIDS
## #---------------------------------------------------
## print 'self.SAVE_Q_PIXELS =', self.SAVE_Q_PIXELS
## print 'self.SAVE_U_PIXELS =', self.SAVE_U_PIXELS
## print 'self.SAVE_D_PIXELS =', self.SAVE_D_PIXELS
## print 'self.SAVE_F_PIXELS =', self.SAVE_F_PIXELS
# IDs = self.outlet_IDs
# for k in xrange( len(self.out_files) ):
# #--------------------------------------
# # Open new files to write grid stacks
# #--------------------------------------
# if (self.out_files[k].save_gs):
# model_output.open_new_gs_file( self, self.out_files[k], self.rti )
# #--------------------------------------
# # Open new files to write time series
# #--------------------------------------
# if (self.out_files[k].save_ts):
# model_output.open_new_ts_file( self, self.out_files[k], IDs )
#--------------------------------------
# Open new files to write grid stacks
#--------------------------------------
if (self.SAVE_Q_GRIDS):
model_output.open_new_gs_file( self, self.Q_gs_file, self.rti,
var_name='Q',
long_name='volumetric_discharge',
units_name='m^3/s')
if (self.SAVE_U_GRIDS):
model_output.open_new_gs_file( self, self.u_gs_file, self.rti,
var_name='u',
long_name='mean_channel_flow_velocity',
units_name='m/s')
if (self.SAVE_D_GRIDS):
model_output.open_new_gs_file( self, self.d_gs_file, self.rti,
var_name='d',
long_name='max_channel_flow_depth',
units_name='m')
if (self.SAVE_F_GRIDS):
model_output.open_new_gs_file( self, self.f_gs_file, self.rti,
var_name='f',
long_name='friction_factor',
units_name='none')
#--------------------------------------
# Open new files to write time series
#--------------------------------------
IDs = self.outlet_IDs
if (self.SAVE_Q_PIXELS):
model_output.open_new_ts_file( self, self.Q_ts_file, IDs,
var_name='Q',
long_name='volumetric_discharge',
units_name='m^3/s')
if (self.SAVE_U_PIXELS):
model_output.open_new_ts_file( self, self.u_ts_file, IDs,
var_name='u',
long_name='mean_channel_flow_velocity',
units_name='m/s')
if (self.SAVE_D_PIXELS):
model_output.open_new_ts_file( self, self.d_ts_file, IDs,
var_name='d',
long_name='max_channel_flow_depth',
units_name='m')
if (self.SAVE_F_PIXELS):
model_output.open_new_ts_file( self, self.f_ts_file, IDs,
var_name='f',
long_name='friction_factor',
units_name='none')
# open_output_files()
#-------------------------------------------------------------------
def write_output_files(self, time_seconds=None):
#---------------------------------------------------------
# Notes: This function was written to use only model
# time (maybe from a caller) in seconds, and
# the save_grid_dt and save_pixels_dt parameters
# read by read_cfg_file().
#
# read_cfg_file() makes sure that all of
# the "save_dts" are larger than or equal to the
# process dt.
#---------------------------------------------------------
#-----------------------------------------
# Allows time to be passed from a caller
#-----------------------------------------
if (time_seconds is None):
time_seconds = self.time_sec
model_time = int(time_seconds)
#----------------------------------------
# Save computed values at sampled times
#----------------------------------------
if (model_time % int(self.save_grid_dt) == 0):
self.save_grids()
if (model_time % int(self.save_pixels_dt) == 0):
self.save_pixel_values()
#----------------------------------------
# Save computed values at sampled times
#----------------------------------------
## if ((self.time_index % self.grid_save_step) == 0):
## self.save_grids()
## if ((self.time_index % self.pixel_save_step) == 0):
## self.save_pixel_values()
# write_output_files()
#-------------------------------------------------------------------
def close_output_files(self):
if (self.SAVE_Q_GRIDS): model_output.close_gs_file( self, 'Q')
if (self.SAVE_U_GRIDS): model_output.close_gs_file( self, 'u')
if (self.SAVE_D_GRIDS): model_output.close_gs_file( self, 'd')
if (self.SAVE_F_GRIDS): model_output.close_gs_file( self, 'f')
#---------------------------------------------------------------
if (self.SAVE_Q_PIXELS): model_output.close_ts_file( self, 'Q')
if (self.SAVE_U_PIXELS): model_output.close_ts_file( self, 'u')
if (self.SAVE_D_PIXELS): model_output.close_ts_file( self, 'd')
if (self.SAVE_F_PIXELS): model_output.close_ts_file( self, 'f')
# close_output_files()
#-------------------------------------------------------------------
def save_grids(self):
#-----------------------------------
# Save grid stack to a netCDF file
#---------------------------------------------
# Note that add_grid() methods will convert
# var from scalar to grid now, if necessary.
#---------------------------------------------
if (self.SAVE_Q_GRIDS):
model_output.add_grid( self, self.Q, 'Q', self.time_min )
if (self.SAVE_U_GRIDS):
model_output.add_grid( self, self.u, 'u', self.time_min )
if (self.SAVE_D_GRIDS):
model_output.add_grid( self, self.d, 'd', self.time_min )
if (self.SAVE_F_GRIDS):
model_output.add_grid( self, self.f, 'f', self.time_min )
# save_grids()
#-------------------------------------------------------------------
def save_pixel_values(self): ##### save_time_series_data(self) #######
IDs = self.outlet_IDs
time = self.time_min #####
#-------------
# New method
#-------------
if (self.SAVE_Q_PIXELS):
model_output.add_values_at_IDs( self, time, self.Q, 'Q', IDs )
if (self.SAVE_U_PIXELS):
model_output.add_values_at_IDs( self, time, self.u, 'u', IDs )
if (self.SAVE_D_PIXELS):
model_output.add_values_at_IDs( self, time, self.d, 'd', IDs )
if (self.SAVE_F_PIXELS):
model_output.add_values_at_IDs( self, time, self.f, 'f', IDs )
# save_pixel_values()
#-------------------------------------------------------------------
def manning_formula(self):
#---------------------------------------------------------
# Notes: R = (A/P) = hydraulic radius [m]
# N = Manning's roughness coefficient
# (usually in the range 0.012 to 0.035)
# S = bed slope or free slope
# R,S, and N may be 2D arrays.
# If length units are all *feet*, then an extra
# factor of 1.49 must be applied. If units are
# meters, no such factor is needed.
# Note that Q = Ac * u, where Ac is cross-section
# area. For a trapezoid, Ac does not equal w*d.
#---------------------------------------------------------
if (self.KINEMATIC_WAVE):
S = self.S_bed
else:
S = self.S_free
u = (self.Rh ** self.two_thirds) * np.sqrt(S) / self.nval
#--------------------------------------------------------
# Add a hydraulic jump option for when u gets too big ?
#--------------------------------------------------------
return u
# manning_formula()
#-------------------------------------------------------------------
def law_of_the_wall(self):
#---------------------------------------------------------
# Notes: u = flow velocity [m/s]
# d = flow depth [m]
# z0 = roughness length
# S = bed slope or free slope
# g = 9.81 = gravitation constant [m/s^2]
# kappa = 0.41 = von Karman's constant
# aval = 0.48 = integration constant
# law_const = sqrt(g)/kappa = 7.6393d
# smoothness = (aval / z0) * d
# f = (kappa / alog(smoothness))^2d
# tau_bed = rho_w * f * u^2 = rho_w * g * d * S
# d, S, and z0 can be arrays.
# To make default z0 correspond to default
# Manning's n, can use this approximation:
# z0 = a * (2.34 * sqrt(9.81) * n / kappa)^6d
# For n=0.03, this gives: z0 = 0.011417
#########################################################
# However, for n=0.3, it gives: z0 = 11417.413
# which is 11.4 km! So the approximation only
# holds within some range of values.
#--------------------------------------------------------
if (self.KINEMATIC_WAVE):
S = self.S_bed
else:
S = self.S_free
smoothness = (self.aval / self.z0val) * self.d
#------------------------------------------------
# Make sure (smoothness > 1) before taking log.
# Should issue a warning if this is used.
#------------------------------------------------
smoothness = np.maximum(smoothness, np.float64(1.1))
u = self.law_const * np.sqrt(self.Rh * S) * np.log(smoothness)
#--------------------------------------------------------
# Add a hydraulic jump option for when u gets too big ?
#--------------------------------------------------------
return u
# law_of_the_wall()
#-------------------------------------------------------------------
def print_status_report(self):
#----------------------------------------------------
# Wherever depth is less than z0, assume that water
# is not flowing and set u and Q to zero.
# However, we also need (d gt 0) to avoid a divide
# by zero problem, even when numerators are zero.
#----------------------------------------------------
# FLOWING = (d > (z0/aval))
#*** FLOWING[noflow_IDs] = False ;******
wflow = np.where( FLOWING != 0 )
n_flow = np.size( wflow[0] )
n_pixels = self.rti.n_pixels
percent = np.float64(100.0) * (np.float64(n_flow) / n_pixels)
fstr = ('%5.1f' % percent) + '%'
# fstr = idl_func.string(percent, format='(F5.1)').strip() + '%'
print ' Percentage of pixels with flow = ' + fstr
print ' '
self.update_mins_and_maxes(REPORT=True)
wmax = np.where(self.Q == self.Q_max)
nwmax = np.size(wmax[0])
print ' Max(Q) occurs at: ' + str( wmax[0] )
#print,' Max attained at ', nwmax, ' pixels.'
print ' '
print '-------------------------------------------------'
# print_status_report()
#-------------------------------------------------------------------
def remove_bad_slopes(self, FLOAT=False):
#------------------------------------------------------------
# Notes: The main purpose of this routine is to find
# pixels that have nonpositive slopes and replace
# then with the smallest value that occurs anywhere
# in the input slope grid. For example, pixels on
# the edges of the DEM will have a slope of zero.
# With the Kinematic Wave option, flow cannot leave
# a pixel that has a slope of zero and the depth
# increases in an unrealistic manner to create a
# spike in the depth grid.
# It would be better, of course, if there were
# no zero-slope pixels in the DEM. We could use
# an "Imposed gradient DEM" to get slopes or some
# method of "profile smoothing".
# It is possible for the flow code to be nonzero
# at a pixel that has NaN for its slope. For these
# pixels, we also set the slope to our min value.
# 7/18/05. Broke this out into separate procedure.
#------------------------------------------------------------
#-----------------------------------
# Are there any "bad" pixels ?
# If not, return with no messages.
#-----------------------------------
wb = np.where(np.logical_or((self.slope <= 0.0), \
np.logical_not(np.isfinite(self.slope))))
nbad = np.size(wb[0])
print 'size(slope) =', np.size(self.slope)
print 'size(wb) =', nbad
wg = np.where(np.invert(np.logical_or((self.slope <= 0.0), \
np.logical_not(np.isfinite(self.slope)))))
ngood = np.size(wg[0])
if (nbad == 0) or (ngood == 0):
return
#---------------------------------------------
# Find smallest positive value in slope grid
# and replace the "bad" values with smin.
#---------------------------------------------
print '-------------------------------------------------'
print 'WARNING: Zero or negative slopes found.'
print ' Replacing them with smallest slope.'
print ' Use "Profile smoothing tool" instead.'
S_min = self.slope[wg].min()
S_max = self.slope[wg].max()
print ' min(S) = ' + str(S_min)
print ' max(S) = ' + str(S_max)
print '-------------------------------------------------'
print ' '
self.slope[wb] = S_min
#--------------------------------
# Convert data type to double ?
#--------------------------------
if (FLOAT):
self.slope = np.float32(self.slope)
else:
self.slope = np.float64(self.slope)
# remove_bad_slopes
#-------------------------------------------------------------------
#-------------------------------------------------------------------
def Trapezoid_Rh(d, wb, theta):
#-------------------------------------------------------------
# Notes: Compute the hydraulic radius of a trapezoid that:
# (1) has a bed width of wb >= 0 (0 for triangular)
# (2) has a bank angle of theta (0 for rectangular)
# (3) is filled with water to a depth of d.
# The units of wb and d are meters. The units of
# theta are assumed to be degrees and are converted.
#-------------------------------------------------------------
# NB! wb should never be zero, so PW can never be 0,
# which would produce a NaN (divide by zero).
#-------------------------------------------------------------
# See Notes for TF_Tan function in utils_TF.pro
# AW = d * (wb + (d * TF_Tan(theta_rad)) )
#-------------------------------------------------------------
theta_rad = (theta * np.pi / 180.0)
AW = d * (wb + (d * np.tan(theta_rad)) )
PW = wb + (np.float64(2) * d / np.cos(theta_rad) )
Rh = (AW / PW)
w = np.where(wb <= 0)
nw = np.size(w[0])
return Rh
# Trapezoid_Rh()
#-------------------------------------------------------------------
def Manning_Formula(Rh, S, nval):
#---------------------------------------------------------
# Notes: R = (A/P) = hydraulic radius [m]
# N = Manning's roughness coefficient
# (usually in the range 0.012 to 0.035)
# S = bed slope (assumed equal to friction slope)
# R,S, and N may be 2D arrays.
# If length units are all *feet*, then an extra
# factor of 1.49 must be applied. If units are
# meters, no such factor is needed.
# Note that Q = Ac * u, where Ac is cross-section
# area. For a trapezoid, Ac does not equal w*d.
#---------------------------------------------------------
## if (N == None): N = np.float64(0.03)
two_thirds = np.float64(2) / 3.0
u = (Rh ** two_thirds) * np.sqrt(S) / nval
#------------------------------
# Add a hydraulic jump option
# for when u gets too big ??
#------------------------------
return u
# Manning_Formula()
#-------------------------------------------------------------------
def Law_of_the_Wall(d, Rh, S, z0val):
#---------------------------------------------------------
# Notes: u = flow velocity [m/s]
# d = flow depth [m]
# z0 = roughness height
# S = bed slope (assumed equal to friction slope)
# g = 9.81 = gravitation constant [m/s^2]
# kappa = 0.41 = von Karman's constant
# aval = 0.48 = integration constant
# sqrt(g)/kappa = 7.6393d
# smoothness = (aval / z0) * d
# f = (kappa / alog(smoothness))^2d
# tau_bed = rho_w * f * u^2 = rho_w * g * d * S
# d, S, and z0 can be arrays.
# To make default z0 correspond to default
# Manning's n, can use this approximation:
# z0 = a * (2.34 * sqrt(9.81) * n / kappa)^6d
# For n=0.03, this gives: z0 = 0.011417
# However, for n=0.3, it gives: z0 = 11417.413
# which is 11.4 km! So the approximation only
# holds within some range of values.
#--------------------------------------------------------
## if (self.z0val == None):
## self.z0val = np.float64(0.011417) # (about 1 cm)
#------------------------
# Define some constants
#------------------------
g = np.float64(9.81) # (gravitation const.)
aval = np.float64(0.476) # (integration const.)
kappa = np.float64(0.408) # (von Karman's const.)
law_const = np.sqrt(g) / kappa
smoothness = (aval / z0val) * d
#-----------------------------
# Make sure (smoothness > 1)
#-----------------------------
smoothness = np.maximum(smoothness, np.float64(1.1))
u = law_const * np.sqrt(Rh * S) * np.log(smoothness)
#------------------------------
# Add a hydraulic jump option
# for when u gets too big ??
#------------------------------
return u | mperignon/component_creator | topoflow_creator/topoflow/channels_base.py | Python | gpl-2.0 | 124,876 |
#include <QDebug>
#include <net/if.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include "monitor.h"
Monitor::Monitor()
{
running = 0;
}
void Monitor::start()
{
int rc;
int s;
fd_set rdfs;
int nbytes;
struct sockaddr_can addr;
struct canfd_frame frame;
struct iovec iov;
char ctrlmsg[CMSG_SPACE(sizeof(struct timeval)) + CMSG_SPACE(sizeof(__u32))];
struct msghdr msg;
struct ifreq ifr;
char* ifname = "can0";
running = 1;
s = socket(PF_CAN, SOCK_RAW, CAN_RAW);
if (s < 0)
{
qDebug() << "Error opening socket: " << s;
stop();
return;
}
strcpy(ifr.ifr_name, ifname);
ioctl(s, SIOCGIFINDEX, &ifr);
addr.can_family = AF_CAN;
addr.can_ifindex = ifr.ifr_ifindex;
rc = bind(s, (struct sockaddr*)&addr, sizeof(addr));
if (rc < 0)
{
qDebug() << "Error binding to interface: " << rc;
stop();
return;
}
iov.iov_base = &frame;
msg.msg_name = &addr;
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
msg.msg_control = &ctrlmsg;
while (running)
{
FD_ZERO(&rdfs);
FD_SET(s, &rdfs);
rc = select(s, &rdfs, NULL, NULL, NULL);
if (rc < 0)
{
qDebug() << "Error calling select" << rc;
stop();
continue;
}
if (FD_ISSET(s, &rdfs))
{
int maxdlen;
// These can apparently get changed, so set before each read
iov.iov_len = sizeof(frame);
msg.msg_namelen = sizeof(addr);
msg.msg_controllen = sizeof(ctrlmsg);
msg.msg_flags = 0;
nbytes = recvmsg(s, &msg, 0);
if (nbytes < 0)
{
qDebug() << "Error calling recvmsg : " << nbytes;
stop();
continue;
}
if ((size_t)nbytes == CAN_MTU)
maxdlen = CAN_MAX_DLEN;
else if ((size_t)nbytes == CANFD_MTU)
maxdlen = CANFD_MAX_DLEN;
else
{
qDebug() << "Warning: read incomplete CAN frame : " << nbytes;
continue;
}
// TODO get timestamp from message
sendMsg(&frame, maxdlen);
}
}
}
void Monitor::stop()
{
running = 0;
}
void Monitor::sendMsg(struct canfd_frame *frame, int maxdlen)
{
canMessage msg;
char buf[200];
int pBuf = 0;
int i;
int len = (frame->len > maxdlen) ? maxdlen : frame->len;
msg.interface = 1; // TODO set in constructor at some point
msg.identifier = QString("%1:%03X")
.arg(msg.interface)
.arg(frame->can_id & CAN_SFF_MASK);
msg.time = QTime::currentTime();
pBuf += sprintf(buf + pBuf, "[%d]", frame->len);
if (frame->can_id & CAN_RTR_FLAG)
{
pBuf += sprintf(buf + pBuf, " remote request");
emit messageInBuffer(&msg);
return;
}
for (i = 0; i < len; i++)
{
pBuf += sprintf(buf + pBuf, " [%02X]", frame->data[i]);
}
msg.content = QString("%1").arg(buf);
emit messageInBuffer(&msg);
}
| timrule/qt-projects | canmon/monitor.cpp | C++ | gpl-2.0 | 2,638 |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.34209
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace CC.Common.Compression.Demo.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
| CanyonCounty/CC.Common.Compression | CC.Common.Compression.Demo/Properties/Settings.Designer.cs | C# | gpl-2.0 | 1,061 |
/* Copyright (c) 2009-2013, The Linux Foundation. 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 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/platform_device.h>
#include <linux/cdev.h>
#include <linux/list.h>
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/interrupt.h>
#include <linux/sched.h>
#include <linux/uaccess.h>
#include <linux/clk.h>
#include <linux/android_pmem.h>
#include <linux/msm_rotator.h>
#include <linux/io.h>
#include <mach/msm_rotator_imem.h>
#include <linux/ktime.h>
#include <linux/workqueue.h>
#include <linux/file.h>
#include <linux/major.h>
#include <linux/regulator/consumer.h>
#include <linux/msm_ion.h>
#include <linux/sync.h>
#include <linux/sw_sync.h>
#ifdef CONFIG_MSM_BUS_SCALING
#include <mach/msm_bus.h>
#include <mach/msm_bus_board.h>
#endif
#include <mach/msm_subsystem_map.h>
#include <mach/iommu_domains.h>
#define DRIVER_NAME "msm_rotator"
#define MSM_ROTATOR_BASE (msm_rotator_dev->io_base)
#define MSM_ROTATOR_INTR_ENABLE (MSM_ROTATOR_BASE+0x0020)
#define MSM_ROTATOR_INTR_STATUS (MSM_ROTATOR_BASE+0x0024)
#define MSM_ROTATOR_INTR_CLEAR (MSM_ROTATOR_BASE+0x0028)
#define MSM_ROTATOR_START (MSM_ROTATOR_BASE+0x0030)
#define MSM_ROTATOR_MAX_BURST_SIZE (MSM_ROTATOR_BASE+0x0050)
#define MSM_ROTATOR_HW_VERSION (MSM_ROTATOR_BASE+0x0070)
#define MSM_ROTATOR_SW_RESET (MSM_ROTATOR_BASE+0x0074)
#define MSM_ROTATOR_SRC_SIZE (MSM_ROTATOR_BASE+0x1108)
#define MSM_ROTATOR_SRCP0_ADDR (MSM_ROTATOR_BASE+0x110c)
#define MSM_ROTATOR_SRCP1_ADDR (MSM_ROTATOR_BASE+0x1110)
#define MSM_ROTATOR_SRCP2_ADDR (MSM_ROTATOR_BASE+0x1114)
#define MSM_ROTATOR_SRC_YSTRIDE1 (MSM_ROTATOR_BASE+0x111c)
#define MSM_ROTATOR_SRC_YSTRIDE2 (MSM_ROTATOR_BASE+0x1120)
#define MSM_ROTATOR_SRC_FORMAT (MSM_ROTATOR_BASE+0x1124)
#define MSM_ROTATOR_SRC_UNPACK_PATTERN1 (MSM_ROTATOR_BASE+0x1128)
#define MSM_ROTATOR_SUB_BLOCK_CFG (MSM_ROTATOR_BASE+0x1138)
#define MSM_ROTATOR_OUT_PACK_PATTERN1 (MSM_ROTATOR_BASE+0x1154)
#define MSM_ROTATOR_OUTP0_ADDR (MSM_ROTATOR_BASE+0x1168)
#define MSM_ROTATOR_OUTP1_ADDR (MSM_ROTATOR_BASE+0x116c)
#define MSM_ROTATOR_OUTP2_ADDR (MSM_ROTATOR_BASE+0x1170)
#define MSM_ROTATOR_OUT_YSTRIDE1 (MSM_ROTATOR_BASE+0x1178)
#define MSM_ROTATOR_OUT_YSTRIDE2 (MSM_ROTATOR_BASE+0x117c)
#define MSM_ROTATOR_SRC_XY (MSM_ROTATOR_BASE+0x1200)
#define MSM_ROTATOR_SRC_IMAGE_SIZE (MSM_ROTATOR_BASE+0x1208)
#define MSM_ROTATOR_MAX_ROT 0x07
#define MSM_ROTATOR_MAX_H 0x1fff
#define MSM_ROTATOR_MAX_W 0x1fff
/* from lsb to msb */
#define GET_PACK_PATTERN(a, x, y, z, bit) \
(((a)<<((bit)*3))|((x)<<((bit)*2))|((y)<<(bit))|(z))
#define CLR_G 0x0
#define CLR_B 0x1
#define CLR_R 0x2
#define CLR_ALPHA 0x3
#define CLR_Y CLR_G
#define CLR_CB CLR_B
#define CLR_CR CLR_R
#define ROTATIONS_TO_BITMASK(r) ((((r) & MDP_ROT_90) ? 1 : 0) | \
(((r) & MDP_FLIP_LR) ? 2 : 0) | \
(((r) & MDP_FLIP_UD) ? 4 : 0))
#define IMEM_NO_OWNER -1;
#define MAX_SESSIONS 16
#define INVALID_SESSION -1
#define VERSION_KEY_MASK 0xFFFFFF00
#define MAX_DOWNSCALE_RATIO 3
#define MAX_COMMIT_QUEUE 4
#define WAIT_ROT_TIMEOUT 1000
#define MAX_TIMELINE_NAME_LEN 16
#define WAIT_FENCE_FIRST_TIMEOUT MSEC_PER_SEC
#define WAIT_FENCE_FINAL_TIMEOUT (10 * MSEC_PER_SEC)
#define ROTATOR_REVISION_V0 0
#define ROTATOR_REVISION_V1 1
#define ROTATOR_REVISION_V2 2
#define ROTATOR_REVISION_NONE 0xffffffff
#define BASE_ADDR(height, y_stride) ((height % 64) * y_stride)
#define HW_BASE_ADDR(height, y_stride) (((dstp0_ystride >> 5) << 11) - \
((dst_height & 0x3f) * dstp0_ystride))
uint32_t rotator_hw_revision;
static char rot_iommu_split_domain;
/*
* rotator_hw_revision:
* 0 == 7x30
* 1 == 8x60
* 2 == 8960
*
*/
struct tile_parm {
unsigned int width; /* tile's width */
unsigned int height; /* tile's height */
unsigned int row_tile_w; /* tiles per row's width */
unsigned int row_tile_h; /* tiles per row's height */
};
struct msm_rotator_mem_planes {
unsigned int num_planes;
unsigned int plane_size[4];
unsigned int total_size;
};
#define checkoffset(offset, size, max_size) \
((size) > (max_size) || (offset) > ((max_size) - (size)))
struct msm_rotator_fd_info {
int pid;
int ref_cnt;
struct list_head list;
};
struct rot_sync_info {
u32 initialized;
struct sync_fence *acq_fen;
struct sync_fence *rel_fen;
int rel_fen_fd;
struct sw_sync_timeline *timeline;
int timeline_value;
struct mutex sync_mutex;
atomic_t queue_buf_cnt;
};
struct msm_rotator_session {
struct msm_rotator_img_info img_info;
struct msm_rotator_fd_info fd_info;
int fast_yuv_enable;
int enable_2pass;
u32 mem_hid;
};
struct msm_rotator_commit_info {
struct msm_rotator_data_info data_info;
struct msm_rotator_img_info img_info;
unsigned int format;
unsigned int in_paddr;
unsigned int out_paddr;
unsigned int in_chroma_paddr;
unsigned int out_chroma_paddr;
unsigned int in_chroma2_paddr;
unsigned int out_chroma2_paddr;
struct file *srcp0_file;
struct file *srcp1_file;
struct file *dstp0_file;
struct file *dstp1_file;
struct ion_handle *srcp0_ihdl;
struct ion_handle *srcp1_ihdl;
struct ion_handle *dstp0_ihdl;
struct ion_handle *dstp1_ihdl;
int ps0_need;
int session_index;
struct sync_fence *acq_fen;
int fast_yuv_en;
int enable_2pass;
};
struct msm_rotator_dev {
void __iomem *io_base;
int irq;
struct clk *core_clk;
struct msm_rotator_session *rot_session[MAX_SESSIONS];
struct list_head fd_list;
struct clk *pclk;
int rot_clk_state;
struct regulator *regulator;
struct delayed_work rot_clk_work;
struct clk *imem_clk;
int imem_clk_state;
struct delayed_work imem_clk_work;
struct platform_device *pdev;
struct cdev cdev;
struct device *device;
struct class *class;
dev_t dev_num;
int processing;
int last_session_idx;
struct mutex rotator_lock;
struct mutex imem_lock;
int imem_owner;
wait_queue_head_t wq;
struct ion_client *client;
#ifdef CONFIG_MSM_BUS_SCALING
uint32_t bus_client_handle;
#endif
u32 sec_mapped;
u32 mmu_clk_on;
struct rot_sync_info sync_info[MAX_SESSIONS];
/* non blocking */
struct mutex commit_mutex;
struct mutex commit_wq_mutex;
struct completion commit_comp;
u32 commit_running;
struct work_struct commit_work;
struct msm_rotator_commit_info commit_info[MAX_COMMIT_QUEUE];
atomic_t commit_q_r;
atomic_t commit_q_w;
atomic_t commit_q_cnt;
struct rot_buf_type *y_rot_buf;
struct rot_buf_type *chroma_rot_buf;
struct rot_buf_type *chroma2_rot_buf;
};
#define COMPONENT_5BITS 1
#define COMPONENT_6BITS 2
#define COMPONENT_8BITS 3
static struct msm_rotator_dev *msm_rotator_dev;
#define mrd msm_rotator_dev
static void rot_wait_for_commit_queue(u32 is_all);
enum {
CLK_EN,
CLK_DIS,
CLK_SUSPEND,
};
struct res_mmu_clk {
char *mmu_clk_name;
struct clk *mmu_clk;
};
static struct res_mmu_clk rot_mmu_clks[] = {
{"mdp_iommu_clk"}, {"rot_iommu_clk"},
{"vcodec_iommu0_clk"}, {"vcodec_iommu1_clk"},
{"smmu_iface_clk"}
};
u32 rotator_allocate_2pass_buf(struct rot_buf_type *rot_buf, int s_ndx)
{
ion_phys_addr_t addr, read_addr = 0;
size_t buffer_size;
unsigned long len;
if (!rot_buf) {
pr_err("Rot_buf NULL pointer %s %i", __func__, __LINE__);
return 0;
}
if (rot_buf->write_addr || !IS_ERR_OR_NULL(rot_buf->ihdl))
return 0;
buffer_size = roundup(1920 * 1088, SZ_4K);
if (!IS_ERR_OR_NULL(mrd->client)) {
pr_info("%s:%d ion based allocation\n",
__func__, __LINE__);
rot_buf->ihdl = ion_alloc(mrd->client, buffer_size, SZ_4K,
mrd->rot_session[s_ndx]->mem_hid,
mrd->rot_session[s_ndx]->mem_hid & ION_SECURE);
if (!IS_ERR_OR_NULL(rot_buf->ihdl)) {
if (rot_iommu_split_domain) {
if (ion_map_iommu(mrd->client, rot_buf->ihdl,
ROTATOR_SRC_DOMAIN, GEN_POOL, SZ_4K,
0, &read_addr, &len, 0, 0)) {
pr_err("ion_map_iommu() read failed\n");
return -ENOMEM;
}
if (mrd->rot_session[s_ndx]->mem_hid &
ION_SECURE) {
if (ion_phys(mrd->client, rot_buf->ihdl,
&addr, (size_t *)&len)) {
pr_err(
"%s:%d: ion_phys map failed\n",
__func__, __LINE__);
return -ENOMEM;
}
} else {
if (ion_map_iommu(mrd->client,
rot_buf->ihdl, ROTATOR_DST_DOMAIN,
GEN_POOL, SZ_4K, 0, &addr, &len,
0, 0)) {
pr_err("ion_map_iommu() failed\n");
return -ENOMEM;
}
}
} else {
if (ion_map_iommu(mrd->client, rot_buf->ihdl,
ROTATOR_SRC_DOMAIN, GEN_POOL, SZ_4K,
0, &addr, &len, 0, 0)) {
pr_err("ion_map_iommu() write failed\n");
return -ENOMEM;
}
}
} else {
pr_err("%s:%d: ion_alloc failed\n", __func__,
__LINE__);
return -ENOMEM;
}
} else {
addr = allocate_contiguous_memory_nomap(buffer_size,
mrd->rot_session[s_ndx]->mem_hid, 4);
}
if (addr) {
pr_info("allocating %d bytes at write=%x, read=%x for 2-pass\n",
buffer_size, (u32) addr, (u32) read_addr);
rot_buf->write_addr = addr;
if (read_addr)
rot_buf->read_addr = read_addr;
else
rot_buf->read_addr = rot_buf->write_addr;
return 0;
} else {
pr_err("%s cannot allocate memory for rotator 2-pass!\n",
__func__);
return -ENOMEM;
}
}
void rotator_free_2pass_buf(struct rot_buf_type *rot_buf, int s_ndx)
{
if (!rot_buf) {
pr_err("Rot_buf NULL pointer %s %i", __func__, __LINE__);
return;
}
if (!rot_buf->write_addr)
return;
if (!IS_ERR_OR_NULL(mrd->client)) {
if (!IS_ERR_OR_NULL(rot_buf->ihdl)) {
if (rot_iommu_split_domain) {
if (!(mrd->rot_session[s_ndx]->mem_hid &
ION_SECURE))
ion_unmap_iommu(mrd->client,
rot_buf->ihdl, ROTATOR_DST_DOMAIN,
GEN_POOL);
ion_unmap_iommu(mrd->client, rot_buf->ihdl,
ROTATOR_SRC_DOMAIN, GEN_POOL);
} else {
ion_unmap_iommu(mrd->client, rot_buf->ihdl,
ROTATOR_SRC_DOMAIN, GEN_POOL);
}
ion_free(mrd->client, rot_buf->ihdl);
rot_buf->ihdl = NULL;
pr_info("%s:%d Free rotator 2pass memory",
__func__, __LINE__);
}
} else {
if (rot_buf->write_addr) {
free_contiguous_memory_by_paddr(rot_buf->write_addr);
pr_debug("%s:%d Free rotator 2pass pmem\n", __func__,
__LINE__);
}
}
rot_buf->write_addr = 0;
rot_buf->read_addr = 0;
}
int msm_rotator_iommu_map_buf(int mem_id, int domain,
unsigned long *start, unsigned long *len,
struct ion_handle **pihdl, unsigned int secure)
{
if (!msm_rotator_dev->client)
return -EINVAL;
*pihdl = ion_import_dma_buf(msm_rotator_dev->client, mem_id);
if (IS_ERR_OR_NULL(*pihdl)) {
pr_err("ion_import_dma_buf() failed\n");
return PTR_ERR(*pihdl);
}
pr_debug("%s(): ion_hdl %p, ion_fd %d\n", __func__, *pihdl, mem_id);
if (rot_iommu_split_domain) {
if (secure) {
if (ion_phys(msm_rotator_dev->client,
*pihdl, start, (unsigned *)len)) {
pr_err("%s:%d: ion_phys map failed\n",
__func__, __LINE__);
return -ENOMEM;
}
} else {
if (ion_map_iommu(msm_rotator_dev->client,
*pihdl, domain, GEN_POOL,
SZ_4K, 0, start, len, 0,
ION_IOMMU_UNMAP_DELAYED)) {
pr_err("ion_map_iommu() failed\n");
return -EINVAL;
}
}
} else {
if (ion_map_iommu(msm_rotator_dev->client,
*pihdl, ROTATOR_SRC_DOMAIN, GEN_POOL,
SZ_4K, 0, start, len, 0, ION_IOMMU_UNMAP_DELAYED)) {
pr_err("ion_map_iommu() failed\n");
return -EINVAL;
}
}
pr_debug("%s(): mem_id %d, start 0x%lx, len 0x%lx\n",
__func__, mem_id, *start, *len);
return 0;
}
int msm_rotator_imem_allocate(int requestor)
{
int rc = 0;
#ifdef CONFIG_MSM_ROTATOR_USE_IMEM
switch (requestor) {
case ROTATOR_REQUEST:
if (mutex_trylock(&msm_rotator_dev->imem_lock)) {
msm_rotator_dev->imem_owner = ROTATOR_REQUEST;
rc = 1;
} else
rc = 0;
break;
case JPEG_REQUEST:
mutex_lock(&msm_rotator_dev->imem_lock);
msm_rotator_dev->imem_owner = JPEG_REQUEST;
rc = 1;
break;
default:
rc = 0;
}
#else
if (requestor == JPEG_REQUEST)
rc = 1;
#endif
if (rc == 1) {
cancel_delayed_work_sync(&msm_rotator_dev->imem_clk_work);
if (msm_rotator_dev->imem_clk_state != CLK_EN
&& msm_rotator_dev->imem_clk) {
clk_prepare_enable(msm_rotator_dev->imem_clk);
msm_rotator_dev->imem_clk_state = CLK_EN;
}
}
return rc;
}
EXPORT_SYMBOL(msm_rotator_imem_allocate);
void msm_rotator_imem_free(int requestor)
{
#ifdef CONFIG_MSM_ROTATOR_USE_IMEM
if (msm_rotator_dev->imem_owner == requestor) {
schedule_delayed_work(&msm_rotator_dev->imem_clk_work, HZ);
mutex_unlock(&msm_rotator_dev->imem_lock);
}
#else
if (requestor == JPEG_REQUEST)
schedule_delayed_work(&msm_rotator_dev->imem_clk_work, HZ);
#endif
}
EXPORT_SYMBOL(msm_rotator_imem_free);
static void msm_rotator_imem_clk_work_f(struct work_struct *work)
{
#ifdef CONFIG_MSM_ROTATOR_USE_IMEM
if (mutex_trylock(&msm_rotator_dev->imem_lock)) {
if (msm_rotator_dev->imem_clk_state == CLK_EN
&& msm_rotator_dev->imem_clk) {
clk_disable_unprepare(msm_rotator_dev->imem_clk);
msm_rotator_dev->imem_clk_state = CLK_DIS;
} else if (msm_rotator_dev->imem_clk_state == CLK_SUSPEND)
msm_rotator_dev->imem_clk_state = CLK_DIS;
mutex_unlock(&msm_rotator_dev->imem_lock);
}
#endif
}
/* enable clocks needed by rotator block */
static void enable_rot_clks(void)
{
if (msm_rotator_dev->regulator)
regulator_enable(msm_rotator_dev->regulator);
if (msm_rotator_dev->core_clk != NULL)
clk_prepare_enable(msm_rotator_dev->core_clk);
if (msm_rotator_dev->pclk != NULL)
clk_prepare_enable(msm_rotator_dev->pclk);
}
/* disable clocks needed by rotator block */
static void disable_rot_clks(void)
{
if (msm_rotator_dev->core_clk != NULL)
clk_disable_unprepare(msm_rotator_dev->core_clk);
if (msm_rotator_dev->pclk != NULL)
clk_disable_unprepare(msm_rotator_dev->pclk);
if (msm_rotator_dev->regulator)
regulator_disable(msm_rotator_dev->regulator);
}
static void msm_rotator_rot_clk_work_f(struct work_struct *work)
{
if (mutex_trylock(&msm_rotator_dev->rotator_lock)) {
if (msm_rotator_dev->rot_clk_state == CLK_EN) {
disable_rot_clks();
msm_rotator_dev->rot_clk_state = CLK_DIS;
} else if (msm_rotator_dev->rot_clk_state == CLK_SUSPEND)
msm_rotator_dev->rot_clk_state = CLK_DIS;
mutex_unlock(&msm_rotator_dev->rotator_lock);
}
}
static irqreturn_t msm_rotator_isr(int irq, void *dev_id)
{
if (msm_rotator_dev->processing) {
msm_rotator_dev->processing = 0;
wake_up(&msm_rotator_dev->wq);
} else
printk(KERN_WARNING "%s: unexpected interrupt\n", DRIVER_NAME);
return IRQ_HANDLED;
}
static void msm_rotator_signal_timeline(u32 session_index)
{
struct rot_sync_info *sync_info;
sync_info = &msm_rotator_dev->sync_info[session_index];
if ((!sync_info->timeline) || (!sync_info->initialized))
return;
mutex_lock(&sync_info->sync_mutex);
sw_sync_timeline_inc(sync_info->timeline, 1);
sync_info->timeline_value++;
mutex_unlock(&sync_info->sync_mutex);
}
static void msm_rotator_signal_timeline_done(u32 session_index)
{
struct rot_sync_info *sync_info;
sync_info = &msm_rotator_dev->sync_info[session_index];
if ((sync_info->timeline == NULL) ||
(sync_info->initialized == false))
return;
mutex_lock(&sync_info->sync_mutex);
sw_sync_timeline_inc(sync_info->timeline, 1);
sync_info->timeline_value++;
if (atomic_read(&sync_info->queue_buf_cnt) <= 0)
pr_err("%s queue_buf_cnt=%d", __func__,
atomic_read(&sync_info->queue_buf_cnt));
else
atomic_dec(&sync_info->queue_buf_cnt);
mutex_unlock(&sync_info->sync_mutex);
}
static void msm_rotator_release_acq_fence(u32 session_index)
{
struct rot_sync_info *sync_info;
sync_info = &msm_rotator_dev->sync_info[session_index];
if ((!sync_info->timeline) || (!sync_info->initialized))
return;
mutex_lock(&sync_info->sync_mutex);
sync_info->acq_fen = NULL;
mutex_unlock(&sync_info->sync_mutex);
}
static void msm_rotator_release_all_timeline(void)
{
int i;
struct rot_sync_info *sync_info;
for (i = 0; i < MAX_SESSIONS; i++) {
sync_info = &msm_rotator_dev->sync_info[i];
if (sync_info->initialized) {
msm_rotator_signal_timeline(i);
msm_rotator_release_acq_fence(i);
}
}
}
static void msm_rotator_wait_for_fence(struct sync_fence *acq_fen)
{
int ret;
if (acq_fen) {
ret = sync_fence_wait(acq_fen,
WAIT_FENCE_FIRST_TIMEOUT);
if (ret == -ETIME) {
pr_warn("%s: timeout, wait %ld more ms\n",
__func__, WAIT_FENCE_FINAL_TIMEOUT);
ret = sync_fence_wait(acq_fen,
WAIT_FENCE_FINAL_TIMEOUT);
}
if (ret < 0) {
pr_err("%s: sync_fence_wait failed! ret = %x\n",
__func__, ret);
}
sync_fence_put(acq_fen);
}
}
static int msm_rotator_buf_sync(unsigned long arg)
{
struct msm_rotator_buf_sync buf_sync;
int ret = 0;
struct sync_fence *fence = NULL;
struct rot_sync_info *sync_info;
struct sync_pt *rel_sync_pt;
struct sync_fence *rel_fence;
int rel_fen_fd;
u32 s;
if (copy_from_user(&buf_sync, (void __user *)arg, sizeof(buf_sync)))
return -EFAULT;
rot_wait_for_commit_queue(false);
for (s = 0; s < MAX_SESSIONS; s++)
if ((msm_rotator_dev->rot_session[s] != NULL) &&
(buf_sync.session_id ==
(unsigned int)msm_rotator_dev->rot_session[s]
))
break;
if (s == MAX_SESSIONS) {
pr_err("%s invalid session id %d", __func__,
buf_sync.session_id);
return -EINVAL;
}
sync_info = &msm_rotator_dev->sync_info[s];
if (sync_info->acq_fen)
pr_err("%s previous acq_fen will be overwritten", __func__);
if ((sync_info->timeline == NULL) ||
(sync_info->initialized == false))
return -EINVAL;
mutex_lock(&sync_info->sync_mutex);
if (buf_sync.acq_fen_fd >= 0)
fence = sync_fence_fdget(buf_sync.acq_fen_fd);
sync_info->acq_fen = fence;
if (sync_info->acq_fen &&
(buf_sync.flags & MDP_BUF_SYNC_FLAG_WAIT)) {
msm_rotator_wait_for_fence(sync_info->acq_fen);
sync_info->acq_fen = NULL;
}
rel_sync_pt = sw_sync_pt_create(sync_info->timeline,
sync_info->timeline_value +
atomic_read(&sync_info->queue_buf_cnt) + 1);
if (rel_sync_pt == NULL) {
pr_err("%s: cannot create sync point", __func__);
ret = -ENOMEM;
goto buf_sync_err_1;
}
/* create fence */
rel_fence = sync_fence_create("msm_rotator-fence",
rel_sync_pt);
if (rel_fence == NULL) {
sync_pt_free(rel_sync_pt);
pr_err("%s: cannot create fence", __func__);
ret = -ENOMEM;
goto buf_sync_err_1;
}
/* create fd */
rel_fen_fd = get_unused_fd_flags(0);
if (rel_fen_fd < 0) {
pr_err("%s: get_unused_fd_flags failed", __func__);
ret = -EIO;
goto buf_sync_err_2;
}
sync_fence_install(rel_fence, rel_fen_fd);
buf_sync.rel_fen_fd = rel_fen_fd;
sync_info->rel_fen = rel_fence;
sync_info->rel_fen_fd = rel_fen_fd;
ret = copy_to_user((void __user *)arg, &buf_sync, sizeof(buf_sync));
mutex_unlock(&sync_info->sync_mutex);
return ret;
buf_sync_err_2:
sync_fence_put(rel_fence);
buf_sync_err_1:
if (sync_info->acq_fen)
sync_fence_put(sync_info->acq_fen);
sync_info->acq_fen = NULL;
mutex_unlock(&sync_info->sync_mutex);
return ret;
}
static unsigned int tile_size(unsigned int src_width,
unsigned int src_height,
const struct tile_parm *tp)
{
unsigned int tile_w, tile_h;
unsigned int row_num_w, row_num_h;
tile_w = tp->width * tp->row_tile_w;
tile_h = tp->height * tp->row_tile_h;
row_num_w = (src_width + tile_w - 1) / tile_w;
row_num_h = (src_height + tile_h - 1) / tile_h;
return ((row_num_w * row_num_h * tile_w * tile_h) + 8191) & ~8191;
}
static int get_bpp(int format)
{
switch (format) {
case MDP_RGB_565:
case MDP_BGR_565:
return 2;
case MDP_XRGB_8888:
case MDP_ARGB_8888:
case MDP_RGBA_8888:
case MDP_BGRA_8888:
case MDP_RGBX_8888:
return 4;
case MDP_Y_CBCR_H2V2:
case MDP_Y_CRCB_H2V2:
case MDP_Y_CB_CR_H2V2:
case MDP_Y_CR_CB_H2V2:
case MDP_Y_CR_CB_GH2V2:
case MDP_Y_CRCB_H2V2_TILE:
case MDP_Y_CBCR_H2V2_TILE:
return 1;
case MDP_RGB_888:
case MDP_YCBCR_H1V1:
case MDP_YCRCB_H1V1:
return 3;
case MDP_YCRYCB_H2V1:
return 2;/* YCrYCb interleave */
case MDP_Y_CRCB_H2V1:
case MDP_Y_CBCR_H2V1:
return 1;
default:
return -1;
}
}
static int msm_rotator_get_plane_sizes(uint32_t format, uint32_t w, uint32_t h,
struct msm_rotator_mem_planes *p)
{
/*
* each row of samsung tile consists of two tiles in height
* and two tiles in width which means width should align to
* 64 x 2 bytes and height should align to 32 x 2 bytes.
* video decoder generate two tiles in width and one tile
* in height which ends up height align to 32 X 1 bytes.
*/
const struct tile_parm tile = {64, 32, 2, 1};
int i;
if (p == NULL)
return -EINVAL;
if ((w > MSM_ROTATOR_MAX_W) || (h > MSM_ROTATOR_MAX_H))
return -ERANGE;
memset(p, 0, sizeof(*p));
switch (format) {
case MDP_XRGB_8888:
case MDP_ARGB_8888:
case MDP_RGBA_8888:
case MDP_BGRA_8888:
case MDP_RGBX_8888:
case MDP_RGB_888:
case MDP_RGB_565:
case MDP_BGR_565:
case MDP_YCRYCB_H2V1:
case MDP_YCBCR_H1V1:
case MDP_YCRCB_H1V1:
p->num_planes = 1;
p->plane_size[0] = w * h * get_bpp(format);
break;
case MDP_Y_CRCB_H2V1:
case MDP_Y_CBCR_H2V1:
case MDP_Y_CRCB_H1V2:
case MDP_Y_CBCR_H1V2:
p->num_planes = 2;
p->plane_size[0] = w * h;
p->plane_size[1] = w * h;
break;
case MDP_Y_CBCR_H2V2:
case MDP_Y_CRCB_H2V2:
p->num_planes = 2;
p->plane_size[0] = w * h;
p->plane_size[1] = w * h / 2;
break;
case MDP_Y_CRCB_H2V2_TILE:
case MDP_Y_CBCR_H2V2_TILE:
p->num_planes = 2;
p->plane_size[0] = tile_size(w, h, &tile);
p->plane_size[1] = tile_size(w, h/2, &tile);
break;
case MDP_Y_CB_CR_H2V2:
case MDP_Y_CR_CB_H2V2:
p->num_planes = 3;
p->plane_size[0] = w * h;
p->plane_size[1] = (w / 2) * (h / 2);
p->plane_size[2] = (w / 2) * (h / 2);
break;
case MDP_Y_CR_CB_GH2V2:
p->num_planes = 3;
p->plane_size[0] = ALIGN(w, 16) * h;
p->plane_size[1] = ALIGN(w / 2, 16) * (h / 2);
p->plane_size[2] = ALIGN(w / 2, 16) * (h / 2);
break;
default:
return -EINVAL;
}
for (i = 0; i < p->num_planes; i++)
p->total_size += p->plane_size[i];
return 0;
}
/* Checking invalid destination image size on FAST YUV for YUV420PP(NV12) with
* HW issue for rotation 90 + U/D filp + with/without flip operation
* (rotation 90 + U/D + L/R flip is rotation 270 degree option) and pix_rot
* block issue with tile line size is 4.
*
* Rotator structure is:
* if Fetch input image: W x H,
* Downscale: W` x H` = W/ScaleHor(2, 4 or 8) x H/ScaleVert(2, 4 or 8)
* Rotated output : W`` x H`` = (W` x H`) or (H` x W`) depends on "Rotation 90
* degree option"
*
* Pack: W`` x H``
*
* Rotator source ROI image width restriction is applied to W x H (case a,
* image resolution before downscaling)
*
* Packer source Image width/ height restriction are applied to W`` x H``
* (case c, image resolution after rotation)
*
* Supertile (64 x 8) and YUV (2 x 2) alignment restriction should be
* applied to the W x H (case a). Input image should be at least (2 x 2).
*
* "Support If packer source image height <= 256, multiple of 8", this
* restriction should be applied to the rotated image (W`` x H``)
*/
uint32_t fast_yuv_invalid_size_checker(unsigned char rot_mode,
uint32_t src_width,
uint32_t dst_width,
uint32_t src_height,
uint32_t dst_height,
uint32_t dstp0_ystride,
uint32_t is_planar420)
{
uint32_t hw_limit;
hw_limit = is_planar420 ? 512 : 256;
/* checking image constaints for missing EOT event from pix_rot block */
if ((src_width > hw_limit) && ((src_width % (hw_limit / 2)) == 8))
return -EINVAL;
if (rot_mode & MDP_ROT_90) {
if ((src_height % 128) == 8)
return -EINVAL;
/* if rotation 90 degree on fast yuv
* rotator image input width has to be multiple of 8
* rotator image input height has to be multiple of 8
*/
if (((dst_width % 8) != 0) || ((dst_height % 8) != 0))
return -EINVAL;
if ((rot_mode & MDP_FLIP_UD) ||
(rot_mode & (MDP_FLIP_UD | MDP_FLIP_LR))) {
/* image constraint checking for wrong address
* generation HW issue for Y plane checking
*/
if (((dst_height % 64) != 0) &&
((dst_height / 64) >= 4)) {
/* compare golden logic for second
* tile base address generation in row
* with actual HW implementation
*/
if (BASE_ADDR(dst_height, dstp0_ystride) !=
HW_BASE_ADDR(dst_height, dstp0_ystride))
return -EINVAL;
}
if (is_planar420) {
dst_width = dst_width / 2;
dstp0_ystride = dstp0_ystride / 2;
}
dst_height = dst_height / 2;
/* image constraint checking for wrong
* address generation HW issue. for
* U/V (P) or UV (PP) plane checking
*/
if (((dst_height % 64) != 0) && ((dst_height / 64) >=
(hw_limit / 128))) {
/* compare golden logic for
* second tile base address
* generation in row with
* actual HW implementation
*/
if (BASE_ADDR(dst_height, dstp0_ystride) !=
HW_BASE_ADDR(dst_height, dstp0_ystride))
return -EINVAL;
}
}
} else {
/* if NOT applying rotation 90 degree on fast yuv,
* rotator image input width has to be multiple of 8
* rotator image input height has to be multiple of 8
*/
if (((dst_width % 8) != 0) || ((dst_height % 8) != 0))
return -EINVAL;
}
return 0;
}
static int msm_rotator_ycxcx_h2v1(struct msm_rotator_img_info *info,
unsigned int in_paddr,
unsigned int out_paddr,
unsigned int use_imem,
int new_session,
unsigned int in_chroma_paddr,
unsigned int out_chroma_paddr)
{
int bpp;
uint32_t dst_format;
switch (info->src.format) {
case MDP_Y_CRCB_H2V1:
if (info->rotations & MDP_ROT_90)
dst_format = MDP_Y_CRCB_H1V2;
else
dst_format = info->src.format;
break;
case MDP_Y_CBCR_H2V1:
if (info->rotations & MDP_ROT_90)
dst_format = MDP_Y_CBCR_H1V2;
else
dst_format = info->src.format;
break;
default:
return -EINVAL;
}
if (info->dst.format != dst_format)
return -EINVAL;
bpp = get_bpp(info->src.format);
if (bpp < 0)
return -ENOTTY;
iowrite32(in_paddr, MSM_ROTATOR_SRCP0_ADDR);
iowrite32(in_chroma_paddr, MSM_ROTATOR_SRCP1_ADDR);
iowrite32(out_paddr +
((info->dst_y * info->dst.width) + info->dst_x),
MSM_ROTATOR_OUTP0_ADDR);
iowrite32(out_chroma_paddr +
((info->dst_y * info->dst.width) + info->dst_x),
MSM_ROTATOR_OUTP1_ADDR);
if (new_session) {
iowrite32(info->src.width |
info->src.width << 16,
MSM_ROTATOR_SRC_YSTRIDE1);
if (info->rotations & MDP_ROT_90)
iowrite32(info->dst.width |
info->dst.width*2 << 16,
MSM_ROTATOR_OUT_YSTRIDE1);
else
iowrite32(info->dst.width |
info->dst.width << 16,
MSM_ROTATOR_OUT_YSTRIDE1);
if (info->src.format == MDP_Y_CBCR_H2V1) {
iowrite32(GET_PACK_PATTERN(0, 0, CLR_CB, CLR_CR, 8),
MSM_ROTATOR_SRC_UNPACK_PATTERN1);
iowrite32(GET_PACK_PATTERN(0, 0, CLR_CB, CLR_CR, 8),
MSM_ROTATOR_OUT_PACK_PATTERN1);
} else {
iowrite32(GET_PACK_PATTERN(0, 0, CLR_CR, CLR_CB, 8),
MSM_ROTATOR_SRC_UNPACK_PATTERN1);
iowrite32(GET_PACK_PATTERN(0, 0, CLR_CR, CLR_CB, 8),
MSM_ROTATOR_OUT_PACK_PATTERN1);
}
iowrite32((1 << 18) | /* chroma sampling 1=H2V1 */
(ROTATIONS_TO_BITMASK(info->rotations) << 9) |
1 << 8 | /* ROT_EN */
info->downscale_ratio << 2 | /* downscale v ratio */
info->downscale_ratio, /* downscale h ratio */
MSM_ROTATOR_SUB_BLOCK_CFG);
iowrite32(0 << 29 | /* frame format 0 = linear */
(use_imem ? 0 : 1) << 22 | /* tile size */
2 << 19 | /* fetch planes 2 = pseudo */
0 << 18 | /* unpack align */
1 << 17 | /* unpack tight */
1 << 13 | /* unpack count 0=1 component */
(bpp-1) << 9 | /* src Bpp 0=1 byte ... */
0 << 8 | /* has alpha */
0 << 6 | /* alpha bits 3=8bits */
3 << 4 | /* R/Cr bits 1=5 2=6 3=8 */
3 << 2 | /* B/Cb bits 1=5 2=6 3=8 */
3 << 0, /* G/Y bits 1=5 2=6 3=8 */
MSM_ROTATOR_SRC_FORMAT);
}
return 0;
}
static int msm_rotator_ycxcx_h2v2(struct msm_rotator_img_info *info,
unsigned int in_paddr,
unsigned int out_paddr,
unsigned int use_imem,
int new_session,
unsigned int in_chroma_paddr,
unsigned int out_chroma_paddr,
unsigned int in_chroma2_paddr,
unsigned int out_chroma2_paddr,
int fast_yuv_en)
{
uint32_t dst_format;
int is_tile = 0;
switch (info->src.format) {
case MDP_Y_CRCB_H2V2_TILE:
is_tile = 1;
dst_format = MDP_Y_CRCB_H2V2;
break;
case MDP_Y_CR_CB_H2V2:
case MDP_Y_CR_CB_GH2V2:
if (fast_yuv_en) {
dst_format = info->src.format;
break;
}
case MDP_Y_CRCB_H2V2:
dst_format = MDP_Y_CRCB_H2V2;
break;
case MDP_Y_CB_CR_H2V2:
if (fast_yuv_en) {
dst_format = info->src.format;
break;
}
dst_format = MDP_Y_CBCR_H2V2;
break;
case MDP_Y_CBCR_H2V2_TILE:
is_tile = 1;
case MDP_Y_CBCR_H2V2:
dst_format = MDP_Y_CBCR_H2V2;
break;
default:
return -EINVAL;
}
if (info->dst.format != dst_format)
return -EINVAL;
/* rotator expects YCbCr for planar input format */
if ((info->src.format == MDP_Y_CR_CB_H2V2 ||
info->src.format == MDP_Y_CR_CB_GH2V2) &&
rotator_hw_revision < ROTATOR_REVISION_V2)
swap(in_chroma_paddr, in_chroma2_paddr);
iowrite32(in_paddr, MSM_ROTATOR_SRCP0_ADDR);
iowrite32(in_chroma_paddr, MSM_ROTATOR_SRCP1_ADDR);
iowrite32(in_chroma2_paddr, MSM_ROTATOR_SRCP2_ADDR);
iowrite32(out_paddr +
((info->dst_y * info->dst.width) + info->dst_x),
MSM_ROTATOR_OUTP0_ADDR);
iowrite32(out_chroma_paddr +
(((info->dst_y * info->dst.width)/2) + info->dst_x),
MSM_ROTATOR_OUTP1_ADDR);
if (out_chroma2_paddr)
iowrite32(out_chroma2_paddr +
(((info->dst_y * info->dst.width)/2) + info->dst_x),
MSM_ROTATOR_OUTP2_ADDR);
if (new_session) {
if (in_chroma2_paddr) {
if (info->src.format == MDP_Y_CR_CB_GH2V2) {
iowrite32(ALIGN(info->src.width, 16) |
ALIGN((info->src.width / 2), 16) << 16,
MSM_ROTATOR_SRC_YSTRIDE1);
iowrite32(ALIGN((info->src.width / 2), 16),
MSM_ROTATOR_SRC_YSTRIDE2);
} else {
iowrite32(info->src.width |
(info->src.width / 2) << 16,
MSM_ROTATOR_SRC_YSTRIDE1);
iowrite32((info->src.width / 2),
MSM_ROTATOR_SRC_YSTRIDE2);
}
} else {
iowrite32(info->src.width |
info->src.width << 16,
MSM_ROTATOR_SRC_YSTRIDE1);
}
if (out_chroma2_paddr) {
if (info->dst.format == MDP_Y_CR_CB_GH2V2) {
iowrite32(ALIGN(info->dst.width, 16) |
ALIGN((info->dst.width / 2), 16) << 16,
MSM_ROTATOR_OUT_YSTRIDE1);
iowrite32(ALIGN((info->dst.width / 2), 16),
MSM_ROTATOR_OUT_YSTRIDE2);
} else {
iowrite32(info->dst.width |
info->dst.width/2 << 16,
MSM_ROTATOR_OUT_YSTRIDE1);
iowrite32(info->dst.width/2,
MSM_ROTATOR_OUT_YSTRIDE2);
}
} else {
iowrite32(info->dst.width |
info->dst.width << 16,
MSM_ROTATOR_OUT_YSTRIDE1);
}
if (dst_format == MDP_Y_CBCR_H2V2 ||
dst_format == MDP_Y_CB_CR_H2V2) {
iowrite32(GET_PACK_PATTERN(0, 0, CLR_CB, CLR_CR, 8),
MSM_ROTATOR_SRC_UNPACK_PATTERN1);
iowrite32(GET_PACK_PATTERN(0, 0, CLR_CB, CLR_CR, 8),
MSM_ROTATOR_OUT_PACK_PATTERN1);
} else {
iowrite32(GET_PACK_PATTERN(0, 0, CLR_CR, CLR_CB, 8),
MSM_ROTATOR_SRC_UNPACK_PATTERN1);
iowrite32(GET_PACK_PATTERN(0, 0, CLR_CR, CLR_CB, 8),
MSM_ROTATOR_OUT_PACK_PATTERN1);
}
iowrite32((3 << 18) | /* chroma sampling 3=4:2:0 */
(ROTATIONS_TO_BITMASK(info->rotations) << 9) |
1 << 8 | /* ROT_EN */
fast_yuv_en << 4 | /*fast YUV*/
info->downscale_ratio << 2 | /* downscale v ratio */
info->downscale_ratio, /* downscale h ratio */
MSM_ROTATOR_SUB_BLOCK_CFG);
iowrite32((is_tile ? 2 : 0) << 29 | /* frame format */
(use_imem ? 0 : 1) << 22 | /* tile size */
(in_chroma2_paddr ? 1 : 2) << 19 | /* fetch planes */
0 << 18 | /* unpack align */
1 << 17 | /* unpack tight */
1 << 13 | /* unpack count 0=1 component */
0 << 9 | /* src Bpp 0=1 byte ... */
0 << 8 | /* has alpha */
0 << 6 | /* alpha bits 3=8bits */
3 << 4 | /* R/Cr bits 1=5 2=6 3=8 */
3 << 2 | /* B/Cb bits 1=5 2=6 3=8 */
3 << 0, /* G/Y bits 1=5 2=6 3=8 */
MSM_ROTATOR_SRC_FORMAT);
}
return 0;
}
static int msm_rotator_ycxcx_h2v2_2pass(struct msm_rotator_img_info *info,
unsigned int in_paddr,
unsigned int out_paddr,
unsigned int use_imem,
int new_session,
unsigned int in_chroma_paddr,
unsigned int out_chroma_paddr,
unsigned int in_chroma2_paddr,
unsigned int out_chroma2_paddr,
int fast_yuv_en,
int enable_2pass,
int session_index)
{
uint32_t pass2_src_format, pass1_dst_format, dst_format;
int is_tile = 0, post_pass1_buf_is_planar = 0;
unsigned int status;
int post_pass1_ystride = info->src_rect.w >> info->downscale_ratio;
int post_pass1_height = info->src_rect.h >> info->downscale_ratio;
/* DST format = SRC format for non-tiled SRC formats
* when fast YUV is enabled. For TILED formats,
* DST format of MDP_Y_CRCB_H2V2_TILE = MDP_Y_CRCB_H2V2
* DST format of MDP_Y_CBCR_H2V2_TILE = MDP_Y_CBCR_H2V2
*/
switch (info->src.format) {
case MDP_Y_CRCB_H2V2_TILE:
is_tile = 1;
dst_format = MDP_Y_CRCB_H2V2;
pass1_dst_format = MDP_Y_CRCB_H2V2;
pass2_src_format = pass1_dst_format;
break;
case MDP_Y_CR_CB_H2V2:
case MDP_Y_CR_CB_GH2V2:
case MDP_Y_CB_CR_H2V2:
post_pass1_buf_is_planar = 1;
case MDP_Y_CRCB_H2V2:
case MDP_Y_CBCR_H2V2:
dst_format = info->src.format;
pass1_dst_format = info->src.format;
pass2_src_format = pass1_dst_format;
break;
case MDP_Y_CBCR_H2V2_TILE:
is_tile = 1;
dst_format = MDP_Y_CBCR_H2V2;
pass1_dst_format = info->src.format;
pass2_src_format = pass1_dst_format;
break;
default:
return -EINVAL;
}
if (info->dst.format != dst_format)
return -EINVAL;
/* Beginning of Pass-1 */
/* rotator expects YCbCr for planar input format */
if ((info->src.format == MDP_Y_CR_CB_H2V2 ||
info->src.format == MDP_Y_CR_CB_GH2V2) &&
rotator_hw_revision < ROTATOR_REVISION_V2)
swap(in_chroma_paddr, in_chroma2_paddr);
iowrite32(in_paddr, MSM_ROTATOR_SRCP0_ADDR);
iowrite32(in_chroma_paddr, MSM_ROTATOR_SRCP1_ADDR);
iowrite32(in_chroma2_paddr, MSM_ROTATOR_SRCP2_ADDR);
if (new_session) {
if (in_chroma2_paddr) {
if (info->src.format == MDP_Y_CR_CB_GH2V2) {
iowrite32(ALIGN(info->src.width, 16) |
ALIGN((info->src.width / 2), 16) << 16,
MSM_ROTATOR_SRC_YSTRIDE1);
iowrite32(ALIGN((info->src.width / 2), 16),
MSM_ROTATOR_SRC_YSTRIDE2);
} else {
iowrite32(info->src.width |
(info->src.width / 2) << 16,
MSM_ROTATOR_SRC_YSTRIDE1);
iowrite32((info->src.width / 2),
MSM_ROTATOR_SRC_YSTRIDE2);
}
} else {
iowrite32(info->src.width |
info->src.width << 16,
MSM_ROTATOR_SRC_YSTRIDE1);
}
}
pr_debug("src_rect.w=%i src_rect.h=%i src_rect.x=%i src_rect.y=%i",
info->src_rect.w, info->src_rect.h, info->src_rect.x,
info->src_rect.y);
pr_debug("src.width=%i src.height=%i src_format=%i",
info->src.width, info->src.height, info->src.format);
pr_debug("dst_width=%i dst_height=%i dst.x=%i dst.y=%i",
info->dst.width, info->dst.height, info->dst_x, info->dst_y);
pr_debug("post_pass1_ystride=%i post_pass1_height=%i downscale=%i",
post_pass1_ystride, post_pass1_height, info->downscale_ratio);
rotator_allocate_2pass_buf(mrd->y_rot_buf, session_index);
rotator_allocate_2pass_buf(mrd->chroma_rot_buf, session_index);
if (post_pass1_buf_is_planar)
rotator_allocate_2pass_buf(mrd->chroma2_rot_buf, session_index);
iowrite32(mrd->y_rot_buf->write_addr, MSM_ROTATOR_OUTP0_ADDR);
iowrite32(mrd->chroma_rot_buf->write_addr, MSM_ROTATOR_OUTP1_ADDR);
if (post_pass1_buf_is_planar)
iowrite32(mrd->chroma2_rot_buf->write_addr,
MSM_ROTATOR_OUTP2_ADDR);
if (post_pass1_buf_is_planar) {
if (pass1_dst_format == MDP_Y_CR_CB_GH2V2) {
iowrite32(ALIGN(post_pass1_ystride, 16) |
ALIGN((post_pass1_ystride / 2), 16) << 16,
MSM_ROTATOR_OUT_YSTRIDE1);
iowrite32(ALIGN((post_pass1_ystride / 2), 16),
MSM_ROTATOR_OUT_YSTRIDE2);
} else {
iowrite32(post_pass1_ystride |
post_pass1_ystride / 2 << 16,
MSM_ROTATOR_OUT_YSTRIDE1);
iowrite32(post_pass1_ystride / 2,
MSM_ROTATOR_OUT_YSTRIDE2);
}
} else {
iowrite32(post_pass1_ystride |
post_pass1_ystride << 16,
MSM_ROTATOR_OUT_YSTRIDE1);
}
if (pass1_dst_format == MDP_Y_CBCR_H2V2 ||
pass1_dst_format == MDP_Y_CB_CR_H2V2) {
iowrite32(GET_PACK_PATTERN(0, 0, CLR_CB, CLR_CR, 8),
MSM_ROTATOR_SRC_UNPACK_PATTERN1);
iowrite32(GET_PACK_PATTERN(0, 0, CLR_CB, CLR_CR, 8),
MSM_ROTATOR_OUT_PACK_PATTERN1);
} else {
iowrite32(GET_PACK_PATTERN(0, 0, CLR_CR, CLR_CB, 8),
MSM_ROTATOR_SRC_UNPACK_PATTERN1);
iowrite32(GET_PACK_PATTERN(0, 0, CLR_CR, CLR_CB, 8),
MSM_ROTATOR_OUT_PACK_PATTERN1);
}
iowrite32((3 << 18) | /* chroma sampling 3=4:2:0 */
0 << 9 | /* Pass-1 No Rotation */
1 << 8 | /* ROT_EN */
fast_yuv_en << 4 | /*fast YUV*/
info->downscale_ratio << 2 | /* downscale v ratio */
info->downscale_ratio, /* downscale h ratio */
MSM_ROTATOR_SUB_BLOCK_CFG);
iowrite32((is_tile ? 2 : 0) << 29 | /* frame format */
(use_imem ? 0 : 1) << 22 | /* tile size */
(in_chroma2_paddr ? 1 : 2) << 19 | /* fetch planes */
0 << 18 | /* unpack align */
1 << 17 | /* unpack tight */
1 << 13 | /* unpack count 0=1 component */
0 << 9 | /* src Bpp 0=1 byte ... */
0 << 8 | /* has alpha */
0 << 6 | /* alpha bits 3=8bits */
3 << 4 | /* R/Cr bits 1=5 2=6 3=8 */
3 << 2 | /* B/Cb bits 1=5 2=6 3=8 */
3 << 0, /* G/Y bits 1=5 2=6 3=8 */
MSM_ROTATOR_SRC_FORMAT);
iowrite32(3, MSM_ROTATOR_INTR_ENABLE);
msm_rotator_dev->processing = 1;
iowrite32(0x1, MSM_ROTATOR_START);
/* End of Pass-1 */
wait_event(msm_rotator_dev->wq,
(msm_rotator_dev->processing == 0));
/* Beginning of Pass-2 */
status = (unsigned char)ioread32(MSM_ROTATOR_INTR_STATUS);
if ((status & 0x03) != 0x01) {
pr_err("%s(): AXI Bus Error, issuing SW_RESET\n",
__func__);
iowrite32(0x1, MSM_ROTATOR_SW_RESET);
}
iowrite32(0, MSM_ROTATOR_INTR_ENABLE);
iowrite32(3, MSM_ROTATOR_INTR_CLEAR);
if (use_imem)
iowrite32(0x42, MSM_ROTATOR_MAX_BURST_SIZE);
iowrite32(((post_pass1_height & 0x1fff)
<< 16) |
(post_pass1_ystride & 0x1fff),
MSM_ROTATOR_SRC_SIZE);
iowrite32(0 << 16 | 0,
MSM_ROTATOR_SRC_XY);
iowrite32(((post_pass1_height & 0x1fff)
<< 16) |
(post_pass1_ystride & 0x1fff),
MSM_ROTATOR_SRC_IMAGE_SIZE);
/* rotator expects YCbCr for planar input format */
if ((pass2_src_format == MDP_Y_CR_CB_H2V2 ||
pass2_src_format == MDP_Y_CR_CB_GH2V2) &&
rotator_hw_revision < ROTATOR_REVISION_V2)
swap(mrd->chroma_rot_buf->read_addr,
mrd->chroma2_rot_buf->read_addr);
iowrite32(mrd->y_rot_buf->read_addr, MSM_ROTATOR_SRCP0_ADDR);
iowrite32(mrd->chroma_rot_buf->read_addr,
MSM_ROTATOR_SRCP1_ADDR);
if (mrd->chroma2_rot_buf->read_addr)
iowrite32(mrd->chroma2_rot_buf->read_addr,
MSM_ROTATOR_SRCP2_ADDR);
if (post_pass1_buf_is_planar) {
if (pass2_src_format == MDP_Y_CR_CB_GH2V2) {
iowrite32(ALIGN(post_pass1_ystride, 16) |
ALIGN((post_pass1_ystride / 2), 16) << 16,
MSM_ROTATOR_SRC_YSTRIDE1);
iowrite32(ALIGN((post_pass1_ystride / 2), 16),
MSM_ROTATOR_SRC_YSTRIDE2);
} else {
iowrite32(post_pass1_ystride |
(post_pass1_ystride / 2) << 16,
MSM_ROTATOR_SRC_YSTRIDE1);
iowrite32((post_pass1_ystride / 2),
MSM_ROTATOR_SRC_YSTRIDE2);
}
} else {
iowrite32(post_pass1_ystride |
post_pass1_ystride << 16,
MSM_ROTATOR_SRC_YSTRIDE1);
}
iowrite32(out_paddr +
((info->dst_y * info->dst.width) + info->dst_x),
MSM_ROTATOR_OUTP0_ADDR);
iowrite32(out_chroma_paddr +
(((info->dst_y * info->dst.width)/2) + info->dst_x),
MSM_ROTATOR_OUTP1_ADDR);
if (out_chroma2_paddr)
iowrite32(out_chroma2_paddr +
(((info->dst_y * info->dst.width)/2) + info->dst_x),
MSM_ROTATOR_OUTP2_ADDR);
if (new_session) {
if (out_chroma2_paddr) {
if (info->dst.format == MDP_Y_CR_CB_GH2V2) {
iowrite32(ALIGN(info->dst.width, 16) |
ALIGN((info->dst.width / 2), 16) << 16,
MSM_ROTATOR_OUT_YSTRIDE1);
iowrite32(ALIGN((info->dst.width / 2), 16),
MSM_ROTATOR_OUT_YSTRIDE2);
} else {
iowrite32(info->dst.width |
info->dst.width/2 << 16,
MSM_ROTATOR_OUT_YSTRIDE1);
iowrite32(info->dst.width/2,
MSM_ROTATOR_OUT_YSTRIDE2);
}
} else {
iowrite32(info->dst.width |
info->dst.width << 16,
MSM_ROTATOR_OUT_YSTRIDE1);
}
if (dst_format == MDP_Y_CBCR_H2V2 ||
dst_format == MDP_Y_CB_CR_H2V2) {
iowrite32(GET_PACK_PATTERN(0, 0, CLR_CB, CLR_CR, 8),
MSM_ROTATOR_SRC_UNPACK_PATTERN1);
iowrite32(GET_PACK_PATTERN(0, 0, CLR_CB, CLR_CR, 8),
MSM_ROTATOR_OUT_PACK_PATTERN1);
} else {
iowrite32(GET_PACK_PATTERN(0, 0, CLR_CR, CLR_CB, 8),
MSM_ROTATOR_SRC_UNPACK_PATTERN1);
iowrite32(GET_PACK_PATTERN(0, 0, CLR_CR, CLR_CB, 8),
MSM_ROTATOR_OUT_PACK_PATTERN1);
}
iowrite32((3 << 18) | /* chroma sampling 3=4:2:0 */
(ROTATIONS_TO_BITMASK(info->rotations) << 9) |
1 << 8 | /* ROT_EN */
fast_yuv_en << 4 | /*fast YUV*/
0 << 2 | /* No downscale in Pass-2 */
0, /* No downscale in Pass-2 */
MSM_ROTATOR_SUB_BLOCK_CFG);
iowrite32(0 << 29 |
/* Output of Pass-1 will always be non-tiled */
(use_imem ? 0 : 1) << 22 | /* tile size */
(in_chroma2_paddr ? 1 : 2) << 19 | /* fetch planes */
0 << 18 | /* unpack align */
1 << 17 | /* unpack tight */
1 << 13 | /* unpack count 0=1 component */
0 << 9 | /* src Bpp 0=1 byte ... */
0 << 8 | /* has alpha */
0 << 6 | /* alpha bits 3=8bits */
3 << 4 | /* R/Cr bits 1=5 2=6 3=8 */
3 << 2 | /* B/Cb bits 1=5 2=6 3=8 */
3 << 0, /* G/Y bits 1=5 2=6 3=8 */
MSM_ROTATOR_SRC_FORMAT);
}
return 0;
}
static int msm_rotator_ycrycb(struct msm_rotator_img_info *info,
unsigned int in_paddr,
unsigned int out_paddr,
unsigned int use_imem,
int new_session,
unsigned int out_chroma_paddr)
{
int bpp;
uint32_t dst_format;
if (info->src.format == MDP_YCRYCB_H2V1) {
if (info->rotations & MDP_ROT_90)
dst_format = MDP_Y_CRCB_H1V2;
else
dst_format = MDP_Y_CRCB_H2V1;
} else
return -EINVAL;
if (info->dst.format != dst_format)
return -EINVAL;
bpp = get_bpp(info->src.format);
if (bpp < 0)
return -ENOTTY;
iowrite32(in_paddr, MSM_ROTATOR_SRCP0_ADDR);
iowrite32(out_paddr +
((info->dst_y * info->dst.width) + info->dst_x),
MSM_ROTATOR_OUTP0_ADDR);
iowrite32(out_chroma_paddr +
((info->dst_y * info->dst.width)/2 + info->dst_x),
MSM_ROTATOR_OUTP1_ADDR);
if (new_session) {
iowrite32(info->src.width * bpp,
MSM_ROTATOR_SRC_YSTRIDE1);
if (info->rotations & MDP_ROT_90)
iowrite32(info->dst.width |
(info->dst.width*2) << 16,
MSM_ROTATOR_OUT_YSTRIDE1);
else
iowrite32(info->dst.width |
(info->dst.width) << 16,
MSM_ROTATOR_OUT_YSTRIDE1);
iowrite32(GET_PACK_PATTERN(CLR_Y, CLR_CR, CLR_Y, CLR_CB, 8),
MSM_ROTATOR_SRC_UNPACK_PATTERN1);
iowrite32(GET_PACK_PATTERN(0, 0, CLR_CR, CLR_CB, 8),
MSM_ROTATOR_OUT_PACK_PATTERN1);
iowrite32((1 << 18) | /* chroma sampling 1=H2V1 */
(ROTATIONS_TO_BITMASK(info->rotations) << 9) |
1 << 8 | /* ROT_EN */
info->downscale_ratio << 2 | /* downscale v ratio */
info->downscale_ratio, /* downscale h ratio */
MSM_ROTATOR_SUB_BLOCK_CFG);
iowrite32(0 << 29 | /* frame format 0 = linear */
(use_imem ? 0 : 1) << 22 | /* tile size */
0 << 19 | /* fetch planes 0=interleaved */
0 << 18 | /* unpack align */
1 << 17 | /* unpack tight */
3 << 13 | /* unpack count 0=1 component */
(bpp-1) << 9 | /* src Bpp 0=1 byte ... */
0 << 8 | /* has alpha */
0 << 6 | /* alpha bits 3=8bits */
3 << 4 | /* R/Cr bits 1=5 2=6 3=8 */
3 << 2 | /* B/Cb bits 1=5 2=6 3=8 */
3 << 0, /* G/Y bits 1=5 2=6 3=8 */
MSM_ROTATOR_SRC_FORMAT);
}
return 0;
}
static int msm_rotator_rgb_types(struct msm_rotator_img_info *info,
unsigned int in_paddr,
unsigned int out_paddr,
unsigned int use_imem,
int new_session)
{
int bpp, abits, rbits, gbits, bbits;
if (info->src.format != info->dst.format)
return -EINVAL;
bpp = get_bpp(info->src.format);
if (bpp < 0)
return -ENOTTY;
iowrite32(in_paddr, MSM_ROTATOR_SRCP0_ADDR);
iowrite32(out_paddr +
((info->dst_y * info->dst.width) + info->dst_x) * bpp,
MSM_ROTATOR_OUTP0_ADDR);
if (new_session) {
iowrite32(info->src.width * bpp, MSM_ROTATOR_SRC_YSTRIDE1);
iowrite32(info->dst.width * bpp, MSM_ROTATOR_OUT_YSTRIDE1);
iowrite32((0 << 18) | /* chroma sampling 0=rgb */
(ROTATIONS_TO_BITMASK(info->rotations) << 9) |
1 << 8 | /* ROT_EN */
info->downscale_ratio << 2 | /* downscale v ratio */
info->downscale_ratio, /* downscale h ratio */
MSM_ROTATOR_SUB_BLOCK_CFG);
switch (info->src.format) {
case MDP_RGB_565:
iowrite32(GET_PACK_PATTERN(0, CLR_R, CLR_G, CLR_B, 8),
MSM_ROTATOR_SRC_UNPACK_PATTERN1);
iowrite32(GET_PACK_PATTERN(0, CLR_R, CLR_G, CLR_B, 8),
MSM_ROTATOR_OUT_PACK_PATTERN1);
abits = 0;
rbits = COMPONENT_5BITS;
gbits = COMPONENT_6BITS;
bbits = COMPONENT_5BITS;
break;
case MDP_BGR_565:
iowrite32(GET_PACK_PATTERN(0, CLR_B, CLR_G, CLR_R, 8),
MSM_ROTATOR_SRC_UNPACK_PATTERN1);
iowrite32(GET_PACK_PATTERN(0, CLR_B, CLR_G, CLR_R, 8),
MSM_ROTATOR_OUT_PACK_PATTERN1);
abits = 0;
rbits = COMPONENT_5BITS;
gbits = COMPONENT_6BITS;
bbits = COMPONENT_5BITS;
break;
case MDP_RGB_888:
case MDP_YCBCR_H1V1:
case MDP_YCRCB_H1V1:
iowrite32(GET_PACK_PATTERN(0, CLR_R, CLR_G, CLR_B, 8),
MSM_ROTATOR_SRC_UNPACK_PATTERN1);
iowrite32(GET_PACK_PATTERN(0, CLR_R, CLR_G, CLR_B, 8),
MSM_ROTATOR_OUT_PACK_PATTERN1);
abits = 0;
rbits = COMPONENT_8BITS;
gbits = COMPONENT_8BITS;
bbits = COMPONENT_8BITS;
break;
case MDP_ARGB_8888:
case MDP_RGBA_8888:
case MDP_XRGB_8888:
case MDP_RGBX_8888:
iowrite32(GET_PACK_PATTERN(CLR_ALPHA, CLR_R, CLR_G,
CLR_B, 8),
MSM_ROTATOR_SRC_UNPACK_PATTERN1);
iowrite32(GET_PACK_PATTERN(CLR_ALPHA, CLR_R, CLR_G,
CLR_B, 8),
MSM_ROTATOR_OUT_PACK_PATTERN1);
abits = COMPONENT_8BITS;
rbits = COMPONENT_8BITS;
gbits = COMPONENT_8BITS;
bbits = COMPONENT_8BITS;
break;
case MDP_BGRA_8888:
iowrite32(GET_PACK_PATTERN(CLR_ALPHA, CLR_B, CLR_G,
CLR_R, 8),
MSM_ROTATOR_SRC_UNPACK_PATTERN1);
iowrite32(GET_PACK_PATTERN(CLR_ALPHA, CLR_B, CLR_G,
CLR_R, 8),
MSM_ROTATOR_OUT_PACK_PATTERN1);
abits = COMPONENT_8BITS;
rbits = COMPONENT_8BITS;
gbits = COMPONENT_8BITS;
bbits = COMPONENT_8BITS;
break;
default:
return -EINVAL;
}
iowrite32(0 << 29 | /* frame format 0 = linear */
(use_imem ? 0 : 1) << 22 | /* tile size */
0 << 19 | /* fetch planes 0=interleaved */
0 << 18 | /* unpack align */
1 << 17 | /* unpack tight */
(abits ? 3 : 2) << 13 | /* unpack count 0=1 comp */
(bpp-1) << 9 | /* src Bpp 0=1 byte ... */
(abits ? 1 : 0) << 8 | /* has alpha */
abits << 6 | /* alpha bits 3=8bits */
rbits << 4 | /* R/Cr bits 1=5 2=6 3=8 */
bbits << 2 | /* B/Cb bits 1=5 2=6 3=8 */
gbits << 0, /* G/Y bits 1=5 2=6 3=8 */
MSM_ROTATOR_SRC_FORMAT);
}
return 0;
}
static int get_img(struct msmfb_data *fbd, int domain,
unsigned long *start, unsigned long *len, struct file **p_file,
int *p_need, struct ion_handle **p_ihdl, unsigned int secure)
{
int ret = 0;
#ifdef CONFIG_FB
struct file *file = NULL;
int put_needed, fb_num;
#endif
#ifdef CONFIG_ANDROID_PMEM
unsigned long vstart;
#endif
*p_need = 0;
#ifdef CONFIG_FB
if (fbd->flags & MDP_MEMORY_ID_TYPE_FB) {
file = fget_light(fbd->memory_id, &put_needed);
if (file == NULL) {
pr_err("fget_light returned NULL\n");
return -EINVAL;
}
if (MAJOR(file->f_dentry->d_inode->i_rdev) == FB_MAJOR) {
fb_num = MINOR(file->f_dentry->d_inode->i_rdev);
if (get_fb_phys_info(start, len, fb_num,
ROTATOR_SUBSYSTEM_ID)) {
pr_err("get_fb_phys_info() failed\n");
ret = -1;
} else {
*p_file = file;
*p_need = put_needed;
}
} else {
pr_err("invalid FB_MAJOR failed\n");
ret = -1;
}
if (ret)
fput_light(file, put_needed);
return ret;
}
#endif
#ifdef CONFIG_MSM_MULTIMEDIA_USE_ION
return msm_rotator_iommu_map_buf(fbd->memory_id, domain, start,
len, p_ihdl, secure);
#endif
#ifdef CONFIG_ANDROID_PMEM
if (!get_pmem_file(fbd->memory_id, start, &vstart, len, p_file))
return 0;
else
return -ENOMEM;
#endif
}
static void put_img(struct file *p_file, struct ion_handle *p_ihdl,
int domain, unsigned int secure)
{
#ifdef CONFIG_ANDROID_PMEM
if (p_file != NULL)
put_pmem_file(p_file);
#endif
#ifdef CONFIG_MSM_MULTIMEDIA_USE_ION
if (!IS_ERR_OR_NULL(p_ihdl)) {
pr_debug("%s(): p_ihdl %p\n", __func__, p_ihdl);
if (rot_iommu_split_domain) {
if (!secure)
ion_unmap_iommu(msm_rotator_dev->client,
p_ihdl, domain, GEN_POOL);
} else {
ion_unmap_iommu(msm_rotator_dev->client,
p_ihdl, ROTATOR_SRC_DOMAIN, GEN_POOL);
}
ion_free(msm_rotator_dev->client, p_ihdl);
}
#endif
}
static int msm_rotator_rotate_prepare(
struct msm_rotator_data_info *data_info,
struct msm_rotator_commit_info *commit_info)
{
unsigned int format;
struct msm_rotator_data_info info;
unsigned int in_paddr, out_paddr;
unsigned long src_len, dst_len;
int rc = 0, s;
struct file *srcp0_file = NULL, *dstp0_file = NULL;
struct file *srcp1_file = NULL, *dstp1_file = NULL;
struct ion_handle *srcp0_ihdl = NULL, *dstp0_ihdl = NULL;
struct ion_handle *srcp1_ihdl = NULL, *dstp1_ihdl = NULL;
int ps0_need, p_need;
unsigned int in_chroma_paddr = 0, out_chroma_paddr = 0;
unsigned int in_chroma2_paddr = 0, out_chroma2_paddr = 0;
struct msm_rotator_img_info *img_info;
struct msm_rotator_mem_planes src_planes, dst_planes;
mutex_lock(&msm_rotator_dev->rotator_lock);
info = *data_info;
for (s = 0; s < MAX_SESSIONS; s++)
if ((msm_rotator_dev->rot_session[s] != NULL) &&
(info.session_id ==
(unsigned int)msm_rotator_dev->rot_session[s]
))
break;
if (s == MAX_SESSIONS) {
pr_err("%s() : Attempt to use invalid session_id %d\n",
__func__, s);
rc = -EINVAL;
mutex_unlock(&msm_rotator_dev->rotator_lock);
return rc;
}
img_info = &(msm_rotator_dev->rot_session[s]->img_info);
if (img_info->enable == 0) {
dev_dbg(msm_rotator_dev->device,
"%s() : Session_id %d not enabled\n", __func__, s);
rc = -EINVAL;
mutex_unlock(&msm_rotator_dev->rotator_lock);
return rc;
}
if (msm_rotator_get_plane_sizes(img_info->src.format,
img_info->src.width,
img_info->src.height,
&src_planes)) {
pr_err("%s: invalid src format\n", __func__);
rc = -EINVAL;
mutex_unlock(&msm_rotator_dev->rotator_lock);
return rc;
}
if (msm_rotator_get_plane_sizes(img_info->dst.format,
img_info->dst.width,
img_info->dst.height,
&dst_planes)) {
pr_err("%s: invalid dst format\n", __func__);
rc = -EINVAL;
mutex_unlock(&msm_rotator_dev->rotator_lock);
return rc;
}
rc = get_img(&info.src, ROTATOR_SRC_DOMAIN, (unsigned long *)&in_paddr,
(unsigned long *)&src_len, &srcp0_file, &ps0_need,
&srcp0_ihdl, 0);
if (rc) {
pr_err("%s: in get_img() failed id=0x%08x\n",
DRIVER_NAME, info.src.memory_id);
goto rotate_prepare_error;
}
rc = get_img(&info.dst, ROTATOR_DST_DOMAIN, (unsigned long *)&out_paddr,
(unsigned long *)&dst_len, &dstp0_file, &p_need,
&dstp0_ihdl, img_info->secure);
if (rc) {
pr_err("%s: out get_img() failed id=0x%08x\n",
DRIVER_NAME, info.dst.memory_id);
goto rotate_prepare_error;
}
format = img_info->src.format;
if (((info.version_key & VERSION_KEY_MASK) == 0xA5B4C300) &&
((info.version_key & ~VERSION_KEY_MASK) > 0) &&
(src_planes.num_planes == 2)) {
if (checkoffset(info.src.offset,
src_planes.plane_size[0],
src_len)) {
pr_err("%s: invalid src buffer (len=%lu offset=%x)\n",
__func__, src_len, info.src.offset);
rc = -ERANGE;
goto rotate_prepare_error;
}
if (checkoffset(info.dst.offset,
dst_planes.plane_size[0],
dst_len)) {
pr_err("%s: invalid dst buffer (len=%lu offset=%x)\n",
__func__, dst_len, info.dst.offset);
rc = -ERANGE;
goto rotate_prepare_error;
}
rc = get_img(&info.src_chroma, ROTATOR_SRC_DOMAIN,
(unsigned long *)&in_chroma_paddr,
(unsigned long *)&src_len, &srcp1_file, &p_need,
&srcp1_ihdl, 0);
if (rc) {
pr_err("%s: in chroma get_img() failed id=0x%08x\n",
DRIVER_NAME, info.src_chroma.memory_id);
goto rotate_prepare_error;
}
rc = get_img(&info.dst_chroma, ROTATOR_DST_DOMAIN,
(unsigned long *)&out_chroma_paddr,
(unsigned long *)&dst_len, &dstp1_file, &p_need,
&dstp1_ihdl, img_info->secure);
if (rc) {
pr_err("%s: out chroma get_img() failed id=0x%08x\n",
DRIVER_NAME, info.dst_chroma.memory_id);
goto rotate_prepare_error;
}
if (checkoffset(info.src_chroma.offset,
src_planes.plane_size[1],
src_len)) {
pr_err("%s: invalid chr src buf len=%lu offset=%x\n",
__func__, src_len, info.src_chroma.offset);
rc = -ERANGE;
goto rotate_prepare_error;
}
if (checkoffset(info.dst_chroma.offset,
src_planes.plane_size[1],
dst_len)) {
pr_err("%s: invalid chr dst buf len=%lu offset=%x\n",
__func__, dst_len, info.dst_chroma.offset);
rc = -ERANGE;
goto rotate_prepare_error;
}
in_chroma_paddr += info.src_chroma.offset;
out_chroma_paddr += info.dst_chroma.offset;
} else {
if (checkoffset(info.src.offset,
src_planes.total_size,
src_len)) {
pr_err("%s: invalid src buffer (len=%lu offset=%x)\n",
__func__, src_len, info.src.offset);
rc = -ERANGE;
goto rotate_prepare_error;
}
if (checkoffset(info.dst.offset,
dst_planes.total_size,
dst_len)) {
pr_err("%s: invalid dst buffer (len=%lu offset=%x)\n",
__func__, dst_len, info.dst.offset);
rc = -ERANGE;
goto rotate_prepare_error;
}
}
in_paddr += info.src.offset;
out_paddr += info.dst.offset;
if (!in_chroma_paddr && src_planes.num_planes >= 2)
in_chroma_paddr = in_paddr + src_planes.plane_size[0];
if (!out_chroma_paddr && dst_planes.num_planes >= 2)
out_chroma_paddr = out_paddr + dst_planes.plane_size[0];
if (src_planes.num_planes >= 3)
in_chroma2_paddr = in_chroma_paddr + src_planes.plane_size[1];
if (dst_planes.num_planes >= 3)
out_chroma2_paddr = out_chroma_paddr + dst_planes.plane_size[1];
commit_info->data_info = info;
commit_info->img_info = *img_info;
commit_info->format = format;
commit_info->in_paddr = in_paddr;
commit_info->out_paddr = out_paddr;
commit_info->in_chroma_paddr = in_chroma_paddr;
commit_info->out_chroma_paddr = out_chroma_paddr;
commit_info->in_chroma2_paddr = in_chroma2_paddr;
commit_info->out_chroma2_paddr = out_chroma2_paddr;
commit_info->srcp0_file = srcp0_file;
commit_info->srcp1_file = srcp1_file;
commit_info->srcp0_ihdl = srcp0_ihdl;
commit_info->srcp1_ihdl = srcp1_ihdl;
commit_info->dstp0_file = dstp0_file;
commit_info->dstp0_ihdl = dstp0_ihdl;
commit_info->dstp1_file = dstp1_file;
commit_info->dstp1_ihdl = dstp1_ihdl;
commit_info->ps0_need = ps0_need;
commit_info->session_index = s;
commit_info->acq_fen = msm_rotator_dev->sync_info[s].acq_fen;
commit_info->fast_yuv_en = mrd->rot_session[s]->fast_yuv_enable;
commit_info->enable_2pass = mrd->rot_session[s]->enable_2pass;
mutex_unlock(&msm_rotator_dev->rotator_lock);
return 0;
rotate_prepare_error:
put_img(dstp1_file, dstp1_ihdl, ROTATOR_DST_DOMAIN,
msm_rotator_dev->rot_session[s]->img_info.secure);
put_img(srcp1_file, srcp1_ihdl, ROTATOR_SRC_DOMAIN, 0);
put_img(dstp0_file, dstp0_ihdl, ROTATOR_DST_DOMAIN,
msm_rotator_dev->rot_session[s]->img_info.secure);
/* only source may use frame buffer */
if (info.src.flags & MDP_MEMORY_ID_TYPE_FB)
fput_light(srcp0_file, ps0_need);
else
put_img(srcp0_file, srcp0_ihdl, ROTATOR_SRC_DOMAIN, 0);
dev_dbg(msm_rotator_dev->device, "%s() returning rc = %d\n",
__func__, rc);
mutex_unlock(&msm_rotator_dev->rotator_lock);
return rc;
}
static int msm_rotator_do_rotate_sub(
struct msm_rotator_commit_info *commit_info)
{
unsigned int status, format;
struct msm_rotator_data_info info;
unsigned int in_paddr, out_paddr;
int use_imem = 0, rc = 0;
struct file *srcp0_file, *dstp0_file;
struct file *srcp1_file, *dstp1_file;
struct ion_handle *srcp0_ihdl, *dstp0_ihdl;
struct ion_handle *srcp1_ihdl, *dstp1_ihdl;
int s, ps0_need;
unsigned int in_chroma_paddr, out_chroma_paddr;
unsigned int in_chroma2_paddr, out_chroma2_paddr;
struct msm_rotator_img_info *img_info;
mutex_lock(&msm_rotator_dev->rotator_lock);
info = commit_info->data_info;
img_info = &commit_info->img_info;
format = commit_info->format;
in_paddr = commit_info->in_paddr;
out_paddr = commit_info->out_paddr;
in_chroma_paddr = commit_info->in_chroma_paddr;
out_chroma_paddr = commit_info->out_chroma_paddr;
in_chroma2_paddr = commit_info->in_chroma2_paddr;
out_chroma2_paddr = commit_info->out_chroma2_paddr;
srcp0_file = commit_info->srcp0_file;
srcp1_file = commit_info->srcp1_file;
srcp0_ihdl = commit_info->srcp0_ihdl;
srcp1_ihdl = commit_info->srcp1_ihdl;
dstp0_file = commit_info->dstp0_file;
dstp0_ihdl = commit_info->dstp0_ihdl;
dstp1_file = commit_info->dstp1_file;
dstp1_ihdl = commit_info->dstp1_ihdl;
ps0_need = commit_info->ps0_need;
s = commit_info->session_index;
msm_rotator_wait_for_fence(commit_info->acq_fen);
commit_info->acq_fen = NULL;
cancel_delayed_work_sync(&msm_rotator_dev->rot_clk_work);
if (msm_rotator_dev->rot_clk_state != CLK_EN) {
enable_rot_clks();
msm_rotator_dev->rot_clk_state = CLK_EN;
}
enable_irq(msm_rotator_dev->irq);
#ifdef CONFIG_MSM_ROTATOR_USE_IMEM
use_imem = msm_rotator_imem_allocate(ROTATOR_REQUEST);
#else
use_imem = 0;
#endif
/*
* workaround for a hardware bug. rotator hardware hangs when we
* use write burst beat size 16 on 128X128 tile fetch mode. As a
* temporary fix use 0x42 for BURST_SIZE when imem used.
*/
if (use_imem)
iowrite32(0x42, MSM_ROTATOR_MAX_BURST_SIZE);
iowrite32(((img_info->src_rect.h & 0x1fff)
<< 16) |
(img_info->src_rect.w & 0x1fff),
MSM_ROTATOR_SRC_SIZE);
iowrite32(((img_info->src_rect.y & 0x1fff)
<< 16) |
(img_info->src_rect.x & 0x1fff),
MSM_ROTATOR_SRC_XY);
iowrite32(((img_info->src.height & 0x1fff)
<< 16) |
(img_info->src.width & 0x1fff),
MSM_ROTATOR_SRC_IMAGE_SIZE);
switch (format) {
case MDP_RGB_565:
case MDP_BGR_565:
case MDP_RGB_888:
case MDP_ARGB_8888:
case MDP_RGBA_8888:
case MDP_XRGB_8888:
case MDP_BGRA_8888:
case MDP_RGBX_8888:
case MDP_YCBCR_H1V1:
case MDP_YCRCB_H1V1:
rc = msm_rotator_rgb_types(img_info,
in_paddr, out_paddr,
use_imem,
msm_rotator_dev->last_session_idx
!= s);
break;
case MDP_Y_CBCR_H2V2:
case MDP_Y_CRCB_H2V2:
case MDP_Y_CB_CR_H2V2:
case MDP_Y_CR_CB_H2V2:
case MDP_Y_CR_CB_GH2V2:
case MDP_Y_CRCB_H2V2_TILE:
case MDP_Y_CBCR_H2V2_TILE:
if (!commit_info->enable_2pass)
rc = msm_rotator_ycxcx_h2v2(img_info,
in_paddr, out_paddr, use_imem,
msm_rotator_dev->last_session_idx
!= s,
in_chroma_paddr,
out_chroma_paddr,
in_chroma2_paddr,
out_chroma2_paddr,
commit_info->fast_yuv_en);
else
rc = msm_rotator_ycxcx_h2v2_2pass(img_info,
in_paddr, out_paddr, use_imem,
msm_rotator_dev->last_session_idx
!= s,
in_chroma_paddr,
out_chroma_paddr,
in_chroma2_paddr,
out_chroma2_paddr,
commit_info->fast_yuv_en,
commit_info->enable_2pass,
s);
break;
case MDP_Y_CBCR_H2V1:
case MDP_Y_CRCB_H2V1:
rc = msm_rotator_ycxcx_h2v1(img_info,
in_paddr, out_paddr, use_imem,
msm_rotator_dev->last_session_idx
!= s,
in_chroma_paddr,
out_chroma_paddr);
break;
case MDP_YCRYCB_H2V1:
rc = msm_rotator_ycrycb(img_info,
in_paddr, out_paddr, use_imem,
msm_rotator_dev->last_session_idx != s,
out_chroma_paddr);
break;
default:
rc = -EINVAL;
pr_err("%s(): Unsupported format %u\n", __func__, format);
goto do_rotate_exit;
}
if (rc != 0) {
msm_rotator_dev->last_session_idx = INVALID_SESSION;
pr_err("%s(): Invalid session error\n", __func__);
goto do_rotate_exit;
}
iowrite32(3, MSM_ROTATOR_INTR_ENABLE);
msm_rotator_dev->processing = 1;
iowrite32(0x1, MSM_ROTATOR_START);
wait_event(msm_rotator_dev->wq,
(msm_rotator_dev->processing == 0));
status = (unsigned char)ioread32(MSM_ROTATOR_INTR_STATUS);
if ((status & 0x03) != 0x01) {
pr_err("%s(): AXI Bus Error, issuing SW_RESET\n", __func__);
iowrite32(0x1, MSM_ROTATOR_SW_RESET);
rc = -EFAULT;
}
iowrite32(0, MSM_ROTATOR_INTR_ENABLE);
iowrite32(3, MSM_ROTATOR_INTR_CLEAR);
do_rotate_exit:
disable_irq(msm_rotator_dev->irq);
#ifdef CONFIG_MSM_ROTATOR_USE_IMEM
msm_rotator_imem_free(ROTATOR_REQUEST);
#endif
schedule_delayed_work(&msm_rotator_dev->rot_clk_work, HZ);
put_img(dstp1_file, dstp1_ihdl, ROTATOR_DST_DOMAIN,
img_info->secure);
put_img(srcp1_file, srcp1_ihdl, ROTATOR_SRC_DOMAIN, 0);
put_img(dstp0_file, dstp0_ihdl, ROTATOR_DST_DOMAIN,
img_info->secure);
/* only source may use frame buffer */
if (info.src.flags & MDP_MEMORY_ID_TYPE_FB)
fput_light(srcp0_file, ps0_need);
else
put_img(srcp0_file, srcp0_ihdl, ROTATOR_SRC_DOMAIN, 0);
msm_rotator_signal_timeline_done(s);
mutex_unlock(&msm_rotator_dev->rotator_lock);
dev_dbg(msm_rotator_dev->device, "%s() returning rc = %d\n",
__func__, rc);
return rc;
}
static void rot_wait_for_commit_queue(u32 is_all)
{
int ret = 0;
u32 loop_cnt = 0;
while (1) {
mutex_lock(&mrd->commit_mutex);
if (is_all && (atomic_read(&mrd->commit_q_cnt) == 0))
break;
if ((!is_all) &&
(atomic_read(&mrd->commit_q_cnt) < MAX_COMMIT_QUEUE))
break;
INIT_COMPLETION(mrd->commit_comp);
mutex_unlock(&mrd->commit_mutex);
ret = wait_for_completion_interruptible_timeout(
&mrd->commit_comp,
msecs_to_jiffies(WAIT_ROT_TIMEOUT));
if ((ret <= 0) ||
(atomic_read(&mrd->commit_q_cnt) >= MAX_COMMIT_QUEUE) ||
(loop_cnt > MAX_COMMIT_QUEUE)) {
pr_err("%s wait for commit queue failed ret=%d pointers:%d %d",
__func__, ret, atomic_read(&mrd->commit_q_r),
atomic_read(&mrd->commit_q_w));
mutex_lock(&mrd->commit_mutex);
ret = -ETIME;
break;
} else {
ret = 0;
}
loop_cnt++;
};
if (is_all || ret) {
atomic_set(&mrd->commit_q_r, 0);
atomic_set(&mrd->commit_q_cnt, 0);
atomic_set(&mrd->commit_q_w, 0);
}
mutex_unlock(&mrd->commit_mutex);
}
static int msm_rotator_do_rotate(unsigned long arg)
{
struct msm_rotator_data_info info;
struct rot_sync_info *sync_info;
int session_index, ret;
int commit_q_w;
if (copy_from_user(&info, (void __user *)arg, sizeof(info)))
return -EFAULT;
rot_wait_for_commit_queue(false);
mutex_lock(&mrd->commit_mutex);
commit_q_w = atomic_read(&mrd->commit_q_w);
ret = msm_rotator_rotate_prepare(&info,
&mrd->commit_info[commit_q_w]);
if (ret) {
mutex_unlock(&mrd->commit_mutex);
return ret;
}
session_index = mrd->commit_info[commit_q_w].session_index;
sync_info = &msm_rotator_dev->sync_info[session_index];
mutex_lock(&sync_info->sync_mutex);
atomic_inc(&sync_info->queue_buf_cnt);
sync_info->acq_fen = NULL;
mutex_unlock(&sync_info->sync_mutex);
if (atomic_inc_return(&mrd->commit_q_w) >= MAX_COMMIT_QUEUE)
atomic_set(&mrd->commit_q_w, 0);
atomic_inc(&mrd->commit_q_cnt);
schedule_work(&mrd->commit_work);
mutex_unlock(&mrd->commit_mutex);
if (info.wait_for_finish)
rot_wait_for_commit_queue(true);
return 0;
}
static void rot_commit_wq_handler(struct work_struct *work)
{
mutex_lock(&mrd->commit_wq_mutex);
mutex_lock(&mrd->commit_mutex);
while (atomic_read(&mrd->commit_q_cnt) > 0) {
mrd->commit_running = true;
mutex_unlock(&mrd->commit_mutex);
msm_rotator_do_rotate_sub(
&mrd->commit_info[atomic_read(&mrd->commit_q_r)]);
mutex_lock(&mrd->commit_mutex);
if (atomic_read(&mrd->commit_q_cnt) > 0) {
atomic_dec(&mrd->commit_q_cnt);
if (atomic_inc_return(&mrd->commit_q_r) >=
MAX_COMMIT_QUEUE)
atomic_set(&mrd->commit_q_r, 0);
}
complete_all(&mrd->commit_comp);
}
mrd->commit_running = false;
if (atomic_read(&mrd->commit_q_r) != atomic_read(&mrd->commit_q_w))
pr_err("%s invalid state: r=%d w=%d cnt=%d", __func__,
atomic_read(&mrd->commit_q_r),
atomic_read(&mrd->commit_q_w),
atomic_read(&mrd->commit_q_cnt));
mutex_unlock(&mrd->commit_mutex);
mutex_unlock(&mrd->commit_wq_mutex);
}
static void msm_rotator_set_perf_level(u32 wh, u32 is_rgb)
{
u32 perf_level;
if (is_rgb)
perf_level = 1;
else if (wh <= (640 * 480))
perf_level = 2;
else if (wh <= (736 * 1280))
perf_level = 3;
else
perf_level = 4;
#ifdef CONFIG_MSM_BUS_SCALING
msm_bus_scale_client_update_request(msm_rotator_dev->bus_client_handle,
perf_level);
#endif
}
static int rot_enable_iommu_clocks(struct msm_rotator_dev *rot_dev)
{
int ret = 0, i;
if (rot_dev->mmu_clk_on)
return 0;
for (i = 0; i < ARRAY_SIZE(rot_mmu_clks); i++) {
rot_mmu_clks[i].mmu_clk = clk_get(&msm_rotator_dev->pdev->dev,
rot_mmu_clks[i].mmu_clk_name);
if (IS_ERR(rot_mmu_clks[i].mmu_clk)) {
pr_err(" %s: Get failed for clk %s", __func__,
rot_mmu_clks[i].mmu_clk_name);
ret = PTR_ERR(rot_mmu_clks[i].mmu_clk);
break;
}
ret = clk_prepare_enable(rot_mmu_clks[i].mmu_clk);
if (ret) {
clk_put(rot_mmu_clks[i].mmu_clk);
rot_mmu_clks[i].mmu_clk = NULL;
}
}
if (ret) {
for (i--; i >= 0; i--) {
clk_disable_unprepare(rot_mmu_clks[i].mmu_clk);
clk_put(rot_mmu_clks[i].mmu_clk);
rot_mmu_clks[i].mmu_clk = NULL;
}
} else {
rot_dev->mmu_clk_on = 1;
}
return ret;
}
static int rot_disable_iommu_clocks(struct msm_rotator_dev *rot_dev)
{
int i;
if (!rot_dev->mmu_clk_on)
return 0;
for (i = 0; i < ARRAY_SIZE(rot_mmu_clks); i++) {
clk_disable_unprepare(rot_mmu_clks[i].mmu_clk);
clk_put(rot_mmu_clks[i].mmu_clk);
rot_mmu_clks[i].mmu_clk = NULL;
}
rot_dev->mmu_clk_on = 0;
return 0;
}
static int map_sec_resource(struct msm_rotator_dev *rot_dev)
{
int ret = 0;
if (rot_dev->sec_mapped)
return 0;
ret = rot_enable_iommu_clocks(rot_dev);
if (ret) {
pr_err("IOMMU clock enabled failed while open");
return ret;
}
ret = msm_ion_secure_heap(ION_HEAP(ION_CP_MM_HEAP_ID));
if (ret)
pr_err("ION heap secure failed heap id %d ret %d\n",
ION_CP_MM_HEAP_ID, ret);
else
rot_dev->sec_mapped = 1;
rot_disable_iommu_clocks(rot_dev);
return ret;
}
static int unmap_sec_resource(struct msm_rotator_dev *rot_dev)
{
int ret = 0;
ret = rot_enable_iommu_clocks(rot_dev);
if (ret) {
pr_err("IOMMU clock enabled failed while close\n");
return ret;
}
msm_ion_unsecure_heap(ION_HEAP(ION_CP_MM_HEAP_ID));
rot_dev->sec_mapped = 0;
rot_disable_iommu_clocks(rot_dev);
return ret;
}
static int msm_rotator_start(unsigned long arg,
struct msm_rotator_fd_info *fd_info)
{
struct msm_rotator_img_info info;
struct msm_rotator_session *rot_session = NULL;
int rc = 0;
int s, is_rgb = 0;
int first_free_idx = INVALID_SESSION;
unsigned int dst_w, dst_h;
unsigned int is_planar420 = 0;
int fast_yuv_en = 0, enable_2pass = 0;
struct rot_sync_info *sync_info;
if (copy_from_user(&info, (void __user *)arg, sizeof(info)))
return -EFAULT;
if ((info.rotations > MSM_ROTATOR_MAX_ROT) ||
(info.src.height > MSM_ROTATOR_MAX_H) ||
(info.src.width > MSM_ROTATOR_MAX_W) ||
(info.dst.height > MSM_ROTATOR_MAX_H) ||
(info.dst.width > MSM_ROTATOR_MAX_W) ||
(info.downscale_ratio > MAX_DOWNSCALE_RATIO)) {
pr_err("%s: Invalid parameters\n", __func__);
return -EINVAL;
}
if (info.rotations & MDP_ROT_90) {
dst_w = info.src_rect.h >> info.downscale_ratio;
dst_h = info.src_rect.w >> info.downscale_ratio;
} else {
dst_w = info.src_rect.w >> info.downscale_ratio;
dst_h = info.src_rect.h >> info.downscale_ratio;
}
if (checkoffset(info.src_rect.x, info.src_rect.w, info.src.width) ||
checkoffset(info.src_rect.y, info.src_rect.h, info.src.height) ||
checkoffset(info.dst_x, dst_w, info.dst.width) ||
checkoffset(info.dst_y, dst_h, info.dst.height)) {
pr_err("%s: Invalid src or dst rect\n", __func__);
return -ERANGE;
}
switch (info.src.format) {
case MDP_Y_CB_CR_H2V2:
case MDP_Y_CR_CB_H2V2:
case MDP_Y_CR_CB_GH2V2:
is_planar420 = 1;
case MDP_Y_CBCR_H2V2:
case MDP_Y_CRCB_H2V2:
case MDP_Y_CRCB_H2V2_TILE:
case MDP_Y_CBCR_H2V2_TILE:
if (rotator_hw_revision >= ROTATOR_REVISION_V2) {
if (info.downscale_ratio &&
(info.rotations & MDP_ROT_90)) {
fast_yuv_en = !fast_yuv_invalid_size_checker(
0,
info.src.width,
info.src_rect.w >>
info.downscale_ratio,
info.src.height,
info.src_rect.h >>
info.downscale_ratio,
info.src_rect.w >>
info.downscale_ratio,
is_planar420);
fast_yuv_en = fast_yuv_en &&
!fast_yuv_invalid_size_checker(
info.rotations,
info.src_rect.w >>
info.downscale_ratio,
dst_w,
info.src_rect.h >>
info.downscale_ratio,
dst_h,
dst_w,
is_planar420);
} else {
fast_yuv_en = !fast_yuv_invalid_size_checker(
info.rotations,
info.src.width,
dst_w,
info.src.height,
dst_h,
dst_w,
is_planar420);
}
if (fast_yuv_en && info.downscale_ratio &&
(info.rotations & MDP_ROT_90))
enable_2pass = 1;
}
break;
default:
fast_yuv_en = 0;
}
switch (info.src.format) {
case MDP_RGB_565:
case MDP_BGR_565:
case MDP_RGB_888:
case MDP_ARGB_8888:
case MDP_RGBA_8888:
case MDP_XRGB_8888:
case MDP_RGBX_8888:
case MDP_BGRA_8888:
is_rgb = 1;
info.dst.format = info.src.format;
break;
case MDP_Y_CBCR_H2V1:
if (info.rotations & MDP_ROT_90) {
info.dst.format = MDP_Y_CBCR_H1V2;
break;
}
case MDP_Y_CRCB_H2V1:
if (info.rotations & MDP_ROT_90) {
info.dst.format = MDP_Y_CRCB_H1V2;
break;
}
case MDP_Y_CBCR_H2V2:
case MDP_Y_CRCB_H2V2:
case MDP_YCBCR_H1V1:
case MDP_YCRCB_H1V1:
info.dst.format = info.src.format;
break;
case MDP_YCRYCB_H2V1:
if (info.rotations & MDP_ROT_90)
info.dst.format = MDP_Y_CRCB_H1V2;
else
info.dst.format = MDP_Y_CRCB_H2V1;
break;
case MDP_Y_CB_CR_H2V2:
if (fast_yuv_en) {
info.dst.format = info.src.format;
break;
}
case MDP_Y_CBCR_H2V2_TILE:
info.dst.format = MDP_Y_CBCR_H2V2;
break;
case MDP_Y_CR_CB_H2V2:
case MDP_Y_CR_CB_GH2V2:
if (fast_yuv_en) {
info.dst.format = info.src.format;
break;
}
case MDP_Y_CRCB_H2V2_TILE:
info.dst.format = MDP_Y_CRCB_H2V2;
break;
default:
return -EINVAL;
}
mutex_lock(&msm_rotator_dev->rotator_lock);
msm_rotator_set_perf_level((info.src.width*info.src.height), is_rgb);
for (s = 0; s < MAX_SESSIONS; s++) {
if ((msm_rotator_dev->rot_session[s] != NULL) &&
(info.session_id ==
(unsigned int)msm_rotator_dev->rot_session[s]
)) {
rot_session = msm_rotator_dev->rot_session[s];
rot_session->img_info = info;
rot_session->fd_info = *fd_info;
rot_session->fast_yuv_enable = fast_yuv_en;
rot_session->enable_2pass = enable_2pass;
if (msm_rotator_dev->last_session_idx == s)
msm_rotator_dev->last_session_idx =
INVALID_SESSION;
break;
}
if ((msm_rotator_dev->rot_session[s] == NULL) &&
(first_free_idx == INVALID_SESSION))
first_free_idx = s;
}
if ((s == MAX_SESSIONS) && (first_free_idx != INVALID_SESSION)) {
/* allocate a session id */
msm_rotator_dev->rot_session[first_free_idx] =
kzalloc(sizeof(struct msm_rotator_session),
GFP_KERNEL);
if (!msm_rotator_dev->rot_session[first_free_idx]) {
printk(KERN_ERR "%s : unable to alloc mem\n",
__func__);
rc = -ENOMEM;
goto rotator_start_exit;
}
info.session_id = (unsigned int)
msm_rotator_dev->rot_session[first_free_idx];
rot_session = msm_rotator_dev->rot_session[first_free_idx];
rot_session->img_info = info;
rot_session->fd_info = *fd_info;
rot_session->fast_yuv_enable = fast_yuv_en;
rot_session->enable_2pass = enable_2pass;
if (!IS_ERR_OR_NULL(mrd->client)) {
if (rot_session->img_info.secure) {
rot_session->mem_hid &= ~BIT(ION_IOMMU_HEAP_ID);
rot_session->mem_hid |= BIT(ION_CP_MM_HEAP_ID);
rot_session->mem_hid |= ION_SECURE;
} else {
rot_session->mem_hid &= ~BIT(ION_CP_MM_HEAP_ID);
rot_session->mem_hid &= ~ION_SECURE;
rot_session->mem_hid |= BIT(ION_IOMMU_HEAP_ID);
}
}
s = first_free_idx;
} else if (s == MAX_SESSIONS) {
dev_dbg(msm_rotator_dev->device, "%s: all sessions in use\n",
__func__);
rc = -EBUSY;
}
if (rc == 0 && copy_to_user((void __user *)arg, &info, sizeof(info)))
rc = -EFAULT;
if ((rc == 0) && (info.secure))
map_sec_resource(msm_rotator_dev);
sync_info = &msm_rotator_dev->sync_info[s];
if ((rc == 0) && (sync_info->initialized == false)) {
char timeline_name[MAX_TIMELINE_NAME_LEN];
if (sync_info->timeline == NULL) {
snprintf(timeline_name, sizeof(timeline_name),
"msm_rot_%d", first_free_idx);
sync_info->timeline =
sw_sync_timeline_create(timeline_name);
if (sync_info->timeline == NULL)
pr_err("%s: cannot create %s time line",
__func__, timeline_name);
sync_info->timeline_value = 0;
}
mutex_init(&sync_info->sync_mutex);
sync_info->initialized = true;
}
sync_info->acq_fen = NULL;
atomic_set(&sync_info->queue_buf_cnt, 0);
rotator_start_exit:
mutex_unlock(&msm_rotator_dev->rotator_lock);
return rc;
}
static int msm_rotator_finish(unsigned long arg)
{
int rc = 0;
int s;
unsigned int session_id;
if (copy_from_user(&session_id, (void __user *)arg, sizeof(s)))
return -EFAULT;
rot_wait_for_commit_queue(true);
mutex_lock(&msm_rotator_dev->rotator_lock);
for (s = 0; s < MAX_SESSIONS; s++) {
if ((msm_rotator_dev->rot_session[s] != NULL) &&
(session_id ==
(unsigned int)msm_rotator_dev->rot_session[s])) {
if (msm_rotator_dev->last_session_idx == s)
msm_rotator_dev->last_session_idx =
INVALID_SESSION;
msm_rotator_signal_timeline(s);
msm_rotator_release_acq_fence(s);
if (msm_rotator_dev->rot_session[s]->enable_2pass) {
rotator_free_2pass_buf(mrd->y_rot_buf, s);
rotator_free_2pass_buf(mrd->chroma_rot_buf, s);
rotator_free_2pass_buf(mrd->chroma2_rot_buf, s);
}
kfree(msm_rotator_dev->rot_session[s]);
msm_rotator_dev->rot_session[s] = NULL;
break;
}
}
if (s == MAX_SESSIONS)
rc = -EINVAL;
#ifdef CONFIG_MSM_BUS_SCALING
msm_bus_scale_client_update_request(msm_rotator_dev->bus_client_handle,
0);
#endif
if (msm_rotator_dev->sec_mapped)
unmap_sec_resource(msm_rotator_dev);
mutex_unlock(&msm_rotator_dev->rotator_lock);
return rc;
}
static int
msm_rotator_open(struct inode *inode, struct file *filp)
{
struct msm_rotator_fd_info *tmp, *fd_info = NULL;
int i;
if (filp->private_data)
return -EBUSY;
mutex_lock(&msm_rotator_dev->rotator_lock);
for (i = 0; i < MAX_SESSIONS; i++) {
if (msm_rotator_dev->rot_session[i] == NULL)
break;
}
if (i == MAX_SESSIONS) {
mutex_unlock(&msm_rotator_dev->rotator_lock);
return -EBUSY;
}
list_for_each_entry(tmp, &msm_rotator_dev->fd_list, list) {
if (tmp->pid == current->pid) {
fd_info = tmp;
break;
}
}
if (!fd_info) {
fd_info = kzalloc(sizeof(*fd_info), GFP_KERNEL);
if (!fd_info) {
mutex_unlock(&msm_rotator_dev->rotator_lock);
pr_err("%s: insufficient memory to alloc resources\n",
__func__);
return -ENOMEM;
}
list_add(&fd_info->list, &msm_rotator_dev->fd_list);
fd_info->pid = current->pid;
}
fd_info->ref_cnt++;
mutex_unlock(&msm_rotator_dev->rotator_lock);
filp->private_data = fd_info;
return 0;
}
static int
msm_rotator_close(struct inode *inode, struct file *filp)
{
struct msm_rotator_fd_info *fd_info;
int s;
fd_info = (struct msm_rotator_fd_info *)filp->private_data;
mutex_lock(&msm_rotator_dev->rotator_lock);
if (--fd_info->ref_cnt > 0) {
mutex_unlock(&msm_rotator_dev->rotator_lock);
return 0;
}
for (s = 0; s < MAX_SESSIONS; s++) {
if (msm_rotator_dev->rot_session[s] != NULL &&
&(msm_rotator_dev->rot_session[s]->fd_info) == fd_info) {
pr_debug("%s: freeing rotator session %p (pid %d)\n",
__func__, msm_rotator_dev->rot_session[s],
fd_info->pid);
rot_wait_for_commit_queue(true);
msm_rotator_signal_timeline(s);
kfree(msm_rotator_dev->rot_session[s]);
msm_rotator_dev->rot_session[s] = NULL;
if (msm_rotator_dev->last_session_idx == s)
msm_rotator_dev->last_session_idx =
INVALID_SESSION;
}
}
list_del(&fd_info->list);
kfree(fd_info);
mutex_unlock(&msm_rotator_dev->rotator_lock);
return 0;
}
static long msm_rotator_ioctl(struct file *file, unsigned cmd,
unsigned long arg)
{
struct msm_rotator_fd_info *fd_info;
if (_IOC_TYPE(cmd) != MSM_ROTATOR_IOCTL_MAGIC)
return -ENOTTY;
fd_info = (struct msm_rotator_fd_info *)file->private_data;
switch (cmd) {
case MSM_ROTATOR_IOCTL_START:
return msm_rotator_start(arg, fd_info);
case MSM_ROTATOR_IOCTL_ROTATE:
return msm_rotator_do_rotate(arg);
case MSM_ROTATOR_IOCTL_FINISH:
return msm_rotator_finish(arg);
case MSM_ROTATOR_IOCTL_BUFFER_SYNC:
return msm_rotator_buf_sync(arg);
default:
dev_dbg(msm_rotator_dev->device,
"unexpected IOCTL %d\n", cmd);
return -ENOTTY;
}
}
static const struct file_operations msm_rotator_fops = {
.owner = THIS_MODULE,
.open = msm_rotator_open,
.release = msm_rotator_close,
.unlocked_ioctl = msm_rotator_ioctl,
};
static int __devinit msm_rotator_probe(struct platform_device *pdev)
{
int rc = 0;
struct resource *res;
struct msm_rotator_platform_data *pdata = NULL;
int i, number_of_clks;
uint32_t ver;
msm_rotator_dev = kzalloc(sizeof(struct msm_rotator_dev), GFP_KERNEL);
if (!msm_rotator_dev) {
printk(KERN_ERR "%s Unable to allocate memory for struct\n",
__func__);
return -ENOMEM;
}
for (i = 0; i < MAX_SESSIONS; i++)
msm_rotator_dev->rot_session[i] = NULL;
msm_rotator_dev->last_session_idx = INVALID_SESSION;
pdata = pdev->dev.platform_data;
number_of_clks = pdata->number_of_clocks;
rot_iommu_split_domain = pdata->rot_iommu_split_domain;
msm_rotator_dev->imem_owner = IMEM_NO_OWNER;
mutex_init(&msm_rotator_dev->imem_lock);
INIT_LIST_HEAD(&msm_rotator_dev->fd_list);
msm_rotator_dev->imem_clk_state = CLK_DIS;
INIT_DELAYED_WORK(&msm_rotator_dev->imem_clk_work,
msm_rotator_imem_clk_work_f);
msm_rotator_dev->imem_clk = NULL;
msm_rotator_dev->pdev = pdev;
msm_rotator_dev->core_clk = NULL;
msm_rotator_dev->pclk = NULL;
mrd->y_rot_buf = kmalloc(sizeof(struct rot_buf_type), GFP_KERNEL);
mrd->chroma_rot_buf = kmalloc(sizeof(struct rot_buf_type), GFP_KERNEL);
mrd->chroma2_rot_buf = kmalloc(sizeof(struct rot_buf_type), GFP_KERNEL);
memset((void *)mrd->y_rot_buf, 0, sizeof(struct rot_buf_type));
memset((void *)mrd->chroma_rot_buf, 0, sizeof(struct rot_buf_type));
memset((void *)mrd->chroma2_rot_buf, 0, sizeof(struct rot_buf_type));
#ifdef CONFIG_MSM_BUS_SCALING
if (!msm_rotator_dev->bus_client_handle && pdata &&
pdata->bus_scale_table) {
msm_rotator_dev->bus_client_handle =
msm_bus_scale_register_client(
pdata->bus_scale_table);
if (!msm_rotator_dev->bus_client_handle) {
pr_err("%s not able to get bus scale handle\n",
__func__);
}
}
#endif
for (i = 0; i < number_of_clks; i++) {
if (pdata->rotator_clks[i].clk_type == ROTATOR_IMEM_CLK) {
msm_rotator_dev->imem_clk =
clk_get(&msm_rotator_dev->pdev->dev,
pdata->rotator_clks[i].clk_name);
if (IS_ERR(msm_rotator_dev->imem_clk)) {
rc = PTR_ERR(msm_rotator_dev->imem_clk);
msm_rotator_dev->imem_clk = NULL;
printk(KERN_ERR "%s: cannot get imem_clk "
"rc=%d\n", DRIVER_NAME, rc);
goto error_imem_clk;
}
if (pdata->rotator_clks[i].clk_rate)
clk_set_rate(msm_rotator_dev->imem_clk,
pdata->rotator_clks[i].clk_rate);
}
if (pdata->rotator_clks[i].clk_type == ROTATOR_PCLK) {
msm_rotator_dev->pclk =
clk_get(&msm_rotator_dev->pdev->dev,
pdata->rotator_clks[i].clk_name);
if (IS_ERR(msm_rotator_dev->pclk)) {
rc = PTR_ERR(msm_rotator_dev->pclk);
msm_rotator_dev->pclk = NULL;
printk(KERN_ERR "%s: cannot get pclk rc=%d\n",
DRIVER_NAME, rc);
goto error_pclk;
}
if (pdata->rotator_clks[i].clk_rate)
clk_set_rate(msm_rotator_dev->pclk,
pdata->rotator_clks[i].clk_rate);
}
if (pdata->rotator_clks[i].clk_type == ROTATOR_CORE_CLK) {
msm_rotator_dev->core_clk =
clk_get(&msm_rotator_dev->pdev->dev,
pdata->rotator_clks[i].clk_name);
if (IS_ERR(msm_rotator_dev->core_clk)) {
rc = PTR_ERR(msm_rotator_dev->core_clk);
msm_rotator_dev->core_clk = NULL;
printk(KERN_ERR "%s: cannot get core clk "
"rc=%d\n", DRIVER_NAME, rc);
goto error_core_clk;
}
if (pdata->rotator_clks[i].clk_rate)
clk_set_rate(msm_rotator_dev->core_clk,
pdata->rotator_clks[i].clk_rate);
}
}
msm_rotator_dev->regulator = regulator_get(&msm_rotator_dev->pdev->dev,
"vdd");
if (IS_ERR(msm_rotator_dev->regulator))
msm_rotator_dev->regulator = NULL;
msm_rotator_dev->rot_clk_state = CLK_DIS;
INIT_DELAYED_WORK(&msm_rotator_dev->rot_clk_work,
msm_rotator_rot_clk_work_f);
mutex_init(&msm_rotator_dev->rotator_lock);
#ifdef CONFIG_MSM_MULTIMEDIA_USE_ION
msm_rotator_dev->client = msm_ion_client_create(-1, pdev->name);
#endif
platform_set_drvdata(pdev, msm_rotator_dev);
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res) {
printk(KERN_ALERT
"%s: could not get IORESOURCE_MEM\n", DRIVER_NAME);
rc = -ENODEV;
goto error_get_resource;
}
msm_rotator_dev->io_base = ioremap(res->start,
resource_size(res));
#ifdef CONFIG_MSM_ROTATOR_USE_IMEM
if (msm_rotator_dev->imem_clk)
clk_prepare_enable(msm_rotator_dev->imem_clk);
#endif
enable_rot_clks();
ver = ioread32(MSM_ROTATOR_HW_VERSION);
disable_rot_clks();
#ifdef CONFIG_MSM_ROTATOR_USE_IMEM
if (msm_rotator_dev->imem_clk)
clk_disable_unprepare(msm_rotator_dev->imem_clk);
#endif
if (ver != pdata->hardware_version_number)
pr_debug("%s: invalid HW version ver 0x%x\n",
DRIVER_NAME, ver);
rotator_hw_revision = ver;
rotator_hw_revision >>= 16; /* bit 31:16 */
rotator_hw_revision &= 0xff;
pr_info("%s: rotator_hw_revision=%x\n",
__func__, rotator_hw_revision);
msm_rotator_dev->irq = platform_get_irq(pdev, 0);
if (msm_rotator_dev->irq < 0) {
printk(KERN_ALERT "%s: could not get IORESOURCE_IRQ\n",
DRIVER_NAME);
rc = -ENODEV;
goto error_get_irq;
}
rc = request_irq(msm_rotator_dev->irq, msm_rotator_isr,
IRQF_TRIGGER_RISING, DRIVER_NAME, NULL);
if (rc) {
printk(KERN_ERR "%s: request_irq() failed\n", DRIVER_NAME);
goto error_get_irq;
}
/* we enable the IRQ when we need it in the ioctl */
disable_irq(msm_rotator_dev->irq);
rc = alloc_chrdev_region(&msm_rotator_dev->dev_num, 0, 1, DRIVER_NAME);
if (rc < 0) {
printk(KERN_ERR "%s: alloc_chrdev_region Failed rc = %d\n",
__func__, rc);
goto error_get_irq;
}
msm_rotator_dev->class = class_create(THIS_MODULE, DRIVER_NAME);
if (IS_ERR(msm_rotator_dev->class)) {
rc = PTR_ERR(msm_rotator_dev->class);
printk(KERN_ERR "%s: couldn't create class rc = %d\n",
DRIVER_NAME, rc);
goto error_class_create;
}
msm_rotator_dev->device = device_create(msm_rotator_dev->class, NULL,
msm_rotator_dev->dev_num, NULL,
DRIVER_NAME);
if (IS_ERR(msm_rotator_dev->device)) {
rc = PTR_ERR(msm_rotator_dev->device);
printk(KERN_ERR "%s: device_create failed %d\n",
DRIVER_NAME, rc);
goto error_class_device_create;
}
cdev_init(&msm_rotator_dev->cdev, &msm_rotator_fops);
rc = cdev_add(&msm_rotator_dev->cdev,
MKDEV(MAJOR(msm_rotator_dev->dev_num), 0),
1);
if (rc < 0) {
printk(KERN_ERR "%s: cdev_add failed %d\n", __func__, rc);
goto error_cdev_add;
}
init_waitqueue_head(&msm_rotator_dev->wq);
INIT_WORK(&msm_rotator_dev->commit_work, rot_commit_wq_handler);
init_completion(&msm_rotator_dev->commit_comp);
mutex_init(&msm_rotator_dev->commit_mutex);
mutex_init(&msm_rotator_dev->commit_wq_mutex);
atomic_set(&msm_rotator_dev->commit_q_w, 0);
atomic_set(&msm_rotator_dev->commit_q_r, 0);
atomic_set(&msm_rotator_dev->commit_q_cnt, 0);
dev_dbg(msm_rotator_dev->device, "probe successful\n");
return rc;
error_cdev_add:
device_destroy(msm_rotator_dev->class, msm_rotator_dev->dev_num);
error_class_device_create:
class_destroy(msm_rotator_dev->class);
error_class_create:
unregister_chrdev_region(msm_rotator_dev->dev_num, 1);
error_get_irq:
iounmap(msm_rotator_dev->io_base);
error_get_resource:
mutex_destroy(&msm_rotator_dev->rotator_lock);
if (msm_rotator_dev->regulator)
regulator_put(msm_rotator_dev->regulator);
clk_put(msm_rotator_dev->core_clk);
error_core_clk:
clk_put(msm_rotator_dev->pclk);
error_pclk:
if (msm_rotator_dev->imem_clk)
clk_put(msm_rotator_dev->imem_clk);
error_imem_clk:
mutex_destroy(&msm_rotator_dev->imem_lock);
kfree(msm_rotator_dev);
return rc;
}
static int __devexit msm_rotator_remove(struct platform_device *plat_dev)
{
int i;
rot_wait_for_commit_queue(true);
#ifdef CONFIG_MSM_BUS_SCALING
if (msm_rotator_dev->bus_client_handle) {
msm_bus_scale_unregister_client
(msm_rotator_dev->bus_client_handle);
msm_rotator_dev->bus_client_handle = 0;
}
#endif
free_irq(msm_rotator_dev->irq, NULL);
mutex_destroy(&msm_rotator_dev->rotator_lock);
cdev_del(&msm_rotator_dev->cdev);
device_destroy(msm_rotator_dev->class, msm_rotator_dev->dev_num);
class_destroy(msm_rotator_dev->class);
unregister_chrdev_region(msm_rotator_dev->dev_num, 1);
iounmap(msm_rotator_dev->io_base);
if (msm_rotator_dev->imem_clk) {
if (msm_rotator_dev->imem_clk_state == CLK_EN)
clk_disable_unprepare(msm_rotator_dev->imem_clk);
clk_put(msm_rotator_dev->imem_clk);
msm_rotator_dev->imem_clk = NULL;
}
if (msm_rotator_dev->rot_clk_state == CLK_EN)
disable_rot_clks();
clk_put(msm_rotator_dev->core_clk);
clk_put(msm_rotator_dev->pclk);
if (msm_rotator_dev->regulator)
regulator_put(msm_rotator_dev->regulator);
msm_rotator_dev->core_clk = NULL;
msm_rotator_dev->pclk = NULL;
mutex_destroy(&msm_rotator_dev->imem_lock);
for (i = 0; i < MAX_SESSIONS; i++)
if (msm_rotator_dev->rot_session[i] != NULL)
kfree(msm_rotator_dev->rot_session[i]);
kfree(msm_rotator_dev);
return 0;
}
#ifdef CONFIG_PM
static int msm_rotator_suspend(struct platform_device *dev, pm_message_t state)
{
rot_wait_for_commit_queue(true);
mutex_lock(&msm_rotator_dev->imem_lock);
if (msm_rotator_dev->imem_clk_state == CLK_EN
&& msm_rotator_dev->imem_clk) {
clk_disable_unprepare(msm_rotator_dev->imem_clk);
msm_rotator_dev->imem_clk_state = CLK_SUSPEND;
}
mutex_unlock(&msm_rotator_dev->imem_lock);
mutex_lock(&msm_rotator_dev->rotator_lock);
if (msm_rotator_dev->rot_clk_state == CLK_EN) {
disable_rot_clks();
msm_rotator_dev->rot_clk_state = CLK_SUSPEND;
}
msm_rotator_release_all_timeline();
mutex_unlock(&msm_rotator_dev->rotator_lock);
return 0;
}
static int msm_rotator_resume(struct platform_device *dev)
{
mutex_lock(&msm_rotator_dev->imem_lock);
if (msm_rotator_dev->imem_clk_state == CLK_SUSPEND
&& msm_rotator_dev->imem_clk) {
clk_prepare_enable(msm_rotator_dev->imem_clk);
msm_rotator_dev->imem_clk_state = CLK_EN;
}
mutex_unlock(&msm_rotator_dev->imem_lock);
mutex_lock(&msm_rotator_dev->rotator_lock);
if (msm_rotator_dev->rot_clk_state == CLK_SUSPEND) {
enable_rot_clks();
msm_rotator_dev->rot_clk_state = CLK_EN;
}
mutex_unlock(&msm_rotator_dev->rotator_lock);
return 0;
}
#endif
static struct platform_driver msm_rotator_platform_driver = {
.probe = msm_rotator_probe,
.remove = __devexit_p(msm_rotator_remove),
#ifdef CONFIG_PM
.suspend = msm_rotator_suspend,
.resume = msm_rotator_resume,
#endif
.driver = {
.owner = THIS_MODULE,
.name = DRIVER_NAME
}
};
static int __init msm_rotator_init(void)
{
return platform_driver_register(&msm_rotator_platform_driver);
}
static void __exit msm_rotator_exit(void)
{
return platform_driver_unregister(&msm_rotator_platform_driver);
}
module_init(msm_rotator_init);
module_exit(msm_rotator_exit);
MODULE_DESCRIPTION("MSM Offline Image Rotator driver");
MODULE_VERSION("1.0");
MODULE_LICENSE("GPL v2");
| AdrianoMartins/android_kernel_lge_v500 | drivers/char/msm_rotator.c | C | gpl-2.0 | 88,858 |
using System;
using Server;
using Server.Gumps;
using Server.Network;
namespace Server.Items
{
public class PowerScroll : Item
{
private SkillName m_Skill;
private double m_Value;
private static SkillName[] m_Skills = new SkillName[]
{
SkillName.Blacksmith,
SkillName.Tailoring,
SkillName.Swords,
SkillName.Fencing,
SkillName.Macing,
SkillName.Archery,
SkillName.Wrestling,
SkillName.Parry,
SkillName.Tactics,
SkillName.Anatomy,
SkillName.Healing,
SkillName.Magery,
SkillName.Meditation,
SkillName.EvalInt,
SkillName.MagicResist,
SkillName.AnimalTaming,
SkillName.AnimalLore,
SkillName.Veterinary,
SkillName.Musicianship,
SkillName.Provocation,
SkillName.Discordance,
SkillName.Peacemaking
};
private static SkillName[] m_AOSSkills = new SkillName[]
{
SkillName.Blacksmith,
SkillName.Tailoring,
SkillName.Swords,
SkillName.Fencing,
SkillName.Macing,
SkillName.Archery,
SkillName.Wrestling,
SkillName.Parry,
SkillName.Tactics,
SkillName.Anatomy,
SkillName.Healing,
SkillName.Magery,
SkillName.Meditation,
SkillName.EvalInt,
SkillName.MagicResist,
SkillName.AnimalTaming,
SkillName.AnimalLore,
SkillName.Veterinary,
SkillName.Musicianship,
SkillName.Provocation,
SkillName.Discordance,
SkillName.Peacemaking,
SkillName.Chivalry,
SkillName.Focus,
SkillName.Necromancy,
SkillName.Stealing,
SkillName.Stealth,
SkillName.SpiritSpeak
};
private static SkillName[] m_SESkills = new SkillName[]
{
SkillName.Blacksmith,
SkillName.Tailoring,
SkillName.Swords,
SkillName.Fencing,
SkillName.Macing,
SkillName.Archery,
SkillName.Wrestling,
SkillName.Parry,
SkillName.Tactics,
SkillName.Anatomy,
SkillName.Healing,
SkillName.Magery,
SkillName.Meditation,
SkillName.EvalInt,
SkillName.MagicResist,
SkillName.AnimalTaming,
SkillName.AnimalLore,
SkillName.Veterinary,
SkillName.Musicianship,
SkillName.Provocation,
SkillName.Discordance,
SkillName.Peacemaking,
SkillName.Chivalry,
SkillName.Focus,
SkillName.Necromancy,
SkillName.Stealing,
SkillName.Stealth,
SkillName.SpiritSpeak,
SkillName.Ninjitsu,
SkillName.Bushido
};
private static SkillName[] m_MLSkills = new SkillName[]
{
SkillName.Blacksmith,
SkillName.Tailoring,
SkillName.Swords,
SkillName.Fencing,
SkillName.Macing,
SkillName.Archery,
SkillName.Wrestling,
SkillName.Parry,
SkillName.Tactics,
SkillName.Anatomy,
SkillName.Healing,
SkillName.Magery,
SkillName.Meditation,
SkillName.EvalInt,
SkillName.MagicResist,
SkillName.AnimalTaming,
SkillName.AnimalLore,
SkillName.Veterinary,
SkillName.Musicianship,
SkillName.Provocation,
SkillName.Discordance,
SkillName.Peacemaking,
SkillName.Chivalry,
SkillName.Focus,
SkillName.Necromancy,
SkillName.Stealing,
SkillName.Stealth,
SkillName.SpiritSpeak,
SkillName.Ninjitsu,
SkillName.Bushido,
SkillName.Spellweaving
};
public static SkillName[] Skills{ get{ return ( Core.ML ? m_MLSkills : Core.SE ? m_SESkills : Core.AOS ? m_AOSSkills : m_Skills ); } }
public static PowerScroll CreateRandom( int min, int max )
{
min /= 5;
max /= 5;
SkillName[] skills = PowerScroll.Skills;
return new PowerScroll( skills[Utility.Random( skills.Length )], 100 + (Utility.RandomMinMax( min, max ) * 5));
}
public static PowerScroll CreateRandomNoCraft( int min, int max )
{
min /= 5;
max /= 5;
SkillName[] skills = PowerScroll.Skills;
SkillName skillName;
do
{
skillName = skills[Utility.Random( skills.Length )];
} while ( skillName == SkillName.Blacksmith || skillName == SkillName.Tailoring );
return new PowerScroll( skillName, 100 + (Utility.RandomMinMax( min, max ) * 5));
}
[Constructable]
public PowerScroll( SkillName skill, double value ) : base( 0x14F0 )
{
base.Hue = 0x481;
base.Weight = 1.0;
m_Skill = skill;
m_Value = value;
if ( m_Value > 105.0 )
LootType = LootType.Cursed;
}
public PowerScroll( Serial serial ) : base( serial )
{
}
[CommandProperty( AccessLevel.GameMaster )]
public SkillName Skill
{
get
{
return m_Skill;
}
set
{
m_Skill = value;
}
}
[CommandProperty( AccessLevel.GameMaster )]
public double Value
{
get
{
return m_Value;
}
set
{
m_Value = value;
}
}
private string GetNameLocalized()
{
return String.Concat( "#", (1044060 + (int)m_Skill).ToString() );
}
private string GetName()
{
int index = (int)m_Skill;
SkillInfo[] table = SkillInfo.Table;
if ( index >= 0 && index < table.Length )
return table[index].Name.ToLower();
else
return "???";
}
public override void AddNameProperty(ObjectPropertyList list)
{
if ( m_Value == 105.0 )
list.Add( 1049639, GetNameLocalized() ); // a wonderous scroll of ~1_type~ (105 Skill)
else if ( m_Value == 110.0 )
list.Add( 1049640, GetNameLocalized() ); // an exalted scroll of ~1_type~ (110 Skill)
else if ( m_Value == 115.0 )
list.Add( 1049641, GetNameLocalized() ); // a mythical scroll of ~1_type~ (115 Skill)
else if ( m_Value == 120.0 )
list.Add( 1049642, GetNameLocalized() ); // a legendary scroll of ~1_type~ (120 Skill)
else
list.Add( "a power scroll of {0} ({1} Skill)", GetName(), m_Value );
}
public override void OnSingleClick( Mobile from )
{
if ( m_Value == 105.0 )
base.LabelTo( from, 1049639, GetNameLocalized() ); // a wonderous scroll of ~1_type~ (105 Skill)
else if ( m_Value == 110.0 )
base.LabelTo( from, 1049640, GetNameLocalized() ); // an exalted scroll of ~1_type~ (110 Skill)
else if ( m_Value == 115.0 )
base.LabelTo( from, 1049641, GetNameLocalized() ); // a mythical scroll of ~1_type~ (115 Skill)
else if ( m_Value == 120.0 )
base.LabelTo( from, 1049642, GetNameLocalized() ); // a legendary scroll of ~1_type~ (120 Skill)
else
base.LabelTo( from, "a power scroll of {0} ({1} Skill)", GetName(), m_Value );
}
public void Use( Mobile from, bool firstStage )
{
if ( Deleted )
return;
if ( IsChildOf( from.Backpack ) )
{
Skill skill = from.Skills[m_Skill];
if ( skill != null )
{
if ( skill.Cap >= m_Value )
{
from.SendLocalizedMessage( 1049511, GetNameLocalized() ); // Your ~1_type~ is too high for this power scroll.
}
else
{
if ( firstStage )
{
from.CloseGump( typeof( StatCapScroll.InternalGump ) );
from.CloseGump( typeof( PowerScroll.InternalGump ) );
from.SendGump( new InternalGump( from, this ) );
}
else
{
from.SendLocalizedMessage( 1049513, GetNameLocalized() ); // You feel a surge of magic as the scroll enhances your ~1_type~!
skill.Cap = m_Value;
Effects.SendLocationParticles( EffectItem.Create( from.Location, from.Map, EffectItem.DefaultDuration ), 0, 0, 0, 0, 0, 5060, 0 );
Effects.PlaySound( from.Location, from.Map, 0x243 );
Effects.SendMovingParticles( new Entity( Serial.Zero, new Point3D( from.X - 6, from.Y - 6, from.Z + 15 ), from.Map ), from, 0x36D4, 7, 0, false, true, 0x497, 0, 9502, 1, 0, (EffectLayer)255, 0x100 );
Effects.SendMovingParticles( new Entity( Serial.Zero, new Point3D( from.X - 4, from.Y - 6, from.Z + 15 ), from.Map ), from, 0x36D4, 7, 0, false, true, 0x497, 0, 9502, 1, 0, (EffectLayer)255, 0x100 );
Effects.SendMovingParticles( new Entity( Serial.Zero, new Point3D( from.X - 6, from.Y - 4, from.Z + 15 ), from.Map ), from, 0x36D4, 7, 0, false, true, 0x497, 0, 9502, 1, 0, (EffectLayer)255, 0x100 );
Effects.SendTargetParticles( from, 0x375A, 35, 90, 0x00, 0x00, 9502, (EffectLayer)255, 0x100 );
Delete();
}
}
}
}
else
{
from.SendLocalizedMessage( 1042001 ); // That must be in your pack for you to use it.
}
}
public override void OnDoubleClick( Mobile from )
{
Use( from, true );
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 0 ); // version
writer.Write( (int) m_Skill );
writer.Write( (double) m_Value );
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
switch ( version )
{
case 0:
{
m_Skill = (SkillName)reader.ReadInt();
m_Value = reader.ReadDouble();
break;
}
}
if ( m_Value == 105.0 )
{
LootType = LootType.Regular;
}
else
{
LootType = LootType.Cursed;
if ( Insured )
Insured = false;
}
}
public class InternalGump : Gump
{
private Mobile m_Mobile;
private PowerScroll m_Scroll;
public InternalGump( Mobile mobile, PowerScroll scroll ) : base( 25, 50 )
{
m_Mobile = mobile;
m_Scroll = scroll;
AddPage( 0 );
AddBackground( 25, 10, 420, 200, 5054 );
AddImageTiled( 33, 20, 401, 181, 2624 );
AddAlphaRegion( 33, 20, 401, 181 );
AddHtmlLocalized( 40, 48, 387, 100, 1049469, true, true ); /* Using a scroll increases the maximum amount of a specific skill or your maximum statistics.
* When used, the effect is not immediately seen without a gain of points with that skill or statistics.
* You can view your maximum skill values in your skills window.
* You can view your maximum statistic value in your statistics window.
*/
AddHtmlLocalized( 125, 148, 200, 20, 1049478, 0xFFFFFF, false, false ); // Do you wish to use this scroll?
AddButton( 100, 172, 4005, 4007, 1, GumpButtonType.Reply, 0 );
AddHtmlLocalized( 135, 172, 120, 20, 1046362, 0xFFFFFF, false, false ); // Yes
AddButton( 275, 172, 4005, 4007, 0, GumpButtonType.Reply, 0 );
AddHtmlLocalized( 310, 172, 120, 20, 1046363, 0xFFFFFF, false, false ); // No
double value = scroll.m_Value;
if ( value == 105.0 )
AddHtmlLocalized( 40, 20, 260, 20, 1049635, 0xFFFFFF, false, false ); // Wonderous Scroll (105 Skill):
else if ( value == 110.0 )
AddHtmlLocalized( 40, 20, 260, 20, 1049636, 0xFFFFFF, false, false ); // Exalted Scroll (110 Skill):
else if ( value == 115.0 )
AddHtmlLocalized( 40, 20, 260, 20, 1049637, 0xFFFFFF, false, false ); // Mythical Scroll (115 Skill):
else if ( value == 120.0 )
AddHtmlLocalized( 40, 20, 260, 20, 1049638, 0xFFFFFF, false, false ); // Legendary Scroll (120 Skill):
else
AddHtml( 40, 20, 260, 20, String.Format( "<basefont color=#FFFFFF>Power Scroll ({0} Skill):</basefont>", value ), false, false );
AddHtmlLocalized( 310, 20, 120, 20, 1044060 + (int)scroll.m_Skill, 0xFFFFFF, false, false );
}
public override void OnResponse( NetState state, RelayInfo info )
{
if ( info.ButtonID == 1 )
m_Scroll.Use( m_Mobile, false );
}
}
}
} | alucardxlx/kaltar | Scripts/Items/Special/Special Scrolls/PowerScroll.cs | C# | gpl-2.0 | 11,516 |
/* Copyright (c) 2010-2011, Code Aurora Forum. 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 and
* only 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.
*/
/*
[SENSOR]
Sensor Model:
Camera Module:
Lens Model:
Driver IC: = OV2655
PV Size = 640 x 480
Cap Size = 2048 x 1536
Output Format = YUYV
MCLK Speed = 24M
PV DVP_PCLK =
Cap DVP_PCLK =
PV Frame Rate = 30fps
Cap Frame Rate = 7.5fps
I2C Slave ID =
I2C Mode = 16Addr, 16Data
*/
#ifndef CAMSENSOR_OV2655
#define CAMSENSOR_OV2655
#define OV2655_WriteSettingTbl(pTbl) OV2655_WriteRegsTbl(pTbl,sizeof(pTbl)/sizeof(pTbl[0]))
enum ov2655_test_mode_t {
TEST_OFF,
TEST_1,
TEST_2,
TEST_3
};
enum ov2655_resolution_t {
QTR_SIZE,
FULL_SIZE,
HFR_60FPS,
HFR_90FPS,
HFR_120FPS,
INVALID_SIZE
};
/******************************************************************************
OV2655_WREG, *POV2655_WREG Definition
******************************************************************************/
typedef struct
{
unsigned int addr; /*Reg Addr :16Bit*/
unsigned int data; /*Reg Data :16Bit or 8Bit*/
unsigned int data_format; /*Reg Data Format:16Bit = 0,8Bit = 1*/
unsigned int delay_mask;
} OV2655_WREG, *POV2655_WREG;
/******************************************************************************
Initial Setting Table
******************************************************************************/
OV2655_WREG ov2655_init_tbl[] =
{
{0x308c,0x80,1,0},
{0x308d,0x0e,1,0},
{0x360b,0x00,1,0},
{0x30b0,0xff,1,0},
{0x30b1,0xff,1,0},
{0x30b2,0x04,1,0},
{0x300e,0x34,1,0},
{0x300f,0xa6,1,0},
{0x3010,0x81,1,0},
{0x3082,0x01,1,0},
{0x30f4,0x01,1,0},
{0x3090,0x43,1,0},
{0x3091,0xc0,1,0},
{0x30ac,0x42,1,0},
{0x30d1,0x08,1,0},
{0x30a8,0x54,1,0},
{0x3015,0x02,1,0},
{0x3093,0x00,1,0},
{0x307e,0xe5,1,0},
{0x3079,0x00,1,0},
{0x30aa,0x52,1,0},
{0x3017,0x40,1,0},
{0x30f3,0x83,1,0},
{0x306a,0x0c,1,0},
{0x306d,0x00,1,0},
{0x336a,0x3c,1,0},
{0x3076,0x6a,1,0},
{0x30d9,0x95,1,0},
{0x3016,0x52,1,0},
{0x3601,0x30,1,0},
{0x304e,0x88,1,0},
{0x30f1,0x82,1,0},
{0x306f,0x14,1,0},
{0x302a,0x02,1,0},
{0x302b,0x84,1,0},
{0x3012,0x10,1,0},
{0x3011,0x01,1,0},//15fps
//;AEC/AGC
{0x3013,0xf7,1,0},
{0x301c,0x13,1,0},
{0x301d,0x17,1,0},
{0x3070,0x5c,1,0},
{0x3072,0x4d,1,0},
//;D5060
{0x30af,0x00,1,0},
{0x3048,0x1f,1,0},
{0x3049,0x4e,1,0},
{0x304a,0x20,1,0},
{0x304f,0x20,1,0},
{0x304b,0x02,1,0},
{0x304c,0x00,1,0},
{0x304d,0x02,1,0},
{0x304f,0x20,1,0},
{0x30a3,0x10,1,0},
{0x3013,0xf7,1,0},
{0x3014,0xa4,1,0},
{0x3071,0x00,1,0},
{0x3070,0xb9,1,0},
{0x3073,0x00,1,0},
{0x3072,0x4d,1,0},
{0x301c,0x03,1,0},
{0x301d,0x06,1,0},
{0x304d,0x42,1,0},
{0x304a,0x40,1,0},
{0x304f,0x40,1,0},
{0x3095,0x07,1,0},
{0x3096,0x16,1,0},
{0x3097,0x1d,1,0},
//;Window Setup
{0x3020,0x01,1,0},
{0x3021,0x18,1,0},
{0x3022,0x00,1,0},
{0x3023,0x06,1,0},
{0x3024,0x06,1,0},
{0x3025,0x58,1,0},
{0x3026,0x02,1,0},
{0x3027,0x61,1,0},
{0x3088,0x02,1,0},
{0x3089,0x80,1,0},
{0x308a,0x01,1,0},
{0x308b,0xe0,1,0},
{0x3316,0x64,1,0},
{0x3317,0x25,1,0},
{0x3318,0x80,1,0},
{0x3319,0x08,1,0},
{0x331a,0x28,1,0},
{0x331b,0x1e,1,0},
{0x331c,0x00,1,0},
{0x331d,0x38,1,0},
{0x3100,0x00,1,0},
//awb
{0x3320,0xfa,1,0},
{0x3321,0x11,1,0},
{0x3322,0x92,1,0},
{0x3323,0x01,1,0},
{0x3324,0x97,1,0},
{0x3325,0x02,1,0},
{0x3326,0xff,1,0},
{0x3327,0x10,1,0},
{0x3328,0x11,1,0},
{0x3329,0x0f,1,0},
{0x332a,0x58,1,0},
{0x332b,0x55,1,0},
{0x332c,0x90,1,0},
{0x332d,0xc0,1,0},
{0x332e,0x46,1,0},
{0x332f,0x2f,1,0},
{0x3330,0x2f,1,0},
{0x3331,0x44,1,0},
{0x3332,0xff,1,0},
{0x3333,0x00,1,0},
{0x3334,0xf0,1,0},
{0x3335,0xf0,1,0},
{0x3336,0xf0,1,0},
{0x3337,0x40,1,0},
{0x3338,0x40,1,0},
{0x3339,0x40,1,0},
{0x333a,0x00,1,0},
{0x333b,0x00,1,0},
//cmx
{0x3380,0x06,1,0},
{0x3381,0x90,1,0},
{0x3382,0x18,1,0},
{0x3383,0x31,1,0},
{0x3384,0x84,1,0},
{0x3385,0xb5,1,0},
{0x3386,0xba,1,0},
{0x3387,0xd2,1,0},
{0x3388,0x17,1,0},
{0x3389,0x9c,1,0},
{0x338a,0x00,1,0},
//gamma
{0x334f,0x20,1,0},
{0x3340,0x06,1,0},
{0x3341,0x14,1,0},
{0x3342,0x2b,1,0},
{0x3343,0x42,1,0},
{0x3344,0x55,1,0},
{0x3345,0x65,1,0},
{0x3346,0x70,1,0},
{0x3347,0x7c,1,0},
{0x3348,0x86,1,0},
{0x3349,0x96,1,0},
{0x334a,0xa3,1,0},
{0x334b,0xaf,1,0},
{0x334c,0xc4,1,0},
{0x334d,0xd7,1,0},
{0x334e,0xe8,1,0},
//;Lens correction
//R
{0x3350,0x35,1,0},
{0x3351,0x29,1,0},
{0x3352,0x08,1,0},
{0x3353,0x24,1,0},
{0x3354,0x00,1,0},
{0x3355,0x85,1,0},
//G
{0x3356,0x34,1,0},
{0x3357,0x29,1,0},
{0x3358,0x0f,1,0},
{0x3359,0x1d,1,0},
{0x335a,0x00,1,0},
{0x335b,0x85,1,0},
//B
{0x335c,0x36,1,0},
{0x335d,0x2b,1,0},
{0x335e,0x08,1,0},
{0x335f,0x1b,1,0},
{0x3360,0x00,1,0},
{0x3361,0x85,1,0},
//lenc gain
{0x3363,0x03,1,0},
{0x3364,0x01,1,0},
{0x3365,0x02,1,0},
{0x3366,0x00,1,0},
{0x3362,0x90,1,0},//lenc for binning
//uv adjust
{0x338b,0x08,1,0},
{0x338c,0x10,1,0},
{0x338d,0x5f,1,0},
//Sharpness/De-noise
{0x3370,0xd0,1,0},
{0x3371,0x00,1,0},
{0x3372,0x00,1,0},
{0x3373,0x30,1,0},
{0x3374,0x10,1,0},
{0x3375,0x10,1,0},
{0x3376,0x08,1,0},
{0x3377,0x02,1,0},
{0x3378,0x04,1,0},
{0x3379,0x40,1,0},
//aec
{0x3018,0x70,1,0},
{0x3019,0x60,1,0},
{0x301a,0x85,1,0},
//;BLC
{0x3069,0x86,1,0},
{0x307c,0x13,1,0},
{0x3087,0x02,1,0},
//;blacksun
//;Avdd 2.55~3.0V
{0x3090,0x3b,1,0},
{0x30a8,0x54,1,0},
{0x30aa,0x82,1,0},
{0x30a3,0x91,1,0},
{0x30a1,0x41,1,0},
//;Other functions
{0x3300,0xfc,1,0},
{0x3302,0x11,1,0},
{0x3400,0x00,1,0},
{0x3606,0x20,1,0},
{0x3601,0x30,1,0},
{0x300e,0x34,1,0},
{0x30f3,0x83,1,0},
{0x304e,0x88,1,0},
};
/******************************************************************************
Preview Setting Table 30Fps
******************************************************************************/
OV2655_WREG ov2655_preview_tbl_30fps[] =
{
//pclk=18M
//framerate:15fps
//YUVVGA(640x480)
{0x300e,0x3a,1,0},
{0x3010,0x81,1,0},
{0x3012,0x10,1,0},
{0x3014,0xac,1,0},
{0x3015,0x11,1,0},
{0x3016,0x82,1,0},
{0x3023,0x06,1,0},
{0x3026,0x02,1,0},
{0x3027,0x5e,1,0},
{0x302a,0x02,1,0},
{0x302b,0xe4,1,0},
{0x330c,0x00,1,0},
{0x3301,0xff,1,0},
{0x3069,0x80,1,0},
{0x306f,0x14,1,0},
{0x3088,0x03,1,0},
{0x3089,0x20,1,0},
{0x308a,0x02,1,0},
{0x308b,0x58,1,0},
{0x308e,0x00,1,0},
{0x30a1,0x41,1,0},
{0x30a3,0x80,1,0},
{0x30d9,0x95,1,0},
{0x3302,0x11,1,0},
{0x3317,0x25,1,0},
{0x3318,0x80,1,0},
{0x3319,0x08,1,0},
{0x331d,0x38,1,0},
{0x3373,0x40,1,0},
{0x3376,0x05,1,0},
{0x3362,0x90,1,0},
//svga->vga
{0x3302,0x11,1,0},
{0x3088,0x02,1,0},
{0x3089,0x80,1,0},
{0x308a,0x01,1,0},
{0x308b,0xe0,1,0},
{0x331a,0x28,1,0},
{0x331b,0x1e,1,0},
{0x331c,0x00,1,0},
{0x3302,0x11,1,0},
//mipi
{0x363b,0x01,1,0},
{0x309e,0x08,1,0},
{0x3606,0x00,1,0},
{0x3630,0x35,1,0},
{0x3086,0x0f,1,0},
{0x3086,0x00,1,0},
{0x304e,0x04,1,0},
{0x363b,0x01,1,0},
{0x309e,0x08,1,0},
{0x3606,0x00,1,0},
{0x3084,0x01,1,0},
{0x3010,0x81,1,0},
{0x3011,0x00,1,0},
{0x3634,0x26,1,0},
{0x3086,0x0f,1,0},
{0x3086,0x00,1,0},
//avoid black screen slash
{0x3000,0x15,1,0},
{0x3002,0x02,1,0},
{0x3003,0x6a,1,0},
};
/******************************************************************************
Preview Setting Table 60Fps
******************************************************************************/
OV2655_WREG ov2655_preview_tbl_60fps[] =
{
};
/******************************************************************************
Preview Setting Table 90Fps
******************************************************************************/
OV2655_WREG ov2655_preview_tbl_90fps[] =
{
};
/******************************************************************************
Capture Setting Table
******************************************************************************/
OV2655_WREG ov2655_capture_tbl[]=
{
//pclk=24M
//framerate:7.5ps
{0x300e,0x34,1,0},
{0x3011,0x01,1,0},
{0x3010,0x81,1,0},
{0x3012,0x00,1,0},
{0x3015,0x02,1,0},
{0x3016,0xc2,1,0},
{0x3023,0x0c,1,0},
{0x3026,0x04,1,0},
{0x3027,0xbc,1,0},
{0x302a,0x04,1,0},
{0x302b,0xd4,1,0},
{0x3069,0x80,1,0},
{0x306f,0x54,1,0},
{0x3088,0x06,1,0},
{0x3089,0x40,1,0},
{0x308a,0x04,1,0},
{0x308b,0xb0,1,0},
{0x308e,0x64,1,0},
{0x30a1,0x41,1,0},
{0x30a3,0x80,1,0},
{0x30d9,0x95,1,0},
{0x3302,0x01,1,0},
{0x3317,0x4b,1,0},
{0x3318,0x00,1,0},
{0x3319,0x4c,1,0},
{0x331d,0x6c,1,0},
{0x3362,0x80,1,0},
{0x3373,0x40,1,0},
{0x3376,0x03,1,0},
};
/******************************************************************************
Contrast Setting
******************************************************************************/
OV2655_WREG ov2655_contrast_lv0_tbl[] =
{
//Contrast -4
{0x3391,0x04,1,0x04},
{0x3390,0x45,1,0x04},
{0x3398,0x14,1,0},
{0x3399,0x14,1,0},
};
OV2655_WREG ov2655_contrast_lv1_tbl[] =
{
//Contrast -3
{0x3391,0x04,1,0x04},
{0x3390,0x45,1,0x04},
{0x3398,0x14,1,0},
{0x3399,0x14,1,0},
};
OV2655_WREG ov2655_contrast_lv2_tbl[] =
{
//Contrast -2
{0x3391,0x04,1,0x04},
{0x3390,0x45,1,0x04},
{0x3398,0x18,1,0},
{0x3399,0x18,1,0},
};
OV2655_WREG ov2655_contrast_lv3_tbl[] =
{
//Contrast -1
{0x3391,0x04,1,0x04},
{0x3390,0x45,1,0x04},
{0x3398,0x1c,1,0},
{0x3399,0x1c,1,0},
};
OV2655_WREG ov2655_contrast_default_lv4_tbl[] =
{
//Contrast (Default)
{0x3391,0x04,1,0x04},
{0x3390,0x41,1,0x04},
{0x3398,0x20,1,0},
{0x3399,0x20,1,0},
};
OV2655_WREG ov2655_contrast_lv5_tbl[] =
{
//Contrast +1
{0x3391,0x04,1,0x04},
{0x3390,0x45,1,0x04},
{0x3398,0x24,1,0},
{0x3399,0x24,1,0},
};
OV2655_WREG ov2655_contrast_lv6_tbl[] =
{
//Contrast +2
{0x3391,0x04,1,0x04},
{0x3390,0x45,1,0x04},
{0x3398,0x28,1,0},
{0x3399,0x28,1,0},
};
OV2655_WREG ov2655_contrast_lv7_tbl[] =
{
//Contrast +3
{0x3391,0x04,1,0x04},
{0x3390,0x45,1,0x04},
{0x3398,0x2c,1,0},
{0x3399,0x2c,1,0},
};
OV2655_WREG ov2655_contrast_lv8_tbl[] =
{
//Contrast +4
{0x3391,0x04,1,0x04},
{0x3390,0x45,1,0x04},
{0x3398,0x30,1,0},
{0x3399,0x30,1,0},
};
/******************************************************************************
Sharpness Setting
******************************************************************************/
OV2655_WREG ov2655_sharpness_lv0_tbl[] =
{
//Sharpness 0
{0x3306,0x00,1,0x08},
{0x3376,0x01,1,0},
{0x3377,0x00,1,0},
{0x3378,0x10,1,0},
{0x3379,0x80,1,0},
};
OV2655_WREG ov2655_sharpness_lv1_tbl[] =
{
//Sharpness 1
{0x3306,0x00,1,0x08},
{0x3376,0x02,1,0},
{0x3377,0x00,1,0},
{0x3378,0x08,1,0},
{0x3379,0x80,1,0},
};
OV2655_WREG ov2655_sharpness_default_lv2_tbl[] =
{
//Sharpness_Auto (Default)
{0x3306,0x00,1,0x08},
{0x3376,0x05,1,0},//0x04
{0x3377,0x00,1,0},
{0x3378,0x04,1,0},
{0x3379,0x80,1,0},
};
OV2655_WREG ov2655_sharpness_lv3_tbl[] =
{
//Sharpness 3
{0x3306,0x00,1,0x08},
{0x3376,0x06,1,0},
{0x3377,0x00,1,0},
{0x3378,0x04,1,0},
{0x3379,0x80,1,0},
};
OV2655_WREG ov2655_sharpness_lv4_tbl[] =
{
//Sharpness 4
{0x3306,0x00,1,0x08},
{0x3376,0x08,1,0},
{0x3377,0x00,1,0},
{0x3378,0x04,1,0},
{0x3379,0x80,1,0},
};
OV2655_WREG ov2655_sharpness_lv5_tbl[] =
{
//Sharpness 5
{0x3306,0x00,1,0x08},
{0x3376,0x0a,1,0},
{0x3377,0x00,1,0},
{0x3378,0x04,1,0},
{0x3379,0x80,1,0},
};
OV2655_WREG ov2655_sharpness_lv6_tbl[] =
{
//Sharpness 5
{0x3306,0x00,1,0x08},
{0x3376,0x0c,1,0},
{0x3377,0x00,1,0},
{0x3378,0x04,1,0},
{0x3379,0x80,1,0},
};
OV2655_WREG ov2655_sharpness_lv7_tbl[] =
{
//Sharpness 7
{0x3306,0x00,1,0x08},
{0x3376,0x0e,1,0},
{0x3377,0x00,1,0},
{0x3378,0x04,1,0},
{0x3379,0x80,1,0},
};
OV2655_WREG ov2655_sharpness_lv8_tbl[] =
{
//Sharpness 8
{0x3306,0x00,1,0x08},
{0x3376,0x10,1,0},
{0x3377,0x00,1,0},
{0x3378,0x04,1,0},
{0x3379,0x80,1,0},
};
/******************************************************************************
Saturation Setting
******************************************************************************/
OV2655_WREG ov2655_saturation_lv0_tbl[] =
{
//Saturation x0.25
{0x3301,0x80,1,0x80},
{0x3391,0x02,1,0x02},
{0x3394,0x10,1,0},
{0x3395,0x10,1,0},
};
OV2655_WREG ov2655_saturation_lv1_tbl[] =
{
//Saturation x0.5
{0x3301,0x80,1,0x80},
{0x3391,0x02,1,0x02},
{0x3394,0x18,1,0},
{0x3395,0x18,1,0},
};
OV2655_WREG ov2655_saturation_lv2_tbl[] =
{
//Saturation x0.75
{0x3301,0x80,1,0x80},
{0x3391,0x02,1,0x02},
{0x3394,0x20,1,0},
{0x3395,0x20,1,0},
};
OV2655_WREG ov2655_saturation_lv3_tbl[] =
{
//Saturation x0.75
{0x3301,0x80,1,0x80},
{0x3391,0x02,1,0x02},
{0x3394,0x30,1,0},
{0x3395,0x30,1,0},
};
OV2655_WREG ov2655_saturation_default_lv4_tbl[] =
{
//Saturation x1 (Default)
{0x3301,0x80,1,0x80},
{0x3391,0x02,1,0x02},
{0x3394,0x40,1,0},
{0x3395,0x40,1,0},
};
OV2655_WREG ov2655_saturation_lv5_tbl[] =
{
//Saturation x1.25
{0x3301,0x80,1,0x80},
{0x3391,0x02,1,0x02},
{0x3394,0x50,1,0},
{0x3395,0x50,1,0},
};
OV2655_WREG ov2655_saturation_lv6_tbl[] =
{
//Saturation x1.5
{0x3301,0x80,1,0x80},
{0x3391,0x02,1,0x02},
{0x3394,0x58,1,0},
{0x3395,0x58,1,0},
};
OV2655_WREG ov2655_saturation_lv7_tbl[] =
{
//Saturation x1.25
{0x3301,0x80,1,0x80},
{0x3391,0x02,1,0x02},
{0x3394,0x60,1,0},
{0x3395,0x60,1,0},
};
OV2655_WREG ov2655_saturation_lv8_tbl[] =
{
//Saturation x1.5
{0x3301,0x80,1,0x80},
{0x3391,0x02,1,0x02},
{0x3394,0x68,1,0},
{0x3395,0x68,1,0},
};
/******************************************************************************
Brightness Setting
******************************************************************************/
OV2655_WREG ov2655_brightness_lv0_tbl[] =
{
//Brightness -4
{0x3391,0x04,1,0x04},
{0x3390,0x49,1,0x08},
{0x339a,0x28,1,0},
};
OV2655_WREG ov2655_brightness_lv1_tbl[] =
{
//Brightness -3
{0x3391,0x04,1,0x04},
{0x3390,0x49,1,0x08},
{0x339a,0x20,1,0},
};
OV2655_WREG ov2655_brightness_lv2_tbl[] =
{
//Brightness -2
{0x3391,0x04,1,0x04},
{0x3390,0x49,1,0x08},
{0x339a,0x18,1,0},
};
OV2655_WREG ov2655_brightness_lv3_tbl[] =
{
//Brightness -1
{0x3391,0x04,1,0x04},
{0x3390,0x49,1,0x08},
{0x339a,0x10,1,0},
};
OV2655_WREG ov2655_brightness_default_lv4_tbl[] =
{
//Brightness 0 (Default)
{0x3391,0x04,1,0x04},
{0x3390,0x41,1,0x08},
{0x339a,0x00,1,0},
};
OV2655_WREG ov2655_brightness_lv5_tbl[] =
{
//Brightness +1
{0x3391,0x04,1,0x04},
{0x3390,0x41,1,0x08},
{0x339a,0x10,1,0},
};
OV2655_WREG ov2655_brightness_lv6_tbl[] =
{
//Brightness +2
{0x3391,0x04,1,0x04},
{0x3390,0x41,1,0x08},
{0x339a,0x20,1,0},
};
OV2655_WREG ov2655_brightness_lv7_tbl[] =
{
//Brightness +3
{0x3391,0x04,1,0x04},
{0x3390,0x41,1,0x08},
{0x339a,0x28,1,0},
};
OV2655_WREG ov2655_brightness_lv8_tbl[] =
{
//Brightness +4
{0x3391,0x04,1,0x04},
{0x3390,0x41,1,0x08},
{0x339a,0x30,1,0},
};
/******************************************************************************
Exposure Compensation Setting
******************************************************************************/
OV2655_WREG ov2655_exposure_compensation_lv0_tbl[]=
{
//Exposure Compensation +1.7EV
{0x3018,0x98,1,0},
{0x3019,0x88,1,0},
{0x301a,0xd4,1,0},
};
OV2655_WREG ov2655_exposure_compensation_lv1_tbl[]=
{
//Exposure Compensation +1.0EV
{0x3018,0x88,1,0},
{0x3019,0x78,1,0},
{0x301a,0xd4,1,0},
};
OV2655_WREG ov2655_exposure_compensation_lv2_default_tbl[]=
{
//Exposure Compensation default
{0x3018,0x70,1,0},//0x78
{0x3019,0x60,1,0},//0x68
{0x301a,0x85,1,0},//0xa5
};
OV2655_WREG ov2655_exposure_compensation_lv3_tbl[]=
{
//Exposure Compensation -1.0EV
{0x3018,0x6a,1,0},
{0x3019,0x5a,1,0},
{0x301a,0xd4,1,0},
};
OV2655_WREG ov2655_exposure_compensation_lv4_tbl[]=
{
//Exposure Compensation -1.7EV
{0x3018,0x5a,1,0},
{0x3019,0x4a,1,0},
{0x301a,0xc2,1,0},
};
/******************************************************************************
ISO TYPE Setting
******************************************************************************/
OV2655_WREG ov2655_iso_type_auto[]=
{
//ISO Auto
};
OV2655_WREG ov2655_iso_type_100[]=
{
//ISO 100
};
OV2655_WREG ov2655_iso_type_200[]=
{
//ISO 200
};
OV2655_WREG ov2655_iso_type_400[]=
{
//ISO 400
};
OV2655_WREG ov2655_iso_type_800[]=
{
//ISO 800
};
OV2655_WREG ov2655_iso_type_1600[]=
{
//ISO 1600
};
/******************************************************************************
Auto Expourse Weight Setting
******************************************************************************/
OV2655_WREG ov2655_ae_average_tbl[] =
{
//Whole Image Average
{0x3030,0x55,1,0},
{0x3031,0x55,1,0},
{0x3032,0x55,1,0},
{0x3033,0x55,1,0},
};
OV2655_WREG ov2655_ae_centerweight_tbl[] =
{
//Whole Image Center More weight
{0x3030,0x00,1,0},
{0x3031,0x3c,1,0},
{0x3032,0x00,1,0},
{0x3033,0x00,1,0},
};
/******************************************************************************
Light Mode Setting
******************************************************************************/
OV2655_WREG ov2655_wb_Auto[]=
{
//CAMERA_WB_AUTO //1
{0x3306,0x00,1,0x02},
};
OV2655_WREG ov2655_wb_custom[]=
{
//CAMERA_WB_CUSTOM //2
{0x3306,0x02,1,0x02},
{0x3337,0x44,1,0},
{0x3338,0x40,1,0},
{0x3339,0x70,1,0},
};
OV2655_WREG ov2655_wb_inc[]=
{
//CAMERA_WB_INCANDESCENT //3
{0x3306,0x02,1,0x02},
{0x3337,0x52,1,0},
{0x3338,0x40,1,0},
{0x3339,0x58,1,0},
};
OV2655_WREG ov2655_wb_fluorescent[]=
{
//CAMERA_WB_FLUORESCENT //4
{0x3306,0x02,1,0x02},
{0x3337,0x44,1,0},
{0x3338,0x40,1,0},
{0x3339,0x70,1,0},
};
OV2655_WREG ov2655_wb_daylight[]=
{
//CAMERA_WB_DAYLIGHT //5
{0x3306,0x02,1,0x02},
{0x3337,0x5e,1,0},
{0x3338,0x40,1,0},
{0x3339,0x46,1,0},
};
OV2655_WREG ov2655_wb_cloudy[]=
{
//CAMERA_WB_CLOUDY_DAYLIGHT //6
// {0x3306,0x02,1,0x02},
// {0x3337,0x68,1,0},
// {0x3338,0x40,1,0},
// {0x3339,0x4e,1,0},
{0x3306,0x02,1,0x02},
{0x3337,0x78,1,0},
{0x3338,0x50,1,0},
{0x3339,0x48,1,0},
};
OV2655_WREG ov2655_wb_twilight[]=
{
//CAMERA_WB_TWILIGHT //7
};
OV2655_WREG ov2655_wb_shade[]=
{
//CAMERA_WB_SHADE //8
};
/******************************************************************************
EFFECT Setting
******************************************************************************/
OV2655_WREG ov2655_effect_normal_tbl[] =
{
//CAMERA_EFFECT_OFF 0
{0x3391,0x00,1,0x78},
};
OV2655_WREG ov2655_effect_mono_tbl[] =
{
//CAMERA_EFFECT_MONO 1
{0x3391,0x20,1,0x78},
};
OV2655_WREG ov2655_effect_negative_tbl[] =
{
//CAMERA_EFFECT_NEGATIVE 2
{0x3391,0x40,1,0x78},
};
OV2655_WREG ov2655_effect_solarize_tbl[] =
{
//CAMERA_EFFECT_SOLARIZE 3
};
OV2655_WREG ov2655_effect_sepia_tbl[] =
{
//CAMERA_EFFECT_SEPIA 4
{0x3391,0x18,1,0x78},
{0x3396,0x40,1,0},
{0x3397,0xa6,1,0},
};
OV2655_WREG ov2655_effect_posterize_tbl[] =
{
//CAMERA_EFFECT_POSTERIZE 5
};
OV2655_WREG ov2655_effect_whiteboard_tbl[] =
{
//CAMERA_EFFECT_WHITEBOARD 6
};
OV2655_WREG ov2655_effect_blackboard_tbl[] =
{
//CAMERA_EFFECT_BLACKBOARD 7
};
OV2655_WREG ov2655_effect_aqua_tbl[] =
{
//CAMERA_EFFECT_AQUA 8
};
OV2655_WREG ov2655_effect_bw_tbl[] =
{
//CAMERA_EFFECT_BW 10
};
OV2655_WREG ov2655_effect_bluish_tbl[] =
{
//CAMERA_EFFECT_BLUISH 12
{0x3391,0x18,1,0x78},
{0x3396,0xa0,1,0},
{0x3397,0x40,1,0},
};
OV2655_WREG ov2655_effect_reddish_tbl[] =
{
//CAMERA_EFFECT_REDDISH 13
{0x3391,0x18,1,0x78},
{0x3396,0x80,1,0},
{0x3397,0xc0,1,0},
};
OV2655_WREG ov2655_effect_greenish_tbl[] =
{
//CAMERA_EFFECT_GREENISH 14
{0x3391,0x18,1,0x78},
{0x3396,0x60,1,0},
{0x3397,0x60,1,0},
};
/******************************************************************************
AntiBanding Setting
******************************************************************************/
OV2655_WREG ov2655_antibanding_auto_tbl[] =
{
//Auto-XCLK24MHz
// {0x3014,0xc0,1,0xc0},
{0x3014,0x80,1,0xc0},
};
OV2655_WREG ov2655_antibanding_50z_tbl[] =
{
//Band 50Hz
{0x3014,0x80,1,0xc0},
};
OV2655_WREG ov2655_antibanding_60z_tbl[] =
{
//Band 60Hz
// {0x3014,0x00,1,0xc0},
{0x3014,0x80,1,0xc0},
};
/******************************************************************************
Lens_shading Setting
******************************************************************************/
OV2655_WREG ov2655_lens_shading_on_tbl[] =
{
//Lens_shading On
{0x3300,0x08,1,0x08},
};
OV2655_WREG ov2655_lens_shading_off_tbl[] =
{
//Lens_shading Off
{0x3300,0x00,1,0x08},
};
/******************************************************************************
Auto Focus Setting
******************************************************************************/
OV2655_WREG ov2655_afinit_tbl[] =
{
};
#endif /* CAMSENSOR_OV2655 */
| rex-xxx/Explay_A350_kernel_source_code | drivers/media/video/msm/ov2655.h | C | gpl-2.0 | 22,304 |
from django.db import models
from django.contrib.auth.models import User
class OrganisationType(models.Model):
type_desc = models.CharField(max_length=200)
def __unicode__(self):
return self.type_desc
class Address(models.Model):
street_address = models.CharField(max_length=100)
city = models.CharField(max_length=100)
pin = models.CharField(max_length=10)
province = models.CharField(max_length=100)
nationality = models.CharField(max_length=100)
def __unicode__(self):
return self.street_address + ',' + self.city
class HattiUser(models.Model):
user = models.OneToOneField(User)
address = models.ForeignKey(Address)
telephone = models.CharField(max_length=500)
date_joined = models.DateTimeField(auto_now_add=True)
fax = models.CharField(max_length=100)
avatar = models.CharField(max_length=100, null=True, blank=True)
tagline = models.CharField(max_length=140)
class Meta:
abstract = True
class AdminOrganisations(HattiUser):
title = models.CharField(max_length=200)
organisation_type = models.ForeignKey(OrganisationType)
def __unicode__(self):
return self.title
class Customer(HattiUser):
title = models.CharField(max_length=200, blank=True, null=True)
is_org = models.BooleanField();
org_type = models.ForeignKey(OrganisationType)
company = models.CharField(max_length = 200)
def __unicode__(self, arg):
return unicode(self.user)
| saloni10/librehatti_new | src/authentication/models.py | Python | gpl-2.0 | 1,479 |
/****************************************************************************************
* Copyright (c) 2010 Maximilian Kossick <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify it under *
* the terms of the GNU General Public License as published by the Free Software *
* Foundation; either version 2 of the License, or (at your option) any later *
* version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT ANY *
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A *
* PARTICULAR PURPOSE. See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License along with *
* this program. If not, see <http://www.gnu.org/licenses/>. *
****************************************************************************************/
#include "TestUnionJob.h"
#include "core/support/Debug.h"
#include "core/collections/CollectionLocation.h"
#include "synchronization/UnionJob.h"
#include "CollectionTestImpl.h"
#include "mocks/MockTrack.h"
#include "mocks/MockAlbum.h"
#include "mocks/MockArtist.h"
#include <KCmdLineArgs>
#include <KGlobal>
#include <QList>
#include <qtest_kde.h>
#include <gmock/gmock.h>
QTEST_KDEMAIN_CORE( TestUnionJob )
using ::testing::Return;
using ::testing::AnyNumber;
static QList<int> trackCopyCount;
namespace Collections {
class MyCollectionLocation : public CollectionLocation
{
public:
Collections::CollectionTestImpl *coll;
QString prettyLocation() const { return "foo"; }
bool isWritable() const { return true; }
bool remove( const Meta::TrackPtr &track )
{
coll->mc->acquireWriteLock();
//theoretically we should clean up the other maps as well...
TrackMap map = coll->mc->trackMap();
map.remove( track->uidUrl() );
coll->mc->setTrackMap( map );
coll->mc->releaseLock();
return true;
}
void copyUrlsToCollection(const QMap<Meta::TrackPtr, KUrl> &sources, const Transcoding::Configuration& conf)
{
Q_UNUSED( conf )
trackCopyCount << sources.count();
foreach( const Meta::TrackPtr &track, sources.keys() )
{
coll->mc->addTrack( track );
}
}
};
class MyCollectionTestImpl : public CollectionTestImpl
{
public:
MyCollectionTestImpl( const QString &id ) : CollectionTestImpl( id ) {}
CollectionLocation* location() const
{
MyCollectionLocation *r = new MyCollectionLocation();
r->coll = const_cast<MyCollectionTestImpl*>( this );
return r;
}
};
} //namespace Collections
void addMockTrack( Collections::CollectionTestImpl *coll, const QString &trackName, const QString &artistName, const QString &albumName )
{
Meta::MockTrack *track = new Meta::MockTrack();
::testing::Mock::AllowLeak( track );
Meta::TrackPtr trackPtr( track );
EXPECT_CALL( *track, name() ).Times( AnyNumber() ).WillRepeatedly( Return( trackName ) );
EXPECT_CALL( *track, uidUrl() ).Times( AnyNumber() ).WillRepeatedly( Return( trackName + "_" + artistName + "_" + albumName ) );
EXPECT_CALL( *track, isPlayable() ).Times( AnyNumber() ).WillRepeatedly( Return( true ) );
EXPECT_CALL( *track, playableUrl() ).Times( AnyNumber() ).WillRepeatedly( Return( KUrl( '/' + track->uidUrl() ) ) );
coll->mc->addTrack( trackPtr );
Meta::AlbumPtr albumPtr = coll->mc->albumMap().value( albumName );
Meta::MockAlbum *album;
Meta::TrackList albumTracks;
if( albumPtr )
{
album = dynamic_cast<Meta::MockAlbum*>( albumPtr.data() );
if( !album )
{
QFAIL( "expected a Meta::MockAlbum" );
return;
}
albumTracks = albumPtr->tracks();
}
else
{
album = new Meta::MockAlbum();
::testing::Mock::AllowLeak( album );
albumPtr = Meta::AlbumPtr( album );
EXPECT_CALL( *album, name() ).Times( AnyNumber() ).WillRepeatedly( Return( albumName ) );
EXPECT_CALL( *album, hasAlbumArtist() ).Times( AnyNumber() ).WillRepeatedly( Return( false ) );
EXPECT_CALL( *album, albumArtist() ).Times( AnyNumber() ).WillRepeatedly( Return( Meta::ArtistPtr() ) );
coll->mc->addAlbum( albumPtr );
}
albumTracks << trackPtr;
EXPECT_CALL( *album, tracks() ).Times( AnyNumber() ).WillRepeatedly( Return( albumTracks ) );
EXPECT_CALL( *track, album() ).Times( AnyNumber() ).WillRepeatedly( Return( albumPtr ) );
Meta::ArtistPtr artistPtr = coll->mc->artistMap().value( artistName );
Meta::MockArtist *artist;
Meta::TrackList artistTracks;
if( artistPtr )
{
artist = dynamic_cast<Meta::MockArtist*>( artistPtr.data() );
if( !artist )
{
QFAIL( "expected a Meta::MockArtist" );
return;
}
artistTracks = artistPtr->tracks();
}
else
{
artist = new Meta::MockArtist();
::testing::Mock::AllowLeak( artist );
artistPtr = Meta::ArtistPtr( artist );
EXPECT_CALL( *artist, name() ).Times( AnyNumber() ).WillRepeatedly( Return( artistName ) );
coll->mc->addArtist( artistPtr );
}
artistTracks << trackPtr;
EXPECT_CALL( *artist, tracks() ).Times( AnyNumber() ).WillRepeatedly( Return( artistTracks ) );
EXPECT_CALL( *track, artist() ).Times( AnyNumber() ).WillRepeatedly( Return( artistPtr ) );
}
TestUnionJob::TestUnionJob() : QObject()
{
KCmdLineArgs::init( KGlobal::activeComponent().aboutData() );
::testing::InitGoogleMock( &KCmdLineArgs::qtArgc(), KCmdLineArgs::qtArgv() );
qRegisterMetaType<Meta::TrackList>();
qRegisterMetaType<Meta::AlbumList>();
qRegisterMetaType<Meta::ArtistList>();
}
void
TestUnionJob::init()
{
trackCopyCount.clear();
}
void
TestUnionJob::testEmptyA()
{
Collections::CollectionTestImpl *collA = new Collections::MyCollectionTestImpl("A");
Collections::CollectionTestImpl *collB = new Collections::MyCollectionTestImpl("B");
addMockTrack( collB, "track1", "artist1", "album1" );
QCOMPARE( collA->mc->trackMap().count(), 0 );
QCOMPARE( collB->mc->trackMap().count(), 1 );
QVERIFY( trackCopyCount.isEmpty() );
UnionJob *job = new UnionJob( collA, collB );
job->synchronize();
QTest::kWaitForSignal( job, SIGNAL(destroyed()), 1000 );
QCOMPARE( trackCopyCount.size(), 1 );
QVERIFY( trackCopyCount.contains( 1 ) );
QCOMPARE( collA->mc->trackMap().count(), 1 );
QCOMPARE( collB->mc->trackMap().count(), 1 );
delete collA;
delete collB;
}
void
TestUnionJob::testEmptyB()
{
Collections::CollectionTestImpl *collA = new Collections::MyCollectionTestImpl("A");
Collections::CollectionTestImpl *collB = new Collections::MyCollectionTestImpl("B");
addMockTrack( collA, "track1", "artist1", "album1" );
QCOMPARE( collA->mc->trackMap().count(), 1 );
QCOMPARE( collB->mc->trackMap().count(), 0 );
QVERIFY( trackCopyCount.isEmpty() );
UnionJob *job = new UnionJob( collA, collB );
job->synchronize();
QTest::kWaitForSignal( job, SIGNAL(destroyed()), 1000 );
QCOMPARE( trackCopyCount.size(), 1 );
QVERIFY( trackCopyCount.contains( 1 ) );
QCOMPARE( collA->mc->trackMap().count(), 1 );
QCOMPARE( collB->mc->trackMap().count(), 1 );
delete collA;
delete collB;
}
void
TestUnionJob::testAddTrackToBoth()
{
Collections::CollectionTestImpl *collA = new Collections::MyCollectionTestImpl("A");
Collections::CollectionTestImpl *collB = new Collections::MyCollectionTestImpl("B");
addMockTrack( collA, "track1", "artist1", "album1" );
addMockTrack( collB, "track2", "artist2", "album2" );
QCOMPARE( collA->mc->trackMap().count(), 1 );
QCOMPARE( collB->mc->trackMap().count(), 1 );
QVERIFY( trackCopyCount.isEmpty() );
UnionJob *job = new UnionJob( collA, collB );
job->synchronize();
QTest::kWaitForSignal( job, SIGNAL(destroyed()), 1000 );
QCOMPARE( trackCopyCount.size(), 2 );
QCOMPARE( trackCopyCount.at( 0 ), 1 );
QCOMPARE( trackCopyCount.at( 1 ), 1 );
QCOMPARE( collA->mc->trackMap().count(), 2 );
QCOMPARE( collB->mc->trackMap().count(), 2 );
delete collA;
delete collB;
}
void
TestUnionJob::testTrackAlreadyInBoth()
{
Collections::CollectionTestImpl *collA = new Collections::MyCollectionTestImpl("A");
Collections::CollectionTestImpl *collB = new Collections::MyCollectionTestImpl("B");
addMockTrack( collA, "track1", "artist1", "album1" );
addMockTrack( collB, "track1", "artist1", "album1" );
addMockTrack( collB, "track2", "artist2", "album2" );
QCOMPARE( collA->mc->trackMap().count(), 1 );
QCOMPARE( collB->mc->trackMap().count(), 2 );
QVERIFY( trackCopyCount.isEmpty() );
UnionJob *job = new UnionJob( collA, collB );
job->synchronize();
QTest::kWaitForSignal( job, SIGNAL(destroyed()), 1000 );
QCOMPARE( trackCopyCount.size(), 1 );
QVERIFY( trackCopyCount.contains( 1 ) );
QCOMPARE( collA->mc->trackMap().count(), 2 );
QCOMPARE( collB->mc->trackMap().count(), 2 );
delete collA;
delete collB;
}
| kkszysiu/amarok | tests/synchronization/TestUnionJob.cpp | C++ | gpl-2.0 | 9,619 |
/* UOL Messenger
* Copyright (c) 2005 Universo Online S/A
*
* Direitos Autorais Reservados
* All rights reserved
*
* Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo
* sob os termos da Licença Pública Geral GNU conforme publicada pela Free
* Software Foundation; tanto a versão 2 da Licença, como (a seu critério)
* qualquer versão posterior.
* Este programa é distribuído na expectativa de que seja útil, porém,
* SEM NENHUMA GARANTIA; nem mesmo a garantia implícita de COMERCIABILIDADE
* OU ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral
* do GNU para mais detalhes.
* Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto
* com este programa; se não, escreva para a Free Software Foundation, Inc.,
* no endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA.
*
* 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.
*
* Universo Online S/A - A/C: UOL Messenger 5o. Andar
* Avenida Brigadeiro Faria Lima, 1.384 - Jardim Paulistano
* São Paulo SP - CEP 01452-002 - BRASIL */
#include "StdAfx.h"
#include <commands/ShowFileTransfersDialogcommand.h>
#include "../UIMApplication.h"
CShowFileTransfersDialogCommand::CShowFileTransfersDialogCommand()
{
}
CShowFileTransfersDialogCommand::~CShowFileTransfersDialogCommand(void)
{
}
void CShowFileTransfersDialogCommand::Execute()
{
CUIMApplication::GetApplication()->GetUIManager()->ShowFileTransferDialog(NULL);
}
| gabrieldelsaint/uol-messenger | src/public/uim/controller/commands/ShowFileTransfersDialogCommand.cpp | C++ | gpl-2.0 | 2,122 |
---
title: "Postmortem: Sheepstacker"
description: "A discussion about the development of the iOS game Sheepstacker from Tiny Tim Games."
categories: Postmortems
tags: [Tiny Tim Games, Unity, indie, iOS, postmortem, game development]
published: 3-21-2009
---
*NOTE: The following postmortem was originally presented on the Tiny Tim Games website, and it discusses a game that is no longer available to purchase or download. It has been placed here as a reference.*
As Sheepstacker has been available in the App Store for over a month now, I thought it might be time to share a few of our experiences from working on the game. If you’re a budding indie game developer, or you’re just interested in how we do the things we do, then I hope you’ll enjoy the following “postmortem” on how we felt the development of Sheepstacker went.
## Necessity… Mother… Invention…
Sheepstacker was a game of necessity for us. I had been working as a gameplay programmer in the traditional gaming industry for over six years by the time we had begun work on Sheepstacker. For a long time, I had felt the burn-out from either working too many hours or simply working on projects that either had no end in sight or just weren’t all that interesting. But that’s how things go in the big console and PC industry; you’re always working on someone else’s game, which is fun for a while. However, if you have any creative ambition at all, eventually you want to do something more.
In addition to this, the industry itself began going through radical changes. The Wii rose to the top as the dominant console in the marketplace (much to the chagrin of many top-tier publishers and developers), and the entire industry seems to have made a shift from being exclusively hardcore to something everyone wants to do. Couple this market shift with an economic recession, and you’ve got an industry that looks healthy overall, but has lots of internal problems at some of the once-successful companies. I was a victim of this shift, as were [many][layoffs1] [others][layoffs2] in the [Great][layoffs3] [Tech][layoffs4] [Layoffs][layoffs5] of 2009.
So with pink slip in hand and the hiring market drying up all across the industry, my wife Shannon and I set out to achieve the indie game development dream. Our number one priority was to simply get something done and out there with the shortest development time possible. We needed three things to get this accomplished though: 1) a platform; 2) an engine or SDK; and 3) a game design.
The first two were easy. Shannon and I both had iPhones, and I had switched fully to Mac about two years ago. We had everything we needed to get going with the iPhone SDK. As for the engine, I had already been messing around with the desktop and iPhone versions of [Unity][unity] for a while at that point. I really liked the workflow advantages of Unity, and felt it was directly engineered toward making great playing and great looking games very quickly. We still needed a game design though.
I had at one time played [Digital Chocolate][digital-chocolate]‘s great mobile game Tower Bloxx. I was so impressed with its simple one-button, addictive gameplay that I wanted to do something similar, but add to it and put my own little twist on it. However, I was having trouble coming up with a theme. That’s when Shannon suggested that we stack sheep. The rest is, as they say, history.
The following are some of the top five things that went right and wrong during the development of Sheepstacker:
## What Went Right
### 1. The Unity Engine
As an indie starting out with Unity, you already start way ahead of the curve. While the editor in Unity is sleek, simple, and a pleasure to use, the real advantage with Unity comes from the myriad things it does to try to keep you focused on making the game, and not worrying about everything else.
Take, for example, importing assets. To import a texture, you simply save the Photoshop file into the Assets folder of your project. After setting a few import settings, you never have to worry about importing the asset again. Simply open up the file, edit it, and save it. Unity automagically detects the edited file and reimports it. And that’s it.
The same goes for the scripting system. Scripts are auto-compiled on save, so you don’t have to worry about and older build lying around. In addition to this, it’s extremely easy to expose variables to the editor, allowing you to not only tweak settings, but also tweak them while the game is running and immediately see the effect in-game. It also helps that the scripting system supports writing scripts in C#, which is just close enough to C/C++ for me to be comfortable.
Being able to run the game in the editor without having to export constantly to the iPhone was great as well, though the export process is fairly straightforward and automated. From input to output, Unity streamlined our development immensely and allowed us to finish Sheepstacker, from initial prototype to app submission, in only three weeks.
### 2. A Simple Game Design
The simple, one-button gameplay of Sheepstacker meant that we had a small, well-scoped game for our first time out on our own. We couldn’t possibly do a larger game or even a simple level-based game as it would simply require too much content. Neither of us had really done 3D artwork before, so we needed something that wouldn’t be demanding content-wise.
We also needed something we could keep the reigns on in case feature creep started to kick in. The prototype for Sheepstacker was finished the same night we came up with the design, and the basic swinging/stacking mechanic changed very little from start to finish. Because we had the core of the game up and running so quickly, and because it was immediately fun, we felt that we could continue adding to the game until we felt like we were done, and not have to struggle with the basic gameplay while also adding all of the bells and whistles to make it polished.
### 3. Blender
While to serious artists in the gaming industry, [Blender][blender] might be an odd choice, for someone who had no prior experience in 3D art, it turned out to be one of our most useful tools.
I had purchased [“The Essential Blender”][the-essential-blender] book nearly a month prior to beginning Sheepstacker in an effort to take the fact that we couldn’t do 3D artwork ourselves out of the equation. While the interface was initially very daunting, with some good tutorials in the book, I was able to fairly quickly overcome the learning curve and become rather confident in my own ability to create 3D art.
Pretty soon, I was wanting the Blender shortcuts and tools to start appearing in other programs. Once you’re acquainted with the intricacies of the Blender workflow, you realize it’s designed for speed, creating things and manipulating them as quickly as possible. Again, this is one of the things we needed most on our project, and Blender delivered in spades.
### 4. Playing To Our Strengths
While I’m a programmer by trade, I had always wanted to get into the realm of game design. While one could simply chalk this up to a case of a programmer thinking he can make a better game than the designers, I had actually spent my entire career paying very close attention to the design aspects of the things I worked on. I regularly spoke with designers to get their insights into why some things work and why some things didn’t work. I would listen to the results from focus tests. I would pass ideas by designers themselves to get their input on it. My goal was always to learn about games beyond what I was simply implementing.
As it turns out, both experiences paid off for Sheepstacker. I had the experience of a seasoned programmer and enough game design knowledge to be able to quickly see when ideas would or wouldn’t work. For instance, we had a black sheep in our game at one point. It was meant to be something that the player should dodge, to kind of mix up the gameplay a bit. However, it never quite felt right. In the end, I’m glad to say that I think the addition would have eventually become a subtraction overall to the simple, addictive gameplay we created.
Additionally, Shannon was able to do what she had been doing for a long time already: graphics art. While I was able to come up with some fairly respectable 3D models, I was absolutely terrible at coming up with textures for them. However, she was able to use her experience and knowledge to fill that gap. I think we nailed the whimsical, cartoony visual style we were going for, and a lot of that can be credited to her.
### 5. The Sheep
While this could have gone under the “Blender” heading, I wanted to specifically point this out. We had the prototype running for a few days before we put the sheep into the game. It was already fairly enjoyable at that point. But as soon as we put the sheep in, without animations or even textures, all of a sudden we had a laugh out loud funny and fun game. The first time we saw a sheep land too far to the side of the stack and roll off, I knew we had something special.
And it only got better. After we textured and rigged the sheep, I began playing around with animating it. I was surprised at how simple, subtle movements really added so much to the game. The way that the sheep’s ears flap in the wind as they fall, the bulgy eyes when they’re knocked from the stack, the simple plop they do when they land, these all added the sort of polish we needed to really make the game stand out when people saw it. If there was one thing we couldn’t mess up, it was the sheep, and I think we did an admirable job with them.
## What Went Wrong
### 1. No Lite Version At Launch
It was a mistake not launching the game with an accompanying “lite” version. What’s an even bigger mistake is that it took us so long to final make one and submit it. We knew we had a great game. We had done numerous focus tests, and everyone who played it loved it. That meant that everyone else would love it too, right?
Unfortunately, people have to play the game first before they realize just how fun and addictive it can be, and without a lite version, we had to rely solely on word of mouth. And being that we’re a tiny independent game developer doing all of this from our home office, there was simply no way to generate the word of mouth buzz to make the game successful. People need to try it for themselves. That’s a mistake we’re not going to make again.
### 2. Where’s The Twist?
While I initially stated that I wanted to do something like Tower Bloxx, but with a twist, unfortunately the “twist” simply became “look, I can stack sheep!” While we have lots of subtle but important gameplay tweaks to the formula, there’s nothing we can really point to and say, “Yes, it’s similar to this, but wait ’til you get a load of this!”
Thankfully, we added a bit of this in our 1.1 update with the “Baa-lance” mode. While there are other “tilt the iPhone to catch something” games on the market, we essentially took the classic stacking gameplay (including the combos and the penalties) and made something that was unique and fun.
### 3. No High Scores
This is one that I was beating myself up for all the way through the submission process. However, we simply couldn’t get it into the initial version of the game within the timeframe we were on. It turned out to be a highly requested feature, so I’m glad we were able to add it finally (along with the inclusion of badges).
### 4. Making Menus
While the menus and UI itself turned out really nicely in the game, the actual development and upkeep of them took far too much time out of our schedule. Unity doesn’t have a very good one-size-fits-all solution for UI, and maybe no engine can provide that. But even so, having to deal with the slightly archaic `GUITexture` and `GUIText` objects was neither quick nor easy.
I will say this, though: The menu system from Sheepstacker is highly portable. We should be able to bring it into our projects going forward with little to no upkeep required. So this negative definitely turned into a positive going forward.
### 5. Sound
I hate sound effects. More specifically, I hate finding and implementing sound effects. While sound effects are most definitely a necessity in any good game and can many times steal the show, I just simply do not have the knack for finding the right sound for the right occasion.
We scoured through hundreds, if not thousands, of sounds before we finally came up with the twenty or so sounds that finally made it into the game. In addition, it took us a long time to find the right music for the title screen. While we had found the in-game music relatively early on and were really pleased with it, we just couldn’t settle on the title screen music. The music we have now is sufficient, but I would have liked to have had something more thematically similar to the great music found in the game proper.
## Something New
We learned a lot of valuable lessons going forward from Sheepstacker. We’re immensely proud of what we created, and we think it’s an excellent game that’s simple enough for a wide variety of people to be able to pick it up, play it, and immediately identify with it and enjoy it. However, I think we can do a lot better, and I look forward to us doing just that on our future projects.
[layoffs1]: http://feeds.gawker.com/~r/kotaku/full/~3/mHMfD_9WXE0/lay-offs-strike-crystal-dynamics
[layoffs2]: http://feeds.gawker.com/~r/kotaku/full/~3/uPDuEH6pKi8/more-ea-cuts-go-live-today
[layoffs3]: http://feeds.gawker.com/~r/kotaku/full/~3/OyTb5APfXuA/amd-cutting-jobs-slashing-survivors-pay
[layoffs4]: http://feeds.gawker.com/~r/kotaku/full/~3/9XPsE4CnawI/sega-staff-cuts-confirmed
[layoffs5]: http://feeds.gawker.com/~r/kotaku/full/~3/-xmbg06okT4/flight-simulator-devs-grounded-by-microsoft-job-cuts
[unity]: http://www.unity3d.com
[blender]: http://www.blender.org
[the-essential-blender]: http://www.blender3d.org/e-shop/product_info.php?products_id=96&PHPSESSID=db3c31556dac7ec5d1a6f0ff8cb7a22c | jerrodputman/jerrodputman.github.io | _drafts/2009-03-21-postmortem-sheepstacker.md | Markdown | gpl-2.0 | 14,183 |
/*
* Copyright (C) 2008-2015 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "AccountMgr.h"
#include "ArenaTeam.h"
#include "ArenaTeamMgr.h"
#include "Battleground.h"
#include "CalendarMgr.h"
#include "Chat.h"
#include "Common.h"
#include "DatabaseEnv.h"
#include "Group.h"
#include "Guild.h"
#include "GuildMgr.h"
#include "Language.h"
#include "Log.h"
#include "ObjectAccessor.h"
#include "ObjectMgr.h"
#include "Opcodes.h"
#include "Pet.h"
#include "PlayerDump.h"
#include "Player.h"
#include "ReputationMgr.h"
#include "ScriptMgr.h"
#include "SharedDefines.h"
#include "SocialMgr.h"
#include "SystemConfig.h"
#include "UpdateMask.h"
#include "Util.h"
#include "World.h"
#include "WorldPacket.h"
#include "WorldSession.h"
#ifdef ELUNA
#include "LuaEngine.h"
#endif
class LoginQueryHolder : public SQLQueryHolder
{
private:
uint32 m_accountId;
ObjectGuid m_guid;
public:
LoginQueryHolder(uint32 accountId, ObjectGuid guid)
: m_accountId(accountId), m_guid(guid) { }
ObjectGuid GetGuid() const { return m_guid; }
uint32 GetAccountId() const { return m_accountId; }
bool Initialize();
};
bool LoginQueryHolder::Initialize()
{
SetSize(MAX_PLAYER_LOGIN_QUERY);
bool res = true;
uint32 lowGuid = m_guid.GetCounter();
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER);
stmt->setUInt32(0, lowGuid);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_FROM, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_GROUP_MEMBER);
stmt->setUInt32(0, lowGuid);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_GROUP, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_INSTANCE);
stmt->setUInt32(0, lowGuid);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_BOUND_INSTANCES, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_AURAS);
stmt->setUInt32(0, lowGuid);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_AURAS, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_SPELL);
stmt->setUInt32(0, lowGuid);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_SPELLS, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_QUESTSTATUS);
stmt->setUInt32(0, lowGuid);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_QUEST_STATUS, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_QUESTSTATUS_DAILY);
stmt->setUInt32(0, lowGuid);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_DAILY_QUEST_STATUS, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_QUESTSTATUS_WEEKLY);
stmt->setUInt32(0, lowGuid);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_WEEKLY_QUEST_STATUS, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_QUESTSTATUS_MONTHLY);
stmt->setUInt32(0, lowGuid);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_MONTHLY_QUEST_STATUS, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_QUESTSTATUS_SEASONAL);
stmt->setUInt32(0, lowGuid);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_SEASONAL_QUEST_STATUS, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_REPUTATION);
stmt->setUInt32(0, lowGuid);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_REPUTATION, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_INVENTORY);
stmt->setUInt32(0, lowGuid);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_INVENTORY, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_ACTIONS);
stmt->setUInt32(0, lowGuid);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_ACTIONS, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_MAILCOUNT);
stmt->setUInt32(0, lowGuid);
stmt->setUInt64(1, uint64(time(NULL)));
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_MAIL_COUNT, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_MAILDATE);
stmt->setUInt32(0, lowGuid);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_MAIL_DATE, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_SOCIALLIST);
stmt->setUInt32(0, lowGuid);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_SOCIAL_LIST, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_HOMEBIND);
stmt->setUInt32(0, lowGuid);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_HOME_BIND, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_SPELLCOOLDOWNS);
stmt->setUInt32(0, lowGuid);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_SPELL_COOLDOWNS, stmt);
if (sWorld->getBoolConfig(CONFIG_DECLINED_NAMES_USED))
{
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_DECLINEDNAMES);
stmt->setUInt32(0, lowGuid);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_DECLINED_NAMES, stmt);
}
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_GUILD_MEMBER);
stmt->setUInt32(0, lowGuid);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_GUILD, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_ARENAINFO);
stmt->setUInt32(0, lowGuid);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_ARENA_INFO, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_ACHIEVEMENTS);
stmt->setUInt32(0, lowGuid);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_ACHIEVEMENTS, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_CRITERIAPROGRESS);
stmt->setUInt32(0, lowGuid);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_CRITERIA_PROGRESS, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_EQUIPMENTSETS);
stmt->setUInt32(0, lowGuid);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_EQUIPMENT_SETS, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_BGDATA);
stmt->setUInt32(0, lowGuid);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_BG_DATA, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_GLYPHS);
stmt->setUInt32(0, lowGuid);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_GLYPHS, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_TALENTS);
stmt->setUInt32(0, lowGuid);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_TALENTS, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_PLAYER_ACCOUNT_DATA);
stmt->setUInt32(0, lowGuid);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_ACCOUNT_DATA, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_SKILLS);
stmt->setUInt32(0, lowGuid);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_SKILLS, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_RANDOMBG);
stmt->setUInt32(0, lowGuid);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_RANDOM_BG, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_BANNED);
stmt->setUInt32(0, lowGuid);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_BANNED, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_QUESTSTATUSREW);
stmt->setUInt32(0, lowGuid);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_QUEST_STATUS_REW, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_ACCOUNT_INSTANCELOCKTIMES);
stmt->setUInt32(0, m_accountId);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_INSTANCE_LOCK_TIMES, stmt);
return res;
}
void WorldSession::HandleCharEnum(PreparedQueryResult result)
{
WorldPacket data(SMSG_CHAR_ENUM, 100); // we guess size
uint8 num = 0;
data << num;
_legitCharacters.clear();
if (result)
{
do
{
ObjectGuid guid(HIGHGUID_PLAYER, (*result)[0].GetUInt32());
TC_LOG_INFO("network", "Loading %s from account %u.", guid.ToString().c_str(), GetAccountId());
if (Player::BuildEnumData(result, &data))
{
// Do not allow banned characters to log in
if (!(*result)[20].GetUInt32())
_legitCharacters.insert(guid);
if (!sWorld->HasCharacterNameData(guid)) // This can happen if characters are inserted into the database manually. Core hasn't loaded name data yet.
sWorld->AddCharacterNameData(guid, (*result)[1].GetString(), (*result)[4].GetUInt8(), (*result)[2].GetUInt8(), (*result)[3].GetUInt8(), (*result)[7].GetUInt8());
++num;
}
}
while (result->NextRow());
}
data.put<uint8>(0, num);
SendPacket(&data);
}
void WorldSession::HandleCharEnumOpcode(WorldPacket& /*recvData*/)
{
// remove expired bans
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_EXPIRED_BANS);
CharacterDatabase.Execute(stmt);
/// get all the data necessary for loading all characters (along with their pets) on the account
if (sWorld->getBoolConfig(CONFIG_DECLINED_NAMES_USED))
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_ENUM_DECLINED_NAME);
else
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_ENUM);
stmt->setUInt8(0, PET_SAVE_AS_CURRENT);
stmt->setUInt32(1, GetAccountId());
_charEnumCallback = CharacterDatabase.AsyncQuery(stmt);
}
void WorldSession::HandleCharCreateOpcode(WorldPacket& recvData)
{
CharacterCreateInfo createInfo;
recvData >> createInfo.Name
>> createInfo.Race
>> createInfo.Class
>> createInfo.Gender
>> createInfo.Skin
>> createInfo.Face
>> createInfo.HairStyle
>> createInfo.HairColor
>> createInfo.FacialHair
>> createInfo.OutfitId;
if (!HasPermission(rbac::RBAC_PERM_SKIP_CHECK_CHARACTER_CREATION_TEAMMASK))
{
if (uint32 mask = sWorld->getIntConfig(CONFIG_CHARACTER_CREATING_DISABLED))
{
bool disabled = false;
switch (Player::TeamForRace(createInfo.Race))
{
case ALLIANCE:
disabled = (mask & (1 << 0)) != 0;
break;
case HORDE:
disabled = (mask & (1 << 1)) != 0;
break;
}
if (disabled)
{
SendCharCreate(CHAR_CREATE_DISABLED);
return;
}
}
}
ChrClassesEntry const* classEntry = sChrClassesStore.LookupEntry(createInfo.Class);
if (!classEntry)
{
TC_LOG_ERROR("network", "Class (%u) not found in DBC while creating new char for account (ID: %u): wrong DBC files or cheater?", createInfo.Class, GetAccountId());
SendCharCreate(CHAR_CREATE_FAILED);
return;
}
ChrRacesEntry const* raceEntry = sChrRacesStore.LookupEntry(createInfo.Race);
if (!raceEntry)
{
TC_LOG_ERROR("network", "Race (%u) not found in DBC while creating new char for account (ID: %u): wrong DBC files or cheater?", createInfo.Race, GetAccountId());
SendCharCreate(CHAR_CREATE_FAILED);
return;
}
// prevent character creating Expansion race without Expansion account
if (raceEntry->expansion > Expansion())
{
TC_LOG_ERROR("network", "Expansion %u account:[%d] tried to Create character with expansion %u race (%u)", Expansion(), GetAccountId(), raceEntry->expansion, createInfo.Race);
SendCharCreate(CHAR_CREATE_EXPANSION);
return;
}
// prevent character creating Expansion class without Expansion account
if (classEntry->expansion > Expansion())
{
TC_LOG_ERROR("network", "Expansion %u account:[%d] tried to Create character with expansion %u class (%u)", Expansion(), GetAccountId(), classEntry->expansion, createInfo.Class);
SendCharCreate(CHAR_CREATE_EXPANSION_CLASS);
return;
}
if (!HasPermission(rbac::RBAC_PERM_SKIP_CHECK_CHARACTER_CREATION_RACEMASK))
{
uint32 raceMaskDisabled = sWorld->getIntConfig(CONFIG_CHARACTER_CREATING_DISABLED_RACEMASK);
if ((1 << (createInfo.Race - 1)) & raceMaskDisabled)
{
SendCharCreate(CHAR_CREATE_DISABLED);
return;
}
}
if (!HasPermission(rbac::RBAC_PERM_SKIP_CHECK_CHARACTER_CREATION_CLASSMASK))
{
uint32 classMaskDisabled = sWorld->getIntConfig(CONFIG_CHARACTER_CREATING_DISABLED_CLASSMASK);
if ((1 << (createInfo.Class - 1)) & classMaskDisabled)
{
SendCharCreate(CHAR_CREATE_DISABLED);
return;
}
}
// prevent character creating with invalid name
if (!normalizePlayerName(createInfo.Name))
{
TC_LOG_ERROR("network", "Account:[%d] but tried to Create character with empty [name] ", GetAccountId());
SendCharCreate(CHAR_NAME_NO_NAME);
return;
}
// check name limitations
ResponseCodes res = ObjectMgr::CheckPlayerName(createInfo.Name, true);
if (res != CHAR_NAME_SUCCESS)
{
SendCharCreate(res);
return;
}
if (!HasPermission(rbac::RBAC_PERM_SKIP_CHECK_CHARACTER_CREATION_RESERVEDNAME) && sObjectMgr->IsReservedName(createInfo.Name))
{
SendCharCreate(CHAR_NAME_RESERVED);
return;
}
if (createInfo.Class == CLASS_DEATH_KNIGHT && !HasPermission(rbac::RBAC_PERM_SKIP_CHECK_CHARACTER_CREATION_HEROIC_CHARACTER))
{
// speedup check for heroic class disabled case
uint32 heroic_free_slots = sWorld->getIntConfig(CONFIG_HEROIC_CHARACTERS_PER_REALM);
if (heroic_free_slots == 0)
{
SendCharCreate(CHAR_CREATE_UNIQUE_CLASS_LIMIT);
return;
}
// speedup check for heroic class disabled case
uint32 req_level_for_heroic = sWorld->getIntConfig(CONFIG_CHARACTER_CREATING_MIN_LEVEL_FOR_HEROIC_CHARACTER);
if (req_level_for_heroic > sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL))
{
SendCharCreate(CHAR_CREATE_LEVEL_REQUIREMENT);
return;
}
}
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHECK_NAME);
stmt->setString(0, createInfo.Name);
delete _charCreateCallback.GetParam(); // Delete existing if any, to make the callback chain reset to stage 0
_charCreateCallback.SetParam(new CharacterCreateInfo(std::move(createInfo)));
_charCreateCallback.SetFutureResult(CharacterDatabase.AsyncQuery(stmt));
}
void WorldSession::HandleCharCreateCallback(PreparedQueryResult result, CharacterCreateInfo* createInfo)
{
/** This is a series of callbacks executed consecutively as a result from the database becomes available.
This is much more efficient than synchronous requests on packet handler, and much less DoS prone.
It also prevents data syncrhonisation errors.
*/
switch (_charCreateCallback.GetStage())
{
case 0:
{
if (result)
{
SendCharCreate(CHAR_CREATE_NAME_IN_USE);
delete createInfo;
_charCreateCallback.Reset();
return;
}
ASSERT(_charCreateCallback.GetParam() == createInfo);
PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_SUM_REALM_CHARACTERS);
stmt->setUInt32(0, GetAccountId());
_charCreateCallback.FreeResult();
_charCreateCallback.SetFutureResult(LoginDatabase.AsyncQuery(stmt));
_charCreateCallback.NextStage();
break;
}
case 1:
{
uint16 acctCharCount = 0;
if (result)
{
Field* fields = result->Fetch();
// SELECT SUM(x) is MYSQL_TYPE_NEWDECIMAL - needs to be read as string
const char* ch = fields[0].GetCString();
if (ch)
acctCharCount = atoi(ch);
}
if (acctCharCount >= sWorld->getIntConfig(CONFIG_CHARACTERS_PER_ACCOUNT))
{
SendCharCreate(CHAR_CREATE_ACCOUNT_LIMIT);
delete createInfo;
_charCreateCallback.Reset();
return;
}
ASSERT(_charCreateCallback.GetParam() == createInfo);
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_SUM_CHARS);
stmt->setUInt32(0, GetAccountId());
_charCreateCallback.FreeResult();
_charCreateCallback.SetFutureResult(CharacterDatabase.AsyncQuery(stmt));
_charCreateCallback.NextStage();
break;
}
case 2:
{
if (result)
{
Field* fields = result->Fetch();
createInfo->CharCount = uint8(fields[0].GetUInt64()); // SQL's COUNT() returns uint64 but it will always be less than uint8.Max
if (createInfo->CharCount >= sWorld->getIntConfig(CONFIG_CHARACTERS_PER_REALM))
{
SendCharCreate(CHAR_CREATE_SERVER_LIMIT);
delete createInfo;
_charCreateCallback.Reset();
return;
}
}
bool allowTwoSideAccounts = !sWorld->IsPvPRealm() || HasPermission(rbac::RBAC_PERM_TWO_SIDE_CHARACTER_CREATION);
uint32 skipCinematics = sWorld->getIntConfig(CONFIG_SKIP_CINEMATICS);
_charCreateCallback.FreeResult();
if (!allowTwoSideAccounts || skipCinematics == 1 || createInfo->Class == CLASS_DEATH_KNIGHT)
{
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_CREATE_INFO);
stmt->setUInt32(0, GetAccountId());
stmt->setUInt32(1, (skipCinematics == 1 || createInfo->Class == CLASS_DEATH_KNIGHT) ? 10 : 1);
_charCreateCallback.SetFutureResult(CharacterDatabase.AsyncQuery(stmt));
_charCreateCallback.NextStage();
return;
}
_charCreateCallback.NextStage();
HandleCharCreateCallback(PreparedQueryResult(NULL), createInfo); // Will jump to case 3
break;
}
case 3:
{
bool haveSameRace = false;
uint32 heroicReqLevel = sWorld->getIntConfig(CONFIG_CHARACTER_CREATING_MIN_LEVEL_FOR_HEROIC_CHARACTER);
bool hasHeroicReqLevel = (heroicReqLevel == 0);
bool allowTwoSideAccounts = !sWorld->IsPvPRealm() || HasPermission(rbac::RBAC_PERM_TWO_SIDE_CHARACTER_CREATION);
uint32 skipCinematics = sWorld->getIntConfig(CONFIG_SKIP_CINEMATICS);
bool checkHeroicReqs = createInfo->Class == CLASS_DEATH_KNIGHT && !HasPermission(rbac::RBAC_PERM_SKIP_CHECK_CHARACTER_CREATION_HEROIC_CHARACTER);
if (result)
{
uint32 team = Player::TeamForRace(createInfo->Race);
uint32 freeHeroicSlots = sWorld->getIntConfig(CONFIG_HEROIC_CHARACTERS_PER_REALM);
Field* field = result->Fetch();
uint8 accRace = field[1].GetUInt8();
if (checkHeroicReqs)
{
uint8 accClass = field[2].GetUInt8();
if (accClass == CLASS_DEATH_KNIGHT)
{
if (freeHeroicSlots > 0)
--freeHeroicSlots;
if (freeHeroicSlots == 0)
{
SendCharCreate(CHAR_CREATE_UNIQUE_CLASS_LIMIT);
delete createInfo;
_charCreateCallback.Reset();
return;
}
}
if (!hasHeroicReqLevel)
{
uint8 accLevel = field[0].GetUInt8();
if (accLevel >= heroicReqLevel)
hasHeroicReqLevel = true;
}
}
// need to check team only for first character
/// @todo what to if account already has characters of both races?
if (!allowTwoSideAccounts)
{
uint32 accTeam = 0;
if (accRace > 0)
accTeam = Player::TeamForRace(accRace);
if (accTeam != team)
{
SendCharCreate(CHAR_CREATE_PVP_TEAMS_VIOLATION);
delete createInfo;
_charCreateCallback.Reset();
return;
}
}
// search same race for cinematic or same class if need
/// @todo check if cinematic already shown? (already logged in?; cinematic field)
while ((skipCinematics == 1 && !haveSameRace) || createInfo->Class == CLASS_DEATH_KNIGHT)
{
if (!result->NextRow())
break;
field = result->Fetch();
accRace = field[1].GetUInt8();
if (!haveSameRace)
haveSameRace = createInfo->Race == accRace;
if (checkHeroicReqs)
{
uint8 acc_class = field[2].GetUInt8();
if (acc_class == CLASS_DEATH_KNIGHT)
{
if (freeHeroicSlots > 0)
--freeHeroicSlots;
if (freeHeroicSlots == 0)
{
SendCharCreate(CHAR_CREATE_UNIQUE_CLASS_LIMIT);
delete createInfo;
_charCreateCallback.Reset();
return;
}
}
if (!hasHeroicReqLevel)
{
uint8 acc_level = field[0].GetUInt8();
if (acc_level >= heroicReqLevel)
hasHeroicReqLevel = true;
}
}
}
}
if (checkHeroicReqs && !hasHeroicReqLevel)
{
SendCharCreate(CHAR_CREATE_LEVEL_REQUIREMENT);
delete createInfo;
_charCreateCallback.Reset();
return;
}
Player newChar(this);
newChar.GetMotionMaster()->Initialize();
if (!newChar.Create(sObjectMgr->GenerateLowGuid(HIGHGUID_PLAYER), createInfo))
{
// Player not create (race/class/etc problem?)
newChar.CleanupsBeforeDelete();
SendCharCreate(CHAR_CREATE_ERROR);
delete createInfo;
_charCreateCallback.Reset();
return;
}
if ((haveSameRace && skipCinematics == 1) || skipCinematics == 2)
newChar.setCinematic(1); // not show intro
newChar.SetAtLoginFlag(AT_LOGIN_FIRST); // First login
// Player created, save it now
newChar.SaveToDB(true);
createInfo->CharCount += 1;
SQLTransaction trans = LoginDatabase.BeginTransaction();
PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_DEL_REALM_CHARACTERS_BY_REALM);
stmt->setUInt32(0, GetAccountId());
stmt->setUInt32(1, realmID);
trans->Append(stmt);
stmt = LoginDatabase.GetPreparedStatement(LOGIN_INS_REALM_CHARACTERS);
stmt->setUInt32(0, createInfo->CharCount);
stmt->setUInt32(1, GetAccountId());
stmt->setUInt32(2, realmID);
trans->Append(stmt);
LoginDatabase.CommitTransaction(trans);
SendCharCreate(CHAR_CREATE_SUCCESS);
TC_LOG_INFO("entities.player.character", "Account: %d (IP: %s) Create Character:[%s] (GUID: %u)", GetAccountId(), GetRemoteAddress().c_str(), createInfo->Name.c_str(), newChar.GetGUIDLow());
sScriptMgr->OnPlayerCreate(&newChar);
sWorld->AddCharacterNameData(newChar.GetGUID(), newChar.GetName(), newChar.getGender(), newChar.getRace(), newChar.getClass(), newChar.getLevel());
newChar.CleanupsBeforeDelete();
delete createInfo;
_charCreateCallback.Reset();
break;
}
}
}
void WorldSession::HandleCharDeleteOpcode(WorldPacket& recvData)
{
ObjectGuid guid;
recvData >> guid;
// Initiating
uint32 initAccountId = GetAccountId();
// can't delete loaded character
if (ObjectAccessor::FindPlayer(guid))
{
sScriptMgr->OnPlayerFailedDelete(guid, initAccountId);
return;
}
uint32 accountId = 0;
uint8 level = 0;
std::string name;
// is guild leader
if (sGuildMgr->GetGuildByLeader(guid))
{
sScriptMgr->OnPlayerFailedDelete(guid, initAccountId);
SendCharDelete(CHAR_DELETE_FAILED_GUILD_LEADER);
return;
}
// is arena team captain
if (sArenaTeamMgr->GetArenaTeamByCaptain(guid))
{
sScriptMgr->OnPlayerFailedDelete(guid, initAccountId);
SendCharDelete(CHAR_DELETE_FAILED_ARENA_CAPTAIN);
return;
}
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_DATA_BY_GUID);
stmt->setUInt32(0, guid.GetCounter());
if (PreparedQueryResult result = CharacterDatabase.Query(stmt))
{
Field* fields = result->Fetch();
accountId = fields[0].GetUInt32();
name = fields[1].GetString();
level = fields[2].GetUInt8();
}
// prevent deleting other players' characters using cheating tools
if (accountId != initAccountId)
{
sScriptMgr->OnPlayerFailedDelete(guid, initAccountId);
return;
}
TC_LOG_INFO("entities.player.character", "Account: %d, IP: %s deleted character: %s, %s, Level: %u", accountId, GetRemoteAddress().c_str(), name.c_str(), guid.ToString().c_str(), level);
// To prevent hook failure, place hook before removing reference from DB
sScriptMgr->OnPlayerDelete(guid, initAccountId); // To prevent race conditioning, but as it also makes sense, we hand the accountId over for successful delete.
// Shouldn't interfere with character deletion though
if (sLog->ShouldLog("entities.player.dump", LOG_LEVEL_INFO)) // optimize GetPlayerDump call
{
std::string dump;
if (PlayerDumpWriter().GetDump(guid.GetCounter(), dump))
sLog->outCharDump(dump.c_str(), accountId, guid.GetRawValue(), name.c_str());
}
sCalendarMgr->RemoveAllPlayerEventsAndInvites(guid);
Player::DeleteFromDB(guid, accountId);
SendCharDelete(CHAR_DELETE_SUCCESS);
}
void WorldSession::HandlePlayerLoginOpcode(WorldPacket& recvData)
{
if (PlayerLoading() || GetPlayer() != NULL)
{
TC_LOG_ERROR("network", "Player tries to login again, AccountId = %d", GetAccountId());
KickPlayer();
return;
}
m_playerLoading = true;
ObjectGuid playerGuid;
TC_LOG_DEBUG("network", "WORLD: Recvd Player Logon Message");
recvData >> playerGuid;
if (!IsLegitCharacterForAccount(playerGuid))
{
TC_LOG_ERROR("network", "Account (%u) can't login with that character (%s).", GetAccountId(), playerGuid.ToString().c_str());
KickPlayer();
return;
}
LoginQueryHolder *holder = new LoginQueryHolder(GetAccountId(), playerGuid);
if (!holder->Initialize())
{
delete holder; // delete all unprocessed queries
m_playerLoading = false;
return;
}
_charLoginCallback = CharacterDatabase.DelayQueryHolder(holder);
}
void WorldSession::HandlePlayerLogin(LoginQueryHolder* holder)
{
ObjectGuid playerGuid = holder->GetGuid();
Player* pCurrChar = new Player(this);
// for send server info and strings (config)
ChatHandler chH = ChatHandler(pCurrChar->GetSession());
// "GetAccountId() == db stored account id" checked in LoadFromDB (prevent login not own character using cheating tools)
if (!pCurrChar->LoadFromDB(playerGuid, holder))
{
SetPlayer(NULL);
KickPlayer(); // disconnect client, player no set to session and it will not deleted or saved at kick
delete pCurrChar; // delete it manually
delete holder; // delete all unprocessed queries
m_playerLoading = false;
return;
}
pCurrChar->GetMotionMaster()->Initialize();
pCurrChar->SendDungeonDifficulty(false);
WorldPacket data(SMSG_LOGIN_VERIFY_WORLD, 20);
data << pCurrChar->GetMapId();
data << pCurrChar->GetPositionX();
data << pCurrChar->GetPositionY();
data << pCurrChar->GetPositionZ();
data << pCurrChar->GetOrientation();
SendPacket(&data);
// load player specific part before send times
LoadAccountData(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOAD_ACCOUNT_DATA), PER_CHARACTER_CACHE_MASK);
SendAccountDataTimes(PER_CHARACTER_CACHE_MASK);
data.Initialize(SMSG_FEATURE_SYSTEM_STATUS, 2); // added in 2.2.0
data << uint8(2); // unknown value
data << uint8(0); // enable(1)/disable(0) voice chat interface in client
SendPacket(&data);
// Send MOTD
{
data.Initialize(SMSG_MOTD, 50); // new in 2.0.1
data << (uint32)0;
uint32 linecount=0;
std::string str_motd = sWorld->GetMotd();
std::string::size_type pos, nextpos;
pos = 0;
while ((nextpos= str_motd.find('@', pos)) != std::string::npos)
{
if (nextpos != pos)
{
data << str_motd.substr(pos, nextpos-pos);
++linecount;
}
pos = nextpos+1;
}
if (pos<str_motd.length())
{
data << str_motd.substr(pos);
++linecount;
}
data.put(0, linecount);
SendPacket(&data);
TC_LOG_DEBUG("network", "WORLD: Sent motd (SMSG_MOTD)");
// send server info
if (sWorld->getIntConfig(CONFIG_ENABLE_SINFO_LOGIN) == 1)
chH.PSendSysMessage(_FULLVERSION);
TC_LOG_DEBUG("network", "WORLD: Sent server info");
}
//QueryResult* result = CharacterDatabase.PQuery("SELECT guildid, rank FROM guild_member WHERE guid = '%u'", pCurrChar->GetGUIDLow());
if (PreparedQueryResult resultGuild = holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOAD_GUILD))
{
Field* fields = resultGuild->Fetch();
pCurrChar->SetInGuild(fields[0].GetUInt32());
pCurrChar->SetRank(fields[1].GetUInt8());
}
else if (pCurrChar->GetGuildId()) // clear guild related fields in case wrong data about non existed membership
{
pCurrChar->SetInGuild(0);
pCurrChar->SetRank(0);
}
if (pCurrChar->GetGuildId() != 0)
{
if (Guild* guild = sGuildMgr->GetGuildById(pCurrChar->GetGuildId()))
guild->SendLoginInfo(this);
else
{
// remove wrong guild data
TC_LOG_ERROR("network", "Player %s (GUID: %u) marked as member of not existing guild (id: %u), removing guild membership for player.", pCurrChar->GetName().c_str(), pCurrChar->GetGUIDLow(), pCurrChar->GetGuildId());
pCurrChar->SetInGuild(0);
}
}
data.Initialize(SMSG_LEARNED_DANCE_MOVES, 4+4);
data << uint32(0);
data << uint32(0);
SendPacket(&data);
pCurrChar->SendInitialPacketsBeforeAddToMap();
//Show cinematic at the first time that player login
if (!pCurrChar->getCinematic())
{
pCurrChar->setCinematic(1);
if (ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(pCurrChar->getClass()))
{
if (cEntry->CinematicSequence)
pCurrChar->SendCinematicStart(cEntry->CinematicSequence);
else if (ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(pCurrChar->getRace()))
pCurrChar->SendCinematicStart(rEntry->CinematicSequence);
// send new char string if not empty
if (!sWorld->GetNewCharString().empty())
chH.PSendSysMessage("%s", sWorld->GetNewCharString().c_str());
}
}
if (!pCurrChar->GetMap()->AddPlayerToMap(pCurrChar) || !pCurrChar->CheckInstanceLoginValid())
{
AreaTrigger const* at = sObjectMgr->GetGoBackTrigger(pCurrChar->GetMapId());
if (at)
pCurrChar->TeleportTo(at->target_mapId, at->target_X, at->target_Y, at->target_Z, pCurrChar->GetOrientation());
else
pCurrChar->TeleportTo(pCurrChar->m_homebindMapId, pCurrChar->m_homebindX, pCurrChar->m_homebindY, pCurrChar->m_homebindZ, pCurrChar->GetOrientation());
}
sObjectAccessor->AddObject(pCurrChar);
//TC_LOG_DEBUG("Player %s added to Map.", pCurrChar->GetName().c_str());
pCurrChar->SendInitialPacketsAfterAddToMap();
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_ONLINE);
stmt->setUInt32(0, pCurrChar->GetGUIDLow());
CharacterDatabase.Execute(stmt);
stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_ACCOUNT_ONLINE);
stmt->setUInt32(0, GetAccountId());
LoginDatabase.Execute(stmt);
pCurrChar->SetInGameTime(getMSTime());
// announce group about member online (must be after add to player list to receive announce to self)
if (Group* group = pCurrChar->GetGroup())
{
//pCurrChar->groupInfo.group->SendInit(this); // useless
group->SendUpdate();
group->ResetMaxEnchantingLevel();
}
// friend status
sSocialMgr->SendFriendStatus(pCurrChar, FRIEND_ONLINE, pCurrChar->GetGUIDLow(), true);
// Place character in world (and load zone) before some object loading
pCurrChar->LoadCorpse();
// setting Ghost+speed if dead
if (pCurrChar->m_deathState != ALIVE)
{
// not blizz like, we must correctly save and load player instead...
if (pCurrChar->getRace() == RACE_NIGHTELF)
pCurrChar->CastSpell(pCurrChar, 20584, true, nullptr);// auras SPELL_AURA_INCREASE_SPEED(+speed in wisp form), SPELL_AURA_INCREASE_SWIM_SPEED(+swim speed in wisp form), SPELL_AURA_TRANSFORM (to wisp form)
pCurrChar->CastSpell(pCurrChar, 8326, true, nullptr); // auras SPELL_AURA_GHOST, SPELL_AURA_INCREASE_SPEED(why?), SPELL_AURA_INCREASE_SWIM_SPEED(why?)
pCurrChar->SetMovement(MOVE_WATER_WALK);
}
pCurrChar->ContinueTaxiFlight();
// reset for all pets before pet loading
if (pCurrChar->HasAtLoginFlag(AT_LOGIN_RESET_PET_TALENTS))
Pet::resetTalentsForAllPetsOf(pCurrChar);
// Load pet if any (if player not alive and in taxi flight or another then pet will remember as temporary unsummoned)
pCurrChar->LoadPet();
// Set FFA PvP for non GM in non-rest mode
if (sWorld->IsFFAPvPRealm() && !pCurrChar->IsGameMaster() && !pCurrChar->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING))
pCurrChar->SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
if (pCurrChar->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_CONTESTED_PVP))
pCurrChar->SetContestedPvP();
// Apply at_login requests
if (pCurrChar->HasAtLoginFlag(AT_LOGIN_RESET_SPELLS))
{
pCurrChar->ResetSpells();
SendNotification(LANG_RESET_SPELLS);
}
if (pCurrChar->HasAtLoginFlag(AT_LOGIN_RESET_TALENTS))
{
pCurrChar->ResetTalents(true);
pCurrChar->SendTalentsInfoData(false); // original talents send already in to SendInitialPacketsBeforeAddToMap, resend reset state
SendNotification(LANG_RESET_TALENTS);
}
bool firstLogin = pCurrChar->HasAtLoginFlag(AT_LOGIN_FIRST);
if (firstLogin)
pCurrChar->RemoveAtLoginFlag(AT_LOGIN_FIRST);
// show time before shutdown if shutdown planned.
if (sWorld->IsShuttingDown())
sWorld->ShutdownMsg(true, pCurrChar);
if (sWorld->getBoolConfig(CONFIG_ALL_TAXI_PATHS))
pCurrChar->SetTaxiCheater(true);
if (pCurrChar->IsGameMaster())
SendNotification(LANG_GM_ON);
std::string IP_str = GetRemoteAddress();
TC_LOG_INFO("entities.player.character", "Account: %d (IP: %s) Login Character:[%s] (GUID: %u) Level: %d",
GetAccountId(), IP_str.c_str(), pCurrChar->GetName().c_str(), pCurrChar->GetGUIDLow(), pCurrChar->getLevel());
if (!pCurrChar->IsStandState() && !pCurrChar->HasUnitState(UNIT_STATE_STUNNED))
pCurrChar->SetStandState(UNIT_STAND_STATE_STAND);
m_playerLoading = false;
// Handle Login-Achievements (should be handled after loading)
_player->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_ON_LOGIN, 1);
sScriptMgr->OnPlayerLogin(pCurrChar, firstLogin);
delete holder;
}
void WorldSession::HandleSetFactionAtWar(WorldPacket& recvData)
{
TC_LOG_DEBUG("network", "WORLD: Received CMSG_SET_FACTION_ATWAR");
uint32 repListID;
uint8 flag;
recvData >> repListID;
recvData >> flag;
GetPlayer()->GetReputationMgr().SetAtWar(repListID, flag != 0);
}
//I think this function is never used :/ I dunno, but i guess this opcode not exists
void WorldSession::HandleSetFactionCheat(WorldPacket& /*recvData*/)
{
TC_LOG_ERROR("network", "WORLD SESSION: HandleSetFactionCheat, not expected call, please report.");
GetPlayer()->GetReputationMgr().SendStates();
}
void WorldSession::HandleTutorialFlag(WorldPacket& recvData)
{
uint32 data;
recvData >> data;
uint8 index = uint8(data / 32);
if (index >= MAX_ACCOUNT_TUTORIAL_VALUES)
return;
uint32 value = (data % 32);
uint32 flag = GetTutorialInt(index);
flag |= (1 << value);
SetTutorialInt(index, flag);
}
void WorldSession::HandleTutorialClear(WorldPacket& /*recvData*/)
{
for (uint8 i = 0; i < MAX_ACCOUNT_TUTORIAL_VALUES; ++i)
SetTutorialInt(i, 0xFFFFFFFF);
}
void WorldSession::HandleTutorialReset(WorldPacket& /*recvData*/)
{
for (uint8 i = 0; i < MAX_ACCOUNT_TUTORIAL_VALUES; ++i)
SetTutorialInt(i, 0x00000000);
}
void WorldSession::HandleSetWatchedFactionOpcode(WorldPacket& recvData)
{
TC_LOG_DEBUG("network", "WORLD: Received CMSG_SET_WATCHED_FACTION");
uint32 fact;
recvData >> fact;
GetPlayer()->SetUInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX, fact);
}
void WorldSession::HandleSetFactionInactiveOpcode(WorldPacket& recvData)
{
TC_LOG_DEBUG("network", "WORLD: Received CMSG_SET_FACTION_INACTIVE");
uint32 replistid;
uint8 inactive;
recvData >> replistid >> inactive;
_player->GetReputationMgr().SetInactive(replistid, inactive != 0);
}
void WorldSession::HandleShowingHelmOpcode(WorldPacket& recvData)
{
TC_LOG_DEBUG("network", "CMSG_SHOWING_HELM for %s", _player->GetName().c_str());
recvData.read_skip<uint8>(); // unknown, bool?
_player->ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM);
}
void WorldSession::HandleShowingCloakOpcode(WorldPacket& recvData)
{
TC_LOG_DEBUG("network", "CMSG_SHOWING_CLOAK for %s", _player->GetName().c_str());
recvData.read_skip<uint8>(); // unknown, bool?
_player->ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK);
}
void WorldSession::HandleCharRenameOpcode(WorldPacket& recvData)
{
CharacterRenameInfo renameInfo;
recvData >> renameInfo.Guid
>> renameInfo.Name;
// prevent character rename to invalid name
if (!normalizePlayerName(renameInfo.Name))
{
SendCharRename(CHAR_NAME_NO_NAME, renameInfo);
return;
}
ResponseCodes res = ObjectMgr::CheckPlayerName(renameInfo.Name, true);
if (res != CHAR_NAME_SUCCESS)
{
SendCharRename(res, renameInfo);
return;
}
// check name limitations
if (!HasPermission(rbac::RBAC_PERM_SKIP_CHECK_CHARACTER_CREATION_RESERVEDNAME) && sObjectMgr->IsReservedName(renameInfo.Name))
{
SendCharRename(CHAR_NAME_RESERVED, renameInfo);
return;
}
// Ensure that the character belongs to the current account, that rename at login is enabled
// and that there is no character with the desired new name
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_FREE_NAME);
stmt->setUInt32(0, renameInfo.Guid.GetCounter());
stmt->setUInt32(1, GetAccountId());
stmt->setUInt16(2, AT_LOGIN_RENAME);
stmt->setUInt16(3, AT_LOGIN_RENAME);
stmt->setString(4, renameInfo.Name);
delete _charRenameCallback.GetParam();
_charRenameCallback.SetParam(new CharacterRenameInfo(std::move(renameInfo)));
_charRenameCallback.SetFutureResult(CharacterDatabase.AsyncQuery(stmt));
}
void WorldSession::HandleChangePlayerNameOpcodeCallBack(PreparedQueryResult result, CharacterRenameInfo const* renameInfo)
{
if (!result)
{
SendCharRename(CHAR_CREATE_ERROR, *renameInfo);
return;
}
Field* fields = result->Fetch();
uint32 guidLow = fields[0].GetUInt32();
std::string oldName = fields[1].GetString();
// Update name and at_login flag in the db
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_NAME);
stmt->setString(0, renameInfo->Name);
stmt->setUInt16(1, AT_LOGIN_RENAME);
stmt->setUInt32(2, guidLow);
CharacterDatabase.Execute(stmt);
// Removed declined name from db
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_DECLINED_NAME);
stmt->setUInt32(0, guidLow);
CharacterDatabase.Execute(stmt);
TC_LOG_INFO("entities.player.character", "Account: %d (IP: %s) Character:[%s] (%s) Changed name to: %s", GetAccountId(), GetRemoteAddress().c_str(), oldName.c_str(), renameInfo->Guid.ToString().c_str(), renameInfo->Name.c_str());
SendCharRename(RESPONSE_SUCCESS, *renameInfo);
sWorld->UpdateCharacterNameData(renameInfo->Guid, renameInfo->Name);
}
void WorldSession::HandleSetPlayerDeclinedNames(WorldPacket& recvData)
{
ObjectGuid guid;
recvData >> guid;
// not accept declined names for unsupported languages
std::string name;
if (!sObjectMgr->GetPlayerNameByGUID(guid, name))
{
SendSetPlayerDeclinedNamesResult(DECLINED_NAMES_RESULT_ERROR, guid);
return;
}
std::wstring wname;
if (!Utf8toWStr(name, wname))
{
SendSetPlayerDeclinedNamesResult(DECLINED_NAMES_RESULT_ERROR, guid);
return;
}
if (!isCyrillicCharacter(wname[0])) // name already stored as only single alphabet using
{
SendSetPlayerDeclinedNamesResult(DECLINED_NAMES_RESULT_ERROR, guid);
return;
}
std::string name2;
DeclinedName declinedname;
recvData >> name2;
if (name2 != name) // character have different name
{
SendSetPlayerDeclinedNamesResult(DECLINED_NAMES_RESULT_ERROR, guid);
return;
}
for (int i = 0; i < MAX_DECLINED_NAME_CASES; ++i)
{
recvData >> declinedname.name[i];
if (!normalizePlayerName(declinedname.name[i]))
{
SendSetPlayerDeclinedNamesResult(DECLINED_NAMES_RESULT_ERROR, guid);
return;
}
}
if (!ObjectMgr::CheckDeclinedNames(wname, declinedname))
{
SendSetPlayerDeclinedNamesResult(DECLINED_NAMES_RESULT_ERROR, guid);
return;
}
for (int i = 0; i < MAX_DECLINED_NAME_CASES; ++i)
CharacterDatabase.EscapeString(declinedname.name[i]);
SQLTransaction trans = CharacterDatabase.BeginTransaction();
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_DECLINED_NAME);
stmt->setUInt32(0, guid.GetCounter());
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHAR_DECLINED_NAME);
stmt->setUInt32(0, guid.GetCounter());
for (uint8 i = 0; i < 5; i++)
stmt->setString(i+1, declinedname.name[i]);
trans->Append(stmt);
CharacterDatabase.CommitTransaction(trans);
SendSetPlayerDeclinedNamesResult(DECLINED_NAMES_RESULT_SUCCESS, guid);
}
void WorldSession::HandleAlterAppearance(WorldPacket& recvData)
{
TC_LOG_DEBUG("network", "CMSG_ALTER_APPEARANCE");
uint32 Hair, Color, FacialHair, SkinColor;
recvData >> Hair >> Color >> FacialHair >> SkinColor;
BarberShopStyleEntry const* bs_hair = sBarberShopStyleStore.LookupEntry(Hair);
if (!bs_hair || bs_hair->type != 0 || bs_hair->race != _player->getRace() || bs_hair->gender != _player->getGender())
return;
BarberShopStyleEntry const* bs_facialHair = sBarberShopStyleStore.LookupEntry(FacialHair);
if (!bs_facialHair || bs_facialHair->type != 2 || bs_facialHair->race != _player->getRace() || bs_facialHair->gender != _player->getGender())
return;
BarberShopStyleEntry const* bs_skinColor = sBarberShopStyleStore.LookupEntry(SkinColor);
if (bs_skinColor && (bs_skinColor->type != 3 || bs_skinColor->race != _player->getRace() || bs_skinColor->gender != _player->getGender()))
return;
if (!Player::ValidateAppearance(_player->getRace(), _player->getClass(), _player->getGender(), bs_hair->hair_id, Color, uint8(_player->GetUInt32Value(PLAYER_FLAGS) >> 8), bs_facialHair->hair_id, bs_skinColor ? bs_skinColor->hair_id : 0))
return;
GameObject* go = _player->FindNearestGameObjectOfType(GAMEOBJECT_TYPE_BARBER_CHAIR, 5.0f);
if (!go)
{
SendBarberShopResult(BARBER_SHOP_RESULT_NOT_ON_CHAIR);
return;
}
if (_player->getStandState() != UNIT_STAND_STATE_SIT_LOW_CHAIR + go->GetGOInfo()->barberChair.chairheight)
{
SendBarberShopResult(BARBER_SHOP_RESULT_NOT_ON_CHAIR);
return;
}
uint32 cost = _player->GetBarberShopCost(bs_hair->hair_id, Color, bs_facialHair->hair_id, bs_skinColor);
// 0 - ok
// 1, 3 - not enough money
// 2 - you have to seat on barber chair
if (!_player->HasEnoughMoney(cost))
{
SendBarberShopResult(BARBER_SHOP_RESULT_NO_MONEY);
return;
}
SendBarberShopResult(BARBER_SHOP_RESULT_SUCCESS);
_player->ModifyMoney(-int32(cost)); // it isn't free
_player->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_AT_BARBER, cost);
_player->SetByteValue(PLAYER_BYTES, 2, uint8(bs_hair->hair_id));
_player->SetByteValue(PLAYER_BYTES, 3, uint8(Color));
_player->SetByteValue(PLAYER_BYTES_2, 0, uint8(bs_facialHair->hair_id));
if (bs_skinColor)
_player->SetByteValue(PLAYER_BYTES, 0, uint8(bs_skinColor->hair_id));
_player->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_VISIT_BARBER_SHOP, 1);
_player->SetStandState(0); // stand up
}
void WorldSession::HandleRemoveGlyph(WorldPacket& recvData)
{
uint32 slot;
recvData >> slot;
if (slot >= MAX_GLYPH_SLOT_INDEX)
{
TC_LOG_DEBUG("network", "Client sent wrong glyph slot number in opcode CMSG_REMOVE_GLYPH %u", slot);
return;
}
if (uint32 glyph = _player->GetGlyph(slot))
{
if (GlyphPropertiesEntry const* gp = sGlyphPropertiesStore.LookupEntry(glyph))
{
_player->RemoveAurasDueToSpell(gp->SpellId);
_player->SetGlyph(slot, 0);
_player->SendTalentsInfoData(false);
}
}
}
void WorldSession::HandleCharCustomize(WorldPacket& recvData)
{
CharacterCustomizeInfo customizeInfo;
recvData >> customizeInfo.Guid;
if (!IsLegitCharacterForAccount(customizeInfo.Guid))
{
TC_LOG_ERROR("network", "Account %u, IP: %s tried to customise %s, but it does not belong to their account!",
GetAccountId(), GetRemoteAddress().c_str(), customizeInfo.Guid.ToString().c_str());
recvData.rfinish();
KickPlayer();
return;
}
recvData >> customizeInfo.Name
>> customizeInfo.Gender
>> customizeInfo.Skin
>> customizeInfo.HairColor
>> customizeInfo.HairStyle
>> customizeInfo.FacialHair
>> customizeInfo.Face;
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_NAME_DATA);
stmt->setUInt32(0, customizeInfo.Guid.GetCounter());
PreparedQueryResult result = CharacterDatabase.Query(stmt);
if (!result)
{
SendCharCustomize(CHAR_CREATE_ERROR, customizeInfo);
return;
}
Field* fields = result->Fetch();
uint8 plrRace = fields[0].GetUInt8();
uint8 plrClass = fields[1].GetUInt8();
uint8 plrGender = fields[2].GetUInt8();
if (!Player::ValidateAppearance(plrRace, plrClass, plrGender, customizeInfo.HairStyle, customizeInfo.HairColor, customizeInfo.Face, customizeInfo.FacialHair, customizeInfo.Skin, true))
{
SendCharCustomize(CHAR_CREATE_ERROR, customizeInfo);
return;
}
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_AT_LOGIN);
stmt->setUInt32(0, customizeInfo.Guid.GetCounter());
// TODO: Make async with callback
result = CharacterDatabase.Query(stmt);
if (!result)
{
SendCharCustomize(CHAR_CREATE_ERROR, customizeInfo);
return;
}
fields = result->Fetch();
uint32 at_loginFlags = fields[0].GetUInt16();
if (!(at_loginFlags & AT_LOGIN_CUSTOMIZE))
{
SendCharCustomize(CHAR_CREATE_ERROR, customizeInfo);
return;
}
// prevent character rename to invalid name
if (!normalizePlayerName(customizeInfo.Name))
{
SendCharCustomize(CHAR_NAME_NO_NAME, customizeInfo);
return;
}
ResponseCodes res = ObjectMgr::CheckPlayerName(customizeInfo.Name, true);
if (res != CHAR_NAME_SUCCESS)
{
SendCharCustomize(res, customizeInfo);
return;
}
// check name limitations
if (!HasPermission(rbac::RBAC_PERM_SKIP_CHECK_CHARACTER_CREATION_RESERVEDNAME) && sObjectMgr->IsReservedName(customizeInfo.Name))
{
SendCharCustomize(CHAR_NAME_RESERVED, customizeInfo);
return;
}
// character with this name already exist
if (ObjectGuid newGuid = sObjectMgr->GetPlayerGUIDByName(customizeInfo.Name))
{
if (newGuid != customizeInfo.Guid)
{
SendCharCustomize(CHAR_CREATE_NAME_IN_USE, customizeInfo);
return;
}
}
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_NAME);
stmt->setUInt32(0, customizeInfo.Guid.GetCounter());
result = CharacterDatabase.Query(stmt);
if (result)
{
std::string oldname = result->Fetch()[0].GetString();
TC_LOG_INFO("entities.player.character", "Account: %d (IP: %s), Character[%s] (%s) Customized to: %s",
GetAccountId(), GetRemoteAddress().c_str(), oldname.c_str(), customizeInfo.Guid.ToString().c_str(), customizeInfo.Name.c_str());
}
SQLTransaction trans = CharacterDatabase.BeginTransaction();
Player::Customize(&customizeInfo, trans);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_NAME_AT_LOGIN);
stmt->setString(0, customizeInfo.Name);
stmt->setUInt16(1, uint16(AT_LOGIN_CUSTOMIZE));
stmt->setUInt32(2, customizeInfo.Guid.GetCounter());
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_DECLINED_NAME);
stmt->setUInt32(0, customizeInfo.Guid.GetCounter());
trans->Append(stmt);
CharacterDatabase.CommitTransaction(trans);
sWorld->UpdateCharacterNameData(customizeInfo.Guid, customizeInfo.Name, customizeInfo.Gender);
SendCharCustomize(RESPONSE_SUCCESS, customizeInfo);
}
void WorldSession::HandleEquipmentSetSave(WorldPacket& recvData)
{
TC_LOG_DEBUG("network", "CMSG_EQUIPMENT_SET_SAVE");
uint64 setGuid;
recvData.readPackGUID(setGuid);
uint32 index;
recvData >> index;
if (index >= MAX_EQUIPMENT_SET_INDEX) // client set slots amount
return;
std::string name;
recvData >> name;
std::string iconName;
recvData >> iconName;
EquipmentSet eqSet;
eqSet.Guid = setGuid;
eqSet.Name = name;
eqSet.IconName = iconName;
eqSet.state = EQUIPMENT_SET_NEW;
for (uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
{
ObjectGuid itemGuid;
recvData >> itemGuid.ReadAsPacked();
// equipment manager sends "1" (as raw GUID) for slots set to "ignore" (don't touch slot at equip set)
if (itemGuid.GetRawValue() == 1)
{
// ignored slots saved as bit mask because we have no free special values for Items[i]
eqSet.IgnoreMask |= 1 << i;
continue;
}
Item* item = _player->GetItemByPos(INVENTORY_SLOT_BAG_0, i);
if (!item && itemGuid) // cheating check 1
return;
if (item && item->GetGUID() != itemGuid) // cheating check 2
return;
eqSet.Items[i] = itemGuid.GetCounter();
}
_player->SetEquipmentSet(index, eqSet);
}
void WorldSession::HandleEquipmentSetDelete(WorldPacket& recvData)
{
TC_LOG_DEBUG("network", "CMSG_EQUIPMENT_SET_DELETE");
uint64 setGuid;
recvData.readPackGUID(setGuid);
_player->DeleteEquipmentSet(setGuid);
}
void WorldSession::HandleEquipmentSetUse(WorldPacket& recvData)
{
TC_LOG_DEBUG("network", "CMSG_EQUIPMENT_SET_USE");
for (uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
{
ObjectGuid itemGuid;
recvData >> itemGuid.ReadAsPacked();
uint8 srcbag, srcslot;
recvData >> srcbag >> srcslot;
TC_LOG_DEBUG("entities.player.items", "%s: srcbag %u, srcslot %u", itemGuid.ToString().c_str(), srcbag, srcslot);
// check if item slot is set to "ignored" (raw value == 1), must not be unequipped then
if (itemGuid.GetRawValue() == 1)
continue;
// Only equip weapons in combat
if (_player->IsInCombat() && i != EQUIPMENT_SLOT_MAINHAND && i != EQUIPMENT_SLOT_OFFHAND && i != EQUIPMENT_SLOT_RANGED)
continue;
Item* item = _player->GetItemByGuid(itemGuid);
uint16 dstpos = i | (INVENTORY_SLOT_BAG_0 << 8);
if (!item)
{
Item* uItem = _player->GetItemByPos(INVENTORY_SLOT_BAG_0, i);
if (!uItem)
continue;
ItemPosCountVec sDest;
InventoryResult msg = _player->CanStoreItem(NULL_BAG, NULL_SLOT, sDest, uItem, false);
if (msg == EQUIP_ERR_OK)
{
_player->RemoveItem(INVENTORY_SLOT_BAG_0, i, true);
_player->StoreItem(sDest, uItem, true);
}
else
_player->SendEquipError(msg, uItem, NULL);
continue;
}
if (item->GetPos() == dstpos)
continue;
_player->SwapItem(item->GetPos(), dstpos);
}
WorldPacket data(SMSG_EQUIPMENT_SET_USE_RESULT, 1);
data << uint8(0); // 4 - equipment swap failed - inventory is full
SendPacket(&data);
}
void WorldSession::HandleCharFactionOrRaceChange(WorldPacket& recvData)
{
CharacterFactionChangeInfo factionChangeInfo;
recvData >> factionChangeInfo.Guid;
if (!IsLegitCharacterForAccount(factionChangeInfo.Guid))
{
TC_LOG_ERROR("network", "Account %u, IP: %s tried to factionchange character %s, but it does not belong to their account!",
GetAccountId(), GetRemoteAddress().c_str(), factionChangeInfo.Guid.ToString().c_str());
recvData.rfinish();
KickPlayer();
return;
}
recvData >> factionChangeInfo.Name
>> factionChangeInfo.Gender
>> factionChangeInfo.Skin
>> factionChangeInfo.HairColor
>> factionChangeInfo.HairStyle
>> factionChangeInfo.FacialHair
>> factionChangeInfo.Face
>> factionChangeInfo.Race;
uint32 lowGuid = factionChangeInfo.Guid.GetCounter();
// get the players old (at this moment current) race
CharacterNameData const* nameData = sWorld->GetCharacterNameData(factionChangeInfo.Guid);
if (!nameData)
{
SendCharFactionChange(CHAR_CREATE_ERROR, factionChangeInfo);
return;
}
uint8 oldRace = nameData->m_race;
uint8 playerClass = nameData->m_class;
uint8 level = nameData->m_level;
// TO Do: Make async
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_AT_LOGIN_TITLES);
stmt->setUInt32(0, lowGuid);
PreparedQueryResult result = CharacterDatabase.Query(stmt);
if (!result)
{
SendCharFactionChange(CHAR_CREATE_ERROR, factionChangeInfo);
return;
}
Field* fields = result->Fetch();
uint32 at_loginFlags = fields[0].GetUInt16();
std::string knownTitlesStr = fields[1].GetString();
uint32 used_loginFlag = ((recvData.GetOpcode() == CMSG_CHAR_RACE_CHANGE) ? AT_LOGIN_CHANGE_RACE : AT_LOGIN_CHANGE_FACTION);
if (!sObjectMgr->GetPlayerInfo(factionChangeInfo.Race, playerClass))
{
SendCharFactionChange(CHAR_CREATE_ERROR, factionChangeInfo);
return;
}
if (!(at_loginFlags & used_loginFlag))
{
SendCharFactionChange(CHAR_CREATE_ERROR, factionChangeInfo);
return;
}
if (!HasPermission(rbac::RBAC_PERM_SKIP_CHECK_CHARACTER_CREATION_RACEMASK))
{
uint32 raceMaskDisabled = sWorld->getIntConfig(CONFIG_CHARACTER_CREATING_DISABLED_RACEMASK);
if ((1 << (factionChangeInfo.Race - 1)) & raceMaskDisabled)
{
SendCharFactionChange(CHAR_CREATE_ERROR, factionChangeInfo);
return;
}
}
// prevent character rename to invalid name
if (!normalizePlayerName(factionChangeInfo.Name))
{
SendCharFactionChange(CHAR_NAME_NO_NAME, factionChangeInfo);
return;
}
ResponseCodes res = ObjectMgr::CheckPlayerName(factionChangeInfo.Name, true);
if (res != CHAR_NAME_SUCCESS)
{
SendCharFactionChange(res, factionChangeInfo);
return;
}
// check name limitations
if (!HasPermission(rbac::RBAC_PERM_SKIP_CHECK_CHARACTER_CREATION_RESERVEDNAME) && sObjectMgr->IsReservedName(factionChangeInfo.Name))
{
SendCharFactionChange(CHAR_NAME_RESERVED, factionChangeInfo);
return;
}
// character with this name already exist
if (ObjectGuid newGuid = sObjectMgr->GetPlayerGUIDByName(factionChangeInfo.Name))
{
if (newGuid != factionChangeInfo.Guid)
{
SendCharFactionChange(CHAR_CREATE_NAME_IN_USE, factionChangeInfo);
return;
}
}
// resurrect the character in case he's dead
sObjectAccessor->ConvertCorpseForPlayer(factionChangeInfo.Guid);
SQLTransaction trans = CharacterDatabase.BeginTransaction();
CharacterDatabase.EscapeString(factionChangeInfo.Name);
Player::Customize(&factionChangeInfo, trans);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_FACTION_OR_RACE);
stmt->setString(0, factionChangeInfo.Name);
stmt->setUInt8(1, factionChangeInfo.Race);
stmt->setUInt16(2, used_loginFlag);
stmt->setUInt32(3, lowGuid);
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_DECLINED_NAME);
stmt->setUInt32(0, lowGuid);
trans->Append(stmt);
sWorld->UpdateCharacterNameData(factionChangeInfo.Guid, factionChangeInfo.Name, factionChangeInfo.Gender, factionChangeInfo.Race);
if (oldRace != factionChangeInfo.Race)
{
TeamId team = TEAM_ALLIANCE;
// Search each faction is targeted
switch (factionChangeInfo.Race)
{
case RACE_ORC:
case RACE_TAUREN:
case RACE_UNDEAD_PLAYER:
case RACE_TROLL:
case RACE_BLOODELF:
team = TEAM_HORDE;
break;
default:
break;
}
// Switch Languages
// delete all languages first
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_SKILL_LANGUAGES);
stmt->setUInt32(0, lowGuid);
trans->Append(stmt);
// Now add them back
stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHAR_SKILL_LANGUAGE);
stmt->setUInt32(0, lowGuid);
// Faction specific languages
if (team == TEAM_HORDE)
stmt->setUInt16(1, 109);
else
stmt->setUInt16(1, 98);
trans->Append(stmt);
// Race specific languages
if (factionChangeInfo.Race != RACE_ORC && factionChangeInfo.Race != RACE_HUMAN)
{
stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHAR_SKILL_LANGUAGE);
stmt->setUInt32(0, lowGuid);
switch (factionChangeInfo.Race)
{
case RACE_DWARF:
stmt->setUInt16(1, 111);
break;
case RACE_DRAENEI:
stmt->setUInt16(1, 759);
break;
case RACE_GNOME:
stmt->setUInt16(1, 313);
break;
case RACE_NIGHTELF:
stmt->setUInt16(1, 113);
break;
case RACE_UNDEAD_PLAYER:
stmt->setUInt16(1, 673);
break;
case RACE_TAUREN:
stmt->setUInt16(1, 115);
break;
case RACE_TROLL:
stmt->setUInt16(1, 315);
break;
case RACE_BLOODELF:
stmt->setUInt16(1, 137);
break;
}
trans->Append(stmt);
}
if (recvData.GetOpcode() == CMSG_CHAR_FACTION_CHANGE)
{
// Delete all Flypaths
stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_TAXI_PATH);
stmt->setUInt32(0, lowGuid);
trans->Append(stmt);
if (level > 7)
{
// Update Taxi path
// this doesn't seem to be 100% blizzlike... but it can't really be helped.
std::ostringstream taximaskstream;
uint32 numFullTaximasks = level / 7;
if (numFullTaximasks > 11)
numFullTaximasks = 11;
if (team == TEAM_ALLIANCE)
{
if (playerClass != CLASS_DEATH_KNIGHT)
{
for (uint8 i = 0; i < numFullTaximasks; ++i)
taximaskstream << uint32(sAllianceTaxiNodesMask[i]) << ' ';
}
else
{
for (uint8 i = 0; i < numFullTaximasks; ++i)
taximaskstream << uint32(sAllianceTaxiNodesMask[i] | sDeathKnightTaxiNodesMask[i]) << ' ';
}
}
else
{
if (playerClass != CLASS_DEATH_KNIGHT)
{
for (uint8 i = 0; i < numFullTaximasks; ++i)
taximaskstream << uint32(sHordeTaxiNodesMask[i]) << ' ';
}
else
{
for (uint8 i = 0; i < numFullTaximasks; ++i)
taximaskstream << uint32(sHordeTaxiNodesMask[i] | sDeathKnightTaxiNodesMask[i]) << ' ';
}
}
uint32 numEmptyTaximasks = 11 - numFullTaximasks;
for (uint8 i = 0; i < numEmptyTaximasks; ++i)
taximaskstream << "0 ";
taximaskstream << '0';
std::string taximask = taximaskstream.str();
stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_TAXIMASK);
stmt->setString(0, taximask);
stmt->setUInt32(1, lowGuid);
trans->Append(stmt);
}
if (!sWorld->getBoolConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_GUILD))
{
// Reset guild
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_GUILD_MEMBER);
stmt->setUInt32(0, lowGuid);
PreparedQueryResult result = CharacterDatabase.Query(stmt);
if (result)
if (Guild* guild = sGuildMgr->GetGuildById((result->Fetch()[0]).GetUInt32()))
guild->DeleteMember(factionChangeInfo.Guid, false, false, true);
Player::LeaveAllArenaTeams(factionChangeInfo.Guid);
}
if (!HasPermission(rbac::RBAC_PERM_TWO_SIDE_ADD_FRIEND))
{
// Delete Friend List
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_SOCIAL_BY_GUID);
stmt->setUInt32(0, lowGuid);
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_SOCIAL_BY_FRIEND);
stmt->setUInt32(0, lowGuid);
trans->Append(stmt);
}
// Reset homebind and position
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_PLAYER_HOMEBIND);
stmt->setUInt32(0, lowGuid);
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_PLAYER_HOMEBIND);
stmt->setUInt32(0, lowGuid);
WorldLocation loc;
uint16 zoneId = 0;
if (team == TEAM_ALLIANCE)
{
loc.WorldRelocate(0, -8867.68f, 673.373f, 97.9034f, 0.0f);
zoneId = 1519;
}
else
{
loc.WorldRelocate(1, 1633.33f, -4439.11f, 15.7588f, 0.0f);
zoneId = 1637;
}
stmt->setUInt16(1, loc.GetMapId());
stmt->setUInt16(2, zoneId);
stmt->setFloat(3, loc.GetPositionX());
stmt->setFloat(4, loc.GetPositionY());
stmt->setFloat(5, loc.GetPositionZ());
trans->Append(stmt);
Player::SavePositionInDB(loc, zoneId, factionChangeInfo.Guid, trans);
// Achievement conversion
for (std::map<uint32, uint32>::const_iterator it = sObjectMgr->FactionChangeAchievements.begin(); it != sObjectMgr->FactionChangeAchievements.end(); ++it)
{
uint32 achiev_alliance = it->first;
uint32 achiev_horde = it->second;
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_ACHIEVEMENT_BY_ACHIEVEMENT);
stmt->setUInt16(0, uint16(team == TEAM_ALLIANCE ? achiev_alliance : achiev_horde));
stmt->setUInt32(1, lowGuid);
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_ACHIEVEMENT);
stmt->setUInt16(0, uint16(team == TEAM_ALLIANCE ? achiev_alliance : achiev_horde));
stmt->setUInt16(1, uint16(team == TEAM_ALLIANCE ? achiev_horde : achiev_alliance));
stmt->setUInt32(2, lowGuid);
trans->Append(stmt);
}
// Item conversion
for (std::map<uint32, uint32>::const_iterator it = sObjectMgr->FactionChangeItems.begin(); it != sObjectMgr->FactionChangeItems.end(); ++it)
{
uint32 item_alliance = it->first;
uint32 item_horde = it->second;
stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_INVENTORY_FACTION_CHANGE);
stmt->setUInt32(0, (team == TEAM_ALLIANCE ? item_alliance : item_horde));
stmt->setUInt32(1, (team == TEAM_ALLIANCE ? item_horde : item_alliance));
stmt->setUInt32(2, lowGuid);
trans->Append(stmt);
}
// Delete all current quests
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_QUESTSTATUS);
stmt->setUInt32(0, lowGuid);
trans->Append(stmt);
// Quest conversion
for (std::map<uint32, uint32>::const_iterator it = sObjectMgr->FactionChangeQuests.begin(); it != sObjectMgr->FactionChangeQuests.end(); ++it)
{
uint32 quest_alliance = it->first;
uint32 quest_horde = it->second;
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_QUESTSTATUS_REWARDED_BY_QUEST);
stmt->setUInt32(0, lowGuid);
stmt->setUInt32(1, (team == TEAM_ALLIANCE ? quest_alliance : quest_horde));
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_QUESTSTATUS_REWARDED_FACTION_CHANGE);
stmt->setUInt32(0, (team == TEAM_ALLIANCE ? quest_alliance : quest_horde));
stmt->setUInt32(1, (team == TEAM_ALLIANCE ? quest_horde : quest_alliance));
stmt->setUInt32(2, lowGuid);
trans->Append(stmt);
}
// Mark all rewarded quests as "active" (will count for completed quests achievements)
stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_QUESTSTATUS_REWARDED_ACTIVE);
stmt->setUInt32(0, lowGuid);
trans->Append(stmt);
// Disable all old-faction specific quests
{
ObjectMgr::QuestMap const& questTemplates = sObjectMgr->GetQuestTemplates();
for (ObjectMgr::QuestMap::const_iterator iter = questTemplates.begin(); iter != questTemplates.end(); ++iter)
{
Quest const* quest = iter->second;
uint32 newRaceMask = (team == TEAM_ALLIANCE) ? RACEMASK_ALLIANCE : RACEMASK_HORDE;
if (!(quest->GetRequiredRaces() & newRaceMask))
{
stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_QUESTSTATUS_REWARDED_ACTIVE_BY_QUEST);
stmt->setUInt32(0, lowGuid);
stmt->setUInt32(1, quest->GetQuestId());
trans->Append(stmt);
}
}
}
// Spell conversion
for (std::map<uint32, uint32>::const_iterator it = sObjectMgr->FactionChangeSpells.begin(); it != sObjectMgr->FactionChangeSpells.end(); ++it)
{
uint32 spell_alliance = it->first;
uint32 spell_horde = it->second;
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_SPELL_BY_SPELL);
stmt->setUInt32(0, (team == TEAM_ALLIANCE ? spell_alliance : spell_horde));
stmt->setUInt32(1, lowGuid);
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_SPELL_FACTION_CHANGE);
stmt->setUInt32(0, (team == TEAM_ALLIANCE ? spell_alliance : spell_horde));
stmt->setUInt32(1, (team == TEAM_ALLIANCE ? spell_horde : spell_alliance));
stmt->setUInt32(2, lowGuid);
trans->Append(stmt);
}
// Reputation conversion
for (std::map<uint32, uint32>::const_iterator it = sObjectMgr->FactionChangeReputation.begin(); it != sObjectMgr->FactionChangeReputation.end(); ++it)
{
uint32 reputation_alliance = it->first;
uint32 reputation_horde = it->second;
uint32 newReputation = (team == TEAM_ALLIANCE) ? reputation_alliance : reputation_horde;
uint32 oldReputation = (team == TEAM_ALLIANCE) ? reputation_horde : reputation_alliance;
// select old standing set in db
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_REP_BY_FACTION);
stmt->setUInt32(0, oldReputation);
stmt->setUInt32(1, lowGuid);
if (PreparedQueryResult result = CharacterDatabase.Query(stmt))
{
Field* fields = result->Fetch();
int32 oldDBRep = fields[0].GetInt32();
FactionEntry const* factionEntry = sFactionStore.LookupEntry(oldReputation);
// old base reputation
int32 oldBaseRep = sObjectMgr->GetBaseReputationOf(factionEntry, oldRace, playerClass);
// new base reputation
int32 newBaseRep = sObjectMgr->GetBaseReputationOf(sFactionStore.LookupEntry(newReputation), factionChangeInfo.Race, playerClass);
// final reputation shouldnt change
int32 FinalRep = oldDBRep + oldBaseRep;
int32 newDBRep = FinalRep - newBaseRep;
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_REP_BY_FACTION);
stmt->setUInt32(0, newReputation);
stmt->setUInt32(1, lowGuid);
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_REP_FACTION_CHANGE);
stmt->setUInt16(0, uint16(newReputation));
stmt->setInt32(1, newDBRep);
stmt->setUInt16(2, uint16(oldReputation));
stmt->setUInt32(3, lowGuid);
trans->Append(stmt);
}
}
// Title conversion
if (!knownTitlesStr.empty())
{
const uint32 ktcount = KNOWN_TITLES_SIZE * 2;
uint32 knownTitles[ktcount];
Tokenizer tokens(knownTitlesStr, ' ', ktcount);
if (tokens.size() != ktcount)
{
SendCharFactionChange(CHAR_CREATE_ERROR, factionChangeInfo);
return;
}
for (uint32 index = 0; index < ktcount; ++index)
knownTitles[index] = atoul(tokens[index]);
for (std::map<uint32, uint32>::const_iterator it = sObjectMgr->FactionChangeTitles.begin(); it != sObjectMgr->FactionChangeTitles.end(); ++it)
{
uint32 title_alliance = it->first;
uint32 title_horde = it->second;
CharTitlesEntry const* atitleInfo = sCharTitlesStore.LookupEntry(title_alliance);
CharTitlesEntry const* htitleInfo = sCharTitlesStore.LookupEntry(title_horde);
// new team
if (team == TEAM_ALLIANCE)
{
uint32 bitIndex = htitleInfo->bit_index;
uint32 index = bitIndex / 32;
uint32 old_flag = 1 << (bitIndex % 32);
uint32 new_flag = 1 << (atitleInfo->bit_index % 32);
if (knownTitles[index] & old_flag)
{
knownTitles[index] &= ~old_flag;
// use index of the new title
knownTitles[atitleInfo->bit_index / 32] |= new_flag;
}
}
else
{
uint32 bitIndex = atitleInfo->bit_index;
uint32 index = bitIndex / 32;
uint32 old_flag = 1 << (bitIndex % 32);
uint32 new_flag = 1 << (htitleInfo->bit_index % 32);
if (knownTitles[index] & old_flag)
{
knownTitles[index] &= ~old_flag;
// use index of the new title
knownTitles[htitleInfo->bit_index / 32] |= new_flag;
}
}
std::ostringstream ss;
for (uint32 index = 0; index < ktcount; ++index)
ss << knownTitles[index] << ' ';
stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_TITLES_FACTION_CHANGE);
stmt->setString(0, ss.str().c_str());
stmt->setUInt32(1, lowGuid);
trans->Append(stmt);
// unset any currently chosen title
stmt = CharacterDatabase.GetPreparedStatement(CHAR_RES_CHAR_TITLES_FACTION_CHANGE);
stmt->setUInt32(0, lowGuid);
trans->Append(stmt);
}
}
}
}
CharacterDatabase.CommitTransaction(trans);
TC_LOG_DEBUG("entities.player", "%s (IP: %s) changed race from %u to %u", GetPlayerInfo().c_str(), GetRemoteAddress().c_str(), oldRace, factionChangeInfo.Race);
SendCharFactionChange(RESPONSE_SUCCESS, factionChangeInfo);
}
void WorldSession::SendCharCreate(ResponseCodes result)
{
WorldPacket data(SMSG_CHAR_CREATE, 1);
data << uint8(result);
SendPacket(&data);
}
void WorldSession::SendCharDelete(ResponseCodes result)
{
WorldPacket data(SMSG_CHAR_DELETE, 1);
data << uint8(result);
SendPacket(&data);
}
void WorldSession::SendCharRename(ResponseCodes result, CharacterRenameInfo const& renameInfo)
{
WorldPacket data(SMSG_CHAR_RENAME, 1 + 8 + renameInfo.Name.size() + 1);
data << uint8(result);
if (result == RESPONSE_SUCCESS)
{
data << renameInfo.Guid;
data << renameInfo.Name;
}
SendPacket(&data);
}
void WorldSession::SendCharCustomize(ResponseCodes result, CharacterCustomizeInfo const& customizeInfo)
{
WorldPacket data(SMSG_CHAR_CUSTOMIZE, 1 + 8 + customizeInfo.Name.size() + 1 + 6);
data << uint8(result);
if (result == RESPONSE_SUCCESS)
{
data << customizeInfo.Guid;
data << customizeInfo.Name;
data << uint8(customizeInfo.Gender);
data << uint8(customizeInfo.Skin);
data << uint8(customizeInfo.Face);
data << uint8(customizeInfo.HairStyle);
data << uint8(customizeInfo.HairColor);
data << uint8(customizeInfo.FacialHair);
}
SendPacket(&data);
}
void WorldSession::SendCharFactionChange(ResponseCodes result, CharacterFactionChangeInfo const& factionChangeInfo)
{
WorldPacket data(SMSG_CHAR_FACTION_CHANGE, 1 + 8 + factionChangeInfo.Name.size() + 1 + 7);
data << uint8(result);
if (result == RESPONSE_SUCCESS)
{
data << factionChangeInfo.Guid;
data << factionChangeInfo.Name;
data << uint8(factionChangeInfo.Gender);
data << uint8(factionChangeInfo.Skin);
data << uint8(factionChangeInfo.Face);
data << uint8(factionChangeInfo.HairStyle);
data << uint8(factionChangeInfo.HairColor);
data << uint8(factionChangeInfo.FacialHair);
data << uint8(factionChangeInfo.Race);
}
SendPacket(&data);
}
void WorldSession::SendSetPlayerDeclinedNamesResult(DeclinedNameResult result, ObjectGuid guid)
{
WorldPacket data(SMSG_SET_PLAYER_DECLINED_NAMES_RESULT, 4 + 8);
data << uint32(result);
data << guid;
SendPacket(&data);
}
void WorldSession::SendBarberShopResult(BarberShopResult result)
{
WorldPacket data(SMSG_BARBER_SHOP_RESULT, 4);
data << uint32(result);
SendPacket(&data);
}
| Rastrian/ElunaTrinityWotlk | src/server/game/Handlers/CharacterHandler.cpp | C++ | gpl-2.0 | 80,672 |
# time-of-flight
| richard-doyle/time-of-flight | README.md | Markdown | gpl-2.0 | 17 |
#pragma once
/*
* Copyright (C) 2012 Team XBMC
* http://www.xbmc.org
*
* This Program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with XBMC; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
#include "FileItem.h"
#include "PVRChannelGroup.h"
#include "threads/CriticalSection.h"
namespace PVR
{
/** A container class for channel groups */
class CPVRChannelGroups
{
public:
/*!
* @brief Create a new group container.
* @param bRadio True if this is a container for radio channels, false if it is for tv channels.
*/
CPVRChannelGroups(bool bRadio);
virtual ~CPVRChannelGroups(void);
/*!
* @brief Remove all channels from this group.
*/
void Clear(void);
/*!
* @brief Load this container's contents from the database or PVR clients.
* @return True if it was loaded successfully, false if not.
*/
bool Load(void);
/*!
* @return Amount of groups in this container
*/
int Size(void) const { CSingleLock lock(m_critSection); return m_groups.size(); }
/*!
* @brief Update a group or add it if it's not in here yet.
* @param group The group to update.
* @param bSaveInDb True to save the changes in the db.
* @return True if the group was added or update successfully, false otherwise.
*/
bool Update(const CPVRChannelGroup &group, bool bSaveInDb = false);
/*!
* @brief Called by the add-on callback to add a new group
* @param group The group to add
* @return True when updated, false otherwise
*/
bool UpdateFromClient(const CPVRChannelGroup &group) { return Update(group, false); }
/*!
* @brief Get a channel given it's path
* @param strPath The path to the channel
* @return The channel, or an empty fileitem when not found
*/
CFileItemPtr GetByPath(const CStdString &strPath) const;
/*!
* @brief Get a pointer to a channel group given it's ID.
* @param iGroupId The ID of the group.
* @return The group or NULL if it wasn't found.
*/
CPVRChannelGroupPtr GetById(int iGroupId) const;
/*!
* @brief Get a group given it's name.
* @param strName The name.
* @return The group or NULL if it wan't found.
*/
CPVRChannelGroupPtr GetByName(const CStdString &strName) const;
/*!
* @brief Get the group that contains all channels.
* @return The group that contains all channels.
*/
CPVRChannelGroupPtr GetGroupAll(void) const;
/*!
* @brief Get the list of groups.
* @param results The file list to store the results in.
* @return The amount of items that were added.
*/
int GetGroupList(CFileItemList* results) const;
/*!
* @brief Get the previous group in this container.
* @param group The current group.
* @return The previous group or the group containing all channels if it wasn't found.
*/
CPVRChannelGroupPtr GetPreviousGroup(const CPVRChannelGroup &group) const;
/*!
* @brief Get the next group in this container.
* @param group The current group.
* @return The next group or the group containing all channels if it wasn't found.
*/
CPVRChannelGroupPtr GetNextGroup(const CPVRChannelGroup &group) const;
/*!
* @brief Get the group that is currently selected in the UI.
* @return The selected group.
*/
CPVRChannelGroupPtr GetSelectedGroup(void) const;
/*!
* @brief Change the selected group.
* @param group The group to select.
*/
void SetSelectedGroup(CPVRChannelGroupPtr group);
/*!
* @brief Add a group to this container.
* @param strName The name of the group.
* @return True if the group was added, false otherwise.
*/
bool AddGroup(const CStdString &strName);
/*!
* @brief Delete a group in this container.
* @param group The group to delete.
* @return True if it was deleted successfully, false if not.
*/
bool DeleteGroup(const CPVRChannelGroup &group);
/*!
* @brief Remove a channel from all non-system groups.
* @param channel The channel to remove.
*/
void RemoveFromAllGroups(const CPVRChannel &channel);
/*!
* @brief Persist all changes in channel groups.
* @return True if everything was persisted, false otherwise.
*/
bool PersistAll(void);
/*!
* @return True when this container contains radio groups, false otherwise
*/
bool IsRadio(void) const { return m_bRadio; }
/*!
* @brief Call by a guiwindow/dialog to add the groups to a control
* @param iWindowId The window to add the groups to.
* @param iControlId The control to add the groups to
*/
void FillGroupsGUI(int iWindowId, int iControlId) const;
/*!
* @brief Update the contents of the groups in this container.
* @param bChannelsOnly Set to true to only update channels, not the groups themselves.
* @return True if the update was successful, false otherwise.
*/
bool Update(bool bChannelsOnly = false);
private:
bool UpdateGroupsEntries(const CPVRChannelGroups &groups);
bool LoadUserDefinedChannelGroups(void);
bool GetGroupsFromClients(void);
bool m_bRadio; /*!< true if this is a container for radio channels, false if it is for tv channels */
CPVRChannelGroupPtr m_selectedGroup; /*!< the group that's currently selected in the UI */
std::vector<CPVRChannelGroupPtr> m_groups; /*!< the groups in this container */
CCriticalSection m_critSection;
};
}
| herrnst/xbmc-opdenkamp | xbmc/pvr/channels/PVRChannelGroups.h | C | gpl-2.0 | 6,251 |
/*
* Copyright (C) 2008-2011 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Log.h"
#include "ObjectAccessor.h"
#include "CreatureAI.h"
#include "ObjectMgr.h"
#include "TemporarySummon.h"
TempSummon::TempSummon(SummonPropertiesEntry const *properties, Unit *owner) :
Creature(), m_Properties(properties), m_type(TEMPSUMMON_MANUAL_DESPAWN),
m_timer(0), m_lifetime(0)
{
m_summonerGUID = owner ? owner->GetGUID() : 0;
m_unitTypeMask |= UNIT_MASK_SUMMON;
}
Unit* TempSummon::GetSummoner() const
{
return m_summonerGUID ? ObjectAccessor::GetUnit(*this, m_summonerGUID) : NULL;
}
void TempSummon::Update(uint32 diff)
{
Creature::Update(diff);
if (m_deathState == DEAD)
{
UnSummon();
return;
}
switch(m_type)
{
case TEMPSUMMON_MANUAL_DESPAWN:
break;
case TEMPSUMMON_TIMED_DESPAWN:
{
if (m_timer <= diff)
{
UnSummon();
return;
}
m_timer -= diff;
break;
}
case TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT:
{
if (!isInCombat())
{
if (m_timer <= diff)
{
UnSummon();
return;
}
m_timer -= diff;
}
else if (m_timer != m_lifetime)
m_timer = m_lifetime;
break;
}
case TEMPSUMMON_CORPSE_TIMED_DESPAWN:
{
if (m_deathState == CORPSE)
{
if (m_timer <= diff)
{
UnSummon();
return;
}
m_timer -= diff;
}
break;
}
case TEMPSUMMON_CORPSE_DESPAWN:
{
// if m_deathState is DEAD, CORPSE was skipped
if (m_deathState == CORPSE || m_deathState == DEAD)
{
UnSummon();
return;
}
break;
}
case TEMPSUMMON_DEAD_DESPAWN:
{
if (m_deathState == DEAD)
{
UnSummon();
return;
}
break;
}
case TEMPSUMMON_TIMED_OR_CORPSE_DESPAWN:
{
// if m_deathState is DEAD, CORPSE was skipped
if (m_deathState == CORPSE || m_deathState == DEAD)
{
UnSummon();
return;
}
if (!isInCombat())
{
if (m_timer <= diff)
{
UnSummon();
return;
}
else
m_timer -= diff;
}
else if (m_timer != m_lifetime)
m_timer = m_lifetime;
break;
}
case TEMPSUMMON_TIMED_OR_DEAD_DESPAWN:
{
// if m_deathState is DEAD, CORPSE was skipped
if (m_deathState == DEAD)
{
UnSummon();
return;
}
if (!isInCombat() && isAlive())
{
if (m_timer <= diff)
{
UnSummon();
return;
}
else
m_timer -= diff;
}
else if (m_timer != m_lifetime)
m_timer = m_lifetime;
break;
}
default:
UnSummon();
sLog->outError("Temporary summoned creature (entry: %u) have unknown type %u of ", GetEntry(), m_type);
break;
}
}
void TempSummon::InitStats(uint32 duration)
{
ASSERT(!isPet());
m_timer = duration;
m_lifetime = duration;
if (m_type == TEMPSUMMON_MANUAL_DESPAWN)
m_type = (duration == 0) ? TEMPSUMMON_DEAD_DESPAWN : TEMPSUMMON_TIMED_DESPAWN;
Unit *owner = GetSummoner();
if (owner && isTrigger() && m_spells[0])
{
setFaction(owner->getFaction());
SetLevel(owner->getLevel());
if (owner->GetTypeId() == TYPEID_PLAYER)
m_ControlledByPlayer = true;
}
if (!m_Properties)
return;
if (owner)
{
if (uint32 slot = m_Properties->Slot)
{
if (owner->m_SummonSlot[slot] && owner->m_SummonSlot[slot] != GetGUID())
{
Creature *oldSummon = GetMap()->GetCreature(owner->m_SummonSlot[slot]);
if (oldSummon && oldSummon->isSummon())
oldSummon->ToTempSummon()->UnSummon();
}
owner->m_SummonSlot[slot] = GetGUID();
}
}
if (m_Properties->Faction)
setFaction(m_Properties->Faction);
else if (IsVehicle()) // properties should be vehicle
setFaction(owner->getFaction());
}
void TempSummon::InitSummon()
{
Unit* owner = GetSummoner();
if (owner)
{
if (owner->GetTypeId() == TYPEID_UNIT && owner->ToCreature()->IsAIEnabled)
owner->ToCreature()->AI()->JustSummoned(this);
if (IsAIEnabled)
AI()->IsSummonedBy(owner);
}
}
void TempSummon::SetTempSummonType(TempSummonType type)
{
m_type = type;
}
void TempSummon::UnSummon(uint32 msTime)
{
if (msTime)
{
ForcedUnsummonDelayEvent *pEvent = new ForcedUnsummonDelayEvent(*this);
m_Events.AddEvent(pEvent, m_Events.CalculateTime(msTime));
return;
}
//ASSERT(!isPet());
if (isPet())
{
((Pet*)this)->Remove(PET_SAVE_NOT_IN_SLOT);
ASSERT(!IsInWorld());
return;
}
Unit* owner = GetSummoner();
if (owner && owner->GetTypeId() == TYPEID_UNIT && owner->ToCreature()->IsAIEnabled)
owner->ToCreature()->AI()->SummonedCreatureDespawn(this);
if (owner &&
owner->GetTypeId() == TYPEID_PLAYER &&
((Player*)owner)->HaveBot() &&
((Player*)owner)->GetBot()->GetGUID()==this->GetGUID() &&
this->isDead()) { // dont unsummon corpse if a bot
return;
}
AddObjectToRemoveList();
}
bool ForcedUnsummonDelayEvent::Execute(uint64 /*e_time*/, uint32 /*p_time*/)
{
m_owner.UnSummon();
return true;
}
void TempSummon::RemoveFromWorld()
{
if (!IsInWorld())
return;
if (m_Properties)
if (uint32 slot = m_Properties->Slot)
if (Unit* owner = GetSummoner())
if (owner->m_SummonSlot[slot] == GetGUID())
owner->m_SummonSlot[slot] = 0;
//if (GetOwnerGUID())
// sLog->outError("Unit %u has owner guid when removed from world", GetEntry());
Creature::RemoveFromWorld();
}
Minion::Minion(SummonPropertiesEntry const *properties, Unit *owner) : TempSummon(properties, owner)
, m_owner(owner)
{
ASSERT(m_owner);
m_unitTypeMask |= UNIT_MASK_MINION;
m_followAngle = PET_FOLLOW_ANGLE;
}
void Minion::InitStats(uint32 duration)
{
TempSummon::InitStats(duration);
SetReactState(REACT_PASSIVE);
SetCreatorGUID(m_owner->GetGUID());
setFaction(m_owner->getFaction());
m_owner->SetMinion(this, true);
}
void Minion::RemoveFromWorld()
{
if (!IsInWorld())
return;
m_owner->SetMinion(this, false);
TempSummon::RemoveFromWorld();
}
bool Minion::IsGuardianPet() const
{
return isPet() || (m_Properties && m_Properties->Category == SUMMON_CATEGORY_PET);
}
Guardian::Guardian(SummonPropertiesEntry const *properties, Unit *owner) : Minion(properties, owner)
, m_bonusSpellDamage(0)
{
memset(m_statFromOwner, 0, sizeof(float)*MAX_STATS);
m_unitTypeMask |= UNIT_MASK_GUARDIAN;
if (properties && properties->Type == SUMMON_TYPE_PET)
{
m_unitTypeMask |= UNIT_MASK_CONTROLABLE_GUARDIAN;
InitCharmInfo();
}
}
void Guardian::InitStats(uint32 duration)
{
Minion::InitStats(duration);
InitStatsForLevel(m_owner->getLevel());
if (m_owner->GetTypeId() == TYPEID_PLAYER && HasUnitTypeMask(UNIT_MASK_CONTROLABLE_GUARDIAN))
m_charmInfo->InitCharmCreateSpells();
SetReactState(REACT_AGGRESSIVE);
}
void Guardian::InitSummon()
{
TempSummon::InitSummon();
if (m_owner->GetTypeId() == TYPEID_PLAYER
&& m_owner->GetMinionGUID() == GetGUID()
&& !m_owner->GetCharmGUID())
m_owner->ToPlayer()->CharmSpellInitialize();
}
Puppet::Puppet(SummonPropertiesEntry const *properties, Unit *owner) : Minion(properties, owner)
{
ASSERT(owner->GetTypeId() == TYPEID_PLAYER);
m_owner = (Player*)owner;
m_unitTypeMask |= UNIT_MASK_PUPPET;
}
void Puppet::InitStats(uint32 duration)
{
Minion::InitStats(duration);
SetLevel(m_owner->getLevel());
SetReactState(REACT_PASSIVE);
}
void Puppet::InitSummon()
{
Minion::InitSummon();
if (!SetCharmedBy(m_owner, CHARM_TYPE_POSSESS))
ASSERT(false);
}
void Puppet::Update(uint32 time)
{
Minion::Update(time);
//check if caster is channelling?
if (IsInWorld())
{
if (!isAlive())
{
UnSummon();
// TODO: why long distance .die does not remove it
}
}
}
void Puppet::RemoveFromWorld()
{
if (!IsInWorld())
return;
RemoveCharmedBy(NULL);
Minion::RemoveFromWorld();
}
| sucofog/chaoscore | src/server/game/Entities/Creature/TemporarySummon.cpp | C++ | gpl-2.0 | 9,947 |
CREATE TABLE `wp_term_taxonomy` (
`term_taxonomy_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`term_id` bigint(20) unsigned NOT NULL DEFAULT '0',
`taxonomy` varchar(32) NOT NULL DEFAULT '',
`description` longtext NOT NULL,
`parent` bigint(20) unsigned NOT NULL DEFAULT '0',
`count` bigint(20) NOT NULL DEFAULT '0',
PRIMARY KEY (`term_taxonomy_id`),
UNIQUE KEY `term_id_taxonomy` (`term_id`,`taxonomy`),
KEY `taxonomy` (`taxonomy`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 | the-wilhelm/chicagostorage | dbv/data/schema/wp_term_taxonomy.sql | SQL | gpl-2.0 | 489 |
/*! jQuery UI - v1.8.20 - 2012-04-30
* https://github.com/jquery/jquery-ui
* Includes: jquery.effects.transfer.js
* Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */(function(a,b){a.effects.transfer=function(b){return this.queue(function(){var c=a(this),d=a(b.options.to),e=d.offset(),f={top:e.top,left:e.left,height:d.innerHeight(),width:d.innerWidth()},g=c.offset(),h=a('<div class="ui-effects-transfer"></div>').appendTo(document.body).addClass(b.options.className).css({top:g.top,left:g.left,height:c.innerHeight(),width:c.innerWidth(),position:"absolute"}).animate(f,b.duration,b.options.easing,function(){h.remove(),b.callback&&b.callback.apply(c[0],arguments),c.dequeue()})})}})(jQuery); | gustavoguichard/simsimultaneas | wp-includes/js/jquery/jquery.effects.transfer.min-ck.js | JavaScript | gpl-2.0 | 697 |
/*
** Zabbix
** Copyright (C) 2001-2018 Zabbix SIA
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
**/
#ifndef ZABBIX_HISTORY_H
#define ZABBIX_HISTORY_H
#define ZBX_HISTORY_IFACE_SQL 0
#define ZBX_HISTORY_IFACE_ELASTIC 1
typedef struct zbx_history_iface zbx_history_iface_t;
typedef void (*zbx_history_destroy_func_t)(struct zbx_history_iface *hist);
typedef int (*zbx_history_add_values_func_t)(struct zbx_history_iface *hist, const zbx_vector_ptr_t *history);
typedef int (*zbx_history_get_values_func_t)(struct zbx_history_iface *hist, zbx_uint64_t itemid, int start,
int count, int end, zbx_vector_history_record_t *values);
typedef void (*zbx_history_flush_func_t)(struct zbx_history_iface *hist);
struct zbx_history_iface
{
unsigned char value_type;
unsigned char requires_trends;
void *data;
zbx_history_destroy_func_t destroy;
zbx_history_add_values_func_t add_values;
zbx_history_get_values_func_t get_values;
zbx_history_flush_func_t flush;
};
/* SQL hist */
int zbx_history_sql_init(zbx_history_iface_t *hist, unsigned char value_type, char **error);
/* elastic hist */
int zbx_history_elastic_init(zbx_history_iface_t *hist, unsigned char value_type, char **error);
#endif
| zyongqing/okp | src/libs/zbxhistory/history.h | C | gpl-2.0 | 1,884 |
package com.orange.documentare.core.comp.clustering.tasksservice;
/*
* Copyright (c) 2016 Orange
*
* Authors: Christophe Maldivi & Joel Gardes
*
* 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.
*/
import com.orange.documentare.core.comp.clustering.graph.ClusteringParameters;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.fest.assertions.Assertions;
import org.junit.After;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
@Slf4j
public class ClusteringTasksServiceTest {
private static final int NB_TASKS = 4 * 10;
private static final String CLUSTERING_TASK_FILE_PREFIX = "clustering_tasks_";
private static final String STRIPPED_CLUSTERING_JSON = "stripped_clustering.json";
private static final String NOT_STRIPPED_CLUSTERING_JSON = "not_stripped_clustering.json";
private final ClusteringTasksService tasksHandler = ClusteringTasksService.instance();
private final ClusteringParameters parameters = ClusteringParameters.builder().acut().qcut().build();
@After
public void cleanup() {
FileUtils.deleteQuietly(new File(STRIPPED_CLUSTERING_JSON));
FileUtils.deleteQuietly(new File(NOT_STRIPPED_CLUSTERING_JSON));
}
@Test
public void runSeveralDistinctTasks() throws IOException, InterruptedException {
// given
String refJson1 = FileUtils.readFileToString(new File(getClass().getResource("/clusteringtasks/latin1_clustering.ref.json").getFile()));
String refJson2 = FileUtils.readFileToString(new File(getClass().getResource("/clusteringtasks/latin2_clustering.ref.json").getFile()));
String refJson3 = FileUtils.readFileToString(new File(getClass().getResource("/clusteringtasks/latin3_clustering.ref.json").getFile()));
String refJson4 = FileUtils.readFileToString(new File(getClass().getResource("/clusteringtasks/latin4_clustering.ref.json").getFile()));
File segFile1 = new File(getClass().getResource("/clusteringtasks/latin1_segmentation.json").getFile());
File segFile2 = new File(getClass().getResource("/clusteringtasks/latin2_segmentation.json").getFile());
File segFile3 = new File(getClass().getResource("/clusteringtasks/latin3_segmentation.json").getFile());
File segFile4 = new File(getClass().getResource("/clusteringtasks/latin4_segmentation.json").getFile());
String[] outputFilenames = new String[NB_TASKS];
ClusteringTask[] clusteringTasks = new ClusteringTask[NB_TASKS];
for (int i = 0; i < NB_TASKS; i++) {
outputFilenames[i] = CLUSTERING_TASK_FILE_PREFIX + i + ".json";
}
for (int i = 0; i < NB_TASKS/4; i++) {
clusteringTasks[i * 4] = ClusteringTask.builder()
.inputFilename(segFile1.getAbsolutePath())
.outputFilename(outputFilenames[i * 4])
.clusteringParameters(parameters)
.build();
clusteringTasks[i * 4 + 1] = ClusteringTask.builder()
.inputFilename(segFile2.getAbsolutePath())
.outputFilename(outputFilenames[i * 4 + 1])
.clusteringParameters(parameters)
.build();
clusteringTasks[i * 4 + 2] = ClusteringTask.builder()
.inputFilename(segFile3.getAbsolutePath())
.outputFilename(outputFilenames[i * 4 + 2])
.clusteringParameters(parameters)
.build();
clusteringTasks[i * 4 + 3] = ClusteringTask.builder()
.inputFilename(segFile4.getAbsolutePath())
.outputFilename(outputFilenames[i * 4 + 3])
.clusteringParameters(parameters)
.build();
}
// when
for (int i = 0; i < NB_TASKS; i++) {
tasksHandler.addNewTask(clusteringTasks[i]);
Thread.sleep(200);
log.info(tasksHandler.tasksDescription().toString());
}
tasksHandler.waitForAllTasksDone();
String[] outputJsons = new String[NB_TASKS];
for (int i = 0; i < NB_TASKS; i++) {
outputJsons[i] = FileUtils.readFileToString(new File(outputFilenames[i]));
}
// then
for (int i = 0; i < NB_TASKS/4; i++) {
Assertions.assertThat(outputJsons[i * 4]).isEqualTo(refJson1);
Assertions.assertThat(outputJsons[i * 4 + 1]).isEqualTo(refJson2);
Assertions.assertThat(outputJsons[i * 4 + 2]).isEqualTo(refJson3);
Assertions.assertThat(outputJsons[i * 4 + 3]).isEqualTo(refJson4);
}
Arrays.stream(outputFilenames)
.forEach(f -> FileUtils.deleteQuietly(new File(f)));
}
@Test
public void saveStrippedOutput() throws IOException, InterruptedException {
// given
File ref = new File(getClass().getResource("/clusteringtasks/stripped_clustering.ref.json").getFile());
String jsonRef = FileUtils.readFileToString(ref);
String strippedFilename = STRIPPED_CLUSTERING_JSON;
File strippedFile = new File(strippedFilename);
strippedFile.delete();
File segFile = new File(getClass().getResource("/clusteringtasks/latin1_segmentation.json").getFile());
String outputFilename = NOT_STRIPPED_CLUSTERING_JSON;
ClusteringTask task = ClusteringTask.builder()
.inputFilename(segFile.getAbsolutePath())
.outputFilename(outputFilename)
.clusteringParameters(parameters)
.strippedOutputFilename(strippedFilename)
.build();
// when
tasksHandler.addNewTask(task);
tasksHandler.waitForAllTasksDone();
// then
String strippedJson = FileUtils.readFileToString(strippedFile);
Assertions.assertThat(strippedFile).exists();
Assertions.assertThat(strippedJson).isEqualTo(jsonRef);
}
}
| Orange-OpenSource/documentare-simdoc | simdoc/core/java/Comp/src/test/java/com/orange/documentare/core/comp/clustering/tasksservice/ClusteringTasksServiceTest.java | Java | gpl-2.0 | 5,621 |
.head_title {
text-align: center;
font-size: 20px;
color:#002529;
font-weight: 400;
position:relative;
}
.head_title:after{content: ''; position: absolute;left: 0;top:30px; background:#cacaca; width: 100%;height: 1px;
-webkit-transform: scaleY(0.5);transform: scaleY(0.5);-webkit-transform-origin: 0 0;transform-origin: 0 0; }
.weui-search-bar,.weui-search-bar__form{background-color:#fff;}
.weui-search-bar__label{text-align: left;margin:0 10px;}
.weui-search-bar:before{border-top:none;}
.weui-search-bar:after{border-bottom:none;}
.swiper-container {
width: 100%;
height: 100%;
}
.swiper-container img{width:100%;height:100%;}
.btn_libao{margin:10px 36px; height: auto; overflow: hidden;}
.btn_libao img{width:100%; height:100%; max-width: 100%; }
.bar_square{margin:10px 0; }
.bar_square:before, .bar_square:after,.bar_square .weui-grid:before{border:none;}
.bar_square .weui-grid__icon{width:45px;height: 50px;}
.bar_square .weui-footer, .weui-grid__label{font-size:16px;}
.song_left{ width:50%; padding-right:5px;}
.song_left img{width:100%; max-width: 100%;}
.song_right{width:50%;}
.song_right img{width:100%; max-width: 100%;}
.demos-title {
text-align: center;
font-size:30px;
color: #2b2b2b;
font-weight: 400;
margin: 0 15%;
}
.demos-sub-title {
text-align: center;
color: #2b2b2b;
font-size: 14px;
}
.demos-header {
position:relative;
margin:25px 0;
}
.demos_right_ico{position:absolute; right:25px;top:30px;}
.demos_right_ico:after{
content: " ";
display: inline-block;
height: 12px;
width: 12px;
border-width: 2px 2px 0 0;
border-color: #c8c8cd;
border-style: solid;
-webkit-transform: matrix(.71,.71,-.71,.71,0,0);
transform: matrix(.71,.71,-.71,.71,0,0);
position: relative;
position: absolute;
right: 2px;
}
.flavor{padding-bottom:5px;}
.flavor .weui-grid__icon{width:100%;height: 100%;}
/*热卖精选*/
.hot_buy{margin:20px 0 80px; height: auto; overflow: hidden; padding:0 2%;}
.hot_buy li{float: left; list-style: none; width:48%;margin:0 1%; text-align: center; margin-bottom:20px;}
.hot_buy img{width:100%;height:100%;}
.hot_buy .p1{color: #222222; font-size:16px; font-weight: bolder;}
.hot_buy .p2{color: #494949; font-size:14px;}
.hot_buy .p3{color: #f4392d; font-size:16px;}
.weui-tabbar{position:fixed;}
.weui-tabbar__item .weui-tabbar__label{color:#252525;}
.weui-tabbar__item.active .weui-tabbar__label{color:#ff2d2d;}
.active i{color:#ff2d2d;}
/**新品上市*/
.news_list li{
box-sizing: border-box;
border:1px solid #eaeaea;
text-align:left;
height: auto;
overflow: hidden;
}
.news_list li p{padding:0 5px;line-height: 26px;}
.news_list li .p2{color: #666666;}
.news_list li .p3 span{color:#b8b8b8; text-decoration: line-through; padding-left:15px;}
.news_list li .p4{font-size:12px; color:#b8b8b8; padding:5px 5px;}
/**类型*/
.type-tab{border-top:1px solid #eee;}
.type_left{float: left;width:30%;position:inherit;display: block; background:#fff;}
.type_left .weui-navbar__item{width:100%;height: auto;overflow: hidden;}
.type_left .weui-navbar__item:after{border-right:none;}
.type_left:after{border-bottom:none;}
.type_right{float:left; width:70%; border-left: 1px solid #eee;min-height: 500px;}
.weui-navbar+.type_right{padding-top:0;}
.type_right .rqtj_list .p_title{font-size:13px; color: #636363;}
.type_right .rqtj_list .p_price{font-size:13px; color:red; text-align: center;}
.pinpai_list li{
list-style: none;
width:31%;
box-sizing: border-box;
padding:0 5px;
border:1px solid #eee;
border-radius: 2px;
}
.pinpai_list li .p_title{text-align: center; font-size:13px; color: #636363;margin-bottom:5px;}
.type_renqun{width:80%;margin:0 10%;}
.type_renqun li{list-style: none; width:100%;}
.type_renqun li img{width:100%;height: 100%;}
.type_right .hot_buy{margin:0 0 80px;}
.type_right .p_biaoti{text-align: center; margin:15px 0; color: #adadad;font-size:13px;}
.type_right .p_biaoti span{color: #eaeaea;}
/**个人中心*/
.nav_info{
background-color:#ec3e36; height:120px;width:100%;
}
.nav_info img{width:50px;height: 50px; border-radius: 50%; border:2px solid #fff; float: left; margin:20px ;}
.nav_info p{color: #fff; font-size: 18px; padding-top:40px;}
.cells_setall{padding-bottom:10px;font-size:16px;}
.cells_setall:before{border:none;}
.weui-cells:after{bottom:1px;}
.user_navlist{text-align: center; color:#938e8e;margin:15px 0}
.user_navlist i{color:#938e8e}
.div_gray{width:100%;height:10px; background: #eeeeee;}
.user_list p{color: #444;}
.user_list:before{border:none;}
/*three.html 详细信息*/
.three_pageinfo{padding:10px;}
.three_pageinfo .p1{color: #373b41;font-size:18px;}
.three_pageinfo .p1 span{background: #66d8d6;display:inline-block;font-size:14px; padding:1px 5px;border-radius: 5px; margin-left: 10px; color:#fff;}
.three_pageinfo .p2{color: #b8b8b8;font-size:16px;margin-top:5px;}
.three_pageinfo .p3{color: #f44236;font-size:18px;font-weight: bolder; margin-top:10px;}
.three_pageinfo .p3 span{display: inline-block;text-decoration: line-through;color: #b8b8b8;margin-left:15px;}
.three_pageinfo .p4{color: #f44236;font-size:16px;border-top:1px solid #eee;margin-top:10px;padding:5px 0;}
.three_guige{margin:10px 0;}
.three_guige p{color:#b8b8b8;font-size:14px;}
.three_guige p span{color:#000000;font-size:14px;margin-left:15px;}
.three_guige:before,.three_guige:after{border:None;}
.three_guige .weui-cell_access .weui-cell__ft:after{border-color:#000000;width:10px;height: 10px;border-width: 1px 1px 0 0;}
.evaluate .weui-cell__bd{color:#b8b8b8}
.evaluate .weui-cell__bd span{display: inline-block;margin-left: 10px; color:#373b41}
.evaluate .weui-cell__bd label{color:red;}
.three_imglist{margin:10px 0 80px; padding:0 10px;}
.three_imglist p{color:#b8b8b8;margin:5px 0;}
.three_imglist img{width:100%;height: 100%;}
.placeholder {
margin: 5px 10px;
padding: 0 20px;
text-align: center;
color: #cfcfcf;
}
.buy_button{display: block; background: #ff3939}
.buy_button .weui-tabbar__item .weui-tabbar__label{color:#fff;font-size:16px;padding-top:10px;}
.buy_wintop{margin:20px 0; height: auto;overflow: hidden;}
.buy_wintop img{float: left; width:50px; height: 50px;margin-left:20px;}
.buy_wintop .div_right{float: left;font-size:14px;margin-left:15px;}
.buy_wintop .p2{color:#f44236;font-size:12px;font-weight: bolder;}
.buy_wintop .p3{color:#b8b8b8;font-size:12px;}
.buy_winmiddle{padding:10px 20px;width:100%;height: auto; overflow: hidden;color: #000;}
.buy_winmiddle span{display: inline-block;margin:10px 5px 0; border-radius: 3px; border:1px solid #666; width:40%;text-align: center;}
.buy_winmiddle .active{border:1px solid #f44236;color: #f44236;}
.buy_bottom p{float: left;}
.weui-actionsheet__title{height: auto;overflow: hidden; text-align: left;padding: 0;}
.weui-actionsheet__action{display: none;}
.gw_num{float:left; margin-left:43%;border: 1px solid #dbdbdb; line-height: 26px;overflow: hidden;}
.gw_num em{display: block;height: 26px;width: 26px;float:left;color: #7A7979;border-right: 1px solid #dbdbdb;text-align: center;cursor: pointer;}
.gw_num .num{display: block;float: left;text-align: center;width: 52px;font-style: normal;font-size: 14px;line-height: 26px;border: 0;}
.gw_num em.add{float: right;border-right:0;border-left: 1px solid #dbdbdb;}
| lanyanjing-2016/lanyanjing-2016.github.io | items/weui-master/css/main.css | CSS | gpl-2.0 | 7,305 |
#!/bin/bash
if [ -z $1 ]
then
exit 0
fi
ip=$1
rules=$2
trunk=$3
access=$4
general_rules='/etc/isida/isida.conf'
get_uplink=`grep 'uplink' $general_rules | cut -d= -f2 | sed -e s/%ip/$ip/`
ism_vlanid=`grep 'ism_vlanid' $general_rules | cut -d= -f2`
port_count=`echo $5 | sed -e s/://`
args=''
count=0
enum_pars=`cat $rules | grep -v '#' | grep '\.x\.' | cut -d. -f1 | uniq`
raw_fix='/tmp/'`date +%s%N`'-fix'
not_access=`/usr/local/sbin/invert_string_interval.sh $access $port_count`
not_trunk=`/usr/local/sbin/invert_string_interval.sh $trunk $port_count`
# Traffic control
traf_control_thold=`grep traffic_control_bcast_threshold $rules | cut -d= -f2`
traffic_control_trap="config traffic control_trap both"
access_ports="`/usr/local/sbin/interval_to_string.sh $access`"
not_access_ports="`/usr/local/sbin/interval_to_string.sh $not_access`"
traffic_control_string=""
for i in $access_ports
do
traffic_control_string=$traffic_control_string"\nconfig traffic control $i broadcast enable multicast enable unicast disable action drop broadcast_threshold $traf_control_thold multicast_threshold 128 unicast_threshold 131072 countdown 0 time_interval 5"
done
for i in $not_access_ports
do
traffic_control_string=$traffic_control_string"\nconfig traffic control $i broadcast disable multicast disable unicast disable action drop broadcast_threshold $traf_control_thold multicast_threshold 128 unicast_threshold 131072 countdown 0 time_interval 5"
done
# LBD
if [ "`grep lbd_state $rules | cut -d= -f2`" = "enable" ]
then
lbd_state="enable loopdetect"
else
lbd_state="disable loopdetect"
fi
lbd_trap="config loopdetect trap `grep lbd_trap $rules | cut -d= -f2`"
lbd_on=""
for i in $access_ports
do
lbd_on=$lbd_on"\nconfig loopdetect ports $i state enable"
done
lbd_off=""
for i in $not_access_ports
do
lbd_off=$lbd_off"\nconfig loopdetect ports $i state disable"
done
#lbd_off="config loopdetect ports $not_access state disabled"
# Safeguard
sg_state=`grep safeguard_state $rules | cut -d= -f2`
sg_rise=`grep safeguard_rising $rules | cut -d= -f2`
sg_fall=`grep safeguard_falling $rules | cut -d= -f2`
if [ "`grep safeguard_trap $rules | cut -d= -f2`" = "yes" ]
then
sg_trap="enable"
else
sg_trap="disable"
fi
safeguard_string="config safeguard_engine state $sg_state utilization rising $sg_rise falling $sg_fall trap_log $sg_trap mode fuzzy"
# Other
snmp_traps="enable snmp traps\nenable snmp authenticate traps"
dhcp_local_relay="disable dhcp_local_relay"
dhcp_snooping="disable address_binding dhcp_snoop"
impb_acl_mode="disable address_binding acl_mode"
dhcp_screening="config filter dhcp_server ports all state disable\nconfig filter dhcp_server ports $access state enable"
netbios_filter="config filter netbios all state disable\nconfig filter netbios $access state enable"
impb_trap="enable address_binding trap_log"
cpu_interface_filtering="enable cpu_interface_filtering"
arp_aging_time="config arp_aging time `grep arp_aging_time $rules | cut -d= -f2`"
igmp_snooping="enable igmp_snooping"
link_trap="enable snmp linkchange_traps\nconfig snmp linkchange_traps ports 1-28 enable"
# SNTP
sntp_addr1=`grep sntp_primary $rules | cut -d= -f2 | awk -F:: '{print $1}'`
sntp_addr2=`grep sntp_primary $rules | cut -d= -f2 | awk -F:: '{print $2}'`
sntp_string="enable sntp\nconfig sntp primary $sntp_addr1 secondary $sntp_addr2 poll-interval 720\nconfig sntp primary $sntp_addr2 secondary $sntp_addr1"
# IGMP acc auth
igmp_acc_auth_enabled="config igmp access_authentication ports $access state enable"
igmp_acc_auth_disabled="config igmp access_authentication ports $not_access state disable"
# Limited mcast
range1="config limited_multicast_addr ports $access add profile_id 1\nconfig limited_multicast_addr ports $not_access delete profile_id 1"
range2="config limited_multicast_addr ports $access add profile_id 2\nconfig limited_multicast_addr ports $not_access delete profile_id 2"
range3="config limited_multicast_addr ports $access add profile_id 3\nconfig limited_multicast_addr ports $not_access delete profile_id 3"
range4="config limited_multicast_addr ports $access add profile_id 4\nconfig limited_multicast_addr ports $not_access delete profile_id 4"
range5="config limited_multicast_addr ports $access add profile_id 5\nconfig limited_multicast_addr ports $not_access delete profile_id 5"
limited_access="config limited_multicast_addr ports $access access permit"
limited_deny="config limited_multicast_addr ports $trunk access deny"
# SYSLOG
syslog_ip=`grep 'syslog_host.x.ip' $rules | cut -d= -f2`
#syslog_severity=`grep 'syslog_host.x.severity' $rules | cut -d= -f2`
syslog_facility=`grep 'syslog_host.x.facility' $rules | cut -d= -f2`
syslog_state=`grep 'syslog_host.x.state' $rules | cut -d= -f2`
syslog_del="delete syslog host 2"
syslog_add="create syslog host 2 ipaddress $syslog_ip severity debug facility $syslog_facility state $syslog_state"
syslog_enabled="enable_syslog"
# SNMP
snmp_ip=`grep 'snmp_host.x.ip' $rules | cut -d= -f2`
snmp_community=`grep 'snmp_host.x.community' $rules | cut -d= -f2`
snmp_del="delete snmp host $snmp_ip\ndelete snmp host 192.168.1.120"
snmp_add="create snmp host $snmp_ip v2c $snmp_community"
# RADIUS
radius_ip=`grep 'radius.x.ip' $rules | cut -d= -f2`
radius_key=`grep 'radius.x.key' $rules | cut -d= -f2`
radius_auth=`grep 'radius.x.auth' $rules | cut -d= -f2`
radius_acct=`grep 'radius.x.acct' $rules | cut -d= -f2`
radius_retransmit=`grep 'radius_retransmit' $rules | cut -d= -f2`
radius_timeout=`grep 'radius_timeout' $rules | cut -d= -f2`
radius_del="config radius delete 1"
radius_add="config radius add 1 $radius_ip key $radius_key auth_port $radius_auth acct_port $radius_acct"
radius_params="config radius 1 timeout $radius_timeout retransmit $radius_retransmit"
for i in $@
do
case $i in
"traffic_control_trap") echo -e "$traffic_control_string" >> $raw_fix;;
"traffic_control_bcast") echo -e "$traffic_control_string" >> $raw_fix;;
"traffic_control_mcast") echo -e "$traffic_control_string" >> $raw_fix;;
"traffic_control_bcast_threshold") echo -e "$traffic_control_string" >> $raw_fix;;
"traffic_control_mcast_threshold") echo -e "$traffic_control_string" >> $raw_fix;;
"lbd_state") echo -e "$lbd_state" >> $raw_fix;;
"lbd_on") echo -e "$lbd_on" >> $raw_fix;;
"lbd_off") echo -e "$lbd_off" >> $raw_fix;;
"lbd_trap") echo -e "$lbd_trap" >> $raw_fix;;
"safeguard_state") echo -e "$safeguard_string" >> $raw_fix;;
"safeguard_trap") echo -e "$safeguard_string" >> $raw_fix;;
"safeguard_rising") echo -e "$safeguard_string" >> $raw_fix;;
"safeguard_falling") echo -e "$safeguard_string" >> $raw_fix;;
"snmp_traps") echo -e "$snmp_traps" >> $raw_fix;;
"dhcp_local_relay") echo -e "$dhcp_local_relay" >> $raw_fix;;
"dhcp_snooping") echo -e "$dhcp_snooping" >> $raw_fix;;
"impb_acl_mode") echo -e "$impb_acl_mode" >> $raw_fix;;
"dhcp_screening") echo -e "$dhcp_screening" >> $raw_fix;;
"netbios_filter") echo -e "$netbios_filter" >> $raw_fix;;
"impb_trap") echo -e "$impb_trap" >> $raw_fix;;
"cpu_interface_filtering") echo -e "$cpu_interface_filtering" >> $raw_fixing;;
"arp_aging_time") echo -e "$arp_aging_time" >> $raw_fix;;
"sntp_state") echo -e "$sntp_string" >> $raw_fix;;
"sntp_primary") echo -e "$sntp_string" >> $raw_fix;;
"sntp_secondary") echo -e "$sntp_string" >> $raw_fix;;
"link_trap") echo -e "$link_trap" >> $raw_fix;;
"mcast_range.iptv1") echo -e "$range1\n$limited_access\n$limited_deny" >> $raw_fix;;
"mcast_range.iptv2") echo -e "$range2\n$limited_access\n$limited_deny" >> $raw_fix;;
"mcast_range.iptv3") echo -e "$range3\n$limited_access\n$limited_deny" >> $raw_fix;;
"mcast_range.iptv4") echo -e "$range4\n$limited_access\n$limited_deny" >> $raw_fix;;
"mcast_range.iptv5") echo -e "$range5\n$limited_access\n$limited_deny" >> $raw_fix;;
"igmp_acc_auth_enabled") echo -e "$igmp_acc_auth_enabled" >> $raw_fix;;
"igmp_acc_auth_disabled") echo -e "$igmp_acc_auth_disabled" >> $raw_fix;;
"syslog_host") echo -e "$syslog_del\n$syslog_add" >> $raw_fix;;
"snmp_host") echo -e "$snmp_del\n$snmp_add" >> $raw_fix;;
"radius") echo -e "$radius_del\n$radius_add\n$radius_params" >> $raw_fix;;
"radius_retransmit") echo -e "$radius_params" >> $raw_fix;;
"radius_timeout") echo -e "$radius_params" >> $raw_fix;;
"igmp_snooping") echo -e "$igmp_snooping" >> $raw_fix;;
"syslog_enabled") echo -e "$syslog_enabled" >> $raw_fix;;
"ism") if [ `/usr/local/sbin/ping_equip.sh $ip` -eq 1 ]
then
ism_prefix='.1.3.6.1.4.1.171.12.64.3.1.1'
ism_name=`snmpget -v2c -c dlread -Ovq $ip $ism_prefix.2.$ism_vlanid | sed -e s/\"//g`
uplink=`$get_uplink`
raw_tagmember=`snmpget -v2c -c dlread -Ovq $ip $ism_prefix.5.$ism_vlanid | sed -e s/\"//g | awk '{print $1 $2 $3 $4}' | xargs -l /usr/local/sbin/portconv.sh`
raw_member=`snmpget -v2c -c dlread -Ovq $ip $ism_prefix.4.$ism_vlanid | sed -e s/\"//g | awk '{print $1 $2 $3 $4}' | xargs -l /usr/local/sbin/portconv.sh`
raw_source=`snmpget -v2c -c dlread -Ovq $ip $ism_prefix.3.$ism_vlanid | sed -e s/\"//g | awk '{print $1 $2 $3 $4}' | xargs -l /usr/local/sbin/portconv.sh`
tagmember=`/usr/local/sbin/string_to_bitmask.sh $raw_tagmember | xargs -l /usr/local/sbin/bitmask_to_interval.sh`
source=`/usr/local/sbin/string_to_bitmask.sh $raw_source | xargs -l /usr/local/sbin/bitmask_to_interval.sh`
echo -e "config igmp_snooping multicast_vlan $ism_name del tag $tagmember" >> $raw_fix
echo -e "config igmp_snooping multicast_vlan $ism_name del source $source" >> $raw_fix
detailed_trunk=`/usr/local/sbin/interval_to_string.sh $trunk`
del_member_raw=''
for i in $detailed_trunk
do
if [ "`echo $raw_member | grep $i`" ]
then
del_member_raw=$del_member_raw" $i"
fi
done
if [ -n "$del_member_raw" ]
then
del_member=`/usr/local/sbin/string_to_bitmask.sh $del_member_raw | xargs -l /usr/local/sbin/bitmask_to_interval.sh`
echo -e "config igmp_snooping multicast_vlan $ism_name del member $del_member" >> $raw_fix
fi
new_source=$uplink
new_tagmember=`echo $detailed_trunk | sed -e s/$uplink// | xargs -l /usr/local/sbin/string_to_bitmask.sh | xargs -l /usr/local/sbin/bitmask_to_interval.sh`
echo -e "config igmp_snooping multicast_vlan $ism_name add source $new_source" >> $raw_fix
echo -e "config igmp_snooping multicast_vlan $ism_name add tag $new_tagmember" >> $raw_fix
fi;;
esac
done
fix_cmd='/tmp/'`date +%s%N`'_fix'
if [ -s $raw_fix ]
then
echo "save" >> $raw_fix
fi
cat $raw_fix | uniq
rm -f $rules $raw_fix
| vlad-syan/isida | usr/local/sbin/fix_3528.sh | Shell | gpl-2.0 | 11,905 |
/*
Colorbox Core Style:
The following CSS is consistent between example themes and should not be altered.
*/
#colorbox, #cboxOverlay, #cboxWrapper{position:absolute; top:0; left:0; z-index:9999; overflow:hidden;}
#cboxWrapper {max-width:none;}
#cboxOverlay{position:fixed; width:100%; height:100%;}
#cboxMiddleLeft, #cboxBottomLeft{clear:left;}
#cboxContent{position:relative;}
#cboxLoadedContent{overflow:auto; -webkit-overflow-scrolling: touch;}
#cboxTitle{margin:0;}
#cboxLoadingOverlay, #cboxLoadingGraphic{position:absolute; top:0; left:0; width:100%; height:100%;}
#cboxPrevious, #cboxNext, #cboxClose, #cboxSlideshow{cursor:pointer;}
.cboxPhoto{float:left; margin:auto; border:0; display:block; max-width:none; -ms-interpolation-mode:bicubic;}
.cboxIframe{width:100%; height:100%; display:block; border:0;}
#colorbox, #cboxContent, #cboxLoadedContent{box-sizing:content-box; -moz-box-sizing:content-box; -webkit-box-sizing:content-box;}
/*
User Style:
Change the following styles to modify the appearance of Colorbox. They are
ordered & tabbed in a way that represents the nesting of the generated HTML.
*/
#colorbox{outline:0;}
#cboxTopLeft{width:21px; height:21px; background:url(images/controls.png) no-repeat -101px 0;}
#cboxTopRight{width:21px; height:21px; background:url(images/controls.png) no-repeat -130px 0;}
#cboxBottomLeft{width:21px; height:21px; background:url(images/controls.png) no-repeat -101px -29px;}
#cboxBottomRight{width:21px; height:21px; background:url(images/controls.png) no-repeat -130px -29px;}
#cboxMiddleLeft{width:21px; background:url(images/controls.png) left top repeat-y;}
#cboxMiddleRight{width:21px; background:url(images/controls.png) right top repeat-y;}
#cboxTopCenter{height:21px; background:url(images/border.png) 0 0 repeat-x;}
#cboxBottomCenter{height:21px; background:url(images/border.png) 0 -29px repeat-x;}
#cboxContent{background:#fff; overflow:hidden;}
.cboxIframe{background:#fff;}
#cboxError{padding:50px; border:1px solid #ccc;}
#cboxLoadedContent{margin-bottom:28px;}
#cboxTitle{position:absolute; bottom:4px; left:0; text-align:center; width:100%; color:#949494;}
#cboxCurrent{position:absolute; bottom:4px; left:58px; color:#949494;}
#cboxLoadingOverlay{background:url(images/loading_background.png) no-repeat center center;}
#cboxLoadingGraphic{background:url(images/loading.gif) no-repeat center center;}
/* these elements are buttons, and may need to have additional styles reset to avoid unwanted base styles */
#cboxPrevious, #cboxNext, #cboxSlideshow, #cboxClose {border:0; padding:0; margin:0; overflow:visible; width:auto; background:none; }
/* avoid outlines on :active (mouseclick), but preserve outlines on :focus (tabbed navigating) */
#cboxPrevious:active, #cboxNext:active, #cboxSlideshow:active, #cboxClose:active {outline:0;}
#cboxSlideshow{position:absolute; bottom:4px; right:30px; color:#0092ef;}
#cboxPrevious{position:absolute; bottom:0; left:0; background:url(images/controls.png) no-repeat -75px 0; width:25px; height:25px; text-indent:-9999px;}
#cboxPrevious:hover{background-position:-75px -25px;}
#cboxNext{position:absolute; bottom:0; left:27px; background:url(images/controls.png) no-repeat -50px 0; width:25px; height:25px; text-indent:-9999px;}
#cboxNext:hover{background-position:-50px -25px;}
#cboxClose{position:absolute; bottom:0; right:0; background:url(images/controls.png) no-repeat -25px 0; width:25px; height:25px; text-indent:-9999px;}
#cboxClose:hover{background-position:-25px -25px;}
/*
The following fixes a problem where IE7 and IE8 replace a PNG's alpha transparency with a black fill
when an alpha filter (opacity change) is set on the element or ancestor element. This style is not applied to or needed in IE9.
See: http://jacklmoore.com/notes/ie-transparency-problems/
*/
.cboxIE #cboxTopLeft,
.cboxIE #cboxTopCenter,
.cboxIE #cboxTopRight,
.cboxIE #cboxBottomLeft,
.cboxIE #cboxBottomCenter,
.cboxIE #cboxBottomRight,
.cboxIE #cboxMiddleLeft,
.cboxIE #cboxMiddleRight {
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#00FFFFFF,endColorstr=#00FFFFFF);
} | emelielindstrom/wordpress | wp-content/plugins/awesome-filterable-portfolio/css/colorbox.css | CSS | gpl-2.0 | 4,311 |
<?php
/**
* @file
* Contains \Drupal\Tests\Core\Form\FormBuilderTest.
*/
namespace Drupal\Tests\Core\Form;
use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Access\AccessResultForbidden;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Form\EnforcedResponseException;
use Drupal\Core\Form\FormBuilderInterface;
use Drupal\Core\Form\FormInterface;
use Drupal\Core\Form\FormState;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Drupal\Core\Cache\Context\CacheContextsManager;
use Symfony\Component\DependencyInjection\ContainerBuilder;
/**
* @coversDefaultClass \Drupal\Core\Form\FormBuilder
* @group Form
*/
class FormBuilderTest extends FormTestBase {
/**
* The dependency injection container.
*
* @var \Symfony\Component\DependencyInjection\ContainerBuilder
*/
protected $container;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->container = new ContainerBuilder();
$cache_contexts_manager = $this->prophesize(CacheContextsManager::class)->reveal();
$this->container->set('cache_contexts_manager', $cache_contexts_manager);
\Drupal::setContainer($this->container);
}
/**
* Tests the getFormId() method with a string based form ID.
*
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage The form argument foo is not a valid form.
*/
public function testGetFormIdWithString() {
$form_arg = 'foo';
$clean_form_state = new FormState();
$form_state = new FormState();
$form_id = $this->formBuilder->getFormId($form_arg, $form_state);
$this->assertSame($form_arg, $form_id);
$this->assertSame($clean_form_state, $form_state);
}
/**
* Tests the getFormId() method with a class name form ID.
*/
public function testGetFormIdWithClassName() {
$form_arg = 'Drupal\Tests\Core\Form\TestForm';
$form_state = new FormState();
$form_id = $this->formBuilder->getFormId($form_arg, $form_state);
$this->assertSame('test_form', $form_id);
$this->assertSame($form_arg, get_class($form_state->getFormObject()));
}
/**
* Tests the getFormId() method with an injected class name form ID.
*/
public function testGetFormIdWithInjectedClassName() {
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
\Drupal::setContainer($container);
$form_arg = 'Drupal\Tests\Core\Form\TestFormInjected';
$form_state = new FormState();
$form_id = $this->formBuilder->getFormId($form_arg, $form_state);
$this->assertSame('test_form', $form_id);
$this->assertSame($form_arg, get_class($form_state->getFormObject()));
}
/**
* Tests the getFormId() method with a form object.
*/
public function testGetFormIdWithObject() {
$expected_form_id = 'my_module_form_id';
$form_arg = $this->getMockForm($expected_form_id);
$form_state = new FormState();
$form_id = $this->formBuilder->getFormId($form_arg, $form_state);
$this->assertSame($expected_form_id, $form_id);
$this->assertSame($form_arg, $form_state->getFormObject());
}
/**
* Tests the getFormId() method with a base form object.
*/
public function testGetFormIdWithBaseForm() {
$expected_form_id = 'my_module_form_id';
$base_form_id = 'my_module';
$form_arg = $this->getMock('Drupal\Core\Form\BaseFormIdInterface');
$form_arg->expects($this->once())
->method('getFormId')
->will($this->returnValue($expected_form_id));
$form_arg->expects($this->once())
->method('getBaseFormId')
->will($this->returnValue($base_form_id));
$form_state = new FormState();
$form_id = $this->formBuilder->getFormId($form_arg, $form_state);
$this->assertSame($expected_form_id, $form_id);
$this->assertSame($form_arg, $form_state->getFormObject());
$this->assertSame($base_form_id, $form_state->getBuildInfo()['base_form_id']);
}
/**
* Tests the handling of FormStateInterface::$response.
*
* @dataProvider formStateResponseProvider
*/
public function testHandleFormStateResponse($class, $form_state_key) {
$form_id = 'test_form_id';
$expected_form = $form_id();
$response = $this->getMockBuilder($class)
->disableOriginalConstructor()
->getMock();
$form_arg = $this->getMockForm($form_id, $expected_form);
$form_arg->expects($this->any())
->method('submitForm')
->will($this->returnCallback(function ($form, FormStateInterface $form_state) use ($response, $form_state_key) {
$form_state->setFormState([$form_state_key => $response]);
}));
$form_state = new FormState();
try {
$input['form_id'] = $form_id;
$form_state->setUserInput($input);
$this->simulateFormSubmission($form_id, $form_arg, $form_state, FALSE);
$this->fail('EnforcedResponseException was not thrown.');
}
catch (EnforcedResponseException $e) {
$this->assertSame($response, $e->getResponse());
}
$this->assertSame($response, $form_state->getResponse());
}
/**
* Provides test data for testHandleFormStateResponse().
*/
public function formStateResponseProvider() {
return array(
array('Symfony\Component\HttpFoundation\Response', 'response'),
array('Symfony\Component\HttpFoundation\RedirectResponse', 'redirect'),
);
}
/**
* Tests the handling of a redirect when FormStateInterface::$response exists.
*/
public function testHandleRedirectWithResponse() {
$form_id = 'test_form_id';
$expected_form = $form_id();
// Set up a response that will be used.
$response = $this->getMockBuilder('Symfony\Component\HttpFoundation\Response')
->disableOriginalConstructor()
->getMock();
// Set up a redirect that will not be called.
$redirect = $this->getMockBuilder('Symfony\Component\HttpFoundation\RedirectResponse')
->disableOriginalConstructor()
->getMock();
$form_arg = $this->getMockForm($form_id, $expected_form);
$form_arg->expects($this->any())
->method('submitForm')
->will($this->returnCallback(function ($form, FormStateInterface $form_state) use ($response, $redirect) {
// Set both the response and the redirect.
$form_state->setResponse($response);
$form_state->set('redirect', $redirect);
}));
$form_state = new FormState();
try {
$input['form_id'] = $form_id;
$form_state->setUserInput($input);
$this->simulateFormSubmission($form_id, $form_arg, $form_state, FALSE);
$this->fail('EnforcedResponseException was not thrown.');
}
catch (EnforcedResponseException $e) {
$this->assertSame($response, $e->getResponse());
}
$this->assertSame($response, $form_state->getResponse());
}
/**
* Tests the getForm() method with a string based form ID.
*
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage The form argument test_form_id is not a valid form.
*/
public function testGetFormWithString() {
$form_id = 'test_form_id';
$expected_form = $form_id();
$form = $this->formBuilder->getForm($form_id);
$this->assertFormElement($expected_form, $form, 'test');
$this->assertSame('test-form-id', $form['#id']);
}
/**
* Tests the getForm() method with a form object.
*/
public function testGetFormWithObject() {
$form_id = 'test_form_id';
$expected_form = $form_id();
$form_arg = $this->getMockForm($form_id, $expected_form);
$form = $this->formBuilder->getForm($form_arg);
$this->assertFormElement($expected_form, $form, 'test');
$this->assertArrayHasKey('#id', $form);
}
/**
* Tests the getForm() method with a class name based form ID.
*/
public function testGetFormWithClassString() {
$form_id = '\Drupal\Tests\Core\Form\TestForm';
$object = new TestForm();
$form = array();
$form_state = new FormState();
$expected_form = $object->buildForm($form, $form_state);
$form = $this->formBuilder->getForm($form_id);
$this->assertFormElement($expected_form, $form, 'test');
$this->assertSame('test-form', $form['#id']);
}
/**
* Tests the buildForm() method with a string based form ID.
*
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage The form argument test_form_id is not a valid form.
*/
public function testBuildFormWithString() {
$form_id = 'test_form_id';
$expected_form = $form_id();
$form = $this->formBuilder->getForm($form_id);
$this->assertFormElement($expected_form, $form, 'test');
$this->assertArrayHasKey('#id', $form);
}
/**
* Tests the buildForm() method with a class name based form ID.
*/
public function testBuildFormWithClassString() {
$form_id = '\Drupal\Tests\Core\Form\TestForm';
$object = new TestForm();
$form = array();
$form_state = new FormState();
$expected_form = $object->buildForm($form, $form_state);
$form = $this->formBuilder->buildForm($form_id, $form_state);
$this->assertFormElement($expected_form, $form, 'test');
$this->assertSame('test-form', $form['#id']);
}
/**
* Tests the buildForm() method with a form object.
*/
public function testBuildFormWithObject() {
$form_id = 'test_form_id';
$expected_form = $form_id();
$form_arg = $this->getMockForm($form_id, $expected_form);
$form_state = new FormState();
$form = $this->formBuilder->buildForm($form_arg, $form_state);
$this->assertFormElement($expected_form, $form, 'test');
$this->assertSame($form_id, $form_state->getBuildInfo()['form_id']);
$this->assertArrayHasKey('#id', $form);
}
/**
* Tests the rebuildForm() method for a POST submission.
*/
public function testRebuildForm() {
$form_id = 'test_form_id';
$expected_form = $form_id();
// The form will be built four times.
$form_arg = $this->getMock('Drupal\Core\Form\FormInterface');
$form_arg->expects($this->exactly(2))
->method('getFormId')
->will($this->returnValue($form_id));
$form_arg->expects($this->exactly(4))
->method('buildForm')
->will($this->returnValue($expected_form));
// Do an initial build of the form and track the build ID.
$form_state = new FormState();
$form = $this->formBuilder->buildForm($form_arg, $form_state);
$original_build_id = $form['#build_id'];
$this->request->setMethod('POST');
$form_state->setRequestMethod('POST');
// Rebuild the form, and assert that the build ID has not changed.
$form_state->setRebuild();
$input['form_id'] = $form_id;
$form_state->setUserInput($input);
$form_state->addRebuildInfo('copy', ['#build_id' => TRUE]);
$this->formBuilder->processForm($form_id, $form, $form_state);
$this->assertSame($original_build_id, $form['#build_id']);
$this->assertTrue($form_state->isCached());
// Rebuild the form again, and assert that there is a new build ID.
$form_state->setRebuildInfo([]);
$form = $this->formBuilder->buildForm($form_arg, $form_state);
$this->assertNotSame($original_build_id, $form['#build_id']);
$this->assertTrue($form_state->isCached());
}
/**
* Tests the rebuildForm() method for a GET submission.
*/
public function testRebuildFormOnGetRequest() {
$form_id = 'test_form_id';
$expected_form = $form_id();
// The form will be built four times.
$form_arg = $this->getMock('Drupal\Core\Form\FormInterface');
$form_arg->expects($this->exactly(2))
->method('getFormId')
->will($this->returnValue($form_id));
$form_arg->expects($this->exactly(4))
->method('buildForm')
->will($this->returnValue($expected_form));
// Do an initial build of the form and track the build ID.
$form_state = new FormState();
$form_state->setMethod('GET');
$form = $this->formBuilder->buildForm($form_arg, $form_state);
$original_build_id = $form['#build_id'];
// Rebuild the form, and assert that the build ID has not changed.
$form_state->setRebuild();
$input['form_id'] = $form_id;
$form_state->setUserInput($input);
$form_state->addRebuildInfo('copy', ['#build_id' => TRUE]);
$this->formBuilder->processForm($form_id, $form, $form_state);
$this->assertSame($original_build_id, $form['#build_id']);
$this->assertFalse($form_state->isCached());
// Rebuild the form again, and assert that there is a new build ID.
$form_state->setRebuildInfo([]);
$form = $this->formBuilder->buildForm($form_arg, $form_state);
$this->assertNotSame($original_build_id, $form['#build_id']);
$this->assertFalse($form_state->isCached());
}
/**
* Tests the getCache() method.
*/
public function testGetCache() {
$form_id = 'test_form_id';
$expected_form = $form_id();
$expected_form['#token'] = FALSE;
// FormBuilder::buildForm() will be called twice, but the form object will
// only be called once due to caching.
$form_arg = $this->getMock('Drupal\Core\Form\FormInterface');
$form_arg->expects($this->exactly(2))
->method('getFormId')
->will($this->returnValue($form_id));
$form_arg->expects($this->once())
->method('buildForm')
->will($this->returnValue($expected_form));
// Do an initial build of the form and track the build ID.
$form_state = (new FormState())
->addBuildInfo('files', [['module' => 'node', 'type' => 'pages.inc']])
->setRequestMethod('POST')
->setCached();
$form = $this->formBuilder->buildForm($form_arg, $form_state);
$cached_form = $form;
$cached_form['#cache_token'] = 'csrf_token';
// The form cache, form_state cache, and CSRF token validation will only be
// called on the cached form.
$this->formCache->expects($this->once())
->method('getCache')
->willReturn($form);
// The final form build will not trigger any actual form building, but will
// use the form cache.
$form_state->setExecuted();
$input['form_id'] = $form_id;
$input['form_build_id'] = $form['#build_id'];
$form_state->setUserInput($input);
$this->formBuilder->buildForm($form_arg, $form_state);
$this->assertEmpty($form_state->getErrors());
}
/**
* Tests that HTML IDs are unique when rebuilding a form with errors.
*/
public function testUniqueHtmlId() {
$form_id = 'test_form_id';
$expected_form = $form_id();
$expected_form['test']['#required'] = TRUE;
// Mock a form object that will be built two times.
$form_arg = $this->getMock('Drupal\Core\Form\FormInterface');
$form_arg->expects($this->exactly(2))
->method('getFormId')
->will($this->returnValue($form_id));
$form_arg->expects($this->exactly(2))
->method('buildForm')
->will($this->returnValue($expected_form));
$form_state = new FormState();
$form = $this->simulateFormSubmission($form_id, $form_arg, $form_state);
$this->assertSame('test-form-id', $form['#id']);
$form_state = new FormState();
$form = $this->simulateFormSubmission($form_id, $form_arg, $form_state);
$this->assertSame('test-form-id--2', $form['#id']);
}
/**
* Tests that a cached form is deleted after submit.
*/
public function testFormCacheDeletionCached() {
$form_id = 'test_form_id';
$form_build_id = $this->randomMachineName();
$expected_form = $form_id();
$expected_form['#build_id'] = $form_build_id;
$form_arg = $this->getMockForm($form_id, $expected_form);
$form_arg->expects($this->once())
->method('submitForm')
->willReturnCallback(function (array &$form, FormStateInterface $form_state) {
// Mimic EntityForm by cleaning the $form_state upon submit.
$form_state->cleanValues();
});
$this->formCache->expects($this->once())
->method('deleteCache')
->with($form_build_id);
$form_state = new FormState();
$form_state->setRequestMethod('POST');
$form_state->setCached();
$this->simulateFormSubmission($form_id, $form_arg, $form_state);
}
/**
* Tests that an uncached form does not trigger cache set or delete.
*/
public function testFormCacheDeletionUncached() {
$form_id = 'test_form_id';
$form_build_id = $this->randomMachineName();
$expected_form = $form_id();
$expected_form['#build_id'] = $form_build_id;
$form_arg = $this->getMockForm($form_id, $expected_form);
$this->formCache->expects($this->never())
->method('deleteCache');
$form_state = new FormState();
$this->simulateFormSubmission($form_id, $form_arg, $form_state);
}
/**
* @covers ::buildForm
*
* @expectedException \Drupal\Core\Form\Exception\BrokenPostRequestException
*/
public function testExceededFileSize() {
$request = new Request([FormBuilderInterface::AJAX_FORM_REQUEST => TRUE]);
$request_stack = new RequestStack();
$request_stack->push($request);
$this->formBuilder = $this->getMockBuilder('\Drupal\Core\Form\FormBuilder')
->setConstructorArgs([$this->formValidator, $this->formSubmitter, $this->formCache, $this->moduleHandler, $this->eventDispatcher, $request_stack, $this->classResolver, $this->elementInfo, $this->themeManager, $this->csrfToken])
->setMethods(['getFileUploadMaxSize'])
->getMock();
$this->formBuilder->expects($this->once())
->method('getFileUploadMaxSize')
->willReturn(33554432);
$form_arg = $this->getMockForm('test_form_id');
$form_state = new FormState();
$this->formBuilder->buildForm($form_arg, $form_state);
}
/**
* @covers ::buildForm
*
* @dataProvider providerTestChildAccessInheritance
*/
public function testChildAccessInheritance($element, $access_checks) {
$form_arg = new TestFormWithPredefinedForm();
$form_arg->setForm($element);
$form_state = new FormState();
$form = $this->formBuilder->buildForm($form_arg, $form_state);
$actual_access_structure = [];
$expected_access_structure = [];
// Ensure that the expected access checks are set.
foreach ($access_checks as $access_check) {
$parents = $access_check[0];
$parents[] = '#access';
$actual_access = NestedArray::getValue($form, $parents);
$actual_access_structure[] = [$parents, $actual_access];
$expected_access_structure[] = [$parents, $access_check[1]];
}
$this->assertEquals($expected_access_structure, $actual_access_structure);
}
/**
* Data provider for testChildAccessInheritance.
*
* @return array
*/
public function providerTestChildAccessInheritance() {
$data = [];
$element = [
'child0' => [
'#type' => 'checkbox',
],
'child1' => [
'#type' => 'checkbox',
],
'child2' => [
'#type' => 'fieldset',
'child2.0' => [
'#type' => 'checkbox',
],
'child2.1' => [
'#type' => 'checkbox',
],
'child2.2' => [
'#type' => 'checkbox',
],
],
];
// Sets access FALSE on the root level, this should be inherited completely.
$clone = $element;
$clone['#access'] = FALSE;
$expected_access = [];
$expected_access[] = [[], FALSE];
$expected_access[] = [['child0'], FALSE];
$expected_access[] = [['child1'], FALSE];
$expected_access[] = [['child2'], FALSE];
$expected_access[] = [['child2', 'child2.0'], FALSE];
$expected_access[] = [['child2', 'child2.1'], FALSE];
$expected_access[] = [['child2', 'child2.2'], FALSE];
$data['access-false-root'] = [$clone, $expected_access];
$clone = $element;
$access_result = AccessResult::forbidden();
$clone['#access'] = $access_result;
$expected_access = [];
$expected_access[] = [[], $access_result];
$expected_access[] = [['child0'], $access_result];
$expected_access[] = [['child1'], $access_result];
$expected_access[] = [['child2'], $access_result];
$expected_access[] = [['child2', 'child2.0'], $access_result];
$expected_access[] = [['child2', 'child2.1'], $access_result];
$expected_access[] = [['child2', 'child2.2'], $access_result];
$data['access-forbidden-root'] = [$clone, $expected_access];
// Allow access on the most outer level but set FALSE otherwise.
$clone = $element;
$clone['#access'] = TRUE;
$clone['child0']['#access'] = FALSE;
$expected_access = [];
$expected_access[] = [[], TRUE];
$expected_access[] = [['child0'], FALSE];
$expected_access[] = [['child1'], NULL];
$expected_access[] = [['child2'], NULL];
$expected_access[] = [['child2', 'child2.0'], NULL];
$expected_access[] = [['child2', 'child2.1'], NULL];
$expected_access[] = [['child2', 'child2.2'], NULL];
$data['access-true-root'] = [$clone, $expected_access];
// Allow access on the most outer level but forbid otherwise.
$clone = $element;
$access_result_allowed = AccessResult::allowed();
$clone['#access'] = $access_result_allowed;
$access_result_forbidden = AccessResult::forbidden();
$clone['child0']['#access'] = $access_result_forbidden;
$expected_access = [];
$expected_access[] = [[], $access_result_allowed];
$expected_access[] = [['child0'], $access_result_forbidden];
$expected_access[] = [['child1'], NULL];
$expected_access[] = [['child2'], NULL];
$expected_access[] = [['child2', 'child2.0'], NULL];
$expected_access[] = [['child2', 'child2.1'], NULL];
$expected_access[] = [['child2', 'child2.2'], NULL];
$data['access-allowed-root'] = [$clone, $expected_access];
// Allow access on the most outer level, deny access on a parent, and allow
// on a child. The denying should be inherited.
$clone = $element;
$clone['#access'] = TRUE;
$clone['child2']['#access'] = FALSE;
$clone['child2.0']['#access'] = TRUE;
$clone['child2.1']['#access'] = TRUE;
$clone['child2.2']['#access'] = TRUE;
$expected_access = [];
$expected_access[] = [[], TRUE];
$expected_access[] = [['child0'], NULL];
$expected_access[] = [['child1'], NULL];
$expected_access[] = [['child2'], FALSE];
$expected_access[] = [['child2', 'child2.0'], FALSE];
$expected_access[] = [['child2', 'child2.1'], FALSE];
$expected_access[] = [['child2', 'child2.2'], FALSE];
$data['access-mixed-parents'] = [$clone, $expected_access];
$clone = $element;
$clone['#access'] = $access_result_allowed;
$clone['child2']['#access'] = $access_result_forbidden;
$clone['child2.0']['#access'] = $access_result_allowed;
$clone['child2.1']['#access'] = $access_result_allowed;
$clone['child2.2']['#access'] = $access_result_allowed;
$expected_access = [];
$expected_access[] = [[], $access_result_allowed];
$expected_access[] = [['child0'], NULL];
$expected_access[] = [['child1'], NULL];
$expected_access[] = [['child2'], $access_result_forbidden];
$expected_access[] = [['child2', 'child2.0'], $access_result_forbidden];
$expected_access[] = [['child2', 'child2.1'], $access_result_forbidden];
$expected_access[] = [['child2', 'child2.2'], $access_result_forbidden];
$data['access-mixed-parents-object'] = [$clone, $expected_access];
return $data;
}
}
class TestForm implements FormInterface {
public function getFormId() {
return 'test_form';
}
public function buildForm(array $form, FormStateInterface $form_state) {
return test_form_id();
}
public function validateForm(array &$form, FormStateInterface $form_state) { }
public function submitForm(array &$form, FormStateInterface $form_state) { }
}
class TestFormInjected extends TestForm implements ContainerInjectionInterface {
public static function create(ContainerInterface $container) {
return new static();
}
}
class TestFormWithPredefinedForm extends TestForm {
/**
* @var array
*/
protected $form;
public function setForm($form) {
$this->form = $form;
}
public function buildForm(array $form, FormStateInterface $form_state) {
return $this->form;
}
}
| havran/Drupal.sk | docroot/drupal/core/tests/Drupal/Tests/Core/Form/FormBuilderTest.php | PHP | gpl-2.0 | 24,356 |
<?php
/**
* DmUserGroupTable
*
* This class has been auto-generated by the Doctrine ORM Framework
*/
class DmUserGroupTable extends PluginDmUserGroupTable
{
/**
* Returns an instance of this class.
*
* @return DmUserGroupTable The table object
*/
public static function getInstance()
{
return Doctrine_Core::getTable('DmUserGroup');
}
} | Teplitsa/bquest.ru | lib/model/doctrine/dmUserPlugin/DmUserGroupTable.class.php | PHP | gpl-2.0 | 386 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package database.parse.util;
import almonds.Parse;
import almonds.ParseObject;
import database.parse.tables.ParsePhenomena;
import database.parse.tables.ParseSensor;
import java.net.URI;
/**
*
* @author jried31
*/
public class DBGlobals {
static public String TABLE_PHENOMENA="tester";
static public String TABLE_SENSOR="Sensor";
public static String URL_GOOGLE_SEARCH="http://suggestqueries.google.com/complete/search?client=firefox&hl=en&q=WORD";
//http://clients1.google.com/complete/search?noLabels=t&client=web&q=WORD";
public static void InitializeParse(){
//App Ids for Connecting to the Parse DB
Parse.initialize("jEciFYpTp2b1XxHuIkmAs3yaP70INpkBDg9WdTl9", //Application ID
"aPEXcVv80kHwfVJK1WEKWckePkWxYNEXBovIR6d5"); //Rest API Key
}
}
| jried31/SSKB | sensite/src/main/java/database/parse/util/DBGlobals.java | Java | gpl-2.0 | 1,007 |
/*
* f_mass_storage.c -- Mass Storage USB Composite Function
*
* Copyright (C) 2003-2008 Alan Stern
* Copyright (C) 2009 Samsung Electronics
* Author: Michal Nazarewicz <[email protected]>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions, and the following disclaimer,
* without modification.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The names of the above-listed copyright holders may not 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 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.
*/
/*
* The Mass Storage Function acts as a USB Mass Storage device,
* appearing to the host as a disk drive or as a CD-ROM drive. In
* addition to providing an example of a genuinely useful composite
* function for a USB device, it also illustrates a technique of
* double-buffering for increased throughput.
*
* For more information about MSF and in particular its module
* parameters and sysfs interface read the
* <Documentation/usb/mass-storage.txt> file.
*/
/*
* MSF is configured by specifying a fsg_config structure. It has the
* following fields:
*
* nluns Number of LUNs function have (anywhere from 1
* to FSG_MAX_LUNS which is 8).
* luns An array of LUN configuration values. This
* should be filled for each LUN that
* function will include (ie. for "nluns"
* LUNs). Each element of the array has
* the following fields:
* ->filename The path to the backing file for the LUN.
* Required if LUN is not marked as
* removable.
* ->ro Flag specifying access to the LUN shall be
* read-only. This is implied if CD-ROM
* emulation is enabled as well as when
* it was impossible to open "filename"
* in R/W mode.
* ->removable Flag specifying that LUN shall be indicated as
* being removable.
* ->cdrom Flag specifying that LUN shall be reported as
* being a CD-ROM.
* ->nofua Flag specifying that FUA flag in SCSI WRITE(10,12)
* commands for this LUN shall be ignored.
*
* vendor_name
* product_name
* release Information used as a reply to INQUIRY
* request. To use default set to NULL,
* NULL, 0xffff respectively. The first
* field should be 8 and the second 16
* characters or less.
*
* can_stall Set to permit function to halt bulk endpoints.
* Disabled on some USB devices known not
* to work correctly. You should set it
* to true.
*
* If "removable" is not set for a LUN then a backing file must be
* specified. If it is set, then NULL filename means the LUN's medium
* is not loaded (an empty string as "filename" in the fsg_config
* structure causes error). The CD-ROM emulation includes a single
* data track and no audio tracks; hence there need be only one
* backing file per LUN.
*
* This function is heavily based on "File-backed Storage Gadget" by
* Alan Stern which in turn is heavily based on "Gadget Zero" by David
* Brownell. The driver's SCSI command interface was based on the
* "Information technology - Small Computer System Interface - 2"
* document from X3T9.2 Project 375D, Revision 10L, 7-SEP-93,
* available at <http://www.t10.org/ftp/t10/drafts/s2/s2-r10l.pdf>.
* The single exception is opcode 0x23 (READ FORMAT CAPACITIES), which
* was based on the "Universal Serial Bus Mass Storage Class UFI
* Command Specification" document, Revision 1.0, December 14, 1998,
* available at
* <http://www.usb.org/developers/devclass_docs/usbmass-ufi10.pdf>.
*/
/*
* Driver Design
*
* The MSF is fairly straightforward. There is a main kernel
* thread that handles most of the work. Interrupt routines field
* callbacks from the controller driver: bulk- and interrupt-request
* completion notifications, endpoint-0 events, and disconnect events.
* Completion events are passed to the main thread by wakeup calls. Many
* ep0 requests are handled at interrupt time, but SetInterface,
* SetConfiguration, and device reset requests are forwarded to the
* thread in the form of "exceptions" using SIGUSR1 signals (since they
* should interrupt any ongoing file I/O operations).
*
* The thread's main routine implements the standard command/data/status
* parts of a SCSI interaction. It and its subroutines are full of tests
* for pending signals/exceptions -- all this polling is necessary since
* the kernel has no setjmp/longjmp equivalents. (Maybe this is an
* indication that the driver really wants to be running in userspace.)
* An important point is that so long as the thread is alive it keeps an
* open reference to the backing file. This will prevent unmounting
* the backing file's underlying filesystem and could cause problems
* during system shutdown, for example. To prevent such problems, the
* thread catches INT, TERM, and KILL signals and converts them into
* an EXIT exception.
*
* In normal operation the main thread is started during the gadget's
* fsg_bind() callback and stopped during fsg_unbind(). But it can
* also exit when it receives a signal, and there's no point leaving
* the gadget running when the thread is dead. As of this moment, MSF
* provides no way to deregister the gadget when thread dies -- maybe
* a callback functions is needed.
*
* To provide maximum throughput, the driver uses a circular pipeline of
* buffer heads (struct fsg_buffhd). In principle the pipeline can be
* arbitrarily long; in practice the benefits don't justify having more
* than 2 stages (i.e., double buffering). But it helps to think of the
* pipeline as being a long one. Each buffer head contains a bulk-in and
* a bulk-out request pointer (since the buffer can be used for both
* output and input -- directions always are given from the host's
* point of view) as well as a pointer to the buffer and various state
* variables.
*
* Use of the pipeline follows a simple protocol. There is a variable
* (fsg->next_buffhd_to_fill) that points to the next buffer head to use.
* At any time that buffer head may still be in use from an earlier
* request, so each buffer head has a state variable indicating whether
* it is EMPTY, FULL, or BUSY. Typical use involves waiting for the
* buffer head to be EMPTY, filling the buffer either by file I/O or by
* USB I/O (during which the buffer head is BUSY), and marking the buffer
* head FULL when the I/O is complete. Then the buffer will be emptied
* (again possibly by USB I/O, during which it is marked BUSY) and
* finally marked EMPTY again (possibly by a completion routine).
*
* A module parameter tells the driver to avoid stalling the bulk
* endpoints wherever the transport specification allows. This is
* necessary for some UDCs like the SuperH, which cannot reliably clear a
* halt on a bulk endpoint. However, under certain circumstances the
* Bulk-only specification requires a stall. In such cases the driver
* will halt the endpoint and set a flag indicating that it should clear
* the halt in software during the next device reset. Hopefully this
* will permit everything to work correctly. Furthermore, although the
* specification allows the bulk-out endpoint to halt when the host sends
* too much data, implementing this would cause an unavoidable race.
* The driver will always use the "no-stall" approach for OUT transfers.
*
* One subtle point concerns sending status-stage responses for ep0
* requests. Some of these requests, such as device reset, can involve
* interrupting an ongoing file I/O operation, which might take an
* arbitrarily long time. During that delay the host might give up on
* the original ep0 request and issue a new one. When that happens the
* driver should not notify the host about completion of the original
* request, as the host will no longer be waiting for it. So the driver
* assigns to each ep0 request a unique tag, and it keeps track of the
* tag value of the request associated with a long-running exception
* (device-reset, interface-change, or configuration-change). When the
* exception handler is finished, the status-stage response is submitted
* only if the current ep0 request tag is equal to the exception request
* tag. Thus only the most recently received ep0 request will get a
* status-stage response.
*
* Warning: This driver source file is too long. It ought to be split up
* into a header file plus about 3 separate .c files, to handle the details
* of the Gadget, USB Mass Storage, and SCSI protocols.
*/
/* #define VERBOSE_DEBUG */
/* #define DUMP_MSGS */
#include <linux/blkdev.h>
#include <linux/completion.h>
#include <linux/dcache.h>
#include <linux/delay.h>
#include <linux/device.h>
#include <linux/fcntl.h>
#include <linux/file.h>
#include <linux/fs.h>
#include <linux/kref.h>
#include <linux/kthread.h>
#include <linux/limits.h>
#include <linux/rwsem.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/string.h>
#include <linux/freezer.h>
#include <linux/module.h>
#include <linux/usb/ch9.h>
#include <linux/usb/gadget.h>
#include <linux/usb/composite.h>
#include "gadget_chips.h"
#include "configfs.h"
/*------------------------------------------------------------------------*/
#define FSG_DRIVER_DESC "Mass Storage Function"
#define FSG_DRIVER_VERSION "2009/09/11"
static const char fsg_string_interface[] = "Mass Storage";
#include "storage_common.h"
#include "f_mass_storage.h"
/* Static strings, in UTF-8 (for simplicity we use only ASCII characters) */
static struct usb_string fsg_strings[] = {
{FSG_STRING_INTERFACE, fsg_string_interface},
{}
};
static struct usb_gadget_strings fsg_stringtab = {
.language = 0x0409, /* en-us */
.strings = fsg_strings,
};
static struct usb_gadget_strings *fsg_strings_array[] = {
&fsg_stringtab,
NULL,
};
/*-------------------------------------------------------------------------*/
/*
* If USB mass storage vfs operation is stuck for more than 10 sec
* host will initiate the reset. Configure the timer with 9 sec to print
* the error message before host is intiating the resume on it.
*/
#define MSC_VFS_TIMER_PERIOD_MS 9000
static int msc_vfs_timer_period_ms = MSC_VFS_TIMER_PERIOD_MS;
module_param(msc_vfs_timer_period_ms, int, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(msc_vfs_timer_period_ms, "Set period for MSC VFS timer");
static int write_error_after_csw_sent;
static int must_report_residue;
static int csw_sent;
struct fsg_dev;
struct fsg_common;
/* Data shared by all the FSG instances. */
struct fsg_common {
struct usb_gadget *gadget;
struct usb_composite_dev *cdev;
struct fsg_dev *fsg, *new_fsg;
wait_queue_head_t fsg_wait;
/* filesem protects: backing files in use */
struct rw_semaphore filesem;
/* lock protects: state, all the req_busy's */
spinlock_t lock;
struct usb_ep *ep0; /* Copy of gadget->ep0 */
struct usb_request *ep0req; /* Copy of cdev->req */
unsigned int ep0_req_tag;
struct fsg_buffhd *next_buffhd_to_fill;
struct fsg_buffhd *next_buffhd_to_drain;
struct fsg_buffhd *buffhds;
unsigned int fsg_num_buffers;
int cmnd_size;
u8 cmnd[MAX_COMMAND_SIZE];
unsigned int nluns;
unsigned int lun;
struct fsg_lun **luns;
struct fsg_lun *curlun;
unsigned int bulk_out_maxpacket;
enum fsg_state state; /* For exception handling */
unsigned int exception_req_tag;
enum data_direction data_dir;
u32 data_size;
u32 data_size_from_cmnd;
u32 tag;
u32 residue;
u32 usb_amount_left;
unsigned int can_stall:1;
unsigned int free_storage_on_release:1;
unsigned int phase_error:1;
unsigned int short_packet_received:1;
unsigned int bad_lun_okay:1;
unsigned int running:1;
unsigned int sysfs:1;
int thread_wakeup_needed;
struct completion thread_notifier;
struct task_struct *thread_task;
/* Callback functions. */
const struct fsg_operations *ops;
/* Gadget's private data. */
void *private_data;
char inquiry_string[INQUIRY_MAX_LEN];
/* LUN name for sysfs purpose */
char name[FSG_MAX_LUNS][LUN_NAME_LEN];
struct kref ref;
struct timer_list vfs_timer;
};
struct fsg_dev {
struct usb_function function;
struct usb_gadget *gadget; /* Copy of cdev->gadget */
struct fsg_common *common;
u16 interface_number;
unsigned int bulk_in_enabled:1;
unsigned int bulk_out_enabled:1;
unsigned long atomic_bitflags;
#define IGNORE_BULK_OUT 0
struct usb_ep *bulk_in;
struct usb_ep *bulk_out;
};
static void msc_usb_vfs_timer_func(unsigned long data)
{
struct fsg_common *common = (struct fsg_common *) data;
switch (common->data_dir) {
case DATA_DIR_FROM_HOST:
dev_err(&common->curlun->dev,
"usb mass storage stuck in vfs_write\n");
break;
case DATA_DIR_TO_HOST:
dev_err(&common->curlun->dev,
"usb mass storage stuck in vfs_read\n");
break;
default:
dev_err(&common->curlun->dev,
"usb mass storage stuck in vfs_sync\n");
break;
}
}
static inline int __fsg_is_set(struct fsg_common *common,
const char *func, unsigned line)
{
if (common->fsg)
return 1;
ERROR(common, "common->fsg is NULL in %s at %u\n", func, line);
WARN_ON(1);
return 0;
}
#define fsg_is_set(common) likely(__fsg_is_set(common, __func__, __LINE__))
static inline struct fsg_dev *fsg_from_func(struct usb_function *f)
{
return container_of(f, struct fsg_dev, function);
}
typedef void (*fsg_routine_t)(struct fsg_dev *);
static int send_status(struct fsg_common *common);
static int exception_in_progress(struct fsg_common *common)
{
return common->state > FSG_STATE_IDLE;
}
/* Make bulk-out requests be divisible by the maxpacket size */
static void set_bulk_out_req_length(struct fsg_common *common,
struct fsg_buffhd *bh, unsigned int length)
{
unsigned int rem;
bh->bulk_out_intended_length = length;
rem = length % common->bulk_out_maxpacket;
if (rem > 0)
length += common->bulk_out_maxpacket - rem;
bh->outreq->length = length;
}
/*-------------------------------------------------------------------------*/
static int fsg_set_halt(struct fsg_dev *fsg, struct usb_ep *ep)
{
const char *name;
if (ep == fsg->bulk_in)
name = "bulk-in";
else if (ep == fsg->bulk_out)
name = "bulk-out";
else
name = ep->name;
DBG(fsg, "%s set halt\n", name);
return usb_ep_set_halt(ep);
}
/*-------------------------------------------------------------------------*/
/* These routines may be called in process context or in_irq */
/* Caller must hold fsg->lock */
static void wakeup_thread(struct fsg_common *common)
{
smp_wmb(); /* ensure the write of bh->state is complete */
/* Tell the main thread that something has happened */
common->thread_wakeup_needed = 1;
if (common->thread_task)
wake_up_process(common->thread_task);
}
static void raise_exception(struct fsg_common *common, enum fsg_state new_state)
{
unsigned long flags;
/*
* Do nothing if a higher-priority exception is already in progress.
* If a lower-or-equal priority exception is in progress, preempt it
* and notify the main thread by sending it a signal.
*/
spin_lock_irqsave(&common->lock, flags);
if (common->state <= new_state) {
common->exception_req_tag = common->ep0_req_tag;
common->state = new_state;
if (common->thread_task)
send_sig_info(SIGUSR1, SEND_SIG_FORCED,
common->thread_task);
}
spin_unlock_irqrestore(&common->lock, flags);
}
/*-------------------------------------------------------------------------*/
static int ep0_queue(struct fsg_common *common)
{
int rc;
rc = usb_ep_queue(common->ep0, common->ep0req, GFP_ATOMIC);
common->ep0->driver_data = common;
if (rc != 0 && rc != -ESHUTDOWN) {
/* We can't do much more than wait for a reset */
WARNING(common, "error in submission: %s --> %d\n",
common->ep0->name, rc);
}
return rc;
}
/*-------------------------------------------------------------------------*/
/* Completion handlers. These always run in_irq. */
static void bulk_in_complete(struct usb_ep *ep, struct usb_request *req)
{
struct fsg_common *common = ep->driver_data;
struct fsg_buffhd *bh = req->context;
if (req->status || req->actual != req->length)
pr_debug("%s --> %d, %u/%u\n", __func__,
req->status, req->actual, req->length);
if (req->status == -ECONNRESET) /* Request was cancelled */
usb_ep_fifo_flush(ep);
/* Hold the lock while we update the request and buffer states */
smp_wmb();
/*
* Disconnect and completion might race each other and driver data
* is set to NULL during ep disable. So, add a check if that is case.
*/
if (!common) {
bh->inreq_busy = 0;
bh->state = BUF_STATE_EMPTY;
return;
}
spin_lock(&common->lock);
bh->inreq_busy = 0;
bh->state = BUF_STATE_EMPTY;
wakeup_thread(common);
spin_unlock(&common->lock);
}
static void bulk_out_complete(struct usb_ep *ep, struct usb_request *req)
{
struct fsg_common *common = ep->driver_data;
struct fsg_buffhd *bh = req->context;
dump_msg(common, "bulk-out", req->buf, req->actual);
if (req->status || req->actual != bh->bulk_out_intended_length)
DBG(common, "%s --> %d, %u/%u\n", __func__,
req->status, req->actual, bh->bulk_out_intended_length);
if (req->status == -ECONNRESET) /* Request was cancelled */
usb_ep_fifo_flush(ep);
/* Hold the lock while we update the request and buffer states */
smp_wmb();
spin_lock(&common->lock);
bh->outreq_busy = 0;
bh->state = BUF_STATE_FULL;
wakeup_thread(common);
spin_unlock(&common->lock);
}
static int fsg_setup(struct usb_function *f,
const struct usb_ctrlrequest *ctrl)
{
struct fsg_dev *fsg = fsg_from_func(f);
struct usb_request *req = fsg->common->ep0req;
u16 w_index = le16_to_cpu(ctrl->wIndex);
u16 w_value = le16_to_cpu(ctrl->wValue);
u16 w_length = le16_to_cpu(ctrl->wLength);
if (!fsg_is_set(fsg->common))
return -EOPNOTSUPP;
++fsg->common->ep0_req_tag; /* Record arrival of a new request */
req->context = NULL;
req->length = 0;
dump_msg(fsg, "ep0-setup", (u8 *) ctrl, sizeof(*ctrl));
switch (ctrl->bRequest) {
case US_BULK_RESET_REQUEST:
if (ctrl->bRequestType !=
(USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE))
break;
if (w_index != fsg->interface_number || w_value != 0 ||
w_length != 0)
return -EDOM;
/*
* Raise an exception to stop the current operation
* and reinitialize our state.
*/
DBG(fsg, "bulk reset request\n");
raise_exception(fsg->common, FSG_STATE_RESET);
return USB_GADGET_DELAYED_STATUS;
case US_BULK_GET_MAX_LUN:
if (ctrl->bRequestType !=
(USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE))
break;
if (w_index != fsg->interface_number || w_value != 0 ||
w_length != 1)
return -EDOM;
VDBG(fsg, "get max LUN\n");
*(u8 *)req->buf = fsg->common->nluns - 1;
/* Respond with data/status */
req->length = min((u16)1, w_length);
return ep0_queue(fsg->common);
}
VDBG(fsg,
"unknown class-specific control req %02x.%02x v%04x i%04x l%u\n",
ctrl->bRequestType, ctrl->bRequest,
le16_to_cpu(ctrl->wValue), w_index, w_length);
return -EOPNOTSUPP;
}
/*-------------------------------------------------------------------------*/
/* All the following routines run in process context */
/* Use this for bulk or interrupt transfers, not ep0 */
static void start_transfer(struct fsg_dev *fsg, struct usb_ep *ep,
struct usb_request *req, int *pbusy,
enum fsg_buffer_state *state)
{
int rc;
if (ep == fsg->bulk_in)
dump_msg(fsg, "bulk-in", req->buf, req->length);
spin_lock_irq(&fsg->common->lock);
*pbusy = 1;
*state = BUF_STATE_BUSY;
spin_unlock_irq(&fsg->common->lock);
rc = usb_ep_queue(ep, req, GFP_KERNEL);
if (rc == 0)
return; /* All good, we're done */
*pbusy = 0;
*state = BUF_STATE_EMPTY;
/* We can't do much more than wait for a reset */
/*
* Note: currently the net2280 driver fails zero-length
* submissions if DMA is enabled.
*/
if (rc != -ESHUTDOWN && !(rc == -EOPNOTSUPP && req->length == 0))
WARNING(fsg, "error in submission: %s --> %d\n", ep->name, rc);
}
static bool start_in_transfer(struct fsg_common *common, struct fsg_buffhd *bh)
{
if (!fsg_is_set(common))
return false;
start_transfer(common->fsg, common->fsg->bulk_in,
bh->inreq, &bh->inreq_busy, &bh->state);
return true;
}
static bool start_out_transfer(struct fsg_common *common, struct fsg_buffhd *bh)
{
if (!fsg_is_set(common))
return false;
start_transfer(common->fsg, common->fsg->bulk_out,
bh->outreq, &bh->outreq_busy, &bh->state);
return true;
}
static int sleep_thread(struct fsg_common *common, bool can_freeze)
{
int rc = 0;
/* Wait until a signal arrives or we are woken up */
for (;;) {
if (can_freeze)
try_to_freeze();
set_current_state(TASK_INTERRUPTIBLE);
if (signal_pending(current)) {
rc = -EINTR;
break;
}
spin_lock_irq(&common->lock);
if (common->thread_wakeup_needed) {
spin_unlock_irq(&common->lock);
break;
}
spin_unlock_irq(&common->lock);
schedule();
}
__set_current_state(TASK_RUNNING);
spin_lock_irq(&common->lock);
common->thread_wakeup_needed = 0;
spin_unlock_irq(&common->lock);
smp_rmb(); /* ensure the latest bh->state is visible */
return rc;
}
/*-------------------------------------------------------------------------*/
static int do_read(struct fsg_common *common)
{
struct fsg_lun *curlun = common->curlun;
u32 lba;
struct fsg_buffhd *bh;
int rc;
u32 amount_left;
loff_t file_offset, file_offset_tmp;
unsigned int amount;
ssize_t nread;
ktime_t start, diff;
/*
* Get the starting Logical Block Address and check that it's
* not too big.
*/
if (common->cmnd[0] == READ_6)
lba = get_unaligned_be24(&common->cmnd[1]);
else {
lba = get_unaligned_be32(&common->cmnd[2]);
/*
* We allow DPO (Disable Page Out = don't save data in the
* cache) and FUA (Force Unit Access = don't read from the
* cache), but we don't implement them.
*/
if ((common->cmnd[1] & ~0x18) != 0) {
curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
return -EINVAL;
}
}
if (lba >= curlun->num_sectors) {
curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
return -EINVAL;
}
file_offset = ((loff_t) lba) << curlun->blkbits;
/* Carry out the file reads */
amount_left = common->data_size_from_cmnd;
if (unlikely(amount_left == 0))
return -EIO; /* No default reply */
for (;;) {
/*
* Figure out how much we need to read:
* Try to read the remaining amount.
* But don't read more than the buffer size.
* And don't try to read past the end of the file.
*/
amount = min(amount_left, FSG_BUFLEN);
amount = min((loff_t)amount,
curlun->file_length - file_offset);
/* Wait for the next buffer to become available */
spin_lock_irq(&common->lock);
bh = common->next_buffhd_to_fill;
while (bh->state != BUF_STATE_EMPTY) {
spin_unlock_irq(&common->lock);
rc = sleep_thread(common, false);
if (rc)
return rc;
spin_lock_irq(&common->lock);
}
spin_unlock_irq(&common->lock);
/*
* If we were asked to read past the end of file,
* end with an empty buffer.
*/
if (amount == 0) {
curlun->sense_data =
SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
curlun->sense_data_info =
file_offset >> curlun->blkbits;
curlun->info_valid = 1;
spin_lock_irq(&common->lock);
bh->inreq->length = 0;
bh->state = BUF_STATE_FULL;
spin_unlock_irq(&common->lock);
break;
}
/* Perform the read */
file_offset_tmp = file_offset;
start = ktime_get();
mod_timer(&common->vfs_timer, jiffies +
msecs_to_jiffies(msc_vfs_timer_period_ms));
nread = vfs_read(curlun->filp,
(char __user *)bh->buf,
amount, &file_offset_tmp);
del_timer_sync(&common->vfs_timer);
VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
(unsigned long long)file_offset, (int)nread);
diff = ktime_sub(ktime_get(), start);
curlun->perf.rbytes += nread;
curlun->perf.rtime = ktime_add(curlun->perf.rtime, diff);
if (signal_pending(current))
return -EINTR;
if (nread < 0) {
LDBG(curlun, "error in file read: %d\n", (int)nread);
nread = 0;
} else if (nread < amount) {
LDBG(curlun, "partial file read: %d/%u\n",
(int)nread, amount);
nread = round_down(nread, curlun->blksize);
}
file_offset += nread;
amount_left -= nread;
common->residue -= nread;
/*
* Except at the end of the transfer, nread will be
* equal to the buffer size, which is divisible by the
* bulk-in maxpacket size.
*/
spin_lock_irq(&common->lock);
bh->inreq->length = nread;
bh->state = BUF_STATE_FULL;
spin_unlock_irq(&common->lock);
/* If an error occurred, report it and its position */
if (nread < amount) {
curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
curlun->sense_data_info =
file_offset >> curlun->blkbits;
curlun->info_valid = 1;
break;
}
if (amount_left == 0)
break; /* No more left to read */
/* Send this buffer and go read some more */
bh->inreq->zero = 0;
if (!start_in_transfer(common, bh))
/* Don't know what to do if common->fsg is NULL */
return -EIO;
common->next_buffhd_to_fill = bh->next;
}
return -EIO; /* No default reply */
}
/*-------------------------------------------------------------------------*/
static int do_write(struct fsg_common *common)
{
struct fsg_lun *curlun = common->curlun;
u32 lba;
struct fsg_buffhd *bh;
int get_some_more;
u32 amount_left_to_req, amount_left_to_write;
loff_t usb_offset, file_offset, file_offset_tmp;
unsigned int amount;
ssize_t nwritten;
ktime_t start, diff;
int rc, i;
if (curlun->ro) {
curlun->sense_data = SS_WRITE_PROTECTED;
return -EINVAL;
}
spin_lock(&curlun->filp->f_lock);
curlun->filp->f_flags &= ~O_SYNC; /* Default is not to wait */
spin_unlock(&curlun->filp->f_lock);
/*
* Get the starting Logical Block Address and check that it's
* not too big
*/
if (common->cmnd[0] == WRITE_6)
lba = get_unaligned_be24(&common->cmnd[1]);
else {
lba = get_unaligned_be32(&common->cmnd[2]);
/*
* We allow DPO (Disable Page Out = don't save data in the
* cache) and FUA (Force Unit Access = write directly to the
* medium). We don't implement DPO; we implement FUA by
* performing synchronous output.
*/
if (common->cmnd[1] & ~0x18) {
curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
return -EINVAL;
}
if (!curlun->nofua && (common->cmnd[1] & 0x08)) { /* FUA */
spin_lock(&curlun->filp->f_lock);
curlun->filp->f_flags |= O_SYNC;
spin_unlock(&curlun->filp->f_lock);
}
}
if (lba >= curlun->num_sectors) {
curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
return -EINVAL;
}
/* Carry out the file writes */
get_some_more = 1;
file_offset = usb_offset = ((loff_t) lba) << curlun->blkbits;
amount_left_to_req = common->data_size_from_cmnd;
amount_left_to_write = common->data_size_from_cmnd;
while (amount_left_to_write > 0) {
/* Queue a request for more data from the host */
bh = common->next_buffhd_to_fill;
if (bh->state == BUF_STATE_EMPTY && get_some_more) {
/*
* Figure out how much we want to get:
* Try to get the remaining amount,
* but not more than the buffer size.
*/
amount = min(amount_left_to_req, FSG_BUFLEN);
/* Beyond the end of the backing file? */
if (usb_offset >= curlun->file_length) {
get_some_more = 0;
curlun->sense_data =
SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
curlun->sense_data_info =
usb_offset >> curlun->blkbits;
curlun->info_valid = 1;
continue;
}
/* Get the next buffer */
usb_offset += amount;
common->usb_amount_left -= amount;
amount_left_to_req -= amount;
if (amount_left_to_req == 0)
get_some_more = 0;
/*
* Except at the end of the transfer, amount will be
* equal to the buffer size, which is divisible by
* the bulk-out maxpacket size.
*/
set_bulk_out_req_length(common, bh, amount);
if (!start_out_transfer(common, bh))
/* Dunno what to do if common->fsg is NULL */
return -EIO;
common->next_buffhd_to_fill = bh->next;
continue;
}
/* Write the received data to the backing file */
bh = common->next_buffhd_to_drain;
if (bh->state == BUF_STATE_EMPTY && !get_some_more)
break; /* We stopped early */
/*
* If the csw packet is already submmitted to the hardware,
* by marking the state of buffer as full, then by checking
* the residue, we make sure that this csw packet is not
* written on to the storage media.
*/
if (bh->state == BUF_STATE_FULL && common->residue) {
smp_rmb();
common->next_buffhd_to_drain = bh->next;
bh->state = BUF_STATE_EMPTY;
/* Did something go wrong with the transfer? */
if (bh->outreq->status != 0) {
curlun->sense_data = SS_COMMUNICATION_FAILURE;
curlun->sense_data_info =
file_offset >> curlun->blkbits;
curlun->info_valid = 1;
break;
}
amount = bh->outreq->actual;
if (curlun->file_length - file_offset < amount) {
LERROR(curlun,
"write %u @ %llu beyond end %llu\n",
amount, (unsigned long long)file_offset,
(unsigned long long)curlun->file_length);
amount = curlun->file_length - file_offset;
}
/* Don't accept excess data. The spec doesn't say
* what to do in this case. We'll ignore the error.
*/
amount = min(amount, bh->bulk_out_intended_length);
/* Don't write a partial block */
amount = round_down(amount, curlun->blksize);
if (amount == 0)
goto empty_write;
/* Perform the write */
file_offset_tmp = file_offset;
start = ktime_get();
mod_timer(&common->vfs_timer, jiffies +
msecs_to_jiffies(msc_vfs_timer_period_ms));
nwritten = vfs_write(curlun->filp,
(char __user *)bh->buf,
amount, &file_offset_tmp);
del_timer_sync(&common->vfs_timer);
VLDBG(curlun, "file write %u @ %llu -> %d\n", amount,
(unsigned long long)file_offset, (int)nwritten);
diff = ktime_sub(ktime_get(), start);
curlun->perf.wbytes += nwritten;
curlun->perf.wtime =
ktime_add(curlun->perf.wtime, diff);
if (signal_pending(current))
return -EINTR; /* Interrupted! */
if (nwritten < 0) {
LDBG(curlun, "error in file write: %d\n",
(int)nwritten);
nwritten = 0;
} else if (nwritten < amount) {
LDBG(curlun, "partial file write: %d/%u\n",
(int)nwritten, amount);
nwritten = round_down(nwritten, curlun->blksize);
}
file_offset += nwritten;
amount_left_to_write -= nwritten;
common->residue -= nwritten;
/* If an error occurred, report it and its position */
if (nwritten < amount) {
curlun->sense_data = SS_WRITE_ERROR;
curlun->sense_data_info =
file_offset >> curlun->blkbits;
curlun->info_valid = 1;
write_error_after_csw_sent = 1;
goto write_error;
break;
}
write_error:
if ((nwritten == amount) && !csw_sent) {
if (write_error_after_csw_sent)
break;
/*
* If residue still exists and nothing left to
* write, device must send correct residue to
* host in this case.
*/
if (!amount_left_to_write && common->residue) {
must_report_residue = 1;
break;
}
/*
* Check if any of the buffer is in the
* busy state, if any buffer is in busy state,
* means the complete data is not received
* yet from the host. So there is no point in
* csw right away without the complete data.
*/
for (i = 0; i < common->fsg_num_buffers; i++) {
if (common->buffhds[i].state ==
BUF_STATE_BUSY)
break;
}
if (!amount_left_to_req &&
i == common->fsg_num_buffers) {
csw_sent = 1;
send_status(common);
}
}
empty_write:
/* Did the host decide to stop early? */
if (bh->outreq->actual < bh->bulk_out_intended_length) {
common->short_packet_received = 1;
break;
}
continue;
}
/* Wait for something to happen */
rc = sleep_thread(common, false);
if (rc)
return rc;
}
return -EIO; /* No default reply */
}
/*-------------------------------------------------------------------------*/
static int do_synchronize_cache(struct fsg_common *common)
{
struct fsg_lun *curlun = common->curlun;
int rc;
/* We ignore the requested LBA and write out all file's
* dirty data buffers. */
mod_timer(&common->vfs_timer, jiffies +
msecs_to_jiffies(msc_vfs_timer_period_ms));
rc = fsg_lun_fsync_sub(curlun);
if (rc)
curlun->sense_data = SS_WRITE_ERROR;
del_timer_sync(&common->vfs_timer);
return 0;
}
/*-------------------------------------------------------------------------*/
static void invalidate_sub(struct fsg_lun *curlun)
{
struct file *filp = curlun->filp;
struct inode *inode = file_inode(filp);
unsigned long rc;
rc = invalidate_mapping_pages(inode->i_mapping, 0, -1);
VLDBG(curlun, "invalidate_mapping_pages -> %ld\n", rc);
}
static int do_verify(struct fsg_common *common)
{
struct fsg_lun *curlun = common->curlun;
u32 lba;
u32 verification_length;
struct fsg_buffhd *bh = common->next_buffhd_to_fill;
loff_t file_offset, file_offset_tmp;
u32 amount_left;
unsigned int amount;
ssize_t nread;
/*
* Get the starting Logical Block Address and check that it's
* not too big.
*/
lba = get_unaligned_be32(&common->cmnd[2]);
if (lba >= curlun->num_sectors) {
curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
return -EINVAL;
}
/*
* We allow DPO (Disable Page Out = don't save data in the
* cache) but we don't implement it.
*/
if (common->cmnd[1] & ~0x10) {
curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
return -EINVAL;
}
verification_length = get_unaligned_be16(&common->cmnd[7]);
if (unlikely(verification_length == 0))
return -EIO; /* No default reply */
/* Prepare to carry out the file verify */
amount_left = verification_length << curlun->blkbits;
file_offset = ((loff_t) lba) << curlun->blkbits;
/* Write out all the dirty buffers before invalidating them */
mod_timer(&common->vfs_timer, jiffies +
msecs_to_jiffies(msc_vfs_timer_period_ms));
fsg_lun_fsync_sub(curlun);
del_timer_sync(&common->vfs_timer);
if (signal_pending(current))
return -EINTR;
invalidate_sub(curlun);
if (signal_pending(current))
return -EINTR;
/* Just try to read the requested blocks */
while (amount_left > 0) {
/*
* Figure out how much we need to read:
* Try to read the remaining amount, but not more than
* the buffer size.
* And don't try to read past the end of the file.
*/
amount = min(amount_left, FSG_BUFLEN);
amount = min((loff_t)amount,
curlun->file_length - file_offset);
if (amount == 0) {
curlun->sense_data =
SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
curlun->sense_data_info =
file_offset >> curlun->blkbits;
curlun->info_valid = 1;
break;
}
/* Perform the read */
file_offset_tmp = file_offset;
mod_timer(&common->vfs_timer, jiffies +
msecs_to_jiffies(msc_vfs_timer_period_ms));
nread = vfs_read(curlun->filp,
(char __user *) bh->buf,
amount, &file_offset_tmp);
del_timer_sync(&common->vfs_timer);
VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
(unsigned long long) file_offset,
(int) nread);
if (signal_pending(current))
return -EINTR;
if (nread < 0) {
LDBG(curlun, "error in file verify: %d\n", (int)nread);
nread = 0;
} else if (nread < amount) {
LDBG(curlun, "partial file verify: %d/%u\n",
(int)nread, amount);
nread = round_down(nread, curlun->blksize);
}
if (nread == 0) {
curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
curlun->sense_data_info =
file_offset >> curlun->blkbits;
curlun->info_valid = 1;
break;
}
file_offset += nread;
amount_left -= nread;
}
return 0;
}
/*-------------------------------------------------------------------------*/
static int do_inquiry(struct fsg_common *common, struct fsg_buffhd *bh)
{
struct fsg_lun *curlun = common->curlun;
u8 *buf = (u8 *) bh->buf;
if (!curlun) { /* Unsupported LUNs are okay */
common->bad_lun_okay = 1;
memset(buf, 0, 36);
buf[0] = 0x7f; /* Unsupported, no device-type */
buf[4] = 31; /* Additional length */
return 36;
}
buf[0] = curlun->cdrom ? TYPE_ROM : TYPE_DISK;
buf[1] = curlun->removable ? 0x80 : 0;
buf[2] = 2; /* ANSI SCSI level 2 */
buf[3] = 2; /* SCSI-2 INQUIRY data format */
buf[4] = 31; /* Additional length */
buf[5] = 0; /* No special options */
buf[6] = 0;
buf[7] = 0;
memcpy(buf + 8, common->inquiry_string, sizeof common->inquiry_string);
return 36;
}
static int do_request_sense(struct fsg_common *common, struct fsg_buffhd *bh)
{
struct fsg_lun *curlun = common->curlun;
u8 *buf = (u8 *) bh->buf;
u32 sd, sdinfo;
int valid;
/*
* From the SCSI-2 spec., section 7.9 (Unit attention condition):
*
* If a REQUEST SENSE command is received from an initiator
* with a pending unit attention condition (before the target
* generates the contingent allegiance condition), then the
* target shall either:
* a) report any pending sense data and preserve the unit
* attention condition on the logical unit, or,
* b) report the unit attention condition, may discard any
* pending sense data, and clear the unit attention
* condition on the logical unit for that initiator.
*
* FSG normally uses option a); enable this code to use option b).
*/
#if 0
if (curlun && curlun->unit_attention_data != SS_NO_SENSE) {
curlun->sense_data = curlun->unit_attention_data;
curlun->unit_attention_data = SS_NO_SENSE;
}
#endif
if (!curlun) { /* Unsupported LUNs are okay */
common->bad_lun_okay = 1;
sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
sdinfo = 0;
valid = 0;
} else {
sd = curlun->sense_data;
sdinfo = curlun->sense_data_info;
valid = curlun->info_valid << 7;
curlun->sense_data = SS_NO_SENSE;
curlun->sense_data_info = 0;
curlun->info_valid = 0;
}
memset(buf, 0, 18);
buf[0] = valid | 0x70; /* Valid, current error */
buf[2] = SK(sd);
put_unaligned_be32(sdinfo, &buf[3]); /* Sense information */
buf[7] = 18 - 8; /* Additional sense length */
buf[12] = ASC(sd);
buf[13] = ASCQ(sd);
return 18;
}
static int do_read_capacity(struct fsg_common *common, struct fsg_buffhd *bh)
{
struct fsg_lun *curlun = common->curlun;
u32 lba = get_unaligned_be32(&common->cmnd[2]);
int pmi = common->cmnd[8];
u8 *buf = (u8 *)bh->buf;
/* Check the PMI and LBA fields */
if (pmi > 1 || (pmi == 0 && lba != 0)) {
curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
return -EINVAL;
}
put_unaligned_be32(curlun->num_sectors - 1, &buf[0]);
/* Max logical block */
put_unaligned_be32(curlun->blksize, &buf[4]);/* Block length */
return 8;
}
static int do_read_header(struct fsg_common *common, struct fsg_buffhd *bh)
{
struct fsg_lun *curlun = common->curlun;
int msf = common->cmnd[1] & 0x02;
u32 lba = get_unaligned_be32(&common->cmnd[2]);
u8 *buf = (u8 *)bh->buf;
if (common->cmnd[1] & ~0x02) { /* Mask away MSF */
curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
return -EINVAL;
}
if (lba >= curlun->num_sectors) {
curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
return -EINVAL;
}
memset(buf, 0, 8);
buf[0] = 0x01; /* 2048 bytes of user data, rest is EC */
store_cdrom_address(&buf[4], msf, lba);
return 8;
}
static int do_read_toc(struct fsg_common *common, struct fsg_buffhd *bh)
{
struct fsg_lun *curlun = common->curlun;
int msf = common->cmnd[1] & 0x02;
int start_track = common->cmnd[6];
u8 *buf = (u8 *)bh->buf;
if ((common->cmnd[1] & ~0x02) != 0 || /* Mask away MSF */
start_track > 1) {
curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
return -EINVAL;
}
memset(buf, 0, 20);
buf[1] = (20-2); /* TOC data length */
buf[2] = 1; /* First track number */
buf[3] = 1; /* Last track number */
buf[5] = 0x16; /* Data track, copying allowed */
buf[6] = 0x01; /* Only track is number 1 */
store_cdrom_address(&buf[8], msf, 0);
buf[13] = 0x16; /* Lead-out track is data */
buf[14] = 0xAA; /* Lead-out track number */
store_cdrom_address(&buf[16], msf, curlun->num_sectors);
return 20;
}
static int do_mode_sense(struct fsg_common *common, struct fsg_buffhd *bh)
{
struct fsg_lun *curlun = common->curlun;
int mscmnd = common->cmnd[0];
u8 *buf = (u8 *) bh->buf;
u8 *buf0 = buf;
int pc, page_code;
int changeable_values, all_pages;
int valid_page = 0;
int len, limit;
if ((common->cmnd[1] & ~0x08) != 0) { /* Mask away DBD */
curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
return -EINVAL;
}
pc = common->cmnd[2] >> 6;
page_code = common->cmnd[2] & 0x3f;
if (pc == 3) {
curlun->sense_data = SS_SAVING_PARAMETERS_NOT_SUPPORTED;
return -EINVAL;
}
changeable_values = (pc == 1);
all_pages = (page_code == 0x3f);
/*
* Write the mode parameter header. Fixed values are: default
* medium type, no cache control (DPOFUA), and no block descriptors.
* The only variable value is the WriteProtect bit. We will fill in
* the mode data length later.
*/
memset(buf, 0, 8);
if (mscmnd == MODE_SENSE) {
buf[2] = (curlun->ro ? 0x80 : 0x00); /* WP, DPOFUA */
buf += 4;
limit = 255;
} else { /* MODE_SENSE_10 */
buf[3] = (curlun->ro ? 0x80 : 0x00); /* WP, DPOFUA */
buf += 8;
limit = 65535; /* Should really be FSG_BUFLEN */
}
/* No block descriptors */
/*
* The mode pages, in numerical order. The only page we support
* is the Caching page.
*/
if (page_code == 0x08 || all_pages) {
valid_page = 1;
buf[0] = 0x08; /* Page code */
buf[1] = 10; /* Page length */
memset(buf+2, 0, 10); /* None of the fields are changeable */
if (!changeable_values) {
buf[2] = 0x04; /* Write cache enable, */
/* Read cache not disabled */
/* No cache retention priorities */
put_unaligned_be16(0xffff, &buf[4]);
/* Don't disable prefetch */
/* Minimum prefetch = 0 */
put_unaligned_be16(0xffff, &buf[8]);
/* Maximum prefetch */
put_unaligned_be16(0xffff, &buf[10]);
/* Maximum prefetch ceiling */
}
buf += 12;
}
/*
* Check that a valid page was requested and the mode data length
* isn't too long.
*/
len = buf - buf0;
if (!valid_page || len > limit) {
curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
return -EINVAL;
}
/* Store the mode data length */
if (mscmnd == MODE_SENSE)
buf0[0] = len - 1;
else
put_unaligned_be16(len - 2, buf0);
return len;
}
static int do_start_stop(struct fsg_common *common)
{
struct fsg_lun *curlun = common->curlun;
int loej, start;
if (!curlun) {
return -EINVAL;
} else if (!curlun->removable) {
curlun->sense_data = SS_INVALID_COMMAND;
return -EINVAL;
} else if ((common->cmnd[1] & ~0x01) != 0 || /* Mask away Immed */
(common->cmnd[4] & ~0x03) != 0) { /* Mask LoEj, Start */
curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
return -EINVAL;
}
loej = common->cmnd[4] & 0x02;
start = common->cmnd[4] & 0x01;
/*
* Our emulation doesn't support mounting; the medium is
* available for use as soon as it is loaded.
*/
if (start) {
if (!fsg_lun_is_open(curlun)) {
curlun->sense_data = SS_MEDIUM_NOT_PRESENT;
return -EINVAL;
}
return 0;
}
/* Are we allowed to unload the media? */
if (curlun->prevent_medium_removal) {
LDBG(curlun, "unload attempt prevented\n");
curlun->sense_data = SS_MEDIUM_REMOVAL_PREVENTED;
return -EINVAL;
}
if (!loej)
return 0;
up_read(&common->filesem);
down_write(&common->filesem);
fsg_lun_close(curlun);
up_write(&common->filesem);
down_read(&common->filesem);
return 0;
}
static int do_prevent_allow(struct fsg_common *common)
{
struct fsg_lun *curlun = common->curlun;
int prevent;
if (!common->curlun) {
return -EINVAL;
} else if (!common->curlun->removable) {
common->curlun->sense_data = SS_INVALID_COMMAND;
return -EINVAL;
}
prevent = common->cmnd[4] & 0x01;
if ((common->cmnd[4] & ~0x01) != 0) { /* Mask away Prevent */
curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
return -EINVAL;
}
if (!curlun->nofua && curlun->prevent_medium_removal && !prevent) {
mod_timer(&common->vfs_timer, jiffies +
msecs_to_jiffies(msc_vfs_timer_period_ms));
fsg_lun_fsync_sub(curlun);
del_timer_sync(&common->vfs_timer);
}
curlun->prevent_medium_removal = prevent;
return 0;
}
static int do_read_format_capacities(struct fsg_common *common,
struct fsg_buffhd *bh)
{
struct fsg_lun *curlun = common->curlun;
u8 *buf = (u8 *) bh->buf;
buf[0] = buf[1] = buf[2] = 0;
buf[3] = 8; /* Only the Current/Maximum Capacity Descriptor */
buf += 4;
put_unaligned_be32(curlun->num_sectors, &buf[0]);
/* Number of blocks */
put_unaligned_be32(curlun->blksize, &buf[4]);/* Block length */
buf[4] = 0x02; /* Current capacity */
return 12;
}
static int do_mode_select(struct fsg_common *common, struct fsg_buffhd *bh)
{
struct fsg_lun *curlun = common->curlun;
/* We don't support MODE SELECT */
if (curlun)
curlun->sense_data = SS_INVALID_COMMAND;
return -EINVAL;
}
/*-------------------------------------------------------------------------*/
static int halt_bulk_in_endpoint(struct fsg_dev *fsg)
{
int rc;
rc = fsg_set_halt(fsg, fsg->bulk_in);
if (rc == -EAGAIN)
VDBG(fsg, "delayed bulk-in endpoint halt\n");
while (rc != 0) {
if (rc != -EAGAIN) {
WARNING(fsg, "usb_ep_set_halt -> %d\n", rc);
rc = 0;
break;
}
/* Wait for a short time and then try again */
if (msleep_interruptible(100) != 0)
return -EINTR;
rc = usb_ep_set_halt(fsg->bulk_in);
}
return rc;
}
static int wedge_bulk_in_endpoint(struct fsg_dev *fsg)
{
int rc;
DBG(fsg, "bulk-in set wedge\n");
rc = usb_ep_set_wedge(fsg->bulk_in);
if (rc == -EAGAIN)
VDBG(fsg, "delayed bulk-in endpoint wedge\n");
while (rc != 0) {
if (rc != -EAGAIN) {
WARNING(fsg, "usb_ep_set_wedge -> %d\n", rc);
rc = 0;
break;
}
/* Wait for a short time and then try again */
if (msleep_interruptible(100) != 0)
return -EINTR;
rc = usb_ep_set_wedge(fsg->bulk_in);
}
return rc;
}
static int throw_away_data(struct fsg_common *common)
{
struct fsg_buffhd *bh;
u32 amount;
int rc;
for (bh = common->next_buffhd_to_drain;
bh->state != BUF_STATE_EMPTY || common->usb_amount_left > 0;
bh = common->next_buffhd_to_drain) {
/* Throw away the data in a filled buffer */
if (bh->state == BUF_STATE_FULL) {
smp_rmb();
bh->state = BUF_STATE_EMPTY;
common->next_buffhd_to_drain = bh->next;
/* A short packet or an error ends everything */
if (bh->outreq->actual < bh->bulk_out_intended_length ||
bh->outreq->status != 0) {
raise_exception(common,
FSG_STATE_ABORT_BULK_OUT);
return -EINTR;
}
continue;
}
/* Try to submit another request if we need one */
bh = common->next_buffhd_to_fill;
if (bh->state == BUF_STATE_EMPTY
&& common->usb_amount_left > 0) {
amount = min(common->usb_amount_left, FSG_BUFLEN);
/*
* Except at the end of the transfer, amount will be
* equal to the buffer size, which is divisible by
* the bulk-out maxpacket size.
*/
set_bulk_out_req_length(common, bh, amount);
if (!start_out_transfer(common, bh))
/* Dunno what to do if common->fsg is NULL */
return -EIO;
common->next_buffhd_to_fill = bh->next;
common->usb_amount_left -= amount;
continue;
}
/* Otherwise wait for something to happen */
rc = sleep_thread(common, true);
if (rc)
return rc;
}
return 0;
}
static int finish_reply(struct fsg_common *common)
{
struct fsg_buffhd *bh = common->next_buffhd_to_fill;
int rc = 0;
switch (common->data_dir) {
case DATA_DIR_NONE:
break; /* Nothing to send */
/*
* If we don't know whether the host wants to read or write,
* this must be CB or CBI with an unknown command. We mustn't
* try to send or receive any data. So stall both bulk pipes
* if we can and wait for a reset.
*/
case DATA_DIR_UNKNOWN:
if (!common->can_stall) {
/* Nothing */
} else if (fsg_is_set(common)) {
fsg_set_halt(common->fsg, common->fsg->bulk_out);
rc = halt_bulk_in_endpoint(common->fsg);
} else {
/* Don't know what to do if common->fsg is NULL */
rc = -EIO;
}
break;
/* All but the last buffer of data must have already been sent */
case DATA_DIR_TO_HOST:
if (common->data_size == 0) {
/* Nothing to send */
/* Don't know what to do if common->fsg is NULL */
} else if (!fsg_is_set(common)) {
rc = -EIO;
/* If there's no residue, simply send the last buffer */
} else if (common->residue == 0) {
bh->inreq->zero = 0;
if (!start_in_transfer(common, bh))
return -EIO;
common->next_buffhd_to_fill = bh->next;
/*
* For Bulk-only, mark the end of the data with a short
* packet. If we are allowed to stall, halt the bulk-in
* endpoint. (Note: This violates the Bulk-Only Transport
* specification, which requires us to pad the data if we
* don't halt the endpoint. Presumably nobody will mind.)
*/
} else {
bh->inreq->zero = 1;
if (!start_in_transfer(common, bh))
rc = -EIO;
common->next_buffhd_to_fill = bh->next;
if (common->can_stall)
rc = halt_bulk_in_endpoint(common->fsg);
}
break;
/*
* We have processed all we want from the data the host has sent.
* There may still be outstanding bulk-out requests.
*/
case DATA_DIR_FROM_HOST:
if (common->residue == 0) {
/* Nothing to receive */
/* Did the host stop sending unexpectedly early? */
} else if (common->short_packet_received) {
raise_exception(common, FSG_STATE_ABORT_BULK_OUT);
rc = -EINTR;
/*
* We haven't processed all the incoming data. Even though
* we may be allowed to stall, doing so would cause a race.
* The controller may already have ACK'ed all the remaining
* bulk-out packets, in which case the host wouldn't see a
* STALL. Not realizing the endpoint was halted, it wouldn't
* clear the halt -- leading to problems later on.
*/
#if 0
} else if (common->can_stall) {
if (fsg_is_set(common))
fsg_set_halt(common->fsg,
common->fsg->bulk_out);
raise_exception(common, FSG_STATE_ABORT_BULK_OUT);
rc = -EINTR;
#endif
/*
* We can't stall. Read in the excess data and throw it
* all away.
*/
} else {
rc = throw_away_data(common);
}
break;
}
return rc;
}
static int send_status(struct fsg_common *common)
{
struct fsg_lun *curlun = common->curlun;
struct fsg_buffhd *bh;
struct bulk_cs_wrap *csw;
int rc;
u8 status = US_BULK_STAT_OK;
u32 sd, sdinfo = 0;
/* Wait for the next buffer to become available */
spin_lock_irq(&common->lock);
bh = common->next_buffhd_to_fill;
while (bh->state != BUF_STATE_EMPTY) {
spin_unlock_irq(&common->lock);
rc = sleep_thread(common, true);
if (rc)
return rc;
spin_lock_irq(&common->lock);
}
spin_unlock_irq(&common->lock);
if (curlun) {
sd = curlun->sense_data;
sdinfo = curlun->sense_data_info;
} else if (common->bad_lun_okay)
sd = SS_NO_SENSE;
else
sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
if (common->phase_error) {
DBG(common, "sending phase-error status\n");
status = US_BULK_STAT_PHASE;
sd = SS_INVALID_COMMAND;
} else if (sd != SS_NO_SENSE) {
DBG(common, "sending command-failure status\n");
status = US_BULK_STAT_FAIL;
VDBG(common, " sense data: SK x%02x, ASC x%02x, ASCQ x%02x;"
" info x%x\n",
SK(sd), ASC(sd), ASCQ(sd), sdinfo);
}
/* Store and send the Bulk-only CSW */
csw = (void *)bh->buf;
csw->Signature = cpu_to_le32(US_BULK_CS_SIGN);
csw->Tag = common->tag;
csw->Residue = cpu_to_le32(common->residue);
/*
* Since csw is being sent early, before
* writing on to storage media, need to set
* residue to zero,assuming that write will succeed.
*/
if (write_error_after_csw_sent || must_report_residue) {
write_error_after_csw_sent = 0;
must_report_residue = 0;
}
else
csw->Residue = 0;
csw->Status = status;
bh->inreq->length = US_BULK_CS_WRAP_LEN;
bh->inreq->zero = 0;
if (!start_in_transfer(common, bh))
/* Don't know what to do if common->fsg is NULL */
return -EIO;
common->next_buffhd_to_fill = bh->next;
return 0;
}
/*-------------------------------------------------------------------------*/
/*
* Check whether the command is properly formed and whether its data size
* and direction agree with the values we already have.
*/
static int check_command(struct fsg_common *common, int cmnd_size,
enum data_direction data_dir, unsigned int mask,
int needs_medium, const char *name)
{
int i;
unsigned int lun = common->cmnd[1] >> 5;
static const char dirletter[4] = {'u', 'o', 'i', 'n'};
char hdlen[20];
struct fsg_lun *curlun;
hdlen[0] = 0;
if (common->data_dir != DATA_DIR_UNKNOWN)
sprintf(hdlen, ", H%c=%u", dirletter[(int) common->data_dir],
common->data_size);
VDBG(common, "SCSI command: %s; Dc=%d, D%c=%u; Hc=%d%s\n",
name, cmnd_size, dirletter[(int) data_dir],
common->data_size_from_cmnd, common->cmnd_size, hdlen);
/*
* We can't reply at all until we know the correct data direction
* and size.
*/
if (common->data_size_from_cmnd == 0)
data_dir = DATA_DIR_NONE;
if (common->data_size < common->data_size_from_cmnd) {
/*
* Host data size < Device data size is a phase error.
* Carry out the command, but only transfer as much as
* we are allowed.
*/
common->data_size_from_cmnd = common->data_size;
common->phase_error = 1;
}
common->residue = common->data_size;
common->usb_amount_left = common->data_size;
/* Conflicting data directions is a phase error */
if (common->data_dir != data_dir && common->data_size_from_cmnd > 0) {
common->phase_error = 1;
return -EINVAL;
}
/* Verify the length of the command itself */
if (cmnd_size != common->cmnd_size) {
/*
* Special case workaround: There are plenty of buggy SCSI
* implementations. Many have issues with cbw->Length
* field passing a wrong command size. For those cases we
* always try to work around the problem by using the length
* sent by the host side provided it is at least as large
* as the correct command length.
* Examples of such cases would be MS-Windows, which issues
* REQUEST SENSE with cbw->Length == 12 where it should
* be 6, and xbox360 issuing INQUIRY, TEST UNIT READY and
* REQUEST SENSE with cbw->Length == 10 where it should
* be 6 as well.
*/
if (cmnd_size <= common->cmnd_size) {
DBG(common, "%s is buggy! Expected length %d "
"but we got %d\n", name,
cmnd_size, common->cmnd_size);
cmnd_size = common->cmnd_size;
} else {
common->phase_error = 1;
return -EINVAL;
}
}
/* Check that the LUN values are consistent */
if (common->lun != lun)
DBG(common, "using LUN %u from CBW, not LUN %u from CDB\n",
common->lun, lun);
/* Check the LUN */
curlun = common->curlun;
if (curlun) {
if (common->cmnd[0] != REQUEST_SENSE) {
curlun->sense_data = SS_NO_SENSE;
curlun->sense_data_info = 0;
curlun->info_valid = 0;
}
} else {
common->bad_lun_okay = 0;
/*
* INQUIRY and REQUEST SENSE commands are explicitly allowed
* to use unsupported LUNs; all others may not.
*/
if (common->cmnd[0] != INQUIRY &&
common->cmnd[0] != REQUEST_SENSE) {
DBG(common, "unsupported LUN %u\n", common->lun);
return -EINVAL;
}
}
/*
* If a unit attention condition exists, only INQUIRY and
* REQUEST SENSE commands are allowed; anything else must fail.
*/
if (curlun && curlun->unit_attention_data != SS_NO_SENSE &&
common->cmnd[0] != INQUIRY &&
common->cmnd[0] != REQUEST_SENSE) {
curlun->sense_data = curlun->unit_attention_data;
curlun->unit_attention_data = SS_NO_SENSE;
return -EINVAL;
}
/* Check that only command bytes listed in the mask are non-zero */
common->cmnd[1] &= 0x1f; /* Mask away the LUN */
for (i = 1; i < cmnd_size; ++i) {
if (common->cmnd[i] && !(mask & (1 << i))) {
if (curlun)
curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
return -EINVAL;
}
}
/* If the medium isn't mounted and the command needs to access
* it, return an error. */
if (curlun && !fsg_lun_is_open(curlun) && needs_medium) {
curlun->sense_data = SS_MEDIUM_NOT_PRESENT;
return -EINVAL;
}
return 0;
}
/* wrapper of check_command for data size in blocks handling */
static int check_command_size_in_blocks(struct fsg_common *common,
int cmnd_size, enum data_direction data_dir,
unsigned int mask, int needs_medium, const char *name)
{
if (common->curlun)
common->data_size_from_cmnd <<= common->curlun->blkbits;
return check_command(common, cmnd_size, data_dir,
mask, needs_medium, name);
}
static int do_scsi_command(struct fsg_common *common)
{
struct fsg_buffhd *bh;
int rc;
int reply = -EINVAL;
int i;
static char unknown[16];
dump_cdb(common);
/* Wait for the next buffer to become available for data or status */
spin_lock_irq(&common->lock);
bh = common->next_buffhd_to_fill;
common->next_buffhd_to_drain = bh;
while (bh->state != BUF_STATE_EMPTY) {
spin_unlock_irq(&common->lock);
rc = sleep_thread(common, true);
if (rc)
return rc;
spin_lock_irq(&common->lock);
}
spin_unlock_irq(&common->lock);
common->phase_error = 0;
common->short_packet_received = 0;
down_read(&common->filesem); /* We're using the backing file */
switch (common->cmnd[0]) {
case INQUIRY:
common->data_size_from_cmnd = common->cmnd[4];
reply = check_command(common, 6, DATA_DIR_TO_HOST,
(1<<4), 0,
"INQUIRY");
if (reply == 0)
reply = do_inquiry(common, bh);
break;
case MODE_SELECT:
common->data_size_from_cmnd = common->cmnd[4];
reply = check_command(common, 6, DATA_DIR_FROM_HOST,
(1<<1) | (1<<4), 0,
"MODE SELECT(6)");
if (reply == 0)
reply = do_mode_select(common, bh);
break;
case MODE_SELECT_10:
common->data_size_from_cmnd =
get_unaligned_be16(&common->cmnd[7]);
reply = check_command(common, 10, DATA_DIR_FROM_HOST,
(1<<1) | (3<<7), 0,
"MODE SELECT(10)");
if (reply == 0)
reply = do_mode_select(common, bh);
break;
case MODE_SENSE:
common->data_size_from_cmnd = common->cmnd[4];
reply = check_command(common, 6, DATA_DIR_TO_HOST,
(1<<1) | (1<<2) | (1<<4), 0,
"MODE SENSE(6)");
if (reply == 0)
reply = do_mode_sense(common, bh);
break;
case MODE_SENSE_10:
common->data_size_from_cmnd =
get_unaligned_be16(&common->cmnd[7]);
reply = check_command(common, 10, DATA_DIR_TO_HOST,
(1<<1) | (1<<2) | (3<<7), 0,
"MODE SENSE(10)");
if (reply == 0)
reply = do_mode_sense(common, bh);
break;
case ALLOW_MEDIUM_REMOVAL:
common->data_size_from_cmnd = 0;
reply = check_command(common, 6, DATA_DIR_NONE,
(1<<4), 0,
"PREVENT-ALLOW MEDIUM REMOVAL");
if (reply == 0)
reply = do_prevent_allow(common);
break;
case READ_6:
i = common->cmnd[4];
common->data_size_from_cmnd = (i == 0) ? 256 : i;
reply = check_command_size_in_blocks(common, 6,
DATA_DIR_TO_HOST,
(7<<1) | (1<<4), 1,
"READ(6)");
if (reply == 0)
reply = do_read(common);
break;
case READ_10:
common->data_size_from_cmnd =
get_unaligned_be16(&common->cmnd[7]);
reply = check_command_size_in_blocks(common, 10,
DATA_DIR_TO_HOST,
(1<<1) | (0xf<<2) | (3<<7), 1,
"READ(10)");
if (reply == 0)
reply = do_read(common);
break;
case READ_12:
common->data_size_from_cmnd =
get_unaligned_be32(&common->cmnd[6]);
reply = check_command_size_in_blocks(common, 12,
DATA_DIR_TO_HOST,
(1<<1) | (0xf<<2) | (0xf<<6), 1,
"READ(12)");
if (reply == 0)
reply = do_read(common);
break;
case READ_CAPACITY:
common->data_size_from_cmnd = 8;
reply = check_command(common, 10, DATA_DIR_TO_HOST,
(0xf<<2) | (1<<8), 1,
"READ CAPACITY");
if (reply == 0)
reply = do_read_capacity(common, bh);
break;
case READ_HEADER:
if (!common->curlun || !common->curlun->cdrom)
goto unknown_cmnd;
common->data_size_from_cmnd =
get_unaligned_be16(&common->cmnd[7]);
reply = check_command(common, 10, DATA_DIR_TO_HOST,
(3<<7) | (0x1f<<1), 1,
"READ HEADER");
if (reply == 0)
reply = do_read_header(common, bh);
break;
case READ_TOC:
if (!common->curlun || !common->curlun->cdrom)
goto unknown_cmnd;
common->data_size_from_cmnd =
get_unaligned_be16(&common->cmnd[7]);
reply = check_command(common, 10, DATA_DIR_TO_HOST,
(7<<6) | (1<<1), 1,
"READ TOC");
if (reply == 0)
reply = do_read_toc(common, bh);
break;
case READ_FORMAT_CAPACITIES:
common->data_size_from_cmnd =
get_unaligned_be16(&common->cmnd[7]);
reply = check_command(common, 10, DATA_DIR_TO_HOST,
(3<<7), 1,
"READ FORMAT CAPACITIES");
if (reply == 0)
reply = do_read_format_capacities(common, bh);
break;
case REQUEST_SENSE:
common->data_size_from_cmnd = common->cmnd[4];
reply = check_command(common, 6, DATA_DIR_TO_HOST,
(1<<4), 0,
"REQUEST SENSE");
if (reply == 0)
reply = do_request_sense(common, bh);
break;
case START_STOP:
common->data_size_from_cmnd = 0;
reply = check_command(common, 6, DATA_DIR_NONE,
(1<<1) | (1<<4), 0,
"START-STOP UNIT");
if (reply == 0)
reply = do_start_stop(common);
break;
case SYNCHRONIZE_CACHE:
common->data_size_from_cmnd = 0;
reply = check_command(common, 10, DATA_DIR_NONE,
(0xf<<2) | (3<<7), 1,
"SYNCHRONIZE CACHE");
if (reply == 0)
reply = do_synchronize_cache(common);
break;
case TEST_UNIT_READY:
common->data_size_from_cmnd = 0;
reply = check_command(common, 6, DATA_DIR_NONE,
0, 1,
"TEST UNIT READY");
break;
/*
* Although optional, this command is used by MS-Windows. We
* support a minimal version: BytChk must be 0.
*/
case VERIFY:
common->data_size_from_cmnd = 0;
reply = check_command(common, 10, DATA_DIR_NONE,
(1<<1) | (0xf<<2) | (3<<7), 1,
"VERIFY");
if (reply == 0)
reply = do_verify(common);
break;
case WRITE_6:
i = common->cmnd[4];
common->data_size_from_cmnd = (i == 0) ? 256 : i;
reply = check_command_size_in_blocks(common, 6,
DATA_DIR_FROM_HOST,
(7<<1) | (1<<4), 1,
"WRITE(6)");
if (reply == 0)
reply = do_write(common);
break;
case WRITE_10:
common->data_size_from_cmnd =
get_unaligned_be16(&common->cmnd[7]);
reply = check_command_size_in_blocks(common, 10,
DATA_DIR_FROM_HOST,
(1<<1) | (0xf<<2) | (3<<7), 1,
"WRITE(10)");
if (reply == 0)
reply = do_write(common);
break;
case WRITE_12:
common->data_size_from_cmnd =
get_unaligned_be32(&common->cmnd[6]);
reply = check_command_size_in_blocks(common, 12,
DATA_DIR_FROM_HOST,
(1<<1) | (0xf<<2) | (0xf<<6), 1,
"WRITE(12)");
if (reply == 0)
reply = do_write(common);
break;
/*
* Some mandatory commands that we recognize but don't implement.
* They don't mean much in this setting. It's left as an exercise
* for anyone interested to implement RESERVE and RELEASE in terms
* of Posix locks.
*/
case FORMAT_UNIT:
case RELEASE:
case RESERVE:
case SEND_DIAGNOSTIC:
/* Fall through */
default:
unknown_cmnd:
common->data_size_from_cmnd = 0;
sprintf(unknown, "Unknown x%02x", common->cmnd[0]);
reply = check_command(common, common->cmnd_size,
DATA_DIR_UNKNOWN, ~0, 0, unknown);
if (reply == 0) {
common->curlun->sense_data = SS_INVALID_COMMAND;
reply = -EINVAL;
}
break;
}
up_read(&common->filesem);
if (reply == -EINTR || signal_pending(current))
return -EINTR;
/* Set up the single reply buffer for finish_reply() */
if (reply == -EINVAL)
reply = 0; /* Error reply length */
if (reply >= 0 && common->data_dir == DATA_DIR_TO_HOST) {
reply = min((u32)reply, common->data_size_from_cmnd);
bh->inreq->length = reply;
bh->state = BUF_STATE_FULL;
common->residue -= reply;
} /* Otherwise it's already set */
return 0;
}
/*-------------------------------------------------------------------------*/
static int received_cbw(struct fsg_dev *fsg, struct fsg_buffhd *bh)
{
struct usb_request *req = bh->outreq;
struct bulk_cb_wrap *cbw = req->buf;
struct fsg_common *common = fsg->common;
/* Was this a real packet? Should it be ignored? */
if (req->status || test_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags))
return -EINVAL;
/* Is the CBW valid? */
if (req->actual != US_BULK_CB_WRAP_LEN ||
cbw->Signature != cpu_to_le32(
US_BULK_CB_SIGN)) {
DBG(fsg, "invalid CBW: len %u sig 0x%x\n",
req->actual,
le32_to_cpu(cbw->Signature));
/*
* The Bulk-only spec says we MUST stall the IN endpoint
* (6.6.1), so it's unavoidable. It also says we must
* retain this state until the next reset, but there's
* no way to tell the controller driver it should ignore
* Clear-Feature(HALT) requests.
*
* We aren't required to halt the OUT endpoint; instead
* we can simply accept and discard any data received
* until the next reset.
*/
wedge_bulk_in_endpoint(fsg);
set_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags);
return -EINVAL;
}
/* Is the CBW meaningful? */
if (cbw->Lun >= FSG_MAX_LUNS || cbw->Flags & ~US_BULK_FLAG_IN ||
cbw->Length <= 0 || cbw->Length > MAX_COMMAND_SIZE) {
DBG(fsg, "non-meaningful CBW: lun = %u, flags = 0x%x, "
"cmdlen %u\n",
cbw->Lun, cbw->Flags, cbw->Length);
/*
* We can do anything we want here, so let's stall the
* bulk pipes if we are allowed to.
*/
if (common->can_stall) {
fsg_set_halt(fsg, fsg->bulk_out);
halt_bulk_in_endpoint(fsg);
}
return -EINVAL;
}
/* Save the command for later */
common->cmnd_size = cbw->Length;
memcpy(common->cmnd, cbw->CDB, common->cmnd_size);
if (cbw->Flags & US_BULK_FLAG_IN)
common->data_dir = DATA_DIR_TO_HOST;
else
common->data_dir = DATA_DIR_FROM_HOST;
common->data_size = le32_to_cpu(cbw->DataTransferLength);
if (common->data_size == 0)
common->data_dir = DATA_DIR_NONE;
common->lun = cbw->Lun;
if (common->lun < common->nluns)
common->curlun = common->luns[common->lun];
else
common->curlun = NULL;
common->tag = cbw->Tag;
return 0;
}
static int get_next_command(struct fsg_common *common)
{
struct fsg_buffhd *bh;
int rc = 0;
/* Wait for the next buffer to become available */
spin_lock_irq(&common->lock);
bh = common->next_buffhd_to_fill;
while (bh->state != BUF_STATE_EMPTY) {
spin_unlock_irq(&common->lock);
rc = sleep_thread(common, true);
if (rc)
return rc;
spin_lock_irq(&common->lock);
}
spin_unlock_irq(&common->lock);
/* Queue a request to read a Bulk-only CBW */
set_bulk_out_req_length(common, bh, US_BULK_CB_WRAP_LEN);
if (!start_out_transfer(common, bh))
/* Don't know what to do if common->fsg is NULL */
return -EIO;
/*
* We will drain the buffer in software, which means we
* can reuse it for the next filling. No need to advance
* next_buffhd_to_fill.
*/
/* Wait for the CBW to arrive */
spin_lock_irq(&common->lock);
while (bh->state != BUF_STATE_FULL) {
spin_unlock_irq(&common->lock);
rc = sleep_thread(common, true);
if (rc)
return rc;
spin_lock_irq(&common->lock);
}
spin_unlock_irq(&common->lock);
smp_rmb();
rc = fsg_is_set(common) ? received_cbw(common->fsg, bh) : -EIO;
spin_lock_irq(&common->lock);
bh->state = BUF_STATE_EMPTY;
spin_unlock_irq(&common->lock);
return rc;
}
/*-------------------------------------------------------------------------*/
static int alloc_request(struct fsg_common *common, struct usb_ep *ep,
struct usb_request **preq)
{
*preq = usb_ep_alloc_request(ep, GFP_ATOMIC);
if (*preq)
return 0;
ERROR(common, "can't allocate request for %s\n", ep->name);
return -ENOMEM;
}
/* Reset interface setting and re-init endpoint state (toggle etc). */
static int do_set_interface(struct fsg_common *common, struct fsg_dev *new_fsg)
{
struct fsg_dev *fsg;
int i, rc = 0;
if (common->running)
DBG(common, "reset interface\n");
reset:
/* Deallocate the requests */
if (common->fsg) {
fsg = common->fsg;
for (i = 0; i < common->fsg_num_buffers; ++i) {
struct fsg_buffhd *bh = &common->buffhds[i];
if (bh->inreq) {
usb_ep_free_request(fsg->bulk_in, bh->inreq);
bh->inreq = NULL;
}
if (bh->outreq) {
usb_ep_free_request(fsg->bulk_out, bh->outreq);
bh->outreq = NULL;
}
}
common->fsg = NULL;
wake_up(&common->fsg_wait);
}
common->running = 0;
if (!new_fsg || rc)
return rc;
common->fsg = new_fsg;
fsg = common->fsg;
/* Allocate the requests */
for (i = 0; i < common->fsg_num_buffers; ++i) {
struct fsg_buffhd *bh = &common->buffhds[i];
rc = alloc_request(common, fsg->bulk_in, &bh->inreq);
if (rc)
goto reset;
rc = alloc_request(common, fsg->bulk_out, &bh->outreq);
if (rc)
goto reset;
bh->inreq->buf = bh->outreq->buf = bh->buf;
bh->inreq->context = bh->outreq->context = bh;
bh->inreq->complete = bulk_in_complete;
bh->outreq->complete = bulk_out_complete;
}
common->running = 1;
for (i = 0; i < common->nluns; ++i)
if (common->luns[i])
common->luns[i]->unit_attention_data =
SS_RESET_OCCURRED;
return rc;
}
/****************************** ALT CONFIGS ******************************/
static int fsg_set_alt(struct usb_function *f, unsigned intf, unsigned alt)
{
struct fsg_dev *fsg = fsg_from_func(f);
struct fsg_common *common = fsg->common;
int rc;
/* Enable the endpoints */
rc = config_ep_by_speed(common->gadget, &(fsg->function), fsg->bulk_in);
if (rc)
goto err_exit;
rc = usb_ep_enable(fsg->bulk_in);
if (rc)
goto err_exit;
fsg->bulk_in->driver_data = common;
fsg->bulk_in_enabled = 1;
rc = config_ep_by_speed(common->gadget, &(fsg->function),
fsg->bulk_out);
if (rc)
goto reset_bulk_int;
rc = usb_ep_enable(fsg->bulk_out);
if (rc)
goto reset_bulk_int;
fsg->bulk_out->driver_data = common;
fsg->bulk_out_enabled = 1;
common->bulk_out_maxpacket = usb_endpoint_maxp(fsg->bulk_out->desc);
clear_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags);
csw_sent = 0;
write_error_after_csw_sent = 0;
fsg->common->new_fsg = fsg;
raise_exception(fsg->common, FSG_STATE_CONFIG_CHANGE);
return USB_GADGET_DELAYED_STATUS;
reset_bulk_int:
usb_ep_disable(fsg->bulk_in);
fsg->bulk_in_enabled = 0;
err_exit:
return rc;
}
static void fsg_disable(struct usb_function *f)
{
struct fsg_dev *fsg = fsg_from_func(f);
/* Disable the endpoints */
if (fsg->bulk_in_enabled) {
usb_ep_disable(fsg->bulk_in);
fsg->bulk_in->driver_data = NULL;
fsg->bulk_in_enabled = 0;
}
if (fsg->bulk_out_enabled) {
usb_ep_disable(fsg->bulk_out);
fsg->bulk_out->driver_data = NULL;
fsg->bulk_out_enabled = 0;
}
fsg->common->new_fsg = NULL;
raise_exception(fsg->common, FSG_STATE_CONFIG_CHANGE);
}
/*-------------------------------------------------------------------------*/
static void handle_exception(struct fsg_common *common)
{
siginfo_t info;
int i;
struct fsg_buffhd *bh;
enum fsg_state old_state;
struct fsg_lun *curlun;
unsigned int exception_req_tag;
unsigned long flags;
/*
* Clear the existing signals. Anything but SIGUSR1 is converted
* into a high-priority EXIT exception.
*/
for (;;) {
int sig =
dequeue_signal_lock(current, ¤t->blocked, &info);
if (!sig)
break;
if (sig != SIGUSR1) {
if (common->state < FSG_STATE_EXIT)
DBG(common, "Main thread exiting on signal\n");
WARN_ON(1);
pr_err("%s: signal(%d) received from PID(%d) UID(%d)\n",
__func__, sig, info.si_pid, info.si_uid);
raise_exception(common, FSG_STATE_EXIT);
}
}
/* Cancel all the pending transfers */
if (likely(common->fsg)) {
for (i = 0; i < common->fsg_num_buffers; ++i) {
bh = &common->buffhds[i];
if (bh->inreq_busy)
usb_ep_dequeue(common->fsg->bulk_in, bh->inreq);
if (bh->outreq_busy)
usb_ep_dequeue(common->fsg->bulk_out,
bh->outreq);
}
/* Wait until everything is idle */
for (;;) {
int num_active = 0;
spin_lock_irq(&common->lock);
for (i = 0; i < common->fsg_num_buffers; ++i) {
bh = &common->buffhds[i];
num_active += bh->inreq_busy + bh->outreq_busy;
}
spin_unlock_irq(&common->lock);
if (num_active == 0)
break;
if (sleep_thread(common, true))
return;
}
/* Clear out the controller's fifos */
if (common->fsg->bulk_in_enabled)
usb_ep_fifo_flush(common->fsg->bulk_in);
if (common->fsg->bulk_out_enabled)
usb_ep_fifo_flush(common->fsg->bulk_out);
}
/*
* Reset the I/O buffer states and pointers, the SCSI
* state, and the exception. Then invoke the handler.
*/
spin_lock_irqsave(&common->lock, flags);
for (i = 0; i < common->fsg_num_buffers; ++i) {
bh = &common->buffhds[i];
bh->state = BUF_STATE_EMPTY;
}
common->next_buffhd_to_fill = &common->buffhds[0];
common->next_buffhd_to_drain = &common->buffhds[0];
exception_req_tag = common->exception_req_tag;
old_state = common->state;
if (old_state == FSG_STATE_ABORT_BULK_OUT)
common->state = FSG_STATE_STATUS_PHASE;
else {
for (i = 0; i < common->nluns; ++i) {
curlun = common->luns[i];
if (!curlun)
continue;
curlun->prevent_medium_removal = 0;
curlun->sense_data = SS_NO_SENSE;
curlun->unit_attention_data = SS_NO_SENSE;
curlun->sense_data_info = 0;
curlun->info_valid = 0;
}
common->state = FSG_STATE_IDLE;
}
spin_unlock_irqrestore(&common->lock, flags);
/* Carry out any extra actions required for the exception */
switch (old_state) {
case FSG_STATE_ABORT_BULK_OUT:
send_status(common);
spin_lock_irq(&common->lock);
if (common->state == FSG_STATE_STATUS_PHASE)
common->state = FSG_STATE_IDLE;
spin_unlock_irq(&common->lock);
break;
case FSG_STATE_RESET:
/*
* In case we were forced against our will to halt a
* bulk endpoint, clear the halt now. (The SuperH UDC
* requires this.)
*/
if (!fsg_is_set(common))
break;
if (test_and_clear_bit(IGNORE_BULK_OUT,
&common->fsg->atomic_bitflags))
usb_ep_clear_halt(common->fsg->bulk_in);
if (common->ep0_req_tag == exception_req_tag) {
/* Complete the status stage */
if (common->cdev)
usb_composite_setup_continue(common->cdev);
else
ep0_queue(common);
}
/*
* Technically this should go here, but it would only be
* a waste of time. Ditto for the INTERFACE_CHANGE and
* CONFIG_CHANGE cases.
*/
/* for (i = 0; i < common->nluns; ++i) */
/* if (common->luns[i]) */
/* common->luns[i]->unit_attention_data = */
/* SS_RESET_OCCURRED; */
break;
case FSG_STATE_CONFIG_CHANGE:
do_set_interface(common, common->new_fsg);
if (common->new_fsg)
usb_composite_setup_continue(common->cdev);
break;
case FSG_STATE_EXIT:
case FSG_STATE_TERMINATED:
do_set_interface(common, NULL); /* Free resources */
spin_lock_irq(&common->lock);
common->state = FSG_STATE_TERMINATED; /* Stop the thread */
spin_unlock_irq(&common->lock);
break;
case FSG_STATE_INTERFACE_CHANGE:
case FSG_STATE_DISCONNECT:
case FSG_STATE_COMMAND_PHASE:
case FSG_STATE_DATA_PHASE:
case FSG_STATE_STATUS_PHASE:
case FSG_STATE_IDLE:
break;
}
}
/*-------------------------------------------------------------------------*/
static int fsg_main_thread(void *common_)
{
struct fsg_common *common = common_;
/*
* Allow the thread to be killed by a signal, but set the signal mask
* to block everything but INT, TERM, KILL, and USR1.
*/
allow_signal(SIGINT);
allow_signal(SIGTERM);
allow_signal(SIGKILL);
allow_signal(SIGUSR1);
/* Allow the thread to be frozen */
set_freezable();
/*
* Arrange for userspace references to be interpreted as kernel
* pointers. That way we can pass a kernel pointer to a routine
* that expects a __user pointer and it will work okay.
*/
set_fs(get_ds());
/* The main loop */
while (common->state != FSG_STATE_TERMINATED) {
if (exception_in_progress(common) || signal_pending(current)) {
handle_exception(common);
continue;
}
if (!common->running) {
sleep_thread(common, true);
continue;
}
if (get_next_command(common))
continue;
spin_lock_irq(&common->lock);
if (!exception_in_progress(common))
common->state = FSG_STATE_DATA_PHASE;
spin_unlock_irq(&common->lock);
if (do_scsi_command(common) || finish_reply(common))
continue;
spin_lock_irq(&common->lock);
if (!exception_in_progress(common))
common->state = FSG_STATE_STATUS_PHASE;
spin_unlock_irq(&common->lock);
/*
* Since status is already sent for write scsi command,
* need to skip sending status once again if it is a
* write scsi command.
*/
if (csw_sent) {
csw_sent = 0;
continue;
}
if (send_status(common))
continue;
spin_lock_irq(&common->lock);
if (!exception_in_progress(common))
common->state = FSG_STATE_IDLE;
spin_unlock_irq(&common->lock);
}
spin_lock_irq(&common->lock);
common->thread_task = NULL;
spin_unlock_irq(&common->lock);
if (!common->ops || !common->ops->thread_exits
|| common->ops->thread_exits(common) < 0) {
struct fsg_lun **curlun_it = common->luns;
unsigned i = common->nluns;
down_write(&common->filesem);
for (; i--; ++curlun_it) {
struct fsg_lun *curlun = *curlun_it;
if (!curlun || !fsg_lun_is_open(curlun))
continue;
fsg_lun_close(curlun);
curlun->unit_attention_data = SS_MEDIUM_NOT_PRESENT;
}
up_write(&common->filesem);
}
/* Let fsg_unbind() know the thread has exited */
complete_and_exit(&common->thread_notifier, 0);
}
/*************************** DEVICE ATTRIBUTES ***************************/
static ssize_t ro_show(struct device *dev, struct device_attribute *attr, char *buf)
{
struct fsg_lun *curlun = fsg_lun_from_dev(dev);
return fsg_show_ro(curlun, buf);
}
static ssize_t nofua_show(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct fsg_lun *curlun = fsg_lun_from_dev(dev);
return fsg_show_nofua(curlun, buf);
}
static ssize_t file_show(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct fsg_lun *curlun = fsg_lun_from_dev(dev);
struct rw_semaphore *filesem = dev_get_drvdata(dev);
return fsg_show_file(curlun, filesem, buf);
}
static ssize_t ro_store(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct fsg_lun *curlun = fsg_lun_from_dev(dev);
struct rw_semaphore *filesem = dev_get_drvdata(dev);
return fsg_store_ro(curlun, filesem, buf, count);
}
static ssize_t nofua_store(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct fsg_lun *curlun = fsg_lun_from_dev(dev);
return fsg_store_nofua(curlun, buf, count);
}
static ssize_t file_store(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct fsg_lun *curlun = fsg_lun_from_dev(dev);
struct rw_semaphore *filesem = dev_get_drvdata(dev);
return fsg_store_file(curlun, filesem, buf, count);
}
static DEVICE_ATTR_RW(ro);
static DEVICE_ATTR_RW(nofua);
static DEVICE_ATTR_RW(file);
static DEVICE_ATTR(perf, 0644, fsg_show_perf, fsg_store_perf);
static struct device_attribute dev_attr_ro_cdrom = __ATTR_RO(ro);
static struct device_attribute dev_attr_file_nonremovable = __ATTR_RO(file);
/****************************** FSG COMMON ******************************/
static void fsg_common_release(struct kref *ref);
static void fsg_lun_release(struct device *dev)
{
/* Nothing needs to be done */
}
void fsg_common_get(struct fsg_common *common)
{
kref_get(&common->ref);
}
EXPORT_SYMBOL_GPL(fsg_common_get);
void fsg_common_put(struct fsg_common *common)
{
kref_put(&common->ref, fsg_common_release);
}
EXPORT_SYMBOL_GPL(fsg_common_put);
/* check if fsg_num_buffers is within a valid range */
static inline int fsg_num_buffers_validate(unsigned int fsg_num_buffers)
{
if (fsg_num_buffers >= 2 && fsg_num_buffers <= 4)
return 0;
pr_err("fsg_num_buffers %u is out of range (%d to %d)\n",
fsg_num_buffers, 2, 4);
return -EINVAL;
}
static struct fsg_common *fsg_common_setup(struct fsg_common *common)
{
if (!common) {
common = kzalloc(sizeof(*common), GFP_KERNEL);
if (!common)
return ERR_PTR(-ENOMEM);
common->free_storage_on_release = 1;
} else {
common->free_storage_on_release = 0;
}
init_rwsem(&common->filesem);
spin_lock_init(&common->lock);
kref_init(&common->ref);
init_completion(&common->thread_notifier);
init_waitqueue_head(&common->fsg_wait);
common->state = FSG_STATE_TERMINATED;
return common;
}
void fsg_common_set_sysfs(struct fsg_common *common, bool sysfs)
{
common->sysfs = sysfs;
}
EXPORT_SYMBOL_GPL(fsg_common_set_sysfs);
static void _fsg_common_free_buffers(struct fsg_buffhd *buffhds, unsigned n)
{
if (buffhds) {
struct fsg_buffhd *bh = buffhds;
while (n--) {
kfree(bh->buf);
++bh;
}
kfree(buffhds);
}
}
int fsg_common_set_num_buffers(struct fsg_common *common, unsigned int n)
{
struct fsg_buffhd *bh, *buffhds;
int i, rc;
size_t extra_buf_alloc = 0;
if (common->gadget)
extra_buf_alloc = common->gadget->extra_buf_alloc;
rc = fsg_num_buffers_validate(n);
if (rc != 0)
return rc;
buffhds = kcalloc(n, sizeof(*buffhds), GFP_KERNEL);
if (!buffhds)
return -ENOMEM;
/* Data buffers cyclic list */
bh = buffhds;
i = n;
goto buffhds_first_it;
do {
bh->next = bh + 1;
++bh;
buffhds_first_it:
bh->buf = kmalloc(FSG_BUFLEN + extra_buf_alloc,
GFP_KERNEL);
if (unlikely(!bh->buf))
goto error_release;
} while (--i);
bh->next = buffhds;
_fsg_common_free_buffers(common->buffhds, common->fsg_num_buffers);
common->fsg_num_buffers = n;
common->buffhds = buffhds;
return 0;
error_release:
/*
* "buf"s pointed to by heads after n - i are NULL
* so releasing them won't hurt
*/
_fsg_common_free_buffers(buffhds, n);
return -ENOMEM;
}
EXPORT_SYMBOL_GPL(fsg_common_set_num_buffers);
static inline void fsg_common_remove_sysfs(struct fsg_lun *lun)
{
device_remove_file(&lun->dev, &dev_attr_nofua);
/*
* device_remove_file() =>
*
* here the attr (e.g. dev_attr_ro) is only used to be passed to:
*
* sysfs_remove_file() =>
*
* here e.g. both dev_attr_ro_cdrom and dev_attr_ro are in
* the same namespace and
* from here only attr->name is passed to:
*
* sysfs_hash_and_remove()
*
* attr->name is the same for dev_attr_ro_cdrom and
* dev_attr_ro
* attr->name is the same for dev_attr_file and
* dev_attr_file_nonremovable
*
* so we don't differentiate between removing e.g. dev_attr_ro_cdrom
* and dev_attr_ro
*/
device_remove_file(&lun->dev, &dev_attr_ro);
device_remove_file(&lun->dev, &dev_attr_file);
device_remove_file(&lun->dev, &dev_attr_perf);
}
void fsg_common_remove_lun(struct fsg_lun *lun, bool sysfs)
{
if (sysfs) {
fsg_common_remove_sysfs(lun);
device_unregister(&lun->dev);
}
fsg_lun_close(lun);
kfree(lun);
}
EXPORT_SYMBOL_GPL(fsg_common_remove_lun);
static void _fsg_common_remove_luns(struct fsg_common *common, int n)
{
int i;
for (i = 0; i < n; ++i)
if (common->luns[i]) {
fsg_common_remove_lun(common->luns[i], common->sysfs);
common->luns[i] = NULL;
}
}
EXPORT_SYMBOL_GPL(fsg_common_remove_luns);
void fsg_common_remove_luns(struct fsg_common *common)
{
_fsg_common_remove_luns(common, common->nluns);
}
void fsg_common_free_luns(struct fsg_common *common)
{
unsigned long flags;
fsg_common_remove_luns(common);
spin_lock_irqsave(&common->lock, flags);
kfree(common->luns);
common->luns = NULL;
common->nluns = 0;
spin_unlock_irqrestore(&common->lock, flags);
}
EXPORT_SYMBOL_GPL(fsg_common_free_luns);
int fsg_common_set_nluns(struct fsg_common *common, int nluns)
{
struct fsg_lun **curlun;
/* Find out how many LUNs there should be */
if (nluns < 1 || nluns > FSG_MAX_LUNS) {
pr_err("invalid number of LUNs: %u\n", nluns);
return -EINVAL;
}
curlun = kcalloc(nluns, sizeof(*curlun), GFP_KERNEL);
if (unlikely(!curlun))
return -ENOMEM;
if (common->luns)
fsg_common_free_luns(common);
common->luns = curlun;
common->nluns = nluns;
pr_info("Number of LUNs=%d\n", common->nluns);
return 0;
}
EXPORT_SYMBOL_GPL(fsg_common_set_nluns);
void fsg_common_set_ops(struct fsg_common *common,
const struct fsg_operations *ops)
{
common->ops = ops;
}
EXPORT_SYMBOL_GPL(fsg_common_set_ops);
void fsg_common_free_buffers(struct fsg_common *common)
{
_fsg_common_free_buffers(common->buffhds, common->fsg_num_buffers);
common->buffhds = NULL;
}
EXPORT_SYMBOL_GPL(fsg_common_free_buffers);
int fsg_common_set_cdev(struct fsg_common *common,
struct usb_composite_dev *cdev, bool can_stall)
{
struct usb_string *us;
common->gadget = cdev->gadget;
common->ep0 = cdev->gadget->ep0;
common->ep0req = cdev->req;
common->cdev = cdev;
us = usb_gstrings_attach(cdev, fsg_strings_array,
ARRAY_SIZE(fsg_strings));
if (IS_ERR(us))
return PTR_ERR(us);
fsg_intf_desc.iInterface = us[FSG_STRING_INTERFACE].id;
/*
* Some peripheral controllers are known not to be able to
* halt bulk endpoints correctly. If one of them is present,
* disable stalls.
*/
common->can_stall = can_stall && !(gadget_is_at91(common->gadget));
return 0;
}
EXPORT_SYMBOL_GPL(fsg_common_set_cdev);
static inline int fsg_common_add_sysfs(struct fsg_common *common,
struct fsg_lun *lun)
{
int rc;
rc = device_register(&lun->dev);
if (rc) {
put_device(&lun->dev);
return rc;
}
rc = device_create_file(&lun->dev,
lun->cdrom
? &dev_attr_ro_cdrom
: &dev_attr_ro);
if (rc)
goto error;
rc = device_create_file(&lun->dev,
lun->removable
? &dev_attr_file
: &dev_attr_file_nonremovable);
if (rc)
goto error;
rc = device_create_file(&lun->dev, &dev_attr_nofua);
if (rc)
goto error;
rc = device_create_file(&lun->dev, &dev_attr_perf);
if (rc)
pr_err("failed to create sysfs entry: %d\n", rc);
return 0;
error:
/* removing nonexistent files is a no-op */
fsg_common_remove_sysfs(lun);
device_unregister(&lun->dev);
return rc;
}
int fsg_common_create_lun(struct fsg_common *common, struct fsg_lun_config *cfg,
unsigned int id, const char *name,
const char **name_pfx)
{
struct fsg_lun *lun;
char *pathbuf, *p;
int rc = -ENOMEM;
if (!common->nluns || !common->luns)
return -ENODEV;
if (common->luns[id])
return -EBUSY;
#ifdef CONFIG_ZTEMT_USB
if (!cfg->filename && !cfg->removable && !cfg->cdrom) {
#else
if (!cfg->filename && !cfg->removable) {
#endif
pr_err("no file given for LUN%d\n", id);
return -EINVAL;
}
lun = kzalloc(sizeof(*lun), GFP_KERNEL);
if (!lun)
return -ENOMEM;
lun->name_pfx = name_pfx;
lun->cdrom = !!cfg->cdrom;
lun->ro = cfg->cdrom || cfg->ro;
lun->initially_ro = lun->ro;
lun->removable = !!cfg->removable;
if (!common->sysfs) {
/* we DON'T own the name!*/
lun->name = name;
} else {
lun->dev.release = fsg_lun_release;
lun->dev.parent = &common->gadget->dev;
dev_set_drvdata(&lun->dev, &common->filesem);
dev_set_name(&lun->dev, "%s", name);
lun->name = dev_name(&lun->dev);
rc = fsg_common_add_sysfs(common, lun);
if (rc) {
pr_info("failed to register LUN%d: %d\n", id, rc);
goto error_sysfs;
}
}
common->luns[id] = lun;
if (cfg->filename) {
rc = fsg_lun_open(lun, cfg->filename);
if (rc)
goto error_lun;
}
pathbuf = kmalloc(PATH_MAX, GFP_KERNEL);
p = "(no medium)";
if (fsg_lun_is_open(lun)) {
p = "(error)";
if (pathbuf) {
p = d_path(&lun->filp->f_path, pathbuf, PATH_MAX);
if (IS_ERR(p))
p = "(error)";
}
}
pr_info("LUN: %s%s%sfile: %s\n",
lun->removable ? "removable " : "",
lun->ro ? "read only " : "",
lun->cdrom ? "CD-ROM " : "",
p);
kfree(pathbuf);
return 0;
error_lun:
if (common->sysfs) {
fsg_common_remove_sysfs(lun);
device_unregister(&lun->dev);
}
fsg_lun_close(lun);
common->luns[id] = NULL;
error_sysfs:
kfree(lun);
return rc;
}
EXPORT_SYMBOL_GPL(fsg_common_create_lun);
int fsg_common_create_luns(struct fsg_common *common, struct fsg_config *cfg)
{
char buf[8]; /* enough for 100000000 different numbers, decimal */
int i, rc;
for (i = 0; i < common->nluns; ++i) {
snprintf(buf, sizeof(buf), "lun%d", i);
rc = fsg_common_create_lun(common, &cfg->luns[i], i, buf, NULL);
if (rc)
goto fail;
}
pr_info("Number of LUNs=%d\n", common->nluns);
return 0;
fail:
_fsg_common_remove_luns(common, i);
return rc;
}
EXPORT_SYMBOL_GPL(fsg_common_create_luns);
void fsg_common_set_inquiry_string(struct fsg_common *common, const char *vn,
const char *pn)
{
int i;
/* Prepare inquiryString */
i = get_default_bcdDevice();
snprintf(common->inquiry_string, sizeof(common->inquiry_string),
"%-8s%-16s%04x", vn ?: "Linux",
/* Assume product name dependent on the first LUN */
pn ?: ((*common->luns)->cdrom
? "File-CD Gadget"
: "File-Stor Gadget"),
i);
}
EXPORT_SYMBOL_GPL(fsg_common_set_inquiry_string);
int fsg_common_run_thread(struct fsg_common *common)
{
common->state = FSG_STATE_IDLE;
/* Tell the thread to start working */
common->thread_task =
kthread_create(fsg_main_thread, common, "file-storage");
if (IS_ERR(common->thread_task)) {
common->state = FSG_STATE_TERMINATED;
return PTR_ERR(common->thread_task);
}
DBG(common, "I/O thread pid: %d\n", task_pid_nr(common->thread_task));
wake_up_process(common->thread_task);
return 0;
}
EXPORT_SYMBOL_GPL(fsg_common_run_thread);
static void fsg_common_release(struct kref *ref)
{
struct fsg_common *common = container_of(ref, struct fsg_common, ref);
/* If the thread isn't already dead, tell it to exit now */
if (common->state != FSG_STATE_TERMINATED) {
raise_exception(common, FSG_STATE_EXIT);
wait_for_completion(&common->thread_notifier);
}
if (likely(common->luns)) {
struct fsg_lun **lun_it = common->luns;
unsigned i = common->nluns;
/* In error recovery common->nluns may be zero. */
for (; i; --i, ++lun_it) {
struct fsg_lun *lun = *lun_it;
if (!lun)
continue;
if (common->sysfs)
fsg_common_remove_sysfs(lun);
fsg_lun_close(lun);
if (common->sysfs)
device_unregister(&lun->dev);
kfree(lun);
}
kfree(common->luns);
}
_fsg_common_free_buffers(common->buffhds, common->fsg_num_buffers);
if (common->free_storage_on_release)
kfree(common);
}
int fsg_sysfs_update(struct fsg_common *common, struct device *dev, bool create)
{
int ret = 0, i;
pr_debug("%s(): common->nluns:%d\n", __func__, common->nluns);
if (create) {
for (i = 0; i < common->nluns; i++) {
if (i == 0)
snprintf(common->name[i], 8, "lun");
else
snprintf(common->name[i], 8, "lun%d", i-1);
ret = sysfs_create_link(&dev->kobj,
&common->luns[i]->dev.kobj,
common->name[i]);
if (ret) {
pr_err("%s(): failed creating sysfs:%d %s)\n",
__func__, i, common->name[i]);
goto remove_sysfs;
}
}
} else {
i = common->nluns;
goto remove_sysfs;
}
return 0;
remove_sysfs:
for (; i > 0; i--) {
pr_debug("%s(): delete sysfs for lun(id:%d)(name:%s)\n",
__func__, i, common->name[i-1]);
sysfs_remove_link(&dev->kobj, common->name[i-1]);
}
return ret;
}
EXPORT_SYMBOL(fsg_sysfs_update);
/*-------------------------------------------------------------------------*/
static int fsg_bind(struct usb_configuration *c, struct usb_function *f)
{
struct fsg_dev *fsg = fsg_from_func(f);
struct usb_gadget *gadget = c->cdev->gadget;
int i;
struct usb_ep *ep;
unsigned max_burst;
int ret;
struct fsg_opts *opts;
opts = fsg_opts_from_func_inst(f->fi);
if (!opts->no_configfs) {
ret = fsg_common_set_cdev(fsg->common, c->cdev,
fsg->common->can_stall);
if (ret)
return ret;
#ifdef CONFIG_ZTEMT_USB
fsg_common_set_inquiry_string(fsg->common, "nubia", "Android");
#else
fsg_common_set_inquiry_string(fsg->common, NULL, NULL);
#endif
ret = fsg_common_run_thread(fsg->common);
if (ret)
return ret;
}
fsg->gadget = gadget;
/* New interface */
i = usb_interface_id(c, f);
if (i < 0)
return i;
fsg_intf_desc.bInterfaceNumber = i;
fsg->interface_number = i;
/* Find all the endpoints we will use */
ep = usb_ep_autoconfig(gadget, &fsg_fs_bulk_in_desc);
if (!ep)
goto autoconf_fail;
ep->driver_data = fsg->common; /* claim the endpoint */
fsg->bulk_in = ep;
ep = usb_ep_autoconfig(gadget, &fsg_fs_bulk_out_desc);
if (!ep)
goto autoconf_fail;
ep->driver_data = fsg->common; /* claim the endpoint */
fsg->bulk_out = ep;
/* Assume endpoint addresses are the same for both speeds */
fsg_hs_bulk_in_desc.bEndpointAddress =
fsg_fs_bulk_in_desc.bEndpointAddress;
fsg_hs_bulk_out_desc.bEndpointAddress =
fsg_fs_bulk_out_desc.bEndpointAddress;
/* Calculate bMaxBurst, we know packet size is 1024 */
max_burst = min_t(unsigned, FSG_BUFLEN / 1024, 15);
fsg_ss_bulk_in_desc.bEndpointAddress =
fsg_fs_bulk_in_desc.bEndpointAddress;
fsg_ss_bulk_in_comp_desc.bMaxBurst = max_burst;
fsg_ss_bulk_out_desc.bEndpointAddress =
fsg_fs_bulk_out_desc.bEndpointAddress;
fsg_ss_bulk_out_comp_desc.bMaxBurst = max_burst;
ret = usb_assign_descriptors(f, fsg_fs_function, fsg_hs_function,
fsg_ss_function);
if (ret)
goto autoconf_fail;
return 0;
autoconf_fail:
ERROR(fsg, "unable to autoconfigure all endpoints\n");
return -ENOTSUPP;
}
/****************************** ALLOCATE FUNCTION *************************/
static void fsg_unbind(struct usb_configuration *c, struct usb_function *f)
{
struct fsg_dev *fsg = fsg_from_func(f);
struct fsg_common *common = fsg->common;
DBG(fsg, "unbind\n");
if (fsg->common->fsg == fsg) {
fsg->common->new_fsg = NULL;
raise_exception(fsg->common, FSG_STATE_CONFIG_CHANGE);
/* FIXME: make interruptible or killable somehow? */
wait_event(common->fsg_wait, common->fsg != fsg);
}
usb_free_all_descriptors(&fsg->function);
}
static inline struct fsg_lun_opts *to_fsg_lun_opts(struct config_item *item)
{
return container_of(to_config_group(item), struct fsg_lun_opts, group);
}
static inline struct fsg_opts *to_fsg_opts(struct config_item *item)
{
return container_of(to_config_group(item), struct fsg_opts,
func_inst.group);
}
CONFIGFS_ATTR_STRUCT(fsg_lun_opts);
CONFIGFS_ATTR_OPS(fsg_lun_opts);
static void fsg_lun_attr_release(struct config_item *item)
{
struct fsg_lun_opts *lun_opts;
lun_opts = to_fsg_lun_opts(item);
kfree(lun_opts);
}
static struct configfs_item_operations fsg_lun_item_ops = {
.release = fsg_lun_attr_release,
.show_attribute = fsg_lun_opts_attr_show,
.store_attribute = fsg_lun_opts_attr_store,
};
static ssize_t fsg_lun_opts_file_show(struct fsg_lun_opts *opts, char *page)
{
struct fsg_opts *fsg_opts;
fsg_opts = to_fsg_opts(opts->group.cg_item.ci_parent);
return fsg_show_file(opts->lun, &fsg_opts->common->filesem, page);
}
static ssize_t fsg_lun_opts_file_store(struct fsg_lun_opts *opts,
const char *page, size_t len)
{
struct fsg_opts *fsg_opts;
fsg_opts = to_fsg_opts(opts->group.cg_item.ci_parent);
return fsg_store_file(opts->lun, &fsg_opts->common->filesem, page, len);
}
static struct fsg_lun_opts_attribute fsg_lun_opts_file =
__CONFIGFS_ATTR(file, S_IRUGO | S_IWUSR, fsg_lun_opts_file_show,
fsg_lun_opts_file_store);
static ssize_t fsg_lun_opts_ro_show(struct fsg_lun_opts *opts, char *page)
{
return fsg_show_ro(opts->lun, page);
}
static ssize_t fsg_lun_opts_ro_store(struct fsg_lun_opts *opts,
const char *page, size_t len)
{
struct fsg_opts *fsg_opts;
fsg_opts = to_fsg_opts(opts->group.cg_item.ci_parent);
return fsg_store_ro(opts->lun, &fsg_opts->common->filesem, page, len);
}
static struct fsg_lun_opts_attribute fsg_lun_opts_ro =
__CONFIGFS_ATTR(ro, S_IRUGO | S_IWUSR, fsg_lun_opts_ro_show,
fsg_lun_opts_ro_store);
static ssize_t fsg_lun_opts_removable_show(struct fsg_lun_opts *opts,
char *page)
{
return fsg_show_removable(opts->lun, page);
}
static ssize_t fsg_lun_opts_removable_store(struct fsg_lun_opts *opts,
const char *page, size_t len)
{
return fsg_store_removable(opts->lun, page, len);
}
static struct fsg_lun_opts_attribute fsg_lun_opts_removable =
__CONFIGFS_ATTR(removable, S_IRUGO | S_IWUSR,
fsg_lun_opts_removable_show,
fsg_lun_opts_removable_store);
static ssize_t fsg_lun_opts_cdrom_show(struct fsg_lun_opts *opts, char *page)
{
return fsg_show_cdrom(opts->lun, page);
}
static ssize_t fsg_lun_opts_cdrom_store(struct fsg_lun_opts *opts,
const char *page, size_t len)
{
struct fsg_opts *fsg_opts;
fsg_opts = to_fsg_opts(opts->group.cg_item.ci_parent);
return fsg_store_cdrom(opts->lun, &fsg_opts->common->filesem, page,
len);
}
static struct fsg_lun_opts_attribute fsg_lun_opts_cdrom =
__CONFIGFS_ATTR(cdrom, S_IRUGO | S_IWUSR, fsg_lun_opts_cdrom_show,
fsg_lun_opts_cdrom_store);
static ssize_t fsg_lun_opts_nofua_show(struct fsg_lun_opts *opts, char *page)
{
return fsg_show_nofua(opts->lun, page);
}
static ssize_t fsg_lun_opts_nofua_store(struct fsg_lun_opts *opts,
const char *page, size_t len)
{
return fsg_store_nofua(opts->lun, page, len);
}
static struct fsg_lun_opts_attribute fsg_lun_opts_nofua =
__CONFIGFS_ATTR(nofua, S_IRUGO | S_IWUSR, fsg_lun_opts_nofua_show,
fsg_lun_opts_nofua_store);
static struct configfs_attribute *fsg_lun_attrs[] = {
&fsg_lun_opts_file.attr,
&fsg_lun_opts_ro.attr,
&fsg_lun_opts_removable.attr,
&fsg_lun_opts_cdrom.attr,
&fsg_lun_opts_nofua.attr,
NULL,
};
static struct config_item_type fsg_lun_type = {
.ct_item_ops = &fsg_lun_item_ops,
.ct_attrs = fsg_lun_attrs,
.ct_owner = THIS_MODULE,
};
static struct config_group *fsg_lun_make(struct config_group *group,
const char *name)
{
struct fsg_lun_opts *opts;
struct fsg_opts *fsg_opts;
struct fsg_lun_config config;
char *num_str;
u8 num;
int ret;
num_str = strchr(name, '.');
if (!num_str) {
pr_err("Unable to locate . in LUN.NUMBER\n");
return ERR_PTR(-EINVAL);
}
num_str++;
ret = kstrtou8(num_str, 0, &num);
if (ret)
return ERR_PTR(ret);
fsg_opts = to_fsg_opts(&group->cg_item);
if (num >= FSG_MAX_LUNS)
return ERR_PTR(-ERANGE);
mutex_lock(&fsg_opts->lock);
if (fsg_opts->refcnt || fsg_opts->common->luns[num]) {
ret = -EBUSY;
goto out;
}
opts = kzalloc(sizeof(*opts), GFP_KERNEL);
if (!opts) {
ret = -ENOMEM;
goto out;
}
memset(&config, 0, sizeof(config));
config.removable = true;
ret = fsg_common_create_lun(fsg_opts->common, &config, num, name,
(const char **)&group->cg_item.ci_name);
if (ret) {
kfree(opts);
goto out;
}
opts->lun = fsg_opts->common->luns[num];
opts->lun_id = num;
mutex_unlock(&fsg_opts->lock);
config_group_init_type_name(&opts->group, name, &fsg_lun_type);
return &opts->group;
out:
mutex_unlock(&fsg_opts->lock);
return ERR_PTR(ret);
}
static void fsg_lun_drop(struct config_group *group, struct config_item *item)
{
struct fsg_lun_opts *lun_opts;
struct fsg_opts *fsg_opts;
lun_opts = to_fsg_lun_opts(item);
fsg_opts = to_fsg_opts(&group->cg_item);
mutex_lock(&fsg_opts->lock);
if (fsg_opts->refcnt) {
struct config_item *gadget;
gadget = group->cg_item.ci_parent->ci_parent;
unregister_gadget_item(gadget);
}
fsg_common_remove_lun(lun_opts->lun, fsg_opts->common->sysfs);
fsg_opts->common->luns[lun_opts->lun_id] = NULL;
lun_opts->lun_id = 0;
mutex_unlock(&fsg_opts->lock);
config_item_put(item);
}
CONFIGFS_ATTR_STRUCT(fsg_opts);
CONFIGFS_ATTR_OPS(fsg_opts);
static void fsg_attr_release(struct config_item *item)
{
struct fsg_opts *opts = to_fsg_opts(item);
usb_put_function_instance(&opts->func_inst);
}
static struct configfs_item_operations fsg_item_ops = {
.release = fsg_attr_release,
.show_attribute = fsg_opts_attr_show,
.store_attribute = fsg_opts_attr_store,
};
static ssize_t fsg_opts_stall_show(struct fsg_opts *opts, char *page)
{
int result;
mutex_lock(&opts->lock);
result = sprintf(page, "%d", opts->common->can_stall);
mutex_unlock(&opts->lock);
return result;
}
static ssize_t fsg_opts_stall_store(struct fsg_opts *opts, const char *page,
size_t len)
{
int ret;
bool stall;
mutex_lock(&opts->lock);
if (opts->refcnt) {
mutex_unlock(&opts->lock);
return -EBUSY;
}
ret = strtobool(page, &stall);
if (!ret) {
opts->common->can_stall = stall;
ret = len;
}
mutex_unlock(&opts->lock);
return ret;
}
static struct fsg_opts_attribute fsg_opts_stall =
__CONFIGFS_ATTR(stall, S_IRUGO | S_IWUSR, fsg_opts_stall_show,
fsg_opts_stall_store);
#ifdef CONFIG_USB_GADGET_DEBUG_FILES
static ssize_t fsg_opts_num_buffers_show(struct fsg_opts *opts, char *page)
{
int result;
mutex_lock(&opts->lock);
result = sprintf(page, "%d", opts->common->fsg_num_buffers);
mutex_unlock(&opts->lock);
return result;
}
static ssize_t fsg_opts_num_buffers_store(struct fsg_opts *opts,
const char *page, size_t len)
{
int ret;
u8 num;
mutex_lock(&opts->lock);
if (opts->refcnt) {
ret = -EBUSY;
goto end;
}
ret = kstrtou8(page, 0, &num);
if (ret)
goto end;
ret = fsg_num_buffers_validate(num);
if (ret)
goto end;
fsg_common_set_num_buffers(opts->common, num);
ret = len;
end:
mutex_unlock(&opts->lock);
return ret;
}
static struct fsg_opts_attribute fsg_opts_num_buffers =
__CONFIGFS_ATTR(num_buffers, S_IRUGO | S_IWUSR,
fsg_opts_num_buffers_show,
fsg_opts_num_buffers_store);
#endif
static struct configfs_attribute *fsg_attrs[] = {
&fsg_opts_stall.attr,
#ifdef CONFIG_USB_GADGET_DEBUG_FILES
&fsg_opts_num_buffers.attr,
#endif
NULL,
};
static struct configfs_group_operations fsg_group_ops = {
.make_group = fsg_lun_make,
.drop_item = fsg_lun_drop,
};
static struct config_item_type fsg_func_type = {
.ct_item_ops = &fsg_item_ops,
.ct_group_ops = &fsg_group_ops,
.ct_attrs = fsg_attrs,
.ct_owner = THIS_MODULE,
};
static void fsg_free_inst(struct usb_function_instance *fi)
{
struct fsg_opts *opts;
opts = fsg_opts_from_func_inst(fi);
fsg_common_put(opts->common);
kfree(opts);
}
static struct usb_function_instance *fsg_alloc_inst(void)
{
struct fsg_opts *opts;
struct fsg_lun_config config;
int rc;
opts = kzalloc(sizeof(*opts), GFP_KERNEL);
if (!opts)
return ERR_PTR(-ENOMEM);
mutex_init(&opts->lock);
opts->func_inst.free_func_inst = fsg_free_inst;
opts->common = fsg_common_setup(opts->common);
if (IS_ERR(opts->common)) {
rc = PTR_ERR(opts->common);
goto release_opts;
}
rc = fsg_common_set_nluns(opts->common, FSG_MAX_LUNS);
if (rc)
goto release_opts;
rc = fsg_common_set_num_buffers(opts->common,
CONFIG_USB_GADGET_STORAGE_NUM_BUFFERS);
if (rc)
goto release_luns;
pr_info(FSG_DRIVER_DESC ", version: " FSG_DRIVER_VERSION "\n");
memset(&config, 0, sizeof(config));
config.removable = true;
rc = fsg_common_create_lun(opts->common, &config, 0, "lun.0",
(const char **)&opts->func_inst.group.cg_item.ci_name);
opts->lun0.lun = opts->common->luns[0];
opts->lun0.lun_id = 0;
config_group_init_type_name(&opts->lun0.group, "lun.0", &fsg_lun_type);
opts->default_groups[0] = &opts->lun0.group;
opts->func_inst.group.default_groups = opts->default_groups;
config_group_init_type_name(&opts->func_inst.group, "", &fsg_func_type);
return &opts->func_inst;
release_luns:
kfree(opts->common->luns);
release_opts:
kfree(opts);
return ERR_PTR(rc);
}
static void fsg_free(struct usb_function *f)
{
struct fsg_dev *fsg;
struct fsg_opts *opts;
fsg = container_of(f, struct fsg_dev, function);
opts = container_of(f->fi, struct fsg_opts, func_inst);
mutex_lock(&opts->lock);
opts->refcnt--;
mutex_unlock(&opts->lock);
kfree(fsg);
}
static struct usb_function *fsg_alloc(struct usb_function_instance *fi)
{
struct fsg_opts *opts = fsg_opts_from_func_inst(fi);
struct fsg_common *common = opts->common;
struct fsg_dev *fsg;
fsg = kzalloc(sizeof(*fsg), GFP_KERNEL);
if (unlikely(!fsg))
return ERR_PTR(-ENOMEM);
mutex_lock(&opts->lock);
opts->refcnt++;
mutex_unlock(&opts->lock);
fsg->function.name = FSG_DRIVER_DESC;
fsg->function.bind = fsg_bind;
fsg->function.unbind = fsg_unbind;
fsg->function.setup = fsg_setup;
fsg->function.set_alt = fsg_set_alt;
fsg->function.disable = fsg_disable;
fsg->function.free_func = fsg_free;
fsg->common = common;
setup_timer(&common->vfs_timer, msc_usb_vfs_timer_func,
(unsigned long) common);
return &fsg->function;
}
DECLARE_USB_FUNCTION_INIT(mass_storage, fsg_alloc_inst, fsg_alloc);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Michal Nazarewicz");
/************************* Module parameters *************************/
void fsg_config_from_params(struct fsg_config *cfg,
const struct fsg_module_parameters *params,
unsigned int fsg_num_buffers)
{
struct fsg_lun_config *lun;
unsigned i;
/* Configure LUNs */
cfg->nluns =
min(params->luns ?: (params->file_count ?: 1u),
(unsigned)FSG_MAX_LUNS);
for (i = 0, lun = cfg->luns; i < cfg->nluns; ++i, ++lun) {
lun->ro = !!params->ro[i];
lun->cdrom = !!params->cdrom[i];
lun->removable = !!params->removable[i];
lun->filename =
params->file_count > i && params->file[i][0]
? params->file[i]
: NULL;
}
/* Let MSF use defaults */
cfg->vendor_name = NULL;
cfg->product_name = NULL;
cfg->ops = NULL;
cfg->private_data = NULL;
/* Finalise */
cfg->can_stall = params->stall;
cfg->fsg_num_buffers = fsg_num_buffers;
}
EXPORT_SYMBOL_GPL(fsg_config_from_params);
| xingrz/android_kernel_nubia_msm8996 | drivers/usb/gadget/function/f_mass_storage.c | C | gpl-2.0 | 106,868 |
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2008,2009 IITP RAS
*
* 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
*
* Authors: Kirill Andreev <[email protected]>
*/
#include "hwmp-protocol.h"
#include "hwmp-protocol-mac.h"
#include "hwmp-tag.h"
#include "hwmp-rtable.h"
#include "ns3/log.h"
#include "ns3/simulator.h"
#include "ns3/packet.h"
#include "ns3/mesh-point-device.h"
#include "ns3/wifi-net-device.h"
#include "ns3/mesh-point-device.h"
#include "ns3/mesh-wifi-interface-mac.h"
#include "ns3/random-variable-stream.h"
#include "airtime-metric.h"
#include "ie-dot11s-preq.h"
#include "ie-dot11s-prep.h"
#include "ns3/trace-source-accessor.h"
#include "ie-dot11s-perr.h"
#include "ns3/arp-l3-protocol.h"
#include "ns3/ipv4-l3-protocol.h"
#include "ns3/udp-l4-protocol.h"
#include "ns3/tcp-l4-protocol.h"
#include "ns3/arp-header.h"
#include "ns3/ipv4-header.h"
#include "ns3/tcp-header.h"
#include "ns3/udp-header.h"
#include "ns3/rhoSigma-tag.h"
#include "ns3/llc-snap-header.h"
#include "ns3/wifi-mac-trailer.h"
#include "dot11s-mac-header.h"
NS_LOG_COMPONENT_DEFINE ("HwmpProtocol");
namespace ns3 {
namespace dot11s {
NS_OBJECT_ENSURE_REGISTERED (HwmpProtocol)
;
/* integration/qng.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Brian Gough
*
* 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, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
//#include <config.h>
#include <math.h>
#include <float.h>
TypeId
HwmpProtocol::GetTypeId ()
{
static TypeId tid = TypeId ("ns3::dot11s::HwmpProtocol")
.SetParent<MeshL2RoutingProtocol> ()
.AddConstructor<HwmpProtocol> ()
.AddAttribute ( "RandomStart",
"Random delay at first proactive PREQ",
TimeValue (Seconds (0.1)),
MakeTimeAccessor (
&HwmpProtocol::m_randomStart),
MakeTimeChecker ()
)
.AddAttribute ( "MaxQueueSize",
"Maximum number of packets we can store when resolving route",
UintegerValue (255),
MakeUintegerAccessor (
&HwmpProtocol::m_maxQueueSize),
MakeUintegerChecker<uint16_t> (1)
)
.AddAttribute ( "Dot11MeshHWMPmaxPREQretries",
"Maximum number of retries before we suppose the destination to be unreachable",
UintegerValue (3),
MakeUintegerAccessor (
&HwmpProtocol::m_dot11MeshHWMPmaxPREQretries),
MakeUintegerChecker<uint8_t> (1)
)
.AddAttribute ( "Dot11MeshHWMPnetDiameterTraversalTime",
"Time we suppose the packet to go from one edge of the network to another",
TimeValue (MicroSeconds (1024*100)),
MakeTimeAccessor (
&HwmpProtocol::m_dot11MeshHWMPnetDiameterTraversalTime),
MakeTimeChecker ()
)
.AddAttribute ( "Dot11MeshHWMPpreqMinInterval",
"Minimal interval between to successive PREQs",
TimeValue (MicroSeconds (1024*100)),
MakeTimeAccessor (
&HwmpProtocol::m_dot11MeshHWMPpreqMinInterval),
MakeTimeChecker ()
)
.AddAttribute ( "Dot11MeshHWMPperrMinInterval",
"Minimal interval between to successive PREQs",
TimeValue (MicroSeconds (1024*100)),
MakeTimeAccessor (&HwmpProtocol::m_dot11MeshHWMPperrMinInterval),
MakeTimeChecker ()
)
.AddAttribute ( "Dot11MeshHWMPactiveRootTimeout",
"Lifetime of poractive routing information",
TimeValue (MicroSeconds (1024*5000)),
MakeTimeAccessor (
&HwmpProtocol::m_dot11MeshHWMPactiveRootTimeout),
MakeTimeChecker ()
)
.AddAttribute ( "Dot11MeshHWMPactivePathTimeout",
"Lifetime of reactive routing information",
TimeValue (MicroSeconds (1024*5000)),
MakeTimeAccessor (
&HwmpProtocol::m_dot11MeshHWMPactivePathTimeout),
MakeTimeChecker ()
)
.AddAttribute ( "Dot11MeshHWMPpathToRootInterval",
"Interval between two successive proactive PREQs",
TimeValue (MicroSeconds (1024*2000)),
MakeTimeAccessor (
&HwmpProtocol::m_dot11MeshHWMPpathToRootInterval),
MakeTimeChecker ()
)
.AddAttribute ( "Dot11MeshHWMPrannInterval",
"Lifetime of poractive routing information",
TimeValue (MicroSeconds (1024*5000)),
MakeTimeAccessor (
&HwmpProtocol::m_dot11MeshHWMPrannInterval),
MakeTimeChecker ()
)
.AddAttribute ( "MaxTtl",
"Initial value of Time To Live field",
UintegerValue (32),
MakeUintegerAccessor (
&HwmpProtocol::m_maxTtl),
MakeUintegerChecker<uint8_t> (2)
)
.AddAttribute ( "UnicastPerrThreshold",
"Maximum number of PERR receivers, when we send a PERR as a chain of unicasts",
UintegerValue (32),
MakeUintegerAccessor (
&HwmpProtocol::m_unicastPerrThreshold),
MakeUintegerChecker<uint8_t> (1)
)
.AddAttribute ( "UnicastPreqThreshold",
"Maximum number of PREQ receivers, when we send a PREQ as a chain of unicasts",
UintegerValue (1),
MakeUintegerAccessor (
&HwmpProtocol::m_unicastPreqThreshold),
MakeUintegerChecker<uint8_t> (1)
)
.AddAttribute ( "UnicastDataThreshold",
"Maximum number ofbroadcast receivers, when we send a broadcast as a chain of unicasts",
UintegerValue (1),
MakeUintegerAccessor (
&HwmpProtocol::m_unicastDataThreshold),
MakeUintegerChecker<uint8_t> (1)
)
.AddAttribute ( "DoFlag",
"Destination only HWMP flag",
BooleanValue (true),
MakeBooleanAccessor (
&HwmpProtocol::m_doFlag),
MakeBooleanChecker ()
)
.AddAttribute ( "RfFlag",
"Reply and forward flag",
BooleanValue (false),
MakeBooleanAccessor (
&HwmpProtocol::m_rfFlag),
MakeBooleanChecker ()
)
.AddTraceSource ( "RouteDiscoveryTime",
"The time of route discovery procedure",
MakeTraceSourceAccessor (
&HwmpProtocol::m_routeDiscoveryTimeCallback)
)
//by hadi
.AddAttribute ( "VBMetricMargin",
"VBMetricMargin",
UintegerValue (2),
MakeUintegerAccessor (
&HwmpProtocol::m_VBMetricMargin),
MakeUintegerChecker<uint32_t> (1)
)
.AddAttribute ( "Gppm",
"G Packets Per Minutes",
UintegerValue (3600),
MakeUintegerAccessor (
&HwmpProtocol::m_Gppm),
MakeUintegerChecker<uint32_t> (1)
)
.AddTraceSource ( "TransmittingFromSource",
"",
MakeTraceSourceAccessor (
&HwmpProtocol::m_txed4mSourceCallback)
)
.AddTraceSource ( "WannaTransmittingFromSource",
"",
MakeTraceSourceAccessor (
&HwmpProtocol::m_wannaTx4mSourceCallback)
)
.AddTraceSource( "CbrCnnStateChanged",
"",
MakeTraceSourceAccessor(
&HwmpProtocol::m_CbrCnnStateChanged))
.AddTraceSource( "PacketBufferredAtSource",
"",
MakeTraceSourceAccessor(
&HwmpProtocol::m_packetBufferredAtSource))
;
return tid;
}
HwmpProtocol::HwmpProtocol () :
m_dataSeqno (1),
m_hwmpSeqno (1),
m_preqId (0),
m_rtable (CreateObject<HwmpRtable> ()),
m_randomStart (Seconds (0.1)),
m_maxQueueSize (255),
m_dot11MeshHWMPmaxPREQretries (3),
m_dot11MeshHWMPnetDiameterTraversalTime (MicroSeconds (1024*100)),
m_dot11MeshHWMPpreqMinInterval (MicroSeconds (1024*100)),
m_dot11MeshHWMPperrMinInterval (MicroSeconds (1024*100)),
m_dot11MeshHWMPactiveRootTimeout (MicroSeconds (1024*5000)),
m_dot11MeshHWMPactivePathTimeout (MicroSeconds (1024*5000)),
m_dot11MeshHWMPpathToRootInterval (MicroSeconds (1024*2000)),
m_dot11MeshHWMPrannInterval (MicroSeconds (1024*5000)),
m_isRoot (false),
m_maxTtl (32),
m_unicastPerrThreshold (32),
m_unicastPreqThreshold (1),
m_unicastDataThreshold (1),
m_doFlag (true),
m_rfFlag (false),
m_VBMetricMargin(2)
{
NS_LOG_FUNCTION_NOARGS ();
m_noDataPacketYet=true;
m_energyPerByte=0;
m_coefficient = CreateObject<UniformRandomVariable> ();
}
HwmpProtocol::~HwmpProtocol ()
{
NS_LOG_FUNCTION_NOARGS ();
}
void
HwmpProtocol::DoInitialize ()
{
m_coefficient->SetAttribute ("Max", DoubleValue (m_randomStart.GetSeconds ()));
if (m_isRoot)
{
SetRoot ();
}
Simulator::Schedule(Seconds(0.5),&HwmpProtocol::CheckCbrRoutes4Expiration,this);//hadi eo94
m_interfaces.begin ()->second->SetEnergyChangeCallback (MakeCallback(&HwmpProtocol::EnergyChange,this));
m_interfaces.begin ()->second->SetGammaChangeCallback (MakeCallback(&HwmpProtocol::GammaChange,this));
m_rtable->setSystemB (m_interfaces.begin ()->second->GetEres ());
m_rtable->setBPrim (m_rtable->systemB ());
m_rtable->setSystemBMax (m_interfaces.begin ()->second->GetBatteryCapacity ());
m_rtable->setBPrimMax (m_rtable->systemBMax ());
m_rtable->setAssignedGamma (0);
m_rtable->setGppm (m_Gppm);
GammaChange (m_rtable->systemGamma (),m_totalSimulationTime);
m_rtable->UpdateToken ();
}
void
HwmpProtocol::DoDispose ()
{
NS_LOG_FUNCTION_NOARGS ();
for (std::map<Mac48Address, PreqEvent>::iterator i = m_preqTimeouts.begin (); i != m_preqTimeouts.end (); i++)
{
i->second.preqTimeout.Cancel ();
}
m_proactivePreqTimer.Cancel ();
m_preqTimeouts.clear ();
m_lastDataSeqno.clear ();
m_hwmpSeqnoMetricDatabase.clear ();
for (std::vector<CnnBasedPreqEvent>::iterator cbpei = m_cnnBasedPreqTimeouts.begin (); cbpei != m_cnnBasedPreqTimeouts.end (); cbpei++)
{
cbpei->preqTimeout.Cancel();
}
m_cnnBasedPreqTimeouts.clear();
for(std::vector<DelayedPrepStruct>::iterator dpsi=m_delayedPrepStruct.begin ();dpsi!=m_delayedPrepStruct.end ();dpsi++)
{
dpsi->prepTimeout.Cancel ();
}
m_delayedPrepStruct.clear ();
m_interfaces.clear ();
m_rqueue.clear ();
m_rtable = 0;
m_mp = 0;
}
bool
HwmpProtocol::RequestRoute (
uint32_t sourceIface,
const Mac48Address source,
const Mac48Address destination,
Ptr<const Packet> constPacket,
uint16_t protocolType, //ethrnet 'Protocol' field
MeshL2RoutingProtocol::RouteReplyCallback routeReply
)
{
Ptr <Packet> packet = constPacket->Copy ();
HwmpTag tag;
if (sourceIface == GetMeshPoint ()->GetIfIndex ())
{
// packet from level 3
if (packet->PeekPacketTag (tag))
{
NS_FATAL_ERROR ("HWMP tag has come with a packet from upper layer. This must not occur...");
}
//Filling TAG:
if (destination == Mac48Address::GetBroadcast ())
{
tag.SetSeqno (m_dataSeqno++);
}
tag.SetTtl (m_maxTtl);
}
else
{
if (!packet->RemovePacketTag (tag))
{
NS_FATAL_ERROR ("HWMP tag is supposed to be here at this point.");
}
tag.DecrementTtl ();
if (tag.GetTtl () == 0)
{
m_stats.droppedTtl++;
return false;
}
}
if (destination == Mac48Address::GetBroadcast ())
{
m_stats.txBroadcast++;
m_stats.txBytes += packet->GetSize ();
//channel IDs where we have already sent broadcast:
std::vector<uint16_t> channels;
for (HwmpProtocolMacMap::const_iterator plugin = m_interfaces.begin (); plugin != m_interfaces.end (); plugin++)
{
bool shouldSend = true;
for (std::vector<uint16_t>::const_iterator chan = channels.begin (); chan != channels.end (); chan++)
{
if ((*chan) == plugin->second->GetChannelId ())
{
shouldSend = false;
}
}
if (!shouldSend)
{
continue;
}
channels.push_back (plugin->second->GetChannelId ());
std::vector<Mac48Address> receivers = GetBroadcastReceivers (plugin->first);
for (std::vector<Mac48Address>::const_iterator i = receivers.begin (); i != receivers.end (); i++)
{
Ptr<Packet> packetCopy = packet->Copy ();
//
// 64-bit Intel valgrind complains about tag.SetAddress (*i). It
// likes this just fine.
//
Mac48Address address = *i;
tag.SetAddress (address);
packetCopy->AddPacketTag (tag);
routeReply (true, packetCopy, source, destination, protocolType, plugin->first);
}
}
}
else
{
return ForwardUnicast (sourceIface, source, destination, packet, protocolType, routeReply, tag.GetTtl ());
}
return true;
}
bool
HwmpProtocol::RemoveRoutingStuff (uint32_t fromIface, const Mac48Address source,
const Mac48Address destination, Ptr<Packet> packet, uint16_t& protocolType)
{
HwmpTag tag;
if (!packet->RemovePacketTag (tag))
{
NS_FATAL_ERROR ("HWMP tag must exist when packet received from the network");
}
return true;
}
bool
HwmpProtocol::ForwardUnicast (uint32_t sourceIface, const Mac48Address source, const Mac48Address destination,
Ptr<Packet> packet, uint16_t protocolType, RouteReplyCallback routeReply, uint32_t ttl)
{
RhoSigmaTag rsTag;
packet->RemovePacketTag (rsTag);
Ptr<Packet> pCopy=packet->Copy();
uint8_t cnnType;//1:mac only, 2:ip only , 3:ip port
Ipv4Address srcIpv4Addr;
Ipv4Address dstIpv4Addr;
uint16_t srcPort;
uint16_t dstPort;
if(protocolType==ArpL3Protocol::PROT_NUMBER)
{
ArpHeader arpHdr;
pCopy->RemoveHeader(arpHdr);
srcIpv4Addr = arpHdr.GetSourceIpv4Address();
dstIpv4Addr = arpHdr.GetDestinationIpv4Address();
cnnType=HwmpRtable::CNN_TYPE_IP_ONLY;
// NS_LOG_HADI(m_address << " ARP packet have seen");
NS_ASSERT(true);
}
else if(protocolType==Ipv4L3Protocol::PROT_NUMBER)
{
Ipv4Header ipv4Hdr;
pCopy->RemoveHeader(ipv4Hdr);
srcIpv4Addr = ipv4Hdr.GetSource();
dstIpv4Addr = ipv4Hdr.GetDestination();
uint8_t protocol = ipv4Hdr.GetProtocol();
if(protocol==TcpL4Protocol::PROT_NUMBER)
{
TcpHeader tcpHdr;
pCopy->RemoveHeader (tcpHdr);
srcPort=tcpHdr.GetSourcePort ();
dstPort=tcpHdr.GetDestinationPort ();
cnnType=HwmpRtable::CNN_TYPE_PKT_BASED;
}
else if(protocol==UdpL4Protocol::PROT_NUMBER)
{
UdpHeader udpHdr;
pCopy->RemoveHeader(udpHdr);
srcPort=udpHdr.GetSourcePort();
dstPort=udpHdr.GetDestinationPort();
cnnType=HwmpRtable::CNN_TYPE_IP_PORT;
// NS_LOG_HADI(m_address << " UDP packet have seen " << source << "->" << destination << " " << srcIpv4Addr << ":" << (int)srcPort << "=>" << dstIpv4Addr << ":" << (int)dstPort);
}
else
{
cnnType=HwmpRtable::CNN_TYPE_IP_ONLY;
// NS_LOG_HADI(m_address << " non TCP or UDP packet have seen");
NS_ASSERT(true);
}
}
else
{
cnnType=HwmpRtable::CNN_TYPE_MAC_ONLY;
// NS_LOG_HADI(m_address << " non IP packet have seen");
NS_ASSERT(true);
}
if((source==GetAddress())&&(cnnType==HwmpRtable::CNN_TYPE_IP_PORT)){
NS_LOG_ROUTING("hwmp forwardUnicast4mSource " << (int)packet->GetUid() << " " << srcIpv4Addr << ":" << (int)srcPort << "=>" << dstIpv4Addr << ":" << (int)dstPort << " " << (int)rsTag.GetRho () << " " << (int)rsTag.GetSigma () << " " << rsTag.GetStopTime ());
m_wannaTx4mSourceCallback();
}
NS_ASSERT (destination != Mac48Address::GetBroadcast ());
NS_ASSERT(cnnType==HwmpRtable::CNN_TYPE_IP_PORT);
CbrConnection connection;
connection.destination=destination;
connection.source=source;
connection.cnnType=cnnType;
connection.dstIpv4Addr=dstIpv4Addr;
connection.srcIpv4Addr=srcIpv4Addr;
connection.dstPort=dstPort;
connection.srcPort=srcPort;
if(cnnType==HwmpRtable::CNN_TYPE_IP_PORT){
CbrConnectionsVector::iterator nrccvi=std::find(m_notRoutedCbrConnections.begin(),m_notRoutedCbrConnections.end(),connection);
if(nrccvi!=m_notRoutedCbrConnections.end()){
if(source==GetAddress()){
NS_LOG_ROUTING("hwmp cnnRejectedDrop " << (int)packet->GetUid() << " " << srcIpv4Addr << ":" << (int)srcPort << "=>" << dstIpv4Addr << ":" << (int)dstPort);
}
return false;
}
}
HwmpRtable::CnnBasedLookupResult cnnBasedResult = m_rtable->LookupCnnBasedReactive(destination,source,cnnType,srcIpv4Addr,dstIpv4Addr,srcPort,dstPort);
NS_LOG_DEBUG ("Requested src = "<<source<<", dst = "<<destination<<", I am "<<GetAddress ()<<", RA = "<<cnnBasedResult.retransmitter);
HwmpTag tag;
tag.SetAddress (cnnBasedResult.retransmitter);
tag.SetTtl (ttl);
//seqno and metric is not used;
packet->AddPacketTag (tag);
if (cnnBasedResult.retransmitter != Mac48Address::GetBroadcast ())
{
if(source==GetAddress())
{
NS_LOG_ROUTING("tx4mSource " << (int)packet->GetUid());
NS_LOG_CAC("tx4mSource " << srcIpv4Addr << ":" << srcPort << "=>" << dstIpv4Addr << ":" << dstPort << " " << (int)packet->GetUid());
m_txed4mSourceCallback();
SourceCbrRouteExtend (destination,source,cnnType,srcIpv4Addr,dstIpv4Addr,srcPort,dstPort);
}
else
{
NS_LOG_CAC("forwardViaIntermediate " << srcIpv4Addr << ":" << srcPort << "=>" << dstIpv4Addr << ":" << dstPort << " " << (int)packet->GetUid());
CbrRouteExtend(destination,source,cnnType,srcIpv4Addr,dstIpv4Addr,srcPort,dstPort);
}
//reply immediately:
//routeReply (true, packet, source, destination, protocolType, cnnBasedResult.ifIndex);
NS_LOG_TB("queuing packet in TBVB queue for send " << (int)packet->GetUid ());
m_rtable->QueueCnnBasedPacket (destination,source,cnnType,srcIpv4Addr,dstIpv4Addr,srcPort,dstPort,packet,protocolType,cnnBasedResult.ifIndex,routeReply);
m_stats.txUnicast++;
m_stats.txBytes += packet->GetSize ();
return true;
}
if (sourceIface != GetMeshPoint ()->GetIfIndex ())
{
//Start path error procedure:
NS_LOG_DEBUG ("Must Send PERR");
m_stats.totalDropped++;
return false;
}
//Request a destination:
if (CnnBasedShouldSendPreq (rsTag, destination, source, cnnType, srcIpv4Addr, dstIpv4Addr, srcPort, dstPort))
{
NS_LOG_ROUTING("sendingPathRequest " << source << " " << destination);
uint32_t originator_seqno = GetNextHwmpSeqno ();
uint32_t dst_seqno = 0;
m_stats.initiatedPreq++;
for (HwmpProtocolMacMap::const_iterator i = m_interfaces.begin (); i != m_interfaces.end (); i++)
{
if(m_routingType==2)
i->second->RequestDestination (destination, originator_seqno, dst_seqno, cnnType, srcIpv4Addr, dstIpv4Addr, srcPort, dstPort,rsTag.GetRho (), rsTag.GetSigma (), rsTag.GetStopTime (), rsTag.delayBound (), rsTag.maxPktSize (), 0x7fffffff,0x7fffffff,0x7fffffff);
else
i->second->RequestDestination (destination, originator_seqno, dst_seqno, cnnType, srcIpv4Addr, dstIpv4Addr, srcPort, dstPort,rsTag.GetRho (), rsTag.GetSigma (), rsTag.GetStopTime (),rsTag.delayBound (), rsTag.maxPktSize (), 0,0,0);
}
}
QueuedPacket pkt;
pkt.pkt = packet;
pkt.dst = destination;
pkt.src = source;
pkt.protocol = protocolType;
pkt.reply = routeReply;
pkt.inInterface = sourceIface;
pkt.cnnType=cnnType;
pkt.srcIpv4Addr=srcIpv4Addr;
pkt.dstIpv4Addr=dstIpv4Addr;
pkt.srcPort=srcPort;
pkt.dstPort=dstPort;
if (QueuePacket (pkt))
{
if((source==GetAddress ())&&(cnnType==HwmpRtable::CNN_TYPE_IP_PORT))
m_packetBufferredAtSource(packet);
m_stats.totalQueued++;
return true;
}
else
{
m_stats.totalDropped++;
return false;
}
}
void
HwmpProtocol::ReceivePreq (IePreq preq, Mac48Address from, uint32_t interface, Mac48Address fromMp, uint32_t metric)
{
preq.IncrementMetric (metric);
NS_LOG_ROUTING("receivePreq " << from << " " << (int)preq.GetGammaPrim () << " " << (int)preq.GetBPrim () << " " << (int)preq.GetTotalE () << " " << (int)preq.GetMetric ());
//acceptance cretirea:
// bool duplicatePreq=false;
//bool freshInfo (true);
for(std::vector<CnnBasedSeqnoMetricDatabase>::iterator i=m_hwmpSeqnoMetricDatabase.begin();i!=m_hwmpSeqnoMetricDatabase.end();i++)
{
if(
(i->originatorAddress==preq.GetOriginatorAddress()) &&
(i->cnnType==preq.GetCnnType()) &&
(i->srcIpv4Addr==preq.GetSrcIpv4Addr()) &&
(i->srcPort==preq.GetSrcPort()) &&
(i->dstIpv4Addr==preq.GetDstIpv4Addr()) &&
(i->dstPort==preq.GetDstPort())
)
{
// duplicatePreq=true;
NS_LOG_ROUTING("duplicatePreq " << (int)i->originatorSeqNumber << " " << (int)preq.GetOriginatorSeqNumber ());
if ((int32_t)(i->originatorSeqNumber - preq.GetOriginatorSeqNumber ()) > 0)
{
return;
}
if (i->originatorSeqNumber == preq.GetOriginatorSeqNumber ())
{
//freshInfo = false;
if((m_routingType==1)||(m_routingType==2))
{
NS_LOG_ROUTING("checking prev " << i->bPrim << " " << i->gammaPrim << " " << i->totalE << " " << preq.GetBPrim () << " " << preq.GetGammaPrim () << " " << (int)preq.GetTotalE () << " " << (int)m_VBMetricMargin);
if((i->totalE+m_VBMetricMargin >= preq.GetTotalE ())&&(i->totalE <= preq.GetTotalE ()+m_VBMetricMargin))
{
if((i->metric+m_VBMetricMargin*10 >= preq.GetMetric ())&&(i->metric <= preq.GetMetric ()+m_VBMetricMargin*10))
{
if(m_routingType==1)
{
if(i->bPrim<=preq.GetBPrim ())
{
NS_LOG_ROUTING("b1 rejected " << (int)i->bPrim << " " << (int)i->gammaPrim << " " << (int)preq.GetBPrim () << " " << (int)preq.GetGammaPrim ());
return;
}
}
else
{
if(i->bPrim>=preq.GetBPrim ())
{
NS_LOG_ROUTING("b2 rejected " << (int)i->bPrim << " " << (int)i->gammaPrim << " " << (int)preq.GetBPrim () << " " << (int)preq.GetGammaPrim ());
return;
}
}
}
else if (i->metric <= preq.GetMetric ())
{
NS_LOG_ROUTING("metric rejected " << (int)i->metric << " " << (int)preq.GetMetric ());
return;
}
}
else
if(m_routingType==1)
{
if(i->totalE<=preq.GetTotalE ())
{
NS_LOG_ROUTING("totalE1 rejected " << (int)i->bPrim << " " << (int)i->gammaPrim << " " << (int)preq.GetBPrim () << " " << (int)preq.GetGammaPrim ());
return;
}
}
else
{
if(i->totalE>=preq.GetTotalE ())
{
NS_LOG_ROUTING("totalE2 rejected " << (int)i->bPrim << " " << (int)i->gammaPrim << " " << (int)preq.GetBPrim () << " " << (int)preq.GetGammaPrim ());
return;
}
}
/*NS_LOG_ROUTING("checking prev " << (int)i->metric << " " << (int)preq.GetMetric () << " " << (int)m_VBMetricMargin);
if ((i->metric+m_VBMetricMargin >= preq.GetMetric ())&&(i->metric <= preq.GetMetric ()+m_VBMetricMargin))
{
// check energy metric
NS_LOG_ROUTING("in margin with one prev preq " << (int)i->metric << " " << (int)preq.GetMetric () << " " << (int)m_VBMetricMargin);
if((i->bPrim+i->gammaPrim*(preq.GetStopTime ()-Simulator::Now ()).GetSeconds ())>=(preq.GetBPrim ()+preq.GetGammaPrim ()*(preq.GetStopTime ()-Simulator::Now ()).GetSeconds ()))
{
NS_LOG_ROUTING("bgamma rejected " << (int)i->bPrim << " " << (int)i->gammaPrim << " " << (int)preq.GetBPrim () << " " << (int)preq.GetGammaPrim ());
return;
}
}
else if (i->metric <= preq.GetMetric ())
{
NS_LOG_ROUTING("metric rejected " << (int)i->metric << " " << (int)preq.GetMetric ());
return;
}*/
}
else
{
if (i->metric <= preq.GetMetric ())
{
NS_LOG_ROUTING("metric rejected " << (int)i->metric << " " << (int)preq.GetMetric ());
return;
}
}
}
m_hwmpSeqnoMetricDatabase.erase (i);
break;
}
}
CnnBasedSeqnoMetricDatabase newDb;
newDb.originatorAddress=preq.GetOriginatorAddress();
newDb.originatorSeqNumber=preq.GetOriginatorSeqNumber();
newDb.metric=preq.GetMetric();
newDb.cnnType=preq.GetCnnType();
newDb.srcIpv4Addr=preq.GetSrcIpv4Addr();
newDb.dstIpv4Addr=preq.GetDstIpv4Addr();
newDb.srcPort=preq.GetSrcPort();
newDb.dstPort=preq.GetDstPort();
newDb.gammaPrim=preq.GetGammaPrim ();
newDb.bPrim=preq.GetBPrim ();
newDb.totalE=preq.GetTotalE ();
m_hwmpSeqnoMetricDatabase.push_back(newDb);
std::vector<Ptr<DestinationAddressUnit> > destinations = preq.GetDestinationList ();
//Add reverse path to originator:
m_rtable->AddCnnBasedReversePath (preq.GetOriginatorAddress(),from,interface,preq.GetCnnType(),preq.GetSrcIpv4Addr(),preq.GetDstIpv4Addr(),preq.GetSrcPort(),preq.GetDstPort(),Seconds(1),preq.GetOriginatorSeqNumber());
//Add reactive path to originator:
for (std::vector<Ptr<DestinationAddressUnit> >::const_iterator i = destinations.begin (); i != destinations.end (); i++)
{
NS_LOG_ROUTING("receivePReq " << preq.GetOriginatorAddress() << " " << from << " " << (*i)->GetDestinationAddress ());
std::vector<Ptr<DestinationAddressUnit> > preqDestinations = preq.GetDestinationList ();
Mac48Address preqDstMac;
if(preqDestinations.size ()==1){
std::vector<Ptr<DestinationAddressUnit> >::const_iterator preqDstMacIt =preqDestinations.begin ();
preqDstMac=(*preqDstMacIt)->GetDestinationAddress();
}else{
preqDstMac=GetAddress ();
}
if ((*i)->GetDestinationAddress () == GetAddress ())
{
// if(!duplicatePreq)
{
if(m_doCAC)
{
// calculate total needed energy for entire connection lifetime and needed energy for bursts.
double totalEnergyNeeded = (m_rtable->m_maxEnergyPerDataPacket+m_rtable->m_maxEnergyPerAckPacket)*(preq.GetStopTime ()-Simulator::Now ()).GetSeconds ()*(preq.GetRho ()/60)*m_rtable->m_energyAlpha;
double burstEnergyNeeded = (m_rtable->m_maxEnergyPerDataPacket+m_rtable->m_maxEnergyPerAckPacket)*preq.GetSigma ()*m_rtable->m_energyAlpha;
double energyUntilEndOfConnection = m_rtable->bPrim ()+ m_rtable->gammaPrim ()*(preq.GetStopTime ()-Simulator::Now ()).GetSeconds ();
NS_LOG_ROUTING("ReceivePreqCACdestination " << m_rtable->m_maxEnergyPerDataPacket << " " << m_rtable->m_maxEnergyPerAckPacket << " " << (int)preq.GetRho () << " " << (int)preq.GetSigma () << " " << preq.GetStopTime () << " ; " << totalEnergyNeeded << " " << burstEnergyNeeded << " " << energyUntilEndOfConnection << " " << m_rtable->bPrim ());
if( ( ( m_rtable->bPrim ()< burstEnergyNeeded ) || ( energyUntilEndOfConnection < totalEnergyNeeded ) ) || (!m_interfaces.begin()->second->HasEnoughCapacity4NewConnection(preq.GetOriginatorAddress (),preqDstMac,preq.GetHopCount (),from,preq.GetRho ()) ) )// CAC check
{
NS_LOG_ROUTING("cac rejected the connection " << totalEnergyNeeded << " " << burstEnergyNeeded << " " << energyUntilEndOfConnection << " " << m_rtable->bPrim ());
return;
}
}
else
{
if(m_rtable->bPrim ()<=0)
{
NS_LOG_ROUTING("bPrim()<=0_1 rejected the connection " << m_rtable->bPrim ());
return;
}
}
}
NS_LOG_ROUTING("schedule2sendPrep");
Schedule2sendPrep (
GetAddress (),
preq.GetOriginatorAddress (),
preq.GetMetric(),
preq.GetCnnType(),
preq.GetSrcIpv4Addr(),
preq.GetDstIpv4Addr(),
preq.GetSrcPort(),
preq.GetDstPort(),
preq.GetRho (),
preq.GetSigma (),
preq.GetStopTime (),
preq.GetDelayBound (),
preq.GetMaxPktSize (),
preq.GetOriginatorSeqNumber (),
GetNextHwmpSeqno (),
preq.GetLifetime (),
interface
);
//NS_ASSERT (m_rtable->LookupReactive (preq.GetOriginatorAddress ()).retransmitter != Mac48Address::GetBroadcast ());
preq.DelDestinationAddressElement ((*i)->GetDestinationAddress ());
continue;
}
else
{
// if(!duplicatePreq)
{
if(m_doCAC)
{
// calculate total needed energy for entire connection lifetime and needed energy for bursts.
double totalEnergyNeeded = 2 * (m_rtable->m_maxEnergyPerDataPacket+m_rtable->m_maxEnergyPerAckPacket)*(preq.GetStopTime ()-Simulator::Now ()).GetSeconds ()*(preq.GetRho ()/60)*m_rtable->m_energyAlpha;
double burstEnergyNeeded = 2 * (m_rtable->m_maxEnergyPerDataPacket+m_rtable->m_maxEnergyPerAckPacket)*preq.GetSigma ()*m_rtable->m_energyAlpha;
double energyUntilEndOfConnection = m_rtable->bPrim ()+ m_rtable->gammaPrim ()*(preq.GetStopTime ()-Simulator::Now ()).GetSeconds ();
NS_LOG_ROUTING("ReceivePreqCACintermediate " << m_rtable->m_maxEnergyPerDataPacket << " " << m_rtable->m_maxEnergyPerAckPacket << " " << (int)preq.GetRho () << " " << (int)preq.GetSigma () << " " << preq.GetStopTime () << " ; " << totalEnergyNeeded << " " << burstEnergyNeeded << " " << energyUntilEndOfConnection << " " << m_rtable->bPrim ());
if( ( ( m_rtable->bPrim ()< burstEnergyNeeded ) || ( energyUntilEndOfConnection < totalEnergyNeeded ) ) || (!m_interfaces.begin()->second->HasEnoughCapacity4NewConnection(preq.GetOriginatorAddress (),preqDstMac,preq.GetHopCount (),from,preq.GetRho ()) ) )// CAC check
{
NS_LOG_ROUTING("cac rejected the connection " << totalEnergyNeeded << " " << burstEnergyNeeded << " " << energyUntilEndOfConnection << " " << m_rtable->bPrim ());
return;
}
}
else
{
if(m_rtable->bPrim ()<=0)
{
NS_LOG_ROUTING("bPrim()<=0_2 rejected the connection " << m_rtable->bPrim ());
return;
}
}
}
if(m_routingType==1)
preq.UpdateVBMetricSum (m_rtable->gammaPrim (),m_rtable->bPrim ());
else if(m_routingType==2)
preq.UpdateVBMetricMin (m_rtable->gammaPrim (),m_rtable->bPrim ());
}
}
NS_LOG_DEBUG ("I am " << GetAddress () << "Accepted preq from address" << from << ", preq:" << preq);
//check if must retransmit:
if (preq.GetDestCount () == 0)
{
return;
}
//Forward PREQ to all interfaces:
NS_LOG_DEBUG ("I am " << GetAddress () << "retransmitting PREQ:" << preq);
NS_LOG_ROUTING("forwardPreq");
for (HwmpProtocolMacMap::const_iterator i = m_interfaces.begin (); i != m_interfaces.end (); i++)
{
i->second->SendPreq (preq);
}
}
void
HwmpProtocol::Schedule2sendPrep(
Mac48Address src,
Mac48Address dst,
uint32_t initMetric,
uint8_t cnnType,
Ipv4Address srcIpv4Addr,
Ipv4Address dstIpv4Addr,
uint16_t srcPort,
uint16_t dstPort,
uint16_t rho,
uint16_t sigma,
Time stopTime,
Time delayBound,
uint16_t maxPktSize,
uint32_t originatorDsn,
uint32_t destinationSN,
uint32_t lifetime,
uint32_t interface)
{
for(std::vector<DelayedPrepStruct>::iterator dpsi=m_delayedPrepStruct.begin ();dpsi!=m_delayedPrepStruct.end ();dpsi++)
{
if(
(dpsi->destination==dst) &&
(dpsi->source==src) &&
(dpsi->cnnType==cnnType) &&
(dpsi->srcIpv4Addr==srcIpv4Addr) &&
(dpsi->dstIpv4Addr==dstIpv4Addr) &&
(dpsi->srcPort==srcPort) &&
(dpsi->dstPort==dstPort)
)
{
NS_LOG_ROUTING("scheduledBefore");
return;
}
}
DelayedPrepStruct dps;
dps.destination=dst;
dps.source=src;
dps.cnnType=cnnType;
dps.srcIpv4Addr=srcIpv4Addr;
dps.dstIpv4Addr=dstIpv4Addr;
dps.srcPort=srcPort;
dps.dstPort=dstPort;
dps.rho=rho;
dps.sigma=sigma;
dps.stopTime=stopTime;
dps.delayBound=delayBound;
dps.maxPktSize=maxPktSize;
dps.initMetric=initMetric;
dps.originatorDsn=originatorDsn;
dps.destinationSN=destinationSN;
dps.lifetime=lifetime;
dps.interface=interface;
dps.whenScheduled=Simulator::Now();
dps.prepTimeout=Simulator::Schedule(Seconds (0.1),&HwmpProtocol::SendDelayedPrep,this,dps);
NS_LOG_ROUTING("scheduled for " << "1" << " seconds");
m_delayedPrepStruct.push_back (dps);
}
void
HwmpProtocol::SendDelayedPrep(DelayedPrepStruct dps)
{
NS_LOG_ROUTING("trying to send prep to " << dps.destination);
HwmpRtable::CnnBasedLookupResult result=m_rtable->LookupCnnBasedReverse(dps.destination,dps.cnnType,dps.srcIpv4Addr,dps.dstIpv4Addr,dps.srcPort,dps.dstPort);
if (result.retransmitter == Mac48Address::GetBroadcast ())
{
NS_LOG_ROUTING("cant find reverse path");
return;
}
//this is only for assigning a VB for this connection
if(!m_rtable->AddCnnBasedReactivePath (
dps.destination,
GetAddress (),
dps.source,
result.retransmitter,
dps.interface,
dps.cnnType,
dps.srcIpv4Addr,
dps.dstIpv4Addr,
dps.srcPort,
dps.dstPort,
dps.rho,
dps.sigma,
dps.stopTime,
dps.delayBound,
dps.maxPktSize,
Seconds (dps.lifetime),
dps.originatorDsn,
false,
m_doCAC))
{
return;
}
SendPrep (
GetAddress (),
dps.destination,
result.retransmitter,
dps.initMetric,
dps.cnnType,
dps.srcIpv4Addr,
dps.dstIpv4Addr,
dps.srcPort,
dps.dstPort,
dps.rho,
dps.sigma,
dps.stopTime,
dps.delayBound,
dps.maxPktSize,
dps.originatorDsn,
dps.destinationSN,
dps.lifetime,
dps.interface
);
NS_LOG_ROUTING("prep sent and AddCnnBasedReactivePath");
//std::vector<DelayedPrepStruct>::iterator it=std::find(m_delayedPrepStruct.begin (),m_delayedPrepStruct.end (),dps);
//if(it!=m_delayedPrepStruct.end ())
// m_delayedPrepStruct.erase (it); // we dont erase the entry from the vector cause of preventing to send prep twice
}
void
HwmpProtocol::ReceivePrep (IePrep prep, Mac48Address from, uint32_t interface, Mac48Address fromMp, uint32_t metric)
{
NS_LOG_UNCOND( Simulator::Now ().GetSeconds () << " " << (int)Simulator::GetContext () << " prep received " << prep.GetSrcIpv4Addr() << ":" << (int)prep.GetSrcPort() << "=>" << prep.GetDstIpv4Addr() << ":" << (int)prep.GetDstPort());
NS_LOG_ROUTING("prep received");
if(prep.GetDestinationAddress () == GetAddress ()){
NS_LOG_ROUTING("prep received for me");
CbrConnection connection;
connection.cnnType=prep.GetCnnType ();
connection.dstIpv4Addr=prep.GetDstIpv4Addr ();
connection.srcIpv4Addr=prep.GetSrcIpv4Addr ();
connection.dstPort=prep.GetDstPort ();
connection.srcPort=prep.GetSrcPort ();
CbrConnectionsVector::iterator nrccvi=std::find(m_notRoutedCbrConnections.begin(),m_notRoutedCbrConnections.end(),connection);
if(nrccvi!=m_notRoutedCbrConnections.end()){
NS_LOG_ROUTING("sourceCnnHasDropped " << prep.GetSrcIpv4Addr() << ":" << (int)prep.GetSrcPort() << "=>" << prep.GetDstIpv4Addr() << ":" << (int)prep.GetDstPort() << " " << from);
return;
}
}
prep.IncrementMetric (metric);
//acceptance cretirea:
bool freshInfo (true);
std::vector<CnnBasedSeqnoMetricDatabase>::iterator dbit;
for(std::vector<CnnBasedSeqnoMetricDatabase>::iterator i=m_hwmpSeqnoMetricDatabase.begin();i!=m_hwmpSeqnoMetricDatabase.end();i++)
{
if(
(i->originatorAddress==prep.GetOriginatorAddress()) &&
(i->cnnType==prep.GetCnnType()) &&
(i->srcIpv4Addr==prep.GetSrcIpv4Addr()) &&
(i->srcPort==prep.GetSrcPort()) &&
(i->dstIpv4Addr==prep.GetDstIpv4Addr()) &&
(i->dstPort==prep.GetDstPort())
)
{
if ((int32_t)(i->destinationSeqNumber - prep.GetDestinationSeqNumber()) > 0)
{
/*BarghiTest 1392/08/02 add for get result start*/
//commented for hadireports std::cout << "t:" << Simulator::Now() << " ,Im " << m_address << " returning because of older preq" << std::endl;
/*BarghiTest 1392/08/02 add for get result end*/
NS_LOG_ROUTING("hwmp droppedCPREP seqnum " << prep.GetSrcIpv4Addr() << ":" << (int)prep.GetSrcPort() << "=>" << prep.GetDstIpv4Addr() << ":" << (int)prep.GetDstPort() << " " << from);
return;
}
dbit=i;
freshInfo=false;
break;
}
}
if(freshInfo)
{
CnnBasedSeqnoMetricDatabase newDb;
newDb.originatorAddress=prep.GetOriginatorAddress();
newDb.originatorSeqNumber=prep.GetOriginatorSeqNumber();
newDb.destinationAddress=prep.GetDestinationAddress();
newDb.destinationSeqNumber=prep.GetDestinationSeqNumber();
newDb.metric=prep.GetMetric();
newDb.cnnType=prep.GetCnnType();
newDb.srcIpv4Addr=prep.GetSrcIpv4Addr();
newDb.dstIpv4Addr=prep.GetDstIpv4Addr();
newDb.srcPort=prep.GetSrcPort();
newDb.dstPort=prep.GetDstPort();
m_hwmpSeqnoMetricDatabase.push_back(newDb);
if (prep.GetDestinationAddress () == GetAddress ())
{
if(!m_rtable->AddCnnBasedReactivePath (
prep.GetOriginatorAddress (),
from,
GetAddress (),
GetAddress (),
interface,
prep.GetCnnType (),
prep.GetSrcIpv4Addr (),
prep.GetDstIpv4Addr (),
prep.GetSrcPort (),
prep.GetDstPort (),
prep.GetRho (),
prep.GetSigma (),
prep.GetStopTime (),
prep.GetDelayBound (),
prep.GetMaxPktSize (),
Seconds (10000),
prep.GetOriginatorSeqNumber (),
false,
m_doCAC))
{
NS_LOG_ROUTING("cac rejected at sourceWhenPrepReceived the connection ");
CbrConnection connection;
connection.destination=prep.GetOriginatorAddress ();
connection.source=GetAddress ();
connection.cnnType=prep.GetCnnType ();
connection.dstIpv4Addr=prep.GetDstIpv4Addr ();
connection.srcIpv4Addr=prep.GetSrcIpv4Addr ();
connection.dstPort=prep.GetDstPort ();
connection.srcPort=prep.GetSrcPort ();
m_notRoutedCbrConnections.push_back (connection);
return;
}
m_rtable->AddPrecursor (prep.GetDestinationAddress (), interface, from,
MicroSeconds (prep.GetLifetime () * 1024));
/*if (result.retransmitter != Mac48Address::GetBroadcast ())
{
m_rtable->AddPrecursor (prep.GetOriginatorAddress (), interface, result.retransmitter,
result.lifetime);
}*/
//ReactivePathResolved (prep.GetOriginatorAddress ());
NS_LOG_ROUTING("hwmp routing pathResolved and AddCnnBasedReactivePath " << prep.GetOriginatorAddress ()<< " " << prep.GetSrcIpv4Addr() << ":" << (int)prep.GetSrcPort() << "=>" << prep.GetDstIpv4Addr() << ":" << (int)prep.GetDstPort() << " " << from);
CnnBasedReactivePathResolved(prep.GetOriginatorAddress (),GetAddress (),prep.GetCnnType (),prep.GetSrcIpv4Addr (),prep.GetDstIpv4Addr (),prep.GetSrcPort (),prep.GetDstPort ());
m_CbrCnnStateChanged(prep.GetSrcIpv4Addr(),prep.GetDstIpv4Addr(),prep.GetSrcPort(),prep.GetDstPort(),true);
InsertCbrCnnAtSourceIntoSourceCbrCnnsVector(prep.GetOriginatorAddress(),GetAddress (),prep.GetCnnType(),prep.GetSrcIpv4Addr(),prep.GetDstIpv4Addr(),prep.GetSrcPort(),prep.GetDstPort(),GetAddress(),from);
NS_LOG_DEBUG ("I am "<<GetAddress ()<<", resolved "<<prep.GetOriginatorAddress ());
return;
}
}else
{
NS_LOG_ROUTING("duplicate prep not allowed!");
NS_ASSERT(false);
}
//update routing info
//Now add a path to destination and add precursor to source
NS_LOG_DEBUG ("I am " << GetAddress () << ", received prep from " << prep.GetOriginatorAddress () << ", receiver was:" << from);
HwmpRtable::CnnBasedLookupResult result=m_rtable->LookupCnnBasedReverse(prep.GetDestinationAddress(),prep.GetCnnType(),prep.GetSrcIpv4Addr(),prep.GetDstIpv4Addr(),prep.GetSrcPort(),prep.GetDstPort());
if (result.retransmitter == Mac48Address::GetBroadcast ())
{
NS_LOG_ROUTING("cant find reverse path 2");
return;
}
if(!m_rtable->AddCnnBasedReactivePath ( prep.GetOriginatorAddress (),
from,
prep.GetDestinationAddress (),
result.retransmitter,
interface,
prep.GetCnnType (),
prep.GetSrcIpv4Addr (),
prep.GetDstIpv4Addr (),
prep.GetSrcPort (),
prep.GetDstPort (),
prep.GetRho (),
prep.GetSigma (),
prep.GetStopTime (),
prep.GetDelayBound (),
prep.GetMaxPktSize (),
Seconds (10000),
prep.GetOriginatorSeqNumber (),
true,
m_doCAC))
{
NS_LOG_ROUTING("cnnRejectedAtPrep " << prep.GetSrcIpv4Addr() << ":" << (int)prep.GetSrcPort() << "=>" << prep.GetDstIpv4Addr() << ":" << (int)prep.GetDstPort());
return;
}
InsertCbrCnnIntoCbrCnnsVector(prep.GetOriginatorAddress(),prep.GetDestinationAddress(),prep.GetCnnType(),prep.GetSrcIpv4Addr(),prep.GetDstIpv4Addr(),prep.GetSrcPort(),prep.GetDstPort(),result.retransmitter,from);
//Forward PREP
NS_LOG_ROUTING("hwmp routing pathSaved and AddCnnBasedReactivePath and SendPrep " << prep.GetOriginatorAddress () << " " << result.retransmitter << " " << prep.GetSrcIpv4Addr() << ":" << (int)prep.GetSrcPort() << "=>" << prep.GetDstIpv4Addr() << ":" << (int)prep.GetDstPort() << " " << from << " " << result.retransmitter);
HwmpProtocolMacMap::const_iterator prep_sender = m_interfaces.find (result.ifIndex);
NS_ASSERT (prep_sender != m_interfaces.end ());
prep_sender->second->SendPrep (prep, result.retransmitter);
}
void
HwmpProtocol::InsertCbrCnnAtSourceIntoSourceCbrCnnsVector(
Mac48Address destination,
Mac48Address source,
uint8_t cnnType,
Ipv4Address srcIpv4Addr,
Ipv4Address dstIpv4Addr,
uint16_t srcPort,
uint16_t dstPort,
Mac48Address prevHop,
Mac48Address nextHop
){
NS_LOG_ROUTING("hwmp inserting cnn into cnnsvector at source " << srcIpv4Addr << ":" << (int)srcPort << "=>" << dstIpv4Addr << ":" << (int)dstPort << " n " << nextHop << " p " << prevHop);
CbrConnection connection;
connection.destination=destination;
connection.source=source;
connection.cnnType=cnnType;
connection.dstIpv4Addr=dstIpv4Addr;
connection.srcIpv4Addr=srcIpv4Addr;
connection.dstPort=dstPort;
connection.srcPort=srcPort;
connection.prevMac=prevHop;
connection.nextMac=nextHop;
connection.whenExpires=Simulator::Now()+MilliSeconds(SOURCE_CBR_ROUTE_EXPIRE_MILLISECONDS);
CbrConnectionsVector::iterator ccvi=std::find(m_sourceCbrConnections.begin(),m_sourceCbrConnections.end(),connection);
if(ccvi==m_sourceCbrConnections.end()){
NS_LOG_ROUTING("hwmp new, inserted at source " << srcIpv4Addr << ":" << (int)srcPort << "=>" << dstIpv4Addr << ":" << (int)dstPort << " n " << nextHop << " p " << prevHop);
m_sourceCbrConnections.push_back(connection);
}else{
NS_LOG_ROUTING("hwmp exist, expiration extended at source " << srcIpv4Addr << ":" << (int)srcPort << "=>" << dstIpv4Addr << ":" << (int)dstPort << " n " << nextHop << " p " << prevHop);
ccvi->whenExpires=Simulator::Now()+Seconds(SOURCE_CBR_ROUTE_EXPIRE_MILLISECONDS);
}
}
void
HwmpProtocol::SourceCbrRouteExtend(
Mac48Address destination,
Mac48Address source,
uint8_t cnnType,
Ipv4Address srcIpv4Addr,
Ipv4Address dstIpv4Addr,
uint16_t srcPort,
uint16_t dstPort
){
NS_LOG_ROUTING("hwmp cbr route extend at source " << srcIpv4Addr << ":" << (int)srcPort << "=>" << dstIpv4Addr << ":" << (int)dstPort);
CbrConnection connection;
connection.destination=destination;
connection.source=source;
connection.cnnType=cnnType;
connection.dstIpv4Addr=dstIpv4Addr;
connection.srcIpv4Addr=srcIpv4Addr;
connection.dstPort=dstPort;
connection.srcPort=srcPort;
CbrConnectionsVector::iterator ccvi=std::find(m_sourceCbrConnections.begin(),m_sourceCbrConnections.end(),connection);
if(ccvi!=m_sourceCbrConnections.end()){
NS_LOG_ROUTING("hwmp cbr route really found and extended at source " << srcIpv4Addr << ":" << (int)srcPort << "=>" << dstIpv4Addr << ":" << (int)dstPort << " n " << ccvi->nextMac << " p " << ccvi->prevMac);
ccvi->whenExpires=Simulator::Now()+MilliSeconds(SOURCE_CBR_ROUTE_EXPIRE_MILLISECONDS);
}else{
NS_LOG_ROUTING("hwmp cbr route not found and not extended at source " << srcIpv4Addr << ":" << (int)srcPort << "=>" << dstIpv4Addr << ":" << (int)dstPort);
}
}
void
HwmpProtocol::InsertCbrCnnIntoCbrCnnsVector(
Mac48Address destination,
Mac48Address source,
uint8_t cnnType,
Ipv4Address srcIpv4Addr,
Ipv4Address dstIpv4Addr,
uint16_t srcPort,
uint16_t dstPort,
Mac48Address prevHop,
Mac48Address nextHop
){
NS_LOG_ROUTING("hwmp inserting cnn into cnnsvector " << srcIpv4Addr << ":" << (int)srcPort << "=>" << dstIpv4Addr << ":" << (int)dstPort << " n " << nextHop << " p " << prevHop);
CbrConnection connection;
connection.destination=destination;
connection.source=source;
connection.cnnType=cnnType;
connection.dstIpv4Addr=dstIpv4Addr;
connection.srcIpv4Addr=srcIpv4Addr;
connection.dstPort=dstPort;
connection.srcPort=srcPort;
connection.prevMac=prevHop;
connection.nextMac=nextHop;
connection.whenExpires=Simulator::Now()+Seconds(CBR_ROUTE_EXPIRE_SECONDS);
//connection.routeExpireEvent=Simulator::Schedule(Seconds(CBR_ROUTE_EXPIRE_SECONDS),&HwmpProtocol::CbrRouteExpire,this,connection);
CbrConnectionsVector::iterator ccvi=std::find(m_cbrConnections.begin(),m_cbrConnections.end(),connection);
if(ccvi==m_cbrConnections.end()){
NS_LOG_ROUTING("hwmp new, inserted " << srcIpv4Addr << ":" << (int)srcPort << "=>" << dstIpv4Addr << ":" << (int)dstPort << " n " << nextHop << " p " << prevHop);
m_cbrConnections.push_back(connection);
}else{
NS_LOG_ROUTING("hwmp exist, expiration extended " << srcIpv4Addr << ":" << (int)srcPort << "=>" << dstIpv4Addr << ":" << (int)dstPort << " n " << nextHop << " p " << prevHop);
ccvi->whenExpires=Simulator::Now()+Seconds(CBR_ROUTE_EXPIRE_SECONDS);
ccvi->nextMac=nextHop;
ccvi->prevMac=prevHop;
//m_cbrConnections.erase(ccvi);
//m_cbrConnections.push_back(connection);
//ccvi->routeExpireEvent.Cancel();
//ccvi->routeExpireEvent=Simulator::Schedule(Seconds(CBR_ROUTE_EXPIRE_SECONDS),&HwmpProtocol::CbrRouteExpire,this,connection);
}
}
void
HwmpProtocol::CbrRouteExtend(
Mac48Address destination,
Mac48Address source,
uint8_t cnnType,
Ipv4Address srcIpv4Addr,
Ipv4Address dstIpv4Addr,
uint16_t srcPort,
uint16_t dstPort
){
NS_LOG_ROUTING("hwmp cbr route extend " << srcIpv4Addr << ":" << (int)srcPort << "=>" << dstIpv4Addr << ":" << (int)dstPort);
CbrConnection connection;
connection.destination=destination;
connection.source=source;
connection.cnnType=cnnType;
connection.dstIpv4Addr=dstIpv4Addr;
connection.srcIpv4Addr=srcIpv4Addr;
connection.dstPort=dstPort;
connection.srcPort=srcPort;
CbrConnectionsVector::iterator ccvi=std::find(m_cbrConnections.begin(),m_cbrConnections.end(),connection);
if(ccvi!=m_cbrConnections.end()){
NS_LOG_ROUTING("hwmp cbr route really found and extended " << srcIpv4Addr << ":" << (int)srcPort << "=>" << dstIpv4Addr << ":" << (int)dstPort << " n " << ccvi->nextMac << " p " << ccvi->prevMac);
ccvi->whenExpires=Simulator::Now()+Seconds(CBR_ROUTE_EXPIRE_SECONDS);
//ccvi->routeExpireEvent.Cancel();
//ccvi->routeExpireEvent=Simulator::Schedule(Seconds(CBR_ROUTE_EXPIRE_SECONDS),&HwmpProtocol::CbrRouteExpire,this,connection);
}else{
NS_LOG_ROUTING("hwmp cbr route not found and not extended " << srcIpv4Addr << ":" << (int)srcPort << "=>" << dstIpv4Addr << ":" << (int)dstPort);
}
}
void
HwmpProtocol::CbrRouteExpire(CbrConnection cbrCnn){
NS_LOG_ROUTING("hwmp cbr route expired " << cbrCnn.srcIpv4Addr << ":" << (int)cbrCnn.srcPort << "=>" << cbrCnn.dstIpv4Addr << ":" << (int)cbrCnn.dstPort << " n " << cbrCnn.nextMac << " p " << cbrCnn.prevMac);
CbrConnectionsVector::iterator ccvi=std::find(m_cbrConnections.begin(),m_cbrConnections.end(),cbrCnn);
if(ccvi!=m_cbrConnections.end()){
m_cbrConnections.erase(ccvi);
m_rtable->DeleteCnnBasedReactivePath(cbrCnn.destination,cbrCnn.source,cbrCnn.cnnType,cbrCnn.srcIpv4Addr,cbrCnn.dstIpv4Addr,cbrCnn.srcPort,cbrCnn.dstPort);
NS_LOG_ROUTING("hwmp cbr route deleted " << cbrCnn.srcIpv4Addr << ":" << (int)cbrCnn.srcPort << "=>" << cbrCnn.dstIpv4Addr << ":" << (int)cbrCnn.dstPort << " n " << cbrCnn.nextMac << " p " << cbrCnn.prevMac);
}
}
void
HwmpProtocol::CheckCbrRoutes4Expiration(){
CbrConnectionsVector tempvector;
bool changed=false;
for(CbrConnectionsVector::iterator ccvi=m_cbrConnections.begin();ccvi!=m_cbrConnections.end();ccvi++){
if(Simulator::Now()<ccvi->whenExpires){
tempvector.push_back(*ccvi);
}else{
changed = true;
m_rtable->DeleteCnnBasedReactivePath(ccvi->destination,ccvi->source,ccvi->cnnType,ccvi->srcIpv4Addr,ccvi->dstIpv4Addr,ccvi->srcPort,ccvi->dstPort);
NS_LOG_ROUTING("hwmp cbr route expired and deleted " << ccvi->srcIpv4Addr << ":" << (int)ccvi->srcPort << "=>" << ccvi->dstIpv4Addr << ":" << (int)ccvi->dstPort << " n " << ccvi->nextMac << " p " << ccvi->prevMac);
}
}
if(changed){
m_cbrConnections.clear();
m_cbrConnections=tempvector;
NS_LOG_ROUTING("hwmp num connections " << m_cbrConnections.size());
}
tempvector.clear();
for(CbrConnectionsVector::iterator ccvi=m_sourceCbrConnections.begin();ccvi!=m_sourceCbrConnections.end();ccvi++){
if(Simulator::Now()<ccvi->whenExpires){
tempvector.push_back(*ccvi);
}else{
changed = true;
m_CbrCnnStateChanged(ccvi->srcIpv4Addr,ccvi->dstIpv4Addr,ccvi->srcPort,ccvi->dstPort,false);
}
}
if(changed){
m_sourceCbrConnections.clear();
m_sourceCbrConnections=tempvector;
}
Simulator::Schedule(MilliSeconds(50),&HwmpProtocol::CheckCbrRoutes4Expiration,this);
}
void
HwmpProtocol::ReceivePerr (std::vector<FailedDestination> destinations, Mac48Address from, uint32_t interface, Mac48Address fromMp)
{
//Acceptance cretirea:
NS_LOG_DEBUG ("I am "<<GetAddress ()<<", received PERR from "<<from);
std::vector<FailedDestination> retval;
HwmpRtable::LookupResult result;
for (unsigned int i = 0; i < destinations.size (); i++)
{
result = m_rtable->LookupReactiveExpired (destinations[i].destination);
if (!(
(result.retransmitter != from) ||
(result.ifIndex != interface) ||
((int32_t)(result.seqnum - destinations[i].seqnum) > 0)
))
{
retval.push_back (destinations[i]);
}
}
if (retval.size () == 0)
{
return;
}
ForwardPathError (MakePathError (retval));
}
void
HwmpProtocol::SendPrep (Mac48Address src,
Mac48Address dst,
Mac48Address retransmitter,
uint32_t initMetric,
uint8_t cnnType,
Ipv4Address srcIpv4Addr,
Ipv4Address dstIpv4Addr,
uint16_t srcPort,
uint16_t dstPort,
uint16_t rho,
uint16_t sigma,
Time stopTime, Time delayBound, uint16_t maxPktSize,
uint32_t originatorDsn,
uint32_t destinationSN,
uint32_t lifetime,
uint32_t interface)
{
IePrep prep;
prep.SetHopcount (0);
prep.SetTtl (m_maxTtl);
prep.SetDestinationAddress (dst);
prep.SetDestinationSeqNumber (destinationSN);
prep.SetLifetime (lifetime);
prep.SetMetric (initMetric);
prep.SetCnnParams(cnnType,srcIpv4Addr,dstIpv4Addr,srcPort,dstPort);
prep.SetRho (rho);
prep.SetSigma (sigma);
prep.SetStopTime (stopTime);
prep.SetDelayBound (delayBound);
prep.SetMaxPktSize (maxPktSize);
prep.SetOriginatorAddress (src);
prep.SetOriginatorSeqNumber (originatorDsn);
HwmpProtocolMacMap::const_iterator prep_sender = m_interfaces.find (interface);
NS_ASSERT (prep_sender != m_interfaces.end ());
prep_sender->second->SendPrep (prep, retransmitter);
m_stats.initiatedPrep++;
}
bool
HwmpProtocol::Install (Ptr<MeshPointDevice> mp)
{
m_mp = mp;
std::vector<Ptr<NetDevice> > interfaces = mp->GetInterfaces ();
for (std::vector<Ptr<NetDevice> >::const_iterator i = interfaces.begin (); i != interfaces.end (); i++)
{
// Checking for compatible net device
Ptr<WifiNetDevice> wifiNetDev = (*i)->GetObject<WifiNetDevice> ();
if (wifiNetDev == 0)
{
return false;
}
Ptr<MeshWifiInterfaceMac> mac = wifiNetDev->GetMac ()->GetObject<MeshWifiInterfaceMac> ();
if (mac == 0)
{
return false;
}
// Installing plugins:
Ptr<HwmpProtocolMac> hwmpMac = Create<HwmpProtocolMac> (wifiNetDev->GetIfIndex (), this);
m_interfaces[wifiNetDev->GetIfIndex ()] = hwmpMac;
mac->InstallPlugin (hwmpMac);
//Installing airtime link metric:
Ptr<AirtimeLinkMetricCalculator> metric = CreateObject <AirtimeLinkMetricCalculator> ();
mac->SetLinkMetricCallback (MakeCallback (&AirtimeLinkMetricCalculator::CalculateMetric, metric));
}
mp->SetRoutingProtocol (this);
// Mesh point aggregates all installed protocols
mp->AggregateObject (this);
m_address = Mac48Address::ConvertFrom (mp->GetAddress ()); // address;
return true;
}
void
HwmpProtocol::PeerLinkStatus (Mac48Address meshPointAddress, Mac48Address peerAddress, uint32_t interface, bool status)
{
if (status)
{
return;
}
std::vector<FailedDestination> destinations = m_rtable->GetUnreachableDestinations (peerAddress);
InitiatePathError (MakePathError (destinations));
}
void
HwmpProtocol::SetNeighboursCallback (Callback<std::vector<Mac48Address>, uint32_t> cb)
{
m_neighboursCallback = cb;
}
bool
HwmpProtocol::DropDataFrame (uint32_t seqno, Mac48Address source)
{
if (source == GetAddress ())
{
return true;
}
std::map<Mac48Address, uint32_t,std::less<Mac48Address> >::const_iterator i = m_lastDataSeqno.find (source);
if (i == m_lastDataSeqno.end ())
{
m_lastDataSeqno[source] = seqno;
}
else
{
if ((int32_t)(i->second - seqno) >= 0)
{
return true;
}
m_lastDataSeqno[source] = seqno;
}
return false;
}
HwmpProtocol::PathError
HwmpProtocol::MakePathError (std::vector<FailedDestination> destinations)
{
PathError retval;
//HwmpRtable increments a sequence number as written in 11B.9.7.2
retval.receivers = GetPerrReceivers (destinations);
if (retval.receivers.size () == 0)
{
return retval;
}
m_stats.initiatedPerr++;
for (unsigned int i = 0; i < destinations.size (); i++)
{
retval.destinations.push_back (destinations[i]);
m_rtable->DeleteReactivePath (destinations[i].destination);
}
return retval;
}
void
HwmpProtocol::InitiatePathError (PathError perr)
{
for (HwmpProtocolMacMap::const_iterator i = m_interfaces.begin (); i != m_interfaces.end (); i++)
{
std::vector<Mac48Address> receivers_for_interface;
for (unsigned int j = 0; j < perr.receivers.size (); j++)
{
if (i->first == perr.receivers[j].first)
{
receivers_for_interface.push_back (perr.receivers[j].second);
}
}
i->second->InitiatePerr (perr.destinations, receivers_for_interface);
}
}
void
HwmpProtocol::ForwardPathError (PathError perr)
{
for (HwmpProtocolMacMap::const_iterator i = m_interfaces.begin (); i != m_interfaces.end (); i++)
{
std::vector<Mac48Address> receivers_for_interface;
for (unsigned int j = 0; j < perr.receivers.size (); j++)
{
if (i->first == perr.receivers[j].first)
{
receivers_for_interface.push_back (perr.receivers[j].second);
}
}
i->second->ForwardPerr (perr.destinations, receivers_for_interface);
}
}
std::vector<std::pair<uint32_t, Mac48Address> >
HwmpProtocol::GetPerrReceivers (std::vector<FailedDestination> failedDest)
{
HwmpRtable::PrecursorList retval;
for (unsigned int i = 0; i < failedDest.size (); i++)
{
HwmpRtable::PrecursorList precursors = m_rtable->GetPrecursors (failedDest[i].destination);
m_rtable->DeleteReactivePath (failedDest[i].destination);
m_rtable->DeleteProactivePath (failedDest[i].destination);
for (unsigned int j = 0; j < precursors.size (); j++)
{
retval.push_back (precursors[j]);
}
}
//Check if we have dublicates in retval and precursors:
for (unsigned int i = 0; i < retval.size (); i++)
{
for (unsigned int j = i+1; j < retval.size (); j++)
{
if (retval[i].second == retval[j].second)
{
retval.erase (retval.begin () + j);
}
}
}
return retval;
}
std::vector<Mac48Address>
HwmpProtocol::GetPreqReceivers (uint32_t interface)
{
std::vector<Mac48Address> retval;
if (!m_neighboursCallback.IsNull ())
{
retval = m_neighboursCallback (interface);
}
if ((retval.size () >= m_unicastPreqThreshold) || (retval.size () == 0))
{
retval.clear ();
retval.push_back (Mac48Address::GetBroadcast ());
}
return retval;
}
std::vector<Mac48Address>
HwmpProtocol::GetBroadcastReceivers (uint32_t interface)
{
std::vector<Mac48Address> retval;
if (!m_neighboursCallback.IsNull ())
{
retval = m_neighboursCallback (interface);
}
if ((retval.size () >= m_unicastDataThreshold) || (retval.size () == 0))
{
retval.clear ();
retval.push_back (Mac48Address::GetBroadcast ());
}
return retval;
}
bool
HwmpProtocol::QueuePacket (QueuedPacket packet)
{
if (m_rqueue.size () >= m_maxQueueSize)
{
NS_LOG_CAC("packetDroppedAtHwmp " << (int)packet.pkt->GetUid () << " " << m_rqueue.size ());
return false;
}
m_rqueue.push_back (packet);
return true;
}
HwmpProtocol::QueuedPacket
HwmpProtocol::DequeueFirstPacketByCnnParams (
Mac48Address dst,
Mac48Address src,
uint8_t cnnType,
Ipv4Address srcIpv4Addr,
Ipv4Address dstIpv4Addr,
uint16_t srcPort,
uint16_t dstPort
)
{
QueuedPacket retval;
retval.pkt = 0;
NS_LOG_ROUTING("hwmp DequeueFirstPacketByCnnParams " << (int)m_rqueue.size());
for (std::vector<QueuedPacket>::iterator i = m_rqueue.begin (); i != m_rqueue.end (); i++)
{
if (
((*i).dst == dst) &&
((*i).src == src) &&
((*i).cnnType == cnnType) &&
((*i).srcIpv4Addr == srcIpv4Addr) &&
((*i).dstIpv4Addr == dstIpv4Addr) &&
((*i).srcPort == srcPort) &&
((*i).dstPort == dstPort)
)
{
retval = (*i);
m_rqueue.erase (i);
break;
}
}
//std::cout << Simulator::Now().GetSeconds() << " " << m_address << " SourceQueueSize " << m_rqueue.size() << std::endl;
return retval;
}
HwmpProtocol::QueuedPacket
HwmpProtocol::DequeueFirstPacketByDst (Mac48Address dst)
{
QueuedPacket retval;
retval.pkt = 0;
for (std::vector<QueuedPacket>::iterator i = m_rqueue.begin (); i != m_rqueue.end (); i++)
{
if ((*i).dst == dst)
{
retval = (*i);
m_rqueue.erase (i);
break;
}
}
return retval;
}
HwmpProtocol::QueuedPacket
HwmpProtocol::DequeueFirstPacket ()
{
QueuedPacket retval;
retval.pkt = 0;
if (m_rqueue.size () != 0)
{
retval = m_rqueue[0];
m_rqueue.erase (m_rqueue.begin ());
}
return retval;
}
void
HwmpProtocol::ReactivePathResolved (Mac48Address dst)
{
std::map<Mac48Address, PreqEvent>::iterator i = m_preqTimeouts.find (dst);
if (i != m_preqTimeouts.end ())
{
m_routeDiscoveryTimeCallback (Simulator::Now () - i->second.whenScheduled);
}
HwmpRtable::LookupResult result = m_rtable->LookupReactive (dst);
NS_ASSERT (result.retransmitter != Mac48Address::GetBroadcast ());
//Send all packets stored for this destination
QueuedPacket packet = DequeueFirstPacketByDst (dst);
while (packet.pkt != 0)
{
if(packet.src==GetAddress()){
NS_LOG_ROUTING("tx4mSource2 " << (int)packet.pkt->GetUid());
}
//set RA tag for retransmitter:
HwmpTag tag;
packet.pkt->RemovePacketTag (tag);
tag.SetAddress (result.retransmitter);
packet.pkt->AddPacketTag (tag);
m_stats.txUnicast++;
m_stats.txBytes += packet.pkt->GetSize ();
packet.reply (true, packet.pkt, packet.src, packet.dst, packet.protocol, result.ifIndex);
packet = DequeueFirstPacketByDst (dst);
}
}
void
HwmpProtocol::CnnBasedReactivePathResolved (
Mac48Address dst,
Mac48Address src,
uint8_t cnnType,
Ipv4Address srcIpv4Addr,
Ipv4Address dstIpv4Addr,
uint16_t srcPort,
uint16_t dstPort
)
{
HwmpRtable::CnnBasedLookupResult result = m_rtable->LookupCnnBasedReactive(dst,src,cnnType,srcIpv4Addr,dstIpv4Addr,srcPort,dstPort);
NS_ASSERT (result.retransmitter != Mac48Address::GetBroadcast ());
//Send all packets stored for this destination
QueuedPacket packet = DequeueFirstPacketByCnnParams (dst,src,cnnType,srcIpv4Addr,dstIpv4Addr,srcPort,dstPort);
while (packet.pkt != 0)
{
if((packet.src==GetAddress())&&(cnnType==HwmpRtable::CNN_TYPE_IP_PORT)){
NS_LOG_ROUTING("tx4mSource2 " << (int)packet.pkt->GetUid());
NS_LOG_CAC("tx4mSource2 " << (int)packet.pkt->GetUid());
m_txed4mSourceCallback();
}
//set RA tag for retransmitter:
HwmpTag tag;
packet.pkt->RemovePacketTag (tag);
tag.SetAddress (result.retransmitter);
packet.pkt->AddPacketTag (tag);
m_stats.txUnicast++;
m_stats.txBytes += packet.pkt->GetSize ();
//packet.reply (true, packet.pkt, packet.src, packet.dst, packet.protocol, result.ifIndex);
// m_rtable->QueueCnnBasedPacket (packet.dst,packet.src,cnnType,srcIpv4Addr,dstIpv4Addr,srcPort,dstPort,packet.pkt,packet.protocol,result.ifIndex,packet.reply);
packet = DequeueFirstPacketByCnnParams (dst,src,cnnType,srcIpv4Addr,dstIpv4Addr,srcPort,dstPort);
}
}
void
HwmpProtocol::ProactivePathResolved ()
{
//send all packets to root
HwmpRtable::LookupResult result = m_rtable->LookupProactive ();
NS_ASSERT (result.retransmitter != Mac48Address::GetBroadcast ());
QueuedPacket packet = DequeueFirstPacket ();
while (packet.pkt != 0)
{
//set RA tag for retransmitter:
HwmpTag tag;
if (!packet.pkt->RemovePacketTag (tag))
{
NS_FATAL_ERROR ("HWMP tag must be present at this point");
}
tag.SetAddress (result.retransmitter);
packet.pkt->AddPacketTag (tag);
m_stats.txUnicast++;
m_stats.txBytes += packet.pkt->GetSize ();
packet.reply (true, packet.pkt, packet.src, packet.dst, packet.protocol, result.ifIndex);
packet = DequeueFirstPacket ();
}
}
bool
HwmpProtocol::ShouldSendPreq (Mac48Address dst)
{
std::map<Mac48Address, PreqEvent>::const_iterator i = m_preqTimeouts.find (dst);
if (i == m_preqTimeouts.end ())
{
m_preqTimeouts[dst].preqTimeout = Simulator::Schedule (
Time (m_dot11MeshHWMPnetDiameterTraversalTime * 2),
&HwmpProtocol::RetryPathDiscovery, this, dst, 1);
m_preqTimeouts[dst].whenScheduled = Simulator::Now ();
return true;
}
return false;
}
bool
HwmpProtocol::CnnBasedShouldSendPreq (
RhoSigmaTag rsTag,
Mac48Address dst,
Mac48Address src,
uint8_t cnnType,
Ipv4Address srcIpv4Addr,
Ipv4Address dstIpv4Addr,
uint16_t srcPort,
uint16_t dstPort
)
{
for(std::vector<CnnBasedPreqEvent>::iterator cbpei = m_cnnBasedPreqTimeouts.begin (); cbpei != m_cnnBasedPreqTimeouts.end (); cbpei++)
{
if(
(cbpei->destination==dst) &&
(cbpei->source==src) &&
(cbpei->cnnType==cnnType) &&
(cbpei->srcIpv4Addr==srcIpv4Addr) &&
(cbpei->dstIpv4Addr==dstIpv4Addr) &&
(cbpei->srcPort==srcPort) &&
(cbpei->dstPort==dstPort)
)
{
return false;
}
}
if(src==GetAddress ())
{
if(m_doCAC)
{
// calculate total needed energy for entire connection lifetime and needed energy for bursts.
double totalEnergyNeeded = (m_rtable->m_maxEnergyPerDataPacket+m_rtable->m_maxEnergyPerAckPacket)*(rsTag.GetStopTime ()-Simulator::Now ()).GetSeconds ()*(rsTag.GetRho ()/60)*m_rtable->m_energyAlpha;
double burstEnergyNeeded = (m_rtable->m_maxEnergyPerDataPacket+m_rtable->m_maxEnergyPerAckPacket)*rsTag.GetSigma ()*m_rtable->m_energyAlpha;
double energyUntilEndOfConnection = m_rtable->bPrim ()+ m_rtable->gammaPrim ()*(rsTag.GetStopTime ()-Simulator::Now ()).GetSeconds ();
NS_LOG_ROUTING("ReceiveFirstPacketCACCheck " << m_rtable->m_maxEnergyPerDataPacket << " " << m_rtable->m_maxEnergyPerAckPacket << " " << (int)rsTag.GetRho () << " " << (int)rsTag.GetSigma () << " " << rsTag.GetStopTime () << " ; " << totalEnergyNeeded << " " << burstEnergyNeeded << " " << energyUntilEndOfConnection << " " << m_rtable->bPrim ());
if( ( ( m_rtable->bPrim () < burstEnergyNeeded ) || ( energyUntilEndOfConnection < totalEnergyNeeded ) ) || (!m_interfaces.begin ()->second->HasEnoughCapacity4NewConnection (GetAddress (),dst,0,GetAddress (),rsTag.GetRho ())) )// CAC check
{
NS_LOG_ROUTING("cac rejected at source the connection " << totalEnergyNeeded << " " << burstEnergyNeeded << " " << energyUntilEndOfConnection << " " << m_rtable->bPrim ());
CbrConnection connection;
connection.destination=dst;
connection.source=src;
connection.cnnType=cnnType;
connection.dstIpv4Addr=dstIpv4Addr;
connection.srcIpv4Addr=srcIpv4Addr;
connection.dstPort=dstPort;
connection.srcPort=srcPort;
m_notRoutedCbrConnections.push_back (connection);
return false;
}
}
else
{
if(m_rtable->bPrim ()<=0)
{
NS_LOG_ROUTING("bPrim()<=0 rejected at source the connection " << m_rtable->bPrim ());
CbrConnection connection;
connection.destination=dst;
connection.source=src;
connection.cnnType=cnnType;
connection.dstIpv4Addr=dstIpv4Addr;
connection.srcIpv4Addr=srcIpv4Addr;
connection.dstPort=dstPort;
connection.srcPort=srcPort;
m_notRoutedCbrConnections.push_back (connection);
return false;
}
}
}
CnnBasedPreqEvent cbpe;
cbpe.destination=dst;
cbpe.source=src;
cbpe.cnnType=cnnType;
cbpe.srcIpv4Addr=srcIpv4Addr;
cbpe.dstIpv4Addr=dstIpv4Addr;
cbpe.srcPort=srcPort;
cbpe.dstPort=dstPort;
cbpe.rho=rsTag.GetRho ();
cbpe.sigma=rsTag.GetSigma ();
cbpe.stopTime=rsTag.GetStopTime ();
cbpe.delayBound=rsTag.delayBound ();
cbpe.maxPktSize=rsTag.maxPktSize ();
cbpe.whenScheduled=Simulator::Now();
cbpe.preqTimeout=Simulator::Schedule(
Time (m_dot11MeshHWMPnetDiameterTraversalTime * 2),
&HwmpProtocol::CnnBasedRetryPathDiscovery,this,cbpe,1);
m_cnnBasedPreqTimeouts.push_back(cbpe);
NS_LOG_ROUTING("need to send preq");
return true;
}
void
HwmpProtocol::RetryPathDiscovery (Mac48Address dst, uint8_t numOfRetry)
{
HwmpRtable::LookupResult result = m_rtable->LookupReactive (dst);
if (result.retransmitter == Mac48Address::GetBroadcast ())
{
result = m_rtable->LookupProactive ();
}
if (result.retransmitter != Mac48Address::GetBroadcast ())
{
std::map<Mac48Address, PreqEvent>::iterator i = m_preqTimeouts.find (dst);
NS_ASSERT (i != m_preqTimeouts.end ());
m_preqTimeouts.erase (i);
return;
}
if (numOfRetry > m_dot11MeshHWMPmaxPREQretries)
{
NS_LOG_ROUTING("givingUpPathRequest " << dst);
QueuedPacket packet = DequeueFirstPacketByDst (dst);
//purge queue and delete entry from retryDatabase
while (packet.pkt != 0)
{
m_stats.totalDropped++;
packet.reply (false, packet.pkt, packet.src, packet.dst, packet.protocol, HwmpRtable::MAX_METRIC);
packet = DequeueFirstPacketByDst (dst);
}
std::map<Mac48Address, PreqEvent>::iterator i = m_preqTimeouts.find (dst);
NS_ASSERT (i != m_preqTimeouts.end ());
m_routeDiscoveryTimeCallback (Simulator::Now () - i->second.whenScheduled);
m_preqTimeouts.erase (i);
return;
}
numOfRetry++;
uint32_t originator_seqno = GetNextHwmpSeqno ();
uint32_t dst_seqno = m_rtable->LookupReactiveExpired (dst).seqnum;
NS_LOG_ROUTING("retryPathRequest " << dst);
for (HwmpProtocolMacMap::const_iterator i = m_interfaces.begin (); i != m_interfaces.end (); i++)
{
Ipv4Address tempadd;
if(m_routingType==2)
i->second->RequestDestination (dst, originator_seqno, dst_seqno,HwmpRtable::CNN_TYPE_PKT_BASED,tempadd,tempadd,0,0,0,0,Seconds (0),Seconds (0),0,0x7fffffff,0x7fffffff,0x7fffffff);
else
i->second->RequestDestination (dst, originator_seqno, dst_seqno,HwmpRtable::CNN_TYPE_PKT_BASED,tempadd,tempadd,0,0,0,0,Seconds (0),Seconds (0),0,0,0,0);
}
m_preqTimeouts[dst].preqTimeout = Simulator::Schedule (
Time ((2 * (numOfRetry + 1)) * m_dot11MeshHWMPnetDiameterTraversalTime),
&HwmpProtocol::RetryPathDiscovery, this, dst, numOfRetry);
}
void
HwmpProtocol::CnnBasedRetryPathDiscovery (
CnnBasedPreqEvent preqEvent,
uint8_t numOfRetry
)
{
HwmpRtable::CnnBasedLookupResult result = m_rtable->LookupCnnBasedReactive(preqEvent.destination,preqEvent.source,preqEvent.cnnType,preqEvent.srcIpv4Addr,preqEvent.dstIpv4Addr,preqEvent.srcPort,preqEvent.dstPort);
if (result.retransmitter != Mac48Address::GetBroadcast ())
{
for(std::vector<CnnBasedPreqEvent>::iterator cbpei = m_cnnBasedPreqTimeouts.begin (); cbpei != m_cnnBasedPreqTimeouts.end (); cbpei++)
{
if(
(cbpei->destination==preqEvent.destination) &&
(cbpei->source==preqEvent.source) &&
(cbpei->cnnType==preqEvent.cnnType) &&
(cbpei->srcIpv4Addr==preqEvent.srcIpv4Addr) &&
(cbpei->dstIpv4Addr==preqEvent.dstIpv4Addr) &&
(cbpei->srcPort==preqEvent.srcPort) &&
(cbpei->dstPort==preqEvent.dstPort)
)
{
m_cnnBasedPreqTimeouts.erase(cbpei);
return;
}
}
NS_ASSERT (false);
return;
}
if (numOfRetry > m_dot11MeshHWMPmaxPREQretries)
{
//hadireport reject connection
NS_LOG_ROUTING("hwmp connectionRejected " << preqEvent.destination << " " << preqEvent.srcIpv4Addr << ":" << (int)preqEvent.srcPort << "=>" << preqEvent.dstIpv4Addr << ":" << (int)preqEvent.dstPort);
QueuedPacket packet = DequeueFirstPacketByCnnParams (preqEvent.destination,preqEvent.source,preqEvent.cnnType,preqEvent.srcIpv4Addr,preqEvent.dstIpv4Addr,preqEvent.srcPort,preqEvent.dstPort);
CbrConnection connection;
connection.destination=preqEvent.destination;
connection.source=preqEvent.source;
connection.cnnType=preqEvent.cnnType;
connection.dstIpv4Addr=preqEvent.dstIpv4Addr;
connection.srcIpv4Addr=preqEvent.srcIpv4Addr;
connection.dstPort=preqEvent.dstPort;
connection.srcPort=preqEvent.srcPort;
CbrConnectionsVector::iterator nrccvi=std::find(m_notRoutedCbrConnections.begin(),m_notRoutedCbrConnections.end(),connection);
if(nrccvi==m_notRoutedCbrConnections.end()){
m_notRoutedCbrConnections.push_back(connection);
}
//purge queue and delete entry from retryDatabase
while (packet.pkt != 0)
{
if(packet.src==GetAddress()){
NS_LOG_ROUTING("hwmp noRouteDrop2 " << (int)packet.pkt->GetUid() << " " << preqEvent.srcIpv4Addr << ":" << (int)preqEvent.srcPort << "=>" << preqEvent.dstIpv4Addr << ":" << (int)preqEvent.dstPort);
}
m_stats.totalDropped++;
packet.reply (false, packet.pkt, packet.src, packet.dst, packet.protocol, HwmpRtable::MAX_METRIC);
packet = DequeueFirstPacketByCnnParams (preqEvent.destination,preqEvent.source,preqEvent.cnnType,preqEvent.srcIpv4Addr,preqEvent.dstIpv4Addr,preqEvent.srcPort,preqEvent.dstPort);
}
for(std::vector<CnnBasedPreqEvent>::iterator cbpei = m_cnnBasedPreqTimeouts.begin (); cbpei != m_cnnBasedPreqTimeouts.end (); cbpei++)
{
if(
(cbpei->destination==preqEvent.destination) &&
(cbpei->cnnType==preqEvent.cnnType) &&
(cbpei->srcIpv4Addr==preqEvent.srcIpv4Addr) &&
(cbpei->dstIpv4Addr==preqEvent.dstIpv4Addr) &&
(cbpei->srcPort==preqEvent.srcPort) &&
(cbpei->dstPort==preqEvent.dstPort)
)
{
m_cnnBasedPreqTimeouts.erase(cbpei);
return;
}
}
NS_ASSERT (false);
return;
}
numOfRetry++;
uint32_t originator_seqno = GetNextHwmpSeqno ();
uint32_t dst_seqno = 0;
for (HwmpProtocolMacMap::const_iterator i = m_interfaces.begin (); i != m_interfaces.end (); i++)
{
if(m_routingType==2)
i->second->RequestDestination (preqEvent.destination, originator_seqno, dst_seqno, preqEvent.cnnType, preqEvent.srcIpv4Addr, preqEvent.dstIpv4Addr, preqEvent.srcPort, preqEvent.dstPort,preqEvent.rho,preqEvent.sigma,preqEvent.stopTime,preqEvent.delayBound,preqEvent.maxPktSize, 0x7fffffff,0x7fffffff,0x7fffffff);
else
i->second->RequestDestination (preqEvent.destination, originator_seqno, dst_seqno, preqEvent.cnnType, preqEvent.srcIpv4Addr, preqEvent.dstIpv4Addr, preqEvent.srcPort, preqEvent.dstPort,preqEvent.rho,preqEvent.sigma,preqEvent.stopTime,preqEvent.delayBound,preqEvent.maxPktSize, 0,0,0);
}
for(std::vector<CnnBasedPreqEvent>::iterator cbpei = m_cnnBasedPreqTimeouts.begin (); cbpei != m_cnnBasedPreqTimeouts.end (); cbpei++)
{
if(
(cbpei->destination==preqEvent.destination) &&
(cbpei->cnnType==preqEvent.cnnType) &&
(cbpei->srcIpv4Addr==preqEvent.srcIpv4Addr) &&
(cbpei->dstIpv4Addr==preqEvent.dstIpv4Addr) &&
(cbpei->srcPort==preqEvent.srcPort) &&
(cbpei->dstPort==preqEvent.dstPort)
)
{
cbpei->preqTimeout=Simulator::Schedule(
Time ((2 * (numOfRetry + 1)) * m_dot11MeshHWMPnetDiameterTraversalTime),
&HwmpProtocol::CnnBasedRetryPathDiscovery,this,(*cbpei),numOfRetry);
cbpei->whenScheduled=Simulator::Now();
return;
}
}
CnnBasedPreqEvent cbpe;
cbpe.destination=preqEvent.destination;
cbpe.cnnType=preqEvent.cnnType;
cbpe.srcIpv4Addr=preqEvent.srcIpv4Addr;
cbpe.dstIpv4Addr=preqEvent.dstIpv4Addr;
cbpe.srcPort=preqEvent.srcPort;
cbpe.dstPort=preqEvent.dstPort;
cbpe.whenScheduled=Simulator::Now();
cbpe.preqTimeout=Simulator::Schedule(
Time ((2 * (numOfRetry + 1)) * m_dot11MeshHWMPnetDiameterTraversalTime),
&HwmpProtocol::CnnBasedRetryPathDiscovery,this,cbpe,numOfRetry);
m_cnnBasedPreqTimeouts.push_back(cbpe);
}
//Proactive PREQ routines:
void
HwmpProtocol::SetRoot ()
{
Time randomStart = Seconds (m_coefficient->GetValue ());
m_proactivePreqTimer = Simulator::Schedule (randomStart, &HwmpProtocol::SendProactivePreq, this);
NS_LOG_DEBUG ("ROOT IS: " << m_address);
m_isRoot = true;
}
void
HwmpProtocol::UnsetRoot ()
{
m_proactivePreqTimer.Cancel ();
}
void
HwmpProtocol::SendProactivePreq ()
{
IePreq preq;
//By default: must answer
preq.SetHopcount (0);
preq.SetTTL (m_maxTtl);
preq.SetLifetime (m_dot11MeshHWMPactiveRootTimeout.GetMicroSeconds () /1024);
//\attention: do not forget to set originator address, sequence
//number and preq ID in HWMP-MAC plugin
preq.AddDestinationAddressElement (true, true, Mac48Address::GetBroadcast (), 0);
preq.SetOriginatorAddress (GetAddress ());
preq.SetPreqID (GetNextPreqId ());
preq.SetOriginatorSeqNumber (GetNextHwmpSeqno ());
for (HwmpProtocolMacMap::const_iterator i = m_interfaces.begin (); i != m_interfaces.end (); i++)
{
i->second->SendPreq (preq);
}
m_proactivePreqTimer = Simulator::Schedule (m_dot11MeshHWMPpathToRootInterval, &HwmpProtocol::SendProactivePreq, this);
}
bool
HwmpProtocol::GetDoFlag ()
{
return m_doFlag;
}
bool
HwmpProtocol::GetRfFlag ()
{
return m_rfFlag;
}
Time
HwmpProtocol::GetPreqMinInterval ()
{
return m_dot11MeshHWMPpreqMinInterval;
}
Time
HwmpProtocol::GetPerrMinInterval ()
{
return m_dot11MeshHWMPperrMinInterval;
}
uint8_t
HwmpProtocol::GetMaxTtl ()
{
return m_maxTtl;
}
uint32_t
HwmpProtocol::GetNextPreqId ()
{
m_preqId++;
return m_preqId;
}
uint32_t
HwmpProtocol::GetNextHwmpSeqno ()
{
m_hwmpSeqno++;
return m_hwmpSeqno;
}
uint32_t
HwmpProtocol::GetActivePathLifetime ()
{
return m_dot11MeshHWMPactivePathTimeout.GetMicroSeconds () / 1024;
}
uint8_t
HwmpProtocol::GetUnicastPerrThreshold ()
{
return m_unicastPerrThreshold;
}
Mac48Address
HwmpProtocol::GetAddress ()
{
return m_address;
}
void
HwmpProtocol::EnergyChange (Ptr<Packet> packet,bool isAck, bool incDec, double energy, double remainedEnergy,uint32_t packetSize)
{
uint8_t cnnType;//1:mac only, 2:ip only , 3:ip port
Ipv4Address srcIpv4Addr;
Ipv4Address dstIpv4Addr;
uint16_t srcPort;
uint16_t dstPort;
if(packet!=0)
{
WifiMacHeader wmhdr;
packet->RemoveHeader (wmhdr);
WifiMacTrailer fcs;
packet->RemoveTrailer (fcs);
MeshHeader meshHdr;
packet->RemoveHeader (meshHdr);
LlcSnapHeader llc;
packet->RemoveHeader (llc);
NS_LOG_VB("rxtx packet llc protocol type " << llc.GetType ());
if(llc.GetType ()==Ipv4L3Protocol::PROT_NUMBER)
{
Ipv4Header ipv4Hdr;
packet->RemoveHeader(ipv4Hdr);
srcIpv4Addr = ipv4Hdr.GetSource();
dstIpv4Addr = ipv4Hdr.GetDestination();
uint8_t protocol = ipv4Hdr.GetProtocol();
if(protocol==TcpL4Protocol::PROT_NUMBER)
{
TcpHeader tcpHdr;
packet->RemoveHeader (tcpHdr);
srcPort=tcpHdr.GetSourcePort ();
dstPort=tcpHdr.GetDestinationPort ();
cnnType=HwmpRtable::CNN_TYPE_PKT_BASED;
}
else if(protocol==UdpL4Protocol::PROT_NUMBER)
{
UdpHeader udpHdr;
packet->RemoveHeader(udpHdr);
srcPort=udpHdr.GetSourcePort();
dstPort=udpHdr.GetDestinationPort();
cnnType=HwmpRtable::CNN_TYPE_IP_PORT;
}
else
{
cnnType=HwmpRtable::CNN_TYPE_MAC_ONLY;
}
}
else
{
cnnType=HwmpRtable::CNN_TYPE_MAC_ONLY;
}
}
double systemB=m_rtable->systemB ();
if(incDec)//increased
{
systemB+=energy;
if(systemB>m_rtable->systemBMax ())
systemB=m_rtable->systemBMax ();
if(packet==0)//increased by gamma or energyback
{
if(packetSize==0)//increased by gamma
{
m_rtable->TotalEnergyIncreasedByGamma (energy);
}
else//increased by collision energy back of other packets
{
m_rtable->ControlEnergyIncreasedByCollisionEnergyBack (energy);
}
}else//increased by collision energy back
{
m_rtable->ChangeEnergy4aConnection (cnnType,srcIpv4Addr,dstIpv4Addr,srcPort,dstPort,energy,true);
}
}else//decreased
{
systemB-=energy;
if(systemB<0)
systemB=0;
if(packet==0)
{
if(packetSize!=0)//decreased by other types of packets
{
if(m_noDataPacketYet)
{
m_energyPerByte = 0.7 * m_energyPerByte + 0.3 * energy/packetSize;
m_rtable->SetMaxEnergyPerAckPacket (m_energyPerByte*14);
m_rtable->SetMaxEnergyPerDataPacket (m_energyPerByte*260);
//NS_LOG_VB("energyPerAckByte " << m_energyPerByte*14);
//NS_LOG_VB("energyPerDataByte " << m_energyPerByte*260);
}
}
m_rtable->ControlPacketsEnergyDecreased (energy);
}
else//decreased by data or ack for data packets
{
m_noDataPacketYet=false;
if(isAck )
{
if(energy > m_rtable->GetMaxEnergyPerAckPacket ())
m_rtable->SetMaxEnergyPerAckPacket (energy);
//NS_LOG_VB("energyPerAck " << energy);
}
else if(cnnType==HwmpRtable::CNN_TYPE_IP_PORT)
{
if(energy > m_rtable->GetMaxEnergyPerDataPacket ())
m_rtable->SetMaxEnergyPerDataPacket (energy);
//NS_LOG_VB("energyPerData " << energy);
}
if(cnnType==HwmpRtable::CNN_TYPE_IP_PORT)
{
m_rtable->ChangeEnergy4aConnection (cnnType,srcIpv4Addr,dstIpv4Addr,srcPort,dstPort,energy,false);
}
else
{
m_rtable->ControlPacketsEnergyDecreased (energy);
}
}
}
if(std::abs(systemB-remainedEnergy)>1)
{
NS_LOG_VB("remainedEnergyError " << systemB << " " << remainedEnergy);
}
else
{
//NS_LOG_VB("remainedEnergy " << systemB << " " << remainedEnergy);
}
m_rtable->setSystemB (remainedEnergy);
}
void
HwmpProtocol::GammaChange(double gamma, double totalSimmTime)
{
m_totalSimulationTime=totalSimmTime;
double remainedSimulationTimeSeconds=m_totalSimulationTime-Simulator::Now ().GetSeconds ();
double remainedControlEnergyNeeded=remainedSimulationTimeSeconds*0.035;
//double remainedControlEnergyNeeded=remainedSimulationTimeSeconds*0;
double bPrim=m_rtable->bPrim ()+m_rtable->controlB ();
double gammaPrim=m_rtable->gammaPrim ()+m_rtable->controlGamma ();
double assignedGamma=m_rtable->assignedGamma ()-m_rtable->controlGamma ();
if(bPrim>=remainedControlEnergyNeeded)
{
m_rtable->setControlB (remainedControlEnergyNeeded);
m_rtable->setControlBMax (remainedControlEnergyNeeded);
m_rtable->setControlGamma (0);
bPrim-=remainedControlEnergyNeeded;
}
else
{
m_rtable->setControlB (bPrim);
m_rtable->setControlBMax (remainedControlEnergyNeeded);
bPrim=0;
double neededControlGamma=(remainedControlEnergyNeeded-bPrim)/remainedSimulationTimeSeconds;
if(gammaPrim>=neededControlGamma)
{
m_rtable->setControlGamma (neededControlGamma);
gammaPrim-=neededControlGamma;
assignedGamma+=neededControlGamma;
}
else
{
m_rtable->setControlGamma (gammaPrim);
assignedGamma+=gammaPrim;
gammaPrim=0;
}
}
m_rtable->setSystemGamma (gamma);
m_rtable->setBPrim (bPrim);
m_rtable->setGammaPrim (gammaPrim);
m_rtable->setAssignedGamma (assignedGamma);
NS_LOG_VB("GammaChange " << gamma << " " << totalSimmTime << " | " << m_rtable->systemGamma () << " " << m_rtable->bPrim () << " " << m_rtable->gammaPrim () << " " << m_rtable->assignedGamma () << " * " << m_rtable->controlGamma () << " " << m_rtable->controlB ());
}
//Statistics:
HwmpProtocol::Statistics::Statistics () :
txUnicast (0),
txBroadcast (0),
txBytes (0),
droppedTtl (0),
totalQueued (0),
totalDropped (0),
initiatedPreq (0),
initiatedPrep (0),
initiatedPerr (0)
{
}
void HwmpProtocol::Statistics::Print (std::ostream & os) const
{
os << "<Statistics "
"txUnicast=\"" << txUnicast << "\" "
"txBroadcast=\"" << txBroadcast << "\" "
"txBytes=\"" << txBytes << "\" "
"droppedTtl=\"" << droppedTtl << "\" "
"totalQueued=\"" << totalQueued << "\" "
"totalDropped=\"" << totalDropped << "\" "
"initiatedPreq=\"" << initiatedPreq << "\" "
"initiatedPrep=\"" << initiatedPrep << "\" "
"initiatedPerr=\"" << initiatedPerr << "\"/>" << std::endl;
}
void
HwmpProtocol::Report (std::ostream & os) const
{
os << "<Hwmp "
"address=\"" << m_address << "\"" << std::endl <<
"maxQueueSize=\"" << m_maxQueueSize << "\"" << std::endl <<
"Dot11MeshHWMPmaxPREQretries=\"" << (uint16_t)m_dot11MeshHWMPmaxPREQretries << "\"" << std::endl <<
"Dot11MeshHWMPnetDiameterTraversalTime=\"" << m_dot11MeshHWMPnetDiameterTraversalTime.GetSeconds () << "\"" << std::endl <<
"Dot11MeshHWMPpreqMinInterval=\"" << m_dot11MeshHWMPpreqMinInterval.GetSeconds () << "\"" << std::endl <<
"Dot11MeshHWMPperrMinInterval=\"" << m_dot11MeshHWMPperrMinInterval.GetSeconds () << "\"" << std::endl <<
"Dot11MeshHWMPactiveRootTimeout=\"" << m_dot11MeshHWMPactiveRootTimeout.GetSeconds () << "\"" << std::endl <<
"Dot11MeshHWMPactivePathTimeout=\"" << m_dot11MeshHWMPactivePathTimeout.GetSeconds () << "\"" << std::endl <<
"Dot11MeshHWMPpathToRootInterval=\"" << m_dot11MeshHWMPpathToRootInterval.GetSeconds () << "\"" << std::endl <<
"Dot11MeshHWMPrannInterval=\"" << m_dot11MeshHWMPrannInterval.GetSeconds () << "\"" << std::endl <<
"isRoot=\"" << m_isRoot << "\"" << std::endl <<
"maxTtl=\"" << (uint16_t)m_maxTtl << "\"" << std::endl <<
"unicastPerrThreshold=\"" << (uint16_t)m_unicastPerrThreshold << "\"" << std::endl <<
"unicastPreqThreshold=\"" << (uint16_t)m_unicastPreqThreshold << "\"" << std::endl <<
"unicastDataThreshold=\"" << (uint16_t)m_unicastDataThreshold << "\"" << std::endl <<
"doFlag=\"" << m_doFlag << "\"" << std::endl <<
"rfFlag=\"" << m_rfFlag << "\">" << std::endl;
m_stats.Print (os);
for (HwmpProtocolMacMap::const_iterator plugin = m_interfaces.begin (); plugin != m_interfaces.end (); plugin++)
{
plugin->second->Report (os);
}
os << "</Hwmp>" << std::endl;
}
void
HwmpProtocol::ResetStats ()
{
m_stats = Statistics ();
for (HwmpProtocolMacMap::const_iterator plugin = m_interfaces.begin (); plugin != m_interfaces.end (); plugin++)
{
plugin->second->ResetStats ();
}
}
int64_t
HwmpProtocol::AssignStreams (int64_t stream)
{
NS_LOG_FUNCTION (this << stream);
m_coefficient->SetStream (stream);
return 1;
}
double HwmpProtocol::GetSumRhoPps()
{
return m_rtable->GetSumRhoPps ();
}
double HwmpProtocol::GetSumGPps()
{
return m_rtable->GetSumGPps ();
}
HwmpProtocol::QueuedPacket::QueuedPacket () :
pkt (0),
protocol (0),
inInterface (0)
{
}
} // namespace dot11s
} // namespace ns3
| hbarghi/VirtualBattery1 | src/mesh/model/dot11s/hwmp-protocol.cc | C++ | gpl-2.0 | 94,361 |
/* Copyright (C) 2001 artofcode LLC. All rights reserved.
This software is provided AS-IS with no warranty, either express or
implied.
This software is distributed under license and may not be copied,
modified or distributed except as expressly authorized under the terms
of the license contained in the file LICENSE in this distribution.
For more information about licensing, please refer to
http://www.ghostscript.com/licensing/. For information on
commercial licensing, go to http://www.artifex.com/licensing/ or
contact Artifex Software, Inc., 101 Lucas Valley Road #110,
San Rafael, CA 94903, U.S.A., +1(415)492-9861.
*/
/* $Id: gp_stdia.c,v 1.5 2002/02/21 22:24:52 giles Exp $ */
/* Read stdin on platforms that support unbuffered read. */
/* We want unbuffered for console input and pipes. */
#include "stdio_.h"
#include "time_.h"
#include "unistd_.h"
#include "gx.h"
#include "gp.h"
/* Read bytes from stdin, unbuffered if possible. */
int gp_stdin_read(char *buf, int len, int interactive, FILE *f)
{
return read(fileno(f), buf, len);
}
| brho/plan9 | sys/src/cmd/gs/src/gp_stdia.c | C | gpl-2.0 | 1,087 |
## Copyright (C) 2007-2012 Red Hat, Inc., Bryn M. Reeves <[email protected]>
### This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
from sos.plugins import Plugin, RedHatPlugin, DebianPlugin, UbuntuPlugin
class SysVIPC(Plugin, RedHatPlugin, DebianPlugin, UbuntuPlugin):
"""SysV IPC related information
"""
plugin_name = "sysvipc"
def setup(self):
self.add_copy_specs([
"/proc/sysvipc/msg",
"/proc/sysvipc/sem",
"/proc/sysvipc/shm"
])
self.add_cmd_output("ipcs")
# vim: et ts=4 sw=4
| portante/sosreport | sos/plugins/sysvipc.py | Python | gpl-2.0 | 1,199 |
/* This file was generated by SableCC (http://www.sablecc.org/). */
package se.sics.kola.node;
import se.sics.kola.analysis.*;
@SuppressWarnings("nls")
public final class AClassFieldAccess extends PFieldAccess
{
private PClassName _className_;
private TIdentifier _identifier_;
public AClassFieldAccess()
{
// Constructor
}
public AClassFieldAccess(
@SuppressWarnings("hiding") PClassName _className_,
@SuppressWarnings("hiding") TIdentifier _identifier_)
{
// Constructor
setClassName(_className_);
setIdentifier(_identifier_);
}
@Override
public Object clone()
{
return new AClassFieldAccess(
cloneNode(this._className_),
cloneNode(this._identifier_));
}
@Override
public void apply(Switch sw)
{
((Analysis) sw).caseAClassFieldAccess(this);
}
public PClassName getClassName()
{
return this._className_;
}
public void setClassName(PClassName node)
{
if(this._className_ != null)
{
this._className_.parent(null);
}
if(node != null)
{
if(node.parent() != null)
{
node.parent().removeChild(node);
}
node.parent(this);
}
this._className_ = node;
}
public TIdentifier getIdentifier()
{
return this._identifier_;
}
public void setIdentifier(TIdentifier node)
{
if(this._identifier_ != null)
{
this._identifier_.parent(null);
}
if(node != null)
{
if(node.parent() != null)
{
node.parent().removeChild(node);
}
node.parent(this);
}
this._identifier_ = node;
}
@Override
public String toString()
{
return ""
+ toString(this._className_)
+ toString(this._identifier_);
}
@Override
void removeChild(@SuppressWarnings("unused") Node child)
{
// Remove child
if(this._className_ == child)
{
this._className_ = null;
return;
}
if(this._identifier_ == child)
{
this._identifier_ = null;
return;
}
throw new RuntimeException("Not a child.");
}
@Override
void replaceChild(@SuppressWarnings("unused") Node oldChild, @SuppressWarnings("unused") Node newChild)
{
// Replace child
if(this._className_ == oldChild)
{
setClassName((PClassName) newChild);
return;
}
if(this._identifier_ == oldChild)
{
setIdentifier((TIdentifier) newChild);
return;
}
throw new RuntimeException("Not a child.");
}
}
| kompics/kola | src/main/java/se/sics/kola/node/AClassFieldAccess.java | Java | gpl-2.0 | 2,887 |
package com.pingdynasty.blipbox;
import java.util.Map;
import java.util.HashMap;
import javax.sound.midi.*;
import com.pingdynasty.midi.ScaleMapper;
import org.apache.log4j.Logger;
public class MidiOutputEventHandler extends MultiModeKeyPressManager {
private static final Logger log = Logger.getLogger(MidiOutputEventHandler.class);
private static final int OCTAVE_SHIFT = 6;
private MidiPlayer midiPlayer;
private int lastNote = 0;
public class MidiConfigurationMode extends ConfigurationMode {
private ScaleMapper mapper;
private int basenote = 40;
public MidiConfigurationMode(String name, String follow){
super(name, follow);
mapper = new ScaleMapper();
mapper.setScale("Mixolydian Mode");
// setScale("Chromatic Scale");
// setScale("C Major");
// setScale("Dorian Mode");
}
public ScaleMapper getScaleMapper(){
return mapper;
}
public int getBaseNote(){
return basenote;
}
public void setBaseNote(int basenote){
this.basenote = basenote;
}
}
public ConfigurationMode createConfigurationMode(String mode, String follow){
return new MidiConfigurationMode(mode, follow);
}
public ScaleMapper getScaleMapper(){
MidiConfigurationMode mode = (MidiConfigurationMode)getCurrentConfigurationMode();
return mode.getScaleMapper();
}
public ScaleMapper getScaleMapper(String mode){
MidiConfigurationMode config = (MidiConfigurationMode)getConfigurationMode(mode);
return config.getScaleMapper();
}
public int getBaseNote(){
MidiConfigurationMode mode = (MidiConfigurationMode)getCurrentConfigurationMode();
return mode.getBaseNote();
}
public void setBaseNote(int basenote){
MidiConfigurationMode mode = (MidiConfigurationMode)getCurrentConfigurationMode();
mode.setBaseNote(basenote);
}
public void setBaseNote(String modename, int basenote){
MidiConfigurationMode mode = (MidiConfigurationMode)getConfigurationMode(modename);
mode.setBaseNote(basenote);
}
public void holdOff(){
super.holdOff();
sendMidiNoteOff(lastNote);
}
public void init(){
super.init();
setSensorEventHandler("Cross", SensorType.BUTTON2_SENSOR, new OctaveShiftUpEventHandler());
setSensorEventHandler("Cross", SensorType.BUTTON3_SENSOR, new OctaveShiftDownEventHandler());
setSensorEventHandler("Criss", SensorType.BUTTON2_SENSOR, new OctaveShiftUpEventHandler());
setSensorEventHandler("Criss", SensorType.BUTTON3_SENSOR, new OctaveShiftDownEventHandler());
}
public class OctaveShiftUpEventHandler implements SensorEventHandler {
public void sensorChange(SensorDefinition sensor){
if(sensor.value != 0){
int basenote = getBaseNote();
log.debug("octave up");
basenote += OCTAVE_SHIFT;
if(basenote + OCTAVE_SHIFT <= 127)
setBaseNote(basenote);
log.debug("new basenote "+basenote);
}
}
}
public class OctaveShiftDownEventHandler implements SensorEventHandler {
public void sensorChange(SensorDefinition sensor){
if(sensor.value != 0){
int basenote = getBaseNote();
log.debug("octave down");
basenote -= OCTAVE_SHIFT;
if(basenote > 0)
setBaseNote(basenote);
log.debug("new basenote "+basenote);
}
}
}
public class BaseNoteChangeEventHandler implements SensorEventHandler {
private int min, max;
public BaseNoteChangeEventHandler(){
this(0, 127);
}
public BaseNoteChangeEventHandler(int min, int max){
this.min = min;
this.max = max;
}
public void sensorChange(SensorDefinition sensor){
int basenote = sensor.scale(min, max);
log.debug("basenote: "+basenote);
setBaseNote(basenote);
}
}
public class ScaleChangeEventHandler implements SensorEventHandler {
public void sensorChange(SensorDefinition sensor){
ScaleMapper mapper = getScaleMapper();
int val = sensor.scale(mapper.getScaleNames().length);
if(val < mapper.getScaleNames().length){
mapper.setScale(val);
log.debug("set scale "+mapper.getScaleNames()[val]);
}
}
}
public class ControlChangeEventHandler implements SensorEventHandler {
private int from;
private int to;
private int cc;
public ControlChangeEventHandler(int cc){
this(cc, 0, 127);
}
public ControlChangeEventHandler(int cc, int from, int to){
this.from = from;
this.to = to;
this.cc = cc;
}
public void sensorChange(SensorDefinition sensor){
int val = sensor.scale(from, to);
sendMidiCC(cc, val);
}
}
public class NonRegisteredParameterEventHandler implements SensorEventHandler {
private int from;
private int to;
private int cc;
public NonRegisteredParameterEventHandler(int cc, int from, int to){
this.from = from;
this.to = to;
this.cc = cc;
}
public void sensorChange(SensorDefinition sensor){
int val = sensor.scale(from, to);
sendMidiNRPN(cc, val);
}
}
public class PitchBendEventHandler implements SensorEventHandler {
private int from;
private int to;
public PitchBendEventHandler(){
this(-8191, 8192);
}
public PitchBendEventHandler(int from, int to){
this.from = from;
this.to = to;
}
public void sensorChange(SensorDefinition sensor){
int val = sensor.scale(from, to);
sendMidiPitchBend(val);
}
}
public class NotePlayer implements KeyEventHandler {
private int lastnote;
public void sensorChange(SensorDefinition sensor){}
protected int getVelocity(int row){
// int velocity = ((row+1)*127/8);
// int velocity = (row*127/8)+1;
int velocity = ((row+1)*127/9);
return velocity;
}
public void keyDown(int col, int row){
lastNote = getScaleMapper().getNote(col+getBaseNote());
sendMidiNoteOn(lastNote, getVelocity(row));
}
public void keyUp(int col, int row){
sendMidiNoteOff(lastNote);
}
public void keyChange(int oldCol, int oldRow, int newCol, int newRow){
int newNote = getScaleMapper().getNote(newCol+getBaseNote());
if(newNote != lastNote){
sendMidiNoteOff(lastNote);
sendMidiNoteOn(newNote, getVelocity(newRow));
}
lastNote = newNote;
}
}
public MidiOutputEventHandler(BlipBox sender){
super(sender);
}
public void configureControlChange(String mode, SensorType type, int channel, int cc, int min, int max){
log.debug("Setting "+mode+":"+type+" to CC "+cc+" ("+min+"-"+max+")");
setSensorEventHandler(mode, type, new ControlChangeEventHandler(cc, min, max));
}
public void configureNRPN(String mode, SensorType type, int channel, int cc, int min, int max){
log.debug("Setting "+mode+":"+type+" to NRPN "+cc+" ("+min+"-"+max+")");
setSensorEventHandler(mode, type, new NonRegisteredParameterEventHandler(cc, min, max));
}
public void configurePitchBend(String mode, SensorType type, int channel, int min, int max){
setSensorEventHandler(mode, type, new PitchBendEventHandler(min, max));
}
public void configureBaseNoteChange(String mode, SensorType type, int min, int max){
log.debug("Setting "+mode+":"+type+" to control base note");
setSensorEventHandler(mode, type, new BaseNoteChangeEventHandler(min, max));
}
public void configureScaleChange(String mode, SensorType type){
log.debug("Setting "+mode+":"+type+" to control scale changes");
setSensorEventHandler(mode, type, new ScaleChangeEventHandler());
}
public void configureNotePlayer(String mode, boolean notes, boolean pb, boolean at){
log.debug("Setting "+mode+" mode to play notes ("+notes+") pitch bend ("+pb+") aftertouch ("+at+")");
if(notes){
setKeyEventHandler(mode, new NotePlayer());
}else{
setKeyEventHandler(mode, null);
}
// todo: honour pb and at
}
// public String[] getScaleNames(){
// return mapper.getScaleNames();
// }
// public void setScale(int index){
// mapper.setScale(index);
// }
public String getCurrentScale(){
ScaleMapper mapper = getScaleMapper();
return mapper.getScaleNames()[mapper.getScaleIndex()];
}
public void setMidiPlayer(MidiPlayer midiPlayer){
this.midiPlayer = midiPlayer;
}
public void sendMidiNoteOn(int note, int velocity){
log.debug("note on:\t "+note+"\t "+velocity);
if(note > 127 || note < 0){
log.error("MIDI note on "+note+"/"+velocity+" value out of range");
return;
}
if(velocity > 127 || velocity < 0){
log.error("MIDI note on "+note+"/"+velocity+" value out of range");
velocity = velocity < 0 ? 0 : 127;
}
try {
if(midiPlayer != null)
midiPlayer.noteOn(note, velocity);
}catch(Exception exc){
log.error(exc, exc);
}
}
public void sendMidiNoteOff(int note){
// note = mapper.getNote(note);
log.debug("note off:\t "+note);
if(note > 127 || note < 0){
log.error("MIDI note off "+note+" value out of range");
return;
}
try {
if(midiPlayer != null)
midiPlayer.noteOff(note);
}catch(Exception exc){
log.error(exc, exc);
}
}
public void sendMidiNRPN(int parameter, int value){
// log.debug("nrpn ("+parameter+") :\t "+value);
sendMidiCC(99, 3);
sendMidiCC(98, parameter & 0x7f); // NRPN LSB
sendMidiCC(6, value);
// sendMidiCC(99, parameter >> 7); // NRPN MSB
// sendMidiCC(98, parameter & 0x7f); // NRPN LSB
// sendMidiCC(6, value >> 7); // Data Entry MSB
// if((value & 0x7f) != 0)
// sendMidiCC(38, value & 0x7f); // Data Entry LSB
}
public void sendMidiCC(int cc, int value){
// log.debug("midi cc:\t "+cc+"\t "+value);
if(value > 127 || value < 0){
log.error("MIDI CC "+cc+" value out of range: "+value);
return;
}
try {
if(midiPlayer != null)
midiPlayer.controlChange(cc, value);
}catch(Exception exc){
log.error(exc, exc);
}
}
public void sendMidiPitchBend(int degree){
// send midi pitch bend in the range -8192 to 8191 inclusive
if(degree < -8192 || degree > 8191){
log.error("MIDI pitch bend value out of range: "+degree);
return;
}
// setPitchBend() expects a value in the range 0 to 16383
degree += 8192;
try {
if(midiPlayer != null)
midiPlayer.pitchBend(degree);
}catch(Exception exc){
log.error(exc, exc);
}
}
public void setChannel(int channel){
midiPlayer.setChannel(channel);
}
public class SensitiveNotePlayer implements KeyEventHandler {
private int lastnote;
private int velocity;
// todo : velocity could be set by row rather than sensor position
public void sensorChange(SensorDefinition sensor){
velocity = sensor.scale(127);
}
public void keyDown(int col, int row){
lastNote = getScaleMapper().getNote(col+getBaseNote());
sendMidiNoteOn(lastNote, velocity);
}
public void keyUp(int col, int row){
sendMidiNoteOff(lastNote);
}
public void keyChange(int oldCol, int oldRow, int newCol, int newRow){
int newNote = getScaleMapper().getNote(newCol+getBaseNote());
if(newNote != lastNote){
sendMidiNoteOff(lastNote);
sendMidiNoteOn(newNote, velocity);
// }else{
// // todo: aftertouch, bend
}
lastNote = newNote;
}
}
} | pingdynasty/BlipBox | src/com/pingdynasty/blipbox/MidiOutputEventHandler.java | Java | gpl-2.0 | 12,949 |
/*
* Copyright 2004-2007 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
* @test
* @bug 4853450
* @summary EnumType tests
* @library ../../lib
* @compile -source 1.5 EnumTyp.java
* @run main EnumTyp
*/
import java.util.*;
import com.sun.mirror.declaration.*;
import com.sun.mirror.type.*;
import com.sun.mirror.util.*;
public class EnumTyp extends Tester {
public static void main(String[] args) {
(new EnumTyp()).run();
}
// Declarations used by tests
enum Suit {
CIVIL,
CRIMINAL
}
private Suit s;
private EnumType e; // an enum type
protected void init() {
e = (EnumType) getField("s").getType();
}
// TypeMirror methods
@Test(result="enum")
Collection<String> accept() {
final Collection<String> res = new ArrayList<String>();
e.accept(new SimpleTypeVisitor() {
public void visitTypeMirror(TypeMirror t) {
res.add("type");
}
public void visitReferenceType(ReferenceType t) {
res.add("ref type");
}
public void visitClassType(ClassType t) {
res.add("class");
}
public void visitEnumType(EnumType t) {
res.add("enum");
}
public void visitInterfaceType(InterfaceType t) {
res.add("interface");
}
});
return res;
}
// EnumType method
@Test(result="EnumTyp.Suit")
EnumDeclaration getDeclaration() {
return e.getDeclaration();
}
}
| unktomi/form-follows-function | mjavac/langtools/test/tools/apt/mirror/type/EnumTyp.java | Java | gpl-2.0 | 2,590 |
/*----------------------------------------------------------------------------
* U S B - K e r n e l
*----------------------------------------------------------------------------
* Name: usbreg_STM32F10x.h
* Purpose: USB Hardware Layer Definitions for ST STM32F10x
* Version: V1.20
*----------------------------------------------------------------------------
* This file is part of the uVision/ARM development tools.
* This software may only be used under the terms of a valid, current,
* end user licence from KEIL for a compatible version of KEIL software
* development tools. Nothing else gives you the right to use this software.
*
* This software is supplied "AS IS" without warranties of any kind.
*
* Copyright (c) 2009-2011 Keil - An ARM Company. All rights reserved.
*----------------------------------------------------------------------------*/
#ifndef __USBREG_STM32F10x_H
#define __USBREG_STM32F10x_H
#define REG(x) (*((volatile unsigned int *)(x)))
#define USB_BASE_ADDR 0x40005C00 /* USB Registers Base Address */
#define USB_PMA_ADDR 0x40006000 /* USB Packet Memory Area Address */
/* Common Registers */
#define CNTR REG(USB_BASE_ADDR + 0x40) /* Control Register */
#define ISTR REG(USB_BASE_ADDR + 0x44) /* Interrupt Status Register */
#define FNR REG(USB_BASE_ADDR + 0x48) /* Frame Number Register */
#define DADDR REG(USB_BASE_ADDR + 0x4C) /* Device Address Register */
#define BTABLE REG(USB_BASE_ADDR + 0x50) /* Buffer Table Address Register */
/* CNTR: Control Register Bit Definitions */
#define CNTR_CTRM 0x8000 /* Correct Transfer Interrupt Mask */
#define CNTR_PMAOVRM 0x4000 /* Packet Memory Aerea Over/underrun Interrupt Mask */
#define CNTR_ERRM 0x2000 /* Error Interrupt Mask */
#define CNTR_WKUPM 0x1000 /* Wake-up Interrupt Mask */
#define CNTR_SUSPM 0x0800 /* Suspend Mode Interrupt Mask */
#define CNTR_RESETM 0x0400 /* USB Reset Interrupt Mask */
#define CNTR_SOFM 0x0200 /* Start of Frame Interrupt Mask */
#define CNTR_ESOFM 0x0100 /* Expected Start of Frame Interrupt Mask */
#define CNTR_RESUME 0x0010 /* Resume Request */
#define CNTR_FSUSP 0x0008 /* Force Suspend */
#define CNTR_LPMODE 0x0004 /* Low-power Mode */
#define CNTR_PDWN 0x0002 /* Power Down */
#define CNTR_FRES 0x0001 /* Force USB Reset */
/* ISTR: Interrupt Status Register Bit Definitions */
#define ISTR_CTR 0x8000 /* Correct Transfer */
#define ISTR_PMAOVR 0x4000 /* Packet Memory Aerea Over/underrun */
#define ISTR_ERR 0x2000 /* Error */
#define ISTR_WKUP 0x1000 /* Wake-up */
#define ISTR_SUSP 0x0800 /* Suspend Mode */
#define ISTR_RESET 0x0400 /* USB Reset */
#define ISTR_SOF 0x0200 /* Start of Frame */
#define ISTR_ESOF 0x0100 /* Expected Start of Frame */
#define ISTR_DIR 0x0010 /* Direction of Transaction */
#define ISTR_EP_ID 0x000F /* EndPoint Identifier */
/* FNR: Frame Number Register Bit Definitions */
#define FNR_RXDP 0x8000 /* D+ Data Line Status */
#define FNR_RXDM 0x4000 /* D- Data Line Status */
#define FNR_LCK 0x2000 /* Locked */
#define FNR_LSOF 0x1800 /* Lost SOF */
#define FNR_FN 0x07FF /* Frame Number */
/* DADDR: Device Address Register Bit Definitions */
#define DADDR_EF 0x0080 /* Enable Function */
#define DADDR_ADD 0x007F /* Device Address */
/* EndPoint Registers */
#define EPxREG(x) REG(USB_BASE_ADDR + 4*(x))
/* EPxREG: EndPoint Registers Bit Definitions */
#define EP_CTR_RX 0x8000 /* Correct RX Transfer */
#define EP_DTOG_RX 0x4000 /* RX Data Toggle */
#define EP_STAT_RX 0x3000 /* RX Status */
#define EP_SETUP 0x0800 /* EndPoint Setup */
#define EP_TYPE 0x0600 /* EndPoint Type */
#define EP_KIND 0x0100 /* EndPoint Kind */
#define EP_CTR_TX 0x0080 /* Correct TX Transfer */
#define EP_DTOG_TX 0x0040 /* TX Data Toggle */
#define EP_STAT_TX 0x0030 /* TX Status */
#define EP_EA 0x000F /* EndPoint Address */
/* EndPoint Register Mask (No Toggle Fields) */
#define EP_MASK (EP_CTR_RX|EP_SETUP|EP_TYPE|EP_KIND|EP_CTR_TX|EP_EA)
/* EP_TYPE: EndPoint Types */
#define EP_BULK 0x0000 /* BULK EndPoint */
#define EP_CONTROL 0x0200 /* CONTROL EndPoint */
#define EP_ISOCHRONOUS 0x0400 /* ISOCHRONOUS EndPoint */
#define EP_INTERRUPT 0x0600 /* INTERRUPT EndPoint */
/* EP_KIND: EndPoint Kind */
#define EP_DBL_BUF EP_KIND /* Double Buffer for Bulk Endpoint */
#define EP_STATUS_OUT EP_KIND /* Status Out for Control Endpoint */
/* EP_STAT_TX: TX Status */
#define EP_TX_DIS 0x0000 /* Disabled */
#define EP_TX_STALL 0x0010 /* Stalled */
#define EP_TX_NAK 0x0020 /* NAKed */
#define EP_TX_VALID 0x0030 /* Valid */
/* EP_STAT_RX: RX Status */
#define EP_RX_DIS 0x0000 /* Disabled */
#define EP_RX_STALL 0x1000 /* Stalled */
#define EP_RX_NAK 0x2000 /* NAKed */
#define EP_RX_VALID 0x3000 /* Valid */
/* Endpoint Buffer Descriptor */
typedef struct _EP_BUF_DSCR {
U32 ADDR_TX;
U32 COUNT_TX;
U32 ADDR_RX;
U32 COUNT_RX;
} EP_BUF_DSCR;
#define EP_ADDR_MASK 0xFFFE /* Address Mask */
#define EP_COUNT_MASK 0x03FF /* Count Mask */
#endif /* __USBREG_STM32F10x_H */
| mcufans/xlink | firmware/xlink-kickstart/USB/usbreg_STM32F10x.h | C | gpl-2.0 | 5,722 |
/* Qualcomm Crypto Engine driver.
*
* Copyright (c) 2012-2013, The Linux Foundation. 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 and
* only 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.
*/
#define pr_fmt(fmt) "QCE50: %s: " fmt, __func__
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/mod_devicetable.h>
#include <linux/device.h>
#include <linux/clk.h>
#include <linux/err.h>
#include <linux/dma-mapping.h>
#include <linux/io.h>
#include <linux/platform_device.h>
#include <linux/spinlock.h>
#include <linux/delay.h>
#include <linux/crypto.h>
#include <linux/qcedev.h>
#include <linux/bitops.h>
#include <crypto/hash.h>
#include <crypto/sha.h>
#include <mach/dma.h>
#include <mach/clk.h>
#include <mach/socinfo.h>
#include <mach/qcrypto.h>
#include "qce.h"
#include "qce50.h"
#include "qcryptohw_50.h"
#define CRYPTO_CONFIG_RESET 0xE001F
#define QCE_MAX_NUM_DSCR 0x500
#define QCE_SECTOR_SIZE 0x200
static DEFINE_MUTEX(bam_register_cnt);
struct bam_registration_info {
uint32_t handle;
uint32_t cnt;
};
static struct bam_registration_info bam_registry;
static bool ce_bam_registered;
/*
* CE HW device structure.
* Each engine has an instance of the structure.
* Each engine can only handle one crypto operation at one time. It is up to
* the sw above to ensure single threading of operation on an engine.
*/
struct qce_device {
struct device *pdev; /* Handle to platform_device structure */
unsigned char *coh_vmem; /* Allocated coherent virtual memory */
dma_addr_t coh_pmem; /* Allocated coherent physical memory */
int memsize; /* Memory allocated */
int is_shared; /* CE HW is shared */
bool support_cmd_dscr;
bool support_hw_key;
void __iomem *iobase; /* Virtual io base of CE HW */
unsigned int phy_iobase; /* Physical io base of CE HW */
struct clk *ce_core_src_clk; /* Handle to CE src clk*/
struct clk *ce_core_clk; /* Handle to CE clk */
struct clk *ce_clk; /* Handle to CE clk */
struct clk *ce_bus_clk; /* Handle to CE AXI clk*/
qce_comp_func_ptr_t qce_cb; /* qce callback function pointer */
int assoc_nents;
int ivsize;
int authsize;
int src_nents;
int dst_nents;
dma_addr_t phy_iv_in;
unsigned char dec_iv[16];
int dir;
void *areq;
enum qce_cipher_mode_enum mode;
struct qce_ce_cfg_reg_setting reg;
struct ce_sps_data ce_sps;
};
/* Standard initialization vector for SHA-1, source: FIPS 180-2 */
static uint32_t _std_init_vector_sha1[] = {
0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0
};
/* Standard initialization vector for SHA-256, source: FIPS 180-2 */
static uint32_t _std_init_vector_sha256[] = {
0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A,
0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19
};
static void _byte_stream_to_net_words(uint32_t *iv, unsigned char *b,
unsigned int len)
{
unsigned n;
n = len / sizeof(uint32_t) ;
for (; n > 0; n--) {
*iv = ((*b << 24) & 0xff000000) |
(((*(b+1)) << 16) & 0xff0000) |
(((*(b+2)) << 8) & 0xff00) |
(*(b+3) & 0xff);
b += sizeof(uint32_t);
iv++;
}
n = len % sizeof(uint32_t);
if (n == 3) {
*iv = ((*b << 24) & 0xff000000) |
(((*(b+1)) << 16) & 0xff0000) |
(((*(b+2)) << 8) & 0xff00) ;
} else if (n == 2) {
*iv = ((*b << 24) & 0xff000000) |
(((*(b+1)) << 16) & 0xff0000) ;
} else if (n == 1) {
*iv = ((*b << 24) & 0xff000000) ;
}
}
static void _byte_stream_swap_to_net_words(uint32_t *iv, unsigned char *b,
unsigned int len)
{
unsigned i, j;
unsigned char swap_iv[AES_IV_LENGTH];
memset(swap_iv, 0, AES_IV_LENGTH);
for (i = (AES_IV_LENGTH-len), j = len-1; i < AES_IV_LENGTH; i++, j--)
swap_iv[i] = b[j];
_byte_stream_to_net_words(iv, swap_iv, AES_IV_LENGTH);
}
static int count_sg(struct scatterlist *sg, int nbytes)
{
int i;
for (i = 0; nbytes > 0; i++, sg = scatterwalk_sg_next(sg))
nbytes -= sg->length;
return i;
}
static int qce_dma_map_sg(struct device *dev, struct scatterlist *sg, int nents,
enum dma_data_direction direction)
{
int i;
for (i = 0; i < nents; ++i) {
dma_map_sg(dev, sg, 1, direction);
sg = scatterwalk_sg_next(sg);
}
return nents;
}
static int qce_dma_unmap_sg(struct device *dev, struct scatterlist *sg,
int nents, enum dma_data_direction direction)
{
int i;
for (i = 0; i < nents; ++i) {
dma_unmap_sg(dev, sg, 1, direction);
sg = scatterwalk_sg_next(sg);
}
return nents;
}
static int _probe_ce_engine(struct qce_device *pce_dev)
{
unsigned int rev;
unsigned int maj_rev, min_rev, step_rev;
rev = readl_relaxed(pce_dev->iobase + CRYPTO_VERSION_REG);
mb();
maj_rev = (rev & CRYPTO_CORE_MAJOR_REV_MASK) >> CRYPTO_CORE_MAJOR_REV;
min_rev = (rev & CRYPTO_CORE_MINOR_REV_MASK) >> CRYPTO_CORE_MINOR_REV;
step_rev = (rev & CRYPTO_CORE_STEP_REV_MASK) >> CRYPTO_CORE_STEP_REV;
if (maj_rev != 0x05) {
pr_err("Unknown Qualcomm crypto device at 0x%x, rev %d.%d.%d\n",
pce_dev->phy_iobase, maj_rev, min_rev, step_rev);
return -EIO;
};
pce_dev->ce_sps.minor_version = min_rev;
dev_info(pce_dev->pdev, "Qualcomm Crypto %d.%d.%d device found @0x%x\n",
maj_rev, min_rev, step_rev, pce_dev->phy_iobase);
pce_dev->ce_sps.ce_burst_size = MAX_CE_BAM_BURST_SIZE;
dev_info(pce_dev->pdev,
"IO base, CE = 0x%x\n, "
"Consumer (IN) PIPE %d, "
"Producer (OUT) PIPE %d\n"
"IO base BAM = 0x%x\n"
"BAM IRQ %d\n",
(uint32_t) pce_dev->iobase,
pce_dev->ce_sps.dest_pipe_index,
pce_dev->ce_sps.src_pipe_index,
(uint32_t)pce_dev->ce_sps.bam_iobase,
pce_dev->ce_sps.bam_irq);
return 0;
};
static int _ce_get_hash_cmdlistinfo(struct qce_device *pce_dev,
struct qce_sha_req *sreq,
struct qce_cmdlist_info **cmdplistinfo)
{
struct qce_cmdlistptr_ops *cmdlistptr = &pce_dev->ce_sps.cmdlistptr;
switch (sreq->alg) {
case QCE_HASH_SHA1:
*cmdplistinfo = &cmdlistptr->auth_sha1;
break;
case QCE_HASH_SHA256:
*cmdplistinfo = &cmdlistptr->auth_sha256;
break;
case QCE_HASH_SHA1_HMAC:
*cmdplistinfo = &cmdlistptr->auth_sha1_hmac;
break;
case QCE_HASH_SHA256_HMAC:
*cmdplistinfo = &cmdlistptr->auth_sha256_hmac;
break;
case QCE_HASH_AES_CMAC:
if (sreq->authklen == AES128_KEY_SIZE)
*cmdplistinfo = &cmdlistptr->auth_aes_128_cmac;
else
*cmdplistinfo = &cmdlistptr->auth_aes_256_cmac;
break;
default:
break;
}
return 0;
}
static int _ce_setup_hash(struct qce_device *pce_dev,
struct qce_sha_req *sreq,
struct qce_cmdlist_info *cmdlistinfo)
{
uint32_t auth32[SHA256_DIGEST_SIZE / sizeof(uint32_t)];
uint32_t diglen;
int i;
uint32_t mackey32[SHA_HMAC_KEY_SIZE/sizeof(uint32_t)] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
bool sha1 = false;
struct sps_command_element *pce = NULL;
if ((sreq->alg == QCE_HASH_SHA1_HMAC) ||
(sreq->alg == QCE_HASH_SHA256_HMAC) ||
(sreq->alg == QCE_HASH_AES_CMAC)) {
uint32_t authk_size_in_word = sreq->authklen/sizeof(uint32_t);
_byte_stream_to_net_words(mackey32, sreq->authkey,
sreq->authklen);
/* check for null key. If null, use hw key*/
for (i = 0; i < authk_size_in_word; i++) {
if (mackey32[i] != 0)
break;
}
pce = cmdlistinfo->go_proc;
if (i == authk_size_in_word) {
pce->addr = (uint32_t)(CRYPTO_GOPROC_QC_KEY_REG +
pce_dev->phy_iobase);
} else {
pce->addr = (uint32_t)(CRYPTO_GOPROC_REG +
pce_dev->phy_iobase);
pce = cmdlistinfo->auth_key;
for (i = 0; i < authk_size_in_word; i++, pce++)
pce->data = mackey32[i];
}
}
if (sreq->alg == QCE_HASH_AES_CMAC)
goto go_proc;
/* if not the last, the size has to be on the block boundary */
if (sreq->last_blk == 0 && (sreq->size % SHA256_BLOCK_SIZE))
return -EIO;
switch (sreq->alg) {
case QCE_HASH_SHA1:
case QCE_HASH_SHA1_HMAC:
diglen = SHA1_DIGEST_SIZE;
sha1 = true;
break;
case QCE_HASH_SHA256:
case QCE_HASH_SHA256_HMAC:
diglen = SHA256_DIGEST_SIZE;
break;
default:
return -EINVAL;
}
/* write 20/32 bytes, 5/8 words into auth_iv for SHA1/SHA256 */
if (sreq->first_blk) {
if (sha1) {
for (i = 0; i < 5; i++)
auth32[i] = _std_init_vector_sha1[i];
} else {
for (i = 0; i < 8; i++)
auth32[i] = _std_init_vector_sha256[i];
}
} else {
_byte_stream_to_net_words(auth32, sreq->digest, diglen);
}
pce = cmdlistinfo->auth_iv;
for (i = 0; i < 5; i++, pce++)
pce->data = auth32[i];
if ((sreq->alg == QCE_HASH_SHA256) ||
(sreq->alg == QCE_HASH_SHA256_HMAC)) {
for (i = 5; i < 8; i++, pce++)
pce->data = auth32[i];
}
/* write auth_bytecnt 0/1, start with 0 */
pce = cmdlistinfo->auth_bytecount;
for (i = 0; i < 2; i++, pce++)
pce->data = sreq->auth_data[i];
/* Set/reset last bit in CFG register */
pce = cmdlistinfo->auth_seg_cfg;
if (sreq->last_blk)
pce->data |= 1 << CRYPTO_LAST;
else
pce->data &= ~(1 << CRYPTO_LAST);
if (sreq->first_blk)
pce->data |= 1 << CRYPTO_FIRST;
else
pce->data &= ~(1 << CRYPTO_FIRST);
go_proc:
/* write auth seg size */
pce = cmdlistinfo->auth_seg_size;
pce->data = sreq->size;
pce = cmdlistinfo->encr_seg_cfg;
pce->data = 0;
/* write auth seg size start*/
pce = cmdlistinfo->auth_seg_start;
pce->data = 0;
/* write seg size */
pce = cmdlistinfo->seg_size;
pce->data = sreq->size;
return 0;
}
static struct qce_cmdlist_info *_ce_get_aead_cmdlistinfo(
struct qce_device *pce_dev, struct qce_req *creq)
{
switch (creq->alg) {
case CIPHER_ALG_DES:
switch (creq->mode) {
case QCE_MODE_ECB:
return &pce_dev->ce_sps.
cmdlistptr.aead_hmac_sha1_ecb_des;
break;
case QCE_MODE_CBC:
return &pce_dev->ce_sps.
cmdlistptr.aead_hmac_sha1_cbc_des;
break;
default:
return NULL;
}
break;
case CIPHER_ALG_3DES:
switch (creq->mode) {
case QCE_MODE_ECB:
return &pce_dev->ce_sps.
cmdlistptr.aead_hmac_sha1_ecb_3des;
break;
case QCE_MODE_CBC:
return &pce_dev->ce_sps.
cmdlistptr.aead_hmac_sha1_cbc_3des;
break;
default:
return NULL;
}
break;
case CIPHER_ALG_AES:
switch (creq->mode) {
case QCE_MODE_ECB:
if (creq->encklen == AES128_KEY_SIZE)
return &pce_dev->ce_sps.
cmdlistptr.aead_hmac_sha1_ecb_aes_128;
else if (creq->encklen == AES256_KEY_SIZE)
return &pce_dev->ce_sps.
cmdlistptr.aead_hmac_sha1_ecb_aes_256;
else
return NULL;
break;
case QCE_MODE_CBC:
if (creq->encklen == AES128_KEY_SIZE)
return &pce_dev->ce_sps.
cmdlistptr.aead_hmac_sha1_cbc_aes_128;
else if (creq->encklen == AES256_KEY_SIZE)
return &pce_dev->ce_sps.
cmdlistptr.aead_hmac_sha1_cbc_aes_256;
else
return NULL;
break;
default:
return NULL;
}
break;
default:
return NULL;
}
return NULL;
}
static int _ce_setup_aead(struct qce_device *pce_dev, struct qce_req *q_req,
uint32_t totallen_in, uint32_t coffset,
struct qce_cmdlist_info *cmdlistinfo)
{
int32_t authk_size_in_word = q_req->authklen/sizeof(uint32_t);
int i;
uint32_t mackey32[SHA_HMAC_KEY_SIZE/sizeof(uint32_t)] = {0};
struct sps_command_element *pce;
uint32_t a_cfg;
uint32_t enckey32[(MAX_CIPHER_KEY_SIZE*2)/sizeof(uint32_t)] = {0};
uint32_t enciv32[MAX_IV_LENGTH/sizeof(uint32_t)] = {0};
uint32_t enck_size_in_word = 0;
uint32_t enciv_in_word;
uint32_t key_size;
uint32_t encr_cfg = 0;
uint32_t ivsize = q_req->ivsize;
key_size = q_req->encklen;
enck_size_in_word = key_size/sizeof(uint32_t);
switch (q_req->alg) {
case CIPHER_ALG_DES:
enciv_in_word = 2;
break;
case CIPHER_ALG_3DES:
enciv_in_word = 2;
break;
case CIPHER_ALG_AES:
if ((key_size != AES128_KEY_SIZE) &&
(key_size != AES256_KEY_SIZE))
return -EINVAL;
enciv_in_word = 4;
break;
default:
return -EINVAL;
}
switch (q_req->mode) {
case QCE_MODE_ECB:
case QCE_MODE_CBC:
case QCE_MODE_CTR:
pce_dev->mode = q_req->mode;
break;
default:
return -EINVAL;
}
if (q_req->mode != QCE_MODE_ECB) {
_byte_stream_to_net_words(enciv32, q_req->iv, ivsize);
pce = cmdlistinfo->encr_cntr_iv;
for (i = 0; i < enciv_in_word; i++, pce++)
pce->data = enciv32[i];
}
/*
* write encr key
* do not use hw key or pipe key
*/
_byte_stream_to_net_words(enckey32, q_req->enckey, key_size);
pce = cmdlistinfo->encr_key;
for (i = 0; i < enck_size_in_word; i++, pce++)
pce->data = enckey32[i];
/* write encr seg cfg */
pce = cmdlistinfo->encr_seg_cfg;
encr_cfg = pce->data;
if (q_req->dir == QCE_ENCRYPT)
encr_cfg |= (1 << CRYPTO_ENCODE);
else
encr_cfg &= ~(1 << CRYPTO_ENCODE);
pce->data = encr_cfg;
/* we only support sha1-hmac at this point */
_byte_stream_to_net_words(mackey32, q_req->authkey,
q_req->authklen);
pce = cmdlistinfo->auth_key;
for (i = 0; i < authk_size_in_word; i++, pce++)
pce->data = mackey32[i];
pce = cmdlistinfo->auth_iv;
for (i = 0; i < 5; i++, pce++)
pce->data = _std_init_vector_sha1[i];
/* write auth_bytecnt 0/1, start with 0 */
pce = cmdlistinfo->auth_bytecount;
for (i = 0; i < 2; i++, pce++)
pce->data = 0;
pce = cmdlistinfo->auth_seg_cfg;
a_cfg = pce->data;
a_cfg &= ~(CRYPTO_AUTH_POS_MASK);
if (q_req->dir == QCE_ENCRYPT)
a_cfg |= (CRYPTO_AUTH_POS_AFTER << CRYPTO_AUTH_POS);
else
a_cfg |= (CRYPTO_AUTH_POS_BEFORE << CRYPTO_AUTH_POS);
pce->data = a_cfg;
/* write auth seg size */
pce = cmdlistinfo->auth_seg_size;
pce->data = totallen_in;
/* write auth seg size start*/
pce = cmdlistinfo->auth_seg_start;
pce->data = 0;
/* write seg size */
pce = cmdlistinfo->seg_size;
pce->data = totallen_in;
/* write encr seg size */
pce = cmdlistinfo->encr_seg_size;
pce->data = q_req->cryptlen;
/* write encr seg start */
pce = cmdlistinfo->encr_seg_start;
pce->data = (coffset & 0xffff);
return 0;
};
static int _ce_get_cipher_cmdlistinfo(struct qce_device *pce_dev,
struct qce_req *creq,
struct qce_cmdlist_info **cmdlistinfo)
{
struct qce_cmdlistptr_ops *cmdlistptr = &pce_dev->ce_sps.cmdlistptr;
if (creq->alg != CIPHER_ALG_AES) {
switch (creq->alg) {
case CIPHER_ALG_DES:
if (creq->mode == QCE_MODE_ECB)
*cmdlistinfo = &cmdlistptr->cipher_des_ecb;
else
*cmdlistinfo = &cmdlistptr->cipher_des_cbc;
break;
case CIPHER_ALG_3DES:
if (creq->mode == QCE_MODE_ECB)
*cmdlistinfo =
&cmdlistptr->cipher_3des_ecb;
else
*cmdlistinfo =
&cmdlistptr->cipher_3des_cbc;
break;
default:
break;
}
} else {
switch (creq->mode) {
case QCE_MODE_ECB:
if (creq->encklen == AES128_KEY_SIZE)
*cmdlistinfo = &cmdlistptr->cipher_aes_128_ecb;
else
*cmdlistinfo = &cmdlistptr->cipher_aes_256_ecb;
break;
case QCE_MODE_CBC:
case QCE_MODE_CTR:
if (creq->encklen == AES128_KEY_SIZE)
*cmdlistinfo =
&cmdlistptr->cipher_aes_128_cbc_ctr;
else
*cmdlistinfo =
&cmdlistptr->cipher_aes_256_cbc_ctr;
break;
case QCE_MODE_XTS:
if (creq->encklen/2 == AES128_KEY_SIZE)
*cmdlistinfo = &cmdlistptr->cipher_aes_128_xts;
else
*cmdlistinfo = &cmdlistptr->cipher_aes_256_xts;
break;
case QCE_MODE_CCM:
if (creq->encklen == AES128_KEY_SIZE)
*cmdlistinfo = &cmdlistptr->aead_aes_128_ccm;
else
*cmdlistinfo = &cmdlistptr->aead_aes_256_ccm;
break;
default:
break;
}
}
return 0;
}
static int _ce_setup_cipher(struct qce_device *pce_dev, struct qce_req *creq,
uint32_t totallen_in, uint32_t coffset,
struct qce_cmdlist_info *cmdlistinfo)
{
uint32_t enckey32[(MAX_CIPHER_KEY_SIZE * 2)/sizeof(uint32_t)] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
uint32_t enciv32[MAX_IV_LENGTH / sizeof(uint32_t)] = {
0, 0, 0, 0};
uint32_t enck_size_in_word = 0;
uint32_t key_size;
bool use_hw_key = false;
bool use_pipe_key = false;
uint32_t encr_cfg = 0;
uint32_t ivsize = creq->ivsize;
int i;
struct sps_command_element *pce = NULL;
if (creq->mode == QCE_MODE_XTS)
key_size = creq->encklen/2;
else
key_size = creq->encklen;
pce = cmdlistinfo->go_proc;
if ((creq->flags & QCRYPTO_CTX_USE_HW_KEY) == QCRYPTO_CTX_USE_HW_KEY) {
use_hw_key = true;
} else {
if ((creq->flags & QCRYPTO_CTX_USE_PIPE_KEY) ==
QCRYPTO_CTX_USE_PIPE_KEY)
use_pipe_key = true;
}
pce = cmdlistinfo->go_proc;
if (use_hw_key == true)
pce->addr = (uint32_t)(CRYPTO_GOPROC_QC_KEY_REG +
pce_dev->phy_iobase);
else
pce->addr = (uint32_t)(CRYPTO_GOPROC_REG +
pce_dev->phy_iobase);
if ((use_pipe_key == false) && (use_hw_key == false)) {
_byte_stream_to_net_words(enckey32, creq->enckey, key_size);
enck_size_in_word = key_size/sizeof(uint32_t);
}
if ((creq->op == QCE_REQ_AEAD) && (creq->mode == QCE_MODE_CCM)) {
uint32_t authklen32 = creq->encklen/sizeof(uint32_t);
uint32_t noncelen32 = MAX_NONCE/sizeof(uint32_t);
uint32_t nonce32[MAX_NONCE/sizeof(uint32_t)] = {0, 0, 0, 0};
uint32_t auth_cfg = 0;
/* write nonce */
_byte_stream_to_net_words(nonce32, creq->nonce, MAX_NONCE);
pce = cmdlistinfo->auth_nonce_info;
for (i = 0; i < noncelen32; i++, pce++)
pce->data = nonce32[i];
if (creq->authklen == AES128_KEY_SIZE)
auth_cfg = pce_dev->reg.auth_cfg_aes_ccm_128;
else {
if (creq->authklen == AES256_KEY_SIZE)
auth_cfg = pce_dev->reg.auth_cfg_aes_ccm_256;
}
if (creq->dir == QCE_ENCRYPT)
auth_cfg |= (CRYPTO_AUTH_POS_BEFORE << CRYPTO_AUTH_POS);
else
auth_cfg |= (CRYPTO_AUTH_POS_AFTER << CRYPTO_AUTH_POS);
auth_cfg |= ((creq->authsize - 1) << CRYPTO_AUTH_SIZE);
if (use_hw_key == true) {
auth_cfg |= (1 << CRYPTO_USE_HW_KEY_AUTH);
} else {
auth_cfg &= ~(1 << CRYPTO_USE_HW_KEY_AUTH);
/* write auth key */
pce = cmdlistinfo->auth_key;
for (i = 0; i < authklen32; i++, pce++)
pce->data = enckey32[i];
}
pce = cmdlistinfo->auth_seg_cfg;
pce->data = auth_cfg;
pce = cmdlistinfo->auth_seg_size;
if (creq->dir == QCE_ENCRYPT)
pce->data = totallen_in;
else
pce->data = totallen_in - creq->authsize;
pce = cmdlistinfo->auth_seg_start;
pce->data = 0;
} else {
if (creq->op != QCE_REQ_AEAD) {
pce = cmdlistinfo->auth_seg_cfg;
pce->data = 0;
}
}
switch (creq->mode) {
case QCE_MODE_ECB:
if (key_size == AES128_KEY_SIZE)
encr_cfg = pce_dev->reg.encr_cfg_aes_ecb_128;
else
encr_cfg = pce_dev->reg.encr_cfg_aes_ecb_256;
break;
case QCE_MODE_CBC:
if (key_size == AES128_KEY_SIZE)
encr_cfg = pce_dev->reg.encr_cfg_aes_cbc_128;
else
encr_cfg = pce_dev->reg.encr_cfg_aes_cbc_256;
break;
case QCE_MODE_XTS:
if (key_size == AES128_KEY_SIZE)
encr_cfg = pce_dev->reg.encr_cfg_aes_xts_128;
else
encr_cfg = pce_dev->reg.encr_cfg_aes_xts_256;
break;
case QCE_MODE_CCM:
if (key_size == AES128_KEY_SIZE)
encr_cfg = pce_dev->reg.encr_cfg_aes_ccm_128;
else
encr_cfg = pce_dev->reg.encr_cfg_aes_ccm_256;
encr_cfg |= (CRYPTO_ENCR_MODE_CCM << CRYPTO_ENCR_MODE) |
(CRYPTO_LAST_CCM_XFR << CRYPTO_LAST_CCM);
break;
case QCE_MODE_CTR:
default:
if (key_size == AES128_KEY_SIZE)
encr_cfg = pce_dev->reg.encr_cfg_aes_ctr_128;
else
encr_cfg = pce_dev->reg.encr_cfg_aes_ctr_256;
break;
}
pce_dev->mode = creq->mode;
switch (creq->alg) {
case CIPHER_ALG_DES:
if (creq->mode != QCE_MODE_ECB) {
_byte_stream_to_net_words(enciv32, creq->iv, ivsize);
pce = cmdlistinfo->encr_cntr_iv;
pce->data = enciv32[0];
pce++;
pce->data = enciv32[1];
}
if (use_hw_key == false) {
pce = cmdlistinfo->encr_key;
pce->data = enckey32[0];
pce++;
pce->data = enckey32[1];
}
break;
case CIPHER_ALG_3DES:
if (creq->mode != QCE_MODE_ECB) {
_byte_stream_to_net_words(enciv32, creq->iv, ivsize);
pce = cmdlistinfo->encr_cntr_iv;
pce->data = enciv32[0];
pce++;
pce->data = enciv32[1];
}
if (use_hw_key == false) {
/* write encr key */
pce = cmdlistinfo->encr_key;
for (i = 0; i < 6; i++, pce++)
pce->data = enckey32[i];
}
break;
case CIPHER_ALG_AES:
default:
if (creq->mode == QCE_MODE_XTS) {
uint32_t xtskey32[MAX_CIPHER_KEY_SIZE/sizeof(uint32_t)]
= {0, 0, 0, 0, 0, 0, 0, 0};
uint32_t xtsklen =
creq->encklen/(2 * sizeof(uint32_t));
if ((use_hw_key == false) && (use_pipe_key == false)) {
_byte_stream_to_net_words(xtskey32,
(creq->enckey + creq->encklen/2),
creq->encklen/2);
/* write xts encr key */
pce = cmdlistinfo->encr_xts_key;
for (i = 0; i < xtsklen; i++, pce++)
pce->data = xtskey32[i];
}
/* write xts du size */
pce = cmdlistinfo->encr_xts_du_size;
if (!(creq->flags & QCRYPTO_CTX_XTS_MASK))
pce->data = creq->cryptlen;
else
pce->data = min((unsigned int)QCE_SECTOR_SIZE,
creq->cryptlen);
}
if (creq->mode != QCE_MODE_ECB) {
if (creq->mode == QCE_MODE_XTS)
_byte_stream_swap_to_net_words(enciv32,
creq->iv, ivsize);
else
_byte_stream_to_net_words(enciv32, creq->iv,
ivsize);
/* write encr cntr iv */
pce = cmdlistinfo->encr_cntr_iv;
for (i = 0; i < 4; i++, pce++)
pce->data = enciv32[i];
if (creq->mode == QCE_MODE_CCM) {
/* write cntr iv for ccm */
pce = cmdlistinfo->encr_ccm_cntr_iv;
for (i = 0; i < 4; i++, pce++)
pce->data = enciv32[i];
/* update cntr_iv[3] by one */
pce = cmdlistinfo->encr_cntr_iv;
pce += 3;
pce->data += 1;
}
}
if (creq->op == QCE_REQ_ABLK_CIPHER_NO_KEY) {
encr_cfg |= (CRYPTO_ENCR_KEY_SZ_AES128 <<
CRYPTO_ENCR_KEY_SZ);
} else {
if (use_hw_key == false) {
/* write encr key */
pce = cmdlistinfo->encr_key;
for (i = 0; i < enck_size_in_word; i++, pce++)
pce->data = enckey32[i];
}
} /* else of if (creq->op == QCE_REQ_ABLK_CIPHER_NO_KEY) */
break;
} /* end of switch (creq->mode) */
if (use_pipe_key)
encr_cfg |= (CRYPTO_USE_PIPE_KEY_ENCR_ENABLED
<< CRYPTO_USE_PIPE_KEY_ENCR);
/* write encr seg cfg */
pce = cmdlistinfo->encr_seg_cfg;
if ((creq->alg == CIPHER_ALG_DES) || (creq->alg == CIPHER_ALG_3DES)) {
if (creq->dir == QCE_ENCRYPT)
pce->data |= (1 << CRYPTO_ENCODE);
else
pce->data &= ~(1 << CRYPTO_ENCODE);
encr_cfg = pce->data;
} else {
encr_cfg |=
((creq->dir == QCE_ENCRYPT) ? 1 : 0) << CRYPTO_ENCODE;
}
if (use_hw_key == true)
encr_cfg |= (CRYPTO_USE_HW_KEY << CRYPTO_USE_HW_KEY_ENCR);
else
encr_cfg &= ~(CRYPTO_USE_HW_KEY << CRYPTO_USE_HW_KEY_ENCR);
pce->data = encr_cfg;
/* write encr seg size */
pce = cmdlistinfo->encr_seg_size;
if ((creq->mode == QCE_MODE_CCM) && (creq->dir == QCE_DECRYPT))
pce->data = (creq->cryptlen + creq->authsize);
else
pce->data = creq->cryptlen;
/* write encr seg start */
pce = cmdlistinfo->encr_seg_start;
pce->data = (coffset & 0xffff);
/* write seg size */
pce = cmdlistinfo->seg_size;
pce->data = totallen_in;
return 0;
};
static int _ce_setup_hash_direct(struct qce_device *pce_dev,
struct qce_sha_req *sreq)
{
uint32_t auth32[SHA256_DIGEST_SIZE / sizeof(uint32_t)];
uint32_t diglen;
bool use_hw_key = false;
int i;
uint32_t mackey32[SHA_HMAC_KEY_SIZE/sizeof(uint32_t)] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
bool sha1 = false;
uint32_t auth_cfg = 0;
/* clear status */
writel_relaxed(0, pce_dev->iobase + CRYPTO_STATUS_REG);
writel_relaxed(pce_dev->reg.crypto_cfg_be, (pce_dev->iobase +
CRYPTO_CONFIG_REG));
/*
* Ensure previous instructions (setting the CONFIG register)
* was completed before issuing starting to set other config register
* This is to ensure the configurations are done in correct endian-ness
* as set in the CONFIG registers
*/
mb();
if (sreq->alg == QCE_HASH_AES_CMAC) {
/* write seg_cfg */
writel_relaxed(0, pce_dev->iobase + CRYPTO_AUTH_SEG_CFG_REG);
/* write seg_cfg */
writel_relaxed(0, pce_dev->iobase + CRYPTO_ENCR_SEG_CFG_REG);
/* write seg_cfg */
writel_relaxed(0, pce_dev->iobase + CRYPTO_ENCR_SEG_SIZE_REG);
/* Clear auth_ivn, auth_keyn registers */
for (i = 0; i < 16; i++) {
writel_relaxed(0, (pce_dev->iobase +
(CRYPTO_AUTH_IV0_REG + i*sizeof(uint32_t))));
writel_relaxed(0, (pce_dev->iobase +
(CRYPTO_AUTH_KEY0_REG + i*sizeof(uint32_t))));
}
/* write auth_bytecnt 0/1/2/3, start with 0 */
for (i = 0; i < 4; i++)
writel_relaxed(0, pce_dev->iobase +
CRYPTO_AUTH_BYTECNT0_REG +
i * sizeof(uint32_t));
if (sreq->authklen == AES128_KEY_SIZE)
auth_cfg = pce_dev->reg.auth_cfg_cmac_128;
else
auth_cfg = pce_dev->reg.auth_cfg_cmac_256;
}
if ((sreq->alg == QCE_HASH_SHA1_HMAC) ||
(sreq->alg == QCE_HASH_SHA256_HMAC) ||
(sreq->alg == QCE_HASH_AES_CMAC)) {
uint32_t authk_size_in_word = sreq->authklen/sizeof(uint32_t);
_byte_stream_to_net_words(mackey32, sreq->authkey,
sreq->authklen);
/* check for null key. If null, use hw key*/
for (i = 0; i < authk_size_in_word; i++) {
if (mackey32[i] != 0)
break;
}
if (i == authk_size_in_word)
use_hw_key = true;
else
/* Clear auth_ivn, auth_keyn registers */
for (i = 0; i < authk_size_in_word; i++)
writel_relaxed(mackey32[i], (pce_dev->iobase +
(CRYPTO_AUTH_KEY0_REG +
i*sizeof(uint32_t))));
}
if (sreq->alg == QCE_HASH_AES_CMAC)
goto go_proc;
/* if not the last, the size has to be on the block boundary */
if (sreq->last_blk == 0 && (sreq->size % SHA256_BLOCK_SIZE))
return -EIO;
switch (sreq->alg) {
case QCE_HASH_SHA1:
auth_cfg = pce_dev->reg.auth_cfg_sha1;
diglen = SHA1_DIGEST_SIZE;
sha1 = true;
break;
case QCE_HASH_SHA1_HMAC:
auth_cfg = pce_dev->reg.auth_cfg_hmac_sha1;
diglen = SHA1_DIGEST_SIZE;
sha1 = true;
break;
case QCE_HASH_SHA256:
auth_cfg = pce_dev->reg.auth_cfg_sha256;
diglen = SHA256_DIGEST_SIZE;
break;
case QCE_HASH_SHA256_HMAC:
auth_cfg = pce_dev->reg.auth_cfg_hmac_sha256;
diglen = SHA256_DIGEST_SIZE;
break;
default:
return -EINVAL;
}
/* write 20/32 bytes, 5/8 words into auth_iv for SHA1/SHA256 */
if (sreq->first_blk) {
if (sha1) {
for (i = 0; i < 5; i++)
auth32[i] = _std_init_vector_sha1[i];
} else {
for (i = 0; i < 8; i++)
auth32[i] = _std_init_vector_sha256[i];
}
} else {
_byte_stream_to_net_words(auth32, sreq->digest, diglen);
}
/* Set auth_ivn, auth_keyn registers */
for (i = 0; i < 5; i++)
writel_relaxed(auth32[i], (pce_dev->iobase +
(CRYPTO_AUTH_IV0_REG + i*sizeof(uint32_t))));
if ((sreq->alg == QCE_HASH_SHA256) ||
(sreq->alg == QCE_HASH_SHA256_HMAC)) {
for (i = 5; i < 8; i++)
writel_relaxed(auth32[i], (pce_dev->iobase +
(CRYPTO_AUTH_IV0_REG + i*sizeof(uint32_t))));
}
/* write auth_bytecnt 0/1/2/3, start with 0 */
for (i = 0; i < 2; i++)
writel_relaxed(sreq->auth_data[i], pce_dev->iobase +
CRYPTO_AUTH_BYTECNT0_REG +
i * sizeof(uint32_t));
/* Set/reset last bit in CFG register */
if (sreq->last_blk)
auth_cfg |= 1 << CRYPTO_LAST;
else
auth_cfg &= ~(1 << CRYPTO_LAST);
if (sreq->first_blk)
auth_cfg |= 1 << CRYPTO_FIRST;
else
auth_cfg &= ~(1 << CRYPTO_FIRST);
go_proc:
/* write seg_cfg */
writel_relaxed(auth_cfg, pce_dev->iobase + CRYPTO_AUTH_SEG_CFG_REG);
/* write auth seg_size */
writel_relaxed(sreq->size, pce_dev->iobase + CRYPTO_AUTH_SEG_SIZE_REG);
/* write auth_seg_start */
writel_relaxed(0, pce_dev->iobase + CRYPTO_AUTH_SEG_START_REG);
/* reset encr seg_cfg */
writel_relaxed(0, pce_dev->iobase + CRYPTO_ENCR_SEG_CFG_REG);
/* write seg_size */
writel_relaxed(sreq->size, pce_dev->iobase + CRYPTO_SEG_SIZE_REG);
writel_relaxed(pce_dev->reg.crypto_cfg_le, (pce_dev->iobase +
CRYPTO_CONFIG_REG));
/* issue go to crypto */
if (use_hw_key == false)
writel_relaxed(((1 << CRYPTO_GO) | (1 << CRYPTO_RESULTS_DUMP)),
pce_dev->iobase + CRYPTO_GOPROC_REG);
else
writel_relaxed(((1 << CRYPTO_GO) | (1 << CRYPTO_RESULTS_DUMP)),
pce_dev->iobase + CRYPTO_GOPROC_QC_KEY_REG);
/*
* Ensure previous instructions (setting the GO register)
* was completed before issuing a DMA transfer request
*/
mb();
return 0;
}
static int _ce_setup_aead_direct(struct qce_device *pce_dev,
struct qce_req *q_req, uint32_t totallen_in, uint32_t coffset)
{
int32_t authk_size_in_word = q_req->authklen/sizeof(uint32_t);
int i;
uint32_t mackey32[SHA_HMAC_KEY_SIZE/sizeof(uint32_t)] = {0};
uint32_t a_cfg;
uint32_t enckey32[(MAX_CIPHER_KEY_SIZE*2)/sizeof(uint32_t)] = {0};
uint32_t enciv32[MAX_IV_LENGTH/sizeof(uint32_t)] = {0};
uint32_t enck_size_in_word = 0;
uint32_t enciv_in_word;
uint32_t key_size;
uint32_t ivsize = q_req->ivsize;
uint32_t encr_cfg;
/* clear status */
writel_relaxed(0, pce_dev->iobase + CRYPTO_STATUS_REG);
writel_relaxed(pce_dev->reg.crypto_cfg_be, (pce_dev->iobase +
CRYPTO_CONFIG_REG));
/*
* Ensure previous instructions (setting the CONFIG register)
* was completed before issuing starting to set other config register
* This is to ensure the configurations are done in correct endian-ness
* as set in the CONFIG registers
*/
mb();
key_size = q_req->encklen;
enck_size_in_word = key_size/sizeof(uint32_t);
switch (q_req->alg) {
case CIPHER_ALG_DES:
switch (q_req->mode) {
case QCE_MODE_ECB:
encr_cfg = pce_dev->reg.encr_cfg_des_ecb;
break;
case QCE_MODE_CBC:
encr_cfg = pce_dev->reg.encr_cfg_des_cbc;
break;
default:
return -EINVAL;
}
enciv_in_word = 2;
break;
case CIPHER_ALG_3DES:
switch (q_req->mode) {
case QCE_MODE_ECB:
encr_cfg = pce_dev->reg.encr_cfg_3des_ecb;
break;
case QCE_MODE_CBC:
encr_cfg = pce_dev->reg.encr_cfg_3des_cbc;
break;
default:
return -EINVAL;
}
enciv_in_word = 2;
break;
case CIPHER_ALG_AES:
switch (q_req->mode) {
case QCE_MODE_ECB:
if (key_size == AES128_KEY_SIZE)
encr_cfg = pce_dev->reg.encr_cfg_aes_ecb_128;
else if (key_size == AES256_KEY_SIZE)
encr_cfg = pce_dev->reg.encr_cfg_aes_ecb_256;
else
return -EINVAL;
break;
case QCE_MODE_CBC:
if (key_size == AES128_KEY_SIZE)
encr_cfg = pce_dev->reg.encr_cfg_aes_cbc_128;
else if (key_size == AES256_KEY_SIZE)
encr_cfg = pce_dev->reg.encr_cfg_aes_cbc_256;
else
return -EINVAL;
break;
default:
return -EINVAL;
}
enciv_in_word = 4;
break;
default:
return -EINVAL;
}
pce_dev->mode = q_req->mode;
/* write CNTR0_IV0_REG */
if (q_req->mode != QCE_MODE_ECB) {
_byte_stream_to_net_words(enciv32, q_req->iv, ivsize);
for (i = 0; i < enciv_in_word; i++)
writel_relaxed(enciv32[i], pce_dev->iobase +
(CRYPTO_CNTR0_IV0_REG + i * sizeof(uint32_t)));
}
/*
* write encr key
* do not use hw key or pipe key
*/
_byte_stream_to_net_words(enckey32, q_req->enckey, key_size);
for (i = 0; i < enck_size_in_word; i++)
writel_relaxed(enckey32[i], pce_dev->iobase +
(CRYPTO_ENCR_KEY0_REG + i * sizeof(uint32_t)));
/* write encr seg cfg */
if (q_req->dir == QCE_ENCRYPT)
encr_cfg |= (1 << CRYPTO_ENCODE);
writel_relaxed(encr_cfg, pce_dev->iobase + CRYPTO_ENCR_SEG_CFG_REG);
/* we only support sha1-hmac at this point */
_byte_stream_to_net_words(mackey32, q_req->authkey,
q_req->authklen);
for (i = 0; i < authk_size_in_word; i++)
writel_relaxed(mackey32[i], pce_dev->iobase +
(CRYPTO_AUTH_KEY0_REG + i * sizeof(uint32_t)));
for (i = 0; i < 5; i++)
writel_relaxed(_std_init_vector_sha1[i], pce_dev->iobase +
(CRYPTO_AUTH_IV0_REG + i * sizeof(uint32_t)));
/* write auth_bytecnt 0/1, start with 0 */
writel_relaxed(0, pce_dev->iobase + CRYPTO_AUTH_BYTECNT0_REG);
writel_relaxed(0, pce_dev->iobase + CRYPTO_AUTH_BYTECNT1_REG);
/* write encr seg size */
writel_relaxed(q_req->cryptlen, pce_dev->iobase +
CRYPTO_ENCR_SEG_SIZE_REG);
/* write encr start */
writel_relaxed(coffset & 0xffff, pce_dev->iobase +
CRYPTO_ENCR_SEG_START_REG);
a_cfg = (CRYPTO_AUTH_MODE_HMAC << CRYPTO_AUTH_MODE) |
(CRYPTO_AUTH_SIZE_SHA1 << CRYPTO_AUTH_SIZE) |
(1 << CRYPTO_LAST) | (1 << CRYPTO_FIRST) |
(CRYPTO_AUTH_ALG_SHA << CRYPTO_AUTH_ALG);
if (q_req->dir == QCE_ENCRYPT)
a_cfg |= (CRYPTO_AUTH_POS_AFTER << CRYPTO_AUTH_POS);
else
a_cfg |= (CRYPTO_AUTH_POS_BEFORE << CRYPTO_AUTH_POS);
/* write auth seg_cfg */
writel_relaxed(a_cfg, pce_dev->iobase + CRYPTO_AUTH_SEG_CFG_REG);
/* write auth seg_size */
writel_relaxed(totallen_in, pce_dev->iobase + CRYPTO_AUTH_SEG_SIZE_REG);
/* write auth_seg_start */
writel_relaxed(0, pce_dev->iobase + CRYPTO_AUTH_SEG_START_REG);
/* write seg_size */
writel_relaxed(totallen_in, pce_dev->iobase + CRYPTO_SEG_SIZE_REG);
writel_relaxed(pce_dev->reg.crypto_cfg_le, (pce_dev->iobase +
CRYPTO_CONFIG_REG));
/* issue go to crypto */
writel_relaxed(((1 << CRYPTO_GO) | (1 << CRYPTO_RESULTS_DUMP)),
pce_dev->iobase + CRYPTO_GOPROC_REG);
/*
* Ensure previous instructions (setting the GO register)
* was completed before issuing a DMA transfer request
*/
mb();
return 0;
};
static int _ce_setup_cipher_direct(struct qce_device *pce_dev,
struct qce_req *creq, uint32_t totallen_in, uint32_t coffset)
{
uint32_t enckey32[(MAX_CIPHER_KEY_SIZE * 2)/sizeof(uint32_t)] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
uint32_t enciv32[MAX_IV_LENGTH / sizeof(uint32_t)] = {
0, 0, 0, 0};
uint32_t enck_size_in_word = 0;
uint32_t key_size;
bool use_hw_key = false;
bool use_pipe_key = false;
uint32_t encr_cfg = 0;
uint32_t ivsize = creq->ivsize;
int i;
/* clear status */
writel_relaxed(0, pce_dev->iobase + CRYPTO_STATUS_REG);
writel_relaxed(pce_dev->reg.crypto_cfg_be, (pce_dev->iobase +
CRYPTO_CONFIG_REG));
/*
* Ensure previous instructions (setting the CONFIG register)
* was completed before issuing starting to set other config register
* This is to ensure the configurations are done in correct endian-ness
* as set in the CONFIG registers
*/
mb();
if (creq->mode == QCE_MODE_XTS)
key_size = creq->encklen/2;
else
key_size = creq->encklen;
if ((creq->flags & QCRYPTO_CTX_USE_HW_KEY) == QCRYPTO_CTX_USE_HW_KEY) {
use_hw_key = true;
} else {
if ((creq->flags & QCRYPTO_CTX_USE_PIPE_KEY) ==
QCRYPTO_CTX_USE_PIPE_KEY)
use_pipe_key = true;
}
if ((use_pipe_key == false) && (use_hw_key == false)) {
_byte_stream_to_net_words(enckey32, creq->enckey, key_size);
enck_size_in_word = key_size/sizeof(uint32_t);
}
if ((creq->op == QCE_REQ_AEAD) && (creq->mode == QCE_MODE_CCM)) {
uint32_t authklen32 = creq->encklen/sizeof(uint32_t);
uint32_t noncelen32 = MAX_NONCE/sizeof(uint32_t);
uint32_t nonce32[MAX_NONCE/sizeof(uint32_t)] = {0, 0, 0, 0};
uint32_t auth_cfg = 0;
/* Clear auth_ivn, auth_keyn registers */
for (i = 0; i < 16; i++) {
writel_relaxed(0, (pce_dev->iobase +
(CRYPTO_AUTH_IV0_REG + i*sizeof(uint32_t))));
writel_relaxed(0, (pce_dev->iobase +
(CRYPTO_AUTH_KEY0_REG + i*sizeof(uint32_t))));
}
/* write auth_bytecnt 0/1/2/3, start with 0 */
for (i = 0; i < 4; i++)
writel_relaxed(0, pce_dev->iobase +
CRYPTO_AUTH_BYTECNT0_REG +
i * sizeof(uint32_t));
/* write nonce */
_byte_stream_to_net_words(nonce32, creq->nonce, MAX_NONCE);
for (i = 0; i < noncelen32; i++)
writel_relaxed(nonce32[i], pce_dev->iobase +
CRYPTO_AUTH_INFO_NONCE0_REG +
(i*sizeof(uint32_t)));
if (creq->authklen == AES128_KEY_SIZE)
auth_cfg = pce_dev->reg.auth_cfg_aes_ccm_128;
else {
if (creq->authklen == AES256_KEY_SIZE)
auth_cfg = pce_dev->reg.auth_cfg_aes_ccm_256;
}
if (creq->dir == QCE_ENCRYPT)
auth_cfg |= (CRYPTO_AUTH_POS_BEFORE << CRYPTO_AUTH_POS);
else
auth_cfg |= (CRYPTO_AUTH_POS_AFTER << CRYPTO_AUTH_POS);
auth_cfg |= ((creq->authsize - 1) << CRYPTO_AUTH_SIZE);
if (use_hw_key == true) {
auth_cfg |= (1 << CRYPTO_USE_HW_KEY_AUTH);
} else {
auth_cfg &= ~(1 << CRYPTO_USE_HW_KEY_AUTH);
/* write auth key */
for (i = 0; i < authklen32; i++)
writel_relaxed(enckey32[i], pce_dev->iobase +
CRYPTO_AUTH_KEY0_REG + (i*sizeof(uint32_t)));
}
writel_relaxed(auth_cfg, pce_dev->iobase +
CRYPTO_AUTH_SEG_CFG_REG);
if (creq->dir == QCE_ENCRYPT)
writel_relaxed(totallen_in, pce_dev->iobase +
CRYPTO_AUTH_SEG_SIZE_REG);
else
writel_relaxed((totallen_in - creq->authsize),
pce_dev->iobase + CRYPTO_AUTH_SEG_SIZE_REG);
writel_relaxed(0, pce_dev->iobase + CRYPTO_AUTH_SEG_START_REG);
} else {
if (creq->op != QCE_REQ_AEAD)
writel_relaxed(0, pce_dev->iobase +
CRYPTO_AUTH_SEG_CFG_REG);
}
/*
* Ensure previous instructions (write to all AUTH registers)
* was completed before accessing a register that is not in
* in the same 1K range.
*/
mb();
switch (creq->mode) {
case QCE_MODE_ECB:
if (key_size == AES128_KEY_SIZE)
encr_cfg = pce_dev->reg.encr_cfg_aes_ecb_128;
else
encr_cfg = pce_dev->reg.encr_cfg_aes_ecb_256;
break;
case QCE_MODE_CBC:
if (key_size == AES128_KEY_SIZE)
encr_cfg = pce_dev->reg.encr_cfg_aes_cbc_128;
else
encr_cfg = pce_dev->reg.encr_cfg_aes_cbc_256;
break;
case QCE_MODE_XTS:
if (key_size == AES128_KEY_SIZE)
encr_cfg = pce_dev->reg.encr_cfg_aes_xts_128;
else
encr_cfg = pce_dev->reg.encr_cfg_aes_xts_256;
break;
case QCE_MODE_CCM:
if (key_size == AES128_KEY_SIZE)
encr_cfg = pce_dev->reg.encr_cfg_aes_ccm_128;
else
encr_cfg = pce_dev->reg.encr_cfg_aes_ccm_256;
break;
case QCE_MODE_CTR:
default:
if (key_size == AES128_KEY_SIZE)
encr_cfg = pce_dev->reg.encr_cfg_aes_ctr_128;
else
encr_cfg = pce_dev->reg.encr_cfg_aes_ctr_256;
break;
}
pce_dev->mode = creq->mode;
switch (creq->alg) {
case CIPHER_ALG_DES:
if (creq->mode != QCE_MODE_ECB) {
encr_cfg = pce_dev->reg.encr_cfg_des_cbc;
_byte_stream_to_net_words(enciv32, creq->iv, ivsize);
writel_relaxed(enciv32[0], pce_dev->iobase +
CRYPTO_CNTR0_IV0_REG);
writel_relaxed(enciv32[1], pce_dev->iobase +
CRYPTO_CNTR1_IV1_REG);
} else {
encr_cfg = pce_dev->reg.encr_cfg_des_ecb;
}
if (use_hw_key == false) {
writel_relaxed(enckey32[0], pce_dev->iobase +
CRYPTO_ENCR_KEY0_REG);
writel_relaxed(enckey32[1], pce_dev->iobase +
CRYPTO_ENCR_KEY1_REG);
}
break;
case CIPHER_ALG_3DES:
if (creq->mode != QCE_MODE_ECB) {
_byte_stream_to_net_words(enciv32, creq->iv, ivsize);
writel_relaxed(enciv32[0], pce_dev->iobase +
CRYPTO_CNTR0_IV0_REG);
writel_relaxed(enciv32[1], pce_dev->iobase +
CRYPTO_CNTR1_IV1_REG);
encr_cfg = pce_dev->reg.encr_cfg_3des_cbc;
} else {
encr_cfg = pce_dev->reg.encr_cfg_3des_ecb;
}
if (use_hw_key == false) {
/* write encr key */
for (i = 0; i < 6; i++)
writel_relaxed(enckey32[0], (pce_dev->iobase +
(CRYPTO_ENCR_KEY0_REG + i * sizeof(uint32_t))));
}
break;
case CIPHER_ALG_AES:
default:
if (creq->mode == QCE_MODE_XTS) {
uint32_t xtskey32[MAX_CIPHER_KEY_SIZE/sizeof(uint32_t)]
= {0, 0, 0, 0, 0, 0, 0, 0};
uint32_t xtsklen =
creq->encklen/(2 * sizeof(uint32_t));
if ((use_hw_key == false) && (use_pipe_key == false)) {
_byte_stream_to_net_words(xtskey32,
(creq->enckey + creq->encklen/2),
creq->encklen/2);
/* write xts encr key */
for (i = 0; i < xtsklen; i++)
writel_relaxed(xtskey32[i],
pce_dev->iobase +
CRYPTO_ENCR_XTS_KEY0_REG +
(i * sizeof(uint32_t)));
}
/* write xts du size */
if (use_pipe_key == true)
writel_relaxed(min((uint32_t)QCE_SECTOR_SIZE,
creq->cryptlen),
pce_dev->iobase +
CRYPTO_ENCR_XTS_DU_SIZE_REG);
else
writel_relaxed(creq->cryptlen ,
pce_dev->iobase +
CRYPTO_ENCR_XTS_DU_SIZE_REG);
}
if (creq->mode != QCE_MODE_ECB) {
if (creq->mode == QCE_MODE_XTS)
_byte_stream_swap_to_net_words(enciv32,
creq->iv, ivsize);
else
_byte_stream_to_net_words(enciv32, creq->iv,
ivsize);
/* write encr cntr iv */
for (i = 0; i <= 3; i++)
writel_relaxed(enciv32[i], pce_dev->iobase +
CRYPTO_CNTR0_IV0_REG +
(i * sizeof(uint32_t)));
if (creq->mode == QCE_MODE_CCM) {
/* write cntr iv for ccm */
for (i = 0; i <= 3; i++)
writel_relaxed(enciv32[i],
pce_dev->iobase +
CRYPTO_ENCR_CCM_INT_CNTR0_REG +
(i * sizeof(uint32_t)));
/* update cntr_iv[3] by one */
writel_relaxed((enciv32[3] + 1),
pce_dev->iobase +
CRYPTO_CNTR0_IV0_REG +
(3 * sizeof(uint32_t)));
}
}
if (creq->op == QCE_REQ_ABLK_CIPHER_NO_KEY) {
encr_cfg |= (CRYPTO_ENCR_KEY_SZ_AES128 <<
CRYPTO_ENCR_KEY_SZ);
} else {
if ((use_hw_key == false) && (use_pipe_key == false)) {
for (i = 0; i < enck_size_in_word; i++)
writel_relaxed(enckey32[i],
pce_dev->iobase +
CRYPTO_ENCR_KEY0_REG +
(i * sizeof(uint32_t)));
}
} /* else of if (creq->op == QCE_REQ_ABLK_CIPHER_NO_KEY) */
break;
} /* end of switch (creq->mode) */
if (use_pipe_key)
encr_cfg |= (CRYPTO_USE_PIPE_KEY_ENCR_ENABLED
<< CRYPTO_USE_PIPE_KEY_ENCR);
/* write encr seg cfg */
encr_cfg |= ((creq->dir == QCE_ENCRYPT) ? 1 : 0) << CRYPTO_ENCODE;
if (use_hw_key == true)
encr_cfg |= (CRYPTO_USE_HW_KEY << CRYPTO_USE_HW_KEY_ENCR);
else
encr_cfg &= ~(CRYPTO_USE_HW_KEY << CRYPTO_USE_HW_KEY_ENCR);
/* write encr seg cfg */
writel_relaxed(encr_cfg, pce_dev->iobase + CRYPTO_ENCR_SEG_CFG_REG);
/* write encr seg size */
if ((creq->mode == QCE_MODE_CCM) && (creq->dir == QCE_DECRYPT))
writel_relaxed((creq->cryptlen + creq->authsize),
pce_dev->iobase + CRYPTO_ENCR_SEG_SIZE_REG);
else
writel_relaxed(creq->cryptlen,
pce_dev->iobase + CRYPTO_ENCR_SEG_SIZE_REG);
/* write encr seg start */
writel_relaxed((coffset & 0xffff),
pce_dev->iobase + CRYPTO_ENCR_SEG_START_REG);
/* write encr seg start */
writel_relaxed(0xffffffff,
pce_dev->iobase + CRYPTO_CNTR_MASK_REG);
/* write seg size */
writel_relaxed(totallen_in, pce_dev->iobase + CRYPTO_SEG_SIZE_REG);
writel_relaxed(pce_dev->reg.crypto_cfg_le, (pce_dev->iobase +
CRYPTO_CONFIG_REG));
/* issue go to crypto */
if (use_hw_key == false)
writel_relaxed(((1 << CRYPTO_GO) | (1 << CRYPTO_RESULTS_DUMP)),
pce_dev->iobase + CRYPTO_GOPROC_REG);
else
writel_relaxed(((1 << CRYPTO_GO) | (1 << CRYPTO_RESULTS_DUMP)),
pce_dev->iobase + CRYPTO_GOPROC_QC_KEY_REG);
/*
* Ensure previous instructions (setting the GO register)
* was completed before issuing a DMA transfer request
*/
mb();
return 0;
};
static int _qce_unlock_other_pipes(struct qce_device *pce_dev)
{
int rc = 0;
if (pce_dev->support_cmd_dscr == false)
return rc;
pce_dev->ce_sps.consumer.event.callback = NULL;
rc = sps_transfer_one(pce_dev->ce_sps.consumer.pipe,
GET_PHYS_ADDR(pce_dev->ce_sps.cmdlistptr.unlock_all_pipes.cmdlist),
0, NULL, (SPS_IOVEC_FLAG_CMD | SPS_IOVEC_FLAG_UNLOCK));
if (rc) {
pr_err("sps_xfr_one() fail rc=%d", rc);
rc = -EINVAL;
}
return rc;
}
static int _aead_complete(struct qce_device *pce_dev)
{
struct aead_request *areq;
unsigned char mac[SHA256_DIGEST_SIZE];
uint32_t status;
int32_t result_status;
areq = (struct aead_request *) pce_dev->areq;
if (areq->src != areq->dst) {
qce_dma_unmap_sg(pce_dev->pdev, areq->dst, pce_dev->dst_nents,
DMA_FROM_DEVICE);
}
qce_dma_unmap_sg(pce_dev->pdev, areq->src, pce_dev->src_nents,
(areq->src == areq->dst) ? DMA_BIDIRECTIONAL :
DMA_TO_DEVICE);
qce_dma_unmap_sg(pce_dev->pdev, areq->assoc, pce_dev->assoc_nents,
DMA_TO_DEVICE);
/* check MAC */
memcpy(mac, (char *)(&pce_dev->ce_sps.result->auth_iv[0]),
SHA256_DIGEST_SIZE);
/* read status before unlock */
status = readl_relaxed(pce_dev->iobase + CRYPTO_STATUS_REG);
if (_qce_unlock_other_pipes(pce_dev))
return -EINVAL;
/*
* Don't use result dump status. The operation may not
* be complete.
* Instead, use the status we just read of device.
* In case, we need to use result_status from result
* dump the result_status needs to be byte swapped,
* since we set the device to little endian.
*/
result_status = 0;
pce_dev->ce_sps.result->status = 0;
if (status & ((1 << CRYPTO_SW_ERR) | (1 << CRYPTO_AXI_ERR)
| (1 << CRYPTO_HSD_ERR))) {
pr_err("aead operation error. Status %x\n", status);
result_status = -ENXIO;
} else if (pce_dev->ce_sps.consumer_status |
pce_dev->ce_sps.producer_status) {
pr_err("aead sps operation error. sps status %x %x\n",
pce_dev->ce_sps.consumer_status,
pce_dev->ce_sps.producer_status);
result_status = -ENXIO;
} else if ((status & (1 << CRYPTO_OPERATION_DONE)) == 0) {
pr_err("aead operation not done? Status %x, sps status %x %x\n",
status,
pce_dev->ce_sps.consumer_status,
pce_dev->ce_sps.producer_status);
result_status = -ENXIO;
}
if (pce_dev->mode == QCE_MODE_CCM) {
if (result_status == 0 && (status & (1 << CRYPTO_MAC_FAILED)))
result_status = -EBADMSG;
pce_dev->qce_cb(areq, mac, NULL, result_status);
} else {
uint32_t ivsize = 0;
struct crypto_aead *aead;
unsigned char iv[NUM_OF_CRYPTO_CNTR_IV_REG * CRYPTO_REG_SIZE];
aead = crypto_aead_reqtfm(areq);
ivsize = crypto_aead_ivsize(aead);
if (pce_dev->ce_sps.minor_version != 0)
dma_unmap_single(pce_dev->pdev, pce_dev->phy_iv_in,
ivsize, DMA_TO_DEVICE);
memcpy(iv, (char *)(pce_dev->ce_sps.result->encr_cntr_iv),
sizeof(iv));
pce_dev->qce_cb(areq, mac, iv, result_status);
}
return 0;
};
static int _sha_complete(struct qce_device *pce_dev)
{
struct ahash_request *areq;
unsigned char digest[SHA256_DIGEST_SIZE];
uint32_t bytecount32[2];
int32_t result_status = pce_dev->ce_sps.result->status;
uint32_t status;
areq = (struct ahash_request *) pce_dev->areq;
qce_dma_unmap_sg(pce_dev->pdev, areq->src, pce_dev->src_nents,
DMA_TO_DEVICE);
memcpy(digest, (char *)(&pce_dev->ce_sps.result->auth_iv[0]),
SHA256_DIGEST_SIZE);
_byte_stream_to_net_words(bytecount32,
(unsigned char *)pce_dev->ce_sps.result->auth_byte_count,
2 * CRYPTO_REG_SIZE);
/* read status before unlock */
status = readl_relaxed(pce_dev->iobase + CRYPTO_STATUS_REG);
if (_qce_unlock_other_pipes(pce_dev))
return -EINVAL;
/*
* Don't use result dump status. The operation may not be complete.
* Instead, use the status we just read of device.
* In case, we need to use result_status from result
* dump the result_status needs to be byte swapped,
* since we set the device to little endian.
*/
if (status & ((1 << CRYPTO_SW_ERR) | (1 << CRYPTO_AXI_ERR)
| (1 << CRYPTO_HSD_ERR))) {
pr_err("sha operation error. Status %x\n", status);
result_status = -ENXIO;
} else if (pce_dev->ce_sps.consumer_status) {
pr_err("sha sps operation error. sps status %x\n",
pce_dev->ce_sps.consumer_status);
result_status = -ENXIO;
} else if ((status & (1 << CRYPTO_OPERATION_DONE)) == 0) {
pr_err("sha operation not done? Status %x, sps status %x\n",
status, pce_dev->ce_sps.consumer_status);
result_status = -ENXIO;
} else {
result_status = 0;
}
pce_dev->qce_cb(areq, digest, (char *)bytecount32,
result_status);
return 0;
};
static int _ablk_cipher_complete(struct qce_device *pce_dev)
{
struct ablkcipher_request *areq;
unsigned char iv[NUM_OF_CRYPTO_CNTR_IV_REG * CRYPTO_REG_SIZE];
uint32_t status;
int32_t result_status;
areq = (struct ablkcipher_request *) pce_dev->areq;
if (areq->src != areq->dst) {
qce_dma_unmap_sg(pce_dev->pdev, areq->dst,
pce_dev->dst_nents, DMA_FROM_DEVICE);
}
qce_dma_unmap_sg(pce_dev->pdev, areq->src, pce_dev->src_nents,
(areq->src == areq->dst) ? DMA_BIDIRECTIONAL :
DMA_TO_DEVICE);
/* read status before unlock */
status = readl_relaxed(pce_dev->iobase + CRYPTO_STATUS_REG);
if (_qce_unlock_other_pipes(pce_dev))
return -EINVAL;
/*
* Don't use result dump status. The operation may not be complete.
* Instead, use the status we just read of device.
* In case, we need to use result_status from result
* dump the result_status needs to be byte swapped,
* since we set the device to little endian.
*/
if (status & ((1 << CRYPTO_SW_ERR) | (1 << CRYPTO_AXI_ERR)
| (1 << CRYPTO_HSD_ERR))) {
pr_err("ablk_cipher operation error. Status %x\n",
status);
result_status = -ENXIO;
} else if (pce_dev->ce_sps.consumer_status |
pce_dev->ce_sps.producer_status) {
pr_err("ablk_cipher sps operation error. sps status %x %x\n",
pce_dev->ce_sps.consumer_status,
pce_dev->ce_sps.producer_status);
result_status = -ENXIO;
} else if ((status & (1 << CRYPTO_OPERATION_DONE)) == 0) {
pr_err("ablk_cipher operation not done? Status %x, sps status %x %x\n",
status,
pce_dev->ce_sps.consumer_status,
pce_dev->ce_sps.producer_status);
result_status = -ENXIO;
} else {
result_status = 0;
}
if (pce_dev->mode == QCE_MODE_ECB) {
pce_dev->qce_cb(areq, NULL, NULL,
pce_dev->ce_sps.consumer_status |
result_status);
} else {
if (pce_dev->ce_sps.minor_version == 0) {
if (pce_dev->mode == QCE_MODE_CBC) {
if (pce_dev->dir == QCE_DECRYPT)
memcpy(iv, (char *)pce_dev->dec_iv,
sizeof(iv));
else
memcpy(iv, (unsigned char *)
(sg_virt(areq->src) +
areq->src->length - 16),
sizeof(iv));
}
if ((pce_dev->mode == QCE_MODE_CTR) ||
(pce_dev->mode == QCE_MODE_XTS)) {
uint32_t num_blk = 0;
uint32_t cntr_iv3 = 0;
unsigned long long cntr_iv64 = 0;
unsigned char *b = (unsigned char *)(&cntr_iv3);
memcpy(iv, areq->info, sizeof(iv));
if (pce_dev->mode != QCE_MODE_XTS)
num_blk = areq->nbytes/16;
else
num_blk = 1;
cntr_iv3 = ((*(iv + 12) << 24) & 0xff000000) |
(((*(iv + 13)) << 16) & 0xff0000) |
(((*(iv + 14)) << 8) & 0xff00) |
(*(iv + 15) & 0xff);
cntr_iv64 =
(((unsigned long long)cntr_iv3 &
(unsigned long long)0xFFFFFFFFULL) +
(unsigned long long)num_blk) %
(unsigned long long)(0x100000000ULL);
cntr_iv3 = (u32)(cntr_iv64 & 0xFFFFFFFF);
*(iv + 15) = (char)(*b);
*(iv + 14) = (char)(*(b + 1));
*(iv + 13) = (char)(*(b + 2));
*(iv + 12) = (char)(*(b + 3));
}
} else {
memcpy(iv,
(char *)(pce_dev->ce_sps.result->encr_cntr_iv),
sizeof(iv));
}
pce_dev->qce_cb(areq, NULL, iv, result_status);
}
return 0;
};
#ifdef QCE_DEBUG
static void _qce_dump_descr_fifos(struct qce_device *pce_dev)
{
int i, j, ents;
struct sps_iovec *iovec = pce_dev->ce_sps.in_transfer.iovec;
uint32_t cmd_flags = SPS_IOVEC_FLAG_CMD;
printk(KERN_INFO "==============================================\n");
printk(KERN_INFO "CONSUMER (TX/IN/DEST) PIPE DESCRIPTOR\n");
printk(KERN_INFO "==============================================\n");
for (i = 0; i < pce_dev->ce_sps.in_transfer.iovec_count; i++) {
printk(KERN_INFO " [%d] addr=0x%x size=0x%x flags=0x%x\n", i,
iovec->addr, iovec->size, iovec->flags);
if (iovec->flags & cmd_flags) {
struct sps_command_element *pced;
pced = (struct sps_command_element *)
(GET_VIRT_ADDR(iovec->addr));
ents = iovec->size/(sizeof(struct sps_command_element));
for (j = 0; j < ents; j++) {
printk(KERN_INFO " [%d] [0x%x] 0x%x\n", j,
pced->addr, pced->data);
pced++;
}
}
iovec++;
}
printk(KERN_INFO "==============================================\n");
printk(KERN_INFO "PRODUCER (RX/OUT/SRC) PIPE DESCRIPTOR\n");
printk(KERN_INFO "==============================================\n");
iovec = pce_dev->ce_sps.out_transfer.iovec;
for (i = 0; i < pce_dev->ce_sps.out_transfer.iovec_count; i++) {
printk(KERN_INFO " [%d] addr=0x%x size=0x%x flags=0x%x\n", i,
iovec->addr, iovec->size, iovec->flags);
iovec++;
}
}
#else
static void _qce_dump_descr_fifos(struct qce_device *pce_dev)
{
}
#endif
static void _qce_dump_descr_fifos_fail(struct qce_device *pce_dev)
{
int i, j, ents;
struct sps_iovec *iovec = pce_dev->ce_sps.in_transfer.iovec;
uint32_t cmd_flags = SPS_IOVEC_FLAG_CMD;
printk(KERN_INFO "==============================================\n");
printk(KERN_INFO "CONSUMER (TX/IN/DEST) PIPE DESCRIPTOR\n");
printk(KERN_INFO "==============================================\n");
for (i = 0; i < pce_dev->ce_sps.in_transfer.iovec_count; i++) {
printk(KERN_INFO " [%d] addr=0x%x size=0x%x flags=0x%x\n", i,
iovec->addr, iovec->size, iovec->flags);
if (iovec->flags & cmd_flags) {
struct sps_command_element *pced;
pced = (struct sps_command_element *)
(GET_VIRT_ADDR(iovec->addr));
ents = iovec->size/(sizeof(struct sps_command_element));
for (j = 0; j < ents; j++) {
printk(KERN_INFO " [%d] [0x%x] 0x%x\n", j,
pced->addr, pced->data);
pced++;
}
}
iovec++;
}
printk(KERN_INFO "==============================================\n");
printk(KERN_INFO "PRODUCER (RX/OUT/SRC) PIPE DESCRIPTOR\n");
printk(KERN_INFO "==============================================\n");
iovec = pce_dev->ce_sps.out_transfer.iovec;
for (i = 0; i < pce_dev->ce_sps.out_transfer.iovec_count; i++) {
printk(KERN_INFO " [%d] addr=0x%x size=0x%x flags=0x%x\n", i,
iovec->addr, iovec->size, iovec->flags);
iovec++;
}
}
static void _qce_sps_iovec_count_init(struct qce_device *pce_dev)
{
pce_dev->ce_sps.in_transfer.iovec_count = 0;
pce_dev->ce_sps.out_transfer.iovec_count = 0;
}
static void _qce_set_flag(struct sps_transfer *sps_bam_pipe, uint32_t flag)
{
struct sps_iovec *iovec = sps_bam_pipe->iovec +
(sps_bam_pipe->iovec_count - 1);
iovec->flags |= flag;
}
static int _qce_sps_add_data(uint32_t addr, uint32_t len,
struct sps_transfer *sps_bam_pipe)
{
struct sps_iovec *iovec = sps_bam_pipe->iovec +
sps_bam_pipe->iovec_count;
if (sps_bam_pipe->iovec_count == QCE_MAX_NUM_DSCR) {
pr_err("Num of descrptor %d exceed max (%d)",
sps_bam_pipe->iovec_count, (uint32_t)QCE_MAX_NUM_DSCR);
return -ENOMEM;
}
if (len) {
iovec->size = len;
iovec->addr = addr;
iovec->flags = 0;
sps_bam_pipe->iovec_count++;
}
return 0;
}
static int _qce_sps_add_sg_data(struct qce_device *pce_dev,
struct scatterlist *sg_src, uint32_t nbytes,
struct sps_transfer *sps_bam_pipe)
{
uint32_t addr, data_cnt, len;
struct sps_iovec *iovec = sps_bam_pipe->iovec +
sps_bam_pipe->iovec_count;
while (nbytes > 0) {
len = min(nbytes, sg_dma_len(sg_src));
nbytes -= len;
addr = sg_dma_address(sg_src);
if (pce_dev->ce_sps.minor_version == 0)
len = ALIGN(len, pce_dev->ce_sps.ce_burst_size);
while (len > 0) {
if (sps_bam_pipe->iovec_count == QCE_MAX_NUM_DSCR) {
pr_err("Num of descrptor %d exceed max (%d)",
sps_bam_pipe->iovec_count,
(uint32_t)QCE_MAX_NUM_DSCR);
return -ENOMEM;
}
if (len > SPS_MAX_PKT_SIZE) {
data_cnt = SPS_MAX_PKT_SIZE;
iovec->size = data_cnt;
iovec->addr = addr;
iovec->flags = 0;
} else {
data_cnt = len;
iovec->size = data_cnt;
iovec->addr = addr;
iovec->flags = 0;
}
iovec++;
sps_bam_pipe->iovec_count++;
addr += data_cnt;
len -= data_cnt;
}
sg_src = scatterwalk_sg_next(sg_src);
}
return 0;
}
static int _qce_sps_add_cmd(struct qce_device *pce_dev, uint32_t flag,
struct qce_cmdlist_info *cmdptr,
struct sps_transfer *sps_bam_pipe)
{
struct sps_iovec *iovec = sps_bam_pipe->iovec +
sps_bam_pipe->iovec_count;
iovec->size = cmdptr->size;
iovec->addr = GET_PHYS_ADDR(cmdptr->cmdlist);
iovec->flags = SPS_IOVEC_FLAG_CMD | flag;
sps_bam_pipe->iovec_count++;
return 0;
}
static int _qce_sps_transfer(struct qce_device *pce_dev)
{
int rc = 0;
_qce_dump_descr_fifos(pce_dev);
rc = sps_transfer(pce_dev->ce_sps.consumer.pipe,
&pce_dev->ce_sps.in_transfer);
if (rc) {
pr_err("sps_xfr() fail (consumer pipe=0x%x) rc = %d,",
(u32)pce_dev->ce_sps.consumer.pipe, rc);
_qce_dump_descr_fifos_fail(pce_dev);
return rc;
}
rc = sps_transfer(pce_dev->ce_sps.producer.pipe,
&pce_dev->ce_sps.out_transfer);
if (rc) {
pr_err("sps_xfr() fail (producer pipe=0x%x) rc = %d,",
(u32)pce_dev->ce_sps.producer.pipe, rc);
return rc;
}
return rc;
}
/**
* Allocate and Connect a CE peripheral's SPS endpoint
*
* This function allocates endpoint context and
* connect it with memory endpoint by calling
* appropriate SPS driver APIs.
*
* Also registers a SPS callback function with
* SPS driver
*
* This function should only be called once typically
* during driver probe.
*
* @pce_dev - Pointer to qce_device structure
* @ep - Pointer to sps endpoint data structure
* @is_produce - 1 means Producer endpoint
* 0 means Consumer endpoint
*
* @return - 0 if successful else negative value.
*
*/
static int qce_sps_init_ep_conn(struct qce_device *pce_dev,
struct qce_sps_ep_conn_data *ep,
bool is_producer)
{
int rc = 0;
struct sps_pipe *sps_pipe_info;
struct sps_connect *sps_connect_info = &ep->connect;
struct sps_register_event *sps_event = &ep->event;
/* Allocate endpoint context */
sps_pipe_info = sps_alloc_endpoint();
if (!sps_pipe_info) {
pr_err("sps_alloc_endpoint() failed!!! is_producer=%d",
is_producer);
rc = -ENOMEM;
goto out;
}
/* Now save the sps pipe handle */
ep->pipe = sps_pipe_info;
/* Get default connection configuration for an endpoint */
rc = sps_get_config(sps_pipe_info, sps_connect_info);
if (rc) {
pr_err("sps_get_config() fail pipe_handle=0x%x, rc = %d\n",
(u32)sps_pipe_info, rc);
goto get_config_err;
}
/* Modify the default connection configuration */
if (is_producer) {
/*
* For CE producer transfer, source should be
* CE peripheral where as destination should
* be system memory.
*/
sps_connect_info->source = pce_dev->ce_sps.bam_handle;
sps_connect_info->destination = SPS_DEV_HANDLE_MEM;
/* Producer pipe will handle this connection */
sps_connect_info->mode = SPS_MODE_SRC;
sps_connect_info->options =
SPS_O_AUTO_ENABLE | SPS_O_DESC_DONE;
} else {
/* For CE consumer transfer, source should be
* system memory where as destination should
* CE peripheral
*/
sps_connect_info->source = SPS_DEV_HANDLE_MEM;
sps_connect_info->destination = pce_dev->ce_sps.bam_handle;
sps_connect_info->mode = SPS_MODE_DEST;
sps_connect_info->options =
SPS_O_AUTO_ENABLE | SPS_O_EOT;
}
/* Producer pipe index */
sps_connect_info->src_pipe_index = pce_dev->ce_sps.src_pipe_index;
/* Consumer pipe index */
sps_connect_info->dest_pipe_index = pce_dev->ce_sps.dest_pipe_index;
/* Set pipe group */
sps_connect_info->lock_group = pce_dev->ce_sps.pipe_pair_index;
sps_connect_info->event_thresh = 0x10;
/*
* Max. no of scatter/gather buffers that can
* be passed by block layer = 32 (NR_SG).
* Each BAM descritor needs 64 bits (8 bytes).
* One BAM descriptor is required per buffer transfer.
* So we would require total 256 (32 * 8) bytes of descriptor FIFO.
* But due to HW limitation we need to allocate atleast one extra
* descriptor memory (256 bytes + 8 bytes). But in order to be
* in power of 2, we are allocating 512 bytes of memory.
*/
sps_connect_info->desc.size = QCE_MAX_NUM_DSCR *
sizeof(struct sps_iovec);
sps_connect_info->desc.base = dma_alloc_coherent(pce_dev->pdev,
sps_connect_info->desc.size,
&sps_connect_info->desc.phys_base,
GFP_KERNEL);
if (sps_connect_info->desc.base == NULL) {
rc = -ENOMEM;
pr_err("Can not allocate coherent memory for sps data\n");
goto get_config_err;
}
memset(sps_connect_info->desc.base, 0x00, sps_connect_info->desc.size);
/* Establish connection between peripheral and memory endpoint */
rc = sps_connect(sps_pipe_info, sps_connect_info);
if (rc) {
pr_err("sps_connect() fail pipe_handle=0x%x, rc = %d\n",
(u32)sps_pipe_info, rc);
goto sps_connect_err;
}
sps_event->mode = SPS_TRIGGER_CALLBACK;
if (is_producer)
sps_event->options = SPS_O_EOT | SPS_O_DESC_DONE;
else
sps_event->options = SPS_O_EOT;
sps_event->xfer_done = NULL;
sps_event->user = (void *)pce_dev;
pr_debug("success, %s : pipe_handle=0x%x, desc fifo base (phy) = 0x%x\n",
is_producer ? "PRODUCER(RX/OUT)" : "CONSUMER(TX/IN)",
(u32)sps_pipe_info, sps_connect_info->desc.phys_base);
goto out;
sps_connect_err:
dma_free_coherent(pce_dev->pdev,
sps_connect_info->desc.size,
sps_connect_info->desc.base,
sps_connect_info->desc.phys_base);
get_config_err:
sps_free_endpoint(sps_pipe_info);
out:
return rc;
}
/**
* Disconnect and Deallocate a CE peripheral's SPS endpoint
*
* This function disconnect endpoint and deallocates
* endpoint context.
*
* This function should only be called once typically
* during driver remove.
*
* @pce_dev - Pointer to qce_device structure
* @ep - Pointer to sps endpoint data structure
*
*/
static void qce_sps_exit_ep_conn(struct qce_device *pce_dev,
struct qce_sps_ep_conn_data *ep)
{
struct sps_pipe *sps_pipe_info = ep->pipe;
struct sps_connect *sps_connect_info = &ep->connect;
sps_disconnect(sps_pipe_info);
dma_free_coherent(pce_dev->pdev,
sps_connect_info->desc.size,
sps_connect_info->desc.base,
sps_connect_info->desc.phys_base);
sps_free_endpoint(sps_pipe_info);
}
/**
* Initialize SPS HW connected with CE core
*
* This function register BAM HW resources with
* SPS driver and then initialize 2 SPS endpoints
*
* This function should only be called once typically
* during driver probe.
*
* @pce_dev - Pointer to qce_device structure
*
* @return - 0 if successful else negative value.
*
*/
static int qce_sps_init(struct qce_device *pce_dev)
{
int rc = 0;
struct sps_bam_props bam = {0};
bool register_bam = false;
bam.phys_addr = pce_dev->ce_sps.bam_mem;
bam.virt_addr = pce_dev->ce_sps.bam_iobase;
/*
* This event thresold value is only significant for BAM-to-BAM
* transfer. It's ignored for BAM-to-System mode transfer.
*/
bam.event_threshold = 0x10; /* Pipe event threshold */
/*
* This threshold controls when the BAM publish
* the descriptor size on the sideband interface.
* SPS HW will only be used when
* data transfer size > 64 bytes.
*/
bam.summing_threshold = 64;
/* SPS driver wll handle the crypto BAM IRQ */
bam.irq = (u32)pce_dev->ce_sps.bam_irq;
/*
* Set flag to indicate BAM global device control is managed
* remotely.
*/
if ((pce_dev->support_cmd_dscr == false) || (pce_dev->is_shared))
bam.manage = SPS_BAM_MGR_DEVICE_REMOTE;
else
bam.manage = SPS_BAM_MGR_LOCAL;
bam.ee = 1;
pr_debug("bam physical base=0x%x\n", (u32)bam.phys_addr);
pr_debug("bam virtual base=0x%x\n", (u32)bam.virt_addr);
mutex_lock(&bam_register_cnt);
if (ce_bam_registered == false) {
bam_registry.handle = 0;
bam_registry.cnt = 0;
}
if ((bam_registry.handle == 0) && (bam_registry.cnt == 0)) {
/* Register CE Peripheral BAM device to SPS driver */
rc = sps_register_bam_device(&bam, &bam_registry.handle);
if (rc) {
mutex_unlock(&bam_register_cnt);
pr_err("sps_register_bam_device() failed! err=%d", rc);
return -EIO;
}
bam_registry.cnt++;
register_bam = true;
ce_bam_registered = true;
} else {
bam_registry.cnt++;
}
mutex_unlock(&bam_register_cnt);
pce_dev->ce_sps.bam_handle = bam_registry.handle;
pr_debug("BAM device registered. bam_handle=0x%x",
pce_dev->ce_sps.bam_handle);
rc = qce_sps_init_ep_conn(pce_dev, &pce_dev->ce_sps.producer, true);
if (rc)
goto sps_connect_producer_err;
rc = qce_sps_init_ep_conn(pce_dev, &pce_dev->ce_sps.consumer, false);
if (rc)
goto sps_connect_consumer_err;
pce_dev->ce_sps.out_transfer.user = pce_dev->ce_sps.producer.pipe;
pce_dev->ce_sps.in_transfer.user = pce_dev->ce_sps.consumer.pipe;
pr_info(" Qualcomm MSM CE-BAM at 0x%016llx irq %d\n",
(unsigned long long)pce_dev->ce_sps.bam_mem,
(unsigned int)pce_dev->ce_sps.bam_irq);
return rc;
sps_connect_consumer_err:
qce_sps_exit_ep_conn(pce_dev, &pce_dev->ce_sps.producer);
sps_connect_producer_err:
if (register_bam) {
mutex_lock(&bam_register_cnt);
sps_deregister_bam_device(pce_dev->ce_sps.bam_handle);
ce_bam_registered = false;
bam_registry.handle = 0;
bam_registry.cnt = 0;
mutex_unlock(&bam_register_cnt);
}
return rc;
}
/**
* De-initialize SPS HW connected with CE core
*
* This function deinitialize SPS endpoints and then
* deregisters BAM resources from SPS driver.
*
* This function should only be called once typically
* during driver remove.
*
* @pce_dev - Pointer to qce_device structure
*
*/
static void qce_sps_exit(struct qce_device *pce_dev)
{
qce_sps_exit_ep_conn(pce_dev, &pce_dev->ce_sps.consumer);
qce_sps_exit_ep_conn(pce_dev, &pce_dev->ce_sps.producer);
mutex_lock(&bam_register_cnt);
if ((bam_registry.handle != 0) && (bam_registry.cnt == 1)) {
sps_deregister_bam_device(pce_dev->ce_sps.bam_handle);
bam_registry.cnt = 0;
bam_registry.handle = 0;
}
if ((bam_registry.handle != 0) && (bam_registry.cnt > 1))
bam_registry.cnt--;
mutex_unlock(&bam_register_cnt);
iounmap(pce_dev->ce_sps.bam_iobase);
}
static void _aead_sps_producer_callback(struct sps_event_notify *notify)
{
struct qce_device *pce_dev = (struct qce_device *)
((struct sps_event_notify *)notify)->user;
pce_dev->ce_sps.notify = *notify;
pr_debug("sps ev_id=%d, addr=0x%x, size=0x%x, flags=0x%x\n",
notify->event_id,
notify->data.transfer.iovec.addr,
notify->data.transfer.iovec.size,
notify->data.transfer.iovec.flags);
if (pce_dev->ce_sps.producer_state == QCE_PIPE_STATE_COMP) {
pce_dev->ce_sps.producer_state = QCE_PIPE_STATE_IDLE;
/* done */
_aead_complete(pce_dev);
} else {
int rc = 0;
pce_dev->ce_sps.producer_state = QCE_PIPE_STATE_COMP;
pce_dev->ce_sps.out_transfer.iovec_count = 0;
_qce_sps_add_data(GET_PHYS_ADDR(pce_dev->ce_sps.result_dump),
CRYPTO_RESULT_DUMP_SIZE,
&pce_dev->ce_sps.out_transfer);
_qce_set_flag(&pce_dev->ce_sps.out_transfer,
SPS_IOVEC_FLAG_INT);
rc = sps_transfer(pce_dev->ce_sps.producer.pipe,
&pce_dev->ce_sps.out_transfer);
if (rc) {
pr_err("sps_xfr() fail (producer pipe=0x%x) rc = %d,",
(u32)pce_dev->ce_sps.producer.pipe, rc);
}
}
};
static void _sha_sps_producer_callback(struct sps_event_notify *notify)
{
struct qce_device *pce_dev = (struct qce_device *)
((struct sps_event_notify *)notify)->user;
pce_dev->ce_sps.notify = *notify;
pr_debug("sps ev_id=%d, addr=0x%x, size=0x%x, flags=0x%x\n",
notify->event_id,
notify->data.transfer.iovec.addr,
notify->data.transfer.iovec.size,
notify->data.transfer.iovec.flags);
/* done */
_sha_complete(pce_dev);
};
static void _ablk_cipher_sps_producer_callback(struct sps_event_notify *notify)
{
struct qce_device *pce_dev = (struct qce_device *)
((struct sps_event_notify *)notify)->user;
pce_dev->ce_sps.notify = *notify;
pr_debug("sps ev_id=%d, addr=0x%x, size=0x%x, flags=0x%x\n",
notify->event_id,
notify->data.transfer.iovec.addr,
notify->data.transfer.iovec.size,
notify->data.transfer.iovec.flags);
if (pce_dev->ce_sps.producer_state == QCE_PIPE_STATE_COMP) {
pce_dev->ce_sps.producer_state = QCE_PIPE_STATE_IDLE;
/* done */
_ablk_cipher_complete(pce_dev);
} else {
int rc = 0;
pce_dev->ce_sps.producer_state = QCE_PIPE_STATE_COMP;
pce_dev->ce_sps.out_transfer.iovec_count = 0;
_qce_sps_add_data(GET_PHYS_ADDR(pce_dev->ce_sps.result_dump),
CRYPTO_RESULT_DUMP_SIZE,
&pce_dev->ce_sps.out_transfer);
_qce_set_flag(&pce_dev->ce_sps.out_transfer,
SPS_IOVEC_FLAG_INT);
rc = sps_transfer(pce_dev->ce_sps.producer.pipe,
&pce_dev->ce_sps.out_transfer);
if (rc) {
pr_err("sps_xfr() fail (producer pipe=0x%x) rc = %d,",
(u32)pce_dev->ce_sps.producer.pipe, rc);
}
}
};
static void qce_add_cmd_element(struct qce_device *pdev,
struct sps_command_element **cmd_ptr, u32 addr,
u32 data, struct sps_command_element **populate)
{
(*cmd_ptr)->addr = (uint32_t)(addr + pdev->phy_iobase);
(*cmd_ptr)->data = data;
(*cmd_ptr)->mask = 0xFFFFFFFF;
if (populate != NULL)
*populate = *cmd_ptr;
(*cmd_ptr)++ ;
}
static int _setup_cipher_aes_cmdlistptrs(struct qce_device *pdev,
unsigned char **pvaddr, enum qce_cipher_mode_enum mode,
bool key_128)
{
struct sps_command_element *ce_vaddr;
uint32_t ce_vaddr_start;
struct qce_cmdlistptr_ops *cmdlistptr = &pdev->ce_sps.cmdlistptr;
struct qce_cmdlist_info *pcl_info = NULL;
int i = 0;
uint32_t encr_cfg = 0;
uint32_t key_reg = 0;
uint32_t xts_key_reg = 0;
uint32_t iv_reg = 0;
*pvaddr = (unsigned char *) ALIGN(((unsigned int)(*pvaddr)),
pdev->ce_sps.ce_burst_size);
ce_vaddr = (struct sps_command_element *)(*pvaddr);
ce_vaddr_start = (uint32_t)(*pvaddr);
/*
* Designate chunks of the allocated memory to various
* command list pointers related to AES cipher operations defined
* in ce_cmdlistptrs_ops structure.
*/
switch (mode) {
case QCE_MODE_CBC:
case QCE_MODE_CTR:
if (key_128 == true) {
cmdlistptr->cipher_aes_128_cbc_ctr.cmdlist =
(uint32_t)ce_vaddr;
pcl_info = &(cmdlistptr->cipher_aes_128_cbc_ctr);
if (mode == QCE_MODE_CBC)
encr_cfg = pdev->reg.encr_cfg_aes_cbc_128;
else
encr_cfg = pdev->reg.encr_cfg_aes_ctr_128;
iv_reg = 4;
key_reg = 4;
xts_key_reg = 0;
} else {
cmdlistptr->cipher_aes_256_cbc_ctr.cmdlist =
(uint32_t)ce_vaddr;
pcl_info = &(cmdlistptr->cipher_aes_256_cbc_ctr);
if (mode == QCE_MODE_CBC)
encr_cfg = pdev->reg.encr_cfg_aes_cbc_256;
else
encr_cfg = pdev->reg.encr_cfg_aes_ctr_256;
iv_reg = 4;
key_reg = 8;
xts_key_reg = 0;
}
break;
case QCE_MODE_ECB:
if (key_128 == true) {
cmdlistptr->cipher_aes_128_ecb.cmdlist =
(uint32_t)ce_vaddr;
pcl_info = &(cmdlistptr->cipher_aes_128_ecb);
encr_cfg = pdev->reg.encr_cfg_aes_ecb_128;
iv_reg = 0;
key_reg = 4;
xts_key_reg = 0;
} else {
cmdlistptr->cipher_aes_256_ecb.cmdlist =
(uint32_t)ce_vaddr;
pcl_info = &(cmdlistptr->cipher_aes_256_ecb);
encr_cfg = pdev->reg.encr_cfg_aes_ecb_256;
iv_reg = 0;
key_reg = 8;
xts_key_reg = 0;
}
break;
case QCE_MODE_XTS:
if (key_128 == true) {
cmdlistptr->cipher_aes_128_xts.cmdlist =
(uint32_t)ce_vaddr;
pcl_info = &(cmdlistptr->cipher_aes_128_xts);
encr_cfg = pdev->reg.encr_cfg_aes_xts_128;
iv_reg = 4;
key_reg = 4;
xts_key_reg = 4;
} else {
cmdlistptr->cipher_aes_256_xts.cmdlist =
(uint32_t)ce_vaddr;
pcl_info = &(cmdlistptr->cipher_aes_256_xts);
encr_cfg = pdev->reg.encr_cfg_aes_xts_256;
iv_reg = 4;
key_reg = 8;
xts_key_reg = 8;
}
break;
default:
pr_err("Unknown mode of operation %d received, exiting now\n",
mode);
return -EINVAL;
break;
}
/* clear status register */
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_STATUS_REG, 0, NULL);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_CONFIG_REG,
pdev->reg.crypto_cfg_be, &pcl_info->crypto_cfg);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_SEG_SIZE_REG, 0,
&pcl_info->seg_size);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_ENCR_SEG_CFG_REG, encr_cfg,
&pcl_info->encr_seg_cfg);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_ENCR_SEG_SIZE_REG, 0,
&pcl_info->encr_seg_size);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_ENCR_SEG_START_REG, 0,
&pcl_info->encr_seg_start);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_CNTR_MASK_REG,
(uint32_t)0xffffffff, &pcl_info->encr_mask);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_AUTH_SEG_CFG_REG, 0,
&pcl_info->auth_seg_cfg);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_ENCR_KEY0_REG, 0,
&pcl_info->encr_key);
for (i = 1; i < key_reg; i++)
qce_add_cmd_element(pdev, &ce_vaddr,
(CRYPTO_ENCR_KEY0_REG + i * sizeof(uint32_t)),
0, NULL);
if (xts_key_reg) {
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_ENCR_XTS_KEY0_REG,
0, &pcl_info->encr_xts_key);
for (i = 1; i < xts_key_reg; i++)
qce_add_cmd_element(pdev, &ce_vaddr,
(CRYPTO_ENCR_XTS_KEY0_REG +
i * sizeof(uint32_t)), 0, NULL);
qce_add_cmd_element(pdev, &ce_vaddr,
CRYPTO_ENCR_XTS_DU_SIZE_REG, 0,
&pcl_info->encr_xts_du_size);
}
if (iv_reg) {
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_CNTR0_IV0_REG, 0,
&pcl_info->encr_cntr_iv);
for (i = 1; i < iv_reg; i++)
qce_add_cmd_element(pdev, &ce_vaddr,
(CRYPTO_CNTR0_IV0_REG + i * sizeof(uint32_t)),
0, NULL);
}
/* Add dummy to align size to burst-size multiple */
if (mode == QCE_MODE_XTS) {
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_AUTH_SEG_SIZE_REG,
0, &pcl_info->auth_seg_size);
} else {
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_AUTH_SEG_SIZE_REG,
0, &pcl_info->auth_seg_size);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_AUTH_SEG_START_REG,
0, &pcl_info->auth_seg_size);
}
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_CONFIG_REG,
pdev->reg.crypto_cfg_le, NULL);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_GOPROC_REG,
((1 << CRYPTO_GO) | (1 << CRYPTO_RESULTS_DUMP)),
&pcl_info->go_proc);
pcl_info->size = (uint32_t)ce_vaddr - (uint32_t)ce_vaddr_start;
*pvaddr = (unsigned char *) ce_vaddr;
return 0;
}
static int _setup_cipher_des_cmdlistptrs(struct qce_device *pdev,
unsigned char **pvaddr, enum qce_cipher_alg_enum alg,
bool mode_cbc)
{
struct sps_command_element *ce_vaddr;
uint32_t ce_vaddr_start;
struct qce_cmdlistptr_ops *cmdlistptr = &pdev->ce_sps.cmdlistptr;
struct qce_cmdlist_info *pcl_info = NULL;
int i = 0;
uint32_t encr_cfg = 0;
uint32_t key_reg = 0;
uint32_t iv_reg = 0;
*pvaddr = (unsigned char *) ALIGN(((unsigned int)(*pvaddr)),
pdev->ce_sps.ce_burst_size);
ce_vaddr = (struct sps_command_element *)(*pvaddr);
ce_vaddr_start = (uint32_t)(*pvaddr);
/*
* Designate chunks of the allocated memory to various
* command list pointers related to cipher operations defined
* in ce_cmdlistptrs_ops structure.
*/
switch (alg) {
case CIPHER_ALG_DES:
if (mode_cbc) {
cmdlistptr->cipher_des_cbc.cmdlist =
(uint32_t)ce_vaddr;
pcl_info = &(cmdlistptr->cipher_des_cbc);
encr_cfg = pdev->reg.encr_cfg_des_cbc;
iv_reg = 2;
key_reg = 2;
} else {
cmdlistptr->cipher_des_ecb.cmdlist =
(uint32_t)ce_vaddr;
pcl_info = &(cmdlistptr->cipher_des_ecb);
encr_cfg = pdev->reg.encr_cfg_des_ecb;
iv_reg = 0;
key_reg = 2;
}
break;
case CIPHER_ALG_3DES:
if (mode_cbc) {
cmdlistptr->cipher_3des_cbc.cmdlist =
(uint32_t)ce_vaddr;
pcl_info = &(cmdlistptr->cipher_3des_cbc);
encr_cfg = pdev->reg.encr_cfg_3des_cbc;
iv_reg = 2;
key_reg = 6;
} else {
cmdlistptr->cipher_3des_ecb.cmdlist =
(uint32_t)ce_vaddr;
pcl_info = &(cmdlistptr->cipher_3des_ecb);
encr_cfg = pdev->reg.encr_cfg_3des_ecb;
iv_reg = 0;
key_reg = 6;
}
break;
default:
pr_err("Unknown algorithms %d received, exiting now\n", alg);
return -EINVAL;
break;
}
/* clear status register */
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_STATUS_REG, 0, NULL);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_CONFIG_REG,
pdev->reg.crypto_cfg_be, &pcl_info->crypto_cfg);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_SEG_SIZE_REG, 0,
&pcl_info->seg_size);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_ENCR_SEG_CFG_REG, encr_cfg,
&pcl_info->encr_seg_cfg);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_ENCR_SEG_SIZE_REG, 0,
&pcl_info->encr_seg_size);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_ENCR_SEG_START_REG, 0,
&pcl_info->encr_seg_start);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_AUTH_SEG_CFG_REG, 0,
&pcl_info->auth_seg_cfg);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_ENCR_KEY0_REG, 0,
&pcl_info->encr_key);
for (i = 1; i < key_reg; i++)
qce_add_cmd_element(pdev, &ce_vaddr,
(CRYPTO_ENCR_KEY0_REG + i * sizeof(uint32_t)),
0, NULL);
if (iv_reg) {
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_CNTR0_IV0_REG, 0,
&pcl_info->encr_cntr_iv);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_CNTR1_IV1_REG, 0,
NULL);
}
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_CONFIG_REG,
pdev->reg.crypto_cfg_le, NULL);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_GOPROC_REG,
((1 << CRYPTO_GO) | (1 << CRYPTO_RESULTS_DUMP)),
&pcl_info->go_proc);
pcl_info->size = (uint32_t)ce_vaddr - (uint32_t)ce_vaddr_start;
*pvaddr = (unsigned char *) ce_vaddr;
return 0;
}
static int _setup_auth_cmdlistptrs(struct qce_device *pdev,
unsigned char **pvaddr, enum qce_hash_alg_enum alg,
bool key_128)
{
struct sps_command_element *ce_vaddr;
uint32_t ce_vaddr_start;
struct qce_cmdlistptr_ops *cmdlistptr = &pdev->ce_sps.cmdlistptr;
struct qce_cmdlist_info *pcl_info = NULL;
int i = 0;
uint32_t key_reg = 0;
uint32_t auth_cfg = 0;
uint32_t iv_reg = 0;
*pvaddr = (unsigned char *) ALIGN(((unsigned int)(*pvaddr)),
pdev->ce_sps.ce_burst_size);
ce_vaddr_start = (uint32_t)(*pvaddr);
ce_vaddr = (struct sps_command_element *)(*pvaddr);
/*
* Designate chunks of the allocated memory to various
* command list pointers related to authentication operations
* defined in ce_cmdlistptrs_ops structure.
*/
switch (alg) {
case QCE_HASH_SHA1:
cmdlistptr->auth_sha1.cmdlist = (uint32_t)ce_vaddr;
pcl_info = &(cmdlistptr->auth_sha1);
auth_cfg = pdev->reg.auth_cfg_sha1;
iv_reg = 5;
/* clear status register */
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_STATUS_REG,
0, NULL);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_CONFIG_REG,
pdev->reg.crypto_cfg_be, &pcl_info->crypto_cfg);
break;
case QCE_HASH_SHA256:
cmdlistptr->auth_sha256.cmdlist = (uint32_t)ce_vaddr;
pcl_info = &(cmdlistptr->auth_sha256);
auth_cfg = pdev->reg.auth_cfg_sha256;
iv_reg = 8;
/* clear status register */
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_STATUS_REG,
0, NULL);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_CONFIG_REG,
pdev->reg.crypto_cfg_be, &pcl_info->crypto_cfg);
/* 1 dummy write */
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_ENCR_SEG_SIZE_REG,
0, NULL);
break;
case QCE_HASH_SHA1_HMAC:
cmdlistptr->auth_sha1_hmac.cmdlist = (uint32_t)ce_vaddr;
pcl_info = &(cmdlistptr->auth_sha1_hmac);
auth_cfg = pdev->reg.auth_cfg_hmac_sha1;
key_reg = 16;
iv_reg = 5;
/* clear status register */
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_STATUS_REG,
0, NULL);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_CONFIG_REG,
pdev->reg.crypto_cfg_be, &pcl_info->crypto_cfg);
break;
case QCE_HASH_SHA256_HMAC:
cmdlistptr->auth_sha256_hmac.cmdlist = (uint32_t)ce_vaddr;
pcl_info = &(cmdlistptr->auth_sha256_hmac);
auth_cfg = pdev->reg.auth_cfg_hmac_sha256;
key_reg = 16;
iv_reg = 8;
/* clear status register */
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_STATUS_REG, 0,
NULL);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_CONFIG_REG,
pdev->reg.crypto_cfg_be, &pcl_info->crypto_cfg);
/* 1 dummy write */
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_ENCR_SEG_SIZE_REG,
0, NULL);
break;
case QCE_HASH_AES_CMAC:
if (key_128 == true) {
cmdlistptr->auth_aes_128_cmac.cmdlist =
(uint32_t)ce_vaddr;
pcl_info = &(cmdlistptr->auth_aes_128_cmac);
auth_cfg = pdev->reg.auth_cfg_cmac_128;
key_reg = 4;
} else {
cmdlistptr->auth_aes_256_cmac.cmdlist =
(uint32_t)ce_vaddr;
pcl_info = &(cmdlistptr->auth_aes_256_cmac);
auth_cfg = pdev->reg.auth_cfg_cmac_256;
key_reg = 8;
}
/* clear status register */
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_STATUS_REG, 0,
NULL);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_CONFIG_REG,
pdev->reg.crypto_cfg_be, &pcl_info->crypto_cfg);
/* 1 dummy write */
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_ENCR_SEG_SIZE_REG,
0, NULL);
break;
default:
pr_err("Unknown algorithms %d received, exiting now\n", alg);
return -EINVAL;
break;
}
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_SEG_SIZE_REG, 0,
&pcl_info->seg_size);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_ENCR_SEG_CFG_REG, 0,
&pcl_info->encr_seg_cfg);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_AUTH_SEG_CFG_REG,
auth_cfg, &pcl_info->auth_seg_cfg);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_AUTH_SEG_SIZE_REG, 0,
&pcl_info->auth_seg_size);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_AUTH_SEG_START_REG, 0,
&pcl_info->auth_seg_start);
if (alg == QCE_HASH_AES_CMAC) {
/* reset auth iv, bytecount and key registers */
for (i = 0; i < 16; i++)
qce_add_cmd_element(pdev, &ce_vaddr,
(CRYPTO_AUTH_IV0_REG + i * sizeof(uint32_t)),
0, NULL);
for (i = 0; i < 16; i++)
qce_add_cmd_element(pdev, &ce_vaddr,
(CRYPTO_AUTH_KEY0_REG + i*sizeof(uint32_t)),
0, NULL);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_AUTH_BYTECNT0_REG,
0, NULL);
} else {
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_AUTH_IV0_REG, 0,
&pcl_info->auth_iv);
for (i = 1; i < iv_reg; i++)
qce_add_cmd_element(pdev, &ce_vaddr,
(CRYPTO_AUTH_IV0_REG + i*sizeof(uint32_t)),
0, NULL);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_AUTH_BYTECNT0_REG,
0, &pcl_info->auth_bytecount);
}
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_AUTH_BYTECNT1_REG, 0, NULL);
if (key_reg) {
qce_add_cmd_element(pdev, &ce_vaddr,
CRYPTO_AUTH_KEY0_REG, 0, &pcl_info->auth_key);
for (i = 1; i < key_reg; i++)
qce_add_cmd_element(pdev, &ce_vaddr,
(CRYPTO_AUTH_KEY0_REG + i*sizeof(uint32_t)),
0, NULL);
}
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_CONFIG_REG,
pdev->reg.crypto_cfg_le, NULL);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_GOPROC_REG,
((1 << CRYPTO_GO) | (1 << CRYPTO_RESULTS_DUMP)),
&pcl_info->go_proc);
pcl_info->size = (uint32_t)ce_vaddr - (uint32_t)ce_vaddr_start;
*pvaddr = (unsigned char *) ce_vaddr;
return 0;
}
static int _setup_aead_cmdlistptrs(struct qce_device *pdev,
unsigned char **pvaddr,
uint32_t alg,
uint32_t mode,
uint32_t key_size)
{
struct sps_command_element *ce_vaddr;
uint32_t ce_vaddr_start;
struct qce_cmdlistptr_ops *cmdlistptr = &pdev->ce_sps.cmdlistptr;
struct qce_cmdlist_info *pcl_info = NULL;
uint32_t key_reg;
uint32_t iv_reg;
uint32_t i;
uint32_t enciv_in_word;
uint32_t encr_cfg;
*pvaddr = (unsigned char *) ALIGN(((unsigned int)(*pvaddr)),
pdev->ce_sps.ce_burst_size);
ce_vaddr_start = (uint32_t)(*pvaddr);
ce_vaddr = (struct sps_command_element *)(*pvaddr);
switch (alg) {
case CIPHER_ALG_DES:
switch (mode) {
case QCE_MODE_ECB:
cmdlistptr->aead_hmac_sha1_ecb_des.cmdlist =
(uint32_t)ce_vaddr;
pcl_info = &(cmdlistptr->aead_hmac_sha1_ecb_des);
encr_cfg = pdev->reg.encr_cfg_des_ecb;
break;
case QCE_MODE_CBC:
cmdlistptr->aead_hmac_sha1_cbc_des.cmdlist =
(uint32_t)ce_vaddr;
pcl_info = &(cmdlistptr->aead_hmac_sha1_cbc_des);
encr_cfg = pdev->reg.encr_cfg_des_cbc;
break;
default:
return -EINVAL;
};
enciv_in_word = 2;
break;
case CIPHER_ALG_3DES:
switch (mode) {
case QCE_MODE_ECB:
cmdlistptr->aead_hmac_sha1_ecb_3des.cmdlist =
(uint32_t)ce_vaddr;
pcl_info = &(cmdlistptr->aead_hmac_sha1_ecb_3des);
encr_cfg = pdev->reg.encr_cfg_3des_ecb;
break;
case QCE_MODE_CBC:
cmdlistptr->aead_hmac_sha1_cbc_3des.cmdlist =
(uint32_t)ce_vaddr;
pcl_info = &(cmdlistptr->aead_hmac_sha1_cbc_3des);
encr_cfg = pdev->reg.encr_cfg_3des_cbc;
break;
default:
return -EINVAL;
};
enciv_in_word = 2;
break;
case CIPHER_ALG_AES:
switch (mode) {
case QCE_MODE_ECB:
if (key_size == AES128_KEY_SIZE) {
cmdlistptr->aead_hmac_sha1_ecb_aes_128.cmdlist =
(uint32_t)ce_vaddr;
pcl_info = &(cmdlistptr->
aead_hmac_sha1_ecb_aes_128);
encr_cfg = pdev->reg.encr_cfg_aes_ecb_128;
} else if (key_size == AES256_KEY_SIZE) {
cmdlistptr->aead_hmac_sha1_ecb_aes_256.cmdlist =
(uint32_t)ce_vaddr;
pcl_info = &(cmdlistptr->
aead_hmac_sha1_ecb_aes_256);
encr_cfg = pdev->reg.encr_cfg_aes_ecb_256;
} else {
return -EINVAL;
}
break;
case QCE_MODE_CBC:
if (key_size == AES128_KEY_SIZE) {
cmdlistptr->aead_hmac_sha1_cbc_aes_128.cmdlist =
(uint32_t)ce_vaddr;
pcl_info = &(cmdlistptr->
aead_hmac_sha1_cbc_aes_128);
encr_cfg = pdev->reg.encr_cfg_aes_cbc_128;
} else if (key_size == AES256_KEY_SIZE) {
cmdlistptr->aead_hmac_sha1_cbc_aes_256.cmdlist =
(uint32_t)ce_vaddr;
pcl_info = &(cmdlistptr->
aead_hmac_sha1_cbc_aes_256);
encr_cfg = pdev->reg.encr_cfg_aes_cbc_256;
} else {
return -EINVAL;
}
break;
default:
return -EINVAL;
};
enciv_in_word = 4;
break;
default:
return -EINVAL;
};
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_STATUS_REG, 0, NULL);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_CONFIG_REG,
pdev->reg.crypto_cfg_be, &pcl_info->crypto_cfg);
key_reg = key_size/sizeof(uint32_t);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_ENCR_KEY0_REG, 0,
&pcl_info->encr_key);
for (i = 1; i < key_reg; i++)
qce_add_cmd_element(pdev, &ce_vaddr,
(CRYPTO_ENCR_KEY0_REG + i * sizeof(uint32_t)),
0, NULL);
if (mode != QCE_MODE_ECB) {
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_CNTR0_IV0_REG, 0,
&pcl_info->encr_cntr_iv);
for (i = 1; i < enciv_in_word; i++)
qce_add_cmd_element(pdev, &ce_vaddr,
(CRYPTO_CNTR0_IV0_REG + i * sizeof(uint32_t)),
0, NULL);
};
iv_reg = 5;
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_AUTH_IV0_REG, 0,
&pcl_info->auth_iv);
for (i = 1; i < iv_reg; i++)
qce_add_cmd_element(pdev, &ce_vaddr,
(CRYPTO_AUTH_IV0_REG + i*sizeof(uint32_t)),
0, NULL);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_AUTH_BYTECNT0_REG,
0, &pcl_info->auth_bytecount);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_AUTH_BYTECNT1_REG, 0, NULL);
key_reg = SHA_HMAC_KEY_SIZE/sizeof(uint32_t);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_AUTH_KEY0_REG, 0,
&pcl_info->auth_key);
for (i = 1; i < key_reg; i++)
qce_add_cmd_element(pdev, &ce_vaddr,
(CRYPTO_AUTH_KEY0_REG + i*sizeof(uint32_t)), 0, NULL);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_SEG_SIZE_REG, 0,
&pcl_info->seg_size);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_ENCR_SEG_CFG_REG, encr_cfg,
&pcl_info->encr_seg_cfg);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_ENCR_SEG_SIZE_REG, 0,
&pcl_info->encr_seg_size);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_ENCR_SEG_START_REG, 0,
&pcl_info->encr_seg_start);
qce_add_cmd_element(
pdev,
&ce_vaddr,
CRYPTO_AUTH_SEG_CFG_REG,
pdev->reg.auth_cfg_aead_sha1_hmac,
&pcl_info->auth_seg_cfg);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_AUTH_SEG_SIZE_REG, 0,
&pcl_info->auth_seg_size);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_AUTH_SEG_START_REG, 0,
&pcl_info->auth_seg_start);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_CONFIG_REG,
pdev->reg.crypto_cfg_le, NULL);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_GOPROC_REG,
((1 << CRYPTO_GO) | (1 << CRYPTO_RESULTS_DUMP)),
&pcl_info->go_proc);
pcl_info->size = (uint32_t)ce_vaddr - (uint32_t)ce_vaddr_start;
*pvaddr = (unsigned char *) ce_vaddr;
return 0;
}
static int _setup_aead_ccm_cmdlistptrs(struct qce_device *pdev,
unsigned char **pvaddr, bool key_128)
{
struct sps_command_element *ce_vaddr;
uint32_t ce_vaddr_start;
struct qce_cmdlistptr_ops *cmdlistptr = &pdev->ce_sps.cmdlistptr;
struct qce_cmdlist_info *pcl_info = NULL;
int i = 0;
uint32_t encr_cfg = 0;
uint32_t auth_cfg = 0;
uint32_t key_reg = 0;
*pvaddr = (unsigned char *) ALIGN(((unsigned int)(*pvaddr)),
pdev->ce_sps.ce_burst_size);
ce_vaddr_start = (uint32_t)(*pvaddr);
ce_vaddr = (struct sps_command_element *)(*pvaddr);
/*
* Designate chunks of the allocated memory to various
* command list pointers related to aead operations
* defined in ce_cmdlistptrs_ops structure.
*/
if (key_128 == true) {
cmdlistptr->aead_aes_128_ccm.cmdlist = (uint32_t)ce_vaddr;
pcl_info = &(cmdlistptr->aead_aes_128_ccm);
auth_cfg = pdev->reg.auth_cfg_aes_ccm_128;
encr_cfg = pdev->reg.encr_cfg_aes_ccm_128;
key_reg = 4;
} else {
cmdlistptr->aead_aes_256_ccm.cmdlist = (uint32_t)ce_vaddr;
pcl_info = &(cmdlistptr->aead_aes_256_ccm);
auth_cfg = pdev->reg.auth_cfg_aes_ccm_256;
encr_cfg = pdev->reg.encr_cfg_aes_ccm_256;
key_reg = 8;
}
/* clear status register */
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_STATUS_REG, 0, NULL);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_CONFIG_REG,
pdev->reg.crypto_cfg_be, &pcl_info->crypto_cfg);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_ENCR_SEG_CFG_REG, 0, NULL);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_ENCR_SEG_START_REG, 0,
NULL);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_SEG_SIZE_REG, 0,
&pcl_info->seg_size);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_ENCR_SEG_CFG_REG,
encr_cfg, &pcl_info->encr_seg_cfg);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_ENCR_SEG_SIZE_REG, 0,
&pcl_info->encr_seg_size);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_ENCR_SEG_START_REG, 0,
&pcl_info->encr_seg_start);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_CNTR_MASK_REG,
(uint32_t)0xffffffff, &pcl_info->encr_mask);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_AUTH_SEG_CFG_REG,
auth_cfg, &pcl_info->auth_seg_cfg);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_AUTH_SEG_SIZE_REG, 0,
&pcl_info->auth_seg_size);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_AUTH_SEG_START_REG, 0,
&pcl_info->auth_seg_start);
/* reset auth iv, bytecount and key registers */
for (i = 0; i < 8; i++)
qce_add_cmd_element(pdev, &ce_vaddr,
(CRYPTO_AUTH_IV0_REG + i * sizeof(uint32_t)),
0, NULL);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_AUTH_BYTECNT0_REG,
0, NULL);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_AUTH_BYTECNT1_REG,
0, NULL);
for (i = 0; i < 16; i++)
qce_add_cmd_element(pdev, &ce_vaddr,
(CRYPTO_AUTH_KEY0_REG + i * sizeof(uint32_t)),
0, NULL);
/* set auth key */
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_AUTH_KEY0_REG, 0,
&pcl_info->auth_key);
for (i = 1; i < key_reg; i++)
qce_add_cmd_element(pdev, &ce_vaddr,
(CRYPTO_AUTH_KEY0_REG + i * sizeof(uint32_t)),
0, NULL);
/* set NONCE info */
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_AUTH_INFO_NONCE0_REG, 0,
&pcl_info->auth_nonce_info);
for (i = 1; i < 4; i++)
qce_add_cmd_element(pdev, &ce_vaddr,
(CRYPTO_AUTH_INFO_NONCE0_REG +
i * sizeof(uint32_t)), 0, NULL);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_ENCR_KEY0_REG, 0,
&pcl_info->encr_key);
for (i = 1; i < key_reg; i++)
qce_add_cmd_element(pdev, &ce_vaddr,
(CRYPTO_ENCR_KEY0_REG + i * sizeof(uint32_t)),
0, NULL);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_CNTR0_IV0_REG, 0,
&pcl_info->encr_cntr_iv);
for (i = 1; i < 4; i++)
qce_add_cmd_element(pdev, &ce_vaddr,
(CRYPTO_CNTR0_IV0_REG + i * sizeof(uint32_t)),
0, NULL);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_ENCR_CCM_INT_CNTR0_REG, 0,
&pcl_info->encr_ccm_cntr_iv);
for (i = 1; i < 4; i++)
qce_add_cmd_element(pdev, &ce_vaddr,
(CRYPTO_ENCR_CCM_INT_CNTR0_REG + i * sizeof(uint32_t)),
0, NULL);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_CONFIG_REG,
pdev->reg.crypto_cfg_le, NULL);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_GOPROC_REG,
((1 << CRYPTO_GO) | (1 << CRYPTO_RESULTS_DUMP)),
&pcl_info->go_proc);
pcl_info->size = (uint32_t)ce_vaddr - (uint32_t)ce_vaddr_start;
*pvaddr = (unsigned char *) ce_vaddr;
return 0;
}
static int _setup_unlock_pipe_cmdlistptrs(struct qce_device *pdev,
unsigned char **pvaddr)
{
struct sps_command_element *ce_vaddr;
uint32_t ce_vaddr_start = (uint32_t)(*pvaddr);
struct qce_cmdlistptr_ops *cmdlistptr = &pdev->ce_sps.cmdlistptr;
struct qce_cmdlist_info *pcl_info = NULL;
*pvaddr = (unsigned char *) ALIGN(((unsigned int)(*pvaddr)),
pdev->ce_sps.ce_burst_size);
ce_vaddr = (struct sps_command_element *)(*pvaddr);
cmdlistptr->unlock_all_pipes.cmdlist = (uint32_t)ce_vaddr;
pcl_info = &(cmdlistptr->unlock_all_pipes);
/*
* Designate chunks of the allocated memory to command list
* to unlock pipes.
*/
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_CONFIG_REG,
CRYPTO_CONFIG_RESET, NULL);
pcl_info->size = (uint32_t)ce_vaddr - (uint32_t)ce_vaddr_start;
*pvaddr = (unsigned char *) ce_vaddr;
return 0;
}
static int qce_setup_cmdlistptrs(struct qce_device *pdev,
unsigned char **pvaddr)
{
struct sps_command_element *ce_vaddr =
(struct sps_command_element *)(*pvaddr);
/*
* Designate chunks of the allocated memory to various
* command list pointers related to operations defined
* in ce_cmdlistptrs_ops structure.
*/
ce_vaddr =
(struct sps_command_element *) ALIGN(((unsigned int) ce_vaddr),
pdev->ce_sps.ce_burst_size);
*pvaddr = (unsigned char *) ce_vaddr;
_setup_cipher_aes_cmdlistptrs(pdev, pvaddr, QCE_MODE_CBC, true);
_setup_cipher_aes_cmdlistptrs(pdev, pvaddr, QCE_MODE_CTR, true);
_setup_cipher_aes_cmdlistptrs(pdev, pvaddr, QCE_MODE_ECB, true);
_setup_cipher_aes_cmdlistptrs(pdev, pvaddr, QCE_MODE_XTS, true);
_setup_cipher_aes_cmdlistptrs(pdev, pvaddr, QCE_MODE_CBC, false);
_setup_cipher_aes_cmdlistptrs(pdev, pvaddr, QCE_MODE_CTR, false);
_setup_cipher_aes_cmdlistptrs(pdev, pvaddr, QCE_MODE_ECB, false);
_setup_cipher_aes_cmdlistptrs(pdev, pvaddr, QCE_MODE_XTS, false);
_setup_cipher_des_cmdlistptrs(pdev, pvaddr, CIPHER_ALG_DES, true);
_setup_cipher_des_cmdlistptrs(pdev, pvaddr, CIPHER_ALG_DES, false);
_setup_cipher_des_cmdlistptrs(pdev, pvaddr, CIPHER_ALG_3DES, true);
_setup_cipher_des_cmdlistptrs(pdev, pvaddr, CIPHER_ALG_3DES, false);
_setup_auth_cmdlistptrs(pdev, pvaddr, QCE_HASH_SHA1, false);
_setup_auth_cmdlistptrs(pdev, pvaddr, QCE_HASH_SHA256, false);
_setup_auth_cmdlistptrs(pdev, pvaddr, QCE_HASH_SHA1_HMAC, false);
_setup_auth_cmdlistptrs(pdev, pvaddr, QCE_HASH_SHA256_HMAC, false);
_setup_auth_cmdlistptrs(pdev, pvaddr, QCE_HASH_AES_CMAC, true);
_setup_auth_cmdlistptrs(pdev, pvaddr, QCE_HASH_AES_CMAC, false);
_setup_aead_cmdlistptrs(pdev, pvaddr, CIPHER_ALG_DES, QCE_MODE_CBC,
DES_KEY_SIZE);
_setup_aead_cmdlistptrs(pdev, pvaddr, CIPHER_ALG_DES, QCE_MODE_ECB,
DES_KEY_SIZE);
_setup_aead_cmdlistptrs(pdev, pvaddr, CIPHER_ALG_3DES, QCE_MODE_CBC,
DES3_EDE_KEY_SIZE);
_setup_aead_cmdlistptrs(pdev, pvaddr, CIPHER_ALG_3DES, QCE_MODE_ECB,
DES3_EDE_KEY_SIZE);
_setup_aead_cmdlistptrs(pdev, pvaddr, CIPHER_ALG_AES, QCE_MODE_CBC,
AES128_KEY_SIZE);
_setup_aead_cmdlistptrs(pdev, pvaddr, CIPHER_ALG_AES, QCE_MODE_ECB,
AES128_KEY_SIZE);
_setup_aead_cmdlistptrs(pdev, pvaddr, CIPHER_ALG_AES, QCE_MODE_CBC,
AES256_KEY_SIZE);
_setup_aead_cmdlistptrs(pdev, pvaddr, CIPHER_ALG_AES, QCE_MODE_ECB,
AES256_KEY_SIZE);
_setup_aead_ccm_cmdlistptrs(pdev, pvaddr, true);
_setup_aead_ccm_cmdlistptrs(pdev, pvaddr, false);
_setup_unlock_pipe_cmdlistptrs(pdev, pvaddr);
return 0;
}
static int qce_setup_ce_sps_data(struct qce_device *pce_dev)
{
unsigned char *vaddr;
vaddr = pce_dev->coh_vmem;
vaddr = (unsigned char *) ALIGN(((unsigned int)vaddr),
pce_dev->ce_sps.ce_burst_size);
/* Allow for 256 descriptor (cmd and data) entries per pipe */
pce_dev->ce_sps.in_transfer.iovec = (struct sps_iovec *)vaddr;
pce_dev->ce_sps.in_transfer.iovec_phys =
(uint32_t)GET_PHYS_ADDR(vaddr);
vaddr += QCE_MAX_NUM_DSCR * sizeof(struct sps_iovec);
pce_dev->ce_sps.out_transfer.iovec = (struct sps_iovec *)vaddr;
pce_dev->ce_sps.out_transfer.iovec_phys =
(uint32_t)GET_PHYS_ADDR(vaddr);
vaddr += QCE_MAX_NUM_DSCR * sizeof(struct sps_iovec);
if (pce_dev->support_cmd_dscr)
qce_setup_cmdlistptrs(pce_dev, &vaddr);
vaddr = (unsigned char *) ALIGN(((unsigned int)vaddr),
pce_dev->ce_sps.ce_burst_size);
pce_dev->ce_sps.result_dump = (uint32_t)vaddr;
pce_dev->ce_sps.result = (struct ce_result_dump_format *)vaddr;
vaddr += CRYPTO_RESULT_DUMP_SIZE;
pce_dev->ce_sps.ignore_buffer = (uint32_t)vaddr;
vaddr += pce_dev->ce_sps.ce_burst_size * 2;
if ((vaddr - pce_dev->coh_vmem) > pce_dev->memsize)
panic("qce50: Not enough coherent memory. Allocate %x , need %x",
pce_dev->memsize, vaddr - pce_dev->coh_vmem);
return 0;
}
static int qce_init_ce_cfg_val(struct qce_device *pce_dev)
{
uint32_t beats = (pce_dev->ce_sps.ce_burst_size >> 3) - 1;
uint32_t pipe_pair = pce_dev->ce_sps.pipe_pair_index;
pce_dev->reg.crypto_cfg_be = (beats << CRYPTO_REQ_SIZE) |
BIT(CRYPTO_MASK_DOUT_INTR) | BIT(CRYPTO_MASK_DIN_INTR) |
BIT(CRYPTO_MASK_OP_DONE_INTR) | (0 << CRYPTO_HIGH_SPD_EN_N) |
(pipe_pair << CRYPTO_PIPE_SET_SELECT);
pce_dev->reg.crypto_cfg_le =
(pce_dev->reg.crypto_cfg_be | CRYPTO_LITTLE_ENDIAN_MASK);
/* Initialize encr_cfg register for AES alg */
pce_dev->reg.encr_cfg_aes_cbc_128 =
(CRYPTO_ENCR_KEY_SZ_AES128 << CRYPTO_ENCR_KEY_SZ) |
(CRYPTO_ENCR_ALG_AES << CRYPTO_ENCR_ALG) |
(CRYPTO_ENCR_MODE_CBC << CRYPTO_ENCR_MODE);
pce_dev->reg.encr_cfg_aes_cbc_256 =
(CRYPTO_ENCR_KEY_SZ_AES256 << CRYPTO_ENCR_KEY_SZ) |
(CRYPTO_ENCR_ALG_AES << CRYPTO_ENCR_ALG) |
(CRYPTO_ENCR_MODE_CBC << CRYPTO_ENCR_MODE);
pce_dev->reg.encr_cfg_aes_ctr_128 =
(CRYPTO_ENCR_KEY_SZ_AES128 << CRYPTO_ENCR_KEY_SZ) |
(CRYPTO_ENCR_ALG_AES << CRYPTO_ENCR_ALG) |
(CRYPTO_ENCR_MODE_CTR << CRYPTO_ENCR_MODE);
pce_dev->reg.encr_cfg_aes_ctr_256 =
(CRYPTO_ENCR_KEY_SZ_AES256 << CRYPTO_ENCR_KEY_SZ) |
(CRYPTO_ENCR_ALG_AES << CRYPTO_ENCR_ALG) |
(CRYPTO_ENCR_MODE_CTR << CRYPTO_ENCR_MODE);
pce_dev->reg.encr_cfg_aes_xts_128 =
(CRYPTO_ENCR_KEY_SZ_AES128 << CRYPTO_ENCR_KEY_SZ) |
(CRYPTO_ENCR_ALG_AES << CRYPTO_ENCR_ALG) |
(CRYPTO_ENCR_MODE_XTS << CRYPTO_ENCR_MODE);
pce_dev->reg.encr_cfg_aes_xts_256 =
(CRYPTO_ENCR_KEY_SZ_AES256 << CRYPTO_ENCR_KEY_SZ) |
(CRYPTO_ENCR_ALG_AES << CRYPTO_ENCR_ALG) |
(CRYPTO_ENCR_MODE_XTS << CRYPTO_ENCR_MODE);
pce_dev->reg.encr_cfg_aes_ecb_128 =
(CRYPTO_ENCR_KEY_SZ_AES128 << CRYPTO_ENCR_KEY_SZ) |
(CRYPTO_ENCR_ALG_AES << CRYPTO_ENCR_ALG) |
(CRYPTO_ENCR_MODE_ECB << CRYPTO_ENCR_MODE);
pce_dev->reg.encr_cfg_aes_ecb_256 =
(CRYPTO_ENCR_KEY_SZ_AES256 << CRYPTO_ENCR_KEY_SZ) |
(CRYPTO_ENCR_ALG_AES << CRYPTO_ENCR_ALG) |
(CRYPTO_ENCR_MODE_ECB << CRYPTO_ENCR_MODE);
pce_dev->reg.encr_cfg_aes_ccm_128 =
(CRYPTO_ENCR_KEY_SZ_AES128 << CRYPTO_ENCR_KEY_SZ) |
(CRYPTO_ENCR_ALG_AES << CRYPTO_ENCR_ALG) |
(CRYPTO_ENCR_MODE_CCM << CRYPTO_ENCR_MODE)|
(CRYPTO_LAST_CCM_XFR << CRYPTO_LAST_CCM);
pce_dev->reg.encr_cfg_aes_ccm_256 =
(CRYPTO_ENCR_KEY_SZ_AES256 << CRYPTO_ENCR_KEY_SZ) |
(CRYPTO_ENCR_ALG_AES << CRYPTO_ENCR_ALG) |
(CRYPTO_ENCR_MODE_CCM << CRYPTO_ENCR_MODE) |
(CRYPTO_LAST_CCM_XFR << CRYPTO_LAST_CCM);
/* Initialize encr_cfg register for DES alg */
pce_dev->reg.encr_cfg_des_ecb =
(CRYPTO_ENCR_KEY_SZ_DES << CRYPTO_ENCR_KEY_SZ) |
(CRYPTO_ENCR_ALG_DES << CRYPTO_ENCR_ALG) |
(CRYPTO_ENCR_MODE_ECB << CRYPTO_ENCR_MODE);
pce_dev->reg.encr_cfg_des_cbc =
(CRYPTO_ENCR_KEY_SZ_DES << CRYPTO_ENCR_KEY_SZ) |
(CRYPTO_ENCR_ALG_DES << CRYPTO_ENCR_ALG) |
(CRYPTO_ENCR_MODE_CBC << CRYPTO_ENCR_MODE);
pce_dev->reg.encr_cfg_3des_ecb =
(CRYPTO_ENCR_KEY_SZ_3DES << CRYPTO_ENCR_KEY_SZ) |
(CRYPTO_ENCR_ALG_DES << CRYPTO_ENCR_ALG) |
(CRYPTO_ENCR_MODE_ECB << CRYPTO_ENCR_MODE);
pce_dev->reg.encr_cfg_3des_cbc =
(CRYPTO_ENCR_KEY_SZ_3DES << CRYPTO_ENCR_KEY_SZ) |
(CRYPTO_ENCR_ALG_DES << CRYPTO_ENCR_ALG) |
(CRYPTO_ENCR_MODE_CBC << CRYPTO_ENCR_MODE);
/* Initialize auth_cfg register for CMAC alg */
pce_dev->reg.auth_cfg_cmac_128 =
(1 << CRYPTO_LAST) | (1 << CRYPTO_FIRST) |
(CRYPTO_AUTH_MODE_CMAC << CRYPTO_AUTH_MODE)|
(CRYPTO_AUTH_SIZE_ENUM_16_BYTES << CRYPTO_AUTH_SIZE) |
(CRYPTO_AUTH_ALG_AES << CRYPTO_AUTH_ALG) |
(CRYPTO_AUTH_KEY_SZ_AES128 << CRYPTO_AUTH_KEY_SIZE);
pce_dev->reg.auth_cfg_cmac_256 =
(1 << CRYPTO_LAST) | (1 << CRYPTO_FIRST) |
(CRYPTO_AUTH_MODE_CMAC << CRYPTO_AUTH_MODE)|
(CRYPTO_AUTH_SIZE_ENUM_16_BYTES << CRYPTO_AUTH_SIZE) |
(CRYPTO_AUTH_ALG_AES << CRYPTO_AUTH_ALG) |
(CRYPTO_AUTH_KEY_SZ_AES256 << CRYPTO_AUTH_KEY_SIZE);
/* Initialize auth_cfg register for HMAC alg */
pce_dev->reg.auth_cfg_hmac_sha1 =
(CRYPTO_AUTH_MODE_HMAC << CRYPTO_AUTH_MODE)|
(CRYPTO_AUTH_SIZE_SHA1 << CRYPTO_AUTH_SIZE) |
(CRYPTO_AUTH_ALG_SHA << CRYPTO_AUTH_ALG) |
(CRYPTO_AUTH_POS_BEFORE << CRYPTO_AUTH_POS);
pce_dev->reg.auth_cfg_hmac_sha256 =
(CRYPTO_AUTH_MODE_HMAC << CRYPTO_AUTH_MODE)|
(CRYPTO_AUTH_SIZE_SHA256 << CRYPTO_AUTH_SIZE) |
(CRYPTO_AUTH_ALG_SHA << CRYPTO_AUTH_ALG) |
(CRYPTO_AUTH_POS_BEFORE << CRYPTO_AUTH_POS);
/* Initialize auth_cfg register for SHA1/256 alg */
pce_dev->reg.auth_cfg_sha1 =
(CRYPTO_AUTH_MODE_HASH << CRYPTO_AUTH_MODE)|
(CRYPTO_AUTH_SIZE_SHA1 << CRYPTO_AUTH_SIZE) |
(CRYPTO_AUTH_ALG_SHA << CRYPTO_AUTH_ALG) |
(CRYPTO_AUTH_POS_BEFORE << CRYPTO_AUTH_POS);
pce_dev->reg.auth_cfg_sha256 =
(CRYPTO_AUTH_MODE_HASH << CRYPTO_AUTH_MODE)|
(CRYPTO_AUTH_SIZE_SHA256 << CRYPTO_AUTH_SIZE) |
(CRYPTO_AUTH_ALG_SHA << CRYPTO_AUTH_ALG) |
(CRYPTO_AUTH_POS_BEFORE << CRYPTO_AUTH_POS);
/* Initialize auth_cfg register for AEAD alg */
pce_dev->reg.auth_cfg_aead_sha1_hmac =
(CRYPTO_AUTH_MODE_HMAC << CRYPTO_AUTH_MODE)|
(CRYPTO_AUTH_SIZE_SHA1 << CRYPTO_AUTH_SIZE) |
(CRYPTO_AUTH_ALG_SHA << CRYPTO_AUTH_ALG) |
(1 << CRYPTO_LAST) | (1 << CRYPTO_FIRST);
pce_dev->reg.auth_cfg_aead_sha256_hmac =
(CRYPTO_AUTH_MODE_HMAC << CRYPTO_AUTH_MODE)|
(CRYPTO_AUTH_SIZE_SHA256 << CRYPTO_AUTH_SIZE) |
(CRYPTO_AUTH_ALG_SHA << CRYPTO_AUTH_ALG) |
(1 << CRYPTO_LAST) | (1 << CRYPTO_FIRST);
pce_dev->reg.auth_cfg_aes_ccm_128 =
(1 << CRYPTO_LAST) | (1 << CRYPTO_FIRST) |
(CRYPTO_AUTH_MODE_CCM << CRYPTO_AUTH_MODE)|
(CRYPTO_AUTH_ALG_AES << CRYPTO_AUTH_ALG) |
(CRYPTO_AUTH_KEY_SZ_AES128 << CRYPTO_AUTH_KEY_SIZE) |
((MAX_NONCE/sizeof(uint32_t)) << CRYPTO_AUTH_NONCE_NUM_WORDS);
pce_dev->reg.auth_cfg_aes_ccm_128 &= ~(1 << CRYPTO_USE_HW_KEY_AUTH);
pce_dev->reg.auth_cfg_aes_ccm_256 =
(1 << CRYPTO_LAST) | (1 << CRYPTO_FIRST) |
(CRYPTO_AUTH_MODE_CCM << CRYPTO_AUTH_MODE)|
(CRYPTO_AUTH_ALG_AES << CRYPTO_AUTH_ALG) |
(CRYPTO_AUTH_KEY_SZ_AES256 << CRYPTO_AUTH_KEY_SIZE) |
((MAX_NONCE/sizeof(uint32_t)) << CRYPTO_AUTH_NONCE_NUM_WORDS);
pce_dev->reg.auth_cfg_aes_ccm_256 &= ~(1 << CRYPTO_USE_HW_KEY_AUTH);
return 0;
}
static int _qce_aead_ccm_req(void *handle, struct qce_req *q_req)
{
struct qce_device *pce_dev = (struct qce_device *) handle;
struct aead_request *areq = (struct aead_request *) q_req->areq;
uint32_t authsize = q_req->authsize;
uint32_t totallen_in, out_len;
uint32_t hw_pad_out = 0;
int rc = 0;
int ce_burst_size;
struct qce_cmdlist_info *cmdlistinfo = NULL;
ce_burst_size = pce_dev->ce_sps.ce_burst_size;
totallen_in = areq->cryptlen + areq->assoclen;
if (q_req->dir == QCE_ENCRYPT) {
q_req->cryptlen = areq->cryptlen;
out_len = areq->cryptlen + authsize;
hw_pad_out = ALIGN(authsize, ce_burst_size) - authsize;
} else {
q_req->cryptlen = areq->cryptlen - authsize;
out_len = q_req->cryptlen;
hw_pad_out = authsize;
}
if (pce_dev->ce_sps.minor_version == 0) {
/*
* For crypto 5.0 that has burst size alignment requirement
* for data descritpor,
* the agent above(qcrypto) prepares the src scatter list with
* memory starting with associated data, followed by
* data stream to be ciphered.
* The destination scatter list is pointing to the same
* data area as source.
*/
pce_dev->src_nents = count_sg(areq->src, totallen_in);
} else {
pce_dev->src_nents = count_sg(areq->src, areq->cryptlen);
}
pce_dev->assoc_nents = count_sg(areq->assoc, areq->assoclen);
pce_dev->authsize = q_req->authsize;
/* associated data input */
qce_dma_map_sg(pce_dev->pdev, areq->assoc, pce_dev->assoc_nents,
DMA_TO_DEVICE);
/* cipher input */
qce_dma_map_sg(pce_dev->pdev, areq->src, pce_dev->src_nents,
(areq->src == areq->dst) ? DMA_BIDIRECTIONAL :
DMA_TO_DEVICE);
/* cipher + mac output for encryption */
if (areq->src != areq->dst) {
if (pce_dev->ce_sps.minor_version == 0)
/*
* The destination scatter list is pointing to the same
* data area as src.
* Note, the associated data will be pass-through
* at the begining of destination area.
*/
pce_dev->dst_nents = count_sg(areq->dst,
out_len + areq->assoclen);
else
pce_dev->dst_nents = count_sg(areq->dst, out_len);
qce_dma_map_sg(pce_dev->pdev, areq->dst, pce_dev->dst_nents,
DMA_FROM_DEVICE);
} else {
pce_dev->dst_nents = pce_dev->src_nents;
}
if (pce_dev->support_cmd_dscr) {
_ce_get_cipher_cmdlistinfo(pce_dev, q_req, &cmdlistinfo);
/* set up crypto device */
rc = _ce_setup_cipher(pce_dev, q_req, totallen_in,
areq->assoclen, cmdlistinfo);
} else {
/* set up crypto device */
rc = _ce_setup_cipher_direct(pce_dev, q_req, totallen_in,
areq->assoclen);
}
if (rc < 0)
goto bad;
/* setup for callback, and issue command to bam */
pce_dev->areq = q_req->areq;
pce_dev->qce_cb = q_req->qce_cb;
/* Register callback event for EOT (End of transfer) event. */
pce_dev->ce_sps.producer.event.callback = _aead_sps_producer_callback;
pce_dev->ce_sps.producer.event.options = SPS_O_DESC_DONE;
rc = sps_register_event(pce_dev->ce_sps.producer.pipe,
&pce_dev->ce_sps.producer.event);
if (rc) {
pr_err("Producer callback registration failed rc = %d\n", rc);
goto bad;
}
_qce_sps_iovec_count_init(pce_dev);
if (pce_dev->support_cmd_dscr)
_qce_sps_add_cmd(pce_dev, SPS_IOVEC_FLAG_LOCK, cmdlistinfo,
&pce_dev->ce_sps.in_transfer);
if (pce_dev->ce_sps.minor_version == 0) {
if (_qce_sps_add_sg_data(pce_dev, areq->src, totallen_in,
&pce_dev->ce_sps.in_transfer))
goto bad;
_qce_set_flag(&pce_dev->ce_sps.in_transfer,
SPS_IOVEC_FLAG_EOT|SPS_IOVEC_FLAG_NWD);
/*
* The destination data should be big enough to
* include CCM padding.
*/
if (_qce_sps_add_sg_data(pce_dev, areq->dst, out_len +
areq->assoclen + hw_pad_out,
&pce_dev->ce_sps.out_transfer))
goto bad;
if (totallen_in > SPS_MAX_PKT_SIZE) {
_qce_set_flag(&pce_dev->ce_sps.out_transfer,
SPS_IOVEC_FLAG_INT);
pce_dev->ce_sps.producer.event.options =
SPS_O_DESC_DONE;
pce_dev->ce_sps.producer_state = QCE_PIPE_STATE_IDLE;
} else {
if (_qce_sps_add_data(GET_PHYS_ADDR(
pce_dev->ce_sps.result_dump),
CRYPTO_RESULT_DUMP_SIZE,
&pce_dev->ce_sps.out_transfer))
goto bad;
_qce_set_flag(&pce_dev->ce_sps.out_transfer,
SPS_IOVEC_FLAG_INT);
pce_dev->ce_sps.producer_state = QCE_PIPE_STATE_COMP;
}
} else {
if (_qce_sps_add_sg_data(pce_dev, areq->assoc, areq->assoclen,
&pce_dev->ce_sps.in_transfer))
goto bad;
if (_qce_sps_add_sg_data(pce_dev, areq->src, areq->cryptlen,
&pce_dev->ce_sps.in_transfer))
goto bad;
_qce_set_flag(&pce_dev->ce_sps.in_transfer,
SPS_IOVEC_FLAG_EOT|SPS_IOVEC_FLAG_NWD);
/* Pass through to ignore associated data*/
if (_qce_sps_add_data(
GET_PHYS_ADDR(pce_dev->ce_sps.ignore_buffer),
areq->assoclen,
&pce_dev->ce_sps.out_transfer))
goto bad;
if (_qce_sps_add_sg_data(pce_dev, areq->dst, out_len,
&pce_dev->ce_sps.out_transfer))
goto bad;
/* Pass through to ignore hw_pad (padding of the MAC data) */
if (_qce_sps_add_data(
GET_PHYS_ADDR(pce_dev->ce_sps.ignore_buffer),
hw_pad_out, &pce_dev->ce_sps.out_transfer))
goto bad;
if (totallen_in > SPS_MAX_PKT_SIZE) {
_qce_set_flag(&pce_dev->ce_sps.out_transfer,
SPS_IOVEC_FLAG_INT);
pce_dev->ce_sps.producer_state = QCE_PIPE_STATE_IDLE;
} else {
if (_qce_sps_add_data(
GET_PHYS_ADDR(pce_dev->ce_sps.result_dump),
CRYPTO_RESULT_DUMP_SIZE,
&pce_dev->ce_sps.out_transfer))
goto bad;
_qce_set_flag(&pce_dev->ce_sps.out_transfer,
SPS_IOVEC_FLAG_INT);
pce_dev->ce_sps.producer_state = QCE_PIPE_STATE_COMP;
}
}
rc = _qce_sps_transfer(pce_dev);
if (rc)
goto bad;
return 0;
bad:
if (pce_dev->assoc_nents) {
qce_dma_unmap_sg(pce_dev->pdev, areq->assoc,
pce_dev->assoc_nents, DMA_TO_DEVICE);
}
if (pce_dev->src_nents) {
qce_dma_unmap_sg(pce_dev->pdev, areq->src, pce_dev->src_nents,
(areq->src == areq->dst) ? DMA_BIDIRECTIONAL :
DMA_TO_DEVICE);
}
if (areq->src != areq->dst) {
qce_dma_unmap_sg(pce_dev->pdev, areq->dst, pce_dev->dst_nents,
DMA_FROM_DEVICE);
}
return rc;
}
int qce_aead_req(void *handle, struct qce_req *q_req)
{
struct qce_device *pce_dev;
struct aead_request *areq;
uint32_t authsize;
struct crypto_aead *aead;
uint32_t ivsize;
uint32_t totallen;
int rc;
struct qce_cmdlist_info *cmdlistinfo = NULL;
if (q_req->mode == QCE_MODE_CCM)
return _qce_aead_ccm_req(handle, q_req);
pce_dev = (struct qce_device *) handle;
areq = (struct aead_request *) q_req->areq;
aead = crypto_aead_reqtfm(areq);
ivsize = crypto_aead_ivsize(aead);
q_req->ivsize = ivsize;
authsize = q_req->authsize;
if (q_req->dir == QCE_ENCRYPT)
q_req->cryptlen = areq->cryptlen;
else
q_req->cryptlen = areq->cryptlen - authsize;
totallen = q_req->cryptlen + areq->assoclen + ivsize;
if (pce_dev->support_cmd_dscr) {
cmdlistinfo = _ce_get_aead_cmdlistinfo(pce_dev, q_req);
if (cmdlistinfo == NULL) {
pr_err("Unsupported aead ciphering algorithm %d, mode %d, ciphering key length %d, auth digest size %d\n",
q_req->alg, q_req->mode, q_req->encklen,
q_req->authsize);
return -EINVAL;
}
/* set up crypto device */
rc = _ce_setup_aead(pce_dev, q_req, totallen,
areq->assoclen + ivsize, cmdlistinfo);
if (rc < 0)
return -EINVAL;
};
pce_dev->assoc_nents = count_sg(areq->assoc, areq->assoclen);
if (pce_dev->ce_sps.minor_version == 0) {
/*
* For crypto 5.0 that has burst size alignment requirement
* for data descritpor,
* the agent above(qcrypto) prepares the src scatter list with
* memory starting with associated data, followed by
* iv, and data stream to be ciphered.
*/
pce_dev->src_nents = count_sg(areq->src, totallen);
} else {
pce_dev->src_nents = count_sg(areq->src, q_req->cryptlen);
};
pce_dev->ivsize = q_req->ivsize;
pce_dev->authsize = q_req->authsize;
pce_dev->phy_iv_in = 0;
/* associated data input */
qce_dma_map_sg(pce_dev->pdev, areq->assoc, pce_dev->assoc_nents,
DMA_TO_DEVICE);
/* cipher input */
qce_dma_map_sg(pce_dev->pdev, areq->src, pce_dev->src_nents,
(areq->src == areq->dst) ? DMA_BIDIRECTIONAL :
DMA_TO_DEVICE);
/* cipher + mac output for encryption */
if (areq->src != areq->dst) {
if (pce_dev->ce_sps.minor_version == 0)
/*
* The destination scatter list is pointing to the same
* data area as source.
*/
pce_dev->dst_nents = count_sg(areq->dst, totallen);
else
pce_dev->dst_nents = count_sg(areq->dst,
q_req->cryptlen);
qce_dma_map_sg(pce_dev->pdev, areq->dst, pce_dev->dst_nents,
DMA_FROM_DEVICE);
}
/* cipher iv for input */
if (pce_dev->ce_sps.minor_version != 0)
pce_dev->phy_iv_in = dma_map_single(pce_dev->pdev, q_req->iv,
ivsize, DMA_TO_DEVICE);
/* setup for callback, and issue command to bam */
pce_dev->areq = q_req->areq;
pce_dev->qce_cb = q_req->qce_cb;
/* Register callback event for EOT (End of transfer) event. */
pce_dev->ce_sps.producer.event.callback = _aead_sps_producer_callback;
pce_dev->ce_sps.producer.event.options = SPS_O_DESC_DONE;
rc = sps_register_event(pce_dev->ce_sps.producer.pipe,
&pce_dev->ce_sps.producer.event);
if (rc) {
pr_err("Producer callback registration failed rc = %d\n", rc);
goto bad;
}
_qce_sps_iovec_count_init(pce_dev);
if (pce_dev->support_cmd_dscr) {
_qce_sps_add_cmd(pce_dev, SPS_IOVEC_FLAG_LOCK, cmdlistinfo,
&pce_dev->ce_sps.in_transfer);
} else {
rc = _ce_setup_aead_direct(pce_dev, q_req, totallen,
areq->assoclen + ivsize);
if (rc)
goto bad;
}
if (pce_dev->ce_sps.minor_version == 0) {
if (_qce_sps_add_sg_data(pce_dev, areq->src, totallen,
&pce_dev->ce_sps.in_transfer))
goto bad;
_qce_set_flag(&pce_dev->ce_sps.in_transfer,
SPS_IOVEC_FLAG_EOT|SPS_IOVEC_FLAG_NWD);
if (_qce_sps_add_sg_data(pce_dev, areq->dst, totallen,
&pce_dev->ce_sps.out_transfer))
goto bad;
if (totallen > SPS_MAX_PKT_SIZE) {
_qce_set_flag(&pce_dev->ce_sps.out_transfer,
SPS_IOVEC_FLAG_INT);
pce_dev->ce_sps.producer.event.options =
SPS_O_DESC_DONE;
pce_dev->ce_sps.producer_state = QCE_PIPE_STATE_IDLE;
} else {
if (_qce_sps_add_data(GET_PHYS_ADDR(
pce_dev->ce_sps.result_dump),
CRYPTO_RESULT_DUMP_SIZE,
&pce_dev->ce_sps.out_transfer))
goto bad;
_qce_set_flag(&pce_dev->ce_sps.out_transfer,
SPS_IOVEC_FLAG_INT);
pce_dev->ce_sps.producer_state = QCE_PIPE_STATE_COMP;
}
} else {
if (_qce_sps_add_sg_data(pce_dev, areq->assoc, areq->assoclen,
&pce_dev->ce_sps.in_transfer))
goto bad;
if (_qce_sps_add_data((uint32_t)pce_dev->phy_iv_in, ivsize,
&pce_dev->ce_sps.in_transfer))
goto bad;
if (_qce_sps_add_sg_data(pce_dev, areq->src, areq->cryptlen,
&pce_dev->ce_sps.in_transfer))
goto bad;
_qce_set_flag(&pce_dev->ce_sps.in_transfer,
SPS_IOVEC_FLAG_EOT|SPS_IOVEC_FLAG_NWD);
/* Pass through to ignore associated + iv data*/
if (_qce_sps_add_data(
GET_PHYS_ADDR(pce_dev->ce_sps.ignore_buffer),
(ivsize + areq->assoclen),
&pce_dev->ce_sps.out_transfer))
goto bad;
if (_qce_sps_add_sg_data(pce_dev, areq->dst, areq->cryptlen,
&pce_dev->ce_sps.out_transfer))
goto bad;
if (totallen > SPS_MAX_PKT_SIZE) {
_qce_set_flag(&pce_dev->ce_sps.out_transfer,
SPS_IOVEC_FLAG_INT);
pce_dev->ce_sps.producer_state = QCE_PIPE_STATE_IDLE;
} else {
if (_qce_sps_add_data(
GET_PHYS_ADDR(pce_dev->ce_sps.result_dump),
CRYPTO_RESULT_DUMP_SIZE,
&pce_dev->ce_sps.out_transfer))
goto bad;
_qce_set_flag(&pce_dev->ce_sps.out_transfer,
SPS_IOVEC_FLAG_INT);
pce_dev->ce_sps.producer_state = QCE_PIPE_STATE_COMP;
}
}
rc = _qce_sps_transfer(pce_dev);
if (rc)
goto bad;
return 0;
bad:
if (pce_dev->assoc_nents) {
qce_dma_unmap_sg(pce_dev->pdev, areq->assoc,
pce_dev->assoc_nents, DMA_TO_DEVICE);
}
if (pce_dev->src_nents) {
qce_dma_unmap_sg(pce_dev->pdev, areq->src, pce_dev->src_nents,
(areq->src == areq->dst) ? DMA_BIDIRECTIONAL :
DMA_TO_DEVICE);
}
if (areq->src != areq->dst) {
qce_dma_unmap_sg(pce_dev->pdev, areq->dst, pce_dev->dst_nents,
DMA_FROM_DEVICE);
}
if (pce_dev->phy_iv_in) {
dma_unmap_single(pce_dev->pdev, pce_dev->phy_iv_in,
ivsize, DMA_TO_DEVICE);
}
return rc;
}
EXPORT_SYMBOL(qce_aead_req);
int qce_ablk_cipher_req(void *handle, struct qce_req *c_req)
{
int rc = 0;
struct qce_device *pce_dev = (struct qce_device *) handle;
struct ablkcipher_request *areq = (struct ablkcipher_request *)
c_req->areq;
struct qce_cmdlist_info *cmdlistinfo = NULL;
pce_dev->src_nents = 0;
pce_dev->dst_nents = 0;
/* cipher input */
pce_dev->src_nents = count_sg(areq->src, areq->nbytes);
qce_dma_map_sg(pce_dev->pdev, areq->src, pce_dev->src_nents,
(areq->src == areq->dst) ? DMA_BIDIRECTIONAL :
DMA_TO_DEVICE);
/* cipher output */
if (areq->src != areq->dst) {
pce_dev->dst_nents = count_sg(areq->dst, areq->nbytes);
qce_dma_map_sg(pce_dev->pdev, areq->dst,
pce_dev->dst_nents, DMA_FROM_DEVICE);
} else {
pce_dev->dst_nents = pce_dev->src_nents;
}
pce_dev->dir = c_req->dir;
if ((pce_dev->ce_sps.minor_version == 0) && (c_req->dir == QCE_DECRYPT)
&& (c_req->mode == QCE_MODE_CBC)) {
memcpy(pce_dev->dec_iv, (unsigned char *)sg_virt(areq->src) +
areq->src->length - 16,
NUM_OF_CRYPTO_CNTR_IV_REG * CRYPTO_REG_SIZE);
}
/* set up crypto device */
if (pce_dev->support_cmd_dscr) {
_ce_get_cipher_cmdlistinfo(pce_dev, c_req, &cmdlistinfo);
rc = _ce_setup_cipher(pce_dev, c_req, areq->nbytes, 0,
cmdlistinfo);
} else {
rc = _ce_setup_cipher_direct(pce_dev, c_req, areq->nbytes, 0);
}
if (rc < 0)
goto bad;
/* setup for client callback, and issue command to BAM */
pce_dev->areq = areq;
pce_dev->qce_cb = c_req->qce_cb;
/* Register callback event for EOT (End of transfer) event. */
pce_dev->ce_sps.producer.event.callback =
_ablk_cipher_sps_producer_callback;
pce_dev->ce_sps.producer.event.options = SPS_O_DESC_DONE;
rc = sps_register_event(pce_dev->ce_sps.producer.pipe,
&pce_dev->ce_sps.producer.event);
if (rc) {
pr_err("Producer callback registration failed rc = %d\n", rc);
goto bad;
}
_qce_sps_iovec_count_init(pce_dev);
if (pce_dev->support_cmd_dscr)
_qce_sps_add_cmd(pce_dev, SPS_IOVEC_FLAG_LOCK, cmdlistinfo,
&pce_dev->ce_sps.in_transfer);
if (_qce_sps_add_sg_data(pce_dev, areq->src, areq->nbytes,
&pce_dev->ce_sps.in_transfer))
goto bad;
_qce_set_flag(&pce_dev->ce_sps.in_transfer,
SPS_IOVEC_FLAG_EOT|SPS_IOVEC_FLAG_NWD);
if (_qce_sps_add_sg_data(pce_dev, areq->dst, areq->nbytes,
&pce_dev->ce_sps.out_transfer))
goto bad;
if (areq->nbytes > SPS_MAX_PKT_SIZE) {
_qce_set_flag(&pce_dev->ce_sps.out_transfer,
SPS_IOVEC_FLAG_INT);
pce_dev->ce_sps.producer_state = QCE_PIPE_STATE_IDLE;
} else {
pce_dev->ce_sps.producer_state = QCE_PIPE_STATE_COMP;
if (_qce_sps_add_data(
GET_PHYS_ADDR(pce_dev->ce_sps.result_dump),
CRYPTO_RESULT_DUMP_SIZE,
&pce_dev->ce_sps.out_transfer))
goto bad;
_qce_set_flag(&pce_dev->ce_sps.out_transfer,
SPS_IOVEC_FLAG_INT);
}
rc = _qce_sps_transfer(pce_dev);
if (rc)
goto bad;
return 0;
bad:
if (areq->src != areq->dst) {
if (pce_dev->dst_nents) {
qce_dma_unmap_sg(pce_dev->pdev, areq->dst,
pce_dev->dst_nents, DMA_FROM_DEVICE);
}
}
if (pce_dev->src_nents) {
qce_dma_unmap_sg(pce_dev->pdev, areq->src,
pce_dev->src_nents,
(areq->src == areq->dst) ?
DMA_BIDIRECTIONAL : DMA_TO_DEVICE);
}
return rc;
}
EXPORT_SYMBOL(qce_ablk_cipher_req);
int qce_process_sha_req(void *handle, struct qce_sha_req *sreq)
{
struct qce_device *pce_dev = (struct qce_device *) handle;
int rc;
struct ahash_request *areq = (struct ahash_request *)sreq->areq;
struct qce_cmdlist_info *cmdlistinfo = NULL;
pce_dev->src_nents = count_sg(sreq->src, sreq->size);
qce_dma_map_sg(pce_dev->pdev, sreq->src, pce_dev->src_nents,
DMA_TO_DEVICE);
if (pce_dev->support_cmd_dscr) {
_ce_get_hash_cmdlistinfo(pce_dev, sreq, &cmdlistinfo);
rc = _ce_setup_hash(pce_dev, sreq, cmdlistinfo);
} else {
rc = _ce_setup_hash_direct(pce_dev, sreq);
}
if (rc < 0)
goto bad;
pce_dev->areq = areq;
pce_dev->qce_cb = sreq->qce_cb;
/* Register callback event for EOT (End of transfer) event. */
pce_dev->ce_sps.producer.event.callback = _sha_sps_producer_callback;
pce_dev->ce_sps.producer.event.options = SPS_O_DESC_DONE;
rc = sps_register_event(pce_dev->ce_sps.producer.pipe,
&pce_dev->ce_sps.producer.event);
if (rc) {
pr_err("Producer callback registration failed rc = %d\n", rc);
goto bad;
}
_qce_sps_iovec_count_init(pce_dev);
if (pce_dev->support_cmd_dscr)
_qce_sps_add_cmd(pce_dev, SPS_IOVEC_FLAG_LOCK, cmdlistinfo,
&pce_dev->ce_sps.in_transfer);
if (_qce_sps_add_sg_data(pce_dev, areq->src, areq->nbytes,
&pce_dev->ce_sps.in_transfer))
goto bad;
_qce_set_flag(&pce_dev->ce_sps.in_transfer,
SPS_IOVEC_FLAG_EOT|SPS_IOVEC_FLAG_NWD);
if (_qce_sps_add_data(GET_PHYS_ADDR(pce_dev->ce_sps.result_dump),
CRYPTO_RESULT_DUMP_SIZE,
&pce_dev->ce_sps.out_transfer))
goto bad;
_qce_set_flag(&pce_dev->ce_sps.out_transfer, SPS_IOVEC_FLAG_INT);
rc = _qce_sps_transfer(pce_dev);
if (rc)
goto bad;
return 0;
bad:
if (pce_dev->src_nents) {
qce_dma_unmap_sg(pce_dev->pdev, sreq->src,
pce_dev->src_nents, DMA_TO_DEVICE);
}
return rc;
}
EXPORT_SYMBOL(qce_process_sha_req);
static int __qce_get_device_tree_data(struct platform_device *pdev,
struct qce_device *pce_dev)
{
struct resource *resource;
int rc = 0;
pce_dev->is_shared = of_property_read_bool((&pdev->dev)->of_node,
"qcom,ce-hw-shared");
pce_dev->support_hw_key = of_property_read_bool((&pdev->dev)->of_node,
"qcom,ce-hw-key");
if (of_property_read_u32((&pdev->dev)->of_node,
"qcom,bam-pipe-pair",
&pce_dev->ce_sps.pipe_pair_index)) {
pr_err("Fail to get bam pipe pair information.\n");
return -EINVAL;
} else {
pr_warn("bam_pipe_pair=0x%x", pce_dev->ce_sps.pipe_pair_index);
}
pce_dev->ce_sps.dest_pipe_index = 2 * pce_dev->ce_sps.pipe_pair_index;
pce_dev->ce_sps.src_pipe_index = pce_dev->ce_sps.dest_pipe_index + 1;
resource = platform_get_resource_byname(pdev, IORESOURCE_MEM,
"crypto-base");
if (resource) {
pce_dev->phy_iobase = resource->start;
pce_dev->iobase = ioremap_nocache(resource->start,
resource_size(resource));
if (!pce_dev->iobase) {
pr_err("Can not map CRYPTO io memory\n");
return -ENOMEM;
}
} else {
pr_err("CRYPTO HW mem unavailable.\n");
return -ENODEV;
}
pr_warn("ce_phy_reg_base=0x%x ", pce_dev->phy_iobase);
pr_warn("ce_virt_reg_base=0x%x\n", (uint32_t)pce_dev->iobase);
resource = platform_get_resource_byname(pdev, IORESOURCE_MEM,
"crypto-bam-base");
if (resource) {
pce_dev->ce_sps.bam_mem = resource->start;
pce_dev->ce_sps.bam_iobase = ioremap_nocache(resource->start,
resource_size(resource));
if (!pce_dev->ce_sps.bam_iobase) {
rc = -ENOMEM;
pr_err("Can not map BAM io memory\n");
goto err_getting_bam_info;
}
} else {
pr_err("CRYPTO BAM mem unavailable.\n");
rc = -ENODEV;
goto err_getting_bam_info;
}
pr_warn("ce_bam_phy_reg_base=0x%x ", pce_dev->ce_sps.bam_mem);
pr_warn("ce_bam_virt_reg_base=0x%x\n",
(uint32_t)pce_dev->ce_sps.bam_iobase);
resource = platform_get_resource(pdev, IORESOURCE_IRQ, 0);
if (resource) {
pce_dev->ce_sps.bam_irq = resource->start;
pr_warn("CRYPTO BAM IRQ = %d.\n", pce_dev->ce_sps.bam_irq);
} else {
pr_err("CRYPTO BAM IRQ unavailable.\n");
goto err_dev;
}
return rc;
err_dev:
if (pce_dev->ce_sps.bam_iobase)
iounmap(pce_dev->ce_sps.bam_iobase);
err_getting_bam_info:
if (pce_dev->iobase)
iounmap(pce_dev->iobase);
return rc;
}
static int __qce_init_clk(struct qce_device *pce_dev)
{
int rc = 0;
struct clk *ce_core_clk;
struct clk *ce_clk;
struct clk *ce_core_src_clk;
struct clk *ce_bus_clk;
/* Get CE3 src core clk. */
ce_core_src_clk = clk_get(pce_dev->pdev, "core_clk_src");
if (!IS_ERR(ce_core_src_clk)) {
pce_dev->ce_core_src_clk = ce_core_src_clk;
/* Set the core src clk @100Mhz */
rc = clk_set_rate(pce_dev->ce_core_src_clk, 100000000);
if (rc) {
clk_put(pce_dev->ce_core_src_clk);
pce_dev->ce_core_src_clk = NULL;
pr_err("Unable to set the core src clk @100Mhz.\n");
goto err_clk;
}
} else {
pr_warn("Unable to get CE core src clk, set to NULL\n");
pce_dev->ce_core_src_clk = NULL;
}
/* Get CE core clk */
ce_core_clk = clk_get(pce_dev->pdev, "core_clk");
if (IS_ERR(ce_core_clk)) {
rc = PTR_ERR(ce_core_clk);
pr_err("Unable to get CE core clk\n");
if (pce_dev->ce_core_src_clk != NULL)
clk_put(pce_dev->ce_core_src_clk);
goto err_clk;
}
pce_dev->ce_core_clk = ce_core_clk;
/* Get CE Interface clk */
ce_clk = clk_get(pce_dev->pdev, "iface_clk");
if (IS_ERR(ce_clk)) {
rc = PTR_ERR(ce_clk);
pr_err("Unable to get CE interface clk\n");
if (pce_dev->ce_core_src_clk != NULL)
clk_put(pce_dev->ce_core_src_clk);
clk_put(pce_dev->ce_core_clk);
goto err_clk;
}
pce_dev->ce_clk = ce_clk;
/* Get CE AXI clk */
ce_bus_clk = clk_get(pce_dev->pdev, "bus_clk");
if (IS_ERR(ce_bus_clk)) {
rc = PTR_ERR(ce_bus_clk);
pr_err("Unable to get CE BUS interface clk\n");
if (pce_dev->ce_core_src_clk != NULL)
clk_put(pce_dev->ce_core_src_clk);
clk_put(pce_dev->ce_core_clk);
clk_put(pce_dev->ce_clk);
goto err_clk;
}
pce_dev->ce_bus_clk = ce_bus_clk;
err_clk:
if (rc)
pr_err("Unable to init CE clks, rc = %d\n", rc);
return rc;
}
static void __qce_deinit_clk(struct qce_device *pce_dev)
{
if (pce_dev->ce_clk != NULL) {
clk_put(pce_dev->ce_clk);
pce_dev->ce_clk = NULL;
}
if (pce_dev->ce_core_clk != NULL) {
clk_put(pce_dev->ce_core_clk);
pce_dev->ce_core_clk = NULL;
}
if (pce_dev->ce_bus_clk != NULL) {
clk_put(pce_dev->ce_bus_clk);
pce_dev->ce_bus_clk = NULL;
}
if (pce_dev->ce_core_src_clk != NULL) {
clk_put(pce_dev->ce_core_src_clk);
pce_dev->ce_core_src_clk = NULL;
}
}
int qce_enable_clk(void *handle)
{
struct qce_device *pce_dev = (struct qce_device *) handle;
int rc = 0;
/* Enable CE core clk */
if (pce_dev->ce_core_clk != NULL) {
rc = clk_prepare_enable(pce_dev->ce_core_clk);
if (rc) {
pr_err("Unable to enable/prepare CE core clk\n");
return rc;
}
}
/* Enable CE clk */
if (pce_dev->ce_clk != NULL) {
rc = clk_prepare_enable(pce_dev->ce_clk);
if (rc) {
pr_err("Unable to enable/prepare CE iface clk\n");
clk_disable_unprepare(pce_dev->ce_core_clk);
return rc;
}
}
/* Enable AXI clk */
if (pce_dev->ce_bus_clk != NULL) {
rc = clk_prepare_enable(pce_dev->ce_bus_clk);
if (rc) {
pr_err("Unable to enable/prepare CE BUS clk\n");
clk_disable_unprepare(pce_dev->ce_clk);
clk_disable_unprepare(pce_dev->ce_core_clk);
return rc;
}
}
return rc;
}
EXPORT_SYMBOL(qce_enable_clk);
int qce_disable_clk(void *handle)
{
struct qce_device *pce_dev = (struct qce_device *) handle;
int rc = 0;
if (pce_dev->ce_clk != NULL)
clk_disable_unprepare(pce_dev->ce_clk);
if (pce_dev->ce_core_clk != NULL)
clk_disable_unprepare(pce_dev->ce_core_clk);
if (pce_dev->ce_bus_clk != NULL)
clk_disable_unprepare(pce_dev->ce_bus_clk);
return rc;
}
EXPORT_SYMBOL(qce_disable_clk);
/* crypto engine open function. */
void *qce_open(struct platform_device *pdev, int *rc)
{
struct qce_device *pce_dev;
uint32_t bam_cfg = 0 ;
pce_dev = kzalloc(sizeof(struct qce_device), GFP_KERNEL);
if (!pce_dev) {
*rc = -ENOMEM;
pr_err("Can not allocate memory: %d\n", *rc);
return NULL;
}
pce_dev->pdev = &pdev->dev;
if (pdev->dev.of_node) {
*rc = __qce_get_device_tree_data(pdev, pce_dev);
if (*rc)
goto err_pce_dev;
} else {
*rc = -EINVAL;
pr_err("Device Node not found.\n");
goto err_pce_dev;
}
pce_dev->memsize = 9 * PAGE_SIZE;
pce_dev->coh_vmem = dma_alloc_coherent(pce_dev->pdev,
pce_dev->memsize, &pce_dev->coh_pmem, GFP_KERNEL);
if (pce_dev->coh_vmem == NULL) {
*rc = -ENOMEM;
pr_err("Can not allocate coherent memory for sps data\n");
goto err_iobase;
}
*rc = __qce_init_clk(pce_dev);
if (*rc)
goto err_mem;
*rc = qce_enable_clk(pce_dev);
if (*rc)
goto err;
if (_probe_ce_engine(pce_dev)) {
*rc = -ENXIO;
goto err;
}
*rc = 0;
bam_cfg = readl_relaxed(pce_dev->ce_sps.bam_iobase +
CRYPTO_BAM_CNFG_BITS_REG);
pce_dev->support_cmd_dscr = (bam_cfg & CRYPTO_BAM_CD_ENABLE_MASK) ?
true : false;
qce_init_ce_cfg_val(pce_dev);
qce_setup_ce_sps_data(pce_dev);
qce_sps_init(pce_dev);
qce_disable_clk(pce_dev);
return pce_dev;
err:
__qce_deinit_clk(pce_dev);
err_mem:
if (pce_dev->coh_vmem)
dma_free_coherent(pce_dev->pdev, pce_dev->memsize,
pce_dev->coh_vmem, pce_dev->coh_pmem);
err_iobase:
if (pce_dev->ce_sps.bam_iobase)
iounmap(pce_dev->ce_sps.bam_iobase);
if (pce_dev->iobase)
iounmap(pce_dev->iobase);
err_pce_dev:
kfree(pce_dev);
return NULL;
}
EXPORT_SYMBOL(qce_open);
/* crypto engine close function. */
int qce_close(void *handle)
{
struct qce_device *pce_dev = (struct qce_device *) handle;
if (handle == NULL)
return -ENODEV;
qce_enable_clk(pce_dev);
qce_sps_exit(pce_dev);
if (pce_dev->iobase)
iounmap(pce_dev->iobase);
if (pce_dev->coh_vmem)
dma_free_coherent(pce_dev->pdev, pce_dev->memsize,
pce_dev->coh_vmem, pce_dev->coh_pmem);
qce_disable_clk(pce_dev);
__qce_deinit_clk(pce_dev);
kfree(handle);
return 0;
}
EXPORT_SYMBOL(qce_close);
int qce_hw_support(void *handle, struct ce_hw_support *ce_support)
{
struct qce_device *pce_dev = (struct qce_device *)handle;
if (ce_support == NULL)
return -EINVAL;
ce_support->sha1_hmac_20 = false;
ce_support->sha1_hmac = false;
ce_support->sha256_hmac = false;
ce_support->sha_hmac = true;
ce_support->cmac = true;
ce_support->aes_key_192 = false;
ce_support->aes_xts = true;
ce_support->ota = false;
ce_support->bam = true;
ce_support->is_shared = (pce_dev->is_shared == 1) ? true : false;
ce_support->hw_key = pce_dev->support_hw_key;
ce_support->aes_ccm = true;
if (pce_dev->ce_sps.minor_version)
ce_support->aligned_only = false;
else
ce_support->aligned_only = true;
return 0;
}
EXPORT_SYMBOL(qce_hw_support);
MODULE_LICENSE("GPL v2");
MODULE_DESCRIPTION("Crypto Engine driver");
| MattCrystal/tripping-hipster | drivers/crypto/msm/qce50.c | C | gpl-2.0 | 128,263 |
package org.zanata.dao;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.zanata.model.HAccount;
import org.zanata.model.HAccountRole;
import org.zanata.model.HProject;
@Name("accountRoleDAO")
@AutoCreate
@Scope(ScopeType.STATELESS)
public class AccountRoleDAO extends AbstractDAOImpl<HAccountRole, Integer> {
public AccountRoleDAO() {
super(HAccountRole.class);
}
public AccountRoleDAO(Session session) {
super(HAccountRole.class, session);
}
public boolean roleExists(String role) {
return findByName(role) != null;
}
public HAccountRole findByName(String roleName) {
Criteria cr = getSession().createCriteria(HAccountRole.class);
cr.add(Restrictions.eq("name", roleName));
cr.setCacheable(true).setComment("AccountRoleDAO.findByName");
return (HAccountRole) cr.uniqueResult();
}
public HAccountRole create(String roleName, HAccountRole.RoleType type,
String... includesRoles) {
HAccountRole role = new HAccountRole();
role.setName(roleName);
role.setRoleType(type);
for (String includeRole : includesRoles) {
Set<HAccountRole> groups = role.getGroups();
if (groups == null) {
groups = new HashSet<HAccountRole>();
role.setGroups(groups);
}
groups.add(findByName(includeRole));
}
makePersistent(role);
return role;
}
public HAccountRole updateIncludeRoles(String roleName,
String... includesRoles) {
HAccountRole role = findByName(roleName);
for (String includeRole : includesRoles) {
Set<HAccountRole> groups = role.getGroups();
if (groups == null) {
groups = new HashSet<HAccountRole>();
role.setGroups(groups);
}
groups.add(findByName(includeRole));
}
makePersistent(role);
return role;
}
public List<HAccount> listMembers(String roleName) {
HAccountRole role = findByName(roleName);
return listMembers(role);
}
@SuppressWarnings("unchecked")
public List<HAccount> listMembers(HAccountRole role) {
Query query =
getSession()
.createQuery(
"from HAccount account where :role member of account.roles");
query.setParameter("role", role);
query.setComment("AccountRoleDAO.listMembers");
return query.list();
}
public Collection<HAccountRole> getByProject(HProject project) {
return getSession()
.createQuery(
"select p.allowedRoles from HProject p where p = :project")
.setParameter("project", project)
.setComment("AccountRoleDAO.getByProject").list();
}
}
| itsazzad/zanata-server | zanata-war/src/main/java/org/zanata/dao/AccountRoleDAO.java | Java | gpl-2.0 | 3,235 |
/*
Copyright (C) 2009 - 2015 by Yurii Chernyi <[email protected]>
Part of the Battle for Wesnoth Project http://www.wesnoth.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.
See the COPYING file for more details.
*/
/**
* @file
* Formula debugger - implementation
* */
#include "formula_debugger.hpp"
#include "formula.hpp"
#include "formula_function.hpp"
#include "game_display.hpp"
#include "log.hpp"
#include "resources.hpp"
#include "gui/dialogs/formula_debugger.hpp"
#include "gui/widgets/settings.hpp"
#include <boost/lexical_cast.hpp>
static lg::log_domain log_formula_debugger("ai/debug/formula");
#define DBG_FDB LOG_STREAM(debug, log_formula_debugger)
#define LOG_FDB LOG_STREAM(info, log_formula_debugger)
#define WRN_FDB LOG_STREAM(warn, log_formula_debugger)
#define ERR_FDB LOG_STREAM(err, log_formula_debugger)
namespace game_logic {
debug_info::debug_info(int arg_number, int counter, int level, const std::string &name, const std::string &str, const variant &value, bool evaluated)
: arg_number_(arg_number), counter_(counter), level_(level), name_(name), str_(str), value_(value), evaluated_(evaluated)
{
}
debug_info::~debug_info()
{
}
int debug_info::level() const
{
return level_;
}
const std::string& debug_info::name() const
{
return name_;
}
int debug_info::counter() const
{
return counter_;
}
const variant& debug_info::value() const
{
return value_;
}
void debug_info::set_value(const variant &value)
{
value_ = value;
}
bool debug_info::evaluated() const
{
return evaluated_;
}
void debug_info::set_evaluated(bool evaluated)
{
evaluated_ = evaluated;
}
const std::string& debug_info::str() const
{
return str_;
}
formula_debugger::formula_debugger()
: call_stack_(), counter_(0), current_breakpoint_(), breakpoints_(), execution_trace_(),arg_number_extra_debug_info(-1), f_name_extra_debug_info("")
{
add_breakpoint_step_into();
add_breakpoint_continue_to_end();
}
formula_debugger::~formula_debugger()
{
}
static void msg(const char *act, debug_info &i, const char *to="", const char *result = "")
{
DBG_FDB << "#" << i.counter() << act << std::endl <<" \""<< i.name().c_str() << "\"='" << i.str().c_str() << "' " << to << result << std::endl;
}
void formula_debugger::add_debug_info(int arg_number, const char *f_name)
{
arg_number_extra_debug_info = arg_number;
f_name_extra_debug_info = f_name;
}
const std::deque<debug_info>& formula_debugger::get_call_stack() const
{
return call_stack_;
}
const breakpoint_ptr formula_debugger::get_current_breakpoint() const
{
return current_breakpoint_;
}
const std::deque<debug_info>& formula_debugger::get_execution_trace() const
{
return execution_trace_;
}
void formula_debugger::check_breakpoints()
{
for( std::deque< breakpoint_ptr >::iterator b = breakpoints_.begin(); b!= breakpoints_.end(); ++b) {
if ((*b)->is_break_now()){
current_breakpoint_ = (*b);
show_gui();
current_breakpoint_ = breakpoint_ptr();
if ((*b)->is_one_time_only()) {
breakpoints_.erase(b);
}
break;
}
}
}
void formula_debugger::show_gui()
{
if (resources::screen == NULL) {
WRN_FDB << "do not showing debug window due to NULL gui" << std::endl;
return;
}
if (gui2::new_widgets) {
gui2::tformula_debugger debug_dialog(*this);
debug_dialog.show(resources::screen->video());
} else {
WRN_FDB << "do not showing debug window due to disabled --new-widgets"<< std::endl;
}
}
void formula_debugger::call_stack_push(const std::string &str)
{
call_stack_.push_back(debug_info(arg_number_extra_debug_info,counter_++,call_stack_.size(),f_name_extra_debug_info,str,variant(),false));
arg_number_extra_debug_info = -1;
f_name_extra_debug_info = "";
execution_trace_.push_back(call_stack_.back());
}
void formula_debugger::call_stack_pop()
{
execution_trace_.push_back(call_stack_.back());
call_stack_.pop_back();
}
void formula_debugger::call_stack_set_evaluated(bool evaluated)
{
call_stack_.back().set_evaluated(evaluated);
}
void formula_debugger::call_stack_set_value(const variant &v)
{
call_stack_.back().set_value(v);
}
variant formula_debugger::evaluate_arg_callback(const formula_expression &expression, const formula_callable &variables)
{
call_stack_push(expression.str());
check_breakpoints();
msg(" evaluating expression: ",call_stack_.back());
variant v = expression.execute(variables,this);
call_stack_set_value(v);
call_stack_set_evaluated(true);
msg(" evaluated expression: ",call_stack_.back()," to ",v.to_debug_string(NULL,true).c_str());
check_breakpoints();
call_stack_pop();
return v;
}
variant formula_debugger::evaluate_formula_callback(const formula &f, const formula_callable &variables)
{
call_stack_push(f.str());
check_breakpoints();
msg(" evaluating formula: ",call_stack_.back());
variant v = f.execute(variables,this);
call_stack_set_value(v);
call_stack_set_evaluated(true);
msg(" evaluated formula: ",call_stack_.back()," to ",v.to_debug_string(NULL,true).c_str());
check_breakpoints();
call_stack_pop();
return v;
}
variant formula_debugger::evaluate_formula_callback(const formula &f)
{
call_stack_push(f.str());
check_breakpoints();
msg(" evaluating formula without variables: ",call_stack_.back());
variant v = f.execute(this);
call_stack_set_value(v);
call_stack_set_evaluated(true);
msg(" evaluated formula without variables: ",call_stack_.back()," to ",v.to_debug_string(NULL,true).c_str());
check_breakpoints();
call_stack_pop();
return v;
}
base_breakpoint::base_breakpoint(formula_debugger &fdb, const std::string &name, bool one_time_only)
: fdb_(fdb), name_(name), one_time_only_(one_time_only)
{
}
base_breakpoint::~base_breakpoint()
{
}
bool base_breakpoint::is_one_time_only() const
{
return one_time_only_;
}
const std::string& base_breakpoint::name() const
{
return name_;
}
class end_breakpoint : public base_breakpoint {
public:
end_breakpoint(formula_debugger &fdb)
: base_breakpoint(fdb,"End", true)
{
}
virtual ~end_breakpoint()
{
}
virtual bool is_break_now() const
{
const std::deque<debug_info> &call_stack = fdb_.get_call_stack();
if ((call_stack.size() == 1) && (call_stack[0].evaluated()) ) {
return true;
}
return false;
}
};
class step_in_breakpoint : public base_breakpoint {
public:
step_in_breakpoint(formula_debugger &fdb)
: base_breakpoint(fdb,"Step",true)
{
}
virtual ~step_in_breakpoint()
{
}
virtual bool is_break_now() const
{
const std::deque<debug_info> &call_stack = fdb_.get_call_stack();
if (call_stack.empty() || call_stack.back().evaluated()) {
return false;
}
return true;
}
};
class step_out_breakpoint : public base_breakpoint {
public:
step_out_breakpoint(formula_debugger &fdb)
: base_breakpoint(fdb,"Step out",true), level_(fdb.get_call_stack().size()-1)
{
}
virtual ~step_out_breakpoint()
{
}
virtual bool is_break_now() const
{
const std::deque<debug_info> &call_stack = fdb_.get_call_stack();
if (call_stack.empty() || call_stack.back().evaluated()) {
return false;
}
if (call_stack.size() == level_) {
return true;
}
return false;
}
private:
size_t level_;
};
class next_breakpoint : public base_breakpoint {
public:
next_breakpoint(formula_debugger &fdb)
: base_breakpoint(fdb,"Next",true), level_(fdb.get_call_stack().size())
{
}
virtual ~next_breakpoint()
{
}
virtual bool is_break_now() const
{
const std::deque<debug_info> &call_stack = fdb_.get_call_stack();
if (call_stack.empty() || call_stack.back().evaluated()) {
return false;
}
if (call_stack.size() == level_) {
return true;
}
return false;
}
private:
size_t level_;
};
void formula_debugger::add_breakpoint_continue_to_end()
{
breakpoints_.push_back(breakpoint_ptr(new end_breakpoint(*this)));
LOG_FDB << "added 'end' breakpoint"<< std::endl;
}
void formula_debugger::add_breakpoint_step_into()
{
breakpoints_.push_back(breakpoint_ptr(new step_in_breakpoint(*this)));
LOG_FDB << "added 'step into' breakpoint"<< std::endl;
}
void formula_debugger::add_breakpoint_step_out()
{
breakpoints_.push_back(breakpoint_ptr(new step_out_breakpoint(*this)));
LOG_FDB << "added 'step out' breakpoint"<< std::endl;
}
void formula_debugger::add_breakpoint_next()
{
breakpoints_.push_back(breakpoint_ptr(new next_breakpoint(*this)));
LOG_FDB << "added 'next' breakpoint"<< std::endl;
}
} // end of namespace game_logic
| techtonik/wesnoth | src/formula_debugger.cpp | C++ | gpl-2.0 | 8,738 |
#include "botpch.h"
#include "../../playerbot.h"
#include "BuyAction.h"
#include "../ItemVisitors.h"
#include "../values/ItemCountValue.h"
using namespace ai;
bool BuyAction::Execute(Event event)
{
string link = event.getParam();
ItemIds itemIds = chat->parseItems(link);
if (itemIds.empty())
return false;
Player* master = GetMaster();
if (!master)
return false;
ObjectGuid vendorguid = master->GetSelectionGuid();
if (!vendorguid)
return false;
Creature *pCreature = bot->GetNPCIfCanInteractWith(vendorguid,UNIT_NPC_FLAG_VENDOR);
if (!pCreature)
{
ai->TellMaster("Cannot talk to vendor");
return false;
}
VendorItemData const* tItems = pCreature->GetVendorItems();
if (!tItems)
{
ai->TellMaster("This vendor has no items");
return false;
}
for (ItemIds::iterator i = itemIds.begin(); i != itemIds.end(); i++)
{
for (uint32 slot = 0; slot < tItems->GetItemCount(); slot++)
{
if (tItems->GetItem(slot)->item == *i)
{
bot->BuyItemFromVendor(vendorguid, *i, 1, NULL_BAG, NULL_SLOT);
ai->TellMaster("Bought item");
}
}
}
return true;
}
| H0zen/M0-server | src/modules/Bots/playerbot/strategy/actions/BuyAction.cpp | C++ | gpl-2.0 | 1,267 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php echo $this->language; ?>" lang="<?php echo $this->language;?>" >
<?php
/* @package mx_joomla121 Template
* @author mixwebtemplates http://www.mixwebtemplates.com
* @copyright Copyright (c) 2006 - 2012 mixwebtemplates. All rights reserved
*/
defined( '_JEXEC' ) or die( 'Restricted access' );
if(!defined('DS')){define('DS',DIRECTORY_SEPARATOR);}
$tcParams = '';
include_once(dirname(__FILE__).DS.'tclibs'.DS.'head.php');
include_once(dirname(__FILE__).DS.'tclibs'.DS.'settings.php');
$tcParams .= '<body id="tc">';
$tcParams .= TCShowModule('adverts', 'mx_xhtml', 'container');
$tcParams .= '<div id="mx_wrapper" class="mx_wrapper">';
$tcParams .= TCShowModule('header', 'mx_xhtml', 'container');
$tcParams .= '<jdoc:include type="modules" name="sign_in" />';
include_once(dirname(__FILE__).DS.'tclibs'.DS.'slider.php');
include_once(dirname(__FILE__).DS.'tclibs'.DS.'social.php');
$tcParams .= TCShowModule('slider', 'mx_xhtml', 'container');
$tcParams .= TCShowModule('top', 'mx_xhtml', 'container');
$tcParams .= TCShowModule('info', 'mx_xhtml', 'container');
$tcParams .= '<section class="mx_wrapper_info mx_section">'
.'<div class="container mx_group"><jdoc:include type="modules" name="search_jobs_box" />'
// .'<div><jdoc:include type="modules" name="test1" /></div>'
.'</div></section>';
//Latest Jobs blocks
$tcParams .= '<div class="row"><jdoc:include type="modules" name="latest_jobs" /></div>'
;
//Slide top
$tcParams .= '<section class="mx_wrapper_top mx_section">'
.'<div class="container mx_group">'
.'<jdoc:include type="modules" name="top_slide" />'
.'</div></section>';
//very maintop content block
$tcParams .= '<section class="mx_wrapper_maintop mx_section">'
.'<div class="container mx_group">'
.'<jdoc:include type="modules" name="top_block" />'
.'</div></section>';
$tcParams .= TCShowModule('maintop', 'mx_xhtml', 'container');
$tcParams .= '<main class="mx_main container clearfix">'.$component.'</main>';
$tcParams .= TCShowModule('mainbottom', 'mx_xhtml', 'container').
TCShowModule('feature', 'mx_xhtml', 'container').
TCShowModule('bottom', 'mx_xhtml', 'container').
TCShowModule('footer', 'mx_xhtml', 'container');
//Advise widget
$tcParams .= '<div class="row">'
.'<jdoc:include type="modules" name="advise-widget" />'
.'</div>';
//Resume nav bar
$tcParams .= '<div class="mod-content clearfix">'
.'<jdoc:include type="modules" name="Create_ResumeNavBar" />'
.'</div>';
//Feature blocks
$tcParams .= '<section class="mx_wrapper_feature mx_section">'
.'<div class="container mx_group">'
.'<jdoc:include type="modules" name="feature-1" />'
.'</div></section>';
//Footer blocks
$tcParams .= '<section class="mx_wrapper_bottom mx_section">'
.'<div class="container mx_group">'
.'<jdoc:include type="modules" name="footer_block" />'
.'</div></section>';
$tcParams .= '<footer class="mx_wrapper_copyright mx_section">'.
'<div class="container clearfix">'.
'<div class="col-md-12">'.($copyright ? '<div style="padding:10px;">'.$cpright.' </div>' : ''). /* You CAN NOT remove (or unreadable) this without mixwebtemplates.com permission */ //'<div style="padding-bottom:10px; text-align:right; ">Designed by <a href="http://www.mixwebtemplates.com/" title="Visit mixwebtemplates.com!" target="blank">mixwebtemplates.com</a></div>'.
'</div>'.
'</div>'.
'</footer>';
$tcParams .='</div>';
include_once(dirname(__FILE__).DS.'tclibs'.DS.'debug.php');
$tcParams .='</body>';
$tcParams .='</html>';
echo $tcParams;
?> | sondang86/hasico | templates/temp_template/index.php | PHP | gpl-2.0 | 3,934 |
/*
* main.cpp
*
* Created on: 30 Xan, 2015
* Author: marcos
*/
#include "common.h"
extern "C" {
#include "perm.h"
}
/**
* \brief Print application help
*/
void printHelp() {
cout << "diffExprpermutation: Find differentially expressed genes from a set of control and cases samples using a permutation strategy." << endl;
cout << "diffExprPermutation -f input [--c1 condition1 --c2 condition2 -n permutations -H stopHits -s statistic] -o outFile" << endl;
cout << "Inputs:" << endl;
cout << " -f input Space separated table. Format: sampleName group lib.size norm.factors gene1 gene2 ... geneN" << endl;
cout << "Outputs:" << endl;
cout << " -o outFile Output file name" << endl;
cout << "Options:" << endl;
cout << " --c1 condition1 Condition that determine one of two groups [default: case]" << endl;
cout << " --c2 condition2 Condition that determine other group [default: control]" << endl;
cout << " -s statistic Statistic to compute pvalue median|perc25|perc75|x [default: median]" << endl;
cout << " -p percentile mode Mode for selection of percentile auto|linear|nearest [default: auto]" << endl;
cout << " -t n_threads Number of threads [default: 1]" << endl;
}
/**
* \brief Check Arguments
* \param string fileInput - Name input file
* \param string outFile - Name output file
* \param unsigned int chunks - Number of chunks to create
* \param string condition1 - First condition group. Usually case.
* \param string condition1 - Second condition group. Usually control.
*/
inline bool argumentChecking(const string &fileInput,
const string &outFile,
const string &condition1,
const string &condition2)
{
bool bWrong = false;
if (fileInput.empty())
{
cout << "Sorry!! No input file was specified!!" << endl;
return true;
}
if (outFile.empty())
{
cout << "Sorry!! No output file was specified!!" << endl;
return true;
}
if (condition1.empty())
{
cout << "Sorry!! Condition group 1 is empty!!" << endl;
return true;
}
if (condition2.empty())
{
cout << "Sorry!! Condition group 2 is empty!!" << endl;
return true;
}
return bWrong;
}
int main(int argc, char **argv)
{
string fileInput = "";
string outFile = "";
string condition1 = "case";
string condition2 = "control";
string percentile_mode = "auto";
cp_mode pc_mode = AUTO;
int n_threads = 1;
string statistic = "median";
double fStatisticValue = 0;
bool doMedian = true;
vector<Gene> vGenes; // vector of genes where each gene has a vector of sampleGenes, each sampleGene contains sample name expression value and group
/**
* BRACA1 -> A,true,0.75
* -> B,false,0.85
* ...
* BRACA2 -> A,true,0.15
* -> B,false,0.20
* ...
*/
// 1.Process parameters
for (int i = 1; i < argc; i++)
{
if (strcmp(argv[i], "-f") == 0)
{
fileInput = argv[++i];
}
else if (strcmp(argv[i], "-o") == 0)
{
outFile = argv[++i];
}
else if (strcmp(argv[i], "--c1") == 0)
{
condition1 = argv[++i];
}
else if (strcmp(argv[i], "--c2") == 0)
{
condition2 = argv[++i];
}
else if (strcmp(argv[i], "-s") == 0)
{
statistic = argv[++i];
}
else if (strcmp(argv[i], "-p") == 0)
{
percentile_mode = argv[++i];
}
else if (strcmp(argv[i], "-t") == 0)
{
n_threads = atoi(argv[++i]);
if (n_threads < 1) n_threads = 1;
}
else if (strcmp(argv[i],"-h") == 0)
{
printHelp();
return 0;
}
}
// Check Arguments
if(argumentChecking(fileInput, outFile, condition1, condition2))
{
return -1;
}
// Updates statistic
string headerOutput = "gene\tdiff_median\tmedianCase\tmedianControl\tfold_change\tmedian_pv\tmedian_pv_fdr";
if (statistic.compare("perc25") == 0)
{
fStatisticValue = 25.0;
doMedian = false;
headerOutput = "gene\tdiff_lowerq\tlowerqCase\tlowerqControl\tfold_change\tlowerq_pv\tlowerq_pv_fdr";
}
else if (statistic.compare("perc75") == 0)
{
fStatisticValue = 75.0;
doMedian = false;
headerOutput = "gene\tdiff_UpQ\tupperqCase\tupperqControl\tfold_change\tupperq_pv\tupper_pv_fdr";
}
else
{
char *p;
double x = strtod(statistic.c_str(), &p);
if (x > 0.0 && x < 100.0)
{
fStatisticValue = x;
doMedian = false;
ostringstream s;
s << "gene\tdiff_" << x << "%\t" << x << "\%_Case\t" << x << "\%_Control\tfold_change\t" << x << "\%_pv\t" << x << "\%_pv_fdr";
headerOutput = s.str();
}
}
if (percentile_mode.compare("auto") == 0) pc_mode = AUTO;
else if (percentile_mode.compare("linear") == 0) pc_mode = LINEAR_INTERPOLATION;
else if (percentile_mode.compare("nearest") == 0) pc_mode = NEAREST_RANK;
else
{
cerr << "Percentile mode '" << percentile_mode << "' not recognized" << endl;
return -1;
}
// Parsing Input file
if (!loadFileInfo(fileInput, vGenes, condition1, condition2))
{
cerr << "Sorry!! Can not open file " << fileInput << endl;
return -1;
}
// Allocate and make C structure for permutation routine
struct perm_data pdata;
pdata.n_cases = vGenes.begin()->nCases;
pdata.n_controls = vGenes.begin()->nControls;
int n_samples = pdata.n_cases + pdata.n_controls;
pdata.n_var = vGenes.size();
pdata.data = (float *)malloc(sizeof(float) * pdata.n_var * (4 + n_samples));
pdata.fold_change = pdata.data + pdata.n_var * n_samples;
pdata.pc_cases = pdata.fold_change + pdata.n_var;
pdata.pc_controls = pdata.pc_cases + pdata.n_var;
pdata.pc_diff = pdata.pc_controls + pdata.n_var;
pdata.grp = (group *)malloc(sizeof(group) * n_samples);
pdata.p_values = (double *)malloc(sizeof(double) * pdata.n_var);
// Copy expression data
float *tp = pdata.data;
for (vector<Gene>::iterator gene_it = vGenes.begin(); gene_it != vGenes.end(); ++gene_it)
{
for (vector<SampleGene>::const_iterator iter = gene_it->vGeneValues.begin();iter != gene_it->vGeneValues.end(); ++iter)
{
(*tp++) = (float)iter->expressionValue;
}
}
// Copy group information
int ix = 0;
for (vector<bool>::const_iterator iter = vGenes.begin()->vGroup.begin(); iter != vGenes.begin()->vGroup.end(); ++iter)
{
pdata.grp[ix++] = *iter ? CASE : CONTROL;
}
// Calculate exact permutation p-values
check_percentile(doMedian ? 50.0 : fStatisticValue, pc_mode, n_threads,&pdata);
vector<double> vPvalues;
int i = 0;
for (vector<Gene>::iterator iter = vGenes.begin(); iter != vGenes.end(); ++iter)
{
// Copy results from pdata struture
(*iter).originalDiff = (double)pdata.pc_diff[i];
(*iter).originalMedianCases = (double)pdata.pc_cases[i];
(*iter).originalMedianControl = (double)pdata.pc_controls[i];
(*iter).foldChange = pdata.fold_change[i];
(*iter).pValue = pdata.p_values[i];
// Add pvalue to a vector of pvalues for being correcte by FDR
vPvalues.push_back((*iter).pValue);
i++;
}
vector<double> correctedPvalues;
correct_pvalues_fdr(vPvalues, correctedPvalues);
// Print to file
std::ofstream outfile(outFile.c_str(), std::ofstream::out);
// Header File
outfile << headerOutput << endl;
vector<double>::const_iterator iterCorrected = correctedPvalues.begin();
outfile.precision(15);
for (vector<Gene>::const_iterator iter = vGenes.begin(); iter != vGenes.end();++iter)
{
outfile << (*iter).geneName << "\t" << (*iter).originalDiff << "\t" << (*iter).originalMedianCases;
outfile << "\t" << (*iter).originalMedianControl << "\t" << (*iter).foldChange << "\t" << (*iter).pValue << "\t" << (*iterCorrected) << endl;
++iterCorrected;
}
free(pdata.grp);
free(pdata.data);
free(pdata.p_values);
outfile.close();
return 0;
}
| MarcosFernandez/diffExprPermutation | main.cpp | C++ | gpl-2.0 | 8,112 |
//
// iTermBoxDrawingBezierCurveFactory.h
// iTerm2
//
// Created by George Nachman on 7/15/16.
//
//
#import <Cocoa/Cocoa.h>
@interface iTermBoxDrawingBezierCurveFactory : NSObject
+ (NSCharacterSet *)boxDrawingCharactersWithBezierPaths;
+ (NSArray<NSBezierPath *> *)bezierPathsForBoxDrawingCode:(unichar)code
cellSize:(NSSize)cellSize
scale:(CGFloat)scale;
@end
| DrabWeb/iTerm2 | sources/iTermBoxDrawingBezierCurveFactory.h | C | gpl-2.0 | 472 |
/* Remove some alpha blended PNGs to avoid problems with antiquated IE <= 6. It doesn't look much different unless you look closely. */
div.post-content, span.post-frame-top, span.post-frame-bottom { background-image: url(images/post-ie.png);height:1px; overflow:visible}
div.widget-center, span.widget-top, span.widget-bottom { background-image: url(images/widget-ie.png);height:1px; overflow:visible}
div.post-body img { margin: 0 5px}
div.post-footer {height: 1px; overflow: visible}
/*
Some crude fixes for ie5.5 to get it to a useable state, not going to worry about 5.5 beyond this.
*/
body.ie5 div.widget-centre, body.ie55 div.widget-centre{ width: 290px}
body.ie5 div.container, body.ie55 div.container{ margin-left: 20px;} /* As ie55 won't centre the container on the page I'll move it a small amount away from the edge. */
body.ie5 div#comments-block, body.ie55 div#comments-block{width:543px} | dlshad/aymta | themes/grassland/css/ie.css | CSS | gpl-2.0 | 920 |
#ifndef _LINUX_PRIO_HEAP_H
#define _LINUX_PRIO_HEAP_H
#include <linux/gfp.h>
struct ptr_heap {
void **ptrs;
int max;
int size;
int (*gt)(void *, void *);
};
extern int heap_init(struct ptr_heap *heap, size_t size, gfp_t gfp_mask,
int (*gt)(void *, void *));
void heap_free(struct ptr_heap *heap);
extern void *heap_insert(struct ptr_heap *heap, void *p);
#endif
| leemgs/OptimusOneKernel-KandroidCommunity | include/linux/prio_heap.h | C | gpl-2.0 | 388 |
bjxypingjiao
============
滨江学院评教系统
| calchen/bjxypingjiao | README.md | Markdown | gpl-2.0 | 52 |
<?php
include_once '../libs/Connection.php';
include_once '../libs/tree_editor.php';
class tree_performance extends tree_editor{
public function __construct(){
parent::__construct();
if(!isset($_POST['action'])){
header("content-type:text/xml;charset=UTF-8");
if(isset($_GET['refresh'])){
$refresh = $_GET['refresh'];
}else{
$refresh = false;
}
echo ($this->getXml($_GET['id'],$_GET['autoload'],$refresh));
}else{
$this->db->query("START TRANSACTION");
$response = "";
$response = $this->parseRequest();
$this->db->query("COMMIT");
echo json_encode($response);
}
}
public function getXmlTree($id=0,$rf,$autoload = true){
$xml = '<tree id="'.$id.'">';
$xml .= $this->getXmlMyPerformanceAuto($id,$rf,$autoload);
$xml .= '</tree>';
return $xml;
}
/********* Top level *****************/
protected function getXmlMyPerformanceAuto($id,$rf,$autoload){
if($autoload=='false'){
$xml = '<item child="1" text="My Studygroups" id="mystg" im1="folder_open.png" im2="folder_closed.png">';
$xml .= $this->getItemLoad(0,"mystg",$rf,false);
$xml .= '</item>';
}else{
if($id == "0"){
$xml = '<item child="1" text="My Studygroups" id="mystg" im1="folder_open.png" im2="folder_closed.png">';
}else{
$xml .= $this->getItemLoad(0,$id,$rf,true);
$xml .= '</item>';
}
}
return $xml;
}
protected function getChildItems($type){
$items = array();
switch ($type) {
case 'studygroup':
$items[] = array('table' => 'performance',
'id' => 'performance',
'pid' => 'studygroup_id',
);
break;
case 'mystg':
$items[] = array('table' => 'studygroups',
'id' => 'studygroup',
'pid' => 'mystg',
);
break;
default:
break;
}
return $items;
}
public function getTableInfoFromType($type){
switch ($type) {
case 'studygroup':
$table = "studygroups";
$id_name = "studygroup";
break;
case 'mystg':
$table = "mystg";
$id_name = "mystg";
break;
case 'performance':
$table = "performance";
$id_name = "performance";
break;
default:
break;
}
return array('table' => $table, 'id_name' => $id_name);
}
public function addPerformanceItem($item){
switch($item){
case "performance":
$values = array(
'studygroup_id' => $_POST["id"],
'public' => 1
);
break;
}
$itemInfo = $this->getTableInfoFromType($item);
$response = $this->addItem($itemInfo['table'],$values,$item);
return $response;
}
public function addNotPublicPerformanceItem($item){
switch($item){
case "performance":
$values = array(
'studygroup_id' => $_POST["id"],
'public' => 0
);
break;
}
$itemInfo = $this->getTableInfoFromType($item);
$response = $this->addItem($itemInfo['table'],$values,$item);
return $response;
}
public function deletePerformanceItem($id,$item){
$itemInfo = $this->getTableInfoFromType($item);
$response = $this->removeItem($id,$itemInfo['table'],$itemInfo['id_name']);
return $response;
}
public function sharePerformanceItem($id,$item){
$itemInfo = $this->getTableInfoFromType($item);
$response = $this->shareItem($id,$itemInfo['table'],$itemInfo['id_name']);
return $response;
}
public function privatePerformanceItem($id,$item){
$itemInfo = $this->getTableInfoFromType($item);
$response = $this->privateItem($id,$itemInfo['table'],$itemInfo['id_name']);
return $response;
}
public function duplicatePerformanceItem($id,$item){
$itemInfo = $this->getTableInfoFromType($item);
$response = $this->duplicateItem($id,$itemInfo['table'],$itemInfo['id_name']);
return $response;
}
public function movePerformanceItem($ids,$item,$sid,$lid,$par){
$itemInfo = $this->getTableInfoFromType($item);
switch($item){
case "performance":
$parents = array(
'studygroup_id' => $_POST['studygroup']
);
break;
}
$response = $this->setParent($sid,$parents,$lid,$itemInfo['id_name'],$itemInfo['table']);
return $response;
}
public function moveDublPerformanceItem($ids,$item,$sid,$lid,$par){
$itemInfo = $this->getTableInfoFromType($item);
switch($item){
case "assignment":
$parents = array(
'studygroup_id' => $_POST['studygroup']
);
break;
}
$response = $this->duplicatePerformanceItem($sid,$item);
$response = $this->setParent($response['id'],$parents,$lid,$itemInfo['id_name'],$itemInfo['table']);
return $response;
}
public function getPerformanceInfo($id){
$result = $this->db->query("
SELECT perf.title_en as title_p, stg.title_en as title_g
FROM performance perf
inner join studygroups stg on perf.studygroup_id=stg.studygroup_id
where perf.performance_id=$id
");
while($row = mysql_fetch_assoc($result)){
$name = $row['title_p'];
$studygroup = $row['title_g'];
}
return array(
"name" => $name,
"studygroup" => $studygroup
);
}
public function getPerformanceDescroption($id){
$description = "";
$notes = "";
$result = $this->db->query("SELECT content_en,owner_notes FROM performance WHERE performance_id=$id LIMIT 1");
while($row = mysql_fetch_assoc($result)){
$description = $row['content_en'];
$notes = $row['owner_notes'];
}
return array('content' => $description,'notes' => $notes);
}
public function putPerformanceDescription($id,$content,$notes){
$result = $this->db->query("UPDATE performance SET content_en='$content',owner_notes='$notes' WHERE performance_id=$id");
return array('update' => true);
}
function parseRequest(){
if(isset($_POST['action'])){
$action = $_POST['action'];
$act = explode("_", $action);
$id = $_POST['id'];
$response = "";
$id = $_POST['id'];
$name = $_POST['name'];
$type = $_POST['node'];
$ids = explode(",", $_POST['ids']);
$par = explode('_', $_POST['tid']);
$sid = $_POST['sid'];
$lid = $_POST['lid'];
$content = $_POST['content'];
$notes = $_POST['notes'];
$description = $_POST['description'];
switch($act[0]){
case "new":
$response = $this->addPerformanceItem($act[1]);
break;
case "delete":
$response = $this->deletePerformanceItem($id,$act[1]);
break;
case "duplicate":
$response = $this->duplicatePerformanceItem($id,$act[1]);
break;
case "rename":
$table = $this->getTableInfoFromType($type);
$response = $this->rename($id,$name,$table['table'],$table['id_name']);
break;
case "move":
$response = $this->movePerformanceItem($ids,$act[1],$sid,$lid,$par);
break;
case "movedupl":
$response = $this->moveDublPerformanceItem($ids,$act[1],$sid,$lid,$par);
break;
case "getassignment":
$response = $this->getAssignmentContent($id);
$response["info"] = $this->getAssignmentInfo($id);
break;
case "putassignment":
$response = $this->putAssignmentContent($id,$content,$notes);
break;
case "share":
$response = $this->sharePerformanceItem($id,$act[1]);
break;
case "private":
$response = $this->privatePerformanceItem($id,$act[1]);
break;
case "getassessperformance":
$response = $this->getPerformanceDescroption($id);
$response["info"] = $this->getPerformanceInfo($id);
$response["info"]["view_assessments"] = dlang("header_asignment_view_performance","View Performance");
$response["info"]["assessment_image"] = "dhtmlx/dhtmlxTree/codebase/imgs/csh_schoolmule/performance.png";
break;
case "getperformance":
$response = $this->getPerformanceDescroption($id);
$response["info"] = $this->getPerformanceInfo($id);
$response["info"]["view_assessments"] = "View Assessments";
$response["info"]["assessment_image"] = "dhtmlx/dhtmlxTree/codebase/imgs/csh_schoolmule/assessment.png";
break;
case "putperformance":
$response = $this->putPerformanceDescription($id,$_POST['content'],$_POST['notes']);
break;
case "newnotpublic":
$response = $this->addNotPublicPerformanceItem($act[1]);
}
return $response;
}else{
return false;
}
}
}
?> | ya6adu6adu/schoolmule | connectors/tree_performance.php | PHP | gpl-2.0 | 8,691 |
package imageresizerforandroid;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.swing.ImageIcon;
/**
*
* @author fonter
*/
public class ImageContainer {
private final BufferedImage image;
private ImageIcon cache;
private final File file;
public ImageContainer (BufferedImage image, File file) {
this.image = image;
this.file = file;
}
public String getNormalizeName () {
String name = file.getName();
int pos = name.lastIndexOf(".");
if (pos > 0) {
return name.substring(0, pos);
}
return name;
}
public ImageIcon getCache () {
return cache;
}
public File getFile () {
return file;
}
public BufferedImage getImage () {
return image;
}
public void setCache (ImageIcon cache) {
this.cache = cache;
}
public boolean isCacheCreate () {
return cache != null;
}
}
| pinkiesky/ImageResizerForAndroid | ImageResizerForAndroid/src/imageresizerforandroid/ImageContainer.java | Java | gpl-2.0 | 995 |
from buildbot.status.web.auth import IAuth
class Authz(object):
"""Decide who can do what."""
knownActions = [
# If you add a new action here, be sure to also update the documentation
# at docs/cfg-statustargets.texinfo
'gracefulShutdown',
'forceBuild',
'forceAllBuilds',
'pingBuilder',
'stopBuild',
'stopAllBuilds',
'cancelPendingBuild',
]
def __init__(self,
default_action=False,
auth=None,
**kwargs):
self.auth = auth
if auth:
assert IAuth.providedBy(auth)
self.config = dict( (a, default_action) for a in self.knownActions )
for act in self.knownActions:
if act in kwargs:
self.config[act] = kwargs[act]
del kwargs[act]
if kwargs:
raise ValueError("unknown authorization action(s) " + ", ".join(kwargs.keys()))
def advertiseAction(self, action):
"""Should the web interface even show the form for ACTION?"""
if action not in self.knownActions:
raise KeyError("unknown action")
cfg = self.config.get(action, False)
if cfg:
return True
return False
def needAuthForm(self, action):
"""Does this action require an authentication form?"""
if action not in self.knownActions:
raise KeyError("unknown action")
cfg = self.config.get(action, False)
if cfg == 'auth' or callable(cfg):
return True
return False
def actionAllowed(self, action, request, *args):
"""Is this ACTION allowed, given this http REQUEST?"""
if action not in self.knownActions:
raise KeyError("unknown action")
cfg = self.config.get(action, False)
if cfg:
if cfg == 'auth' or callable(cfg):
if not self.auth:
return False
user = request.args.get("username", ["<unknown>"])[0]
passwd = request.args.get("passwd", ["<no-password>"])[0]
if user == "<unknown>" or passwd == "<no-password>":
return False
if self.auth.authenticate(user, passwd):
if callable(cfg) and not cfg(user, *args):
return False
return True
return False
else:
return True # anyone can do this..
| centrumholdings/buildbot | buildbot/status/web/authz.py | Python | gpl-2.0 | 2,513 |
#! /usr/bin/env python
# encoding: UTF-8
'''give access permission for files in this folder'''
| anandkp92/waf | gui/__init__.py | Python | gpl-2.0 | 96 |
## IGSuite 4.0.1
## Procedure: SpreadsheetWriteExcelUtility.pm
## Last update: 01/07/2010
#############################################################################
# IGSuite 4.0.1 - Provides an Office Suite by simple web interface #
# Copyright (C) 2002 Dante Ortolani [LucaS] #
# #
# 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. #
#############################################################################
package Spreadsheet::WriteExcel::Utility;
###############################################################################
#
# Utility - Helper functions for Spreadsheet::WriteExcel.
#
# Copyright 2000-2008, John McNamara, [email protected]
#
#
use Exporter;
use strict;
use autouse 'Date::Calc' => qw(Delta_DHMS Decode_Date_EU Decode_Date_US);
use autouse 'Date::Manip' => qw(ParseDate Date_Init);
# Do all of the export preparation
use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
# Row and column functions
my @rowcol = qw(
xl_rowcol_to_cell
xl_cell_to_rowcol
xl_inc_row
xl_dec_row
xl_inc_col
xl_dec_col
);
# Date and Time functions
my @dates = qw(
xl_date_list
xl_date_1904
xl_parse_time
xl_parse_date
xl_parse_date_init
xl_decode_date_EU
xl_decode_date_US
);
@ISA = qw(Exporter);
@EXPORT_OK = ();
@EXPORT = (@rowcol, @dates);
%EXPORT_TAGS = (
rowcol => \@rowcol,
dates => \@dates
);
$VERSION = '2.20';
=head1 NAME
Utility - Helper functions for Spreadsheet::WriteExcel.
=head1 VERSION
This document refers to version 0.03 of Spreadsheet::WriteExcel::Utility, released March, 2002.
=head1 SYNOPSIS
Functions to help with some common tasks when using Spreadsheet::WriteExcel.
These functions mainly relate to dealing with rows and columns in A1 notation and to handling dates and times.
use Spreadsheet::WriteExcel::Utility; # Import everything
($row, $col) = xl_cell_to_rowcol('C2'); # (1, 2)
$str = xl_rowcol_to_cell(1, 2); # C2
$str = xl_inc_col('Z1' ); # AA1
$str = xl_dec_col('AA1' ); # Z1
$date = xl_date_list(2002, 1, 1); # 37257
$date = xl_parse_date("11 July 1997"); # 35622
$time = xl_parse_time('3:21:36 PM'); # 0.64
$date = xl_decode_date_EU("13 May 2002"); # 37389
=head1 DESCRIPTION
This module provides a set of functions to help with some common tasks encountered when using the Spreadsheet::WriteExcel module. The two main categories of function are:
Row and column functions: these are used to deal with Excel's A1 representation of cells. The functions in this category are:
xl_rowcol_to_cell
xl_cell_to_rowcol
xl_inc_row
xl_dec_row
xl_inc_col
xl_dec_col
Date and Time functions: these are used to convert dates and times to the numeric format used by Excel. The functions in this category are:
xl_date_list
xl_date_1904
xl_parse_time
xl_parse_date
xl_parse_date_init
xl_decode_date_EU
xl_decode_date_US
All of these functions are exported by default. However, you can use import lists if you wish to limit the functions that are imported:
use Spreadsheet::WriteExcel::Utility; # Import everything
use Spreadsheet::WriteExcel::Utility qw(xl_date_list); # xl_date_list only
use Spreadsheet::WriteExcel::Utility qw(:rowcol); # Row/col functions
use Spreadsheet::WriteExcel::Utility qw(:dates); # Date functions
=head1 ROW AND COLUMN FUNCTIONS
Spreadsheet::WriteExcel supports two forms of notation to designate the position of cells: Row-column notation and A1 notation.
Row-column notation uses a zero based index for both row and column while A1 notation uses the standard Excel alphanumeric sequence of column letter and 1-based row. Columns range from A to IV i.e. 0 to 255, rows range from 1 to 16384 in Excel 5 and 65536 in Excel 97. For example:
(0, 0) # The top left cell in row-column notation.
('A1') # The top left cell in A1 notation.
(1999, 29) # Row-column notation.
('AD2000') # The same cell in A1 notation.
Row-column notation is useful if you are referring to cells programmatically:
for my $i (0 .. 9) {
$worksheet->write($i, 0, 'Hello'); # Cells A1 to A10
}
A1 notation is useful for setting up a worksheet manually and for working with formulas:
$worksheet->write('H1', 200);
$worksheet->write('H2', '=H7+1');
The functions in the following sections can be used for dealing with A1 notation, for example:
($row, $col) = xl_cell_to_rowcol('C2'); # (1, 2)
$str = xl_rowcol_to_cell(1, 2); # C2
Cell references in Excel can be either relative or absolute. Absolute references are prefixed by the dollar symbol as shown below:
A1 # Column and row are relative
$A1 # Column is absolute and row is relative
A$1 # Column is relative and row is absolute
$A$1 # Column and row are absolute
An absolute reference only has an effect if the cell is copied. Refer to the Excel documentation for further details. All of the following functions support absolute references.
=cut
###############################################################################
###############################################################################
=head2 xl_rowcol_to_cell($row, $col, $row_absolute, $col_absolute)
Parameters: $row: Integer
$col: Integer
$row_absolute: Boolean (1/0) [optional, default is 0]
$col_absolute: Boolean (1/0) [optional, default is 0]
Returns: A string in A1 cell notation
This function converts a zero based row and column cell reference to a A1 style string:
$str = xl_rowcol_to_cell(0, 0); # A1
$str = xl_rowcol_to_cell(0, 1); # B1
$str = xl_rowcol_to_cell(1, 0); # A2
The optional parameters C<$row_absolute> and C<$col_absolute> can be used to indicate if the row or column is absolute:
$str = xl_rowcol_to_cell(0, 0, 0, 1); # $A1
$str = xl_rowcol_to_cell(0, 0, 1, 0); # A$1
$str = xl_rowcol_to_cell(0, 0, 1, 1); # $A$1
See L<ROW AND COLUMN FUNCTIONS> for an explanation of absolute cell references.
=cut
###############################################################################
#
# xl_rowcol_to_cell($row, $col, $row_absolute, $col_absolute)
#
sub xl_rowcol_to_cell {
my $row = $_[0];
my $col = $_[1];
my $row_abs = $_[2] ? '$' : '';
my $col_abs = $_[3] ? '$' : '';
my $int = int ($col / 26);
my $frac = $col % 26;
my $chr1 =''; # Most significant character in AA1
if ($int > 0) {
$chr1 = chr( ord('A') + $int -1 );
}
my $chr2 = chr( ord('A') + $frac );
# Zero index to 1-index
$row++;
return $col_abs . $chr1 . $chr2 . $row_abs. $row;
}
###############################################################################
###############################################################################
=head2 xl_cell_to_rowcol($string)
Parameters: $string String in A1 format
Returns: List ($row, $col)
This function converts an Excel cell reference in A1 notation to a zero based row and column. The function will also handle Excel's absolute, C<$>, cell notation.
my ($row, $col) = xl_cell_to_rowcol('A1'); # (0, 0)
my ($row, $col) = xl_cell_to_rowcol('B1'); # (0, 1)
my ($row, $col) = xl_cell_to_rowcol('C2'); # (1, 2)
my ($row, $col) = xl_cell_to_rowcol('$C2' ); # (1, 2)
my ($row, $col) = xl_cell_to_rowcol('C$2' ); # (1, 2)
my ($row, $col) = xl_cell_to_rowcol('$C$2'); # (1, 2)
=cut
###############################################################################
#
# xl_cell_to_rowcol($string)
#
# Returns: ($row, $col, $row_absolute, $col_absolute)
#
# The $row_absolute and $col_absolute parameters aren't documented because they
# mainly used internally and aren't very useful to the user.
#
sub xl_cell_to_rowcol {
my $cell = shift;
$cell =~ /(\$?)([A-I]?[A-Z])(\$?)(\d+)/;
my $col_abs = $1 eq "" ? 0 : 1;
my $col = $2;
my $row_abs = $3 eq "" ? 0 : 1;
my $row = $4;
# Convert base26 column string to number
# All your Base are belong to us.
my @chars = split //, $col;
my $expn = 0;
$col = 0;
while (@chars) {
my $char = pop(@chars); # LS char first
$col += (ord($char) -ord('A') +1) * (26**$expn);
$expn++;
}
# Convert 1-index to zero-index
$row--;
$col--;
return $row, $col, $row_abs, $col_abs;
}
###############################################################################
###############################################################################
=head2 xl_inc_row($string)
Parameters: $string, a string in A1 format
Returns: Incremented string in A1 format
This functions takes a cell reference string in A1 notation and increments the row. The function will also handle Excel's absolute, C<$>, cell notation:
my $str = xl_inc_row('A1' ); # A2
my $str = xl_inc_row('B$2' ); # B$3
my $str = xl_inc_row('$C3' ); # $C4
my $str = xl_inc_row('$D$4'); # $D$5
=cut
###############################################################################
#
# xl_inc_row($string)
#
sub xl_inc_row {
my $cell = shift;
my ($row, $col, $row_abs, $col_abs) = xl_cell_to_rowcol($cell);
return xl_rowcol_to_cell(++$row, $col, $row_abs, $col_abs);
}
###############################################################################
###############################################################################
=head2 xl_dec_row($string)
Parameters: $string, a string in A1 format
Returns: Decremented string in A1 format
This functions takes a cell reference string in A1 notation and decrements the row. The function will also handle Excel's absolute, C<$>, cell notation:
my $str = xl_dec_row('A2' ); # A1
my $str = xl_dec_row('B$3' ); # B$2
my $str = xl_dec_row('$C4' ); # $C3
my $str = xl_dec_row('$D$5'); # $D$4
=cut
###############################################################################
#
# xl_dec_row($string)
#
# Decrements the row number of an Excel cell reference in A1 notation.
# For example C4 to C3
#
# Returns: a cell reference string.
#
sub xl_dec_row {
my $cell = shift;
my ($row, $col, $row_abs, $col_abs) = xl_cell_to_rowcol($cell);
return xl_rowcol_to_cell(--$row, $col, $row_abs, $col_abs);
}
###############################################################################
###############################################################################
=head2 xl_inc_col($string)
Parameters: $string, a string in A1 format
Returns: Incremented string in A1 format
This functions takes a cell reference string in A1 notation and increments the column. The function will also handle Excel's absolute, C<$>, cell notation:
my $str = xl_inc_col('A1' ); # B1
my $str = xl_inc_col('Z1' ); # AA1
my $str = xl_inc_col('$B1' ); # $C1
my $str = xl_inc_col('$D$5'); # $E$5
=cut
###############################################################################
#
# xl_inc_col($string)
#
# Increments the column number of an Excel cell reference in A1 notation.
# For example C3 to D3
#
# Returns: a cell reference string.
#
sub xl_inc_col {
my $cell = shift;
my ($row, $col, $row_abs, $col_abs) = xl_cell_to_rowcol($cell);
return xl_rowcol_to_cell($row, ++$col, $row_abs, $col_abs);
}
###############################################################################
###############################################################################
=head2 xl_dec_col($string)
Parameters: $string, a string in A1 format
Returns: Decremented string in A1 format
This functions takes a cell reference string in A1 notation and decrements the column. The function will also handle Excel's absolute, C<$>, cell notation:
my $str = xl_dec_col('B1' ); # A1
my $str = xl_dec_col('AA1' ); # Z1
my $str = xl_dec_col('$C1' ); # $B1
my $str = xl_dec_col('$E$5'); # $D$5
=cut
###############################################################################
#
# xl_dec_col($string)
#
sub xl_dec_col {
my $cell = shift;
my ($row, $col, $row_abs, $col_abs) = xl_cell_to_rowcol($cell);
return xl_rowcol_to_cell($row, --$col, $row_abs, $col_abs);
}
=head1 TIME AND DATE FUNCTIONS
Dates and times in Excel are represented by real numbers, for example "Jan 1 2001 12:30 AM" is represented by the number 36892.521.
The integer part of the number stores the number of days since the epoch and the fractional part stores the percentage of the day in seconds.
The epoch can be either 1900 or 1904. Excel for Windows uses 1900 and Excel for Macintosh uses 1904. The epochs are:
1900: 0 January 1900 i.e. 31 December 1899
1904: 1 January 1904
Excel on Windows and the Macintosh will convert automatically between one system and the other. By default Spreadsheet::WriteExcel uses the 1900 format. To use the 1904 epoch you must use the C<set_1904()> workbook method, see the Spreadsheet::WriteExcel documentation.
There are two things to note about the 1900 date format. The first is that the epoch starts on 0 January 1900. The second is that the year 1900 is erroneously but deliberately treated as a leap year. Therefore you must add an extra day to dates after 28 February 1900. The functions in the following section will deal with these issues automatically. The reason for this anomaly is explained at http://support.microsoft.com/support/kb/articles/Q181/3/70.asp
Note, a date or time in Excel is like any other number. To display the number as a date you must apply a number format to it: Refer to the C<set_num_format()> method in the Spreadsheet::WriteExcel documentation:
$date = xl_date_list(2001, 1, 1, 12, 30);
$format->set_num_format('mmm d yyyy hh:mm AM/PM');
$worksheet->write('A1', $date , $format); # Jan 1 2001 12:30 AM
To use these functions you must install the C<Date::Manip> and C<Date::Calc> modules. See L<REQUIREMENTS> and the individual requirements of each functions.
See also the DateTime::Format::Excel module,http://search.cpan.org/search?dist=DateTime-Format-Excel which is part of the DateTime project and which deals specifically with converting dates and times to and from Excel's format.
=cut
###############################################################################
###############################################################################
=head2 xl_date_list($years, $months, $days, $hours, $minutes, $seconds)
Parameters: $years: Integer
$months: Integer [optional, default is 1]
$days: Integer [optional, default is 1]
$hours: Integer [optional, default is 0]
$minutes: Integer [optional, default is 0]
$seconds: Float [optional, default is 0]
Returns: A number that represents an Excel date
or undef for an invalid date.
Requires: Date::Calc
This function converts an array of data into a number that represents an Excel date. All of the parameters are optional except for C<$years>.
$date1 = xl_date_list(2002, 1, 2); # 2 Jan 2002
$date2 = xl_date_list(2002, 1, 2, 12); # 2 Jan 2002 12:00 pm
$date3 = xl_date_list(2002, 1, 2, 12, 30); # 2 Jan 2002 12:30 pm
$date4 = xl_date_list(2002, 1, 2, 12, 30, 45); # 2 Jan 2002 12:30:45 pm
This function can be used in conjunction with functions that parse date and time strings. In fact it is used in most of the following functions.
=cut
###############################################################################
#
# xl_date_list($years, $months, $days, $hours, $minutes, $seconds)
#
sub xl_date_list {
return undef unless @_;
my $years = $_[0];
my $months = $_[1] || 1;
my $days = $_[2] || 1;
my $hours = $_[3] || 0;
my $minutes = $_[4] || 0;
my $seconds = $_[5] || 0;
my @date = ($years, $months, $days, $hours, $minutes, $seconds);
my @epoch = (1899, 12, 31, 0, 0, 0);
($days, $hours, $minutes, $seconds) = Delta_DHMS(@epoch, @date);
my $date = $days + ($hours*3600 +$minutes*60 +$seconds)/(24*60*60);
# Add a day for Excel's missing leap day in 1900
$date++ if ($date > 59);
return $date;
}
###############################################################################
###############################################################################
=head2 xl_parse_time($string)
Parameters: $string, a textual representation of a time
Returns: A number that represents an Excel time
or undef for an invalid time.
This function converts a time string into a number that represents an Excel time. The following time formats are valid:
hh:mm [AM|PM]
hh:mm [AM|PM]
hh:mm:ss [AM|PM]
hh:mm:ss.ss [AM|PM]
The meridian, AM or PM, is optional and case insensitive. A 24 hour time is assumed if the meridian is omitted
$time1 = xl_parse_time('12:18');
$time2 = xl_parse_time('12:18:14');
$time3 = xl_parse_time('12:18:14 AM');
$time4 = xl_parse_time('1:18:14 AM');
Time in Excel is expressed as a fraction of the day in seconds. Therefore you can calculate an Excel time as follows:
$time = ($hours*3600 +$minutes*60 +$seconds)/(24*60*60);
=cut
###############################################################################
#
# xl_parse_time($string)
#
sub xl_parse_time {
my $time = shift;
if ($time =~ /(\d{1,2}):(\d\d):?((?:\d\d)(?:\.\d+)?)?(?:\s+)?(am|pm)?/i) {
my $hours = $1;
my $minutes = $2;
my $seconds = $3 || 0;
my $meridian = lc($4) || '';
# Normalise midnight and midday
$hours = 0 if ($hours == 12 && $meridian ne '');
# Add 12 hours to the pm times. Note: 12.00 pm has been set to 0.00.
$hours += 12 if $meridian eq 'pm';
# Calculate the time as a fraction of 24 hours in seconds
return ($hours*3600 +$minutes*60 +$seconds)/(24*60*60);
}
else {
return undef; # Not a valid time string
}
}
###############################################################################
###############################################################################
=head2 xl_parse_date($string)
Parameters: $string, a textual representation of a date and time
Returns: A number that represents an Excel date
or undef for an invalid date.
Requires: Date::Manip and Date::Calc
This function converts a date and time string into a number that represents an Excel date.
The parsing is performed using the C<ParseDate()> function of the Date::Manip module. Refer to the Date::Manip documentation for further information about the date and time formats that can be parsed. In order to use this function you will probably have to initialise some Date::Manip variables via the C<xl_parse_date_init()> function, see below.
xl_parse_date_init("TZ=GMT","DateFormat=non-US");
$date1 = xl_parse_date("11/7/97");
$date2 = xl_parse_date("Friday 11 July 1997");
$date3 = xl_parse_date("10:30 AM Friday 11 July 1997");
$date4 = xl_parse_date("Today");
$date5 = xl_parse_date("Yesterday");
Note, if you parse a string that represents a time but not a date this function will add the current date. If you want the time without the date you can do something like the following:
$time = xl_parse_date("10:30 AM");
$time -= int($time);
=cut
###############################################################################
#
# xl_parse_date($string)
#
sub xl_parse_date {
my $date = ParseDate($_[0]);
return undef unless defined $date;
# Unpack the return value from ParseDate()
my ($years, $months, $days, $hours, undef, $minutes, undef, $seconds) =
unpack("A4 A2 A2 A2 C A2 C A2", $date);
# Convert to Excel date
return xl_date_list($years, $months, $days, $hours, $minutes, $seconds);
}
###############################################################################
###############################################################################
=head2 xl_parse_date_init("variable=value", ...)
Parameters: A list of Date::Manip variable strings
Returns: A list of all the Date::Manip strings
Requires: Date::Manip
This function is used to initialise variables required by the Date::Manip module. You should call this function before calling C<xl_parse_date()>. It need only be called once.
This function is a thin wrapper for the C<Date::Manip::Date_Init()> function. You can use C<Date_Init()> directly if you wish. Refer to the Date::Manip documentation for further information.
xl_parse_date_init("TZ=MST","DateFormat=US");
$date1 = xl_parse_date("11/7/97"); # November 7th 1997
xl_parse_date_init("TZ=GMT","DateFormat=non-US");
$date1 = xl_parse_date("11/7/97"); # July 11th 1997
=cut
###############################################################################
#
# xl_parse_date_init("variable=value", ...)
#
sub xl_parse_date_init {
Date_Init(@_); # How lazy is that.
}
###############################################################################
###############################################################################
=head2 xl_decode_date_EU($string)
Parameters: $string, a textual representation of a date and time
Returns: A number that represents an Excel date
or undef for an invalid date.
Requires: Date::Calc
This function converts a date and time string into a number that represents an Excel date.
The date parsing is performed using the C<Decode_Date_EU()> function of the Date::Calc module. Refer to the Date::Calc for further information about the date formats that can be parsed. Also note the following from the Date::Calc documentation:
"If the year is given as one or two digits only (i.e., if the year is less than 100), it is mapped to the window 1970 -2069 as follows":
0 E<lt>= $year E<lt> 70 ==> $year += 2000;
70 E<lt>= $year E<lt> 100 ==> $year += 1900;
The time portion of the string is parsed using the C<xl_parse_time()> function described above.
Note: the EU in the function name means that a European date format is assumed if it is not clear from the string. See the first example below.
$date1 = xl_decode_date_EU("11/7/97"); #11 July 1997
$date2 = xl_decode_date_EU("Sat 12 Sept 1998");
$date3 = xl_decode_date_EU("4:30 AM Sat 12 Sept 1998");
=cut
###############################################################################
#
# xl_decode_date_EU($string)
#
sub xl_decode_date_EU {
return undef unless @_;
my $date = shift;
my @date;
my $time = 0;
# Remove and decode the time portion of the string
if ($date =~ s/(\d{1,2}:\d\d:?(\d\d(\.\d+)?)?(\s+)?(am|pm)?)//i) {
$time = xl_parse_time($1);
return undef unless defined $time;
}
# Return if the string is now blank, i.e. it contained a time only.
return $time if $date =~ /^\s*$/;
# Decode the date portion of the string
@date = Decode_Date_EU($date);
return undef unless @date;
return xl_date_list(@date) + $time;
}
###############################################################################
###############################################################################
=head2 xl_decode_date_US($string)
Parameters: $string, a textual representation of a date and time
Returns: A number that represents an Excel date
or undef for an invalid date.
Requires: Date::Calc
This function converts a date and time string into a number that represents an Excel date.
The date parsing is performed using the C<Decode_Date_US()> function of the Date::Calc module. Refer to the Date::Calc for further information about the date formats that can be parsed. Also note the following from the Date::Calc documentation:
"If the year is given as one or two digits only (i.e., if the year is less than 100), it is mapped to the window 1970 -2069 as follows":
0 <= $year < 70 ==> $year += 2000;
70 <= $year < 100 ==> $year += 1900;
The time portion of the string is parsed using the C<xl_parse_time()> function described above.
Note: the US in the function name means that an American date format is assumed if it is not clear from the string. See the first example below.
$date1 = xl_decode_date_US("11/7/97"); # 7 November 1997
$date2 = xl_decode_date_US("12 Sept Saturday 1998");
$date3 = xl_decode_date_US("4:30 AM 12 Sept Sat 1998");
=cut
###############################################################################
#
# xl_decode_date_US($string)
#
sub xl_decode_date_US {
return undef unless @_;
my $date = shift;
my @date;
my $time = 0;
# Remove and decode the time portion of the string
if ($date =~ s/(\d{1,2}:\d\d:?(\d\d(\.\d+)?)?(\s+)?(am|pm)?)//i) {
$time = xl_parse_time($1);
return undef unless defined $time;
}
# Return if the string is now blank, i.e. it contained a time only.
return $time if $date =~ /^\s*$/;
# Decode the date portion of the string
@date = Decode_Date_US($date);
return undef unless @date;
return xl_date_list(@date) + $time;
}
###############################################################################
###############################################################################
=head2 xl_date_1904($date)
Parameters: $date, an Excel date with a 1900 epoch
Returns: an Excel date with a 1904 epoch or zero if
the $date is before 1904
This function converts an Excel date based on the 1900 epoch into a date based on the 1904 epoch.
$date1 = xl_date_list(2002, 1, 13); # 13 Jan 2002, 1900 epoch
$date2 = xl_date_1904($date1); # 13 Jan 2002, 1904 epoch
See also the C<set_1904()> workbook method in the Spreadsheet::WriteExcel documentation.
=cut
###############################################################################
#
# xl_decode_date_US($string)
#
sub xl_date_1904 {
my $date = $_[0] || 0;
if ($date < 1462) {
# before 1904
$date = 0;
}
else {
$date -= 1462;
}
return $date;
}
=head1 REQUIREMENTS
The date and time functions require functions from the C<Date::Manip> and C<Date::Calc> modules. The required functions are "autoused" from these modules so that you do not have to install them unless you wish to use the date and time routines. Therefore it is possible to use the row and column functions without having C<Date::Manip> and C<Date::Calc> installed.
For more information about "autousing" refer to the documentation on the C<autouse> pragma.
=head1 BUGS
When using the autoused functions from C<Date::Manip> and C<Date::Calc> on Perl 5.6.0 with C<-w> you will get a warning like this:
"Subroutine xxx redefined ..."
The current workaround for this is to put C<use warnings;> near the beginning of your program.
=head1 AUTHOR
John McNamara [email protected]
=head1 COPYRIGHT
© MM-MMVIII, John McNamara.
All Rights Reserved. This module is free software. It may be used, redistributed and/or modified under the same terms as Perl itself.
=cut
1;
__END__
| polettix/igsuite-unofficial | IG/SpreadsheetWriteExcelUtility.pm | Perl | gpl-2.0 | 29,176 |
<?php
/**
* Helpers for handling timezone based event datetimes.
*
* In our timezone logic, the term "local" refers to the locality of an event
* rather than the local WordPress timezone.
*/
class E_Register_NowTimezones {
const SITE_TIMEZONE = 'site';
const EVENT_TIMEZONE = 'event';
/**
* Container for reusable DateTimeZone objects.
*
* @var array
*/
protected static $timezones = array();
public static function init() {
self::invalidate_caches();
}
/**
* Clear any cached timezone-related values when appropriate.
*
* Currently we are concerned only with the site timezone abbreviation.
*/
protected static function invalidate_caches() {
add_filter( 'pre_update_option_gmt_offset', array( __CLASS__, 'clear_site_timezone_abbr' ) );
add_filter( 'pre_update_option_timezone_string', array( __CLASS__, 'clear_site_timezone_abbr' ) );
}
/**
* Wipe the cached site timezone abbreviation, if set.
*
* @param mixed $option_val (passed through without modification)
*
* @return mixed
*/
public static function clear_site_timezone_abbr( $option_val ) {
delete_transient( 'tribe_events_wp_timezone_abbr' );
return $option_val;
}
/**
* Returns the current site-wide timezone string.
*
* Based on the core WP code found in wp-admin/options-general.php.
*
* @return string
*/
public static function wp_timezone_string() {
$current_offset = get_option( 'gmt_offset' );
$tzstring = get_option( 'timezone_string' );
// Return the timezone string if already set
if ( ! empty( $tzstring ) ) {
return $tzstring;
}
// Otherwise return the UTC offset
if ( 0 == $current_offset ) {
return 'UTC+0';
} elseif ( $current_offset < 0 ) {
return 'UTC' . $current_offset;
}
return 'UTC+' . $current_offset;
}
/**
* Returns the current site-wide timezone string abbreviation, if it can be
* determined or falls back on the full timezone string/offset text.
*
* @param string $date
*
* @return string
*/
public static function wp_timezone_abbr( $date ) {
$abbr = get_transient( 'tribe_events_wp_timezone_abbr' );
if ( empty( $abbr ) ) {
$timezone_string = self::wp_timezone_string();
$abbr = self::abbr( $date, $timezone_string );
set_transient( 'tribe_events_wp_timezone_abbr', $abbr );
}
return empty( $abbr )
? $timezone_string
: $abbr;
}
/**
* Helper function to retrieve the timezone string for a given UTC offset
*
* This is a close copy of WooCommerce's wc_timezone_string() method
*
* @param string $offset UTC offset
*
* @return string
*/
public static function generate_timezone_string_from_utc_offset( $offset ) {
if ( ! self::is_utc_offset( $offset ) ) {
return $offset;
}
// ensure we have the minutes on the offset
if ( ! strpos( $offset, ':' ) ) {
$offset .= ':00';
}
$offset = str_replace( 'UTC', '', $offset );
list( $hours, $minutes ) = explode( ':', $offset );
$seconds = $hours * 60 * 60 + $minutes * 60;
// attempt to guess the timezone string from the UTC offset
$timezone = timezone_name_from_abbr( '', $seconds, 0 );
if ( false === $timezone ) {
$is_dst = date( 'I' );
foreach ( timezone_abbreviations_list() as $abbr ) {
foreach ( $abbr as $city ) {
if (
$city['dst'] == $is_dst
&& $city['offset'] == $seconds
) {
return $city['timezone_id'];
}
}
}
// fallback to UTC
return 'UTC';
}
return $timezone;
}
/**
* Tried to convert the provided $datetime to UTC from the timezone represented by $tzstring.
*
* Though the usual range of formats are allowed, $datetime ordinarily ought to be something
* like the "Y-m-d H:i:s" format (ie, no timezone information). If it itself contains timezone
* data, the results may be unexpected.
*
* In those cases where the conversion fails to take place, the $datetime string will be
* returned untouched.
*
* @param string $datetime
* @param string $tzstring
*
* @return string
*/
public static function to_utc( $datetime, $tzstring ) {
if ( self::is_utc_offset( $tzstring ) ) {
return self::apply_offset( $datetime, $tzstring, true );
}
try {
$local = self::get_timezone( $tzstring );
$utc = self::get_timezone( 'UTC' );
$datetime = date_create( $datetime, $local )->setTimezone( $utc );
return $datetime->format( E_Register_NowDate_Utils::DBDATETIMEFORMAT );
}
catch ( Exception $e ) {
return $datetime;
}
}
/**
* Tries to convert the provided $datetime to the timezone represented by $tzstring.
*
* This is the sister function of self::to_utc() - please review the docs for that method
* for more information.
*
* @param string $datetime
* @param string $tzstring
*
* @return string
*/
public static function to_tz( $datetime, $tzstring ) {
if ( self::is_utc_offset( $tzstring ) ) {
return self::apply_offset( $datetime, $tzstring );
}
try {
$local = self::get_timezone( $tzstring );
$utc = self::get_timezone( 'UTC' );
$datetime = date_create( $datetime, $utc )->setTimezone( $local );
return $datetime->format( E_Register_NowDate_Utils::DBDATETIMEFORMAT );
}
catch ( Exception $e ) {
return $datetime;
}
}
/**
* Tests to see if the timezone string is a UTC offset, ie "UTC+2".
*
* @param string $timezone
*
* @return bool
*/
public static function is_utc_offset( $timezone ) {
$timezone = trim( $timezone );
return ( 0 === strpos( $timezone, 'UTC' ) && strlen( $timezone ) > 3 );
}
/**
* @param string $datetime
* @param mixed $offset (string or numeric offset)
* @param bool $invert = false
*
* @return string
*/
public static function apply_offset( $datetime, $offset, $invert = false ) {
// Normalize
$offset = strtolower( trim( $offset ) );
// Strip any leading "utc" text if set
if ( 0 === strpos( $offset, 'utc' ) ) {
$offset = substr( $offset, 3 );
}
// It's possible no adjustment will be needed
if ( 0 === $offset ) {
return $datetime;
}
// Convert the offset to minutes for easier handling of fractional offsets
$offset = (int) ( $offset * 60 );
// Invert the offset? Useful for stripping an offset that has already been applied
if ( $invert ) {
$offset *= -1;
}
try {
if ( $offset > 0 ) $offset = '+' . $offset;
$offset = $offset . ' minutes';
$datetime = date_create( $datetime )->modify( $offset );
return $datetime->format( E_Register_NowDate_Utils::DBDATETIMEFORMAT );
}
catch ( Exception $e ) {
return $datetime;
}
}
/**
* Accepts a unix timestamp and adjusts it so that when it is used to consitute
* a new datetime string, that string reflects the designated timezone.
*
* @param string $unix_timestamp
* @param string $tzstring
*
* @return string
*/
public static function adjust_timestamp( $unix_timestamp, $tzstring ) {
try {
$local = self::get_timezone( $tzstring );
$datetime = date_create_from_format( 'U', $unix_timestamp )->format( E_Register_NowDate_Utils::DBDATETIMEFORMAT );
return date_create_from_format( 'Y-m-d H:i:s', $datetime, $local )->getTimestamp();
}
catch( Exception $e ) {
return $unix_timestamp;
}
}
/**
* Returns a DateTimeZone object matching the representation in $tzstring where
* possible, or else representing UTC (or, in the worst case, false).
*
* If optional parameter $with_fallback is true, which is the default, then in
* the event it cannot find/create the desired timezone it will try to return the
* UTC DateTimeZone before bailing.
*
* @param string $tzstring
* @param bool $with_fallback = true
*
* @return DateTimeZone|false
*/
public static function get_timezone( $tzstring, $with_fallback = true ) {
if ( isset( self::$timezones[ $tzstring ] ) ) {
return self::$timezones[ $tzstring ];
}
try {
self::$timezones[ $tzstring ] = new DateTimeZone( $tzstring );
return self::$timezones[ $tzstring ];
}
catch ( Exception $e ) {
if ( $with_fallback ) {
return self::get_timezone( 'UTC', true );
}
}
return false;
}
/**
* Returns a string representing the timezone/offset currently desired for
* the display of dates and times.
*
* @return string
*/
public static function mode() {
$mode = self::EVENT_TIMEZONE;
if ( 'site' === tribe_get_option( 'tribe_events_timezone_mode' ) ) {
$mode = self::SITE_TIMEZONE;
}
return apply_filters( 'tribe_events_current_display_timezone', $mode );
}
/**
* Confirms if the current timezone mode matches the $possible_mode.
*
* @param string $possible_mode
*
* @return bool
*/
public static function is_mode( $possible_mode ) {
return $possible_mode === self::mode();
}
/**
* Attempts to provide the correct timezone abbreviation for the provided timezone string
* on the date given (and so should account for daylight saving time, etc).
*
* @param string $date
* @param string $timezone_string
*
* @return string
*/
public static function abbr( $date, $timezone_string ) {
try {
return date_create( $date, new DateTimeZone( $timezone_string ) )->format( 'T' );
}
catch ( Exception $e ) {
return '';
}
}
}
| romangrb/register-now-plugin | backup/event-tickets 1.2.3/common/src/e_register_now/Timezones.php | PHP | gpl-2.0 | 9,222 |
/*****************************************************************************
* Copyright (C) 2009 by Peter Penz <[email protected]> *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License version 2 as published by the Free Software Foundation. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public License *
* along with this library; see the file COPYING.LIB. If not, write to *
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, *
* Boston, MA 02110-1301, USA. *
*****************************************************************************/
#ifndef KEDIT_TAGS_DIALOG_H
#define KEDIT_TAGS_DIALOG_H
#include <kdialog.h>
#include <Nepomuk2/Tag>
class KLineEdit;
class QListWidget;
class QListWidgetItem;
class QPushButton;
class QTimer;
/**
* @brief Dialog to edit a list of Nepomuk tags.
*
* It is possible for the user to add existing tags,
* create new tags or to remove tags.
*
* @see KMetaDataConfigurationDialog
*/
class KEditTagsDialog : public KDialog
{
Q_OBJECT
public:
KEditTagsDialog(const QList<Nepomuk2::Tag>& tags,
QWidget* parent = 0,
Qt::WFlags flags = 0);
virtual ~KEditTagsDialog();
QList<Nepomuk2::Tag> tags() const;
virtual bool eventFilter(QObject* watched, QEvent* event);
protected slots:
virtual void slotButtonClicked(int button);
private slots:
void slotTextEdited(const QString& text);
void slotItemEntered(QListWidgetItem* item);
void showDeleteButton();
void deleteTag();
private:
void loadTags();
void removeNewTagItem();
private:
QList<Nepomuk2::Tag> m_tags;
QListWidget* m_tagsList;
QListWidgetItem* m_newTagItem;
QListWidgetItem* m_autoCheckedItem;
QListWidgetItem* m_deleteCandidate;
KLineEdit* m_newTagEdit;
QPushButton* m_deleteButton;
QTimer* m_deleteButtonTimer;
};
#endif
| KDE/nepomuk-widgets | ui/kedittagsdialog_p.h | C | gpl-2.0 | 2,652 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3c.org/TR/1999/REC-html401-19991224/loose.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>»ÆÊ¯ÓÎÏ·ÖÐÐÄÏÂÔØ</title>
<meta name="keywords" content="»ÆÊ¯,ÓÎÏ·ÖÐÐÄ,ÏÂÔØ,»ÆÊ¯,ÓÎÏ·ÖÐÐÄ,µ±µØ,ÆåÅÆÓÎÏ·,ƽ̨," />
<meta name="description" content="»ÆÊ¯ÓÎÏ·ÖÐÐÄÊÇ»ÆÊ¯µ±µØµÄÆåÅÆÓÎϷƽ̨£¬¸Ãƽ̨¾ßÓÐŨÓôµÄµØ·½ÌØÉ«£¬£¬ÔÚÕâÀï¿ÉÒÔÏÖ³¡ÊÓÆµ£¬µ±µØµÄÅóÓÑϲ»¶ÍæµÄ²Ð¼²¶·µØÖ÷ÓÎÏ·£¬»ÆÊ¯Â齫ÓÎÏ·»ÆÊ¯ÓÎÏ·ÖÐÐͼÓУ¬ÁíÍâΪÄú»ÆÊ¯ÓÎÏ·»¹Óи÷ÖÖ½±Æ·Å¶£¡ »ÆÊ¯ÓÎÏ· »ÆÊ¯ÓÎÏ·ÖÐÐÄ »ÆÊ¯ÓÎÏ·´óÌüÏÂÔØ »ÆÊ¯ÓÎÏ·ÖÐÐÄÊǺÜ" />
<LINK rel=stylesheet type=text/css href="/qipai/templets/default/style/style.css">
<LINK rel=stylesheet type=text/css href="/qipai/templets/default/style/p.css">
<BODY>
<DIV class=top>
<DIV class=c_960>
<DIV class=top-nav><SPAN>Hi£¬»¶ÓÀ´µ½789ÓÎÏ·ÖÐÐÄ£¡</SPAN></DIV>
<DIV><!-- logo -->
<DIV style="POSITION: relative" class=logo><A
href="/"></A></DIV>
<DIV class=nav>
<UL>
<LI><a href="/">ÍøÕ¾Ê×Ò³</a></LI>
<LI class=gap></LI>
<LI><a href="/qipai/qpplat/">ÓÎϷƽ̨</a></LI>
<LI class=gap></LI>
<LI><a href="/kefuzhongxin/">¿Í·þÖÐÐÄ</a></LI>
<LI class=gap></LI>
<LI><a href="/youxijieshao/">ÓÎÏ·½éÉÜ</a></LI>
<LI class=gap></LI>
<LI><a href="/Download/">ÏÂÔØÖÐÐÄ</a></LI>
<LI class=gap></LI></UL></DIV><!-- µ¼º½À¸½áÊø --></DIV></DIV></DIV>
<div style="BORDER: #cdcdcd 1px solid; margin-top:10px; width:960px; margin:5px auto"><a href="/Download/"><img src="/qipai/templets/default/images/960X424.jpg" width="960" height="424"></a></div>
<div class="main">
<DIV id=p_con><!--Ò³Ãæ×ó²à²¿·Ö ¿ªÊ¼ -->
<DIV class=p_l>
<DIV class=location><IMG src="/qipai/templets/default/images/flag.png" width=16 height=16>
µ±Ç°Î»ÖÃ:</strong> <a href="/">Ö÷Ò³</a> ><a href='/qipai/qpplat/'>ÆåÅÆÓÎϷƽ̨</a> > </DIV>
<DIV id=pnlContent>
<H1 class=que-title>»ÆÊ¯ÓÎÏ·ÖÐÐÄÏÂÔØ</H1>
<DIV class=que-date> <span>ʱ¼ä:</span>2014-02-21 14:31<span>À´Ô´:</span><a href="http://www.789game.com/">789gameÆåÅÆÓÎÏ·ÖÐÐÄ</a>
<span>×÷Õß:</span>admin <span>µã»÷:</span>
<script src="/qipai/plus/count.php?view=yes&aid=70&mid=1" type='text/javascript' language="javascript"></script>
´Î</DIV>
<DIV class=que-content>
<p>
»ÆÊ¯ÓÎÏ·ÖÐÐÄÊÇ»ÆÊ¯µ±µØµÄÆåÅÆÓÎϷƽ̨£¬¸Ãƽ̨¾ßÓÐŨÓôµÄµØ·½ÌØÉ«£¬£¬ÔÚÕâÀï¿ÉÒÔÏÖ³¡ÊÓÆµ£¬µ±µØµÄÅóÓÑϲ»¶ÍæµÄ²Ð¼²¶·µØÖ÷ÓÎÏ·£¬»ÆÊ¯Â齫ÓÎÏ·»ÆÊ¯ÓÎÏ·ÖÐÐͼÓУ¬ÁíÍâΪÄú»ÆÊ¯ÓÎÏ·»¹Óи÷ÖÖ½±Æ·Å¶£¡</p>
<p>
<strong>»ÆÊ¯ÓÎÏ·</strong></p>
<p>
<strong>»ÆÊ¯ÓÎÏ·ÖÐÐÄ</strong></p>
<p>
<strong>»ÆÊ¯ÓÎÏ·´óÌüÏÂÔØ</strong></p>
<p>
»ÆÊ¯ÓÎÏ·ÖÐÐÄÊǺÜÊÜÓû§»¶ÓµÄ£¬»ÆÊ¯ÓÎÏ·ÖÐÐÄÊǶ¨ÆÚÌṩÉý¼¶£¬°üÀ¨Æ·ËĹú¾üÆå£¬ÏóÆå£¬ºÍÆäËûÁ÷ÐеÄÓÎÏ·Ãâ·ÑÏÂÔØ£¬Ï£Íû»ÆÊ¯ÆåÅÆÓÎÏ·ÄÜÔö¼ÓÄúµÄÉú»îÀÖȤÈÃÄúÍæµÄÓä¿ì£¡</p>
</DIV>
<DIV class=pre-nex>ÉÏһƪ£º<a href='/qipai/qpplat/69.html'>¡¾¾©¶¼ÆåÅÆ¡¿¾©¶¼ÆåÅÆ¹ÙÍø_¾©¶¼ÆåÅÆÏÂÔØ</a> ÏÂÒ»Ìõ£ºÏÂһƪ£º<a href='/qipai/qpplat/71.html'>Ì콡ÆåÅÆ¹Ù·½ÍøÕ¾-´óÁ¬Ì콡ÆåÅÆÏÂÔØ</a> </DIV></DIV>
</DIV>
<DIV class=p_r_xiazai><DIV class=r_ad>
<DIV class=dl_client_v2>
<A style="BACKGROUND-POSITION: 22px -536px" class=client_dl title=ÏÂÔØ¿Í»§¶Ë
rel=nofollow href="/Download/"></A><A class="reg reg_fadein" title=×¢²áÕ˺Å
rel=nofollow href="/Download/"></A>
<A class=demo title=ÓÎÏ·ÊÔÍæ rel=nofollow href="/Download/"></A></DIV></DIV></div>
<DIV class=p_r>
<DL class=box_dl>
<DT>×îÐÂÎÄÕÂ</DT><DD><a href="/qipai/qpplat/136.html">ÒâȤÆåÅÆÓÎÏ·´óÌü¹Ù·½ÍøÕ¾-ÒâȤ</a> </DD>
<DD><a href="/qipai/qpplat/135.html">¿À³ÆåÅÆÓÎÏ·ÖÐÐÄ-¿À³ÆåÅÆÓÎÏ·</a> </DD>
<DD><a href="/qipai/qpplat/134.html">ÁúÓòÆåÅÆÓÎÏ·ÖÐÐÄ-ÁúÓòÆåÅÆ´óÌü</a> </DD>
<DD><a href="/qipai/qpplat/133.html">ÃûÊ˹ú¼ÊÆåÅÆÓÎÏ·¹Ù·½ÍøÕ¾-ÃûÊË</a> </DD>
<DD><a href="/qipai/qpplat/132.html">ÆåÀÖ°ÉÆåÅÆÓÎϷƽ̨-ÆåÀÖ°ÉÓÎÏ·</a> </DD>
<DD><a href="/qipai/qpplat/131.html">ɽˮÆåÅÆÓÎÏ·ÖÐÐÄ-ÖÛɽɽˮÆåÅÆ</a> </DD>
<DD><a href="/qipai/qpplat/130.html">ºã·áÆåÅÆÓÎÏ·´óÌü-ºã·áÆåÅÆ¹Ù·½</a> </DD>
<DD><a href="/qipai/qpplat/129.html">ÓÀºêÆåÅÆÓÎÏ·´óÌü-ÓÀºêÆåÅÆ¹Ù·½</a> </DD>
<DD><a href="/qipai/qpplat/128.html">½ðÀöÆåÅÆÓÎÏ·ÖÐÐĹÙÍø-½ðÀöÆåÅÆ</a> </DD>
<DD><a href="/qipai/qpplat/127.html">ÌìºãÆåÅÆÓÎÏ·ÖÐÐĹÙÍø-ÌìºãÆåÅÆ</a> </DD>
</DL>
<DL class=box_dl>
<DT>×îÈÈÎÄÕÂ</DT>
<DD><a href="/qipai/qpplat/17.html">°²»Õ±ß·æÓÎÏ·¶·µØÖ÷</a> </DD>
<DD><a href="/qipai/qpplat/67.html">6603ÆåÅÆÓÎÏ·ÖÐÐÄ-6603ÆåÅÆ´óÌü</a> </DD>
<DD><a href="/qipai/qpplat/126.html">3171ÓÎÏ·ÖÐÐÄ-3171ÓÎÏ·´óÌü¹Ù·½</a> </DD>
<DD><a href="/qipai/qpplat/89.html">·çÀ×ÓÎÏ·´óÌüÏÂÔØ</a> </DD>
<DD><a href="/qipai/qpplat/117.html">898ÆåÅÆÓÎÏ·´óÌüÏÂÔØ-¿ìÀÖÖ®¶¼Æå</a> </DD>
<DD><a href="/qipai/qpplat/94.html">»ªÏÄÆåÅÆÓÎÏ·´óÌü</a> </DD>
<DD><a href="/qipai/qpplat/112.html">66ÓÎÏ·ÖÐÐÄ-66ÆåÅÆ´óÌü¹Ù·½ÍøÕ¾</a> </DD>
<DD><a href="/qipai/qpplat/121.html">sosoÆåÅÆÓÎÏ·ÖÐÐÄ¡ªÓÎÏ·´óÌüÏÂÔØ</a> </DD>
<DD><a href="/qipai/qpplat/122.html">ÑÇÐÄÆåÅÆÓÎÏ·ÖÐÐÄ-ÑÇÐÄÆåÅÆ¹Ù·½</a> </DD>
<DD><a href="/qipai/qpplat/56.html">89ÆåÅÆÓÎÏ·¹Ù·½ÍøÕ¾-89ÆåÅÆ´óÌü</a> </DD>
</DL><DIV class=tags>
<DL class=box_dl>
<DT>ÓÎÏ·½éÉÜ</DT>
<DIV class=tags>
<A href="/youxijieshao/xiuxianleiyouxi/55.html">½ð²õ²¶Óã</A>
<A href="/youxijieshao/paileiyouxi/65.html">²¶ÓãÓÎÏ·</A>
<A href="/youxijieshao/paileiyouxi/60.html">ÖÁ×ð¶·Å£</A>
<A href="/youxijieshao/paileiyouxi/64.html">ţţÓÎÏ·</A>
<A href="/youxijieshao/shoujileiyouxi/63.html">¿¨ÎåÐÇ</A>
<A href="/youxijieshao/paileiyouxi/61.html">»¶ÀÖ¶·µØÖ÷</A>
<A href="/youxijieshao/paileiyouxi/58.html">¶þÈ˶·Å£</A>
<A href="/youxijieshao/paileiyouxi/58.html">ͬ±Èţţ</A>
<A href="/youxijieshao/xiuxianleiyouxi/57.html">·è¿ñÈü³µ</A>
<A href="/youxijieshao/xiuxianleiyouxi/56.html">·è¿ñ30Ãë³µ</A>
<A href="/youxijieshao/xiuxianleiyouxi/54.html">Îò¿ÕÄÔº£</A>
<A href="/youxijieshao/xiuxianleiyouxi/54.html">´óÉùÄÔº£</A>
<A href="/youxijieshao/xiuxianleiyouxi/50.html">ÀîåÓÅüÓã</A>
<A href="/youxijieshao/paileiyouxi/49.html">·ÉÇÝ×ßÊÞ</A>
<A href="/youxijieshao/paileiyouxi/51.html">¶·µØÖ÷</A>
</DIV></DL></DIV>
</DIV>
</DIV><!--Ò³ÃæÓҲಿ·Ö ½áÊø --></DIV>
</DIV>
<DIV class=footer>
µÖÖÆ²»Á¼ÓÎÏ· ¾Ü¾øµÁ°æÓÎÏ· ×¢Òâ×ÔÎÒ±£»¤ ½÷·ÀÊÜÆÉϵ± ÊʶÈÓÎÏ·ÒæÄÔ ³ÁÃÔÓÎÏ·ÉËÉí ºÏÀí°²ÅÅʱ¼ä ÏíÊܽ¡¿µÉú»î <BR>
789ÓÎÏ·ÖÐÐÄ Ô¥ICP±¸12014032ºÅ-1
±¸°¸ÎĺÅ:ÎÄÍøÓα¸×Ö[2011]C-CBG002ºÅ<BR>¿Í·þQQ£º4000371814 ¿Í·þÈÈÏߣº4000371814 <script type="text/javascript">
var _bdhmProtocol = (("https:" == document.location.protocol) ? " https://" : " http://");
document.write(unescape("%3Cscript src='" + _bdhmProtocol + "hm.baidu.com/h.js%3Fde6684532de22a1b45cd44b14141ff07' type='text/javascript'%3E%3C/script%3E"));
</script><script type="text/javascript">var cnzz_protocol = (("https:" == document.location.protocol) ? " https://" : " http://");document.write(unescape("%3Cspan id='cnzz_stat_icon_5813709'%3E%3C/span%3E%3Cscript src='" + cnzz_protocol + "s23.cnzz.com/stat.php%3Fid%3D5813709%26show%3Dpic' type='text/javascript'%3E%3C/script%3E"));</script>
</DIV>
</BODY></HTML>
| bylu/Test | wulu/2015.11.23/qipai/1008/qpplat/70.html | HTML | gpl-2.0 | 7,029 |
using UnityEngine;
using System.Collections;
public class EndScreenController : ScreenController {
public UnityEngine.UI.Text winnerText;
public UnityEngine.UI.Text player1Text;
public UnityEngine.UI.Text player2Text;
public UnityEngine.UI.Text nextLeftPlayers;
public UnityEngine.UI.Text nextRightPlayers;
protected override void OnActivation() {
gameObject.SetActive(true);
winnerText.text = "...";
player1Text.text = "...";
player2Text.text = "...";
nextLeftPlayers.text = "...";
nextRightPlayers.text = "...";
int matchId = eventInfo.matchId;
StartCoroutine (DownloadMatchInfo (matchId));
}
protected override void OnDeactivation() {
}
protected override void OnMatchInfoDownloaded (MatchInfo matchInfo) {
if (matchInfo.state != "OK") {
int matchId = eventInfo.matchId;
StartCoroutine (DownloadMatchInfo (matchId));
return;
}
Bot winner = matchInfo.GetWinner();
if (winner == null) {
winnerText.text = "Draw!";
Bot[] bots = matchInfo.bots;
player1Text.text = createText (bots[0].name, -1);
player2Text.text = createText (bots[1].name, -1);
} else {
winnerText.text = winner.name + " wins!";
Bot looser = matchInfo.GetLooser ();
player1Text.text = createText (winner.name, 3);
player2Text.text = createText (looser.name, 0);
}
int tournamentId = matchInfo.tournamentId;
StartCoroutine(DownloadUpcomingMatches(tournamentId));
}
protected override void OnUpcomingMatchesDownloaded(UpcomingMatches upcomingMatches) {
Match[] matches = upcomingMatches.matches;
nextLeftPlayers.text = "";
nextRightPlayers.text = "";
for (int i = 0; i < 3 && i < matches.Length; i++) {
Match match = matches [i];
string botNameLeft = match.bots [0];
string botNameRight = match.bots [1];
if (i > 0) {
nextLeftPlayers.text += "\n";
nextRightPlayers.text += "\n";
}
nextLeftPlayers.text += botNameLeft;
nextRightPlayers.text += botNameRight;
}
}
private string createText(string botName, int pts) {
string sign = pts >= 0 ? "+" : "";
return botName + "\n" + sign + pts + " pts";
}
}
| hackcraft-sk/swarm | ubwtv/Assets/Scripts/EndScreenController.cs | C# | gpl-2.0 | 2,119 |
package fortesting;
import java.io.IOException;
public class RunTransformTim {
/**
* Loads data into appropriate tables (assumes scheme already created)
*
* This will import the tables from my CSVs, which I have on dropbox. Let me
* (Tim) know if you need the CSVs No guarantee that it works on CSVs
* generated differently
*
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// String host = "127.0.0.1";
String host = "52.32.209.104";
// String keyspace = "new";
String keyspace = "main";
String year = "2012";
// if an error occurs during upload of first CSV, use
// GetLastRow.getLastEntry() to find its
// npi value and use that as start. This will not work in other CSVs
// unless the last npi
// added is greater than the largest npi in all previously loaded CSVs
String start = "";
TransformTim t = new TransformTim();
t.injest(host, keyspace, "CSV/MedicareA2012.csv", year, start);
t.injest(host, keyspace, "CSV/MedicareB2012.csv", year, "");
t.injest(host, keyspace, "CSV/MedicareC2012.csv", year, "");
t.injest(host, keyspace, "CSV/MedicareD2012.csv", year, "");
t.injest(host, keyspace, "CSV/MedicareEG2012.csv", year, "");
t.injest(host, keyspace, "CSV/MedicareHJ2012.csv", year, "");
t.injest(host, keyspace, "CSV/MedicareKL2012.csv", year, "");
t.injest(host, keyspace, "CSV/MedicareMN2012.csv", year, "");
t.injest(host, keyspace, "CSV/MedicareOQ2012.csv", year, "");
t.injest(host, keyspace, "CSV/MedicareR2012.csv", year, "");
t.injest(host, keyspace, "CSV/MedicareS2012.csv", year, "");
t.injest(host, keyspace, "CSV/MedicareTX2012.csv", year, "");
t.injest(host, keyspace, "CSV/MedicareYZ2012.csv", year, "");
}
}
| ZheyuJin/CS8674.FALL2015.NEUSeattle | cassandra/Tim Cassandra Testing and Table Creation/RunTransformTim.java | Java | gpl-2.0 | 1,948 |
/*
* Open Firm Accounting
* A double-entry accounting application for professional services.
*
* Copyright (C) 2014-2020 Pierre Wieser (see AUTHORS)
*
* Open Firm Accounting 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.
*
* Open Firm Accounting 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 Open Firm Accounting; see the file COPYING. If not,
* see <http://www.gnu.org/licenses/>.
*
* Authors:
* Pierre Wieser <[email protected]>
*/
#ifndef __OPENBOOK_API_OFO_BASE_H__
#define __OPENBOOK_API_OFO_BASE_H__
/**
* SECTION: ofobase
* @title: ofoBase
* @short_description: #ofoBase class definition.
* @include: openbook/ofo-base.h
*
* The ofoBase class is the class base for application objects.
*
* Properties:
* - ofo-base-getter:
* a #ofaIGetter instance;
* no default, will be %NULL if has not been previously set.
*/
#include "api/ofa-box.h"
#include "api/ofa-idbconnect-def.h"
#include "api/ofa-igetter-def.h"
#include "api/ofo-base-def.h"
G_BEGIN_DECLS
#define OFO_TYPE_BASE ( ofo_base_get_type())
#define OFO_BASE( object ) ( G_TYPE_CHECK_INSTANCE_CAST( object, OFO_TYPE_BASE, ofoBase ))
#define OFO_BASE_CLASS( klass ) ( G_TYPE_CHECK_CLASS_CAST( klass, OFO_TYPE_BASE, ofoBaseClass ))
#define OFO_IS_BASE( object ) ( G_TYPE_CHECK_INSTANCE_TYPE( object, OFO_TYPE_BASE ))
#define OFO_IS_BASE_CLASS( klass ) ( G_TYPE_CHECK_CLASS_TYPE(( klass ), OFO_TYPE_BASE ))
#define OFO_BASE_GET_CLASS( object ) ( G_TYPE_INSTANCE_GET_CLASS(( object ), OFO_TYPE_BASE, ofoBaseClass ))
#if 0
typedef struct _ofoBaseProtected ofoBaseProtected;
typedef struct {
/*< public members >*/
GObject parent;
/*< protected members >*/
ofoBaseProtected *prot;
}
ofoBase;
typedef struct {
/*< public members >*/
GObjectClass parent;
}
ofoBaseClass;
#endif
/**
* ofo_base_getter:
* @C: the class radical (e.g. 'ACCOUNT')
* @V: the variable name (e.g. 'account')
* @T: the type of required data (e.g. 'amount')
* @R: the returned data if %NULL or an error occured (e.g. '0')
* @I: the identifier of the required field (e.g. 'ACC_DEB_AMOUNT')
*
* A convenience macro to get the value of an identified field from an
* #ofoBase object.
*/
#define ofo_base_getter(C,V,T,R,I) \
g_return_val_if_fail((V) && OFO_IS_ ## C(V),(R)); \
g_return_val_if_fail( !OFO_BASE(V)->prot->dispose_has_run, (R)); \
if( !ofa_box_is_set( OFO_BASE(V)->prot->fields,(I))) return(R); \
return(ofa_box_get_ ## T(OFO_BASE(V)->prot->fields,(I)))
/**
* ofo_base_setter:
* @C: the class mnemonic (e.g. 'ACCOUNT')
* @V: the variable name (e.g. 'account')
* @T: the type of required data (e.g. 'amount')
* @I: the identifier of the required field (e.g. 'ACC_DEB_AMOUNT')
* @D: the data value to be set
*
* A convenience macro to set the value of an identified field from an
* #ofoBase object.
*/
#define ofo_base_setter(C,V,T,I,D) \
g_return_if_fail((V) && OFO_IS_ ## C(V)); \
g_return_if_fail( !OFO_BASE(V)->prot->dispose_has_run ); \
ofa_box_set_ ## T(OFO_BASE(V)->prot->fields,(I),(D))
/**
* Identifier unset value
*/
#define OFO_BASE_UNSET_ID -1
GType ofo_base_get_type ( void ) G_GNUC_CONST;
GList *ofo_base_init_fields_list( const ofsBoxDef *defs );
GList *ofo_base_load_dataset ( const ofsBoxDef *defs,
const gchar *from,
GType type,
ofaIGetter *getter );
GList *ofo_base_load_rows ( const ofsBoxDef *defs,
const ofaIDBConnect *connect,
const gchar *from );
ofaIGetter *ofo_base_get_getter ( ofoBase *base );
G_END_DECLS
#endif /* __OPENBOOK_API_OFO_BASE_H__ */
| trychlos/openbook | src/api/ofo-base.h | C | gpl-2.0 | 4,134 |
package edu.cmu.cs.cimds.geogame.client.ui;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import edu.cmu.cs.cimds.geogame.client.model.dto.ItemDTO;
public class InventoryGrid extends Grid {
// public static final String MONEY_ICON_FILENAME = "coinbag.jpg";
public static final String BLANK_ICON_FILENAME = "blank.png";
private int numCells;
private VerticalPanel[] blanks;
private List<ItemDTO> inventory = new ArrayList<ItemDTO>();
private ItemImageCreator imageCreator;
private String imageWidth = null;
public InventoryGrid(int numRows, int numColumns) {
super(numRows, numColumns);
this.numCells = numRows * numColumns;
this.blanks = new VerticalPanel[this.numCells];
for(int i=0;i<numCells;i++) {
this.blanks[i] = new VerticalPanel();
this.blanks[i].add(new Image(BLANK_ICON_FILENAME));
this.setWidget(i, this.blanks[i]);
}
this.clearContent();
}
public InventoryGrid(int numRows, int numColumns, ItemImageCreator imageCreator) {
this(numRows, numColumns);
this.imageCreator = imageCreator;
}
public List<ItemDTO> getInventory() { return inventory; }
public void setInventory(List<ItemDTO> inventory) { this.inventory = inventory; }
// public void setInventory(List<ItemTypeDTO> inventory) {
// this.inventory = new ArrayList<ItemTypeDTO>();
// for(ItemTypeDTO itemType : inventory) {
// Item dummyItem = new Item();
// dummyItem.setItemType(itemType);
// this.inventory.add(dummyItem);
// }
// }
public ItemImageCreator getImageCreator() { return imageCreator; }
public void setImageCreator(ItemImageCreator imageCreator) { this.imageCreator = imageCreator; }
public void setImageWidth(String imageWidth) { this.imageWidth = imageWidth; }
public void setWidget(int numCell, Widget w) {
// if(numCell >= this.numCells) {
// throw new IndexOutOfBoundsException();
// }
super.setWidget((int)Math.floor(numCell/this.numColumns), numCell%this.numColumns, w);
}
public void clearContent() {
for(int i=0;i<numCells;i++) {
this.setWidget(i, this.blanks[i]);
}
}
public void refresh() {
this.clearContent();
Collections.sort(this.inventory);
for(int i=0;i<this.inventory.size();i++) {
final ItemDTO item = this.inventory.get(i);
Image image = this.imageCreator.createImage(item);
if(this.imageWidth!=null) {
image.setWidth(this.imageWidth);
}
//Label descriptionLabel = new Label(item.getItemType().getName() + " - " + item.getItemType().getBasePrice() + "G", true);
VerticalPanel itemPanel = new VerticalPanel();
itemPanel.add(image);
//itemPanel.add(descriptionLabel);
this.setWidget(i, itemPanel);
}
}
} | grapesmoker/geogame | src/edu/cmu/cs/cimds/geogame/client/ui/InventoryGrid.java | Java | gpl-2.0 | 2,903 |
<?php
/**
* @package phposm
* @copyright Copyright (C) 2015 Wene - ssm2017 Binder ( S.Massiaux ). All rights reserved.
* @link https://github.com/ssm2017/phposm
* @license GNU/GPL, http://www.gnu.org/licenses/gpl-2.0.html
* Phposm 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.
*/
function createArchiveUrl($file_path)
{
logWrite('[archive] createArchiveUrl called');
// check if file exists
if (!is_file($file_path))
{
logWrite('[archive] file not found : '. $file_path);
return False;
}
// parse the path
$splitted = explode('/', $file_path);
if ($splitted[1] != 'home' || $splitted[3] != 'opensimulator' or ($splitted[4] != 'iar' && $splitted[4] != 'oar'))
{
logWrite('[archive] wrong file path : '. $file_path);
return False;
}
$username = $splitted[2];
$archive_type = $splitted[4];
$expiration = time() + 300;
$url = '/archive?q='. $archive_type. '/'. $username. '/'. md5($expiration. ':'. $GLOBALS['config']['password']). '/'. $expiration. '/'. $splitted[5];
return $url;
}
function parseArchiveUrl($url)
{
logWrite('[archive] parseArchiveUrl called');
$splitted = explode('/', $url);
if ($splitted[1] != 'archive' || ($splitted[2] != 'oar' && $splitted[2] != 'iar'))
{
logWrite('[archive] wrong url : '. $url);
return Null;
}
$filename = $splitted[6];
$username = $splitted[3];
// check expiration
$expiration = $splitted[5];
$now = time();
if ($now > $expiration)
{
logWrite('[archive] url expired : '. $url);
return Null;
}
// check password
if ($splitted[4] != md5($expiration. ':'. $GLOBALS['config']['password']))
{
logWrite('[archive] wrong password');
return Null;
}
// check if file exists
$file_path = '/home/'. $username. '/opensimulator/'. $splitted[2]. '/'. $filename;
if (!is_file($file_path))
{
logWrite('[archive] file not found');
return Null;
}
return $file_path;
}
| ssm2017/phposm | includes/helpers/archive.php | PHP | gpl-2.0 | 2,275 |
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
Sig="/home/dai/tmp/Assignment#3/Size/Signature/BatchProcessing.m"
Rect="/home/dai/tmp/Assignment#3/Size/Rectangle/BatchProcessing.sh"
Eva="/home/dai/tmp/Assignment#3/Size/Evaluation/BatchProcessing.m"
MatlabExe="/opt/Matlab2013/bin/matlab"
${MatlabExe} -nodesktop -nosplash -r "run ${Sig};quit"
sh ${Rect}
${MatlabExe} -nodesktop -nosplash -r "run ${Eva};quit"
| zhenglab/2015SpringCV | Assignments/Assignment3Solutions/戴嘉伦/Grab/Size/Batch_Size.sh | Shell | gpl-2.0 | 451 |
<?php
/**
* NoNumber Framework Helper File: Assignments: Tags
*
* @package NoNumber Framework
* @version 14.9.9
*
* @author Peter van Westen <[email protected]>
* @link http://www.nonumber.nl
* @copyright Copyright © 2014 NoNumber All Rights Reserved
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
*/
defined('_JEXEC') or die;
/**
* Assignments: Tags
*/
class NNFrameworkAssignmentsTags
{
function passTags(&$parent, &$params, $selection = array(), $assignment = 'all', $article = 0)
{
$is_content = in_array($parent->params->option, array('com_content', 'com_flexicontent'));
if (!$is_content)
{
return $parent->pass(0, $assignment);
}
$is_item = in_array($parent->params->view, array('', 'article', 'item'));
$is_category = in_array($parent->params->view, array('category'));
if ($is_item)
{
$prefix = 'com_content.article';
}
else if ($is_category)
{
$prefix = 'com_content.category';
}
else
{
return $parent->pass(0, $assignment);
}
// Load the tags.
$parent->q->clear()
->select($parent->db->quoteName('t.id'))
->from('#__tags AS t')
->join(
'INNER', '#__contentitem_tag_map AS m'
. ' ON m.tag_id = t.id'
. ' AND m.type_alias = ' . $parent->db->quote($prefix)
. ' AND m.content_item_id IN ( ' . $parent->params->id . ')'
);
$parent->db->setQuery($parent->q);
$tags = $parent->db->loadColumn();
if (empty($tags))
{
return $parent->pass(0, $assignment);
}
$pass = 0;
foreach ($tags as $tag)
{
$pass = in_array($tag, $selection);
if ($pass && $params->inc_children == 2)
{
$pass = 0;
}
else if (!$pass && $params->inc_children)
{
$parentids = self::getParentIds($parent, $tag);
$parentids = array_diff($parentids, array('1'));
foreach ($parentids as $id)
{
if (in_array($id, $selection))
{
$pass = 1;
break;
}
}
unset($parentids);
}
}
return $parent->pass($pass, $assignment);
}
function getParentIds(&$parent, $id = 0)
{
return $parent->getParentIds($id, 'tags');
}
}
| rusuni/unicyclingru | plugins/system/nnframework/helpers/assignments/tags.php | PHP | gpl-2.0 | 2,139 |
/* GStreamer
* Copyright (C) 1999,2000 Erik Walthinsen <[email protected]>
* 2005 Wim Taymans <[email protected]>
*
* gstaudiosink.c: simple audio sink base class
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
/**
* SECTION:gstaudiosink
* @short_description: Simple base class for audio sinks
* @see_also: #GstAudioBaseSink, #GstAudioRingBuffer, #GstAudioSink.
*
* This is the most simple base class for audio sinks that only requires
* subclasses to implement a set of simple functions:
*
* <variablelist>
* <varlistentry>
* <term>open()</term>
* <listitem><para>Open the device.</para></listitem>
* </varlistentry>
* <varlistentry>
* <term>prepare()</term>
* <listitem><para>Configure the device with the specified format.</para></listitem>
* </varlistentry>
* <varlistentry>
* <term>write()</term>
* <listitem><para>Write samples to the device.</para></listitem>
* </varlistentry>
* <varlistentry>
* <term>reset()</term>
* <listitem><para>Unblock writes and flush the device.</para></listitem>
* </varlistentry>
* <varlistentry>
* <term>delay()</term>
* <listitem><para>Get the number of samples written but not yet played
* by the device.</para></listitem>
* </varlistentry>
* <varlistentry>
* <term>unprepare()</term>
* <listitem><para>Undo operations done by prepare.</para></listitem>
* </varlistentry>
* <varlistentry>
* <term>close()</term>
* <listitem><para>Close the device.</para></listitem>
* </varlistentry>
* </variablelist>
*
* All scheduling of samples and timestamps is done in this base class
* together with #GstAudioBaseSink using a default implementation of a
* #GstAudioRingBuffer that uses threads.
*/
#include <string.h>
#include <gst/audio/audio.h>
#include "gstaudiosink.h"
GST_DEBUG_CATEGORY_STATIC (gst_audio_sink_debug);
#define GST_CAT_DEFAULT gst_audio_sink_debug
#define GST_TYPE_AUDIO_SINK_RING_BUFFER \
(gst_audio_sink_ring_buffer_get_type())
#define GST_AUDIO_SINK_RING_BUFFER(obj) \
(G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_AUDIO_SINK_RING_BUFFER,GstAudioSinkRingBuffer))
#define GST_AUDIO_SINK_RING_BUFFER_CLASS(klass) \
(G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_AUDIO_SINK_RING_BUFFER,GstAudioSinkRingBufferClass))
#define GST_AUDIO_SINK_RING_BUFFER_GET_CLASS(obj) \
(G_TYPE_INSTANCE_GET_CLASS ((obj), GST_TYPE_AUDIO_SINK_RING_BUFFER, GstAudioSinkRingBufferClass))
#define GST_AUDIO_SINK_RING_BUFFER_CAST(obj) \
((GstAudioSinkRingBuffer *)obj)
#define GST_IS_AUDIO_SINK_RING_BUFFER(obj) \
(G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_AUDIO_SINK_RING_BUFFER))
#define GST_IS_AUDIO_SINK_RING_BUFFER_CLASS(klass)\
(G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_AUDIO_SINK_RING_BUFFER))
typedef struct _GstAudioSinkRingBuffer GstAudioSinkRingBuffer;
typedef struct _GstAudioSinkRingBufferClass GstAudioSinkRingBufferClass;
#define GST_AUDIO_SINK_RING_BUFFER_GET_COND(buf) (&(((GstAudioSinkRingBuffer *)buf)->cond))
#define GST_AUDIO_SINK_RING_BUFFER_WAIT(buf) (g_cond_wait (GST_AUDIO_SINK_RING_BUFFER_GET_COND (buf), GST_OBJECT_GET_LOCK (buf)))
#define GST_AUDIO_SINK_RING_BUFFER_SIGNAL(buf) (g_cond_signal (GST_AUDIO_SINK_RING_BUFFER_GET_COND (buf)))
#define GST_AUDIO_SINK_RING_BUFFER_BROADCAST(buf)(g_cond_broadcast (GST_AUDIO_SINK_RING_BUFFER_GET_COND (buf)))
struct _GstAudioSinkRingBuffer
{
GstAudioRingBuffer object;
gboolean running;
gint queuedseg;
GCond cond;
};
struct _GstAudioSinkRingBufferClass
{
GstAudioRingBufferClass parent_class;
};
static void gst_audio_sink_ring_buffer_class_init (GstAudioSinkRingBufferClass *
klass);
static void gst_audio_sink_ring_buffer_init (GstAudioSinkRingBuffer *
ringbuffer, GstAudioSinkRingBufferClass * klass);
static void gst_audio_sink_ring_buffer_dispose (GObject * object);
static void gst_audio_sink_ring_buffer_finalize (GObject * object);
static GstAudioRingBufferClass *ring_parent_class = NULL;
static gboolean gst_audio_sink_ring_buffer_open_device (GstAudioRingBuffer *
buf);
static gboolean gst_audio_sink_ring_buffer_close_device (GstAudioRingBuffer *
buf);
static gboolean gst_audio_sink_ring_buffer_acquire (GstAudioRingBuffer * buf,
GstAudioRingBufferSpec * spec);
static gboolean gst_audio_sink_ring_buffer_release (GstAudioRingBuffer * buf);
static gboolean gst_audio_sink_ring_buffer_start (GstAudioRingBuffer * buf);
static gboolean gst_audio_sink_ring_buffer_pause (GstAudioRingBuffer * buf);
static gboolean gst_audio_sink_ring_buffer_stop (GstAudioRingBuffer * buf);
static guint gst_audio_sink_ring_buffer_delay (GstAudioRingBuffer * buf);
static gboolean gst_audio_sink_ring_buffer_activate (GstAudioRingBuffer * buf,
gboolean active);
/* ringbuffer abstract base class */
static GType
gst_audio_sink_ring_buffer_get_type (void)
{
static GType ringbuffer_type = 0;
if (!ringbuffer_type) {
static const GTypeInfo ringbuffer_info = {
sizeof (GstAudioSinkRingBufferClass),
NULL,
NULL,
(GClassInitFunc) gst_audio_sink_ring_buffer_class_init,
NULL,
NULL,
sizeof (GstAudioSinkRingBuffer),
0,
(GInstanceInitFunc) gst_audio_sink_ring_buffer_init,
NULL
};
ringbuffer_type =
g_type_register_static (GST_TYPE_AUDIO_RING_BUFFER,
"GstAudioSinkRingBuffer", &ringbuffer_info, 0);
}
return ringbuffer_type;
}
static void
gst_audio_sink_ring_buffer_class_init (GstAudioSinkRingBufferClass * klass)
{
GObjectClass *gobject_class;
GstAudioRingBufferClass *gstringbuffer_class;
gobject_class = (GObjectClass *) klass;
gstringbuffer_class = (GstAudioRingBufferClass *) klass;
ring_parent_class = g_type_class_peek_parent (klass);
gobject_class->dispose = gst_audio_sink_ring_buffer_dispose;
gobject_class->finalize = gst_audio_sink_ring_buffer_finalize;
gstringbuffer_class->open_device =
GST_DEBUG_FUNCPTR (gst_audio_sink_ring_buffer_open_device);
gstringbuffer_class->close_device =
GST_DEBUG_FUNCPTR (gst_audio_sink_ring_buffer_close_device);
gstringbuffer_class->acquire =
GST_DEBUG_FUNCPTR (gst_audio_sink_ring_buffer_acquire);
gstringbuffer_class->release =
GST_DEBUG_FUNCPTR (gst_audio_sink_ring_buffer_release);
gstringbuffer_class->start =
GST_DEBUG_FUNCPTR (gst_audio_sink_ring_buffer_start);
gstringbuffer_class->pause =
GST_DEBUG_FUNCPTR (gst_audio_sink_ring_buffer_pause);
gstringbuffer_class->resume =
GST_DEBUG_FUNCPTR (gst_audio_sink_ring_buffer_start);
gstringbuffer_class->stop =
GST_DEBUG_FUNCPTR (gst_audio_sink_ring_buffer_stop);
gstringbuffer_class->delay =
GST_DEBUG_FUNCPTR (gst_audio_sink_ring_buffer_delay);
gstringbuffer_class->activate =
GST_DEBUG_FUNCPTR (gst_audio_sink_ring_buffer_activate);
}
typedef gint (*WriteFunc) (GstAudioSink * sink, gpointer data, guint length);
/* this internal thread does nothing else but write samples to the audio device.
* It will write each segment in the ringbuffer and will update the play
* pointer.
* The start/stop methods control the thread.
*/
static void
audioringbuffer_thread_func (GstAudioRingBuffer * buf)
{
GstAudioSink *sink;
GstAudioSinkClass *csink;
GstAudioSinkRingBuffer *abuf = GST_AUDIO_SINK_RING_BUFFER_CAST (buf);
WriteFunc writefunc;
GstMessage *message;
GValue val = { 0 };
sink = GST_AUDIO_SINK (GST_OBJECT_PARENT (buf));
csink = GST_AUDIO_SINK_GET_CLASS (sink);
GST_DEBUG_OBJECT (sink, "enter thread");
GST_OBJECT_LOCK (abuf);
GST_DEBUG_OBJECT (sink, "signal wait");
GST_AUDIO_SINK_RING_BUFFER_SIGNAL (buf);
GST_OBJECT_UNLOCK (abuf);
writefunc = csink->write;
if (writefunc == NULL)
goto no_function;
message = gst_message_new_stream_status (GST_OBJECT_CAST (buf),
GST_STREAM_STATUS_TYPE_ENTER, GST_ELEMENT_CAST (sink));
g_value_init (&val, GST_TYPE_G_THREAD);
g_value_set_boxed (&val, sink->thread);
gst_message_set_stream_status_object (message, &val);
g_value_unset (&val);
GST_DEBUG_OBJECT (sink, "posting ENTER stream status");
gst_element_post_message (GST_ELEMENT_CAST (sink), message);
while (TRUE) {
gint left, len;
guint8 *readptr;
gint readseg;
/* buffer must be started */
if (gst_audio_ring_buffer_prepare_read (buf, &readseg, &readptr, &len)) {
gint written;
left = len;
do {
written = writefunc (sink, readptr, left);
GST_LOG_OBJECT (sink, "transfered %d bytes of %d from segment %d",
written, left, readseg);
if (written < 0 || written > left) {
/* might not be critical, it e.g. happens when aborting playback */
GST_WARNING_OBJECT (sink,
"error writing data in %s (reason: %s), skipping segment (left: %d, written: %d)",
GST_DEBUG_FUNCPTR_NAME (writefunc),
(errno > 1 ? g_strerror (errno) : "unknown"), left, written);
break;
}
left -= written;
readptr += written;
} while (left > 0);
/* clear written samples */
gst_audio_ring_buffer_clear (buf, readseg);
/* we wrote one segment */
gst_audio_ring_buffer_advance (buf, 1);
} else {
GST_OBJECT_LOCK (abuf);
if (!abuf->running)
goto stop_running;
if (G_UNLIKELY (g_atomic_int_get (&buf->state) ==
GST_AUDIO_RING_BUFFER_STATE_STARTED)) {
GST_OBJECT_UNLOCK (abuf);
continue;
}
GST_DEBUG_OBJECT (sink, "signal wait");
GST_AUDIO_SINK_RING_BUFFER_SIGNAL (buf);
GST_DEBUG_OBJECT (sink, "wait for action");
GST_AUDIO_SINK_RING_BUFFER_WAIT (buf);
GST_DEBUG_OBJECT (sink, "got signal");
if (!abuf->running)
goto stop_running;
GST_DEBUG_OBJECT (sink, "continue running");
GST_OBJECT_UNLOCK (abuf);
}
}
/* Will never be reached */
g_assert_not_reached ();
return;
/* ERROR */
no_function:
{
GST_DEBUG_OBJECT (sink, "no write function, exit thread");
return;
}
stop_running:
{
GST_OBJECT_UNLOCK (abuf);
GST_DEBUG_OBJECT (sink, "stop running, exit thread");
message = gst_message_new_stream_status (GST_OBJECT_CAST (buf),
GST_STREAM_STATUS_TYPE_LEAVE, GST_ELEMENT_CAST (sink));
g_value_init (&val, GST_TYPE_G_THREAD);
g_value_set_boxed (&val, sink->thread);
gst_message_set_stream_status_object (message, &val);
g_value_unset (&val);
GST_DEBUG_OBJECT (sink, "posting LEAVE stream status");
gst_element_post_message (GST_ELEMENT_CAST (sink), message);
return;
}
}
static void
gst_audio_sink_ring_buffer_init (GstAudioSinkRingBuffer * ringbuffer,
GstAudioSinkRingBufferClass * g_class)
{
ringbuffer->running = FALSE;
ringbuffer->queuedseg = 0;
g_cond_init (&ringbuffer->cond);
}
static void
gst_audio_sink_ring_buffer_dispose (GObject * object)
{
G_OBJECT_CLASS (ring_parent_class)->dispose (object);
}
static void
gst_audio_sink_ring_buffer_finalize (GObject * object)
{
GstAudioSinkRingBuffer *ringbuffer = GST_AUDIO_SINK_RING_BUFFER_CAST (object);
g_cond_clear (&ringbuffer->cond);
G_OBJECT_CLASS (ring_parent_class)->finalize (object);
}
static gboolean
gst_audio_sink_ring_buffer_open_device (GstAudioRingBuffer * buf)
{
GstAudioSink *sink;
GstAudioSinkClass *csink;
gboolean result = TRUE;
sink = GST_AUDIO_SINK (GST_OBJECT_PARENT (buf));
csink = GST_AUDIO_SINK_GET_CLASS (sink);
if (csink->open)
result = csink->open (sink);
if (!result)
goto could_not_open;
return result;
could_not_open:
{
GST_DEBUG_OBJECT (sink, "could not open device");
return FALSE;
}
}
static gboolean
gst_audio_sink_ring_buffer_close_device (GstAudioRingBuffer * buf)
{
GstAudioSink *sink;
GstAudioSinkClass *csink;
gboolean result = TRUE;
sink = GST_AUDIO_SINK (GST_OBJECT_PARENT (buf));
csink = GST_AUDIO_SINK_GET_CLASS (sink);
if (csink->close)
result = csink->close (sink);
if (!result)
goto could_not_close;
return result;
could_not_close:
{
GST_DEBUG_OBJECT (sink, "could not close device");
return FALSE;
}
}
static gboolean
gst_audio_sink_ring_buffer_acquire (GstAudioRingBuffer * buf,
GstAudioRingBufferSpec * spec)
{
GstAudioSink *sink;
GstAudioSinkClass *csink;
gboolean result = FALSE;
sink = GST_AUDIO_SINK (GST_OBJECT_PARENT (buf));
csink = GST_AUDIO_SINK_GET_CLASS (sink);
if (csink->prepare)
result = csink->prepare (sink, spec);
if (!result)
goto could_not_prepare;
/* set latency to one more segment as we need some headroom */
spec->seglatency = spec->segtotal + 1;
buf->size = spec->segtotal * spec->segsize;
buf->memory = g_malloc (buf->size);
if (buf->spec.type == GST_AUDIO_RING_BUFFER_FORMAT_TYPE_RAW) {
gst_audio_format_fill_silence (buf->spec.info.finfo, buf->memory,
buf->size);
} else {
/* FIXME, non-raw formats get 0 as the empty sample */
memset (buf->memory, 0, buf->size);
}
return TRUE;
/* ERRORS */
could_not_prepare:
{
GST_DEBUG_OBJECT (sink, "could not prepare device");
return FALSE;
}
}
static gboolean
gst_audio_sink_ring_buffer_activate (GstAudioRingBuffer * buf, gboolean active)
{
GstAudioSink *sink;
GstAudioSinkRingBuffer *abuf;
GError *error = NULL;
sink = GST_AUDIO_SINK (GST_OBJECT_PARENT (buf));
abuf = GST_AUDIO_SINK_RING_BUFFER_CAST (buf);
if (active) {
abuf->running = TRUE;
GST_DEBUG_OBJECT (sink, "starting thread");
sink->thread = g_thread_try_new ("audiosink-ringbuffer",
(GThreadFunc) audioringbuffer_thread_func, buf, &error);
if (!sink->thread || error != NULL)
goto thread_failed;
GST_DEBUG_OBJECT (sink, "waiting for thread");
/* the object lock is taken */
GST_AUDIO_SINK_RING_BUFFER_WAIT (buf);
GST_DEBUG_OBJECT (sink, "thread is started");
} else {
abuf->running = FALSE;
GST_DEBUG_OBJECT (sink, "signal wait");
GST_AUDIO_SINK_RING_BUFFER_SIGNAL (buf);
GST_OBJECT_UNLOCK (buf);
/* join the thread */
g_thread_join (sink->thread);
GST_OBJECT_LOCK (buf);
}
return TRUE;
/* ERRORS */
thread_failed:
{
if (error)
GST_ERROR_OBJECT (sink, "could not create thread %s", error->message);
else
GST_ERROR_OBJECT (sink, "could not create thread for unknown reason");
g_clear_error (&error);
return FALSE;
}
}
/* function is called with LOCK */
static gboolean
gst_audio_sink_ring_buffer_release (GstAudioRingBuffer * buf)
{
GstAudioSink *sink;
GstAudioSinkClass *csink;
gboolean result = FALSE;
sink = GST_AUDIO_SINK (GST_OBJECT_PARENT (buf));
csink = GST_AUDIO_SINK_GET_CLASS (sink);
/* free the buffer */
g_free (buf->memory);
buf->memory = NULL;
if (csink->unprepare)
result = csink->unprepare (sink);
if (!result)
goto could_not_unprepare;
GST_DEBUG_OBJECT (sink, "unprepared");
return result;
could_not_unprepare:
{
GST_DEBUG_OBJECT (sink, "could not unprepare device");
return FALSE;
}
}
static gboolean
gst_audio_sink_ring_buffer_start (GstAudioRingBuffer * buf)
{
GstAudioSink *sink;
sink = GST_AUDIO_SINK (GST_OBJECT_PARENT (buf));
GST_DEBUG_OBJECT (sink, "start, sending signal");
GST_AUDIO_SINK_RING_BUFFER_SIGNAL (buf);
return TRUE;
}
static gboolean
gst_audio_sink_ring_buffer_pause (GstAudioRingBuffer * buf)
{
GstAudioSink *sink;
GstAudioSinkClass *csink;
sink = GST_AUDIO_SINK (GST_OBJECT_PARENT (buf));
csink = GST_AUDIO_SINK_GET_CLASS (sink);
/* unblock any pending writes to the audio device */
if (csink->reset) {
GST_DEBUG_OBJECT (sink, "reset...");
csink->reset (sink);
GST_DEBUG_OBJECT (sink, "reset done");
}
return TRUE;
}
static gboolean
gst_audio_sink_ring_buffer_stop (GstAudioRingBuffer * buf)
{
GstAudioSink *sink;
GstAudioSinkClass *csink;
sink = GST_AUDIO_SINK (GST_OBJECT_PARENT (buf));
csink = GST_AUDIO_SINK_GET_CLASS (sink);
/* unblock any pending writes to the audio device */
if (csink->reset) {
GST_DEBUG_OBJECT (sink, "reset...");
csink->reset (sink);
GST_DEBUG_OBJECT (sink, "reset done");
}
#if 0
if (abuf->running) {
GST_DEBUG_OBJECT (sink, "stop, waiting...");
GST_AUDIO_SINK_RING_BUFFER_WAIT (buf);
GST_DEBUG_OBJECT (sink, "stopped");
}
#endif
return TRUE;
}
static guint
gst_audio_sink_ring_buffer_delay (GstAudioRingBuffer * buf)
{
GstAudioSink *sink;
GstAudioSinkClass *csink;
guint res = 0;
sink = GST_AUDIO_SINK (GST_OBJECT_PARENT (buf));
csink = GST_AUDIO_SINK_GET_CLASS (sink);
if (csink->delay)
res = csink->delay (sink);
return res;
}
/* AudioSink signals and args */
enum
{
/* FILL ME */
LAST_SIGNAL
};
enum
{
ARG_0,
};
#define _do_init \
GST_DEBUG_CATEGORY_INIT (gst_audio_sink_debug, "audiosink", 0, "audiosink element");
#define gst_audio_sink_parent_class parent_class
G_DEFINE_TYPE_WITH_CODE (GstAudioSink, gst_audio_sink,
GST_TYPE_AUDIO_BASE_SINK, _do_init);
static GstAudioRingBuffer *gst_audio_sink_create_ringbuffer (GstAudioBaseSink *
sink);
static void
gst_audio_sink_class_init (GstAudioSinkClass * klass)
{
GstAudioBaseSinkClass *gstaudiobasesink_class;
gstaudiobasesink_class = (GstAudioBaseSinkClass *) klass;
gstaudiobasesink_class->create_ringbuffer =
GST_DEBUG_FUNCPTR (gst_audio_sink_create_ringbuffer);
g_type_class_ref (GST_TYPE_AUDIO_SINK_RING_BUFFER);
}
static void
gst_audio_sink_init (GstAudioSink * audiosink)
{
}
static GstAudioRingBuffer *
gst_audio_sink_create_ringbuffer (GstAudioBaseSink * sink)
{
GstAudioRingBuffer *buffer;
GST_DEBUG_OBJECT (sink, "creating ringbuffer");
buffer = g_object_new (GST_TYPE_AUDIO_SINK_RING_BUFFER, NULL);
GST_DEBUG_OBJECT (sink, "created ringbuffer @%p", buffer);
return buffer;
}
| iperry/gst-plugins-base | gst-libs/gst/audio/gstaudiosink.c | C | gpl-2.0 | 18,574 |
/**
@file TextOutput.cpp
@maintainer Morgan McGuire, http://graphics.cs.williams.edu
@created 2004-06-21
@edited 2010-03-14
Copyright 2000-2010, Morgan McGuire.
All rights reserved.
*/
#include "G3D/TextOutput.h"
#include "G3D/Log.h"
#include "G3D/fileutils.h"
#include "G3D/FileSystem.h"
namespace G3D {
TextOutput::TextOutput(const TextOutput::Settings& opt) :
startingNewLine(true),
currentColumn(0),
inDQuote(false),
filename(""),
indentLevel(0)
{
setOptions(opt);
}
TextOutput::TextOutput(const std::string& fil, const TextOutput::Settings& opt) :
startingNewLine(true),
currentColumn(0),
inDQuote(false),
filename(fil),
indentLevel(0)
{
setOptions(opt);
}
void TextOutput::setIndentLevel(int i) {
indentLevel = i;
// If there were more pops than pushes, don't let that take us below 0 indent.
// Don't ever indent more than the number of columns.
indentSpaces =
iClamp(option.spacesPerIndent * indentLevel,
0,
option.numColumns - 1);
}
void TextOutput::setOptions(const Settings& _opt) {
option = _opt;
debugAssert(option.numColumns > 1);
setIndentLevel(indentLevel);
newline = (option.newlineStyle == Settings::NEWLINE_WINDOWS) ? "\r\n" : "\n";
}
void TextOutput::pushIndent() {
setIndentLevel(indentLevel + 1);
}
void TextOutput::popIndent() {
setIndentLevel(indentLevel - 1);
}
static std::string escape(const std::string& string) {
std::string result = "";
for (std::string::size_type i = 0; i < string.length(); ++i) {
char c = string.at(i);
switch (c) {
case '\0':
result += "\\0";
break;
case '\r':
result += "\\r";
break;
case '\n':
result += "\\n";
break;
case '\t':
result += "\\t";
break;
case '\\':
result += "\\\\";
break;
default:
result += c;
}
}
return result;
}
void TextOutput::writeString(const std::string& string) {
// Convert special characters to escape sequences
this->printf("\"%s\"", escape(string).c_str());
}
void TextOutput::writeBoolean(bool b) {
this->printf("%s ", b ? option.trueSymbol.c_str() : option.falseSymbol.c_str());
}
void TextOutput::writeNumber(double n) {
this->printf("%f ", n);
}
void TextOutput::writeNumber(int n) {
this->printf("%d ", n);
}
void TextOutput::writeSymbol(const std::string& string) {
if (string.size() > 0) {
// TODO: check for legal symbols?
this->printf("%s ", string.c_str());
}
}
void TextOutput::writeSymbols(
const std::string& a,
const std::string& b,
const std::string& c,
const std::string& d,
const std::string& e,
const std::string& f) {
writeSymbol(a);
writeSymbol(b);
writeSymbol(c);
writeSymbol(d);
writeSymbol(e);
writeSymbol(f);
}
void TextOutput::printf(const std::string formatString, ...) {
va_list argList;
va_start(argList, formatString);
this->vprintf(formatString.c_str(), argList);
va_end(argList);
}
void TextOutput::printf(const char* formatString, ...) {
va_list argList;
va_start(argList, formatString);
this->vprintf(formatString, argList);
va_end(argList);
}
void TextOutput::convertNewlines(const std::string& in, std::string& out) {
// TODO: can be significantly optimized in cases where
// single characters are copied in order by walking through
// the array and copying substrings as needed.
if (option.convertNewlines) {
out = "";
for (uint32 i = 0; i < in.size(); ++i) {
if (in[i] == '\n') {
// Unix newline
out += newline;
} else if ((in[i] == '\r') && (i + 1 < in.size()) && (in[i + 1] == '\n')) {
// Windows newline
out += newline;
++i;
} else {
out += in[i];
}
}
} else {
out = in;
}
}
void TextOutput::writeNewline() {
for (uint32 i = 0; i < newline.size(); ++i) {
indentAppend(newline[i]);
}
}
void TextOutput::writeNewlines(int numLines) {
for (int i = 0; i < numLines; ++i) {
writeNewline();
}
}
void TextOutput::wordWrapIndentAppend(const std::string& str) {
// TODO: keep track of the last space character we saw so we don't
// have to always search.
if ((option.wordWrap == Settings::WRAP_NONE) ||
(currentColumn + (int)str.size() <= option.numColumns)) {
// No word-wrapping is needed
// Add one character at a time.
// TODO: optimize for strings without newlines to add multiple
// characters.
for (uint32 i = 0; i < str.size(); ++i) {
indentAppend(str[i]);
}
return;
}
// Number of columns to wrap against
int cols = option.numColumns - indentSpaces;
// Copy forward until we exceed the column size,
// and then back up and try to insert newlines as needed.
for (uint32 i = 0; i < str.size(); ++i) {
indentAppend(str[i]);
if ((str[i] == '\r') && (i + 1 < str.size()) && (str[i + 1] == '\n')) {
// \r\n, we need to hit the \n to enter word wrapping.
++i;
indentAppend(str[i]);
}
if (currentColumn >= cols) {
debugAssertM(str[i] != '\n' && str[i] != '\r',
"Should never enter word-wrapping on a newline character");
// True when we're allowed to treat a space as a space.
bool unquotedSpace = option.allowWordWrapInsideDoubleQuotes || ! inDQuote;
// Cases:
//
// 1. Currently in a series of spaces that ends with a newline
// strip all spaces and let the newline
// flow through.
//
// 2. Currently in a series of spaces that does not end with a newline
// strip all spaces and replace them with single newline
//
// 3. Not in a series of spaces
// search backwards for a space, then execute case 2.
// Index of most recent space
uint32 lastSpace = data.size() - 1;
// How far back we had to look for a space
uint32 k = 0;
uint32 maxLookBackward = currentColumn - indentSpaces;
// Search backwards (from current character), looking for a space.
while ((k < maxLookBackward) &&
(lastSpace > 0) &&
(! ((data[lastSpace] == ' ') && unquotedSpace))) {
--lastSpace;
++k;
if ((data[lastSpace] == '\"') && !option.allowWordWrapInsideDoubleQuotes) {
unquotedSpace = ! unquotedSpace;
}
}
if (k == maxLookBackward) {
// We couldn't find a series of spaces
if (option.wordWrap == Settings::WRAP_ALWAYS) {
// Strip the last character we wrote, force a newline,
// and replace the last character;
data.pop();
writeNewline();
indentAppend(str[i]);
} else {
// Must be Settings::WRAP_WITHOUT_BREAKING
//
// Don't write the newline; we'll come back to
// the word wrap code after writing another character
}
} else {
// We found a series of spaces. If they continue
// to the new string, strip spaces off both. Otherwise
// strip spaces from data only and insert a newline.
// Find the start of the spaces. firstSpace is the index of the
// first non-space, looking backwards from lastSpace.
uint32 firstSpace = lastSpace;
while ((k < maxLookBackward) &&
(firstSpace > 0) &&
(data[firstSpace] == ' ')) {
--firstSpace;
++k;
}
if (k == maxLookBackward) {
++firstSpace;
}
if (lastSpace == (uint32)data.size() - 1) {
// Spaces continued up to the new string
data.resize(firstSpace + 1);
writeNewline();
// Delete the spaces from the new string
while ((i < str.size() - 1) && (str[i + 1] == ' ')) {
++i;
}
} else {
// Spaces were somewhere in the middle of the old string.
// replace them with a newline.
// Copy over the characters that should be saved
Array<char> temp;
for (uint32 j = lastSpace + 1; j < (uint32)data.size(); ++j) {
char c = data[j];
if (c == '\"') {
// Undo changes to quoting (they will be re-done
// when we paste these characters back on).
inDQuote = !inDQuote;
}
temp.append(c);
}
// Remove those characters and replace with a newline.
data.resize(firstSpace + 1);
writeNewline();
// Write them back
for (uint32 j = 0; j < (uint32)temp.size(); ++j) {
indentAppend(temp[j]);
}
// We are now free to continue adding from the
// new string, which may or may not begin with spaces.
} // if spaces included new string
} // if hit indent
} // if line exceeded
} // iterate over str
}
void TextOutput::indentAppend(char c) {
if (startingNewLine) {
for (int j = 0; j < indentSpaces; ++j) {
data.push(' ');
}
startingNewLine = false;
currentColumn = indentSpaces;
}
data.push(c);
// Don't increment the column count on return character
// newline is taken care of below.
if (c != '\r') {
++currentColumn;
}
if (c == '\"') {
inDQuote = ! inDQuote;
}
startingNewLine = (c == '\n');
if (startingNewLine) {
currentColumn = 0;
}
}
void TextOutput::vprintf(const char* formatString, va_list argPtr) {
std::string str = vformat(formatString, argPtr);
std::string clean;
convertNewlines(str, clean);
wordWrapIndentAppend(clean);
}
void TextOutput::commit(bool flush) {
std::string p = filenamePath(filename);
if (! FileSystem::exists(p, false)) {
FileSystem::createDirectory(p);
}
FILE* f = FileSystem::fopen(filename.c_str(), "wb");
debugAssertM(f, "Could not open \"" + filename + "\"");
fwrite(data.getCArray(), 1, data.size(), f);
if (flush) {
fflush(f);
}
FileSystem::fclose(f);
}
void TextOutput::commitString(std::string& out) {
// Null terminate
data.push('\0');
out = data.getCArray();
data.pop();
}
std::string TextOutput::commitString() {
std::string str;
commitString(str);
return str;
}
/////////////////////////////////////////////////////////////////////
void serialize(const float& b, TextOutput& to) {
to.writeNumber(b);
}
void serialize(const bool& b, TextOutput& to) {
to.writeSymbol(b ? "true" : "false");
}
void serialize(const int& b, TextOutput& to) {
to.writeNumber(b);
}
void serialize(const uint8& b, TextOutput& to) {
to.writeNumber(b);
}
void serialize(const double& b, TextOutput& to) {
to.writeNumber(b);
}
}
| SeTM/MythCore | dep/g3dlite/source/TextOutput.cpp | C++ | gpl-2.0 | 11,994 |
/*
* kernel/workqueue.c - generic async execution with shared worker pool
*
* Copyright (C) 2002 Ingo Molnar
*
* Derived from the taskqueue/keventd code by:
* David Woodhouse <[email protected]>
* Andrew Morton
* Kai Petzke <[email protected]>
* Theodore Ts'o <[email protected]>
*
* Made to use alloc_percpu by Christoph Lameter.
*
* Copyright (C) 2010 SUSE Linux Products GmbH
* Copyright (C) 2010 Tejun Heo <[email protected]>
*
* 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/bug.h>
#include <linux/module.h>
#include "workqueue_sched.h"
enum {
/* global_cwq flags */
GCWQ_DISASSOCIATED = 1 << 0, /* cpu can't serve workers */
GCWQ_FREEZING = 1 << 1, /* freeze in progress */
/* pool flags */
POOL_MANAGE_WORKERS = 1 << 0, /* need to manage workers */
POOL_MANAGING_WORKERS = 1 << 1, /* managing workers */
/* 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_ROGUE = 1 << 4, /* not bound to any cpu */
WORKER_REBIND = 1 << 5, /* mom is home, come back */
WORKER_CPU_INTENSIVE = 1 << 6, /* cpu intensive */
WORKER_UNBOUND = 1 << 7, /* worker is unbound */
WORKER_NOT_RUNNING = WORKER_PREP | WORKER_ROGUE | WORKER_REBIND |
WORKER_CPU_INTENSIVE | WORKER_UNBOUND,
/* gcwq->trustee_state */
TRUSTEE_START = 0, /* start */
TRUSTEE_IN_CHARGE = 1, /* trustee in charge of gcwq */
TRUSTEE_BUTCHER = 2, /* butcher workers */
TRUSTEE_RELEASE = 3, /* release workers */
TRUSTEE_DONE = 4, /* trustee is done */
NR_WORKER_POOLS = 2, /* # worker pools per gcwq */
BUSY_WORKER_HASH_ORDER = 6, /* 64 pointers */
BUSY_WORKER_HASH_SIZE = 1 << BUSY_WORKER_HASH_ORDER,
BUSY_WORKER_HASH_MASK = BUSY_WORKER_HASH_SIZE - 1,
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 */
TRUSTEE_COOLDOWN = HZ / 10, /* for trustee draining */
/*
* Rescue workers are used only on emergencies and shared by
* all cpus. Give -20.
*/
RESCUER_NICE_LEVEL = -20,
HIGHPRI_NICE_LEVEL = -20,
};
/*
* 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: gcwq->lock protected. Access with gcwq->lock held.
*
* X: During normal operation, modification requires gcwq->lock and
* should be done only from local cpu. Either disabling preemption
* on local cpu or grabbing gcwq->lock is enough for read access.
* If GCWQ_DISASSOCIATED is set, it's identical to L.
*
* F: wq->flush_mutex protected.
*
* W: workqueue_lock protected.
*/
struct global_cwq;
struct worker_pool;
/*
* The poor guys doing the actual heavy lifting. All on-duty workers
* are either serving the manager role, on idle list or on busy hash.
*/
struct worker {
/* on idle list while idle, on busy hash table while busy */
union {
struct list_head entry; /* L: while idle */
struct hlist_node hentry; /* L: while busy */
};
struct work_struct *current_work; /* L: work being processed */
struct cpu_workqueue_struct *current_cwq; /* L: current_work's cwq */
struct list_head scheduled; /* L: scheduled works */
struct task_struct *task; /* I: worker task */
struct worker_pool *pool; /* I: the associated pool */
/* 64 bytes boundary on 64bit, 32 on 32bit */
unsigned long last_active; /* L: last active timestamp */
unsigned int flags; /* X: flags */
int id; /* I: worker id */
struct work_struct rebind_work; /* L: rebind worker to cpu */
};
struct worker_pool {
struct global_cwq *gcwq; /* I: the owning gcwq */
unsigned int flags; /* X: flags */
struct list_head worklist; /* L: list of pending works */
int nr_workers; /* L: total number of workers */
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 */
struct ida worker_ida; /* L: for worker IDs */
struct worker *first_idle; /* L: first idle worker */
};
/*
* Global per-cpu workqueue. There's one and only one for each cpu
* and all works are queued and processed here regardless of their
* target workqueues.
*/
struct global_cwq {
spinlock_t lock; /* the gcwq lock */
unsigned int cpu; /* I: the associated cpu */
unsigned int flags; /* L: GCWQ_* flags */
/* workers are chained either in busy_hash or pool idle_list */
struct hlist_head busy_hash[BUSY_WORKER_HASH_SIZE];
/* L: hash of busy workers */
struct worker_pool pools[2]; /* normal and highpri pools */
struct task_struct *trustee; /* L: for gcwq shutdown */
unsigned int trustee_state; /* L: trustee state */
wait_queue_head_t trustee_wait; /* trustee wait */
} ____cacheline_aligned_in_smp;
/*
* The per-CPU workqueue. The lower WORK_STRUCT_FLAG_BITS of
* work_struct->data are used for flags and thus cwqs need to be
* aligned at two's power of the number of flag bits.
*/
struct cpu_workqueue_struct {
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 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 */
};
/*
* Structure used to wait for workqueue flush.
*/
struct wq_flusher {
struct list_head list; /* F: list of flushers */
int flush_color; /* F: flush color waiting for */
struct completion done; /* flush completion */
};
/*
* All cpumasks are assumed to be always set on UP and thus can't be
* used to determine whether there's something to be done.
*/
#ifdef CONFIG_SMP
typedef cpumask_var_t mayday_mask_t;
#define mayday_test_and_set_cpu(cpu, mask) \
cpumask_test_and_set_cpu((cpu), (mask))
#define mayday_clear_cpu(cpu, mask) cpumask_clear_cpu((cpu), (mask))
#define for_each_mayday_cpu(cpu, mask) for_each_cpu((cpu), (mask))
#define alloc_mayday_mask(maskp, gfp) zalloc_cpumask_var((maskp), (gfp))
#define free_mayday_mask(mask) free_cpumask_var((mask))
#else
typedef unsigned long mayday_mask_t;
#define mayday_test_and_set_cpu(cpu, mask) test_and_set_bit(0, &(mask))
#define mayday_clear_cpu(cpu, mask) clear_bit(0, &(mask))
#define for_each_mayday_cpu(cpu, mask) if ((cpu) = 0, (mask))
#define alloc_mayday_mask(maskp, gfp) true
#define free_mayday_mask(mask) do { } while (0)
#endif
/*
* The externally visible workqueue abstraction is an array of
* per-CPU workqueues:
*/
struct workqueue_struct {
unsigned int flags; /* W: WQ_* flags */
union {
struct cpu_workqueue_struct __percpu *pcpu;
struct cpu_workqueue_struct *single;
unsigned long v;
} cpu_wq; /* I: cwq's */
struct list_head list; /* W: list of all workqueues */
struct mutex flush_mutex; /* protects wq flushing */
int work_color; /* F: current work color */
int flush_color; /* F: current flush color */
atomic_t nr_cwqs_to_flush; /* flush in progress */
struct wq_flusher *first_flusher; /* F: first flusher */
struct list_head flusher_queue; /* F: flush waiters */
struct list_head flusher_overflow; /* F: flush overflow list */
mayday_mask_t mayday_mask; /* cpus requesting rescue */
struct worker *rescuer; /* I: rescue worker */
int nr_drainers; /* W: drain in progress */
int saved_max_active; /* W: saved cwq max_active */
#ifdef CONFIG_LOCKDEP
struct lockdep_map lockdep_map;
#endif
char name[]; /* I: workqueue name */
};
/* see the comment above the definition of WQ_POWER_EFFICIENT */
#ifdef CONFIG_WQ_POWER_EFFICIENT_DEFAULT
static bool wq_power_efficient = true;
#else
static bool wq_power_efficient;
#endif
module_param_named(power_efficient, wq_power_efficient, bool, 0444);
struct workqueue_struct *system_wq __read_mostly;
struct workqueue_struct *system_long_wq __read_mostly;
struct workqueue_struct *system_nrt_wq __read_mostly;
struct workqueue_struct *system_unbound_wq __read_mostly;
struct workqueue_struct *system_freezable_wq __read_mostly;
struct workqueue_struct *system_nrt_freezable_wq __read_mostly;
struct workqueue_struct *system_power_efficient_wq __read_mostly;
struct workqueue_struct *system_freezable_power_efficient_wq __read_mostly;
EXPORT_SYMBOL_GPL(system_wq);
EXPORT_SYMBOL_GPL(system_long_wq);
EXPORT_SYMBOL_GPL(system_nrt_wq);
EXPORT_SYMBOL_GPL(system_unbound_wq);
EXPORT_SYMBOL_GPL(system_freezable_wq);
EXPORT_SYMBOL_GPL(system_nrt_freezable_wq);
EXPORT_SYMBOL_GPL(system_power_efficient_wq);
EXPORT_SYMBOL_GPL(system_freezable_power_efficient_wq);
#define CREATE_TRACE_POINTS
#include <trace/events/workqueue.h>
#define for_each_worker_pool(pool, gcwq) \
for ((pool) = &(gcwq)->pools[0]; \
(pool) < &(gcwq)->pools[NR_WORKER_POOLS]; (pool)++)
#define for_each_busy_worker(worker, i, pos, gcwq) \
for (i = 0; i < BUSY_WORKER_HASH_SIZE; i++) \
hlist_for_each_entry(worker, pos, &gcwq->busy_hash[i], hentry)
static inline int __next_gcwq_cpu(int cpu, const struct cpumask *mask,
unsigned int sw)
{
if (cpu < nr_cpu_ids) {
if (sw & 1) {
cpu = cpumask_next(cpu, mask);
if (cpu < nr_cpu_ids)
return cpu;
}
if (sw & 2)
return WORK_CPU_UNBOUND;
}
return WORK_CPU_NONE;
}
static inline int __next_wq_cpu(int cpu, const struct cpumask *mask,
struct workqueue_struct *wq)
{
return __next_gcwq_cpu(cpu, mask, !(wq->flags & WQ_UNBOUND) ? 1 : 2);
}
/*
* CPU iterators
*
* An extra gcwq is defined for an invalid cpu number
* (WORK_CPU_UNBOUND) to host workqueues which are not bound to any
* specific CPU. The following iterators are similar to
* for_each_*_cpu() iterators but also considers the unbound gcwq.
*
* for_each_gcwq_cpu() : possible CPUs + WORK_CPU_UNBOUND
* for_each_online_gcwq_cpu() : online CPUs + WORK_CPU_UNBOUND
* for_each_cwq_cpu() : possible CPUs for bound workqueues,
* WORK_CPU_UNBOUND for unbound workqueues
*/
#define for_each_gcwq_cpu(cpu) \
for ((cpu) = __next_gcwq_cpu(-1, cpu_possible_mask, 3); \
(cpu) < WORK_CPU_NONE; \
(cpu) = __next_gcwq_cpu((cpu), cpu_possible_mask, 3))
#define for_each_online_gcwq_cpu(cpu) \
for ((cpu) = __next_gcwq_cpu(-1, cpu_online_mask, 3); \
(cpu) < WORK_CPU_NONE; \
(cpu) = __next_gcwq_cpu((cpu), cpu_online_mask, 3))
#define for_each_cwq_cpu(cpu, wq) \
for ((cpu) = __next_wq_cpu(-1, cpu_possible_mask, (wq)); \
(cpu) < WORK_CPU_NONE; \
(cpu) = __next_wq_cpu((cpu), cpu_possible_mask, (wq)))
#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
/* Serializes the accesses to the list of workqueues. */
static DEFINE_SPINLOCK(workqueue_lock);
static LIST_HEAD(workqueues);
static bool workqueue_freezing; /* W: have wqs started freezing? */
/*
* The almighty global cpu workqueues. nr_running is the only field
* which is expected to be used frequently by other cpus via
* try_to_wake_up(). Put it in a separate cacheline.
*/
static DEFINE_PER_CPU(struct global_cwq, global_cwq);
static DEFINE_PER_CPU_SHARED_ALIGNED(atomic_t, pool_nr_running[NR_WORKER_POOLS]);
/*
* Global cpu workqueue and nr_running counter for unbound gcwq. The
* gcwq is always online, has GCWQ_DISASSOCIATED set, and all its
* workers have WORKER_UNBOUND set.
*/
static struct global_cwq unbound_global_cwq;
static atomic_t unbound_pool_nr_running[NR_WORKER_POOLS] = {
[0 ... NR_WORKER_POOLS - 1] = ATOMIC_INIT(0), /* always 0 */
};
static int worker_thread(void *__worker);
static int worker_pool_pri(struct worker_pool *pool)
{
return pool - pool->gcwq->pools;
}
static struct global_cwq *get_gcwq(unsigned int cpu)
{
if (cpu != WORK_CPU_UNBOUND)
return &per_cpu(global_cwq, cpu);
else
return &unbound_global_cwq;
}
static atomic_t *get_pool_nr_running(struct worker_pool *pool)
{
int cpu = pool->gcwq->cpu;
int idx = worker_pool_pri(pool);
if (cpu != WORK_CPU_UNBOUND)
return &per_cpu(pool_nr_running, cpu)[idx];
else
return &unbound_pool_nr_running[idx];
}
static struct cpu_workqueue_struct *get_cwq(unsigned int cpu,
struct workqueue_struct *wq)
{
if (!(wq->flags & WQ_UNBOUND)) {
if (likely(cpu < nr_cpu_ids))
return per_cpu_ptr(wq->cpu_wq.pcpu, cpu);
} else if (likely(cpu == WORK_CPU_UNBOUND))
return wq->cpu_wq.single;
return NULL;
}
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;
}
/*
* A work's data points to the cwq with WORK_STRUCT_CWQ set while the
* work is on queue. Once execution starts, WORK_STRUCT_CWQ is
* cleared and the work data contains the cpu number it was last on.
*
* set_work_{cwq|cpu}() and clear_work_data() can be used to set the
* cwq, cpu or clear work->data. These functions should only be
* called while the work is owned - ie. while the PENDING bit is set.
*
* get_work_[g]cwq() can be used to obtain the gcwq or cwq
* corresponding to a work. gcwq is available once the work has been
* queued anywhere after initialization. cwq is available only from
* queueing until execution starts.
*/
static inline void set_work_data(struct work_struct *work, unsigned long data,
unsigned long flags)
{
BUG_ON(!work_pending(work));
atomic_long_set(&work->data, data | flags | work_static(work));
}
static void set_work_cwq(struct work_struct *work,
struct cpu_workqueue_struct *cwq,
unsigned long extra_flags)
{
set_work_data(work, (unsigned long)cwq,
WORK_STRUCT_PENDING | WORK_STRUCT_CWQ | extra_flags);
}
static void set_work_cpu(struct work_struct *work, unsigned int cpu)
{
set_work_data(work, cpu << WORK_STRUCT_FLAG_BITS, WORK_STRUCT_PENDING);
}
static void clear_work_data(struct work_struct *work)
{
set_work_data(work, WORK_STRUCT_NO_CPU, 0);
}
static struct cpu_workqueue_struct *get_work_cwq(struct work_struct *work)
{
unsigned long data = atomic_long_read(&work->data);
if (data & WORK_STRUCT_CWQ)
return (void *)(data & WORK_STRUCT_WQ_DATA_MASK);
else
return NULL;
}
static struct global_cwq *get_work_gcwq(struct work_struct *work)
{
unsigned long data = atomic_long_read(&work->data);
unsigned int cpu;
if (data & WORK_STRUCT_CWQ)
return ((struct cpu_workqueue_struct *)
(data & WORK_STRUCT_WQ_DATA_MASK))->pool->gcwq;
cpu = data >> WORK_STRUCT_FLAG_BITS;
if (cpu == WORK_CPU_NONE)
return NULL;
BUG_ON(cpu >= nr_cpu_ids && cpu != WORK_CPU_UNBOUND);
return get_gcwq(cpu);
}
/*
* 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 gcwq->lock held.
*/
static bool __need_more_worker(struct worker_pool *pool)
{
return !atomic_read(get_pool_nr_running(pool));
}
/*
* 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 gcwq 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)
{
atomic_t *nr_running = get_pool_nr_running(pool);
return !list_empty(&pool->worklist) && atomic_read(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 = pool->flags & POOL_MANAGING_WORKERS;
int nr_idle = pool->nr_idle + managing; /* manager is considered idle */
int nr_busy = pool->nr_workers - nr_idle;
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(gcwq->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, unsigned int cpu)
{
struct worker *worker = kthread_data(task);
if (!(worker->flags & WORKER_NOT_RUNNING))
atomic_inc(get_pool_nr_running(worker->pool));
}
/**
* 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,
unsigned int cpu)
{
struct worker *worker = kthread_data(task), *to_wakeup = NULL;
struct worker_pool *pool = worker->pool;
atomic_t *nr_running = get_pool_nr_running(pool);
if (worker->flags & WORKER_NOT_RUNNING)
return NULL;
/* this can only happen on the local cpu */
BUG_ON(cpu != raw_smp_processor_id());
/*
* 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 trustee is not in
* charge and we're 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 gcwq lock is safe.
*/
if (atomic_dec_and_test(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(gcwq->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)) {
atomic_t *nr_running = get_pool_nr_running(pool);
if (wakeup) {
if (atomic_dec_and_test(nr_running) &&
!list_empty(&pool->worklist))
wake_up_worker(pool);
} else
atomic_dec(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(gcwq->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(get_pool_nr_running(pool));
}
/**
* busy_worker_head - return the busy hash head for a work
* @gcwq: gcwq of interest
* @work: work to be hashed
*
* Return hash head of @gcwq for @work.
*
* CONTEXT:
* spin_lock_irq(gcwq->lock).
*
* RETURNS:
* Pointer to the hash head.
*/
static struct hlist_head *busy_worker_head(struct global_cwq *gcwq,
struct work_struct *work)
{
const int base_shift = ilog2(sizeof(struct work_struct));
unsigned long v = (unsigned long)work;
/* simple shift and fold hash, do we need something better? */
v >>= base_shift;
v += v >> BUSY_WORKER_HASH_ORDER;
v &= BUSY_WORKER_HASH_MASK;
return &gcwq->busy_hash[v];
}
/**
* __find_worker_executing_work - find worker which is executing a work
* @gcwq: gcwq of interest
* @bwh: hash head as returned by busy_worker_head()
* @work: work to find worker for
*
* Find a worker which is executing @work on @gcwq. @bwh should be
* the hash head obtained by calling busy_worker_head() with the same
* work.
*
* CONTEXT:
* spin_lock_irq(gcwq->lock).
*
* RETURNS:
* Pointer to worker which is executing @work if found, NULL
* otherwise.
*/
static struct worker *__find_worker_executing_work(struct global_cwq *gcwq,
struct hlist_head *bwh,
struct work_struct *work)
{
struct worker *worker;
struct hlist_node *tmp;
hlist_for_each_entry(worker, tmp, bwh, hentry)
if (worker->current_work == work)
return worker;
return NULL;
}
/**
* find_worker_executing_work - find worker which is executing a work
* @gcwq: gcwq of interest
* @work: work to find worker for
*
* Find a worker which is executing @work on @gcwq. This function is
* identical to __find_worker_executing_work() except that this
* function calculates @bwh itself.
*
* CONTEXT:
* spin_lock_irq(gcwq->lock).
*
* RETURNS:
* Pointer to worker which is executing @work if found, NULL
* otherwise.
*/
static struct worker *find_worker_executing_work(struct global_cwq *gcwq,
struct work_struct *work)
{
return __find_worker_executing_work(gcwq, busy_worker_head(gcwq, work),
work);
}
/**
* insert_work - insert a work into gcwq
* @cwq: cwq @work belongs to
* @work: work to insert
* @head: insertion point
* @extra_flags: extra WORK_STRUCT_* flags to set
*
* Insert @work which belongs to @cwq into @gcwq after @head.
* @extra_flags is or'd to work_struct flags.
*
* CONTEXT:
* spin_lock_irq(gcwq->lock).
*/
static void insert_work(struct cpu_workqueue_struct *cwq,
struct work_struct *work, struct list_head *head,
unsigned int extra_flags)
{
struct worker_pool *pool = cwq->pool;
/* we own @work, set data and link */
set_work_cwq(work, cwq, extra_flags);
/*
* Ensure that we get the right work->data if we see the
* result of list_add() below, see try_to_grab_pending().
*/
smp_wmb();
list_add_tail(&work->entry, head);
/*
* Ensure either worker_sched_deactivated() 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. This is rather expensive and should only be used from
* cold paths.
*/
static bool is_chained_work(struct workqueue_struct *wq)
{
unsigned long flags;
unsigned int cpu;
for_each_gcwq_cpu(cpu) {
struct global_cwq *gcwq = get_gcwq(cpu);
struct worker *worker;
struct hlist_node *pos;
int i;
spin_lock_irqsave(&gcwq->lock, flags);
for_each_busy_worker(worker, i, pos, gcwq) {
if (worker->task != current)
continue;
spin_unlock_irqrestore(&gcwq->lock, flags);
/*
* I'm @worker, no locking necessary. See if @work
* is headed to the same workqueue.
*/
return worker->current_cwq->wq == wq;
}
spin_unlock_irqrestore(&gcwq->lock, flags);
}
return false;
}
static void __queue_work(unsigned int cpu, struct workqueue_struct *wq,
struct work_struct *work)
{
struct global_cwq *gcwq;
struct cpu_workqueue_struct *cwq;
struct list_head *worklist;
unsigned int work_flags;
unsigned long flags;
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;
/* determine gcwq to use */
if (!(wq->flags & WQ_UNBOUND)) {
struct global_cwq *last_gcwq;
if (unlikely(cpu == WORK_CPU_UNBOUND))
cpu = raw_smp_processor_id();
/*
* It's multi cpu. If @wq is non-reentrant and @work
* was previously on a different cpu, it might still
* be running there, in which case the work needs to
* be queued on that cpu to guarantee non-reentrance.
*/
gcwq = get_gcwq(cpu);
if (wq->flags & WQ_NON_REENTRANT &&
(last_gcwq = get_work_gcwq(work)) && last_gcwq != gcwq) {
struct worker *worker;
spin_lock_irqsave(&last_gcwq->lock, flags);
worker = find_worker_executing_work(last_gcwq, work);
if (worker && worker->current_cwq->wq == wq)
gcwq = last_gcwq;
else {
/* meh... not running there, queue here */
spin_unlock_irqrestore(&last_gcwq->lock, flags);
spin_lock_irqsave(&gcwq->lock, flags);
}
} else
spin_lock_irqsave(&gcwq->lock, flags);
} else {
gcwq = get_gcwq(WORK_CPU_UNBOUND);
spin_lock_irqsave(&gcwq->lock, flags);
}
/* gcwq determined, get cwq and queue */
cwq = get_cwq(gcwq->cpu, wq);
trace_workqueue_queue_work(cpu, cwq, work);
BUG_ON(!list_empty(&work->entry));
cwq->nr_in_flight[cwq->work_color]++;
work_flags = work_color_to_flags(cwq->work_color);
if (likely(cwq->nr_active < cwq->max_active)) {
trace_workqueue_activate_work(work);
cwq->nr_active++;
worklist = &cwq->pool->worklist;
} else {
work_flags |= WORK_STRUCT_DELAYED;
worklist = &cwq->delayed_works;
}
insert_work(cwq, work, worklist, work_flags);
spin_unlock_irqrestore(&gcwq->lock, flags);
}
/**
* queue_work - queue work on a workqueue
* @wq: workqueue to use
* @work: work to queue
*
* Returns 0 if @work was already on a queue, non-zero otherwise.
*
* We queue the work to the CPU on which it was submitted, but if the CPU dies
* it can be processed by another CPU.
*/
int queue_work(struct workqueue_struct *wq, struct work_struct *work)
{
int ret;
ret = queue_work_on(get_cpu(), wq, work);
put_cpu();
return ret;
}
EXPORT_SYMBOL_GPL(queue_work);
/**
* queue_work_on - queue work on specific cpu
* @cpu: CPU number to execute work on
* @wq: workqueue to use
* @work: work to queue
*
* Returns 0 if @work was already on a queue, non-zero otherwise.
*
* We queue the work to a specific CPU, the caller must ensure it
* can't go away.
*/
int
queue_work_on(int cpu, struct workqueue_struct *wq, struct work_struct *work)
{
int ret = 0;
if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
__queue_work(cpu, wq, work);
ret = 1;
}
return ret;
}
EXPORT_SYMBOL_GPL(queue_work_on);
static void delayed_work_timer_fn(unsigned long __data)
{
struct delayed_work *dwork = (struct delayed_work *)__data;
struct cpu_workqueue_struct *cwq = get_work_cwq(&dwork->work);
__queue_work(smp_processor_id(), cwq->wq, &dwork->work);
}
/**
* queue_delayed_work - queue work on a workqueue after delay
* @wq: workqueue to use
* @dwork: delayable work to queue
* @delay: number of jiffies to wait before queueing
*
* Returns 0 if @work was already on a queue, non-zero otherwise.
*/
int queue_delayed_work(struct workqueue_struct *wq,
struct delayed_work *dwork, unsigned long delay)
{
if (delay == 0)
return queue_work(wq, &dwork->work);
return queue_delayed_work_on(-1, wq, dwork, delay);
}
EXPORT_SYMBOL_GPL(queue_delayed_work);
/**
* 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 0 if @work was already on a queue, non-zero otherwise.
*/
int queue_delayed_work_on(int cpu, struct workqueue_struct *wq,
struct delayed_work *dwork, unsigned long delay)
{
int ret = 0;
struct timer_list *timer = &dwork->timer;
struct work_struct *work = &dwork->work;
if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
unsigned int lcpu;
BUG_ON(timer_pending(timer));
BUG_ON(!list_empty(&work->entry));
timer_stats_timer_set_start_info(&dwork->timer);
/*
* This stores cwq for the moment, for the timer_fn.
* Note that the work's gcwq is preserved to allow
* reentrance detection for delayed works.
*/
if (!(wq->flags & WQ_UNBOUND)) {
struct global_cwq *gcwq = get_work_gcwq(work);
if (gcwq && gcwq->cpu != WORK_CPU_UNBOUND)
lcpu = gcwq->cpu;
else
lcpu = raw_smp_processor_id();
} else
lcpu = WORK_CPU_UNBOUND;
set_work_cwq(work, get_cwq(lcpu, wq), 0);
timer->expires = jiffies + delay;
timer->data = (unsigned long)dwork;
timer->function = delayed_work_timer_fn;
if (unlikely(cpu >= 0))
add_timer_on(timer, cpu);
else
add_timer(timer);
ret = 1;
}
return ret;
}
EXPORT_SYMBOL_GPL(queue_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(gcwq->lock).
*/
static void worker_enter_idle(struct worker *worker)
{
struct worker_pool *pool = worker->pool;
struct global_cwq *gcwq = pool->gcwq;
BUG_ON(worker->flags & WORKER_IDLE);
BUG_ON(!list_empty(&worker->entry) &&
(worker->hentry.next || worker->hentry.pprev));
/* 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 (likely(!(worker->flags & WORKER_ROGUE))) {
if (too_many_workers(pool) && !timer_pending(&pool->idle_timer))
mod_timer(&pool->idle_timer,
jiffies + IDLE_WORKER_TIMEOUT);
} else
wake_up_all(&gcwq->trustee_wait);
/*
* Sanity check nr_running. Because trustee releases gcwq->lock
* between setting %WORKER_ROGUE and zapping nr_running, the
* warning may trigger spuriously. Check iff trustee is idle.
*/
WARN_ON_ONCE(gcwq->trustee_state == TRUSTEE_DONE &&
pool->nr_workers == pool->nr_idle &&
atomic_read(get_pool_nr_running(pool)));
}
/**
* worker_leave_idle - leave idle state
* @worker: worker which is leaving idle state
*
* @worker is leaving idle state. Update stats.
*
* LOCKING:
* spin_lock_irq(gcwq->lock).
*/
static void worker_leave_idle(struct worker *worker)
{
struct worker_pool *pool = worker->pool;
BUG_ON(!(worker->flags & WORKER_IDLE));
worker_clr_flags(worker, WORKER_IDLE);
pool->nr_idle--;
list_del_init(&worker->entry);
}
/**
* worker_maybe_bind_and_lock - bind worker to its cpu if possible and lock gcwq
* @worker: self
*
* 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 rogue 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 gcwq may be
* [dis]associated in the meantime.
*
* This function tries set_cpus_allowed() and locks gcwq and verifies
* the binding against GCWQ_DISASSOCIATED which is set during
* CPU_DYING 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 gcwq->lock
* held.
*
* RETURNS:
* %true if the associated gcwq is online (@worker is successfully
* bound), %false if offline.
*/
static bool worker_maybe_bind_and_lock(struct worker *worker)
__acquires(&gcwq->lock)
{
struct global_cwq *gcwq = worker->pool->gcwq;
struct task_struct *task = worker->task;
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 GCWQ_DISASSOCIATED.
*/
if (!(gcwq->flags & GCWQ_DISASSOCIATED))
set_cpus_allowed_ptr(task, get_cpu_mask(gcwq->cpu));
spin_lock_irq(&gcwq->lock);
if (gcwq->flags & GCWQ_DISASSOCIATED)
return false;
if (task_cpu(task) == gcwq->cpu &&
cpumask_equal(¤t->cpus_allowed,
get_cpu_mask(gcwq->cpu)))
return true;
spin_unlock_irq(&gcwq->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();
}
}
/*
* Function for worker->rebind_work used to rebind rogue busy workers
* to the associated cpu which is coming back online. This is
* scheduled by cpu up but can race with other cpu hotplug operations
* and may be executed twice without intervening cpu down.
*/
static void worker_rebind_fn(struct work_struct *work)
{
struct worker *worker = container_of(work, struct worker, rebind_work);
struct global_cwq *gcwq = worker->pool->gcwq;
if (worker_maybe_bind_and_lock(worker))
worker_clr_flags(worker, WORKER_REBIND);
spin_unlock_irq(&gcwq->lock);
}
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);
INIT_WORK(&worker->rebind_work, worker_rebind_fn);
/* 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
* @bind: whether to set affinity to @cpu or not
*
* 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, bool bind)
{
struct global_cwq *gcwq = pool->gcwq;
bool on_unbound_cpu = gcwq->cpu == WORK_CPU_UNBOUND;
const char *pri = worker_pool_pri(pool) ? "H" : "";
struct worker *worker = NULL;
int id = -1;
spin_lock_irq(&gcwq->lock);
while (ida_get_new(&pool->worker_ida, &id)) {
spin_unlock_irq(&gcwq->lock);
if (!ida_pre_get(&pool->worker_ida, GFP_KERNEL))
goto fail;
spin_lock_irq(&gcwq->lock);
}
spin_unlock_irq(&gcwq->lock);
worker = alloc_worker();
if (!worker)
goto fail;
worker->pool = pool;
worker->id = id;
if (!on_unbound_cpu)
worker->task = kthread_create_on_node(worker_thread,
worker, cpu_to_node(gcwq->cpu),
"kworker/%u:%d%s", gcwq->cpu, id, pri);
else
worker->task = kthread_create(worker_thread, worker,
"kworker/u:%d%s", id, pri);
if (IS_ERR(worker->task))
goto fail;
if (worker_pool_pri(pool))
set_user_nice(worker->task, HIGHPRI_NICE_LEVEL);
/*
* A rogue worker will become a regular one if CPU comes
* online later on. Make sure every worker has
* PF_THREAD_BOUND set.
*/
if (bind && !on_unbound_cpu)
kthread_bind(worker->task, gcwq->cpu);
else {
worker->task->flags |= PF_THREAD_BOUND;
if (on_unbound_cpu)
worker->flags |= WORKER_UNBOUND;
}
return worker;
fail:
if (id >= 0) {
spin_lock_irq(&gcwq->lock);
ida_remove(&pool->worker_ida, id);
spin_unlock_irq(&gcwq->lock);
}
kfree(worker);
return NULL;
}
/**
* start_worker - start a newly created worker
* @worker: worker to start
*
* Make the gcwq aware of @worker and start it.
*
* CONTEXT:
* spin_lock_irq(gcwq->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);
}
/**
* destroy_worker - destroy a workqueue worker
* @worker: worker to be destroyed
*
* Destroy @worker and adjust @gcwq stats accordingly.
*
* CONTEXT:
* spin_lock_irq(gcwq->lock) which is released and regrabbed.
*/
static void destroy_worker(struct worker *worker)
{
struct worker_pool *pool = worker->pool;
struct global_cwq *gcwq = pool->gcwq;
int id = worker->id;
/* sanity check frenzy */
BUG_ON(worker->current_work);
BUG_ON(!list_empty(&worker->scheduled));
if (worker->flags & WORKER_STARTED)
pool->nr_workers--;
if (worker->flags & WORKER_IDLE)
pool->nr_idle--;
list_del_init(&worker->entry);
worker->flags |= WORKER_DIE;
spin_unlock_irq(&gcwq->lock);
kthread_stop(worker->task);
kfree(worker);
spin_lock_irq(&gcwq->lock);
ida_remove(&pool->worker_ida, id);
}
static void idle_worker_timeout(unsigned long __pool)
{
struct worker_pool *pool = (void *)__pool;
struct global_cwq *gcwq = pool->gcwq;
spin_lock_irq(&gcwq->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(&gcwq->lock);
}
static bool send_mayday(struct work_struct *work)
{
struct cpu_workqueue_struct *cwq = get_work_cwq(work);
struct workqueue_struct *wq = cwq->wq;
unsigned int cpu;
if (!(wq->flags & WQ_RESCUER))
return false;
/* mayday mayday mayday */
cpu = cwq->pool->gcwq->cpu;
/* WORK_CPU_UNBOUND can't be set in cpumask, use cpu 0 instead */
if (cpu == WORK_CPU_UNBOUND)
cpu = 0;
if (!mayday_test_and_set_cpu(cpu, wq->mayday_mask))
wake_up_process(wq->rescuer->task);
return true;
}
static void gcwq_mayday_timeout(unsigned long __pool)
{
struct worker_pool *pool = (void *)__pool;
struct global_cwq *gcwq = pool->gcwq;
struct work_struct *work;
spin_lock_irq(&gcwq->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_irq(&gcwq->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(gcwq->lock) which may be released and regrabbed
* multiple times. Does GFP_KERNEL allocations. Called only from
* manager.
*
* RETURNS:
* false if no action was taken and gcwq->lock stayed locked, true
* otherwise.
*/
static bool maybe_create_worker(struct worker_pool *pool)
__releases(&gcwq->lock)
__acquires(&gcwq->lock)
{
struct global_cwq *gcwq = pool->gcwq;
if (!need_to_create_worker(pool))
return false;
restart:
spin_unlock_irq(&gcwq->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, true);
if (worker) {
del_timer_sync(&pool->mayday_timer);
spin_lock_irq(&gcwq->lock);
start_worker(worker);
BUG_ON(need_to_create_worker(pool));
return true;
}
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(&gcwq->lock);
if (need_to_create_worker(pool))
goto restart;
return true;
}
/**
* 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(gcwq->lock) which may be released and regrabbed
* multiple times. Called only from manager.
*
* RETURNS:
* false if no action was taken and gcwq->lock stayed locked, true
* otherwise.
*/
static bool maybe_destroy_workers(struct worker_pool *pool)
{
bool ret = false;
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);
ret = true;
}
return ret;
}
/**
* manage_workers - manage worker pool
* @worker: self
*
* Assume the manager role and manage gcwq worker pool @worker belongs
* to. At any given time, there can be only zero or one manager per
* gcwq. 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(gcwq->lock) which may be released and regrabbed
* multiple times. Does GFP_KERNEL allocations.
*
* RETURNS:
* false if no action was taken and gcwq->lock stayed locked, true if
* some action was taken.
*/
static bool manage_workers(struct worker *worker)
{
struct worker_pool *pool = worker->pool;
struct global_cwq *gcwq = pool->gcwq;
bool ret = false;
if (pool->flags & POOL_MANAGING_WORKERS)
return ret;
pool->flags &= ~POOL_MANAGE_WORKERS;
pool->flags |= POOL_MANAGING_WORKERS;
/*
* Destroy and then create so that may_start_working() is true
* on return.
*/
ret |= maybe_destroy_workers(pool);
ret |= maybe_create_worker(pool);
pool->flags &= ~POOL_MANAGING_WORKERS;
/*
* The trustee might be waiting to take over the manager
* position, tell it we're done.
*/
if (unlikely(gcwq->trustee))
wake_up_all(&gcwq->trustee_wait);
return ret;
}
/**
* 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(gcwq->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;
}
static void cwq_activate_first_delayed(struct cpu_workqueue_struct *cwq)
{
struct work_struct *work = list_first_entry(&cwq->delayed_works,
struct work_struct, entry);
trace_workqueue_activate_work(work);
move_linked_works(work, &cwq->pool->worklist, NULL);
__clear_bit(WORK_STRUCT_DELAYED_BIT, work_data_bits(work));
cwq->nr_active++;
}
/**
* cwq_dec_nr_in_flight - decrement cwq's nr_in_flight
* @cwq: cwq of interest
* @color: color of work which left the queue
* @delayed: for a delayed work
*
* A work either has completed or is removed from pending queue,
* decrement nr_in_flight of its cwq and handle workqueue flushing.
*
* CONTEXT:
* spin_lock_irq(gcwq->lock).
*/
static void cwq_dec_nr_in_flight(struct cpu_workqueue_struct *cwq, int color,
bool delayed)
{
/* ignore uncolored works */
if (color == WORK_NO_COLOR)
return;
cwq->nr_in_flight[color]--;
if (!delayed) {
cwq->nr_active--;
if (!list_empty(&cwq->delayed_works)) {
/* one down, submit a delayed one */
if (cwq->nr_active < cwq->max_active)
cwq_activate_first_delayed(cwq);
}
}
/* is flush in progress and are we at the flushing tip? */
if (likely(cwq->flush_color != color))
return;
/* are there still in-flight works? */
if (cwq->nr_in_flight[color])
return;
/* this cwq is done, clear flush_color */
cwq->flush_color = -1;
/*
* If this was the last cwq, wake up the first flusher. It
* will handle the rest.
*/
if (atomic_dec_and_test(&cwq->wq->nr_cwqs_to_flush))
complete(&cwq->wq->first_flusher->done);
}
/**
* 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(gcwq->lock) which is released and regrabbed.
*/
static void process_one_work(struct worker *worker, struct work_struct *work)
__releases(&gcwq->lock)
__acquires(&gcwq->lock)
{
struct cpu_workqueue_struct *cwq = get_work_cwq(work);
struct worker_pool *pool = worker->pool;
struct global_cwq *gcwq = pool->gcwq;
struct hlist_head *bwh = busy_worker_head(gcwq, work);
bool cpu_intensive = cwq->wq->flags & WQ_CPU_INTENSIVE;
work_func_t f = work->func;
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 = work->lockdep_map;
#endif
/*
* 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(gcwq, bwh, work);
if (unlikely(collision)) {
move_linked_works(work, &collision->scheduled, NULL);
return;
}
/* claim and process */
debug_work_deactivate(work);
hlist_add_head(&worker->hentry, bwh);
worker->current_work = work;
worker->current_cwq = cwq;
work_color = get_work_color(work);
/* record the current cpu number in the work data and dequeue */
set_work_cpu(work, gcwq->cpu);
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 gcwq 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);
spin_unlock_irq(&gcwq->lock);
work_clear_pending(work);
lock_map_acquire_read(&cwq->wq->lockdep_map);
lock_map_acquire(&lockdep_map);
trace_workqueue_execute_start(work);
f(work);
/*
* 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(&cwq->wq->lockdep_map);
if (unlikely(in_atomic() || lockdep_depth(current) > 0)) {
printk(KERN_ERR "BUG: workqueue leaked lock or atomic: "
"%s/0x%08x/%d\n",
current->comm, preempt_count(), task_pid_nr(current));
printk(KERN_ERR " last function: ");
print_symbol("%s\n", (unsigned long)f);
debug_show_held_locks(current);
BUG_ON(PANIC_CORRUPTION);
dump_stack();
}
spin_lock_irq(&gcwq->lock);
/* clear cpu intensive status */
if (unlikely(cpu_intensive))
worker_clr_flags(worker, WORKER_CPU_INTENSIVE);
/* we're done with it, release */
hlist_del_init(&worker->hentry);
worker->current_work = NULL;
worker->current_cwq = NULL;
cwq_dec_nr_in_flight(cwq, work_color, false);
}
/**
* 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(gcwq->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 gcwq worker thread function. There's a single dynamic pool of
* these per each cpu. These workers process all works regardless of
* their specific target workqueue. The only exception is works 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;
struct global_cwq *gcwq = pool->gcwq;
/* tell the scheduler that this is a workqueue worker */
worker->task->flags |= PF_WQ_WORKER;
woke_up:
spin_lock_irq(&gcwq->lock);
/* DIE can be set only while we're idle, checking here is enough */
if (worker->flags & WORKER_DIE) {
spin_unlock_irq(&gcwq->lock);
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.
*/
BUG_ON(!list_empty(&worker->scheduled));
/*
* When control reaches this point, we're guaranteed to have
* at least one idle worker or that someone else has already
* assumed the manager role.
*/
worker_clr_flags(worker, WORKER_PREP);
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;
/*
* gcwq->lock is held and there's no work to process and no
* need to manage, sleep. Workers are woken up only while
* holding gcwq->lock or from local cpu, so setting the
* current state before releasing gcwq->lock is enough to
* prevent losing any event.
*/
worker_enter_idle(worker);
__set_current_state(TASK_INTERRUPTIBLE);
spin_unlock_irq(&gcwq->lock);
schedule();
goto woke_up;
}
/**
* rescuer_thread - the rescuer thread function
* @__wq: the associated workqueue
*
* Workqueue rescuer thread function. There's one rescuer for each
* workqueue which has WQ_RESCUER set.
*
* Regular work processing on a gcwq 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 gcwq summons rescuers of all
* workqueues which have works queued on the gcwq and let them process
* those works so that forward progress can be guaranteed.
*
* This should happen rarely.
*/
static int rescuer_thread(void *__wq)
{
struct workqueue_struct *wq = __wq;
struct worker *rescuer = wq->rescuer;
struct list_head *scheduled = &rescuer->scheduled;
bool is_unbound = wq->flags & WQ_UNBOUND;
unsigned int cpu;
set_user_nice(current, RESCUER_NICE_LEVEL);
repeat:
set_current_state(TASK_INTERRUPTIBLE);
if (kthread_should_stop())
return 0;
/*
* See whether any cpu is asking for help. Unbounded
* workqueues use cpu 0 in mayday_mask for CPU_UNBOUND.
*/
for_each_mayday_cpu(cpu, wq->mayday_mask) {
unsigned int tcpu = is_unbound ? WORK_CPU_UNBOUND : cpu;
struct cpu_workqueue_struct *cwq = get_cwq(tcpu, wq);
struct worker_pool *pool = cwq->pool;
struct global_cwq *gcwq = pool->gcwq;
struct work_struct *work, *n;
__set_current_state(TASK_RUNNING);
mayday_clear_cpu(cpu, wq->mayday_mask);
/* migrate to the target cpu if possible */
rescuer->pool = pool;
worker_maybe_bind_and_lock(rescuer);
/*
* Slurp in all works issued via this workqueue and
* process'em.
*/
BUG_ON(!list_empty(&rescuer->scheduled));
list_for_each_entry_safe(work, n, &pool->worklist, entry)
if (get_work_cwq(work) == cwq)
move_linked_works(work, scheduled, &n);
process_scheduled_works(rescuer);
/*
* Leave this gcwq. 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);
spin_unlock_irq(&gcwq->lock);
}
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
* @cwq: cwq 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 cwq from @target.
*
* CONTEXT:
* spin_lock_irq(gcwq->lock).
*/
static void insert_wq_barrier(struct cpu_workqueue_struct *cwq,
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 gcwq->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(cwq, &barr->work, head,
work_color_to_flags(WORK_NO_COLOR) | linked);
}
/**
* flush_workqueue_prep_cwqs - prepare cwqs 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 cwqs for workqueue flushing.
*
* If @flush_color is non-negative, flush_color on all cwqs should be
* -1. If no cwq has in-flight commands at the specified color, all
* cwq->flush_color's stay at -1 and %false is returned. If any cwq
* has in flight commands, its cwq->flush_color is set to
* @flush_color, @wq->nr_cwqs_to_flush is updated accordingly, cwq
* 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 cwqs should have the same
* work_color which is previous to @work_color and all will be
* advanced to @work_color.
*
* CONTEXT:
* mutex_lock(wq->flush_mutex).
*
* RETURNS:
* %true if @flush_color >= 0 and there's something to flush. %false
* otherwise.
*/
static bool flush_workqueue_prep_cwqs(struct workqueue_struct *wq,
int flush_color, int work_color)
{
bool wait = false;
unsigned int cpu;
if (flush_color >= 0) {
BUG_ON(atomic_read(&wq->nr_cwqs_to_flush));
atomic_set(&wq->nr_cwqs_to_flush, 1);
}
for_each_cwq_cpu(cpu, wq) {
struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
struct global_cwq *gcwq = cwq->pool->gcwq;
spin_lock_irq(&gcwq->lock);
if (flush_color >= 0) {
BUG_ON(cwq->flush_color != -1);
if (cwq->nr_in_flight[flush_color]) {
cwq->flush_color = flush_color;
atomic_inc(&wq->nr_cwqs_to_flush);
wait = true;
}
}
if (work_color >= 0) {
BUG_ON(work_color != work_next_color(cwq->work_color));
cwq->work_color = work_color;
}
spin_unlock_irq(&gcwq->lock);
}
if (flush_color >= 0 && atomic_dec_and_test(&wq->nr_cwqs_to_flush))
complete(&wq->first_flusher->done);
return wait;
}
/**
* flush_workqueue - ensure that any scheduled work has run to completion.
* @wq: workqueue to flush
*
* Forces execution of the workqueue and blocks until its completion.
* This is typically used in driver shutdown handlers.
*
* We sleep until all works which were queued on entry have been handled,
* but we are 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->flush_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.
*/
BUG_ON(!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 */
BUG_ON(wq->flush_color != this_flusher.flush_color);
wq->first_flusher = &this_flusher;
if (!flush_workqueue_prep_cwqs(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 */
BUG_ON(wq->flush_color == this_flusher.flush_color);
list_add_tail(&this_flusher.list, &wq->flusher_queue);
flush_workqueue_prep_cwqs(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->flush_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->flush_mutex);
/* we might have raced, check again with mutex held */
if (wq->first_flusher != &this_flusher)
goto out_unlock;
wq->first_flusher = NULL;
BUG_ON(!list_empty(&this_flusher.list));
BUG_ON(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);
}
BUG_ON(!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_cwqs(wq, -1, wq->work_color);
}
if (list_empty(&wq->flusher_queue)) {
BUG_ON(wq->flush_color != wq->work_color);
break;
}
/*
* Need to flush more colors. Make the next flusher
* the new first flusher and arm cwqs.
*/
BUG_ON(wq->flush_color == wq->work_color);
BUG_ON(wq->flush_color != next->flush_color);
list_del_init(&next->list);
wq->first_flusher = next;
if (flush_workqueue_prep_cwqs(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->flush_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;
unsigned int cpu;
/*
* __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.
*/
spin_lock(&workqueue_lock);
if (!wq->nr_drainers++)
wq->flags |= WQ_DRAINING;
spin_unlock(&workqueue_lock);
reflush:
flush_workqueue(wq);
for_each_cwq_cpu(cpu, wq) {
struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
bool drained;
spin_lock_irq(&cwq->pool->gcwq->lock);
drained = !cwq->nr_active && list_empty(&cwq->delayed_works);
spin_unlock_irq(&cwq->pool->gcwq->lock);
if (drained)
continue;
if (++flush_cnt == 10 ||
(flush_cnt % 100 == 0 && flush_cnt <= 1000))
pr_warning("workqueue %s: flush on destruction isn't complete after %u tries\n",
wq->name, flush_cnt);
goto reflush;
}
spin_lock(&workqueue_lock);
if (!--wq->nr_drainers)
wq->flags &= ~WQ_DRAINING;
spin_unlock(&workqueue_lock);
}
EXPORT_SYMBOL_GPL(drain_workqueue);
static bool start_flush_work(struct work_struct *work, struct wq_barrier *barr,
bool wait_executing)
{
struct worker *worker = NULL;
struct global_cwq *gcwq;
struct cpu_workqueue_struct *cwq;
might_sleep();
gcwq = get_work_gcwq(work);
if (!gcwq)
return false;
spin_lock_irq(&gcwq->lock);
if (!list_empty(&work->entry)) {
/*
* See the comment near try_to_grab_pending()->smp_rmb().
* If it was re-queued to a different gcwq under us, we
* are not going to wait.
*/
smp_rmb();
cwq = get_work_cwq(work);
if (unlikely(!cwq || gcwq != cwq->pool->gcwq))
goto already_gone;
} else if (wait_executing) {
worker = find_worker_executing_work(gcwq, work);
if (!worker)
goto already_gone;
cwq = worker->current_cwq;
} else
goto already_gone;
insert_wq_barrier(cwq, barr, work, worker);
spin_unlock_irq(&gcwq->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 (cwq->wq->saved_max_active == 1 || cwq->wq->flags & WQ_RESCUER)
lock_map_acquire(&cwq->wq->lockdep_map);
else
lock_map_acquire_read(&cwq->wq->lockdep_map);
lock_map_release(&cwq->wq->lockdep_map);
return true;
already_gone:
spin_unlock_irq(&gcwq->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. This function considers
* only the last queueing instance of @work. If @work has been
* enqueued across different CPUs on a non-reentrant workqueue or on
* multiple workqueues, @work might still be executing on return on
* some of the CPUs from earlier queueing.
*
* If @work was queued only on a non-reentrant, ordered or unbound
* workqueue, @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;
if (start_flush_work(work, &barr, true)) {
wait_for_completion(&barr.done);
destroy_work_on_stack(&barr.work);
return true;
} else
return false;
}
EXPORT_SYMBOL_GPL(flush_work);
static bool wait_on_cpu_work(struct global_cwq *gcwq, struct work_struct *work)
{
struct wq_barrier barr;
struct worker *worker;
spin_lock_irq(&gcwq->lock);
worker = find_worker_executing_work(gcwq, work);
if (unlikely(worker))
insert_wq_barrier(worker->current_cwq, &barr, work, worker);
spin_unlock_irq(&gcwq->lock);
if (unlikely(worker)) {
wait_for_completion(&barr.done);
destroy_work_on_stack(&barr.work);
return true;
} else
return false;
}
static bool wait_on_work(struct work_struct *work)
{
bool ret = false;
int cpu;
might_sleep();
lock_map_acquire(&work->lockdep_map);
lock_map_release(&work->lockdep_map);
for_each_gcwq_cpu(cpu)
ret |= wait_on_cpu_work(get_gcwq(cpu), work);
return ret;
}
/**
* flush_work_sync - wait until a work has finished execution
* @work: the work to flush
*
* Wait until @work has finished execution. On return, it's
* guaranteed that all queueing instances of @work which happened
* before this function is called are finished. In other words, if
* @work hasn't been requeued since this function was called, @work is
* guaranteed to be idle on return.
*
* RETURNS:
* %true if flush_work_sync() waited for the work to finish execution,
* %false if it was already idle.
*/
bool flush_work_sync(struct work_struct *work)
{
struct wq_barrier barr;
bool pending, waited;
/* we'll wait for executions separately, queue barr only if pending */
pending = start_flush_work(work, &barr, false);
/* wait for executions to finish */
waited = wait_on_work(work);
/* wait for the pending one */
if (pending) {
wait_for_completion(&barr.done);
destroy_work_on_stack(&barr.work);
}
return pending || waited;
}
EXPORT_SYMBOL_GPL(flush_work_sync);
/*
* Upon a successful return (>= 0), the caller "owns" WORK_STRUCT_PENDING bit,
* so this work can't be re-armed in any way.
*/
static int try_to_grab_pending(struct work_struct *work)
{
struct global_cwq *gcwq;
int ret = -1;
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.
*/
gcwq = get_work_gcwq(work);
if (!gcwq)
return ret;
spin_lock_irq(&gcwq->lock);
if (!list_empty(&work->entry)) {
/*
* This work is queued, but perhaps we locked the wrong gcwq.
* In that case we must see the new value after rmb(), see
* insert_work()->wmb().
*/
smp_rmb();
if (gcwq == get_work_gcwq(work)) {
debug_work_deactivate(work);
list_del_init(&work->entry);
cwq_dec_nr_in_flight(get_work_cwq(work),
get_work_color(work),
*work_data_bits(work) & WORK_STRUCT_DELAYED);
ret = 1;
}
}
spin_unlock_irq(&gcwq->lock);
return ret;
}
static bool __cancel_work_timer(struct work_struct *work,
struct timer_list* timer)
{
int ret;
do {
ret = (timer && likely(del_timer(timer)));
if (!ret)
ret = try_to_grab_pending(work);
wait_on_work(work);
} while (unlikely(ret < 0));
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, NULL);
}
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)
{
if (del_timer_sync(&dwork->timer))
__queue_work(raw_smp_processor_id(),
get_work_cwq(&dwork->work)->wq, &dwork->work);
return flush_work(&dwork->work);
}
EXPORT_SYMBOL(flush_delayed_work);
/**
* flush_delayed_work_sync - wait for a dwork to finish
* @dwork: the delayed work to flush
*
* Delayed timer is cancelled and the pending work is queued for
* execution immediately. Other than timer handling, its behavior
* is identical to flush_work_sync().
*
* RETURNS:
* %true if flush_work_sync() waited for the work to finish execution,
* %false if it was already idle.
*/
bool flush_delayed_work_sync(struct delayed_work *dwork)
{
if (del_timer_sync(&dwork->timer))
__queue_work(raw_smp_processor_id(),
get_work_cwq(&dwork->work)->wq, &dwork->work);
return flush_work_sync(&dwork->work);
}
EXPORT_SYMBOL(flush_delayed_work_sync);
/**
* 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, &dwork->timer);
}
EXPORT_SYMBOL(cancel_delayed_work_sync);
/**
* schedule_work - put work task in global workqueue
* @work: job to be done
*
* Returns zero if @work was already on the kernel-global workqueue and
* non-zero otherwise.
*
* This puts a job in the kernel-global workqueue if it was not already
* queued and leaves it in the same position on the kernel-global
* workqueue otherwise.
*/
int schedule_work(struct work_struct *work)
{
return queue_work(system_wq, work);
}
EXPORT_SYMBOL(schedule_work);
/*
* schedule_work_on - put work task on a specific cpu
* @cpu: cpu to put the work task on
* @work: job to be done
*
* This puts a job on a specific cpu
*/
int schedule_work_on(int cpu, struct work_struct *work)
{
return queue_work_on(cpu, system_wq, work);
}
EXPORT_SYMBOL(schedule_work_on);
/**
* schedule_delayed_work - put work task in global workqueue after delay
* @dwork: job to be done
* @delay: number of jiffies to wait or 0 for immediate execution
*
* After waiting for a given time this puts a job in the kernel-global
* workqueue.
*/
int schedule_delayed_work(struct delayed_work *dwork,
unsigned long delay)
{
return queue_delayed_work(system_wq, dwork, delay);
}
EXPORT_SYMBOL(schedule_delayed_work);
/**
* schedule_delayed_work_on - queue work in global workqueue on CPU after delay
* @cpu: cpu to use
* @dwork: job to be done
* @delay: number of jiffies to wait
*
* After waiting for a given time this puts a job in the kernel-global
* workqueue on the specified CPU.
*/
int schedule_delayed_work_on(int cpu,
struct delayed_work *dwork, unsigned long delay)
{
return queue_delayed_work_on(cpu, system_wq, dwork, delay);
}
EXPORT_SYMBOL(schedule_delayed_work_on);
/**
* 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);
int keventd_up(void)
{
return system_wq != NULL;
}
static int alloc_cwqs(struct workqueue_struct *wq)
{
/*
* cwqs are forced aligned according to WORK_STRUCT_FLAG_BITS.
* Make sure that the alignment isn't lower than that of
* unsigned long long.
*/
const size_t size = sizeof(struct cpu_workqueue_struct);
const size_t align = max_t(size_t, 1 << WORK_STRUCT_FLAG_BITS,
__alignof__(unsigned long long));
if (!(wq->flags & WQ_UNBOUND))
wq->cpu_wq.pcpu = __alloc_percpu(size, align);
else {
void *ptr;
/*
* Allocate enough room to align cwq and put an extra
* pointer at the end pointing back to the originally
* allocated pointer which will be used for free.
*/
ptr = kzalloc(size + align + sizeof(void *), GFP_KERNEL);
if (ptr) {
wq->cpu_wq.single = PTR_ALIGN(ptr, align);
*(void **)(wq->cpu_wq.single + 1) = ptr;
}
}
/* just in case, make sure it's actually aligned */
BUG_ON(!IS_ALIGNED(wq->cpu_wq.v, align));
return wq->cpu_wq.v ? 0 : -ENOMEM;
}
static void free_cwqs(struct workqueue_struct *wq)
{
if (!(wq->flags & WQ_UNBOUND))
free_percpu(wq->cpu_wq.pcpu);
else if (wq->cpu_wq.single) {
/* the pointer to free is stored right after the cwq */
kfree(*(void **)(wq->cpu_wq.single + 1));
}
}
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)
printk(KERN_WARNING "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, ...)
{
va_list args, args1;
struct workqueue_struct *wq;
unsigned int cpu;
size_t namelen;
/* determine namelen, allocate wq and format name */
va_start(args, lock_name);
va_copy(args1, args);
namelen = vsnprintf(NULL, 0, fmt, args) + 1;
wq = kzalloc(sizeof(*wq) + namelen, GFP_KERNEL);
if (!wq)
goto err;
vsnprintf(wq->name, namelen, fmt, args1);
va_end(args);
va_end(args1);
/* see the comment above the definition of WQ_POWER_EFFICIENT */
if ((flags & WQ_POWER_EFFICIENT) && wq_power_efficient)
flags |= WQ_UNBOUND;
/*
* Workqueues which may be used during memory reclaim should
* have a rescuer to guarantee forward progress.
*/
if (flags & WQ_MEM_RECLAIM)
flags |= WQ_RESCUER;
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->flush_mutex);
atomic_set(&wq->nr_cwqs_to_flush, 0);
INIT_LIST_HEAD(&wq->flusher_queue);
INIT_LIST_HEAD(&wq->flusher_overflow);
lockdep_init_map(&wq->lockdep_map, lock_name, key, 0);
INIT_LIST_HEAD(&wq->list);
if (alloc_cwqs(wq) < 0)
goto err;
for_each_cwq_cpu(cpu, wq) {
struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
struct global_cwq *gcwq = get_gcwq(cpu);
int pool_idx = (bool)(flags & WQ_HIGHPRI);
BUG_ON((unsigned long)cwq & WORK_STRUCT_FLAG_MASK);
cwq->pool = &gcwq->pools[pool_idx];
cwq->wq = wq;
cwq->flush_color = -1;
cwq->max_active = max_active;
INIT_LIST_HEAD(&cwq->delayed_works);
}
if (flags & WQ_RESCUER) {
struct worker *rescuer;
if (!alloc_mayday_mask(&wq->mayday_mask, GFP_KERNEL))
goto err;
wq->rescuer = rescuer = alloc_worker();
if (!rescuer)
goto err;
rescuer->task = kthread_create(rescuer_thread, wq, "%s",
wq->name);
if (IS_ERR(rescuer->task))
goto err;
rescuer->task->flags |= PF_THREAD_BOUND;
wake_up_process(rescuer->task);
}
/*
* workqueue_lock protects global freeze state and workqueues
* list. Grab it, set max_active accordingly and add the new
* workqueue to workqueues list.
*/
spin_lock(&workqueue_lock);
if (workqueue_freezing && wq->flags & WQ_FREEZABLE)
for_each_cwq_cpu(cpu, wq)
get_cwq(cpu, wq)->max_active = 0;
list_add(&wq->list, &workqueues);
spin_unlock(&workqueue_lock);
return wq;
err:
if (wq) {
free_cwqs(wq);
free_mayday_mask(wq->mayday_mask);
kfree(wq->rescuer);
kfree(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)
{
unsigned int cpu;
/* drain it before proceeding with destruction */
drain_workqueue(wq);
/*
* wq list is used to freeze wq, remove from list after
* flushing is complete in case freeze races us.
*/
spin_lock(&workqueue_lock);
list_del(&wq->list);
spin_unlock(&workqueue_lock);
/* sanity check */
for_each_cwq_cpu(cpu, wq) {
struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
int i;
for (i = 0; i < WORK_NR_COLORS; i++)
BUG_ON(cwq->nr_in_flight[i]);
BUG_ON(cwq->nr_active);
BUG_ON(!list_empty(&cwq->delayed_works));
}
if (wq->flags & WQ_RESCUER) {
kthread_stop(wq->rescuer->task);
free_mayday_mask(wq->mayday_mask);
kfree(wq->rescuer);
}
free_cwqs(wq);
kfree(wq);
}
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)
{
unsigned int cpu;
max_active = wq_clamp_max_active(max_active, wq->flags, wq->name);
spin_lock(&workqueue_lock);
wq->saved_max_active = max_active;
for_each_cwq_cpu(cpu, wq) {
struct global_cwq *gcwq = get_gcwq(cpu);
spin_lock_irq(&gcwq->lock);
if (!(wq->flags & WQ_FREEZABLE) ||
!(gcwq->flags & GCWQ_FREEZING))
get_cwq(gcwq->cpu, wq)->max_active = max_active;
spin_unlock_irq(&gcwq->lock);
}
spin_unlock(&workqueue_lock);
}
EXPORT_SYMBOL_GPL(workqueue_set_max_active);
/**
* 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.
*
* RETURNS:
* %true if congested, %false otherwise.
*/
bool workqueue_congested(unsigned int cpu, struct workqueue_struct *wq)
{
struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
return !list_empty(&cwq->delayed_works);
}
EXPORT_SYMBOL_GPL(workqueue_congested);
/**
* work_cpu - return the last known associated cpu for @work
* @work: the work of interest
*
* RETURNS:
* CPU number if @work was ever queued. WORK_CPU_NONE otherwise.
*/
unsigned int work_cpu(struct work_struct *work)
{
struct global_cwq *gcwq = get_work_gcwq(work);
return gcwq ? gcwq->cpu : WORK_CPU_NONE;
}
EXPORT_SYMBOL_GPL(work_cpu);
/**
* 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.
* Especially for reentrant wqs, the pending state might hide the
* running state.
*
* RETURNS:
* OR'd bitmask of WORK_BUSY_* bits.
*/
unsigned int work_busy(struct work_struct *work)
{
struct global_cwq *gcwq = get_work_gcwq(work);
unsigned long flags;
unsigned int ret = 0;
if (!gcwq)
return false;
spin_lock_irqsave(&gcwq->lock, flags);
if (work_pending(work))
ret |= WORK_BUSY_PENDING;
if (find_worker_executing_work(gcwq, work))
ret |= WORK_BUSY_RUNNING;
spin_unlock_irqrestore(&gcwq->lock, flags);
return ret;
}
EXPORT_SYMBOL_GPL(work_busy);
/*
* CPU hotplug.
*
* There are two challenges in supporting CPU hotplug. Firstly, there
* are a lot of assumptions on strong associations among work, cwq and
* gcwq which make migrating pending and scheduled works very
* difficult to implement without impacting hot paths. Secondly,
* gcwqs serve mix of short, long and very long running works making
* blocked draining impractical.
*
* This is solved by allowing a gcwq to be detached from CPU, running
* it with unbound (rogue) workers and allowing it to be reattached
* later if the cpu comes back online. A separate thread is created
* to govern a gcwq in such state and is called the trustee of the
* gcwq.
*
* Trustee states and their descriptions.
*
* START Command state used on startup. On CPU_DOWN_PREPARE, a
* new trustee is started with this state.
*
* IN_CHARGE Once started, trustee will enter this state after
* assuming the manager role and making all existing
* workers rogue. DOWN_PREPARE waits for trustee to
* enter this state. After reaching IN_CHARGE, trustee
* tries to execute the pending worklist until it's empty
* and the state is set to BUTCHER, or the state is set
* to RELEASE.
*
* BUTCHER Command state which is set by the cpu callback after
* the cpu has went down. Once this state is set trustee
* knows that there will be no new works on the worklist
* and once the worklist is empty it can proceed to
* killing idle workers.
*
* RELEASE Command state which is set by the cpu callback if the
* cpu down has been canceled or it has come online
* again. After recognizing this state, trustee stops
* trying to drain or butcher and clears ROGUE, rebinds
* all remaining workers back to the cpu and releases
* manager role.
*
* DONE Trustee will enter this state after BUTCHER or RELEASE
* is complete.
*
* trustee CPU draining
* took over down complete
* START -----------> IN_CHARGE -----------> BUTCHER -----------> DONE
* | | ^
* | CPU is back online v return workers |
* ----------------> RELEASE --------------
*/
/**
* trustee_wait_event_timeout - timed event wait for trustee
* @cond: condition to wait for
* @timeout: timeout in jiffies
*
* wait_event_timeout() for trustee to use. Handles locking and
* checks for RELEASE request.
*
* CONTEXT:
* spin_lock_irq(gcwq->lock) which may be released and regrabbed
* multiple times. To be used by trustee.
*
* RETURNS:
* Positive indicating left time if @cond is satisfied, 0 if timed
* out, -1 if canceled.
*/
#define trustee_wait_event_timeout(cond, timeout) ({ \
long __ret = (timeout); \
while (!((cond) || (gcwq->trustee_state == TRUSTEE_RELEASE)) && \
__ret) { \
spin_unlock_irq(&gcwq->lock); \
__wait_event_timeout(gcwq->trustee_wait, (cond) || \
(gcwq->trustee_state == TRUSTEE_RELEASE), \
__ret); \
spin_lock_irq(&gcwq->lock); \
} \
gcwq->trustee_state == TRUSTEE_RELEASE ? -1 : (__ret); \
})
/**
* trustee_wait_event - event wait for trustee
* @cond: condition to wait for
*
* wait_event() for trustee to use. Automatically handles locking and
* checks for CANCEL request.
*
* CONTEXT:
* spin_lock_irq(gcwq->lock) which may be released and regrabbed
* multiple times. To be used by trustee.
*
* RETURNS:
* 0 if @cond is satisfied, -1 if canceled.
*/
#define trustee_wait_event(cond) ({ \
long __ret1; \
__ret1 = trustee_wait_event_timeout(cond, MAX_SCHEDULE_TIMEOUT);\
__ret1 < 0 ? -1 : 0; \
})
static bool gcwq_is_managing_workers(struct global_cwq *gcwq)
{
struct worker_pool *pool;
for_each_worker_pool(pool, gcwq)
if (pool->flags & POOL_MANAGING_WORKERS)
return true;
return false;
}
static bool gcwq_has_idle_workers(struct global_cwq *gcwq)
{
struct worker_pool *pool;
for_each_worker_pool(pool, gcwq)
if (!list_empty(&pool->idle_list))
return true;
return false;
}
static int __cpuinit trustee_thread(void *__gcwq)
{
struct global_cwq *gcwq = __gcwq;
struct worker_pool *pool;
struct worker *worker;
struct work_struct *work;
struct hlist_node *pos;
long rc;
int i;
BUG_ON(gcwq->cpu != smp_processor_id());
spin_lock_irq(&gcwq->lock);
/*
* Claim the manager position and make all workers rogue.
* Trustee must be bound to the target cpu and can't be
* cancelled.
*/
BUG_ON(gcwq->cpu != smp_processor_id());
rc = trustee_wait_event(!gcwq_is_managing_workers(gcwq));
BUG_ON(rc < 0);
for_each_worker_pool(pool, gcwq) {
pool->flags |= POOL_MANAGING_WORKERS;
list_for_each_entry(worker, &pool->idle_list, entry)
worker->flags |= WORKER_ROGUE;
}
for_each_busy_worker(worker, i, pos, gcwq)
worker->flags |= WORKER_ROGUE;
/*
* Call schedule() so that we cross rq->lock and thus can
* guarantee sched callbacks see the rogue flag. This is
* necessary as scheduler callbacks may be invoked from other
* cpus.
*/
spin_unlock_irq(&gcwq->lock);
schedule();
spin_lock_irq(&gcwq->lock);
/*
* 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.
*/
for_each_worker_pool(pool, gcwq)
atomic_set(get_pool_nr_running(pool), 0);
spin_unlock_irq(&gcwq->lock);
for_each_worker_pool(pool, gcwq)
del_timer_sync(&pool->idle_timer);
spin_lock_irq(&gcwq->lock);
/*
* We're now in charge. Notify and proceed to drain. We need
* to keep the gcwq running during the whole CPU down
* procedure as other cpu hotunplug callbacks may need to
* flush currently running tasks.
*/
gcwq->trustee_state = TRUSTEE_IN_CHARGE;
wake_up_all(&gcwq->trustee_wait);
/*
* The original cpu is in the process of dying and may go away
* anytime now. When that happens, we and all workers would
* be migrated to other cpus. Try draining any left work. We
* want to get it over with ASAP - spam rescuers, wake up as
* many idlers as necessary and create new ones till the
* worklist is empty. Note that if the gcwq is frozen, there
* may be frozen works in freezable cwqs. Don't declare
* completion while frozen.
*/
while (true) {
bool busy = false;
for_each_worker_pool(pool, gcwq)
busy |= pool->nr_workers != pool->nr_idle;
if (!busy && !(gcwq->flags & GCWQ_FREEZING) &&
gcwq->trustee_state != TRUSTEE_IN_CHARGE)
break;
for_each_worker_pool(pool, gcwq) {
int nr_works = 0;
list_for_each_entry(work, &pool->worklist, entry) {
send_mayday(work);
nr_works++;
}
list_for_each_entry(worker, &pool->idle_list, entry) {
if (!nr_works--)
break;
wake_up_process(worker->task);
}
if (need_to_create_worker(pool)) {
spin_unlock_irq(&gcwq->lock);
worker = create_worker(pool, false);
spin_lock_irq(&gcwq->lock);
if (worker) {
worker->flags |= WORKER_ROGUE;
start_worker(worker);
}
}
}
/* give a breather */
if (trustee_wait_event_timeout(false, TRUSTEE_COOLDOWN) < 0)
break;
}
/*
* Either all works have been scheduled and cpu is down, or
* cpu down has already been canceled. Wait for and butcher
* all workers till we're canceled.
*/
do {
rc = trustee_wait_event(gcwq_has_idle_workers(gcwq));
i = 0;
for_each_worker_pool(pool, gcwq) {
while (!list_empty(&pool->idle_list)) {
worker = list_first_entry(&pool->idle_list,
struct worker, entry);
destroy_worker(worker);
}
i |= pool->nr_workers;
}
} while (i && rc >= 0);
/*
* At this point, either draining has completed and no worker
* is left, or cpu down has been canceled or the cpu is being
* brought back up. There shouldn't be any idle one left.
* Tell the remaining busy ones to rebind once it finishes the
* currently scheduled works by scheduling the rebind_work.
*/
for_each_worker_pool(pool, gcwq)
WARN_ON(!list_empty(&pool->idle_list));
for_each_busy_worker(worker, i, pos, gcwq) {
struct work_struct *rebind_work = &worker->rebind_work;
/*
* Rebind_work may race with future cpu hotplug
* operations. Use a separate flag to mark that
* rebinding is scheduled.
*/
worker->flags |= WORKER_REBIND;
worker->flags &= ~WORKER_ROGUE;
/* queue rebind_work, wq doesn't matter, use the default one */
if (test_and_set_bit(WORK_STRUCT_PENDING_BIT,
work_data_bits(rebind_work)))
continue;
debug_work_activate(rebind_work);
insert_work(get_cwq(gcwq->cpu, system_wq), rebind_work,
worker->scheduled.next,
work_color_to_flags(WORK_NO_COLOR));
}
/* relinquish manager role */
for_each_worker_pool(pool, gcwq)
pool->flags &= ~POOL_MANAGING_WORKERS;
/* notify completion */
gcwq->trustee = NULL;
gcwq->trustee_state = TRUSTEE_DONE;
wake_up_all(&gcwq->trustee_wait);
spin_unlock_irq(&gcwq->lock);
return 0;
}
/**
* wait_trustee_state - wait for trustee to enter the specified state
* @gcwq: gcwq the trustee of interest belongs to
* @state: target state to wait for
*
* Wait for the trustee to reach @state. DONE is already matched.
*
* CONTEXT:
* spin_lock_irq(gcwq->lock) which may be released and regrabbed
* multiple times. To be used by cpu_callback.
*/
static void __cpuinit wait_trustee_state(struct global_cwq *gcwq, int state)
__releases(&gcwq->lock)
__acquires(&gcwq->lock)
{
if (!(gcwq->trustee_state == state ||
gcwq->trustee_state == TRUSTEE_DONE)) {
spin_unlock_irq(&gcwq->lock);
__wait_event(gcwq->trustee_wait,
gcwq->trustee_state == state ||
gcwq->trustee_state == TRUSTEE_DONE);
spin_lock_irq(&gcwq->lock);
}
}
static int __devinit workqueue_cpu_callback(struct notifier_block *nfb,
unsigned long action,
void *hcpu)
{
unsigned int cpu = (unsigned long)hcpu;
struct global_cwq *gcwq = get_gcwq(cpu);
struct task_struct *new_trustee = NULL;
struct worker *new_workers[NR_WORKER_POOLS] = { };
struct worker_pool *pool;
unsigned long flags;
int i;
action &= ~CPU_TASKS_FROZEN;
switch (action) {
case CPU_DOWN_PREPARE:
new_trustee = kthread_create(trustee_thread, gcwq,
"workqueue_trustee/%d\n", cpu);
if (IS_ERR(new_trustee))
return notifier_from_errno(PTR_ERR(new_trustee));
kthread_bind(new_trustee, cpu);
/* fall through */
case CPU_UP_PREPARE:
i = 0;
for_each_worker_pool(pool, gcwq) {
BUG_ON(pool->first_idle);
new_workers[i] = create_worker(pool, false);
if (!new_workers[i++])
goto err_destroy;
}
}
/* some are called w/ irq disabled, don't disturb irq status */
spin_lock_irqsave(&gcwq->lock, flags);
switch (action) {
case CPU_DOWN_PREPARE:
/* initialize trustee and tell it to acquire the gcwq */
BUG_ON(gcwq->trustee || gcwq->trustee_state != TRUSTEE_DONE);
gcwq->trustee = new_trustee;
gcwq->trustee_state = TRUSTEE_START;
wake_up_process(gcwq->trustee);
wait_trustee_state(gcwq, TRUSTEE_IN_CHARGE);
/* fall through */
case CPU_UP_PREPARE:
i = 0;
for_each_worker_pool(pool, gcwq) {
BUG_ON(pool->first_idle);
pool->first_idle = new_workers[i++];
}
break;
case CPU_DYING:
/*
* Before this, the trustee and 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'll all be diasporas.
*/
gcwq->flags |= GCWQ_DISASSOCIATED;
break;
case CPU_POST_DEAD:
gcwq->trustee_state = TRUSTEE_BUTCHER;
/* fall through */
case CPU_UP_CANCELED:
for_each_worker_pool(pool, gcwq) {
destroy_worker(pool->first_idle);
pool->first_idle = NULL;
}
break;
case CPU_DOWN_FAILED:
case CPU_ONLINE:
gcwq->flags &= ~GCWQ_DISASSOCIATED;
if (gcwq->trustee_state != TRUSTEE_DONE) {
gcwq->trustee_state = TRUSTEE_RELEASE;
wake_up_process(gcwq->trustee);
wait_trustee_state(gcwq, TRUSTEE_DONE);
}
/*
* Trustee is done and there might be no worker left.
* Put the first_idle in and request a real manager to
* take a look.
*/
for_each_worker_pool(pool, gcwq) {
spin_unlock_irq(&gcwq->lock);
kthread_bind(pool->first_idle->task, cpu);
spin_lock_irq(&gcwq->lock);
pool->flags |= POOL_MANAGE_WORKERS;
start_worker(pool->first_idle);
pool->first_idle = NULL;
}
break;
}
spin_unlock_irqrestore(&gcwq->lock, flags);
return notifier_from_errno(0);
err_destroy:
if (new_trustee)
kthread_stop(new_trustee);
spin_lock_irqsave(&gcwq->lock, flags);
for (i = 0; i < NR_WORKER_POOLS; i++)
if (new_workers[i])
destroy_worker(new_workers[i]);
spin_unlock_irqrestore(&gcwq->lock, flags);
return NOTIFY_BAD;
}
#ifdef CONFIG_SMP
struct work_for_cpu {
struct completion completion;
long (*fn)(void *);
void *arg;
long ret;
};
static int do_work_for_cpu(void *_wfc)
{
struct work_for_cpu *wfc = _wfc;
wfc->ret = wfc->fn(wfc->arg);
complete(&wfc->completion);
return 0;
}
/**
* 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(unsigned int cpu, long (*fn)(void *), void *arg)
{
struct task_struct *sub_thread;
struct work_for_cpu wfc = {
.completion = COMPLETION_INITIALIZER_ONSTACK(wfc.completion),
.fn = fn,
.arg = arg,
};
sub_thread = kthread_create(do_work_for_cpu, &wfc, "work_for_cpu");
if (IS_ERR(sub_thread))
return PTR_ERR(sub_thread);
kthread_bind(sub_thread, cpu);
wake_up_process(sub_thread);
wait_for_completion(&wfc.completion);
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 frozen_works list instead of
* gcwq->worklist.
*
* CONTEXT:
* Grabs and releases workqueue_lock and gcwq->lock's.
*/
void freeze_workqueues_begin(void)
{
unsigned int cpu;
spin_lock(&workqueue_lock);
BUG_ON(workqueue_freezing);
workqueue_freezing = true;
for_each_gcwq_cpu(cpu) {
struct global_cwq *gcwq = get_gcwq(cpu);
struct workqueue_struct *wq;
spin_lock_irq(&gcwq->lock);
BUG_ON(gcwq->flags & GCWQ_FREEZING);
gcwq->flags |= GCWQ_FREEZING;
list_for_each_entry(wq, &workqueues, list) {
struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
if (cwq && wq->flags & WQ_FREEZABLE)
cwq->max_active = 0;
}
spin_unlock_irq(&gcwq->lock);
}
spin_unlock(&workqueue_lock);
}
/**
* 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 workqueue_lock.
*
* RETURNS:
* %true if some freezable workqueues are still busy. %false if freezing
* is complete.
*/
bool freeze_workqueues_busy(void)
{
unsigned int cpu;
bool busy = false;
spin_lock(&workqueue_lock);
BUG_ON(!workqueue_freezing);
for_each_gcwq_cpu(cpu) {
struct workqueue_struct *wq;
/*
* nr_active is monotonically decreasing. It's safe
* to peek without lock.
*/
list_for_each_entry(wq, &workqueues, list) {
struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
if (!cwq || !(wq->flags & WQ_FREEZABLE))
continue;
BUG_ON(cwq->nr_active < 0);
if (cwq->nr_active) {
busy = true;
goto out_unlock;
}
}
}
out_unlock:
spin_unlock(&workqueue_lock);
return busy;
}
/**
* thaw_workqueues - thaw workqueues
*
* Thaw workqueues. Normal queueing is restored and all collected
* frozen works are transferred to their respective gcwq worklists.
*
* CONTEXT:
* Grabs and releases workqueue_lock and gcwq->lock's.
*/
void thaw_workqueues(void)
{
unsigned int cpu;
spin_lock(&workqueue_lock);
if (!workqueue_freezing)
goto out_unlock;
for_each_gcwq_cpu(cpu) {
struct global_cwq *gcwq = get_gcwq(cpu);
struct worker_pool *pool;
struct workqueue_struct *wq;
spin_lock_irq(&gcwq->lock);
BUG_ON(!(gcwq->flags & GCWQ_FREEZING));
gcwq->flags &= ~GCWQ_FREEZING;
list_for_each_entry(wq, &workqueues, list) {
struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
if (!cwq || !(wq->flags & WQ_FREEZABLE))
continue;
/* restore max_active and repopulate worklist */
cwq->max_active = wq->saved_max_active;
while (!list_empty(&cwq->delayed_works) &&
cwq->nr_active < cwq->max_active)
cwq_activate_first_delayed(cwq);
}
for_each_worker_pool(pool, gcwq)
wake_up_worker(pool);
spin_unlock_irq(&gcwq->lock);
}
workqueue_freezing = false;
out_unlock:
spin_unlock(&workqueue_lock);
}
#endif /* CONFIG_FREEZER */
static int __init init_workqueues(void)
{
unsigned int cpu;
int i;
cpu_notifier(workqueue_cpu_callback, CPU_PRI_WORKQUEUE);
/* initialize gcwqs */
for_each_gcwq_cpu(cpu) {
struct global_cwq *gcwq = get_gcwq(cpu);
struct worker_pool *pool;
spin_lock_init(&gcwq->lock);
gcwq->cpu = cpu;
gcwq->flags |= GCWQ_DISASSOCIATED;
for (i = 0; i < BUSY_WORKER_HASH_SIZE; i++)
INIT_HLIST_HEAD(&gcwq->busy_hash[i]);
for_each_worker_pool(pool, gcwq) {
pool->gcwq = gcwq;
INIT_LIST_HEAD(&pool->worklist);
INIT_LIST_HEAD(&pool->idle_list);
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, gcwq_mayday_timeout,
(unsigned long)pool);
ida_init(&pool->worker_ida);
}
gcwq->trustee_state = TRUSTEE_DONE;
init_waitqueue_head(&gcwq->trustee_wait);
}
/* create the initial worker */
for_each_online_gcwq_cpu(cpu) {
struct global_cwq *gcwq = get_gcwq(cpu);
struct worker_pool *pool;
if (cpu != WORK_CPU_UNBOUND)
gcwq->flags &= ~GCWQ_DISASSOCIATED;
for_each_worker_pool(pool, gcwq) {
struct worker *worker;
worker = create_worker(pool, true);
BUG_ON(!worker);
spin_lock_irq(&gcwq->lock);
start_worker(worker);
spin_unlock_irq(&gcwq->lock);
}
}
system_wq = alloc_workqueue("events", 0, 0);
system_long_wq = alloc_workqueue("events_long", 0, 0);
system_nrt_wq = alloc_workqueue("events_nrt", WQ_NON_REENTRANT, 0);
system_unbound_wq = alloc_workqueue("events_unbound", WQ_UNBOUND,
WQ_UNBOUND_MAX_ACTIVE);
system_freezable_wq = alloc_workqueue("events_freezable",
WQ_FREEZABLE, 0);
system_nrt_freezable_wq = alloc_workqueue("events_nrt_freezable",
WQ_NON_REENTRANT | WQ_FREEZABLE, 0);
system_power_efficient_wq = alloc_workqueue("events_power_efficient",
WQ_POWER_EFFICIENT, 0);
system_freezable_power_efficient_wq = alloc_workqueue("events_freezable_power_efficient",
WQ_FREEZABLE | WQ_POWER_EFFICIENT,
0);
BUG_ON(!system_wq || !system_long_wq || !system_nrt_wq ||
!system_unbound_wq || !system_freezable_wq ||
!system_nrt_freezable_wq ||
!system_power_efficient_wq ||
!system_freezable_power_efficient_wq);
return 0;
}
early_initcall(init_workqueues);
| SubhrajyotiSen/HelioxKernelOnyx | kernel/workqueue.c | C | gpl-2.0 | 109,169 |
/**
* @version 1.0.0
* @package YPR - YouTube Playlist Reader
* @author Fotis Evangelou - http://nuevvo.gr
* @copyright Copyright (c) 2010 - 2012 Nuevvo Webware Ltd. All rights reserved.
* @license GNU/GPL license: http://www.gnu.org/copyleft/gpl.html
*/
ul.yprList {list-style:none;padding:8px 0;margin:0;}
ul.yprList li {float:left;width:310px;padding:5px;margin:0;text-align:center;}
ul.yprList li img {display:block;border:5px solid #ccc;width:300px;height:auto;}
| cristoslc/youtube-playlist-reader | css/ypr.css | CSS | gpl-2.0 | 481 |
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="en-US" xmlns="http://www.w3.org/1999/xhtml">
<head>
<!-- Taken from from http://easy-code.ru/lesson/formatting-numeric-output-java -->
<!-- Edited by Dushen Alexey on 05.08.2014 https://github.com/blacky0x0/java-docs-ru -->
<title>Formatting Numeric Print Output (The Java™ Tutorials >
Learning the Java Language > Numbers and Strings)
</title>
<meta content="text/html; charset=UTF-8" http-equiv="content-type">
<meta name="description" content="This beginner Java tutorial describes fundamentals of programming in the Java programming language" />
<meta name="keywords" content="java programming, learn java, java sample code, java objects, java classes, java inheritance, interfaces, variables, arrays, data types, operators, control flow, number, string" />
<style type="text/css">
.FigureCaption {
margin-left: 1in;
margin-right: 1in;
font-family: sans-serif;
font-size: smaller;
text-align: justify;
}
#TopBar_bl {
background: url(../../images/java_bar_bl.gif) 0 100% no-repeat;
width: 100%;
height: 60px;
}
#TopBar_br {
background: url(../../images/java_bar_br.gif) 100% 100% no-repeat;
width: 100%;
height: 60px;
}
#TopBar_tl {
background: url(../../images/java_bar_tl.gif) 0 0 no-repeat;
width: 100%;
height: 60px;
}
#TopBar_tr {
background: url(../../images/java_bar_tr.gif) 100% 0 no-repeat;
width: 100%;
height: 60px;
}
#TopBar {
background: #35556B url(../../images/java_bar.gif);
margin: 10px 10px 0 10px;
height:60px;
min-width:700px;
color: white;
font-family: sans-serif;
font-weight: bold;
}
@media print {
#BreadCrumbs, #Download {
display: none;
}
}
#TopBar_right {
line-height: 14px;
float: right;
padding-top: 2px;
padding-right: 30px;
text-align: left;
}
@media print {
#TopBar_right {
display: none;
}
}
#TopBar_right a {
font-size: 12px;
margin: 3px;
padding: 0;
}
#TopBar a:visited, #TopBar a:link {
color: white;
text-decoration: none;
}
#TopBar a:hover, #TopBar a:active {
background-color: white;
color: #35556B;
}
#BreadCrumbs {
padding: 4px 5px 0.5em 0;
font-family: sans-serif;
float: right;
}
#BreadCrumbs a {
color: blue;
}
#BreadCrumbs a:visited, #BreadCrumbs a:link {
text-decoration: none;
}
#BreadCrumbs a:hover, #BreadCrumbs a:active {
text-decoration: underline;
}
#PageTitle {
margin: 0 5px 0.5em 0;
color: #F90000;
}
#PageContent{
margin: 0 5px 0 20px;
}
.LeftBar_shown {
width: 13em;
float: left;
margin-left: 10px;
margin-top: 4px;
margin-bottom: 2em;
margin-right: 10px;
}
@media print {
.LeftBar_shown {
display: none;
}
}
.LeftBar_hidden {
display: none;
}
#Footer {
padding-top: 10px;
padding-left: 10px;
margin-right: 10px;
}
.footertext {
font-size: 10px;
font-family: sans-serif;
margin-top: 1px;
}
#Footer2 {
padding-top: 10px;
padding-left: 10px;
margin-right: 10px;
}
.NavBit {
padding: 4px 5px 0.5em 0;
font-family: sans-serif;
}
@media print {
.NavBit {
display: none;
}
}
#TagNotes {
text-align: right;
}
@media print {
#TagNotes a:visited, #TagNotes a:link {
color: #35556B;
text-decoration: none;
}
}
#Contents a, .NavBit a, #TagNotes a {
color: blue
}
#TagNotes a:visited, #TagNotes a:link,
#Contents a:visited, #Contents a:link,
.NavBit a:visited, .NavBit a:link {
text-decoration: none;
}
#TagNotes a:hover, #TagNotes a:active,
#Contents a:hover, #Contents a:active,
.NavBit a:hover, .NavBit a:active {
text-decoration: underline;
}
#Contents {
float: left;
font-family: sans-serif;
}
@media print {
#Contents {
display: none;
}
}
@media screen {
div.PrintHeaders {
display: none;
}
}
.linkLESSON, .nolinkLESSON {
margin-left: 0.5em;
text-indent: -0.5em
}
.linkAHEAD, .nolinkAHEAD, .linkQUESTIONS, .nolinkQUESTIONS {
margin-left: 1.5em;
text-indent: -0.5em
}
.linkBHEAD, .nolinkBHEAD {
margin-left: 2.5em;
text-indent: -0.5em
}
.linkCHEAD, .nolinkCHEAD {
margin-left: 3.5em;
text-indent: -0.5em
}
.nolinkLESSON, .nolinkAHEAD, .nolinkBHEAD, .nolinkCHEAD,
.nolinkQUESTIONS {
font-weight: bold;
color: #F90000;
}
.MainFlow_indented {
margin-right: 10px;
margin-left: 15em;
margin-bottom: 2em;
}
.MainFlow_wide {
margin-right: 10px;
margin-left: 10px;
margin-bottom: 2em;
}
@media print {
.MainFlow_indented, .MainFlow_wide {
padding-top: 0;
margin-top: 10px;
margin-right: 10px;
margin-left: 0;
}
}
h1, h2, h3, h4, h5 {
color: #F90000;
font-family: sans-serif;
}
h1 {
font-weight: bold;
font-size: 20px;
}
h2 {
font-weight: bold;
font-size: 17px;
}
h3 {
font-weight: bold;
font-size: 14px;
}
h4 {
font-size: 15px;
}
h5 {
font-size: 12px;
}
#ToggleLeft {
display: none;
}
.note {
margin: 0 30px 0px 30px;
}
.codeblock {
margin: 0 30px 0px 30px;
}
.tocli {
list-style-type:none;
}
</style>
<script type="text/javascript">
/* <![CDATA[ */
function leftBar() {
var nameq = 'tutorial_showLeftBar='
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookieString = cookies[i];
while (cookieString.charAt(0) == ' ') {
cookieString = cookieString.substring(1, cookieString.length);
}
if (cookieString.indexOf(nameq) == 0) {
cookieValue = cookieString.substring(nameq.length,
cookieString.length);
return cookieValue == 'yes';
}
}
return true;
}
function showLeft(b) {
var contents = document.getElementById("LeftBar");
var main = document.getElementById("MainFlow");
var toggle = document.getElementById("ToggleLeft");
if (b) {
contents.className = "LeftBar_shown";
main.className = "MainFlow_indented";
toggle.innerHTML = "Hide TOC";
document.cookie = 'tutorial_showLeftBar=yes; path=/';
} else {
contents.className = "LeftBar_hidden";
main.className = "MainFlow_wide";
toggle.innerHTML = "Show the TOC";
document.cookie = 'tutorial_showLeftBar=no; path=/';
}
}
function toggleLeft() {
showLeft(document.getElementById("LeftBar").className ==
"LeftBar_hidden");
document.getElementById("ToggleLeft").blur();
}
function load() {
showLeft(leftBar());
document.getElementById("ToggleLeft").style.display="inline";
}
function showCode(displayCodePage, codePath) {
var codePathEls = codePath.split("/");
var currDocPathEls = location.href.split("/");
//alert ("codePathEls = " + codePathEls + "\n" + "currDocPathEls = " + currDocPathEls);
currDocPathEls.pop(); // remove file name at the end
while (codePathEls.length > 0) {
if (codePathEls[0] == "..") {
codePathEls.shift();
currDocPathEls.pop();
} else {
break;
}
}
var fullCodePath = currDocPathEls.join("/") + "/" + codePathEls.join("/");
//alert ("fullCodePath = " + fullCodePath );
if (codePath.indexOf(".java") != -1 || codePath.indexOf(".jnlp") != -1) {
window.location.href = displayCodePage + "?code=" + encodeURI(fullCodePath);
} else {
window.location.href = fullCodePath;
}
}
/* ]]> */
</script>
</head>
<body onload="load()">
<noscript>
A browser with JavaScript enabled is required for this page to operate properly.
</noscript>
<div id="TopBar"> <div id="TopBar_tr"> <div id="TopBar_tl"> <div id="TopBar_br"> <div id="TopBar_bl">
<div id="TopBar_right">
<a target="_blank"
href="http://www.oracle.com/technetwork/java/javase/downloads/java-se-7-tutorial-2012-02-28-1536013.html">Download Ebooks</a><br />
<a target="_blank"
href="http://www.oracle.com/technetwork/java/javase/downloads/index.html">Download JDK</a>
<br />
<a href="../../search.html" target="_blank">Search Java Tutorials</a>
<br />
<a href="javascript:toggleLeft()"
id="ToggleLeft">Hide TOC</a>
</div>
</div> </div> </div> </div> </div>
<div class="PrintHeaders">
<b>Курс:</b> Изучение языка Java
<br /><b>Урок:</b> Числа и строки
<br /><b>Section:</b> Numbers
</div>
<div id="LeftBar" class="LeftBar_shown">
<div id="Contents">
<div class="linkLESSON"><a href="index.html">Числа и строки</a></div>
<div class="linkAHEAD"><a href="numbers.html">Числа</a></div>
<div class="linkBHEAD"><a href="numberclasses.html">Классы чисел</a></div>
<div class="nolinkBHEAD">Форматирование вывода</div>
<div class="linkBHEAD"><a href="beyondmath.html">Beyond Basic Arithmetic</a></div>
<div class="linkBHEAD"><a href="numbersummary.html">Summary of Numbers</a></div>
<div class="linkQUESTIONS"><a href="QandE/numbers-questions.html">Вопросы и упражнения</a></div>
<div class="linkAHEAD"><a href="characters.html">Characters</a></div>
<div class="linkAHEAD"><a href="strings.html">Строки</a></div>
<div class="linkBHEAD"><a href="converting.html">Converting Between Numbers and Strings</a></div>
<div class="linkBHEAD"><a href="manipstrings.html">Работа со строками</a></div>
<div class="linkBHEAD"><a href="comparestrings.html">Сравнение строк и частей строк</a></div>
<div class="linkBHEAD"><a href="buffers.html">Класс StringBuilder</a></div>
<div class="linkBHEAD"><a href="stringsummary.html">Summary of Characters and Strings</a></div>
<div class="linkAHEAD"><a href="autoboxing.html">Autoboxing and Unboxing</a></div>
<div class="linkQUESTIONS"><a href="QandE/characters-questions.html">Вопросы и упражнения</a></div>
</div>
</div>
<div id="MainFlow" class="MainFlow_indented">
<span id="BreadCrumbs">
<a href="../../index.html" target="_top">Home Page</a>
>
<a href="../index.html" target="_top">Изучение языка Java</a>
>
<a href="index.html" target="_top">Числа и строки</a>
</span>
<div class="NavBit">
<a target="_top" href="numberclasses.html">« Previous</a> • <a target="_top" href="../TOC.html">Trail</a> • <a target="_top" href="beyondmath.html">Next »</a>
</div>
<div id="PageTitle"><h1>Форматирование вывода</h1></div>
<div id="PageContent">
<!-- Formatting Numeric Print Output -->
<p>
Earlier you saw the use of the <code>print</code> and <code>println</code> methods for printing strings to standard output (<code>System.out</code>).
Since all numbers can be converted to strings (as you will see later in this
lesson),
you can use these methods to print out an arbitrary mixture of strings and numbers.
The Java programming language has other methods, however, that allow you to exercise much more control over your print output when numbers are included.</p>
<h2>Методы printf и format</h2>
<p>
Пакет <code>java.io</code> содержит
класс
<code>PrintStream</code>, у которого есть специальные методы <code>format</code> и <code>printf</code> для форматирования.
Эти методы эквивалентны друг другу и
их можно использовать вместо <code>print</code> и <code>println</code>.
Хорошо знакомая конструкция <code>System.out</code> является объектом класса <code>PrintStream</code>,
поэтому в любом участке кода можно спокойно заменить методы <code>print</code> и <code>println</code> на
<code>format</code> или <code>printf</code>.
Например:
</p>
<div class="codeblock"><pre>
System.out.format(.....);
</pre></div>
<p>
Синтаксис этих методов класса
<a class="APILink" target="_blank" href="http://docs.oracle.com/javase/7/docs/api/java/io/PrintStream.html"><code>java.io.PrintStream</code> </a>
одинаков:
</p>
<div class="codeblock"><pre>
public PrintStream format(String format, Object... args)
</pre></div>
<p>
где <code>format</code> - это строка, определяющая шаблон, согласно которому будет происходить форматирование, а
<code>args</code> - это список переменных для печати по заданному шаблону
(запись <code>Object... args</code> определяет переменное количество аргументов). Простой пример:
</p>
<div class="codeblock"><pre>
System.out.format("The value of " + "the float variable is " +
"%f, while the value of the " + "integer variable is %d, " +
"and the string is %s", floatVar, intVar, stringVar);
</pre></div>
<p>
Строка <code>format</code> содержит простой текст и специальные <em>форматирующие символы</em>,
используемые при форматировании списка объектов второго параметра <code>args</code>.
Эти символы начинаются со знака процента (%) и заканчиваются <i>конвертором</i> - символом,
который определяет тип переменной для форматирования.
Между знаком процента (%) и конвертером можно указать дополнительные флаги и спецификаторы.
Полное описание конвертеров, флагов и спецификаторов можно посмотреть по ссылке
<a class="APILink" target="_blank" href="http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html">
<code>java.util.Formatter</code></a>.
Пример:
</p>
<p>
Простенький пример:
</p>
<div class="codeblock"><pre>
int i = 461012;
System.out.format("The value of i is: %d%n", i);
</pre></div>
<p>
Спецификатор <code>%d</code> указывает на то, что переменная должна быть целым числом.
<code>%n</code> - платформенно-независимый символ перевода строки.
Вывод будет следующим:</p>
<div class="codeblock"><pre>
The value of i is: 461012
</pre></div>
<p>
Чтобы вывод соответствовал <s>региональным стандартам определенного языка</s> следует использовать
перегруженные версии методов <code>printf</code> и <code>format</code>, которые имеют следующий синтаксис:
</p>
<div class="codeblock"><pre>
public PrintStream printf(Locale l, String format, Object... args)
public PrintStream format(Locale l, String format, Object... args)
</pre></div>
<p>
Например, в качестве разделителя целой и дробной частей числа с плавающей точкой во Французской системе используется запятая,
в то время как в Английской используется точка:</p>
<div class="codeblock"><pre>
System.out.format(Locale.FRANCE,
"The value of the float " + "variable is %f, while the " +
"value of the integer variable " + "is %d, and the string is %s%n",
floatVar, intVar, stringVar);
</pre></div>
<h2>Пример</h2>
<p>
В таблице перечислены некоторые конвертеры и флаги, которые были использованы в программе <code>TestFormat.java</code>
</p>
<table width="70%" border="1" cellpadding="4" cellspacing="3"
summary="Converters and flags that are used in the sample program TestFormat.java">
<caption style="font-weight: bold">Конвертеры и флаги, использованные в <code>TestFormat.java</code></caption>
<tr>
<th id="h1" width="10%">Конвертер</th>
<th id="h2" width="10%">Флаг</th>
<th id="h3" width="50%">Описание</th>
</tr>
<tr>
<td headers="h1">d</td>
<td headers="h2"> </td>
<td headers="h3">
Десятичное целое
</td>
</tr>
<tr>
<td headers="h1">f</td>
<td headers="h2"> </td>
<td headers="h3">
Число с плавающей точкой (float)
</td>
</tr>
<tr>
<td headers="h1">n</td>
<td headers="h2"> </td>
<td headers="h3">
Символ новой строки в зависимости от платформы, на которой запущена программа.
Старайтесь всегда использовать <code>%n</code>, а не <code>\n</code>
</td>
</tr>
<tr>
<td headers="h1">tB</td>
<td headers="h2"> </td>
<td headers="h3">
Дата и время—полное название месяца в зависимости от языка
</td>
</tr>
<tr>
<td headers="h1">td, te</td>
<td headers="h2"> </td>
<td headers="h3">
Дата и время — 2 цифры дня месяца. td - с ведущими нулями, te - без
</td>
</tr>
<tr>
<td headers="h1">ty, tY</td>
<td headers="h2"> </td>
<td headers="h3">
Дата и время —ty = год из 2-х цифр, tY = год из 4-х цифр
</td>
</tr>
<tr>
<td headers="h1">tl</td>
<td headers="h2"> </td>
<td headers="h3">
Дата и время— часы в 12-ти часовом формате
</td>
</tr>
<tr>
<td headers="h1">tM</td>
<td headers="h2"> </td>
<td headers="h3">
Дата и время— минуты из 2-х цифр с ведущими нулями
</td>
</tr>
<tr>
<td headers="h1">tp</td>
<td headers="h2"> </td>
<td headers="h3">
Дата и время — am/pm в зависимости от языка (в нижнем регистре)
</td>
</tr>
<tr>
<td headers="h1">tm</td>
<td headers="h2"> </td>
<td headers="h3">
Дата и время — месяц из 2-х цифр с ведущими нулями
</td>
</tr>
<tr>
<td headers="h1">tD</td>
<td headers="h2"> </td>
<td headers="h3">
Дата и время — дата в формате %tm%td%ty
</td>
</tr>
<tr>
<td headers="h1"> </td>
<td headers="h2">08</td>
<td headers="h3">
Восемь символов в ширину, дозаполняя ведущими нулями по необходимости
</td>
</tr>
<tr>
<td headers="h1"> </td>
<td headers="h2">+</td>
<td headers="h3">
Включить знак (положительный или отрицательный)
</td>
</tr>
<tr>
<td headers="h1"> </td>
<td headers="h2">,</td>
<td headers="h3">
Включить специфичную для каждой локали группировку символов
</td>
</tr>
<tr>
<td headers="h1"> </td>
<td headers="h2">-</td>
<td headers="h3">
Выравнивание по левому краю
</td>
</tr>
<tr>
<td headers="h1"> </td>
<td headers="h2">.3</td>
<td headers="h3">
Три символа после десятичного разделителя
</td>
</tr>
<tr>
<td headers="h1"> </td>
<td headers="h2">10.3</td>
<td headers="h3">
Десять символов в ширину, выравнивание по правому краю, три символа после десятичного разделителя
</td>
</tr>
</table>
<p>
В программе показаны несколько примеров форматирования с использованием метода <code>format</code>.
Вывод показан в комментариях:</p>
<div class="codeblock"><pre>
import java.util.Calendar;
import java.util.Locale;
public class TestFormat {
public static void main(String[] args) {
long n = 461012;
System.out.format("%d%n", n); // --> "461012"
System.out.format("%08d%n", n); // --> "00461012"
System.out.format("%+8d%n", n); // --> " +461012"
System.out.format("%,8d%n", n); // --> " 461,012"
System.out.format("%+,8d%n%n", n); // --> "+461,012"
double pi = Math.PI;
System.out.format("%f%n", pi); // --> "3.141593"
System.out.format("%.3f%n", pi); // --> "3.142"
System.out.format("%10.3f%n", pi); // --> " 3.142"
System.out.format("%-10.3f%n", pi); // --> "3.142"
System.out.format(Locale.FRANCE,
"%-10.4f%n%n", pi); // --> "3,1416"
Calendar c = Calendar.getInstance();
System.out.format("%tB %te, %tY%n", c, c, c); // --> "May 29, 2006"
System.out.format("%tl:%tM %tp%n", c, c, c); // --> "2:34 am"
System.out.format("%tD%n", c); // --> "05/29/06"
}
}
</pre></div>
<div class="note"><hr /><strong>Примечание:</strong>
в этой главе показаны основы работы с методами <code>format</code> и <code>printf</code>.
Более подробно о форматировании рассказано в главе, посвященной
<a class="TutorialLink" target="_top" href="../../essential/io/formatting.html"><code>основам ввода/вывода</code></a>.<br />
О создании строк при помощи метода <code>String.format</code> рассказано в главе, посвященной
<a class="TutorialLink" target="_top" href="strings.html">строкам</a>.
<hr /></div>
<h2>Класс DecimalFormat</h2>
<p>
You can use the
<a class="APILink" target="_blank" href="http://docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html"><code>java.text.DecimalFormat</code> </a> class to control the display of leading and trailing zeros, prefixes and suffixes, grouping (thousands) separators, and the decimal separator.
<code>DecimalFormat</code> offers a great deal of flexibility in the formatting of numbers, but it can make your code more complex.</p>
<p>
The example that follows creates a <code>DecimalFormat</code> object, <code>myFormatter</code>, by passing a pattern string to the <code>DecimalFormat</code> constructor.
The <code>format()</code> method, which <code>DecimalFormat</code> inherits from <code>NumberFormat</code>, is then invoked by <code>myFormatter</code>—it accepts a <code>double</code> value as an argument and returns the formatted number in a string:</p>
<p>
Here is a sample program that illustrates the use of <code>DecimalFormat</code>:</p>
<div class="codeblock"><pre>
import java.text.*;
public class DecimalFormatDemo {
static public void customFormat(String pattern, double value ) {
DecimalFormat myFormatter = new DecimalFormat(pattern);
String output = myFormatter.format(value);
System.out.println(value + " " + pattern + " " + output);
}
static public void main(String[] args) {
customFormat("###,###.###", 123456.789);
customFormat("###.##", 123456.789);
customFormat("000000.000", 123.78);
customFormat("$###,###.###", 12345.67);
}
}
</pre></div>
<p>
Вывод будет следующим:</p>
<div class="codeblock"><pre>
123456.789 ###,###.### 123,456.789
123456.789 ###.## 123456.79
123.78 000000.000 000123.780
12345.67 $###,###.### $12,345.67
</pre></div>
<p>
В таблице даны пояснения к каждой выведенной строке:
</p>
<table width="100%" border="1" cellpadding="4" cellspacing="3" summary="DecimalFormatDemo.java output">
<caption style="font-weight: normal">Вывод <code>DecimalFormat.java</code></caption>
<tr>
<th id="h101">Значение</th>
<th id="h102">Шаблон</th>
<th id="h103">Вывод</th>
<th id="h104">Пояснение</th>
</tr>
<tr>
<td headers="h101">123456.789</td>
<td headers="h102">###,###.###</td>
<td headers="h103">123,456.789</td>
<td headers="h104">Знак решетки (в Англии # является знаком фунта - 'pound sign') обозначает цифру,
а точка и запятая являются символами-заполнителями. Первый из которых - это десятичный разделитель,
а второй служит для группировки чисел.
</td>
</tr>
<tr>
<td headers="h101">123456.789</td>
<td headers="h102">###.##</td>
<td headers="h103">123456.79</td>
<td headers="h104">
В дробной части используемого значения указаны три цифры, а в шаблоне для дробной части используется только два разряда.
В этому случает метод <code>format</code> сделает необходимое округление.
</td>
</tr>
<tr>
<td headers="h101">123.78</td>
<td headers="h102">000000.000</td>
<td headers="h103">000123.780</td>
<td headers="h104">
Символ 0 можно использовать вместо знака решетки (или знак фунта - #), тогда форматируемое число будет дополнено нулями в начале и конце.
</td>
</tr>
<tr>
<td headers="h101">12345.67</td>
<td headers="h102">$###,###.###</td>
<td headers="h103">$12,345.67</td>
<td headers="h104">Первым знаком в шаблоне идет знак доллара ($).
Обратите внимание на то, что он выводится перед цифрами.
</td>
</tr>
</table>
</div>
<div class="NavBit">
<a target="_top" href="numberclasses.html">« Previous</a>
•
<a target="_top" href="../TOC.html">Trail</a>
•
<a target="_top" href="beyondmath.html">Next »</a>
</div>
</div>
<div id="Footer2">
<hr />
<div id="TagNotes">
<p class="footertext">Problems with the examples? Try <a target="_blank"
href="../../information/run-examples.html">Compiling and Running
the Examples: FAQs</a>.
<br />
Complaints? Compliments? Suggestions? <a target="_blank"
href="http://docs.oracle.com/javase/feedback.html">Give
us your feedback</a>.
</p>
</div>
<div id="Footer">
<p class="footertext"><a name="license_info">Your use of this</a> page and all the material on pages under "The Java Tutorials" banner
is subject to these <a href="../../information/cpyr.html">legal notices</a>.
</p>
<table border="0" cellspacing="0" cellpadding="5" summary="">
<tr>
<td width="20%">
<table width="100%" border="0" cellspacing="0" cellpadding="5">
<tr>
<td headers="h201" align="center"><img id="duke" src="../../images/DukeWave.gif" width="55" height="55" alt="duke image" /></td>
<td headers="h202" align="left" valign="middle"><img id="oracle" src="../../images/logo_oracle_footer.gif" width="100" height="29" alt="Oracle logo" /></td>
</tr>
</table>
</td>
<td width="55%" valign="middle" align="center">
<p class="footertext"><a href="http://www.oracle.com/us/corporate/index.html">About Oracle</a> | <a href="http://www.oracle.com/technology/index.html">Oracle Technology Network</a> | <a href="http://www.oracle.com/us/legal/terms/index.html">Terms of Use</a></p>
</td>
<td width="25%" valign="middle" align="right">
<p class="footertext">Copyright © 1995, 2012 Oracle and/or its affiliates.
All rights reserved.</p>
</td>
</tr>
</table>
</div>
</div>
<div class="PrintHeaders">
<b>Previous page:</b> The Numbers Classes
<br /><b>Next page:</b> Beyond Basic Arithmetic
</div>
</body>
</html>
| blacky0x0/java-docs-ru | tutorials/java/data/numberformat.html | HTML | gpl-2.0 | 30,007 |
## Xrt3d.pm is a sub-module of Graph.pm. It has all the subroutines
## needed for the Xrt3d part of the package.
##
## $Id: Xrt3d.pm,v 1.30 2006/06/07 21:09:33 emile Exp $ $Name: $
##
## This software product is developed by Michael Young and David Moore,
## and copyrighted(C) 1998 by the University of California, San Diego
## (UCSD), with all rights reserved. UCSD administers the CAIDA grant,
## NCR-9711092, under which part of this code was developed.
##
## There is no charge for this software. You can redistribute it and/or
## modify it under the terms of the GNU General Public License, v. 2 dated
## June 1991 which is incorporated by reference herein. This software is
## distributed WITHOUT ANY WARRANTY, IMPLIED OR EXPRESS, OF MERCHANTABILITY
## OR FITNESS FOR A PARTICULAR PURPOSE or that the use of it will not
## infringe on any third party's intellectual property rights.
##
## You should have received a copy of the GNU GPL along with this program.
##
##
## IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY
## PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL
## DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS
## SOFTWARE, EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF
## THE POSSIBILITY OF SUCH DAMAGE.
##
## THE SOFTWARE PROVIDED HEREIN IS ON AN "AS IS" BASIS, AND THE
## UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO PROVIDE MAINTENANCE,
## SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. THE UNIVERSITY
## OF CALIFORNIA MAKES NO REPRESENTATIONS AND EXTENDS NO WARRANTIES
## OF ANY KIND, EITHER IMPLIED OR EXPRESS, INCLUDING, BUT NOT LIMITED
## TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A
## PARTICULAR PURPOSE, OR THAT THE USE OF THE SOFTWARE WILL NOT INFRINGE
## ANY PATENT, TRADEMARK OR OTHER RIGHTS.
##
##
## Contact: [email protected]
##
##
package Chart::Graph::Xrt3d;
use Exporter ();
@ISA = qw(Exporter);
@EXPORT = qw();
@EXPORT_OK = qw(&xrt3d);
use FileHandle; # to create generic filehandles
use Carp; # for carp() and croak()
use Chart::Graph::Utils qw(:UTILS); # get global subs and variables
use Chart::Graph::XrtUtils qw(:UTILS);
$cvs_Id = '$Id: Xrt3d.pm,v 1.30 2006/06/07 21:09:33 emile Exp $';
$cvs_Author = '$Author: emile $';
$cvs_Name = '$Name: $';
$cvs_Revision = '$Revision: 1.30 $';
$VERSION = 3.2;
use strict;
#
# xrt graphing package
#
my %def_xrt_global_opts; # xrt specific globals
%def_xrt_global_opts = (
"output file" => "untitled-xrt3d.gif",
"output type" => "gif",
"x-axis title" => "x-axis",
"y-axis title" => "y-axis",
"z-axis title" => "z-axis",
"x-min" => "0",
"y-min" => "0",
"x-step" => "1",
"y-step" => "1",
"x-ticks" => undef,
"y-ticks" => undef,
"header" => ["header"],
"footer" => ["footer"],
);
#
#
# Subroutine: xrt()
#
# Description: this is the main function you will be calling from
# our scripts. please see
# www.caida.org/Tools/Graph/ for a full description
# and how-to of this subroutine
#
sub xrt3d {
my $user_global_opts_ref = shift;
my $data_set_ref = shift;
my $matrix_data_ref;
my $data_filename;
my (%global_opts);
# variables to be written to the command file
my ($plot_file, $x_axis, $y_axis, $z_axis, $x_step, $y_step);
my ($x_min, $y_min, $x_ticks, $y_ticks, $header, $footer);
my ($x_cnt, $y_cnt, $hdr_cnt, $ftr_cnt);
my ($output_file);
if (@_) {
carp 'Too many arguments. Usage: xrt3d(\%options, \@data_set)';
return 0;
}
_make_tmpdir("_Xrt3d_");
# set paths for external programs
if (not _set_xrtpaths("xrt3d")) {
_cleanup_tmpdir();
return 0;
}
# check first arg for hash
if (ref($user_global_opts_ref) ne "HASH") {
carp "Global options must be a hash.";
_cleanup_tmpdir();
return 0;
}
# call to combine user options with default options
%global_opts = _mesh_opts($user_global_opts_ref, \%def_xrt_global_opts);
# check for values in command file
while (my ($key, $value) = each %global_opts) {
if ($key eq "output file") {
$output_file = $value;
unless (defined $global_opts{"output type"}) {
carp "Must have an output type defined";
_cleanup_tmpdir();
return 0;
}
}
# If the file is PostScript ... what XRT makes is PostScript
if ($global_opts{"output type"} eq "ps") {
$plot_file = _make_tmpfile("plot", "ps");
}
# For all raster formats XRT starts out with
# X-Windows XWD format.
elsif (($global_opts{"output type"} eq "gif") or
($global_opts{"output type"} eq "xwd") or
($global_opts{"output type"} eq "png") or
($global_opts{"output type"} eq "jpg")
) {
$plot_file = _make_tmpfile("plot", "xwd");
} else {
# Default is XWD
carp "Unknown output type, defaulting to xwd";
$plot_file = _make_tmpfile("plot", "xwd");
}
if ($key eq "x-axis title") {
if(defined($value)) {
$x_axis = $value;
}
}
if ($key eq "y-axis title") {
if(defined($value)) {
$y_axis = $value;
}
}
if ($key eq "z-axis title") {
if(defined($value)) {
$z_axis = $value;
}
}
if ($key eq "x-min") {
if(defined($value)) {
$x_min = $value;
}
}
if ($key eq "y-min") {
if(defined($value)) {
$y_min = $value;
}
}
if ($key eq "x-step") {
if(defined($value)) {
$x_step = $value;
}
}
if ($key eq "y-step") {
if(defined($value)) {
$y_step = $value;
}
}
if ($key eq "x-ticks") {
if(defined($value)) {
$x_ticks = $value;
}
}
if ($key eq "y-ticks") {
if(defined($value)) {
$y_ticks = $value;
}
}
if ($key eq "header") {
if(defined($value)) {
$header = $value;
}
}
if ($key eq "footer") {
if(defined($value)) {
$footer = $value;
}
}
}
# Extract options for data.
my $data_opts = shift @{$data_set_ref};
while (my ($key, $value) = each %{$data_opts}) {
if ($key eq "type") {
if ($value eq "matrix") {
$matrix_data_ref = $data_set_ref;
}
elsif ($value eq "file") {
$data_filename = pop @{$data_set_ref};
} else {
carp "Unsupported or unknown format for data";
}
}
}
# because xrt allows multiline headers
# get the length of the header array
# each line of the header is one index
# in the array
$hdr_cnt = $#{$global_opts{"header"}} + 1;
$ftr_cnt = $#{$global_opts{"footer"}} + 1;
if (defined($matrix_data_ref)) {
# get the number of columns and number of rows
# and verify that each row has same number of
# columns
$x_cnt = $#{$matrix_data_ref} + 1;
my $tmp = $#{$matrix_data_ref->[0]} + 1;
foreach my $i (@{$matrix_data_ref}) {
if ($tmp != $#{$i} + 1) {
carp "each row must have the same number of columns";
_cleanup_tmpdir();
return 0;
}
}
$y_cnt = $tmp;
# verify that number of tick marks == corresponds
# to that of xy matrix. One tick mark for every x
# y.
if (not _verify_ticks($x_cnt, $global_opts{"x-ticks"})) {
_cleanup_tmpdir();
return 0;
}
if (not _verify_ticks($y_cnt, $global_opts{"y-ticks"})) {
_cleanup_tmpdir();
return 0;
}
} else {
# XXX
# Poor man's hack to compute rows and columns in data file. This will
# make a second pass through file, but is probably faster than doing it
# in Perl.
my ($lead, $words, $bytes);
($lead, $x_cnt, $words, $bytes) = split(/\D+/, `wc $data_filename`);
if (($x_cnt > 0) and ($words > 0)) {
$x_cnt++;
$y_cnt = $words/$x_cnt;
} else {
$x_cnt = 0;
$y_cnt = 0;
carp "Cannot compute number of rows and/or columns in file data";
}
}
##
## print command file using this format
##
# output.file
# x_min (normally 0)
# y_min (normally 0)
# x_step (normally 1)
# y_step (normally 1)
# x_cnt (number of rows of input)
# y_cnt (number of columns of input)
# data11 data12 data13 data14 .... (x by y matrix of doubles)
# data21 data22 data23 ....
# .
# .
# .
# datax1 datax2 ... dataxy
# Number of header lines (multiple header lines available)
# header1
# header2
# ...
# Number of header lines (multiple header lines available)
# foot1
# foot2
# ...
# Title of x-axis
# Title of y-axis
# Title of z-axis
# xlabel0 (x_cnt number of labels for ticks along x-axis)
# ...
# xlabelx
# ylabel0 (y_cnt number of labels for ticks along y-axis)
# ...
# ylabely
# create command file and open file handle
my $command_file = _make_tmpfile("command");
my $handle = new FileHandle;
if (not $handle->open(">$command_file")) {
carp "could not open $command_file";
_cleanup_tmpdir();
return 0;
}
print $handle "$plot_file\n";
print $handle "$x_min\n";
print $handle "$y_min\n";
print $handle "$x_step\n";
print $handle "$y_step\n";
print $handle "$x_cnt\n";
print $handle "$y_cnt\n";
if (defined($matrix_data_ref)) {
_print_matrix($handle, @{$matrix_data_ref});
} else {
_transfer_file($handle, $data_filename)
}
print $handle "$hdr_cnt\n";
_print_array($handle, @{$header});
print $handle "$ftr_cnt\n";
_print_array($handle, @{$footer});
print $handle "$x_axis\n";
print $handle "$y_axis\n";
print $handle "$z_axis\n";
_print_array($handle, @{$x_ticks});
_print_array($handle, @{$y_ticks});
$handle->close();
# call xrt and convert file to gif
if (not _exec_xrt3d($command_file)) {
_cleanup_tmpdir();
return 0;
}
my $graph_format = $global_opts{"output type"};
if ($graph_format eq "ps") {
if (not _chk_status(system("cp $plot_file $output_file"))) {
_cleanup_tmpdir();
return 0;
}
} elsif ($graph_format eq "xwd") {
if (not _chk_status(system("cp $plot_file $output_file"))) {
_cleanup_tmpdir();
return 0;
}
} else {
if(not _convert_raster($graph_format, $plot_file, $output_file)) {
_cleanup_tmpdir();
return 0;
}
}
_cleanup_tmpdir();
return 1;
}
1;
__END__
=head1 NAME
Chart::Graph::Xrt3d
=head1 SYNOPSIS
#Include module
use Chart::Graph::Xrt3d qw(xrt3d);
# Function call
xrt3d(\%options,
\@data_set
);
=head1 DESCRIPTION
This module is unmaintained, it worked with Sitraka's XRT, and hasn't been
tested against newer versions.
Sitraka (now Quest) makes a number of graphics packages for UNIX systems. XRT is
a Motif-based commercial software product that has been adapted by
CAIDA using a combination of C drivers and Perl function I<xrt3d()>.
The Perl function I<xrt3d()> provides access to the three dimensional
graphing capabilities of XRT from Perl. To access the two dimensional
graphing using XRT, use I<xrt2d()> also supplied in the
I<Chart::Graph> package.
=head1 ARGUMENTS
The options to I<xrt3d()> are listed below. Additional control over the
resulting graph is possible by using the XRT application itself once
the graph has been created.
+--------------------------------------------------------------------------+
| OPTIONS |
+----------------+--------------------------+------------------------------+
| Name | Options | Default |
|"output file" | (set your own) | "untitled-xrt3d.gif" |
|"output type" | "ps","xwd", "png", "jpg"| "xwd" |
|"x-axis title" | (set your own) | "x-axis" |
|"y-axis title" | (set your own) | "y-axis" |
|"z-axis title" | (set your own) | "z-axis" |
|"x-min" | "0" or "1"(normally 0) | "0" |
|"y-min" | "0" or "1"(normally 0) | "0" |
|"x-step" | "0" or "1"(normally 1) | "1" |
|"y-step" | "0" or "1"(normally 1) | "1" |
|"x-ticks" | (set your own) | none |
|"y-ticks" | (set your own) | none |
|"header" | (set your own) | Array ref of "header" text |
|"footer" | (set your own) | Array ref of "footer" text |
+----------------+--------------------------+------------------------------+
The I<xrt3d> function only accepts data in one of two forms. The
choices are: either C<[\%data1_opts, \@data_matrix]> or
C<[\%data1_opts, "filename"]> The data options are listed below.
+--------------------------------------------------------------------------+
| DATA OPTIONS |
+----------------+--------------------------+------------------------------+
| Name | Options | Default |
+----------------+--------------------------+------------------------------+
| "type" | Data format: "matrix" or | none |
| | "file" | |
+----------------+--------------------------+------------------------------+
=head2 DETAILS ON GRAPHICS CONVERTER OPTIONS
The xrt package supports only two graphics formats internally:
Postscript and the X windows format XWD. Additional raster graphics
formats are supported with Chart::Graph by using one of two graphics
converter packages: I<Imagemagick> and I<Netpbm>.
If you need to install a converter package,I<Imagemagick>
I<http://www.imagemagick.org/> is probably preferable
simply for its comparatively simplicity. It uses one program
I<convert> for all of it's conversion needs, so it is easy to manage
and simple for Chart::Graph to use. Many UNIX systems come with some
collection of the I<Netpbm> utilities already installed, thus users
may be able to start using Chart::Graph without adding any additional
converters. Alas, it is unlikely any distributions would include all
the converters for the newest graphics formats used by Chart::Graph.
In that case it may still preferable to use I<Imagemagick> simply for
the sake of avoiding installing over 80 utilities that come with
current distributions of I<Netpbm>. For more information on the
current distribution of I<Netpbm> go to the current website at:
I<http://netpbm.sourceforge.net/>
The xrt package also allows for multiple header and footers with each
graph. As a result, instead of just the usual string, an array
reference containing the multiple strings for the header and footer
text.
=head1 EXAMPLES
The following four examples show Chart::Graph::Xrt3d in different roles
and producing different styles of output.
=head2 EXAMPLE: STOCK PRICES FOR JOE'S RESTAURANT
The first example creates a three dimensional bar chart of
fictitious stock data that is displayed in the graphic file
F<xrt3d-1.gif>. Note that I<xrt3d()> uses the older gif file format,
but can use others as noted above if you have the available converters
provided.
#make sure to include Chart::Graph
use Chart::Graph::Xrt3d qw(xrt3d);
#using a 3 by 6 matrix for the data set
xrt3d({"output file" => "xrt3d-1.gif",
"output type" => "gif",
"header" =>
["Stock prices for Joe's restaurant chain",
"Compiled from local records"
],
"footer" =>
["Joe's Restaurant"],
"y-ticks"=>["Jan/Feb", "Mar/Apr", "May/Jun", "Jul/Aug",
"Sep/Oct", "Nov/Dec"],
"x-axis title" => "Years monitored",
"y-axis title" => "Month's tracked",
"z-axis title" => "Stock prices",
},
[{"type" => "matrix"},
["4", "5", "3", "6", "6", "5"],
["8", "13", "20", "45", "100", "110" ],
["70", "45", "10", "5", "4", "3"]])
=for html
<p><center><img src="http://www.caida.org/tools/utilities/graphing/xrt3d-1.jpg"></center></p>
<p><center><em>xrt3d-1.jpg</em></center></p>
=head2 EXAMPLE: EARLY GROWTH OF THE INTERNET
The following example creates a three dimensional bar chart of data
collected on the early growth of the Internet (URL and corporate
source included on graph.) The result in this case is display in one
of the newest graphics formats the PNG format: F<xrt3d-2.png>.
#make sure to include Chart::Graph
use Chart::Graph::Xrt3d qw(xrt3d);
xrt3d({"output file" => "xrt3d-2.png",
"output type" => "png",
"header" =>
["Growth of Early Internet",
"(according to Internet Wizards - http://www.nw.com/)",
],
"footer" =>
["http://www.mit.edu/people/mkgray/net/internet-growth-raw-data.html"],
"y-ticks"=>["Jan 93", "Apr 93", "Jul 93",
"Oct 93", "Jan 94", "Jul 94",
"Oct 94", "Jan 95", "Jul 95",
"Jan 96"
],
"x-ticks"=>["Hosts", "Domains", "Replied to Ping"],},
[{"type" => "matrix"},
["1.3e6", "1.5e6", "1.8e6", "2.1e6", "2.2e6", "3.2e6",
"3.9e6","4.9e6", "6.6e6", "9.5e6"
],
["21000","22000", "26000", "28000", "30000", "46000",
"56000", "71000", "120000", "240000"
],
["NA", "0.4e6", "NA", "0.5e6", "0.6e6", "0.7e6",
"1.0e6", "1.0e6", "1.1e6", "1.7e6"
]
]
);
=for html
<p><center><img src="http://www.caida.org/tools/utilities/graphing/xrt3d-2.png"></center></p>
<p><center><em>xrt3d-2.png</em></center></p>
=head2 EXAMPLE: USING A DATA FILE FOR INPUT
The next example uses a file instead of a array for it's data source.
The file is listed below the Perl code.
#make sure to include Chart::Graph
use Chart::Graph::Xrt3d qw(xrt3d);
if (xrt3d({"output file" => "xrt3d-3.gif",
"output type" => "gif",
"x-ticks"=>["a", "b", "c"],
"y-ticks"=>["w", "x", "y", "z"],},
[{"type" => "file"},
"xrt3d_data.txt"])) {
print "ok\n";
} else {
print "not ok\n";
}
The data file used in the above example is as follows.
10 15 23 10
4 13 35 45
29 15 64 24
=for html
<p><center><img src="http://www.caida.org/tools/utilities/graphing/xrt3d-3.gif"></center></p>
<p><center><em>xrt3d-3.gif</em></center></p>
=head1 MORE INFO
For more information on XRT:
http://www.quest.com/xrt_pds/
=head1 CONTACT
Send email to [email protected] is you have problems, questions,
or comments. To subscribe to the mailing list send mail to
[email protected] with a body of "subscribe [email protected]"
=head1 AUTHOR
CAIDA Perl development team ([email protected])
=cut
| gitpan/Chart-Graph | Graph/Xrt3d.pm | Perl | gpl-2.0 | 18,578 |
package mx.gob.sct.utic.mimappir.admseg.postgreSQL.services;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import mx.gob.sct.utic.mimappir.admseg.postgreSQL.model.SEGUSUARIO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.transaction.annotation.Transactional;
/**
* A custom service for retrieving users from a custom datasource, such as a
* database.
* <p>
* This custom service must implement Spring's {@link UserDetailsService}
*/
@Transactional(value="transactionManager_ADMSEG_POSGIS",readOnly=true)
public class CustomUserDetailsService implements UserDetailsService{
private SEGUSUARIO_Service SEGUSUARIO_Service;
//private UserDAO userDAO2 = new UserDAO();
/**
* Retrieves a user record containing the user's credentials and access.
*/
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException, DataAccessException {
// Declare a null Spring User
UserDetails user = null;
try {
// Search database for a user that matches the specified username
// You can provide a custom DAO to access your persistence layer
// Or use JDBC to access your database
// DbUser is our custom domain user. This is not the same as
// Spring's User
List<SEGUSUARIO> registros = SEGUSUARIO_Service.getUsuario(username);
//List<SEGUSUARIO> registros = SEGUSUARIO_Service.getUsuariosList();
Iterator<SEGUSUARIO> it = registros.iterator();
SEGUSUARIO dbUser = null;
while(it.hasNext()){
dbUser = it.next();
}
// Populate the Spring User object with details from the dbUser
// Here we just pass the username, password, and access level
// getAuthorities() will translate the access level to the correct
// role type
user = new User(dbUser.getCUSUARIO(), dbUser.getCPASSWORD(), true, true,
true, true, getAuthorities(0));
} catch (Exception e) {
throw new UsernameNotFoundException("Error in retrieving user");
}
// Return user to Spring for processing.
// Take note we're not the one evaluating whether this user is
// authenticated or valid
// We just merely retrieve a user that matches the specified username
return user;
}
/**
* Retrieves the correct ROLE type depending on the access level, where
* access level is an Integer. Basically, this interprets the access value
* whether it's for a regular user or admin.
*
* @param access
* an integer value representing the access of the user
* @return collection of granted authorities
*/
public Collection<GrantedAuthority> getAuthorities(Integer access) {
// Create a list of grants for this user
List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>(2);
// All users are granted with ROLE_USER access
// Therefore this user gets a ROLE_USER by default
authList.add(new GrantedAuthorityImpl("ROLE_USER"));
// Check if this user has admin access
// We interpret Integer(1) as an admin user
if (access.compareTo(1) == 0) {
// User has admin access
authList.add(new GrantedAuthorityImpl("ROLE_ADMIN"));
}
// Return list of granted authorities
return authList;
}
@Autowired
public void setMenuService(SEGUSUARIO_Service service) {
this.SEGUSUARIO_Service = service;
}
} | IvanSantiago/retopublico | MiMappir/src/mx/gob/sct/utic/mimappir/admseg/postgreSQL/services/CustomUserDetailsService.java | Java | gpl-2.0 | 3,913 |
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>translate.storage.pypo</title>
<link rel="stylesheet" href="epydoc.css" type="text/css" />
<script type="text/javascript" src="epydoc.js"></script>
</head>
<body bgcolor="white" text="black" link="blue" vlink="#204080"
alink="#204080">
<!-- ==================== NAVIGATION BAR ==================== -->
<table class="navbar" border="0" width="100%" cellpadding="0"
bgcolor="#a0c0ff" cellspacing="0">
<tr valign="middle">
<!-- Home link -->
<th> <a
href="translate-module.html">Home</a> </th>
<!-- Tree link -->
<th> <a
href="module-tree.html">Trees</a> </th>
<!-- Index link -->
<th> <a
href="identifier-index.html">Indices</a> </th>
<!-- Help link -->
<th> <a
href="help.html">Help</a> </th>
<!-- Project homepage -->
<th class="navbar" align="right" width="100%">
<table border="0" cellpadding="0" cellspacing="0">
<tr><th class="navbar" align="center"
><a class="navbar" target="_top" href="http://translate.sourceforge.net/wiki/toolkit/index">Translate Toolkit</a></th>
</tr></table></th>
</tr>
</table>
<table width="100%" cellpadding="0" cellspacing="0">
<tr valign="top">
<td width="100%">
<span class="breadcrumbs">
<a href="translate-module.html">Package translate</a> ::
<a href="translate.storage-module.html">Package storage</a> ::
Module pypo
</span>
</td>
<td>
<table cellpadding="0" cellspacing="0">
<!-- hide/show private -->
<tr><td align="right"><span class="options">[<a href="javascript:void(0);" class="privatelink"
onclick="toggle_private();">hide private</a>]</span></td></tr>
<tr><td align="right"><span class="options"
>[<a href="frames.html" target="_top">frames</a
>] | <a href="translate.storage.pypo-module.html"
target="_top">no frames</a>]</span></td></tr>
</table>
</td>
</tr>
</table>
<!-- ==================== MODULE DESCRIPTION ==================== -->
<h1 class="epydoc">Module pypo</h1><p class="nomargin-top"><span class="codelink"><a href="translate.storage.pypo-pysrc.html">source code</a></span></p>
<p>classes that hold units of .po files (pounit) or entire files (pofile)
gettext-style .po (or .pot) files are used in translations for KDE et al
(see kbabel)</p>
<!-- ==================== CLASSES ==================== -->
<a name="section-Classes"></a>
<table class="summary" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td colspan="2" class="table-header">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr valign="top">
<td align="left"><span class="table-header">Classes</span></td>
<td align="right" valign="top"
><span class="options">[<a href="#section-Classes"
class="privatelink" onclick="toggle_private();"
>hide private</a>]</span></td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="translate.storage.pypo.pounit-class.html" class="summary-name">pounit</a>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="translate.storage.pypo.pofile-class.html" class="summary-name">pofile</a><br />
A .po file containing various units
</td>
</tr>
</table>
<!-- ==================== FUNCTIONS ==================== -->
<a name="section-Functions"></a>
<table class="summary" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td colspan="2" class="table-header">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr valign="top">
<td align="left"><span class="table-header">Functions</span></td>
<td align="right" valign="top"
><span class="options">[<a href="#section-Functions"
class="privatelink" onclick="toggle_private();"
>hide private</a>]</span></td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a href="translate.storage.pypo-module.html#escapeforpo" class="summary-sig-name">escapeforpo</a>(<span class="summary-sig-arg">line</span>)</span><br />
Escapes a line for po format.</td>
<td align="right" valign="top">
<span class="codelink"><a href="translate.storage.pypo-pysrc.html#escapeforpo">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="unescapehandler"></a><span class="summary-sig-name">unescapehandler</span>(<span class="summary-sig-arg">escape</span>)</span></td>
<td align="right" valign="top">
<span class="codelink"><a href="translate.storage.pypo-pysrc.html#unescapehandler">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="wrapline"></a><span class="summary-sig-name">wrapline</span>(<span class="summary-sig-arg">line</span>)</span><br />
Wrap text for po files.</td>
<td align="right" valign="top">
<span class="codelink"><a href="translate.storage.pypo-pysrc.html#wrapline">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="quoteforpo"></a><span class="summary-sig-name">quoteforpo</span>(<span class="summary-sig-arg">text</span>)</span><br />
quotes the given text for a PO file, returning quoted and escaped
lines</td>
<td align="right" valign="top">
<span class="codelink"><a href="translate.storage.pypo-pysrc.html#quoteforpo">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a href="translate.storage.pypo-module.html#extractpoline" class="summary-sig-name">extractpoline</a>(<span class="summary-sig-arg">line</span>)</span><br />
Remove quote and unescape line from po file.</td>
<td align="right" valign="top">
<span class="codelink"><a href="translate.storage.pypo-pysrc.html#extractpoline">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="unquotefrompo"></a><span class="summary-sig-name">unquotefrompo</span>(<span class="summary-sig-arg">postr</span>)</span></td>
<td align="right" valign="top">
<span class="codelink"><a href="translate.storage.pypo-pysrc.html#unquotefrompo">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="is_null"></a><span class="summary-sig-name">is_null</span>(<span class="summary-sig-arg">lst</span>)</span></td>
<td align="right" valign="top">
<span class="codelink"><a href="translate.storage.pypo-pysrc.html#is_null">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="extractstr"></a><span class="summary-sig-name">extractstr</span>(<span class="summary-sig-arg">string</span>)</span></td>
<td align="right" valign="top">
<span class="codelink"><a href="translate.storage.pypo-pysrc.html#extractstr">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
</table>
<!-- ==================== VARIABLES ==================== -->
<a name="section-Variables"></a>
<table class="summary" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td colspan="2" class="table-header">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr valign="top">
<td align="left"><span class="table-header">Variables</span></td>
<td align="right" valign="top"
><span class="options">[<a href="#section-Variables"
class="privatelink" onclick="toggle_private();"
>hide private</a>]</span></td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="lsep"></a><span class="summary-name">lsep</span> = <code title=""\n#: "">"\n#: "</code><br />
Seperator for #: entries
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="translate.storage.pypo-module.html#po_unescape_map" class="summary-name">po_unescape_map</a> = <code title="{"\\r": "\r", "\\t": "\t", '\\"': '"', '\\n': '\n', '\\\\': '\\'}">{"\\r": "\r", "\\t": "\t", '\\"': '"', '\\n'<code class="variable-ellipsis">...</code></code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="translate.storage.pypo-module.html#po_escape_map" class="summary-name">po_escape_map</a> = <code title="dict([(value, key) for(key, value) in po_unescape_map.items()])">dict([(value, key) for(key, value) in po_unesc<code class="variable-ellipsis">...</code></code>
</td>
</tr>
</table>
<p class="indent-wrapped-lines"><b>Imports:</b>
<span title="copy">copy</span>,
<span title="cStringIO">cStringIO</span>,
<span title="re">re</span>,
<span title="translate.lang.data">data</span>,
<a href="translate.misc.multistring.multistring-class.html" title="translate.misc.multistring.multistring">multistring</a>,
<a href="translate.misc.quote-module.html" title="translate.misc.quote">quote</a>,
<a href="translate.misc.textwrap-module.html" title="translate.misc.textwrap">textwrap</a>,
<a href="translate.storage.pocommon-module.html" title="translate.storage.pocommon">pocommon</a>,
<a href="translate.storage.base-module.html" title="translate.storage.base">base</a>,
<a href="translate.storage.poparser-module.html" title="translate.storage.poparser">poparser</a>,
<a href="translate.storage.pocommon-module.html#encodingToUse" title="translate.storage.pocommon.encodingToUse">encodingToUse</a>
</p><br />
<!-- ==================== FUNCTION DETAILS ==================== -->
<a name="section-FunctionDetails"></a>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td colspan="2" class="table-header">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr valign="top">
<td align="left"><span class="table-header">Function Details</span></td>
<td align="right" valign="top"
><span class="options">[<a href="#section-FunctionDetails"
class="privatelink" onclick="toggle_private();"
>hide private</a>]</span></td>
</tr>
</table>
</td>
</tr>
</table>
<a name="escapeforpo"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr valign="top"><td>
<h3 class="epydoc"><span class="sig"><span class="sig-name">escapeforpo</span>(<span class="sig-arg">line</span>)</span>
</h3>
</td><td align="right" valign="top"
><span class="codelink"><a href="translate.storage.pypo-pysrc.html#escapeforpo">source code</a></span>
</td>
</tr></table>
<p>Escapes a line for po format. assumes no occurs in the line.</p>
<dl class="fields">
<dt>Parameters:</dt>
<dd><ul class="nomargin-top">
<li><strong class="pname"><code>line</code></strong> - unescaped text</li>
</ul></dd>
</dl>
</td></tr></table>
</div>
<a name="extractpoline"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr valign="top"><td>
<h3 class="epydoc"><span class="sig"><span class="sig-name">extractpoline</span>(<span class="sig-arg">line</span>)</span>
</h3>
</td><td align="right" valign="top"
><span class="codelink"><a href="translate.storage.pypo-pysrc.html#extractpoline">source code</a></span>
</td>
</tr></table>
<p>Remove quote and unescape line from po file.</p>
<dl class="fields">
<dt>Parameters:</dt>
<dd><ul class="nomargin-top">
<li><strong class="pname"><code>line</code></strong> - a quoted line from a po file (msgid or msgstr)</li>
</ul></dd>
</dl>
</td></tr></table>
</div>
<br />
<!-- ==================== VARIABLES DETAILS ==================== -->
<a name="section-VariablesDetails"></a>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td colspan="2" class="table-header">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr valign="top">
<td align="left"><span class="table-header">Variables Details</span></td>
<td align="right" valign="top"
><span class="options">[<a href="#section-VariablesDetails"
class="privatelink" onclick="toggle_private();"
>hide private</a>]</span></td>
</tr>
</table>
</td>
</tr>
</table>
<a name="po_unescape_map"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<h3 class="epydoc">po_unescape_map</h3>
<dl class="fields">
</dl>
<dl class="fields">
<dt>Value:</dt>
<dd><table><tr><td><pre class="variable">
{"\\r": "\r", "\\t": "\t", '\\"': '"', '\\n': '\n', '\\\\': '\\'}
</pre></td></tr></table>
</dd>
</dl>
</td></tr></table>
</div>
<a name="po_escape_map"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<h3 class="epydoc">po_escape_map</h3>
<dl class="fields">
</dl>
<dl class="fields">
<dt>Value:</dt>
<dd><table><tr><td><pre class="variable">
dict([(value, key) for(key, value) in po_unescape_map.items()])
</pre></td></tr></table>
</dd>
</dl>
</td></tr></table>
</div>
<br />
<!-- ==================== NAVIGATION BAR ==================== -->
<table class="navbar" border="0" width="100%" cellpadding="0"
bgcolor="#a0c0ff" cellspacing="0">
<tr valign="middle">
<!-- Home link -->
<th> <a
href="translate-module.html">Home</a> </th>
<!-- Tree link -->
<th> <a
href="module-tree.html">Trees</a> </th>
<!-- Index link -->
<th> <a
href="identifier-index.html">Indices</a> </th>
<!-- Help link -->
<th> <a
href="help.html">Help</a> </th>
<!-- Project homepage -->
<th class="navbar" align="right" width="100%">
<table border="0" cellpadding="0" cellspacing="0">
<tr><th class="navbar" align="center"
><a class="navbar" target="_top" href="http://translate.sourceforge.net/wiki/toolkit/index">Translate Toolkit</a></th>
</tr></table></th>
</tr>
</table>
<table border="0" cellpadding="0" cellspacing="0" width="100%%">
<tr>
<td align="left" class="footer">
Generated by Epydoc 3.0.1 on Tue Apr 12 18:11:55 2011
</td>
<td align="right" class="footer">
<a target="mainFrame" href="http://epydoc.sourceforge.net"
>http://epydoc.sourceforge.net</a>
</td>
</tr>
</table>
<script type="text/javascript">
<!--
// Private objects are initially displayed (because if
// javascript is turned off then we want them to be
// visible); but by default, we want to hide them. So hide
// them unless we have a cookie that says to show them.
checkCookie();
// -->
</script>
</body>
</html>
| jagg81/translate-toolkit | translate/doc/api/translate.storage.pypo-module.html | HTML | gpl-2.0 | 18,885 |
/*
* (C) 2007-2010 Taobao Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
*
* Version: $Id$
*
* Authors:
* duolong <[email protected]>
*
*/
#ifndef TBNET_SERVERSOCKET_H_
#define TBNET_SERVERSOCKET_H_
namespace tbnet {
class ServerSocket : public Socket {
public:
/*
* ¹¹Ô캯Êý
*/
ServerSocket();
/*
* acceptÒ»¸öеÄÁ¬½Ó
*
* @return Ò»¸öSocket
*/
Socket* accept();
/*
* ´ò¿ª¼àÌý
*
* @return ÊÇ·ñ³É¹¦
*/
bool listen();
private:
int _backLog; // backlog
};
}
#endif /*SERVERSOCKET_H_*/
| mrunix/streambase | external/tb-common-utils/tbnet/src/serversocket.h | C | gpl-2.0 | 698 |
<?php
/* core/themes/classy/templates/views/views-view-grid.html.twig */
class __TwigTemplate_b1b5e6a9a8cd209497117279c69ebc6612c8c2cb7794b0f45dd07835addb061c extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = false;
$this->blocks = array(
);
}
protected function doDisplay(array $context, array $blocks = array())
{
$tags = array("set" => 28, "if" => 35, "for" => 56);
$filters = array();
$functions = array();
try {
$this->env->getExtension('Twig_Extension_Sandbox')->checkSecurity(
array('set', 'if', 'for'),
array(),
array()
);
} catch (Twig_Sandbox_SecurityError $e) {
$e->setSourceContext($this->getSourceContext());
if ($e instanceof Twig_Sandbox_SecurityNotAllowedTagError && isset($tags[$e->getTagName()])) {
$e->setTemplateLine($tags[$e->getTagName()]);
} elseif ($e instanceof Twig_Sandbox_SecurityNotAllowedFilterError && isset($filters[$e->getFilterName()])) {
$e->setTemplateLine($filters[$e->getFilterName()]);
} elseif ($e instanceof Twig_Sandbox_SecurityNotAllowedFunctionError && isset($functions[$e->getFunctionName()])) {
$e->setTemplateLine($functions[$e->getFunctionName()]);
}
throw $e;
}
// line 28
$context["classes"] = array(0 => "views-view-grid", 1 => $this->getAttribute( // line 30
(isset($context["options"]) ? $context["options"] : null), "alignment", array()), 2 => ("cols-" . $this->getAttribute( // line 31
(isset($context["options"]) ? $context["options"] : null), "columns", array())), 3 => "clearfix");
// line 35
if ($this->getAttribute((isset($context["options"]) ? $context["options"] : null), "row_class_default", array())) {
// line 36
echo " ";
// line 37
$context["row_classes"] = array(0 => "views-row", 1 => ((($this->getAttribute( // line 39
(isset($context["options"]) ? $context["options"] : null), "alignment", array()) == "horizontal")) ? ("clearfix") : ("")));
}
// line 43
if ($this->getAttribute((isset($context["options"]) ? $context["options"] : null), "col_class_default", array())) {
// line 44
echo " ";
// line 45
$context["col_classes"] = array(0 => "views-col", 1 => ((($this->getAttribute( // line 47
(isset($context["options"]) ? $context["options"] : null), "alignment", array()) == "vertical")) ? ("clearfix") : ("")));
}
// line 51
if ((isset($context["title"]) ? $context["title"] : null)) {
// line 52
echo " <h3>";
echo $this->env->getExtension('Twig_Extension_Sandbox')->ensureToStringAllowed($this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, (isset($context["title"]) ? $context["title"] : null), "html", null, true));
echo "</h3>
";
}
// line 54
echo "<div";
echo $this->env->getExtension('Twig_Extension_Sandbox')->ensureToStringAllowed($this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->getAttribute((isset($context["attributes"]) ? $context["attributes"] : null), "addClass", array(0 => (isset($context["classes"]) ? $context["classes"] : null)), "method"), "html", null, true));
echo ">
";
// line 55
if (($this->getAttribute((isset($context["options"]) ? $context["options"] : null), "alignment", array()) == "horizontal")) {
// line 56
echo " ";
$context['_parent'] = $context;
$context['_seq'] = twig_ensure_traversable((isset($context["items"]) ? $context["items"] : null));
$context['loop'] = array(
'parent' => $context['_parent'],
'index0' => 0,
'index' => 1,
'first' => true,
);
if (is_array($context['_seq']) || (is_object($context['_seq']) && $context['_seq'] instanceof Countable)) {
$length = count($context['_seq']);
$context['loop']['revindex0'] = $length - 1;
$context['loop']['revindex'] = $length;
$context['loop']['length'] = $length;
$context['loop']['last'] = 1 === $length;
}
foreach ($context['_seq'] as $context["_key"] => $context["row"]) {
// line 57
echo " <div";
echo $this->env->getExtension('Twig_Extension_Sandbox')->ensureToStringAllowed($this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->getAttribute($this->getAttribute($context["row"], "attributes", array()), "addClass", array(0 => (isset($context["row_classes"]) ? $context["row_classes"] : null), 1 => (($this->getAttribute((isset($context["options"]) ? $context["options"] : null), "row_class_default", array())) ? (("row-" . $this->getAttribute($context["loop"], "index", array()))) : (""))), "method"), "html", null, true));
echo ">
";
// line 58
$context['_parent'] = $context;
$context['_seq'] = twig_ensure_traversable($this->getAttribute($context["row"], "content", array()));
$context['loop'] = array(
'parent' => $context['_parent'],
'index0' => 0,
'index' => 1,
'first' => true,
);
if (is_array($context['_seq']) || (is_object($context['_seq']) && $context['_seq'] instanceof Countable)) {
$length = count($context['_seq']);
$context['loop']['revindex0'] = $length - 1;
$context['loop']['revindex'] = $length;
$context['loop']['length'] = $length;
$context['loop']['last'] = 1 === $length;
}
foreach ($context['_seq'] as $context["_key"] => $context["column"]) {
// line 59
echo " <div";
echo $this->env->getExtension('Twig_Extension_Sandbox')->ensureToStringAllowed($this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->getAttribute($this->getAttribute($context["column"], "attributes", array()), "addClass", array(0 => (isset($context["col_classes"]) ? $context["col_classes"] : null), 1 => (($this->getAttribute((isset($context["options"]) ? $context["options"] : null), "col_class_default", array())) ? (("col-" . $this->getAttribute($context["loop"], "index", array()))) : (""))), "method"), "html", null, true));
echo ">
";
// line 60
echo $this->env->getExtension('Twig_Extension_Sandbox')->ensureToStringAllowed($this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->getAttribute($context["column"], "content", array()), "html", null, true));
echo "
</div>
";
++$context['loop']['index0'];
++$context['loop']['index'];
$context['loop']['first'] = false;
if (isset($context['loop']['length'])) {
--$context['loop']['revindex0'];
--$context['loop']['revindex'];
$context['loop']['last'] = 0 === $context['loop']['revindex0'];
}
}
$_parent = $context['_parent'];
unset($context['_seq'], $context['_iterated'], $context['_key'], $context['column'], $context['_parent'], $context['loop']);
$context = array_intersect_key($context, $_parent) + $_parent;
// line 63
echo " </div>
";
++$context['loop']['index0'];
++$context['loop']['index'];
$context['loop']['first'] = false;
if (isset($context['loop']['length'])) {
--$context['loop']['revindex0'];
--$context['loop']['revindex'];
$context['loop']['last'] = 0 === $context['loop']['revindex0'];
}
}
$_parent = $context['_parent'];
unset($context['_seq'], $context['_iterated'], $context['_key'], $context['row'], $context['_parent'], $context['loop']);
$context = array_intersect_key($context, $_parent) + $_parent;
// line 65
echo " ";
} else {
// line 66
echo " ";
$context['_parent'] = $context;
$context['_seq'] = twig_ensure_traversable((isset($context["items"]) ? $context["items"] : null));
$context['loop'] = array(
'parent' => $context['_parent'],
'index0' => 0,
'index' => 1,
'first' => true,
);
if (is_array($context['_seq']) || (is_object($context['_seq']) && $context['_seq'] instanceof Countable)) {
$length = count($context['_seq']);
$context['loop']['revindex0'] = $length - 1;
$context['loop']['revindex'] = $length;
$context['loop']['length'] = $length;
$context['loop']['last'] = 1 === $length;
}
foreach ($context['_seq'] as $context["_key"] => $context["column"]) {
// line 67
echo " <div";
echo $this->env->getExtension('Twig_Extension_Sandbox')->ensureToStringAllowed($this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->getAttribute($this->getAttribute($context["column"], "attributes", array()), "addClass", array(0 => (isset($context["col_classes"]) ? $context["col_classes"] : null), 1 => (($this->getAttribute((isset($context["options"]) ? $context["options"] : null), "col_class_default", array())) ? (("col-" . $this->getAttribute($context["loop"], "index", array()))) : (""))), "method"), "html", null, true));
echo ">
";
// line 68
$context['_parent'] = $context;
$context['_seq'] = twig_ensure_traversable($this->getAttribute($context["column"], "content", array()));
$context['loop'] = array(
'parent' => $context['_parent'],
'index0' => 0,
'index' => 1,
'first' => true,
);
if (is_array($context['_seq']) || (is_object($context['_seq']) && $context['_seq'] instanceof Countable)) {
$length = count($context['_seq']);
$context['loop']['revindex0'] = $length - 1;
$context['loop']['revindex'] = $length;
$context['loop']['length'] = $length;
$context['loop']['last'] = 1 === $length;
}
foreach ($context['_seq'] as $context["_key"] => $context["row"]) {
// line 69
echo " <div";
echo $this->env->getExtension('Twig_Extension_Sandbox')->ensureToStringAllowed($this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->getAttribute($this->getAttribute($context["row"], "attributes", array()), "addClass", array(0 => (isset($context["row_classes"]) ? $context["row_classes"] : null), 1 => (($this->getAttribute((isset($context["options"]) ? $context["options"] : null), "row_class_default", array())) ? (("row-" . $this->getAttribute($context["loop"], "index", array()))) : (""))), "method"), "html", null, true));
echo ">
";
// line 70
echo $this->env->getExtension('Twig_Extension_Sandbox')->ensureToStringAllowed($this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->getAttribute($context["row"], "content", array()), "html", null, true));
echo "
</div>
";
++$context['loop']['index0'];
++$context['loop']['index'];
$context['loop']['first'] = false;
if (isset($context['loop']['length'])) {
--$context['loop']['revindex0'];
--$context['loop']['revindex'];
$context['loop']['last'] = 0 === $context['loop']['revindex0'];
}
}
$_parent = $context['_parent'];
unset($context['_seq'], $context['_iterated'], $context['_key'], $context['row'], $context['_parent'], $context['loop']);
$context = array_intersect_key($context, $_parent) + $_parent;
// line 73
echo " </div>
";
++$context['loop']['index0'];
++$context['loop']['index'];
$context['loop']['first'] = false;
if (isset($context['loop']['length'])) {
--$context['loop']['revindex0'];
--$context['loop']['revindex'];
$context['loop']['last'] = 0 === $context['loop']['revindex0'];
}
}
$_parent = $context['_parent'];
unset($context['_seq'], $context['_iterated'], $context['_key'], $context['column'], $context['_parent'], $context['loop']);
$context = array_intersect_key($context, $_parent) + $_parent;
// line 75
echo " ";
}
// line 76
echo "</div>
";
}
public function getTemplateName()
{
return "core/themes/classy/templates/views/views-view-grid.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 238 => 76, 235 => 75, 220 => 73, 203 => 70, 198 => 69, 181 => 68, 176 => 67, 158 => 66, 155 => 65, 140 => 63, 123 => 60, 118 => 59, 101 => 58, 96 => 57, 78 => 56, 76 => 55, 71 => 54, 65 => 52, 63 => 51, 60 => 47, 59 => 45, 57 => 44, 55 => 43, 52 => 39, 51 => 37, 49 => 36, 47 => 35, 45 => 31, 44 => 30, 43 => 28,);
}
/** @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead */
public function getSource()
{
@trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', E_USER_DEPRECATED);
return $this->getSourceContext()->getCode();
}
public function getSourceContext()
{
return new Twig_Source("{#
/**
* @file
* Theme override for views to display rows in a grid.
*
* Available variables:
* - attributes: HTML attributes for the wrapping element.
* - title: The title of this group of rows.
* - view: The view object.
* - rows: The rendered view results.
* - options: The view plugin style options.
* - row_class_default: A flag indicating whether default classes should be
* used on rows.
* - col_class_default: A flag indicating whether default classes should be
* used on columns.
* - items: A list of grid items. Each item contains a list of rows or columns.
* The order in what comes first (row or column) depends on which alignment
* type is chosen (horizontal or vertical).
* - attributes: HTML attributes for each row or column.
* - content: A list of columns or rows. Each row or column contains:
* - attributes: HTML attributes for each row or column.
* - content: The row or column contents.
*
* @see template_preprocess_views_view_grid()
*/
#}
{%
set classes = [
'views-view-grid',
options.alignment,
'cols-' ~ options.columns,
'clearfix',
]
%}
{% if options.row_class_default %}
{%
set row_classes = [
'views-row',
options.alignment == 'horizontal' ? 'clearfix',
]
%}
{% endif %}
{% if options.col_class_default %}
{%
set col_classes = [
'views-col',
options.alignment == 'vertical' ? 'clearfix',
]
%}
{% endif %}
{% if title %}
<h3>{{ title }}</h3>
{% endif %}
<div{{ attributes.addClass(classes) }}>
{% if options.alignment == 'horizontal' %}
{% for row in items %}
<div{{ row.attributes.addClass(row_classes, options.row_class_default ? 'row-' ~ loop.index) }}>
{% for column in row.content %}
<div{{ column.attributes.addClass(col_classes, options.col_class_default ? 'col-' ~ loop.index) }}>
{{ column.content }}
</div>
{% endfor %}
</div>
{% endfor %}
{% else %}
{% for column in items %}
<div{{ column.attributes.addClass(col_classes, options.col_class_default ? 'col-' ~ loop.index) }}>
{% for row in column.content %}
<div{{ row.attributes.addClass(row_classes, options.row_class_default ? 'row-' ~ loop.index) }}>
{{ row.content }}
</div>
{% endfor %}
</div>
{% endfor %}
{% endif %}
</div>
", "core/themes/classy/templates/views/views-view-grid.html.twig", "/mnt/jeet/www/local/chipc/core/themes/classy/templates/views/views-view-grid.html.twig");
}
}
| jeetpatel/commerce | sites/default/files/php/twig/59bab1c8da2f0_views-view-grid.html.twig_EPlGe06aVJoi4zUrFjATKjYCr/1EZjvIiVVOjfsiRwHdlwVHySb4hg_3u82WztPZQxA3Y.php | PHP | gpl-2.0 | 17,619 |
<?php
/**
* @version $Id: joocmavatar.php 48 2010-02-08 22:15:48Z sterob $
* @package Joo!CM
* @copyright Copyright (C) 2007-2010 Joo!BB Project. All rights reserved.
* @license GNU/GPL. Please see license.php in Joo!CM directory
* for copyright notices and details.
* Joo!CM is free software. This version may have been NOT modified.
*/
/**
* Joocm Avatar Table Class
*
* @package Joo!CM
*/
class JTableJoocmAvatar extends JTable {
/** @var int Unique id*/
var $id = null;
/** @var string */
var $avatar_file = null;
/** @var int */
var $published = null;
/** @var int */
var $checked_out = null;
/** @var datetime */
var $checked_out_time = null;
/** @var int */
var $id_user = null;
/**
* @param database A database connector object
*/
function __construct(&$db) {
parent::__construct('#__joocm_avatars', 'id', $db);
}
}
?> | srajib/share2learn | administrator/components/com_joocm/tables/joocmavatar.php | PHP | gpl-2.0 | 891 |
# This Makefile is for the VFS dumper extension to perl.
#
# It was generated automatically by MakeMaker version
# 7.0401 (Revision: 70401) from the contents of
# Makefile.PL. Don't edit this file, edit Makefile.PL instead.
#
# ANY CHANGES MADE HERE WILL BE LOST!
#
# MakeMaker ARGV: ()
#
# MakeMaker Parameters:
# BUILD_REQUIRES => { }
# CONFIGURE_REQUIRES => { }
# NAME => q[VFS dumper]
# PREREQ_PM => { }
# TEST_REQUIRES => { }
# VERSION_FROM => q[bin/vfs_dumper.pl]
# --- MakeMaker post_initialize section:
# --- MakeMaker const_config section:
# These definitions are from config.sh (via /usr/lib/i386-linux-gnu/perl/5.22/Config.pm).
# They may have been overridden via Makefile.PL or on the command line.
AR = ar
CC = i686-linux-gnu-gcc
CCCDLFLAGS = -fPIC
CCDLFLAGS = -Wl,-E
DLEXT = so
DLSRC = dl_dlopen.xs
EXE_EXT =
FULL_AR = /usr/bin/ar
LD = i686-linux-gnu-gcc
LDDLFLAGS = -shared -L/usr/local/lib -fstack-protector-strong
LDFLAGS = -fstack-protector-strong -L/usr/local/lib
LIBC = libc-2.21.so
LIB_EXT = .a
OBJ_EXT = .o
OSNAME = linux
OSVERS = 3.16.0
RANLIB = :
SITELIBEXP = /usr/local/share/perl/5.22.1
SITEARCHEXP = /usr/local/lib/i386-linux-gnu/perl/5.22.1
SO = so
VENDORARCHEXP = /usr/lib/i386-linux-gnu/perl5/5.22
VENDORLIBEXP = /usr/share/perl5
# --- MakeMaker constants section:
AR_STATIC_ARGS = cr
DIRFILESEP = /
DFSEP = $(DIRFILESEP)
NAME = VFS dumper
NAME_SYM = VFS_dumper
VERSION = 1
VERSION_MACRO = VERSION
VERSION_SYM = 1
DEFINE_VERSION = -D$(VERSION_MACRO)=\"$(VERSION)\"
XS_VERSION = 1
XS_VERSION_MACRO = XS_VERSION
XS_DEFINE_VERSION = -D$(XS_VERSION_MACRO)=\"$(XS_VERSION)\"
INST_ARCHLIB = blib/arch
INST_SCRIPT = blib/script
INST_BIN = blib/bin
INST_LIB = blib/lib
INST_MAN1DIR = blib/man1
INST_MAN3DIR = blib/man3
MAN1EXT = 1p
MAN3EXT = 3pm
INSTALLDIRS = site
INSTALL_BASE = /home/popyan/perl5
DESTDIR =
PREFIX = $(INSTALL_BASE)
INSTALLPRIVLIB = $(INSTALL_BASE)/lib/perl5
DESTINSTALLPRIVLIB = $(DESTDIR)$(INSTALLPRIVLIB)
INSTALLSITELIB = $(INSTALL_BASE)/lib/perl5
DESTINSTALLSITELIB = $(DESTDIR)$(INSTALLSITELIB)
INSTALLVENDORLIB = $(INSTALL_BASE)/lib/perl5
DESTINSTALLVENDORLIB = $(DESTDIR)$(INSTALLVENDORLIB)
INSTALLARCHLIB = $(INSTALL_BASE)/lib/perl5/i686-linux-gnu-thread-multi-64int
DESTINSTALLARCHLIB = $(DESTDIR)$(INSTALLARCHLIB)
INSTALLSITEARCH = $(INSTALL_BASE)/lib/perl5/i686-linux-gnu-thread-multi-64int
DESTINSTALLSITEARCH = $(DESTDIR)$(INSTALLSITEARCH)
INSTALLVENDORARCH = $(INSTALL_BASE)/lib/perl5/i686-linux-gnu-thread-multi-64int
DESTINSTALLVENDORARCH = $(DESTDIR)$(INSTALLVENDORARCH)
INSTALLBIN = $(INSTALL_BASE)/bin
DESTINSTALLBIN = $(DESTDIR)$(INSTALLBIN)
INSTALLSITEBIN = $(INSTALL_BASE)/bin
DESTINSTALLSITEBIN = $(DESTDIR)$(INSTALLSITEBIN)
INSTALLVENDORBIN = $(INSTALL_BASE)/bin
DESTINSTALLVENDORBIN = $(DESTDIR)$(INSTALLVENDORBIN)
INSTALLSCRIPT = $(INSTALL_BASE)/bin
DESTINSTALLSCRIPT = $(DESTDIR)$(INSTALLSCRIPT)
INSTALLSITESCRIPT = $(INSTALL_BASE)/bin
DESTINSTALLSITESCRIPT = $(DESTDIR)$(INSTALLSITESCRIPT)
INSTALLVENDORSCRIPT = $(INSTALL_BASE)/bin
DESTINSTALLVENDORSCRIPT = $(DESTDIR)$(INSTALLVENDORSCRIPT)
INSTALLMAN1DIR = $(INSTALL_BASE)/man/man1
DESTINSTALLMAN1DIR = $(DESTDIR)$(INSTALLMAN1DIR)
INSTALLSITEMAN1DIR = $(INSTALL_BASE)/man/man1
DESTINSTALLSITEMAN1DIR = $(DESTDIR)$(INSTALLSITEMAN1DIR)
INSTALLVENDORMAN1DIR = $(INSTALL_BASE)/man/man1
DESTINSTALLVENDORMAN1DIR = $(DESTDIR)$(INSTALLVENDORMAN1DIR)
INSTALLMAN3DIR = $(INSTALL_BASE)/man/man3
DESTINSTALLMAN3DIR = $(DESTDIR)$(INSTALLMAN3DIR)
INSTALLSITEMAN3DIR = $(INSTALL_BASE)/man/man3
DESTINSTALLSITEMAN3DIR = $(DESTDIR)$(INSTALLSITEMAN3DIR)
INSTALLVENDORMAN3DIR = $(INSTALL_BASE)/man/man3
DESTINSTALLVENDORMAN3DIR = $(DESTDIR)$(INSTALLVENDORMAN3DIR)
PERL_LIB = /usr/share/perl/5.22
PERL_ARCHLIB = /usr/lib/i386-linux-gnu/perl/5.22
PERL_ARCHLIBDEP = /usr/lib/i386-linux-gnu/perl/5.22
LIBPERL_A = libperl.a
FIRST_MAKEFILE = Makefile
MAKEFILE_OLD = Makefile.old
MAKE_APERL_FILE = Makefile.aperl
PERLMAINCC = $(CC)
PERL_INC = /usr/lib/i386-linux-gnu/perl/5.22/CORE
PERL_INCDEP = /usr/lib/i386-linux-gnu/perl/5.22/CORE
PERL = "/usr/bin/perl"
FULLPERL = "/usr/bin/perl"
ABSPERL = $(PERL)
PERLRUN = $(PERL)
FULLPERLRUN = $(FULLPERL)
ABSPERLRUN = $(ABSPERL)
PERLRUNINST = $(PERLRUN) "-I$(INST_ARCHLIB)" "-I$(INST_LIB)"
FULLPERLRUNINST = $(FULLPERLRUN) "-I$(INST_ARCHLIB)" "-I$(INST_LIB)"
ABSPERLRUNINST = $(ABSPERLRUN) "-I$(INST_ARCHLIB)" "-I$(INST_LIB)"
PERL_CORE = 0
PERM_DIR = 755
PERM_RW = 644
PERM_RWX = 755
MAKEMAKER = /usr/share/perl/5.22/ExtUtils/MakeMaker.pm
MM_VERSION = 7.0401
MM_REVISION = 70401
# FULLEXT = Pathname for extension directory (eg Foo/Bar/Oracle).
# BASEEXT = Basename part of FULLEXT. May be just equal FULLEXT. (eg Oracle)
# PARENT_NAME = NAME without BASEEXT and no trailing :: (eg Foo::Bar)
# DLBASE = Basename part of dynamic library. May be just equal BASEEXT.
MAKE = make
FULLEXT = VFS dumper
BASEEXT = dumper
PARENT_NAME =
DLBASE = $(BASEEXT)
VERSION_FROM = bin/vfs_dumper.pl
OBJECT =
LDFROM = $(OBJECT)
LINKTYPE = dynamic
BOOTDEP =
# Handy lists of source code files:
XS_FILES =
C_FILES =
O_FILES =
H_FILES =
MAN1PODS =
MAN3PODS = lib/VFS.pm
# Where is the Config information that we are using/depend on
CONFIGDEP = $(PERL_ARCHLIBDEP)$(DFSEP)Config.pm $(PERL_INCDEP)$(DFSEP)config.h
# Where to build things
INST_LIBDIR = $(INST_LIB)
INST_ARCHLIBDIR = $(INST_ARCHLIB)
INST_AUTODIR = $(INST_LIB)/auto/$(FULLEXT)
INST_ARCHAUTODIR = $(INST_ARCHLIB)/auto/$(FULLEXT)
INST_STATIC =
INST_DYNAMIC =
INST_BOOT =
# Extra linker info
EXPORT_LIST =
PERL_ARCHIVE =
PERL_ARCHIVEDEP =
PERL_ARCHIVE_AFTER =
TO_INST_PM = lib/VFS.pm
PM_TO_BLIB = lib/VFS.pm \
blib/lib/VFS.pm
# --- MakeMaker platform_constants section:
MM_Unix_VERSION = 7.0401
PERL_MALLOC_DEF = -DPERL_EXTMALLOC_DEF -Dmalloc=Perl_malloc -Dfree=Perl_mfree -Drealloc=Perl_realloc -Dcalloc=Perl_calloc
# --- MakeMaker tool_autosplit section:
# Usage: $(AUTOSPLITFILE) FileToSplit AutoDirToSplitInto
AUTOSPLITFILE = $(ABSPERLRUN) -e 'use AutoSplit; autosplit($$$$ARGV[0], $$$$ARGV[1], 0, 1, 1)' --
# --- MakeMaker tool_xsubpp section:
# --- MakeMaker tools_other section:
SHELL = /bin/sh
CHMOD = chmod
CP = cp
MV = mv
NOOP = $(TRUE)
NOECHO = @
RM_F = rm -f
RM_RF = rm -rf
TEST_F = test -f
TOUCH = touch
UMASK_NULL = umask 0
DEV_NULL = > /dev/null 2>&1
MKPATH = $(ABSPERLRUN) -MExtUtils::Command -e 'mkpath' --
EQUALIZE_TIMESTAMP = $(ABSPERLRUN) -MExtUtils::Command -e 'eqtime' --
FALSE = false
TRUE = true
ECHO = echo
ECHO_N = echo -n
UNINST = 0
VERBINST = 0
MOD_INSTALL = $(ABSPERLRUN) -MExtUtils::Install -e 'install([ from_to => {@ARGV}, verbose => '\''$(VERBINST)'\'', uninstall_shadows => '\''$(UNINST)'\'', dir_mode => '\''$(PERM_DIR)'\'' ]);' --
DOC_INSTALL = $(ABSPERLRUN) -MExtUtils::Command::MM -e 'perllocal_install' --
UNINSTALL = $(ABSPERLRUN) -MExtUtils::Command::MM -e 'uninstall' --
WARN_IF_OLD_PACKLIST = $(ABSPERLRUN) -MExtUtils::Command::MM -e 'warn_if_old_packlist' --
MACROSTART =
MACROEND =
USEMAKEFILE = -f
FIXIN = $(ABSPERLRUN) -MExtUtils::MY -e 'MY->fixin(shift)' --
CP_NONEMPTY = $(ABSPERLRUN) -MExtUtils::Command::MM -e 'cp_nonempty' --
# --- MakeMaker makemakerdflt section:
makemakerdflt : all
$(NOECHO) $(NOOP)
# --- MakeMaker dist section:
TAR = tar
TARFLAGS = cvf
ZIP = zip
ZIPFLAGS = -r
COMPRESS = gzip --best
SUFFIX = .gz
SHAR = shar
PREOP = $(NOECHO) $(NOOP)
POSTOP = $(NOECHO) $(NOOP)
TO_UNIX = $(NOECHO) $(NOOP)
CI = ci -u
RCS_LABEL = rcs -Nv$(VERSION_SYM): -q
DIST_CP = best
DIST_DEFAULT = tardist
DISTNAME = VFS dumper
DISTVNAME = VFS dumper-1
# --- MakeMaker macro section:
# --- MakeMaker depend section:
# --- MakeMaker cflags section:
# --- MakeMaker const_loadlibs section:
# --- MakeMaker const_cccmd section:
# --- MakeMaker post_constants section:
# --- MakeMaker pasthru section:
PASTHRU = LIBPERL_A="$(LIBPERL_A)"\
LINKTYPE="$(LINKTYPE)"\
LD="$(LD)"\
PREFIX="$(PREFIX)"\
INSTALL_BASE="$(INSTALL_BASE)"
# --- MakeMaker special_targets section:
.SUFFIXES : .xs .c .C .cpp .i .s .cxx .cc $(OBJ_EXT)
.PHONY: all config static dynamic test linkext manifest blibdirs clean realclean disttest distdir
# --- MakeMaker c_o section:
# --- MakeMaker xs_c section:
# --- MakeMaker xs_o section:
# --- MakeMaker top_targets section:
all :: pure_all manifypods
$(NOECHO) $(NOOP)
pure_all :: config pm_to_blib subdirs linkext
$(NOECHO) $(NOOP)
subdirs :: $(MYEXTLIB)
$(NOECHO) $(NOOP)
config :: $(FIRST_MAKEFILE) blibdirs
$(NOECHO) $(NOOP)
help :
perldoc ExtUtils::MakeMaker
# --- MakeMaker blibdirs section:
blibdirs : $(INST_LIBDIR)$(DFSEP).exists $(INST_ARCHLIB)$(DFSEP).exists $(INST_AUTODIR)$(DFSEP).exists $(INST_ARCHAUTODIR)$(DFSEP).exists $(INST_BIN)$(DFSEP).exists $(INST_SCRIPT)$(DFSEP).exists $(INST_MAN1DIR)$(DFSEP).exists $(INST_MAN3DIR)$(DFSEP).exists
$(NOECHO) $(NOOP)
# Backwards compat with 6.18 through 6.25
blibdirs.ts : blibdirs
$(NOECHO) $(NOOP)
$(INST_LIBDIR)$(DFSEP).exists :: Makefile.PL
$(NOECHO) $(MKPATH) $(INST_LIBDIR)
$(NOECHO) $(CHMOD) $(PERM_DIR) $(INST_LIBDIR)
$(NOECHO) $(TOUCH) $(INST_LIBDIR)$(DFSEP).exists
$(INST_ARCHLIB)$(DFSEP).exists :: Makefile.PL
$(NOECHO) $(MKPATH) $(INST_ARCHLIB)
$(NOECHO) $(CHMOD) $(PERM_DIR) $(INST_ARCHLIB)
$(NOECHO) $(TOUCH) $(INST_ARCHLIB)$(DFSEP).exists
$(INST_AUTODIR)$(DFSEP).exists :: Makefile.PL
$(NOECHO) $(MKPATH) $(INST_AUTODIR)
$(NOECHO) $(CHMOD) $(PERM_DIR) $(INST_AUTODIR)
$(NOECHO) $(TOUCH) $(INST_AUTODIR)$(DFSEP).exists
$(INST_ARCHAUTODIR)$(DFSEP).exists :: Makefile.PL
$(NOECHO) $(MKPATH) $(INST_ARCHAUTODIR)
$(NOECHO) $(CHMOD) $(PERM_DIR) $(INST_ARCHAUTODIR)
$(NOECHO) $(TOUCH) $(INST_ARCHAUTODIR)$(DFSEP).exists
$(INST_BIN)$(DFSEP).exists :: Makefile.PL
$(NOECHO) $(MKPATH) $(INST_BIN)
$(NOECHO) $(CHMOD) $(PERM_DIR) $(INST_BIN)
$(NOECHO) $(TOUCH) $(INST_BIN)$(DFSEP).exists
$(INST_SCRIPT)$(DFSEP).exists :: Makefile.PL
$(NOECHO) $(MKPATH) $(INST_SCRIPT)
$(NOECHO) $(CHMOD) $(PERM_DIR) $(INST_SCRIPT)
$(NOECHO) $(TOUCH) $(INST_SCRIPT)$(DFSEP).exists
$(INST_MAN1DIR)$(DFSEP).exists :: Makefile.PL
$(NOECHO) $(MKPATH) $(INST_MAN1DIR)
$(NOECHO) $(CHMOD) $(PERM_DIR) $(INST_MAN1DIR)
$(NOECHO) $(TOUCH) $(INST_MAN1DIR)$(DFSEP).exists
$(INST_MAN3DIR)$(DFSEP).exists :: Makefile.PL
$(NOECHO) $(MKPATH) $(INST_MAN3DIR)
$(NOECHO) $(CHMOD) $(PERM_DIR) $(INST_MAN3DIR)
$(NOECHO) $(TOUCH) $(INST_MAN3DIR)$(DFSEP).exists
# --- MakeMaker linkext section:
linkext :: $(LINKTYPE)
$(NOECHO) $(NOOP)
# --- MakeMaker dlsyms section:
# --- MakeMaker dynamic_bs section:
BOOTSTRAP =
# --- MakeMaker dynamic section:
dynamic :: $(FIRST_MAKEFILE) $(BOOTSTRAP) $(INST_DYNAMIC)
$(NOECHO) $(NOOP)
# --- MakeMaker dynamic_lib section:
# --- MakeMaker static section:
## $(INST_PM) has been moved to the all: target.
## It remains here for awhile to allow for old usage: "make static"
static :: $(FIRST_MAKEFILE) $(INST_STATIC)
$(NOECHO) $(NOOP)
# --- MakeMaker static_lib section:
# --- MakeMaker manifypods section:
POD2MAN_EXE = $(PERLRUN) "-MExtUtils::Command::MM" -e pod2man "--"
POD2MAN = $(POD2MAN_EXE)
manifypods : pure_all \
lib/VFS.pm
$(NOECHO) $(POD2MAN) --section=$(MAN3EXT) --perm_rw=$(PERM_RW) -u \
lib/VFS.pm $(INST_MAN3DIR)/VFS.$(MAN3EXT)
# --- MakeMaker processPL section:
# --- MakeMaker installbin section:
# --- MakeMaker subdirs section:
# none
# --- MakeMaker clean_subdirs section:
clean_subdirs :
$(NOECHO) $(NOOP)
# --- MakeMaker clean section:
# Delete temporary files but do not touch installed files. We don't delete
# the Makefile here so a later make realclean still has a makefile to use.
clean :: clean_subdirs
- $(RM_F) \
$(BASEEXT).bso $(BASEEXT).def \
$(BASEEXT).exp $(BASEEXT).x \
$(BOOTSTRAP) $(INST_ARCHAUTODIR)/extralibs.all \
$(INST_ARCHAUTODIR)/extralibs.ld $(MAKE_APERL_FILE) \
*$(LIB_EXT) *$(OBJ_EXT) \
*perl.core MYMETA.json \
MYMETA.yml blibdirs.ts \
core core.*perl.*.? \
core.[0-9] core.[0-9][0-9] \
core.[0-9][0-9][0-9] core.[0-9][0-9][0-9][0-9] \
core.[0-9][0-9][0-9][0-9][0-9] lib$(BASEEXT).def \
mon.out perl \
perl$(EXE_EXT) perl.exe \
perlmain.c pm_to_blib \
pm_to_blib.ts so_locations \
tmon.out
- $(RM_RF) \
blib
$(NOECHO) $(RM_F) $(MAKEFILE_OLD)
- $(MV) $(FIRST_MAKEFILE) $(MAKEFILE_OLD) $(DEV_NULL)
# --- MakeMaker realclean_subdirs section:
realclean_subdirs :
$(NOECHO) $(NOOP)
# --- MakeMaker realclean section:
# Delete temporary files (via clean) and also delete dist files
realclean purge :: clean realclean_subdirs
- $(RM_F) \
$(FIRST_MAKEFILE) $(MAKEFILE_OLD)
- $(RM_RF) \
$(DISTVNAME)
# --- MakeMaker metafile section:
metafile : create_distdir
$(NOECHO) $(ECHO) Generating META.yml
$(NOECHO) $(ECHO) '---' > META_new.yml
$(NOECHO) $(ECHO) 'abstract: unknown' >> META_new.yml
$(NOECHO) $(ECHO) 'author:' >> META_new.yml
$(NOECHO) $(ECHO) ' - unknown' >> META_new.yml
$(NOECHO) $(ECHO) 'build_requires:' >> META_new.yml
$(NOECHO) $(ECHO) ' ExtUtils::MakeMaker: '\''0'\''' >> META_new.yml
$(NOECHO) $(ECHO) 'configure_requires:' >> META_new.yml
$(NOECHO) $(ECHO) ' ExtUtils::MakeMaker: '\''0'\''' >> META_new.yml
$(NOECHO) $(ECHO) 'dynamic_config: 1' >> META_new.yml
$(NOECHO) $(ECHO) 'generated_by: '\''ExtUtils::MakeMaker version 7.0401, CPAN::Meta::Converter version 2.150001'\''' >> META_new.yml
$(NOECHO) $(ECHO) 'license: unknown' >> META_new.yml
$(NOECHO) $(ECHO) 'meta-spec:' >> META_new.yml
$(NOECHO) $(ECHO) ' url: http://module-build.sourceforge.net/META-spec-v1.4.html' >> META_new.yml
$(NOECHO) $(ECHO) ' version: '\''1.4'\''' >> META_new.yml
$(NOECHO) $(ECHO) 'name: '\''VFS dumper'\''' >> META_new.yml
$(NOECHO) $(ECHO) 'no_index:' >> META_new.yml
$(NOECHO) $(ECHO) ' directory:' >> META_new.yml
$(NOECHO) $(ECHO) ' - t' >> META_new.yml
$(NOECHO) $(ECHO) ' - inc' >> META_new.yml
$(NOECHO) $(ECHO) 'requires: {}' >> META_new.yml
$(NOECHO) $(ECHO) 'version: 1' >> META_new.yml
-$(NOECHO) $(MV) META_new.yml $(DISTVNAME)/META.yml
$(NOECHO) $(ECHO) Generating META.json
$(NOECHO) $(ECHO) '{' > META_new.json
$(NOECHO) $(ECHO) ' "abstract" : "unknown",' >> META_new.json
$(NOECHO) $(ECHO) ' "author" : [' >> META_new.json
$(NOECHO) $(ECHO) ' "unknown"' >> META_new.json
$(NOECHO) $(ECHO) ' ],' >> META_new.json
$(NOECHO) $(ECHO) ' "dynamic_config" : 1,' >> META_new.json
$(NOECHO) $(ECHO) ' "generated_by" : "ExtUtils::MakeMaker version 7.0401, CPAN::Meta::Converter version 2.150001",' >> META_new.json
$(NOECHO) $(ECHO) ' "license" : [' >> META_new.json
$(NOECHO) $(ECHO) ' "unknown"' >> META_new.json
$(NOECHO) $(ECHO) ' ],' >> META_new.json
$(NOECHO) $(ECHO) ' "meta-spec" : {' >> META_new.json
$(NOECHO) $(ECHO) ' "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec",' >> META_new.json
$(NOECHO) $(ECHO) ' "version" : "2"' >> META_new.json
$(NOECHO) $(ECHO) ' },' >> META_new.json
$(NOECHO) $(ECHO) ' "name" : "VFS dumper",' >> META_new.json
$(NOECHO) $(ECHO) ' "no_index" : {' >> META_new.json
$(NOECHO) $(ECHO) ' "directory" : [' >> META_new.json
$(NOECHO) $(ECHO) ' "t",' >> META_new.json
$(NOECHO) $(ECHO) ' "inc"' >> META_new.json
$(NOECHO) $(ECHO) ' ]' >> META_new.json
$(NOECHO) $(ECHO) ' },' >> META_new.json
$(NOECHO) $(ECHO) ' "prereqs" : {' >> META_new.json
$(NOECHO) $(ECHO) ' "build" : {' >> META_new.json
$(NOECHO) $(ECHO) ' "requires" : {' >> META_new.json
$(NOECHO) $(ECHO) ' "ExtUtils::MakeMaker" : "0"' >> META_new.json
$(NOECHO) $(ECHO) ' }' >> META_new.json
$(NOECHO) $(ECHO) ' },' >> META_new.json
$(NOECHO) $(ECHO) ' "configure" : {' >> META_new.json
$(NOECHO) $(ECHO) ' "requires" : {' >> META_new.json
$(NOECHO) $(ECHO) ' "ExtUtils::MakeMaker" : "0"' >> META_new.json
$(NOECHO) $(ECHO) ' }' >> META_new.json
$(NOECHO) $(ECHO) ' },' >> META_new.json
$(NOECHO) $(ECHO) ' "runtime" : {' >> META_new.json
$(NOECHO) $(ECHO) ' "requires" : {}' >> META_new.json
$(NOECHO) $(ECHO) ' }' >> META_new.json
$(NOECHO) $(ECHO) ' },' >> META_new.json
$(NOECHO) $(ECHO) ' "release_status" : "stable",' >> META_new.json
$(NOECHO) $(ECHO) ' "version" : 1' >> META_new.json
$(NOECHO) $(ECHO) '}' >> META_new.json
-$(NOECHO) $(MV) META_new.json $(DISTVNAME)/META.json
# --- MakeMaker signature section:
signature :
cpansign -s
# --- MakeMaker dist_basics section:
distclean :: realclean distcheck
$(NOECHO) $(NOOP)
distcheck :
$(PERLRUN) "-MExtUtils::Manifest=fullcheck" -e fullcheck
skipcheck :
$(PERLRUN) "-MExtUtils::Manifest=skipcheck" -e skipcheck
manifest :
$(PERLRUN) "-MExtUtils::Manifest=mkmanifest" -e mkmanifest
veryclean : realclean
$(RM_F) *~ */*~ *.orig */*.orig *.bak */*.bak *.old */*.old
# --- MakeMaker dist_core section:
dist : $(DIST_DEFAULT) $(FIRST_MAKEFILE)
$(NOECHO) $(ABSPERLRUN) -l -e 'print '\''Warning: Makefile possibly out of date with $(VERSION_FROM)'\''' \
-e ' if -e '\''$(VERSION_FROM)'\'' and -M '\''$(VERSION_FROM)'\'' < -M '\''$(FIRST_MAKEFILE)'\'';' --
tardist : $(DISTVNAME).tar$(SUFFIX)
$(NOECHO) $(NOOP)
uutardist : $(DISTVNAME).tar$(SUFFIX)
uuencode $(DISTVNAME).tar$(SUFFIX) $(DISTVNAME).tar$(SUFFIX) > $(DISTVNAME).tar$(SUFFIX)_uu
$(NOECHO) $(ECHO) 'Created $(DISTVNAME).tar$(SUFFIX)_uu'
$(DISTVNAME).tar$(SUFFIX) : distdir
$(PREOP)
$(TO_UNIX)
$(TAR) $(TARFLAGS) $(DISTVNAME).tar $(DISTVNAME)
$(RM_RF) $(DISTVNAME)
$(COMPRESS) $(DISTVNAME).tar
$(NOECHO) $(ECHO) 'Created $(DISTVNAME).tar$(SUFFIX)'
$(POSTOP)
zipdist : $(DISTVNAME).zip
$(NOECHO) $(NOOP)
$(DISTVNAME).zip : distdir
$(PREOP)
$(ZIP) $(ZIPFLAGS) $(DISTVNAME).zip $(DISTVNAME)
$(RM_RF) $(DISTVNAME)
$(NOECHO) $(ECHO) 'Created $(DISTVNAME).zip'
$(POSTOP)
shdist : distdir
$(PREOP)
$(SHAR) $(DISTVNAME) > $(DISTVNAME).shar
$(RM_RF) $(DISTVNAME)
$(NOECHO) $(ECHO) 'Created $(DISTVNAME).shar'
$(POSTOP)
# --- MakeMaker distdir section:
create_distdir :
$(RM_RF) $(DISTVNAME)
$(PERLRUN) "-MExtUtils::Manifest=manicopy,maniread" \
-e "manicopy(maniread(),'$(DISTVNAME)', '$(DIST_CP)');"
distdir : create_distdir distmeta
$(NOECHO) $(NOOP)
# --- MakeMaker dist_test section:
disttest : distdir
cd $(DISTVNAME) && $(ABSPERLRUN) Makefile.PL
cd $(DISTVNAME) && $(MAKE) $(PASTHRU)
cd $(DISTVNAME) && $(MAKE) test $(PASTHRU)
# --- MakeMaker dist_ci section:
ci :
$(PERLRUN) "-MExtUtils::Manifest=maniread" \
-e "@all = keys %{ maniread() };" \
-e "print(qq{Executing $(CI) @all\n}); system(qq{$(CI) @all});" \
-e "print(qq{Executing $(RCS_LABEL) ...\n}); system(qq{$(RCS_LABEL) @all});"
# --- MakeMaker distmeta section:
distmeta : create_distdir metafile
$(NOECHO) cd $(DISTVNAME) && $(ABSPERLRUN) -MExtUtils::Manifest=maniadd -e 'exit unless -e q{META.yml};' \
-e 'eval { maniadd({q{META.yml} => q{Module YAML meta-data (added by MakeMaker)}}) }' \
-e ' or print "Could not add META.yml to MANIFEST: $$$${'\''@'\''}\n"' --
$(NOECHO) cd $(DISTVNAME) && $(ABSPERLRUN) -MExtUtils::Manifest=maniadd -e 'exit unless -f q{META.json};' \
-e 'eval { maniadd({q{META.json} => q{Module JSON meta-data (added by MakeMaker)}}) }' \
-e ' or print "Could not add META.json to MANIFEST: $$$${'\''@'\''}\n"' --
# --- MakeMaker distsignature section:
distsignature : create_distdir
$(NOECHO) cd $(DISTVNAME) && $(ABSPERLRUN) -MExtUtils::Manifest=maniadd -e 'eval { maniadd({q{SIGNATURE} => q{Public-key signature (added by MakeMaker)}}) }' \
-e ' or print "Could not add SIGNATURE to MANIFEST: $$$${'\''@'\''}\n"' --
$(NOECHO) cd $(DISTVNAME) && $(TOUCH) SIGNATURE
cd $(DISTVNAME) && cpansign -s
# --- MakeMaker install section:
install :: pure_install doc_install
$(NOECHO) $(NOOP)
install_perl :: pure_perl_install doc_perl_install
$(NOECHO) $(NOOP)
install_site :: pure_site_install doc_site_install
$(NOECHO) $(NOOP)
install_vendor :: pure_vendor_install doc_vendor_install
$(NOECHO) $(NOOP)
pure_install :: pure_$(INSTALLDIRS)_install
$(NOECHO) $(NOOP)
doc_install :: doc_$(INSTALLDIRS)_install
$(NOECHO) $(NOOP)
pure__install : pure_site_install
$(NOECHO) $(ECHO) INSTALLDIRS not defined, defaulting to INSTALLDIRS=site
doc__install : doc_site_install
$(NOECHO) $(ECHO) INSTALLDIRS not defined, defaulting to INSTALLDIRS=site
pure_perl_install :: all
$(NOECHO) umask 022; $(MOD_INSTALL) \
"$(INST_LIB)" "$(DESTINSTALLPRIVLIB)" \
"$(INST_ARCHLIB)" "$(DESTINSTALLARCHLIB)" \
"$(INST_BIN)" "$(DESTINSTALLBIN)" \
"$(INST_SCRIPT)" "$(DESTINSTALLSCRIPT)" \
"$(INST_MAN1DIR)" "$(DESTINSTALLMAN1DIR)" \
"$(INST_MAN3DIR)" "$(DESTINSTALLMAN3DIR)"
$(NOECHO) $(WARN_IF_OLD_PACKLIST) \
"$(SITEARCHEXP)/auto/$(FULLEXT)"
pure_site_install :: all
$(NOECHO) umask 02; $(MOD_INSTALL) \
read "$(SITEARCHEXP)/auto/$(FULLEXT)/.packlist" \
write "$(DESTINSTALLSITEARCH)/auto/$(FULLEXT)/.packlist" \
"$(INST_LIB)" "$(DESTINSTALLSITELIB)" \
"$(INST_ARCHLIB)" "$(DESTINSTALLSITEARCH)" \
"$(INST_BIN)" "$(DESTINSTALLSITEBIN)" \
"$(INST_SCRIPT)" "$(DESTINSTALLSITESCRIPT)" \
"$(INST_MAN1DIR)" "$(DESTINSTALLSITEMAN1DIR)" \
"$(INST_MAN3DIR)" "$(DESTINSTALLSITEMAN3DIR)"
$(NOECHO) $(WARN_IF_OLD_PACKLIST) \
"$(PERL_ARCHLIB)/auto/$(FULLEXT)"
pure_vendor_install :: all
$(NOECHO) umask 022; $(MOD_INSTALL) \
"$(INST_LIB)" "$(DESTINSTALLVENDORLIB)" \
"$(INST_ARCHLIB)" "$(DESTINSTALLVENDORARCH)" \
"$(INST_BIN)" "$(DESTINSTALLVENDORBIN)" \
"$(INST_SCRIPT)" "$(DESTINSTALLVENDORSCRIPT)" \
"$(INST_MAN1DIR)" "$(DESTINSTALLVENDORMAN1DIR)" \
"$(INST_MAN3DIR)" "$(DESTINSTALLVENDORMAN3DIR)"
doc_perl_install :: all
doc_site_install :: all
$(NOECHO) $(ECHO) Appending installation info to "$(DESTINSTALLSITEARCH)/perllocal.pod"
-$(NOECHO) umask 02; $(MKPATH) "$(DESTINSTALLSITEARCH)"
-$(NOECHO) umask 02; $(DOC_INSTALL) \
"Module" "$(NAME)" \
"installed into" $(INSTALLSITELIB) \
LINKTYPE "$(LINKTYPE)" \
VERSION "$(VERSION)" \
EXE_FILES "$(EXE_FILES)" \
>> "$(DESTINSTALLSITEARCH)/perllocal.pod"
doc_vendor_install :: all
uninstall :: uninstall_from_$(INSTALLDIRS)dirs
$(NOECHO) $(NOOP)
uninstall_from_perldirs ::
uninstall_from_sitedirs ::
$(NOECHO) $(UNINSTALL) "$(SITEARCHEXP)/auto/$(FULLEXT)/.packlist"
uninstall_from_vendordirs ::
# --- MakeMaker force section:
# Phony target to force checking subdirectories.
FORCE :
$(NOECHO) $(NOOP)
# --- MakeMaker perldepend section:
# --- MakeMaker makefile section:
# We take a very conservative approach here, but it's worth it.
# We move Makefile to Makefile.old here to avoid gnu make looping.
$(FIRST_MAKEFILE) : Makefile.PL $(CONFIGDEP)
$(NOECHO) $(ECHO) "Makefile out-of-date with respect to $?"
$(NOECHO) $(ECHO) "Cleaning current config before rebuilding Makefile..."
-$(NOECHO) $(RM_F) $(MAKEFILE_OLD)
-$(NOECHO) $(MV) $(FIRST_MAKEFILE) $(MAKEFILE_OLD)
- $(MAKE) $(USEMAKEFILE) $(MAKEFILE_OLD) clean $(DEV_NULL)
$(PERLRUN) Makefile.PL
$(NOECHO) $(ECHO) "==> Your Makefile has been rebuilt. <=="
$(NOECHO) $(ECHO) "==> Please rerun the $(MAKE) command. <=="
$(FALSE)
# --- MakeMaker staticmake section:
# --- MakeMaker makeaperl section ---
MAP_TARGET = perl
FULLPERL = "/usr/bin/perl"
$(MAP_TARGET) :: static $(MAKE_APERL_FILE)
$(MAKE) $(USEMAKEFILE) $(MAKE_APERL_FILE) $@
$(MAKE_APERL_FILE) : $(FIRST_MAKEFILE) pm_to_blib
$(NOECHO) $(ECHO) Writing \"$(MAKE_APERL_FILE)\" for this $(MAP_TARGET)
$(NOECHO) $(PERLRUNINST) \
Makefile.PL DIR="" \
MAKEFILE=$(MAKE_APERL_FILE) LINKTYPE=static \
MAKEAPERL=1 NORECURS=1 CCCDLFLAGS=
# --- MakeMaker test section:
TEST_VERBOSE=0
TEST_TYPE=test_$(LINKTYPE)
TEST_FILE = test.pl
TEST_FILES = t/*.t
TESTDB_SW = -d
testdb :: testdb_$(LINKTYPE)
test :: $(TEST_TYPE) subdirs-test
subdirs-test ::
$(NOECHO) $(NOOP)
test_dynamic :: pure_all
PERL_DL_NONLAZY=1 $(FULLPERLRUN) "-MExtUtils::Command::MM" "-MTest::Harness" "-e" "undef *Test::Harness::Switches; test_harness($(TEST_VERBOSE), '$(INST_LIB)', '$(INST_ARCHLIB)')" $(TEST_FILES)
testdb_dynamic :: pure_all
PERL_DL_NONLAZY=1 $(FULLPERLRUN) $(TESTDB_SW) "-I$(INST_LIB)" "-I$(INST_ARCHLIB)" $(TEST_FILE)
test_ : test_dynamic
test_static :: test_dynamic
testdb_static :: testdb_dynamic
# --- MakeMaker ppd section:
# Creates a PPD (Perl Package Description) for a binary distribution.
ppd :
$(NOECHO) $(ECHO) '<SOFTPKG NAME="$(DISTNAME)" VERSION="$(VERSION)">' > $(DISTNAME).ppd
$(NOECHO) $(ECHO) ' <ABSTRACT></ABSTRACT>' >> $(DISTNAME).ppd
$(NOECHO) $(ECHO) ' <AUTHOR></AUTHOR>' >> $(DISTNAME).ppd
$(NOECHO) $(ECHO) ' <IMPLEMENTATION>' >> $(DISTNAME).ppd
$(NOECHO) $(ECHO) ' <ARCHITECTURE NAME="i686-linux-gnu-thread-multi-64int-5.22" />' >> $(DISTNAME).ppd
$(NOECHO) $(ECHO) ' <CODEBASE HREF="" />' >> $(DISTNAME).ppd
$(NOECHO) $(ECHO) ' </IMPLEMENTATION>' >> $(DISTNAME).ppd
$(NOECHO) $(ECHO) '</SOFTPKG>' >> $(DISTNAME).ppd
# --- MakeMaker pm_to_blib section:
pm_to_blib : $(FIRST_MAKEFILE) $(TO_INST_PM)
$(NOECHO) $(ABSPERLRUN) -MExtUtils::Install -e 'pm_to_blib({@ARGV}, '\''$(INST_LIB)/auto'\'', q[$(PM_FILTER)], '\''$(PERM_DIR)'\'')' -- \
lib/VFS.pm blib/lib/VFS.pm
$(NOECHO) $(TOUCH) pm_to_blib
# --- MakeMaker selfdocument section:
# --- MakeMaker postamble section:
# End.
| Kwisats/JAH | homeworks/vfs_dumper/Makefile | Makefile | gpl-2.0 | 25,348 |
package org.ljc.adoptojdk.class_name;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class ResolveSimpleNameClassName {
private Collection<String> packages = null;
public Collection<String> getPackages() {
Set<String> returnPackages = new HashSet<String>();
for (Package aPackage : Package.getPackages()) {
returnPackages.add(aPackage.getName());
}
return returnPackages;
}
public List<String> getFullyQualifiedNames(String simpleName) {
if (this.packages == null) {
this.packages = getPackages();
}
List<String> fqns = new ArrayList<String>();
for (String aPackage : packages) {
try {
String fqn = aPackage + "." + simpleName;
Class.forName(fqn);
fqns.add(fqn);
} catch (Exception e) {
// Ignore
}
}
return fqns;
}
}
| neomatrix369/OpenJDKProductivityTool | src/main/java/org/ljc/adoptojdk/class_name/ResolveSimpleNameClassName.java | Java | gpl-2.0 | 1,001 |
/*!
* Bootstrap v3.2.0 (http://getbootstrap.com)
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
*/
/*! normalize.css v3.0.1 | MIT License | git.io/normalize */
html {
font-family: sans-serif;
-webkit-text-size-adjust: 100%;
-ms-text-size-adjust: 100%;
}
body {
margin: 0;
}
article,
aside,
details,
figcaption,
figure,
footer,
header,
hgroup,
main,
nav,
section,
summary {
display: block;
}
audio,
canvas,
progress,
video {
display: inline-block;
vertical-align: baseline;
}
audio:not([controls]) {
display: none;
height: 0;
}
[hidden],
template {
display: none;
}
a {
background: transparent;
}
a:active,
a:hover {
outline: 0;
}
abbr[title] {
border-bottom: 1px dotted;
}
b,
strong {
font-weight: bold;
}
dfn {
font-style: italic;
}
h1 {
margin: .67em 0;
font-size: 2em;
}
mark {
color: #000;
background: #ff0;
}
small {
font-size: 80%;
}
sub,
sup {
position: relative;
font-size: 75%;
line-height: 0;
vertical-align: baseline;
}
sup {
top: -.5em;
}
sub {
bottom: -.25em;
}
img {
border: 0;
}
svg:not(:root) {
overflow: hidden;
}
figure {
margin: 1em 40px;
}
hr {
height: 0;
-webkit-box-sizing: content-box;
-moz-box-sizing: content-box;
box-sizing: content-box;
}
pre {
overflow: auto;
}
code,
kbd,
pre,
samp {
font-family: monospace, monospace;
font-size: 1em;
}
button,
input,
optgroup,
select,
textarea {
margin: 0;
font: inherit;
color: inherit;
}
button {
overflow: visible;
}
button,
select {
text-transform: none;
}
button,
html input[type="button"],
input[type="reset"],
input[type="submit"] {
-webkit-appearance: button;
cursor: pointer;
}
button[disabled],
html input[disabled] {
cursor: default;
}
button::-moz-focus-inner,
input::-moz-focus-inner {
padding: 0;
border: 0;
}
input {
line-height: normal;
}
input[type="checkbox"],
input[type="radio"] {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
padding: 0;
}
input[type="number"]::-webkit-inner-spin-button,
input[type="number"]::-webkit-outer-spin-button {
height: auto;
}
input[type="search"] {
-webkit-box-sizing: content-box;
-moz-box-sizing: content-box;
box-sizing: content-box;
-webkit-appearance: textfield;
}
input[type="search"]::-webkit-search-cancel-button,
input[type="search"]::-webkit-search-decoration {
-webkit-appearance: none;
}
fieldset {
padding: .35em .625em .75em;
margin: 0 2px;
border: 1px solid #c0c0c0;
}
legend {
padding: 0;
border: 0;
}
textarea {
overflow: auto;
}
optgroup {
font-weight: bold;
}
table {
border-spacing: 0;
border-collapse: collapse;
}
td,
th {
padding: 0;
}
@media print {
* {
color: #000 !important;
text-shadow: none !important;
background: transparent !important;
-webkit-box-shadow: none !important;
box-shadow: none !important;
}
a,
a:visited {
text-decoration: underline;
}
a[href]:after {
content: " (" attr(href) ")";
}
abbr[title]:after {
content: " (" attr(title) ")";
}
a[href^="javascript:"]:after,
a[href^="#"]:after {
content: "";
}
pre,
blockquote {
border: 1px solid #999;
page-break-inside: avoid;
}
thead {
display: table-header-group;
}
tr,
img {
page-break-inside: avoid;
}
img {
max-width: 100% !important;
}
p,
h2,
h3 {
orphans: 3;
widows: 3;
}
h2,
h3 {
page-break-after: avoid;
}
select {
background: #fff !important;
}
.navbar {
display: none;
}
.table td,
.table th {
background-color: #fff !important;
}
.btn > .caret,
.dropup > .btn > .caret {
border-top-color: #000 !important;
}
.label {
border: 1px solid #000;
}
.table {
border-collapse: collapse !important;
}
.table-bordered th,
.table-bordered td {
border: 1px solid #ddd !important;
}
}
@font-face {
font-family: 'Glyphicons Halflings';
src: url('../fonts/glyphicons-halflings-regular.eot');
src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons_halflingsregular') format('svg');
}
.glyphicon {
position: relative;
top: 1px;
display: inline-block;
font-family: 'Glyphicons Halflings';
font-style: normal;
font-weight: normal;
line-height: 1;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
.glyphicon-asterisk:before {
content: "\2a";
}
.glyphicon-plus:before {
content: "\2b";
}
.glyphicon-euro:before {
content: "\20ac";
}
.glyphicon-minus:before {
content: "\2212";
}
.glyphicon-cloud:before {
content: "\2601";
}
.glyphicon-envelope:before {
content: "\2709";
}
.glyphicon-pencil:before {
content: "\270f";
}
.glyphicon-glass:before {
content: "\e001";
}
.glyphicon-music:before {
content: "\e002";
}
.glyphicon-search:before {
content: "\e003";
}
.glyphicon-heart:before {
content: "\e005";
}
.glyphicon-star:before {
content: "\e006";
}
.glyphicon-star-empty:before {
content: "\e007";
}
.glyphicon-user:before {
content: "\e008";
}
.glyphicon-film:before {
content: "\e009";
}
.glyphicon-th-large:before {
content: "\e010";
}
.glyphicon-th:before {
content: "\e011";
}
.glyphicon-th-list:before {
content: "\e012";
}
.glyphicon-ok:before {
content: "\e013";
}
.glyphicon-remove:before {
content: "\e014";
}
.glyphicon-zoom-in:before {
content: "\e015";
}
.glyphicon-zoom-out:before {
content: "\e016";
}
.glyphicon-off:before {
content: "\e017";
}
.glyphicon-signal:before {
content: "\e018";
}
.glyphicon-cog:before {
content: "\e019";
}
.glyphicon-trash:before {
content: "\e020";
}
.glyphicon-home:before {
content: "\e021";
}
.glyphicon-file:before {
content: "\e022";
}
.glyphicon-time:before {
content: "\e023";
}
.glyphicon-road:before {
content: "\e024";
}
.glyphicon-download-alt:before {
content: "\e025";
}
.glyphicon-download:before {
content: "\e026";
}
.glyphicon-upload:before {
content: "\e027";
}
.glyphicon-inbox:before {
content: "\e028";
}
.glyphicon-play-circle:before {
content: "\e029";
}
.glyphicon-repeat:before {
content: "\e030";
}
.glyphicon-refresh:before {
content: "\e031";
}
.glyphicon-list-alt:before {
content: "\e032";
}
.glyphicon-lock:before {
content: "\e033";
}
.glyphicon-flag:before {
content: "\e034";
}
.glyphicon-headphones:before {
content: "\e035";
}
.glyphicon-volume-off:before {
content: "\e036";
}
.glyphicon-volume-down:before {
content: "\e037";
}
.glyphicon-volume-up:before {
content: "\e038";
}
.glyphicon-qrcode:before {
content: "\e039";
}
.glyphicon-barcode:before {
content: "\e040";
}
.glyphicon-tag:before {
content: "\e041";
}
.glyphicon-tags:before {
content: "\e042";
}
.glyphicon-book:before {
content: "\e043";
}
.glyphicon-bookmark:before {
content: "\e044";
}
.glyphicon-print:before {
content: "\e045";
}
.glyphicon-camera:before {
content: "\e046";
}
.glyphicon-font:before {
content: "\e047";
}
.glyphicon-bold:before {
content: "\e048";
}
.glyphicon-italic:before {
content: "\e049";
}
.glyphicon-text-height:before {
content: "\e050";
}
.glyphicon-text-width:before {
content: "\e051";
}
.glyphicon-align-left:before {
content: "\e052";
}
.glyphicon-align-center:before {
content: "\e053";
}
.glyphicon-align-right:before {
content: "\e054";
}
.glyphicon-align-justify:before {
content: "\e055";
}
.glyphicon-list:before {
content: "\e056";
}
.glyphicon-indent-left:before {
content: "\e057";
}
.glyphicon-indent-right:before {
content: "\e058";
}
.glyphicon-facetime-video:before {
content: "\e059";
}
.glyphicon-picture:before {
content: "\e060";
}
.glyphicon-map-marker:before {
content: "\e062";
}
.glyphicon-adjust:before {
content: "\e063";
}
.glyphicon-tint:before {
content: "\e064";
}
.glyphicon-edit:before {
content: "\e065";
}
.glyphicon-share:before {
content: "\e066";
}
.glyphicon-check:before {
content: "\e067";
}
.glyphicon-move:before {
content: "\e068";
}
.glyphicon-step-backward:before {
content: "\e069";
}
.glyphicon-fast-backward:before {
content: "\e070";
}
.glyphicon-backward:before {
content: "\e071";
}
.glyphicon-play:before {
content: "\e072";
}
.glyphicon-pause:before {
content: "\e073";
}
.glyphicon-stop:before {
content: "\e074";
}
.glyphicon-forward:before {
content: "\e075";
}
.glyphicon-fast-forward:before {
content: "\e076";
}
.glyphicon-step-forward:before {
content: "\e077";
}
.glyphicon-eject:before {
content: "\e078";
}
.glyphicon-chevron-left:before {
content: "\e079";
}
.glyphicon-chevron-right:before {
content: "\e080";
}
.glyphicon-plus-sign:before {
content: "\e081";
}
.glyphicon-minus-sign:before {
content: "\e082";
}
.glyphicon-remove-sign:before {
content: "\e083";
}
.glyphicon-ok-sign:before {
content: "\e084";
}
.glyphicon-question-sign:before {
content: "\e085";
}
.glyphicon-info-sign:before {
content: "\e086";
}
.glyphicon-screenshot:before {
content: "\e087";
}
.glyphicon-remove-circle:before {
content: "\e088";
}
.glyphicon-ok-circle:before {
content: "\e089";
}
.glyphicon-ban-circle:before {
content: "\e090";
}
.glyphicon-arrow-left:before {
content: "\e091";
}
.glyphicon-arrow-right:before {
content: "\e092";
}
.glyphicon-arrow-up:before {
content: "\e093";
}
.glyphicon-arrow-down:before {
content: "\e094";
}
.glyphicon-share-alt:before {
content: "\e095";
}
.glyphicon-resize-full:before {
content: "\e096";
}
.glyphicon-resize-small:before {
content: "\e097";
}
.glyphicon-exclamation-sign:before {
content: "\e101";
}
.glyphicon-gift:before {
content: "\e102";
}
.glyphicon-leaf:before {
content: "\e103";
}
.glyphicon-fire:before {
content: "\e104";
}
.glyphicon-eye-open:before {
content: "\e105";
}
.glyphicon-eye-close:before {
content: "\e106";
}
.glyphicon-warning-sign:before {
content: "\e107";
}
.glyphicon-plane:before {
content: "\e108";
}
.glyphicon-calendar:before {
content: "\e109";
}
.glyphicon-random:before {
content: "\e110";
}
.glyphicon-comment:before {
content: "\e111";
}
.glyphicon-magnet:before {
content: "\e112";
}
.glyphicon-chevron-up:before {
content: "\e113";
}
.glyphicon-chevron-down:before {
content: "\e114";
}
.glyphicon-retweet:before {
content: "\e115";
}
.glyphicon-shopping-cart:before {
content: "\e116";
}
.glyphicon-folder-close:before {
content: "\e117";
}
.glyphicon-folder-open:before {
content: "\e118";
}
.glyphicon-resize-vertical:before {
content: "\e119";
}
.glyphicon-resize-horizontal:before {
content: "\e120";
}
.glyphicon-hdd:before {
content: "\e121";
}
.glyphicon-bullhorn:before {
content: "\e122";
}
.glyphicon-bell:before {
content: "\e123";
}
.glyphicon-certificate:before {
content: "\e124";
}
.glyphicon-thumbs-up:before {
content: "\e125";
}
.glyphicon-thumbs-down:before {
content: "\e126";
}
.glyphicon-hand-right:before {
content: "\e127";
}
.glyphicon-hand-left:before {
content: "\e128";
}
.glyphicon-hand-up:before {
content: "\e129";
}
.glyphicon-hand-down:before {
content: "\e130";
}
.glyphicon-circle-arrow-right:before {
content: "\e131";
}
.glyphicon-circle-arrow-left:before {
content: "\e132";
}
.glyphicon-circle-arrow-up:before {
content: "\e133";
}
.glyphicon-circle-arrow-down:before {
content: "\e134";
}
.glyphicon-globe:before {
content: "\e135";
}
.glyphicon-wrench:before {
content: "\e136";
}
.glyphicon-tasks:before {
content: "\e137";
}
.glyphicon-filter:before {
content: "\e138";
}
.glyphicon-briefcase:before {
content: "\e139";
}
.glyphicon-fullscreen:before {
content: "\e140";
}
.glyphicon-dashboard:before {
content: "\e141";
}
.glyphicon-paperclip:before {
content: "\e142";
}
.glyphicon-heart-empty:before {
content: "\e143";
}
.glyphicon-link:before {
content: "\e144";
}
.glyphicon-phone:before {
content: "\e145";
}
.glyphicon-pushpin:before {
content: "\e146";
}
.glyphicon-usd:before {
content: "\e148";
}
.glyphicon-gbp:before {
content: "\e149";
}
.glyphicon-sort:before {
content: "\e150";
}
.glyphicon-sort-by-alphabet:before {
content: "\e151";
}
.glyphicon-sort-by-alphabet-alt:before {
content: "\e152";
}
.glyphicon-sort-by-order:before {
content: "\e153";
}
.glyphicon-sort-by-order-alt:before {
content: "\e154";
}
.glyphicon-sort-by-attributes:before {
content: "\e155";
}
.glyphicon-sort-by-attributes-alt:before {
content: "\e156";
}
.glyphicon-unchecked:before {
content: "\e157";
}
.glyphicon-expand:before {
content: "\e158";
}
.glyphicon-collapse-down:before {
content: "\e159";
}
.glyphicon-collapse-up:before {
content: "\e160";
}
.glyphicon-log-in:before {
content: "\e161";
}
.glyphicon-flash:before {
content: "\e162";
}
.glyphicon-log-out:before {
content: "\e163";
}
.glyphicon-new-window:before {
content: "\e164";
}
.glyphicon-record:before {
content: "\e165";
}
.glyphicon-save:before {
content: "\e166";
}
.glyphicon-open:before {
content: "\e167";
}
.glyphicon-saved:before {
content: "\e168";
}
.glyphicon-import:before {
content: "\e169";
}
.glyphicon-export:before {
content: "\e170";
}
.glyphicon-send:before {
content: "\e171";
}
.glyphicon-floppy-disk:before {
content: "\e172";
}
.glyphicon-floppy-saved:before {
content: "\e173";
}
.glyphicon-floppy-remove:before {
content: "\e174";
}
.glyphicon-floppy-save:before {
content: "\e175";
}
.glyphicon-floppy-open:before {
content: "\e176";
}
.glyphicon-credit-card:before {
content: "\e177";
}
.glyphicon-transfer:before {
content: "\e178";
}
.glyphicon-cutlery:before {
content: "\e179";
}
.glyphicon-header:before {
content: "\e180";
}
.glyphicon-compressed:before {
content: "\e181";
}
.glyphicon-earphone:before {
content: "\e182";
}
.glyphicon-phone-alt:before {
content: "\e183";
}
.glyphicon-tower:before {
content: "\e184";
}
.glyphicon-stats:before {
content: "\e185";
}
.glyphicon-sd-video:before {
content: "\e186";
}
.glyphicon-hd-video:before {
content: "\e187";
}
.glyphicon-subtitles:before {
content: "\e188";
}
.glyphicon-sound-stereo:before {
content: "\e189";
}
.glyphicon-sound-dolby:before {
content: "\e190";
}
.glyphicon-sound-5-1:before {
content: "\e191";
}
.glyphicon-sound-6-1:before {
content: "\e192";
}
.glyphicon-sound-7-1:before {
content: "\e193";
}
.glyphicon-copyright-mark:before {
content: "\e194";
}
.glyphicon-registration-mark:before {
content: "\e195";
}
.glyphicon-cloud-download:before {
content: "\e197";
}
.glyphicon-cloud-upload:before {
content: "\e198";
}
.glyphicon-tree-conifer:before {
content: "\e199";
}
.glyphicon-tree-deciduous:before {
content: "\e200";
}
* {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
*:before,
*:after {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
html {
font-size: 10px;
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
}
body {
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 14px;
line-height: 1.42857143;
color: #333;
background-color: #fff;
}
input,
button,
select,
textarea {
font-family: inherit;
font-size: inherit;
line-height: inherit;
}
a {
color: #428bca;
text-decoration: none;
}
a:hover,
a:focus {
color: #2a6496;
text-decoration: underline;
}
a:focus {
outline: thin dotted;
outline: 5px auto -webkit-focus-ring-color;
outline-offset: -2px;
}
figure {
margin: 0;
}
img {
vertical-align: middle;
}
.img-responsive,
.thumbnail > img,
.thumbnail a > img,
.carousel-inner > .item > img,
.carousel-inner > .item > a > img {
display: block;
width: 100% \9;
max-width: 100%;
height: auto;
}
.img-rounded {
border-radius: 6px;
}
.img-thumbnail {
display: inline-block;
width: 100% \9;
max-width: 100%;
height: auto;
padding: 4px;
line-height: 1.42857143;
background-color: #fff;
border: 1px solid #ddd;
border-radius: 4px;
-webkit-transition: all .2s ease-in-out;
-o-transition: all .2s ease-in-out;
transition: all .2s ease-in-out;
}
.img-circle {
border-radius: 50%;
}
hr {
margin-top: 20px;
margin-bottom: 20px;
border: 0;
border-top: 1px solid #eee;
}
.sr-only {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
border: 0;
}
.sr-only-focusable:active,
.sr-only-focusable:focus {
position: static;
width: auto;
height: auto;
margin: 0;
overflow: visible;
clip: auto;
}
h1,
h2,
h3,
h4,
h5,
h6,
.h1,
.h2,
.h3,
.h4,
.h5,
.h6 {
font-family: inherit;
font-weight: 500;
line-height: 1.1;
color: inherit;
}
h1 small,
h2 small,
h3 small,
h4 small,
h5 small,
h6 small,
.h1 small,
.h2 small,
.h3 small,
.h4 small,
.h5 small,
.h6 small,
h1 .small,
h2 .small,
h3 .small,
h4 .small,
h5 .small,
h6 .small,
.h1 .small,
.h2 .small,
.h3 .small,
.h4 .small,
.h5 .small,
.h6 .small {
font-weight: normal;
line-height: 1;
color: #777;
}
h1,
.h1,
h2,
.h2,
h3,
.h3 {
margin-top: 20px;
margin-bottom: 10px;
}
h1 small,
.h1 small,
h2 small,
.h2 small,
h3 small,
.h3 small,
h1 .small,
.h1 .small,
h2 .small,
.h2 .small,
h3 .small,
.h3 .small {
font-size: 65%;
}
h4,
.h4,
h5,
.h5,
h6,
.h6 {
margin-top: 10px;
margin-bottom: 10px;
}
h4 small,
.h4 small,
h5 small,
.h5 small,
h6 small,
.h6 small,
h4 .small,
.h4 .small,
h5 .small,
.h5 .small,
h6 .small,
.h6 .small {
font-size: 75%;
}
h1,
.h1 {
font-size: 36px;
}
h2,
.h2 {
font-size: 30px;
}
h3,
.h3 {
font-size: 24px;
}
h4,
.h4 {
font-size: 18px;
}
h5,
.h5 {
font-size: 14px;
}
h6,
.h6 {
font-size: 12px;
}
p {
margin: 0 0 10px;
}
.lead {
margin-bottom: 20px;
font-size: 16px;
font-weight: 300;
line-height: 1.4;
}
@media (min-width: 768px) {
.lead {
font-size: 21px;
}
}
small,
.small {
font-size: 85%;
}
cite {
font-style: normal;
}
mark,
.mark {
padding: .2em;
background-color: #fcf8e3;
}
.text-left {
text-align: left;
}
.text-right {
text-align: right;
}
.text-center {
text-align: center;
}
.text-justify {
text-align: justify;
}
.text-nowrap {
white-space: nowrap;
}
.text-lowercase {
text-transform: lowercase;
}
.text-uppercase {
text-transform: uppercase;
}
.text-capitalize {
text-transform: capitalize;
}
.text-muted {
color: #777;
}
.text-primary {
color: #428bca;
}
a.text-primary:hover {
color: #3071a9;
}
.text-success {
color: #3c763d;
}
a.text-success:hover {
color: #2b542c;
}
.text-info {
color: #31708f;
}
a.text-info:hover {
color: #245269;
}
.text-warning {
color: #8a6d3b;
}
a.text-warning:hover {
color: #66512c;
}
.text-danger {
color: #a94442;
}
a.text-danger:hover {
color: #843534;
}
.bg-primary {
color: #fff;
background-color: #428bca;
}
a.bg-primary:hover {
background-color: #3071a9;
}
.bg-success {
background-color: #dff0d8;
}
a.bg-success:hover {
background-color: #c1e2b3;
}
.bg-info {
background-color: #d9edf7;
}
a.bg-info:hover {
background-color: #afd9ee;
}
.bg-warning {
background-color: #fcf8e3;
}
a.bg-warning:hover {
background-color: #f7ecb5;
}
.bg-danger {
background-color: #f2dede;
}
a.bg-danger:hover {
background-color: #e4b9b9;
}
.page-header {
padding-bottom: 9px;
margin: 40px 0 20px;
border-bottom: 1px solid #eee;
}
ul,
ol {
margin-top: 0;
margin-bottom: 10px;
}
ul ul,
ol ul,
ul ol,
ol ol {
margin-bottom: 0;
}
.list-unstyled {
padding-left: 0;
list-style: none;
}
.list-inline {
padding-left: 0;
margin-left: -5px;
list-style: none;
}
.list-inline > li {
display: inline-block;
padding-right: 5px;
padding-left: 5px;
}
dl {
margin-top: 0;
margin-bottom: 20px;
}
dt,
dd {
line-height: 1.42857143;
}
dt {
font-weight: bold;
}
dd {
margin-left: 0;
}
@media (min-width: 768px) {
.dl-horizontal dt {
float: left;
width: 160px;
overflow: hidden;
clear: left;
text-align: right;
text-overflow: ellipsis;
white-space: nowrap;
}
.dl-horizontal dd {
margin-left: 180px;
}
}
abbr[title],
abbr[data-original-title] {
cursor: help;
border-bottom: 1px dotted #777;
}
.initialism {
font-size: 90%;
text-transform: uppercase;
}
blockquote {
padding: 10px 20px;
margin: 0 0 20px;
font-size: 17.5px;
border-left: 5px solid #eee;
}
blockquote p:last-child,
blockquote ul:last-child,
blockquote ol:last-child {
margin-bottom: 0;
}
blockquote footer,
blockquote small,
blockquote .small {
display: block;
font-size: 80%;
line-height: 1.42857143;
color: #777;
}
blockquote footer:before,
blockquote small:before,
blockquote .small:before {
content: '\2014 \00A0';
}
.blockquote-reverse,
blockquote.pull-right {
padding-right: 15px;
padding-left: 0;
text-align: right;
border-right: 5px solid #eee;
border-left: 0;
}
.blockquote-reverse footer:before,
blockquote.pull-right footer:before,
.blockquote-reverse small:before,
blockquote.pull-right small:before,
.blockquote-reverse .small:before,
blockquote.pull-right .small:before {
content: '';
}
.blockquote-reverse footer:after,
blockquote.pull-right footer:after,
.blockquote-reverse small:after,
blockquote.pull-right small:after,
.blockquote-reverse .small:after,
blockquote.pull-right .small:after {
content: '\00A0 \2014';
}
blockquote:before,
blockquote:after {
content: "";
}
address {
margin-bottom: 20px;
font-style: normal;
line-height: 1.42857143;
}
code,
kbd,
pre,
samp {
font-family: Menlo, Monaco, Consolas, "Courier New", monospace;
}
code {
padding: 2px 4px;
font-size: 90%;
color: #c7254e;
background-color: #f9f2f4;
border-radius: 4px;
}
kbd {
padding: 2px 4px;
font-size: 90%;
color: #fff;
background-color: #333;
border-radius: 3px;
-webkit-box-shadow: inset 0 -1px 0 rgba(0, 0, 0, .25);
box-shadow: inset 0 -1px 0 rgba(0, 0, 0, .25);
}
kbd kbd {
padding: 0;
font-size: 100%;
-webkit-box-shadow: none;
box-shadow: none;
}
pre {
display: block;
padding: 9.5px;
margin: 0 0 10px;
font-size: 13px;
line-height: 1.42857143;
color: #333;
word-break: break-all;
word-wrap: break-word;
background-color: #f5f5f5;
border: 1px solid #ccc;
border-radius: 4px;
}
pre code {
padding: 0;
font-size: inherit;
color: inherit;
white-space: pre-wrap;
background-color: transparent;
border-radius: 0;
}
.pre-scrollable {
max-height: 340px;
overflow-y: scroll;
}
.container {
padding-right: 15px;
padding-left: 15px;
margin-right: auto;
margin-left: auto;
}
@media (min-width: 768px) {
.container {
width: 750px;
}
}
@media (min-width: 992px) {
.container {
width: 970px;
}
}
@media (min-width: 1200px) {
.container {
width: 1170px;
}
}
.container-fluid {
padding-right: 6px;
padding-left: 6px;
margin-right: auto;
margin-left: auto;
}
.row {
margin-right: -6px;
margin-left: -6px;
}
.col-xs-1, .col-sm-1, .col-md-1, .col-lg-1, .col-xs-2, .col-sm-2, .col-md-2, .col-lg-2, .col-xs-3, .col-sm-3, .col-md-3, .col-lg-3, .col-xs-4, .col-sm-4, .col-md-4, .col-lg-4, .col-xs-5, .col-sm-5, .col-md-5, .col-lg-5, .col-xs-6, .col-sm-6, .col-md-6, .col-lg-6, .col-xs-7, .col-sm-7, .col-md-7, .col-lg-7, .col-xs-8, .col-sm-8, .col-md-8, .col-lg-8, .col-xs-9, .col-sm-9, .col-md-9, .col-lg-9, .col-xs-10, .col-sm-10, .col-md-10, .col-lg-10, .col-xs-11, .col-sm-11, .col-md-11, .col-lg-11, .col-xs-12, .col-sm-12, .col-md-12, .col-lg-12 {
position: relative;
min-height: 1px;
padding-right: 6px;
padding-left: 6px;
}
.col-xs-1, .col-xs-2, .col-xs-3, .col-xs-4, .col-xs-5, .col-xs-6, .col-xs-7, .col-xs-8, .col-xs-9, .col-xs-10, .col-xs-11, .col-xs-12 {
float: left;
}
.col-xs-12 {
width: 100%;
}
.col-xs-11 {
width: 91.66666667%;
}
.col-xs-10 {
width: 83.33333333%;
}
.col-xs-9 {
width: 75%;
}
.col-xs-8 {
width: 66.66666667%;
}
.col-xs-7 {
width: 58.33333333%;
}
.col-xs-6 {
width: 50%;
}
.col-xs-5 {
width: 41.66666667%;
}
.col-xs-4 {
width: 33.33333333%;
}
.col-xs-3 {
width: 25%;
}
.col-xs-2 {
width: 16.66666667%;
}
.col-xs-1 {
width: 8.33333333%;
}
.col-xs-pull-12 {
right: 100%;
}
.col-xs-pull-11 {
right: 91.66666667%;
}
.col-xs-pull-10 {
right: 83.33333333%;
}
.col-xs-pull-9 {
right: 75%;
}
.col-xs-pull-8 {
right: 66.66666667%;
}
.col-xs-pull-7 {
right: 58.33333333%;
}
.col-xs-pull-6 {
right: 50%;
}
.col-xs-pull-5 {
right: 41.66666667%;
}
.col-xs-pull-4 {
right: 33.33333333%;
}
.col-xs-pull-3 {
right: 25%;
}
.col-xs-pull-2 {
right: 16.66666667%;
}
.col-xs-pull-1 {
right: 8.33333333%;
}
.col-xs-pull-0 {
right: auto;
}
.col-xs-push-12 {
left: 100%;
}
.col-xs-push-11 {
left: 91.66666667%;
}
.col-xs-push-10 {
left: 83.33333333%;
}
.col-xs-push-9 {
left: 75%;
}
.col-xs-push-8 {
left: 66.66666667%;
}
.col-xs-push-7 {
left: 58.33333333%;
}
.col-xs-push-6 {
left: 50%;
}
.col-xs-push-5 {
left: 41.66666667%;
}
.col-xs-push-4 {
left: 33.33333333%;
}
.col-xs-push-3 {
left: 25%;
}
.col-xs-push-2 {
left: 16.66666667%;
}
.col-xs-push-1 {
left: 8.33333333%;
}
.col-xs-push-0 {
left: auto;
}
.col-xs-offset-12 {
margin-left: 100%;
}
.col-xs-offset-11 {
margin-left: 91.66666667%;
}
.col-xs-offset-10 {
margin-left: 83.33333333%;
}
.col-xs-offset-9 {
margin-left: 75%;
}
.col-xs-offset-8 {
margin-left: 66.66666667%;
}
.col-xs-offset-7 {
margin-left: 58.33333333%;
}
.col-xs-offset-6 {
margin-left: 50%;
}
.col-xs-offset-5 {
margin-left: 41.66666667%;
}
.col-xs-offset-4 {
margin-left: 33.33333333%;
}
.col-xs-offset-3 {
margin-left: 25%;
}
.col-xs-offset-2 {
margin-left: 16.66666667%;
}
.col-xs-offset-1 {
margin-left: 8.33333333%;
}
.col-xs-offset-0 {
margin-left: 0;
}
@media (min-width: 768px) {
.col-sm-1, .col-sm-2, .col-sm-3, .col-sm-4, .col-sm-5, .col-sm-6, .col-sm-7, .col-sm-8, .col-sm-9, .col-sm-10, .col-sm-11, .col-sm-12 {
float: left;
}
.col-sm-12 {
width: 100%;
}
.col-sm-11 {
width: 91.66666667%;
}
.col-sm-10 {
width: 83.33333333%;
}
.col-sm-9 {
width: 75%;
}
.col-sm-8 {
width: 66.66666667%;
}
.col-sm-7 {
width: 58.33333333%;
}
.col-sm-6 {
width: 50%;
}
.col-sm-5 {
width: 41.66666667%;
}
.col-sm-4 {
width: 33.33333333%;
}
.col-sm-3 {
width: 25%;
}
.col-sm-2 {
width: 16.66666667%;
}
.col-sm-1 {
width: 8.33333333%;
}
.col-sm-pull-12 {
right: 100%;
}
.col-sm-pull-11 {
right: 91.66666667%;
}
.col-sm-pull-10 {
right: 83.33333333%;
}
.col-sm-pull-9 {
right: 75%;
}
.col-sm-pull-8 {
right: 66.66666667%;
}
.col-sm-pull-7 {
right: 58.33333333%;
}
.col-sm-pull-6 {
right: 50%;
}
.col-sm-pull-5 {
right: 41.66666667%;
}
.col-sm-pull-4 {
right: 33.33333333%;
}
.col-sm-pull-3 {
right: 25%;
}
.col-sm-pull-2 {
right: 16.66666667%;
}
.col-sm-pull-1 {
right: 8.33333333%;
}
.col-sm-pull-0 {
right: auto;
}
.col-sm-push-12 {
left: 100%;
}
.col-sm-push-11 {
left: 91.66666667%;
}
.col-sm-push-10 {
left: 83.33333333%;
}
.col-sm-push-9 {
left: 75%;
}
.col-sm-push-8 {
left: 66.66666667%;
}
.col-sm-push-7 {
left: 58.33333333%;
}
.col-sm-push-6 {
left: 50%;
}
.col-sm-push-5 {
left: 41.66666667%;
}
.col-sm-push-4 {
left: 33.33333333%;
}
.col-sm-push-3 {
left: 25%;
}
.col-sm-push-2 {
left: 16.66666667%;
}
.col-sm-push-1 {
left: 8.33333333%;
}
.col-sm-push-0 {
left: auto;
}
.col-sm-offset-12 {
margin-left: 100%;
}
.col-sm-offset-11 {
margin-left: 91.66666667%;
}
.col-sm-offset-10 {
margin-left: 83.33333333%;
}
.col-sm-offset-9 {
margin-left: 75%;
}
.col-sm-offset-8 {
margin-left: 66.66666667%;
}
.col-sm-offset-7 {
margin-left: 58.33333333%;
}
.col-sm-offset-6 {
margin-left: 50%;
}
.col-sm-offset-5 {
margin-left: 41.66666667%;
}
.col-sm-offset-4 {
margin-left: 33.33333333%;
}
.col-sm-offset-3 {
margin-left: 25%;
}
.col-sm-offset-2 {
margin-left: 16.66666667%;
}
.col-sm-offset-1 {
margin-left: 8.33333333%;
}
.col-sm-offset-0 {
margin-left: 0;
}
}
@media (min-width: 992px) {
.col-md-1, .col-md-2, .col-md-3, .col-md-4, .col-md-5, .col-md-6, .col-md-7, .col-md-8, .col-md-9, .col-md-10, .col-md-11, .col-md-12 {
float: left;
}
.col-md-12 {
width: 100%;
}
.col-md-11 {
width: 91.66666667%;
}
.col-md-10 {
width: 83.33333333%;
}
.col-md-9 {
width: 75%;
}
.col-md-8 {
width: 66.66666667%;
}
.col-md-7 {
width: 58.33333333%;
}
.col-md-6 {
width: 50%;
}
.col-md-5 {
width: 41.66666667%;
}
.col-md-4 {
width: 33.33333333%;
}
.col-md-3 {
width: 25%;
}
.col-md-2 {
width: 16.66666667%;
}
.col-md-1 {
width: 8.33333333%;
}
.col-md-pull-12 {
right: 100%;
}
.col-md-pull-11 {
right: 91.66666667%;
}
.col-md-pull-10 {
right: 83.33333333%;
}
.col-md-pull-9 {
right: 75%;
}
.col-md-pull-8 {
right: 66.66666667%;
}
.col-md-pull-7 {
right: 58.33333333%;
}
.col-md-pull-6 {
right: 50%;
}
.col-md-pull-5 {
right: 41.66666667%;
}
.col-md-pull-4 {
right: 33.33333333%;
}
.col-md-pull-3 {
right: 25%;
}
.col-md-pull-2 {
right: 16.66666667%;
}
.col-md-pull-1 {
right: 8.33333333%;
}
.col-md-pull-0 {
right: auto;
}
.col-md-push-12 {
left: 100%;
}
.col-md-push-11 {
left: 91.66666667%;
}
.col-md-push-10 {
left: 83.33333333%;
}
.col-md-push-9 {
left: 75%;
}
.col-md-push-8 {
left: 66.66666667%;
}
.col-md-push-7 {
left: 58.33333333%;
}
.col-md-push-6 {
left: 50%;
}
.col-md-push-5 {
left: 41.66666667%;
}
.col-md-push-4 {
left: 33.33333333%;
}
.col-md-push-3 {
left: 25%;
}
.col-md-push-2 {
left: 16.66666667%;
}
.col-md-push-1 {
left: 8.33333333%;
}
.col-md-push-0 {
left: auto;
}
.col-md-offset-12 {
margin-left: 100%;
}
.col-md-offset-11 {
margin-left: 91.66666667%;
}
.col-md-offset-10 {
margin-left: 83.33333333%;
}
.col-md-offset-9 {
margin-left: 75%;
}
.col-md-offset-8 {
margin-left: 66.66666667%;
}
.col-md-offset-7 {
margin-left: 58.33333333%;
}
.col-md-offset-6 {
margin-left: 50%;
}
.col-md-offset-5 {
margin-left: 41.66666667%;
}
.col-md-offset-4 {
margin-left: 33.33333333%;
}
.col-md-offset-3 {
margin-left: 25%;
}
.col-md-offset-2 {
margin-left: 16.66666667%;
}
.col-md-offset-1 {
margin-left: 8.33333333%;
}
.col-md-offset-0 {
margin-left: 0;
}
}
@media (min-width: 1200px) {
.col-lg-1, .col-lg-2, .col-lg-3, .col-lg-4, .col-lg-5, .col-lg-6, .col-lg-7, .col-lg-8, .col-lg-9, .col-lg-10, .col-lg-11, .col-lg-12 {
float: left;
}
.col-lg-12 {
width: 100%;
}
.col-lg-11 {
width: 91.66666667%;
}
.col-lg-10 {
width: 83.33333333%;
}
.col-lg-9 {
width: 75%;
}
.col-lg-8 {
width: 66.66666667%;
}
.col-lg-7 {
width: 58.33333333%;
}
.col-lg-6 {
width: 50%;
}
.col-lg-5 {
width: 41.66666667%;
}
.col-lg-4 {
width: 33.33333333%;
}
.col-lg-3 {
width: 25%;
}
.col-lg-2 {
width: 16.66666667%;
}
.col-lg-1 {
width: 8.33333333%;
}
.col-lg-pull-12 {
right: 100%;
}
.col-lg-pull-11 {
right: 91.66666667%;
}
.col-lg-pull-10 {
right: 83.33333333%;
}
.col-lg-pull-9 {
right: 75%;
}
.col-lg-pull-8 {
right: 66.66666667%;
}
.col-lg-pull-7 {
right: 58.33333333%;
}
.col-lg-pull-6 {
right: 50%;
}
.col-lg-pull-5 {
right: 41.66666667%;
}
.col-lg-pull-4 {
right: 33.33333333%;
}
.col-lg-pull-3 {
right: 25%;
}
.col-lg-pull-2 {
right: 16.66666667%;
}
.col-lg-pull-1 {
right: 8.33333333%;
}
.col-lg-pull-0 {
right: auto;
}
.col-lg-push-12 {
left: 100%;
}
.col-lg-push-11 {
left: 91.66666667%;
}
.col-lg-push-10 {
left: 83.33333333%;
}
.col-lg-push-9 {
left: 75%;
}
.col-lg-push-8 {
left: 66.66666667%;
}
.col-lg-push-7 {
left: 58.33333333%;
}
.col-lg-push-6 {
left: 50%;
}
.col-lg-push-5 {
left: 41.66666667%;
}
.col-lg-push-4 {
left: 33.33333333%;
}
.col-lg-push-3 {
left: 25%;
}
.col-lg-push-2 {
left: 16.66666667%;
}
.col-lg-push-1 {
left: 8.33333333%;
}
.col-lg-push-0 {
left: auto;
}
.col-lg-offset-12 {
margin-left: 100%;
}
.col-lg-offset-11 {
margin-left: 91.66666667%;
}
.col-lg-offset-10 {
margin-left: 83.33333333%;
}
.col-lg-offset-9 {
margin-left: 75%;
}
.col-lg-offset-8 {
margin-left: 66.66666667%;
}
.col-lg-offset-7 {
margin-left: 58.33333333%;
}
.col-lg-offset-6 {
margin-left: 50%;
}
.col-lg-offset-5 {
margin-left: 41.66666667%;
}
.col-lg-offset-4 {
margin-left: 33.33333333%;
}
.col-lg-offset-3 {
margin-left: 25%;
}
.col-lg-offset-2 {
margin-left: 16.66666667%;
}
.col-lg-offset-1 {
margin-left: 8.33333333%;
}
.col-lg-offset-0 {
margin-left: 0;
}
}
table {
background-color: transparent;
}
th {
text-align: left;
}
.table {
width: 100%;
max-width: 100%;
margin-bottom: 20px;
}
.table > thead > tr > th,
.table > tbody > tr > th,
.table > tfoot > tr > th,
.table > thead > tr > td,
.table > tbody > tr > td,
.table > tfoot > tr > td {
padding: 8px;
line-height: 1.42857143;
vertical-align: top;
border-top: 1px solid #ddd;
}
.table > thead > tr > th {
vertical-align: bottom;
border-bottom: 2px solid #ddd;
}
.table > caption + thead > tr:first-child > th,
.table > colgroup + thead > tr:first-child > th,
.table > thead:first-child > tr:first-child > th,
.table > caption + thead > tr:first-child > td,
.table > colgroup + thead > tr:first-child > td,
.table > thead:first-child > tr:first-child > td {
border-top: 0;
}
.table > tbody + tbody {
border-top: 2px solid #ddd;
}
.table .table {
background-color: #fff;
}
.table-condensed > thead > tr > th,
.table-condensed > tbody > tr > th,
.table-condensed > tfoot > tr > th,
.table-condensed > thead > tr > td,
.table-condensed > tbody > tr > td,
.table-condensed > tfoot > tr > td {
padding: 5px;
}
.table-bordered {
border: 1px solid #ddd;
}
.table-bordered > thead > tr > th,
.table-bordered > tbody > tr > th,
.table-bordered > tfoot > tr > th,
.table-bordered > thead > tr > td,
.table-bordered > tbody > tr > td,
.table-bordered > tfoot > tr > td {
border: 1px solid #ddd;
}
.table-bordered > thead > tr > th,
.table-bordered > thead > tr > td {
border-bottom-width: 2px;
}
.table-striped > tbody > tr:nth-child(odd) > td,
.table-striped > tbody > tr:nth-child(odd) > th {
background-color: #f9f9f9;
}
.table-hover > tbody > tr:hover > td,
.table-hover > tbody > tr:hover > th {
background-color: #f5f5f5;
}
table col[class*="col-"] {
position: static;
display: table-column;
float: none;
}
table td[class*="col-"],
table th[class*="col-"] {
position: static;
display: table-cell;
float: none;
}
.table > thead > tr > td.active,
.table > tbody > tr > td.active,
.table > tfoot > tr > td.active,
.table > thead > tr > th.active,
.table > tbody > tr > th.active,
.table > tfoot > tr > th.active,
.table > thead > tr.active > td,
.table > tbody > tr.active > td,
.table > tfoot > tr.active > td,
.table > thead > tr.active > th,
.table > tbody > tr.active > th,
.table > tfoot > tr.active > th {
background-color: #f5f5f5;
}
.table-hover > tbody > tr > td.active:hover,
.table-hover > tbody > tr > th.active:hover,
.table-hover > tbody > tr.active:hover > td,
.table-hover > tbody > tr:hover > .active,
.table-hover > tbody > tr.active:hover > th {
background-color: #e8e8e8;
}
.table > thead > tr > td.success,
.table > tbody > tr > td.success,
.table > tfoot > tr > td.success,
.table > thead > tr > th.success,
.table > tbody > tr > th.success,
.table > tfoot > tr > th.success,
.table > thead > tr.success > td,
.table > tbody > tr.success > td,
.table > tfoot > tr.success > td,
.table > thead > tr.success > th,
.table > tbody > tr.success > th,
.table > tfoot > tr.success > th {
background-color: #dff0d8;
}
.table-hover > tbody > tr > td.success:hover,
.table-hover > tbody > tr > th.success:hover,
.table-hover > tbody > tr.success:hover > td,
.table-hover > tbody > tr:hover > .success,
.table-hover > tbody > tr.success:hover > th {
background-color: #d0e9c6;
}
.table > thead > tr > td.info,
.table > tbody > tr > td.info,
.table > tfoot > tr > td.info,
.table > thead > tr > th.info,
.table > tbody > tr > th.info,
.table > tfoot > tr > th.info,
.table > thead > tr.info > td,
.table > tbody > tr.info > td,
.table > tfoot > tr.info > td,
.table > thead > tr.info > th,
.table > tbody > tr.info > th,
.table > tfoot > tr.info > th {
background-color: #d9edf7;
}
.table-hover > tbody > tr > td.info:hover,
.table-hover > tbody > tr > th.info:hover,
.table-hover > tbody > tr.info:hover > td,
.table-hover > tbody > tr:hover > .info,
.table-hover > tbody > tr.info:hover > th {
background-color: #c4e3f3;
}
.table > thead > tr > td.warning,
.table > tbody > tr > td.warning,
.table > tfoot > tr > td.warning,
.table > thead > tr > th.warning,
.table > tbody > tr > th.warning,
.table > tfoot > tr > th.warning,
.table > thead > tr.warning > td,
.table > tbody > tr.warning > td,
.table > tfoot > tr.warning > td,
.table > thead > tr.warning > th,
.table > tbody > tr.warning > th,
.table > tfoot > tr.warning > th {
background-color: #fcf8e3;
}
.table-hover > tbody > tr > td.warning:hover,
.table-hover > tbody > tr > th.warning:hover,
.table-hover > tbody > tr.warning:hover > td,
.table-hover > tbody > tr:hover > .warning,
.table-hover > tbody > tr.warning:hover > th {
background-color: #faf2cc;
}
.table > thead > tr > td.danger,
.table > tbody > tr > td.danger,
.table > tfoot > tr > td.danger,
.table > thead > tr > th.danger,
.table > tbody > tr > th.danger,
.table > tfoot > tr > th.danger,
.table > thead > tr.danger > td,
.table > tbody > tr.danger > td,
.table > tfoot > tr.danger > td,
.table > thead > tr.danger > th,
.table > tbody > tr.danger > th,
.table > tfoot > tr.danger > th {
background-color: #f2dede;
}
.table-hover > tbody > tr > td.danger:hover,
.table-hover > tbody > tr > th.danger:hover,
.table-hover > tbody > tr.danger:hover > td,
.table-hover > tbody > tr:hover > .danger,
.table-hover > tbody > tr.danger:hover > th {
background-color: #ebcccc;
}
@media screen and (max-width: 767px) {
.table-responsive {
width: 100%;
margin-bottom: 15px;
overflow-x: auto;
overflow-y: hidden;
-webkit-overflow-scrolling: touch;
-ms-overflow-style: -ms-autohiding-scrollbar;
border: 1px solid #ddd;
}
.table-responsive > .table {
margin-bottom: 0;
}
.table-responsive > .table > thead > tr > th,
.table-responsive > .table > tbody > tr > th,
.table-responsive > .table > tfoot > tr > th,
.table-responsive > .table > thead > tr > td,
.table-responsive > .table > tbody > tr > td,
.table-responsive > .table > tfoot > tr > td {
white-space: nowrap;
}
.table-responsive > .table-bordered {
border: 0;
}
.table-responsive > .table-bordered > thead > tr > th:first-child,
.table-responsive > .table-bordered > tbody > tr > th:first-child,
.table-responsive > .table-bordered > tfoot > tr > th:first-child,
.table-responsive > .table-bordered > thead > tr > td:first-child,
.table-responsive > .table-bordered > tbody > tr > td:first-child,
.table-responsive > .table-bordered > tfoot > tr > td:first-child {
border-left: 0;
}
.table-responsive > .table-bordered > thead > tr > th:last-child,
.table-responsive > .table-bordered > tbody > tr > th:last-child,
.table-responsive > .table-bordered > tfoot > tr > th:last-child,
.table-responsive > .table-bordered > thead > tr > td:last-child,
.table-responsive > .table-bordered > tbody > tr > td:last-child,
.table-responsive > .table-bordered > tfoot > tr > td:last-child {
border-right: 0;
}
.table-responsive > .table-bordered > tbody > tr:last-child > th,
.table-responsive > .table-bordered > tfoot > tr:last-child > th,
.table-responsive > .table-bordered > tbody > tr:last-child > td,
.table-responsive > .table-bordered > tfoot > tr:last-child > td {
border-bottom: 0;
}
}
fieldset {
min-width: 0;
padding: 0;
margin: 0;
border: 0;
}
legend {
display: block;
width: 100%;
padding: 0;
margin-bottom: 20px;
font-size: 21px;
line-height: inherit;
color: #333;
border: 0;
border-bottom: 1px solid #e5e5e5;
}
label {
display: inline-block;
max-width: 100%;
margin-bottom: 5px;
font-weight: bold;
}
input[type="search"] {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
input[type="radio"],
input[type="checkbox"] {
margin: 4px 0 0;
margin-top: 1px \9;
line-height: normal;
}
input[type="file"] {
display: block;
}
input[type="range"] {
display: block;
width: 100%;
}
select[multiple],
select[size] {
height: auto;
}
input[type="file"]:focus,
input[type="radio"]:focus,
input[type="checkbox"]:focus {
outline: thin dotted;
outline: 5px auto -webkit-focus-ring-color;
outline-offset: -2px;
}
output {
display: block;
padding-top: 7px;
font-size: 14px;
line-height: 1.42857143;
color: #555;
}
.form-control {
display: block;
width: 100%;
height: 34px;
padding: 6px 12px;
font-size: 14px;
line-height: 1.42857143;
color: #555;
background-color: #fff;
background-image: none;
border: 1px solid #ccc;
border-radius: 4px;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
-webkit-transition: border-color ease-in-out .15s, -webkit-box-shadow ease-in-out .15s;
-o-transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
}
.form-control:focus {
border-color: #66afe9;
outline: 0;
-webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102, 175, 233, .6);
box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102, 175, 233, .6);
}
.form-control::-moz-placeholder {
color: #777;
opacity: 1;
}
.form-control:-ms-input-placeholder {
color: #777;
}
.form-control::-webkit-input-placeholder {
color: #777;
}
.form-control[disabled],
.form-control[readonly],
fieldset[disabled] .form-control {
cursor: not-allowed;
background-color: #eee;
opacity: 1;
}
textarea.form-control {
height: auto;
}
input[type="search"] {
-webkit-appearance: none;
}
input[type="date"],
input[type="time"],
input[type="datetime-local"],
input[type="month"] {
line-height: 34px;
line-height: 1.42857143 \0;
}
input[type="date"].input-sm,
input[type="time"].input-sm,
input[type="datetime-local"].input-sm,
input[type="month"].input-sm {
line-height: 30px;
}
input[type="date"].input-lg,
input[type="time"].input-lg,
input[type="datetime-local"].input-lg,
input[type="month"].input-lg {
line-height: 46px;
}
.form-group {
margin-bottom: 15px;
}
.radio,
.checkbox {
position: relative;
display: block;
min-height: 20px;
margin-top: 10px;
margin-bottom: 10px;
}
.radio label,
.checkbox label {
padding-left: 20px;
margin-bottom: 0;
font-weight: normal;
cursor: pointer;
}
.radio input[type="radio"],
.radio-inline input[type="radio"],
.checkbox input[type="checkbox"],
.checkbox-inline input[type="checkbox"] {
position: absolute;
margin-top: 4px \9;
margin-left: -20px;
}
.radio + .radio,
.checkbox + .checkbox {
margin-top: -5px;
}
.radio-inline,
.checkbox-inline {
display: inline-block;
padding-left: 20px;
margin-bottom: 0;
font-weight: normal;
vertical-align: middle;
cursor: pointer;
}
.radio-inline + .radio-inline,
.checkbox-inline + .checkbox-inline {
margin-top: 0;
margin-left: 10px;
}
input[type="radio"][disabled],
input[type="checkbox"][disabled],
input[type="radio"].disabled,
input[type="checkbox"].disabled,
fieldset[disabled] input[type="radio"],
fieldset[disabled] input[type="checkbox"] {
cursor: not-allowed;
}
.radio-inline.disabled,
.checkbox-inline.disabled,
fieldset[disabled] .radio-inline,
fieldset[disabled] .checkbox-inline {
cursor: not-allowed;
}
.radio.disabled label,
.checkbox.disabled label,
fieldset[disabled] .radio label,
fieldset[disabled] .checkbox label {
cursor: not-allowed;
}
.form-control-static {
padding-top: 7px;
padding-bottom: 7px;
margin-bottom: 0;
}
.form-control-static.input-lg,
.form-control-static.input-sm {
padding-right: 0;
padding-left: 0;
}
.input-sm,
.form-horizontal .form-group-sm .form-control {
height: 30px;
padding: 5px 10px;
font-size: 12px;
line-height: 1.5;
border-radius: 3px;
}
select.input-sm {
height: 30px;
line-height: 30px;
}
textarea.input-sm,
select[multiple].input-sm {
height: auto;
}
.input-lg,
.form-horizontal .form-group-lg .form-control {
height: 46px;
padding: 10px 16px;
font-size: 18px;
line-height: 1.33;
border-radius: 6px;
}
select.input-lg {
height: 46px;
line-height: 46px;
}
textarea.input-lg,
select[multiple].input-lg {
height: auto;
}
.has-feedback {
position: relative;
}
.has-feedback .form-control {
padding-right: 42.5px;
}
.form-control-feedback {
position: absolute;
top: 25px;
right: 0;
z-index: 2;
display: block;
width: 34px;
height: 34px;
line-height: 34px;
text-align: center;
}
.input-lg + .form-control-feedback {
width: 46px;
height: 46px;
line-height: 46px;
}
.input-sm + .form-control-feedback {
width: 30px;
height: 30px;
line-height: 30px;
}
.has-success .help-block,
.has-success .control-label,
.has-success .radio,
.has-success .checkbox,
.has-success .radio-inline,
.has-success .checkbox-inline {
color: #3c763d;
}
.has-success .form-control {
border-color: #3c763d;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
}
.has-success .form-control:focus {
border-color: #2b542c;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #67b168;
box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #67b168;
}
.has-success .input-group-addon {
color: #3c763d;
background-color: #dff0d8;
border-color: #3c763d;
}
.has-success .form-control-feedback {
color: #3c763d;
}
.has-warning .help-block,
.has-warning .control-label,
.has-warning .radio,
.has-warning .checkbox,
.has-warning .radio-inline,
.has-warning .checkbox-inline {
color: #8a6d3b;
}
.has-warning .form-control {
border-color: #8a6d3b;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
}
.has-warning .form-control:focus {
border-color: #66512c;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #c0a16b;
box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #c0a16b;
}
.has-warning .input-group-addon {
color: #8a6d3b;
background-color: #fcf8e3;
border-color: #8a6d3b;
}
.has-warning .form-control-feedback {
color: #8a6d3b;
}
.has-error .help-block,
.has-error .control-label,
.has-error .radio,
.has-error .checkbox,
.has-error .radio-inline,
.has-error .checkbox-inline {
color: #a94442;
}
.has-error .form-control {
border-color: #a94442;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
}
.has-error .form-control:focus {
border-color: #843534;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #ce8483;
box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #ce8483;
}
.has-error .input-group-addon {
color: #a94442;
background-color: #f2dede;
border-color: #a94442;
}
.has-error .form-control-feedback {
color: #a94442;
}
.has-feedback label.sr-only ~ .form-control-feedback {
top: 0;
}
.help-block {
display: block;
margin-top: 5px;
margin-bottom: 10px;
color: #737373;
}
@media (min-width: 768px) {
.form-inline .form-group {
display: inline-block;
margin-bottom: 0;
vertical-align: middle;
}
.form-inline .form-control {
display: inline-block;
width: auto;
vertical-align: middle;
}
.form-inline .input-group {
display: inline-table;
vertical-align: middle;
}
.form-inline .input-group .input-group-addon,
.form-inline .input-group .input-group-btn,
.form-inline .input-group .form-control {
width: auto;
}
.form-inline .input-group > .form-control {
width: 100%;
}
.form-inline .control-label {
margin-bottom: 0;
vertical-align: middle;
}
.form-inline .radio,
.form-inline .checkbox {
display: inline-block;
margin-top: 0;
margin-bottom: 0;
vertical-align: middle;
}
.form-inline .radio label,
.form-inline .checkbox label {
padding-left: 0;
}
.form-inline .radio input[type="radio"],
.form-inline .checkbox input[type="checkbox"] {
position: relative;
margin-left: 0;
}
.form-inline .has-feedback .form-control-feedback {
top: 0;
}
}
.form-horizontal .radio,
.form-horizontal .checkbox,
.form-horizontal .radio-inline,
.form-horizontal .checkbox-inline {
padding-top: 7px;
margin-top: 0;
margin-bottom: 0;
}
.form-horizontal .radio,
.form-horizontal .checkbox {
min-height: 27px;
}
.form-horizontal .form-group {
margin-right: -15px;
margin-left: -15px;
}
@media (min-width: 768px) {
.form-horizontal .control-label {
padding-top: 7px;
margin-bottom: 0;
text-align: right;
}
}
.form-horizontal .has-feedback .form-control-feedback {
top: 0;
right: 15px;
}
@media (min-width: 768px) {
.form-horizontal .form-group-lg .control-label {
padding-top: 14.3px;
}
}
@media (min-width: 768px) {
.form-horizontal .form-group-sm .control-label {
padding-top: 6px;
}
}
.btn {
display: inline-block;
padding: 6px 12px;
margin-bottom: 0;
font-size: 14px;
font-weight: normal;
line-height: 1.42857143;
text-align: center;
white-space: nowrap;
vertical-align: middle;
cursor: pointer;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
background-image: none;
border: 1px solid transparent;
border-radius: 4px;
}
.btn:focus,
.btn:active:focus,
.btn.active:focus {
outline: thin dotted;
outline: 5px auto -webkit-focus-ring-color;
outline-offset: -2px;
}
.btn:hover,
.btn:focus {
color: #333;
text-decoration: none;
}
.btn:active,
.btn.active {
background-image: none;
outline: 0;
-webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, .125);
box-shadow: inset 0 3px 5px rgba(0, 0, 0, .125);
}
.btn.disabled,
.btn[disabled],
fieldset[disabled] .btn {
pointer-events: none;
cursor: not-allowed;
filter: alpha(opacity=65);
-webkit-box-shadow: none;
box-shadow: none;
opacity: .65;
}
.btn-default {
color: #333;
background-color: #fff;
border-color: #ccc;
}
.btn-default:hover,
.btn-default:focus,
.btn-default:active,
.btn-default.active,
.open > .dropdown-toggle.btn-default {
color: #333;
background-color: #e6e6e6;
border-color: #adadad;
}
.btn-default:active,
.btn-default.active,
.open > .dropdown-toggle.btn-default {
background-image: none;
}
.btn-default.disabled,
.btn-default[disabled],
fieldset[disabled] .btn-default,
.btn-default.disabled:hover,
.btn-default[disabled]:hover,
fieldset[disabled] .btn-default:hover,
.btn-default.disabled:focus,
.btn-default[disabled]:focus,
fieldset[disabled] .btn-default:focus,
.btn-default.disabled:active,
.btn-default[disabled]:active,
fieldset[disabled] .btn-default:active,
.btn-default.disabled.active,
.btn-default[disabled].active,
fieldset[disabled] .btn-default.active {
background-color: #fff;
border-color: #ccc;
}
.btn-default .badge {
color: #fff;
background-color: #333;
}
.btn-primary {
color: #fff;
background-color: #428bca;
border-color: #357ebd;
}
.btn-primary:hover,
.btn-primary:focus,
.btn-primary:active,
.btn-primary.active,
.open > .dropdown-toggle.btn-primary {
color: #fff;
background-color: #3071a9;
border-color: #285e8e;
}
.btn-primary:active,
.btn-primary.active,
.open > .dropdown-toggle.btn-primary {
background-image: none;
}
.btn-primary.disabled,
.btn-primary[disabled],
fieldset[disabled] .btn-primary,
.btn-primary.disabled:hover,
.btn-primary[disabled]:hover,
fieldset[disabled] .btn-primary:hover,
.btn-primary.disabled:focus,
.btn-primary[disabled]:focus,
fieldset[disabled] .btn-primary:focus,
.btn-primary.disabled:active,
.btn-primary[disabled]:active,
fieldset[disabled] .btn-primary:active,
.btn-primary.disabled.active,
.btn-primary[disabled].active,
fieldset[disabled] .btn-primary.active {
background-color: #428bca;
border-color: #357ebd;
}
.btn-primary .badge {
color: #428bca;
background-color: #fff;
}
.btn-success {
color: #fff;
background-color: #5cb85c;
border-color: #4cae4c;
}
.btn-success:hover,
.btn-success:focus,
.btn-success:active,
.btn-success.active,
.open > .dropdown-toggle.btn-success {
color: #fff;
background-color: #449d44;
border-color: #398439;
}
.btn-success:active,
.btn-success.active,
.open > .dropdown-toggle.btn-success {
background-image: none;
}
.btn-success.disabled,
.btn-success[disabled],
fieldset[disabled] .btn-success,
.btn-success.disabled:hover,
.btn-success[disabled]:hover,
fieldset[disabled] .btn-success:hover,
.btn-success.disabled:focus,
.btn-success[disabled]:focus,
fieldset[disabled] .btn-success:focus,
.btn-success.disabled:active,
.btn-success[disabled]:active,
fieldset[disabled] .btn-success:active,
.btn-success.disabled.active,
.btn-success[disabled].active,
fieldset[disabled] .btn-success.active {
background-color: #5cb85c;
border-color: #4cae4c;
}
.btn-success .badge {
color: #5cb85c;
background-color: #fff;
}
.btn-info {
color: #fff;
background-color: #5bc0de;
border-color: #46b8da;
}
.btn-info:hover,
.btn-info:focus,
.btn-info:active,
.btn-info.active,
.open > .dropdown-toggle.btn-info {
color: #fff;
background-color: #31b0d5;
border-color: #269abc;
}
.btn-info:active,
.btn-info.active,
.open > .dropdown-toggle.btn-info {
background-image: none;
}
.btn-info.disabled,
.btn-info[disabled],
fieldset[disabled] .btn-info,
.btn-info.disabled:hover,
.btn-info[disabled]:hover,
fieldset[disabled] .btn-info:hover,
.btn-info.disabled:focus,
.btn-info[disabled]:focus,
fieldset[disabled] .btn-info:focus,
.btn-info.disabled:active,
.btn-info[disabled]:active,
fieldset[disabled] .btn-info:active,
.btn-info.disabled.active,
.btn-info[disabled].active,
fieldset[disabled] .btn-info.active {
background-color: #5bc0de;
border-color: #46b8da;
}
.btn-info .badge {
color: #5bc0de;
background-color: #fff;
}
.btn-warning {
color: #fff;
background-color: #f0ad4e;
border-color: #eea236;
}
.btn-warning:hover,
.btn-warning:focus,
.btn-warning:active,
.btn-warning.active,
.open > .dropdown-toggle.btn-warning {
color: #fff;
background-color: #ec971f;
border-color: #d58512;
}
.btn-warning:active,
.btn-warning.active,
.open > .dropdown-toggle.btn-warning {
background-image: none;
}
.btn-warning.disabled,
.btn-warning[disabled],
fieldset[disabled] .btn-warning,
.btn-warning.disabled:hover,
.btn-warning[disabled]:hover,
fieldset[disabled] .btn-warning:hover,
.btn-warning.disabled:focus,
.btn-warning[disabled]:focus,
fieldset[disabled] .btn-warning:focus,
.btn-warning.disabled:active,
.btn-warning[disabled]:active,
fieldset[disabled] .btn-warning:active,
.btn-warning.disabled.active,
.btn-warning[disabled].active,
fieldset[disabled] .btn-warning.active {
background-color: #f0ad4e;
border-color: #eea236;
}
.btn-warning .badge {
color: #f0ad4e;
background-color: #fff;
}
.btn-danger {
color: #fff;
background-color: #d9534f;
border-color: #d43f3a;
}
.btn-danger:hover,
.btn-danger:focus,
.btn-danger:active,
.btn-danger.active,
.open > .dropdown-toggle.btn-danger {
color: #fff;
background-color: #c9302c;
border-color: #ac2925;
}
.btn-danger:active,
.btn-danger.active,
.open > .dropdown-toggle.btn-danger {
background-image: none;
}
.btn-danger.disabled,
.btn-danger[disabled],
fieldset[disabled] .btn-danger,
.btn-danger.disabled:hover,
.btn-danger[disabled]:hover,
fieldset[disabled] .btn-danger:hover,
.btn-danger.disabled:focus,
.btn-danger[disabled]:focus,
fieldset[disabled] .btn-danger:focus,
.btn-danger.disabled:active,
.btn-danger[disabled]:active,
fieldset[disabled] .btn-danger:active,
.btn-danger.disabled.active,
.btn-danger[disabled].active,
fieldset[disabled] .btn-danger.active {
background-color: #d9534f;
border-color: #d43f3a;
}
.btn-danger .badge {
color: #d9534f;
background-color: #fff;
}
.btn-link {
font-weight: normal;
color: #428bca;
cursor: pointer;
border-radius: 0;
}
.btn-link,
.btn-link:active,
.btn-link[disabled],
fieldset[disabled] .btn-link {
background-color: transparent;
-webkit-box-shadow: none;
box-shadow: none;
}
.btn-link,
.btn-link:hover,
.btn-link:focus,
.btn-link:active {
border-color: transparent;
}
.btn-link:hover,
.btn-link:focus {
color: #2a6496;
text-decoration: underline;
background-color: transparent;
}
.btn-link[disabled]:hover,
fieldset[disabled] .btn-link:hover,
.btn-link[disabled]:focus,
fieldset[disabled] .btn-link:focus {
color: #777;
text-decoration: none;
}
.btn-lg,
.btn-group-lg > .btn {
padding: 10px 16px;
font-size: 18px;
line-height: 1.33;
border-radius: 6px;
}
.btn-sm,
.btn-group-sm > .btn {
padding: 5px 10px;
font-size: 12px;
line-height: 1.5;
border-radius: 3px;
}
.btn-xs,
.btn-group-xs > .btn {
padding: 1px 5px;
font-size: 12px;
line-height: 1.5;
border-radius: 3px;
}
.btn-block {
display: block;
width: 100%;
}
.btn-block + .btn-block {
margin-top: 5px;
}
input[type="submit"].btn-block,
input[type="reset"].btn-block,
input[type="button"].btn-block {
width: 100%;
}
.fade {
opacity: 0;
-webkit-transition: opacity .15s linear;
-o-transition: opacity .15s linear;
transition: opacity .15s linear;
}
.fade.in {
opacity: 1;
}
.collapse {
display: none;
}
.collapse.in {
display: block;
}
tr.collapse.in {
display: table-row;
}
tbody.collapse.in {
display: table-row-group;
}
.collapsing {
position: relative;
height: 0;
overflow: hidden;
-webkit-transition: height .35s ease;
-o-transition: height .35s ease;
transition: height .35s ease;
}
.caret {
display: inline-block;
width: 0;
height: 0;
margin-left: 2px;
vertical-align: middle;
border-top: 4px solid;
border-right: 4px solid transparent;
border-left: 4px solid transparent;
}
.dropdown {
position: relative;
}
.dropdown-toggle:focus {
outline: 0;
}
.dropdown-menu {
position: absolute;
top: 100%;
left: 0;
z-index: 1000;
display: none;
float: left;
min-width: 160px;
padding: 5px 0;
margin: 2px 0 0;
font-size: 14px;
text-align: left;
list-style: none;
background-color: #fff;
-webkit-background-clip: padding-box;
background-clip: padding-box;
border: 1px solid #ccc;
border: 1px solid rgba(0, 0, 0, .15);
border-radius: 4px;
-webkit-box-shadow: 0 6px 12px rgba(0, 0, 0, .175);
box-shadow: 0 6px 12px rgba(0, 0, 0, .175);
}
.dropdown-menu.pull-right {
right: 0;
left: auto;
}
.dropdown-menu .divider {
height: 1px;
margin: 9px 0;
overflow: hidden;
background-color: #e5e5e5;
}
.dropdown-menu > li > a {
display: block;
padding: 3px 20px;
clear: both;
font-weight: normal;
line-height: 1.42857143;
color: #333;
white-space: nowrap;
}
.dropdown-menu > li > a:hover,
.dropdown-menu > li > a:focus {
color: #262626;
text-decoration: none;
background-color: #f5f5f5;
}
.dropdown-menu > .active > a,
.dropdown-menu > .active > a:hover,
.dropdown-menu > .active > a:focus {
color: #fff;
text-decoration: none;
background-color: #428bca;
outline: 0;
}
.dropdown-menu > .disabled > a,
.dropdown-menu > .disabled > a:hover,
.dropdown-menu > .disabled > a:focus {
color: #777;
}
.dropdown-menu > .disabled > a:hover,
.dropdown-menu > .disabled > a:focus {
text-decoration: none;
cursor: not-allowed;
background-color: transparent;
background-image: none;
filter: progid:DXImageTransform.Microsoft.gradient(enabled = false);
}
.open > .dropdown-menu {
display: block;
}
.open > a {
outline: 0;
}
.dropdown-menu-right {
right: 0;
left: auto;
}
.dropdown-menu-left {
right: auto;
left: 0;
}
.dropdown-header {
display: block;
padding: 3px 20px;
font-size: 12px;
line-height: 1.42857143;
color: #777;
white-space: nowrap;
}
.dropdown-backdrop {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 990;
}
.pull-right > .dropdown-menu {
right: 0;
left: auto;
}
.dropup .caret,
.navbar-fixed-bottom .dropdown .caret {
content: "";
border-top: 0;
border-bottom: 4px solid;
}
.dropup .dropdown-menu,
.navbar-fixed-bottom .dropdown .dropdown-menu {
top: auto;
bottom: 100%;
margin-bottom: 1px;
}
@media (min-width: 768px) {
.navbar-right .dropdown-menu {
right: 0;
left: auto;
}
.navbar-right .dropdown-menu-left {
right: auto;
left: 0;
}
}
.btn-group,
.btn-group-vertical {
position: relative;
display: inline-block;
vertical-align: middle;
}
.btn-group > .btn,
.btn-group-vertical > .btn {
position: relative;
float: left;
}
.btn-group > .btn:hover,
.btn-group-vertical > .btn:hover,
.btn-group > .btn:focus,
.btn-group-vertical > .btn:focus,
.btn-group > .btn:active,
.btn-group-vertical > .btn:active,
.btn-group > .btn.active,
.btn-group-vertical > .btn.active {
z-index: 2;
}
.btn-group > .btn:focus,
.btn-group-vertical > .btn:focus {
outline: 0;
}
.btn-group .btn + .btn,
.btn-group .btn + .btn-group,
.btn-group .btn-group + .btn,
.btn-group .btn-group + .btn-group {
margin-left: -1px;
}
.btn-toolbar {
margin-left: -5px;
}
.btn-toolbar .btn-group,
.btn-toolbar .input-group {
float: left;
}
.btn-toolbar > .btn,
.btn-toolbar > .btn-group,
.btn-toolbar > .input-group {
margin-left: 5px;
}
.btn-group > .btn:not(:first-child):not(:last-child):not(.dropdown-toggle) {
border-radius: 0;
}
.btn-group > .btn:first-child {
margin-left: 0;
}
.btn-group > .btn:first-child:not(:last-child):not(.dropdown-toggle) {
border-top-right-radius: 0;
border-bottom-right-radius: 0;
}
.btn-group > .btn:last-child:not(:first-child),
.btn-group > .dropdown-toggle:not(:first-child) {
border-top-left-radius: 0;
border-bottom-left-radius: 0;
}
.btn-group > .btn-group {
float: left;
}
.btn-group > .btn-group:not(:first-child):not(:last-child) > .btn {
border-radius: 0;
}
.btn-group > .btn-group:first-child > .btn:last-child,
.btn-group > .btn-group:first-child > .dropdown-toggle {
border-top-right-radius: 0;
border-bottom-right-radius: 0;
}
.btn-group > .btn-group:last-child > .btn:first-child {
border-top-left-radius: 0;
border-bottom-left-radius: 0;
}
.btn-group .dropdown-toggle:active,
.btn-group.open .dropdown-toggle {
outline: 0;
}
.btn-group > .btn + .dropdown-toggle {
padding-right: 8px;
padding-left: 8px;
}
.btn-group > .btn-lg + .dropdown-toggle {
padding-right: 12px;
padding-left: 12px;
}
.btn-group.open .dropdown-toggle {
-webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, .125);
box-shadow: inset 0 3px 5px rgba(0, 0, 0, .125);
}
.btn-group.open .dropdown-toggle.btn-link {
-webkit-box-shadow: none;
box-shadow: none;
}
.btn .caret {
margin-left: 0;
}
.btn-lg .caret {
border-width: 5px 5px 0;
border-bottom-width: 0;
}
.dropup .btn-lg .caret {
border-width: 0 5px 5px;
}
.btn-group-vertical > .btn,
.btn-group-vertical > .btn-group,
.btn-group-vertical > .btn-group > .btn {
display: block;
float: none;
width: 100%;
max-width: 100%;
}
.btn-group-vertical > .btn-group > .btn {
float: none;
}
.btn-group-vertical > .btn + .btn,
.btn-group-vertical > .btn + .btn-group,
.btn-group-vertical > .btn-group + .btn,
.btn-group-vertical > .btn-group + .btn-group {
margin-top: -1px;
margin-left: 0;
}
.btn-group-vertical > .btn:not(:first-child):not(:last-child) {
border-radius: 0;
}
.btn-group-vertical > .btn:first-child:not(:last-child) {
border-top-right-radius: 4px;
border-bottom-right-radius: 0;
border-bottom-left-radius: 0;
}
.btn-group-vertical > .btn:last-child:not(:first-child) {
border-top-left-radius: 0;
border-top-right-radius: 0;
border-bottom-left-radius: 4px;
}
.btn-group-vertical > .btn-group:not(:first-child):not(:last-child) > .btn {
border-radius: 0;
}
.btn-group-vertical > .btn-group:first-child:not(:last-child) > .btn:last-child,
.btn-group-vertical > .btn-group:first-child:not(:last-child) > .dropdown-toggle {
border-bottom-right-radius: 0;
border-bottom-left-radius: 0;
}
.btn-group-vertical > .btn-group:last-child:not(:first-child) > .btn:first-child {
border-top-left-radius: 0;
border-top-right-radius: 0;
}
.btn-group-justified {
display: table;
width: 100%;
table-layout: fixed;
border-collapse: separate;
}
.btn-group-justified > .btn,
.btn-group-justified > .btn-group {
display: table-cell;
float: none;
width: 1%;
}
.btn-group-justified > .btn-group .btn {
width: 100%;
}
.btn-group-justified > .btn-group .dropdown-menu {
left: auto;
}
[data-toggle="buttons"] > .btn > input[type="radio"],
[data-toggle="buttons"] > .btn > input[type="checkbox"] {
position: absolute;
z-index: -1;
filter: alpha(opacity=0);
opacity: 0;
}
.input-group {
position: relative;
display: table;
border-collapse: separate;
}
.input-group[class*="col-"] {
float: none;
padding-right: 0;
padding-left: 0;
}
.input-group .form-control {
position: relative;
z-index: 2;
float: left;
width: 100%;
margin-bottom: 0;
}
.input-group-lg > .form-control,
.input-group-lg > .input-group-addon,
.input-group-lg > .input-group-btn > .btn {
height: 46px;
padding: 10px 16px;
font-size: 18px;
line-height: 1.33;
border-radius: 6px;
}
select.input-group-lg > .form-control,
select.input-group-lg > .input-group-addon,
select.input-group-lg > .input-group-btn > .btn {
height: 46px;
line-height: 46px;
}
textarea.input-group-lg > .form-control,
textarea.input-group-lg > .input-group-addon,
textarea.input-group-lg > .input-group-btn > .btn,
select[multiple].input-group-lg > .form-control,
select[multiple].input-group-lg > .input-group-addon,
select[multiple].input-group-lg > .input-group-btn > .btn {
height: auto;
}
.input-group-sm > .form-control,
.input-group-sm > .input-group-addon,
.input-group-sm > .input-group-btn > .btn {
height: 30px;
padding: 5px 10px;
font-size: 12px;
line-height: 1.5;
border-radius: 3px;
}
select.input-group-sm > .form-control,
select.input-group-sm > .input-group-addon,
select.input-group-sm > .input-group-btn > .btn {
height: 30px;
line-height: 30px;
}
textarea.input-group-sm > .form-control,
textarea.input-group-sm > .input-group-addon,
textarea.input-group-sm > .input-group-btn > .btn,
select[multiple].input-group-sm > .form-control,
select[multiple].input-group-sm > .input-group-addon,
select[multiple].input-group-sm > .input-group-btn > .btn {
height: auto;
}
.input-group-addon,
.input-group-btn,
.input-group .form-control {
display: table-cell;
}
.input-group-addon:not(:first-child):not(:last-child),
.input-group-btn:not(:first-child):not(:last-child),
.input-group .form-control:not(:first-child):not(:last-child) {
border-radius: 0;
}
.input-group-addon,
.input-group-btn {
width: 1%;
white-space: nowrap;
vertical-align: middle;
}
.input-group-addon {
padding: 6px 12px;
font-size: 14px;
font-weight: normal;
line-height: 1;
color: #555;
text-align: center;
background-color: #eee;
border: 1px solid #ccc;
border-radius: 4px;
}
.input-group-addon.input-sm {
padding: 5px 10px;
font-size: 12px;
border-radius: 3px;
}
.input-group-addon.input-lg {
padding: 10px 16px;
font-size: 18px;
border-radius: 6px;
}
.input-group-addon input[type="radio"],
.input-group-addon input[type="checkbox"] {
margin-top: 0;
}
.input-group .form-control:first-child,
.input-group-addon:first-child,
.input-group-btn:first-child > .btn,
.input-group-btn:first-child > .btn-group > .btn,
.input-group-btn:first-child > .dropdown-toggle,
.input-group-btn:last-child > .btn:not(:last-child):not(.dropdown-toggle),
.input-group-btn:last-child > .btn-group:not(:last-child) > .btn {
border-top-right-radius: 0;
border-bottom-right-radius: 0;
}
.input-group-addon:first-child {
border-right: 0;
}
.input-group .form-control:last-child,
.input-group-addon:last-child,
.input-group-btn:last-child > .btn,
.input-group-btn:last-child > .btn-group > .btn,
.input-group-btn:last-child > .dropdown-toggle,
.input-group-btn:first-child > .btn:not(:first-child),
.input-group-btn:first-child > .btn-group:not(:first-child) > .btn {
border-top-left-radius: 0;
border-bottom-left-radius: 0;
}
.input-group-addon:last-child {
border-left: 0;
}
.input-group-btn {
position: relative;
font-size: 0;
white-space: nowrap;
}
.input-group-btn > .btn {
position: relative;
}
.input-group-btn > .btn + .btn {
margin-left: -1px;
}
.input-group-btn > .btn:hover,
.input-group-btn > .btn:focus,
.input-group-btn > .btn:active {
z-index: 2;
}
.input-group-btn:first-child > .btn,
.input-group-btn:first-child > .btn-group {
margin-right: -1px;
}
.input-group-btn:last-child > .btn,
.input-group-btn:last-child > .btn-group {
margin-left: -1px;
}
.nav {
padding-left: 0;
margin-bottom: 0;
list-style: none;
}
.nav > li {
position: relative;
display: block;
}
.nav > li > a {
position: relative;
display: block;
padding: 10px 15px;
}
.nav > li > a:hover,
.nav > li > a:focus {
text-decoration: none;
background-color: #eee;
}
.nav > li.disabled > a {
color: #777;
}
.nav > li.disabled > a:hover,
.nav > li.disabled > a:focus {
color: #777;
text-decoration: none;
cursor: not-allowed;
background-color: transparent;
}
.nav .open > a,
.nav .open > a:hover,
.nav .open > a:focus {
background-color: #eee;
border-color: #428bca;
}
.nav .nav-divider {
height: 1px;
margin: 9px 0;
overflow: hidden;
background-color: #e5e5e5;
}
.nav > li > a > img {
max-width: none;
}
.nav-tabs {
border-bottom: 1px solid #ddd;
}
.nav-tabs > li {
float: left;
margin-bottom: -1px;
}
.nav-tabs > li > a {
margin-right: 2px;
line-height: 1.42857143;
border: 1px solid transparent;
border-radius: 4px 4px 0 0;
}
.nav-tabs > li > a:hover {
border-color: #eee #eee #ddd;
}
.nav-tabs > li.active > a,
.nav-tabs > li.active > a:hover,
.nav-tabs > li.active > a:focus {
color: #555;
cursor: default;
background-color: #fff;
border: 1px solid #ddd;
border-bottom-color: transparent;
}
.nav-tabs.nav-justified {
width: 100%;
border-bottom: 0;
}
.nav-tabs.nav-justified > li {
float: none;
}
.nav-tabs.nav-justified > li > a {
margin-bottom: 5px;
text-align: center;
}
.nav-tabs.nav-justified > .dropdown .dropdown-menu {
top: auto;
left: auto;
}
@media (min-width: 768px) {
.nav-tabs.nav-justified > li {
display: table-cell;
width: 1%;
}
.nav-tabs.nav-justified > li > a {
margin-bottom: 0;
}
}
.nav-tabs.nav-justified > li > a {
margin-right: 0;
border-radius: 4px;
}
.nav-tabs.nav-justified > .active > a,
.nav-tabs.nav-justified > .active > a:hover,
.nav-tabs.nav-justified > .active > a:focus {
border: 1px solid #ddd;
}
@media (min-width: 768px) {
.nav-tabs.nav-justified > li > a {
border-bottom: 1px solid #ddd;
border-radius: 4px 4px 0 0;
}
.nav-tabs.nav-justified > .active > a,
.nav-tabs.nav-justified > .active > a:hover,
.nav-tabs.nav-justified > .active > a:focus {
border-bottom-color: #fff;
}
}
.nav-pills > li {
float: left;
}
.nav-pills > li > a {
border-radius: 4px;
}
.nav-pills > li + li {
margin-left: 2px;
}
.nav-pills > li.active > a,
.nav-pills > li.active > a:hover,
.nav-pills > li.active > a:focus {
color: #fff;
background-color: #428bca;
}
.nav-stacked > li {
float: none;
}
.nav-stacked > li + li {
margin-top: 2px;
margin-left: 0;
}
.nav-justified {
width: 100%;
}
.nav-justified > li {
float: none;
}
.nav-justified > li > a {
margin-bottom: 5px;
text-align: center;
}
.nav-justified > .dropdown .dropdown-menu {
top: auto;
left: auto;
}
@media (min-width: 768px) {
.nav-justified > li {
display: table-cell;
width: 1%;
}
.nav-justified > li > a {
margin-bottom: 0;
}
}
.nav-tabs-justified {
border-bottom: 0;
}
.nav-tabs-justified > li > a {
margin-right: 0;
border-radius: 4px;
}
.nav-tabs-justified > .active > a,
.nav-tabs-justified > .active > a:hover,
.nav-tabs-justified > .active > a:focus {
border: 1px solid #ddd;
}
@media (min-width: 768px) {
.nav-tabs-justified > li > a {
border-bottom: 1px solid #ddd;
border-radius: 4px 4px 0 0;
}
.nav-tabs-justified > .active > a,
.nav-tabs-justified > .active > a:hover,
.nav-tabs-justified > .active > a:focus {
border-bottom-color: #fff;
}
}
.tab-content > .tab-pane {
display: none;
}
.tab-content > .active {
display: block;
}
.nav-tabs .dropdown-menu {
margin-top: -1px;
border-top-left-radius: 0;
border-top-right-radius: 0;
}
.navbar {
position: relative;
min-height: 50px;
margin-bottom: 20px;
border: 1px solid transparent;
}
@media (min-width: 768px) {
.navbar {
border-radius: 4px;
}
}
@media (min-width: 768px) {
.navbar-header {
float: left;
}
}
.navbar-collapse {
padding-right: 15px;
padding-left: 15px;
overflow-x: visible;
-webkit-overflow-scrolling: touch;
border-top: 1px solid transparent;
-webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, .1);
box-shadow: inset 0 1px 0 rgba(255, 255, 255, .1);
}
.navbar-collapse.in {
overflow-y: auto;
}
@media (min-width: 768px) {
.navbar-collapse {
width: auto;
border-top: 0;
-webkit-box-shadow: none;
box-shadow: none;
}
.navbar-collapse.collapse {
display: block !important;
height: auto !important;
padding-bottom: 0;
overflow: visible !important;
}
.navbar-collapse.in {
overflow-y: visible;
}
.navbar-fixed-top .navbar-collapse,
.navbar-static-top .navbar-collapse,
.navbar-fixed-bottom .navbar-collapse {
padding-right: 0;
padding-left: 0;
}
}
.navbar-fixed-top .navbar-collapse,
.navbar-fixed-bottom .navbar-collapse {
max-height: 340px;
}
@media (max-width: 480px) and (orientation: landscape) {
.navbar-fixed-top .navbar-collapse,
.navbar-fixed-bottom .navbar-collapse {
max-height: 200px;
}
}
.container > .navbar-header,
.container-fluid > .navbar-header,
.container > .navbar-collapse,
.container-fluid > .navbar-collapse {
margin-right: -15px;
margin-left: -15px;
}
@media (min-width: 768px) {
.container > .navbar-header,
.container-fluid > .navbar-header,
.container > .navbar-collapse,
.container-fluid > .navbar-collapse {
margin-right: 0;
margin-left: 0;
}
}
.navbar-static-top {
z-index: 1000;
border-width: 0 0 1px;
}
@media (min-width: 768px) {
.navbar-static-top {
border-radius: 0;
}
}
.navbar-fixed-top,
.navbar-fixed-bottom {
position: fixed;
right: 0;
left: 0;
z-index: 1030;
-webkit-transform: translate3d(0, 0, 0);
-o-transform: translate3d(0, 0, 0);
transform: translate3d(0, 0, 0);
}
@media (min-width: 768px) {
.navbar-fixed-top,
.navbar-fixed-bottom {
border-radius: 0;
}
}
.navbar-fixed-top {
top: 0;
border-width: 0 0 1px;
}
.navbar-fixed-bottom {
bottom: 0;
margin-bottom: 0;
border-width: 1px 0 0;
}
.navbar-brand {
float: left;
height: 50px;
padding: 15px 15px;
font-size: 18px;
line-height: 20px;
}
.navbar-brand:hover,
.navbar-brand:focus {
text-decoration: none;
}
@media (min-width: 768px) {
.navbar > .container .navbar-brand,
.navbar > .container-fluid .navbar-brand {
margin-left: -15px;
}
}
.navbar-toggle {
position: relative;
float: right;
padding: 9px 10px;
margin-top: 8px;
margin-right: 15px;
margin-bottom: 8px;
background-color: transparent;
background-image: none;
border: 1px solid transparent;
border-radius: 4px;
}
.navbar-toggle:focus {
outline: 0;
}
.navbar-toggle .icon-bar {
display: block;
width: 22px;
height: 2px;
border-radius: 1px;
}
.navbar-toggle .icon-bar + .icon-bar {
margin-top: 4px;
}
@media (min-width: 768px) {
.navbar-toggle {
display: none;
}
}
.navbar-nav {
margin: 7.5px -15px;
}
.navbar-nav > li > a {
padding-top: 10px;
padding-bottom: 10px;
line-height: 20px;
}
@media (max-width: 767px) {
.navbar-nav .open .dropdown-menu {
position: static;
float: none;
width: auto;
margin-top: 0;
background-color: transparent;
border: 0;
-webkit-box-shadow: none;
box-shadow: none;
}
.navbar-nav .open .dropdown-menu > li > a,
.navbar-nav .open .dropdown-menu .dropdown-header {
padding: 5px 15px 5px 25px;
}
.navbar-nav .open .dropdown-menu > li > a {
line-height: 20px;
}
.navbar-nav .open .dropdown-menu > li > a:hover,
.navbar-nav .open .dropdown-menu > li > a:focus {
background-image: none;
}
}
@media (min-width: 768px) {
.navbar-nav {
float: left;
margin: 0;
}
.navbar-nav > li {
float: left;
}
.navbar-nav > li > a {
padding-top: 15px;
padding-bottom: 15px;
}
.navbar-nav.navbar-right:last-child {
margin-right: -15px;
}
}
@media (min-width: 768px) {
.navbar-left {
float: left !important;
}
.navbar-right {
float: right !important;
}
}
.navbar-form {
padding: 10px 15px;
margin-top: 8px;
margin-right: -15px;
margin-bottom: 8px;
margin-left: -15px;
border-top: 1px solid transparent;
border-bottom: 1px solid transparent;
-webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, .1), 0 1px 0 rgba(255, 255, 255, .1);
box-shadow: inset 0 1px 0 rgba(255, 255, 255, .1), 0 1px 0 rgba(255, 255, 255, .1);
}
@media (min-width: 768px) {
.navbar-form .form-group {
display: inline-block;
margin-bottom: 0;
vertical-align: middle;
}
.navbar-form .form-control {
display: inline-block;
width: auto;
vertical-align: middle;
}
.navbar-form .input-group {
display: inline-table;
vertical-align: middle;
}
.navbar-form .input-group .input-group-addon,
.navbar-form .input-group .input-group-btn,
.navbar-form .input-group .form-control {
width: auto;
}
.navbar-form .input-group > .form-control {
width: 100%;
}
.navbar-form .control-label {
margin-bottom: 0;
vertical-align: middle;
}
.navbar-form .radio,
.navbar-form .checkbox {
display: inline-block;
margin-top: 0;
margin-bottom: 0;
vertical-align: middle;
}
.navbar-form .radio label,
.navbar-form .checkbox label {
padding-left: 0;
}
.navbar-form .radio input[type="radio"],
.navbar-form .checkbox input[type="checkbox"] {
position: relative;
margin-left: 0;
}
.navbar-form .has-feedback .form-control-feedback {
top: 0;
}
}
@media (max-width: 767px) {
.navbar-form .form-group {
margin-bottom: 5px;
}
}
@media (min-width: 768px) {
.navbar-form {
width: auto;
padding-top: 0;
padding-bottom: 0;
margin-right: 0;
margin-left: 0;
border: 0;
-webkit-box-shadow: none;
box-shadow: none;
}
.navbar-form.navbar-right:last-child {
margin-right: -15px;
}
}
.navbar-nav > li > .dropdown-menu {
margin-top: 0;
border-top-left-radius: 0;
border-top-right-radius: 0;
}
.navbar-fixed-bottom .navbar-nav > li > .dropdown-menu {
border-bottom-right-radius: 0;
border-bottom-left-radius: 0;
}
.navbar-btn {
margin-top: 8px;
margin-bottom: 8px;
}
.navbar-btn.btn-sm {
margin-top: 10px;
margin-bottom: 10px;
}
.navbar-btn.btn-xs {
margin-top: 14px;
margin-bottom: 14px;
}
.navbar-text {
margin-top: 15px;
margin-bottom: 15px;
}
@media (min-width: 768px) {
.navbar-text {
float: left;
margin-right: 15px;
margin-left: 15px;
}
.navbar-text.navbar-right:last-child {
margin-right: 0;
}
}
.navbar-default {
background-color: #f8f8f8;
border-color: #e7e7e7;
}
.navbar-default .navbar-brand {
color: #777;
}
.navbar-default .navbar-brand:hover,
.navbar-default .navbar-brand:focus {
color: #5e5e5e;
background-color: transparent;
}
.navbar-default .navbar-text {
color: #777;
}
.navbar-default .navbar-nav > li > a {
color: #777;
}
.navbar-default .navbar-nav > li > a:hover,
.navbar-default .navbar-nav > li > a:focus {
color: #333;
background-color: transparent;
}
.navbar-default .navbar-nav > .active > a,
.navbar-default .navbar-nav > .active > a:hover,
.navbar-default .navbar-nav > .active > a:focus {
color: #555;
background-color: #e7e7e7;
}
.navbar-default .navbar-nav > .disabled > a,
.navbar-default .navbar-nav > .disabled > a:hover,
.navbar-default .navbar-nav > .disabled > a:focus {
color: #ccc;
background-color: transparent;
}
.navbar-default .navbar-toggle {
border-color: #ddd;
}
.navbar-default .navbar-toggle:hover,
.navbar-default .navbar-toggle:focus {
background-color: #ddd;
}
.navbar-default .navbar-toggle .icon-bar {
background-color: #888;
}
.navbar-default .navbar-collapse,
.navbar-default .navbar-form {
border-color: #e7e7e7;
}
.navbar-default .navbar-nav > .open > a,
.navbar-default .navbar-nav > .open > a:hover,
.navbar-default .navbar-nav > .open > a:focus {
color: #555;
background-color: #e7e7e7;
}
@media (max-width: 767px) {
.navbar-default .navbar-nav .open .dropdown-menu > li > a {
color: #777;
}
.navbar-default .navbar-nav .open .dropdown-menu > li > a:hover,
.navbar-default .navbar-nav .open .dropdown-menu > li > a:focus {
color: #333;
background-color: transparent;
}
.navbar-default .navbar-nav .open .dropdown-menu > .active > a,
.navbar-default .navbar-nav .open .dropdown-menu > .active > a:hover,
.navbar-default .navbar-nav .open .dropdown-menu > .active > a:focus {
color: #555;
background-color: #e7e7e7;
}
.navbar-default .navbar-nav .open .dropdown-menu > .disabled > a,
.navbar-default .navbar-nav .open .dropdown-menu > .disabled > a:hover,
.navbar-default .navbar-nav .open .dropdown-menu > .disabled > a:focus {
color: #ccc;
background-color: transparent;
}
}
.navbar-default .navbar-link {
color: #777;
}
.navbar-default .navbar-link:hover {
color: #333;
}
.navbar-default .btn-link {
color: #777;
}
.navbar-default .btn-link:hover,
.navbar-default .btn-link:focus {
color: #333;
}
.navbar-default .btn-link[disabled]:hover,
fieldset[disabled] .navbar-default .btn-link:hover,
.navbar-default .btn-link[disabled]:focus,
fieldset[disabled] .navbar-default .btn-link:focus {
color: #ccc;
}
.navbar-inverse {
background-color: #222;
border-color: #080808;
}
.navbar-inverse .navbar-brand {
color: #777;
}
.navbar-inverse .navbar-brand:hover,
.navbar-inverse .navbar-brand:focus {
color: #fff;
background-color: transparent;
}
.navbar-inverse .navbar-text {
color: #777;
}
.navbar-inverse .navbar-nav > li > a {
color: #777;
}
.navbar-inverse .navbar-nav > li > a:hover,
.navbar-inverse .navbar-nav > li > a:focus {
color: #fff;
background-color: transparent;
}
.navbar-inverse .navbar-nav > .active > a,
.navbar-inverse .navbar-nav > .active > a:hover,
.navbar-inverse .navbar-nav > .active > a:focus {
color: #fff;
background-color: #080808;
}
.navbar-inverse .navbar-nav > .disabled > a,
.navbar-inverse .navbar-nav > .disabled > a:hover,
.navbar-inverse .navbar-nav > .disabled > a:focus {
color: #444;
background-color: transparent;
}
.navbar-inverse .navbar-toggle {
border-color: #333;
}
.navbar-inverse .navbar-toggle:hover,
.navbar-inverse .navbar-toggle:focus {
background-color: #333;
}
.navbar-inverse .navbar-toggle .icon-bar {
background-color: #fff;
}
.navbar-inverse .navbar-collapse,
.navbar-inverse .navbar-form {
border-color: #101010;
}
.navbar-inverse .navbar-nav > .open > a,
.navbar-inverse .navbar-nav > .open > a:hover,
.navbar-inverse .navbar-nav > .open > a:focus {
color: #fff;
background-color: #080808;
}
@media (max-width: 767px) {
.navbar-inverse .navbar-nav .open .dropdown-menu > .dropdown-header {
border-color: #080808;
}
.navbar-inverse .navbar-nav .open .dropdown-menu .divider {
background-color: #080808;
}
.navbar-inverse .navbar-nav .open .dropdown-menu > li > a {
color: #777;
}
.navbar-inverse .navbar-nav .open .dropdown-menu > li > a:hover,
.navbar-inverse .navbar-nav .open .dropdown-menu > li > a:focus {
color: #fff;
background-color: transparent;
}
.navbar-inverse .navbar-nav .open .dropdown-menu > .active > a,
.navbar-inverse .navbar-nav .open .dropdown-menu > .active > a:hover,
.navbar-inverse .navbar-nav .open .dropdown-menu > .active > a:focus {
color: #fff;
background-color: #080808;
}
.navbar-inverse .navbar-nav .open .dropdown-menu > .disabled > a,
.navbar-inverse .navbar-nav .open .dropdown-menu > .disabled > a:hover,
.navbar-inverse .navbar-nav .open .dropdown-menu > .disabled > a:focus {
color: #444;
background-color: transparent;
}
}
.navbar-inverse .navbar-link {
color: #777;
}
.navbar-inverse .navbar-link:hover {
color: #fff;
}
.navbar-inverse .btn-link {
color: #777;
}
.navbar-inverse .btn-link:hover,
.navbar-inverse .btn-link:focus {
color: #fff;
}
.navbar-inverse .btn-link[disabled]:hover,
fieldset[disabled] .navbar-inverse .btn-link:hover,
.navbar-inverse .btn-link[disabled]:focus,
fieldset[disabled] .navbar-inverse .btn-link:focus {
color: #444;
}
.breadcrumb {
padding: 8px 15px;
margin-bottom: 20px;
list-style: none;
background-color: #f5f5f5;
border-radius: 4px;
}
.breadcrumb > li {
display: inline-block;
}
.breadcrumb > li + li:before {
padding: 0 5px;
color: #ccc;
content: "/\00a0";
}
.breadcrumb > .active {
color: #777;
}
.pagination {
display: inline-block;
padding-left: 0;
margin: 20px 0;
border-radius: 4px;
}
.pagination > li {
display: inline;
}
.pagination > li > a,
.pagination > li > span {
position: relative;
float: left;
padding: 6px 12px;
margin-left: -1px;
line-height: 1.42857143;
color: #428bca;
text-decoration: none;
background-color: #fff;
border: 1px solid #ddd;
}
.pagination > li:first-child > a,
.pagination > li:first-child > span {
margin-left: 0;
border-top-left-radius: 4px;
border-bottom-left-radius: 4px;
}
.pagination > li:last-child > a,
.pagination > li:last-child > span {
border-top-right-radius: 4px;
border-bottom-right-radius: 4px;
}
.pagination > li > a:hover,
.pagination > li > span:hover,
.pagination > li > a:focus,
.pagination > li > span:focus {
color: #2a6496;
background-color: #eee;
border-color: #ddd;
}
.pagination > .active > a,
.pagination > .active > span,
.pagination > .active > a:hover,
.pagination > .active > span:hover,
.pagination > .active > a:focus,
.pagination > .active > span:focus {
z-index: 2;
color: #fff;
cursor: default;
background-color: #428bca;
border-color: #428bca;
}
.pagination > .disabled > span,
.pagination > .disabled > span:hover,
.pagination > .disabled > span:focus,
.pagination > .disabled > a,
.pagination > .disabled > a:hover,
.pagination > .disabled > a:focus {
color: #777;
cursor: not-allowed;
background-color: #fff;
border-color: #ddd;
}
.pagination-lg > li > a,
.pagination-lg > li > span {
padding: 10px 16px;
font-size: 18px;
}
.pagination-lg > li:first-child > a,
.pagination-lg > li:first-child > span {
border-top-left-radius: 6px;
border-bottom-left-radius: 6px;
}
.pagination-lg > li:last-child > a,
.pagination-lg > li:last-child > span {
border-top-right-radius: 6px;
border-bottom-right-radius: 6px;
}
.pagination-sm > li > a,
.pagination-sm > li > span {
padding: 5px 10px;
font-size: 12px;
}
.pagination-sm > li:first-child > a,
.pagination-sm > li:first-child > span {
border-top-left-radius: 3px;
border-bottom-left-radius: 3px;
}
.pagination-sm > li:last-child > a,
.pagination-sm > li:last-child > span {
border-top-right-radius: 3px;
border-bottom-right-radius: 3px;
}
.pager {
padding-left: 0;
margin: 20px 0;
text-align: center;
list-style: none;
}
.pager li {
display: inline;
}
.pager li > a,
.pager li > span {
display: inline-block;
padding: 5px 14px;
background-color: #fff;
border: 1px solid #ddd;
border-radius: 15px;
}
.pager li > a:hover,
.pager li > a:focus {
text-decoration: none;
background-color: #eee;
}
.pager .next > a,
.pager .next > span {
float: right;
}
.pager .previous > a,
.pager .previous > span {
float: left;
}
.pager .disabled > a,
.pager .disabled > a:hover,
.pager .disabled > a:focus,
.pager .disabled > span {
color: #777;
cursor: not-allowed;
background-color: #fff;
}
.label {
display: inline;
padding: .2em .6em .3em;
font-size: 75%;
font-weight: bold;
line-height: 1;
color: #fff;
text-align: center;
white-space: nowrap;
vertical-align: baseline;
border-radius: .25em;
}
a.label:hover,
a.label:focus {
color: #fff;
text-decoration: none;
cursor: pointer;
}
.label:empty {
display: none;
}
.btn .label {
position: relative;
top: -1px;
}
.label-default {
background-color: #777;
}
.label-default[href]:hover,
.label-default[href]:focus {
background-color: #5e5e5e;
}
.label-primary {
background-color: #428bca;
}
.label-primary[href]:hover,
.label-primary[href]:focus {
background-color: #3071a9;
}
.label-success {
background-color: #5cb85c;
}
.label-success[href]:hover,
.label-success[href]:focus {
background-color: #449d44;
}
.label-info {
background-color: #5bc0de;
}
.label-info[href]:hover,
.label-info[href]:focus {
background-color: #31b0d5;
}
.label-warning {
background-color: #f0ad4e;
}
.label-warning[href]:hover,
.label-warning[href]:focus {
background-color: #ec971f;
}
.label-danger {
background-color: #d9534f;
}
.label-danger[href]:hover,
.label-danger[href]:focus {
background-color: #c9302c;
}
.badge {
display: inline-block;
min-width: 10px;
padding: 3px 7px;
font-size: 12px;
font-weight: bold;
line-height: 1;
color: #fff;
text-align: center;
white-space: nowrap;
vertical-align: baseline;
background-color: #777;
border-radius: 10px;
}
.badge:empty {
display: none;
}
.btn .badge {
position: relative;
top: -1px;
}
.btn-xs .badge {
top: 0;
padding: 1px 5px;
}
a.badge:hover,
a.badge:focus {
color: #fff;
text-decoration: none;
cursor: pointer;
}
a.list-group-item.active > .badge,
.nav-pills > .active > a > .badge {
color: #428bca;
background-color: #fff;
}
.nav-pills > li > a > .badge {
margin-left: 3px;
}
.jumbotron {
padding: 30px;
margin-bottom: 30px;
color: inherit;
background-color: #eee;
}
.jumbotron h1,
.jumbotron .h1 {
color: inherit;
}
.jumbotron p {
margin-bottom: 15px;
font-size: 21px;
font-weight: 200;
}
.jumbotron > hr {
border-top-color: #d5d5d5;
}
.container .jumbotron {
border-radius: 6px;
}
.jumbotron .container {
max-width: 100%;
}
@media screen and (min-width: 768px) {
.jumbotron {
padding-top: 48px;
padding-bottom: 48px;
}
.container .jumbotron {
padding-right: 60px;
padding-left: 60px;
}
.jumbotron h1,
.jumbotron .h1 {
font-size: 63px;
}
}
.thumbnail {
display: block;
padding: 4px;
margin-bottom: 20px;
line-height: 1.42857143;
background-color: #fff;
border: 1px solid #ddd;
border-radius: 4px;
-webkit-transition: all .2s ease-in-out;
-o-transition: all .2s ease-in-out;
transition: all .2s ease-in-out;
}
.thumbnail > img,
.thumbnail a > img {
margin-right: auto;
margin-left: auto;
}
a.thumbnail:hover,
a.thumbnail:focus,
a.thumbnail.active {
border-color: #428bca;
}
.thumbnail .caption {
padding: 9px;
color: #333;
}
.alert {
padding: 15px;
margin-bottom: 20px;
border: 1px solid transparent;
border-radius: 4px;
}
.alert h4 {
margin-top: 0;
color: inherit;
}
.alert .alert-link {
font-weight: bold;
}
.alert > p,
.alert > ul {
margin-bottom: 0;
}
.alert > p + p {
margin-top: 5px;
}
.alert-dismissable,
.alert-dismissible {
padding-right: 35px;
}
.alert-dismissable .close,
.alert-dismissible .close {
position: relative;
top: -2px;
right: -21px;
color: inherit;
}
.alert-success {
color: #3c763d;
background-color: #dff0d8;
border-color: #d6e9c6;
}
.alert-success hr {
border-top-color: #c9e2b3;
}
.alert-success .alert-link {
color: #2b542c;
}
.alert-info {
color: #31708f;
background-color: #d9edf7;
border-color: #bce8f1;
}
.alert-info hr {
border-top-color: #a6e1ec;
}
.alert-info .alert-link {
color: #245269;
}
.alert-warning {
color: #8a6d3b;
background-color: #fcf8e3;
border-color: #faebcc;
}
.alert-warning hr {
border-top-color: #f7e1b5;
}
.alert-warning .alert-link {
color: #66512c;
}
.alert-danger {
color: #a94442;
background-color: #f2dede;
border-color: #ebccd1;
}
.alert-danger hr {
border-top-color: #e4b9c0;
}
.alert-danger .alert-link {
color: #843534;
}
@-webkit-keyframes progress-bar-stripes {
from {
background-position: 40px 0;
}
to {
background-position: 0 0;
}
}
@-o-keyframes progress-bar-stripes {
from {
background-position: 40px 0;
}
to {
background-position: 0 0;
}
}
@keyframes progress-bar-stripes {
from {
background-position: 40px 0;
}
to {
background-position: 0 0;
}
}
.progress {
height: 20px;
margin-bottom: 20px;
overflow: hidden;
background-color: #f5f5f5;
border-radius: 4px;
-webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, .1);
box-shadow: inset 0 1px 2px rgba(0, 0, 0, .1);
}
.progress-bar {
float: left;
width: 0;
height: 100%;
font-size: 12px;
line-height: 20px;
color: #fff;
text-align: center;
background-color: #428bca;
-webkit-box-shadow: inset 0 -1px 0 rgba(0, 0, 0, .15);
box-shadow: inset 0 -1px 0 rgba(0, 0, 0, .15);
-webkit-transition: width .6s ease;
-o-transition: width .6s ease;
transition: width .6s ease;
}
.progress-striped .progress-bar,
.progress-bar-striped {
background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
background-image: linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
-webkit-background-size: 40px 40px;
background-size: 40px 40px;
}
.progress.active .progress-bar,
.progress-bar.active {
-webkit-animation: progress-bar-stripes 2s linear infinite;
-o-animation: progress-bar-stripes 2s linear infinite;
animation: progress-bar-stripes 2s linear infinite;
}
.progress-bar[aria-valuenow="1"],
.progress-bar[aria-valuenow="2"] {
min-width: 30px;
}
.progress-bar[aria-valuenow="0"] {
min-width: 30px;
color: #777;
background-color: transparent;
background-image: none;
-webkit-box-shadow: none;
box-shadow: none;
}
.progress-bar-success {
background-color: #5cb85c;
}
.progress-striped .progress-bar-success {
background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
background-image: linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
}
.progress-bar-info {
background-color: #5bc0de;
}
.progress-striped .progress-bar-info {
background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
background-image: linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
}
.progress-bar-warning {
background-color: #f0ad4e;
}
.progress-striped .progress-bar-warning {
background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
background-image: linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
}
.progress-bar-danger {
background-color: #d9534f;
}
.progress-striped .progress-bar-danger {
background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
background-image: linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
}
.media,
.media-body {
overflow: hidden;
zoom: 1;
}
.media,
.media .media {
margin-top: 15px;
}
.media:first-child {
margin-top: 0;
}
.media-object {
display: block;
}
.media-heading {
margin: 0 0 5px;
}
.media > .pull-left {
margin-right: 10px;
}
.media > .pull-right {
margin-left: 10px;
}
.media-list {
padding-left: 0;
list-style: none;
}
.list-group {
padding-left: 0;
margin-bottom: 20px;
}
.list-group-item {
position: relative;
display: block;
padding: 10px 15px;
margin-bottom: -1px;
background-color: #fff;
border: 1px solid #ddd;
}
.list-group-item:first-child {
border-top-left-radius: 4px;
border-top-right-radius: 4px;
}
.list-group-item:last-child {
margin-bottom: 0;
border-bottom-right-radius: 4px;
border-bottom-left-radius: 4px;
}
.list-group-item > .badge {
float: right;
}
.list-group-item > .badge + .badge {
margin-right: 5px;
}
a.list-group-item {
color: #555;
}
a.list-group-item .list-group-item-heading {
color: #333;
}
a.list-group-item:hover,
a.list-group-item:focus {
color: #555;
text-decoration: none;
background-color: #f5f5f5;
}
.list-group-item.disabled,
.list-group-item.disabled:hover,
.list-group-item.disabled:focus {
color: #777;
background-color: #eee;
}
.list-group-item.disabled .list-group-item-heading,
.list-group-item.disabled:hover .list-group-item-heading,
.list-group-item.disabled:focus .list-group-item-heading {
color: inherit;
}
.list-group-item.disabled .list-group-item-text,
.list-group-item.disabled:hover .list-group-item-text,
.list-group-item.disabled:focus .list-group-item-text {
color: #777;
}
.list-group-item.active,
.list-group-item.active:hover,
.list-group-item.active:focus {
z-index: 2;
color: #fff;
background-color: #428bca;
border-color: #428bca;
}
.list-group-item.active .list-group-item-heading,
.list-group-item.active:hover .list-group-item-heading,
.list-group-item.active:focus .list-group-item-heading,
.list-group-item.active .list-group-item-heading > small,
.list-group-item.active:hover .list-group-item-heading > small,
.list-group-item.active:focus .list-group-item-heading > small,
.list-group-item.active .list-group-item-heading > .small,
.list-group-item.active:hover .list-group-item-heading > .small,
.list-group-item.active:focus .list-group-item-heading > .small {
color: inherit;
}
.list-group-item.active .list-group-item-text,
.list-group-item.active:hover .list-group-item-text,
.list-group-item.active:focus .list-group-item-text {
color: #e1edf7;
}
.list-group-item-success {
color: #3c763d;
background-color: #dff0d8;
}
a.list-group-item-success {
color: #3c763d;
}
a.list-group-item-success .list-group-item-heading {
color: inherit;
}
a.list-group-item-success:hover,
a.list-group-item-success:focus {
color: #3c763d;
background-color: #d0e9c6;
}
a.list-group-item-success.active,
a.list-group-item-success.active:hover,
a.list-group-item-success.active:focus {
color: #fff;
background-color: #3c763d;
border-color: #3c763d;
}
.list-group-item-info {
color: #31708f;
background-color: #d9edf7;
}
a.list-group-item-info {
color: #31708f;
}
a.list-group-item-info .list-group-item-heading {
color: inherit;
}
a.list-group-item-info:hover,
a.list-group-item-info:focus {
color: #31708f;
background-color: #c4e3f3;
}
a.list-group-item-info.active,
a.list-group-item-info.active:hover,
a.list-group-item-info.active:focus {
color: #fff;
background-color: #31708f;
border-color: #31708f;
}
.list-group-item-warning {
color: #8a6d3b;
background-color: #fcf8e3;
}
a.list-group-item-warning {
color: #8a6d3b;
}
a.list-group-item-warning .list-group-item-heading {
color: inherit;
}
a.list-group-item-warning:hover,
a.list-group-item-warning:focus {
color: #8a6d3b;
background-color: #faf2cc;
}
a.list-group-item-warning.active,
a.list-group-item-warning.active:hover,
a.list-group-item-warning.active:focus {
color: #fff;
background-color: #8a6d3b;
border-color: #8a6d3b;
}
.list-group-item-danger {
color: #a94442;
background-color: #f2dede;
}
a.list-group-item-danger {
color: #a94442;
}
a.list-group-item-danger .list-group-item-heading {
color: inherit;
}
a.list-group-item-danger:hover,
a.list-group-item-danger:focus {
color: #a94442;
background-color: #ebcccc;
}
a.list-group-item-danger.active,
a.list-group-item-danger.active:hover,
a.list-group-item-danger.active:focus {
color: #fff;
background-color: #a94442;
border-color: #a94442;
}
.list-group-item-heading {
margin-top: 0;
margin-bottom: 5px;
}
.list-group-item-text {
margin-bottom: 0;
line-height: 1.3;
}
.panel {
margin-bottom: 20px;
background-color: #fff;
border: 1px solid transparent;
border-radius: 4px;
-webkit-box-shadow: 0 1px 1px rgba(0, 0, 0, .05);
box-shadow: 0 1px 1px rgba(0, 0, 0, .05);
}
.panel-body {
padding: 15px;
}
.panel-heading {
padding: 10px 15px;
border-bottom: 1px solid transparent;
border-top-left-radius: 3px;
border-top-right-radius: 3px;
}
.panel-heading > .dropdown .dropdown-toggle {
color: inherit;
}
.panel-title {
margin-top: 0;
margin-bottom: 0;
font-size: 16px;
color: inherit;
}
.panel-title > a {
color: inherit;
}
.panel-footer {
padding: 10px 15px;
background-color: #f5f5f5;
border-top: 1px solid #ddd;
border-bottom-right-radius: 3px;
border-bottom-left-radius: 3px;
}
.panel > .list-group {
margin-bottom: 0;
}
.panel > .list-group .list-group-item {
border-width: 1px 0;
border-radius: 0;
}
.panel > .list-group:first-child .list-group-item:first-child {
border-top: 0;
border-top-left-radius: 3px;
border-top-right-radius: 3px;
}
.panel > .list-group:last-child .list-group-item:last-child {
border-bottom: 0;
border-bottom-right-radius: 3px;
border-bottom-left-radius: 3px;
}
.panel-heading + .list-group .list-group-item:first-child {
border-top-width: 0;
}
.list-group + .panel-footer {
border-top-width: 0;
}
.panel > .table,
.panel > .table-responsive > .table,
.panel > .panel-collapse > .table {
margin-bottom: 0;
}
.panel > .table:first-child,
.panel > .table-responsive:first-child > .table:first-child {
border-top-left-radius: 3px;
border-top-right-radius: 3px;
}
.panel > .table:first-child > thead:first-child > tr:first-child td:first-child,
.panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child td:first-child,
.panel > .table:first-child > tbody:first-child > tr:first-child td:first-child,
.panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child td:first-child,
.panel > .table:first-child > thead:first-child > tr:first-child th:first-child,
.panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child th:first-child,
.panel > .table:first-child > tbody:first-child > tr:first-child th:first-child,
.panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child th:first-child {
border-top-left-radius: 3px;
}
.panel > .table:first-child > thead:first-child > tr:first-child td:last-child,
.panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child td:last-child,
.panel > .table:first-child > tbody:first-child > tr:first-child td:last-child,
.panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child td:last-child,
.panel > .table:first-child > thead:first-child > tr:first-child th:last-child,
.panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child th:last-child,
.panel > .table:first-child > tbody:first-child > tr:first-child th:last-child,
.panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child th:last-child {
border-top-right-radius: 3px;
}
.panel > .table:last-child,
.panel > .table-responsive:last-child > .table:last-child {
border-bottom-right-radius: 3px;
border-bottom-left-radius: 3px;
}
.panel > .table:last-child > tbody:last-child > tr:last-child td:first-child,
.panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child td:first-child,
.panel > .table:last-child > tfoot:last-child > tr:last-child td:first-child,
.panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child td:first-child,
.panel > .table:last-child > tbody:last-child > tr:last-child th:first-child,
.panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child th:first-child,
.panel > .table:last-child > tfoot:last-child > tr:last-child th:first-child,
.panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child th:first-child {
border-bottom-left-radius: 3px;
}
.panel > .table:last-child > tbody:last-child > tr:last-child td:last-child,
.panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child td:last-child,
.panel > .table:last-child > tfoot:last-child > tr:last-child td:last-child,
.panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child td:last-child,
.panel > .table:last-child > tbody:last-child > tr:last-child th:last-child,
.panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child th:last-child,
.panel > .table:last-child > tfoot:last-child > tr:last-child th:last-child,
.panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child th:last-child {
border-bottom-right-radius: 3px;
}
.panel > .panel-body + .table,
.panel > .panel-body + .table-responsive {
border-top: 1px solid #ddd;
}
.panel > .table > tbody:first-child > tr:first-child th,
.panel > .table > tbody:first-child > tr:first-child td {
border-top: 0;
}
.panel > .table-bordered,
.panel > .table-responsive > .table-bordered {
border: 0;
}
.panel > .table-bordered > thead > tr > th:first-child,
.panel > .table-responsive > .table-bordered > thead > tr > th:first-child,
.panel > .table-bordered > tbody > tr > th:first-child,
.panel > .table-responsive > .table-bordered > tbody > tr > th:first-child,
.panel > .table-bordered > tfoot > tr > th:first-child,
.panel > .table-responsive > .table-bordered > tfoot > tr > th:first-child,
.panel > .table-bordered > thead > tr > td:first-child,
.panel > .table-responsive > .table-bordered > thead > tr > td:first-child,
.panel > .table-bordered > tbody > tr > td:first-child,
.panel > .table-responsive > .table-bordered > tbody > tr > td:first-child,
.panel > .table-bordered > tfoot > tr > td:first-child,
.panel > .table-responsive > .table-bordered > tfoot > tr > td:first-child {
border-left: 0;
}
.panel > .table-bordered > thead > tr > th:last-child,
.panel > .table-responsive > .table-bordered > thead > tr > th:last-child,
.panel > .table-bordered > tbody > tr > th:last-child,
.panel > .table-responsive > .table-bordered > tbody > tr > th:last-child,
.panel > .table-bordered > tfoot > tr > th:last-child,
.panel > .table-responsive > .table-bordered > tfoot > tr > th:last-child,
.panel > .table-bordered > thead > tr > td:last-child,
.panel > .table-responsive > .table-bordered > thead > tr > td:last-child,
.panel > .table-bordered > tbody > tr > td:last-child,
.panel > .table-responsive > .table-bordered > tbody > tr > td:last-child,
.panel > .table-bordered > tfoot > tr > td:last-child,
.panel > .table-responsive > .table-bordered > tfoot > tr > td:last-child {
border-right: 0;
}
.panel > .table-bordered > thead > tr:first-child > td,
.panel > .table-responsive > .table-bordered > thead > tr:first-child > td,
.panel > .table-bordered > tbody > tr:first-child > td,
.panel > .table-responsive > .table-bordered > tbody > tr:first-child > td,
.panel > .table-bordered > thead > tr:first-child > th,
.panel > .table-responsive > .table-bordered > thead > tr:first-child > th,
.panel > .table-bordered > tbody > tr:first-child > th,
.panel > .table-responsive > .table-bordered > tbody > tr:first-child > th {
border-bottom: 0;
}
.panel > .table-bordered > tbody > tr:last-child > td,
.panel > .table-responsive > .table-bordered > tbody > tr:last-child > td,
.panel > .table-bordered > tfoot > tr:last-child > td,
.panel > .table-responsive > .table-bordered > tfoot > tr:last-child > td,
.panel > .table-bordered > tbody > tr:last-child > th,
.panel > .table-responsive > .table-bordered > tbody > tr:last-child > th,
.panel > .table-bordered > tfoot > tr:last-child > th,
.panel > .table-responsive > .table-bordered > tfoot > tr:last-child > th {
border-bottom: 0;
}
.panel > .table-responsive {
margin-bottom: 0;
border: 0;
}
.panel-group {
margin-bottom: 20px;
}
.panel-group .panel {
margin-bottom: 0;
border-radius: 4px;
}
.panel-group .panel + .panel {
margin-top: 5px;
}
.panel-group .panel-heading {
border-bottom: 0;
}
.panel-group .panel-heading + .panel-collapse > .panel-body {
border-top: 1px solid #ddd;
}
.panel-group .panel-footer {
border-top: 0;
}
.panel-group .panel-footer + .panel-collapse .panel-body {
border-bottom: 1px solid #ddd;
}
.panel-default {
border-color: #ddd;
}
.panel-default > .panel-heading {
color: #333;
background-color: #f5f5f5;
border-color: #ddd;
}
.panel-default > .panel-heading + .panel-collapse > .panel-body {
border-top-color: #ddd;
}
.panel-default > .panel-heading .badge {
color: #f5f5f5;
background-color: #333;
}
.panel-default > .panel-footer + .panel-collapse > .panel-body {
border-bottom-color: #ddd;
}
.panel-primary {
border-color: #428bca;
}
.panel-primary > .panel-heading {
color: #fff;
background-color: #428bca;
border-color: #428bca;
}
.panel-primary > .panel-heading + .panel-collapse > .panel-body {
border-top-color: #428bca;
}
.panel-primary > .panel-heading .badge {
color: #428bca;
background-color: #fff;
}
.panel-primary > .panel-footer + .panel-collapse > .panel-body {
border-bottom-color: #428bca;
}
.panel-success {
border-color: #d6e9c6;
}
.panel-success > .panel-heading {
color: #3c763d;
background-color: #dff0d8;
border-color: #d6e9c6;
}
.panel-success > .panel-heading + .panel-collapse > .panel-body {
border-top-color: #d6e9c6;
}
.panel-success > .panel-heading .badge {
color: #dff0d8;
background-color: #3c763d;
}
.panel-success > .panel-footer + .panel-collapse > .panel-body {
border-bottom-color: #d6e9c6;
}
.panel-info {
border-color: #bce8f1;
}
.panel-info > .panel-heading {
color: #31708f;
background-color: #d9edf7;
border-color: #bce8f1;
}
.panel-info > .panel-heading + .panel-collapse > .panel-body {
border-top-color: #bce8f1;
}
.panel-info > .panel-heading .badge {
color: #d9edf7;
background-color: #31708f;
}
.panel-info > .panel-footer + .panel-collapse > .panel-body {
border-bottom-color: #bce8f1;
}
.panel-warning {
border-color: #faebcc;
}
.panel-warning > .panel-heading {
color: #8a6d3b;
background-color: #fcf8e3;
border-color: #faebcc;
}
.panel-warning > .panel-heading + .panel-collapse > .panel-body {
border-top-color: #faebcc;
}
.panel-warning > .panel-heading .badge {
color: #fcf8e3;
background-color: #8a6d3b;
}
.panel-warning > .panel-footer + .panel-collapse > .panel-body {
border-bottom-color: #faebcc;
}
.panel-danger {
border-color: #ebccd1;
}
.panel-danger > .panel-heading {
color: #a94442;
background-color: #f2dede;
border-color: #ebccd1;
}
.panel-danger > .panel-heading + .panel-collapse > .panel-body {
border-top-color: #ebccd1;
}
.panel-danger > .panel-heading .badge {
color: #f2dede;
background-color: #a94442;
}
.panel-danger > .panel-footer + .panel-collapse > .panel-body {
border-bottom-color: #ebccd1;
}
.embed-responsive {
position: relative;
display: block;
height: 0;
padding: 0;
overflow: hidden;
}
.embed-responsive .embed-responsive-item,
.embed-responsive iframe,
.embed-responsive embed,
.embed-responsive object {
position: absolute;
top: 0;
bottom: 0;
left: 0;
width: 100%;
height: 100%;
border: 0;
}
.embed-responsive.embed-responsive-16by9 {
padding-bottom: 56.25%;
}
.embed-responsive.embed-responsive-4by3 {
padding-bottom: 75%;
}
.well {
min-height: 20px;
padding: 19px;
margin-bottom: 20px;
background-color: #f5f5f5;
border: 1px solid #e3e3e3;
border-radius: 4px;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .05);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, .05);
}
.well blockquote {
border-color: #ddd;
border-color: rgba(0, 0, 0, .15);
}
.well-lg {
padding: 24px;
border-radius: 6px;
}
.well-sm {
padding: 9px;
border-radius: 3px;
}
.close {
float: right;
font-size: 21px;
font-weight: bold;
line-height: 1;
color: #000;
text-shadow: 0 1px 0 #fff;
filter: alpha(opacity=20);
opacity: .2;
}
.close:hover,
.close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
filter: alpha(opacity=50);
opacity: .5;
}
button.close {
-webkit-appearance: none;
padding: 0;
cursor: pointer;
background: transparent;
border: 0;
}
.modal-open {
overflow: hidden;
}
.modal {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 1050;
display: none;
overflow: hidden;
-webkit-overflow-scrolling: touch;
outline: 0;
}
.modal.fade .modal-dialog {
-webkit-transition: -webkit-transform .3s ease-out;
-o-transition: -o-transform .3s ease-out;
transition: transform .3s ease-out;
-webkit-transform: translate3d(0, -25%, 0);
-o-transform: translate3d(0, -25%, 0);
transform: translate3d(0, -25%, 0);
}
.modal.in .modal-dialog {
-webkit-transform: translate3d(0, 0, 0);
-o-transform: translate3d(0, 0, 0);
transform: translate3d(0, 0, 0);
}
.modal-open .modal {
overflow-x: hidden;
overflow-y: auto;
}
.modal-dialog {
position: relative;
width: auto;
margin: 10px;
}
.modal-content {
position: relative;
background-color: #fff;
-webkit-background-clip: padding-box;
background-clip: padding-box;
border: 1px solid #999;
border: 1px solid rgba(0, 0, 0, .2);
border-radius: 6px;
outline: 0;
-webkit-box-shadow: 0 3px 9px rgba(0, 0, 0, .5);
box-shadow: 0 3px 9px rgba(0, 0, 0, .5);
}
.modal-backdrop {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 1040;
background-color: #000;
}
.modal-backdrop.fade {
filter: alpha(opacity=0);
opacity: 0;
}
.modal-backdrop.in {
filter: alpha(opacity=50);
opacity: .5;
}
.modal-header {
min-height: 16.42857143px;
padding: 15px;
border-bottom: 1px solid #e5e5e5;
}
.modal-header .close {
margin-top: -2px;
}
.modal-title {
margin: 0;
line-height: 1.42857143;
}
.modal-body {
position: relative;
padding: 15px;
}
.modal-footer {
padding: 15px;
text-align: right;
border-top: 1px solid #e5e5e5;
}
.modal-footer .btn + .btn {
margin-bottom: 0;
margin-left: 5px;
}
.modal-footer .btn-group .btn + .btn {
margin-left: -1px;
}
.modal-footer .btn-block + .btn-block {
margin-left: 0;
}
.modal-scrollbar-measure {
position: absolute;
top: -9999px;
width: 50px;
height: 50px;
overflow: scroll;
}
@media (min-width: 768px) {
.modal-dialog {
width: 600px;
margin: 30px auto;
}
.modal-content {
-webkit-box-shadow: 0 5px 15px rgba(0, 0, 0, .5);
box-shadow: 0 5px 15px rgba(0, 0, 0, .5);
}
.modal-sm {
width: 300px;
}
}
@media (min-width: 992px) {
.modal-lg {
width: 900px;
}
}
.tooltip {
position: absolute;
z-index: 1070;
display: block;
font-size: 12px;
line-height: 1.4;
visibility: visible;
filter: alpha(opacity=0);
opacity: 0;
}
.tooltip.in {
filter: alpha(opacity=90);
opacity: .9;
}
.tooltip.top {
padding: 5px 0;
margin-top: -3px;
}
.tooltip.right {
padding: 0 5px;
margin-left: 3px;
}
.tooltip.bottom {
padding: 5px 0;
margin-top: 3px;
}
.tooltip.left {
padding: 0 5px;
margin-left: -3px;
}
.tooltip-inner {
max-width: 200px;
padding: 3px 8px;
color: #fff;
text-align: center;
text-decoration: none;
background-color: #000;
border-radius: 4px;
}
.tooltip-arrow {
position: absolute;
width: 0;
height: 0;
border-color: transparent;
border-style: solid;
}
.tooltip.top .tooltip-arrow {
bottom: 0;
left: 50%;
margin-left: -5px;
border-width: 5px 5px 0;
border-top-color: #000;
}
.tooltip.top-left .tooltip-arrow {
bottom: 0;
left: 5px;
border-width: 5px 5px 0;
border-top-color: #000;
}
.tooltip.top-right .tooltip-arrow {
right: 5px;
bottom: 0;
border-width: 5px 5px 0;
border-top-color: #000;
}
.tooltip.right .tooltip-arrow {
top: 50%;
left: 0;
margin-top: -5px;
border-width: 5px 5px 5px 0;
border-right-color: #000;
}
.tooltip.left .tooltip-arrow {
top: 50%;
right: 0;
margin-top: -5px;
border-width: 5px 0 5px 5px;
border-left-color: #000;
}
.tooltip.bottom .tooltip-arrow {
top: 0;
left: 50%;
margin-left: -5px;
border-width: 0 5px 5px;
border-bottom-color: #000;
}
.tooltip.bottom-left .tooltip-arrow {
top: 0;
left: 5px;
border-width: 0 5px 5px;
border-bottom-color: #000;
}
.tooltip.bottom-right .tooltip-arrow {
top: 0;
right: 5px;
border-width: 0 5px 5px;
border-bottom-color: #000;
}
.popover {
position: absolute;
top: 0;
left: 0;
z-index: 1060;
display: none;
max-width: 276px;
padding: 1px;
text-align: left;
white-space: normal;
background-color: #fff;
-webkit-background-clip: padding-box;
background-clip: padding-box;
border: 1px solid #ccc;
border: 1px solid rgba(0, 0, 0, .2);
border-radius: 6px;
-webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, .2);
box-shadow: 0 5px 10px rgba(0, 0, 0, .2);
}
.popover.top {
margin-top: -10px;
}
.popover.right {
margin-left: 10px;
}
.popover.bottom {
margin-top: 10px;
}
.popover.left {
margin-left: -10px;
}
.popover-title {
padding: 8px 14px;
margin: 0;
font-size: 14px;
font-weight: normal;
line-height: 18px;
background-color: #f7f7f7;
border-bottom: 1px solid #ebebeb;
border-radius: 5px 5px 0 0;
}
.popover-content {
padding: 9px 14px;
}
.popover > .arrow,
.popover > .arrow:after {
position: absolute;
display: block;
width: 0;
height: 0;
border-color: transparent;
border-style: solid;
}
.popover > .arrow {
border-width: 11px;
}
.popover > .arrow:after {
content: "";
border-width: 10px;
}
.popover.top > .arrow {
bottom: -11px;
left: 50%;
margin-left: -11px;
border-top-color: #999;
border-top-color: rgba(0, 0, 0, .25);
border-bottom-width: 0;
}
.popover.top > .arrow:after {
bottom: 1px;
margin-left: -10px;
content: " ";
border-top-color: #fff;
border-bottom-width: 0;
}
.popover.right > .arrow {
top: 50%;
left: -11px;
margin-top: -11px;
border-right-color: #999;
border-right-color: rgba(0, 0, 0, .25);
border-left-width: 0;
}
.popover.right > .arrow:after {
bottom: -10px;
left: 1px;
content: " ";
border-right-color: #fff;
border-left-width: 0;
}
.popover.bottom > .arrow {
top: -11px;
left: 50%;
margin-left: -11px;
border-top-width: 0;
border-bottom-color: #999;
border-bottom-color: rgba(0, 0, 0, .25);
}
.popover.bottom > .arrow:after {
top: 1px;
margin-left: -10px;
content: " ";
border-top-width: 0;
border-bottom-color: #fff;
}
.popover.left > .arrow {
top: 50%;
right: -11px;
margin-top: -11px;
border-right-width: 0;
border-left-color: #999;
border-left-color: rgba(0, 0, 0, .25);
}
.popover.left > .arrow:after {
right: 1px;
bottom: -10px;
content: " ";
border-right-width: 0;
border-left-color: #fff;
}
.carousel {
position: relative;
}
.carousel-inner {
position: relative;
width: 100%;
overflow: hidden;
}
.carousel-inner > .item {
position: relative;
display: none;
-webkit-transition: .6s ease-in-out left;
-o-transition: .6s ease-in-out left;
transition: .6s ease-in-out left;
}
.carousel-inner > .item > img,
.carousel-inner > .item > a > img {
line-height: 1;
}
.carousel-inner > .active,
.carousel-inner > .next,
.carousel-inner > .prev {
display: block;
}
.carousel-inner > .active {
left: 0;
}
.carousel-inner > .next,
.carousel-inner > .prev {
position: absolute;
top: 0;
width: 100%;
}
.carousel-inner > .next {
left: 100%;
}
.carousel-inner > .prev {
left: -100%;
}
.carousel-inner > .next.left,
.carousel-inner > .prev.right {
left: 0;
}
.carousel-inner > .active.left {
left: -100%;
}
.carousel-inner > .active.right {
left: 100%;
}
.carousel-control {
position: absolute;
top: 0;
bottom: 0;
left: 0;
width: 15%;
font-size: 20px;
color: #fff;
text-align: center;
text-shadow: 0 1px 2px rgba(0, 0, 0, .6);
filter: alpha(opacity=50);
opacity: .5;
}
.carousel-control.left {
background-image: -webkit-linear-gradient(left, rgba(0, 0, 0, .5) 0%, rgba(0, 0, 0, .0001) 100%);
background-image: -o-linear-gradient(left, rgba(0, 0, 0, .5) 0%, rgba(0, 0, 0, .0001) 100%);
background-image: -webkit-gradient(linear, left top, right top, from(rgba(0, 0, 0, .5)), to(rgba(0, 0, 0, .0001)));
background-image: linear-gradient(to right, rgba(0, 0, 0, .5) 0%, rgba(0, 0, 0, .0001) 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#80000000', endColorstr='#00000000', GradientType=1);
background-repeat: repeat-x;
}
.carousel-control.right {
right: 0;
left: auto;
background-image: -webkit-linear-gradient(left, rgba(0, 0, 0, .0001) 0%, rgba(0, 0, 0, .5) 100%);
background-image: -o-linear-gradient(left, rgba(0, 0, 0, .0001) 0%, rgba(0, 0, 0, .5) 100%);
background-image: -webkit-gradient(linear, left top, right top, from(rgba(0, 0, 0, .0001)), to(rgba(0, 0, 0, .5)));
background-image: linear-gradient(to right, rgba(0, 0, 0, .0001) 0%, rgba(0, 0, 0, .5) 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#00000000', endColorstr='#80000000', GradientType=1);
background-repeat: repeat-x;
}
.carousel-control:hover,
.carousel-control:focus {
color: #fff;
text-decoration: none;
filter: alpha(opacity=90);
outline: 0;
opacity: .9;
}
.carousel-control .icon-prev,
.carousel-control .icon-next,
.carousel-control .glyphicon-chevron-left,
.carousel-control .glyphicon-chevron-right {
position: absolute;
top: 50%;
z-index: 5;
display: inline-block;
}
.carousel-control .icon-prev,
.carousel-control .glyphicon-chevron-left {
left: 50%;
margin-left: -10px;
}
.carousel-control .icon-next,
.carousel-control .glyphicon-chevron-right {
right: 50%;
margin-right: -10px;
}
.carousel-control .icon-prev,
.carousel-control .icon-next {
width: 20px;
height: 20px;
margin-top: -10px;
font-family: serif;
}
.carousel-control .icon-prev:before {
content: '\2039';
}
.carousel-control .icon-next:before {
content: '\203a';
}
.carousel-indicators {
position: absolute;
bottom: 10px;
left: 50%;
z-index: 15;
width: 60%;
padding-left: 0;
margin-left: -30%;
text-align: center;
list-style: none;
}
.carousel-indicators li {
display: inline-block;
width: 10px;
height: 10px;
margin: 1px;
text-indent: -999px;
cursor: pointer;
background-color: #000 \9;
background-color: rgba(0, 0, 0, 0);
border: 1px solid #fff;
border-radius: 10px;
}
.carousel-indicators .active {
width: 12px;
height: 12px;
margin: 0;
background-color: #fff;
}
.carousel-caption {
position: absolute;
right: 15%;
bottom: 20px;
left: 15%;
z-index: 10;
padding-top: 20px;
padding-bottom: 20px;
color: #fff;
text-align: center;
text-shadow: 0 1px 2px rgba(0, 0, 0, .6);
}
.carousel-caption .btn {
text-shadow: none;
}
@media screen and (min-width: 768px) {
.carousel-control .glyphicon-chevron-left,
.carousel-control .glyphicon-chevron-right,
.carousel-control .icon-prev,
.carousel-control .icon-next {
width: 30px;
height: 30px;
margin-top: -15px;
font-size: 30px;
}
.carousel-control .glyphicon-chevron-left,
.carousel-control .icon-prev {
margin-left: -15px;
}
.carousel-control .glyphicon-chevron-right,
.carousel-control .icon-next {
margin-right: -15px;
}
.carousel-caption {
right: 20%;
left: 20%;
padding-bottom: 30px;
}
.carousel-indicators {
bottom: 20px;
}
}
.clearfix:before,
.clearfix:after,
.dl-horizontal dd:before,
.dl-horizontal dd:after,
.container:before,
.container:after,
.container-fluid:before,
.container-fluid:after,
.row:before,
.row:after,
.form-horizontal .form-group:before,
.form-horizontal .form-group:after,
.btn-toolbar:before,
.btn-toolbar:after,
.btn-group-vertical > .btn-group:before,
.btn-group-vertical > .btn-group:after,
.nav:before,
.nav:after,
.navbar:before,
.navbar:after,
.navbar-header:before,
.navbar-header:after,
.navbar-collapse:before,
.navbar-collapse:after,
.pager:before,
.pager:after,
.panel-body:before,
.panel-body:after,
.modal-footer:before,
.modal-footer:after {
display: table;
content: " ";
}
.clearfix:after,
.dl-horizontal dd:after,
.container:after,
.container-fluid:after,
.row:after,
.form-horizontal .form-group:after,
.btn-toolbar:after,
.btn-group-vertical > .btn-group:after,
.nav:after,
.navbar:after,
.navbar-header:after,
.navbar-collapse:after,
.pager:after,
.panel-body:after,
.modal-footer:after {
clear: both;
}
.center-block {
display: block;
margin-right: auto;
margin-left: auto;
}
.pull-right {
float: right !important;
}
.pull-left {
float: left !important;
}
.hide {
display: none !important;
}
.show {
display: block !important;
}
.invisible {
visibility: hidden;
}
.text-hide {
font: 0/0 a;
color: transparent;
text-shadow: none;
background-color: transparent;
border: 0;
}
.hidden {
display: none !important;
visibility: hidden !important;
}
.affix {
position: fixed;
-webkit-transform: translate3d(0, 0, 0);
-o-transform: translate3d(0, 0, 0);
transform: translate3d(0, 0, 0);
}
@-ms-viewport {
width: device-width;
}
.visible-xs,
.visible-sm,
.visible-md,
.visible-lg {
display: none !important;
}
.visible-xs-block,
.visible-xs-inline,
.visible-xs-inline-block,
.visible-sm-block,
.visible-sm-inline,
.visible-sm-inline-block,
.visible-md-block,
.visible-md-inline,
.visible-md-inline-block,
.visible-lg-block,
.visible-lg-inline,
.visible-lg-inline-block {
display: none !important;
}
@media (max-width: 767px) {
.visible-xs {
display: block !important;
}
table.visible-xs {
display: table;
}
tr.visible-xs {
display: table-row !important;
}
th.visible-xs,
td.visible-xs {
display: table-cell !important;
}
}
@media (max-width: 767px) {
.visible-xs-block {
display: block !important;
}
}
@media (max-width: 767px) {
.visible-xs-inline {
display: inline !important;
}
}
@media (max-width: 767px) {
.visible-xs-inline-block {
display: inline-block !important;
}
}
@media (min-width: 768px) and (max-width: 991px) {
.visible-sm {
display: block !important;
}
table.visible-sm {
display: table;
}
tr.visible-sm {
display: table-row !important;
}
th.visible-sm,
td.visible-sm {
display: table-cell !important;
}
}
@media (min-width: 768px) and (max-width: 991px) {
.visible-sm-block {
display: block !important;
}
}
@media (min-width: 768px) and (max-width: 991px) {
.visible-sm-inline {
display: inline !important;
}
}
@media (min-width: 768px) and (max-width: 991px) {
.visible-sm-inline-block {
display: inline-block !important;
}
}
@media (min-width: 992px) and (max-width: 1199px) {
.visible-md {
display: block !important;
}
table.visible-md {
display: table;
}
tr.visible-md {
display: table-row !important;
}
th.visible-md,
td.visible-md {
display: table-cell !important;
}
}
@media (min-width: 992px) and (max-width: 1199px) {
.visible-md-block {
display: block !important;
}
}
@media (min-width: 992px) and (max-width: 1199px) {
.visible-md-inline {
display: inline !important;
}
}
@media (min-width: 992px) and (max-width: 1199px) {
.visible-md-inline-block {
display: inline-block !important;
}
}
@media (min-width: 1200px) {
.visible-lg {
display: block !important;
}
table.visible-lg {
display: table;
}
tr.visible-lg {
display: table-row !important;
}
th.visible-lg,
td.visible-lg {
display: table-cell !important;
}
}
@media (min-width: 1200px) {
.visible-lg-block {
display: block !important;
}
}
@media (min-width: 1200px) {
.visible-lg-inline {
display: inline !important;
}
}
@media (min-width: 1200px) {
.visible-lg-inline-block {
display: inline-block !important;
}
}
@media (max-width: 767px) {
.hidden-xs {
display: none !important;
}
}
@media (min-width: 768px) and (max-width: 991px) {
.hidden-sm {
display: none !important;
}
}
@media (min-width: 992px) and (max-width: 1199px) {
.hidden-md {
display: none !important;
}
}
@media (min-width: 1200px) {
.hidden-lg {
display: none !important;
}
}
.visible-print {
display: none !important;
}
@media print {
.visible-print {
display: block !important;
}
table.visible-print {
display: table;
}
tr.visible-print {
display: table-row !important;
}
th.visible-print,
td.visible-print {
display: table-cell !important;
}
}
.visible-print-block {
display: none !important;
}
@media print {
.visible-print-block {
display: block !important;
}
}
.visible-print-inline {
display: none !important;
}
@media print {
.visible-print-inline {
display: inline !important;
}
}
.visible-print-inline-block {
display: none !important;
}
@media print {
.visible-print-inline-block {
display: inline-block !important;
}
}
@media print {
.hidden-print {
display: none !important;
}
}
/*# sourceMappingURL=bootstrap.css.map */
| EmericWEB/WP_GuruTheme | bootstrap/css/bootstrap.custom.css | CSS | gpl-2.0 | 132,540 |
#!/usr/bin/env python
# **********************************************************************
#
# Copyright (c) 2003-2011 ZeroC, Inc. All rights reserved.
#
# This copy of Ice is licensed to you under the terms described in the
# ICE_LICENSE file included in this distribution.
#
# **********************************************************************
import os, sys, traceback
import Ice, AllTests
def test(b):
if not b:
raise RuntimeError('test assertion failed')
def usage(n):
sys.stderr.write("Usage: " + n + " port...\n")
def run(args, communicator):
ports = []
for arg in args[1:]:
if arg[0] == '-':
sys.stderr.write(args[0] + ": unknown option `" + arg + "'\n")
usage(args[0])
return False
ports.append(int(arg))
if len(ports) == 0:
sys.stderr.write(args[0] + ": no ports specified\n")
usage(args[0])
return False
try:
AllTests.allTests(communicator, ports)
except:
traceback.print_exc()
test(False)
return True
try:
initData = Ice.InitializationData()
initData.properties = Ice.createProperties(sys.argv)
#
# This test aborts servers, so we don't want warnings.
#
initData.properties.setProperty('Ice.Warn.Connections', '0')
communicator = Ice.initialize(sys.argv, initData)
status = run(sys.argv, communicator)
except:
traceback.print_exc()
status = False
if communicator:
try:
communicator.destroy()
except:
traceback.print_exc()
status = False
sys.exit(not status)
| joshmoore/zeroc-ice | py/test/Ice/faultTolerance/Client.py | Python | gpl-2.0 | 1,608 |
/*
* Copyright (C) 2000 Matthias Elter <[email protected]>
* Copyright (C) 2001-2002 Raffaele Sandrini <[email protected])
* Copyright (C) 2003 Waldo Bastian <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include <unistd.h>
#include <tqcstring.h>
#include <tqcursor.h>
#include <tqdatastream.h>
#include <tqdir.h>
#include <tqdragobject.h>
#include <tqfileinfo.h>
#include <tqheader.h>
#include <tqpainter.h>
#include <tqpopupmenu.h>
#include <tqregexp.h>
#include <tqstringlist.h>
#include <tdeglobal.h>
#include <kstandarddirs.h>
#include <kinputdialog.h>
#include <tdelocale.h>
#include <ksimpleconfig.h>
#include <kdebug.h>
#include <kiconloader.h>
#include <kdesktopfile.h>
#include <tdeaction.h>
#include <tdemessagebox.h>
#include <tdeapplication.h>
#include <kservice.h>
#include <kservicegroup.h>
#include <tdemultipledrag.h>
#include <kurldrag.h>
#include "treeview.h"
#include "treeview.moc"
#include "khotkeys.h"
#include "menufile.h"
#include "menuinfo.h"
#define MOVE_FOLDER 'M'
#define COPY_FOLDER 'C'
#define MOVE_FILE 'm'
#define COPY_FILE 'c'
#define COPY_SEPARATOR 'S'
TreeItem::TreeItem(TQListViewItem *parent, TQListViewItem *after, const TQString& menuId, bool __init)
:TQListViewItem(parent, after), _hidden(false), _init(__init), _layoutDirty(false), _menuId(menuId),
m_folderInfo(0), m_entryInfo(0) {}
TreeItem::TreeItem(TQListView *parent, TQListViewItem *after, const TQString& menuId, bool __init)
: TQListViewItem(parent, after), _hidden(false), _init(__init), _layoutDirty(false), _menuId(menuId),
m_folderInfo(0), m_entryInfo(0) {}
void TreeItem::setName(const TQString &name)
{
_name = name;
update();
}
void TreeItem::setHidden(bool b)
{
if (_hidden == b) return;
_hidden = b;
update();
}
void TreeItem::update()
{
TQString s = _name;
if (_hidden)
s += i18n(" [Hidden]");
setText(0, s);
}
void TreeItem::setOpen(bool o)
{
if (o)
load();
TQListViewItem::setOpen(o);
}
void TreeItem::load()
{
if (m_folderInfo && !_init)
{
_init = true;
TreeView *tv = static_cast<TreeView *>(listView());
tv->fillBranch(m_folderInfo, this);
}
}
void TreeItem::paintCell ( TQPainter * p, const TQColorGroup & cg, int column, int width, int align )
{
TQListViewItem::paintCell(p, cg, column, width, align);
if (!m_folderInfo && !m_entryInfo)
{
// Draw Separator
int h = (height() / 2) -1;
if (isSelected())
p->setPen( cg.highlightedText() );
else
p->setPen( cg.text() );
p->drawLine(0, h,
width, h);
}
}
void TreeItem::setup()
{
TQListViewItem::setup();
if (!m_folderInfo && !m_entryInfo)
setHeight(8);
}
static TQPixmap appIcon(const TQString &iconName)
{
TQPixmap normal = TDEGlobal::iconLoader()->loadIcon(iconName, TDEIcon::Small, 0, TDEIcon::DefaultState, 0L, true);
// make sure they are not larger than 20x20
if (normal.width() > 20 || normal.height() > 20)
{
TQImage tmp = normal.convertToImage();
tmp = tmp.smoothScale(20, 20);
normal.convertFromImage(tmp);
}
return normal;
}
TreeView::TreeView( bool controlCenter, TDEActionCollection *ac, TQWidget *parent, const char *name )
: TDEListView(parent, name), m_ac(ac), m_rmb(0), m_clipboard(0),
m_clipboardFolderInfo(0), m_clipboardEntryInfo(0),
m_controlCenter(controlCenter), m_layoutDirty(false)
{
setFrameStyle(TQFrame::WinPanel | TQFrame::Sunken);
setAllColumnsShowFocus(true);
setRootIsDecorated(true);
setSorting(-1);
setAcceptDrops(true);
setDropVisualizer(true);
setDragEnabled(true);
setMinimumWidth(240);
addColumn("");
header()->hide();
connect(this, TQT_SIGNAL(dropped(TQDropEvent*, TQListViewItem*, TQListViewItem*)),
TQT_SLOT(slotDropped(TQDropEvent*, TQListViewItem*, TQListViewItem*)));
connect(this, TQT_SIGNAL(clicked( TQListViewItem* )),
TQT_SLOT(itemSelected( TQListViewItem* )));
connect(this,TQT_SIGNAL(selectionChanged ( TQListViewItem * )),
TQT_SLOT(itemSelected( TQListViewItem* )));
connect(this, TQT_SIGNAL(rightButtonPressed(TQListViewItem*, const TQPoint&, int)),
TQT_SLOT(slotRMBPressed(TQListViewItem*, const TQPoint&)));
// connect actions
connect(m_ac->action("newitem"), TQT_SIGNAL(activated()), TQT_SLOT(newitem()));
connect(m_ac->action("newsubmenu"), TQT_SIGNAL(activated()), TQT_SLOT(newsubmenu()));
if (m_ac->action("newsep"))
connect(m_ac->action("newsep"), TQT_SIGNAL(activated()), TQT_SLOT(newsep()));
m_menuFile = new MenuFile( locateLocal("xdgconf-menu", "applications-tdemenuedit.menu"));
m_rootFolder = new MenuFolderInfo;
m_separator = new MenuSeparatorInfo;
m_drag = 0;
// Read menu format configuration information
TDESharedConfig::Ptr pConfig = TDESharedConfig::openConfig("kickerrc");
pConfig->setGroup("menus");
m_detailedMenuEntries = pConfig->readBoolEntry("DetailedMenuEntries",true);
if (m_detailedMenuEntries)
{
m_detailedEntriesNamesFirst = pConfig->readBoolEntry("DetailedEntriesNamesFirst",false);
}
}
TreeView::~TreeView() {
cleanupClipboard();
delete m_rootFolder;
delete m_separator;
}
void TreeView::setViewMode(bool showHidden)
{
delete m_rmb;
// setup rmb menu
m_rmb = new TQPopupMenu(this);
TDEAction *action;
action = m_ac->action("edit_cut");
if(action) {
action->plug(m_rmb);
action->setEnabled(false);
connect(action, TQT_SIGNAL(activated()), TQT_SLOT(cut()));
}
action = m_ac->action("edit_copy");
if(action) {
action->plug(m_rmb);
action->setEnabled(false);
connect(action, TQT_SIGNAL(activated()), TQT_SLOT(copy()));
}
action = m_ac->action("edit_paste");
if(action) {
action->plug(m_rmb);
action->setEnabled(false);
connect(action, TQT_SIGNAL(activated()), TQT_SLOT(paste()));
}
m_rmb->insertSeparator();
action = m_ac->action("delete");
if(action) {
action->plug(m_rmb);
action->setEnabled(false);
connect(action, TQT_SIGNAL(activated()), TQT_SLOT(del()));
}
m_rmb->insertSeparator();
if(m_ac->action("newitem"))
m_ac->action("newitem")->plug(m_rmb);
if(m_ac->action("newsubmenu"))
m_ac->action("newsubmenu")->plug(m_rmb);
if(m_ac->action("newsep"))
m_ac->action("newsep")->plug(m_rmb);
m_showHidden = showHidden;
readMenuFolderInfo();
fill();
}
void TreeView::readMenuFolderInfo(MenuFolderInfo *folderInfo, KServiceGroup::Ptr folder, const TQString &prefix)
{
if (!folderInfo)
{
folderInfo = m_rootFolder;
if (m_controlCenter)
folder = KServiceGroup::baseGroup("settings");
else
folder = KServiceGroup::root();
}
if (!folder || !folder->isValid())
return;
folderInfo->caption = folder->caption();
folderInfo->comment = folder->comment();
// Item names may contain ampersands. To avoid them being converted
// to accelerators, replace them with two ampersands.
folderInfo->hidden = folder->noDisplay();
folderInfo->directoryFile = folder->directoryEntryPath();
folderInfo->icon = folder->icon();
TQString id = folder->relPath();
int i = id.findRev('/', -2);
id = id.mid(i+1);
folderInfo->id = id;
folderInfo->fullId = prefix + id;
KServiceGroup::List list = folder->entries(true, !m_showHidden, true, m_detailedMenuEntries && !m_detailedEntriesNamesFirst);
for(KServiceGroup::List::ConstIterator it = list.begin();
it != list.end(); ++it)
{
KSycocaEntry * e = *it;
if (e->isType(KST_KServiceGroup))
{
KServiceGroup::Ptr g(static_cast<KServiceGroup *>(e));
MenuFolderInfo *subFolderInfo = new MenuFolderInfo();
readMenuFolderInfo(subFolderInfo, g, folderInfo->fullId);
folderInfo->add(subFolderInfo, true);
}
else if (e->isType(KST_KService))
{
folderInfo->add(new MenuEntryInfo(static_cast<KService *>(e)), true);
}
else if (e->isType(KST_KServiceSeparator))
{
folderInfo->add(m_separator, true);
}
}
}
void TreeView::fill()
{
TQApplication::setOverrideCursor(Qt::WaitCursor);
clear();
fillBranch(m_rootFolder, 0);
TQApplication::restoreOverrideCursor();
}
TQString TreeView::findName(KDesktopFile *df, bool deleted)
{
TQString name = df->readName();
if (deleted)
{
if (name == "empty")
name = TQString::null;
if (name.isEmpty())
{
TQString file = df->fileName();
TQString res = df->resource();
bool isLocal = true;
TQStringList files = TDEGlobal::dirs()->findAllResources(res.latin1(), file);
for(TQStringList::ConstIterator it = files.begin();
it != files.end();
++it)
{
if (isLocal)
{
isLocal = false;
continue;
}
KDesktopFile df2(*it);
name = df2.readName();
if (!name.isEmpty() && (name != "empty"))
return name;
}
}
}
return name;
}
TreeItem *TreeView::createTreeItem(TreeItem *parent, TQListViewItem *after, MenuFolderInfo *folderInfo, bool _init)
{
TreeItem *item;
if (parent == 0)
item = new TreeItem(this, after, TQString::null, _init);
else
item = new TreeItem(parent, after, TQString::null, _init);
item->setMenuFolderInfo(folderInfo);
item->setName(folderInfo->caption);
item->setPixmap(0, appIcon(folderInfo->icon));
item->setDirectoryPath(folderInfo->fullId);
item->setHidden(folderInfo->hidden);
item->setExpandable(true);
return item;
}
TreeItem *TreeView::createTreeItem(TreeItem *parent, TQListViewItem *after, MenuEntryInfo *entryInfo, bool _init)
{
bool hidden = entryInfo->hidden;
TreeItem* item;
if (parent == 0)
item = new TreeItem(this, after, entryInfo->menuId(), _init);
else
item = new TreeItem(parent, after, entryInfo->menuId(),_init);
QString name;
if (m_detailedMenuEntries && entryInfo->description.length() != 0)
{
if (m_detailedEntriesNamesFirst)
{
name = entryInfo->caption + " (" + entryInfo->description + ")";
}
else
{
name = entryInfo->description + " (" + entryInfo->caption + ")";
}
}
else
{
name = entryInfo->caption;
}
item->setMenuEntryInfo(entryInfo);
item->setName(name);
item->setPixmap(0, appIcon(entryInfo->icon));
item->setHidden(hidden);
return item;
}
TreeItem *TreeView::createTreeItem(TreeItem *parent, TQListViewItem *after, MenuSeparatorInfo *, bool _init)
{
TreeItem* item;
if (parent == 0)
item = new TreeItem(this, after, TQString::null, _init);
else
item = new TreeItem(parent, after, TQString::null,_init);
return item;
}
void TreeView::fillBranch(MenuFolderInfo *folderInfo, TreeItem *parent)
{
TQString relPath = parent ? parent->directory() : TQString::null;
TQPtrListIterator<MenuInfo> it( folderInfo->initialLayout );
TreeItem *after = 0;
for (MenuInfo *info; (info = it.current()); ++it)
{
MenuEntryInfo *entry = dynamic_cast<MenuEntryInfo*>(info);
if (entry)
{
after = createTreeItem(parent, after, entry);
continue;
}
MenuFolderInfo *subFolder = dynamic_cast<MenuFolderInfo*>(info);
if (subFolder)
{
after = createTreeItem(parent, after, subFolder);
continue;
}
MenuSeparatorInfo *separator = dynamic_cast<MenuSeparatorInfo*>(info);
if (separator)
{
after = createTreeItem(parent, after, separator);
continue;
}
}
}
void TreeView::closeAllItems(TQListViewItem *item)
{
if (!item) return;
while(item)
{
item->setOpen(false);
closeAllItems(item->firstChild());
item = item->nextSibling();
}
}
void TreeView::selectMenu(const TQString &menu)
{
closeAllItems(firstChild());
if (menu.length() <= 1)
{
setCurrentItem(firstChild());
clearSelection();
return; // Root menu
}
TQString restMenu = menu.mid(1);
if (!restMenu.endsWith("/"))
restMenu += "/";
TreeItem *item = 0;
do
{
int i = restMenu.find("/");
TQString subMenu = restMenu.left(i+1);
restMenu = restMenu.mid(i+1);
item = (TreeItem*)(item ? item->firstChild() : firstChild());
while(item)
{
MenuFolderInfo *folderInfo = item->folderInfo();
if (folderInfo && (folderInfo->id == subMenu))
{
item->setOpen(true);
break;
}
item = (TreeItem*) item->nextSibling();
}
}
while( item && !restMenu.isEmpty());
if (item)
{
setCurrentItem(item);
ensureItemVisible(item);
}
}
void TreeView::selectMenuEntry(const TQString &menuEntry)
{
TreeItem *item = (TreeItem *) selectedItem();
if (!item)
{
item = (TreeItem *) currentItem();
while (item && item->isDirectory())
item = (TreeItem*) item->nextSibling();
}
else
item = (TreeItem *) item->firstChild();
while(item)
{
MenuEntryInfo *entry = item->entryInfo();
if (entry && (entry->menuId() == menuEntry))
{
setCurrentItem(item);
ensureItemVisible(item);
return;
}
item = (TreeItem*) item->nextSibling();
}
}
void TreeView::itemSelected(TQListViewItem *item)
{
TreeItem *_item = (TreeItem*)item;
bool selected = false;
bool dselected = false;
if (_item) {
selected = true;
dselected = _item->isHidden();
}
m_ac->action("edit_cut")->setEnabled(selected);
m_ac->action("edit_copy")->setEnabled(selected);
if (m_ac->action("delete"))
m_ac->action("delete")->setEnabled(selected && !dselected);
if(!item)
{
emit disableAction();
return;
}
if (_item->isDirectory())
emit entrySelected(_item->folderInfo());
else
emit entrySelected(_item->entryInfo());
}
void TreeView::currentChanged(MenuFolderInfo *folderInfo)
{
TreeItem *item = (TreeItem*)selectedItem();
if (item == 0) return;
if (folderInfo == 0) return;
item->setName(folderInfo->caption);
item->setPixmap(0, appIcon(folderInfo->icon));
}
void TreeView::currentChanged(MenuEntryInfo *entryInfo)
{
TreeItem *item = (TreeItem*)selectedItem();
if (item == 0) return;
if (entryInfo == 0) return;
QString name;
if (m_detailedMenuEntries && entryInfo->description.length() != 0)
{
if (m_detailedEntriesNamesFirst)
{
name = entryInfo->caption + " (" + entryInfo->description + ")";
}
else
{
name = entryInfo->description + " (" + entryInfo->caption + ")";
}
}
else
{
name = entryInfo->caption;
}
item->setName(name);
item->setPixmap(0, appIcon(entryInfo->icon));
}
TQStringList TreeView::fileList(const TQString& rPath)
{
TQString relativePath = rPath;
// truncate "/.directory"
int pos = relativePath.findRev("/.directory");
if (pos > 0) relativePath.truncate(pos);
TQStringList filelist;
// loop through all resource dirs and build a file list
TQStringList resdirlist = TDEGlobal::dirs()->resourceDirs("apps");
for (TQStringList::ConstIterator it = resdirlist.begin(); it != resdirlist.end(); ++it)
{
TQDir dir((*it) + "/" + relativePath);
if(!dir.exists()) continue;
dir.setFilter(TQDir::Files);
dir.setNameFilter("*.desktop;*.kdelnk");
// build a list of files
TQStringList files = dir.entryList();
for (TQStringList::ConstIterator it = files.begin(); it != files.end(); ++it) {
// does not work?!
//if (filelist.contains(*it)) continue;
if (relativePath.isEmpty()) {
filelist.remove(*it); // hack
filelist.append(*it);
}
else {
filelist.remove(relativePath + "/" + *it); //hack
filelist.append(relativePath + "/" + *it);
}
}
}
return filelist;
}
TQStringList TreeView::dirList(const TQString& rPath)
{
TQString relativePath = rPath;
// truncate "/.directory"
int pos = relativePath.findRev("/.directory");
if (pos > 0) relativePath.truncate(pos);
TQStringList dirlist;
// loop through all resource dirs and build a subdir list
TQStringList resdirlist = TDEGlobal::dirs()->resourceDirs("apps");
for (TQStringList::ConstIterator it = resdirlist.begin(); it != resdirlist.end(); ++it)
{
TQDir dir((*it) + "/" + relativePath);
if(!dir.exists()) continue;
dir.setFilter(TQDir::Dirs);
// build a list of subdirs
TQStringList subdirs = dir.entryList();
for (TQStringList::ConstIterator it = subdirs.begin(); it != subdirs.end(); ++it) {
if ((*it) == "." || (*it) == "..") continue;
// does not work?!
// if (dirlist.contains(*it)) continue;
if (relativePath.isEmpty()) {
dirlist.remove(*it); //hack
dirlist.append(*it);
}
else {
dirlist.remove(relativePath + "/" + *it); //hack
dirlist.append(relativePath + "/" + *it);
}
}
}
return dirlist;
}
bool TreeView::acceptDrag(TQDropEvent* e) const
{
if (e->provides("application/x-kmenuedit-internal") &&
(e->source() == const_cast<TreeView *>(this)))
return true;
KURL::List urls;
if (KURLDrag::decode(e, urls) && (urls.count() == 1) &&
urls[0].isLocalFile() && urls[0].path().endsWith(".desktop"))
return true;
return false;
}
static TQString createDesktopFile(const TQString &file, TQString *menuId, TQStringList *excludeList)
{
TQString base = file.mid(file.findRev('/')+1);
base = base.left(base.findRev('.'));
TQRegExp r("(.*)(?=-\\d+)");
base = (r.search(base) > -1) ? r.cap(1) : base;
TQString result = KService::newServicePath(true, base, menuId, excludeList);
excludeList->append(*menuId);
// Todo for Undo-support: Undo menuId allocation:
return result;
}
static KDesktopFile *copyDesktopFile(MenuEntryInfo *entryInfo, TQString *menuId, TQStringList *excludeList)
{
TQString result = createDesktopFile(entryInfo->file(), menuId, excludeList);
KDesktopFile *df = entryInfo->desktopFile()->copyTo(result);
df->deleteEntry("Categories"); // Don't set any categories!
return df;
}
static TQString createDirectoryFile(const TQString &file, TQStringList *excludeList)
{
TQString base = file.mid(file.findRev('/')+1);
base = base.left(base.findRev('.'));
TQString result;
int i = 1;
while(true)
{
if (i == 1)
result = base + ".directory";
else
result = base + TQString("-%1.directory").arg(i);
if (!excludeList->contains(result))
{
if (locate("xdgdata-dirs", result).isEmpty())
break;
}
i++;
}
excludeList->append(result);
result = locateLocal("xdgdata-dirs", result);
return result;
}
void TreeView::slotDropped (TQDropEvent * e, TQListViewItem *parent, TQListViewItem*after)
{
if(!e) return;
// get destination folder
TreeItem *parentItem = static_cast<TreeItem*>(parent);
TQString folder = parentItem ? parentItem->directory() : TQString::null;
MenuFolderInfo *parentFolderInfo = parentItem ? parentItem->folderInfo() : m_rootFolder;
if (e->source() != this)
{
// External drop
KURL::List urls;
if (!KURLDrag::decode(e, urls) || (urls.count() != 1) || !urls[0].isLocalFile())
return;
TQString path = urls[0].path();
if (!path.endsWith(".desktop"))
return;
TQString menuId;
TQString result = createDesktopFile(path, &menuId, &m_newMenuIds);
KDesktopFile orig_df(path);
KDesktopFile *df = orig_df.copyTo(result);
df->deleteEntry("Categories"); // Don't set any categories!
KService *s = new KService(df);
s->setMenuId(menuId);
MenuEntryInfo *entryInfo = new MenuEntryInfo(s, df);
TQString oldCaption = entryInfo->caption;
TQString newCaption = parentFolderInfo->uniqueItemCaption(oldCaption, oldCaption);
entryInfo->setCaption(newCaption);
// Add file to menu
// m_menuFile->addEntry(folder, menuId);
m_menuFile->pushAction(MenuFile::ADD_ENTRY, folder, menuId);
// create the TreeItem
if(parentItem)
parentItem->setOpen(true);
// update fileInfo data
parentFolderInfo->add(entryInfo);
TreeItem *newItem = createTreeItem(parentItem, after, entryInfo, true);
setSelected ( newItem, true);
itemSelected( newItem);
m_drag = 0;
setLayoutDirty(parentItem);
return;
}
// is there content in the clipboard?
if (!m_drag) return;
if (m_dragItem == after) return; // Nothing to do
int command = m_drag;
if (command == MOVE_FOLDER)
{
MenuFolderInfo *folderInfo = m_dragInfo;
if (e->action() == TQDropEvent::Copy)
{
// Ugh.. this is hard :)
// * Create new .directory file
// Add
}
else
{
TreeItem *tmpItem = static_cast<TreeItem*>(parentItem);
while ( tmpItem )
{
if ( tmpItem == m_dragItem )
{
m_drag = 0;
return;
}
tmpItem = static_cast<TreeItem*>(tmpItem->parent() );
}
// Remove MenuFolderInfo
TreeItem *oldParentItem = static_cast<TreeItem*>(m_dragItem->parent());
MenuFolderInfo *oldParentFolderInfo = oldParentItem ? oldParentItem->folderInfo() : m_rootFolder;
oldParentFolderInfo->take(folderInfo);
// Move menu
TQString oldFolder = folderInfo->fullId;
TQString folderName = folderInfo->id;
TQString newFolder = m_menuFile->uniqueMenuName(folder, folderName, parentFolderInfo->existingMenuIds());
folderInfo->id = newFolder;
// Add file to menu
//m_menuFile->moveMenu(oldFolder, folder + newFolder);
m_menuFile->pushAction(MenuFile::MOVE_MENU, oldFolder, folder + newFolder);
// Make sure caption is unique
TQString newCaption = parentFolderInfo->uniqueMenuCaption(folderInfo->caption);
if (newCaption != folderInfo->caption)
{
folderInfo->setCaption(newCaption);
}
// create the TreeItem
if(parentItem)
parentItem->setOpen(true);
// update fileInfo data
folderInfo->updateFullId(parentFolderInfo->fullId);
folderInfo->setInUse(true);
parentFolderInfo->add(folderInfo);
if ((parentItem != oldParentItem) || !after)
{
if (oldParentItem)
oldParentItem->takeItem(m_dragItem);
else
takeItem(m_dragItem);
if (parentItem)
parentItem->insertItem(m_dragItem);
else
insertItem(m_dragItem);
}
m_dragItem->moveItem(after);
m_dragItem->setName(folderInfo->caption);
m_dragItem->setDirectoryPath(folderInfo->fullId);
setSelected(m_dragItem, true);
itemSelected(m_dragItem);
}
}
else if (command == MOVE_FILE)
{
MenuEntryInfo *entryInfo = m_dragItem->entryInfo();
TQString menuId = entryInfo->menuId();
if (e->action() == TQDropEvent::Copy)
{
// Need to copy file and then add it
KDesktopFile *df = copyDesktopFile(entryInfo, &menuId, &m_newMenuIds); // Duplicate
//UNDO-ACTION: NEW_MENU_ID (menuId)
KService *s = new KService(df);
s->setMenuId(menuId);
entryInfo = new MenuEntryInfo(s, df);
TQString oldCaption = entryInfo->caption;
TQString newCaption = parentFolderInfo->uniqueItemCaption(oldCaption, oldCaption);
entryInfo->setCaption(newCaption);
}
else
{
del(m_dragItem, false);
TQString oldCaption = entryInfo->caption;
TQString newCaption = parentFolderInfo->uniqueItemCaption(oldCaption);
entryInfo->setCaption(newCaption);
entryInfo->setInUse(true);
}
// Add file to menu
// m_menuFile->addEntry(folder, menuId);
m_menuFile->pushAction(MenuFile::ADD_ENTRY, folder, menuId);
// create the TreeItem
if(parentItem)
parentItem->setOpen(true);
// update fileInfo data
parentFolderInfo->add(entryInfo);
TreeItem *newItem = createTreeItem(parentItem, after, entryInfo, true);
setSelected ( newItem, true);
itemSelected( newItem);
}
else if (command == COPY_SEPARATOR)
{
if (e->action() != TQDropEvent::Copy)
del(m_dragItem, false);
TreeItem *newItem = createTreeItem(parentItem, after, m_separator, true);
setSelected ( newItem, true);
itemSelected( newItem);
}
else
{
// Error
}
m_drag = 0;
setLayoutDirty(parentItem);
}
void TreeView::startDrag()
{
TQDragObject *drag = dragObject();
if (!drag)
return;
drag->dragMove();
}
TQDragObject *TreeView::dragObject()
{
m_dragPath = TQString::null;
TreeItem *item = (TreeItem*)selectedItem();
if(item == 0) return 0;
KMultipleDrag *drag = new KMultipleDrag( this );
if (item->isDirectory())
{
m_drag = MOVE_FOLDER;
m_dragInfo = item->folderInfo();
m_dragItem = item;
}
else if (item->isEntry())
{
m_drag = MOVE_FILE;
m_dragInfo = 0;
m_dragItem = item;
TQString menuId = item->menuId();
m_dragPath = item->entryInfo()->service->desktopEntryPath();
if (!m_dragPath.isEmpty())
m_dragPath = locate("apps", m_dragPath);
if (!m_dragPath.isEmpty())
{
KURL url;
url.setPath(m_dragPath);
drag->addDragObject( new KURLDrag(url, 0));
}
}
else
{
m_drag = COPY_SEPARATOR;
m_dragInfo = 0;
m_dragItem = item;
}
drag->addDragObject( new TQStoredDrag("application/x-kmenuedit-internal", 0));
if ( item->pixmap(0) )
drag->setPixmap(*item->pixmap(0));
return drag;
}
void TreeView::slotRMBPressed(TQListViewItem*, const TQPoint& p)
{
TreeItem *item = (TreeItem*)selectedItem();
if(item == 0) return;
if(m_rmb) m_rmb->exec(p);
}
void TreeView::newsubmenu()
{
TreeItem *parentItem = 0;
TreeItem *item = (TreeItem*)selectedItem();
bool ok;
TQString caption = KInputDialog::getText( i18n( "New Submenu" ),
i18n( "Submenu name:" ), TQString::null, &ok, this );
if (!ok) return;
TQString file = caption;
file.replace('/', '-');
file = createDirectoryFile(file, &m_newDirectoryList); // Create
// get destination folder
TQString folder;
if(!item)
{
parentItem = 0;
folder = TQString::null;
}
else if(item->isDirectory())
{
parentItem = item;
item = 0;
folder = parentItem->directory();
}
else
{
parentItem = static_cast<TreeItem*>(item->parent());
folder = parentItem ? parentItem->directory() : TQString::null;
}
MenuFolderInfo *parentFolderInfo = parentItem ? parentItem->folderInfo() : m_rootFolder;
MenuFolderInfo *folderInfo = new MenuFolderInfo();
folderInfo->caption = parentFolderInfo->uniqueMenuCaption(caption);
folderInfo->id = m_menuFile->uniqueMenuName(folder, caption, parentFolderInfo->existingMenuIds());
folderInfo->directoryFile = file;
folderInfo->icon = "package";
folderInfo->hidden = false;
folderInfo->setDirty();
KDesktopFile *df = new KDesktopFile(file);
df->writeEntry("Name", folderInfo->caption);
df->writeEntry("Icon", folderInfo->icon);
df->sync();
delete df;
// Add file to menu
// m_menuFile->addMenu(folder + folderInfo->id, file);
m_menuFile->pushAction(MenuFile::ADD_MENU, folder + folderInfo->id, file);
folderInfo->fullId = parentFolderInfo->fullId + folderInfo->id;
// create the TreeItem
if(parentItem)
parentItem->setOpen(true);
// update fileInfo data
parentFolderInfo->add(folderInfo);
TreeItem *newItem = createTreeItem(parentItem, item, folderInfo, true);
setSelected ( newItem, true);
itemSelected( newItem);
setLayoutDirty(parentItem);
}
void TreeView::newitem()
{
TreeItem *parentItem = 0;
TreeItem *item = (TreeItem*)selectedItem();
bool ok;
TQString caption = KInputDialog::getText( i18n( "New Item" ),
i18n( "Item name:" ), TQString::null, &ok, this );
if (!ok) return;
TQString menuId;
TQString file = caption;
file.replace('/', '-');
file = createDesktopFile(file, &menuId, &m_newMenuIds); // Create
KDesktopFile *df = new KDesktopFile(file);
df->writeEntry("Name", caption);
df->writeEntry("Type", "Application");
// get destination folder
TQString folder;
if(!item)
{
parentItem = 0;
folder = TQString::null;
}
else if(item->isDirectory())
{
parentItem = item;
item = 0;
folder = parentItem->directory();
}
else
{
parentItem = static_cast<TreeItem*>(item->parent());
folder = parentItem ? parentItem->directory() : TQString::null;
}
MenuFolderInfo *parentFolderInfo = parentItem ? parentItem->folderInfo() : m_rootFolder;
// Add file to menu
// m_menuFile->addEntry(folder, menuId);
m_menuFile->pushAction(MenuFile::ADD_ENTRY, folder, menuId);
KService *s = new KService(df);
s->setMenuId(menuId);
MenuEntryInfo *entryInfo = new MenuEntryInfo(s, df);
// create the TreeItem
if(parentItem)
parentItem->setOpen(true);
// update fileInfo data
parentFolderInfo->add(entryInfo);
TreeItem *newItem = createTreeItem(parentItem, item, entryInfo, true);
setSelected ( newItem, true);
itemSelected( newItem);
setLayoutDirty(parentItem);
}
void TreeView::newsep()
{
TreeItem *parentItem = 0;
TreeItem *item = (TreeItem*)selectedItem();
if(!item)
{
parentItem = 0;
}
else if(item->isDirectory())
{
parentItem = item;
item = 0;
}
else
{
parentItem = static_cast<TreeItem*>(item->parent());
}
// create the TreeItem
if(parentItem)
parentItem->setOpen(true);
TreeItem *newItem = createTreeItem(parentItem, item, m_separator, true);
setSelected ( newItem, true);
itemSelected( newItem);
setLayoutDirty(parentItem);
}
void TreeView::cut()
{
copy( true );
m_ac->action("edit_cut")->setEnabled(false);
m_ac->action("edit_copy")->setEnabled(false);
m_ac->action("delete")->setEnabled(false);
// Select new current item
setSelected( currentItem(), true );
// Switch the UI to show that item
itemSelected( selectedItem() );
}
void TreeView::copy()
{
copy( false );
}
void TreeView::copy( bool cutting )
{
TreeItem *item = (TreeItem*)selectedItem();
// nil selected? -> nil to copy
if (item == 0) return;
if (cutting)
setLayoutDirty((TreeItem*)item->parent());
// clean up old stuff
cleanupClipboard();
// is item a folder or a file?
if(item->isDirectory())
{
TQString folder = item->directory();
if (cutting)
{
// Place in clipboard
m_clipboard = MOVE_FOLDER;
m_clipboardFolderInfo = item->folderInfo();
del(item, false);
}
else
{
// Place in clipboard
m_clipboard = COPY_FOLDER;
m_clipboardFolderInfo = item->folderInfo();
}
}
else if (item->isEntry())
{
if (cutting)
{
// Place in clipboard
m_clipboard = MOVE_FILE;
m_clipboardEntryInfo = item->entryInfo();
del(item, false);
}
else
{
// Place in clipboard
m_clipboard = COPY_FILE;
m_clipboardEntryInfo = item->entryInfo();
}
}
else
{
// Place in clipboard
m_clipboard = COPY_SEPARATOR;
if (cutting)
del(item, false);
}
m_ac->action("edit_paste")->setEnabled(true);
}
void TreeView::paste()
{
TreeItem *parentItem = 0;
TreeItem *item = (TreeItem*)selectedItem();
// nil selected? -> nil to paste to
if (item == 0) return;
// is there content in the clipboard?
if (!m_clipboard) return;
// get destination folder
TQString folder;
if(item->isDirectory())
{
parentItem = item;
item = 0;
folder = parentItem->directory();
}
else
{
parentItem = static_cast<TreeItem*>(item->parent());
folder = parentItem ? parentItem->directory() : TQString::null;
}
MenuFolderInfo *parentFolderInfo = parentItem ? parentItem->folderInfo() : m_rootFolder;
int command = m_clipboard;
if ((command == COPY_FOLDER) || (command == MOVE_FOLDER))
{
MenuFolderInfo *folderInfo = m_clipboardFolderInfo;
if (command == COPY_FOLDER)
{
// Ugh.. this is hard :)
// * Create new .directory file
// Add
}
else if (command == MOVE_FOLDER)
{
// Move menu
TQString oldFolder = folderInfo->fullId;
TQString folderName = folderInfo->id;
TQString newFolder = m_menuFile->uniqueMenuName(folder, folderName, parentFolderInfo->existingMenuIds());
folderInfo->id = newFolder;
// Add file to menu
// m_menuFile->moveMenu(oldFolder, folder + newFolder);
m_menuFile->pushAction(MenuFile::MOVE_MENU, oldFolder, folder + newFolder);
// Make sure caption is unique
TQString newCaption = parentFolderInfo->uniqueMenuCaption(folderInfo->caption);
if (newCaption != folderInfo->caption)
{
folderInfo->setCaption(newCaption);
}
// create the TreeItem
if(parentItem)
parentItem->setOpen(true);
// update fileInfo data
folderInfo->fullId = parentFolderInfo->fullId + folderInfo->id;
folderInfo->setInUse(true);
parentFolderInfo->add(folderInfo);
TreeItem *newItem = createTreeItem(parentItem, item, folderInfo);
setSelected ( newItem, true);
itemSelected( newItem);
}
m_clipboard = COPY_FOLDER; // Next one copies.
}
else if ((command == COPY_FILE) || (command == MOVE_FILE))
{
MenuEntryInfo *entryInfo = m_clipboardEntryInfo;
TQString menuId;
if (command == COPY_FILE)
{
// Need to copy file and then add it
KDesktopFile *df = copyDesktopFile(entryInfo, &menuId, &m_newMenuIds); // Duplicate
KService *s = new KService(df);
s->setMenuId(menuId);
entryInfo = new MenuEntryInfo(s, df);
TQString oldCaption = entryInfo->caption;
TQString newCaption = parentFolderInfo->uniqueItemCaption(oldCaption, oldCaption);
entryInfo->setCaption(newCaption);
}
else if (command == MOVE_FILE)
{
menuId = entryInfo->menuId();
m_clipboard = COPY_FILE; // Next one copies.
TQString oldCaption = entryInfo->caption;
TQString newCaption = parentFolderInfo->uniqueItemCaption(oldCaption);
entryInfo->setCaption(newCaption);
entryInfo->setInUse(true);
}
// Add file to menu
// m_menuFile->addEntry(folder, menuId);
m_menuFile->pushAction(MenuFile::ADD_ENTRY, folder, menuId);
// create the TreeItem
if(parentItem)
parentItem->setOpen(true);
// update fileInfo data
parentFolderInfo->add(entryInfo);
TreeItem *newItem = createTreeItem(parentItem, item, entryInfo, true);
setSelected ( newItem, true);
itemSelected( newItem);
}
else
{
// create separator
if(parentItem)
parentItem->setOpen(true);
TreeItem *newItem = createTreeItem(parentItem, item, m_separator, true);
setSelected ( newItem, true);
itemSelected( newItem);
}
setLayoutDirty(parentItem);
}
void TreeView::del()
{
TreeItem *item = (TreeItem*)selectedItem();
// nil selected? -> nil to delete
if (item == 0) return;
del(item, true);
m_ac->action("edit_cut")->setEnabled(false);
m_ac->action("edit_copy")->setEnabled(false);
m_ac->action("delete")->setEnabled(false);
// Select new current item
setSelected( currentItem(), true );
// Switch the UI to show that item
itemSelected( selectedItem() );
}
void TreeView::del(TreeItem *item, bool deleteInfo)
{
TreeItem *parentItem = static_cast<TreeItem*>(item->parent());
// is file a .directory or a .desktop file
if(item->isDirectory())
{
MenuFolderInfo *folderInfo = item->folderInfo();
// Remove MenuFolderInfo
MenuFolderInfo *parentFolderInfo = parentItem ? parentItem->folderInfo() : m_rootFolder;
parentFolderInfo->take(folderInfo);
folderInfo->setInUse(false);
if (m_clipboard == COPY_FOLDER && (m_clipboardFolderInfo == folderInfo))
{
// Copy + Del == Cut
m_clipboard = MOVE_FOLDER; // Clipboard now owns folderInfo
}
else
{
if (folderInfo->takeRecursive(m_clipboardFolderInfo))
m_clipboard = MOVE_FOLDER; // Clipboard now owns m_clipboardFolderInfo
if (deleteInfo)
delete folderInfo; // Delete folderInfo
}
// Remove from menu
// m_menuFile->removeMenu(item->directory());
m_menuFile->pushAction(MenuFile::REMOVE_MENU, item->directory(), TQString::null);
// Remove tree item
delete item;
}
else if (item->isEntry())
{
MenuEntryInfo *entryInfo = item->entryInfo();
TQString menuId = entryInfo->menuId();
// Remove MenuFolderInfo
MenuFolderInfo *parentFolderInfo = parentItem ? parentItem->folderInfo() : m_rootFolder;
parentFolderInfo->take(entryInfo);
entryInfo->setInUse(false);
if (m_clipboard == COPY_FILE && (m_clipboardEntryInfo == entryInfo))
{
// Copy + Del == Cut
m_clipboard = MOVE_FILE; // Clipboard now owns entryInfo
}
else
{
if (deleteInfo)
delete entryInfo; // Delete entryInfo
}
// Remove from menu
TQString folder = parentItem ? parentItem->directory() : TQString::null;
// m_menuFile->removeEntry(folder, menuId);
m_menuFile->pushAction(MenuFile::REMOVE_ENTRY, folder, menuId);
// Remove tree item
delete item;
}
else
{
// Remove separator
delete item;
}
setLayoutDirty(parentItem);
}
void TreeView::cleanupClipboard() {
if (m_clipboard == MOVE_FOLDER)
delete m_clipboardFolderInfo;
m_clipboardFolderInfo = 0;
if (m_clipboard == MOVE_FILE)
delete m_clipboardEntryInfo;
m_clipboardEntryInfo = 0;
m_clipboard = 0;
}
static TQStringList extractLayout(TreeItem *item)
{
bool firstFolder = true;
bool firstEntry = true;
TQStringList layout;
for(;item; item = static_cast<TreeItem*>(item->nextSibling()))
{
if (item->isDirectory())
{
if (firstFolder)
{
firstFolder = false;
layout << ":M"; // Add new folders here...
}
layout << (item->folderInfo()->id);
}
else if (item->isEntry())
{
if (firstEntry)
{
firstEntry = false;
layout << ":F"; // Add new entries here...
}
layout << (item->entryInfo()->menuId());
}
else
{
layout << ":S";
}
}
return layout;
}
TQStringList TreeItem::layout()
{
TQStringList layout = extractLayout(static_cast<TreeItem*>(firstChild()));
_layoutDirty = false;
return layout;
}
void TreeView::saveLayout()
{
if (m_layoutDirty)
{
TQStringList layout = extractLayout(static_cast<TreeItem*>(firstChild()));
m_menuFile->setLayout(m_rootFolder->fullId, layout);
m_layoutDirty = false;
}
TQPtrList<TQListViewItem> lst;
TQListViewItemIterator it( this );
while ( it.current() ) {
TreeItem *item = static_cast<TreeItem*>(it.current());
if ( item->isLayoutDirty() )
{
m_menuFile->setLayout(item->folderInfo()->fullId, item->layout());
}
++it;
}
}
bool TreeView::save()
{
saveLayout();
m_rootFolder->save(m_menuFile);
bool success = m_menuFile->performAllActions();
m_newMenuIds.clear();
m_newDirectoryList.clear();
if (success)
{
KService::rebuildKSycoca(this);
}
else
{
KMessageBox::sorry(this, "<qt>"+i18n("Menu changes could not be saved because of the following problem:")+"<br><br>"+
m_menuFile->error()+"</qt>");
}
return success;
}
void TreeView::setLayoutDirty(TreeItem *parentItem)
{
if (parentItem)
parentItem->setLayoutDirty();
else
m_layoutDirty = true;
}
bool TreeView::isLayoutDirty()
{
TQPtrList<TQListViewItem> lst;
TQListViewItemIterator it( this );
while ( it.current() ) {
if ( static_cast<TreeItem*>(it.current())->isLayoutDirty() )
return true;
++it;
}
return false;
}
bool TreeView::dirty()
{
return m_layoutDirty || m_rootFolder->hasDirt() || m_menuFile->dirty() || isLayoutDirty();
}
void TreeView::findServiceShortcut(const TDEShortcut&cut, KService::Ptr &service)
{
service = m_rootFolder->findServiceShortcut(cut);
}
| Fat-Zer/tdebase | kmenuedit/treeview.cpp | C++ | gpl-2.0 | 42,979 |
/*
* Copyright (C) Dag Henning Liodden Sørbø <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "drawingview.h"
#include <QApplication>
#include "randomgenerator.h"
#include "drawingcontroller.h"
#include "drawingsetupcontroller.h"
#include "lotwindow.h"
#include "app.h"
#include <QLibraryInfo>
#include <QTranslator>
#include "color.h"
#include "settingshandler.h"
#include "selectlanguagedialog.h"
#include "updatereminder.h"
#include "updateview.h"
#include "i18n.h"
bool setLanguageToSystemLanguage() {
QString langCountry = QLocale().system().name();
QString lang = langCountry.left(2);
if (lang == "nb" || lang == "nn") {
lang = "no";
}
bool langIsSupported = false;
for (int i = 0; i < NUM_LANGUAGES; ++i) {
if (LANGUAGES[i][1] == lang) {
langIsSupported = true;
}
}
if (langIsSupported) {
SettingsHandler::setLanguage(lang);
}
return langIsSupported;
}
int setupLanguage(QApplication& app) {
if (!SettingsHandler::hasLanguage()) {
bool ok = setLanguageToSystemLanguage();
if (!ok) {
SelectLanguageDialog dialog;
if (dialog.exec() == QDialog::Rejected) {
return -1;
}
}
}
QString language = SettingsHandler::language();
if (language != "en") {
QTranslator* translator = new QTranslator();
QString filename = QString(language).append(".qm");
translator->load(filename, ":/app/translations");
app.installTranslator(translator);
}
return 0;
}
int main(int argc, char *argv[])
{
RandomGenerator::init();
qRegisterMetaTypeStreamOperators<Color>("Color");
QApplication app(argc, argv);
app.setApplicationName(APPLICATION_NAME);
app.setApplicationDisplayName(APPLICATION_NAME);
app.setApplicationVersion(APPLICATION_VERSION);
app.setOrganizationName(ORG_NAME);
app.setOrganizationDomain(ORG_DOMAIN);
QIcon icon(":/gui/icons/lots.svg");
app.setWindowIcon(icon);
#ifdef Q_OS_MAC
app.setAttribute(Qt::AA_DontShowIconsInMenus, true);
#endif
SettingsHandler::initialize(ORG_NAME, APPLICATION_NAME);
if (int res = setupLanguage(app) != 0) {
return res;
}
DrawingSetupController setupController;
DrawingSetupDialog setupDialog(&setupController);
DrawingController controller;
DrawingView drawingView(&controller, &setupDialog);
controller.setDrawingView(&drawingView);
UpdateView updateView(&setupDialog);
UpdateReminder reminder([&](UpdateInfo info) {
if (!info.hasError && info.hasUpdate) {
updateView.setUpdateInfo(info);
updateView.show();
}
});
if (!SettingsHandler::autoUpdatesDisabled()) {
reminder.checkForUpdate();
}
return app.exec();
}
| Soerboe/Urim | app/main.cpp | C++ | gpl-2.0 | 3,410 |
#include "../comedidev.h"
#include "comedi_pci.h"
#include "8255.h"
#define PCI_VENDOR_ID_CB 0x1307 /* PCI vendor number of ComputerBoards */
#define EEPROM_SIZE 128 /* number of entries in eeprom */
#define MAX_AO_CHANNELS 8 /* maximum number of ao channels for supported boards */
/* PCI-DDA base addresses */
#define DIGITALIO_BADRINDEX 2
/* DIGITAL I/O is pci_dev->resource[2] */
#define DIGITALIO_SIZE 8
/* DIGITAL I/O uses 8 I/O port addresses */
#define DAC_BADRINDEX 3
/* DAC is pci_dev->resource[3] */
/* Digital I/O registers */
#define PORT1A 0 /* PORT 1A DATA */
#define PORT1B 1 /* PORT 1B DATA */
#define PORT1C 2 /* PORT 1C DATA */
#define CONTROL1 3 /* CONTROL REGISTER 1 */
#define PORT2A 4 /* PORT 2A DATA */
#define PORT2B 5 /* PORT 2B DATA */
#define PORT2C 6 /* PORT 2C DATA */
#define CONTROL2 7 /* CONTROL REGISTER 2 */
/* DAC registers */
#define DACONTROL 0 /* D/A CONTROL REGISTER */
#define SU 0000001 /* Simultaneous update enabled */
#define NOSU 0000000 /* Simultaneous update disabled */
#define ENABLEDAC 0000002 /* Enable specified DAC */
#define DISABLEDAC 0000000 /* Disable specified DAC */
#define RANGE2V5 0000000 /* 2.5V */
#define RANGE5V 0000200 /* 5V */
#define RANGE10V 0000300 /* 10V */
#define UNIP 0000400 /* Unipolar outputs */
#define BIP 0000000 /* Bipolar outputs */
#define DACALIBRATION1 4 /* D/A CALIBRATION REGISTER 1 */
/* write bits */
#define SERIAL_IN_BIT 0x1 /* serial data input for eeprom, caldacs, reference dac */
#define CAL_CHANNEL_MASK (0x7 << 1)
#define CAL_CHANNEL_BITS(channel) (((channel) << 1) & CAL_CHANNEL_MASK)
/* read bits */
#define CAL_COUNTER_MASK 0x1f
#define CAL_COUNTER_OVERFLOW_BIT 0x20 /* calibration counter overflow status bit */
#define AO_BELOW_REF_BIT 0x40 /* analog output is less than reference dac voltage */
#define SERIAL_OUT_BIT 0x80 /* serial data out, for reading from eeprom */
#define DACALIBRATION2 6 /* D/A CALIBRATION REGISTER 2 */
#define SELECT_EEPROM_BIT 0x1 /* send serial data in to eeprom */
#define DESELECT_REF_DAC_BIT 0x2 /* don't send serial data to MAX542 reference dac */
#define DESELECT_CALDAC_BIT(n) (0x4 << (n)) /* don't send serial data to caldac n */
#define DUMMY_BIT 0x40 /* manual says to set this bit with no explanation */
#define DADATA 8 /* FIRST D/A DATA REGISTER (0) */
static const struct comedi_lrange cb_pcidda_ranges = {
6,
{
BIP_RANGE(10),
BIP_RANGE(5),
BIP_RANGE(2.5),
UNI_RANGE(10),
UNI_RANGE(5),
UNI_RANGE(2.5),
}
};
struct cb_pcidda_board {
const char *name;
char status; /* Driver status: */
/*
* 0 - tested
* 1 - manual read, not tested
* 2 - manual not read
*/
unsigned short device_id;
int ao_chans;
int ao_bits;
const struct comedi_lrange *ranges;
};
static const struct cb_pcidda_board cb_pcidda_boards[] = {
{
.name = "pci-dda02/12",
.status = 1,
.device_id = 0x20,
.ao_chans = 2,
.ao_bits = 12,
.ranges = &cb_pcidda_ranges,
},
{
.name = "pci-dda04/12",
.status = 1,
.device_id = 0x21,
.ao_chans = 4,
.ao_bits = 12,
.ranges = &cb_pcidda_ranges,
},
{
.name = "pci-dda08/12",
.status = 0,
.device_id = 0x22,
.ao_chans = 8,
.ao_bits = 12,
.ranges = &cb_pcidda_ranges,
},
{
.name = "pci-dda02/16",
.status = 2,
.device_id = 0x23,
.ao_chans = 2,
.ao_bits = 16,
.ranges = &cb_pcidda_ranges,
},
{
.name = "pci-dda04/16",
.status = 2,
.device_id = 0x24,
.ao_chans = 4,
.ao_bits = 16,
.ranges = &cb_pcidda_ranges,
},
{
.name = "pci-dda08/16",
.status = 0,
.device_id = 0x25,
.ao_chans = 8,
.ao_bits = 16,
.ranges = &cb_pcidda_ranges,
},
};
static DEFINE_PCI_DEVICE_TABLE(cb_pcidda_pci_table) = {
{
PCI_VENDOR_ID_CB, 0x0020, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0}, {
PCI_VENDOR_ID_CB, 0x0021, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0}, {
PCI_VENDOR_ID_CB, 0x0022, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0}, {
PCI_VENDOR_ID_CB, 0x0023, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0}, {
PCI_VENDOR_ID_CB, 0x0024, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0}, {
PCI_VENDOR_ID_CB, 0x0025, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0}, {
0}
};
MODULE_DEVICE_TABLE(pci, cb_pcidda_pci_table);
#define thisboard ((const struct cb_pcidda_board *)dev->board_ptr)
struct cb_pcidda_private {
int data;
/* would be useful for a PCI device */
struct pci_dev *pci_dev;
unsigned long digitalio;
unsigned long dac;
/* unsigned long control_status; */
/* unsigned long adc_fifo; */
unsigned int dac_cal1_bits; /* bits last written to da calibration register 1 */
unsigned int ao_range[MAX_AO_CHANNELS]; /* current range settings for output channels */
u16 eeprom_data[EEPROM_SIZE]; /* software copy of board's eeprom */
};
#define devpriv ((struct cb_pcidda_private *)dev->private)
static int cb_pcidda_attach(struct comedi_device *dev,
struct comedi_devconfig *it);
static int cb_pcidda_detach(struct comedi_device *dev);
/* static int cb_pcidda_ai_rinsn(struct comedi_device *dev,struct comedi_subdevice *s,struct comedi_insn *insn,unsigned int *data); */
static int cb_pcidda_ao_winsn(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data);
/* static int cb_pcidda_ai_cmd(struct comedi_device *dev, struct *comedi_subdevice *s);*/
/* static int cb_pcidda_ai_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s, struct comedi_cmd *cmd); */
/* static int cb_pcidda_ns_to_timer(unsigned int *ns,int *round); */
static unsigned int cb_pcidda_serial_in(struct comedi_device *dev);
static void cb_pcidda_serial_out(struct comedi_device *dev, unsigned int value,
unsigned int num_bits);
static unsigned int cb_pcidda_read_eeprom(struct comedi_device *dev,
unsigned int address);
static void cb_pcidda_calibrate(struct comedi_device *dev, unsigned int channel,
unsigned int range);
static struct comedi_driver driver_cb_pcidda = {
.driver_name = "cb_pcidda",
.module = THIS_MODULE,
.attach = cb_pcidda_attach,
.detach = cb_pcidda_detach,
};
static int cb_pcidda_attach(struct comedi_device *dev,
struct comedi_devconfig *it)
{
struct comedi_subdevice *s;
struct pci_dev *pcidev;
int index;
printk("comedi%d: cb_pcidda: ", dev->minor);
if (alloc_private(dev, sizeof(struct cb_pcidda_private)) < 0)
return -ENOMEM;
printk("\n");
for (pcidev = pci_get_device(PCI_ANY_ID, PCI_ANY_ID, NULL);
pcidev != NULL;
pcidev = pci_get_device(PCI_ANY_ID, PCI_ANY_ID, pcidev)) {
if (pcidev->vendor == PCI_VENDOR_ID_CB) {
if (it->options[0] || it->options[1]) {
if (pcidev->bus->number != it->options[0] ||
PCI_SLOT(pcidev->devfn) != it->options[1]) {
continue;
}
}
for (index = 0; index < ARRAY_SIZE(cb_pcidda_boards); index++) {
if (cb_pcidda_boards[index].device_id ==
pcidev->device) {
goto found;
}
}
}
}
if (!pcidev) {
printk
("Not a ComputerBoards/MeasurementComputing card on requested position\n");
return -EIO;
}
found:
devpriv->pci_dev = pcidev;
dev->board_ptr = cb_pcidda_boards + index;
/* "thisboard" macro can be used from here. */
printk("Found %s at requested position\n", thisboard->name);
/*
* Enable PCI device and request regions.
*/
if (comedi_pci_enable(pcidev, thisboard->name)) {
printk
("cb_pcidda: failed to enable PCI device and request regions\n");
return -EIO;
}
devpriv->digitalio =
pci_resource_start(devpriv->pci_dev, DIGITALIO_BADRINDEX);
devpriv->dac = pci_resource_start(devpriv->pci_dev, DAC_BADRINDEX);
if (thisboard->status == 2)
printk
("WARNING: DRIVER FOR THIS BOARD NOT CHECKED WITH MANUAL. "
"WORKS ASSUMING FULL COMPATIBILITY WITH PCI-DDA08/12. "
"PLEASE REPORT USAGE TO <[email protected]>.\n");
dev->board_name = thisboard->name;
if (alloc_subdevices(dev, 3) < 0)
return -ENOMEM;
s = dev->subdevices + 0;
/* analog output subdevice */
s->type = COMEDI_SUBD_AO;
s->subdev_flags = SDF_WRITABLE;
s->n_chan = thisboard->ao_chans;
s->maxdata = (1 << thisboard->ao_bits) - 1;
s->range_table = thisboard->ranges;
s->insn_write = cb_pcidda_ao_winsn;
/* s->subdev_flags |= SDF_CMD_READ; */
/* s->do_cmd = cb_pcidda_ai_cmd; */
/* s->do_cmdtest = cb_pcidda_ai_cmdtest; */
/* two 8255 digital io subdevices */
s = dev->subdevices + 1;
subdev_8255_init(dev, s, NULL, devpriv->digitalio);
s = dev->subdevices + 2;
subdev_8255_init(dev, s, NULL, devpriv->digitalio + PORT2A);
printk(" eeprom:");
for (index = 0; index < EEPROM_SIZE; index++) {
devpriv->eeprom_data[index] = cb_pcidda_read_eeprom(dev, index);
printk(" %i:0x%x ", index, devpriv->eeprom_data[index]);
}
printk("\n");
/* set calibrations dacs */
for (index = 0; index < thisboard->ao_chans; index++)
cb_pcidda_calibrate(dev, index, devpriv->ao_range[index]);
return 1;
}
static int cb_pcidda_detach(struct comedi_device *dev)
{
if (devpriv) {
if (devpriv->pci_dev) {
if (devpriv->dac)
comedi_pci_disable(devpriv->pci_dev);
pci_dev_put(devpriv->pci_dev);
}
}
/* cleanup 8255 */
if (dev->subdevices) {
subdev_8255_cleanup(dev, dev->subdevices + 1);
subdev_8255_cleanup(dev, dev->subdevices + 2);
}
printk("comedi%d: cb_pcidda: remove\n", dev->minor);
return 0;
}
#if 0
static int cb_pcidda_ai_cmd(struct comedi_device *dev,
struct comedi_subdevice *s)
{
printk("cb_pcidda_ai_cmd\n");
printk("subdev: %d\n", cmd->subdev);
printk("flags: %d\n", cmd->flags);
printk("start_src: %d\n", cmd->start_src);
printk("start_arg: %d\n", cmd->start_arg);
printk("scan_begin_src: %d\n", cmd->scan_begin_src);
printk("convert_src: %d\n", cmd->convert_src);
printk("convert_arg: %d\n", cmd->convert_arg);
printk("scan_end_src: %d\n", cmd->scan_end_src);
printk("scan_end_arg: %d\n", cmd->scan_end_arg);
printk("stop_src: %d\n", cmd->stop_src);
printk("stop_arg: %d\n", cmd->stop_arg);
printk("chanlist_len: %d\n", cmd->chanlist_len);
}
#endif
#if 0
static int cb_pcidda_ai_cmdtest(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_cmd *cmd)
{
int err = 0;
int tmp;
/* cmdtest tests a particular command to see if it is valid.
* Using the cmdtest ioctl, a user can create a valid cmd
* and then have it executes by the cmd ioctl.
*
* cmdtest returns 1,2,3,4 or 0, depending on which tests
* the command passes. */
/* step 1: make sure trigger sources are trivially valid */
tmp = cmd->start_src;
cmd->start_src &= TRIG_NOW;
if (!cmd->start_src || tmp != cmd->start_src)
err++;
tmp = cmd->scan_begin_src;
cmd->scan_begin_src &= TRIG_TIMER | TRIG_EXT;
if (!cmd->scan_begin_src || tmp != cmd->scan_begin_src)
err++;
tmp = cmd->convert_src;
cmd->convert_src &= TRIG_TIMER | TRIG_EXT;
if (!cmd->convert_src || tmp != cmd->convert_src)
err++;
tmp = cmd->scan_end_src;
cmd->scan_end_src &= TRIG_COUNT;
if (!cmd->scan_end_src || tmp != cmd->scan_end_src)
err++;
tmp = cmd->stop_src;
cmd->stop_src &= TRIG_COUNT | TRIG_NONE;
if (!cmd->stop_src || tmp != cmd->stop_src)
err++;
if (err)
return 1;
/* step 2: make sure trigger sources are unique and mutually compatible */
/* note that mutual compatibility is not an issue here */
if (cmd->scan_begin_src != TRIG_TIMER
&& cmd->scan_begin_src != TRIG_EXT)
err++;
if (cmd->convert_src != TRIG_TIMER && cmd->convert_src != TRIG_EXT)
err++;
if (cmd->stop_src != TRIG_TIMER && cmd->stop_src != TRIG_EXT)
err++;
if (err)
return 2;
/* step 3: make sure arguments are trivially compatible */
if (cmd->start_arg != 0) {
cmd->start_arg = 0;
err++;
}
#define MAX_SPEED 10000 /* in nanoseconds */
#define MIN_SPEED 1000000000 /* in nanoseconds */
if (cmd->scan_begin_src == TRIG_TIMER) {
if (cmd->scan_begin_arg < MAX_SPEED) {
cmd->scan_begin_arg = MAX_SPEED;
err++;
}
if (cmd->scan_begin_arg > MIN_SPEED) {
cmd->scan_begin_arg = MIN_SPEED;
err++;
}
} else {
/* external trigger */
/* should be level/edge, hi/lo specification here */
/* should specify multiple external triggers */
if (cmd->scan_begin_arg > 9) {
cmd->scan_begin_arg = 9;
err++;
}
}
if (cmd->convert_src == TRIG_TIMER) {
if (cmd->convert_arg < MAX_SPEED) {
cmd->convert_arg = MAX_SPEED;
err++;
}
if (cmd->convert_arg > MIN_SPEED) {
cmd->convert_arg = MIN_SPEED;
err++;
}
} else {
/* external trigger */
/* see above */
if (cmd->convert_arg > 9) {
cmd->convert_arg = 9;
err++;
}
}
if (cmd->scan_end_arg != cmd->chanlist_len) {
cmd->scan_end_arg = cmd->chanlist_len;
err++;
}
if (cmd->stop_src == TRIG_COUNT) {
if (cmd->stop_arg > 0x00ffffff) {
cmd->stop_arg = 0x00ffffff;
err++;
}
} else {
/* TRIG_NONE */
if (cmd->stop_arg != 0) {
cmd->stop_arg = 0;
err++;
}
}
if (err)
return 3;
/* step 4: fix up any arguments */
if (cmd->scan_begin_src == TRIG_TIMER) {
tmp = cmd->scan_begin_arg;
cb_pcidda_ns_to_timer(&cmd->scan_begin_arg,
cmd->flags & TRIG_ROUND_MASK);
if (tmp != cmd->scan_begin_arg)
err++;
}
if (cmd->convert_src == TRIG_TIMER) {
tmp = cmd->convert_arg;
cb_pcidda_ns_to_timer(&cmd->convert_arg,
cmd->flags & TRIG_ROUND_MASK);
if (tmp != cmd->convert_arg)
err++;
if (cmd->scan_begin_src == TRIG_TIMER &&
cmd->scan_begin_arg <
cmd->convert_arg * cmd->scan_end_arg) {
cmd->scan_begin_arg =
cmd->convert_arg * cmd->scan_end_arg;
err++;
}
}
if (err)
return 4;
return 0;
}
#endif
#if 0
static int cb_pcidda_ns_to_timer(unsigned int *ns, int round)
{
/* trivial timer */
return *ns;
}
#endif
static int cb_pcidda_ao_winsn(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
unsigned int command;
unsigned int channel, range;
channel = CR_CHAN(insn->chanspec);
range = CR_RANGE(insn->chanspec);
/* adjust calibration dacs if range has changed */
if (range != devpriv->ao_range[channel])
cb_pcidda_calibrate(dev, channel, range);
/* output channel configuration */
command = NOSU | ENABLEDAC;
/* output channel range */
switch (range) {
case 0:
command |= BIP | RANGE10V;
break;
case 1:
command |= BIP | RANGE5V;
break;
case 2:
command |= BIP | RANGE2V5;
break;
case 3:
command |= UNIP | RANGE10V;
break;
case 4:
command |= UNIP | RANGE5V;
break;
case 5:
command |= UNIP | RANGE2V5;
break;
};
/* output channel specification */
command |= channel << 2;
outw(command, devpriv->dac + DACONTROL);
/* write data */
outw(data[0], devpriv->dac + DADATA + channel * 2);
/* return the number of samples read/written */
return 1;
}
/* lowlevel read from eeprom */
static unsigned int cb_pcidda_serial_in(struct comedi_device *dev)
{
unsigned int value = 0;
int i;
const int value_width = 16; /* number of bits wide values are */
for (i = 1; i <= value_width; i++) {
/* read bits most significant bit first */
if (inw_p(devpriv->dac + DACALIBRATION1) & SERIAL_OUT_BIT)
value |= 1 << (value_width - i);
}
return value;
}
/* lowlevel write to eeprom/dac */
static void cb_pcidda_serial_out(struct comedi_device *dev, unsigned int value,
unsigned int num_bits)
{
int i;
for (i = 1; i <= num_bits; i++) {
/* send bits most significant bit first */
if (value & (1 << (num_bits - i)))
devpriv->dac_cal1_bits |= SERIAL_IN_BIT;
else
devpriv->dac_cal1_bits &= ~SERIAL_IN_BIT;
outw_p(devpriv->dac_cal1_bits, devpriv->dac + DACALIBRATION1);
}
}
/* reads a 16 bit value from board's eeprom */
static unsigned int cb_pcidda_read_eeprom(struct comedi_device *dev,
unsigned int address)
{
unsigned int i;
unsigned int cal2_bits;
unsigned int value;
const int max_num_caldacs = 4; /* one caldac for every two dac channels */
const int read_instruction = 0x6; /* bits to send to tell eeprom we want to read */
const int instruction_length = 3;
const int address_length = 8;
/* send serial output stream to eeprom */
cal2_bits = SELECT_EEPROM_BIT | DESELECT_REF_DAC_BIT | DUMMY_BIT;
/* deactivate caldacs (one caldac for every two channels) */
for (i = 0; i < max_num_caldacs; i++)
cal2_bits |= DESELECT_CALDAC_BIT(i);
outw_p(cal2_bits, devpriv->dac + DACALIBRATION2);
/* tell eeprom we want to read */
cb_pcidda_serial_out(dev, read_instruction, instruction_length);
/* send address we want to read from */
cb_pcidda_serial_out(dev, address, address_length);
value = cb_pcidda_serial_in(dev);
/* deactivate eeprom */
cal2_bits &= ~SELECT_EEPROM_BIT;
outw_p(cal2_bits, devpriv->dac + DACALIBRATION2);
return value;
}
/* writes to 8 bit calibration dacs */
static void cb_pcidda_write_caldac(struct comedi_device *dev,
unsigned int caldac, unsigned int channel,
unsigned int value)
{
unsigned int cal2_bits;
unsigned int i;
const int num_channel_bits = 3; /* caldacs use 3 bit channel specification */
const int num_caldac_bits = 8; /* 8 bit calibration dacs */
const int max_num_caldacs = 4; /* one caldac for every two dac channels */
/* write 3 bit channel */
cb_pcidda_serial_out(dev, channel, num_channel_bits);
/* write 8 bit caldac value */
cb_pcidda_serial_out(dev, value, num_caldac_bits);
cal2_bits = DESELECT_REF_DAC_BIT | DUMMY_BIT;
/* deactivate caldacs (one caldac for every two channels) */
for (i = 0; i < max_num_caldacs; i++)
cal2_bits |= DESELECT_CALDAC_BIT(i);
/* activate the caldac we want */
cal2_bits &= ~DESELECT_CALDAC_BIT(caldac);
outw_p(cal2_bits, devpriv->dac + DACALIBRATION2);
/* deactivate caldac */
cal2_bits |= DESELECT_CALDAC_BIT(caldac);
outw_p(cal2_bits, devpriv->dac + DACALIBRATION2);
}
/* returns caldac that calibrates given analog out channel */
static unsigned int caldac_number(unsigned int channel)
{
return channel / 2;
}
/* returns caldac channel that provides fine gain for given ao channel */
static unsigned int fine_gain_channel(unsigned int ao_channel)
{
return 4 * (ao_channel % 2);
}
/* returns caldac channel that provides coarse gain for given ao channel */
static unsigned int coarse_gain_channel(unsigned int ao_channel)
{
return 1 + 4 * (ao_channel % 2);
}
/* returns caldac channel that provides coarse offset for given ao channel */
static unsigned int coarse_offset_channel(unsigned int ao_channel)
{
return 2 + 4 * (ao_channel % 2);
}
/* returns caldac channel that provides fine offset for given ao channel */
static unsigned int fine_offset_channel(unsigned int ao_channel)
{
return 3 + 4 * (ao_channel % 2);
}
/* returns eeprom address that provides offset for given ao channel and range */
static unsigned int offset_eeprom_address(unsigned int ao_channel,
unsigned int range)
{
return 0x7 + 2 * range + 12 * ao_channel;
}
/* returns eeprom address that provides gain calibration for given ao channel and range */
static unsigned int gain_eeprom_address(unsigned int ao_channel,
unsigned int range)
{
return 0x8 + 2 * range + 12 * ao_channel;
}
/* returns upper byte of eeprom entry, which gives the coarse adjustment values */
static unsigned int eeprom_coarse_byte(unsigned int word)
{
return (word >> 8) & 0xff;
}
/* returns lower byte of eeprom entry, which gives the fine adjustment values */
static unsigned int eeprom_fine_byte(unsigned int word)
{
return word & 0xff;
}
/* set caldacs to eeprom values for given channel and range */
static void cb_pcidda_calibrate(struct comedi_device *dev, unsigned int channel,
unsigned int range)
{
unsigned int coarse_offset, fine_offset, coarse_gain, fine_gain;
/* remember range so we can tell when we need to readjust calibration */
devpriv->ao_range[channel] = range;
/* get values from eeprom data */
coarse_offset =
eeprom_coarse_byte(devpriv->eeprom_data
[offset_eeprom_address(channel, range)]);
fine_offset =
eeprom_fine_byte(devpriv->eeprom_data
[offset_eeprom_address(channel, range)]);
coarse_gain =
eeprom_coarse_byte(devpriv->eeprom_data
[gain_eeprom_address(channel, range)]);
fine_gain =
eeprom_fine_byte(devpriv->eeprom_data
[gain_eeprom_address(channel, range)]);
/* set caldacs */
cb_pcidda_write_caldac(dev, caldac_number(channel),
coarse_offset_channel(channel), coarse_offset);
cb_pcidda_write_caldac(dev, caldac_number(channel),
fine_offset_channel(channel), fine_offset);
cb_pcidda_write_caldac(dev, caldac_number(channel),
coarse_gain_channel(channel), coarse_gain);
cb_pcidda_write_caldac(dev, caldac_number(channel),
fine_gain_channel(channel), fine_gain);
}
COMEDI_PCI_INITCLEANUP(driver_cb_pcidda, cb_pcidda_pci_table);
| luckasfb/OT_903D-kernel-2.6.35.7 | kernel/drivers/staging/comedi/drivers/cb_pcidda.c | C | gpl-2.0 | 20,633 |
#ifndef SCSI_TRANSPORT_SRP_H
#define SCSI_TRANSPORT_SRP_H
#include <linux/transport_class.h>
#include <linux/types.h>
#include <linux/mutex.h>
#define SRP_RPORT_ROLE_INITIATOR 0
#define SRP_RPORT_ROLE_TARGET 1
struct srp_rport_identifiers {
u8 port_id[16];
u8 roles;
};
struct srp_rport {
struct device dev;
u8 port_id[16];
u8 roles;
};
struct srp_function_template {
/* for target drivers */
int (* tsk_mgmt_response)(struct Scsi_Host *, u64, u64, int);
int (* it_nexus_response)(struct Scsi_Host *, u64, int);
};
extern struct scsi_transport_template *
srp_attach_transport(struct srp_function_template *);
extern void srp_release_transport(struct scsi_transport_template *);
extern struct srp_rport *srp_rport_add(struct Scsi_Host *,
struct srp_rport_identifiers *);
extern void srp_rport_del(struct srp_rport *);
extern void srp_remove_host(struct Scsi_Host *);
#endif
| luckasfb/OT_903D-kernel-2.6.35.7 | kernel/include/scsi/scsi_transport_srp.h | C | gpl-2.0 | 903 |
/** ======================================================================== */
/** */
/** @copyright Copyright (c) 2010-2015, S2S s.r.l. */
/** @license http://www.gnu.org/licenses/gpl-2.0.html GNU Public License v.2 */
/** @version 6.0 */
/** This file is part of SdS - Sistema della Sicurezza . */
/** SdS - Sistema della Sicurezza 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. */
/** SdS - Sistema della Sicurezza 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 SdS - Sistema della Sicurezza . If not, see <http://www.gnu.org/licenses/gpl-2.0.html> GNU Public License v.2 */
/** */
/** ======================================================================== */
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.apconsulting.luna.ejb.Corsi;
/**
*
* @author Dario
*/
public class MaterialeCorso_View implements java.io.Serializable {
public long COD_DOC;
public String TIT_DOC;
public java.sql.Date DAT_REV_DOC;
public String RSP_DOC;
public String NOME_FILE;
}
| s2sprodotti/SDS | SistemaDellaSicurezza/src/com/apconsulting/luna/ejb/Corsi/MaterialeCorso_View.java | Java | gpl-2.0 | 1,710 |
/*
* Copyright (C) 2014-2017 StormCore
*
* 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 "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "SpellAuraEffects.h"
#include "SpellScript.h"
#include "vault_of_archavon.h"
enum Events
{
// Koralon
EVENT_BURNING_BREATH = 1,
EVENT_BURNING_FURY = 2,
EVENT_FLAME_CINDER = 3,
EVENT_METEOR_FISTS = 4,
// Flame Warder
EVENT_FW_LAVA_BIRST = 5,
EVENT_FW_METEOR_FISTS = 6
};
enum Spells
{
// Spells Koralon
SPELL_BURNING_BREATH = 66665,
SPELL_BURNING_FURY = 66721,
SPELL_FLAME_CINDER_A = 66684,
SPELL_FLAME_CINDER_B = 66681, // don't know the real relation to SPELL_FLAME_CINDER_A atm.
SPELL_METEOR_FISTS = 66725,
SPELL_METEOR_FISTS_DAMAGE = 66765,
// Spells Flame Warder
SPELL_FW_LAVA_BIRST = 66813,
SPELL_FW_METEOR_FISTS = 66808,
SPELL_FW_METEOR_FISTS_DAMAGE = 66809
};
class boss_koralon : public CreatureScript
{
public:
boss_koralon() : CreatureScript("boss_koralon") { }
struct boss_koralonAI : public BossAI
{
boss_koralonAI(Creature* creature) : BossAI(creature, DATA_KORALON)
{
}
void EnterCombat(Unit* /*who*/) override
{
DoCast(me, SPELL_BURNING_FURY);
events.ScheduleEvent(EVENT_BURNING_FURY, 20000); /// @todo check timer
events.ScheduleEvent(EVENT_BURNING_BREATH, 15000); // 1st after 15sec, then every 45sec
events.ScheduleEvent(EVENT_METEOR_FISTS, 75000); // 1st after 75sec, then every 45sec
events.ScheduleEvent(EVENT_FLAME_CINDER, 30000); /// @todo check timer
_EnterCombat();
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
return;
events.Update(diff);
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
while (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_BURNING_FURY:
DoCast(me, SPELL_BURNING_FURY);
events.ScheduleEvent(EVENT_BURNING_FURY, 20000);
break;
case EVENT_BURNING_BREATH:
DoCast(me, SPELL_BURNING_BREATH);
events.ScheduleEvent(EVENT_BURNING_BREATH, 45000);
break;
case EVENT_METEOR_FISTS:
DoCast(me, SPELL_METEOR_FISTS);
events.ScheduleEvent(EVENT_METEOR_FISTS, 45000);
break;
case EVENT_FLAME_CINDER:
DoCast(me, SPELL_FLAME_CINDER_A);
events.ScheduleEvent(EVENT_FLAME_CINDER, 30000);
break;
default:
break;
}
}
DoMeleeAttackIfReady();
}
};
CreatureAI* GetAI(Creature* creature) const override
{
return new boss_koralonAI(creature);
}
};
/*######
## Npc Flame Warder
######*/
class npc_flame_warder : public CreatureScript
{
public:
npc_flame_warder() : CreatureScript("npc_flame_warder") { }
struct npc_flame_warderAI : public ScriptedAI
{
npc_flame_warderAI(Creature* creature) : ScriptedAI(creature)
{
}
void Reset() override
{
events.Reset();
}
void EnterCombat(Unit* /*who*/) override
{
DoZoneInCombat();
events.ScheduleEvent(EVENT_FW_LAVA_BIRST, 5000);
events.ScheduleEvent(EVENT_FW_METEOR_FISTS, 10000);
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
return;
events.Update(diff);
while (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_FW_LAVA_BIRST:
DoCastVictim(SPELL_FW_LAVA_BIRST);
events.ScheduleEvent(EVENT_FW_LAVA_BIRST, 15000);
break;
case EVENT_FW_METEOR_FISTS:
DoCast(me, SPELL_FW_METEOR_FISTS);
events.ScheduleEvent(EVENT_FW_METEOR_FISTS, 20000);
break;
default:
break;
}
}
DoMeleeAttackIfReady();
}
private:
EventMap events;
};
CreatureAI* GetAI(Creature* creature) const override
{
return new npc_flame_warderAI(creature);
}
};
class spell_koralon_meteor_fists : public SpellScriptLoader
{
public:
spell_koralon_meteor_fists() : SpellScriptLoader("spell_koralon_meteor_fists") { }
class spell_koralon_meteor_fists_AuraScript : public AuraScript
{
PrepareAuraScript(spell_koralon_meteor_fists_AuraScript);
bool Validate(SpellInfo const* /*spellInfo*/) override
{
if (!sSpellMgr->GetSpellInfo(SPELL_METEOR_FISTS_DAMAGE))
return false;
return true;
}
void TriggerFists(AuraEffect const* aurEff, ProcEventInfo& eventInfo)
{
PreventDefaultAction();
GetTarget()->CastSpell(eventInfo.GetProcTarget(), SPELL_METEOR_FISTS_DAMAGE, true, NULL, aurEff);
}
void Register() override
{
OnEffectProc += AuraEffectProcFn(spell_koralon_meteor_fists_AuraScript::TriggerFists, EFFECT_0, SPELL_AURA_DUMMY);
}
};
AuraScript* GetAuraScript() const override
{
return new spell_koralon_meteor_fists_AuraScript();
}
};
class spell_koralon_meteor_fists_damage : public SpellScriptLoader
{
public:
spell_koralon_meteor_fists_damage() : SpellScriptLoader("spell_koralon_meteor_fists_damage") { }
class spell_koralon_meteor_fists_damage_SpellScript : public SpellScript
{
PrepareSpellScript(spell_koralon_meteor_fists_damage_SpellScript);
public:
spell_koralon_meteor_fists_damage_SpellScript()
{
_chainTargets = 0;
}
private:
void FilterTargets(std::list<WorldObject*>& targets)
{
_chainTargets = targets.size();
}
void CalculateSplitDamage()
{
if (_chainTargets)
SetHitDamage(GetHitDamage() / (_chainTargets + 1));
}
void Register() override
{
OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_koralon_meteor_fists_damage_SpellScript::FilterTargets, EFFECT_0, TARGET_UNIT_TARGET_ENEMY);
OnHit += SpellHitFn(spell_koralon_meteor_fists_damage_SpellScript::CalculateSplitDamage);
}
private:
uint8 _chainTargets;
};
SpellScript* GetSpellScript() const override
{
return new spell_koralon_meteor_fists_damage_SpellScript();
}
};
class spell_flame_warder_meteor_fists : public SpellScriptLoader
{
public:
spell_flame_warder_meteor_fists() : SpellScriptLoader("spell_flame_warder_meteor_fists") { }
class spell_flame_warder_meteor_fists_AuraScript : public AuraScript
{
PrepareAuraScript(spell_flame_warder_meteor_fists_AuraScript);
bool Validate(SpellInfo const* /*spellInfo*/) override
{
if (!sSpellMgr->GetSpellInfo(SPELL_FW_METEOR_FISTS_DAMAGE))
return false;
return true;
}
void TriggerFists(AuraEffect const* aurEff, ProcEventInfo& eventInfo)
{
PreventDefaultAction();
GetTarget()->CastSpell(eventInfo.GetProcTarget(), SPELL_FW_METEOR_FISTS_DAMAGE, true, NULL, aurEff);
}
void Register() override
{
OnEffectProc += AuraEffectProcFn(spell_flame_warder_meteor_fists_AuraScript::TriggerFists, EFFECT_0, SPELL_AURA_DUMMY);
}
};
AuraScript* GetAuraScript() const override
{
return new spell_flame_warder_meteor_fists_AuraScript();
}
};
void AddSC_boss_koralon()
{
new boss_koralon();
new npc_flame_warder();
new spell_koralon_meteor_fists();
new spell_koralon_meteor_fists_damage();
new spell_flame_warder_meteor_fists();
}
| Ragebones/StormCore | src/server/scripts/Northrend/VaultOfArchavon/boss_koralon.cpp | C++ | gpl-2.0 | 9,922 |
<?php
/**
* @version SEBLOD 3.x Core ~ $Id: version.php sebastienheraud $
* @package SEBLOD (App Builder & CCK) // SEBLOD nano (Form Builder)
* @url http://www.seblod.com
* @editor Octopoos - www.octopoos.com
* @copyright Copyright (C) 2009 - 2016 SEBLOD. All Rights Reserved.
* @license GNU General Public License version 2 or later; see _LICENSE.php
**/
defined( '_JEXEC' ) or die;
require_once JPATH_COMPONENT.'/helpers/helper_version.php';
// Model
class CCKModelVersion extends JCckBaseLegacyModelAdmin
{
protected $text_prefix = 'COM_CCK';
protected $vName = 'version';
// populateState
protected function populateState()
{
$app = JFactory::getApplication( 'administrator' );
$pk = $app->input->getInt( 'id', 0 );
$this->setState( 'version.id', $pk );
}
// getForm
public function getForm( $data = array(), $loadData = true )
{
$form = $this->loadForm( CCK_COM.'.'.$this->vName, $this->vName, array( 'control' => 'jform', 'load_data' => $loadData ) );
if ( empty( $form ) ) {
return false;
}
return $form;
}
// getItem
public function getItem( $pk = null )
{
if ( $item = parent::getItem( $pk ) ) {
//
}
return $item;
}
// getTable
public function getTable( $type = 'Version', $prefix = CCK_TABLE, $config = array() )
{
return JTable::getInstance( $type, $prefix, $config );
}
// loadFormData
protected function loadFormData()
{
// Check the session for previously entered form data.
$data = JFactory::getApplication()->getUserState( CCK_COM.'.edit.'.$this->vName.'.data', array() );
if ( empty( $data ) ) {
$data = $this->getItem();
}
return $data;
}
// -------- -------- -------- -------- -------- -------- -------- -------- // Store
// prepareData
protected function prepareData()
{
$data = JRequest::get( 'post' );
return $data;
}
// revert
public function revert( $pk, $type )
{
$db = $this->getDbo();
$table = $this->getTable();
if ( !$pk || !$type ) {
return false;
}
$table->load( $pk );
if ( JCck::getConfig_Param( 'version_revert', 1 ) == 1 ) {
Helper_Version::createVersion( $type, $table->e_id, JText::sprintf( 'COM_CCK_VERSION_AUTO_BEFORE_REVERT', $table->e_version ) );
}
$row = JTable::getInstance( $type, 'CCK_Table' );
$row->load( $table->e_id );
$core = JCckDev::fromJSON( $table->e_core );
if ( isset( $row->asset_id ) && $row->asset_id && isset( $core['rules'] ) ) {
JCckDatabase::execute( 'UPDATE #__assets SET rules = "'.$db->escape( $core['rules'] ).'" WHERE id = '.(int)$row->asset_id );
}
// More
if ( $type == 'search' ) {
$clients = array( 1=>'search', 2=>'filter', 3=>'list', 4=>'item', 5=>'order' );
} else {
$clients = array( 1=>'admin', 2=>'site', 3=>'intro', 4=>'content' );
}
foreach ( $clients as $i=>$client ) {
$name = 'e_more'.$i;
$this->_revert_more( $type, $client, $table->e_id, $table->{$name} );
}
// Override
if ( $row->version && ( $row->version != $table->e_version ) ) {
$core['version'] = ++$row->version;
}
$core['checked_out'] = 0;
$core['checked_out_time'] = '0000-00-00 00:00:00';
$row->bind( $core );
$row->check();
$row->store();
return true;
}
// _revert_more
public function _revert_more( $type, $client, $pk, $json )
{
$data = json_decode( $json );
$table = JCckTableBatch::getInstance( '#__cck_core_'.$type.'_field' );
$table->delete( $type.'id = '.$pk.' AND client = "'.$client.'"' );
$table->save( $data->fields, array(), array(), array( 'markup'=>'', 'restriction'=>'', 'restriction_options'=>'' ) );
$table = JCckTableBatch::getInstance( '#__cck_core_'.$type.'_position' );
$table->delete( $type.'id = '.$pk.' AND client = "'.$client.'"' );
$table->save( $data->positions );
}
}
?> | klas/SEBLOD | administrator/components/com_cck/models/version.php | PHP | gpl-2.0 | 3,951 |
<!DOCTYPE html>
<!--[if IE 7]>
<html class="ie ie7" lang="en-US" prefix="og: http://ogp.me/ns#">
<![endif]-->
<!--[if IE 8]>
<html class="ie ie8" lang="en-US" prefix="og: http://ogp.me/ns#">
<![endif]-->
<!--[if !(IE 7) | !(IE 8) ]><!-->
<html lang="en-US" prefix="og: http://ogp.me/ns#">
<!--<![endif]-->
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<title>Page Not Found | Team California Baseball</title>
<link rel="profile" href="http://gmpg.org/xfn/11">
<link rel="pingback" href="http://teamcalbaseball.com/xmlrpc.php">
<!--[if lt IE 9]>
<script src="http://teamcalbaseball.com/wp-content/themes/teamcalbaseball/js/html5.js"></script>
<![endif]-->
<!-- This site is optimized with the Yoast WordPress SEO plugin v1.4.24 - http://yoast.com/wordpress/seo/ -->
<meta property="og:locale" content="en_US" />
<meta property="og:type" content="website" />
<meta property="og:title" content="Page Not Found - Team California Baseball" />
<meta property="og:site_name" content="Team California Baseball" />
<!-- / Yoast WordPress SEO plugin. -->
<link rel="alternate" type="application/rss+xml" title="Team California Baseball » Feed" href="http://teamcalbaseball.com/feed/" />
<link rel="alternate" type="application/rss+xml" title="Team California Baseball » Comments Feed" href="http://teamcalbaseball.com/comments/feed/" />
<link rel='stylesheet' id='contact-form-7-css' href='http://teamcalbaseball.com/wp-content/plugins/contact-form-7/includes/css/styles.css?ver=3.7' type='text/css' media='all' />
<link rel='stylesheet' id='symple_shortcode_styles-css' href='http://teamcalbaseball.com/wp-content/plugins/symple-shortcodes/includes/css/symple_shortcodes_styles.css?ver=3.8.1' type='text/css' media='all' />
<link rel='stylesheet' id='twentyfourteen-lato-css' href='//fonts.googleapis.com/css?family=Lato%3A300%2C400%2C700%2C900%2C300italic%2C400italic%2C700italic' type='text/css' media='all' />
<link rel='stylesheet' id='genericons-css' href='http://teamcalbaseball.com/wp-content/themes/teamcalbaseball/genericons/genericons.css?ver=3.0.2' type='text/css' media='all' />
<link rel='stylesheet' id='twentyfourteen-style-css' href='http://teamcalbaseball.com/wp-content/themes/teamcalbaseball/style.css?ver=3.8.1' type='text/css' media='all' />
<!--[if lt IE 9]>
<link rel='stylesheet' id='twentyfourteen-ie-css' href='http://teamcalbaseball.com/wp-content/themes/teamcalbaseball/css/ie.css?ver=20131205' type='text/css' media='all' />
<![endif]-->
<script type='text/javascript' src='http://teamcalbaseball.com/wp-includes/js/jquery/jquery.js?ver=1.10.2'></script>
<script type='text/javascript' src='http://teamcalbaseball.com/wp-includes/js/jquery/jquery-migrate.min.js?ver=1.2.1'></script>
<link rel="EditURI" type="application/rsd+xml" title="RSD" href="http://teamcalbaseball.com/xmlrpc.php?rsd" />
<link rel="wlwmanifest" type="application/wlwmanifest+xml" href="http://teamcalbaseball.com/wp-includes/wlwmanifest.xml" />
<meta name="generator" content="WordPress 3.8.1" />
<style>span>iframe{
max-width:none !important;
}
</style>
<link rel="stylesheet" href="http://teamcalbaseball.com/wp-content/themes/teamcalbaseball/styles/fonts.css" type="text/css">
<link rel="stylesheet" href="http://teamcalbaseball.com/wp-content/themes/teamcalbaseball/styles/jquery.bxslider.css" type="text/css">
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css">
<link rel="stylesheet/less" href="http://teamcalbaseball.com/wp-content/themes/teamcalbaseball/less/tcb.less" type="text/css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.0/js/bootstrap.min.js"></script>
<script src="http://cdn.kendostatic.com/2013.3.1119/js/kendo.web.min.js"></script>
<script src="http://teamcalbaseball.com/wp-content/themes/teamcalbaseball/js/less-1.6.1.min.js"></script>
<script src="http://teamcalbaseball.com/wp-content/themes/teamcalbaseball/js/jquery.bxslider.min.js"></script>
<script src="http://teamcalbaseball.com/wp-content/themes/teamcalbaseball/js/jquery.marquee.min.js"></script>
<script>
$(document).ready(function() {
$('.marquee').marquee({
duration: 10000,
pauseOnHover: true,
});
$('.sponsors').bxSlider({
minSlides: 4,
slideWidth: 210,
});
});
</script>
</head>
<body class="error404 masthead-fixed full-width footer-widgets">
<div class="container">
<header>
<div class="pageTitle">
<h1>Team California Baseball</h1>
</div>
<div id="headerImage"><img src="/wp-content/themes/teamcalbaseball/images/headerImage2.png"></div>
<div class="twitterLink"><a href="https://twitter.com/teamcalbaseball" target="_blank"><img src="/wp-content/themes/teamcalbaseball/images/twitterLink.png"></a></div>
</header>
<section id="ticker">
<div class="row">
<div class="col-lg-12">
<div class="marquee">
<div class="playerScroll">
<a href="http://www.cuieagles.com/sport/0/1.php" target="_blank"><p>MIKE MARTINEZ</p>
<p>2014 - EASTLAKE HS</p>
<p>PITCHER/1ST BASE</p>
<p>CONCORDIA UNIVERSITY</p>
</a>
</div>
<div class="playerScroll">
<a href="http://www.nevadawolfpack.com/sports/m-basebl/unv-m-basebl-body.html" target="_blank"><p>JORDAN PEARCE</p>
<p>2014 - EL CAMINO HS</p>
<p>3RD BASE</p>
<p>UNIVERSITY OF NEVADA RENO</p>
</a>
</div>
<div class="playerScroll">
<a href="http://www.baylorbears.com/sports/m-basebl/" target="_blank"><p>HUDSON PEARSON</p>
<p>2014 - EASTLAKE HS</p>
<p>PITCHER</p>
<p>BAYLOR UNIVERSITY</p>
</a>
</div>
<div class="playerScroll">
<a href="http://www.usfdons.com/index.aspx?path=baseball" target="_blank"><p>AARON PING</p>
<p>2014 - PATRICK HENRY HS</p>
<p>INFIELD</p>
<p>UNIVERSITY OF SAN FRANCISCO</p>
</a>
</div>
<div class="playerScroll">
<a href="http://www.oit.edu/athletics/mens-sports/baseball" target="_blank"><p>JOHN SCHULZ</p>
<p>2014 - CALVARY CHRISTIAN HS</p>
<p>PITCHER</p>
<p>OREGON INSTITUTE OF TECHNOLOGY</p>
</a>
</div>
<div class="playerScroll">
<a href="http://www.gomatadors.com/sports/m-basebl/index" target="_blank"><p>DREW WESTON</p>
<p>2014 - SAN MARCOS HS</p>
<p>PITCHER</p>
<p>CAL STATE NORTHRIDGE</p>
</div>
<div class="playerScroll">
<a href="http://goaztecs.cstv.com/sports/m-basebl/sdsu-m-basebl-body.html" target="_blank"><p>MATT WEZNIAK</p>
<p>2014 CARLSBAD HS</p>
<p>INFIELD</p>
<p>SAN DIEGO STATE UNIVERSITY</p>
</a>
</div> <div class="playerScroll">
<a href="http://www.hokiesports.com/baseball/players/anderson_nick.html" target="_blank"><p>NICK ANDERSON</p>
<p>2013 - CARLSBAD HS</p>
<p>OUTFIELD</p>
<p>VIRGINIA TECH</p>
</a>
</div>
<div class="playerScroll">
<a href="http://www.milb.com/milb/stats/stats.jsp?sid=milb&t=p_pbp&pid=641334" target="_blank"><p>MATT BALL</p>
<p>2013 - BONITA VISTA HS</p>
<p>PITCHER - LONG BEACH STATE</p>
<p>DRAFTED 10TH RD CHICAGO WHITE SOX (SIGNED)</p>
</a>
</div>
<div class="playerScroll">
<a href="http://goaztecs.cstv.com/sports/m-basebl/mtt/andrew_brown_865856.html" target="_blank"><p>ANDY BROWN</p>
<p>2013 - THE ROCK ACADEMY HS</p>
<p>SHORTSTOP</p>
<p>SAN DIEGO STATE UNIVERSITY</p></a>
</div>
<div class="playerScroll">
<a href="http://www.csusmcougars.com/roster.aspx?rp_id=2240" target="_blank"><p>NOAH BUCHANAN</p>
<p>2013 - GROSSMONT HS</p>
<p>OUTFIELD</p>
<p>CAL STATE SAN MARCOS</p>
</a>
</div>
<div class="playerScroll">
<a href="http://usdtoreros.cstv.com/sports/m-basebl/mtt/cj_burdick_881275.html" target="_blank"><p>CJ BURDICK</p>
<p>2013 - SERRA HS</p>
<p>PITCHER</p>
<p>UNIVERSITY OF SAN DIEGO</p>
</a>
</div>
<div class="playerScroll">
<a href="http://rccathletics.com/sports/bsb/2013-14/bios/devries_josh_gh7b" target="_blank"><p>JOSH DEVRIES</p>
<p>2013 - CAPISTRANO VALLEY HS</p>
<p>PITCHER</p>
<p>RIVERSIDE COMMUNITY COLLEGE</p></a>
</div>
<div class="playerScroll">
<a href="http://www.gostanford.com/ViewArticle.dbml?ATCLID=209370499&DB_OEM_ID=30600" target="_blank"><p>TOMMY EDMAN</p>
<p>2013 - LJCDS</p>
<p>SHORTSTOP</p>
<p>STANFORD UNIVERSITY</p>
</a>
</div>
<div class="playerScroll">
<a href="http://www.sgucavaliers.com/roster/11/3/1481.php" target="_blank"><p>DAVID FLORES</p>
<p>2013 - CALVARY CHRISTIAN HS</p>
<p>PITCHER</p>
<p>ST. GREGORY'S UNIVERSITY</p>
</a>
</div>
<div class="playerScroll">
<a href="http://www.plnusealions.com/roster.aspx?rp_id=1721&path=baseball" target="_blank"><p>RYAN GARCIA</p>
<p>2013 - EL CAMINO HS</p>
<p>1ST BASE</p>
<p>POINT LOMA NAZARENE UNIVERSITY</p>
</a>
</a>
</div>
<div class="playerScroll">
<a href="http://www.ucirvinesports.com/sports/m-basebl/2013-14/bios/guenette_alex_8xac" target="_blank"><p>ALEX GUENETTE</p>
<p>2013 - LJCDS</p>
<p>CATCHER</p>
<p>UC IRVINE</p>
</a>
</div>
<div class="playerScroll">
<a href="http://utahutes.cstv.com/sports/m-basebl/mtt/dustin_hughes_863278.html" target="_blank"><p>DUSTIN HUGHES</p>
<p>2013 - LJCDS</p>
<p>PITCHER</p>
<p>UNIVERSITY OF UTAH</p>
</a>
</div>
<div class="playerScroll">
<a href="http://www.plnusealions.com/roster.aspx?rp_id=1723" target="_blank"><p>MATT JERVIS</p>
<p>2013 - RANCHO BERNARDO HS</p>
<p>SHORTSTOP</p>
<p>POINT LOMA NAZARENE UNIVERSITY</p>
</a>
</div>
<div class="playerScroll">
<a href="https://www.gopoly.com/sports/bsb/2013-14/bios/lee_slater_sppl" target="_blank"><p>SLATER LEE</p>
<p>2013 - CARLSBAD HS</p>
<p>PITCHER</p>
<p>CAL POLY SAN LUIS OBISPO</p>
</a>
</div>
<div class="playerScroll">
<a href="http://www.cmsathletics.org/sports/bsb/2013-14/bios/l-esperance_james_b8gw" target="_blank"><p>JAMES L'ESPERANCE</p>
<p>2013 - EASTLAKE HS</p>
<p>OUTFIELD</p>
<p>CLAREMONT COLLEGE</p>
</a>
</div>
<div class="playerScroll">
<a href="http://www.centralaz.edu/home/athletics/teams/baseball.htm" target="_blank"><p>DEANDRE SIMPSON</p>
<p>2013 - THE ROCK ACADEMY HS</p>
<p>PITCHER</p>
<p>CENTRAL ARIZONA COMMUNITY COLLEGE</p>
</a>
</div>
<div class="playerScroll">
<a href="http://gocugo.com/roster.aspx?path=baseball&rp_id=1637" target="_blank"><p>ADAM TAYLOR</p>
<p>2013 - THE ROCK ACADEMY HS</p>
<p>UTILITY</p>
<p>CONCORDIA UNIVERSITY</p>
</a>
</div>
<div class="playerScroll">
<a href="https://www.masters.edu/athletics/menssports/baseball/roster.aspx" target="_blank"><p>CALEB WHITLEY</p>
<p>2013 - CALVARY CHRISTIAN HS</p>
<p>CATCHER</p>
<p>MASTERS COLLEGE</p>
</a>
</div>
<div class="playerScroll">
<a target="_blank" href="http://www.milb.com/milb/stats/stats.jsp?sid=milb&t=p_pbp&pid=622049"><p>SAM AYALA</p>
<p>2012 - LJCDS</p>
<p>CATCHER - UC SANTA BARBARA</p>
<p>DRAFTED 17TH RD CHICAGO WHITE SOX (SIGNED)</p></a>
</div>
<div class="playerScroll">
<a href="http://webapps.westmont.edu/cgi-bin/WebObjects/sportsData.woa/1/wo/DGQb83Mwxqlz2zv1jiywTw/0.1.2.1.18.24.2.0.0" target="_blank"><p>RUSSELL HARMENING</p>
<p>2012 - CALVARY CHRISTIAN HS</p>
<p>PITCHER</p>
<p>WESTMONT COLLEGE</p>
</a>
</div>
<div class="playerScroll">
<a href="https://www.masters.edu/athletics/menssports/baseball/roster.aspx" target="_blank"><p>COLLIN NYENHUIS</p>
<p>2012 - VISTA HS</p>
<p>3RD BASE</p>
<p>MASTERS COLLEGE</p>
</a>
</div>
<div class="playerScroll">
<a href="http://www.sdmesa.edu/students/athletics/sports/baseball/roster/" target="_blank"><p>KYLE HARRIS</p>
<p>2012 - CHRISTIAN HS</p>
<p>OUTFIELD</p>
<p>MESA COLLEGE</p>
</a>
</div>
</div>
<!-- <div class="popout">
<a class="button" href="#" onclick="javascript:void window.open('http://harrisonschaen.com/teamcalbaseball/ticker/','tickerWindow','width=990,height=110,toolbar=0,menubar=0,location=0,status=0,scrollbars=0,resizable=0,left=0,top=0');return false;">
Popout
</a>
</div>-->
</div>
</div>
</section>
<nav id="primary-navigation" class="site-navigation primary-navigation tcbNav" role="navigation">
<a class="screen-reader-text skip-link" href="#content">Skip to content</a>
<div class="menu-main-menu-container"><ul id="menu-main-menu" class="nav-menu tcbNav"><li id="menu-item-32" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-32"><a href="/">Home</a></li>
<li id="menu-item-252" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-has-children menu-item-252"><a href="#">About</a>
<ul class="sub-menu">
<li id="menu-item-205" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-205"><a href="http://teamcalbaseball.com/about/">Mission Statement</a></li>
<li id="menu-item-125" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-125"><a href="http://teamcalbaseball.com/about/staff/">Staff</a></li>
<li id="menu-item-101" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-101"><a href="http://teamcalbaseball.com/about/partners/">Partners</a></li>
<li id="menu-item-102" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-102"><a href="http://teamcalbaseball.com/about/resources/">Resources</a></li>
</ul>
</li>
<li id="menu-item-72" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-72"><a href="http://teamcalbaseball.com/alumni/">Alumni</a></li>
<li id="menu-item-74" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-has-children menu-item-74"><a href="http://teamcalbaseball.com/events/">Events</a>
<ul class="sub-menu">
<li id="menu-item-130" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-130"><a href="http://teamcalbaseball.com/events/tournaments/">Tournaments</a></li>
<li id="menu-item-129" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-129"><a href="http://teamcalbaseball.com/events/showcases/">Showcases</a></li>
<li id="menu-item-127" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-127"><a href="http://teamcalbaseball.com/events/college-team-camps/">College Team Camps</a></li>
<li id="menu-item-128" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-128"><a href="http://teamcalbaseball.com/events/perfect-game-so-cal-league/">Perfect Game Socal League</a></li>
</ul>
</li>
<li id="menu-item-132" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-has-children menu-item-132"><a href="http://teamcalbaseball.com/prospects/">Prospects</a>
<ul class="sub-menu">
<li id="menu-item-161" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-161"><a target="_blank" href="http://web1.ncaa.org/ECWR2/NCAA_EMS/NCAA_EMS.html#">Clearinghouse</a></li>
</ul>
</li>
<li id="menu-item-251" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-has-children menu-item-251"><a href="#">Teams</a>
<ul class="sub-menu">
<li id="menu-item-80" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-80"><a href="http://teamcalbaseball.com/teams/san-diego/">San Diego</a></li>
<li id="menu-item-79" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-79"><a href="http://teamcalbaseball.com/teams/orange-county/">Orange County</a></li>
<li id="menu-item-78" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-78"><a href="http://teamcalbaseball.com/teams/los-angeles/">Los Angeles</a></li>
<li id="menu-item-81" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-81"><a href="http://teamcalbaseball.com/teams/valley/">Valley</a></li>
</ul>
</li>
<li id="menu-item-131" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-131"><a href="http://teamcalbaseball.com/perfect-game-all-tournament-teams/">Perfect Game All-Tournament Teams</a></li>
<li id="menu-item-406" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-has-children menu-item-406"><a href="http://teamcalbaseball.com/schedule/">Schedule</a>
<ul class="sub-menu">
<li id="menu-item-408" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-408"><a href="http://teamcalbaseball.com/schedule/workout/">Workout</a></li>
<li id="menu-item-407" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-407"><a target="_blank" href="http://teamcalbaseball.com/schedule/game/">Game</a></li>
</ul>
</li>
<li id="menu-item-76" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-76"><a href="http://teamcalbaseball.com/team-store/">Team Store</a></li>
<li id="menu-item-73" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-73"><a href="http://teamcalbaseball.com/contact/">Contact</a></li>
</ul></div> </nav>
<article id="tcbPage">
<section>
<header class="page-header">
<h1 class="page-title">Not Found</h1>
</header>
<div class="page-content">
<p>It looks like nothing was found at this location. Maybe try a search?</p>
<form role="search" method="get" class="search-form" action="http://teamcalbaseball.com/">
<label>
<span class="screen-reader-text">Search for:</span>
<input type="search" class="search-field" placeholder="Search …" value="" name="s" title="Search for:" />
</label>
<input type="submit" class="search-submit" value="Search" />
</form> </div><!-- .page-content -->
</section><!-- #content -->
</article><!-- #primary -->
<footer id="colophon" class="site-footer container" role="contentinfo">
<div class="row">
<div class="col-lg-12">
<div class="foot pull-left"><img src="http://teamcalbaseball.com/wp-content/themes/teamcalbaseball/images/tcblogo.png"></div>
<div class="foot pull-left"><h2><a href="/teamcalbaseball/">Home</h2><h2><a href="/teamcalbaseball/about">About</a></h2><ul><li><a href="/teamcalbaseball/about/">Mission</a></li><li><a href="/teamcalbaseball/about/staff">Staff</a></li><li><a href="/teamcalbaseball/about/partners">Partners</a></li><li><a href="/teamcalbaseball/about/resources">Resources</a></li></ul><h2><a href="/teamcalbaseball/alumni">Alumni</a></h2></div>
<div class="foot pull-left"><h2><a href="/teamcalbaseball/events/">Events</a></h2><h2>Teams</h2><ul><li><a href="/teamcalbaseball/teams/san-diego/">San Diego</a></li><li><a href="/teamcalbaseball/teams/orange-county/">Orange County</a></li><li><a href="/teamcalbaseball/teams/los-angeles/">Los Angeles</a></li><li><a href="/teamcalbaseball/teams/valley/">Valley</a></li></ul></div>
<div class="foot pull-left"><h2><a href="/teamcalbaseball/contact/">Contact</a></h2><ul><li><p>Team California Baseball</p><p>PO Box 131406<p>(760) 994-9114</p><p>teamcalbaseball.com</p><p class="designedBy"><a href="http://www.harrisonschaen.com" alt="Designed and Developed by Harrison Schaen">Site by Harrison Schaen</a></p></div>
</div>
</div>
</footer><!-- #colophon -->
</div><!-- end Container-->
<script type='text/javascript' src='http://teamcalbaseball.com/wp-content/plugins/contact-form-7/includes/js/jquery.form.min.js?ver=3.48.0-2013.12.28'></script>
<script type='text/javascript'>
/* <![CDATA[ */
var _wpcf7 = {"loaderUrl":"http:\/\/teamcalbaseball.com\/wp-content\/plugins\/contact-form-7\/images\/ajax-loader.gif","sending":"Sending ...","cached":"1"};
/* ]]> */
</script>
<script type='text/javascript' src='http://teamcalbaseball.com/wp-content/plugins/contact-form-7/includes/js/scripts.js?ver=3.7'></script>
<script type='text/javascript' src='http://teamcalbaseball.com/wp-includes/js/jquery/jquery.masonry.min.js?ver=2.1.05'></script>
<script type='text/javascript' src='http://teamcalbaseball.com/wp-content/themes/teamcalbaseball/js/functions.js?ver=20131209'></script>
</body>
</html>
<!-- Dynamic page generated in 0.129 seconds. -->
<!-- Cached page generated by WP-Super-Cache on 2014-02-22 09:52:28 -->
<!-- Compression = gzip -->
<!-- super cache --> | hschaen/teamcalbaseball | wp-content/cache/supercache/teamcalbaseball.com/profile/brevenhonda/index.html | HTML | gpl-2.0 | 20,553 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.