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
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2011-2012 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2012 The OpenNMS Group, Inc. * * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. * * OpenNMS(R) 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. * * OpenNMS(R) 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 OpenNMS(R). If not, see: * http://www.gnu.org/licenses/ * * For more information contact: * OpenNMS(R) Licensing <[email protected]> * http://www.opennms.org/ * http://www.opennms.com/ *******************************************************************************/ package org.opennms.netmgt.icmp; import java.io.IOException; public class IcmpMessengerIOException extends IOException { private static final long serialVersionUID = 4658370128592224097L; public IcmpMessengerIOException(final String message) { super(message); } public IcmpMessengerIOException(final String message, final Throwable throwable) { super(message, throwable); } public IcmpMessengerIOException(final Throwable throwable) { super(throwable); } }
vishwaAbhinav/OpenNMS
opennms-icmp/opennms-icmp-api/src/main/java/org/opennms/netmgt/icmp/IcmpMessengerIOException.java
Java
gpl-2.0
1,708
/***************************************************************************** * video.c: transcoding stream output module (video) ***************************************************************************** * Copyright (C) 2003-2009 VLC authors and VideoLAN * $Id$ * * Authors: Laurent Aimar <[email protected]> * Gildas Bazin <[email protected]> * Jean-Paul Saman <jpsaman #_at_# m2x dot nl> * Antoine Cellerier <dionoea at videolan dot org> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser 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. *****************************************************************************/ /***************************************************************************** * Preamble *****************************************************************************/ #include "transcode.h" #include <math.h> #include <vlc_meta.h> #include <vlc_spu.h> #include <vlc_modules.h> #define ENC_FRAMERATE (25 * 1000) #define ENC_FRAMERATE_BASE 1000 struct decoder_owner_sys_t { sout_stream_sys_t *p_sys; }; static int video_update_format_decoder( decoder_t *p_dec ) { p_dec->fmt_out.video.i_chroma = p_dec->fmt_out.i_codec; return 0; } static picture_t *video_new_buffer_decoder( decoder_t *p_dec ) { return picture_NewFromFormat( &p_dec->fmt_out.video ); } static picture_t *video_new_buffer_encoder( encoder_t *p_enc ) { p_enc->fmt_in.video.i_chroma = p_enc->fmt_in.i_codec; return picture_NewFromFormat( &p_enc->fmt_in.video ); } static picture_t *transcode_video_filter_buffer_new( filter_t *p_filter ) { p_filter->fmt_out.video.i_chroma = p_filter->fmt_out.i_codec; return picture_NewFromFormat( &p_filter->fmt_out.video ); } static void* EncoderThread( void *obj ) { sout_stream_sys_t *p_sys = (sout_stream_sys_t*)obj; sout_stream_id_sys_t *id = p_sys->id_video; picture_t *p_pic = NULL; int canc = vlc_savecancel (); block_t *p_block = NULL; vlc_mutex_lock( &p_sys->lock_out ); for( ;; ) { while( !p_sys->b_abort && (p_pic = picture_fifo_Pop( p_sys->pp_pics )) == NULL ) vlc_cond_wait( &p_sys->cond, &p_sys->lock_out ); if( p_pic ) { /* release lock while encoding */ vlc_mutex_unlock( &p_sys->lock_out ); p_block = id->p_encoder->pf_encode_video( id->p_encoder, p_pic ); picture_Release( p_pic ); vlc_mutex_lock( &p_sys->lock_out ); block_ChainAppend( &p_sys->p_buffers, p_block ); } if( p_sys->b_abort ) break; } /*Encode what we have in the buffer on closing*/ while( (p_pic = picture_fifo_Pop( p_sys->pp_pics )) != NULL ) { p_block = id->p_encoder->pf_encode_video( id->p_encoder, p_pic ); picture_Release( p_pic ); block_ChainAppend( &p_sys->p_buffers, p_block ); } /*Now flush encoder*/ do { p_block = id->p_encoder->pf_encode_video(id->p_encoder, NULL ); block_ChainAppend( &p_sys->p_buffers, p_block ); } while( p_block ); vlc_mutex_unlock( &p_sys->lock_out ); vlc_restorecancel (canc); return NULL; } int transcode_video_new( sout_stream_t *p_stream, sout_stream_id_sys_t *id ) { sout_stream_sys_t *p_sys = p_stream->p_sys; /* Open decoder * Initialization of decoder structures */ id->p_decoder->fmt_out = id->p_decoder->fmt_in; id->p_decoder->fmt_out.i_extra = 0; id->p_decoder->fmt_out.p_extra = 0; id->p_decoder->pf_decode_video = NULL; id->p_decoder->pf_get_cc = NULL; id->p_decoder->pf_get_cc = 0; id->p_decoder->pf_vout_format_update = video_update_format_decoder; id->p_decoder->pf_vout_buffer_new = video_new_buffer_decoder; id->p_decoder->p_owner = malloc( sizeof(decoder_owner_sys_t) ); if( !id->p_decoder->p_owner ) return VLC_EGENERIC; id->p_decoder->p_owner->p_sys = p_sys; /* id->p_decoder->p_cfg = p_sys->p_video_cfg; */ id->p_decoder->p_module = module_need( id->p_decoder, "decoder", "$codec", false ); if( !id->p_decoder->p_module ) { msg_Err( p_stream, "cannot find video decoder" ); free( id->p_decoder->p_owner ); return VLC_EGENERIC; } /* * Open encoder. * Because some info about the decoded input will only be available * once the first frame is decoded, we actually only test the availability * of the encoder here. */ /* Initialization of encoder format structures */ es_format_Init( &id->p_encoder->fmt_in, id->p_decoder->fmt_in.i_cat, id->p_decoder->fmt_out.i_codec ); id->p_encoder->fmt_in.video.i_chroma = id->p_decoder->fmt_out.i_codec; /* The dimensions will be set properly later on. * Just put sensible values so we can test an encoder is available. */ id->p_encoder->fmt_in.video.i_width = id->p_encoder->fmt_out.video.i_width ? id->p_encoder->fmt_out.video.i_width : id->p_decoder->fmt_in.video.i_width ? id->p_decoder->fmt_in.video.i_width : 16; id->p_encoder->fmt_in.video.i_height = id->p_encoder->fmt_out.video.i_height ? id->p_encoder->fmt_out.video.i_height : id->p_decoder->fmt_in.video.i_height ? id->p_decoder->fmt_in.video.i_height : 16; id->p_encoder->fmt_in.video.i_visible_width = id->p_encoder->fmt_out.video.i_visible_width ? id->p_encoder->fmt_out.video.i_visible_width : id->p_decoder->fmt_in.video.i_visible_width ? id->p_decoder->fmt_in.video.i_visible_width : id->p_encoder->fmt_in.video.i_width; id->p_encoder->fmt_in.video.i_visible_height = id->p_encoder->fmt_out.video.i_visible_height ? id->p_encoder->fmt_out.video.i_visible_height : id->p_decoder->fmt_in.video.i_visible_height ? id->p_decoder->fmt_in.video.i_visible_height : id->p_encoder->fmt_in.video.i_height; id->p_encoder->i_threads = p_sys->i_threads; id->p_encoder->p_cfg = p_sys->p_video_cfg; id->p_encoder->p_module = module_need( id->p_encoder, "encoder", p_sys->psz_venc, true ); if( !id->p_encoder->p_module ) { msg_Err( p_stream, "cannot find video encoder (module:%s fourcc:%4.4s). Take a look few lines earlier to see possible reason.", p_sys->psz_venc ? p_sys->psz_venc : "any", (char *)&p_sys->i_vcodec ); module_unneed( id->p_decoder, id->p_decoder->p_module ); id->p_decoder->p_module = 0; free( id->p_decoder->p_owner ); return VLC_EGENERIC; } /* Close the encoder. * We'll open it only when we have the first frame. */ module_unneed( id->p_encoder, id->p_encoder->p_module ); if( id->p_encoder->fmt_out.p_extra ) { free( id->p_encoder->fmt_out.p_extra ); id->p_encoder->fmt_out.p_extra = NULL; id->p_encoder->fmt_out.i_extra = 0; } id->p_encoder->p_module = NULL; if( p_sys->i_threads <= 0 ) return VLC_SUCCESS; int i_priority = p_sys->b_high_priority ? VLC_THREAD_PRIORITY_OUTPUT : VLC_THREAD_PRIORITY_VIDEO; p_sys->id_video = id; p_sys->pp_pics = picture_fifo_New(); if( p_sys->pp_pics == NULL ) { msg_Err( p_stream, "cannot create picture fifo" ); module_unneed( id->p_decoder, id->p_decoder->p_module ); id->p_decoder->p_module = NULL; free( id->p_decoder->p_owner ); return VLC_ENOMEM; } vlc_mutex_init( &p_sys->lock_out ); vlc_cond_init( &p_sys->cond ); p_sys->p_buffers = NULL; p_sys->b_abort = false; if( vlc_clone( &p_sys->thread, EncoderThread, p_sys, i_priority ) ) { msg_Err( p_stream, "cannot spawn encoder thread" ); vlc_mutex_destroy( &p_sys->lock_out ); vlc_cond_destroy( &p_sys->cond ); picture_fifo_Delete( p_sys->pp_pics ); module_unneed( id->p_decoder, id->p_decoder->p_module ); id->p_decoder->p_module = NULL; free( id->p_decoder->p_owner ); return VLC_EGENERIC; } return VLC_SUCCESS; } static void transcode_video_filter_init( sout_stream_t *p_stream, sout_stream_id_sys_t *id ) { filter_owner_t owner = { .sys = p_stream->p_sys, .video = { .buffer_new = transcode_video_filter_buffer_new, }, }; es_format_t *p_fmt_out = &id->p_decoder->fmt_out; id->p_encoder->fmt_in.video.i_chroma = id->p_encoder->fmt_in.i_codec; id->p_f_chain = filter_chain_NewVideo( p_stream, false, &owner ); filter_chain_Reset( id->p_f_chain, p_fmt_out, p_fmt_out ); /* Deinterlace */ if( p_stream->p_sys->b_deinterlace ) { filter_chain_AppendFilter( id->p_f_chain, p_stream->p_sys->psz_deinterlace, p_stream->p_sys->p_deinterlace_cfg, &id->p_decoder->fmt_out, &id->p_decoder->fmt_out ); p_fmt_out = filter_chain_GetFmtOut( id->p_f_chain ); } if( p_stream->p_sys->b_master_sync ) { filter_chain_AppendFilter( id->p_f_chain, "fps", NULL, p_fmt_out, &id->p_encoder->fmt_in ); p_fmt_out = filter_chain_GetFmtOut( id->p_f_chain ); } /* Check that we have visible_width/height*/ if( !p_fmt_out->video.i_visible_height ) p_fmt_out->video.i_visible_height = p_fmt_out->video.i_height; if( !p_fmt_out->video.i_visible_width ) p_fmt_out->video.i_visible_width = p_fmt_out->video.i_width; if( p_stream->p_sys->psz_vf2 ) { id->p_uf_chain = filter_chain_NewVideo( p_stream, true, &owner ); filter_chain_Reset( id->p_uf_chain, p_fmt_out, &id->p_encoder->fmt_in ); if( p_fmt_out->video.i_chroma != id->p_encoder->fmt_in.video.i_chroma ) { filter_chain_AppendFilter( id->p_uf_chain, NULL, NULL, p_fmt_out, &id->p_encoder->fmt_in ); } filter_chain_AppendFromString( id->p_uf_chain, p_stream->p_sys->psz_vf2 ); p_fmt_out = filter_chain_GetFmtOut( id->p_uf_chain ); es_format_Copy( &id->p_encoder->fmt_in, p_fmt_out ); id->p_encoder->fmt_out.video.i_width = id->p_encoder->fmt_in.video.i_width; id->p_encoder->fmt_out.video.i_height = id->p_encoder->fmt_in.video.i_height; id->p_encoder->fmt_out.video.i_sar_num = id->p_encoder->fmt_in.video.i_sar_num; id->p_encoder->fmt_out.video.i_sar_den = id->p_encoder->fmt_in.video.i_sar_den; } } /* Take care of the scaling and chroma conversions. */ static void conversion_video_filter_append( sout_stream_id_sys_t *id ) { const es_format_t *p_fmt_out = &id->p_decoder->fmt_out; if( id->p_f_chain ) p_fmt_out = filter_chain_GetFmtOut( id->p_f_chain ); if( id->p_uf_chain ) p_fmt_out = filter_chain_GetFmtOut( id->p_uf_chain ); if( ( p_fmt_out->video.i_chroma != id->p_encoder->fmt_in.video.i_chroma ) || ( p_fmt_out->video.i_width != id->p_encoder->fmt_in.video.i_width ) || ( p_fmt_out->video.i_height != id->p_encoder->fmt_in.video.i_height ) ) { filter_chain_AppendFilter( id->p_uf_chain ? id->p_uf_chain : id->p_f_chain, NULL, NULL, p_fmt_out, &id->p_encoder->fmt_in ); } } static void transcode_video_encoder_init( sout_stream_t *p_stream, sout_stream_id_sys_t *id ) { sout_stream_sys_t *p_sys = p_stream->p_sys; const es_format_t *p_fmt_out = &id->p_decoder->fmt_out; if( id->p_f_chain ) { p_fmt_out = filter_chain_GetFmtOut( id->p_f_chain ); } if( id->p_uf_chain ) { p_fmt_out = filter_chain_GetFmtOut( id->p_uf_chain ); } /* Calculate scaling * width/height of source */ int i_src_visible_width = p_fmt_out->video.i_visible_width; int i_src_visible_height = p_fmt_out->video.i_visible_height; if (i_src_visible_width == 0) i_src_visible_width = p_fmt_out->video.i_width; if (i_src_visible_height == 0) i_src_visible_height = p_fmt_out->video.i_height; /* with/height scaling */ float f_scale_width = 1; float f_scale_height = 1; /* aspect ratio */ float f_aspect = (double)p_fmt_out->video.i_sar_num * p_fmt_out->video.i_width / p_fmt_out->video.i_sar_den / p_fmt_out->video.i_height; msg_Dbg( p_stream, "decoder aspect is %f:1", (double) f_aspect ); /* Change f_aspect from source frame to source pixel */ f_aspect = f_aspect * i_src_visible_height / i_src_visible_width; msg_Dbg( p_stream, "source pixel aspect is %f:1", (double) f_aspect ); /* Calculate scaling factor for specified parameters */ if( id->p_encoder->fmt_out.video.i_visible_width <= 0 && id->p_encoder->fmt_out.video.i_visible_height <= 0 && p_sys->f_scale ) { /* Global scaling. Make sure width will remain a factor of 16 */ float f_real_scale; int i_new_height; int i_new_width = i_src_visible_width * p_sys->f_scale; if( i_new_width % 16 <= 7 && i_new_width >= 16 ) i_new_width -= i_new_width % 16; else i_new_width += 16 - i_new_width % 16; f_real_scale = (float)( i_new_width ) / (float) i_src_visible_width; i_new_height = __MAX( 16, i_src_visible_height * (float)f_real_scale ); f_scale_width = f_real_scale; f_scale_height = (float) i_new_height / (float) i_src_visible_height; } else if( id->p_encoder->fmt_out.video.i_visible_width > 0 && id->p_encoder->fmt_out.video.i_visible_height <= 0 ) { /* Only width specified */ f_scale_width = (float)id->p_encoder->fmt_out.video.i_visible_width/i_src_visible_width; f_scale_height = f_scale_width; } else if( id->p_encoder->fmt_out.video.i_visible_width <= 0 && id->p_encoder->fmt_out.video.i_visible_height > 0 ) { /* Only height specified */ f_scale_height = (float)id->p_encoder->fmt_out.video.i_visible_height/i_src_visible_height; f_scale_width = f_scale_height; } else if( id->p_encoder->fmt_out.video.i_visible_width > 0 && id->p_encoder->fmt_out.video.i_visible_height > 0 ) { /* Width and height specified */ f_scale_width = (float)id->p_encoder->fmt_out.video.i_visible_width/i_src_visible_width; f_scale_height = (float)id->p_encoder->fmt_out.video.i_visible_height/i_src_visible_height; } /* check maxwidth and maxheight */ if( p_sys->i_maxwidth && f_scale_width > (float)p_sys->i_maxwidth / i_src_visible_width ) { f_scale_width = (float)p_sys->i_maxwidth / i_src_visible_width; } if( p_sys->i_maxheight && f_scale_height > (float)p_sys->i_maxheight / i_src_visible_height ) { f_scale_height = (float)p_sys->i_maxheight / i_src_visible_height; } /* Change aspect ratio from source pixel to scaled pixel */ f_aspect = f_aspect * f_scale_height / f_scale_width; msg_Dbg( p_stream, "scaled pixel aspect is %f:1", (double) f_aspect ); /* f_scale_width and f_scale_height are now final */ /* Calculate width, height from scaling * Make sure its multiple of 2 */ /* width/height of output stream */ int i_dst_visible_width = 2 * lroundf(f_scale_width*i_src_visible_width/2); int i_dst_visible_height = 2 * lroundf(f_scale_height*i_src_visible_height/2); int i_dst_width = 2 * lroundf(f_scale_width*p_fmt_out->video.i_width/2); int i_dst_height = 2 * lroundf(f_scale_height*p_fmt_out->video.i_height/2); /* Change aspect ratio from scaled pixel to output frame */ f_aspect = f_aspect * i_dst_visible_width / i_dst_visible_height; /* Store calculated values */ id->p_encoder->fmt_out.video.i_width = i_dst_width; id->p_encoder->fmt_out.video.i_visible_width = i_dst_visible_width; id->p_encoder->fmt_out.video.i_height = i_dst_height; id->p_encoder->fmt_out.video.i_visible_height = i_dst_visible_height; id->p_encoder->fmt_in.video.i_width = i_dst_width; id->p_encoder->fmt_in.video.i_visible_width = i_dst_visible_width; id->p_encoder->fmt_in.video.i_height = i_dst_height; id->p_encoder->fmt_in.video.i_visible_height = i_dst_visible_height; msg_Dbg( p_stream, "source %ix%i, destination %ix%i", i_src_visible_width, i_src_visible_height, i_dst_visible_width, i_dst_visible_height ); /* Handle frame rate conversion */ if( !id->p_encoder->fmt_out.video.i_frame_rate || !id->p_encoder->fmt_out.video.i_frame_rate_base ) { if( p_fmt_out->video.i_frame_rate && p_fmt_out->video.i_frame_rate_base ) { id->p_encoder->fmt_out.video.i_frame_rate = p_fmt_out->video.i_frame_rate; id->p_encoder->fmt_out.video.i_frame_rate_base = p_fmt_out->video.i_frame_rate_base; } else { /* Pick a sensible default value */ id->p_encoder->fmt_out.video.i_frame_rate = ENC_FRAMERATE; id->p_encoder->fmt_out.video.i_frame_rate_base = ENC_FRAMERATE_BASE; } } id->p_encoder->fmt_in.video.orientation = id->p_encoder->fmt_out.video.orientation = id->p_decoder->fmt_in.video.orientation; id->p_encoder->fmt_in.video.i_frame_rate = id->p_encoder->fmt_out.video.i_frame_rate; id->p_encoder->fmt_in.video.i_frame_rate_base = id->p_encoder->fmt_out.video.i_frame_rate_base; vlc_ureduce( &id->p_encoder->fmt_in.video.i_frame_rate, &id->p_encoder->fmt_in.video.i_frame_rate_base, id->p_encoder->fmt_in.video.i_frame_rate, id->p_encoder->fmt_in.video.i_frame_rate_base, 0 ); msg_Dbg( p_stream, "source fps %d/%d, destination %d/%d", id->p_decoder->fmt_out.video.i_frame_rate, id->p_decoder->fmt_out.video.i_frame_rate_base, id->p_encoder->fmt_in.video.i_frame_rate, id->p_encoder->fmt_in.video.i_frame_rate_base ); /* Check whether a particular aspect ratio was requested */ if( id->p_encoder->fmt_out.video.i_sar_num <= 0 || id->p_encoder->fmt_out.video.i_sar_den <= 0 ) { vlc_ureduce( &id->p_encoder->fmt_out.video.i_sar_num, &id->p_encoder->fmt_out.video.i_sar_den, (uint64_t)p_fmt_out->video.i_sar_num * i_src_visible_width * i_dst_visible_height, (uint64_t)p_fmt_out->video.i_sar_den * i_src_visible_height * i_dst_visible_width, 0 ); } else { vlc_ureduce( &id->p_encoder->fmt_out.video.i_sar_num, &id->p_encoder->fmt_out.video.i_sar_den, id->p_encoder->fmt_out.video.i_sar_num, id->p_encoder->fmt_out.video.i_sar_den, 0 ); } id->p_encoder->fmt_in.video.i_sar_num = id->p_encoder->fmt_out.video.i_sar_num; id->p_encoder->fmt_in.video.i_sar_den = id->p_encoder->fmt_out.video.i_sar_den; msg_Dbg( p_stream, "encoder aspect is %i:%i", id->p_encoder->fmt_out.video.i_sar_num * id->p_encoder->fmt_out.video.i_width, id->p_encoder->fmt_out.video.i_sar_den * id->p_encoder->fmt_out.video.i_height ); } static int transcode_video_encoder_open( sout_stream_t *p_stream, sout_stream_id_sys_t *id ) { sout_stream_sys_t *p_sys = p_stream->p_sys; msg_Dbg( p_stream, "destination (after video filters) %ix%i", id->p_encoder->fmt_in.video.i_width, id->p_encoder->fmt_in.video.i_height ); id->p_encoder->p_module = module_need( id->p_encoder, "encoder", p_sys->psz_venc, true ); if( !id->p_encoder->p_module ) { msg_Err( p_stream, "cannot find video encoder (module:%s fourcc:%4.4s)", p_sys->psz_venc ? p_sys->psz_venc : "any", (char *)&p_sys->i_vcodec ); return VLC_EGENERIC; } id->p_encoder->fmt_in.video.i_chroma = id->p_encoder->fmt_in.i_codec; /* */ id->p_encoder->fmt_out.i_codec = vlc_fourcc_GetCodec( VIDEO_ES, id->p_encoder->fmt_out.i_codec ); id->id = sout_StreamIdAdd( p_stream->p_next, &id->p_encoder->fmt_out ); if( !id->id ) { msg_Err( p_stream, "cannot add this stream" ); return VLC_EGENERIC; } return VLC_SUCCESS; } void transcode_video_close( sout_stream_t *p_stream, sout_stream_id_sys_t *id ) { if( p_stream->p_sys->i_threads >= 1 && !p_stream->p_sys->b_abort ) { vlc_mutex_lock( &p_stream->p_sys->lock_out ); p_stream->p_sys->b_abort = true; vlc_cond_signal( &p_stream->p_sys->cond ); vlc_mutex_unlock( &p_stream->p_sys->lock_out ); vlc_join( p_stream->p_sys->thread, NULL ); picture_fifo_Delete( p_stream->p_sys->pp_pics ); block_ChainRelease( p_stream->p_sys->p_buffers ); } vlc_mutex_destroy( &p_stream->p_sys->lock_out ); vlc_cond_destroy( &p_stream->p_sys->cond ); /* Close decoder */ if( id->p_decoder->p_module ) module_unneed( id->p_decoder, id->p_decoder->p_module ); if( id->p_decoder->p_description ) vlc_meta_Delete( id->p_decoder->p_description ); free( id->p_decoder->p_owner ); /* Close encoder */ if( id->p_encoder->p_module ) module_unneed( id->p_encoder, id->p_encoder->p_module ); /* Close filters */ if( id->p_f_chain ) filter_chain_Delete( id->p_f_chain ); if( id->p_uf_chain ) filter_chain_Delete( id->p_uf_chain ); } static void OutputFrame( sout_stream_t *p_stream, picture_t *p_pic, sout_stream_id_sys_t *id, block_t **out ) { sout_stream_sys_t *p_sys = p_stream->p_sys; picture_t *p_pic2 = NULL; /* * Encoding */ /* Check if we have a subpicture to overlay */ if( p_sys->p_spu ) { video_format_t fmt = id->p_encoder->fmt_in.video; if( fmt.i_visible_width <= 0 || fmt.i_visible_height <= 0 ) { fmt.i_visible_width = fmt.i_width; fmt.i_visible_height = fmt.i_height; fmt.i_x_offset = 0; fmt.i_y_offset = 0; } subpicture_t *p_subpic = spu_Render( p_sys->p_spu, NULL, &fmt, &id->p_decoder->fmt_out.video, p_pic->date, p_pic->date, false ); /* Overlay subpicture */ if( p_subpic ) { if( picture_IsReferenced( p_pic ) && !filter_chain_GetLength( id->p_f_chain ) ) { /* We can't modify the picture, we need to duplicate it, * in this point the picture is already p_encoder->fmt.in format*/ picture_t *p_tmp = video_new_buffer_encoder( id->p_encoder ); if( likely( p_tmp ) ) { picture_Copy( p_tmp, p_pic ); picture_Release( p_pic ); p_pic = p_tmp; } } if( unlikely( !p_sys->p_spu_blend ) ) p_sys->p_spu_blend = filter_NewBlend( VLC_OBJECT( p_sys->p_spu ), &fmt ); if( likely( p_sys->p_spu_blend ) ) picture_BlendSubpicture( p_pic, p_sys->p_spu_blend, p_subpic ); subpicture_Delete( p_subpic ); } } if( p_sys->i_threads == 0 ) { block_t *p_block; p_block = id->p_encoder->pf_encode_video( id->p_encoder, p_pic ); block_ChainAppend( out, p_block ); } if( p_sys->i_threads ) { vlc_mutex_lock( &p_sys->lock_out ); picture_fifo_Push( p_sys->pp_pics, p_pic ); vlc_cond_signal( &p_sys->cond ); vlc_mutex_unlock( &p_sys->lock_out ); } if( p_sys->i_threads && p_pic2 ) picture_Release( p_pic2 ); else if ( p_sys->i_threads == 0 ) picture_Release( p_pic ); } int transcode_video_process( sout_stream_t *p_stream, sout_stream_id_sys_t *id, block_t *in, block_t **out ) { sout_stream_sys_t *p_sys = p_stream->p_sys; picture_t *p_pic = NULL; *out = NULL; if( unlikely( in == NULL ) ) { if( p_sys->i_threads == 0 ) { block_t *p_block; do { p_block = id->p_encoder->pf_encode_video(id->p_encoder, NULL ); block_ChainAppend( out, p_block ); } while( p_block ); } else { msg_Dbg( p_stream, "Flushing thread and waiting that"); vlc_mutex_lock( &p_stream->p_sys->lock_out ); p_stream->p_sys->b_abort = true; vlc_cond_signal( &p_stream->p_sys->cond ); vlc_mutex_unlock( &p_stream->p_sys->lock_out ); vlc_join( p_stream->p_sys->thread, NULL ); vlc_mutex_lock( &p_sys->lock_out ); *out = p_sys->p_buffers; p_sys->p_buffers = NULL; vlc_mutex_unlock( &p_sys->lock_out ); msg_Dbg( p_stream, "Flushing done"); } return VLC_SUCCESS; } while( (p_pic = id->p_decoder->pf_decode_video( id->p_decoder, &in )) ) { if( unlikely ( id->p_encoder->p_module && !video_format_IsSimilar( &id->fmt_input_video, &id->p_decoder->fmt_out.video ) ) ) { msg_Info( p_stream, "aspect-ratio changed, reiniting. %i -> %i : %i -> %i.", id->fmt_input_video.i_sar_num, id->p_decoder->fmt_out.video.i_sar_num, id->fmt_input_video.i_sar_den, id->p_decoder->fmt_out.video.i_sar_den ); /* Close filters */ if( id->p_f_chain ) filter_chain_Delete( id->p_f_chain ); id->p_f_chain = NULL; if( id->p_uf_chain ) filter_chain_Delete( id->p_uf_chain ); id->p_uf_chain = NULL; /* Reinitialize filters */ id->p_encoder->fmt_out.video.i_visible_width = p_sys->i_width & ~1; id->p_encoder->fmt_out.video.i_visible_height = p_sys->i_height & ~1; id->p_encoder->fmt_out.video.i_sar_num = id->p_encoder->fmt_out.video.i_sar_den = 0; transcode_video_filter_init( p_stream, id ); transcode_video_encoder_init( p_stream, id ); conversion_video_filter_append( id ); memcpy( &id->fmt_input_video, &id->p_decoder->fmt_out.video, sizeof(video_format_t)); } if( unlikely( !id->p_encoder->p_module ) ) { if( id->p_f_chain ) filter_chain_Delete( id->p_f_chain ); if( id->p_uf_chain ) filter_chain_Delete( id->p_uf_chain ); id->p_f_chain = id->p_uf_chain = NULL; transcode_video_filter_init( p_stream, id ); transcode_video_encoder_init( p_stream, id ); conversion_video_filter_append( id ); memcpy( &id->fmt_input_video, &id->p_decoder->fmt_out.video, sizeof(video_format_t)); if( transcode_video_encoder_open( p_stream, id ) != VLC_SUCCESS ) { picture_Release( p_pic ); transcode_video_close( p_stream, id ); id->b_transcode = false; return VLC_EGENERIC; } } /* Run the filter and output chains; first with the picture, * and then with NULL as many times as we need until they * stop outputting frames. */ for ( ;; ) { picture_t *p_filtered_pic = p_pic; /* Run filter chain */ if( id->p_f_chain ) p_filtered_pic = filter_chain_VideoFilter( id->p_f_chain, p_filtered_pic ); if( !p_filtered_pic ) break; for ( ;; ) { picture_t *p_user_filtered_pic = p_filtered_pic; /* Run user specified filter chain */ if( id->p_uf_chain ) p_user_filtered_pic = filter_chain_VideoFilter( id->p_uf_chain, p_user_filtered_pic ); if( !p_user_filtered_pic ) break; OutputFrame( p_stream, p_user_filtered_pic, id, out ); p_filtered_pic = NULL; } p_pic = NULL; } } if( p_sys->i_threads >= 1 ) { /* Pick up any return data the encoder thread wants to output. */ vlc_mutex_lock( &p_sys->lock_out ); *out = p_sys->p_buffers; p_sys->p_buffers = NULL; vlc_mutex_unlock( &p_sys->lock_out ); } return VLC_SUCCESS; } bool transcode_video_add( sout_stream_t *p_stream, const es_format_t *p_fmt, sout_stream_id_sys_t *id ) { sout_stream_sys_t *p_sys = p_stream->p_sys; msg_Dbg( p_stream, "creating video transcoding from fcc=`%4.4s' to fcc=`%4.4s'", (char*)&p_fmt->i_codec, (char*)&p_sys->i_vcodec ); /* Complete destination format */ id->p_encoder->fmt_out.i_codec = p_sys->i_vcodec; id->p_encoder->fmt_out.video.i_visible_width = p_sys->i_width & ~1; id->p_encoder->fmt_out.video.i_visible_height = p_sys->i_height & ~1; id->p_encoder->fmt_out.i_bitrate = p_sys->i_vbitrate; /* Build decoder -> filter -> encoder chain */ if( transcode_video_new( p_stream, id ) ) { msg_Err( p_stream, "cannot create video chain" ); return false; } /* Stream will be added later on because we don't know * all the characteristics of the decoded stream yet */ id->b_transcode = true; if( p_sys->fps_num ) { id->p_encoder->fmt_in.video.i_frame_rate = id->p_encoder->fmt_out.video.i_frame_rate = (p_sys->fps_num ); id->p_encoder->fmt_in.video.i_frame_rate_base = id->p_encoder->fmt_out.video.i_frame_rate_base = (p_sys->fps_den ? p_sys->fps_den : 1); } return true; }
greeshmab/vlc
modules/stream_out/transcode/video.c
C
gpl-2.0
31,472
/* * Copyright (C) 2010-2013 The Paparazzi Team * * This file is part of paparazzi. * * paparazzi 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. * * paparazzi 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 paparazzi; see the file COPYING. If not, write to * the Free Software Foundation, 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ /** * @file subsystems/electrical.h * * Interface for electrical status: supply voltage, current, battery status, etc. */ #ifndef SUBSYSTEMS_ELECTRICAL_H #define SUBSYSTEMS_ELECTRICAL_H #include "std.h" #include "generated/airframe.h" /** low battery level in Volts (for 3S LiPo) */ #ifndef LOW_BAT_LEVEL #define LOW_BAT_LEVEL 10.5 #endif /** critical battery level in Volts (for 3S LiPo) */ #ifndef CRITIC_BAT_LEVEL #define CRITIC_BAT_LEVEL 9.8 #endif struct Electrical { float vsupply; ///< supply voltage in V float current; ///< current in A float charge; ///< consumed electric charge in Ah float energy; ///< consumed energy in Wh bool bat_low; ///< battery low status bool bat_critical; ///< battery critical status }; extern struct Electrical electrical; extern void electrical_init(void); extern void electrical_periodic(void); #endif /* SUBSYSTEMS_ELECTRICAL_H */
HWal/paparazzi
sw/airborne/subsystems/electrical.h
C
gpl-2.0
1,738
/* ==================================================================== * Copyright (c) 1993-2000 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The names "Sphinx" and "Carnegie Mellon" must not be used to * endorse or promote products derived from this software without * prior written permission. To obtain permission, contact * [email protected]. * * 4. Products derived from this software may not be called "Sphinx" * nor may "Sphinx" appear in their names without prior written * permission of Carnegie Mellon University. To obtain permission, * contact [email protected]. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by Carnegie * Mellon University (http://www.speech.cs.cmu.edu/)." * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED 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 CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES 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. * * ==================================================================== * */ /* * HISTORY * * 02-Aug-95 M K Ravishankar ([email protected]) at Carnegie Mellon University * Changed latnode_t.fef and latnode_t.lef to int32. */ #ifndef _SEARCH_H_ #define _SEARCH_H_ 1 /* * Back pointer table (forward pass lattice; actually a tree) */ typedef struct bptbl_s { FRAME_ID frame; /* start or end frame */ WORD_ID wid; /* Word index */ LAT_ID bp; /* Back Pointer */ int32 score; /* Score (best among all right contexts) */ int32 s_idx; /* Start of BScoreStack for various right contexts*/ WORD_ID real_fwid; /* fwid of this or latest predecessor real word */ WORD_ID prev_real_fwid; /* real word predecessor of real_fwid */ int32 r_diph; /* rightmost diphone of this word */ int32 ascr; int32 lscr; } BPTBL_T; #define NO_BP -1 /* #hyp entries */ #define HYP_SZ 1024 /* -------------- Lattice (DAG) search related -------------- */ /* * Links between DAG nodes (see latnode_t below). * Also used to keep scores in a bestpath search. */ typedef struct latlink_s { struct latnode_s *from; /* From node */ struct latnode_s *to; /* To node */ struct latlink_s *next; /* Next link from the same "from" node */ struct latlink_s *best_prev; struct latlink_s *q_next; int32 link_scr; /* Score for from->wid (from->sf to this->ef) */ int32 path_scr; /* Best path score from root of DAG */ int32 ef; /* end-frame for the "from" node */ } latlink_t; typedef struct rev_latlink_s { latlink_t *link; struct rev_latlink_s *next; } rev_latlink_t; /* * DAG nodes. */ typedef struct latnode_s { int32 wid; /* Dictionary word id */ int32 fef; /* First end frame */ int32 lef; /* Last end frame */ int16 sf; /* Start frame */ int16 reachable; /* From </s> or <s> */ union { int32 fanin; /* #nodes with links to this node */ int32 rem_score; /* Estimated best score from node.sf to end */ } info; latlink_t *links; /* Links out of this node */ rev_latlink_t *revlinks; /* Reverse links (for housekeeping purposes only) */ struct latnode_s *next; /* Next node (for housekeeping purposes only) */ } latnode_t; /* Interface */ void search_initialize (void); void search_set_beam_width (double beam); void search_set_new_word_beam_width (float beam); void search_set_lastphone_alone_beam_width (float beam); void search_set_new_phone_beam_width (float beam); void search_set_last_phone_beam_width (float beam); void search_set_channels_per_frame_target (int32 cpf); void searchSetScVqTopN (int32 topN); int32 searchFrame (void); int32 searchCurrentFrame (void); void search_set_newword_penalty (double nw_pen); void search_set_silence_word_penalty (float pen, float pip); void search_set_filler_word_penalty (float pen, float pip); void search_set_lw (double p1lw, double p2lw, double p3lw); void search_set_ip (float ip); void search_set_hyp_alternates (int32 arg); void search_set_skip_alt_frm (int32 flag); void search_set_hyp_total_score (int32 score); void search_set_context (int32 w1, int32 w2); void search_set_startword (char const *str); int32 search_result(int32 *fr, char **res); /* Decoded result as a single string */ int32 search_partial_result (int32 *fr, char **res); int32 search_get_score(void); int32 *search_get_dist_scores(void); search_hyp_t *search_get_hyp (void); char *search_get_wordlist (int *len, char sep_char); int32 search_get_bptable_size (void); int32 *search_get_lattice_density ( void ); double *search_get_phone_perplexity ( void ); int32 search_get_sil_penalty (void); int32 search_get_filler_penalty ( void ); BPTBL_T *search_get_bptable ( void ); void search_postprocess_bptable (double lwf, char const *pass); int32 *search_get_bscorestack ( void ); double search_get_lw ( void ); uint16 **search_get_uttpscr ( void ); int32 search_uttpscr2phlat_print ( void ); search_hyp_t *search_uttpscr2allphone ( void ); void search_remove_context (search_hyp_t *hyp); void search_hyp_to_str ( void ); void search_hyp_free (search_hyp_t *h); void sort_lattice(void); void search_dump_lattice (char const *file); void search_dump_lattice_ascii (char const *file); void dump_traceword_chan (void); void init_search_tree (dictT *dict); void create_search_tree (dictT *dict, int32 use_lm); void delete_search_tree (void); void delete_search_subtree (CHAN_T *hmm); void root_chan_v_eval (ROOT_CHAN_T *chan); void chan_v_eval (CHAN_T *chan); int32 eval_root_chan (void); int32 eval_nonroot_chan (void); int32 eval_word_chan (void); void save_bwd_ptr (WORD_ID w, int32 score, int32 path, int32 rc); void prune_root_chan (void); void prune_nonroot_chan (void); void last_phone_transition (void); void prune_word_chan (void); void alloc_all_rc (int32 w); void free_all_rc (int32 w); void word_transition (void); void search_set_current_lm (void); /* Need to call lm_set_current() first */ int32 seg_topsen_score (int32 sf, int32 ef); void compute_seg_scores (double lwf); void compute_sen_active (void); void evaluateChannels (void); void pruneChannels (void); void search_fwd (float *cep, float *dcep, float *dcep_80ms, float *pcep, float *ddcep); void search_start_fwd (void); void search_finish_fwd (void); void search_one_ply_fwd (void); void bestpath_search ( void ); void search_fwdflat_init ( void ); void search_fwdflat_finish ( void ); void build_fwdflat_chan ( void ); void destroy_fwdflat_chan ( void ); void search_set_fwdflat_bw (double bw, double nwbw); void search_fwdflat_start ( void ); void search_fwdflat_frame (float *cep, float *dcep, float *dcep_80ms, float *pcep, float *ddcep); void compute_fwdflat_senone_active ( void ); void fwdflat_eval_chan ( void ); void fwdflat_prune_chan ( void ); void fwdflat_word_transition ( void ); void destroy_frm_wordlist ( void ); void get_expand_wordlist (int32 frm, int32 win); int32 search_bptbl_wordlist (int32 wid, int32 frm); int32 search_bptbl_pred (int32 b); /* Warning: the following block of functions are not actually implemented. */ void search_finish_document (void); void searchBestN (void); void search_hyp_write (void); void parse_ref_str (void); void search_filtered_endpts (void); /* Functions from searchlat.c */ void searchlat_init ( void ); int32 bptbl2latdensity (int32 bptbl_sz, int32 *density); int32 lattice_rescore ( double lwf ); #endif
carlobar/uclinux_leon3_UD
user/mibench/office/sphinx/src/libsphinx2/include/search.h
C
gpl-2.0
8,589
/* Copyright (c) 2003-2007 MySQL AB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. 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 <ndb_global.h> #include "DbUtil.hpp" #include <ndb_version.h> #include <signaldata/WaitGCP.hpp> #include <signaldata/KeyInfo.hpp> #include <signaldata/AttrInfo.hpp> #include <signaldata/TcKeyConf.hpp> #include <signaldata/TcKeyFailConf.hpp> #include <signaldata/GetTabInfo.hpp> #include <signaldata/DictTabInfo.hpp> #include <signaldata/UtilSequence.hpp> #include <signaldata/UtilPrepare.hpp> #include <signaldata/UtilRelease.hpp> #include <signaldata/UtilExecute.hpp> #include <signaldata/UtilLock.hpp> #include <SectionReader.hpp> #include <Interpreter.hpp> #include <AttributeHeader.hpp> #include <NdbTick.h> /************************************************************************** * ------------------------------------------------------------------------ * MODULE: Startup * ------------------------------------------------------------------------ * * Constructors, startup, initializations **************************************************************************/ DbUtil::DbUtil(Block_context& ctx) : SimulatedBlock(DBUTIL, ctx), c_runningPrepares(c_preparePool), c_seizingTransactions(c_transactionPool), c_runningTransactions(c_transactionPool), c_lockQueues(c_lockQueuePool) { BLOCK_CONSTRUCTOR(DbUtil); // Add received signals addRecSignal(GSN_READ_CONFIG_REQ, &DbUtil::execREAD_CONFIG_REQ); addRecSignal(GSN_STTOR, &DbUtil::execSTTOR); addRecSignal(GSN_NDB_STTOR, &DbUtil::execNDB_STTOR); addRecSignal(GSN_DUMP_STATE_ORD, &DbUtil::execDUMP_STATE_ORD); addRecSignal(GSN_CONTINUEB, &DbUtil::execCONTINUEB); //addRecSignal(GSN_TCSEIZEREF, &DbUtil::execTCSEIZEREF); addRecSignal(GSN_TCSEIZECONF, &DbUtil::execTCSEIZECONF); addRecSignal(GSN_TCKEYCONF, &DbUtil::execTCKEYCONF); addRecSignal(GSN_TCKEYREF, &DbUtil::execTCKEYREF); addRecSignal(GSN_TCROLLBACKREP, &DbUtil::execTCROLLBACKREP); //addRecSignal(GSN_TCKEY_FAILCONF, &DbUtil::execTCKEY_FAILCONF); //addRecSignal(GSN_TCKEY_FAILREF, &DbUtil::execTCKEY_FAILREF); addRecSignal(GSN_TRANSID_AI, &DbUtil::execTRANSID_AI); /** * Sequence Service */ addRecSignal(GSN_UTIL_SEQUENCE_REQ, &DbUtil::execUTIL_SEQUENCE_REQ); // Debug addRecSignal(GSN_UTIL_SEQUENCE_REF, &DbUtil::execUTIL_SEQUENCE_REF); addRecSignal(GSN_UTIL_SEQUENCE_CONF, &DbUtil::execUTIL_SEQUENCE_CONF); /** * Locking */ addRecSignal(GSN_UTIL_CREATE_LOCK_REQ, &DbUtil::execUTIL_CREATE_LOCK_REQ); addRecSignal(GSN_UTIL_DESTROY_LOCK_REQ, &DbUtil::execUTIL_DESTORY_LOCK_REQ); addRecSignal(GSN_UTIL_LOCK_REQ, &DbUtil::execUTIL_LOCK_REQ); addRecSignal(GSN_UTIL_UNLOCK_REQ, &DbUtil::execUTIL_UNLOCK_REQ); /** * Backend towards Dict */ addRecSignal(GSN_GET_TABINFOREF, &DbUtil::execGET_TABINFOREF); addRecSignal(GSN_GET_TABINFO_CONF, &DbUtil::execGET_TABINFO_CONF); /** * Prepare / Execute / Release Services */ addRecSignal(GSN_UTIL_PREPARE_REQ, &DbUtil::execUTIL_PREPARE_REQ); addRecSignal(GSN_UTIL_PREPARE_CONF, &DbUtil::execUTIL_PREPARE_CONF); addRecSignal(GSN_UTIL_PREPARE_REF, &DbUtil::execUTIL_PREPARE_REF); addRecSignal(GSN_UTIL_EXECUTE_REQ, &DbUtil::execUTIL_EXECUTE_REQ); addRecSignal(GSN_UTIL_EXECUTE_CONF, &DbUtil::execUTIL_EXECUTE_CONF); addRecSignal(GSN_UTIL_EXECUTE_REF, &DbUtil::execUTIL_EXECUTE_REF); addRecSignal(GSN_UTIL_RELEASE_REQ, &DbUtil::execUTIL_RELEASE_REQ); addRecSignal(GSN_UTIL_RELEASE_CONF, &DbUtil::execUTIL_RELEASE_CONF); addRecSignal(GSN_UTIL_RELEASE_REF, &DbUtil::execUTIL_RELEASE_REF); } DbUtil::~DbUtil() { } BLOCK_FUNCTIONS(DbUtil) void DbUtil::releasePrepare(PreparePtr prepPtr) { prepPtr.p->preparePages.release(); c_runningPrepares.release(prepPtr); // Automatic release in pool } void DbUtil::releasePreparedOperation(PreparedOperationPtr prepOpPtr) { prepOpPtr.p->attrMapping.release(); prepOpPtr.p->attrInfo.release(); prepOpPtr.p->rsInfo.release(); prepOpPtr.p->pkBitmask.clear(); c_preparedOperationPool.release(prepOpPtr); // No list holding these structs } void DbUtil::releaseTransaction(TransactionPtr transPtr){ transPtr.p->executePages.release(); OperationPtr opPtr; for(transPtr.p->operations.first(opPtr); opPtr.i != RNIL; transPtr.p->operations.next(opPtr)){ opPtr.p->attrInfo.release(); opPtr.p->keyInfo.release(); opPtr.p->rs.release(); if (opPtr.p->prepOp != 0 && opPtr.p->prepOp_i != RNIL) { if (opPtr.p->prepOp->releaseFlag) { PreparedOperationPtr prepOpPtr; prepOpPtr.i = opPtr.p->prepOp_i; prepOpPtr.p = opPtr.p->prepOp; releasePreparedOperation(prepOpPtr); } } } transPtr.p->operations.release(); c_runningTransactions.release(transPtr); } void DbUtil::execREAD_CONFIG_REQ(Signal* signal) { jamEntry(); const ReadConfigReq * req = (ReadConfigReq*)signal->getDataPtr(); Uint32 ref = req->senderRef; Uint32 senderData = req->senderData; const ndb_mgm_configuration_iterator * p = m_ctx.m_config.getOwnConfigIterator(); ndbrequire(p != 0); c_pagePool.setSize(10); c_preparePool.setSize(1); // one parallel prepare at a time c_preparedOperationPool.setSize(5); // three hardcoded, two for test c_operationPool.setSize(64); // 64 parallel operations c_transactionPool.setSize(32); // 16 parallel transactions c_attrMappingPool.setSize(100); c_dataBufPool.setSize(6000); // 6000*11*4 = 264K > 8k+8k*16 = 256k { SLList<Prepare> tmp(c_preparePool); PreparePtr ptr; while(tmp.seize(ptr)) new (ptr.p) Prepare(c_pagePool); tmp.release(); } { SLList<Operation> tmp(c_operationPool); OperationPtr ptr; while(tmp.seize(ptr)) new (ptr.p) Operation(c_dataBufPool, c_dataBufPool, c_dataBufPool); tmp.release(); } { SLList<PreparedOperation> tmp(c_preparedOperationPool); PreparedOperationPtr ptr; while(tmp.seize(ptr)) new (ptr.p) PreparedOperation(c_attrMappingPool, c_dataBufPool, c_dataBufPool); tmp.release(); } { SLList<Transaction> tmp(c_transactionPool); TransactionPtr ptr; while(tmp.seize(ptr)) new (ptr.p) Transaction(c_pagePool, c_operationPool); tmp.release(); } c_lockQueuePool.setSize(5); c_lockElementPool.setSize(5); c_lockQueues.setSize(8); ReadConfigConf * conf = (ReadConfigConf*)signal->getDataPtrSend(); conf->senderRef = reference(); conf->senderData = senderData; sendSignal(ref, GSN_READ_CONFIG_CONF, signal, ReadConfigConf::SignalLength, JBB); } void DbUtil::execSTTOR(Signal* signal) { jamEntry(); const Uint32 startphase = signal->theData[1]; if(startphase == 1){ c_transId[0] = (number() << 20) + (getOwnNodeId() << 8); c_transId[1] = 0; } if(startphase == 6){ hardcodedPrepare(); connectTc(signal); } signal->theData[0] = 0; signal->theData[3] = 1; signal->theData[4] = 6; signal->theData[5] = 255; sendSignal(NDBCNTR_REF, GSN_STTORRY, signal, 6, JBB); return; } void DbUtil::execNDB_STTOR(Signal* signal) { (void)signal; // Don't want compiler warning jamEntry(); } /*************************** * Seize a number of TC records * to use for Util transactions */ void DbUtil::connectTc(Signal* signal){ TransactionPtr ptr; while(c_seizingTransactions.seize(ptr)){ signal->theData[0] = ptr.i << 1; // See TcCommitConf signal->theData[1] = reference(); sendSignal(DBTC_REF, GSN_TCSEIZEREQ, signal, 2, JBB); } } void DbUtil::execTCSEIZECONF(Signal* signal){ jamEntry(); TransactionPtr ptr; ptr.i = signal->theData[0] >> 1; c_seizingTransactions.getPtr(ptr, signal->theData[0] >> 1); ptr.p->connectPtr = signal->theData[1]; c_seizingTransactions.release(ptr); } /************************************************************************** * ------------------------------------------------------------------------ * MODULE: Misc * ------------------------------------------------------------------------ * * ContinueB, Dump **************************************************************************/ void DbUtil::execCONTINUEB(Signal* signal){ jamEntry(); const Uint32 Tdata0 = signal->theData[0]; switch(Tdata0){ default: ndbrequire(0); } } void DbUtil::execDUMP_STATE_ORD(Signal* signal){ jamEntry(); /**************************************************************************** * SEQUENCE SERVICE * * 200 : Simple test of Public Sequence Interface * ---------------------------------------------- * - Sends a SEQUENCE_REQ signal to Util (itself) */ const Uint32 tCase = signal->theData[0]; if(tCase == 200){ jam() ndbout << "--------------------------------------------------" << endl; UtilSequenceReq * req = (UtilSequenceReq*)signal->getDataPtrSend(); Uint32 seqId = 1; Uint32 reqTy = UtilSequenceReq::CurrVal; if(signal->length() > 1) seqId = signal->theData[1]; if(signal->length() > 2) reqTy = signal->theData[2]; req->senderData = 12; req->sequenceId = seqId; req->requestType = reqTy; sendSignal(DBUTIL_REF, GSN_UTIL_SEQUENCE_REQ, signal, UtilSequenceReq::SignalLength, JBB); } /****************************************************************************/ /* // Obsolete tests, should be rewritten for long signals!! if(tCase == 210){ jam(); ndbout << "--------------------------------------------------" << endl; const Uint32 pageSizeInWords = 128; Uint32 propPage[pageSizeInWords]; LinearWriter w(&propPage[0], 128); w.first(); w.add(UtilPrepareReq::NoOfOperations, 1); w.add(UtilPrepareReq::OperationType, UtilPrepareReq::Delete); w.add(UtilPrepareReq::TableName, "sys/def/SYSTAB_0"); w.add(UtilPrepareReq::AttributeName, "SYSKEY_0"); // AttrNo = 0 Uint32 length = w.getWordsUsed(); ndbassert(length <= pageSizeInWords); sendUtilPrepareReqSignals(signal, propPage, length); } if(tCase == 211){ jam(); ndbout << "--------------------------------------------------" << endl; const Uint32 pageSizeInWords = 128; Uint32 propPage[pageSizeInWords]; LinearWriter w(&propPage[0],128); w.first(); w.add(UtilPrepareReq::NoOfOperations, 1); w.add(UtilPrepareReq::OperationType, UtilPrepareReq::Insert); w.add(UtilPrepareReq::TableName, "sys/def/SYSTAB_0"); w.add(UtilPrepareReq::AttributeName, "SYSKEY_0"); // AttrNo = 0 w.add(UtilPrepareReq::AttributeName, "NEXTID"); // AttrNo = 1 Uint32 length = w.getWordsUsed(); ndbassert(length <= pageSizeInWords); sendUtilPrepareReqSignals(signal, propPage, length); } if(tCase == 212){ jam(); ndbout << "--------------------------------------------------" << endl; const Uint32 pageSizeInWords = 128; Uint32 propPage[pageSizeInWords]; LinearWriter w(&propPage[0],128); w.first(); w.add(UtilPrepareReq::NoOfOperations, 1); w.add(UtilPrepareReq::OperationType, UtilPrepareReq::Update); w.add(UtilPrepareReq::TableName, "sys/def/SYSTAB_0"); w.add(UtilPrepareReq::AttributeName, "SYSKEY_0"); // AttrNo = 0 w.add(UtilPrepareReq::AttributeName, "NEXTID"); // AttrNo = 1 Uint32 length = w.getWordsUsed(); ndbassert(length <= pageSizeInWords); sendUtilPrepareReqSignals(signal, propPage, length); } if(tCase == 213){ jam(); ndbout << "--------------------------------------------------" << endl; const Uint32 pageSizeInWords = 128; Uint32 propPage[pageSizeInWords]; LinearWriter w(&propPage[0],128); w.first(); w.add(UtilPrepareReq::NoOfOperations, 1); w.add(UtilPrepareReq::OperationType, UtilPrepareReq::Read); w.add(UtilPrepareReq::TableName, "sys/def/SYSTAB_0"); w.add(UtilPrepareReq::AttributeName, "SYSKEY_0"); // AttrNo = 0 Uint32 length = w.getWordsUsed(); ndbassert(length <= pageSizeInWords); sendUtilPrepareReqSignals(signal, propPage, length); } if(tCase == 214){ jam(); ndbout << "--------------------------------------------------" << endl; const Uint32 pageSizeInWords = 128; Uint32 propPage[pageSizeInWords]; LinearWriter w(&propPage[0], 128); w.first(); w.add(UtilPrepareReq::NoOfOperations, 1); w.add(UtilPrepareReq::OperationType, UtilPrepareReq::Delete); w.add(UtilPrepareReq::TableId, (unsigned int)0); // SYSTAB_0 w.add(UtilPrepareReq::AttributeId, (unsigned int)0);// SYSKEY_0 Uint32 length = w.getWordsUsed(); ndbassert(length <= pageSizeInWords); sendUtilPrepareReqSignals(signal, propPage, length); } if(tCase == 215){ jam(); ndbout << "--------------------------------------------------" << endl; const Uint32 pageSizeInWords = 128; Uint32 propPage[pageSizeInWords]; LinearWriter w(&propPage[0],128); w.first(); w.add(UtilPrepareReq::NoOfOperations, 1); w.add(UtilPrepareReq::OperationType, UtilPrepareReq::Insert); w.add(UtilPrepareReq::TableId, (unsigned int)0); // SYSTAB_0 w.add(UtilPrepareReq::AttributeId, (unsigned int)0); // SYSKEY_0 w.add(UtilPrepareReq::AttributeId, 1); // NEXTID Uint32 length = w.getWordsUsed(); ndbassert(length <= pageSizeInWords); sendUtilPrepareReqSignals(signal, propPage, length); } if(tCase == 216){ jam(); ndbout << "--------------------------------------------------" << endl; const Uint32 pageSizeInWords = 128; Uint32 propPage[pageSizeInWords]; LinearWriter w(&propPage[0],128); w.first(); w.add(UtilPrepareReq::NoOfOperations, 1); w.add(UtilPrepareReq::OperationType, UtilPrepareReq::Update); w.add(UtilPrepareReq::TableId, (unsigned int)0); // SYSTAB_0 w.add(UtilPrepareReq::AttributeId, (unsigned int)0);// SYSKEY_0 w.add(UtilPrepareReq::AttributeId, 1); // NEXTID Uint32 length = w.getWordsUsed(); ndbassert(length <= pageSizeInWords); sendUtilPrepareReqSignals(signal, propPage, length); } if(tCase == 217){ jam(); ndbout << "--------------------------------------------------" << endl; const Uint32 pageSizeInWords = 128; Uint32 propPage[pageSizeInWords]; LinearWriter w(&propPage[0],128); w.first(); w.add(UtilPrepareReq::NoOfOperations, 1); w.add(UtilPrepareReq::OperationType, UtilPrepareReq::Read); w.add(UtilPrepareReq::TableId, (unsigned int)0); // SYSTAB_0 w.add(UtilPrepareReq::AttributeId, (unsigned int)0);// SYSKEY_0 Uint32 length = w.getWordsUsed(); ndbassert(length <= pageSizeInWords); sendUtilPrepareReqSignals(signal, propPage, length); } */ /****************************************************************************/ /* // Obsolete tests, should be rewritten for long signals!! if(tCase == 220){ jam(); ndbout << "--------------------------------------------------" << endl; Uint32 prepI = signal->theData[1]; Uint32 length = signal->theData[2]; Uint32 attributeValue0 = signal->theData[3]; Uint32 attributeValue1a = signal->theData[4]; Uint32 attributeValue1b = signal->theData[5]; ndbrequire(prepI != 0); UtilExecuteReq * req = (UtilExecuteReq *)signal->getDataPtrSend(); req->senderData = 221; req->prepareId = prepI; req->totalDataLen = length; // Including headers req->offset = 0; AttributeHeader::init(&req->attrData[0], 0, 1); // AttrNo 0, DataSize req->attrData[1] = attributeValue0; // AttrValue AttributeHeader::init(&req->attrData[2], 1, 2); // AttrNo 1, DataSize req->attrData[3] = attributeValue1a; // AttrValue req->attrData[4] = attributeValue1b; // AttrValue printUTIL_EXECUTE_REQ(stdout, signal->getDataPtrSend(), 3 + 5,0); sendSignal(DBUTIL_REF, GSN_UTIL_EXECUTE_REQ, signal, 3 + 5, JBB); } */ /**************************************************************************** * 230 : PRINT STATE */ #ifdef ARRAY_GUARD if(tCase == 230){ jam(); ndbout << "--------------------------------------------------" << endl; if (signal->length() <= 1) { ndbout << "Usage: DUMP 230 <recordType> <recordNo>" << endl << "[1] Print Prepare (running) records" << endl << "[2] Print PreparedOperation records" << endl << "[3] Print Transaction records" << endl << "[4] Print Operation records" << endl << "Ex. \"dump 230 1 2\" prints Prepare record no 2." << endl << endl << "210 : PREPARE_REQ DELETE SYSTAB_0 SYSKEY_0" << endl << "211 : PREPARE_REQ INSERT SYSTAB_0 SYSKEY_0 NEXTID" << endl << "212 : PREPARE_REQ UPDATE SYSTAB_0 SYSKEY_0 NEXTID" << endl << "213 : PREPARE_REQ READ SYSTAB_0 SYSKEY_0" << endl << "214 : PREPARE_REQ DELETE SYSTAB_0 SYSKEY_0 using id" << endl << "215 : PREPARE_REQ INSERT SYSTAB_0 SYSKEY_0 NEXTID using id" << endl << "216 : PREPARE_REQ UPDATE SYSTAB_0 SYSKEY_0 NEXTID using id" << endl << "217 : PREPARE_REQ READ SYSTAB_0 SYSKEY_0 using id" << endl << "220 : EXECUTE_REQ <PrepId> <Len> <Val1> <Val2a> <Val2b>" <<endl << "299 : Crash system (using ndbrequire(0))" << endl << "Ex. \"dump 220 3 5 1 0 17 \" prints Prepare record no 2." << endl; return; } switch (signal->theData[1]) { case 1: // ** Print a specific record ** if (signal->length() >= 3) { PreparePtr prepPtr; if (!c_preparePool.isSeized(signal->theData[2])) { ndbout << "Prepare Id: " << signal->theData[2] << " (Not seized!)" << endl; } else { c_preparePool.getPtr(prepPtr, signal->theData[2]); prepPtr.p->print(); } return; } // ** Print all records ** PreparePtr prepPtr; if (!c_runningPrepares.first(prepPtr)) { ndbout << "No Prepare records exist" << endl; return; } while (!prepPtr.isNull()) { prepPtr.p->print(); c_runningPrepares.next(prepPtr); } return; case 2: // ** Print a specific record ** if (signal->length() >= 3) { if (!c_preparedOperationPool.isSeized(signal->theData[2])) { ndbout << "PreparedOperation Id: " << signal->theData[2] << " (Not seized!)" << endl; return; } ndbout << "PreparedOperation Id: " << signal->theData[2] << endl; PreparedOperationPtr prepOpPtr; c_preparedOperationPool.getPtr(prepOpPtr, signal->theData[2]); prepOpPtr.p->print(); return; } // ** Print all records ** #if 0 // not implemented PreparedOperationPtr prepOpPtr; if (!c_runningPreparedOperations.first(prepOpPtr)) { ndbout << "No PreparedOperations exist" << endl; return; } while (!prepOpPtr.isNull()) { ndbout << "[-PreparedOperation no " << prepOpPtr.i << ":"; prepOpPtr.p->print(); ndbout << "]"; c_runningPreparedOperations.next(prepOpPtr); } #endif return; case 3: // ** Print a specific record ** if (signal->length() >= 3) { ndbout << "Print specific record not implemented." << endl; return; } // ** Print all records ** ndbout << "Print all records not implemented, specify an Id." << endl; return; case 4: ndbout << "Not implemented" << endl; return; default: ndbout << "Unknown input (try without any data)" << endl; return; } } #endif if(tCase == 240 && signal->getLength() == 2){ MutexManager::ActiveMutexPtr ptr; ndbrequire(c_mutexMgr.seize(ptr)); ptr.p->m_mutexId = signal->theData[1]; Callback c = { safe_cast(&DbUtil::mutex_created), ptr.i }; ptr.p->m_callback = c; c_mutexMgr.create(signal, ptr); ndbout_c("c_mutexMgr.create ptrI=%d mutexId=%d", ptr.i, ptr.p->m_mutexId); } if(tCase == 241 && signal->getLength() == 2){ MutexManager::ActiveMutexPtr ptr; ndbrequire(c_mutexMgr.seize(ptr)); ptr.p->m_mutexId = signal->theData[1]; Callback c = { safe_cast(&DbUtil::mutex_locked), ptr.i }; ptr.p->m_callback = c; c_mutexMgr.lock(signal, ptr); ndbout_c("c_mutexMgr.lock ptrI=%d mutexId=%d", ptr.i, ptr.p->m_mutexId); } if(tCase == 242 && signal->getLength() == 2){ MutexManager::ActiveMutexPtr ptr; ptr.i = signal->theData[1]; c_mutexMgr.getPtr(ptr); Callback c = { safe_cast(&DbUtil::mutex_unlocked), ptr.i }; ptr.p->m_callback = c; c_mutexMgr.unlock(signal, ptr); ndbout_c("c_mutexMgr.unlock ptrI=%d mutexId=%d", ptr.i, ptr.p->m_mutexId); } if(tCase == 243 && signal->getLength() == 3){ MutexManager::ActiveMutexPtr ptr; ndbrequire(c_mutexMgr.seize(ptr)); ptr.p->m_mutexId = signal->theData[1]; ptr.p->m_mutexKey = signal->theData[2]; Callback c = { safe_cast(&DbUtil::mutex_destroyed), ptr.i }; ptr.p->m_callback = c; c_mutexMgr.destroy(signal, ptr); ndbout_c("c_mutexMgr.destroy ptrI=%d mutexId=%d key=%d", ptr.i, ptr.p->m_mutexId, ptr.p->m_mutexKey); } } void DbUtil::mutex_created(Signal* signal, Uint32 ptrI, Uint32 retVal){ MutexManager::ActiveMutexPtr ptr; ptr.i = ptrI; c_mutexMgr.getPtr(ptr); ndbout_c("mutex_created - mutexId=%d, retVal=%d", ptr.p->m_mutexId, retVal); c_mutexMgr.release(ptrI); } void DbUtil::mutex_destroyed(Signal* signal, Uint32 ptrI, Uint32 retVal){ MutexManager::ActiveMutexPtr ptr; ptr.i = ptrI; c_mutexMgr.getPtr(ptr); ndbout_c("mutex_destroyed - mutexId=%d, retVal=%d", ptr.p->m_mutexId, retVal); c_mutexMgr.release(ptrI); } void DbUtil::mutex_locked(Signal* signal, Uint32 ptrI, Uint32 retVal){ MutexManager::ActiveMutexPtr ptr; ptr.i = ptrI; c_mutexMgr.getPtr(ptr); ndbout_c("mutex_locked - mutexId=%d, retVal=%d key=%d ptrI=%d", ptr.p->m_mutexId, retVal, ptr.p->m_mutexKey, ptrI); if(retVal) c_mutexMgr.release(ptrI); } void DbUtil::mutex_unlocked(Signal* signal, Uint32 ptrI, Uint32 retVal){ MutexManager::ActiveMutexPtr ptr; ptr.i = ptrI; c_mutexMgr.getPtr(ptr); ndbout_c("mutex_unlocked - mutexId=%d, retVal=%d", ptr.p->m_mutexId, retVal); if(!retVal) c_mutexMgr.release(ptrI); } void DbUtil::execUTIL_SEQUENCE_REF(Signal* signal){ jamEntry(); ndbout << "UTIL_SEQUENCE_REF" << endl; printUTIL_SEQUENCE_REF(stdout, signal->getDataPtrSend(), signal->length(), 0); } void DbUtil::execUTIL_SEQUENCE_CONF(Signal* signal){ jamEntry(); ndbout << "UTIL_SEQUENCE_CONF" << endl; printUTIL_SEQUENCE_CONF(stdout, signal->getDataPtrSend(), signal->length(),0); } void DbUtil::execUTIL_PREPARE_CONF(Signal* signal){ jamEntry(); ndbout << "UTIL_PREPARE_CONF" << endl; printUTIL_PREPARE_CONF(stdout, signal->getDataPtrSend(), signal->length(), 0); } void DbUtil::execUTIL_PREPARE_REF(Signal* signal){ jamEntry(); ndbout << "UTIL_PREPARE_REF" << endl; printUTIL_PREPARE_REF(stdout, signal->getDataPtrSend(), signal->length(), 0); } void DbUtil::execUTIL_EXECUTE_CONF(Signal* signal) { jamEntry(); ndbout << "UTIL_EXECUTE_CONF" << endl; printUTIL_EXECUTE_CONF(stdout, signal->getDataPtrSend(), signal->length(), 0); } void DbUtil::execUTIL_EXECUTE_REF(Signal* signal) { jamEntry(); ndbout << "UTIL_EXECUTE_REF" << endl; printUTIL_EXECUTE_REF(stdout, signal->getDataPtrSend(), signal->length(), 0); } void DbUtil::execUTIL_RELEASE_CONF(Signal* signal) { jamEntry(); ndbout << "UTIL_RELEASE_CONF" << endl; } void DbUtil::execUTIL_RELEASE_REF(Signal* signal) { jamEntry(); ndbout << "UTIL_RELEASE_REF" << endl; } void DbUtil::sendUtilPrepareRef(Signal* signal, UtilPrepareRef::ErrorCode error, Uint32 recipient, Uint32 senderData){ UtilPrepareRef * ref = (UtilPrepareRef *)signal->getDataPtrSend(); ref->errorCode = error; ref->senderData = senderData; sendSignal(recipient, GSN_UTIL_PREPARE_REF, signal, UtilPrepareRef::SignalLength, JBB); } void DbUtil::sendUtilExecuteRef(Signal* signal, UtilExecuteRef::ErrorCode error, Uint32 TCerror, Uint32 recipient, Uint32 senderData){ UtilExecuteRef * ref = (UtilExecuteRef *)signal->getDataPtrSend(); ref->senderData = senderData; ref->errorCode = error; ref->TCErrorCode = TCerror; sendSignal(recipient, GSN_UTIL_EXECUTE_REF, signal, UtilPrepareRef::SignalLength, JBB); } /************************************************************************** * ------------------------------------------------------------------------ * MODULE: Prepare service * ------------------------------------------------------------------------ * * Prepares a transaction by storing info in some structs **************************************************************************/ void DbUtil::execUTIL_PREPARE_REQ(Signal* signal) { jamEntry(); /**************** * Decode Signal ****************/ UtilPrepareReq * req = (UtilPrepareReq *)signal->getDataPtr(); const Uint32 senderRef = req->senderRef; const Uint32 senderData = req->senderData; if(signal->getNoOfSections() == 0) { // Missing prepare data jam(); releaseSections(signal); sendUtilPrepareRef(signal, UtilPrepareRef::MISSING_PROPERTIES_SECTION, senderRef, senderData); return; } PreparePtr prepPtr; SegmentedSectionPtr ptr; jam(); if(!c_runningPrepares.seize(prepPtr)) { jam(); releaseSections(signal); sendUtilPrepareRef(signal, UtilPrepareRef::PREPARE_SEIZE_ERROR, senderRef, senderData); return; }; signal->getSection(ptr, UtilPrepareReq::PROPERTIES_SECTION); const Uint32 noPages = (ptr.sz + sizeof(Page32)) / sizeof(Page32); ndbassert(noPages > 0); if (!prepPtr.p->preparePages.seize(noPages)) { jam(); releaseSections(signal); sendUtilPrepareRef(signal, UtilPrepareRef::PREPARE_PAGES_SEIZE_ERROR, senderRef, senderData); c_preparePool.release(prepPtr); return; } // Save SimpleProperties Uint32* target = &prepPtr.p->preparePages.getPtr(0)->data[0]; copy(target, ptr); prepPtr.p->prepDataLen = ptr.sz; // Release long signal sections releaseSections(signal); // Check table properties with DICT SimplePropertiesSectionReader reader(ptr, getSectionSegmentPool()); prepPtr.p->clientRef = senderRef; prepPtr.p->clientData = senderData; // Release long signal sections releaseSections(signal); readPrepareProps(signal, &reader, prepPtr.i); } void DbUtil::readPrepareProps(Signal* signal, SimpleProperties::Reader* reader, Uint32 senderData) { jam(); #if 0 printf("DbUtil::readPrepareProps: Received SimpleProperties:\n"); reader->printAll(ndbout); #endif ndbrequire(reader->first()); ndbrequire(reader->getKey() == UtilPrepareReq::NoOfOperations); ndbrequire(reader->getUint32() == 1); // Only one op/trans implemented ndbrequire(reader->next()); ndbrequire(reader->getKey() == UtilPrepareReq::OperationType); ndbrequire(reader->next()); UtilPrepareReq::KeyValue tableKey = (UtilPrepareReq::KeyValue) reader->getKey(); ndbrequire((tableKey == UtilPrepareReq::TableName) || (tableKey == UtilPrepareReq::TableId)); /************************ * Ask Dict for metadata ************************/ { GetTabInfoReq * req = (GetTabInfoReq *)signal->getDataPtrSend(); req->senderRef = reference(); req->senderData = senderData; if (tableKey == UtilPrepareReq::TableName) { jam(); char tableName[MAX_TAB_NAME_SIZE]; req->requestType = GetTabInfoReq::RequestByName | GetTabInfoReq::LongSignalConf; req->tableNameLen = reader->getValueLen(); // Including trailing \0 /******************************************** * Code signal data and send signals to DICT ********************************************/ ndbrequire(req->tableNameLen < MAX_TAB_NAME_SIZE); reader->getString((char*)tableName); LinearSectionPtr ptr[1]; ptr[0].p = (Uint32*)tableName; ptr[0].sz = req->tableNameLen; sendSignal(DBDICT_REF, GSN_GET_TABINFOREQ, signal, GetTabInfoReq::SignalLength, JBB, ptr,1); } else { // (tableKey == UtilPrepareReq::TableId) jam(); req->requestType = GetTabInfoReq::RequestById | GetTabInfoReq::LongSignalConf; req->tableId = reader->getUint32(); sendSignal(DBDICT_REF, GSN_GET_TABINFOREQ, signal, GetTabInfoReq::SignalLength, JBB); } } } /** * @note We assume that this signal comes due to a request related * to a Prepare struct. DictTabInfo:s 'senderData' denotes * the Prepare struct related to the request. */ void DbUtil::execGET_TABINFO_CONF(Signal* signal){ jamEntry(); if(!assembleFragments(signal)){ jam(); return; } /**************** * Decode signal ****************/ GetTabInfoConf * const conf = (GetTabInfoConf*)signal->getDataPtr(); const Uint32 prepI = conf->senderData; const Uint32 totalLen = conf->totalLen; SegmentedSectionPtr dictTabInfoPtr; signal->getSection(dictTabInfoPtr, GetTabInfoConf::DICT_TAB_INFO); ndbrequire(dictTabInfoPtr.sz == totalLen); PreparePtr prepPtr; c_runningPrepares.getPtr(prepPtr, prepI); prepareOperation(signal, prepPtr); } void DbUtil::execGET_TABINFOREF(Signal* signal){ jamEntry(); GetTabInfoRef * ref = (GetTabInfoRef *)signal->getDataPtr(); Uint32 prepI = ref->senderData; #define EVENT_DEBUG #if 0 //def EVENT_DEBUG ndbout << "Signal GET_TABINFOREF received." << endl; ndbout << "Error Code: " << ref->errorCode << endl; switch (ref->errorCode) { case GetTabInfoRef::InvalidTableId: ndbout << " Msg: Invalid table id" << endl; break; case GetTabInfoRef::TableNotDefined: ndbout << " Msg: Table not defined" << endl; break; case GetTabInfoRef::TableNameToLong: ndbout << " Msg: Table node too long" << endl; break; default: ndbout << " Msg: Unknown error returned from Dict" << endl; break; } #endif PreparePtr prepPtr; c_runningPrepares.getPtr(prepPtr, prepI); sendUtilPrepareRef(signal, UtilPrepareRef::DICT_TAB_INFO_ERROR, prepPtr.p->clientRef, prepPtr.p->clientData); releasePrepare(prepPtr); } /****************************************************************************** * Prepare Operation * * Using a prepare record, prepare an operation (i.e. create PreparedOperation). * Info from both Pepare request (PreparePages) and DictTabInfo is used. * * Algorithm: * -# Seize AttrbuteMapping * - Lookup in preparePages how many attributes should be prepared * - Seize AttributeMapping * -# For each attributes in preparePages * - Lookup id and isPK in dictInfoPages * - Store "no -> (AttributeId, Position)" in AttributeMapping * -# For each map in AttributeMapping * - if (isPK) then assign offset ******************************************************************************/ void DbUtil::prepareOperation(Signal* signal, PreparePtr prepPtr) { jam(); /******************************************* * Seize and store PreparedOperation struct *******************************************/ PreparedOperationPtr prepOpPtr; if(!c_preparedOperationPool.seize(prepOpPtr)) { jam(); releaseSections(signal); sendUtilPrepareRef(signal, UtilPrepareRef::PREPARED_OPERATION_SEIZE_ERROR, prepPtr.p->clientRef, prepPtr.p->clientData); releasePrepare(prepPtr); return; } prepPtr.p->prepOpPtr = prepOpPtr; /******************** * Read request info ********************/ SimplePropertiesLinearReader prepPagesReader(&prepPtr.p->preparePages.getPtr(0)->data[0], prepPtr.p->prepDataLen); ndbrequire(prepPagesReader.first()); ndbrequire(prepPagesReader.getKey() == UtilPrepareReq::NoOfOperations); const Uint32 noOfOperations = prepPagesReader.getUint32(); ndbrequire(noOfOperations == 1); ndbrequire(prepPagesReader.next()); ndbrequire(prepPagesReader.getKey() == UtilPrepareReq::OperationType); const Uint32 operationType = prepPagesReader.getUint32(); ndbrequire(prepPagesReader.next()); char tableName[MAX_TAB_NAME_SIZE]; Uint32 tableId; UtilPrepareReq::KeyValue tableKey = (UtilPrepareReq::KeyValue) prepPagesReader.getKey(); if (tableKey == UtilPrepareReq::TableId) { jam(); tableId = prepPagesReader.getUint32(); } else { jam(); ndbrequire(prepPagesReader.getKey() == UtilPrepareReq::TableName); ndbrequire(prepPagesReader.getValueLen() <= MAX_TAB_NAME_SIZE); prepPagesReader.getString(tableName); } /****************************************************************** * Seize AttributeMapping (by counting no of attribs in prepPages) ******************************************************************/ Uint32 noOfAttributes = 0; // No of attributes in PreparePages (used later) while(prepPagesReader.next()) { if (tableKey == UtilPrepareReq::TableName) { jam(); ndbrequire(prepPagesReader.getKey() == UtilPrepareReq::AttributeName); } else { jam(); ndbrequire(prepPagesReader.getKey() == UtilPrepareReq::AttributeId); } noOfAttributes++; } ndbrequire(prepPtr.p->prepOpPtr.p->attrMapping.seize(noOfAttributes)); if (operationType == UtilPrepareReq::Read) { ndbrequire(prepPtr.p->prepOpPtr.p->rsInfo.seize(noOfAttributes)); } /*************************************** * For each attribute name, lookup info ***************************************/ // Goto start of attribute names ndbrequire(prepPagesReader.first() && prepPagesReader.next() && prepPagesReader.next()); DictTabInfo::Table tableDesc; tableDesc.init(); AttrMappingBuffer::DataBufferIterator attrMappingIt; ndbrequire(prepPtr.p->prepOpPtr.p->attrMapping.first(attrMappingIt)); ResultSetBuffer::DataBufferIterator rsInfoIt; if (operationType == UtilPrepareReq::Read) { ndbrequire(prepPtr.p->prepOpPtr.p->rsInfo.first(rsInfoIt)); } Uint32 noOfPKAttribsStored = 0; Uint32 noOfNonPKAttribsStored = 0; Uint32 attrLength = 0; Uint32 pkAttrLength = 0; char attrNameRequested[MAX_ATTR_NAME_SIZE]; Uint32 attrIdRequested; while(prepPagesReader.next()) { UtilPrepareReq::KeyValue attributeKey = (UtilPrepareReq::KeyValue) prepPagesReader.getKey(); ndbrequire((attributeKey == UtilPrepareReq::AttributeName) || (attributeKey == UtilPrepareReq::AttributeId)); if (attributeKey == UtilPrepareReq::AttributeName) { jam(); ndbrequire(prepPagesReader.getValueLen() <= MAX_ATTR_NAME_SIZE); prepPagesReader.getString(attrNameRequested); attrIdRequested= ~0u; } else { jam(); attrIdRequested = prepPagesReader.getUint32(); } /***************************************** * Copy DictTabInfo into tableDesc struct *****************************************/ SegmentedSectionPtr ptr; signal->getSection(ptr, GetTabInfoConf::DICT_TAB_INFO); SimplePropertiesSectionReader dictInfoReader(ptr, getSectionSegmentPool()); SimpleProperties::UnpackStatus unpackStatus; unpackStatus = SimpleProperties::unpack(dictInfoReader, &tableDesc, DictTabInfo::TableMapping, DictTabInfo::TableMappingSize, true, true); ndbrequire(unpackStatus == SimpleProperties::Break); /************************ * Lookup in DictTabInfo ************************/ DictTabInfo::Attribute attrDesc; attrDesc.init(); char attrName[MAX_ATTR_NAME_SIZE]; Uint32 attrId= ~(Uint32)0; bool attributeFound = false; Uint32 noOfKeysFound = 0; // # PK attrs found before attr in DICTdata Uint32 noOfNonKeysFound = 0; // # nonPK attrs found before attr in DICTdata for (Uint32 i=0; i<tableDesc.NoOfAttributes; i++) { if (tableKey == UtilPrepareReq::TableName) { jam(); ndbrequire(dictInfoReader.getKey() == DictTabInfo::AttributeName); ndbrequire(dictInfoReader.getValueLen() <= MAX_ATTR_NAME_SIZE); dictInfoReader.getString(attrName); attrId= ~(Uint32)0; // attrId not used } else { // (tableKey == UtilPrepareReq::TableId) jam(); dictInfoReader.next(); // Skip name ndbrequire(dictInfoReader.getKey() == DictTabInfo::AttributeId); attrId = dictInfoReader.getUint32(); attrName[0]= '\0'; // attrName not used } unpackStatus = SimpleProperties::unpack(dictInfoReader, &attrDesc, DictTabInfo::AttributeMapping, DictTabInfo::AttributeMappingSize, true, true); ndbrequire(unpackStatus == SimpleProperties::Break); //attrDesc.print(stdout); if (attrDesc.AttributeKeyFlag) { jam(); noOfKeysFound++; } else { jam(); noOfNonKeysFound++; } if (attributeKey == UtilPrepareReq::AttributeName) { if (strcmp(attrName, attrNameRequested) == 0) { attributeFound = true; break; } } else // (attributeKey == UtilPrepareReq::AttributeId) if (attrId == attrIdRequested) { attributeFound = true; break; } // Move to next attribute ndbassert(dictInfoReader.getKey() == DictTabInfo::AttributeEnd); dictInfoReader.next(); } /********************** * Attribute not found **********************/ if (!attributeFound) { jam(); releaseSections(signal); sendUtilPrepareRef(signal, UtilPrepareRef::DICT_TAB_INFO_ERROR, prepPtr.p->clientRef, prepPtr.p->clientData); infoEvent("UTIL: Unknown attribute requested: %s in table: %s", attrNameRequested, tableName); releasePreparedOperation(prepOpPtr); releasePrepare(prepPtr); return; } /************************************************************** * Attribute found - store in mapping (AttributeId, Position) **************************************************************/ AttributeHeader attrMap(attrDesc.AttributeId, // 1. Store AttrId 0); if (attrDesc.AttributeKeyFlag) { // ** Attribute belongs to PK ** prepOpPtr.p->pkBitmask.set(attrDesc.AttributeId); attrMap.setDataSize(noOfKeysFound - 1); // 2. Store Position noOfPKAttribsStored++; } else { attrMap.setDataSize(0x3fff); // 2. Store Position (fake) noOfNonPKAttribsStored++; /*********************************************************** * Error: Read nonPK Attr before all PK attr have been read ***********************************************************/ if (noOfPKAttribsStored != tableDesc.NoOfKeyAttr) { jam(); releaseSections(signal); sendUtilPrepareRef(signal, UtilPrepareRef::DICT_TAB_INFO_ERROR, prepPtr.p->clientRef, prepPtr.p->clientData); infoEvent("UTIL: Non-PK attr not allowed before " "all PK attrs have been defined, table: %s", tableName); releasePreparedOperation(prepOpPtr); releasePrepare(prepPtr); return; } } *(attrMappingIt.data) = attrMap.m_value; #if 0 ndbout << "BEFORE: attrLength: " << attrLength << endl; #endif { int len = 0; switch (attrDesc.AttributeSize) { case DictTabInfo::an8Bit: len = (attrDesc.AttributeArraySize + 3)/ 4; break; case DictTabInfo::a16Bit: len = (attrDesc.AttributeArraySize + 1) / 2; break; case DictTabInfo::a32Bit: len = attrDesc.AttributeArraySize; break; case DictTabInfo::a64Bit: len = attrDesc.AttributeArraySize * 2; break; case DictTabInfo::a128Bit: len = attrDesc.AttributeArraySize * 4; break; } attrLength += len; if (attrDesc.AttributeKeyFlag) pkAttrLength += len; if (operationType == UtilPrepareReq::Read) { AttributeHeader::init(rsInfoIt.data, attrDesc.AttributeId, // 1. Store AttrId len << 2); prepOpPtr.p->rsInfo.next(rsInfoIt, 1); } } #if 0 ndbout << ": AttributeSize: " << attrDesc.AttributeSize << endl; ndbout << ": AttributeArraySize: " << attrDesc.AttributeArraySize << endl; ndbout << "AFTER: attrLength: " << attrLength << endl; #endif //attrMappingIt.print(stdout); //prepPtr.p->prepOpPtr.p->attrMapping.print(stdout); prepPtr.p->prepOpPtr.p->attrMapping.next(attrMappingIt, 1); } /*************************** * Error: Not all PKs found ***************************/ if (noOfPKAttribsStored != tableDesc.NoOfKeyAttr) { jam(); releaseSections(signal); sendUtilPrepareRef(signal, UtilPrepareRef::DICT_TAB_INFO_ERROR, prepPtr.p->clientRef, prepPtr.p->clientData); infoEvent("UTIL: Not all primary key attributes requested for table: %s", tableName); releasePreparedOperation(prepOpPtr); releasePrepare(prepPtr); return; } #if 0 AttrMappingBuffer::ConstDataBufferIterator tmpIt; for (prepPtr.p->prepOpPtr.p->attrMapping.first(tmpIt); tmpIt.curr.i != RNIL; prepPtr.p->prepOpPtr.p->attrMapping.next(tmpIt)) { AttributeHeader* ah = (AttributeHeader *) tmpIt.data; ah->print(stdout); } #endif /********************************************** * Preparing of PreparedOperation signal train **********************************************/ Uint32 static_len = TcKeyReq::StaticLength; prepOpPtr.p->tckey.tableId = tableDesc.TableId; prepOpPtr.p->tckey.tableSchemaVersion = tableDesc.TableVersion; prepOpPtr.p->noOfKeyAttr = tableDesc.NoOfKeyAttr; prepOpPtr.p->keyLen = tableDesc.KeyLength; // Total no of words in PK if (prepOpPtr.p->keyLen > TcKeyReq::MaxKeyInfo) { jam(); prepOpPtr.p->tckeyLenInBytes = (static_len + TcKeyReq::MaxKeyInfo) * 4; } else { jam(); prepOpPtr.p->tckeyLenInBytes = (static_len + prepOpPtr.p->keyLen) * 4; } prepOpPtr.p->keyDataPos = static_len; // Start of keyInfo[] in tckeyreq Uint32 requestInfo = 0; TcKeyReq::setAbortOption(requestInfo, TcKeyReq::AbortOnError); TcKeyReq::setKeyLength(requestInfo, tableDesc.KeyLength); switch(operationType) { case(UtilPrepareReq::Read): prepOpPtr.p->rsLen = attrLength + tableDesc.NoOfKeyAttr + noOfNonPKAttribsStored; // Read needs a resultset prepOpPtr.p->noOfAttr = tableDesc.NoOfKeyAttr + noOfNonPKAttribsStored; prepOpPtr.p->tckey.attrLen = prepOpPtr.p->noOfAttr; TcKeyReq::setOperationType(requestInfo, ZREAD); break; case(UtilPrepareReq::Update): prepOpPtr.p->rsLen = 0; prepOpPtr.p->noOfAttr = tableDesc.NoOfKeyAttr + noOfNonPKAttribsStored; prepOpPtr.p->tckey.attrLen = attrLength + prepOpPtr.p->noOfAttr; TcKeyReq::setOperationType(requestInfo, ZUPDATE); break; case(UtilPrepareReq::Insert): prepOpPtr.p->rsLen = 0; prepOpPtr.p->noOfAttr = tableDesc.NoOfKeyAttr + noOfNonPKAttribsStored; prepOpPtr.p->tckey.attrLen = attrLength + prepOpPtr.p->noOfAttr; TcKeyReq::setOperationType(requestInfo, ZINSERT); break; case(UtilPrepareReq::Delete): // The number of attributes should equal the size of the primary key ndbrequire(tableDesc.KeyLength == attrLength); prepOpPtr.p->rsLen = 0; prepOpPtr.p->noOfAttr = tableDesc.NoOfKeyAttr; prepOpPtr.p->tckey.attrLen = 0; TcKeyReq::setOperationType(requestInfo, ZDELETE); break; case(UtilPrepareReq::Write): prepOpPtr.p->rsLen = 0; prepOpPtr.p->noOfAttr = tableDesc.NoOfKeyAttr + noOfNonPKAttribsStored; prepOpPtr.p->tckey.attrLen = attrLength + prepOpPtr.p->noOfAttr; TcKeyReq::setOperationType(requestInfo, ZWRITE); break; } TcKeyReq::setAIInTcKeyReq(requestInfo, 0); // Attrinfo sent separately prepOpPtr.p->tckey.requestInfo = requestInfo; /**************************** * Confirm completed prepare ****************************/ UtilPrepareConf * conf = (UtilPrepareConf *)signal->getDataPtr(); conf->senderData = prepPtr.p->clientData; conf->prepareId = prepPtr.p->prepOpPtr.i; releaseSections(signal); sendSignal(prepPtr.p->clientRef, GSN_UTIL_PREPARE_CONF, signal, UtilPrepareConf::SignalLength, JBB); #if 0 prepPtr.p->prepOpPtr.p->print(); #endif releasePrepare(prepPtr); } void DbUtil::execUTIL_RELEASE_REQ(Signal* signal){ jamEntry(); UtilReleaseReq * req = (UtilReleaseReq *)signal->getDataPtr(); const Uint32 clientRef = signal->senderBlockRef(); const Uint32 prepareId = req->prepareId; const Uint32 senderData = req->senderData; #if 0 /** * This only works in when ARRAY_GUARD is defined (debug-mode) */ if (!c_preparedOperationPool.isSeized(prepareId)) { UtilReleaseRef * ref = (UtilReleaseRef *)signal->getDataPtr(); ref->prepareId = prepareId; ref->errorCode = UtilReleaseRef::NO_SUCH_PREPARE_SEIZED; sendSignal(clientRef, GSN_UTIL_RELEASE_REF, signal, UtilReleaseRef::SignalLength, JBB); } #endif PreparedOperationPtr prepOpPtr; c_preparedOperationPool.getPtr(prepOpPtr, prepareId); releasePreparedOperation(prepOpPtr); UtilReleaseConf * const conf = (UtilReleaseConf*)signal->getDataPtrSend(); conf->senderData = senderData; sendSignal(clientRef, GSN_UTIL_RELEASE_CONF, signal, UtilReleaseConf::SignalLength, JBB); } /************************************************************************** * ------------------------------------------------------------------------ * MODULE: Sequence Service * ------------------------------------------------------------------------ * * A service with a stored incrementable number **************************************************************************/ void DbUtil::hardcodedPrepare() { /** * Prepare SequenceCurrVal (READ) */ { PreparedOperationPtr ptr; ndbrequire(c_preparedOperationPool.seizeId(ptr, 0)); ptr.p->keyLen = 1; ptr.p->tckey.attrLen = 1; ptr.p->rsLen = 3; ptr.p->tckeyLenInBytes = (TcKeyReq::StaticLength + ptr.p->keyLen + ptr.p->tckey.attrLen) * 4; ptr.p->keyDataPos = TcKeyReq::StaticLength; ptr.p->tckey.tableId = 0; Uint32 requestInfo = 0; TcKeyReq::setAbortOption(requestInfo, TcKeyReq::CommitIfFailFree); TcKeyReq::setOperationType(requestInfo, ZREAD); TcKeyReq::setKeyLength(requestInfo, 1); TcKeyReq::setAIInTcKeyReq(requestInfo, 1); ptr.p->tckey.requestInfo = requestInfo; ptr.p->tckey.tableSchemaVersion = 1; // This is actually attr data AttributeHeader::init(&ptr.p->tckey.distrGroupHashValue, 1, 0); ndbrequire(ptr.p->rsInfo.seize(1)); ResultSetInfoBuffer::DataBufferIterator it; ptr.p->rsInfo.first(it); AttributeHeader::init(it.data, 1, 2 << 2); // Attribute 1 - 2 data words } /** * Prepare SequenceNextVal (UPDATE) */ { PreparedOperationPtr ptr; ndbrequire(c_preparedOperationPool.seizeId(ptr, 1)); ptr.p->keyLen = 1; ptr.p->rsLen = 3; ptr.p->tckeyLenInBytes = (TcKeyReq::StaticLength + ptr.p->keyLen + 5) * 4; ptr.p->keyDataPos = TcKeyReq::StaticLength; ptr.p->tckey.attrLen = 11; ptr.p->tckey.tableId = 0; Uint32 requestInfo = 0; TcKeyReq::setAbortOption(requestInfo, TcKeyReq::CommitIfFailFree); TcKeyReq::setOperationType(requestInfo, ZUPDATE); TcKeyReq::setKeyLength(requestInfo, 1); TcKeyReq::setAIInTcKeyReq(requestInfo, 5); TcKeyReq::setInterpretedFlag(requestInfo, 1); ptr.p->tckey.requestInfo = requestInfo; ptr.p->tckey.tableSchemaVersion = 1; // Signal is packed, which is why attrInfo is at distrGroupHashValue // position Uint32 * attrInfo = &ptr.p->tckey.distrGroupHashValue; attrInfo[0] = 0; // IntialReadSize attrInfo[1] = 5; // InterpretedSize attrInfo[2] = 0; // FinalUpdateSize attrInfo[3] = 1; // FinalReadSize attrInfo[4] = 0; // SubroutineSize { // AttrInfo ndbrequire(ptr.p->attrInfo.seize(6)); AttrInfoBuffer::DataBufferIterator it; ptr.p->attrInfo.first(it); * it.data = Interpreter::Read(1, 6); ndbrequire(ptr.p->attrInfo.next(it)); * it.data = Interpreter::LoadConst16(7, 1); ndbrequire(ptr.p->attrInfo.next(it)); * it.data = Interpreter::Add(7, 6, 7); ndbrequire(ptr.p->attrInfo.next(it)); * it.data = Interpreter::Write(1, 7); ndbrequire(ptr.p->attrInfo.next(it)); * it.data = Interpreter::ExitOK(); ndbrequire(ptr.p->attrInfo.next(it)); AttributeHeader::init(it.data, 1, 0); } { // ResultSet ndbrequire(ptr.p->rsInfo.seize(1)); ResultSetInfoBuffer::DataBufferIterator it; ptr.p->rsInfo.first(it); AttributeHeader::init(it.data, 1, 2 << 2); // Attribute 1 - 2 data words } } /** * Prepare CreateSequence (INSERT) */ { PreparedOperationPtr ptr; ndbrequire(c_preparedOperationPool.seizeId(ptr, 2)); ptr.p->keyLen = 1; ptr.p->tckey.attrLen = 5; ptr.p->rsLen = 0; ptr.p->tckeyLenInBytes = (TcKeyReq::StaticLength + ptr.p->keyLen + ptr.p->tckey.attrLen) * 4; ptr.p->keyDataPos = TcKeyReq::StaticLength; ptr.p->tckey.tableId = 0; Uint32 requestInfo = 0; TcKeyReq::setAbortOption(requestInfo, TcKeyReq::CommitIfFailFree); TcKeyReq::setOperationType(requestInfo, ZINSERT); TcKeyReq::setKeyLength(requestInfo, 1); TcKeyReq::setAIInTcKeyReq(requestInfo, 0); ptr.p->tckey.requestInfo = requestInfo; ptr.p->tckey.tableSchemaVersion = 1; } } void DbUtil::execUTIL_SEQUENCE_REQ(Signal* signal){ jamEntry(); UtilSequenceReq * req = (UtilSequenceReq*)signal->getDataPtr(); PreparedOperation * prepOp; switch(req->requestType){ case UtilSequenceReq::CurrVal: prepOp = c_preparedOperationPool.getPtr(0); //c_SequenceCurrVal break; case UtilSequenceReq::NextVal: prepOp = c_preparedOperationPool.getPtr(1); //c_SequenceNextVal break; case UtilSequenceReq::Create: prepOp = c_preparedOperationPool.getPtr(2); //c_CreateSequence break; default: ndbrequire(false); prepOp = 0; // remove warning } /** * 1 Transaction with 1 operation */ TransactionPtr transPtr; ndbrequire(c_runningTransactions.seize(transPtr)); OperationPtr opPtr; ndbrequire(transPtr.p->operations.seize(opPtr)); ndbrequire(opPtr.p->rs.seize(prepOp->rsLen)); ndbrequire(opPtr.p->keyInfo.seize(prepOp->keyLen)); transPtr.p->gsn = GSN_UTIL_SEQUENCE_REQ; transPtr.p->clientRef = signal->senderBlockRef(); transPtr.p->clientData = req->senderData; transPtr.p->sequence.sequenceId = req->sequenceId; transPtr.p->sequence.requestType = req->requestType; opPtr.p->prepOp = prepOp; opPtr.p->prepOp_i = RNIL; KeyInfoBuffer::DataBufferIterator it; opPtr.p->keyInfo.first(it); it.data[0] = transPtr.p->sequence.sequenceId; if(req->requestType == UtilSequenceReq::Create){ ndbrequire(opPtr.p->attrInfo.seize(5)); AttrInfoBuffer::DataBufferIterator it; opPtr.p->attrInfo.first(it); AttributeHeader::init(it.data, 0, 1 << 2); ndbrequire(opPtr.p->attrInfo.next(it)); * it.data = transPtr.p->sequence.sequenceId; ndbrequire(opPtr.p->attrInfo.next(it)); AttributeHeader::init(it.data, 1, 2 << 2); ndbrequire(opPtr.p->attrInfo.next(it)); * it.data = 0; ndbrequire(opPtr.p->attrInfo.next(it)); * it.data = 0; } runTransaction(signal, transPtr); } int DbUtil::getResultSet(Signal* signal, const Transaction * transP, struct LinearSectionPtr sectionsPtr[]) { OperationPtr opPtr; ndbrequire(transP->operations.first(opPtr)); ndbrequire(transP->operations.hasNext(opPtr) == false); int noAttr = 0; int dataSz = 0; Uint32* tmpBuf = signal->theData + 25; const Uint32* headerBuffer = tmpBuf; const ResultSetBuffer & rs = opPtr.p->rs; ResultSetInfoBuffer::ConstDataBufferIterator it; // extract headers for(rs.first(it); it.curr.i != RNIL; ) { *tmpBuf++ = it.data[0]; rs.next(it, ((AttributeHeader*)&it.data[0])->getDataSize() + 1); noAttr++; } if (noAttr == 0) return 0; const Uint32* dataBuffer = tmpBuf; // extract data for(rs.first(it); it.curr.i != RNIL; ) { int sz = ((AttributeHeader*)&it.data[0])->getDataSize(); rs.next(it,1); for (int i = 0; i < sz; i++) { *tmpBuf++ = *it.data; rs.next(it,1); dataSz++; } } sectionsPtr[UtilExecuteReq::HEADER_SECTION].p = (Uint32 *)headerBuffer; sectionsPtr[UtilExecuteReq::HEADER_SECTION].sz = noAttr; sectionsPtr[UtilExecuteReq::DATA_SECTION].p = (Uint32 *)dataBuffer; sectionsPtr[UtilExecuteReq::DATA_SECTION].sz = dataSz; return 1; } void DbUtil::reportSequence(Signal* signal, const Transaction * transP){ OperationPtr opPtr; ndbrequire(transP->operations.first(opPtr)); ndbrequire(transP->operations.hasNext(opPtr) == false); if(transP->errorCode == 0){ jam(); // OK UtilSequenceConf * ret = (UtilSequenceConf *)signal->getDataPtrSend(); ret->senderData = transP->clientData; ret->sequenceId = transP->sequence.sequenceId; ret->requestType = transP->sequence.requestType; bool ok = false; switch(transP->sequence.requestType){ case UtilSequenceReq::CurrVal: case UtilSequenceReq::NextVal:{ ok = true; ndbrequire(opPtr.p->rsRecv == 3); ResultSetBuffer::DataBufferIterator rsit; ndbrequire(opPtr.p->rs.first(rsit)); ret->sequenceValue[0] = rsit.data[1]; ret->sequenceValue[1] = rsit.data[2]; break; } case UtilSequenceReq::Create: ok = true; ret->sequenceValue[0] = 0; ret->sequenceValue[1] = 0; break; } ndbrequire(ok); sendSignal(transP->clientRef, GSN_UTIL_SEQUENCE_CONF, signal, UtilSequenceConf::SignalLength, JBB); return; } UtilSequenceRef::ErrorCode errCode = UtilSequenceRef::TCError; switch(transP->sequence.requestType) { case UtilSequenceReq::CurrVal: case UtilSequenceReq::NextVal:{ if (transP->errorCode == 626) errCode = UtilSequenceRef::NoSuchSequence; break; } case UtilSequenceReq::Create: break; } UtilSequenceRef * ret = (UtilSequenceRef *)signal->getDataPtrSend(); ret->senderData = transP->clientData; ret->sequenceId = transP->sequence.sequenceId; ret->requestType = transP->sequence.requestType; ret->errorCode = (Uint32)errCode; sendSignal(transP->clientRef, GSN_UTIL_SEQUENCE_REF, signal, UtilSequenceRef::SignalLength, JBB); } #if 0 Ndb ndb("ndb","def"); NdbConnection* tConnection = ndb.startTransaction(); NdbOperation* tOperation = tConnection->getNdbOperation("SYSTAB_0"); //#if 0 && API_CODE if( tOperation != NULL ) { tOperation->interpretedUpdateTuple(); tOperation->equal((U_Int32)0, keyValue ); tNextId_Result = tOperation->getValue((U_Int32)1); tOperation->incValue((U_Int32)1, (U_Int32)8192); if (tConnection->execute( Commit ) != -1 ) { U_Int64 tValue = tNextId_Result->u_64_value(); // Read result value theFirstTransId = tValue; theLastTransId = tValue + 8191; closeTransaction(tConnection); return startTransactionLocal(aPriority, nodeId); } } /** * IntialReadSize = 0; * InterpretedSize = incValue(1); * FinalUpdateSize = 0; * FinalReadSize = 1; // Read value * SubroutineSize = 0; */ #endif /************************************************************************** * ------------------------------------------------------------------------ * MODULE: Transaction execution request * ------------------------------------------------------------------------ * * Handle requests to execute a prepared transaction **************************************************************************/ void DbUtil::execUTIL_EXECUTE_REQ(Signal* signal) { jamEntry(); UtilExecuteReq * req = (UtilExecuteReq *)signal->getDataPtr(); const Uint32 clientRef = req->senderRef; const Uint32 clientData = req->senderData; const Uint32 prepareId = req->getPrepareId(); const bool releaseFlag = req->getReleaseFlag(); if(signal->getNoOfSections() == 0) { // Missing prepare data jam(); releaseSections(signal); sendUtilExecuteRef(signal, UtilExecuteRef::MissingDataSection, 0, clientRef, clientData); return; } /******************************* * Get PreparedOperation struct *******************************/ PreparedOperationPtr prepOpPtr; c_preparedOperationPool.getPtr(prepOpPtr, prepareId); prepOpPtr.p->releaseFlag = releaseFlag; TransactionPtr transPtr; OperationPtr opPtr; SegmentedSectionPtr headerPtr, dataPtr; signal->getSection(headerPtr, UtilExecuteReq::HEADER_SECTION); SectionReader headerReader(headerPtr, getSectionSegmentPool()); signal->getSection(dataPtr, UtilExecuteReq::DATA_SECTION); SectionReader dataReader(dataPtr, getSectionSegmentPool()); #if 0 //def EVENT_DEBUG // Debugging printf("DbUtil::execUTIL_EXECUTEL_REQ: Headers (%u): ", headerPtr.sz); Uint32 word; while(headerReader.getWord(&word)) printf("H'%.8x ", word); printf("\n"); printf("DbUtil::execUTIL_EXECUTEL_REQ: Data (%u): ", dataPtr.sz); headerReader.reset(); while(dataReader.getWord(&word)) printf("H'%.8x ", word); printf("\n"); dataReader.reset(); #endif // Uint32 totalDataLen = headerPtr.sz + dataPtr.sz; /************************************************************ * Seize Transaction record ************************************************************/ ndbrequire(c_runningTransactions.seize(transPtr)); transPtr.p->gsn = GSN_UTIL_EXECUTE_REQ; transPtr.p->clientRef = clientRef; transPtr.p->clientData = clientData; ndbrequire(transPtr.p->operations.seize(opPtr)); opPtr.p->prepOp = prepOpPtr.p; opPtr.p->prepOp_i = prepOpPtr.i; #if 0 //def EVENT_DEBUG printf("opPtr.p->rs.seize( %u )\n", prepOpPtr.p->rsLen); #endif ndbrequire(opPtr.p->rs.seize(prepOpPtr.p->rsLen)); /*********************************************************** * Store signal data on linear memory in Transaction record ***********************************************************/ KeyInfoBuffer* keyInfo = &opPtr.p->keyInfo; AttrInfoBuffer* attrInfo = &opPtr.p->attrInfo; AttributeHeader header; Uint32* tempBuf = signal->theData + 25; bool dataComplete = true; while(headerReader.getWord((Uint32 *)&header)) { Uint32* bufStart = tempBuf; header.insertHeader(tempBuf++); for(unsigned int i = 0; i < header.getDataSize(); i++) { if (!dataReader.getWord(tempBuf++)) { dataComplete = false; break; } } bool res = true; #if 0 //def EVENT_DEBUG if (TcKeyReq::getOperationType(prepOpPtr.p->tckey.requestInfo) == TcKeyReq::Read) { if(prepOpPtr.p->pkBitmask.get(header.getAttributeId())) printf("PrimaryKey\n"); } printf("AttrId %u Hdrsz %d Datasz %u \n", header.getAttributeId(), header.getHeaderSize(), header.getDataSize()); #endif if(prepOpPtr.p->pkBitmask.get(header.getAttributeId())) // A primary key attribute res = keyInfo->append(bufStart + header.getHeaderSize(), header.getDataSize()); switch (TcKeyReq::getOperationType(prepOpPtr.p->tckey.requestInfo)) { case ZREAD: res &= attrInfo->append(bufStart, header.getHeaderSize()); break; case ZDELETE: // no attrinfo for Delete break; default: res &= attrInfo->append(bufStart, header.getHeaderSize() + header.getDataSize()); } if (!res) { // Failed to allocate buffer data jam(); releaseSections(signal); sendUtilExecuteRef(signal, UtilExecuteRef::AllocationError, 0, clientRef, clientData); releaseTransaction(transPtr); return; } } if (!dataComplete) { // Missing data in data section jam(); releaseSections(signal); sendUtilExecuteRef(signal, UtilExecuteRef::MissingData, 0, clientRef, clientData); releaseTransaction(transPtr); return; } // quick hack for hash index build if (TcKeyReq::getOperationType(prepOpPtr.p->tckey.requestInfo) != ZREAD){ prepOpPtr.p->tckey.attrLen = prepOpPtr.p->attrInfo.getSize() + opPtr.p->attrInfo.getSize(); TcKeyReq::setKeyLength(prepOpPtr.p->tckey.requestInfo, keyInfo->getSize()); } #if 0 const Uint32 l1 = prepOpPtr.p->tckey.attrLen; const Uint32 l2 = prepOpPtr.p->attrInfo.getSize() + opPtr.p->attrInfo.getSize(); if (TcKeyReq::getOperationType(prepOpPtr.p->tckey.requestInfo) != ZREAD){ ndbrequire(l1 == l2); } else { ndbout_c("TcKeyReq::Read"); } #endif releaseSections(signal); transPtr.p->noOfRetries = 3; runTransaction(signal, transPtr); } /************************************************************************** * ------------------------------------------------------------------------ * MODULE: General transaction machinery * ------------------------------------------------------------------------ * Executes a prepared transaction **************************************************************************/ void DbUtil::runTransaction(Signal* signal, TransactionPtr transPtr){ /* Init transaction */ transPtr.p->sent = 0; transPtr.p->recv = 0; transPtr.p->errorCode = 0; getTransId(transPtr.p); OperationPtr opPtr; ndbrequire(transPtr.p->operations.first(opPtr)); /* First operation */ Uint32 start = 0; TcKeyReq::setStartFlag(start, 1); runOperation(signal, transPtr, opPtr, start); transPtr.p->sent ++; /* Rest of operations */ start = 0; while(opPtr.i != RNIL){ runOperation(signal, transPtr, opPtr, start); transPtr.p->sent ++; } //transPtr.p->print(); } void DbUtil::runOperation(Signal* signal, TransactionPtr & transPtr, OperationPtr & opPtr, Uint32 start) { Uint32 opI = opPtr.i; Operation * op = opPtr.p; const PreparedOperation * pop = op->prepOp; if(!transPtr.p->operations.next(opPtr)){ TcKeyReq::setCommitFlag(start, 1); // Last operation TcKeyReq::setExecuteFlag(start, 1); } #if 0 //def EVENT_DEBUG if (TcKeyReq::getOperationType(pop->tckey.requestInfo) == TcKeyReq::Read) { printf("TcKeyReq::Read runOperation\n"); } #endif /** * Init operation w.r.t result set */ initResultSet(op->rs, pop->rsInfo); op->rs.first(op->rsIterator); op->rsRecv = 0; #if 0 //def EVENT_DEBUG printf("pop->rsLen %u\n", pop->rsLen); #endif op->rsExpect = 0; op->transPtrI = transPtr.i; TcKeyReq * tcKey = (TcKeyReq*)signal->getDataPtrSend(); //ndbout << "*** 6 ***"<< endl; pop->print(); memcpy(tcKey, &pop->tckey, pop->tckeyLenInBytes); //ndbout << "*** 6b ***"<< endl; //printTCKEYREQ(stdout, signal->getDataPtrSend(), // pop->tckeyLenInBytes >> 2, 0); tcKey->apiConnectPtr = transPtr.p->connectPtr; tcKey->senderData = opI; tcKey->transId1 = transPtr.p->transId[0]; tcKey->transId2 = transPtr.p->transId[1]; tcKey->requestInfo |= start; #if 0 //def EVENT_DEBUG // Debugging printf("DbUtil::runOperation: KEYINFO\n"); op->keyInfo.print(stdout); printf("DbUtil::runOperation: ATTRINFO\n"); op->attrInfo.print(stdout); #endif /** * Key Info */ //KeyInfoBuffer::DataBufferIterator kit; KeyInfoIterator kit; op->keyInfo.first(kit); Uint32 *keyDst = ((Uint32*)tcKey) + pop->keyDataPos; for(Uint32 i = 0; i<8 && kit.curr.i != RNIL; i++, op->keyInfo.next(kit)){ keyDst[i] = * kit.data; } //ndbout << "*** 7 ***" << endl; //printTCKEYREQ(stdout, signal->getDataPtrSend(), // pop->tckeyLenInBytes >> 2, 0); #if 0 //def EVENT_DEBUG printf("DbUtil::runOperation: sendSignal(DBTC_REF, GSN_TCKEYREQ, signal, %d , JBB)\n", pop->tckeyLenInBytes >> 2); printTCKEYREQ(stdout, signal->getDataPtr(), pop->tckeyLenInBytes >> 2,0); #endif sendSignal(DBTC_REF, GSN_TCKEYREQ, signal, pop->tckeyLenInBytes >> 2, JBB); /** * More the 8 words of key info not implemented */ // ndbrequire(kit.curr.i == RNIL); // Yes it is /** * KeyInfo */ KeyInfo* keyInfo = (KeyInfo *)signal->getDataPtrSend(); keyInfo->connectPtr = transPtr.p->connectPtr; keyInfo->transId[0] = transPtr.p->transId[0]; keyInfo->transId[1] = transPtr.p->transId[1]; sendKeyInfo(signal, keyInfo, op->keyInfo, kit); /** * AttrInfo */ AttrInfo* attrInfo = (AttrInfo *)signal->getDataPtrSend(); attrInfo->connectPtr = transPtr.p->connectPtr; attrInfo->transId[0] = transPtr.p->transId[0]; attrInfo->transId[1] = transPtr.p->transId[1]; AttrInfoIterator ait; pop->attrInfo.first(ait); sendAttrInfo(signal, attrInfo, pop->attrInfo, ait); op->attrInfo.first(ait); sendAttrInfo(signal, attrInfo, op->attrInfo, ait); } void DbUtil::sendKeyInfo(Signal* signal, KeyInfo* keyInfo, const KeyInfoBuffer & keyBuf, KeyInfoIterator & kit) { while(kit.curr.i != RNIL) { Uint32 *keyDst = keyInfo->keyData; Uint32 keyDataLen = 0; for(Uint32 i = 0; i<KeyInfo::DataLength && kit.curr.i != RNIL; i++, keyBuf.next(kit)){ keyDst[i] = * kit.data; keyDataLen++; } #if 0 //def EVENT_DEBUG printf("DbUtil::sendKeyInfo: sendSignal(DBTC_REF, GSN_KEYINFO, signal, %d , JBB)\n", KeyInfo::HeaderLength + keyDataLen); #endif sendSignal(DBTC_REF, GSN_KEYINFO, signal, KeyInfo::HeaderLength + keyDataLen, JBB); } } void DbUtil::sendAttrInfo(Signal* signal, AttrInfo* attrInfo, const AttrInfoBuffer & attrBuf, AttrInfoIterator & ait) { while(ait.curr.i != RNIL) { Uint32 *attrDst = attrInfo->attrData; Uint32 i = 0; for(i = 0; i<AttrInfo::DataLength && ait.curr.i != RNIL; i++, attrBuf.next(ait)){ attrDst[i] = * ait.data; } #if 0 //def EVENT_DEBUG printf("DbUtil::sendAttrInfo: sendSignal(DBTC_REF, GSN_ATTRINFO, signal, %d , JBB)\n", AttrInfo::HeaderLength + i); #endif sendSignal(DBTC_REF, GSN_ATTRINFO, signal, AttrInfo::HeaderLength + i, JBB); } } void DbUtil::initResultSet(ResultSetBuffer & rs, const ResultSetInfoBuffer & rsi){ ResultSetBuffer::DataBufferIterator rsit; rs.first(rsit); ResultSetInfoBuffer::ConstDataBufferIterator rsiit; for(rsi.first(rsiit); rsiit.curr.i != RNIL; rsi.next(rsiit)){ ndbrequire(rsit.curr.i != RNIL); rsit.data[0] = rsiit.data[0]; #if 0 //def EVENT_DEBUG printf("Init resultset %u, sz %d\n", rsit.curr.i, ((AttributeHeader*)&rsit.data[0])->getDataSize() + 1); #endif rs.next(rsit, ((AttributeHeader*)&rsit.data[0])->getDataSize() + 1); } } void DbUtil::getTransId(Transaction * transP){ Uint32 tmp[2]; tmp[0] = c_transId[0]; tmp[1] = c_transId[1]; transP->transId[0] = tmp[0]; transP->transId[1] = tmp[1]; c_transId[1] = tmp[1] + 1; } /************************************************************************** * ------------------------------------------------------------------------ * MODULE: Post Execute * ------------------------------------------------------------------------ * * Handles result from a sent transaction **************************************************************************/ /** * execTRANSID_AI * * Receive result from transaction * * NOTE: This codes assumes that * TransidAI::DataLength = ResultSetBuffer::getSegmentSize() * n */ void DbUtil::execTRANSID_AI(Signal* signal){ jamEntry(); #if 0 //def EVENT_DEBUG ndbout_c("File: %s line: %u",__FILE__,__LINE__); #endif const Uint32 opI = signal->theData[0]; const Uint32 transId1 = signal->theData[1]; const Uint32 transId2 = signal->theData[2]; const Uint32 dataLen = signal->length() - 3; Operation * opP = c_operationPool.getPtr(opI); TransactionPtr transPtr; c_runningTransactions.getPtr(transPtr, opP->transPtrI); ndbrequire(transId1 == transPtr.p->transId[0] && transId2 == transPtr.p->transId[1]); opP->rsRecv += dataLen; /** * Save result */ const Uint32 *src = &signal->theData[3]; ResultSetBuffer::DataBufferIterator rs = opP->rsIterator; ndbrequire(opP->rs.import(rs,src,dataLen)); opP->rs.next(rs, dataLen); opP->rsIterator = rs; if(!opP->complete()){ jam(); return; } transPtr.p->recv++; if(!transPtr.p->complete()){ jam(); return; } finishTransaction(signal, transPtr); } void DbUtil::execTCKEYCONF(Signal* signal){ jamEntry(); #if 0 //def EVENT_DEBUG ndbout_c("File: %s line: %u",__FILE__,__LINE__); #endif TcKeyConf * keyConf = (TcKeyConf*)signal->getDataPtr(); //const Uint32 gci = keyConf->gci; const Uint32 transI = keyConf->apiConnectPtr >> 1; const Uint32 confInfo = keyConf->confInfo; const Uint32 transId1 = keyConf->transId1; const Uint32 transId2 = keyConf->transId2; Uint32 recv = 0; const Uint32 ops = TcKeyConf::getNoOfOperations(confInfo); for(Uint32 i = 0; i<ops; i++){ OperationPtr opPtr; c_operationPool.getPtr(opPtr, keyConf->operations[i].apiOperationPtr); ndbrequire(opPtr.p->transPtrI == transI); opPtr.p->rsExpect += keyConf->operations[i].attrInfoLen; if(opPtr.p->complete()){ recv++; } } /** * Check commit ack marker flag */ if (TcKeyConf::getMarkerFlag(confInfo)){ signal->theData[0] = transId1; signal->theData[1] = transId2; sendSignal(DBTC_REF, GSN_TC_COMMIT_ACK, signal, 2, JBB); }//if TransactionPtr transPtr; c_runningTransactions.getPtr(transPtr, transI); ndbrequire(transId1 == transPtr.p->transId[0] && transId2 == transPtr.p->transId[1]); transPtr.p->recv += recv; if(!transPtr.p->complete()){ jam(); return; } finishTransaction(signal, transPtr); } void DbUtil::execTCKEYREF(Signal* signal){ jamEntry(); #if 0 //def EVENT_DEBUG ndbout_c("File: %s line: %u",__FILE__,__LINE__); #endif const Uint32 transI = signal->theData[0] >> 1; const Uint32 transId1 = signal->theData[1]; const Uint32 transId2 = signal->theData[2]; const Uint32 errCode = signal->theData[3]; TransactionPtr transPtr; c_runningTransactions.getPtr(transPtr, transI); ndbrequire(transId1 == transPtr.p->transId[0] && transId2 == transPtr.p->transId[1]); //if(getClassification(errCode) == PermanentError){ //} //ndbout << "Transaction error (code: " << errCode << ")" << endl; transPtr.p->errorCode = errCode; finishTransaction(signal, transPtr); } void DbUtil::execTCROLLBACKREP(Signal* signal){ jamEntry(); #if 0 //def EVENT_DEBUG ndbout_c("File: %s line: %u",__FILE__,__LINE__); #endif const Uint32 transI = signal->theData[0] >> 1; const Uint32 transId1 = signal->theData[1]; const Uint32 transId2 = signal->theData[2]; const Uint32 errCode = signal->theData[3]; TransactionPtr transPtr; c_runningTransactions.getPtr(transPtr, transI); ndbrequire(transId1 == transPtr.p->transId[0] && transId2 == transPtr.p->transId[1]); //if(getClassification(errCode) == PermanentError){ //} #if 0 //def EVENT_DEBUG ndbout << "Transaction error (code: " << errCode << ")" << endl; #endif if(transPtr.p->noOfRetries > 0){ transPtr.p->noOfRetries--; switch(errCode){ case 266: case 410: case 1204: #if 0 ndbout_c("errCode: %d noOfRetries: %d -> retry", errCode, transPtr.p->noOfRetries); #endif runTransaction(signal, transPtr); return; } } transPtr.p->errorCode = errCode; finishTransaction(signal, transPtr); } void DbUtil::finishTransaction(Signal* signal, TransactionPtr transPtr){ #if 0 //def EVENT_DEBUG ndbout_c("Transaction %x %x completed %s", transPtr.p->transId[0], transPtr.p->transId[1], transPtr.p->errorCode == 0 ? "OK" : "FAILED"); #endif /* How to find the correct RS? Could we have multi-RS/transaction? Operation * opP = c_operationPool.getPtr(opI); ResultSetBuffer::DataBufferIterator rsit; ndbrequire(opP->rs.first(rsit)); ndbout << "F Result: " << rsit.data << endl; while (opP->rs.next(rsit)) { ndbout << "R Result: " << rsit.data << endl; } */ switch(transPtr.p->gsn){ case GSN_UTIL_SEQUENCE_REQ: jam(); reportSequence(signal, transPtr.p); break; case GSN_UTIL_EXECUTE_REQ: if (transPtr.p->errorCode) { UtilExecuteRef * ret = (UtilExecuteRef *)signal->getDataPtrSend(); ret->senderData = transPtr.p->clientData; ret->errorCode = UtilExecuteRef::TCError; ret->TCErrorCode = transPtr.p->errorCode; sendSignal(transPtr.p->clientRef, GSN_UTIL_EXECUTE_REF, signal, UtilExecuteRef::SignalLength, JBB); } else { struct LinearSectionPtr sectionsPtr[UtilExecuteReq::NoOfSections]; UtilExecuteConf * ret = (UtilExecuteConf *)signal->getDataPtrSend(); ret->senderData = transPtr.p->clientData; if (getResultSet(signal, transPtr.p, sectionsPtr)) { #if 0 //def EVENT_DEBUG for (int j = 0; j < 2; j++) { printf("Result set %u %u\n", j,sectionsPtr[j].sz); for (int i=0; i < sectionsPtr[j].sz; i++) printf("H'%.8x ", sectionsPtr[j].p[i]); printf("\n"); } #endif sendSignal(transPtr.p->clientRef, GSN_UTIL_EXECUTE_CONF, signal, UtilExecuteConf::SignalLength, JBB, sectionsPtr, UtilExecuteReq::NoOfSections); } else sendSignal(transPtr.p->clientRef, GSN_UTIL_EXECUTE_CONF, signal, UtilExecuteConf::SignalLength, JBB); } break; default: ndbrequire(0); break; } releaseTransaction(transPtr); } void DbUtil::execUTIL_LOCK_REQ(Signal * signal){ jamEntry(); UtilLockReq * req = (UtilLockReq*)signal->getDataPtr(); const Uint32 lockId = req->lockId; LockQueuePtr lockQPtr; if(!c_lockQueues.find(lockQPtr, lockId)){ jam(); sendLOCK_REF(signal, req, UtilLockRef::NoSuchLock); return; } // const Uint32 requestInfo = req->requestInfo; const Uint32 senderNode = refToNode(req->senderRef); if(senderNode != getOwnNodeId() && senderNode != 0){ jam(); sendLOCK_REF(signal, req, UtilLockRef::DistributedLockNotSupported); return; } LocalDLFifoList<LockQueueElement> queue(c_lockElementPool, lockQPtr.p->m_queue); if(req->requestInfo & UtilLockReq::TryLock && !queue.isEmpty()){ jam(); sendLOCK_REF(signal, req, UtilLockRef::LockAlreadyHeld); return; } LockQueueElementPtr lockEPtr; if(!c_lockElementPool.seize(lockEPtr)){ jam(); sendLOCK_REF(signal, req, UtilLockRef::OutOfLockRecords); return; } lockEPtr.p->m_senderRef = req->senderRef; lockEPtr.p->m_senderData = req->senderData; if(queue.isEmpty()){ jam(); sendLOCK_CONF(signal, lockQPtr.p, lockEPtr.p); } queue.add(lockEPtr); } void DbUtil::execUTIL_UNLOCK_REQ(Signal* signal){ jamEntry(); UtilUnlockReq * req = (UtilUnlockReq*)signal->getDataPtr(); const Uint32 lockId = req->lockId; LockQueuePtr lockQPtr; if(!c_lockQueues.find(lockQPtr, lockId)){ jam(); sendUNLOCK_REF(signal, req, UtilUnlockRef::NoSuchLock); return; } LocalDLFifoList<LockQueueElement> queue(c_lockElementPool, lockQPtr.p->m_queue); LockQueueElementPtr lockEPtr; if(!queue.first(lockEPtr)){ jam(); sendUNLOCK_REF(signal, req, UtilUnlockRef::NotLockOwner); return; } if(lockQPtr.p->m_lockKey != req->lockKey){ jam(); sendUNLOCK_REF(signal, req, UtilUnlockRef::NotLockOwner); return; } sendUNLOCK_CONF(signal, lockQPtr.p, lockEPtr.p); queue.release(lockEPtr); if(queue.first(lockEPtr)){ jam(); sendLOCK_CONF(signal, lockQPtr.p, lockEPtr.p); return; } } void DbUtil::sendLOCK_REF(Signal* signal, const UtilLockReq * req, UtilLockRef::ErrorCode err){ const Uint32 senderData = req->senderData; const Uint32 senderRef = req->senderRef; const Uint32 lockId = req->lockId; UtilLockRef * ref = (UtilLockRef*)signal->getDataPtrSend(); ref->senderData = senderData; ref->senderRef = reference(); ref->lockId = lockId; ref->errorCode = err; sendSignal(senderRef, GSN_UTIL_LOCK_REF, signal, UtilLockRef::SignalLength, JBB); } void DbUtil::sendLOCK_CONF(Signal* signal, LockQueue * lockQP, LockQueueElement * lockEP){ const Uint32 senderData = lockEP->m_senderData; const Uint32 senderRef = lockEP->m_senderRef; const Uint32 lockId = lockQP->m_lockId; const Uint32 lockKey = ++lockQP->m_lockKey; UtilLockConf * conf = (UtilLockConf*)signal->getDataPtrSend(); conf->senderData = senderData; conf->senderRef = reference(); conf->lockId = lockId; conf->lockKey = lockKey; sendSignal(senderRef, GSN_UTIL_LOCK_CONF, signal, UtilLockConf::SignalLength, JBB); } void DbUtil::sendUNLOCK_REF(Signal* signal, const UtilUnlockReq* req, UtilUnlockRef::ErrorCode err){ const Uint32 senderData = req->senderData; const Uint32 senderRef = req->senderRef; const Uint32 lockId = req->lockId; UtilUnlockRef * ref = (UtilUnlockRef*)signal->getDataPtrSend(); ref->senderData = senderData; ref->senderRef = reference(); ref->lockId = lockId; ref->errorCode = err; sendSignal(senderRef, GSN_UTIL_UNLOCK_REF, signal, UtilUnlockRef::SignalLength, JBB); } void DbUtil::sendUNLOCK_CONF(Signal* signal, LockQueue * lockQP, LockQueueElement * lockEP){ const Uint32 senderData = lockEP->m_senderData; const Uint32 senderRef = lockEP->m_senderRef; const Uint32 lockId = lockQP->m_lockId; ++lockQP->m_lockKey; UtilUnlockConf * conf = (UtilUnlockConf*)signal->getDataPtrSend(); conf->senderData = senderData; conf->senderRef = reference(); conf->lockId = lockId; sendSignal(senderRef, GSN_UTIL_UNLOCK_CONF, signal, UtilUnlockConf::SignalLength, JBB); } void DbUtil::execUTIL_CREATE_LOCK_REQ(Signal* signal){ jamEntry(); UtilCreateLockReq req = * (UtilCreateLockReq*)signal->getDataPtr(); UtilCreateLockRef::ErrorCode err = UtilCreateLockRef::OK; do { LockQueuePtr lockQPtr; if(c_lockQueues.find(lockQPtr, req.lockId)){ jam(); err = UtilCreateLockRef::LockIdAlreadyUsed; break; } if(req.lockType != UtilCreateLockReq::Mutex){ jam(); err = UtilCreateLockRef::UnsupportedLockType; break; } if(!c_lockQueues.seize(lockQPtr)){ jam(); err = UtilCreateLockRef::OutOfLockQueueRecords; break; } new (lockQPtr.p) LockQueue(req.lockId); c_lockQueues.add(lockQPtr); UtilCreateLockConf * conf = (UtilCreateLockConf*)signal->getDataPtrSend(); conf->senderData = req.senderData; conf->senderRef = reference(); conf->lockId = req.lockId; sendSignal(req.senderRef, GSN_UTIL_CREATE_LOCK_CONF, signal, UtilCreateLockConf::SignalLength, JBB); return; } while(false); UtilCreateLockRef * ref = (UtilCreateLockRef*)signal->getDataPtrSend(); ref->senderData = req.senderData; ref->senderRef = reference(); ref->lockId = req.lockId; ref->errorCode = err; sendSignal(req.senderRef, GSN_UTIL_CREATE_LOCK_REF, signal, UtilCreateLockRef::SignalLength, JBB); } void DbUtil::execUTIL_DESTORY_LOCK_REQ(Signal* signal){ jamEntry(); UtilDestroyLockReq req = * (UtilDestroyLockReq*)signal->getDataPtr(); UtilDestroyLockRef::ErrorCode err = UtilDestroyLockRef::OK; do { LockQueuePtr lockQPtr; if(!c_lockQueues.find(lockQPtr, req.lockId)){ jam(); err = UtilDestroyLockRef::NoSuchLock; break; } LocalDLFifoList<LockQueueElement> queue(c_lockElementPool, lockQPtr.p->m_queue); LockQueueElementPtr lockEPtr; if(!queue.first(lockEPtr)){ jam(); err = UtilDestroyLockRef::NotLockOwner; break; } if(lockQPtr.p->m_lockKey != req.lockKey){ jam(); err = UtilDestroyLockRef::NotLockOwner; break; } /** * OK */ // Inform all in lock queue that queue has been destroyed UtilLockRef * ref = (UtilLockRef*)signal->getDataPtrSend(); ref->lockId = req.lockId; ref->errorCode = UtilLockRef::NoSuchLock; ref->senderRef = reference(); LockQueueElementPtr loopPtr = lockEPtr; for(queue.next(loopPtr); !loopPtr.isNull(); queue.next(loopPtr)){ jam(); ref->senderData = loopPtr.p->m_senderData; const Uint32 senderRef = loopPtr.p->m_senderRef; sendSignal(senderRef, GSN_UTIL_LOCK_REF, signal, UtilLockRef::SignalLength, JBB); } queue.release(); c_lockQueues.release(lockQPtr); // Send Destroy conf UtilDestroyLockConf* conf=(UtilDestroyLockConf*)signal->getDataPtrSend(); conf->senderData = req.senderData; conf->senderRef = reference(); conf->lockId = req.lockId; sendSignal(req.senderRef, GSN_UTIL_DESTROY_LOCK_CONF, signal, UtilDestroyLockConf::SignalLength, JBB); return; } while(false); UtilDestroyLockRef * ref = (UtilDestroyLockRef*)signal->getDataPtrSend(); ref->senderData = req.senderData; ref->senderRef = reference(); ref->lockId = req.lockId; ref->errorCode = err; sendSignal(req.senderRef, GSN_UTIL_DESTROY_LOCK_REF, signal, UtilDestroyLockRef::SignalLength, JBB); } template class ArrayPool<DbUtil::Page32>;
SunguckLee/MariaDB
storage/ndb/src/kernel/blocks/dbutil/DbUtil.cpp
C++
gpl-2.0
81,659
// Copyright 2007, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Author: [email protected] (Zhanyong Wan) // Google Mock - a framework for writing C++ mock classes. // // This file implements some commonly used argument matchers. More // matchers can be defined by the user implementing the // MatcherInterface<T> interface if necessary. #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_ #define GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_ #include <math.h> #include <algorithm> #include <iterator> #include <limits> #include <ostream> // NOLINT #include <sstream> #include <string> #include <utility> #include <vector> #include "gmock/internal/gmock-internal-utils.h" #include "gmock/internal/gmock-port.h" #include "gtest/gtest.h" #if GTEST_HAS_STD_INITIALIZER_LIST_ # include <initializer_list> // NOLINT -- must be after gtest.h #endif namespace testing { // To implement a matcher Foo for type T, define: // 1. a class FooMatcherImpl that implements the // MatcherInterface<T> interface, and // 2. a factory function that creates a Matcher<T> object from a // FooMatcherImpl*. // // The two-level delegation design makes it possible to allow a user // to write "v" instead of "Eq(v)" where a Matcher is expected, which // is impossible if we pass matchers by pointers. It also eases // ownership management as Matcher objects can now be copied like // plain values. // MatchResultListener is an abstract class. Its << operator can be // used by a matcher to explain why a value matches or doesn't match. // // TODO([email protected]): add method // bool InterestedInWhy(bool result) const; // to indicate whether the listener is interested in why the match // result is 'result'. class MatchResultListener { public: // Creates a listener object with the given underlying ostream. The // listener does not own the ostream, and does not dereference it // in the constructor or destructor. explicit MatchResultListener(::std::ostream* os) : stream_(os) {} virtual ~MatchResultListener() = 0; // Makes this class abstract. // Streams x to the underlying ostream; does nothing if the ostream // is NULL. template <typename T> MatchResultListener& operator<<(const T& x) { if (stream_ != NULL) *stream_ << x; return *this; } // Returns the underlying ostream. ::std::ostream* stream() { return stream_; } // Returns true iff the listener is interested in an explanation of // the match result. A matcher's MatchAndExplain() method can use // this information to avoid generating the explanation when no one // intends to hear it. bool IsInterested() const { return stream_ != NULL; } private: ::std::ostream* const stream_; GTEST_DISALLOW_COPY_AND_ASSIGN_(MatchResultListener); }; inline MatchResultListener::~MatchResultListener() { } // An instance of a subclass of this knows how to describe itself as a // matcher. class MatcherDescriberInterface { public: virtual ~MatcherDescriberInterface() {} // Describes this matcher to an ostream. The function should print // a verb phrase that describes the property a value matching this // matcher should have. The subject of the verb phrase is the value // being matched. For example, the DescribeTo() method of the Gt(7) // matcher prints "is greater than 7". virtual void DescribeTo(::std::ostream* os) const = 0; // Describes the negation of this matcher to an ostream. For // example, if the description of this matcher is "is greater than // 7", the negated description could be "is not greater than 7". // You are not required to override this when implementing // MatcherInterface, but it is highly advised so that your matcher // can produce good error messages. virtual void DescribeNegationTo(::std::ostream* os) const { *os << "not ("; DescribeTo(os); *os << ")"; } }; // The implementation of a matcher. template <typename T> class MatcherInterface : public MatcherDescriberInterface { public: // Returns true iff the matcher matches x; also explains the match // result to 'listener' if necessary (see the next paragraph), in // the form of a non-restrictive relative clause ("which ...", // "whose ...", etc) that describes x. For example, the // MatchAndExplain() method of the Pointee(...) matcher should // generate an explanation like "which points to ...". // // Implementations of MatchAndExplain() should add an explanation of // the match result *if and only if* they can provide additional // information that's not already present (or not obvious) in the // print-out of x and the matcher's description. Whether the match // succeeds is not a factor in deciding whether an explanation is // needed, as sometimes the caller needs to print a failure message // when the match succeeds (e.g. when the matcher is used inside // Not()). // // For example, a "has at least 10 elements" matcher should explain // what the actual element count is, regardless of the match result, // as it is useful information to the reader; on the other hand, an // "is empty" matcher probably only needs to explain what the actual // size is when the match fails, as it's redundant to say that the // size is 0 when the value is already known to be empty. // // You should override this method when defining a new matcher. // // It's the responsibility of the caller (Google Mock) to guarantee // that 'listener' is not NULL. This helps to simplify a matcher's // implementation when it doesn't care about the performance, as it // can talk to 'listener' without checking its validity first. // However, in order to implement dummy listeners efficiently, // listener->stream() may be NULL. virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0; // Inherits these methods from MatcherDescriberInterface: // virtual void DescribeTo(::std::ostream* os) const = 0; // virtual void DescribeNegationTo(::std::ostream* os) const; }; // A match result listener that stores the explanation in a string. class StringMatchResultListener : public MatchResultListener { public: StringMatchResultListener() : MatchResultListener(&ss_) {} // Returns the explanation accumulated so far. internal::string str() const { return ss_.str(); } // Clears the explanation accumulated so far. void Clear() { ss_.str(""); } private: ::std::stringstream ss_; GTEST_DISALLOW_COPY_AND_ASSIGN_(StringMatchResultListener); }; namespace internal { // A match result listener that ignores the explanation. class DummyMatchResultListener : public MatchResultListener { public: DummyMatchResultListener() : MatchResultListener(NULL) {} private: GTEST_DISALLOW_COPY_AND_ASSIGN_(DummyMatchResultListener); }; // A match result listener that forwards the explanation to a given // ostream. The difference between this and MatchResultListener is // that the former is concrete. class StreamMatchResultListener : public MatchResultListener { public: explicit StreamMatchResultListener(::std::ostream* os) : MatchResultListener(os) {} private: GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamMatchResultListener); }; // An internal class for implementing Matcher<T>, which will derive // from it. We put functionalities common to all Matcher<T> // specializations here to avoid code duplication. template <typename T> class MatcherBase { public: // Returns true iff the matcher matches x; also explains the match // result to 'listener'. bool MatchAndExplain(T x, MatchResultListener* listener) const { return impl_->MatchAndExplain(x, listener); } // Returns true iff this matcher matches x. bool Matches(T x) const { DummyMatchResultListener dummy; return MatchAndExplain(x, &dummy); } // Describes this matcher to an ostream. void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); } // Describes the negation of this matcher to an ostream. void DescribeNegationTo(::std::ostream* os) const { impl_->DescribeNegationTo(os); } // Explains why x matches, or doesn't match, the matcher. void ExplainMatchResultTo(T x, ::std::ostream* os) const { StreamMatchResultListener listener(os); MatchAndExplain(x, &listener); } // Returns the describer for this matcher object; retains ownership // of the describer, which is only guaranteed to be alive when // this matcher object is alive. const MatcherDescriberInterface* GetDescriber() const { return impl_.get(); } protected: MatcherBase() {} // Constructs a matcher from its implementation. explicit MatcherBase(const MatcherInterface<T>* impl) : impl_(impl) {} virtual ~MatcherBase() {} private: // shared_ptr (util/gtl/shared_ptr.h) and linked_ptr have similar // interfaces. The former dynamically allocates a chunk of memory // to hold the reference count, while the latter tracks all // references using a circular linked list without allocating // memory. It has been observed that linked_ptr performs better in // typical scenarios. However, shared_ptr can out-perform // linked_ptr when there are many more uses of the copy constructor // than the default constructor. // // If performance becomes a problem, we should see if using // shared_ptr helps. ::testing::internal::linked_ptr<const MatcherInterface<T> > impl_; }; } // namespace internal // A Matcher<T> is a copyable and IMMUTABLE (except by assignment) // object that can check whether a value of type T matches. The // implementation of Matcher<T> is just a linked_ptr to const // MatcherInterface<T>, so copying is fairly cheap. Don't inherit // from Matcher! template <typename T> class Matcher : public internal::MatcherBase<T> { public: // Constructs a null matcher. Needed for storing Matcher objects in STL // containers. A default-constructed matcher is not yet initialized. You // cannot use it until a valid value has been assigned to it. Matcher() {} // Constructs a matcher from its implementation. explicit Matcher(const MatcherInterface<T>* impl) : internal::MatcherBase<T>(impl) {} // Implicit constructor here allows people to write // EXPECT_CALL(foo, Bar(5)) instead of EXPECT_CALL(foo, Bar(Eq(5))) sometimes Matcher(T value); // NOLINT }; // The following two specializations allow the user to write str // instead of Eq(str) and "foo" instead of Eq("foo") when a string // matcher is expected. template <> class GTEST_API_ Matcher<const internal::string&> : public internal::MatcherBase<const internal::string&> { public: Matcher() {} explicit Matcher(const MatcherInterface<const internal::string&>* impl) : internal::MatcherBase<const internal::string&>(impl) {} // Allows the user to write str instead of Eq(str) sometimes, where // str is a string object. Matcher(const internal::string& s); // NOLINT // Allows the user to write "foo" instead of Eq("foo") sometimes. Matcher(const char* s); // NOLINT }; template <> class GTEST_API_ Matcher<internal::string> : public internal::MatcherBase<internal::string> { public: Matcher() {} explicit Matcher(const MatcherInterface<internal::string>* impl) : internal::MatcherBase<internal::string>(impl) {} // Allows the user to write str instead of Eq(str) sometimes, where // str is a string object. Matcher(const internal::string& s); // NOLINT // Allows the user to write "foo" instead of Eq("foo") sometimes. Matcher(const char* s); // NOLINT }; #if GTEST_HAS_STRING_PIECE_ // The following two specializations allow the user to write str // instead of Eq(str) and "foo" instead of Eq("foo") when a StringPiece // matcher is expected. template <> class GTEST_API_ Matcher<const StringPiece&> : public internal::MatcherBase<const StringPiece&> { public: Matcher() {} explicit Matcher(const MatcherInterface<const StringPiece&>* impl) : internal::MatcherBase<const StringPiece&>(impl) {} // Allows the user to write str instead of Eq(str) sometimes, where // str is a string object. Matcher(const internal::string& s); // NOLINT // Allows the user to write "foo" instead of Eq("foo") sometimes. Matcher(const char* s); // NOLINT // Allows the user to pass StringPieces directly. Matcher(StringPiece s); // NOLINT }; template <> class GTEST_API_ Matcher<StringPiece> : public internal::MatcherBase<StringPiece> { public: Matcher() {} explicit Matcher(const MatcherInterface<StringPiece>* impl) : internal::MatcherBase<StringPiece>(impl) {} // Allows the user to write str instead of Eq(str) sometimes, where // str is a string object. Matcher(const internal::string& s); // NOLINT // Allows the user to write "foo" instead of Eq("foo") sometimes. Matcher(const char* s); // NOLINT // Allows the user to pass StringPieces directly. Matcher(StringPiece s); // NOLINT }; #endif // GTEST_HAS_STRING_PIECE_ // The PolymorphicMatcher class template makes it easy to implement a // polymorphic matcher (i.e. a matcher that can match values of more // than one type, e.g. Eq(n) and NotNull()). // // To define a polymorphic matcher, a user should provide an Impl // class that has a DescribeTo() method and a DescribeNegationTo() // method, and define a member function (or member function template) // // bool MatchAndExplain(const Value& value, // MatchResultListener* listener) const; // // See the definition of NotNull() for a complete example. template <class Impl> class PolymorphicMatcher { public: explicit PolymorphicMatcher(const Impl& an_impl) : impl_(an_impl) {} // Returns a mutable reference to the underlying matcher // implementation object. Impl& mutable_impl() { return impl_; } // Returns an immutable reference to the underlying matcher // implementation object. const Impl& impl() const { return impl_; } template <typename T> operator Matcher<T>() const { return Matcher<T>(new MonomorphicImpl<T>(impl_)); } private: template <typename T> class MonomorphicImpl : public MatcherInterface<T> { public: explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {} virtual void DescribeTo(::std::ostream* os) const { impl_.DescribeTo(os); } virtual void DescribeNegationTo(::std::ostream* os) const { impl_.DescribeNegationTo(os); } virtual bool MatchAndExplain(T x, MatchResultListener* listener) const { return impl_.MatchAndExplain(x, listener); } private: const Impl impl_; GTEST_DISALLOW_ASSIGN_(MonomorphicImpl); }; Impl impl_; GTEST_DISALLOW_ASSIGN_(PolymorphicMatcher); }; // Creates a matcher from its implementation. This is easier to use // than the Matcher<T> constructor as it doesn't require you to // explicitly write the template argument, e.g. // // MakeMatcher(foo); // vs // Matcher<const string&>(foo); template <typename T> inline Matcher<T> MakeMatcher(const MatcherInterface<T>* impl) { return Matcher<T>(impl); } // Creates a polymorphic matcher from its implementation. This is // easier to use than the PolymorphicMatcher<Impl> constructor as it // doesn't require you to explicitly write the template argument, e.g. // // MakePolymorphicMatcher(foo); // vs // PolymorphicMatcher<TypeOfFoo>(foo); template <class Impl> inline PolymorphicMatcher<Impl> MakePolymorphicMatcher(const Impl& impl) { return PolymorphicMatcher<Impl>(impl); } // Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION // and MUST NOT BE USED IN USER CODE!!! namespace internal { // The MatcherCastImpl class template is a helper for implementing // MatcherCast(). We need this helper in order to partially // specialize the implementation of MatcherCast() (C++ allows // class/struct templates to be partially specialized, but not // function templates.). // This general version is used when MatcherCast()'s argument is a // polymorphic matcher (i.e. something that can be converted to a // Matcher but is not one yet; for example, Eq(value)) or a value (for // example, "hello"). template <typename T, typename M> class MatcherCastImpl { public: static Matcher<T> Cast(const M& polymorphic_matcher_or_value) { // M can be a polymorhic matcher, in which case we want to use // its conversion operator to create Matcher<T>. Or it can be a value // that should be passed to the Matcher<T>'s constructor. // // We can't call Matcher<T>(polymorphic_matcher_or_value) when M is a // polymorphic matcher because it'll be ambiguous if T has an implicit // constructor from M (this usually happens when T has an implicit // constructor from any type). // // It won't work to unconditionally implict_cast // polymorphic_matcher_or_value to Matcher<T> because it won't trigger // a user-defined conversion from M to T if one exists (assuming M is // a value). return CastImpl( polymorphic_matcher_or_value, BooleanConstant< internal::ImplicitlyConvertible<M, Matcher<T> >::value>()); } private: static Matcher<T> CastImpl(const M& value, BooleanConstant<false>) { // M can't be implicitly converted to Matcher<T>, so M isn't a polymorphic // matcher. It must be a value then. Use direct initialization to create // a matcher. return Matcher<T>(ImplicitCast_<T>(value)); } static Matcher<T> CastImpl(const M& polymorphic_matcher_or_value, BooleanConstant<true>) { // M is implicitly convertible to Matcher<T>, which means that either // M is a polymorhpic matcher or Matcher<T> has an implicit constructor // from M. In both cases using the implicit conversion will produce a // matcher. // // Even if T has an implicit constructor from M, it won't be called because // creating Matcher<T> would require a chain of two user-defined conversions // (first to create T from M and then to create Matcher<T> from T). return polymorphic_matcher_or_value; } }; // This more specialized version is used when MatcherCast()'s argument // is already a Matcher. This only compiles when type T can be // statically converted to type U. template <typename T, typename U> class MatcherCastImpl<T, Matcher<U> > { public: static Matcher<T> Cast(const Matcher<U>& source_matcher) { return Matcher<T>(new Impl(source_matcher)); } private: class Impl : public MatcherInterface<T> { public: explicit Impl(const Matcher<U>& source_matcher) : source_matcher_(source_matcher) {} // We delegate the matching logic to the source matcher. virtual bool MatchAndExplain(T x, MatchResultListener* listener) const { return source_matcher_.MatchAndExplain(static_cast<U>(x), listener); } virtual void DescribeTo(::std::ostream* os) const { source_matcher_.DescribeTo(os); } virtual void DescribeNegationTo(::std::ostream* os) const { source_matcher_.DescribeNegationTo(os); } private: const Matcher<U> source_matcher_; GTEST_DISALLOW_ASSIGN_(Impl); }; }; // This even more specialized version is used for efficiently casting // a matcher to its own type. template <typename T> class MatcherCastImpl<T, Matcher<T> > { public: static Matcher<T> Cast(const Matcher<T>& matcher) { return matcher; } }; } // namespace internal // In order to be safe and clear, casting between different matcher // types is done explicitly via MatcherCast<T>(m), which takes a // matcher m and returns a Matcher<T>. It compiles only when T can be // statically converted to the argument type of m. template <typename T, typename M> inline Matcher<T> MatcherCast(const M& matcher) { return internal::MatcherCastImpl<T, M>::Cast(matcher); } // Implements SafeMatcherCast(). // // We use an intermediate class to do the actual safe casting as Nokia's // Symbian compiler cannot decide between // template <T, M> ... (M) and // template <T, U> ... (const Matcher<U>&) // for function templates but can for member function templates. template <typename T> class SafeMatcherCastImpl { public: // This overload handles polymorphic matchers and values only since // monomorphic matchers are handled by the next one. template <typename M> static inline Matcher<T> Cast(const M& polymorphic_matcher_or_value) { return internal::MatcherCastImpl<T, M>::Cast(polymorphic_matcher_or_value); } // This overload handles monomorphic matchers. // // In general, if type T can be implicitly converted to type U, we can // safely convert a Matcher<U> to a Matcher<T> (i.e. Matcher is // contravariant): just keep a copy of the original Matcher<U>, convert the // argument from type T to U, and then pass it to the underlying Matcher<U>. // The only exception is when U is a reference and T is not, as the // underlying Matcher<U> may be interested in the argument's address, which // is not preserved in the conversion from T to U. template <typename U> static inline Matcher<T> Cast(const Matcher<U>& matcher) { // Enforce that T can be implicitly converted to U. GTEST_COMPILE_ASSERT_((internal::ImplicitlyConvertible<T, U>::value), T_must_be_implicitly_convertible_to_U); // Enforce that we are not converting a non-reference type T to a reference // type U. GTEST_COMPILE_ASSERT_( internal::is_reference<T>::value || !internal::is_reference<U>::value, cannot_convert_non_referentce_arg_to_reference); // In case both T and U are arithmetic types, enforce that the // conversion is not lossy. typedef GTEST_REMOVE_REFERENCE_AND_CONST_(T) RawT; typedef GTEST_REMOVE_REFERENCE_AND_CONST_(U) RawU; const bool kTIsOther = GMOCK_KIND_OF_(RawT) == internal::kOther; const bool kUIsOther = GMOCK_KIND_OF_(RawU) == internal::kOther; GTEST_COMPILE_ASSERT_( kTIsOther || kUIsOther || (internal::LosslessArithmeticConvertible<RawT, RawU>::value), conversion_of_arithmetic_types_must_be_lossless); return MatcherCast<T>(matcher); } }; template <typename T, typename M> inline Matcher<T> SafeMatcherCast(const M& polymorphic_matcher) { return SafeMatcherCastImpl<T>::Cast(polymorphic_matcher); } // A<T>() returns a matcher that matches any value of type T. template <typename T> Matcher<T> A(); // Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION // and MUST NOT BE USED IN USER CODE!!! namespace internal { // If the explanation is not empty, prints it to the ostream. inline void PrintIfNotEmpty(const internal::string& explanation, ::std::ostream* os) { if (explanation != "" && os != NULL) { *os << ", " << explanation; } } // Returns true if the given type name is easy to read by a human. // This is used to decide whether printing the type of a value might // be helpful. inline bool IsReadableTypeName(const string& type_name) { // We consider a type name readable if it's short or doesn't contain // a template or function type. return (type_name.length() <= 20 || type_name.find_first_of("<(") == string::npos); } // Matches the value against the given matcher, prints the value and explains // the match result to the listener. Returns the match result. // 'listener' must not be NULL. // Value cannot be passed by const reference, because some matchers take a // non-const argument. template <typename Value, typename T> bool MatchPrintAndExplain(Value& value, const Matcher<T>& matcher, MatchResultListener* listener) { if (!listener->IsInterested()) { // If the listener is not interested, we do not need to construct the // inner explanation. return matcher.Matches(value); } StringMatchResultListener inner_listener; const bool match = matcher.MatchAndExplain(value, &inner_listener); UniversalPrint(value, listener->stream()); #if GTEST_HAS_RTTI const string& type_name = GetTypeName<Value>(); if (IsReadableTypeName(type_name)) *listener->stream() << " (of type " << type_name << ")"; #endif PrintIfNotEmpty(inner_listener.str(), listener->stream()); return match; } // An internal helper class for doing compile-time loop on a tuple's // fields. template <size_t N> class TuplePrefix { public: // TuplePrefix<N>::Matches(matcher_tuple, value_tuple) returns true // iff the first N fields of matcher_tuple matches the first N // fields of value_tuple, respectively. template <typename MatcherTuple, typename ValueTuple> static bool Matches(const MatcherTuple& matcher_tuple, const ValueTuple& value_tuple) { return TuplePrefix<N - 1>::Matches(matcher_tuple, value_tuple) && get<N - 1>(matcher_tuple).Matches(get<N - 1>(value_tuple)); } // TuplePrefix<N>::ExplainMatchFailuresTo(matchers, values, os) // describes failures in matching the first N fields of matchers // against the first N fields of values. If there is no failure, // nothing will be streamed to os. template <typename MatcherTuple, typename ValueTuple> static void ExplainMatchFailuresTo(const MatcherTuple& matchers, const ValueTuple& values, ::std::ostream* os) { // First, describes failures in the first N - 1 fields. TuplePrefix<N - 1>::ExplainMatchFailuresTo(matchers, values, os); // Then describes the failure (if any) in the (N - 1)-th (0-based) // field. typename tuple_element<N - 1, MatcherTuple>::type matcher = get<N - 1>(matchers); typedef typename tuple_element<N - 1, ValueTuple>::type Value; Value value = get<N - 1>(values); StringMatchResultListener listener; if (!matcher.MatchAndExplain(value, &listener)) { // TODO(wan): include in the message the name of the parameter // as used in MOCK_METHOD*() when possible. *os << " Expected arg #" << N - 1 << ": "; get<N - 1>(matchers).DescribeTo(os); *os << "\n Actual: "; // We remove the reference in type Value to prevent the // universal printer from printing the address of value, which // isn't interesting to the user most of the time. The // matcher's MatchAndExplain() method handles the case when // the address is interesting. internal::UniversalPrint(value, os); PrintIfNotEmpty(listener.str(), os); *os << "\n"; } } }; // The base case. template <> class TuplePrefix<0> { public: template <typename MatcherTuple, typename ValueTuple> static bool Matches(const MatcherTuple& /* matcher_tuple */, const ValueTuple& /* value_tuple */) { return true; } template <typename MatcherTuple, typename ValueTuple> static void ExplainMatchFailuresTo(const MatcherTuple& /* matchers */, const ValueTuple& /* values */, ::std::ostream* /* os */) {} }; // TupleMatches(matcher_tuple, value_tuple) returns true iff all // matchers in matcher_tuple match the corresponding fields in // value_tuple. It is a compiler error if matcher_tuple and // value_tuple have different number of fields or incompatible field // types. template <typename MatcherTuple, typename ValueTuple> bool TupleMatches(const MatcherTuple& matcher_tuple, const ValueTuple& value_tuple) { // Makes sure that matcher_tuple and value_tuple have the same // number of fields. GTEST_COMPILE_ASSERT_(tuple_size<MatcherTuple>::value == tuple_size<ValueTuple>::value, matcher_and_value_have_different_numbers_of_fields); return TuplePrefix<tuple_size<ValueTuple>::value>:: Matches(matcher_tuple, value_tuple); } // Describes failures in matching matchers against values. If there // is no failure, nothing will be streamed to os. template <typename MatcherTuple, typename ValueTuple> void ExplainMatchFailureTupleTo(const MatcherTuple& matchers, const ValueTuple& values, ::std::ostream* os) { TuplePrefix<tuple_size<MatcherTuple>::value>::ExplainMatchFailuresTo( matchers, values, os); } // TransformTupleValues and its helper. // // TransformTupleValuesHelper hides the internal machinery that // TransformTupleValues uses to implement a tuple traversal. template <typename Tuple, typename Func, typename OutIter> class TransformTupleValuesHelper { private: typedef ::testing::tuple_size<Tuple> TupleSize; public: // For each member of tuple 't', taken in order, evaluates '*out++ = f(t)'. // Returns the final value of 'out' in case the caller needs it. static OutIter Run(Func f, const Tuple& t, OutIter out) { return IterateOverTuple<Tuple, TupleSize::value>()(f, t, out); } private: template <typename Tup, size_t kRemainingSize> struct IterateOverTuple { OutIter operator() (Func f, const Tup& t, OutIter out) const { *out++ = f(::testing::get<TupleSize::value - kRemainingSize>(t)); return IterateOverTuple<Tup, kRemainingSize - 1>()(f, t, out); } }; template <typename Tup> struct IterateOverTuple<Tup, 0> { OutIter operator() (Func /* f */, const Tup& /* t */, OutIter out) const { return out; } }; }; // Successively invokes 'f(element)' on each element of the tuple 't', // appending each result to the 'out' iterator. Returns the final value // of 'out'. template <typename Tuple, typename Func, typename OutIter> OutIter TransformTupleValues(Func f, const Tuple& t, OutIter out) { return TransformTupleValuesHelper<Tuple, Func, OutIter>::Run(f, t, out); } // Implements A<T>(). template <typename T> class AnyMatcherImpl : public MatcherInterface<T> { public: virtual bool MatchAndExplain( T /* x */, MatchResultListener* /* listener */) const { return true; } virtual void DescribeTo(::std::ostream* os) const { *os << "is anything"; } virtual void DescribeNegationTo(::std::ostream* os) const { // This is mostly for completeness' safe, as it's not very useful // to write Not(A<bool>()). However we cannot completely rule out // such a possibility, and it doesn't hurt to be prepared. *os << "never matches"; } }; // Implements _, a matcher that matches any value of any // type. This is a polymorphic matcher, so we need a template type // conversion operator to make it appearing as a Matcher<T> for any // type T. class AnythingMatcher { public: template <typename T> operator Matcher<T>() const { return A<T>(); } }; // Implements a matcher that compares a given value with a // pre-supplied value using one of the ==, <=, <, etc, operators. The // two values being compared don't have to have the same type. // // The matcher defined here is polymorphic (for example, Eq(5) can be // used to match an int, a short, a double, etc). Therefore we use // a template type conversion operator in the implementation. // // We define this as a macro in order to eliminate duplicated source // code. // // The following template definition assumes that the Rhs parameter is // a "bare" type (i.e. neither 'const T' nor 'T&'). #define GMOCK_IMPLEMENT_COMPARISON_MATCHER_( \ name, op, relation, negated_relation) \ template <typename Rhs> class name##Matcher { \ public: \ explicit name##Matcher(const Rhs& rhs) : rhs_(rhs) {} \ template <typename Lhs> \ operator Matcher<Lhs>() const { \ return MakeMatcher(new Impl<Lhs>(rhs_)); \ } \ private: \ template <typename Lhs> \ class Impl : public MatcherInterface<Lhs> { \ public: \ explicit Impl(const Rhs& rhs) : rhs_(rhs) {} \ virtual bool MatchAndExplain(\ Lhs lhs, MatchResultListener* /* listener */) const { \ return lhs op rhs_; \ } \ virtual void DescribeTo(::std::ostream* os) const { \ *os << relation " "; \ UniversalPrint(rhs_, os); \ } \ virtual void DescribeNegationTo(::std::ostream* os) const { \ *os << negated_relation " "; \ UniversalPrint(rhs_, os); \ } \ private: \ Rhs rhs_; \ GTEST_DISALLOW_ASSIGN_(Impl); \ }; \ Rhs rhs_; \ GTEST_DISALLOW_ASSIGN_(name##Matcher); \ } // Implements Eq(v), Ge(v), Gt(v), Le(v), Lt(v), and Ne(v) // respectively. GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Eq, ==, "is equal to", "isn't equal to"); GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Ge, >=, "is >=", "isn't >="); GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Gt, >, "is >", "isn't >"); GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Le, <=, "is <=", "isn't <="); GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Lt, <, "is <", "isn't <"); GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Ne, !=, "isn't equal to", "is equal to"); #undef GMOCK_IMPLEMENT_COMPARISON_MATCHER_ // Implements the polymorphic IsNull() matcher, which matches any raw or smart // pointer that is NULL. class IsNullMatcher { public: template <typename Pointer> bool MatchAndExplain(const Pointer& p, MatchResultListener* /* listener */) const { return GetRawPointer(p) == NULL; } void DescribeTo(::std::ostream* os) const { *os << "is NULL"; } void DescribeNegationTo(::std::ostream* os) const { *os << "isn't NULL"; } }; // Implements the polymorphic NotNull() matcher, which matches any raw or smart // pointer that is not NULL. class NotNullMatcher { public: template <typename Pointer> bool MatchAndExplain(const Pointer& p, MatchResultListener* /* listener */) const { return GetRawPointer(p) != NULL; } void DescribeTo(::std::ostream* os) const { *os << "isn't NULL"; } void DescribeNegationTo(::std::ostream* os) const { *os << "is NULL"; } }; // Ref(variable) matches any argument that is a reference to // 'variable'. This matcher is polymorphic as it can match any // super type of the type of 'variable'. // // The RefMatcher template class implements Ref(variable). It can // only be instantiated with a reference type. This prevents a user // from mistakenly using Ref(x) to match a non-reference function // argument. For example, the following will righteously cause a // compiler error: // // int n; // Matcher<int> m1 = Ref(n); // This won't compile. // Matcher<int&> m2 = Ref(n); // This will compile. template <typename T> class RefMatcher; template <typename T> class RefMatcher<T&> { // Google Mock is a generic framework and thus needs to support // mocking any function types, including those that take non-const // reference arguments. Therefore the template parameter T (and // Super below) can be instantiated to either a const type or a // non-const type. public: // RefMatcher() takes a T& instead of const T&, as we want the // compiler to catch using Ref(const_value) as a matcher for a // non-const reference. explicit RefMatcher(T& x) : object_(x) {} // NOLINT template <typename Super> operator Matcher<Super&>() const { // By passing object_ (type T&) to Impl(), which expects a Super&, // we make sure that Super is a super type of T. In particular, // this catches using Ref(const_value) as a matcher for a // non-const reference, as you cannot implicitly convert a const // reference to a non-const reference. return MakeMatcher(new Impl<Super>(object_)); } private: template <typename Super> class Impl : public MatcherInterface<Super&> { public: explicit Impl(Super& x) : object_(x) {} // NOLINT // MatchAndExplain() takes a Super& (as opposed to const Super&) // in order to match the interface MatcherInterface<Super&>. virtual bool MatchAndExplain( Super& x, MatchResultListener* listener) const { *listener << "which is located @" << static_cast<const void*>(&x); return &x == &object_; } virtual void DescribeTo(::std::ostream* os) const { *os << "references the variable "; UniversalPrinter<Super&>::Print(object_, os); } virtual void DescribeNegationTo(::std::ostream* os) const { *os << "does not reference the variable "; UniversalPrinter<Super&>::Print(object_, os); } private: const Super& object_; GTEST_DISALLOW_ASSIGN_(Impl); }; T& object_; GTEST_DISALLOW_ASSIGN_(RefMatcher); }; // Polymorphic helper functions for narrow and wide string matchers. inline bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) { return String::CaseInsensitiveCStringEquals(lhs, rhs); } inline bool CaseInsensitiveCStringEquals(const wchar_t* lhs, const wchar_t* rhs) { return String::CaseInsensitiveWideCStringEquals(lhs, rhs); } // String comparison for narrow or wide strings that can have embedded NUL // characters. template <typename StringType> bool CaseInsensitiveStringEquals(const StringType& s1, const StringType& s2) { // Are the heads equal? if (!CaseInsensitiveCStringEquals(s1.c_str(), s2.c_str())) { return false; } // Skip the equal heads. const typename StringType::value_type nul = 0; const size_t i1 = s1.find(nul), i2 = s2.find(nul); // Are we at the end of either s1 or s2? if (i1 == StringType::npos || i2 == StringType::npos) { return i1 == i2; } // Are the tails equal? return CaseInsensitiveStringEquals(s1.substr(i1 + 1), s2.substr(i2 + 1)); } // String matchers. // Implements equality-based string matchers like StrEq, StrCaseNe, and etc. template <typename StringType> class StrEqualityMatcher { public: StrEqualityMatcher(const StringType& str, bool expect_eq, bool case_sensitive) : string_(str), expect_eq_(expect_eq), case_sensitive_(case_sensitive) {} // Accepts pointer types, particularly: // const char* // char* // const wchar_t* // wchar_t* template <typename CharType> bool MatchAndExplain(CharType* s, MatchResultListener* listener) const { if (s == NULL) { return !expect_eq_; } return MatchAndExplain(StringType(s), listener); } // Matches anything that can convert to StringType. // // This is a template, not just a plain function with const StringType&, // because StringPiece has some interfering non-explicit constructors. template <typename MatcheeStringType> bool MatchAndExplain(const MatcheeStringType& s, MatchResultListener* /* listener */) const { const StringType& s2(s); const bool eq = case_sensitive_ ? s2 == string_ : CaseInsensitiveStringEquals(s2, string_); return expect_eq_ == eq; } void DescribeTo(::std::ostream* os) const { DescribeToHelper(expect_eq_, os); } void DescribeNegationTo(::std::ostream* os) const { DescribeToHelper(!expect_eq_, os); } private: void DescribeToHelper(bool expect_eq, ::std::ostream* os) const { *os << (expect_eq ? "is " : "isn't "); *os << "equal to "; if (!case_sensitive_) { *os << "(ignoring case) "; } UniversalPrint(string_, os); } const StringType string_; const bool expect_eq_; const bool case_sensitive_; GTEST_DISALLOW_ASSIGN_(StrEqualityMatcher); }; // Implements the polymorphic HasSubstr(substring) matcher, which // can be used as a Matcher<T> as long as T can be converted to a // string. template <typename StringType> class HasSubstrMatcher { public: explicit HasSubstrMatcher(const StringType& substring) : substring_(substring) {} // Accepts pointer types, particularly: // const char* // char* // const wchar_t* // wchar_t* template <typename CharType> bool MatchAndExplain(CharType* s, MatchResultListener* listener) const { return s != NULL && MatchAndExplain(StringType(s), listener); } // Matches anything that can convert to StringType. // // This is a template, not just a plain function with const StringType&, // because StringPiece has some interfering non-explicit constructors. template <typename MatcheeStringType> bool MatchAndExplain(const MatcheeStringType& s, MatchResultListener* /* listener */) const { const StringType& s2(s); return s2.find(substring_) != StringType::npos; } // Describes what this matcher matches. void DescribeTo(::std::ostream* os) const { *os << "has substring "; UniversalPrint(substring_, os); } void DescribeNegationTo(::std::ostream* os) const { *os << "has no substring "; UniversalPrint(substring_, os); } private: const StringType substring_; GTEST_DISALLOW_ASSIGN_(HasSubstrMatcher); }; // Implements the polymorphic StartsWith(substring) matcher, which // can be used as a Matcher<T> as long as T can be converted to a // string. template <typename StringType> class StartsWithMatcher { public: explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) { } // Accepts pointer types, particularly: // const char* // char* // const wchar_t* // wchar_t* template <typename CharType> bool MatchAndExplain(CharType* s, MatchResultListener* listener) const { return s != NULL && MatchAndExplain(StringType(s), listener); } // Matches anything that can convert to StringType. // // This is a template, not just a plain function with const StringType&, // because StringPiece has some interfering non-explicit constructors. template <typename MatcheeStringType> bool MatchAndExplain(const MatcheeStringType& s, MatchResultListener* /* listener */) const { const StringType& s2(s); return s2.length() >= prefix_.length() && s2.substr(0, prefix_.length()) == prefix_; } void DescribeTo(::std::ostream* os) const { *os << "starts with "; UniversalPrint(prefix_, os); } void DescribeNegationTo(::std::ostream* os) const { *os << "doesn't start with "; UniversalPrint(prefix_, os); } private: const StringType prefix_; GTEST_DISALLOW_ASSIGN_(StartsWithMatcher); }; // Implements the polymorphic EndsWith(substring) matcher, which // can be used as a Matcher<T> as long as T can be converted to a // string. template <typename StringType> class EndsWithMatcher { public: explicit EndsWithMatcher(const StringType& suffix) : suffix_(suffix) {} // Accepts pointer types, particularly: // const char* // char* // const wchar_t* // wchar_t* template <typename CharType> bool MatchAndExplain(CharType* s, MatchResultListener* listener) const { return s != NULL && MatchAndExplain(StringType(s), listener); } // Matches anything that can convert to StringType. // // This is a template, not just a plain function with const StringType&, // because StringPiece has some interfering non-explicit constructors. template <typename MatcheeStringType> bool MatchAndExplain(const MatcheeStringType& s, MatchResultListener* /* listener */) const { const StringType& s2(s); return s2.length() >= suffix_.length() && s2.substr(s2.length() - suffix_.length()) == suffix_; } void DescribeTo(::std::ostream* os) const { *os << "ends with "; UniversalPrint(suffix_, os); } void DescribeNegationTo(::std::ostream* os) const { *os << "doesn't end with "; UniversalPrint(suffix_, os); } private: const StringType suffix_; GTEST_DISALLOW_ASSIGN_(EndsWithMatcher); }; // Implements polymorphic matchers MatchesRegex(regex) and // ContainsRegex(regex), which can be used as a Matcher<T> as long as // T can be converted to a string. class MatchesRegexMatcher { public: MatchesRegexMatcher(const RE* regex, bool full_match) : regex_(regex), full_match_(full_match) {} // Accepts pointer types, particularly: // const char* // char* // const wchar_t* // wchar_t* template <typename CharType> bool MatchAndExplain(CharType* s, MatchResultListener* listener) const { return s != NULL && MatchAndExplain(internal::string(s), listener); } // Matches anything that can convert to internal::string. // // This is a template, not just a plain function with const internal::string&, // because StringPiece has some interfering non-explicit constructors. template <class MatcheeStringType> bool MatchAndExplain(const MatcheeStringType& s, MatchResultListener* /* listener */) const { const internal::string& s2(s); return full_match_ ? RE::FullMatch(s2, *regex_) : RE::PartialMatch(s2, *regex_); } void DescribeTo(::std::ostream* os) const { *os << (full_match_ ? "matches" : "contains") << " regular expression "; UniversalPrinter<internal::string>::Print(regex_->pattern(), os); } void DescribeNegationTo(::std::ostream* os) const { *os << "doesn't " << (full_match_ ? "match" : "contain") << " regular expression "; UniversalPrinter<internal::string>::Print(regex_->pattern(), os); } private: const internal::linked_ptr<const RE> regex_; const bool full_match_; GTEST_DISALLOW_ASSIGN_(MatchesRegexMatcher); }; // Implements a matcher that compares the two fields of a 2-tuple // using one of the ==, <=, <, etc, operators. The two fields being // compared don't have to have the same type. // // The matcher defined here is polymorphic (for example, Eq() can be // used to match a tuple<int, short>, a tuple<const long&, double>, // etc). Therefore we use a template type conversion operator in the // implementation. // // We define this as a macro in order to eliminate duplicated source // code. #define GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(name, op, relation) \ class name##2Matcher { \ public: \ template <typename T1, typename T2> \ operator Matcher< ::testing::tuple<T1, T2> >() const { \ return MakeMatcher(new Impl< ::testing::tuple<T1, T2> >); \ } \ template <typename T1, typename T2> \ operator Matcher<const ::testing::tuple<T1, T2>&>() const { \ return MakeMatcher(new Impl<const ::testing::tuple<T1, T2>&>); \ } \ private: \ template <typename Tuple> \ class Impl : public MatcherInterface<Tuple> { \ public: \ virtual bool MatchAndExplain( \ Tuple args, \ MatchResultListener* /* listener */) const { \ return ::testing::get<0>(args) op ::testing::get<1>(args); \ } \ virtual void DescribeTo(::std::ostream* os) const { \ *os << "are " relation; \ } \ virtual void DescribeNegationTo(::std::ostream* os) const { \ *os << "aren't " relation; \ } \ }; \ } // Implements Eq(), Ge(), Gt(), Le(), Lt(), and Ne() respectively. GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Eq, ==, "an equal pair"); GMOCK_IMPLEMENT_COMPARISON2_MATCHER_( Ge, >=, "a pair where the first >= the second"); GMOCK_IMPLEMENT_COMPARISON2_MATCHER_( Gt, >, "a pair where the first > the second"); GMOCK_IMPLEMENT_COMPARISON2_MATCHER_( Le, <=, "a pair where the first <= the second"); GMOCK_IMPLEMENT_COMPARISON2_MATCHER_( Lt, <, "a pair where the first < the second"); GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Ne, !=, "an unequal pair"); #undef GMOCK_IMPLEMENT_COMPARISON2_MATCHER_ // Implements the Not(...) matcher for a particular argument type T. // We do not nest it inside the NotMatcher class template, as that // will prevent different instantiations of NotMatcher from sharing // the same NotMatcherImpl<T> class. template <typename T> class NotMatcherImpl : public MatcherInterface<T> { public: explicit NotMatcherImpl(const Matcher<T>& matcher) : matcher_(matcher) {} virtual bool MatchAndExplain(T x, MatchResultListener* listener) const { return !matcher_.MatchAndExplain(x, listener); } virtual void DescribeTo(::std::ostream* os) const { matcher_.DescribeNegationTo(os); } virtual void DescribeNegationTo(::std::ostream* os) const { matcher_.DescribeTo(os); } private: const Matcher<T> matcher_; GTEST_DISALLOW_ASSIGN_(NotMatcherImpl); }; // Implements the Not(m) matcher, which matches a value that doesn't // match matcher m. template <typename InnerMatcher> class NotMatcher { public: explicit NotMatcher(InnerMatcher matcher) : matcher_(matcher) {} // This template type conversion operator allows Not(m) to be used // to match any type m can match. template <typename T> operator Matcher<T>() const { return Matcher<T>(new NotMatcherImpl<T>(SafeMatcherCast<T>(matcher_))); } private: InnerMatcher matcher_; GTEST_DISALLOW_ASSIGN_(NotMatcher); }; // Implements the AllOf(m1, m2) matcher for a particular argument type // T. We do not nest it inside the BothOfMatcher class template, as // that will prevent different instantiations of BothOfMatcher from // sharing the same BothOfMatcherImpl<T> class. template <typename T> class BothOfMatcherImpl : public MatcherInterface<T> { public: BothOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2) : matcher1_(matcher1), matcher2_(matcher2) {} virtual void DescribeTo(::std::ostream* os) const { *os << "("; matcher1_.DescribeTo(os); *os << ") and ("; matcher2_.DescribeTo(os); *os << ")"; } virtual void DescribeNegationTo(::std::ostream* os) const { *os << "("; matcher1_.DescribeNegationTo(os); *os << ") or ("; matcher2_.DescribeNegationTo(os); *os << ")"; } virtual bool MatchAndExplain(T x, MatchResultListener* listener) const { // If either matcher1_ or matcher2_ doesn't match x, we only need // to explain why one of them fails. StringMatchResultListener listener1; if (!matcher1_.MatchAndExplain(x, &listener1)) { *listener << listener1.str(); return false; } StringMatchResultListener listener2; if (!matcher2_.MatchAndExplain(x, &listener2)) { *listener << listener2.str(); return false; } // Otherwise we need to explain why *both* of them match. const internal::string s1 = listener1.str(); const internal::string s2 = listener2.str(); if (s1 == "") { *listener << s2; } else { *listener << s1; if (s2 != "") { *listener << ", and " << s2; } } return true; } private: const Matcher<T> matcher1_; const Matcher<T> matcher2_; GTEST_DISALLOW_ASSIGN_(BothOfMatcherImpl); }; #if GTEST_LANG_CXX11 // MatcherList provides mechanisms for storing a variable number of matchers in // a list structure (ListType) and creating a combining matcher from such a // list. // The template is defined recursively using the following template paramters: // * kSize is the length of the MatcherList. // * Head is the type of the first matcher of the list. // * Tail denotes the types of the remaining matchers of the list. template <int kSize, typename Head, typename... Tail> struct MatcherList { typedef MatcherList<kSize - 1, Tail...> MatcherListTail; typedef ::std::pair<Head, typename MatcherListTail::ListType> ListType; // BuildList stores variadic type values in a nested pair structure. // Example: // MatcherList<3, int, string, float>::BuildList(5, "foo", 2.0) will return // the corresponding result of type pair<int, pair<string, float>>. static ListType BuildList(const Head& matcher, const Tail&... tail) { return ListType(matcher, MatcherListTail::BuildList(tail...)); } // CreateMatcher<T> creates a Matcher<T> from a given list of matchers (built // by BuildList()). CombiningMatcher<T> is used to combine the matchers of the // list. CombiningMatcher<T> must implement MatcherInterface<T> and have a // constructor taking two Matcher<T>s as input. template <typename T, template <typename /* T */> class CombiningMatcher> static Matcher<T> CreateMatcher(const ListType& matchers) { return Matcher<T>(new CombiningMatcher<T>( SafeMatcherCast<T>(matchers.first), MatcherListTail::template CreateMatcher<T, CombiningMatcher>( matchers.second))); } }; // The following defines the base case for the recursive definition of // MatcherList. template <typename Matcher1, typename Matcher2> struct MatcherList<2, Matcher1, Matcher2> { typedef ::std::pair<Matcher1, Matcher2> ListType; static ListType BuildList(const Matcher1& matcher1, const Matcher2& matcher2) { return ::std::pair<Matcher1, Matcher2>(matcher1, matcher2); } template <typename T, template <typename /* T */> class CombiningMatcher> static Matcher<T> CreateMatcher(const ListType& matchers) { return Matcher<T>(new CombiningMatcher<T>( SafeMatcherCast<T>(matchers.first), SafeMatcherCast<T>(matchers.second))); } }; // VariadicMatcher is used for the variadic implementation of // AllOf(m_1, m_2, ...) and AnyOf(m_1, m_2, ...). // CombiningMatcher<T> is used to recursively combine the provided matchers // (of type Args...). template <template <typename T> class CombiningMatcher, typename... Args> class VariadicMatcher { public: VariadicMatcher(const Args&... matchers) // NOLINT : matchers_(MatcherListType::BuildList(matchers...)) {} // This template type conversion operator allows an // VariadicMatcher<Matcher1, Matcher2...> object to match any type that // all of the provided matchers (Matcher1, Matcher2, ...) can match. template <typename T> operator Matcher<T>() const { return MatcherListType::template CreateMatcher<T, CombiningMatcher>( matchers_); } private: typedef MatcherList<sizeof...(Args), Args...> MatcherListType; const typename MatcherListType::ListType matchers_; GTEST_DISALLOW_ASSIGN_(VariadicMatcher); }; template <typename... Args> using AllOfMatcher = VariadicMatcher<BothOfMatcherImpl, Args...>; #endif // GTEST_LANG_CXX11 // Used for implementing the AllOf(m_1, ..., m_n) matcher, which // matches a value that matches all of the matchers m_1, ..., and m_n. template <typename Matcher1, typename Matcher2> class BothOfMatcher { public: BothOfMatcher(Matcher1 matcher1, Matcher2 matcher2) : matcher1_(matcher1), matcher2_(matcher2) {} // This template type conversion operator allows a // BothOfMatcher<Matcher1, Matcher2> object to match any type that // both Matcher1 and Matcher2 can match. template <typename T> operator Matcher<T>() const { return Matcher<T>(new BothOfMatcherImpl<T>(SafeMatcherCast<T>(matcher1_), SafeMatcherCast<T>(matcher2_))); } private: Matcher1 matcher1_; Matcher2 matcher2_; GTEST_DISALLOW_ASSIGN_(BothOfMatcher); }; // Implements the AnyOf(m1, m2) matcher for a particular argument type // T. We do not nest it inside the AnyOfMatcher class template, as // that will prevent different instantiations of AnyOfMatcher from // sharing the same EitherOfMatcherImpl<T> class. template <typename T> class EitherOfMatcherImpl : public MatcherInterface<T> { public: EitherOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2) : matcher1_(matcher1), matcher2_(matcher2) {} virtual void DescribeTo(::std::ostream* os) const { *os << "("; matcher1_.DescribeTo(os); *os << ") or ("; matcher2_.DescribeTo(os); *os << ")"; } virtual void DescribeNegationTo(::std::ostream* os) const { *os << "("; matcher1_.DescribeNegationTo(os); *os << ") and ("; matcher2_.DescribeNegationTo(os); *os << ")"; } virtual bool MatchAndExplain(T x, MatchResultListener* listener) const { // If either matcher1_ or matcher2_ matches x, we just need to // explain why *one* of them matches. StringMatchResultListener listener1; if (matcher1_.MatchAndExplain(x, &listener1)) { *listener << listener1.str(); return true; } StringMatchResultListener listener2; if (matcher2_.MatchAndExplain(x, &listener2)) { *listener << listener2.str(); return true; } // Otherwise we need to explain why *both* of them fail. const internal::string s1 = listener1.str(); const internal::string s2 = listener2.str(); if (s1 == "") { *listener << s2; } else { *listener << s1; if (s2 != "") { *listener << ", and " << s2; } } return false; } private: const Matcher<T> matcher1_; const Matcher<T> matcher2_; GTEST_DISALLOW_ASSIGN_(EitherOfMatcherImpl); }; #if GTEST_LANG_CXX11 // AnyOfMatcher is used for the variadic implementation of AnyOf(m_1, m_2, ...). template <typename... Args> using AnyOfMatcher = VariadicMatcher<EitherOfMatcherImpl, Args...>; #endif // GTEST_LANG_CXX11 // Used for implementing the AnyOf(m_1, ..., m_n) matcher, which // matches a value that matches at least one of the matchers m_1, ..., // and m_n. template <typename Matcher1, typename Matcher2> class EitherOfMatcher { public: EitherOfMatcher(Matcher1 matcher1, Matcher2 matcher2) : matcher1_(matcher1), matcher2_(matcher2) {} // This template type conversion operator allows a // EitherOfMatcher<Matcher1, Matcher2> object to match any type that // both Matcher1 and Matcher2 can match. template <typename T> operator Matcher<T>() const { return Matcher<T>(new EitherOfMatcherImpl<T>( SafeMatcherCast<T>(matcher1_), SafeMatcherCast<T>(matcher2_))); } private: Matcher1 matcher1_; Matcher2 matcher2_; GTEST_DISALLOW_ASSIGN_(EitherOfMatcher); }; // Used for implementing Truly(pred), which turns a predicate into a // matcher. template <typename Predicate> class TrulyMatcher { public: explicit TrulyMatcher(Predicate pred) : predicate_(pred) {} // This method template allows Truly(pred) to be used as a matcher // for type T where T is the argument type of predicate 'pred'. The // argument is passed by reference as the predicate may be // interested in the address of the argument. template <typename T> bool MatchAndExplain(T& x, // NOLINT MatchResultListener* /* listener */) const { // Without the if-statement, MSVC sometimes warns about converting // a value to bool (warning 4800). // // We cannot write 'return !!predicate_(x);' as that doesn't work // when predicate_(x) returns a class convertible to bool but // having no operator!(). if (predicate_(x)) return true; return false; } void DescribeTo(::std::ostream* os) const { *os << "satisfies the given predicate"; } void DescribeNegationTo(::std::ostream* os) const { *os << "doesn't satisfy the given predicate"; } private: Predicate predicate_; GTEST_DISALLOW_ASSIGN_(TrulyMatcher); }; // Used for implementing Matches(matcher), which turns a matcher into // a predicate. template <typename M> class MatcherAsPredicate { public: explicit MatcherAsPredicate(M matcher) : matcher_(matcher) {} // This template operator() allows Matches(m) to be used as a // predicate on type T where m is a matcher on type T. // // The argument x is passed by reference instead of by value, as // some matcher may be interested in its address (e.g. as in // Matches(Ref(n))(x)). template <typename T> bool operator()(const T& x) const { // We let matcher_ commit to a particular type here instead of // when the MatcherAsPredicate object was constructed. This // allows us to write Matches(m) where m is a polymorphic matcher // (e.g. Eq(5)). // // If we write Matcher<T>(matcher_).Matches(x) here, it won't // compile when matcher_ has type Matcher<const T&>; if we write // Matcher<const T&>(matcher_).Matches(x) here, it won't compile // when matcher_ has type Matcher<T>; if we just write // matcher_.Matches(x), it won't compile when matcher_ is // polymorphic, e.g. Eq(5). // // MatcherCast<const T&>() is necessary for making the code work // in all of the above situations. return MatcherCast<const T&>(matcher_).Matches(x); } private: M matcher_; GTEST_DISALLOW_ASSIGN_(MatcherAsPredicate); }; // For implementing ASSERT_THAT() and EXPECT_THAT(). The template // argument M must be a type that can be converted to a matcher. template <typename M> class PredicateFormatterFromMatcher { public: explicit PredicateFormatterFromMatcher(const M& m) : matcher_(m) {} // This template () operator allows a PredicateFormatterFromMatcher // object to act as a predicate-formatter suitable for using with // Google Test's EXPECT_PRED_FORMAT1() macro. template <typename T> AssertionResult operator()(const char* value_text, const T& x) const { // We convert matcher_ to a Matcher<const T&> *now* instead of // when the PredicateFormatterFromMatcher object was constructed, // as matcher_ may be polymorphic (e.g. NotNull()) and we won't // know which type to instantiate it to until we actually see the // type of x here. // // We write SafeMatcherCast<const T&>(matcher_) instead of // Matcher<const T&>(matcher_), as the latter won't compile when // matcher_ has type Matcher<T> (e.g. An<int>()). // We don't write MatcherCast<const T&> either, as that allows // potentially unsafe downcasting of the matcher argument. const Matcher<const T&> matcher = SafeMatcherCast<const T&>(matcher_); StringMatchResultListener listener; if (MatchPrintAndExplain(x, matcher, &listener)) return AssertionSuccess(); ::std::stringstream ss; ss << "Value of: " << value_text << "\n" << "Expected: "; matcher.DescribeTo(&ss); ss << "\n Actual: " << listener.str(); return AssertionFailure() << ss.str(); } private: const M matcher_; GTEST_DISALLOW_ASSIGN_(PredicateFormatterFromMatcher); }; // A helper function for converting a matcher to a predicate-formatter // without the user needing to explicitly write the type. This is // used for implementing ASSERT_THAT() and EXPECT_THAT(). template <typename M> inline PredicateFormatterFromMatcher<M> MakePredicateFormatterFromMatcher(const M& matcher) { return PredicateFormatterFromMatcher<M>(matcher); } // Implements the polymorphic floating point equality matcher, which matches // two float values using ULP-based approximation or, optionally, a // user-specified epsilon. The template is meant to be instantiated with // FloatType being either float or double. template <typename FloatType> class FloatingEqMatcher { public: // Constructor for FloatingEqMatcher. // The matcher's input will be compared with rhs. The matcher treats two // NANs as equal if nan_eq_nan is true. Otherwise, under IEEE standards, // equality comparisons between NANs will always return false. We specify a // negative max_abs_error_ term to indicate that ULP-based approximation will // be used for comparison. FloatingEqMatcher(FloatType rhs, bool nan_eq_nan) : rhs_(rhs), nan_eq_nan_(nan_eq_nan), max_abs_error_(-1) { } // Constructor that supports a user-specified max_abs_error that will be used // for comparison instead of ULP-based approximation. The max absolute // should be non-negative. FloatingEqMatcher(FloatType rhs, bool nan_eq_nan, FloatType max_abs_error) : rhs_(rhs), nan_eq_nan_(nan_eq_nan), max_abs_error_(max_abs_error) { GTEST_CHECK_(max_abs_error >= 0) << ", where max_abs_error is" << max_abs_error; } // Implements floating point equality matcher as a Matcher<T>. template <typename T> class Impl : public MatcherInterface<T> { public: Impl(FloatType rhs, bool nan_eq_nan, FloatType max_abs_error) : rhs_(rhs), nan_eq_nan_(nan_eq_nan), max_abs_error_(max_abs_error) {} virtual bool MatchAndExplain(T value, MatchResultListener* /* listener */) const { const FloatingPoint<FloatType> lhs(value), rhs(rhs_); // Compares NaNs first, if nan_eq_nan_ is true. if (lhs.is_nan() || rhs.is_nan()) { if (lhs.is_nan() && rhs.is_nan()) { return nan_eq_nan_; } // One is nan; the other is not nan. return false; } if (HasMaxAbsError()) { // We perform an equality check so that inf will match inf, regardless // of error bounds. If the result of value - rhs_ would result in // overflow or if either value is inf, the default result is infinity, // which should only match if max_abs_error_ is also infinity. return value == rhs_ || fabs(value - rhs_) <= max_abs_error_; } else { return lhs.AlmostEquals(rhs); } } virtual void DescribeTo(::std::ostream* os) const { // os->precision() returns the previously set precision, which we // store to restore the ostream to its original configuration // after outputting. const ::std::streamsize old_precision = os->precision( ::std::numeric_limits<FloatType>::digits10 + 2); if (FloatingPoint<FloatType>(rhs_).is_nan()) { if (nan_eq_nan_) { *os << "is NaN"; } else { *os << "never matches"; } } else { *os << "is approximately " << rhs_; if (HasMaxAbsError()) { *os << " (absolute error <= " << max_abs_error_ << ")"; } } os->precision(old_precision); } virtual void DescribeNegationTo(::std::ostream* os) const { // As before, get original precision. const ::std::streamsize old_precision = os->precision( ::std::numeric_limits<FloatType>::digits10 + 2); if (FloatingPoint<FloatType>(rhs_).is_nan()) { if (nan_eq_nan_) { *os << "isn't NaN"; } else { *os << "is anything"; } } else { *os << "isn't approximately " << rhs_; if (HasMaxAbsError()) { *os << " (absolute error > " << max_abs_error_ << ")"; } } // Restore original precision. os->precision(old_precision); } private: bool HasMaxAbsError() const { return max_abs_error_ >= 0; } const FloatType rhs_; const bool nan_eq_nan_; // max_abs_error will be used for value comparison when >= 0. const FloatType max_abs_error_; GTEST_DISALLOW_ASSIGN_(Impl); }; // The following 3 type conversion operators allow FloatEq(rhs) and // NanSensitiveFloatEq(rhs) to be used as a Matcher<float>, a // Matcher<const float&>, or a Matcher<float&>, but nothing else. // (While Google's C++ coding style doesn't allow arguments passed // by non-const reference, we may see them in code not conforming to // the style. Therefore Google Mock needs to support them.) operator Matcher<FloatType>() const { return MakeMatcher(new Impl<FloatType>(rhs_, nan_eq_nan_, max_abs_error_)); } operator Matcher<const FloatType&>() const { return MakeMatcher( new Impl<const FloatType&>(rhs_, nan_eq_nan_, max_abs_error_)); } operator Matcher<FloatType&>() const { return MakeMatcher(new Impl<FloatType&>(rhs_, nan_eq_nan_, max_abs_error_)); } private: const FloatType rhs_; const bool nan_eq_nan_; // max_abs_error will be used for value comparison when >= 0. const FloatType max_abs_error_; GTEST_DISALLOW_ASSIGN_(FloatingEqMatcher); }; // Implements the Pointee(m) matcher for matching a pointer whose // pointee matches matcher m. The pointer can be either raw or smart. template <typename InnerMatcher> class PointeeMatcher { public: explicit PointeeMatcher(const InnerMatcher& matcher) : matcher_(matcher) {} // This type conversion operator template allows Pointee(m) to be // used as a matcher for any pointer type whose pointee type is // compatible with the inner matcher, where type Pointer can be // either a raw pointer or a smart pointer. // // The reason we do this instead of relying on // MakePolymorphicMatcher() is that the latter is not flexible // enough for implementing the DescribeTo() method of Pointee(). template <typename Pointer> operator Matcher<Pointer>() const { return MakeMatcher(new Impl<Pointer>(matcher_)); } private: // The monomorphic implementation that works for a particular pointer type. template <typename Pointer> class Impl : public MatcherInterface<Pointer> { public: typedef typename PointeeOf<GTEST_REMOVE_CONST_( // NOLINT GTEST_REMOVE_REFERENCE_(Pointer))>::type Pointee; explicit Impl(const InnerMatcher& matcher) : matcher_(MatcherCast<const Pointee&>(matcher)) {} virtual void DescribeTo(::std::ostream* os) const { *os << "points to a value that "; matcher_.DescribeTo(os); } virtual void DescribeNegationTo(::std::ostream* os) const { *os << "does not point to a value that "; matcher_.DescribeTo(os); } virtual bool MatchAndExplain(Pointer pointer, MatchResultListener* listener) const { if (GetRawPointer(pointer) == NULL) return false; *listener << "which points to "; return MatchPrintAndExplain(*pointer, matcher_, listener); } private: const Matcher<const Pointee&> matcher_; GTEST_DISALLOW_ASSIGN_(Impl); }; const InnerMatcher matcher_; GTEST_DISALLOW_ASSIGN_(PointeeMatcher); }; // Implements the Field() matcher for matching a field (i.e. member // variable) of an object. template <typename Class, typename FieldType> class FieldMatcher { public: FieldMatcher(FieldType Class::*field, const Matcher<const FieldType&>& matcher) : field_(field), matcher_(matcher) {} void DescribeTo(::std::ostream* os) const { *os << "is an object whose given field "; matcher_.DescribeTo(os); } void DescribeNegationTo(::std::ostream* os) const { *os << "is an object whose given field "; matcher_.DescribeNegationTo(os); } template <typename T> bool MatchAndExplain(const T& value, MatchResultListener* listener) const { return MatchAndExplainImpl( typename ::testing::internal:: is_pointer<GTEST_REMOVE_CONST_(T)>::type(), value, listener); } private: // The first argument of MatchAndExplainImpl() is needed to help // Symbian's C++ compiler choose which overload to use. Its type is // true_type iff the Field() matcher is used to match a pointer. bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj, MatchResultListener* listener) const { *listener << "whose given field is "; return MatchPrintAndExplain(obj.*field_, matcher_, listener); } bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p, MatchResultListener* listener) const { if (p == NULL) return false; *listener << "which points to an object "; // Since *p has a field, it must be a class/struct/union type and // thus cannot be a pointer. Therefore we pass false_type() as // the first argument. return MatchAndExplainImpl(false_type(), *p, listener); } const FieldType Class::*field_; const Matcher<const FieldType&> matcher_; GTEST_DISALLOW_ASSIGN_(FieldMatcher); }; // Implements the Property() matcher for matching a property // (i.e. return value of a getter method) of an object. template <typename Class, typename PropertyType> class PropertyMatcher { public: // The property may have a reference type, so 'const PropertyType&' // may cause double references and fail to compile. That's why we // need GTEST_REFERENCE_TO_CONST, which works regardless of // PropertyType being a reference or not. typedef GTEST_REFERENCE_TO_CONST_(PropertyType) RefToConstProperty; PropertyMatcher(PropertyType (Class::*property)() const, const Matcher<RefToConstProperty>& matcher) : property_(property), matcher_(matcher) {} void DescribeTo(::std::ostream* os) const { *os << "is an object whose given property "; matcher_.DescribeTo(os); } void DescribeNegationTo(::std::ostream* os) const { *os << "is an object whose given property "; matcher_.DescribeNegationTo(os); } template <typename T> bool MatchAndExplain(const T&value, MatchResultListener* listener) const { return MatchAndExplainImpl( typename ::testing::internal:: is_pointer<GTEST_REMOVE_CONST_(T)>::type(), value, listener); } private: // The first argument of MatchAndExplainImpl() is needed to help // Symbian's C++ compiler choose which overload to use. Its type is // true_type iff the Property() matcher is used to match a pointer. bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj, MatchResultListener* listener) const { *listener << "whose given property is "; // Cannot pass the return value (for example, int) to MatchPrintAndExplain, // which takes a non-const reference as argument. RefToConstProperty result = (obj.*property_)(); return MatchPrintAndExplain(result, matcher_, listener); } bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p, MatchResultListener* listener) const { if (p == NULL) return false; *listener << "which points to an object "; // Since *p has a property method, it must be a class/struct/union // type and thus cannot be a pointer. Therefore we pass // false_type() as the first argument. return MatchAndExplainImpl(false_type(), *p, listener); } PropertyType (Class::*property_)() const; const Matcher<RefToConstProperty> matcher_; GTEST_DISALLOW_ASSIGN_(PropertyMatcher); }; // Type traits specifying various features of different functors for ResultOf. // The default template specifies features for functor objects. // Functor classes have to typedef argument_type and result_type // to be compatible with ResultOf. template <typename Functor> struct CallableTraits { typedef typename Functor::result_type ResultType; typedef Functor StorageType; static void CheckIsValid(Functor /* functor */) {} template <typename T> static ResultType Invoke(Functor f, T arg) { return f(arg); } }; // Specialization for function pointers. template <typename ArgType, typename ResType> struct CallableTraits<ResType(*)(ArgType)> { typedef ResType ResultType; typedef ResType(*StorageType)(ArgType); static void CheckIsValid(ResType(*f)(ArgType)) { GTEST_CHECK_(f != NULL) << "NULL function pointer is passed into ResultOf()."; } template <typename T> static ResType Invoke(ResType(*f)(ArgType), T arg) { return (*f)(arg); } }; // Implements the ResultOf() matcher for matching a return value of a // unary function of an object. template <typename Callable> class ResultOfMatcher { public: typedef typename CallableTraits<Callable>::ResultType ResultType; ResultOfMatcher(Callable callable, const Matcher<ResultType>& matcher) : callable_(callable), matcher_(matcher) { CallableTraits<Callable>::CheckIsValid(callable_); } template <typename T> operator Matcher<T>() const { return Matcher<T>(new Impl<T>(callable_, matcher_)); } private: typedef typename CallableTraits<Callable>::StorageType CallableStorageType; template <typename T> class Impl : public MatcherInterface<T> { public: Impl(CallableStorageType callable, const Matcher<ResultType>& matcher) : callable_(callable), matcher_(matcher) {} virtual void DescribeTo(::std::ostream* os) const { *os << "is mapped by the given callable to a value that "; matcher_.DescribeTo(os); } virtual void DescribeNegationTo(::std::ostream* os) const { *os << "is mapped by the given callable to a value that "; matcher_.DescribeNegationTo(os); } virtual bool MatchAndExplain(T obj, MatchResultListener* listener) const { *listener << "which is mapped by the given callable to "; // Cannot pass the return value (for example, int) to // MatchPrintAndExplain, which takes a non-const reference as argument. ResultType result = CallableTraits<Callable>::template Invoke<T>(callable_, obj); return MatchPrintAndExplain(result, matcher_, listener); } private: // Functors often define operator() as non-const method even though // they are actualy stateless. But we need to use them even when // 'this' is a const pointer. It's the user's responsibility not to // use stateful callables with ResultOf(), which does't guarantee // how many times the callable will be invoked. mutable CallableStorageType callable_; const Matcher<ResultType> matcher_; GTEST_DISALLOW_ASSIGN_(Impl); }; // class Impl const CallableStorageType callable_; const Matcher<ResultType> matcher_; GTEST_DISALLOW_ASSIGN_(ResultOfMatcher); }; // Implements a matcher that checks the size of an STL-style container. template <typename SizeMatcher> class SizeIsMatcher { public: explicit SizeIsMatcher(const SizeMatcher& size_matcher) : size_matcher_(size_matcher) { } template <typename Container> operator Matcher<Container>() const { return MakeMatcher(new Impl<Container>(size_matcher_)); } template <typename Container> class Impl : public MatcherInterface<Container> { public: typedef internal::StlContainerView< GTEST_REMOVE_REFERENCE_AND_CONST_(Container)> ContainerView; typedef typename ContainerView::type::size_type SizeType; explicit Impl(const SizeMatcher& size_matcher) : size_matcher_(MatcherCast<SizeType>(size_matcher)) {} virtual void DescribeTo(::std::ostream* os) const { *os << "size "; size_matcher_.DescribeTo(os); } virtual void DescribeNegationTo(::std::ostream* os) const { *os << "size "; size_matcher_.DescribeNegationTo(os); } virtual bool MatchAndExplain(Container container, MatchResultListener* listener) const { SizeType size = container.size(); StringMatchResultListener size_listener; const bool result = size_matcher_.MatchAndExplain(size, &size_listener); *listener << "whose size " << size << (result ? " matches" : " doesn't match"); PrintIfNotEmpty(size_listener.str(), listener->stream()); return result; } private: const Matcher<SizeType> size_matcher_; GTEST_DISALLOW_ASSIGN_(Impl); }; private: const SizeMatcher size_matcher_; GTEST_DISALLOW_ASSIGN_(SizeIsMatcher); }; // Implements a matcher that checks the begin()..end() distance of an STL-style // container. template <typename DistanceMatcher> class BeginEndDistanceIsMatcher { public: explicit BeginEndDistanceIsMatcher(const DistanceMatcher& distance_matcher) : distance_matcher_(distance_matcher) {} template <typename Container> operator Matcher<Container>() const { return MakeMatcher(new Impl<Container>(distance_matcher_)); } template <typename Container> class Impl : public MatcherInterface<Container> { public: typedef internal::StlContainerView< GTEST_REMOVE_REFERENCE_AND_CONST_(Container)> ContainerView; typedef typename std::iterator_traits< typename ContainerView::type::const_iterator>::difference_type DistanceType; explicit Impl(const DistanceMatcher& distance_matcher) : distance_matcher_(MatcherCast<DistanceType>(distance_matcher)) {} virtual void DescribeTo(::std::ostream* os) const { *os << "distance between begin() and end() "; distance_matcher_.DescribeTo(os); } virtual void DescribeNegationTo(::std::ostream* os) const { *os << "distance between begin() and end() "; distance_matcher_.DescribeNegationTo(os); } virtual bool MatchAndExplain(Container container, MatchResultListener* listener) const { #if GTEST_LANG_CXX11 using std::begin; using std::end; DistanceType distance = std::distance(begin(container), end(container)); #else DistanceType distance = std::distance(container.begin(), container.end()); #endif StringMatchResultListener distance_listener; const bool result = distance_matcher_.MatchAndExplain(distance, &distance_listener); *listener << "whose distance between begin() and end() " << distance << (result ? " matches" : " doesn't match"); PrintIfNotEmpty(distance_listener.str(), listener->stream()); return result; } private: const Matcher<DistanceType> distance_matcher_; GTEST_DISALLOW_ASSIGN_(Impl); }; private: const DistanceMatcher distance_matcher_; GTEST_DISALLOW_ASSIGN_(BeginEndDistanceIsMatcher); }; // Implements an equality matcher for any STL-style container whose elements // support ==. This matcher is like Eq(), but its failure explanations provide // more detailed information that is useful when the container is used as a set. // The failure message reports elements that are in one of the operands but not // the other. The failure messages do not report duplicate or out-of-order // elements in the containers (which don't properly matter to sets, but can // occur if the containers are vectors or lists, for example). // // Uses the container's const_iterator, value_type, operator ==, // begin(), and end(). template <typename Container> class ContainerEqMatcher { public: typedef internal::StlContainerView<Container> View; typedef typename View::type StlContainer; typedef typename View::const_reference StlContainerReference; // We make a copy of rhs in case the elements in it are modified // after this matcher is created. explicit ContainerEqMatcher(const Container& rhs) : rhs_(View::Copy(rhs)) { // Makes sure the user doesn't instantiate this class template // with a const or reference type. (void)testing::StaticAssertTypeEq<Container, GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>(); } void DescribeTo(::std::ostream* os) const { *os << "equals "; UniversalPrint(rhs_, os); } void DescribeNegationTo(::std::ostream* os) const { *os << "does not equal "; UniversalPrint(rhs_, os); } template <typename LhsContainer> bool MatchAndExplain(const LhsContainer& lhs, MatchResultListener* listener) const { // GTEST_REMOVE_CONST_() is needed to work around an MSVC 8.0 bug // that causes LhsContainer to be a const type sometimes. typedef internal::StlContainerView<GTEST_REMOVE_CONST_(LhsContainer)> LhsView; typedef typename LhsView::type LhsStlContainer; StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs); if (lhs_stl_container == rhs_) return true; ::std::ostream* const os = listener->stream(); if (os != NULL) { // Something is different. Check for extra values first. bool printed_header = false; for (typename LhsStlContainer::const_iterator it = lhs_stl_container.begin(); it != lhs_stl_container.end(); ++it) { if (internal::ArrayAwareFind(rhs_.begin(), rhs_.end(), *it) == rhs_.end()) { if (printed_header) { *os << ", "; } else { *os << "which has these unexpected elements: "; printed_header = true; } UniversalPrint(*it, os); } } // Now check for missing values. bool printed_header2 = false; for (typename StlContainer::const_iterator it = rhs_.begin(); it != rhs_.end(); ++it) { if (internal::ArrayAwareFind( lhs_stl_container.begin(), lhs_stl_container.end(), *it) == lhs_stl_container.end()) { if (printed_header2) { *os << ", "; } else { *os << (printed_header ? ",\nand" : "which") << " doesn't have these expected elements: "; printed_header2 = true; } UniversalPrint(*it, os); } } } return false; } private: const StlContainer rhs_; GTEST_DISALLOW_ASSIGN_(ContainerEqMatcher); }; // A comparator functor that uses the < operator to compare two values. struct LessComparator { template <typename T, typename U> bool operator()(const T& lhs, const U& rhs) const { return lhs < rhs; } }; // Implements WhenSortedBy(comparator, container_matcher). template <typename Comparator, typename ContainerMatcher> class WhenSortedByMatcher { public: WhenSortedByMatcher(const Comparator& comparator, const ContainerMatcher& matcher) : comparator_(comparator), matcher_(matcher) {} template <typename LhsContainer> operator Matcher<LhsContainer>() const { return MakeMatcher(new Impl<LhsContainer>(comparator_, matcher_)); } template <typename LhsContainer> class Impl : public MatcherInterface<LhsContainer> { public: typedef internal::StlContainerView< GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView; typedef typename LhsView::type LhsStlContainer; typedef typename LhsView::const_reference LhsStlContainerReference; // Transforms std::pair<const Key, Value> into std::pair<Key, Value> // so that we can match associative containers. typedef typename RemoveConstFromKey< typename LhsStlContainer::value_type>::type LhsValue; Impl(const Comparator& comparator, const ContainerMatcher& matcher) : comparator_(comparator), matcher_(matcher) {} virtual void DescribeTo(::std::ostream* os) const { *os << "(when sorted) "; matcher_.DescribeTo(os); } virtual void DescribeNegationTo(::std::ostream* os) const { *os << "(when sorted) "; matcher_.DescribeNegationTo(os); } virtual bool MatchAndExplain(LhsContainer lhs, MatchResultListener* listener) const { LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs); ::std::vector<LhsValue> sorted_container(lhs_stl_container.begin(), lhs_stl_container.end()); ::std::sort( sorted_container.begin(), sorted_container.end(), comparator_); if (!listener->IsInterested()) { // If the listener is not interested, we do not need to // construct the inner explanation. return matcher_.Matches(sorted_container); } *listener << "which is "; UniversalPrint(sorted_container, listener->stream()); *listener << " when sorted"; StringMatchResultListener inner_listener; const bool match = matcher_.MatchAndExplain(sorted_container, &inner_listener); PrintIfNotEmpty(inner_listener.str(), listener->stream()); return match; } private: const Comparator comparator_; const Matcher<const ::std::vector<LhsValue>&> matcher_; GTEST_DISALLOW_COPY_AND_ASSIGN_(Impl); }; private: const Comparator comparator_; const ContainerMatcher matcher_; GTEST_DISALLOW_ASSIGN_(WhenSortedByMatcher); }; // Implements Pointwise(tuple_matcher, rhs_container). tuple_matcher // must be able to be safely cast to Matcher<tuple<const T1&, const // T2&> >, where T1 and T2 are the types of elements in the LHS // container and the RHS container respectively. template <typename TupleMatcher, typename RhsContainer> class PointwiseMatcher { public: typedef internal::StlContainerView<RhsContainer> RhsView; typedef typename RhsView::type RhsStlContainer; typedef typename RhsStlContainer::value_type RhsValue; // Like ContainerEq, we make a copy of rhs in case the elements in // it are modified after this matcher is created. PointwiseMatcher(const TupleMatcher& tuple_matcher, const RhsContainer& rhs) : tuple_matcher_(tuple_matcher), rhs_(RhsView::Copy(rhs)) { // Makes sure the user doesn't instantiate this class template // with a const or reference type. (void)testing::StaticAssertTypeEq<RhsContainer, GTEST_REMOVE_REFERENCE_AND_CONST_(RhsContainer)>(); } template <typename LhsContainer> operator Matcher<LhsContainer>() const { return MakeMatcher(new Impl<LhsContainer>(tuple_matcher_, rhs_)); } template <typename LhsContainer> class Impl : public MatcherInterface<LhsContainer> { public: typedef internal::StlContainerView< GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView; typedef typename LhsView::type LhsStlContainer; typedef typename LhsView::const_reference LhsStlContainerReference; typedef typename LhsStlContainer::value_type LhsValue; // We pass the LHS value and the RHS value to the inner matcher by // reference, as they may be expensive to copy. We must use tuple // instead of pair here, as a pair cannot hold references (C++ 98, // 20.2.2 [lib.pairs]). typedef ::testing::tuple<const LhsValue&, const RhsValue&> InnerMatcherArg; Impl(const TupleMatcher& tuple_matcher, const RhsStlContainer& rhs) // mono_tuple_matcher_ holds a monomorphic version of the tuple matcher. : mono_tuple_matcher_(SafeMatcherCast<InnerMatcherArg>(tuple_matcher)), rhs_(rhs) {} virtual void DescribeTo(::std::ostream* os) const { *os << "contains " << rhs_.size() << " values, where each value and its corresponding value in "; UniversalPrinter<RhsStlContainer>::Print(rhs_, os); *os << " "; mono_tuple_matcher_.DescribeTo(os); } virtual void DescribeNegationTo(::std::ostream* os) const { *os << "doesn't contain exactly " << rhs_.size() << " values, or contains a value x at some index i" << " where x and the i-th value of "; UniversalPrint(rhs_, os); *os << " "; mono_tuple_matcher_.DescribeNegationTo(os); } virtual bool MatchAndExplain(LhsContainer lhs, MatchResultListener* listener) const { LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs); const size_t actual_size = lhs_stl_container.size(); if (actual_size != rhs_.size()) { *listener << "which contains " << actual_size << " values"; return false; } typename LhsStlContainer::const_iterator left = lhs_stl_container.begin(); typename RhsStlContainer::const_iterator right = rhs_.begin(); for (size_t i = 0; i != actual_size; ++i, ++left, ++right) { const InnerMatcherArg value_pair(*left, *right); if (listener->IsInterested()) { StringMatchResultListener inner_listener; if (!mono_tuple_matcher_.MatchAndExplain( value_pair, &inner_listener)) { *listener << "where the value pair ("; UniversalPrint(*left, listener->stream()); *listener << ", "; UniversalPrint(*right, listener->stream()); *listener << ") at index #" << i << " don't match"; PrintIfNotEmpty(inner_listener.str(), listener->stream()); return false; } } else { if (!mono_tuple_matcher_.Matches(value_pair)) return false; } } return true; } private: const Matcher<InnerMatcherArg> mono_tuple_matcher_; const RhsStlContainer rhs_; GTEST_DISALLOW_ASSIGN_(Impl); }; private: const TupleMatcher tuple_matcher_; const RhsStlContainer rhs_; GTEST_DISALLOW_ASSIGN_(PointwiseMatcher); }; // Holds the logic common to ContainsMatcherImpl and EachMatcherImpl. template <typename Container> class QuantifierMatcherImpl : public MatcherInterface<Container> { public: typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer; typedef StlContainerView<RawContainer> View; typedef typename View::type StlContainer; typedef typename View::const_reference StlContainerReference; typedef typename StlContainer::value_type Element; template <typename InnerMatcher> explicit QuantifierMatcherImpl(InnerMatcher inner_matcher) : inner_matcher_( testing::SafeMatcherCast<const Element&>(inner_matcher)) {} // Checks whether: // * All elements in the container match, if all_elements_should_match. // * Any element in the container matches, if !all_elements_should_match. bool MatchAndExplainImpl(bool all_elements_should_match, Container container, MatchResultListener* listener) const { StlContainerReference stl_container = View::ConstReference(container); size_t i = 0; for (typename StlContainer::const_iterator it = stl_container.begin(); it != stl_container.end(); ++it, ++i) { StringMatchResultListener inner_listener; const bool matches = inner_matcher_.MatchAndExplain(*it, &inner_listener); if (matches != all_elements_should_match) { *listener << "whose element #" << i << (matches ? " matches" : " doesn't match"); PrintIfNotEmpty(inner_listener.str(), listener->stream()); return !all_elements_should_match; } } return all_elements_should_match; } protected: const Matcher<const Element&> inner_matcher_; GTEST_DISALLOW_ASSIGN_(QuantifierMatcherImpl); }; // Implements Contains(element_matcher) for the given argument type Container. // Symmetric to EachMatcherImpl. template <typename Container> class ContainsMatcherImpl : public QuantifierMatcherImpl<Container> { public: template <typename InnerMatcher> explicit ContainsMatcherImpl(InnerMatcher inner_matcher) : QuantifierMatcherImpl<Container>(inner_matcher) {} // Describes what this matcher does. virtual void DescribeTo(::std::ostream* os) const { *os << "contains at least one element that "; this->inner_matcher_.DescribeTo(os); } virtual void DescribeNegationTo(::std::ostream* os) const { *os << "doesn't contain any element that "; this->inner_matcher_.DescribeTo(os); } virtual bool MatchAndExplain(Container container, MatchResultListener* listener) const { return this->MatchAndExplainImpl(false, container, listener); } private: GTEST_DISALLOW_ASSIGN_(ContainsMatcherImpl); }; // Implements Each(element_matcher) for the given argument type Container. // Symmetric to ContainsMatcherImpl. template <typename Container> class EachMatcherImpl : public QuantifierMatcherImpl<Container> { public: template <typename InnerMatcher> explicit EachMatcherImpl(InnerMatcher inner_matcher) : QuantifierMatcherImpl<Container>(inner_matcher) {} // Describes what this matcher does. virtual void DescribeTo(::std::ostream* os) const { *os << "only contains elements that "; this->inner_matcher_.DescribeTo(os); } virtual void DescribeNegationTo(::std::ostream* os) const { *os << "contains some element that "; this->inner_matcher_.DescribeNegationTo(os); } virtual bool MatchAndExplain(Container container, MatchResultListener* listener) const { return this->MatchAndExplainImpl(true, container, listener); } private: GTEST_DISALLOW_ASSIGN_(EachMatcherImpl); }; // Implements polymorphic Contains(element_matcher). template <typename M> class ContainsMatcher { public: explicit ContainsMatcher(M m) : inner_matcher_(m) {} template <typename Container> operator Matcher<Container>() const { return MakeMatcher(new ContainsMatcherImpl<Container>(inner_matcher_)); } private: const M inner_matcher_; GTEST_DISALLOW_ASSIGN_(ContainsMatcher); }; // Implements polymorphic Each(element_matcher). template <typename M> class EachMatcher { public: explicit EachMatcher(M m) : inner_matcher_(m) {} template <typename Container> operator Matcher<Container>() const { return MakeMatcher(new EachMatcherImpl<Container>(inner_matcher_)); } private: const M inner_matcher_; GTEST_DISALLOW_ASSIGN_(EachMatcher); }; // Implements Key(inner_matcher) for the given argument pair type. // Key(inner_matcher) matches an std::pair whose 'first' field matches // inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an // std::map that contains at least one element whose key is >= 5. template <typename PairType> class KeyMatcherImpl : public MatcherInterface<PairType> { public: typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType; typedef typename RawPairType::first_type KeyType; template <typename InnerMatcher> explicit KeyMatcherImpl(InnerMatcher inner_matcher) : inner_matcher_( testing::SafeMatcherCast<const KeyType&>(inner_matcher)) { } // Returns true iff 'key_value.first' (the key) matches the inner matcher. virtual bool MatchAndExplain(PairType key_value, MatchResultListener* listener) const { StringMatchResultListener inner_listener; const bool match = inner_matcher_.MatchAndExplain(key_value.first, &inner_listener); const internal::string explanation = inner_listener.str(); if (explanation != "") { *listener << "whose first field is a value " << explanation; } return match; } // Describes what this matcher does. virtual void DescribeTo(::std::ostream* os) const { *os << "has a key that "; inner_matcher_.DescribeTo(os); } // Describes what the negation of this matcher does. virtual void DescribeNegationTo(::std::ostream* os) const { *os << "doesn't have a key that "; inner_matcher_.DescribeTo(os); } private: const Matcher<const KeyType&> inner_matcher_; GTEST_DISALLOW_ASSIGN_(KeyMatcherImpl); }; // Implements polymorphic Key(matcher_for_key). template <typename M> class KeyMatcher { public: explicit KeyMatcher(M m) : matcher_for_key_(m) {} template <typename PairType> operator Matcher<PairType>() const { return MakeMatcher(new KeyMatcherImpl<PairType>(matcher_for_key_)); } private: const M matcher_for_key_; GTEST_DISALLOW_ASSIGN_(KeyMatcher); }; // Implements Pair(first_matcher, second_matcher) for the given argument pair // type with its two matchers. See Pair() function below. template <typename PairType> class PairMatcherImpl : public MatcherInterface<PairType> { public: typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType; typedef typename RawPairType::first_type FirstType; typedef typename RawPairType::second_type SecondType; template <typename FirstMatcher, typename SecondMatcher> PairMatcherImpl(FirstMatcher first_matcher, SecondMatcher second_matcher) : first_matcher_( testing::SafeMatcherCast<const FirstType&>(first_matcher)), second_matcher_( testing::SafeMatcherCast<const SecondType&>(second_matcher)) { } // Describes what this matcher does. virtual void DescribeTo(::std::ostream* os) const { *os << "has a first field that "; first_matcher_.DescribeTo(os); *os << ", and has a second field that "; second_matcher_.DescribeTo(os); } // Describes what the negation of this matcher does. virtual void DescribeNegationTo(::std::ostream* os) const { *os << "has a first field that "; first_matcher_.DescribeNegationTo(os); *os << ", or has a second field that "; second_matcher_.DescribeNegationTo(os); } // Returns true iff 'a_pair.first' matches first_matcher and 'a_pair.second' // matches second_matcher. virtual bool MatchAndExplain(PairType a_pair, MatchResultListener* listener) const { if (!listener->IsInterested()) { // If the listener is not interested, we don't need to construct the // explanation. return first_matcher_.Matches(a_pair.first) && second_matcher_.Matches(a_pair.second); } StringMatchResultListener first_inner_listener; if (!first_matcher_.MatchAndExplain(a_pair.first, &first_inner_listener)) { *listener << "whose first field does not match"; PrintIfNotEmpty(first_inner_listener.str(), listener->stream()); return false; } StringMatchResultListener second_inner_listener; if (!second_matcher_.MatchAndExplain(a_pair.second, &second_inner_listener)) { *listener << "whose second field does not match"; PrintIfNotEmpty(second_inner_listener.str(), listener->stream()); return false; } ExplainSuccess(first_inner_listener.str(), second_inner_listener.str(), listener); return true; } private: void ExplainSuccess(const internal::string& first_explanation, const internal::string& second_explanation, MatchResultListener* listener) const { *listener << "whose both fields match"; if (first_explanation != "") { *listener << ", where the first field is a value " << first_explanation; } if (second_explanation != "") { *listener << ", "; if (first_explanation != "") { *listener << "and "; } else { *listener << "where "; } *listener << "the second field is a value " << second_explanation; } } const Matcher<const FirstType&> first_matcher_; const Matcher<const SecondType&> second_matcher_; GTEST_DISALLOW_ASSIGN_(PairMatcherImpl); }; // Implements polymorphic Pair(first_matcher, second_matcher). template <typename FirstMatcher, typename SecondMatcher> class PairMatcher { public: PairMatcher(FirstMatcher first_matcher, SecondMatcher second_matcher) : first_matcher_(first_matcher), second_matcher_(second_matcher) {} template <typename PairType> operator Matcher<PairType> () const { return MakeMatcher( new PairMatcherImpl<PairType>( first_matcher_, second_matcher_)); } private: const FirstMatcher first_matcher_; const SecondMatcher second_matcher_; GTEST_DISALLOW_ASSIGN_(PairMatcher); }; // Implements ElementsAre() and ElementsAreArray(). template <typename Container> class ElementsAreMatcherImpl : public MatcherInterface<Container> { public: typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer; typedef internal::StlContainerView<RawContainer> View; typedef typename View::type StlContainer; typedef typename View::const_reference StlContainerReference; typedef typename StlContainer::value_type Element; // Constructs the matcher from a sequence of element values or // element matchers. template <typename InputIter> ElementsAreMatcherImpl(InputIter first, InputIter last) { while (first != last) { matchers_.push_back(MatcherCast<const Element&>(*first++)); } } // Describes what this matcher does. virtual void DescribeTo(::std::ostream* os) const { if (count() == 0) { *os << "is empty"; } else if (count() == 1) { *os << "has 1 element that "; matchers_[0].DescribeTo(os); } else { *os << "has " << Elements(count()) << " where\n"; for (size_t i = 0; i != count(); ++i) { *os << "element #" << i << " "; matchers_[i].DescribeTo(os); if (i + 1 < count()) { *os << ",\n"; } } } } // Describes what the negation of this matcher does. virtual void DescribeNegationTo(::std::ostream* os) const { if (count() == 0) { *os << "isn't empty"; return; } *os << "doesn't have " << Elements(count()) << ", or\n"; for (size_t i = 0; i != count(); ++i) { *os << "element #" << i << " "; matchers_[i].DescribeNegationTo(os); if (i + 1 < count()) { *os << ", or\n"; } } } virtual bool MatchAndExplain(Container container, MatchResultListener* listener) const { // To work with stream-like "containers", we must only walk // through the elements in one pass. const bool listener_interested = listener->IsInterested(); // explanations[i] is the explanation of the element at index i. ::std::vector<internal::string> explanations(count()); StlContainerReference stl_container = View::ConstReference(container); typename StlContainer::const_iterator it = stl_container.begin(); size_t exam_pos = 0; bool mismatch_found = false; // Have we found a mismatched element yet? // Go through the elements and matchers in pairs, until we reach // the end of either the elements or the matchers, or until we find a // mismatch. for (; it != stl_container.end() && exam_pos != count(); ++it, ++exam_pos) { bool match; // Does the current element match the current matcher? if (listener_interested) { StringMatchResultListener s; match = matchers_[exam_pos].MatchAndExplain(*it, &s); explanations[exam_pos] = s.str(); } else { match = matchers_[exam_pos].Matches(*it); } if (!match) { mismatch_found = true; break; } } // If mismatch_found is true, 'exam_pos' is the index of the mismatch. // Find how many elements the actual container has. We avoid // calling size() s.t. this code works for stream-like "containers" // that don't define size(). size_t actual_count = exam_pos; for (; it != stl_container.end(); ++it) { ++actual_count; } if (actual_count != count()) { // The element count doesn't match. If the container is empty, // there's no need to explain anything as Google Mock already // prints the empty container. Otherwise we just need to show // how many elements there actually are. if (listener_interested && (actual_count != 0)) { *listener << "which has " << Elements(actual_count); } return false; } if (mismatch_found) { // The element count matches, but the exam_pos-th element doesn't match. if (listener_interested) { *listener << "whose element #" << exam_pos << " doesn't match"; PrintIfNotEmpty(explanations[exam_pos], listener->stream()); } return false; } // Every element matches its expectation. We need to explain why // (the obvious ones can be skipped). if (listener_interested) { bool reason_printed = false; for (size_t i = 0; i != count(); ++i) { const internal::string& s = explanations[i]; if (!s.empty()) { if (reason_printed) { *listener << ",\nand "; } *listener << "whose element #" << i << " matches, " << s; reason_printed = true; } } } return true; } private: static Message Elements(size_t count) { return Message() << count << (count == 1 ? " element" : " elements"); } size_t count() const { return matchers_.size(); } ::std::vector<Matcher<const Element&> > matchers_; GTEST_DISALLOW_ASSIGN_(ElementsAreMatcherImpl); }; // Connectivity matrix of (elements X matchers), in element-major order. // Initially, there are no edges. // Use NextGraph() to iterate over all possible edge configurations. // Use Randomize() to generate a random edge configuration. class GTEST_API_ MatchMatrix { public: MatchMatrix(size_t num_elements, size_t num_matchers) : num_elements_(num_elements), num_matchers_(num_matchers), matched_(num_elements_* num_matchers_, 0) { } size_t LhsSize() const { return num_elements_; } size_t RhsSize() const { return num_matchers_; } bool HasEdge(size_t ilhs, size_t irhs) const { return matched_[SpaceIndex(ilhs, irhs)] == 1; } void SetEdge(size_t ilhs, size_t irhs, bool b) { matched_[SpaceIndex(ilhs, irhs)] = b ? 1 : 0; } // Treating the connectivity matrix as a (LhsSize()*RhsSize())-bit number, // adds 1 to that number; returns false if incrementing the graph left it // empty. bool NextGraph(); void Randomize(); string DebugString() const; private: size_t SpaceIndex(size_t ilhs, size_t irhs) const { return ilhs * num_matchers_ + irhs; } size_t num_elements_; size_t num_matchers_; // Each element is a char interpreted as bool. They are stored as a // flattened array in lhs-major order, use 'SpaceIndex()' to translate // a (ilhs, irhs) matrix coordinate into an offset. ::std::vector<char> matched_; }; typedef ::std::pair<size_t, size_t> ElementMatcherPair; typedef ::std::vector<ElementMatcherPair> ElementMatcherPairs; // Returns a maximum bipartite matching for the specified graph 'g'. // The matching is represented as a vector of {element, matcher} pairs. GTEST_API_ ElementMatcherPairs FindMaxBipartiteMatching(const MatchMatrix& g); GTEST_API_ bool FindPairing(const MatchMatrix& matrix, MatchResultListener* listener); // Untyped base class for implementing UnorderedElementsAre. By // putting logic that's not specific to the element type here, we // reduce binary bloat and increase compilation speed. class GTEST_API_ UnorderedElementsAreMatcherImplBase { protected: // A vector of matcher describers, one for each element matcher. // Does not own the describers (and thus can be used only when the // element matchers are alive). typedef ::std::vector<const MatcherDescriberInterface*> MatcherDescriberVec; // Describes this UnorderedElementsAre matcher. void DescribeToImpl(::std::ostream* os) const; // Describes the negation of this UnorderedElementsAre matcher. void DescribeNegationToImpl(::std::ostream* os) const; bool VerifyAllElementsAndMatchersAreMatched( const ::std::vector<string>& element_printouts, const MatchMatrix& matrix, MatchResultListener* listener) const; MatcherDescriberVec& matcher_describers() { return matcher_describers_; } static Message Elements(size_t n) { return Message() << n << " element" << (n == 1 ? "" : "s"); } private: MatcherDescriberVec matcher_describers_; GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcherImplBase); }; // Implements unordered ElementsAre and unordered ElementsAreArray. template <typename Container> class UnorderedElementsAreMatcherImpl : public MatcherInterface<Container>, public UnorderedElementsAreMatcherImplBase { public: typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer; typedef internal::StlContainerView<RawContainer> View; typedef typename View::type StlContainer; typedef typename View::const_reference StlContainerReference; typedef typename StlContainer::const_iterator StlContainerConstIterator; typedef typename StlContainer::value_type Element; // Constructs the matcher from a sequence of element values or // element matchers. template <typename InputIter> UnorderedElementsAreMatcherImpl(InputIter first, InputIter last) { for (; first != last; ++first) { matchers_.push_back(MatcherCast<const Element&>(*first)); matcher_describers().push_back(matchers_.back().GetDescriber()); } } // Describes what this matcher does. virtual void DescribeTo(::std::ostream* os) const { return UnorderedElementsAreMatcherImplBase::DescribeToImpl(os); } // Describes what the negation of this matcher does. virtual void DescribeNegationTo(::std::ostream* os) const { return UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl(os); } virtual bool MatchAndExplain(Container container, MatchResultListener* listener) const { StlContainerReference stl_container = View::ConstReference(container); ::std::vector<string> element_printouts; MatchMatrix matrix = AnalyzeElements(stl_container.begin(), stl_container.end(), &element_printouts, listener); const size_t actual_count = matrix.LhsSize(); if (actual_count == 0 && matchers_.empty()) { return true; } if (actual_count != matchers_.size()) { // The element count doesn't match. If the container is empty, // there's no need to explain anything as Google Mock already // prints the empty container. Otherwise we just need to show // how many elements there actually are. if (actual_count != 0 && listener->IsInterested()) { *listener << "which has " << Elements(actual_count); } return false; } return VerifyAllElementsAndMatchersAreMatched(element_printouts, matrix, listener) && FindPairing(matrix, listener); } private: typedef ::std::vector<Matcher<const Element&> > MatcherVec; template <typename ElementIter> MatchMatrix AnalyzeElements(ElementIter elem_first, ElementIter elem_last, ::std::vector<string>* element_printouts, MatchResultListener* listener) const { element_printouts->clear(); ::std::vector<char> did_match; size_t num_elements = 0; for (; elem_first != elem_last; ++num_elements, ++elem_first) { if (listener->IsInterested()) { element_printouts->push_back(PrintToString(*elem_first)); } for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) { did_match.push_back(Matches(matchers_[irhs])(*elem_first)); } } MatchMatrix matrix(num_elements, matchers_.size()); ::std::vector<char>::const_iterator did_match_iter = did_match.begin(); for (size_t ilhs = 0; ilhs != num_elements; ++ilhs) { for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) { matrix.SetEdge(ilhs, irhs, *did_match_iter++ != 0); } } return matrix; } MatcherVec matchers_; GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcherImpl); }; // Functor for use in TransformTuple. // Performs MatcherCast<Target> on an input argument of any type. template <typename Target> struct CastAndAppendTransform { template <typename Arg> Matcher<Target> operator()(const Arg& a) const { return MatcherCast<Target>(a); } }; // Implements UnorderedElementsAre. template <typename MatcherTuple> class UnorderedElementsAreMatcher { public: explicit UnorderedElementsAreMatcher(const MatcherTuple& args) : matchers_(args) {} template <typename Container> operator Matcher<Container>() const { typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer; typedef typename internal::StlContainerView<RawContainer>::type View; typedef typename View::value_type Element; typedef ::std::vector<Matcher<const Element&> > MatcherVec; MatcherVec matchers; matchers.reserve(::testing::tuple_size<MatcherTuple>::value); TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_, ::std::back_inserter(matchers)); return MakeMatcher(new UnorderedElementsAreMatcherImpl<Container>( matchers.begin(), matchers.end())); } private: const MatcherTuple matchers_; GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcher); }; // Implements ElementsAre. template <typename MatcherTuple> class ElementsAreMatcher { public: explicit ElementsAreMatcher(const MatcherTuple& args) : matchers_(args) {} template <typename Container> operator Matcher<Container>() const { typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer; typedef typename internal::StlContainerView<RawContainer>::type View; typedef typename View::value_type Element; typedef ::std::vector<Matcher<const Element&> > MatcherVec; MatcherVec matchers; matchers.reserve(::testing::tuple_size<MatcherTuple>::value); TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_, ::std::back_inserter(matchers)); return MakeMatcher(new ElementsAreMatcherImpl<Container>( matchers.begin(), matchers.end())); } private: const MatcherTuple matchers_; GTEST_DISALLOW_ASSIGN_(ElementsAreMatcher); }; // Implements UnorderedElementsAreArray(). template <typename T> class UnorderedElementsAreArrayMatcher { public: UnorderedElementsAreArrayMatcher() {} template <typename Iter> UnorderedElementsAreArrayMatcher(Iter first, Iter last) : matchers_(first, last) {} template <typename Container> operator Matcher<Container>() const { return MakeMatcher( new UnorderedElementsAreMatcherImpl<Container>(matchers_.begin(), matchers_.end())); } private: ::std::vector<T> matchers_; GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreArrayMatcher); }; // Implements ElementsAreArray(). template <typename T> class ElementsAreArrayMatcher { public: template <typename Iter> ElementsAreArrayMatcher(Iter first, Iter last) : matchers_(first, last) {} template <typename Container> operator Matcher<Container>() const { return MakeMatcher(new ElementsAreMatcherImpl<Container>( matchers_.begin(), matchers_.end())); } private: const ::std::vector<T> matchers_; GTEST_DISALLOW_ASSIGN_(ElementsAreArrayMatcher); }; // Returns the description for a matcher defined using the MATCHER*() // macro where the user-supplied description string is "", if // 'negation' is false; otherwise returns the description of the // negation of the matcher. 'param_values' contains a list of strings // that are the print-out of the matcher's parameters. GTEST_API_ string FormatMatcherDescription(bool negation, const char* matcher_name, const Strings& param_values); } // namespace internal // ElementsAreArray(first, last) // ElementsAreArray(pointer, count) // ElementsAreArray(array) // ElementsAreArray(vector) // ElementsAreArray({ e1, e2, ..., en }) // // The ElementsAreArray() functions are like ElementsAre(...), except // that they are given a homogeneous sequence rather than taking each // element as a function argument. The sequence can be specified as an // array, a pointer and count, a vector, an initializer list, or an // STL iterator range. In each of these cases, the underlying sequence // can be either a sequence of values or a sequence of matchers. // // All forms of ElementsAreArray() make a copy of the input matcher sequence. template <typename Iter> inline internal::ElementsAreArrayMatcher< typename ::std::iterator_traits<Iter>::value_type> ElementsAreArray(Iter first, Iter last) { typedef typename ::std::iterator_traits<Iter>::value_type T; return internal::ElementsAreArrayMatcher<T>(first, last); } template <typename T> inline internal::ElementsAreArrayMatcher<T> ElementsAreArray( const T* pointer, size_t count) { return ElementsAreArray(pointer, pointer + count); } template <typename T, size_t N> inline internal::ElementsAreArrayMatcher<T> ElementsAreArray( const T (&array)[N]) { return ElementsAreArray(array, N); } template <typename T, typename A> inline internal::ElementsAreArrayMatcher<T> ElementsAreArray( const ::std::vector<T, A>& vec) { return ElementsAreArray(vec.begin(), vec.end()); } #if GTEST_HAS_STD_INITIALIZER_LIST_ template <typename T> inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(::std::initializer_list<T> xs) { return ElementsAreArray(xs.begin(), xs.end()); } #endif // UnorderedElementsAreArray(first, last) // UnorderedElementsAreArray(pointer, count) // UnorderedElementsAreArray(array) // UnorderedElementsAreArray(vector) // UnorderedElementsAreArray({ e1, e2, ..., en }) // // The UnorderedElementsAreArray() functions are like // ElementsAreArray(...), but allow matching the elements in any order. template <typename Iter> inline internal::UnorderedElementsAreArrayMatcher< typename ::std::iterator_traits<Iter>::value_type> UnorderedElementsAreArray(Iter first, Iter last) { typedef typename ::std::iterator_traits<Iter>::value_type T; return internal::UnorderedElementsAreArrayMatcher<T>(first, last); } template <typename T> inline internal::UnorderedElementsAreArrayMatcher<T> UnorderedElementsAreArray(const T* pointer, size_t count) { return UnorderedElementsAreArray(pointer, pointer + count); } template <typename T, size_t N> inline internal::UnorderedElementsAreArrayMatcher<T> UnorderedElementsAreArray(const T (&array)[N]) { return UnorderedElementsAreArray(array, N); } template <typename T, typename A> inline internal::UnorderedElementsAreArrayMatcher<T> UnorderedElementsAreArray(const ::std::vector<T, A>& vec) { return UnorderedElementsAreArray(vec.begin(), vec.end()); } #if GTEST_HAS_STD_INITIALIZER_LIST_ template <typename T> inline internal::UnorderedElementsAreArrayMatcher<T> UnorderedElementsAreArray(::std::initializer_list<T> xs) { return UnorderedElementsAreArray(xs.begin(), xs.end()); } #endif // _ is a matcher that matches anything of any type. // // This definition is fine as: // // 1. The C++ standard permits using the name _ in a namespace that // is not the global namespace or ::std. // 2. The AnythingMatcher class has no data member or constructor, // so it's OK to create global variables of this type. // 3. c-style has approved of using _ in this case. const internal::AnythingMatcher _ = {}; // Creates a matcher that matches any value of the given type T. template <typename T> inline Matcher<T> A() { return MakeMatcher(new internal::AnyMatcherImpl<T>()); } // Creates a matcher that matches any value of the given type T. template <typename T> inline Matcher<T> An() { return A<T>(); } // Creates a polymorphic matcher that matches anything equal to x. // Note: if the parameter of Eq() were declared as const T&, Eq("foo") // wouldn't compile. template <typename T> inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); } // Constructs a Matcher<T> from a 'value' of type T. The constructed // matcher matches any value that's equal to 'value'. template <typename T> Matcher<T>::Matcher(T value) { *this = Eq(value); } // Creates a monomorphic matcher that matches anything with type Lhs // and equal to rhs. A user may need to use this instead of Eq(...) // in order to resolve an overloading ambiguity. // // TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x)) // or Matcher<T>(x), but more readable than the latter. // // We could define similar monomorphic matchers for other comparison // operations (e.g. TypedLt, TypedGe, and etc), but decided not to do // it yet as those are used much less than Eq() in practice. A user // can always write Matcher<T>(Lt(5)) to be explicit about the type, // for example. template <typename Lhs, typename Rhs> inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); } // Creates a polymorphic matcher that matches anything >= x. template <typename Rhs> inline internal::GeMatcher<Rhs> Ge(Rhs x) { return internal::GeMatcher<Rhs>(x); } // Creates a polymorphic matcher that matches anything > x. template <typename Rhs> inline internal::GtMatcher<Rhs> Gt(Rhs x) { return internal::GtMatcher<Rhs>(x); } // Creates a polymorphic matcher that matches anything <= x. template <typename Rhs> inline internal::LeMatcher<Rhs> Le(Rhs x) { return internal::LeMatcher<Rhs>(x); } // Creates a polymorphic matcher that matches anything < x. template <typename Rhs> inline internal::LtMatcher<Rhs> Lt(Rhs x) { return internal::LtMatcher<Rhs>(x); } // Creates a polymorphic matcher that matches anything != x. template <typename Rhs> inline internal::NeMatcher<Rhs> Ne(Rhs x) { return internal::NeMatcher<Rhs>(x); } // Creates a polymorphic matcher that matches any NULL pointer. inline PolymorphicMatcher<internal::IsNullMatcher > IsNull() { return MakePolymorphicMatcher(internal::IsNullMatcher()); } // Creates a polymorphic matcher that matches any non-NULL pointer. // This is convenient as Not(NULL) doesn't compile (the compiler // thinks that that expression is comparing a pointer with an integer). inline PolymorphicMatcher<internal::NotNullMatcher > NotNull() { return MakePolymorphicMatcher(internal::NotNullMatcher()); } // Creates a polymorphic matcher that matches any argument that // references variable x. template <typename T> inline internal::RefMatcher<T&> Ref(T& x) { // NOLINT return internal::RefMatcher<T&>(x); } // Creates a matcher that matches any double argument approximately // equal to rhs, where two NANs are considered unequal. inline internal::FloatingEqMatcher<double> DoubleEq(double rhs) { return internal::FloatingEqMatcher<double>(rhs, false); } // Creates a matcher that matches any double argument approximately // equal to rhs, including NaN values when rhs is NaN. inline internal::FloatingEqMatcher<double> NanSensitiveDoubleEq(double rhs) { return internal::FloatingEqMatcher<double>(rhs, true); } // Creates a matcher that matches any double argument approximately equal to // rhs, up to the specified max absolute error bound, where two NANs are // considered unequal. The max absolute error bound must be non-negative. inline internal::FloatingEqMatcher<double> DoubleNear( double rhs, double max_abs_error) { return internal::FloatingEqMatcher<double>(rhs, false, max_abs_error); } // Creates a matcher that matches any double argument approximately equal to // rhs, up to the specified max absolute error bound, including NaN values when // rhs is NaN. The max absolute error bound must be non-negative. inline internal::FloatingEqMatcher<double> NanSensitiveDoubleNear( double rhs, double max_abs_error) { return internal::FloatingEqMatcher<double>(rhs, true, max_abs_error); } // Creates a matcher that matches any float argument approximately // equal to rhs, where two NANs are considered unequal. inline internal::FloatingEqMatcher<float> FloatEq(float rhs) { return internal::FloatingEqMatcher<float>(rhs, false); } // Creates a matcher that matches any float argument approximately // equal to rhs, including NaN values when rhs is NaN. inline internal::FloatingEqMatcher<float> NanSensitiveFloatEq(float rhs) { return internal::FloatingEqMatcher<float>(rhs, true); } // Creates a matcher that matches any float argument approximately equal to // rhs, up to the specified max absolute error bound, where two NANs are // considered unequal. The max absolute error bound must be non-negative. inline internal::FloatingEqMatcher<float> FloatNear( float rhs, float max_abs_error) { return internal::FloatingEqMatcher<float>(rhs, false, max_abs_error); } // Creates a matcher that matches any float argument approximately equal to // rhs, up to the specified max absolute error bound, including NaN values when // rhs is NaN. The max absolute error bound must be non-negative. inline internal::FloatingEqMatcher<float> NanSensitiveFloatNear( float rhs, float max_abs_error) { return internal::FloatingEqMatcher<float>(rhs, true, max_abs_error); } // Creates a matcher that matches a pointer (raw or smart) that points // to a value that matches inner_matcher. template <typename InnerMatcher> inline internal::PointeeMatcher<InnerMatcher> Pointee( const InnerMatcher& inner_matcher) { return internal::PointeeMatcher<InnerMatcher>(inner_matcher); } // Creates a matcher that matches an object whose given field matches // 'matcher'. For example, // Field(&Foo::number, Ge(5)) // matches a Foo object x iff x.number >= 5. template <typename Class, typename FieldType, typename FieldMatcher> inline PolymorphicMatcher< internal::FieldMatcher<Class, FieldType> > Field( FieldType Class::*field, const FieldMatcher& matcher) { return MakePolymorphicMatcher( internal::FieldMatcher<Class, FieldType>( field, MatcherCast<const FieldType&>(matcher))); // The call to MatcherCast() is required for supporting inner // matchers of compatible types. For example, it allows // Field(&Foo::bar, m) // to compile where bar is an int32 and m is a matcher for int64. } // Creates a matcher that matches an object whose given property // matches 'matcher'. For example, // Property(&Foo::str, StartsWith("hi")) // matches a Foo object x iff x.str() starts with "hi". template <typename Class, typename PropertyType, typename PropertyMatcher> inline PolymorphicMatcher< internal::PropertyMatcher<Class, PropertyType> > Property( PropertyType (Class::*property)() const, const PropertyMatcher& matcher) { return MakePolymorphicMatcher( internal::PropertyMatcher<Class, PropertyType>( property, MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher))); // The call to MatcherCast() is required for supporting inner // matchers of compatible types. For example, it allows // Property(&Foo::bar, m) // to compile where bar() returns an int32 and m is a matcher for int64. } // Creates a matcher that matches an object iff the result of applying // a callable to x matches 'matcher'. // For example, // ResultOf(f, StartsWith("hi")) // matches a Foo object x iff f(x) starts with "hi". // callable parameter can be a function, function pointer, or a functor. // Callable has to satisfy the following conditions: // * It is required to keep no state affecting the results of // the calls on it and make no assumptions about how many calls // will be made. Any state it keeps must be protected from the // concurrent access. // * If it is a function object, it has to define type result_type. // We recommend deriving your functor classes from std::unary_function. template <typename Callable, typename ResultOfMatcher> internal::ResultOfMatcher<Callable> ResultOf( Callable callable, const ResultOfMatcher& matcher) { return internal::ResultOfMatcher<Callable>( callable, MatcherCast<typename internal::CallableTraits<Callable>::ResultType>( matcher)); // The call to MatcherCast() is required for supporting inner // matchers of compatible types. For example, it allows // ResultOf(Function, m) // to compile where Function() returns an int32 and m is a matcher for int64. } // String matchers. // Matches a string equal to str. inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> > StrEq(const internal::string& str) { return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>( str, true, true)); } // Matches a string not equal to str. inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> > StrNe(const internal::string& str) { return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>( str, false, true)); } // Matches a string equal to str, ignoring case. inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> > StrCaseEq(const internal::string& str) { return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>( str, true, false)); } // Matches a string not equal to str, ignoring case. inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> > StrCaseNe(const internal::string& str) { return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>( str, false, false)); } // Creates a matcher that matches any string, std::string, or C string // that contains the given substring. inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::string> > HasSubstr(const internal::string& substring) { return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::string>( substring)); } // Matches a string that starts with 'prefix' (case-sensitive). inline PolymorphicMatcher<internal::StartsWithMatcher<internal::string> > StartsWith(const internal::string& prefix) { return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::string>( prefix)); } // Matches a string that ends with 'suffix' (case-sensitive). inline PolymorphicMatcher<internal::EndsWithMatcher<internal::string> > EndsWith(const internal::string& suffix) { return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::string>( suffix)); } // Matches a string that fully matches regular expression 'regex'. // The matcher takes ownership of 'regex'. inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex( const internal::RE* regex) { return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true)); } inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex( const internal::string& regex) { return MatchesRegex(new internal::RE(regex)); } // Matches a string that contains regular expression 'regex'. // The matcher takes ownership of 'regex'. inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex( const internal::RE* regex) { return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false)); } inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex( const internal::string& regex) { return ContainsRegex(new internal::RE(regex)); } #if GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING // Wide string matchers. // Matches a string equal to str. inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> > StrEq(const internal::wstring& str) { return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>( str, true, true)); } // Matches a string not equal to str. inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> > StrNe(const internal::wstring& str) { return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>( str, false, true)); } // Matches a string equal to str, ignoring case. inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> > StrCaseEq(const internal::wstring& str) { return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>( str, true, false)); } // Matches a string not equal to str, ignoring case. inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> > StrCaseNe(const internal::wstring& str) { return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>( str, false, false)); } // Creates a matcher that matches any wstring, std::wstring, or C wide string // that contains the given substring. inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::wstring> > HasSubstr(const internal::wstring& substring) { return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::wstring>( substring)); } // Matches a string that starts with 'prefix' (case-sensitive). inline PolymorphicMatcher<internal::StartsWithMatcher<internal::wstring> > StartsWith(const internal::wstring& prefix) { return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::wstring>( prefix)); } // Matches a string that ends with 'suffix' (case-sensitive). inline PolymorphicMatcher<internal::EndsWithMatcher<internal::wstring> > EndsWith(const internal::wstring& suffix) { return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::wstring>( suffix)); } #endif // GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING // Creates a polymorphic matcher that matches a 2-tuple where the // first field == the second field. inline internal::Eq2Matcher Eq() { return internal::Eq2Matcher(); } // Creates a polymorphic matcher that matches a 2-tuple where the // first field >= the second field. inline internal::Ge2Matcher Ge() { return internal::Ge2Matcher(); } // Creates a polymorphic matcher that matches a 2-tuple where the // first field > the second field. inline internal::Gt2Matcher Gt() { return internal::Gt2Matcher(); } // Creates a polymorphic matcher that matches a 2-tuple where the // first field <= the second field. inline internal::Le2Matcher Le() { return internal::Le2Matcher(); } // Creates a polymorphic matcher that matches a 2-tuple where the // first field < the second field. inline internal::Lt2Matcher Lt() { return internal::Lt2Matcher(); } // Creates a polymorphic matcher that matches a 2-tuple where the // first field != the second field. inline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); } // Creates a matcher that matches any value of type T that m doesn't // match. template <typename InnerMatcher> inline internal::NotMatcher<InnerMatcher> Not(InnerMatcher m) { return internal::NotMatcher<InnerMatcher>(m); } // Returns a matcher that matches anything that satisfies the given // predicate. The predicate can be any unary function or functor // whose return type can be implicitly converted to bool. template <typename Predicate> inline PolymorphicMatcher<internal::TrulyMatcher<Predicate> > Truly(Predicate pred) { return MakePolymorphicMatcher(internal::TrulyMatcher<Predicate>(pred)); } // Returns a matcher that matches the container size. The container must // support both size() and size_type which all STL-like containers provide. // Note that the parameter 'size' can be a value of type size_type as well as // matcher. For instance: // EXPECT_THAT(container, SizeIs(2)); // Checks container has 2 elements. // EXPECT_THAT(container, SizeIs(Le(2)); // Checks container has at most 2. template <typename SizeMatcher> inline internal::SizeIsMatcher<SizeMatcher> SizeIs(const SizeMatcher& size_matcher) { return internal::SizeIsMatcher<SizeMatcher>(size_matcher); } // Returns a matcher that matches the distance between the container's begin() // iterator and its end() iterator, i.e. the size of the container. This matcher // can be used instead of SizeIs with containers such as std::forward_list which // do not implement size(). The container must provide const_iterator (with // valid iterator_traits), begin() and end(). template <typename DistanceMatcher> inline internal::BeginEndDistanceIsMatcher<DistanceMatcher> BeginEndDistanceIs(const DistanceMatcher& distance_matcher) { return internal::BeginEndDistanceIsMatcher<DistanceMatcher>(distance_matcher); } // Returns a matcher that matches an equal container. // This matcher behaves like Eq(), but in the event of mismatch lists the // values that are included in one container but not the other. (Duplicate // values and order differences are not explained.) template <typename Container> inline PolymorphicMatcher<internal::ContainerEqMatcher< // NOLINT GTEST_REMOVE_CONST_(Container)> > ContainerEq(const Container& rhs) { // This following line is for working around a bug in MSVC 8.0, // which causes Container to be a const type sometimes. typedef GTEST_REMOVE_CONST_(Container) RawContainer; return MakePolymorphicMatcher( internal::ContainerEqMatcher<RawContainer>(rhs)); } // Returns a matcher that matches a container that, when sorted using // the given comparator, matches container_matcher. template <typename Comparator, typename ContainerMatcher> inline internal::WhenSortedByMatcher<Comparator, ContainerMatcher> WhenSortedBy(const Comparator& comparator, const ContainerMatcher& container_matcher) { return internal::WhenSortedByMatcher<Comparator, ContainerMatcher>( comparator, container_matcher); } // Returns a matcher that matches a container that, when sorted using // the < operator, matches container_matcher. template <typename ContainerMatcher> inline internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher> WhenSorted(const ContainerMatcher& container_matcher) { return internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>( internal::LessComparator(), container_matcher); } // Matches an STL-style container or a native array that contains the // same number of elements as in rhs, where its i-th element and rhs's // i-th element (as a pair) satisfy the given pair matcher, for all i. // TupleMatcher must be able to be safely cast to Matcher<tuple<const // T1&, const T2&> >, where T1 and T2 are the types of elements in the // LHS container and the RHS container respectively. template <typename TupleMatcher, typename Container> inline internal::PointwiseMatcher<TupleMatcher, GTEST_REMOVE_CONST_(Container)> Pointwise(const TupleMatcher& tuple_matcher, const Container& rhs) { // This following line is for working around a bug in MSVC 8.0, // which causes Container to be a const type sometimes. typedef GTEST_REMOVE_CONST_(Container) RawContainer; return internal::PointwiseMatcher<TupleMatcher, RawContainer>( tuple_matcher, rhs); } // Matches an STL-style container or a native array that contains at // least one element matching the given value or matcher. // // Examples: // ::std::set<int> page_ids; // page_ids.insert(3); // page_ids.insert(1); // EXPECT_THAT(page_ids, Contains(1)); // EXPECT_THAT(page_ids, Contains(Gt(2))); // EXPECT_THAT(page_ids, Not(Contains(4))); // // ::std::map<int, size_t> page_lengths; // page_lengths[1] = 100; // EXPECT_THAT(page_lengths, // Contains(::std::pair<const int, size_t>(1, 100))); // // const char* user_ids[] = { "joe", "mike", "tom" }; // EXPECT_THAT(user_ids, Contains(Eq(::std::string("tom")))); template <typename M> inline internal::ContainsMatcher<M> Contains(M matcher) { return internal::ContainsMatcher<M>(matcher); } // Matches an STL-style container or a native array that contains only // elements matching the given value or matcher. // // Each(m) is semantically equivalent to Not(Contains(Not(m))). Only // the messages are different. // // Examples: // ::std::set<int> page_ids; // // Each(m) matches an empty container, regardless of what m is. // EXPECT_THAT(page_ids, Each(Eq(1))); // EXPECT_THAT(page_ids, Each(Eq(77))); // // page_ids.insert(3); // EXPECT_THAT(page_ids, Each(Gt(0))); // EXPECT_THAT(page_ids, Not(Each(Gt(4)))); // page_ids.insert(1); // EXPECT_THAT(page_ids, Not(Each(Lt(2)))); // // ::std::map<int, size_t> page_lengths; // page_lengths[1] = 100; // page_lengths[2] = 200; // page_lengths[3] = 300; // EXPECT_THAT(page_lengths, Not(Each(Pair(1, 100)))); // EXPECT_THAT(page_lengths, Each(Key(Le(3)))); // // const char* user_ids[] = { "joe", "mike", "tom" }; // EXPECT_THAT(user_ids, Not(Each(Eq(::std::string("tom"))))); template <typename M> inline internal::EachMatcher<M> Each(M matcher) { return internal::EachMatcher<M>(matcher); } // Key(inner_matcher) matches an std::pair whose 'first' field matches // inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an // std::map that contains at least one element whose key is >= 5. template <typename M> inline internal::KeyMatcher<M> Key(M inner_matcher) { return internal::KeyMatcher<M>(inner_matcher); } // Pair(first_matcher, second_matcher) matches a std::pair whose 'first' field // matches first_matcher and whose 'second' field matches second_matcher. For // example, EXPECT_THAT(map_type, ElementsAre(Pair(Ge(5), "foo"))) can be used // to match a std::map<int, string> that contains exactly one element whose key // is >= 5 and whose value equals "foo". template <typename FirstMatcher, typename SecondMatcher> inline internal::PairMatcher<FirstMatcher, SecondMatcher> Pair(FirstMatcher first_matcher, SecondMatcher second_matcher) { return internal::PairMatcher<FirstMatcher, SecondMatcher>( first_matcher, second_matcher); } // Returns a predicate that is satisfied by anything that matches the // given matcher. template <typename M> inline internal::MatcherAsPredicate<M> Matches(M matcher) { return internal::MatcherAsPredicate<M>(matcher); } // Returns true iff the value matches the matcher. template <typename T, typename M> inline bool Value(const T& value, M matcher) { return testing::Matches(matcher)(value); } // Matches the value against the given matcher and explains the match // result to listener. template <typename T, typename M> inline bool ExplainMatchResult( M matcher, const T& value, MatchResultListener* listener) { return SafeMatcherCast<const T&>(matcher).MatchAndExplain(value, listener); } #if GTEST_LANG_CXX11 // Define variadic matcher versions. They are overloaded in // gmock-generated-matchers.h for the cases supported by pre C++11 compilers. template <typename... Args> inline internal::AllOfMatcher<Args...> AllOf(const Args&... matchers) { return internal::AllOfMatcher<Args...>(matchers...); } template <typename... Args> inline internal::AnyOfMatcher<Args...> AnyOf(const Args&... matchers) { return internal::AnyOfMatcher<Args...>(matchers...); } #endif // GTEST_LANG_CXX11 // AllArgs(m) is a synonym of m. This is useful in // // EXPECT_CALL(foo, Bar(_, _)).With(AllArgs(Eq())); // // which is easier to read than // // EXPECT_CALL(foo, Bar(_, _)).With(Eq()); template <typename InnerMatcher> inline InnerMatcher AllArgs(const InnerMatcher& matcher) { return matcher; } // These macros allow using matchers to check values in Google Test // tests. ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher) // succeed iff the value matches the matcher. If the assertion fails, // the value and the description of the matcher will be printed. #define ASSERT_THAT(value, matcher) ASSERT_PRED_FORMAT1(\ ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value) #define EXPECT_THAT(value, matcher) EXPECT_PRED_FORMAT1(\ ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value) } // namespace testing #endif // GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
RasPlex/plex-home-theatre
plex/Third-Party/gmock/include/gmock/gmock-matchers.h
C
gpl-2.0
147,098
/* * Copyright (C) 2008-2014 Free Software Foundation, Inc. * Written by Simon Josefsson. * * 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/>. */ #include <config.h> /* Get gethostname() declaration. */ #include <unistd.h> #include "signature.h" SIGNATURE_CHECK (gethostname, int, (char *, size_t)); /* Get HOST_NAME_MAX definition. */ #include <limits.h> #include <stdio.h> #include <string.h> #include <errno.h> #define NOHOSTNAME "magic-gnulib-test-string" int main (int argc, char *argv[] _GL_UNUSED) { char buf[HOST_NAME_MAX]; int rc; if (strlen (NOHOSTNAME) >= HOST_NAME_MAX) { printf ("HOST_NAME_MAX impossibly small?! %d\n", HOST_NAME_MAX); return 2; } strcpy (buf, NOHOSTNAME); rc = gethostname (buf, sizeof (buf)); if (rc != 0) { printf ("gethostname failed, rc %d errno %d\n", rc, errno); return 1; } if (strcmp (buf, NOHOSTNAME) == 0) { printf ("gethostname left buffer untouched.\n"); return 1; } if (argc > 1) printf ("hostname: %s\n", buf); return 0; }
marmeladema/libprelude
libmissing/tests/test-gethostname.c
C
gpl-2.0
1,665
""" vidabc urlresolver plugin Copyright (C) 2016 suuhm 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/>. """ from __generic_resolver__ import GenericResolver from lib import helpers class VidabcResolver(GenericResolver): name = "vidabc" domains = ["vidabc.com"] pattern = '(?://|\.)(vidabc\.com)/(?:embed-)?([0-9a-zA-Z-]+)' def get_media_url(self, host, media_id): return helpers.get_media_url(self.get_url(host, media_id), result_blacklist=['error.'])
repotvsupertuga/repo
script.module.urlresolver/lib/urlresolver/plugins/vidabc.py
Python
gpl-2.0
1,089
/* * Microchip ENC28J60 ethernet driver (MAC + PHY) * * Copyright (C) 2007 Eurek srl * Author: Claudio Lanconelli <[email protected]> * based on enc28j60.c written by David Anders for 2.4 kernel version * * 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. * * $Id: enc28j60.c,v 1.22 2007/12/20 10:47:01 claudio Exp $ */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/types.h> #include <linux/fcntl.h> #include <linux/interrupt.h> #include <linux/slab.h> #include <linux/string.h> #include <linux/errno.h> #include <linux/init.h> #include <linux/netdevice.h> #include <linux/etherdevice.h> #include <linux/ethtool.h> #include <linux/tcp.h> #include <linux/skbuff.h> #include <linux/delay.h> #include <linux/spi/spi.h> #include "enc28j60_hw.h" #define DRV_NAME "enc28j60" #define DRV_VERSION "1.01" #define SPI_OPLEN 1 #define ENC28J60_MSG_DEFAULT \ (NETIF_MSG_PROBE | NETIF_MSG_IFUP | NETIF_MSG_IFDOWN | NETIF_MSG_LINK) /* Buffer size required for the largest SPI transfer (i.e., reading a * frame). */ #define SPI_TRANSFER_BUF_LEN (4 + MAX_FRAMELEN) #define TX_TIMEOUT (4 * HZ) /* Max TX retries in case of collision as suggested by errata datasheet */ #define MAX_TX_RETRYCOUNT 16 enum { RXFILTER_NORMAL, RXFILTER_MULTI, RXFILTER_PROMISC }; /* Driver local data */ struct enc28j60_net { struct net_device *netdev; struct spi_device *spi; struct mutex lock; struct sk_buff *tx_skb; struct work_struct tx_work; struct work_struct irq_work; struct work_struct setrx_work; struct work_struct restart_work; u8 bank; /* current register bank selected */ u16 next_pk_ptr; /* next packet pointer within FIFO */ u16 max_pk_counter; /* statistics: max packet counter */ u16 tx_retry_count; bool hw_enable; bool full_duplex; int rxfilter; u32 msg_enable; u8 spi_transfer_buf[SPI_TRANSFER_BUF_LEN]; }; /* use ethtool to change the level for any given device */ static struct { u32 msg_enable; } debug = { -1 }; /* * SPI read buffer * wait for the SPI transfer and copy received data to destination */ static int spi_read_buf(struct enc28j60_net *priv, int len, u8 *data) { u8 *rx_buf = priv->spi_transfer_buf + 4; u8 *tx_buf = priv->spi_transfer_buf; struct spi_transfer t = { .tx_buf = tx_buf, .rx_buf = rx_buf, .len = SPI_OPLEN + len, }; struct spi_message msg; int ret; tx_buf[0] = ENC28J60_READ_BUF_MEM; tx_buf[1] = tx_buf[2] = tx_buf[3] = 0; /* don't care */ spi_message_init(&msg); spi_message_add_tail(&t, &msg); ret = spi_sync(priv->spi, &msg); if (ret == 0) { memcpy(data, &rx_buf[SPI_OPLEN], len); ret = msg.status; } if (ret && netif_msg_drv(priv)) printk(KERN_DEBUG DRV_NAME ": %s() failed: ret = %d\n", __func__, ret); return ret; } /* * SPI write buffer */ static int spi_write_buf(struct enc28j60_net *priv, int len, const u8 *data) { int ret; if (len > SPI_TRANSFER_BUF_LEN - 1 || len <= 0) ret = -EINVAL; else { priv->spi_transfer_buf[0] = ENC28J60_WRITE_BUF_MEM; memcpy(&priv->spi_transfer_buf[1], data, len); ret = spi_write(priv->spi, priv->spi_transfer_buf, len + 1); if (ret && netif_msg_drv(priv)) printk(KERN_DEBUG DRV_NAME ": %s() failed: ret = %d\n", __func__, ret); } return ret; } /* * basic SPI read operation */ static u8 spi_read_op(struct enc28j60_net *priv, u8 op, u8 addr) { u8 tx_buf[2]; u8 rx_buf[4]; u8 val = 0; int ret; int slen = SPI_OPLEN; /* do dummy read if needed */ if (addr & SPRD_MASK) slen++; tx_buf[0] = op | (addr & ADDR_MASK); ret = spi_write_then_read(priv->spi, tx_buf, 1, rx_buf, slen); if (ret) printk(KERN_DEBUG DRV_NAME ": %s() failed: ret = %d\n", __func__, ret); else val = rx_buf[slen - 1]; return val; } /* * basic SPI write operation */ static int spi_write_op(struct enc28j60_net *priv, u8 op, u8 addr, u8 val) { int ret; priv->spi_transfer_buf[0] = op | (addr & ADDR_MASK); priv->spi_transfer_buf[1] = val; ret = spi_write(priv->spi, priv->spi_transfer_buf, 2); if (ret && netif_msg_drv(priv)) printk(KERN_DEBUG DRV_NAME ": %s() failed: ret = %d\n", __func__, ret); return ret; } static void enc28j60_soft_reset(struct enc28j60_net *priv) { if (netif_msg_hw(priv)) printk(KERN_DEBUG DRV_NAME ": %s() enter\n", __func__); spi_write_op(priv, ENC28J60_SOFT_RESET, 0, ENC28J60_SOFT_RESET); /* Errata workaround #1, CLKRDY check is unreliable, * delay at least 1 mS instead */ udelay(2000); } /* * select the current register bank if necessary */ static void enc28j60_set_bank(struct enc28j60_net *priv, u8 addr) { u8 b = (addr & BANK_MASK) >> 5; /* These registers (EIE, EIR, ESTAT, ECON2, ECON1) * are present in all banks, no need to switch bank */ if (addr >= EIE && addr <= ECON1) return; /* Clear or set each bank selection bit as needed */ if ((b & ECON1_BSEL0) != (priv->bank & ECON1_BSEL0)) { if (b & ECON1_BSEL0) spi_write_op(priv, ENC28J60_BIT_FIELD_SET, ECON1, ECON1_BSEL0); else spi_write_op(priv, ENC28J60_BIT_FIELD_CLR, ECON1, ECON1_BSEL0); } if ((b & ECON1_BSEL1) != (priv->bank & ECON1_BSEL1)) { if (b & ECON1_BSEL1) spi_write_op(priv, ENC28J60_BIT_FIELD_SET, ECON1, ECON1_BSEL1); else spi_write_op(priv, ENC28J60_BIT_FIELD_CLR, ECON1, ECON1_BSEL1); } priv->bank = b; } /* * Register access routines through the SPI bus. * Every register access comes in two flavours: * - nolock_xxx: caller needs to invoke mutex_lock, usually to access * atomically more than one register * - locked_xxx: caller doesn't need to invoke mutex_lock, single access * * Some registers can be accessed through the bit field clear and * bit field set to avoid a read modify write cycle. */ /* * Register bit field Set */ static void nolock_reg_bfset(struct enc28j60_net *priv, u8 addr, u8 mask) { enc28j60_set_bank(priv, addr); spi_write_op(priv, ENC28J60_BIT_FIELD_SET, addr, mask); } static void locked_reg_bfset(struct enc28j60_net *priv, u8 addr, u8 mask) { mutex_lock(&priv->lock); nolock_reg_bfset(priv, addr, mask); mutex_unlock(&priv->lock); } /* * Register bit field Clear */ static void nolock_reg_bfclr(struct enc28j60_net *priv, u8 addr, u8 mask) { enc28j60_set_bank(priv, addr); spi_write_op(priv, ENC28J60_BIT_FIELD_CLR, addr, mask); } static void locked_reg_bfclr(struct enc28j60_net *priv, u8 addr, u8 mask) { mutex_lock(&priv->lock); nolock_reg_bfclr(priv, addr, mask); mutex_unlock(&priv->lock); } /* * Register byte read */ static int nolock_regb_read(struct enc28j60_net *priv, u8 address) { enc28j60_set_bank(priv, address); return spi_read_op(priv, ENC28J60_READ_CTRL_REG, address); } static int locked_regb_read(struct enc28j60_net *priv, u8 address) { int ret; mutex_lock(&priv->lock); ret = nolock_regb_read(priv, address); mutex_unlock(&priv->lock); return ret; } /* * Register word read */ static int nolock_regw_read(struct enc28j60_net *priv, u8 address) { int rl, rh; enc28j60_set_bank(priv, address); rl = spi_read_op(priv, ENC28J60_READ_CTRL_REG, address); rh = spi_read_op(priv, ENC28J60_READ_CTRL_REG, address + 1); return (rh << 8) | rl; } static int locked_regw_read(struct enc28j60_net *priv, u8 address) { int ret; mutex_lock(&priv->lock); ret = nolock_regw_read(priv, address); mutex_unlock(&priv->lock); return ret; } /* * Register byte write */ static void nolock_regb_write(struct enc28j60_net *priv, u8 address, u8 data) { enc28j60_set_bank(priv, address); spi_write_op(priv, ENC28J60_WRITE_CTRL_REG, address, data); } static void locked_regb_write(struct enc28j60_net *priv, u8 address, u8 data) { mutex_lock(&priv->lock); nolock_regb_write(priv, address, data); mutex_unlock(&priv->lock); } /* * Register word write */ static void nolock_regw_write(struct enc28j60_net *priv, u8 address, u16 data) { enc28j60_set_bank(priv, address); spi_write_op(priv, ENC28J60_WRITE_CTRL_REG, address, (u8) data); spi_write_op(priv, ENC28J60_WRITE_CTRL_REG, address + 1, (u8) (data >> 8)); } static void locked_regw_write(struct enc28j60_net *priv, u8 address, u16 data) { mutex_lock(&priv->lock); nolock_regw_write(priv, address, data); mutex_unlock(&priv->lock); } /* * Buffer memory read * Select the starting address and execute a SPI buffer read */ static void enc28j60_mem_read(struct enc28j60_net *priv, u16 addr, int len, u8 *data) { mutex_lock(&priv->lock); nolock_regw_write(priv, ERDPTL, addr); #ifdef CONFIG_ENC28J60_WRITEVERIFY if (netif_msg_drv(priv)) { u16 reg; reg = nolock_regw_read(priv, ERDPTL); if (reg != addr) printk(KERN_DEBUG DRV_NAME ": %s() error writing ERDPT " "(0x%04x - 0x%04x)\n", __func__, reg, addr); } #endif spi_read_buf(priv, len, data); mutex_unlock(&priv->lock); } /* * Write packet to enc28j60 TX buffer memory */ static void enc28j60_packet_write(struct enc28j60_net *priv, int len, const u8 *data) { mutex_lock(&priv->lock); /* Set the write pointer to start of transmit buffer area */ nolock_regw_write(priv, EWRPTL, TXSTART_INIT); #ifdef CONFIG_ENC28J60_WRITEVERIFY if (netif_msg_drv(priv)) { u16 reg; reg = nolock_regw_read(priv, EWRPTL); if (reg != TXSTART_INIT) printk(KERN_DEBUG DRV_NAME ": %s() ERWPT:0x%04x != 0x%04x\n", __func__, reg, TXSTART_INIT); } #endif /* Set the TXND pointer to correspond to the packet size given */ nolock_regw_write(priv, ETXNDL, TXSTART_INIT + len); /* write per-packet control byte */ spi_write_op(priv, ENC28J60_WRITE_BUF_MEM, 0, 0x00); if (netif_msg_hw(priv)) printk(KERN_DEBUG DRV_NAME ": %s() after control byte ERWPT:0x%04x\n", __func__, nolock_regw_read(priv, EWRPTL)); /* copy the packet into the transmit buffer */ spi_write_buf(priv, len, data); if (netif_msg_hw(priv)) printk(KERN_DEBUG DRV_NAME ": %s() after write packet ERWPT:0x%04x, len=%d\n", __func__, nolock_regw_read(priv, EWRPTL), len); mutex_unlock(&priv->lock); } static unsigned long msec20_to_jiffies; static int poll_ready(struct enc28j60_net *priv, u8 reg, u8 mask, u8 val) { unsigned long timeout = jiffies + msec20_to_jiffies; /* 20 msec timeout read */ while ((nolock_regb_read(priv, reg) & mask) != val) { if (time_after(jiffies, timeout)) { if (netif_msg_drv(priv)) dev_dbg(&priv->spi->dev, "reg %02x ready timeout!\n", reg); return -ETIMEDOUT; } cpu_relax(); } return 0; } /* * Wait until the PHY operation is complete. */ static int wait_phy_ready(struct enc28j60_net *priv) { return poll_ready(priv, MISTAT, MISTAT_BUSY, 0) ? 0 : 1; } /* * PHY register read * PHY registers are not accessed directly, but through the MII */ static u16 enc28j60_phy_read(struct enc28j60_net *priv, u8 address) { u16 ret; mutex_lock(&priv->lock); /* set the PHY register address */ nolock_regb_write(priv, MIREGADR, address); /* start the register read operation */ nolock_regb_write(priv, MICMD, MICMD_MIIRD); /* wait until the PHY read completes */ wait_phy_ready(priv); /* quit reading */ nolock_regb_write(priv, MICMD, 0x00); /* return the data */ ret = nolock_regw_read(priv, MIRDL); mutex_unlock(&priv->lock); return ret; } static int enc28j60_phy_write(struct enc28j60_net *priv, u8 address, u16 data) { int ret; mutex_lock(&priv->lock); /* set the PHY register address */ nolock_regb_write(priv, MIREGADR, address); /* write the PHY data */ nolock_regw_write(priv, MIWRL, data); /* wait until the PHY write completes and return */ ret = wait_phy_ready(priv); mutex_unlock(&priv->lock); return ret; } /* * Program the hardware MAC address from dev->dev_addr. */ static int enc28j60_set_hw_macaddr(struct net_device *ndev) { int ret; struct enc28j60_net *priv = netdev_priv(ndev); mutex_lock(&priv->lock); if (!priv->hw_enable) { if (netif_msg_drv(priv)) printk(KERN_INFO DRV_NAME ": %s: Setting MAC address to %pM\n", ndev->name, ndev->dev_addr); /* NOTE: MAC address in ENC28J60 is byte-backward */ nolock_regb_write(priv, MAADR5, ndev->dev_addr[0]); nolock_regb_write(priv, MAADR4, ndev->dev_addr[1]); nolock_regb_write(priv, MAADR3, ndev->dev_addr[2]); nolock_regb_write(priv, MAADR2, ndev->dev_addr[3]); nolock_regb_write(priv, MAADR1, ndev->dev_addr[4]); nolock_regb_write(priv, MAADR0, ndev->dev_addr[5]); ret = 0; } else { if (netif_msg_drv(priv)) printk(KERN_DEBUG DRV_NAME ": %s() Hardware must be disabled to set " "Mac address\n", __func__); ret = -EBUSY; } mutex_unlock(&priv->lock); return ret; } /* * Store the new hardware address in dev->dev_addr, and update the MAC. */ static int enc28j60_set_mac_address(struct net_device *dev, void *addr) { struct sockaddr *address = addr; if (netif_running(dev)) return -EBUSY; if (!is_valid_ether_addr(address->sa_data)) return -EADDRNOTAVAIL; memcpy(dev->dev_addr, address->sa_data, dev->addr_len); return enc28j60_set_hw_macaddr(dev); } /* * Debug routine to dump useful register contents */ static void enc28j60_dump_regs(struct enc28j60_net *priv, const char *msg) { mutex_lock(&priv->lock); printk(KERN_DEBUG DRV_NAME " %s\n" "HwRevID: 0x%02x\n" "Cntrl: ECON1 ECON2 ESTAT EIR EIE\n" " 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x\n" "MAC : MACON1 MACON3 MACON4\n" " 0x%02x 0x%02x 0x%02x\n" "Rx : ERXST ERXND ERXWRPT ERXRDPT ERXFCON EPKTCNT MAMXFL\n" " 0x%04x 0x%04x 0x%04x 0x%04x " "0x%02x 0x%02x 0x%04x\n" "Tx : ETXST ETXND MACLCON1 MACLCON2 MAPHSUP\n" " 0x%04x 0x%04x 0x%02x 0x%02x 0x%02x\n", msg, nolock_regb_read(priv, EREVID), nolock_regb_read(priv, ECON1), nolock_regb_read(priv, ECON2), nolock_regb_read(priv, ESTAT), nolock_regb_read(priv, EIR), nolock_regb_read(priv, EIE), nolock_regb_read(priv, MACON1), nolock_regb_read(priv, MACON3), nolock_regb_read(priv, MACON4), nolock_regw_read(priv, ERXSTL), nolock_regw_read(priv, ERXNDL), nolock_regw_read(priv, ERXWRPTL), nolock_regw_read(priv, ERXRDPTL), nolock_regb_read(priv, ERXFCON), nolock_regb_read(priv, EPKTCNT), nolock_regw_read(priv, MAMXFLL), nolock_regw_read(priv, ETXSTL), nolock_regw_read(priv, ETXNDL), nolock_regb_read(priv, MACLCON1), nolock_regb_read(priv, MACLCON2), nolock_regb_read(priv, MAPHSUP)); mutex_unlock(&priv->lock); } /* * ERXRDPT need to be set always at odd addresses, refer to errata datasheet */ static u16 erxrdpt_workaround(u16 next_packet_ptr, u16 start, u16 end) { u16 erxrdpt; if ((next_packet_ptr - 1 < start) || (next_packet_ptr - 1 > end)) erxrdpt = end; else erxrdpt = next_packet_ptr - 1; return erxrdpt; } /* * Calculate wrap around when reading beyond the end of the RX buffer */ static u16 rx_packet_start(u16 ptr) { if (ptr + RSV_SIZE > RXEND_INIT) return (ptr + RSV_SIZE) - (RXEND_INIT - RXSTART_INIT + 1); else return ptr + RSV_SIZE; } static void nolock_rxfifo_init(struct enc28j60_net *priv, u16 start, u16 end) { u16 erxrdpt; if (start > 0x1FFF || end > 0x1FFF || start > end) { if (netif_msg_drv(priv)) printk(KERN_ERR DRV_NAME ": %s(%d, %d) RXFIFO " "bad parameters!\n", __func__, start, end); return; } /* set receive buffer start + end */ priv->next_pk_ptr = start; nolock_regw_write(priv, ERXSTL, start); erxrdpt = erxrdpt_workaround(priv->next_pk_ptr, start, end); nolock_regw_write(priv, ERXRDPTL, erxrdpt); nolock_regw_write(priv, ERXNDL, end); } static void nolock_txfifo_init(struct enc28j60_net *priv, u16 start, u16 end) { if (start > 0x1FFF || end > 0x1FFF || start > end) { if (netif_msg_drv(priv)) printk(KERN_ERR DRV_NAME ": %s(%d, %d) TXFIFO " "bad parameters!\n", __func__, start, end); return; } /* set transmit buffer start + end */ nolock_regw_write(priv, ETXSTL, start); nolock_regw_write(priv, ETXNDL, end); } /* * Low power mode shrinks power consumption about 100x, so we'd like * the chip to be in that mode whenever it's inactive. (However, we * can't stay in lowpower mode during suspend with WOL active.) */ static void enc28j60_lowpower(struct enc28j60_net *priv, bool is_low) { if (netif_msg_drv(priv)) dev_dbg(&priv->spi->dev, "%s power...\n", is_low ? "low" : "high"); mutex_lock(&priv->lock); if (is_low) { nolock_reg_bfclr(priv, ECON1, ECON1_RXEN); poll_ready(priv, ESTAT, ESTAT_RXBUSY, 0); poll_ready(priv, ECON1, ECON1_TXRTS, 0); /* ECON2_VRPS was set during initialization */ nolock_reg_bfset(priv, ECON2, ECON2_PWRSV); } else { nolock_reg_bfclr(priv, ECON2, ECON2_PWRSV); poll_ready(priv, ESTAT, ESTAT_CLKRDY, ESTAT_CLKRDY); /* caller sets ECON1_RXEN */ } mutex_unlock(&priv->lock); } static int enc28j60_hw_init(struct enc28j60_net *priv) { u8 reg; if (netif_msg_drv(priv)) printk(KERN_DEBUG DRV_NAME ": %s() - %s\n", __func__, priv->full_duplex ? "FullDuplex" : "HalfDuplex"); mutex_lock(&priv->lock); /* first reset the chip */ enc28j60_soft_reset(priv); /* Clear ECON1 */ spi_write_op(priv, ENC28J60_WRITE_CTRL_REG, ECON1, 0x00); priv->bank = 0; priv->hw_enable = false; priv->tx_retry_count = 0; priv->max_pk_counter = 0; priv->rxfilter = RXFILTER_NORMAL; /* enable address auto increment and voltage regulator powersave */ nolock_regb_write(priv, ECON2, ECON2_AUTOINC | ECON2_VRPS); nolock_rxfifo_init(priv, RXSTART_INIT, RXEND_INIT); nolock_txfifo_init(priv, TXSTART_INIT, TXEND_INIT); mutex_unlock(&priv->lock); /* * Check the RevID. * If it's 0x00 or 0xFF probably the enc28j60 is not mounted or * damaged */ reg = locked_regb_read(priv, EREVID); if (netif_msg_drv(priv)) printk(KERN_INFO DRV_NAME ": chip RevID: 0x%02x\n", reg); if (reg == 0x00 || reg == 0xff) { if (netif_msg_drv(priv)) printk(KERN_DEBUG DRV_NAME ": %s() Invalid RevId %d\n", __func__, reg); return 0; } /* default filter mode: (unicast OR broadcast) AND crc valid */ locked_regb_write(priv, ERXFCON, ERXFCON_UCEN | ERXFCON_CRCEN | ERXFCON_BCEN); /* enable MAC receive */ locked_regb_write(priv, MACON1, MACON1_MARXEN | MACON1_TXPAUS | MACON1_RXPAUS); /* enable automatic padding and CRC operations */ if (priv->full_duplex) { locked_regb_write(priv, MACON3, MACON3_PADCFG0 | MACON3_TXCRCEN | MACON3_FRMLNEN | MACON3_FULDPX); /* set inter-frame gap (non-back-to-back) */ locked_regb_write(priv, MAIPGL, 0x12); /* set inter-frame gap (back-to-back) */ locked_regb_write(priv, MABBIPG, 0x15); } else { locked_regb_write(priv, MACON3, MACON3_PADCFG0 | MACON3_TXCRCEN | MACON3_FRMLNEN); locked_regb_write(priv, MACON4, 1 << 6); /* DEFER bit */ /* set inter-frame gap (non-back-to-back) */ locked_regw_write(priv, MAIPGL, 0x0C12); /* set inter-frame gap (back-to-back) */ locked_regb_write(priv, MABBIPG, 0x12); } /* * MACLCON1 (default) * MACLCON2 (default) * Set the maximum packet size which the controller will accept */ locked_regw_write(priv, MAMXFLL, MAX_FRAMELEN); /* Configure LEDs */ if (!enc28j60_phy_write(priv, PHLCON, ENC28J60_LAMPS_MODE)) return 0; if (priv->full_duplex) { if (!enc28j60_phy_write(priv, PHCON1, PHCON1_PDPXMD)) return 0; if (!enc28j60_phy_write(priv, PHCON2, 0x00)) return 0; } else { if (!enc28j60_phy_write(priv, PHCON1, 0x00)) return 0; if (!enc28j60_phy_write(priv, PHCON2, PHCON2_HDLDIS)) return 0; } if (netif_msg_hw(priv)) enc28j60_dump_regs(priv, "Hw initialized."); return 1; } static void enc28j60_hw_enable(struct enc28j60_net *priv) { /* enable interrupts */ if (netif_msg_hw(priv)) printk(KERN_DEBUG DRV_NAME ": %s() enabling interrupts.\n", __func__); enc28j60_phy_write(priv, PHIE, PHIE_PGEIE | PHIE_PLNKIE); mutex_lock(&priv->lock); nolock_reg_bfclr(priv, EIR, EIR_DMAIF | EIR_LINKIF | EIR_TXIF | EIR_TXERIF | EIR_RXERIF | EIR_PKTIF); nolock_regb_write(priv, EIE, EIE_INTIE | EIE_PKTIE | EIE_LINKIE | EIE_TXIE | EIE_TXERIE | EIE_RXERIE); /* enable receive logic */ nolock_reg_bfset(priv, ECON1, ECON1_RXEN); priv->hw_enable = true; mutex_unlock(&priv->lock); } static void enc28j60_hw_disable(struct enc28j60_net *priv) { mutex_lock(&priv->lock); /* disable interrutps and packet reception */ nolock_regb_write(priv, EIE, 0x00); nolock_reg_bfclr(priv, ECON1, ECON1_RXEN); priv->hw_enable = false; mutex_unlock(&priv->lock); } static int enc28j60_setlink(struct net_device *ndev, u8 autoneg, u16 speed, u8 duplex) { struct enc28j60_net *priv = netdev_priv(ndev); int ret = 0; if (!priv->hw_enable) { /* link is in low power mode now; duplex setting * will take effect on next enc28j60_hw_init(). */ if (autoneg == AUTONEG_DISABLE && speed == SPEED_10) priv->full_duplex = (duplex == DUPLEX_FULL); else { if (netif_msg_link(priv)) dev_warn(&ndev->dev, "unsupported link setting\n"); ret = -EOPNOTSUPP; } } else { if (netif_msg_link(priv)) dev_warn(&ndev->dev, "Warning: hw must be disabled " "to set link mode\n"); ret = -EBUSY; } return ret; } /* * Read the Transmit Status Vector */ static void enc28j60_read_tsv(struct enc28j60_net *priv, u8 tsv[TSV_SIZE]) { int endptr; endptr = locked_regw_read(priv, ETXNDL); if (netif_msg_hw(priv)) printk(KERN_DEBUG DRV_NAME ": reading TSV at addr:0x%04x\n", endptr + 1); enc28j60_mem_read(priv, endptr + 1, sizeof(tsv), tsv); } static void enc28j60_dump_tsv(struct enc28j60_net *priv, const char *msg, u8 tsv[TSV_SIZE]) { u16 tmp1, tmp2; printk(KERN_DEBUG DRV_NAME ": %s - TSV:\n", msg); tmp1 = tsv[1]; tmp1 <<= 8; tmp1 |= tsv[0]; tmp2 = tsv[5]; tmp2 <<= 8; tmp2 |= tsv[4]; printk(KERN_DEBUG DRV_NAME ": ByteCount: %d, CollisionCount: %d," " TotByteOnWire: %d\n", tmp1, tsv[2] & 0x0f, tmp2); printk(KERN_DEBUG DRV_NAME ": TxDone: %d, CRCErr:%d, LenChkErr: %d," " LenOutOfRange: %d\n", TSV_GETBIT(tsv, TSV_TXDONE), TSV_GETBIT(tsv, TSV_TXCRCERROR), TSV_GETBIT(tsv, TSV_TXLENCHKERROR), TSV_GETBIT(tsv, TSV_TXLENOUTOFRANGE)); printk(KERN_DEBUG DRV_NAME ": Multicast: %d, Broadcast: %d, " "PacketDefer: %d, ExDefer: %d\n", TSV_GETBIT(tsv, TSV_TXMULTICAST), TSV_GETBIT(tsv, TSV_TXBROADCAST), TSV_GETBIT(tsv, TSV_TXPACKETDEFER), TSV_GETBIT(tsv, TSV_TXEXDEFER)); printk(KERN_DEBUG DRV_NAME ": ExCollision: %d, LateCollision: %d, " "Giant: %d, Underrun: %d\n", TSV_GETBIT(tsv, TSV_TXEXCOLLISION), TSV_GETBIT(tsv, TSV_TXLATECOLLISION), TSV_GETBIT(tsv, TSV_TXGIANT), TSV_GETBIT(tsv, TSV_TXUNDERRUN)); printk(KERN_DEBUG DRV_NAME ": ControlFrame: %d, PauseFrame: %d, " "BackPressApp: %d, VLanTagFrame: %d\n", TSV_GETBIT(tsv, TSV_TXCONTROLFRAME), TSV_GETBIT(tsv, TSV_TXPAUSEFRAME), TSV_GETBIT(tsv, TSV_BACKPRESSUREAPP), TSV_GETBIT(tsv, TSV_TXVLANTAGFRAME)); } /* * Receive Status vector */ static void enc28j60_dump_rsv(struct enc28j60_net *priv, const char *msg, u16 pk_ptr, int len, u16 sts) { printk(KERN_DEBUG DRV_NAME ": %s - NextPk: 0x%04x - RSV:\n", msg, pk_ptr); printk(KERN_DEBUG DRV_NAME ": ByteCount: %d, DribbleNibble: %d\n", len, RSV_GETBIT(sts, RSV_DRIBBLENIBBLE)); printk(KERN_DEBUG DRV_NAME ": RxOK: %d, CRCErr:%d, LenChkErr: %d," " LenOutOfRange: %d\n", RSV_GETBIT(sts, RSV_RXOK), RSV_GETBIT(sts, RSV_CRCERROR), RSV_GETBIT(sts, RSV_LENCHECKERR), RSV_GETBIT(sts, RSV_LENOUTOFRANGE)); printk(KERN_DEBUG DRV_NAME ": Multicast: %d, Broadcast: %d, " "LongDropEvent: %d, CarrierEvent: %d\n", RSV_GETBIT(sts, RSV_RXMULTICAST), RSV_GETBIT(sts, RSV_RXBROADCAST), RSV_GETBIT(sts, RSV_RXLONGEVDROPEV), RSV_GETBIT(sts, RSV_CARRIEREV)); printk(KERN_DEBUG DRV_NAME ": ControlFrame: %d, PauseFrame: %d," " UnknownOp: %d, VLanTagFrame: %d\n", RSV_GETBIT(sts, RSV_RXCONTROLFRAME), RSV_GETBIT(sts, RSV_RXPAUSEFRAME), RSV_GETBIT(sts, RSV_RXUNKNOWNOPCODE), RSV_GETBIT(sts, RSV_RXTYPEVLAN)); } static void dump_packet(const char *msg, int len, const char *data) { printk(KERN_DEBUG DRV_NAME ": %s - packet len:%d\n", msg, len); print_hex_dump(KERN_DEBUG, "pk data: ", DUMP_PREFIX_OFFSET, 16, 1, data, len, true); } /* * Hardware receive function. * Read the buffer memory, update the FIFO pointer to free the buffer, * check the status vector and decrement the packet counter. */ static void enc28j60_hw_rx(struct net_device *ndev) { struct enc28j60_net *priv = netdev_priv(ndev); struct sk_buff *skb = NULL; u16 erxrdpt, next_packet, rxstat; u8 rsv[RSV_SIZE]; int len; if (netif_msg_rx_status(priv)) printk(KERN_DEBUG DRV_NAME ": RX pk_addr:0x%04x\n", priv->next_pk_ptr); if (unlikely(priv->next_pk_ptr > RXEND_INIT)) { if (netif_msg_rx_err(priv)) dev_err(&ndev->dev, "%s() Invalid packet address!! 0x%04x\n", __func__, priv->next_pk_ptr); /* packet address corrupted: reset RX logic */ mutex_lock(&priv->lock); nolock_reg_bfclr(priv, ECON1, ECON1_RXEN); nolock_reg_bfset(priv, ECON1, ECON1_RXRST); nolock_reg_bfclr(priv, ECON1, ECON1_RXRST); nolock_rxfifo_init(priv, RXSTART_INIT, RXEND_INIT); nolock_reg_bfclr(priv, EIR, EIR_RXERIF); nolock_reg_bfset(priv, ECON1, ECON1_RXEN); mutex_unlock(&priv->lock); ndev->stats.rx_errors++; return; } /* Read next packet pointer and rx status vector */ enc28j60_mem_read(priv, priv->next_pk_ptr, sizeof(rsv), rsv); next_packet = rsv[1]; next_packet <<= 8; next_packet |= rsv[0]; len = rsv[3]; len <<= 8; len |= rsv[2]; rxstat = rsv[5]; rxstat <<= 8; rxstat |= rsv[4]; if (netif_msg_rx_status(priv)) enc28j60_dump_rsv(priv, __func__, next_packet, len, rxstat); if (!RSV_GETBIT(rxstat, RSV_RXOK) || len > MAX_FRAMELEN) { if (netif_msg_rx_err(priv)) dev_err(&ndev->dev, "Rx Error (%04x)\n", rxstat); ndev->stats.rx_errors++; if (RSV_GETBIT(rxstat, RSV_CRCERROR)) ndev->stats.rx_crc_errors++; if (RSV_GETBIT(rxstat, RSV_LENCHECKERR)) ndev->stats.rx_frame_errors++; if (len > MAX_FRAMELEN) ndev->stats.rx_over_errors++; } else { skb = dev_alloc_skb(len + NET_IP_ALIGN); if (!skb) { if (netif_msg_rx_err(priv)) dev_err(&ndev->dev, "out of memory for Rx'd frame\n"); ndev->stats.rx_dropped++; } else { skb->dev = ndev; skb_reserve(skb, NET_IP_ALIGN); /* copy the packet from the receive buffer */ enc28j60_mem_read(priv, rx_packet_start(priv->next_pk_ptr), len, skb_put(skb, len)); if (netif_msg_pktdata(priv)) dump_packet(__func__, skb->len, skb->data); skb->protocol = eth_type_trans(skb, ndev); /* update statistics */ ndev->stats.rx_packets++; ndev->stats.rx_bytes += len; netif_rx_ni(skb); } } /* * Move the RX read pointer to the start of the next * received packet. * This frees the memory we just read out */ erxrdpt = erxrdpt_workaround(next_packet, RXSTART_INIT, RXEND_INIT); if (netif_msg_hw(priv)) printk(KERN_DEBUG DRV_NAME ": %s() ERXRDPT:0x%04x\n", __func__, erxrdpt); mutex_lock(&priv->lock); nolock_regw_write(priv, ERXRDPTL, erxrdpt); #ifdef CONFIG_ENC28J60_WRITEVERIFY if (netif_msg_drv(priv)) { u16 reg; reg = nolock_regw_read(priv, ERXRDPTL); if (reg != erxrdpt) printk(KERN_DEBUG DRV_NAME ": %s() ERXRDPT verify " "error (0x%04x - 0x%04x)\n", __func__, reg, erxrdpt); } #endif priv->next_pk_ptr = next_packet; /* we are done with this packet, decrement the packet counter */ nolock_reg_bfset(priv, ECON2, ECON2_PKTDEC); mutex_unlock(&priv->lock); } /* * Calculate free space in RxFIFO */ static int enc28j60_get_free_rxfifo(struct enc28j60_net *priv) { int epkcnt, erxst, erxnd, erxwr, erxrd; int free_space; mutex_lock(&priv->lock); epkcnt = nolock_regb_read(priv, EPKTCNT); if (epkcnt >= 255) free_space = -1; else { erxst = nolock_regw_read(priv, ERXSTL); erxnd = nolock_regw_read(priv, ERXNDL); erxwr = nolock_regw_read(priv, ERXWRPTL); erxrd = nolock_regw_read(priv, ERXRDPTL); if (erxwr > erxrd) free_space = (erxnd - erxst) - (erxwr - erxrd); else if (erxwr == erxrd) free_space = (erxnd - erxst); else free_space = erxrd - erxwr - 1; } mutex_unlock(&priv->lock); if (netif_msg_rx_status(priv)) printk(KERN_DEBUG DRV_NAME ": %s() free_space = %d\n", __func__, free_space); return free_space; } /* * Access the PHY to determine link status */ static void enc28j60_check_link_status(struct net_device *ndev) { struct enc28j60_net *priv = netdev_priv(ndev); u16 reg; int duplex; reg = enc28j60_phy_read(priv, PHSTAT2); if (netif_msg_hw(priv)) printk(KERN_DEBUG DRV_NAME ": %s() PHSTAT1: %04x, " "PHSTAT2: %04x\n", __func__, enc28j60_phy_read(priv, PHSTAT1), reg); duplex = reg & PHSTAT2_DPXSTAT; if (reg & PHSTAT2_LSTAT) { netif_carrier_on(ndev); if (netif_msg_ifup(priv)) dev_info(&ndev->dev, "link up - %s\n", duplex ? "Full duplex" : "Half duplex"); } else { if (netif_msg_ifdown(priv)) dev_info(&ndev->dev, "link down\n"); netif_carrier_off(ndev); } } static void enc28j60_tx_clear(struct net_device *ndev, bool err) { struct enc28j60_net *priv = netdev_priv(ndev); if (err) ndev->stats.tx_errors++; else ndev->stats.tx_packets++; if (priv->tx_skb) { if (!err) ndev->stats.tx_bytes += priv->tx_skb->len; dev_kfree_skb(priv->tx_skb); priv->tx_skb = NULL; } locked_reg_bfclr(priv, ECON1, ECON1_TXRTS); netif_wake_queue(ndev); } /* * RX handler * ignore PKTIF because is unreliable! (look at the errata datasheet) * check EPKTCNT is the suggested workaround. * We don't need to clear interrupt flag, automatically done when * enc28j60_hw_rx() decrements the packet counter. * Returns how many packet processed. */ static int enc28j60_rx_interrupt(struct net_device *ndev) { struct enc28j60_net *priv = netdev_priv(ndev); int pk_counter, ret; pk_counter = locked_regb_read(priv, EPKTCNT); if (pk_counter && netif_msg_intr(priv)) printk(KERN_DEBUG DRV_NAME ": intRX, pk_cnt: %d\n", pk_counter); if (pk_counter > priv->max_pk_counter) { /* update statistics */ priv->max_pk_counter = pk_counter; if (netif_msg_rx_status(priv) && priv->max_pk_counter > 1) printk(KERN_DEBUG DRV_NAME ": RX max_pk_cnt: %d\n", priv->max_pk_counter); } ret = pk_counter; while (pk_counter-- > 0) enc28j60_hw_rx(ndev); return ret; } static void enc28j60_irq_work_handler(struct work_struct *work) { struct enc28j60_net *priv = container_of(work, struct enc28j60_net, irq_work); struct net_device *ndev = priv->netdev; int intflags, loop; if (netif_msg_intr(priv)) printk(KERN_DEBUG DRV_NAME ": %s() enter\n", __func__); /* disable further interrupts */ locked_reg_bfclr(priv, EIE, EIE_INTIE); do { loop = 0; intflags = locked_regb_read(priv, EIR); /* DMA interrupt handler (not currently used) */ if ((intflags & EIR_DMAIF) != 0) { loop++; if (netif_msg_intr(priv)) printk(KERN_DEBUG DRV_NAME ": intDMA(%d)\n", loop); locked_reg_bfclr(priv, EIR, EIR_DMAIF); } /* LINK changed handler */ if ((intflags & EIR_LINKIF) != 0) { loop++; if (netif_msg_intr(priv)) printk(KERN_DEBUG DRV_NAME ": intLINK(%d)\n", loop); enc28j60_check_link_status(ndev); /* read PHIR to clear the flag */ enc28j60_phy_read(priv, PHIR); } /* TX complete handler */ if ((intflags & EIR_TXIF) != 0) { bool err = false; loop++; if (netif_msg_intr(priv)) printk(KERN_DEBUG DRV_NAME ": intTX(%d)\n", loop); priv->tx_retry_count = 0; if (locked_regb_read(priv, ESTAT) & ESTAT_TXABRT) { if (netif_msg_tx_err(priv)) dev_err(&ndev->dev, "Tx Error (aborted)\n"); err = true; } if (netif_msg_tx_done(priv)) { u8 tsv[TSV_SIZE]; enc28j60_read_tsv(priv, tsv); enc28j60_dump_tsv(priv, "Tx Done", tsv); } enc28j60_tx_clear(ndev, err); locked_reg_bfclr(priv, EIR, EIR_TXIF); } /* TX Error handler */ if ((intflags & EIR_TXERIF) != 0) { u8 tsv[TSV_SIZE]; loop++; if (netif_msg_intr(priv)) printk(KERN_DEBUG DRV_NAME ": intTXErr(%d)\n", loop); locked_reg_bfclr(priv, ECON1, ECON1_TXRTS); enc28j60_read_tsv(priv, tsv); if (netif_msg_tx_err(priv)) enc28j60_dump_tsv(priv, "Tx Error", tsv); /* Reset TX logic */ mutex_lock(&priv->lock); nolock_reg_bfset(priv, ECON1, ECON1_TXRST); nolock_reg_bfclr(priv, ECON1, ECON1_TXRST); nolock_txfifo_init(priv, TXSTART_INIT, TXEND_INIT); mutex_unlock(&priv->lock); /* Transmit Late collision check for retransmit */ if (TSV_GETBIT(tsv, TSV_TXLATECOLLISION)) { if (netif_msg_tx_err(priv)) printk(KERN_DEBUG DRV_NAME ": LateCollision TXErr (%d)\n", priv->tx_retry_count); if (priv->tx_retry_count++ < MAX_TX_RETRYCOUNT) locked_reg_bfset(priv, ECON1, ECON1_TXRTS); else enc28j60_tx_clear(ndev, true); } else enc28j60_tx_clear(ndev, true); locked_reg_bfclr(priv, EIR, EIR_TXERIF); } /* RX Error handler */ if ((intflags & EIR_RXERIF) != 0) { loop++; if (netif_msg_intr(priv)) printk(KERN_DEBUG DRV_NAME ": intRXErr(%d)\n", loop); /* Check free FIFO space to flag RX overrun */ if (enc28j60_get_free_rxfifo(priv) <= 0) { if (netif_msg_rx_err(priv)) printk(KERN_DEBUG DRV_NAME ": RX Overrun\n"); ndev->stats.rx_dropped++; } locked_reg_bfclr(priv, EIR, EIR_RXERIF); } /* RX handler */ if (enc28j60_rx_interrupt(ndev)) loop++; } while (loop); /* re-enable interrupts */ locked_reg_bfset(priv, EIE, EIE_INTIE); if (netif_msg_intr(priv)) printk(KERN_DEBUG DRV_NAME ": %s() exit\n", __func__); } /* * Hardware transmit function. * Fill the buffer memory and send the contents of the transmit buffer * onto the network */ static void enc28j60_hw_tx(struct enc28j60_net *priv) { if (netif_msg_tx_queued(priv)) printk(KERN_DEBUG DRV_NAME ": Tx Packet Len:%d\n", priv->tx_skb->len); if (netif_msg_pktdata(priv)) dump_packet(__func__, priv->tx_skb->len, priv->tx_skb->data); enc28j60_packet_write(priv, priv->tx_skb->len, priv->tx_skb->data); #ifdef CONFIG_ENC28J60_WRITEVERIFY /* readback and verify written data */ if (netif_msg_drv(priv)) { int test_len, k; u8 test_buf[64]; /* limit the test to the first 64 bytes */ int okflag; test_len = priv->tx_skb->len; if (test_len > sizeof(test_buf)) test_len = sizeof(test_buf); /* + 1 to skip control byte */ enc28j60_mem_read(priv, TXSTART_INIT + 1, test_len, test_buf); okflag = 1; for (k = 0; k < test_len; k++) { if (priv->tx_skb->data[k] != test_buf[k]) { printk(KERN_DEBUG DRV_NAME ": Error, %d location differ: " "0x%02x-0x%02x\n", k, priv->tx_skb->data[k], test_buf[k]); okflag = 0; } } if (!okflag) printk(KERN_DEBUG DRV_NAME ": Tx write buffer, " "verify ERROR!\n"); } #endif /* set TX request flag */ locked_reg_bfset(priv, ECON1, ECON1_TXRTS); } static netdev_tx_t enc28j60_send_packet(struct sk_buff *skb, struct net_device *dev) { struct enc28j60_net *priv = netdev_priv(dev); if (netif_msg_tx_queued(priv)) printk(KERN_DEBUG DRV_NAME ": %s() enter\n", __func__); /* If some error occurs while trying to transmit this * packet, you should return '1' from this function. * In such a case you _may not_ do anything to the * SKB, it is still owned by the network queueing * layer when an error is returned. This means you * may not modify any SKB fields, you may not free * the SKB, etc. */ netif_stop_queue(dev); /* save the timestamp */ priv->netdev->trans_start = jiffies; /* Remember the skb for deferred processing */ priv->tx_skb = skb; schedule_work(&priv->tx_work); return NETDEV_TX_OK; } static void enc28j60_tx_work_handler(struct work_struct *work) { struct enc28j60_net *priv = container_of(work, struct enc28j60_net, tx_work); /* actual delivery of data */ enc28j60_hw_tx(priv); } static irqreturn_t enc28j60_irq(int irq, void *dev_id) { struct enc28j60_net *priv = dev_id; /* * Can't do anything in interrupt context because we need to * block (spi_sync() is blocking) so fire of the interrupt * handling workqueue. * Remember that we access enc28j60 registers through SPI bus * via spi_sync() call. */ schedule_work(&priv->irq_work); return IRQ_HANDLED; } static void enc28j60_tx_timeout(struct net_device *ndev) { struct enc28j60_net *priv = netdev_priv(ndev); if (netif_msg_timer(priv)) dev_err(&ndev->dev, DRV_NAME " tx timeout\n"); ndev->stats.tx_errors++; /* can't restart safely under softirq */ schedule_work(&priv->restart_work); } /* * Open/initialize the board. This is called (in the current kernel) * sometime after booting when the 'ifconfig' program is run. * * This routine should set everything up anew at each open, even * registers that "should" only need to be set once at boot, so that * there is non-reboot way to recover if something goes wrong. */ static int enc28j60_net_open(struct net_device *dev) { struct enc28j60_net *priv = netdev_priv(dev); if (netif_msg_drv(priv)) printk(KERN_DEBUG DRV_NAME ": %s() enter\n", __func__); if (!is_valid_ether_addr(dev->dev_addr)) { if (netif_msg_ifup(priv)) dev_err(&dev->dev, "invalid MAC address %pM\n", dev->dev_addr); return -EADDRNOTAVAIL; } /* Reset the hardware here (and take it out of low power mode) */ enc28j60_lowpower(priv, false); enc28j60_hw_disable(priv); if (!enc28j60_hw_init(priv)) { if (netif_msg_ifup(priv)) dev_err(&dev->dev, "hw_reset() failed\n"); return -EINVAL; } /* Update the MAC address (in case user has changed it) */ enc28j60_set_hw_macaddr(dev); /* Enable interrupts */ enc28j60_hw_enable(priv); /* check link status */ enc28j60_check_link_status(dev); /* We are now ready to accept transmit requests from * the queueing layer of the networking. */ netif_start_queue(dev); return 0; } /* The inverse routine to net_open(). */ static int enc28j60_net_close(struct net_device *dev) { struct enc28j60_net *priv = netdev_priv(dev); if (netif_msg_drv(priv)) printk(KERN_DEBUG DRV_NAME ": %s() enter\n", __func__); enc28j60_hw_disable(priv); enc28j60_lowpower(priv, true); netif_stop_queue(dev); return 0; } /* * Set or clear the multicast filter for this adapter * num_addrs == -1 Promiscuous mode, receive all packets * num_addrs == 0 Normal mode, filter out multicast packets * num_addrs > 0 Multicast mode, receive normal and MC packets */ static void enc28j60_set_multicast_list(struct net_device *dev) { struct enc28j60_net *priv = netdev_priv(dev); int oldfilter = priv->rxfilter; if (dev->flags & IFF_PROMISC) { if (netif_msg_link(priv)) dev_info(&dev->dev, "promiscuous mode\n"); priv->rxfilter = RXFILTER_PROMISC; } else if ((dev->flags & IFF_ALLMULTI) || !netdev_mc_empty(dev)) { if (netif_msg_link(priv)) dev_info(&dev->dev, "%smulticast mode\n", (dev->flags & IFF_ALLMULTI) ? "all-" : ""); priv->rxfilter = RXFILTER_MULTI; } else { if (netif_msg_link(priv)) dev_info(&dev->dev, "normal mode\n"); priv->rxfilter = RXFILTER_NORMAL; } if (oldfilter != priv->rxfilter) schedule_work(&priv->setrx_work); } static void enc28j60_setrx_work_handler(struct work_struct *work) { struct enc28j60_net *priv = container_of(work, struct enc28j60_net, setrx_work); if (priv->rxfilter == RXFILTER_PROMISC) { if (netif_msg_drv(priv)) printk(KERN_DEBUG DRV_NAME ": promiscuous mode\n"); locked_regb_write(priv, ERXFCON, 0x00); } else if (priv->rxfilter == RXFILTER_MULTI) { if (netif_msg_drv(priv)) printk(KERN_DEBUG DRV_NAME ": multicast mode\n"); locked_regb_write(priv, ERXFCON, ERXFCON_UCEN | ERXFCON_CRCEN | ERXFCON_BCEN | ERXFCON_MCEN); } else { if (netif_msg_drv(priv)) printk(KERN_DEBUG DRV_NAME ": normal mode\n"); locked_regb_write(priv, ERXFCON, ERXFCON_UCEN | ERXFCON_CRCEN | ERXFCON_BCEN); } } static void enc28j60_restart_work_handler(struct work_struct *work) { struct enc28j60_net *priv = container_of(work, struct enc28j60_net, restart_work); struct net_device *ndev = priv->netdev; int ret; rtnl_lock(); if (netif_running(ndev)) { enc28j60_net_close(ndev); ret = enc28j60_net_open(ndev); if (unlikely(ret)) { dev_info(&ndev->dev, " could not restart %d\n", ret); dev_close(ndev); } } rtnl_unlock(); } /* ......................... ETHTOOL SUPPORT ........................... */ static void enc28j60_get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info) { strlcpy(info->driver, DRV_NAME, sizeof(info->driver)); strlcpy(info->version, DRV_VERSION, sizeof(info->version)); strlcpy(info->bus_info, dev_name(dev->dev.parent), sizeof(info->bus_info)); } static int enc28j60_get_settings(struct net_device *dev, struct ethtool_cmd *cmd) { struct enc28j60_net *priv = netdev_priv(dev); cmd->transceiver = XCVR_INTERNAL; cmd->supported = SUPPORTED_10baseT_Half | SUPPORTED_10baseT_Full | SUPPORTED_TP; cmd->speed = SPEED_10; cmd->duplex = priv->full_duplex ? DUPLEX_FULL : DUPLEX_HALF; cmd->port = PORT_TP; cmd->autoneg = AUTONEG_DISABLE; return 0; } static int enc28j60_set_settings(struct net_device *dev, struct ethtool_cmd *cmd) { return enc28j60_setlink(dev, cmd->autoneg, cmd->speed, cmd->duplex); } static u32 enc28j60_get_msglevel(struct net_device *dev) { struct enc28j60_net *priv = netdev_priv(dev); return priv->msg_enable; } static void enc28j60_set_msglevel(struct net_device *dev, u32 val) { struct enc28j60_net *priv = netdev_priv(dev); priv->msg_enable = val; } static const struct ethtool_ops enc28j60_ethtool_ops = { .get_settings = enc28j60_get_settings, .set_settings = enc28j60_set_settings, .get_drvinfo = enc28j60_get_drvinfo, .get_msglevel = enc28j60_get_msglevel, .set_msglevel = enc28j60_set_msglevel, }; static int enc28j60_chipset_init(struct net_device *dev) { struct enc28j60_net *priv = netdev_priv(dev); return enc28j60_hw_init(priv); } static const struct net_device_ops enc28j60_netdev_ops = { .ndo_open = enc28j60_net_open, .ndo_stop = enc28j60_net_close, .ndo_start_xmit = enc28j60_send_packet, .ndo_set_multicast_list = enc28j60_set_multicast_list, .ndo_set_mac_address = enc28j60_set_mac_address, .ndo_tx_timeout = enc28j60_tx_timeout, .ndo_change_mtu = eth_change_mtu, .ndo_validate_addr = eth_validate_addr, }; static int __devinit enc28j60_probe(struct spi_device *spi) { struct net_device *dev; struct enc28j60_net *priv; int ret = 0; if (netif_msg_drv(&debug)) dev_info(&spi->dev, DRV_NAME " Ethernet driver %s loaded\n", DRV_VERSION); dev = alloc_etherdev(sizeof(struct enc28j60_net)); if (!dev) { if (netif_msg_drv(&debug)) dev_err(&spi->dev, DRV_NAME ": unable to alloc new ethernet\n"); ret = -ENOMEM; goto error_alloc; } priv = netdev_priv(dev); priv->netdev = dev; /* priv to netdev reference */ priv->spi = spi; /* priv to spi reference */ priv->msg_enable = netif_msg_init(debug.msg_enable, ENC28J60_MSG_DEFAULT); mutex_init(&priv->lock); INIT_WORK(&priv->tx_work, enc28j60_tx_work_handler); INIT_WORK(&priv->setrx_work, enc28j60_setrx_work_handler); INIT_WORK(&priv->irq_work, enc28j60_irq_work_handler); INIT_WORK(&priv->restart_work, enc28j60_restart_work_handler); dev_set_drvdata(&spi->dev, priv); /* spi to priv reference */ SET_NETDEV_DEV(dev, &spi->dev); if (!enc28j60_chipset_init(dev)) { if (netif_msg_probe(priv)) dev_info(&spi->dev, DRV_NAME " chip not found\n"); ret = -EIO; goto error_irq; } random_ether_addr(dev->dev_addr); enc28j60_set_hw_macaddr(dev); /* Board setup must set the relevant edge trigger type; * level triggers won't currently work. */ ret = request_irq(spi->irq, enc28j60_irq, 0, DRV_NAME, priv); if (ret < 0) { if (netif_msg_probe(priv)) dev_err(&spi->dev, DRV_NAME ": request irq %d failed " "(ret = %d)\n", spi->irq, ret); goto error_irq; } dev->if_port = IF_PORT_10BASET; dev->irq = spi->irq; dev->netdev_ops = &enc28j60_netdev_ops; dev->watchdog_timeo = TX_TIMEOUT; SET_ETHTOOL_OPS(dev, &enc28j60_ethtool_ops); enc28j60_lowpower(priv, true); ret = register_netdev(dev); if (ret) { if (netif_msg_probe(priv)) dev_err(&spi->dev, "register netdev " DRV_NAME " failed (ret = %d)\n", ret); goto error_register; } dev_info(&dev->dev, DRV_NAME " driver registered\n"); return 0; error_register: free_irq(spi->irq, priv); error_irq: free_netdev(dev); error_alloc: return ret; } static int __devexit enc28j60_remove(struct spi_device *spi) { struct enc28j60_net *priv = dev_get_drvdata(&spi->dev); if (netif_msg_drv(priv)) printk(KERN_DEBUG DRV_NAME ": remove\n"); unregister_netdev(priv->netdev); free_irq(spi->irq, priv); free_netdev(priv->netdev); return 0; } static struct spi_driver enc28j60_driver = { .driver = { .name = DRV_NAME, .owner = THIS_MODULE, }, .probe = enc28j60_probe, .remove = __devexit_p(enc28j60_remove), }; static int __init enc28j60_init(void) { msec20_to_jiffies = msecs_to_jiffies(20); return spi_register_driver(&enc28j60_driver); } module_init(enc28j60_init); static void __exit enc28j60_exit(void) { spi_unregister_driver(&enc28j60_driver); } module_exit(enc28j60_exit); MODULE_DESCRIPTION(DRV_NAME " ethernet driver"); MODULE_AUTHOR("Claudio Lanconelli <[email protected]>"); MODULE_LICENSE("GPL"); module_param_named(debug, debug.msg_enable, int, 0); MODULE_PARM_DESC(debug, "Debug verbosity level (0=none, ..., ffff=all)"); MODULE_ALIAS("spi:" DRV_NAME);
grate-driver/linux-2.6
drivers/net/enc28j60.c
C
gpl-2.0
45,588
/* APPLE LOCAL file v7 merge */ /* Test the `vreinterprets8_s32' ARM Neon intrinsic. */ /* This file was autogenerated by neon-testgen. */ /* { dg-do assemble } */ /* { dg-require-effective-target arm_neon_ok } */ /* { dg-options "-save-temps -O0 -mfpu=neon -mfloat-abi=softfp" } */ #include "arm_neon.h" void test_vreinterprets8_s32 (void) { int8x8_t out_int8x8_t; int32x2_t arg0_int32x2_t; out_int8x8_t = vreinterpret_s8_s32 (arg0_int32x2_t); } /* { dg-final { cleanup-saved-temps } } */
unofficial-opensource-apple/llvmgcc42
gcc/testsuite/gcc.target/arm/neon/vreinterprets8_s32.c
C
gpl-2.0
503
/******************************************************************************* * mt6575_pwm.h PWM Drvier * * Copyright (c) 2010, Media Teck.inc * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public Licence, * version 2, as publish by the Free Software Foundation. * * This program is distributed and in hope it will be useful, but WITHOUT * ANY WARRNTY; without even the implied warranty of MERCHANTABITLITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * ******************************************************************************** * Author : Chagnlei Gao ([email protected]) ******************************************************************************** */ #ifndef __MT_PWM_HAL_H__ #define __MT_PWM_HAL_H__ #include <mach/mt_reg_base.h> #include <mach/mt_typedefs.h> #include <mach/mt_clkmgr.h> #include <mach/mt_gpio.h> #include <mach/irqs.h> #include <mach/upmu_common.h> #include <mach/sync_write.h> /********************************** * Global enum data ***********************************/ enum PWN_NO{ PWM_MIN, PWM1 = PWM_MIN, PWM2, PWM3, PWM4, PWM5, PWM_NUM, PWM_MAX=PWM_NUM }; enum TEST_SEL_BIT{ TEST_SEL_FALSE, TEST_SEL_TRUE }; enum PWM_CON_MODE_BIT{ PERIOD, RAND }; enum PWM_CON_SRCSEL_BIT{ PWM_FIFO, MEMORY }; enum PWM_CON_IDLE_BIT{ IDLE_FALSE, IDLE_TRUE, IDLE_MAX }; enum PWM_CON_GUARD_BIT{ GUARD_FALSE, GUARD_TRUE, GUARD_MAX }; enum OLD_MODE_BIT{ OLDMODE_DISABLE, OLDMODE_ENABLE }; enum PWM_BUF_VALID_BIT{ BUF0_VALID, BUF0_EN_VALID, BUF1_VALID, BUF1_EN_VALID, BUF_EN_MAX }; enum CLOCK_SRC{ CLK_BLOCK, CLK_BLOCK_BY_1625_OR_32K }; enum PWM_CLK_DIV{ CLK_DIV_MIN, CLK_DIV1 = CLK_DIV_MIN, CLK_DIV2, CLK_DIV4, CLK_DIV8, CLK_DIV16, CLK_DIV32, CLK_DIV64, CLK_DIV128, CLK_DIV_MAX }; enum PWM_INT_ENABLE_BITS{ PWM1_INT_FINISH_EN, PWM1_INT_UNDERFLOW_EN, PWM2_INT_FINISH_EN, PWM2_INT_UNDERFLOW_EN, PWM3_INT_FINISH_EN, PWM3_INT_UNDERFLOW_EN, PWM4_INT_FINISH_EN, PWM4_INT_UNDERFLOW_EN, PWM5_INT_FINISH_EN, PWM5_INT_UNDERFLOW_EN, PWM_INT_ENABLE_BITS_MAX, }; enum PWM_INT_STATUS_BITS{ PWM1_INT_FINISH_ST, PWM1_INT_UNDERFLOW_ST, PWM2_INT_FINISH_ST, PWM2_INT_UNDERFLOW_ST, PWM3_INT_FINISH_ST, PWM3_INT_UNDERFLOW_ST, PWM4_INT_FINISH_ST, PWM4_INT_UNDERFLOW_ST, PWM5_INT_FINISH_ST, PWM5_INT_UNDERFLOW_ST, PWM_INT_STATUS_BITS_MAX, }; enum PWM_INT_ACK_BITS{ PWM1_INT_FINISH_ACK, PWM1_INT_UNDERFLOW_ACK, PWM2_INT_FINISH_ACK, PWM2_INT_UNDERFLOW_ACK, PWM3_INT_FINISH_ACK, PWM3_INT_UNDERFLOW_ACK, PWM4_INT_FINISH_ACK, PWM4_INT_UNDERFLOW_ACK, PWM5_INT_FINISH_ACK, PWM5_INT_UNDERFLOW_ACK, PWM_INT_ACK_BITS_MAX, }; enum PWM_CLOCK_SRC_ENUM{ PWM_CLK_SRC_MIN, PWM_CLK_OLD_MODE_BLOCK = PWM_CLK_SRC_MIN, PWM_CLK_OLD_MODE_32K, PWM_CLK_NEW_MODE_BLOCK, PWM_CLK_NEW_MODE_BLOCK_DIV_BY_1625, PWM_CLK_SRC_NUM, PWM_CLK_SRC_INVALID, }; enum PWM_MODE_ENUM{ PWM_MODE_MIN, PWM_MODE_OLD = PWM_MODE_MIN, PWM_MODE_FIFO, PWM_MODE_MEMORY, PWM_MODE_RANDOM, PWM_MODE_DELAY, PWM_MODE_INVALID, }; #define PWM_NEW_MODE_DUTY_TOTAL_BITS 64 void mt_set_pwm_3dlcm_enable_hal(BOOL enable); void mt_set_pwm_3dlcm_inv_hal(U32 pwm_no, BOOL inv); void mt_set_pwm_3dlcm_base_hal(U32 pwm_no); void mt_pwm_26M_clk_enable_hal(U32 enable); #endif
visi0nary/mediatek
mt6592/mediatek/platform/mt6592/kernel/core/include/mach/mt_pwm_hal.h
C
gpl-2.0
4,103
/* * This file is part of the CMaNGOS Project. See AUTHORS file for Copyright information * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef MANGOS_CREATURE_EAI_H #define MANGOS_CREATURE_EAI_H #include "Common.h" #include "Creature.h" #include "CreatureAI.h" #include "Unit.h" class Player; class WorldObject; #define EVENT_UPDATE_TIME 500 #define MAX_ACTIONS 3 #define MAX_PHASE 32 enum EventAI_Type { EVENT_T_TIMER_IN_COMBAT = 0, // InitialMin, InitialMax, RepeatMin, RepeatMax EVENT_T_TIMER_OOC = 1, // InitialMin, InitialMax, RepeatMin, RepeatMax EVENT_T_HP = 2, // HPMax%, HPMin%, RepeatMin, RepeatMax EVENT_T_MANA = 3, // ManaMax%,ManaMin% RepeatMin, RepeatMax EVENT_T_AGGRO = 4, // NONE EVENT_T_KILL = 5, // RepeatMin, RepeatMax EVENT_T_DEATH = 6, // NONE EVENT_T_EVADE = 7, // NONE EVENT_T_SPELLHIT = 8, // SpellID, School, RepeatMin, RepeatMax EVENT_T_RANGE = 9, // MinDist, MaxDist, RepeatMin, RepeatMax EVENT_T_OOC_LOS = 10, // NoHostile, MaxRnage, RepeatMin, RepeatMax EVENT_T_SPAWNED = 11, // Condition, CondValue1 EVENT_T_TARGET_HP = 12, // HPMax%, HPMin%, RepeatMin, RepeatMax EVENT_T_TARGET_CASTING = 13, // RepeatMin, RepeatMax EVENT_T_FRIENDLY_HP = 14, // HPDeficit, Radius, RepeatMin, RepeatMax EVENT_T_FRIENDLY_IS_CC = 15, // DispelType, Radius, RepeatMin, RepeatMax EVENT_T_FRIENDLY_MISSING_BUFF = 16, // SpellId, Radius, RepeatMin, RepeatMax EVENT_T_SUMMONED_UNIT = 17, // CreatureId, RepeatMin, RepeatMax EVENT_T_TARGET_MANA = 18, // ManaMax%, ManaMin%, RepeatMin, RepeatMax EVENT_T_QUEST_ACCEPT = 19, // QuestID EVENT_T_QUEST_COMPLETE = 20, // EVENT_T_REACHED_HOME = 21, // NONE EVENT_T_RECEIVE_EMOTE = 22, // EmoteId, Condition, CondValue1, CondValue2 EVENT_T_AURA = 23, // Param1 = SpellID, Param2 = Number of time stacked, Param3/4 Repeat Min/Max EVENT_T_TARGET_AURA = 24, // Param1 = SpellID, Param2 = Number of time stacked, Param3/4 Repeat Min/Max EVENT_T_SUMMONED_JUST_DIED = 25, // CreatureId, RepeatMin, RepeatMax EVENT_T_SUMMONED_JUST_DESPAWN = 26, // CreatureId, RepeatMin, RepeatMax EVENT_T_MISSING_AURA = 27, // Param1 = SpellID, Param2 = Number of time stacked expected, Param3/4 Repeat Min/Max EVENT_T_TARGET_MISSING_AURA = 28, // Param1 = SpellID, Param2 = Number of time stacked expected, Param3/4 Repeat Min/Max EVENT_T_TIMER_GENERIC = 29, // InitialMin, InitialMax, RepeatMin, RepeatMax EVENT_T_RECEIVE_AI_EVENT = 30, // AIEventType, Sender-Entry, unused, unused EVENT_T_ENERGY = 31, // EnergyMax%, EnergyMin%, RepeatMin, RepeatMax EVENT_T_END, }; enum EventAI_ActionType { ACTION_T_NONE = 0, // No action ACTION_T_TEXT = 1, // TextId1, optionally -TextId2, optionally -TextId3(if -TextId2 exist). If more than just -TextId1 is defined, randomize. Negative values. ACTION_T_SET_FACTION = 2, // FactionId (or 0 for default) ACTION_T_MORPH_TO_ENTRY_OR_MODEL = 3, // Creature_template entry(param1) OR ModelId (param2) (or 0 for both to demorph) ACTION_T_SOUND = 4, // SoundId ACTION_T_EMOTE = 5, // EmoteId ACTION_T_RANDOM_SAY = 6, // UNUSED ACTION_T_RANDOM_YELL = 7, // UNUSED ACTION_T_RANDOM_TEXTEMOTE = 8, // UNUSED ACTION_T_RANDOM_SOUND = 9, // SoundId1, SoundId2, SoundId3 (-1 in any field means no output if randomed that field) ACTION_T_RANDOM_EMOTE = 10, // EmoteId1, EmoteId2, EmoteId3 (-1 in any field means no output if randomed that field) ACTION_T_CAST = 11, // SpellId, Target, CastFlags ACTION_T_SUMMON = 12, // CreatureID, Target, Duration in ms ACTION_T_THREAT_SINGLE_PCT = 13, // Threat%, Target ACTION_T_THREAT_ALL_PCT = 14, // Threat% ACTION_T_QUEST_EVENT = 15, // QuestID, Target ACTION_T_CAST_EVENT = 16, // QuestID, SpellId, Target - must be removed as hack? ACTION_T_SET_UNIT_FIELD = 17, // Field_Number, Value, Target ACTION_T_SET_UNIT_FLAG = 18, // Flags (may be more than one field OR'd together), Target ACTION_T_REMOVE_UNIT_FLAG = 19, // Flags (may be more than one field OR'd together), Target ACTION_T_AUTO_ATTACK = 20, // AllowAttackState (0 = stop attack, anything else means continue attacking) ACTION_T_COMBAT_MOVEMENT = 21, // AllowCombatMovement (0 = stop combat based movement, anything else continue attacking) ACTION_T_SET_PHASE = 22, // Phase ACTION_T_INC_PHASE = 23, // Value (may be negative to decrement phase, should not be 0) ACTION_T_EVADE = 24, // No Params ACTION_T_FLEE_FOR_ASSIST = 25, // No Params ACTION_T_QUEST_EVENT_ALL = 26, // QuestID ACTION_T_CAST_EVENT_ALL = 27, // CreatureId, SpellId ACTION_T_REMOVEAURASFROMSPELL = 28, // Target, Spellid ACTION_T_RANGED_MOVEMENT = 29, // Distance, Angle ACTION_T_RANDOM_PHASE = 30, // PhaseId1, PhaseId2, PhaseId3 ACTION_T_RANDOM_PHASE_RANGE = 31, // PhaseMin, PhaseMax ACTION_T_SUMMON_ID = 32, // CreatureId, Target, SpawnId ACTION_T_KILLED_MONSTER = 33, // CreatureId, Target ACTION_T_SET_INST_DATA = 34, // Field, Data ACTION_T_SET_INST_DATA64 = 35, // Field, Target ACTION_T_UPDATE_TEMPLATE = 36, // Entry, Team ACTION_T_DIE = 37, // No Params ACTION_T_ZONE_COMBAT_PULSE = 38, // No Params ACTION_T_CALL_FOR_HELP = 39, // Radius ACTION_T_SET_SHEATH = 40, // Sheath (0-passive,1-melee,2-ranged) ACTION_T_FORCE_DESPAWN = 41, // Delay (0-instant despawn) ACTION_T_SET_INVINCIBILITY_HP_LEVEL = 42, // MinHpValue, format(0-flat,1-percent from max health) ACTION_T_MOUNT_TO_ENTRY_OR_MODEL = 43, // Creature_template entry(param1) OR ModelId (param2) (or 0 for both to unmount) ACTION_T_CHANCED_TEXT = 44, // Chance to display the text, TextId1, optionally TextId2. If more than just -TextId1 is defined, randomize. Negative values. ACTION_T_THROW_AI_EVENT = 45, // EventType, Radius, unused ACTION_T_SET_THROW_MASK = 46, // EventTypeMask, unused, unused ACTION_T_SET_STAND_STATE = 47, // StandState, unused, unused ACTION_T_CHANGE_MOVEMENT = 48, // MovementType, WanderDistance, unused ACTION_T_END, }; enum Target { // Self (m_creature) TARGET_T_SELF = 0, // Self cast // Hostile targets TARGET_T_HOSTILE = 1, // Our current target (ie: highest aggro) TARGET_T_HOSTILE_SECOND_AGGRO = 2, // Second highest aggro (generaly used for cleaves and some special attacks) TARGET_T_HOSTILE_LAST_AGGRO = 3, // Dead last on aggro (no idea what this could be used for) TARGET_T_HOSTILE_RANDOM = 4, // Just any random target on our threat list TARGET_T_HOSTILE_RANDOM_NOT_TOP = 5, // Any random target except top threat // Invoker targets TARGET_T_ACTION_INVOKER = 6, // Unit who caused this Event to occur (only works for EVENT_T_AGGRO, EVENT_T_KILL, EVENT_T_DEATH, EVENT_T_SPELLHIT, EVENT_T_OOC_LOS, EVENT_T_FRIENDLY_HP, EVENT_T_FRIENDLY_IS_CC, EVENT_T_FRIENDLY_MISSING_BUFF, EVENT_T_RECEIVE_EMOTE, EVENT_T_RECEIVE_AI_EVENT) TARGET_T_ACTION_INVOKER_OWNER = 7, // Unit who is responsible for Event to occur (only works for EVENT_T_AGGRO, EVENT_T_KILL, EVENT_T_DEATH, EVENT_T_SPELLHIT, EVENT_T_OOC_LOS, EVENT_T_FRIENDLY_HP, EVENT_T_FRIENDLY_IS_CC, EVENT_T_FRIENDLY_MISSING_BUFF, EVENT_T_RECEIVE_EMOTE, EVENT_T_RECEIVE_AI_EVENT) TARGET_T_EVENT_SENDER = 10, // Unit who sent an AIEvent that was received with EVENT_T_RECEIVE_AI_EVENT // Hostile players TARGET_T_HOSTILE_RANDOM_PLAYER = 8, // Just any random player on our threat list TARGET_T_HOSTILE_RANDOM_NOT_TOP_PLAYER = 9, // Any random player from threat list except top threat }; enum EventFlags { EFLAG_REPEATABLE = 0x01, // Event repeats EFLAG_RESERVED_1 = 0x02, EFLAG_RESERVED_2 = 0x04, EFLAG_RESERVED_3 = 0x08, EFLAG_RESERVED_4 = 0x10, EFLAG_RANDOM_ACTION = 0x20, // Event only execute one from existed actions instead each action. EFLAG_RESERVED_6 = 0x40, EFLAG_DEBUG_ONLY = 0x80, // Event only occurs in debug build // no free bits, uint8 field }; enum SpawnedEventMode { SPAWNED_EVENT_ALWAY = 0, SPAWNED_EVENT_MAP = 1, SPAWNED_EVENT_ZONE = 2 }; struct CreatureEventAI_Action { EventAI_ActionType type: 16; union { // ACTION_T_TEXT = 1 struct { int32 TextId[3]; } text; // ACTION_T_SET_FACTION = 2 struct { uint32 factionId; // faction id or 0 to restore default faction uint32 factionFlags; // flags will restore default faction at evade and/or respawn } set_faction; // ACTION_T_MORPH_TO_ENTRY_OR_MODEL = 3 struct { uint32 creatureId; // set one from fields (or 0 for both to demorph) uint32 modelId; } morph; // ACTION_T_SOUND = 4 struct { uint32 soundId; } sound; // ACTION_T_EMOTE = 5 struct { uint32 emoteId; } emote; // ACTION_T_RANDOM_SOUND = 9 struct { int32 soundId1; // (-1 in any field means no output if randomed that field) int32 soundId2; int32 soundId3; } random_sound; // ACTION_T_RANDOM_EMOTE = 10 struct { int32 emoteId1; // (-1 in any field means no output if randomed that field) int32 emoteId2; int32 emoteId3; } random_emote; // ACTION_T_CAST = 11 struct { uint32 spellId; uint32 target; uint32 castFlags; } cast; // ACTION_T_SUMMON = 12 struct { uint32 creatureId; uint32 target; uint32 duration; } summon; // ACTION_T_THREAT_SINGLE_PCT = 13 struct { int32 percent; uint32 target; } threat_single_pct; // ACTION_T_THREAT_ALL_PCT = 14 struct { int32 percent; } threat_all_pct; // ACTION_T_QUEST_EVENT = 15 struct { uint32 questId; uint32 target; } quest_event; // ACTION_T_CAST_EVENT = 16 struct { uint32 creatureId; uint32 spellId; uint32 target; } cast_event; // ACTION_T_SET_UNIT_FIELD = 17 struct { uint32 field; uint32 value; uint32 target; } set_unit_field; // ACTION_T_SET_UNIT_FLAG = 18, // value provided mask bits that will be set // ACTION_T_REMOVE_UNIT_FLAG = 19, // value provided mask bits that will be clear struct { uint32 value; uint32 target; } unit_flag; // ACTION_T_AUTO_ATTACK = 20 struct { uint32 state; // 0 = stop attack, anything else means continue attacking } auto_attack; // ACTION_T_COMBAT_MOVEMENT = 21 struct { uint32 state; // 0 = stop combat based movement, anything else continue attacking uint32 melee; // if set: at stop send melee combat stop if in combat, use for terminate melee fighting state for switch to ranged } combat_movement; // ACTION_T_SET_PHASE = 22 struct { uint32 phase; } set_phase; // ACTION_T_INC_PHASE = 23 struct { int32 step; } set_inc_phase; // ACTION_T_QUEST_EVENT_ALL = 26 struct { uint32 questId; } quest_event_all; // ACTION_T_CAST_EVENT_ALL = 27 struct { uint32 creatureId; uint32 spellId; } cast_event_all; // ACTION_T_REMOVEAURASFROMSPELL = 28 struct { uint32 target; uint32 spellId; } remove_aura; // ACTION_T_RANGED_MOVEMENT = 29 struct { uint32 distance; int32 angle; } ranged_movement; // ACTION_T_RANDOM_PHASE = 30 struct { uint32 phase1; uint32 phase2; uint32 phase3; } random_phase; // ACTION_T_RANDOM_PHASE_RANGE = 31 struct { uint32 phaseMin; uint32 phaseMax; } random_phase_range; // ACTION_T_SUMMON_ID = 32 struct { uint32 creatureId; uint32 target; uint32 spawnId; } summon_id; // ACTION_T_KILLED_MONSTER = 33 struct { uint32 creatureId; uint32 target; } killed_monster; // ACTION_T_SET_INST_DATA = 34 struct { uint32 field; uint32 value; } set_inst_data; // ACTION_T_SET_INST_DATA64 = 35 struct { uint32 field; uint32 target; } set_inst_data64; // ACTION_T_UPDATE_TEMPLATE = 36 struct { uint32 creatureId; uint32 team; } update_template; // ACTION_T_CALL_FOR_HELP = 39 struct { uint32 radius; } call_for_help; // ACTION_T_SET_SHEATH = 40 struct { uint32 sheath; } set_sheath; // ACTION_T_FORCE_DESPAWN = 41 struct { uint32 msDelay; } forced_despawn; // ACTION_T_SET_INVINCIBILITY_HP_LEVEL = 42 struct { uint32 hp_level; uint32 is_percent; } invincibility_hp_level; // ACTION_T_MOUNT_TO_ENTRY_OR_MODEL = 43 struct { uint32 creatureId; // set one from fields (or 0 for both to dismount) uint32 modelId; } mount; // ACTION_T_CHANCED_TEXT = 44 struct { uint32 chance; int32 TextId[2]; } chanced_text; // ACTION_T_THROW_AI_EVENT = 45 struct { uint32 eventType; uint32 radius; uint32 unused; } throwEvent; // ACTION_T_SET_THROW_MASK = 46 struct { uint32 eventTypeMask; uint32 unused1; uint32 unused2; } setThrowMask; // ACTION_T_SET_STAND_STATE = 47 struct { uint32 standState; uint32 unused1; uint32 unused2; } setStandState; // ACTION_T_CHANGE_MOVEMENT = 48 struct { uint32 movementType; uint32 wanderDistance; uint32 unused1; } changeMovement; // RAW struct { uint32 param1; uint32 param2; uint32 param3; } raw; }; }; struct CreatureEventAI_Event { uint32 event_id; uint32 creature_id; uint32 event_inverse_phase_mask; EventAI_Type event_type : 16; uint8 event_chance : 8; uint8 event_flags : 8; union { // EVENT_T_TIMER_IN_COMBAT = 0 // EVENT_T_TIMER_OOC = 1 // EVENT_T_TIMER_GENERIC = 29 struct { uint32 initialMin; uint32 initialMax; uint32 repeatMin; uint32 repeatMax; } timer; // EVENT_T_HP = 2 // EVENT_T_MANA = 3 // EVENT_T_TARGET_HP = 12 // EVENT_T_TARGET_MANA = 18 // EVENT_T_ENERGY = 31 struct { uint32 percentMax; uint32 percentMin; uint32 repeatMin; uint32 repeatMax; } percent_range; // EVENT_T_KILL = 5 struct { uint32 repeatMin; uint32 repeatMax; } kill; // EVENT_T_SPELLHIT = 8 struct { uint32 spellId; uint32 schoolMask; // -1 (==0xffffffff) is ok value for full mask, or must be more limited mask like (0 < 1) = 1 for normal/physical school uint32 repeatMin; uint32 repeatMax; } spell_hit; // EVENT_T_RANGE = 9 struct { uint32 minDist; uint32 maxDist; uint32 repeatMin; uint32 repeatMax; } range; // EVENT_T_OOC_LOS = 10 struct { uint32 noHostile; uint32 maxRange; uint32 repeatMin; uint32 repeatMax; } ooc_los; // EVENT_T_SPAWNED = 11 struct { uint32 condition; uint32 conditionValue1; } spawned; // EVENT_T_TARGET_CASTING = 13 struct { uint32 repeatMin; uint32 repeatMax; } target_casting; // EVENT_T_FRIENDLY_HP = 14 struct { uint32 hpDeficit; uint32 radius; uint32 repeatMin; uint32 repeatMax; } friendly_hp; // EVENT_T_FRIENDLY_IS_CC = 15 struct { uint32 dispelType; // unused ? uint32 radius; uint32 repeatMin; uint32 repeatMax; } friendly_is_cc; // EVENT_T_FRIENDLY_MISSING_BUFF = 16 struct { uint32 spellId; uint32 radius; uint32 repeatMin; uint32 repeatMax; } friendly_buff; // EVENT_T_SUMMONED_UNIT = 17 // EVENT_T_SUMMONED_JUST_DIED = 25 // EVENT_T_SUMMONED_JUST_DESPAWN = 26 struct { uint32 creatureId; uint32 repeatMin; uint32 repeatMax; } summoned; // EVENT_T_QUEST_ACCEPT = 19 // EVENT_T_QUEST_COMPLETE = 20 struct { uint32 questId; } quest; // EVENT_T_RECEIVE_EMOTE = 22 struct { uint32 emoteId; uint32 condition; uint32 conditionValue1; uint32 conditionValue2; } receive_emote; // EVENT_T_AURA = 23 // EVENT_T_TARGET_AURA = 24 // EVENT_T_MISSING_AURA = 27 // EVENT_T_TARGET_MISSING_AURA = 28 struct { uint32 spellId; uint32 amount; uint32 repeatMin; uint32 repeatMax; } buffed; // EVENT_T_RECEIVE_AI_EVENT = 30 struct { uint32 eventType; // See CreatureAI.h enum AIEventType - Receive only events of this type uint32 senderEntry; // Optional npc from only whom this event can be received uint32 unused1; uint32 unused2; } receiveAIEvent; // RAW struct { uint32 param1; uint32 param2; uint32 param3; uint32 param4; } raw; }; CreatureEventAI_Action action[MAX_ACTIONS]; }; #define AIEVENT_DEFAULT_THROW_RADIUS 30.0f // Event_Map typedef std::vector<CreatureEventAI_Event> CreatureEventAI_Event_Vec; typedef UNORDERED_MAP<uint32, CreatureEventAI_Event_Vec > CreatureEventAI_Event_Map; struct CreatureEventAI_Summon { uint32 id; float position_x; float position_y; float position_z; float orientation; uint32 SpawnTimeSecs; }; // EventSummon_Map typedef UNORDERED_MAP<uint32, CreatureEventAI_Summon> CreatureEventAI_Summon_Map; struct CreatureEventAIHolder { CreatureEventAIHolder(CreatureEventAI_Event p) : Event(p), Time(0), Enabled(true) {} CreatureEventAI_Event Event; uint32 Time; bool Enabled; // helper bool UpdateRepeatTimer(Creature* creature, uint32 repeatMin, uint32 repeatMax); }; class MANGOS_DLL_SPEC CreatureEventAI : public CreatureAI { public: explicit CreatureEventAI(Creature* c); ~CreatureEventAI() { m_CreatureEventAIList.clear(); } void GetAIInformation(ChatHandler& reader) override; void JustRespawned() override; void Reset(); void JustReachedHome() override; void EnterCombat(Unit* enemy) override; void EnterEvadeMode() override; void JustDied(Unit* killer) override; void KilledUnit(Unit* victim) override; void JustSummoned(Creature* pUnit) override; void AttackStart(Unit* who) override; void MoveInLineOfSight(Unit* who) override; void SpellHit(Unit* pUnit, const SpellEntry* pSpell) override; void DamageTaken(Unit* done_by, uint32& damage) override; void HealedBy(Unit* healer, uint32& healedAmount) override; void UpdateAI(const uint32 diff) override; bool IsVisible(Unit*) const override; void ReceiveEmote(Player* pPlayer, uint32 text_emote) override; void SummonedCreatureJustDied(Creature* unit) override; void SummonedCreatureDespawn(Creature* unit) override; void ReceiveAIEvent(AIEventType eventType, Creature* pSender, Unit* pInvoker, uint32 miscValue) override; static int Permissible(const Creature*); bool ProcessEvent(CreatureEventAIHolder& pHolder, Unit* pActionInvoker = NULL, Creature* pAIEventSender = NULL); void ProcessAction(CreatureEventAI_Action const& action, uint32 rnd, uint32 EventId, Unit* pActionInvoker, Creature* pAIEventSender); inline uint32 GetRandActionParam(uint32 rnd, uint32 param1, uint32 param2, uint32 param3); inline int32 GetRandActionParam(uint32 rnd, int32 param1, int32 param2, int32 param3); /// If the bool& param is true, an error should be reported inline Unit* GetTargetByType(uint32 Target, Unit* pActionInvoker, Creature* pAIEventSender, bool& isError, uint32 forSpellId = 0, uint32 selectFlags = 0); bool SpawnedEventConditionsCheck(CreatureEventAI_Event const& event); Unit* DoSelectLowestHpFriendly(float range, uint32 MinHPDiff); void DoFindFriendlyMissingBuff(std::list<Creature*>& _list, float range, uint32 spellid); void DoFindFriendlyCC(std::list<Creature*>& _list, float range); protected: uint32 m_EventUpdateTime; // Time between event updates uint32 m_EventDiff; // Time between the last event call // Variables used by Events themselves typedef std::vector<CreatureEventAIHolder> CreatureEventAIList; CreatureEventAIList m_CreatureEventAIList; // Holder for events (stores enabled, time, and eventid) uint8 m_Phase; // Current phase, max 32 phases bool m_MeleeEnabled; // If we allow melee auto attack bool m_HasOOCLoSEvent; // Cache if a OOC-LoS Event exists uint32 m_InvinceabilityHpLevel; // Minimal health level allowed at damage apply uint32 m_throwAIEventMask; // Automatically throw AIEvents that are encoded into this mask // Note that Step 100 means that AI_EVENT_GOT_FULL_HEALTH was sent // Steps 0..2 correspond to AI_EVENT_LOST_SOME_HEALTH(90%), AI_EVENT_LOST_HEALTH(50%), AI_EVENT_CRITICAL_HEALTH(10%) uint32 m_throwAIEventStep; // Used for damage taken/ received heal }; #endif
yyhhrr/portalclassic
src/game/CreatureEventAI.h
C
gpl-2.0
29,052
#ifndef MARCO_WINDOW_MANAGER_H #define MARCO_WINDOW_MANAGER_H #include <glib-object.h> #include "mate-window-manager.h" #define MARCO_WINDOW_MANAGER(obj) G_TYPE_CHECK_INSTANCE_CAST (obj, marco_window_manager_get_type (), MarcoWindowManager) #define MARCO_WINDOW_MANAGER_CLASS(klass) G_TYPE_CHECK_CLASS_CAST (klass, marco_window_manager_get_type (), MarcoWindowManagerClass) #define IS_MARCO_WINDOW_MANAGER(obj) G_TYPE_CHECK_INSTANCE_TYPE (obj, marco_window_manager_get_type ()) typedef struct _MarcoWindowManager MarcoWindowManager; typedef struct _MarcoWindowManagerClass MarcoWindowManagerClass; typedef struct _MarcoWindowManagerPrivate MarcoWindowManagerPrivate; struct _MarcoWindowManager { MateWindowManager parent; MarcoWindowManagerPrivate *p; }; struct _MarcoWindowManagerClass { MateWindowManagerClass klass; }; GType marco_window_manager_get_type (void); #endif
flexiondotorg/mate-control-center
libwindow-settings/marco-window-manager.h
C
gpl-2.0
917
/* ----------------------------------------------------------------------------- * Copyright (c) 2011 Ozmo Inc * Released under the GNU General Public License Version 2 (GPLv2). * ----------------------------------------------------------------------------- */ #ifndef _OZELTBUF_H #define _OZELTBUF_H #include "ozprotocol.h" /*----------------------------------------------------------------------------- */ struct oz_pd; typedef void (*oz_elt_callback_t)(struct oz_pd *pd, long context); struct oz_elt_stream { struct list_head link; struct list_head elt_list; atomic_t ref_count; unsigned buf_count; unsigned max_buf_count; u8 frame_number; u8 id; }; #define OZ_MAX_ELT_PAYLOAD 255 struct oz_elt_info { struct list_head link; struct list_head link_order; u8 flags; u8 app_id; oz_elt_callback_t callback; long context; struct oz_elt_stream *stream; u8 data[sizeof(struct oz_elt) + OZ_MAX_ELT_PAYLOAD]; int length; unsigned magic; }; /* Flags values */ #define OZ_EI_F_MARKED 0x1 struct oz_elt_buf { spinlock_t lock; struct list_head stream_list; struct list_head order_list; struct list_head isoc_list; struct list_head *elt_pool; int free_elts; int max_free_elts; u8 tx_seq_num[OZ_NB_APPS]; }; int oz_elt_buf_init(struct oz_elt_buf *buf); void oz_elt_buf_term(struct oz_elt_buf *buf); struct oz_elt_info *oz_elt_info_alloc(struct oz_elt_buf *buf); void oz_elt_info_free(struct oz_elt_buf *buf, struct oz_elt_info *ei); void oz_elt_info_free_chain(struct oz_elt_buf *buf, struct list_head *list); int oz_elt_stream_create(struct oz_elt_buf *buf, u8 id, int max_buf_count); int oz_elt_stream_delete(struct oz_elt_buf *buf, u8 id); void oz_elt_stream_get(struct oz_elt_stream *st); void oz_elt_stream_put(struct oz_elt_stream *st); int oz_queue_elt_info(struct oz_elt_buf *buf, u8 isoc, u8 id, struct oz_elt_info *ei); int oz_select_elts_for_tx(struct oz_elt_buf *buf, u8 isoc, unsigned *len, unsigned max_len, struct list_head *list); int oz_are_elts_available(struct oz_elt_buf *buf); void oz_trim_elt_pool(struct oz_elt_buf *buf); #endif /* _OZELTBUF_H */
davidmueller13/arter97_bb
drivers/staging/ozwpan/ozeltbuf.h
C
gpl-2.0
2,100
<?php $eZTranslationCacheCodeDate = 1058863428; $CacheInfo = array ( 'charset' => 'utf-8', ); $TranslationInfo = array ( 'context' => 'extension/ezodf/export/error', ); $TranslationRoot = array ( '73623c5bd7bcc9305cdf14409aa6646f' => array ( 'context' => 'extension/ezodf/export/error', 'source' => 'Destination file format not supported', 'comment' => NULL, 'translation' => 'Le format du fichier de destination n\'est pas pris en charge', 'key' => '73623c5bd7bcc9305cdf14409aa6646f', ), '937c60aa58d5ab5e2460c98c5752aa30' => array ( 'context' => 'extension/ezodf/export/error', 'source' => 'PDF conversion failed', 'comment' => NULL, 'translation' => 'Échec de la conversion PDF', 'key' => '937c60aa58d5ab5e2460c98c5752aa30', ), '0f73e965ec653e8dfcdfb3d18c75b69a' => array ( 'context' => 'extension/ezodf/export/error', 'source' => 'Word conversion failed', 'comment' => NULL, 'translation' => 'Échec de la conversion Word', 'key' => '0f73e965ec653e8dfcdfb3d18c75b69a', ), '9d0f34fa74112faa1172f68a15e0f0f7' => array ( 'context' => 'extension/ezodf/export/error', 'source' => 'Unable to fetch node, or no read access', 'comment' => NULL, 'translation' => 'Impossible de récupérer le nœud ou de lire le chemin d\'accès', 'key' => '9d0f34fa74112faa1172f68a15e0f0f7', ), '982c74d7f574f67a85180310a3089459' => array ( 'context' => 'extension/ezodf/export/error', 'source' => 'Unable to open file %1 on server side', 'comment' => NULL, 'translation' => 'Impossible d\'ouvrir le fichier %1 côté serveur', 'key' => '982c74d7f574f67a85180310a3089459', ), ); ?>
legende91/toto
var/plain_site/cache/translation/ffd42c3d9ba139a00bfbf35cd9c5e7ac/fre-FR/c634e876367d4d820497284198d0d572.php
PHP
gpl-2.0
1,704
{% extends "base.html" %} {% block title %}Internal Server Error{% endblock %} {% block page_content %} <div class="page-header"> <h1>Internal Server Error</h1> </div> {% endblock %}
bikeshare/bikeshare-web
templates/500.html
HTML
gpl-2.0
189
/* * This file is part of the coreboot project. * * Copyright (C) 2005 Yinghai Lu <[email protected]> * Copyright (C) 2009 coresystems GmbH * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 2 of the License. * * 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 <device/smbus_def.h> #include "soc.h" static void smbus_delay(void) { inb(0x80); } static int smbus_wait_until_ready(u16 smbus_base) { unsigned loops = SMBUS_TIMEOUT; unsigned char byte; do { smbus_delay(); if (--loops == 0) break; byte = inb(smbus_base + SMBHSTSTAT); } while (byte & 1); return loops ? 0 : -1; } static int smbus_wait_until_done(u16 smbus_base) { unsigned loops = SMBUS_TIMEOUT; unsigned char byte; do { smbus_delay(); if (--loops == 0) break; byte = inb(smbus_base + SMBHSTSTAT); } while ((byte & 1) || (byte & ~((1 << 6) | (1 << 0))) == 0); return loops ? 0 : -1; } static int do_smbus_read_byte(unsigned smbus_base, unsigned device, unsigned address) { unsigned char global_status_register; unsigned char byte; if (smbus_wait_until_ready(smbus_base) < 0) { return SMBUS_WAIT_UNTIL_READY_TIMEOUT; } /* Setup transaction */ /* Disable interrupts */ outb(inb(smbus_base + SMBHSTCTL) & (~1), smbus_base + SMBHSTCTL); /* Set the device I'm talking too */ outb(((device & 0x7f) << 1) | 1, smbus_base + SMBXMITADD); /* Set the command/address... */ outb(address & 0xff, smbus_base + SMBHSTCMD); /* Set up for a byte data read */ outb((inb(smbus_base + SMBHSTCTL) & 0xe3) | (0x2 << 2), (smbus_base + SMBHSTCTL)); /* Clear any lingering errors, so the transaction will run */ outb(inb(smbus_base + SMBHSTSTAT), smbus_base + SMBHSTSTAT); /* Clear the data byte... */ outb(0, smbus_base + SMBHSTDAT0); /* Start the command */ outb((inb(smbus_base + SMBHSTCTL) | 0x40), smbus_base + SMBHSTCTL); /* Poll for transaction completion */ if (smbus_wait_until_done(smbus_base) < 0) { return SMBUS_WAIT_UNTIL_DONE_TIMEOUT; } global_status_register = inb(smbus_base + SMBHSTSTAT); /* Ignore the "In Use" status... */ global_status_register &= ~(3 << 5); /* Read results of transaction */ byte = inb(smbus_base + SMBHSTDAT0); if (global_status_register != (1 << 1)) { return SMBUS_ERROR; } return byte; }
librecore-org/librecore
src/southbridge/intel/fsp_rangeley/smbus.h
C
gpl-2.0
2,608
/* * NVMe over Fabrics RDMA host code. * Copyright (c) 2015-2016 HGST, a Western Digital Company. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/module.h> #include <linux/init.h> #include <linux/slab.h> #include <linux/err.h> #include <linux/string.h> #include <linux/atomic.h> #include <linux/blk-mq.h> #include <linux/types.h> #include <linux/list.h> #include <linux/mutex.h> #include <linux/scatterlist.h> #include <linux/nvme.h> #include <asm/unaligned.h> #include <rdma/ib_verbs.h> #include <rdma/rdma_cm.h> #include <linux/nvme-rdma.h> #include "nvme.h" #include "fabrics.h" #define NVME_RDMA_CONNECT_TIMEOUT_MS 1000 /* 1 second */ #define NVME_RDMA_MAX_SEGMENT_SIZE 0xffffff /* 24-bit SGL field */ #define NVME_RDMA_MAX_SEGMENTS 256 #define NVME_RDMA_MAX_INLINE_SEGMENTS 1 /* * We handle AEN commands ourselves and don't even let the * block layer know about them. */ #define NVME_RDMA_NR_AEN_COMMANDS 1 #define NVME_RDMA_AQ_BLKMQ_DEPTH \ (NVMF_AQ_DEPTH - NVME_RDMA_NR_AEN_COMMANDS) struct nvme_rdma_device { struct ib_device *dev; struct ib_pd *pd; struct kref ref; struct list_head entry; }; struct nvme_rdma_qe { struct ib_cqe cqe; void *data; u64 dma; }; struct nvme_rdma_queue; struct nvme_rdma_request { struct nvme_request req; struct ib_mr *mr; struct nvme_rdma_qe sqe; struct ib_sge sge[1 + NVME_RDMA_MAX_INLINE_SEGMENTS]; u32 num_sge; int nents; bool inline_data; struct ib_reg_wr reg_wr; struct ib_cqe reg_cqe; struct nvme_rdma_queue *queue; struct sg_table sg_table; struct scatterlist first_sgl[]; }; enum nvme_rdma_queue_flags { NVME_RDMA_Q_CONNECTED = (1 << 0), NVME_RDMA_IB_QUEUE_ALLOCATED = (1 << 1), NVME_RDMA_Q_DELETING = (1 << 2), NVME_RDMA_Q_LIVE = (1 << 3), }; struct nvme_rdma_queue { struct nvme_rdma_qe *rsp_ring; u8 sig_count; int queue_size; size_t cmnd_capsule_len; struct nvme_rdma_ctrl *ctrl; struct nvme_rdma_device *device; struct ib_cq *ib_cq; struct ib_qp *qp; unsigned long flags; struct rdma_cm_id *cm_id; int cm_error; struct completion cm_done; }; struct nvme_rdma_ctrl { /* read and written in the hot path */ spinlock_t lock; /* read only in the hot path */ struct nvme_rdma_queue *queues; u32 queue_count; /* other member variables */ struct blk_mq_tag_set tag_set; struct work_struct delete_work; struct work_struct reset_work; struct work_struct err_work; struct nvme_rdma_qe async_event_sqe; int reconnect_delay; struct delayed_work reconnect_work; struct list_head list; struct blk_mq_tag_set admin_tag_set; struct nvme_rdma_device *device; u64 cap; u32 max_fr_pages; union { struct sockaddr addr; struct sockaddr_in addr_in; }; union { struct sockaddr src_addr; struct sockaddr_in src_addr_in; }; struct nvme_ctrl ctrl; }; static inline struct nvme_rdma_ctrl *to_rdma_ctrl(struct nvme_ctrl *ctrl) { return container_of(ctrl, struct nvme_rdma_ctrl, ctrl); } static LIST_HEAD(device_list); static DEFINE_MUTEX(device_list_mutex); static LIST_HEAD(nvme_rdma_ctrl_list); static DEFINE_MUTEX(nvme_rdma_ctrl_mutex); static struct workqueue_struct *nvme_rdma_wq; /* * Disabling this option makes small I/O goes faster, but is fundamentally * unsafe. With it turned off we will have to register a global rkey that * allows read and write access to all physical memory. */ static bool register_always = true; module_param(register_always, bool, 0444); MODULE_PARM_DESC(register_always, "Use memory registration even for contiguous memory regions"); static int nvme_rdma_cm_handler(struct rdma_cm_id *cm_id, struct rdma_cm_event *event); static void nvme_rdma_recv_done(struct ib_cq *cq, struct ib_wc *wc); /* XXX: really should move to a generic header sooner or later.. */ static inline void put_unaligned_le24(u32 val, u8 *p) { *p++ = val; *p++ = val >> 8; *p++ = val >> 16; } static inline int nvme_rdma_queue_idx(struct nvme_rdma_queue *queue) { return queue - queue->ctrl->queues; } static inline size_t nvme_rdma_inline_data_size(struct nvme_rdma_queue *queue) { return queue->cmnd_capsule_len - sizeof(struct nvme_command); } static void nvme_rdma_free_qe(struct ib_device *ibdev, struct nvme_rdma_qe *qe, size_t capsule_size, enum dma_data_direction dir) { ib_dma_unmap_single(ibdev, qe->dma, capsule_size, dir); kfree(qe->data); } static int nvme_rdma_alloc_qe(struct ib_device *ibdev, struct nvme_rdma_qe *qe, size_t capsule_size, enum dma_data_direction dir) { qe->data = kzalloc(capsule_size, GFP_KERNEL); if (!qe->data) return -ENOMEM; qe->dma = ib_dma_map_single(ibdev, qe->data, capsule_size, dir); if (ib_dma_mapping_error(ibdev, qe->dma)) { kfree(qe->data); return -ENOMEM; } return 0; } static void nvme_rdma_free_ring(struct ib_device *ibdev, struct nvme_rdma_qe *ring, size_t ib_queue_size, size_t capsule_size, enum dma_data_direction dir) { int i; for (i = 0; i < ib_queue_size; i++) nvme_rdma_free_qe(ibdev, &ring[i], capsule_size, dir); kfree(ring); } static struct nvme_rdma_qe *nvme_rdma_alloc_ring(struct ib_device *ibdev, size_t ib_queue_size, size_t capsule_size, enum dma_data_direction dir) { struct nvme_rdma_qe *ring; int i; ring = kcalloc(ib_queue_size, sizeof(struct nvme_rdma_qe), GFP_KERNEL); if (!ring) return NULL; for (i = 0; i < ib_queue_size; i++) { if (nvme_rdma_alloc_qe(ibdev, &ring[i], capsule_size, dir)) goto out_free_ring; } return ring; out_free_ring: nvme_rdma_free_ring(ibdev, ring, i, capsule_size, dir); return NULL; } static void nvme_rdma_qp_event(struct ib_event *event, void *context) { pr_debug("QP event %s (%d)\n", ib_event_msg(event->event), event->event); } static int nvme_rdma_wait_for_cm(struct nvme_rdma_queue *queue) { wait_for_completion_interruptible_timeout(&queue->cm_done, msecs_to_jiffies(NVME_RDMA_CONNECT_TIMEOUT_MS) + 1); return queue->cm_error; } static int nvme_rdma_create_qp(struct nvme_rdma_queue *queue, const int factor) { struct nvme_rdma_device *dev = queue->device; struct ib_qp_init_attr init_attr; int ret; memset(&init_attr, 0, sizeof(init_attr)); init_attr.event_handler = nvme_rdma_qp_event; /* +1 for drain */ init_attr.cap.max_send_wr = factor * queue->queue_size + 1; /* +1 for drain */ init_attr.cap.max_recv_wr = queue->queue_size + 1; init_attr.cap.max_recv_sge = 1; init_attr.cap.max_send_sge = 1 + NVME_RDMA_MAX_INLINE_SEGMENTS; init_attr.sq_sig_type = IB_SIGNAL_REQ_WR; init_attr.qp_type = IB_QPT_RC; init_attr.send_cq = queue->ib_cq; init_attr.recv_cq = queue->ib_cq; ret = rdma_create_qp(queue->cm_id, dev->pd, &init_attr); queue->qp = queue->cm_id->qp; return ret; } static int nvme_rdma_reinit_request(void *data, struct request *rq) { struct nvme_rdma_ctrl *ctrl = data; struct nvme_rdma_device *dev = ctrl->device; struct nvme_rdma_request *req = blk_mq_rq_to_pdu(rq); int ret = 0; if (!req->mr->need_inval) goto out; ib_dereg_mr(req->mr); req->mr = ib_alloc_mr(dev->pd, IB_MR_TYPE_MEM_REG, ctrl->max_fr_pages); if (IS_ERR(req->mr)) { ret = PTR_ERR(req->mr); req->mr = NULL; goto out; } req->mr->need_inval = false; out: return ret; } static void __nvme_rdma_exit_request(struct nvme_rdma_ctrl *ctrl, struct request *rq, unsigned int queue_idx) { struct nvme_rdma_request *req = blk_mq_rq_to_pdu(rq); struct nvme_rdma_queue *queue = &ctrl->queues[queue_idx]; struct nvme_rdma_device *dev = queue->device; if (req->mr) ib_dereg_mr(req->mr); nvme_rdma_free_qe(dev->dev, &req->sqe, sizeof(struct nvme_command), DMA_TO_DEVICE); } static void nvme_rdma_exit_request(void *data, struct request *rq, unsigned int hctx_idx, unsigned int rq_idx) { return __nvme_rdma_exit_request(data, rq, hctx_idx + 1); } static void nvme_rdma_exit_admin_request(void *data, struct request *rq, unsigned int hctx_idx, unsigned int rq_idx) { return __nvme_rdma_exit_request(data, rq, 0); } static int __nvme_rdma_init_request(struct nvme_rdma_ctrl *ctrl, struct request *rq, unsigned int queue_idx) { struct nvme_rdma_request *req = blk_mq_rq_to_pdu(rq); struct nvme_rdma_queue *queue = &ctrl->queues[queue_idx]; struct nvme_rdma_device *dev = queue->device; struct ib_device *ibdev = dev->dev; int ret; ret = nvme_rdma_alloc_qe(ibdev, &req->sqe, sizeof(struct nvme_command), DMA_TO_DEVICE); if (ret) return ret; req->mr = ib_alloc_mr(dev->pd, IB_MR_TYPE_MEM_REG, ctrl->max_fr_pages); if (IS_ERR(req->mr)) { ret = PTR_ERR(req->mr); goto out_free_qe; } req->queue = queue; return 0; out_free_qe: nvme_rdma_free_qe(dev->dev, &req->sqe, sizeof(struct nvme_command), DMA_TO_DEVICE); return -ENOMEM; } static int nvme_rdma_init_request(void *data, struct request *rq, unsigned int hctx_idx, unsigned int rq_idx, unsigned int numa_node) { return __nvme_rdma_init_request(data, rq, hctx_idx + 1); } static int nvme_rdma_init_admin_request(void *data, struct request *rq, unsigned int hctx_idx, unsigned int rq_idx, unsigned int numa_node) { return __nvme_rdma_init_request(data, rq, 0); } static int nvme_rdma_init_hctx(struct blk_mq_hw_ctx *hctx, void *data, unsigned int hctx_idx) { struct nvme_rdma_ctrl *ctrl = data; struct nvme_rdma_queue *queue = &ctrl->queues[hctx_idx + 1]; BUG_ON(hctx_idx >= ctrl->queue_count); hctx->driver_data = queue; return 0; } static int nvme_rdma_init_admin_hctx(struct blk_mq_hw_ctx *hctx, void *data, unsigned int hctx_idx) { struct nvme_rdma_ctrl *ctrl = data; struct nvme_rdma_queue *queue = &ctrl->queues[0]; BUG_ON(hctx_idx != 0); hctx->driver_data = queue; return 0; } static void nvme_rdma_free_dev(struct kref *ref) { struct nvme_rdma_device *ndev = container_of(ref, struct nvme_rdma_device, ref); mutex_lock(&device_list_mutex); list_del(&ndev->entry); mutex_unlock(&device_list_mutex); ib_dealloc_pd(ndev->pd); kfree(ndev); } static void nvme_rdma_dev_put(struct nvme_rdma_device *dev) { kref_put(&dev->ref, nvme_rdma_free_dev); } static int nvme_rdma_dev_get(struct nvme_rdma_device *dev) { return kref_get_unless_zero(&dev->ref); } static struct nvme_rdma_device * nvme_rdma_find_get_device(struct rdma_cm_id *cm_id) { struct nvme_rdma_device *ndev; mutex_lock(&device_list_mutex); list_for_each_entry(ndev, &device_list, entry) { if (ndev->dev->node_guid == cm_id->device->node_guid && nvme_rdma_dev_get(ndev)) goto out_unlock; } ndev = kzalloc(sizeof(*ndev), GFP_KERNEL); if (!ndev) goto out_err; ndev->dev = cm_id->device; kref_init(&ndev->ref); ndev->pd = ib_alloc_pd(ndev->dev, register_always ? 0 : IB_PD_UNSAFE_GLOBAL_RKEY); if (IS_ERR(ndev->pd)) goto out_free_dev; if (!(ndev->dev->attrs.device_cap_flags & IB_DEVICE_MEM_MGT_EXTENSIONS)) { dev_err(&ndev->dev->dev, "Memory registrations not supported.\n"); goto out_free_pd; } list_add(&ndev->entry, &device_list); out_unlock: mutex_unlock(&device_list_mutex); return ndev; out_free_pd: ib_dealloc_pd(ndev->pd); out_free_dev: kfree(ndev); out_err: mutex_unlock(&device_list_mutex); return NULL; } static void nvme_rdma_destroy_queue_ib(struct nvme_rdma_queue *queue) { struct nvme_rdma_device *dev; struct ib_device *ibdev; if (!test_and_clear_bit(NVME_RDMA_IB_QUEUE_ALLOCATED, &queue->flags)) return; dev = queue->device; ibdev = dev->dev; rdma_destroy_qp(queue->cm_id); ib_free_cq(queue->ib_cq); nvme_rdma_free_ring(ibdev, queue->rsp_ring, queue->queue_size, sizeof(struct nvme_completion), DMA_FROM_DEVICE); nvme_rdma_dev_put(dev); } static int nvme_rdma_create_queue_ib(struct nvme_rdma_queue *queue, struct nvme_rdma_device *dev) { struct ib_device *ibdev = dev->dev; const int send_wr_factor = 3; /* MR, SEND, INV */ const int cq_factor = send_wr_factor + 1; /* + RECV */ int comp_vector, idx = nvme_rdma_queue_idx(queue); int ret; queue->device = dev; /* * The admin queue is barely used once the controller is live, so don't * bother to spread it out. */ if (idx == 0) comp_vector = 0; else comp_vector = idx % ibdev->num_comp_vectors; /* +1 for ib_stop_cq */ queue->ib_cq = ib_alloc_cq(dev->dev, queue, cq_factor * queue->queue_size + 1, comp_vector, IB_POLL_SOFTIRQ); if (IS_ERR(queue->ib_cq)) { ret = PTR_ERR(queue->ib_cq); goto out; } ret = nvme_rdma_create_qp(queue, send_wr_factor); if (ret) goto out_destroy_ib_cq; queue->rsp_ring = nvme_rdma_alloc_ring(ibdev, queue->queue_size, sizeof(struct nvme_completion), DMA_FROM_DEVICE); if (!queue->rsp_ring) { ret = -ENOMEM; goto out_destroy_qp; } set_bit(NVME_RDMA_IB_QUEUE_ALLOCATED, &queue->flags); return 0; out_destroy_qp: ib_destroy_qp(queue->qp); out_destroy_ib_cq: ib_free_cq(queue->ib_cq); out: return ret; } static int nvme_rdma_init_queue(struct nvme_rdma_ctrl *ctrl, int idx, size_t queue_size) { struct nvme_rdma_queue *queue; struct sockaddr *src_addr = NULL; int ret; queue = &ctrl->queues[idx]; queue->ctrl = ctrl; init_completion(&queue->cm_done); if (idx > 0) queue->cmnd_capsule_len = ctrl->ctrl.ioccsz * 16; else queue->cmnd_capsule_len = sizeof(struct nvme_command); queue->queue_size = queue_size; queue->cm_id = rdma_create_id(&init_net, nvme_rdma_cm_handler, queue, RDMA_PS_TCP, IB_QPT_RC); if (IS_ERR(queue->cm_id)) { dev_info(ctrl->ctrl.device, "failed to create CM ID: %ld\n", PTR_ERR(queue->cm_id)); return PTR_ERR(queue->cm_id); } queue->cm_error = -ETIMEDOUT; if (ctrl->ctrl.opts->mask & NVMF_OPT_HOST_TRADDR) src_addr = &ctrl->src_addr; ret = rdma_resolve_addr(queue->cm_id, src_addr, &ctrl->addr, NVME_RDMA_CONNECT_TIMEOUT_MS); if (ret) { dev_info(ctrl->ctrl.device, "rdma_resolve_addr failed (%d).\n", ret); goto out_destroy_cm_id; } ret = nvme_rdma_wait_for_cm(queue); if (ret) { dev_info(ctrl->ctrl.device, "rdma_resolve_addr wait failed (%d).\n", ret); goto out_destroy_cm_id; } clear_bit(NVME_RDMA_Q_DELETING, &queue->flags); set_bit(NVME_RDMA_Q_CONNECTED, &queue->flags); return 0; out_destroy_cm_id: nvme_rdma_destroy_queue_ib(queue); rdma_destroy_id(queue->cm_id); return ret; } static void nvme_rdma_stop_queue(struct nvme_rdma_queue *queue) { rdma_disconnect(queue->cm_id); ib_drain_qp(queue->qp); } static void nvme_rdma_free_queue(struct nvme_rdma_queue *queue) { nvme_rdma_destroy_queue_ib(queue); rdma_destroy_id(queue->cm_id); } static void nvme_rdma_stop_and_free_queue(struct nvme_rdma_queue *queue) { if (test_and_set_bit(NVME_RDMA_Q_DELETING, &queue->flags)) return; nvme_rdma_stop_queue(queue); nvme_rdma_free_queue(queue); } static void nvme_rdma_free_io_queues(struct nvme_rdma_ctrl *ctrl) { int i; for (i = 1; i < ctrl->queue_count; i++) nvme_rdma_stop_and_free_queue(&ctrl->queues[i]); } static int nvme_rdma_connect_io_queues(struct nvme_rdma_ctrl *ctrl) { int i, ret = 0; for (i = 1; i < ctrl->queue_count; i++) { ret = nvmf_connect_io_queue(&ctrl->ctrl, i); if (ret) { dev_info(ctrl->ctrl.device, "failed to connect i/o queue: %d\n", ret); goto out_free_queues; } set_bit(NVME_RDMA_Q_LIVE, &ctrl->queues[i].flags); } return 0; out_free_queues: nvme_rdma_free_io_queues(ctrl); return ret; } static int nvme_rdma_init_io_queues(struct nvme_rdma_ctrl *ctrl) { struct nvmf_ctrl_options *opts = ctrl->ctrl.opts; unsigned int nr_io_queues; int i, ret; nr_io_queues = min(opts->nr_io_queues, num_online_cpus()); ret = nvme_set_queue_count(&ctrl->ctrl, &nr_io_queues); if (ret) return ret; ctrl->queue_count = nr_io_queues + 1; if (ctrl->queue_count < 2) return 0; dev_info(ctrl->ctrl.device, "creating %d I/O queues.\n", nr_io_queues); for (i = 1; i < ctrl->queue_count; i++) { ret = nvme_rdma_init_queue(ctrl, i, ctrl->ctrl.opts->queue_size); if (ret) { dev_info(ctrl->ctrl.device, "failed to initialize i/o queue: %d\n", ret); goto out_free_queues; } } return 0; out_free_queues: for (i--; i >= 1; i--) nvme_rdma_stop_and_free_queue(&ctrl->queues[i]); return ret; } static void nvme_rdma_destroy_admin_queue(struct nvme_rdma_ctrl *ctrl) { nvme_rdma_free_qe(ctrl->queues[0].device->dev, &ctrl->async_event_sqe, sizeof(struct nvme_command), DMA_TO_DEVICE); nvme_rdma_stop_and_free_queue(&ctrl->queues[0]); blk_cleanup_queue(ctrl->ctrl.admin_q); blk_mq_free_tag_set(&ctrl->admin_tag_set); nvme_rdma_dev_put(ctrl->device); } static void nvme_rdma_free_ctrl(struct nvme_ctrl *nctrl) { struct nvme_rdma_ctrl *ctrl = to_rdma_ctrl(nctrl); if (list_empty(&ctrl->list)) goto free_ctrl; mutex_lock(&nvme_rdma_ctrl_mutex); list_del(&ctrl->list); mutex_unlock(&nvme_rdma_ctrl_mutex); kfree(ctrl->queues); nvmf_free_options(nctrl->opts); free_ctrl: kfree(ctrl); } static void nvme_rdma_reconnect_ctrl_work(struct work_struct *work) { struct nvme_rdma_ctrl *ctrl = container_of(to_delayed_work(work), struct nvme_rdma_ctrl, reconnect_work); bool changed; int ret; if (ctrl->queue_count > 1) { nvme_rdma_free_io_queues(ctrl); ret = blk_mq_reinit_tagset(&ctrl->tag_set); if (ret) goto requeue; } nvme_rdma_stop_and_free_queue(&ctrl->queues[0]); ret = blk_mq_reinit_tagset(&ctrl->admin_tag_set); if (ret) goto requeue; ret = nvme_rdma_init_queue(ctrl, 0, NVMF_AQ_DEPTH); if (ret) goto requeue; blk_mq_start_stopped_hw_queues(ctrl->ctrl.admin_q, true); ret = nvmf_connect_admin_queue(&ctrl->ctrl); if (ret) goto stop_admin_q; set_bit(NVME_RDMA_Q_LIVE, &ctrl->queues[0].flags); ret = nvme_enable_ctrl(&ctrl->ctrl, ctrl->cap); if (ret) goto stop_admin_q; nvme_start_keep_alive(&ctrl->ctrl); if (ctrl->queue_count > 1) { ret = nvme_rdma_init_io_queues(ctrl); if (ret) goto stop_admin_q; ret = nvme_rdma_connect_io_queues(ctrl); if (ret) goto stop_admin_q; } changed = nvme_change_ctrl_state(&ctrl->ctrl, NVME_CTRL_LIVE); WARN_ON_ONCE(!changed); if (ctrl->queue_count > 1) { nvme_start_queues(&ctrl->ctrl); nvme_queue_scan(&ctrl->ctrl); nvme_queue_async_events(&ctrl->ctrl); } dev_info(ctrl->ctrl.device, "Successfully reconnected\n"); return; stop_admin_q: blk_mq_stop_hw_queues(ctrl->ctrl.admin_q); requeue: /* Make sure we are not resetting/deleting */ if (ctrl->ctrl.state == NVME_CTRL_RECONNECTING) { dev_info(ctrl->ctrl.device, "Failed reconnect attempt, requeueing...\n"); queue_delayed_work(nvme_rdma_wq, &ctrl->reconnect_work, ctrl->reconnect_delay * HZ); } } static void nvme_rdma_error_recovery_work(struct work_struct *work) { struct nvme_rdma_ctrl *ctrl = container_of(work, struct nvme_rdma_ctrl, err_work); int i; nvme_stop_keep_alive(&ctrl->ctrl); for (i = 0; i < ctrl->queue_count; i++) { clear_bit(NVME_RDMA_Q_CONNECTED, &ctrl->queues[i].flags); clear_bit(NVME_RDMA_Q_LIVE, &ctrl->queues[i].flags); } if (ctrl->queue_count > 1) nvme_stop_queues(&ctrl->ctrl); blk_mq_stop_hw_queues(ctrl->ctrl.admin_q); /* We must take care of fastfail/requeue all our inflight requests */ if (ctrl->queue_count > 1) blk_mq_tagset_busy_iter(&ctrl->tag_set, nvme_cancel_request, &ctrl->ctrl); blk_mq_tagset_busy_iter(&ctrl->admin_tag_set, nvme_cancel_request, &ctrl->ctrl); dev_info(ctrl->ctrl.device, "reconnecting in %d seconds\n", ctrl->reconnect_delay); queue_delayed_work(nvme_rdma_wq, &ctrl->reconnect_work, ctrl->reconnect_delay * HZ); } static void nvme_rdma_error_recovery(struct nvme_rdma_ctrl *ctrl) { if (!nvme_change_ctrl_state(&ctrl->ctrl, NVME_CTRL_RECONNECTING)) return; queue_work(nvme_rdma_wq, &ctrl->err_work); } static void nvme_rdma_wr_error(struct ib_cq *cq, struct ib_wc *wc, const char *op) { struct nvme_rdma_queue *queue = cq->cq_context; struct nvme_rdma_ctrl *ctrl = queue->ctrl; if (ctrl->ctrl.state == NVME_CTRL_LIVE) dev_info(ctrl->ctrl.device, "%s for CQE 0x%p failed with status %s (%d)\n", op, wc->wr_cqe, ib_wc_status_msg(wc->status), wc->status); nvme_rdma_error_recovery(ctrl); } static void nvme_rdma_memreg_done(struct ib_cq *cq, struct ib_wc *wc) { if (unlikely(wc->status != IB_WC_SUCCESS)) nvme_rdma_wr_error(cq, wc, "MEMREG"); } static void nvme_rdma_inv_rkey_done(struct ib_cq *cq, struct ib_wc *wc) { if (unlikely(wc->status != IB_WC_SUCCESS)) nvme_rdma_wr_error(cq, wc, "LOCAL_INV"); } static int nvme_rdma_inv_rkey(struct nvme_rdma_queue *queue, struct nvme_rdma_request *req) { struct ib_send_wr *bad_wr; struct ib_send_wr wr = { .opcode = IB_WR_LOCAL_INV, .next = NULL, .num_sge = 0, .send_flags = 0, .ex.invalidate_rkey = req->mr->rkey, }; req->reg_cqe.done = nvme_rdma_inv_rkey_done; wr.wr_cqe = &req->reg_cqe; return ib_post_send(queue->qp, &wr, &bad_wr); } static void nvme_rdma_unmap_data(struct nvme_rdma_queue *queue, struct request *rq) { struct nvme_rdma_request *req = blk_mq_rq_to_pdu(rq); struct nvme_rdma_ctrl *ctrl = queue->ctrl; struct nvme_rdma_device *dev = queue->device; struct ib_device *ibdev = dev->dev; int res; if (!blk_rq_bytes(rq)) return; if (req->mr->need_inval) { res = nvme_rdma_inv_rkey(queue, req); if (res < 0) { dev_err(ctrl->ctrl.device, "Queueing INV WR for rkey %#x failed (%d)\n", req->mr->rkey, res); nvme_rdma_error_recovery(queue->ctrl); } } ib_dma_unmap_sg(ibdev, req->sg_table.sgl, req->nents, rq_data_dir(rq) == WRITE ? DMA_TO_DEVICE : DMA_FROM_DEVICE); nvme_cleanup_cmd(rq); sg_free_table_chained(&req->sg_table, true); } static int nvme_rdma_set_sg_null(struct nvme_command *c) { struct nvme_keyed_sgl_desc *sg = &c->common.dptr.ksgl; sg->addr = 0; put_unaligned_le24(0, sg->length); put_unaligned_le32(0, sg->key); sg->type = NVME_KEY_SGL_FMT_DATA_DESC << 4; return 0; } static int nvme_rdma_map_sg_inline(struct nvme_rdma_queue *queue, struct nvme_rdma_request *req, struct nvme_command *c) { struct nvme_sgl_desc *sg = &c->common.dptr.sgl; req->sge[1].addr = sg_dma_address(req->sg_table.sgl); req->sge[1].length = sg_dma_len(req->sg_table.sgl); req->sge[1].lkey = queue->device->pd->local_dma_lkey; sg->addr = cpu_to_le64(queue->ctrl->ctrl.icdoff); sg->length = cpu_to_le32(sg_dma_len(req->sg_table.sgl)); sg->type = (NVME_SGL_FMT_DATA_DESC << 4) | NVME_SGL_FMT_OFFSET; req->inline_data = true; req->num_sge++; return 0; } static int nvme_rdma_map_sg_single(struct nvme_rdma_queue *queue, struct nvme_rdma_request *req, struct nvme_command *c) { struct nvme_keyed_sgl_desc *sg = &c->common.dptr.ksgl; sg->addr = cpu_to_le64(sg_dma_address(req->sg_table.sgl)); put_unaligned_le24(sg_dma_len(req->sg_table.sgl), sg->length); put_unaligned_le32(queue->device->pd->unsafe_global_rkey, sg->key); sg->type = NVME_KEY_SGL_FMT_DATA_DESC << 4; return 0; } static int nvme_rdma_map_sg_fr(struct nvme_rdma_queue *queue, struct nvme_rdma_request *req, struct nvme_command *c, int count) { struct nvme_keyed_sgl_desc *sg = &c->common.dptr.ksgl; int nr; nr = ib_map_mr_sg(req->mr, req->sg_table.sgl, count, NULL, PAGE_SIZE); if (nr < count) { if (nr < 0) return nr; return -EINVAL; } ib_update_fast_reg_key(req->mr, ib_inc_rkey(req->mr->rkey)); req->reg_cqe.done = nvme_rdma_memreg_done; memset(&req->reg_wr, 0, sizeof(req->reg_wr)); req->reg_wr.wr.opcode = IB_WR_REG_MR; req->reg_wr.wr.wr_cqe = &req->reg_cqe; req->reg_wr.wr.num_sge = 0; req->reg_wr.mr = req->mr; req->reg_wr.key = req->mr->rkey; req->reg_wr.access = IB_ACCESS_LOCAL_WRITE | IB_ACCESS_REMOTE_READ | IB_ACCESS_REMOTE_WRITE; req->mr->need_inval = true; sg->addr = cpu_to_le64(req->mr->iova); put_unaligned_le24(req->mr->length, sg->length); put_unaligned_le32(req->mr->rkey, sg->key); sg->type = (NVME_KEY_SGL_FMT_DATA_DESC << 4) | NVME_SGL_FMT_INVALIDATE; return 0; } static int nvme_rdma_map_data(struct nvme_rdma_queue *queue, struct request *rq, struct nvme_command *c) { struct nvme_rdma_request *req = blk_mq_rq_to_pdu(rq); struct nvme_rdma_device *dev = queue->device; struct ib_device *ibdev = dev->dev; int count, ret; req->num_sge = 1; req->inline_data = false; req->mr->need_inval = false; c->common.flags |= NVME_CMD_SGL_METABUF; if (!blk_rq_bytes(rq)) return nvme_rdma_set_sg_null(c); req->sg_table.sgl = req->first_sgl; ret = sg_alloc_table_chained(&req->sg_table, blk_rq_nr_phys_segments(rq), req->sg_table.sgl); if (ret) return -ENOMEM; req->nents = blk_rq_map_sg(rq->q, rq, req->sg_table.sgl); count = ib_dma_map_sg(ibdev, req->sg_table.sgl, req->nents, rq_data_dir(rq) == WRITE ? DMA_TO_DEVICE : DMA_FROM_DEVICE); if (unlikely(count <= 0)) { sg_free_table_chained(&req->sg_table, true); return -EIO; } if (count == 1) { if (rq_data_dir(rq) == WRITE && nvme_rdma_queue_idx(queue) && blk_rq_payload_bytes(rq) <= nvme_rdma_inline_data_size(queue)) return nvme_rdma_map_sg_inline(queue, req, c); if (dev->pd->flags & IB_PD_UNSAFE_GLOBAL_RKEY) return nvme_rdma_map_sg_single(queue, req, c); } return nvme_rdma_map_sg_fr(queue, req, c, count); } static void nvme_rdma_send_done(struct ib_cq *cq, struct ib_wc *wc) { if (unlikely(wc->status != IB_WC_SUCCESS)) nvme_rdma_wr_error(cq, wc, "SEND"); } static int nvme_rdma_post_send(struct nvme_rdma_queue *queue, struct nvme_rdma_qe *qe, struct ib_sge *sge, u32 num_sge, struct ib_send_wr *first, bool flush) { struct ib_send_wr wr, *bad_wr; int ret; sge->addr = qe->dma; sge->length = sizeof(struct nvme_command), sge->lkey = queue->device->pd->local_dma_lkey; qe->cqe.done = nvme_rdma_send_done; wr.next = NULL; wr.wr_cqe = &qe->cqe; wr.sg_list = sge; wr.num_sge = num_sge; wr.opcode = IB_WR_SEND; wr.send_flags = 0; /* * Unsignalled send completions are another giant desaster in the * IB Verbs spec: If we don't regularly post signalled sends * the send queue will fill up and only a QP reset will rescue us. * Would have been way to obvious to handle this in hardware or * at least the RDMA stack.. * * This messy and racy code sniplet is copy and pasted from the iSER * initiator, and the magic '32' comes from there as well. * * Always signal the flushes. The magic request used for the flush * sequencer is not allocated in our driver's tagset and it's * triggered to be freed by blk_cleanup_queue(). So we need to * always mark it as signaled to ensure that the "wr_cqe", which is * embedded in request's payload, is not freed when __ib_process_cq() * calls wr_cqe->done(). */ if ((++queue->sig_count % 32) == 0 || flush) wr.send_flags |= IB_SEND_SIGNALED; if (first) first->next = &wr; else first = &wr; ret = ib_post_send(queue->qp, first, &bad_wr); if (ret) { dev_err(queue->ctrl->ctrl.device, "%s failed with error code %d\n", __func__, ret); } return ret; } static int nvme_rdma_post_recv(struct nvme_rdma_queue *queue, struct nvme_rdma_qe *qe) { struct ib_recv_wr wr, *bad_wr; struct ib_sge list; int ret; list.addr = qe->dma; list.length = sizeof(struct nvme_completion); list.lkey = queue->device->pd->local_dma_lkey; qe->cqe.done = nvme_rdma_recv_done; wr.next = NULL; wr.wr_cqe = &qe->cqe; wr.sg_list = &list; wr.num_sge = 1; ret = ib_post_recv(queue->qp, &wr, &bad_wr); if (ret) { dev_err(queue->ctrl->ctrl.device, "%s failed with error code %d\n", __func__, ret); } return ret; } static struct blk_mq_tags *nvme_rdma_tagset(struct nvme_rdma_queue *queue) { u32 queue_idx = nvme_rdma_queue_idx(queue); if (queue_idx == 0) return queue->ctrl->admin_tag_set.tags[queue_idx]; return queue->ctrl->tag_set.tags[queue_idx - 1]; } static void nvme_rdma_submit_async_event(struct nvme_ctrl *arg, int aer_idx) { struct nvme_rdma_ctrl *ctrl = to_rdma_ctrl(arg); struct nvme_rdma_queue *queue = &ctrl->queues[0]; struct ib_device *dev = queue->device->dev; struct nvme_rdma_qe *sqe = &ctrl->async_event_sqe; struct nvme_command *cmd = sqe->data; struct ib_sge sge; int ret; if (WARN_ON_ONCE(aer_idx != 0)) return; ib_dma_sync_single_for_cpu(dev, sqe->dma, sizeof(*cmd), DMA_TO_DEVICE); memset(cmd, 0, sizeof(*cmd)); cmd->common.opcode = nvme_admin_async_event; cmd->common.command_id = NVME_RDMA_AQ_BLKMQ_DEPTH; cmd->common.flags |= NVME_CMD_SGL_METABUF; nvme_rdma_set_sg_null(cmd); ib_dma_sync_single_for_device(dev, sqe->dma, sizeof(*cmd), DMA_TO_DEVICE); ret = nvme_rdma_post_send(queue, sqe, &sge, 1, NULL, false); WARN_ON_ONCE(ret); } static int nvme_rdma_process_nvme_rsp(struct nvme_rdma_queue *queue, struct nvme_completion *cqe, struct ib_wc *wc, int tag) { struct request *rq; struct nvme_rdma_request *req; int ret = 0; rq = blk_mq_tag_to_rq(nvme_rdma_tagset(queue), cqe->command_id); if (!rq) { dev_err(queue->ctrl->ctrl.device, "tag 0x%x on QP %#x not found\n", cqe->command_id, queue->qp->qp_num); nvme_rdma_error_recovery(queue->ctrl); return ret; } req = blk_mq_rq_to_pdu(rq); if (rq->tag == tag) ret = 1; if ((wc->wc_flags & IB_WC_WITH_INVALIDATE) && wc->ex.invalidate_rkey == req->mr->rkey) req->mr->need_inval = false; req->req.result = cqe->result; blk_mq_complete_request(rq, le16_to_cpu(cqe->status) >> 1); return ret; } static int __nvme_rdma_recv_done(struct ib_cq *cq, struct ib_wc *wc, int tag) { struct nvme_rdma_qe *qe = container_of(wc->wr_cqe, struct nvme_rdma_qe, cqe); struct nvme_rdma_queue *queue = cq->cq_context; struct ib_device *ibdev = queue->device->dev; struct nvme_completion *cqe = qe->data; const size_t len = sizeof(struct nvme_completion); int ret = 0; if (unlikely(wc->status != IB_WC_SUCCESS)) { nvme_rdma_wr_error(cq, wc, "RECV"); return 0; } ib_dma_sync_single_for_cpu(ibdev, qe->dma, len, DMA_FROM_DEVICE); /* * AEN requests are special as they don't time out and can * survive any kind of queue freeze and often don't respond to * aborts. We don't even bother to allocate a struct request * for them but rather special case them here. */ if (unlikely(nvme_rdma_queue_idx(queue) == 0 && cqe->command_id >= NVME_RDMA_AQ_BLKMQ_DEPTH)) nvme_complete_async_event(&queue->ctrl->ctrl, cqe->status, &cqe->result); else ret = nvme_rdma_process_nvme_rsp(queue, cqe, wc, tag); ib_dma_sync_single_for_device(ibdev, qe->dma, len, DMA_FROM_DEVICE); nvme_rdma_post_recv(queue, qe); return ret; } static void nvme_rdma_recv_done(struct ib_cq *cq, struct ib_wc *wc) { __nvme_rdma_recv_done(cq, wc, -1); } static int nvme_rdma_conn_established(struct nvme_rdma_queue *queue) { int ret, i; for (i = 0; i < queue->queue_size; i++) { ret = nvme_rdma_post_recv(queue, &queue->rsp_ring[i]); if (ret) goto out_destroy_queue_ib; } return 0; out_destroy_queue_ib: nvme_rdma_destroy_queue_ib(queue); return ret; } static int nvme_rdma_conn_rejected(struct nvme_rdma_queue *queue, struct rdma_cm_event *ev) { struct rdma_cm_id *cm_id = queue->cm_id; int status = ev->status; const char *rej_msg; const struct nvme_rdma_cm_rej *rej_data; u8 rej_data_len; rej_msg = rdma_reject_msg(cm_id, status); rej_data = rdma_consumer_reject_data(cm_id, ev, &rej_data_len); if (rej_data && rej_data_len >= sizeof(u16)) { u16 sts = le16_to_cpu(rej_data->sts); dev_err(queue->ctrl->ctrl.device, "Connect rejected: status %d (%s) nvme status %d (%s).\n", status, rej_msg, sts, nvme_rdma_cm_msg(sts)); } else { dev_err(queue->ctrl->ctrl.device, "Connect rejected: status %d (%s).\n", status, rej_msg); } return -ECONNRESET; } static int nvme_rdma_addr_resolved(struct nvme_rdma_queue *queue) { struct nvme_rdma_device *dev; int ret; dev = nvme_rdma_find_get_device(queue->cm_id); if (!dev) { dev_err(queue->cm_id->device->dev.parent, "no client data found!\n"); return -ECONNREFUSED; } ret = nvme_rdma_create_queue_ib(queue, dev); if (ret) { nvme_rdma_dev_put(dev); goto out; } ret = rdma_resolve_route(queue->cm_id, NVME_RDMA_CONNECT_TIMEOUT_MS); if (ret) { dev_err(queue->ctrl->ctrl.device, "rdma_resolve_route failed (%d).\n", queue->cm_error); goto out_destroy_queue; } return 0; out_destroy_queue: nvme_rdma_destroy_queue_ib(queue); out: return ret; } static int nvme_rdma_route_resolved(struct nvme_rdma_queue *queue) { struct nvme_rdma_ctrl *ctrl = queue->ctrl; struct rdma_conn_param param = { }; struct nvme_rdma_cm_req priv = { }; int ret; param.qp_num = queue->qp->qp_num; param.flow_control = 1; param.responder_resources = queue->device->dev->attrs.max_qp_rd_atom; /* maximum retry count */ param.retry_count = 7; param.rnr_retry_count = 7; param.private_data = &priv; param.private_data_len = sizeof(priv); priv.recfmt = cpu_to_le16(NVME_RDMA_CM_FMT_1_0); priv.qid = cpu_to_le16(nvme_rdma_queue_idx(queue)); /* * set the admin queue depth to the minimum size * specified by the Fabrics standard. */ if (priv.qid == 0) { priv.hrqsize = cpu_to_le16(NVMF_AQ_DEPTH); priv.hsqsize = cpu_to_le16(NVMF_AQ_DEPTH - 1); } else { /* * current interpretation of the fabrics spec * is at minimum you make hrqsize sqsize+1, or a * 1's based representation of sqsize. */ priv.hrqsize = cpu_to_le16(queue->queue_size); priv.hsqsize = cpu_to_le16(queue->ctrl->ctrl.sqsize); } ret = rdma_connect(queue->cm_id, &param); if (ret) { dev_err(ctrl->ctrl.device, "rdma_connect failed (%d).\n", ret); goto out_destroy_queue_ib; } return 0; out_destroy_queue_ib: nvme_rdma_destroy_queue_ib(queue); return ret; } static int nvme_rdma_cm_handler(struct rdma_cm_id *cm_id, struct rdma_cm_event *ev) { struct nvme_rdma_queue *queue = cm_id->context; int cm_error = 0; dev_dbg(queue->ctrl->ctrl.device, "%s (%d): status %d id %p\n", rdma_event_msg(ev->event), ev->event, ev->status, cm_id); switch (ev->event) { case RDMA_CM_EVENT_ADDR_RESOLVED: cm_error = nvme_rdma_addr_resolved(queue); break; case RDMA_CM_EVENT_ROUTE_RESOLVED: cm_error = nvme_rdma_route_resolved(queue); break; case RDMA_CM_EVENT_ESTABLISHED: queue->cm_error = nvme_rdma_conn_established(queue); /* complete cm_done regardless of success/failure */ complete(&queue->cm_done); return 0; case RDMA_CM_EVENT_REJECTED: cm_error = nvme_rdma_conn_rejected(queue, ev); break; case RDMA_CM_EVENT_ADDR_ERROR: case RDMA_CM_EVENT_ROUTE_ERROR: case RDMA_CM_EVENT_CONNECT_ERROR: case RDMA_CM_EVENT_UNREACHABLE: dev_dbg(queue->ctrl->ctrl.device, "CM error event %d\n", ev->event); cm_error = -ECONNRESET; break; case RDMA_CM_EVENT_DISCONNECTED: case RDMA_CM_EVENT_ADDR_CHANGE: case RDMA_CM_EVENT_TIMEWAIT_EXIT: dev_dbg(queue->ctrl->ctrl.device, "disconnect received - connection closed\n"); nvme_rdma_error_recovery(queue->ctrl); break; case RDMA_CM_EVENT_DEVICE_REMOVAL: /* device removal is handled via the ib_client API */ break; default: dev_err(queue->ctrl->ctrl.device, "Unexpected RDMA CM event (%d)\n", ev->event); nvme_rdma_error_recovery(queue->ctrl); break; } if (cm_error) { queue->cm_error = cm_error; complete(&queue->cm_done); } return 0; } static enum blk_eh_timer_return nvme_rdma_timeout(struct request *rq, bool reserved) { struct nvme_rdma_request *req = blk_mq_rq_to_pdu(rq); /* queue error recovery */ nvme_rdma_error_recovery(req->queue->ctrl); /* fail with DNR on cmd timeout */ rq->errors = NVME_SC_ABORT_REQ | NVME_SC_DNR; return BLK_EH_HANDLED; } /* * We cannot accept any other command until the Connect command has completed. */ static inline bool nvme_rdma_queue_is_ready(struct nvme_rdma_queue *queue, struct request *rq) { if (unlikely(!test_bit(NVME_RDMA_Q_LIVE, &queue->flags))) { struct nvme_command *cmd = nvme_req(rq)->cmd; if (!blk_rq_is_passthrough(rq) || cmd->common.opcode != nvme_fabrics_command || cmd->fabrics.fctype != nvme_fabrics_type_connect) return false; } return true; } static int nvme_rdma_queue_rq(struct blk_mq_hw_ctx *hctx, const struct blk_mq_queue_data *bd) { struct nvme_ns *ns = hctx->queue->queuedata; struct nvme_rdma_queue *queue = hctx->driver_data; struct request *rq = bd->rq; struct nvme_rdma_request *req = blk_mq_rq_to_pdu(rq); struct nvme_rdma_qe *sqe = &req->sqe; struct nvme_command *c = sqe->data; bool flush = false; struct ib_device *dev; int ret; WARN_ON_ONCE(rq->tag < 0); if (!nvme_rdma_queue_is_ready(queue, rq)) return BLK_MQ_RQ_QUEUE_BUSY; dev = queue->device->dev; ib_dma_sync_single_for_cpu(dev, sqe->dma, sizeof(struct nvme_command), DMA_TO_DEVICE); ret = nvme_setup_cmd(ns, rq, c); if (ret != BLK_MQ_RQ_QUEUE_OK) return ret; blk_mq_start_request(rq); ret = nvme_rdma_map_data(queue, rq, c); if (ret < 0) { dev_err(queue->ctrl->ctrl.device, "Failed to map data (%d)\n", ret); nvme_cleanup_cmd(rq); goto err; } ib_dma_sync_single_for_device(dev, sqe->dma, sizeof(struct nvme_command), DMA_TO_DEVICE); if (req_op(rq) == REQ_OP_FLUSH) flush = true; ret = nvme_rdma_post_send(queue, sqe, req->sge, req->num_sge, req->mr->need_inval ? &req->reg_wr.wr : NULL, flush); if (ret) { nvme_rdma_unmap_data(queue, rq); goto err; } return BLK_MQ_RQ_QUEUE_OK; err: return (ret == -ENOMEM || ret == -EAGAIN) ? BLK_MQ_RQ_QUEUE_BUSY : BLK_MQ_RQ_QUEUE_ERROR; } static int nvme_rdma_poll(struct blk_mq_hw_ctx *hctx, unsigned int tag) { struct nvme_rdma_queue *queue = hctx->driver_data; struct ib_cq *cq = queue->ib_cq; struct ib_wc wc; int found = 0; ib_req_notify_cq(cq, IB_CQ_NEXT_COMP); while (ib_poll_cq(cq, 1, &wc) > 0) { struct ib_cqe *cqe = wc.wr_cqe; if (cqe) { if (cqe->done == nvme_rdma_recv_done) found |= __nvme_rdma_recv_done(cq, &wc, tag); else cqe->done(cq, &wc); } } return found; } static void nvme_rdma_complete_rq(struct request *rq) { struct nvme_rdma_request *req = blk_mq_rq_to_pdu(rq); struct nvme_rdma_queue *queue = req->queue; int error = 0; nvme_rdma_unmap_data(queue, rq); if (unlikely(rq->errors)) { if (nvme_req_needs_retry(rq, rq->errors)) { nvme_requeue_req(rq); return; } if (blk_rq_is_passthrough(rq)) error = rq->errors; else error = nvme_error_status(rq->errors); } blk_mq_end_request(rq, error); } static struct blk_mq_ops nvme_rdma_mq_ops = { .queue_rq = nvme_rdma_queue_rq, .complete = nvme_rdma_complete_rq, .init_request = nvme_rdma_init_request, .exit_request = nvme_rdma_exit_request, .reinit_request = nvme_rdma_reinit_request, .init_hctx = nvme_rdma_init_hctx, .poll = nvme_rdma_poll, .timeout = nvme_rdma_timeout, }; static struct blk_mq_ops nvme_rdma_admin_mq_ops = { .queue_rq = nvme_rdma_queue_rq, .complete = nvme_rdma_complete_rq, .init_request = nvme_rdma_init_admin_request, .exit_request = nvme_rdma_exit_admin_request, .reinit_request = nvme_rdma_reinit_request, .init_hctx = nvme_rdma_init_admin_hctx, .timeout = nvme_rdma_timeout, }; static int nvme_rdma_configure_admin_queue(struct nvme_rdma_ctrl *ctrl) { int error; error = nvme_rdma_init_queue(ctrl, 0, NVMF_AQ_DEPTH); if (error) return error; ctrl->device = ctrl->queues[0].device; /* * We need a reference on the device as long as the tag_set is alive, * as the MRs in the request structures need a valid ib_device. */ error = -EINVAL; if (!nvme_rdma_dev_get(ctrl->device)) goto out_free_queue; ctrl->max_fr_pages = min_t(u32, NVME_RDMA_MAX_SEGMENTS, ctrl->device->dev->attrs.max_fast_reg_page_list_len); memset(&ctrl->admin_tag_set, 0, sizeof(ctrl->admin_tag_set)); ctrl->admin_tag_set.ops = &nvme_rdma_admin_mq_ops; ctrl->admin_tag_set.queue_depth = NVME_RDMA_AQ_BLKMQ_DEPTH; ctrl->admin_tag_set.reserved_tags = 2; /* connect + keep-alive */ ctrl->admin_tag_set.numa_node = NUMA_NO_NODE; ctrl->admin_tag_set.cmd_size = sizeof(struct nvme_rdma_request) + SG_CHUNK_SIZE * sizeof(struct scatterlist); ctrl->admin_tag_set.driver_data = ctrl; ctrl->admin_tag_set.nr_hw_queues = 1; ctrl->admin_tag_set.timeout = ADMIN_TIMEOUT; error = blk_mq_alloc_tag_set(&ctrl->admin_tag_set); if (error) goto out_put_dev; ctrl->ctrl.admin_q = blk_mq_init_queue(&ctrl->admin_tag_set); if (IS_ERR(ctrl->ctrl.admin_q)) { error = PTR_ERR(ctrl->ctrl.admin_q); goto out_free_tagset; } error = nvmf_connect_admin_queue(&ctrl->ctrl); if (error) goto out_cleanup_queue; set_bit(NVME_RDMA_Q_LIVE, &ctrl->queues[0].flags); error = nvmf_reg_read64(&ctrl->ctrl, NVME_REG_CAP, &ctrl->cap); if (error) { dev_err(ctrl->ctrl.device, "prop_get NVME_REG_CAP failed\n"); goto out_cleanup_queue; } ctrl->ctrl.sqsize = min_t(int, NVME_CAP_MQES(ctrl->cap) + 1, ctrl->ctrl.sqsize); error = nvme_enable_ctrl(&ctrl->ctrl, ctrl->cap); if (error) goto out_cleanup_queue; ctrl->ctrl.max_hw_sectors = (ctrl->max_fr_pages - 1) << (PAGE_SHIFT - 9); error = nvme_init_identify(&ctrl->ctrl); if (error) goto out_cleanup_queue; error = nvme_rdma_alloc_qe(ctrl->queues[0].device->dev, &ctrl->async_event_sqe, sizeof(struct nvme_command), DMA_TO_DEVICE); if (error) goto out_cleanup_queue; nvme_start_keep_alive(&ctrl->ctrl); return 0; out_cleanup_queue: blk_cleanup_queue(ctrl->ctrl.admin_q); out_free_tagset: /* disconnect and drain the queue before freeing the tagset */ nvme_rdma_stop_queue(&ctrl->queues[0]); blk_mq_free_tag_set(&ctrl->admin_tag_set); out_put_dev: nvme_rdma_dev_put(ctrl->device); out_free_queue: nvme_rdma_free_queue(&ctrl->queues[0]); return error; } static void nvme_rdma_shutdown_ctrl(struct nvme_rdma_ctrl *ctrl) { nvme_stop_keep_alive(&ctrl->ctrl); cancel_work_sync(&ctrl->err_work); cancel_delayed_work_sync(&ctrl->reconnect_work); if (ctrl->queue_count > 1) { nvme_stop_queues(&ctrl->ctrl); blk_mq_tagset_busy_iter(&ctrl->tag_set, nvme_cancel_request, &ctrl->ctrl); nvme_rdma_free_io_queues(ctrl); } if (test_bit(NVME_RDMA_Q_CONNECTED, &ctrl->queues[0].flags)) nvme_shutdown_ctrl(&ctrl->ctrl); blk_mq_stop_hw_queues(ctrl->ctrl.admin_q); blk_mq_tagset_busy_iter(&ctrl->admin_tag_set, nvme_cancel_request, &ctrl->ctrl); nvme_rdma_destroy_admin_queue(ctrl); } static void __nvme_rdma_remove_ctrl(struct nvme_rdma_ctrl *ctrl, bool shutdown) { nvme_uninit_ctrl(&ctrl->ctrl); if (shutdown) nvme_rdma_shutdown_ctrl(ctrl); if (ctrl->ctrl.tagset) { blk_cleanup_queue(ctrl->ctrl.connect_q); blk_mq_free_tag_set(&ctrl->tag_set); nvme_rdma_dev_put(ctrl->device); } nvme_put_ctrl(&ctrl->ctrl); } static void nvme_rdma_del_ctrl_work(struct work_struct *work) { struct nvme_rdma_ctrl *ctrl = container_of(work, struct nvme_rdma_ctrl, delete_work); __nvme_rdma_remove_ctrl(ctrl, true); } static int __nvme_rdma_del_ctrl(struct nvme_rdma_ctrl *ctrl) { if (!nvme_change_ctrl_state(&ctrl->ctrl, NVME_CTRL_DELETING)) return -EBUSY; if (!queue_work(nvme_rdma_wq, &ctrl->delete_work)) return -EBUSY; return 0; } static int nvme_rdma_del_ctrl(struct nvme_ctrl *nctrl) { struct nvme_rdma_ctrl *ctrl = to_rdma_ctrl(nctrl); int ret = 0; /* * Keep a reference until all work is flushed since * __nvme_rdma_del_ctrl can free the ctrl mem */ if (!kref_get_unless_zero(&ctrl->ctrl.kref)) return -EBUSY; ret = __nvme_rdma_del_ctrl(ctrl); if (!ret) flush_work(&ctrl->delete_work); nvme_put_ctrl(&ctrl->ctrl); return ret; } static void nvme_rdma_remove_ctrl_work(struct work_struct *work) { struct nvme_rdma_ctrl *ctrl = container_of(work, struct nvme_rdma_ctrl, delete_work); __nvme_rdma_remove_ctrl(ctrl, false); } static void nvme_rdma_reset_ctrl_work(struct work_struct *work) { struct nvme_rdma_ctrl *ctrl = container_of(work, struct nvme_rdma_ctrl, reset_work); int ret; bool changed; nvme_rdma_shutdown_ctrl(ctrl); ret = nvme_rdma_configure_admin_queue(ctrl); if (ret) { /* ctrl is already shutdown, just remove the ctrl */ INIT_WORK(&ctrl->delete_work, nvme_rdma_remove_ctrl_work); goto del_dead_ctrl; } if (ctrl->queue_count > 1) { ret = blk_mq_reinit_tagset(&ctrl->tag_set); if (ret) goto del_dead_ctrl; ret = nvme_rdma_init_io_queues(ctrl); if (ret) goto del_dead_ctrl; ret = nvme_rdma_connect_io_queues(ctrl); if (ret) goto del_dead_ctrl; } changed = nvme_change_ctrl_state(&ctrl->ctrl, NVME_CTRL_LIVE); WARN_ON_ONCE(!changed); if (ctrl->queue_count > 1) { nvme_start_queues(&ctrl->ctrl); nvme_queue_scan(&ctrl->ctrl); nvme_queue_async_events(&ctrl->ctrl); } return; del_dead_ctrl: /* Deleting this dead controller... */ dev_warn(ctrl->ctrl.device, "Removing after reset failure\n"); WARN_ON(!queue_work(nvme_rdma_wq, &ctrl->delete_work)); } static int nvme_rdma_reset_ctrl(struct nvme_ctrl *nctrl) { struct nvme_rdma_ctrl *ctrl = to_rdma_ctrl(nctrl); if (!nvme_change_ctrl_state(&ctrl->ctrl, NVME_CTRL_RESETTING)) return -EBUSY; if (!queue_work(nvme_rdma_wq, &ctrl->reset_work)) return -EBUSY; flush_work(&ctrl->reset_work); return 0; } static const struct nvme_ctrl_ops nvme_rdma_ctrl_ops = { .name = "rdma", .module = THIS_MODULE, .is_fabrics = true, .reg_read32 = nvmf_reg_read32, .reg_read64 = nvmf_reg_read64, .reg_write32 = nvmf_reg_write32, .reset_ctrl = nvme_rdma_reset_ctrl, .free_ctrl = nvme_rdma_free_ctrl, .submit_async_event = nvme_rdma_submit_async_event, .delete_ctrl = nvme_rdma_del_ctrl, .get_subsysnqn = nvmf_get_subsysnqn, .get_address = nvmf_get_address, }; static int nvme_rdma_create_io_queues(struct nvme_rdma_ctrl *ctrl) { int ret; ret = nvme_rdma_init_io_queues(ctrl); if (ret) return ret; /* * We need a reference on the device as long as the tag_set is alive, * as the MRs in the request structures need a valid ib_device. */ ret = -EINVAL; if (!nvme_rdma_dev_get(ctrl->device)) goto out_free_io_queues; memset(&ctrl->tag_set, 0, sizeof(ctrl->tag_set)); ctrl->tag_set.ops = &nvme_rdma_mq_ops; ctrl->tag_set.queue_depth = ctrl->ctrl.opts->queue_size; ctrl->tag_set.reserved_tags = 1; /* fabric connect */ ctrl->tag_set.numa_node = NUMA_NO_NODE; ctrl->tag_set.flags = BLK_MQ_F_SHOULD_MERGE; ctrl->tag_set.cmd_size = sizeof(struct nvme_rdma_request) + SG_CHUNK_SIZE * sizeof(struct scatterlist); ctrl->tag_set.driver_data = ctrl; ctrl->tag_set.nr_hw_queues = ctrl->queue_count - 1; ctrl->tag_set.timeout = NVME_IO_TIMEOUT; ret = blk_mq_alloc_tag_set(&ctrl->tag_set); if (ret) goto out_put_dev; ctrl->ctrl.tagset = &ctrl->tag_set; ctrl->ctrl.connect_q = blk_mq_init_queue(&ctrl->tag_set); if (IS_ERR(ctrl->ctrl.connect_q)) { ret = PTR_ERR(ctrl->ctrl.connect_q); goto out_free_tag_set; } ret = nvme_rdma_connect_io_queues(ctrl); if (ret) goto out_cleanup_connect_q; return 0; out_cleanup_connect_q: blk_cleanup_queue(ctrl->ctrl.connect_q); out_free_tag_set: blk_mq_free_tag_set(&ctrl->tag_set); out_put_dev: nvme_rdma_dev_put(ctrl->device); out_free_io_queues: nvme_rdma_free_io_queues(ctrl); return ret; } static int nvme_rdma_parse_ipaddr(struct sockaddr_in *in_addr, char *p) { u8 *addr = (u8 *)&in_addr->sin_addr.s_addr; size_t buflen = strlen(p); /* XXX: handle IPv6 addresses */ if (buflen > INET_ADDRSTRLEN) return -EINVAL; if (in4_pton(p, buflen, addr, '\0', NULL) == 0) return -EINVAL; in_addr->sin_family = AF_INET; return 0; } static struct nvme_ctrl *nvme_rdma_create_ctrl(struct device *dev, struct nvmf_ctrl_options *opts) { struct nvme_rdma_ctrl *ctrl; int ret; bool changed; ctrl = kzalloc(sizeof(*ctrl), GFP_KERNEL); if (!ctrl) return ERR_PTR(-ENOMEM); ctrl->ctrl.opts = opts; INIT_LIST_HEAD(&ctrl->list); ret = nvme_rdma_parse_ipaddr(&ctrl->addr_in, opts->traddr); if (ret) { pr_err("malformed IP address passed: %s\n", opts->traddr); goto out_free_ctrl; } if (opts->mask & NVMF_OPT_HOST_TRADDR) { ret = nvme_rdma_parse_ipaddr(&ctrl->src_addr_in, opts->host_traddr); if (ret) { pr_err("malformed src IP address passed: %s\n", opts->host_traddr); goto out_free_ctrl; } } if (opts->mask & NVMF_OPT_TRSVCID) { u16 port; ret = kstrtou16(opts->trsvcid, 0, &port); if (ret) goto out_free_ctrl; ctrl->addr_in.sin_port = cpu_to_be16(port); } else { ctrl->addr_in.sin_port = cpu_to_be16(NVME_RDMA_IP_PORT); } ret = nvme_init_ctrl(&ctrl->ctrl, dev, &nvme_rdma_ctrl_ops, 0 /* no quirks, we're perfect! */); if (ret) goto out_free_ctrl; ctrl->reconnect_delay = opts->reconnect_delay; INIT_DELAYED_WORK(&ctrl->reconnect_work, nvme_rdma_reconnect_ctrl_work); INIT_WORK(&ctrl->err_work, nvme_rdma_error_recovery_work); INIT_WORK(&ctrl->delete_work, nvme_rdma_del_ctrl_work); INIT_WORK(&ctrl->reset_work, nvme_rdma_reset_ctrl_work); spin_lock_init(&ctrl->lock); ctrl->queue_count = opts->nr_io_queues + 1; /* +1 for admin queue */ ctrl->ctrl.sqsize = opts->queue_size - 1; ctrl->ctrl.kato = opts->kato; ret = -ENOMEM; ctrl->queues = kcalloc(ctrl->queue_count, sizeof(*ctrl->queues), GFP_KERNEL); if (!ctrl->queues) goto out_uninit_ctrl; ret = nvme_rdma_configure_admin_queue(ctrl); if (ret) goto out_kfree_queues; /* sanity check icdoff */ if (ctrl->ctrl.icdoff) { dev_err(ctrl->ctrl.device, "icdoff is not supported!\n"); goto out_remove_admin_queue; } /* sanity check keyed sgls */ if (!(ctrl->ctrl.sgls & (1 << 20))) { dev_err(ctrl->ctrl.device, "Mandatory keyed sgls are not support\n"); goto out_remove_admin_queue; } if (opts->queue_size > ctrl->ctrl.maxcmd) { /* warn if maxcmd is lower than queue_size */ dev_warn(ctrl->ctrl.device, "queue_size %zu > ctrl maxcmd %u, clamping down\n", opts->queue_size, ctrl->ctrl.maxcmd); opts->queue_size = ctrl->ctrl.maxcmd; } if (opts->queue_size > ctrl->ctrl.sqsize + 1) { /* warn if sqsize is lower than queue_size */ dev_warn(ctrl->ctrl.device, "queue_size %zu > ctrl sqsize %u, clamping down\n", opts->queue_size, ctrl->ctrl.sqsize + 1); opts->queue_size = ctrl->ctrl.sqsize + 1; } if (opts->nr_io_queues) { ret = nvme_rdma_create_io_queues(ctrl); if (ret) goto out_remove_admin_queue; } changed = nvme_change_ctrl_state(&ctrl->ctrl, NVME_CTRL_LIVE); WARN_ON_ONCE(!changed); dev_info(ctrl->ctrl.device, "new ctrl: NQN \"%s\", addr %pISp\n", ctrl->ctrl.opts->subsysnqn, &ctrl->addr); kref_get(&ctrl->ctrl.kref); mutex_lock(&nvme_rdma_ctrl_mutex); list_add_tail(&ctrl->list, &nvme_rdma_ctrl_list); mutex_unlock(&nvme_rdma_ctrl_mutex); if (opts->nr_io_queues) { nvme_queue_scan(&ctrl->ctrl); nvme_queue_async_events(&ctrl->ctrl); } return &ctrl->ctrl; out_remove_admin_queue: nvme_stop_keep_alive(&ctrl->ctrl); nvme_rdma_destroy_admin_queue(ctrl); out_kfree_queues: kfree(ctrl->queues); out_uninit_ctrl: nvme_uninit_ctrl(&ctrl->ctrl); nvme_put_ctrl(&ctrl->ctrl); if (ret > 0) ret = -EIO; return ERR_PTR(ret); out_free_ctrl: kfree(ctrl); return ERR_PTR(ret); } static struct nvmf_transport_ops nvme_rdma_transport = { .name = "rdma", .required_opts = NVMF_OPT_TRADDR, .allowed_opts = NVMF_OPT_TRSVCID | NVMF_OPT_RECONNECT_DELAY | NVMF_OPT_HOST_TRADDR, .create_ctrl = nvme_rdma_create_ctrl, }; static void nvme_rdma_add_one(struct ib_device *ib_device) { } static void nvme_rdma_remove_one(struct ib_device *ib_device, void *client_data) { struct nvme_rdma_ctrl *ctrl; /* Delete all controllers using this device */ mutex_lock(&nvme_rdma_ctrl_mutex); list_for_each_entry(ctrl, &nvme_rdma_ctrl_list, list) { if (ctrl->device->dev != ib_device) continue; dev_info(ctrl->ctrl.device, "Removing ctrl: NQN \"%s\", addr %pISp\n", ctrl->ctrl.opts->subsysnqn, &ctrl->addr); __nvme_rdma_del_ctrl(ctrl); } mutex_unlock(&nvme_rdma_ctrl_mutex); flush_workqueue(nvme_rdma_wq); } static struct ib_client nvme_rdma_ib_client = { .name = "nvme_rdma", .add = nvme_rdma_add_one, .remove = nvme_rdma_remove_one }; static int __init nvme_rdma_init_module(void) { int ret; nvme_rdma_wq = create_workqueue("nvme_rdma_wq"); if (!nvme_rdma_wq) return -ENOMEM; ret = ib_register_client(&nvme_rdma_ib_client); if (ret) { destroy_workqueue(nvme_rdma_wq); return ret; } return nvmf_register_transport(&nvme_rdma_transport); } static void __exit nvme_rdma_cleanup_module(void) { nvmf_unregister_transport(&nvme_rdma_transport); ib_unregister_client(&nvme_rdma_ib_client); destroy_workqueue(nvme_rdma_wq); } module_init(nvme_rdma_init_module); module_exit(nvme_rdma_cleanup_module); MODULE_LICENSE("GPL v2");
aberlemont/linux
drivers/nvme/host/rdma.c
C
gpl-2.0
52,790
//@HEADER // ************************************************************************ // // Kokkos v. 2.0 // Copyright (2014) Sandia Corporation // // Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, // the U.S. Government retains certain rights in this software. // // Kokkos is licensed under 3-clause BSD terms of use: // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the name of the Corporation nor the names of the // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "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 SANDIA CORPORATION OR THE // 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. // // Questions? Contact Christian R. Trott ([email protected]) // // ************************************************************************ //@HEADER #define KOKKOS_IMPL_COMPILING_LIBRARY true #include<Kokkos_Core.hpp> namespace Kokkos { namespace Impl { KOKKOS_IMPL_VIEWCOPY_ETI_INST(int********,LayoutRight,LayoutRight, Experimental::ROCm,int) KOKKOS_IMPL_VIEWCOPY_ETI_INST(int********,LayoutRight,LayoutLeft, Experimental::ROCm,int) KOKKOS_IMPL_VIEWCOPY_ETI_INST(int********,LayoutRight,LayoutStride,Experimental::ROCm,int) KOKKOS_IMPL_VIEWFILL_ETI_INST(int********,LayoutRight,Experimental::ROCm,int) } }
quang-ha/lammps
lib/kokkos/core/src/eti/ROCm/Kokkos_ROCm_ViewCopyETIInst_int_int_LayoutRight_Rank8.cpp
C++
gpl-2.0
2,482
/* * Copyright (c) 2006 Dave Airlie <[email protected]> * Copyright (c) 2007-2008 Intel Corporation * Jesse Barnes <[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #ifndef __INTEL_DRV_H__ #define __INTEL_DRV_H__ #include <linux/async.h> #include <linux/i2c.h> #include <linux/hdmi.h> #include <linux/sched/clock.h> #include <drm/i915_drm.h> #include "i915_drv.h" #include <drm/drm_crtc.h> #include <drm/drm_crtc_helper.h> #include <drm/drm_encoder.h> #include <drm/drm_fb_helper.h> #include <drm/drm_dp_dual_mode_helper.h> #include <drm/drm_dp_mst_helper.h> #include <drm/drm_rect.h> #include <drm/drm_atomic.h> /** * _wait_for - magic (register) wait macro * * Does the right thing for modeset paths when run under kdgb or similar atomic * contexts. Note that it's important that we check the condition again after * having timed out, since the timeout could be due to preemption or similar and * we've never had a chance to check the condition before the timeout. * * TODO: When modesetting has fully transitioned to atomic, the below * drm_can_sleep() can be removed and in_atomic()/!in_atomic() asserts * added. */ #define _wait_for(COND, US, W) ({ \ unsigned long timeout__ = jiffies + usecs_to_jiffies(US) + 1; \ int ret__; \ for (;;) { \ bool expired__ = time_after(jiffies, timeout__); \ if (COND) { \ ret__ = 0; \ break; \ } \ if (expired__) { \ ret__ = -ETIMEDOUT; \ break; \ } \ if ((W) && drm_can_sleep()) { \ usleep_range((W), (W)*2); \ } else { \ cpu_relax(); \ } \ } \ ret__; \ }) #define wait_for(COND, MS) _wait_for((COND), (MS) * 1000, 1000) /* If CONFIG_PREEMPT_COUNT is disabled, in_atomic() always reports false. */ #if defined(CONFIG_DRM_I915_DEBUG) && defined(CONFIG_PREEMPT_COUNT) # define _WAIT_FOR_ATOMIC_CHECK(ATOMIC) WARN_ON_ONCE((ATOMIC) && !in_atomic()) #else # define _WAIT_FOR_ATOMIC_CHECK(ATOMIC) do { } while (0) #endif #define _wait_for_atomic(COND, US, ATOMIC) \ ({ \ int cpu, ret, timeout = (US) * 1000; \ u64 base; \ _WAIT_FOR_ATOMIC_CHECK(ATOMIC); \ if (!(ATOMIC)) { \ preempt_disable(); \ cpu = smp_processor_id(); \ } \ base = local_clock(); \ for (;;) { \ u64 now = local_clock(); \ if (!(ATOMIC)) \ preempt_enable(); \ if (COND) { \ ret = 0; \ break; \ } \ if (now - base >= timeout) { \ ret = -ETIMEDOUT; \ break; \ } \ cpu_relax(); \ if (!(ATOMIC)) { \ preempt_disable(); \ if (unlikely(cpu != smp_processor_id())) { \ timeout -= now - base; \ cpu = smp_processor_id(); \ base = local_clock(); \ } \ } \ } \ ret; \ }) #define wait_for_us(COND, US) \ ({ \ int ret__; \ BUILD_BUG_ON(!__builtin_constant_p(US)); \ if ((US) > 10) \ ret__ = _wait_for((COND), (US), 10); \ else \ ret__ = _wait_for_atomic((COND), (US), 0); \ ret__; \ }) #define wait_for_atomic_us(COND, US) \ ({ \ BUILD_BUG_ON(!__builtin_constant_p(US)); \ BUILD_BUG_ON((US) > 50000); \ _wait_for_atomic((COND), (US), 1); \ }) #define wait_for_atomic(COND, MS) wait_for_atomic_us((COND), (MS) * 1000) #define KHz(x) (1000 * (x)) #define MHz(x) KHz(1000 * (x)) /* * Display related stuff */ /* store information about an Ixxx DVO */ /* The i830->i865 use multiple DVOs with multiple i2cs */ /* the i915, i945 have a single sDVO i2c bus - which is different */ #define MAX_OUTPUTS 6 /* maximum connectors per crtcs in the mode set */ /* Maximum cursor sizes */ #define GEN2_CURSOR_WIDTH 64 #define GEN2_CURSOR_HEIGHT 64 #define MAX_CURSOR_WIDTH 256 #define MAX_CURSOR_HEIGHT 256 #define INTEL_I2C_BUS_DVO 1 #define INTEL_I2C_BUS_SDVO 2 /* these are outputs from the chip - integrated only external chips are via DVO or SDVO output */ enum intel_output_type { INTEL_OUTPUT_UNUSED = 0, INTEL_OUTPUT_ANALOG = 1, INTEL_OUTPUT_DVO = 2, INTEL_OUTPUT_SDVO = 3, INTEL_OUTPUT_LVDS = 4, INTEL_OUTPUT_TVOUT = 5, INTEL_OUTPUT_HDMI = 6, INTEL_OUTPUT_DP = 7, INTEL_OUTPUT_EDP = 8, INTEL_OUTPUT_DSI = 9, INTEL_OUTPUT_UNKNOWN = 10, INTEL_OUTPUT_DP_MST = 11, }; #define INTEL_DVO_CHIP_NONE 0 #define INTEL_DVO_CHIP_LVDS 1 #define INTEL_DVO_CHIP_TMDS 2 #define INTEL_DVO_CHIP_TVOUT 4 #define INTEL_DSI_VIDEO_MODE 0 #define INTEL_DSI_COMMAND_MODE 1 struct intel_framebuffer { struct drm_framebuffer base; struct drm_i915_gem_object *obj; struct intel_rotation_info rot_info; /* for each plane in the normal GTT view */ struct { unsigned int x, y; } normal[2]; /* for each plane in the rotated GTT view */ struct { unsigned int x, y; unsigned int pitch; /* pixels */ } rotated[2]; }; struct intel_fbdev { struct drm_fb_helper helper; struct intel_framebuffer *fb; struct i915_vma *vma; async_cookie_t cookie; int preferred_bpp; }; struct intel_encoder { struct drm_encoder base; enum intel_output_type type; enum port port; unsigned int cloneable; void (*hot_plug)(struct intel_encoder *); bool (*compute_config)(struct intel_encoder *, struct intel_crtc_state *, struct drm_connector_state *); void (*pre_pll_enable)(struct intel_encoder *, struct intel_crtc_state *, struct drm_connector_state *); void (*pre_enable)(struct intel_encoder *, struct intel_crtc_state *, struct drm_connector_state *); void (*enable)(struct intel_encoder *, struct intel_crtc_state *, struct drm_connector_state *); void (*disable)(struct intel_encoder *, struct intel_crtc_state *, struct drm_connector_state *); void (*post_disable)(struct intel_encoder *, struct intel_crtc_state *, struct drm_connector_state *); void (*post_pll_disable)(struct intel_encoder *, struct intel_crtc_state *, struct drm_connector_state *); /* Read out the current hw state of this connector, returning true if * the encoder is active. If the encoder is enabled it also set the pipe * it is connected to in the pipe parameter. */ bool (*get_hw_state)(struct intel_encoder *, enum pipe *pipe); /* Reconstructs the equivalent mode flags for the current hardware * state. This must be called _after_ display->get_pipe_config has * pre-filled the pipe config. Note that intel_encoder->base.crtc must * be set correctly before calling this function. */ void (*get_config)(struct intel_encoder *, struct intel_crtc_state *pipe_config); /* Returns a mask of power domains that need to be referenced as part * of the hardware state readout code. */ u64 (*get_power_domains)(struct intel_encoder *encoder); /* * Called during system suspend after all pending requests for the * encoder are flushed (for example for DP AUX transactions) and * device interrupts are disabled. */ void (*suspend)(struct intel_encoder *); int crtc_mask; enum hpd_pin hpd_pin; enum intel_display_power_domain power_domain; /* for communication with audio component; protected by av_mutex */ const struct drm_connector *audio_connector; }; struct intel_panel { struct drm_display_mode *fixed_mode; struct drm_display_mode *alt_fixed_mode; struct drm_display_mode *downclock_mode; /* backlight */ struct { bool present; u32 level; u32 min; u32 max; bool enabled; bool combination_mode; /* gen 2/4 only */ bool active_low_pwm; bool alternate_pwm_increment; /* lpt+ */ /* PWM chip */ bool util_pin_active_low; /* bxt+ */ u8 controller; /* bxt+ only */ struct pwm_device *pwm; struct backlight_device *device; /* Connector and platform specific backlight functions */ int (*setup)(struct intel_connector *connector, enum pipe pipe); uint32_t (*get)(struct intel_connector *connector); void (*set)(const struct drm_connector_state *conn_state, uint32_t level); void (*disable)(const struct drm_connector_state *conn_state); void (*enable)(const struct intel_crtc_state *crtc_state, const struct drm_connector_state *conn_state); uint32_t (*hz_to_pwm)(struct intel_connector *connector, uint32_t hz); void (*power)(struct intel_connector *, bool enable); } backlight; }; struct intel_connector { struct drm_connector base; /* * The fixed encoder this connector is connected to. */ struct intel_encoder *encoder; /* ACPI device id for ACPI and driver cooperation */ u32 acpi_device_id; /* Reads out the current hw, returning true if the connector is enabled * and active (i.e. dpms ON state). */ bool (*get_hw_state)(struct intel_connector *); /* Panel info for eDP and LVDS */ struct intel_panel panel; /* Cached EDID for eDP and LVDS. May hold ERR_PTR for invalid EDID. */ struct edid *edid; struct edid *detect_edid; /* since POLL and HPD connectors may use the same HPD line keep the native state of connector->polled in case hotplug storm detection changes it */ u8 polled; void *port; /* store this opaque as its illegal to dereference it */ struct intel_dp *mst_port; /* Work struct to schedule a uevent on link train failure */ struct work_struct modeset_retry_work; }; struct intel_digital_connector_state { struct drm_connector_state base; enum hdmi_force_audio force_audio; int broadcast_rgb; }; #define to_intel_digital_connector_state(x) container_of(x, struct intel_digital_connector_state, base) struct dpll { /* given values */ int n; int m1, m2; int p1, p2; /* derived values */ int dot; int vco; int m; int p; }; struct intel_atomic_state { struct drm_atomic_state base; struct { /* * Logical state of cdclk (used for all scaling, watermark, * etc. calculations and checks). This is computed as if all * enabled crtcs were active. */ struct intel_cdclk_state logical; /* * Actual state of cdclk, can be different from the logical * state only when all crtc's are DPMS off. */ struct intel_cdclk_state actual; } cdclk; bool dpll_set, modeset; /* * Does this transaction change the pipes that are active? This mask * tracks which CRTC's have changed their active state at the end of * the transaction (not counting the temporary disable during modesets). * This mask should only be non-zero when intel_state->modeset is true, * but the converse is not necessarily true; simply changing a mode may * not flip the final active status of any CRTC's */ unsigned int active_pipe_changes; unsigned int active_crtcs; unsigned int min_pixclk[I915_MAX_PIPES]; struct intel_shared_dpll_state shared_dpll[I915_NUM_PLLS]; /* * Current watermarks can't be trusted during hardware readout, so * don't bother calculating intermediate watermarks. */ bool skip_intermediate_wm; /* Gen9+ only */ struct skl_wm_values wm_results; struct i915_sw_fence commit_ready; struct llist_node freed; }; struct intel_plane_state { struct drm_plane_state base; struct drm_rect clip; struct i915_vma *vma; struct { u32 offset; int x, y; } main; struct { u32 offset; int x, y; } aux; /* plane control register */ u32 ctl; /* * scaler_id * = -1 : not using a scaler * >= 0 : using a scalers * * plane requiring a scaler: * - During check_plane, its bit is set in * crtc_state->scaler_state.scaler_users by calling helper function * update_scaler_plane. * - scaler_id indicates the scaler it got assigned. * * plane doesn't require a scaler: * - this can happen when scaling is no more required or plane simply * got disabled. * - During check_plane, corresponding bit is reset in * crtc_state->scaler_state.scaler_users by calling helper function * update_scaler_plane. */ int scaler_id; struct drm_intel_sprite_colorkey ckey; }; struct intel_initial_plane_config { struct intel_framebuffer *fb; unsigned int tiling; int size; u32 base; }; #define SKL_MIN_SRC_W 8 #define SKL_MAX_SRC_W 4096 #define SKL_MIN_SRC_H 8 #define SKL_MAX_SRC_H 4096 #define SKL_MIN_DST_W 8 #define SKL_MAX_DST_W 4096 #define SKL_MIN_DST_H 8 #define SKL_MAX_DST_H 4096 struct intel_scaler { int in_use; uint32_t mode; }; struct intel_crtc_scaler_state { #define SKL_NUM_SCALERS 2 struct intel_scaler scalers[SKL_NUM_SCALERS]; /* * scaler_users: keeps track of users requesting scalers on this crtc. * * If a bit is set, a user is using a scaler. * Here user can be a plane or crtc as defined below: * bits 0-30 - plane (bit position is index from drm_plane_index) * bit 31 - crtc * * Instead of creating a new index to cover planes and crtc, using * existing drm_plane_index for planes which is well less than 31 * planes and bit 31 for crtc. This should be fine to cover all * our platforms. * * intel_atomic_setup_scalers will setup available scalers to users * requesting scalers. It will gracefully fail if request exceeds * avilability. */ #define SKL_CRTC_INDEX 31 unsigned scaler_users; /* scaler used by crtc for panel fitting purpose */ int scaler_id; }; /* drm_mode->private_flags */ #define I915_MODE_FLAG_INHERITED 1 struct intel_pipe_wm { struct intel_wm_level wm[5]; uint32_t linetime; bool fbc_wm_enabled; bool pipe_enabled; bool sprites_enabled; bool sprites_scaled; }; struct skl_plane_wm { struct skl_wm_level wm[8]; struct skl_wm_level trans_wm; }; struct skl_pipe_wm { struct skl_plane_wm planes[I915_MAX_PLANES]; uint32_t linetime; }; enum vlv_wm_level { VLV_WM_LEVEL_PM2, VLV_WM_LEVEL_PM5, VLV_WM_LEVEL_DDR_DVFS, NUM_VLV_WM_LEVELS, }; struct vlv_wm_state { struct g4x_pipe_wm wm[NUM_VLV_WM_LEVELS]; struct g4x_sr_wm sr[NUM_VLV_WM_LEVELS]; uint8_t num_levels; bool cxsr; }; struct vlv_fifo_state { u16 plane[I915_MAX_PLANES]; }; enum g4x_wm_level { G4X_WM_LEVEL_NORMAL, G4X_WM_LEVEL_SR, G4X_WM_LEVEL_HPLL, NUM_G4X_WM_LEVELS, }; struct g4x_wm_state { struct g4x_pipe_wm wm; struct g4x_sr_wm sr; struct g4x_sr_wm hpll; bool cxsr; bool hpll_en; bool fbc_en; }; struct intel_crtc_wm_state { union { struct { /* * Intermediate watermarks; these can be * programmed immediately since they satisfy * both the current configuration we're * switching away from and the new * configuration we're switching to. */ struct intel_pipe_wm intermediate; /* * Optimal watermarks, programmed post-vblank * when this state is committed. */ struct intel_pipe_wm optimal; } ilk; struct { /* gen9+ only needs 1-step wm programming */ struct skl_pipe_wm optimal; struct skl_ddb_entry ddb; } skl; struct { /* "raw" watermarks (not inverted) */ struct g4x_pipe_wm raw[NUM_VLV_WM_LEVELS]; /* intermediate watermarks (inverted) */ struct vlv_wm_state intermediate; /* optimal watermarks (inverted) */ struct vlv_wm_state optimal; /* display FIFO split */ struct vlv_fifo_state fifo_state; } vlv; struct { /* "raw" watermarks */ struct g4x_pipe_wm raw[NUM_G4X_WM_LEVELS]; /* intermediate watermarks */ struct g4x_wm_state intermediate; /* optimal watermarks */ struct g4x_wm_state optimal; } g4x; }; /* * Platforms with two-step watermark programming will need to * update watermark programming post-vblank to switch from the * safe intermediate watermarks to the optimal final * watermarks. */ bool need_postvbl_update; }; struct intel_crtc_state { struct drm_crtc_state base; /** * quirks - bitfield with hw state readout quirks * * For various reasons the hw state readout code might not be able to * completely faithfully read out the current state. These cases are * tracked with quirk flags so that fastboot and state checker can act * accordingly. */ #define PIPE_CONFIG_QUIRK_MODE_SYNC_FLAGS (1<<0) /* unreliable sync mode.flags */ unsigned long quirks; unsigned fb_bits; /* framebuffers to flip */ bool update_pipe; /* can a fast modeset be performed? */ bool disable_cxsr; bool update_wm_pre, update_wm_post; /* watermarks are updated */ bool fb_changed; /* fb on any of the planes is changed */ bool fifo_changed; /* FIFO split is changed */ /* Pipe source size (ie. panel fitter input size) * All planes will be positioned inside this space, * and get clipped at the edges. */ int pipe_src_w, pipe_src_h; /* * Pipe pixel rate, adjusted for * panel fitter/pipe scaler downscaling. */ unsigned int pixel_rate; /* Whether to set up the PCH/FDI. Note that we never allow sharing * between pch encoders and cpu encoders. */ bool has_pch_encoder; /* Are we sending infoframes on the attached port */ bool has_infoframe; /* CPU Transcoder for the pipe. Currently this can only differ from the * pipe on Haswell and later (where we have a special eDP transcoder) * and Broxton (where we have special DSI transcoders). */ enum transcoder cpu_transcoder; /* * Use reduced/limited/broadcast rbg range, compressing from the full * range fed into the crtcs. */ bool limited_color_range; /* Bitmask of encoder types (enum intel_output_type) * driven by the pipe. */ unsigned int output_types; /* Whether we should send NULL infoframes. Required for audio. */ bool has_hdmi_sink; /* Audio enabled on this pipe. Only valid if either has_hdmi_sink or * has_dp_encoder is set. */ bool has_audio; /* * Enable dithering, used when the selected pipe bpp doesn't match the * plane bpp. */ bool dither; /* * Dither gets enabled for 18bpp which causes CRC mismatch errors for * compliance video pattern tests. * Disable dither only if it is a compliance test request for * 18bpp. */ bool dither_force_disable; /* Controls for the clock computation, to override various stages. */ bool clock_set; /* SDVO TV has a bunch of special case. To make multifunction encoders * work correctly, we need to track this at runtime.*/ bool sdvo_tv_clock; /* * crtc bandwidth limit, don't increase pipe bpp or clock if not really * required. This is set in the 2nd loop of calling encoder's * ->compute_config if the first pick doesn't work out. */ bool bw_constrained; /* Settings for the intel dpll used on pretty much everything but * haswell. */ struct dpll dpll; /* Selected dpll when shared or NULL. */ struct intel_shared_dpll *shared_dpll; /* Actual register state of the dpll, for shared dpll cross-checking. */ struct intel_dpll_hw_state dpll_hw_state; /* DSI PLL registers */ struct { u32 ctrl, div; } dsi_pll; int pipe_bpp; struct intel_link_m_n dp_m_n; /* m2_n2 for eDP downclock */ struct intel_link_m_n dp_m2_n2; bool has_drrs; /* * Frequence the dpll for the port should run at. Differs from the * adjusted dotclock e.g. for DP or 12bpc hdmi mode. This is also * already multiplied by pixel_multiplier. */ int port_clock; /* Used by SDVO (and if we ever fix it, HDMI). */ unsigned pixel_multiplier; uint8_t lane_count; /* * Used by platforms having DP/HDMI PHY with programmable lane * latency optimization. */ uint8_t lane_lat_optim_mask; /* Panel fitter controls for gen2-gen4 + VLV */ struct { u32 control; u32 pgm_ratios; u32 lvds_border_bits; } gmch_pfit; /* Panel fitter placement and size for Ironlake+ */ struct { u32 pos; u32 size; bool enabled; bool force_thru; } pch_pfit; /* FDI configuration, only valid if has_pch_encoder is set. */ int fdi_lanes; struct intel_link_m_n fdi_m_n; bool ips_enabled; bool enable_fbc; bool double_wide; int pbn; struct intel_crtc_scaler_state scaler_state; /* w/a for waiting 2 vblanks during crtc enable */ enum pipe hsw_workaround_pipe; /* IVB sprite scaling w/a (WaCxSRDisabledForSpriteScaling:ivb) */ bool disable_lp_wm; struct intel_crtc_wm_state wm; /* Gamma mode programmed on the pipe */ uint32_t gamma_mode; /* bitmask of visible planes (enum plane_id) */ u8 active_planes; /* HDMI scrambling status */ bool hdmi_scrambling; /* HDMI High TMDS char rate ratio */ bool hdmi_high_tmds_clock_ratio; /* output format is YCBCR 4:2:0 */ bool ycbcr420; }; struct intel_crtc { struct drm_crtc base; enum pipe pipe; enum plane plane; /* * Whether the crtc and the connected output pipeline is active. Implies * that crtc->enabled is set, i.e. the current mode configuration has * some outputs connected to this crtc. */ bool active; bool lowfreq_avail; u8 plane_ids_mask; unsigned long long enabled_power_domains; struct intel_overlay *overlay; /* Display surface base address adjustement for pageflips. Note that on * gen4+ this only adjusts up to a tile, offsets within a tile are * handled in the hw itself (with the TILEOFF register). */ u32 dspaddr_offset; int adjusted_x; int adjusted_y; struct intel_crtc_state *config; /* global reset count when the last flip was submitted */ unsigned int reset_count; /* Access to these should be protected by dev_priv->irq_lock. */ bool cpu_fifo_underrun_disabled; bool pch_fifo_underrun_disabled; /* per-pipe watermark state */ struct { /* watermarks currently being used */ union { struct intel_pipe_wm ilk; struct vlv_wm_state vlv; struct g4x_wm_state g4x; } active; } wm; int scanline_offset; struct { unsigned start_vbl_count; ktime_t start_vbl_time; int min_vbl, max_vbl; int scanline_start; } debug; /* scalers available on this crtc */ int num_scalers; }; struct intel_plane { struct drm_plane base; u8 plane; enum plane_id id; enum pipe pipe; bool can_scale; int max_downscale; uint32_t frontbuffer_bit; struct { u32 base, cntl, size; } cursor; /* * NOTE: Do not place new plane state fields here (e.g., when adding * new plane properties). New runtime state should now be placed in * the intel_plane_state structure and accessed via plane_state. */ void (*update_plane)(struct intel_plane *plane, const struct intel_crtc_state *crtc_state, const struct intel_plane_state *plane_state); void (*disable_plane)(struct intel_plane *plane, struct intel_crtc *crtc); bool (*get_hw_state)(struct intel_plane *plane); int (*check_plane)(struct intel_plane *plane, struct intel_crtc_state *crtc_state, struct intel_plane_state *state); }; struct intel_watermark_params { u16 fifo_size; u16 max_wm; u8 default_wm; u8 guard_size; u8 cacheline_size; }; struct cxsr_latency { bool is_desktop : 1; bool is_ddr3 : 1; u16 fsb_freq; u16 mem_freq; u16 display_sr; u16 display_hpll_disable; u16 cursor_sr; u16 cursor_hpll_disable; }; #define to_intel_atomic_state(x) container_of(x, struct intel_atomic_state, base) #define to_intel_crtc(x) container_of(x, struct intel_crtc, base) #define to_intel_crtc_state(x) container_of(x, struct intel_crtc_state, base) #define to_intel_connector(x) container_of(x, struct intel_connector, base) #define to_intel_encoder(x) container_of(x, struct intel_encoder, base) #define to_intel_framebuffer(x) container_of(x, struct intel_framebuffer, base) #define to_intel_plane(x) container_of(x, struct intel_plane, base) #define to_intel_plane_state(x) container_of(x, struct intel_plane_state, base) #define intel_fb_obj(x) (x ? to_intel_framebuffer(x)->obj : NULL) struct intel_hdmi { i915_reg_t hdmi_reg; int ddc_bus; struct { enum drm_dp_dual_mode_type type; int max_tmds_clock; } dp_dual_mode; bool has_hdmi_sink; bool has_audio; bool rgb_quant_range_selectable; struct intel_connector *attached_connector; void (*write_infoframe)(struct drm_encoder *encoder, const struct intel_crtc_state *crtc_state, enum hdmi_infoframe_type type, const void *frame, ssize_t len); void (*set_infoframes)(struct drm_encoder *encoder, bool enable, const struct intel_crtc_state *crtc_state, const struct drm_connector_state *conn_state); bool (*infoframe_enabled)(struct drm_encoder *encoder, const struct intel_crtc_state *pipe_config); }; struct intel_dp_mst_encoder; #define DP_MAX_DOWNSTREAM_PORTS 0x10 /* * enum link_m_n_set: * When platform provides two set of M_N registers for dp, we can * program them and switch between them incase of DRRS. * But When only one such register is provided, we have to program the * required divider value on that registers itself based on the DRRS state. * * M1_N1 : Program dp_m_n on M1_N1 registers * dp_m2_n2 on M2_N2 registers (If supported) * * M2_N2 : Program dp_m2_n2 on M1_N1 registers * M2_N2 registers are not supported */ enum link_m_n_set { /* Sets the m1_n1 and m2_n2 */ M1_N1 = 0, M2_N2 }; struct intel_dp_compliance_data { unsigned long edid; uint8_t video_pattern; uint16_t hdisplay, vdisplay; uint8_t bpc; }; struct intel_dp_compliance { unsigned long test_type; struct intel_dp_compliance_data test_data; bool test_active; int test_link_rate; u8 test_lane_count; }; struct intel_dp { i915_reg_t output_reg; i915_reg_t aux_ch_ctl_reg; i915_reg_t aux_ch_data_reg[5]; uint32_t DP; int link_rate; uint8_t lane_count; uint8_t sink_count; bool link_mst; bool has_audio; bool detect_done; bool channel_eq_status; bool reset_link_params; uint8_t dpcd[DP_RECEIVER_CAP_SIZE]; uint8_t psr_dpcd[EDP_PSR_RECEIVER_CAP_SIZE]; uint8_t downstream_ports[DP_MAX_DOWNSTREAM_PORTS]; uint8_t edp_dpcd[EDP_DISPLAY_CTL_CAP_SIZE]; /* source rates */ int num_source_rates; const int *source_rates; /* sink rates as reported by DP_MAX_LINK_RATE/DP_SUPPORTED_LINK_RATES */ int num_sink_rates; int sink_rates[DP_MAX_SUPPORTED_RATES]; bool use_rate_select; /* intersection of source and sink rates */ int num_common_rates; int common_rates[DP_MAX_SUPPORTED_RATES]; /* Max lane count for the current link */ int max_link_lane_count; /* Max rate for the current link */ int max_link_rate; /* sink or branch descriptor */ struct drm_dp_desc desc; struct drm_dp_aux aux; enum intel_display_power_domain aux_power_domain; uint8_t train_set[4]; int panel_power_up_delay; int panel_power_down_delay; int panel_power_cycle_delay; int backlight_on_delay; int backlight_off_delay; struct delayed_work panel_vdd_work; bool want_panel_vdd; unsigned long last_power_on; unsigned long last_backlight_off; ktime_t panel_power_off_time; struct notifier_block edp_notifier; /* * Pipe whose power sequencer is currently locked into * this port. Only relevant on VLV/CHV. */ enum pipe pps_pipe; /* * Pipe currently driving the port. Used for preventing * the use of the PPS for any pipe currentrly driving * external DP as that will mess things up on VLV. */ enum pipe active_pipe; /* * Set if the sequencer may be reset due to a power transition, * requiring a reinitialization. Only relevant on BXT. */ bool pps_reset; struct edp_power_seq pps_delays; bool can_mst; /* this port supports mst */ bool is_mst; int active_mst_links; /* connector directly attached - won't be use for modeset in mst world */ struct intel_connector *attached_connector; /* mst connector list */ struct intel_dp_mst_encoder *mst_encoders[I915_MAX_PIPES]; struct drm_dp_mst_topology_mgr mst_mgr; uint32_t (*get_aux_clock_divider)(struct intel_dp *dp, int index); /* * This function returns the value we have to program the AUX_CTL * register with to kick off an AUX transaction. */ uint32_t (*get_aux_send_ctl)(struct intel_dp *dp, bool has_aux_irq, int send_bytes, uint32_t aux_clock_divider); /* This is called before a link training is starterd */ void (*prepare_link_retrain)(struct intel_dp *intel_dp); /* Displayport compliance testing */ struct intel_dp_compliance compliance; }; struct intel_lspcon { bool active; enum drm_lspcon_mode mode; }; struct intel_digital_port { struct intel_encoder base; enum port port; u32 saved_port_bits; struct intel_dp dp; struct intel_hdmi hdmi; struct intel_lspcon lspcon; enum irqreturn (*hpd_pulse)(struct intel_digital_port *, bool); bool release_cl2_override; uint8_t max_lanes; enum intel_display_power_domain ddi_io_power_domain; }; struct intel_dp_mst_encoder { struct intel_encoder base; enum pipe pipe; struct intel_digital_port *primary; struct intel_connector *connector; }; static inline enum dpio_channel vlv_dport_to_channel(struct intel_digital_port *dport) { switch (dport->port) { case PORT_B: case PORT_D: return DPIO_CH0; case PORT_C: return DPIO_CH1; default: BUG(); } } static inline enum dpio_phy vlv_dport_to_phy(struct intel_digital_port *dport) { switch (dport->port) { case PORT_B: case PORT_C: return DPIO_PHY0; case PORT_D: return DPIO_PHY1; default: BUG(); } } static inline enum dpio_channel vlv_pipe_to_channel(enum pipe pipe) { switch (pipe) { case PIPE_A: case PIPE_C: return DPIO_CH0; case PIPE_B: return DPIO_CH1; default: BUG(); } } static inline struct intel_crtc * intel_get_crtc_for_pipe(struct drm_i915_private *dev_priv, enum pipe pipe) { return dev_priv->pipe_to_crtc_mapping[pipe]; } static inline struct intel_crtc * intel_get_crtc_for_plane(struct drm_i915_private *dev_priv, enum plane plane) { return dev_priv->plane_to_crtc_mapping[plane]; } struct intel_load_detect_pipe { struct drm_atomic_state *restore_state; }; static inline struct intel_encoder * intel_attached_encoder(struct drm_connector *connector) { return to_intel_connector(connector)->encoder; } static inline struct intel_digital_port * enc_to_dig_port(struct drm_encoder *encoder) { struct intel_encoder *intel_encoder = to_intel_encoder(encoder); switch (intel_encoder->type) { case INTEL_OUTPUT_UNKNOWN: WARN_ON(!HAS_DDI(to_i915(encoder->dev))); case INTEL_OUTPUT_DP: case INTEL_OUTPUT_EDP: case INTEL_OUTPUT_HDMI: return container_of(encoder, struct intel_digital_port, base.base); default: return NULL; } } static inline struct intel_dp_mst_encoder * enc_to_mst(struct drm_encoder *encoder) { return container_of(encoder, struct intel_dp_mst_encoder, base.base); } static inline struct intel_dp *enc_to_intel_dp(struct drm_encoder *encoder) { return &enc_to_dig_port(encoder)->dp; } static inline struct intel_digital_port * dp_to_dig_port(struct intel_dp *intel_dp) { return container_of(intel_dp, struct intel_digital_port, dp); } static inline struct intel_lspcon * dp_to_lspcon(struct intel_dp *intel_dp) { return &dp_to_dig_port(intel_dp)->lspcon; } static inline struct intel_digital_port * hdmi_to_dig_port(struct intel_hdmi *intel_hdmi) { return container_of(intel_hdmi, struct intel_digital_port, hdmi); } /* intel_fifo_underrun.c */ bool intel_set_cpu_fifo_underrun_reporting(struct drm_i915_private *dev_priv, enum pipe pipe, bool enable); bool intel_set_pch_fifo_underrun_reporting(struct drm_i915_private *dev_priv, enum pipe pch_transcoder, bool enable); void intel_cpu_fifo_underrun_irq_handler(struct drm_i915_private *dev_priv, enum pipe pipe); void intel_pch_fifo_underrun_irq_handler(struct drm_i915_private *dev_priv, enum pipe pch_transcoder); void intel_check_cpu_fifo_underruns(struct drm_i915_private *dev_priv); void intel_check_pch_fifo_underruns(struct drm_i915_private *dev_priv); /* i915_irq.c */ void gen5_enable_gt_irq(struct drm_i915_private *dev_priv, uint32_t mask); void gen5_disable_gt_irq(struct drm_i915_private *dev_priv, uint32_t mask); void gen6_reset_pm_iir(struct drm_i915_private *dev_priv, u32 mask); void gen6_mask_pm_irq(struct drm_i915_private *dev_priv, u32 mask); void gen6_unmask_pm_irq(struct drm_i915_private *dev_priv, u32 mask); void gen6_enable_pm_irq(struct drm_i915_private *dev_priv, uint32_t mask); void gen6_disable_pm_irq(struct drm_i915_private *dev_priv, uint32_t mask); void gen6_reset_rps_interrupts(struct drm_i915_private *dev_priv); void gen6_enable_rps_interrupts(struct drm_i915_private *dev_priv); void gen6_disable_rps_interrupts(struct drm_i915_private *dev_priv); static inline u32 gen6_sanitize_rps_pm_mask(const struct drm_i915_private *i915, u32 mask) { return mask & ~i915->rps.pm_intrmsk_mbz; } void intel_runtime_pm_disable_interrupts(struct drm_i915_private *dev_priv); void intel_runtime_pm_enable_interrupts(struct drm_i915_private *dev_priv); static inline bool intel_irqs_enabled(struct drm_i915_private *dev_priv) { /* * We only use drm_irq_uninstall() at unload and VT switch, so * this is the only thing we need to check. */ return dev_priv->pm.irqs_enabled; } int intel_get_crtc_scanline(struct intel_crtc *crtc); void gen8_irq_power_well_post_enable(struct drm_i915_private *dev_priv, u8 pipe_mask); void gen8_irq_power_well_pre_disable(struct drm_i915_private *dev_priv, u8 pipe_mask); void gen9_reset_guc_interrupts(struct drm_i915_private *dev_priv); void gen9_enable_guc_interrupts(struct drm_i915_private *dev_priv); void gen9_disable_guc_interrupts(struct drm_i915_private *dev_priv); /* intel_crt.c */ void intel_crt_init(struct drm_i915_private *dev_priv); void intel_crt_reset(struct drm_encoder *encoder); /* intel_ddi.c */ void intel_ddi_fdi_post_disable(struct intel_encoder *intel_encoder, struct intel_crtc_state *old_crtc_state, struct drm_connector_state *old_conn_state); void hsw_fdi_link_train(struct intel_crtc *crtc, const struct intel_crtc_state *crtc_state); void intel_ddi_init(struct drm_i915_private *dev_priv, enum port port); enum port intel_ddi_get_encoder_port(struct intel_encoder *intel_encoder); bool intel_ddi_get_hw_state(struct intel_encoder *encoder, enum pipe *pipe); void intel_ddi_enable_transcoder_func(const struct intel_crtc_state *crtc_state); void intel_ddi_disable_transcoder_func(struct drm_i915_private *dev_priv, enum transcoder cpu_transcoder); void intel_ddi_enable_pipe_clock(const struct intel_crtc_state *crtc_state); void intel_ddi_disable_pipe_clock(const struct intel_crtc_state *crtc_state); struct intel_encoder * intel_ddi_get_crtc_new_encoder(struct intel_crtc_state *crtc_state); void intel_ddi_set_pipe_settings(const struct intel_crtc_state *crtc_state); void intel_ddi_prepare_link_retrain(struct intel_dp *intel_dp); bool intel_ddi_connector_get_hw_state(struct intel_connector *intel_connector); bool intel_ddi_is_audio_enabled(struct drm_i915_private *dev_priv, struct intel_crtc *intel_crtc); void intel_ddi_get_config(struct intel_encoder *encoder, struct intel_crtc_state *pipe_config); void intel_ddi_clock_get(struct intel_encoder *encoder, struct intel_crtc_state *pipe_config); void intel_ddi_set_vc_payload_alloc(const struct intel_crtc_state *crtc_state, bool state); uint32_t ddi_signal_levels(struct intel_dp *intel_dp); u8 intel_ddi_dp_voltage_max(struct intel_encoder *encoder); unsigned int intel_fb_align_height(const struct drm_framebuffer *fb, int plane, unsigned int height); /* intel_audio.c */ void intel_init_audio_hooks(struct drm_i915_private *dev_priv); void intel_audio_codec_enable(struct intel_encoder *encoder, const struct intel_crtc_state *crtc_state, const struct drm_connector_state *conn_state); void intel_audio_codec_disable(struct intel_encoder *encoder); void i915_audio_component_init(struct drm_i915_private *dev_priv); void i915_audio_component_cleanup(struct drm_i915_private *dev_priv); void intel_audio_init(struct drm_i915_private *dev_priv); void intel_audio_deinit(struct drm_i915_private *dev_priv); /* intel_cdclk.c */ void skl_init_cdclk(struct drm_i915_private *dev_priv); void skl_uninit_cdclk(struct drm_i915_private *dev_priv); void cnl_init_cdclk(struct drm_i915_private *dev_priv); void cnl_uninit_cdclk(struct drm_i915_private *dev_priv); void bxt_init_cdclk(struct drm_i915_private *dev_priv); void bxt_uninit_cdclk(struct drm_i915_private *dev_priv); void intel_init_cdclk_hooks(struct drm_i915_private *dev_priv); void intel_update_max_cdclk(struct drm_i915_private *dev_priv); void intel_update_cdclk(struct drm_i915_private *dev_priv); void intel_update_rawclk(struct drm_i915_private *dev_priv); bool intel_cdclk_state_compare(const struct intel_cdclk_state *a, const struct intel_cdclk_state *b); void intel_set_cdclk(struct drm_i915_private *dev_priv, const struct intel_cdclk_state *cdclk_state); /* intel_display.c */ void i830_enable_pipe(struct drm_i915_private *dev_priv, enum pipe pipe); void i830_disable_pipe(struct drm_i915_private *dev_priv, enum pipe pipe); enum pipe intel_crtc_pch_transcoder(struct intel_crtc *crtc); void intel_update_rawclk(struct drm_i915_private *dev_priv); int vlv_get_hpll_vco(struct drm_i915_private *dev_priv); int vlv_get_cck_clock(struct drm_i915_private *dev_priv, const char *name, u32 reg, int ref_freq); int vlv_get_cck_clock_hpll(struct drm_i915_private *dev_priv, const char *name, u32 reg); void lpt_disable_pch_transcoder(struct drm_i915_private *dev_priv); void lpt_disable_iclkip(struct drm_i915_private *dev_priv); void intel_init_display_hooks(struct drm_i915_private *dev_priv); unsigned int intel_fb_xy_to_linear(int x, int y, const struct intel_plane_state *state, int plane); void intel_add_fb_offsets(int *x, int *y, const struct intel_plane_state *state, int plane); unsigned int intel_rotation_info_size(const struct intel_rotation_info *rot_info); bool intel_has_pending_fb_unpin(struct drm_i915_private *dev_priv); void intel_mark_busy(struct drm_i915_private *dev_priv); void intel_mark_idle(struct drm_i915_private *dev_priv); int intel_display_suspend(struct drm_device *dev); void intel_pps_unlock_regs_wa(struct drm_i915_private *dev_priv); void intel_encoder_destroy(struct drm_encoder *encoder); int intel_connector_init(struct intel_connector *); struct intel_connector *intel_connector_alloc(void); bool intel_connector_get_hw_state(struct intel_connector *connector); void intel_connector_attach_encoder(struct intel_connector *connector, struct intel_encoder *encoder); struct drm_display_mode *intel_crtc_mode_get(struct drm_device *dev, struct drm_crtc *crtc); enum pipe intel_get_pipe_from_connector(struct intel_connector *connector); int intel_get_pipe_from_crtc_id(struct drm_device *dev, void *data, struct drm_file *file_priv); enum transcoder intel_pipe_to_cpu_transcoder(struct drm_i915_private *dev_priv, enum pipe pipe); static inline bool intel_crtc_has_type(const struct intel_crtc_state *crtc_state, enum intel_output_type type) { return crtc_state->output_types & (1 << type); } static inline bool intel_crtc_has_dp_encoder(const struct intel_crtc_state *crtc_state) { return crtc_state->output_types & ((1 << INTEL_OUTPUT_DP) | (1 << INTEL_OUTPUT_DP_MST) | (1 << INTEL_OUTPUT_EDP)); } static inline void intel_wait_for_vblank(struct drm_i915_private *dev_priv, enum pipe pipe) { drm_wait_one_vblank(&dev_priv->drm, pipe); } static inline void intel_wait_for_vblank_if_active(struct drm_i915_private *dev_priv, int pipe) { const struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe); if (crtc->active) intel_wait_for_vblank(dev_priv, pipe); } u32 intel_crtc_get_vblank_counter(struct intel_crtc *crtc); int ironlake_get_lanes_required(int target_clock, int link_bw, int bpp); void vlv_wait_port_ready(struct drm_i915_private *dev_priv, struct intel_digital_port *dport, unsigned int expected_mask); int intel_get_load_detect_pipe(struct drm_connector *connector, struct drm_display_mode *mode, struct intel_load_detect_pipe *old, struct drm_modeset_acquire_ctx *ctx); void intel_release_load_detect_pipe(struct drm_connector *connector, struct intel_load_detect_pipe *old, struct drm_modeset_acquire_ctx *ctx); struct i915_vma * intel_pin_and_fence_fb_obj(struct drm_framebuffer *fb, unsigned int rotation); void intel_unpin_fb_vma(struct i915_vma *vma); struct drm_framebuffer * intel_framebuffer_create(struct drm_i915_gem_object *obj, struct drm_mode_fb_cmd2 *mode_cmd); int intel_prepare_plane_fb(struct drm_plane *plane, struct drm_plane_state *new_state); void intel_cleanup_plane_fb(struct drm_plane *plane, struct drm_plane_state *old_state); int intel_plane_atomic_get_property(struct drm_plane *plane, const struct drm_plane_state *state, struct drm_property *property, uint64_t *val); int intel_plane_atomic_set_property(struct drm_plane *plane, struct drm_plane_state *state, struct drm_property *property, uint64_t val); int intel_plane_atomic_calc_changes(struct drm_crtc_state *crtc_state, struct drm_plane_state *plane_state); void assert_pch_transcoder_disabled(struct drm_i915_private *dev_priv, enum pipe pipe); int vlv_force_pll_on(struct drm_i915_private *dev_priv, enum pipe pipe, const struct dpll *dpll); void vlv_force_pll_off(struct drm_i915_private *dev_priv, enum pipe pipe); int lpt_get_iclkip(struct drm_i915_private *dev_priv); /* modesetting asserts */ void assert_panel_unlocked(struct drm_i915_private *dev_priv, enum pipe pipe); void assert_pll(struct drm_i915_private *dev_priv, enum pipe pipe, bool state); #define assert_pll_enabled(d, p) assert_pll(d, p, true) #define assert_pll_disabled(d, p) assert_pll(d, p, false) void assert_dsi_pll(struct drm_i915_private *dev_priv, bool state); #define assert_dsi_pll_enabled(d) assert_dsi_pll(d, true) #define assert_dsi_pll_disabled(d) assert_dsi_pll(d, false) void assert_fdi_rx_pll(struct drm_i915_private *dev_priv, enum pipe pipe, bool state); #define assert_fdi_rx_pll_enabled(d, p) assert_fdi_rx_pll(d, p, true) #define assert_fdi_rx_pll_disabled(d, p) assert_fdi_rx_pll(d, p, false) void assert_pipe(struct drm_i915_private *dev_priv, enum pipe pipe, bool state); #define assert_pipe_enabled(d, p) assert_pipe(d, p, true) #define assert_pipe_disabled(d, p) assert_pipe(d, p, false) u32 intel_compute_tile_offset(int *x, int *y, const struct intel_plane_state *state, int plane); void intel_prepare_reset(struct drm_i915_private *dev_priv); void intel_finish_reset(struct drm_i915_private *dev_priv); void hsw_enable_pc8(struct drm_i915_private *dev_priv); void hsw_disable_pc8(struct drm_i915_private *dev_priv); void gen9_sanitize_dc_state(struct drm_i915_private *dev_priv); void bxt_enable_dc9(struct drm_i915_private *dev_priv); void bxt_disable_dc9(struct drm_i915_private *dev_priv); void gen9_enable_dc5(struct drm_i915_private *dev_priv); unsigned int skl_cdclk_get_vco(unsigned int freq); void skl_enable_dc6(struct drm_i915_private *dev_priv); void skl_disable_dc6(struct drm_i915_private *dev_priv); void intel_dp_get_m_n(struct intel_crtc *crtc, struct intel_crtc_state *pipe_config); void intel_dp_set_m_n(struct intel_crtc *crtc, enum link_m_n_set m_n); int intel_dotclock_calculate(int link_freq, const struct intel_link_m_n *m_n); bool bxt_find_best_dpll(struct intel_crtc_state *crtc_state, int target_clock, struct dpll *best_clock); int chv_calc_dpll_params(int refclk, struct dpll *pll_clock); bool intel_crtc_active(struct intel_crtc *crtc); void hsw_enable_ips(struct intel_crtc *crtc); void hsw_disable_ips(struct intel_crtc *crtc); enum intel_display_power_domain intel_port_to_power_domain(enum port port); void intel_mode_from_pipe_config(struct drm_display_mode *mode, struct intel_crtc_state *pipe_config); int skl_update_scaler_crtc(struct intel_crtc_state *crtc_state); int skl_max_scale(struct intel_crtc *crtc, struct intel_crtc_state *crtc_state); static inline u32 intel_plane_ggtt_offset(const struct intel_plane_state *state) { return i915_ggtt_offset(state->vma); } u32 skl_plane_ctl(const struct intel_crtc_state *crtc_state, const struct intel_plane_state *plane_state); u32 skl_plane_stride(const struct drm_framebuffer *fb, int plane, unsigned int rotation); int skl_check_plane_surface(struct intel_plane_state *plane_state); int i9xx_check_plane_surface(struct intel_plane_state *plane_state); /* intel_csr.c */ void intel_csr_ucode_init(struct drm_i915_private *); void intel_csr_load_program(struct drm_i915_private *); void intel_csr_ucode_fini(struct drm_i915_private *); void intel_csr_ucode_suspend(struct drm_i915_private *); void intel_csr_ucode_resume(struct drm_i915_private *); /* intel_dp.c */ bool intel_dp_init(struct drm_i915_private *dev_priv, i915_reg_t output_reg, enum port port); bool intel_dp_init_connector(struct intel_digital_port *intel_dig_port, struct intel_connector *intel_connector); void intel_dp_set_link_params(struct intel_dp *intel_dp, int link_rate, uint8_t lane_count, bool link_mst); int intel_dp_get_link_train_fallback_values(struct intel_dp *intel_dp, int link_rate, uint8_t lane_count); void intel_dp_start_link_train(struct intel_dp *intel_dp); void intel_dp_stop_link_train(struct intel_dp *intel_dp); void intel_dp_sink_dpms(struct intel_dp *intel_dp, int mode); void intel_dp_encoder_reset(struct drm_encoder *encoder); void intel_dp_encoder_suspend(struct intel_encoder *intel_encoder); void intel_dp_encoder_destroy(struct drm_encoder *encoder); int intel_dp_sink_crc(struct intel_dp *intel_dp, u8 *crc); bool intel_dp_compute_config(struct intel_encoder *encoder, struct intel_crtc_state *pipe_config, struct drm_connector_state *conn_state); bool intel_dp_is_edp(struct drm_i915_private *dev_priv, enum port port); enum irqreturn intel_dp_hpd_pulse(struct intel_digital_port *intel_dig_port, bool long_hpd); void intel_edp_backlight_on(const struct intel_crtc_state *crtc_state, const struct drm_connector_state *conn_state); void intel_edp_backlight_off(const struct drm_connector_state *conn_state); void intel_edp_panel_vdd_on(struct intel_dp *intel_dp); void intel_edp_panel_on(struct intel_dp *intel_dp); void intel_edp_panel_off(struct intel_dp *intel_dp); void intel_dp_mst_suspend(struct drm_device *dev); void intel_dp_mst_resume(struct drm_device *dev); int intel_dp_max_link_rate(struct intel_dp *intel_dp); int intel_dp_max_lane_count(struct intel_dp *intel_dp); int intel_dp_rate_select(struct intel_dp *intel_dp, int rate); void intel_dp_hot_plug(struct intel_encoder *intel_encoder); void intel_power_sequencer_reset(struct drm_i915_private *dev_priv); uint32_t intel_dp_pack_aux(const uint8_t *src, int src_bytes); void intel_plane_destroy(struct drm_plane *plane); void intel_edp_drrs_enable(struct intel_dp *intel_dp, struct intel_crtc_state *crtc_state); void intel_edp_drrs_disable(struct intel_dp *intel_dp, struct intel_crtc_state *crtc_state); void intel_edp_drrs_invalidate(struct drm_i915_private *dev_priv, unsigned int frontbuffer_bits); void intel_edp_drrs_flush(struct drm_i915_private *dev_priv, unsigned int frontbuffer_bits); void intel_dp_program_link_training_pattern(struct intel_dp *intel_dp, uint8_t dp_train_pat); void intel_dp_set_signal_levels(struct intel_dp *intel_dp); void intel_dp_set_idle_link_train(struct intel_dp *intel_dp); uint8_t intel_dp_voltage_max(struct intel_dp *intel_dp); uint8_t intel_dp_pre_emphasis_max(struct intel_dp *intel_dp, uint8_t voltage_swing); void intel_dp_compute_rate(struct intel_dp *intel_dp, int port_clock, uint8_t *link_bw, uint8_t *rate_select); bool intel_dp_source_supports_hbr2(struct intel_dp *intel_dp); bool intel_dp_get_link_status(struct intel_dp *intel_dp, uint8_t link_status[DP_LINK_STATUS_SIZE]); static inline unsigned int intel_dp_unused_lane_mask(int lane_count) { return ~((1 << lane_count) - 1) & 0xf; } bool intel_dp_read_dpcd(struct intel_dp *intel_dp); int intel_dp_link_required(int pixel_clock, int bpp); int intel_dp_max_data_rate(int max_link_clock, int max_lanes); bool intel_digital_port_connected(struct drm_i915_private *dev_priv, struct intel_digital_port *port); /* intel_dp_aux_backlight.c */ int intel_dp_aux_init_backlight_funcs(struct intel_connector *intel_connector); /* intel_dp_mst.c */ int intel_dp_mst_encoder_init(struct intel_digital_port *intel_dig_port, int conn_id); void intel_dp_mst_encoder_cleanup(struct intel_digital_port *intel_dig_port); /* intel_dsi.c */ void intel_dsi_init(struct drm_i915_private *dev_priv); /* intel_dsi_dcs_backlight.c */ int intel_dsi_dcs_init_backlight_funcs(struct intel_connector *intel_connector); /* intel_dvo.c */ void intel_dvo_init(struct drm_i915_private *dev_priv); /* intel_hotplug.c */ void intel_hpd_poll_init(struct drm_i915_private *dev_priv); /* legacy fbdev emulation in intel_fbdev.c */ #ifdef CONFIG_DRM_FBDEV_EMULATION extern int intel_fbdev_init(struct drm_device *dev); extern void intel_fbdev_initial_config_async(struct drm_device *dev); extern void intel_fbdev_unregister(struct drm_i915_private *dev_priv); extern void intel_fbdev_fini(struct drm_i915_private *dev_priv); extern void intel_fbdev_set_suspend(struct drm_device *dev, int state, bool synchronous); extern void intel_fbdev_output_poll_changed(struct drm_device *dev); extern void intel_fbdev_restore_mode(struct drm_device *dev); #else static inline int intel_fbdev_init(struct drm_device *dev) { return 0; } static inline void intel_fbdev_initial_config_async(struct drm_device *dev) { } static inline void intel_fbdev_unregister(struct drm_i915_private *dev_priv) { } static inline void intel_fbdev_fini(struct drm_i915_private *dev_priv) { } static inline void intel_fbdev_set_suspend(struct drm_device *dev, int state, bool synchronous) { } static inline void intel_fbdev_output_poll_changed(struct drm_device *dev) { } static inline void intel_fbdev_restore_mode(struct drm_device *dev) { } #endif /* intel_fbc.c */ void intel_fbc_choose_crtc(struct drm_i915_private *dev_priv, struct drm_atomic_state *state); bool intel_fbc_is_active(struct drm_i915_private *dev_priv); void intel_fbc_pre_update(struct intel_crtc *crtc, struct intel_crtc_state *crtc_state, struct intel_plane_state *plane_state); void intel_fbc_post_update(struct intel_crtc *crtc); void intel_fbc_init(struct drm_i915_private *dev_priv); void intel_fbc_init_pipe_state(struct drm_i915_private *dev_priv); void intel_fbc_enable(struct intel_crtc *crtc, struct intel_crtc_state *crtc_state, struct intel_plane_state *plane_state); void intel_fbc_disable(struct intel_crtc *crtc); void intel_fbc_global_disable(struct drm_i915_private *dev_priv); void intel_fbc_invalidate(struct drm_i915_private *dev_priv, unsigned int frontbuffer_bits, enum fb_op_origin origin); void intel_fbc_flush(struct drm_i915_private *dev_priv, unsigned int frontbuffer_bits, enum fb_op_origin origin); void intel_fbc_cleanup_cfb(struct drm_i915_private *dev_priv); void intel_fbc_handle_fifo_underrun_irq(struct drm_i915_private *dev_priv); /* intel_hdmi.c */ void intel_hdmi_init(struct drm_i915_private *dev_priv, i915_reg_t hdmi_reg, enum port port); void intel_hdmi_init_connector(struct intel_digital_port *intel_dig_port, struct intel_connector *intel_connector); struct intel_hdmi *enc_to_intel_hdmi(struct drm_encoder *encoder); bool intel_hdmi_compute_config(struct intel_encoder *encoder, struct intel_crtc_state *pipe_config, struct drm_connector_state *conn_state); void intel_hdmi_handle_sink_scrambling(struct intel_encoder *intel_encoder, struct drm_connector *connector, bool high_tmds_clock_ratio, bool scrambling); void intel_dp_dual_mode_set_tmds_output(struct intel_hdmi *hdmi, bool enable); /* intel_lvds.c */ void intel_lvds_init(struct drm_i915_private *dev_priv); struct intel_encoder *intel_get_lvds_encoder(struct drm_device *dev); bool intel_is_dual_link_lvds(struct drm_device *dev); /* intel_modes.c */ int intel_connector_update_modes(struct drm_connector *connector, struct edid *edid); int intel_ddc_get_modes(struct drm_connector *c, struct i2c_adapter *adapter); void intel_attach_force_audio_property(struct drm_connector *connector); void intel_attach_broadcast_rgb_property(struct drm_connector *connector); void intel_attach_aspect_ratio_property(struct drm_connector *connector); /* intel_overlay.c */ void intel_setup_overlay(struct drm_i915_private *dev_priv); void intel_cleanup_overlay(struct drm_i915_private *dev_priv); int intel_overlay_switch_off(struct intel_overlay *overlay); int intel_overlay_put_image_ioctl(struct drm_device *dev, void *data, struct drm_file *file_priv); int intel_overlay_attrs_ioctl(struct drm_device *dev, void *data, struct drm_file *file_priv); void intel_overlay_reset(struct drm_i915_private *dev_priv); /* intel_panel.c */ int intel_panel_init(struct intel_panel *panel, struct drm_display_mode *fixed_mode, struct drm_display_mode *alt_fixed_mode, struct drm_display_mode *downclock_mode); void intel_panel_fini(struct intel_panel *panel); void intel_fixed_panel_mode(const struct drm_display_mode *fixed_mode, struct drm_display_mode *adjusted_mode); void intel_pch_panel_fitting(struct intel_crtc *crtc, struct intel_crtc_state *pipe_config, int fitting_mode); void intel_gmch_panel_fitting(struct intel_crtc *crtc, struct intel_crtc_state *pipe_config, int fitting_mode); void intel_panel_set_backlight_acpi(const struct drm_connector_state *conn_state, u32 level, u32 max); int intel_panel_setup_backlight(struct drm_connector *connector, enum pipe pipe); void intel_panel_enable_backlight(const struct intel_crtc_state *crtc_state, const struct drm_connector_state *conn_state); void intel_panel_disable_backlight(const struct drm_connector_state *old_conn_state); void intel_panel_destroy_backlight(struct drm_connector *connector); enum drm_connector_status intel_panel_detect(struct drm_i915_private *dev_priv); extern struct drm_display_mode *intel_find_panel_downclock( struct drm_i915_private *dev_priv, struct drm_display_mode *fixed_mode, struct drm_connector *connector); #if IS_ENABLED(CONFIG_BACKLIGHT_CLASS_DEVICE) int intel_backlight_device_register(struct intel_connector *connector); void intel_backlight_device_unregister(struct intel_connector *connector); #else /* CONFIG_BACKLIGHT_CLASS_DEVICE */ static inline int intel_backlight_device_register(struct intel_connector *connector) { return 0; } static inline void intel_backlight_device_unregister(struct intel_connector *connector) { } #endif /* CONFIG_BACKLIGHT_CLASS_DEVICE */ /* intel_psr.c */ void intel_psr_enable(struct intel_dp *intel_dp); void intel_psr_disable(struct intel_dp *intel_dp); void intel_psr_invalidate(struct drm_i915_private *dev_priv, unsigned frontbuffer_bits); void intel_psr_flush(struct drm_i915_private *dev_priv, unsigned frontbuffer_bits, enum fb_op_origin origin); void intel_psr_init(struct drm_i915_private *dev_priv); void intel_psr_single_frame_update(struct drm_i915_private *dev_priv, unsigned frontbuffer_bits); /* intel_runtime_pm.c */ int intel_power_domains_init(struct drm_i915_private *); void intel_power_domains_fini(struct drm_i915_private *); void intel_power_domains_init_hw(struct drm_i915_private *dev_priv, bool resume); void intel_power_domains_suspend(struct drm_i915_private *dev_priv); void intel_power_domains_verify_state(struct drm_i915_private *dev_priv); void bxt_display_core_init(struct drm_i915_private *dev_priv, bool resume); void bxt_display_core_uninit(struct drm_i915_private *dev_priv); void intel_runtime_pm_enable(struct drm_i915_private *dev_priv); const char * intel_display_power_domain_str(enum intel_display_power_domain domain); bool intel_display_power_is_enabled(struct drm_i915_private *dev_priv, enum intel_display_power_domain domain); bool __intel_display_power_is_enabled(struct drm_i915_private *dev_priv, enum intel_display_power_domain domain); void intel_display_power_get(struct drm_i915_private *dev_priv, enum intel_display_power_domain domain); bool intel_display_power_get_if_enabled(struct drm_i915_private *dev_priv, enum intel_display_power_domain domain); void intel_display_power_put(struct drm_i915_private *dev_priv, enum intel_display_power_domain domain); static inline void assert_rpm_device_not_suspended(struct drm_i915_private *dev_priv) { WARN_ONCE(dev_priv->pm.suspended, "Device suspended during HW access\n"); } static inline void assert_rpm_wakelock_held(struct drm_i915_private *dev_priv) { assert_rpm_device_not_suspended(dev_priv); WARN_ONCE(!atomic_read(&dev_priv->pm.wakeref_count), "RPM wakelock ref not held during HW access"); } /** * disable_rpm_wakeref_asserts - disable the RPM assert checks * @dev_priv: i915 device instance * * This function disable asserts that check if we hold an RPM wakelock * reference, while keeping the device-not-suspended checks still enabled. * It's meant to be used only in special circumstances where our rule about * the wakelock refcount wrt. the device power state doesn't hold. According * to this rule at any point where we access the HW or want to keep the HW in * an active state we must hold an RPM wakelock reference acquired via one of * the intel_runtime_pm_get() helpers. Currently there are a few special spots * where this rule doesn't hold: the IRQ and suspend/resume handlers, the * forcewake release timer, and the GPU RPS and hangcheck works. All other * users should avoid using this function. * * Any calls to this function must have a symmetric call to * enable_rpm_wakeref_asserts(). */ static inline void disable_rpm_wakeref_asserts(struct drm_i915_private *dev_priv) { atomic_inc(&dev_priv->pm.wakeref_count); } /** * enable_rpm_wakeref_asserts - re-enable the RPM assert checks * @dev_priv: i915 device instance * * This function re-enables the RPM assert checks after disabling them with * disable_rpm_wakeref_asserts. It's meant to be used only in special * circumstances otherwise its use should be avoided. * * Any calls to this function must have a symmetric call to * disable_rpm_wakeref_asserts(). */ static inline void enable_rpm_wakeref_asserts(struct drm_i915_private *dev_priv) { atomic_dec(&dev_priv->pm.wakeref_count); } void intel_runtime_pm_get(struct drm_i915_private *dev_priv); bool intel_runtime_pm_get_if_in_use(struct drm_i915_private *dev_priv); void intel_runtime_pm_get_noresume(struct drm_i915_private *dev_priv); void intel_runtime_pm_put(struct drm_i915_private *dev_priv); void intel_display_set_init_power(struct drm_i915_private *dev, bool enable); void chv_phy_powergate_lanes(struct intel_encoder *encoder, bool override, unsigned int mask); bool chv_phy_powergate_ch(struct drm_i915_private *dev_priv, enum dpio_phy phy, enum dpio_channel ch, bool override); /* intel_pm.c */ void intel_init_clock_gating(struct drm_i915_private *dev_priv); void intel_suspend_hw(struct drm_i915_private *dev_priv); int ilk_wm_max_level(const struct drm_i915_private *dev_priv); void intel_update_watermarks(struct intel_crtc *crtc); void intel_init_pm(struct drm_i915_private *dev_priv); void intel_init_clock_gating_hooks(struct drm_i915_private *dev_priv); void intel_pm_setup(struct drm_i915_private *dev_priv); void intel_gpu_ips_init(struct drm_i915_private *dev_priv); void intel_gpu_ips_teardown(void); void intel_init_gt_powersave(struct drm_i915_private *dev_priv); void intel_cleanup_gt_powersave(struct drm_i915_private *dev_priv); void intel_sanitize_gt_powersave(struct drm_i915_private *dev_priv); void intel_enable_gt_powersave(struct drm_i915_private *dev_priv); void intel_autoenable_gt_powersave(struct drm_i915_private *dev_priv); void intel_disable_gt_powersave(struct drm_i915_private *dev_priv); void intel_suspend_gt_powersave(struct drm_i915_private *dev_priv); void gen6_rps_busy(struct drm_i915_private *dev_priv); void gen6_rps_reset_ei(struct drm_i915_private *dev_priv); void gen6_rps_idle(struct drm_i915_private *dev_priv); void gen6_rps_boost(struct drm_i915_gem_request *rq, struct intel_rps_client *rps); void intel_queue_rps_boost_for_request(struct drm_i915_gem_request *req); void g4x_wm_get_hw_state(struct drm_device *dev); void vlv_wm_get_hw_state(struct drm_device *dev); void ilk_wm_get_hw_state(struct drm_device *dev); void skl_wm_get_hw_state(struct drm_device *dev); void skl_ddb_get_hw_state(struct drm_i915_private *dev_priv, struct skl_ddb_allocation *ddb /* out */); void skl_pipe_wm_get_hw_state(struct drm_crtc *crtc, struct skl_pipe_wm *out); void g4x_wm_sanitize(struct drm_i915_private *dev_priv); void vlv_wm_sanitize(struct drm_i915_private *dev_priv); bool intel_can_enable_sagv(struct drm_atomic_state *state); int intel_enable_sagv(struct drm_i915_private *dev_priv); int intel_disable_sagv(struct drm_i915_private *dev_priv); bool skl_wm_level_equals(const struct skl_wm_level *l1, const struct skl_wm_level *l2); bool skl_ddb_allocation_overlaps(const struct skl_ddb_entry **entries, const struct skl_ddb_entry *ddb, int ignore); bool ilk_disable_lp_wm(struct drm_device *dev); int sanitize_rc6_option(struct drm_i915_private *dev_priv, int enable_rc6); int skl_check_pipe_max_pixel_rate(struct intel_crtc *intel_crtc, struct intel_crtc_state *cstate); static inline int intel_enable_rc6(void) { return i915.enable_rc6; } /* intel_sdvo.c */ bool intel_sdvo_init(struct drm_i915_private *dev_priv, i915_reg_t reg, enum port port); /* intel_sprite.c */ int intel_usecs_to_scanlines(const struct drm_display_mode *adjusted_mode, int usecs); struct intel_plane *intel_sprite_plane_create(struct drm_i915_private *dev_priv, enum pipe pipe, int plane); int intel_sprite_set_colorkey(struct drm_device *dev, void *data, struct drm_file *file_priv); void intel_pipe_update_start(struct intel_crtc *crtc); void intel_pipe_update_end(struct intel_crtc *crtc); bool skl_plane_get_hw_state(struct intel_plane *plane); /* intel_tv.c */ void intel_tv_init(struct drm_i915_private *dev_priv); /* intel_atomic.c */ int intel_digital_connector_atomic_get_property(struct drm_connector *connector, const struct drm_connector_state *state, struct drm_property *property, uint64_t *val); int intel_digital_connector_atomic_set_property(struct drm_connector *connector, struct drm_connector_state *state, struct drm_property *property, uint64_t val); int intel_digital_connector_atomic_check(struct drm_connector *conn, struct drm_connector_state *new_state); struct drm_connector_state * intel_digital_connector_duplicate_state(struct drm_connector *connector); struct drm_crtc_state *intel_crtc_duplicate_state(struct drm_crtc *crtc); void intel_crtc_destroy_state(struct drm_crtc *crtc, struct drm_crtc_state *state); struct drm_atomic_state *intel_atomic_state_alloc(struct drm_device *dev); void intel_atomic_state_clear(struct drm_atomic_state *); static inline struct intel_crtc_state * intel_atomic_get_crtc_state(struct drm_atomic_state *state, struct intel_crtc *crtc) { struct drm_crtc_state *crtc_state; crtc_state = drm_atomic_get_crtc_state(state, &crtc->base); if (IS_ERR(crtc_state)) return ERR_CAST(crtc_state); return to_intel_crtc_state(crtc_state); } static inline struct intel_crtc_state * intel_atomic_get_existing_crtc_state(struct drm_atomic_state *state, struct intel_crtc *crtc) { struct drm_crtc_state *crtc_state; crtc_state = drm_atomic_get_existing_crtc_state(state, &crtc->base); if (crtc_state) return to_intel_crtc_state(crtc_state); else return NULL; } static inline struct intel_plane_state * intel_atomic_get_existing_plane_state(struct drm_atomic_state *state, struct intel_plane *plane) { struct drm_plane_state *plane_state; plane_state = drm_atomic_get_existing_plane_state(state, &plane->base); return to_intel_plane_state(plane_state); } int intel_atomic_setup_scalers(struct drm_i915_private *dev_priv, struct intel_crtc *intel_crtc, struct intel_crtc_state *crtc_state); /* intel_atomic_plane.c */ struct intel_plane_state *intel_create_plane_state(struct drm_plane *plane); struct drm_plane_state *intel_plane_duplicate_state(struct drm_plane *plane); void intel_plane_destroy_state(struct drm_plane *plane, struct drm_plane_state *state); extern const struct drm_plane_helper_funcs intel_plane_helper_funcs; int intel_plane_atomic_check_with_state(struct intel_crtc_state *crtc_state, struct intel_plane_state *intel_state); /* intel_color.c */ void intel_color_init(struct drm_crtc *crtc); int intel_color_check(struct drm_crtc *crtc, struct drm_crtc_state *state); void intel_color_set_csc(struct drm_crtc_state *crtc_state); void intel_color_load_luts(struct drm_crtc_state *crtc_state); /* intel_lspcon.c */ bool lspcon_init(struct intel_digital_port *intel_dig_port); void lspcon_resume(struct intel_lspcon *lspcon); void lspcon_wait_pcon_mode(struct intel_lspcon *lspcon); /* intel_pipe_crc.c */ int intel_pipe_crc_create(struct drm_minor *minor); #ifdef CONFIG_DEBUG_FS int intel_crtc_set_crc_source(struct drm_crtc *crtc, const char *source_name, size_t *values_cnt); #else #define intel_crtc_set_crc_source NULL #endif extern const struct file_operations i915_display_crc_ctl_fops; #endif /* __INTEL_DRV_H__ */
BPI-SINOVOIP/BPI-Mainline-kernel
linux-4.14/drivers/gpu/drm/i915/intel_drv.h
C
gpl-2.0
66,247
/* * Copyright (c) 2015, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.graalvm.compiler.lir.amd64; import org.graalvm.compiler.asm.amd64.AMD64MacroAssembler; import org.graalvm.compiler.lir.LIRInstructionClass; import org.graalvm.compiler.lir.StandardOp.AbstractBlockEndOp; import org.graalvm.compiler.lir.asm.CompilationResultBuilder; public abstract class AMD64BlockEndOp extends AbstractBlockEndOp { public static final LIRInstructionClass<AMD64BlockEndOp> TYPE = LIRInstructionClass.create(AMD64BlockEndOp.class); protected AMD64BlockEndOp(LIRInstructionClass<? extends AMD64BlockEndOp> c) { super(c); } @Override public final void emitCode(CompilationResultBuilder crb) { emitCode(crb, (AMD64MacroAssembler) crb.asm); } public abstract void emitCode(CompilationResultBuilder crb, AMD64MacroAssembler masm); }
YouDiSN/OpenJDK-Research
jdk9/hotspot/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.lir.amd64/src/org/graalvm/compiler/lir/amd64/AMD64BlockEndOp.java
Java
gpl-2.0
1,862
<html> <head> <title>Yadex hacker's guide</title> <meta http-equiv="Content-Style-Type" content="text/css"> <style type="text/css"> DT { margin-bottom: 1em; margin-top: 1em; display: list-item; list-style-image: none; list-style-position: inside; list-style-type: disc; } DD { margin-bottom: 1em; margin-top: 1em } </style> </head> <body> <div align="center"> <img src="logo_small.png" alt="Fancy logo"> <br>Yadex $VERSION ($SOURCE_DATE) <h1>Hacker's guide</h1> </div> <br> <br> <br> <h2>Read this first</h2> Before you start hacking&mdash;no, before you even <em>think</em> about hacking&mdash;Yadex, you should do this&nbsp;: <dl> <dt>Read the <a href="TODO"><code>TODO</code></a> file <dd> Many possible improvements and fixes have been identified and sometimes a particular approach has already been decided on and written down in <code>TODO</code>. Yes it's tedious reading. But if you skip it, you run the risk of seeing your work go to waste because it's in conflict with an earlier plan. <dt>Read the <a href="hackers_guide.html">hacker's guide</a> <dd> Patches that don't <em>at the minimum</em> abide by the coding standards and other guidelines in this document are not very likely to be accepted. <dt>Subscribe to the <a href="contact.html#list_yadex"><code>yadex</code> list</a> <dd> The mailing list is the way by which users and developers communicate. Subscribe to the list and do all communication through the list. It allows developers to coordinate and to benefit from the feedback of all other developers and users. <p> For whatever reason, some contributors seem to think they don't need to subscribe to the list. But the need for coordination remains. Each contributor needs a communication channel with the rest of the project. If it's not the mailing list, it'll probably be the maintainer (me) and I don't want to have to play the role of a mailing list digest server. </p> <p> Having a single many-to-many communication channel is better than having many one-to-one channels because you don't have to repeat the same thing <var>n</var> times to <var>n</var> people. </p> <p> The mailing list is archived and the archives are publicly accessible by anyone at any time. Private mail isn't. </p> <dt>Post on the list about your plans <dd> The job you want to do might be already underway, or might be conflicting with something else. </dl> <h2>Blah</h2> <h3>Foreword</h3> This documents is aimed at people who want to hack Yadex. It is very incomplete, partly due to lack of time, partly because as some subsystems are going to be rewritten, I'd rather not spend too much time documenting them. But if you're interested in a particular area of Yadex's bowels that does not appear here, don't hesitate to let me know. <p> I apologize for the poor quality of Yadex's code but it seemed to me it was better to release something imperfect now than something clean two years from now. If you want to improve it, be my guest. <h3>Introduction</h3> Yadex is written in a mixture of C and C++. The Unix version interfaces with X through Xlib directly&nbsp;; it uses no toolkit. The DOS version uses BGI (Borland Graphics Interface), a rather low-level API to set the video mode, draw lines, text, etc. <h3>Original platform</h3> The Unix version has been developped with GCC 2.7.2, EGCS 1.0.3, EGCS 1.1.1, libc5, glibc2 and XFree 3.3 on a PC K6/200 with Linux 2.0.29, 2.0.30 and 2.0.34. <p> The DOS version has been developped with Borland C++ 4.0 on a PC 486 DX4/75 with MS-DOS 6.22. <p> Yadex should be compilable on all reasonable Unix-and-X11 platforms provided that <ul> <li>you have GNU make, <li>you have a C compiler and a C++ compiler, <li>$c short is 16-bit long, <li>$c long is 32-bit long. </ul> To compile on platforms where $c short or $c long don't have the needed size, just change the definitions of $c u16, $c i16, $c u32 and $c i32 in $c yadex.h. <h3>Historic background</h3> Yadex descends from DEU 5.21. <p> DEU 5.21 was written by Raphaël Quinet, Brendon Wyber and others and released on 1994-05-21. As you probably already know, DEU was a real-mode DOS program, in C, compiled with Borland C++ 4.0 (I think) and using BGI for its output. <p> In the mists of time (that is probably 1996), I began to hack DEU for my own use. In 1997, other people began to use my hack and I gave it a name : "Yade" (which meant Yet Another Doom Editor). It was still a real-mode DOS program. <p> In june 1998, tired of rebooting to DOS every time I wanted to do some Doom level editing, I started porting Yade to Linux. As there already was a Unix program called "Yade" (Yet Another Diagram Editor), I changed the name of my baby to "Yadex". At the same time, I began to use C++ in places so that's why Yadex is such an ugly mixture of languages. <h2>Development cycle</h2> <h3>Compiling, installing, testing</h3> <p>OK. So I want to hack Yadex&nbsp;; what do I do now&nbsp;? The obvious development cycle is <ol> <li>modify the files in <code>src/</code>, <li>type <code>make</code>, <li>type <code>su -c 'make install'</code>, <li>run Yadex and test. </ol> <p>However, there are a few things to know that can make you more efficient. <p>To compile with debugging information, you don't have to modifiy the makefile&nbsp;; just use the appropriate target (<code>dyadex</code>). The resulting executable is put in <code>dobj/0/</code> instead of <code>obj/0/</code>. <p>You don't have to install to test&nbsp;: you can test in place with the special targets <code>test</code> and <code>dtest</code> (<code>test</code> is for the regular executable, <code>dtest</code> is for the debugging executable and is my favourite target by far). When testing through make, you can't pass arguments to Yadex directly&nbsp;: you have to pass them through the <code>A</code> macro. For example&nbsp;: <pre> $ <b>make dtest A='-g heretic foo.wad'</b></pre> <p>You can also run your hack through the debugger with the <code>dg</code> (GDB) and <code>dd</code> (DDD) targets. With those targets, you can't use the <code>A=</code> convention&nbsp;: you have to type "<code>set args blah blah blah</code>" at the debugger prompt. <pre> $ <b>make dg</b> (gdb) <b>set args -g heretic foo.wad</b> (gdb) <b>run</b></pre> <p>Even if you want to install your hack, you may want to keep the original Yadex around, for reference or for a good laugh. To do that, edit the <code>VERSION</code> file before compiling your hack. If your hack bears a different version number, it will not overwrite the original version. You don't have to change the version number much&nbsp;: you can just change "<code>3.8.0</code>" into "<code>3.8.0a</code>" or "<code>3.8.0.0</code>" for example. <p> <h2>The programming environment</h2> <h3>Memory allocation</h3> You're not supposed to use $c malloc() and $c free() but $c GetMemory(), $c FreeMemory(), $c GetFarMemory() and $c FreeFarMemory() instead. Why ? <p>$c GetMemory() and friends manage more things for you. They include an anti-fragmentation system, they try to swap things out when memory is tight (this is an only an issue for the 16-bit DOS version) and if they fail, they call $c fatal_error() so you don't need to check their return value. <p>The reason for $c GetFarMemory() is that, for the 16-bit DOS version, it can allocate more than 64 kB ($c GetMemory() cannot). I must say that I don't use $c GetFarMemory() a lot myself because I don't like the idea of having to use two different memory allocation routines depending on the size I expect to allocate. I modified $c GetMemory() so that it accepts an <code>unsigned long</code> but checks that the passed value fits in $c size_t. In other words, if you call $c GetMemory() with a size of 65,536 the 16-bit DOS version will trigger a fatal error immediately instead of silently allocating 1 byte and letting you search afterwards why the program behaves strangely. A better fix would be to make $c GetMemory() call $c GetFarMemory() when the block is too large for $c malloc(). Any volunteers ? <p>Memory allocated with $c GetMemory() is guaranteed to be freeable with $c free(). On the other hand, memory allocated with $c GetFarMemory() must be freeed with $c FreeFarMemory(). <h3><a name="endianness">Endianness</a></h3> The 16-bit and 32-bit integers in a wad file are always little-endian, whatever the platform. <p>On the other hand, Yadex keeps all its in-core integer in the platform's native endianness, i.e. in little-endian format on little-endian machines and in big-endian format on big-endian machines. <p>The wad endianness &lt;-&gt; native endianness conversion is done automagically by $c wad_read_i16() and $c wad_read_i32(). <p><u>To maintain compatibility with big-endian platforms, all I/O of multibyte integers should be done with those functions.</u> <h2>The directory</h2> <h3>Principle</h3> Like Doom, Yadex accesses lumps through an indirection layer that called the <i>directory</i>. The directory is basically a list of all the lumps that exist in the iwad and/or at least one of the pwads with, for each lump, the information necessary to read it. Each directory entry has 4 fields&nbsp;; the name of the lump, its offset in the wad, its length, and an indirect pointer to the file descriptor for the wad that contains it. <p>As you might expect, if the same lump is present in more than one wad, it has only one directory entry, pointing to the last occurence. <p>When you need to load a lump by name, you call <code>FindMasterDir()</code>. It returns you a pointer on its entry in the directory, which in turn contains everything you need to read it. <h3>Managing the directory</h3> <p>The directory is kept in memory at all times. It is only modified when you initially load the iwad and when you load or unload a pwad. And of course when you delete the directory. Simple, isn't it&nbsp;? <p>Ha-ha, gotcha, this is not how the actual API works. The actual set of operations is somewhat different in that it does not include unloading a pwad. Instead, there is a function to close all unused pwads, that is pwads that are not referenced by a single entry in the directory. I suppose that the reason why it was done this way is that unloading a pwad is a bit more complicated, since it involves finding the previous "provider" of all lumps that the wad to unload used to "provide". I guess the only way to do that would be rebuilding the directory from scratch. This "feature" is discussed in the Comments section below. Anyway, here is the API. <dl> <dt><code>OpenMainWad()</code> <dd>Create the directory and fill it with the contents of the directory of the iwad. <dt><code>OpenPatchWad()</code> <dd>Add a pwad to the list of the open wads and to the directory. <dt><code>CloseUnusedWadFiles()</code> <dd>Close all wads that are not used in the directory anymore. <dt><code>CloseWadFiles()</code> <dd>Close all open wads and delete the list of open wads and the directory. </dl> <h3>Implementation</h3> It has not been said explicitly so far but Yadex maintains a list of all open wads (iwads and pwads). It is a linked list of the <code>WadFileInfo</code> structure. The global variable <code>WadeFileList</code> is a pointer to the first element of the list, which is always the iwad. The type <code>WadPtr</code> is an alias for "<code>struct WadFileInfo *</code>" (yes, I know, it's confusing to have two names for the same thing). <pre> struct WadFileInfo { WadPtr next; // Next file in linked list char *filename; // Name of the wad file FILE *fd; // C file stream information char type[4]; // Type of wad file ("IWAD" or "PWAD") i32 dirsize; // Directory size of wad i32 dirstart; // Offset to start of directory DirPtr directory; // Array of directory information }; typedef struct WadFileInfo *WadPtr; extern WadPtr WadFileList; // List of wad files </pre> <p>The directory itself is a linked list of the <code>MasterDirectory</code> structure. The global variable <code>MasterDir</code> points to the first element of the directory. The type <code>MDirPtr</code> is an alias for "<code>struct MasterDirectory *</code>". <pre> struct Directory { i32 start; // Offset to start of data i32 size; // Byte size of data char name[WAD_NAME]; // Name of data block }; struct MasterDirectory { MDirPtr next; // Next in list WadPtr wadfile; // File of origin struct Directory dir; // Directory data (name, offset, size) }; typedef struct MasterDirectory *MDirPtr; extern MDirPtr MasterDir; // The master directory </pre> <h3>Sample code</h3> To be written : searching for a directory entry. The same thing, in an incremental fashion. <h3>Comments</h3> <p>The decision to use a directory is arguable. It is convenient for the programmer when he/she is looking for the <em>effective</em> instance of a lump, which is the case most of the time. But it also prevents the user from editing a resource (notably, a level), if it has been overridden in another wad. It's not a big deal but I don't like it. <p>The fact that the directory managing operations don't include removing a pwad from the directory means that there is no way for the user to "unload" a pwad. The "<code>read</code>" command has no inverse. The only way to do it is to restart Yadex. <p>Another somewhat non obvious design decision is that, in most places where the directory is updated, <code>CloseUnusedWadFiles()</code> is called too. This means that you can't load two pwads that have exactly the same lumps. As the second pwad is loaded, the first one is automatically (and silently) unloaded. Not a big deal either but, as a user, I don't like the programs I use to behave like that. I'll illustrate my point with the following scenario, which assumes the "unload pwad" function exists&nbsp;: <ol> <li>Load pwad A (MAP01) <li>Load pwad B (MAP01) <li>Unload pwad B <li>Edit MAP01 </ol> At this point, as you have backtracked on your action of loading B, you would expect to see the MAP01 from A, wouldn't you&nbsp;? Instead you get the MAP01 from the iwad, because A was unloaded as you loaded B. From a user point of view, such a behaviour is confusing and therefore to be avoided. <p>I don't like the directory management API very much because it's unexpectedly asymmetric and therefore neither intuitive nor orthogonal. The way Yadex plays games with the directory is really disgusting and confusing to me. <p>I should look into replacing the iwad "on the fly", so that the user is able to change the game parameter dynamically, without restarting Yadex. In fact, the ultimate goal is to remove the game parameter completely or, more precisely, to make it local to a Level object, automatically adjusting and dynamically modifiable by the user. <h2>The wad data</h2> TBD <h2>The level data</h2> <h3>Structure</h3> The data for a level is stored in 10 variables that are declared in <code>levels.h</code> and defined in <code>levels.cc</code>. Here they are : <pre>int NumThings; /* number of things */ TPtr Things; /* things data */ int NumLineDefs; /* number of linedefs */ LDPtr LineDefs; /* linedefs data */ int NumSideDefs; /* number of sidedefs */ SDPtr SideDefs; /* sidedefs data */ int NumVertices; /* number of vertices */ VPtr Vertices; /* vertices data */ int NumSectors; /* number of sectors */ SPtr Sectors; /* sectors data */</pre> <h3>Scope and lifetime</h3> Since those variables (and other critical ones) are unfortunately static, it's not possible to open editing windows on several different levels simultaneously. This should be fixed in the future by making the level data a class and turning those variables into members of that class. <p> I think that the level data class should be separate from the editing window class because it might be useful to open several editing windows on the same level. Separate class should also make the design of the read level and write level routines cleaner and simpler. <h3>Maintenance</h3> It's of paramount importance for the stability and reliability of Yadex that the level data be maintained in a consistent state at all times. In particular, <ul> <li>the $c Num* variables must remain accurate, <li>vertex references in linedefs must be either $c OBJ_NO_NONE or the number of an existing vertex, <li>sidedef references in linedefs must be either $c OBJ_NO_NONE or the number of an existing sidedef, <li>sector references in sidedefs must be either $c OBJ_NO_NONE or the number of an existing sector. </ul> <h3>Loading</h3> The SEGS, SSECTORS, NODES, BLOCKMAP and REJECT lumps are ignored. The other lumps are read into the level data variables with a special case for VERTEXES ; vertices that are not used by any linedef are ignored (such vertices are believed to come from the nodes builder and therefore be irrelevant to level editing). The linedefs vertices references are updated if necessary. <p> Since the endianness of the wad files is fixed (little endian) and thus not necessarily identical to the endianness of the CPU, reading 2- and 4-byte integers from the file is done through special endianness-independant routines. <h3>Saving</h3> If $c MadeMapChanges is false, the SEGS, SSECTORS, NODES, BLOCKMAP, REJECT and VERTEXES lumps are copied from the original file. Else, they are output with a length of zero bytes, except the VERTEXES lump that is created from the the level data ($c NumVertices and $c Vertices). <p>Since the endianness of the wad files is fixed (little endian) and thus not necessarily identical to the endianness of the CPU, writing 2- and 4-byte integers to the file is done through special endianness-independant routines. <h2>Editing windows, or the lack of it</h2> Too many global variables... <p> See "<code>_edit.h</code>". <h2>The editor loop</h2> All the time the user spends editing a level is spent within a certain function, the <dfn>editor loop</dfn>, a.k.a. $c EditorLoop() in $c editloop.c. It's essential for you to understand it if you want to get how Yadex works right. <p> The $c EditorLoop() is an endless loop (okay, not <em>really</em> endless) which, for each iteration, first, refreshes the display, second, waits for an event, third, processes that event. I could have put things in a different order but I liked the idea of displaying something <em>before</em> waiting for user input. <p> Because the event input and the graphical output are complex and not-quite-synchronous processes, I've tried to separate them. $c EditorLoop() gets input events and processes them and calls another function, $c edisplay_c::refresh(), to take care of everything display related. If you replaced $c edisplay_c::refresh() by a stub (and did the same with a couple of functions in $c gfx.c and $c input.c), you could perfectly well, if blindly, run Yadex without a connection to an X server. While you may object that this would be a pointless exercise (to which I agree), it still proves the modularity of the design. <p> The $c edisplay_c::refresh() function is also a very important one to understand, at least if you work on graphical output. It is discussed in another section but, just to settle ideas, I thought I'd give you here a bird's eye view of the whole thing. If there is a single paragraph in this document that you need to read, it's probably this one : <ul> <li>$c EditorLoop() <ul> <li>Call $c edisplay_c::refresh(), <ul> <li>Do some basic geometry management, <li>setup widgets according to editing session, <li>call the $c need_to_clear() method of the widgets to determine whether we need to redisplay everything from scratch, <li>if so, call the $c clear() method of the widgets and call $c ClearScreen() to clear the pixmap (if available) and make sure all subsequent graphical output will be sent to the pixmap (if available), <li>else, make sure all subsequent graphical ouput will be sent to the window and call the $c undraw() method of the widgets from the top down, <li>call the $c draw() method of the widgets from the bottom up, <li>call $c update_display() to refresh the physical display (if we're using the window, it's a no-op, if we're using the pixmap, call $c XCopyArea()). </ul> <li>call $c get_input_status() to get the next event, <li>process that event. </ul> </ul> Note that all graphical output is done from within $c edisplay_c::refresh(). <h2>The display</h2> <h3>Logical and physical display : widgets</h3> The display can be seen at two levels ; the logical level and the physical level. The physical level is just a rectangular matrix of pixels. It's the contents of the window/screen. The logical level is more like "oh, there's a window displayed at those coordinates". <p> There's obviously more to say on this... <h3>The pixmap</h3> To further complicate matters, there are two physical displays : a window and a pixmap. The role of the pixmap is to help avoid flicker. Here's how it works : <p> As long as we do incremental changes to the display (E.G. "undisplaying" the highlight on a vertex or redisplaying the pointer coordinates), we do it directly on the window. <p> But, if we have to redraw everything from scratch, we have to clear the window first which generates an annoying "flashing" of the screen. To avoid this, we instead clear a pixmap, do our display thing on it and then put the pixmap onto the window, with $c XCopyArea(). The result is a flicker-less refresh. <p> The graphical routines from $c gfx.c switch automatically to the pixmap if $c ClearScreen() was called. Thanks to this, that window vs. pixmap thing is nearly transparent to the application functions. $c edisplay_c::refresh() just forces widgets that can undraw themselves to use the window, not the pixmap. <p> But a pixmap is large. For a 800x600 window in 64k colours, 937 kB. And copying it to the window is obviously long. So, on machines with little memory or a slow CPU, the user might prefer to do without it. That's what $c no_pixmap is for. <h2>The selection</h2> <h3>Introduction</h3> From the user's point of view, the selection is a "list" of objects. I use the term "list" instead of "collection" because, for certain operations, the order in which objects were added to the selection is significant. <p> From the programmer's point of view, the selection is a singly linked list of objects of this type : <p> <pre>typedef struct SelectionList *SelPtr; struct SelectionList { SelPtr next; /* next in list */ int objnum; /* object number */ };</pre> <p> Note that the $c SelectionList structure has no $c objtype field ; the type of the object (THING, vertex...) is implicit from the current mode (the $c obj_type field from the $c edit_t structure). As a consequence, the selection cannot contain objects of different types. <p> The selection manipulation functions are supposed to be defined in $c selectn.c and declared in $c selectn.h. Here they are : <dl> <dt><code>void SelectObject (SelPtr *s, int n)</code> <dd>Adds object $c n at the beginning of list $c *s. $c *s can be $c NULL ; it means the list is empty. Warning : does not check that object $c n is not already in the list. <dt><code>void UnSelectObject (SelPtr *s, int n)</code> <dd>Removes from list $c *s all occurrences of object $c n. If all objects are removed, sets $c *s to $c NULL. <dt><code>void select_unselect_obj (SelPtr *s, int n)</code> <dd>If the object $c n is already in the list $c *n, remove it. If it's not, insert it at the beginning. $c *s can be $c NULL ; it means the list is empty. <dt><code>Bool IsSelected (SelPtr s, int n)</code> <dd>Tells whether object $c n is in selection $c s. $c s can be $c NULL ; it means the list is empty. <dt><code>void ForgetSelection (SelPtr *s)</code> <dd>Frees all memory allocated to list $c *s and sets $c *s to $c NULL. <dt><code>void DumpSelection (SelPtr s)</code> <dd>Debugging function ; prints the contents of the selection to $c stdout. </dl> Note that there is not selection iteration function. Indeed, iterating through a selection is always done by the application functions themselves, usually with something like : <p> <pre>SelPtr cur; for (cur = list; cur; cur = cur-&gt;next) do_something_with_object (cur-&gt;objnum); </pre> <h3>Selecting in/out</h3> When you draw a box with [<kbd>Ctrl</kbd>] depressed, the objects in the box are added to the selection. However, if some of those objects were already selected, they are unselected. So $c SelectObjectsInBox() cannot just add all the objects in the box to the list or we would end up with multiply selected objects. Wouldn't do us much good when displaying the selection or dragging objects. <p> That's when $c select_unselect_obj() is used. <h2>The highlight</h2> TBD <h2>Colours</h2> The colour management system in very complex. There are lots of things to say on that topic. However, for most uses, you need to know only three functions : <dl> <dt>$c set_colour() <dd>Set the current colour to a new value. <dt>$c push_colour() <dd>Save the current colour on the colour stack and set the current colour to a new value. <dt>$c pop_colour() <dd>Set the current colour to the value it had at the moment of the last call to $c push_colour(). </dl> <h2>Menus and pop-up windows</h2> TBD <h2>Game graphics</h2> <h3>Doom graphics basics</h3> Doom and its derivatives have two main formats for graphics&nbsp;: pictures and plain bitmaps. Pictures are made of columns which are in turn made of one or more posts. If there are several posts in a column, they can be separated by void space and thus the picture can have transparent areas. Pictures are used for patches, sprites and the rest of the graphics (but Yadex doesn't use them). Plain bitmaps are just arrays of pixels and cannot contain transparent areas. That latter format is used only for flats, which are all 64&times;64 bitmaps. <p>Textures are made by pasting one or more patches onto a rectangular buffer. The resulting image can be of course transparent. <p>For all formats, a pixel is a byte. The value of the byte (between 0 and 255 inclusive) is an index into one of the palettes contained in the <code>PLAYPAL</code> lump. To be able to know the actual RGB colour of a pixel, it is necessary to look up its value in the <code>PLAYPAL</code> (normally, only the first palette is used). <h3>The <code>Img</code> class</h3> <p>The <code>Img</code> class is used to store and manipulate all game graphics (flats, patches, sprites and textures). It's a palette-encoded rectangular array of pixels. The type <code>img_pixel_t</code> is the type of a pixel; it's the same as in the wad, that is a byte. The value of the elements of the array is also the same as in the wad, that is an index into <code>PLAYPAL</code>. Transparent areas are filled with colour number 0 (which translates to black with all known iwads). Unfortunately, colour 0 is also used in certain graphics which causes them to be rendered with holes in them. This needs to be fixed. <p>The related functions are&nbsp;: <pre>Img::Img - default constructor Img::Img - constructor with dimensions Img::~Img - dtor Img::is_null - return true iff this is a null image Img::width - return the current width Img::height - return the current height Img::buf - return a const pointer on the buffer Img::wbuf - return a writable pointer on the buffer Img::resize - resize the image clear_img - clear a game image buffer display_img - display a game image scale_img - scale a game image spectrify_img - make a game image look vaguely like a spectre LoadPicture - read a picture from a wad file into an Img object</pre> <h3>Viewing graphics</h3> <p>As is the case with saving graphics to a file, viewing graphics would involve a lot of coding to do it in an optimized fashion. Therefore it's done in a somewhat wasteful way&nbsp;: <ol> <li>the image is put into an <code>Img</code> object <li>the <code>Img</code> is pasted onto the window or screen </ol> <p>The first step is done with <code>DisplayFloorTexture()</code> (for flats) and <code>LoadPicture()</code> (for other graphics). For textures, <code>LoadPicture()</code> is called repeatedly on the same <code>Img</code> object, once for each flat. <p>The second step is done with <code>display_img()</code>. It takes care of converting Doom pixel values into actual pixel values needed by the graphical API (which depend on a lot of factors like the video mode, type and depth of visual, byte order of X server, etc.) and getting the graphical API to display it on the window or screen. <p><code>display_pic()</code> combines fetching the image into the game image buffer and displaying it. <p><code>spectrify_img()</code> can be used on a game image buffer to make it look more or less like a spectre. <h3>Saving graphics to file (screenshots etc.)</h3> The basic idea is to <ol> <li>get the image to save in an <code>Rgbbmp</code> buffer (with <code>window_to_rgbbmp()</code>), <li>save the <code>Rgbbmp</code> buffer to a file (with <code>rgbbmp_to_ppm()</code>). </ol> This is inefficient because, in many cases, the image could be saved directly from the window to the file. This two-step algorithm wastes memory (the buffer can be quite large) and time. However, there is a good reason for doing things this way. <p>The way to retrieve the image from the window or screen is very dependent on the platform or video mode or type of visual and the fashion in which the image is read is very dependent on the graphic format. Therefore, if you want to use a one-step algorithm and you have <var>n</var> platforms or video modes or types of visuals and <var>m</var> graphic formats, you have to write <var>n</var> &times; <var>m</var> functions. With a two-step algorithm, you have only <var>n</var> + <var>m</var> functions to write. As saving graphics to file is not a critical function, I'd rather keep the code short and simple, unless the result proves unacceptable. <h2>Saving</h2> <p>One very important constraint in the saving code is that it should never fail unless there is no reasonable alternative. That's because, for users, saving is a <em>passage obligé</em> to quit the program without losing their work. Therefore, the saving code must be particularly robust and able to recover from errors. <p>This implies that the saving code <strong>must not need to allocate new memory</strong>. To understand why, consider the following scenario&nbsp;: you load a level and edit it until Yadex uses all the available memory save a few kB. Then you want to save it and Yadex says "nope, I don't have enough memory to do that". From a user point of view, that sucks. <p>Unfortunately, at present, many benign errors are considered fatal when saving. For example, trying to save to a file on which you don't have the necessary rights will make Yadex abort even though this error is perfectly recoverable. This should be fixed since it could cause users to lose data. <h2>Compile-time variables (defines)</h2> <dl> <dt>$c AYM_MOUSE_HACKS <dd>Some experimental code by me to try to understand why, under DOS, the mouse pointer moves 8 pixels at a time (seems to depend on the mouse driver ?). <p> <dt>$c CIRRUS_PATCH <dd>Dates back to DEU 5.21. Apparently, some code specific to Cirrus VGA boards. Does nothing unless $c Y_BGI is defined. <p> <dt>$c DEBUG <dd>The obvious. <p> <dt>$c DIALOG <dd>Experimental code by me to test the dialog box function that Jim Flynn wrote for Deth in the beginning of 1998. <p> <dt>$c NO_CIRCLES <dd>If your BGI driver does not support drawing circles, define this and Yadex will draw squares instead. <p> <dt>$c OLD <dd>Misc. obsolete stuff I didn't want to delete at the time. Never define it or you'll break Yadex&nbsp;! Code under <code>#ifdef OLD</code> should probably be removed. <p> <dt>$c OLD_GRID <dd>Pre-1.5 grid (no dots, only lines). <p> <dt>$c OLD_METHOD <dd>My cruft. Code thus <code>#ifdef</code>'d should probably be removed. <p> <dt>$c OLD_MESSAGE <dd>My cruft. Code thus <code>#ifdef</code>'d should probably be removed. <p> <dt>$c ROUND_THINGS <dd>Draw THINGS as circles (like DEU did), not as squares. <p> <dt>$c SWAP_TO_XMS <dd>Comes from DEU : related to code supposed to use XMS as "swap space". Apparently, was never used ? <p> <dt>$c Y_BGI <dd>Use BGI for graphics output and BIOS for keyboard and mouse input. Makes senses only for DOS + Borland C++ 4.0. Exactly one of ($c Y_BGI, $c Y_X11) must be defined. <p> <dt>$c Y_DOS <dd>Compile for DOS (with Borland C++ 4.0). Allows, among others, the $c huge and $c far pointer modifiers. Exactly one of ($c Y_DOS, $c Y_UNIX) must be defined. <p> <dt>$c Y_UNIX <dd>Compile for Unix (with GCC 2.7.2). Causes, among other things, "huge" and "far" to be <code>#define</code>'d to "". Exactly one of ($c Y_DOS, $c Y_UNIX) must be defined. <p> <dt>$c Y_X11 <dd>Use X11 (Xlib) for graphics output, keyboard and mouse input and other events. Exactly one of ($c Y_BGI, $c Y_X11) must be defined. </dl> <h2>Coding standards</h2> Warning : this section was written when Yadex was still plain C. Some of it may be inadequate or incomplete with C++. <h3>Indent style</h3> BSD style with an indent width of 2. <ul> <li>tab stops every 8 characters, <li>indent width is 2 spaces, <li>line width limited to 80 characters, <li>the braces have the same indentation as the text they contain, <li>the body of a function is not indented. </ul> Many files still use Whitesmiths with an indent width of 3. They will be reformatted. Whitespace&nbsp;: <ul> <li>one space between the name of the function/statement and the "(", <li>no space between the "(" and the first argument, <li>no space between the end of the argument and the "," or ";", <li>one space between the "," or ";" and the next argument, <li>no space between the end of the argument and the ")", <li>no space between the ")" and the ";", <li>no space between the name of a variable and a "<code>[</code>", <li>no space between a "<code>[</code>" and the character that follows, <li>no space between a "<code>]</code>" and the character that precedes, <li>one space on either side of binary operators, <li>the dereferencing operator ("<code>*</code>") has a space to the left but no space to the right. </ul> <p> Example : <p> <pre>static const char *foo (int n) { for (stuff; stuff; stuff) { if (thingie || gadget ()) call_this_one (with, three, exactly[arguments]); else dont (); call_that_one (); } return NULL; }</pre> <h3>Identifiers</h3> For variables and functions (and certain macros), I use all-lower-case identifiers with underscores where it seems appropriate. For enums and most macros, I use all-upper-case identifiers. <p> I consistently use the English spelling (E.G. "colour", not "color"). <h3>Conditionals</h3> The argument of <code>if</code> and <code>while</code> and the second argument of <code>for</code> are booleans, not integers, so you should provide a boolean expression. The following expressions are not booleans&nbsp;: <ul> <li>pointers, <li>the return value of <code>strcmp()</code>, <li>the return value of functions to return 0 to indicate success and non-zero to indicate failure, </ul> Therefore, don't write <p><pre> if (! fopen (filename, "r")) // Test for failure ... if (strcmp (str1, str2)) // Test for non-equality ... if (! strcmp (str1, str2)) // Test for equality ... if (remove (filename)) // Test for failure ... </pre></p> but <p><pre> if (fopen (filename, "r") <b>== NULL</b>) ... if (strcmp (str1, str2) <b>!= 0</b>) ... if (strcmp (str1, str2) <b>== 0</b>) ... if (remove (filename) <b>!= 0</b>) ... </pre></p> On the other hand, when an expression is a boolean, you don't need to add anything. <i>Don't</i> write <code>if (boolvar == true)</code>. <h3>General style</h3> My general style is to try to make it look clear and pretty. If there are several similar consecutive statements, I try to align what I can. <p> <pre>/* This is a long comment. A long comment is a comment that spans over several lines. See how I "typeset" it. */ func (object, mutter ); another_func (object, mumble, 46); yet_another (object, grunt ); // Short comment.</pre> <h3>Code</h3> Good code ;-). <p> <ul> <li>Use $c const for all arguments passed by reference unless they're modified. <li>Use $c static for all functions and variables unless they're extern. <li>Be careful with $c int, on some platforms, it's equivalent to $c short, on others, it's equivalent to $c long. <li>Whenever you need a fixed number of bytes, use $c u16, $c i32, etc. <li>Use prototypes. <li>Prototype functions that take no args with "<code>foo (void);</code>", not "<code>foo ();</code>" (author's note : this is C-ish !). <li>Try to avoid buffer overruns by using $c y_snprintf() instead of $c sprintf(), $c al_scps() instead of $c strcpy(), $c al_saps() instead of $c strcat(), etc. </ul> <h3>Functions to avoid</h3> <dl> <dt><b><code>sprintf()</code></b> <dd>Prone to buffer overruns. Use <code>y_snprintf()</code> instead, as it uses <code>snprintf()</code> if it's available, and falls back on <code>sprintf()</code> if it isn't. <dt><b><code>snprintf()</code></b> <dd>Not supported widely enough yet. Use <code>y_snprintf()</code> instead. If <code>snprintf()</code> is available, it uses it (well, at least that's what it's meant to do). If not, it falls back on <code>sprintf()</code>. <dt><b><code>stricmp()</code></b> and <b><code>strcasecmp()</code></b> <dd>Not portable. Use <code>y_stricmp()</code> instead. <code>y_strnicmp()</code> is available as well. </dl> <h3>Use the helpers</h3> <dl> <dt><b>Converting an ASCII digit into its value</b> <dd>Don't subtract <code>'0'</code>. Use <code>dectoi()</code> or <code>hextoi()</code>. <dt><b>Testing whether a value is comprised between two bounds</b> <dd>Instead of <code>v &gt;= min &amp;&amp; v &lt;= max</code> you can use <code>within (v, min, max)</code>. It's inlined. The inverse test is provided by <code>outside()</code>. <dt><b>Comparing two file names</b> <dd>If you come from a Unix background, you'll be tempted to use <code>strcmp()</code>. If you come from a DOS background, you'll be tempted to use <code>y_stricmp()</code>. Neither is correct. Use <code>fncmp()</code>. In its current implementation, it's not correct either but it gets you a little bit closer. If only because it helps you to say what you mean. <dt><b>Telling whether is file name is absolute</b> <dd>This is not needed in many places. But when it is, use <code>is_absolute()</code>. <dt><b>Comparing two lump names</b> <dd>The code is peppered with <code>y_strnicmp(name1, name2, WAD_NAME)</code>. This should of course be replaced by a specialized function. This also applies to comparing flat names, texture names, sprite names, patch names, etc. </dl> <h3>Includes</h3> Put $c yadex.h first, then any standard headers needed (E.G. $c math.h) then all the Yadex headers needed by alphabetical order. <p> If the need arises to protect a Yadex header against multiple inclusion, use this : <p> <pre>#ifndef YH_FOO #define YH_FOO (put the contents of the header here) #endif</pre> <h3>File format</h3> <table width="100%" bgcolor="#90a0c0" cellpadding="8"> <tr> <td> The format of the source files is&nbsp;: <table cellspacing="0" cellpadding="0"> <tr> <td> <ul> <li>Character set&nbsp; <li>Line length&nbsp; <li>Line terminator&nbsp; <li>Tab width&nbsp; </ul> </td> <td> ISO 8859-1 (a.k.a. Latin1) <br>80 columns <br>LF <br>8 </td> </tr> </table> </table> <h2>Notes</h2> Here is the text of the notes in the source code. <p> <dl> <dt>1 <dd>It's important to set the $c line_width to 1 and not 0 for GCs that have the $c GXxor function, for the following reason. <p> Those GCs are used for objects that should be "undrawn" by drawing them again, E.G. the highlight. Now, imagine the following scenario : you highlight a linedef and then press, say, page up to make the window scroll. This is not an incremental change to the display so everything is redrawn from scratch onto the pixmap. The pixmap is <code>XCopyArea()</code>'d onto the window, the linedef still highlighted. Then, Yadex realizes that the map coordinates of the pointer have changed so the linedef is not highlighted anymore. It dutifully unhighlights the linedef. But $c XDrawLine() on a window does not use the same algorithm as on a pixmap (attempts to use the blitter on the video card). So the first line and the second don't coincide exactly and the result is a trail of yellow pixels where the highlight used to be. <p> That's why I use a $c line_width sure that the same algorithm is used both for pixmap output and for window output. </dl> <p><hr>AYM $SELF_DATE </body> </html>
farhaven/yadex
docsrc/hackers_guide.html
HTML
gpl-2.0
41,900
/* * SGI RTC clock/timer routines. * * 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 * * Copyright (c) 2009 Silicon Graphics, Inc. All Rights Reserved. * Copyright (c) Dimitri Sivanich */ #include <linux/clockchips.h> #include <asm/uv/uv_mmrs.h> #include <asm/uv/uv_hub.h> #include <asm/uv/bios.h> #include <asm/uv/uv.h> #include <asm/apic.h> #include <asm/cpu.h> #define RTC_NAME "sgi_rtc" static cycle_t uv_read_rtc(struct clocksource *cs); static int uv_rtc_next_event(unsigned long, struct clock_event_device *); static void uv_rtc_timer_setup(enum clock_event_mode, struct clock_event_device *); static struct clocksource clocksource_uv = { .name = RTC_NAME, .rating = 400, .read = uv_read_rtc, .mask = (cycle_t)UVH_RTC_REAL_TIME_CLOCK_MASK, .shift = 10, .flags = CLOCK_SOURCE_IS_CONTINUOUS, }; static struct clock_event_device clock_event_device_uv = { .name = RTC_NAME, .features = CLOCK_EVT_FEAT_ONESHOT, .shift = 20, .rating = 400, .irq = -1, .set_next_event = uv_rtc_next_event, .set_mode = uv_rtc_timer_setup, .event_handler = NULL, }; static DEFINE_PER_CPU(struct clock_event_device, cpu_ced); /* There is one of these allocated per node */ struct uv_rtc_timer_head { spinlock_t lock; /* next cpu waiting for timer, local node relative: */ int next_cpu; /* number of cpus on this node: */ int ncpus; struct { int lcpu; /* systemwide logical cpu number */ u64 expires; /* next timer expiration for this cpu */ } cpu[1]; }; /* * Access to uv_rtc_timer_head via blade id. */ static struct uv_rtc_timer_head **blade_info __read_mostly; static int uv_rtc_evt_enable; /* * Hardware interface routines */ /* Send IPIs to another node */ static void uv_rtc_send_IPI(int cpu) { unsigned long apicid, val; int pnode; apicid = cpu_physical_id(cpu); pnode = uv_apicid_to_pnode(apicid); apicid |= uv_apicid_hibits; val = (1UL << UVH_IPI_INT_SEND_SHFT) | (apicid << UVH_IPI_INT_APIC_ID_SHFT) | (X86_PLATFORM_IPI_VECTOR << UVH_IPI_INT_VECTOR_SHFT); uv_write_global_mmr64(pnode, UVH_IPI_INT, val); } /* Check for an RTC interrupt pending */ static int uv_intr_pending(int pnode) { if (is_uv1_hub()) return uv_read_global_mmr64(pnode, UVH_EVENT_OCCURRED0) & UV1H_EVENT_OCCURRED0_RTC1_MASK; else return uv_read_global_mmr64(pnode, UV2H_EVENT_OCCURRED2) & UV2H_EVENT_OCCURRED2_RTC_1_MASK; } /* Setup interrupt and return non-zero if early expiration occurred. */ static int uv_setup_intr(int cpu, u64 expires) { u64 val; unsigned long apicid = cpu_physical_id(cpu) | uv_apicid_hibits; int pnode = uv_cpu_to_pnode(cpu); uv_write_global_mmr64(pnode, UVH_RTC1_INT_CONFIG, UVH_RTC1_INT_CONFIG_M_MASK); uv_write_global_mmr64(pnode, UVH_INT_CMPB, -1L); if (is_uv1_hub()) uv_write_global_mmr64(pnode, UVH_EVENT_OCCURRED0_ALIAS, UV1H_EVENT_OCCURRED0_RTC1_MASK); else uv_write_global_mmr64(pnode, UV2H_EVENT_OCCURRED2_ALIAS, UV2H_EVENT_OCCURRED2_RTC_1_MASK); val = (X86_PLATFORM_IPI_VECTOR << UVH_RTC1_INT_CONFIG_VECTOR_SHFT) | ((u64)apicid << UVH_RTC1_INT_CONFIG_APIC_ID_SHFT); /* Set configuration */ uv_write_global_mmr64(pnode, UVH_RTC1_INT_CONFIG, val); /* Initialize comparator value */ uv_write_global_mmr64(pnode, UVH_INT_CMPB, expires); if (uv_read_rtc(NULL) <= expires) return 0; return !uv_intr_pending(pnode); } /* * Per-cpu timer tracking routines */ static __init void uv_rtc_deallocate_timers(void) { int bid; for_each_possible_blade(bid) { kfree(blade_info[bid]); } kfree(blade_info); } /* Allocate per-node list of cpu timer expiration times. */ static __init int uv_rtc_allocate_timers(void) { int cpu; blade_info = kmalloc(uv_possible_blades * sizeof(void *), GFP_KERNEL); if (!blade_info) return -ENOMEM; memset(blade_info, 0, uv_possible_blades * sizeof(void *)); for_each_present_cpu(cpu) { int nid = cpu_to_node(cpu); int bid = uv_cpu_to_blade_id(cpu); int bcpu = uv_cpu_hub_info(cpu)->blade_processor_id; struct uv_rtc_timer_head *head = blade_info[bid]; if (!head) { head = kmalloc_node(sizeof(struct uv_rtc_timer_head) + (uv_blade_nr_possible_cpus(bid) * 2 * sizeof(u64)), GFP_KERNEL, nid); if (!head) { uv_rtc_deallocate_timers(); return -ENOMEM; } spin_lock_init(&head->lock); head->ncpus = uv_blade_nr_possible_cpus(bid); head->next_cpu = -1; blade_info[bid] = head; } head->cpu[bcpu].lcpu = cpu; head->cpu[bcpu].expires = ULLONG_MAX; } return 0; } /* Find and set the next expiring timer. */ static void uv_rtc_find_next_timer(struct uv_rtc_timer_head *head, int pnode) { u64 lowest = ULLONG_MAX; int c, bcpu = -1; head->next_cpu = -1; for (c = 0; c < head->ncpus; c++) { u64 exp = head->cpu[c].expires; if (exp < lowest) { bcpu = c; lowest = exp; } } if (bcpu >= 0) { head->next_cpu = bcpu; c = head->cpu[bcpu].lcpu; if (uv_setup_intr(c, lowest)) /* If we didn't set it up in time, trigger */ uv_rtc_send_IPI(c); } else { uv_write_global_mmr64(pnode, UVH_RTC1_INT_CONFIG, UVH_RTC1_INT_CONFIG_M_MASK); } } /* * Set expiration time for current cpu. * * Returns 1 if we missed the expiration time. */ static int uv_rtc_set_timer(int cpu, u64 expires) { int pnode = uv_cpu_to_pnode(cpu); int bid = uv_cpu_to_blade_id(cpu); struct uv_rtc_timer_head *head = blade_info[bid]; int bcpu = uv_cpu_hub_info(cpu)->blade_processor_id; u64 *t = &head->cpu[bcpu].expires; unsigned long flags; int next_cpu; spin_lock_irqsave(&head->lock, flags); next_cpu = head->next_cpu; *t = expires; /* Will this one be next to go off? */ if (next_cpu < 0 || bcpu == next_cpu || expires < head->cpu[next_cpu].expires) { head->next_cpu = bcpu; if (uv_setup_intr(cpu, expires)) { *t = ULLONG_MAX; uv_rtc_find_next_timer(head, pnode); spin_unlock_irqrestore(&head->lock, flags); return -ETIME; } } spin_unlock_irqrestore(&head->lock, flags); return 0; } /* * Unset expiration time for current cpu. * * Returns 1 if this timer was pending. */ static int uv_rtc_unset_timer(int cpu, int force) { int pnode = uv_cpu_to_pnode(cpu); int bid = uv_cpu_to_blade_id(cpu); struct uv_rtc_timer_head *head = blade_info[bid]; int bcpu = uv_cpu_hub_info(cpu)->blade_processor_id; u64 *t = &head->cpu[bcpu].expires; unsigned long flags; int rc = 0; spin_lock_irqsave(&head->lock, flags); if ((head->next_cpu == bcpu && uv_read_rtc(NULL) >= *t) || force) rc = 1; if (rc) { *t = ULLONG_MAX; /* Was the hardware setup for this timer? */ if (head->next_cpu == bcpu) uv_rtc_find_next_timer(head, pnode); } spin_unlock_irqrestore(&head->lock, flags); return rc; } /* * Kernel interface routines. */ /* * Read the RTC. * * Starting with HUB rev 2.0, the UV RTC register is replicated across all * cachelines of it's own page. This allows faster simultaneous reads * from a given socket. */ static cycle_t uv_read_rtc(struct clocksource *cs) { unsigned long offset; if (uv_get_min_hub_revision_id() == 1) offset = 0; else offset = (uv_blade_processor_id() * L1_CACHE_BYTES) % PAGE_SIZE; return (cycle_t)uv_read_local_mmr(UVH_RTC | offset); } /* * Program the next event, relative to now */ static int uv_rtc_next_event(unsigned long delta, struct clock_event_device *ced) { int ced_cpu = cpumask_first(ced->cpumask); return uv_rtc_set_timer(ced_cpu, delta + uv_read_rtc(NULL)); } /* * Setup the RTC timer in oneshot mode */ static void uv_rtc_timer_setup(enum clock_event_mode mode, struct clock_event_device *evt) { int ced_cpu = cpumask_first(evt->cpumask); switch (mode) { case CLOCK_EVT_MODE_PERIODIC: case CLOCK_EVT_MODE_ONESHOT: case CLOCK_EVT_MODE_RESUME: /* Nothing to do here yet */ break; case CLOCK_EVT_MODE_UNUSED: case CLOCK_EVT_MODE_SHUTDOWN: uv_rtc_unset_timer(ced_cpu, 1); break; } } static void uv_rtc_interrupt(void) { int cpu = smp_processor_id(); struct clock_event_device *ced = &per_cpu(cpu_ced, cpu); if (!ced || !ced->event_handler) return; if (uv_rtc_unset_timer(cpu, 0) != 1) return; ced->event_handler(ced); } static int __init uv_enable_evt_rtc(char *str) { uv_rtc_evt_enable = 1; return 1; } __setup("uvrtcevt", uv_enable_evt_rtc); static __init void uv_rtc_register_clockevents(struct work_struct *dummy) { struct clock_event_device *ced = &__get_cpu_var(cpu_ced); *ced = clock_event_device_uv; ced->cpumask = cpumask_of(smp_processor_id()); clockevents_register_device(ced); } static __init int uv_rtc_setup_clock(void) { int rc; if (!is_uv_system()) return -ENODEV; clocksource_uv.mult = clocksource_hz2mult(sn_rtc_cycles_per_second, clocksource_uv.shift); /* If single blade, prefer tsc */ if (uv_num_possible_blades() == 1) clocksource_uv.rating = 250; rc = clocksource_register(&clocksource_uv); if (rc) printk(KERN_INFO "UV RTC clocksource failed rc %d\n", rc); else printk(KERN_INFO "UV RTC clocksource registered freq %lu MHz\n", sn_rtc_cycles_per_second/(unsigned long)1E6); if (rc || !uv_rtc_evt_enable || x86_platform_ipi_callback) return rc; /* Setup and register clockevents */ rc = uv_rtc_allocate_timers(); if (rc) goto error; x86_platform_ipi_callback = uv_rtc_interrupt; clock_event_device_uv.mult = div_sc(sn_rtc_cycles_per_second, NSEC_PER_SEC, clock_event_device_uv.shift); clock_event_device_uv.min_delta_ns = NSEC_PER_SEC / sn_rtc_cycles_per_second; clock_event_device_uv.max_delta_ns = clocksource_uv.mask * (NSEC_PER_SEC / sn_rtc_cycles_per_second); rc = schedule_on_each_cpu(uv_rtc_register_clockevents); if (rc) { x86_platform_ipi_callback = NULL; uv_rtc_deallocate_timers(); goto error; } printk(KERN_INFO "UV RTC clockevents registered\n"); return 0; error: clocksource_unregister(&clocksource_uv); printk(KERN_INFO "UV RTC clockevents failed rc %d\n", rc); return rc; } arch_initcall(uv_rtc_setup_clock);
yubo/linux-2-6-32-220-23-1-el6
arch/x86/kernel/uv_time.c
C
gpl-2.0
10,617
//////////////////////////////////////////////////////////////////////////////////////// // // Nestopia - NES/Famicom emulator written in C++ // // Copyright (C) 2003-2008 Martin Freij // // This file is part of Nestopia. // // Nestopia 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. // // Nestopia 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 Nestopia; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // //////////////////////////////////////////////////////////////////////////////////////// #ifndef NST_BOARD_TXC_POLICEMAN_H #define NST_BOARD_TXC_POLICEMAN_H #ifdef NST_PRAGMA_ONCE #pragma once #endif namespace Nes { namespace Core { namespace Boards { namespace Txc { class Policeman : public Board { public: explicit Policeman(const Context& c) : Board(c) {} private: void SubReset(bool); NES_DECL_POKE( 8400 ); }; } } } } #endif
hendersa/bes
src/nes/core/board/NstBoardTxcPoliceman.hpp
C++
gpl-2.0
1,486
<?php /* $Id: header.php,v 1.1.1.1 2004/03/04 23:40:39 ccwjr Exp $ osCommerce, Open Source E-Commerce Solutions http://www.oscommerce.com Copyright (c) 2003 osCommerce Released under the GNU General Public License */ //You will need to edit this file In the /templates/(template name)/ //If it is used by the template you are using> ?>
loadedcommerce/Loaded6CE
Loaded_Commerce_CE/includes/header.php
PHP
gpl-2.0
351
<?php /******************************************************* * * Custom Recent Project Widget * By: Andre Gagnon * http://www.designcirc.us * *******************************************************/ // Initialize widget add_action( 'widgets_init', 'ag_recentprojects_widgets' ); // Register widget function ag_recentprojects_widgets() { register_widget( 'ag_recentprojects_widget' ); } // Widget class class ag_recentprojects_widget extends WP_Widget { /*----------------------------------------------------------*/ /* Set up the Widget /*----------------------------------------------------------*/ function __construct() { /* General widget settings */ $widget_ops = array( 'classname' => 'ag_recentprojects_widget', 'description' => __('A widget that displays small project thumbnails from recent portfolio items.', 'framework') ); /* Widget control settings */ $control_ops = array( 'width' => 400, 'height' => 350, 'id_base' => 'ag_recentprojects_widget' ); /* Create widget */ parent::__construct( 'ag_recentprojects_widget', __('Custom Recent Portfolio Items Widget', 'framework'), $widget_ops, $control_ops ); } /*----------------------------------------------------------*/ /* Display The Widget /*----------------------------------------------------------*/ function widget( $args, $instance ) { extract( $args ); $title = apply_filters('widget_title', $instance['title'] ); /* Variables from settings. */ $postnum = $instance['postnum']; /* Before widget (defined in functions.php). */ echo $before_widget; /* Display The Widget */ ?> <?php /* Display the widget title & subtitle if one was input (before and after defined by themes). */ if ( $title ) echo $before_title . $title . $after_title; ?> <?php $loop = new WP_Query( array( 'post_type' => 'portfolio', 'posts_per_page' => $postnum, 'orderby' => 'menu_order', // Sorted by Drag and Drop Order 'order' => 'DESC', // Top to Bottom ) ); ?> <div class="recent-projects"> <?php while ( $loop->have_posts() ) : $loop->the_post(); ?> <?php if (has_post_thumbnail()) { ?> <div class="recent-project"> <a href="<?php the_permalink(); ?>" class="hover"><?php the_post_thumbnail('tinyfeatured', array('class' => 'scale-with-grid')); ?></a> </div> <?php } ?> <?php endwhile;?> <div class="clear"></div> </div> <?php /* After widget (defined by themes). */ echo $after_widget; } /*----------------------------------------------------------*/ /* Update the Widget /*----------------------------------------------------------*/ function update( $new_instance, $old_instance ) { $instance = $old_instance; /* Remove HTML: */ $instance['title'] = strip_tags( $new_instance['title'] ); $instance['postnum'] = strip_tags( $new_instance['postnum'] ); return $instance; } /*----------------------------------------------------------*/ /* Widget Settings /*----------------------------------------------------------*/ function form( $instance ) { /* Default widget settings */ $defaults = array( 'title' => '', 'postnum' => '', ); $instance = wp_parse_args( (array) $instance, $defaults ); ?> <p> <label for="<?php echo $this->get_field_id( 'title' ); ?>"> <?php _e('Projects Title (Optional):', 'framework') ?> </label> <input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" value="<?php echo $instance['title']; ?>" /> </p> <p> <label for="<?php echo $this->get_field_id( 'postnum' ); ?>"> <?php _e('Number of Posts:', 'framework') ?> </label> <input class="widefat" id="<?php echo $this->get_field_id( 'postnum' ); ?>" name="<?php echo $this->get_field_name( 'postnum' ); ?>" value="<?php echo $instance['postnum']; ?>" /> </p> <?php } } ?>
bmdinteractive/b3sci
wp-content/themes/gridstack_default/functions/widgets/widget-recent-projects.php
PHP
gpl-2.0
3,910
/* APPLE LOCAL file v7 merge */ /* Test the `vreinterprets16_s8' ARM Neon intrinsic. */ /* This file was autogenerated by neon-testgen. */ /* { dg-do assemble } */ /* { dg-require-effective-target arm_neon_ok } */ /* { dg-options "-save-temps -O0 -mfpu=neon -mfloat-abi=softfp" } */ #include "arm_neon.h" void test_vreinterprets16_s8 (void) { int16x4_t out_int16x4_t; int8x8_t arg0_int8x8_t; out_int16x4_t = vreinterpret_s16_s8 (arg0_int8x8_t); } /* { dg-final { cleanup-saved-temps } } */
unofficial-opensource-apple/llvmgcc42
gcc/testsuite/gcc.target/arm/neon/vreinterprets16_s8.c
C
gpl-2.0
503
/* * Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * @test * @summary class p1.c1 defined in an unnamed module tries to access p2.c2 defined in m2x. * Access allowed, an unnamed module can read all modules and p2 in module m2x * which is exported unqualifiedly. * @modules java.base/jdk.internal.misc * @library /test/lib * @compile myloaders/MyDiffClassLoader.java * @compile p2/c2.java * @compile p1/c1.java * @run main/othervm -Xbootclasspath/a:. UmodDiffCL_ExpUnqual */ import static jdk.test.lib.Asserts.*; import java.lang.module.Configuration; import java.lang.module.ModuleDescriptor; import java.lang.module.ModuleFinder; import java.util.HashMap; import java.util.Map; import java.util.Set; import myloaders.MyDiffClassLoader; // // ClassLoader1 --> defines m1x --> no packages // ClassLoader2 --> defines m2x --> packages p2 // // m1x can read m2x // package p2 in m2x is exported unqualifiedly. // // class p1.c1 defined in an unnamed module tries to access p2.c2 defined in m2x // Access allowed, an unnamed module can read all modules and p2 in module // m2x which is exported unqualifiedly. // public class UmodDiffCL_ExpUnqual { // Create a layer over the boot layer. // Define modules within this layer to test access between // publically defined classes within packages of those modules. public void createLayerOnBoot() throws Throwable { // Define module: m1x // Can read: java.base, m2x // Packages: none // Packages exported: none ModuleDescriptor descriptor_m1x = ModuleDescriptor.newModule("m1x") .requires("java.base") .requires("m2x") .build(); // Define module: m2x // Can read: java.base // Packages: p2 // Packages exported: none ModuleDescriptor descriptor_m2x = ModuleDescriptor.newModule("m2x") .requires("java.base") .exports("p2") .build(); // Set up a ModuleFinder containing all modules for this layer. ModuleFinder finder = ModuleLibrary.of(descriptor_m1x, descriptor_m2x); // Resolves "m1x" Configuration cf = ModuleLayer.boot() .configuration() .resolve(finder, ModuleFinder.of(), Set.of("m1x")); // map each module to differing class loaders for this test Map<String, ClassLoader> map = new HashMap<>(); map.put("m1x", MyDiffClassLoader.loader1); map.put("m2x", MyDiffClassLoader.loader2); // Create layer that contains m1x & m2x ModuleLayer layer = ModuleLayer.boot().defineModules(cf, map::get); assertTrue(layer.findLoader("m1x") == MyDiffClassLoader.loader1); assertTrue(layer.findLoader("m2x") == MyDiffClassLoader.loader2); assertTrue(layer.findLoader("java.base") == null); // NOTE: module m1x does not define a package named p1. // p1 will be loaded in an unnamed module. Class p1_c1_class = MyDiffClassLoader.loader1.loadClass("p1.c1"); try { p1_c1_class.newInstance(); } catch (IllegalAccessError e) { throw new RuntimeException("Test Failed, p1.c1 defined in unnamed module can access p2.c2 in module m2x"); } } public static void main(String args[]) throws Throwable { UmodDiffCL_ExpUnqual test = new UmodDiffCL_ExpUnqual(); test.createLayerOnBoot(); } }
YouDiSN/OpenJDK-Research
jdk9/hotspot/test/runtime/modules/AccessCheck/UmodDiffCL_ExpUnqual.java
Java
gpl-2.0
4,782
/* ScummVM - Graphic Adventure Engine * * ScummVM is the legal property of its developers, whose names * are too numerous to list here. Please refer to the COPYRIGHT * file distributed with this source distribution. * * 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 "lastexpress/entities/vassili.h" #include "lastexpress/entities/anna.h" #include "lastexpress/entities/coudert.h" #include "lastexpress/game/action.h" #include "lastexpress/game/entities.h" #include "lastexpress/game/inventory.h" #include "lastexpress/game/logic.h" #include "lastexpress/game/object.h" #include "lastexpress/game/savepoint.h" #include "lastexpress/game/scenes.h" #include "lastexpress/game/state.h" #include "lastexpress/sound/queue.h" #include "lastexpress/lastexpress.h" namespace LastExpress { Vassili::Vassili(LastExpressEngine *engine) : Entity(engine, kEntityVassili) { ADD_CALLBACK_FUNCTION(Vassili, reset); ADD_CALLBACK_FUNCTION(Vassili, draw); ADD_CALLBACK_FUNCTION(Vassili, savegame); ADD_CALLBACK_FUNCTION(Vassili, chapter1); ADD_CALLBACK_FUNCTION(Vassili, chapter1Handler); ADD_CALLBACK_FUNCTION(Vassili, function6); ADD_CALLBACK_FUNCTION(Vassili, function7); ADD_CALLBACK_FUNCTION(Vassili, function8); ADD_CALLBACK_FUNCTION(Vassili, function9); ADD_CALLBACK_FUNCTION(Vassili, seizure); ADD_CALLBACK_FUNCTION(Vassili, drawInBed); ADD_CALLBACK_FUNCTION(Vassili, chapter2); ADD_CALLBACK_FUNCTION(Vassili, sleeping); ADD_CALLBACK_FUNCTION(Vassili, chapter3); ADD_CALLBACK_FUNCTION(Vassili, stealEgg); ADD_CALLBACK_FUNCTION(Vassili, chapter4); ADD_CALLBACK_FUNCTION(Vassili, chapter4Handler); ADD_CALLBACK_FUNCTION(Vassili, chapter5); } ////////////////////////////////////////////////////////////////////////// IMPLEMENT_FUNCTION(1, Vassili, reset) Entity::reset(savepoint); IMPLEMENT_FUNCTION_END ////////////////////////////////////////////////////////////////////////// IMPLEMENT_FUNCTION_S(2, Vassili, draw) Entity::draw(savepoint); IMPLEMENT_FUNCTION_END ////////////////////////////////////////////////////////////////////////// IMPLEMENT_FUNCTION_II(3, Vassili, savegame, SavegameType, uint32) Entity::savegame(savepoint); IMPLEMENT_FUNCTION_END ////////////////////////////////////////////////////////////////////////// IMPLEMENT_FUNCTION(4, Vassili, chapter1) switch (savepoint.action) { default: break; case kActionNone: Entity::timeCheck(kTimeChapter1, params->param1, WRAP_SETUP_FUNCTION(Vassili, setup_chapter1Handler)); break; case kActionDefault: getObjects()->update(kObjectCompartmentA, kEntityPlayer, kObjectLocationNone, kCursorHandKnock, kCursorHand); getObjects()->update(kObject40, kEntityPlayer, kObjectLocationNone, kCursorKeepValue, kCursorKeepValue); break; } IMPLEMENT_FUNCTION_END ////////////////////////////////////////////////////////////////////////// IMPLEMENT_FUNCTION(5, Vassili, chapter1Handler) switch (savepoint.action) { default: break; case kActionNone: if (params->param1) { getData()->entityPosition = getEntityData(kEntityTatiana)->entityPosition; getData()->location = getEntityData(kEntityTatiana)->location; } else { if (params->param3 && params->param3 >= getState()->time) { break; }else { params->param3 = (uint)getState()->time + 450; if (params->param3 == 0) break; } if (!params->param2 && getObjects()->get(kObjectCompartmentA).location == kObjectLocation1) { params->param2 = 1; getEntities()->drawSequenceLeft(kEntityVassili, "303A"); getObjects()->update(kObjectCompartmentA, kEntityPlayer, kObjectLocationNone, kCursorHandKnock, kCursorHand); } break; } break; case kActionDefault: params->param1 = 1; break; case kAction122732000: setup_function6(); break; case kAction168459827: params->param1 = 0; getObjects()->update(kObjectCompartmentA, kEntityPlayer, kObjectLocation1, kCursorHandKnock, kCursorHand); break; } IMPLEMENT_FUNCTION_END ////////////////////////////////////////////////////////////////////////// IMPLEMENT_FUNCTION(6, Vassili, function6) switch (savepoint.action) { default: break; case kActionNone: if (getEntities()->isInsideCompartment(kEntityPlayer, kCarRedSleeping, kPosition_8200)) { if (!Entity::updateParameter(params->param3, getState()->timeTicks, params->param1)) goto label_function7; setCallback(1); setup_draw("303B"); break; } params->param3 = 0; if (params->param2) getEntities()->drawSequenceLeft(kEntityVassili, "303A"); label_function7: if (params->param4 != kTimeInvalid && getState()->time > kTime1489500) { if (getState()->time <= kTime1503000) { if (getEntities()->isInsideCompartment(kEntityPlayer, kCarRedSleeping, kPosition_8200) || !params->param4) { params->param4 = (uint)getState()->time; if (!params->param4) { setup_function7(); break; } } if (params->param4 >= getState()->time) break; } params->param4 = kTimeInvalid; setup_function7(); } break; case kActionDefault: getData()->entityPosition = kPosition_8200; getData()->location = kLocationInsideCompartment; getData()->car = kCarRedSleeping; getObjects()->update(kObjectCompartmentA, kEntityPlayer, kObjectLocationNone, kCursorHandKnock, kCursorHand); params->param1 = 5 * (3 * rnd(25) + 15); getEntities()->drawSequenceLeft(kEntityVassili, "303A"); break; case kActionCallback: if (getCallback() == 1) { getEntities()->drawSequenceLeft(kEntityVassili, "303C"); params->param1 = 5 * (3 * rnd(25) + 15); params->param2 = 1; // Shared part with kActionNone goto label_function7; } break; } IMPLEMENT_FUNCTION_END ////////////////////////////////////////////////////////////////////////// IMPLEMENT_FUNCTION(7, Vassili, function7) switch (savepoint.action) { default: break; case kActionNone: if (params->param1 != kTimeInvalid && getState()->time > kTime1503000) { if (getState()->time <= kTime1512000) { if (getEntities()->isPlayerInCar(kCarRedSleeping) || !params->param1) { params->param1 = (uint)getState()->time + 150; if (params->param1) { setup_function8(); break; } } if (params->param1 >= getState()->time) break; } params->param1 = kTimeInvalid; setup_function8(); } break; case kActionDefault: getData()->entityPosition = kPosition_8200; getData()->location = kLocationInsideCompartment; getData()->car = kCarRedSleeping; getEntities()->clearSequences(kEntityVassili); if (getEntities()->isInsideCompartment(kEntityPlayer, kCarRedSleeping, kPosition_8200)) getScenes()->loadSceneFromObject(kObjectCompartmentA); getObjects()->update(kObjectCompartmentA, kEntityPlayer, kObjectLocation1, kCursorHandKnock, kCursorHand); break; case kAction339669520: setup_function9(); break; } IMPLEMENT_FUNCTION_END ////////////////////////////////////////////////////////////////////////// IMPLEMENT_FUNCTION(8, Vassili, function8) switch (savepoint.action) { default: break; case kActionEndSound: setup_function9(); break; case kActionDefault: if (!getEntities()->isInsideTrainCar(kEntityPlayer, kCarRedSleeping)) { getSound()->playSound(kEntityPlayer, "BUMP"); getScenes()->loadSceneFromPosition(kCarRedSleeping, (getEntityData(kEntityPlayer)->car <= kCarRedSleeping) ? 1 : 40); } getSavePoints()->push(kEntityVassili, kEntityAnna, kAction226031488); getSavePoints()->push(kEntityVassili, kEntityVerges, kAction226031488); getSavePoints()->push(kEntityVassili, kEntityCoudert, kAction226031488); getSound()->playSound(kEntityVassili, "VAS1027", kFlagDefault); break; } IMPLEMENT_FUNCTION_END ////////////////////////////////////////////////////////////////////////// IMPLEMENT_FUNCTION(9, Vassili, function9) switch (savepoint.action) { default: break; case kActionEndSound: if (!getEntities()->isDistanceBetweenEntities(kEntityVassili, kEntityPlayer, 2500)) getSound()->playSound(kEntityPlayer, "BUMP"); setup_seizure(); break; case kActionDefault: case kActionDrawScene: if ((getObjects()->get(kObjectCompartmentA).location == kObjectLocation2 && getEntities()->isPlayerPosition(kCarRedSleeping, 17)) || getEntities()->isPlayerPosition(kCarRedSleeping, 18) || getEntities()->isPlayerPosition(kCarRedSleeping, 37) || getEntities()->isPlayerPosition(kCarRedSleeping, 38) || getEntities()->isPlayerPosition(kCarRedSleeping, 41)) { if (savepoint.action == kActionDrawScene) getSoundQueue()->processEntry(kEntityVassili); setup_seizure(); } else { if (savepoint.action == kActionDefault) getSound()->playSound(kEntityVassili, "VAS1028", kFlagDefault); } break; } IMPLEMENT_FUNCTION_END ////////////////////////////////////////////////////////////////////////// IMPLEMENT_FUNCTION(10, Vassili, seizure) switch (savepoint.action) { default: break; case kActionDefault: // Check that we have removed the body from the train and changed jacket if (!getProgress().eventCorpseMovedFromFloor) { getAction()->playAnimation(kEventMertensCorpseFloor); getLogic()->gameOver(kSavegameTypeIndex, 0, kSceneNone, false); break; } if (!getProgress().eventCorpseThrown) { getAction()->playAnimation(kEventMertensCorpseBed); getLogic()->gameOver(kSavegameTypeIndex, 0, kSceneNone, false); break; } if (getProgress().jacket == kJacketBlood) { getAction()->playAnimation(kEventMertensBloodJacket); getLogic()->gameOver(kSavegameTypeIndex, 0, kSceneNone, false); break; } // Setup Anna & Coudert RESET_ENTITY_STATE(kEntityAnna, Anna, setup_function37); RESET_ENTITY_STATE(kEntityCoudert, Coudert, setup_function38); setCallback(1); setup_savegame(kSavegameTypeEvent, kEventVassiliSeizure); break; case kActionCallback: if (getCallback() != 1) break; getData()->location = kLocationInsideCompartment; getAction()->playAnimation(kEventVassiliSeizure); getObjects()->update(kObjectCompartmentA, kEntityPlayer, kObjectLocationNone, kCursorHandKnock, kCursorHand); getObjects()->update(kObjectCompartment1, kEntityPlayer, kObjectLocationNone, kCursorHandKnock, kCursorHand); getProgress().field_18 = 2; getSavePoints()->push(kEntityVassili, kEntityAnna, kAction191477936); getSavePoints()->push(kEntityVassili, kEntityVerges, kAction191477936); getSavePoints()->push(kEntityVassili, kEntityCoudert, kAction191477936); getScenes()->loadSceneFromObject(kObjectCompartmentA); setup_drawInBed(); break; } IMPLEMENT_FUNCTION_END ////////////////////////////////////////////////////////////////////////// IMPLEMENT_FUNCTION(11, Vassili, drawInBed) if (savepoint.action == kActionDefault) getEntities()->drawSequenceLeft(kEntityVassili, "303A"); IMPLEMENT_FUNCTION_END ////////////////////////////////////////////////////////////////////////// IMPLEMENT_FUNCTION(12, Vassili, chapter2) switch (savepoint.action) { default: break; case kActionNone: setup_sleeping(); break; case kActionDefault: getEntities()->clearSequences(kEntityVassili); getData()->entityPosition = kPosition_8200; getData()->location = kLocationInsideCompartment; getData()->car = kCarRedSleeping; getData()->clothes = kClothesDefault; getData()->inventoryItem = kItemNone; getObjects()->update(kObjectCompartmentA, kEntityPlayer, kObjectLocationNone, kCursorHandKnock, kCursorHand); getObjects()->updateLocation2(kObjectCompartmentA, kObjectLocation1); break; } IMPLEMENT_FUNCTION_END ////////////////////////////////////////////////////////////////////////// IMPLEMENT_FUNCTION(13, Vassili, sleeping) switch (savepoint.action) { default: break; case kActionNone: if (getEntities()->isInsideCompartment(kEntityPlayer, kCarRedSleeping, kPosition_8200)) { if (!Entity::updateParameter(params->param3, getState()->timeTicks, params->param1)) break; setCallback(1); setup_draw("303B"); } else { params->param3 = 0; if (params->param2) getEntities()->drawSequenceLeft(kEntityVassili, "303A"); } break; case kActionDefault: params->param5 = 5 * (3 * rnd(25) + 15); getEntities()->drawSequenceLeft(kEntityVassili, "303A"); break; case kActionCallback: if (getCallback() != 1) break; getEntities()->drawSequenceLeft(kEntityVassili, "303C"); params->param1 = 5 * (3 * rnd(25) + 15); params->param2 = 1; break; } IMPLEMENT_FUNCTION_END ////////////////////////////////////////////////////////////////////////// IMPLEMENT_FUNCTION(14, Vassili, chapter3) switch (savepoint.action) { default: break; case kActionNone: setup_stealEgg(); break; case kActionDefault: getEntities()->clearSequences(kEntityVassili); getData()->entityPosition = kPosition_8200; getData()->location = kLocationInsideCompartment; getData()->car = kCarRedSleeping; getData()->clothes = kClothesDefault; getData()->inventoryItem = kItemNone; getObjects()->update(kObjectCompartmentA, kEntityPlayer, kObjectLocationNone, kCursorHandKnock, kCursorHand); break; } IMPLEMENT_FUNCTION_END ////////////////////////////////////////////////////////////////////////// IMPLEMENT_FUNCTION(15, Vassili, stealEgg) switch (savepoint.action) { default: break; case kActionNone: if (getEntities()->isInsideCompartment(kEntityPlayer, kCarRedSleeping, kPosition_8200)) { if (!Entity::updateParameter(params->param3, getState()->timeTicks, params->param1)) break; setCallback(1); setup_draw("303B"); } else { params->param3 = 0; if (params->param2) getEntities()->drawSequenceLeft(kEntityVassili, "303A"); } break; case kActionOpenDoor: setCallback(2); setup_savegame(kSavegameTypeEvent, kEventVassiliCompartmentStealEgg); break; case kActionDefault: params->param5 = 5 * (3 * rnd(25) + 15); getEntities()->drawSequenceLeft(kEntityVassili, "303A"); break; case kActionDrawScene: if (getEntities()->isInsideCompartment(kEntityPlayer, kCarRedSleeping, kPosition_7850) && getInventory()->hasItem(kItemFirebird) && !getEvent(kEventVassiliCompartmentStealEgg)) getObjects()->update(kObject48, kEntityVassili, kObjectLocationNone, kCursorNormal, kCursorHand); else getObjects()->update(kObject48, kEntityPlayer, kObjectLocationNone, kCursorNormal, kCursorHand); break; case kActionCallback: switch (getCallback()) { default: break; case 1: getEntities()->drawSequenceLeft(kEntityVassili, "303C"); params->param1 = 5 * (3 * rnd(25) + 15); params->param2 = 1; break; case 2: getAction()->playAnimation(kEventVassiliCompartmentStealEgg); getScenes()->loadSceneFromPosition(kCarRedSleeping, 67); break; } break; } IMPLEMENT_FUNCTION_END ////////////////////////////////////////////////////////////////////////// IMPLEMENT_FUNCTION(16, Vassili, chapter4) switch (savepoint.action) { default: break; case kActionNone: setup_chapter4Handler(); break; case kActionDefault: getEntities()->clearSequences(kEntityVassili); getData()->entityPosition = kPosition_8200; getData()->location = kLocationInsideCompartment; getData()->car = kCarRedSleeping; getData()->clothes = kClothesDefault; getData()->inventoryItem = kItemNone; getObjects()->update(kObjectCompartmentA, kEntityPlayer, kObjectLocationNone, kCursorHandKnock, kCursorHand); getObjects()->updateLocation2(kObjectCompartmentA, kObjectLocation1); break; } IMPLEMENT_FUNCTION_END ////////////////////////////////////////////////////////////////////////// // Looks identical to sleeping (#13) IMPLEMENT_FUNCTION(17, Vassili, chapter4Handler) switch (savepoint.action) { default: break; case kActionNone: if (getEntities()->isInsideCompartment(kEntityPlayer, kCarRedSleeping, kPosition_8200)) { if (!Entity::updateParameter(params->param3, getState()->timeTicks, params->param1)) break; setCallback(1); setup_draw("303B"); } else { params->param3 = 0; if (params->param2) getEntities()->drawSequenceLeft(kEntityVassili, "303A"); } break; case kActionDefault: params->param5 = 5 * (3 * rnd(25) + 15); getEntities()->drawSequenceLeft(kEntityVassili, "303A"); break; case kActionCallback: if (getCallback() != 1) break; getEntities()->drawSequenceLeft(kEntityVassili, "303C"); params->param1 = 5 * (3 * rnd(25) + 15); params->param2 = 1; break; } IMPLEMENT_FUNCTION_END ////////////////////////////////////////////////////////////////////////// IMPLEMENT_FUNCTION(18, Vassili, chapter5) if (savepoint.action == kActionDefault) { getEntities()->clearSequences(kEntityVassili); getData()->entityPosition = kPosition_3969; getData()->location = kLocationInsideCompartment; getData()->car = kCarRestaurant; getData()->clothes = kClothesDefault; getData()->inventoryItem = kItemNone; } IMPLEMENT_FUNCTION_END } // End of namespace LastExpress
joeriedel/scummvm
engines/lastexpress/entities/vassili.cpp
C++
gpl-2.0
17,547
obj-$(CONFIG_EXYNOS_MEDIA_MONITOR) += media_monitor.o
nian0114/CherryS.AOSP-smdk4412
drivers/media/video/samsung/media_monitor/Makefile
Makefile
gpl-2.0
62
/* * This module exposes the interface to kernel space for specifying * QoS dependencies. It provides infrastructure for registration of: * * Dependents on a QoS value : register requests * Watchers of QoS value : get notified when target QoS value changes * * This QoS design is best effort based. Dependents register their QoS needs. * Watchers register to keep track of the current QoS needs of the system. * * There are 3 basic classes of QoS parameter: latency, timeout, throughput * each have defined units: * latency: usec * timeout: usec <-- currently not used. * throughput: kbs (kilo byte / sec) * * There are lists of pm_qos_objects each one wrapping requests, notifiers * * User mode requests on a QOS parameter register themselves to the * subsystem by opening the device node /dev/... and writing there request to * the node. As long as the process holds a file handle open to the node the * client continues to be accounted for. Upon file release the usermode * request is removed and a new qos target is computed. This way when the * request that the application has is cleaned up when closes the file * pointer or exits the pm_qos_object will get an opportunity to clean up. * * Mark Gross <[email protected]> */ /*#define DEBUG*/ #include <linux/pm_qos.h> #include <linux/sched.h> #include <linux/spinlock.h> #include <linux/slab.h> #include <linux/time.h> #include <linux/fs.h> #include <linux/device.h> #include <linux/miscdevice.h> #include <linux/string.h> #include <linux/platform_device.h> #include <linux/init.h> #include <linux/kernel.h> #include <linux/irq.h> #include <linux/irqdesc.h> #include <linux/uaccess.h> #include <linux/export.h> /* * locking rule: all changes to constraints or notifiers lists * or pm_qos_object list and pm_qos_objects need to happen with pm_qos_lock * held, taken with _irqsave. One lock to rule them all */ struct pm_qos_object { struct pm_qos_constraints *constraints; struct miscdevice pm_qos_power_miscdev; char *name; }; static DEFINE_SPINLOCK(pm_qos_lock); static struct pm_qos_object null_pm_qos; static BLOCKING_NOTIFIER_HEAD(cpu_dma_lat_notifier); static struct pm_qos_constraints cpu_dma_constraints = { .list = PLIST_HEAD_INIT(cpu_dma_constraints.list), .target_value = PM_QOS_CPU_DMA_LAT_DEFAULT_VALUE, .target_per_cpu = { [0 ... (NR_CPUS - 1)] = PM_QOS_CPU_DMA_LAT_DEFAULT_VALUE }, .default_value = PM_QOS_CPU_DMA_LAT_DEFAULT_VALUE, .type = PM_QOS_MIN, .notifiers = &cpu_dma_lat_notifier, }; static struct pm_qos_object cpu_dma_pm_qos = { .constraints = &cpu_dma_constraints, .name = "cpu_dma_latency", }; static BLOCKING_NOTIFIER_HEAD(network_lat_notifier); static struct pm_qos_constraints network_lat_constraints = { .list = PLIST_HEAD_INIT(network_lat_constraints.list), .target_value = PM_QOS_NETWORK_LAT_DEFAULT_VALUE, .target_per_cpu = { [0 ... (NR_CPUS - 1)] = PM_QOS_NETWORK_LAT_DEFAULT_VALUE }, .default_value = PM_QOS_NETWORK_LAT_DEFAULT_VALUE, .type = PM_QOS_MIN, .notifiers = &network_lat_notifier, }; static struct pm_qos_object network_lat_pm_qos = { .constraints = &network_lat_constraints, .name = "network_latency", }; static BLOCKING_NOTIFIER_HEAD(network_throughput_notifier); static struct pm_qos_constraints network_tput_constraints = { .list = PLIST_HEAD_INIT(network_tput_constraints.list), .target_value = PM_QOS_NETWORK_THROUGHPUT_DEFAULT_VALUE, .target_per_cpu = { [0 ... (NR_CPUS - 1)] = PM_QOS_NETWORK_THROUGHPUT_DEFAULT_VALUE }, .default_value = PM_QOS_NETWORK_THROUGHPUT_DEFAULT_VALUE, .type = PM_QOS_MAX, .notifiers = &network_throughput_notifier, }; static struct pm_qos_object network_throughput_pm_qos = { .constraints = &network_tput_constraints, .name = "network_throughput", }; static struct pm_qos_object *pm_qos_array[] = { &null_pm_qos, &cpu_dma_pm_qos, &network_lat_pm_qos, &network_throughput_pm_qos }; static ssize_t pm_qos_power_write(struct file *filp, const char __user *buf, size_t count, loff_t *f_pos); static ssize_t pm_qos_power_read(struct file *filp, char __user *buf, size_t count, loff_t *f_pos); static int pm_qos_power_open(struct inode *inode, struct file *filp); static int pm_qos_power_release(struct inode *inode, struct file *filp); static const struct file_operations pm_qos_power_fops = { .write = pm_qos_power_write, .read = pm_qos_power_read, .open = pm_qos_power_open, .release = pm_qos_power_release, .llseek = noop_llseek, }; /* unlocked internal variant */ static inline int pm_qos_get_value(struct pm_qos_constraints *c) { if (plist_head_empty(&c->list)) return c->default_value; switch (c->type) { case PM_QOS_MIN: return plist_first(&c->list)->prio; case PM_QOS_MAX: return plist_last(&c->list)->prio; default: /* runtime check for not using enum */ BUG(); return PM_QOS_DEFAULT_VALUE; } } s32 pm_qos_read_value(struct pm_qos_constraints *c) { return c->target_value; } static inline void pm_qos_set_value(struct pm_qos_constraints *c, s32 value) { c->target_value = value; } static inline void pm_qos_set_value_for_cpus(struct pm_qos_constraints *c, struct cpumask *cpus) { struct pm_qos_request *req = NULL; int cpu; s32 qos_val[NR_CPUS] = { [0 ... (NR_CPUS - 1)] = c->default_value }; plist_for_each_entry(req, &c->list, node) { for_each_cpu(cpu, &req->cpus_affine) { switch (c->type) { case PM_QOS_MIN: if (qos_val[cpu] > req->node.prio) qos_val[cpu] = req->node.prio; break; case PM_QOS_MAX: if (req->node.prio > qos_val[cpu]) qos_val[cpu] = req->node.prio; break; default: BUG(); break; } } } for_each_possible_cpu(cpu) { if (c->target_per_cpu[cpu] != qos_val[cpu]) cpumask_set_cpu(cpu, cpus); c->target_per_cpu[cpu] = qos_val[cpu]; } } /** * pm_qos_update_target - manages the constraints list and calls the notifiers * if needed * @c: constraints data struct * @node: request to add to the list, to update or to remove * @action: action to take on the constraints list * @value: value of the request to add or update * * This function returns 1 if the aggregated constraint value has changed, 0 * otherwise. */ int pm_qos_update_target(struct pm_qos_constraints *c, struct plist_node *node, enum pm_qos_req_action action, int value) { unsigned long flags; int prev_value, curr_value, new_value; struct cpumask cpus; spin_lock_irqsave(&pm_qos_lock, flags); prev_value = pm_qos_get_value(c); if (value == PM_QOS_DEFAULT_VALUE) new_value = c->default_value; else new_value = value; switch (action) { case PM_QOS_REMOVE_REQ: plist_del(node, &c->list); break; case PM_QOS_UPDATE_REQ: /* * to change the list, we atomically remove, reinit * with new value and add, then see if the extremal * changed */ plist_del(node, &c->list); case PM_QOS_ADD_REQ: plist_node_init(node, new_value); plist_add(node, &c->list); break; default: /* no action */ ; } curr_value = pm_qos_get_value(c); cpumask_clear(&cpus); pm_qos_set_value(c, curr_value); pm_qos_set_value_for_cpus(c, &cpus); spin_unlock_irqrestore(&pm_qos_lock, flags); if (prev_value != curr_value) { blocking_notifier_call_chain(c->notifiers, (unsigned long)curr_value, &cpus); return 1; } else { return 0; } } /** * pm_qos_flags_remove_req - Remove device PM QoS flags request. * @pqf: Device PM QoS flags set to remove the request from. * @req: Request to remove from the set. */ static void pm_qos_flags_remove_req(struct pm_qos_flags *pqf, struct pm_qos_flags_request *req) { s32 val = 0; list_del(&req->node); list_for_each_entry(req, &pqf->list, node) val |= req->flags; pqf->effective_flags = val; } /** * pm_qos_update_flags - Update a set of PM QoS flags. * @pqf: Set of flags to update. * @req: Request to add to the set, to modify, or to remove from the set. * @action: Action to take on the set. * @val: Value of the request to add or modify. * * Update the given set of PM QoS flags and call notifiers if the aggregate * value has changed. Returns 1 if the aggregate constraint value has changed, * 0 otherwise. */ bool pm_qos_update_flags(struct pm_qos_flags *pqf, struct pm_qos_flags_request *req, enum pm_qos_req_action action, s32 val) { unsigned long irqflags; s32 prev_value, curr_value; spin_lock_irqsave(&pm_qos_lock, irqflags); prev_value = list_empty(&pqf->list) ? 0 : pqf->effective_flags; switch (action) { case PM_QOS_REMOVE_REQ: pm_qos_flags_remove_req(pqf, req); break; case PM_QOS_UPDATE_REQ: pm_qos_flags_remove_req(pqf, req); case PM_QOS_ADD_REQ: req->flags = val; INIT_LIST_HEAD(&req->node); list_add_tail(&req->node, &pqf->list); pqf->effective_flags |= val; break; default: /* no action */ ; } curr_value = list_empty(&pqf->list) ? 0 : pqf->effective_flags; spin_unlock_irqrestore(&pm_qos_lock, irqflags); return prev_value != curr_value; } /** * pm_qos_request - returns current system wide qos expectation * @pm_qos_class: identification of which qos value is requested * * This function returns the current target value. */ int pm_qos_request(int pm_qos_class) { return pm_qos_read_value(pm_qos_array[pm_qos_class]->constraints); } EXPORT_SYMBOL_GPL(pm_qos_request); int pm_qos_request_for_cpu(int pm_qos_class, int cpu) { return pm_qos_array[pm_qos_class]->constraints->target_per_cpu[cpu]; } EXPORT_SYMBOL(pm_qos_request_for_cpu); int pm_qos_request_active(struct pm_qos_request *req) { return req->pm_qos_class != 0; } EXPORT_SYMBOL_GPL(pm_qos_request_active); int pm_qos_request_for_cpumask(int pm_qos_class, struct cpumask *mask) { unsigned long irqflags; int cpu; struct pm_qos_constraints *c = NULL; int val; spin_lock_irqsave(&pm_qos_lock, irqflags); c = pm_qos_array[pm_qos_class]->constraints; val = c->default_value; for_each_cpu(cpu, mask) { switch (c->type) { case PM_QOS_MIN: if (c->target_per_cpu[cpu] < val) val = c->target_per_cpu[cpu]; break; case PM_QOS_MAX: if (c->target_per_cpu[cpu] > val) val = c->target_per_cpu[cpu]; break; default: BUG(); break; } } spin_unlock_irqrestore(&pm_qos_lock, irqflags); return val; } EXPORT_SYMBOL(pm_qos_request_for_cpumask); static void __pm_qos_update_request(struct pm_qos_request *req, s32 new_value) { if (new_value != req->node.prio) pm_qos_update_target( pm_qos_array[req->pm_qos_class]->constraints, &req->node, PM_QOS_UPDATE_REQ, new_value); } /** * pm_qos_work_fn - the timeout handler of pm_qos_update_request_timeout * @work: work struct for the delayed work (timeout) * * This cancels the timeout request by falling back to the default at timeout. */ static void pm_qos_work_fn(struct work_struct *work) { struct pm_qos_request *req = container_of(to_delayed_work(work), struct pm_qos_request, work); if (!req || !pm_qos_request_active(req)) return; __pm_qos_update_request(req, PM_QOS_DEFAULT_VALUE); } #ifdef CONFIG_SMP static void pm_qos_irq_release(struct kref *ref) { unsigned long flags; struct irq_affinity_notify *notify = container_of(ref, struct irq_affinity_notify, kref); struct pm_qos_request *req = container_of(notify, struct pm_qos_request, irq_notify); struct pm_qos_constraints *c = pm_qos_array[req->pm_qos_class]->constraints; spin_lock_irqsave(&pm_qos_lock, flags); cpumask_setall(&req->cpus_affine); spin_unlock_irqrestore(&pm_qos_lock, flags); pm_qos_update_target(c, &req->node, PM_QOS_UPDATE_REQ, c->default_value); } static void pm_qos_irq_notify(struct irq_affinity_notify *notify, const cpumask_t *mask) { unsigned long flags; struct pm_qos_request *req = container_of(notify, struct pm_qos_request, irq_notify); struct pm_qos_constraints *c = pm_qos_array[req->pm_qos_class]->constraints; spin_lock_irqsave(&pm_qos_lock, flags); cpumask_copy(&req->cpus_affine, mask); spin_unlock_irqrestore(&pm_qos_lock, flags); pm_qos_update_target(c, &req->node, PM_QOS_UPDATE_REQ, req->node.prio); } #endif /** * pm_qos_add_request - inserts new qos request into the list * @req: pointer to a preallocated handle * @pm_qos_class: identifies which list of qos request to use * @value: defines the qos request * * This function inserts a new entry in the pm_qos_class list of requested qos * performance characteristics. It recomputes the aggregate QoS expectations * for the pm_qos_class of parameters and initializes the pm_qos_request * handle. Caller needs to save this handle for later use in updates and * removal. */ void pm_qos_add_request(struct pm_qos_request *req, int pm_qos_class, s32 value) { if (!req) /*guard against callers passing in null */ return; if (pm_qos_request_active(req)) { WARN(1, KERN_ERR "pm_qos_add_request() called for already added request\n"); return; } switch (req->type) { case PM_QOS_REQ_AFFINE_CORES: if (cpumask_empty(&req->cpus_affine)) { req->type = PM_QOS_REQ_ALL_CORES; cpumask_setall(&req->cpus_affine); WARN(1, KERN_ERR "Affine cores not set for request with affinity flag\n"); } break; #ifdef CONFIG_SMP case PM_QOS_REQ_AFFINE_IRQ: if (irq_can_set_affinity(req->irq)) { int ret = 0; struct irq_desc *desc = irq_to_desc(req->irq); struct cpumask *mask = desc->irq_data.affinity; /* Get the current affinity */ cpumask_copy(&req->cpus_affine, mask); req->irq_notify.irq = req->irq; req->irq_notify.notify = pm_qos_irq_notify; req->irq_notify.release = pm_qos_irq_release; ret = irq_set_affinity_notifier(req->irq, &req->irq_notify); if (ret) { WARN(1, KERN_ERR "IRQ affinity notify set failed\n"); req->type = PM_QOS_REQ_ALL_CORES; cpumask_setall(&req->cpus_affine); } } else { req->type = PM_QOS_REQ_ALL_CORES; cpumask_setall(&req->cpus_affine); WARN(1, KERN_ERR "IRQ-%d not set for request with affinity flag\n", req->irq); } break; #endif default: WARN(1, KERN_ERR "Unknown request type %d\n", req->type); /* fall through */ case PM_QOS_REQ_ALL_CORES: cpumask_setall(&req->cpus_affine); break; } req->pm_qos_class = pm_qos_class; INIT_DELAYED_WORK(&req->work, pm_qos_work_fn); pm_qos_update_target(pm_qos_array[pm_qos_class]->constraints, &req->node, PM_QOS_ADD_REQ, value); } EXPORT_SYMBOL_GPL(pm_qos_add_request); /** * pm_qos_update_request - modifies an existing qos request * @req : handle to list element holding a pm_qos request to use * @value: defines the qos request * * Updates an existing qos request for the pm_qos_class of parameters along * with updating the target pm_qos_class value. * * Attempts are made to make this code callable on hot code paths. */ void pm_qos_update_request(struct pm_qos_request *req, s32 new_value) { if (!req) /*guard against callers passing in null */ return; if (!pm_qos_request_active(req)) { WARN(1, KERN_ERR "pm_qos_update_request() called for unknown object\n"); return; } cancel_delayed_work_sync(&req->work); __pm_qos_update_request(req, new_value); } EXPORT_SYMBOL_GPL(pm_qos_update_request); /** * pm_qos_update_request_timeout - modifies an existing qos request temporarily. * @req : handle to list element holding a pm_qos request to use * @new_value: defines the temporal qos request * @timeout_us: the effective duration of this qos request in usecs. * * After timeout_us, this qos request is cancelled automatically. */ void pm_qos_update_request_timeout(struct pm_qos_request *req, s32 new_value, unsigned long timeout_us) { if (!req) return; if (WARN(!pm_qos_request_active(req), "%s called for unknown object.", __func__)) return; cancel_delayed_work_sync(&req->work); if (new_value != req->node.prio) pm_qos_update_target( pm_qos_array[req->pm_qos_class]->constraints, &req->node, PM_QOS_UPDATE_REQ, new_value); schedule_delayed_work(&req->work, usecs_to_jiffies(timeout_us)); } /** * pm_qos_remove_request - modifies an existing qos request * @req: handle to request list element * * Will remove pm qos request from the list of constraints and * recompute the current target value for the pm_qos_class. Call this * on slow code paths. */ void pm_qos_remove_request(struct pm_qos_request *req) { if (!req) /*guard against callers passing in null */ return; /* silent return to keep pcm code cleaner */ if (!pm_qos_request_active(req)) { WARN(1, KERN_ERR "pm_qos_remove_request() called for unknown object\n"); return; } cancel_delayed_work_sync(&req->work); #ifdef CONFIG_SMP if (req->type == PM_QOS_REQ_AFFINE_IRQ) { int ret = 0; /* Get the current affinity */ ret = irq_release_affinity_notifier(&req->irq_notify); if (ret) WARN(1, "IRQ affinity notify set failed\n"); } #endif pm_qos_update_target(pm_qos_array[req->pm_qos_class]->constraints, &req->node, PM_QOS_REMOVE_REQ, PM_QOS_DEFAULT_VALUE); memset(req, 0, sizeof(*req)); } EXPORT_SYMBOL_GPL(pm_qos_remove_request); /** * pm_qos_add_notifier - sets notification entry for changes to target value * @pm_qos_class: identifies which qos target changes should be notified. * @notifier: notifier block managed by caller. * * will register the notifier into a notification chain that gets called * upon changes to the pm_qos_class target value. */ int pm_qos_add_notifier(int pm_qos_class, struct notifier_block *notifier) { int retval; retval = blocking_notifier_chain_register( pm_qos_array[pm_qos_class]->constraints->notifiers, notifier); return retval; } EXPORT_SYMBOL_GPL(pm_qos_add_notifier); /** * pm_qos_remove_notifier - deletes notification entry from chain. * @pm_qos_class: identifies which qos target changes are notified. * @notifier: notifier block to be removed. * * will remove the notifier from the notification chain that gets called * upon changes to the pm_qos_class target value. */ int pm_qos_remove_notifier(int pm_qos_class, struct notifier_block *notifier) { int retval; retval = blocking_notifier_chain_unregister( pm_qos_array[pm_qos_class]->constraints->notifiers, notifier); return retval; } EXPORT_SYMBOL_GPL(pm_qos_remove_notifier); /* User space interface to PM QoS classes via misc devices */ static int register_pm_qos_misc(struct pm_qos_object *qos) { qos->pm_qos_power_miscdev.minor = MISC_DYNAMIC_MINOR; qos->pm_qos_power_miscdev.name = qos->name; qos->pm_qos_power_miscdev.fops = &pm_qos_power_fops; return misc_register(&qos->pm_qos_power_miscdev); } static int find_pm_qos_object_by_minor(int minor) { int pm_qos_class; for (pm_qos_class = 0; pm_qos_class < PM_QOS_NUM_CLASSES; pm_qos_class++) { if (minor == pm_qos_array[pm_qos_class]->pm_qos_power_miscdev.minor) return pm_qos_class; } return -1; } static int pm_qos_power_open(struct inode *inode, struct file *filp) { long pm_qos_class; pm_qos_class = find_pm_qos_object_by_minor(iminor(inode)); if (pm_qos_class >= 0) { struct pm_qos_request *req = kzalloc(sizeof(*req), GFP_KERNEL); if (!req) return -ENOMEM; pm_qos_add_request(req, pm_qos_class, PM_QOS_DEFAULT_VALUE); filp->private_data = req; return 0; } return -EPERM; } static int pm_qos_power_release(struct inode *inode, struct file *filp) { struct pm_qos_request *req; req = filp->private_data; pm_qos_remove_request(req); kfree(req); return 0; } static ssize_t pm_qos_power_read(struct file *filp, char __user *buf, size_t count, loff_t *f_pos) { s32 value; unsigned long flags; struct pm_qos_request *req = filp->private_data; if (!req) return -EINVAL; if (!pm_qos_request_active(req)) return -EINVAL; spin_lock_irqsave(&pm_qos_lock, flags); value = pm_qos_get_value(pm_qos_array[req->pm_qos_class]->constraints); spin_unlock_irqrestore(&pm_qos_lock, flags); return simple_read_from_buffer(buf, count, f_pos, &value, sizeof(s32)); } static ssize_t pm_qos_power_write(struct file *filp, const char __user *buf, size_t count, loff_t *f_pos) { s32 value; struct pm_qos_request *req; if (count == sizeof(s32)) { if (copy_from_user(&value, buf, sizeof(s32))) return -EFAULT; } else if (count <= 11) { /* ASCII perhaps? */ char ascii_value[11]; unsigned long int ulval; int ret; if (copy_from_user(ascii_value, buf, count)) return -EFAULT; if (count > 10) { if (ascii_value[10] == '\n') ascii_value[10] = '\0'; else return -EINVAL; } else { ascii_value[count] = '\0'; } ret = kstrtoul(ascii_value, 16, &ulval); if (ret) { pr_debug("%s, 0x%lx, 0x%x\n", ascii_value, ulval, ret); return -EINVAL; } value = (s32)lower_32_bits(ulval); } else { return -EINVAL; } req = filp->private_data; pm_qos_update_request(req, value); return count; } static int __init pm_qos_power_init(void) { int ret = 0; int i; BUILD_BUG_ON(ARRAY_SIZE(pm_qos_array) != PM_QOS_NUM_CLASSES); for (i = 1; i < PM_QOS_NUM_CLASSES; i++) { ret = register_pm_qos_misc(pm_qos_array[i]); if (ret < 0) { printk(KERN_ERR "pm_qos_param: %s setup failed\n", pm_qos_array[i]->name); return ret; } } return ret; } late_initcall(pm_qos_power_init);
rwaterspf1/android_kernel_lge_hammerheadcaf
kernel/power/qos.c
C
gpl-2.0
21,159
<?php namespace Drupal\Tests\webform\Kernel\Entity; use Drupal\Core\Serialization\Yaml; use Drupal\KernelTests\KernelTestBase; use Drupal\webform\Entity\Webform; use Drupal\webform\WebformInterface; /** * Tests the webform entity class. * * @group webform * @see \Drupal\webform\Entity\Webform */ class WebformEntityTest extends KernelTestBase { /** * Modules to enable. * * @var array */ public static $modules = ['system', 'path', 'webform', 'user', 'field']; /** * Tests some of the methods. */ public function testWebformMethods() { $this->installSchema('webform', ['webform']); $this->installConfig('webform'); /**************************************************************************/ // Create. /**************************************************************************/ // Create webform. /** @var \Drupal\webform\WebformInterface $webform */ $webform = Webform::create(['id' => 'webform_test']); $webform->save(); $this->assertEquals('webform_test', $webform->id()); $this->assertFalse($webform->isTemplate()); $this->assertTrue($webform->isOpen()); /**************************************************************************/ // Status. /**************************************************************************/ // Check set status to FALSE. $webform->setStatus(FALSE); $this->assertFalse($webform->isOpen()); $this->assertEquals($webform->get('status'), WebformInterface::STATUS_CLOSED); $this->assertFalse($webform->isScheduled()); // Check set status to TRUE. $webform->setStatus(TRUE); $this->assertTrue($webform->isOpen()); $this->assertEquals($webform->get('status'), WebformInterface::STATUS_OPEN); // Check set status to NULL. $webform->setStatus(NULL); $this->assertTrue($webform->isOpen()); $this->assertEquals($webform->get('status'), WebformInterface::STATUS_SCHEDULED); // Check set status to WebformInterface::STATUS_CLOSED. $webform->setStatus(WebformInterface::STATUS_CLOSED); $this->assertFalse($webform->isOpen()); // Check set status to WebformInterface::STATUS_OPEN. $webform->setStatus(WebformInterface::STATUS_OPEN); $this->assertTrue($webform->isOpen()); // Check set status to WebformInterface::STATUS_SCHEDULED. $webform->setStatus(WebformInterface::STATUS_SCHEDULED); $this->assertTrue($webform->isOpen()); $this->assertTrue($webform->isScheduled()); /**************************************************************************/ // Scheduled. /**************************************************************************/ $webform->setStatus(WebformInterface::STATUS_SCHEDULED); // Check set open date to yesterday. $webform->set('open', date('Y-m-d\TH:i:s', strtotime('today -1 days'))); $webform->set('close', NULL); $this->assertTrue($webform->isOpen()); // Check set open date to tomorrow. $webform->set('open', date('Y-m-d\TH:i:s', strtotime('today +1 day'))); $webform->set('close', NULL); $this->assertFalse($webform->isOpen()); // Check set close date to yesterday. $webform->set('open', NULL); $webform->set('close', date('Y-m-d\TH:i:s', strtotime('today -1 day'))); $this->assertFalse($webform->isOpen()); // Check set close date to tomorrow. $webform->set('open', NULL); $webform->set('close', date('Y-m-d\TH:i:s', strtotime('today +1 day'))); $this->assertTrue($webform->isOpen()); // Check set open date to tomorrow with close date in 10 days. $webform->set('open', date('Y-m-d\TH:i:s', strtotime('today +1 day'))); $webform->set('close', date('Y-m-d\TH:i:s', strtotime('today +10 days'))); $this->assertFalse($webform->isOpen()); $this->assertTrue($webform->isOpening()); // Check set open date to yesterday with close date in +10 days. $webform->set('open', date('Y-m-d\TH:i:s', strtotime('today -1 day'))); $webform->set('close', date('Y-m-d\TH:i:s', strtotime('today +10 days'))); $this->assertTrue($webform->isOpen()); // Check set open date to yesterday with close date -10 days. $webform->set('open', date('Y-m-d\TH:i:s', strtotime('today -1 day'))); $webform->set('close', date('Y-m-d\TH:i:s', strtotime('today -10 days'))); $this->assertFalse($webform->isOpen()); $this->assertFalse($webform->isOpening()); // Check that open overrides scheduled. $webform->setStatus(TRUE); $webform->set('open', date('Y-m-d\TH:i:s', strtotime('today -1 day'))); $webform->set('close', date('Y-m-d\TH:i:s', strtotime('today -10 days'))); $this->assertTrue($webform->isOpen()); // Check that closed overrides scheduled. $webform->setStatus(FALSE); $webform->set('open', date('Y-m-d\TH:i:s', strtotime('today +1 day'))); $webform->set('close', date('Y-m-d\TH:i:s', strtotime('today -10 days'))); $this->assertFalse($webform->isOpen()); // Check that open and close date is set to NULL when status is set to open // or closed. $webform->set('open', date('Y-m-d\TH:i:s', strtotime('today +1 day'))); $webform->set('close', date('Y-m-d\TH:i:s', strtotime('today -10 days'))); $this->assertNotNull($webform->get('open')); $this->assertNotNull($webform->get('close')); $webform->setStatus(TRUE); $this->assertNull($webform->get('open')); $this->assertNull($webform->get('close')); /**************************************************************************/ // Templates. /**************************************************************************/ // Check that templates are always closed. $webform->set('template', TRUE)->save(); $this->assertTrue($webform->isTemplate()); $this->assertFalse($webform->isOpen()); /**************************************************************************/ // Elements. /**************************************************************************/ // Set elements. $elements = [ 'root' => [ '#type' => 'textfield', '#title' => 'root', ], 'container' => [ '#type' => 'container', '#title' => 'container', 'child' => [ '#type' => 'textfield', '#title' => 'child', ], ], ]; $webform->setElements($elements); // Check that elements are serialized to YAML. $this->assertTrue($webform->getElementsRaw(), Yaml::encode($elements)); // Check elements decoded and flattened. $flattened_elements = [ 'root' => [ '#type' => 'textfield', '#title' => 'root', ], 'container' => [ '#type' => 'container', '#title' => 'container', ], 'child' => [ '#type' => 'textfield', '#title' => 'child', ], ]; $this->assertEquals($webform->getElementsDecodedAndFlattened(), $flattened_elements); // Check elements initialized and flattened. $elements_initialized_and_flattened = [ 'root' => [ '#type' => 'textfield', '#title' => 'root', '#webform_id' => 'webform_test--root', '#webform_key' => 'root', '#webform_parent_key' => '', '#webform_parent_flexbox' => FALSE, '#webform_depth' => 0, '#webform_children' => [], '#webform_multiple' => FALSE, '#webform_composite' => FALSE, '#webform_parents' => ['root'], '#admin_title' => 'root', ], 'container' => [ '#type' => 'container', '#title' => 'container', '#webform_id' => 'webform_test--container', '#webform_key' => 'container', '#webform_parent_key' => '', '#webform_parent_flexbox' => FALSE, '#webform_depth' => 0, '#webform_children' => [], '#webform_multiple' => FALSE, '#webform_composite' => FALSE, '#webform_parents' => ['container'], '#admin_title' => 'container', ], 'child' => [ '#type' => 'textfield', '#title' => 'child', '#webform_id' => 'webform_test--child', '#webform_key' => 'child', '#webform_parent_key' => 'container', '#webform_parent_flexbox' => FALSE, '#webform_depth' => 1, '#webform_children' => [], '#webform_multiple' => FALSE, '#webform_composite' => FALSE, '#webform_parents' => ['container', 'child'], '#admin_title' => 'child', ], ]; $this->assertEquals($webform->getElementsInitializedAndFlattened(), $elements_initialized_and_flattened); // Check elements flattened has value. $elements_initialized_flattened_and_has_value = $elements_initialized_and_flattened; unset($elements_initialized_flattened_and_has_value['container']); $this->assertEquals($webform->getElementsInitializedFlattenedAndHasValue(), $elements_initialized_flattened_and_has_value); // Check invalid elements. $webform->set('elements', 'invalid')->save(); $this->assertFalse($webform->getElementsInitialized()); /**************************************************************************/ // Wizard pages. /**************************************************************************/ // Check get no wizard pages. $this->assertEquals($webform->getPages(), []); // Set wizard pages. $wizard_elements = [ 'page_1' => ['#type' => 'webform_wizard_page', '#title' => 'Page 1'], 'page_2' => ['#type' => 'webform_wizard_page', '#title' => 'Page 2'], 'page_3' => ['#type' => 'webform_wizard_page', '#title' => 'Page 3'], ]; $webform->set('elements', $wizard_elements)->save(); // Check get wizard pages. $wizard_pages = [ 'page_1' => ['#title' => 'Page 1'], 'page_2' => ['#title' => 'Page 2'], 'page_3' => ['#title' => 'Page 3'], 'webform_complete' => ['#title' => 'Complete'], ]; $this->assertEquals($webform->getPages(), $wizard_pages); // Check get wizard pages with preview. $webform->setSetting('preview', TRUE)->save(); $wizard_pages = [ 'page_1' => ['#title' => 'Page 1'], 'page_2' => ['#title' => 'Page 2'], 'page_3' => ['#title' => 'Page 3'], 'webform_preview' => ['#title' => 'Preview'], 'webform_complete' => ['#title' => 'Complete'], ]; $this->assertEquals($webform->getPages(), $wizard_pages); // Check get wizard pages with preview with disable pages. $webform->setSetting('preview', TRUE)->save(); $wizard_pages = [ 'webform_start' => ['#title' => 'Start'], 'webform_preview' => ['#title' => 'Preview'], 'webform_complete' => ['#title' => 'Complete'], ]; $this->assertEquals($webform->getPages(TRUE), $wizard_pages); // @todo Add the below assertions. // Check access rules. // Check get submission form. // Check handlers CRUD operations. } /** * Test paths. */ public function testPaths() { $this->installSchema('webform', ['webform']); $this->installConfig('webform'); /** @var \Drupal\webform\WebformInterface $webform */ $webform = Webform::create(['id' => 'webform_test']); $webform->save(); $aliases = \Drupal::database()->query('SELECT source, alias FROM {url_alias}')->fetchAllKeyed(); $this->assertEquals($aliases['/webform/webform_test'], '/form/webform-test'); $this->assertEquals($aliases['/webform/webform_test/confirmation'], '/form/webform-test/confirmation'); $this->assertEquals($aliases['/webform/webform_test/submissions'], '/form/webform-test/submissions'); } /** * Test elements CRUD operations. */ public function testElementsCrud() { $this->installSchema('webform', ['webform']); $this->installEntitySchema('webform_submission'); /** @var \Drupal\webform\WebformInterface $webform */ $webform = Webform::create(['id' => 'webform_test']); $webform->save(); // Check set new root element. $elements = [ 'root' => [ '#type' => 'container', '#title' => 'root', ], ]; $webform->setElementProperties('root', $elements['root']); $this->assertEquals($webform->getElementsRaw(), Yaml::encode($elements)); // Check add new container to root. $elements['root']['container'] = [ '#type' => 'container', '#title' => 'container', ]; $webform->setElementProperties('container', $elements['root']['container'], 'root'); $this->assertEquals($webform->getElementsRaw(), Yaml::encode($elements)); // Check add new element to container. $elements['root']['container']['element'] = [ '#type' => 'textfield', '#title' => 'element', ]; $webform->setElementProperties('element', $elements['root']['container']['element'], 'container'); $this->assertEquals($webform->getElementsRaw(), Yaml::encode($elements)); // Check delete container with al recursively delete all children. $elements = [ 'root' => [ '#type' => 'container', '#title' => 'root', ], ]; $webform->deleteElement('container'); $this->assertEquals($webform->getElementsRaw(), Yaml::encode($elements)); } }
jagnoha/website
profiles/varbase/profiles/varbase/modules/contrib/webform/tests/src/Kernel/Entity/WebformEntityTest.php
PHP
gpl-2.0
13,182
# -*- coding: utf-8 -*- # # This file is part of Invenio Demosite. # Copyright (C) 2014 CERN. # # Invenio Demosite 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. # # Invenio Demosite 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 Invenio; if not, write to the Free Software Foundation, Inc., # 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. from invenio.modules.jsonalchemy.jsonext.functions.util_merge_fields_info_list \ import util_merge_fields_info_list def sync_corparate_names(self, field_name, connected_field, action): # pylint: disable=W0613 """ Sync meeting names content only when `__setitem__` or similar is used """ if action == 'set': if field_name == 'meeting_names' and self.get('meeting_names'): self.__setitem__('_first_meeting_name', self['meeting_names'][0], exclude=['connect']) if self['meeting_names'][1:]: self.__setitem__('_additional_meeting_names', self['meeting_names'][1:], exclude=['connect']) elif field_name in ('_first_author', '_additional_authors'): self.__setitem__( 'meeting_names', util_merge_fields_info_list(self, ['_first_meeting_name', '_additional_meeting_names']), exclude=['connect'])
mvesper/invenio-demosite
invenio_demosite/base/recordext/functions/sync_corparate_names.py
Python
gpl-2.0
1,895
/* Copyright (c) 2003-2007 MySQL AB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. 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 <ndb_global.h> #include "TimeModule.hpp" static const char* cMonth[] = { "x", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}; static const char* cDay[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}; static const char* cHour[] = { "00","01","02","03","04","05","06","07","08","09","10","11","12", "13","14","15","16","17","18","19","20","21","22","23"}; static const char* cMinute[] = { "00","01","02","03","04","05","06","07","08","09","10","11","12", "13","14","15","16","17","18","19","20","21","22","23","24","25", "26","27","28","29","30","31","32","33","34","35","36","37","38", "39","40","41","42","43","44","45","46","47","48","49","50","51", "52","53","54","55","56","57","58","59"}; static const char* cSecond[] = { "00","01","02","03","04","05","06","07","08","09","10","11","12", "13","14","15","16","17","18","19","20","21","22","23","24","25", "26","27","28","29","30","31","32","33","34","35","36","37","38", "39","40","41","42","43","44","45","46","47","48","49","50","51", "52","53","54","55","56","57","58","59"}; TimeModule::TimeModule(){ } TimeModule::~TimeModule(){ } void TimeModule::setTimeStamp() { struct tm* rightnow; time_t now; time(&now); rightnow = localtime(&now); iYear = rightnow->tm_year+1900; // localtime returns current year -1900 iMonth = rightnow->tm_mon+1; // and month 0-11 iMonthDay = rightnow->tm_mday; iWeekDay = rightnow->tm_wday; iHour = rightnow->tm_hour; iMinute = rightnow->tm_min; iSecond = rightnow->tm_sec; } int TimeModule::getYear() const { return iYear; } int TimeModule::getMonthNumber() const { return iMonth; } const char* TimeModule::getMonthName() const { return cMonth[iMonth]; } int TimeModule::getDayOfMonth() const { return iMonthDay; } const char* TimeModule::getDayName() const { return cDay[iWeekDay]; } const char* TimeModule::getHour() const { return cHour[iHour]; } const char* TimeModule::getMinute() const { return cMinute[iMinute]; } const char* TimeModule::getSecond() const { return cSecond[iSecond]; }
infinidb/mysql
storage/ndb/src/kernel/error/TimeModule.cpp
C++
gpl-2.0
2,974
/* * esp.c - driver for Hayes ESP serial cards * * --- Notices from serial.c, upon which this driver is based --- * * Copyright (C) 1991, 1992 Linus Torvalds * * Extensively rewritten by Theodore Ts'o, 8/16/92 -- 9/14/92. Now * much more extensible to support other serial cards based on the * 16450/16550A UART's. Added support for the AST FourPort and the * Accent Async board. * * set_serial_info fixed to set the flags, custom divisor, and uart * type fields. Fix suggested by Michael K. Johnson 12/12/92. * * 11/95: TIOCMIWAIT, TIOCGICOUNT by Angelo Haritsis <[email protected]> * * 03/96: Modularised by Angelo Haritsis <[email protected]> * * rs_set_termios fixed to look also for changes of the input * flags INPCK, BRKINT, PARMRK, IGNPAR and IGNBRK. * Bernd Anhäupl 05/17/96. * * --- End of notices from serial.c --- * * Support for the ESP serial card by Andrew J. Robinson * <[email protected]> (Card detection routine taken from a patch * by Dennis J. Boylan). Patches to allow use with 2.1.x contributed * by Chris Faylor. * * Most recent changes: (Andrew J. Robinson) * Support for PIO mode. This allows the driver to work properly with * multiport cards. * * This module exports the following rs232 io functions: * * int espserial_init(void); */ #include <linux/module.h> #include <linux/errno.h> #include <linux/signal.h> #include <linux/sched.h> #include <linux/interrupt.h> #include <linux/tty.h> #include <linux/tty_flip.h> #include <linux/serial.h> #include <linux/serialP.h> #include <linux/serial_reg.h> #include <linux/major.h> #include <linux/string.h> #include <linux/fcntl.h> #include <linux/ptrace.h> #include <linux/ioport.h> #include <linux/mm.h> #include <linux/init.h> #include <asm/system.h> #include <asm/io.h> #include <asm/segment.h> #include <asm/bitops.h> #include <asm/dma.h> #include <linux/malloc.h> #include <asm/uaccess.h> #include <linux/hayesesp.h> #define NR_PORTS 64 /* maximum number of ports */ #define NR_PRIMARY 8 /* maximum number of primary ports */ /* The following variables can be set by giving module options */ static int irq[NR_PRIMARY]; /* IRQ for each base port */ static unsigned int divisor[NR_PRIMARY]; /* custom divisor for each port */ static unsigned int dma = ESP_DMA_CHANNEL; /* DMA channel */ static unsigned int rx_trigger = ESP_RX_TRIGGER; static unsigned int tx_trigger = ESP_TX_TRIGGER; static unsigned int flow_off = ESP_FLOW_OFF; static unsigned int flow_on = ESP_FLOW_ON; static unsigned int rx_timeout = ESP_RX_TMOUT; static unsigned int pio_threshold = ESP_PIO_THRESHOLD; MODULE_PARM(irq, "1-8i"); MODULE_PARM(divisor, "1-8i"); MODULE_PARM(dma, "i"); MODULE_PARM(rx_trigger, "i"); MODULE_PARM(tx_trigger, "i"); MODULE_PARM(flow_off, "i"); MODULE_PARM(flow_on, "i"); MODULE_PARM(rx_timeout, "i"); MODULE_PARM(pio_threshold, "i"); /* END */ static char *dma_buffer; static int dma_bytes; static struct esp_pio_buffer *free_pio_buf; #define DMA_BUFFER_SZ 1024 #define WAKEUP_CHARS 1024 static char *serial_name = "ESP serial driver"; static char *serial_version = "2.2"; static DECLARE_TASK_QUEUE(tq_esp); static struct tty_driver esp_driver, esp_callout_driver; static int serial_refcount; /* serial subtype definitions */ #define SERIAL_TYPE_NORMAL 1 #define SERIAL_TYPE_CALLOUT 2 /* * Serial driver configuration section. Here are the various options: * * SERIAL_PARANOIA_CHECK * Check the magic number for the esp_structure where * ever possible. */ #undef SERIAL_PARANOIA_CHECK #define SERIAL_DO_RESTART #undef SERIAL_DEBUG_INTR #undef SERIAL_DEBUG_OPEN #undef SERIAL_DEBUG_FLOW #define _INLINE_ inline #if defined(MODULE) && defined(SERIAL_DEBUG_MCOUNT) #define DBG_CNT(s) printk("(%s): [%x] refc=%d, serc=%d, ttyc=%d -> %s\n", \ kdevname(tty->device), (info->flags), serial_refcount,info->count,tty->count,s) #else #define DBG_CNT(s) #endif static struct esp_struct *ports; static void change_speed(struct esp_struct *info); static void rs_wait_until_sent(struct tty_struct *, int); /* * The ESP card has a clock rate of 14.7456 MHz (that is, 2**ESPC_SCALE * times the normal 1.8432 Mhz clock of most serial boards). */ #define BASE_BAUD ((1843200 / 16) * (1 << ESPC_SCALE)) /* Standard COM flags (except for COM4, because of the 8514 problem) */ #define STD_COM_FLAGS (ASYNC_BOOT_AUTOCONF | ASYNC_SKIP_TEST) static struct tty_struct *serial_table[NR_PORTS]; static struct termios *serial_termios[NR_PORTS]; static struct termios *serial_termios_locked[NR_PORTS]; #ifndef MIN #define MIN(a,b) ((a) < (b) ? (a) : (b)) #endif /* * tmp_buf is used as a temporary buffer by serial_write. We need to * lock it in case the memcpy_fromfs blocks while swapping in a page, * and some other program tries to do a serial write at the same time. * Since the lock will only come under contention when the system is * swapping and available memory is low, it makes sense to share one * buffer across all the serial ports, since it significantly saves * memory if large numbers of serial ports are open. */ static unsigned char *tmp_buf; static DECLARE_MUTEX(tmp_buf_sem); static inline int serial_paranoia_check(struct esp_struct *info, kdev_t device, const char *routine) { #ifdef SERIAL_PARANOIA_CHECK static const char *badmagic = "Warning: bad magic number for serial struct (%s) in %s\n"; static const char *badinfo = "Warning: null esp_struct for (%s) in %s\n"; if (!info) { printk(badinfo, kdevname(device), routine); return 1; } if (info->magic != ESP_MAGIC) { printk(badmagic, kdevname(device), routine); return 1; } #endif return 0; } static inline unsigned int serial_in(struct esp_struct *info, int offset) { return inb(info->port + offset); } static inline void serial_out(struct esp_struct *info, int offset, unsigned char value) { outb(value, info->port+offset); } /* * ------------------------------------------------------------ * rs_stop() and rs_start() * * This routines are called before setting or resetting tty->stopped. * They enable or disable transmitter interrupts, as necessary. * ------------------------------------------------------------ */ static void rs_stop(struct tty_struct *tty) { struct esp_struct *info = (struct esp_struct *)tty->driver_data; unsigned long flags; if (serial_paranoia_check(info, tty->device, "rs_stop")) return; save_flags(flags); cli(); if (info->IER & UART_IER_THRI) { info->IER &= ~UART_IER_THRI; serial_out(info, UART_ESI_CMD1, ESI_SET_SRV_MASK); serial_out(info, UART_ESI_CMD2, info->IER); } restore_flags(flags); } static void rs_start(struct tty_struct *tty) { struct esp_struct *info = (struct esp_struct *)tty->driver_data; unsigned long flags; if (serial_paranoia_check(info, tty->device, "rs_start")) return; save_flags(flags); cli(); if (info->xmit_cnt && info->xmit_buf && !(info->IER & UART_IER_THRI)) { info->IER |= UART_IER_THRI; serial_out(info, UART_ESI_CMD1, ESI_SET_SRV_MASK); serial_out(info, UART_ESI_CMD2, info->IER); } restore_flags(flags); } /* * ---------------------------------------------------------------------- * * Here starts the interrupt handling routines. All of the following * subroutines are declared as inline and are folded into * rs_interrupt(). They were separated out for readability's sake. * * Note: rs_interrupt() is a "fast" interrupt, which means that it * runs with interrupts turned off. People who may want to modify * rs_interrupt() should try to keep the interrupt handler as fast as * possible. After you are done making modifications, it is not a bad * idea to do: * * gcc -S -DKERNEL -Wall -Wstrict-prototypes -O6 -fomit-frame-pointer serial.c * * and look at the resulting assemble code in serial.s. * * - Ted Ts'o ([email protected]), 7-Mar-93 * ----------------------------------------------------------------------- */ /* * This routine is used by the interrupt handler to schedule * processing in the software interrupt portion of the driver. */ static _INLINE_ void rs_sched_event(struct esp_struct *info, int event) { info->event |= 1 << event; queue_task(&info->tqueue, &tq_esp); mark_bh(ESP_BH); } static _INLINE_ struct esp_pio_buffer *get_pio_buffer(void) { struct esp_pio_buffer *buf; if (free_pio_buf) { buf = free_pio_buf; free_pio_buf = buf->next; } else { buf = (struct esp_pio_buffer *) kmalloc(sizeof(struct esp_pio_buffer), GFP_ATOMIC); } return buf; } static _INLINE_ void release_pio_buffer(struct esp_pio_buffer *buf) { buf->next = free_pio_buf; free_pio_buf = buf; } static _INLINE_ void receive_chars_pio(struct esp_struct *info, int num_bytes) { struct tty_struct *tty = info->tty; int i; struct esp_pio_buffer *pio_buf; struct esp_pio_buffer *err_buf; unsigned char status_mask; pio_buf = get_pio_buffer(); if (!pio_buf) return; err_buf = get_pio_buffer(); if (!err_buf) { release_pio_buffer(pio_buf); return; } sti(); status_mask = (info->read_status_mask >> 2) & 0x07; for (i = 0; i < num_bytes - 1; i += 2) { *((unsigned short *)(pio_buf->data + i)) = inw(info->port + UART_ESI_RX); err_buf->data[i] = serial_in(info, UART_ESI_RWS); err_buf->data[i + 1] = (err_buf->data[i] >> 3) & status_mask; err_buf->data[i] &= status_mask; } if (num_bytes & 0x0001) { pio_buf->data[num_bytes - 1] = serial_in(info, UART_ESI_RX); err_buf->data[num_bytes - 1] = (serial_in(info, UART_ESI_RWS) >> 3) & status_mask; } cli(); /* make sure everything is still ok since interrupts were enabled */ tty = info->tty; if (!tty) { release_pio_buffer(pio_buf); release_pio_buffer(err_buf); info->stat_flags &= ~ESP_STAT_RX_TIMEOUT; return; } status_mask = (info->ignore_status_mask >> 2) & 0x07; for (i = 0; i < num_bytes; i++) { if (!(err_buf->data[i] & status_mask)) { *(tty->flip.char_buf_ptr++) = pio_buf->data[i]; if (err_buf->data[i] & 0x04) { *(tty->flip.flag_buf_ptr++) = TTY_BREAK; if (info->flags & ASYNC_SAK) do_SAK(tty); } else if (err_buf->data[i] & 0x02) *(tty->flip.flag_buf_ptr++) = TTY_FRAME; else if (err_buf->data[i] & 0x01) *(tty->flip.flag_buf_ptr++) = TTY_PARITY; else *(tty->flip.flag_buf_ptr++) = 0; tty->flip.count++; } } queue_task(&tty->flip.tqueue, &tq_timer); info->stat_flags &= ~ESP_STAT_RX_TIMEOUT; release_pio_buffer(pio_buf); release_pio_buffer(err_buf); } static _INLINE_ void receive_chars_dma(struct esp_struct *info, int num_bytes) { unsigned long flags; info->stat_flags &= ~ESP_STAT_RX_TIMEOUT; dma_bytes = num_bytes; info->stat_flags |= ESP_STAT_DMA_RX; flags=claim_dma_lock(); disable_dma(dma); clear_dma_ff(dma); set_dma_mode(dma, DMA_MODE_READ); set_dma_addr(dma, virt_to_bus(dma_buffer)); set_dma_count(dma, dma_bytes); enable_dma(dma); release_dma_lock(flags); serial_out(info, UART_ESI_CMD1, ESI_START_DMA_RX); } static _INLINE_ void receive_chars_dma_done(struct esp_struct *info, int status) { struct tty_struct *tty = info->tty; int num_bytes; unsigned long flags; flags=claim_dma_lock(); disable_dma(dma); clear_dma_ff(dma); info->stat_flags &= ~ESP_STAT_DMA_RX; num_bytes = dma_bytes - get_dma_residue(dma); release_dma_lock(flags); info->icount.rx += num_bytes; memcpy(tty->flip.char_buf_ptr, dma_buffer, num_bytes); tty->flip.char_buf_ptr += num_bytes; tty->flip.count += num_bytes; memset(tty->flip.flag_buf_ptr, 0, num_bytes); tty->flip.flag_buf_ptr += num_bytes; if (num_bytes > 0) { tty->flip.flag_buf_ptr--; status &= (0x1c & info->read_status_mask); if (status & info->ignore_status_mask) { tty->flip.count--; tty->flip.char_buf_ptr--; tty->flip.flag_buf_ptr--; } else if (status & 0x10) { *tty->flip.flag_buf_ptr = TTY_BREAK; (info->icount.brk)++; if (info->flags & ASYNC_SAK) do_SAK(tty); } else if (status & 0x08) { *tty->flip.flag_buf_ptr = TTY_FRAME; (info->icount.frame)++; } else if (status & 0x04) { *tty->flip.flag_buf_ptr = TTY_PARITY; (info->icount.parity)++; } tty->flip.flag_buf_ptr++; queue_task(&tty->flip.tqueue, &tq_timer); } if (dma_bytes != num_bytes) { num_bytes = dma_bytes - num_bytes; dma_bytes = 0; receive_chars_dma(info, num_bytes); } else dma_bytes = 0; } static _INLINE_ void transmit_chars_pio(struct esp_struct *info, int space_avail) { int i; struct esp_pio_buffer *pio_buf; pio_buf = get_pio_buffer(); if (!pio_buf) return; while (space_avail && info->xmit_cnt) { if (info->xmit_tail + space_avail <= ESP_XMIT_SIZE) { memcpy(pio_buf->data, &(info->xmit_buf[info->xmit_tail]), space_avail); } else { i = ESP_XMIT_SIZE - info->xmit_tail; memcpy(pio_buf->data, &(info->xmit_buf[info->xmit_tail]), i); memcpy(&(pio_buf->data[i]), info->xmit_buf, space_avail - i); } info->xmit_cnt -= space_avail; info->xmit_tail = (info->xmit_tail + space_avail) & (ESP_XMIT_SIZE - 1); sti(); for (i = 0; i < space_avail - 1; i += 2) { outw(*((unsigned short *)(pio_buf->data + i)), info->port + UART_ESI_TX); } if (space_avail & 0x0001) serial_out(info, UART_ESI_TX, pio_buf->data[space_avail - 1]); cli(); if (info->xmit_cnt) { serial_out(info, UART_ESI_CMD1, ESI_NO_COMMAND); serial_out(info, UART_ESI_CMD1, ESI_GET_TX_AVAIL); space_avail = serial_in(info, UART_ESI_STAT1) << 8; space_avail |= serial_in(info, UART_ESI_STAT2); if (space_avail > info->xmit_cnt) space_avail = info->xmit_cnt; } } if (info->xmit_cnt < WAKEUP_CHARS) { rs_sched_event(info, ESP_EVENT_WRITE_WAKEUP); #ifdef SERIAL_DEBUG_INTR printk("THRE..."); #endif if (info->xmit_cnt <= 0) { info->IER &= ~UART_IER_THRI; serial_out(info, UART_ESI_CMD1, ESI_SET_SRV_MASK); serial_out(info, UART_ESI_CMD2, info->IER); } } release_pio_buffer(pio_buf); } static _INLINE_ void transmit_chars_dma(struct esp_struct *info, int num_bytes) { unsigned long flags; dma_bytes = num_bytes; if (info->xmit_tail + dma_bytes <= ESP_XMIT_SIZE) { memcpy(dma_buffer, &(info->xmit_buf[info->xmit_tail]), dma_bytes); } else { int i = ESP_XMIT_SIZE - info->xmit_tail; memcpy(dma_buffer, &(info->xmit_buf[info->xmit_tail]), i); memcpy(&(dma_buffer[i]), info->xmit_buf, dma_bytes - i); } info->xmit_cnt -= dma_bytes; info->xmit_tail = (info->xmit_tail + dma_bytes) & (ESP_XMIT_SIZE - 1); if (info->xmit_cnt < WAKEUP_CHARS) { rs_sched_event(info, ESP_EVENT_WRITE_WAKEUP); #ifdef SERIAL_DEBUG_INTR printk("THRE..."); #endif if (info->xmit_cnt <= 0) { info->IER &= ~UART_IER_THRI; serial_out(info, UART_ESI_CMD1, ESI_SET_SRV_MASK); serial_out(info, UART_ESI_CMD2, info->IER); } } info->stat_flags |= ESP_STAT_DMA_TX; flags=claim_dma_lock(); disable_dma(dma); clear_dma_ff(dma); set_dma_mode(dma, DMA_MODE_WRITE); set_dma_addr(dma, virt_to_bus(dma_buffer)); set_dma_count(dma, dma_bytes); enable_dma(dma); release_dma_lock(flags); serial_out(info, UART_ESI_CMD1, ESI_START_DMA_TX); } static _INLINE_ void transmit_chars_dma_done(struct esp_struct *info) { int num_bytes; unsigned long flags; flags=claim_dma_lock(); disable_dma(dma); clear_dma_ff(dma); num_bytes = dma_bytes - get_dma_residue(dma); info->icount.tx += dma_bytes; release_dma_lock(flags); if (dma_bytes != num_bytes) { dma_bytes -= num_bytes; memmove(dma_buffer, dma_buffer + num_bytes, dma_bytes); flags=claim_dma_lock(); disable_dma(dma); clear_dma_ff(dma); set_dma_mode(dma, DMA_MODE_WRITE); set_dma_addr(dma, virt_to_bus(dma_buffer)); set_dma_count(dma, dma_bytes); enable_dma(dma); release_dma_lock(flags); serial_out(info, UART_ESI_CMD1, ESI_START_DMA_TX); } else { dma_bytes = 0; info->stat_flags &= ~ESP_STAT_DMA_TX; } } static _INLINE_ void check_modem_status(struct esp_struct *info) { int status; serial_out(info, UART_ESI_CMD1, ESI_GET_UART_STAT); status = serial_in(info, UART_ESI_STAT2); if (status & UART_MSR_ANY_DELTA) { /* update input line counters */ if (status & UART_MSR_TERI) info->icount.rng++; if (status & UART_MSR_DDSR) info->icount.dsr++; if (status & UART_MSR_DDCD) info->icount.dcd++; if (status & UART_MSR_DCTS) info->icount.cts++; wake_up_interruptible(&info->delta_msr_wait); } if ((info->flags & ASYNC_CHECK_CD) && (status & UART_MSR_DDCD)) { #if (defined(SERIAL_DEBUG_OPEN) || defined(SERIAL_DEBUG_INTR)) printk("ttys%d CD now %s...", info->line, (status & UART_MSR_DCD) ? "on" : "off"); #endif if (status & UART_MSR_DCD) wake_up_interruptible(&info->open_wait); else if (!((info->flags & ASYNC_CALLOUT_ACTIVE) && (info->flags & ASYNC_CALLOUT_NOHUP))) { #ifdef SERIAL_DEBUG_OPEN printk("scheduling hangup..."); #endif MOD_INC_USE_COUNT; if (schedule_task(&info->tqueue_hangup) == 0) MOD_DEC_USE_COUNT; } } } /* * This is the serial driver's interrupt routine */ static void rs_interrupt_single(int irq, void *dev_id, struct pt_regs * regs) { struct esp_struct * info; unsigned err_status; unsigned int scratch; #ifdef SERIAL_DEBUG_INTR printk("rs_interrupt_single(%d)...", irq); #endif info = (struct esp_struct *)dev_id; err_status = 0; scratch = serial_in(info, UART_ESI_SID); cli(); if (!info->tty) { sti(); return; } if (scratch & 0x04) { /* error */ serial_out(info, UART_ESI_CMD1, ESI_GET_ERR_STAT); err_status = serial_in(info, UART_ESI_STAT1); serial_in(info, UART_ESI_STAT2); if (err_status & 0x01) info->stat_flags |= ESP_STAT_RX_TIMEOUT; if (err_status & 0x20) /* UART status */ check_modem_status(info); if (err_status & 0x80) /* Start break */ wake_up_interruptible(&info->break_wait); } if ((scratch & 0x88) || /* DMA completed or timed out */ (err_status & 0x1c) /* receive error */) { if (info->stat_flags & ESP_STAT_DMA_RX) receive_chars_dma_done(info, err_status); else if (info->stat_flags & ESP_STAT_DMA_TX) transmit_chars_dma_done(info); } if (!(info->stat_flags & (ESP_STAT_DMA_RX | ESP_STAT_DMA_TX)) && ((scratch & 0x01) || (info->stat_flags & ESP_STAT_RX_TIMEOUT)) && (info->IER & UART_IER_RDI)) { int num_bytes; serial_out(info, UART_ESI_CMD1, ESI_NO_COMMAND); serial_out(info, UART_ESI_CMD1, ESI_GET_RX_AVAIL); num_bytes = serial_in(info, UART_ESI_STAT1) << 8; num_bytes |= serial_in(info, UART_ESI_STAT2); if (num_bytes > (TTY_FLIPBUF_SIZE - info->tty->flip.count)) num_bytes = TTY_FLIPBUF_SIZE - info->tty->flip.count; if (num_bytes) { if (dma_bytes || (info->stat_flags & ESP_STAT_USE_PIO) || (num_bytes <= info->config.pio_threshold)) receive_chars_pio(info, num_bytes); else receive_chars_dma(info, num_bytes); } } if (!(info->stat_flags & (ESP_STAT_DMA_RX | ESP_STAT_DMA_TX)) && (scratch & 0x02) && (info->IER & UART_IER_THRI)) { if ((info->xmit_cnt <= 0) || info->tty->stopped) { info->IER &= ~UART_IER_THRI; serial_out(info, UART_ESI_CMD1, ESI_SET_SRV_MASK); serial_out(info, UART_ESI_CMD2, info->IER); } else { int num_bytes; serial_out(info, UART_ESI_CMD1, ESI_NO_COMMAND); serial_out(info, UART_ESI_CMD1, ESI_GET_TX_AVAIL); num_bytes = serial_in(info, UART_ESI_STAT1) << 8; num_bytes |= serial_in(info, UART_ESI_STAT2); if (num_bytes > info->xmit_cnt) num_bytes = info->xmit_cnt; if (num_bytes) { if (dma_bytes || (info->stat_flags & ESP_STAT_USE_PIO) || (num_bytes <= info->config.pio_threshold)) transmit_chars_pio(info, num_bytes); else transmit_chars_dma(info, num_bytes); } } } info->last_active = jiffies; #ifdef SERIAL_DEBUG_INTR printk("end.\n"); #endif sti(); } /* * ------------------------------------------------------------------- * Here ends the serial interrupt routines. * ------------------------------------------------------------------- */ /* * This routine is used to handle the "bottom half" processing for the * serial driver, known also the "software interrupt" processing. * This processing is done at the kernel interrupt level, after the * rs_interrupt() has returned, BUT WITH INTERRUPTS TURNED ON. This * is where time-consuming activities which can not be done in the * interrupt driver proper are done; the interrupt driver schedules * them using rs_sched_event(), and they get done here. */ static void do_serial_bh(void) { run_task_queue(&tq_esp); } static void do_softint(void *private_) { struct esp_struct *info = (struct esp_struct *) private_; struct tty_struct *tty; tty = info->tty; if (!tty) return; if (test_and_clear_bit(ESP_EVENT_WRITE_WAKEUP, &info->event)) { if ((tty->flags & (1 << TTY_DO_WRITE_WAKEUP)) && tty->ldisc.write_wakeup) (tty->ldisc.write_wakeup)(tty); wake_up_interruptible(&tty->write_wait); } } /* * This routine is called from the scheduler tqueue when the interrupt * routine has signalled that a hangup has occurred. The path of * hangup processing is: * * serial interrupt routine -> (scheduler tqueue) -> * do_serial_hangup() -> tty->hangup() -> esp_hangup() * */ static void do_serial_hangup(void *private_) { struct esp_struct *info = (struct esp_struct *) private_; struct tty_struct *tty; tty = info->tty; if (tty) tty_hangup(tty); MOD_DEC_USE_COUNT; } /* * --------------------------------------------------------------- * Low level utility subroutines for the serial driver: routines to * figure out the appropriate timeout for an interrupt chain, routines * to initialize and startup a serial port, and routines to shutdown a * serial port. Useful stuff like that. * --------------------------------------------------------------- */ static _INLINE_ void esp_basic_init(struct esp_struct * info) { /* put ESPC in enhanced mode */ serial_out(info, UART_ESI_CMD1, ESI_SET_MODE); if (info->stat_flags & ESP_STAT_NEVER_DMA) serial_out(info, UART_ESI_CMD2, 0x01); else serial_out(info, UART_ESI_CMD2, 0x31); /* disable interrupts for now */ serial_out(info, UART_ESI_CMD1, ESI_SET_SRV_MASK); serial_out(info, UART_ESI_CMD2, 0x00); /* set interrupt and DMA channel */ serial_out(info, UART_ESI_CMD1, ESI_SET_IRQ); if (info->stat_flags & ESP_STAT_NEVER_DMA) serial_out(info, UART_ESI_CMD2, 0x01); else serial_out(info, UART_ESI_CMD2, (dma << 4) | 0x01); serial_out(info, UART_ESI_CMD1, ESI_SET_ENH_IRQ); if (info->line % 8) /* secondary port */ serial_out(info, UART_ESI_CMD2, 0x0d); /* shared */ else if (info->irq == 9) serial_out(info, UART_ESI_CMD2, 0x02); else serial_out(info, UART_ESI_CMD2, info->irq); /* set error status mask (check this) */ serial_out(info, UART_ESI_CMD1, ESI_SET_ERR_MASK); if (info->stat_flags & ESP_STAT_NEVER_DMA) serial_out(info, UART_ESI_CMD2, 0xa1); else serial_out(info, UART_ESI_CMD2, 0xbd); serial_out(info, UART_ESI_CMD2, 0x00); /* set DMA timeout */ serial_out(info, UART_ESI_CMD1, ESI_SET_DMA_TMOUT); serial_out(info, UART_ESI_CMD2, 0xff); /* set FIFO trigger levels */ serial_out(info, UART_ESI_CMD1, ESI_SET_TRIGGER); serial_out(info, UART_ESI_CMD2, info->config.rx_trigger >> 8); serial_out(info, UART_ESI_CMD2, info->config.rx_trigger); serial_out(info, UART_ESI_CMD2, info->config.tx_trigger >> 8); serial_out(info, UART_ESI_CMD2, info->config.tx_trigger); /* Set clock scaling and wait states */ serial_out(info, UART_ESI_CMD1, ESI_SET_PRESCALAR); serial_out(info, UART_ESI_CMD2, 0x04 | ESPC_SCALE); /* set reinterrupt pacing */ serial_out(info, UART_ESI_CMD1, ESI_SET_REINTR); serial_out(info, UART_ESI_CMD2, 0xff); } static int startup(struct esp_struct * info) { unsigned long flags; int retval=0; unsigned int num_chars; save_flags(flags); cli(); if (info->flags & ASYNC_INITIALIZED) { restore_flags(flags); return retval; } if (!info->xmit_buf) { info->xmit_buf = (unsigned char *)get_free_page(GFP_KERNEL); if (!info->xmit_buf) { restore_flags(flags); return -ENOMEM; } } #ifdef SERIAL_DEBUG_OPEN printk("starting up ttys%d (irq %d)...", info->line, info->irq); #endif /* Flush the RX buffer. Using the ESI flush command may cause */ /* wild interrupts, so read all the data instead. */ serial_out(info, UART_ESI_CMD1, ESI_NO_COMMAND); serial_out(info, UART_ESI_CMD1, ESI_GET_RX_AVAIL); num_chars = serial_in(info, UART_ESI_STAT1) << 8; num_chars |= serial_in(info, UART_ESI_STAT2); while (num_chars > 1) { inw(info->port + UART_ESI_RX); num_chars -= 2; } if (num_chars) serial_in(info, UART_ESI_RX); /* set receive character timeout */ serial_out(info, UART_ESI_CMD1, ESI_SET_RX_TIMEOUT); serial_out(info, UART_ESI_CMD2, info->config.rx_timeout); /* clear all flags except the "never DMA" flag */ info->stat_flags &= ESP_STAT_NEVER_DMA; if (info->stat_flags & ESP_STAT_NEVER_DMA) info->stat_flags |= ESP_STAT_USE_PIO; /* * Allocate the IRQ */ retval = request_irq(info->irq, rs_interrupt_single, SA_SHIRQ, "esp serial", info); if (retval) { if (capable(CAP_SYS_ADMIN)) { if (info->tty) set_bit(TTY_IO_ERROR, &info->tty->flags); retval = 0; } restore_flags(flags); return retval; } if (!(info->stat_flags & ESP_STAT_USE_PIO) && !dma_buffer) { dma_buffer = (char *)__get_dma_pages( GFP_KERNEL, get_order(DMA_BUFFER_SZ)); /* use PIO mode if DMA buf/chan cannot be allocated */ if (!dma_buffer) info->stat_flags |= ESP_STAT_USE_PIO; else if (request_dma(dma, "esp serial")) { free_pages((unsigned int)dma_buffer, get_order(DMA_BUFFER_SZ)); dma_buffer = 0; info->stat_flags |= ESP_STAT_USE_PIO; } } info->MCR = UART_MCR_DTR | UART_MCR_RTS | UART_MCR_OUT2; serial_out(info, UART_ESI_CMD1, ESI_WRITE_UART); serial_out(info, UART_ESI_CMD2, UART_MCR); serial_out(info, UART_ESI_CMD2, info->MCR); /* * Finally, enable interrupts */ /* info->IER = UART_IER_MSI | UART_IER_RLSI | UART_IER_RDI; */ info->IER = UART_IER_RLSI | UART_IER_RDI | UART_IER_DMA_TMOUT | UART_IER_DMA_TC; serial_out(info, UART_ESI_CMD1, ESI_SET_SRV_MASK); serial_out(info, UART_ESI_CMD2, info->IER); if (info->tty) clear_bit(TTY_IO_ERROR, &info->tty->flags); info->xmit_cnt = info->xmit_head = info->xmit_tail = 0; /* * Set up the tty->alt_speed kludge */ if (info->tty) { if ((info->flags & ASYNC_SPD_MASK) == ASYNC_SPD_HI) info->tty->alt_speed = 57600; if ((info->flags & ASYNC_SPD_MASK) == ASYNC_SPD_VHI) info->tty->alt_speed = 115200; if ((info->flags & ASYNC_SPD_MASK) == ASYNC_SPD_SHI) info->tty->alt_speed = 230400; if ((info->flags & ASYNC_SPD_MASK) == ASYNC_SPD_WARP) info->tty->alt_speed = 460800; } /* * set the speed of the serial port */ change_speed(info); info->flags |= ASYNC_INITIALIZED; restore_flags(flags); return 0; } /* * This routine will shutdown a serial port; interrupts are disabled, and * DTR is dropped if the hangup on close termio flag is on. */ static void shutdown(struct esp_struct * info) { unsigned long flags, f; if (!(info->flags & ASYNC_INITIALIZED)) return; #ifdef SERIAL_DEBUG_OPEN printk("Shutting down serial port %d (irq %d)....", info->line, info->irq); #endif save_flags(flags); cli(); /* Disable interrupts */ /* * clear delta_msr_wait queue to avoid mem leaks: we may free the irq * here so the queue might never be waken up */ wake_up_interruptible(&info->delta_msr_wait); wake_up_interruptible(&info->break_wait); /* stop a DMA transfer on the port being closed */ if (info->stat_flags & (ESP_STAT_DMA_RX | ESP_STAT_DMA_TX)) { f=claim_dma_lock(); disable_dma(dma); clear_dma_ff(dma); release_dma_lock(f); dma_bytes = 0; } /* * Free the IRQ */ free_irq(info->irq, info); if (dma_buffer) { struct esp_struct *current_port = ports; while (current_port) { if ((current_port != info) && (current_port->flags & ASYNC_INITIALIZED)) break; current_port = current_port->next_port; } if (!current_port) { free_dma(dma); free_pages((unsigned int)dma_buffer, get_order(DMA_BUFFER_SZ)); dma_buffer = 0; } } if (info->xmit_buf) { free_page((unsigned long) info->xmit_buf); info->xmit_buf = 0; } info->IER = 0; serial_out(info, UART_ESI_CMD1, ESI_SET_SRV_MASK); serial_out(info, UART_ESI_CMD2, 0x00); if (!info->tty || (info->tty->termios->c_cflag & HUPCL)) info->MCR &= ~(UART_MCR_DTR|UART_MCR_RTS); info->MCR &= ~UART_MCR_OUT2; serial_out(info, UART_ESI_CMD1, ESI_WRITE_UART); serial_out(info, UART_ESI_CMD2, UART_MCR); serial_out(info, UART_ESI_CMD2, info->MCR); if (info->tty) set_bit(TTY_IO_ERROR, &info->tty->flags); info->flags &= ~ASYNC_INITIALIZED; restore_flags(flags); } /* * This routine is called to set the UART divisor registers to match * the specified baud rate for a serial port. */ static void change_speed(struct esp_struct *info) { unsigned short port; int quot = 0; unsigned cflag,cval; int baud, bits; unsigned char flow1 = 0, flow2 = 0; unsigned long flags; if (!info->tty || !info->tty->termios) return; cflag = info->tty->termios->c_cflag; port = info->port; /* byte size and parity */ switch (cflag & CSIZE) { case CS5: cval = 0x00; bits = 7; break; case CS6: cval = 0x01; bits = 8; break; case CS7: cval = 0x02; bits = 9; break; case CS8: cval = 0x03; bits = 10; break; default: cval = 0x00; bits = 7; break; } if (cflag & CSTOPB) { cval |= 0x04; bits++; } if (cflag & PARENB) { cval |= UART_LCR_PARITY; bits++; } if (!(cflag & PARODD)) cval |= UART_LCR_EPAR; #ifdef CMSPAR if (cflag & CMSPAR) cval |= UART_LCR_SPAR; #endif baud = tty_get_baud_rate(info->tty); if (baud == 38400 && ((info->flags & ASYNC_SPD_MASK) == ASYNC_SPD_CUST)) quot = info->custom_divisor; else { if (baud == 134) /* Special case since 134 is really 134.5 */ quot = (2*BASE_BAUD / 269); else if (baud) quot = BASE_BAUD / baud; } /* If the quotient is ever zero, default to 9600 bps */ if (!quot) quot = BASE_BAUD / 9600; info->timeout = ((1024 * HZ * bits * quot) / BASE_BAUD) + (HZ / 50); /* CTS flow control flag and modem status interrupts */ /* info->IER &= ~UART_IER_MSI; */ if (cflag & CRTSCTS) { info->flags |= ASYNC_CTS_FLOW; /* info->IER |= UART_IER_MSI; */ flow1 = 0x04; flow2 = 0x10; } else info->flags &= ~ASYNC_CTS_FLOW; if (cflag & CLOCAL) info->flags &= ~ASYNC_CHECK_CD; else { info->flags |= ASYNC_CHECK_CD; /* info->IER |= UART_IER_MSI; */ } /* * Set up parity check flag */ #define RELEVANT_IFLAG(iflag) (iflag & (IGNBRK|BRKINT|IGNPAR|PARMRK|INPCK)) info->read_status_mask = UART_LSR_OE | UART_LSR_THRE | UART_LSR_DR; if (I_INPCK(info->tty)) info->read_status_mask |= UART_LSR_FE | UART_LSR_PE; if (I_BRKINT(info->tty) || I_PARMRK(info->tty)) info->read_status_mask |= UART_LSR_BI; info->ignore_status_mask = 0; #if 0 /* This should be safe, but for some broken bits of hardware... */ if (I_IGNPAR(info->tty)) { info->ignore_status_mask |= UART_LSR_PE | UART_LSR_FE; info->read_status_mask |= UART_LSR_PE | UART_LSR_FE; } #endif if (I_IGNBRK(info->tty)) { info->ignore_status_mask |= UART_LSR_BI; info->read_status_mask |= UART_LSR_BI; /* * If we're ignore parity and break indicators, ignore * overruns too. (For real raw support). */ if (I_IGNPAR(info->tty)) { info->ignore_status_mask |= UART_LSR_OE | \ UART_LSR_PE | UART_LSR_FE; info->read_status_mask |= UART_LSR_OE | \ UART_LSR_PE | UART_LSR_FE; } } if (I_IXOFF(info->tty)) flow1 |= 0x81; save_flags(flags); cli(); /* set baud */ serial_out(info, UART_ESI_CMD1, ESI_SET_BAUD); serial_out(info, UART_ESI_CMD2, quot >> 8); serial_out(info, UART_ESI_CMD2, quot & 0xff); /* set data bits, parity, etc. */ serial_out(info, UART_ESI_CMD1, ESI_WRITE_UART); serial_out(info, UART_ESI_CMD2, UART_LCR); serial_out(info, UART_ESI_CMD2, cval); /* Enable flow control */ serial_out(info, UART_ESI_CMD1, ESI_SET_FLOW_CNTL); serial_out(info, UART_ESI_CMD2, flow1); serial_out(info, UART_ESI_CMD2, flow2); /* set flow control characters (XON/XOFF only) */ if (I_IXOFF(info->tty)) { serial_out(info, UART_ESI_CMD1, ESI_SET_FLOW_CHARS); serial_out(info, UART_ESI_CMD2, START_CHAR(info->tty)); serial_out(info, UART_ESI_CMD2, STOP_CHAR(info->tty)); serial_out(info, UART_ESI_CMD2, 0x10); serial_out(info, UART_ESI_CMD2, 0x21); switch (cflag & CSIZE) { case CS5: serial_out(info, UART_ESI_CMD2, 0x1f); break; case CS6: serial_out(info, UART_ESI_CMD2, 0x3f); break; case CS7: case CS8: serial_out(info, UART_ESI_CMD2, 0x7f); break; default: serial_out(info, UART_ESI_CMD2, 0xff); break; } } /* Set high/low water */ serial_out(info, UART_ESI_CMD1, ESI_SET_FLOW_LVL); serial_out(info, UART_ESI_CMD2, info->config.flow_off >> 8); serial_out(info, UART_ESI_CMD2, info->config.flow_off); serial_out(info, UART_ESI_CMD2, info->config.flow_on >> 8); serial_out(info, UART_ESI_CMD2, info->config.flow_on); restore_flags(flags); } static void rs_put_char(struct tty_struct *tty, unsigned char ch) { struct esp_struct *info = (struct esp_struct *)tty->driver_data; unsigned long flags; if (serial_paranoia_check(info, tty->device, "rs_put_char")) return; if (!tty || !info->xmit_buf) return; save_flags(flags); cli(); if (info->xmit_cnt >= ESP_XMIT_SIZE - 1) { restore_flags(flags); return; } info->xmit_buf[info->xmit_head++] = ch; info->xmit_head &= ESP_XMIT_SIZE-1; info->xmit_cnt++; restore_flags(flags); } static void rs_flush_chars(struct tty_struct *tty) { struct esp_struct *info = (struct esp_struct *)tty->driver_data; unsigned long flags; if (serial_paranoia_check(info, tty->device, "rs_flush_chars")) return; if (info->xmit_cnt <= 0 || tty->stopped || !info->xmit_buf) return; save_flags(flags); cli(); if (!(info->IER & UART_IER_THRI)) { info->IER |= UART_IER_THRI; serial_out(info, UART_ESI_CMD1, ESI_SET_SRV_MASK); serial_out(info, UART_ESI_CMD2, info->IER); } restore_flags(flags); } static int rs_write(struct tty_struct * tty, int from_user, const unsigned char *buf, int count) { int c, t, ret = 0; struct esp_struct *info = (struct esp_struct *)tty->driver_data; unsigned long flags; if (serial_paranoia_check(info, tty->device, "rs_write")) return 0; if (!tty || !info->xmit_buf || !tmp_buf) return 0; if (from_user) down(&tmp_buf_sem); while (1) { /* Thanks to R. Wolff for suggesting how to do this with */ /* interrupts enabled */ c = count; t = ESP_XMIT_SIZE - info->xmit_cnt - 1; if (t < c) c = t; t = ESP_XMIT_SIZE - info->xmit_head; if (t < c) c = t; if (c <= 0) break; if (from_user) { c -= copy_from_user(tmp_buf, buf, c); if (!c) { if (!ret) ret = -EFAULT; break; } memcpy(info->xmit_buf + info->xmit_head, tmp_buf, c); } else memcpy(info->xmit_buf + info->xmit_head, buf, c); info->xmit_head = (info->xmit_head + c) & (ESP_XMIT_SIZE-1); info->xmit_cnt += c; buf += c; count -= c; ret += c; } if (from_user) up(&tmp_buf_sem); save_flags(flags); cli(); if (info->xmit_cnt && !tty->stopped && !(info->IER & UART_IER_THRI)) { info->IER |= UART_IER_THRI; serial_out(info, UART_ESI_CMD1, ESI_SET_SRV_MASK); serial_out(info, UART_ESI_CMD2, info->IER); } restore_flags(flags); return ret; } static int rs_write_room(struct tty_struct *tty) { struct esp_struct *info = (struct esp_struct *)tty->driver_data; int ret; if (serial_paranoia_check(info, tty->device, "rs_write_room")) return 0; ret = ESP_XMIT_SIZE - info->xmit_cnt - 1; if (ret < 0) ret = 0; return ret; } static int rs_chars_in_buffer(struct tty_struct *tty) { struct esp_struct *info = (struct esp_struct *)tty->driver_data; if (serial_paranoia_check(info, tty->device, "rs_chars_in_buffer")) return 0; return info->xmit_cnt; } static void rs_flush_buffer(struct tty_struct *tty) { struct esp_struct *info = (struct esp_struct *)tty->driver_data; if (serial_paranoia_check(info, tty->device, "rs_flush_buffer")) return; cli(); info->xmit_cnt = info->xmit_head = info->xmit_tail = 0; sti(); wake_up_interruptible(&tty->write_wait); if ((tty->flags & (1 << TTY_DO_WRITE_WAKEUP)) && tty->ldisc.write_wakeup) (tty->ldisc.write_wakeup)(tty); } /* * ------------------------------------------------------------ * rs_throttle() * * This routine is called by the upper-layer tty layer to signal that * incoming characters should be throttled. * ------------------------------------------------------------ */ static void rs_throttle(struct tty_struct * tty) { struct esp_struct *info = (struct esp_struct *)tty->driver_data; #ifdef SERIAL_DEBUG_THROTTLE char buf[64]; printk("throttle %s: %d....\n", tty_name(tty, buf), tty->ldisc.chars_in_buffer(tty)); #endif if (serial_paranoia_check(info, tty->device, "rs_throttle")) return; cli(); info->IER &= ~UART_IER_RDI; serial_out(info, UART_ESI_CMD1, ESI_SET_SRV_MASK); serial_out(info, UART_ESI_CMD2, info->IER); serial_out(info, UART_ESI_CMD1, ESI_SET_RX_TIMEOUT); serial_out(info, UART_ESI_CMD2, 0x00); sti(); } static void rs_unthrottle(struct tty_struct * tty) { struct esp_struct *info = (struct esp_struct *)tty->driver_data; #ifdef SERIAL_DEBUG_THROTTLE char buf[64]; printk("unthrottle %s: %d....\n", tty_name(tty, buf), tty->ldisc.chars_in_buffer(tty)); #endif if (serial_paranoia_check(info, tty->device, "rs_unthrottle")) return; cli(); info->IER |= UART_IER_RDI; serial_out(info, UART_ESI_CMD1, ESI_SET_SRV_MASK); serial_out(info, UART_ESI_CMD2, info->IER); serial_out(info, UART_ESI_CMD1, ESI_SET_RX_TIMEOUT); serial_out(info, UART_ESI_CMD2, info->config.rx_timeout); sti(); } /* * ------------------------------------------------------------ * rs_ioctl() and friends * ------------------------------------------------------------ */ static int get_serial_info(struct esp_struct * info, struct serial_struct * retinfo) { struct serial_struct tmp; if (!retinfo) return -EFAULT; memset(&tmp, 0, sizeof(tmp)); tmp.type = PORT_16550A; tmp.line = info->line; tmp.port = info->port; tmp.irq = info->irq; tmp.flags = info->flags; tmp.xmit_fifo_size = 1024; tmp.baud_base = BASE_BAUD; tmp.close_delay = info->close_delay; tmp.closing_wait = info->closing_wait; tmp.custom_divisor = info->custom_divisor; tmp.hub6 = 0; if (copy_to_user(retinfo,&tmp,sizeof(*retinfo))) return -EFAULT; return 0; } static int get_esp_config(struct esp_struct * info, struct hayes_esp_config * retinfo) { struct hayes_esp_config tmp; if (!retinfo) return -EFAULT; memset(&tmp, 0, sizeof(tmp)); tmp.rx_timeout = info->config.rx_timeout; tmp.rx_trigger = info->config.rx_trigger; tmp.tx_trigger = info->config.tx_trigger; tmp.flow_off = info->config.flow_off; tmp.flow_on = info->config.flow_on; tmp.pio_threshold = info->config.pio_threshold; tmp.dma_channel = (info->stat_flags & ESP_STAT_NEVER_DMA ? 0 : dma); if (copy_to_user(retinfo,&tmp,sizeof(*retinfo))) return -EFAULT; return 0; } static int set_serial_info(struct esp_struct * info, struct serial_struct * new_info) { struct serial_struct new_serial; struct esp_struct old_info; unsigned int change_irq; int retval = 0; struct esp_struct *current_async; if (copy_from_user(&new_serial,new_info,sizeof(new_serial))) return -EFAULT; old_info = *info; if ((new_serial.type != PORT_16550A) || (new_serial.hub6) || (info->port != new_serial.port) || (new_serial.baud_base != BASE_BAUD) || (new_serial.irq > 15) || (new_serial.irq < 2) || (new_serial.irq == 6) || (new_serial.irq == 8) || (new_serial.irq == 13)) return -EINVAL; change_irq = new_serial.irq != info->irq; if (change_irq && (info->line % 8)) return -EINVAL; if (!capable(CAP_SYS_ADMIN)) { if (change_irq || (new_serial.close_delay != info->close_delay) || ((new_serial.flags & ~ASYNC_USR_MASK) != (info->flags & ~ASYNC_USR_MASK))) return -EPERM; info->flags = ((info->flags & ~ASYNC_USR_MASK) | (new_serial.flags & ASYNC_USR_MASK)); info->custom_divisor = new_serial.custom_divisor; } else { if (new_serial.irq == 2) new_serial.irq = 9; if (change_irq) { current_async = ports; while (current_async) { if ((current_async->line >= info->line) && (current_async->line < (info->line + 8))) { if (current_async == info) { if (current_async->count > 1) return -EBUSY; } else if (current_async->count) return -EBUSY; } current_async = current_async->next_port; } } /* * OK, past this point, all the error checking has been done. * At this point, we start making changes..... */ info->flags = ((info->flags & ~ASYNC_FLAGS) | (new_serial.flags & ASYNC_FLAGS)); info->custom_divisor = new_serial.custom_divisor; info->close_delay = new_serial.close_delay * HZ/100; info->closing_wait = new_serial.closing_wait * HZ/100; if (change_irq) { /* * We need to shutdown the serial port at the old * port/irq combination. */ shutdown(info); current_async = ports; while (current_async) { if ((current_async->line >= info->line) && (current_async->line < (info->line + 8))) current_async->irq = new_serial.irq; current_async = current_async->next_port; } serial_out(info, UART_ESI_CMD1, ESI_SET_ENH_IRQ); if (info->irq == 9) serial_out(info, UART_ESI_CMD2, 0x02); else serial_out(info, UART_ESI_CMD2, info->irq); } } if (info->flags & ASYNC_INITIALIZED) { if (((old_info.flags & ASYNC_SPD_MASK) != (info->flags & ASYNC_SPD_MASK)) || (old_info.custom_divisor != info->custom_divisor)) { if ((info->flags & ASYNC_SPD_MASK) == ASYNC_SPD_HI) info->tty->alt_speed = 57600; if ((info->flags & ASYNC_SPD_MASK) == ASYNC_SPD_VHI) info->tty->alt_speed = 115200; if ((info->flags & ASYNC_SPD_MASK) == ASYNC_SPD_SHI) info->tty->alt_speed = 230400; if ((info->flags & ASYNC_SPD_MASK) == ASYNC_SPD_WARP) info->tty->alt_speed = 460800; change_speed(info); } } else retval = startup(info); return retval; } static int set_esp_config(struct esp_struct * info, struct hayes_esp_config * new_info) { struct hayes_esp_config new_config; unsigned int change_dma; int retval = 0; struct esp_struct *current_async; /* Perhaps a non-sysadmin user should be able to do some of these */ /* operations. I haven't decided yet. */ if (!capable(CAP_SYS_ADMIN)) return -EPERM; if (copy_from_user(&new_config, new_info, sizeof(new_config))) return -EFAULT; if ((new_config.flow_on >= new_config.flow_off) || (new_config.rx_trigger < 1) || (new_config.tx_trigger < 1) || (new_config.flow_off < 1) || (new_config.flow_on < 1) || (new_config.rx_trigger > 1023) || (new_config.tx_trigger > 1023) || (new_config.flow_off > 1023) || (new_config.flow_on > 1023) || (new_config.pio_threshold < 0) || (new_config.pio_threshold > 1024)) return -EINVAL; if ((new_config.dma_channel != 1) && (new_config.dma_channel != 3)) new_config.dma_channel = 0; if (info->stat_flags & ESP_STAT_NEVER_DMA) change_dma = new_config.dma_channel; else change_dma = (new_config.dma_channel != dma); if (change_dma) { if (new_config.dma_channel) { /* PIO mode to DMA mode transition OR */ /* change current DMA channel */ current_async = ports; while (current_async) { if (current_async == info) { if (current_async->count > 1) return -EBUSY; } else if (current_async->count) return -EBUSY; current_async = current_async->next_port; } shutdown(info); dma = new_config.dma_channel; info->stat_flags &= ~ESP_STAT_NEVER_DMA; /* all ports must use the same DMA channel */ current_async = ports; while (current_async) { esp_basic_init(current_async); current_async = current_async->next_port; } } else { /* DMA mode to PIO mode only */ if (info->count > 1) return -EBUSY; shutdown(info); info->stat_flags |= ESP_STAT_NEVER_DMA; esp_basic_init(info); } } info->config.pio_threshold = new_config.pio_threshold; if ((new_config.flow_off != info->config.flow_off) || (new_config.flow_on != info->config.flow_on)) { unsigned long flags; info->config.flow_off = new_config.flow_off; info->config.flow_on = new_config.flow_on; save_flags(flags); cli(); serial_out(info, UART_ESI_CMD1, ESI_SET_FLOW_LVL); serial_out(info, UART_ESI_CMD2, new_config.flow_off >> 8); serial_out(info, UART_ESI_CMD2, new_config.flow_off); serial_out(info, UART_ESI_CMD2, new_config.flow_on >> 8); serial_out(info, UART_ESI_CMD2, new_config.flow_on); restore_flags(flags); } if ((new_config.rx_trigger != info->config.rx_trigger) || (new_config.tx_trigger != info->config.tx_trigger)) { unsigned long flags; info->config.rx_trigger = new_config.rx_trigger; info->config.tx_trigger = new_config.tx_trigger; save_flags(flags); cli(); serial_out(info, UART_ESI_CMD1, ESI_SET_TRIGGER); serial_out(info, UART_ESI_CMD2, new_config.rx_trigger >> 8); serial_out(info, UART_ESI_CMD2, new_config.rx_trigger); serial_out(info, UART_ESI_CMD2, new_config.tx_trigger >> 8); serial_out(info, UART_ESI_CMD2, new_config.tx_trigger); restore_flags(flags); } if (new_config.rx_timeout != info->config.rx_timeout) { unsigned long flags; info->config.rx_timeout = new_config.rx_timeout; save_flags(flags); cli(); if (info->IER & UART_IER_RDI) { serial_out(info, UART_ESI_CMD1, ESI_SET_RX_TIMEOUT); serial_out(info, UART_ESI_CMD2, new_config.rx_timeout); } restore_flags(flags); } if (!(info->flags & ASYNC_INITIALIZED)) retval = startup(info); return retval; } /* * get_lsr_info - get line status register info * * Purpose: Let user call ioctl() to get info when the UART physically * is emptied. On bus types like RS485, the transmitter must * release the bus after transmitting. This must be done when * the transmit shift register is empty, not be done when the * transmit holding register is empty. This functionality * allows an RS485 driver to be written in user space. */ static int get_lsr_info(struct esp_struct * info, unsigned int *value) { unsigned char status; unsigned int result; cli(); serial_out(info, UART_ESI_CMD1, ESI_GET_UART_STAT); status = serial_in(info, UART_ESI_STAT1); sti(); result = ((status & UART_LSR_TEMT) ? TIOCSER_TEMT : 0); return put_user(result,value); } static int get_modem_info(struct esp_struct * info, unsigned int *value) { unsigned char control, status; unsigned int result; control = info->MCR; cli(); serial_out(info, UART_ESI_CMD1, ESI_GET_UART_STAT); status = serial_in(info, UART_ESI_STAT2); sti(); result = ((control & UART_MCR_RTS) ? TIOCM_RTS : 0) | ((control & UART_MCR_DTR) ? TIOCM_DTR : 0) | ((status & UART_MSR_DCD) ? TIOCM_CAR : 0) | ((status & UART_MSR_RI) ? TIOCM_RNG : 0) | ((status & UART_MSR_DSR) ? TIOCM_DSR : 0) | ((status & UART_MSR_CTS) ? TIOCM_CTS : 0); return put_user(result,value); } static int set_modem_info(struct esp_struct * info, unsigned int cmd, unsigned int *value) { int error; unsigned int arg; error = get_user(arg, value); if (error) return error; switch (cmd) { case TIOCMBIS: if (arg & TIOCM_RTS) info->MCR |= UART_MCR_RTS; if (arg & TIOCM_DTR) info->MCR |= UART_MCR_DTR; break; case TIOCMBIC: if (arg & TIOCM_RTS) info->MCR &= ~UART_MCR_RTS; if (arg & TIOCM_DTR) info->MCR &= ~UART_MCR_DTR; break; case TIOCMSET: info->MCR = ((info->MCR & ~(UART_MCR_RTS | UART_MCR_DTR)) | ((arg & TIOCM_RTS) ? UART_MCR_RTS : 0) | ((arg & TIOCM_DTR) ? UART_MCR_DTR : 0)); break; default: return -EINVAL; } cli(); serial_out(info, UART_ESI_CMD1, ESI_WRITE_UART); serial_out(info, UART_ESI_CMD2, UART_MCR); serial_out(info, UART_ESI_CMD2, info->MCR); sti(); return 0; } /* * rs_break() --- routine which turns the break handling on or off */ static void esp_break(struct tty_struct *tty, int break_state) { struct esp_struct * info = (struct esp_struct *)tty->driver_data; unsigned long flags; if (serial_paranoia_check(info, tty->device, "esp_break")) return; save_flags(flags); cli(); if (break_state == -1) { serial_out(info, UART_ESI_CMD1, ESI_ISSUE_BREAK); serial_out(info, UART_ESI_CMD2, 0x01); interruptible_sleep_on(&info->break_wait); } else { serial_out(info, UART_ESI_CMD1, ESI_ISSUE_BREAK); serial_out(info, UART_ESI_CMD2, 0x00); } restore_flags(flags); } static int rs_ioctl(struct tty_struct *tty, struct file * file, unsigned int cmd, unsigned long arg) { int error; struct esp_struct * info = (struct esp_struct *)tty->driver_data; struct async_icount cprev, cnow; /* kernel counter temps */ struct serial_icounter_struct *p_cuser; /* user space */ if (serial_paranoia_check(info, tty->device, "rs_ioctl")) return -ENODEV; if ((cmd != TIOCGSERIAL) && (cmd != TIOCSSERIAL) && (cmd != TIOCSERCONFIG) && (cmd != TIOCSERGWILD) && (cmd != TIOCSERSWILD) && (cmd != TIOCSERGSTRUCT) && (cmd != TIOCMIWAIT) && (cmd != TIOCGICOUNT) && (cmd != TIOCGHAYESESP) && (cmd != TIOCSHAYESESP)) { if (tty->flags & (1 << TTY_IO_ERROR)) return -EIO; } switch (cmd) { case TIOCMGET: return get_modem_info(info, (unsigned int *) arg); case TIOCMBIS: case TIOCMBIC: case TIOCMSET: return set_modem_info(info, cmd, (unsigned int *) arg); case TIOCGSERIAL: return get_serial_info(info, (struct serial_struct *) arg); case TIOCSSERIAL: return set_serial_info(info, (struct serial_struct *) arg); case TIOCSERCONFIG: /* do not reconfigure after initial configuration */ return 0; case TIOCSERGWILD: return put_user(0L, (unsigned long *) arg); case TIOCSERGETLSR: /* Get line status register */ return get_lsr_info(info, (unsigned int *) arg); case TIOCSERSWILD: if (!suser()) return -EPERM; return 0; /* * Wait for any of the 4 modem inputs (DCD,RI,DSR,CTS) to change * - mask passed in arg for lines of interest * (use |'ed TIOCM_RNG/DSR/CD/CTS for masking) * Caller should use TIOCGICOUNT to see which one it was */ case TIOCMIWAIT: cli(); cprev = info->icount; /* note the counters on entry */ sti(); while (1) { interruptible_sleep_on(&info->delta_msr_wait); /* see if a signal did it */ if (signal_pending(current)) return -ERESTARTSYS; cli(); cnow = info->icount; /* atomic copy */ sti(); if (cnow.rng == cprev.rng && cnow.dsr == cprev.dsr && cnow.dcd == cprev.dcd && cnow.cts == cprev.cts) return -EIO; /* no change => error */ if ( ((arg & TIOCM_RNG) && (cnow.rng != cprev.rng)) || ((arg & TIOCM_DSR) && (cnow.dsr != cprev.dsr)) || ((arg & TIOCM_CD) && (cnow.dcd != cprev.dcd)) || ((arg & TIOCM_CTS) && (cnow.cts != cprev.cts)) ) { return 0; } cprev = cnow; } /* NOTREACHED */ /* * Get counter of input serial line interrupts (DCD,RI,DSR,CTS) * Return: write counters to the user passed counter struct * NB: both 1->0 and 0->1 transitions are counted except for * RI where only 0->1 is counted. */ case TIOCGICOUNT: cli(); cnow = info->icount; sti(); p_cuser = (struct serial_icounter_struct *) arg; if ((error = put_user(cnow.cts, &p_cuser->cts))) return error; if ((error = put_user(cnow.dsr, &p_cuser->dsr))) return error; if ((error = put_user(cnow.rng, &p_cuser->rng))) return error; if ((error = put_user(cnow.dcd, &p_cuser->dcd))) return error; return 0; case TIOCGHAYESESP: return (get_esp_config(info, (struct hayes_esp_config *)arg)); case TIOCSHAYESESP: return (set_esp_config(info, (struct hayes_esp_config *)arg)); default: return -ENOIOCTLCMD; } return 0; } static void rs_set_termios(struct tty_struct *tty, struct termios *old_termios) { struct esp_struct *info = (struct esp_struct *)tty->driver_data; if ( (tty->termios->c_cflag == old_termios->c_cflag) && ( RELEVANT_IFLAG(tty->termios->c_iflag) == RELEVANT_IFLAG(old_termios->c_iflag))) return; change_speed(info); /* Handle transition to B0 status */ if ((old_termios->c_cflag & CBAUD) && !(tty->termios->c_cflag & CBAUD)) { info->MCR &= ~(UART_MCR_DTR|UART_MCR_RTS); cli(); serial_out(info, UART_ESI_CMD1, ESI_WRITE_UART); serial_out(info, UART_ESI_CMD2, UART_MCR); serial_out(info, UART_ESI_CMD2, info->MCR); sti(); } /* Handle transition away from B0 status */ if (!(old_termios->c_cflag & CBAUD) && (tty->termios->c_cflag & CBAUD)) { info->MCR |= (UART_MCR_DTR | UART_MCR_RTS); cli(); serial_out(info, UART_ESI_CMD1, ESI_WRITE_UART); serial_out(info, UART_ESI_CMD2, UART_MCR); serial_out(info, UART_ESI_CMD2, info->MCR); sti(); } /* Handle turning of CRTSCTS */ if ((old_termios->c_cflag & CRTSCTS) && !(tty->termios->c_cflag & CRTSCTS)) { rs_start(tty); } #if 0 /* * No need to wake up processes in open wait, since they * sample the CLOCAL flag once, and don't recheck it. * XXX It's not clear whether the current behavior is correct * or not. Hence, this may change..... */ if (!(old_termios->c_cflag & CLOCAL) && (tty->termios->c_cflag & CLOCAL)) wake_up_interruptible(&info->open_wait); #endif } /* * ------------------------------------------------------------ * rs_close() * * This routine is called when the serial port gets closed. First, we * wait for the last remaining data to be sent. Then, we unlink its * async structure from the interrupt chain if necessary, and we free * that IRQ if nothing is left in the chain. * ------------------------------------------------------------ */ static void rs_close(struct tty_struct *tty, struct file * filp) { struct esp_struct * info = (struct esp_struct *)tty->driver_data; unsigned long flags; if (!info || serial_paranoia_check(info, tty->device, "rs_close")) return; save_flags(flags); cli(); if (tty_hung_up_p(filp)) { DBG_CNT("before DEC-hung"); MOD_DEC_USE_COUNT; restore_flags(flags); return; } #ifdef SERIAL_DEBUG_OPEN printk("rs_close ttys%d, count = %d\n", info->line, info->count); #endif if ((tty->count == 1) && (info->count != 1)) { /* * Uh, oh. tty->count is 1, which means that the tty * structure will be freed. Info->count should always * be one in these conditions. If it's greater than * one, we've got real problems, since it means the * serial port won't be shutdown. */ printk("rs_close: bad serial port count; tty->count is 1, " "info->count is %d\n", info->count); info->count = 1; } if (--info->count < 0) { printk("rs_close: bad serial port count for ttys%d: %d\n", info->line, info->count); info->count = 0; } if (info->count) { DBG_CNT("before DEC-2"); MOD_DEC_USE_COUNT; restore_flags(flags); return; } info->flags |= ASYNC_CLOSING; /* * Save the termios structure, since this port may have * separate termios for callout and dialin. */ if (info->flags & ASYNC_NORMAL_ACTIVE) info->normal_termios = *tty->termios; if (info->flags & ASYNC_CALLOUT_ACTIVE) info->callout_termios = *tty->termios; /* * Now we wait for the transmit buffer to clear; and we notify * the line discipline to only process XON/XOFF characters. */ tty->closing = 1; if (info->closing_wait != ASYNC_CLOSING_WAIT_NONE) tty_wait_until_sent(tty, info->closing_wait); /* * At this point we stop accepting input. To do this, we * disable the receive line status interrupts, and tell the * interrupt driver to stop checking the data ready bit in the * line status register. */ /* info->IER &= ~UART_IER_RLSI; */ info->IER &= ~UART_IER_RDI; info->read_status_mask &= ~UART_LSR_DR; if (info->flags & ASYNC_INITIALIZED) { serial_out(info, UART_ESI_CMD1, ESI_SET_SRV_MASK); serial_out(info, UART_ESI_CMD2, info->IER); /* disable receive timeout */ serial_out(info, UART_ESI_CMD1, ESI_SET_RX_TIMEOUT); serial_out(info, UART_ESI_CMD2, 0x00); /* * Before we drop DTR, make sure the UART transmitter * has completely drained; this is especially * important if there is a transmit FIFO! */ rs_wait_until_sent(tty, info->timeout); } shutdown(info); if (tty->driver.flush_buffer) tty->driver.flush_buffer(tty); if (tty->ldisc.flush_buffer) tty->ldisc.flush_buffer(tty); tty->closing = 0; info->event = 0; info->tty = 0; if (info->blocked_open) { if (info->close_delay) { current->state = TASK_INTERRUPTIBLE; schedule_timeout(info->close_delay); } wake_up_interruptible(&info->open_wait); } info->flags &= ~(ASYNC_NORMAL_ACTIVE|ASYNC_CALLOUT_ACTIVE| ASYNC_CLOSING); wake_up_interruptible(&info->close_wait); MOD_DEC_USE_COUNT; restore_flags(flags); } static void rs_wait_until_sent(struct tty_struct *tty, int timeout) { struct esp_struct *info = (struct esp_struct *)tty->driver_data; unsigned long orig_jiffies, char_time; unsigned long flags; if (serial_paranoia_check(info, tty->device, "rs_wait_until_sent")) return; orig_jiffies = jiffies; char_time = ((info->timeout - HZ / 50) / 1024) / 5; if (!char_time) char_time = 1; save_flags(flags); cli(); serial_out(info, UART_ESI_CMD1, ESI_NO_COMMAND); serial_out(info, UART_ESI_CMD1, ESI_GET_TX_AVAIL); while ((serial_in(info, UART_ESI_STAT1) != 0x03) || (serial_in(info, UART_ESI_STAT2) != 0xff)) { current->state = TASK_INTERRUPTIBLE; schedule_timeout(char_time); if (signal_pending(current)) break; if (timeout && ((orig_jiffies + timeout) < jiffies)) break; serial_out(info, UART_ESI_CMD1, ESI_NO_COMMAND); serial_out(info, UART_ESI_CMD1, ESI_GET_TX_AVAIL); } restore_flags(flags); current->state = TASK_RUNNING; } /* * esp_hangup() --- called by tty_hangup() when a hangup is signaled. */ static void esp_hangup(struct tty_struct *tty) { struct esp_struct * info = (struct esp_struct *)tty->driver_data; if (serial_paranoia_check(info, tty->device, "esp_hangup")) return; rs_flush_buffer(tty); shutdown(info); info->event = 0; info->count = 0; info->flags &= ~(ASYNC_NORMAL_ACTIVE|ASYNC_CALLOUT_ACTIVE); info->tty = 0; wake_up_interruptible(&info->open_wait); } /* * ------------------------------------------------------------ * esp_open() and friends * ------------------------------------------------------------ */ static int block_til_ready(struct tty_struct *tty, struct file * filp, struct esp_struct *info) { DECLARE_WAITQUEUE(wait, current); int retval; int do_clocal = 0; /* * If the device is in the middle of being closed, then block * until it's done, and then try again. */ if (tty_hung_up_p(filp) || (info->flags & ASYNC_CLOSING)) { if (info->flags & ASYNC_CLOSING) interruptible_sleep_on(&info->close_wait); #ifdef SERIAL_DO_RESTART if (info->flags & ASYNC_HUP_NOTIFY) return -EAGAIN; else return -ERESTARTSYS; #else return -EAGAIN; #endif } /* * If this is a callout device, then just make sure the normal * device isn't being used. */ if (tty->driver.subtype == SERIAL_TYPE_CALLOUT) { if (info->flags & ASYNC_NORMAL_ACTIVE) return -EBUSY; if ((info->flags & ASYNC_CALLOUT_ACTIVE) && (info->flags & ASYNC_SESSION_LOCKOUT) && (info->session != current->session)) return -EBUSY; if ((info->flags & ASYNC_CALLOUT_ACTIVE) && (info->flags & ASYNC_PGRP_LOCKOUT) && (info->pgrp != current->pgrp)) return -EBUSY; info->flags |= ASYNC_CALLOUT_ACTIVE; return 0; } /* * If non-blocking mode is set, or the port is not enabled, * then make the check up front and then exit. */ if ((filp->f_flags & O_NONBLOCK) || (tty->flags & (1 << TTY_IO_ERROR))) { if (info->flags & ASYNC_CALLOUT_ACTIVE) return -EBUSY; info->flags |= ASYNC_NORMAL_ACTIVE; return 0; } if (info->flags & ASYNC_CALLOUT_ACTIVE) { if (info->normal_termios.c_cflag & CLOCAL) do_clocal = 1; } else { if (tty->termios->c_cflag & CLOCAL) do_clocal = 1; } /* * Block waiting for the carrier detect and the line to become * free (i.e., not in use by the callout). While we are in * this loop, info->count is dropped by one, so that * rs_close() knows when to free things. We restore it upon * exit, either normal or abnormal. */ retval = 0; add_wait_queue(&info->open_wait, &wait); #ifdef SERIAL_DEBUG_OPEN printk("block_til_ready before block: ttys%d, count = %d\n", info->line, info->count); #endif cli(); if (!tty_hung_up_p(filp)) info->count--; sti(); info->blocked_open++; while (1) { cli(); if (!(info->flags & ASYNC_CALLOUT_ACTIVE) && (tty->termios->c_cflag & CBAUD)) { unsigned int scratch; serial_out(info, UART_ESI_CMD1, ESI_READ_UART); serial_out(info, UART_ESI_CMD2, UART_MCR); scratch = serial_in(info, UART_ESI_STAT1); serial_out(info, UART_ESI_CMD1, ESI_WRITE_UART); serial_out(info, UART_ESI_CMD2, UART_MCR); serial_out(info, UART_ESI_CMD2, scratch | UART_MCR_DTR | UART_MCR_RTS); } sti(); set_current_state(TASK_INTERRUPTIBLE); if (tty_hung_up_p(filp) || !(info->flags & ASYNC_INITIALIZED)) { #ifdef SERIAL_DO_RESTART if (info->flags & ASYNC_HUP_NOTIFY) retval = -EAGAIN; else retval = -ERESTARTSYS; #else retval = -EAGAIN; #endif break; } serial_out(info, UART_ESI_CMD1, ESI_GET_UART_STAT); if (serial_in(info, UART_ESI_STAT2) & UART_MSR_DCD) do_clocal = 1; if (!(info->flags & ASYNC_CALLOUT_ACTIVE) && !(info->flags & ASYNC_CLOSING) && (do_clocal)) break; if (signal_pending(current)) { retval = -ERESTARTSYS; break; } #ifdef SERIAL_DEBUG_OPEN printk("block_til_ready blocking: ttys%d, count = %d\n", info->line, info->count); #endif schedule(); } current->state = TASK_RUNNING; remove_wait_queue(&info->open_wait, &wait); if (!tty_hung_up_p(filp)) info->count++; info->blocked_open--; #ifdef SERIAL_DEBUG_OPEN printk("block_til_ready after blocking: ttys%d, count = %d\n", info->line, info->count); #endif if (retval) return retval; info->flags |= ASYNC_NORMAL_ACTIVE; return 0; } /* * This routine is called whenever a serial port is opened. It * enables interrupts for a serial port, linking in its async structure into * the IRQ chain. It also performs the serial-specific * initialization for the tty structure. */ static int esp_open(struct tty_struct *tty, struct file * filp) { struct esp_struct *info; int retval, line; unsigned long page; line = MINOR(tty->device) - tty->driver.minor_start; if ((line < 0) || (line >= NR_PORTS)) return -ENODEV; /* find the port in the chain */ info = ports; while (info && (info->line != line)) info = info->next_port; if (!info) { serial_paranoia_check(info, tty->device, "esp_open"); return -ENODEV; } #ifdef SERIAL_DEBUG_OPEN printk("esp_open %s%d, count = %d\n", tty->driver.name, info->line, info->count); #endif MOD_INC_USE_COUNT; info->count++; tty->driver_data = info; info->tty = tty; if (!tmp_buf) { page = get_free_page(GFP_KERNEL); if (!page) return -ENOMEM; if (tmp_buf) free_page(page); else tmp_buf = (unsigned char *) page; } /* * Start up serial port */ retval = startup(info); if (retval) return retval; retval = block_til_ready(tty, filp, info); if (retval) { #ifdef SERIAL_DEBUG_OPEN printk("esp_open returning after block_til_ready with %d\n", retval); #endif return retval; } if ((info->count == 1) && (info->flags & ASYNC_SPLIT_TERMIOS)) { if (tty->driver.subtype == SERIAL_TYPE_NORMAL) *tty->termios = info->normal_termios; else *tty->termios = info->callout_termios; change_speed(info); } info->session = current->session; info->pgrp = current->pgrp; #ifdef SERIAL_DEBUG_OPEN printk("esp_open ttys%d successful...", info->line); #endif return 0; } /* * --------------------------------------------------------------------- * espserial_init() and friends * * espserial_init() is called at boot-time to initialize the serial driver. * --------------------------------------------------------------------- */ /* * This routine prints out the appropriate serial driver version * number, and identifies which options were configured into this * driver. */ static _INLINE_ void show_serial_version(void) { printk(KERN_INFO "%s version %s (DMA %u)\n", serial_name, serial_version, dma); } /* * This routine is called by espserial_init() to initialize a specific serial * port. */ static _INLINE_ int autoconfig(struct esp_struct * info, int *region_start) { int port_detected = 0; unsigned long flags; save_flags(flags); cli(); /* * Check for ESP card */ if (!check_region(info->port, 8) && serial_in(info, UART_ESI_BASE) == 0xf3) { serial_out(info, UART_ESI_CMD1, 0x00); serial_out(info, UART_ESI_CMD1, 0x01); if ((serial_in(info, UART_ESI_STAT2) & 0x70) == 0x20) { port_detected = 1; if (!(info->irq)) { serial_out(info, UART_ESI_CMD1, 0x02); if (serial_in(info, UART_ESI_STAT1) & 0x01) info->irq = 3; else info->irq = 4; } if (ports && (ports->port == (info->port - 8))) { release_region(*region_start, info->port - *region_start); } else *region_start = info->port; request_region(*region_start, info->port - *region_start + 8, "esp serial"); /* put card in enhanced mode */ /* this prevents access through */ /* the "old" IO ports */ esp_basic_init(info); /* clear out MCR */ serial_out(info, UART_ESI_CMD1, ESI_WRITE_UART); serial_out(info, UART_ESI_CMD2, UART_MCR); serial_out(info, UART_ESI_CMD2, 0x00); } } restore_flags(flags); return (port_detected); } /* * The serial driver boot-time initialization code! */ int __init espserial_init(void) { int i, offset; int region_start; struct esp_struct * info; struct esp_struct *last_primary = 0; int esp[] = {0x100,0x140,0x180,0x200,0x240,0x280,0x300,0x380}; init_bh(ESP_BH, do_serial_bh); for (i = 0; i < NR_PRIMARY; i++) { if (irq[i] != 0) { if ((irq[i] < 2) || (irq[i] > 15) || (irq[i] == 6) || (irq[i] == 8) || (irq[i] == 13)) irq[i] = 0; else if (irq[i] == 2) irq[i] = 9; } } if ((dma != 1) && (dma != 3)) dma = 0; if ((rx_trigger < 1) || (rx_trigger > 1023)) rx_trigger = 768; if ((tx_trigger < 1) || (tx_trigger > 1023)) tx_trigger = 768; if ((flow_off < 1) || (flow_off > 1023)) flow_off = 1016; if ((flow_on < 1) || (flow_on > 1023)) flow_on = 944; if ((rx_timeout < 0) || (rx_timeout > 255)) rx_timeout = 128; if (flow_on >= flow_off) flow_on = flow_off - 1; show_serial_version(); /* Initialize the tty_driver structure */ memset(&esp_driver, 0, sizeof(struct tty_driver)); esp_driver.magic = TTY_DRIVER_MAGIC; esp_driver.name = "ttyP"; esp_driver.major = ESP_IN_MAJOR; esp_driver.minor_start = 0; esp_driver.num = NR_PORTS; esp_driver.type = TTY_DRIVER_TYPE_SERIAL; esp_driver.subtype = SERIAL_TYPE_NORMAL; esp_driver.init_termios = tty_std_termios; esp_driver.init_termios.c_cflag = B9600 | CS8 | CREAD | HUPCL | CLOCAL; esp_driver.flags = TTY_DRIVER_REAL_RAW; esp_driver.refcount = &serial_refcount; esp_driver.table = serial_table; esp_driver.termios = serial_termios; esp_driver.termios_locked = serial_termios_locked; esp_driver.open = esp_open; esp_driver.close = rs_close; esp_driver.write = rs_write; esp_driver.put_char = rs_put_char; esp_driver.flush_chars = rs_flush_chars; esp_driver.write_room = rs_write_room; esp_driver.chars_in_buffer = rs_chars_in_buffer; esp_driver.flush_buffer = rs_flush_buffer; esp_driver.ioctl = rs_ioctl; esp_driver.throttle = rs_throttle; esp_driver.unthrottle = rs_unthrottle; esp_driver.set_termios = rs_set_termios; esp_driver.stop = rs_stop; esp_driver.start = rs_start; esp_driver.hangup = esp_hangup; esp_driver.break_ctl = esp_break; esp_driver.wait_until_sent = rs_wait_until_sent; /* * The callout device is just like normal device except for * major number and the subtype code. */ esp_callout_driver = esp_driver; esp_callout_driver.name = "cup"; esp_callout_driver.major = ESP_OUT_MAJOR; esp_callout_driver.subtype = SERIAL_TYPE_CALLOUT; if (tty_register_driver(&esp_driver)) { printk(KERN_ERR "Couldn't register esp serial driver"); return 1; } if (tty_register_driver(&esp_callout_driver)) { printk(KERN_ERR "Couldn't register esp callout driver"); tty_unregister_driver(&esp_driver); return 1; } info = (struct esp_struct *)kmalloc(sizeof(struct esp_struct), GFP_KERNEL); if (!info) { printk(KERN_ERR "Couldn't allocate memory for esp serial device information\n"); tty_unregister_driver(&esp_driver); tty_unregister_driver(&esp_callout_driver); return 1; } memset((void *)info, 0, sizeof(struct esp_struct)); /* rx_trigger, tx_trigger are needed by autoconfig */ info->config.rx_trigger = rx_trigger; info->config.tx_trigger = tx_trigger; i = 0; offset = 0; do { info->port = esp[i] + offset; info->irq = irq[i]; info->line = (i * 8) + (offset / 8); if (!autoconfig(info, &region_start)) { i++; offset = 0; continue; } info->custom_divisor = (divisor[i] >> (offset / 2)) & 0xf; info->flags = STD_COM_FLAGS; if (info->custom_divisor) info->flags |= ASYNC_SPD_CUST; info->magic = ESP_MAGIC; info->close_delay = 5*HZ/10; info->closing_wait = 30*HZ; info->tqueue.routine = do_softint; info->tqueue.data = info; info->tqueue_hangup.routine = do_serial_hangup; info->tqueue_hangup.data = info; info->callout_termios = esp_callout_driver.init_termios; info->normal_termios = esp_driver.init_termios; info->config.rx_timeout = rx_timeout; info->config.flow_on = flow_on; info->config.flow_off = flow_off; info->config.pio_threshold = pio_threshold; info->next_port = ports; init_waitqueue_head(&info->open_wait); init_waitqueue_head(&info->close_wait); init_waitqueue_head(&info->delta_msr_wait); init_waitqueue_head(&info->break_wait); ports = info; printk(KERN_INFO "ttyP%d at 0x%04x (irq = %d) is an ESP ", info->line, info->port, info->irq); if (info->line % 8) { printk("secondary port\n"); /* 8 port cards can't do DMA */ info->stat_flags |= ESP_STAT_NEVER_DMA; if (last_primary) last_primary->stat_flags |= ESP_STAT_NEVER_DMA; } else { printk("primary port\n"); last_primary = info; irq[i] = info->irq; } if (!dma) info->stat_flags |= ESP_STAT_NEVER_DMA; info = (struct esp_struct *)kmalloc(sizeof(struct esp_struct), GFP_KERNEL); if (!info) { printk(KERN_ERR "Couldn't allocate memory for esp serial device information\n"); /* allow use of the already detected ports */ return 0; } memset((void *)info, 0, sizeof(struct esp_struct)); /* rx_trigger, tx_trigger are needed by autoconfig */ info->config.rx_trigger = rx_trigger; info->config.tx_trigger = tx_trigger; if (offset == 56) { i++; offset = 0; } else { offset += 8; } } while (i < NR_PRIMARY); /* free the last port memory allocation */ kfree(info); return 0; } #ifdef MODULE int init_module(void) { return espserial_init(); } void cleanup_module(void) { unsigned long flags; int e1, e2; unsigned int region_start, region_end; struct esp_struct *temp_async; struct esp_pio_buffer *pio_buf; /* printk("Unloading %s: version %s\n", serial_name, serial_version); */ save_flags(flags); cli(); remove_bh(ESP_BH); if ((e1 = tty_unregister_driver(&esp_driver))) printk("SERIAL: failed to unregister serial driver (%d)\n", e1); if ((e2 = tty_unregister_driver(&esp_callout_driver))) printk("SERIAL: failed to unregister callout driver (%d)\n", e2); restore_flags(flags); while (ports) { if (ports->port) { region_start = region_end = ports->port; temp_async = ports; while (temp_async) { if ((region_start - temp_async->port) == 8) { region_start = temp_async->port; temp_async->port = 0; temp_async = ports; } else if ((temp_async->port - region_end) == 8) { region_end = temp_async->port; temp_async->port = 0; temp_async = ports; } else temp_async = temp_async->next_port; } release_region(region_start, region_end - region_start + 8); } temp_async = ports->next_port; kfree(ports); ports = temp_async; } if (dma_buffer) free_pages((unsigned int)dma_buffer, get_order(DMA_BUFFER_SZ)); if (tmp_buf) free_page((unsigned long)tmp_buf); while (free_pio_buf) { pio_buf = free_pio_buf->next; kfree(free_pio_buf); free_pio_buf = pio_buf; } } #endif /* MODULE */
snike4342/linux-2.4.0
drivers/char/esp.c
C
gpl-2.0
73,599
/* * File : interrupt.c * This file is part of RT-Thread RTOS * COPYRIGHT (C) 2009, RT-Thread Development Team * * The license and distribution terms for this file may be * found in the file LICENSE in this distribution or at * http://www.rt-thread.org/license/LICENSE * * Change Logs: * Date Author Notes * 2009-01-05 Bernard first version */ #include <rtthread.h> #include <asm/ppc4xx.h> #include <asm/processor.h> /* interrupt nest */ extern volatile rt_uint8_t rt_interrupt_nest; /* exception and interrupt handler table */ #define MAX_HANDLERS 32 rt_isr_handler_t isr_table[MAX_HANDLERS]; rt_uint32_t rt_interrupt_from_thread, rt_interrupt_to_thread; rt_uint32_t rt_thread_switch_interrput_flag; rt_isr_handler_t rt_hw_interrupt_handle(rt_uint32_t vector) { rt_kprintf("Unhandled interrupt %d occured!!!\n", vector); return RT_NULL; } void uic_irq_ack(unsigned int vec) { mtdcr(uic0sr, UIC_MASK(vec)); } void uic_int_handler (unsigned int vec) { rt_interrupt_enter(); /* Allow external interrupts to the CPU. */ if (isr_table [vec] != 0) { (*isr_table[vec])(vec); } uic_irq_ack(vec); rt_interrupt_leave(); } /* handler for UIC interrupt */ void uic_interrupt(rt_uint32_t uic_base, int vec_base) { int vec; rt_uint32_t uic_msr; rt_uint32_t msr_shift; /* * Read masked interrupt status register to determine interrupt source */ uic_msr = get_dcr(uic_base + UIC_MSR); msr_shift = uic_msr; vec = vec_base; while (msr_shift != 0) { if (msr_shift & 0x80000000) uic_int_handler(vec); /* * Shift msr to next position and increment vector */ msr_shift <<= 1; vec++; } } void rt_hw_interrupt_install(int vector, rt_isr_handler_t new_handler, rt_isr_handler_t *old_handler) { int intVal; if (((int)vector < 0) || ((int) vector >= MAX_HANDLERS)) { return; /* out of range */ } /* install the handler in the system interrupt table */ intVal = rt_hw_interrupt_disable (); /* lock interrupts to prevent races */ if (*old_handler != RT_NULL) *old_handler = isr_table[vector]; if (new_handler != RT_NULL) isr_table[vector] = new_handler; rt_hw_interrupt_enable (intVal); } void rt_hw_interrupt_mask(int vector) { mtdcr(uic0er, mfdcr(uic0er) & ~UIC_MASK(vector)); } void rt_hw_interrupt_unmask(int vector) { mtdcr(uic0er, mfdcr(uic0er) | UIC_MASK(vector)); } void rt_hw_interrupt_init() { int vector; rt_uint32_t pit_value; pit_value = RT_TICK_PER_SECOND * (100000000 / RT_CPU_FREQ); /* enable pit */ mtspr(SPRN_PIT, pit_value); mtspr(SPRN_TCR, 0x4400000); /* set default interrupt handler */ for (vector = 0; vector < MAX_HANDLERS; vector++) { isr_table [vector] = (rt_isr_handler_t)rt_hw_interrupt_handle; } /* initialize interrupt nest, and context in thread sp */ rt_interrupt_nest = 0; rt_interrupt_from_thread = 0; rt_interrupt_to_thread = 0; rt_thread_switch_interrput_flag = 0; } /*@}*/
poranmeloge/test-github
stm32_rtt_wifi/libcpu/ppc/ppc405/interrupt.c
C
gpl-2.0
3,000
/**************************************************************************** ** Meta object code from reading C++ file 'qitemeditorfactory_p.h' ** ** Created by: The Qt Meta Object Compiler version 63 (Qt 4.8.5) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../../../itemviews/qitemeditorfactory_p.h" #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'qitemeditorfactory_p.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 63 #error "This file was generated using the moc from 4.8.5. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE static const uint qt_meta_data_QExpandingLineEdit[] = { // content: 6, // revision 0, // classname 0, 0, // classinfo 1, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: signature, parameters, type, tag, flags 20, 19, 19, 19, 0x0a, 0 // eod }; static const char qt_meta_stringdata_QExpandingLineEdit[] = { "QExpandingLineEdit\0\0resizeToContents()\0" }; void QExpandingLineEdit::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { Q_ASSERT(staticMetaObject.cast(_o)); QExpandingLineEdit *_t = static_cast<QExpandingLineEdit *>(_o); switch (_id) { case 0: _t->resizeToContents(); break; default: ; } } Q_UNUSED(_a); } const QMetaObjectExtraData QExpandingLineEdit::staticMetaObjectExtraData = { 0, qt_static_metacall }; const QMetaObject QExpandingLineEdit::staticMetaObject = { { &QLineEdit::staticMetaObject, qt_meta_stringdata_QExpandingLineEdit, qt_meta_data_QExpandingLineEdit, &staticMetaObjectExtraData } }; #ifdef Q_NO_DATA_RELOCATION const QMetaObject &QExpandingLineEdit::getStaticMetaObject() { return staticMetaObject; } #endif //Q_NO_DATA_RELOCATION const QMetaObject *QExpandingLineEdit::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject; } void *QExpandingLineEdit::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_QExpandingLineEdit)) return static_cast<void*>(const_cast< QExpandingLineEdit*>(this)); return QLineEdit::qt_metacast(_clname); } int QExpandingLineEdit::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QLineEdit::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 1) qt_static_metacall(this, _c, _id, _a); _id -= 1; } return _id; } QT_END_MOC_NAMESPACE
dulton/vlc-2.1.4.32.subproject-2013-update2
win32/include/qt4/src/gui/tmp/moc/debug_shared/moc_qitemeditorfactory_p.cpp
C++
gpl-2.0
2,946
//@HEADER // ************************************************************************ // // Kokkos v. 2.0 // Copyright (2014) Sandia Corporation // // Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, // the U.S. Government retains certain rights in this software. // // Kokkos is licensed under 3-clause BSD terms of use: // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the name of the Corporation nor the names of the // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "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 SANDIA CORPORATION OR THE // 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. // // Questions? Contact Christian R. Trott ([email protected]) // // ************************************************************************ //@HEADER #define KOKKOS_IMPL_COMPILING_LIBRARY true #include<Kokkos_Core.hpp> namespace Kokkos { namespace Impl { KOKKOS_IMPL_VIEWCOPY_ETI_INST(float**,LayoutLeft,LayoutRight, Cuda,int) KOKKOS_IMPL_VIEWCOPY_ETI_INST(float**,LayoutLeft,LayoutLeft, Cuda,int) KOKKOS_IMPL_VIEWCOPY_ETI_INST(float**,LayoutLeft,LayoutStride,Cuda,int) KOKKOS_IMPL_VIEWFILL_ETI_INST(float**,LayoutLeft,Cuda,int) } }
quang-ha/lammps
lib/kokkos/core/src/eti/Cuda/Kokkos_Cuda_ViewCopyETIInst_int_float_LayoutLeft_Rank2.cpp
C++
gpl-2.0
2,406
Deface::Override.new(:virtual_path => "hostgroups/_form", :name => "add_activation_keys_tab", :insert_after => 'ul.nav > code[erb-silent]:contains("show_organization_tab?") ~ code[erb-silent]:contains("end")', :partial => '../overrides/foreman/activation_keys/host_tab') Deface::Override.new(:virtual_path => "hostgroups/_form", :name => "add_activation_keys_tab_pane", :insert_after => 'code[erb-loud]:contains("render"):contains("taxonomies/loc_org_tabs")', :partial => '../overrides/foreman/activation_keys/host_tab_pane') Deface::Override.new(:virtual_path => "hostgroups/_form", :name => "hostgroups_update_environments_select", :replace => 'code[erb-loud]:contains("select_f"):contains(":environment_id")', :partial => '../overrides/foreman/activation_keys/host_environment_select') Deface::Override.new(:virtual_path => "hosts/_form", :name => "hosts_update_environments_select", :replace => 'code[erb-loud]:contains("select_f"):contains(":environment_id")', :partial => '../overrides/foreman/activation_keys/host_environment_select')
steveloranz/katello
app/overrides/add_activation_keys_input.rb
Ruby
gpl-2.0
1,297
/* $License: Copyright (C) 2010 InvenSense Corporation, All Rights Reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; 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/>. $ */ /** * @addtogroup MLDL * * @{ * @file mldl_cfg.c * @brief The Motion Library Driver Layer. */ /* ------------------ */ /* - Include Files. - */ /* ------------------ */ #include <stddef.h> #include "mldl_cfg.h" #include "mpu.h" #include "mlsl.h" #include "mlos.h" #include "log.h" #include "mpu-accel.h" #undef MPL_LOG_TAG #define MPL_LOG_TAG "mldl_cfg:" /* --------------------- */ /* - Variables. - */ /* --------------------- */ #ifdef M_HW #define SLEEP 0 #define WAKE_UP 7 #define RESET 1 #define STANDBY 1 #else /* licteral significance of all parameters used in MLDLPowerMgmtMPU */ #define SLEEP 1 #define WAKE_UP 0 #define RESET 1 #define STANDBY 1 #endif // 20110825 [email protected] Sensor I2C Error [S] #define ERROR_CHECK_WITH_MUTEX_UNLOCK(x,y) \ { \ if (ML_SUCCESS != x) { \ MPL_LOGE("%s|%s|%d returning %d\n", \ __FILE__, __func__, __LINE__, x); \ mutex_unlock(y); \ return x; \ } \ } // 20110825 [email protected] Sensor I2C Error [E] /*---------------------*/ /*- Prototypes. -*/ /*---------------------*/ /*----------------------*/ /*- Static Functions. -*/ /*----------------------*/ static int dmp_stop(struct mldl_cfg *mldl_cfg, void *gyro_handle) { unsigned char userCtrlReg; int result; if (!mldl_cfg->dmp_is_running) return ML_SUCCESS; result = MLSLSerialRead(gyro_handle, mldl_cfg->addr, MPUREG_USER_CTRL, 1, &userCtrlReg); ERROR_CHECK(result); userCtrlReg = (userCtrlReg & (~BIT_FIFO_EN)) | BIT_FIFO_RST; userCtrlReg = (userCtrlReg & (~BIT_DMP_EN)) | BIT_DMP_RST; result = MLSLSerialWriteSingle(gyro_handle, mldl_cfg->addr, MPUREG_USER_CTRL, userCtrlReg); ERROR_CHECK(result); mldl_cfg->dmp_is_running = 0; return result; } /** * @brief Starts the DMP running * * @return ML_SUCCESS or non-zero error code */ static int dmp_start(struct mldl_cfg *pdata, void *mlsl_handle) { unsigned char userCtrlReg; int result; if (pdata->dmp_is_running == pdata->dmp_enable) return ML_SUCCESS; result = MLSLSerialRead(mlsl_handle, pdata->addr, MPUREG_USER_CTRL, 1, &userCtrlReg); ERROR_CHECK(result); result = MLSLSerialWriteSingle(mlsl_handle, pdata->addr, MPUREG_USER_CTRL, ((userCtrlReg & (~BIT_FIFO_EN)) | BIT_FIFO_RST)); ERROR_CHECK(result); result = MLSLSerialWriteSingle(mlsl_handle, pdata->addr, MPUREG_USER_CTRL, userCtrlReg); ERROR_CHECK(result); result = MLSLSerialRead(mlsl_handle, pdata->addr, MPUREG_USER_CTRL, 1, &userCtrlReg); ERROR_CHECK(result); if (pdata->dmp_enable) userCtrlReg |= BIT_DMP_EN; else userCtrlReg &= ~BIT_DMP_EN; if (pdata->fifo_enable) userCtrlReg |= BIT_FIFO_EN; else userCtrlReg &= ~BIT_FIFO_EN; userCtrlReg |= BIT_DMP_RST; result = MLSLSerialWriteSingle(mlsl_handle, pdata->addr, MPUREG_USER_CTRL, userCtrlReg); ERROR_CHECK(result); pdata->dmp_is_running = pdata->dmp_enable; return result; } /** * @brief enables/disables the I2C bypass to an external device * connected to MPU's secondary I2C bus. * @param enable * Non-zero to enable pass through. * @return ML_SUCCESS if successful, a non-zero error code otherwise. */ static int MLDLSetI2CBypass(struct mldl_cfg *mldl_cfg, void *mlsl_handle, unsigned char enable) { unsigned char b; int result; if ((mldl_cfg->gyro_is_bypassed && enable) || (!mldl_cfg->gyro_is_bypassed && !enable)) return ML_SUCCESS; /*---- get current 'USER_CTRL' into b ----*/ result = MLSLSerialRead(mlsl_handle, mldl_cfg->addr, MPUREG_USER_CTRL, 1, &b); ERROR_CHECK(result); b &= ~BIT_AUX_IF_EN; if (!enable) { result = MLSLSerialWriteSingle(mlsl_handle, mldl_cfg->addr, MPUREG_USER_CTRL, (b | BIT_AUX_IF_EN)); ERROR_CHECK(result); } else { /* Coming out of I2C is tricky due to several erratta. Do not * modify this algorithm */ /* * 1) wait for the right time and send the command to change * the aux i2c slave address to an invalid address that will * get nack'ed * * 0x00 is broadcast. 0x7F is unlikely to be used by any aux. */ result = MLSLSerialWriteSingle(mlsl_handle, mldl_cfg->addr, MPUREG_AUX_SLV_ADDR, 0x7F); ERROR_CHECK(result); /* * 2) wait enough time for a nack to occur, then go into * bypass mode: */ MLOSSleep(2); result = MLSLSerialWriteSingle(mlsl_handle, mldl_cfg->addr, MPUREG_USER_CTRL, (b)); ERROR_CHECK(result); /* * 3) wait for up to one MPU cycle then restore the slave * address */ MLOSSleep(SAMPLING_PERIOD_US(mldl_cfg) / 1000); result = MLSLSerialWriteSingle(mlsl_handle, mldl_cfg->addr, MPUREG_AUX_SLV_ADDR, mldl_cfg->pdata-> accel.address); ERROR_CHECK(result); /* * 4) reset the ime interface */ #ifdef M_HW result = MLSLSerialWriteSingle(mlsl_handle, mldl_cfg->addr, MPUREG_USER_CTRL, (b | BIT_I2C_MST_RST)); #else result = MLSLSerialWriteSingle(mlsl_handle, mldl_cfg->addr, MPUREG_USER_CTRL, (b | BIT_AUX_IF_RST)); #endif ERROR_CHECK(result); MLOSSleep(2); } mldl_cfg->gyro_is_bypassed = enable; return result; } struct tsProdRevMap { unsigned char siliconRev; unsigned short sensTrim; }; #define NUM_OF_PROD_REVS (DIM(prodRevsMap)) /* NOTE : 'npp' is a non production part */ #ifdef M_HW #define OLDEST_PROD_REV_SUPPORTED 1 static struct tsProdRevMap prodRevsMap[] = { {0, 0}, {MPU_SILICON_REV_A1, 131}, /* 1 A1 (npp) */ {MPU_SILICON_REV_A1, 131}, /* 2 A1 (npp) */ {MPU_SILICON_REV_A1, 131}, /* 3 A1 (npp) */ {MPU_SILICON_REV_A1, 131}, /* 4 A1 (npp) */ {MPU_SILICON_REV_A1, 131}, /* 5 A1 (npp) */ {MPU_SILICON_REV_A1, 131}, /* 6 A1 (npp) */ {MPU_SILICON_REV_A1, 131}, /* 7 A1 (npp) */ {MPU_SILICON_REV_A1, 131}, /* 8 A1 (npp) */ }; #else /* !M_HW */ #define OLDEST_PROD_REV_SUPPORTED 11 static struct tsProdRevMap prodRevsMap[] = { {0, 0}, {MPU_SILICON_REV_A4, 131}, /* 1 A? OBSOLETED */ {MPU_SILICON_REV_A4, 131}, /* 2 | */ {MPU_SILICON_REV_A4, 131}, /* 3 V */ {MPU_SILICON_REV_A4, 131}, /* 4 */ {MPU_SILICON_REV_A4, 131}, /* 5 */ {MPU_SILICON_REV_A4, 131}, /* 6 */ {MPU_SILICON_REV_A4, 131}, /* 7 */ {MPU_SILICON_REV_A4, 131}, /* 8 */ {MPU_SILICON_REV_A4, 131}, /* 9 */ {MPU_SILICON_REV_A4, 131}, /* 10 */ {MPU_SILICON_REV_B1, 131}, /* 11 B1 */ {MPU_SILICON_REV_B1, 131}, /* 12 | */ {MPU_SILICON_REV_B1, 131}, /* 13 V */ {MPU_SILICON_REV_B1, 131}, /* 14 B4 */ {MPU_SILICON_REV_B4, 131}, /* 15 | */ {MPU_SILICON_REV_B4, 131}, /* 16 V */ {MPU_SILICON_REV_B4, 131}, /* 17 */ {MPU_SILICON_REV_B4, 131}, /* 18 */ {MPU_SILICON_REV_B4, 115}, /* 19 */ {MPU_SILICON_REV_B4, 115}, /* 20 */ {MPU_SILICON_REV_B6, 131}, /* 21 B6 (B6/A9) */ {MPU_SILICON_REV_B4, 115}, /* 22 B4 (B7/A10) */ {MPU_SILICON_REV_B6, 0}, /* 23 B6 (npp) */ {MPU_SILICON_REV_B6, 0}, /* 24 | (npp) */ {MPU_SILICON_REV_B6, 0}, /* 25 V (npp) */ {MPU_SILICON_REV_B6, 131}, /* 26 (B6/A11) */ }; #endif /* !M_HW */ /** * @internal * @brief Get the silicon revision ID from OTP. * The silicon revision number is in read from OTP bank 0, * ADDR6[7:2]. The corresponding ID is retrieved by lookup * in a map. * @return The silicon revision ID (0 on error). */ static int MLDLGetSiliconRev(struct mldl_cfg *pdata, void *mlsl_handle) { int result; unsigned char index = 0x00; unsigned char bank = (BIT_PRFTCH_EN | BIT_CFG_USER_BANK | MPU_MEM_OTP_BANK_0); unsigned short memAddr = ((bank << 8) | 0x06); result = MLSLSerialReadMem(mlsl_handle, pdata->addr, memAddr, 1, &index); ERROR_CHECK(result) if (result) return result; index >>= 2; /* clean the prefetch and cfg user bank bits */ result = MLSLSerialWriteSingle(mlsl_handle, pdata->addr, MPUREG_BANK_SEL, 0); ERROR_CHECK(result) if (result) return result; if (index < OLDEST_PROD_REV_SUPPORTED || NUM_OF_PROD_REVS <= index) { pdata->silicon_revision = 0; pdata->trim = 0; MPL_LOGE("Unsupported Product Revision Detected : %d\n", index); return ML_ERROR_INVALID_MODULE; } pdata->silicon_revision = prodRevsMap[index].siliconRev; pdata->trim = prodRevsMap[index].sensTrim; if (pdata->trim == 0) { MPL_LOGE("sensitivity trim is 0" " - unsupported non production part.\n"); return ML_ERROR_INVALID_MODULE; } return result; } /** * @brief Enable/Disable the use MPU's VDDIO level shifters. * When enabled the voltage interface with AUX or other external * accelerometer is using Vlogic instead of VDD (supply). * * @note Must be called after MLSerialOpen(). * @note Typically be called before MLDmpOpen(). * If called after MLDmpOpen(), must be followed by a call to * MLDLApplyLevelShifterBit() to write the setting on the hw. * * @param[in] enable * 1 to enable, 0 to disable * * @return ML_SUCCESS if successfull, a non-zero error code otherwise. **/ static int MLDLSetLevelShifterBit(struct mldl_cfg *pdata, void *mlsl_handle, unsigned char enable) { #ifndef M_HW int result; unsigned char reg; unsigned char mask; unsigned char regval; if (0 == pdata->silicon_revision) return ML_ERROR_INVALID_PARAMETER; /*-- on parts before B6 the VDDIO bit is bit 7 of ACCEL_BURST_ADDR -- NOTE: this is incompatible with ST accelerometers where the VDDIO bit MUST be set to enable ST's internal logic to autoincrement the register address on burst reads --*/ if ((pdata->silicon_revision & 0xf) < MPU_SILICON_REV_B6) { reg = MPUREG_ACCEL_BURST_ADDR; mask = 0x80; } else { /*-- on B6 parts the VDDIO bit was moved to FIFO_EN2 => the mask is always 0x04 --*/ reg = MPUREG_FIFO_EN2; mask = 0x04; } result = MLSLSerialRead(mlsl_handle, pdata->addr, reg, 1, &regval); if (result) return result; if (enable) regval |= mask; else regval &= ~mask; result = MLSLSerialWriteSingle(mlsl_handle, pdata->addr, reg, regval); return result; #else return ML_SUCCESS; #endif } #ifdef M_HW /** * @internal * @param reset 1 to reset hardware */ static tMLError mpu60xx_pwr_mgmt(struct mldl_cfg *pdata, void *mlsl_handle, unsigned char reset, unsigned char powerselection) { unsigned char b; tMLError result; if (powerselection < 0 || powerselection > 7) return ML_ERROR_INVALID_PARAMETER; result = MLSLSerialRead(mlsl_handle, pdata->addr, MPUREG_PWR_MGMT_1, 1, &b); ERROR_CHECK(result); b &= ~(BITS_PWRSEL); if (reset) { /* Current sillicon has an errata where the reset will get * nacked. Ignore the error code for now. */ result = MLSLSerialWriteSingle(mlsl_handle, pdata->addr, MPUREG_PWR_MGM, b | BIT_H_RESET); #define M_HW_RESET_ERRATTA #ifndef M_HW_RESET_ERRATTA ERROR_CHECK(result); #else MLOSSleep(50); #endif } b |= (powerselection << 4); if (b & BITS_PWRSEL) pdata->gyro_is_suspended = FALSE; else pdata->gyro_is_suspended = TRUE; result = MLSLSerialWriteSingle(mlsl_handle, pdata->addr, MPUREG_PWR_MGM, b); ERROR_CHECK(result); return ML_SUCCESS; } /** * @internal */ static tMLError MLDLStandByGyros(struct mldl_cfg *pdata, void *mlsl_handle, unsigned char disable_gx, unsigned char disable_gy, unsigned char disable_gz) { unsigned char b; tMLError result; result = MLSLSerialRead(mlsl_handle, pdata->addr, MPUREG_PWR_MGMT_2, 1, &b); ERROR_CHECK(result); b &= ~(BIT_STBY_XG | BIT_STBY_YG | BIT_STBY_ZG); b |= (disable_gx << 2 | disable_gy << 1 | disable_gz); result = MLSLSerialWriteSingle(mlsl_handle, pdata->addr, MPUREG_PWR_MGMT_2, b); ERROR_CHECK(result); return ML_SUCCESS; } /** * @internal */ static tMLError MLDLStandByAccels(struct mldl_cfg *pdata, void *mlsl_handle, unsigned char disable_ax, unsigned char disable_ay, unsigned char disable_az) { unsigned char b; tMLError result; result = MLSLSerialRead(mlsl_handle, pdata->addr, MPUREG_PWR_MGMT_2, 1, &b); ERROR_CHECK(result); b &= ~(BIT_STBY_XA | BIT_STBY_YA | BIT_STBY_ZA); b |= (disable_ax << 2 | disable_ay << 1 | disable_az); result = MLSLSerialWriteSingle(mlsl_handle, pdata->addr, MPUREG_PWR_MGMT_2, b); ERROR_CHECK(result); return ML_SUCCESS; } #else /* ! M_HW */ /** * @internal * @brief This function controls the power management on the MPU device. * The entire chip can be put to low power sleep mode, or individual * gyros can be turned on/off. * * Putting the device into sleep mode depending upon the changing needs * of the associated applications is a recommended method for reducing * power consuption. It is a safe opearation in that sleep/wake up of * gyros while running will not result in any interruption of data. * * Although it is entirely allowed to put the device into full sleep * while running the DMP, it is not recomended because it will disrupt * the ongoing calculations carried on inside the DMP and consequently * the sensor fusion algorithm. Furthermore, while in sleep mode * read & write operation from the app processor on both registers and * memory are disabled and can only regained by restoring the MPU in * normal power mode. * Disabling any of the gyro axis will reduce the associated power * consuption from the PLL but will not stop the DMP from running * state. * * @param reset * Non-zero to reset the device. Note that this setting * is volatile and the corresponding register bit will * clear itself right after being applied. * @param sleep * Non-zero to put device into full sleep. * @param disable_gx * Non-zero to disable gyro X. * @param disable_gy * Non-zero to disable gyro Y. * @param disable_gz * Non-zero to disable gyro Z. * * @return ML_SUCCESS if successfull; a non-zero error code otherwise. */ static int MLDLPowerMgmtMPU(struct mldl_cfg *pdata, void *mlsl_handle, unsigned char reset, unsigned char sleep, unsigned char disable_gx, unsigned char disable_gy, unsigned char disable_gz) { unsigned char b; int result; result = MLSLSerialRead(mlsl_handle, pdata->addr, MPUREG_PWR_MGM, 1, &b); ERROR_CHECK(result); /* If we are awake, we need to put it in bypass before resetting */ if ((!(b & BIT_SLEEP)) && reset) result = MLDLSetI2CBypass(pdata, mlsl_handle, 1); /* If we are awake, we need stop the dmp sleeping */ if ((!(b & BIT_SLEEP)) && sleep) dmp_stop(pdata, mlsl_handle); /* Reset if requested */ if (reset) { MPL_LOGV("Reset MPU3050\n"); result = MLSLSerialWriteSingle(mlsl_handle, pdata->addr, MPUREG_PWR_MGM, b | BIT_H_RESET); ERROR_CHECK(result); MLOSSleep(5); pdata->gyro_needs_reset = FALSE; /* Some chips are awake after reset and some are asleep, * check the status */ result = MLSLSerialRead(mlsl_handle, pdata->addr, MPUREG_PWR_MGM, 1, &b); ERROR_CHECK(result); } /* Update the suspended state just in case we return early */ if (b & BIT_SLEEP) pdata->gyro_is_suspended = TRUE; else pdata->gyro_is_suspended = FALSE; /* if power status match requested, nothing else's left to do */ if ((b & (BIT_SLEEP | BIT_STBY_XG | BIT_STBY_YG | BIT_STBY_ZG)) == (((sleep != 0) * BIT_SLEEP) | ((disable_gx != 0) * BIT_STBY_XG) | ((disable_gy != 0) * BIT_STBY_YG) | ((disable_gz != 0) * BIT_STBY_ZG))) { return ML_SUCCESS; } /* * This specific transition between states needs to be reinterpreted: * (1,1,1,1) -> (0,1,1,1) has to become * (1,1,1,1) -> (1,0,0,0) -> (0,1,1,1) * where * (1,1,1,1) is (sleep=1,disable_gx=1,disable_gy=1,disable_gz=1) */ if ((b & (BIT_SLEEP | BIT_STBY_XG | BIT_STBY_YG | BIT_STBY_ZG)) == (BIT_SLEEP | BIT_STBY_XG | BIT_STBY_YG | BIT_STBY_ZG) && ((!sleep) && disable_gx && disable_gy && disable_gz)) { result = MLDLPowerMgmtMPU(pdata, mlsl_handle, 0, 1, 0, 0, 0); if (result) return result; b |= BIT_SLEEP; b &= ~(BIT_STBY_XG | BIT_STBY_YG | BIT_STBY_ZG); } if ((b & BIT_SLEEP) != ((sleep != 0) * BIT_SLEEP)) { if (sleep) { result = MLDLSetI2CBypass(pdata, mlsl_handle, 1); ERROR_CHECK(result); b |= BIT_SLEEP; result = MLSLSerialWriteSingle(mlsl_handle, pdata->addr, MPUREG_PWR_MGM, b); ERROR_CHECK(result); pdata->gyro_is_suspended = TRUE; } else { b &= ~BIT_SLEEP; result = MLSLSerialWriteSingle(mlsl_handle, pdata->addr, MPUREG_PWR_MGM, b); ERROR_CHECK(result); pdata->gyro_is_suspended = FALSE; MLOSSleep(5); } } /*--- WORKAROUND FOR PUTTING GYRO AXIS in STAND-BY MODE 1) put one axis at a time in stand-by ---*/ if ((b & BIT_STBY_XG) != ((disable_gx != 0) * BIT_STBY_XG)) { b ^= BIT_STBY_XG; result = MLSLSerialWriteSingle(mlsl_handle, pdata->addr, MPUREG_PWR_MGM, b); ERROR_CHECK(result); } if ((b & BIT_STBY_YG) != ((disable_gy != 0) * BIT_STBY_YG)) { b ^= BIT_STBY_YG; result = MLSLSerialWriteSingle(mlsl_handle, pdata->addr, MPUREG_PWR_MGM, b); ERROR_CHECK(result); } if ((b & BIT_STBY_ZG) != ((disable_gz != 0) * BIT_STBY_ZG)) { b ^= BIT_STBY_ZG; result = MLSLSerialWriteSingle(mlsl_handle, pdata->addr, MPUREG_PWR_MGM, b); ERROR_CHECK(result); } return ML_SUCCESS; } #endif /* M_HW */ void mpu_print_cfg(struct mldl_cfg *mldl_cfg) { struct mpu3050_platform_data *pdata = mldl_cfg->pdata; struct ext_slave_platform_data *accel = &mldl_cfg->pdata->accel; struct ext_slave_platform_data *compass = &mldl_cfg->pdata->compass; struct ext_slave_platform_data *pressure = &mldl_cfg->pdata->pressure; MPL_LOGD("mldl_cfg.addr = %02x\n", mldl_cfg->addr); MPL_LOGD("mldl_cfg.int_config = %02x\n", mldl_cfg->int_config); MPL_LOGD("mldl_cfg.ext_sync = %02x\n", mldl_cfg->ext_sync); MPL_LOGD("mldl_cfg.full_scale = %02x\n", mldl_cfg->full_scale); MPL_LOGD("mldl_cfg.lpf = %02x\n", mldl_cfg->lpf); MPL_LOGD("mldl_cfg.clk_src = %02x\n", mldl_cfg->clk_src); MPL_LOGD("mldl_cfg.divider = %02x\n", mldl_cfg->divider); MPL_LOGD("mldl_cfg.dmp_enable = %02x\n", mldl_cfg->dmp_enable); MPL_LOGD("mldl_cfg.fifo_enable = %02x\n", mldl_cfg->fifo_enable); MPL_LOGD("mldl_cfg.dmp_cfg1 = %02x\n", mldl_cfg->dmp_cfg1); MPL_LOGD("mldl_cfg.dmp_cfg2 = %02x\n", mldl_cfg->dmp_cfg2); MPL_LOGD("mldl_cfg.offset_tc[0] = %02x\n", mldl_cfg->offset_tc[0]); MPL_LOGD("mldl_cfg.offset_tc[1] = %02x\n", mldl_cfg->offset_tc[1]); MPL_LOGD("mldl_cfg.offset_tc[2] = %02x\n", mldl_cfg->offset_tc[2]); MPL_LOGD("mldl_cfg.silicon_revision = %02x\n", mldl_cfg->silicon_revision); MPL_LOGD("mldl_cfg.product_id = %02x\n", mldl_cfg->product_id); MPL_LOGD("mldl_cfg.trim = %02x\n", mldl_cfg->trim); MPL_LOGD("mldl_cfg.requested_sensors= %04lx\n", mldl_cfg->requested_sensors); if (mldl_cfg->accel) { MPL_LOGD("slave_accel->suspend = %02x\n", (int) mldl_cfg->accel->suspend); MPL_LOGD("slave_accel->resume = %02x\n", (int) mldl_cfg->accel->resume); MPL_LOGD("slave_accel->read = %02x\n", (int) mldl_cfg->accel->read); MPL_LOGD("slave_accel->type = %02x\n", mldl_cfg->accel->type); MPL_LOGD("slave_accel->reg = %02x\n", mldl_cfg->accel->reg); MPL_LOGD("slave_accel->len = %02x\n", mldl_cfg->accel->len); MPL_LOGD("slave_accel->endian = %02x\n", mldl_cfg->accel->endian); MPL_LOGD("slave_accel->range.mantissa= %02lx\n", mldl_cfg->accel->range.mantissa); MPL_LOGD("slave_accel->range.fraction= %02lx\n", mldl_cfg->accel->range.fraction); } else { MPL_LOGD("slave_accel = NULL\n"); } if (mldl_cfg->compass) { MPL_LOGD("slave_compass->suspend = %02x\n", (int) mldl_cfg->compass->suspend); MPL_LOGD("slave_compass->resume = %02x\n", (int) mldl_cfg->compass->resume); MPL_LOGD("slave_compass->read = %02x\n", (int) mldl_cfg->compass->read); MPL_LOGD("slave_compass->type = %02x\n", mldl_cfg->compass->type); MPL_LOGD("slave_compass->reg = %02x\n", mldl_cfg->compass->reg); MPL_LOGD("slave_compass->len = %02x\n", mldl_cfg->compass->len); MPL_LOGD("slave_compass->endian = %02x\n", mldl_cfg->compass->endian); MPL_LOGD("slave_compass->range.mantissa= %02lx\n", mldl_cfg->compass->range.mantissa); MPL_LOGD("slave_compass->range.fraction= %02lx\n", mldl_cfg->compass->range.fraction); } else { MPL_LOGD("slave_compass = NULL\n"); } if (mldl_cfg->pressure) { MPL_LOGD("slave_pressure->suspend = %02x\n", (int) mldl_cfg->pressure->suspend); MPL_LOGD("slave_pressure->resume = %02x\n", (int) mldl_cfg->pressure->resume); MPL_LOGD("slave_pressure->read = %02x\n", (int) mldl_cfg->pressure->read); MPL_LOGD("slave_pressure->type = %02x\n", mldl_cfg->pressure->type); MPL_LOGD("slave_pressure->reg = %02x\n", mldl_cfg->pressure->reg); MPL_LOGD("slave_pressure->len = %02x\n", mldl_cfg->pressure->len); MPL_LOGD("slave_pressure->endian = %02x\n", mldl_cfg->pressure->endian); MPL_LOGD("slave_pressure->range.mantissa= %02lx\n", mldl_cfg->pressure->range.mantissa); MPL_LOGD("slave_pressure->range.fraction= %02lx\n", mldl_cfg->pressure->range.fraction); } else { MPL_LOGD("slave_pressure = NULL\n"); } MPL_LOGD("accel->get_slave_descr = %x\n", (unsigned int) accel->get_slave_descr); MPL_LOGD("accel->irq = %02x\n", accel->irq); MPL_LOGD("accel->adapt_num = %02x\n", accel->adapt_num); MPL_LOGD("accel->bus = %02x\n", accel->bus); MPL_LOGD("accel->address = %02x\n", accel->address); MPL_LOGD("accel->orientation =\n" " %2d %2d %2d\n" " %2d %2d %2d\n" " %2d %2d %2d\n", accel->orientation[0], accel->orientation[1], accel->orientation[2], accel->orientation[3], accel->orientation[4], accel->orientation[5], accel->orientation[6], accel->orientation[7], accel->orientation[8]); MPL_LOGD("compass->get_slave_descr = %x\n", (unsigned int) compass->get_slave_descr); MPL_LOGD("compass->irq = %02x\n", compass->irq); MPL_LOGD("compass->adapt_num = %02x\n", compass->adapt_num); MPL_LOGD("compass->bus = %02x\n", compass->bus); MPL_LOGD("compass->address = %02x\n", compass->address); MPL_LOGD("compass->orientation =\n" " %2d %2d %2d\n" " %2d %2d %2d\n" " %2d %2d %2d\n", compass->orientation[0], compass->orientation[1], compass->orientation[2], compass->orientation[3], compass->orientation[4], compass->orientation[5], compass->orientation[6], compass->orientation[7], compass->orientation[8]); MPL_LOGD("pressure->get_slave_descr = %x\n", (unsigned int) pressure->get_slave_descr); MPL_LOGD("pressure->irq = %02x\n", pressure->irq); MPL_LOGD("pressure->adapt_num = %02x\n", pressure->adapt_num); MPL_LOGD("pressure->bus = %02x\n", pressure->bus); MPL_LOGD("pressure->address = %02x\n", pressure->address); MPL_LOGD("pressure->orientation =\n" " %2d %2d %2d\n" " %2d %2d %2d\n" " %2d %2d %2d\n", pressure->orientation[0], pressure->orientation[1], pressure->orientation[2], pressure->orientation[3], pressure->orientation[4], pressure->orientation[5], pressure->orientation[6], pressure->orientation[7], pressure->orientation[8]); MPL_LOGD("pdata->int_config = %02x\n", pdata->int_config); MPL_LOGD("pdata->level_shifter = %02x\n", pdata->level_shifter); MPL_LOGD("pdata->orientation =\n" " %2d %2d %2d\n" " %2d %2d %2d\n" " %2d %2d %2d\n", pdata->orientation[0], pdata->orientation[1], pdata->orientation[2], pdata->orientation[3], pdata->orientation[4], pdata->orientation[5], pdata->orientation[6], pdata->orientation[7], pdata->orientation[8]); MPL_LOGD("Struct sizes: mldl_cfg: %d, " "ext_slave_descr:%d, " "mpu3050_platform_data:%d: RamOffset: %d\n", sizeof(struct mldl_cfg), sizeof(struct ext_slave_descr), sizeof(struct mpu3050_platform_data), offsetof(struct mldl_cfg, ram)); } int mpu_set_slave(struct mldl_cfg *mldl_cfg, void *gyro_handle, struct ext_slave_descr *slave, struct ext_slave_platform_data *slave_pdata) { int result; unsigned char reg; unsigned char slave_reg; unsigned char slave_len; unsigned char slave_endian; unsigned char slave_address; result = MLDLSetI2CBypass(mldl_cfg, gyro_handle, TRUE); if (NULL == slave || NULL == slave_pdata) { slave_reg = 0; slave_len = 0; slave_endian = 0; slave_address = 0; } else { slave_reg = slave->reg; slave_len = slave->len; slave_endian = slave->endian; slave_address = slave_pdata->address; } /* Address */ result = MLSLSerialWriteSingle(gyro_handle, mldl_cfg->addr, MPUREG_AUX_SLV_ADDR, slave_address); ERROR_CHECK(result); /* Register */ result = MLSLSerialRead(gyro_handle, mldl_cfg->addr, MPUREG_ACCEL_BURST_ADDR, 1, &reg); ERROR_CHECK(result); reg = ((reg & 0x80) | slave_reg); result = MLSLSerialWriteSingle(gyro_handle, mldl_cfg->addr, MPUREG_ACCEL_BURST_ADDR, reg); ERROR_CHECK(result); #ifdef M_HW /* Length, byte swapping, grouping & enable */ if (slave_len > BITS_SLV_LENG) { MPL_LOGW("Limiting slave burst read length to " "the allowed maximum (15B, req. %d)\n", slave_len); slave_len = BITS_SLV_LENG; } reg = slave_len; if (slave_endian == EXT_SLAVE_LITTLE_ENDIAN) reg |= BIT_SLV_BYTE_SW; reg |= BIT_SLV_GRP; reg |= BIT_SLV_ENABLE; result = MLSLSerialWriteSingle(gyro_handle, mldl_cfg->addr, MPUREG_I2C_SLV0_CTRL, reg); #else /* Length */ result = MLSLSerialRead(gyro_handle, mldl_cfg->addr, MPUREG_USER_CTRL, 1, &reg); ERROR_CHECK(result); reg = (reg & ~BIT_AUX_RD_LENG); result = MLSLSerialWriteSingle(gyro_handle, mldl_cfg->addr, MPUREG_USER_CTRL, reg); ERROR_CHECK(result); #endif if (slave_address) { result = MLDLSetI2CBypass(mldl_cfg, gyro_handle, FALSE); ERROR_CHECK(result); } return result; } /** * Check to see if the gyro was reset by testing a couple of registers known * to change on reset. * * @param mldl_cfg mldl configuration structure * @param gyro_handle handle used to communicate with the gyro * * @return ML_SUCCESS or non-zero error code */ static int mpu_was_reset(struct mldl_cfg *mldl_cfg, void *gyro_handle) { int result = ML_SUCCESS; unsigned char reg; result = MLSLSerialRead(gyro_handle, mldl_cfg->addr, MPUREG_DMP_CFG_2, 1, &reg); ERROR_CHECK(result); if (mldl_cfg->dmp_cfg2 != reg) return TRUE; if (0 != mldl_cfg->dmp_cfg1) return FALSE; result = MLSLSerialRead(gyro_handle, mldl_cfg->addr, MPUREG_SMPLRT_DIV, 1, &reg); ERROR_CHECK(result); if (reg != mldl_cfg->divider) return TRUE; if (0 != mldl_cfg->divider) return FALSE; /* Inconclusive assume it was reset */ return TRUE; } static int gyro_resume(struct mldl_cfg *mldl_cfg, void *gyro_handle) { int result; int ii; int jj; unsigned char reg; unsigned char regs[7]; /* Wake up the part */ #ifdef M_HW result = mpu60xx_pwr_mgmt(mldl_cfg, gyro_handle, RESET, WAKE_UP); ERROR_CHECK(result); /* Configure the MPU */ result = MLDLSetI2CBypass(mldl_cfg, gyro_handle, 1); ERROR_CHECK(result); /* setting int_config with the propert flag BIT_BYPASS_EN should be done by the setup functions */ result = MLSLSerialWriteSingle(gyro_handle, mldl_cfg->addr, MPUREG_INT_PIN_CFG, (mldl_cfg->pdata->int_config | BIT_BYPASS_EN)); ERROR_CHECK(result); /* temporary: masking out higher bits to avoid switching intelligence */ result = MLSLSerialWriteSingle(gyro_handle, mldl_cfg->addr, MPUREG_INT_ENABLE, (mldl_cfg->int_config)); ERROR_CHECK(result); #else result = MLDLPowerMgmtMPU(mldl_cfg, gyro_handle, 0, 0, mldl_cfg->gyro_power & BIT_STBY_XG, mldl_cfg->gyro_power & BIT_STBY_YG, mldl_cfg->gyro_power & BIT_STBY_ZG); if (!mldl_cfg->gyro_needs_reset && !mpu_was_reset(mldl_cfg, gyro_handle)) { return ML_SUCCESS; } result = MLDLPowerMgmtMPU(mldl_cfg, gyro_handle, 1, 0, mldl_cfg->gyro_power & BIT_STBY_XG, mldl_cfg->gyro_power & BIT_STBY_YG, mldl_cfg->gyro_power & BIT_STBY_ZG); ERROR_CHECK(result); result = MLSLSerialWriteSingle(gyro_handle, mldl_cfg->addr, MPUREG_INT_CFG, (mldl_cfg->int_config | mldl_cfg->pdata->int_config)); ERROR_CHECK(result); #endif result = MLSLSerialRead(gyro_handle, mldl_cfg->addr, MPUREG_PWR_MGM, 1, &reg); ERROR_CHECK(result); reg &= ~BITS_CLKSEL; result = MLSLSerialWriteSingle(gyro_handle, mldl_cfg->addr, MPUREG_PWR_MGM, mldl_cfg->clk_src | reg); ERROR_CHECK(result); result = MLSLSerialWriteSingle(gyro_handle, mldl_cfg->addr, MPUREG_SMPLRT_DIV, mldl_cfg->divider); ERROR_CHECK(result); #ifdef M_HW reg = DLPF_FS_SYNC_VALUE(0, mldl_cfg->full_scale, 0); result = MLSLSerialWriteSingle(gyro_handle, mldl_cfg->addr, MPUREG_GYRO_CONFIG, reg); reg = DLPF_FS_SYNC_VALUE(mldl_cfg->ext_sync, 0, mldl_cfg->lpf); result = MLSLSerialWriteSingle(gyro_handle, mldl_cfg->addr, MPUREG_CONFIG, reg); #else reg = DLPF_FS_SYNC_VALUE(mldl_cfg->ext_sync, mldl_cfg->full_scale, mldl_cfg->lpf); result = MLSLSerialWriteSingle(gyro_handle, mldl_cfg->addr, MPUREG_DLPF_FS_SYNC, reg); #endif ERROR_CHECK(result); result = MLSLSerialWriteSingle(gyro_handle, mldl_cfg->addr, MPUREG_DMP_CFG_1, mldl_cfg->dmp_cfg1); ERROR_CHECK(result); result = MLSLSerialWriteSingle(gyro_handle, mldl_cfg->addr, MPUREG_DMP_CFG_2, mldl_cfg->dmp_cfg2); ERROR_CHECK(result); /* Write and verify memory */ for (ii = 0; ii < MPU_MEM_NUM_RAM_BANKS; ii++) { unsigned char read[MPU_MEM_BANK_SIZE]; result = MLSLSerialWriteMem(gyro_handle, mldl_cfg->addr, ((ii << 8) | 0x00), MPU_MEM_BANK_SIZE, mldl_cfg->ram[ii]); ERROR_CHECK(result); result = MLSLSerialReadMem(gyro_handle, mldl_cfg->addr, ((ii << 8) | 0x00), MPU_MEM_BANK_SIZE, read); ERROR_CHECK(result); #ifdef M_HW #define ML_SKIP_CHECK 38 #else #define ML_SKIP_CHECK 20 #endif for (jj = 0; jj < MPU_MEM_BANK_SIZE; jj++) { /* skip the register memory locations */ if (ii == 0 && jj < ML_SKIP_CHECK) continue; if (mldl_cfg->ram[ii][jj] != read[jj]) { result = ML_ERROR_SERIAL_WRITE; break; } } ERROR_CHECK(result); } result = MLSLSerialWriteSingle(gyro_handle, mldl_cfg->addr, MPUREG_XG_OFFS_TC, mldl_cfg->offset_tc[0]); ERROR_CHECK(result); result = MLSLSerialWriteSingle(gyro_handle, mldl_cfg->addr, MPUREG_YG_OFFS_TC, mldl_cfg->offset_tc[1]); ERROR_CHECK(result); result = MLSLSerialWriteSingle(gyro_handle, mldl_cfg->addr, MPUREG_ZG_OFFS_TC, mldl_cfg->offset_tc[2]); ERROR_CHECK(result); regs[0] = MPUREG_X_OFFS_USRH; for (ii = 0; ii < DIM(mldl_cfg->offset); ii++) { regs[1 + ii * 2] = (unsigned char)(mldl_cfg->offset[ii] >> 8) & 0xff; regs[1 + ii * 2 + 1] = (unsigned char)(mldl_cfg->offset[ii] & 0xff); } result = MLSLSerialWrite(gyro_handle, mldl_cfg->addr, 7, regs); ERROR_CHECK(result); /* Configure slaves */ result = MLDLSetLevelShifterBit(mldl_cfg, gyro_handle, mldl_cfg->pdata->level_shifter); ERROR_CHECK(result); return result; } /******************************************************************************* ******************************************************************************* * Exported functions ******************************************************************************* ******************************************************************************/ /** * Initializes the pdata structure to defaults. * * Opens the device to read silicon revision, product id and whoami. * * @param mldl_cfg * The internal device configuration data structure. * @param mlsl_handle * The serial communication handle. * * @return ML_SUCCESS if silicon revision, product id and woami are supported * by this software. */ int mpu3050_open(struct mldl_cfg *mldl_cfg, void *mlsl_handle, void *accel_handle, void *compass_handle, void *pressure_handle) { int result; /* Default is Logic HIGH, pushpull, latch disabled, anyread to clear */ mldl_cfg->int_config = BIT_INT_ANYRD_2CLEAR | BIT_DMP_INT_EN; mldl_cfg->clk_src = MPU_CLK_SEL_PLLGYROZ; mldl_cfg->lpf = MPU_FILTER_42HZ; mldl_cfg->full_scale = MPU_FS_2000DPS; mldl_cfg->divider = 4; mldl_cfg->dmp_enable = 1; mldl_cfg->fifo_enable = 1; mldl_cfg->ext_sync = 0; mldl_cfg->dmp_cfg1 = 0; mldl_cfg->dmp_cfg2 = 0; mldl_cfg->gyro_power = 0; mldl_cfg->gyro_is_bypassed = TRUE; mldl_cfg->dmp_is_running = FALSE; mldl_cfg->gyro_is_suspended = TRUE; mldl_cfg->accel_is_suspended = TRUE; mldl_cfg->compass_is_suspended = TRUE; mldl_cfg->pressure_is_suspended = TRUE; mldl_cfg->gyro_needs_reset = FALSE; if (mldl_cfg->addr == 0) { #ifdef __KERNEL__ return ML_ERROR_INVALID_PARAMETER; #else mldl_cfg->addr = 0x68; #endif } /* * Reset, * Take the DMP out of sleep, and * read the product_id, sillicon rev and whoami */ #ifdef M_HW result = mpu60xx_pwr_mgmt(mldl_cfg, mlsl_handle, RESET, WAKE_UP); #else result = MLDLPowerMgmtMPU(mldl_cfg, mlsl_handle, RESET, 0, 0, 0, 0); #endif ERROR_CHECK(result); result = MLDLGetSiliconRev(mldl_cfg, mlsl_handle); ERROR_CHECK(result); #ifndef M_HW result = MLSLSerialRead(mlsl_handle, mldl_cfg->addr, MPUREG_PRODUCT_ID, 1, &mldl_cfg->product_id); ERROR_CHECK(result); #endif /* Get the factory temperature compensation offsets */ result = MLSLSerialRead(mlsl_handle, mldl_cfg->addr, MPUREG_XG_OFFS_TC, 1, &mldl_cfg->offset_tc[0]); ERROR_CHECK(result); result = MLSLSerialRead(mlsl_handle, mldl_cfg->addr, MPUREG_YG_OFFS_TC, 1, &mldl_cfg->offset_tc[1]); ERROR_CHECK(result); result = MLSLSerialRead(mlsl_handle, mldl_cfg->addr, MPUREG_ZG_OFFS_TC, 1, &mldl_cfg->offset_tc[2]); ERROR_CHECK(result); /* Configure the MPU */ #ifdef M_HW result = mpu60xx_pwr_mgmt(mldl_cfg, mlsl_handle, FALSE, SLEEP); #else result = MLDLPowerMgmtMPU(mldl_cfg, mlsl_handle, 0, SLEEP, 0, 0, 0); #endif ERROR_CHECK(result); if (mldl_cfg->accel && mldl_cfg->accel->init) { result = mldl_cfg->accel->init(accel_handle, mldl_cfg->accel, &mldl_cfg->pdata->accel); MPL_LOGE("mldl_cfg->accel->init returned %d\n",result); ERROR_CHECK(result); } if (mldl_cfg->compass && mldl_cfg->compass->init) { result = mldl_cfg->compass->init(compass_handle, mldl_cfg->compass, &mldl_cfg->pdata->compass); MPL_LOGE("mldl_cfg->compass->init returned %d\n",result); if (ML_SUCCESS != result) { MPL_LOGE("mldl_cfg->compass->init returned %d\n", result); goto out_accel; } } if (mldl_cfg->pressure && mldl_cfg->pressure->init) { result = mldl_cfg->pressure->init(pressure_handle, mldl_cfg->pressure, &mldl_cfg->pdata->pressure); MPL_LOGE("mldl_cfg->pressure->init returned %d\n",result); if (ML_SUCCESS != result) { MPL_LOGE("mldl_cfg->pressure->init returned %d\n", result); goto out_compass; } } mldl_cfg->requested_sensors = ML_THREE_AXIS_GYRO; if (mldl_cfg->accel && mldl_cfg->accel->resume) mldl_cfg->requested_sensors |= ML_THREE_AXIS_ACCEL; if (mldl_cfg->compass && mldl_cfg->compass->resume) mldl_cfg->requested_sensors |= ML_THREE_AXIS_COMPASS; if (mldl_cfg->pressure && mldl_cfg->pressure->resume) mldl_cfg->requested_sensors |= ML_THREE_AXIS_PRESSURE; return result; out_compass: if (mldl_cfg->compass->init) mldl_cfg->compass->exit(compass_handle, mldl_cfg->compass, &mldl_cfg->pdata->compass); out_accel: if (mldl_cfg->accel->init) mldl_cfg->accel->exit(accel_handle, mldl_cfg->accel, &mldl_cfg->pdata->accel); return result; } /** * Close the mpu3050 interface * * @param mldl_cfg pointer to the configuration structure * @param mlsl_handle pointer to the serial layer handle * * @return ML_SUCCESS or non-zero error code */ int mpu3050_close(struct mldl_cfg *mldl_cfg, void *mlsl_handle, void *accel_handle, void *compass_handle, void *pressure_handle) { int result = ML_SUCCESS; int ret_result = ML_SUCCESS; if (mldl_cfg->accel && mldl_cfg->accel->exit) { result = mldl_cfg->accel->exit(accel_handle, mldl_cfg->accel, &mldl_cfg->pdata->accel); if (ML_SUCCESS != result) MPL_LOGE("Accel exit failed %d\n", result); ret_result = result; } if (ML_SUCCESS == ret_result) ret_result = result; if (mldl_cfg->compass && mldl_cfg->compass->exit) { result = mldl_cfg->compass->exit(compass_handle, mldl_cfg->compass, &mldl_cfg->pdata->compass); if (ML_SUCCESS != result) MPL_LOGE("Compass exit failed %d\n", result); } if (ML_SUCCESS == ret_result) ret_result = result; if (mldl_cfg->pressure && mldl_cfg->pressure->exit) { result = mldl_cfg->pressure->exit(pressure_handle, mldl_cfg->pressure, &mldl_cfg->pdata->pressure); if (ML_SUCCESS != result) MPL_LOGE("Pressure exit failed %d\n", result); } if (ML_SUCCESS == ret_result) ret_result = result; return ret_result; } /** * @brief resume the MPU3050 device and all the other sensor * devices from their low power state. * * @param mldl_cfg * pointer to the configuration structure * @param gyro_handle * the main file handle to the MPU3050 device. * @param accel_handle * an handle to the accelerometer device, if sitting * onto a separate bus. Can match mlsl_handle if * the accelerometer device operates on the same * primary bus of MPU. * @param compass_handle * an handle to the compass device, if sitting * onto a separate bus. Can match mlsl_handle if * the compass device operates on the same * primary bus of MPU. * @param pressure_handle * an handle to the pressure sensor device, if sitting * onto a separate bus. Can match mlsl_handle if * the pressure sensor device operates on the same * primary bus of MPU. * @param resume_gyro * whether resuming the gyroscope device is * actually needed (if the device supports low power * mode of some sort). * @param resume_accel * whether resuming the accelerometer device is * actually needed (if the device supports low power * mode of some sort). * @param resume_compass * whether resuming the compass device is * actually needed (if the device supports low power * mode of some sort). * @param resume_pressure * whether resuming the pressure sensor device is * actually needed (if the device supports low power * mode of some sort). * @return ML_SUCCESS or a non-zero error code. */ int mpu3050_resume(struct mldl_cfg *mldl_cfg, void *gyro_handle, void *accel_handle, void *compass_handle, void *pressure_handle, bool resume_gyro, bool resume_accel, bool resume_compass, bool resume_pressure) { int result = ML_SUCCESS; mutex_lock(&mldl_cfg->mutex); #ifdef CONFIG_MPU_SENSORS_DEBUG mpu_print_cfg(mldl_cfg); #endif if (resume_accel && ((!mldl_cfg->accel) || (!mldl_cfg->accel->resume))) return ML_ERROR_INVALID_PARAMETER; if (resume_compass && ((!mldl_cfg->compass) || (!mldl_cfg->compass->resume))) return ML_ERROR_INVALID_PARAMETER; if (resume_pressure && ((!mldl_cfg->pressure) || (!mldl_cfg->pressure->resume))) return ML_ERROR_INVALID_PARAMETER; if (resume_gyro && mldl_cfg->gyro_is_suspended) { result = gyro_resume(mldl_cfg, gyro_handle); ERROR_CHECK_WITH_MUTEX_UNLOCK(result,&mldl_cfg->mutex); } if (resume_accel && mldl_cfg->accel_is_suspended) { if (!mldl_cfg->gyro_is_suspended && EXT_SLAVE_BUS_SECONDARY == mldl_cfg->pdata->accel.bus) { result = MLDLSetI2CBypass(mldl_cfg, gyro_handle, TRUE); ERROR_CHECK_WITH_MUTEX_UNLOCK(result,&mldl_cfg->mutex); } #ifdef FEATURE_USES_MPU_ACCEL result = mpu_accel_resume(mldl_cfg); #else result = mldl_cfg->accel->resume(accel_handle, mldl_cfg->accel, &mldl_cfg->pdata->accel); #endif ERROR_CHECK_WITH_MUTEX_UNLOCK(result,&mldl_cfg->mutex); mldl_cfg->accel_is_suspended = FALSE; } if (!mldl_cfg->gyro_is_suspended && !mldl_cfg->accel_is_suspended && EXT_SLAVE_BUS_SECONDARY == mldl_cfg->pdata->accel.bus) { result = mpu_set_slave(mldl_cfg, gyro_handle, mldl_cfg->accel, &mldl_cfg->pdata->accel); ERROR_CHECK_WITH_MUTEX_UNLOCK(result,&mldl_cfg->mutex); } if (resume_compass && mldl_cfg->compass_is_suspended) { if (!mldl_cfg->gyro_is_suspended && EXT_SLAVE_BUS_SECONDARY == mldl_cfg->pdata->compass.bus) { result = MLDLSetI2CBypass(mldl_cfg, gyro_handle, TRUE); ERROR_CHECK_WITH_MUTEX_UNLOCK(result,&mldl_cfg->mutex); } result = mldl_cfg->compass->resume(compass_handle, mldl_cfg->compass, &mldl_cfg->pdata-> compass); ERROR_CHECK_WITH_MUTEX_UNLOCK(result,&mldl_cfg->mutex); mldl_cfg->compass_is_suspended = FALSE; } if (!mldl_cfg->gyro_is_suspended && !mldl_cfg->compass_is_suspended && EXT_SLAVE_BUS_SECONDARY == mldl_cfg->pdata->compass.bus) { result = mpu_set_slave(mldl_cfg, gyro_handle, mldl_cfg->compass, &mldl_cfg->pdata->compass); ERROR_CHECK_WITH_MUTEX_UNLOCK(result,&mldl_cfg->mutex); } if (resume_pressure && mldl_cfg->pressure_is_suspended) { if (!mldl_cfg->gyro_is_suspended && EXT_SLAVE_BUS_SECONDARY == mldl_cfg->pdata->pressure.bus) { result = MLDLSetI2CBypass(mldl_cfg, gyro_handle, TRUE); ERROR_CHECK_WITH_MUTEX_UNLOCK(result,&mldl_cfg->mutex); } result = mldl_cfg->pressure->resume(pressure_handle, mldl_cfg->pressure, &mldl_cfg->pdata-> pressure); ERROR_CHECK_WITH_MUTEX_UNLOCK(result,&mldl_cfg->mutex); mldl_cfg->pressure_is_suspended = FALSE; } if (!mldl_cfg->gyro_is_suspended && !mldl_cfg->pressure_is_suspended && EXT_SLAVE_BUS_SECONDARY == mldl_cfg->pdata->pressure.bus) { result = mpu_set_slave(mldl_cfg, gyro_handle, mldl_cfg->pressure, &mldl_cfg->pdata->pressure); ERROR_CHECK_WITH_MUTEX_UNLOCK(result,&mldl_cfg->mutex); } /* Now start */ if (resume_gyro) { result = dmp_start(mldl_cfg, gyro_handle); ERROR_CHECK_WITH_MUTEX_UNLOCK(result,&mldl_cfg->mutex); } mutex_unlock(&mldl_cfg->mutex); return result; } /** * @brief suspend the MPU3050 device and all the other sensor * devices into their low power state. * @param gyro_handle * the main file handle to the MPU3050 device. * @param accel_handle * an handle to the accelerometer device, if sitting * onto a separate bus. Can match gyro_handle if * the accelerometer device operates on the same * primary bus of MPU. * @param compass_handle * an handle to the compass device, if sitting * onto a separate bus. Can match gyro_handle if * the compass device operates on the same * primary bus of MPU. * @param pressure_handle * an handle to the pressure sensor device, if sitting * onto a separate bus. Can match gyro_handle if * the pressure sensor device operates on the same * primary bus of MPU. * @param accel * whether suspending the accelerometer device is * actually needed (if the device supports low power * mode of some sort). * @param compass * whether suspending the compass device is * actually needed (if the device supports low power * mode of some sort). * @param pressure * whether suspending the pressure sensor device is * actually needed (if the device supports low power * mode of some sort). * @return ML_SUCCESS or a non-zero error code. */ int mpu3050_suspend(struct mldl_cfg *mldl_cfg, void *gyro_handle, void *accel_handle, void *compass_handle, void *pressure_handle, bool suspend_gyro, bool suspend_accel, bool suspend_compass, bool suspend_pressure) { int result = ML_SUCCESS; mutex_lock(&mldl_cfg->mutex); if (suspend_gyro && !mldl_cfg->gyro_is_suspended) { #ifdef M_HW return ML_SUCCESS; /* This puts the bus into bypass mode */ result = MLDLSetI2CBypass(mldl_cfg, gyro_handle, 1); ERROR_CHECK_WITH_MUTEX_UNLOCK(result,&mldl_cfg->mutex); result = mpu60xx_pwr_mgmt(mldl_cfg, gyro_handle, 0, SLEEP); #else result = MLDLPowerMgmtMPU(mldl_cfg, gyro_handle, 0, SLEEP, 0, 0, 0); #endif ERROR_CHECK_WITH_MUTEX_UNLOCK(result,&mldl_cfg->mutex); } if (!mldl_cfg->accel_is_suspended && suspend_accel && mldl_cfg->accel && mldl_cfg->accel->suspend) { if (!mldl_cfg->gyro_is_suspended && EXT_SLAVE_BUS_SECONDARY == mldl_cfg->pdata->accel.bus) { result = mpu_set_slave(mldl_cfg, gyro_handle, NULL, NULL); ERROR_CHECK_WITH_MUTEX_UNLOCK(result,&mldl_cfg->mutex); } #ifdef FEATURE_USES_MPU_ACCEL result = mpu_accel_suspend(mldl_cfg); #else result = mldl_cfg->accel->suspend(accel_handle, mldl_cfg->accel, &mldl_cfg->pdata->accel); #endif ERROR_CHECK_WITH_MUTEX_UNLOCK(result,&mldl_cfg->mutex); mldl_cfg->accel_is_suspended = TRUE; } if (!mldl_cfg->compass_is_suspended && suspend_compass && mldl_cfg->compass && mldl_cfg->compass->suspend) { if (!mldl_cfg->gyro_is_suspended && EXT_SLAVE_BUS_SECONDARY == mldl_cfg->pdata->compass.bus) { result = mpu_set_slave(mldl_cfg, gyro_handle, NULL, NULL); ERROR_CHECK_WITH_MUTEX_UNLOCK(result,&mldl_cfg->mutex); } result = mldl_cfg->compass->suspend(compass_handle, mldl_cfg->compass, &mldl_cfg-> pdata->compass); ERROR_CHECK_WITH_MUTEX_UNLOCK(result,&mldl_cfg->mutex); mldl_cfg->compass_is_suspended = TRUE; } if (!mldl_cfg->pressure_is_suspended && suspend_pressure && mldl_cfg->pressure && mldl_cfg->pressure->suspend) { if (!mldl_cfg->gyro_is_suspended && EXT_SLAVE_BUS_SECONDARY == mldl_cfg->pdata->pressure.bus) { result = mpu_set_slave(mldl_cfg, gyro_handle, NULL, NULL); ERROR_CHECK_WITH_MUTEX_UNLOCK(result,&mldl_cfg->mutex); } result = mldl_cfg->pressure->suspend(pressure_handle, mldl_cfg->pressure, &mldl_cfg-> pdata->pressure); ERROR_CHECK_WITH_MUTEX_UNLOCK(result,&mldl_cfg->mutex); mldl_cfg->pressure_is_suspended = TRUE; } mutex_unlock(&mldl_cfg->mutex); return result; } /** * @brief read raw sensor data from the accelerometer device * in use. * @param mldl_cfg * A pointer to the struct mldl_cfg data structure. * @param accel_handle * The handle to the device the accelerometer is connected to. * @param data * a buffer to store the raw sensor data. * @return ML_SUCCESS if successful, a non-zero error code otherwise. */ int mpu3050_read_accel(struct mldl_cfg *mldl_cfg, void *accel_handle, unsigned char *data) { if (NULL != mldl_cfg->accel && NULL != mldl_cfg->accel->read) if ((EXT_SLAVE_BUS_SECONDARY == mldl_cfg->pdata->accel.bus) && (!mldl_cfg->gyro_is_bypassed)) return ML_ERROR_FEATURE_NOT_ENABLED; else return mldl_cfg->accel->read(accel_handle, mldl_cfg->accel, &mldl_cfg->pdata->accel, data); else return ML_ERROR_FEATURE_NOT_IMPLEMENTED; } /** * @brief read raw sensor data from the compass device * in use. * @param mldl_cfg * A pointer to the struct mldl_cfg data structure. * @param compass_handle * The handle to the device the compass is connected to. * @param data * a buffer to store the raw sensor data. * @return ML_SUCCESS if successful, a non-zero error code otherwise. */ int mpu3050_read_compass(struct mldl_cfg *mldl_cfg, void *compass_handle, unsigned char *data) { if (NULL != mldl_cfg->compass && NULL != mldl_cfg->compass->read) if ((EXT_SLAVE_BUS_SECONDARY == mldl_cfg->pdata->compass.bus) && (!mldl_cfg->gyro_is_bypassed)) return ML_ERROR_FEATURE_NOT_ENABLED; else return mldl_cfg->compass->read(compass_handle, mldl_cfg->compass, &mldl_cfg->pdata->compass, data); else return ML_ERROR_FEATURE_NOT_IMPLEMENTED; } /** * @brief read raw sensor data from the pressure device * in use. * @param mldl_cfg * A pointer to the struct mldl_cfg data structure. * @param pressure_handle * The handle to the device the pressure sensor is connected to. * @param data * a buffer to store the raw sensor data. * @return ML_SUCCESS if successful, a non-zero error code otherwise. */ int mpu3050_read_pressure(struct mldl_cfg *mldl_cfg, void *pressure_handle, unsigned char *data) { if (NULL != mldl_cfg->pressure && NULL != mldl_cfg->pressure->read) if ((EXT_SLAVE_BUS_SECONDARY == mldl_cfg->pdata->pressure.bus) && (!mldl_cfg->gyro_is_bypassed)) return ML_ERROR_FEATURE_NOT_ENABLED; else return mldl_cfg->pressure->read( pressure_handle, mldl_cfg->pressure, &mldl_cfg->pdata->pressure, data); else return ML_ERROR_FEATURE_NOT_IMPLEMENTED; } int mpu3050_config_accel(struct mldl_cfg *mldl_cfg, void *accel_handle, struct ext_slave_config *data) { if (NULL != mldl_cfg->accel && NULL != mldl_cfg->accel->config) return mldl_cfg->accel->config(accel_handle, mldl_cfg->accel, &mldl_cfg->pdata->accel, data); else return ML_ERROR_FEATURE_NOT_IMPLEMENTED; } int mpu3050_config_compass(struct mldl_cfg *mldl_cfg, void *compass_handle, struct ext_slave_config *data) { if (NULL != mldl_cfg->compass && NULL != mldl_cfg->compass->config) return mldl_cfg->compass->config(compass_handle, mldl_cfg->compass, &mldl_cfg->pdata->compass, data); else return ML_ERROR_FEATURE_NOT_IMPLEMENTED; } int mpu3050_config_pressure(struct mldl_cfg *mldl_cfg, void *pressure_handle, struct ext_slave_config *data) { if (NULL != mldl_cfg->pressure && NULL != mldl_cfg->pressure->config) return mldl_cfg->pressure->config(pressure_handle, mldl_cfg->pressure, &mldl_cfg->pdata->pressure, data); else return ML_ERROR_FEATURE_NOT_IMPLEMENTED; } int mpu3050_get_config_accel(struct mldl_cfg *mldl_cfg, void *accel_handle, struct ext_slave_config *data) { if (NULL != mldl_cfg->accel && NULL != mldl_cfg->accel->get_config) return mldl_cfg->accel->get_config(accel_handle, mldl_cfg->accel, &mldl_cfg->pdata->accel, data); else return ML_ERROR_FEATURE_NOT_IMPLEMENTED; } int mpu3050_get_config_compass(struct mldl_cfg *mldl_cfg, void *compass_handle, struct ext_slave_config *data) { if (NULL != mldl_cfg->compass && NULL != mldl_cfg->compass->get_config) return mldl_cfg->compass->get_config(compass_handle, mldl_cfg->compass, &mldl_cfg->pdata->compass, data); else return ML_ERROR_FEATURE_NOT_IMPLEMENTED; } int mpu3050_get_config_pressure(struct mldl_cfg *mldl_cfg, void *pressure_handle, struct ext_slave_config *data) { if (NULL != mldl_cfg->pressure && NULL != mldl_cfg->pressure->get_config) return mldl_cfg->pressure->get_config(pressure_handle, mldl_cfg->pressure, &mldl_cfg->pdata->pressure, data); else return ML_ERROR_FEATURE_NOT_IMPLEMENTED; } /** *@} */
CyanogenMod/lge-kernel-star
drivers/misc/mpu3050/mldl_cfg.c
C
gpl-2.0
53,418
#!/usr/bin/env python # Copyright 2008, 2009 Hannes Hochreiner # 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/. # These lines are only needed if you don't put the script directly into # the installation directory import sys # Unix sys.path.append('/usr/share/inkscape/extensions') # OS X sys.path.append('/Applications/Inkscape.app/Contents/Resources/extensions') # Windows sys.path.append('C:\Program Files\Inkscape\share\extensions') # We will use the inkex module with the predefined Effect base class. import inkex inkex.localize() class JessyInk_Effects(inkex.Effect): def __init__(self): # Call the base class constructor. inkex.Effect.__init__(self) self.OptionParser.add_option('--tab', action = 'store', type = 'string', dest = 'what') self.OptionParser.add_option('--effectInOrder', action = 'store', type = 'string', dest = 'effectInOrder', default = 1) self.OptionParser.add_option('--effectInDuration', action = 'store', type = 'float', dest = 'effectInDuration', default = 0.8) self.OptionParser.add_option('--effectIn', action = 'store', type = 'string', dest = 'effectIn', default = 'none') self.OptionParser.add_option('--effectOutOrder', action = 'store', type = 'string', dest = 'effectOutOrder', default = 2) self.OptionParser.add_option('--effectOutDuration', action = 'store', type = 'float', dest = 'effectOutDuration', default = 0.8) self.OptionParser.add_option('--effectOut', action = 'store', type = 'string', dest = 'effectOut', default = 'none') inkex.NSS[u"jessyink"] = u"https://launchpad.net/jessyink" def effect(self): # Check version. scriptNodes = self.document.xpath("//svg:script[@jessyink:version='1.5.5']", namespaces=inkex.NSS) if len(scriptNodes) != 1: inkex.errormsg(_("The JessyInk script is not installed in this SVG file or has a different version than the JessyInk extensions. Please select \"install/update...\" from the \"JessyInk\" sub-menu of the \"Extensions\" menu to install or update the JessyInk script.\n\n")) if len(self.selected) == 0: inkex.errormsg(_("No object selected. Please select the object you want to assign an effect to and then press apply.\n")) for id, node in self.selected.items(): if (self.options.effectIn == "appear") or (self.options.effectIn == "fade") or (self.options.effectIn == "pop"): node.set("{" + inkex.NSS["jessyink"] + "}effectIn","name:" + self.options.effectIn + ";order:" + self.options.effectInOrder + ";length:" + str(int(self.options.effectInDuration * 1000))) # Remove possible view argument. if node.attrib.has_key("{" + inkex.NSS["jessyink"] + "}view"): del node.attrib["{" + inkex.NSS["jessyink"] + "}view"] else: if node.attrib.has_key("{" + inkex.NSS["jessyink"] + "}effectIn"): del node.attrib["{" + inkex.NSS["jessyink"] + "}effectIn"] if (self.options.effectOut == "appear") or (self.options.effectOut == "fade") or (self.options.effectOut == "pop"): node.set("{" + inkex.NSS["jessyink"] + "}effectOut","name:" + self.options.effectOut + ";order:" + self.options.effectOutOrder + ";length:" + str(int(self.options.effectOutDuration * 1000))) # Remove possible view argument. if node.attrib.has_key("{" + inkex.NSS["jessyink"] + "}view"): del node.attrib["{" + inkex.NSS["jessyink"] + "}view"] else: if node.attrib.has_key("{" + inkex.NSS["jessyink"] + "}effectOut"): del node.attrib["{" + inkex.NSS["jessyink"] + "}effectOut"] # Create effect instance effect = JessyInk_Effects() effect.affect()
danieljabailey/inkscape_experiments
share/extensions/jessyInk_effects.py
Python
gpl-2.0
4,100
/****************************************************************************** * Product: Adempiere ERP & CRM Smart Business Solution * * Copyright (C) 1999-2007 ComPiere, Inc. All Rights Reserved. * * This program is free software, you can redistribute it and/or modify it * * under the terms version 2 of the GNU General Public License 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. * * For the text or an alternative of this public license, you may reach us * * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * * or via [email protected] or http://www.compiere.org/license.html * *****************************************************************************/ /** Generated Model - DO NOT CHANGE */ package org.compiere.model; import java.math.BigDecimal; import java.sql.ResultSet; import java.sql.Timestamp; import java.util.Properties; import org.compiere.util.Env; import org.compiere.util.KeyNamePair; /** Generated Model for A_Depreciation_Entry * @author Adempiere (generated) * @version Release 3.8.0 - $Id$ */ public class X_A_Depreciation_Entry extends PO implements I_A_Depreciation_Entry, I_Persistent { /** * */ private static final long serialVersionUID = 20150223L; /** Standard Constructor */ public X_A_Depreciation_Entry (Properties ctx, int A_Depreciation_Entry_ID, String trxName) { super (ctx, A_Depreciation_Entry_ID, trxName); /** if (A_Depreciation_Entry_ID == 0) { setA_Depreciation_Entry_ID (0); setC_AcctSchema_ID (0); setC_Currency_ID (0); // @$C_CURRENCY_ID@ setC_DocType_ID (0); setC_Period_ID (0); setDateAcct (new Timestamp( System.currentTimeMillis() )); // @Date@ setDateDoc (new Timestamp( System.currentTimeMillis() )); // @#Date@ setDocAction (null); // 'CO' setDocStatus (null); // 'DR' setDocumentNo (null); setIsApproved (false); // @#IsCanApproveOwnDoc@ setPosted (false); // 'N' setPostingType (null); // 'A' setProcessed (false); setProcessing (false); } */ } /** Load Constructor */ public X_A_Depreciation_Entry (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } /** AccessLevel * @return 3 - Client - Org */ protected int get_AccessLevel() { return accessLevel.intValue(); } /** Load Meta Data */ protected POInfo initPO (Properties ctx) { POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName()); return poi; } public String toString() { StringBuffer sb = new StringBuffer ("X_A_Depreciation_Entry[") .append(get_ID()).append("]"); return sb.toString(); } /** Set Depreciation Entry. @param A_Depreciation_Entry_ID Depreciation Entry */ public void setA_Depreciation_Entry_ID (int A_Depreciation_Entry_ID) { if (A_Depreciation_Entry_ID < 1) set_ValueNoCheck (COLUMNNAME_A_Depreciation_Entry_ID, null); else set_ValueNoCheck (COLUMNNAME_A_Depreciation_Entry_ID, Integer.valueOf(A_Depreciation_Entry_ID)); } /** Get Depreciation Entry. @return Depreciation Entry */ public int getA_Depreciation_Entry_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_A_Depreciation_Entry_ID); if (ii == null) return 0; return ii.intValue(); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), String.valueOf(getA_Depreciation_Entry_ID())); } /** A_Entry_Type AD_Reference_ID=53257 */ public static final int A_ENTRY_TYPE_AD_Reference_ID=53257; /** Depreciation = DEP */ public static final String A_ENTRY_TYPE_Depreciation = "DEP"; /** Disposals = DIS */ public static final String A_ENTRY_TYPE_Disposals = "DIS"; /** Forecasts = FOR */ public static final String A_ENTRY_TYPE_Forecasts = "FOR"; /** New = NEW */ public static final String A_ENTRY_TYPE_New = "NEW"; /** Splits = SPL */ public static final String A_ENTRY_TYPE_Splits = "SPL"; /** Transfers = TRN */ public static final String A_ENTRY_TYPE_Transfers = "TRN"; /** Set Entry Type. @param A_Entry_Type Entry Type */ public void setA_Entry_Type (String A_Entry_Type) { set_Value (COLUMNNAME_A_Entry_Type, A_Entry_Type); } /** Get Entry Type. @return Entry Type */ public String getA_Entry_Type () { return (String)get_Value(COLUMNNAME_A_Entry_Type); } public org.compiere.model.I_C_AcctSchema getC_AcctSchema() throws RuntimeException { return (org.compiere.model.I_C_AcctSchema)MTable.get(getCtx(), org.compiere.model.I_C_AcctSchema.Table_Name) .getPO(getC_AcctSchema_ID(), get_TrxName()); } /** Set Accounting Schema. @param C_AcctSchema_ID Rules for accounting */ public void setC_AcctSchema_ID (int C_AcctSchema_ID) { if (C_AcctSchema_ID < 1) set_Value (COLUMNNAME_C_AcctSchema_ID, null); else set_Value (COLUMNNAME_C_AcctSchema_ID, Integer.valueOf(C_AcctSchema_ID)); } /** Get Accounting Schema. @return Rules for accounting */ public int getC_AcctSchema_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_AcctSchema_ID); if (ii == null) return 0; return ii.intValue(); } public org.compiere.model.I_C_Currency getC_Currency() throws RuntimeException { return (org.compiere.model.I_C_Currency)MTable.get(getCtx(), org.compiere.model.I_C_Currency.Table_Name) .getPO(getC_Currency_ID(), get_TrxName()); } /** Set Currency. @param C_Currency_ID The Currency for this record */ public void setC_Currency_ID (int C_Currency_ID) { if (C_Currency_ID < 1) set_Value (COLUMNNAME_C_Currency_ID, null); else set_Value (COLUMNNAME_C_Currency_ID, Integer.valueOf(C_Currency_ID)); } /** Get Currency. @return The Currency for this record */ public int getC_Currency_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Currency_ID); if (ii == null) return 0; return ii.intValue(); } public org.compiere.model.I_C_DocType getC_DocType() throws RuntimeException { return (org.compiere.model.I_C_DocType)MTable.get(getCtx(), org.compiere.model.I_C_DocType.Table_Name) .getPO(getC_DocType_ID(), get_TrxName()); } /** Set Document Type. @param C_DocType_ID Document type or rules */ public void setC_DocType_ID (int C_DocType_ID) { if (C_DocType_ID < 0) set_Value (COLUMNNAME_C_DocType_ID, null); else set_Value (COLUMNNAME_C_DocType_ID, Integer.valueOf(C_DocType_ID)); } /** Get Document Type. @return Document type or rules */ public int getC_DocType_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_DocType_ID); if (ii == null) return 0; return ii.intValue(); } public org.compiere.model.I_C_Period getC_Period() throws RuntimeException { return (org.compiere.model.I_C_Period)MTable.get(getCtx(), org.compiere.model.I_C_Period.Table_Name) .getPO(getC_Period_ID(), get_TrxName()); } /** Set Period. @param C_Period_ID Period of the Calendar */ public void setC_Period_ID (int C_Period_ID) { if (C_Period_ID < 1) set_Value (COLUMNNAME_C_Period_ID, null); else set_Value (COLUMNNAME_C_Period_ID, Integer.valueOf(C_Period_ID)); } /** Get Period. @return Period of the Calendar */ public int getC_Period_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Period_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Account Date. @param DateAcct Accounting Date */ public void setDateAcct (Timestamp DateAcct) { set_Value (COLUMNNAME_DateAcct, DateAcct); } /** Get Account Date. @return Accounting Date */ public Timestamp getDateAcct () { return (Timestamp)get_Value(COLUMNNAME_DateAcct); } /** Set Document Date. @param DateDoc Date of the Document */ public void setDateDoc (Timestamp DateDoc) { set_Value (COLUMNNAME_DateDoc, DateDoc); } /** Get Document Date. @return Date of the Document */ public Timestamp getDateDoc () { return (Timestamp)get_Value(COLUMNNAME_DateDoc); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** DocAction AD_Reference_ID=135 */ public static final int DOCACTION_AD_Reference_ID=135; /** Complete = CO */ public static final String DOCACTION_Complete = "CO"; /** Approve = AP */ public static final String DOCACTION_Approve = "AP"; /** Reject = RJ */ public static final String DOCACTION_Reject = "RJ"; /** Post = PO */ public static final String DOCACTION_Post = "PO"; /** Void = VO */ public static final String DOCACTION_Void = "VO"; /** Close = CL */ public static final String DOCACTION_Close = "CL"; /** Reverse - Correct = RC */ public static final String DOCACTION_Reverse_Correct = "RC"; /** Reverse - Accrual = RA */ public static final String DOCACTION_Reverse_Accrual = "RA"; /** Invalidate = IN */ public static final String DOCACTION_Invalidate = "IN"; /** Re-activate = RE */ public static final String DOCACTION_Re_Activate = "RE"; /** <None> = -- */ public static final String DOCACTION_None = "--"; /** Prepare = PR */ public static final String DOCACTION_Prepare = "PR"; /** Unlock = XL */ public static final String DOCACTION_Unlock = "XL"; /** Wait Complete = WC */ public static final String DOCACTION_WaitComplete = "WC"; /** Set Document Action. @param DocAction The targeted status of the document */ public void setDocAction (String DocAction) { set_Value (COLUMNNAME_DocAction, DocAction); } /** Get Document Action. @return The targeted status of the document */ public String getDocAction () { return (String)get_Value(COLUMNNAME_DocAction); } /** DocStatus AD_Reference_ID=131 */ public static final int DOCSTATUS_AD_Reference_ID=131; /** Drafted = DR */ public static final String DOCSTATUS_Drafted = "DR"; /** Completed = CO */ public static final String DOCSTATUS_Completed = "CO"; /** Approved = AP */ public static final String DOCSTATUS_Approved = "AP"; /** Not Approved = NA */ public static final String DOCSTATUS_NotApproved = "NA"; /** Voided = VO */ public static final String DOCSTATUS_Voided = "VO"; /** Invalid = IN */ public static final String DOCSTATUS_Invalid = "IN"; /** Reversed = RE */ public static final String DOCSTATUS_Reversed = "RE"; /** Closed = CL */ public static final String DOCSTATUS_Closed = "CL"; /** Unknown = ?? */ public static final String DOCSTATUS_Unknown = "??"; /** In Progress = IP */ public static final String DOCSTATUS_InProgress = "IP"; /** Waiting Payment = WP */ public static final String DOCSTATUS_WaitingPayment = "WP"; /** Waiting Confirmation = WC */ public static final String DOCSTATUS_WaitingConfirmation = "WC"; /** Set Document Status. @param DocStatus The current status of the document */ public void setDocStatus (String DocStatus) { set_Value (COLUMNNAME_DocStatus, DocStatus); } /** Get Document Status. @return The current status of the document */ public String getDocStatus () { return (String)get_Value(COLUMNNAME_DocStatus); } /** Set Document No. @param DocumentNo Document sequence number of the document */ public void setDocumentNo (String DocumentNo) { set_Value (COLUMNNAME_DocumentNo, DocumentNo); } /** Get Document No. @return Document sequence number of the document */ public String getDocumentNo () { return (String)get_Value(COLUMNNAME_DocumentNo); } public org.compiere.model.I_GL_Category getGL_Category() throws RuntimeException { return (org.compiere.model.I_GL_Category)MTable.get(getCtx(), org.compiere.model.I_GL_Category.Table_Name) .getPO(getGL_Category_ID(), get_TrxName()); } /** Set GL Category. @param GL_Category_ID General Ledger Category */ public void setGL_Category_ID (int GL_Category_ID) { if (GL_Category_ID < 1) set_Value (COLUMNNAME_GL_Category_ID, null); else set_Value (COLUMNNAME_GL_Category_ID, Integer.valueOf(GL_Category_ID)); } /** Get GL Category. @return General Ledger Category */ public int getGL_Category_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_GL_Category_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Approved. @param IsApproved Indicates if this document requires approval */ public void setIsApproved (boolean IsApproved) { set_Value (COLUMNNAME_IsApproved, Boolean.valueOf(IsApproved)); } /** Get Approved. @return Indicates if this document requires approval */ public boolean isApproved () { Object oo = get_Value(COLUMNNAME_IsApproved); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Posted. @param Posted Posting status */ public void setPosted (boolean Posted) { set_Value (COLUMNNAME_Posted, Boolean.valueOf(Posted)); } /** Get Posted. @return Posting status */ public boolean isPosted () { Object oo = get_Value(COLUMNNAME_Posted); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** PostingType AD_Reference_ID=125 */ public static final int POSTINGTYPE_AD_Reference_ID=125; /** Actual = A */ public static final String POSTINGTYPE_Actual = "A"; /** Budget = B */ public static final String POSTINGTYPE_Budget = "B"; /** Commitment = E */ public static final String POSTINGTYPE_Commitment = "E"; /** Statistical = S */ public static final String POSTINGTYPE_Statistical = "S"; /** Reservation = R */ public static final String POSTINGTYPE_Reservation = "R"; /** Set PostingType. @param PostingType The type of posted amount for the transaction */ public void setPostingType (String PostingType) { set_Value (COLUMNNAME_PostingType, PostingType); } /** Get PostingType. @return The type of posted amount for the transaction */ public String getPostingType () { return (String)get_Value(COLUMNNAME_PostingType); } /** Set Processed. @param Processed The document has been processed */ public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Processed. @return The document has been processed */ public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Processed On. @param ProcessedOn The date+time (expressed in decimal format) when the document has been processed */ public void setProcessedOn (BigDecimal ProcessedOn) { set_Value (COLUMNNAME_ProcessedOn, ProcessedOn); } /** Get Processed On. @return The date+time (expressed in decimal format) when the document has been processed */ public BigDecimal getProcessedOn () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_ProcessedOn); if (bd == null) return Env.ZERO; return bd; } /** Set Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
TaymourReda/-https-github.com-adempiere-adempiere
base/src/org/compiere/model/X_A_Depreciation_Entry.java
Java
gpl-2.0
16,399
// clang-format off /* ---------------------------------------------------------------------- LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator https://www.lammps.org/, Sandia National Laboratories Steve Plimpton, [email protected] Copyright (2003) Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. This software is distributed under the GNU General Public License. See the README file in the top-level LAMMPS directory. ------------------------------------------------------------------------- */ /* ---------------------------------------------------------------------- Contributing author: Pavel Elkind (Gothenburg University) ------------------------------------------------------------------------- */ #include "pair_lj_cut_tip4p_cut.h" #include <cmath> #include <cstring> #include "atom.h" #include "force.h" #include "neighbor.h" #include "neigh_list.h" #include "domain.h" #include "angle.h" #include "bond.h" #include "comm.h" #include "math_const.h" #include "memory.h" #include "error.h" using namespace LAMMPS_NS; using namespace MathConst; /* ---------------------------------------------------------------------- */ PairLJCutTIP4PCut::PairLJCutTIP4PCut(LAMMPS *lmp) : Pair(lmp) { single_enable = 0; writedata = 1; nmax = 0; hneigh = nullptr; newsite = nullptr; // TIP4P cannot compute virial as F dot r // due to finding bonded H atoms which are not near O atom no_virial_fdotr_compute = 1; } /* ---------------------------------------------------------------------- */ PairLJCutTIP4PCut::~PairLJCutTIP4PCut() { if (allocated) { memory->destroy(setflag); memory->destroy(cutsq); memory->destroy(cut_lj); memory->destroy(cut_ljsq); memory->destroy(epsilon); memory->destroy(sigma); memory->destroy(lj1); memory->destroy(lj2); memory->destroy(lj3); memory->destroy(lj4); memory->destroy(offset); } memory->destroy(hneigh); memory->destroy(newsite); } /* ---------------------------------------------------------------------- */ void PairLJCutTIP4PCut::compute(int eflag, int vflag) { int i,j,ii,jj,inum,jnum,itype,jtype; double qtmp,xtmp,ytmp,ztmp,delx,dely,delz,evdwl,ecoul; double rsq,r2inv,r6inv,forcecoul,forcelj,factor_lj,factor_coul; int *ilist,*jlist,*numneigh,**firstneigh; int key; int n,vlist[6]; int iH1,iH2,jH1,jH2; double cforce; double fO[3],fH[3],fd[3],v[6]; double *x1,*x2,*xH1,*xH2; evdwl = ecoul = 0.0; ev_init(eflag,vflag); // reallocate hneigh & newsite if necessary // initialize hneigh[0] to -1 on steps when reneighboring occurred // initialize hneigh[2] to 0 every step int nlocal = atom->nlocal; int nall = nlocal + atom->nghost; if (atom->nmax > nmax) { nmax = atom->nmax; memory->destroy(hneigh); memory->create(hneigh,nmax,3,"pair:hneigh"); memory->destroy(newsite); memory->create(newsite,nmax,3,"pair:newsite"); } if (neighbor->ago == 0) for (i = 0; i < nall; i++) hneigh[i][0] = -1; for (i = 0; i < nall; i++) hneigh[i][2] = 0; double **f = atom->f; double **x = atom->x; double *q = atom->q; tagint *tag = atom->tag; int *type = atom->type; double *special_lj = force->special_lj; double *special_coul = force->special_coul; int newton_pair = force->newton_pair; double qqrd2e = force->qqrd2e; inum = list->inum; ilist = list->ilist; numneigh = list->numneigh; firstneigh = list->firstneigh; // loop over neighbors of my atoms for (ii = 0; ii < inum; ii++) { i = ilist[ii]; qtmp = q[i]; xtmp = x[i][0]; ytmp = x[i][1]; ztmp = x[i][2]; itype = type[i]; if (itype == typeO) { if (hneigh[i][0] < 0) { iH1 = atom->map(tag[i] + 1); iH2 = atom->map(tag[i] + 2); if (iH1 == -1 || iH2 == -1) error->one(FLERR,"TIP4P hydrogen is missing"); if (atom->type[iH1] != typeH || atom->type[iH2] != typeH) error->one(FLERR,"TIP4P hydrogen has incorrect atom type"); // set iH1,iH2 to index of closest image to O iH1 = domain->closest_image(i,iH1); iH2 = domain->closest_image(i,iH2); compute_newsite(x[i],x[iH1],x[iH2],newsite[i]); hneigh[i][0] = iH1; hneigh[i][1] = iH2; hneigh[i][2] = 1; } else { iH1 = hneigh[i][0]; iH2 = hneigh[i][1]; if (hneigh[i][2] == 0) { hneigh[i][2] = 1; compute_newsite(x[i],x[iH1],x[iH2],newsite[i]); } } x1 = newsite[i]; } else x1 = x[i]; jlist = firstneigh[i]; jnum = numneigh[i]; for (jj = 0; jj < jnum; jj++) { j = jlist[jj]; factor_lj = special_lj[sbmask(j)]; factor_coul = special_coul[sbmask(j)]; j &= NEIGHMASK; delx = xtmp - x[j][0]; dely = ytmp - x[j][1]; delz = ztmp - x[j][2]; rsq = delx*delx + dely*dely + delz*delz; jtype = type[j]; // LJ interaction based on true rsq if (rsq < cut_ljsq[itype][jtype]) { r2inv = 1.0/rsq; r6inv = r2inv*r2inv*r2inv; forcelj = r6inv * (lj1[itype][jtype]*r6inv - lj2[itype][jtype]); forcelj *= factor_lj * r2inv; f[i][0] += delx*forcelj; f[i][1] += dely*forcelj; f[i][2] += delz*forcelj; f[j][0] -= delx*forcelj; f[j][1] -= dely*forcelj; f[j][2] -= delz*forcelj; if (eflag) { evdwl = r6inv*(lj3[itype][jtype]*r6inv-lj4[itype][jtype]) - offset[itype][jtype]; evdwl *= factor_lj; } else evdwl = 0.0; if (evflag) ev_tally(i,j,nlocal,newton_pair, evdwl,0.0,forcelj,delx,dely,delz); } // adjust rsq and delxyz for off-site O charge(s) if necessary // but only if they are within reach if (rsq < cut_coulsqplus) { if (itype == typeO || jtype == typeO) { // if atom J = water O, set x2 = offset charge site // else x2 = x of atom J if (jtype == typeO) { if (hneigh[j][0] < 0) { jH1 = atom->map(tag[j] + 1); jH2 = atom->map(tag[j] + 2); if (jH1 == -1 || jH2 == -1) error->one(FLERR,"TIP4P hydrogen is missing"); if (atom->type[jH1] != typeH || atom->type[jH2] != typeH) error->one(FLERR,"TIP4P hydrogen has incorrect atom type"); // set jH1,jH2 to closest image to O jH1 = domain->closest_image(j,jH1); jH2 = domain->closest_image(j,jH2); compute_newsite(x[j],x[jH1],x[jH2],newsite[j]); hneigh[j][0] = jH1; hneigh[j][1] = jH2; hneigh[j][2] = 1; } else { jH1 = hneigh[j][0]; jH2 = hneigh[j][1]; if (hneigh[j][2] == 0) { hneigh[j][2] = 1; compute_newsite(x[j],x[jH1],x[jH2],newsite[j]); } } x2 = newsite[j]; } else x2 = x[j]; delx = x1[0] - x2[0]; dely = x1[1] - x2[1]; delz = x1[2] - x2[2]; rsq = delx*delx + dely*dely + delz*delz; } // Coulombic interaction based on modified rsq if (rsq < cut_coulsq) { r2inv = 1.0 / rsq; forcecoul = qqrd2e * qtmp * q[j] * sqrt(r2inv); cforce = factor_coul * forcecoul * r2inv; // if i,j are not O atoms, force is applied directly; // if i or j are O atoms, force is on fictitious atom & partitioned // force partitioning due to Feenstra, J Comp Chem, 20, 786 (1999) // f_f = fictitious force, fO = f_f (1 - 2 alpha), fH = alpha f_f // preserves total force and torque on water molecule // virial = sum(r x F) where each water's atoms are near xi and xj // vlist stores 2,4,6 atoms whose forces contribute to virial n = 0; key = 0; if (itype != typeO) { f[i][0] += delx * cforce; f[i][1] += dely * cforce; f[i][2] += delz * cforce; if (vflag) { v[0] = x[i][0] * delx * cforce; v[1] = x[i][1] * dely * cforce; v[2] = x[i][2] * delz * cforce; v[3] = x[i][0] * dely * cforce; v[4] = x[i][0] * delz * cforce; v[5] = x[i][1] * delz * cforce; } vlist[n++] = i; } else { key++; fd[0] = delx*cforce; fd[1] = dely*cforce; fd[2] = delz*cforce; fO[0] = fd[0]*(1.0 - alpha); fO[1] = fd[1]*(1.0 - alpha); fO[2] = fd[2]*(1.0 - alpha); fH[0] = 0.5 * alpha * fd[0]; fH[1] = 0.5 * alpha * fd[1]; fH[2] = 0.5 * alpha * fd[2]; f[i][0] += fO[0]; f[i][1] += fO[1]; f[i][2] += fO[2]; f[iH1][0] += fH[0]; f[iH1][1] += fH[1]; f[iH1][2] += fH[2]; f[iH2][0] += fH[0]; f[iH2][1] += fH[1]; f[iH2][2] += fH[2]; if (vflag) { xH1 = x[iH1]; xH2 = x[iH2]; v[0] = x[i][0]*fO[0] + xH1[0]*fH[0] + xH2[0]*fH[0]; v[1] = x[i][1]*fO[1] + xH1[1]*fH[1] + xH2[1]*fH[1]; v[2] = x[i][2]*fO[2] + xH1[2]*fH[2] + xH2[2]*fH[2]; v[3] = x[i][0]*fO[1] + xH1[0]*fH[1] + xH2[0]*fH[1]; v[4] = x[i][0]*fO[2] + xH1[0]*fH[2] + xH2[0]*fH[2]; v[5] = x[i][1]*fO[2] + xH1[1]*fH[2] + xH2[1]*fH[2]; } vlist[n++] = i; vlist[n++] = iH1; vlist[n++] = iH2; } if (jtype != typeO) { f[j][0] -= delx * cforce; f[j][1] -= dely * cforce; f[j][2] -= delz * cforce; if (vflag) { v[0] -= x[j][0] * delx * cforce; v[1] -= x[j][1] * dely * cforce; v[2] -= x[j][2] * delz * cforce; v[3] -= x[j][0] * dely * cforce; v[4] -= x[j][0] * delz * cforce; v[5] -= x[j][1] * delz * cforce; } vlist[n++] = j; } else { key += 2; fd[0] = -delx*cforce; fd[1] = -dely*cforce; fd[2] = -delz*cforce; fO[0] = fd[0]*(1 - alpha); fO[1] = fd[1]*(1 - alpha); fO[2] = fd[2]*(1 - alpha); fH[0] = 0.5 * alpha * fd[0]; fH[1] = 0.5 * alpha * fd[1]; fH[2] = 0.5 * alpha * fd[2]; f[j][0] += fO[0]; f[j][1] += fO[1]; f[j][2] += fO[2]; f[jH1][0] += fH[0]; f[jH1][1] += fH[1]; f[jH1][2] += fH[2]; f[jH2][0] += fH[0]; f[jH2][1] += fH[1]; f[jH2][2] += fH[2]; if (vflag) { xH1 = x[jH1]; xH2 = x[jH2]; v[0] += x[j][0]*fO[0] + xH1[0]*fH[0] + xH2[0]*fH[0]; v[1] += x[j][1]*fO[1] + xH1[1]*fH[1] + xH2[1]*fH[1]; v[2] += x[j][2]*fO[2] + xH1[2]*fH[2] + xH2[2]*fH[2]; v[3] += x[j][0]*fO[1] + xH1[0]*fH[1] + xH2[0]*fH[1]; v[4] += x[j][0]*fO[2] + xH1[0]*fH[2] + xH2[0]*fH[2]; v[5] += x[j][1]*fO[2] + xH1[1]*fH[2] + xH2[1]*fH[2]; } vlist[n++] = j; vlist[n++] = jH1; vlist[n++] = jH2; } if (eflag) { ecoul = qqrd2e * qtmp * q[j] * sqrt(r2inv); ecoul *= factor_coul; } else ecoul = 0.0; if (evflag) ev_tally_tip4p(key,vlist,v,ecoul,alpha); } } } } } /* ---------------------------------------------------------------------- allocate all arrays ------------------------------------------------------------------------- */ void PairLJCutTIP4PCut::allocate() { allocated = 1; int n = atom->ntypes; memory->create(setflag,n+1,n+1,"pair:setflag"); for (int i = 1; i <= n; i++) for (int j = i; j <= n; j++) setflag[i][j] = 0; memory->create(cutsq,n+1,n+1,"pair:cutsq"); memory->create(cut_lj,n+1,n+1,"pair:cut_lj"); memory->create(cut_ljsq,n+1,n+1,"pair:cut_ljsq"); memory->create(epsilon,n+1,n+1,"pair:epsilon"); memory->create(sigma,n+1,n+1,"pair:sigma"); memory->create(lj1,n+1,n+1,"pair:lj1"); memory->create(lj2,n+1,n+1,"pair:lj2"); memory->create(lj3,n+1,n+1,"pair:lj3"); memory->create(lj4,n+1,n+1,"pair:lj4"); memory->create(offset,n+1,n+1,"pair:offset"); } /* ---------------------------------------------------------------------- global settings ------------------------------------------------------------------------- */ void PairLJCutTIP4PCut::settings(int narg, char **arg) { if (narg < 6 || narg > 7) error->all(FLERR,"Illegal pair_style command"); typeO = utils::inumeric(FLERR,arg[0],false,lmp); typeH = utils::inumeric(FLERR,arg[1],false,lmp); typeB = utils::inumeric(FLERR,arg[2],false,lmp); typeA = utils::inumeric(FLERR,arg[3],false,lmp); qdist = utils::numeric(FLERR,arg[4],false,lmp); cut_lj_global = utils::numeric(FLERR,arg[5],false,lmp); if (narg == 6) cut_coul = cut_lj_global; else cut_coul = utils::numeric(FLERR,arg[6],false,lmp); cut_coulsq = cut_coul * cut_coul; cut_coulsqplus = (cut_coul + 2.0*qdist) * (cut_coul + 2.0*qdist); if (allocated) { int i,j; for (i = 1; i <= atom->ntypes; i++) for (j = i; j <= atom->ntypes; j++) if (setflag[i][j]) cut_lj[i][j] = cut_lj_global; } } /* ---------------------------------------------------------------------- set coeffs for one or more type pairs ------------------------------------------------------------------------- */ void PairLJCutTIP4PCut::coeff(int narg, char **arg) { if (narg < 4 || narg > 5) error->all(FLERR,"Incorrect args for pair coefficients"); if (!allocated) allocate(); int ilo,ihi,jlo,jhi; utils::bounds(FLERR,arg[0],1,atom->ntypes,ilo,ihi,error); utils::bounds(FLERR,arg[1],1,atom->ntypes,jlo,jhi,error); double epsilon_one = utils::numeric(FLERR,arg[2],false,lmp); double sigma_one = utils::numeric(FLERR,arg[3],false,lmp); double cut_lj_one = cut_lj_global; if (narg == 5) cut_lj_one = utils::numeric(FLERR,arg[4],false,lmp); int count = 0; for (int i = ilo; i <= ihi; i++) { for (int j = MAX(jlo,i); j <= jhi; j++) { epsilon[i][j] = epsilon_one; sigma[i][j] = sigma_one; cut_lj[i][j] = cut_lj_one; setflag[i][j] = 1; count++; } } if (count == 0) error->all(FLERR,"Incorrect args for pair coefficients"); } /* ---------------------------------------------------------------------- init specific to this pair style ------------------------------------------------------------------------- */ void PairLJCutTIP4PCut::init_style() { if (atom->tag_enable == 0) error->all(FLERR,"Pair style lj/cut/tip4p/cut requires atom IDs"); if (!force->newton_pair) error->all(FLERR, "Pair style lj/cut/tip4p/cut requires newton pair on"); if (!atom->q_flag) error->all(FLERR, "Pair style lj/cut/tip4p/cut requires atom attribute q"); if (force->bond == nullptr) error->all(FLERR,"Must use a bond style with TIP4P potential"); if (force->angle == nullptr) error->all(FLERR,"Must use an angle style with TIP4P potential"); neighbor->request(this,instance_me); // set alpha parameter double theta = force->angle->equilibrium_angle(typeA); double blen = force->bond->equilibrium_distance(typeB); alpha = qdist / (cos(0.5*theta) * blen); } /* ---------------------------------------------------------------------- init for one type pair i,j and corresponding j,i ------------------------------------------------------------------------- */ double PairLJCutTIP4PCut::init_one(int i, int j) { if (setflag[i][j] == 0) { epsilon[i][j] = mix_energy(epsilon[i][i],epsilon[j][j], sigma[i][i],sigma[j][j]); sigma[i][j] = mix_distance(sigma[i][i],sigma[j][j]); cut_lj[i][j] = mix_distance(cut_lj[i][i],cut_lj[j][j]); } // include TIP4P qdist in full cutoff, qdist = 0.0 if not TIP4P double cut = MAX(cut_lj[i][j],cut_coul+2.0*qdist); cut_ljsq[i][j] = cut_lj[i][j] * cut_lj[i][j]; lj1[i][j] = 48.0 * epsilon[i][j] * pow(sigma[i][j],12.0); lj2[i][j] = 24.0 * epsilon[i][j] * pow(sigma[i][j],6.0); lj3[i][j] = 4.0 * epsilon[i][j] * pow(sigma[i][j],12.0); lj4[i][j] = 4.0 * epsilon[i][j] * pow(sigma[i][j],6.0); if (offset_flag && (cut_lj[i][j] > 0.0)) { double ratio = sigma[i][j] / cut_lj[i][j]; offset[i][j] = 4.0 * epsilon[i][j] * (pow(ratio,12.0) - pow(ratio,6.0)); } else offset[i][j] = 0.0; cut_ljsq[j][i] = cut_ljsq[i][j]; lj1[j][i] = lj1[i][j]; lj2[j][i] = lj2[i][j]; lj3[j][i] = lj3[i][j]; lj4[j][i] = lj4[i][j]; offset[j][i] = offset[i][j]; // compute I,J contribution to long-range tail correction // count total # of atoms of type I and J via Allreduce if (tail_flag) { int *type = atom->type; int nlocal = atom->nlocal; double count[2],all[2]; count[0] = count[1] = 0.0; for (int k = 0; k < nlocal; k++) { if (type[k] == i) count[0] += 1.0; if (type[k] == j) count[1] += 1.0; } MPI_Allreduce(count,all,2,MPI_DOUBLE,MPI_SUM,world); double sig2 = sigma[i][j]*sigma[i][j]; double sig6 = sig2*sig2*sig2; double rc3 = cut_lj[i][j]*cut_lj[i][j]*cut_lj[i][j]; double rc6 = rc3*rc3; double rc9 = rc3*rc6; etail_ij = 8.0*MY_PI*all[0]*all[1]*epsilon[i][j] * sig6 * (sig6 - 3.0*rc6) / (9.0*rc9); ptail_ij = 16.0*MY_PI*all[0]*all[1]*epsilon[i][j] * sig6 * (2.0*sig6 - 3.0*rc6) / (9.0*rc9); } // check that LJ epsilon = 0.0 for water H // set LJ cutoff to 0.0 for any interaction involving water H // so LJ term isn't calculated in compute() if ((i == typeH && epsilon[i][i] != 0.0) || (j == typeH && epsilon[j][j] != 0.0)) error->all(FLERR,"Water H epsilon must be 0.0 for " "pair style lj/cut/tip4p/cut"); if (i == typeH || j == typeH) cut_ljsq[j][i] = cut_ljsq[i][j] = 0.0; return cut; } /* ---------------------------------------------------------------------- proc 0 writes to restart file ------------------------------------------------------------------------- */ void PairLJCutTIP4PCut::write_restart(FILE *fp) { write_restart_settings(fp); int i,j; for (i = 1; i <= atom->ntypes; i++) { for (j = i; j <= atom->ntypes; j++) { fwrite(&setflag[i][j],sizeof(int),1,fp); if (setflag[i][j]) { fwrite(&epsilon[i][j],sizeof(double),1,fp); fwrite(&sigma[i][j],sizeof(double),1,fp); fwrite(&cut_lj[i][j],sizeof(double),1,fp); } } } } /* ---------------------------------------------------------------------- proc 0 reads from restart file, bcasts ------------------------------------------------------------------------- */ void PairLJCutTIP4PCut::read_restart(FILE *fp) { read_restart_settings(fp); allocate(); int i,j; int me = comm->me; for (i = 1; i <= atom->ntypes; i++) { for (j = i; j <= atom->ntypes; j++) { if (me == 0) utils::sfread(FLERR,&setflag[i][j],sizeof(int),1,fp,nullptr,error); MPI_Bcast(&setflag[i][j],1,MPI_INT,0,world); if (setflag[i][j]) { if (me == 0) { utils::sfread(FLERR,&epsilon[i][j],sizeof(double),1,fp,nullptr,error); utils::sfread(FLERR,&sigma[i][j],sizeof(double),1,fp,nullptr,error); utils::sfread(FLERR,&cut_lj[i][j],sizeof(double),1,fp,nullptr,error); } MPI_Bcast(&epsilon[i][j],1,MPI_DOUBLE,0,world); MPI_Bcast(&sigma[i][j],1,MPI_DOUBLE,0,world); MPI_Bcast(&cut_lj[i][j],1,MPI_DOUBLE,0,world); } } } } /* ---------------------------------------------------------------------- proc 0 writes to restart file ------------------------------------------------------------------------- */ void PairLJCutTIP4PCut::write_restart_settings(FILE *fp) { fwrite(&typeO,sizeof(int),1,fp); fwrite(&typeH,sizeof(int),1,fp); fwrite(&typeB,sizeof(int),1,fp); fwrite(&typeA,sizeof(int),1,fp); fwrite(&qdist,sizeof(double),1,fp); fwrite(&cut_lj_global,sizeof(double),1,fp); fwrite(&cut_coul,sizeof(double),1,fp); fwrite(&offset_flag,sizeof(int),1,fp); fwrite(&mix_flag,sizeof(int),1,fp); fwrite(&tail_flag,sizeof(int),1,fp); } /* ---------------------------------------------------------------------- proc 0 reads from restart file, bcasts ------------------------------------------------------------------------- */ void PairLJCutTIP4PCut::read_restart_settings(FILE *fp) { if (comm->me == 0) { utils::sfread(FLERR,&typeO,sizeof(int),1,fp,nullptr,error); utils::sfread(FLERR,&typeH,sizeof(int),1,fp,nullptr,error); utils::sfread(FLERR,&typeB,sizeof(int),1,fp,nullptr,error); utils::sfread(FLERR,&typeA,sizeof(int),1,fp,nullptr,error); utils::sfread(FLERR,&qdist,sizeof(double),1,fp,nullptr,error); utils::sfread(FLERR,&cut_lj_global,sizeof(double),1,fp,nullptr,error); utils::sfread(FLERR,&cut_coul,sizeof(double),1,fp,nullptr,error); utils::sfread(FLERR,&offset_flag,sizeof(int),1,fp,nullptr,error); utils::sfread(FLERR,&mix_flag,sizeof(int),1,fp,nullptr,error); utils::sfread(FLERR,&tail_flag,sizeof(int),1,fp,nullptr,error); } MPI_Bcast(&typeO,1,MPI_INT,0,world); MPI_Bcast(&typeH,1,MPI_INT,0,world); MPI_Bcast(&typeB,1,MPI_INT,0,world); MPI_Bcast(&typeA,1,MPI_INT,0,world); MPI_Bcast(&qdist,1,MPI_DOUBLE,0,world); MPI_Bcast(&cut_lj_global,1,MPI_DOUBLE,0,world); MPI_Bcast(&cut_coul,1,MPI_DOUBLE,0,world); MPI_Bcast(&offset_flag,1,MPI_INT,0,world); MPI_Bcast(&mix_flag,1,MPI_INT,0,world); MPI_Bcast(&tail_flag,1,MPI_INT,0,world); cut_coulsq = cut_coul * cut_coul; cut_coulsqplus = (cut_coul + 2.0*qdist) * (cut_coul + 2.0*qdist); } /* ---------------------------------------------------------------------- proc 0 writes to data file ------------------------------------------------------------------------- */ void PairLJCutTIP4PCut::write_data(FILE *fp) { for (int i = 1; i <= atom->ntypes; i++) fprintf(fp,"%d %g %g\n",i,epsilon[i][i],sigma[i][i]); } /* ---------------------------------------------------------------------- proc 0 writes all pairs to data file ------------------------------------------------------------------------- */ void PairLJCutTIP4PCut::write_data_all(FILE *fp) { for (int i = 1; i <= atom->ntypes; i++) for (int j = i; j <= atom->ntypes; j++) fprintf(fp,"%d %d %g %g %g\n",i,j,epsilon[i][j],sigma[i][j],cut_lj[i][j]); } /* ---------------------------------------------------------------------- compute position xM of fictitious charge site for O atom and 2 H atoms return it as xM ------------------------------------------------------------------------- */ void PairLJCutTIP4PCut::compute_newsite(double *xO, double *xH1, double *xH2, double *xM) { double delx1 = xH1[0] - xO[0]; double dely1 = xH1[1] - xO[1]; double delz1 = xH1[2] - xO[2]; double delx2 = xH2[0] - xO[0]; double dely2 = xH2[1] - xO[1]; double delz2 = xH2[2] - xO[2]; xM[0] = xO[0] + alpha * 0.5 * (delx1 + delx2); xM[1] = xO[1] + alpha * 0.5 * (dely1 + dely2); xM[2] = xO[2] + alpha * 0.5 * (delz1 + delz2); } /* ---------------------------------------------------------------------- */ void *PairLJCutTIP4PCut::extract(const char *str, int &dim) { dim = 0; if (strcmp(str,"cut_coul") == 0) return (void *) &cut_coul; dim = 2; if (strcmp(str,"epsilon") == 0) return (void *) epsilon; if (strcmp(str,"sigma") == 0) return (void *) sigma; return nullptr; } /* ---------------------------------------------------------------------- memory usage of hneigh ------------------------------------------------------------------------- */ double PairLJCutTIP4PCut::memory_usage() { double bytes = (double)maxeatom * sizeof(double); bytes += (double)maxvatom*6 * sizeof(double); bytes += (double)2 * nmax * sizeof(double); return bytes; }
akohlmey/lammps
src/MOLECULE/pair_lj_cut_tip4p_cut.cpp
C++
gpl-2.0
24,257
/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab: * * LibMemcached * * Copyright (C) 2011 Data Differential, http://datadifferential.com/ * Copyright (C) 2006-2009 Brian Aker * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * * The names of its contributors may not be used to endorse or * promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 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. * */ #pragma once /* To hide the platform differences between MS Windows and Unix, I am * going to use the Microsoft way and #define the Microsoft-specific * functions to the unix way. Microsoft use a separate subsystem for sockets, * but Unix normally just use a filedescriptor on the same functions. It is * a lot easier to map back to the unix way with macros than going the other * way without side effect ;-) */ #ifdef WIN32 #include "win32/wrappers.h" #define get_socket_errno() WSAGetLastError() #else #include <unistd.h> #define INVALID_SOCKET -1 #define SOCKET_ERROR -1 #define closesocket(a) close(a) #define get_socket_errno() errno #endif #ifdef __cplusplus static inline void memcached_close_socket(int& socket_fd) { closesocket(socket_fd); socket_fd= INVALID_SOCKET; } #endif #ifndef HAVE_MSG_NOSIGNAL #define MSG_NOSIGNAL 0 #endif #ifndef HAVE_MSG_DONTWAIT #define MSG_DONTWAIT 0 #endif #ifndef HAVE_MSG_MORE #define MSG_MORE 0 #endif
seamlessstack/SeamlessStack
oss/libmemcached-1.0.8/libmemcached/socket.hpp
C++
gpl-2.0
2,679
<?php N2Loader::import('libraries.form.element.folders'); N2Loader::import('libraries.form.element.foldersimage', 'platform');
WordBenchNagoya/WordFes2016
wp/wp-content/plugins/smart-slider-3/nextend/library/libraries/form/element/foldersimage.php
PHP
gpl-2.0
128
/* Unix SMB/CIFS implementation. Main SMB reply routines Copyright (C) Andrew Tridgell 1992-1998 Copyright (C) Andrew Bartlett 2001 Copyright (C) Jeremy Allison 1992-2007. 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. */ /* This file handles most of the reply_ calls that the server makes to handle specific protocols */ #include "includes.h" /* look in server.c for some explanation of these variables */ extern enum protocol_types Protocol; extern int max_send; extern int max_recv; unsigned int smb_echo_count = 0; extern uint32 global_client_caps; extern struct current_user current_user; extern BOOL global_encrypted_passwords_negotiated; /**************************************************************************** Ensure we check the path in *exactly* the same way as W2K for a findfirst/findnext path or anything including wildcards. We're assuming here that '/' is not the second byte in any multibyte char set (a safe assumption). '\\' *may* be the second byte in a multibyte char set. ****************************************************************************/ /* Custom version for processing POSIX paths. */ #define IS_PATH_SEP(c,posix_only) ((c) == '/' || (!(posix_only) && (c) == '\\')) NTSTATUS check_path_syntax_internal(pstring destname, const pstring srcname, BOOL posix_path, BOOL *p_last_component_contains_wcard) { char *d = destname; const char *s = srcname; NTSTATUS ret = NT_STATUS_OK; BOOL start_of_name_component = True; *p_last_component_contains_wcard = False; while (*s) { if (IS_PATH_SEP(*s,posix_path)) { /* * Safe to assume is not the second part of a mb char as this is handled below. */ /* Eat multiple '/' or '\\' */ while (IS_PATH_SEP(*s,posix_path)) { s++; } if ((d != destname) && (*s != '\0')) { /* We only care about non-leading or trailing '/' or '\\' */ *d++ = '/'; } start_of_name_component = True; /* New component. */ *p_last_component_contains_wcard = False; continue; } if (start_of_name_component) { if ((s[0] == '.') && (s[1] == '.') && (IS_PATH_SEP(s[2],posix_path) || s[2] == '\0')) { /* Uh oh - "/../" or "\\..\\" or "/..\0" or "\\..\0" ! */ /* * No mb char starts with '.' so we're safe checking the directory separator here. */ /* If we just added a '/' - delete it */ if ((d > destname) && (*(d-1) == '/')) { *(d-1) = '\0'; d--; } /* Are we at the start ? Can't go back further if so. */ if (d <= destname) { ret = NT_STATUS_OBJECT_PATH_SYNTAX_BAD; break; } /* Go back one level... */ /* We know this is safe as '/' cannot be part of a mb sequence. */ /* NOTE - if this assumption is invalid we are not in good shape... */ /* Decrement d first as d points to the *next* char to write into. */ for (d--; d > destname; d--) { if (*d == '/') break; } s += 2; /* Else go past the .. */ /* We're still at the start of a name component, just the previous one. */ continue; } else if ((s[0] == '.') && ((s[1] == '\0') || IS_PATH_SEP(s[1],posix_path))) { if (posix_path) { /* Eat the '.' */ s++; continue; } } } if (!(*s & 0x80)) { if (!posix_path) { if (*s <= 0x1f) { return NT_STATUS_OBJECT_NAME_INVALID; } switch (*s) { case '*': case '?': case '<': case '>': case '"': *p_last_component_contains_wcard = True; break; default: break; } } *d++ = *s++; } else { size_t siz; /* Get the size of the next MB character. */ next_codepoint(s,&siz); switch(siz) { case 5: *d++ = *s++; /*fall through*/ case 4: *d++ = *s++; /*fall through*/ case 3: *d++ = *s++; /*fall through*/ case 2: *d++ = *s++; /*fall through*/ case 1: *d++ = *s++; break; default: DEBUG(0,("check_path_syntax_internal: character length assumptions invalid !\n")); *d = '\0'; return NT_STATUS_INVALID_PARAMETER; } } start_of_name_component = False; } *d = '\0'; return ret; } /**************************************************************************** Ensure we check the path in *exactly* the same way as W2K for regular pathnames. No wildcards allowed. ****************************************************************************/ NTSTATUS check_path_syntax(pstring destname, const pstring srcname) { BOOL ignore; return check_path_syntax_internal(destname, srcname, False, &ignore); } /**************************************************************************** Ensure we check the path in *exactly* the same way as W2K for regular pathnames. Wildcards allowed - p_contains_wcard returns true if the last component contained a wildcard. ****************************************************************************/ NTSTATUS check_path_syntax_wcard(pstring destname, const pstring srcname, BOOL *p_contains_wcard) { return check_path_syntax_internal(destname, srcname, False, p_contains_wcard); } /**************************************************************************** Check the path for a POSIX client. We're assuming here that '/' is not the second byte in any multibyte char set (a safe assumption). ****************************************************************************/ NTSTATUS check_path_syntax_posix(pstring destname, const pstring srcname) { BOOL ignore; return check_path_syntax_internal(destname, srcname, True, &ignore); } /**************************************************************************** Pull a string and check the path allowing a wilcard - provide for error return. ****************************************************************************/ size_t srvstr_get_path_wcard(char *inbuf, char *dest, const char *src, size_t dest_len, size_t src_len, int flags, NTSTATUS *err, BOOL *contains_wcard) { pstring tmppath; char *tmppath_ptr = tmppath; size_t ret; #ifdef DEVELOPER SMB_ASSERT(dest_len == sizeof(pstring)); #endif if (src_len == 0) { ret = srvstr_pull_buf( inbuf, tmppath_ptr, src, dest_len, flags); } else { ret = srvstr_pull( inbuf, tmppath_ptr, src, dest_len, src_len, flags); } *contains_wcard = False; if (SVAL(inbuf,smb_flg2) & FLAGS2_DFS_PATHNAMES) { /* * For a DFS path the function parse_dfs_path() * will do the path processing, just make a copy. */ pstrcpy(dest, tmppath); *err = NT_STATUS_OK; return ret; } if (lp_posix_pathnames()) { *err = check_path_syntax_posix(dest, tmppath); } else { *err = check_path_syntax_wcard(dest, tmppath, contains_wcard); } return ret; } /**************************************************************************** Pull a string and check the path - provide for error return. ****************************************************************************/ size_t srvstr_get_path(char *inbuf, char *dest, const char *src, size_t dest_len, size_t src_len, int flags, NTSTATUS *err) { pstring tmppath; char *tmppath_ptr = tmppath; size_t ret; #ifdef DEVELOPER SMB_ASSERT(dest_len == sizeof(pstring)); #endif if (src_len == 0) { ret = srvstr_pull_buf( inbuf, tmppath_ptr, src, dest_len, flags); } else { ret = srvstr_pull( inbuf, tmppath_ptr, src, dest_len, src_len, flags); } if (SVAL(inbuf,smb_flg2) & FLAGS2_DFS_PATHNAMES) { /* * For a DFS path the function parse_dfs_path() * will do the path processing, just make a copy. */ pstrcpy(dest, tmppath); *err = NT_STATUS_OK; return ret; } if (lp_posix_pathnames()) { *err = check_path_syntax_posix(dest, tmppath); } else { *err = check_path_syntax(dest, tmppath); } return ret; } /**************************************************************************** Reply to a special message. ****************************************************************************/ int reply_special(char *inbuf,char *outbuf) { int outsize = 4; int msg_type = CVAL(inbuf,0); int msg_flags = CVAL(inbuf,1); fstring name1,name2; char name_type = 0; static BOOL already_got_session = False; *name1 = *name2 = 0; memset(outbuf,'\0',smb_size); smb_setlen(outbuf,0); switch (msg_type) { case 0x81: /* session request */ if (already_got_session) { exit_server_cleanly("multiple session request not permitted"); } SCVAL(outbuf,0,0x82); SCVAL(outbuf,3,0); if (name_len(inbuf+4) > 50 || name_len(inbuf+4 + name_len(inbuf + 4)) > 50) { DEBUG(0,("Invalid name length in session request\n")); return(0); } name_extract(inbuf,4,name1); name_type = name_extract(inbuf,4 + name_len(inbuf + 4),name2); DEBUG(2,("netbios connect: name1=%s name2=%s\n", name1,name2)); set_local_machine_name(name1, True); set_remote_machine_name(name2, True); DEBUG(2,("netbios connect: local=%s remote=%s, name type = %x\n", get_local_machine_name(), get_remote_machine_name(), name_type)); if (name_type == 'R') { /* We are being asked for a pathworks session --- no thanks! */ SCVAL(outbuf, 0,0x83); break; } /* only add the client's machine name to the list of possibly valid usernames if we are operating in share mode security */ if (lp_security() == SEC_SHARE) { add_session_user(get_remote_machine_name()); } reload_services(True); reopen_logs(); already_got_session = True; break; case 0x89: /* session keepalive request (some old clients produce this?) */ SCVAL(outbuf,0,SMBkeepalive); SCVAL(outbuf,3,0); break; case 0x82: /* positive session response */ case 0x83: /* negative session response */ case 0x84: /* retarget session response */ DEBUG(0,("Unexpected session response\n")); break; case SMBkeepalive: /* session keepalive */ default: return(0); } DEBUG(5,("init msg_type=0x%x msg_flags=0x%x\n", msg_type, msg_flags)); return(outsize); } /**************************************************************************** Reply to a tcon. conn POINTER CAN BE NULL HERE ! ****************************************************************************/ int reply_tcon(connection_struct *conn, char *inbuf,char *outbuf, int dum_size, int dum_buffsize) { const char *service; pstring service_buf; pstring password; pstring dev; int outsize = 0; uint16 vuid = SVAL(inbuf,smb_uid); int pwlen=0; NTSTATUS nt_status; char *p; DATA_BLOB password_blob; START_PROFILE(SMBtcon); *service_buf = *password = *dev = 0; p = smb_buf(inbuf)+1; p += srvstr_pull_buf(inbuf, service_buf, p, sizeof(service_buf), STR_TERMINATE) + 1; pwlen = srvstr_pull_buf(inbuf, password, p, sizeof(password), STR_TERMINATE) + 1; p += pwlen; p += srvstr_pull_buf(inbuf, dev, p, sizeof(dev), STR_TERMINATE) + 1; p = strrchr_m(service_buf,'\\'); if (p) { service = p+1; } else { service = service_buf; } password_blob = data_blob(password, pwlen+1); conn = make_connection(service,password_blob,dev,vuid,&nt_status); data_blob_clear_free(&password_blob); if (!conn) { END_PROFILE(SMBtcon); return ERROR_NT(nt_status); } outsize = set_message(outbuf,2,0,True); SSVAL(outbuf,smb_vwv0,max_recv); SSVAL(outbuf,smb_vwv1,conn->cnum); SSVAL(outbuf,smb_tid,conn->cnum); DEBUG(3,("tcon service=%s cnum=%d\n", service, conn->cnum)); END_PROFILE(SMBtcon); return(outsize); } /**************************************************************************** Reply to a tcon and X. conn POINTER CAN BE NULL HERE ! ****************************************************************************/ int reply_tcon_and_X(connection_struct *conn, char *inbuf,char *outbuf,int length,int bufsize) { fstring service; DATA_BLOB password; /* what the cleint thinks the device is */ fstring client_devicetype; /* what the server tells the client the share represents */ const char *server_devicetype; NTSTATUS nt_status; uint16 vuid = SVAL(inbuf,smb_uid); int passlen = SVAL(inbuf,smb_vwv3); pstring path; char *p, *q; uint16 tcon_flags = SVAL(inbuf,smb_vwv2); START_PROFILE(SMBtconX); *service = *client_devicetype = 0; /* we might have to close an old one */ if ((SVAL(inbuf,smb_vwv2) & 0x1) && conn) { close_cnum(conn,vuid); } if (passlen > MAX_PASS_LEN) { return ERROR_DOS(ERRDOS,ERRbuftoosmall); } if (global_encrypted_passwords_negotiated) { password = data_blob(smb_buf(inbuf),passlen); if (lp_security() == SEC_SHARE) { /* * Security = share always has a pad byte * after the password. */ p = smb_buf(inbuf) + passlen + 1; } else { p = smb_buf(inbuf) + passlen; } } else { password = data_blob(smb_buf(inbuf),passlen+1); /* Ensure correct termination */ password.data[passlen]=0; p = smb_buf(inbuf) + passlen + 1; } p += srvstr_pull_buf(inbuf, path, p, sizeof(path), STR_TERMINATE); /* * the service name can be either: \\server\share * or share directly like on the DELL PowerVault 705 */ if (*path=='\\') { q = strchr_m(path+2,'\\'); if (!q) { END_PROFILE(SMBtconX); return(ERROR_DOS(ERRDOS,ERRnosuchshare)); } fstrcpy(service,q+1); } else fstrcpy(service,path); p += srvstr_pull(inbuf, client_devicetype, p, sizeof(client_devicetype), 6, STR_ASCII); DEBUG(4,("Client requested device type [%s] for share [%s]\n", client_devicetype, service)); conn = make_connection(service,password,client_devicetype,vuid,&nt_status); data_blob_clear_free(&password); if (!conn) { END_PROFILE(SMBtconX); return ERROR_NT(nt_status); } if ( IS_IPC(conn) ) server_devicetype = "IPC"; else if ( IS_PRINT(conn) ) server_devicetype = "LPT1:"; else server_devicetype = "A:"; if (Protocol < PROTOCOL_NT1) { set_message(outbuf,2,0,True); p = smb_buf(outbuf); p += srvstr_push(outbuf, p, server_devicetype, -1, STR_TERMINATE|STR_ASCII); set_message_end(outbuf,p); } else { /* NT sets the fstype of IPC$ to the null string */ const char *fstype = IS_IPC(conn) ? "" : lp_fstype(SNUM(conn)); if (tcon_flags & TCONX_FLAG_EXTENDED_RESPONSE) { /* Return permissions. */ uint32 perm1 = 0; uint32 perm2 = 0; set_message(outbuf,7,0,True); if (IS_IPC(conn)) { perm1 = FILE_ALL_ACCESS; perm2 = FILE_ALL_ACCESS; } else { perm1 = CAN_WRITE(conn) ? SHARE_ALL_ACCESS : SHARE_READ_ONLY; } SIVAL(outbuf, smb_vwv3, perm1); SIVAL(outbuf, smb_vwv5, perm2); } else { set_message(outbuf,3,0,True); } p = smb_buf(outbuf); p += srvstr_push(outbuf, p, server_devicetype, -1, STR_TERMINATE|STR_ASCII); p += srvstr_push(outbuf, p, fstype, -1, STR_TERMINATE); set_message_end(outbuf,p); /* what does setting this bit do? It is set by NT4 and may affect the ability to autorun mounted cdroms */ SSVAL(outbuf, smb_vwv2, SMB_SUPPORT_SEARCH_BITS| (lp_csc_policy(SNUM(conn)) << 2)); init_dfsroot(conn, inbuf, outbuf); } DEBUG(3,("tconX service=%s \n", service)); /* set the incoming and outgoing tid to the just created one */ SSVAL(inbuf,smb_tid,conn->cnum); SSVAL(outbuf,smb_tid,conn->cnum); END_PROFILE(SMBtconX); return chain_reply(inbuf,outbuf,length,bufsize); } /**************************************************************************** Reply to an unknown type. ****************************************************************************/ int reply_unknown(char *inbuf,char *outbuf) { int type; type = CVAL(inbuf,smb_com); DEBUG(0,("unknown command type (%s): type=%d (0x%X)\n", smb_fn_name(type), type, type)); return(ERROR_DOS(ERRSRV,ERRunknownsmb)); } /**************************************************************************** Reply to an ioctl. conn POINTER CAN BE NULL HERE ! ****************************************************************************/ int reply_ioctl(connection_struct *conn, char *inbuf,char *outbuf, int dum_size, int dum_buffsize) { uint16 device = SVAL(inbuf,smb_vwv1); uint16 function = SVAL(inbuf,smb_vwv2); uint32 ioctl_code = (device << 16) + function; int replysize, outsize; char *p; START_PROFILE(SMBioctl); DEBUG(4, ("Received IOCTL (code 0x%x)\n", ioctl_code)); switch (ioctl_code) { case IOCTL_QUERY_JOB_INFO: replysize = 32; break; default: END_PROFILE(SMBioctl); return(ERROR_DOS(ERRSRV,ERRnosupport)); } outsize = set_message(outbuf,8,replysize+1,True); SSVAL(outbuf,smb_vwv1,replysize); /* Total data bytes returned */ SSVAL(outbuf,smb_vwv5,replysize); /* Data bytes this buffer */ SSVAL(outbuf,smb_vwv6,52); /* Offset to data */ p = smb_buf(outbuf) + 1; /* Allow for alignment */ switch (ioctl_code) { case IOCTL_QUERY_JOB_INFO: { files_struct *fsp = file_fsp(inbuf,smb_vwv0); if (!fsp) { END_PROFILE(SMBioctl); return(UNIXERROR(ERRDOS,ERRbadfid)); } SSVAL(p,0,fsp->rap_print_jobid); /* Job number */ srvstr_push(outbuf, p+2, global_myname(), 15, STR_TERMINATE|STR_ASCII); if (conn) { srvstr_push(outbuf, p+18, lp_servicename(SNUM(conn)), 13, STR_TERMINATE|STR_ASCII); } break; } } END_PROFILE(SMBioctl); return outsize; } /**************************************************************************** Strange checkpath NTSTATUS mapping. ****************************************************************************/ static NTSTATUS map_checkpath_error(const char *inbuf, NTSTATUS status) { /* Strange DOS error code semantics only for checkpath... */ if (!(SVAL(inbuf,smb_flg2) & FLAGS2_32_BIT_ERROR_CODES)) { if (NT_STATUS_EQUAL(NT_STATUS_OBJECT_NAME_INVALID,status)) { /* We need to map to ERRbadpath */ return NT_STATUS_OBJECT_PATH_NOT_FOUND; } } return status; } /**************************************************************************** Reply to a checkpath. ****************************************************************************/ int reply_checkpath(connection_struct *conn, char *inbuf,char *outbuf, int dum_size, int dum_buffsize) { int outsize = 0; pstring name; SMB_STRUCT_STAT sbuf; NTSTATUS status; START_PROFILE(SMBcheckpath); srvstr_get_path(inbuf, name, smb_buf(inbuf) + 1, sizeof(name), 0, STR_TERMINATE, &status); if (!NT_STATUS_IS_OK(status)) { END_PROFILE(SMBcheckpath); status = map_checkpath_error(inbuf, status); return ERROR_NT(status); } status = resolve_dfspath(conn, SVAL(inbuf,smb_flg2) & FLAGS2_DFS_PATHNAMES, name); if (!NT_STATUS_IS_OK(status)) { if (NT_STATUS_EQUAL(status,NT_STATUS_PATH_NOT_COVERED)) { END_PROFILE(SMBcheckpath); return ERROR_BOTH(NT_STATUS_PATH_NOT_COVERED, ERRSRV, ERRbadpath); } goto path_err; } DEBUG(3,("reply_checkpath %s mode=%d\n", name, (int)SVAL(inbuf,smb_vwv0))); status = unix_convert(conn, name, False, NULL, &sbuf); if (!NT_STATUS_IS_OK(status)) { goto path_err; } status = check_name(conn, name); if (!NT_STATUS_IS_OK(status)) { DEBUG(3,("reply_checkpath: check_name of %s failed (%s)\n",name,nt_errstr(status))); goto path_err; } if (!VALID_STAT(sbuf) && (SMB_VFS_STAT(conn,name,&sbuf) != 0)) { DEBUG(3,("reply_checkpath: stat of %s failed (%s)\n",name,strerror(errno))); status = map_nt_error_from_unix(errno); goto path_err; } if (!S_ISDIR(sbuf.st_mode)) { END_PROFILE(SMBcheckpath); return ERROR_BOTH(NT_STATUS_NOT_A_DIRECTORY,ERRDOS,ERRbadpath); } outsize = set_message(outbuf,0,0,False); END_PROFILE(SMBcheckpath); return outsize; path_err: END_PROFILE(SMBcheckpath); /* We special case this - as when a Windows machine is parsing a path is steps through the components one at a time - if a component fails it expects ERRbadpath, not ERRbadfile. */ status = map_checkpath_error(inbuf, status); if(NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) { /* * Windows returns different error codes if * the parent directory is valid but not the * last component - it returns NT_STATUS_OBJECT_NAME_NOT_FOUND * for that case and NT_STATUS_OBJECT_PATH_NOT_FOUND * if the path is invalid. */ return ERROR_BOTH(NT_STATUS_OBJECT_NAME_NOT_FOUND,ERRDOS,ERRbadpath); } return ERROR_NT(status); } /**************************************************************************** Reply to a getatr. ****************************************************************************/ int reply_getatr(connection_struct *conn, char *inbuf,char *outbuf, int dum_size, int dum_buffsize) { pstring fname; int outsize = 0; SMB_STRUCT_STAT sbuf; int mode=0; SMB_OFF_T size=0; time_t mtime=0; char *p; NTSTATUS status; START_PROFILE(SMBgetatr); p = smb_buf(inbuf) + 1; p += srvstr_get_path(inbuf, fname, p, sizeof(fname), 0, STR_TERMINATE, &status); if (!NT_STATUS_IS_OK(status)) { END_PROFILE(SMBgetatr); return ERROR_NT(status); } status = resolve_dfspath(conn, SVAL(inbuf,smb_flg2) & FLAGS2_DFS_PATHNAMES, fname); if (!NT_STATUS_IS_OK(status)) { END_PROFILE(SMBgetatr); if (NT_STATUS_EQUAL(status,NT_STATUS_PATH_NOT_COVERED)) { return ERROR_BOTH(NT_STATUS_PATH_NOT_COVERED, ERRSRV, ERRbadpath); } return ERROR_NT(status); } /* dos smetimes asks for a stat of "" - it returns a "hidden directory" under WfWg - weird! */ if (*fname == '\0') { mode = aHIDDEN | aDIR; if (!CAN_WRITE(conn)) { mode |= aRONLY; } size = 0; mtime = 0; } else { status = unix_convert(conn, fname, False, NULL,&sbuf); if (!NT_STATUS_IS_OK(status)) { END_PROFILE(SMBgetatr); return ERROR_NT(status); } status = check_name(conn, fname); if (!NT_STATUS_IS_OK(status)) { DEBUG(3,("reply_getatr: check_name of %s failed (%s)\n",fname,nt_errstr(status))); END_PROFILE(SMBgetatr); return ERROR_NT(status); } if (!VALID_STAT(sbuf) && (SMB_VFS_STAT(conn,fname,&sbuf) != 0)) { DEBUG(3,("reply_getatr: stat of %s failed (%s)\n",fname,strerror(errno))); return UNIXERROR(ERRDOS,ERRbadfile); } mode = dos_mode(conn,fname,&sbuf); size = sbuf.st_size; mtime = sbuf.st_mtime; if (mode & aDIR) { size = 0; } } outsize = set_message(outbuf,10,0,True); SSVAL(outbuf,smb_vwv0,mode); if(lp_dos_filetime_resolution(SNUM(conn)) ) { srv_put_dos_date3(outbuf,smb_vwv1,mtime & ~1); } else { srv_put_dos_date3(outbuf,smb_vwv1,mtime); } SIVAL(outbuf,smb_vwv3,(uint32)size); if (Protocol >= PROTOCOL_NT1) { SSVAL(outbuf,smb_flg2,SVAL(outbuf, smb_flg2) | FLAGS2_IS_LONG_NAME); } DEBUG(3,("reply_getatr: name=%s mode=%d size=%u\n", fname, mode, (unsigned int)size ) ); END_PROFILE(SMBgetatr); return(outsize); } /**************************************************************************** Reply to a setatr. ****************************************************************************/ int reply_setatr(connection_struct *conn, char *inbuf,char *outbuf, int dum_size, int dum_buffsize) { pstring fname; int outsize = 0; int mode; time_t mtime; SMB_STRUCT_STAT sbuf; char *p; NTSTATUS status; START_PROFILE(SMBsetatr); p = smb_buf(inbuf) + 1; p += srvstr_get_path(inbuf, fname, p, sizeof(fname), 0, STR_TERMINATE, &status); if (!NT_STATUS_IS_OK(status)) { END_PROFILE(SMBsetatr); return ERROR_NT(status); } status = resolve_dfspath(conn, SVAL(inbuf,smb_flg2) & FLAGS2_DFS_PATHNAMES, fname); if (!NT_STATUS_IS_OK(status)) { END_PROFILE(SMBsetatr); if (NT_STATUS_EQUAL(status,NT_STATUS_PATH_NOT_COVERED)) { return ERROR_BOTH(NT_STATUS_PATH_NOT_COVERED, ERRSRV, ERRbadpath); } return ERROR_NT(status); } status = unix_convert(conn, fname, False, NULL, &sbuf); if (!NT_STATUS_IS_OK(status)) { END_PROFILE(SMBsetatr); return ERROR_NT(status); } status = check_name(conn, fname); if (!NT_STATUS_IS_OK(status)) { END_PROFILE(SMBsetatr); return ERROR_NT(status); } if (fname[0] == '.' && fname[1] == '\0') { /* * Not sure here is the right place to catch this * condition. Might be moved to somewhere else later -- vl */ END_PROFILE(SMBsetatr); return ERROR_NT(NT_STATUS_ACCESS_DENIED); } mode = SVAL(inbuf,smb_vwv0); mtime = srv_make_unix_date3(inbuf+smb_vwv1); if (mode != FILE_ATTRIBUTE_NORMAL) { if (VALID_STAT_OF_DIR(sbuf)) mode |= aDIR; else mode &= ~aDIR; if (file_set_dosmode(conn,fname,mode,&sbuf,False) != 0) { END_PROFILE(SMBsetatr); return UNIXERROR(ERRDOS, ERRnoaccess); } } if (!set_filetime(conn,fname,convert_time_t_to_timespec(mtime))) { END_PROFILE(SMBsetatr); return UNIXERROR(ERRDOS, ERRnoaccess); } outsize = set_message(outbuf,0,0,False); DEBUG( 3, ( "setatr name=%s mode=%d\n", fname, mode ) ); END_PROFILE(SMBsetatr); return(outsize); } /**************************************************************************** Reply to a dskattr. ****************************************************************************/ int reply_dskattr(connection_struct *conn, char *inbuf,char *outbuf, int dum_size, int dum_buffsize) { int outsize = 0; SMB_BIG_UINT dfree,dsize,bsize; START_PROFILE(SMBdskattr); if (get_dfree_info(conn,".",True,&bsize,&dfree,&dsize) == (SMB_BIG_UINT)-1) { END_PROFILE(SMBdskattr); return(UNIXERROR(ERRHRD,ERRgeneral)); } outsize = set_message(outbuf,5,0,True); if (Protocol <= PROTOCOL_LANMAN2) { double total_space, free_space; /* we need to scale this to a number that DOS6 can handle. We use floating point so we can handle large drives on systems that don't have 64 bit integers we end up displaying a maximum of 2G to DOS systems */ total_space = dsize * (double)bsize; free_space = dfree * (double)bsize; dsize = (total_space+63*512) / (64*512); dfree = (free_space+63*512) / (64*512); if (dsize > 0xFFFF) dsize = 0xFFFF; if (dfree > 0xFFFF) dfree = 0xFFFF; SSVAL(outbuf,smb_vwv0,dsize); SSVAL(outbuf,smb_vwv1,64); /* this must be 64 for dos systems */ SSVAL(outbuf,smb_vwv2,512); /* and this must be 512 */ SSVAL(outbuf,smb_vwv3,dfree); } else { SSVAL(outbuf,smb_vwv0,dsize); SSVAL(outbuf,smb_vwv1,bsize/512); SSVAL(outbuf,smb_vwv2,512); SSVAL(outbuf,smb_vwv3,dfree); } DEBUG(3,("dskattr dfree=%d\n", (unsigned int)dfree)); END_PROFILE(SMBdskattr); return(outsize); } /**************************************************************************** Reply to a search. Can be called from SMBsearch, SMBffirst or SMBfunique. ****************************************************************************/ int reply_search(connection_struct *conn, char *inbuf,char *outbuf, int dum_size, int dum_buffsize) { pstring mask; pstring directory; pstring fname; SMB_OFF_T size; uint32 mode; time_t date; uint32 dirtype; int outsize = 0; unsigned int numentries = 0; unsigned int maxentries = 0; BOOL finished = False; char *p; int status_len; pstring path; char status[21]; int dptr_num= -1; BOOL check_descend = False; BOOL expect_close = False; NTSTATUS nt_status; BOOL mask_contains_wcard = False; BOOL allow_long_path_components = (SVAL(inbuf,smb_flg2) & FLAGS2_LONG_PATH_COMPONENTS) ? True : False; START_PROFILE(SMBsearch); if (lp_posix_pathnames()) { END_PROFILE(SMBsearch); return reply_unknown(inbuf, outbuf); } *mask = *directory = *fname = 0; /* If we were called as SMBffirst then we must expect close. */ if(CVAL(inbuf,smb_com) == SMBffirst) { expect_close = True; } outsize = set_message(outbuf,1,3,True); maxentries = SVAL(inbuf,smb_vwv0); dirtype = SVAL(inbuf,smb_vwv1); p = smb_buf(inbuf) + 1; p += srvstr_get_path_wcard(inbuf, path, p, sizeof(path), 0, STR_TERMINATE, &nt_status, &mask_contains_wcard); if (!NT_STATUS_IS_OK(nt_status)) { END_PROFILE(SMBsearch); return ERROR_NT(nt_status); } nt_status = resolve_dfspath_wcard(conn, SVAL(inbuf,smb_flg2) & FLAGS2_DFS_PATHNAMES, path, &mask_contains_wcard); if (!NT_STATUS_IS_OK(nt_status)) { END_PROFILE(SMBsearch); if (NT_STATUS_EQUAL(nt_status,NT_STATUS_PATH_NOT_COVERED)) { return ERROR_BOTH(NT_STATUS_PATH_NOT_COVERED, ERRSRV, ERRbadpath); } return ERROR_NT(nt_status); } p++; status_len = SVAL(p, 0); p += 2; /* dirtype &= ~aDIR; */ if (status_len == 0) { SMB_STRUCT_STAT sbuf; pstrcpy(directory,path); nt_status = unix_convert(conn, directory, True, NULL, &sbuf); if (!NT_STATUS_IS_OK(nt_status)) { END_PROFILE(SMBsearch); return ERROR_NT(nt_status); } nt_status = check_name(conn, directory); if (!NT_STATUS_IS_OK(nt_status)) { END_PROFILE(SMBsearch); return ERROR_NT(nt_status); } p = strrchr_m(directory,'/'); if (!p) { pstrcpy(mask,directory); pstrcpy(directory,"."); } else { *p = 0; pstrcpy(mask,p+1); } if (*directory == '\0') { pstrcpy(directory,"."); } memset((char *)status,'\0',21); SCVAL(status,0,(dirtype & 0x1F)); } else { int status_dirtype; memcpy(status,p,21); status_dirtype = CVAL(status,0) & 0x1F; if (status_dirtype != (dirtype & 0x1F)) { dirtype = status_dirtype; } conn->dirptr = dptr_fetch(status+12,&dptr_num); if (!conn->dirptr) { goto SearchEmpty; } string_set(&conn->dirpath,dptr_path(dptr_num)); pstrcpy(mask, dptr_wcard(dptr_num)); /* * For a 'continue' search we have no string. So * check from the initial saved string. */ mask_contains_wcard = ms_has_wild(mask); } p = smb_buf(outbuf) + 3; if (status_len == 0) { nt_status = dptr_create(conn, directory, True, expect_close, SVAL(inbuf,smb_pid), mask, mask_contains_wcard, dirtype, &conn->dirptr); if (!NT_STATUS_IS_OK(nt_status)) { return ERROR_NT(nt_status); } dptr_num = dptr_dnum(conn->dirptr); } else { dirtype = dptr_attr(dptr_num); } DEBUG(4,("dptr_num is %d\n",dptr_num)); if ((dirtype&0x1F) == aVOLID) { memcpy(p,status,21); make_dir_struct(p,"???????????",volume_label(SNUM(conn)), 0,aVOLID,0,!allow_long_path_components); dptr_fill(p+12,dptr_num); if (dptr_zero(p+12) && (status_len==0)) { numentries = 1; } else { numentries = 0; } p += DIR_STRUCT_SIZE; } else { unsigned int i; maxentries = MIN(maxentries, ((BUFFER_SIZE - (p - outbuf))/DIR_STRUCT_SIZE)); DEBUG(8,("dirpath=<%s> dontdescend=<%s>\n", conn->dirpath,lp_dontdescend(SNUM(conn)))); if (in_list(conn->dirpath, lp_dontdescend(SNUM(conn)),True)) { check_descend = True; } for (i=numentries;(i<maxentries) && !finished;i++) { finished = !get_dir_entry(conn,mask,dirtype,fname,&size,&mode,&date,check_descend); if (!finished) { memcpy(p,status,21); make_dir_struct(p,mask,fname,size, mode,date, !allow_long_path_components); if (!dptr_fill(p+12,dptr_num)) { break; } numentries++; p += DIR_STRUCT_SIZE; } } } SearchEmpty: /* If we were called as SMBffirst with smb_search_id == NULL and no entries were found then return error and close dirptr (X/Open spec) */ if (numentries == 0) { dptr_close(&dptr_num); } else if(expect_close && status_len == 0) { /* Close the dptr - we know it's gone */ dptr_close(&dptr_num); } /* If we were called as SMBfunique, then we can close the dirptr now ! */ if(dptr_num >= 0 && CVAL(inbuf,smb_com) == SMBfunique) { dptr_close(&dptr_num); } if ((numentries == 0) && !mask_contains_wcard) { return ERROR_BOTH(STATUS_NO_MORE_FILES,ERRDOS,ERRnofiles); } SSVAL(outbuf,smb_vwv0,numentries); SSVAL(outbuf,smb_vwv1,3 + numentries * DIR_STRUCT_SIZE); SCVAL(smb_buf(outbuf),0,5); SSVAL(smb_buf(outbuf),1,numentries*DIR_STRUCT_SIZE); /* The replies here are never long name. */ SSVAL(outbuf,smb_flg2,SVAL(outbuf, smb_flg2) & (~FLAGS2_IS_LONG_NAME)); if (!allow_long_path_components) { SSVAL(outbuf,smb_flg2,SVAL(outbuf, smb_flg2) & (~FLAGS2_LONG_PATH_COMPONENTS)); } /* This SMB *always* returns ASCII names. Remove the unicode bit in flags2. */ SSVAL(outbuf,smb_flg2, (SVAL(outbuf, smb_flg2) & (~FLAGS2_UNICODE_STRINGS))); outsize += DIR_STRUCT_SIZE*numentries; smb_setlen(outbuf,outsize - 4); if ((! *directory) && dptr_path(dptr_num)) slprintf(directory, sizeof(directory)-1, "(%s)",dptr_path(dptr_num)); DEBUG( 4, ( "%s mask=%s path=%s dtype=%d nument=%u of %u\n", smb_fn_name(CVAL(inbuf,smb_com)), mask, directory, dirtype, numentries, maxentries ) ); END_PROFILE(SMBsearch); return(outsize); } /**************************************************************************** Reply to a fclose (stop directory search). ****************************************************************************/ int reply_fclose(connection_struct *conn, char *inbuf,char *outbuf, int dum_size, int dum_buffsize) { int outsize = 0; int status_len; pstring path; char status[21]; int dptr_num= -2; char *p; NTSTATUS err; BOOL path_contains_wcard = False; START_PROFILE(SMBfclose); if (lp_posix_pathnames()) { END_PROFILE(SMBfclose); return reply_unknown(inbuf, outbuf); } outsize = set_message(outbuf,1,0,True); p = smb_buf(inbuf) + 1; p += srvstr_get_path_wcard(inbuf, path, p, sizeof(path), 0, STR_TERMINATE, &err, &path_contains_wcard); if (!NT_STATUS_IS_OK(err)) { END_PROFILE(SMBfclose); return ERROR_NT(err); } p++; status_len = SVAL(p,0); p += 2; if (status_len == 0) { END_PROFILE(SMBfclose); return ERROR_DOS(ERRSRV,ERRsrverror); } memcpy(status,p,21); if(dptr_fetch(status+12,&dptr_num)) { /* Close the dptr - we know it's gone */ dptr_close(&dptr_num); } SSVAL(outbuf,smb_vwv0,0); DEBUG(3,("search close\n")); END_PROFILE(SMBfclose); return(outsize); } /**************************************************************************** Reply to an open. ****************************************************************************/ int reply_open(connection_struct *conn, char *inbuf,char *outbuf, int dum_size, int dum_buffsize) { pstring fname; int outsize = 0; uint32 fattr=0; SMB_OFF_T size = 0; time_t mtime=0; int info; SMB_STRUCT_STAT sbuf; files_struct *fsp; int oplock_request = CORE_OPLOCK_REQUEST(inbuf); int deny_mode; uint32 dos_attr = SVAL(inbuf,smb_vwv1); uint32 access_mask; uint32 share_mode; uint32 create_disposition; uint32 create_options = 0; NTSTATUS status; START_PROFILE(SMBopen); deny_mode = SVAL(inbuf,smb_vwv0); srvstr_get_path(inbuf, fname, smb_buf(inbuf)+1, sizeof(fname), 0, STR_TERMINATE, &status); if (!NT_STATUS_IS_OK(status)) { END_PROFILE(SMBopen); return ERROR_NT(status); } status = resolve_dfspath(conn, SVAL(inbuf,smb_flg2) & FLAGS2_DFS_PATHNAMES, fname); if (!NT_STATUS_IS_OK(status)) { END_PROFILE(SMBopen); if (NT_STATUS_EQUAL(status,NT_STATUS_PATH_NOT_COVERED)) { return ERROR_BOTH(NT_STATUS_PATH_NOT_COVERED, ERRSRV, ERRbadpath); } return ERROR_NT(status); } status = unix_convert(conn, fname, False, NULL, &sbuf); if (!NT_STATUS_IS_OK(status)) { END_PROFILE(SMBopen); return ERROR_NT(status); } status = check_name(conn, fname); if (!NT_STATUS_IS_OK(status)) { END_PROFILE(SMBopen); return ERROR_NT(status); } if (!map_open_params_to_ntcreate(fname, deny_mode, OPENX_FILE_EXISTS_OPEN, &access_mask, &share_mode, &create_disposition, &create_options)) { END_PROFILE(SMBopen); return ERROR_NT(NT_STATUS_DOS(ERRDOS, ERRbadaccess)); } status = open_file_ntcreate(conn,fname,&sbuf, access_mask, share_mode, create_disposition, create_options, dos_attr, oplock_request, &info, &fsp); if (!NT_STATUS_IS_OK(status)) { END_PROFILE(SMBopen); if (open_was_deferred(SVAL(inbuf,smb_mid))) { /* We have re-scheduled this call. */ return -1; } return ERROR_NT(status); } size = sbuf.st_size; fattr = dos_mode(conn,fname,&sbuf); mtime = sbuf.st_mtime; if (fattr & aDIR) { DEBUG(3,("attempt to open a directory %s\n",fname)); close_file(fsp,ERROR_CLOSE); END_PROFILE(SMBopen); return ERROR_DOS(ERRDOS,ERRnoaccess); } outsize = set_message(outbuf,7,0,True); SSVAL(outbuf,smb_vwv0,fsp->fnum); SSVAL(outbuf,smb_vwv1,fattr); if(lp_dos_filetime_resolution(SNUM(conn)) ) { srv_put_dos_date3(outbuf,smb_vwv2,mtime & ~1); } else { srv_put_dos_date3(outbuf,smb_vwv2,mtime); } SIVAL(outbuf,smb_vwv4,(uint32)size); SSVAL(outbuf,smb_vwv6,deny_mode); if (oplock_request && lp_fake_oplocks(SNUM(conn))) { SCVAL(outbuf,smb_flg,CVAL(outbuf,smb_flg)|CORE_OPLOCK_GRANTED); } if(EXCLUSIVE_OPLOCK_TYPE(fsp->oplock_type)) { SCVAL(outbuf,smb_flg,CVAL(outbuf,smb_flg)|CORE_OPLOCK_GRANTED); } END_PROFILE(SMBopen); return(outsize); } /**************************************************************************** Reply to an open and X. ****************************************************************************/ int reply_open_and_X(connection_struct *conn, char *inbuf,char *outbuf,int length,int bufsize) { pstring fname; uint16 open_flags = SVAL(inbuf,smb_vwv2); int deny_mode = SVAL(inbuf,smb_vwv3); uint32 smb_attr = SVAL(inbuf,smb_vwv5); /* Breakout the oplock request bits so we can set the reply bits separately. */ int ex_oplock_request = EXTENDED_OPLOCK_REQUEST(inbuf); int core_oplock_request = CORE_OPLOCK_REQUEST(inbuf); int oplock_request = ex_oplock_request | core_oplock_request; #if 0 int smb_sattr = SVAL(inbuf,smb_vwv4); uint32 smb_time = make_unix_date3(inbuf+smb_vwv6); #endif int smb_ofun = SVAL(inbuf,smb_vwv8); uint32 fattr=0; int mtime=0; SMB_STRUCT_STAT sbuf; int smb_action = 0; files_struct *fsp; NTSTATUS status; SMB_BIG_UINT allocation_size = (SMB_BIG_UINT)IVAL(inbuf,smb_vwv9); ssize_t retval = -1; uint32 access_mask; uint32 share_mode; uint32 create_disposition; uint32 create_options = 0; START_PROFILE(SMBopenX); /* If it's an IPC, pass off the pipe handler. */ if (IS_IPC(conn)) { if (lp_nt_pipe_support()) { END_PROFILE(SMBopenX); return reply_open_pipe_and_X(conn, inbuf,outbuf,length,bufsize); } else { END_PROFILE(SMBopenX); return ERROR_DOS(ERRSRV,ERRaccess); } } /* XXXX we need to handle passed times, sattr and flags */ srvstr_get_path(inbuf, fname, smb_buf(inbuf), sizeof(fname), 0, STR_TERMINATE, &status); if (!NT_STATUS_IS_OK(status)) { END_PROFILE(SMBopenX); return ERROR_NT(status); } status = resolve_dfspath(conn, SVAL(inbuf,smb_flg2) & FLAGS2_DFS_PATHNAMES, fname); if (!NT_STATUS_IS_OK(status)) { END_PROFILE(SMBopenX); if (NT_STATUS_EQUAL(status,NT_STATUS_PATH_NOT_COVERED)) { return ERROR_BOTH(NT_STATUS_PATH_NOT_COVERED, ERRSRV, ERRbadpath); } return ERROR_NT(status); } status = unix_convert(conn, fname, False, NULL, &sbuf); if (!NT_STATUS_IS_OK(status)) { END_PROFILE(SMBopenX); return ERROR_NT(status); } status = check_name(conn, fname); if (!NT_STATUS_IS_OK(status)) { END_PROFILE(SMBopenX); return ERROR_NT(status); } if (!map_open_params_to_ntcreate(fname, deny_mode, smb_ofun, &access_mask, &share_mode, &create_disposition, &create_options)) { END_PROFILE(SMBopenX); return ERROR_NT(NT_STATUS_DOS(ERRDOS, ERRbadaccess)); } status = open_file_ntcreate(conn,fname,&sbuf, access_mask, share_mode, create_disposition, create_options, smb_attr, oplock_request, &smb_action, &fsp); if (!NT_STATUS_IS_OK(status)) { END_PROFILE(SMBopenX); if (open_was_deferred(SVAL(inbuf,smb_mid))) { /* We have re-scheduled this call. */ return -1; } return ERROR_NT(status); } /* Setting the "size" field in vwv9 and vwv10 causes the file to be set to this size, if the file is truncated or created. */ if (((smb_action == FILE_WAS_CREATED) || (smb_action == FILE_WAS_OVERWRITTEN)) && allocation_size) { fsp->initial_allocation_size = smb_roundup(fsp->conn, allocation_size); if (vfs_allocate_file_space(fsp, fsp->initial_allocation_size) == -1) { close_file(fsp,ERROR_CLOSE); END_PROFILE(SMBopenX); return ERROR_NT(NT_STATUS_DISK_FULL); } retval = vfs_set_filelen(fsp, (SMB_OFF_T)allocation_size); if (retval < 0) { close_file(fsp,ERROR_CLOSE); END_PROFILE(SMBopenX); return ERROR_NT(NT_STATUS_DISK_FULL); } sbuf.st_size = get_allocation_size(conn,fsp,&sbuf); } fattr = dos_mode(conn,fname,&sbuf); mtime = sbuf.st_mtime; if (fattr & aDIR) { close_file(fsp,ERROR_CLOSE); END_PROFILE(SMBopenX); return ERROR_DOS(ERRDOS,ERRnoaccess); } /* If the caller set the extended oplock request bit and we granted one (by whatever means) - set the correct bit for extended oplock reply. */ if (ex_oplock_request && lp_fake_oplocks(SNUM(conn))) { smb_action |= EXTENDED_OPLOCK_GRANTED; } if(ex_oplock_request && EXCLUSIVE_OPLOCK_TYPE(fsp->oplock_type)) { smb_action |= EXTENDED_OPLOCK_GRANTED; } /* If the caller set the core oplock request bit and we granted one (by whatever means) - set the correct bit for core oplock reply. */ if (core_oplock_request && lp_fake_oplocks(SNUM(conn))) { SCVAL(outbuf,smb_flg,CVAL(outbuf,smb_flg)|CORE_OPLOCK_GRANTED); } if(core_oplock_request && EXCLUSIVE_OPLOCK_TYPE(fsp->oplock_type)) { SCVAL(outbuf,smb_flg,CVAL(outbuf,smb_flg)|CORE_OPLOCK_GRANTED); } if (open_flags & EXTENDED_RESPONSE_REQUIRED) { set_message(outbuf,19,0,True); } else { set_message(outbuf,15,0,True); } SSVAL(outbuf,smb_vwv2,fsp->fnum); SSVAL(outbuf,smb_vwv3,fattr); if(lp_dos_filetime_resolution(SNUM(conn)) ) { srv_put_dos_date3(outbuf,smb_vwv4,mtime & ~1); } else { srv_put_dos_date3(outbuf,smb_vwv4,mtime); } SIVAL(outbuf,smb_vwv6,(uint32)sbuf.st_size); SSVAL(outbuf,smb_vwv8,GET_OPENX_MODE(deny_mode)); SSVAL(outbuf,smb_vwv11,smb_action); if (open_flags & EXTENDED_RESPONSE_REQUIRED) { SIVAL(outbuf, smb_vwv15, STD_RIGHT_ALL_ACCESS); } END_PROFILE(SMBopenX); return chain_reply(inbuf,outbuf,length,bufsize); } /**************************************************************************** Reply to a SMBulogoffX. conn POINTER CAN BE NULL HERE ! ****************************************************************************/ int reply_ulogoffX(connection_struct *conn, char *inbuf,char *outbuf,int length,int bufsize) { uint16 vuid = SVAL(inbuf,smb_uid); user_struct *vuser = get_valid_user_struct(vuid); START_PROFILE(SMBulogoffX); if(vuser == 0) DEBUG(3,("ulogoff, vuser id %d does not map to user.\n", vuid)); /* in user level security we are supposed to close any files open by this user */ if ((vuser != 0) && (lp_security() != SEC_SHARE)) file_close_user(vuid); invalidate_vuid(vuid); set_message(outbuf,2,0,True); DEBUG( 3, ( "ulogoffX vuid=%d\n", vuid ) ); END_PROFILE(SMBulogoffX); return chain_reply(inbuf,outbuf,length,bufsize); } /**************************************************************************** Reply to a mknew or a create. ****************************************************************************/ int reply_mknew(connection_struct *conn, char *inbuf,char *outbuf, int dum_size, int dum_buffsize) { pstring fname; int com; int outsize = 0; uint32 fattr = SVAL(inbuf,smb_vwv0); struct timespec ts[2]; files_struct *fsp; int oplock_request = CORE_OPLOCK_REQUEST(inbuf); SMB_STRUCT_STAT sbuf; NTSTATUS status; uint32 access_mask = FILE_GENERIC_READ | FILE_GENERIC_WRITE; uint32 share_mode = FILE_SHARE_READ|FILE_SHARE_WRITE; uint32 create_disposition; uint32 create_options = 0; START_PROFILE(SMBcreate); com = SVAL(inbuf,smb_com); ts[1] = convert_time_t_to_timespec(srv_make_unix_date3(inbuf + smb_vwv1)); /* mtime. */ srvstr_get_path(inbuf, fname, smb_buf(inbuf) + 1, sizeof(fname), 0, STR_TERMINATE, &status); if (!NT_STATUS_IS_OK(status)) { END_PROFILE(SMBcreate); return ERROR_NT(status); } status = resolve_dfspath(conn, SVAL(inbuf,smb_flg2) & FLAGS2_DFS_PATHNAMES, fname); if (!NT_STATUS_IS_OK(status)) { END_PROFILE(SMBcreate); if (NT_STATUS_EQUAL(status,NT_STATUS_PATH_NOT_COVERED)) { return ERROR_BOTH(NT_STATUS_PATH_NOT_COVERED, ERRSRV, ERRbadpath); } return ERROR_NT(status); } status = unix_convert(conn, fname, False, NULL, &sbuf); if (!NT_STATUS_IS_OK(status)) { END_PROFILE(SMBcreate); return ERROR_NT(status); } status = check_name(conn, fname); if (!NT_STATUS_IS_OK(status)) { END_PROFILE(SMBcreate); return ERROR_NT(status); } if (fattr & aVOLID) { DEBUG(0,("Attempt to create file (%s) with volid set - please report this\n",fname)); } if(com == SMBmknew) { /* We should fail if file exists. */ create_disposition = FILE_CREATE; } else { /* Create if file doesn't exist, truncate if it does. */ create_disposition = FILE_OVERWRITE_IF; } /* Open file using ntcreate. */ status = open_file_ntcreate(conn,fname,&sbuf, access_mask, share_mode, create_disposition, create_options, fattr, oplock_request, NULL, &fsp); if (!NT_STATUS_IS_OK(status)) { END_PROFILE(SMBcreate); if (open_was_deferred(SVAL(inbuf,smb_mid))) { /* We have re-scheduled this call. */ return -1; } return ERROR_NT(status); } ts[0] = get_atimespec(&sbuf); /* atime. */ file_ntimes(conn, fname, ts); outsize = set_message(outbuf,1,0,True); SSVAL(outbuf,smb_vwv0,fsp->fnum); if (oplock_request && lp_fake_oplocks(SNUM(conn))) { SCVAL(outbuf,smb_flg,CVAL(outbuf,smb_flg)|CORE_OPLOCK_GRANTED); } if(EXCLUSIVE_OPLOCK_TYPE(fsp->oplock_type)) { SCVAL(outbuf,smb_flg,CVAL(outbuf,smb_flg)|CORE_OPLOCK_GRANTED); } DEBUG( 2, ( "reply_mknew: file %s\n", fname ) ); DEBUG( 3, ( "reply_mknew %s fd=%d dmode=0x%x\n", fname, fsp->fh->fd, (unsigned int)fattr ) ); END_PROFILE(SMBcreate); return(outsize); } /**************************************************************************** Reply to a create temporary file. ****************************************************************************/ int reply_ctemp(connection_struct *conn, char *inbuf,char *outbuf, int dum_size, int dum_buffsize) { pstring fname; int outsize = 0; uint32 fattr = SVAL(inbuf,smb_vwv0); files_struct *fsp; int oplock_request = CORE_OPLOCK_REQUEST(inbuf); int tmpfd; SMB_STRUCT_STAT sbuf; char *p, *s; NTSTATUS status; unsigned int namelen; START_PROFILE(SMBctemp); srvstr_get_path(inbuf, fname, smb_buf(inbuf)+1, sizeof(fname), 0, STR_TERMINATE, &status); if (!NT_STATUS_IS_OK(status)) { END_PROFILE(SMBctemp); return ERROR_NT(status); } if (*fname) { pstrcat(fname,"/TMXXXXXX"); } else { pstrcat(fname,"TMXXXXXX"); } status = resolve_dfspath(conn, SVAL(inbuf,smb_flg2) & FLAGS2_DFS_PATHNAMES, fname); if (!NT_STATUS_IS_OK(status)) { END_PROFILE(SMBctemp); if (NT_STATUS_EQUAL(status,NT_STATUS_PATH_NOT_COVERED)) { return ERROR_BOTH(NT_STATUS_PATH_NOT_COVERED, ERRSRV, ERRbadpath); } return ERROR_NT(status); } status = unix_convert(conn, fname, False, NULL, &sbuf); if (!NT_STATUS_IS_OK(status)) { END_PROFILE(SMBctemp); return ERROR_NT(status); } status = check_name(conn, fname); if (!NT_STATUS_IS_OK(status)) { END_PROFILE(SMBctemp); return ERROR_NT(status); } tmpfd = smb_mkstemp(fname); if (tmpfd == -1) { END_PROFILE(SMBctemp); return(UNIXERROR(ERRDOS,ERRnoaccess)); } SMB_VFS_STAT(conn,fname,&sbuf); /* We should fail if file does not exist. */ status = open_file_ntcreate(conn,fname,&sbuf, FILE_GENERIC_READ | FILE_GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, FILE_OPEN, 0, fattr, oplock_request, NULL, &fsp); /* close fd from smb_mkstemp() */ close(tmpfd); if (!NT_STATUS_IS_OK(status)) { END_PROFILE(SMBctemp); if (open_was_deferred(SVAL(inbuf,smb_mid))) { /* We have re-scheduled this call. */ return -1; } return ERROR_NT(status); } outsize = set_message(outbuf,1,0,True); SSVAL(outbuf,smb_vwv0,fsp->fnum); /* the returned filename is relative to the directory */ s = strrchr_m(fname, '/'); if (!s) { s = fname; } else { s++; } p = smb_buf(outbuf); #if 0 /* Tested vs W2K3 - this doesn't seem to be here - null terminated filename is the only thing in the byte section. JRA */ SSVALS(p, 0, -1); /* what is this? not in spec */ #endif namelen = srvstr_push(outbuf, p, s, -1, STR_ASCII|STR_TERMINATE); p += namelen; outsize = set_message_end(outbuf, p); if (oplock_request && lp_fake_oplocks(SNUM(conn))) { SCVAL(outbuf,smb_flg,CVAL(outbuf,smb_flg)|CORE_OPLOCK_GRANTED); } if (EXCLUSIVE_OPLOCK_TYPE(fsp->oplock_type)) { SCVAL(outbuf,smb_flg,CVAL(outbuf,smb_flg)|CORE_OPLOCK_GRANTED); } DEBUG( 2, ( "reply_ctemp: created temp file %s\n", fname ) ); DEBUG( 3, ( "reply_ctemp %s fd=%d umode=0%o\n", fname, fsp->fh->fd, (unsigned int)sbuf.st_mode ) ); END_PROFILE(SMBctemp); return(outsize); } /******************************************************************* Check if a user is allowed to rename a file. ********************************************************************/ static NTSTATUS can_rename(connection_struct *conn, char *fname, uint16 dirtype, SMB_STRUCT_STAT *pst, BOOL self_open) { files_struct *fsp; uint32 fmode; NTSTATUS status; if (!CAN_WRITE(conn)) { return NT_STATUS_MEDIA_WRITE_PROTECTED; } fmode = dos_mode(conn,fname,pst); if ((fmode & ~dirtype) & (aHIDDEN | aSYSTEM)) { return NT_STATUS_NO_SUCH_FILE; } if (S_ISDIR(pst->st_mode)) { return NT_STATUS_OK; } status = open_file_ntcreate(conn, fname, pst, DELETE_ACCESS, /* If we're checking our fsp don't deny for delete. */ self_open ? FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE : FILE_SHARE_READ|FILE_SHARE_WRITE, FILE_OPEN, 0, FILE_ATTRIBUTE_NORMAL, 0, NULL, &fsp); if (!NT_STATUS_IS_OK(status)) { return status; } close_file(fsp,NORMAL_CLOSE); return NT_STATUS_OK; } /******************************************************************* Check if a user is allowed to delete a file. ********************************************************************/ static NTSTATUS can_delete(connection_struct *conn, char *fname, uint32 dirtype, BOOL can_defer) { SMB_STRUCT_STAT sbuf; uint32 fattr; files_struct *fsp; uint32 dirtype_orig = dirtype; NTSTATUS status; DEBUG(10,("can_delete: %s, dirtype = %d\n", fname, dirtype )); if (!CAN_WRITE(conn)) { return NT_STATUS_MEDIA_WRITE_PROTECTED; } if (SMB_VFS_LSTAT(conn,fname,&sbuf) != 0) { return map_nt_error_from_unix(errno); } fattr = dos_mode(conn,fname,&sbuf); if (dirtype & FILE_ATTRIBUTE_NORMAL) { dirtype = aDIR|aARCH|aRONLY; } dirtype &= (aDIR|aARCH|aRONLY|aHIDDEN|aSYSTEM); if (!dirtype) { return NT_STATUS_NO_SUCH_FILE; } if (!dir_check_ftype(conn, fattr, dirtype)) { if (fattr & aDIR) { return NT_STATUS_FILE_IS_A_DIRECTORY; } return NT_STATUS_NO_SUCH_FILE; } if (dirtype_orig & 0x8000) { /* These will never be set for POSIX. */ return NT_STATUS_NO_SUCH_FILE; } #if 0 if ((fattr & dirtype) & FILE_ATTRIBUTE_DIRECTORY) { return NT_STATUS_FILE_IS_A_DIRECTORY; } if ((fattr & ~dirtype) & (FILE_ATTRIBUTE_HIDDEN|FILE_ATTRIBUTE_SYSTEM)) { return NT_STATUS_NO_SUCH_FILE; } if (dirtype & 0xFF00) { /* These will never be set for POSIX. */ return NT_STATUS_NO_SUCH_FILE; } dirtype &= 0xFF; if (!dirtype) { return NT_STATUS_NO_SUCH_FILE; } /* Can't delete a directory. */ if (fattr & aDIR) { return NT_STATUS_FILE_IS_A_DIRECTORY; } #endif #if 0 /* JRATEST */ else if (dirtype & aDIR) /* Asked for a directory and it isn't. */ return NT_STATUS_OBJECT_NAME_INVALID; #endif /* JRATEST */ /* Fix for bug #3035 from SATOH Fumiyasu <[email protected]> On a Windows share, a file with read-only dosmode can be opened with DELETE_ACCESS. But on a Samba share (delete readonly = no), it fails with NT_STATUS_CANNOT_DELETE error. This semantic causes a problem that a user can not rename a file with read-only dosmode on a Samba share from a Windows command prompt (i.e. cmd.exe, but can rename from Windows Explorer). */ if (!lp_delete_readonly(SNUM(conn))) { if (fattr & aRONLY) { return NT_STATUS_CANNOT_DELETE; } } /* On open checks the open itself will check the share mode, so don't do it here as we'll get it wrong. */ status = open_file_ntcreate(conn, fname, &sbuf, DELETE_ACCESS, FILE_SHARE_NONE, FILE_OPEN, 0, FILE_ATTRIBUTE_NORMAL, can_defer ? 0 : INTERNAL_OPEN_ONLY, NULL, &fsp); if (NT_STATUS_IS_OK(status)) { close_file(fsp,NORMAL_CLOSE); } return status; } /**************************************************************************** The guts of the unlink command, split out so it may be called by the NT SMB code. ****************************************************************************/ NTSTATUS unlink_internals(connection_struct *conn, uint32 dirtype, char *name, BOOL has_wild, BOOL can_defer) { pstring directory; pstring mask; char *p; int count=0; NTSTATUS status = NT_STATUS_OK; SMB_STRUCT_STAT sbuf; *directory = *mask = 0; status = unix_convert(conn, name, has_wild, NULL, &sbuf); if (!NT_STATUS_IS_OK(status)) { return status; } p = strrchr_m(name,'/'); if (!p) { pstrcpy(directory,"."); pstrcpy(mask,name); } else { *p = 0; pstrcpy(directory,name); pstrcpy(mask,p+1); } /* * We should only check the mangled cache * here if unix_convert failed. This means * that the path in 'mask' doesn't exist * on the file system and so we need to look * for a possible mangle. This patch from * Tine Smukavec <[email protected]>. */ if (!VALID_STAT(sbuf) && mangle_is_mangled(mask,conn->params)) mangle_check_cache( mask, sizeof(pstring)-1, conn->params ); if (!has_wild) { pstrcat(directory,"/"); pstrcat(directory,mask); if (dirtype == 0) { dirtype = FILE_ATTRIBUTE_NORMAL; } status = check_name(conn, directory); if (!NT_STATUS_IS_OK(status)) { return status; } status = can_delete(conn,directory,dirtype,can_defer); if (!NT_STATUS_IS_OK(status)) { return status; } if (SMB_VFS_UNLINK(conn,directory) == 0) { count++; notify_fname(conn, NOTIFY_ACTION_REMOVED, FILE_NOTIFY_CHANGE_FILE_NAME, directory); } } else { struct smb_Dir *dir_hnd = NULL; long offset = 0; const char *dname; if ((dirtype & SAMBA_ATTRIBUTES_MASK) == aDIR) { return NT_STATUS_OBJECT_NAME_INVALID; } if (strequal(mask,"????????.???")) { pstrcpy(mask,"*"); } status = check_name(conn, directory); if (!NT_STATUS_IS_OK(status)) { return status; } dir_hnd = OpenDir(conn, directory, mask, dirtype); if (dir_hnd == NULL) { return map_nt_error_from_unix(errno); } /* XXXX the CIFS spec says that if bit0 of the flags2 field is set then the pattern matches against the long name, otherwise the short name We don't implement this yet XXXX */ status = NT_STATUS_NO_SUCH_FILE; while ((dname = ReadDirName(dir_hnd, &offset))) { SMB_STRUCT_STAT st; pstring fname; pstrcpy(fname,dname); if (!is_visible_file(conn, directory, dname, &st, True)) { continue; } /* Quick check for "." and ".." */ if (fname[0] == '.') { if (!fname[1] || (fname[1] == '.' && !fname[2])) { continue; } } if(!mask_match(fname, mask, conn->case_sensitive)) { continue; } slprintf(fname,sizeof(fname)-1, "%s/%s",directory,dname); status = check_name(conn, fname); if (!NT_STATUS_IS_OK(status)) { CloseDir(dir_hnd); return status; } status = can_delete(conn, fname, dirtype, can_defer); if (!NT_STATUS_IS_OK(status)) { continue; } if (SMB_VFS_UNLINK(conn,fname) == 0) { count++; DEBUG(3,("unlink_internals: succesful unlink " "[%s]\n",fname)); notify_fname(conn, NOTIFY_ACTION_REMOVED, FILE_NOTIFY_CHANGE_FILE_NAME, fname); } } CloseDir(dir_hnd); } if (count == 0 && NT_STATUS_IS_OK(status)) { status = map_nt_error_from_unix(errno); } return status; } /**************************************************************************** Reply to a unlink ****************************************************************************/ int reply_unlink(connection_struct *conn, char *inbuf,char *outbuf, int dum_size, int dum_buffsize) { int outsize = 0; pstring name; uint32 dirtype; NTSTATUS status; BOOL path_contains_wcard = False; START_PROFILE(SMBunlink); dirtype = SVAL(inbuf,smb_vwv0); srvstr_get_path_wcard(inbuf, name, smb_buf(inbuf) + 1, sizeof(name), 0, STR_TERMINATE, &status, &path_contains_wcard); if (!NT_STATUS_IS_OK(status)) { END_PROFILE(SMBunlink); return ERROR_NT(status); } status = resolve_dfspath_wcard(conn, SVAL(inbuf,smb_flg2) & FLAGS2_DFS_PATHNAMES, name, &path_contains_wcard); if (!NT_STATUS_IS_OK(status)) { END_PROFILE(SMBunlink); if (NT_STATUS_EQUAL(status,NT_STATUS_PATH_NOT_COVERED)) { return ERROR_BOTH(NT_STATUS_PATH_NOT_COVERED, ERRSRV, ERRbadpath); } return ERROR_NT(status); } DEBUG(3,("reply_unlink : %s\n",name)); status = unlink_internals(conn, dirtype, name, path_contains_wcard, True); if (!NT_STATUS_IS_OK(status)) { if (open_was_deferred(SVAL(inbuf,smb_mid))) { /* We have re-scheduled this call. */ return -1; } return ERROR_NT(status); } outsize = set_message(outbuf,0,0,False); END_PROFILE(SMBunlink); return outsize; } /**************************************************************************** Fail for readbraw. ****************************************************************************/ static void fail_readraw(void) { pstring errstr; slprintf(errstr, sizeof(errstr)-1, "FAIL ! reply_readbraw: socket write fail (%s)", strerror(errno) ); exit_server_cleanly(errstr); } #if defined(WITH_SENDFILE) /**************************************************************************** Fake (read/write) sendfile. Returns -1 on read or write fail. ****************************************************************************/ static ssize_t fake_sendfile(files_struct *fsp, SMB_OFF_T startpos, size_t nread, char *buf, int bufsize) { ssize_t ret=0; /* Paranioa check... */ if (nread > bufsize) { fail_readraw(); } if (nread > 0) { ret = read_file(fsp,buf,startpos,nread); if (ret == -1) { return -1; } } /* If we had a short read, fill with zeros. */ if (ret < nread) { memset(buf, '\0', nread - ret); } if (write_data(smbd_server_fd(),buf,nread) != nread) { return -1; } return (ssize_t)nread; } #endif /**************************************************************************** Use sendfile in readbraw. ****************************************************************************/ void send_file_readbraw(connection_struct *conn, files_struct *fsp, SMB_OFF_T startpos, size_t nread, ssize_t mincount, char *outbuf, int out_buffsize) { ssize_t ret=0; #if defined(WITH_SENDFILE) /* * We can only use sendfile on a non-chained packet * but we can use on a non-oplocked file. tridge proved this * on a train in Germany :-). JRA. * reply_readbraw has already checked the length. */ if ( (chain_size == 0) && (nread > 0) && (fsp->wcp == NULL) && lp_use_sendfile(SNUM(conn)) ) { DATA_BLOB header; _smb_setlen(outbuf,nread); header.data = (uint8 *)outbuf; header.length = 4; header.free = NULL; if ( SMB_VFS_SENDFILE( smbd_server_fd(), fsp, fsp->fh->fd, &header, startpos, nread) == -1) { /* Returning ENOSYS means no data at all was sent. Do this as a normal read. */ if (errno == ENOSYS) { goto normal_readbraw; } /* * Special hack for broken Linux with no working sendfile. If we * return EINTR we sent the header but not the rest of the data. * Fake this up by doing read/write calls. */ if (errno == EINTR) { /* Ensure we don't do this again. */ set_use_sendfile(SNUM(conn), False); DEBUG(0,("send_file_readbraw: sendfile not available. Faking..\n")); if (fake_sendfile(fsp, startpos, nread, outbuf + 4, out_buffsize - 4) == -1) { DEBUG(0,("send_file_readbraw: fake_sendfile failed for file %s (%s).\n", fsp->fsp_name, strerror(errno) )); exit_server_cleanly("send_file_readbraw fake_sendfile failed"); } return; } DEBUG(0,("send_file_readbraw: sendfile failed for file %s (%s). Terminating\n", fsp->fsp_name, strerror(errno) )); exit_server_cleanly("send_file_readbraw sendfile failed"); } return; } normal_readbraw: #endif if (nread > 0) { ret = read_file(fsp,outbuf+4,startpos,nread); #if 0 /* mincount appears to be ignored in a W2K server. JRA. */ if (ret < mincount) ret = 0; #else if (ret < nread) ret = 0; #endif } _smb_setlen(outbuf,ret); if (write_data(smbd_server_fd(),outbuf,4+ret) != 4+ret) fail_readraw(); } /**************************************************************************** Reply to a readbraw (core+ protocol). ****************************************************************************/ int reply_readbraw(connection_struct *conn, char *inbuf, char *outbuf, int dum_size, int out_buffsize) { ssize_t maxcount,mincount; size_t nread = 0; SMB_OFF_T startpos; char *header = outbuf; files_struct *fsp; START_PROFILE(SMBreadbraw); if (srv_is_signing_active()) { exit_server_cleanly("reply_readbraw: SMB signing is active - raw reads/writes are disallowed."); } /* * Special check if an oplock break has been issued * and the readraw request croses on the wire, we must * return a zero length response here. */ fsp = file_fsp(inbuf,smb_vwv0); if (!FNUM_OK(fsp,conn) || !fsp->can_read) { /* * fsp could be NULL here so use the value from the packet. JRA. */ DEBUG(3,("fnum %d not open in readbraw - cache prime?\n",(int)SVAL(inbuf,smb_vwv0))); _smb_setlen(header,0); if (write_data(smbd_server_fd(),header,4) != 4) fail_readraw(); END_PROFILE(SMBreadbraw); return(-1); } CHECK_FSP(fsp,conn); flush_write_cache(fsp, READRAW_FLUSH); startpos = IVAL_TO_SMB_OFF_T(inbuf,smb_vwv1); if(CVAL(inbuf,smb_wct) == 10) { /* * This is a large offset (64 bit) read. */ #ifdef LARGE_SMB_OFF_T startpos |= (((SMB_OFF_T)IVAL(inbuf,smb_vwv8)) << 32); #else /* !LARGE_SMB_OFF_T */ /* * Ensure we haven't been sent a >32 bit offset. */ if(IVAL(inbuf,smb_vwv8) != 0) { DEBUG(0,("readbraw - large offset (%x << 32) used and we don't support \ 64 bit offsets.\n", (unsigned int)IVAL(inbuf,smb_vwv8) )); _smb_setlen(header,0); if (write_data(smbd_server_fd(),header,4) != 4) fail_readraw(); END_PROFILE(SMBreadbraw); return(-1); } #endif /* LARGE_SMB_OFF_T */ if(startpos < 0) { DEBUG(0,("readbraw - negative 64 bit readraw offset (%.0f) !\n", (double)startpos )); _smb_setlen(header,0); if (write_data(smbd_server_fd(),header,4) != 4) fail_readraw(); END_PROFILE(SMBreadbraw); return(-1); } } maxcount = (SVAL(inbuf,smb_vwv3) & 0xFFFF); mincount = (SVAL(inbuf,smb_vwv4) & 0xFFFF); /* ensure we don't overrun the packet size */ maxcount = MIN(65535,maxcount); if (!is_locked(fsp,(uint32)SVAL(inbuf,smb_pid),(SMB_BIG_UINT)maxcount,(SMB_BIG_UINT)startpos, READ_LOCK)) { SMB_STRUCT_STAT st; SMB_OFF_T size = 0; if (SMB_VFS_FSTAT(fsp,fsp->fh->fd,&st) == 0) { size = st.st_size; } if (startpos >= size) { nread = 0; } else { nread = MIN(maxcount,(size - startpos)); } } #if 0 /* mincount appears to be ignored in a W2K server. JRA. */ if (nread < mincount) nread = 0; #endif DEBUG( 3, ( "readbraw fnum=%d start=%.0f max=%lu min=%lu nread=%lu\n", fsp->fnum, (double)startpos, (unsigned long)maxcount, (unsigned long)mincount, (unsigned long)nread ) ); send_file_readbraw(conn, fsp, startpos, nread, mincount, outbuf, out_buffsize); DEBUG(5,("readbraw finished\n")); END_PROFILE(SMBreadbraw); return -1; } #undef DBGC_CLASS #define DBGC_CLASS DBGC_LOCKING /**************************************************************************** Reply to a lockread (core+ protocol). ****************************************************************************/ int reply_lockread(connection_struct *conn, char *inbuf,char *outbuf, int length, int dum_buffsiz) { ssize_t nread = -1; char *data; int outsize = 0; SMB_OFF_T startpos; size_t numtoread; NTSTATUS status; files_struct *fsp = file_fsp(inbuf,smb_vwv0); struct byte_range_lock *br_lck = NULL; START_PROFILE(SMBlockread); CHECK_FSP(fsp,conn); if (!CHECK_READ(fsp,inbuf)) { return(ERROR_DOS(ERRDOS,ERRbadaccess)); } release_level_2_oplocks_on_change(fsp); numtoread = SVAL(inbuf,smb_vwv1); startpos = IVAL_TO_SMB_OFF_T(inbuf,smb_vwv2); outsize = set_message(outbuf,5,3,True); numtoread = MIN(BUFFER_SIZE-outsize,numtoread); data = smb_buf(outbuf) + 3; /* * NB. Discovered by Menny Hamburger at Mainsoft. This is a core+ * protocol request that predates the read/write lock concept. * Thus instead of asking for a read lock here we need to ask * for a write lock. JRA. * Note that the requested lock size is unaffected by max_recv. */ br_lck = do_lock(fsp, (uint32)SVAL(inbuf,smb_pid), (SMB_BIG_UINT)numtoread, (SMB_BIG_UINT)startpos, WRITE_LOCK, WINDOWS_LOCK, False, /* Non-blocking lock. */ &status, NULL); TALLOC_FREE(br_lck); if (NT_STATUS_V(status)) { END_PROFILE(SMBlockread); return ERROR_NT(status); } /* * However the requested READ size IS affected by max_recv. Insanity.... JRA. */ if (numtoread > max_recv) { DEBUG(0,("reply_lockread: requested read size (%u) is greater than maximum allowed (%u). \ Returning short read of maximum allowed for compatibility with Windows 2000.\n", (unsigned int)numtoread, (unsigned int)max_recv )); numtoread = MIN(numtoread,max_recv); } nread = read_file(fsp,data,startpos,numtoread); if (nread < 0) { END_PROFILE(SMBlockread); return(UNIXERROR(ERRDOS,ERRnoaccess)); } outsize += nread; SSVAL(outbuf,smb_vwv0,nread); SSVAL(outbuf,smb_vwv5,nread+3); SSVAL(smb_buf(outbuf),1,nread); DEBUG(3,("lockread fnum=%d num=%d nread=%d\n", fsp->fnum, (int)numtoread, (int)nread)); END_PROFILE(SMBlockread); return(outsize); } #undef DBGC_CLASS #define DBGC_CLASS DBGC_ALL /**************************************************************************** Reply to a read. ****************************************************************************/ int reply_read(connection_struct *conn, char *inbuf,char *outbuf, int size, int dum_buffsize) { size_t numtoread; ssize_t nread = 0; char *data; SMB_OFF_T startpos; int outsize = 0; files_struct *fsp = file_fsp(inbuf,smb_vwv0); START_PROFILE(SMBread); CHECK_FSP(fsp,conn); if (!CHECK_READ(fsp,inbuf)) { return(ERROR_DOS(ERRDOS,ERRbadaccess)); } numtoread = SVAL(inbuf,smb_vwv1); startpos = IVAL_TO_SMB_OFF_T(inbuf,smb_vwv2); outsize = set_message(outbuf,5,3,True); numtoread = MIN(BUFFER_SIZE-outsize,numtoread); /* * The requested read size cannot be greater than max_recv. JRA. */ if (numtoread > max_recv) { DEBUG(0,("reply_read: requested read size (%u) is greater than maximum allowed (%u). \ Returning short read of maximum allowed for compatibility with Windows 2000.\n", (unsigned int)numtoread, (unsigned int)max_recv )); numtoread = MIN(numtoread,max_recv); } data = smb_buf(outbuf) + 3; if (is_locked(fsp,(uint32)SVAL(inbuf,smb_pid),(SMB_BIG_UINT)numtoread,(SMB_BIG_UINT)startpos, READ_LOCK)) { END_PROFILE(SMBread); return ERROR_DOS(ERRDOS,ERRlock); } if (numtoread > 0) nread = read_file(fsp,data,startpos,numtoread); if (nread < 0) { END_PROFILE(SMBread); return(UNIXERROR(ERRDOS,ERRnoaccess)); } outsize += nread; SSVAL(outbuf,smb_vwv0,nread); SSVAL(outbuf,smb_vwv5,nread+3); SCVAL(smb_buf(outbuf),0,1); SSVAL(smb_buf(outbuf),1,nread); DEBUG( 3, ( "read fnum=%d num=%d nread=%d\n", fsp->fnum, (int)numtoread, (int)nread ) ); END_PROFILE(SMBread); return(outsize); } /**************************************************************************** Reply to a read and X - possibly using sendfile. ****************************************************************************/ int send_file_readX(connection_struct *conn, char *inbuf,char *outbuf,int length, int len_outbuf, files_struct *fsp, SMB_OFF_T startpos, size_t smb_maxcnt) { int outsize = 0; ssize_t nread = -1; char *data = smb_buf(outbuf); #if defined(WITH_SENDFILE) /* * We can only use sendfile on a non-chained packet * but we can use on a non-oplocked file. tridge proved this * on a train in Germany :-). JRA. */ if ((chain_size == 0) && (CVAL(inbuf,smb_vwv0) == 0xFF) && lp_use_sendfile(SNUM(conn)) && (fsp->wcp == NULL) ) { SMB_STRUCT_STAT sbuf; DATA_BLOB header; if(SMB_VFS_FSTAT(fsp,fsp->fh->fd, &sbuf) == -1) return(UNIXERROR(ERRDOS,ERRnoaccess)); if (startpos > sbuf.st_size) goto normal_read; if (smb_maxcnt > (sbuf.st_size - startpos)) smb_maxcnt = (sbuf.st_size - startpos); if (smb_maxcnt == 0) goto normal_read; /* * Set up the packet header before send. We * assume here the sendfile will work (get the * correct amount of data). */ SSVAL(outbuf,smb_vwv2,0xFFFF); /* Remaining - must be -1. */ SSVAL(outbuf,smb_vwv5,smb_maxcnt); SSVAL(outbuf,smb_vwv6,smb_offset(data,outbuf)); SSVAL(outbuf,smb_vwv7,((smb_maxcnt >> 16) & 1)); SSVAL(smb_buf(outbuf),-2,smb_maxcnt); SCVAL(outbuf,smb_vwv0,0xFF); set_message(outbuf,12,smb_maxcnt,False); header.data = (uint8 *)outbuf; header.length = data - outbuf; header.free = NULL; if ((nread = SMB_VFS_SENDFILE( smbd_server_fd(), fsp, fsp->fh->fd, &header, startpos, smb_maxcnt)) == -1) { /* Returning ENOSYS means no data at all was sent. Do this as a normal read. */ if (errno == ENOSYS) { goto normal_read; } /* * Special hack for broken Linux with no working sendfile. If we * return EINTR we sent the header but not the rest of the data. * Fake this up by doing read/write calls. */ if (errno == EINTR) { /* Ensure we don't do this again. */ set_use_sendfile(SNUM(conn), False); DEBUG(0,("send_file_readX: sendfile not available. Faking..\n")); if ((nread = fake_sendfile(fsp, startpos, smb_maxcnt, data, len_outbuf - (data-outbuf))) == -1) { DEBUG(0,("send_file_readX: fake_sendfile failed for file %s (%s).\n", fsp->fsp_name, strerror(errno) )); exit_server_cleanly("send_file_readX: fake_sendfile failed"); } DEBUG( 3, ( "send_file_readX: fake_sendfile fnum=%d max=%d nread=%d\n", fsp->fnum, (int)smb_maxcnt, (int)nread ) ); /* Returning -1 here means successful sendfile. */ return -1; } DEBUG(0,("send_file_readX: sendfile failed for file %s (%s). Terminating\n", fsp->fsp_name, strerror(errno) )); exit_server_cleanly("send_file_readX sendfile failed"); } DEBUG( 3, ( "send_file_readX: sendfile fnum=%d max=%d nread=%d\n", fsp->fnum, (int)smb_maxcnt, (int)nread ) ); /* Returning -1 here means successful sendfile. */ return -1; } normal_read: #endif nread = read_file(fsp,data,startpos,smb_maxcnt); if (nread < 0) { return(UNIXERROR(ERRDOS,ERRnoaccess)); } outsize = set_message(outbuf,12,nread,False); SSVAL(outbuf,smb_vwv2,0xFFFF); /* Remaining - must be -1. */ SSVAL(outbuf,smb_vwv5,nread); SSVAL(outbuf,smb_vwv6,smb_offset(data,outbuf)); SSVAL(outbuf,smb_vwv7,((nread >> 16) & 1)); SSVAL(smb_buf(outbuf),-2,nread); DEBUG( 3, ( "send_file_readX fnum=%d max=%d nread=%d\n", fsp->fnum, (int)smb_maxcnt, (int)nread ) ); /* Returning the number of bytes we want to send back - including header. */ return outsize; } /**************************************************************************** Reply to a read and X. ****************************************************************************/ int reply_read_and_X(connection_struct *conn, char *inbuf,char *outbuf,int length,int bufsize) { files_struct *fsp = file_fsp(inbuf,smb_vwv2); SMB_OFF_T startpos = IVAL_TO_SMB_OFF_T(inbuf,smb_vwv3); ssize_t nread = -1; size_t smb_maxcnt = SVAL(inbuf,smb_vwv5); #if 0 size_t smb_mincnt = SVAL(inbuf,smb_vwv6); #endif START_PROFILE(SMBreadX); /* If it's an IPC, pass off the pipe handler. */ if (IS_IPC(conn)) { END_PROFILE(SMBreadX); return reply_pipe_read_and_X(inbuf,outbuf,length,bufsize); } CHECK_FSP(fsp,conn); if (!CHECK_READ(fsp,inbuf)) { return(ERROR_DOS(ERRDOS,ERRbadaccess)); } set_message(outbuf,12,0,True); if (global_client_caps & CAP_LARGE_READX) { if (SVAL(inbuf,smb_vwv7) == 1) { smb_maxcnt |= (1<<16); } if (smb_maxcnt > BUFFER_SIZE) { DEBUG(0,("reply_read_and_X - read too large (%u) for reply buffer %u\n", (unsigned int)smb_maxcnt, (unsigned int)BUFFER_SIZE)); END_PROFILE(SMBreadX); return ERROR_NT(NT_STATUS_INVALID_PARAMETER); } } if(CVAL(inbuf,smb_wct) == 12) { #ifdef LARGE_SMB_OFF_T /* * This is a large offset (64 bit) read. */ startpos |= (((SMB_OFF_T)IVAL(inbuf,smb_vwv10)) << 32); #else /* !LARGE_SMB_OFF_T */ /* * Ensure we haven't been sent a >32 bit offset. */ if(IVAL(inbuf,smb_vwv10) != 0) { DEBUG(0,("reply_read_and_X - large offset (%x << 32) used and we don't support \ 64 bit offsets.\n", (unsigned int)IVAL(inbuf,smb_vwv10) )); END_PROFILE(SMBreadX); return ERROR_DOS(ERRDOS,ERRbadaccess); } #endif /* LARGE_SMB_OFF_T */ } if (is_locked(fsp,(uint32)SVAL(inbuf,smb_pid),(SMB_BIG_UINT)smb_maxcnt,(SMB_BIG_UINT)startpos, READ_LOCK)) { END_PROFILE(SMBreadX); return ERROR_DOS(ERRDOS,ERRlock); } if (schedule_aio_read_and_X(conn, inbuf, outbuf, length, bufsize, fsp, startpos, smb_maxcnt)) { END_PROFILE(SMBreadX); return -1; } nread = send_file_readX(conn, inbuf, outbuf, length, bufsize, fsp, startpos, smb_maxcnt); /* Only call chain_reply if not an error. */ if (nread != -1 && SVAL(outbuf,smb_rcls) == 0) { nread = chain_reply(inbuf,outbuf,length,bufsize); } END_PROFILE(SMBreadX); return nread; } /**************************************************************************** Reply to a writebraw (core+ or LANMAN1.0 protocol). ****************************************************************************/ int reply_writebraw(connection_struct *conn, char *inbuf,char *outbuf, int size, int dum_buffsize) { ssize_t nwritten=0; ssize_t total_written=0; size_t numtowrite=0; size_t tcount; SMB_OFF_T startpos; char *data=NULL; BOOL write_through; files_struct *fsp = file_fsp(inbuf,smb_vwv0); int outsize = 0; START_PROFILE(SMBwritebraw); if (srv_is_signing_active()) { exit_server_cleanly("reply_writebraw: SMB signing is active - raw reads/writes are disallowed."); } CHECK_FSP(fsp,conn); if (!CHECK_WRITE(fsp)) { return(ERROR_DOS(ERRDOS,ERRbadaccess)); } tcount = IVAL(inbuf,smb_vwv1); startpos = IVAL_TO_SMB_OFF_T(inbuf,smb_vwv3); write_through = BITSETW(inbuf+smb_vwv7,0); /* We have to deal with slightly different formats depending on whether we are using the core+ or lanman1.0 protocol */ if(Protocol <= PROTOCOL_COREPLUS) { numtowrite = SVAL(smb_buf(inbuf),-2); data = smb_buf(inbuf); } else { numtowrite = SVAL(inbuf,smb_vwv10); data = smb_base(inbuf) + SVAL(inbuf, smb_vwv11); } /* force the error type */ SCVAL(inbuf,smb_com,SMBwritec); SCVAL(outbuf,smb_com,SMBwritec); if (is_locked(fsp,(uint32)SVAL(inbuf,smb_pid),(SMB_BIG_UINT)tcount,(SMB_BIG_UINT)startpos, WRITE_LOCK)) { END_PROFILE(SMBwritebraw); return(ERROR_DOS(ERRDOS,ERRlock)); } if (numtowrite>0) nwritten = write_file(fsp,data,startpos,numtowrite); DEBUG(3,("writebraw1 fnum=%d start=%.0f num=%d wrote=%d sync=%d\n", fsp->fnum, (double)startpos, (int)numtowrite, (int)nwritten, (int)write_through)); if (nwritten < (ssize_t)numtowrite) { END_PROFILE(SMBwritebraw); return(UNIXERROR(ERRHRD,ERRdiskfull)); } total_written = nwritten; /* Return a message to the redirector to tell it to send more bytes */ SCVAL(outbuf,smb_com,SMBwritebraw); SSVALS(outbuf,smb_vwv0,-1); outsize = set_message(outbuf,Protocol>PROTOCOL_COREPLUS?1:0,0,True); show_msg(outbuf); if (!send_smb(smbd_server_fd(),outbuf)) exit_server_cleanly("reply_writebraw: send_smb failed."); /* Now read the raw data into the buffer and write it */ if (read_smb_length(smbd_server_fd(),inbuf,SMB_SECONDARY_WAIT) == -1) { exit_server_cleanly("secondary writebraw failed"); } /* Even though this is not an smb message, smb_len returns the generic length of an smb message */ numtowrite = smb_len(inbuf); /* Set up outbuf to return the correct return */ outsize = set_message(outbuf,1,0,True); SCVAL(outbuf,smb_com,SMBwritec); if (numtowrite != 0) { if (numtowrite > BUFFER_SIZE) { DEBUG(0,("reply_writebraw: Oversize secondary write raw requested (%u). Terminating\n", (unsigned int)numtowrite )); exit_server_cleanly("secondary writebraw failed"); } if (tcount > nwritten+numtowrite) { DEBUG(3,("Client overestimated the write %d %d %d\n", (int)tcount,(int)nwritten,(int)numtowrite)); } if (read_data( smbd_server_fd(), inbuf+4, numtowrite) != numtowrite ) { DEBUG(0,("reply_writebraw: Oversize secondary write raw read failed (%s). Terminating\n", strerror(errno) )); exit_server_cleanly("secondary writebraw failed"); } nwritten = write_file(fsp,inbuf+4,startpos+nwritten,numtowrite); if (nwritten == -1) { END_PROFILE(SMBwritebraw); return(UNIXERROR(ERRHRD,ERRdiskfull)); } if (nwritten < (ssize_t)numtowrite) { SCVAL(outbuf,smb_rcls,ERRHRD); SSVAL(outbuf,smb_err,ERRdiskfull); } if (nwritten > 0) total_written += nwritten; } SSVAL(outbuf,smb_vwv0,total_written); sync_file(conn, fsp, write_through); DEBUG(3,("writebraw2 fnum=%d start=%.0f num=%d wrote=%d\n", fsp->fnum, (double)startpos, (int)numtowrite,(int)total_written)); /* we won't return a status if write through is not selected - this follows what WfWg does */ END_PROFILE(SMBwritebraw); if (!write_through && total_written==tcount) { #if RABBIT_PELLET_FIX /* * Fix for "rabbit pellet" mode, trigger an early TCP ack by * sending a SMBkeepalive. Thanks to DaveCB at Sun for this. JRA. */ if (!send_keepalive(smbd_server_fd())) exit_server_cleanly("reply_writebraw: send of keepalive failed"); #endif return(-1); } return(outsize); } #undef DBGC_CLASS #define DBGC_CLASS DBGC_LOCKING /**************************************************************************** Reply to a writeunlock (core+). ****************************************************************************/ int reply_writeunlock(connection_struct *conn, char *inbuf,char *outbuf, int size, int dum_buffsize) { ssize_t nwritten = -1; size_t numtowrite; SMB_OFF_T startpos; char *data; NTSTATUS status = NT_STATUS_OK; files_struct *fsp = file_fsp(inbuf,smb_vwv0); int outsize = 0; START_PROFILE(SMBwriteunlock); CHECK_FSP(fsp,conn); if (!CHECK_WRITE(fsp)) { return(ERROR_DOS(ERRDOS,ERRbadaccess)); } numtowrite = SVAL(inbuf,smb_vwv1); startpos = IVAL_TO_SMB_OFF_T(inbuf,smb_vwv2); data = smb_buf(inbuf) + 3; if (numtowrite && is_locked(fsp,(uint32)SVAL(inbuf,smb_pid),(SMB_BIG_UINT)numtowrite,(SMB_BIG_UINT)startpos, WRITE_LOCK)) { END_PROFILE(SMBwriteunlock); return ERROR_DOS(ERRDOS,ERRlock); } /* The special X/Open SMB protocol handling of zero length writes is *NOT* done for this call */ if(numtowrite == 0) { nwritten = 0; } else { nwritten = write_file(fsp,data,startpos,numtowrite); } sync_file(conn, fsp, False /* write through */); if(((nwritten == 0) && (numtowrite != 0))||(nwritten < 0)) { END_PROFILE(SMBwriteunlock); return(UNIXERROR(ERRHRD,ERRdiskfull)); } if (numtowrite) { status = do_unlock(fsp, (uint32)SVAL(inbuf,smb_pid), (SMB_BIG_UINT)numtowrite, (SMB_BIG_UINT)startpos, WINDOWS_LOCK); if (NT_STATUS_V(status)) { END_PROFILE(SMBwriteunlock); return ERROR_NT(status); } } outsize = set_message(outbuf,1,0,True); SSVAL(outbuf,smb_vwv0,nwritten); DEBUG(3,("writeunlock fnum=%d num=%d wrote=%d\n", fsp->fnum, (int)numtowrite, (int)nwritten)); END_PROFILE(SMBwriteunlock); return outsize; } #undef DBGC_CLASS #define DBGC_CLASS DBGC_ALL /**************************************************************************** Reply to a write. ****************************************************************************/ int reply_write(connection_struct *conn, char *inbuf,char *outbuf,int size,int dum_buffsize) { size_t numtowrite; ssize_t nwritten = -1; SMB_OFF_T startpos; char *data; files_struct *fsp = file_fsp(inbuf,smb_vwv0); int outsize = 0; START_PROFILE(SMBwrite); /* If it's an IPC, pass off the pipe handler. */ if (IS_IPC(conn)) { END_PROFILE(SMBwrite); return reply_pipe_write(inbuf,outbuf,size,dum_buffsize); } CHECK_FSP(fsp,conn); if (!CHECK_WRITE(fsp)) { return(ERROR_DOS(ERRDOS,ERRbadaccess)); } numtowrite = SVAL(inbuf,smb_vwv1); startpos = IVAL_TO_SMB_OFF_T(inbuf,smb_vwv2); data = smb_buf(inbuf) + 3; if (is_locked(fsp,(uint32)SVAL(inbuf,smb_pid),(SMB_BIG_UINT)numtowrite,(SMB_BIG_UINT)startpos, WRITE_LOCK)) { END_PROFILE(SMBwrite); return ERROR_DOS(ERRDOS,ERRlock); } /* * X/Open SMB protocol says that if smb_vwv1 is * zero then the file size should be extended or * truncated to the size given in smb_vwv[2-3]. */ if(numtowrite == 0) { /* * This is actually an allocate call, and set EOF. JRA. */ nwritten = vfs_allocate_file_space(fsp, (SMB_OFF_T)startpos); if (nwritten < 0) { END_PROFILE(SMBwrite); return ERROR_NT(NT_STATUS_DISK_FULL); } nwritten = vfs_set_filelen(fsp, (SMB_OFF_T)startpos); if (nwritten < 0) { END_PROFILE(SMBwrite); return ERROR_NT(NT_STATUS_DISK_FULL); } } else nwritten = write_file(fsp,data,startpos,numtowrite); sync_file(conn, fsp, False); if(((nwritten == 0) && (numtowrite != 0))||(nwritten < 0)) { END_PROFILE(SMBwrite); return(UNIXERROR(ERRHRD,ERRdiskfull)); } outsize = set_message(outbuf,1,0,True); SSVAL(outbuf,smb_vwv0,nwritten); if (nwritten < (ssize_t)numtowrite) { SCVAL(outbuf,smb_rcls,ERRHRD); SSVAL(outbuf,smb_err,ERRdiskfull); } DEBUG(3,("write fnum=%d num=%d wrote=%d\n", fsp->fnum, (int)numtowrite, (int)nwritten)); END_PROFILE(SMBwrite); return(outsize); } /**************************************************************************** Reply to a write and X. ****************************************************************************/ int reply_write_and_X(connection_struct *conn, char *inbuf,char *outbuf,int length,int bufsize) { files_struct *fsp = file_fsp(inbuf,smb_vwv2); SMB_OFF_T startpos = IVAL_TO_SMB_OFF_T(inbuf,smb_vwv3); size_t numtowrite = SVAL(inbuf,smb_vwv10); BOOL write_through = BITSETW(inbuf+smb_vwv7,0); ssize_t nwritten = -1; unsigned int smb_doff = SVAL(inbuf,smb_vwv11); unsigned int smblen = smb_len(inbuf); char *data; BOOL large_writeX = ((CVAL(inbuf,smb_wct) == 14) && (smblen > 0xFFFF)); START_PROFILE(SMBwriteX); /* If it's an IPC, pass off the pipe handler. */ if (IS_IPC(conn)) { END_PROFILE(SMBwriteX); return reply_pipe_write_and_X(inbuf,outbuf,length,bufsize); } CHECK_FSP(fsp,conn); if (!CHECK_WRITE(fsp)) { return(ERROR_DOS(ERRDOS,ERRbadaccess)); } set_message(outbuf,6,0,True); /* Deal with possible LARGE_WRITEX */ if (large_writeX) { numtowrite |= ((((size_t)SVAL(inbuf,smb_vwv9)) & 1 )<<16); } if(smb_doff > smblen || (smb_doff + numtowrite > smblen)) { END_PROFILE(SMBwriteX); return ERROR_DOS(ERRDOS,ERRbadmem); } data = smb_base(inbuf) + smb_doff; if(CVAL(inbuf,smb_wct) == 14) { #ifdef LARGE_SMB_OFF_T /* * This is a large offset (64 bit) write. */ startpos |= (((SMB_OFF_T)IVAL(inbuf,smb_vwv12)) << 32); #else /* !LARGE_SMB_OFF_T */ /* * Ensure we haven't been sent a >32 bit offset. */ if(IVAL(inbuf,smb_vwv12) != 0) { DEBUG(0,("reply_write_and_X - large offset (%x << 32) used and we don't support \ 64 bit offsets.\n", (unsigned int)IVAL(inbuf,smb_vwv12) )); END_PROFILE(SMBwriteX); return ERROR_DOS(ERRDOS,ERRbadaccess); } #endif /* LARGE_SMB_OFF_T */ } if (is_locked(fsp,(uint32)SVAL(inbuf,smb_pid),(SMB_BIG_UINT)numtowrite,(SMB_BIG_UINT)startpos, WRITE_LOCK)) { END_PROFILE(SMBwriteX); return ERROR_DOS(ERRDOS,ERRlock); } /* X/Open SMB protocol says that, unlike SMBwrite if the length is zero then NO truncation is done, just a write of zero. To truncate a file, use SMBwrite. */ if(numtowrite == 0) { nwritten = 0; } else { if (schedule_aio_write_and_X(conn, inbuf, outbuf, length, bufsize, fsp,data,startpos,numtowrite)) { END_PROFILE(SMBwriteX); return -1; } nwritten = write_file(fsp,data,startpos,numtowrite); } if(((nwritten == 0) && (numtowrite != 0))||(nwritten < 0)) { END_PROFILE(SMBwriteX); return(UNIXERROR(ERRHRD,ERRdiskfull)); } SSVAL(outbuf,smb_vwv2,nwritten); if (large_writeX) SSVAL(outbuf,smb_vwv4,(nwritten>>16)&1); if (nwritten < (ssize_t)numtowrite) { SCVAL(outbuf,smb_rcls,ERRHRD); SSVAL(outbuf,smb_err,ERRdiskfull); } DEBUG(3,("writeX fnum=%d num=%d wrote=%d\n", fsp->fnum, (int)numtowrite, (int)nwritten)); sync_file(conn, fsp, write_through); END_PROFILE(SMBwriteX); return chain_reply(inbuf,outbuf,length,bufsize); } /**************************************************************************** Reply to a lseek. ****************************************************************************/ int reply_lseek(connection_struct *conn, char *inbuf,char *outbuf, int size, int dum_buffsize) { SMB_OFF_T startpos; SMB_OFF_T res= -1; int mode,umode; int outsize = 0; files_struct *fsp = file_fsp(inbuf,smb_vwv0); START_PROFILE(SMBlseek); CHECK_FSP(fsp,conn); flush_write_cache(fsp, SEEK_FLUSH); mode = SVAL(inbuf,smb_vwv1) & 3; /* NB. This doesn't use IVAL_TO_SMB_OFF_T as startpos can be signed in this case. */ startpos = (SMB_OFF_T)IVALS(inbuf,smb_vwv2); switch (mode) { case 0: umode = SEEK_SET; res = startpos; break; case 1: umode = SEEK_CUR; res = fsp->fh->pos + startpos; break; case 2: umode = SEEK_END; break; default: umode = SEEK_SET; res = startpos; break; } if (umode == SEEK_END) { if((res = SMB_VFS_LSEEK(fsp,fsp->fh->fd,startpos,umode)) == -1) { if(errno == EINVAL) { SMB_OFF_T current_pos = startpos; SMB_STRUCT_STAT sbuf; if(SMB_VFS_FSTAT(fsp,fsp->fh->fd, &sbuf) == -1) { END_PROFILE(SMBlseek); return(UNIXERROR(ERRDOS,ERRnoaccess)); } current_pos += sbuf.st_size; if(current_pos < 0) res = SMB_VFS_LSEEK(fsp,fsp->fh->fd,0,SEEK_SET); } } if(res == -1) { END_PROFILE(SMBlseek); return(UNIXERROR(ERRDOS,ERRnoaccess)); } } fsp->fh->pos = res; outsize = set_message(outbuf,2,0,True); SIVAL(outbuf,smb_vwv0,res); DEBUG(3,("lseek fnum=%d ofs=%.0f newpos = %.0f mode=%d\n", fsp->fnum, (double)startpos, (double)res, mode)); END_PROFILE(SMBlseek); return(outsize); } /**************************************************************************** Reply to a flush. ****************************************************************************/ int reply_flush(connection_struct *conn, char *inbuf,char *outbuf, int size, int dum_buffsize) { int outsize = set_message(outbuf,0,0,False); uint16 fnum = SVAL(inbuf,smb_vwv0); files_struct *fsp = file_fsp(inbuf,smb_vwv0); START_PROFILE(SMBflush); if (fnum != 0xFFFF) CHECK_FSP(fsp,conn); if (!fsp) { file_sync_all(conn); } else { sync_file(conn,fsp, True); } DEBUG(3,("flush\n")); END_PROFILE(SMBflush); return(outsize); } /**************************************************************************** Reply to a exit. conn POINTER CAN BE NULL HERE ! ****************************************************************************/ int reply_exit(connection_struct *conn, char *inbuf,char *outbuf, int dum_size, int dum_buffsize) { int outsize; START_PROFILE(SMBexit); file_close_pid(SVAL(inbuf,smb_pid),SVAL(inbuf,smb_uid)); outsize = set_message(outbuf,0,0,False); DEBUG(3,("exit\n")); END_PROFILE(SMBexit); return(outsize); } /**************************************************************************** Reply to a close - has to deal with closing a directory opened by NT SMB's. ****************************************************************************/ int reply_close(connection_struct *conn, char *inbuf,char *outbuf, int size, int dum_buffsize) { NTSTATUS status = NT_STATUS_OK; int outsize = 0; files_struct *fsp = NULL; START_PROFILE(SMBclose); outsize = set_message(outbuf,0,0,False); /* If it's an IPC, pass off to the pipe handler. */ if (IS_IPC(conn)) { END_PROFILE(SMBclose); return reply_pipe_close(conn, inbuf,outbuf); } fsp = file_fsp(inbuf,smb_vwv0); /* * We can only use CHECK_FSP if we know it's not a directory. */ if(!fsp || (fsp->conn != conn) || (fsp->vuid != current_user.vuid)) { END_PROFILE(SMBclose); return ERROR_DOS(ERRDOS,ERRbadfid); } if(fsp->is_directory) { /* * Special case - close NT SMB directory handle. */ DEBUG(3,("close directory fnum=%d\n", fsp->fnum)); status = close_file(fsp,NORMAL_CLOSE); } else { /* * Close ordinary file. */ DEBUG(3,("close fd=%d fnum=%d (numopen=%d)\n", fsp->fh->fd, fsp->fnum, conn->num_files_open)); /* * Take care of any time sent in the close. */ fsp_set_pending_modtime(fsp, convert_time_t_to_timespec(srv_make_unix_date3(inbuf+smb_vwv1))); /* * close_file() returns the unix errno if an error * was detected on close - normally this is due to * a disk full error. If not then it was probably an I/O error. */ status = close_file(fsp,NORMAL_CLOSE); } if(!NT_STATUS_IS_OK(status)) { END_PROFILE(SMBclose); return ERROR_NT(status); } END_PROFILE(SMBclose); return(outsize); } /**************************************************************************** Reply to a writeclose (Core+ protocol). ****************************************************************************/ int reply_writeclose(connection_struct *conn, char *inbuf,char *outbuf, int size, int dum_buffsize) { size_t numtowrite; ssize_t nwritten = -1; int outsize = 0; NTSTATUS close_status = NT_STATUS_OK; SMB_OFF_T startpos; char *data; struct timespec mtime; files_struct *fsp = file_fsp(inbuf,smb_vwv0); START_PROFILE(SMBwriteclose); CHECK_FSP(fsp,conn); if (!CHECK_WRITE(fsp)) { return(ERROR_DOS(ERRDOS,ERRbadaccess)); } numtowrite = SVAL(inbuf,smb_vwv1); startpos = IVAL_TO_SMB_OFF_T(inbuf,smb_vwv2); mtime = convert_time_t_to_timespec(srv_make_unix_date3(inbuf+smb_vwv4)); data = smb_buf(inbuf) + 1; if (numtowrite && is_locked(fsp,(uint32)SVAL(inbuf,smb_pid),(SMB_BIG_UINT)numtowrite,(SMB_BIG_UINT)startpos, WRITE_LOCK)) { END_PROFILE(SMBwriteclose); return ERROR_DOS(ERRDOS,ERRlock); } nwritten = write_file(fsp,data,startpos,numtowrite); set_filetime(conn, fsp->fsp_name, mtime); /* * More insanity. W2K only closes the file if writelen > 0. * JRA. */ if (numtowrite) { DEBUG(3,("reply_writeclose: zero length write doesn't close file %s\n", fsp->fsp_name )); close_status = close_file(fsp,NORMAL_CLOSE); } DEBUG(3,("writeclose fnum=%d num=%d wrote=%d (numopen=%d)\n", fsp->fnum, (int)numtowrite, (int)nwritten, conn->num_files_open)); if(((nwritten == 0) && (numtowrite != 0))||(nwritten < 0)) { END_PROFILE(SMBwriteclose); return(UNIXERROR(ERRHRD,ERRdiskfull)); } if(!NT_STATUS_IS_OK(close_status)) { END_PROFILE(SMBwriteclose); return ERROR_NT(close_status); } outsize = set_message(outbuf,1,0,True); SSVAL(outbuf,smb_vwv0,nwritten); END_PROFILE(SMBwriteclose); return(outsize); } #undef DBGC_CLASS #define DBGC_CLASS DBGC_LOCKING /**************************************************************************** Reply to a lock. ****************************************************************************/ int reply_lock(connection_struct *conn, char *inbuf,char *outbuf, int length, int dum_buffsize) { int outsize = set_message(outbuf,0,0,False); SMB_BIG_UINT count,offset; NTSTATUS status; files_struct *fsp = file_fsp(inbuf,smb_vwv0); struct byte_range_lock *br_lck = NULL; START_PROFILE(SMBlock); CHECK_FSP(fsp,conn); release_level_2_oplocks_on_change(fsp); count = (SMB_BIG_UINT)IVAL(inbuf,smb_vwv1); offset = (SMB_BIG_UINT)IVAL(inbuf,smb_vwv3); DEBUG(3,("lock fd=%d fnum=%d offset=%.0f count=%.0f\n", fsp->fh->fd, fsp->fnum, (double)offset, (double)count)); br_lck = do_lock(fsp, (uint32)SVAL(inbuf,smb_pid), count, offset, WRITE_LOCK, WINDOWS_LOCK, False, /* Non-blocking lock. */ &status, NULL); TALLOC_FREE(br_lck); if (NT_STATUS_V(status)) { END_PROFILE(SMBlock); return ERROR_NT(status); } END_PROFILE(SMBlock); return(outsize); } /**************************************************************************** Reply to a unlock. ****************************************************************************/ int reply_unlock(connection_struct *conn, char *inbuf,char *outbuf, int size, int dum_buffsize) { int outsize = set_message(outbuf,0,0,False); SMB_BIG_UINT count,offset; NTSTATUS status; files_struct *fsp = file_fsp(inbuf,smb_vwv0); START_PROFILE(SMBunlock); CHECK_FSP(fsp,conn); count = (SMB_BIG_UINT)IVAL(inbuf,smb_vwv1); offset = (SMB_BIG_UINT)IVAL(inbuf,smb_vwv3); status = do_unlock(fsp, (uint32)SVAL(inbuf,smb_pid), count, offset, WINDOWS_LOCK); if (NT_STATUS_V(status)) { END_PROFILE(SMBunlock); return ERROR_NT(status); } DEBUG( 3, ( "unlock fd=%d fnum=%d offset=%.0f count=%.0f\n", fsp->fh->fd, fsp->fnum, (double)offset, (double)count ) ); END_PROFILE(SMBunlock); return(outsize); } #undef DBGC_CLASS #define DBGC_CLASS DBGC_ALL /**************************************************************************** Reply to a tdis. conn POINTER CAN BE NULL HERE ! ****************************************************************************/ int reply_tdis(connection_struct *conn, char *inbuf,char *outbuf, int dum_size, int dum_buffsize) { int outsize = set_message(outbuf,0,0,False); uint16 vuid; START_PROFILE(SMBtdis); vuid = SVAL(inbuf,smb_uid); if (!conn) { DEBUG(4,("Invalid connection in tdis\n")); END_PROFILE(SMBtdis); return ERROR_DOS(ERRSRV,ERRinvnid); } conn->used = False; close_cnum(conn,vuid); END_PROFILE(SMBtdis); return outsize; } /**************************************************************************** Reply to a echo. conn POINTER CAN BE NULL HERE ! ****************************************************************************/ int reply_echo(connection_struct *conn, char *inbuf,char *outbuf, int dum_size, int dum_buffsize) { int smb_reverb = SVAL(inbuf,smb_vwv0); int seq_num; unsigned int data_len = smb_buflen(inbuf); int outsize = set_message(outbuf,1,data_len,True); START_PROFILE(SMBecho); if (data_len > BUFFER_SIZE) { DEBUG(0,("reply_echo: data_len too large.\n")); END_PROFILE(SMBecho); return -1; } /* copy any incoming data back out */ if (data_len > 0) memcpy(smb_buf(outbuf),smb_buf(inbuf),data_len); if (smb_reverb > 100) { DEBUG(0,("large reverb (%d)?? Setting to 100\n",smb_reverb)); smb_reverb = 100; } for (seq_num =1 ; seq_num <= smb_reverb ; seq_num++) { SSVAL(outbuf,smb_vwv0,seq_num); smb_setlen(outbuf,outsize - 4); show_msg(outbuf); if (!send_smb(smbd_server_fd(),outbuf)) exit_server_cleanly("reply_echo: send_smb failed."); } DEBUG(3,("echo %d times\n", smb_reverb)); smb_echo_count++; END_PROFILE(SMBecho); return -1; } /**************************************************************************** Reply to a printopen. ****************************************************************************/ int reply_printopen(connection_struct *conn, char *inbuf,char *outbuf, int dum_size, int dum_buffsize) { int outsize = 0; files_struct *fsp; NTSTATUS status; START_PROFILE(SMBsplopen); if (!CAN_PRINT(conn)) { END_PROFILE(SMBsplopen); return ERROR_DOS(ERRDOS,ERRnoaccess); } /* Open for exclusive use, write only. */ status = print_fsp_open(conn, NULL, &fsp); if (!NT_STATUS_IS_OK(status)) { END_PROFILE(SMBsplopen); return(ERROR_NT(status)); } outsize = set_message(outbuf,1,0,True); SSVAL(outbuf,smb_vwv0,fsp->fnum); DEBUG(3,("openprint fd=%d fnum=%d\n", fsp->fh->fd, fsp->fnum)); END_PROFILE(SMBsplopen); return(outsize); } /**************************************************************************** Reply to a printclose. ****************************************************************************/ int reply_printclose(connection_struct *conn, char *inbuf,char *outbuf, int dum_size, int dum_buffsize) { int outsize = set_message(outbuf,0,0,False); files_struct *fsp = file_fsp(inbuf,smb_vwv0); NTSTATUS status; START_PROFILE(SMBsplclose); CHECK_FSP(fsp,conn); if (!CAN_PRINT(conn)) { END_PROFILE(SMBsplclose); return ERROR_NT(NT_STATUS_DOS(ERRSRV, ERRerror)); } DEBUG(3,("printclose fd=%d fnum=%d\n", fsp->fh->fd,fsp->fnum)); status = close_file(fsp,NORMAL_CLOSE); if(!NT_STATUS_IS_OK(status)) { END_PROFILE(SMBsplclose); return ERROR_NT(status); } END_PROFILE(SMBsplclose); return(outsize); } /**************************************************************************** Reply to a printqueue. ****************************************************************************/ int reply_printqueue(connection_struct *conn, char *inbuf,char *outbuf, int dum_size, int dum_buffsize) { int outsize = set_message(outbuf,2,3,True); int max_count = SVAL(inbuf,smb_vwv0); int start_index = SVAL(inbuf,smb_vwv1); START_PROFILE(SMBsplretq); /* we used to allow the client to get the cnum wrong, but that is really quite gross and only worked when there was only one printer - I think we should now only accept it if they get it right (tridge) */ if (!CAN_PRINT(conn)) { END_PROFILE(SMBsplretq); return ERROR_DOS(ERRDOS,ERRnoaccess); } SSVAL(outbuf,smb_vwv0,0); SSVAL(outbuf,smb_vwv1,0); SCVAL(smb_buf(outbuf),0,1); SSVAL(smb_buf(outbuf),1,0); DEBUG(3,("printqueue start_index=%d max_count=%d\n", start_index, max_count)); { print_queue_struct *queue = NULL; print_status_struct status; char *p = smb_buf(outbuf) + 3; int count = print_queue_status(SNUM(conn), &queue, &status); int num_to_get = ABS(max_count); int first = (max_count>0?start_index:start_index+max_count+1); int i; if (first >= count) num_to_get = 0; else num_to_get = MIN(num_to_get,count-first); for (i=first;i<first+num_to_get;i++) { srv_put_dos_date2(p,0,queue[i].time); SCVAL(p,4,(queue[i].status==LPQ_PRINTING?2:3)); SSVAL(p,5, queue[i].job); SIVAL(p,7,queue[i].size); SCVAL(p,11,0); srvstr_push(outbuf, p+12, queue[i].fs_user, 16, STR_ASCII); p += 28; } if (count > 0) { outsize = set_message(outbuf,2,28*count+3,False); SSVAL(outbuf,smb_vwv0,count); SSVAL(outbuf,smb_vwv1,(max_count>0?first+count:first-1)); SCVAL(smb_buf(outbuf),0,1); SSVAL(smb_buf(outbuf),1,28*count); } SAFE_FREE(queue); DEBUG(3,("%d entries returned in queue\n",count)); } END_PROFILE(SMBsplretq); return(outsize); } /**************************************************************************** Reply to a printwrite. ****************************************************************************/ int reply_printwrite(connection_struct *conn, char *inbuf,char *outbuf, int dum_size, int dum_buffsize) { int numtowrite; int outsize = set_message(outbuf,0,0,False); char *data; files_struct *fsp = file_fsp(inbuf,smb_vwv0); START_PROFILE(SMBsplwr); if (!CAN_PRINT(conn)) { END_PROFILE(SMBsplwr); return ERROR_DOS(ERRDOS,ERRnoaccess); } CHECK_FSP(fsp,conn); if (!CHECK_WRITE(fsp)) { return(ERROR_DOS(ERRDOS,ERRbadaccess)); } numtowrite = SVAL(smb_buf(inbuf),1); data = smb_buf(inbuf) + 3; if (write_file(fsp,data,-1,numtowrite) != numtowrite) { END_PROFILE(SMBsplwr); return(UNIXERROR(ERRHRD,ERRdiskfull)); } DEBUG( 3, ( "printwrite fnum=%d num=%d\n", fsp->fnum, numtowrite ) ); END_PROFILE(SMBsplwr); return(outsize); } /**************************************************************************** Reply to a mkdir. ****************************************************************************/ int reply_mkdir(connection_struct *conn, char *inbuf,char *outbuf, int dum_size, int dum_buffsize) { pstring directory; int outsize; NTSTATUS status; SMB_STRUCT_STAT sbuf; START_PROFILE(SMBmkdir); srvstr_get_path(inbuf, directory, smb_buf(inbuf) + 1, sizeof(directory), 0, STR_TERMINATE, &status); if (!NT_STATUS_IS_OK(status)) { END_PROFILE(SMBmkdir); return ERROR_NT(status); } status = resolve_dfspath(conn, SVAL(inbuf,smb_flg2) & FLAGS2_DFS_PATHNAMES, directory); if (!NT_STATUS_IS_OK(status)) { END_PROFILE(SMBmkdir); if (NT_STATUS_EQUAL(status,NT_STATUS_PATH_NOT_COVERED)) { return ERROR_BOTH(NT_STATUS_PATH_NOT_COVERED, ERRSRV, ERRbadpath); } return ERROR_NT(status); } status = unix_convert(conn, directory, False, NULL, &sbuf); if (!NT_STATUS_IS_OK(status)) { END_PROFILE(SMBmkdir); return ERROR_NT(status); } status = check_name(conn, directory); if (!NT_STATUS_IS_OK(status)) { END_PROFILE(SMBmkdir); return ERROR_NT(status); } status = create_directory(conn, directory); DEBUG(5, ("create_directory returned %s\n", nt_errstr(status))); if (!NT_STATUS_IS_OK(status)) { if (!use_nt_status() && NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_COLLISION)) { /* * Yes, in the DOS error code case we get a * ERRDOS:ERRnoaccess here. See BASE-SAMBA3ERROR * samba4 torture test. */ status = NT_STATUS_DOS(ERRDOS, ERRnoaccess); } END_PROFILE(SMBmkdir); return ERROR_NT(status); } outsize = set_message(outbuf,0,0,False); DEBUG( 3, ( "mkdir %s ret=%d\n", directory, outsize ) ); END_PROFILE(SMBmkdir); return(outsize); } /**************************************************************************** Static function used by reply_rmdir to delete an entire directory tree recursively. Return True on ok, False on fail. ****************************************************************************/ static BOOL recursive_rmdir(connection_struct *conn, char *directory) { const char *dname = NULL; BOOL ret = True; long offset = 0; struct smb_Dir *dir_hnd = OpenDir(conn, directory, NULL, 0); if(dir_hnd == NULL) return False; while((dname = ReadDirName(dir_hnd, &offset))) { pstring fullname; SMB_STRUCT_STAT st; if((strcmp(dname, ".") == 0) || (strcmp(dname, "..")==0)) continue; if (!is_visible_file(conn, directory, dname, &st, False)) continue; /* Construct the full name. */ if(strlen(directory) + strlen(dname) + 1 >= sizeof(fullname)) { errno = ENOMEM; ret = False; break; } pstrcpy(fullname, directory); pstrcat(fullname, "/"); pstrcat(fullname, dname); if(SMB_VFS_LSTAT(conn,fullname, &st) != 0) { ret = False; break; } if(st.st_mode & S_IFDIR) { if(!recursive_rmdir(conn, fullname)) { ret = False; break; } if(SMB_VFS_RMDIR(conn,fullname) != 0) { ret = False; break; } } else if(SMB_VFS_UNLINK(conn,fullname) != 0) { ret = False; break; } } CloseDir(dir_hnd); return ret; } /**************************************************************************** The internals of the rmdir code - called elsewhere. ****************************************************************************/ NTSTATUS rmdir_internals(connection_struct *conn, const char *directory) { int ret; SMB_STRUCT_STAT st; /* Might be a symlink. */ if(SMB_VFS_LSTAT(conn, directory, &st) != 0) { return map_nt_error_from_unix(errno); } if (S_ISLNK(st.st_mode)) { /* Is what it points to a directory ? */ if(SMB_VFS_STAT(conn, directory, &st) != 0) { return map_nt_error_from_unix(errno); } if (!(S_ISDIR(st.st_mode))) { return NT_STATUS_NOT_A_DIRECTORY; } ret = SMB_VFS_UNLINK(conn,directory); } else { ret = SMB_VFS_RMDIR(conn,directory); } if (ret == 0) { notify_fname(conn, NOTIFY_ACTION_REMOVED, FILE_NOTIFY_CHANGE_DIR_NAME, directory); return NT_STATUS_OK; } if(((errno == ENOTEMPTY)||(errno == EEXIST)) && lp_veto_files(SNUM(conn))) { /* * Check to see if the only thing in this directory are * vetoed files/directories. If so then delete them and * retry. If we fail to delete any of them (and we *don't* * do a recursive delete) then fail the rmdir. */ const char *dname; long dirpos = 0; struct smb_Dir *dir_hnd = OpenDir(conn, directory, NULL, 0); if(dir_hnd == NULL) { errno = ENOTEMPTY; goto err; } while ((dname = ReadDirName(dir_hnd,&dirpos))) { if((strcmp(dname, ".") == 0) || (strcmp(dname, "..")==0)) continue; if (!is_visible_file(conn, directory, dname, &st, False)) continue; if(!IS_VETO_PATH(conn, dname)) { CloseDir(dir_hnd); errno = ENOTEMPTY; goto err; } } /* We only have veto files/directories. Recursive delete. */ RewindDir(dir_hnd,&dirpos); while ((dname = ReadDirName(dir_hnd,&dirpos))) { pstring fullname; if((strcmp(dname, ".") == 0) || (strcmp(dname, "..")==0)) continue; if (!is_visible_file(conn, directory, dname, &st, False)) continue; /* Construct the full name. */ if(strlen(directory) + strlen(dname) + 1 >= sizeof(fullname)) { errno = ENOMEM; break; } pstrcpy(fullname, directory); pstrcat(fullname, "/"); pstrcat(fullname, dname); if(SMB_VFS_LSTAT(conn,fullname, &st) != 0) break; if(st.st_mode & S_IFDIR) { if(lp_recursive_veto_delete(SNUM(conn))) { if(!recursive_rmdir(conn, fullname)) break; } if(SMB_VFS_RMDIR(conn,fullname) != 0) break; } else if(SMB_VFS_UNLINK(conn,fullname) != 0) break; } CloseDir(dir_hnd); /* Retry the rmdir */ ret = SMB_VFS_RMDIR(conn,directory); } err: if (ret != 0) { DEBUG(3,("rmdir_internals: couldn't remove directory %s : " "%s\n", directory,strerror(errno))); return map_nt_error_from_unix(errno); } notify_fname(conn, NOTIFY_ACTION_REMOVED, FILE_NOTIFY_CHANGE_DIR_NAME, directory); return NT_STATUS_OK; } /**************************************************************************** Reply to a rmdir. ****************************************************************************/ int reply_rmdir(connection_struct *conn, char *inbuf,char *outbuf, int dum_size, int dum_buffsize) { pstring directory; int outsize = 0; SMB_STRUCT_STAT sbuf; NTSTATUS status; START_PROFILE(SMBrmdir); srvstr_get_path(inbuf, directory, smb_buf(inbuf) + 1, sizeof(directory), 0, STR_TERMINATE, &status); if (!NT_STATUS_IS_OK(status)) { END_PROFILE(SMBrmdir); return ERROR_NT(status); } status = resolve_dfspath(conn, SVAL(inbuf,smb_flg2) & FLAGS2_DFS_PATHNAMES, directory); if (!NT_STATUS_IS_OK(status)) { END_PROFILE(SMBrmdir); if (NT_STATUS_EQUAL(status,NT_STATUS_PATH_NOT_COVERED)) { return ERROR_BOTH(NT_STATUS_PATH_NOT_COVERED, ERRSRV, ERRbadpath); } return ERROR_NT(status); } status = unix_convert(conn, directory, False, NULL, &sbuf); if (!NT_STATUS_IS_OK(status)) { END_PROFILE(SMBrmdir); return ERROR_NT(status); } status = check_name(conn, directory); if (!NT_STATUS_IS_OK(status)) { END_PROFILE(SMBrmdir); return ERROR_NT(status); } dptr_closepath(directory,SVAL(inbuf,smb_pid)); status = rmdir_internals(conn, directory); if (!NT_STATUS_IS_OK(status)) { END_PROFILE(SMBrmdir); return ERROR_NT(status); } outsize = set_message(outbuf,0,0,False); DEBUG( 3, ( "rmdir %s\n", directory ) ); END_PROFILE(SMBrmdir); return(outsize); } /******************************************************************* Resolve wildcards in a filename rename. Note that name is in UNIX charset and thus potentially can be more than fstring buffer (255 bytes) especially in default UTF-8 case. Therefore, we use pstring inside and all calls should ensure that name2 is at least pstring-long (they do already) ********************************************************************/ static BOOL resolve_wildcards(const char *name1, char *name2) { pstring root1,root2; pstring ext1,ext2; char *p,*p2, *pname1, *pname2; int available_space, actual_space; pname1 = strrchr_m(name1,'/'); pname2 = strrchr_m(name2,'/'); if (!pname1 || !pname2) return(False); pstrcpy(root1,pname1); pstrcpy(root2,pname2); p = strrchr_m(root1,'.'); if (p) { *p = 0; pstrcpy(ext1,p+1); } else { pstrcpy(ext1,""); } p = strrchr_m(root2,'.'); if (p) { *p = 0; pstrcpy(ext2,p+1); } else { pstrcpy(ext2,""); } p = root1; p2 = root2; while (*p2) { if (*p2 == '?') { *p2 = *p; p2++; } else if (*p2 == '*') { pstrcpy(p2, p); break; } else { p2++; } if (*p) p++; } p = ext1; p2 = ext2; while (*p2) { if (*p2 == '?') { *p2 = *p; p2++; } else if (*p2 == '*') { pstrcpy(p2, p); break; } else { p2++; } if (*p) p++; } available_space = sizeof(pstring) - PTR_DIFF(pname2, name2); if (ext2[0]) { actual_space = snprintf(pname2, available_space - 1, "%s.%s", root2, ext2); if (actual_space >= available_space - 1) { DEBUG(1,("resolve_wildcards: can't fit resolved name into specified buffer (overrun by %d bytes)\n", actual_space - available_space)); } } else { pstrcpy_base(pname2, root2, name2); } return(True); } /**************************************************************************** Ensure open files have their names updated. Updated to notify other smbd's asynchronously. ****************************************************************************/ static void rename_open_files(connection_struct *conn, struct share_mode_lock *lck, SMB_DEV_T dev, SMB_INO_T inode, const char *newname) { files_struct *fsp; BOOL did_rename = False; for(fsp = file_find_di_first(dev, inode); fsp; fsp = file_find_di_next(fsp)) { /* fsp_name is a relative path under the fsp. To change this for other sharepaths we need to manipulate relative paths. */ /* TODO - create the absolute path and manipulate the newname relative to the sharepath. */ if (fsp->conn != conn) { continue; } DEBUG(10,("rename_open_files: renaming file fnum %d (dev = %x, inode = %.0f) from %s -> %s\n", fsp->fnum, (unsigned int)fsp->dev, (double)fsp->inode, fsp->fsp_name, newname )); string_set(&fsp->fsp_name, newname); did_rename = True; } if (!did_rename) { DEBUG(10,("rename_open_files: no open files on dev %x, inode %.0f for %s\n", (unsigned int)dev, (double)inode, newname )); } /* Send messages to all smbd's (not ourself) that the name has changed. */ rename_share_filename(lck, conn->connectpath, newname); } /**************************************************************************** We need to check if the source path is a parent directory of the destination (ie. a rename of /foo/bar/baz -> /foo/bar/baz/bibble/bobble. If so we must refuse the rename with a sharing violation. Under UNIX the above call can *succeed* if /foo/bar/baz is a symlink to another area in the share. We probably need to check that the client is a Windows one before disallowing this as a UNIX client (one with UNIX extensions) can know the source is a symlink and make this decision intelligently. Found by an excellent bug report from <[email protected]>. ****************************************************************************/ static BOOL rename_path_prefix_equal(const char *src, const char *dest) { const char *psrc = src; const char *pdst = dest; size_t slen; if (psrc[0] == '.' && psrc[1] == '/') { psrc += 2; } if (pdst[0] == '.' && pdst[1] == '/') { pdst += 2; } if ((slen = strlen(psrc)) > strlen(pdst)) { return False; } return ((memcmp(psrc, pdst, slen) == 0) && pdst[slen] == '/'); } /**************************************************************************** Rename an open file - given an fsp. ****************************************************************************/ NTSTATUS rename_internals_fsp(connection_struct *conn, files_struct *fsp, pstring newname, uint32 attrs, BOOL replace_if_exists) { SMB_STRUCT_STAT sbuf; pstring newname_last_component; NTSTATUS status = NT_STATUS_OK; BOOL dest_exists; struct share_mode_lock *lck = NULL; ZERO_STRUCT(sbuf); status = unix_convert(conn, newname, False, newname_last_component, &sbuf); /* If an error we expect this to be NT_STATUS_OBJECT_PATH_NOT_FOUND */ if (!NT_STATUS_IS_OK(status) && !NT_STATUS_EQUAL(NT_STATUS_OBJECT_PATH_NOT_FOUND, status)) { return status; } status = check_name(conn, newname); if (!NT_STATUS_IS_OK(status)) { return status; } /* Ensure newname contains a '/' */ if(strrchr_m(newname,'/') == 0) { pstring tmpstr; pstrcpy(tmpstr, "./"); pstrcat(tmpstr, newname); pstrcpy(newname, tmpstr); } /* * Check for special case with case preserving and not * case sensitive. If the old last component differs from the original * last component only by case, then we should allow * the rename (user is trying to change the case of the * filename). */ if((conn->case_sensitive == False) && (conn->case_preserve == True) && strequal(newname, fsp->fsp_name)) { char *p; pstring newname_modified_last_component; /* * Get the last component of the modified name. * Note that we guarantee that newname contains a '/' * character above. */ p = strrchr_m(newname,'/'); pstrcpy(newname_modified_last_component,p+1); if(strcsequal(newname_modified_last_component, newname_last_component) == False) { /* * Replace the modified last component with * the original. */ pstrcpy(p+1, newname_last_component); } } /* * If the src and dest names are identical - including case, * don't do the rename, just return success. */ if (strcsequal(fsp->fsp_name, newname)) { DEBUG(3,("rename_internals_fsp: identical names in rename %s - returning success\n", newname)); return NT_STATUS_OK; } dest_exists = vfs_object_exist(conn,newname,NULL); if(!replace_if_exists && dest_exists) { DEBUG(3,("rename_internals_fsp: dest exists doing rename %s -> %s\n", fsp->fsp_name,newname)); return NT_STATUS_OBJECT_NAME_COLLISION; } /* Ensure we have a valid stat struct for the source. */ if (fsp->fh->fd != -1) { if (SMB_VFS_FSTAT(fsp,fsp->fh->fd,&sbuf) == -1) { return map_nt_error_from_unix(errno); } } else { if (SMB_VFS_STAT(conn,fsp->fsp_name,&sbuf) == -1) { return map_nt_error_from_unix(errno); } } status = can_rename(conn,fsp->fsp_name,attrs,&sbuf,True); if (!NT_STATUS_IS_OK(status)) { DEBUG(3,("rename_internals_fsp: Error %s rename %s -> %s\n", nt_errstr(status), fsp->fsp_name,newname)); if (NT_STATUS_EQUAL(status,NT_STATUS_SHARING_VIOLATION)) status = NT_STATUS_ACCESS_DENIED; return status; } if (rename_path_prefix_equal(fsp->fsp_name, newname)) { return NT_STATUS_ACCESS_DENIED; } lck = get_share_mode_lock(NULL, fsp->dev, fsp->inode, NULL, NULL); if(SMB_VFS_RENAME(conn,fsp->fsp_name, newname) == 0) { uint32 create_options = fsp->fh->private_options; DEBUG(3,("rename_internals_fsp: succeeded doing rename on %s -> %s\n", fsp->fsp_name,newname)); rename_open_files(conn, lck, fsp->dev, fsp->inode, newname); /* * A rename acts as a new file create w.r.t. allowing an initial delete * on close, probably because in Windows there is a new handle to the * new file. If initial delete on close was requested but not * originally set, we need to set it here. This is probably not 100% correct, * but will work for the CIFSFS client which in non-posix mode * depends on these semantics. JRA. */ set_allow_initial_delete_on_close(lck, fsp, True); if (create_options & FILE_DELETE_ON_CLOSE) { status = can_set_delete_on_close(fsp, True, 0); if (NT_STATUS_IS_OK(status)) { /* Note that here we set the *inital* delete on close flag, * not the regular one. The magic gets handled in close. */ fsp->initial_delete_on_close = True; } } TALLOC_FREE(lck); return NT_STATUS_OK; } TALLOC_FREE(lck); if (errno == ENOTDIR || errno == EISDIR) { status = NT_STATUS_OBJECT_NAME_COLLISION; } else { status = map_nt_error_from_unix(errno); } DEBUG(3,("rename_internals_fsp: Error %s rename %s -> %s\n", nt_errstr(status), fsp->fsp_name,newname)); return status; } /* * Do the notify calls from a rename */ static void notify_rename(connection_struct *conn, BOOL is_dir, const char *oldpath, const char *newpath) { char *olddir, *newdir; const char *oldname, *newname; uint32 mask; mask = is_dir ? FILE_NOTIFY_CHANGE_DIR_NAME : FILE_NOTIFY_CHANGE_FILE_NAME; if (!parent_dirname_talloc(NULL, oldpath, &olddir, &oldname) || !parent_dirname_talloc(NULL, newpath, &newdir, &newname)) { TALLOC_FREE(olddir); return; } if (strcmp(olddir, newdir) == 0) { notify_fname(conn, NOTIFY_ACTION_OLD_NAME, mask, oldpath); notify_fname(conn, NOTIFY_ACTION_NEW_NAME, mask, newpath); } else { notify_fname(conn, NOTIFY_ACTION_REMOVED, mask, oldpath); notify_fname(conn, NOTIFY_ACTION_ADDED, mask, newpath); } TALLOC_FREE(olddir); TALLOC_FREE(newdir); /* this is a strange one. w2k3 gives an additional event for CHANGE_ATTRIBUTES and CHANGE_CREATION on the new file when renaming files, but not directories */ if (!is_dir) { notify_fname(conn, NOTIFY_ACTION_MODIFIED, FILE_NOTIFY_CHANGE_ATTRIBUTES |FILE_NOTIFY_CHANGE_CREATION, newpath); } } /**************************************************************************** The guts of the rename command, split out so it may be called by the NT SMB code. ****************************************************************************/ NTSTATUS rename_internals(connection_struct *conn, pstring name, pstring newname, uint32 attrs, BOOL replace_if_exists, BOOL src_has_wild, BOOL dest_has_wild) { pstring directory; pstring mask; pstring last_component_src; pstring last_component_dest; char *p; int count=0; NTSTATUS status = NT_STATUS_OK; SMB_STRUCT_STAT sbuf1, sbuf2; struct share_mode_lock *lck = NULL; struct smb_Dir *dir_hnd = NULL; const char *dname; long offset = 0; pstring destname; *directory = *mask = 0; ZERO_STRUCT(sbuf1); ZERO_STRUCT(sbuf2); status = unix_convert(conn, name, src_has_wild, last_component_src, &sbuf1); if (!NT_STATUS_IS_OK(status)) { return status; } status = unix_convert(conn, newname, dest_has_wild, last_component_dest, &sbuf2); if (!NT_STATUS_IS_OK(status)) { return status; } /* * Split the old name into directory and last component * strings. Note that unix_convert may have stripped off a * leading ./ from both name and newname if the rename is * at the root of the share. We need to make sure either both * name and newname contain a / character or neither of them do * as this is checked in resolve_wildcards(). */ p = strrchr_m(name,'/'); if (!p) { pstrcpy(directory,"."); pstrcpy(mask,name); } else { *p = 0; pstrcpy(directory,name); pstrcpy(mask,p+1); *p = '/'; /* Replace needed for exceptional test below. */ } /* * We should only check the mangled cache * here if unix_convert failed. This means * that the path in 'mask' doesn't exist * on the file system and so we need to look * for a possible mangle. This patch from * Tine Smukavec <[email protected]>. */ if (!VALID_STAT(sbuf1) && mangle_is_mangled(mask, conn->params)) { mangle_check_cache( mask, sizeof(pstring)-1, conn->params ); } if (!src_has_wild) { /* * No wildcards - just process the one file. */ BOOL is_short_name = mangle_is_8_3(name, True, conn->params); /* Add a terminating '/' to the directory name. */ pstrcat(directory,"/"); pstrcat(directory,mask); /* Ensure newname contains a '/' also */ if(strrchr_m(newname,'/') == 0) { pstring tmpstr; pstrcpy(tmpstr, "./"); pstrcat(tmpstr, newname); pstrcpy(newname, tmpstr); } DEBUG(3, ("rename_internals: case_sensitive = %d, " "case_preserve = %d, short case preserve = %d, " "directory = %s, newname = %s, " "last_component_dest = %s, is_8_3 = %d\n", conn->case_sensitive, conn->case_preserve, conn->short_case_preserve, directory, newname, last_component_dest, is_short_name)); /* Ensure the source name is valid for us to access. */ status = check_name(conn, directory); if (!NT_STATUS_IS_OK(status)) { return status; } /* The dest name still may have wildcards. */ if (dest_has_wild) { if (!resolve_wildcards(directory,newname)) { DEBUG(6, ("rename_internals: resolve_wildcards %s %s failed\n", directory,newname)); return NT_STATUS_NO_MEMORY; } } /* * Check for special case with case preserving and not * case sensitive, if directory and newname are identical, * and the old last component differs from the original * last component only by case, then we should allow * the rename (user is trying to change the case of the * filename). */ if((conn->case_sensitive == False) && (((conn->case_preserve == True) && (is_short_name == False)) || ((conn->short_case_preserve == True) && (is_short_name == True))) && strcsequal(directory, newname)) { pstring modified_last_component; /* * Get the last component of the modified name. * Note that we guarantee that newname contains a '/' * character above. */ p = strrchr_m(newname,'/'); pstrcpy(modified_last_component,p+1); if(strcsequal(modified_last_component, last_component_dest) == False) { /* * Replace the modified last component with * the original. */ pstrcpy(p+1, last_component_dest); } } /* Ensure the dest name is valid for us to access. */ status = check_name(conn, newname); if (!NT_STATUS_IS_OK(status)) { return status; } /* * The source object must exist. */ if (!vfs_object_exist(conn, directory, &sbuf1)) { DEBUG(3, ("rename_internals: source doesn't exist " "doing rename %s -> %s\n", directory,newname)); if (errno == ENOTDIR || errno == EISDIR || errno == ENOENT) { /* * Must return different errors depending on * whether the parent directory existed or * not. */ p = strrchr_m(directory, '/'); if (!p) return NT_STATUS_OBJECT_NAME_NOT_FOUND; *p = '\0'; if (vfs_object_exist(conn, directory, NULL)) return NT_STATUS_OBJECT_NAME_NOT_FOUND; return NT_STATUS_OBJECT_PATH_NOT_FOUND; } status = map_nt_error_from_unix(errno); DEBUG(3, ("rename_internals: Error %s rename %s -> " "%s\n", nt_errstr(status), directory, newname)); return status; } status = can_rename(conn,directory,attrs,&sbuf1,False); if (!NT_STATUS_IS_OK(status)) { DEBUG(3,("rename_internals: Error %s rename %s -> " "%s\n", nt_errstr(status), directory, newname)); return status; } /* * If the src and dest names are identical - including case, * don't do the rename, just return success. */ if (strcsequal(directory, newname)) { rename_open_files(conn, NULL, sbuf1.st_dev, sbuf1.st_ino, newname); DEBUG(3, ("rename_internals: identical names in " "rename %s - returning success\n", directory)); return NT_STATUS_OK; } if(!replace_if_exists && vfs_object_exist(conn,newname,NULL)) { DEBUG(3,("rename_internals: dest exists doing " "rename %s -> %s\n", directory, newname)); return NT_STATUS_OBJECT_NAME_COLLISION; } if (rename_path_prefix_equal(directory, newname)) { return NT_STATUS_SHARING_VIOLATION; } lck = get_share_mode_lock(NULL, sbuf1.st_dev, sbuf1.st_ino, NULL, NULL); if(SMB_VFS_RENAME(conn,directory, newname) == 0) { DEBUG(3,("rename_internals: succeeded doing rename " "on %s -> %s\n", directory, newname)); rename_open_files(conn, lck, sbuf1.st_dev, sbuf1.st_ino, newname); TALLOC_FREE(lck); notify_rename(conn, S_ISDIR(sbuf1.st_mode), directory, newname); return NT_STATUS_OK; } TALLOC_FREE(lck); if (errno == ENOTDIR || errno == EISDIR) { status = NT_STATUS_OBJECT_NAME_COLLISION; } else { status = map_nt_error_from_unix(errno); } DEBUG(3,("rename_internals: Error %s rename %s -> %s\n", nt_errstr(status), directory,newname)); return status; } /* * Wildcards - process each file that matches. */ if (strequal(mask,"????????.???")) { pstrcpy(mask,"*"); } status = check_name(conn, directory); if (!NT_STATUS_IS_OK(status)) { return status; } dir_hnd = OpenDir(conn, directory, mask, attrs); if (dir_hnd == NULL) { return map_nt_error_from_unix(errno); } status = NT_STATUS_NO_SUCH_FILE; /* * Was status = NT_STATUS_OBJECT_NAME_NOT_FOUND; * - gentest fix. JRA */ while ((dname = ReadDirName(dir_hnd, &offset))) { pstring fname; BOOL sysdir_entry = False; pstrcpy(fname,dname); /* Quick check for "." and ".." */ if (fname[0] == '.') { if (!fname[1] || (fname[1] == '.' && !fname[2])) { if (attrs & aDIR) { sysdir_entry = True; } else { continue; } } } if (!is_visible_file(conn, directory, dname, &sbuf1, False)) { continue; } if(!mask_match(fname, mask, conn->case_sensitive)) { continue; } if (sysdir_entry) { status = NT_STATUS_OBJECT_NAME_INVALID; break; } status = NT_STATUS_ACCESS_DENIED; slprintf(fname, sizeof(fname)-1, "%s/%s", directory, dname); /* Ensure the source name is valid for us to access. */ status = check_name(conn, fname); if (!NT_STATUS_IS_OK(status)) { return status; } if (!vfs_object_exist(conn, fname, &sbuf1)) { status = NT_STATUS_OBJECT_NAME_NOT_FOUND; DEBUG(6, ("rename %s failed. Error %s\n", fname, nt_errstr(status))); continue; } status = can_rename(conn,fname,attrs,&sbuf1,False); if (!NT_STATUS_IS_OK(status)) { DEBUG(6, ("rename %s refused\n", fname)); continue; } pstrcpy(destname,newname); if (!resolve_wildcards(fname,destname)) { DEBUG(6, ("resolve_wildcards %s %s failed\n", fname, destname)); continue; } /* Ensure the dest name is valid for us to access. */ status = check_name(conn, destname); if (!NT_STATUS_IS_OK(status)) { return status; } if (strcsequal(fname,destname)) { rename_open_files(conn, NULL, sbuf1.st_dev, sbuf1.st_ino, newname); DEBUG(3,("rename_internals: identical names " "in wildcard rename %s - success\n", fname)); count++; status = NT_STATUS_OK; continue; } if (!replace_if_exists && vfs_file_exist(conn,destname, NULL)) { DEBUG(6,("file_exist %s\n", destname)); status = NT_STATUS_OBJECT_NAME_COLLISION; continue; } if (rename_path_prefix_equal(fname, destname)) { return NT_STATUS_SHARING_VIOLATION; } lck = get_share_mode_lock(NULL, sbuf1.st_dev, sbuf1.st_ino, NULL, NULL); if (!SMB_VFS_RENAME(conn,fname,destname)) { rename_open_files(conn, lck, sbuf1.st_dev, sbuf1.st_ino, newname); count++; status = NT_STATUS_OK; } TALLOC_FREE(lck); DEBUG(3,("rename_internals: doing rename on %s -> " "%s\n",fname,destname)); } CloseDir(dir_hnd); if (count == 0 && NT_STATUS_IS_OK(status)) { status = map_nt_error_from_unix(errno); } return status; } /**************************************************************************** Reply to a mv. ****************************************************************************/ int reply_mv(connection_struct *conn, char *inbuf,char *outbuf, int dum_size, int dum_buffsize) { int outsize = 0; pstring name; pstring newname; char *p; uint32 attrs = SVAL(inbuf,smb_vwv0); NTSTATUS status; BOOL src_has_wcard = False; BOOL dest_has_wcard = False; START_PROFILE(SMBmv); p = smb_buf(inbuf) + 1; p += srvstr_get_path_wcard(inbuf, name, p, sizeof(name), 0, STR_TERMINATE, &status, &src_has_wcard); if (!NT_STATUS_IS_OK(status)) { END_PROFILE(SMBmv); return ERROR_NT(status); } p++; p += srvstr_get_path_wcard(inbuf, newname, p, sizeof(newname), 0, STR_TERMINATE, &status, &dest_has_wcard); if (!NT_STATUS_IS_OK(status)) { END_PROFILE(SMBmv); return ERROR_NT(status); } status = resolve_dfspath_wcard(conn, SVAL(inbuf,smb_flg2) & FLAGS2_DFS_PATHNAMES, name, &src_has_wcard); if (!NT_STATUS_IS_OK(status)) { END_PROFILE(SMBmv); if (NT_STATUS_EQUAL(status,NT_STATUS_PATH_NOT_COVERED)) { return ERROR_BOTH(NT_STATUS_PATH_NOT_COVERED, ERRSRV, ERRbadpath); } return ERROR_NT(status); } status = resolve_dfspath_wcard(conn, SVAL(inbuf,smb_flg2) & FLAGS2_DFS_PATHNAMES, newname, &dest_has_wcard); if (!NT_STATUS_IS_OK(status)) { END_PROFILE(SMBmv); if (NT_STATUS_EQUAL(status,NT_STATUS_PATH_NOT_COVERED)) { return ERROR_BOTH(NT_STATUS_PATH_NOT_COVERED, ERRSRV, ERRbadpath); } return ERROR_NT(status); } DEBUG(3,("reply_mv : %s -> %s\n",name,newname)); status = rename_internals(conn, name, newname, attrs, False, src_has_wcard, dest_has_wcard); if (!NT_STATUS_IS_OK(status)) { END_PROFILE(SMBmv); if (open_was_deferred(SVAL(inbuf,smb_mid))) { /* We have re-scheduled this call. */ return -1; } return ERROR_NT(status); } outsize = set_message(outbuf,0,0,False); END_PROFILE(SMBmv); return(outsize); } /******************************************************************* Copy a file as part of a reply_copy. ******************************************************************/ /* * TODO: check error codes on all callers */ NTSTATUS copy_file(connection_struct *conn, char *src, char *dest1, int ofun, int count, BOOL target_is_directory) { SMB_STRUCT_STAT src_sbuf, sbuf2; SMB_OFF_T ret=-1; files_struct *fsp1,*fsp2; pstring dest; uint32 dosattrs; uint32 new_create_disposition; NTSTATUS status; pstrcpy(dest,dest1); if (target_is_directory) { char *p = strrchr_m(src,'/'); if (p) { p++; } else { p = src; } pstrcat(dest,"/"); pstrcat(dest,p); } if (!vfs_file_exist(conn,src,&src_sbuf)) { return NT_STATUS_OBJECT_NAME_NOT_FOUND; } if (!target_is_directory && count) { new_create_disposition = FILE_OPEN; } else { if (!map_open_params_to_ntcreate(dest1,0,ofun, NULL, NULL, &new_create_disposition, NULL)) { return NT_STATUS_INVALID_PARAMETER; } } status = open_file_ntcreate(conn,src,&src_sbuf, FILE_GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE, FILE_OPEN, 0, FILE_ATTRIBUTE_NORMAL, INTERNAL_OPEN_ONLY, NULL, &fsp1); if (!NT_STATUS_IS_OK(status)) { return status; } dosattrs = dos_mode(conn, src, &src_sbuf); if (SMB_VFS_STAT(conn,dest,&sbuf2) == -1) { ZERO_STRUCTP(&sbuf2); } status = open_file_ntcreate(conn,dest,&sbuf2, FILE_GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, new_create_disposition, 0, dosattrs, INTERNAL_OPEN_ONLY, NULL, &fsp2); if (!NT_STATUS_IS_OK(status)) { close_file(fsp1,ERROR_CLOSE); return status; } if ((ofun&3) == 1) { if(SMB_VFS_LSEEK(fsp2,fsp2->fh->fd,0,SEEK_END) == -1) { DEBUG(0,("copy_file: error - vfs lseek returned error %s\n", strerror(errno) )); /* * Stop the copy from occurring. */ ret = -1; src_sbuf.st_size = 0; } } if (src_sbuf.st_size) { ret = vfs_transfer_file(fsp1, fsp2, src_sbuf.st_size); } close_file(fsp1,NORMAL_CLOSE); /* Ensure the modtime is set correctly on the destination file. */ fsp_set_pending_modtime( fsp2, get_mtimespec(&src_sbuf)); /* * As we are opening fsp1 read-only we only expect * an error on close on fsp2 if we are out of space. * Thus we don't look at the error return from the * close of fsp1. */ status = close_file(fsp2,NORMAL_CLOSE); if (!NT_STATUS_IS_OK(status)) { return status; } if (ret != (SMB_OFF_T)src_sbuf.st_size) { return NT_STATUS_DISK_FULL; } return NT_STATUS_OK; } /**************************************************************************** Reply to a file copy. ****************************************************************************/ int reply_copy(connection_struct *conn, char *inbuf,char *outbuf, int dum_size, int dum_buffsize) { int outsize = 0; pstring name; pstring directory; pstring mask,newname; char *p; int count=0; int error = ERRnoaccess; int err = 0; int tid2 = SVAL(inbuf,smb_vwv0); int ofun = SVAL(inbuf,smb_vwv1); int flags = SVAL(inbuf,smb_vwv2); BOOL target_is_directory=False; BOOL source_has_wild = False; BOOL dest_has_wild = False; SMB_STRUCT_STAT sbuf1, sbuf2; NTSTATUS status; START_PROFILE(SMBcopy); *directory = *mask = 0; p = smb_buf(inbuf); p += srvstr_get_path_wcard(inbuf, name, p, sizeof(name), 0, STR_TERMINATE, &status, &source_has_wild); if (!NT_STATUS_IS_OK(status)) { END_PROFILE(SMBcopy); return ERROR_NT(status); } p += srvstr_get_path_wcard(inbuf, newname, p, sizeof(newname), 0, STR_TERMINATE, &status, &dest_has_wild); if (!NT_STATUS_IS_OK(status)) { END_PROFILE(SMBcopy); return ERROR_NT(status); } DEBUG(3,("reply_copy : %s -> %s\n",name,newname)); if (tid2 != conn->cnum) { /* can't currently handle inter share copies XXXX */ DEBUG(3,("Rejecting inter-share copy\n")); END_PROFILE(SMBcopy); return ERROR_DOS(ERRSRV,ERRinvdevice); } status = resolve_dfspath_wcard(conn, SVAL(inbuf,smb_flg2) & FLAGS2_DFS_PATHNAMES, name, &source_has_wild); if (!NT_STATUS_IS_OK(status)) { END_PROFILE(SMBcopy); if (NT_STATUS_EQUAL(status,NT_STATUS_PATH_NOT_COVERED)) { return ERROR_BOTH(NT_STATUS_PATH_NOT_COVERED, ERRSRV, ERRbadpath); } return ERROR_NT(status); } status = resolve_dfspath_wcard(conn, SVAL(inbuf,smb_flg2) & FLAGS2_DFS_PATHNAMES, newname, &dest_has_wild); if (!NT_STATUS_IS_OK(status)) { END_PROFILE(SMBcopy); if (NT_STATUS_EQUAL(status,NT_STATUS_PATH_NOT_COVERED)) { return ERROR_BOTH(NT_STATUS_PATH_NOT_COVERED, ERRSRV, ERRbadpath); } return ERROR_NT(status); } status = unix_convert(conn, name, source_has_wild, NULL, &sbuf1); if (!NT_STATUS_IS_OK(status)) { END_PROFILE(SMBcopy); return ERROR_NT(status); } status = unix_convert(conn, newname, dest_has_wild, NULL, &sbuf2); if (!NT_STATUS_IS_OK(status)) { END_PROFILE(SMBcopy); return ERROR_NT(status); } target_is_directory = VALID_STAT_OF_DIR(sbuf2); if ((flags&1) && target_is_directory) { END_PROFILE(SMBcopy); return ERROR_DOS(ERRDOS,ERRbadfile); } if ((flags&2) && !target_is_directory) { END_PROFILE(SMBcopy); return ERROR_DOS(ERRDOS,ERRbadpath); } if ((flags&(1<<5)) && VALID_STAT_OF_DIR(sbuf1)) { /* wants a tree copy! XXXX */ DEBUG(3,("Rejecting tree copy\n")); END_PROFILE(SMBcopy); return ERROR_DOS(ERRSRV,ERRerror); } p = strrchr_m(name,'/'); if (!p) { pstrcpy(directory,"./"); pstrcpy(mask,name); } else { *p = 0; pstrcpy(directory,name); pstrcpy(mask,p+1); } /* * We should only check the mangled cache * here if unix_convert failed. This means * that the path in 'mask' doesn't exist * on the file system and so we need to look * for a possible mangle. This patch from * Tine Smukavec <[email protected]>. */ if (!VALID_STAT(sbuf1) && mangle_is_mangled(mask, conn->params)) { mangle_check_cache( mask, sizeof(pstring)-1, conn->params ); } if (!source_has_wild) { pstrcat(directory,"/"); pstrcat(directory,mask); if (dest_has_wild) { if (!resolve_wildcards(directory,newname)) { END_PROFILE(SMBcopy); return ERROR_NT(NT_STATUS_NO_MEMORY); } } status = check_name(conn, directory); if (!NT_STATUS_IS_OK(status)) { return ERROR_NT(status); } status = check_name(conn, newname); if (!NT_STATUS_IS_OK(status)) { return ERROR_NT(status); } status = copy_file(conn,directory,newname,ofun, count,target_is_directory); if(!NT_STATUS_IS_OK(status)) { END_PROFILE(SMBcopy); return ERROR_NT(status); } else { count++; } } else { struct smb_Dir *dir_hnd = NULL; const char *dname; long offset = 0; pstring destname; if (strequal(mask,"????????.???")) pstrcpy(mask,"*"); status = check_name(conn, directory); if (!NT_STATUS_IS_OK(status)) { return ERROR_NT(status); } dir_hnd = OpenDir(conn, directory, mask, 0); if (dir_hnd == NULL) { status = map_nt_error_from_unix(errno); return ERROR_NT(status); } error = ERRbadfile; while ((dname = ReadDirName(dir_hnd, &offset))) { pstring fname; pstrcpy(fname,dname); if (!is_visible_file(conn, directory, dname, &sbuf1, False)) { continue; } if(!mask_match(fname, mask, conn->case_sensitive)) { continue; } error = ERRnoaccess; slprintf(fname,sizeof(fname)-1, "%s/%s",directory,dname); pstrcpy(destname,newname); if (!resolve_wildcards(fname,destname)) { continue; } status = check_name(conn, fname); if (!NT_STATUS_IS_OK(status)) { return ERROR_NT(status); } status = check_name(conn, destname); if (!NT_STATUS_IS_OK(status)) { return ERROR_NT(status); } DEBUG(3,("reply_copy : doing copy on %s -> %s\n",fname, destname)); status = copy_file(conn,fname,destname,ofun, count,target_is_directory); if (NT_STATUS_IS_OK(status)) { count++; } } CloseDir(dir_hnd); } if (count == 0) { if(err) { /* Error on close... */ errno = err; END_PROFILE(SMBcopy); return(UNIXERROR(ERRHRD,ERRgeneral)); } END_PROFILE(SMBcopy); return ERROR_DOS(ERRDOS,error); } outsize = set_message(outbuf,1,0,True); SSVAL(outbuf,smb_vwv0,count); END_PROFILE(SMBcopy); return(outsize); } /**************************************************************************** Reply to a setdir. ****************************************************************************/ int reply_setdir(connection_struct *conn, char *inbuf,char *outbuf, int dum_size, int dum_buffsize) { int snum; int outsize = 0; pstring newdir; NTSTATUS status; START_PROFILE(pathworks_setdir); snum = SNUM(conn); if (!CAN_SETDIR(snum)) { END_PROFILE(pathworks_setdir); return ERROR_DOS(ERRDOS,ERRnoaccess); } srvstr_get_path(inbuf, newdir, smb_buf(inbuf) + 1, sizeof(newdir), 0, STR_TERMINATE, &status); if (!NT_STATUS_IS_OK(status)) { END_PROFILE(pathworks_setdir); return ERROR_NT(status); } status = resolve_dfspath(conn, SVAL(inbuf,smb_flg2) & FLAGS2_DFS_PATHNAMES, newdir); if (!NT_STATUS_IS_OK(status)) { END_PROFILE(pathworks_setdir); if (NT_STATUS_EQUAL(status,NT_STATUS_PATH_NOT_COVERED)) { return ERROR_BOTH(NT_STATUS_PATH_NOT_COVERED, ERRSRV, ERRbadpath); } return ERROR_NT(status); } if (strlen(newdir) != 0) { if (!vfs_directory_exist(conn,newdir,NULL)) { END_PROFILE(pathworks_setdir); return ERROR_DOS(ERRDOS,ERRbadpath); } set_conn_connectpath(conn,newdir); } outsize = set_message(outbuf,0,0,False); SCVAL(outbuf,smb_reh,CVAL(inbuf,smb_reh)); DEBUG(3,("setdir %s\n", newdir)); END_PROFILE(pathworks_setdir); return(outsize); } #undef DBGC_CLASS #define DBGC_CLASS DBGC_LOCKING /**************************************************************************** Get a lock pid, dealing with large count requests. ****************************************************************************/ uint32 get_lock_pid( char *data, int data_offset, BOOL large_file_format) { if(!large_file_format) return (uint32)SVAL(data,SMB_LPID_OFFSET(data_offset)); else return (uint32)SVAL(data,SMB_LARGE_LPID_OFFSET(data_offset)); } /**************************************************************************** Get a lock count, dealing with large count requests. ****************************************************************************/ SMB_BIG_UINT get_lock_count( char *data, int data_offset, BOOL large_file_format) { SMB_BIG_UINT count = 0; if(!large_file_format) { count = (SMB_BIG_UINT)IVAL(data,SMB_LKLEN_OFFSET(data_offset)); } else { #if defined(HAVE_LONGLONG) count = (((SMB_BIG_UINT) IVAL(data,SMB_LARGE_LKLEN_OFFSET_HIGH(data_offset))) << 32) | ((SMB_BIG_UINT) IVAL(data,SMB_LARGE_LKLEN_OFFSET_LOW(data_offset))); #else /* HAVE_LONGLONG */ /* * NT4.x seems to be broken in that it sends large file (64 bit) * lockingX calls even if the CAP_LARGE_FILES was *not* * negotiated. For boxes without large unsigned ints truncate the * lock count by dropping the top 32 bits. */ if(IVAL(data,SMB_LARGE_LKLEN_OFFSET_HIGH(data_offset)) != 0) { DEBUG(3,("get_lock_count: truncating lock count (high)0x%x (low)0x%x to just low count.\n", (unsigned int)IVAL(data,SMB_LARGE_LKLEN_OFFSET_HIGH(data_offset)), (unsigned int)IVAL(data,SMB_LARGE_LKLEN_OFFSET_LOW(data_offset)) )); SIVAL(data,SMB_LARGE_LKLEN_OFFSET_HIGH(data_offset),0); } count = (SMB_BIG_UINT)IVAL(data,SMB_LARGE_LKLEN_OFFSET_LOW(data_offset)); #endif /* HAVE_LONGLONG */ } return count; } #if !defined(HAVE_LONGLONG) /**************************************************************************** Pathetically try and map a 64 bit lock offset into 31 bits. I hate Windows :-). ****************************************************************************/ static uint32 map_lock_offset(uint32 high, uint32 low) { unsigned int i; uint32 mask = 0; uint32 highcopy = high; /* * Try and find out how many significant bits there are in high. */ for(i = 0; highcopy; i++) highcopy >>= 1; /* * We use 31 bits not 32 here as POSIX * lock offsets may not be negative. */ mask = (~0) << (31 - i); if(low & mask) return 0; /* Fail. */ high <<= (31 - i); return (high|low); } #endif /* !defined(HAVE_LONGLONG) */ /**************************************************************************** Get a lock offset, dealing with large offset requests. ****************************************************************************/ SMB_BIG_UINT get_lock_offset( char *data, int data_offset, BOOL large_file_format, BOOL *err) { SMB_BIG_UINT offset = 0; *err = False; if(!large_file_format) { offset = (SMB_BIG_UINT)IVAL(data,SMB_LKOFF_OFFSET(data_offset)); } else { #if defined(HAVE_LONGLONG) offset = (((SMB_BIG_UINT) IVAL(data,SMB_LARGE_LKOFF_OFFSET_HIGH(data_offset))) << 32) | ((SMB_BIG_UINT) IVAL(data,SMB_LARGE_LKOFF_OFFSET_LOW(data_offset))); #else /* HAVE_LONGLONG */ /* * NT4.x seems to be broken in that it sends large file (64 bit) * lockingX calls even if the CAP_LARGE_FILES was *not* * negotiated. For boxes without large unsigned ints mangle the * lock offset by mapping the top 32 bits onto the lower 32. */ if(IVAL(data,SMB_LARGE_LKOFF_OFFSET_HIGH(data_offset)) != 0) { uint32 low = IVAL(data,SMB_LARGE_LKOFF_OFFSET_LOW(data_offset)); uint32 high = IVAL(data,SMB_LARGE_LKOFF_OFFSET_HIGH(data_offset)); uint32 new_low = 0; if((new_low = map_lock_offset(high, low)) == 0) { *err = True; return (SMB_BIG_UINT)-1; } DEBUG(3,("get_lock_offset: truncating lock offset (high)0x%x (low)0x%x to offset 0x%x.\n", (unsigned int)high, (unsigned int)low, (unsigned int)new_low )); SIVAL(data,SMB_LARGE_LKOFF_OFFSET_HIGH(data_offset),0); SIVAL(data,SMB_LARGE_LKOFF_OFFSET_LOW(data_offset),new_low); } offset = (SMB_BIG_UINT)IVAL(data,SMB_LARGE_LKOFF_OFFSET_LOW(data_offset)); #endif /* HAVE_LONGLONG */ } return offset; } /**************************************************************************** Reply to a lockingX request. ****************************************************************************/ int reply_lockingX(connection_struct *conn, char *inbuf, char *outbuf, int length, int bufsize) { files_struct *fsp = file_fsp(inbuf,smb_vwv2); unsigned char locktype = CVAL(inbuf,smb_vwv3); unsigned char oplocklevel = CVAL(inbuf,smb_vwv3+1); uint16 num_ulocks = SVAL(inbuf,smb_vwv6); uint16 num_locks = SVAL(inbuf,smb_vwv7); SMB_BIG_UINT count = 0, offset = 0; uint32 lock_pid; int32 lock_timeout = IVAL(inbuf,smb_vwv4); int i; char *data; BOOL large_file_format = (locktype & LOCKING_ANDX_LARGE_FILES)?True:False; BOOL err; NTSTATUS status = NT_STATUS_UNSUCCESSFUL; START_PROFILE(SMBlockingX); CHECK_FSP(fsp,conn); data = smb_buf(inbuf); if (locktype & LOCKING_ANDX_CHANGE_LOCKTYPE) { /* we don't support these - and CANCEL_LOCK makes w2k and XP reboot so I don't really want to be compatible! (tridge) */ return ERROR_NT(NT_STATUS_DOS(ERRDOS, ERRnoatomiclocks)); } /* Check if this is an oplock break on a file we have granted an oplock on. */ if ((locktype & LOCKING_ANDX_OPLOCK_RELEASE)) { /* Client can insist on breaking to none. */ BOOL break_to_none = (oplocklevel == 0); BOOL result; DEBUG(5,("reply_lockingX: oplock break reply (%u) from client " "for fnum = %d\n", (unsigned int)oplocklevel, fsp->fnum )); /* * Make sure we have granted an exclusive or batch oplock on * this file. */ if (fsp->oplock_type == 0) { /* The Samba4 nbench simulator doesn't understand the difference between break to level2 and break to none from level2 - it sends oplock break replies in both cases. Don't keep logging an error message here - just ignore it. JRA. */ DEBUG(5,("reply_lockingX: Error : oplock break from " "client for fnum = %d (oplock=%d) and no " "oplock granted on this file (%s).\n", fsp->fnum, fsp->oplock_type, fsp->fsp_name)); /* if this is a pure oplock break request then don't * send a reply */ if (num_locks == 0 && num_ulocks == 0) { END_PROFILE(SMBlockingX); return -1; } else { END_PROFILE(SMBlockingX); return ERROR_DOS(ERRDOS,ERRlock); } } if ((fsp->sent_oplock_break == BREAK_TO_NONE_SENT) || (break_to_none)) { result = remove_oplock(fsp); } else { result = downgrade_oplock(fsp); } if (!result) { DEBUG(0, ("reply_lockingX: error in removing " "oplock on file %s\n", fsp->fsp_name)); /* Hmmm. Is this panic justified? */ smb_panic("internal tdb error"); } reply_to_oplock_break_requests(fsp); /* if this is a pure oplock break request then don't send a * reply */ if (num_locks == 0 && num_ulocks == 0) { /* Sanity check - ensure a pure oplock break is not a chained request. */ if(CVAL(inbuf,smb_vwv0) != 0xff) DEBUG(0,("reply_lockingX: Error : pure oplock " "break is a chained %d request !\n", (unsigned int)CVAL(inbuf,smb_vwv0) )); END_PROFILE(SMBlockingX); return -1; } } /* * We do this check *after* we have checked this is not a oplock break * response message. JRA. */ release_level_2_oplocks_on_change(fsp); /* Data now points at the beginning of the list of smb_unlkrng structs */ for(i = 0; i < (int)num_ulocks; i++) { lock_pid = get_lock_pid( data, i, large_file_format); count = get_lock_count( data, i, large_file_format); offset = get_lock_offset( data, i, large_file_format, &err); /* * There is no error code marked "stupid client bug".... :-). */ if(err) { END_PROFILE(SMBlockingX); return ERROR_DOS(ERRDOS,ERRnoaccess); } DEBUG(10,("reply_lockingX: unlock start=%.0f, len=%.0f for " "pid %u, file %s\n", (double)offset, (double)count, (unsigned int)lock_pid, fsp->fsp_name )); status = do_unlock(fsp, lock_pid, count, offset, WINDOWS_LOCK); if (NT_STATUS_V(status)) { END_PROFILE(SMBlockingX); return ERROR_NT(status); } } /* Setup the timeout in seconds. */ if (!lp_blocking_locks(SNUM(conn))) { lock_timeout = 0; } /* Now do any requested locks */ data += ((large_file_format ? 20 : 10)*num_ulocks); /* Data now points at the beginning of the list of smb_lkrng structs */ for(i = 0; i < (int)num_locks; i++) { enum brl_type lock_type = ((locktype & LOCKING_ANDX_SHARED_LOCK) ? READ_LOCK:WRITE_LOCK); lock_pid = get_lock_pid( data, i, large_file_format); count = get_lock_count( data, i, large_file_format); offset = get_lock_offset( data, i, large_file_format, &err); /* * There is no error code marked "stupid client bug".... :-). */ if(err) { END_PROFILE(SMBlockingX); return ERROR_DOS(ERRDOS,ERRnoaccess); } DEBUG(10,("reply_lockingX: lock start=%.0f, len=%.0f for pid " "%u, file %s timeout = %d\n", (double)offset, (double)count, (unsigned int)lock_pid, fsp->fsp_name, (int)lock_timeout )); if (locktype & LOCKING_ANDX_CANCEL_LOCK) { if (lp_blocking_locks(SNUM(conn))) { /* Schedule a message to ourselves to remove the blocking lock record and return the right error. */ if (!blocking_lock_cancel(fsp, lock_pid, offset, count, WINDOWS_LOCK, locktype, NT_STATUS_FILE_LOCK_CONFLICT)) { END_PROFILE(SMBlockingX); return ERROR_NT(NT_STATUS_DOS(ERRDOS, ERRcancelviolation)); } } /* Remove a matching pending lock. */ status = do_lock_cancel(fsp, lock_pid, count, offset, WINDOWS_LOCK); } else { BOOL blocking_lock = lock_timeout ? True : False; BOOL defer_lock = False; struct byte_range_lock *br_lck; uint32 block_smbpid; br_lck = do_lock(fsp, lock_pid, count, offset, lock_type, WINDOWS_LOCK, blocking_lock, &status, &block_smbpid); if (br_lck && blocking_lock && ERROR_WAS_LOCK_DENIED(status)) { /* Windows internal resolution for blocking locks seems to be about 200ms... Don't wait for less than that. JRA. */ if (lock_timeout != -1 && lock_timeout < lp_lock_spin_time()) { lock_timeout = lp_lock_spin_time(); } defer_lock = True; } /* This heuristic seems to match W2K3 very well. If a lock sent with timeout of zero would fail with NT_STATUS_FILE_LOCK_CONFLICT it pretends we asked for a timeout of between 150 - 300 milliseconds as far as I can tell. Replacement for do_lock_spin(). JRA. */ if (br_lck && lp_blocking_locks(SNUM(conn)) && !blocking_lock && NT_STATUS_EQUAL((status), NT_STATUS_FILE_LOCK_CONFLICT)) { defer_lock = True; lock_timeout = lp_lock_spin_time(); } if (br_lck && defer_lock) { /* * A blocking lock was requested. Package up * this smb into a queued request and push it * onto the blocking lock queue. */ if(push_blocking_lock_request(br_lck, inbuf, length, fsp, lock_timeout, i, lock_pid, lock_type, WINDOWS_LOCK, offset, count, block_smbpid)) { TALLOC_FREE(br_lck); END_PROFILE(SMBlockingX); return -1; } } TALLOC_FREE(br_lck); } if (NT_STATUS_V(status)) { END_PROFILE(SMBlockingX); return ERROR_NT(status); } } /* If any of the above locks failed, then we must unlock all of the previous locks (X/Open spec). */ if (!(locktype & LOCKING_ANDX_CANCEL_LOCK) && (i != num_locks) && (num_locks != 0)) { /* * Ensure we don't do a remove on the lock that just failed, * as under POSIX rules, if we have a lock already there, we * will delete it (and we shouldn't) ..... */ for(i--; i >= 0; i--) { lock_pid = get_lock_pid( data, i, large_file_format); count = get_lock_count( data, i, large_file_format); offset = get_lock_offset( data, i, large_file_format, &err); /* * There is no error code marked "stupid client * bug".... :-). */ if(err) { END_PROFILE(SMBlockingX); return ERROR_DOS(ERRDOS,ERRnoaccess); } do_unlock(fsp, lock_pid, count, offset, WINDOWS_LOCK); } END_PROFILE(SMBlockingX); return ERROR_NT(status); } set_message(outbuf,2,0,True); DEBUG(3, ("lockingX fnum=%d type=%d num_locks=%d num_ulocks=%d\n", fsp->fnum, (unsigned int)locktype, num_locks, num_ulocks)); END_PROFILE(SMBlockingX); return chain_reply(inbuf,outbuf,length,bufsize); } #undef DBGC_CLASS #define DBGC_CLASS DBGC_ALL /**************************************************************************** Reply to a SMBreadbmpx (read block multiplex) request. ****************************************************************************/ int reply_readbmpx(connection_struct *conn, char *inbuf,char *outbuf,int length,int bufsize) { ssize_t nread = -1; ssize_t total_read; char *data; SMB_OFF_T startpos; int outsize; size_t maxcount; int max_per_packet; size_t tcount; int pad; files_struct *fsp = file_fsp(inbuf,smb_vwv0); START_PROFILE(SMBreadBmpx); /* this function doesn't seem to work - disable by default */ if (!lp_readbmpx()) { END_PROFILE(SMBreadBmpx); return ERROR_DOS(ERRSRV,ERRuseSTD); } outsize = set_message(outbuf,8,0,True); CHECK_FSP(fsp,conn); if (!CHECK_READ(fsp,inbuf)) { return(ERROR_DOS(ERRDOS,ERRbadaccess)); } startpos = IVAL_TO_SMB_OFF_T(inbuf,smb_vwv1); maxcount = SVAL(inbuf,smb_vwv3); data = smb_buf(outbuf); pad = ((long)data)%4; if (pad) pad = 4 - pad; data += pad; max_per_packet = bufsize-(outsize+pad); tcount = maxcount; total_read = 0; if (is_locked(fsp,(uint32)SVAL(inbuf,smb_pid),(SMB_BIG_UINT)maxcount,(SMB_BIG_UINT)startpos, READ_LOCK)) { END_PROFILE(SMBreadBmpx); return ERROR_DOS(ERRDOS,ERRlock); } do { size_t N = MIN(max_per_packet,tcount-total_read); nread = read_file(fsp,data,startpos,N); if (nread <= 0) nread = 0; if (nread < (ssize_t)N) tcount = total_read + nread; set_message(outbuf,8,nread+pad,False); SIVAL(outbuf,smb_vwv0,startpos); SSVAL(outbuf,smb_vwv2,tcount); SSVAL(outbuf,smb_vwv6,nread); SSVAL(outbuf,smb_vwv7,smb_offset(data,outbuf)); show_msg(outbuf); if (!send_smb(smbd_server_fd(),outbuf)) exit_server_cleanly("reply_readbmpx: send_smb failed."); total_read += nread; startpos += nread; } while (total_read < (ssize_t)tcount); END_PROFILE(SMBreadBmpx); return(-1); } /**************************************************************************** Reply to a SMBsetattrE. ****************************************************************************/ int reply_setattrE(connection_struct *conn, char *inbuf,char *outbuf, int size, int dum_buffsize) { struct timespec ts[2]; int outsize = 0; files_struct *fsp = file_fsp(inbuf,smb_vwv0); START_PROFILE(SMBsetattrE); outsize = set_message(outbuf,0,0,False); if(!fsp || (fsp->conn != conn)) { END_PROFILE(SMBsetattrE); return ERROR_DOS(ERRDOS,ERRbadfid); } /* * Convert the DOS times into unix times. Ignore create * time as UNIX can't set this. */ ts[0] = convert_time_t_to_timespec(srv_make_unix_date2(inbuf+smb_vwv3)); /* atime. */ ts[1] = convert_time_t_to_timespec(srv_make_unix_date2(inbuf+smb_vwv5)); /* mtime. */ /* * Patch from Ray Frush <[email protected]> * Sometimes times are sent as zero - ignore them. */ if (null_timespec(ts[0]) && null_timespec(ts[1])) { /* Ignore request */ if( DEBUGLVL( 3 ) ) { dbgtext( "reply_setattrE fnum=%d ", fsp->fnum); dbgtext( "ignoring zero request - not setting timestamps of 0\n" ); } END_PROFILE(SMBsetattrE); return(outsize); } else if (!null_timespec(ts[0]) && null_timespec(ts[1])) { /* set modify time = to access time if modify time was unset */ ts[1] = ts[0]; } /* Set the date on this file */ /* Should we set pending modtime here ? JRA */ if(file_ntimes(conn, fsp->fsp_name, ts)) { END_PROFILE(SMBsetattrE); return ERROR_DOS(ERRDOS,ERRnoaccess); } DEBUG( 3, ( "reply_setattrE fnum=%d actime=%u modtime=%u\n", fsp->fnum, (unsigned int)ts[0].tv_sec, (unsigned int)ts[1].tv_sec)); END_PROFILE(SMBsetattrE); return(outsize); } /* Back from the dead for OS/2..... JRA. */ /**************************************************************************** Reply to a SMBwritebmpx (write block multiplex primary) request. ****************************************************************************/ int reply_writebmpx(connection_struct *conn, char *inbuf,char *outbuf, int size, int dum_buffsize) { size_t numtowrite; ssize_t nwritten = -1; int outsize = 0; SMB_OFF_T startpos; size_t tcount; BOOL write_through; int smb_doff; char *data; files_struct *fsp = file_fsp(inbuf,smb_vwv0); START_PROFILE(SMBwriteBmpx); CHECK_FSP(fsp,conn); if (!CHECK_WRITE(fsp)) { return(ERROR_DOS(ERRDOS,ERRbadaccess)); } if (HAS_CACHED_ERROR(fsp)) { return(CACHED_ERROR(fsp)); } tcount = SVAL(inbuf,smb_vwv1); startpos = IVAL_TO_SMB_OFF_T(inbuf,smb_vwv3); write_through = BITSETW(inbuf+smb_vwv7,0); numtowrite = SVAL(inbuf,smb_vwv10); smb_doff = SVAL(inbuf,smb_vwv11); data = smb_base(inbuf) + smb_doff; /* If this fails we need to send an SMBwriteC response, not an SMBwritebmpx - set this up now so we don't forget */ SCVAL(outbuf,smb_com,SMBwritec); if (is_locked(fsp,(uint32)SVAL(inbuf,smb_pid),(SMB_BIG_UINT)tcount,(SMB_BIG_UINT)startpos,WRITE_LOCK)) { END_PROFILE(SMBwriteBmpx); return(ERROR_DOS(ERRDOS,ERRlock)); } nwritten = write_file(fsp,data,startpos,numtowrite); sync_file(conn, fsp, write_through); if(nwritten < (ssize_t)numtowrite) { END_PROFILE(SMBwriteBmpx); return(UNIXERROR(ERRHRD,ERRdiskfull)); } /* If the maximum to be written to this file is greater than what we just wrote then set up a secondary struct to be attached to this fd, we will use this to cache error messages etc. */ if((ssize_t)tcount > nwritten) { write_bmpx_struct *wbms; if(fsp->wbmpx_ptr != NULL) wbms = fsp->wbmpx_ptr; /* Use an existing struct */ else wbms = SMB_MALLOC_P(write_bmpx_struct); if(!wbms) { DEBUG(0,("Out of memory in reply_readmpx\n")); END_PROFILE(SMBwriteBmpx); return(ERROR_DOS(ERRSRV,ERRnoresource)); } wbms->wr_mode = write_through; wbms->wr_discard = False; /* No errors yet */ wbms->wr_total_written = nwritten; wbms->wr_errclass = 0; wbms->wr_error = 0; fsp->wbmpx_ptr = wbms; } /* We are returning successfully, set the message type back to SMBwritebmpx */ SCVAL(outbuf,smb_com,SMBwriteBmpx); outsize = set_message(outbuf,1,0,True); SSVALS(outbuf,smb_vwv0,-1); /* We don't support smb_remaining */ DEBUG( 3, ( "writebmpx fnum=%d num=%d wrote=%d\n", fsp->fnum, (int)numtowrite, (int)nwritten ) ); if (write_through && tcount==nwritten) { /* We need to send both a primary and a secondary response */ smb_setlen(outbuf,outsize - 4); show_msg(outbuf); if (!send_smb(smbd_server_fd(),outbuf)) exit_server_cleanly("reply_writebmpx: send_smb failed."); /* Now the secondary */ outsize = set_message(outbuf,1,0,True); SCVAL(outbuf,smb_com,SMBwritec); SSVAL(outbuf,smb_vwv0,nwritten); } END_PROFILE(SMBwriteBmpx); return(outsize); } /**************************************************************************** Reply to a SMBwritebs (write block multiplex secondary) request. ****************************************************************************/ int reply_writebs(connection_struct *conn, char *inbuf,char *outbuf, int dum_size, int dum_buffsize) { size_t numtowrite; ssize_t nwritten = -1; int outsize = 0; SMB_OFF_T startpos; size_t tcount; BOOL write_through; int smb_doff; char *data; write_bmpx_struct *wbms; BOOL send_response = False; files_struct *fsp = file_fsp(inbuf,smb_vwv0); START_PROFILE(SMBwriteBs); CHECK_FSP(fsp,conn); if (!CHECK_WRITE(fsp)) { return(ERROR_DOS(ERRDOS,ERRbadaccess)); } tcount = SVAL(inbuf,smb_vwv1); startpos = IVAL_TO_SMB_OFF_T(inbuf,smb_vwv2); numtowrite = SVAL(inbuf,smb_vwv6); smb_doff = SVAL(inbuf,smb_vwv7); data = smb_base(inbuf) + smb_doff; /* We need to send an SMBwriteC response, not an SMBwritebs */ SCVAL(outbuf,smb_com,SMBwritec); /* This fd should have an auxiliary struct attached, check that it does */ wbms = fsp->wbmpx_ptr; if(!wbms) { END_PROFILE(SMBwriteBs); return(-1); } /* If write through is set we can return errors, else we must cache them */ write_through = wbms->wr_mode; /* Check for an earlier error */ if(wbms->wr_discard) { END_PROFILE(SMBwriteBs); return -1; /* Just discard the packet */ } nwritten = write_file(fsp,data,startpos,numtowrite); sync_file(conn, fsp, write_through); if (nwritten < (ssize_t)numtowrite) { if(write_through) { /* We are returning an error - we can delete the aux struct */ if (wbms) free((char *)wbms); fsp->wbmpx_ptr = NULL; END_PROFILE(SMBwriteBs); return(ERROR_DOS(ERRHRD,ERRdiskfull)); } wbms->wr_errclass = ERRHRD; wbms->wr_error = ERRdiskfull; wbms->wr_status = NT_STATUS_DISK_FULL; wbms->wr_discard = True; END_PROFILE(SMBwriteBs); return -1; } /* Increment the total written, if this matches tcount we can discard the auxiliary struct (hurrah !) and return a writeC */ wbms->wr_total_written += nwritten; if(wbms->wr_total_written >= tcount) { if (write_through) { outsize = set_message(outbuf,1,0,True); SSVAL(outbuf,smb_vwv0,wbms->wr_total_written); send_response = True; } free((char *)wbms); fsp->wbmpx_ptr = NULL; } if(send_response) { END_PROFILE(SMBwriteBs); return(outsize); } END_PROFILE(SMBwriteBs); return(-1); } /**************************************************************************** Reply to a SMBgetattrE. ****************************************************************************/ int reply_getattrE(connection_struct *conn, char *inbuf,char *outbuf, int size, int dum_buffsize) { SMB_STRUCT_STAT sbuf; int outsize = 0; int mode; files_struct *fsp = file_fsp(inbuf,smb_vwv0); START_PROFILE(SMBgetattrE); outsize = set_message(outbuf,11,0,True); if(!fsp || (fsp->conn != conn)) { END_PROFILE(SMBgetattrE); return ERROR_DOS(ERRDOS,ERRbadfid); } /* Do an fstat on this file */ if(fsp_stat(fsp, &sbuf)) { END_PROFILE(SMBgetattrE); return(UNIXERROR(ERRDOS,ERRnoaccess)); } mode = dos_mode(conn,fsp->fsp_name,&sbuf); /* * Convert the times into dos times. Set create * date to be last modify date as UNIX doesn't save * this. */ srv_put_dos_date2(outbuf,smb_vwv0,get_create_time(&sbuf,lp_fake_dir_create_times(SNUM(conn)))); srv_put_dos_date2(outbuf,smb_vwv2,sbuf.st_atime); /* Should we check pending modtime here ? JRA */ srv_put_dos_date2(outbuf,smb_vwv4,sbuf.st_mtime); if (mode & aDIR) { SIVAL(outbuf,smb_vwv6,0); SIVAL(outbuf,smb_vwv8,0); } else { uint32 allocation_size = get_allocation_size(conn,fsp, &sbuf); SIVAL(outbuf,smb_vwv6,(uint32)sbuf.st_size); SIVAL(outbuf,smb_vwv8,allocation_size); } SSVAL(outbuf,smb_vwv10, mode); DEBUG( 3, ( "reply_getattrE fnum=%d\n", fsp->fnum)); END_PROFILE(SMBgetattrE); return(outsize); }
rhuitl/uClinux
user/samba/source/smbd/reply.c
C
gpl-2.0
163,384
<?php /** * show the blogs owned by the provided user */ $container_guid = (int) get_input("owner_guid"); $params["filter_context"] = "mine"; $options = array( "type" => "object", "subtype" => "blog", "full_view" => false, ); $current_user = elgg_get_logged_in_user_entity(); if ($container_guid) { // access check for closed groups //group_gatekeeper(); $options["owner_guid"] = $container_guid; $container = get_entity($container_guid); $params["title"] = elgg_echo("blog:title:user_blogs", array($container->name)); elgg_push_breadcrumb($container->name); if ($current_user && ($container_guid == $current_user->getGUID())) { $params["filter_context"] = "mine"; } elseif (elgg_instanceof($container, "group")) { $params["filter"] = false; } else { // do not show button or select a tab when viewing someone else"s posts $params["filter_context"] = "none"; } } elgg_register_title_button(); // show all posts for admin or users looking at their own blogs // show only published posts for other users. $show_only_published = true; if ($current_user) { if (($current_user->getGUID() == $container_guid) || $current_user->isAdmin()) { $show_only_published = false; } } if ($show_only_published) { $options["metadata_name_value_pairs"] = array( "name" => "status", "value" => "published" ); } $list = elgg_list_entities_from_metadata($options); if (!$list) { $params["content"] = elgg_echo("blog:none"); } else { $params["content"] = $list; } $params["sidebar"] = elgg_view("blog/sidebar", array("page" => $page_type)); $body = elgg_view_layout("content", $params); echo elgg_view_page($params["title"], $body);
pscrevs/gcconnex
mod/blog_tools/pages/owner.php
PHP
gpl-2.0
1,661
/******************************************************************************/ /* */ /* X r d A d m i n F i n d . c c */ /* */ /* (c) 2009 by the Board of Trustees of the Leland Stanford, Jr., University */ /* All Rights Reserved */ /* Produced by Andrew Hanushevsky for Stanford University under contract */ /* DE-AC02-76-SFO0515 with the Department of Energy */ /* */ /* This file is part of the XRootD software suite. */ /* */ /* XRootD is free software: you can redistribute it and/or modify it under */ /* the terms of the GNU Lesser General Public License as published by the */ /* Free Software Foundation, either version 3 of the License, or (at your */ /* option) any later version. */ /* */ /* XRootD is distributed in the hope that it will be useful, but WITHOUT */ /* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or */ /* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public */ /* License for more details. */ /* */ /* You should have received a copy of the GNU Lesser General Public License */ /* along with XRootD in a file called COPYING.LESSER (LGPL license) and file */ /* COPYING (GPL license). If not, see <http://www.gnu.org/licenses/>. */ /* */ /* The copyright holder's institutional names and contributor's names may not */ /* be used to endorse or promote products derived from this software without */ /* specific prior written permission of the institution or contributor. */ /******************************************************************************/ #include <stdio.h> #include <string.h> #include <strings.h> #include <time.h> #include <sys/param.h> #include "XrdCks/XrdCksManager.hh" #include "XrdFrc/XrdFrcTrace.hh" #include "XrdFrm/XrdFrmAdmin.hh" #include "XrdFrm/XrdFrmConfig.hh" #include "XrdFrm/XrdFrmFiles.hh" #include "XrdOuc/XrdOucArgs.hh" #include "XrdOuc/XrdOucNSWalk.hh" using namespace XrdFrc; using namespace XrdFrm; /******************************************************************************/ /* F i n d F a i l */ /******************************************************************************/ int XrdFrmAdmin::FindFail(XrdOucArgs &Spec) { XrdOucNSWalk::NSEnt *nP, *fP; XrdOucNSWalk *nsP; char pDir[MAXPATHLEN], *dotP, *dirFN, *lDir = Opt.Args[1]; char *dirP = pDir + Config.xfrFdln; int dirL = sizeof(pDir) - Config.xfrFdln; int opts = XrdOucNSWalk::retFile | (Opt.Recurse ? XrdOucNSWalk::Recurse : 0); int ec, rc = 0, num = 0; // Check if fail files are being relocated // if (Config.xfrFdir) strcpy(pDir, Config.xfrFdir); // Process each directory // do {if (!Config.LocalPath(lDir, dirP, dirL)) continue; nsP = new XrdOucNSWalk(&Say, pDir, 0, opts); while((nP = nsP->Index(ec)) || ec) {while((fP = nP)) {if ((dotP = rindex(fP->File,'.')) && !strcmp(dotP,".fail")) {Msg(fP->Path); num++;} nP = fP->Next; delete fP; } if (ec) rc = 4; } delete nsP; } while((dirFN = Spec.getarg())); // All done // sprintf(pDir, "%d fail file%s found.", num, (num == 1 ? "" : "s")); Msg(pDir); return rc; } /******************************************************************************/ /* F i n d M m a p */ /******************************************************************************/ int XrdFrmAdmin::FindMmap(XrdOucArgs &Spec) { XrdOucXAttr<XrdFrcXAttrMem> memInfo; XrdFrmFileset *sP; XrdFrmFiles *fP; char buff[128], pDir[MAXPATHLEN], *lDir = Opt.Args[1]; int opts = (Opt.Recurse ? XrdFrmFiles::Recursive : 0); int mFlag, ec = 0, rc = 0, num = 0; // Process each directory // do {if (!Config.LocalPath(lDir, pDir, sizeof(pDir))) continue; fP = new XrdFrmFiles(pDir, opts | XrdFrmFiles::NoAutoDel); while((sP = fP->Get(ec))) {if (memInfo.Get(sP->basePath()) >= 0 && (mFlag = memInfo.Attr.Flags)) {const char *Kp = (mFlag&XrdFrcXAttrMem::memKeep ? "-keep ":0); const char *Lk = (mFlag&XrdFrcXAttrMem::memLock ? "-lock ":0); Msg("mmap ", Kp, Lk, sP->basePath()); num++; } delete sP; } if (ec) rc = 4; delete fP; } while((lDir = Spec.getarg())); // All done // sprintf(buff,"%d mmapped file%s found.",num,(num == 1 ? "" : "s")); Msg(buff); return rc; } /******************************************************************************/ /* F i n d N o c s */ /******************************************************************************/ int XrdFrmAdmin::FindNocs(XrdOucArgs &Spec) { XrdFrmFileset *sP; XrdFrmFiles *fP; char buff[128], pDir[MAXPATHLEN], *lDir = Opt.Args[1]; int opts = (Opt.Recurse ? XrdFrmFiles::Recursive : 0); int ec = 0, rc = 0, num = 0; // Check if this is even supported // if (!Config.CksMan) {Emsg("Checksum support has not been configured!"); return 8;} // First get the checksum type // if (!(CksData.Length = Config.CksMan->Size(Opt.Args[1])) || !CksData.Set(Opt.Args[1])) {Emsg(Opt.Args[1], " checksum is not supported."); return 4;} // Now get the actual target // if (!(lDir = Spec.getarg())) {Emsg("Find target not specified."); return 4;} // Process each directory // do {if (!Config.LocalPath(lDir, pDir, sizeof(pDir))) continue; fP = new XrdFrmFiles(pDir, opts | XrdFrmFiles::NoAutoDel); while((sP = fP->Get(ec))) {if ((rc = Config.CksMan->Get(sP->basePath(), CksData)) <= 0) {num++; Msg((rc == -ESTALE ? "Invalid " : "Missing "), CksData.Name, " ",sP->basePath()); } delete sP; } if (ec) rc = 4; delete fP; } while((lDir = Spec.getarg())); // All done // sprintf(buff,"%d file%s found with no chksum.",num,(num == 1 ? "" : "s")); Msg(buff); return rc; } /******************************************************************************/ /* F i n d N o l k */ /******************************************************************************/ int XrdFrmAdmin::FindNolk(XrdOucArgs &Spec) { XrdFrmFileset *sP; XrdFrmFiles *fP; char pDir[MAXPATHLEN], *lDir = Opt.Args[1]; int opts = (Opt.Recurse ? XrdFrmFiles::Recursive : 0); int ec = 0, rc = 0, num = 0; // This mode is not supported in new-style spaces // if (Config.runNew) {Msg("New runmode does not have any lock files!"); return 0;} // Process each directory // do {if (!Config.LocalPath(lDir, pDir, sizeof(pDir))) continue; fP = new XrdFrmFiles(pDir, opts | XrdFrmFiles::NoAutoDel); while((sP = fP->Get(ec))) {if (!(sP->lockFile())) {Msg(sP->basePath()); num++;} // runOld delete sP; } if (ec) rc = 4; delete fP; } while((lDir = Spec.getarg())); // All done // sprintf(pDir,"%d missing lock file%s found.", num, (num == 1 ? "" : "s")); Msg(pDir); return rc; } /******************************************************************************/ /* F i n d P i n s */ /******************************************************************************/ int XrdFrmAdmin::FindPins(XrdOucArgs &Spec) { XrdFrmFileset *sP; XrdFrmFiles *fP; char buff[128], pDir[MAXPATHLEN], *lDir = Opt.Args[1]; int opts = (Opt.Recurse ? XrdFrmFiles::Recursive : 0); int ec = 0, rc = 0, num = 0; // Process each directory // do {if (!Config.LocalPath(lDir, pDir, sizeof(pDir))) continue; fP = new XrdFrmFiles(pDir, opts | XrdFrmFiles::NoAutoDel); while((sP = fP->Get(ec))) {if (sP->pinInfo.Get(sP->basePath()) >= 0 && FindPins(sP)) num++; delete sP; } if (ec) rc = 4; delete fP; } while((lDir = Spec.getarg())); // All done // sprintf(buff,"%d pinned file%s found.",num,(num == 1 ? "" : "s")); Msg(buff); return rc; } /******************************************************************************/ int XrdFrmAdmin::FindPins(XrdFrmFileset *sP) { static const int Week = 7*24*60*60; time_t pinVal; const char *Pfx = "+"; char How[256], Scale; int pinFlag; // If no pif flags are set then no pin value exists // if (!(pinFlag = sP->pinInfo.Attr.Flags)) return 0; // If it's pinned forever, we can blither the message right away // if (pinFlag & XrdFrcXAttrPin::pinPerm) {Msg("pin -k forever ", sP->basePath()); return 1;} // Be optimistic and get the pin time value // pinVal = static_cast<time_t>(sP->pinInfo.Attr.pinTime); *How = 0; // If it's a keep then decide how to format it. If the keep has been exceeed // then just delete the attribute, since it isn't pinned anymore. // if (pinFlag & XrdFrcXAttrPin::pinKeep) {time_t nowT = time(0); if (pinVal <= nowT) {sP->pinInfo.Del(sP->basePath()); return 0;} if ((pinVal - nowT) <= Week) {pinFlag = XrdFrcXAttrPin::pinIdle; pinVal = pinVal - nowT; Pfx = ""; } else { struct tm *lclTime = localtime(&pinVal); sprintf(How, "-k %02d/%02d/%04d", lclTime->tm_mon+1, lclTime->tm_mday, lclTime->tm_year+1900); } } // Check for idle pin or convert keep pin to suedo-idle formatting // if (pinFlag & XrdFrcXAttrPin::pinIdle) { if ( pinVal <= 180) Scale = 's'; else if ((pinVal /= 60) <= 90) Scale = 'm'; else if ((pinVal /= 60) <= 45) Scale = 'h'; else { pinVal /= 24; Scale = 'd';} sprintf(How, "-k %s%d%c", Pfx, static_cast<int>(pinVal), Scale); } else if (!*How) return 0; // Print the result // Msg("pin ", How, " ", sP->basePath()); return 1; } /******************************************************************************/ /* F i n d U n m i */ /******************************************************************************/ int XrdFrmAdmin::FindUnmi(XrdOucArgs &Spec) { static const char *noCPT = (Config.runNew ? "Unmigrated; no copy time: " : "Unmigrated; no lock file: "); XrdFrmFileset *sP; XrdFrmFiles *fP; const char *Why; char buff[128], pDir[MAXPATHLEN], *lDir = Opt.Args[1]; int opts = (Opt.Recurse ? XrdFrmFiles::Recursive : 0)|XrdFrmFiles::GetCpyTim; int ec = 0, rc = 0, num = 0; // Process each directory // do {if (!Config.LocalPath(lDir, pDir, sizeof(pDir))) continue; fP = new XrdFrmFiles(pDir, opts | XrdFrmFiles::NoAutoDel); while((sP = fP->Get(ec))) { if (!(sP->cpyInfo.Attr.cpyTime)) Why = noCPT; else if (static_cast<long long>(sP->baseFile()->Stat.st_mtime) > sP->cpyInfo.Attr.cpyTime) Why="Unmigrated; modified: "; else Why = 0; if (Why) {Msg(Why, sP->basePath()); num++;} delete sP; } if (ec) rc = 4; delete fP; } while((lDir = Spec.getarg())); // All done // sprintf(buff,"%d unmigrated file%s found.",num,(num == 1 ? "" : "s")); Msg(buff); return rc; }
bbockelm/xrootd_old_git
src/XrdFrm/XrdFrmAdminFind.cc
C++
gpl-3.0
12,372
<?php /** * Contains \jamesiarmes\PhpEws\Response\GetUserPhotoResponseMessageType. */ namespace jamesiarmes\PhpEws\Response; /** * Defines the response to a GetUserPhoto request. * * @package php-ews\Response */ class GetUserPhotoResponseMessageType extends ResponseMessageType { /** * Indicates whether a user’s photo has changed. * * @since Exchange 2013 * * @var boolean */ public $HasChanged; /** * Contains the stream of picture data. * * @since Exchange 2013 * * @var string * * @todo Create a base64 class? */ public $PictureData; }
FreePBX/calendar
vendor/php-ews/php-ews/src/Response/GetUserPhotoResponseMessageType.php
PHP
gpl-3.0
637
/* The contents of this file are subject to the license and copyright terms * detailed in the license directory at the root of the source tree (also * available online at http://fedora-commons.org/license/). */ package org.fcrepo.server.errors; /** * Signals that an instance of DisseminationBindingInfo could not be found * or was null. * * @author Ross Wayland */ public class DisseminationBindingInfoNotFoundException extends StorageException { private static final long serialVersionUID = 1L; /** * Creates a DisseminationBindingInfoNotFoundException. * * @param message * An informative message explaining what happened and (possibly) how * to fix it. */ public DisseminationBindingInfoNotFoundException(String message) { super(message); } }
ceskaexpedice/kramerius
shared/common/src/main/java/org/fcrepo/server/errors/DisseminationBindingInfoNotFoundException.java
Java
gpl-3.0
838
"use strict"; var db = require('./database'), async = require('async'), winston = require('winston'), fs = require('fs'), path = require('path'), User = require('./user'), Topics = require('./topics'), Posts = require('./posts'), Categories = require('./categories'), Groups = require('./groups'), Meta = require('./meta'), Plugins = require('./plugins'), Utils = require('../public/src/utils'), Upgrade = {}, minSchemaDate = Date.UTC(2015, 0, 30), // This value gets updated every new MINOR version schemaDate, thisSchemaDate, // IMPORTANT: REMEMBER TO UPDATE VALUE OF latestSchema latestSchema = Date.UTC(2015, 7, 18); Upgrade.check = function(callback) { db.get('schemaDate', function(err, value) { if (err) { return callback(err); } if (!value) { db.set('schemaDate', latestSchema, function(err) { if (err) { return callback(err); } callback(null); }); return; } var schema_ok = parseInt(value, 10) >= latestSchema; callback(!schema_ok ? new Error('schema-out-of-date') : null); }); }; Upgrade.update = function(schemaDate, callback) { db.set('schemaDate', schemaDate, callback); }; Upgrade.upgrade = function(callback) { var updatesMade = false; winston.info('Beginning database schema update'); async.series([ function(next) { // Prepare for upgrade & check to make sure the upgrade is possible db.get('schemaDate', function(err, value) { if(!value) { db.set('schemaDate', latestSchema, function(err) { next(); }); schemaDate = latestSchema; } else { schemaDate = parseInt(value, 10); } if (schemaDate >= minSchemaDate) { next(); } else { next(new Error('upgrade-not-possible')); } }); }, function(next) { thisSchemaDate = Date.UTC(2015, 1, 8); if (schemaDate < thisSchemaDate) { updatesMade = true; winston.info('[2015/02/08] Clearing reset tokens'); db.deleteAll(['reset:expiry', 'reset:uid'], function(err) { if (err) { winston.error('[2015/02/08] Error encountered while Clearing reset tokens'); return next(err); } winston.info('[2015/02/08] Clearing reset tokens done'); Upgrade.update(thisSchemaDate, next); }); } else { winston.info('[2015/02/08] Clearing reset tokens skipped'); next(); } }, function(next) { thisSchemaDate = Date.UTC(2015, 1, 17); if (schemaDate < thisSchemaDate) { updatesMade = true; winston.info('[2015/02/17] renaming home.tpl to categories.tpl'); db.rename('widgets:home.tpl', 'widgets:categories.tpl', function(err) { if (err) { return next(err); } winston.info('[2015/02/17] renaming home.tpl to categories.tpl done'); Upgrade.update(thisSchemaDate, next); }); } else { winston.info('[2015/02/17] renaming home.tpl to categories.tpl skipped'); next(); } }, function(next) { thisSchemaDate = Date.UTC(2015, 1, 23); if (schemaDate < thisSchemaDate) { db.setAdd('plugins:active', 'nodebb-rewards-essentials', function(err) { winston.info('[2015/2/23] Activating NodeBB Essential Rewards'); Plugins.reload(function() { if (err) { next(err); } else { Upgrade.update(thisSchemaDate, next); } }); }); } else { winston.info('[2015/2/23] Activating NodeBB Essential Rewards - skipped'); next(); } }, function(next) { thisSchemaDate = Date.UTC(2015, 1, 24); if (schemaDate < thisSchemaDate) { updatesMade = true; winston.info('[2015/02/24] Upgrading plugins:active to sorted set'); db.getSetMembers('plugins:active', function(err, activePlugins) { if (err) { return next(err); } if (!Array.isArray(activePlugins) || !activePlugins.length) { winston.info('[2015/02/24] Upgrading plugins:active to sorted set done'); Upgrade.update(thisSchemaDate, next); } db.delete('plugins:active', function(err) { if (err) { return next(err); } var order = -1; async.eachSeries(activePlugins, function(plugin, next) { ++order; db.sortedSetAdd('plugins:active', order, plugin, next); }, function(err) { if (err) { return next(err); } winston.info('[2015/02/24] Upgrading plugins:active to sorted set done'); Upgrade.update(thisSchemaDate, next); }); }); }); } else { winston.info('[2015/02/24] Upgrading plugins:active to sorted set skipped'); next(); } }, function(next) { thisSchemaDate = Date.UTC(2015, 1, 24, 1); if (schemaDate < thisSchemaDate) { updatesMade = true; winston.info('[2015/02/24] Upgrading privilege groups to system groups'); var isPrivilegeGroup = /^cid:\d+:privileges:[\w:]+$/; db.getSortedSetRange('groups:createtime', 0, -1, function (err, groupNames) { groupNames = groupNames.filter(function(name) { return isPrivilegeGroup.test(name); }); async.eachLimit(groupNames, 5, function(groupName, next) { db.setObjectField('group:' + groupName, 'system', '1', next); }, function(err) { if (err) { return next(err); } winston.info('[2015/02/24] Upgrading privilege groups to system groups done'); Upgrade.update(thisSchemaDate, next); }); }); } else { winston.info('[2015/02/24] Upgrading privilege groups to system groups skipped'); next(); } }, function(next) { thisSchemaDate = Date.UTC(2015, 1, 25, 6); if (schemaDate < thisSchemaDate) { updatesMade = true; winston.info('[2015/02/25] Upgrading menu items to dynamic navigation system'); require('./navigation/admin').save(require('../install/data/navigation.json'), function(err) { if (err) { return next(err); } winston.info('[2015/02/25] Upgrading menu items to dynamic navigation system done'); Upgrade.update(thisSchemaDate, next); }); } else { winston.info('[2015/02/25] Upgrading menu items to dynamic navigation system skipped'); next(); } }, function(next) { function upgradeHashToSortedSet(hash, callback) { db.getObject(hash, function(err, oldHash) { if (err || !oldHash) { return callback(err); } db.rename(hash, hash + '_old', function(err) { if (err) { return callback(err); } var keys = Object.keys(oldHash); if (!keys.length) { return callback(); } async.each(keys, function(key, next) { db.sortedSetAdd(hash, oldHash[key], key, next); }, callback); }); }); } thisSchemaDate = Date.UTC(2015, 4, 7); if (schemaDate < thisSchemaDate) { updatesMade = true; winston.info('[2015/05/07] Upgrading uid mappings to sorted set'); async.series([ async.apply(upgradeHashToSortedSet, 'email:uid'), async.apply(upgradeHashToSortedSet, 'fullname:uid'), async.apply(upgradeHashToSortedSet, 'username:uid'), async.apply(upgradeHashToSortedSet, 'userslug:uid'), ], function(err) { if (err) { return next(err); } winston.info('[2015/05/07] Upgrading uid mappings to sorted set done'); Upgrade.update(thisSchemaDate, next); }); } else { winston.info('[2015/05/07] Upgrading uid mappings to sorted set skipped'); next(); } }, function(next) { thisSchemaDate = Date.UTC(2015, 4, 8); if (schemaDate < thisSchemaDate) { updatesMade = true; winston.info('[2015/05/08] Fixing emails'); db.getSortedSetRangeWithScores('email:uid', 0, -1, function(err, users) { if (err) { return next(err); } async.eachLimit(users, 100, function(user, next) { var newEmail = user.value.replace(/\uff0E/g, '.'); if (newEmail === user.value) { return process.nextTick(next); } async.series([ async.apply(db.sortedSetRemove, 'email:uid', user.value), async.apply(db.sortedSetAdd, 'email:uid', user.score, newEmail) ], next); }, function(err) { if (err) { return next(err); } winston.info('[2015/05/08] Fixing emails done'); Upgrade.update(thisSchemaDate, next); }); }); } else { winston.info('[2015/05/08] Fixing emails skipped'); next(); } }, function(next) { thisSchemaDate = Date.UTC(2015, 4, 11); if (schemaDate < thisSchemaDate) { updatesMade = true; winston.info('[2015/05/11] Updating widgets to tjs 0.2x'); require('./widgets/admin').get(function(err, data) { async.each(data.areas, function(area, next) { require('./widgets').getArea(area.template, area.location, function(err, widgets) { if (err) { return next(err); } for (var w in widgets) { if (widgets.hasOwnProperty(w)) { widgets[w].data.container = widgets[w].data.container .replace(/\{\{([\s\S]*?)\}\}/g, '{$1}') .replace(/\{([\s\S]*?)\}/g, '{{$1}}'); } } require('./widgets').setArea({ template: area.template, location: area.location, widgets: widgets }, next); }); }, function(err) { if (err) { return next(err); } winston.info('[2015/05/11] Updating widgets to tjs 0.2x done'); Upgrade.update(thisSchemaDate, next); }); }); } else { winston.info('[2015/05/11] Updating widgets to tjs 0.2x skipped'); next(); } }, function(next) { function upgradeSet(set, callback) { db.getSortedSetRangeWithScores(set + ':uid', 0, -1, function(err, userData) { if (err) { return callback(err); } userData = userData.filter(function(user) { return user && user.value; }); async.eachLimit(userData, 500, function(userData, next) { db.sortedSetAdd(set + ':sorted', 0, userData.value.toLowerCase() + ':' + userData.score, next); }, function(err) { callback(err); }); }); } thisSchemaDate = Date.UTC(2015, 4, 20); if (schemaDate < thisSchemaDate) { updatesMade = true; winston.info('[2015/05/20] Adding username:sorted and email:sorted'); async.series([ function(next) { upgradeSet('username', next); }, function(next) { upgradeSet('email', next); } ], function(err) { if (err) { return next(err); } winston.info('[2015/05/20] Added username:sorted and email:sorted'); Upgrade.update(thisSchemaDate, next); }); } else { winston.info('[2015/05/20] Adding username:sorted and email:sorted skipped'); next(); } }, function(next) { thisSchemaDate = Date.UTC(2015, 5, 2); if (schemaDate < thisSchemaDate) { updatesMade = true; winston.info('[2015/06/02] Creating group sorted sets'); db.getSortedSetRange('groups:createtime', 0, -1, function(err, groupNames) { if (err) { return callback(err); } groupNames = groupNames.filter(Boolean); async.eachLimit(groupNames, 500, function(groupName, next) { db.getObjectFields('group:' + groupName, ['hidden', 'system', 'createtime', 'memberCount'], function(err, groupData) { if (err) { return next(err); } if (parseInt(groupData.hidden, 10) === 1 || parseInt(groupData.system, 10) === 1) { return next(); } async.parallel([ async.apply(db.sortedSetAdd, 'groups:visible:createtime', groupData.createtime, groupName), async.apply(db.sortedSetAdd, 'groups:visible:memberCount', groupData.memberCount, groupName), async.apply(db.sortedSetAdd, 'groups:visible:name', 0, groupName.toLowerCase() + ':' + groupName) ], next); }); }, function(err) { if (err) { return next(err); } winston.info('[2015/06/02] Creating group sorted sets done'); Upgrade.update(thisSchemaDate, next); }); }); } else { winston.info('[2015/06/02] Creating group sorted sets skipped'); next(); } }, function(next) { thisSchemaDate = Date.UTC(2015, 6, 3); if (schemaDate < thisSchemaDate) { updatesMade = true; winston.info('[2015/07/03] Enabling default composer plugin'); db.isSortedSetMember('plugins:active', 'nodebb-plugin-composer-default', function(err, active) { if (!active) { Plugins.toggleActive('nodebb-plugin-composer-default', function(err) { if (err) { return next(err); } winston.info('[2015/07/03] Enabling default composer plugin done'); Upgrade.update(thisSchemaDate, next); }); } else { winston.info('[2015/07/03] Enabling default composer plugin done'); Upgrade.update(thisSchemaDate, next); } }); } else { winston.info('[2015/07/03] Enabling default composer plugin skipped'); next(); } }, function(next) { thisSchemaDate = Date.UTC(2015, 7, 18); if (schemaDate < thisSchemaDate) { updatesMade = true; winston.info('[2015/08/18] Creating children category sorted sets'); db.getSortedSetRange('categories:cid', 0, -1, function(err, cids) { if (err) { return next(err); } async.each(cids, function(cid, next) { db.getObjectFields('category:' + cid, ['parentCid', 'order'], function(err, category) { if (err) { return next(err); } if (!category) { return next(); } if (parseInt(category.parentCid, 10)) { db.sortedSetAdd('cid:' + category.parentCid + ':children', parseInt(category.order, 10), cid, next); } else { db.sortedSetAdd('cid:0:children', parseInt(category.order, 10), cid, next); } }); }, function(err) { if (err) { return next(err); } winston.info('[2015/08/18] Creating children category sorted sets done'); Upgrade.update(thisSchemaDate, next); }); }); } else { winston.info('[2015/08/18] Creating children category sorted sets skipped'); next(); } } // Add new schema updates here // IMPORTANT: REMEMBER TO UPDATE VALUE OF latestSchema IN LINE 24!!! ], function(err) { if (!err) { if(updatesMade) { winston.info('[upgrade] Schema update complete!'); } else { winston.info('[upgrade] Schema already up to date!'); } } else { switch(err.message) { case 'upgrade-not-possible': winston.error('[upgrade] NodeBB upgrade could not complete, as your database schema is too far out of date.'); winston.error('[upgrade] Please ensure that you did not skip any minor version upgrades.'); winston.error('[upgrade] (e.g. v0.1.x directly to v0.3.x)'); break; default: winston.error('[upgrade] Errors were encountered while updating the NodeBB schema: ' + err.message); break; } } if (typeof callback === 'function') { callback(err); } else { process.exit(); } }); }; module.exports = Upgrade;
williamluke4/Examenable
src/upgrade.js
JavaScript
gpl-3.0
14,927
using System.Xml.Linq; namespace TailBlazer.Views.Layout { public interface ILayoutConverter { XElement CaptureState(); void Restore(XElement element); } }
mreichardt95/TailBlazer
Source/TailBlazer/Views/Layout/ILayoutConverter.cs
C#
gpl-3.0
184
<?php // $HeadURL: https://joomgallery.org/svn/joomgallery/JG-3/JG/trunk/administrator/components/com_joomgallery/models/fields/joomcategory.php $ // $Id: joomcategory.php 4381 2014-05-04 09:30:44Z erftralle $ /****************************************************************************************\ ** JoomGallery 3 ** ** By: JoomGallery::ProjectTeam ** ** Copyright (C) 2008 - 2013 JoomGallery::ProjectTeam ** ** Based on: JoomGallery 1.0.0 by JoomGallery::ProjectTeam ** ** Released under GNU GPL Public License ** ** License: http://www.gnu.org/copyleft/gpl.html or have a look ** ** at administrator/components/com_joomgallery/LICENSE.TXT ** \****************************************************************************************/ defined('_JEXEC') or die('Direct Access to this location is not allowed.'); /** * Renders a category select box form field * * @package JoomGallery * @since 2.0 */ class JFormFieldJoomCategory extends JFormField { /** * The form field type. * * @var string * @since 2.0 */ protected $type = 'JoomCategory'; /** * Returns the HTML for a category select box form field. * * @return object The category select box form field. * @since 2.0 */ protected function getInput() { require_once JPATH_ADMINISTRATOR.'/components/com_joomgallery/includes/defines.php'; JLoader::register('JoomExtensions', JPATH_ADMINISTRATOR.'/components/'._JOOM_OPTION.'/helpers/extensions.php'); JLoader::register('JoomHelper', JPATH_BASE.'/components/'._JOOM_OPTION.'/helpers/helper.php'); JLoader::register('JoomConfig', JPATH_BASE.'/components/'._JOOM_OPTION.'/helpers/config.php'); JLoader::register('JoomAmbit', JPATH_BASE.'/components/'._JOOM_OPTION.'/helpers/ambit.php'); JTable::addIncludePath(JPATH_ADMINISTRATOR.'/components/'._JOOM_OPTION.'/tables'); JHTML::addIncludePath(JPATH_BASE.'/components/'._JOOM_OPTION.'/helpers/html'); $class = $this->element['class'] ? (string) $this->element['class'] : ''; if($this->element['required'] && $this->element['required'] == true && strpos($class, 'required') === false) { if(!empty($class)) { $class .= ' '; } $class .= 'required'; } if($this->element['validate'] && (string) $this->element['validate'] == 'joompositivenumeric') { $doc = JFactory::getDocument(); // Add a validation script for form validation $js_validate = " jQuery(document).ready(function() { document.formvalidator.setHandler('joompositivenumeric', function(value) { regex=/^[1-9]+[0-9]*$/; return regex.test(value); }) });"; $doc->addScriptDeclaration($js_validate); // Element class needs attribute validate-... if(!empty($class)) { $class .= ' '; } $class .= 'validate-'.(string) $this->element['validate']; // Add some style to make the slect box red bordered when invalid $css = ' select.invalid { border: 1px solid red; }'; $doc->addStyleDeclaration($css); } $attr = ''; $attr .= !empty($class) ? ' class="'.$class.'"' : ''; $attr .= ((string) $this->element['disabled'] == 'true') ? ' disabled="disabled"' : ''; $attr .= $this->element['size'] ? ' size="'.(int) $this->element['size'].'"' : ''; $attr .= $this->element['onchange'] ? ' onchange="'.(string) $this->element['onchange'].'"' : ''; $action = $this->element['action'] ? (string) $this->element['action'] : 'core.create'; $exclude = $this->element['exclude'] ? (int) $this->element['exclude'] : null; $task = $this->element['task'] ? (int) $this->element['task'] : null; $html = JHTML::_('joomselect.categorylist', $this->value, $this->name, $attr, $exclude, '- ', $task, $action, $this->id); return $html; } }
VitUrzh/JoomGallery
administrator/components/com_joomgallery/models/fields/joomcategory.php
PHP
gpl-3.0
4,189
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (c) 2016 Red Hat, Inc. # # This file is part of Ansible # # Ansible 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. # # Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>. # ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: ovirt_templates short_description: Module to manage virtual machine templates in oVirt/RHV version_added: "2.3" author: "Ondra Machacek (@machacekondra)" description: - "Module to manage virtual machine templates in oVirt/RHV." options: name: description: - "Name of the template to manage." id: description: - "ID of the template to be registered." version_added: "2.4" state: description: - "Should the template be present/absent/exported/imported/registered. When C(state) is I(registered) and the unregistered template's name belongs to an already registered in engine template in the same DC then we fail to register the unregistered template." choices: ['present', 'absent', 'exported', 'imported', 'registered'] default: present vm: description: - "Name of the VM, which will be used to create template." description: description: - "Description of the template." cpu_profile: description: - "CPU profile to be set to template." cluster: description: - "Name of the cluster, where template should be created/imported." allow_partial_import: description: - "Boolean indication whether to allow partial registration of a template when C(state) is registered." version_added: "2.4" exclusive: description: - "When C(state) is I(exported) this parameter indicates if the existing templates with the same name should be overwritten." export_domain: description: - "When C(state) is I(exported) or I(imported) this parameter specifies the name of the export storage domain." image_provider: description: - "When C(state) is I(imported) this parameter specifies the name of the image provider to be used." image_disk: description: - "When C(state) is I(imported) and C(image_provider) is used this parameter specifies the name of disk to be imported as template." aliases: ['glance_image_disk_name'] template_image_disk_name: description: - "When C(state) is I(imported) and C(image_provider) is used this parameter specifies the new name for imported disk, if omitted then I(image_disk) name is used by default. This parameter is used only in case of importing disk image from Glance domain." version_added: "2.4" storage_domain: description: - "When C(state) is I(imported) this parameter specifies the name of the destination data storage domain. When C(state) is I(registered) this parameter specifies the name of the data storage domain of the unregistered template." clone_permissions: description: - "If I(True) then the permissions of the VM (only the direct ones, not the inherited ones) will be copied to the created template." - "This parameter is used only when C(state) I(present)." default: False seal: description: - "'Sealing' is an operation that erases all machine-specific configurations from a filesystem: This includes SSH keys, UDEV rules, MAC addresses, system ID, hostname, etc. If I(true) subsequent virtual machines made from this template will avoid configuration inheritance." - "This parameter is used only when C(state) I(present)." default: False version_added: "2.5" extends_documentation_fragment: ovirt ''' EXAMPLES = ''' # Examples don't contain auth parameter for simplicity, # look at ovirt_auth module to see how to reuse authentication: # Create template from vm - ovirt_templates: cluster: Default name: mytemplate vm: rhel7 cpu_profile: Default description: Test # Import template - ovirt_templates: state: imported name: mytemplate export_domain: myexport storage_domain: mystorage cluster: mycluster # Remove template - ovirt_templates: state: absent name: mytemplate # Register template - ovirt_templates: state: registered storage_domain: mystorage cluster: mycluster name: mytemplate # Register template using id - ovirt_templates: state: registered storage_domain: mystorage cluster: mycluster id: 1111-1111-1111-1111 # Register template, allowing partial import - ovirt_templates: state: registered storage_domain: mystorage allow_partial_import: "True" cluster: mycluster id: 1111-1111-1111-1111 # Import image from Glance s a template - ovirt_templates: state: imported name: mytemplate image_disk: "centos7" template_image_disk_name: centos7_from_glance image_provider: "glance_domain" storage_domain: mystorage cluster: mycluster ''' RETURN = ''' id: description: ID of the template which is managed returned: On success if template is found. type: str sample: 7de90f31-222c-436c-a1ca-7e655bd5b60c template: description: "Dictionary of all the template attributes. Template attributes can be found on your oVirt/RHV instance at following url: http://ovirt.github.io/ovirt-engine-api-model/master/#types/template." returned: On success if template is found. type: dict ''' import time import traceback try: import ovirtsdk4.types as otypes except ImportError: pass from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.ovirt import ( BaseModule, check_sdk, create_connection, equal, get_dict_of_struct, get_link_name, get_id_by_name, ovirt_full_argument_spec, search_by_attributes, search_by_name, ) class TemplatesModule(BaseModule): def build_entity(self): return otypes.Template( name=self._module.params['name'], cluster=otypes.Cluster( name=self._module.params['cluster'] ) if self._module.params['cluster'] else None, vm=otypes.Vm( name=self._module.params['vm'] ) if self._module.params['vm'] else None, description=self._module.params['description'], cpu_profile=otypes.CpuProfile( id=search_by_name( self._connection.system_service().cpu_profiles_service(), self._module.params['cpu_profile'], ).id ) if self._module.params['cpu_profile'] else None, ) def update_check(self, entity): return ( equal(self._module.params.get('cluster'), get_link_name(self._connection, entity.cluster)) and equal(self._module.params.get('description'), entity.description) and equal(self._module.params.get('cpu_profile'), get_link_name(self._connection, entity.cpu_profile)) ) def _get_export_domain_service(self): provider_name = self._module.params['export_domain'] or self._module.params['image_provider'] export_sds_service = self._connection.system_service().storage_domains_service() export_sd = search_by_name(export_sds_service, provider_name) if export_sd is None: raise ValueError( "Export storage domain/Image Provider '%s' wasn't found." % provider_name ) return export_sds_service.service(export_sd.id) def post_export_action(self, entity): self._service = self._get_export_domain_service().templates_service() def post_import_action(self, entity): self._service = self._connection.system_service().templates_service() def main(): argument_spec = ovirt_full_argument_spec( state=dict( choices=['present', 'absent', 'exported', 'imported', 'registered'], default='present', ), id=dict(default=None), name=dict(default=None), vm=dict(default=None), description=dict(default=None), cluster=dict(default=None), allow_partial_import=dict(default=None, type='bool'), cpu_profile=dict(default=None), disks=dict(default=[], type='list'), clone_permissions=dict(type='bool'), export_domain=dict(default=None), storage_domain=dict(default=None), exclusive=dict(type='bool'), image_provider=dict(default=None), image_disk=dict(default=None, aliases=['glance_image_disk_name']), template_image_disk_name=dict(default=None), seal=dict(type='bool'), ) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, required_one_of=[['id', 'name']], ) check_sdk(module) try: auth = module.params.pop('auth') connection = create_connection(auth) templates_service = connection.system_service().templates_service() templates_module = TemplatesModule( connection=connection, module=module, service=templates_service, ) state = module.params['state'] if state == 'present': ret = templates_module.create( result_state=otypes.TemplateStatus.OK, clone_permissions=module.params['clone_permissions'], seal=module.params['seal'], ) elif state == 'absent': ret = templates_module.remove() elif state == 'exported': template = templates_module.search_entity() export_service = templates_module._get_export_domain_service() export_template = search_by_attributes(export_service.templates_service(), id=template.id) ret = templates_module.action( entity=template, action='export', action_condition=lambda t: export_template is None or module.params['exclusive'], wait_condition=lambda t: t is not None, post_action=templates_module.post_export_action, storage_domain=otypes.StorageDomain(id=export_service.get().id), exclusive=module.params['exclusive'], ) elif state == 'imported': template = templates_module.search_entity() if template: ret = templates_module.create( result_state=otypes.TemplateStatus.OK, ) else: kwargs = {} if module.params['image_provider']: kwargs.update( disk=otypes.Disk( name=module.params['template_image_disk_name'] or module.params['image_disk'] ), template=otypes.Template( name=module.params['name'], ), import_as_template=True, ) if module.params['image_disk']: # We need to refresh storage domain to get list of images: templates_module._get_export_domain_service().images_service().list() glance_service = connection.system_service().openstack_image_providers_service() image_provider = search_by_name(glance_service, module.params['image_provider']) images_service = glance_service.service(image_provider.id).images_service() else: images_service = templates_module._get_export_domain_service().templates_service() template_name = module.params['image_disk'] or module.params['name'] entity = search_by_name(images_service, template_name) if entity is None: raise Exception("Image/template '%s' was not found." % template_name) images_service.service(entity.id).import_( storage_domain=otypes.StorageDomain( name=module.params['storage_domain'] ) if module.params['storage_domain'] else None, cluster=otypes.Cluster( name=module.params['cluster'] ) if module.params['cluster'] else None, **kwargs ) # Wait for template to appear in system: template = templates_module.wait_for_import( condition=lambda t: t.status == otypes.TemplateStatus.OK ) ret = { 'changed': True, 'id': template.id, 'template': get_dict_of_struct(template), } elif state == 'registered': storage_domains_service = connection.system_service().storage_domains_service() # Find the storage domain with unregistered template: sd_id = get_id_by_name(storage_domains_service, module.params['storage_domain']) storage_domain_service = storage_domains_service.storage_domain_service(sd_id) templates_service = storage_domain_service.templates_service() # Find the unregistered Template we want to register: templates = templates_service.list(unregistered=True) template = next( (t for t in templates if (t.id == module.params['id'] or t.name == module.params['name'])), None ) changed = False if template is None: template = templates_module.search_entity() if template is None: raise ValueError( "Template '%s(%s)' wasn't found." % (module.params['name'], module.params['id']) ) else: # Register the template into the system: changed = True template_service = templates_service.template_service(template.id) template_service.register( allow_partial_import=module.params['allow_partial_import'], cluster=otypes.Cluster( name=module.params['cluster'] ) if module.params['cluster'] else None ) if module.params['wait']: template = templates_module.wait_for_import() else: # Fetch template to initialize return. template = template_service.get() ret = { 'changed': changed, 'id': template.id, 'template': get_dict_of_struct(template) } module.exit_json(**ret) except Exception as e: module.fail_json(msg=str(e), exception=traceback.format_exc()) finally: connection.close(logout=auth.get('token') is None) if __name__ == "__main__": main()
tsdmgz/ansible
lib/ansible/modules/cloud/ovirt/ovirt_templates.py
Python
gpl-3.0
15,907
/* * This file is part of muCommander, http://www.mucommander.com * Copyright (C) 2002-2012 Maxence Bernard * * muCommander 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. * * muCommander 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 com.mucommander.ui.autocomplete.completers.services; import com.mucommander.commons.file.AbstractFile; import com.mucommander.commons.file.filter.FileFilter; import java.io.IOException; /** * This <code>FilesService</code> returns filtered files in a given directory, * according to a certain <code>FileFilter</code>. * * @author Arik Hadas */ public class FilteredFilesService extends FilesService { private FileFilter fileFilter; public FilteredFilesService(FileFilter fileFilter) { this.fileFilter = fileFilter; } @Override protected AbstractFile[] getFiles(AbstractFile directory) throws IOException { return fileFilter.filter(directory.ls()); } }
Keltek/mucommander
src/main/com/mucommander/ui/autocomplete/completers/services/FilteredFilesService.java
Java
gpl-3.0
1,448
/// <reference path="../../allors.module.ts" /> /// <reference path="internal/Field.ts" /> namespace Allors.Bootstrap { export class TextAngularTemplate { static templateName = "allors/bootstrap/text-angular"; static createDefaultView() { return ` <div ng-if="$ctrl.canWrite"> <text-angular ng-model="$ctrl.role" '/> </div> <div ng-if="!$ctrl.canWrite"> <text-angular ta-bind="text" ng-model="$ctrl.role" '/> </div>`; } static register(templateCache: angular.ITemplateCacheService, view = TextAngularTemplate.createDefaultView()) { templateCache.put(TextAngularTemplate.templateName, view); } } export class TextAngularController extends Field { static bindings = { object: "<", relation: "@" } as { [binding: string]: string } static $inject = ["$log", "$translate"]; constructor($log: angular.ILogService, $translate: angular.translate.ITranslateService) { super($log, $translate); } } angular .module("allors") .component("bTextAngular", { controller: TextAngularController, templateUrl: TextAngularTemplate.templateName, require: FormController.require, bindings: TextAngularController.bindings }); }
Allors/allors
Domains/Base/Workspace/Typescript/globals/Angular/components/bootstrap/TextAngular.ts
TypeScript
gpl-3.0
1,347
<?php /////////////////////////////////////////////////////////////////////////// // // // This file is part of Moodle - http://moodle.org/ // // Moodle - Modular Object-Oriented Dynamic Learning Environment // // // // Moodle 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. // // // // Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>. // // // /////////////////////////////////////////////////////////////////////////// defined('MOODLE_INTERNAL') || die(); /** * Rendering of files viewer related widgets. * @package core * @subpackage file * @copyright 2010 Dongsheng Cai * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since Moodle 2.0 */ /** * File browser render * * @copyright 2010 Dongsheng Cai * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since Moodle 2.0 */ class core_files_renderer extends plugin_renderer_base { public function files_tree_viewer(file_info $file_info, array $options = null) { $tree = new files_tree_viewer($file_info, $options); return $this->render($tree); } public function render_files_tree_viewer(files_tree_viewer $tree) { $html = $this->output->heading_with_help(get_string('coursefiles'), 'courselegacyfiles', 'moodle'); $html .= $this->output->container_start('coursefilesbreadcrumb'); foreach($tree->path as $path) { $html .= $path; $html .= ' / '; } $html .= $this->output->container_end(); $html .= $this->output->box_start(); $table = new html_table(); $table->head = array(get_string('name'), get_string('lastmodified'), get_string('size', 'repository'), get_string('type', 'repository')); $table->align = array('left', 'left', 'left', 'left'); $table->width = '100%'; $table->data = array(); foreach ($tree->tree as $file) { $filedate = $filesize = $filetype = ''; if ($file['filedate']) { $filedate = userdate($file['filedate'], get_string('strftimedatetimeshort', 'langconfig')); } if (empty($file['isdir'])) { if ($file['filesize']) { $filesize = display_size($file['filesize']); } $fileicon = file_file_icon($file, 24); $filetype = get_mimetype_description($file); } else { $fileicon = file_folder_icon(24); } $table->data[] = array( html_writer::link($file['url'], $this->output->pix_icon($fileicon, get_string('icon')) . ' ' . $file['filename']), $filedate, $filesize, $filetype ); } $html .= html_writer::table($table); $html .= $this->output->single_button(new moodle_url('/files/coursefilesedit.php', array('contextid'=>$tree->context->id)), get_string('coursefilesedit'), 'get'); $html .= $this->output->box_end(); return $html; } /** * Prints the file manager and initializes all necessary libraries * * <pre> * $fm = new form_filemanager($options); * $output = get_renderer('core', 'files'); * echo $output->render($fm); * </pre> * * @param form_filemanager $fm File manager to render * @return string HTML fragment */ public function render_form_filemanager($fm) { $html = $this->fm_print_generallayout($fm); $module = array( 'name'=>'form_filemanager', 'fullpath'=>'/lib/form/filemanager.js', 'requires' => array('moodle-core-notification-dialogue', 'core_filepicker', 'base', 'io-base', 'node', 'json', 'core_dndupload', 'panel', 'resize-plugin', 'dd-plugin'), 'strings' => array( array('error', 'moodle'), array('info', 'moodle'), array('confirmdeletefile', 'repository'), array('draftareanofiles', 'repository'), array('entername', 'repository'), array('enternewname', 'repository'), array('invalidjson', 'repository'), array('popupblockeddownload', 'repository'), array('unknownoriginal', 'repository'), array('confirmdeletefolder', 'repository'), array('confirmdeletefilewithhref', 'repository'), array('confirmrenamefolder', 'repository'), array('confirmrenamefile', 'repository'), array('newfolder', 'repository'), array('edit', 'moodle') ) ); if ($this->page->requires->should_create_one_time_item_now('core_file_managertemplate')) { $this->page->requires->js_init_call('M.form_filemanager.set_templates', array($this->filemanager_js_templates()), true, $module); } $this->page->requires->js_init_call('M.form_filemanager.init', array($fm->options), true, $module); // non javascript file manager $html .= '<noscript>'; $html .= "<div><object type='text/html' data='".$fm->get_nonjsurl()."' height='160' width='600' style='border:1px solid #000'></object></div>"; $html .= '</noscript>'; return $html; } /** * Returns html for displaying one file manager * * The main element in HTML must have id="filemanager-{$client_id}" and * class="filemanager fm-loading"; * After all necessary code on the page (both html and javascript) is loaded, * the class fm-loading will be removed and added class fm-loaded; * The main element (class=filemanager) will be assigned the following classes: * 'fm-maxfiles' - when filemanager has maximum allowed number of files; * 'fm-nofiles' - when filemanager has no files at all (although there might be folders); * 'fm-noitems' - when current view (folder) has no items - neither files nor folders; * 'fm-updating' - when current view is being updated (usually means that loading icon is to be displayed); * 'fm-nomkdir' - when 'Make folder' action is unavailable (empty($fm->options->subdirs) == true) * * Element with class 'filemanager-container' will be holding evens for dnd upload (dragover, etc.). * It will have class: * 'dndupload-ready' - when a file is being dragged over the browser * 'dndupload-over' - when file is being dragged over this filepicker (additional to 'dndupload-ready') * 'dndupload-uploading' - during the upload process (note that after dnd upload process is * over, the file manager will refresh the files list and therefore will have for a while class * fm-updating. Both waiting processes should look similar so the images don't jump for user) * * If browser supports Drag-and-drop, the body element will have class 'dndsupported', * otherwise - 'dndnotsupported'; * * Element with class 'fp-content' will be populated with files list; * Element with class 'fp-btn-add' will hold onclick event for adding a file (opening filepicker); * Element with class 'fp-btn-mkdir' will hold onclick event for adding new folder; * Element with class 'fp-btn-download' will hold onclick event for download action; * * Element with class 'fp-path-folder' is a template for one folder in path toolbar. * It will hold mouse click event and will be assigned classes first/last/even/odd respectfully. * Parent element will receive class 'empty' when there are no folders to be displayed; * The content of subelement with class 'fp-path-folder-name' will be substituted with folder name; * * Element with class 'fp-viewbar' will have the class 'enabled' or 'disabled' when view mode * can be changed or not; * Inside element with class 'fp-viewbar' there are expected elements with classes * 'fp-vb-icons', 'fp-vb-tree' and 'fp-vb-details'. They will handle onclick events to switch * between the view modes, the last clicked element will have the class 'checked'; * * @param form_filemanager $fm * @return string */ protected function fm_print_generallayout($fm) { global $OUTPUT; $options = $fm->options; $client_id = $options->client_id; $straddfile = get_string('addfile', 'repository'); $strmakedir = get_string('makeafolder', 'moodle'); $strdownload = get_string('downloadfolder', 'repository'); $strloading = get_string('loading', 'repository'); $strdroptoupload = get_string('droptoupload', 'moodle'); $icon_progress = $OUTPUT->pix_icon('i/loading_small', $strloading).''; $restrictions = $this->fm_print_restrictions($fm); $strdndnotsupported = get_string('dndnotsupported_insentence', 'moodle').$OUTPUT->help_icon('dndnotsupported'); $strdndenabledinbox = get_string('dndenabled_inbox', 'moodle'); $loading = get_string('loading', 'repository'); $straddfiletext = get_string('addfiletext', 'repository'); $strcreatefolder = get_string('createfolder', 'repository'); $strdownloadallfiles = get_string('downloadallfiles', 'repository'); $html = ' <div id="filemanager-'.$client_id.'" class="filemanager fm-loading"> <div class="fp-restrictions"> '.$restrictions.' <span class="dnduploadnotsupported-message"> - '.$strdndnotsupported.' </span> </div> <div class="fp-navbar"> <div class="filemanager-toolbar"> <div class="fp-toolbar"> <div class="fp-btn-add"> <a role="button" title="' . $straddfile . '" href="#"> ' . $this->pix_icon('a/add_file', $straddfiletext) . ' </a> </div> <div class="fp-btn-mkdir"> <a role="button" title="' . $strmakedir . '" href="#"> ' . $this->pix_icon('a/create_folder', $strcreatefolder) . ' </a> </div> <div class="fp-btn-download"> <a role="button" title="' . $strdownload . '" href="#"> ' . $this->pix_icon('a/download_all', $strdownloadallfiles) . ' </a> </div> <span class="fp-img-downloading"> ' . $this->pix_icon('i/loading_small', '') . ' </span> </div> <div class="fp-viewbar"> <a title="'. get_string('displayicons', 'repository') .'" class="fp-vb-icons" href="#"> ' . $this->pix_icon('fp/view_icon_active', get_string('displayasicons', 'repository'), 'theme') . ' </a> <a title="'. get_string('displaydetails', 'repository') .'" class="fp-vb-details" href="#"> ' . $this->pix_icon('fp/view_list_active', get_string('displayasdetails', 'repository'), 'theme') . ' </a> <a title="'. get_string('displaytree', 'repository') .'" class="fp-vb-tree" href="#"> ' . $this->pix_icon('fp/view_tree_active', get_string('displayastree', 'repository'), 'theme') . ' </a> </div> </div> <div class="fp-pathbar"> <span class="fp-path-folder"><a class="fp-path-folder-name" href="#"></a></span> </div> </div> <div class="filemanager-loading mdl-align">'.$icon_progress.'</div> <div class="filemanager-container" > <div class="fm-content-wrapper"> <div class="fp-content"></div> <div class="fm-empty-container"> <div class="dndupload-message">'.$strdndenabledinbox.'<br/><div class="dndupload-arrow"></div></div> </div> <div class="dndupload-target">'.$strdroptoupload.'<br/><div class="dndupload-arrow"></div></div> <div class="dndupload-progressbars"></div> <div class="dndupload-uploadinprogress">'.$icon_progress.'</div> </div> <div class="filemanager-updating">'.$icon_progress.'</div> </div> </div>'; return $html; } /** * FileManager JS template for displaying one file in 'icon view' mode. * * Except for elements described in fp_js_template_iconfilename, this template may also * contain element with class 'fp-contextmenu'. If context menu is available for this * file, the top element will receive the additional class 'fp-hascontextmenu' and * the element with class 'fp-contextmenu' will hold onclick event for displaying * the context menu. * * @see fp_js_template_iconfilename() * @return string */ protected function fm_js_template_iconfilename() { $rv = ' <div class="fp-file"> <a href="#"> <div style="position:relative;"> <div class="fp-thumbnail"></div> <div class="fp-reficons1"></div> <div class="fp-reficons2"></div> </div> <div class="fp-filename-field"> <div class="fp-filename"></div> </div> </a> <a class="fp-contextmenu" href="#">'.$this->pix_icon('i/menu', '▶').'</a> </div>'; return $rv; } /** * FileManager JS template for displaying file name in 'table view' and 'tree view' modes. * * Except for elements described in fp_js_template_listfilename, this template may also * contain element with class 'fp-contextmenu'. If context menu is available for this * file, the top element will receive the additional class 'fp-hascontextmenu' and * the element with class 'fp-contextmenu' will hold onclick event for displaying * the context menu. * * @todo MDL-32736 remove onclick="return false;" * @see fp_js_template_listfilename() * @return string */ protected function fm_js_template_listfilename() { $rv = ' <span class="fp-filename-icon"> <a href="#"> <span class="fp-icon"></span> <span class="fp-reficons1"></span> <span class="fp-reficons2"></span> <span class="fp-filename"></span> </a> <a class="fp-contextmenu" href="#" onclick="return false;">'.$this->pix_icon('i/menu', '▶').'</a> </span>'; return $rv; } /** * FileManager JS template for displaying 'Make new folder' dialog. * * Must be wrapped in an element, CSS for this element must define width and height of the window; * * Must have one input element with type="text" (for users to enter the new folder name); * * content of element with class 'fp-dlg-curpath' will be replaced with current path where * new folder is about to be created; * elements with classes 'fp-dlg-butcreate' and 'fp-dlg-butcancel' will hold onclick events; * * @return string */ protected function fm_js_template_mkdir() { $rv = ' <div class="filemanager fp-mkdir-dlg" role="dialog" aria-live="assertive" aria-labelledby="fp-mkdir-dlg-title"> <div class="fp-mkdir-dlg-text"> <label id="fp-mkdir-dlg-title">' . get_string('newfoldername', 'repository') . '</label><br/> <input type="text" /> </div> <button class="fp-dlg-butcreate btn-primary btn">'.get_string('makeafolder').'</button> <button class="fp-dlg-butcancel btn-cancel btn">'.get_string('cancel').'</button> </div>'; return $rv; } /** * FileManager JS template for error/info message displayed as a separate popup window. * * @see fp_js_template_message() * @return string */ protected function fm_js_template_message() { return $this->fp_js_template_message(); } /** * FileManager JS template for window with file information/actions. * * All content must be enclosed in one element, CSS for this class must define width and * height of the window; * * Thumbnail image will be added as content to the element with class 'fp-thumbnail'; * * Inside the window the elements with the following classnames must be present: * 'fp-saveas', 'fp-author', 'fp-license', 'fp-path'. Inside each of them must be * one input element (or select in case of fp-license and fp-path). They may also have labels. * The elements will be assign with class 'uneditable' and input/select element will become * disabled if they are not applicable for the particular file; * * There may be present elements with classes 'fp-original', 'fp-datemodified', 'fp-datecreated', * 'fp-size', 'fp-dimensions', 'fp-reflist'. They will receive additional class 'fp-unknown' if * information is unavailable. If there is information available, the content of embedded * element with class 'fp-value' will be substituted with the value; * * The value of Original ('fp-original') is loaded in separate request. When it is applicable * but not yet loaded the 'fp-original' element receives additional class 'fp-loading'; * * The value of 'Aliases/Shortcuts' ('fp-reflist') is also loaded in separate request. When it * is applicable but not yet loaded the 'fp-original' element receives additional class * 'fp-loading'. The string explaining that XX references exist will replace content of element * 'fp-refcount'. Inside '.fp-reflist .fp-value' each reference will be enclosed in <li>; * * Elements with classes 'fp-file-update', 'fp-file-download', 'fp-file-delete', 'fp-file-zip', * 'fp-file-unzip', 'fp-file-setmain' and 'fp-file-cancel' will hold corresponding onclick * events (there may be several elements with class 'fp-file-cancel'); * * When confirm button is pressed and file is being selected, the top element receives * additional class 'loading'. It is removed when response from server is received. * * When any of the input fields is changed, the top element receives class 'fp-changed'; * When current file can be set as main - top element receives class 'fp-cansetmain'; * When current file is folder/zip/file - top element receives respectfully class * 'fp-folder'/'fp-zip'/'fp-file'; * * @return string */ protected function fm_js_template_fileselectlayout() { global $OUTPUT; $strloading = get_string('loading', 'repository'); $iconprogress = $this->pix_icon('i/loading_small', $strloading).''; $rv = ' <div class="filemanager fp-select"> <div class="fp-select-loading"> ' . $this->pix_icon('i/loading_small', '') . ' </div> <form class="form-horizontal"> <button class="fp-file-download">'.get_string('download').'</button> <button class="fp-file-delete">'.get_string('delete').'</button> <button class="fp-file-setmain">'.get_string('setmainfile', 'repository').'</button> <span class="fp-file-setmain-help">'.$OUTPUT->help_icon('setmainfile', 'repository').'</span> <button class="fp-file-zip">'.get_string('zip', 'editor').'</button> <button class="fp-file-unzip">'.get_string('unzip').'</button> <div class="fp-hr"></div> <div class="fp-forminset"> <div class="fp-saveas control-group clearfix"> <label class="control-label">'.get_string('name', 'repository').'</label> <div class="controls"> <input type="text"/> </div> </div> <div class="fp-author control-group clearfix"> <label class="control-label">'.get_string('author', 'repository').'</label> <div class="controls"> <input type="text"/> </div> </div> <div class="fp-license control-group clearfix"> <label class="control-label">'.get_string('chooselicense', 'repository').'</label> <div class="controls"> <select></select> </div> </div> <div class="fp-path control-group clearfix"> <label class="control-label">'.get_string('path', 'repository').'</label> <div class="controls"> <select></select> </div> </div> <div class="fp-original control-group clearfix"> <label class="control-label">'.get_string('original', 'repository').'</label> <div class="controls"> <span class="fp-originloading">'.$iconprogress.' '.$strloading.'</span><span class="fp-value"></span> </div> </div> <div class="fp-reflist control-group clearfix"> <label class="control-label">'.get_string('referenceslist', 'repository').'</label> <div class="controls"> <p class="fp-refcount"></p> <span class="fp-reflistloading">'.$iconprogress.' '.$strloading.'</span> <ul class="fp-value"></ul> </div> </div> </div> <div class="fp-select-buttons"> <button class="fp-file-update btn-primary btn">'.get_string('update', 'moodle').'</button> <button class="fp-file-cancel btn-cancel btn">'.get_string('cancel').'</button> </div> </form> <div class="fp-info clearfix"> <div class="fp-hr"></div> <p class="fp-thumbnail"></p> <div class="fp-fileinfo"> <div class="fp-datemodified">'.get_string('lastmodified', 'repository').' <span class="fp-value"></span></div> <div class="fp-datecreated">'.get_string('datecreated', 'repository').' <span class="fp-value"></span></div> <div class="fp-size">'.get_string('size', 'repository').' <span class="fp-value"></span></div> <div class="fp-dimensions">'.get_string('dimensions', 'repository').' <span class="fp-value"></span></div> </div> </div> </div>'; return $rv; } /** * FileManager JS template for popup confirm dialogue window. * * Must have one top element, CSS for this element must define width and height of the window; * * content of element with class 'fp-dlg-text' will be replaced with dialog text; * elements with classes 'fp-dlg-butconfirm' and 'fp-dlg-butcancel' will * hold onclick events; * * @return string */ protected function fm_js_template_confirmdialog() { $rv = ' <div class="filemanager fp-dlg"> <div class="fp-dlg-text"></div> <button class="fp-dlg-butconfirm btn-primary btn">'.get_string('ok').'</button> <button class="fp-dlg-butcancel btn-cancel btn">'.get_string('cancel').'</button> </div>'; return $rv; } /** * Returns all FileManager JavaScript templates as an array. * * @return array */ public function filemanager_js_templates() { $class_methods = get_class_methods($this); $templates = array(); foreach ($class_methods as $method_name) { if (preg_match('/^fm_js_template_(.*)$/', $method_name, $matches)) $templates[$matches[1]] = $this->$method_name(); } return $templates; } /** * Displays restrictions for the file manager * * @param form_filemanager $fm * @return string */ protected function fm_print_restrictions($fm) { $maxbytes = display_size($fm->options->maxbytes); $strparam = (object) array('size' => $maxbytes, 'attachments' => $fm->options->maxfiles, 'areasize' => display_size($fm->options->areamaxbytes)); $hasmaxfiles = !empty($fm->options->maxfiles) && $fm->options->maxfiles > 0; $hasarealimit = !empty($fm->options->areamaxbytes) && $fm->options->areamaxbytes != -1; if ($hasmaxfiles && $hasarealimit) { $maxsize = get_string('maxsizeandattachmentsandareasize', 'moodle', $strparam); } else if ($hasmaxfiles) { $maxsize = get_string('maxsizeandattachments', 'moodle', $strparam); } else if ($hasarealimit) { $maxsize = get_string('maxsizeandareasize', 'moodle', $strparam); } else { $maxsize = get_string('maxfilesize', 'moodle', $maxbytes); } // TODO MDL-32020 also should say about 'File types accepted' return '<span>'. $maxsize . '</span>'; } /** * Template for FilePicker with general layout (not QuickUpload). * * Must have one top element containing everything else (recommended <div class="file-picker">), * CSS for this element must define width and height of the filepicker window. Or CSS must * define min-width, max-width, min-height and max-height and in this case the filepicker * window will be resizeable; * * Element with class 'fp-viewbar' will have the class 'enabled' or 'disabled' when view mode * can be changed or not; * Inside element with class 'fp-viewbar' there are expected elements with classes * 'fp-vb-icons', 'fp-vb-tree' and 'fp-vb-details'. They will handle onclick events to switch * between the view modes, the last clicked element will have the class 'checked'; * * Element with class 'fp-repo' is a template for displaying one repository. Other repositories * will be attached as siblings (classes first/last/even/odd will be added respectfully). * The currently selected repostory will have class 'active'. Contents of element with class * 'fp-repo-name' will be replaced with repository name, source of image with class * 'fp-repo-icon' will be replaced with repository icon; * * Element with class 'fp-content' is obligatory and will hold the current contents; * * Element with class 'fp-paging' will contain page navigation (will be deprecated soon); * * Element with class 'fp-path-folder' is a template for one folder in path toolbar. * It will hold mouse click event and will be assigned classes first/last/even/odd respectfully. * Parent element will receive class 'empty' when there are no folders to be displayed; * The content of subelement with class 'fp-path-folder-name' will be substituted with folder name; * * Element with class 'fp-toolbar' will have class 'empty' if all 'Back', 'Search', 'Refresh', * 'Logout', 'Manage' and 'Help' are unavailable for this repo; * * Inside fp-toolbar there are expected elements with classes fp-tb-back, fp-tb-search, * fp-tb-refresh, fp-tb-logout, fp-tb-manage and fp-tb-help. Each of them will have * class 'enabled' or 'disabled' if particular repository has this functionality. * Element with class 'fp-tb-search' must contain empty form inside, it's contents will * be substituted with the search form returned by repository (in the most cases it * is generated with template core_repository_renderer::repository_default_searchform); * Other elements must have either <a> or <button> element inside, it will hold onclick * event for corresponding action; labels for fp-tb-back and fp-tb-logout may be * replaced with those specified by repository; * * @return string */ protected function fp_js_template_generallayout() { $rv = ' <div tabindex="0" class="file-picker fp-generallayout" role="dialog" aria-live="assertive"> <div class="fp-repo-area"> <ul class="fp-list"> <li class="fp-repo"> <a href="#"><img class="fp-repo-icon" alt=" " width="16" height="16" />&nbsp;<span class="fp-repo-name"></span></a> </li> </ul> </div> <div class="fp-repo-items" tabindex="0"> <div class="fp-navbar"> <div> <div class="fp-toolbar"> <div class="fp-tb-back"> <a href="#">'.get_string('back', 'repository').'</a> </div> <div class="fp-tb-search"> <form></form> </div> <div class="fp-tb-refresh"> <a title="'. get_string('refresh', 'repository') .'" href="#"> ' . $this->pix_icon('a/refresh', '') . ' </a> </div> <div class="fp-tb-logout"> <a title="'. get_string('logout', 'repository') .'" href="#"> ' . $this->pix_icon('a/logout', '') . ' </a> </div> <div class="fp-tb-manage"> <a title="'. get_string('settings', 'repository') .'" href="#"> ' . $this->pix_icon('a/setting', '') . ' </a> </div> <div class="fp-tb-help"> <a title="'. get_string('help', 'repository') .'" href="#"> ' . $this->pix_icon('a/help', '') . ' </a> </div> <div class="fp-tb-message"></div> </div> <div class="fp-viewbar"> <a role="button" title="'. get_string('displayicons', 'repository') .'" class="fp-vb-icons" href="#"> ' . $this->pix_icon('fp/view_icon_active', '', 'theme') . ' </a> <a role="button" title="'. get_string('displaydetails', 'repository') .'" class="fp-vb-details" href="#"> ' . $this->pix_icon('fp/view_list_active', '', 'theme') . ' </a> <a role="button" title="'. get_string('displaytree', 'repository') .'" class="fp-vb-tree" href="#"> ' . $this->pix_icon('fp/view_tree_active', '', 'theme') . ' </a> </div> <div class="fp-clear-left"></div> </div> <div class="fp-pathbar"> <span class="fp-path-folder"><a class="fp-path-folder-name" href="#"></a></span> </div> </div> <div class="fp-content"></div> </div> </div>'; return $rv; } /** * FilePicker JS template for displaying one file in 'icon view' mode. * * the element with class 'fp-thumbnail' will be resized to the repository thumbnail size * (both width and height, unless min-width and/or min-height is set in CSS) and the content of * an element will be replaced with an appropriate img; * * the width of element with class 'fp-filename' will be set to the repository thumbnail width * (unless min-width is set in css) and the content of an element will be replaced with filename * supplied by repository; * * top element(s) will have class fp-folder if the element is a folder; * * List of files will have parent <div> element with class 'fp-iconview' * * @return string */ protected function fp_js_template_iconfilename() { $rv = ' <a class="fp-file" href="#" > <div style="position:relative;"> <div class="fp-thumbnail"></div> <div class="fp-reficons1"></div> <div class="fp-reficons2"></div> </div> <div class="fp-filename-field"> <p class="fp-filename"></p> </div> </a>'; return $rv; } /** * FilePicker JS template for displaying file name in 'table view' and 'tree view' modes. * * content of the element with class 'fp-icon' will be replaced with an appropriate img; * * content of element with class 'fp-filename' will be replaced with filename supplied by * repository; * * top element(s) will have class fp-folder if the element is a folder; * * Note that tree view and table view are the YUI widgets and therefore there are no * other templates. The widgets will be wrapped in <div> with class fp-treeview or * fp-tableview (respectfully). * * @return string */ protected function fp_js_template_listfilename() { $rv = ' <span class="fp-filename-icon"> <a href="#"> <span class="fp-icon"></span> <span class="fp-filename"></span> </a> </span>'; return $rv; } /** * FilePicker JS template for displaying link/loading progress for fetching of the next page * * This text is added to .fp-content AFTER .fp-iconview/.fp-treeview/.fp-tableview * * Must have one parent element with class 'fp-nextpage'. It will be assigned additional * class 'loading' during loading of the next page (it is recommended that in this case the link * becomes unavailable). Also must contain one element <a> or <button> that will hold * onclick event for displaying of the next page. The event will be triggered automatically * when user scrolls to this link. * * @return string */ protected function fp_js_template_nextpage() { $rv = ' <div class="fp-nextpage"> <div class="fp-nextpage-link"><a href="#">'.get_string('more').'</a></div> <div class="fp-nextpage-loading"> ' . $this->pix_icon('i/loading_small', '') . ' </div> </div>'; return $rv; } /** * FilePicker JS template for window appearing to select a file. * * All content must be enclosed in one element, CSS for this class must define width and * height of the window; * * Thumbnail image will be added as content to the element with class 'fp-thumbnail'; * * Inside the window the elements with the following classnames must be present: * 'fp-saveas', 'fp-linktype-2', 'fp-linktype-1', 'fp-linktype-4', 'fp-setauthor', * 'fp-setlicense'. Inside each of them must have one input element (or select in case of * fp-setlicense). They may also have labels. * The elements will be assign with class 'uneditable' and input/select element will become * disabled if they are not applicable for the particular file; * * There may be present elements with classes 'fp-datemodified', 'fp-datecreated', 'fp-size', * 'fp-license', 'fp-author', 'fp-dimensions'. They will receive additional class 'fp-unknown' * if information is unavailable. If there is information available, the content of embedded * element with class 'fp-value' will be substituted with the value; * * Elements with classes 'fp-select-confirm' and 'fp-select-cancel' will hold corresponding * onclick events; * * When confirm button is pressed and file is being selected, the top element receives * additional class 'loading'. It is removed when response from server is received. * * @return string */ protected function fp_js_template_selectlayout() { $rv = ' <div class="file-picker fp-select"> <div class="fp-select-loading"> ' . $this->pix_icon('i/loading_small', '') . ' </div> <form class="form-horizontal"> <div class="fp-forminset"> <div class="fp-linktype-2 control-group control-radio clearfix"> <label class="control-label control-radio">'.get_string('makefileinternal', 'repository').'</label> <div class="controls control-radio"> <input type="radio"/> </div> </div> <div class="fp-linktype-1 control-group control-radio clearfix"> <label class="control-label control-radio">'.get_string('makefilelink', 'repository').'</label> <div class="controls control-radio"> <input type="radio"/> </div> </div> <div class="fp-linktype-4 control-group control-radio clearfix"> <label class="control-label control-radio">'.get_string('makefilereference', 'repository').'</label> <div class="controls control-radio"> <input type="radio"/> </div> </div> <div class="fp-saveas control-group clearfix"> <label class="control-label">'.get_string('saveas', 'repository').'</label> <div class="controls"> <input type="text"/> </div> </div> <div class="fp-setauthor control-group clearfix"> <label class="control-label">'.get_string('author', 'repository').'</label> <div class="controls"> <input type="text"/> </div> </div> <div class="fp-setlicense control-group clearfix"> <label class="control-label">'.get_string('chooselicense', 'repository').'</label> <div class="controls"> <select></select> </div> </div> </div> <div class="fp-select-buttons"> <button class="fp-select-confirm btn-primary btn">'.get_string('getfile', 'repository').'</button> <button class="fp-select-cancel btn-cancel btn">'.get_string('cancel').'</button> </div> </form> <div class="fp-info clearfix"> <div class="fp-hr"></div> <p class="fp-thumbnail"></p> <div class="fp-fileinfo"> <div class="fp-datemodified">'.get_string('lastmodified', 'repository').'<span class="fp-value"></span></div> <div class="fp-datecreated">'.get_string('datecreated', 'repository').'<span class="fp-value"></span></div> <div class="fp-size">'.get_string('size', 'repository').'<span class="fp-value"></span></div> <div class="fp-license">'.get_string('license', 'repository').'<span class="fp-value"></span></div> <div class="fp-author">'.get_string('author', 'repository').'<span class="fp-value"></span></div> <div class="fp-dimensions">'.get_string('dimensions', 'repository').'<span class="fp-value"></span></div> </div> </div> </div>'; return $rv; } /** * FilePicker JS template for 'Upload file' repository * * Content to display when user chooses 'Upload file' repository (will be nested inside * element with class 'fp-content'). * * Must contain form (enctype="multipart/form-data" method="POST") * * The elements with the following classnames must be present: * 'fp-file', 'fp-saveas', 'fp-setauthor', 'fp-setlicense'. Inside each of them must have * one input element (or select in case of fp-setlicense). They may also have labels. * * Element with class 'fp-upload-btn' will hold onclick event for uploading the file; * * Please note that some fields may be hidden using CSS if this is part of quickupload form * * @return string */ protected function fp_js_template_uploadform() { $rv = ' <div class="fp-upload-form"> <div class="fp-content-center"> <form enctype="multipart/form-data" method="POST" class="form-horizontal"> <div class="fp-formset"> <div class="fp-file control-group clearfix"> <label class="control-label">'.get_string('attachment', 'repository').'</label> <div class="controls"> <input type="file"/> </div> </div> <div class="fp-saveas control-group clearfix"> <label class="control-label">'.get_string('saveas', 'repository').'</label> <div class="controls"> <input type="text"/> </div> </div> <div class="fp-setauthor control-group clearfix"> <label class="control-label">'.get_string('author', 'repository').'</label> <div class="controls"> <input type="text"/> </div> </div> <div class="fp-setlicense control-group clearfix"> <label class="control-label">'.get_string('chooselicense', 'repository').'</label> <div class="controls"> <select ></select> </div> </div> </div> </form> <div class="mdl-align"> <button class="fp-upload-btn btn-primary btn">'.get_string('upload', 'repository').'</button> </div> </div> </div> '; return $rv; } /** * FilePicker JS template to display during loading process (inside element with class 'fp-content'). * * @return string */ protected function fp_js_template_loading() { return ' <div class="fp-content-loading"> <div class="fp-content-center"> ' . $this->pix_icon('i/loading_small', '') . ' </div> </div>'; } /** * FilePicker JS template for error (inside element with class 'fp-content'). * * must have element with class 'fp-error', its content will be replaced with error text * and the error code will be assigned as additional class to this element * used errors: invalidjson, nofilesavailable, norepositoriesavailable * * @return string */ protected function fp_js_template_error() { $rv = ' <div class="fp-content-error" ><div class="fp-error"></div></div>'; return $rv; } /** * FilePicker JS template for error/info message displayed as a separate popup window. * * Must be wrapped in one element, CSS for this element must define * width and height of the window. It will be assigned with an additional class 'fp-msg-error' * or 'fp-msg-info' depending on message type; * * content of element with class 'fp-msg-text' will be replaced with error/info text; * * element with class 'fp-msg-butok' will hold onclick event * * @return string */ protected function fp_js_template_message() { $rv = ' <div class="file-picker fp-msg" role="alertdialog" aria-live="assertive" aria-labelledby="fp-msg-labelledby"> <p class="fp-msg-text" id="fp-msg-labelledby"></p> <button class="fp-msg-butok btn-primary btn">'.get_string('ok').'</button> </div>'; return $rv; } /** * FilePicker JS template for popup dialogue window asking for action when file with the same name already exists. * * Must have one top element, CSS for this element must define width and height of the window; * * content of element with class 'fp-dlg-text' will be replaced with dialog text; * elements with classes 'fp-dlg-butoverwrite', 'fp-dlg-butrename', * 'fp-dlg-butoverwriteall', 'fp-dlg-butrenameall' and 'fp-dlg-butcancel' will * hold onclick events; * * content of element with class 'fp-dlg-butrename' will be substituted with appropriate string * (Note that it may have long text) * * @return string */ protected function fp_js_template_processexistingfile() { $rv = ' <div class="file-picker fp-dlg"> <p class="fp-dlg-text"></p> <div class="fp-dlg-buttons"> <button class="fp-dlg-butoverwrite btn">'.get_string('overwrite', 'repository').'</button> <button class="fp-dlg-butrename btn"></button> <button class="fp-dlg-butcancel btn btn-cancel">'.get_string('cancel').'</button> </div> </div>'; return $rv; } /** * FilePicker JS template for popup dialogue window asking for action when file with the same name already exists (multiple-file version). * * Must have one top element, CSS for this element must define width and height of the window; * * content of element with class 'fp-dlg-text' will be replaced with dialog text; * elements with classes 'fp-dlg-butoverwrite', 'fp-dlg-butrename' and 'fp-dlg-butcancel' will * hold onclick events; * * content of element with class 'fp-dlg-butrename' will be substituted with appropriate string * (Note that it may have long text) * * @return string */ protected function fp_js_template_processexistingfilemultiple() { $rv = ' <div class="file-picker fp-dlg"> <p class="fp-dlg-text"></p> <a class="fp-dlg-butoverwrite fp-panel-button" href="#">'.get_string('overwrite', 'repository').'</a> <a class="fp-dlg-butcancel fp-panel-button" href="#">'.get_string('cancel').'</a> <a class="fp-dlg-butrename fp-panel-button" href="#"></a> <br/> <a class="fp-dlg-butoverwriteall fp-panel-button" href="#">'.get_string('overwriteall', 'repository').'</a> <a class="fp-dlg-butrenameall fp-panel-button" href="#">'.get_string('renameall', 'repository').'</a> </div>'; return $rv; } /** * FilePicker JS template for repository login form including templates for each element type * * Must contain one <form> element with templates for different input types inside: * Elements with classes 'fp-login-popup', 'fp-login-textarea', 'fp-login-select' and * 'fp-login-input' are templates for displaying respective login form elements. Inside * there must be exactly one element with type <button>, <textarea>, <select> or <input> * (i.e. fp-login-popup should have <button>, fp-login-textarea should have <textarea>, etc.); * They may also contain the <label> element and it's content will be substituted with * label; * * You can also define elements with classes 'fp-login-checkbox', 'fp-login-text' * but if they are not found, 'fp-login-input' will be used; * * Element with class 'fp-login-radiogroup' will be used for group of radio inputs. Inside * it should hava a template for one radio input (with class 'fp-login-radio'); * * Element with class 'fp-login-submit' will hold on click mouse event (form submission). It * will be removed if at least one popup element is present; * * @return string */ protected function fp_js_template_loginform() { $rv = ' <div class="fp-login-form"> <div class="fp-content-center"> <form class="form-horizontal"> <div class="fp-formset"> <div class="fp-login-popup control-group clearfix"> <div class="controls fp-popup"> <button class="fp-login-popup-but btn-primary btn">'.get_string('login', 'repository').'</button> </div> </div> <div class="fp-login-textarea control-group clearfix"> <div class="controls"><textarea></textarea></div> </div> <div class="fp-login-select control-group clearfix"> <label class="control-label"></label> <div class="controls"><select></select></div> </div>'; $rv .= ' <div class="fp-login-input control-group clearfix"> <label class="control-label"></label> <div class="controls"><input/></div> </div> <div class="fp-login-radiogroup control-group clearfix"> <label class="control-label"></label> <div class="controls fp-login-radio"><input /> <label></label></div> </div> </div> <p><button class="fp-login-submit btn-primary btn">'.get_string('submit', 'repository').'</button></p> </form> </div> </div>'; return $rv; } /** * Returns all FilePicker JavaScript templates as an array. * * @return array */ public function filepicker_js_templates() { $class_methods = get_class_methods($this); $templates = array(); foreach ($class_methods as $method_name) { if (preg_match('/^fp_js_template_(.*)$/', $method_name, $matches)) $templates[$matches[1]] = $this->$method_name(); } return $templates; } /** * Returns HTML for default repository searchform to be passed to Filepicker * * This will be used as contents for search form defined in generallayout template * (form with id {TOOLSEARCHID}). * Default contents is one text input field with name="s" */ public function repository_default_searchform() { $searchinput = html_writer::label(get_string('searchrepo', 'repository'), 'reposearch', false, array('class' => 'accesshide')); $searchinput .= html_writer::empty_tag('input', array('type' => 'text', 'id' => 'reposearch', 'name' => 's', 'value' => get_string('search', 'repository'))); $str = html_writer::tag('div', $searchinput, array('class' => "fp-def-search")); return $str; } } /** * Data structure representing a general moodle file tree viewer * * @copyright 2010 Dongsheng Cai * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since Moodle 2.0 */ class files_tree_viewer implements renderable { public $tree; public $path; public $context; /** * Constructor of moodle_file_tree_viewer class * @param file_info $file_info * @param array $options */ public function __construct(file_info $file_info, array $options = null) { global $CFG; //note: this MUST NOT use get_file_storage() !!!!!!!!!!!!!!!!!!!!!!!!!!!! $this->options = (array)$options; $this->context = $options['context']; $this->tree = array(); $children = $file_info->get_children(); $current_file_params = $file_info->get_params(); $parent_info = $file_info->get_parent(); $level = $parent_info; $this->path = array(); while ($level) { $params = $level->get_params(); $context = context::instance_by_id($params['contextid']); // $this->context is current context if ($context->id != $this->context->id or empty($params['filearea'])) { break; } // unset unused parameters unset($params['component']); unset($params['filearea']); unset($params['filename']); unset($params['itemid']); $url = new moodle_url('/files/index.php', $params); $this->path[] = html_writer::link($url, $level->get_visible_name()); $level = $level->get_parent(); } $this->path = array_reverse($this->path); if ($current_file_params['filepath'] != '/') { $this->path[] = $file_info->get_visible_name(); } foreach ($children as $child) { $filedate = $child->get_timemodified(); $filesize = $child->get_filesize(); $mimetype = $child->get_mimetype(); $params = $child->get_params(); unset($params['component']); unset($params['filearea']); unset($params['filename']); unset($params['itemid']); $fileitem = array( 'params' => $params, 'filename' => $child->get_visible_name(), 'mimetype' => $child->get_mimetype(), 'filedate' => $filedate ? $filedate : '', 'filesize' => $filesize ? $filesize : '' ); $url = new moodle_url('/files/index.php', $params); if ($child->is_directory()) { $fileitem['isdir'] = true; $fileitem['url'] = $url->out(false); } else { $fileitem['url'] = $child->get_url(); } $this->tree[] = $fileitem; } } }
mrmark/moodle
files/renderer.php
PHP
gpl-3.0
53,064
/* =========================================================================== Wolfenstein: Enemy Territory GPL Source Code Copyright (C) 1999-2010 id Software LLC, a ZeniMax Media company. This file is part of the Wolfenstein: Enemy Territory GPL Source Code (“Wolf ET Source Code”). Wolf ET Source Code 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. Wolf ET Source 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 for more details. You should have received a copy of the GNU General Public License along with Wolf ET Source Code. If not, see <http://www.gnu.org/licenses/>. In addition, the Wolf: ET Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Wolf ET Source Code. If not, please request a copy in writing from id Software at the address below. If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA. =========================================================================== */ //=========================================================================== // // Name: aas_store.h // Function: // Programmer: Mr Elusive ([email protected]) // Last update: 1997-12-04 // Tab Size: 3 //=========================================================================== #define AAS_MAX_BBOXES 5 #define AAS_MAX_VERTEXES 512000 #define AAS_MAX_PLANES 65536 #define AAS_MAX_EDGES 512000 #define AAS_MAX_EDGEINDEXSIZE 512000 #define AAS_MAX_FACES 512000 #define AAS_MAX_FACEINDEXSIZE 512000 #define AAS_MAX_AREAS 65536 #define AAS_MAX_AREASETTINGS 65536 #define AAS_MAX_REACHABILITYSIZE 128000 #define AAS_MAX_NODES 256000 #define AAS_MAX_PORTALS 65536 #define AAS_MAX_PORTALINDEXSIZE 65536 #define AAS_MAX_CLUSTERS 65536 #define BSPCINCLUDE #include "../game/be_aas.h" #include "../botlib/be_aas_def.h" /* typedef struct bspc_aas_s { int loaded; int initialized; //true when AAS has been initialized int savefile; //set true when file should be saved //bounding boxes int numbboxes; aas_bbox_t *bboxes; //vertexes int numvertexes; aas_vertex_t *vertexes; //planes int numplanes; aas_plane_t *planes; //edges int numedges; aas_edge_t *edges; //edge index int edgeindexsize; aas_edgeindex_t *edgeindex; //faces int numfaces; aas_face_t *faces; //face index int faceindexsize; aas_faceindex_t *faceindex; //convex areas int numareas; aas_area_t *areas; //convex area settings int numareasettings; aas_areasettings_t *areasettings; //reachablity list int reachabilitysize; aas_reachability_t *reachability; //nodes of the bsp tree int numnodes; aas_node_t *nodes; //cluster portals int numportals; aas_portal_t *portals; //cluster portal index int portalindexsize; aas_portalindex_t *portalindex; //clusters int numclusters; aas_cluster_t *clusters; // int numreachabilityareas; float reachabilitytime; } bspc_aas_t; extern bspc_aas_t aasworld; //*/ // Ridah extern aas_t aasworlds[1]; extern aas_t *aasworld; // done. //stores the AAS file from the temporary AAS void AAS_StoreFile( char *filename ); //returns a number of the given plane qboolean AAS_FindPlane( vec3_t normal, float dist, int *planenum ); //allocates the maximum AAS memory for storage void AAS_AllocMaxAAS( void ); //frees the maximum AAS memory for storage void AAS_FreeMaxAAS( void );
ensiform/ETe
src/bspc/aas_store.h
C
gpl-3.0
4,156
/******************************************************************************* * * Copyright (c) 2010-2015 Edans Sandes * * This file is part of MASA-Core. * * MASA-Core 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. * * MASA-Core 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 MASA-Core. If not, see <http://www.gnu.org/licenses/>. * ******************************************************************************/ #ifndef LIBMASATYPES_HPP_ #define LIBMASATYPES_HPP_ /** * Struct that represents a cell in the DP matrix. See the Smith-Waterman * recurrence function with the gotoh affine gap modification. * * Each cell has three components: H, E and F. But note that the E and F * components holds the same memory area, because the E and F components are a * union. So, the cell structure may represent only two components simultaneously, * the \f$(H,F)\f$ components or the \f$(H,E)\f$ components. */ typedef struct { int h; union { int f; int e; }; } __attribute__ ((aligned (8))) cell_t; /** * Infinity number used in the cells of the DP matrix. */ #define INF (999999999) /** * Struct that notifies the match result in the Mayers-Miller matching procedure. */ typedef struct { /** true if the matching procedure found the goal score */ bool found; /** index of the matched score */ int k; /** matched score */ int score; /** type of the match: MATCH_ALIGNED or MATCH_GAPPED */ int type; } match_result_t; /** * Indicates that the matching procedure found the goal score adding the H * component of both rows. */ #define MATCH_ALIGNED (0) /** * Indicates that the matching procedure found the goal score adding the E * component of both rows (minus the GAP_OPENING penalty). */ #define MATCH_GAPPED (1) /** * Indicates that the matching procedure failed with (sum_match > goalScore) */ #define MATCH_ERROR_1 (-1) /** * Indicates that the matching procedure failed with (sum_gap > goalScore) */ #define MATCH_ERROR_2 (-2) /** * Represents a score in the DP matrix. */ typedef struct { /** i-coordinate of the score */ int i; /** j-coordinate of the score */ int j; /** value of the score */ int score; } score_t; /** * Defines the match/mismatch score and affine gap penalties. */ typedef struct { /** match score (positive). */ int match; /** mismatch penalty (negative). */ int mismatch; /** gap opening penalty (positive). */ int gap_open; /** gap extension penalty (positive). */ int gap_ext; } score_params_t; #endif /* LIBMASATYPES_HPP_ */
edanssandes/MASA-Serial
masa-serial-1.0.1.1024/libs/masa-core/src/libmasa/libmasaTypes.hpp
C++
gpl-3.0
2,994
/* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2014 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Rasmus Lerdorf <[email protected]> | | Marcus Boerger <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #ifndef PHP_IMAGE_H #define PHP_IMAGE_H PHP_FUNCTION(getimagesize); PHP_FUNCTION(getimagesizefromstring); PHP_FUNCTION(image_type_to_mime_type); PHP_FUNCTION(image_type_to_extension); /* {{{ enum image_filetype This enum is used to have ext/standard/image.c and ext/exif/exif.c use the same constants for file types. */ typedef enum { IMAGE_FILETYPE_UNKNOWN=0, IMAGE_FILETYPE_GIF=1, IMAGE_FILETYPE_JPEG, IMAGE_FILETYPE_PNG, IMAGE_FILETYPE_SWF, IMAGE_FILETYPE_PSD, IMAGE_FILETYPE_BMP, IMAGE_FILETYPE_TIFF_II, /* intel */ IMAGE_FILETYPE_TIFF_MM, /* motorola */ IMAGE_FILETYPE_JPC, IMAGE_FILETYPE_JP2, IMAGE_FILETYPE_JPX, IMAGE_FILETYPE_JB2, IMAGE_FILETYPE_SWC, IMAGE_FILETYPE_IFF, IMAGE_FILETYPE_WBMP, /* IMAGE_FILETYPE_JPEG2000 is a userland alias for IMAGE_FILETYPE_JPC */ IMAGE_FILETYPE_XBM, IMAGE_FILETYPE_ICO, /* WHEN EXTENDING: PLEASE ALSO REGISTER IN image.c:PHP_MINIT_FUNCTION(imagetypes) */ IMAGE_FILETYPE_COUNT } image_filetype; /* }}} */ PHP_MINIT_FUNCTION(imagetypes); PHPAPI int php_getimagetype(php_stream *stream, char *filetype TSRMLS_DC); PHPAPI char * php_image_type_to_mime_type(int image_type); #endif /* PHP_IMAGE_H */
tukusejssirs/eSpievatko
spievatko/espievatko/prtbl/srv/php-5.5.11/ext/standard/php_image.h
C
gpl-3.0
2,424
<?php /** * * Copyright (C) 2007,2008 Arie Nugraha ([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 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 * */ /* Global application configuration */ // key to authenticate define('INDEX_AUTH', '1'); // key to get full database access define('DB_ACCESS', 'fa'); if (!defined('SB')) { // main system configuration require '../../../sysconfig.inc.php'; // start the session require SB.'admin/default/session.inc.php'; } // IP based access limitation require LIB.'ip_based_access.inc.php'; do_checkIP('smc'); do_checkIP('smc-system'); // only administrator have privileges to change global settings if ($_SESSION['uid'] != 1) { header('Location: '.MWB.'system/content.php'); die(); } require SB.'admin/default/session_check.inc.php'; require SIMBIO.'simbio_FILE/simbio_directory.inc.php'; require SIMBIO.'simbio_GUI/form_maker/simbio_form_table_AJAX.inc.php'; require SIMBIO.'simbio_GUI/table/simbio_table.inc.php'; require SIMBIO.'simbio_DB/simbio_dbop.inc.php'; ?> <fieldset class="menuBox"> <div class="menuBoxInner systemIcon"> <div class="per_title"> <h2><?php echo __('System Configuration'); ?></h2> </div> <div class="infoBox"> <?php echo __('Modify global application preferences'); ?> </div> </div> </fieldset> <?php /* main content */ /* Config Vars EDIT FORM */ /* Config Vars update process */ if (isset($_POST['updateData'])) { // reset/truncate setting table content // library name $library_name = $dbs->escape_string(strip_tags(trim($_POST['library_name']))); $dbs->query('UPDATE setting SET setting_value=\''.$dbs->escape_string(serialize($library_name)).'\' WHERE setting_name=\'library_name\''); // library subname $library_subname = $dbs->escape_string(strip_tags(trim($_POST['library_subname']))); $dbs->query('UPDATE setting SET setting_value=\''.$dbs->escape_string(serialize($library_subname)).'\' WHERE setting_name=\'library_subname\''); // initialize template arrays $template = array('theme' => $sysconf['template']['theme'], 'css' => $sysconf['template']['css']); $admin_template = array('theme' => $sysconf['admin_template']['theme'], 'css' => $sysconf['admin_template']['css']); // template $template['theme'] = $_POST['template']; $template['css'] = str_replace($sysconf['template']['theme'], $template['theme'], $sysconf['template']['css']); $dbs->query('UPDATE setting SET setting_value=\''.$dbs->escape_string(serialize($template)).'\' WHERE setting_name=\'template\''); // admin template $admin_template['theme'] = $_POST['admin_template']; $admin_template['css'] = str_replace($sysconf['admin_template']['theme'], $admin_template['theme'], $sysconf['admin_template']['css']); $dbs->query('UPDATE setting SET setting_value=\''.$dbs->escape_string(serialize($admin_template)).'\' WHERE setting_name=\'admin_template\''); // language $dbs->query('UPDATE setting SET setting_value=\''.$dbs->escape_string(serialize($_POST['default_lang'])).'\' WHERE setting_name=\'default_lang\''); // opac num result $dbs->query('UPDATE setting SET setting_value=\''.$dbs->escape_string(serialize($_POST['opac_result_num'])).'\' WHERE setting_name=\'opac_result_num\''); // promoted titles in homepage if (isset($_POST['enable_promote_titles'])) { $dbs->query('UPDATE setting SET setting_value=\''.$dbs->escape_string(serialize($_POST['enable_promote_titles'])).'\' WHERE setting_name=\'enable_promote_titles\''); } else { $dbs->query('UPDATE setting SET setting_value=\'N;\' WHERE setting_name=\'enable_promote_titles\''); } // quick return $quick_return = $_POST['quick_return'] == '1'?true:false; $dbs->query('UPDATE setting SET setting_value=\''.$dbs->escape_string(serialize($quick_return)).'\' WHERE setting_name=\'quick_return\''); // loan and due date manual change $circulation_receipt = $_POST['circulation_receipt'] == '1'?true:false; $dbs->query('UPDATE setting SET setting_value=\''.$dbs->escape_string(serialize($circulation_receipt)).'\' WHERE setting_name=\'circulation_receipt\''); // loan and due date manual change $allow_loan_date_change = $_POST['allow_loan_date_change'] == '1'?true:false; $dbs->query('UPDATE setting SET setting_value=\''.$dbs->escape_string(serialize($allow_loan_date_change)).'\' WHERE setting_name=\'allow_loan_date_change\''); // loan limit override $loan_limit_override = $_POST['loan_limit_override'] == '1'?true:false; $dbs->query('UPDATE setting SET setting_value=\''.$dbs->escape_string(serialize($loan_limit_override)).'\' WHERE setting_name=\'loan_limit_override\''); // ignore holidays fine calculation // added by Indra Sutriadi $ignore_holidays_fine_calc = $_POST['ignore_holidays_fine_calc'] == '1'?true:false; $dbs->query('UPDATE setting SET setting_value=\''.$dbs->escape_string(serialize($ignore_holidays_fine_calc)).'\' WHERE setting_name=\'ignore_holidays_fine_calc\''); // xml detail $xml_detail = $_POST['enable_xml_detail'] == '1'?true:false; $dbs->query('UPDATE setting SET setting_value=\''.$dbs->escape_string(serialize($xml_detail)).'\' WHERE setting_name=\'enable_xml_detail\''); // xml result $xml_result = $_POST['enable_xml_result'] == '1'?true:false; $dbs->query('UPDATE setting SET setting_value=\''.$dbs->escape_string(serialize($xml_result)).'\' WHERE setting_name=\'enable_xml_result\''); // file download $file_download = $_POST['allow_file_download'] == '1'?true:false; $dbs->query('UPDATE setting SET setting_value=\''.$dbs->escape_string(serialize($file_download)).'\' WHERE setting_name=\'allow_file_download\''); // session timeout $session_timeout = intval($_POST['session_timeout']) >= 1800?$_POST['session_timeout']:1800; $dbs->query('UPDATE setting SET setting_value=\''.$dbs->escape_string(serialize($session_timeout)).'\' WHERE setting_name=\'session_timeout\''); // barcode encoding $dbs->query('UPDATE setting SET setting_value=\''.$dbs->escape_string(serialize($_POST['barcode_encoding'])).'\' WHERE setting_name=\'barcode_encoding\''); // spellchecker $spellchecker_enabled = $_POST['spellchecker_enabled'] == '1'?true:false; $dbs->query('REPLACE INTO setting (setting_value, setting_name) VALUES (\''.serialize($spellchecker_enabled).'\', \'spellchecker_enabled\')'); // write log utility::writeLogs($dbs, 'staff', $_SESSION['uid'], 'system', $_SESSION['realname'].' change application global configuration'); utility::jsAlert(__('Settings saved. Refreshing page')); echo '<script type="text/javascript">parent.location.href = \'../../index.php?mod=system\';</script>'; } /* Config Vars update process end */ // create new instance $form = new simbio_form_table_AJAX('mainForm', $_SERVER['PHP_SELF'], 'post'); $form->submit_button_attr = 'name="updateData" value="'.__('Save Settings').'" class="btn btn-default"'; // form table attributes $form->table_attr = 'align="center" id="dataList" cellpadding="5" cellspacing="0"'; $form->table_header_attr = 'class="alterCell" style="font-weight: bold;"'; $form->table_content_attr = 'class="alterCell2"'; // load settings from database utility::loadSettings($dbs); // version status $form->addAnything('Senayan Version', '<strong>'.SENAYAN_VERSION.'</strong>'); // library name $form->addTextField('text', 'library_name', __('Library Name'), $sysconf['library_name'], 'style="width: 100%;"'); // library subname $form->addTextField('text', 'library_subname', __('Library Subname'), $sysconf['library_subname'], 'style="width: 100%;"'); /* Form Element(s) */ // public template // scan template directory $template_dir = SB.$sysconf['template']['dir']; $dir = new simbio_directory($template_dir); $dir_tree = $dir->getDirectoryTree(1); // sort array by index ksort($dir_tree); // loop array foreach ($dir_tree as $dir) { $tpl_options[] = array($dir, $dir); } $form->addSelectList('template', __('Public Template'), $tpl_options, $sysconf['template']['theme']); // admin template // scan admin template directory $admin_template_dir = SB.'admin'.DS.$sysconf['admin_template']['dir']; $dir = new simbio_directory($admin_template_dir); $dir_tree = $dir->getDirectoryTree(1); // sort array by index ksort($dir_tree); // loop array foreach ($dir_tree as $dir) { $admin_tpl_options[] = array($dir, $dir); } $form->addSelectList('admin_template', __('Admin Template'), $admin_tpl_options, $sysconf['admin_template']['theme']); // application language require_once(LANG.'localisation.php'); $form->addSelectList('default_lang', __('Default App. Language'), $available_languages, $sysconf['default_lang']); // opac result list number $result_num_options[] = array('10', '10'); $result_num_options[] = array('20', '20'); $result_num_options[] = array('30', '30'); $result_num_options[] = array('40', '40'); $result_num_options[] = array('50', '50'); $form->addSelectList('opac_result_num', __('Number Of Collections To Show In OPAC Result List'), $result_num_options, $sysconf['opac_result_num'] ); // homepage setting $promote_options[] = array('1', 'Yes'); $form->addCheckBox('enable_promote_titles', __('Show Promoted Titles at Homepage'), $promote_options, $sysconf['enable_promote_titles']?'1':'0'); // enable quick return $options = null; $options[] = array('0', __('Disable')); $options[] = array('1', __('Enable')); $form->addSelectList('quick_return', __('Quick Return'), $options, $sysconf['quick_return']?'1':'0'); // circulation receipt $options = null; $options[] = array('0', __('Don\'t Print')); $options[] = array('1', __('Print')); $form->addSelectList('circulation_receipt', __('Print Circulation Receipt'), $options, $sysconf['circulation_receipt']?'1':'0'); // enable manual changes of loan and due date in circulation transaction $options = null; $options[] = array('0', __('Disable')); $options[] = array('1', __('Enable')); $form->addSelectList('allow_loan_date_change', __('Loan and Due Date Manual Change'), $options, $sysconf['allow_loan_date_change']?'1':'0'); // enable loan limit overriden $options = null; $options[] = array('0', __('Disable')); $options[] = array('1', __('Enable')); $form->addSelectList('loan_limit_override', __('Loan Limit Override'), $options, $sysconf['loan_limit_override']?'1':'0'); // enable ignore holidays fine calc // added by Indra Sutriadi $options = null; $options[] = array('0', __('Disable')); $options[] = array('1', __('Enable')); $form->addSelectList('ignore_holidays_fine_calc', __('Ignore Holidays Fine Calculation'), $options, $sysconf['ignore_holidays_fine_calc']?'1':'0'); // enable bibliography xml detail $options = null; $options[] = array('0', __('Disable')); $options[] = array('1', __('Enable')); $form->addSelectList('enable_xml_detail', __('OPAC XML Detail'), $options, $sysconf['enable_xml_detail']?'1':'0'); // enable bibliography xml result set $options = null; $options[] = array('0', __('Disable')); $options[] = array('1', __('Enable')); $form->addSelectList('enable_xml_result', __('OPAC XML Result'), $options, $sysconf['enable_xml_result']?'1':'0'); // enable spell checker on search $options = null; $options[] = array('0', __('Disable')); $options[] = array('1', __('Enable')); $form->addSelectList('spellchecker_enabled', __('Enable Search Spellchecker'), $options, $sysconf['spellchecker_enabled']?'1':'0'); // allow file attachment download $options = null; $options[] = array('0', __('Forbid')); $options[] = array('1', __('Allow')); $form->addSelectList('allow_file_download', __('Allow OPAC File Download'), $options, $sysconf['allow_file_download']?'1':'0'); // session timeout $form->addTextField('text', 'session_timeout', __('Session Login Timeout'), $sysconf['session_timeout'], 'style="width: 10%;"'); // barcode encoding $form->addSelectList('barcode_encoding', __('Barcode Encoding'), $barcodes_encoding, $sysconf['barcode_encoding'] ); // print out the object echo $form->printOut(); /* main content end */
slims/slims7_cendana
admin/modules/system/index.php
PHP
gpl-3.0
12,728
#include "AP_Avoidance.h" #if HAL_ADSB_ENABLED extern const AP_HAL::HAL& hal; #include <limits> #include <AP_AHRS/AP_AHRS.h> #include <GCS_MAVLink/GCS.h> #define AVOIDANCE_DEBUGGING 0 #if APM_BUILD_TYPE(APM_BUILD_ArduPlane) #define AP_AVOIDANCE_WARN_TIME_DEFAULT 30 #define AP_AVOIDANCE_FAIL_TIME_DEFAULT 30 #define AP_AVOIDANCE_WARN_DISTANCE_XY_DEFAULT 1000 #define AP_AVOIDANCE_WARN_DISTANCE_Z_DEFAULT 300 #define AP_AVOIDANCE_FAIL_DISTANCE_XY_DEFAULT 300 #define AP_AVOIDANCE_FAIL_DISTANCE_Z_DEFAULT 100 #define AP_AVOIDANCE_RECOVERY_DEFAULT RecoveryAction::RESUME_IF_AUTO_ELSE_LOITER #define AP_AVOIDANCE_FAIL_ACTION_DEFAULT MAV_COLLISION_ACTION_REPORT #else // APM_BUILD_TYPE(APM_BUILD_ArduCopter),Heli, Rover, Boat #define AP_AVOIDANCE_WARN_TIME_DEFAULT 30 #define AP_AVOIDANCE_FAIL_TIME_DEFAULT 30 #define AP_AVOIDANCE_WARN_DISTANCE_XY_DEFAULT 300 #define AP_AVOIDANCE_WARN_DISTANCE_Z_DEFAULT 300 #define AP_AVOIDANCE_FAIL_DISTANCE_XY_DEFAULT 100 #define AP_AVOIDANCE_FAIL_DISTANCE_Z_DEFAULT 100 #define AP_AVOIDANCE_RECOVERY_DEFAULT RecoveryAction::RTL #define AP_AVOIDANCE_FAIL_ACTION_DEFAULT MAV_COLLISION_ACTION_REPORT #endif #if AVOIDANCE_DEBUGGING #include <stdio.h> #define debug(fmt, args ...) do {::fprintf(stderr,"%s:%d: " fmt "\n", __FUNCTION__, __LINE__, ## args); } while(0) #else #define debug(fmt, args ...) #endif // table of user settable parameters const AP_Param::GroupInfo AP_Avoidance::var_info[] = { // @Param: ENABLE // @DisplayName: Enable Avoidance using ADSB // @Description: Enable Avoidance using ADSB // @Values: 0:Disabled,1:Enabled // @User: Advanced AP_GROUPINFO_FLAGS("ENABLE", 1, AP_Avoidance, _enabled, 0, AP_PARAM_FLAG_ENABLE), // @Param: F_ACTION // @DisplayName: Collision Avoidance Behavior // @Description: Specifies aircraft behaviour when a collision is imminent // @Values: 0:None,1:Report,2:Climb Or Descend,3:Move Horizontally,4:Move Perpendicularly in 3D,5:RTL,6:Hover // @User: Advanced AP_GROUPINFO("F_ACTION", 2, AP_Avoidance, _fail_action, AP_AVOIDANCE_FAIL_ACTION_DEFAULT), // @Param: W_ACTION // @DisplayName: Collision Avoidance Behavior - Warn // @Description: Specifies aircraft behaviour when a collision may occur // @Values: 0:None,1:Report // @User: Advanced AP_GROUPINFO("W_ACTION", 3, AP_Avoidance, _warn_action, MAV_COLLISION_ACTION_REPORT), // @Param: F_RCVRY // @DisplayName: Recovery behaviour after a fail event // @Description: Determines what the aircraft will do after a fail event is resolved // @Values: 0:Remain in AVOID_ADSB,1:Resume previous flight mode,2:RTL,3:Resume if AUTO else Loiter // @User: Advanced AP_GROUPINFO("F_RCVRY", 4, AP_Avoidance, _fail_recovery, uint8_t(AP_AVOIDANCE_RECOVERY_DEFAULT)), // @Param: OBS_MAX // @DisplayName: Maximum number of obstacles to track // @Description: Maximum number of obstacles to track // @User: Advanced AP_GROUPINFO("OBS_MAX", 5, AP_Avoidance, _obstacles_max, 20), // @Param: W_TIME // @DisplayName: Time Horizon Warn // @Description: Aircraft velocity vectors are multiplied by this time to determine closest approach. If this results in an approach closer than W_DIST_XY or W_DIST_Z then W_ACTION is undertaken (assuming F_ACTION is not undertaken) // @Units: s // @User: Advanced AP_GROUPINFO("W_TIME", 6, AP_Avoidance, _warn_time_horizon, AP_AVOIDANCE_WARN_TIME_DEFAULT), // @Param: F_TIME // @DisplayName: Time Horizon Fail // @Description: Aircraft velocity vectors are multiplied by this time to determine closest approach. If this results in an approach closer than F_DIST_XY or F_DIST_Z then F_ACTION is undertaken // @Units: s // @User: Advanced AP_GROUPINFO("F_TIME", 7, AP_Avoidance, _fail_time_horizon, AP_AVOIDANCE_FAIL_TIME_DEFAULT), // @Param: W_DIST_XY // @DisplayName: Distance Warn XY // @Description: Closest allowed projected distance before W_ACTION is undertaken // @Units: m // @User: Advanced AP_GROUPINFO("W_DIST_XY", 8, AP_Avoidance, _warn_distance_xy, AP_AVOIDANCE_WARN_DISTANCE_XY_DEFAULT), // @Param: F_DIST_XY // @DisplayName: Distance Fail XY // @Description: Closest allowed projected distance before F_ACTION is undertaken // @Units: m // @User: Advanced AP_GROUPINFO("F_DIST_XY", 9, AP_Avoidance, _fail_distance_xy, AP_AVOIDANCE_FAIL_DISTANCE_XY_DEFAULT), // @Param: W_DIST_Z // @DisplayName: Distance Warn Z // @Description: Closest allowed projected distance before BEHAVIOUR_W is undertaken // @Units: m // @User: Advanced AP_GROUPINFO("W_DIST_Z", 10, AP_Avoidance, _warn_distance_z, AP_AVOIDANCE_WARN_DISTANCE_Z_DEFAULT), // @Param: F_DIST_Z // @DisplayName: Distance Fail Z // @Description: Closest allowed projected distance before BEHAVIOUR_F is undertaken // @Units: m // @User: Advanced AP_GROUPINFO("F_DIST_Z", 11, AP_Avoidance, _fail_distance_z, AP_AVOIDANCE_FAIL_DISTANCE_Z_DEFAULT), // @Param: F_ALT_MIN // @DisplayName: ADS-B avoidance minimum altitude // @Description: Minimum AMSL (above mean sea level) altitude for ADS-B avoidance. If the vehicle is below this altitude, no avoidance action will take place. Useful to prevent ADS-B avoidance from activating while below the tree line or around structures. Default of 0 is no minimum. // @Units: m // @User: Advanced AP_GROUPINFO("F_ALT_MIN", 12, AP_Avoidance, _fail_altitude_minimum, 0), AP_GROUPEND }; AP_Avoidance::AP_Avoidance(AP_ADSB &adsb) : _adsb(adsb) { AP_Param::setup_object_defaults(this, var_info); if (_singleton != nullptr) { AP_HAL::panic("AP_Avoidance must be singleton"); } _singleton = this; } /* * Initialize variables and allocate memory for array */ void AP_Avoidance::init(void) { debug("ADSB initialisation: %d obstacles", _obstacles_max.get()); if (_obstacles == nullptr) { _obstacles = new AP_Avoidance::Obstacle[_obstacles_max]; if (_obstacles == nullptr) { // dynamic RAM allocation of _obstacles[] failed, disable gracefully hal.console->printf("Unable to initialize Avoidance obstacle list\n"); // disable ourselves to avoid repeated allocation attempts _enabled.set(0); return; } _obstacles_allocated = _obstacles_max; } _obstacle_count = 0; _last_state_change_ms = 0; _threat_level = MAV_COLLISION_THREAT_LEVEL_NONE; _gcs_cleared_messages_first_sent = std::numeric_limits<uint32_t>::max(); _current_most_serious_threat = -1; } /* * de-initialize and free up some memory */ void AP_Avoidance::deinit(void) { if (_obstacles != nullptr) { delete [] _obstacles; _obstacles = nullptr; _obstacles_allocated = 0; handle_recovery(RecoveryAction::RTL); } _obstacle_count = 0; } bool AP_Avoidance::check_startup() { if (!_enabled) { if (_obstacles != nullptr) { deinit(); } // nothing to do return false; } if (_obstacles == nullptr) { init(); } return _obstacles != nullptr; } // vel is north/east/down! void AP_Avoidance::add_obstacle(const uint32_t obstacle_timestamp_ms, const MAV_COLLISION_SRC src, const uint32_t src_id, const Location &loc, const Vector3f &vel_ned) { if (! check_startup()) { return; } uint32_t oldest_timestamp = std::numeric_limits<uint32_t>::max(); uint8_t oldest_index = 255; // avoid compiler warning with initialisation int16_t index = -1; uint8_t i; for (i=0; i<_obstacle_count; i++) { if (_obstacles[i].src_id == src_id && _obstacles[i].src == src) { // pre-existing obstacle found; we will update its information index = i; break; } if (_obstacles[i].timestamp_ms < oldest_timestamp) { oldest_timestamp = _obstacles[i].timestamp_ms; oldest_index = i; } } WITH_SEMAPHORE(_rsem); if (index == -1) { // existing obstacle not found. See if we can store it anyway: if (i <_obstacles_allocated) { // have room to store more vehicles... index = _obstacle_count++; } else if (oldest_timestamp < obstacle_timestamp_ms) { // replace this very old entry with this new data index = oldest_index; } else { // no room for this (old?!) data return; } _obstacles[index].src = src; _obstacles[index].src_id = src_id; } _obstacles[index]._location = loc; _obstacles[index]._velocity = vel_ned; _obstacles[index].timestamp_ms = obstacle_timestamp_ms; } void AP_Avoidance::add_obstacle(const uint32_t obstacle_timestamp_ms, const MAV_COLLISION_SRC src, const uint32_t src_id, const Location &loc, const float cog, const float hspeed, const float vspeed) { Vector3f vel; vel[0] = hspeed * cosf(radians(cog)); vel[1] = hspeed * sinf(radians(cog)); vel[2] = vspeed; // debug("cog=%f hspeed=%f veln=%f vele=%f", cog, hspeed, vel[0], vel[1]); return add_obstacle(obstacle_timestamp_ms, src, src_id, loc, vel); } uint32_t AP_Avoidance::src_id_for_adsb_vehicle(const AP_ADSB::adsb_vehicle_t &vehicle) const { // TODO: need to include squawk code and callsign return vehicle.info.ICAO_address; } void AP_Avoidance::get_adsb_samples() { AP_ADSB::adsb_vehicle_t vehicle; while (_adsb.next_sample(vehicle)) { uint32_t src_id = src_id_for_adsb_vehicle(vehicle); Location loc = _adsb.get_location(vehicle); add_obstacle(vehicle.last_update_ms, MAV_COLLISION_SRC_ADSB, src_id, loc, vehicle.info.heading * 0.01, vehicle.info.hor_velocity * 0.01, -vehicle.info.ver_velocity * 0.01); // convert cm-up to m-down } } float closest_approach_xy(const Location &my_loc, const Vector3f &my_vel, const Location &obstacle_loc, const Vector3f &obstacle_vel, const uint8_t time_horizon) { Vector2f delta_vel_ne = Vector2f(obstacle_vel[0] - my_vel[0], obstacle_vel[1] - my_vel[1]); const Vector2f delta_pos_ne = obstacle_loc.get_distance_NE(my_loc); Vector2f line_segment_ne = delta_vel_ne * time_horizon; float ret = Vector2<float>::closest_distance_between_radial_and_point (line_segment_ne, delta_pos_ne); debug(" time_horizon: (%d)", time_horizon); debug(" delta pos: (y=%f,x=%f)", delta_pos_ne[0], delta_pos_ne[1]); debug(" delta vel: (y=%f,x=%f)", delta_vel_ne[0], delta_vel_ne[1]); debug(" line segment: (y=%f,x=%f)", line_segment_ne[0], line_segment_ne[1]); debug(" closest: (%f)", ret); return ret; } // returns the closest these objects will get in the body z axis (in metres) float closest_approach_z(const Location &my_loc, const Vector3f &my_vel, const Location &obstacle_loc, const Vector3f &obstacle_vel, const uint8_t time_horizon) { float delta_vel_d = obstacle_vel[2] - my_vel[2]; float delta_pos_d = obstacle_loc.alt - my_loc.alt; float ret; if (delta_pos_d >= 0 && delta_vel_d >= 0) { ret = delta_pos_d; } else if (delta_pos_d <= 0 && delta_vel_d <= 0) { ret = fabsf(delta_pos_d); } else { ret = fabsf(delta_pos_d - delta_vel_d * time_horizon); } debug(" time_horizon: (%d)", time_horizon); debug(" delta pos: (%f) metres", delta_pos_d/100.0f); debug(" delta vel: (%f) m/s", delta_vel_d); debug(" closest: (%f) metres", ret/100.0f); return ret/100.0f; } void AP_Avoidance::update_threat_level(const Location &my_loc, const Vector3f &my_vel, AP_Avoidance::Obstacle &obstacle) { Location &obstacle_loc = obstacle._location; Vector3f &obstacle_vel = obstacle._velocity; obstacle.threat_level = MAV_COLLISION_THREAT_LEVEL_NONE; const uint32_t obstacle_age = AP_HAL::millis() - obstacle.timestamp_ms; float closest_xy = closest_approach_xy(my_loc, my_vel, obstacle_loc, obstacle_vel, _fail_time_horizon + obstacle_age/1000); if (closest_xy < _fail_distance_xy) { obstacle.threat_level = MAV_COLLISION_THREAT_LEVEL_HIGH; } else { closest_xy = closest_approach_xy(my_loc, my_vel, obstacle_loc, obstacle_vel, _warn_time_horizon + obstacle_age/1000); if (closest_xy < _warn_distance_xy) { obstacle.threat_level = MAV_COLLISION_THREAT_LEVEL_LOW; } } // check for vertical separation; our threat level is the minimum // of vertical and horizontal threat levels float closest_z = closest_approach_z(my_loc, my_vel, obstacle_loc, obstacle_vel, _warn_time_horizon + obstacle_age/1000); if (obstacle.threat_level != MAV_COLLISION_THREAT_LEVEL_NONE) { if (closest_z > _warn_distance_z) { obstacle.threat_level = MAV_COLLISION_THREAT_LEVEL_NONE; } else { closest_z = closest_approach_z(my_loc, my_vel, obstacle_loc, obstacle_vel, _fail_time_horizon + obstacle_age/1000); if (closest_z > _fail_distance_z) { obstacle.threat_level = MAV_COLLISION_THREAT_LEVEL_LOW; } } } // If we haven't heard from a vehicle then assume it is no threat if (obstacle_age > MAX_OBSTACLE_AGE_MS) { obstacle.threat_level = MAV_COLLISION_THREAT_LEVEL_NONE; } // could optimise this to not calculate a lot of this if threat // level is none - but only *once the GCS has been informed*! obstacle.closest_approach_xy = closest_xy; obstacle.closest_approach_z = closest_z; float current_distance = my_loc.get_distance(obstacle_loc); obstacle.distance_to_closest_approach = current_distance - closest_xy; Vector2f net_velocity_ne = Vector2f(my_vel[0] - obstacle_vel[0], my_vel[1] - obstacle_vel[1]); obstacle.time_to_closest_approach = 0.0f; if (!is_zero(obstacle.distance_to_closest_approach) && ! is_zero(net_velocity_ne.length())) { obstacle.time_to_closest_approach = obstacle.distance_to_closest_approach / net_velocity_ne.length(); } } MAV_COLLISION_THREAT_LEVEL AP_Avoidance::current_threat_level() const { if (_obstacles == nullptr) { return MAV_COLLISION_THREAT_LEVEL_NONE; } if (_current_most_serious_threat == -1) { return MAV_COLLISION_THREAT_LEVEL_NONE; } return _obstacles[_current_most_serious_threat].threat_level; } void AP_Avoidance::send_collision_all(const AP_Avoidance::Obstacle &threat, MAV_COLLISION_ACTION behaviour) const { const mavlink_collision_t packet{ id: threat.src_id, time_to_minimum_delta: threat.time_to_closest_approach, altitude_minimum_delta: threat.closest_approach_z, horizontal_minimum_delta: threat.closest_approach_xy, src: MAV_COLLISION_SRC_ADSB, action: (uint8_t)behaviour, threat_level: (uint8_t)threat.threat_level, }; gcs().send_to_active_channels(MAVLINK_MSG_ID_COLLISION, (const char *)&packet); } void AP_Avoidance::handle_threat_gcs_notify(AP_Avoidance::Obstacle *threat) { if (threat == nullptr) { return; } uint32_t now = AP_HAL::millis(); if (threat->threat_level == MAV_COLLISION_THREAT_LEVEL_NONE) { // only send cleared messages for a few seconds: if (_gcs_cleared_messages_first_sent == 0) { _gcs_cleared_messages_first_sent = now; } if (now - _gcs_cleared_messages_first_sent > _gcs_cleared_messages_duration * 1000) { return; } } else { _gcs_cleared_messages_first_sent = 0; } if (now - threat->last_gcs_report_time > _gcs_notify_interval * 1000) { send_collision_all(*threat, mav_avoidance_action()); threat->last_gcs_report_time = now; } } bool AP_Avoidance::obstacle_is_more_serious_threat(const AP_Avoidance::Obstacle &obstacle) const { if (_current_most_serious_threat == -1) { // any threat is more of a threat than no threat return true; } const AP_Avoidance::Obstacle &current = _obstacles[_current_most_serious_threat]; if (obstacle.threat_level > current.threat_level) { // threat_level is updated by update_threat_level return true; } if (obstacle.threat_level == current.threat_level && obstacle.time_to_closest_approach < current.time_to_closest_approach) { return true; } return false; } void AP_Avoidance::check_for_threats() { const AP_AHRS &_ahrs = AP::ahrs(); Location my_loc; if (!_ahrs.get_position(my_loc)) { // if we don't know our own location we can't determine any threat level return; } Vector3f my_vel; if (!_ahrs.get_velocity_NED(my_vel)) { // assuming our own velocity to be zero here may cause us to // fly into something. Better not to attempt to avoid in this // case. return; } // we always check all obstacles to see if they are threats since it // is most likely our own position and/or velocity have changed // determine the current most-serious-threat _current_most_serious_threat = -1; for (uint8_t i=0; i<_obstacle_count; i++) { AP_Avoidance::Obstacle &obstacle = _obstacles[i]; const uint32_t obstacle_age = AP_HAL::millis() - obstacle.timestamp_ms; debug("i=%d src_id=%d timestamp=%u age=%d", i, obstacle.src_id, obstacle.timestamp_ms, obstacle_age); update_threat_level(my_loc, my_vel, obstacle); debug(" threat-level=%d", obstacle.threat_level); // ignore any really old data: if (obstacle_age > MAX_OBSTACLE_AGE_MS) { // shrink list if this is the last entry: if (i == _obstacle_count-1) { _obstacle_count -= 1; } continue; } if (obstacle_is_more_serious_threat(obstacle)) { _current_most_serious_threat = i; } } if (_current_most_serious_threat != -1) { debug("Current most serious threat: %d level=%d", _current_most_serious_threat, _obstacles[_current_most_serious_threat].threat_level); } } AP_Avoidance::Obstacle *AP_Avoidance::most_serious_threat() { if (_current_most_serious_threat < 0) { // we *really_ should not have been called! return nullptr; } return &_obstacles[_current_most_serious_threat]; } void AP_Avoidance::update() { if (!check_startup()) { return; } if (_adsb.enabled()) { get_adsb_samples(); } check_for_threats(); // avoid object (if necessary) handle_avoidance_local(most_serious_threat()); // notify GCS of most serious thread handle_threat_gcs_notify(most_serious_threat()); } void AP_Avoidance::handle_avoidance_local(AP_Avoidance::Obstacle *threat) { MAV_COLLISION_THREAT_LEVEL new_threat_level = MAV_COLLISION_THREAT_LEVEL_NONE; MAV_COLLISION_ACTION action = MAV_COLLISION_ACTION_NONE; if (threat != nullptr) { new_threat_level = threat->threat_level; if (new_threat_level == MAV_COLLISION_THREAT_LEVEL_HIGH) { action = (MAV_COLLISION_ACTION)_fail_action.get(); Location my_loc; if (action != MAV_COLLISION_ACTION_NONE && _fail_altitude_minimum > 0 && AP::ahrs().get_position(my_loc) && ((my_loc.alt*0.01f) < _fail_altitude_minimum)) { // disable avoidance when close to ground, report only action = MAV_COLLISION_ACTION_REPORT; } } } uint32_t now = AP_HAL::millis(); if (new_threat_level != _threat_level) { // transition to higher states immediately, recovery to lower states more slowly if (((now - _last_state_change_ms) > AP_AVOIDANCE_STATE_RECOVERY_TIME_MS) || (new_threat_level > _threat_level)) { // handle recovery from high threat level if (_threat_level == MAV_COLLISION_THREAT_LEVEL_HIGH) { handle_recovery(RecoveryAction(_fail_recovery.get())); _latest_action = MAV_COLLISION_ACTION_NONE; } // update state _last_state_change_ms = now; _threat_level = new_threat_level; } } // handle ongoing threat by calling vehicle specific handler if ((threat != nullptr) && (_threat_level == MAV_COLLISION_THREAT_LEVEL_HIGH) && (action > MAV_COLLISION_ACTION_REPORT)) { _latest_action = handle_avoidance(threat, action); } } void AP_Avoidance::handle_msg(const mavlink_message_t &msg) { if (!check_startup()) { // avoidance is not active / allocated return; } if (msg.msgid != MAVLINK_MSG_ID_GLOBAL_POSITION_INT) { // we only take position from GLOBAL_POSITION_INT return; } if (msg.sysid == mavlink_system.sysid) { // we do not obstruct ourselves.... return; } // inform AP_Avoidance we have a new player mavlink_global_position_int_t packet; mavlink_msg_global_position_int_decode(&msg, &packet); Location loc; loc.lat = packet.lat; loc.lng = packet.lon; loc.alt = packet.alt / 10; // mm -> cm loc.relative_alt = false; Vector3f vel = Vector3f(packet.vx/100.0f, // cm to m packet.vy/100.0f, packet.vz/100.0f); add_obstacle(AP_HAL::millis(), MAV_COLLISION_SRC_MAVLINK_GPS_GLOBAL_INT, msg.sysid, loc, vel); } // get unit vector away from the nearest obstacle bool AP_Avoidance::get_vector_perpendicular(const AP_Avoidance::Obstacle *obstacle, Vector3f &vec_neu) const { if (obstacle == nullptr) { // why where we called?! return false; } Location my_abs_pos; if (!AP::ahrs().get_position(my_abs_pos)) { // we should not get to here! If we don't know our position // we can't know if there are any threats, for starters! return false; } // if their velocity is moving around close to zero then flying // perpendicular to that velocity may mean we do weird things. // Instead, we will fly directly away from them if (obstacle->_velocity.length() < _low_velocity_threshold) { const Vector2f delta_pos_xy = obstacle->_location.get_distance_NE(my_abs_pos); const float delta_pos_z = my_abs_pos.alt - obstacle->_location.alt; Vector3f delta_pos_xyz = Vector3f(delta_pos_xy.x, delta_pos_xy.y, delta_pos_z); // avoid div by zero if (delta_pos_xyz.is_zero()) { return false; } delta_pos_xyz.normalize(); vec_neu = delta_pos_xyz; return true; } else { vec_neu = perpendicular_xyz(obstacle->_location, obstacle->_velocity, my_abs_pos); // avoid div by zero if (vec_neu.is_zero()) { return false; } vec_neu.normalize(); return true; } } // helper functions to calculate 3D destination to get us away from obstacle // v1 is NED Vector3f AP_Avoidance::perpendicular_xyz(const Location &p1, const Vector3f &v1, const Location &p2) { const Vector2f delta_p_2d = p1.get_distance_NE(p2); Vector3f delta_p_xyz = Vector3f(delta_p_2d[0],delta_p_2d[1],(p2.alt-p1.alt)/100.0f); //check this line Vector3f v1_xyz = Vector3f(v1[0], v1[1], -v1[2]); Vector3f ret = Vector3f::perpendicular(delta_p_xyz, v1_xyz); return ret; } // helper functions to calculate horizontal destination to get us away from obstacle // v1 is NED Vector2f AP_Avoidance::perpendicular_xy(const Location &p1, const Vector3f &v1, const Location &p2) { const Vector2f delta_p = p1.get_distance_NE(p2); Vector2f delta_p_n = Vector2f(delta_p[0],delta_p[1]); Vector2f v1n(v1[0],v1[1]); Vector2f ret_xy = Vector2f::perpendicular(delta_p_n, v1n); return ret_xy; } // singleton instance AP_Avoidance *AP_Avoidance::_singleton; namespace AP { AP_Avoidance *ap_avoidance() { return AP_Avoidance::get_singleton(); } } #endif // HAL_ADSB_ENABLED
diydrones/ardupilot
libraries/AP_Avoidance/AP_Avoidance.cpp
C++
gpl-3.0
25,101
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle 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. // // Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>. /** * External user API * * @package moodlecore * @subpackage user * @copyright 2009 Moodle Pty Ltd (http://moodle.com) * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ /** * Creates a user * * @param stdClass $user user to create * @param bool $updatepassword if true, authentication plugin will update password. * @param bool $triggerevent set false if user_created event should not be triggred. * @return int id of the newly created user */ function user_create_user($user, $updatepassword = true, $triggerevent = true) { global $CFG, $DB; // Set the timecreate field to the current time. if (!is_object($user)) { $user = (object) $user; } // Check username. if ($user->username !== core_text::strtolower($user->username)) { throw new moodle_exception('usernamelowercase'); } else { if ($user->username !== clean_param($user->username, PARAM_USERNAME)) { throw new moodle_exception('invalidusername'); } } // Save the password in a temp value for later. if ($updatepassword && isset($user->password)) { // Check password toward the password policy. if (!check_password_policy($user->password, $errmsg)) { throw new moodle_exception($errmsg); } $userpassword = $user->password; unset($user->password); } // Make sure calendartype, if set, is valid. if (!empty($user->calendartype)) { $availablecalendartypes = \core_calendar\type_factory::get_list_of_calendar_types(); if (empty($availablecalendartypes[$user->calendartype])) { $user->calendartype = $CFG->calendartype; } } else { $user->calendartype = $CFG->calendartype; } $user->timecreated = time(); $user->timemodified = $user->timecreated; // Insert the user into the database. $newuserid = $DB->insert_record('user', $user); // Create USER context for this user. $usercontext = context_user::instance($newuserid); // Update user password if necessary. if (isset($userpassword)) { // Get full database user row, in case auth is default. $newuser = $DB->get_record('user', array('id' => $newuserid)); $authplugin = get_auth_plugin($newuser->auth); $authplugin->user_update_password($newuser, $userpassword); } // Trigger event If required. if ($triggerevent) { \core\event\user_created::create_from_userid($newuserid)->trigger(); } return $newuserid; } /** * Update a user with a user object (will compare against the ID) * * @param stdClass $user the user to update * @param bool $updatepassword if true, authentication plugin will update password. * @param bool $triggerevent set false if user_updated event should not be triggred. */ function user_update_user($user, $updatepassword = true, $triggerevent = true) { global $DB; // set the timecreate field to the current time if (!is_object($user)) { $user = (object) $user; } //check username if (isset($user->username)) { if ($user->username !== core_text::strtolower($user->username)) { throw new moodle_exception('usernamelowercase'); } else { if ($user->username !== clean_param($user->username, PARAM_USERNAME)) { throw new moodle_exception('invalidusername'); } } } // Unset password here, for updating later, if password update is required. if ($updatepassword && isset($user->password)) { //check password toward the password policy if (!check_password_policy($user->password, $errmsg)) { throw new moodle_exception($errmsg); } $passwd = $user->password; unset($user->password); } // Make sure calendartype, if set, is valid. if (!empty($user->calendartype)) { $availablecalendartypes = \core_calendar\type_factory::get_list_of_calendar_types(); // If it doesn't exist, then unset this value, we do not want to update the user's value. if (empty($availablecalendartypes[$user->calendartype])) { unset($user->calendartype); } } else { // Unset this variable, must be an empty string, which we do not want to update the calendartype to. unset($user->calendartype); } $user->timemodified = time(); $DB->update_record('user', $user); if ($updatepassword) { // Get full user record. $updateduser = $DB->get_record('user', array('id' => $user->id)); // if password was set, then update its hash if (isset($passwd)) { $authplugin = get_auth_plugin($updateduser->auth); if ($authplugin->can_change_password()) { $authplugin->user_update_password($updateduser, $passwd); } } } // Trigger event if required. if ($triggerevent) { \core\event\user_updated::create_from_userid($user->id)->trigger(); } } /** * Marks user deleted in internal user database and notifies the auth plugin. * Also unenrols user from all roles and does other cleanup. * * @todo Decide if this transaction is really needed (look for internal TODO:) * @param object $user Userobject before delete (without system magic quotes) * @return boolean success */ function user_delete_user($user) { return delete_user($user); } /** * Get users by id * @param array $userids id of users to retrieve * */ function user_get_users_by_id($userids) { global $DB; return $DB->get_records_list('user', 'id', $userids); } /** * Returns the list of default 'displayable' fields * * Contains database field names but also names used to generate information, such as enrolledcourses * * @return array of user fields */ function user_get_default_fields() { return array( 'id', 'username', 'fullname', 'firstname', 'lastname', 'email', 'address', 'phone1', 'phone2', 'icq', 'skype', 'yahoo', 'aim', 'msn', 'department', 'institution', 'interests', 'firstaccess', 'lastaccess', 'auth', 'confirmed', 'idnumber', 'lang', 'theme', 'timezone', 'mailformat', 'description', 'descriptionformat', 'city', 'url', 'country', 'profileimageurlsmall', 'profileimageurl', 'customfields', 'groups', 'roles', 'preferences', 'enrolledcourses' ); } /** * * Give user record from mdl_user, build an array conntains * all user details * * Warning: description file urls are 'webservice/pluginfile.php' is use. * it can be changed with $CFG->moodlewstextformatlinkstoimagesfile * * @param stdClass $user user record from mdl_user * @param stdClass $context context object * @param stdClass $course moodle course * @param array $userfields required fields * @return array|null */ function user_get_user_details($user, $course = null, array $userfields = array()) { global $USER, $DB, $CFG; require_once($CFG->dirroot . "/user/profile/lib.php"); //custom field library require_once($CFG->dirroot . "/lib/filelib.php"); // file handling on description and friends $defaultfields = user_get_default_fields(); if (empty($userfields)) { $userfields = $defaultfields; } foreach ($userfields as $thefield) { if (!in_array($thefield, $defaultfields)) { throw new moodle_exception('invaliduserfield', 'error', '', $thefield); } } // Make sure id and fullname are included if (!in_array('id', $userfields)) { $userfields[] = 'id'; } if (!in_array('fullname', $userfields)) { $userfields[] = 'fullname'; } if (!empty($course)) { $context = context_course::instance($course->id); $usercontext = context_user::instance($user->id); $canviewdetailscap = (has_capability('moodle/user:viewdetails', $context) || has_capability('moodle/user:viewdetails', $usercontext)); } else { $context = context_user::instance($user->id); $usercontext = $context; $canviewdetailscap = has_capability('moodle/user:viewdetails', $usercontext); } $currentuser = ($user->id == $USER->id); $isadmin = is_siteadmin($USER); $showuseridentityfields = get_extra_user_fields($context); if (!empty($course)) { $canviewhiddenuserfields = has_capability('moodle/course:viewhiddenuserfields', $context); } else { $canviewhiddenuserfields = has_capability('moodle/user:viewhiddendetails', $context); } $canviewfullnames = has_capability('moodle/site:viewfullnames', $context); if (!empty($course)) { $canviewuseremail = has_capability('moodle/course:useremail', $context); } else { $canviewuseremail = false; } $cannotviewdescription = !empty($CFG->profilesforenrolledusersonly) && !$currentuser && !$DB->record_exists('role_assignments', array('userid'=>$user->id)); if (!empty($course)) { $canaccessallgroups = has_capability('moodle/site:accessallgroups', $context); } else { $canaccessallgroups = false; } if (!$currentuser && !$canviewdetailscap && !has_coursecontact_role($user->id)) { // skip this user details return null; } $userdetails = array(); $userdetails['id'] = $user->id; if (($isadmin or $currentuser) and in_array('username', $userfields)) { $userdetails['username'] = $user->username; } if ($isadmin or $canviewfullnames) { if (in_array('firstname', $userfields)) { $userdetails['firstname'] = $user->firstname; } if (in_array('lastname', $userfields)) { $userdetails['lastname'] = $user->lastname; } } $userdetails['fullname'] = fullname($user); if (in_array('customfields', $userfields)) { $fields = $DB->get_recordset_sql("SELECT f.* FROM {user_info_field} f JOIN {user_info_category} c ON f.categoryid=c.id ORDER BY c.sortorder ASC, f.sortorder ASC"); $userdetails['customfields'] = array(); foreach ($fields as $field) { require_once($CFG->dirroot.'/user/profile/field/'.$field->datatype.'/field.class.php'); $newfield = 'profile_field_'.$field->datatype; $formfield = new $newfield($field->id, $user->id); if ($formfield->is_visible() and !$formfield->is_empty()) { $userdetails['customfields'][] = array('name' => $formfield->field->name, 'value' => $formfield->data, 'type' => $field->datatype, 'shortname' => $formfield->field->shortname); } } $fields->close(); // unset customfields if it's empty if (empty($userdetails['customfields'])) { unset($userdetails['customfields']); } } // profile image if (in_array('profileimageurl', $userfields)) { $profileimageurl = moodle_url::make_pluginfile_url($usercontext->id, 'user', 'icon', NULL, '/', 'f1'); $userdetails['profileimageurl'] = $profileimageurl->out(false); } if (in_array('profileimageurlsmall', $userfields)) { $profileimageurlsmall = moodle_url::make_pluginfile_url($usercontext->id, 'user', 'icon', NULL, '/', 'f2'); $userdetails['profileimageurlsmall'] = $profileimageurlsmall->out(false); } //hidden user field if ($canviewhiddenuserfields) { $hiddenfields = array(); // address, phone1 and phone2 not appears in hidden fields list // but require viewhiddenfields capability // according to user/profile.php if ($user->address && in_array('address', $userfields)) { $userdetails['address'] = $user->address; } } else { $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields)); } if ($user->phone1 && in_array('phone1', $userfields) && (in_array('phone1', $showuseridentityfields) or $canviewhiddenuserfields)) { $userdetails['phone1'] = $user->phone1; } if ($user->phone2 && in_array('phone2', $userfields) && (in_array('phone2', $showuseridentityfields) or $canviewhiddenuserfields)) { $userdetails['phone2'] = $user->phone2; } if (isset($user->description) && ((!isset($hiddenfields['description']) && !$cannotviewdescription) or $isadmin)) { if (in_array('description', $userfields)) { // Always return the descriptionformat if description is requested. list($userdetails['description'], $userdetails['descriptionformat']) = external_format_text($user->description, $user->descriptionformat, $usercontext->id, 'user', 'profile', null); } } if (in_array('country', $userfields) && (!isset($hiddenfields['country']) or $isadmin) && $user->country) { $userdetails['country'] = $user->country; } if (in_array('city', $userfields) && (!isset($hiddenfields['city']) or $isadmin) && $user->city) { $userdetails['city'] = $user->city; } if (in_array('url', $userfields) && $user->url && (!isset($hiddenfields['webpage']) or $isadmin)) { $url = $user->url; if (strpos($user->url, '://') === false) { $url = 'http://'. $url; } $user->url = clean_param($user->url, PARAM_URL); $userdetails['url'] = $user->url; } if (in_array('icq', $userfields) && $user->icq && (!isset($hiddenfields['icqnumber']) or $isadmin)) { $userdetails['icq'] = $user->icq; } if (in_array('skype', $userfields) && $user->skype && (!isset($hiddenfields['skypeid']) or $isadmin)) { $userdetails['skype'] = $user->skype; } if (in_array('yahoo', $userfields) && $user->yahoo && (!isset($hiddenfields['yahooid']) or $isadmin)) { $userdetails['yahoo'] = $user->yahoo; } if (in_array('aim', $userfields) && $user->aim && (!isset($hiddenfields['aimid']) or $isadmin)) { $userdetails['aim'] = $user->aim; } if (in_array('msn', $userfields) && $user->msn && (!isset($hiddenfields['msnid']) or $isadmin)) { $userdetails['msn'] = $user->msn; } if (in_array('firstaccess', $userfields) && (!isset($hiddenfields['firstaccess']) or $isadmin)) { if ($user->firstaccess) { $userdetails['firstaccess'] = $user->firstaccess; } else { $userdetails['firstaccess'] = 0; } } if (in_array('lastaccess', $userfields) && (!isset($hiddenfields['lastaccess']) or $isadmin)) { if ($user->lastaccess) { $userdetails['lastaccess'] = $user->lastaccess; } else { $userdetails['lastaccess'] = 0; } } if (in_array('email', $userfields) && ($isadmin // The admin is allowed the users email or $currentuser // Of course the current user is as well or $canviewuseremail // this is a capability in course context, it will be false in usercontext or in_array('email', $showuseridentityfields) or $user->maildisplay == 1 or ($user->maildisplay == 2 and enrol_sharing_course($user, $USER)))) { $userdetails['email'] = $user->email; } if (in_array('interests', $userfields) && !empty($CFG->usetags)) { require_once($CFG->dirroot . '/tag/lib.php'); if ($interests = tag_get_tags_csv('user', $user->id, TAG_RETURN_TEXT) ) { $userdetails['interests'] = $interests; } } //Departement/Institution/Idnumber are not displayed on any profile, however you can get them from editing profile. if ($isadmin or $currentuser or in_array('idnumber', $showuseridentityfields)) { if (in_array('idnumber', $userfields) && $user->idnumber) { $userdetails['idnumber'] = $user->idnumber; } } if ($isadmin or $currentuser or in_array('institution', $showuseridentityfields)) { if (in_array('institution', $userfields) && $user->institution) { $userdetails['institution'] = $user->institution; } } if ($isadmin or $currentuser or in_array('department', $showuseridentityfields)) { if (in_array('department', $userfields) && isset($user->department)) { //isset because it's ok to have department 0 $userdetails['department'] = $user->department; } } if (in_array('roles', $userfields) && !empty($course)) { // not a big secret $roles = get_user_roles($context, $user->id, false); $userdetails['roles'] = array(); foreach ($roles as $role) { $userdetails['roles'][] = array( 'roleid' => $role->roleid, 'name' => $role->name, 'shortname' => $role->shortname, 'sortorder' => $role->sortorder ); } } // If groups are in use and enforced throughout the course, then make sure we can meet in at least one course level group if (in_array('groups', $userfields) && !empty($course) && $canaccessallgroups) { $usergroups = groups_get_all_groups($course->id, $user->id, $course->defaultgroupingid, 'g.id, g.name,g.description,g.descriptionformat'); $userdetails['groups'] = array(); foreach ($usergroups as $group) { list($group->description, $group->descriptionformat) = external_format_text($group->description, $group->descriptionformat, $context->id, 'group', 'description', $group->id); $userdetails['groups'][] = array('id'=>$group->id, 'name'=>$group->name, 'description'=>$group->description, 'descriptionformat'=>$group->descriptionformat); } } //list of courses where the user is enrolled if (in_array('enrolledcourses', $userfields) && !isset($hiddenfields['mycourses'])) { $enrolledcourses = array(); if ($mycourses = enrol_get_users_courses($user->id, true)) { foreach ($mycourses as $mycourse) { if ($mycourse->category) { $coursecontext = context_course::instance($mycourse->id); $enrolledcourse = array(); $enrolledcourse['id'] = $mycourse->id; $enrolledcourse['fullname'] = format_string($mycourse->fullname, true, array('context' => $coursecontext)); $enrolledcourse['shortname'] = format_string($mycourse->shortname, true, array('context' => $coursecontext)); $enrolledcourses[] = $enrolledcourse; } } $userdetails['enrolledcourses'] = $enrolledcourses; } } //user preferences if (in_array('preferences', $userfields) && $currentuser) { $preferences = array(); $userpreferences = get_user_preferences(); foreach($userpreferences as $prefname => $prefvalue) { $preferences[] = array('name' => $prefname, 'value' => $prefvalue); } $userdetails['preferences'] = $preferences; } return $userdetails; } /** * Tries to obtain user details, either recurring directly to the user's system profile * or through one of the user's course enrollments (course profile). * * @param object $user The user. * @return array if unsuccessful or the allowed user details. */ function user_get_user_details_courses($user) { global $USER; $userdetails = null; // Get the courses that the user is enrolled in (only active). $courses = enrol_get_users_courses($user->id, true); $systemprofile = false; if (can_view_user_details_cap($user) || ($user->id == $USER->id) || has_coursecontact_role($user->id)) { $systemprofile = true; } // Try using system profile. if ($systemprofile) { $userdetails = user_get_user_details($user, null); } else { // Try through course profile. foreach ($courses as $course) { if (can_view_user_details_cap($user, $course) || ($user->id == $USER->id) || has_coursecontact_role($user->id)) { $userdetails = user_get_user_details($user, $course); } } } return $userdetails; } /** * Check if $USER have the necessary capabilities to obtain user details. * * @param object $user * @param object $course if null then only consider system profile otherwise also consider the course's profile. * @return bool true if $USER can view user details. */ function can_view_user_details_cap($user, $course = null) { // Check $USER has the capability to view the user details at user context. $usercontext = context_user::instance($user->id); $result = has_capability('moodle/user:viewdetails', $usercontext); // Otherwise can $USER see them at course context. if (!$result && !empty($course)) { $context = context_course::instance($course->id); $result = has_capability('moodle/user:viewdetails', $context); } return $result; } /** * Return a list of page types * @param string $pagetype current page type * @param stdClass $parentcontext Block's parent context * @param stdClass $currentcontext Current context of block */ function user_page_type_list($pagetype, $parentcontext, $currentcontext) { return array('user-profile'=>get_string('page-user-profile', 'pagetype')); }
miguelangelUvirtual/uEducon
user/lib.php
PHP
gpl-3.0
22,284
----------------------------------- -- Area: Selbina -- NPC: Graegham -- Guild Merchant NPC: Fishing Guild -- @pos -12.423 -7.287 8.665 248 ----------------------------------- package.loaded["scripts/zones/Selbina/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/shop"); require("scripts/zones/Selbina/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(player:sendGuild(5182,3,18,5)) then player:showText(npc,FISHING_SHOP_DIALOG); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
The-HalcyonDays/darkstar
scripts/zones/Selbina/npcs/Graegham.lua
Lua
gpl-3.0
1,182
/* * This file is part of EchoPet. * * EchoPet 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. * * EchoPet 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 EchoPet. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.echopet.compat.api.entity.type.pet; import com.dsh105.echopet.compat.api.entity.IAgeablePet; public interface ICowPet extends IAgeablePet { }
UnlimitedFreedom/UF-EchoPet
modules/API/src/main/java/com/dsh105/echopet/compat/api/entity/type/pet/ICowPet.java
Java
gpl-3.0
838
/* This testcase is part of GDB, the GNU debugger. Copyright 2016 Free Software Foundation, Inc. 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/>. */ volatile int global = 0; int main (void) { global = 1; /* set break main console here */ global = 1; global = 1; /* set break extra console here */ global = 1; return 0; }
ccilab/binutils
gdb/testsuite/gdb.base/new-ui-echo.c
C
gpl-3.0
932
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle 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. // // Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>. /** * DML layer tests * * @package core_dml * @category phpunit * @copyright 2008 Nicolas Connault * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); class dml_testcase extends database_driver_testcase { protected function setUp() { parent::setUp(); $dbman = $this->tdb->get_manager(); // loads DDL libs } /** * Get a xmldb_table object for testing, deleting any existing table * of the same name, for example if one was left over from a previous test * run that crashed. * * @param string $suffix table name suffix, use if you need more test tables * @return xmldb_table the table object. */ private function get_test_table($suffix = '') { $tablename = "test_table"; if ($suffix !== '') { $tablename .= $suffix; } $table = new xmldb_table($tablename); $table->setComment("This is a test'n drop table. You can drop it safely"); return new xmldb_table($tablename); } function test_diagnose() { $DB = $this->tdb; $result = $DB->diagnose(); $this->assertNull($result, 'Database self diagnostics failed %s'); } function test_get_server_info() { $DB = $this->tdb; $result = $DB->get_server_info(); $this->assertTrue(is_array($result)); $this->assertTrue(array_key_exists('description', $result)); $this->assertTrue(array_key_exists('version', $result)); } public function test_get_in_or_equal() { $DB = $this->tdb; // SQL_PARAMS_QM - IN or = // Correct usage of multiple values $in_values = array('value1', 'value2', '3', 4, null, false, true); list($usql, $params) = $DB->get_in_or_equal($in_values); $this->assertEquals('IN ('.implode(',',array_fill(0, count($in_values), '?')).')', $usql); $this->assertEquals(count($in_values), count($params)); foreach ($params as $key => $value) { $this->assertSame($in_values[$key], $value); } // Correct usage of single value (in an array) $in_values = array('value1'); list($usql, $params) = $DB->get_in_or_equal($in_values); $this->assertEquals("= ?", $usql); $this->assertEquals(1, count($params)); $this->assertEquals($in_values[0], $params[0]); // Correct usage of single value $in_value = 'value1'; list($usql, $params) = $DB->get_in_or_equal($in_values); $this->assertEquals("= ?", $usql); $this->assertEquals(1, count($params)); $this->assertEquals($in_value, $params[0]); // SQL_PARAMS_QM - NOT IN or <> // Correct usage of multiple values $in_values = array('value1', 'value2', 'value3', 'value4'); list($usql, $params) = $DB->get_in_or_equal($in_values, SQL_PARAMS_QM, null, false); $this->assertEquals("NOT IN (?,?,?,?)", $usql); $this->assertEquals(4, count($params)); foreach ($params as $key => $value) { $this->assertEquals($in_values[$key], $value); } // Correct usage of single value (in array() $in_values = array('value1'); list($usql, $params) = $DB->get_in_or_equal($in_values, SQL_PARAMS_QM, null, false); $this->assertEquals("<> ?", $usql); $this->assertEquals(1, count($params)); $this->assertEquals($in_values[0], $params[0]); // Correct usage of single value $in_value = 'value1'; list($usql, $params) = $DB->get_in_or_equal($in_values, SQL_PARAMS_QM, null, false); $this->assertEquals("<> ?", $usql); $this->assertEquals(1, count($params)); $this->assertEquals($in_value, $params[0]); // SQL_PARAMS_NAMED - IN or = // Correct usage of multiple values $in_values = array('value1', 'value2', 'value3', 'value4'); list($usql, $params) = $DB->get_in_or_equal($in_values, SQL_PARAMS_NAMED, 'param', true); $this->assertEquals(4, count($params)); reset($in_values); $ps = array(); foreach ($params as $key => $value) { $this->assertEquals(current($in_values), $value); next($in_values); $ps[] = ':'.$key; } $this->assertEquals("IN (".implode(',', $ps).")", $usql); // Correct usage of single values (in array) $in_values = array('value1'); list($usql, $params) = $DB->get_in_or_equal($in_values, SQL_PARAMS_NAMED, 'param', true); $this->assertEquals(1, count($params)); $value = reset($params); $key = key($params); $this->assertEquals("= :$key", $usql); $this->assertEquals($in_value, $value); // Correct usage of single value $in_value = 'value1'; list($usql, $params) = $DB->get_in_or_equal($in_values, SQL_PARAMS_NAMED, 'param', true); $this->assertEquals(1, count($params)); $value = reset($params); $key = key($params); $this->assertEquals("= :$key", $usql); $this->assertEquals($in_value, $value); // SQL_PARAMS_NAMED - NOT IN or <> // Correct usage of multiple values $in_values = array('value1', 'value2', 'value3', 'value4'); list($usql, $params) = $DB->get_in_or_equal($in_values, SQL_PARAMS_NAMED, 'param', false); $this->assertEquals(4, count($params)); reset($in_values); $ps = array(); foreach ($params as $key => $value) { $this->assertEquals(current($in_values), $value); next($in_values); $ps[] = ':'.$key; } $this->assertEquals("NOT IN (".implode(',', $ps).")", $usql); // Correct usage of single values (in array) $in_values = array('value1'); list($usql, $params) = $DB->get_in_or_equal($in_values, SQL_PARAMS_NAMED, 'param', false); $this->assertEquals(1, count($params)); $value = reset($params); $key = key($params); $this->assertEquals("<> :$key", $usql); $this->assertEquals($in_value, $value); // Correct usage of single value $in_value = 'value1'; list($usql, $params) = $DB->get_in_or_equal($in_values, SQL_PARAMS_NAMED, 'param', false); $this->assertEquals(1, count($params)); $value = reset($params); $key = key($params); $this->assertEquals("<> :$key", $usql); $this->assertEquals($in_value, $value); // make sure the param names are unique list($usql1, $params1) = $DB->get_in_or_equal(array(1,2,3), SQL_PARAMS_NAMED, 'param'); list($usql2, $params2) = $DB->get_in_or_equal(array(1,2,3), SQL_PARAMS_NAMED, 'param'); $params1 = array_keys($params1); $params2 = array_keys($params2); $common = array_intersect($params1, $params2); $this->assertEquals(count($common), 0); // Some incorrect tests // Incorrect usage passing not-allowed params type $in_values = array(1, 2, 3); try { list($usql, $params) = $DB->get_in_or_equal($in_values, SQL_PARAMS_DOLLAR, 'param', false); $this->fail('An Exception is missing, expected due to not supported SQL_PARAMS_DOLLAR'); } catch (exception $e) { $this->assertTrue($e instanceof dml_exception); $this->assertEquals($e->errorcode, 'typenotimplement'); } // Incorrect usage passing empty array $in_values = array(); try { list($usql, $params) = $DB->get_in_or_equal($in_values, SQL_PARAMS_NAMED, 'param', false); $this->fail('An Exception is missing, expected due to empty array of items'); } catch (exception $e) { $this->assertTrue($e instanceof coding_exception); } // Test using $onemptyitems // Correct usage passing empty array and $onemptyitems = NULL (equal = true, QM) $in_values = array(); list($usql, $params) = $DB->get_in_or_equal($in_values, SQL_PARAMS_QM, 'param', true, NULL); $this->assertEquals(' IS NULL', $usql); $this->assertSame(array(), $params); // Correct usage passing empty array and $onemptyitems = NULL (equal = false, NAMED) $in_values = array(); list($usql, $params) = $DB->get_in_or_equal($in_values, SQL_PARAMS_NAMED, 'param', false, NULL); $this->assertEquals(' IS NOT NULL', $usql); $this->assertSame(array(), $params); // Correct usage passing empty array and $onemptyitems = true (equal = true, QM) $in_values = array(); list($usql, $params) = $DB->get_in_or_equal($in_values, SQL_PARAMS_QM, 'param', true, true); $this->assertEquals('= ?', $usql); $this->assertSame(array(true), $params); // Correct usage passing empty array and $onemptyitems = true (equal = false, NAMED) $in_values = array(); list($usql, $params) = $DB->get_in_or_equal($in_values, SQL_PARAMS_NAMED, 'param', false, true); $this->assertEquals(1, count($params)); $value = reset($params); $key = key($params); $this->assertEquals('<> :'.$key, $usql); $this->assertSame($value, true); // Correct usage passing empty array and $onemptyitems = -1 (equal = true, QM) $in_values = array(); list($usql, $params) = $DB->get_in_or_equal($in_values, SQL_PARAMS_QM, 'param', true, -1); $this->assertEquals('= ?', $usql); $this->assertSame(array(-1), $params); // Correct usage passing empty array and $onemptyitems = -1 (equal = false, NAMED) $in_values = array(); list($usql, $params) = $DB->get_in_or_equal($in_values, SQL_PARAMS_NAMED, 'param', false, -1); $this->assertEquals(1, count($params)); $value = reset($params); $key = key($params); $this->assertEquals('<> :'.$key, $usql); $this->assertSame($value, -1); // Correct usage passing empty array and $onemptyitems = 'onevalue' (equal = true, QM) $in_values = array(); list($usql, $params) = $DB->get_in_or_equal($in_values, SQL_PARAMS_QM, 'param', true, 'onevalue'); $this->assertEquals('= ?', $usql); $this->assertSame(array('onevalue'), $params); // Correct usage passing empty array and $onemptyitems = 'onevalue' (equal = false, NAMED) $in_values = array(); list($usql, $params) = $DB->get_in_or_equal($in_values, SQL_PARAMS_NAMED, 'param', false, 'onevalue'); $this->assertEquals(1, count($params)); $value = reset($params); $key = key($params); $this->assertEquals('<> :'.$key, $usql); $this->assertSame($value, 'onevalue'); } public function test_fix_table_names() { $DB = new moodle_database_for_testing(); $prefix = $DB->get_prefix(); // Simple placeholder $placeholder = "{user_123}"; $this->assertSame($prefix."user_123", $DB->public_fix_table_names($placeholder)); // wrong table name $placeholder = "{user-a}"; $this->assertSame($placeholder, $DB->public_fix_table_names($placeholder)); // wrong table name $placeholder = "{123user}"; $this->assertSame($placeholder, $DB->public_fix_table_names($placeholder)); // Full SQL $sql = "SELECT * FROM {user}, {funny_table_name}, {mdl_stupid_table} WHERE {user}.id = {funny_table_name}.userid"; $expected = "SELECT * FROM {$prefix}user, {$prefix}funny_table_name, {$prefix}mdl_stupid_table WHERE {$prefix}user.id = {$prefix}funny_table_name.userid"; $this->assertSame($expected, $DB->public_fix_table_names($sql)); } function test_fix_sql_params() { $DB = $this->tdb; $prefix = $DB->get_prefix(); $table = $this->get_test_table(); $tablename = $table->getName(); // Correct table placeholder substitution $sql = "SELECT * FROM {{$tablename}}"; $sqlarray = $DB->fix_sql_params($sql); $this->assertEquals("SELECT * FROM {$prefix}".$tablename, $sqlarray[0]); // Conversions of all param types $sql = array(); $sql[SQL_PARAMS_NAMED] = "SELECT * FROM {$prefix}testtable WHERE name = :param1, course = :param2"; $sql[SQL_PARAMS_QM] = "SELECT * FROM {$prefix}testtable WHERE name = ?, course = ?"; $sql[SQL_PARAMS_DOLLAR] = "SELECT * FROM {$prefix}testtable WHERE name = \$1, course = \$2"; $params = array(); $params[SQL_PARAMS_NAMED] = array('param1'=>'first record', 'param2'=>1); $params[SQL_PARAMS_QM] = array('first record', 1); $params[SQL_PARAMS_DOLLAR] = array('first record', 1); list($rsql, $rparams, $rtype) = $DB->fix_sql_params($sql[SQL_PARAMS_NAMED], $params[SQL_PARAMS_NAMED]); $this->assertSame($rsql, $sql[$rtype]); $this->assertSame($rparams, $params[$rtype]); list($rsql, $rparams, $rtype) = $DB->fix_sql_params($sql[SQL_PARAMS_QM], $params[SQL_PARAMS_QM]); $this->assertSame($rsql, $sql[$rtype]); $this->assertSame($rparams, $params[$rtype]); list($rsql, $rparams, $rtype) = $DB->fix_sql_params($sql[SQL_PARAMS_DOLLAR], $params[SQL_PARAMS_DOLLAR]); $this->assertSame($rsql, $sql[$rtype]); $this->assertSame($rparams, $params[$rtype]); // Malformed table placeholder $sql = "SELECT * FROM [testtable]"; $sqlarray = $DB->fix_sql_params($sql); $this->assertSame($sql, $sqlarray[0]); // Mixed param types (colon and dollar) $sql = "SELECT * FROM {{$tablename}} WHERE name = :param1, course = \$1"; $params = array('param1' => 'record1', 'param2' => 3); try { $DB->fix_sql_params($sql, $params); $this->fail("Expecting an exception, none occurred"); } catch (Exception $e) { $this->assertTrue($e instanceof dml_exception); } // Mixed param types (question and dollar) $sql = "SELECT * FROM {{$tablename}} WHERE name = ?, course = \$1"; $params = array('param1' => 'record2', 'param2' => 5); try { $DB->fix_sql_params($sql, $params); $this->fail("Expecting an exception, none occurred"); } catch (Exception $e) { $this->assertTrue($e instanceof dml_exception); } // Too few params in sql $sql = "SELECT * FROM {{$tablename}} WHERE name = ?, course = ?, id = ?"; $params = array('record2', 3); try { $DB->fix_sql_params($sql, $params); $this->fail("Expecting an exception, none occurred"); } catch (Exception $e) { $this->assertTrue($e instanceof dml_exception); } // Too many params in array: no error, just use what is necessary $params[] = 1; $params[] = time(); try { $sqlarray = $DB->fix_sql_params($sql, $params); $this->assertTrue(is_array($sqlarray)); $this->assertEquals(count($sqlarray[1]), 3); } catch (Exception $e) { $this->fail("Unexpected ".get_class($e)." exception"); } // Named params missing from array $sql = "SELECT * FROM {{$tablename}} WHERE name = :name, course = :course"; $params = array('wrongname' => 'record1', 'course' => 1); try { $DB->fix_sql_params($sql, $params); $this->fail("Expecting an exception, none occurred"); } catch (Exception $e) { $this->assertTrue($e instanceof dml_exception); } // Duplicate named param in query - this is a very important feature!! // it helps with debugging of sloppy code $sql = "SELECT * FROM {{$tablename}} WHERE name = :name, course = :name"; $params = array('name' => 'record2', 'course' => 3); try { $DB->fix_sql_params($sql, $params); $this->fail("Expecting an exception, none occurred"); } catch (Exception $e) { $this->assertTrue($e instanceof dml_exception); } // Extra named param is ignored $sql = "SELECT * FROM {{$tablename}} WHERE name = :name, course = :course"; $params = array('name' => 'record1', 'course' => 1, 'extrastuff'=>'haha'); try { $sqlarray = $DB->fix_sql_params($sql, $params); $this->assertTrue(is_array($sqlarray)); $this->assertEquals(count($sqlarray[1]), 2); } catch (Exception $e) { $this->fail("Unexpected ".get_class($e)." exception"); } // Params exceeding 30 chars length $sql = "SELECT * FROM {{$tablename}} WHERE name = :long_placeholder_with_more_than_30"; $params = array('long_placeholder_with_more_than_30' => 'record1'); try { $DB->fix_sql_params($sql, $params); $this->fail("Expecting an exception, none occurred"); } catch (Exception $e) { $this->assertTrue($e instanceof coding_exception); } // Booleans in NAMED params are casting to 1/0 int $sql = "SELECT * FROM {{$tablename}} WHERE course = ? OR course = ?"; $params = array(true, false); list($sql, $params) = $DB->fix_sql_params($sql, $params); $this->assertTrue(reset($params) === 1); $this->assertTrue(next($params) === 0); // Booleans in QM params are casting to 1/0 int $sql = "SELECT * FROM {{$tablename}} WHERE course = :course1 OR course = :course2"; $params = array('course1' => true, 'course2' => false); list($sql, $params) = $DB->fix_sql_params($sql, $params); $this->assertTrue(reset($params) === 1); $this->assertTrue(next($params) === 0); // Booleans in DOLLAR params are casting to 1/0 int $sql = "SELECT * FROM {{$tablename}} WHERE course = \$1 OR course = \$2"; $params = array(true, false); list($sql, $params) = $DB->fix_sql_params($sql, $params); $this->assertTrue(reset($params) === 1); $this->assertTrue(next($params) === 0); // No data types are touched except bool $sql = "SELECT * FROM {{$tablename}} WHERE name IN (?,?,?,?,?,?)"; $inparams = array('abc', 'ABC', NULL, '1', 1, 1.4); list($sql, $params) = $DB->fix_sql_params($sql, $inparams); $this->assertSame(array_values($params), array_values($inparams)); } public function test_strtok() { // strtok was previously used by bound emulation, make sure it is not used any more $DB = $this->tdb; $dbman = $this->tdb->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); $table->add_field('name', XMLDB_TYPE_CHAR, '255', null, null, null, 'lala'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $str = 'a?b?c?d'; $this->assertSame(strtok($str, '?'), 'a'); $DB->get_records($tablename, array('id'=>1)); $this->assertSame(strtok('?'), 'b'); } public function test_tweak_param_names() { // Note the tweak_param_names() method is only available in the oracle driver, // hence we look for expected results indirectly, by testing various DML methods // with some "extreme" conditions causing the tweak to happen. $DB = $this->tdb; $dbman = $this->tdb->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); // Add some columns with 28 chars in the name $table->add_field('long_int_columnname_with_28c', XMLDB_TYPE_INTEGER, '10'); $table->add_field('long_dec_columnname_with_28c', XMLDB_TYPE_NUMBER, '10,2'); $table->add_field('long_str_columnname_with_28c', XMLDB_TYPE_CHAR, '100'); // Add some columns with 30 chars in the name $table->add_field('long_int_columnname_with_30cxx', XMLDB_TYPE_INTEGER, '10'); $table->add_field('long_dec_columnname_with_30cxx', XMLDB_TYPE_NUMBER, '10,2'); $table->add_field('long_str_columnname_with_30cxx', XMLDB_TYPE_CHAR, '100'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $this->assertTrue($dbman->table_exists($tablename)); // Test insert record $rec1 = new stdClass(); $rec1->long_int_columnname_with_28c = 28; $rec1->long_dec_columnname_with_28c = 28.28; $rec1->long_str_columnname_with_28c = '28'; $rec1->long_int_columnname_with_30cxx = 30; $rec1->long_dec_columnname_with_30cxx = 30.30; $rec1->long_str_columnname_with_30cxx = '30'; // insert_record() $rec1->id = $DB->insert_record($tablename, $rec1); $this->assertEquals($rec1, $DB->get_record($tablename, array('id' => $rec1->id))); // update_record() $DB->update_record($tablename, $rec1); $this->assertEquals($rec1, $DB->get_record($tablename, array('id' => $rec1->id))); // set_field() $rec1->long_int_columnname_with_28c = 280; $DB->set_field($tablename, 'long_int_columnname_with_28c', $rec1->long_int_columnname_with_28c, array('id' => $rec1->id, 'long_int_columnname_with_28c' => 28)); $rec1->long_dec_columnname_with_28c = 280.28; $DB->set_field($tablename, 'long_dec_columnname_with_28c', $rec1->long_dec_columnname_with_28c, array('id' => $rec1->id, 'long_dec_columnname_with_28c' => 28.28)); $rec1->long_str_columnname_with_28c = '280'; $DB->set_field($tablename, 'long_str_columnname_with_28c', $rec1->long_str_columnname_with_28c, array('id' => $rec1->id, 'long_str_columnname_with_28c' => '28')); $rec1->long_int_columnname_with_30cxx = 300; $DB->set_field($tablename, 'long_int_columnname_with_30cxx', $rec1->long_int_columnname_with_30cxx, array('id' => $rec1->id, 'long_int_columnname_with_30cxx' => 30)); $rec1->long_dec_columnname_with_30cxx = 300.30; $DB->set_field($tablename, 'long_dec_columnname_with_30cxx', $rec1->long_dec_columnname_with_30cxx, array('id' => $rec1->id, 'long_dec_columnname_with_30cxx' => 30.30)); $rec1->long_str_columnname_with_30cxx = '300'; $DB->set_field($tablename, 'long_str_columnname_with_30cxx', $rec1->long_str_columnname_with_30cxx, array('id' => $rec1->id, 'long_str_columnname_with_30cxx' => '30')); $this->assertEquals($rec1, $DB->get_record($tablename, array('id' => $rec1->id))); // delete_records() $rec2 = $DB->get_record($tablename, array('id' => $rec1->id)); $rec2->id = $DB->insert_record($tablename, $rec2); $this->assertEquals(2, $DB->count_records($tablename)); $DB->delete_records($tablename, (array) $rec2); $this->assertEquals(1, $DB->count_records($tablename)); // get_recordset() $rs = $DB->get_recordset($tablename, (array) $rec1); $iterations = 0; foreach ($rs as $rec2) { $iterations++; } $rs->close(); $this->assertEquals(1, $iterations); $this->assertEquals($rec1, $rec2); // get_records() $recs = $DB->get_records($tablename, (array) $rec1); $this->assertEquals(1, count($recs)); $this->assertEquals($rec1, reset($recs)); // get_fieldset_select() $select = 'id = :id AND long_int_columnname_with_28c = :long_int_columnname_with_28c AND long_dec_columnname_with_28c = :long_dec_columnname_with_28c AND long_str_columnname_with_28c = :long_str_columnname_with_28c AND long_int_columnname_with_30cxx = :long_int_columnname_with_30cxx AND long_dec_columnname_with_30cxx = :long_dec_columnname_with_30cxx AND long_str_columnname_with_30cxx = :long_str_columnname_with_30cxx'; $fields = $DB->get_fieldset_select($tablename, 'long_int_columnname_with_28c', $select, (array)$rec1); $this->assertEquals(1, count($fields)); $this->assertEquals($rec1->long_int_columnname_with_28c, reset($fields)); $fields = $DB->get_fieldset_select($tablename, 'long_dec_columnname_with_28c', $select, (array)$rec1); $this->assertEquals($rec1->long_dec_columnname_with_28c, reset($fields)); $fields = $DB->get_fieldset_select($tablename, 'long_str_columnname_with_28c', $select, (array)$rec1); $this->assertEquals($rec1->long_str_columnname_with_28c, reset($fields)); $fields = $DB->get_fieldset_select($tablename, 'long_int_columnname_with_30cxx', $select, (array)$rec1); $this->assertEquals($rec1->long_int_columnname_with_30cxx, reset($fields)); $fields = $DB->get_fieldset_select($tablename, 'long_dec_columnname_with_30cxx', $select, (array)$rec1); $this->assertEquals($rec1->long_dec_columnname_with_30cxx, reset($fields)); $fields = $DB->get_fieldset_select($tablename, 'long_str_columnname_with_30cxx', $select, (array)$rec1); $this->assertEquals($rec1->long_str_columnname_with_30cxx, reset($fields)); // overlapping placeholders (progressive str_replace) $overlapselect = 'id = :p AND long_int_columnname_with_28c = :param1 AND long_dec_columnname_with_28c = :param2 AND long_str_columnname_with_28c = :param_with_29_characters_long AND long_int_columnname_with_30cxx = :param_with_30_characters_long_ AND long_dec_columnname_with_30cxx = :param_ AND long_str_columnname_with_30cxx = :param__'; $overlapparams = array( 'p' => $rec1->id, 'param1' => $rec1->long_int_columnname_with_28c, 'param2' => $rec1->long_dec_columnname_with_28c, 'param_with_29_characters_long' => $rec1->long_str_columnname_with_28c, 'param_with_30_characters_long_' => $rec1->long_int_columnname_with_30cxx, 'param_' => $rec1->long_dec_columnname_with_30cxx, 'param__' => $rec1->long_str_columnname_with_30cxx); $recs = $DB->get_records_select($tablename, $overlapselect, $overlapparams); $this->assertEquals(1, count($recs)); $this->assertEquals($rec1, reset($recs)); // execute() $DB->execute("DELETE FROM {{$tablename}} WHERE $select", (array)$rec1); $this->assertEquals(0, $DB->count_records($tablename)); } public function test_get_tables() { $DB = $this->tdb; $dbman = $this->tdb->get_manager(); // Need to test with multiple DBs $table = $this->get_test_table(); $tablename = $table->getName(); $original_count = count($DB->get_tables()); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $this->assertTrue(count($DB->get_tables()) == $original_count + 1); $dbman->drop_table($table); $this->assertTrue(count($DB->get_tables()) == $original_count); } public function test_get_indexes() { $DB = $this->tdb; $dbman = $this->tdb->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $table->add_index('course', XMLDB_INDEX_NOTUNIQUE, array('course')); $table->add_index('course-id', XMLDB_INDEX_UNIQUE, array('course', 'id')); $dbman->create_table($table); $indices = $DB->get_indexes($tablename); $this->assertTrue(is_array($indices)); $this->assertEquals(count($indices), 2); // we do not care about index names for now $first = array_shift($indices); $second = array_shift($indices); if (count($first['columns']) == 2) { $composed = $first; $single = $second; } else { $composed = $second; $single = $first; } $this->assertFalse($single['unique']); $this->assertTrue($composed['unique']); $this->assertEquals(1, count($single['columns'])); $this->assertEquals(2, count($composed['columns'])); $this->assertEquals('course', $single['columns'][0]); $this->assertEquals('course', $composed['columns'][0]); $this->assertEquals('id', $composed['columns'][1]); } public function test_get_columns() { $DB = $this->tdb; $dbman = $this->tdb->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); $table->add_field('name', XMLDB_TYPE_CHAR, '255', null, null, null, 'lala'); $table->add_field('description', XMLDB_TYPE_TEXT, 'small', null, null, null, null); $table->add_field('enumfield', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, 'test2'); $table->add_field('onenum', XMLDB_TYPE_NUMBER, '10,2', null, null, null, 200); $table->add_field('onefloat', XMLDB_TYPE_FLOAT, '10,2', null, null, null, 300); $table->add_field('anotherfloat', XMLDB_TYPE_FLOAT, null, null, null, null, 400); $table->add_field('negativedfltint', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '-1'); $table->add_field('negativedfltnumber', XMLDB_TYPE_NUMBER, '10', null, XMLDB_NOTNULL, null, '-2'); $table->add_field('negativedfltfloat', XMLDB_TYPE_FLOAT, '10', null, XMLDB_NOTNULL, null, '-3'); $table->add_field('someint1', XMLDB_TYPE_INTEGER, '1', null, null, null, '0'); $table->add_field('someint2', XMLDB_TYPE_INTEGER, '2', null, null, null, '0'); $table->add_field('someint3', XMLDB_TYPE_INTEGER, '3', null, null, null, '0'); $table->add_field('someint4', XMLDB_TYPE_INTEGER, '4', null, null, null, '0'); $table->add_field('someint5', XMLDB_TYPE_INTEGER, '5', null, null, null, '0'); $table->add_field('someint6', XMLDB_TYPE_INTEGER, '6', null, null, null, '0'); $table->add_field('someint7', XMLDB_TYPE_INTEGER, '7', null, null, null, '0'); $table->add_field('someint8', XMLDB_TYPE_INTEGER, '8', null, null, null, '0'); $table->add_field('someint9', XMLDB_TYPE_INTEGER, '9', null, null, null, '0'); $table->add_field('someint10', XMLDB_TYPE_INTEGER, '10', null, null, null, '0'); $table->add_field('someint18', XMLDB_TYPE_INTEGER, '18', null, null, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $columns = $DB->get_columns($tablename); $this->assertTrue(is_array($columns)); $fields = $table->getFields(); $this->assertEquals(count($columns), count($fields)); $field = $columns['id']; $this->assertEquals('R', $field->meta_type); $this->assertTrue($field->auto_increment); $this->assertTrue($field->unique); $field = $columns['course']; $this->assertEquals('I', $field->meta_type); $this->assertFalse($field->auto_increment); $this->assertTrue($field->has_default); $this->assertEquals(0, $field->default_value); $this->assertTrue($field->not_null); for($i=1;$i<=10;$i++) { $field = $columns['someint'.$i]; $this->assertEquals('I', $field->meta_type); $this->assertGreaterThanOrEqual($i, $field->max_length); } $field = $columns['someint18']; $this->assertEquals('I', $field->meta_type); $this->assertGreaterThanOrEqual(18, $field->max_length); $field = $columns['name']; $this->assertEquals('C', $field->meta_type); $this->assertFalse($field->auto_increment); $this->assertEquals(255, $field->max_length); $this->assertTrue($field->has_default); $this->assertSame('lala', $field->default_value); $this->assertFalse($field->not_null); $field = $columns['description']; $this->assertEquals('X', $field->meta_type); $this->assertFalse($field->auto_increment); $this->assertFalse($field->has_default); $this->assertSame(null, $field->default_value); $this->assertFalse($field->not_null); $field = $columns['enumfield']; $this->assertEquals('C', $field->meta_type); $this->assertFalse($field->auto_increment); $this->assertSame('test2', $field->default_value); $this->assertTrue($field->not_null); $field = $columns['onenum']; $this->assertEquals('N', $field->meta_type); $this->assertFalse($field->auto_increment); $this->assertEquals(10, $field->max_length); $this->assertEquals(2, $field->scale); $this->assertTrue($field->has_default); $this->assertEquals(200.0, $field->default_value); $this->assertFalse($field->not_null); $field = $columns['onefloat']; $this->assertEquals('N', $field->meta_type); $this->assertFalse($field->auto_increment); $this->assertTrue($field->has_default); $this->assertEquals(300.0, $field->default_value); $this->assertFalse($field->not_null); $field = $columns['anotherfloat']; $this->assertEquals('N', $field->meta_type); $this->assertFalse($field->auto_increment); $this->assertTrue($field->has_default); $this->assertEquals(400.0, $field->default_value); $this->assertFalse($field->not_null); // Test negative defaults in numerical columns $field = $columns['negativedfltint']; $this->assertTrue($field->has_default); $this->assertEquals(-1, $field->default_value); $field = $columns['negativedfltnumber']; $this->assertTrue($field->has_default); $this->assertEquals(-2, $field->default_value); $field = $columns['negativedfltfloat']; $this->assertTrue($field->has_default); $this->assertEquals(-3, $field->default_value); for ($i = 0; $i < count($columns); $i++) { if ($i == 0) { $next_column = reset($columns); $next_field = reset($fields); } else { $next_column = next($columns); $next_field = next($fields); } $this->assertEquals($next_column->name, $next_field->getName()); } // Test get_columns for non-existing table returns empty array. MDL-30147 $columns = $DB->get_columns('xxxx'); $this->assertEquals(array(), $columns); // create something similar to "context_temp" with id column without sequence $dbman->drop_table($table); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $columns = $DB->get_columns($tablename); $this->assertFalse($columns['id']->auto_increment); } public function test_get_manager() { $DB = $this->tdb; $dbman = $this->tdb->get_manager(); $this->assertTrue($dbman instanceof database_manager); } public function test_setup_is_unicodedb() { $DB = $this->tdb; $this->assertTrue($DB->setup_is_unicodedb()); } public function test_set_debug() { //tests get_debug() too $DB = $this->tdb; $dbman = $this->tdb->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $sql = "SELECT * FROM {{$tablename}}"; $prevdebug = $DB->get_debug(); ob_start(); $DB->set_debug(true); $this->assertTrue($DB->get_debug()); $DB->execute($sql); $DB->set_debug(false); $this->assertFalse($DB->get_debug()); $debuginfo = ob_get_contents(); ob_end_clean(); $this->assertFalse($debuginfo === ''); ob_start(); $DB->execute($sql); $debuginfo = ob_get_contents(); ob_end_clean(); $this->assertTrue($debuginfo === ''); $DB->set_debug($prevdebug); } public function test_execute() { $DB = $this->tdb; $dbman = $this->tdb->get_manager(); $table1 = $this->get_test_table('1'); $tablename1 = $table1->getName(); $table1->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table1->add_field('course', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); $table1->add_field('name', XMLDB_TYPE_CHAR, '255', null, null, null, '0'); $table1->add_index('course', XMLDB_INDEX_NOTUNIQUE, array('course')); $table1->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table1); $table2 = $this->get_test_table('2'); $tablename2 = $table2->getName(); $table2->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table2->add_field('course', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); $table2->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table2); $DB->insert_record($tablename1, array('course' => 3, 'name' => 'aaa')); $DB->insert_record($tablename1, array('course' => 1, 'name' => 'bbb')); $DB->insert_record($tablename1, array('course' => 7, 'name' => 'ccc')); $DB->insert_record($tablename1, array('course' => 3, 'name' => 'ddd')); // select results are ignored $sql = "SELECT * FROM {{$tablename1}} WHERE course = :course"; $this->assertTrue($DB->execute($sql, array('course'=>3))); // throw exception on error $sql = "XXUPDATE SET XSSD"; try { $DB->execute($sql); $this->fail("Expecting an exception, none occurred"); } catch (Exception $e) { $this->assertTrue($e instanceof dml_exception); } // update records $sql = "UPDATE {{$tablename1}} SET course = 6 WHERE course = ?"; $this->assertTrue($DB->execute($sql, array('3'))); $this->assertEquals($DB->count_records($tablename1, array('course' => 6)), 2); // update records with subquery condition // confirm that the option not using table aliases is cross-db $sql = "UPDATE {{$tablename1}} SET course = 0 WHERE NOT EXISTS ( SELECT course FROM {{$tablename2}} tbl2 WHERE tbl2.course = {{$tablename1}}.course AND 1 = 0)"; // Really we don't update anything, but verify the syntax is allowed $this->assertTrue($DB->execute($sql)); // insert from one into second table $sql = "INSERT INTO {{$tablename2}} (course) SELECT course FROM {{$tablename1}}"; $this->assertTrue($DB->execute($sql)); $this->assertEquals($DB->count_records($tablename2), 4); } public function test_get_recordset() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); $table->add_field('name', XMLDB_TYPE_CHAR, '255', null, null, null, '0'); $table->add_field('onetext', XMLDB_TYPE_TEXT, 'big', null, null, null); $table->add_index('course', XMLDB_INDEX_NOTUNIQUE, array('course')); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $data = array(array('course' => 3, 'name' => 'record1', 'onetext'=>'abc'), array('course' => 3, 'name' => 'record2', 'onetext'=>'abcd'), array('course' => 5, 'name' => 'record3', 'onetext'=>'abcde')); foreach ($data as $key=>$record) { $data[$key]['id'] = $DB->insert_record($tablename, $record); } // standard recordset iteration $rs = $DB->get_recordset($tablename); $this->assertTrue($rs instanceof moodle_recordset); reset($data); foreach($rs as $record) { $data_record = current($data); foreach ($record as $k => $v) { $this->assertEquals($data_record[$k], $v); } next($data); } $rs->close(); // iterator style usage $rs = $DB->get_recordset($tablename); $this->assertTrue($rs instanceof moodle_recordset); reset($data); while ($rs->valid()) { $record = $rs->current(); $data_record = current($data); foreach ($record as $k => $v) { $this->assertEquals($data_record[$k], $v); } next($data); $rs->next(); } $rs->close(); // make sure rewind is ignored $rs = $DB->get_recordset($tablename); $this->assertTrue($rs instanceof moodle_recordset); reset($data); $i = 0; foreach($rs as $record) { $i++; $rs->rewind(); if ($i > 10) { $this->fail('revind not ignored in recordsets'); break; } $data_record = current($data); foreach ($record as $k => $v) { $this->assertEquals($data_record[$k], $v); } next($data); } $rs->close(); // test for exception throwing on text conditions being compared. (MDL-24863, unwanted auto conversion of param to int) $conditions = array('onetext' => '1'); try { $rs = $DB->get_recordset($tablename, $conditions); $this->fail('An Exception is missing, expected due to equating of text fields'); } catch (exception $e) { $this->assertTrue($e instanceof dml_exception); $this->assertEquals($e->errorcode, 'textconditionsnotallowed'); } // Test nested iteration. $rs1 = $DB->get_recordset($tablename); $i = 0; foreach($rs1 as $record1) { $rs2 = $DB->get_recordset($tablename); $i++; $j = 0; foreach($rs2 as $record2) { $j++; } $rs2->close(); $this->assertEquals($j, count($data)); } $rs1->close(); $this->assertEquals($i, count($data)); // notes: // * limits are tested in test_get_recordset_sql() // * where_clause() is used internally and is tested in test_get_records() } public function test_get_recordset_static() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('course' => 1)); $DB->insert_record($tablename, array('course' => 2)); $DB->insert_record($tablename, array('course' => 3)); $DB->insert_record($tablename, array('course' => 4)); $rs = $DB->get_recordset($tablename, array(), 'id'); $DB->set_field($tablename, 'course', 666, array('course'=>1)); $DB->delete_records($tablename, array('course'=>2)); $i = 0; foreach($rs as $record) { $i++; $this->assertEquals($i, $record->course); } $rs->close(); $this->assertEquals(4, $i); // Now repeat with limits because it may use different code. $DB->delete_records($tablename, array()); $DB->insert_record($tablename, array('course' => 1)); $DB->insert_record($tablename, array('course' => 2)); $DB->insert_record($tablename, array('course' => 3)); $DB->insert_record($tablename, array('course' => 4)); $rs = $DB->get_recordset($tablename, array(), 'id', '*', 0, 3); $DB->set_field($tablename, 'course', 666, array('course'=>1)); $DB->delete_records($tablename, array('course'=>2)); $i = 0; foreach($rs as $record) { $i++; $this->assertEquals($i, $record->course); } $rs->close(); $this->assertEquals(3, $i); } public function test_get_recordset_iterator_keys() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); $table->add_field('name', XMLDB_TYPE_CHAR, '255', null, null, null, '0'); $table->add_index('course', XMLDB_INDEX_NOTUNIQUE, array('course')); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $data = array(array('course' => 3, 'name' => 'record1'), array('course' => 3, 'name' => 'record2'), array('course' => 5, 'name' => 'record3')); foreach ($data as $key=>$record) { $data[$key]['id'] = $DB->insert_record($tablename, $record); } // Test repeated numeric keys are returned ok $rs = $DB->get_recordset($tablename, NULL, NULL, 'course, name, id'); reset($data); $count = 0; foreach($rs as $key => $record) { $data_record = current($data); $this->assertEquals($data_record['course'], $key); next($data); $count++; } $rs->close(); $this->assertEquals($count, 3); // Test string keys are returned ok $rs = $DB->get_recordset($tablename, NULL, NULL, 'name, course, id'); reset($data); $count = 0; foreach($rs as $key => $record) { $data_record = current($data); $this->assertEquals($data_record['name'], $key); next($data); $count++; } $rs->close(); $this->assertEquals($count, 3); // Test numeric not starting in 1 keys are returned ok $rs = $DB->get_recordset($tablename, NULL, 'id DESC', 'id, course, name'); $data = array_reverse($data); reset($data); $count = 0; foreach($rs as $key => $record) { $data_record = current($data); $this->assertEquals($data_record['id'], $key); next($data); $count++; } $rs->close(); $this->assertEquals($count, 3); } public function test_get_recordset_list() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, '0'); $table->add_index('course', XMLDB_INDEX_NOTUNIQUE, array('course')); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('course' => 3)); $DB->insert_record($tablename, array('course' => 3)); $DB->insert_record($tablename, array('course' => 5)); $DB->insert_record($tablename, array('course' => 2)); $DB->insert_record($tablename, array('course' => null)); $DB->insert_record($tablename, array('course' => 1)); $DB->insert_record($tablename, array('course' => 0)); $rs = $DB->get_recordset_list($tablename, 'course', array(3, 2)); $counter = 0; foreach ($rs as $record) { $counter++; } $this->assertEquals(3, $counter); $rs->close(); $rs = $DB->get_recordset_list($tablename, 'course', array(3)); $counter = 0; foreach ($rs as $record) { $counter++; } $this->assertEquals(2, $counter); $rs->close(); $rs = $DB->get_recordset_list($tablename, 'course', array(null)); $counter = 0; foreach ($rs as $record) { $counter++; } $this->assertEquals(1, $counter); $rs->close(); $rs = $DB->get_recordset_list($tablename, 'course', array(6, null)); $counter = 0; foreach ($rs as $record) { $counter++; } $this->assertEquals(1, $counter); $rs->close(); $rs = $DB->get_recordset_list($tablename, 'course', array(null, 5, 5, 5)); $counter = 0; foreach ($rs as $record) { $counter++; } $this->assertEquals(2, $counter); $rs->close(); $rs = $DB->get_recordset_list($tablename, 'course', array(true)); $counter = 0; foreach ($rs as $record) { $counter++; } $this->assertEquals(1, $counter); $rs->close(); $rs = $DB->get_recordset_list($tablename, 'course', array(false)); $counter = 0; foreach ($rs as $record) { $counter++; } $this->assertEquals(1, $counter); $rs->close(); $rs = $DB->get_recordset_list($tablename, 'course',array()); // Must return 0 rows without conditions. MDL-17645 $counter = 0; foreach ($rs as $record) { $counter++; } $rs->close(); $this->assertEquals(0, $counter); // notes: // * limits are tested in test_get_recordset_sql() // * where_clause() is used internally and is tested in test_get_records() } public function test_get_recordset_select() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('course' => 3)); $DB->insert_record($tablename, array('course' => 3)); $DB->insert_record($tablename, array('course' => 5)); $DB->insert_record($tablename, array('course' => 2)); $rs = $DB->get_recordset_select($tablename, ''); $counter = 0; foreach ($rs as $record) { $counter++; } $rs->close(); $this->assertEquals(4, $counter); $this->assertNotEmpty($rs = $DB->get_recordset_select($tablename, 'course = 3')); $counter = 0; foreach ($rs as $record) { $counter++; } $rs->close(); $this->assertEquals(2, $counter); // notes: // * limits are tested in test_get_recordset_sql() } public function test_get_recordset_sql() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $inskey1 = $DB->insert_record($tablename, array('course' => 3)); $inskey2 = $DB->insert_record($tablename, array('course' => 5)); $inskey3 = $DB->insert_record($tablename, array('course' => 4)); $inskey4 = $DB->insert_record($tablename, array('course' => 3)); $inskey5 = $DB->insert_record($tablename, array('course' => 2)); $inskey6 = $DB->insert_record($tablename, array('course' => 1)); $inskey7 = $DB->insert_record($tablename, array('course' => 0)); $rs = $DB->get_recordset_sql("SELECT * FROM {{$tablename}} WHERE course = ?", array(3)); $counter = 0; foreach ($rs as $record) { $counter++; } $rs->close(); $this->assertEquals(2, $counter); // limits - only need to test this case, the rest have been tested by test_get_records_sql() // only limitfrom = skips that number of records $rs = $DB->get_recordset_sql("SELECT * FROM {{$tablename}} ORDER BY id", null, 2, 0); $records = array(); foreach($rs as $key => $record) { $records[$key] = $record; } $rs->close(); $this->assertEquals(5, count($records)); $this->assertEquals($inskey3, reset($records)->id); $this->assertEquals($inskey7, end($records)->id); // note: fetching nulls, empties, LOBs already tested by test_insert_record() no needed here } public function test_export_table_recordset() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $ids = array(); $ids[] = $DB->insert_record($tablename, array('course' => 3)); $ids[] = $DB->insert_record($tablename, array('course' => 5)); $ids[] = $DB->insert_record($tablename, array('course' => 4)); $ids[] = $DB->insert_record($tablename, array('course' => 3)); $ids[] = $DB->insert_record($tablename, array('course' => 2)); $ids[] = $DB->insert_record($tablename, array('course' => 1)); $ids[] = $DB->insert_record($tablename, array('course' => 0)); $rs = $DB->export_table_recordset($tablename); $rids = array(); foreach ($rs as $record) { $rids[] = $record->id; } $rs->close(); $this->assertEquals($ids, $rids, '', 0, 0, true); } public function test_get_records() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); $table->add_field('onetext', XMLDB_TYPE_TEXT, 'big', null, null, null); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('course' => 3)); $DB->insert_record($tablename, array('course' => 3)); $DB->insert_record($tablename, array('course' => 5)); $DB->insert_record($tablename, array('course' => 2)); // All records $records = $DB->get_records($tablename); $this->assertEquals(4, count($records)); $this->assertEquals(3, $records[1]->course); $this->assertEquals(3, $records[2]->course); $this->assertEquals(5, $records[3]->course); $this->assertEquals(2, $records[4]->course); // Records matching certain conditions $records = $DB->get_records($tablename, array('course' => 3)); $this->assertEquals(2, count($records)); $this->assertEquals(3, $records[1]->course); $this->assertEquals(3, $records[2]->course); // All records sorted by course $records = $DB->get_records($tablename, null, 'course'); $this->assertEquals(4, count($records)); $current_record = reset($records); $this->assertEquals(4, $current_record->id); $current_record = next($records); $this->assertEquals(1, $current_record->id); $current_record = next($records); $this->assertEquals(2, $current_record->id); $current_record = next($records); $this->assertEquals(3, $current_record->id); // All records, but get only one field $records = $DB->get_records($tablename, null, '', 'id'); $this->assertFalse(isset($records[1]->course)); $this->assertTrue(isset($records[1]->id)); $this->assertEquals(4, count($records)); // Booleans into params $records = $DB->get_records($tablename, array('course' => true)); $this->assertEquals(0, count($records)); $records = $DB->get_records($tablename, array('course' => false)); $this->assertEquals(0, count($records)); // test for exception throwing on text conditions being compared. (MDL-24863, unwanted auto conversion of param to int) $conditions = array('onetext' => '1'); try { $records = $DB->get_records($tablename, $conditions); if (debugging()) { // only in debug mode - hopefully all devs test code in debug mode... $this->fail('An Exception is missing, expected due to equating of text fields'); } } catch (exception $e) { $this->assertTrue($e instanceof dml_exception); $this->assertEquals($e->errorcode, 'textconditionsnotallowed'); } // test get_records passing non-existing table // with params try { $records = $DB->get_records('xxxx', array('id' => 0)); $this->fail('An Exception is missing, expected due to query against non-existing table'); } catch (exception $e) { $this->assertTrue($e instanceof dml_exception); if (debugging()) { // information for developers only, normal users get general error message $this->assertEquals($e->errorcode, 'ddltablenotexist'); } } // and without params try { $records = $DB->get_records('xxxx', array()); $this->fail('An Exception is missing, expected due to query against non-existing table'); } catch (exception $e) { $this->assertTrue($e instanceof dml_exception); if (debugging()) { // information for developers only, normal users get general error message $this->assertEquals($e->errorcode, 'ddltablenotexist'); } } // test get_records passing non-existing column try { $records = $DB->get_records($tablename, array('xxxx' => 0)); $this->fail('An Exception is missing, expected due to query against non-existing column'); } catch (exception $e) { $this->assertTrue($e instanceof dml_exception); if (debugging()) { // information for developers only, normal users get general error message $this->assertEquals($e->errorcode, 'ddlfieldnotexist'); } } // note: delegate limits testing to test_get_records_sql() } public function test_get_records_list() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('course' => 3)); $DB->insert_record($tablename, array('course' => 3)); $DB->insert_record($tablename, array('course' => 5)); $DB->insert_record($tablename, array('course' => 2)); $records = $DB->get_records_list($tablename, 'course', array(3, 2)); $this->assertTrue(is_array($records)); $this->assertEquals(3, count($records)); $this->assertEquals(1, reset($records)->id); $this->assertEquals(2, next($records)->id); $this->assertEquals(4, next($records)->id); $this->assertSame(array(), $records = $DB->get_records_list($tablename, 'course', array())); // Must return 0 rows without conditions. MDL-17645 $this->assertEquals(0, count($records)); // note: delegate limits testing to test_get_records_sql() } public function test_get_records_sql() { global $CFG; $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $inskey1 = $DB->insert_record($tablename, array('course' => 3)); $inskey2 = $DB->insert_record($tablename, array('course' => 5)); $inskey3 = $DB->insert_record($tablename, array('course' => 4)); $inskey4 = $DB->insert_record($tablename, array('course' => 3)); $inskey5 = $DB->insert_record($tablename, array('course' => 2)); $inskey6 = $DB->insert_record($tablename, array('course' => 1)); $inskey7 = $DB->insert_record($tablename, array('course' => 0)); $table2 = $this->get_test_table("2"); $tablename2 = $table2->getName(); $table2->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table2->add_field('course', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); $table2->add_field('nametext', XMLDB_TYPE_TEXT, 'small', null, null, null, null); $table2->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table2); $DB->insert_record($tablename2, array('course'=>3, 'nametext'=>'badabing')); $DB->insert_record($tablename2, array('course'=>4, 'nametext'=>'badabang')); $DB->insert_record($tablename2, array('course'=>5, 'nametext'=>'badabung')); $DB->insert_record($tablename2, array('course'=>6, 'nametext'=>'badabong')); $records = $DB->get_records_sql("SELECT * FROM {{$tablename}} WHERE course = ?", array(3)); $this->assertEquals(2, count($records)); $this->assertEquals($inskey1, reset($records)->id); $this->assertEquals($inskey4, next($records)->id); // Awful test, requires debug enabled and sent to browser. Let's do that and restore after test $records = $DB->get_records_sql("SELECT course AS id, course AS course FROM {{$tablename}}", null); $this->assertDebuggingCalled(); $this->assertEquals(6, count($records)); $CFG->debug = DEBUG_MINIMAL; $records = $DB->get_records_sql("SELECT course AS id, course AS course FROM {{$tablename}}", null); $this->assertDebuggingNotCalled(); $this->assertEquals(6, count($records)); $CFG->debug = DEBUG_DEVELOPER; // negative limits = no limits $records = $DB->get_records_sql("SELECT * FROM {{$tablename}} ORDER BY id", null, -1, -1); $this->assertEquals(7, count($records)); // zero limits = no limits $records = $DB->get_records_sql("SELECT * FROM {{$tablename}} ORDER BY id", null, 0, 0); $this->assertEquals(7, count($records)); // only limitfrom = skips that number of records $records = $DB->get_records_sql("SELECT * FROM {{$tablename}} ORDER BY id", null, 2, 0); $this->assertEquals(5, count($records)); $this->assertEquals($inskey3, reset($records)->id); $this->assertEquals($inskey7, end($records)->id); // only limitnum = fetches that number of records $records = $DB->get_records_sql("SELECT * FROM {{$tablename}} ORDER BY id", null, 0, 3); $this->assertEquals(3, count($records)); $this->assertEquals($inskey1, reset($records)->id); $this->assertEquals($inskey3, end($records)->id); // both limitfrom and limitnum = skips limitfrom records and fetches limitnum ones $records = $DB->get_records_sql("SELECT * FROM {{$tablename}} ORDER BY id", null, 3, 2); $this->assertEquals(2, count($records)); $this->assertEquals($inskey4, reset($records)->id); $this->assertEquals($inskey5, end($records)->id); // both limitfrom and limitnum in query having subqueris // note the subquery skips records with course = 0 and 3 $sql = "SELECT * FROM {{$tablename}} WHERE course NOT IN ( SELECT course FROM {{$tablename}} WHERE course IN (0, 3)) ORDER BY course"; $records = $DB->get_records_sql($sql, null, 0, 2); // Skip 0, get 2 $this->assertEquals(2, count($records)); $this->assertEquals($inskey6, reset($records)->id); $this->assertEquals($inskey5, end($records)->id); $records = $DB->get_records_sql($sql, null, 2, 2); // Skip 2, get 2 $this->assertEquals(2, count($records)); $this->assertEquals($inskey3, reset($records)->id); $this->assertEquals($inskey2, end($records)->id); // test 2 tables with aliases and limits with order bys $sql = "SELECT t1.id, t1.course AS cid, t2.nametext FROM {{$tablename}} t1, {{$tablename2}} t2 WHERE t2.course=t1.course ORDER BY t1.course, ". $DB->sql_compare_text('t2.nametext'); $records = $DB->get_records_sql($sql, null, 2, 2); // Skip courses 3 and 6, get 4 and 5 $this->assertEquals(2, count($records)); $this->assertEquals('5', end($records)->cid); $this->assertEquals('4', reset($records)->cid); // test 2 tables with aliases and limits with the highest INT limit works $records = $DB->get_records_sql($sql, null, 2, PHP_INT_MAX); // Skip course {3,6}, get {4,5} $this->assertEquals(2, count($records)); $this->assertEquals('5', end($records)->cid); $this->assertEquals('4', reset($records)->cid); // test 2 tables with aliases and limits with order bys (limit which is highest INT number) $records = $DB->get_records_sql($sql, null, PHP_INT_MAX, 2); // Skip all courses $this->assertEquals(0, count($records)); // test 2 tables with aliases and limits with order bys (limit which s highest INT number) $records = $DB->get_records_sql($sql, null, PHP_INT_MAX, PHP_INT_MAX); // Skip all courses $this->assertEquals(0, count($records)); // TODO: Test limits in queries having DISTINCT clauses // note: fetching nulls, empties, LOBs already tested by test_update_record() no needed here } public function test_get_records_menu() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('course' => 3)); $DB->insert_record($tablename, array('course' => 3)); $DB->insert_record($tablename, array('course' => 5)); $DB->insert_record($tablename, array('course' => 2)); $records = $DB->get_records_menu($tablename, array('course' => 3)); $this->assertTrue(is_array($records)); $this->assertEquals(2, count($records)); $this->assertFalse(empty($records[1])); $this->assertFalse(empty($records[2])); $this->assertEquals(3, $records[1]); $this->assertEquals(3, $records[2]); // note: delegate limits testing to test_get_records_sql() } public function test_get_records_select_menu() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('course' => 3)); $DB->insert_record($tablename, array('course' => 2)); $DB->insert_record($tablename, array('course' => 3)); $DB->insert_record($tablename, array('course' => 5)); $records = $DB->get_records_select_menu($tablename, "course > ?", array(2)); $this->assertTrue(is_array($records)); $this->assertEquals(3, count($records)); $this->assertFalse(empty($records[1])); $this->assertTrue(empty($records[2])); $this->assertFalse(empty($records[3])); $this->assertFalse(empty($records[4])); $this->assertEquals(3, $records[1]); $this->assertEquals(3, $records[3]); $this->assertEquals(5, $records[4]); // note: delegate limits testing to test_get_records_sql() } public function test_get_records_sql_menu() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('course' => 3)); $DB->insert_record($tablename, array('course' => 2)); $DB->insert_record($tablename, array('course' => 3)); $DB->insert_record($tablename, array('course' => 5)); $records = $DB->get_records_sql_menu("SELECT * FROM {{$tablename}} WHERE course > ?", array(2)); $this->assertTrue(is_array($records)); $this->assertEquals(3, count($records)); $this->assertFalse(empty($records[1])); $this->assertTrue(empty($records[2])); $this->assertFalse(empty($records[3])); $this->assertFalse(empty($records[4])); $this->assertEquals(3, $records[1]); $this->assertEquals(3, $records[3]); $this->assertEquals(5, $records[4]); // note: delegate limits testing to test_get_records_sql() } public function test_get_record() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('course' => 3)); $DB->insert_record($tablename, array('course' => 2)); $record = $DB->get_record($tablename, array('id' => 2)); $this->assertTrue($record instanceof stdClass); $this->assertEquals(2, $record->course); $this->assertEquals(2, $record->id); } public function test_get_record_select() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('course' => 3)); $DB->insert_record($tablename, array('course' => 2)); $record = $DB->get_record_select($tablename, "id = ?", array(2)); $this->assertTrue($record instanceof stdClass); $this->assertEquals(2, $record->course); // note: delegates limit testing to test_get_records_sql() } public function test_get_record_sql() { global $CFG; $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('course' => 3)); $DB->insert_record($tablename, array('course' => 2)); // standard use $record = $DB->get_record_sql("SELECT * FROM {{$tablename}} WHERE id = ?", array(2)); $this->assertTrue($record instanceof stdClass); $this->assertEquals(2, $record->course); $this->assertEquals(2, $record->id); // backwards compatibility with $ignoremultiple $this->assertFalse((bool)IGNORE_MISSING); $this->assertTrue((bool)IGNORE_MULTIPLE); // record not found - ignore $this->assertFalse($DB->get_record_sql("SELECT * FROM {{$tablename}} WHERE id = ?", array(666), IGNORE_MISSING)); $this->assertFalse($DB->get_record_sql("SELECT * FROM {{$tablename}} WHERE id = ?", array(666), IGNORE_MULTIPLE)); // record not found error try { $DB->get_record_sql("SELECT * FROM {{$tablename}} WHERE id = ?", array(666), MUST_EXIST); $this->fail("Exception expected"); } catch (dml_missing_record_exception $e) { $this->assertTrue(true); } $this->assertNotEmpty($DB->get_record_sql("SELECT * FROM {{$tablename}}", array(), IGNORE_MISSING)); $this->assertDebuggingCalled(); $CFG->debug = DEBUG_MINIMAL; $this->assertNotEmpty($DB->get_record_sql("SELECT * FROM {{$tablename}}", array(), IGNORE_MISSING)); $this->assertDebuggingNotCalled(); $CFG->debug = DEBUG_DEVELOPER; // multiple matches ignored $this->assertNotEmpty($DB->get_record_sql("SELECT * FROM {{$tablename}}", array(), IGNORE_MULTIPLE)); // multiple found error try { $DB->get_record_sql("SELECT * FROM {{$tablename}}", array(), MUST_EXIST); $this->fail("Exception expected"); } catch (dml_multiple_records_exception $e) { $this->assertTrue(true); } } public function test_get_field() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); $table->add_field('onetext', XMLDB_TYPE_TEXT, 'big', null, null, null); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $id1 = $DB->insert_record($tablename, array('course' => 3)); $DB->insert_record($tablename, array('course' => 5)); $DB->insert_record($tablename, array('course' => 5)); $this->assertEquals(3, $DB->get_field($tablename, 'course', array('id' => $id1))); $this->assertEquals(3, $DB->get_field($tablename, 'course', array('course' => 3))); $this->assertSame(false, $DB->get_field($tablename, 'course', array('course' => 11), IGNORE_MISSING)); try { $DB->get_field($tablename, 'course', array('course' => 4), MUST_EXIST); $this->fail('Exception expected due to missing record'); } catch (dml_exception $ex) { $this->assertTrue(true); } $this->assertEquals(5, $DB->get_field($tablename, 'course', array('course' => 5), IGNORE_MULTIPLE)); $this->assertDebuggingNotCalled(); $this->assertEquals(5, $DB->get_field($tablename, 'course', array('course' => 5), IGNORE_MISSING)); $this->assertDebuggingCalled(); // test for exception throwing on text conditions being compared. (MDL-24863, unwanted auto conversion of param to int) $conditions = array('onetext' => '1'); try { $DB->get_field($tablename, 'course', $conditions); if (debugging()) { // only in debug mode - hopefully all devs test code in debug mode... $this->fail('An Exception is missing, expected due to equating of text fields'); } } catch (exception $e) { $this->assertTrue($e instanceof dml_exception); $this->assertEquals($e->errorcode, 'textconditionsnotallowed'); } } public function test_get_field_select() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('course' => 3)); $this->assertEquals(3, $DB->get_field_select($tablename, 'course', "id = ?", array(1))); } public function test_get_field_sql() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('course' => 3)); $this->assertEquals(3, $DB->get_field_sql("SELECT course FROM {{$tablename}} WHERE id = ?", array(1))); } public function test_get_fieldset_select() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('course' => 1)); $DB->insert_record($tablename, array('course' => 3)); $DB->insert_record($tablename, array('course' => 2)); $DB->insert_record($tablename, array('course' => 6)); $fieldset = $DB->get_fieldset_select($tablename, 'course', "course > ?", array(1)); $this->assertTrue(is_array($fieldset)); $this->assertEquals(3, count($fieldset)); $this->assertEquals(3, $fieldset[0]); $this->assertEquals(2, $fieldset[1]); $this->assertEquals(6, $fieldset[2]); } public function test_get_fieldset_sql() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('course' => 1)); $DB->insert_record($tablename, array('course' => 3)); $DB->insert_record($tablename, array('course' => 2)); $DB->insert_record($tablename, array('course' => 6)); $fieldset = $DB->get_fieldset_sql("SELECT * FROM {{$tablename}} WHERE course > ?", array(1)); $this->assertTrue(is_array($fieldset)); $this->assertEquals(3, count($fieldset)); $this->assertEquals(2, $fieldset[0]); $this->assertEquals(3, $fieldset[1]); $this->assertEquals(4, $fieldset[2]); } public function test_insert_record_raw() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); $table->add_field('onechar', XMLDB_TYPE_CHAR, '100', null, null, null, 'onestring'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $record = (object)array('course' => 1, 'onechar' => 'xx'); $before = clone($record); $result = $DB->insert_record_raw($tablename, $record); $this->assertSame(1, $result); $this->assertEquals($record, $before); $record = $DB->get_record($tablename, array('course' => 1)); $this->assertTrue($record instanceof stdClass); $this->assertSame('xx', $record->onechar); $result = $DB->insert_record_raw($tablename, array('course' => 2, 'onechar' => 'yy'), false); $this->assertSame(true, $result); // note: bulk not implemented yet $DB->insert_record_raw($tablename, array('course' => 3, 'onechar' => 'zz'), true, true); $record = $DB->get_record($tablename, array('course' => 3)); $this->assertTrue($record instanceof stdClass); $this->assertSame('zz', $record->onechar); // custom sequence (id) - returnid is ignored $result = $DB->insert_record_raw($tablename, array('id' => 10, 'course' => 3, 'onechar' => 'bb'), true, false, true); $this->assertSame(true, $result); $record = $DB->get_record($tablename, array('id' => 10)); $this->assertTrue($record instanceof stdClass); $this->assertSame('bb', $record->onechar); // custom sequence - missing id error try { $DB->insert_record_raw($tablename, array('course' => 3, 'onechar' => 'bb'), true, false, true); $this->fail('Exception expected due to missing record'); } catch (coding_exception $ex) { $this->assertTrue(true); } // wrong column error try { $DB->insert_record_raw($tablename, array('xxxxx' => 3, 'onechar' => 'bb')); $this->fail('Exception expected due to invalid column'); } catch (dml_exception $ex) { $this->assertTrue(true); } // create something similar to "context_temp" with id column without sequence $dbman->drop_table($table); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $record = (object)array('id'=>5, 'course' => 1); $DB->insert_record_raw($tablename, $record, false, false, true); $record = $DB->get_record($tablename, array()); $this->assertEquals(5, $record->id); } public function test_insert_record() { // All the information in this test is fetched from DB by get_recordset() so we // have such method properly tested against nulls, empties and friends... $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); $table->add_field('oneint', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, 100); $table->add_field('onenum', XMLDB_TYPE_NUMBER, '10,2', null, null, null, 200); $table->add_field('onechar', XMLDB_TYPE_CHAR, '100', null, null, null, 'onestring'); $table->add_field('onetext', XMLDB_TYPE_TEXT, 'big', null, null, null); $table->add_field('onebinary', XMLDB_TYPE_BINARY, 'big', null, null, null); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $this->assertSame(1, $DB->insert_record($tablename, array('course' => 1), true)); $record = $DB->get_record($tablename, array('course' => 1)); $this->assertEquals(1, $record->id); $this->assertEquals(100, $record->oneint); // Just check column defaults have been applied $this->assertEquals(200, $record->onenum); $this->assertSame('onestring', $record->onechar); $this->assertNull($record->onetext); $this->assertNull($record->onebinary); // without returning id, bulk not implemented $result = $this->assertSame(true, $DB->insert_record($tablename, array('course' => 99), false, true)); $record = $DB->get_record($tablename, array('course' => 99)); $this->assertEquals(2, $record->id); $this->assertEquals(99, $record->course); // Check nulls are set properly for all types $record = new stdClass(); $record->oneint = null; $record->onenum = null; $record->onechar = null; $record->onetext = null; $record->onebinary = null; $recid = $DB->insert_record($tablename, $record); $record = $DB->get_record($tablename, array('id' => $recid)); $this->assertEquals(0, $record->course); $this->assertNull($record->oneint); $this->assertNull($record->onenum); $this->assertNull($record->onechar); $this->assertNull($record->onetext); $this->assertNull($record->onebinary); // Check zeros are set properly for all types $record = new stdClass(); $record->oneint = 0; $record->onenum = 0; $recid = $DB->insert_record($tablename, $record); $record = $DB->get_record($tablename, array('id' => $recid)); $this->assertEquals(0, $record->oneint); $this->assertEquals(0, $record->onenum); // Check booleans are set properly for all types $record = new stdClass(); $record->oneint = true; // trues $record->onenum = true; $record->onechar = true; $record->onetext = true; $recid = $DB->insert_record($tablename, $record); $record = $DB->get_record($tablename, array('id' => $recid)); $this->assertEquals(1, $record->oneint); $this->assertEquals(1, $record->onenum); $this->assertEquals(1, $record->onechar); $this->assertEquals(1, $record->onetext); $record = new stdClass(); $record->oneint = false; // falses $record->onenum = false; $record->onechar = false; $record->onetext = false; $recid = $DB->insert_record($tablename, $record); $record = $DB->get_record($tablename, array('id' => $recid)); $this->assertEquals(0, $record->oneint); $this->assertEquals(0, $record->onenum); $this->assertEquals(0, $record->onechar); $this->assertEquals(0, $record->onetext); // Check string data causes exception in numeric types $record = new stdClass(); $record->oneint = 'onestring'; $record->onenum = 0; try { $DB->insert_record($tablename, $record); $this->fail("Expecting an exception, none occurred"); } catch (exception $e) { $this->assertTrue($e instanceof dml_exception); } $record = new stdClass(); $record->oneint = 0; $record->onenum = 'onestring'; try { $DB->insert_record($tablename, $record); $this->fail("Expecting an exception, none occurred"); } catch (exception $e) { $this->assertTrue($e instanceof dml_exception); } // Check empty string data is stored as 0 in numeric datatypes $record = new stdClass(); $record->oneint = ''; // empty string $record->onenum = 0; $recid = $DB->insert_record($tablename, $record); $record = $DB->get_record($tablename, array('id' => $recid)); $this->assertTrue(is_numeric($record->oneint) && $record->oneint == 0); $record = new stdClass(); $record->oneint = 0; $record->onenum = ''; // empty string $recid = $DB->insert_record($tablename, $record); $record = $DB->get_record($tablename, array('id' => $recid)); $this->assertTrue(is_numeric($record->onenum) && $record->onenum == 0); // Check empty strings are set properly in string types $record = new stdClass(); $record->oneint = 0; $record->onenum = 0; $record->onechar = ''; $record->onetext = ''; $recid = $DB->insert_record($tablename, $record); $record = $DB->get_record($tablename, array('id' => $recid)); $this->assertTrue($record->onechar === ''); $this->assertTrue($record->onetext === ''); // Check operation ((210.10 + 39.92) - 150.02) against numeric types $record = new stdClass(); $record->oneint = ((210.10 + 39.92) - 150.02); $record->onenum = ((210.10 + 39.92) - 150.02); $recid = $DB->insert_record($tablename, $record); $record = $DB->get_record($tablename, array('id' => $recid)); $this->assertEquals(100, $record->oneint); $this->assertEquals(100, $record->onenum); // Check various quotes/backslashes combinations in string types $teststrings = array( 'backslashes and quotes alone (even): "" \'\' \\\\', 'backslashes and quotes alone (odd): """ \'\'\' \\\\\\', 'backslashes and quotes sequences (even): \\"\\" \\\'\\\'', 'backslashes and quotes sequences (odd): \\"\\"\\" \\\'\\\'\\\''); foreach ($teststrings as $teststring) { $record = new stdClass(); $record->onechar = $teststring; $record->onetext = $teststring; $recid = $DB->insert_record($tablename, $record); $record = $DB->get_record($tablename, array('id' => $recid)); $this->assertEquals($teststring, $record->onechar); $this->assertEquals($teststring, $record->onetext); } // Check LOBs in text/binary columns $clob = file_get_contents(__DIR__ . '/fixtures/clob.txt'); $blob = file_get_contents(__DIR__ . '/fixtures/randombinary'); $record = new stdClass(); $record->onetext = $clob; $record->onebinary = $blob; $recid = $DB->insert_record($tablename, $record); $rs = $DB->get_recordset($tablename, array('id' => $recid)); $record = $rs->current(); $rs->close(); $this->assertEquals($clob, $record->onetext, 'Test CLOB insert (full contents output disabled)'); $this->assertEquals($blob, $record->onebinary, 'Test BLOB insert (full contents output disabled)'); // And "small" LOBs too, just in case $newclob = substr($clob, 0, 500); $newblob = substr($blob, 0, 250); $record = new stdClass(); $record->onetext = $newclob; $record->onebinary = $newblob; $recid = $DB->insert_record($tablename, $record); $rs = $DB->get_recordset($tablename, array('id' => $recid)); $record = $rs->current(); $rs->close(); $this->assertEquals($newclob, $record->onetext, 'Test "small" CLOB insert (full contents output disabled)'); $this->assertEquals($newblob, $record->onebinary, 'Test "small" BLOB insert (full contents output disabled)'); $this->assertEquals(false, $rs->key()); // Ensure recordset key() method to be working ok after closing // And "diagnostic" LOBs too, just in case $newclob = '\'"\\;/ěščřžýáíé'; $newblob = '\'"\\;/ěščřžýáíé'; $record = new stdClass(); $record->onetext = $newclob; $record->onebinary = $newblob; $recid = $DB->insert_record($tablename, $record); $rs = $DB->get_recordset($tablename, array('id' => $recid)); $record = $rs->current(); $rs->close(); $this->assertSame($newclob, $record->onetext); $this->assertSame($newblob, $record->onebinary); $this->assertEquals(false, $rs->key()); // Ensure recordset key() method to be working ok after closing // test data is not modified $record = new stdClass(); $record->id = -1; // has to be ignored $record->course = 3; $record->lalala = 'lalal'; // unused $before = clone($record); $DB->insert_record($tablename, $record); $this->assertEquals($record, $before); // make sure the id is always increasing and never reuses the same id $id1 = $DB->insert_record($tablename, array('course' => 3)); $id2 = $DB->insert_record($tablename, array('course' => 3)); $this->assertTrue($id1 < $id2); $DB->delete_records($tablename, array('id'=>$id2)); $id3 = $DB->insert_record($tablename, array('course' => 3)); $this->assertTrue($id2 < $id3); $DB->delete_records($tablename, array()); $id4 = $DB->insert_record($tablename, array('course' => 3)); $this->assertTrue($id3 < $id4); // Test saving a float in a CHAR column, and reading it back. $id = $DB->insert_record($tablename, array('onechar' => 1.0)); $this->assertEquals(1.0, $DB->get_field($tablename, 'onechar', array('id' => $id))); $id = $DB->insert_record($tablename, array('onechar' => 1e20)); $this->assertEquals(1e20, $DB->get_field($tablename, 'onechar', array('id' => $id))); $id = $DB->insert_record($tablename, array('onechar' => 1e-4)); $this->assertEquals(1e-4, $DB->get_field($tablename, 'onechar', array('id' => $id))); $id = $DB->insert_record($tablename, array('onechar' => 1e-5)); $this->assertEquals(1e-5, $DB->get_field($tablename, 'onechar', array('id' => $id))); $id = $DB->insert_record($tablename, array('onechar' => 1e-300)); $this->assertEquals(1e-300, $DB->get_field($tablename, 'onechar', array('id' => $id))); $id = $DB->insert_record($tablename, array('onechar' => 1e300)); $this->assertEquals(1e300, $DB->get_field($tablename, 'onechar', array('id' => $id))); // Test saving a float in a TEXT column, and reading it back. $id = $DB->insert_record($tablename, array('onetext' => 1.0)); $this->assertEquals(1.0, $DB->get_field($tablename, 'onetext', array('id' => $id))); $id = $DB->insert_record($tablename, array('onetext' => 1e20)); $this->assertEquals(1e20, $DB->get_field($tablename, 'onetext', array('id' => $id))); $id = $DB->insert_record($tablename, array('onetext' => 1e-4)); $this->assertEquals(1e-4, $DB->get_field($tablename, 'onetext', array('id' => $id))); $id = $DB->insert_record($tablename, array('onetext' => 1e-5)); $this->assertEquals(1e-5, $DB->get_field($tablename, 'onetext', array('id' => $id))); $id = $DB->insert_record($tablename, array('onetext' => 1e-300)); $this->assertEquals(1e-300, $DB->get_field($tablename, 'onetext', array('id' => $id))); $id = $DB->insert_record($tablename, array('onetext' => 1e300)); $this->assertEquals(1e300, $DB->get_field($tablename, 'onetext', array('id' => $id))); // Test that inserting data violating one unique key leads to error. // Empty the table completely. $this->assertTrue($DB->delete_records($tablename)); // Add one unique constraint (index). $key = new xmldb_key('testuk', XMLDB_KEY_UNIQUE, array('course', 'oneint')); $dbman->add_key($table, $key); // Let's insert one record violating the constraint multiple times. $record = (object)array('course' => 1, 'oneint' => 1); $this->assertTrue($DB->insert_record($tablename, $record, false)); // insert 1st. No problem expected. // Re-insert same record, not returning id. dml_exception expected. try { $DB->insert_record($tablename, $record, false); $this->fail("Expecting an exception, none occurred"); } catch (exception $e) { $this->assertTrue($e instanceof dml_exception); } // Re-insert same record, returning id. dml_exception expected. try { $DB->insert_record($tablename, $record, true); $this->fail("Expecting an exception, none occurred"); } catch (exception $e) { $this->assertTrue($e instanceof dml_exception); } } public function test_import_record() { // All the information in this test is fetched from DB by get_recordset() so we // have such method properly tested against nulls, empties and friends... $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); $table->add_field('oneint', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, 100); $table->add_field('onenum', XMLDB_TYPE_NUMBER, '10,2', null, null, null, 200); $table->add_field('onechar', XMLDB_TYPE_CHAR, '100', null, null, null, 'onestring'); $table->add_field('onetext', XMLDB_TYPE_TEXT, 'big', null, null, null); $table->add_field('onebinary', XMLDB_TYPE_BINARY, 'big', null, null, null); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $this->assertSame(1, $DB->insert_record($tablename, array('course' => 1), true)); $record = $DB->get_record($tablename, array('course' => 1)); $this->assertEquals(1, $record->id); $this->assertEquals(100, $record->oneint); // Just check column defaults have been applied $this->assertEquals(200, $record->onenum); $this->assertSame('onestring', $record->onechar); $this->assertNull($record->onetext); $this->assertNull($record->onebinary); // ignore extra columns $record = (object)array('id'=>13, 'course'=>2, 'xxxx'=>788778); $before = clone($record); $this->assertSame(true, $DB->import_record($tablename, $record)); $this->assertEquals($record, $before); $records = $DB->get_records($tablename); $this->assertEquals(2, $records[13]->course); // Check nulls are set properly for all types $record = new stdClass(); $record->id = 20; $record->oneint = null; $record->onenum = null; $record->onechar = null; $record->onetext = null; $record->onebinary = null; $this->assertTrue($DB->import_record($tablename, $record)); $record = $DB->get_record($tablename, array('id' => 20)); $this->assertEquals(0, $record->course); $this->assertNull($record->oneint); $this->assertNull($record->onenum); $this->assertNull($record->onechar); $this->assertNull($record->onetext); $this->assertNull($record->onebinary); // Check zeros are set properly for all types $record = new stdClass(); $record->id = 23; $record->oneint = 0; $record->onenum = 0; $this->assertTrue($DB->import_record($tablename, $record)); $record = $DB->get_record($tablename, array('id' => 23)); $this->assertEquals(0, $record->oneint); $this->assertEquals(0, $record->onenum); // Check string data causes exception in numeric types $record = new stdClass(); $record->id = 32; $record->oneint = 'onestring'; $record->onenum = 0; try { $DB->import_record($tablename, $record); $this->fail("Expecting an exception, none occurred"); } catch (exception $e) { $this->assertTrue($e instanceof dml_exception); } $record = new stdClass(); $record->id = 35; $record->oneint = 0; $record->onenum = 'onestring'; try { $DB->import_record($tablename, $record); $this->fail("Expecting an exception, none occurred"); } catch (exception $e) { $this->assertTrue($e instanceof dml_exception); } // Check empty strings are set properly in string types $record = new stdClass(); $record->id = 44; $record->oneint = 0; $record->onenum = 0; $record->onechar = ''; $record->onetext = ''; $this->assertTrue($DB->import_record($tablename, $record)); $record = $DB->get_record($tablename, array('id' => 44)); $this->assertTrue($record->onechar === ''); $this->assertTrue($record->onetext === ''); // Check operation ((210.10 + 39.92) - 150.02) against numeric types $record = new stdClass(); $record->id = 47; $record->oneint = ((210.10 + 39.92) - 150.02); $record->onenum = ((210.10 + 39.92) - 150.02); $this->assertTrue($DB->import_record($tablename, $record)); $record = $DB->get_record($tablename, array('id' => 47)); $this->assertEquals(100, $record->oneint); $this->assertEquals(100, $record->onenum); // Check various quotes/backslashes combinations in string types $i = 50; $teststrings = array( 'backslashes and quotes alone (even): "" \'\' \\\\', 'backslashes and quotes alone (odd): """ \'\'\' \\\\\\', 'backslashes and quotes sequences (even): \\"\\" \\\'\\\'', 'backslashes and quotes sequences (odd): \\"\\"\\" \\\'\\\'\\\''); foreach ($teststrings as $teststring) { $record = new stdClass(); $record->id = $i; $record->onechar = $teststring; $record->onetext = $teststring; $this->assertTrue($DB->import_record($tablename, $record)); $record = $DB->get_record($tablename, array('id' => $i)); $this->assertEquals($teststring, $record->onechar); $this->assertEquals($teststring, $record->onetext); $i = $i + 3; } // Check LOBs in text/binary columns $clob = file_get_contents(__DIR__ . '/fixtures/clob.txt'); $record = new stdClass(); $record->id = 70; $record->onetext = $clob; $record->onebinary = ''; $this->assertTrue($DB->import_record($tablename, $record)); $rs = $DB->get_recordset($tablename, array('id' => 70)); $record = $rs->current(); $rs->close(); $this->assertEquals($clob, $record->onetext, 'Test CLOB insert (full contents output disabled)'); $blob = file_get_contents(__DIR__ . '/fixtures/randombinary'); $record = new stdClass(); $record->id = 71; $record->onetext = ''; $record->onebinary = $blob; $this->assertTrue($DB->import_record($tablename, $record)); $rs = $DB->get_recordset($tablename, array('id' => 71)); $record = $rs->current(); $rs->close(); $this->assertEquals($blob, $record->onebinary, 'Test BLOB insert (full contents output disabled)'); // And "small" LOBs too, just in case $newclob = substr($clob, 0, 500); $newblob = substr($blob, 0, 250); $record = new stdClass(); $record->id = 73; $record->onetext = $newclob; $record->onebinary = $newblob; $this->assertTrue($DB->import_record($tablename, $record)); $rs = $DB->get_recordset($tablename, array('id' => 73)); $record = $rs->current(); $rs->close(); $this->assertEquals($newclob, $record->onetext, 'Test "small" CLOB insert (full contents output disabled)'); $this->assertEquals($newblob, $record->onebinary, 'Test "small" BLOB insert (full contents output disabled)'); $this->assertEquals(false, $rs->key()); // Ensure recordset key() method to be working ok after closing } public function test_update_record_raw() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('course' => 1)); $DB->insert_record($tablename, array('course' => 3)); $record = $DB->get_record($tablename, array('course' => 1)); $record->course = 2; $this->assertTrue($DB->update_record_raw($tablename, $record)); $this->assertEquals(0, $DB->count_records($tablename, array('course' => 1))); $this->assertEquals(1, $DB->count_records($tablename, array('course' => 2))); $this->assertEquals(1, $DB->count_records($tablename, array('course' => 3))); $record = $DB->get_record($tablename, array('course' => 3)); $record->xxxxx = 2; try { $DB->update_record_raw($tablename, $record); $this->fail("Expecting an exception, none occurred"); } catch (Exception $e) { $this->assertTrue($e instanceof moodle_exception); } $record = $DB->get_record($tablename, array('course' => 3)); unset($record->id); try { $DB->update_record_raw($tablename, $record); $this->fail("Expecting an exception, none occurred"); } catch (Exception $e) { $this->assertTrue($e instanceof coding_exception); } } public function test_update_record() { // All the information in this test is fetched from DB by get_record() so we // have such method properly tested against nulls, empties and friends... $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); $table->add_field('oneint', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, 100); $table->add_field('onenum', XMLDB_TYPE_NUMBER, '10,2', null, null, null, 200); $table->add_field('onechar', XMLDB_TYPE_CHAR, '100', null, null, null, 'onestring'); $table->add_field('onetext', XMLDB_TYPE_TEXT, 'big', null, null, null); $table->add_field('onebinary', XMLDB_TYPE_BINARY, 'big', null, null, null); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('course' => 1)); $record = $DB->get_record($tablename, array('course' => 1)); $record->course = 2; $this->assertTrue($DB->update_record($tablename, $record)); $this->assertFalse($record = $DB->get_record($tablename, array('course' => 1))); $this->assertNotEmpty($record = $DB->get_record($tablename, array('course' => 2))); $this->assertEquals(100, $record->oneint); // Just check column defaults have been applied $this->assertEquals(200, $record->onenum); $this->assertEquals('onestring', $record->onechar); $this->assertNull($record->onetext); $this->assertNull($record->onebinary); // Check nulls are set properly for all types $record->oneint = null; $record->onenum = null; $record->onechar = null; $record->onetext = null; $record->onebinary = null; $DB->update_record($tablename, $record); $record = $DB->get_record($tablename, array('course' => 2)); $this->assertNull($record->oneint); $this->assertNull($record->onenum); $this->assertNull($record->onechar); $this->assertNull($record->onetext); $this->assertNull($record->onebinary); // Check zeros are set properly for all types $record->oneint = 0; $record->onenum = 0; $DB->update_record($tablename, $record); $record = $DB->get_record($tablename, array('course' => 2)); $this->assertEquals(0, $record->oneint); $this->assertEquals(0, $record->onenum); // Check booleans are set properly for all types $record->oneint = true; // trues $record->onenum = true; $record->onechar = true; $record->onetext = true; $DB->update_record($tablename, $record); $record = $DB->get_record($tablename, array('course' => 2)); $this->assertEquals(1, $record->oneint); $this->assertEquals(1, $record->onenum); $this->assertEquals(1, $record->onechar); $this->assertEquals(1, $record->onetext); $record->oneint = false; // falses $record->onenum = false; $record->onechar = false; $record->onetext = false; $DB->update_record($tablename, $record); $record = $DB->get_record($tablename, array('course' => 2)); $this->assertEquals(0, $record->oneint); $this->assertEquals(0, $record->onenum); $this->assertEquals(0, $record->onechar); $this->assertEquals(0, $record->onetext); // Check string data causes exception in numeric types $record->oneint = 'onestring'; $record->onenum = 0; try { $DB->update_record($tablename, $record); $this->fail("Expecting an exception, none occurred"); } catch (exception $e) { $this->assertTrue($e instanceof dml_exception); } $record->oneint = 0; $record->onenum = 'onestring'; try { $DB->update_record($tablename, $record); $this->fail("Expecting an exception, none occurred"); } catch (exception $e) { $this->assertTrue($e instanceof dml_exception); } // Check empty string data is stored as 0 in numeric datatypes $record->oneint = ''; // empty string $record->onenum = 0; $DB->update_record($tablename, $record); $record = $DB->get_record($tablename, array('course' => 2)); $this->assertTrue(is_numeric($record->oneint) && $record->oneint == 0); $record->oneint = 0; $record->onenum = ''; // empty string $DB->update_record($tablename, $record); $record = $DB->get_record($tablename, array('course' => 2)); $this->assertTrue(is_numeric($record->onenum) && $record->onenum == 0); // Check empty strings are set properly in string types $record->oneint = 0; $record->onenum = 0; $record->onechar = ''; $record->onetext = ''; $DB->update_record($tablename, $record); $record = $DB->get_record($tablename, array('course' => 2)); $this->assertTrue($record->onechar === ''); $this->assertTrue($record->onetext === ''); // Check operation ((210.10 + 39.92) - 150.02) against numeric types $record->oneint = ((210.10 + 39.92) - 150.02); $record->onenum = ((210.10 + 39.92) - 150.02); $DB->update_record($tablename, $record); $record = $DB->get_record($tablename, array('course' => 2)); $this->assertEquals(100, $record->oneint); $this->assertEquals(100, $record->onenum); // Check various quotes/backslashes combinations in string types $teststrings = array( 'backslashes and quotes alone (even): "" \'\' \\\\', 'backslashes and quotes alone (odd): """ \'\'\' \\\\\\', 'backslashes and quotes sequences (even): \\"\\" \\\'\\\'', 'backslashes and quotes sequences (odd): \\"\\"\\" \\\'\\\'\\\''); foreach ($teststrings as $teststring) { $record->onechar = $teststring; $record->onetext = $teststring; $DB->update_record($tablename, $record); $record = $DB->get_record($tablename, array('course' => 2)); $this->assertEquals($teststring, $record->onechar); $this->assertEquals($teststring, $record->onetext); } // Check LOBs in text/binary columns $clob = file_get_contents(__DIR__ . '/fixtures/clob.txt'); $blob = file_get_contents(__DIR__ . '/fixtures/randombinary'); $record->onetext = $clob; $record->onebinary = $blob; $DB->update_record($tablename, $record); $record = $DB->get_record($tablename, array('course' => 2)); $this->assertEquals($clob, $record->onetext, 'Test CLOB update (full contents output disabled)'); $this->assertEquals($blob, $record->onebinary, 'Test BLOB update (full contents output disabled)'); // And "small" LOBs too, just in case $newclob = substr($clob, 0, 500); $newblob = substr($blob, 0, 250); $record->onetext = $newclob; $record->onebinary = $newblob; $DB->update_record($tablename, $record); $record = $DB->get_record($tablename, array('course' => 2)); $this->assertEquals($newclob, $record->onetext, 'Test "small" CLOB update (full contents output disabled)'); $this->assertEquals($newblob, $record->onebinary, 'Test "small" BLOB update (full contents output disabled)'); // Test saving a float in a CHAR column, and reading it back. $id = $DB->insert_record($tablename, array('onechar' => 'X')); $DB->update_record($tablename, array('id' => $id, 'onechar' => 1.0)); $this->assertEquals(1.0, $DB->get_field($tablename, 'onechar', array('id' => $id))); $DB->update_record($tablename, array('id' => $id, 'onechar' => 1e20)); $this->assertEquals(1e20, $DB->get_field($tablename, 'onechar', array('id' => $id))); $DB->update_record($tablename, array('id' => $id, 'onechar' => 1e-4)); $this->assertEquals(1e-4, $DB->get_field($tablename, 'onechar', array('id' => $id))); $DB->update_record($tablename, array('id' => $id, 'onechar' => 1e-5)); $this->assertEquals(1e-5, $DB->get_field($tablename, 'onechar', array('id' => $id))); $DB->update_record($tablename, array('id' => $id, 'onechar' => 1e-300)); $this->assertEquals(1e-300, $DB->get_field($tablename, 'onechar', array('id' => $id))); $DB->update_record($tablename, array('id' => $id, 'onechar' => 1e300)); $this->assertEquals(1e300, $DB->get_field($tablename, 'onechar', array('id' => $id))); // Test saving a float in a TEXT column, and reading it back. $id = $DB->insert_record($tablename, array('onetext' => 'X')); $DB->update_record($tablename, array('id' => $id, 'onetext' => 1.0)); $this->assertEquals(1.0, $DB->get_field($tablename, 'onetext', array('id' => $id))); $DB->update_record($tablename, array('id' => $id, 'onetext' => 1e20)); $this->assertEquals(1e20, $DB->get_field($tablename, 'onetext', array('id' => $id))); $DB->update_record($tablename, array('id' => $id, 'onetext' => 1e-4)); $this->assertEquals(1e-4, $DB->get_field($tablename, 'onetext', array('id' => $id))); $DB->update_record($tablename, array('id' => $id, 'onetext' => 1e-5)); $this->assertEquals(1e-5, $DB->get_field($tablename, 'onetext', array('id' => $id))); $DB->update_record($tablename, array('id' => $id, 'onetext' => 1e-300)); $this->assertEquals(1e-300, $DB->get_field($tablename, 'onetext', array('id' => $id))); $DB->update_record($tablename, array('id' => $id, 'onetext' => 1e300)); $this->assertEquals(1e300, $DB->get_field($tablename, 'onetext', array('id' => $id))); } public function test_set_field() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); $table->add_field('onechar', XMLDB_TYPE_CHAR, '100', null, null, null); $table->add_field('onetext', XMLDB_TYPE_TEXT, 'big', null, null, null); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); // simple set_field $id1 = $DB->insert_record($tablename, array('course' => 1)); $id2 = $DB->insert_record($tablename, array('course' => 1)); $id3 = $DB->insert_record($tablename, array('course' => 3)); $this->assertTrue($DB->set_field($tablename, 'course', 2, array('id' => $id1))); $this->assertEquals(2, $DB->get_field($tablename, 'course', array('id' => $id1))); $this->assertEquals(1, $DB->get_field($tablename, 'course', array('id' => $id2))); $this->assertEquals(3, $DB->get_field($tablename, 'course', array('id' => $id3))); $DB->delete_records($tablename, array()); // multiple fields affected $id1 = $DB->insert_record($tablename, array('course' => 1)); $id2 = $DB->insert_record($tablename, array('course' => 1)); $id3 = $DB->insert_record($tablename, array('course' => 3)); $DB->set_field($tablename, 'course', '5', array('course' => 1)); $this->assertEquals(5, $DB->get_field($tablename, 'course', array('id' => $id1))); $this->assertEquals(5, $DB->get_field($tablename, 'course', array('id' => $id2))); $this->assertEquals(3, $DB->get_field($tablename, 'course', array('id' => $id3))); $DB->delete_records($tablename, array()); // no field affected $id1 = $DB->insert_record($tablename, array('course' => 1)); $id2 = $DB->insert_record($tablename, array('course' => 1)); $id3 = $DB->insert_record($tablename, array('course' => 3)); $DB->set_field($tablename, 'course', '5', array('course' => 0)); $this->assertEquals(1, $DB->get_field($tablename, 'course', array('id' => $id1))); $this->assertEquals(1, $DB->get_field($tablename, 'course', array('id' => $id2))); $this->assertEquals(3, $DB->get_field($tablename, 'course', array('id' => $id3))); $DB->delete_records($tablename, array()); // all fields - no condition $id1 = $DB->insert_record($tablename, array('course' => 1)); $id2 = $DB->insert_record($tablename, array('course' => 1)); $id3 = $DB->insert_record($tablename, array('course' => 3)); $DB->set_field($tablename, 'course', 5, array()); $this->assertEquals(5, $DB->get_field($tablename, 'course', array('id' => $id1))); $this->assertEquals(5, $DB->get_field($tablename, 'course', array('id' => $id2))); $this->assertEquals(5, $DB->get_field($tablename, 'course', array('id' => $id3))); // test for exception throwing on text conditions being compared. (MDL-24863, unwanted auto conversion of param to int) $conditions = array('onetext' => '1'); try { $DB->set_field($tablename, 'onechar', 'frog', $conditions); if (debugging()) { // only in debug mode - hopefully all devs test code in debug mode... $this->fail('An Exception is missing, expected due to equating of text fields'); } } catch (exception $e) { $this->assertTrue($e instanceof dml_exception); $this->assertEquals($e->errorcode, 'textconditionsnotallowed'); } // Test saving a float in a CHAR column, and reading it back. $id = $DB->insert_record($tablename, array('onechar' => 'X')); $DB->set_field($tablename, 'onechar', 1.0, array('id' => $id)); $this->assertEquals(1.0, $DB->get_field($tablename, 'onechar', array('id' => $id))); $DB->set_field($tablename, 'onechar', 1e20, array('id' => $id)); $this->assertEquals(1e20, $DB->get_field($tablename, 'onechar', array('id' => $id))); $DB->set_field($tablename, 'onechar', 1e-4, array('id' => $id)); $this->assertEquals(1e-4, $DB->get_field($tablename, 'onechar', array('id' => $id))); $DB->set_field($tablename, 'onechar', 1e-5, array('id' => $id)); $this->assertEquals(1e-5, $DB->get_field($tablename, 'onechar', array('id' => $id))); $DB->set_field($tablename, 'onechar', 1e-300, array('id' => $id)); $this->assertEquals(1e-300, $DB->get_field($tablename, 'onechar', array('id' => $id))); $DB->set_field($tablename, 'onechar', 1e300, array('id' => $id)); $this->assertEquals(1e300, $DB->get_field($tablename, 'onechar', array('id' => $id))); // Test saving a float in a TEXT column, and reading it back. $id = $DB->insert_record($tablename, array('onetext' => 'X')); $DB->set_field($tablename, 'onetext', 1.0, array('id' => $id)); $this->assertEquals(1.0, $DB->get_field($tablename, 'onetext', array('id' => $id))); $DB->set_field($tablename, 'onetext', 1e20, array('id' => $id)); $this->assertEquals(1e20, $DB->get_field($tablename, 'onetext', array('id' => $id))); $DB->set_field($tablename, 'onetext', 1e-4, array('id' => $id)); $this->assertEquals(1e-4, $DB->get_field($tablename, 'onetext', array('id' => $id))); $DB->set_field($tablename, 'onetext', 1e-5, array('id' => $id)); $this->assertEquals(1e-5, $DB->get_field($tablename, 'onetext', array('id' => $id))); $DB->set_field($tablename, 'onetext', 1e-300, array('id' => $id)); $this->assertEquals(1e-300, $DB->get_field($tablename, 'onetext', array('id' => $id))); $DB->set_field($tablename, 'onetext', 1e300, array('id' => $id)); $this->assertEquals(1e300, $DB->get_field($tablename, 'onetext', array('id' => $id))); // Note: All the nulls, booleans, empties, quoted and backslashes tests // go to set_field_select() because set_field() is just one wrapper over it } public function test_set_field_select() { // All the information in this test is fetched from DB by get_field() so we // have such method properly tested against nulls, empties and friends... $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); $table->add_field('oneint', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null); $table->add_field('onenum', XMLDB_TYPE_NUMBER, '10,2', null, null, null); $table->add_field('onechar', XMLDB_TYPE_CHAR, '100', null, null, null); $table->add_field('onetext', XMLDB_TYPE_TEXT, 'big', null, null, null); $table->add_field('onebinary', XMLDB_TYPE_BINARY, 'big', null, null, null); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('course' => 1)); $this->assertTrue($DB->set_field_select($tablename, 'course', 2, 'id = ?', array(1))); $this->assertEquals(2, $DB->get_field($tablename, 'course', array('id' => 1))); // Check nulls are set properly for all types $DB->set_field_select($tablename, 'oneint', null, 'id = ?', array(1)); // trues $DB->set_field_select($tablename, 'onenum', null, 'id = ?', array(1)); $DB->set_field_select($tablename, 'onechar', null, 'id = ?', array(1)); $DB->set_field_select($tablename, 'onetext', null, 'id = ?', array(1)); $DB->set_field_select($tablename, 'onebinary', null, 'id = ?', array(1)); $this->assertNull($DB->get_field($tablename, 'oneint', array('id' => 1))); $this->assertNull($DB->get_field($tablename, 'onenum', array('id' => 1))); $this->assertNull($DB->get_field($tablename, 'onechar', array('id' => 1))); $this->assertNull($DB->get_field($tablename, 'onetext', array('id' => 1))); $this->assertNull($DB->get_field($tablename, 'onebinary', array('id' => 1))); // Check zeros are set properly for all types $DB->set_field_select($tablename, 'oneint', 0, 'id = ?', array(1)); $DB->set_field_select($tablename, 'onenum', 0, 'id = ?', array(1)); $this->assertEquals(0, $DB->get_field($tablename, 'oneint', array('id' => 1))); $this->assertEquals(0, $DB->get_field($tablename, 'onenum', array('id' => 1))); // Check booleans are set properly for all types $DB->set_field_select($tablename, 'oneint', true, 'id = ?', array(1)); // trues $DB->set_field_select($tablename, 'onenum', true, 'id = ?', array(1)); $DB->set_field_select($tablename, 'onechar', true, 'id = ?', array(1)); $DB->set_field_select($tablename, 'onetext', true, 'id = ?', array(1)); $this->assertEquals(1, $DB->get_field($tablename, 'oneint', array('id' => 1))); $this->assertEquals(1, $DB->get_field($tablename, 'onenum', array('id' => 1))); $this->assertEquals(1, $DB->get_field($tablename, 'onechar', array('id' => 1))); $this->assertEquals(1, $DB->get_field($tablename, 'onetext', array('id' => 1))); $DB->set_field_select($tablename, 'oneint', false, 'id = ?', array(1)); // falses $DB->set_field_select($tablename, 'onenum', false, 'id = ?', array(1)); $DB->set_field_select($tablename, 'onechar', false, 'id = ?', array(1)); $DB->set_field_select($tablename, 'onetext', false, 'id = ?', array(1)); $this->assertEquals(0, $DB->get_field($tablename, 'oneint', array('id' => 1))); $this->assertEquals(0, $DB->get_field($tablename, 'onenum', array('id' => 1))); $this->assertEquals(0, $DB->get_field($tablename, 'onechar', array('id' => 1))); $this->assertEquals(0, $DB->get_field($tablename, 'onetext', array('id' => 1))); // Check string data causes exception in numeric types try { $DB->set_field_select($tablename, 'oneint', 'onestring', 'id = ?', array(1)); $this->fail("Expecting an exception, none occurred"); } catch (exception $e) { $this->assertTrue($e instanceof dml_exception); } try { $DB->set_field_select($tablename, 'onenum', 'onestring', 'id = ?', array(1)); $this->fail("Expecting an exception, none occurred"); } catch (exception $e) { $this->assertTrue($e instanceof dml_exception); } // Check empty string data is stored as 0 in numeric datatypes $DB->set_field_select($tablename, 'oneint', '', 'id = ?', array(1)); $field = $DB->get_field($tablename, 'oneint', array('id' => 1)); $this->assertTrue(is_numeric($field) && $field == 0); $DB->set_field_select($tablename, 'onenum', '', 'id = ?', array(1)); $field = $DB->get_field($tablename, 'onenum', array('id' => 1)); $this->assertTrue(is_numeric($field) && $field == 0); // Check empty strings are set properly in string types $DB->set_field_select($tablename, 'onechar', '', 'id = ?', array(1)); $DB->set_field_select($tablename, 'onetext', '', 'id = ?', array(1)); $this->assertTrue($DB->get_field($tablename, 'onechar', array('id' => 1)) === ''); $this->assertTrue($DB->get_field($tablename, 'onetext', array('id' => 1)) === ''); // Check operation ((210.10 + 39.92) - 150.02) against numeric types $DB->set_field_select($tablename, 'oneint', ((210.10 + 39.92) - 150.02), 'id = ?', array(1)); $DB->set_field_select($tablename, 'onenum', ((210.10 + 39.92) - 150.02), 'id = ?', array(1)); $this->assertEquals(100, $DB->get_field($tablename, 'oneint', array('id' => 1))); $this->assertEquals(100, $DB->get_field($tablename, 'onenum', array('id' => 1))); // Check various quotes/backslashes combinations in string types $teststrings = array( 'backslashes and quotes alone (even): "" \'\' \\\\', 'backslashes and quotes alone (odd): """ \'\'\' \\\\\\', 'backslashes and quotes sequences (even): \\"\\" \\\'\\\'', 'backslashes and quotes sequences (odd): \\"\\"\\" \\\'\\\'\\\''); foreach ($teststrings as $teststring) { $DB->set_field_select($tablename, 'onechar', $teststring, 'id = ?', array(1)); $DB->set_field_select($tablename, 'onetext', $teststring, 'id = ?', array(1)); $this->assertEquals($teststring, $DB->get_field($tablename, 'onechar', array('id' => 1))); $this->assertEquals($teststring, $DB->get_field($tablename, 'onetext', array('id' => 1))); } // Check LOBs in text/binary columns $clob = file_get_contents(__DIR__ . '/fixtures/clob.txt'); $blob = file_get_contents(__DIR__ . '/fixtures/randombinary'); $DB->set_field_select($tablename, 'onetext', $clob, 'id = ?', array(1)); $DB->set_field_select($tablename, 'onebinary', $blob, 'id = ?', array(1)); $this->assertEquals($clob, $DB->get_field($tablename, 'onetext', array('id' => 1)), 'Test CLOB set_field (full contents output disabled)'); $this->assertEquals($blob, $DB->get_field($tablename, 'onebinary', array('id' => 1)), 'Test BLOB set_field (full contents output disabled)'); // And "small" LOBs too, just in case $newclob = substr($clob, 0, 500); $newblob = substr($blob, 0, 250); $DB->set_field_select($tablename, 'onetext', $newclob, 'id = ?', array(1)); $DB->set_field_select($tablename, 'onebinary', $newblob, 'id = ?', array(1)); $this->assertEquals($newclob, $DB->get_field($tablename, 'onetext', array('id' => 1)), 'Test "small" CLOB set_field (full contents output disabled)'); $this->assertEquals($newblob, $DB->get_field($tablename, 'onebinary', array('id' => 1)), 'Test "small" BLOB set_field (full contents output disabled)'); // This is the failure from MDL-24863. This was giving an error on MSSQL, // which converts the '1' to an integer, which cannot then be compared with // onetext cast to a varchar. This should be fixed and working now. $newchar = 'frog'; // test for exception throwing on text conditions being compared. (MDL-24863, unwanted auto conversion of param to int) $params = array('onetext' => '1'); try { $DB->set_field_select($tablename, 'onechar', $newchar, $DB->sql_compare_text('onetext') . ' = ?', $params); $this->assertTrue(true, 'No exceptions thrown with numerical text param comparison for text field.'); } catch (dml_exception $e) { $this->assertFalse(true, 'We have an unexpected exception.'); throw $e; } } public function test_count_records() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); $table->add_field('onetext', XMLDB_TYPE_TEXT, 'big', null, null, null); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $this->assertSame(0, $DB->count_records($tablename)); $DB->insert_record($tablename, array('course' => 3)); $DB->insert_record($tablename, array('course' => 4)); $DB->insert_record($tablename, array('course' => 5)); $this->assertSame(3, $DB->count_records($tablename)); // test for exception throwing on text conditions being compared. (MDL-24863, unwanted auto conversion of param to int) $conditions = array('onetext' => '1'); try { $DB->count_records($tablename, $conditions); if (debugging()) { // only in debug mode - hopefully all devs test code in debug mode... $this->fail('An Exception is missing, expected due to equating of text fields'); } } catch (exception $e) { $this->assertTrue($e instanceof dml_exception); $this->assertEquals($e->errorcode, 'textconditionsnotallowed'); } } public function test_count_records_select() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $this->assertSame(0, $DB->count_records($tablename)); $DB->insert_record($tablename, array('course' => 3)); $DB->insert_record($tablename, array('course' => 4)); $DB->insert_record($tablename, array('course' => 5)); $this->assertSame(2, $DB->count_records_select($tablename, 'course > ?', array(3))); } public function test_count_records_sql() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); $table->add_field('onechar', XMLDB_TYPE_CHAR, '100', null, null, null); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $this->assertSame(0, $DB->count_records($tablename)); $DB->insert_record($tablename, array('course' => 3, 'onechar' => 'a')); $DB->insert_record($tablename, array('course' => 4, 'onechar' => 'b')); $DB->insert_record($tablename, array('course' => 5, 'onechar' => 'c')); $this->assertSame(2, $DB->count_records_sql("SELECT COUNT(*) FROM {{$tablename}} WHERE course > ?", array(3))); // test invalid use try { $DB->count_records_sql("SELECT onechar FROM {{$tablename}} WHERE course = ?", array(3)); $this->fail('Exception expected when non-number field used in count_records_sql'); } catch (exception $e) { $this->assertInstanceOf('coding_exception', $e); } try { $DB->count_records_sql("SELECT course FROM {{$tablename}} WHERE 1 = 2"); $this->fail('Exception expected when non-number field used in count_records_sql'); } catch (exception $e) { $this->assertInstanceOf('coding_exception', $e); } } public function test_record_exists() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); $table->add_field('onetext', XMLDB_TYPE_TEXT, 'big', null, null, null); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $this->assertEquals(0, $DB->count_records($tablename)); $this->assertFalse($DB->record_exists($tablename, array('course' => 3))); $DB->insert_record($tablename, array('course' => 3)); $this->assertTrue($DB->record_exists($tablename, array('course' => 3))); // test for exception throwing on text conditions being compared. (MDL-24863, unwanted auto conversion of param to int) $conditions = array('onetext' => '1'); try { $DB->record_exists($tablename, $conditions); if (debugging()) { // only in debug mode - hopefully all devs test code in debug mode... $this->fail('An Exception is missing, expected due to equating of text fields'); } } catch (exception $e) { $this->assertTrue($e instanceof dml_exception); $this->assertEquals($e->errorcode, 'textconditionsnotallowed'); } } public function test_record_exists_select() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $this->assertEquals(0, $DB->count_records($tablename)); $this->assertFalse($DB->record_exists_select($tablename, "course = ?", array(3))); $DB->insert_record($tablename, array('course' => 3)); $this->assertTrue($DB->record_exists_select($tablename, "course = ?", array(3))); } public function test_record_exists_sql() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $this->assertEquals(0, $DB->count_records($tablename)); $this->assertFalse($DB->record_exists_sql("SELECT * FROM {{$tablename}} WHERE course = ?", array(3))); $DB->insert_record($tablename, array('course' => 3)); $this->assertTrue($DB->record_exists_sql("SELECT * FROM {{$tablename}} WHERE course = ?", array(3))); } public function test_recordset_locks_delete() { $DB = $this->tdb; $dbman = $DB->get_manager(); //Setup $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('course' => 1)); $DB->insert_record($tablename, array('course' => 2)); $DB->insert_record($tablename, array('course' => 3)); $DB->insert_record($tablename, array('course' => 4)); $DB->insert_record($tablename, array('course' => 5)); $DB->insert_record($tablename, array('course' => 6)); // Test against db write locking while on an open recordset $rs = $DB->get_recordset($tablename, array(), null, 'course', 2, 2); // get courses = {3,4} foreach ($rs as $record) { $cid = $record->course; $DB->delete_records($tablename, array('course' => $cid)); $this->assertFalse($DB->record_exists($tablename, array('course' => $cid))); } $rs->close(); $this->assertEquals(4, $DB->count_records($tablename, array())); } public function test_recordset_locks_update() { $DB = $this->tdb; $dbman = $DB->get_manager(); //Setup $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('course' => 1)); $DB->insert_record($tablename, array('course' => 2)); $DB->insert_record($tablename, array('course' => 3)); $DB->insert_record($tablename, array('course' => 4)); $DB->insert_record($tablename, array('course' => 5)); $DB->insert_record($tablename, array('course' => 6)); // Test against db write locking while on an open recordset $rs = $DB->get_recordset($tablename, array(), null, 'course', 2, 2); // get courses = {3,4} foreach ($rs as $record) { $cid = $record->course; $DB->set_field($tablename, 'course', 10, array('course' => $cid)); $this->assertFalse($DB->record_exists($tablename, array('course' => $cid))); } $rs->close(); $this->assertEquals(2, $DB->count_records($tablename, array('course' => 10))); } public function test_delete_records() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); $table->add_field('onetext', XMLDB_TYPE_TEXT, 'big', null, null, null); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('course' => 3)); $DB->insert_record($tablename, array('course' => 2)); $DB->insert_record($tablename, array('course' => 2)); // Delete all records $this->assertTrue($DB->delete_records($tablename)); $this->assertEquals(0, $DB->count_records($tablename)); // Delete subset of records $DB->insert_record($tablename, array('course' => 3)); $DB->insert_record($tablename, array('course' => 2)); $DB->insert_record($tablename, array('course' => 2)); $this->assertTrue($DB->delete_records($tablename, array('course' => 2))); $this->assertEquals(1, $DB->count_records($tablename)); // delete all $this->assertTrue($DB->delete_records($tablename, array())); $this->assertEquals(0, $DB->count_records($tablename)); // test for exception throwing on text conditions being compared. (MDL-24863, unwanted auto conversion of param to int) $conditions = array('onetext'=>'1'); try { $DB->delete_records($tablename, $conditions); if (debugging()) { // only in debug mode - hopefully all devs test code in debug mode... $this->fail('An Exception is missing, expected due to equating of text fields'); } } catch (exception $e) { $this->assertTrue($e instanceof dml_exception); $this->assertEquals($e->errorcode, 'textconditionsnotallowed'); } // test for exception throwing on text conditions being compared. (MDL-24863, unwanted auto conversion of param to int) $conditions = array('onetext' => 1); try { $DB->delete_records($tablename, $conditions); if (debugging()) { // only in debug mode - hopefully all devs test code in debug mode... $this->fail('An Exception is missing, expected due to equating of text fields'); } } catch (exception $e) { $this->assertTrue($e instanceof dml_exception); $this->assertEquals($e->errorcode, 'textconditionsnotallowed'); } } public function test_delete_records_select() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('course' => 3)); $DB->insert_record($tablename, array('course' => 2)); $DB->insert_record($tablename, array('course' => 2)); $this->assertTrue($DB->delete_records_select($tablename, 'course = ?', array(2))); $this->assertEquals(1, $DB->count_records($tablename)); } public function test_delete_records_list() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('course' => 1)); $DB->insert_record($tablename, array('course' => 2)); $DB->insert_record($tablename, array('course' => 3)); $this->assertTrue($DB->delete_records_list($tablename, 'course', array(2, 3))); $this->assertEquals(1, $DB->count_records($tablename)); $this->assertTrue($DB->delete_records_list($tablename, 'course', array())); // Must delete 0 rows without conditions. MDL-17645 $this->assertEquals(1, $DB->count_records($tablename)); } public function test_object_params() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $o = new stdClass(); // objects without __toString - never worked try { $DB->fix_sql_params("SELECT {{$tablename}} WHERE course = ? ", array($o)); $this->fail('coding_exception expected'); } catch (Exception $e) { $this->assertTrue($e instanceof coding_exception); } // objects with __toString() forbidden everywhere since 2.3 $o = new dml_test_object_one(); try { $DB->fix_sql_params("SELECT {{$tablename}} WHERE course = ? ", array($o)); $this->fail('coding_exception expected'); } catch (Exception $e) { $this->assertTrue($e instanceof coding_exception); } try { $DB->execute("SELECT {{$tablename}} WHERE course = ? ", array($o)); $this->fail('coding_exception expected'); } catch (Exception $e) { $this->assertTrue($e instanceof coding_exception); } try { $DB->get_recordset_sql("SELECT {{$tablename}} WHERE course = ? ", array($o)); $this->fail('coding_exception expected'); } catch (Exception $e) { $this->assertTrue($e instanceof coding_exception); } try { $DB->get_records_sql("SELECT {{$tablename}} WHERE course = ? ", array($o)); $this->fail('coding_exception expected'); } catch (Exception $e) { $this->assertTrue($e instanceof coding_exception); } try { $record = new stdClass(); $record->course = $o; $DB->insert_record_raw($tablename, $record); $this->fail('coding_exception expected'); } catch (Exception $e) { $this->assertTrue($e instanceof coding_exception); } try { $record = new stdClass(); $record->course = $o; $DB->insert_record($tablename, $record); $this->fail('coding_exception expected'); } catch (Exception $e) { $this->assertTrue($e instanceof coding_exception); } try { $record = new stdClass(); $record->course = $o; $DB->import_record($tablename, $record); $this->fail('coding_exception expected'); } catch (Exception $e) { $this->assertTrue($e instanceof coding_exception); } try { $record = new stdClass(); $record->id = 1; $record->course = $o; $DB->update_record_raw($tablename, $record); $this->fail('coding_exception expected'); } catch (Exception $e) { $this->assertTrue($e instanceof coding_exception); } try { $record = new stdClass(); $record->id = 1; $record->course = $o; $DB->update_record($tablename, $record); $this->fail('coding_exception expected'); } catch (Exception $e) { $this->assertTrue($e instanceof coding_exception); } try { $DB->set_field_select($tablename, 'course', 1, "course = ? ", array($o)); $this->fail('coding_exception expected'); } catch (Exception $e) { $this->assertTrue($e instanceof coding_exception); } try { $DB->delete_records_select($tablename, "course = ? ", array($o)); $this->fail('coding_exception expected'); } catch (Exception $e) { $this->assertTrue($e instanceof coding_exception); } } function test_sql_null_from_clause() { $DB = $this->tdb; $sql = "SELECT 1 AS id ".$DB->sql_null_from_clause(); $this->assertEquals($DB->get_field_sql($sql), 1); } function test_sql_bitand() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('col1', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); $table->add_field('col2', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('col1' => 3, 'col2' => 10)); $sql = "SELECT ".$DB->sql_bitand(10, 3)." AS res ".$DB->sql_null_from_clause(); $this->assertEquals($DB->get_field_sql($sql), 2); $sql = "SELECT id, ".$DB->sql_bitand('col1', 'col2')." AS res FROM {{$tablename}}"; $result = $DB->get_records_sql($sql); $this->assertEquals(count($result), 1); $this->assertEquals(reset($result)->res, 2); $sql = "SELECT id, ".$DB->sql_bitand('col1', '?')." AS res FROM {{$tablename}}"; $result = $DB->get_records_sql($sql, array(10)); $this->assertEquals(count($result), 1); $this->assertEquals(reset($result)->res, 2); } function test_sql_bitnot() { $DB = $this->tdb; $not = $DB->sql_bitnot(2); $notlimited = $DB->sql_bitand($not, 7); // might be positive or negative number which can not fit into PHP INT! $sql = "SELECT $notlimited AS res ".$DB->sql_null_from_clause(); $this->assertEquals($DB->get_field_sql($sql), 5); } function test_sql_bitor() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('col1', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); $table->add_field('col2', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('col1' => 3, 'col2' => 10)); $sql = "SELECT ".$DB->sql_bitor(10, 3)." AS res ".$DB->sql_null_from_clause(); $this->assertEquals($DB->get_field_sql($sql), 11); $sql = "SELECT id, ".$DB->sql_bitor('col1', 'col2')." AS res FROM {{$tablename}}"; $result = $DB->get_records_sql($sql); $this->assertEquals(count($result), 1); $this->assertEquals(reset($result)->res, 11); $sql = "SELECT id, ".$DB->sql_bitor('col1', '?')." AS res FROM {{$tablename}}"; $result = $DB->get_records_sql($sql, array(10)); $this->assertEquals(count($result), 1); $this->assertEquals(reset($result)->res, 11); } function test_sql_bitxor() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('col1', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); $table->add_field('col2', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('col1' => 3, 'col2' => 10)); $sql = "SELECT ".$DB->sql_bitxor(10, 3)." AS res ".$DB->sql_null_from_clause(); $this->assertEquals($DB->get_field_sql($sql), 9); $sql = "SELECT id, ".$DB->sql_bitxor('col1', 'col2')." AS res FROM {{$tablename}}"; $result = $DB->get_records_sql($sql); $this->assertEquals(count($result), 1); $this->assertEquals(reset($result)->res, 9); $sql = "SELECT id, ".$DB->sql_bitxor('col1', '?')." AS res FROM {{$tablename}}"; $result = $DB->get_records_sql($sql, array(10)); $this->assertEquals(count($result), 1); $this->assertEquals(reset($result)->res, 9); } function test_sql_modulo() { $DB = $this->tdb; $sql = "SELECT ".$DB->sql_modulo(10, 7)." AS res ".$DB->sql_null_from_clause(); $this->assertEquals($DB->get_field_sql($sql), 3); } function test_sql_ceil() { $DB = $this->tdb; $sql = "SELECT ".$DB->sql_ceil(665.666)." AS res ".$DB->sql_null_from_clause(); $this->assertEquals($DB->get_field_sql($sql), 666); } function test_cast_char2int() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table1 = $this->get_test_table("1"); $tablename1 = $table1->getName(); $table1->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table1->add_field('name', XMLDB_TYPE_CHAR, '255', null, null, null, null); $table1->add_field('nametext', XMLDB_TYPE_TEXT, 'small', null, null, null, null); $table1->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table1); $DB->insert_record($tablename1, array('name'=>'0100', 'nametext'=>'0200')); $DB->insert_record($tablename1, array('name'=>'10', 'nametext'=>'20')); $table2 = $this->get_test_table("2"); $tablename2 = $table2->getName(); $table2->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table2->add_field('res', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); $table2->add_field('restext', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); $table2->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table2); $DB->insert_record($tablename2, array('res'=>100, 'restext'=>200)); // casting varchar field $sql = "SELECT * FROM {".$tablename1."} t1 JOIN {".$tablename2."} t2 ON ".$DB->sql_cast_char2int("t1.name")." = t2.res "; $records = $DB->get_records_sql($sql); $this->assertEquals(count($records), 1); // also test them in order clauses $sql = "SELECT * FROM {{$tablename1}} ORDER BY ".$DB->sql_cast_char2int('name'); $records = $DB->get_records_sql($sql); $this->assertEquals(count($records), 2); $this->assertEquals(reset($records)->name, '10'); $this->assertEquals(next($records)->name, '0100'); // casting text field $sql = "SELECT * FROM {".$tablename1."} t1 JOIN {".$tablename2."} t2 ON ".$DB->sql_cast_char2int("t1.nametext", true)." = t2.restext "; $records = $DB->get_records_sql($sql); $this->assertEquals(count($records), 1); // also test them in order clauses $sql = "SELECT * FROM {{$tablename1}} ORDER BY ".$DB->sql_cast_char2int('nametext', true); $records = $DB->get_records_sql($sql); $this->assertEquals(count($records), 2); $this->assertEquals(reset($records)->nametext, '20'); $this->assertEquals(next($records)->nametext, '0200'); } function test_cast_char2real() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('name', XMLDB_TYPE_CHAR, '255', null, null, null, null); $table->add_field('nametext', XMLDB_TYPE_TEXT, 'small', null, null, null, null); $table->add_field('res', XMLDB_TYPE_NUMBER, '12, 7', null, null, null, null); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('name'=>'10.10', 'nametext'=>'10.10', 'res'=>5.1)); $DB->insert_record($tablename, array('name'=>'91.10', 'nametext'=>'91.10', 'res'=>666)); $DB->insert_record($tablename, array('name'=>'011.10','nametext'=>'011.10','res'=>10.1)); // casting varchar field $sql = "SELECT * FROM {{$tablename}} WHERE ".$DB->sql_cast_char2real('name')." > res"; $records = $DB->get_records_sql($sql); $this->assertEquals(count($records), 2); // also test them in order clauses $sql = "SELECT * FROM {{$tablename}} ORDER BY ".$DB->sql_cast_char2real('name'); $records = $DB->get_records_sql($sql); $this->assertEquals(count($records), 3); $this->assertEquals(reset($records)->name, '10.10'); $this->assertEquals(next($records)->name, '011.10'); $this->assertEquals(next($records)->name, '91.10'); // casting text field $sql = "SELECT * FROM {{$tablename}} WHERE ".$DB->sql_cast_char2real('nametext', true)." > res"; $records = $DB->get_records_sql($sql); $this->assertEquals(count($records), 2); // also test them in order clauses $sql = "SELECT * FROM {{$tablename}} ORDER BY ".$DB->sql_cast_char2real('nametext', true); $records = $DB->get_records_sql($sql); $this->assertEquals(count($records), 3); $this->assertEquals(reset($records)->nametext, '10.10'); $this->assertEquals(next($records)->nametext, '011.10'); $this->assertEquals(next($records)->nametext, '91.10'); } public function test_sql_compare_text() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('name', XMLDB_TYPE_CHAR, '255', null, null, null, null); $table->add_field('description', XMLDB_TYPE_TEXT, 'big', null, null, null, null); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('name'=>'abcd', 'description'=>'abcd')); $DB->insert_record($tablename, array('name'=>'abcdef', 'description'=>'bbcdef')); $DB->insert_record($tablename, array('name'=>'aaaa', 'description'=>'aaaacccccccccccccccccc')); $DB->insert_record($tablename, array('name'=>'xxxx', 'description'=>'123456789a123456789b123456789c123456789d')); // Only some supported databases truncate TEXT fields for comparisons, currently MSSQL and Oracle. $dbtruncatestextfields = ($DB->get_dbfamily() == 'mssql' || $DB->get_dbfamily() == 'oracle'); if ($dbtruncatestextfields) { // Ensure truncation behaves as expected. $sql = "SELECT " . $DB->sql_compare_text('description') . " AS field FROM {{$tablename}} WHERE name = ?"; $description = $DB->get_field_sql($sql, array('xxxx')); // Should truncate to 32 chars (the default). $this->assertEquals('123456789a123456789b123456789c12', $description); $sql = "SELECT " . $DB->sql_compare_text('description', 35) . " AS field FROM {{$tablename}} WHERE name = ?"; $description = $DB->get_field_sql($sql, array('xxxx')); // Should truncate to the specified number of chars. $this->assertEquals('123456789a123456789b123456789c12345', $description); } // Ensure text field comparison is successful. $sql = "SELECT * FROM {{$tablename}} WHERE name = ".$DB->sql_compare_text('description'); $records = $DB->get_records_sql($sql); $this->assertCount(1, $records); $sql = "SELECT * FROM {{$tablename}} WHERE name = ".$DB->sql_compare_text('description', 4); $records = $DB->get_records_sql($sql); if ($dbtruncatestextfields) { // Should truncate description to 4 characters before comparing. $this->assertCount(2, $records); } else { // Should leave untruncated, so one less match. $this->assertCount(1, $records); } } function test_unique_index_collation_trouble() { // note: this is a work in progress, we should probably move this to ddl test $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('name', XMLDB_TYPE_CHAR, '255', null, null, null, null); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $table->add_index('name', XMLDB_INDEX_UNIQUE, array('name')); $dbman->create_table($table); $DB->insert_record($tablename, array('name'=>'aaa')); try { $DB->insert_record($tablename, array('name'=>'AAA')); } catch (Exception $e) { //TODO: ignore case insensitive uniqueness problems for now //$this->fail("Unique index is case sensitive - this may cause problems in some tables"); } try { $DB->insert_record($tablename, array('name'=>'aäa')); $DB->insert_record($tablename, array('name'=>'aáa')); $this->assertTrue(true); } catch (Exception $e) { $family = $DB->get_dbfamily(); if ($family === 'mysql' or $family === 'mssql') { $this->fail("Unique index is accent insensitive, this may cause problems for non-ascii languages. This is usually caused by accent insensitive default collation."); } else { // this should not happen, PostgreSQL and Oracle do not support accent insensitive uniqueness. $this->fail("Unique index is accent insensitive, this may cause problems for non-ascii languages."); } throw($e); } } function test_sql_binary_equal() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('name', XMLDB_TYPE_CHAR, '255', null, null, null, null); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('name'=>'aaa')); $DB->insert_record($tablename, array('name'=>'aáa')); $DB->insert_record($tablename, array('name'=>'aäa')); $DB->insert_record($tablename, array('name'=>'bbb')); $DB->insert_record($tablename, array('name'=>'BBB')); $records = $DB->get_records_sql("SELECT * FROM {{$tablename}} WHERE name = ?", array('bbb')); $this->assertEquals(count($records), 1, 'SQL operator "=" is expected to be case sensitive'); $records = $DB->get_records_sql("SELECT * FROM {{$tablename}} WHERE name = ?", array('aaa')); $this->assertEquals(count($records), 1, 'SQL operator "=" is expected to be accent sensitive'); } function test_sql_like() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('name', XMLDB_TYPE_CHAR, '255', null, null, null, null); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('name'=>'SuperDuperRecord')); $DB->insert_record($tablename, array('name'=>'Nodupor')); $DB->insert_record($tablename, array('name'=>'ouch')); $DB->insert_record($tablename, array('name'=>'ouc_')); $DB->insert_record($tablename, array('name'=>'ouc%')); $DB->insert_record($tablename, array('name'=>'aui')); $DB->insert_record($tablename, array('name'=>'aüi')); $DB->insert_record($tablename, array('name'=>'aÜi')); $sql = "SELECT * FROM {{$tablename}} WHERE ".$DB->sql_like('name', '?', false); $records = $DB->get_records_sql($sql, array("%dup_r%")); $this->assertEquals(count($records), 2); $sql = "SELECT * FROM {{$tablename}} WHERE ".$DB->sql_like('name', '?', true); $records = $DB->get_records_sql($sql, array("%dup%")); $this->assertEquals(count($records), 1); $sql = "SELECT * FROM {{$tablename}} WHERE ".$DB->sql_like('name', '?'); // defaults $records = $DB->get_records_sql($sql, array("%dup%")); $this->assertEquals(count($records), 1); $sql = "SELECT * FROM {{$tablename}} WHERE ".$DB->sql_like('name', '?', true); $records = $DB->get_records_sql($sql, array("ouc\\_")); $this->assertEquals(count($records), 1); $sql = "SELECT * FROM {{$tablename}} WHERE ".$DB->sql_like('name', '?', true, true, false, '|'); $records = $DB->get_records_sql($sql, array($DB->sql_like_escape("ouc%", '|'))); $this->assertEquals(count($records), 1); $sql = "SELECT * FROM {{$tablename}} WHERE ".$DB->sql_like('name', '?', true, true); $records = $DB->get_records_sql($sql, array('aui')); $this->assertEquals(count($records), 1); $sql = "SELECT * FROM {{$tablename}} WHERE ".$DB->sql_like('name', '?', true, true, true); // NOT LIKE $records = $DB->get_records_sql($sql, array("%o%")); $this->assertEquals(count($records), 3); $sql = "SELECT * FROM {{$tablename}} WHERE ".$DB->sql_like('name', '?', false, true, true); // NOT ILIKE $records = $DB->get_records_sql($sql, array("%D%")); $this->assertEquals(count($records), 6); // verify usual escaping characters work fine $sql = "SELECT * FROM {{$tablename}} WHERE ".$DB->sql_like('name', '?', true, true, false, '\\'); $records = $DB->get_records_sql($sql, array("ouc\\_")); $this->assertEquals(count($records), 1); $sql = "SELECT * FROM {{$tablename}} WHERE ".$DB->sql_like('name', '?', true, true, false, '|'); $records = $DB->get_records_sql($sql, array("ouc|%")); $this->assertEquals(count($records), 1); // TODO: we do not require accent insensitivness yet, just make sure it does not throw errors $sql = "SELECT * FROM {{$tablename}} WHERE ".$DB->sql_like('name', '?', true, false); $records = $DB->get_records_sql($sql, array('aui')); //$this->assertEquals(count($records), 2, 'Accent insensitive LIKE searches may not be supported in all databases, this is not a problem.'); $sql = "SELECT * FROM {{$tablename}} WHERE ".$DB->sql_like('name', '?', false, false); $records = $DB->get_records_sql($sql, array('aui')); //$this->assertEquals(count($records), 3, 'Accent insensitive LIKE searches may not be supported in all databases, this is not a problem.'); } function test_coalesce() { $DB = $this->tdb; // Testing not-null occurrences, return 1st $sql = "SELECT COALESCE('returnthis', 'orthis', 'orwhynotthis') AS test" . $DB->sql_null_from_clause(); $this->assertEquals('returnthis', $DB->get_field_sql($sql, array())); $sql = "SELECT COALESCE(:paramvalue, 'orthis', 'orwhynotthis') AS test" . $DB->sql_null_from_clause(); $this->assertEquals('returnthis', $DB->get_field_sql($sql, array('paramvalue' => 'returnthis'))); // Testing null occurrences, return 2nd $sql = "SELECT COALESCE(null, 'returnthis', 'orthis') AS test" . $DB->sql_null_from_clause(); $this->assertEquals('returnthis', $DB->get_field_sql($sql, array())); $sql = "SELECT COALESCE(:paramvalue, 'returnthis', 'orthis') AS test" . $DB->sql_null_from_clause(); $this->assertEquals('returnthis', $DB->get_field_sql($sql, array('paramvalue' => null))); $sql = "SELECT COALESCE(null, :paramvalue, 'orthis') AS test" . $DB->sql_null_from_clause(); $this->assertEquals('returnthis', $DB->get_field_sql($sql, array('paramvalue' => 'returnthis'))); // Testing null occurrences, return 3rd $sql = "SELECT COALESCE(null, null, 'returnthis') AS test" . $DB->sql_null_from_clause(); $this->assertEquals('returnthis', $DB->get_field_sql($sql, array())); $sql = "SELECT COALESCE(null, :paramvalue, 'returnthis') AS test" . $DB->sql_null_from_clause(); $this->assertEquals('returnthis', $DB->get_field_sql($sql, array('paramvalue' => null))); $sql = "SELECT COALESCE(null, null, :paramvalue) AS test" . $DB->sql_null_from_clause(); $this->assertEquals('returnthis', $DB->get_field_sql($sql, array('paramvalue' => 'returnthis'))); // Testing all null occurrences, return null // Note: under mssql, if all elements are nulls, at least one must be a "typed" null, hence // we cannot test this in a cross-db way easily, so next 2 tests are using // different queries depending of the DB family $customnull = $DB->get_dbfamily() == 'mssql' ? 'CAST(null AS varchar)' : 'null'; $sql = "SELECT COALESCE(null, null, " . $customnull . ") AS test" . $DB->sql_null_from_clause(); $this->assertNull($DB->get_field_sql($sql, array())); $sql = "SELECT COALESCE(null, :paramvalue, " . $customnull . ") AS test" . $DB->sql_null_from_clause(); $this->assertNull($DB->get_field_sql($sql, array('paramvalue' => null))); // Check there are not problems with whitespace strings $sql = "SELECT COALESCE(null, '', null) AS test" . $DB->sql_null_from_clause(); $this->assertEquals('', $DB->get_field_sql($sql, array())); $sql = "SELECT COALESCE(null, :paramvalue, null) AS test" . $DB->sql_null_from_clause(); $this->assertEquals('', $DB->get_field_sql($sql, array('paramvalue' => ''))); } function test_sql_concat() { $DB = $this->tdb; $dbman = $DB->get_manager(); // Testing all sort of values $sql = "SELECT ".$DB->sql_concat("?", "?", "?")." AS fullname ". $DB->sql_null_from_clause(); // string, some unicode chars $params = array('name', 'áéíóú', 'name3'); $this->assertEquals('nameáéíóúname3', $DB->get_field_sql($sql, $params)); // string, spaces and numbers $params = array('name', ' ', 12345); $this->assertEquals('name 12345', $DB->get_field_sql($sql, $params)); // float, empty and strings $params = array(123.45, '', 'test'); $this->assertEquals('123.45test', $DB->get_field_sql($sql, $params)); // only integers $params = array(12, 34, 56); $this->assertEquals('123456', $DB->get_field_sql($sql, $params)); // float, null and strings $params = array(123.45, null, 'test'); $this->assertNull($DB->get_field_sql($sql, $params)); // Concatenate NULL with anything result = NULL // Testing fieldnames + values and also integer fieldnames $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('description', XMLDB_TYPE_TEXT, 'big', null, null, null, null); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('description'=>'áéíóú')); $DB->insert_record($tablename, array('description'=>'dxxx')); $DB->insert_record($tablename, array('description'=>'bcde')); // fieldnames and values mixed $sql = 'SELECT id, ' . $DB->sql_concat('description', "'harcoded'", '?', '?') . ' AS result FROM {' . $tablename . '}'; $records = $DB->get_records_sql($sql, array(123.45, 'test')); $this->assertEquals(count($records), 3); $this->assertEquals($records[1]->result, 'áéíóúharcoded123.45test'); // integer fieldnames and values $sql = 'SELECT id, ' . $DB->sql_concat('id', "'harcoded'", '?', '?') . ' AS result FROM {' . $tablename . '}'; $records = $DB->get_records_sql($sql, array(123.45, 'test')); $this->assertEquals(count($records), 3); $this->assertEquals($records[1]->result, '1harcoded123.45test'); // all integer fieldnames $sql = 'SELECT id, ' . $DB->sql_concat('id', 'id', 'id') . ' AS result FROM {' . $tablename . '}'; $records = $DB->get_records_sql($sql, array()); $this->assertEquals(count($records), 3); $this->assertEquals($records[1]->result, '111'); } function test_concat_join() { $DB = $this->tdb; $sql = "SELECT ".$DB->sql_concat_join("' '", array("?", "?", "?"))." AS fullname ".$DB->sql_null_from_clause(); $params = array("name", "name2", "name3"); $result = $DB->get_field_sql($sql, $params); $this->assertEquals("name name2 name3", $result); } function test_sql_fullname() { $DB = $this->tdb; $sql = "SELECT ".$DB->sql_fullname(':first', ':last')." AS fullname ".$DB->sql_null_from_clause(); $params = array('first'=>'Firstname', 'last'=>'Surname'); $this->assertEquals("Firstname Surname", $DB->get_field_sql($sql, $params)); } function test_sql_order_by_text() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('description', XMLDB_TYPE_TEXT, 'big', null, null, null, null); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('description'=>'abcd')); $DB->insert_record($tablename, array('description'=>'dxxx')); $DB->insert_record($tablename, array('description'=>'bcde')); $sql = "SELECT * FROM {{$tablename}} ORDER BY ".$DB->sql_order_by_text('description'); $records = $DB->get_records_sql($sql); $first = array_shift($records); $this->assertEquals(1, $first->id); $second = array_shift($records); $this->assertEquals(3, $second->id); $last = array_shift($records); $this->assertEquals(2, $last->id); } function test_sql_substring() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('name', XMLDB_TYPE_CHAR, '255', null, null, null, null); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $string = 'abcdefghij'; $DB->insert_record($tablename, array('name'=>$string)); $sql = "SELECT id, ".$DB->sql_substr("name", 5)." AS name FROM {{$tablename}}"; $record = $DB->get_record_sql($sql); $this->assertEquals(substr($string, 5-1), $record->name); $sql = "SELECT id, ".$DB->sql_substr("name", 5, 2)." AS name FROM {{$tablename}}"; $record = $DB->get_record_sql($sql); $this->assertEquals(substr($string, 5-1, 2), $record->name); try { // silence php warning ;-) @$DB->sql_substr("name"); $this->fail("Expecting an exception, none occurred"); } catch (Exception $e) { $this->assertTrue($e instanceof coding_exception); } } function test_sql_length() { $DB = $this->tdb; $this->assertEquals($DB->get_field_sql( "SELECT ".$DB->sql_length("'aeiou'").$DB->sql_null_from_clause()), 5); $this->assertEquals($DB->get_field_sql( "SELECT ".$DB->sql_length("'áéíóú'").$DB->sql_null_from_clause()), 5); } function test_sql_position() { $DB = $this->tdb; $this->assertEquals($DB->get_field_sql( "SELECT ".$DB->sql_position("'ood'", "'Moodle'").$DB->sql_null_from_clause()), 2); $this->assertEquals($DB->get_field_sql( "SELECT ".$DB->sql_position("'Oracle'", "'Moodle'").$DB->sql_null_from_clause()), 0); } function test_sql_empty() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $this->assertSame('', $DB->sql_empty()); // Since 2.5 the hack is applied automatically to all bound params. $this->assertDebuggingCalled(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('name', XMLDB_TYPE_CHAR, '255', null, null, null, null); $table->add_field('namenotnull', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, 'default value'); $table->add_field('namenotnullnodeflt', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('name'=>'', 'namenotnull'=>'')); $DB->insert_record($tablename, array('name'=>null)); $DB->insert_record($tablename, array('name'=>'lalala')); $DB->insert_record($tablename, array('name'=>0)); $records = $DB->get_records_sql("SELECT * FROM {{$tablename}} WHERE name = ?", array('')); $this->assertEquals(count($records), 1); $record = reset($records); $this->assertEquals($record->name, ''); $records = $DB->get_records_sql("SELECT * FROM {{$tablename}} WHERE namenotnull = ?", array('')); $this->assertEquals(count($records), 1); $record = reset($records); $this->assertEquals($record->namenotnull, ''); $records = $DB->get_records_sql("SELECT * FROM {{$tablename}} WHERE namenotnullnodeflt = ?", array('')); $this->assertEquals(count($records), 4); $record = reset($records); $this->assertEquals($record->namenotnullnodeflt, ''); } function test_sql_isempty() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('name', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null); $table->add_field('namenull', XMLDB_TYPE_CHAR, '255', null, null, null, null); $table->add_field('description', XMLDB_TYPE_TEXT, 'big', null, XMLDB_NOTNULL, null, null); $table->add_field('descriptionnull', XMLDB_TYPE_TEXT, 'big', null, null, null, null); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('name'=>'', 'namenull'=>'', 'description'=>'', 'descriptionnull'=>'')); $DB->insert_record($tablename, array('name'=>'??', 'namenull'=>null, 'description'=>'??', 'descriptionnull'=>null)); $DB->insert_record($tablename, array('name'=>'la', 'namenull'=>'la', 'description'=>'la', 'descriptionnull'=>'lalala')); $DB->insert_record($tablename, array('name'=>0, 'namenull'=>0, 'description'=>0, 'descriptionnull'=>0)); $records = $DB->get_records_sql("SELECT * FROM {{$tablename}} WHERE ".$DB->sql_isempty($tablename, 'name', false, false)); $this->assertEquals(count($records), 1); $record = reset($records); $this->assertEquals($record->name, ''); $records = $DB->get_records_sql("SELECT * FROM {{$tablename}} WHERE ".$DB->sql_isempty($tablename, 'namenull', true, false)); $this->assertEquals(count($records), 1); $record = reset($records); $this->assertEquals($record->namenull, ''); $records = $DB->get_records_sql("SELECT * FROM {{$tablename}} WHERE ".$DB->sql_isempty($tablename, 'description', false, true)); $this->assertEquals(count($records), 1); $record = reset($records); $this->assertEquals($record->description, ''); $records = $DB->get_records_sql("SELECT * FROM {{$tablename}} WHERE ".$DB->sql_isempty($tablename, 'descriptionnull', true, true)); $this->assertEquals(count($records), 1); $record = reset($records); $this->assertEquals($record->descriptionnull, ''); } function test_sql_isnotempty() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('name', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null); $table->add_field('namenull', XMLDB_TYPE_CHAR, '255', null, null, null, null); $table->add_field('description', XMLDB_TYPE_TEXT, 'big', null, XMLDB_NOTNULL, null, null); $table->add_field('descriptionnull', XMLDB_TYPE_TEXT, 'big', null, null, null, null); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('name'=>'', 'namenull'=>'', 'description'=>'', 'descriptionnull'=>'')); $DB->insert_record($tablename, array('name'=>'??', 'namenull'=>null, 'description'=>'??', 'descriptionnull'=>null)); $DB->insert_record($tablename, array('name'=>'la', 'namenull'=>'la', 'description'=>'la', 'descriptionnull'=>'lalala')); $DB->insert_record($tablename, array('name'=>0, 'namenull'=>0, 'description'=>0, 'descriptionnull'=>0)); $records = $DB->get_records_sql("SELECT * FROM {{$tablename}} WHERE ".$DB->sql_isnotempty($tablename, 'name', false, false)); $this->assertEquals(count($records), 3); $record = reset($records); $this->assertEquals($record->name, '??'); $records = $DB->get_records_sql("SELECT * FROM {{$tablename}} WHERE ".$DB->sql_isnotempty($tablename, 'namenull', true, false)); $this->assertEquals(count($records), 2); // nulls aren't comparable (so they aren't "not empty"). SQL expected behaviour $record = reset($records); $this->assertEquals($record->namenull, 'la'); // so 'la' is the first non-empty 'namenull' record $records = $DB->get_records_sql("SELECT * FROM {{$tablename}} WHERE ".$DB->sql_isnotempty($tablename, 'description', false, true)); $this->assertEquals(count($records), 3); $record = reset($records); $this->assertEquals($record->description, '??'); $records = $DB->get_records_sql("SELECT * FROM {{$tablename}} WHERE ".$DB->sql_isnotempty($tablename, 'descriptionnull', true, true)); $this->assertEquals(count($records), 2); // nulls aren't comparable (so they aren't "not empty"). SQL expected behaviour $record = reset($records); $this->assertEquals($record->descriptionnull, 'lalala'); // so 'lalala' is the first non-empty 'descriptionnull' record } function test_sql_regex() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('name', XMLDB_TYPE_CHAR, '255', null, null, null, null); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('name'=>'lalala')); $DB->insert_record($tablename, array('name'=>'holaaa')); $DB->insert_record($tablename, array('name'=>'aouch')); $sql = "SELECT * FROM {{$tablename}} WHERE name ".$DB->sql_regex()." ?"; $params = array('a$'); if ($DB->sql_regex_supported()) { $records = $DB->get_records_sql($sql, $params); $this->assertEquals(count($records), 2); } else { $this->assertTrue(true, 'Regexp operations not supported. Test skipped'); } $sql = "SELECT * FROM {{$tablename}} WHERE name ".$DB->sql_regex(false)." ?"; $params = array('.a'); if ($DB->sql_regex_supported()) { $records = $DB->get_records_sql($sql, $params); $this->assertEquals(count($records), 1); } else { $this->assertTrue(true, 'Regexp operations not supported. Test skipped'); } } /** * Test some more complex SQL syntax which moodle uses and depends on to work * useful to determine if new database libraries can be supported. */ public function test_get_records_sql_complicated() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); $table->add_field('name', XMLDB_TYPE_CHAR, '255', null, null, null, null); $table->add_field('content', XMLDB_TYPE_TEXT, 'big', XMLDB_UNSIGNED, XMLDB_NOTNULL); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('course' => 3, 'content' => 'hello', 'name'=>'xyz')); $DB->insert_record($tablename, array('course' => 3, 'content' => 'world', 'name'=>'abc')); $DB->insert_record($tablename, array('course' => 5, 'content' => 'hello', 'name'=>'def')); $DB->insert_record($tablename, array('course' => 2, 'content' => 'universe', 'name'=>'abc')); // test grouping by expressions in the query. MDL-26819. Note that there are 4 ways: // - By column position (GROUP by 1) - Not supported by mssql & oracle // - By column name (GROUP by course) - Supported by all, but leading to wrong results // - By column alias (GROUP by casecol) - Not supported by mssql & oracle // - By complete expression (GROUP BY CASE ...) - 100% cross-db, this test checks it $sql = "SELECT (CASE WHEN course = 3 THEN 1 ELSE 0 END) AS casecol, COUNT(1) AS countrecs, MAX(name) AS maxname FROM {{$tablename}} GROUP BY CASE WHEN course = 3 THEN 1 ELSE 0 END ORDER BY casecol DESC"; $result = array( 1 => (object)array('casecol' => 1, 'countrecs' => 2, 'maxname' => 'xyz'), 0 => (object)array('casecol' => 0, 'countrecs' => 2, 'maxname' => 'def')); $records = $DB->get_records_sql($sql, null); $this->assertEquals($result, $records); // another grouping by CASE expression just to ensure it works ok for multiple WHEN $sql = "SELECT CASE name WHEN 'xyz' THEN 'last' WHEN 'def' THEN 'mid' WHEN 'abc' THEN 'first' END AS casecol, COUNT(1) AS countrecs, MAX(name) AS maxname FROM {{$tablename}} GROUP BY CASE name WHEN 'xyz' THEN 'last' WHEN 'def' THEN 'mid' WHEN 'abc' THEN 'first' END ORDER BY casecol DESC"; $result = array( 'mid' => (object)array('casecol' => 'mid', 'countrecs' => 1, 'maxname' => 'def'), 'last' => (object)array('casecol' => 'last', 'countrecs' => 1, 'maxname' => 'xyz'), 'first'=> (object)array('casecol' => 'first', 'countrecs' => 2, 'maxname' => 'abc')); $records = $DB->get_records_sql($sql, null); $this->assertEquals($result, $records); // Test CASE expressions in the ORDER BY clause - used by MDL-34657. $sql = "SELECT id, course, name FROM {{$tablename}} ORDER BY CASE WHEN (course = 5 OR name = 'xyz') THEN 0 ELSE 1 END, name, course"; // First, records matching the course = 5 OR name = 'xyz', then the rest. Each // group ordered by name and course. $result = array( 3 => (object)array('id' => 3, 'course' => 5, 'name' => 'def'), 1 => (object)array('id' => 1, 'course' => 3, 'name' => 'xyz'), 4 => (object)array('id' => 4, 'course' => 2, 'name' => 'abc'), 2 => (object)array('id' => 2, 'course' => 3, 'name' => 'abc')); $records = $DB->get_records_sql($sql, null); $this->assertEquals($result, $records); // Verify also array keys, order is important in this test. $this->assertEquals(array_keys($result), array_keys($records)); // test limits in queries with DISTINCT/ALL clauses and multiple whitespace. MDL-25268 $sql = "SELECT DISTINCT course FROM {{$tablename}} ORDER BY course"; // only limitfrom $records = $DB->get_records_sql($sql, null, 1); $this->assertEquals(2, count($records)); $this->assertEquals(3, reset($records)->course); $this->assertEquals(5, next($records)->course); // only limitnum $records = $DB->get_records_sql($sql, null, 0, 2); $this->assertEquals(2, count($records)); $this->assertEquals(2, reset($records)->course); $this->assertEquals(3, next($records)->course); // both limitfrom and limitnum $records = $DB->get_records_sql($sql, null, 2, 2); $this->assertEquals(1, count($records)); $this->assertEquals(5, reset($records)->course); // we have sql like this in moodle, this syntax breaks on older versions of sqlite for example.. $sql = "SELECT a.id AS id, a.course AS course FROM {{$tablename}} a JOIN (SELECT * FROM {{$tablename}}) b ON a.id = b.id WHERE a.course = ?"; $records = $DB->get_records_sql($sql, array(3)); $this->assertEquals(2, count($records)); $this->assertEquals(1, reset($records)->id); $this->assertEquals(2, next($records)->id); // do NOT try embedding sql_xxxx() helper functions in conditions array of count_records(), they don't break params/binding! $count = $DB->count_records_select($tablename, "course = :course AND ".$DB->sql_compare_text('content')." = :content", array('course' => 3, 'content' => 'hello')); $this->assertEquals(1, $count); // test int x string comparison $sql = "SELECT * FROM {{$tablename}} c WHERE name = ?"; $this->assertEquals(count($DB->get_records_sql($sql, array(10))), 0); $this->assertEquals(count($DB->get_records_sql($sql, array("10"))), 0); $DB->insert_record($tablename, array('course' => 7, 'content' => 'xx', 'name'=>'1')); $DB->insert_record($tablename, array('course' => 7, 'content' => 'yy', 'name'=>'2')); $this->assertEquals(count($DB->get_records_sql($sql, array(1))), 1); $this->assertEquals(count($DB->get_records_sql($sql, array("1"))), 1); $this->assertEquals(count($DB->get_records_sql($sql, array(10))), 0); $this->assertEquals(count($DB->get_records_sql($sql, array("10"))), 0); $DB->insert_record($tablename, array('course' => 7, 'content' => 'xx', 'name'=>'1abc')); $this->assertEquals(count($DB->get_records_sql($sql, array(1))), 1); $this->assertEquals(count($DB->get_records_sql($sql, array("1"))), 1); // Test get_in_or_equal() with a big number of elements. Note that ideally // we should be detecting and warning about any use over, say, 200 elements // and recommend to change code to use subqueries and/or chunks instead. $currentcount = $DB->count_records($tablename); $numelements = 10000; // Verify that we can handle 10000 elements (crazy!) $values = range(1, $numelements); list($insql, $inparams) = $DB->get_in_or_equal($values, SQL_PARAMS_QM); // With QM params. $sql = "SELECT * FROM {{$tablename}} WHERE id $insql"; $results = $DB->get_records_sql($sql, $inparams); $this->assertEquals($currentcount, count($results)); list($insql, $inparams) = $DB->get_in_or_equal($values, SQL_PARAMS_NAMED); // With NAMED params. $sql = "SELECT * FROM {{$tablename}} WHERE id $insql"; $results = $DB->get_records_sql($sql, $inparams); $this->assertEquals($currentcount, count($results)); } function test_onelevel_commit() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $transaction = $DB->start_delegated_transaction(); $data = (object)array('course'=>3); $this->assertEquals(0, $DB->count_records($tablename)); $DB->insert_record($tablename, $data); $this->assertEquals(1, $DB->count_records($tablename)); $transaction->allow_commit(); $this->assertEquals(1, $DB->count_records($tablename)); } function test_transaction_ignore_error_trouble() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $table->add_index('course', XMLDB_INDEX_UNIQUE, array('course')); $dbman->create_table($table); // Test error on SQL_QUERY_INSERT. $transaction = $DB->start_delegated_transaction(); $this->assertEquals(0, $DB->count_records($tablename)); $DB->insert_record($tablename, (object)array('course'=>1)); $this->assertEquals(1, $DB->count_records($tablename)); try { $DB->insert_record($tablename, (object)array('course'=>1)); } catch (Exception $e) { // This must be ignored and it must not roll back the whole transaction. } $DB->insert_record($tablename, (object)array('course'=>2)); $this->assertEquals(2, $DB->count_records($tablename)); $transaction->allow_commit(); $this->assertEquals(2, $DB->count_records($tablename)); $this->assertFalse($DB->is_transaction_started()); // Test error on SQL_QUERY_SELECT. $DB->delete_records($tablename); $transaction = $DB->start_delegated_transaction(); $this->assertEquals(0, $DB->count_records($tablename)); $DB->insert_record($tablename, (object)array('course'=>1)); $this->assertEquals(1, $DB->count_records($tablename)); try { $DB->get_records_sql('s e l e c t'); } catch (Exception $e) { // This must be ignored and it must not roll back the whole transaction. } $DB->insert_record($tablename, (object)array('course'=>2)); $this->assertEquals(2, $DB->count_records($tablename)); $transaction->allow_commit(); $this->assertEquals(2, $DB->count_records($tablename)); $this->assertFalse($DB->is_transaction_started()); // Test error on structure SQL_QUERY_UPDATE. $DB->delete_records($tablename); $transaction = $DB->start_delegated_transaction(); $this->assertEquals(0, $DB->count_records($tablename)); $DB->insert_record($tablename, (object)array('course'=>1)); $this->assertEquals(1, $DB->count_records($tablename)); try { $DB->execute('xxxx'); } catch (Exception $e) { // This must be ignored and it must not roll back the whole transaction. } $DB->insert_record($tablename, (object)array('course'=>2)); $this->assertEquals(2, $DB->count_records($tablename)); $transaction->allow_commit(); $this->assertEquals(2, $DB->count_records($tablename)); $this->assertFalse($DB->is_transaction_started()); // Test error on structure SQL_QUERY_STRUCTURE. $DB->delete_records($tablename); $transaction = $DB->start_delegated_transaction(); $this->assertEquals(0, $DB->count_records($tablename)); $DB->insert_record($tablename, (object)array('course'=>1)); $this->assertEquals(1, $DB->count_records($tablename)); try { $DB->change_database_structure('xxxx'); } catch (Exception $e) { // This must be ignored and it must not roll back the whole transaction. } $DB->insert_record($tablename, (object)array('course'=>2)); $this->assertEquals(2, $DB->count_records($tablename)); $transaction->allow_commit(); $this->assertEquals(2, $DB->count_records($tablename)); $this->assertFalse($DB->is_transaction_started()); // NOTE: SQL_QUERY_STRUCTURE is intentionally not tested here because it should never fail. } function test_onelevel_rollback() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); // this might in fact encourage ppl to migrate from myisam to innodb $transaction = $DB->start_delegated_transaction(); $data = (object)array('course'=>3); $this->assertEquals(0, $DB->count_records($tablename)); $DB->insert_record($tablename, $data); $this->assertEquals(1, $DB->count_records($tablename)); try { $transaction->rollback(new Exception('test')); $this->fail('transaction rollback must rethrow exception'); } catch (Exception $e) { } $this->assertEquals(0, $DB->count_records($tablename)); } function test_nested_transactions() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); // two level commit $this->assertFalse($DB->is_transaction_started()); $transaction1 = $DB->start_delegated_transaction(); $this->assertTrue($DB->is_transaction_started()); $data = (object)array('course'=>3); $DB->insert_record($tablename, $data); $transaction2 = $DB->start_delegated_transaction(); $data = (object)array('course'=>4); $DB->insert_record($tablename, $data); $transaction2->allow_commit(); $this->assertTrue($DB->is_transaction_started()); $transaction1->allow_commit(); $this->assertFalse($DB->is_transaction_started()); $this->assertEquals(2, $DB->count_records($tablename)); $DB->delete_records($tablename); // rollback from top level $transaction1 = $DB->start_delegated_transaction(); $data = (object)array('course'=>3); $DB->insert_record($tablename, $data); $transaction2 = $DB->start_delegated_transaction(); $data = (object)array('course'=>4); $DB->insert_record($tablename, $data); $transaction2->allow_commit(); try { $transaction1->rollback(new Exception('test')); $this->fail('transaction rollback must rethrow exception'); } catch (Exception $e) { $this->assertEquals(get_class($e), 'Exception'); } $this->assertEquals(0, $DB->count_records($tablename)); $DB->delete_records($tablename); // rollback from nested level $transaction1 = $DB->start_delegated_transaction(); $data = (object)array('course'=>3); $DB->insert_record($tablename, $data); $transaction2 = $DB->start_delegated_transaction(); $data = (object)array('course'=>4); $DB->insert_record($tablename, $data); try { $transaction2->rollback(new Exception('test')); $this->fail('transaction rollback must rethrow exception'); } catch (Exception $e) { $this->assertEquals(get_class($e), 'Exception'); } $this->assertEquals(2, $DB->count_records($tablename)); // not rolled back yet try { $transaction1->allow_commit(); } catch (Exception $e) { $this->assertEquals(get_class($e), 'dml_transaction_exception'); } $this->assertEquals(2, $DB->count_records($tablename)); // not rolled back yet // the forced rollback is done from the default_exception handler and similar places, // let's do it manually here $this->assertTrue($DB->is_transaction_started()); $DB->force_transaction_rollback(); $this->assertFalse($DB->is_transaction_started()); $this->assertEquals(0, $DB->count_records($tablename)); // finally rolled back $DB->delete_records($tablename); // Test interactions of recordset and transactions - this causes problems in SQL Server. $table2 = $this->get_test_table('2'); $tablename2 = $table2->getName(); $table2->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table2->add_field('course', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); $table2->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table2); $DB->insert_record($tablename, array('course'=>1)); $DB->insert_record($tablename, array('course'=>2)); $DB->insert_record($tablename, array('course'=>3)); $DB->insert_record($tablename2, array('course'=>5)); $DB->insert_record($tablename2, array('course'=>6)); $DB->insert_record($tablename2, array('course'=>7)); $DB->insert_record($tablename2, array('course'=>8)); $rs1 = $DB->get_recordset($tablename); $i = 0; foreach ($rs1 as $record1) { $i++; $rs2 = $DB->get_recordset($tablename2); $j = 0; foreach ($rs2 as $record2) { $t = $DB->start_delegated_transaction(); $DB->set_field($tablename, 'course', $record1->course+1, array('id'=>$record1->id)); $DB->set_field($tablename2, 'course', $record2->course+1, array('id'=>$record2->id)); $t->allow_commit(); $j++; } $rs2->close(); $this->assertEquals(4, $j); } $rs1->close(); $this->assertEquals(3, $i); // Test nested recordsets isolation without transaction. $DB->delete_records($tablename); $DB->insert_record($tablename, array('course'=>1)); $DB->insert_record($tablename, array('course'=>2)); $DB->insert_record($tablename, array('course'=>3)); $DB->delete_records($tablename2); $DB->insert_record($tablename2, array('course'=>5)); $DB->insert_record($tablename2, array('course'=>6)); $DB->insert_record($tablename2, array('course'=>7)); $DB->insert_record($tablename2, array('course'=>8)); $rs1 = $DB->get_recordset($tablename); $i = 0; foreach ($rs1 as $record1) { $i++; $rs2 = $DB->get_recordset($tablename2); $j = 0; foreach ($rs2 as $record2) { $DB->set_field($tablename, 'course', $record1->course+1, array('id'=>$record1->id)); $DB->set_field($tablename2, 'course', $record2->course+1, array('id'=>$record2->id)); $j++; } $rs2->close(); $this->assertEquals(4, $j); } $rs1->close(); $this->assertEquals(3, $i); } function test_transactions_forbidden() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->transactions_forbidden(); $transaction = $DB->start_delegated_transaction(); $data = (object)array('course'=>1); $DB->insert_record($tablename, $data); try { $DB->transactions_forbidden(); } catch (Exception $e) { $this->assertEquals(get_class($e), 'dml_transaction_exception'); } // the previous test does not force rollback $transaction->allow_commit(); $this->assertFalse($DB->is_transaction_started()); $this->assertEquals(1, $DB->count_records($tablename)); } function test_wrong_transactions() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); // wrong order of nested commits $transaction1 = $DB->start_delegated_transaction(); $data = (object)array('course'=>3); $DB->insert_record($tablename, $data); $transaction2 = $DB->start_delegated_transaction(); $data = (object)array('course'=>4); $DB->insert_record($tablename, $data); try { $transaction1->allow_commit(); $this->fail('wrong order of commits must throw exception'); } catch (Exception $e) { $this->assertEquals(get_class($e), 'dml_transaction_exception'); } try { $transaction2->allow_commit(); $this->fail('first wrong commit forces rollback'); } catch (Exception $e) { $this->assertEquals(get_class($e), 'dml_transaction_exception'); } // this is done in default exception handler usually $this->assertTrue($DB->is_transaction_started()); $this->assertEquals(2, $DB->count_records($tablename)); // not rolled back yet $DB->force_transaction_rollback(); $this->assertEquals(0, $DB->count_records($tablename)); $DB->delete_records($tablename); // wrong order of nested rollbacks $transaction1 = $DB->start_delegated_transaction(); $data = (object)array('course'=>3); $DB->insert_record($tablename, $data); $transaction2 = $DB->start_delegated_transaction(); $data = (object)array('course'=>4); $DB->insert_record($tablename, $data); try { // this first rollback should prevent all other rollbacks $transaction1->rollback(new Exception('test')); } catch (Exception $e) { $this->assertEquals(get_class($e), 'Exception'); } try { $transaction2->rollback(new Exception('test')); } catch (Exception $e) { $this->assertEquals(get_class($e), 'Exception'); } try { $transaction1->rollback(new Exception('test')); } catch (Exception $e) { // the rollback was used already once, no way to use it again $this->assertEquals(get_class($e), 'dml_transaction_exception'); } // this is done in default exception handler usually $this->assertTrue($DB->is_transaction_started()); $DB->force_transaction_rollback(); $DB->delete_records($tablename); // unknown transaction object $transaction1 = $DB->start_delegated_transaction(); $data = (object)array('course'=>3); $DB->insert_record($tablename, $data); $transaction2 = new moodle_transaction($DB); try { $transaction2->allow_commit(); $this->fail('foreign transaction must fail'); } catch (Exception $e) { $this->assertEquals(get_class($e), 'dml_transaction_exception'); } try { $transaction1->allow_commit(); $this->fail('first wrong commit forces rollback'); } catch (Exception $e) { $this->assertEquals(get_class($e), 'dml_transaction_exception'); } $DB->force_transaction_rollback(); $DB->delete_records($tablename); } function test_concurent_transactions() { // Notes about this test: // 1- MySQL needs to use one engine with transactions support (InnoDB). // 2- MSSQL needs to have enabled versioning for read committed // transactions (ALTER DATABASE xxx SET READ_COMMITTED_SNAPSHOT ON) $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $transaction = $DB->start_delegated_transaction(); $data = (object)array('course'=>1); $this->assertEquals(0, $DB->count_records($tablename)); $DB->insert_record($tablename, $data); $this->assertEquals(1, $DB->count_records($tablename)); //open second connection $cfg = $DB->export_dbconfig(); if (!isset($cfg->dboptions)) { $cfg->dboptions = array(); } $DB2 = moodle_database::get_driver_instance($cfg->dbtype, $cfg->dblibrary); $DB2->connect($cfg->dbhost, $cfg->dbuser, $cfg->dbpass, $cfg->dbname, $cfg->prefix, $cfg->dboptions); // second instance should not see pending inserts $this->assertEquals(0, $DB2->count_records($tablename)); $data = (object)array('course'=>2); $DB2->insert_record($tablename, $data); $this->assertEquals(1, $DB2->count_records($tablename)); // first should see the changes done from second $this->assertEquals(2, $DB->count_records($tablename)); // now commit and we should see it finally in second connections $transaction->allow_commit(); $this->assertEquals(2, $DB2->count_records($tablename)); // let's try delete all is also working on (this checks MDL-29198) // initially both connections see all the records in the table (2) $this->assertEquals(2, $DB->count_records($tablename)); $this->assertEquals(2, $DB2->count_records($tablename)); $transaction = $DB->start_delegated_transaction(); // delete all from within transaction $DB->delete_records($tablename); // transactional $DB, sees 0 records now $this->assertEquals(0, $DB->count_records($tablename)); // others ($DB2) get no changes yet $this->assertEquals(2, $DB2->count_records($tablename)); // now commit and we should see changes $transaction->allow_commit(); $this->assertEquals(0, $DB2->count_records($tablename)); $DB2->dispose(); } public function test_session_locks() { $DB = $this->tdb; $dbman = $DB->get_manager(); // Open second connection $cfg = $DB->export_dbconfig(); if (!isset($cfg->dboptions)) { $cfg->dboptions = array(); } $DB2 = moodle_database::get_driver_instance($cfg->dbtype, $cfg->dblibrary); $DB2->connect($cfg->dbhost, $cfg->dbuser, $cfg->dbpass, $cfg->dbname, $cfg->prefix, $cfg->dboptions); // Testing that acquiring a lock effectively locks // Get a session lock on connection1 $rowid = rand(100, 200); $timeout = 1; $DB->get_session_lock($rowid, $timeout); // Try to get the same session lock on connection2 try { $DB2->get_session_lock($rowid, $timeout); $DB2->release_session_lock($rowid); // Should not be executed, but here for safety $this->fail('An Exception is missing, expected due to session lock acquired.'); } catch (exception $e) { $this->assertTrue($e instanceof dml_sessionwait_exception); $DB->release_session_lock($rowid); // Release lock on connection1 } // Testing that releasing a lock effectively frees // Get a session lock on connection1 $rowid = rand(100, 200); $timeout = 1; $DB->get_session_lock($rowid, $timeout); // Release the lock on connection1 $DB->release_session_lock($rowid); // Get the just released lock on connection2 $DB2->get_session_lock($rowid, $timeout); // Release the lock on connection2 $DB2->release_session_lock($rowid); $DB2->dispose(); } public function test_bound_param_types() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('name', XMLDB_TYPE_CHAR, '255', null, null, null, null); $table->add_field('content', XMLDB_TYPE_TEXT, 'big', XMLDB_UNSIGNED, XMLDB_NOTNULL); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $this->assertNotEmpty($DB->insert_record($tablename, array('name' => '1', 'content'=>'xx'))); $this->assertNotEmpty($DB->insert_record($tablename, array('name' => 2, 'content'=>'yy'))); $this->assertNotEmpty($DB->insert_record($tablename, array('name' => 'somestring', 'content'=>'zz'))); $this->assertNotEmpty($DB->insert_record($tablename, array('name' => 'aa', 'content'=>'1'))); $this->assertNotEmpty($DB->insert_record($tablename, array('name' => 'bb', 'content'=>2))); $this->assertNotEmpty($DB->insert_record($tablename, array('name' => 'cc', 'content'=>'sometext'))); // Conditions in CHAR columns $this->assertTrue($DB->record_exists($tablename, array('name'=>1))); $this->assertTrue($DB->record_exists($tablename, array('name'=>'1'))); $this->assertFalse($DB->record_exists($tablename, array('name'=>111))); $this->assertNotEmpty($DB->get_record($tablename, array('name'=>1))); $this->assertNotEmpty($DB->get_record($tablename, array('name'=>'1'))); $this->assertEmpty($DB->get_record($tablename, array('name'=>111))); $sqlqm = "SELECT * FROM {{$tablename}} WHERE name = ?"; $this->assertNotEmpty($records = $DB->get_records_sql($sqlqm, array(1))); $this->assertEquals(1, count($records)); $this->assertNotEmpty($records = $DB->get_records_sql($sqlqm, array('1'))); $this->assertEquals(1, count($records)); $records = $DB->get_records_sql($sqlqm, array(222)); $this->assertEquals(0, count($records)); $sqlnamed = "SELECT * FROM {{$tablename}} WHERE name = :name"; $this->assertNotEmpty($records = $DB->get_records_sql($sqlnamed, array('name' => 2))); $this->assertEquals(1, count($records)); $this->assertNotEmpty($records = $DB->get_records_sql($sqlnamed, array('name' => '2'))); $this->assertEquals(1, count($records)); // Conditions in TEXT columns always must be performed with the sql_compare_text // helper function on both sides of the condition $sqlqm = "SELECT * FROM {{$tablename}} WHERE " . $DB->sql_compare_text('content') . " = " . $DB->sql_compare_text('?'); $this->assertNotEmpty($records = $DB->get_records_sql($sqlqm, array('1'))); $this->assertEquals(1, count($records)); $this->assertNotEmpty($records = $DB->get_records_sql($sqlqm, array(1))); $this->assertEquals(1, count($records)); $sqlnamed = "SELECT * FROM {{$tablename}} WHERE " . $DB->sql_compare_text('content') . " = " . $DB->sql_compare_text(':content'); $this->assertNotEmpty($records = $DB->get_records_sql($sqlnamed, array('content' => 2))); $this->assertEquals(1, count($records)); $this->assertNotEmpty($records = $DB->get_records_sql($sqlnamed, array('content' => '2'))); $this->assertEquals(1, count($records)); } public function test_bound_param_reserved() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('course' => '1')); // make sure reserved words do not cause fatal problems in query parameters $DB->execute("UPDATE {{$tablename}} SET course = 1 WHERE id = :select", array('select'=>1)); $DB->get_records_sql("SELECT * FROM {{$tablename}} WHERE course = :select", array('select'=>1)); $rs = $DB->get_recordset_sql("SELECT * FROM {{$tablename}} WHERE course = :select", array('select'=>1)); $rs->close(); $DB->get_fieldset_sql("SELECT id FROM {{$tablename}} WHERE course = :select", array('select'=>1)); $DB->set_field_select($tablename, 'course', '1', "id = :select", array('select'=>1)); $DB->delete_records_select($tablename, "id = :select", array('select'=>1)); // if we get here test passed ok $this->assertTrue(true); } public function test_limits_and_offsets() { $DB = $this->tdb; $dbman = $DB->get_manager(); if (false) $DB = new moodle_database (); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('name', XMLDB_TYPE_CHAR, '255', null, null, null, null); $table->add_field('content', XMLDB_TYPE_TEXT, 'big', XMLDB_UNSIGNED, XMLDB_NOTNULL); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $this->assertNotEmpty($DB->insert_record($tablename, array('name' => 'a', 'content'=>'one'))); $this->assertNotEmpty($DB->insert_record($tablename, array('name' => 'b', 'content'=>'two'))); $this->assertNotEmpty($DB->insert_record($tablename, array('name' => 'c', 'content'=>'three'))); $this->assertNotEmpty($DB->insert_record($tablename, array('name' => 'd', 'content'=>'four'))); $this->assertNotEmpty($DB->insert_record($tablename, array('name' => 'e', 'content'=>'five'))); $this->assertNotEmpty($DB->insert_record($tablename, array('name' => 'f', 'content'=>'six'))); $sqlqm = "SELECT * FROM {{$tablename}}"; $this->assertNotEmpty($records = $DB->get_records_sql($sqlqm, null, 4)); $this->assertEquals(2, count($records)); $this->assertEquals('e', reset($records)->name); $this->assertEquals('f', end($records)->name); $sqlqm = "SELECT * FROM {{$tablename}}"; $this->assertEmpty($records = $DB->get_records_sql($sqlqm, null, 8)); $sqlqm = "SELECT * FROM {{$tablename}}"; $this->assertNotEmpty($records = $DB->get_records_sql($sqlqm, null, 0, 4)); $this->assertEquals(4, count($records)); $this->assertEquals('a', reset($records)->name); $this->assertEquals('d', end($records)->name); $sqlqm = "SELECT * FROM {{$tablename}}"; $this->assertNotEmpty($records = $DB->get_records_sql($sqlqm, null, 0, 8)); $this->assertEquals(6, count($records)); $this->assertEquals('a', reset($records)->name); $this->assertEquals('f', end($records)->name); $sqlqm = "SELECT * FROM {{$tablename}}"; $this->assertNotEmpty($records = $DB->get_records_sql($sqlqm, null, 1, 4)); $this->assertEquals(4, count($records)); $this->assertEquals('b', reset($records)->name); $this->assertEquals('e', end($records)->name); $sqlqm = "SELECT * FROM {{$tablename}}"; $this->assertNotEmpty($records = $DB->get_records_sql($sqlqm, null, 4, 4)); $this->assertEquals(2, count($records)); $this->assertEquals('e', reset($records)->name); $this->assertEquals('f', end($records)->name); $sqlqm = "SELECT t.*, t.name AS test FROM {{$tablename}} t ORDER BY t.id ASC"; $this->assertNotEmpty($records = $DB->get_records_sql($sqlqm, null, 4, 4)); $this->assertEquals(2, count($records)); $this->assertEquals('e', reset($records)->name); $this->assertEquals('f', end($records)->name); $sqlqm = "SELECT DISTINCT t.name, t.name AS test FROM {{$tablename}} t ORDER BY t.name DESC"; $this->assertNotEmpty($records = $DB->get_records_sql($sqlqm, null, 4, 4)); $this->assertEquals(2, count($records)); $this->assertEquals('b', reset($records)->name); $this->assertEquals('a', end($records)->name); $sqlqm = "SELECT 1 FROM {{$tablename}} t WHERE t.name = 'a'"; $this->assertNotEmpty($records = $DB->get_records_sql($sqlqm, null, 0, 1)); $this->assertEquals(1, count($records)); $sqlqm = "SELECT 'constant' FROM {{$tablename}} t WHERE t.name = 'a'"; $this->assertNotEmpty($records = $DB->get_records_sql($sqlqm, null, 0, 8)); $this->assertEquals(1, count($records)); $this->assertNotEmpty($DB->insert_record($tablename, array('name' => 'a', 'content'=>'one'))); $this->assertNotEmpty($DB->insert_record($tablename, array('name' => 'b', 'content'=>'two'))); $this->assertNotEmpty($DB->insert_record($tablename, array('name' => 'c', 'content'=>'three'))); $sqlqm = "SELECT t.name, COUNT(DISTINCT t2.id) AS count, 'Test' AS teststring FROM {{$tablename}} t LEFT JOIN ( SELECT t.id, t.name FROM {{$tablename}} t ) t2 ON t2.name = t.name GROUP BY t.name ORDER BY t.name ASC"; $this->assertNotEmpty($records = $DB->get_records_sql($sqlqm)); $this->assertEquals(6, count($records)); // a,b,c,d,e,f $this->assertEquals(2, reset($records)->count); // a has 2 records now $this->assertEquals(1, end($records)->count); // f has 1 record still $this->assertNotEmpty($records = $DB->get_records_sql($sqlqm, null, 0, 2)); $this->assertEquals(2, count($records)); $this->assertEquals(2, reset($records)->count); $this->assertEquals(2, end($records)->count); } public function test_queries_counter() { $DB = $this->tdb; $dbman = $this->tdb->get_manager(); // Test database. $table = $this->get_test_table(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('fieldvalue', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $tablename = $table->getName(); // Initial counters values. $initreads = $DB->perf_get_reads(); $initwrites = $DB->perf_get_writes(); $previousqueriestime = $DB->perf_get_queries_time(); // Selects counts as reads. // The get_records_sql() method generates only 1 db query. $whatever = $DB->get_records_sql("SELECT * FROM {{$tablename}}"); $this->assertEquals($initreads + 1, $DB->perf_get_reads()); // The get_records() method generates 2 queries the first time is called // as it is fetching the table structure. $whatever = $DB->get_records($tablename); $this->assertEquals($initreads + 3, $DB->perf_get_reads()); $this->assertEquals($initwrites, $DB->perf_get_writes()); // The elapsed time is counted. $lastqueriestime = $DB->perf_get_queries_time(); $this->assertGreaterThanOrEqual($previousqueriestime, $lastqueriestime); $previousqueriestime = $lastqueriestime; // Only 1 now, it already fetched the table columns. $whatever = $DB->get_records($tablename); $this->assertEquals($initreads + 4, $DB->perf_get_reads()); // And only 1 more from now. $whatever = $DB->get_records($tablename); $this->assertEquals($initreads + 5, $DB->perf_get_reads()); // Inserts counts as writes. $rec1 = new stdClass(); $rec1->fieldvalue = 11; $rec1->id = $DB->insert_record($tablename, $rec1); $this->assertEquals($initwrites + 1, $DB->perf_get_writes()); $this->assertEquals($initreads + 5, $DB->perf_get_reads()); // The elapsed time is counted. $lastqueriestime = $DB->perf_get_queries_time(); $this->assertGreaterThanOrEqual($previousqueriestime, $lastqueriestime); $previousqueriestime = $lastqueriestime; $rec2 = new stdClass(); $rec2->fieldvalue = 22; $rec2->id = $DB->insert_record($tablename, $rec2); $this->assertEquals($initwrites + 2, $DB->perf_get_writes()); // Updates counts as writes. $rec1->fieldvalue = 111; $DB->update_record($tablename, $rec1); $this->assertEquals($initwrites + 3, $DB->perf_get_writes()); $this->assertEquals($initreads + 5, $DB->perf_get_reads()); // The elapsed time is counted. $lastqueriestime = $DB->perf_get_queries_time(); $this->assertGreaterThanOrEqual($previousqueriestime, $lastqueriestime); $previousqueriestime = $lastqueriestime; // Sum of them. $totaldbqueries = $DB->perf_get_reads() + $DB->perf_get_writes(); $this->assertEquals($totaldbqueries, $DB->perf_get_queries()); } } /** * This class is not a proper subclass of moodle_database. It is * intended to be used only in unit tests, in order to gain access to the * protected methods of moodle_database, and unit test them. */ class moodle_database_for_testing extends moodle_database { protected $prefix = 'mdl_'; public function public_fix_table_names($sql) { return $this->fix_table_names($sql); } public function driver_installed(){} public function get_dbfamily(){} protected function get_dbtype(){} protected function get_dblibrary(){} public function get_name(){} public function get_configuration_help(){} public function get_configuration_hints(){} public function connect($dbhost, $dbuser, $dbpass, $dbname, $prefix, array $dboptions=null){} public function get_server_info(){} protected function allowed_param_types(){} public function get_last_error(){} public function get_tables($usecache=true){} public function get_indexes($table){} public function get_columns($table, $usecache=true){} protected function normalise_value($column, $value){} public function set_debug($state){} public function get_debug(){} public function set_logging($state){} public function change_database_structure($sql){} public function execute($sql, array $params=null){} public function get_recordset_sql($sql, array $params=null, $limitfrom=0, $limitnum=0){} public function get_records_sql($sql, array $params=null, $limitfrom=0, $limitnum=0){} public function get_fieldset_sql($sql, array $params=null){} public function insert_record_raw($table, $params, $returnid=true, $bulk=false, $customsequence=false){} public function insert_record($table, $dataobject, $returnid=true, $bulk=false){} public function import_record($table, $dataobject){} public function update_record_raw($table, $params, $bulk=false){} public function update_record($table, $dataobject, $bulk=false){} public function set_field_select($table, $newfield, $newvalue, $select, array $params=null){} public function delete_records_select($table, $select, array $params=null){} public function sql_concat(){} public function sql_concat_join($separator="' '", $elements=array()){} public function sql_substr($expr, $start, $length=false){} public function begin_transaction() {} public function commit_transaction() {} public function rollback_transaction() {} } /** * Dumb test class with toString() returning 1. */ class dml_test_object_one { public function __toString() { return 1; } }
abhinay100/moodle_app
lib/dml/tests/dml_test.php
PHP
gpl-3.0
238,243
/** @odoo-module **/ import { Popover } from "./popover"; const { Component } = owl; const { useExternalListener, useState } = owl.hooks; const { xml } = owl.tags; class PopoverController extends Component { setup() { this.state = useState({ displayed: false }); this.targetObserver = new MutationObserver(this.onTargetMutate.bind(this)); useExternalListener(window, "click", this.onClickAway, { capture: true }); } mounted() { this.targetObserver.observe(this.target.parentElement, { childList: true }); } willUnmount() { this.targetObserver.disconnect(); } shouldUpdate() { return false; } get popoverProps() { return { target: this.target, position: this.props.position, popoverClass: this.props.popoverClass, }; } get target() { if (typeof this.props.target === "string") { return document.querySelector(this.props.target); } else { return this.props.target; } } onClickAway(ev) { if (this.target.contains(ev.target) || ev.target.closest(".o_popover")) { return; } if (this.props.closeOnClickAway) { this.props.close(); } } onTargetMutate() { const target = this.target; if (!target || !target.parentElement) { this.props.close(); } } } PopoverController.components = { Popover }; PopoverController.defaultProps = { alwaysDisplayed: false, closeOnClickAway: true, }; PopoverController.template = xml/*xml*/ ` <Popover t-props="popoverProps" t-on-popover-closed="props.close()"> <t t-component="props.Component" t-props="props.props" /> </Popover> `; export class PopoverContainer extends Component { setup() { this.props.bus.on("UPDATE", this, this.render); } } PopoverContainer.components = { PopoverController }; PopoverContainer.template = xml` <div class="o_popover_container"> <t t-foreach="Object.values(props.popovers)" t-as="popover" t-key="popover.id"> <PopoverController t-props="popover" /> </t> </div> `;
jeremiahyan/odoo
addons/web/static/src/core/popover/popover_container.js
JavaScript
gpl-3.0
2,208
package org.ovirt.engine.ui.userportal.widget.basic; import org.ovirt.engine.core.common.businessentities.storage.DiskImage; import org.ovirt.engine.ui.common.idhandler.HasElementId; import org.ovirt.engine.ui.common.utils.ElementIdUtils; import com.google.gwt.core.client.GWT; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.Widget; public class DiskImageWidget extends Composite implements HasElementId { interface WidgetUiBinder extends UiBinder<Widget, DiskImageWidget> { WidgetUiBinder uiBinder = GWT.create(WidgetUiBinder.class); } @UiField Label diskName; @UiField Label diskSize; public DiskImageWidget(DiskImage diskImage) { initWidget(WidgetUiBinder.uiBinder.createAndBindUi(this)); diskSize.setText(diskImage.getSizeInGigabytes() + "GB"); //$NON-NLS-1$ diskName.setText(diskImage.getDiskAlias() + ':'); //$NON-NLS-1$ } @Override public void setElementId(String elementId) { // Set disk name element ID diskName.getElement().setId( ElementIdUtils.createElementId(elementId, "diskName")); //$NON-NLS-1$ // Set disk size element ID diskSize.getElement().setId( ElementIdUtils.createElementId(elementId, "diskSize")); //$NON-NLS-1$ } }
jtux270/translate
ovirt/3.6_source/frontend/webadmin/modules/userportal-gwtp/src/main/java/org/ovirt/engine/ui/userportal/widget/basic/DiskImageWidget.java
Java
gpl-3.0
1,468
const shell = require("shelljs"); const _ = require("lodash"); const fs = require("fs"); /* Mochi Intermittents is a small script for running the full mochitest suite several times to look for intermittent failures. There are two commands: * run - runs the full suite N times * uniqErrors - scans the logs for uniq test errors and their count It is easy to pick up on trends by running `less logs` and looking for `TEST-START <test-name>` */ function run(count) { fs.writeFileSync("logs", ""); const headlessParam = headless ? '': `-- --setenv MOZ_HEADLESS=1` const cmd = `mochii --ci true --mc ./firefox --default-test-path devtools/client/debugger/new`; _.times(count).forEach(i => { console.log(`### RUN ${i}`); fs.appendFileSync("logs", `### RUN ${i}`); const out = shell.exec(cmd); fs.appendFileSync("logs", out.stdout); fs.appendFileSync("logs", out.stderr); }); } function uniqErrors() { const text = fs.readFileSync("logs", "utf8") const errors = text.split("\n") .filter(line => line.includes("TEST-START")) .map(line => line.match(/TEST-START (.*)/)[1]) const uniq_errors = _.uniq(errors) errorCounts = uniq_errors.map(error => ({ error, count: errors.filter(e => e == error).length })) console.log(errors.length) } (() => { // run(50); // uniqErrors(); })()
borian/debugger.html
bin/mochi-intermittents.js
JavaScript
mpl-2.0
1,343
<?php /********************************************************************************* * SugarCRM Community Edition is a customer relationship management program developed by * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by the * Free Software Foundation with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * 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 Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along with * this program; if not, see http://www.gnu.org/licenses or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road, * SW2-130, Cupertino, CA 95014, USA. or at email address [email protected]. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License version 3, * these Appropriate Legal Notices must retain the display of the "Powered by * SugarCRM" logo. If the display of the logo is not reasonably feasible for * technical reasons, the Appropriate Legal Notices must display the words * "Powered by SugarCRM". ********************************************************************************/ $searchdefs ['Meetings'] = array ( 'layout' => array ( 'basic_search' => array ( 'name' => array ( 'name' => 'name', 'default' => true, 'width' => '10%', ), 'current_user_only' => array ( 'name' => 'current_user_only', 'label' => 'LBL_CURRENT_USER_FILTER', 'type' => 'bool', 'default' => true, 'width' => '10%', ), array ('name' => 'open_only', 'label' => 'LBL_OPEN_ITEMS', 'type' => 'bool', 'default' => false, 'width' => '10%'), ), 'advanced_search' => array ( 'name' => array ( 'name' => 'name', 'default' => true, 'width' => '10%', ), 'parent_name' => array ( 'type' => 'parent', 'label' => 'LBL_LIST_RELATED_TO', 'width' => '10%', 'default' => true, 'name' => 'parent_name', ), 'current_user_only' => array ( 'name' => 'current_user_only', 'label' => 'LBL_CURRENT_USER_FILTER', 'type' => 'bool', 'default' => true, 'width' => '10%', ), 'status' => array ( 'name' => 'status', 'default' => true, 'width' => '10%', ), 'assigned_user_id' => array ( 'name' => 'assigned_user_id', 'type' => 'enum', 'label' => 'LBL_ASSIGNED_TO', 'function' => array ( 'name' => 'get_user_array', 'params' => array ( 0 => false, ), ), 'default' => true, 'width' => '10%', ), ), ), 'templateMeta' => array ( 'maxColumns' => '3', 'maxColumnsBasic' => '4', 'widths' => array ( 'label' => '10', 'field' => '30', ), ), ); ?>
shahrooz33ce/sugarcrm
modules/Meetings/metadata/searchdefs.php
PHP
agpl-3.0
3,855
<?php /** * The Project Task handles creating the base application * * * PHP 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @since CakePHP(tm) v 1.2 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ App::uses('AppShell', 'Console/Command'); App::uses('File', 'Utility'); App::uses('Folder', 'Utility'); App::uses('String', 'Utility'); App::uses('Security', 'Utility'); /** * Task class for creating new project apps and plugins * * @package Cake.Console.Command.Task */ class ProjectTask extends AppShell { /** * configs path (used in testing). * * @var string */ public $configPath = null; /** * Checks that given project path does not already exist, and * finds the app directory in it. Then it calls bake() with that information. * * @return mixed */ public function execute() { $project = null; if (isset($this->args[0])) { $project = $this->args[0]; } while (!$project) { $prompt = __d('cake_console', "What is the path to the project you want to bake?"); $project = $this->in($prompt, null, APP . 'myapp'); } if ($project && !Folder::isAbsolute($project) && isset($_SERVER['PWD'])) { $project = $_SERVER['PWD'] . DS . $project; } $response = false; while ($response == false && is_dir($project) === true && file_exists($project . 'Config' . 'core.php')) { $prompt = __d('cake_console', '<warning>A project already exists in this location:</warning> %s Overwrite?', $project); $response = $this->in($prompt, array('y', 'n'), 'n'); if (strtolower($response) === 'n') { $response = $project = false; } } $success = true; if ($this->bake($project)) { $path = Folder::slashTerm($project); if ($this->createHome($path)) { $this->out(__d('cake_console', ' * Welcome page created')); } else { $this->err(__d('cake_console', 'The Welcome page was <error>NOT</error> created')); $success = false; } if ($this->securitySalt($path) === true) { $this->out(__d('cake_console', ' * Random hash key created for \'Security.salt\'')); } else { $this->err(__d('cake_console', 'Unable to generate random hash for \'Security.salt\', you should change it in %s', APP . 'Config' . DS . 'core.php')); $success = false; } if ($this->securityCipherSeed($path) === true) { $this->out(__d('cake_console', ' * Random seed created for \'Security.cipherSeed\'')); } else { $this->err(__d('cake_console', 'Unable to generate random seed for \'Security.cipherSeed\', you should change it in %s', APP . 'Config' . DS . 'core.php')); $success = false; } if ($this->consolePath($path) === true) { $this->out(__d('cake_console', ' * app/Console/cake.php path set.')); } else { $this->err(__d('cake_console', 'Unable to set console path for app/Console.')); $success = false; } $hardCode = false; if ($this->cakeOnIncludePath()) { $this->out(__d('cake_console', '<info>CakePHP is on your `include_path`. CAKE_CORE_INCLUDE_PATH will be set, but commented out.</info>')); } else { $this->out(__d('cake_console', '<warning>CakePHP is not on your `include_path`, CAKE_CORE_INCLUDE_PATH will be hard coded.</warning>')); $this->out(__d('cake_console', 'You can fix this by adding CakePHP to your `include_path`.')); $hardCode = true; } $success = $this->corePath($path, $hardCode) === true; if ($success) { $this->out(__d('cake_console', ' * CAKE_CORE_INCLUDE_PATH set to %s in webroot/index.php', CAKE_CORE_INCLUDE_PATH)); $this->out(__d('cake_console', ' * CAKE_CORE_INCLUDE_PATH set to %s in webroot/test.php', CAKE_CORE_INCLUDE_PATH)); } else { $this->err(__d('cake_console', 'Unable to set CAKE_CORE_INCLUDE_PATH, you should change it in %s', $path . 'webroot' . DS .'index.php')); $success = false; } if ($success && $hardCode) { $this->out(__d('cake_console', ' * <warning>Remember to check these values after moving to production server</warning>')); } $Folder = new Folder($path); if (!$Folder->chmod($path . 'tmp', 0777)) { $this->err(__d('cake_console', 'Could not set permissions on %s', $path . DS .'tmp')); $this->out(__d('cake_console', 'chmod -R 0777 %s', $path . DS .'tmp')); $success = false; } if ($success) { $this->out(__d('cake_console', '<success>Project baked successfully!</success>')); } else { $this->out(__d('cake_console', 'Project baked but with <warning>some issues.</warning>.')); } return $path; } } /** * Checks PHP's include_path for CakePHP. * * @return boolean Indicates whether or not CakePHP exists on include_path */ public function cakeOnIncludePath() { $paths = explode(PATH_SEPARATOR, ini_get('include_path')); foreach ($paths as $path) { if (file_exists($path . DS . 'Cake' . DS . 'bootstrap.php')) { return true; } } return false; } /** * Looks for a skeleton template of a Cake application, * and if not found asks the user for a path. When there is a path * this method will make a deep copy of the skeleton to the project directory. * * @param string $path Project path * @param string $skel Path to copy from * @param string $skip array of directories to skip when copying * @return mixed */ public function bake($path, $skel = null, $skip = array('empty')) { if (!$skel && !empty($this->params['skel'])) { $skel = $this->params['skel']; } while (!$skel) { $skel = $this->in( __d('cake_console', "What is the path to the directory layout you wish to copy?"), null, CAKE . 'Console' . DS . 'Templates' . DS . 'skel' ); if (!$skel) { $this->err(__d('cake_console', 'The directory path you supplied was empty. Please try again.')); } else { while (is_dir($skel) === false) { $skel = $this->in( __d('cake_console', 'Directory path does not exist please choose another:'), null, CAKE . 'Console' . DS . 'Templates' . DS . 'skel' ); } } } $app = basename($path); $this->out(__d('cake_console', '<info>Skel Directory</info>: ') . $skel); $this->out(__d('cake_console', '<info>Will be copied to</info>: ') . $path); $this->hr(); $looksGood = $this->in(__d('cake_console', 'Look okay?'), array('y', 'n', 'q'), 'y'); switch (strtolower($looksGood)) { case 'y': $Folder = new Folder($skel); if (!empty($this->params['empty'])) { $skip = array(); } if ($Folder->copy(array('to' => $path, 'skip' => $skip))) { $this->hr(); $this->out(__d('cake_console', '<success>Created:</success> %s in %s', $app, $path)); $this->hr(); } else { $this->err(__d('cake_console', "<error>Could not create</error> '%s' properly.", $app)); return false; } foreach ($Folder->messages() as $message) { $this->out(String::wrap(' * ' . $message), 1, Shell::VERBOSE); } return true; case 'n': unset($this->args[0]); $this->execute(); return false; case 'q': $this->out(__d('cake_console', '<error>Bake Aborted.</error>')); return false; } } /** * Writes a file with a default home page to the project. * * @param string $dir Path to project * @return boolean Success */ public function createHome($dir) { $app = basename($dir); $path = $dir . 'View' . DS . 'Pages' . DS; $source = CAKE . 'Console' . DS . 'Templates' . DS .'default' . DS . 'views' . DS . 'home.ctp'; include $source; return $this->createFile($path . 'home.ctp', $output); } /** * Generates the correct path to the CakePHP libs that are generating the project * and points app/console/cake.php to the right place * * @param string $path Project path. * @return boolean success */ public function consolePath($path) { $File = new File($path . 'Console' . DS . 'cake.php'); $contents = $File->read(); if (preg_match('/(__CAKE_PATH__)/', $contents, $match)) { $root = strpos(CAKE_CORE_INCLUDE_PATH, '/') === 0 ? " \$ds . '" : "'"; $replacement = $root . str_replace(DS, "' . \$ds . '", trim(CAKE_CORE_INCLUDE_PATH, DS)) . "'"; $result = str_replace($match[0], $replacement, $contents); if ($File->write($result)) { return true; } return false; } return false; } /** * Generates and writes 'Security.salt' * * @param string $path Project path * @return boolean Success */ public function securitySalt($path) { $File = new File($path . 'Config' . DS . 'core.php'); $contents = $File->read(); if (preg_match('/([\s]*Configure::write\(\'Security.salt\',[\s\'A-z0-9]*\);)/', $contents, $match)) { $string = Security::generateAuthKey(); $result = str_replace($match[0], "\t" . 'Configure::write(\'Security.salt\', \'' . $string . '\');', $contents); if ($File->write($result)) { return true; } return false; } return false; } /** * Generates and writes 'Security.cipherSeed' * * @param string $path Project path * @return boolean Success */ public function securityCipherSeed($path) { $File = new File($path . 'Config' . DS . 'core.php'); $contents = $File->read(); if (preg_match('/([\s]*Configure::write\(\'Security.cipherSeed\',[\s\'A-z0-9]*\);)/', $contents, $match)) { App::uses('Security', 'Utility'); $string = substr(bin2hex(Security::generateAuthKey()), 0, 30); $result = str_replace($match[0], "\t" . 'Configure::write(\'Security.cipherSeed\', \'' . $string . '\');', $contents); if ($File->write($result)) { return true; } return false; } return false; } /** * Generates and writes CAKE_CORE_INCLUDE_PATH * * @param string $path Project path * @param boolean $hardCode Wether or not define calls should be hardcoded. * @return boolean Success */ public function corePath($path, $hardCode = true) { if (dirname($path) !== CAKE_CORE_INCLUDE_PATH) { $filename = $path . 'webroot' . DS . 'index.php'; if (!$this->_replaceCorePath($filename, $hardCode)) { return false; } $filename = $path . 'webroot' . DS . 'test.php'; if (!$this->_replaceCorePath($filename, $hardCode)) { return false; } return true; } } /** * Replaces the __CAKE_PATH__ placeholder in the template files. * * @param string $filename The filename to operate on. * @param boolean $hardCode Whether or not the define should be uncommented. * @return boolean Success */ protected function _replaceCorePath($filename, $hardCode) { $contents = file_get_contents($filename); $root = strpos(CAKE_CORE_INCLUDE_PATH, '/') === 0 ? " DS . '" : "'"; $corePath = $root . str_replace(DS, "' . DS . '", trim(CAKE_CORE_INCLUDE_PATH, DS)) . "'"; $result = str_replace('__CAKE_PATH__', $corePath, $contents, $count); if ($hardCode) { $result = str_replace('//define(\'CAKE_CORE', 'define(\'CAKE_CORE', $result); } if (!file_put_contents($filename, $result)) { return false; } if ($count == 0) { return false; } return true; } /** * Enables Configure::read('Routing.prefixes') in /app/Config/core.php * * @param string $name Name to use as admin routing * @return boolean Success */ public function cakeAdmin($name) { $path = (empty($this->configPath)) ? APP . 'Config' . DS : $this->configPath; $File = new File($path . 'core.php'); $contents = $File->read(); if (preg_match('%(\s*[/]*Configure::write\(\'Routing.prefixes\',[\s\'a-z,\)\(]*\);)%', $contents, $match)) { $result = str_replace($match[0], "\n" . 'Configure::write(\'Routing.prefixes\', array(\'' . $name . '\'));', $contents); if ($File->write($result)) { Configure::write('Routing.prefixes', array($name)); return true; } else { return false; } } else { return false; } } /** * Checks for Configure::read('Routing.prefixes') and forces user to input it if not enabled * * @return string Admin route to use */ public function getPrefix() { $admin = ''; $prefixes = Configure::read('Routing.prefixes'); if (!empty($prefixes)) { if (count($prefixes) == 1) { return $prefixes[0] . '_'; } if ($this->interactive) { $this->out(); $this->out(__d('cake_console', 'You have more than one routing prefix configured')); } $options = array(); foreach ($prefixes as $i => $prefix) { $options[] = $i + 1; if ($this->interactive) { $this->out($i + 1 . '. ' . $prefix); } } $selection = $this->in(__d('cake_console', 'Please choose a prefix to bake with.'), $options, 1); return $prefixes[$selection - 1] . '_'; } if ($this->interactive) { $this->hr(); $this->out(__d('cake_console', 'You need to enable Configure::write(\'Routing.prefixes\',array(\'admin\')) in /app/Config/core.php to use prefix routing.')); $this->out(__d('cake_console', 'What would you like the prefix route to be?')); $this->out(__d('cake_console', 'Example: www.example.com/admin/controller')); while ($admin == '') { $admin = $this->in(__d('cake_console', 'Enter a routing prefix:'), null, 'admin'); } if ($this->cakeAdmin($admin) !== true) { $this->out(__d('cake_console', '<error>Unable to write to</error> /app/Config/core.php.')); $this->out(__d('cake_console', 'You need to enable Configure::write(\'Routing.prefixes\',array(\'admin\')) in /app/Config/core.php to use prefix routing.')); $this->_stop(); } return $admin . '_'; } return ''; } /** * get the option parser. * * @return ConsoleOptionParser */ public function getOptionParser() { $parser = parent::getOptionParser(); return $parser->description( __d('cake_console', 'Generate a new CakePHP project skeleton.') )->addArgument('name', array( 'help' => __d('cake_console', 'Application directory to make, if it starts with "/" the path is absolute.') ))->addOption('empty', array( 'boolean' => true, 'help' => __d('cake_console', 'Create empty files in each of the directories. Good if you are using git') ))->addOption('skel', array( 'default' => current(App::core('Console')) . 'Templates' . DS . 'skel', 'help' => __d('cake_console', 'The directory layout to use for the new application skeleton. Defaults to cake/Console/Templates/skel of CakePHP used to create the project.') )); } }
wesley1001/HEC-87-Mobile-Website
lib/Cake/Console/Command/Task/ProjectTask.php
PHP
agpl-3.0
14,543
'use strict' describe('First mobile test', () => { it('should expect true', () => { expect(true) }) })
goldoraf/cozy-drive
test/targets/mobile/test/test.spec.js
JavaScript
agpl-3.0
112
<?php /** * Connection Manager tests * * PHP 5 * * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://book.cakephp.org/view/1196/Testing CakePHP(tm) Tests * @package Cake.Test.Case.Model * @since CakePHP(tm) v 1.2.0.5550 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ App::uses('ConnectionManager', 'Model'); /** * ConnectionManagerTest * * @package Cake.Test.Case.Model */ class ConnectionManagerTest extends CakeTestCase { /** * tearDown method * * @return void */ public function tearDown() { parent::tearDown(); CakePlugin::unload(); } /** * testEnumConnectionObjects method * * @return void */ public function testEnumConnectionObjects() { $sources = ConnectionManager::enumConnectionObjects(); $this->assertTrue(count($sources) >= 1); $connections = array('default', 'test', 'test'); $this->assertTrue(count(array_intersect(array_keys($sources), $connections)) >= 1); } /** * testGetDataSource method * * @return void */ public function testGetDataSource() { App::build(array( 'Model/Datasource' => array( CAKE . 'Test' . DS . 'test_app' . DS . 'Model' . DS . 'Datasource' . DS ) )); $name = 'test_get_datasource'; $config = array('datasource' => 'Test2Source'); $connection = ConnectionManager::create($name, $config); $connections = ConnectionManager::enumConnectionObjects(); $this->assertTrue((bool)(count(array_keys($connections) >= 1))); $source = ConnectionManager::getDataSource('test_get_datasource'); $this->assertTrue(is_object($source)); ConnectionManager::drop('test_get_datasource'); } /** * testGetDataSourceException() method * * @return void * @expectedException MissingDatasourceConfigException */ public function testGetDataSourceException() { ConnectionManager::getDataSource('non_existent_source'); } /** * testGetPluginDataSource method * * @return void */ public function testGetPluginDataSource() { App::build(array( 'plugins' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS) ), App::RESET); CakePlugin::load('TestPlugin'); $name = 'test_source'; $config = array('datasource' => 'TestPlugin.TestSource'); $connection = ConnectionManager::create($name, $config); $this->assertTrue(class_exists('TestSource')); $this->assertEquals($connection->configKeyName, $name); $this->assertEquals($connection->config, $config); ConnectionManager::drop($name); } /** * testGetPluginDataSourceAndPluginDriver method * * @return void */ public function testGetPluginDataSourceAndPluginDriver() { App::build(array( 'plugins' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS) ), App::RESET); CakePlugin::load('TestPlugin'); $name = 'test_plugin_source_and_driver'; $config = array('datasource' => 'TestPlugin.Database/TestDriver'); $connection = ConnectionManager::create($name, $config); $this->assertTrue(class_exists('TestSource')); $this->assertTrue(class_exists('TestDriver')); $this->assertEquals($connection->configKeyName, $name); $this->assertEquals($connection->config, $config); ConnectionManager::drop($name); } /** * testGetLocalDataSourceAndPluginDriver method * * @return void */ public function testGetLocalDataSourceAndPluginDriver() { App::build(array( 'plugins' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS) )); CakePlugin::load('TestPlugin'); $name = 'test_local_source_and_plugin_driver'; $config = array('datasource' => 'TestPlugin.Database/DboDummy'); $connection = ConnectionManager::create($name, $config); $this->assertTrue(class_exists('DboSource')); $this->assertTrue(class_exists('DboDummy')); $this->assertEquals($connection->configKeyName, $name); ConnectionManager::drop($name); } /** * testGetPluginDataSourceAndLocalDriver method * * @return void */ public function testGetPluginDataSourceAndLocalDriver() { App::build(array( 'plugins' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS), 'Model/Datasource/Database' => array( CAKE . 'Test' . DS . 'test_app' . DS . 'Model' . DS . 'Datasource' . DS . 'Database' . DS ) )); $name = 'test_plugin_source_and_local_driver'; $config = array('datasource' => 'Database/TestLocalDriver'); $connection = ConnectionManager::create($name, $config); $this->assertTrue(class_exists('TestSource')); $this->assertTrue(class_exists('TestLocalDriver')); $this->assertEquals($connection->configKeyName, $name); $this->assertEquals($connection->config, $config); ConnectionManager::drop($name); } /** * testSourceList method * * @return void */ public function testSourceList() { ConnectionManager::getDataSource('test'); $sources = ConnectionManager::sourceList(); $this->assertTrue(count($sources) >= 1); $this->assertTrue(in_array('test', array_keys($sources))); } /** * testGetSourceName method * * @return void */ public function testGetSourceName() { $connections = ConnectionManager::enumConnectionObjects(); $source = ConnectionManager::getDataSource('test'); $result = ConnectionManager::getSourceName($source); $this->assertEquals('test', $result); $source = new StdClass(); $result = ConnectionManager::getSourceName($source); $this->assertNull($result); } /** * testLoadDataSource method * * @return void */ public function testLoadDataSource() { $connections = array( array('classname' => 'Mysql', 'filename' => 'Mysql', 'package' => 'Database'), array('classname' => 'Postgres', 'filename' => 'Postgres', 'package' => 'Database'), array('classname' => 'Sqlite', 'filename' => 'Sqlite', 'package' => 'Database'), ); foreach ($connections as $connection) { $exists = class_exists($connection['classname']); $loaded = ConnectionManager::loadDataSource($connection); $this->assertEquals($loaded, !$exists, "Failed loading the {$connection['classname']} datasource"); } } /** * testLoadDataSourceException() method * * @return void * @expectedException MissingDatasourceException */ public function testLoadDataSourceException() { $connection = array('classname' => 'NonExistentDataSource', 'filename' => 'non_existent'); $loaded = ConnectionManager::loadDataSource($connection); } /** * testCreateDataSource method * * @return void */ public function testCreateDataSourceWithIntegrationTests() { $name = 'test_created_connection'; $connections = ConnectionManager::enumConnectionObjects(); $this->assertTrue((bool)(count(array_keys($connections) >= 1))); $source = ConnectionManager::getDataSource('test'); $this->assertTrue(is_object($source)); $config = $source->config; $connection = ConnectionManager::create($name, $config); $this->assertTrue(is_object($connection)); $this->assertEquals($name, $connection->configKeyName); $this->assertEquals($name, ConnectionManager::getSourceName($connection)); $source = ConnectionManager::create(null, array()); $this->assertEquals($source, null); $source = ConnectionManager::create('another_test', array()); $this->assertEquals($source, null); $config = array('classname' => 'DboMysql', 'filename' => 'dbo' . DS . 'dbo_mysql'); $source = ConnectionManager::create(null, $config); $this->assertEquals($source, null); } /** * testConnectionData method * * @return void */ public function testConnectionData() { App::build(array( 'plugins' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS), 'Model/Datasource' => array( CAKE . 'Test' . DS . 'test_app' . DS . 'Model' . DS . 'Datasource' . DS ) ), App::RESET); CakePlugin::loadAll(); $expected = array( 'datasource' => 'Test2Source' ); ConnectionManager::create('connection1', array('datasource' => 'Test2Source')); $connections = ConnectionManager::enumConnectionObjects(); $this->assertEquals($expected, $connections['connection1']); ConnectionManager::drop('connection1'); ConnectionManager::create('connection2', array('datasource' => 'Test2Source')); $connections = ConnectionManager::enumConnectionObjects(); $this->assertEquals($expected, $connections['connection2']); ConnectionManager::drop('connection2'); ConnectionManager::create('connection3', array('datasource' => 'TestPlugin.TestSource')); $connections = ConnectionManager::enumConnectionObjects(); $expected['datasource'] = 'TestPlugin.TestSource'; $this->assertEquals($expected, $connections['connection3']); ConnectionManager::drop('connection3'); ConnectionManager::create('connection4', array('datasource' => 'TestPlugin.TestSource')); $connections = ConnectionManager::enumConnectionObjects(); $this->assertEquals($expected, $connections['connection4']); ConnectionManager::drop('connection4'); ConnectionManager::create('connection5', array('datasource' => 'Test2OtherSource')); $connections = ConnectionManager::enumConnectionObjects(); $expected['datasource'] = 'Test2OtherSource'; $this->assertEquals($expected, $connections['connection5']); ConnectionManager::drop('connection5'); ConnectionManager::create('connection6', array('datasource' => 'Test2OtherSource')); $connections = ConnectionManager::enumConnectionObjects(); $this->assertEquals($expected, $connections['connection6']); ConnectionManager::drop('connection6'); ConnectionManager::create('connection7', array('datasource' => 'TestPlugin.TestOtherSource')); $connections = ConnectionManager::enumConnectionObjects(); $expected['datasource'] = 'TestPlugin.TestOtherSource'; $this->assertEquals($expected, $connections['connection7']); ConnectionManager::drop('connection7'); ConnectionManager::create('connection8', array('datasource' => 'TestPlugin.TestOtherSource')); $connections = ConnectionManager::enumConnectionObjects(); $this->assertEquals($expected, $connections['connection8']); ConnectionManager::drop('connection8'); } /** * Tests that a connection configuration can be deleted in runtime * * @return void */ public function testDrop() { App::build(array( 'Model/Datasource' => array( CAKE . 'Test' . DS . 'test_app' . DS . 'Model' . DS . 'Datasource' . DS ) )); ConnectionManager::create('droppable', array('datasource' => 'Test2Source')); $connections = ConnectionManager::enumConnectionObjects(); $this->assertEquals(array('datasource' => 'Test2Source'), $connections['droppable']); $this->assertTrue(ConnectionManager::drop('droppable')); $connections = ConnectionManager::enumConnectionObjects(); $this->assertFalse(isset($connections['droppable'])); } }
parkr/HEC-87-Database-Admin
lib/Cake/Test/Case/Model/ConnectionManagerTest.php
PHP
agpl-3.0
10,890
class CategoriesController < AdminController protect 'manage_environment_categories', :environment helper :categories def index @categories = environment.categories.where("parent_id is null AND type is null") @regions = environment.regions.where(:parent_id => nil) end def get_children children = Category.find(params[:id]).children render :partial => 'category_children', :locals => {:children => children} end ALLOWED_TYPES = CategoriesHelper::TYPES.map {|item| item[1] } # posts back def new type = (params[:type] || params[:parent_type] || 'Category') raise 'Type not allowed' unless ALLOWED_TYPES.include?(type) @category = type.constantize.new(params[:category]) @category.environment = environment if params[:parent_id] @category.parent = environment.categories.find(params[:parent_id]) end if request.post? begin @category.save! @saved = true redirect_to :action => 'index' rescue Exception => e render :action => 'new' end end end # posts back def edit begin @category = environment.categories.find(params[:id]) if request.post? @category.update!(params[:category]) @saved = true session[:notice] = _("Category %s saved." % @category.name).html_safe redirect_to :action => 'index' end rescue Exception => e session[:notice] = _('Could not save category.') render :action => 'edit' end end after_filter :manage_categories_menu_cache, :only => [:edit, :new] post_only :remove def remove environment.categories.find(params[:id]).destroy redirect_to :action => 'index' end protected def manage_categories_menu_cache if @saved && request.post? && @category.display_in_menu? expire_fragment(:controller => 'public', :action => 'categories_menu') end end end
AlessandroCaetano/noosfero
app/controllers/admin/categories_controller.rb
Ruby
agpl-3.0
1,914
<?php /** * @package plugins.integration */ interface IIntegrationProviderPlugin { /** * @return KalturaVersion */ public static function getRequiredIntegrationPluginVersion(); /** * Return class name that expand IntegrationProviderType enum * @return string */ public static function getIntegrationProviderClassName(); }
ivesbai/server
plugins/integration/IIntegrationProviderPlugin.php
PHP
agpl-3.0
340
package dr.inference.distribution; import dr.inference.model.AbstractModelLikelihood; import dr.inference.model.Model; import dr.inference.model.Parameter; import dr.inference.model.MatrixParameter; import dr.inference.model.Variable; import dr.math.Binomial; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * * * @author Gabriela Cybis */ public class HierarchicalGraphLikelihood extends AbstractModelLikelihood { public static final String HIERARCHICAL_GRAPH_LIKELIHOOD = "hierarchicalGraphLikelihood"; public HierarchicalGraphLikelihood(Parameter hierarchicalIndicator, MatrixParameter strataIndicatorMatrix, Parameter prob) { super(HIERARCHICAL_GRAPH_LIKELIHOOD); this.hierarchicalIndicator = hierarchicalIndicator; this.strataIndicatorMatrix = strataIndicatorMatrix; this.prob = prob; addVariable(hierarchicalIndicator); addVariable(strataIndicatorMatrix); addVariable(prob); } // ************************************************************** // Likelihood IMPLEMENTATION // ************************************************************** public Parameter getHierarchicalIndicator() { return this.hierarchicalIndicator; } public MatrixParameter getStrataMatrix() { return this.strataIndicatorMatrix; } public Parameter getProb() { return this.prob; } public Model getModel() { return this; } /** * Calculate the log likelihood of the current state. * * @return the log likelihood. */ public double getLogLikelihood() { double p = prob.getParameterValue(0); if (p <= 0 || p >= 1) return Double.NEGATIVE_INFINITY; double logP = Math.log(p); double log1MinusP = Math.log(1.0 - p); if ( hierarchicalIndicator.getDimension()!= strataIndicatorMatrix.getRowDimension()) return Double.NEGATIVE_INFINITY; double logL = 0.0; for (int j =0; j < strataIndicatorMatrix.getColumnDimension();j++){ int diff = 0; for (int i = 0; i < hierarchicalIndicator.getDimension(); i++) { diff += (int) Math.abs(Math.round(hierarchicalIndicator.getParameterValue(i)-strataIndicatorMatrix.getParameterValue(i,j))); } logL += geometricLogLikelihood( diff, logP, log1MinusP); /** double logL += binomialLogLikelihood(hierarchicalIndicator.getDimension(), diff, logP, log1MinusP); *binomialLogLikelihood(hierarchicalIndicator.getDimension(), diff, logP, log1MinusP); */ } return logL; } public void makeDirty() { } public void acceptState() { // DO NOTHING } public void restoreState() { // DO NOTHING } public void storeState() { // DO NOTHING } protected void handleModelChangedEvent(Model model, Object object, int index) { // DO NOTHING } protected final void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) { // DO NOTHING } /** * @return the bernoulli loglikelihood * when the log of the probability is logP. */ private double binomialLogLikelihood(int trials, int count, double logP, double log1MinusP) { return Math.log(Binomial.choose(trials, count)) + (logP * count) + (log1MinusP * (trials - count)); } /** * @return the geometric loglikelihood * when the log of the probability is logP. */ private double geometricLogLikelihood( int count, double logP, double log1MinusP) { return (log1MinusP ) + (logP * count); } // ************************************************************** // XMLElement IMPLEMENTATION // ************************************************************** public Element createElement(Document d) { throw new RuntimeException("Not implemented yet!"); } // Binomial binom = new Binomial(); Parameter hierarchicalIndicator; MatrixParameter strataIndicatorMatrix; Parameter prob; }
armanbilge/BEAST_sandbox
src/dr/inference/distribution/HierarchicalGraphLikelihood.java
Java
lgpl-2.1
4,287
// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at // the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights // reserved. See file COPYRIGHT for details. // // This file is part of the MFEM library. For more information and source code // availability see http://mfem.googlecode.com. // // MFEM is free software; you can redistribute it and/or modify it under the // terms of the GNU Lesser General Public License (as published by the Free // Software Foundation) version 2.1 dated February 1999. #ifndef MFEM_SOCKETSTREAM #define MFEM_SOCKETSTREAM #include "../config/config.hpp" #include <iostream> namespace mfem { class socketbuf : public std::streambuf { private: int socket_descriptor; static const int buflen = 1024; char ibuf[buflen], obuf[buflen]; public: socketbuf() { socket_descriptor = -1; } explicit socketbuf(int sd) { socket_descriptor = sd; setp(obuf, obuf + buflen); } socketbuf(const char hostname[], int port) { socket_descriptor = -1; open(hostname, port); } /** Attach a new socket descriptor to the socketbuf. Returns the old socket descriptor which is NOT closed. */ int attach(int sd); int detach() { return attach(-1); } int open(const char hostname[], int port); int close(); int getsocketdescriptor() { return socket_descriptor; } bool is_open() { return (socket_descriptor >= 0); } ~socketbuf() { close(); } protected: virtual int sync(); virtual int_type underflow(); virtual int_type overflow(int_type c = traits_type::eof()); virtual std::streamsize xsgetn(char_type *__s, std::streamsize __n); virtual std::streamsize xsputn(const char_type *__s, std::streamsize __n); }; class socketstream : public std::iostream { private: socketbuf __buf; public: socketstream() : std::iostream(&__buf) { } explicit socketstream(int s) : std::iostream(&__buf), __buf(s) { } socketstream(const char hostname[], int port) : std::iostream(&__buf) { open(hostname, port); } socketbuf *rdbuf() { return &__buf; } int open(const char hostname[], int port) { int err = __buf.open(hostname, port); if (err) setstate(std::ios::failbit); return err; } int close() { return __buf.close(); } bool is_open() { return __buf.is_open(); } virtual ~socketstream() { } }; class socketserver { private: int listen_socket; public: explicit socketserver(int port); bool good() { return (listen_socket >= 0); } int close(); int accept(socketstream &sockstr); ~socketserver() { close(); } }; } #endif
hhxia/mfem
general/socketstream.hpp
C++
lgpl-2.1
2,676
/* * Copyright (C) 2014 PHYTEC Messtechnik GmbH * 2016 Freie Universität Berlin * * This file is subject to the terms and conditions of the GNU Lesser * General Public License v2.1. See the file LICENSE in the top level * directory for more details. * */ /** * @ingroup drivers_mma8652 * @{ * * @file * @brief Register definition for the MMA8x5x accelerometer driver * * @author Johann Fischer <[email protected]> * @author Hauke Petersen * */ #ifndef MMA8X5X_REG_H #define MMA8X5X_REG_H #ifdef __cplusplus extern "C" { #endif /** * @brief Register addresses * @{ */ #define MMA8X5X_STATUS 0x00 /**< Data or FIFO Status */ #define MMA8X5X_OUT_X_MSB 0x01 /**< [7:0] are 8 MSBs of X data */ #define MMA8X5X_OUT_X_LSB 0x02 /**< [7:4] are 4 LSBs of X data */ #define MMA8X5X_OUT_Y_MSB 0x03 /**< [7:0] are 8 MSBs of Y data */ #define MMA8X5X_OUT_Y_LSB 0x04 /**< [7:4] are 4 LSBs of Y data */ #define MMA8X5X_OUT_Z_MSB 0x05 /**< [7:0] are 8 MSBs of Z data */ #define MMA8X5X_OUT_Z_LSB 0x06 /**< [7:4] are 8 LSBs of Z data */ #define MMA8X5X_F_SETUP 0x09 /**< FIFO setup */ #define MMA8X5X_TRIG_CFG 0x0A /**< Map of FIFO data capture events */ #define MMA8X5X_SYSMOD 0x0B /**< Current System mode */ #define MMA8X5X_INT_SOURCE 0x0C /**< Interrupt status */ #define MMA8X5X_WHO_AM_I 0x0D /**< Device ID */ #define MMA8X5X_XYZ_DATA_CFG 0x0E /**< Dynamic Range Settings */ #define MMA8X5X_HP_FILTER_CUTOFF 0x0F /**< High-Pass Filter Selection */ #define MMA8X5X_PL_STATUS 0x10 /**< Landscape/Portrait orientation status */ #define MMA8X5X_PL_CFG 0x11 /**< Landscape/Portrait configuration */ #define MMA8X5X_PL_COUNT 0x12 /**< Landscape/Portrait debounce counter */ #define MMA8X5X_PL_BF_ZCOMP 0x13 /**< Back/Front, Z-Lock Trip threshold */ #define MMA8X5X_P_L_THS_REG 0x14 /**< Portrait/Landscape Threshold and Hysteresis */ #define MMA8X5X_FF_MT_CFG 0x15 /**< Freefall/Motion functional block configuration */ #define MMA8X5X_FF_MT_SRC 0x16 /**< Freefall/Motion event source register */ #define MMA8X5X_FF_MT_THS 0x17 /**< Freefall/Motion threshold register */ #define MMA8X5X_FF_MT_COUNT 0x18 /**< Freefall/Motion debounce counter */ #define MMA8X5X_TRANSIENT_CFG 0x1D /**< Transient functional block configuration */ #define MMA8X5X_TRANSIENT_SRC 0x1E /**< Transient event status register */ #define MMA8X5X_TRANSIENT_THS 0x1F /**< Transient event threshold */ #define MMA8X5X_TRANSIENT_COUNT 0x20 /**< Transient debounce counter */ #define MMA8X5X_PULSE_CFG 0x21 /**< Pulse enable configuration */ #define MMA8X5X_PULSE_SRC 0x22 /**< Pulse detection source */ #define MMA8X5X_PULSE_THSX 0x23 /**< X pulse threshold */ #define MMA8X5X_PULSE_THSY 0x24 /**< Y pulse threshold */ #define MMA8X5X_PULSE_THSZ 0x25 /**< Z pulse threshold */ #define MMA8X5X_PULSE_TMLT 0x26 /**< Time limit for pulse */ #define MMA8X5X_PULSE_LTCY 0x27 /**< Latency time for 2nd pulse */ #define MMA8X5X_PULSE_WIND 0x28 /**< Window time for 2nd pulse */ #define MMA8X5X_ASLP_COUNT 0x29 /**< Counter setting for Auto-SLEEP */ #define MMA8X5X_CTRL_REG1 0x2A /**< Data rates and modes setting */ #define MMA8X5X_CTRL_REG2 0x2B /**< Sleep Enable, OS modes, RST, ST */ #define MMA8X5X_CTRL_REG3 0x2C /**< Wake from Sleep, IPOL, PP_OD */ #define MMA8X5X_CTRL_REG4 0x2D /**< Interrupt enable register */ #define MMA8X5X_CTRL_REG5 0x2E /**< Interrupt pin (INT1/INT2) map */ #define MMA8X5X_OFF_X 0x2F /**< X-axis offset adjust */ #define MMA8X5X_OFF_Y 0x30 /**< Y-axis offset adjust */ #define MMA8X5X_OFF_Z 0x31 /**< Z-axis offset adjust */ /** @} */ /** * @brief MMA8x5x register bitfields * @{ */ #define MMA8X5X_STATUS_XDR (1 << 0) #define MMA8X5X_STATUS_YDR (1 << 1) #define MMA8X5X_STATUS_ZDR (1 << 2) #define MMA8X5X_STATUS_ZYXDR (1 << 3) #define MMA8X5X_STATUS_XOW (1 << 4) #define MMA8X5X_STATUS_YOW (1 << 5) #define MMA8X5X_STATUS_ZOW (1 << 6) #define MMA8X5X_STATUS_ZYXOW (1 << 7) #define MMA8X5X_F_STATUS_F_CNT_MASK 0x3F #define MMA8X5X_F_STATUS_F_WMRK_FLAG (1 << 6) #define MMA8X5X_F_STATUS_F_OVF (1 << 7) #define MMA8X5X_F_SETUP_MODE_MASK 0xC0 #define MMA8X5X_F_SETUP_MODE_DISABLED 0 #define MMA8X5X_F_SETUP_MODE_CIRCULAR 1 #define MMA8X5X_F_SETUP_MODE_STOP 2 #define MMA8X5X_F_SETUP_MODE_TRIGGER 3 #define MMA8X5X_F_SETUP_F_WMRK_MASK 0x3F #define MMA8X5X_TRIG_CFG_FF_MT (1 << 2) #define MMA8X5X_TRIG_CFG_PULSE (1 << 3) #define MMA8X5X_TRIG_CFG_LNDPRT (1 << 4) #define MMA8X5X_TRIG_CFG_TRANS (1 << 5) #define MMA8X5X_SYSMOD_MASK 0x3 #define MMA8X5X_SYSMOD_STANDBY 0 #define MMA8X5X_SYSMOD_WAKE 1 #define MMA8X5X_SYSMOD_SLEEP 2 #define MMA8X5X_SYSMOD_FGT_MASK 0x7C #define MMA8X5X_SYSMOD_FGERR (1 << 7) #define MMA8X5X_INT_SOURCE_DRDY (1 << 0) #define MMA8X5X_INT_SOURCE_FF_MT (1 << 2) #define MMA8X5X_INT_SOURCE_PULSE (1 << 3) #define MMA8X5X_INT_SOURCE_LNDPRT (1 << 4) #define MMA8X5X_INT_SOURCE_TRANS (1 << 5) #define MMA8X5X_INT_SOURCE_FIFO (1 << 6) #define MMA8X5X_INT_SOURCE_ASLP (1 << 7) #define MMA8X5X_XYZ_DATA_CFG_FS_MASK 0x3 #define MMA8X5X_XYZ_DATA_CFG_HPF_OUT (1 << 4) #define MMA8X5X_HP_FILTER_SEL_MASK 0x03 #define MMA8X5X_HP_FILTER_LPF_EN (1 << 4) #define MMA8X5X_HP_FILTER_HPF_BYP (1 << 5) #define MMA8X5X_PL_STATUS_BAFRO (1 << 0) #define MMA8X5X_PL_STATUS_LAPO_MASK 0x6 #define MMA8X5X_PL_STATUS_LAPO_P_UP 0 #define MMA8X5X_PL_STATUS_LAPO_P_DOWN 1 #define MMA8X5X_PL_STATUS_LAPO_L_RIGHT 2 #define MMA8X5X_PL_STATUS_LAPO_L_LEFT 3 #define MMA8X5X_PL_STATUS_LO (1 << 6) #define MMA8X5X_PL_STATUS_NEWLP (1 << 7) #define MMA8X5X_PL_CFG_PL_EN (1 << 6) #define MMA8X5X_PL_CFG_DBCNTM (1 << 7) #define MMA8X5X_PL_BF_ZCOMP_ZLOCK_MASK 0x07 #define MMA8X5X_PL_BF_ZCOMP_BKFR_MASK 0xC0 #define MMA8X5X_P_L_HYS_MASK 0x07 #define MMA8X5X_P_L_THS_MASK 0xF8 #define MMA8X5X_FF_MT_CFG_XEFE (1 << 3) #define MMA8X5X_FF_MT_CFG_YEFE (1 << 4) #define MMA8X5X_FF_MT_CFG_ZEFE (1 << 5) #define MMA8X5X_FF_MT_CFG_OAE (1 << 6) #define MMA8X5X_FF_MT_CFG_ELE (1 << 7) #define MMA8X5X_FF_MT_SRC_XHP (1 << 0) #define MMA8X5X_FF_MT_SRC_XHE (1 << 1) #define MMA8X5X_FF_MT_SRC_YHP (1 << 2) #define MMA8X5X_FF_MT_SRC_YHE (1 << 3) #define MMA8X5X_FF_MT_SRC_ZHP (1 << 4) #define MMA8X5X_FF_MT_SRC_ZHE (1 << 5) #define MMA8X5X_FF_MT_SRC_EA (1 << 7) #define MMA8X5X_FF_MT_THS_MASK 0x7F #define MMA8X5X_FF_MT_THS_DBCNTM (1 << 7) #define MMA8X5X_TRANSIENT_CFG_HPF_BYP (1 << 0) #define MMA8X5X_TRANSIENT_CFG_XTEFE (1 << 1) #define MMA8X5X_TRANSIENT_CFG_YTEFE (1 << 2) #define MMA8X5X_TRANSIENT_CFG_ZTEFE (1 << 3) #define MMA8X5X_TRANSIENT_CFG_ELE (1 << 4) #define MMA8X5X_TRANSIENT_SRC_XTPOL (1 << 0) #define MMA8X5X_TRANSIENT_SRC_XTEVENT (1 << 1) #define MMA8X5X_TRANSIENT_SRC_YTPOL (1 << 2) #define MMA8X5X_TRANSIENT_SRC_YTEVENT (1 << 3) #define MMA8X5X_TRANSIENT_SRC_ZTPOL (1 << 4) #define MMA8X5X_TRANSIENT_SRC_ZTEVENT (1 << 5) #define MMA8X5X_TRANSIENT_SRC_EA (1 << 6) #define MMA8X5X_TRANSIENT_THS_MASK 0x7F #define MMA8X5X_TRANSIENT_THS_DBCNTM (1<< 7) #define MMA8X5X_PULSE_CFG_XSPEFE (1 << 0) #define MMA8X5X_PULSE_CFG_XDPEFE (1 << 1) #define MMA8X5X_PULSE_CFG_YSPEFE (1 << 2) #define MMA8X5X_PULSE_CFG_YDPEFE (1 << 3) #define MMA8X5X_PULSE_CFG_ZSPEFE (1 << 4) #define MMA8X5X_PULSE_CFG_ZDPEFE (1 << 5) #define MMA8X5X_PULSE_CFG_ELE (1 << 6) #define MMA8X5X_PULSE_CFG_DPA (1 << 7) #define MMA8X5X_PULSE_SRC_POLX (1 << 0) #define MMA8X5X_PULSE_SRC_POLY (1 << 1) #define MMA8X5X_PULSE_SRC_POLZ (1 << 2) #define MMA8X5X_PULSE_SRC_DPE (1 << 3) #define MMA8X5X_PULSE_SRC_AXX (1 << 4) #define MMA8X5X_PULSE_SRC_AXY (1 << 5) #define MMA8X5X_PULSE_SRC_AXZ (1 << 6) #define MMA8X5X_PULSE_SRC_EA (1 << 7) #define MMA8X5X_PULSE_THSX_MASK 0x7F #define MMA8X5X_PULSE_THSY_MASK 0x7F #define MMA8X5X_PULSE_THSZ_MASK 0x7F #define MMA8X5X_CTRL_REG1_ACTIVE (1 << 0) #define MMA8X5X_CTRL_REG1_F_READ (1 << 1) #define MMA8X5X_CTRL_REG1_DR_MASK 0x38 #define MMA8X5X_CTRL_REG1_DR_SHIFT 3 #define MMA8X5X_CTRL_REG1_DR(x) (((uint8_t)(((uint8_t)(x))<<MMA8X5X_CTRL_REG1_DR_SHIFT))\ &MMA8X5X_CTRL_REG1_DR_MASK) #define MMA8X5X_CTRL_REG1_ASR_MASK 0xC0 #define MMA8X5X_CTRL_REG1_ASR_50HZ 0 #define MMA8X5X_CTRL_REG1_ASR_12HZ5 1 #define MMA8X5X_CTRL_REG1_ASR_6HZ25 2 #define MMA8X5X_CTRL_REG1_ASR_1HZ56 3 #define MMA8X5X_CTRL_REG2_MODS_MASK 0x3 #define MMA8X5X_CTRL_REG2_MODS_NORMAL 0 #define MMA8X5X_CTRL_REG2_MODS_LNLP 1 #define MMA8X5X_CTRL_REG2_MODS_HR 2 #define MMA8X5X_CTRL_REG2_MODS_LP 3 #define MMA8X5X_CTRL_REG2_SLPE (1 << 2) #define MMA8X5X_CTRL_REG2_SMODS_MASK 0x18 #define MMA8X5X_CTRL_REG2_SMODS_NORMAL 0 #define MMA8X5X_CTRL_REG2_SMODS_LNLP 1 #define MMA8X5X_CTRL_REG2_SMODS_HR 2 #define MMA8X5X_CTRL_REG2_SMODS_LP 3 #define MMA8X5X_CTRL_REG2_RST (1 << 6) #define MMA8X5X_CTRL_REG2_ST (1 << 7) #define MMA8X5X_CTRL_REG3_PP_OD (1 << 0) #define MMA8X5X_CTRL_REG3_IPOL (1 << 1) #define MMA8X5X_CTRL_REG3_WAKE_FF_MT (1 << 3) #define MMA8X5X_CTRL_REG3_WAKE_PULSE (1 << 4) #define MMA8X5X_CTRL_REG3_WAKE_LNDPRT (1 << 5) #define MMA8X5X_CTRL_REG3_WAKE_TRANS (1 << 6) #define MMA8X5X_CTRL_REG3_FIFO_GATE (1 << 7) #define MMA8X5X_CTRL_REG4_INT_EN_DRDY (1 << 0) #define MMA8X5X_CTRL_REG4_INT_EN_FF_MT (1 << 2) #define MMA8X5X_CTRL_REG4_INT_EN_PULSE (1 << 3) #define MMA8X5X_CTRL_REG4_INT_EN_LNDPRT (1 << 4) #define MMA8X5X_CTRL_REG4_INT_EN_TRANS (1 << 5) #define MMA8X5X_CTRL_REG4_INT_EN_FIFO (1 << 6) #define MMA8X5X_CTRL_REG4_INT_EN_ASLP (1 << 7) #define MMA8X5X_CTRL_REG5_INT_CFG_DRDY (1 << 0) #define MMA8X5X_CTRL_REG5_INT_CFG_FF_MT (1 << 2) #define MMA8X5X_CTRL_REG5_INT_CFG_PULSE (1 << 3) #define MMA8X5X_CTRL_REG5_INT_CFG_LNDPRT (1 << 4) #define MMA8X5X_CTRL_REG5_INT_CFG_TRANS (1 << 5) #define MMA8X5X_CTRL_REG5_INT_CFG_FIFO (1 << 6) #define MMA8X5X_CTRL_REG5_INT_CFG_ASLP (1 << 7) /** @} */ #ifdef __cplusplus } #endif #endif /** @} */
backenklee/RIOT
drivers/mma8x5x/include/mma8x5x_regs.h
C
lgpl-2.1
11,637
/* * Copyright (C) 2017-2018 Freie Universität Berlin * * This file is subject to the terms and conditions of the GNU Lesser * General Public License v2.1. See the file LICENSE in the top level * directory for more details. */ /** * @ingroup net_cord_ep * @{ * * @file * @brief CoRE Resource Directory endpoint implementation * * @author Hauke Petersen <[email protected]> * * @} */ #include <string.h> #include "mutex.h" #include "assert.h" #include "thread_flags.h" #include "net/gcoap.h" #include "net/ipv6/addr.h" #include "net/cord/ep.h" #include "net/cord/common.h" #include "net/cord/config.h" #ifdef MODULE_CORD_EP_STANDALONE #include "net/cord/ep_standalone.h" #endif #define ENABLE_DEBUG (0) #include "debug.h" #define FLAG_SUCCESS (0x0001) #define FLAG_TIMEOUT (0x0002) #define FLAG_ERR (0x0004) #define FLAG_OVERFLOW (0x0008) #define FLAG_MASK (0x000f) #define BUFSIZE (512U) static char *_regif_buf; static size_t _regif_buf_len; static char _rd_loc[NANOCOAP_URI_MAX]; static char _rd_regif[NANOCOAP_URI_MAX]; static sock_udp_ep_t _rd_remote; static mutex_t _mutex = MUTEX_INIT; static volatile thread_t *_waiter; static uint8_t buf[BUFSIZE]; static void _lock(void) { mutex_lock(&_mutex); _waiter = sched_active_thread; } static int _sync(void) { thread_flags_t flags = thread_flags_wait_any(FLAG_MASK); if (flags & FLAG_ERR) { return CORD_EP_ERR; } else if (flags & FLAG_TIMEOUT) { return CORD_EP_TIMEOUT; } else if (flags & FLAG_OVERFLOW) { return CORD_EP_OVERFLOW; } else { return CORD_EP_OK; } } static void _on_register(const gcoap_request_memo_t *memo, coap_pkt_t* pdu, const sock_udp_ep_t *remote) { thread_flags_t flag = FLAG_ERR; if ((memo->state == GCOAP_MEMO_RESP) && (pdu->hdr->code == COAP_CODE_CREATED)) { /* read the location header and save the RD details on success */ if (coap_get_location_path(pdu, (uint8_t *)_rd_loc, sizeof(_rd_loc)) > 0) { memcpy(&_rd_remote, remote, sizeof(_rd_remote)); flag = FLAG_SUCCESS; } else { /* reset RD entry */ flag = FLAG_OVERFLOW; } } else if (memo->state == GCOAP_MEMO_TIMEOUT) { flag = FLAG_TIMEOUT; } thread_flags_set((thread_t *)_waiter, flag); } static void _on_update_remove(unsigned req_state, coap_pkt_t *pdu, uint8_t code) { thread_flags_t flag = FLAG_ERR; if ((req_state == GCOAP_MEMO_RESP) && (pdu->hdr->code == code)) { flag = FLAG_SUCCESS; } else if (req_state == GCOAP_MEMO_TIMEOUT) { flag = FLAG_TIMEOUT; } thread_flags_set((thread_t *)_waiter, flag); } static void _on_update(const gcoap_request_memo_t *memo, coap_pkt_t *pdu, const sock_udp_ep_t *remote) { (void)remote; _on_update_remove(memo->state, pdu, COAP_CODE_CHANGED); } static void _on_remove(const gcoap_request_memo_t *memo, coap_pkt_t *pdu, const sock_udp_ep_t *remote) { (void)remote; _on_update_remove(memo->state, pdu, COAP_CODE_DELETED); } static int _update_remove(unsigned code, gcoap_resp_handler_t handle) { coap_pkt_t pkt; if (_rd_loc[0] == 0) { return CORD_EP_NORD; } /* build CoAP request packet */ int res = gcoap_req_init(&pkt, buf, sizeof(buf), code, _rd_loc); if (res < 0) { return CORD_EP_ERR; } coap_hdr_set_type(pkt.hdr, COAP_TYPE_CON); ssize_t pkt_len = coap_opt_finish(&pkt, COAP_OPT_FINISH_NONE); /* send request */ gcoap_req_send(buf, pkt_len, &_rd_remote, handle, NULL); /* synchronize response */ return _sync(); } static void _on_discover(const gcoap_request_memo_t *memo, coap_pkt_t *pdu, const sock_udp_ep_t *remote) { thread_flags_t flag = CORD_EP_NORD; (void)remote; if (memo->state == GCOAP_MEMO_RESP) { unsigned ct = coap_get_content_type(pdu); if (ct != COAP_FORMAT_LINK) { goto end; } if (pdu->payload_len == 0) { goto end; } /* do simplified parsing of registration interface location */ char *start = (char *)pdu->payload; char *end; char *limit = (char *)(pdu->payload + pdu->payload_len); while ((*start != '<') && (start < limit)) { start++; } if (*start != '<') { goto end; } end = ++start; while ((*end != '>') && (end < limit)) { end++; } if (*end != '>') { goto end; } /* TODO: verify size of interface resource identifier */ size_t uri_len = (size_t)(end - start); if (uri_len >= _regif_buf_len) { goto end; } memcpy(_regif_buf, start, uri_len); memset((_regif_buf + uri_len), 0, (_regif_buf_len - uri_len)); flag = FLAG_SUCCESS; } else if (memo->state == GCOAP_MEMO_TIMEOUT) { flag = FLAG_TIMEOUT; } end: thread_flags_set((thread_t *)_waiter, flag); } static int _discover_internal(const sock_udp_ep_t *remote, char *regif, size_t maxlen) { coap_pkt_t pkt; /* save pointer to result buffer */ _regif_buf = regif; _regif_buf_len = maxlen; /* do URI discovery for the registration interface */ int res = gcoap_req_init(&pkt, buf, sizeof(buf), COAP_METHOD_GET, "/.well-known/core"); if (res < 0) { return CORD_EP_ERR; } coap_hdr_set_type(pkt.hdr, COAP_TYPE_CON); gcoap_add_qstring(&pkt, "rt", "core.rd"); size_t pkt_len = coap_opt_finish(&pkt, COAP_OPT_FINISH_NONE); res = gcoap_req_send(buf, pkt_len, remote, _on_discover, NULL); if (res < 0) { return CORD_EP_ERR; } return _sync(); } int cord_ep_discover_regif(const sock_udp_ep_t *remote, char *regif, size_t maxlen) { assert(remote && regif); _lock(); int res = _discover_internal(remote, regif, maxlen); mutex_unlock(&_mutex); return res; } int cord_ep_register(const sock_udp_ep_t *remote, const char *regif) { assert(remote); int res; ssize_t pkt_len; int retval; coap_pkt_t pkt; _lock(); /* if no registration interface is given, we will need to trigger a URI * discovery for it first (see section 5.2) */ if (regif == NULL) { retval = _discover_internal(remote, _rd_regif, sizeof(_rd_regif)); if (retval != CORD_EP_OK) { goto end; } } else { if (strlen(_rd_regif) >= sizeof(_rd_regif)) { retval = CORD_EP_OVERFLOW; goto end; } strncpy(_rd_regif, regif, sizeof(_rd_regif)); } /* build and send CoAP POST request to the RD's registration interface */ res = gcoap_req_init(&pkt, buf, sizeof(buf), COAP_METHOD_POST, _rd_regif); if (res < 0) { retval = CORD_EP_ERR; goto end; } /* set some packet options and write query string */ coap_hdr_set_type(pkt.hdr, COAP_TYPE_CON); coap_opt_add_uint(&pkt, COAP_OPT_CONTENT_FORMAT, COAP_FORMAT_LINK); cord_common_add_qstring(&pkt); pkt_len = coap_opt_finish(&pkt, COAP_OPT_FINISH_PAYLOAD); /* add the resource description as payload */ res = gcoap_get_resource_list(pkt.payload, pkt.payload_len, COAP_FORMAT_LINK); if (res < 0) { retval = CORD_EP_ERR; goto end; } pkt_len += res; /* send out the request */ res = gcoap_req_send(buf, pkt_len, remote, _on_register, NULL); if (res < 0) { retval = CORD_EP_ERR; goto end; } retval = _sync(); end: /* if we encountered any error, we mark the endpoint as not connected */ if (retval != CORD_EP_OK) { _rd_loc[0] = '\0'; } #ifdef MODULE_CORD_EP_STANDALONE else { cord_ep_standalone_signal(true); } #endif mutex_unlock(&_mutex); return retval; } int cord_ep_update(void) { _lock(); int res = _update_remove(COAP_METHOD_POST, _on_update); if (res != CORD_EP_OK) { /* in case we are not able to reach the RD, we drop the association */ #ifdef MODULE_CORD_EP_STANDALONE cord_ep_standalone_signal(false); #endif _rd_loc[0] = '\0'; } mutex_unlock(&_mutex); return res; } int cord_ep_remove(void) { _lock(); if (_rd_loc[0] == '\0') { mutex_unlock(&_mutex); return CORD_EP_NORD; } #ifdef MODULE_CORD_EP_STANDALONE cord_ep_standalone_signal(false); #endif _update_remove(COAP_METHOD_DELETE, _on_remove); /* we actually do not care about the result, we drop the RD local RD entry * in any case */ _rd_loc[0] = '\0'; mutex_unlock(&_mutex); return CORD_EP_OK; } void cord_ep_dump_status(void) { puts("CoAP RD connection status:"); if (_rd_loc[0] == 0) { puts(" --- not registered with any RD ---"); } else { /* get address string */ char addr[IPV6_ADDR_MAX_STR_LEN]; ipv6_addr_to_str(addr, (ipv6_addr_t *)&_rd_remote.addr, sizeof(addr)); printf("RD address: coap://[%s]:%i\n", addr, (int)_rd_remote.port); printf(" ep name: %s\n", cord_common_get_ep()); printf(" lifetime: %is\n", (int)CORD_LT); printf(" reg if: %s\n", _rd_regif); printf(" location: %s\n", _rd_loc); } }
aeneby/RIOT
sys/net/application_layer/cord/ep/cord_ep.c
C
lgpl-2.1
9,611
/* * virxdrdefs.h * * Copyright (C) 2016 Red Hat, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see * <http://www.gnu.org/licenses/>. */ #pragma once /* The portablexdr implementation lacks IXDR_PUT_U_INT32 and IXDR_GET_U_INT32 */ #ifndef IXDR_PUT_U_INT32 # define IXDR_PUT_U_INT32 IXDR_PUT_U_LONG #endif #ifndef IXDR_GET_U_INT32 # define IXDR_GET_U_INT32 IXDR_GET_U_LONG #endif
libvirt/libvirt
src/util/virxdrdefs.h
C
lgpl-2.1
982
// Wild Magic Source Code // David Eberly // http://www.geometrictools.com // Copyright (c) 1998-2008 // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation; either version 2.1 of the License, or (at // your option) any later version. The license is available for reading at // either of the locations: // http://www.gnu.org/copyleft/lgpl.html // http://www.geometrictools.com/License/WildMagicLicense.pdf // // Version: 4.0.1 (2007/05/06) #include "Wm4FoundationPCH.h" #include "Wm4IntrTetrahedron3Tetrahedron3.h" namespace Wm4 { //---------------------------------------------------------------------------- template <class Real> IntrTetrahedron3Tetrahedron3<Real>::IntrTetrahedron3Tetrahedron3 ( const Tetrahedron3<Real>& rkTetrahedron0, const Tetrahedron3<Real>& rkTetrahedron1) : m_pkTetrahedron0(&rkTetrahedron0), m_pkTetrahedron1(&rkTetrahedron1) { } //---------------------------------------------------------------------------- template <class Real> const Tetrahedron3<Real>& IntrTetrahedron3Tetrahedron3<Real>::GetTetrahedron0 () const { return *m_pkTetrahedron0; } //---------------------------------------------------------------------------- template <class Real> const Tetrahedron3<Real>& IntrTetrahedron3Tetrahedron3<Real>::GetTetrahedron1 () const { return *m_pkTetrahedron1; } //---------------------------------------------------------------------------- template <class Real> bool IntrTetrahedron3Tetrahedron3<Real>::Find () { // build planar faces of tetrahedron0 Plane3<Real> akPlane[4]; m_pkTetrahedron0->GetPlanes(akPlane,true); // initial object to clip is tetrahedron1 m_kIntersection.clear(); m_kIntersection.push_back(*m_pkTetrahedron1); // clip tetrahedron1 against planes of tetrahedron0 for (int iP = 0; iP < 4; iP++) { std::vector<Tetrahedron3<Real> > kInside; for (int iT = 0; iT < (int)m_kIntersection.size(); iT++) { SplitAndDecompose(m_kIntersection[iT],akPlane[iP],kInside); } m_kIntersection = kInside; } return m_kIntersection.size() > 0; } //---------------------------------------------------------------------------- template <class Real> const std::vector<Tetrahedron3<Real> >& IntrTetrahedron3Tetrahedron3<Real>::GetIntersection () const { return m_kIntersection; } //---------------------------------------------------------------------------- template <class Real> void IntrTetrahedron3Tetrahedron3<Real>::SplitAndDecompose ( Tetrahedron3<Real> kTetra, const Plane3<Real>& rkPlane, std::vector<Tetrahedron3<Real> >& rkInside) { // determine on which side of the plane the points of the tetrahedron lie Real afC[4]; int i, aiP[4], aiN[4], aiZ[4]; int iPositive = 0, iNegative = 0, iZero = 0; for (i = 0; i < 4; i++) { afC[i] = rkPlane.DistanceTo(kTetra.V[i]); if (afC[i] > (Real)0.0) { aiP[iPositive++] = i; } else if (afC[i] < (Real)0.0) { aiN[iNegative++] = i; } else { aiZ[iZero++] = i; } } // For a split to occur, one of the c_i must be positive and one must // be negative. if (iNegative == 0) { // tetrahedron is completely on the positive side of plane, full clip return; } if (iPositive == 0) { // tetrahedron is completely on the negative side of plane rkInside.push_back(kTetra); return; } // Tetrahedron is split by plane. Determine how it is split and how to // decompose the negative-side portion into tetrahedra (6 cases). Real fW0, fW1, fInvCDiff; Vector3<Real> akIntp[4]; if (iPositive == 3) { // +++- for (i = 0; i < iPositive; i++) { fInvCDiff = ((Real)1.0)/(afC[aiP[i]] - afC[aiN[0]]); fW0 = -afC[aiN[0]]*fInvCDiff; fW1 = +afC[aiP[i]]*fInvCDiff; kTetra.V[aiP[i]] = fW0*kTetra.V[aiP[i]] + fW1*kTetra.V[aiN[0]]; } rkInside.push_back(kTetra); } else if (iPositive == 2) { if (iNegative == 2) { // ++-- for (i = 0; i < iPositive; i++) { fInvCDiff = ((Real)1.0)/(afC[aiP[i]]-afC[aiN[0]]); fW0 = -afC[aiN[0]]*fInvCDiff; fW1 = +afC[aiP[i]]*fInvCDiff; akIntp[i] = fW0*kTetra.V[aiP[i]] + fW1*kTetra.V[aiN[0]]; } for (i = 0; i < iNegative; i++) { fInvCDiff = ((Real)1.0)/(afC[aiP[i]]-afC[aiN[1]]); fW0 = -afC[aiN[1]]*fInvCDiff; fW1 = +afC[aiP[i]]*fInvCDiff; akIntp[i+2] = fW0*kTetra.V[aiP[i]] + fW1*kTetra.V[aiN[1]]; } kTetra.V[aiP[0]] = akIntp[2]; kTetra.V[aiP[1]] = akIntp[1]; rkInside.push_back(kTetra); rkInside.push_back(Tetrahedron3<Real>(kTetra.V[aiN[1]],akIntp[3], akIntp[2],akIntp[1])); rkInside.push_back(Tetrahedron3<Real>(kTetra.V[aiN[0]],akIntp[0], akIntp[1],akIntp[2])); } else { // ++-0 for (i = 0; i < iPositive; i++) { fInvCDiff = ((Real)1.0)/(afC[aiP[i]]-afC[aiN[0]]); fW0 = -afC[aiN[0]]*fInvCDiff; fW1 = +afC[aiP[i]]*fInvCDiff; kTetra.V[aiP[i]] = fW0*kTetra.V[aiP[i]] + fW1*kTetra.V[aiN[0]]; } rkInside.push_back(kTetra); } } else if (iPositive == 1) { if (iNegative == 3) { // +--- for (i = 0; i < iNegative; i++) { fInvCDiff = ((Real)1.0)/(afC[aiP[0]]-afC[aiN[i]]); fW0 = -afC[aiN[i]]*fInvCDiff; fW1 = +afC[aiP[0]]*fInvCDiff; akIntp[i] = fW0*kTetra.V[aiP[0]] + fW1*kTetra.V[aiN[i]]; } kTetra.V[aiP[0]] = akIntp[0]; rkInside.push_back(kTetra); rkInside.push_back(Tetrahedron3<Real>(akIntp[0],kTetra.V[aiN[1]], kTetra.V[aiN[2]],akIntp[1])); rkInside.push_back(Tetrahedron3<Real>(kTetra.V[aiN[2]],akIntp[1], akIntp[2],akIntp[0])); } else if (iNegative == 2) { // +--0 for (i = 0; i < iNegative; i++) { fInvCDiff = ((Real)1.0)/(afC[aiP[0]]-afC[aiN[i]]); fW0 = -afC[aiN[i]]*fInvCDiff; fW1 = +afC[aiP[0]]*fInvCDiff; akIntp[i] = fW0*kTetra.V[aiP[0]] + fW1*kTetra.V[aiN[i]]; } kTetra.V[aiP[0]] = akIntp[0]; rkInside.push_back(kTetra); rkInside.push_back(Tetrahedron3<Real>(akIntp[1],kTetra.V[aiZ[0]], kTetra.V[aiN[1]],akIntp[0])); } else { // +-00 fInvCDiff = ((Real)1.0)/(afC[aiP[0]]-afC[aiN[0]]); fW0 = -afC[aiN[0]]*fInvCDiff; fW1 = +afC[aiP[0]]*fInvCDiff; kTetra.V[aiP[0]] = fW0*kTetra.V[aiP[0]] + fW1*kTetra.V[aiN[0]]; rkInside.push_back(kTetra); } } } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- // explicit instantiation //---------------------------------------------------------------------------- template WM4_FOUNDATION_ITEM class IntrTetrahedron3Tetrahedron3<float>; template WM4_FOUNDATION_ITEM class IntrTetrahedron3Tetrahedron3<double>; template WM4_FOUNDATION_ITEM class IntrTetrahedron3Tetrahedron3<long double>; //---------------------------------------------------------------------------- }
rjferrier/fluidity
libwm/Wm4IntrTetrahedron3Tetrahedron3.cpp
C++
lgpl-2.1
8,188
/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ----------------- * PermutationIsomorphismInspector.java * ----------------- * (C) Copyright 2005-2008, by Assaf Lehr and Contributors. * * Original Author: Assaf Lehr * Contributor(s): - * * $Id: PermutationIsomorphismInspector.java 485 2006-06-26 09:12:14Z * perfecthash $ * * Changes * ------- */ package org.jgrapht.experimental.isomorphism; import java.util.*; import org.jgrapht.*; import org.jgrapht.experimental.equivalence.*; import org.jgrapht.experimental.permutation.*; /** * Checks every possible permutation. * * <p>It does not uses the graph topology to enhance the performance. It is * recommended to use only if there cannot be a useful division into equivalence * sets. * * @author Assaf * @since Jul 29, 2005 */ class PermutationIsomorphismInspector<V, E> extends AbstractExhaustiveIsomorphismInspector<V, E> { //~ Constructors ----------------------------------------------------------- /** * @param graph1 * @param graph2 * @param vertexChecker eq. group checker for vertexes. If null, * UniformEquivalenceComparator will be used as default (always return true) * @param edgeChecker eq. group checker for edges. If null, * UniformEquivalenceComparator will be used as default (always return true) */ public PermutationIsomorphismInspector( Graph<V, E> graph1, Graph<V, E> graph2, // XXX hb 060128: FOllowing parameter may need Graph<? super V,? super // E> EquivalenceComparator<? super V, ? super Graph<? super V, ? super E>> vertexChecker, EquivalenceComparator<? super E, ? super Graph<? super V, ? super E>> edgeChecker) { super(graph1, graph2, vertexChecker, edgeChecker); } /** * Constructor which uses the default comparators. * * @see AbstractExhaustiveIsomorphismInspector#AbstractExhaustiveIsomorphismInspector(Graph, * Graph) */ public PermutationIsomorphismInspector( Graph<V, E> graph1, Graph<V, E> graph2) { super(graph1, graph2); } //~ Methods ---------------------------------------------------------------- /** * Creates the permutation iterator, not dependant on equality group, or the * other vertexset. * * @param vertexSet1 FIXME Document me * @param vertexSet2 FIXME Document me * * @return the permutation iterator */ protected CollectionPermutationIter<V> createPermutationIterator( Set<V> vertexSet1, Set<V> vertexSet2) { return new CollectionPermutationIter<V>(vertexSet2); } /** * FIXME Document me FIXME Document me * * @param vertexSet1 FIXME Document me * @param vertexSet2 FIXME Document me * * @return FIXME Document me */ protected boolean areVertexSetsOfTheSameEqualityGroup( Set<V> vertexSet1, Set<V> vertexSet2) { if (vertexSet1.size() != vertexSet2.size()) { return false; } Iterator<V> iter2 = vertexSet2.iterator(); // only check hasNext() of one , cause they are of the same size for (Iterator<V> iter1 = vertexSet1.iterator(); iter1.hasNext();) { V vertex1 = iter1.next(); V vertex2 = iter2.next(); if (!this.vertexComparator.equivalenceCompare( vertex1, vertex2, this.graph1, this.graph2)) { return false; } } return true; } } // End PermutationIsomorphismInspector.java
AndersonQ/IA.2012.2
src/org/jgrapht/experimental/isomorphism/PermutationIsomorphismInspector.java
Java
lgpl-2.1
4,705
/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QGSTREAMERIMAGECAPTURECONTROL_H #define QGSTREAMERIMAGECAPTURECONTROL_H #include <qcameraimagecapturecontrol.h> #include "qgstreamercapturesession.h" QT_BEGIN_NAMESPACE class QGstreamerImageCaptureControl : public QCameraImageCaptureControl { Q_OBJECT public: QGstreamerImageCaptureControl(QGstreamerCaptureSession *session); virtual ~QGstreamerImageCaptureControl(); QCameraImageCapture::DriveMode driveMode() const { return QCameraImageCapture::SingleImageCapture; } void setDriveMode(QCameraImageCapture::DriveMode) {} bool isReadyForCapture() const; int capture(const QString &fileName); void cancelCapture(); private slots: void updateState(); private: QGstreamerCaptureSession *m_session; bool m_ready; int m_lastId; }; QT_END_NAMESPACE #endif // QGSTREAMERCAPTURECORNTROL_H
jfaust/qtmultimedia
src/plugins/gstreamer/mediacapture/qgstreamerimagecapturecontrol.h
C
lgpl-2.1
2,795
/* * Copyright (C) 2005-2010 Alfresco Software Limited. * * This file is part of Alfresco * * Alfresco is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Alfresco is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Alfresco. If not, see <http://www.gnu.org/licenses/>. */ package org.alfresco.repo.security.permissions.impl; import org.alfresco.repo.security.permissions.AccessControlListProperties; import org.alfresco.repo.security.permissions.NodePermissionEntry; import org.alfresco.repo.security.permissions.PermissionEntry; import org.alfresco.repo.security.permissions.PermissionReference; import org.alfresco.service.cmr.repository.NodeRef; import org.alfresco.service.cmr.repository.StoreRef; /** * The API for accessing persisted Alfresco permissions. * * @author andyh */ public interface PermissionsDaoComponent { /** * Get the permissions that have been set on a given node. * * @return the node permission entry */ public NodePermissionEntry getPermissions(NodeRef nodeRef); /** * Delete the access control list and all access control entries for the node. * * @param nodeRef * the node for which to delete permission */ public void deletePermissions(NodeRef nodeRef); /** * Remove all permissions for the specified authority */ public void deletePermissions(String authority); /** * Delete permission entries for the given node and authority * * @param nodeRef * the node to query against * @param authority * the specific authority to query against */ public void deletePermissions(NodeRef nodeRef, String authority); /** * Delete as single permission entry, if a match is found. This deleted one permission on the node. It does not * affect the persistence of any other permissions. * * @param nodeRef * the node with the access control list * @param authority * the specific authority to look for * @param permission * the permission to look for */ public void deletePermission(NodeRef nodeRef, String authority, PermissionReference permission); /** * Set a permission on a node. If the node has no permissions set then a default node permission (allowing * inheritance) will be created to contain the permission entry. */ public void setPermission(NodeRef nodeRef, String authority, PermissionReference perm, boolean allow); /** * Create a persisted permission entry given and other representation of a permission entry. */ public void setPermission(PermissionEntry permissionEntry); /** * Create a persisted node permission entry given a template object from which to copy. */ public void setPermission(NodePermissionEntry nodePermissionEntry); /** * Set the inheritance behaviour for permissions on a given node. */ public void setInheritParentPermissions(NodeRef nodeRef, boolean inheritParentPermissions); /** * Return the inheritance behaviour for permissions on a given node. * * @return inheritParentPermissions */ public boolean getInheritParentPermissions(NodeRef nodeRef); /** * Delete entries from a permission mask on a store by authority */ public void deletePermissions(StoreRef storeRef, String authority); /** * Remove part of a permission mask from a store */ public void deletePermission(StoreRef storeRef, String authority, PermissionReference perm); /** * Remove all permission masks from a store * */ public void deletePermissions(StoreRef storeRef); /** * Set part of a permission mask on a store. */ public void setPermission(StoreRef storeRef, String authority, PermissionReference permission, boolean allow); /** * Get permission masks set on a store * * @return the node permission entry */ public NodePermissionEntry getPermissions(StoreRef storeRef); /** * Get the properties for the access control list * * @return the properties for the access control list */ public AccessControlListProperties getAccessControlListProperties(NodeRef nodeRef); }
fxcebx/community-edition
projects/repository/source/java/org/alfresco/repo/security/permissions/impl/PermissionsDaoComponent.java
Java
lgpl-3.0
4,932
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.common.geo; import org.apache.lucene.spatial.util.GeoHashUtils; import org.elasticsearch.test.ESTestCase; /** * Tests for {@link org.apache.lucene.spatial.util.GeoHashUtils} */ public class GeoHashTests extends ESTestCase { public void testGeohashAsLongRoutines() { final GeoPoint expected = new GeoPoint(); final GeoPoint actual = new GeoPoint(); //Ensure that for all points at all supported levels of precision // that the long encoding of a geohash is compatible with its // String based counterpart for (double lat=-90;lat<90;lat++) { for (double lng=-180;lng<180;lng++) { for(int p=1;p<=12;p++) { long geoAsLong = GeoHashUtils.longEncode(lng, lat, p); // string encode from geohashlong encoded location String geohashFromLong = GeoHashUtils.stringEncode(geoAsLong); // string encode from full res lat lon String geohash = GeoHashUtils.stringEncode(lng, lat, p); // ensure both strings are the same assertEquals(geohash, geohashFromLong); // decode from the full-res geohash string expected.resetFromGeoHash(geohash); // decode from the geohash encoded long actual.resetFromGeoHash(geoAsLong); assertEquals(expected, actual); } } } } }
jbertouch/elasticsearch
core/src/test/java/org/elasticsearch/common/geo/GeoHashTests.java
Java
apache-2.0
2,362
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.heron.scheduler.aurora; import java.io.File; import org.apache.heron.spi.common.Config; import org.apache.heron.spi.common.Context; public final class AuroraContext extends Context { public static final String JOB_LINK_TEMPLATE = "heron.scheduler.job.link.template"; public static final String JOB_TEMPLATE = "heron.scheduler.job.template"; public static final String JOB_MAX_KILL_ATTEMPTS = "heron.scheduler.job.max.kill.attempts"; public static final String JOB_KILL_RETRY_INTERVAL_MS = "heron.scheduler.job.kill.retry.interval.ms"; private AuroraContext() { } public static String getJobLinkTemplate(Config config) { return config.getStringValue(JOB_LINK_TEMPLATE); } public static String getHeronAuroraPath(Config config) { return config.getStringValue(JOB_TEMPLATE, new File(Context.heronConf(config), "heron.aurora").getPath()); } public static int getJobMaxKillAttempts(Config config) { return config.getIntegerValue(JOB_MAX_KILL_ATTEMPTS, 5); } public static long getJobKillRetryIntervalMs(Config config) { return config.getLongValue(JOB_KILL_RETRY_INTERVAL_MS, 2000); } }
twitter/heron
heron/schedulers/src/java/org/apache/heron/scheduler/aurora/AuroraContext.java
Java
apache-2.0
1,976
// // Copyright (c) Microsoft. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System.Reflection; using System.Resources; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Microsoft Azure Resource Management Library")] [assembly: AssemblyDescription("Provides Microsoft Azure resource management operations including Resource Groups.")] [assembly: AssemblyVersion("2.0.0.0")] [assembly: AssemblyFileVersion("2.18.8.0")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Azure .NET SDK")] [assembly: AssemblyCopyright("Copyright (c) Microsoft Corporation")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")]
SpotLabsNET/azure-sdk-for-net
src/ResourceManagement/Resource/ResourceManagement/Properties/AssemblyInfo.cs
C#
apache-2.0
1,276
// Licensed under the Apache License, Version 2.0 (the 'License'); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an 'AS IS' BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. /** * KernelCode namespace holds constant Python code that can be executed in an * IPython kernel that has Apache Beam Python SDK installed. */ export namespace KernelCode { export const COMMON_KERNEL_IMPORTS: string = 'from apache_beam.runners.interactive' + ' import interactive_beam as ib\n' + 'from apache_beam.runners.interactive' + ' import interactive_environment as ie\n'; }
lukecwik/incubator-beam
sdks/python/apache_beam/runners/interactive/extensions/apache-beam-jupyterlab-sidepanel/src/kernel/KernelCode.ts
TypeScript
apache-2.0
958
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. mod a { pub enum Enum<T> { A(T), } pub trait X {} impl X for int {} pub struct Z<'a>(Enum<&'a X>); fn foo() { let x = 42i; let z = Z(A(&x as &X)); let _ = z; } } mod b { trait X {} impl X for int {} struct Y<'a>{ x:Option<&'a X>, } fn bar() { let x = 42i; let _y = Y { x: Some(&x as &X) }; } } mod c { pub trait X { fn f(&self); } impl X for int { fn f(&self) {} } pub struct Z<'a>(Option<&'a X>); fn main() { let x = 42i; let z = Z(Some(&x as &X)); let _ = z; } } pub fn main() {}
stepancheg/rust-ide-rust
src/test/run-pass/issue-9719.rs
Rust
apache-2.0
1,051
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure; using Microsoft.Azure.Management.StreamAnalytics; using Microsoft.Azure.Management.StreamAnalytics.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.StreamAnalytics { /// <summary> /// Operations for managing the function(s) of the stream analytics job. /// </summary> internal partial class FunctionOperations : IServiceOperations<StreamAnalyticsManagementClient>, IFunctionOperations { /// <summary> /// Initializes a new instance of the FunctionOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal FunctionOperations(StreamAnalyticsManagementClient client) { this._client = client; } private StreamAnalyticsManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.StreamAnalytics.StreamAnalyticsManagementClient. /// </summary> public StreamAnalyticsManagementClient Client { get { return this._client; } } /// <summary> /// Test the connectivity of a function for a stream analytics job. /// Asynchronous call. /// </summary> /// <param name='resourceGroupName'> /// Required. The resource group name of the stream analytics job. /// </param> /// <param name='jobName'> /// Required. The name of the stream analytics job. /// </param> /// <param name='functionName'> /// Required. The name of the function for the stream analytics job. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The test result of the input or output data source. /// </returns> public async Task<ResourceTestConnectionResponse> BeginTestConnectionAsync(string resourceGroupName, string jobName, string functionName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (jobName == null) { throw new ArgumentNullException("jobName"); } if (functionName == null) { throw new ArgumentNullException("functionName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("jobName", jobName); tracingParameters.Add("functionName", functionName); TracingAdapter.Enter(invocationId, this, "BeginTestConnectionAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourcegroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/Microsoft.StreamAnalytics/streamingjobs/"; url = url + Uri.EscapeDataString(jobName); url = url + "/functions/"; url = url + Uri.EscapeDataString(functionName); url = url + "/test"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-09-01"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Post; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString()); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Accepted && statusCode != HttpStatusCode.BadRequest && statusCode != HttpStatusCode.NotFound) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ResourceTestConnectionResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Accepted || statusCode == HttpStatusCode.BadRequest || statusCode == HttpStatusCode.NotFound) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ResourceTestConnectionResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken statusValue = responseDoc["status"]; if (statusValue != null && statusValue.Type != JTokenType.Null) { string statusInstance = ((string)statusValue); result.ResourceTestStatus = statusInstance; } JToken errorValue = responseDoc["error"]; if (errorValue != null && errorValue.Type != JTokenType.Null) { ErrorResponse errorInstance = new ErrorResponse(); result.Error = errorInstance; JToken codeValue = errorValue["code"]; if (codeValue != null && codeValue.Type != JTokenType.Null) { string codeInstance = ((string)codeValue); errorInstance.Code = codeInstance; } JToken messageValue = errorValue["message"]; if (messageValue != null && messageValue.Type != JTokenType.Null) { string messageInstance = ((string)messageValue); errorInstance.Message = messageInstance; } JToken detailsValue = errorValue["details"]; if (detailsValue != null && detailsValue.Type != JTokenType.Null) { ErrorDetailsResponse detailsInstance = new ErrorDetailsResponse(); errorInstance.Details = detailsInstance; JToken codeValue2 = detailsValue["code"]; if (codeValue2 != null && codeValue2.Type != JTokenType.Null) { string codeInstance2 = ((string)codeValue2); detailsInstance.Code = codeInstance2; } JToken messageValue2 = detailsValue["message"]; if (messageValue2 != null && messageValue2.Type != JTokenType.Null) { string messageInstance2 = ((string)messageValue2); detailsInstance.Message = messageInstance2; } } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("Location")) { result.OperationStatusLink = httpResponse.Headers.GetValues("Location").FirstOrDefault(); } if (httpResponse.Headers.Contains("Retry-After")) { result.RetryAfter = int.Parse(httpResponse.Headers.GetValues("Retry-After").FirstOrDefault(), CultureInfo.InvariantCulture); } if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (statusCode == HttpStatusCode.NotFound) { result.Status = OperationStatus.Failed; } if (statusCode == HttpStatusCode.BadRequest) { result.Status = OperationStatus.Failed; } if (statusCode == HttpStatusCode.OK) { result.Status = OperationStatus.Succeeded; } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Create or update a function for a stream analytics job. /// </summary> /// <param name='resourceGroupName'> /// Required. The resource group name of the stream analytics job. /// </param> /// <param name='jobName'> /// Required. The name of the stream analytics job. /// </param> /// <param name='parameters'> /// Required. The parameters required to create or update a function /// for a stream analytics job. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response of the function create or update operation. /// </returns> public async Task<FunctionCreateOrUpdateResponse> CreateOrUpdateAsync(string resourceGroupName, string jobName, FunctionCreateOrUpdateParameters parameters, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (jobName == null) { throw new ArgumentNullException("jobName"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Function != null) { if (parameters.Function.Name == null) { throw new ArgumentNullException("parameters.Function.Name"); } } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("jobName", jobName); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourcegroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/Microsoft.StreamAnalytics/streamingjobs/"; url = url + Uri.EscapeDataString(jobName); url = url + "/functions/"; if (parameters.Function != null && parameters.Function.Name != null) { url = url + Uri.EscapeDataString(parameters.Function.Name); } List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-09-01"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString()); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject functionCreateOrUpdateParametersValue = new JObject(); requestDoc = functionCreateOrUpdateParametersValue; if (parameters.Function != null) { functionCreateOrUpdateParametersValue["name"] = parameters.Function.Name; if (parameters.Function.Properties != null) { JObject propertiesValue = new JObject(); functionCreateOrUpdateParametersValue["properties"] = propertiesValue; if (parameters.Function.Properties is ScalarFunctionProperties) { propertiesValue["type"] = "Scalar"; ScalarFunctionProperties derived = ((ScalarFunctionProperties)parameters.Function.Properties); if (derived.Properties != null) { JObject propertiesValue2 = new JObject(); propertiesValue["properties"] = propertiesValue2; if (derived.Properties.Inputs != null) { JArray inputsArray = new JArray(); foreach (FunctionInput inputsItem in derived.Properties.Inputs) { JObject functionInputValue = new JObject(); inputsArray.Add(functionInputValue); if (inputsItem.DataType != null) { functionInputValue["dataType"] = inputsItem.DataType; } if (inputsItem.IsConfigurationParameter != null) { functionInputValue["isConfigurationParameter"] = inputsItem.IsConfigurationParameter.Value; } } propertiesValue2["inputs"] = inputsArray; } if (derived.Properties.Output != null) { JObject outputValue = new JObject(); propertiesValue2["output"] = outputValue; if (derived.Properties.Output.DataType != null) { outputValue["dataType"] = derived.Properties.Output.DataType; } } if (derived.Properties.Binding != null) { JObject bindingValue = new JObject(); propertiesValue2["binding"] = bindingValue; if (derived.Properties.Binding is AzureMachineLearningWebServiceFunctionBinding) { bindingValue["type"] = "Microsoft.MachineLearning/WebService"; AzureMachineLearningWebServiceFunctionBinding derived2 = ((AzureMachineLearningWebServiceFunctionBinding)derived.Properties.Binding); if (derived2.Properties != null) { JObject propertiesValue3 = new JObject(); bindingValue["properties"] = propertiesValue3; if (derived2.Properties.Endpoint != null) { propertiesValue3["endpoint"] = derived2.Properties.Endpoint; } if (derived2.Properties.ApiKey != null) { propertiesValue3["apiKey"] = derived2.Properties.ApiKey; } if (derived2.Properties.Inputs != null) { JObject inputsValue = new JObject(); propertiesValue3["inputs"] = inputsValue; inputsValue["name"] = derived2.Properties.Inputs.Name; if (derived2.Properties.Inputs.ColumnNames != null) { JArray columnNamesArray = new JArray(); foreach (AzureMachineLearningWebServiceInputColumn columnNamesItem in derived2.Properties.Inputs.ColumnNames) { JObject azureMachineLearningWebServiceInputColumnValue = new JObject(); columnNamesArray.Add(azureMachineLearningWebServiceInputColumnValue); azureMachineLearningWebServiceInputColumnValue["name"] = columnNamesItem.Name; if (columnNamesItem.DataType != null) { azureMachineLearningWebServiceInputColumnValue["dataType"] = columnNamesItem.DataType; } if (columnNamesItem.MapTo != null) { azureMachineLearningWebServiceInputColumnValue["mapTo"] = columnNamesItem.MapTo.Value; } } inputsValue["columnNames"] = columnNamesArray; } } if (derived2.Properties.Outputs != null) { JArray outputsArray = new JArray(); foreach (AzureMachineLearningWebServiceOutputColumn outputsItem in derived2.Properties.Outputs) { JObject azureMachineLearningWebServiceOutputColumnValue = new JObject(); outputsArray.Add(azureMachineLearningWebServiceOutputColumnValue); azureMachineLearningWebServiceOutputColumnValue["name"] = outputsItem.Name; if (outputsItem.DataType != null) { azureMachineLearningWebServiceOutputColumnValue["dataType"] = outputsItem.DataType; } } propertiesValue3["outputs"] = outputsArray; } if (derived2.Properties.BatchSize != null) { propertiesValue3["batchSize"] = derived2.Properties.BatchSize.Value; } } if (derived2.Type != null) { bindingValue["type"] = derived2.Type; } } } } if (derived.Etag != null) { propertiesValue["etag"] = derived.Etag; } if (derived.Type != null) { propertiesValue["type"] = derived.Type; } } } } requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result FunctionCreateOrUpdateResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new FunctionCreateOrUpdateResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { Function functionInstance = new Function(); result.Function = functionInstance; JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); functionInstance.Name = nameInstance; } JToken propertiesValue4 = responseDoc["properties"]; if (propertiesValue4 != null && propertiesValue4.Type != JTokenType.Null) { string typeName = ((string)propertiesValue4["type"]); if (typeName == "Scalar") { ScalarFunctionProperties scalarFunctionPropertiesInstance = new ScalarFunctionProperties(); JToken propertiesValue5 = propertiesValue4["properties"]; if (propertiesValue5 != null && propertiesValue5.Type != JTokenType.Null) { ScalarFunctionConfiguration propertiesInstance = new ScalarFunctionConfiguration(); scalarFunctionPropertiesInstance.Properties = propertiesInstance; JToken inputsArray2 = propertiesValue5["inputs"]; if (inputsArray2 != null && inputsArray2.Type != JTokenType.Null) { propertiesInstance.Inputs = new System.Collections.Generic.List<Microsoft.Azure.Management.StreamAnalytics.Models.FunctionInput>(); foreach (JToken inputsValue2 in ((JArray)inputsArray2)) { FunctionInput functionInputInstance = new FunctionInput(); propertiesInstance.Inputs.Add(functionInputInstance); JToken dataTypeValue = inputsValue2["dataType"]; if (dataTypeValue != null && dataTypeValue.Type != JTokenType.Null) { string dataTypeInstance = ((string)dataTypeValue); functionInputInstance.DataType = dataTypeInstance; } JToken isConfigurationParameterValue = inputsValue2["isConfigurationParameter"]; if (isConfigurationParameterValue != null && isConfigurationParameterValue.Type != JTokenType.Null) { bool isConfigurationParameterInstance = ((bool)isConfigurationParameterValue); functionInputInstance.IsConfigurationParameter = isConfigurationParameterInstance; } } } JToken outputValue2 = propertiesValue5["output"]; if (outputValue2 != null && outputValue2.Type != JTokenType.Null) { FunctionOutput outputInstance = new FunctionOutput(); propertiesInstance.Output = outputInstance; JToken dataTypeValue2 = outputValue2["dataType"]; if (dataTypeValue2 != null && dataTypeValue2.Type != JTokenType.Null) { string dataTypeInstance2 = ((string)dataTypeValue2); outputInstance.DataType = dataTypeInstance2; } } JToken bindingValue2 = propertiesValue5["binding"]; if (bindingValue2 != null && bindingValue2.Type != JTokenType.Null) { string typeName2 = ((string)bindingValue2["type"]); if (typeName2 == "Microsoft.MachineLearning/WebService") { AzureMachineLearningWebServiceFunctionBinding azureMachineLearningWebServiceFunctionBindingInstance = new AzureMachineLearningWebServiceFunctionBinding(); JToken propertiesValue6 = bindingValue2["properties"]; if (propertiesValue6 != null && propertiesValue6.Type != JTokenType.Null) { AzureMachineLearningWebServiceFunctionBindingProperties propertiesInstance2 = new AzureMachineLearningWebServiceFunctionBindingProperties(); azureMachineLearningWebServiceFunctionBindingInstance.Properties = propertiesInstance2; JToken endpointValue = propertiesValue6["endpoint"]; if (endpointValue != null && endpointValue.Type != JTokenType.Null) { string endpointInstance = ((string)endpointValue); propertiesInstance2.Endpoint = endpointInstance; } JToken apiKeyValue = propertiesValue6["apiKey"]; if (apiKeyValue != null && apiKeyValue.Type != JTokenType.Null) { string apiKeyInstance = ((string)apiKeyValue); propertiesInstance2.ApiKey = apiKeyInstance; } JToken inputsValue3 = propertiesValue6["inputs"]; if (inputsValue3 != null && inputsValue3.Type != JTokenType.Null) { AzureMachineLearningWebServiceInputs inputsInstance = new AzureMachineLearningWebServiceInputs(); propertiesInstance2.Inputs = inputsInstance; JToken nameValue2 = inputsValue3["name"]; if (nameValue2 != null && nameValue2.Type != JTokenType.Null) { string nameInstance2 = ((string)nameValue2); inputsInstance.Name = nameInstance2; } JToken columnNamesArray2 = inputsValue3["columnNames"]; if (columnNamesArray2 != null && columnNamesArray2.Type != JTokenType.Null) { inputsInstance.ColumnNames = new System.Collections.Generic.List<Microsoft.Azure.Management.StreamAnalytics.Models.AzureMachineLearningWebServiceInputColumn>(); foreach (JToken columnNamesValue in ((JArray)columnNamesArray2)) { AzureMachineLearningWebServiceInputColumn azureMachineLearningWebServiceInputColumnInstance = new AzureMachineLearningWebServiceInputColumn(); inputsInstance.ColumnNames.Add(azureMachineLearningWebServiceInputColumnInstance); JToken nameValue3 = columnNamesValue["name"]; if (nameValue3 != null && nameValue3.Type != JTokenType.Null) { string nameInstance3 = ((string)nameValue3); azureMachineLearningWebServiceInputColumnInstance.Name = nameInstance3; } JToken dataTypeValue3 = columnNamesValue["dataType"]; if (dataTypeValue3 != null && dataTypeValue3.Type != JTokenType.Null) { string dataTypeInstance3 = ((string)dataTypeValue3); azureMachineLearningWebServiceInputColumnInstance.DataType = dataTypeInstance3; } JToken mapToValue = columnNamesValue["mapTo"]; if (mapToValue != null && mapToValue.Type != JTokenType.Null) { int mapToInstance = ((int)mapToValue); azureMachineLearningWebServiceInputColumnInstance.MapTo = mapToInstance; } } } } JToken outputsArray2 = propertiesValue6["outputs"]; if (outputsArray2 != null && outputsArray2.Type != JTokenType.Null) { propertiesInstance2.Outputs = new System.Collections.Generic.List<Microsoft.Azure.Management.StreamAnalytics.Models.AzureMachineLearningWebServiceOutputColumn>(); foreach (JToken outputsValue in ((JArray)outputsArray2)) { AzureMachineLearningWebServiceOutputColumn azureMachineLearningWebServiceOutputColumnInstance = new AzureMachineLearningWebServiceOutputColumn(); propertiesInstance2.Outputs.Add(azureMachineLearningWebServiceOutputColumnInstance); JToken nameValue4 = outputsValue["name"]; if (nameValue4 != null && nameValue4.Type != JTokenType.Null) { string nameInstance4 = ((string)nameValue4); azureMachineLearningWebServiceOutputColumnInstance.Name = nameInstance4; } JToken dataTypeValue4 = outputsValue["dataType"]; if (dataTypeValue4 != null && dataTypeValue4.Type != JTokenType.Null) { string dataTypeInstance4 = ((string)dataTypeValue4); azureMachineLearningWebServiceOutputColumnInstance.DataType = dataTypeInstance4; } } } JToken batchSizeValue = propertiesValue6["batchSize"]; if (batchSizeValue != null && batchSizeValue.Type != JTokenType.Null) { int batchSizeInstance = ((int)batchSizeValue); propertiesInstance2.BatchSize = batchSizeInstance; } } JToken typeValue = bindingValue2["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); azureMachineLearningWebServiceFunctionBindingInstance.Type = typeInstance; } propertiesInstance.Binding = azureMachineLearningWebServiceFunctionBindingInstance; } } } JToken etagValue = propertiesValue4["etag"]; if (etagValue != null && etagValue.Type != JTokenType.Null) { string etagInstance = ((string)etagValue); scalarFunctionPropertiesInstance.Etag = etagInstance; } JToken typeValue2 = propertiesValue4["type"]; if (typeValue2 != null && typeValue2.Type != JTokenType.Null) { string typeInstance2 = ((string)typeValue2); scalarFunctionPropertiesInstance.Type = typeInstance2; } functionInstance.Properties = scalarFunctionPropertiesInstance; } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("Date")) { result.Date = DateTime.Parse(httpResponse.Headers.GetValues("Date").FirstOrDefault(), CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal).ToLocalTime(); } if (httpResponse.Headers.Contains("ETag")) { result.Function.Properties.Etag = httpResponse.Headers.GetValues("ETag").FirstOrDefault(); } if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Create or update a function for a stream analytics job. The raw /// json content will be used. /// </summary> /// <param name='resourceGroupName'> /// Required. The resource group name of the stream analytics job. /// </param> /// <param name='jobName'> /// Required. The name of the stream analytics job. /// </param> /// <param name='functionName'> /// Required. The name of the function for the stream analytics job. /// </param> /// <param name='parameters'> /// Required. The parameters required to create or update a function /// for a stream analytics job. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response of the function create or update operation. /// </returns> public async Task<FunctionCreateOrUpdateResponse> CreateOrUpdateWithRawJsonContentAsync(string resourceGroupName, string jobName, string functionName, FunctionCreateOrUpdateWithRawJsonContentParameters parameters, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (jobName == null) { throw new ArgumentNullException("jobName"); } if (functionName == null) { throw new ArgumentNullException("functionName"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Content == null) { throw new ArgumentNullException("parameters.Content"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("jobName", jobName); tracingParameters.Add("functionName", functionName); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "CreateOrUpdateWithRawJsonContentAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourcegroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/Microsoft.StreamAnalytics/streamingjobs/"; url = url + Uri.EscapeDataString(jobName); url = url + "/functions/"; url = url + Uri.EscapeDataString(functionName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-09-01"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString()); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = parameters.Content; httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result FunctionCreateOrUpdateResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new FunctionCreateOrUpdateResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { Function functionInstance = new Function(); result.Function = functionInstance; JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); functionInstance.Name = nameInstance; } JToken propertiesValue = responseDoc["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { string typeName = ((string)propertiesValue["type"]); if (typeName == "Scalar") { ScalarFunctionProperties scalarFunctionPropertiesInstance = new ScalarFunctionProperties(); JToken propertiesValue2 = propertiesValue["properties"]; if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null) { ScalarFunctionConfiguration propertiesInstance = new ScalarFunctionConfiguration(); scalarFunctionPropertiesInstance.Properties = propertiesInstance; JToken inputsArray = propertiesValue2["inputs"]; if (inputsArray != null && inputsArray.Type != JTokenType.Null) { propertiesInstance.Inputs = new System.Collections.Generic.List<Microsoft.Azure.Management.StreamAnalytics.Models.FunctionInput>(); foreach (JToken inputsValue in ((JArray)inputsArray)) { FunctionInput functionInputInstance = new FunctionInput(); propertiesInstance.Inputs.Add(functionInputInstance); JToken dataTypeValue = inputsValue["dataType"]; if (dataTypeValue != null && dataTypeValue.Type != JTokenType.Null) { string dataTypeInstance = ((string)dataTypeValue); functionInputInstance.DataType = dataTypeInstance; } JToken isConfigurationParameterValue = inputsValue["isConfigurationParameter"]; if (isConfigurationParameterValue != null && isConfigurationParameterValue.Type != JTokenType.Null) { bool isConfigurationParameterInstance = ((bool)isConfigurationParameterValue); functionInputInstance.IsConfigurationParameter = isConfigurationParameterInstance; } } } JToken outputValue = propertiesValue2["output"]; if (outputValue != null && outputValue.Type != JTokenType.Null) { FunctionOutput outputInstance = new FunctionOutput(); propertiesInstance.Output = outputInstance; JToken dataTypeValue2 = outputValue["dataType"]; if (dataTypeValue2 != null && dataTypeValue2.Type != JTokenType.Null) { string dataTypeInstance2 = ((string)dataTypeValue2); outputInstance.DataType = dataTypeInstance2; } } JToken bindingValue = propertiesValue2["binding"]; if (bindingValue != null && bindingValue.Type != JTokenType.Null) { string typeName2 = ((string)bindingValue["type"]); if (typeName2 == "Microsoft.MachineLearning/WebService") { AzureMachineLearningWebServiceFunctionBinding azureMachineLearningWebServiceFunctionBindingInstance = new AzureMachineLearningWebServiceFunctionBinding(); JToken propertiesValue3 = bindingValue["properties"]; if (propertiesValue3 != null && propertiesValue3.Type != JTokenType.Null) { AzureMachineLearningWebServiceFunctionBindingProperties propertiesInstance2 = new AzureMachineLearningWebServiceFunctionBindingProperties(); azureMachineLearningWebServiceFunctionBindingInstance.Properties = propertiesInstance2; JToken endpointValue = propertiesValue3["endpoint"]; if (endpointValue != null && endpointValue.Type != JTokenType.Null) { string endpointInstance = ((string)endpointValue); propertiesInstance2.Endpoint = endpointInstance; } JToken apiKeyValue = propertiesValue3["apiKey"]; if (apiKeyValue != null && apiKeyValue.Type != JTokenType.Null) { string apiKeyInstance = ((string)apiKeyValue); propertiesInstance2.ApiKey = apiKeyInstance; } JToken inputsValue2 = propertiesValue3["inputs"]; if (inputsValue2 != null && inputsValue2.Type != JTokenType.Null) { AzureMachineLearningWebServiceInputs inputsInstance = new AzureMachineLearningWebServiceInputs(); propertiesInstance2.Inputs = inputsInstance; JToken nameValue2 = inputsValue2["name"]; if (nameValue2 != null && nameValue2.Type != JTokenType.Null) { string nameInstance2 = ((string)nameValue2); inputsInstance.Name = nameInstance2; } JToken columnNamesArray = inputsValue2["columnNames"]; if (columnNamesArray != null && columnNamesArray.Type != JTokenType.Null) { inputsInstance.ColumnNames = new System.Collections.Generic.List<Microsoft.Azure.Management.StreamAnalytics.Models.AzureMachineLearningWebServiceInputColumn>(); foreach (JToken columnNamesValue in ((JArray)columnNamesArray)) { AzureMachineLearningWebServiceInputColumn azureMachineLearningWebServiceInputColumnInstance = new AzureMachineLearningWebServiceInputColumn(); inputsInstance.ColumnNames.Add(azureMachineLearningWebServiceInputColumnInstance); JToken nameValue3 = columnNamesValue["name"]; if (nameValue3 != null && nameValue3.Type != JTokenType.Null) { string nameInstance3 = ((string)nameValue3); azureMachineLearningWebServiceInputColumnInstance.Name = nameInstance3; } JToken dataTypeValue3 = columnNamesValue["dataType"]; if (dataTypeValue3 != null && dataTypeValue3.Type != JTokenType.Null) { string dataTypeInstance3 = ((string)dataTypeValue3); azureMachineLearningWebServiceInputColumnInstance.DataType = dataTypeInstance3; } JToken mapToValue = columnNamesValue["mapTo"]; if (mapToValue != null && mapToValue.Type != JTokenType.Null) { int mapToInstance = ((int)mapToValue); azureMachineLearningWebServiceInputColumnInstance.MapTo = mapToInstance; } } } } JToken outputsArray = propertiesValue3["outputs"]; if (outputsArray != null && outputsArray.Type != JTokenType.Null) { propertiesInstance2.Outputs = new System.Collections.Generic.List<Microsoft.Azure.Management.StreamAnalytics.Models.AzureMachineLearningWebServiceOutputColumn>(); foreach (JToken outputsValue in ((JArray)outputsArray)) { AzureMachineLearningWebServiceOutputColumn azureMachineLearningWebServiceOutputColumnInstance = new AzureMachineLearningWebServiceOutputColumn(); propertiesInstance2.Outputs.Add(azureMachineLearningWebServiceOutputColumnInstance); JToken nameValue4 = outputsValue["name"]; if (nameValue4 != null && nameValue4.Type != JTokenType.Null) { string nameInstance4 = ((string)nameValue4); azureMachineLearningWebServiceOutputColumnInstance.Name = nameInstance4; } JToken dataTypeValue4 = outputsValue["dataType"]; if (dataTypeValue4 != null && dataTypeValue4.Type != JTokenType.Null) { string dataTypeInstance4 = ((string)dataTypeValue4); azureMachineLearningWebServiceOutputColumnInstance.DataType = dataTypeInstance4; } } } JToken batchSizeValue = propertiesValue3["batchSize"]; if (batchSizeValue != null && batchSizeValue.Type != JTokenType.Null) { int batchSizeInstance = ((int)batchSizeValue); propertiesInstance2.BatchSize = batchSizeInstance; } } JToken typeValue = bindingValue["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); azureMachineLearningWebServiceFunctionBindingInstance.Type = typeInstance; } propertiesInstance.Binding = azureMachineLearningWebServiceFunctionBindingInstance; } } } JToken etagValue = propertiesValue["etag"]; if (etagValue != null && etagValue.Type != JTokenType.Null) { string etagInstance = ((string)etagValue); scalarFunctionPropertiesInstance.Etag = etagInstance; } JToken typeValue2 = propertiesValue["type"]; if (typeValue2 != null && typeValue2.Type != JTokenType.Null) { string typeInstance2 = ((string)typeValue2); scalarFunctionPropertiesInstance.Type = typeInstance2; } functionInstance.Properties = scalarFunctionPropertiesInstance; } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("Date")) { result.Date = DateTime.Parse(httpResponse.Headers.GetValues("Date").FirstOrDefault(), CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal).ToLocalTime(); } if (httpResponse.Headers.Contains("ETag")) { result.Function.Properties.Etag = httpResponse.Headers.GetValues("ETag").FirstOrDefault(); } if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Delete a function for a stream analytics job. /// </summary> /// <param name='resourceGroupName'> /// Required. The resource group name of the stream analytics job. /// </param> /// <param name='jobName'> /// Required. The name of the stream analytics job. /// </param> /// <param name='functionName'> /// Required. The name of the function for the stream analytics job. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The common operation response. /// </returns> public async Task<CommonOperationResponse> DeleteAsync(string resourceGroupName, string jobName, string functionName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (jobName == null) { throw new ArgumentNullException("jobName"); } if (functionName == null) { throw new ArgumentNullException("functionName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("jobName", jobName); tracingParameters.Add("functionName", functionName); TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourcegroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/Microsoft.StreamAnalytics/streamingjobs/"; url = url + Uri.EscapeDataString(jobName); url = url + "/functions/"; url = url + Uri.EscapeDataString(functionName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-09-01"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Delete; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString()); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.NoContent) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result CommonOperationResponse result = null; // Deserialize Response result = new CommonOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("Date")) { result.Date = DateTime.Parse(httpResponse.Headers.GetValues("Date").FirstOrDefault(), CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal).ToLocalTime(); } if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Get a function for a stream analytics job. /// </summary> /// <param name='resourceGroupName'> /// Required. The resource group name of the stream analytics job. /// </param> /// <param name='jobName'> /// Required. The name of the stream analytics job. /// </param> /// <param name='functionName'> /// Required. The name of the function for the stream analytics job. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response of the get stream analytics function operation. /// </returns> public async Task<FunctionGetResponse> GetAsync(string resourceGroupName, string jobName, string functionName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (jobName == null) { throw new ArgumentNullException("jobName"); } if (functionName == null) { throw new ArgumentNullException("functionName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("jobName", jobName); tracingParameters.Add("functionName", functionName); TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourcegroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/Microsoft.StreamAnalytics/streamingjobs/"; url = url + Uri.EscapeDataString(jobName); url = url + "/functions/"; url = url + Uri.EscapeDataString(functionName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-09-01"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString()); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result FunctionGetResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new FunctionGetResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { Function functionInstance = new Function(); result.Function = functionInstance; JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); functionInstance.Name = nameInstance; } JToken propertiesValue = responseDoc["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { string typeName = ((string)propertiesValue["type"]); if (typeName == "Scalar") { ScalarFunctionProperties scalarFunctionPropertiesInstance = new ScalarFunctionProperties(); JToken propertiesValue2 = propertiesValue["properties"]; if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null) { ScalarFunctionConfiguration propertiesInstance = new ScalarFunctionConfiguration(); scalarFunctionPropertiesInstance.Properties = propertiesInstance; JToken inputsArray = propertiesValue2["inputs"]; if (inputsArray != null && inputsArray.Type != JTokenType.Null) { propertiesInstance.Inputs = new System.Collections.Generic.List<Microsoft.Azure.Management.StreamAnalytics.Models.FunctionInput>(); foreach (JToken inputsValue in ((JArray)inputsArray)) { FunctionInput functionInputInstance = new FunctionInput(); propertiesInstance.Inputs.Add(functionInputInstance); JToken dataTypeValue = inputsValue["dataType"]; if (dataTypeValue != null && dataTypeValue.Type != JTokenType.Null) { string dataTypeInstance = ((string)dataTypeValue); functionInputInstance.DataType = dataTypeInstance; } JToken isConfigurationParameterValue = inputsValue["isConfigurationParameter"]; if (isConfigurationParameterValue != null && isConfigurationParameterValue.Type != JTokenType.Null) { bool isConfigurationParameterInstance = ((bool)isConfigurationParameterValue); functionInputInstance.IsConfigurationParameter = isConfigurationParameterInstance; } } } JToken outputValue = propertiesValue2["output"]; if (outputValue != null && outputValue.Type != JTokenType.Null) { FunctionOutput outputInstance = new FunctionOutput(); propertiesInstance.Output = outputInstance; JToken dataTypeValue2 = outputValue["dataType"]; if (dataTypeValue2 != null && dataTypeValue2.Type != JTokenType.Null) { string dataTypeInstance2 = ((string)dataTypeValue2); outputInstance.DataType = dataTypeInstance2; } } JToken bindingValue = propertiesValue2["binding"]; if (bindingValue != null && bindingValue.Type != JTokenType.Null) { string typeName2 = ((string)bindingValue["type"]); if (typeName2 == "Microsoft.MachineLearning/WebService") { AzureMachineLearningWebServiceFunctionBinding azureMachineLearningWebServiceFunctionBindingInstance = new AzureMachineLearningWebServiceFunctionBinding(); JToken propertiesValue3 = bindingValue["properties"]; if (propertiesValue3 != null && propertiesValue3.Type != JTokenType.Null) { AzureMachineLearningWebServiceFunctionBindingProperties propertiesInstance2 = new AzureMachineLearningWebServiceFunctionBindingProperties(); azureMachineLearningWebServiceFunctionBindingInstance.Properties = propertiesInstance2; JToken endpointValue = propertiesValue3["endpoint"]; if (endpointValue != null && endpointValue.Type != JTokenType.Null) { string endpointInstance = ((string)endpointValue); propertiesInstance2.Endpoint = endpointInstance; } JToken apiKeyValue = propertiesValue3["apiKey"]; if (apiKeyValue != null && apiKeyValue.Type != JTokenType.Null) { string apiKeyInstance = ((string)apiKeyValue); propertiesInstance2.ApiKey = apiKeyInstance; } JToken inputsValue2 = propertiesValue3["inputs"]; if (inputsValue2 != null && inputsValue2.Type != JTokenType.Null) { AzureMachineLearningWebServiceInputs inputsInstance = new AzureMachineLearningWebServiceInputs(); propertiesInstance2.Inputs = inputsInstance; JToken nameValue2 = inputsValue2["name"]; if (nameValue2 != null && nameValue2.Type != JTokenType.Null) { string nameInstance2 = ((string)nameValue2); inputsInstance.Name = nameInstance2; } JToken columnNamesArray = inputsValue2["columnNames"]; if (columnNamesArray != null && columnNamesArray.Type != JTokenType.Null) { inputsInstance.ColumnNames = new System.Collections.Generic.List<Microsoft.Azure.Management.StreamAnalytics.Models.AzureMachineLearningWebServiceInputColumn>(); foreach (JToken columnNamesValue in ((JArray)columnNamesArray)) { AzureMachineLearningWebServiceInputColumn azureMachineLearningWebServiceInputColumnInstance = new AzureMachineLearningWebServiceInputColumn(); inputsInstance.ColumnNames.Add(azureMachineLearningWebServiceInputColumnInstance); JToken nameValue3 = columnNamesValue["name"]; if (nameValue3 != null && nameValue3.Type != JTokenType.Null) { string nameInstance3 = ((string)nameValue3); azureMachineLearningWebServiceInputColumnInstance.Name = nameInstance3; } JToken dataTypeValue3 = columnNamesValue["dataType"]; if (dataTypeValue3 != null && dataTypeValue3.Type != JTokenType.Null) { string dataTypeInstance3 = ((string)dataTypeValue3); azureMachineLearningWebServiceInputColumnInstance.DataType = dataTypeInstance3; } JToken mapToValue = columnNamesValue["mapTo"]; if (mapToValue != null && mapToValue.Type != JTokenType.Null) { int mapToInstance = ((int)mapToValue); azureMachineLearningWebServiceInputColumnInstance.MapTo = mapToInstance; } } } } JToken outputsArray = propertiesValue3["outputs"]; if (outputsArray != null && outputsArray.Type != JTokenType.Null) { propertiesInstance2.Outputs = new System.Collections.Generic.List<Microsoft.Azure.Management.StreamAnalytics.Models.AzureMachineLearningWebServiceOutputColumn>(); foreach (JToken outputsValue in ((JArray)outputsArray)) { AzureMachineLearningWebServiceOutputColumn azureMachineLearningWebServiceOutputColumnInstance = new AzureMachineLearningWebServiceOutputColumn(); propertiesInstance2.Outputs.Add(azureMachineLearningWebServiceOutputColumnInstance); JToken nameValue4 = outputsValue["name"]; if (nameValue4 != null && nameValue4.Type != JTokenType.Null) { string nameInstance4 = ((string)nameValue4); azureMachineLearningWebServiceOutputColumnInstance.Name = nameInstance4; } JToken dataTypeValue4 = outputsValue["dataType"]; if (dataTypeValue4 != null && dataTypeValue4.Type != JTokenType.Null) { string dataTypeInstance4 = ((string)dataTypeValue4); azureMachineLearningWebServiceOutputColumnInstance.DataType = dataTypeInstance4; } } } JToken batchSizeValue = propertiesValue3["batchSize"]; if (batchSizeValue != null && batchSizeValue.Type != JTokenType.Null) { int batchSizeInstance = ((int)batchSizeValue); propertiesInstance2.BatchSize = batchSizeInstance; } } JToken typeValue = bindingValue["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); azureMachineLearningWebServiceFunctionBindingInstance.Type = typeInstance; } propertiesInstance.Binding = azureMachineLearningWebServiceFunctionBindingInstance; } } } JToken etagValue = propertiesValue["etag"]; if (etagValue != null && etagValue.Type != JTokenType.Null) { string etagInstance = ((string)etagValue); scalarFunctionPropertiesInstance.Etag = etagInstance; } JToken typeValue2 = propertiesValue["type"]; if (typeValue2 != null && typeValue2.Type != JTokenType.Null) { string typeInstance2 = ((string)typeValue2); scalarFunctionPropertiesInstance.Type = typeInstance2; } functionInstance.Properties = scalarFunctionPropertiesInstance; } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("Date")) { result.Date = DateTime.Parse(httpResponse.Headers.GetValues("Date").FirstOrDefault(), CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal).ToLocalTime(); } if (httpResponse.Headers.Contains("ETag")) { result.Function.Properties.Etag = httpResponse.Headers.GetValues("ETag").FirstOrDefault(); } if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Get a list of the functions defined in a stream analytics job. /// </summary> /// <param name='resourceGroupName'> /// Required. The resource group name of the stream analytics job. /// </param> /// <param name='jobName'> /// Required. The name of the stream analytics job. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response of the function list operation. /// </returns> public async Task<FunctionListResponse> ListFunctionsInJobAsync(string resourceGroupName, string jobName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (jobName == null) { throw new ArgumentNullException("jobName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("jobName", jobName); TracingAdapter.Enter(invocationId, this, "ListFunctionsInJobAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourcegroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/Microsoft.StreamAnalytics/streamingjobs/"; url = url + Uri.EscapeDataString(jobName); url = url + "/functions"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-09-01"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString()); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result FunctionListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new FunctionListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { Function functionInstance = new Function(); result.Value.Add(functionInstance); JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); functionInstance.Name = nameInstance; } JToken propertiesValue = valueValue["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { string typeName = ((string)propertiesValue["type"]); if (typeName == "Scalar") { ScalarFunctionProperties scalarFunctionPropertiesInstance = new ScalarFunctionProperties(); JToken propertiesValue2 = propertiesValue["properties"]; if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null) { ScalarFunctionConfiguration propertiesInstance = new ScalarFunctionConfiguration(); scalarFunctionPropertiesInstance.Properties = propertiesInstance; JToken inputsArray = propertiesValue2["inputs"]; if (inputsArray != null && inputsArray.Type != JTokenType.Null) { propertiesInstance.Inputs = new System.Collections.Generic.List<Microsoft.Azure.Management.StreamAnalytics.Models.FunctionInput>(); foreach (JToken inputsValue in ((JArray)inputsArray)) { FunctionInput functionInputInstance = new FunctionInput(); propertiesInstance.Inputs.Add(functionInputInstance); JToken dataTypeValue = inputsValue["dataType"]; if (dataTypeValue != null && dataTypeValue.Type != JTokenType.Null) { string dataTypeInstance = ((string)dataTypeValue); functionInputInstance.DataType = dataTypeInstance; } JToken isConfigurationParameterValue = inputsValue["isConfigurationParameter"]; if (isConfigurationParameterValue != null && isConfigurationParameterValue.Type != JTokenType.Null) { bool isConfigurationParameterInstance = ((bool)isConfigurationParameterValue); functionInputInstance.IsConfigurationParameter = isConfigurationParameterInstance; } } } JToken outputValue = propertiesValue2["output"]; if (outputValue != null && outputValue.Type != JTokenType.Null) { FunctionOutput outputInstance = new FunctionOutput(); propertiesInstance.Output = outputInstance; JToken dataTypeValue2 = outputValue["dataType"]; if (dataTypeValue2 != null && dataTypeValue2.Type != JTokenType.Null) { string dataTypeInstance2 = ((string)dataTypeValue2); outputInstance.DataType = dataTypeInstance2; } } JToken bindingValue = propertiesValue2["binding"]; if (bindingValue != null && bindingValue.Type != JTokenType.Null) { string typeName2 = ((string)bindingValue["type"]); if (typeName2 == "Microsoft.MachineLearning/WebService") { AzureMachineLearningWebServiceFunctionBinding azureMachineLearningWebServiceFunctionBindingInstance = new AzureMachineLearningWebServiceFunctionBinding(); JToken propertiesValue3 = bindingValue["properties"]; if (propertiesValue3 != null && propertiesValue3.Type != JTokenType.Null) { AzureMachineLearningWebServiceFunctionBindingProperties propertiesInstance2 = new AzureMachineLearningWebServiceFunctionBindingProperties(); azureMachineLearningWebServiceFunctionBindingInstance.Properties = propertiesInstance2; JToken endpointValue = propertiesValue3["endpoint"]; if (endpointValue != null && endpointValue.Type != JTokenType.Null) { string endpointInstance = ((string)endpointValue); propertiesInstance2.Endpoint = endpointInstance; } JToken apiKeyValue = propertiesValue3["apiKey"]; if (apiKeyValue != null && apiKeyValue.Type != JTokenType.Null) { string apiKeyInstance = ((string)apiKeyValue); propertiesInstance2.ApiKey = apiKeyInstance; } JToken inputsValue2 = propertiesValue3["inputs"]; if (inputsValue2 != null && inputsValue2.Type != JTokenType.Null) { AzureMachineLearningWebServiceInputs inputsInstance = new AzureMachineLearningWebServiceInputs(); propertiesInstance2.Inputs = inputsInstance; JToken nameValue2 = inputsValue2["name"]; if (nameValue2 != null && nameValue2.Type != JTokenType.Null) { string nameInstance2 = ((string)nameValue2); inputsInstance.Name = nameInstance2; } JToken columnNamesArray = inputsValue2["columnNames"]; if (columnNamesArray != null && columnNamesArray.Type != JTokenType.Null) { inputsInstance.ColumnNames = new System.Collections.Generic.List<Microsoft.Azure.Management.StreamAnalytics.Models.AzureMachineLearningWebServiceInputColumn>(); foreach (JToken columnNamesValue in ((JArray)columnNamesArray)) { AzureMachineLearningWebServiceInputColumn azureMachineLearningWebServiceInputColumnInstance = new AzureMachineLearningWebServiceInputColumn(); inputsInstance.ColumnNames.Add(azureMachineLearningWebServiceInputColumnInstance); JToken nameValue3 = columnNamesValue["name"]; if (nameValue3 != null && nameValue3.Type != JTokenType.Null) { string nameInstance3 = ((string)nameValue3); azureMachineLearningWebServiceInputColumnInstance.Name = nameInstance3; } JToken dataTypeValue3 = columnNamesValue["dataType"]; if (dataTypeValue3 != null && dataTypeValue3.Type != JTokenType.Null) { string dataTypeInstance3 = ((string)dataTypeValue3); azureMachineLearningWebServiceInputColumnInstance.DataType = dataTypeInstance3; } JToken mapToValue = columnNamesValue["mapTo"]; if (mapToValue != null && mapToValue.Type != JTokenType.Null) { int mapToInstance = ((int)mapToValue); azureMachineLearningWebServiceInputColumnInstance.MapTo = mapToInstance; } } } } JToken outputsArray = propertiesValue3["outputs"]; if (outputsArray != null && outputsArray.Type != JTokenType.Null) { propertiesInstance2.Outputs = new System.Collections.Generic.List<Microsoft.Azure.Management.StreamAnalytics.Models.AzureMachineLearningWebServiceOutputColumn>(); foreach (JToken outputsValue in ((JArray)outputsArray)) { AzureMachineLearningWebServiceOutputColumn azureMachineLearningWebServiceOutputColumnInstance = new AzureMachineLearningWebServiceOutputColumn(); propertiesInstance2.Outputs.Add(azureMachineLearningWebServiceOutputColumnInstance); JToken nameValue4 = outputsValue["name"]; if (nameValue4 != null && nameValue4.Type != JTokenType.Null) { string nameInstance4 = ((string)nameValue4); azureMachineLearningWebServiceOutputColumnInstance.Name = nameInstance4; } JToken dataTypeValue4 = outputsValue["dataType"]; if (dataTypeValue4 != null && dataTypeValue4.Type != JTokenType.Null) { string dataTypeInstance4 = ((string)dataTypeValue4); azureMachineLearningWebServiceOutputColumnInstance.DataType = dataTypeInstance4; } } } JToken batchSizeValue = propertiesValue3["batchSize"]; if (batchSizeValue != null && batchSizeValue.Type != JTokenType.Null) { int batchSizeInstance = ((int)batchSizeValue); propertiesInstance2.BatchSize = batchSizeInstance; } } JToken typeValue = bindingValue["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); azureMachineLearningWebServiceFunctionBindingInstance.Type = typeInstance; } propertiesInstance.Binding = azureMachineLearningWebServiceFunctionBindingInstance; } } } JToken etagValue = propertiesValue["etag"]; if (etagValue != null && etagValue.Type != JTokenType.Null) { string etagInstance = ((string)etagValue); scalarFunctionPropertiesInstance.Etag = etagInstance; } JToken typeValue2 = propertiesValue["type"]; if (typeValue2 != null && typeValue2.Type != JTokenType.Null) { string typeInstance2 = ((string)typeValue2); scalarFunctionPropertiesInstance.Type = typeInstance2; } functionInstance.Properties = scalarFunctionPropertiesInstance; } } } } JToken nextLinkValue = responseDoc["nextLink"]; if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null) { string nextLinkInstance = ((string)nextLinkValue); result.NextLink = nextLinkInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("Date")) { result.Date = DateTime.Parse(httpResponse.Headers.GetValues("Date").FirstOrDefault(), CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal).ToLocalTime(); } if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Update a function for a stream analytics job. /// </summary> /// <param name='resourceGroupName'> /// Required. The resource group name of the stream analytics job. /// </param> /// <param name='jobName'> /// Required. The name of the stream analytics job. /// </param> /// <param name='functionName'> /// Required. The name of the function for the stream analytics job. /// </param> /// <param name='parameters'> /// Required. The parameters required to update a function for a stream /// analytics job. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response of the function patch operation. /// </returns> public async Task<FunctionPatchResponse> PatchAsync(string resourceGroupName, string jobName, string functionName, FunctionPatchParameters parameters, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (jobName == null) { throw new ArgumentNullException("jobName"); } if (functionName == null) { throw new ArgumentNullException("functionName"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Properties == null) { throw new ArgumentNullException("parameters.Properties"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("jobName", jobName); tracingParameters.Add("functionName", functionName); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "PatchAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourcegroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/Microsoft.StreamAnalytics/streamingjobs/"; url = url + Uri.EscapeDataString(jobName); url = url + "/functions/"; url = url + Uri.EscapeDataString(functionName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-09-01"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("PATCH"); httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString()); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject functionPatchParametersValue = new JObject(); requestDoc = functionPatchParametersValue; JObject propertiesValue = new JObject(); functionPatchParametersValue["properties"] = propertiesValue; if (parameters.Properties is ScalarFunctionProperties) { propertiesValue["type"] = "Scalar"; ScalarFunctionProperties derived = ((ScalarFunctionProperties)parameters.Properties); if (derived.Properties != null) { JObject propertiesValue2 = new JObject(); propertiesValue["properties"] = propertiesValue2; if (derived.Properties.Inputs != null) { JArray inputsArray = new JArray(); foreach (FunctionInput inputsItem in derived.Properties.Inputs) { JObject functionInputValue = new JObject(); inputsArray.Add(functionInputValue); if (inputsItem.DataType != null) { functionInputValue["dataType"] = inputsItem.DataType; } if (inputsItem.IsConfigurationParameter != null) { functionInputValue["isConfigurationParameter"] = inputsItem.IsConfigurationParameter.Value; } } propertiesValue2["inputs"] = inputsArray; } if (derived.Properties.Output != null) { JObject outputValue = new JObject(); propertiesValue2["output"] = outputValue; if (derived.Properties.Output.DataType != null) { outputValue["dataType"] = derived.Properties.Output.DataType; } } if (derived.Properties.Binding != null) { JObject bindingValue = new JObject(); propertiesValue2["binding"] = bindingValue; if (derived.Properties.Binding is AzureMachineLearningWebServiceFunctionBinding) { bindingValue["type"] = "Microsoft.MachineLearning/WebService"; AzureMachineLearningWebServiceFunctionBinding derived2 = ((AzureMachineLearningWebServiceFunctionBinding)derived.Properties.Binding); if (derived2.Properties != null) { JObject propertiesValue3 = new JObject(); bindingValue["properties"] = propertiesValue3; if (derived2.Properties.Endpoint != null) { propertiesValue3["endpoint"] = derived2.Properties.Endpoint; } if (derived2.Properties.ApiKey != null) { propertiesValue3["apiKey"] = derived2.Properties.ApiKey; } if (derived2.Properties.Inputs != null) { JObject inputsValue = new JObject(); propertiesValue3["inputs"] = inputsValue; inputsValue["name"] = derived2.Properties.Inputs.Name; if (derived2.Properties.Inputs.ColumnNames != null) { JArray columnNamesArray = new JArray(); foreach (AzureMachineLearningWebServiceInputColumn columnNamesItem in derived2.Properties.Inputs.ColumnNames) { JObject azureMachineLearningWebServiceInputColumnValue = new JObject(); columnNamesArray.Add(azureMachineLearningWebServiceInputColumnValue); azureMachineLearningWebServiceInputColumnValue["name"] = columnNamesItem.Name; if (columnNamesItem.DataType != null) { azureMachineLearningWebServiceInputColumnValue["dataType"] = columnNamesItem.DataType; } if (columnNamesItem.MapTo != null) { azureMachineLearningWebServiceInputColumnValue["mapTo"] = columnNamesItem.MapTo.Value; } } inputsValue["columnNames"] = columnNamesArray; } } if (derived2.Properties.Outputs != null) { JArray outputsArray = new JArray(); foreach (AzureMachineLearningWebServiceOutputColumn outputsItem in derived2.Properties.Outputs) { JObject azureMachineLearningWebServiceOutputColumnValue = new JObject(); outputsArray.Add(azureMachineLearningWebServiceOutputColumnValue); azureMachineLearningWebServiceOutputColumnValue["name"] = outputsItem.Name; if (outputsItem.DataType != null) { azureMachineLearningWebServiceOutputColumnValue["dataType"] = outputsItem.DataType; } } propertiesValue3["outputs"] = outputsArray; } if (derived2.Properties.BatchSize != null) { propertiesValue3["batchSize"] = derived2.Properties.BatchSize.Value; } } if (derived2.Type != null) { bindingValue["type"] = derived2.Type; } } } } if (derived.Etag != null) { propertiesValue["etag"] = derived.Etag; } if (derived.Type != null) { propertiesValue["type"] = derived.Type; } } requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result FunctionPatchResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new FunctionPatchResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken propertiesValue4 = responseDoc["properties"]; if (propertiesValue4 != null && propertiesValue4.Type != JTokenType.Null) { string typeName = ((string)propertiesValue4["type"]); if (typeName == "Scalar") { ScalarFunctionProperties scalarFunctionPropertiesInstance = new ScalarFunctionProperties(); JToken propertiesValue5 = propertiesValue4["properties"]; if (propertiesValue5 != null && propertiesValue5.Type != JTokenType.Null) { ScalarFunctionConfiguration propertiesInstance = new ScalarFunctionConfiguration(); scalarFunctionPropertiesInstance.Properties = propertiesInstance; JToken inputsArray2 = propertiesValue5["inputs"]; if (inputsArray2 != null && inputsArray2.Type != JTokenType.Null) { propertiesInstance.Inputs = new System.Collections.Generic.List<Microsoft.Azure.Management.StreamAnalytics.Models.FunctionInput>(); foreach (JToken inputsValue2 in ((JArray)inputsArray2)) { FunctionInput functionInputInstance = new FunctionInput(); propertiesInstance.Inputs.Add(functionInputInstance); JToken dataTypeValue = inputsValue2["dataType"]; if (dataTypeValue != null && dataTypeValue.Type != JTokenType.Null) { string dataTypeInstance = ((string)dataTypeValue); functionInputInstance.DataType = dataTypeInstance; } JToken isConfigurationParameterValue = inputsValue2["isConfigurationParameter"]; if (isConfigurationParameterValue != null && isConfigurationParameterValue.Type != JTokenType.Null) { bool isConfigurationParameterInstance = ((bool)isConfigurationParameterValue); functionInputInstance.IsConfigurationParameter = isConfigurationParameterInstance; } } } JToken outputValue2 = propertiesValue5["output"]; if (outputValue2 != null && outputValue2.Type != JTokenType.Null) { FunctionOutput outputInstance = new FunctionOutput(); propertiesInstance.Output = outputInstance; JToken dataTypeValue2 = outputValue2["dataType"]; if (dataTypeValue2 != null && dataTypeValue2.Type != JTokenType.Null) { string dataTypeInstance2 = ((string)dataTypeValue2); outputInstance.DataType = dataTypeInstance2; } } JToken bindingValue2 = propertiesValue5["binding"]; if (bindingValue2 != null && bindingValue2.Type != JTokenType.Null) { string typeName2 = ((string)bindingValue2["type"]); if (typeName2 == "Microsoft.MachineLearning/WebService") { AzureMachineLearningWebServiceFunctionBinding azureMachineLearningWebServiceFunctionBindingInstance = new AzureMachineLearningWebServiceFunctionBinding(); JToken propertiesValue6 = bindingValue2["properties"]; if (propertiesValue6 != null && propertiesValue6.Type != JTokenType.Null) { AzureMachineLearningWebServiceFunctionBindingProperties propertiesInstance2 = new AzureMachineLearningWebServiceFunctionBindingProperties(); azureMachineLearningWebServiceFunctionBindingInstance.Properties = propertiesInstance2; JToken endpointValue = propertiesValue6["endpoint"]; if (endpointValue != null && endpointValue.Type != JTokenType.Null) { string endpointInstance = ((string)endpointValue); propertiesInstance2.Endpoint = endpointInstance; } JToken apiKeyValue = propertiesValue6["apiKey"]; if (apiKeyValue != null && apiKeyValue.Type != JTokenType.Null) { string apiKeyInstance = ((string)apiKeyValue); propertiesInstance2.ApiKey = apiKeyInstance; } JToken inputsValue3 = propertiesValue6["inputs"]; if (inputsValue3 != null && inputsValue3.Type != JTokenType.Null) { AzureMachineLearningWebServiceInputs inputsInstance = new AzureMachineLearningWebServiceInputs(); propertiesInstance2.Inputs = inputsInstance; JToken nameValue = inputsValue3["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); inputsInstance.Name = nameInstance; } JToken columnNamesArray2 = inputsValue3["columnNames"]; if (columnNamesArray2 != null && columnNamesArray2.Type != JTokenType.Null) { inputsInstance.ColumnNames = new System.Collections.Generic.List<Microsoft.Azure.Management.StreamAnalytics.Models.AzureMachineLearningWebServiceInputColumn>(); foreach (JToken columnNamesValue in ((JArray)columnNamesArray2)) { AzureMachineLearningWebServiceInputColumn azureMachineLearningWebServiceInputColumnInstance = new AzureMachineLearningWebServiceInputColumn(); inputsInstance.ColumnNames.Add(azureMachineLearningWebServiceInputColumnInstance); JToken nameValue2 = columnNamesValue["name"]; if (nameValue2 != null && nameValue2.Type != JTokenType.Null) { string nameInstance2 = ((string)nameValue2); azureMachineLearningWebServiceInputColumnInstance.Name = nameInstance2; } JToken dataTypeValue3 = columnNamesValue["dataType"]; if (dataTypeValue3 != null && dataTypeValue3.Type != JTokenType.Null) { string dataTypeInstance3 = ((string)dataTypeValue3); azureMachineLearningWebServiceInputColumnInstance.DataType = dataTypeInstance3; } JToken mapToValue = columnNamesValue["mapTo"]; if (mapToValue != null && mapToValue.Type != JTokenType.Null) { int mapToInstance = ((int)mapToValue); azureMachineLearningWebServiceInputColumnInstance.MapTo = mapToInstance; } } } } JToken outputsArray2 = propertiesValue6["outputs"]; if (outputsArray2 != null && outputsArray2.Type != JTokenType.Null) { propertiesInstance2.Outputs = new System.Collections.Generic.List<Microsoft.Azure.Management.StreamAnalytics.Models.AzureMachineLearningWebServiceOutputColumn>(); foreach (JToken outputsValue in ((JArray)outputsArray2)) { AzureMachineLearningWebServiceOutputColumn azureMachineLearningWebServiceOutputColumnInstance = new AzureMachineLearningWebServiceOutputColumn(); propertiesInstance2.Outputs.Add(azureMachineLearningWebServiceOutputColumnInstance); JToken nameValue3 = outputsValue["name"]; if (nameValue3 != null && nameValue3.Type != JTokenType.Null) { string nameInstance3 = ((string)nameValue3); azureMachineLearningWebServiceOutputColumnInstance.Name = nameInstance3; } JToken dataTypeValue4 = outputsValue["dataType"]; if (dataTypeValue4 != null && dataTypeValue4.Type != JTokenType.Null) { string dataTypeInstance4 = ((string)dataTypeValue4); azureMachineLearningWebServiceOutputColumnInstance.DataType = dataTypeInstance4; } } } JToken batchSizeValue = propertiesValue6["batchSize"]; if (batchSizeValue != null && batchSizeValue.Type != JTokenType.Null) { int batchSizeInstance = ((int)batchSizeValue); propertiesInstance2.BatchSize = batchSizeInstance; } } JToken typeValue = bindingValue2["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); azureMachineLearningWebServiceFunctionBindingInstance.Type = typeInstance; } propertiesInstance.Binding = azureMachineLearningWebServiceFunctionBindingInstance; } } } JToken etagValue = propertiesValue4["etag"]; if (etagValue != null && etagValue.Type != JTokenType.Null) { string etagInstance = ((string)etagValue); scalarFunctionPropertiesInstance.Etag = etagInstance; } JToken typeValue2 = propertiesValue4["type"]; if (typeValue2 != null && typeValue2.Type != JTokenType.Null) { string typeInstance2 = ((string)typeValue2); scalarFunctionPropertiesInstance.Type = typeInstance2; } result.Properties = scalarFunctionPropertiesInstance; } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("Date")) { result.Date = DateTime.Parse(httpResponse.Headers.GetValues("Date").FirstOrDefault(), CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal).ToLocalTime(); } if (httpResponse.Headers.Contains("ETag")) { result.Properties.Etag = httpResponse.Headers.GetValues("ETag").FirstOrDefault(); } if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Retrieve the default definition of a function for a stream /// analytics job. /// </summary> /// <param name='resourceGroupName'> /// Required. The resource group name of the stream analytics job. /// </param> /// <param name='jobName'> /// Required. The name of the stream analytics job. /// </param> /// <param name='functionName'> /// Required. The name of the function for the stream analytics job. /// </param> /// <param name='parameters'> /// Required. The parameters required to retrieve the default /// definition of a function for a stream analytics job. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response of the retrieve default function definition operation. /// </returns> public async Task<FunctionRetrieveDefaultDefinitionResponse> RetrieveDefaultDefinitionAsync(string resourceGroupName, string jobName, string functionName, FunctionRetrieveDefaultDefinitionParameters parameters, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (jobName == null) { throw new ArgumentNullException("jobName"); } if (functionName == null) { throw new ArgumentNullException("functionName"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("jobName", jobName); tracingParameters.Add("functionName", functionName); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "RetrieveDefaultDefinitionAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourcegroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/Microsoft.StreamAnalytics/streamingjobs/"; url = url + Uri.EscapeDataString(jobName); url = url + "/functions/"; url = url + Uri.EscapeDataString(functionName); url = url + "/RetrieveDefaultDefinition"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-09-01"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Post; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString()); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject functionRetrieveDefaultDefinitionParametersValue = new JObject(); requestDoc = functionRetrieveDefaultDefinitionParametersValue; if (parameters is AzureMachineLearningWebServiceFunctionRetrieveDefaultDefinitionParameters) { functionRetrieveDefaultDefinitionParametersValue["bindingType"] = "Microsoft.MachineLearning/WebService"; AzureMachineLearningWebServiceFunctionRetrieveDefaultDefinitionParameters derived = ((AzureMachineLearningWebServiceFunctionRetrieveDefaultDefinitionParameters)parameters); if (derived.BindingRetrievalProperties != null) { JObject bindingRetrievalPropertiesValue = new JObject(); functionRetrieveDefaultDefinitionParametersValue["bindingRetrievalProperties"] = bindingRetrievalPropertiesValue; if (derived.BindingRetrievalProperties.ExecuteEndpoint != null) { bindingRetrievalPropertiesValue["executeEndpoint"] = derived.BindingRetrievalProperties.ExecuteEndpoint; } if (derived.BindingRetrievalProperties.UdfType != null) { bindingRetrievalPropertiesValue["udfType"] = derived.BindingRetrievalProperties.UdfType; } } if (derived.BindingType != null) { functionRetrieveDefaultDefinitionParametersValue["bindingType"] = derived.BindingType; } } requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result FunctionRetrieveDefaultDefinitionResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new FunctionRetrieveDefaultDefinitionResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { Function functionInstance = new Function(); result.Function = functionInstance; JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); functionInstance.Name = nameInstance; } JToken propertiesValue = responseDoc["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { string typeName = ((string)propertiesValue["type"]); if (typeName == "Scalar") { ScalarFunctionProperties scalarFunctionPropertiesInstance = new ScalarFunctionProperties(); JToken propertiesValue2 = propertiesValue["properties"]; if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null) { ScalarFunctionConfiguration propertiesInstance = new ScalarFunctionConfiguration(); scalarFunctionPropertiesInstance.Properties = propertiesInstance; JToken inputsArray = propertiesValue2["inputs"]; if (inputsArray != null && inputsArray.Type != JTokenType.Null) { propertiesInstance.Inputs = new System.Collections.Generic.List<Microsoft.Azure.Management.StreamAnalytics.Models.FunctionInput>(); foreach (JToken inputsValue in ((JArray)inputsArray)) { FunctionInput functionInputInstance = new FunctionInput(); propertiesInstance.Inputs.Add(functionInputInstance); JToken dataTypeValue = inputsValue["dataType"]; if (dataTypeValue != null && dataTypeValue.Type != JTokenType.Null) { string dataTypeInstance = ((string)dataTypeValue); functionInputInstance.DataType = dataTypeInstance; } JToken isConfigurationParameterValue = inputsValue["isConfigurationParameter"]; if (isConfigurationParameterValue != null && isConfigurationParameterValue.Type != JTokenType.Null) { bool isConfigurationParameterInstance = ((bool)isConfigurationParameterValue); functionInputInstance.IsConfigurationParameter = isConfigurationParameterInstance; } } } JToken outputValue = propertiesValue2["output"]; if (outputValue != null && outputValue.Type != JTokenType.Null) { FunctionOutput outputInstance = new FunctionOutput(); propertiesInstance.Output = outputInstance; JToken dataTypeValue2 = outputValue["dataType"]; if (dataTypeValue2 != null && dataTypeValue2.Type != JTokenType.Null) { string dataTypeInstance2 = ((string)dataTypeValue2); outputInstance.DataType = dataTypeInstance2; } } JToken bindingValue = propertiesValue2["binding"]; if (bindingValue != null && bindingValue.Type != JTokenType.Null) { string typeName2 = ((string)bindingValue["type"]); if (typeName2 == "Microsoft.MachineLearning/WebService") { AzureMachineLearningWebServiceFunctionBinding azureMachineLearningWebServiceFunctionBindingInstance = new AzureMachineLearningWebServiceFunctionBinding(); JToken propertiesValue3 = bindingValue["properties"]; if (propertiesValue3 != null && propertiesValue3.Type != JTokenType.Null) { AzureMachineLearningWebServiceFunctionBindingProperties propertiesInstance2 = new AzureMachineLearningWebServiceFunctionBindingProperties(); azureMachineLearningWebServiceFunctionBindingInstance.Properties = propertiesInstance2; JToken endpointValue = propertiesValue3["endpoint"]; if (endpointValue != null && endpointValue.Type != JTokenType.Null) { string endpointInstance = ((string)endpointValue); propertiesInstance2.Endpoint = endpointInstance; } JToken apiKeyValue = propertiesValue3["apiKey"]; if (apiKeyValue != null && apiKeyValue.Type != JTokenType.Null) { string apiKeyInstance = ((string)apiKeyValue); propertiesInstance2.ApiKey = apiKeyInstance; } JToken inputsValue2 = propertiesValue3["inputs"]; if (inputsValue2 != null && inputsValue2.Type != JTokenType.Null) { AzureMachineLearningWebServiceInputs inputsInstance = new AzureMachineLearningWebServiceInputs(); propertiesInstance2.Inputs = inputsInstance; JToken nameValue2 = inputsValue2["name"]; if (nameValue2 != null && nameValue2.Type != JTokenType.Null) { string nameInstance2 = ((string)nameValue2); inputsInstance.Name = nameInstance2; } JToken columnNamesArray = inputsValue2["columnNames"]; if (columnNamesArray != null && columnNamesArray.Type != JTokenType.Null) { inputsInstance.ColumnNames = new System.Collections.Generic.List<Microsoft.Azure.Management.StreamAnalytics.Models.AzureMachineLearningWebServiceInputColumn>(); foreach (JToken columnNamesValue in ((JArray)columnNamesArray)) { AzureMachineLearningWebServiceInputColumn azureMachineLearningWebServiceInputColumnInstance = new AzureMachineLearningWebServiceInputColumn(); inputsInstance.ColumnNames.Add(azureMachineLearningWebServiceInputColumnInstance); JToken nameValue3 = columnNamesValue["name"]; if (nameValue3 != null && nameValue3.Type != JTokenType.Null) { string nameInstance3 = ((string)nameValue3); azureMachineLearningWebServiceInputColumnInstance.Name = nameInstance3; } JToken dataTypeValue3 = columnNamesValue["dataType"]; if (dataTypeValue3 != null && dataTypeValue3.Type != JTokenType.Null) { string dataTypeInstance3 = ((string)dataTypeValue3); azureMachineLearningWebServiceInputColumnInstance.DataType = dataTypeInstance3; } JToken mapToValue = columnNamesValue["mapTo"]; if (mapToValue != null && mapToValue.Type != JTokenType.Null) { int mapToInstance = ((int)mapToValue); azureMachineLearningWebServiceInputColumnInstance.MapTo = mapToInstance; } } } } JToken outputsArray = propertiesValue3["outputs"]; if (outputsArray != null && outputsArray.Type != JTokenType.Null) { propertiesInstance2.Outputs = new System.Collections.Generic.List<Microsoft.Azure.Management.StreamAnalytics.Models.AzureMachineLearningWebServiceOutputColumn>(); foreach (JToken outputsValue in ((JArray)outputsArray)) { AzureMachineLearningWebServiceOutputColumn azureMachineLearningWebServiceOutputColumnInstance = new AzureMachineLearningWebServiceOutputColumn(); propertiesInstance2.Outputs.Add(azureMachineLearningWebServiceOutputColumnInstance); JToken nameValue4 = outputsValue["name"]; if (nameValue4 != null && nameValue4.Type != JTokenType.Null) { string nameInstance4 = ((string)nameValue4); azureMachineLearningWebServiceOutputColumnInstance.Name = nameInstance4; } JToken dataTypeValue4 = outputsValue["dataType"]; if (dataTypeValue4 != null && dataTypeValue4.Type != JTokenType.Null) { string dataTypeInstance4 = ((string)dataTypeValue4); azureMachineLearningWebServiceOutputColumnInstance.DataType = dataTypeInstance4; } } } JToken batchSizeValue = propertiesValue3["batchSize"]; if (batchSizeValue != null && batchSizeValue.Type != JTokenType.Null) { int batchSizeInstance = ((int)batchSizeValue); propertiesInstance2.BatchSize = batchSizeInstance; } } JToken typeValue = bindingValue["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); azureMachineLearningWebServiceFunctionBindingInstance.Type = typeInstance; } propertiesInstance.Binding = azureMachineLearningWebServiceFunctionBindingInstance; } } } JToken etagValue = propertiesValue["etag"]; if (etagValue != null && etagValue.Type != JTokenType.Null) { string etagInstance = ((string)etagValue); scalarFunctionPropertiesInstance.Etag = etagInstance; } JToken typeValue2 = propertiesValue["type"]; if (typeValue2 != null && typeValue2.Type != JTokenType.Null) { string typeInstance2 = ((string)typeValue2); scalarFunctionPropertiesInstance.Type = typeInstance2; } functionInstance.Properties = scalarFunctionPropertiesInstance; } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("Date")) { result.Date = DateTime.Parse(httpResponse.Headers.GetValues("Date").FirstOrDefault(), CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal).ToLocalTime(); } if (httpResponse.Headers.Contains("ETag")) { result.Function.Properties.Etag = httpResponse.Headers.GetValues("ETag").FirstOrDefault(); } if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Retrieve the default definition of a function for a stream /// analytics job. The raw json content will be used for the request /// body. /// </summary> /// <param name='resourceGroupName'> /// Required. The resource group name of the stream analytics job. /// </param> /// <param name='jobName'> /// Required. The name of the stream analytics job. /// </param> /// <param name='functionName'> /// Required. The name of the function for the stream analytics job. /// </param> /// <param name='parameters'> /// Required. The parameters required to retrieve the default /// definition of a function for a stream analytics job. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response of the retrieve default function definition operation. /// </returns> public async Task<FunctionRetrieveDefaultDefinitionResponse> RetrieveDefaultDefinitionWithRawJsonContentAsync(string resourceGroupName, string jobName, string functionName, FunctionRetrieveDefaultDefinitionWithRawJsonContentParameters parameters, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (jobName == null) { throw new ArgumentNullException("jobName"); } if (functionName == null) { throw new ArgumentNullException("functionName"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Content == null) { throw new ArgumentNullException("parameters.Content"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("jobName", jobName); tracingParameters.Add("functionName", functionName); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "RetrieveDefaultDefinitionWithRawJsonContentAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourcegroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/Microsoft.StreamAnalytics/streamingjobs/"; url = url + Uri.EscapeDataString(jobName); url = url + "/functions/"; url = url + Uri.EscapeDataString(functionName); url = url + "/RetrieveDefaultDefinition"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-09-01"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Post; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString()); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = parameters.Content; httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result FunctionRetrieveDefaultDefinitionResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new FunctionRetrieveDefaultDefinitionResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { Function functionInstance = new Function(); result.Function = functionInstance; JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); functionInstance.Name = nameInstance; } JToken propertiesValue = responseDoc["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { string typeName = ((string)propertiesValue["type"]); if (typeName == "Scalar") { ScalarFunctionProperties scalarFunctionPropertiesInstance = new ScalarFunctionProperties(); JToken propertiesValue2 = propertiesValue["properties"]; if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null) { ScalarFunctionConfiguration propertiesInstance = new ScalarFunctionConfiguration(); scalarFunctionPropertiesInstance.Properties = propertiesInstance; JToken inputsArray = propertiesValue2["inputs"]; if (inputsArray != null && inputsArray.Type != JTokenType.Null) { propertiesInstance.Inputs = new System.Collections.Generic.List<Microsoft.Azure.Management.StreamAnalytics.Models.FunctionInput>(); foreach (JToken inputsValue in ((JArray)inputsArray)) { FunctionInput functionInputInstance = new FunctionInput(); propertiesInstance.Inputs.Add(functionInputInstance); JToken dataTypeValue = inputsValue["dataType"]; if (dataTypeValue != null && dataTypeValue.Type != JTokenType.Null) { string dataTypeInstance = ((string)dataTypeValue); functionInputInstance.DataType = dataTypeInstance; } JToken isConfigurationParameterValue = inputsValue["isConfigurationParameter"]; if (isConfigurationParameterValue != null && isConfigurationParameterValue.Type != JTokenType.Null) { bool isConfigurationParameterInstance = ((bool)isConfigurationParameterValue); functionInputInstance.IsConfigurationParameter = isConfigurationParameterInstance; } } } JToken outputValue = propertiesValue2["output"]; if (outputValue != null && outputValue.Type != JTokenType.Null) { FunctionOutput outputInstance = new FunctionOutput(); propertiesInstance.Output = outputInstance; JToken dataTypeValue2 = outputValue["dataType"]; if (dataTypeValue2 != null && dataTypeValue2.Type != JTokenType.Null) { string dataTypeInstance2 = ((string)dataTypeValue2); outputInstance.DataType = dataTypeInstance2; } } JToken bindingValue = propertiesValue2["binding"]; if (bindingValue != null && bindingValue.Type != JTokenType.Null) { string typeName2 = ((string)bindingValue["type"]); if (typeName2 == "Microsoft.MachineLearning/WebService") { AzureMachineLearningWebServiceFunctionBinding azureMachineLearningWebServiceFunctionBindingInstance = new AzureMachineLearningWebServiceFunctionBinding(); JToken propertiesValue3 = bindingValue["properties"]; if (propertiesValue3 != null && propertiesValue3.Type != JTokenType.Null) { AzureMachineLearningWebServiceFunctionBindingProperties propertiesInstance2 = new AzureMachineLearningWebServiceFunctionBindingProperties(); azureMachineLearningWebServiceFunctionBindingInstance.Properties = propertiesInstance2; JToken endpointValue = propertiesValue3["endpoint"]; if (endpointValue != null && endpointValue.Type != JTokenType.Null) { string endpointInstance = ((string)endpointValue); propertiesInstance2.Endpoint = endpointInstance; } JToken apiKeyValue = propertiesValue3["apiKey"]; if (apiKeyValue != null && apiKeyValue.Type != JTokenType.Null) { string apiKeyInstance = ((string)apiKeyValue); propertiesInstance2.ApiKey = apiKeyInstance; } JToken inputsValue2 = propertiesValue3["inputs"]; if (inputsValue2 != null && inputsValue2.Type != JTokenType.Null) { AzureMachineLearningWebServiceInputs inputsInstance = new AzureMachineLearningWebServiceInputs(); propertiesInstance2.Inputs = inputsInstance; JToken nameValue2 = inputsValue2["name"]; if (nameValue2 != null && nameValue2.Type != JTokenType.Null) { string nameInstance2 = ((string)nameValue2); inputsInstance.Name = nameInstance2; } JToken columnNamesArray = inputsValue2["columnNames"]; if (columnNamesArray != null && columnNamesArray.Type != JTokenType.Null) { inputsInstance.ColumnNames = new System.Collections.Generic.List<Microsoft.Azure.Management.StreamAnalytics.Models.AzureMachineLearningWebServiceInputColumn>(); foreach (JToken columnNamesValue in ((JArray)columnNamesArray)) { AzureMachineLearningWebServiceInputColumn azureMachineLearningWebServiceInputColumnInstance = new AzureMachineLearningWebServiceInputColumn(); inputsInstance.ColumnNames.Add(azureMachineLearningWebServiceInputColumnInstance); JToken nameValue3 = columnNamesValue["name"]; if (nameValue3 != null && nameValue3.Type != JTokenType.Null) { string nameInstance3 = ((string)nameValue3); azureMachineLearningWebServiceInputColumnInstance.Name = nameInstance3; } JToken dataTypeValue3 = columnNamesValue["dataType"]; if (dataTypeValue3 != null && dataTypeValue3.Type != JTokenType.Null) { string dataTypeInstance3 = ((string)dataTypeValue3); azureMachineLearningWebServiceInputColumnInstance.DataType = dataTypeInstance3; } JToken mapToValue = columnNamesValue["mapTo"]; if (mapToValue != null && mapToValue.Type != JTokenType.Null) { int mapToInstance = ((int)mapToValue); azureMachineLearningWebServiceInputColumnInstance.MapTo = mapToInstance; } } } } JToken outputsArray = propertiesValue3["outputs"]; if (outputsArray != null && outputsArray.Type != JTokenType.Null) { propertiesInstance2.Outputs = new System.Collections.Generic.List<Microsoft.Azure.Management.StreamAnalytics.Models.AzureMachineLearningWebServiceOutputColumn>(); foreach (JToken outputsValue in ((JArray)outputsArray)) { AzureMachineLearningWebServiceOutputColumn azureMachineLearningWebServiceOutputColumnInstance = new AzureMachineLearningWebServiceOutputColumn(); propertiesInstance2.Outputs.Add(azureMachineLearningWebServiceOutputColumnInstance); JToken nameValue4 = outputsValue["name"]; if (nameValue4 != null && nameValue4.Type != JTokenType.Null) { string nameInstance4 = ((string)nameValue4); azureMachineLearningWebServiceOutputColumnInstance.Name = nameInstance4; } JToken dataTypeValue4 = outputsValue["dataType"]; if (dataTypeValue4 != null && dataTypeValue4.Type != JTokenType.Null) { string dataTypeInstance4 = ((string)dataTypeValue4); azureMachineLearningWebServiceOutputColumnInstance.DataType = dataTypeInstance4; } } } JToken batchSizeValue = propertiesValue3["batchSize"]; if (batchSizeValue != null && batchSizeValue.Type != JTokenType.Null) { int batchSizeInstance = ((int)batchSizeValue); propertiesInstance2.BatchSize = batchSizeInstance; } } JToken typeValue = bindingValue["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); azureMachineLearningWebServiceFunctionBindingInstance.Type = typeInstance; } propertiesInstance.Binding = azureMachineLearningWebServiceFunctionBindingInstance; } } } JToken etagValue = propertiesValue["etag"]; if (etagValue != null && etagValue.Type != JTokenType.Null) { string etagInstance = ((string)etagValue); scalarFunctionPropertiesInstance.Etag = etagInstance; } JToken typeValue2 = propertiesValue["type"]; if (typeValue2 != null && typeValue2.Type != JTokenType.Null) { string typeInstance2 = ((string)typeValue2); scalarFunctionPropertiesInstance.Type = typeInstance2; } functionInstance.Properties = scalarFunctionPropertiesInstance; } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("Date")) { result.Date = DateTime.Parse(httpResponse.Headers.GetValues("Date").FirstOrDefault(), CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal).ToLocalTime(); } if (httpResponse.Headers.Contains("ETag")) { result.Function.Properties.Etag = httpResponse.Headers.GetValues("ETag").FirstOrDefault(); } if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Test the connectivity of a function for a stream analytics job. /// </summary> /// <param name='resourceGroupName'> /// Required. The resource group name of the stream analytics job. /// </param> /// <param name='jobName'> /// Required. The name of the stream analytics job. /// </param> /// <param name='functionName'> /// Required. The name of the function for the stream analytics job. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The test result of the input or output data source. /// </returns> public async Task<ResourceTestConnectionResponse> TestConnectionAsync(string resourceGroupName, string jobName, string functionName, CancellationToken cancellationToken) { StreamAnalyticsManagementClient client = this.Client; bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("jobName", jobName); tracingParameters.Add("functionName", functionName); TracingAdapter.Enter(invocationId, this, "TestConnectionAsync", tracingParameters); } cancellationToken.ThrowIfCancellationRequested(); ResourceTestConnectionResponse response = await client.Functions.BeginTestConnectionAsync(resourceGroupName, jobName, functionName, cancellationToken).ConfigureAwait(false); if (response.Status == OperationStatus.Succeeded) { return response; } cancellationToken.ThrowIfCancellationRequested(); ResourceTestConnectionResponse result = await client.GetTestConnectionStatusAsync(response.OperationStatusLink, cancellationToken).ConfigureAwait(false); int delayInSeconds = response.RetryAfter; if (delayInSeconds == 0) { delayInSeconds = 10; } if (client.LongRunningOperationInitialTimeout >= 0) { delayInSeconds = client.LongRunningOperationInitialTimeout; } while (result.Status == OperationStatus.InProgress) { cancellationToken.ThrowIfCancellationRequested(); await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); result = await client.GetTestConnectionStatusAsync(response.OperationStatusLink, cancellationToken).ConfigureAwait(false); delayInSeconds = result.RetryAfter; if (delayInSeconds == 0) { delayInSeconds = 10; } if (client.LongRunningOperationRetryTimeout >= 0) { delayInSeconds = client.LongRunningOperationRetryTimeout; } } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } } }
abhing/azure-sdk-for-net
src/ResourceManagement/StreamAnalytics/StreamAnalyticsManagement/Generated/FunctionOperations.cs
C#
apache-2.0
223,764
'use strict'; var _ = require('lodash'), childProcess = require('child_process'), execSync = childProcess.execSync, semver = require('semver'), spawn = childProcess.spawn; var branch = 'npm-packages'; var reLine = /^.*$/gm; var output = execSync('git log ' + branch + ' --pretty=format:"%s | %h"').toString(); var pairs = _.map(output.match(reLine), function(value) { var pair = _.map(_.trim(value, '"\'').split('|'), _.trim); pair[0] = _.result(/\d+(?:\.\d+)*/.exec(pair[0]), 0, ''); return pair; }); pairs = _.filter(pairs, '0'); pairs.sort(function(a, b) { return semver.gt(a[0], b[0]) ? 1 : (semver.lt(a[0], b[0]) ? -1 : 0); }); pairs = pairs.map(function(pair) { var tag = pair[0] + (branch == 'master' ? '' : '-' + branch); return [ //'git checkout ' + tag + ' && git commit --amend --no-edit --date "`date`"', 'git tag -f -a -m ' + tag + ' "' + tag + '" ' + pair[1], 'git push -f origin ' + tag ]; }); _.each(pairs, function(pair, index) { _.each(pair, function(command) { _.delay(function() { console.log(command) execSync(command); }, 1000 * index); }); });
ChromeDevTools/devtools-node-modules
third_party/node_modules/lodash/tag.js
JavaScript
apache-2.0
1,142
/* Copyright 2013 Google Inc Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* This class connects to a serial port socket server, and receives data. It is setup to use an arduino with the rotary encoder firmware on it that sends out 3 bytes for the reading. 1 header byte, and 2 data bytes this combines those bytes and fires events when new data is available */ var mootools = require('mootools'); var net = require('net'); var ConfigParams = require('../../ConfigParams').ConfigParams; //test exports.ArmSensorArduinoSocket = new Class({ Implements: [Options, Events, process.EventEmitter], options: { }, initialize: function(NET_PORT, options) { this.setOptions(options); this.UPPER_VALUE = -10; //holds the upper arm degree value this.TIP_VALUE = -10; this.LOWER_VALUE = -10; this.BASE_VALUE = -10; this.serialBuffer = [1000]; //just an array to hold the data bytes //the ascii char code for the header byte this.UPPER_HEADER_CHAR = 66; //B this.TIP_HEADER_CHAR = 67; //C this.LOWER_HEADER_CHAR = 65; //A this.BASE_HEADER_CHAR = 76; //L this.ERROR_HEADER_CHAR = 69; //E if (!NET_PORT) console.log("You must specify a net port."); this.port = NET_PORT; //time admissible for no new data. after this, serial will be reset this.WATCHDOG_PERIOD = 4000; //new serial connection this.createNewNetConnection(); this.flush(); //clear the buffer array just in case. console.log(this.port + " init"); //this.lastTimeDataReceived = (new Date()).getTime(); this.lastTimeDataReceived = 0; this.DEBUG = false; // if (this.DEBUG) this.on('newLowerValue', function(){console.log("new lower value")}); }, runPeriodicDataWatchdog: function() { if (this.DEBUG) { console.log(this.port + " time since data " + this.getTimeSinceLastDataReceived() + " " + this.port + " upper " + this.UPPER_VALUE + " " + this.port + " lower " + this.LOWER_VALUE + " " + this.port + " tip " + this.TIP_VALUE + " " + this.port + " base " + this.BASE_VALUE); } if (this.getTimeSinceLastDataReceived() > this.WATCHDOG_PERIOD) { console.log(this.port + " position data stale: value=" + this.UPPER_VALUE + " time=" + this.getTimeSinceLastDataReceived() + " Re-opening serial port after closing it."); this.serialPort.once('close', function() { console.log(this.port + " Port successfully closed. Now attempting to open."); this.resetSerial(); }.bind(this)); this.serialPort.end(); return; } this.runPeriodicDataWatchdog.delay(this.WATCHDOG_PERIOD, this); }, resetSerial: function() { console.log(this.port + " Resetting serial port now"); this.createNewNetConnection(); }, createNewNetConnection: function() { try { this.serialPort = new net.Stream(); this.serialPort.connect(this.port, '127.0.0.1', function() { console.log('ARDUINO TCP CONNECTED TO: ' + '127.0.0.1' + ':' + this.port); }.bind(this)); this.serialPort.on('data', this.serialData.bind(this)); this.serialPort.on('connect', this.open.bind(this)); //this does not seem to get called by lib this.serialPort.on('error', this.error.bind(this)); this.serialPort.on('close', this.close.bind(this)); this.serialPort.on('end', this.end.bind(this)); this.serialPort.once('data', function() { console.log(this.port + " Got data after reset."); }.bind(this)); //start the watchdog, which will reset the port if the data stops coming in console.log(this.port + " Starting watchdog now."); this.runPeriodicDataWatchdog.delay(this.WATCHDOG_PERIOD, this); } catch (e) { console.log(this.port + " No port opened. Error while attempting to open port: " + e); console.log("Re-attempting open."); this.resetSerial.delay(this.WATCHDOG_PERIOD, this); } }, reportLastLowerArmDegrees: function() { return this.LOWER_VALUE; }, reportLastBase: function() { return this.BASE_VALUE; }, reportLastTipReading: function() { return this.TIP_VALUE; }, getUpperArmDegrees: function() { return this.UPPER_VALUE; }, getTipReading: function() { return temp = this.TIP_VALUE; }, reportLastLowerArmDegrees: function() { return this.LOWER_VALUE; }, reportLastBase: function() { return this.BASE_VALUE; }, getLowerArmDegrees: function() { return this.LOWER_VALUE; }, getBase: function() { return this.BASE_VALUE; }, getTimeSinceLastDataReceived: function() { var time = (new Date()).getTime() - this.lastTimeDataReceived; // if (this.DEBUG) console.log(this.port+" getTimeSinceLastDataReceived(): "+(new Date()).getTime()); // if (this.DEBUG) console.log(this.port+" getTimeSinceLastDataReceived(): "+this.lastTimeDataReceived); // if (this.DEBUG) console.log(this.port+" getTimeSinceLastDataReceived(): "+time); return time; }, updateTimeDataReceived: function() { // if (this.DEBUG) console.log(this.port+" updateTimeDataReceived()"); this.lastTimeDataReceived = (new Date()).getTime(); }, serialData: function(data) { //even though we are sending the serial in bunches of 3 bytes per sensor //they do come in the order sent, but not always in full chunks, //so we cant just process them right away as some data could be missing //until the next data is sent //this just builds a long line of bytes and cycles through them as they come. this.updateTimeDataReceived(); // if (this.DEBUG){ // console.log(this.port); // console.log(this.port+" data length "+data.length); // console.log(this.port+" data "+data); // } //push all the incoming bytes into an array for (var i = 0; i < data.length; i++) { this.serialBuffer.push(data[i]); } //cycle through the bytes until there is less than 3 bytes available while (this.serialBuffer.length >= 6) { //readByte removes that character from the line, so no matter if it // is used at all, we are moving through the serial array var header = this.readByte(); //this allows ot peak at values without removing them var P0 = this.serialBuffer[0]; var P1 = this.serialBuffer[1]; var P2 = this.serialBuffer[2]; var P3 = this.serialBuffer[3]; var P4 = this.serialBuffer[4]; //the pattern of data is this ABCCBA (header, data1 data2, data2, data1, header) //check to see if the next 5 chars with the header we just read matches that pattern //if it does, lets use it, if no skip this and move on to the next character //this way ZABCCB does not match the profile, but does not remove all 6 characters, just 1 //so if the next character comes along is an A, the next round we have ABCCBA, a match if (P0 == P3 && P1 == P2 && header == P4) { MSB = this.readByte(); LSB = this.readByte(); //these are just here to remove them from the chain LSB2 = this.readByte(); MSB2 = this.readByte(); footer = this.readByte(); //console.log('values: '+MSB+' | '+LSB); //if that char matches the header character, //the following 2 bytes are data for the upper arm //////////////////////////////////////////////// if (header == this.UPPER_HEADER_CHAR) { //////////////////////////////////////////////// this.UPPER_VALUE = this.getFloatValue(MSB, LSB); this.emit('newUpperValue', this.UPPER_VALUE); //console.log('UPPER_VALUE: '+this.UPPER_VALUE); //if that char matches the header character, //the following 2 bytes are data for the tip sensor //////////////////////////////////////////////// } else if (header == this.TIP_HEADER_CHAR) { //////////////////////////////////////////////// this.TIP_VALUE = this.getFloatValue(MSB, LSB); this.emit('newTipValue', this.TIP_VALUE); if (this.TIP_VALUE < ConfigParams.HOMEBREW_GALIL__TIP_VALUE_THRESHOLD) this.emit('tipSpot', this.TIP_VALUE); //////////////////////////////////////////////// } else if (header == this.LOWER_HEADER_CHAR) { //////////////////////////////////////////////// this.LOWER_VALUE = this.getFloatValue(MSB, LSB); if (Math.abs(this.LOWER_VALUE - 90) < 1) this.emit('lowerAt90', this.LOWER_VALUE); this.emit('newLowerValue', this.LOWER_VALUE); //////////////////////////////////////////////// } else if (header == this.BASE_HEADER_CHAR) { //////////////////////////////////////////////// if (MSB == 87 && LSB == 87) { this.BASE_VALUE = 'on'; if (this.mostRecent_BASE_VALUE != this.BASE_VALUE) this.emit('baseChange'); this.mostRecent_BASE_VALUE = 'on'; this.emit('newBaseValue', this.BASE_VALUE); } else if (MSB == 66 && LSB == 66) { this.BASE_VALUE = 'off'; if (this.mostRecent_BASE_VALUE != this.BASE_VALUE) this.emit('baseChange'); this.mostRecent_BASE_VALUE = 'off'; this.emit('newBaseValue', this.BASE_VALUE); } else { //console.log('MSB: '+ MSB+'\tLSB: '+LSB); } //////////////////////////////////////////////// } else if (header == this.ERROR_HEADER_CHAR) { //////////////////////////////////////////////// var errorValue = this.getFloatValue(MSB, LSB) > 0 ? "no magnet sensed" : "no sensor attached"; console.log(this.port + "Got error header from arduino. Sensor read was probably bad (" + errorValue + ")"); } else { console.log(this.port + " Arduino serial byte order error."); } } } // this.updateTimeDataReceived(); }, flush: function() { this.serialBuffer = []; }, reset: function() { this.UPPER_VALUE = -10; this.TIP_VALUE = -10; this.LOWER_VALUE = -10; this.BASE_VALUE = -10; this.flush(); }, readByte: function() { ///////////////////////////////////////////// //take 2 data bytes and combine to make an int/10 ///////////////////////////////////////////// return this.serialBuffer.shift(); }, getFloatValue: function(MSB, LSB) { ///////////////////////////////////////////// //take 2 data bytes and combine to make an int/10 ///////////////////////////////////////////// var value = ((MSB << 8) | LSB); //combine the 2 bytes //data comes in in thenths of a degree (1805 for 180.5) value /= 10; return value; }, open: function() { console.log('Arduino Opened'); }, error: function(msg) { console.log(this.port + ' Arduino Error ' + msg); this.emit('arduinoError'); }, close: function() { console.log(this.port + ' Arduino Closed'); this.emit('arduinoClose'); }, end: function() { console.log(this.port + ' Arduino Ended'); this.emit('arduinoEnd'); }, });
r8o8s1e0/ChromeWebLab
Sketchbots/sw/robotcontrol/src/draw_machines/HomebrewGalil/ArmSensorArduinoSocket.js
JavaScript
apache-2.0
12,945
(function () { 'use strict'; angular .module('<%=angularAppName%>') .controller('SocialAuthController', SocialAuthController); SocialAuthController.$inject = ['$state', '$cookies', 'Auth']; function SocialAuthController($state, $cookies, Auth) { var token = $cookies.get('social-authentication'); Auth.loginWithToken(token, false).then(function () { $cookies.remove('social-authentication'); Auth.authorize(true); }, function () { $state.go('social-register', {'success': 'false'}); }); } })();
magnumresearch/manatee
node_modules/generator-jhipster/generators/client/templates/src/main/webapp/app/account/social/_social-auth.controller.js
JavaScript
apache-2.0
603
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.cxf.jaxrs; import java.lang.reflect.Proxy; import org.apache.cxf.jaxrs.lifecycle.PerRequestResourceProvider; import org.apache.cxf.jaxrs.lifecycle.ResourceProvider; import org.apache.cxf.message.Message; public class CamelResourceProvider implements ResourceProvider { // Using the dynamical proxy to provide the instance of client to invoke private Class<?> clazz; private ResourceProvider provider; public CamelResourceProvider(Class<?> clazz) { this.clazz = clazz; if (!clazz.isInterface()) { provider = new PerRequestResourceProvider(clazz); } } @Override public Object getInstance(Message m) { Object result = null; if (provider != null) { result = provider.getInstance(m); } else { // create the instance with the invoker result = Proxy.newProxyInstance(clazz.getClassLoader(), new Class[] {clazz}, new SubResourceClassInvocationHandler()); } return result; } @Override public void releaseInstance(Message m, Object o) { if (provider != null) { provider.releaseInstance(m, o); } } @Override public Class<?> getResourceClass() { if (provider != null) { return provider.getResourceClass(); } else { return clazz; } } @Override public boolean isSingleton() { return false; } }
DariusX/camel
components/camel-cxf/src/main/java/org/apache/camel/component/cxf/jaxrs/CamelResourceProvider.java
Java
apache-2.0
2,339
/* * Copyright 2020 The JSpecify Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import org.jspecify.annotations.DefaultNonNull; import org.jspecify.annotations.Nullable; import org.jspecify.annotations.NullnessUnspecified; @DefaultNonNull class TypeVariableToObjectUnionNull< Never1T, ChildOfNever1T extends Never1T, UnspecChildOfNever1T extends @NullnessUnspecified Never1T, NullChildOfNever1T extends @Nullable Never1T, // Never2T extends Object, ChildOfNever2T extends Never2T, UnspecChildOfNever2T extends @NullnessUnspecified Never2T, NullChildOfNever2T extends @Nullable Never2T, // UnspecT extends @NullnessUnspecified Object, ChildOfUnspecT extends UnspecT, UnspecChildOfUnspecT extends @NullnessUnspecified UnspecT, NullChildOfUnspecT extends @Nullable UnspecT, // ParametricT extends @Nullable Object, ChildOfParametricT extends ParametricT, UnspecChildOfParametricT extends @NullnessUnspecified ParametricT, NullChildOfParametricT extends @Nullable ParametricT, // UnusedT> { @Nullable Object x0(Never1T x) { return x; } @Nullable Object x1(ChildOfNever1T x) { return x; } @Nullable Object x2(UnspecChildOfNever1T x) { return x; } @Nullable Object x3(NullChildOfNever1T x) { return x; } @Nullable Object x4(Never2T x) { return x; } @Nullable Object x5(ChildOfNever2T x) { return x; } @Nullable Object x6(UnspecChildOfNever2T x) { return x; } @Nullable Object x7(NullChildOfNever2T x) { return x; } @Nullable Object x8(UnspecT x) { return x; } @Nullable Object x9(ChildOfUnspecT x) { return x; } @Nullable Object x10(UnspecChildOfUnspecT x) { return x; } @Nullable Object x11(NullChildOfUnspecT x) { return x; } @Nullable Object x12(ParametricT x) { return x; } @Nullable Object x13(ChildOfParametricT x) { return x; } @Nullable Object x14(UnspecChildOfParametricT x) { return x; } @Nullable Object x15(NullChildOfParametricT x) { return x; } }
GunoH/intellij-community
java/java-tests/testData/inspection/dataFlow/jspecify/TypeVariableToObjectUnionNull.java
Java
apache-2.0
2,641
// Copyright (C) 2016 and later: Unicode, Inc. and others. // License & terms of use: http://www.unicode.org/copyright.html /* ******************************************************************************* * * Copyright (C) 2003-2013, International Business Machines * Corporation and others. All Rights Reserved. * ******************************************************************************* * file name: utrace.h * encoding: US-ASCII * tab size: 8 (not used) * indentation:4 * * created on: 2003aug06 * created by: Markus W. Scherer * * Definitions for ICU tracing/logging. * */ #ifndef __UTRACE_H__ #define __UTRACE_H__ #include <stdarg.h> #include "unicode/utypes.h" /** * \file * \brief C API: Definitions for ICU tracing/logging. * * This provides API for debugging the internals of ICU without the use of * a traditional debugger. * * By default, tracing is disabled in ICU. If you need to debug ICU with * tracing, please compile ICU with the --enable-tracing configure option. */ U_CDECL_BEGIN /** * Trace severity levels. Higher levels increase the verbosity of the trace output. * @see utrace_setLevel * @stable ICU 2.8 */ typedef enum UTraceLevel { /** Disable all tracing @stable ICU 2.8*/ UTRACE_OFF=-1, /** Trace error conditions only @stable ICU 2.8*/ UTRACE_ERROR=0, /** Trace errors and warnings @stable ICU 2.8*/ UTRACE_WARNING=3, /** Trace opens and closes of ICU services @stable ICU 2.8*/ UTRACE_OPEN_CLOSE=5, /** Trace an intermediate number of ICU operations @stable ICU 2.8*/ UTRACE_INFO=7, /** Trace the maximum number of ICU operations @stable ICU 2.8*/ UTRACE_VERBOSE=9 } UTraceLevel; /** * These are the ICU functions that will be traced when tracing is enabled. * @stable ICU 2.8 */ typedef enum UTraceFunctionNumber { UTRACE_FUNCTION_START=0, UTRACE_U_INIT=UTRACE_FUNCTION_START, UTRACE_U_CLEANUP, #ifndef U_HIDE_DEPRECATED_API /** * One more than the highest normal collation trace location. * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. */ UTRACE_FUNCTION_LIMIT, #endif // U_HIDE_DEPRECATED_API UTRACE_CONVERSION_START=0x1000, UTRACE_UCNV_OPEN=UTRACE_CONVERSION_START, UTRACE_UCNV_OPEN_PACKAGE, UTRACE_UCNV_OPEN_ALGORITHMIC, UTRACE_UCNV_CLONE, UTRACE_UCNV_CLOSE, UTRACE_UCNV_FLUSH_CACHE, UTRACE_UCNV_LOAD, UTRACE_UCNV_UNLOAD, #ifndef U_HIDE_DEPRECATED_API /** * One more than the highest normal collation trace location. * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. */ UTRACE_CONVERSION_LIMIT, #endif // U_HIDE_DEPRECATED_API UTRACE_COLLATION_START=0x2000, UTRACE_UCOL_OPEN=UTRACE_COLLATION_START, UTRACE_UCOL_CLOSE, UTRACE_UCOL_STRCOLL, UTRACE_UCOL_GET_SORTKEY, UTRACE_UCOL_GETLOCALE, UTRACE_UCOL_NEXTSORTKEYPART, UTRACE_UCOL_STRCOLLITER, UTRACE_UCOL_OPEN_FROM_SHORT_STRING, UTRACE_UCOL_STRCOLLUTF8, /**< @stable ICU 50 */ #ifndef U_HIDE_DEPRECATED_API /** * One more than the highest normal collation trace location. * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. */ UTRACE_COLLATION_LIMIT #endif // U_HIDE_DEPRECATED_API } UTraceFunctionNumber; /** * Setter for the trace level. * @param traceLevel A UTraceLevel value. * @stable ICU 2.8 */ U_STABLE void U_EXPORT2 utrace_setLevel(int32_t traceLevel); /** * Getter for the trace level. * @return The UTraceLevel value being used by ICU. * @stable ICU 2.8 */ U_STABLE int32_t U_EXPORT2 utrace_getLevel(void); /* Trace function pointers types ----------------------------- */ /** * Type signature for the trace function to be called when entering a function. * @param context value supplied at the time the trace functions are set. * @param fnNumber Enum value indicating the ICU function being entered. * @stable ICU 2.8 */ typedef void U_CALLCONV UTraceEntry(const void *context, int32_t fnNumber); /** * Type signature for the trace function to be called when exiting from a function. * @param context value supplied at the time the trace functions are set. * @param fnNumber Enum value indicating the ICU function being exited. * @param fmt A formatting string that describes the number and types * of arguments included with the variable args. The fmt * string has the same form as the utrace_vformat format * string. * @param args A variable arguments list. Contents are described by * the fmt parameter. * @see utrace_vformat * @stable ICU 2.8 */ typedef void U_CALLCONV UTraceExit(const void *context, int32_t fnNumber, const char *fmt, va_list args); /** * Type signature for the trace function to be called from within an ICU function * to display data or messages. * @param context value supplied at the time the trace functions are set. * @param fnNumber Enum value indicating the ICU function being exited. * @param level The current tracing level * @param fmt A format string describing the tracing data that is supplied * as variable args * @param args The data being traced, passed as variable args. * @stable ICU 2.8 */ typedef void U_CALLCONV UTraceData(const void *context, int32_t fnNumber, int32_t level, const char *fmt, va_list args); /** * Set ICU Tracing functions. Installs application-provided tracing * functions into ICU. After doing this, subsequent ICU operations * will call back to the installed functions, providing a trace * of the use of ICU. Passing a NULL pointer for a tracing function * is allowed, and inhibits tracing action at points where that function * would be called. * <p> * Tracing and Threads: Tracing functions are global to a process, and * will be called in response to ICU operations performed by any * thread. If tracing of an individual thread is desired, the * tracing functions must themselves filter by checking that the * current thread is the desired thread. * * @param context an uninterpretted pointer. Whatever is passed in * here will in turn be passed to each of the tracing * functions UTraceEntry, UTraceExit and UTraceData. * ICU does not use or alter this pointer. * @param e Callback function to be called on entry to a * a traced ICU function. * @param x Callback function to be called on exit from a * traced ICU function. * @param d Callback function to be called from within a * traced ICU function, for the purpose of providing * data to the trace. * * @stable ICU 2.8 */ U_STABLE void U_EXPORT2 utrace_setFunctions(const void *context, UTraceEntry *e, UTraceExit *x, UTraceData *d); /** * Get the currently installed ICU tracing functions. Note that a null function * pointer will be returned if no trace function has been set. * * @param context The currently installed tracing context. * @param e The currently installed UTraceEntry function. * @param x The currently installed UTraceExit function. * @param d The currently installed UTraceData function. * @stable ICU 2.8 */ U_STABLE void U_EXPORT2 utrace_getFunctions(const void **context, UTraceEntry **e, UTraceExit **x, UTraceData **d); /* * * ICU trace format string syntax * * Format Strings are passed to UTraceData functions, and define the * number and types of the trace data being passed on each call. * * The UTraceData function, which is supplied by the application, * not by ICU, can either forward the trace data (passed via * varargs) and the format string back to ICU for formatting into * a displayable string, or it can interpret the format itself, * and do as it wishes with the trace data. * * * Goals for the format string * - basic data output * - easy to use for trace programmer * - sufficient provision for data types for trace output readability * - well-defined types and binary portable APIs * * Non-goals * - printf compatibility * - fancy formatting * - argument reordering and other internationalization features * * ICU trace format strings contain plain text with argument inserts, * much like standard printf format strings. * Each insert begins with a '%', then optionally contains a 'v', * then exactly one type character. * Two '%' in a row represent a '%' instead of an insert. * The trace format strings need not have \n at the end. * * * Types * ----- * * Type characters: * - c A char character in the default codepage. * - s A NUL-terminated char * string in the default codepage. * - S A UChar * string. Requires two params, (ptr, length). Length=-1 for nul term. * - b A byte (8-bit integer). * - h A 16-bit integer. Also a 16 bit Unicode code unit. * - d A 32-bit integer. Also a 20 bit Unicode code point value. * - l A 64-bit integer. * - p A data pointer. * * Vectors * ------- * * If the 'v' is not specified, then one item of the specified type * is passed in. * If the 'v' (for "vector") is specified, then a vector of items of the * specified type is passed in, via a pointer to the first item * and an int32_t value for the length of the vector. * Length==-1 means zero or NUL termination. Works for vectors of all types. * * Note: %vS is a vector of (UChar *) strings. The strings must * be nul terminated as there is no way to provide a * separate length parameter for each string. The length * parameter (required for all vectors) is the number of * strings, not the length of the strings. * * Examples * -------- * * These examples show the parameters that will be passed to an application's * UTraceData() function for various formats. * * - the precise formatting is up to the application! * - the examples use type casts for arguments only to _show_ the types of * arguments without needing variable declarations in the examples; * the type casts will not be necessary in actual code * * UTraceDataFunc(context, fnNumber, level, * "There is a character %c in the string %s.", // Format String * (char)c, (const char *)s); // varargs parameters * -> There is a character 0x42 'B' in the string "Bravo". * * UTraceDataFunc(context, fnNumber, level, * "Vector of bytes %vb vector of chars %vc", * (const uint8_t *)bytes, (int32_t)bytesLength, * (const char *)chars, (int32_t)charsLength); * -> Vector of bytes * 42 63 64 3f [4] * vector of chars * "Bcd?"[4] * * UTraceDataFunc(context, fnNumber, level, * "An int32_t %d and a whole bunch of them %vd", * (int32_t)-5, (const int32_t *)ints, (int32_t)intsLength); * -> An int32_t 0xfffffffb and a whole bunch of them * fffffffb 00000005 0000010a [3] * */ /** * Trace output Formatter. An application's UTraceData tracing functions may call * back to this function to format the trace output in a * human readable form. Note that a UTraceData function may choose * to not format the data; it could, for example, save it in * in the raw form it was received (more compact), leaving * formatting for a later trace analyis tool. * @param outBuf pointer to a buffer to receive the formatted output. Output * will be nul terminated if there is space in the buffer - * if the length of the requested output < the output buffer size. * @param capacity Length of the output buffer. * @param indent Number of spaces to indent the output. Intended to allow * data displayed from nested functions to be indented for readability. * @param fmt Format specification for the data to output * @param args Data to be formatted. * @return Length of formatted output, including the terminating NUL. * If buffer capacity is insufficient, the required capacity is returned. * @stable ICU 2.8 */ U_STABLE int32_t U_EXPORT2 utrace_vformat(char *outBuf, int32_t capacity, int32_t indent, const char *fmt, va_list args); /** * Trace output Formatter. An application's UTraceData tracing functions may call * this function to format any additional trace data, beyond that * provided by default, in human readable form with the same * formatting conventions used by utrace_vformat(). * @param outBuf pointer to a buffer to receive the formatted output. Output * will be nul terminated if there is space in the buffer - * if the length of the requested output < the output buffer size. * @param capacity Length of the output buffer. * @param indent Number of spaces to indent the output. Intended to allow * data displayed from nested functions to be indented for readability. * @param fmt Format specification for the data to output * @param ... Data to be formatted. * @return Length of formatted output, including the terminating NUL. * If buffer capacity is insufficient, the required capacity is returned. * @stable ICU 2.8 */ U_STABLE int32_t U_EXPORT2 utrace_format(char *outBuf, int32_t capacity, int32_t indent, const char *fmt, ...); /* Trace function numbers --------------------------------------------------- */ /** * Get the name of a function from its trace function number. * * @param fnNumber The trace number for an ICU function. * @return The name string for the function. * * @see UTraceFunctionNumber * @stable ICU 2.8 */ U_STABLE const char * U_EXPORT2 utrace_functionName(int32_t fnNumber); U_CDECL_END #endif
qscx9512/vdl
vdl/include/unicode/utrace.h
C
apache-2.0
14,233
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.spark.sql.catalyst.analysis import org.apache.spark.sql.catalog.v2.{Identifier, TableCatalog, TestTableCatalog} import org.apache.spark.sql.catalog.v2.expressions.LogicalExpressions import org.apache.spark.sql.catalyst.expressions.AttributeReference import org.apache.spark.sql.catalyst.plans.logical.{CreateTableAsSelect, LeafNode} import org.apache.spark.sql.types.{DoubleType, LongType, StringType, StructType} import org.apache.spark.sql.util.CaseInsensitiveStringMap class CreateTablePartitioningValidationSuite extends AnalysisTest { import CreateTablePartitioningValidationSuite._ test("CreateTableAsSelect: fail missing top-level column") { val plan = CreateTableAsSelect( catalog, Identifier.of(Array(), "table_name"), LogicalExpressions.bucket(4, "does_not_exist") :: Nil, TestRelation2, Map.empty, Map.empty, ignoreIfExists = false) assert(!plan.resolved) assertAnalysisError(plan, Seq( "Invalid partitioning", "does_not_exist is missing or is in a map or array")) } test("CreateTableAsSelect: fail missing top-level column nested reference") { val plan = CreateTableAsSelect( catalog, Identifier.of(Array(), "table_name"), LogicalExpressions.bucket(4, "does_not_exist.z") :: Nil, TestRelation2, Map.empty, Map.empty, ignoreIfExists = false) assert(!plan.resolved) assertAnalysisError(plan, Seq( "Invalid partitioning", "does_not_exist.z is missing or is in a map or array")) } test("CreateTableAsSelect: fail missing nested column") { val plan = CreateTableAsSelect( catalog, Identifier.of(Array(), "table_name"), LogicalExpressions.bucket(4, "point.z") :: Nil, TestRelation2, Map.empty, Map.empty, ignoreIfExists = false) assert(!plan.resolved) assertAnalysisError(plan, Seq( "Invalid partitioning", "point.z is missing or is in a map or array")) } test("CreateTableAsSelect: fail with multiple errors") { val plan = CreateTableAsSelect( catalog, Identifier.of(Array(), "table_name"), LogicalExpressions.bucket(4, "does_not_exist", "point.z") :: Nil, TestRelation2, Map.empty, Map.empty, ignoreIfExists = false) assert(!plan.resolved) assertAnalysisError(plan, Seq( "Invalid partitioning", "point.z is missing or is in a map or array", "does_not_exist is missing or is in a map or array")) } test("CreateTableAsSelect: success with top-level column") { val plan = CreateTableAsSelect( catalog, Identifier.of(Array(), "table_name"), LogicalExpressions.bucket(4, "id") :: Nil, TestRelation2, Map.empty, Map.empty, ignoreIfExists = false) assertAnalysisSuccess(plan) } test("CreateTableAsSelect: success using nested column") { val plan = CreateTableAsSelect( catalog, Identifier.of(Array(), "table_name"), LogicalExpressions.bucket(4, "point.x") :: Nil, TestRelation2, Map.empty, Map.empty, ignoreIfExists = false) assertAnalysisSuccess(plan) } test("CreateTableAsSelect: success using complex column") { val plan = CreateTableAsSelect( catalog, Identifier.of(Array(), "table_name"), LogicalExpressions.bucket(4, "point") :: Nil, TestRelation2, Map.empty, Map.empty, ignoreIfExists = false) assertAnalysisSuccess(plan) } } private object CreateTablePartitioningValidationSuite { val catalog: TableCatalog = { val cat = new TestTableCatalog() cat.initialize("test", CaseInsensitiveStringMap.empty()) cat } val schema: StructType = new StructType() .add("id", LongType) .add("data", StringType) .add("point", new StructType().add("x", DoubleType).add("y", DoubleType)) } private case object TestRelation2 extends LeafNode with NamedRelation { override def name: String = "source_relation" override def output: Seq[AttributeReference] = CreateTablePartitioningValidationSuite.schema.toAttributes }
aosagie/spark
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/analysis/CreateTablePartitioningValidationSuite.scala
Scala
apache-2.0
4,941
/* * Copyright 2012 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.handler.codec.compression; import io.netty.buffer.ByteBuf; /** * Uncompresses an input {@link ByteBuf} encoded with Snappy compression into an * output {@link ByteBuf}. * * See <a href="https://github.com/google/snappy/blob/master/format_description.txt">snappy format</a>. */ public final class Snappy { private static final int MAX_HT_SIZE = 1 << 14; private static final int MIN_COMPRESSIBLE_BYTES = 15; // used as a return value to indicate that we haven't yet read our full preamble private static final int PREAMBLE_NOT_FULL = -1; private static final int NOT_ENOUGH_INPUT = -1; // constants for the tag types private static final int LITERAL = 0; private static final int COPY_1_BYTE_OFFSET = 1; private static final int COPY_2_BYTE_OFFSET = 2; private static final int COPY_4_BYTE_OFFSET = 3; private State state = State.READY; private byte tag; private int written; private enum State { READY, READING_PREAMBLE, READING_TAG, READING_LITERAL, READING_COPY } public void reset() { state = State.READY; tag = 0; written = 0; } public void encode(final ByteBuf in, final ByteBuf out, final int length) { // Write the preamble length to the output buffer for (int i = 0;; i ++) { int b = length >>> i * 7; if ((b & 0xFFFFFF80) != 0) { out.writeByte(b & 0x7f | 0x80); } else { out.writeByte(b); break; } } int inIndex = in.readerIndex(); final int baseIndex = inIndex; final short[] table = getHashTable(length); final int shift = Integer.numberOfLeadingZeros(table.length) + 1; int nextEmit = inIndex; if (length - inIndex >= MIN_COMPRESSIBLE_BYTES) { int nextHash = hash(in, ++inIndex, shift); outer: while (true) { int skip = 32; int candidate; int nextIndex = inIndex; do { inIndex = nextIndex; int hash = nextHash; int bytesBetweenHashLookups = skip++ >> 5; nextIndex = inIndex + bytesBetweenHashLookups; // We need at least 4 remaining bytes to read the hash if (nextIndex > length - 4) { break outer; } nextHash = hash(in, nextIndex, shift); candidate = baseIndex + table[hash]; table[hash] = (short) (inIndex - baseIndex); } while (in.getInt(inIndex) != in.getInt(candidate)); encodeLiteral(in, out, inIndex - nextEmit); int insertTail; do { int base = inIndex; int matched = 4 + findMatchingLength(in, candidate + 4, inIndex + 4, length); inIndex += matched; int offset = base - candidate; encodeCopy(out, offset, matched); in.readerIndex(in.readerIndex() + matched); insertTail = inIndex - 1; nextEmit = inIndex; if (inIndex >= length - 4) { break outer; } int prevHash = hash(in, insertTail, shift); table[prevHash] = (short) (inIndex - baseIndex - 1); int currentHash = hash(in, insertTail + 1, shift); candidate = baseIndex + table[currentHash]; table[currentHash] = (short) (inIndex - baseIndex); } while (in.getInt(insertTail + 1) == in.getInt(candidate)); nextHash = hash(in, insertTail + 2, shift); ++inIndex; } } // If there are any remaining characters, write them out as a literal if (nextEmit < length) { encodeLiteral(in, out, length - nextEmit); } } /** * Hashes the 4 bytes located at index, shifting the resulting hash into * the appropriate range for our hash table. * * @param in The input buffer to read 4 bytes from * @param index The index to read at * @param shift The shift value, for ensuring that the resulting value is * withing the range of our hash table size * @return A 32-bit hash of 4 bytes located at index */ private static int hash(ByteBuf in, int index, int shift) { return in.getInt(index) * 0x1e35a7bd >>> shift; } /** * Creates an appropriately sized hashtable for the given input size * * @param inputSize The size of our input, ie. the number of bytes we need to encode * @return An appropriately sized empty hashtable */ private static short[] getHashTable(int inputSize) { int htSize = 256; while (htSize < MAX_HT_SIZE && htSize < inputSize) { htSize <<= 1; } return new short[htSize]; } /** * Iterates over the supplied input buffer between the supplied minIndex and * maxIndex to find how long our matched copy overlaps with an already-written * literal value. * * @param in The input buffer to scan over * @param minIndex The index in the input buffer to start scanning from * @param inIndex The index of the start of our copy * @param maxIndex The length of our input buffer * @return The number of bytes for which our candidate copy is a repeat of */ private static int findMatchingLength(ByteBuf in, int minIndex, int inIndex, int maxIndex) { int matched = 0; while (inIndex <= maxIndex - 4 && in.getInt(inIndex) == in.getInt(minIndex + matched)) { inIndex += 4; matched += 4; } while (inIndex < maxIndex && in.getByte(minIndex + matched) == in.getByte(inIndex)) { ++inIndex; ++matched; } return matched; } /** * Calculates the minimum number of bits required to encode a value. This can * then in turn be used to calculate the number of septets or octets (as * appropriate) to use to encode a length parameter. * * @param value The value to calculate the minimum number of bits required to encode * @return The minimum number of bits required to encode the supplied value */ private static int bitsToEncode(int value) { int highestOneBit = Integer.highestOneBit(value); int bitLength = 0; while ((highestOneBit >>= 1) != 0) { bitLength++; } return bitLength; } /** * Writes a literal to the supplied output buffer by directly copying from * the input buffer. The literal is taken from the current readerIndex * up to the supplied length. * * @param in The input buffer to copy from * @param out The output buffer to copy to * @param length The length of the literal to copy */ static void encodeLiteral(ByteBuf in, ByteBuf out, int length) { if (length < 61) { out.writeByte(length - 1 << 2); } else { int bitLength = bitsToEncode(length - 1); int bytesToEncode = 1 + bitLength / 8; out.writeByte(59 + bytesToEncode << 2); for (int i = 0; i < bytesToEncode; i++) { out.writeByte(length - 1 >> i * 8 & 0x0ff); } } out.writeBytes(in, length); } private static void encodeCopyWithOffset(ByteBuf out, int offset, int length) { if (length < 12 && offset < 2048) { out.writeByte(COPY_1_BYTE_OFFSET | length - 4 << 2 | offset >> 8 << 5); out.writeByte(offset & 0x0ff); } else { out.writeByte(COPY_2_BYTE_OFFSET | length - 1 << 2); out.writeByte(offset & 0x0ff); out.writeByte(offset >> 8 & 0x0ff); } } /** * Encodes a series of copies, each at most 64 bytes in length. * * @param out The output buffer to write the copy pointer to * @param offset The offset at which the original instance lies * @param length The length of the original instance */ private static void encodeCopy(ByteBuf out, int offset, int length) { while (length >= 68) { encodeCopyWithOffset(out, offset, 64); length -= 64; } if (length > 64) { encodeCopyWithOffset(out, offset, 60); length -= 60; } encodeCopyWithOffset(out, offset, length); } public void decode(ByteBuf in, ByteBuf out) { while (in.isReadable()) { switch (state) { case READY: state = State.READING_PREAMBLE; // fall through case READING_PREAMBLE: int uncompressedLength = readPreamble(in); if (uncompressedLength == PREAMBLE_NOT_FULL) { // We've not yet read all of the preamble, so wait until we can return; } if (uncompressedLength == 0) { // Should never happen, but it does mean we have nothing further to do state = State.READY; return; } out.ensureWritable(uncompressedLength); state = State.READING_TAG; // fall through case READING_TAG: if (!in.isReadable()) { return; } tag = in.readByte(); switch (tag & 0x03) { case LITERAL: state = State.READING_LITERAL; break; case COPY_1_BYTE_OFFSET: case COPY_2_BYTE_OFFSET: case COPY_4_BYTE_OFFSET: state = State.READING_COPY; break; } break; case READING_LITERAL: int literalWritten = decodeLiteral(tag, in, out); if (literalWritten != NOT_ENOUGH_INPUT) { state = State.READING_TAG; written += literalWritten; } else { // Need to wait for more data return; } break; case READING_COPY: int decodeWritten; switch (tag & 0x03) { case COPY_1_BYTE_OFFSET: decodeWritten = decodeCopyWith1ByteOffset(tag, in, out, written); if (decodeWritten != NOT_ENOUGH_INPUT) { state = State.READING_TAG; written += decodeWritten; } else { // Need to wait for more data return; } break; case COPY_2_BYTE_OFFSET: decodeWritten = decodeCopyWith2ByteOffset(tag, in, out, written); if (decodeWritten != NOT_ENOUGH_INPUT) { state = State.READING_TAG; written += decodeWritten; } else { // Need to wait for more data return; } break; case COPY_4_BYTE_OFFSET: decodeWritten = decodeCopyWith4ByteOffset(tag, in, out, written); if (decodeWritten != NOT_ENOUGH_INPUT) { state = State.READING_TAG; written += decodeWritten; } else { // Need to wait for more data return; } break; } } } } /** * Reads the length varint (a series of bytes, where the lower 7 bits * are data and the upper bit is a flag to indicate more bytes to be * read). * * @param in The input buffer to read the preamble from * @return The calculated length based on the input buffer, or 0 if * no preamble is able to be calculated */ private static int readPreamble(ByteBuf in) { int length = 0; int byteIndex = 0; while (in.isReadable()) { int current = in.readUnsignedByte(); length |= (current & 0x7f) << byteIndex++ * 7; if ((current & 0x80) == 0) { return length; } if (byteIndex >= 4) { throw new DecompressionException("Preamble is greater than 4 bytes"); } } return 0; } /** * Reads a literal from the input buffer directly to the output buffer. * A "literal" is an uncompressed segment of data stored directly in the * byte stream. * * @param tag The tag that identified this segment as a literal is also * used to encode part of the length of the data * @param in The input buffer to read the literal from * @param out The output buffer to write the literal to * @return The number of bytes appended to the output buffer, or -1 to indicate "try again later" */ static int decodeLiteral(byte tag, ByteBuf in, ByteBuf out) { in.markReaderIndex(); int length; switch(tag >> 2 & 0x3F) { case 60: if (!in.isReadable()) { return NOT_ENOUGH_INPUT; } length = in.readUnsignedByte(); break; case 61: if (in.readableBytes() < 2) { return NOT_ENOUGH_INPUT; } length = in.readUnsignedShortLE(); break; case 62: if (in.readableBytes() < 3) { return NOT_ENOUGH_INPUT; } length = in.readUnsignedMediumLE(); break; case 63: if (in.readableBytes() < 4) { return NOT_ENOUGH_INPUT; } length = in.readIntLE(); break; default: length = tag >> 2 & 0x3F; } length += 1; if (in.readableBytes() < length) { in.resetReaderIndex(); return NOT_ENOUGH_INPUT; } out.writeBytes(in, length); return length; } /** * Reads a compressed reference offset and length from the supplied input * buffer, seeks back to the appropriate place in the input buffer and * writes the found data to the supplied output stream. * * @param tag The tag used to identify this as a copy is also used to encode * the length and part of the offset * @param in The input buffer to read from * @param out The output buffer to write to * @return The number of bytes appended to the output buffer, or -1 to indicate * "try again later" * @throws DecompressionException If the read offset is invalid */ private static int decodeCopyWith1ByteOffset(byte tag, ByteBuf in, ByteBuf out, int writtenSoFar) { if (!in.isReadable()) { return NOT_ENOUGH_INPUT; } int initialIndex = out.writerIndex(); int length = 4 + ((tag & 0x01c) >> 2); int offset = (tag & 0x0e0) << 8 >> 5 | in.readUnsignedByte(); validateOffset(offset, writtenSoFar); out.markReaderIndex(); if (offset < length) { int copies = length / offset; for (; copies > 0; copies--) { out.readerIndex(initialIndex - offset); out.readBytes(out, offset); } if (length % offset != 0) { out.readerIndex(initialIndex - offset); out.readBytes(out, length % offset); } } else { out.readerIndex(initialIndex - offset); out.readBytes(out, length); } out.resetReaderIndex(); return length; } /** * Reads a compressed reference offset and length from the supplied input * buffer, seeks back to the appropriate place in the input buffer and * writes the found data to the supplied output stream. * * @param tag The tag used to identify this as a copy is also used to encode * the length and part of the offset * @param in The input buffer to read from * @param out The output buffer to write to * @throws DecompressionException If the read offset is invalid * @return The number of bytes appended to the output buffer, or -1 to indicate * "try again later" */ private static int decodeCopyWith2ByteOffset(byte tag, ByteBuf in, ByteBuf out, int writtenSoFar) { if (in.readableBytes() < 2) { return NOT_ENOUGH_INPUT; } int initialIndex = out.writerIndex(); int length = 1 + (tag >> 2 & 0x03f); int offset = in.readUnsignedShortLE(); validateOffset(offset, writtenSoFar); out.markReaderIndex(); if (offset < length) { int copies = length / offset; for (; copies > 0; copies--) { out.readerIndex(initialIndex - offset); out.readBytes(out, offset); } if (length % offset != 0) { out.readerIndex(initialIndex - offset); out.readBytes(out, length % offset); } } else { out.readerIndex(initialIndex - offset); out.readBytes(out, length); } out.resetReaderIndex(); return length; } /** * Reads a compressed reference offset and length from the supplied input * buffer, seeks back to the appropriate place in the input buffer and * writes the found data to the supplied output stream. * * @param tag The tag used to identify this as a copy is also used to encode * the length and part of the offset * @param in The input buffer to read from * @param out The output buffer to write to * @return The number of bytes appended to the output buffer, or -1 to indicate * "try again later" * @throws DecompressionException If the read offset is invalid */ private static int decodeCopyWith4ByteOffset(byte tag, ByteBuf in, ByteBuf out, int writtenSoFar) { if (in.readableBytes() < 4) { return NOT_ENOUGH_INPUT; } int initialIndex = out.writerIndex(); int length = 1 + (tag >> 2 & 0x03F); int offset = in.readIntLE(); validateOffset(offset, writtenSoFar); out.markReaderIndex(); if (offset < length) { int copies = length / offset; for (; copies > 0; copies--) { out.readerIndex(initialIndex - offset); out.readBytes(out, offset); } if (length % offset != 0) { out.readerIndex(initialIndex - offset); out.readBytes(out, length % offset); } } else { out.readerIndex(initialIndex - offset); out.readBytes(out, length); } out.resetReaderIndex(); return length; } /** * Validates that the offset extracted from a compressed reference is within * the permissible bounds of an offset (0 < offset < Integer.MAX_VALUE), and does not * exceed the length of the chunk currently read so far. * * @param offset The offset extracted from the compressed reference * @param chunkSizeSoFar The number of bytes read so far from this chunk * @throws DecompressionException if the offset is invalid */ private static void validateOffset(int offset, int chunkSizeSoFar) { if (offset == 0) { throw new DecompressionException("Offset is less than minimum permissible value"); } if (offset < 0) { // Due to arithmetic overflow throw new DecompressionException("Offset is greater than maximum value supported by this implementation"); } if (offset > chunkSizeSoFar) { throw new DecompressionException("Offset exceeds size of chunk"); } } /** * Computes the CRC32C checksum of the supplied data and performs the "mask" operation * on the computed checksum * * @param data The input data to calculate the CRC32C checksum of */ static int calculateChecksum(ByteBuf data) { return calculateChecksum(data, data.readerIndex(), data.readableBytes()); } /** * Computes the CRC32C checksum of the supplied data and performs the "mask" operation * on the computed checksum * * @param data The input data to calculate the CRC32C checksum of */ static int calculateChecksum(ByteBuf data, int offset, int length) { Crc32c crc32 = new Crc32c(); try { crc32.update(data, offset, length); return maskChecksum((int) crc32.getValue()); } finally { crc32.reset(); } } /** * Computes the CRC32C checksum of the supplied data, performs the "mask" operation * on the computed checksum, and then compares the resulting masked checksum to the * supplied checksum. * * @param expectedChecksum The checksum decoded from the stream to compare against * @param data The input data to calculate the CRC32C checksum of * @throws DecompressionException If the calculated and supplied checksums do not match */ static void validateChecksum(int expectedChecksum, ByteBuf data) { validateChecksum(expectedChecksum, data, data.readerIndex(), data.readableBytes()); } /** * Computes the CRC32C checksum of the supplied data, performs the "mask" operation * on the computed checksum, and then compares the resulting masked checksum to the * supplied checksum. * * @param expectedChecksum The checksum decoded from the stream to compare against * @param data The input data to calculate the CRC32C checksum of * @throws DecompressionException If the calculated and supplied checksums do not match */ static void validateChecksum(int expectedChecksum, ByteBuf data, int offset, int length) { final int actualChecksum = calculateChecksum(data, offset, length); if (actualChecksum != expectedChecksum) { throw new DecompressionException( "mismatching checksum: " + Integer.toHexString(actualChecksum) + " (expected: " + Integer.toHexString(expectedChecksum) + ')'); } } /** * From the spec: * * "Checksums are not stored directly, but masked, as checksumming data and * then its own checksum can be problematic. The masking is the same as used * in Apache Hadoop: Rotate the checksum by 15 bits, then add the constant * 0xa282ead8 (using wraparound as normal for unsigned integers)." * * @param checksum The actual checksum of the data * @return The masked checksum */ static int maskChecksum(int checksum) { return (checksum >> 15 | checksum << 17) + 0xa282ead8; } }
bryce-anderson/netty
codec/src/main/java/io/netty/handler/codec/compression/Snappy.java
Java
apache-2.0
24,168
# Contributing to libchan Want to hack on libchan? Awesome! Here are instructions to get you started. libchan is a part of the [Docker](https://docker.io) project, and follows the same rules and principles. If you're already familiar with the way Docker does things, you'll feel right at home. Otherwise, go read [Docker's contributions guidelines](https://github.com/docker/docker/blob/master/CONTRIBUTING.md). Happy hacking!
docker/golem
vendor/github.com/docker/libchan/CONTRIBUTING.md
Markdown
apache-2.0
431