code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
/* Copyright (c) 2010-2011, Code Aurora Forum. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 and * only version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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 "vcd_ddl.h" #include "vcd_ddl_metadata.h" static u32 ddl_set_dec_property(struct ddl_client_context *pddl, struct vcd_property_hdr *property_hdr, void *property_value); static u32 ddl_set_enc_property(struct ddl_client_context *pddl, struct vcd_property_hdr *property_hdr, void *property_value); static u32 ddl_get_dec_property(struct ddl_client_context *pddl, struct vcd_property_hdr *property_hdr, void *property_value); static u32 ddl_get_enc_property(struct ddl_client_context *pddl, struct vcd_property_hdr *property_hdr, void *property_value); static u32 ddl_set_enc_dynamic_property(struct ddl_client_context *ddl, struct vcd_property_hdr *property_hdr, void *property_value); static void ddl_set_default_enc_property(struct ddl_client_context *ddl); static void ddl_set_default_enc_profile( struct ddl_encoder_data *encoder); static void ddl_set_default_enc_level(struct ddl_encoder_data *encoder); static void ddl_set_default_enc_vop_timing( struct ddl_encoder_data *encoder); static void ddl_set_default_enc_intra_period( struct ddl_encoder_data *encoder); static void ddl_set_default_enc_rc_params( struct ddl_encoder_data *encoder); static u32 ddl_valid_buffer_requirement( struct vcd_buffer_requirement *original_buf_req, struct vcd_buffer_requirement *req_buf_req); static u32 ddl_decoder_min_num_dpb(struct ddl_decoder_data *decoder); static u32 ddl_set_dec_buffers(struct ddl_decoder_data *decoder, struct ddl_property_dec_pic_buffers *dpb); u32 ddl_set_property(u32 *ddl_handle, struct vcd_property_hdr *property_hdr, void *property_value) { struct ddl_context *ddl_context; struct ddl_client_context *ddl = (struct ddl_client_context *) ddl_handle; u32 vcd_status; DDL_MSG_HIGH("ddl_set_property"); if (!property_hdr || !property_value) { DDL_MSG_ERROR("ddl_set_prop:Bad_argument"); return VCD_ERR_ILLEGAL_PARM; } ddl_context = ddl_get_context(); if (!DDL_IS_INITIALIZED(ddl_context)) { DDL_MSG_ERROR("ddl_set_prop:Not_inited"); return VCD_ERR_ILLEGAL_OP; } if (!ddl) { DDL_MSG_ERROR("ddl_set_prop:Bad_handle"); return VCD_ERR_BAD_HANDLE; } if (ddl->decoding) vcd_status = ddl_set_dec_property(ddl, property_hdr, property_value); else vcd_status = ddl_set_enc_property(ddl, property_hdr, property_value); if (vcd_status) DDL_MSG_ERROR("ddl_set_prop:FAILED"); return vcd_status; } u32 ddl_get_property(u32 *ddl_handle, struct vcd_property_hdr *property_hdr, void *property_value) { struct ddl_context *ddl_context; struct ddl_client_context *ddl = (struct ddl_client_context *) ddl_handle; u32 vcd_status = VCD_ERR_ILLEGAL_PARM; DDL_MSG_HIGH("ddl_get_property"); if (!property_hdr || !property_value) return VCD_ERR_ILLEGAL_PARM; if (property_hdr->prop_id == DDL_I_CAPABILITY) { if (sizeof(struct ddl_property_capability) == property_hdr->sz) { struct ddl_property_capability *ddl_capability = (struct ddl_property_capability *) property_value; ddl_capability->max_num_client = VCD_MAX_NO_CLIENT; ddl_capability->exclusive = VCD_COMMAND_EXCLUSIVE; ddl_capability->frame_command_depth = VCD_FRAME_COMMAND_DEPTH; ddl_capability->general_command_depth = VCD_GENEVIDC_COMMAND_DEPTH; ddl_capability->ddl_time_out_in_ms = DDL_HW_TIMEOUT_IN_MS; vcd_status = VCD_S_SUCCESS; } return vcd_status; } ddl_context = ddl_get_context(); if (!DDL_IS_INITIALIZED(ddl_context)) return VCD_ERR_ILLEGAL_OP; if (!ddl) return VCD_ERR_BAD_HANDLE; if (ddl->decoding) vcd_status = ddl_get_dec_property(ddl, property_hdr, property_value); else vcd_status = ddl_get_enc_property(ddl, property_hdr, property_value); if (vcd_status) DDL_MSG_ERROR("ddl_get_prop:FAILED"); else DDL_MSG_MED("ddl_get_prop:SUCCESS"); return vcd_status; } u32 ddl_decoder_ready_to_start(struct ddl_client_context *ddl, struct vcd_sequence_hdr *header) { struct ddl_decoder_data *decoder = &(ddl->codec_data.decoder); if (!decoder->codec.codec) { DDL_MSG_ERROR("ddl_dec_start_check:Codec_not_set"); return false; } if ((!header) && (!decoder->client_frame_size.height || !decoder->client_frame_size.width)) { DDL_MSG_ERROR("ddl_dec_start_check:" "Client_height_width_default"); return false; } return true; } u32 ddl_encoder_ready_to_start(struct ddl_client_context *ddl) { struct ddl_encoder_data *encoder = &(ddl->codec_data.encoder); if (!encoder->codec.codec || !encoder->frame_size.height || !encoder->frame_size.width || !encoder->frame_rate.fps_denominator || !encoder->frame_rate.fps_numerator || !encoder->target_bit_rate.target_bitrate) return false; if (encoder->frame_rate.fps_numerator > (encoder->frame_rate.fps_denominator * encoder->vop_timing.vop_time_resolution)) { DDL_MSG_ERROR("ResVsFrameRateFailed!"); return false; } if (encoder->profile.profile == VCD_PROFILE_H264_BASELINE && encoder->entropy_control.entropy_sel == VCD_ENTROPY_SEL_CABAC) { DDL_MSG_ERROR("H264BaseLineCABAC!!"); return false; } return true; } static u32 ddl_set_dec_property(struct ddl_client_context *ddl, struct vcd_property_hdr *property_hdr, void *property_value) { struct ddl_decoder_data *decoder = &(ddl->codec_data.decoder); u32 vcd_status = VCD_ERR_ILLEGAL_PARM ; switch (property_hdr->prop_id) { case DDL_I_DPB_RELEASE: if ((sizeof(struct ddl_frame_data_tag) == property_hdr->sz) && (decoder->dp_buf.no_of_dec_pic_buf)) vcd_status = ddl_decoder_dpb_transact(decoder, (struct ddl_frame_data_tag *) property_value, DDL_DPB_OP_MARK_FREE); break; case DDL_I_DPB: { struct ddl_property_dec_pic_buffers *dpb = (struct ddl_property_dec_pic_buffers *) property_value; if ((sizeof(struct ddl_property_dec_pic_buffers) == property_hdr->sz) && (DDLCLIENT_STATE_IS(ddl, DDL_CLIENT_WAIT_FOR_INITCODEC) || DDLCLIENT_STATE_IS(ddl, DDL_CLIENT_WAIT_FOR_DPB)) && (dpb->no_of_dec_pic_buf == decoder->client_output_buf_req.actual_count)) vcd_status = ddl_set_dec_buffers(decoder, dpb); } break; case DDL_I_REQ_OUTPUT_FLUSH: if (sizeof(u32) == property_hdr->sz) { decoder->dynamic_prop_change |= DDL_DEC_REQ_OUTPUT_FLUSH; decoder->dpb_mask.client_mask = 0; vcd_status = VCD_S_SUCCESS; } break; case DDL_I_INPUT_BUF_REQ: { struct vcd_buffer_requirement *buffer_req = (struct vcd_buffer_requirement *)property_value; if (sizeof(struct vcd_buffer_requirement) == property_hdr->sz && (DDLCLIENT_STATE_IS(ddl, DDL_CLIENT_WAIT_FOR_INITCODEC) || DDLCLIENT_STATE_IS(ddl, DDL_CLIENT_WAIT_FOR_DPB) || DDLCLIENT_STATE_IS(ddl, DDL_CLIENT_OPEN)) && (ddl_valid_buffer_requirement( &decoder->min_input_buf_req, buffer_req))) { decoder->client_input_buf_req = *buffer_req; vcd_status = VCD_S_SUCCESS; } } break; case DDL_I_OUTPUT_BUF_REQ: { struct vcd_buffer_requirement *buffer_req = (struct vcd_buffer_requirement *)property_value; if (sizeof(struct vcd_buffer_requirement) == property_hdr->sz && (DDLCLIENT_STATE_IS(ddl, DDL_CLIENT_WAIT_FOR_INITCODEC) || DDLCLIENT_STATE_IS(ddl, DDL_CLIENT_WAIT_FOR_DPB) || DDLCLIENT_STATE_IS(ddl, DDL_CLIENT_OPEN)) && (ddl_valid_buffer_requirement( &decoder->min_output_buf_req, buffer_req))) { decoder->client_output_buf_req = *buffer_req; vcd_status = VCD_S_SUCCESS; } } break; case VCD_I_CODEC: { struct vcd_property_codec *codec = (struct vcd_property_codec *)property_value; if (sizeof(struct vcd_property_codec) == property_hdr->sz && DDLCLIENT_STATE_IS(ddl, DDL_CLIENT_OPEN) && ddl_codec_type_transact(ddl, false, codec->codec)) { if (decoder->codec.codec != codec->codec) { decoder->codec = *codec; ddl_set_default_dec_property(ddl); } vcd_status = VCD_S_SUCCESS; } } break; case VCD_I_POST_FILTER: if (sizeof(struct vcd_property_post_filter) == property_hdr->sz && DDLCLIENT_STATE_IS(ddl, DDL_CLIENT_OPEN) && ( decoder->codec.codec == VCD_CODEC_MPEG4 || decoder->codec.codec == VCD_CODEC_MPEG2)) { decoder->post_filter = *(struct vcd_property_post_filter *) property_value; vcd_status = VCD_S_SUCCESS; } break; case VCD_I_FRAME_SIZE: { struct vcd_property_frame_size *frame_size = (struct vcd_property_frame_size *) property_value; if ((sizeof(struct vcd_property_frame_size) == property_hdr->sz) && (DDLCLIENT_STATE_IS(ddl, DDL_CLIENT_OPEN)) && (DDL_ALLOW_DEC_FRAMESIZE(frame_size->width, frame_size->height))) { if (decoder->client_frame_size.height != frame_size->height || decoder->client_frame_size.width != frame_size->width) { decoder->client_frame_size = *frame_size; ddl_set_default_decoder_buffer_req(decoder, true); } vcd_status = VCD_S_SUCCESS; } } break; case VCD_I_BUFFER_FORMAT: { struct vcd_property_buffer_format *tile = (struct vcd_property_buffer_format *) property_value; if (sizeof(struct vcd_property_buffer_format) == property_hdr->sz && DDLCLIENT_STATE_IS(ddl, DDL_CLIENT_OPEN) && tile->buffer_format == VCD_BUFFER_FORMAT_TILE_4x2) { if (tile->buffer_format != decoder->buf_format.buffer_format) { decoder->buf_format = *tile; ddl_set_default_decoder_buffer_req( decoder, true); } vcd_status = VCD_S_SUCCESS; } } break; case VCD_I_H264_MV_BUFFER: { int index, buffer_size; u8 *phys_addr; u8 *virt_addr; struct vcd_property_h264_mv_buffer *mv_buff = (struct vcd_property_h264_mv_buffer *) property_value; DDL_MSG_LOW("Entered VCD_I_H264_MV_BUFFER Virt: %p, Phys %p," "fd: %d size: %d count: %d\n", mv_buff->kernel_virtual_addr, mv_buff->physical_addr, mv_buff->pmem_fd, mv_buff->size, mv_buff->count); if ((property_hdr->sz == sizeof(struct vcd_property_h264_mv_buffer)) && (DDLCLIENT_STATE_IS(ddl, DDL_CLIENT_WAIT_FOR_INITCODEC) || DDLCLIENT_STATE_IS(ddl, DDL_CLIENT_WAIT_FOR_DPB) || DDLCLIENT_STATE_IS(ddl, DDL_CLIENT_OPEN))) { phys_addr = mv_buff->physical_addr; virt_addr = mv_buff->kernel_virtual_addr; buffer_size = mv_buff->size/mv_buff->count; for (index = 0; index < mv_buff->count; index++) { ddl->codec_data.decoder.hw_bufs. h264_mv[index].align_physical_addr = phys_addr; ddl->codec_data.decoder.hw_bufs. h264_mv[index].align_virtual_addr = virt_addr; ddl->codec_data.decoder.hw_bufs. h264_mv[index].buffer_size = buffer_size; ddl->codec_data.decoder.hw_bufs. h264_mv[index].physical_base_addr = phys_addr; ddl->codec_data.decoder.hw_bufs. h264_mv[index].virtual_base_addr = virt_addr; DDL_MSG_LOW("Assigned %d buffer for " "virt: %p, phys %p for " "h264_mv_buffers " "of size: %d\n", index, virt_addr, phys_addr, buffer_size); phys_addr += buffer_size; virt_addr += buffer_size; } vcd_status = VCD_S_SUCCESS; } } break; case VCD_I_FREE_H264_MV_BUFFER: { memset(&decoder->hw_bufs.h264_mv, 0, sizeof(struct ddl_buf_addr) * DDL_MAX_BUFFER_COUNT); vcd_status = VCD_S_SUCCESS; } break; case VCD_I_OUTPUT_ORDER: { if (sizeof(u32) == property_hdr->sz && DDLCLIENT_STATE_IS(ddl, DDL_CLIENT_OPEN)) { decoder->output_order = *(u32 *)property_value; vcd_status = VCD_S_SUCCESS; } } break; case VCD_I_DEC_PICTYPE: { if ((sizeof(u32) == property_hdr->sz) && DDLCLIENT_STATE_IS(ddl, DDL_CLIENT_OPEN)) { decoder->idr_only_decoding = *(u32 *)property_value; ddl_set_default_decoder_buffer_req( decoder, true); vcd_status = VCD_S_SUCCESS; } } break; case VCD_I_METADATA_ENABLE: case VCD_I_METADATA_HEADER: DDL_MSG_MED("Meta Data Interface is Requested"); vcd_status = ddl_set_metadata_params(ddl, property_hdr, property_value); vcd_status = VCD_S_SUCCESS; break; case VCD_I_FRAME_RATE: vcd_status = VCD_S_SUCCESS; break; case VCD_I_CONT_ON_RECONFIG: { DDL_MSG_LOW("Set property VCD_I_CONT_ON_RECONFIG\n"); if (sizeof(u32) == property_hdr->sz && DDLCLIENT_STATE_IS(ddl, DDL_CLIENT_OPEN)) { decoder->cont_mode = *(u32 *)property_value; vcd_status = VCD_S_SUCCESS; } } break; default: vcd_status = VCD_ERR_ILLEGAL_OP; break; } return vcd_status; } static u32 ddl_check_valid_enc_level(struct vcd_property_codec *codec, struct vcd_property_profile *profile, struct vcd_property_level *level) { u32 status = false; if (codec && profile && level) { switch (codec->codec) { case VCD_CODEC_MPEG4: status = (profile->profile == VCD_PROFILE_MPEG4_SP) && (level->level >= VCD_LEVEL_MPEG4_0) && (level->level <= VCD_LEVEL_MPEG4_6) && (VCD_LEVEL_MPEG4_3b != level->level); status = status || ((profile->profile == VCD_PROFILE_MPEG4_ASP) && (level->level >= VCD_LEVEL_MPEG4_0) && (level->level <= VCD_LEVEL_MPEG4_5)); break; case VCD_CODEC_H264: status = (level->level >= VCD_LEVEL_H264_1) && (level->level <= VCD_LEVEL_H264_4); break; case VCD_CODEC_H263: status = (level->level >= VCD_LEVEL_H263_10) && (level->level <= VCD_LEVEL_H263_70); break; default: break; } } return status; } static u32 ddl_set_enc_property(struct ddl_client_context *ddl, struct vcd_property_hdr *property_hdr, void *property_value) { struct ddl_encoder_data *encoder = &(ddl->codec_data.encoder); u32 vcd_status = VCD_ERR_ILLEGAL_PARM; if (DDLCLIENT_STATE_IS(ddl, DDL_CLIENT_WAIT_FOR_FRAME) || DDLCLIENT_STATE_IS(ddl, DDL_CLIENT_WAIT_FOR_FRAME_DONE) || DDLCLIENT_STATE_IS(ddl, DDL_CLIENT_OPEN)) { vcd_status = ddl_set_enc_dynamic_property(ddl, property_hdr, property_value); } if (vcd_status) { if (!DDLCLIENT_STATE_IS(ddl, DDL_CLIENT_OPEN) || vcd_status != VCD_ERR_ILLEGAL_OP) { DDL_MSG_ERROR("ddl_set_enc_property:" "Fails_as_not_in_open_state"); return VCD_ERR_ILLEGAL_OP; } } else return vcd_status; switch (property_hdr->prop_id) { case VCD_I_FRAME_SIZE: { struct vcd_property_frame_size *frame_size = (struct vcd_property_frame_size *) property_value; if ((sizeof(struct vcd_property_frame_size) == property_hdr->sz) && (DDL_ALLOW_ENC_FRAMESIZE(frame_size->width, frame_size->height))) { if (encoder->frame_size.height != frame_size->height || encoder->frame_size.width != frame_size->width) { ddl_calculate_stride(frame_size, false); encoder->frame_size = *frame_size; ddl_set_default_encoder_buffer_req(encoder); } vcd_status = VCD_S_SUCCESS; } } break; case VCD_I_CODEC: { struct vcd_property_codec *codec = (struct vcd_property_codec *) property_value; if ((sizeof(struct vcd_property_codec) == property_hdr->sz) && (ddl_codec_type_transact(ddl, false, codec->codec))) { if (codec->codec != encoder->codec.codec) { encoder->codec = *codec; ddl_set_default_enc_property(ddl); } vcd_status = VCD_S_SUCCESS; } } break; case VCD_I_REQ_IFRAME: vcd_status = VCD_S_SUCCESS; break; case VCD_I_INTRA_PERIOD: { struct vcd_property_i_period *i_period = (struct vcd_property_i_period *)property_value; if (sizeof(struct vcd_property_i_period) == property_hdr->sz && i_period->b_frames <= DDL_MAX_NUM_OF_B_FRAME) { encoder->i_period = *i_period; encoder->client_input_buf_req.min_count = i_period->b_frames + 1; encoder->client_input_buf_req.actual_count = DDL_MAX(encoder->client_input_buf_req.\ actual_count, encoder->\ client_input_buf_req.min_count); encoder->client_output_buf_req.min_count = i_period->b_frames + 2; encoder->client_output_buf_req.actual_count = DDL_MAX(encoder->client_output_buf_req.\ actual_count, encoder->\ client_output_buf_req.min_count); ddl->extra_output_buf_count = i_period->b_frames - 1; vcd_status = VCD_S_SUCCESS; } } break; case VCD_I_PROFILE: { struct vcd_property_profile *profile = (struct vcd_property_profile *)property_value; if ((sizeof(struct vcd_property_profile) == property_hdr->sz) && (( (encoder->codec.codec == VCD_CODEC_MPEG4) && ( profile->profile == VCD_PROFILE_MPEG4_SP || profile->profile == VCD_PROFILE_MPEG4_ASP)) || ((encoder->codec.codec == VCD_CODEC_H264) && (profile->profile >= VCD_PROFILE_H264_BASELINE) && (profile->profile <= VCD_PROFILE_H264_HIGH)) || ((encoder->codec.codec == VCD_CODEC_H263) && (profile->profile == VCD_PROFILE_H263_BASELINE)))) { encoder->profile = *profile; vcd_status = VCD_S_SUCCESS; if (profile->profile == VCD_PROFILE_H264_BASELINE) encoder->entropy_control.entropy_sel = VCD_ENTROPY_SEL_CAVLC; else encoder->entropy_control.entropy_sel = VCD_ENTROPY_SEL_CABAC; } } break; case VCD_I_LEVEL: { struct vcd_property_level *level = (struct vcd_property_level *) property_value; if ((sizeof(struct vcd_property_level) == property_hdr->sz) && (ddl_check_valid_enc_level (&encoder->codec, &encoder->profile, level))) { encoder->level = *level; vcd_status = VCD_S_SUCCESS; } } break; case VCD_I_MULTI_SLICE: { struct vcd_property_multi_slice *multi_slice = (struct vcd_property_multi_slice *) property_value; switch (multi_slice->m_slice_sel) { case VCD_MSLICE_OFF: vcd_status = VCD_S_SUCCESS; break; case VCD_MSLICE_BY_GOB: if (encoder->codec.codec == VCD_CODEC_H263) vcd_status = VCD_S_SUCCESS; break; case VCD_MSLICE_BY_MB_COUNT: if (multi_slice->m_slice_size >= 1 && (multi_slice->m_slice_size <= DDL_NO_OF_MB(encoder->frame_size.width, encoder->frame_size.height))) vcd_status = VCD_S_SUCCESS; break; case VCD_MSLICE_BY_BYTE_COUNT: if (multi_slice->m_slice_size > 0) vcd_status = VCD_S_SUCCESS; break; default: break; } if (sizeof(struct vcd_property_multi_slice) == property_hdr->sz && !vcd_status) { encoder->multi_slice = *multi_slice; if (multi_slice->m_slice_sel == VCD_MSLICE_OFF) encoder->multi_slice.m_slice_size = 0; } } break; case VCD_I_RATE_CONTROL: { struct vcd_property_rate_control *rate_control = (struct vcd_property_rate_control *) property_value; if (sizeof(struct vcd_property_rate_control) == property_hdr->sz && rate_control->rate_control >= VCD_RATE_CONTROL_OFF && rate_control->rate_control <= VCD_RATE_CONTROL_CBR_CFR) { encoder->rc = *rate_control; ddl_set_default_enc_rc_params(encoder); vcd_status = VCD_S_SUCCESS; } } break; case VCD_I_SHORT_HEADER: if (sizeof(struct vcd_property_short_header) == property_hdr->sz && encoder->codec.codec == VCD_CODEC_MPEG4) { encoder->short_header = *(struct vcd_property_short_header *) property_value; vcd_status = VCD_S_SUCCESS; } break; case VCD_I_VOP_TIMING: { struct vcd_property_vop_timing *vop_time = (struct vcd_property_vop_timing *) property_value; if ((sizeof(struct vcd_property_vop_timing) == property_hdr->sz) && (encoder->frame_rate.fps_numerator <= vop_time->vop_time_resolution) && (encoder->codec.codec == VCD_CODEC_MPEG4)) { encoder->vop_timing = *vop_time; vcd_status = VCD_S_SUCCESS; } } break; case VCD_I_HEADER_EXTENSION: if (sizeof(u32) == property_hdr->sz && encoder->codec.codec == VCD_CODEC_MPEG4) { encoder->hdr_ext_control = *(u32 *)property_value; vcd_status = VCD_S_SUCCESS; } break; case VCD_I_ENTROPY_CTRL: { struct vcd_property_entropy_control *entropy_control = (struct vcd_property_entropy_control *) property_value; if (sizeof(struct vcd_property_entropy_control) == property_hdr->sz && encoder->codec.codec == VCD_CODEC_H264 && entropy_control->entropy_sel >= VCD_ENTROPY_SEL_CAVLC && entropy_control->entropy_sel <= VCD_ENTROPY_SEL_CABAC) { if ((entropy_control->entropy_sel == VCD_ENTROPY_SEL_CABAC) && (encoder->entropy_control.cabac_model == VCD_CABAC_MODEL_NUMBER_1 || encoder->entropy_control.cabac_model == VCD_CABAC_MODEL_NUMBER_2)) { vcd_status = VCD_ERR_ILLEGAL_PARM; } else { encoder->entropy_control = *entropy_control; vcd_status = VCD_S_SUCCESS; } } } break; case VCD_I_DEBLOCKING: { struct vcd_property_db_config *db_config = (struct vcd_property_db_config *) property_value; if (sizeof(struct vcd_property_db_config) == property_hdr->sz && encoder->codec.codec == VCD_CODEC_H264 && db_config->db_config >= VCD_DB_ALL_BLOCKING_BOUNDARY && db_config->db_config <= VCD_DB_SKIP_SLICE_BOUNDARY) { encoder->db_control = *db_config; vcd_status = VCD_S_SUCCESS; } } break; case VCD_I_QP_RANGE: { struct vcd_property_qp_range *qp = (struct vcd_property_qp_range *)property_value; if ((sizeof(struct vcd_property_qp_range) == property_hdr->sz) && (qp->min_qp <= qp->max_qp) && ((encoder->codec.codec == VCD_CODEC_H264 && qp->max_qp <= DDL_MAX_H264_QP) || (qp->max_qp <= DDL_MAX_MPEG4_QP))) { encoder->qp_range = *qp; vcd_status = VCD_S_SUCCESS; } } break; case VCD_I_SESSION_QP: { struct vcd_property_session_qp *qp = (struct vcd_property_session_qp *)property_value; if ((sizeof(struct vcd_property_session_qp) == property_hdr->sz) && (qp->i_frame_qp >= encoder->qp_range.min_qp) && (qp->i_frame_qp <= encoder->qp_range.max_qp) && (qp->p_frame_qp >= encoder->qp_range.min_qp) && (qp->p_frame_qp <= encoder->qp_range.max_qp)) { encoder->session_qp = *qp; vcd_status = VCD_S_SUCCESS; } } break; case VCD_I_RC_LEVEL_CONFIG: { struct vcd_property_rc_level *rc_level = (struct vcd_property_rc_level *) property_value; if (sizeof(struct vcd_property_rc_level) == property_hdr->sz && (encoder->rc.rate_control >= VCD_RATE_CONTROL_VBR_VFR || encoder->rc.rate_control <= VCD_RATE_CONTROL_CBR_VFR) && (!rc_level->mb_level_rc || encoder->codec.codec == VCD_CODEC_H264)) { encoder->rc_level = *rc_level; vcd_status = VCD_S_SUCCESS; } } break; case VCD_I_FRAME_LEVEL_RC: { struct vcd_property_frame_level_rc_params *frame_level_rc = (struct vcd_property_frame_level_rc_params *) property_value; if ((sizeof(struct vcd_property_frame_level_rc_params) == property_hdr->sz) && (frame_level_rc->reaction_coeff) && (encoder->rc_level.frame_level_rc)) { encoder->frame_level_rc = *frame_level_rc; vcd_status = VCD_S_SUCCESS; } } break; case VCD_I_ADAPTIVE_RC: if ((sizeof(struct vcd_property_adaptive_rc_params) == property_hdr->sz) && (encoder->codec.codec == VCD_CODEC_H264) && (encoder->rc_level.mb_level_rc)) { encoder->adaptive_rc = *(struct vcd_property_adaptive_rc_params *) property_value; vcd_status = VCD_S_SUCCESS; } break; case VCD_I_BUFFER_FORMAT: { struct vcd_property_buffer_format *buffer_format = (struct vcd_property_buffer_format *) property_value; if (sizeof(struct vcd_property_buffer_format) == property_hdr->sz && ((buffer_format->buffer_format == VCD_BUFFER_FORMAT_NV12_16M2KA) || (VCD_BUFFER_FORMAT_TILE_4x2 == buffer_format->buffer_format))) { if (buffer_format->buffer_format != encoder->buf_format.buffer_format) { encoder->buf_format = *buffer_format; ddl_set_default_encoder_buffer_req(encoder); } vcd_status = VCD_S_SUCCESS; } } break; case DDL_I_INPUT_BUF_REQ: { struct vcd_buffer_requirement *buffer_req = (struct vcd_buffer_requirement *)property_value; if (sizeof(struct vcd_buffer_requirement) == property_hdr->sz && (ddl_valid_buffer_requirement( &encoder->input_buf_req, buffer_req))) { encoder->client_input_buf_req = *buffer_req; vcd_status = VCD_S_SUCCESS; } } break; case DDL_I_OUTPUT_BUF_REQ: { struct vcd_buffer_requirement *buffer_req = (struct vcd_buffer_requirement *)property_value; if (sizeof(struct vcd_buffer_requirement) == property_hdr->sz && (ddl_valid_buffer_requirement( &encoder->output_buf_req, buffer_req))) { encoder->client_output_buf_req = *buffer_req; encoder->client_output_buf_req.sz = DDL_ALIGN(buffer_req->sz, DDL_KILO_BYTE(4)); vcd_status = VCD_S_SUCCESS; } } break; case VCD_I_RECON_BUFFERS: { int index; struct vcd_property_enc_recon_buffer *recon_buffers = (struct vcd_property_enc_recon_buffer *)property_value; for (index = 0; index < 4; index++) { if (!encoder->hw_bufs.dpb_y[index].align_physical_addr) break; else continue; } if (property_hdr->sz == sizeof(struct vcd_property_enc_recon_buffer)) { encoder->hw_bufs.dpb_y[index].align_physical_addr = recon_buffers->physical_addr; encoder->hw_bufs.dpb_y[index].align_virtual_addr = recon_buffers->kernel_virtual_addr; encoder->hw_bufs.dpb_y[index].buffer_size = recon_buffers->buffer_size; encoder->hw_bufs.dpb_c[index].align_physical_addr = recon_buffers->physical_addr + ddl_get_yuv_buf_size( encoder->frame_size.width, encoder->frame_size. height, DDL_YUV_BUF_TYPE_TILE); encoder->hw_bufs.dpb_c[index].align_virtual_addr = recon_buffers->kernel_virtual_addr + recon_buffers->ysize; DDL_MSG_LOW("Y::KVirt: %p,KPhys: %p" "UV::KVirt: %p,KPhys: %p\n", encoder->hw_bufs.dpb_y[index].align_virtual_addr, encoder->hw_bufs.dpb_y[index].align_physical_addr, encoder->hw_bufs.dpb_c[index].align_virtual_addr, encoder->hw_bufs.dpb_c[index].align_physical_addr); vcd_status = VCD_S_SUCCESS; } } break; case VCD_I_FREE_RECON_BUFFERS: { memset(&encoder->hw_bufs.dpb_y, 0, sizeof(struct ddl_buf_addr) * 4); memset(&encoder->hw_bufs.dpb_c, 0, sizeof(struct ddl_buf_addr) * 4); vcd_status = VCD_S_SUCCESS; break; } case VCD_I_METADATA_ENABLE: case VCD_I_METADATA_HEADER: DDL_MSG_ERROR("Meta Data Interface is Requested"); vcd_status = ddl_set_metadata_params(ddl, property_hdr, property_value); vcd_status = VCD_S_SUCCESS; break; default: DDL_MSG_ERROR("INVALID ID %d\n", (int)property_hdr->prop_id); vcd_status = VCD_ERR_ILLEGAL_OP; break; } return vcd_status; } static u32 ddl_get_dec_property(struct ddl_client_context *ddl, struct vcd_property_hdr *property_hdr, void *property_value) { struct ddl_decoder_data *decoder = &ddl->codec_data.decoder; struct vcd_property_frame_size *fz_size; u32 vcd_status = VCD_ERR_ILLEGAL_PARM; DDL_MSG_HIGH("property_hdr->prop_id:%x\n", property_hdr->prop_id); switch (property_hdr->prop_id) { case VCD_I_FRAME_SIZE: if (sizeof(struct vcd_property_frame_size) == property_hdr->sz) { ddl_calculate_stride(&decoder->client_frame_size, !decoder->progressive_only); fz_size = &decoder->client_frame_size; fz_size->stride = DDL_TILE_ALIGN(fz_size->width, DDL_TILE_ALIGN_WIDTH); fz_size->scan_lines = DDL_TILE_ALIGN(fz_size->height, DDL_TILE_ALIGN_HEIGHT); *(struct vcd_property_frame_size *) property_value = decoder->client_frame_size; vcd_status = VCD_S_SUCCESS; } break; case VCD_I_PROFILE: if (sizeof(struct vcd_property_profile) == property_hdr->sz) { *(struct vcd_property_profile *)property_value = decoder->profile; vcd_status = VCD_S_SUCCESS; } break; case VCD_I_LEVEL: if (sizeof(struct vcd_property_level) == property_hdr->sz) { *(struct vcd_property_level *)property_value = decoder->level; vcd_status = VCD_S_SUCCESS; } break; case VCD_I_PROGRESSIVE_ONLY: if (sizeof(u32) == property_hdr->sz) { *(u32 *)property_value = decoder->progressive_only; vcd_status = VCD_S_SUCCESS; } break; case DDL_I_INPUT_BUF_REQ: if (sizeof(struct vcd_buffer_requirement) == property_hdr->sz) { *(struct vcd_buffer_requirement *) property_value = decoder->client_input_buf_req; vcd_status = VCD_S_SUCCESS; } break; case DDL_I_OUTPUT_BUF_REQ: if (sizeof(struct vcd_buffer_requirement) == property_hdr->sz) { *(struct vcd_buffer_requirement *) property_value = decoder->client_output_buf_req; vcd_status = VCD_S_SUCCESS; } break; case VCD_I_CODEC: if (sizeof(struct vcd_property_codec) == property_hdr->sz) { *(struct vcd_property_codec *) property_value = decoder->codec; vcd_status = VCD_S_SUCCESS; } break; case VCD_I_BUFFER_FORMAT: if (sizeof(struct vcd_property_buffer_format) == property_hdr->sz) { *(struct vcd_property_buffer_format *) property_value = decoder->buf_format; vcd_status = VCD_S_SUCCESS; } break; case VCD_I_POST_FILTER: if (sizeof(struct vcd_property_post_filter) == property_hdr->sz) { *(struct vcd_property_post_filter *) property_value = decoder->post_filter; vcd_status = VCD_S_SUCCESS; } break; case DDL_I_SEQHDR_ALIGN_BYTES: if (sizeof(u32) == property_hdr->sz) { *(u32 *)property_value = DDL_LINEAR_BUFFER_ALIGN_BYTES; vcd_status = VCD_S_SUCCESS; } break; case DDL_I_FRAME_PROC_UNITS: if (sizeof(u32) == property_hdr->sz) { if (!decoder->progressive_only && (decoder->client_frame_size.width * decoder->client_frame_size.height) <= DDL_FRAME_VGA_SIZE) { *(u32 *) property_value = DDL_NO_OF_MB( DDL_FRAME_720P_WIDTH, DDL_FRAME_720P_HEIGHT); } else { *(u32 *) property_value = DDL_NO_OF_MB( decoder->client_frame_size.width, decoder->client_frame_size.height); } vcd_status = VCD_S_SUCCESS; } break; case DDL_I_DPB_RETRIEVE: if (sizeof(struct ddl_frame_data_tag) == property_hdr->sz) { vcd_status = ddl_decoder_dpb_transact(decoder, (struct ddl_frame_data_tag *) property_value, DDL_DPB_OP_RETRIEVE); } break; case VCD_I_GET_H264_MV_SIZE: if (property_hdr->sz == sizeof(struct vcd_property_buffer_size)) { struct vcd_property_buffer_size *mv_size = (struct vcd_property_buffer_size *) property_value; mv_size->size = ddl_get_yuv_buf_size(mv_size->width, mv_size->height, DDL_YUV_BUF_TYPE_TILE); mv_size->alignment = DDL_TILE_BUFFER_ALIGN_BYTES; DDL_MSG_LOW("w: %d, h: %d, S: %d, " "A: %d", mv_size->width, mv_size->height, mv_size->size, mv_size->alignment); vcd_status = VCD_S_SUCCESS; } break; case VCD_I_OUTPUT_ORDER: { if (sizeof(u32) == property_hdr->sz) { *(u32 *)property_value = decoder->output_order; vcd_status = VCD_S_SUCCESS; } } break; case VCD_I_METADATA_ENABLE: case VCD_I_METADATA_HEADER: DDL_MSG_ERROR("Meta Data Interface is Requested"); vcd_status = ddl_get_metadata_params(ddl, property_hdr, property_value); vcd_status = VCD_S_SUCCESS; break; case VCD_I_CONT_ON_RECONFIG: if (sizeof(u32) == property_hdr->sz) { *(u32 *)property_value = decoder->cont_mode; vcd_status = VCD_S_SUCCESS; } break; default: vcd_status = VCD_ERR_ILLEGAL_OP; break; } return vcd_status; } static u32 ddl_get_enc_property(struct ddl_client_context *ddl, struct vcd_property_hdr *property_hdr, void *property_value) { struct ddl_encoder_data *encoder = &ddl->codec_data.encoder; u32 vcd_status = VCD_ERR_ILLEGAL_PARM; switch (property_hdr->prop_id) { case VCD_I_CODEC: if (sizeof(struct vcd_property_codec) == property_hdr->sz) { *(struct vcd_property_codec *) property_value = encoder->codec; vcd_status = VCD_S_SUCCESS; } break; case VCD_I_FRAME_SIZE: if (sizeof(struct vcd_property_frame_size) == property_hdr->sz) { *(struct vcd_property_frame_size *) property_value = encoder->frame_size; vcd_status = VCD_S_SUCCESS; } break; case VCD_I_FRAME_RATE: if (sizeof(struct vcd_property_frame_rate) == property_hdr->sz) { *(struct vcd_property_frame_rate *) property_value = encoder->frame_rate; vcd_status = VCD_S_SUCCESS; } break; case VCD_I_TARGET_BITRATE: if (sizeof(struct vcd_property_target_bitrate) == property_hdr->sz) { *(struct vcd_property_target_bitrate *) property_value = encoder->target_bit_rate; vcd_status = VCD_S_SUCCESS; } break; case VCD_I_RATE_CONTROL: if (sizeof(struct vcd_property_rate_control) == property_hdr->sz) { *(struct vcd_property_rate_control *) property_value = encoder->rc; vcd_status = VCD_S_SUCCESS; } break; case VCD_I_PROFILE: if (sizeof(struct vcd_property_profile) == property_hdr->sz) { *(struct vcd_property_profile *) property_value = encoder->profile; vcd_status = VCD_S_SUCCESS; } break; case VCD_I_LEVEL: if (sizeof(struct vcd_property_level) == property_hdr->sz) { *(struct vcd_property_level *) property_value = encoder->level; vcd_status = VCD_S_SUCCESS; } break; case VCD_I_MULTI_SLICE: if (sizeof(struct vcd_property_multi_slice) == property_hdr->sz) { *(struct vcd_property_multi_slice *) property_value = encoder->multi_slice; vcd_status = VCD_S_SUCCESS; } break; case VCD_I_SEQ_HEADER: { struct vcd_sequence_hdr *seq_hdr = (struct vcd_sequence_hdr *) property_value; if (!encoder->seq_header_length) { seq_hdr->sequence_header_len = encoder->seq_header_length; vcd_status = VCD_ERR_NO_SEQ_HDR; } else if (sizeof(struct vcd_sequence_hdr) == property_hdr->sz && encoder->seq_header_length <= seq_hdr->sequence_header_len) { memcpy(seq_hdr->sequence_header, encoder->seq_header.align_virtual_addr, encoder->seq_header_length); seq_hdr->sequence_header_len = encoder->seq_header_length; vcd_status = VCD_S_SUCCESS; } } break; case DDL_I_SEQHDR_PRESENT: if (sizeof(u32) == property_hdr->sz) { if ((encoder->codec.codec == VCD_CODEC_MPEG4 && !encoder->short_header.short_header) || encoder->codec.codec == VCD_CODEC_H264) *(u32 *) property_value = 0x1; else *(u32 *) property_value = 0x0; vcd_status = VCD_S_SUCCESS; } break; case VCD_I_VOP_TIMING: if (sizeof(struct vcd_property_vop_timing) == property_hdr->sz) { *(struct vcd_property_vop_timing *) property_value = encoder->vop_timing; vcd_status = VCD_S_SUCCESS; } break; case VCD_I_SHORT_HEADER: if (sizeof(struct vcd_property_short_header) == property_hdr->sz) { if (encoder->codec.codec == VCD_CODEC_MPEG4) { *(struct vcd_property_short_header *) property_value = encoder->short_header; vcd_status = VCD_S_SUCCESS; } else vcd_status = VCD_ERR_ILLEGAL_OP; } break; case VCD_I_ENTROPY_CTRL: if (sizeof(struct vcd_property_entropy_control) == property_hdr->sz) { if (encoder->codec.codec == VCD_CODEC_H264) { *(struct vcd_property_entropy_control *) property_value = encoder->entropy_control; vcd_status = VCD_S_SUCCESS; } else vcd_status = VCD_ERR_ILLEGAL_OP; } break; case VCD_I_DEBLOCKING: if (sizeof(struct vcd_property_db_config) == property_hdr->sz) { if (encoder->codec.codec == VCD_CODEC_H264) { *(struct vcd_property_db_config *) property_value = encoder->db_control; vcd_status = VCD_S_SUCCESS; } else vcd_status = VCD_ERR_ILLEGAL_OP; } break; case VCD_I_INTRA_PERIOD: if (sizeof(struct vcd_property_i_period) == property_hdr->sz) { *(struct vcd_property_i_period *) property_value = encoder->i_period; vcd_status = VCD_S_SUCCESS; } break; case VCD_I_QP_RANGE: if (sizeof(struct vcd_property_qp_range) == property_hdr->sz) { *(struct vcd_property_qp_range *) property_value = encoder->qp_range; vcd_status = VCD_S_SUCCESS; } break; case VCD_I_SESSION_QP: if (sizeof(struct vcd_property_session_qp) == property_hdr->sz) { *(struct vcd_property_session_qp *) property_value = encoder->session_qp; vcd_status = VCD_S_SUCCESS; } break; case VCD_I_RC_LEVEL_CONFIG: if (sizeof(struct vcd_property_rc_level) == property_hdr->sz) { *(struct vcd_property_rc_level *) property_value = encoder->rc_level; vcd_status = VCD_S_SUCCESS; } break; case VCD_I_FRAME_LEVEL_RC: if (sizeof(struct vcd_property_frame_level_rc_params) == property_hdr->sz) { *(struct vcd_property_frame_level_rc_params *) property_value = encoder->frame_level_rc; vcd_status = VCD_S_SUCCESS; } break; case VCD_I_ADAPTIVE_RC: if (sizeof(struct vcd_property_adaptive_rc_params) == property_hdr->sz) { *(struct vcd_property_adaptive_rc_params *) property_value = encoder->adaptive_rc; vcd_status = VCD_S_SUCCESS; } break; case VCD_I_INTRA_REFRESH: if (sizeof(struct vcd_property_intra_refresh_mb_number) == property_hdr->sz) { *(struct vcd_property_intra_refresh_mb_number *) property_value = encoder->intra_refresh; vcd_status = VCD_S_SUCCESS; } break; case DDL_I_INPUT_BUF_REQ: if (sizeof(struct vcd_buffer_requirement) == property_hdr->sz) { *(struct vcd_buffer_requirement *) property_value = encoder->client_input_buf_req; vcd_status = VCD_S_SUCCESS; } break; case DDL_I_OUTPUT_BUF_REQ: if (sizeof(struct vcd_buffer_requirement) == property_hdr->sz) { *(struct vcd_buffer_requirement *) property_value = encoder->client_output_buf_req; vcd_status = VCD_S_SUCCESS; } break; case VCD_I_BUFFER_FORMAT: if (sizeof(struct vcd_property_buffer_format) == property_hdr->sz) { *(struct vcd_property_buffer_format *) property_value = encoder->buf_format; vcd_status = VCD_S_SUCCESS; } break; case DDL_I_FRAME_PROC_UNITS: if (sizeof(u32) == property_hdr->sz && encoder->frame_size.width && encoder->frame_size.height) { *(u32 *)property_value = DDL_NO_OF_MB( encoder->frame_size.width, encoder->frame_size.height); vcd_status = VCD_S_SUCCESS; } break; case VCD_I_HEADER_EXTENSION: if (sizeof(u32) == property_hdr->sz && encoder->codec.codec == VCD_CODEC_MPEG4) { *(u32 *) property_value = encoder->hdr_ext_control; vcd_status = VCD_S_SUCCESS; } break; case VCD_I_GET_RECON_BUFFER_SIZE: { u32 ysize, uvsize; if (property_hdr->sz == sizeof(struct vcd_property_buffer_size)) { struct vcd_property_buffer_size *recon_buff_size = (struct vcd_property_buffer_size *) property_value; ysize = ddl_get_yuv_buf_size(recon_buff_size->width, recon_buff_size->height, DDL_YUV_BUF_TYPE_TILE); uvsize = ddl_get_yuv_buf_size(recon_buff_size->width, recon_buff_size->height/2, DDL_YUV_BUF_TYPE_TILE); recon_buff_size->size = ysize + uvsize; recon_buff_size->alignment = DDL_TILE_BUFFER_ALIGN_BYTES; DDL_MSG_LOW("w: %d, h: %d, S: %d, A: %d", recon_buff_size->width, recon_buff_size->height, recon_buff_size->size, recon_buff_size->alignment); vcd_status = VCD_S_SUCCESS; } } break; case VCD_I_METADATA_ENABLE: case VCD_I_METADATA_HEADER: DDL_MSG_ERROR("Meta Data Interface is Requested"); vcd_status = ddl_get_metadata_params(ddl, property_hdr, property_value); vcd_status = VCD_S_SUCCESS; break; default: vcd_status = VCD_ERR_ILLEGAL_OP; break; } return vcd_status; } static u32 ddl_set_enc_dynamic_property(struct ddl_client_context *ddl, struct vcd_property_hdr *property_hdr, void *property_value) { struct ddl_encoder_data *encoder = &ddl->codec_data.encoder; u32 vcd_status = VCD_ERR_ILLEGAL_PARM; u32 dynamic_prop_change = 0x0; switch (property_hdr->prop_id) { case VCD_I_REQ_IFRAME: if (sizeof(struct vcd_property_req_i_frame) == property_hdr->sz) { dynamic_prop_change |= DDL_ENC_REQ_IFRAME; vcd_status = VCD_S_SUCCESS; } break; case VCD_I_TARGET_BITRATE: { struct vcd_property_target_bitrate *bitrate = (struct vcd_property_target_bitrate *)property_value; if (sizeof(struct vcd_property_target_bitrate) == property_hdr->sz && bitrate->target_bitrate && bitrate->target_bitrate <= DDL_MAX_BIT_RATE) { encoder->target_bit_rate = *bitrate; dynamic_prop_change = DDL_ENC_CHANGE_BITRATE; vcd_status = VCD_S_SUCCESS; } } break; case VCD_I_INTRA_PERIOD: { struct vcd_property_i_period *i_period = (struct vcd_property_i_period *)property_value; if (sizeof(struct vcd_property_i_period) == property_hdr->sz) { encoder->i_period = *i_period; dynamic_prop_change = DDL_ENC_CHANGE_IPERIOD; vcd_status = VCD_S_SUCCESS; } } break; case VCD_I_FRAME_RATE: { struct vcd_property_frame_rate *frame_rate = (struct vcd_property_frame_rate *) property_value; if (sizeof(struct vcd_property_frame_rate) == property_hdr->sz && frame_rate->fps_denominator && frame_rate->fps_numerator && frame_rate->fps_denominator <= frame_rate->fps_numerator) { encoder->frame_rate = *frame_rate; dynamic_prop_change = DDL_ENC_CHANGE_FRAMERATE; if (DDLCLIENT_STATE_IS(ddl, DDL_CLIENT_OPEN) && (encoder->codec.codec != VCD_CODEC_MPEG4 || encoder->short_header.short_header)) { ddl_set_default_enc_vop_timing(encoder); } vcd_status = VCD_S_SUCCESS; } } case VCD_I_INTRA_REFRESH: { struct vcd_property_intra_refresh_mb_number *intra_refresh_mb_num = (struct vcd_property_intra_refresh_mb_number *) property_value; u32 frame_mb_num = DDL_NO_OF_MB(encoder->frame_size.width, encoder->frame_size.height); if ((sizeof(struct vcd_property_intra_refresh_mb_number) == property_hdr->sz) && (intra_refresh_mb_num->cir_mb_number <= frame_mb_num)) { encoder->intra_refresh = *intra_refresh_mb_num; dynamic_prop_change = DDL_ENC_CHANGE_CIR; vcd_status = VCD_S_SUCCESS; } } break; default: vcd_status = VCD_ERR_ILLEGAL_OP; break; } if (!vcd_status && (DDLCLIENT_STATE_IS(ddl, DDL_CLIENT_WAIT_FOR_FRAME) || DDLCLIENT_STATE_IS(ddl, DDL_CLIENT_WAIT_FOR_FRAME_DONE))) encoder->dynamic_prop_change |= dynamic_prop_change; return vcd_status; } void ddl_set_default_dec_property(struct ddl_client_context *ddl) { struct ddl_decoder_data *decoder = &(ddl->codec_data.decoder); if (decoder->codec.codec >= VCD_CODEC_MPEG2 && decoder->codec.codec <= VCD_CODEC_XVID) decoder->post_filter.post_filter = false; else decoder->post_filter.post_filter = false; decoder->buf_format.buffer_format = VCD_BUFFER_FORMAT_TILE_4x2; decoder->client_frame_size.height = VCD_DDL_TEST_DEFAULT_HEIGHT; decoder->client_frame_size.width = VCD_DDL_TEST_DEFAULT_WIDTH; decoder->client_frame_size.stride = VCD_DDL_TEST_DEFAULT_WIDTH; decoder->client_frame_size.scan_lines = VCD_DDL_TEST_DEFAULT_HEIGHT; decoder->progressive_only = 1; decoder->idr_only_decoding = false; decoder->output_order = VCD_DEC_ORDER_DISPLAY; decoder->field_needed_for_prev_ip = 0; decoder->cont_mode = 0; decoder->reconfig_detected = false; ddl_set_default_metadata_flag(ddl); ddl_set_default_decoder_buffer_req(decoder, true); } static void ddl_set_default_enc_property(struct ddl_client_context *ddl) { struct ddl_encoder_data *encoder = &(ddl->codec_data.encoder); ddl_set_default_enc_profile(encoder); ddl_set_default_enc_level(encoder); encoder->rc.rate_control = VCD_RATE_CONTROL_VBR_VFR; ddl_set_default_enc_rc_params(encoder); ddl_set_default_enc_intra_period(encoder); encoder->intra_refresh.cir_mb_number = 0; ddl_set_default_enc_vop_timing(encoder); encoder->multi_slice.m_slice_sel = VCD_MSLICE_OFF; encoder->multi_slice.m_slice_size = 0; ddl->b_count = 0; encoder->short_header.short_header = false; encoder->entropy_control.entropy_sel = VCD_ENTROPY_SEL_CAVLC; encoder->entropy_control.cabac_model = VCD_CABAC_MODEL_NUMBER_0; encoder->db_control.db_config = VCD_DB_ALL_BLOCKING_BOUNDARY; encoder->db_control.slice_alpha_offset = 0; encoder->db_control.slice_beta_offset = 0; encoder->recon_buf_format.buffer_format = VCD_BUFFER_FORMAT_TILE_1x1; encoder->buf_format.buffer_format = VCD_BUFFER_FORMAT_NV12_16M2KA; encoder->hdr_ext_control = 0; encoder->mb_info_enable = false; encoder->num_references_for_p_frame = DDL_MIN_NUM_REF_FOR_P_FRAME; ddl_set_default_metadata_flag(ddl); ddl_set_default_encoder_buffer_req(encoder); } static void ddl_set_default_enc_profile(struct ddl_encoder_data *encoder) { enum vcd_codec codec = encoder->codec.codec; if (codec == VCD_CODEC_MPEG4) encoder->profile.profile = VCD_PROFILE_MPEG4_SP; else if (codec == VCD_CODEC_H264) encoder->profile.profile = VCD_PROFILE_H264_BASELINE; else encoder->profile.profile = VCD_PROFILE_H263_BASELINE; } static void ddl_set_default_enc_level(struct ddl_encoder_data *encoder) { enum vcd_codec codec = encoder->codec.codec; if (codec == VCD_CODEC_MPEG4) encoder->level.level = VCD_LEVEL_MPEG4_1; else if (codec == VCD_CODEC_H264) encoder->level.level = VCD_LEVEL_H264_1; else encoder->level.level = VCD_LEVEL_H263_10; } static void ddl_set_default_enc_vop_timing( struct ddl_encoder_data *encoder) { if (encoder->codec.codec == VCD_CODEC_MPEG4) { encoder->vop_timing.vop_time_resolution = (encoder->frame_rate.fps_numerator << 1) / encoder->frame_rate.fps_denominator; } else encoder->vop_timing.vop_time_resolution = DDL_FRAMERATE_SCALE(DDL_INITIAL_FRAME_RATE); } static void ddl_set_default_enc_intra_period( struct ddl_encoder_data *encoder) { switch (encoder->rc.rate_control) { default: case VCD_RATE_CONTROL_VBR_VFR: case VCD_RATE_CONTROL_VBR_CFR: case VCD_RATE_CONTROL_CBR_VFR: case VCD_RATE_CONTROL_OFF: encoder->i_period.p_frames = ((encoder->frame_rate.fps_numerator << 1) / encoder->frame_rate.fps_denominator) - 1; break; case VCD_RATE_CONTROL_CBR_CFR: encoder->i_period.p_frames = ((encoder->frame_rate.fps_numerator >> 1) / encoder->frame_rate.fps_denominator) - 1; break; } encoder->i_period.b_frames = DDL_DEFAULT_NUM_OF_B_FRAME; } static void ddl_set_default_enc_rc_params( struct ddl_encoder_data *encoder) { enum vcd_codec codec = encoder->codec.codec; encoder->rc_level.frame_level_rc = true; encoder->qp_range.min_qp = 0x1; if (codec == VCD_CODEC_H264) { encoder->qp_range.min_qp = 0x1; encoder->qp_range.max_qp = 0x33; encoder->session_qp.i_frame_qp = 0x14; encoder->session_qp.p_frame_qp = 0x14; encoder->session_qp.b_frame_qp = 0x14; encoder->rc_level.mb_level_rc = true; encoder->adaptive_rc.disable_activity_region_flag = true; encoder->adaptive_rc.disable_dark_region_as_flag = true; encoder->adaptive_rc.disable_smooth_region_as_flag = true; encoder->adaptive_rc.disable_static_region_as_flag = true; } else { encoder->qp_range.max_qp = 0x1f; encoder->qp_range.min_qp = 0x1; encoder->session_qp.i_frame_qp = 0xd; encoder->session_qp.p_frame_qp = 0xd; encoder->session_qp.b_frame_qp = 0xd; encoder->rc_level.frame_level_rc = true; encoder->rc_level.mb_level_rc = false; } switch (encoder->rc.rate_control) { case VCD_RATE_CONTROL_VBR_CFR: encoder->r_cframe_skip = 0; encoder->frame_level_rc.reaction_coeff = 0x1f4; break; case VCD_RATE_CONTROL_CBR_VFR: encoder->r_cframe_skip = 1; if (codec != VCD_CODEC_H264) { encoder->session_qp.i_frame_qp = 0xf; encoder->session_qp.p_frame_qp = 0xf; encoder->session_qp.b_frame_qp = 0xf; } encoder->frame_level_rc.reaction_coeff = 0x14; break; case VCD_RATE_CONTROL_CBR_CFR: encoder->r_cframe_skip = 0; encoder->frame_level_rc.reaction_coeff = 0x6; break; case VCD_RATE_CONTROL_OFF: encoder->r_cframe_skip = 0; encoder->rc_level.frame_level_rc = false; encoder->rc_level.mb_level_rc = false; break; case VCD_RATE_CONTROL_VBR_VFR: default: encoder->r_cframe_skip = 1; encoder->frame_level_rc.reaction_coeff = 0x1f4; break; } } void ddl_set_default_encoder_buffer_req(struct ddl_encoder_data *encoder) { u32 y_cb_cr_size, y_size; memset(&encoder->hw_bufs.dpb_y, 0, sizeof(struct ddl_buf_addr) * 4); memset(&encoder->hw_bufs.dpb_c, 0, sizeof(struct ddl_buf_addr) * 4); y_cb_cr_size = ddl_get_yuv_buffer_size(&encoder->frame_size, &encoder->buf_format, false, encoder->hdr.decoding, &y_size); encoder->input_buf_size.size_yuv = y_cb_cr_size; encoder->input_buf_size.size_y = y_size; encoder->input_buf_size.size_c = y_cb_cr_size - y_size; memset(&encoder->input_buf_req , 0 , sizeof(struct vcd_buffer_requirement)); encoder->input_buf_req.min_count = 3; encoder->input_buf_req.actual_count = encoder->input_buf_req.min_count; encoder->input_buf_req.max_count = DDL_MAX_BUFFER_COUNT; encoder->input_buf_req.sz = y_cb_cr_size; if (encoder->buf_format.buffer_format == VCD_BUFFER_FORMAT_NV12_16M2KA) encoder->input_buf_req.align = DDL_LINEAR_BUFFER_ALIGN_BYTES; else if (VCD_BUFFER_FORMAT_TILE_4x2 == encoder->buf_format.buffer_format) encoder->input_buf_req.align = DDL_TILE_BUFFER_ALIGN_BYTES; encoder->client_input_buf_req = encoder->input_buf_req; memset(&encoder->output_buf_req , 0 , sizeof(struct vcd_buffer_requirement)); encoder->output_buf_req.min_count = encoder->i_period.b_frames + 2; encoder->output_buf_req.actual_count = encoder->output_buf_req.min_count + 3; encoder->output_buf_req.max_count = DDL_MAX_BUFFER_COUNT; encoder->output_buf_req.align = DDL_LINEAR_BUFFER_ALIGN_BYTES; if (y_cb_cr_size >= VCD_DDL_720P_YUV_BUF_SIZE) y_cb_cr_size = y_cb_cr_size>>1; encoder->output_buf_req.sz = DDL_ALIGN(y_cb_cr_size, DDL_KILO_BYTE(4)); ddl_set_default_encoder_metadata_buffer_size(encoder); encoder->client_output_buf_req = encoder->output_buf_req; } u32 ddl_set_default_decoder_buffer_req(struct ddl_decoder_data *decoder, u32 estimate) { struct vcd_property_frame_size *frame_size; struct vcd_buffer_requirement *input_buf_req; struct vcd_buffer_requirement *output_buf_req; u32 min_dpb, y_cb_cr_size; if (!decoder->codec.codec) return false; if (estimate) { if (!decoder->cont_mode) min_dpb = ddl_decoder_min_num_dpb(decoder); else min_dpb = 5; frame_size = &decoder->client_frame_size; output_buf_req = &decoder->client_output_buf_req; input_buf_req = &decoder->client_input_buf_req; y_cb_cr_size = ddl_get_yuv_buffer_size(frame_size, &decoder->buf_format, (!decoder->progressive_only), decoder->hdr.decoding, NULL); } else { frame_size = &decoder->frame_size; output_buf_req = &decoder->actual_output_buf_req; input_buf_req = &decoder->actual_input_buf_req; min_dpb = decoder->min_dpb_num; y_cb_cr_size = decoder->y_cb_cr_size; } memset(output_buf_req, 0, sizeof(struct vcd_buffer_requirement)); if (!estimate && !decoder->idr_only_decoding && !decoder->cont_mode) output_buf_req->actual_count = min_dpb + 4; else output_buf_req->actual_count = min_dpb; output_buf_req->min_count = min_dpb; output_buf_req->max_count = DDL_MAX_BUFFER_COUNT; output_buf_req->sz = y_cb_cr_size; DDL_MSG_LOW("output_buf_req->sz : %d", output_buf_req->sz); if (decoder->buf_format.buffer_format != VCD_BUFFER_FORMAT_NV12) output_buf_req->align = DDL_TILE_BUFFER_ALIGN_BYTES; else output_buf_req->align = DDL_LINEAR_BUFFER_ALIGN_BYTES; ddl_set_default_decoder_metadata_buffer_size(decoder, frame_size, output_buf_req); decoder->min_output_buf_req = *output_buf_req; memset(input_buf_req, 0, sizeof(struct vcd_buffer_requirement)); input_buf_req->min_count = 1; input_buf_req->actual_count = input_buf_req->min_count + 1; input_buf_req->max_count = DDL_MAX_BUFFER_COUNT; input_buf_req->sz = (1024 * 1024 * 2); input_buf_req->align = DDL_LINEAR_BUFFER_ALIGN_BYTES; decoder->min_input_buf_req = *input_buf_req; return true; } u32 ddl_get_yuv_buffer_size(struct vcd_property_frame_size *frame_size, struct vcd_property_buffer_format *buf_format, u32 interlace, u32 decoding, u32 *pn_c_offset) { struct vcd_property_frame_size frame_sz = *frame_size; u32 total_memory_size = 0, c_offset = 0; ddl_calculate_stride(&frame_sz, interlace); if (buf_format->buffer_format == VCD_BUFFER_FORMAT_TILE_4x2) { u32 component_mem_size, width_round_up; u32 height_round_up, height_chroma = (frame_sz.scan_lines >> 1); width_round_up = DDL_ALIGN(frame_sz.stride, DDL_TILE_ALIGN_WIDTH); height_round_up = DDL_ALIGN(frame_sz.scan_lines, DDL_TILE_ALIGN_HEIGHT); component_mem_size = width_round_up * height_round_up; component_mem_size = DDL_ALIGN(component_mem_size, DDL_TILE_MULTIPLY_FACTOR); c_offset = component_mem_size; total_memory_size = ((component_mem_size + DDL_TILE_BUF_ALIGN_GUARD_BYTES) & DDL_TILE_BUF_ALIGN_MASK); height_round_up = DDL_ALIGN(height_chroma, DDL_TILE_ALIGN_HEIGHT); component_mem_size = width_round_up * height_round_up; component_mem_size = DDL_ALIGN(component_mem_size, DDL_TILE_MULTIPLY_FACTOR); total_memory_size += component_mem_size; } else { if (decoding) total_memory_size = frame_sz.scan_lines * frame_sz.stride; else total_memory_size = frame_sz.height * frame_sz.stride; c_offset = DDL_ALIGN(total_memory_size, DDL_LINEAR_MULTIPLY_FACTOR); total_memory_size = c_offset + DDL_ALIGN( total_memory_size >> 1, DDL_LINEAR_MULTIPLY_FACTOR); } if (pn_c_offset) *pn_c_offset = c_offset; return total_memory_size; } void ddl_calculate_stride(struct vcd_property_frame_size *frame_size, u32 interlace) { frame_size->stride = DDL_ALIGN(frame_size->width, DDL_LINEAR_ALIGN_WIDTH); if (interlace) frame_size->scan_lines = DDL_ALIGN(frame_size->height, DDL_TILE_ALIGN_HEIGHT); else frame_size->scan_lines = DDL_ALIGN(frame_size->height, DDL_LINEAR_ALIGN_HEIGHT); } static u32 ddl_valid_buffer_requirement(struct vcd_buffer_requirement *original_buf_req, struct vcd_buffer_requirement *req_buf_req) { u32 status = false; if (original_buf_req->max_count >= req_buf_req->actual_count && original_buf_req->min_count <= req_buf_req->actual_count && !((original_buf_req->align - (u32)0x1) & req_buf_req->align) && /*original_buf_req->align <= req_buf_req->align,*/ original_buf_req->sz <= req_buf_req->sz) status = true; else DDL_MSG_ERROR("ddl_valid_buf_req:Failed"); return status; } static u32 ddl_decoder_min_num_dpb(struct ddl_decoder_data *decoder) { u32 min_dpb = 0; if (decoder->idr_only_decoding) { min_dpb = DDL_MIN_BUFFER_COUNT; if (decoder->post_filter.post_filter) min_dpb *= 2; return min_dpb; } switch (decoder->codec.codec) { case VCD_CODEC_H264: { u32 yuv_size_in_mb = DDL_MIN(DDL_NO_OF_MB( decoder->client_frame_size.stride, decoder->client_frame_size.scan_lines), MAX_FRAME_SIZE_L4PT0_MBS); min_dpb = DDL_MIN((MAX_DPB_SIZE_L4PT0_MBS / yuv_size_in_mb), 16); min_dpb += 2; } break; case VCD_CODEC_H263: min_dpb = 3; break; default: case VCD_CODEC_MPEG1: case VCD_CODEC_MPEG2: case VCD_CODEC_MPEG4: case VCD_CODEC_DIVX_3: case VCD_CODEC_DIVX_4: case VCD_CODEC_DIVX_5: case VCD_CODEC_DIVX_6: case VCD_CODEC_XVID: case VCD_CODEC_VC1: case VCD_CODEC_VC1_RCV: min_dpb = 4; if (decoder->post_filter.post_filter) min_dpb *= 2; break; } return min_dpb; } static u32 ddl_set_dec_buffers(struct ddl_decoder_data *decoder, struct ddl_property_dec_pic_buffers *dpb) { u32 vcd_status = VCD_S_SUCCESS, loopc; for (loopc = 0; !vcd_status && loopc < dpb->no_of_dec_pic_buf; ++loopc) { if ((!DDL_ADDR_IS_ALIGNED(dpb->dec_pic_buffers[loopc]. vcd_frm.physical, decoder->client_output_buf_req.align)) || (dpb->dec_pic_buffers[loopc].vcd_frm.alloc_len < decoder->client_output_buf_req.sz)) vcd_status = VCD_ERR_ILLEGAL_PARM; } if (vcd_status) { DDL_MSG_ERROR("ddl_set_prop:" "Dpb_align_fail_or_alloc_size_small"); return vcd_status; } if (decoder->dp_buf.no_of_dec_pic_buf) { kfree(decoder->dp_buf.dec_pic_buffers); decoder->dp_buf.no_of_dec_pic_buf = 0; } decoder->dp_buf.dec_pic_buffers = kmalloc(dpb->no_of_dec_pic_buf * sizeof(struct ddl_frame_data_tag), GFP_KERNEL); if (!decoder->dp_buf.dec_pic_buffers) { DDL_MSG_ERROR("ddl_dec_set_prop:Dpb_container_alloc_failed"); return VCD_ERR_ALLOC_FAIL; } decoder->dp_buf.no_of_dec_pic_buf = dpb->no_of_dec_pic_buf; for (loopc = 0; loopc < dpb->no_of_dec_pic_buf; ++loopc) decoder->dp_buf.dec_pic_buffers[loopc] = dpb->dec_pic_buffers[loopc]; decoder->dpb_mask.client_mask = 0; decoder->dpb_mask.hw_mask = 0; decoder->dynamic_prop_change = 0; return VCD_S_SUCCESS; } void ddl_set_initial_default_values(struct ddl_client_context *ddl) { if (ddl->decoding) { ddl->codec_data.decoder.codec.codec = VCD_CODEC_MPEG4; ddl_set_default_dec_property(ddl); } else { struct ddl_encoder_data *encoder = &(ddl->codec_data.encoder); encoder->codec.codec = VCD_CODEC_MPEG4; encoder->target_bit_rate.target_bitrate = 64000; encoder->frame_size.width = VCD_DDL_TEST_DEFAULT_WIDTH; encoder->frame_size.height = VCD_DDL_TEST_DEFAULT_HEIGHT; encoder->frame_size.scan_lines = VCD_DDL_TEST_DEFAULT_HEIGHT; encoder->frame_size.stride = VCD_DDL_TEST_DEFAULT_WIDTH; encoder->frame_rate.fps_numerator = DDL_INITIAL_FRAME_RATE; encoder->frame_rate.fps_denominator = 1; ddl_set_default_enc_property(ddl); } }
Danile71/u8850_kernel
drivers/video/msm/vidc_old/1080p/ddl/vcd_ddl_properties.c
C
gpl-2.0
57,246
/* ResidualVM - A 3D game interpreter * * ResidualVM 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. * */ #ifndef GRIM_LUA_VAR_COMPONENT_H #define GRIM_LUA_VAR_COMPONENT_H #include "engines/grim/costume/component.h" namespace Grim { class LuaVarComponent : public Component { public: LuaVarComponent(Component *parent, int parentID, const char *name, tag32 tag); void setKey(int val) override; }; } // end of namespace Grim #endif
firesock/residualvm
engines/grim/costume/lua_var_component.h
C
gpl-2.0
1,284
/* * Copyright 2014 Samsung Electronics Co., Ltd. * http://www.samsung.com/ * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #ifndef __CORESIGHT_REGS_H #define __CORESIGHT_REGS_H #include <linux/kernel.h> #include <linux/types.h> #define OSLOCK_MAGIC (0xc5acce55) #ifdef CONFIG_EXYNOS_CORESIGHT /* Defines are used by core-sight */ #define CS_SJTAG_OFFSET (0x8000) #define SJTAG_STATUS (0x4) #define SJTAG_SOFT_LOCK (1<<2) /* DBG Registers */ #define DBGWFAR (0x018) /* RW */ #define DBGVCR (0x01c) /* RW */ #define DBGECR (0x024) /* RW or RAZ */ #define DBGDSCCR (0x028) /* RW or RAZ */ #define DBGDSMCR (0x02c) /* RW or RAZ */ #define DBGDTRRX (0x080) /* RW */ #define DBGDSCR (0x088) /* RW */ #define DBGDTRTX (0x08c) /* RW */ #define DBGDRCR (0x090) /* WO */ #define DBGEACR (0x094) /* RW */ #define DBGECCR (0x098) /* RW */ #define DBGPCSRlo (0x0a0) /* RO */ #define DBGCIDSR (0x0a4) /* RO */ #define DBGVIDSR (0x0a8) /* RO */ #define DBGPCSRhi (0x0ac) /* RO */ #define DBGBXVR0 (0x250) /* RW */ #define DBGBXVR1 (0x254) /* RW */ #define DBGOSLAR (0x300) /* WO */ #define DBGOSLSR (0x304) /* RO */ #define DBGPRCR (0x310) /* RW */ #define DBGPRSR (0x314) /* RO, OSLSR in ARMv8 */ #define DBGITOCTRL (0xef8) /* WO */ #define DBGITISR (0xefc) /* RO */ #define DBGITCTRL (0xf00) /* RW */ #define DBGCLAIMSET (0xfa0) /* RW */ #define DBGCLAIMCLR (0xfa4) /* RW */ #define DBGLAR (0xfb0) /* WO */ #define DBGLSR (0xfb4) /* RO */ #define DBGAUTHSTATUS (0xfb8) /* RO */ #define DBGDEVID2 (0xfc0) /* RO */ #define DBGDEVID1 (0xfc4) /* RO, PC offset */ #define DBGDEVID0 (0xfc8) /* RO */ #define DBGDEVTYPE (0xfcc) /* RO */ #define MIDR (0xd00) /* RO */ #define ID_AA64DFR0_EL1 (0xd28) /* DBG breakpoint registers (All RW) */ #define DBGBVRn(n) (0x400 + (n * 0x10)) /* 64bit */ #define DBGBCRn(n) (0x408 + (n * 0x10)) /* DBG watchpoint registers (All RW) */ #define DBGWVRn(n) (0x800 + (n * 0x10)) /* 64bit */ #define DBGWCRn(n) (0x808 + (n * 0x10)) /* DIDR or ID_AA64DFR0_EL1 bit */ #define DEBUG_ARCH_V8 (0x6) /* MIDR bit */ #define ARMV8_PROCESSOR (0xd00) #define ARMV8_CORTEXA53 (0xd03) #define ARMV8_CORTEXA57 (0xd07) #endif #ifdef CONFIG_EXYNOS_CORESIGHT_PC_INFO extern void exynos_cs_show_pcval(void); #else #define exynos_cs_show_pcval() do { } while(0) #endif #ifdef CONFIG_EXYNOS_CORESIGHT_ETM /* TMC(ETB/ETF/ETR) registers */ #define TMCRSZ (0x004) #define TMCSTS (0x00c) #define TMCRRD (0x010) #define TMCRRP (0x014) #define TMCRWP (0x018) #define TMCTGR (0x01c) #define TMCCTL (0x020) #define TMCRWD (0x024) #define TMCMODE (0x028) #define TMCLBUFLEVEL (0x02c) #define TMCCBUFLEVEL (0x030) #define TMCBUFWM (0x034) #define TMCRRPHI (0x038) #define TMCRWPHI (0x03c) #define TMCAXICTL (0x110) #define TMCDBALO (0x118) #define TMCDBAHI (0x11c) #define TMCFFSR (0x300) #define TMCFFCR (0x304) #define TMCPSCR (0x308) /* Coresight manager register */ #define ITCTRL (0xf00) #define CLAIMSET (0xfa0) #define CLAIMCLR (0xfa4) #define LAR (0xfb0) #define LSR (0xfb4) #define AUTHSTATUS (0xfb8) /* FUNNEL configuration register */ #define FUNCTRL (0x0) #define FUNPRIORCTRL (0x4) /* ETM registers */ #define ETMCTLR (0x004) #define ETMPROCSELR (0x008) #define ETMSTATUS (0x00c) #define ETMCONFIG (0x010) #define ETMAUXCTLR (0x018) #define ETMEVENTCTL0R (0x020) #define ETMEVENTCTL1R (0x024) #define ETMSTALLCTLR (0x02c) #define ETMTSCTLR (0x030) #define ETMSYNCPR (0x034) #define ETMCCCCTLR (0x038) #define ETMBBCTLR (0x03c) #define ETMTRACEIDR (0x040) #define ETMQCTRLR (0x044) #define ETMVICTLR (0x080) #define ETMVIIECTLR (0x084) #define ETMVISSCTLR (0x088) #define ETMVIPCSSCTLR (0x08c) #define ETMVDCTLR (0x0a0) #define ETMVDSACCTLR (0x0a4) #define ETMVDARCCTLR (0x0a8) #define ETMSEQEVR(n) (0x100 + (n * 4)) #define ETMSEQRSTEVR (0x118) #define ETMSEQSTR (0x11c) #define ETMEXTINSELR (0x120) #define ETMCNTRLDVR(n) (0x140 + (n * 4)) #define ETMCNTCTLR(n) (0x150 + (n * 4)) #define ETMCNTVR(n) (0x160 + (n * 4)) #define ETMIDR8 (0x180) #define ETMIDR9 (0x184) #define ETMID10 (0x188) #define ETMID11 (0x18c) #define ETMID12 (0x190) #define ETMID13 (0x194) #define ETMID0 (0x1e0) #define ETMID1 (0x1e4) #define ETMID2 (0x1e8) #define ETMID3 (0x1ec) #define ETMID4 (0x1f0) #define ETMID5 (0x1f4) #define ETMID6 (0x1f8) #define ETMID7 (0x1fc) #define ETMRSCTLR(n) (0x200 + (n * 4)) #define ETMSSCCR(n) (0x280 + (n * 4)) #define ETMSSCSR(n) (0x2a0 + (n * 4)) #define ETMSSPCICR(n) (0x2c0 + (n * 4)) #define ETMOSLAR (0x300) #define ETMOSLSR (0x304) #define ETMPDCR (0x310) #define ETMPDSR (0x314) #define ETMACVR(n) (0x400 + (n * 4)) #define ETMACAT(n) (0x480 + (n * 4)) #define ETMDVCVR(n) (0x500 + (n * 4)) #define ETMDVCMR(n) (0x580 + (n * 4)) #define ETMCIDCVR(n) (0x600 + (n * 4)) #define ETMVMIDCVR(n) (0x640 + (n * 4)) #define ETMCCIDCCTLR0 (0x680) #define ETMCCIDCCTLR1 (0x684) #define ETMVMIDCCTLR0 (0x688) #define ETMVMIDCCTLR1 (0x68c) extern void exynos_trace_stop(void); #else #define exynos_trace_stop() do { } while(0) #endif /* defines for MNGS reset */ #define PEND_MNGS (1 << 1) #define PEND_APOLLO (1 << 0) #define DEFAULT_VAL_CPU_RESET_DISABLE 0xFFFFFFFC #define RESET_DISABLE_GPR_CPUPORESET (1 << 15) #define RESET_DISABLE_WDT_CPUPORESET (1 << 12) #define RESET_DISABLE_CORERESET (1 << 9) #define RESET_DISABLE_CPUPORESET (1 << 8) #define RESET_DISABLE_WDT_PRESET_DBG (1 << 25) #define RESET_DISABLE_PRESET_DBG (1 << 18) #define DFD_EDPCSR_DUMP_EN (1 << 0) #define RESET_DISABLE_L2RESET (1 << 16) #endif
cile381/s7_flat_kernel
arch/arm64/include/asm/core_regs.h
C
gpl-2.0
5,795
package DBI::ProfileDumper; use strict; =head1 NAME DBI::ProfileDumper - profile DBI usage and output data to a file =head1 SYNOPSIS To profile an existing program using DBI::ProfileDumper, set the DBI_PROFILE environment variable and run your program as usual. For example, using bash: DBI_PROFILE=2/DBI::ProfileDumper program.pl Then analyze the generated file (F<dbi.prof>) with L<dbiprof|dbiprof>: dbiprof You can also activate DBI::ProfileDumper from within your code: use DBI; # profile with default path (2) and output file (dbi.prof) $dbh->{Profile} = "!Statement/DBI::ProfileDumper"; # same thing, spelled out $dbh->{Profile} = "!Statement/DBI::ProfileDumper/File:dbi.prof"; # another way to say it use DBI::ProfileDumper; $dbh->{Profile} = DBI::ProfileDumper->new( Path => [ '!Statement' ], File => 'dbi.prof' ); # using a custom path $dbh->{Profile} = DBI::ProfileDumper->new( Path => [ "foo", "bar" ], File => 'dbi.prof', ); =head1 DESCRIPTION DBI::ProfileDumper is a subclass of L<DBI::Profile|DBI::Profile> which dumps profile data to disk instead of printing a summary to your screen. You can then use L<dbiprof|dbiprof> to analyze the data in a number of interesting ways, or you can roll your own analysis using L<DBI::ProfileData|DBI::ProfileData>. B<NOTE:> For Apache/mod_perl applications, use L<DBI::ProfileDumper::Apache|DBI::ProfileDumper::Apache>. =head1 USAGE One way to use this module is just to enable it in your C<$dbh>: $dbh->{Profile} = "1/DBI::ProfileDumper"; This will write out profile data by statement into a file called F<dbi.prof>. If you want to modify either of these properties, you can construct the DBI::ProfileDumper object yourself: use DBI::ProfileDumper; $dbh->{Profile} = DBI::ProfileDumper->new( Path => [ '!Statement' ], File => 'dbi.prof' ); The C<Path> option takes the same values as in L<DBI::Profile>. The C<File> option gives the name of the file where results will be collected. If it already exists it will be overwritten. You can also activate this module by setting the DBI_PROFILE environment variable: $ENV{DBI_PROFILE} = "!Statement/DBI::ProfileDumper"; This will cause all DBI handles to share the same profiling object. =head1 METHODS The following methods are available to be called using the profile object. You can get access to the profile object from the Profile key in any DBI handle: my $profile = $dbh->{Profile}; =head2 flush_to_disk $profile->flush_to_disk() Flushes all collected profile data to disk and empties the Data hash. Returns the filename written to. If no profile data has been collected then the file is not written and flush_to_disk() returns undef. The file is locked while it's being written. A process 'consuming' the files while they're being written to, should rename the file first, then lock it, then read it, then close and delete it. The C<DeleteFiles> option to L<DBI::ProfileData> does the right thing. This method may be called multiple times during a program run. =head2 empty $profile->empty() Clears the Data hash without writing to disk. =head2 filename $filename = $profile->filename(); Get or set the filename. The filename can be specified as a CODE reference, in which case the referenced code should return the filename to be used. The code will be called with the profile object as its first argument. =head1 DATA FORMAT The data format written by DBI::ProfileDumper starts with a header containing the version number of the module used to generate it. Then a block of variable declarations describes the profile. After two newlines, the profile data forms the body of the file. For example: DBI::ProfileDumper 2.003762 Path = [ '!Statement', '!MethodName' ] Program = t/42profile_data.t + 1 SELECT name FROM users WHERE id = ? + 2 prepare = 1 0.0312958955764771 0.000490069389343262 0.000176072120666504 0.00140702724456787 1023115819.83019 1023115819.86576 + 2 execute 1 0.0312958955764771 0.000490069389343262 0.000176072120666504 0.00140702724456787 1023115819.83019 1023115819.86576 + 2 fetchrow_hashref = 1 0.0312958955764771 0.000490069389343262 0.000176072120666504 0.00140702724456787 1023115819.83019 1023115819.86576 + 1 UPDATE users SET name = ? WHERE id = ? + 2 prepare = 1 0.0312958955764771 0.000490069389343262 0.000176072120666504 0.00140702724456787 1023115819.83019 1023115819.86576 + 2 execute = 1 0.0312958955764771 0.000490069389343262 0.000176072120666504 0.00140702724456787 1023115819.83019 1023115819.86576 The lines beginning with C<+> signs signify keys. The number after the C<+> sign shows the nesting level of the key. Lines beginning with C<=> are the actual profile data, in the same order as in DBI::Profile. Note that the same path may be present multiple times in the data file since C<format()> may be called more than once. When read by DBI::ProfileData the data points will be merged to produce a single data set for each distinct path. The key strings are transformed in three ways. First, all backslashes are doubled. Then all newlines and carriage-returns are transformed into C<\n> and C<\r> respectively. Finally, any NULL bytes (C<\0>) are entirely removed. When DBI::ProfileData reads the file the first two transformations will be reversed, but NULL bytes will not be restored. =head1 AUTHOR Sam Tregar <sam@tregar.com> =head1 COPYRIGHT AND LICENSE Copyright (C) 2002 Sam Tregar This program is free software; you can redistribute it and/or modify it under the same terms as Perl 5 itself. =cut # inherit from DBI::Profile use DBI::Profile; our @ISA = ("DBI::Profile"); our $VERSION = "2.015325"; use Carp qw(croak); use Fcntl qw(:flock); use Symbol; my $HAS_FLOCK = (defined $ENV{DBI_PROFILE_FLOCK}) ? $ENV{DBI_PROFILE_FLOCK} : do { local $@; eval { flock STDOUT, 0; 1 } }; my $program_header; # validate params and setup default sub new { my $pkg = shift; my $self = $pkg->SUPER::new( LockFile => $HAS_FLOCK, @_, ); # provide a default filename $self->filename("dbi.prof") unless $self->filename; DBI->trace_msg("$self: @{[ %$self ]}\n",0) if $self->{Trace} && $self->{Trace} >= 2; return $self; } # get/set filename to use sub filename { my $self = shift; $self->{File} = shift if @_; my $filename = $self->{File}; $filename = $filename->($self) if ref($filename) eq 'CODE'; return $filename; } # flush available data to disk sub flush_to_disk { my $self = shift; my $class = ref $self; my $filename = $self->filename; my $data = $self->{Data}; if (1) { # make an option if (not $data or ref $data eq 'HASH' && !%$data) { DBI->trace_msg("flush_to_disk skipped for empty profile\n",0) if $self->{Trace}; return undef; } } my $fh = gensym; if (($self->{_wrote_header}||'') eq $filename) { # append more data to the file # XXX assumes that Path hasn't changed open($fh, ">>", $filename) or croak("Unable to open '$filename' for $class output: $!"); } else { # create new file (or overwrite existing) if (-f $filename) { my $bak = $filename.'.prev'; unlink($bak); rename($filename, $bak) or warn "Error renaming $filename to $bak: $!\n"; } open($fh, ">", $filename) or croak("Unable to open '$filename' for $class output: $!"); } # lock the file (before checking size and writing the header) flock($fh, LOCK_EX) if $self->{LockFile}; # write header if file is empty - typically because we just opened it # in '>' mode, or perhaps we used '>>' but the file had been truncated externally. if (-s $fh == 0) { DBI->trace_msg("flush_to_disk wrote header to $filename\n",0) if $self->{Trace}; $self->write_header($fh); $self->{_wrote_header} = $filename; } my $lines = $self->write_data($fh, $self->{Data}, 1); DBI->trace_msg("flush_to_disk wrote $lines lines to $filename\n",0) if $self->{Trace}; close($fh) # unlocks the file or croak("Error closing '$filename': $!"); $self->empty(); return $filename; } # write header to a filehandle sub write_header { my ($self, $fh) = @_; # isolate us against globals which effect print local($\, $,); # $self->VERSION can return undef during global destruction my $version = $self->VERSION || $VERSION; # module name and version number print $fh ref($self)." $version\n"; # print out Path (may contain CODE refs etc) my @path_words = map { escape_key($_) } @{ $self->{Path} || [] }; print $fh "Path = [ ", join(', ', @path_words), " ]\n"; # print out $0 and @ARGV if (!$program_header) { # XXX should really quote as well as escape $program_header = "Program = " . join(" ", map { escape_key($_) } $0, @ARGV) . "\n"; } print $fh $program_header; # all done print $fh "\n"; } # write data in the proscribed format sub write_data { my ($self, $fh, $data, $level) = @_; # XXX it's valid for $data to be an ARRAY ref, i.e., Path is empty. # produce an empty profile for invalid $data return 0 unless $data and UNIVERSAL::isa($data,'HASH'); # isolate us against globals which affect print local ($\, $,); my $lines = 0; while (my ($key, $value) = each(%$data)) { # output a key print $fh "+ $level ". escape_key($key). "\n"; if (UNIVERSAL::isa($value,'ARRAY')) { # output a data set for a leaf node print $fh "= ".join(' ', @$value)."\n"; $lines += 1; } else { # recurse through keys - this could be rewritten to use a # stack for some small performance gain $lines += $self->write_data($fh, $value, $level + 1); } } return $lines; } # escape a key for output sub escape_key { my $key = shift; $key =~ s!\\!\\\\!g; $key =~ s!\n!\\n!g; $key =~ s!\r!\\r!g; $key =~ s!\0!!g; return $key; } # flush data to disk when profile object goes out of scope sub on_destroy { shift->flush_to_disk(); } 1;
mishin/dwimperl-windows
strawberry-perl-5.20.0.1-32bit-portable/perl/vendor/lib/DBI/ProfileDumper.pm
Perl
gpl-2.0
10,386
! { dg-do run } ! { dg-options "-pedantic-errors -mdalign" { target sh*-*-* } } ! Tests the fix for PR37614, in which the alignment of commons followed ! g77 rather than the standard or other compilers. ! ! Contributed by Tobias Burnus <burnus@gcc.gnu.org> ! subroutine foo (z) real(8) x, y, z common i(8) equivalence (x, i(3)),(y,i(7)) if ((i(1) .ne. 42) .or. (i(5) .ne. 43)) STOP 1 if ((i(2) .ne. 0) .or. (i(2) .ne. 0)) STOP 2 if ((x .ne. z) .or. (y .ne. z)) STOP 3 end subroutine subroutine bar common i(8) i = 0 end subroutine real(8) x, y common i, x, j, y ! { dg-warning "Padding" } call bar i = 42 j = 43 x = atan (1.0)*4.0 y = x call foo (x) end
Gurgel100/gcc
gcc/testsuite/gfortran.dg/common_align_2.f90
FORTRAN
gpl-2.0
690
<?php /** * @package Joomla.Installation * @subpackage Application * * @copyright (C) 2005 Open Source Matters, Inc. <https://www.joomla.org> * @license GNU General Public License version 2 or later; see LICENSE.txt */ defined('_JEXEC') or die; // Global definitions $parts = explode(DIRECTORY_SEPARATOR, JPATH_BASE); array_pop($parts); // Defines define('JPATH_ROOT', implode(DIRECTORY_SEPARATOR, $parts)); define('JPATH_SITE', JPATH_ROOT); define('JPATH_CONFIGURATION', JPATH_ROOT); define('JPATH_ADMINISTRATOR', JPATH_ROOT . DIRECTORY_SEPARATOR . 'administrator'); define('JPATH_LIBRARIES', JPATH_ROOT . DIRECTORY_SEPARATOR . 'libraries'); define('JPATH_PLUGINS', JPATH_ROOT . DIRECTORY_SEPARATOR . 'plugins'); define('JPATH_INSTALLATION', JPATH_ROOT . DIRECTORY_SEPARATOR . 'installation'); define('JPATH_THEMES', JPATH_BASE); define('JPATH_CACHE', JPATH_ADMINISTRATOR . DIRECTORY_SEPARATOR . 'cache'); define('JPATH_MANIFESTS', JPATH_ADMINISTRATOR . DIRECTORY_SEPARATOR . 'manifests'); define('JPATH_API', JPATH_ROOT . DIRECTORY_SEPARATOR . 'api'); define('JPATH_CLI', JPATH_ROOT . DIRECTORY_SEPARATOR . 'cli');
brianteeman/joomla-cms
installation/includes/defines.php
PHP
gpl-2.0
1,205
/* ========================================================================== */ /* === colamd - a sparse matrix column ordering algorithm =================== */ /* ========================================================================== */ /* colamd: An approximate minimum degree column ordering algorithm. Purpose: Colamd computes a permutation Q such that the Cholesky factorization of (AQ)'(AQ) has less fill-in and requires fewer floating point operations than A'A. This also provides a good ordering for sparse partial pivoting methods, P(AQ) = LU, where Q is computed prior to numerical factorization, and P is computed during numerical factorization via conventional partial pivoting with row interchanges. Colamd is the column ordering method used in SuperLU, part of the ScaLAPACK library. It is also available as user-contributed software for Matlab 5.2, available from MathWorks, Inc. (http://www.mathworks.com). This routine can be used in place of COLMMD in Matlab. By default, the \ and / operators in Matlab perform a column ordering (using COLMMD) prior to LU factorization using sparse partial pivoting, in the built-in Matlab LU(A) routine. Authors: The authors of the code itself are Stefan I. Larimore and Timothy A. Davis (davis@cise.ufl.edu), University of Florida. The algorithm was developed in collaboration with John Gilbert, Xerox PARC, and Esmond Ng, Oak Ridge National Laboratory. Date: August 3, 1998. Version 1.0. Acknowledgements: This work was supported by the National Science Foundation, under grants DMS-9504974 and DMS-9803599. Notice: Copyright (c) 1998 by the University of Florida. All Rights Reserved. THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED OR IMPLIED. ANY USE IS AT YOUR OWN RISK. Permission is hereby granted to use or copy this program for any purpose, provided the above notices are retained on all copies. User documentation of any code that uses this code must cite the Authors, the Copyright, and "Used by permission." If this code is accessible from within Matlab, then typing "help colamd" or "colamd" (with no arguments) must cite the Authors. Permission to modify the code and to distribute modified code is granted, provided the above notices are retained, and a notice that the code was modified is included with the above copyright notice. You must also retain the Availability information below, of the original version. This software is provided free of charge. Availability: This file is located at http://www.cise.ufl.edu/~davis/colamd/colamd.c The colamd.h file is required, located in the same directory. The colamdmex.c file provides a Matlab interface for colamd. The symamdmex.c file provides a Matlab interface for symamd, which is a symmetric ordering based on this code, colamd.c. All codes are purely ANSI C compliant (they use no Unix-specific routines, include files, etc.). */ /* ========================================================================== */ /* === Description of user-callable routines ================================ */ /* ========================================================================== */ /* Each user-callable routine (declared as PUBLIC) is briefly described below. Refer to the comments preceding each routine for more details. ---------------------------------------------------------------------------- colamd_recommended: ---------------------------------------------------------------------------- Usage: Alen = colamd_recommended (nnz, n_row, n_col) ; Purpose: Returns recommended value of Alen for use by colamd. Returns -1 if any input argument is negative. Arguments: int nnz ; Number of nonzeros in the matrix A. This must be the same value as p [n_col] in the call to colamd - otherwise you will get a wrong value of the recommended memory to use. int n_row ; Number of rows in the matrix A. int n_col ; Number of columns in the matrix A. ---------------------------------------------------------------------------- colamd_set_defaults: ---------------------------------------------------------------------------- Usage: colamd_set_defaults (knobs) ; Purpose: Sets the default parameters. Arguments: double knobs [COLAMD_KNOBS] ; Output only. Rows with more than (knobs [COLAMD_DENSE_ROW] * n_col) entries are removed prior to ordering. Columns with more than (knobs [COLAMD_DENSE_COL] * n_row) entries are removed prior to ordering, and placed last in the output column ordering. Default values of these two knobs are both 0.5. Currently, only knobs [0] and knobs [1] are used, but future versions may use more knobs. If so, they will be properly set to their defaults by the future version of colamd_set_defaults, so that the code that calls colamd will not need to change, assuming that you either use colamd_set_defaults, or pass a (double *) NULL pointer as the knobs array to colamd. ---------------------------------------------------------------------------- colamd: ---------------------------------------------------------------------------- Usage: colamd (n_row, n_col, Alen, A, p, knobs) ; Purpose: Computes a column ordering (Q) of A such that P(AQ)=LU or (AQ)'AQ=LL' have less fill-in and require fewer floating point operations than factorizing the unpermuted matrix A or A'A, respectively. Arguments: int n_row ; Number of rows in the matrix A. Restriction: n_row >= 0. Colamd returns FALSE if n_row is negative. int n_col ; Number of columns in the matrix A. Restriction: n_col >= 0. Colamd returns FALSE if n_col is negative. int Alen ; Restriction (see note): Alen >= 2*nnz + 6*(n_col+1) + 4*(n_row+1) + n_col + COLAMD_STATS Colamd returns FALSE if these conditions are not met. Note: this restriction makes an modest assumption regarding the size of the two typedef'd structures, below. We do, however, guarantee that Alen >= colamd_recommended (nnz, n_row, n_col) will be sufficient. int A [Alen] ; Input argument, stats on output. A is an integer array of size Alen. Alen must be at least as large as the bare minimum value given above, but this is very low, and can result in excessive run time. For best performance, we recommend that Alen be greater than or equal to colamd_recommended (nnz, n_row, n_col), which adds nnz/5 to the bare minimum value given above. On input, the row indices of the entries in column c of the matrix are held in A [(p [c]) ... (p [c+1]-1)]. The row indices in a given column c need not be in ascending order, and duplicate row indices may be be present. However, colamd will work a little faster if both of these conditions are met (Colamd puts the matrix into this format, if it finds that the the conditions are not met). The matrix is 0-based. That is, rows are in the range 0 to n_row-1, and columns are in the range 0 to n_col-1. Colamd returns FALSE if any row index is out of range. The contents of A are modified during ordering, and are thus undefined on output with the exception of a few statistics about the ordering (A [0..COLAMD_STATS-1]): A [0]: number of dense or empty rows ignored. A [1]: number of dense or empty columns ignored (and ordered last in the output permutation p) A [2]: number of garbage collections performed. A [3]: 0, if all row indices in each column were in sorted order, and no duplicates were present. 1, otherwise (in which case colamd had to do more work) Note that a row can become "empty" if it contains only "dense" and/or "empty" columns, and similarly a column can become "empty" if it only contains "dense" and/or "empty" rows. Future versions may return more statistics in A, but the usage of these 4 entries in A will remain unchanged. int p [n_col+1] ; Both input and output argument. p is an integer array of size n_col+1. On input, it holds the "pointers" for the column form of the matrix A. Column c of the matrix A is held in A [(p [c]) ... (p [c+1]-1)]. The first entry, p [0], must be zero, and p [c] <= p [c+1] must hold for all c in the range 0 to n_col-1. The value p [n_col] is thus the total number of entries in the pattern of the matrix A. Colamd returns FALSE if these conditions are not met. On output, if colamd returns TRUE, the array p holds the column permutation (Q, for P(AQ)=LU or (AQ)'(AQ)=LL'), where p [0] is the first column index in the new ordering, and p [n_col-1] is the last. That is, p [k] = j means that column j of A is the kth pivot column, in AQ, where k is in the range 0 to n_col-1 (p [0] = j means that column j of A is the first column in AQ). If colamd returns FALSE, then no permutation is returned, and p is undefined on output. double knobs [COLAMD_KNOBS] ; Input only. See colamd_set_defaults for a description. If the knobs array is not present (that is, if a (double *) NULL pointer is passed in its place), then the default values of the parameters are used instead. */ /* ========================================================================== */ /* === Include files ======================================================== */ /* ========================================================================== */ /* limits.h: the largest positive integer (INT_MAX) */ #include <limits.h> /* colamd.h: knob array size, stats output size, and global prototypes */ #include "colamd.h" /* ========================================================================== */ /* === Scaffolding code definitions ======================================== */ /* ========================================================================== */ /* Ensure that debugging is turned off: */ #ifndef NDEBUG #define NDEBUG #endif /* assert.h: the assert macro (no debugging if NDEBUG is defined) */ #include <assert.h> /* Our "scaffolding code" philosophy: In our opinion, well-written library code should keep its "debugging" code, and just normally have it turned off by the compiler so as not to interfere with performance. This serves several purposes: (1) assertions act as comments to the reader, telling you what the code expects at that point. All assertions will always be true (unless there really is a bug, of course). (2) leaving in the scaffolding code assists anyone who would like to modify the code, or understand the algorithm (by reading the debugging output, one can get a glimpse into what the code is doing). (3) (gasp!) for actually finding bugs. This code has been heavily tested and "should" be fully functional and bug-free ... but you never know... To enable debugging, comment out the "#define NDEBUG" above. The code will become outrageously slow when debugging is enabled. To control the level of debugging output, set an environment variable D to 0 (little), 1 (some), 2, 3, or 4 (lots). */ /* ========================================================================== */ /* === Row and Column structures ============================================ */ /* ========================================================================== */ typedef struct ColInfo_struct { int start ; /* index for A of first row in this column, or DEAD */ /* if column is dead */ int length ; /* number of rows in this column */ union { int thickness ; /* number of original columns represented by this */ /* col, if the column is alive */ int parent ; /* parent in parent tree super-column structure, if */ /* the column is dead */ } shared1 ; union { int score ; /* the score used to maintain heap, if col is alive */ int order ; /* pivot ordering of this column, if col is dead */ } shared2 ; union { int headhash ; /* head of a hash bucket, if col is at the head of */ /* a degree list */ int hash ; /* hash value, if col is not in a degree list */ int prev ; /* previous column in degree list, if col is in a */ /* degree list (but not at the head of a degree list) */ } shared3 ; union { int degree_next ; /* next column, if col is in a degree list */ int hash_next ; /* next column, if col is in a hash list */ } shared4 ; } ColInfo ; typedef struct RowInfo_struct { int start ; /* index for A of first col in this row */ int length ; /* number of principal columns in this row */ union { int degree ; /* number of principal & non-principal columns in row */ int p ; /* used as a row pointer in init_rows_cols () */ } shared1 ; union { int mark ; /* for computing set differences and marking dead rows*/ int first_column ;/* first column in row (used in garbage collection) */ } shared2 ; } RowInfo ; /* ========================================================================== */ /* === Definitions ========================================================== */ /* ========================================================================== */ #define MAX(a,b) (((a) > (b)) ? (a) : (b)) #define MIN(a,b) (((a) < (b)) ? (a) : (b)) #define ONES_COMPLEMENT(r) (-(r)-1) #define TRUE (1) #define FALSE (0) #define EMPTY (-1) /* Row and column status */ #define ALIVE (0) #define DEAD (-1) /* Column status */ #define DEAD_PRINCIPAL (-1) #define DEAD_NON_PRINCIPAL (-2) /* Macros for row and column status update and checking. */ #define ROW_IS_DEAD(r) ROW_IS_MARKED_DEAD (Row[r].shared2.mark) #define ROW_IS_MARKED_DEAD(row_mark) (row_mark < ALIVE) #define ROW_IS_ALIVE(r) (Row [r].shared2.mark >= ALIVE) #define COL_IS_DEAD(c) (Col [c].start < ALIVE) #define COL_IS_ALIVE(c) (Col [c].start >= ALIVE) #define COL_IS_DEAD_PRINCIPAL(c) (Col [c].start == DEAD_PRINCIPAL) #define KILL_ROW(r) { Row [r].shared2.mark = DEAD ; } #define KILL_PRINCIPAL_COL(c) { Col [c].start = DEAD_PRINCIPAL ; } #define KILL_NON_PRINCIPAL_COL(c) { Col [c].start = DEAD_NON_PRINCIPAL ; } /* Routines are either PUBLIC (user-callable) or PRIVATE (not user-callable) */ #define PUBLIC #define PRIVATE static /* ========================================================================== */ /* === Prototypes of PRIVATE routines ======================================= */ /* ========================================================================== */ PRIVATE int init_rows_cols ( int n_row, int n_col, RowInfo Row [], ColInfo Col [], int A [], int p [] ) ; PRIVATE void init_scoring ( int n_row, int n_col, RowInfo Row [], ColInfo Col [], int A [], int head [], double knobs [COLAMD_KNOBS], int *p_n_row2, int *p_n_col2, int *p_max_deg ) ; PRIVATE int find_ordering ( int n_row, int n_col, int Alen, RowInfo Row [], ColInfo Col [], int A [], int head [], int n_col2, int max_deg, int pfree ) ; PRIVATE void order_children ( int n_col, ColInfo Col [], int p [] ) ; PRIVATE void detect_super_cols ( #ifndef NDEBUG int n_col, RowInfo Row [], #endif ColInfo Col [], int A [], int head [], int row_start, int row_length ) ; PRIVATE int garbage_collection ( int n_row, int n_col, RowInfo Row [], ColInfo Col [], int A [], int *pfree ) ; PRIVATE int clear_mark ( int n_row, RowInfo Row [] ) ; /* ========================================================================== */ /* === Debugging definitions ================================================ */ /* ========================================================================== */ #ifndef NDEBUG /* === With debugging ======================================================= */ /* stdlib.h: for getenv and atoi, to get debugging level from environment */ #include <stdlib.h> /* stdio.h: for printf (no printing if debugging is turned off) */ #include <stdio.h> PRIVATE void debug_deg_lists ( int n_row, int n_col, RowInfo Row [], ColInfo Col [], int head [], int min_score, int should, int max_deg ) ; PRIVATE void debug_mark ( int n_row, RowInfo Row [], int tag_mark, int max_mark ) ; PRIVATE void debug_matrix ( int n_row, int n_col, RowInfo Row [], ColInfo Col [], int A [] ) ; PRIVATE void debug_structures ( int n_row, int n_col, RowInfo Row [], ColInfo Col [], int A [], int n_col2 ) ; /* the following is the *ONLY* global variable in this file, and is only */ /* present when debugging */ PRIVATE int debug_colamd ; /* debug print level */ #define DEBUG0(params) { (void) printf params ; } #define DEBUG1(params) { if (debug_colamd >= 1) (void) printf params ; } #define DEBUG2(params) { if (debug_colamd >= 2) (void) printf params ; } #define DEBUG3(params) { if (debug_colamd >= 3) (void) printf params ; } #define DEBUG4(params) { if (debug_colamd >= 4) (void) printf params ; } #else /* === No debugging ========================================================= */ #define DEBUG0(params) ; #define DEBUG1(params) ; #define DEBUG2(params) ; #define DEBUG3(params) ; #define DEBUG4(params) ; #endif /* ========================================================================== */ /* ========================================================================== */ /* === USER-CALLABLE ROUTINES: ============================================== */ /* ========================================================================== */ /* ========================================================================== */ /* === colamd_recommended =================================================== */ /* ========================================================================== */ /* The colamd_recommended routine returns the suggested size for Alen. This value has been determined to provide good balance between the number of garbage collections and the memory requirements for colamd. */ PUBLIC int colamd_recommended /* returns recommended value of Alen. */ ( /* === Parameters ======================================================= */ int nnz, /* number of nonzeros in A */ int n_row, /* number of rows in A */ int n_col /* number of columns in A */ ) { /* === Local variables ================================================== */ int minimum ; /* bare minimum requirements */ int recommended ; /* recommended value of Alen */ if (nnz < 0 || n_row < 0 || n_col < 0) { /* return -1 if any input argument is corrupted */ DEBUG0 (("colamd_recommended error!")) ; DEBUG0 ((" nnz: %d, n_row: %d, n_col: %d\n", nnz, n_row, n_col)) ; return (-1) ; } minimum = 2 * (nnz) /* for A */ + (((n_col) + 1) * sizeof (ColInfo) / sizeof (int)) /* for Col */ + (((n_row) + 1) * sizeof (RowInfo) / sizeof (int)) /* for Row */ + n_col /* minimum elbow room to guarrantee success */ + COLAMD_STATS ; /* for output statistics */ /* recommended is equal to the minumum plus enough memory to keep the */ /* number garbage collections low */ recommended = minimum + nnz/5 ; return (recommended) ; } /* ========================================================================== */ /* === colamd_set_defaults ================================================== */ /* ========================================================================== */ /* The colamd_set_defaults routine sets the default values of the user- controllable parameters for colamd: knobs [0] rows with knobs[0]*n_col entries or more are removed prior to ordering. knobs [1] columns with knobs[1]*n_row entries or more are removed prior to ordering, and placed last in the column permutation. knobs [2..19] unused, but future versions might use this */ PUBLIC void colamd_set_defaults ( /* === Parameters ======================================================= */ double knobs [COLAMD_KNOBS] /* knob array */ ) { /* === Local variables ================================================== */ int i ; if (!knobs) { return ; /* no knobs to initialize */ } for (i = 0 ; i < COLAMD_KNOBS ; i++) { knobs [i] = 0 ; } knobs [COLAMD_DENSE_ROW] = 0.5 ; /* ignore rows over 50% dense */ knobs [COLAMD_DENSE_COL] = 0.5 ; /* ignore columns over 50% dense */ } /* ========================================================================== */ /* === colamd =============================================================== */ /* ========================================================================== */ /* The colamd routine computes a column ordering Q of a sparse matrix A such that the LU factorization P(AQ) = LU remains sparse, where P is selected via partial pivoting. The routine can also be viewed as providing a permutation Q such that the Cholesky factorization (AQ)'(AQ) = LL' remains sparse. On input, the nonzero patterns of the columns of A are stored in the array A, in order 0 to n_col-1. A is held in 0-based form (rows in the range 0 to n_row-1 and columns in the range 0 to n_col-1). Row indices for column c are located in A [(p [c]) ... (p [c+1]-1)], where p [0] = 0, and thus p [n_col] is the number of entries in A. The matrix is destroyed on output. The row indices within each column do not have to be sorted (from small to large row indices), and duplicate row indices may be present. However, colamd will work a little faster if columns are sorted and no duplicates are present. Matlab 5.2 always passes the matrix with sorted columns, and no duplicates. The integer array A is of size Alen. Alen must be at least of size (where nnz is the number of entries in A): nnz for the input column form of A + nnz for a row form of A that colamd generates + 6*(n_col+1) for a ColInfo Col [0..n_col] array (this assumes sizeof (ColInfo) is 6 int's). + 4*(n_row+1) for a RowInfo Row [0..n_row] array (this assumes sizeof (RowInfo) is 4 int's). + elbow_room must be at least n_col. We recommend at least nnz/5 in addition to that. If sufficient, changes in the elbow room affect the ordering time only, not the ordering itself. + COLAMD_STATS for the output statistics Colamd returns FALSE is memory is insufficient, or TRUE otherwise. On input, the caller must specify: n_row the number of rows of A n_col the number of columns of A Alen the size of the array A A [0 ... nnz-1] the row indices, where nnz = p [n_col] A [nnz ... Alen-1] (need not be initialized by the user) p [0 ... n_col] the column pointers, p [0] = 0, and p [n_col] is the number of entries in A. Column c of A is stored in A [p [c] ... p [c+1]-1]. knobs [0 ... 19] a set of parameters that control the behavior of colamd. If knobs is a NULL pointer the defaults are used. The user-callable colamd_set_defaults routine sets the default parameters. See that routine for a description of the user-controllable parameters. If the return value of Colamd is TRUE, then on output: p [0 ... n_col-1] the column permutation. p [0] is the first column index, and p [n_col-1] is the last. That is, p [k] = j means that column j of A is the kth column of AQ. A is undefined on output (the matrix pattern is destroyed), except for the following statistics: A [0] the number of dense (or empty) rows ignored A [1] the number of dense (or empty) columms. These are ordered last, in their natural order. A [2] the number of garbage collections performed. If this is excessive, then you would have gotten your results faster if Alen was larger. A [3] 0, if all row indices in each column were in sorted order and no duplicates were present. 1, if there were unsorted or duplicate row indices in the input. You would have gotten your results faster if A [3] was returned as 0. If the return value of Colamd is FALSE, then A and p are undefined on output. */ PUBLIC int colamd /* returns TRUE if successful */ ( /* === Parameters ======================================================= */ int n_row, /* number of rows in A */ int n_col, /* number of columns in A */ int Alen, /* length of A */ int A [], /* row indices of A */ int p [], /* pointers to columns in A */ double knobs [COLAMD_KNOBS] /* parameters (uses defaults if NULL) */ ) { /* === Local variables ================================================== */ int i ; /* loop index */ int nnz ; /* nonzeros in A */ int Row_size ; /* size of Row [], in integers */ int Col_size ; /* size of Col [], in integers */ int elbow_room ; /* remaining free space */ RowInfo *Row ; /* pointer into A of Row [0..n_row] array */ ColInfo *Col ; /* pointer into A of Col [0..n_col] array */ int n_col2 ; /* number of non-dense, non-empty columns */ int n_row2 ; /* number of non-dense, non-empty rows */ int ngarbage ; /* number of garbage collections performed */ int max_deg ; /* maximum row degree */ double default_knobs [COLAMD_KNOBS] ; /* default knobs knobs array */ int init_result ; /* return code from initialization */ #ifndef NDEBUG debug_colamd = 0 ; /* no debug printing */ /* get "D" environment variable, which gives the debug printing level */ if (getenv ("D")) debug_colamd = atoi (getenv ("D")) ; DEBUG0 (("debug version, D = %d (THIS WILL BE SLOOOOW!)\n", debug_colamd)) ; #endif /* === Check the input arguments ======================================== */ if (n_row < 0 || n_col < 0 || !A || !p) { /* n_row and n_col must be non-negative, A and p must be present */ DEBUG0 (("colamd error! %d %d %d\n", n_row, n_col, Alen)) ; return (FALSE) ; } nnz = p [n_col] ; if (nnz < 0 || p [0] != 0) { /* nnz must be non-negative, and p [0] must be zero */ DEBUG0 (("colamd error! %d %d\n", nnz, p [0])) ; return (FALSE) ; } /* === If no knobs, set default parameters ============================== */ if (!knobs) { knobs = default_knobs ; colamd_set_defaults (knobs) ; } /* === Allocate the Row and Col arrays from array A ===================== */ Col_size = (n_col + 1) * sizeof (ColInfo) / sizeof (int) ; Row_size = (n_row + 1) * sizeof (RowInfo) / sizeof (int) ; elbow_room = Alen - (2*nnz + Col_size + Row_size) ; if (elbow_room < n_col + COLAMD_STATS) { /* not enough space in array A to perform the ordering */ DEBUG0 (("colamd error! elbow_room %d, %d\n", elbow_room,n_col)) ; return (FALSE) ; } Alen = 2*nnz + elbow_room ; Col = (ColInfo *) &A [Alen] ; Row = (RowInfo *) &A [Alen + Col_size] ; /* === Construct the row and column data structures ===================== */ init_result = init_rows_cols (n_row, n_col, Row, Col, A, p) ; if (init_result == -1) { /* input matrix is invalid */ DEBUG0 (("colamd error! matrix invalid\n")) ; return (FALSE) ; } /* === Initialize scores, kill dense rows/columns ======================= */ init_scoring (n_row, n_col, Row, Col, A, p, knobs, &n_row2, &n_col2, &max_deg) ; /* === Order the supercolumns =========================================== */ ngarbage = find_ordering (n_row, n_col, Alen, Row, Col, A, p, n_col2, max_deg, 2*nnz) ; /* === Order the non-principal columns ================================== */ order_children (n_col, Col, p) ; /* === Return statistics in A =========================================== */ for (i = 0 ; i < COLAMD_STATS ; i++) { A [i] = 0 ; } A [COLAMD_DENSE_ROW] = n_row - n_row2 ; A [COLAMD_DENSE_COL] = n_col - n_col2 ; A [COLAMD_DEFRAG_COUNT] = ngarbage ; A [COLAMD_JUMBLED_COLS] = init_result ; return (TRUE) ; } /* ========================================================================== */ /* === NON-USER-CALLABLE ROUTINES: ========================================== */ /* ========================================================================== */ /* There are no user-callable routines beyond this point in the file */ /* ========================================================================== */ /* === init_rows_cols ======================================================= */ /* ========================================================================== */ /* Takes the column form of the matrix in A and creates the row form of the matrix. Also, row and column attributes are stored in the Col and Row structs. If the columns are un-sorted or contain duplicate row indices, this routine will also sort and remove duplicate row indices from the column form of the matrix. Returns -1 on error, 1 if columns jumbled, or 0 if columns not jumbled. Not user-callable. */ PRIVATE int init_rows_cols /* returns status code */ ( /* === Parameters ======================================================= */ int n_row, /* number of rows of A */ int n_col, /* number of columns of A */ RowInfo Row [], /* of size n_row+1 */ ColInfo Col [], /* of size n_col+1 */ int A [], /* row indices of A, of size Alen */ int p [] /* pointers to columns in A, of size n_col+1 */ ) { /* === Local variables ================================================== */ int col ; /* a column index */ int row ; /* a row index */ int *cp ; /* a column pointer */ int *cp_end ; /* a pointer to the end of a column */ int *rp ; /* a row pointer */ int *rp_end ; /* a pointer to the end of a row */ int last_start ; /* start index of previous column in A */ int start ; /* start index of column in A */ int last_row ; /* previous row */ int jumbled_columns ; /* indicates if columns are jumbled */ /* === Initialize columns, and check column pointers ==================== */ last_start = 0 ; for (col = 0 ; col < n_col ; col++) { start = p [col] ; if (start < last_start) { /* column pointers must be non-decreasing */ DEBUG0 (("colamd error! last p %d p [col] %d\n",last_start,start)); return (-1) ; } Col [col].start = start ; Col [col].length = p [col+1] - start ; Col [col].shared1.thickness = 1 ; Col [col].shared2.score = 0 ; Col [col].shared3.prev = EMPTY ; Col [col].shared4.degree_next = EMPTY ; last_start = start ; } /* must check the end pointer for last column */ if (p [n_col] < last_start) { /* column pointers must be non-decreasing */ DEBUG0 (("colamd error! last p %d p [n_col] %d\n",p[col],last_start)) ; return (-1) ; } /* p [0..n_col] no longer needed, used as "head" in subsequent routines */ /* === Scan columns, compute row degrees, and check row indices ========= */ jumbled_columns = FALSE ; for (row = 0 ; row < n_row ; row++) { Row [row].length = 0 ; Row [row].shared2.mark = -1 ; } for (col = 0 ; col < n_col ; col++) { last_row = -1 ; cp = &A [p [col]] ; cp_end = &A [p [col+1]] ; while (cp < cp_end) { row = *cp++ ; /* make sure row indices within range */ if (row < 0 || row >= n_row) { DEBUG0 (("colamd error! col %d row %d last_row %d\n", col, row, last_row)) ; return (-1) ; } else if (row <= last_row) { /* row indices are not sorted or repeated, thus cols */ /* are jumbled */ jumbled_columns = TRUE ; } /* prevent repeated row from being counted */ if (Row [row].shared2.mark != col) { Row [row].length++ ; Row [row].shared2.mark = col ; last_row = row ; } else { /* this is a repeated entry in the column, */ /* it will be removed */ Col [col].length-- ; } } } /* === Compute row pointers ============================================= */ /* row form of the matrix starts directly after the column */ /* form of matrix in A */ Row [0].start = p [n_col] ; Row [0].shared1.p = Row [0].start ; Row [0].shared2.mark = -1 ; for (row = 1 ; row < n_row ; row++) { Row [row].start = Row [row-1].start + Row [row-1].length ; Row [row].shared1.p = Row [row].start ; Row [row].shared2.mark = -1 ; } /* === Create row form ================================================== */ if (jumbled_columns) { /* if cols jumbled, watch for repeated row indices */ for (col = 0 ; col < n_col ; col++) { cp = &A [p [col]] ; cp_end = &A [p [col+1]] ; while (cp < cp_end) { row = *cp++ ; if (Row [row].shared2.mark != col) { A [(Row [row].shared1.p)++] = col ; Row [row].shared2.mark = col ; } } } } else { /* if cols not jumbled, we don't need the mark (this is faster) */ for (col = 0 ; col < n_col ; col++) { cp = &A [p [col]] ; cp_end = &A [p [col+1]] ; while (cp < cp_end) { A [(Row [*cp++].shared1.p)++] = col ; } } } /* === Clear the row marks and set row degrees ========================== */ for (row = 0 ; row < n_row ; row++) { Row [row].shared2.mark = 0 ; Row [row].shared1.degree = Row [row].length ; } /* === See if we need to re-create columns ============================== */ if (jumbled_columns) { #ifndef NDEBUG /* make sure column lengths are correct */ for (col = 0 ; col < n_col ; col++) { p [col] = Col [col].length ; } for (row = 0 ; row < n_row ; row++) { rp = &A [Row [row].start] ; rp_end = rp + Row [row].length ; while (rp < rp_end) { p [*rp++]-- ; } } for (col = 0 ; col < n_col ; col++) { assert (p [col] == 0) ; } /* now p is all zero (different than when debugging is turned off) */ #endif /* === Compute col pointers ========================================= */ /* col form of the matrix starts at A [0]. */ /* Note, we may have a gap between the col form and the row */ /* form if there were duplicate entries, if so, it will be */ /* removed upon the first garbage collection */ Col [0].start = 0 ; p [0] = Col [0].start ; for (col = 1 ; col < n_col ; col++) { /* note that the lengths here are for pruned columns, i.e. */ /* no duplicate row indices will exist for these columns */ Col [col].start = Col [col-1].start + Col [col-1].length ; p [col] = Col [col].start ; } /* === Re-create col form =========================================== */ for (row = 0 ; row < n_row ; row++) { rp = &A [Row [row].start] ; rp_end = rp + Row [row].length ; while (rp < rp_end) { A [(p [*rp++])++] = row ; } } return (1) ; } else { /* no columns jumbled (this is faster) */ return (0) ; } } /* ========================================================================== */ /* === init_scoring ========================================================= */ /* ========================================================================== */ /* Kills dense or empty columns and rows, calculates an initial score for each column, and places all columns in the degree lists. Not user-callable. */ PRIVATE void init_scoring ( /* === Parameters ======================================================= */ int n_row, /* number of rows of A */ int n_col, /* number of columns of A */ RowInfo Row [], /* of size n_row+1 */ ColInfo Col [], /* of size n_col+1 */ int A [], /* column form and row form of A */ int head [], /* of size n_col+1 */ double knobs [COLAMD_KNOBS],/* parameters */ int *p_n_row2, /* number of non-dense, non-empty rows */ int *p_n_col2, /* number of non-dense, non-empty columns */ int *p_max_deg /* maximum row degree */ ) { /* === Local variables ================================================== */ int c ; /* a column index */ int r, row ; /* a row index */ int *cp ; /* a column pointer */ int deg ; /* degree (# entries) of a row or column */ int *cp_end ; /* a pointer to the end of a column */ int *new_cp ; /* new column pointer */ int col_length ; /* length of pruned column */ int score ; /* current column score */ int n_col2 ; /* number of non-dense, non-empty columns */ int n_row2 ; /* number of non-dense, non-empty rows */ int dense_row_count ; /* remove rows with more entries than this */ int dense_col_count ; /* remove cols with more entries than this */ int min_score ; /* smallest column score */ int max_deg ; /* maximum row degree */ int next_col ; /* Used to add to degree list.*/ #ifndef NDEBUG int debug_count ; /* debug only. */ #endif /* === Extract knobs ==================================================== */ dense_row_count = MAX (0, MIN (knobs [COLAMD_DENSE_ROW] * n_col, n_col)) ; dense_col_count = MAX (0, MIN (knobs [COLAMD_DENSE_COL] * n_row, n_row)) ; DEBUG0 (("densecount: %d %d\n", dense_row_count, dense_col_count)) ; max_deg = 0 ; n_col2 = n_col ; n_row2 = n_row ; /* === Kill empty columns =============================================== */ /* Put the empty columns at the end in their natural, so that LU */ /* factorization can proceed as far as possible. */ for (c = n_col-1 ; c >= 0 ; c--) { deg = Col [c].length ; if (deg == 0) { /* this is a empty column, kill and order it last */ Col [c].shared2.order = --n_col2 ; KILL_PRINCIPAL_COL (c) ; } } DEBUG0 (("null columns killed: %d\n", n_col - n_col2)) ; /* === Kill dense columns =============================================== */ /* Put the dense columns at the end, in their natural order */ for (c = n_col-1 ; c >= 0 ; c--) { /* skip any dead columns */ if (COL_IS_DEAD (c)) { continue ; } deg = Col [c].length ; if (deg > dense_col_count) { /* this is a dense column, kill and order it last */ Col [c].shared2.order = --n_col2 ; /* decrement the row degrees */ cp = &A [Col [c].start] ; cp_end = cp + Col [c].length ; while (cp < cp_end) { Row [*cp++].shared1.degree-- ; } KILL_PRINCIPAL_COL (c) ; } } DEBUG0 (("Dense and null columns killed: %d\n", n_col - n_col2)) ; /* === Kill dense and empty rows ======================================== */ for (r = 0 ; r < n_row ; r++) { deg = Row [r].shared1.degree ; assert (deg >= 0 && deg <= n_col) ; if (deg > dense_row_count || deg == 0) { /* kill a dense or empty row */ KILL_ROW (r) ; --n_row2 ; } else { /* keep track of max degree of remaining rows */ max_deg = MAX (max_deg, deg) ; } } DEBUG0 (("Dense and null rows killed: %d\n", n_row - n_row2)) ; /* === Compute initial column scores ==================================== */ /* At this point the row degrees are accurate. They reflect the number */ /* of "live" (non-dense) columns in each row. No empty rows exist. */ /* Some "live" columns may contain only dead rows, however. These are */ /* pruned in the code below. */ /* now find the initial matlab score for each column */ for (c = n_col-1 ; c >= 0 ; c--) { /* skip dead column */ if (COL_IS_DEAD (c)) { continue ; } score = 0 ; cp = &A [Col [c].start] ; new_cp = cp ; cp_end = cp + Col [c].length ; while (cp < cp_end) { /* get a row */ row = *cp++ ; /* skip if dead */ if (ROW_IS_DEAD (row)) { continue ; } /* compact the column */ *new_cp++ = row ; /* add row's external degree */ score += Row [row].shared1.degree - 1 ; /* guard against integer overflow */ score = MIN (score, n_col) ; } /* determine pruned column length */ col_length = (int) (new_cp - &A [Col [c].start]) ; if (col_length == 0) { /* a newly-made null column (all rows in this col are "dense" */ /* and have already been killed) */ DEBUG0 (("Newly null killed: %d\n", c)) ; Col [c].shared2.order = --n_col2 ; KILL_PRINCIPAL_COL (c) ; } else { /* set column length and set score */ assert (score >= 0) ; assert (score <= n_col) ; Col [c].length = col_length ; Col [c].shared2.score = score ; } } DEBUG0 (("Dense, null, and newly-null columns killed: %d\n",n_col-n_col2)) ; /* At this point, all empty rows and columns are dead. All live columns */ /* are "clean" (containing no dead rows) and simplicial (no supercolumns */ /* yet). Rows may contain dead columns, but all live rows contain at */ /* least one live column. */ #ifndef NDEBUG debug_structures (n_row, n_col, Row, Col, A, n_col2) ; #endif /* === Initialize degree lists ========================================== */ #ifndef NDEBUG debug_count = 0 ; #endif /* clear the hash buckets */ for (c = 0 ; c <= n_col ; c++) { head [c] = EMPTY ; } min_score = n_col ; /* place in reverse order, so low column indices are at the front */ /* of the lists. This is to encourage natural tie-breaking */ for (c = n_col-1 ; c >= 0 ; c--) { /* only add principal columns to degree lists */ if (COL_IS_ALIVE (c)) { DEBUG4 (("place %d score %d minscore %d ncol %d\n", c, Col [c].shared2.score, min_score, n_col)) ; /* === Add columns score to DList =============================== */ score = Col [c].shared2.score ; assert (min_score >= 0) ; assert (min_score <= n_col) ; assert (score >= 0) ; assert (score <= n_col) ; assert (head [score] >= EMPTY) ; /* now add this column to dList at proper score location */ next_col = head [score] ; Col [c].shared3.prev = EMPTY ; Col [c].shared4.degree_next = next_col ; /* if there already was a column with the same score, set its */ /* previous pointer to this new column */ if (next_col != EMPTY) { Col [next_col].shared3.prev = c ; } head [score] = c ; /* see if this score is less than current min */ min_score = MIN (min_score, score) ; #ifndef NDEBUG debug_count++ ; #endif } } #ifndef NDEBUG DEBUG0 (("Live cols %d out of %d, non-princ: %d\n", debug_count, n_col, n_col-debug_count)) ; assert (debug_count == n_col2) ; debug_deg_lists (n_row, n_col, Row, Col, head, min_score, n_col2, max_deg) ; #endif /* === Return number of remaining columns, and max row degree =========== */ *p_n_col2 = n_col2 ; *p_n_row2 = n_row2 ; *p_max_deg = max_deg ; } /* ========================================================================== */ /* === find_ordering ======================================================== */ /* ========================================================================== */ /* Order the principal columns of the supercolumn form of the matrix (no supercolumns on input). Uses a minimum approximate column minimum degree ordering method. Not user-callable. */ PRIVATE int find_ordering /* return the number of garbage collections */ ( /* === Parameters ======================================================= */ int n_row, /* number of rows of A */ int n_col, /* number of columns of A */ int Alen, /* size of A, 2*nnz + elbow_room or larger */ RowInfo Row [], /* of size n_row+1 */ ColInfo Col [], /* of size n_col+1 */ int A [], /* column form and row form of A */ int head [], /* of size n_col+1 */ int n_col2, /* Remaining columns to order */ int max_deg, /* Maximum row degree */ int pfree /* index of first free slot (2*nnz on entry) */ ) { /* === Local variables ================================================== */ int k ; /* current pivot ordering step */ int pivot_col ; /* current pivot column */ int *cp ; /* a column pointer */ int *rp ; /* a row pointer */ int pivot_row ; /* current pivot row */ int *new_cp ; /* modified column pointer */ int *new_rp ; /* modified row pointer */ int pivot_row_start ; /* pointer to start of pivot row */ int pivot_row_degree ; /* # of columns in pivot row */ int pivot_row_length ; /* # of supercolumns in pivot row */ int pivot_col_score ; /* score of pivot column */ int needed_memory ; /* free space needed for pivot row */ int *cp_end ; /* pointer to the end of a column */ int *rp_end ; /* pointer to the end of a row */ int row ; /* a row index */ int col ; /* a column index */ int max_score ; /* maximum possible score */ int cur_score ; /* score of current column */ unsigned int hash ; /* hash value for supernode detection */ int head_column ; /* head of hash bucket */ int first_col ; /* first column in hash bucket */ int tag_mark ; /* marker value for mark array */ int row_mark ; /* Row [row].shared2.mark */ int set_difference ; /* set difference size of row with pivot row */ int min_score ; /* smallest column score */ int col_thickness ; /* "thickness" (# of columns in a supercol) */ int max_mark ; /* maximum value of tag_mark */ int pivot_col_thickness ; /* number of columns represented by pivot col */ int prev_col ; /* Used by Dlist operations. */ int next_col ; /* Used by Dlist operations. */ int ngarbage ; /* number of garbage collections performed */ #ifndef NDEBUG int debug_d ; /* debug loop counter */ int debug_step = 0 ; /* debug loop counter */ #endif /* === Initialization and clear mark ==================================== */ max_mark = INT_MAX - n_col ; /* INT_MAX defined in <limits.h> */ tag_mark = clear_mark (n_row, Row) ; min_score = 0 ; ngarbage = 0 ; DEBUG0 (("Ordering.. n_col2=%d\n", n_col2)) ; /* === Order the columns ================================================ */ for (k = 0 ; k < n_col2 ; /* 'k' is incremented below */) { #ifndef NDEBUG if (debug_step % 100 == 0) { DEBUG0 (("\n... Step k: %d out of n_col2: %d\n", k, n_col2)) ; } else { DEBUG1 (("\n----------Step k: %d out of n_col2: %d\n", k, n_col2)) ; } debug_step++ ; debug_deg_lists (n_row, n_col, Row, Col, head, min_score, n_col2-k, max_deg) ; debug_matrix (n_row, n_col, Row, Col, A) ; #endif /* === Select pivot column, and order it ============================ */ /* make sure degree list isn't empty */ assert (min_score >= 0) ; assert (min_score <= n_col) ; assert (head [min_score] >= EMPTY) ; #ifndef NDEBUG for (debug_d = 0 ; debug_d < min_score ; debug_d++) { assert (head [debug_d] == EMPTY) ; } #endif /* get pivot column from head of minimum degree list */ while (head [min_score] == EMPTY && min_score < n_col) { min_score++ ; } pivot_col = head [min_score] ; assert (pivot_col >= 0 && pivot_col <= n_col) ; next_col = Col [pivot_col].shared4.degree_next ; head [min_score] = next_col ; if (next_col != EMPTY) { Col [next_col].shared3.prev = EMPTY ; } assert (COL_IS_ALIVE (pivot_col)) ; DEBUG3 (("Pivot col: %d\n", pivot_col)) ; /* remember score for defrag check */ pivot_col_score = Col [pivot_col].shared2.score ; /* the pivot column is the kth column in the pivot order */ Col [pivot_col].shared2.order = k ; /* increment order count by column thickness */ pivot_col_thickness = Col [pivot_col].shared1.thickness ; k += pivot_col_thickness ; assert (pivot_col_thickness > 0) ; /* === Garbage_collection, if necessary ============================= */ needed_memory = MIN (pivot_col_score, n_col - k) ; if (pfree + needed_memory >= Alen) { pfree = garbage_collection (n_row, n_col, Row, Col, A, &A [pfree]) ; ngarbage++ ; /* after garbage collection we will have enough */ assert (pfree + needed_memory < Alen) ; /* garbage collection has wiped out the Row[].shared2.mark array */ tag_mark = clear_mark (n_row, Row) ; #ifndef NDEBUG debug_matrix (n_row, n_col, Row, Col, A) ; #endif } /* === Compute pivot row pattern ==================================== */ /* get starting location for this new merged row */ pivot_row_start = pfree ; /* initialize new row counts to zero */ pivot_row_degree = 0 ; /* tag pivot column as having been visited so it isn't included */ /* in merged pivot row */ Col [pivot_col].shared1.thickness = -pivot_col_thickness ; /* pivot row is the union of all rows in the pivot column pattern */ cp = &A [Col [pivot_col].start] ; cp_end = cp + Col [pivot_col].length ; while (cp < cp_end) { /* get a row */ row = *cp++ ; DEBUG4 (("Pivot col pattern %d %d\n", ROW_IS_ALIVE (row), row)) ; /* skip if row is dead */ if (ROW_IS_DEAD (row)) { continue ; } rp = &A [Row [row].start] ; rp_end = rp + Row [row].length ; while (rp < rp_end) { /* get a column */ col = *rp++ ; /* add the column, if alive and untagged */ col_thickness = Col [col].shared1.thickness ; if (col_thickness > 0 && COL_IS_ALIVE (col)) { /* tag column in pivot row */ Col [col].shared1.thickness = -col_thickness ; assert (pfree < Alen) ; /* place column in pivot row */ A [pfree++] = col ; pivot_row_degree += col_thickness ; } } } /* clear tag on pivot column */ Col [pivot_col].shared1.thickness = pivot_col_thickness ; max_deg = MAX (max_deg, pivot_row_degree) ; #ifndef NDEBUG DEBUG3 (("check2\n")) ; debug_mark (n_row, Row, tag_mark, max_mark) ; #endif /* === Kill all rows used to construct pivot row ==================== */ /* also kill pivot row, temporarily */ cp = &A [Col [pivot_col].start] ; cp_end = cp + Col [pivot_col].length ; while (cp < cp_end) { /* may be killing an already dead row */ row = *cp++ ; DEBUG2 (("Kill row in pivot col: %d\n", row)) ; KILL_ROW (row) ; } /* === Select a row index to use as the new pivot row =============== */ pivot_row_length = pfree - pivot_row_start ; if (pivot_row_length > 0) { /* pick the "pivot" row arbitrarily (first row in col) */ pivot_row = A [Col [pivot_col].start] ; DEBUG2 (("Pivotal row is %d\n", pivot_row)) ; } else { /* there is no pivot row, since it is of zero length */ pivot_row = EMPTY ; assert (pivot_row_length == 0) ; } assert (Col [pivot_col].length > 0 || pivot_row_length == 0) ; /* === Approximate degree computation =============================== */ /* Here begins the computation of the approximate degree. The column */ /* score is the sum of the pivot row "length", plus the size of the */ /* set differences of each row in the column minus the pattern of the */ /* pivot row itself. The column ("thickness") itself is also */ /* excluded from the column score (we thus use an approximate */ /* external degree). */ /* The time taken by the following code (compute set differences, and */ /* add them up) is proportional to the size of the data structure */ /* being scanned - that is, the sum of the sizes of each column in */ /* the pivot row. Thus, the amortized time to compute a column score */ /* is proportional to the size of that column (where size, in this */ /* context, is the column "length", or the number of row indices */ /* in that column). The number of row indices in a column is */ /* monotonically non-decreasing, from the length of the original */ /* column on input to colamd. */ /* === Compute set differences ====================================== */ DEBUG1 (("** Computing set differences phase. **\n")) ; /* pivot row is currently dead - it will be revived later. */ DEBUG2 (("Pivot row: ")) ; /* for each column in pivot row */ rp = &A [pivot_row_start] ; rp_end = rp + pivot_row_length ; while (rp < rp_end) { col = *rp++ ; assert (COL_IS_ALIVE (col) && col != pivot_col) ; DEBUG2 (("Col: %d\n", col)) ; /* clear tags used to construct pivot row pattern */ col_thickness = -Col [col].shared1.thickness ; assert (col_thickness > 0) ; Col [col].shared1.thickness = col_thickness ; /* === Remove column from degree list =========================== */ cur_score = Col [col].shared2.score ; prev_col = Col [col].shared3.prev ; next_col = Col [col].shared4.degree_next ; assert (cur_score >= 0) ; assert (cur_score <= n_col) ; assert (cur_score >= EMPTY) ; if (prev_col == EMPTY) { head [cur_score] = next_col ; } else { Col [prev_col].shared4.degree_next = next_col ; } if (next_col != EMPTY) { Col [next_col].shared3.prev = prev_col ; } /* === Scan the column ========================================== */ cp = &A [Col [col].start] ; cp_end = cp + Col [col].length ; while (cp < cp_end) { /* get a row */ row = *cp++ ; row_mark = Row [row].shared2.mark ; /* skip if dead */ if (ROW_IS_MARKED_DEAD (row_mark)) { continue ; } assert (row != pivot_row) ; set_difference = row_mark - tag_mark ; /* check if the row has been seen yet */ if (set_difference < 0) { assert (Row [row].shared1.degree <= max_deg) ; set_difference = Row [row].shared1.degree ; } /* subtract column thickness from this row's set difference */ set_difference -= col_thickness ; assert (set_difference >= 0) ; /* absorb this row if the set difference becomes zero */ if (set_difference == 0) { DEBUG1 (("aggressive absorption. Row: %d\n", row)) ; KILL_ROW (row) ; } else { /* save the new mark */ Row [row].shared2.mark = set_difference + tag_mark ; } } } #ifndef NDEBUG debug_deg_lists (n_row, n_col, Row, Col, head, min_score, n_col2-k-pivot_row_degree, max_deg) ; #endif /* === Add up set differences for each column ======================= */ DEBUG1 (("** Adding set differences phase. **\n")) ; /* for each column in pivot row */ rp = &A [pivot_row_start] ; rp_end = rp + pivot_row_length ; while (rp < rp_end) { /* get a column */ col = *rp++ ; assert (COL_IS_ALIVE (col) && col != pivot_col) ; hash = 0 ; cur_score = 0 ; cp = &A [Col [col].start] ; /* compact the column */ new_cp = cp ; cp_end = cp + Col [col].length ; DEBUG2 (("Adding set diffs for Col: %d.\n", col)) ; while (cp < cp_end) { /* get a row */ row = *cp++ ; assert(row >= 0 && row < n_row) ; row_mark = Row [row].shared2.mark ; /* skip if dead */ if (ROW_IS_MARKED_DEAD (row_mark)) { continue ; } assert (row_mark > tag_mark) ; /* compact the column */ *new_cp++ = row ; /* compute hash function */ hash += row ; /* add set difference */ cur_score += row_mark - tag_mark ; /* integer overflow... */ cur_score = MIN (cur_score, n_col) ; } /* recompute the column's length */ Col [col].length = (int) (new_cp - &A [Col [col].start]) ; /* === Further mass elimination ================================= */ if (Col [col].length == 0) { DEBUG1 (("further mass elimination. Col: %d\n", col)) ; /* nothing left but the pivot row in this column */ KILL_PRINCIPAL_COL (col) ; pivot_row_degree -= Col [col].shared1.thickness ; assert (pivot_row_degree >= 0) ; /* order it */ Col [col].shared2.order = k ; /* increment order count by column thickness */ k += Col [col].shared1.thickness ; } else { /* === Prepare for supercolumn detection ==================== */ DEBUG2 (("Preparing supercol detection for Col: %d.\n", col)) ; /* save score so far */ Col [col].shared2.score = cur_score ; /* add column to hash table, for supercolumn detection */ hash %= n_col + 1 ; DEBUG2 ((" Hash = %d, n_col = %d.\n", hash, n_col)) ; assert (hash <= n_col) ; head_column = head [hash] ; if (head_column > EMPTY) { /* degree list "hash" is non-empty, use prev (shared3) of */ /* first column in degree list as head of hash bucket */ first_col = Col [head_column].shared3.headhash ; Col [head_column].shared3.headhash = col ; } else { /* degree list "hash" is empty, use head as hash bucket */ first_col = - (head_column + 2) ; head [hash] = - (col + 2) ; } Col [col].shared4.hash_next = first_col ; /* save hash function in Col [col].shared3.hash */ Col [col].shared3.hash = (int) hash ; assert (COL_IS_ALIVE (col)) ; } } /* The approximate external column degree is now computed. */ /* === Supercolumn detection ======================================== */ DEBUG1 (("** Supercolumn detection phase. **\n")) ; detect_super_cols ( #ifndef NDEBUG n_col, Row, #endif Col, A, head, pivot_row_start, pivot_row_length) ; /* === Kill the pivotal column ====================================== */ KILL_PRINCIPAL_COL (pivot_col) ; /* === Clear mark =================================================== */ tag_mark += (max_deg + 1) ; if (tag_mark >= max_mark) { DEBUG1 (("clearing tag_mark\n")) ; tag_mark = clear_mark (n_row, Row) ; } #ifndef NDEBUG DEBUG3 (("check3\n")) ; debug_mark (n_row, Row, tag_mark, max_mark) ; #endif /* === Finalize the new pivot row, and column scores ================ */ DEBUG1 (("** Finalize scores phase. **\n")) ; /* for each column in pivot row */ rp = &A [pivot_row_start] ; /* compact the pivot row */ new_rp = rp ; rp_end = rp + pivot_row_length ; while (rp < rp_end) { col = *rp++ ; /* skip dead columns */ if (COL_IS_DEAD (col)) { continue ; } *new_rp++ = col ; /* add new pivot row to column */ A [Col [col].start + (Col [col].length++)] = pivot_row ; /* retrieve score so far and add on pivot row's degree. */ /* (we wait until here for this in case the pivot */ /* row's degree was reduced due to mass elimination). */ cur_score = Col [col].shared2.score + pivot_row_degree ; /* calculate the max possible score as the number of */ /* external columns minus the 'k' value minus the */ /* columns thickness */ max_score = n_col - k - Col [col].shared1.thickness ; /* make the score the external degree of the union-of-rows */ cur_score -= Col [col].shared1.thickness ; /* make sure score is less or equal than the max score */ cur_score = MIN (cur_score, max_score) ; assert (cur_score >= 0) ; /* store updated score */ Col [col].shared2.score = cur_score ; /* === Place column back in degree list ========================= */ assert (min_score >= 0) ; assert (min_score <= n_col) ; assert (cur_score >= 0) ; assert (cur_score <= n_col) ; assert (head [cur_score] >= EMPTY) ; next_col = head [cur_score] ; Col [col].shared4.degree_next = next_col ; Col [col].shared3.prev = EMPTY ; if (next_col != EMPTY) { Col [next_col].shared3.prev = col ; } head [cur_score] = col ; /* see if this score is less than current min */ min_score = MIN (min_score, cur_score) ; } #ifndef NDEBUG debug_deg_lists (n_row, n_col, Row, Col, head, min_score, n_col2-k, max_deg) ; #endif /* === Resurrect the new pivot row ================================== */ if (pivot_row_degree > 0) { /* update pivot row length to reflect any cols that were killed */ /* during super-col detection and mass elimination */ Row [pivot_row].start = pivot_row_start ; Row [pivot_row].length = (int) (new_rp - &A[pivot_row_start]) ; Row [pivot_row].shared1.degree = pivot_row_degree ; Row [pivot_row].shared2.mark = 0 ; /* pivot row is no longer dead */ } } /* === All principal columns have now been ordered ====================== */ return (ngarbage) ; } /* ========================================================================== */ /* === order_children ======================================================= */ /* ========================================================================== */ /* The find_ordering routine has ordered all of the principal columns (the representatives of the supercolumns). The non-principal columns have not yet been ordered. This routine orders those columns by walking up the parent tree (a column is a child of the column which absorbed it). The final permutation vector is then placed in p [0 ... n_col-1], with p [0] being the first column, and p [n_col-1] being the last. It doesn't look like it at first glance, but be assured that this routine takes time linear in the number of columns. Although not immediately obvious, the time taken by this routine is O (n_col), that is, linear in the number of columns. Not user-callable. */ PRIVATE void order_children ( /* === Parameters ======================================================= */ int n_col, /* number of columns of A */ ColInfo Col [], /* of size n_col+1 */ int p [] /* p [0 ... n_col-1] is the column permutation*/ ) { /* === Local variables ================================================== */ int i ; /* loop counter for all columns */ int c ; /* column index */ int parent ; /* index of column's parent */ int order ; /* column's order */ /* === Order each non-principal column ================================== */ for (i = 0 ; i < n_col ; i++) { /* find an un-ordered non-principal column */ assert (COL_IS_DEAD (i)) ; if (!COL_IS_DEAD_PRINCIPAL (i) && Col [i].shared2.order == EMPTY) { parent = i ; /* once found, find its principal parent */ do { parent = Col [parent].shared1.parent ; } while (!COL_IS_DEAD_PRINCIPAL (parent)) ; /* now, order all un-ordered non-principal columns along path */ /* to this parent. collapse tree at the same time */ c = i ; /* get order of parent */ order = Col [parent].shared2.order ; do { assert (Col [c].shared2.order == EMPTY) ; /* order this column */ Col [c].shared2.order = order++ ; /* collaps tree */ Col [c].shared1.parent = parent ; /* get immediate parent of this column */ c = Col [c].shared1.parent ; /* continue until we hit an ordered column. There are */ /* guarranteed not to be anymore unordered columns */ /* above an ordered column */ } while (Col [c].shared2.order == EMPTY) ; /* re-order the super_col parent to largest order for this group */ Col [parent].shared2.order = order ; } } /* === Generate the permutation ========================================= */ for (c = 0 ; c < n_col ; c++) { p [Col [c].shared2.order] = c ; } } /* ========================================================================== */ /* === detect_super_cols ==================================================== */ /* ========================================================================== */ /* Detects supercolumns by finding matches between columns in the hash buckets. Check amongst columns in the set A [row_start ... row_start + row_length-1]. The columns under consideration are currently *not* in the degree lists, and have already been placed in the hash buckets. The hash bucket for columns whose hash function is equal to h is stored as follows: if head [h] is >= 0, then head [h] contains a degree list, so: head [h] is the first column in degree bucket h. Col [head [h]].headhash gives the first column in hash bucket h. otherwise, the degree list is empty, and: -(head [h] + 2) is the first column in hash bucket h. For a column c in a hash bucket, Col [c].shared3.prev is NOT a "previous column" pointer. Col [c].shared3.hash is used instead as the hash number for that column. The value of Col [c].shared4.hash_next is the next column in the same hash bucket. Assuming no, or "few" hash collisions, the time taken by this routine is linear in the sum of the sizes (lengths) of each column whose score has just been computed in the approximate degree computation. Not user-callable. */ PRIVATE void detect_super_cols ( /* === Parameters ======================================================= */ #ifndef NDEBUG /* these two parameters are only needed when debugging is enabled: */ int n_col, /* number of columns of A */ RowInfo Row [], /* of size n_row+1 */ #endif ColInfo Col [], /* of size n_col+1 */ int A [], /* row indices of A */ int head [], /* head of degree lists and hash buckets */ int row_start, /* pointer to set of columns to check */ int row_length /* number of columns to check */ ) { /* === Local variables ================================================== */ int hash ; /* hash # for a column */ int *rp ; /* pointer to a row */ int c ; /* a column index */ int super_c ; /* column index of the column to absorb into */ int *cp1 ; /* column pointer for column super_c */ int *cp2 ; /* column pointer for column c */ int length ; /* length of column super_c */ int prev_c ; /* column preceding c in hash bucket */ int i ; /* loop counter */ int *rp_end ; /* pointer to the end of the row */ int col ; /* a column index in the row to check */ int head_column ; /* first column in hash bucket or degree list */ int first_col ; /* first column in hash bucket */ /* === Consider each column in the row ================================== */ rp = &A [row_start] ; rp_end = rp + row_length ; while (rp < rp_end) { col = *rp++ ; if (COL_IS_DEAD (col)) { continue ; } /* get hash number for this column */ hash = Col [col].shared3.hash ; assert (hash <= n_col) ; /* === Get the first column in this hash bucket ===================== */ head_column = head [hash] ; if (head_column > EMPTY) { first_col = Col [head_column].shared3.headhash ; } else { first_col = - (head_column + 2) ; } /* === Consider each column in the hash bucket ====================== */ for (super_c = first_col ; super_c != EMPTY ; super_c = Col [super_c].shared4.hash_next) { assert (COL_IS_ALIVE (super_c)) ; assert (Col [super_c].shared3.hash == hash) ; length = Col [super_c].length ; /* prev_c is the column preceding column c in the hash bucket */ prev_c = super_c ; /* === Compare super_c with all columns after it ================ */ for (c = Col [super_c].shared4.hash_next ; c != EMPTY ; c = Col [c].shared4.hash_next) { assert (c != super_c) ; assert (COL_IS_ALIVE (c)) ; assert (Col [c].shared3.hash == hash) ; /* not identical if lengths or scores are different */ if (Col [c].length != length || Col [c].shared2.score != Col [super_c].shared2.score) { prev_c = c ; continue ; } /* compare the two columns */ cp1 = &A [Col [super_c].start] ; cp2 = &A [Col [c].start] ; for (i = 0 ; i < length ; i++) { /* the columns are "clean" (no dead rows) */ assert (ROW_IS_ALIVE (*cp1)) ; assert (ROW_IS_ALIVE (*cp2)) ; /* row indices will same order for both supercols, */ /* no gather scatter nessasary */ if (*cp1++ != *cp2++) { break ; } } /* the two columns are different if the for-loop "broke" */ if (i != length) { prev_c = c ; continue ; } /* === Got it! two columns are identical =================== */ assert (Col [c].shared2.score == Col [super_c].shared2.score) ; Col [super_c].shared1.thickness += Col [c].shared1.thickness ; Col [c].shared1.parent = super_c ; KILL_NON_PRINCIPAL_COL (c) ; /* order c later, in order_children() */ Col [c].shared2.order = EMPTY ; /* remove c from hash bucket */ Col [prev_c].shared4.hash_next = Col [c].shared4.hash_next ; } } /* === Empty this hash bucket ======================================= */ if (head_column > EMPTY) { /* corresponding degree list "hash" is not empty */ Col [head_column].shared3.headhash = EMPTY ; } else { /* corresponding degree list "hash" is empty */ head [hash] = EMPTY ; } } } /* ========================================================================== */ /* === garbage_collection =================================================== */ /* ========================================================================== */ /* Defragments and compacts columns and rows in the workspace A. Used when all avaliable memory has been used while performing row merging. Returns the index of the first free position in A, after garbage collection. The time taken by this routine is linear is the size of the array A, which is itself linear in the number of nonzeros in the input matrix. Not user-callable. */ PRIVATE int garbage_collection /* returns the new value of pfree */ ( /* === Parameters ======================================================= */ int n_row, /* number of rows */ int n_col, /* number of columns */ RowInfo Row [], /* row info */ ColInfo Col [], /* column info */ int A [], /* A [0 ... Alen-1] holds the matrix */ int *pfree /* &A [0] ... pfree is in use */ ) { /* === Local variables ================================================== */ int *psrc ; /* source pointer */ int *pdest ; /* destination pointer */ int j ; /* counter */ int r ; /* a row index */ int c ; /* a column index */ int length ; /* length of a row or column */ #ifndef NDEBUG int debug_rows ; DEBUG0 (("Defrag..\n")) ; for (psrc = &A[0] ; psrc < pfree ; psrc++) assert (*psrc >= 0) ; debug_rows = 0 ; #endif /* === Defragment the columns =========================================== */ pdest = &A[0] ; for (c = 0 ; c < n_col ; c++) { if (COL_IS_ALIVE (c)) { psrc = &A [Col [c].start] ; /* move and compact the column */ assert (pdest <= psrc) ; Col [c].start = (int) (pdest - &A [0]) ; length = Col [c].length ; for (j = 0 ; j < length ; j++) { r = *psrc++ ; if (ROW_IS_ALIVE (r)) { *pdest++ = r ; } } Col [c].length = (int) (pdest - &A [Col [c].start]) ; } } /* === Prepare to defragment the rows =================================== */ for (r = 0 ; r < n_row ; r++) { if (ROW_IS_ALIVE (r)) { if (Row [r].length == 0) { /* this row is of zero length. cannot compact it, so kill it */ DEBUG0 (("Defrag row kill\n")) ; KILL_ROW (r) ; } else { /* save first column index in Row [r].shared2.first_column */ psrc = &A [Row [r].start] ; Row [r].shared2.first_column = *psrc ; assert (ROW_IS_ALIVE (r)) ; /* flag the start of the row with the one's complement of row */ *psrc = ONES_COMPLEMENT (r) ; #ifndef NDEBUG debug_rows++ ; #endif } } } /* === Defragment the rows ============================================== */ psrc = pdest ; while (psrc < pfree) { /* find a negative number ... the start of a row */ if (*psrc++ < 0) { psrc-- ; /* get the row index */ r = ONES_COMPLEMENT (*psrc) ; assert (r >= 0 && r < n_row) ; /* restore first column index */ *psrc = Row [r].shared2.first_column ; assert (ROW_IS_ALIVE (r)) ; /* move and compact the row */ assert (pdest <= psrc) ; Row [r].start = (int) (pdest - &A [0]) ; length = Row [r].length ; for (j = 0 ; j < length ; j++) { c = *psrc++ ; if (COL_IS_ALIVE (c)) { *pdest++ = c ; } } Row [r].length = (int) (pdest - &A [Row [r].start]) ; #ifndef NDEBUG debug_rows-- ; #endif } } /* ensure we found all the rows */ assert (debug_rows == 0) ; /* === Return the new value of pfree ==================================== */ return ((int) (pdest - &A [0])) ; } /* ========================================================================== */ /* === clear_mark =========================================================== */ /* ========================================================================== */ /* Clears the Row [].shared2.mark array, and returns the new tag_mark. Return value is the new tag_mark. Not user-callable. */ PRIVATE int clear_mark /* return the new value for tag_mark */ ( /* === Parameters ======================================================= */ int n_row, /* number of rows in A */ RowInfo Row [] /* Row [0 ... n_row-1].shared2.mark is set to zero */ ) { /* === Local variables ================================================== */ int r ; DEBUG0 (("Clear mark\n")) ; for (r = 0 ; r < n_row ; r++) { if (ROW_IS_ALIVE (r)) { Row [r].shared2.mark = 0 ; } } return (1) ; } /* ========================================================================== */ /* === debugging routines =================================================== */ /* ========================================================================== */ /* When debugging is disabled, the remainder of this file is ignored. */ #ifndef NDEBUG /* ========================================================================== */ /* === debug_structures ===================================================== */ /* ========================================================================== */ /* At this point, all empty rows and columns are dead. All live columns are "clean" (containing no dead rows) and simplicial (no supercolumns yet). Rows may contain dead columns, but all live rows contain at least one live column. */ PRIVATE void debug_structures ( /* === Parameters ======================================================= */ int n_row, int n_col, RowInfo Row [], ColInfo Col [], int A [], int n_col2 ) { /* === Local variables ================================================== */ int i ; int c ; int *cp ; int *cp_end ; int len ; int score ; int r ; int *rp ; int *rp_end ; int deg ; /* === Check A, Row, and Col ============================================ */ for (c = 0 ; c < n_col ; c++) { if (COL_IS_ALIVE (c)) { len = Col [c].length ; score = Col [c].shared2.score ; DEBUG4 (("initial live col %5d %5d %5d\n", c, len, score)) ; assert (len > 0) ; assert (score >= 0) ; assert (Col [c].shared1.thickness == 1) ; cp = &A [Col [c].start] ; cp_end = cp + len ; while (cp < cp_end) { r = *cp++ ; assert (ROW_IS_ALIVE (r)) ; } } else { i = Col [c].shared2.order ; assert (i >= n_col2 && i < n_col) ; } } for (r = 0 ; r < n_row ; r++) { if (ROW_IS_ALIVE (r)) { i = 0 ; len = Row [r].length ; deg = Row [r].shared1.degree ; assert (len > 0) ; assert (deg > 0) ; rp = &A [Row [r].start] ; rp_end = rp + len ; while (rp < rp_end) { c = *rp++ ; if (COL_IS_ALIVE (c)) { i++ ; } } assert (i > 0) ; } } } /* ========================================================================== */ /* === debug_deg_lists ====================================================== */ /* ========================================================================== */ /* Prints the contents of the degree lists. Counts the number of columns in the degree list and compares it to the total it should have. Also checks the row degrees. */ PRIVATE void debug_deg_lists ( /* === Parameters ======================================================= */ int n_row, int n_col, RowInfo Row [], ColInfo Col [], int head [], int min_score, int should, int max_deg ) { /* === Local variables ================================================== */ int deg ; int col ; int have ; int row ; /* === Check the degree lists =========================================== */ if (n_col > 10000 && debug_colamd <= 0) { return ; } have = 0 ; DEBUG4 (("Degree lists: %d\n", min_score)) ; for (deg = 0 ; deg <= n_col ; deg++) { col = head [deg] ; if (col == EMPTY) { continue ; } DEBUG4 (("%d:", deg)) ; while (col != EMPTY) { DEBUG4 ((" %d", col)) ; have += Col [col].shared1.thickness ; assert (COL_IS_ALIVE (col)) ; col = Col [col].shared4.degree_next ; } DEBUG4 (("\n")) ; } DEBUG4 (("should %d have %d\n", should, have)) ; assert (should == have) ; /* === Check the row degrees ============================================ */ if (n_row > 10000 && debug_colamd <= 0) { return ; } for (row = 0 ; row < n_row ; row++) { if (ROW_IS_ALIVE (row)) { assert (Row [row].shared1.degree <= max_deg) ; } } } /* ========================================================================== */ /* === debug_mark =========================================================== */ /* ========================================================================== */ /* Ensures that the tag_mark is less that the maximum and also ensures that each entry in the mark array is less than the tag mark. */ PRIVATE void debug_mark ( /* === Parameters ======================================================= */ int n_row, RowInfo Row [], int tag_mark, int max_mark ) { /* === Local variables ================================================== */ int r ; /* === Check the Row marks ============================================== */ assert (tag_mark > 0 && tag_mark <= max_mark) ; if (n_row > 10000 && debug_colamd <= 0) { return ; } for (r = 0 ; r < n_row ; r++) { assert (Row [r].shared2.mark < tag_mark) ; } } /* ========================================================================== */ /* === debug_matrix ========================================================= */ /* ========================================================================== */ /* Prints out the contents of the columns and the rows. */ PRIVATE void debug_matrix ( /* === Parameters ======================================================= */ int n_row, int n_col, RowInfo Row [], ColInfo Col [], int A [] ) { /* === Local variables ================================================== */ int r ; int c ; int *rp ; int *rp_end ; int *cp ; int *cp_end ; /* === Dump the rows and columns of the matrix ========================== */ if (debug_colamd < 3) { return ; } DEBUG3 (("DUMP MATRIX:\n")) ; for (r = 0 ; r < n_row ; r++) { DEBUG3 (("Row %d alive? %d\n", r, ROW_IS_ALIVE (r))) ; if (ROW_IS_DEAD (r)) { continue ; } DEBUG3 (("start %d length %d degree %d\n", Row [r].start, Row [r].length, Row [r].shared1.degree)) ; rp = &A [Row [r].start] ; rp_end = rp + Row [r].length ; while (rp < rp_end) { c = *rp++ ; DEBUG3 ((" %d col %d\n", COL_IS_ALIVE (c), c)) ; } } for (c = 0 ; c < n_col ; c++) { DEBUG3 (("Col %d alive? %d\n", c, COL_IS_ALIVE (c))) ; if (COL_IS_DEAD (c)) { continue ; } DEBUG3 (("start %d length %d shared1 %d shared2 %d\n", Col [c].start, Col [c].length, Col [c].shared1.thickness, Col [c].shared2.score)) ; cp = &A [Col [c].start] ; cp_end = cp + Col [c].length ; while (cp < cp_end) { r = *cp++ ; DEBUG3 ((" %d row %d\n", ROW_IS_ALIVE (r), r)) ; } } } #endif
dilawar/sesc
src_without_LF/libsuperlu/old_colamd.c
C
gpl-2.0
79,574
// // Thread_WIN32.h // // $Id: //poco/1.3/Foundation/include/Poco/Thread_WIN32.h#7 $ // // Library: Foundation // Package: Threading // Module: Thread // // Definition of the ThreadImpl class for WIN32. // // Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef Foundation_Thread_WIN32_INCLUDED #define Foundation_Thread_WIN32_INCLUDED #include "Poco/Foundation.h" #include "Poco/Runnable.h" #include "Poco/UnWindows.h" namespace Poco { class Foundation_API ThreadImpl { public: typedef void (*Callable)(void*); #if defined(_DLL) typedef DWORD (WINAPI *Entry)(LPVOID); #else typedef unsigned (__stdcall *Entry)(void*); #endif struct CallbackData { CallbackData(): callback(0), pData(0) { } Callable callback; void* pData; }; enum Priority { PRIO_LOWEST_IMPL = THREAD_PRIORITY_LOWEST, PRIO_LOW_IMPL = THREAD_PRIORITY_BELOW_NORMAL, PRIO_NORMAL_IMPL = THREAD_PRIORITY_NORMAL, PRIO_HIGH_IMPL = THREAD_PRIORITY_ABOVE_NORMAL, PRIO_HIGHEST_IMPL = THREAD_PRIORITY_HIGHEST }; ThreadImpl(); ~ThreadImpl(); void setPriorityImpl(int prio); int getPriorityImpl() const; void setOSPriorityImpl(int prio); int getOSPriorityImpl() const; static int getMinOSPriorityImpl(); static int getMaxOSPriorityImpl(); void setStackSizeImpl(int size); int getStackSizeImpl() const; void startImpl(Runnable& target); void startImpl(Callable target, void* pData = 0); void joinImpl(); bool joinImpl(long milliseconds); bool isRunningImpl() const; static void sleepImpl(long milliseconds); static void yieldImpl(); static ThreadImpl* currentImpl(); protected: #if defined(_DLL) static DWORD WINAPI runnableEntry(LPVOID pThread); #else static unsigned __stdcall runnableEntry(void* pThread); #endif #if defined(_DLL) static DWORD WINAPI callableEntry(LPVOID pThread); #else static unsigned __stdcall callableEntry(void* pThread); #endif void createImpl(Entry ent, void* pData); void threadCleanup(); private: Runnable* _pRunnableTarget; CallbackData _callbackTarget; HANDLE _thread; int _prio; int _stackSize; static DWORD _currentKey; }; // // inlines // inline int ThreadImpl::getPriorityImpl() const { return _prio; } inline int ThreadImpl::getOSPriorityImpl() const { return _prio; } inline int ThreadImpl::getMinOSPriorityImpl() { return PRIO_LOWEST_IMPL; } inline int ThreadImpl::getMaxOSPriorityImpl() { return PRIO_HIGHEST_IMPL; } inline void ThreadImpl::sleepImpl(long milliseconds) { Sleep(DWORD(milliseconds)); } inline void ThreadImpl::yieldImpl() { Sleep(0); } inline void ThreadImpl::setStackSizeImpl(int size) { _stackSize = size; } inline int ThreadImpl::getStackSizeImpl() const { return _stackSize; } } // namespace Poco #endif // Foundation_Thread_WIN32_INCLUDED
vcazan/openFloor
openCVBlobTracking/libs/poco/include/Poco/Thread_WIN32.h
C
gpl-3.0
4,204
# Copyright 2015 Abhijit Menon-Sen <ams@2ndQuadrant.com> # # 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/>. # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type import string from ansible.compat.tests import unittest from ansible.compat.tests.mock import patch from ansible.inventory.manager import InventoryManager, split_host_pattern from ansible.vars.manager import VariableManager from units.mock.loader import DictDataLoader class TestInventory(unittest.TestCase): patterns = { 'a': ['a'], 'a, b': ['a', 'b'], 'a , b': ['a', 'b'], ' a,b ,c[1:2] ': ['a', 'b', 'c[1:2]'], '9a01:7f8:191:7701::9': ['9a01:7f8:191:7701::9'], '9a01:7f8:191:7701::9,9a01:7f8:191:7701::9': ['9a01:7f8:191:7701::9', '9a01:7f8:191:7701::9'], '9a01:7f8:191:7701::9,9a01:7f8:191:7701::9,foo': ['9a01:7f8:191:7701::9', '9a01:7f8:191:7701::9', 'foo'], 'foo[1:2]': ['foo[1:2]'], 'a::b': ['a::b'], 'a:b': ['a', 'b'], ' a : b ': ['a', 'b'], 'foo:bar:baz[1:2]': ['foo', 'bar', 'baz[1:2]'], } pattern_lists = [ [['a'], ['a']], [['a', 'b'], ['a', 'b']], [['a, b'], ['a', 'b']], [['9a01:7f8:191:7701::9', '9a01:7f8:191:7701::9,foo'], ['9a01:7f8:191:7701::9', '9a01:7f8:191:7701::9', 'foo']] ] # pattern_string: [ ('base_pattern', (a,b)), ['x','y','z'] ] # a,b are the bounds of the subscript; x..z are the results of the subscript # when applied to string.ascii_letters. subscripts = { 'a': [('a', None), list(string.ascii_letters)], 'a[0]': [('a', (0, None)), ['a']], 'a[1]': [('a', (1, None)), ['b']], 'a[2:3]': [('a', (2, 3)), ['c', 'd']], 'a[-1]': [('a', (-1, None)), ['Z']], 'a[-2]': [('a', (-2, None)), ['Y']], 'a[48:]': [('a', (48, -1)), ['W', 'X', 'Y', 'Z']], 'a[49:]': [('a', (49, -1)), ['X', 'Y', 'Z']], 'a[1:]': [('a', (1, -1)), list(string.ascii_letters[1:])], } ranges_to_expand = { 'a[1:2]': ['a1', 'a2'], 'a[1:10:2]': ['a1', 'a3', 'a5', 'a7', 'a9'], 'a[a:b]': ['aa', 'ab'], 'a[a:i:3]': ['aa', 'ad', 'ag'], 'a[a:b][c:d]': ['aac', 'aad', 'abc', 'abd'], 'a[0:1][2:3]': ['a02', 'a03', 'a12', 'a13'], 'a[a:b][2:3]': ['aa2', 'aa3', 'ab2', 'ab3'], } def setUp(self): fake_loader = DictDataLoader({}) self.i = InventoryManager(loader=fake_loader, sources=[None]) def test_split_patterns(self): for p in self.patterns: r = self.patterns[p] self.assertEqual(r, split_host_pattern(p)) for p, r in self.pattern_lists: self.assertEqual(r, split_host_pattern(p)) def test_ranges(self): for s in self.subscripts: r = self.subscripts[s] self.assertEqual(r[0], self.i._split_subscript(s)) self.assertEqual( r[1], self.i._apply_subscript( list(string.ascii_letters), r[0][1] ) ) class InventoryDefaultGroup(unittest.TestCase): def test_empty_inventory(self): inventory = self._get_inventory('') self.assertIn('all', inventory.groups) self.assertIn('ungrouped', inventory.groups) self.assertFalse(inventory.groups['all'].get_hosts()) self.assertFalse(inventory.groups['ungrouped'].get_hosts()) def test_ini(self): self._test_default_groups(""" host1 host2 host3 [servers] host3 host4 host5 """) def test_ini_explicit_ungrouped(self): self._test_default_groups(""" [ungrouped] host1 host2 host3 [servers] host3 host4 host5 """) def _get_inventory(self, inventory_content): fake_loader = DictDataLoader({__file__: inventory_content}) return InventoryManager(loader=fake_loader, sources=[__file__]) def _test_default_groups(self, inventory_content): inventory = self._get_inventory(inventory_content) self.assertIn('all', inventory.groups) self.assertIn('ungrouped', inventory.groups) all_hosts = set(host.name for host in inventory.groups['all'].get_hosts()) self.assertEqual(set(['host1', 'host2', 'host3', 'host4', 'host5']), all_hosts) ungrouped_hosts = set(host.name for host in inventory.groups['ungrouped'].get_hosts()) self.assertEqual(set(['host1', 'host2', 'host3']), ungrouped_hosts) servers_hosts = set(host.name for host in inventory.groups['servers'].get_hosts()) self.assertEqual(set(['host3', 'host4', 'host5']), servers_hosts)
tux-00/ansible
test/units/inventory/test_inventory.py
Python
gpl-3.0
5,504
// Copyright 2015 Canonical Ltd. // Copyright 2015 Cloudbase Solutions SRL // Licensed under the AGPLv3, see LICENCE file for details. package openstack_test import ( jc "github.com/juju/testing/checkers" "github.com/juju/utils" "github.com/juju/utils/os" gc "gopkg.in/check.v1" "github.com/juju/juju/cloudconfig/cloudinit/cloudinittest" "github.com/juju/juju/cloudconfig/providerinit/renderers" "github.com/juju/juju/provider/openstack" "github.com/juju/juju/testing" ) type UserdataSuite struct { testing.BaseSuite } var _ = gc.Suite(&UserdataSuite{}) func (s *UserdataSuite) TestOpenstackUnix(c *gc.C) { renderer := openstack.OpenstackRenderer{} cloudcfg := &cloudinittest.CloudConfig{YAML: []byte("yaml")} result, err := renderer.Render(cloudcfg, os.Ubuntu) c.Assert(err, jc.ErrorIsNil) c.Assert(result, jc.DeepEquals, utils.Gzip(cloudcfg.YAML)) result, err = renderer.Render(cloudcfg, os.CentOS) c.Assert(err, jc.ErrorIsNil) c.Assert(result, jc.DeepEquals, utils.Gzip(cloudcfg.YAML)) } func (s *UserdataSuite) TestOpenstackWindows(c *gc.C) { renderer := openstack.OpenstackRenderer{} cloudcfg := &cloudinittest.CloudConfig{YAML: []byte("yaml")} result, err := renderer.Render(cloudcfg, os.Windows) c.Assert(err, jc.ErrorIsNil) c.Assert(result, jc.DeepEquals, renderers.WinEmbedInScript(cloudcfg.YAML)) } func (s *UserdataSuite) TestOpenstackUnknownOS(c *gc.C) { renderer := openstack.OpenstackRenderer{} cloudcfg := &cloudinittest.CloudConfig{} result, err := renderer.Render(cloudcfg, os.GenericLinux) c.Assert(result, gc.IsNil) c.Assert(err, gc.ErrorMatches, "Cannot encode userdata for OS: GenericLinux") }
mjs/juju
provider/openstack/userdata_test.go
GO
agpl-3.0
1,653
import unittest from scrapy.contrib.downloadermiddleware.redirect import RedirectMiddleware from scrapy.spider import BaseSpider from scrapy.exceptions import IgnoreRequest from scrapy.http import Request, Response, HtmlResponse, Headers class RedirectMiddlewareTest(unittest.TestCase): def setUp(self): self.spider = BaseSpider('foo') self.mw = RedirectMiddleware() def test_priority_adjust(self): req = Request('http://a.com') rsp = Response('http://a.com', headers={'Location': 'http://a.com/redirected'}, status=301) req2 = self.mw.process_response(req, rsp, self.spider) assert req2.priority > req.priority def test_redirect_301(self): def _test(method): url = 'http://www.example.com/301' url2 = 'http://www.example.com/redirected' req = Request(url, method=method) rsp = Response(url, headers={'Location': url2}, status=301) req2 = self.mw.process_response(req, rsp, self.spider) assert isinstance(req2, Request) self.assertEqual(req2.url, url2) self.assertEqual(req2.method, method) # response without Location header but with status code is 3XX should be ignored del rsp.headers['Location'] assert self.mw.process_response(req, rsp, self.spider) is rsp _test('GET') _test('POST') _test('HEAD') def test_dont_redirect(self): url = 'http://www.example.com/301' url2 = 'http://www.example.com/redirected' req = Request(url, meta={'dont_redirect': True}) rsp = Response(url, headers={'Location': url2}, status=301) r = self.mw.process_response(req, rsp, self.spider) assert isinstance(r, Response) assert r is rsp def test_redirect_302(self): url = 'http://www.example.com/302' url2 = 'http://www.example.com/redirected2' req = Request(url, method='POST', body='test', headers={'Content-Type': 'text/plain', 'Content-length': '4'}) rsp = Response(url, headers={'Location': url2}, status=302) req2 = self.mw.process_response(req, rsp, self.spider) assert isinstance(req2, Request) self.assertEqual(req2.url, url2) self.assertEqual(req2.method, 'GET') assert 'Content-Type' not in req2.headers, \ "Content-Type header must not be present in redirected request" assert 'Content-Length' not in req2.headers, \ "Content-Length header must not be present in redirected request" assert not req2.body, \ "Redirected body must be empty, not '%s'" % req2.body # response without Location header but with status code is 3XX should be ignored del rsp.headers['Location'] assert self.mw.process_response(req, rsp, self.spider) is rsp def test_redirect_302_head(self): url = 'http://www.example.com/302' url2 = 'http://www.example.com/redirected2' req = Request(url, method='HEAD') rsp = Response(url, headers={'Location': url2}, status=302) req2 = self.mw.process_response(req, rsp, self.spider) assert isinstance(req2, Request) self.assertEqual(req2.url, url2) self.assertEqual(req2.method, 'HEAD') # response without Location header but with status code is 3XX should be ignored del rsp.headers['Location'] assert self.mw.process_response(req, rsp, self.spider) is rsp def test_meta_refresh(self): body = """<html> <head><meta http-equiv="refresh" content="5;url=http://example.org/newpage" /></head> </html>""" req = Request(url='http://example.org') rsp = HtmlResponse(url='http://example.org', body=body) req2 = self.mw.process_response(req, rsp, self.spider) assert isinstance(req2, Request) self.assertEqual(req2.url, 'http://example.org/newpage') def test_meta_refresh_with_high_interval(self): # meta-refresh with high intervals don't trigger redirects body = """<html> <head><meta http-equiv="refresh" content="1000;url=http://example.org/newpage" /></head> </html>""" req = Request(url='http://example.org') rsp = HtmlResponse(url='http://example.org', body=body) rsp2 = self.mw.process_response(req, rsp, self.spider) assert rsp is rsp2 def test_meta_refresh_trough_posted_request(self): body = """<html> <head><meta http-equiv="refresh" content="5;url=http://example.org/newpage" /></head> </html>""" req = Request(url='http://example.org', method='POST', body='test', headers={'Content-Type': 'text/plain', 'Content-length': '4'}) rsp = HtmlResponse(url='http://example.org', body=body) req2 = self.mw.process_response(req, rsp, self.spider) assert isinstance(req2, Request) self.assertEqual(req2.url, 'http://example.org/newpage') self.assertEqual(req2.method, 'GET') assert 'Content-Type' not in req2.headers, \ "Content-Type header must not be present in redirected request" assert 'Content-Length' not in req2.headers, \ "Content-Length header must not be present in redirected request" assert not req2.body, \ "Redirected body must be empty, not '%s'" % req2.body def test_max_redirect_times(self): self.mw.max_redirect_times = 1 req = Request('http://scrapytest.org/302') rsp = Response('http://scrapytest.org/302', headers={'Location': '/redirected'}, status=302) req = self.mw.process_response(req, rsp, self.spider) assert isinstance(req, Request) assert 'redirect_times' in req.meta self.assertEqual(req.meta['redirect_times'], 1) self.assertRaises(IgnoreRequest, self.mw.process_response, req, rsp, self.spider) def test_ttl(self): self.mw.max_redirect_times = 100 req = Request('http://scrapytest.org/302', meta={'redirect_ttl': 1}) rsp = Response('http://www.scrapytest.org/302', headers={'Location': '/redirected'}, status=302) req = self.mw.process_response(req, rsp, self.spider) assert isinstance(req, Request) self.assertRaises(IgnoreRequest, self.mw.process_response, req, rsp, self.spider) def test_redirect_urls(self): req1 = Request('http://scrapytest.org/first') rsp1 = Response('http://scrapytest.org/first', headers={'Location': '/redirected'}, status=302) req2 = self.mw.process_response(req1, rsp1, self.spider) rsp2 = Response('http://scrapytest.org/redirected', headers={'Location': '/redirected2'}, status=302) req3 = self.mw.process_response(req2, rsp2, self.spider) self.assertEqual(req2.url, 'http://scrapytest.org/redirected') self.assertEqual(req2.meta['redirect_urls'], ['http://scrapytest.org/first']) self.assertEqual(req3.url, 'http://scrapytest.org/redirected2') self.assertEqual(req3.meta['redirect_urls'], ['http://scrapytest.org/first', 'http://scrapytest.org/redirected']) if __name__ == "__main__": unittest.main()
mzdaniel/oh-mainline
vendor/packages/scrapy/scrapy/tests/test_downloadermiddleware_redirect.py
Python
agpl-3.0
7,244
/* * Copyright 1999-2011 Alibaba Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.rpc.filter; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.beanutil.JavaBeanAccessor; import com.alibaba.dubbo.common.beanutil.JavaBeanDescriptor; import com.alibaba.dubbo.common.beanutil.JavaBeanSerializeUtil; import com.alibaba.dubbo.common.extension.Activate; import com.alibaba.dubbo.common.logger.Logger; import com.alibaba.dubbo.common.logger.LoggerFactory; import com.alibaba.dubbo.common.utils.PojoUtils; import com.alibaba.dubbo.common.utils.ReflectUtils; import com.alibaba.dubbo.rpc.Filter; import com.alibaba.dubbo.rpc.Invocation; import com.alibaba.dubbo.rpc.Invoker; import com.alibaba.dubbo.rpc.Result; import com.alibaba.dubbo.rpc.RpcException; import com.alibaba.dubbo.rpc.RpcInvocation; import com.alibaba.dubbo.rpc.RpcResult; import com.alibaba.dubbo.rpc.service.GenericException; import com.alibaba.dubbo.rpc.support.ProtocolUtils; /** * GenericImplInvokerFilter * * @author william.liangf */ @Activate(group = Constants.CONSUMER, value = Constants.GENERIC_KEY, order = 20000) public class GenericImplFilter implements Filter { private static final Logger logger = LoggerFactory.getLogger(GenericImplFilter.class); private static final Class<?>[] GENERIC_PARAMETER_TYPES = new Class<?>[] {String.class, String[].class, Object[].class}; public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { String generic = invoker.getUrl().getParameter(Constants.GENERIC_KEY); if (ProtocolUtils.isGeneric(generic) && ! Constants.$INVOKE.equals(invocation.getMethodName()) && invocation instanceof RpcInvocation) { RpcInvocation invocation2 = (RpcInvocation) invocation; String methodName = invocation2.getMethodName(); Class<?>[] parameterTypes = invocation2.getParameterTypes(); Object[] arguments = invocation2.getArguments(); String[] types = new String[parameterTypes.length]; for (int i = 0; i < parameterTypes.length; i ++) { types[i] = ReflectUtils.getName(parameterTypes[i]); } Object[] args; if (ProtocolUtils.isBeanGenericSerialization(generic)) { args = new Object[arguments.length]; for(int i = 0; i < arguments.length; i++) { args[i] = JavaBeanSerializeUtil.serialize(arguments[i], JavaBeanAccessor.METHOD); } } else { args = PojoUtils.generalize(arguments); } invocation2.setMethodName(Constants.$INVOKE); invocation2.setParameterTypes(GENERIC_PARAMETER_TYPES); invocation2.setArguments(new Object[] {methodName, types, args}); Result result = invoker.invoke(invocation2); if (! result.hasException()) { Object value = result.getValue(); try { Method method = invoker.getInterface().getMethod(methodName, parameterTypes); if (ProtocolUtils.isBeanGenericSerialization(generic)) { if (value == null) { return new RpcResult(value); } else if (value instanceof JavaBeanDescriptor) { return new RpcResult(JavaBeanSerializeUtil.deserialize((JavaBeanDescriptor)value)); } else { throw new RpcException( new StringBuilder(64) .append("The type of result value is ") .append(value.getClass().getName()) .append(" other than ") .append(JavaBeanDescriptor.class.getName()) .append(", and the result is ") .append(value).toString()); } } else { return new RpcResult(PojoUtils.realize(value, method.getReturnType(), method.getGenericReturnType())); } } catch (NoSuchMethodException e) { throw new RpcException(e.getMessage(), e); } } else if (result.getException() instanceof GenericException) { GenericException exception = (GenericException) result.getException(); try { String className = exception.getExceptionClass(); Class<?> clazz = ReflectUtils.forName(className); Throwable targetException = null; Throwable lastException = null; try { targetException = (Throwable) clazz.newInstance(); } catch (Throwable e) { lastException = e; for (Constructor<?> constructor : clazz.getConstructors()) { try { targetException = (Throwable) constructor.newInstance(new Object[constructor.getParameterTypes().length]); break; } catch (Throwable e1) { lastException = e1; } } } if (targetException != null) { try { Field field = Throwable.class.getDeclaredField("detailMessage"); if (! field.isAccessible()) { field.setAccessible(true); } field.set(targetException, exception.getExceptionMessage()); } catch (Throwable e) { logger.warn(e.getMessage(), e); } result = new RpcResult(targetException); } else if (lastException != null) { throw lastException; } } catch (Throwable e) { throw new RpcException("Can not deserialize exception " + exception.getExceptionClass() + ", message: " + exception.getExceptionMessage(), e); } } return result; } if (invocation.getMethodName().equals(Constants.$INVOKE) && invocation.getArguments() != null && invocation.getArguments().length == 3 && ProtocolUtils.isGeneric(generic)) { Object[] args = (Object[]) invocation.getArguments()[2]; if (ProtocolUtils.isJavaGenericSerialization(generic)) { for (Object arg : args) { if (!(byte[].class == arg.getClass())) { error(byte[].class.getName(), arg.getClass().getName()); } } } else if (ProtocolUtils.isBeanGenericSerialization(generic)) { for(Object arg : args) { if (!(arg instanceof JavaBeanDescriptor)) { error(JavaBeanDescriptor.class.getName(), arg.getClass().getName()); } } } ((RpcInvocation)invocation).setAttachment( Constants.GENERIC_KEY, invoker.getUrl().getParameter(Constants.GENERIC_KEY)); } return invoker.invoke(invocation); } private void error(String expected, String actual) throws RpcException { throw new RpcException( new StringBuilder(32) .append("Generic serialization [") .append(Constants.GENERIC_SERIALIZATION_NATIVE_JAVA) .append("] only support message type ") .append(expected) .append(" and your message type is ") .append(actual).toString()); } }
zhushuchen/Ocean
项目源码/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/filter/GenericImplFilter.java
Java
agpl-3.0
8,743
package com.mossle.ext.message; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.jms.JMSException; import javax.jms.MessageConsumer; import javax.jms.Topic; public class ProxyTopic implements Topic { private Map<MessageConsumer, List<String>> map = new HashMap<MessageConsumer, List<String>>(); private String name; public ProxyTopic(String name) { this.name = name; } public String getTopicName() throws JMSException { return name; } public String toString() { return name; } // ~ ================================================== public void sendMessage(String text) { for (Map.Entry<MessageConsumer, List<String>> entry : map.entrySet()) { entry.getValue().add(text); } } public void addConsumer(MessageConsumer messageConsumer) { map.put(messageConsumer, new ArrayList<String>()); } public void removeConsumer(MessageConsumer messageConsumer) { map.remove(messageConsumer); } public String getMessage(MessageConsumer messageConsumer) { List<String> list = map.get(messageConsumer); if (list.isEmpty()) { return null; } return list.remove(0); } }
callmeyan/lemon
src/main/java/com/mossle/ext/message/ProxyTopic.java
Java
apache-2.0
1,306
// "Sort content" "true" enum e { Foo, Bar,<caret> Baz; }
siosio/intellij-community
java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/sortContent/beforeEnum.java
Java
apache-2.0
65
/** PURE_IMPORTS_START .._Subscriber PURE_IMPORTS_END */ var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; import { Subscriber } from '../Subscriber'; /* tslint:enable:max-line-length */ /** * Applies an accumulator function over the source Observable, and returns each * intermediate result, with an optional seed value. * * <span class="informal">It's like {@link reduce}, but emits the current * accumulation whenever the source emits a value.</span> * * <img src="./img/scan.png" width="100%"> * * Combines together all values emitted on the source, using an accumulator * function that knows how to join a new source value into the accumulation from * the past. Is similar to {@link reduce}, but emits the intermediate * accumulations. * * Returns an Observable that applies a specified `accumulator` function to each * item emitted by the source Observable. If a `seed` value is specified, then * that value will be used as the initial value for the accumulator. If no seed * value is specified, the first item of the source is used as the seed. * * @example <caption>Count the number of click events</caption> * var clicks = Rx.Observable.fromEvent(document, 'click'); * var ones = clicks.mapTo(1); * var seed = 0; * var count = ones.scan((acc, one) => acc + one, seed); * count.subscribe(x => console.log(x)); * * @see {@link expand} * @see {@link mergeScan} * @see {@link reduce} * * @param {function(acc: R, value: T, index: number): R} accumulator * The accumulator function called on each source value. * @param {T|R} [seed] The initial accumulation value. * @return {Observable<R>} An observable of the accumulated values. * @method scan * @owner Observable */ export function scan(accumulator, seed) { var hasSeed = false; // providing a seed of `undefined` *should* be valid and trigger // hasSeed! so don't use `seed !== undefined` checks! // For this reason, we have to check it here at the original call site // otherwise inside Operator/Subscriber we won't know if `undefined` // means they didn't provide anything or if they literally provided `undefined` if (arguments.length >= 2) { hasSeed = true; } return function scanOperatorFunction(source) { return source.lift(new ScanOperator(accumulator, seed, hasSeed)); }; } var ScanOperator = /*@__PURE__*/ (/*@__PURE__*/ function () { function ScanOperator(accumulator, seed, hasSeed) { if (hasSeed === void 0) { hasSeed = false; } this.accumulator = accumulator; this.seed = seed; this.hasSeed = hasSeed; } ScanOperator.prototype.call = function (subscriber, source) { return source.subscribe(new ScanSubscriber(subscriber, this.accumulator, this.seed, this.hasSeed)); }; return ScanOperator; }()); /** * We need this JSDoc comment for affecting ESDoc. * @ignore * @extends {Ignored} */ var ScanSubscriber = /*@__PURE__*/ (/*@__PURE__*/ function (_super) { __extends(ScanSubscriber, _super); function ScanSubscriber(destination, accumulator, _seed, hasSeed) { _super.call(this, destination); this.accumulator = accumulator; this._seed = _seed; this.hasSeed = hasSeed; this.index = 0; } Object.defineProperty(ScanSubscriber.prototype, "seed", { get: function () { return this._seed; }, set: function (value) { this.hasSeed = true; this._seed = value; }, enumerable: true, configurable: true }); ScanSubscriber.prototype._next = function (value) { if (!this.hasSeed) { this.seed = value; this.destination.next(value); } else { return this._tryNext(value); } }; ScanSubscriber.prototype._tryNext = function (value) { var index = this.index++; var result; try { result = this.accumulator(this.seed, value, index); } catch (err) { this.destination.error(err); } this.seed = result; this.destination.next(result); }; return ScanSubscriber; }(Subscriber)); //# sourceMappingURL=scan.js.map
rospilot/rospilot
share/web_assets/nodejs_deps/node_modules/rxjs/_esm5/operators/scan.js
JavaScript
apache-2.0
4,477
--- layout: doc_page --- Druid vs Spark ============== Druid and Spark are complementary solutions as Druid can be used to accelerate OLAP queries in Spark. Spark is a general cluster computing framework initially designed around the concept of Resilient Distributed Datasets (RDDs). RDDs enable data reuse by persisting intermediate results in memory and enable Spark to provide fast computations for iterative algorithms. This is especially beneficial for certain work flows such as machine learning, where the same operation may be applied over and over again until some result is converged upon. The generality of Spark makes it very suitable as an engine to process (clean or transform) data. Although Spark provides the ability to query data through Spark SQL, much like Hadoop, the query latencies are not specifically targeted to be interactive (sub-second). Druid's focus is on extremely low latency queries, and is ideal for powering applications used by thousands of users, and where each query must return fast enough such that users can interactively explore through data. Druid fully indexes all data, and can act as a middle layer between Spark and your application. One typical setup seen in production is to process data in Spark, and load the processed data into Druid for faster access. For more information about using Druid and Spark together, including benchmarks of the two systems, please see: <https://www.linkedin.com/pulse/combining-druid-spark-interactive-flexible-analytics-scale-butani>
tubemogul/druid
docs/content/comparisons/druid-vs-spark.md
Markdown
apache-2.0
1,528
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.webkit; /** * A callback interface used to provide values asynchronously. */ public interface ValueCallback<T> { /** * Invoked when the value is available. * @param value The value. */ public void onReceiveValue(T value); };
haikuowuya/android_system_code
src/android/webkit/ValueCallback.java
Java
apache-2.0
888
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.internal.validation; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.project.Project; /** * @author Konstantin Bulenkov */ public class TestDialogWithValidationAction extends AnAction { @Override public void actionPerformed(AnActionEvent e) { final Project project = e.getProject(); if (project != null) { new ValidationTest(project).show(); } } }
asedunov/intellij-community
platform/platform-impl/src/com/intellij/internal/validation/TestDialogWithValidationAction.java
Java
apache-2.0
1,085
/** * 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 kafka.producer import java.util.Properties import kafka.api.TopicMetadata import kafka.cluster.BrokerEndPoint import kafka.common.UnavailableProducerException import kafka.utils.Logging import scala.collection.mutable.HashMap @deprecated("This object has been deprecated and will be removed in a future release.", "0.10.0.0") object ProducerPool { /** * Used in ProducerPool to initiate a SyncProducer connection with a broker. */ def createSyncProducer(config: ProducerConfig, broker: BrokerEndPoint): SyncProducer = { val props = new Properties() props.put("host", broker.host) props.put("port", broker.port.toString) props.putAll(config.props.props) new SyncProducer(new SyncProducerConfig(props)) } } @deprecated("This class has been deprecated and will be removed in a future release.", "0.10.0.0") class ProducerPool(val config: ProducerConfig) extends Logging { private val syncProducers = new HashMap[Int, SyncProducer] private val lock = new Object() def updateProducer(topicMetadata: Seq[TopicMetadata]) { val newBrokers = new collection.mutable.HashSet[BrokerEndPoint] topicMetadata.foreach(tmd => { tmd.partitionsMetadata.foreach(pmd => { if(pmd.leader.isDefined) { newBrokers += pmd.leader.get } }) }) lock synchronized { newBrokers.foreach(b => { if(syncProducers.contains(b.id)){ syncProducers(b.id).close() syncProducers.put(b.id, ProducerPool.createSyncProducer(config, b)) } else syncProducers.put(b.id, ProducerPool.createSyncProducer(config, b)) }) } } def getProducer(brokerId: Int) : SyncProducer = { lock.synchronized { val producer = syncProducers.get(brokerId) producer match { case Some(p) => p case None => throw new UnavailableProducerException("Sync producer for broker id %d does not exist".format(brokerId)) } } } /** * Closes all the producers in the pool */ def close() = { lock.synchronized { info("Closing all sync producers") val iter = syncProducers.values.iterator while(iter.hasNext) iter.next.close } } }
flange/drift-dev
kafka/00-kafka_2.11-0.10.1.0/libs/tmp/kafka/producer/ProducerPool.scala
Scala
apache-2.0
3,012
/* Copyright 2021 The Kubernetes 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. */ package create import ( "context" "crypto/tls" "fmt" "io/ioutil" "github.com/spf13/cobra" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/cli-runtime/pkg/genericclioptions" "k8s.io/cli-runtime/pkg/resource" corev1client "k8s.io/client-go/kubernetes/typed/core/v1" cmdutil "k8s.io/kubectl/pkg/cmd/util" "k8s.io/kubectl/pkg/scheme" "k8s.io/kubectl/pkg/util" "k8s.io/kubectl/pkg/util/hash" "k8s.io/kubectl/pkg/util/i18n" "k8s.io/kubectl/pkg/util/templates" ) var ( secretForTLSLong = templates.LongDesc(i18n.T(` Create a TLS secret from the given public/private key pair. The public/private key pair must exist before hand. The public key certificate must be .PEM encoded and match the given private key.`)) secretForTLSExample = templates.Examples(i18n.T(` # Create a new TLS secret named tls-secret with the given key pair: kubectl create secret tls tls-secret --cert=path/to/tls.cert --key=path/to/tls.key`)) ) // CreateSecretTLSOptions holds the options for 'create secret tls' sub command type CreateSecretTLSOptions struct { // PrintFlags holds options necessary for obtaining a printer PrintFlags *genericclioptions.PrintFlags PrintObj func(obj runtime.Object) error // Name is the name of this TLS secret. Name string // Key is the path to the user's private key. Key string // Cert is the path to the user's public key certificate. Cert string // AppendHash; if true, derive a hash from the Secret and append it to the name AppendHash bool FieldManager string CreateAnnotation bool Namespace string EnforceNamespace bool Client corev1client.CoreV1Interface DryRunStrategy cmdutil.DryRunStrategy DryRunVerifier *resource.DryRunVerifier genericclioptions.IOStreams } // NewSecretTLSOptions creates a new *CreateSecretTLSOptions with default value func NewSecretTLSOptions(ioStrems genericclioptions.IOStreams) *CreateSecretTLSOptions { return &CreateSecretTLSOptions{ PrintFlags: genericclioptions.NewPrintFlags("created").WithTypeSetter(scheme.Scheme), IOStreams: ioStrems, } } // NewCmdCreateSecretTLS is a macro command for creating secrets to work with TLS client or server func NewCmdCreateSecretTLS(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command { o := NewSecretTLSOptions(ioStreams) cmd := &cobra.Command{ Use: "tls NAME --cert=path/to/cert/file --key=path/to/key/file [--dry-run=server|client|none]", DisableFlagsInUseLine: true, Short: i18n.T("Create a TLS secret"), Long: secretForTLSLong, Example: secretForTLSExample, Run: func(cmd *cobra.Command, args []string) { cmdutil.CheckErr(o.Complete(f, cmd, args)) cmdutil.CheckErr(o.Validate()) cmdutil.CheckErr(o.Run()) }, } o.PrintFlags.AddFlags(cmd) cmdutil.AddApplyAnnotationFlags(cmd) cmdutil.AddValidateFlags(cmd) cmdutil.AddDryRunFlag(cmd) cmd.Flags().StringVar(&o.Cert, "cert", o.Cert, i18n.T("Path to PEM encoded public key certificate.")) cmd.Flags().StringVar(&o.Key, "key", o.Key, i18n.T("Path to private key associated with given certificate.")) cmd.Flags().BoolVar(&o.AppendHash, "append-hash", o.AppendHash, "Append a hash of the secret to its name.") cmdutil.AddFieldManagerFlagVar(cmd, &o.FieldManager, "kubectl-create") return cmd } // Complete loads data from the command line environment func (o *CreateSecretTLSOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error { var err error o.Name, err = NameFromCommandArgs(cmd, args) if err != nil { return err } restConfig, err := f.ToRESTConfig() if err != nil { return err } o.Client, err = corev1client.NewForConfig(restConfig) if err != nil { return err } o.CreateAnnotation = cmdutil.GetFlagBool(cmd, cmdutil.ApplyAnnotationsFlag) o.DryRunStrategy, err = cmdutil.GetDryRunStrategy(cmd) if err != nil { return err } dynamicClient, err := f.DynamicClient() if err != nil { return err } discoveryClient, err := f.ToDiscoveryClient() if err != nil { return err } o.DryRunVerifier = resource.NewDryRunVerifier(dynamicClient, discoveryClient) o.Namespace, o.EnforceNamespace, err = f.ToRawKubeConfigLoader().Namespace() if err != nil { return nil } cmdutil.PrintFlagsWithDryRunStrategy(o.PrintFlags, o.DryRunStrategy) printer, err := o.PrintFlags.ToPrinter() if err != nil { return nil } o.PrintObj = func(obj runtime.Object) error { return printer.PrintObj(obj, o.Out) } return nil } // Validate checks if CreateSecretTLSOptions hass sufficient value to run func (o *CreateSecretTLSOptions) Validate() error { // TODO: This is not strictly necessary. We can generate a self signed cert // if no key/cert is given. The only requirement is that we either get both // or none. See test/e2e/ingress_utils for self signed cert generation. if len(o.Key) == 0 || len(o.Cert) == 0 { return fmt.Errorf("key and cert must be specified") } return nil } // Run calls createSecretTLS which will create secretTLS based on CreateSecretTLSOptions // and makes an API call to the server func (o *CreateSecretTLSOptions) Run() error { secretTLS, err := o.createSecretTLS() if err != nil { return err } err = util.CreateOrUpdateAnnotation(o.CreateAnnotation, secretTLS, scheme.DefaultJSONEncoder()) if err != nil { return err } if o.DryRunStrategy != cmdutil.DryRunClient { createOptions := metav1.CreateOptions{} if o.FieldManager != "" { createOptions.FieldManager = o.FieldManager } if o.DryRunStrategy == cmdutil.DryRunServer { err := o.DryRunVerifier.HasSupport(secretTLS.GroupVersionKind()) if err != nil { return err } createOptions.DryRun = []string{metav1.DryRunAll} } secretTLS, err = o.Client.Secrets(o.Namespace).Create(context.TODO(), secretTLS, createOptions) if err != nil { return fmt.Errorf("failed to create secret %v", err) } } return o.PrintObj(secretTLS) } // createSecretTLS fills in key value pair from the information given in // CreateSecretTLSOptions into *corev1.Secret func (o *CreateSecretTLSOptions) createSecretTLS() (*corev1.Secret, error) { namespace := "" if o.EnforceNamespace { namespace = o.Namespace } tlsCert, err := readFile(o.Cert) if err != nil { return nil, err } tlsKey, err := readFile(o.Key) if err != nil { return nil, err } if _, err := tls.X509KeyPair(tlsCert, tlsKey); err != nil { return nil, err } // TODO: Add more validation. // 1. If the certificate contains intermediates, it is a valid chain. // 2. Format etc. secretTLS := newSecretObj(o.Name, namespace, corev1.SecretTypeTLS) secretTLS.Data[corev1.TLSCertKey] = []byte(tlsCert) secretTLS.Data[corev1.TLSPrivateKeyKey] = []byte(tlsKey) if o.AppendHash { hash, err := hash.SecretHash(secretTLS) if err != nil { return nil, err } secretTLS.Name = fmt.Sprintf("%s-%s", secretTLS.Name, hash) } return secretTLS, nil } // readFile just reads a file into a byte array. func readFile(file string) ([]byte, error) { b, err := ioutil.ReadFile(file) if err != nil { return []byte{}, fmt.Errorf("Cannot read file %v, %v", file, err) } return b, nil }
xychu/kubernetes
staging/src/k8s.io/kubectl/pkg/cmd/create/create_secret_tls.go
GO
apache-2.0
7,809
/// Copyright (c) 2012 Ecma International. All rights reserved. /** * 15.5.5.2 defines [[GetOwnProperty]] for Strings. It supports using indexing * notation to look up non numeric property names. * * @path ch15/15.5/15.5.5/15.5.5.2/15.5.5.5.2-3-5.js * @description String object indexing returns undefined if the numeric index ( 2^32-1) is not an array index */ function testcase() { var s = new String("hello world"); if (s[Math.pow(2, 32)-1]===undefined) { return true; } } runTestCase(testcase);
Oceanswave/NiL.JS
Tests/tests/sputnik/ch15/15.5/15.5.5/15.5.5.2/15.5.5.5.2-3-5.js
JavaScript
bsd-3-clause
521
// Copyright 2014 The b Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package b import ( "bytes" "fmt" "io" "math" "path" "runtime" "runtime/debug" "strings" "testing" "github.com/flynn/flynn/Godeps/_workspace/src/github.com/cznic/mathutil" "github.com/flynn/flynn/Godeps/_workspace/src/github.com/cznic/strutil" ) var caller = func(s string, va ...interface{}) { _, fn, fl, _ := runtime.Caller(2) fmt.Printf("%s:%d: ", path.Base(fn), fl) fmt.Printf(s, va...) fmt.Println() } func dbg(s string, va ...interface{}) { if s == "" { s = strings.Repeat("%v ", len(va)) } _, fn, fl, _ := runtime.Caller(1) fmt.Printf("%s:%d: ", path.Base(fn), fl) fmt.Printf(s, va...) fmt.Println() } func TODO(...interface{}) string { _, fn, fl, _ := runtime.Caller(1) return fmt.Sprintf("TODO: %s:%d:\n", path.Base(fn), fl) } func use(...interface{}) {} // ============================================================================ func isNil(p interface{}) bool { switch x := p.(type) { case *x: if x == nil { return true } case *d: if x == nil { return true } } return false } func (t *Tree) dump() string { var buf bytes.Buffer f := strutil.IndentFormatter(&buf, "\t") num := map[interface{}]int{} visited := map[interface{}]bool{} handle := func(p interface{}) int { if isNil(p) { return 0 } if n, ok := num[p]; ok { return n } n := len(num) + 1 num[p] = n return n } var pagedump func(interface{}, string) pagedump = func(p interface{}, pref string) { if isNil(p) || visited[p] { return } visited[p] = true switch x := p.(type) { case *x: h := handle(p) n := 0 for i, v := range x.x { if v.ch != nil || v.k != nil { n = i + 1 } } f.Format("%sX#%d(%p) n %d:%d {", pref, h, x, x.c, n) a := []interface{}{} for i, v := range x.x[:n] { a = append(a, v.ch) if i != 0 { f.Format(" ") } f.Format("(C#%d K %v)", handle(v.ch), v.k) } f.Format("}\n") for _, p := range a { pagedump(p, pref+". ") } case *d: h := handle(p) n := 0 for i, v := range x.d { if v.k != nil || v.v != nil { n = i + 1 } } f.Format("%sD#%d(%p) P#%d N#%d n %d:%d {", pref, h, x, handle(x.p), handle(x.n), x.c, n) for i, v := range x.d[:n] { if i != 0 { f.Format(" ") } f.Format("%v:%v", v.k, v.v) } f.Format("}\n") } } pagedump(t.r, "") s := buf.String() if s != "" { s = s[:len(s)-1] } return s } func rng() *mathutil.FC32 { x, err := mathutil.NewFC32(math.MinInt32/4, math.MaxInt32/4, false) if err != nil { panic(err) } return x } func cmp(a, b interface{}) int { return a.(int) - b.(int) } func TestGet0(t *testing.T) { r := TreeNew(cmp) if g, e := r.Len(), 0; g != e { t.Fatal(g, e) } _, ok := r.Get(42) if ok { t.Fatal(ok) } } func TestSetGet0(t *testing.T) { r := TreeNew(cmp) set := r.Set set(42, 314) if g, e := r.Len(), 1; g != e { t.Fatal(g, e) } v, ok := r.Get(42) if !ok { t.Fatal(ok) } if g, e := v.(int), 314; g != e { t.Fatal(g, e) } set(42, 278) if g, e := r.Len(), 1; g != e { t.Fatal(g, e) } v, ok = r.Get(42) if !ok { t.Fatal(ok) } if g, e := v.(int), 278; g != e { t.Fatal(g, e) } set(420, 0.5) if g, e := r.Len(), 2; g != e { t.Fatal(g, e) } v, ok = r.Get(42) if !ok { t.Fatal(ok) } if g, e := v.(int), 278; g != e { t.Fatal(g, e) } v, ok = r.Get(420) if !ok { t.Fatal(ok) } if g, e := v.(float64), 0.5; g != e { t.Fatal(g, e) } } func TestSetGet1(t *testing.T) { const N = 40000 for _, x := range []int{0, -1, 0x555555, 0xaaaaaa, 0x333333, 0xcccccc, 0x314159} { r := TreeNew(cmp) set := r.Set a := make([]int, N) for i := range a { a[i] = (i ^ x) << 1 } for i, k := range a { set(k, k^x) if g, e := r.Len(), i+1; g != e { t.Fatal(i, g, e) } } for i, k := range a { v, ok := r.Get(k) if !ok { t.Fatal(i, k, v, ok) } if g, e := v.(int), k^x; g != e { t.Fatal(i, g, e) } k |= 1 _, ok = r.Get(k) if ok { t.Fatal(i, k) } } for _, k := range a { r.Set(k, (k^x)+42) } for i, k := range a { v, ok := r.Get(k) if !ok { t.Fatal(i, k, v, ok) } if g, e := v.(int), k^x+42; g != e { t.Fatal(i, g, e) } k |= 1 _, ok = r.Get(k) if ok { t.Fatal(i, k) } } } } func TestPrealloc(*testing.T) { const n = 2e6 rng := rng() a := make([]int, n) for i := range a { a[i] = rng.Next() } r := TreeNew(cmp) for _, v := range a { r.Set(v, 0) } r.Close() } func BenchmarkSetSeq1e3(b *testing.B) { benchmarkSetSeq(b, 1e3) } func BenchmarkSetSeq1e4(b *testing.B) { benchmarkSetSeq(b, 1e4) } func BenchmarkSetSeq1e5(b *testing.B) { benchmarkSetSeq(b, 1e5) } func BenchmarkSetSeq1e6(b *testing.B) { benchmarkSetSeq(b, 1e6) } func benchmarkSetSeq(b *testing.B, n int) { b.ResetTimer() for i := 0; i < b.N; i++ { b.StopTimer() r := TreeNew(cmp) debug.FreeOSMemory() b.StartTimer() for j := 0; j < n; j++ { r.Set(j, j) } b.StopTimer() r.Close() } b.StopTimer() } func BenchmarkGetSeq1e3(b *testing.B) { benchmarkGetSeq(b, 1e3) } func BenchmarkGetSeq1e4(b *testing.B) { benchmarkGetSeq(b, 1e4) } func BenchmarkGetSeq1e5(b *testing.B) { benchmarkGetSeq(b, 1e5) } func BenchmarkGetSeq1e6(b *testing.B) { benchmarkGetSeq(b, 1e6) } func benchmarkGetSeq(b *testing.B, n int) { r := TreeNew(cmp) for i := 0; i < n; i++ { r.Set(i, i) } debug.FreeOSMemory() b.ResetTimer() for i := 0; i < b.N; i++ { for j := 0; j < n; j++ { r.Get(j) } } b.StopTimer() r.Close() } func BenchmarkSetRnd1e3(b *testing.B) { benchmarkSetRnd(b, 1e3) } func BenchmarkSetRnd1e4(b *testing.B) { benchmarkSetRnd(b, 1e4) } func BenchmarkSetRnd1e5(b *testing.B) { benchmarkSetRnd(b, 1e5) } func BenchmarkSetRnd1e6(b *testing.B) { benchmarkSetRnd(b, 1e6) } func benchmarkSetRnd(b *testing.B, n int) { rng := rng() a := make([]int, n) for i := range a { a[i] = rng.Next() } b.ResetTimer() for i := 0; i < b.N; i++ { b.StopTimer() r := TreeNew(cmp) debug.FreeOSMemory() b.StartTimer() for _, v := range a { r.Set(v, 0) } b.StopTimer() r.Close() } b.StopTimer() } func BenchmarkGetRnd1e3(b *testing.B) { benchmarkGetRnd(b, 1e3) } func BenchmarkGetRnd1e4(b *testing.B) { benchmarkGetRnd(b, 1e4) } func BenchmarkGetRnd1e5(b *testing.B) { benchmarkGetRnd(b, 1e5) } func BenchmarkGetRnd1e6(b *testing.B) { benchmarkGetRnd(b, 1e6) } func benchmarkGetRnd(b *testing.B, n int) { r := TreeNew(cmp) rng := rng() a := make([]int, n) for i := range a { a[i] = rng.Next() } for _, v := range a { r.Set(v, 0) } debug.FreeOSMemory() b.ResetTimer() for i := 0; i < b.N; i++ { for _, v := range a { r.Get(v) } } b.StopTimer() r.Close() } func TestSetGet2(t *testing.T) { const N = 40000 for _, x := range []int{0, -1, 0x555555, 0xaaaaaa, 0x333333, 0xcccccc, 0x314159} { rng := rng() r := TreeNew(cmp) set := r.Set a := make([]int, N) for i := range a { a[i] = (rng.Next() ^ x) << 1 } for i, k := range a { set(k, k^x) if g, e := r.Len(), i+1; g != e { t.Fatal(i, x, g, e) } } for i, k := range a { v, ok := r.Get(k) if !ok { t.Fatal(i, k, v, ok) } if g, e := v.(int), k^x; g != e { t.Fatal(i, g, e) } k |= 1 _, ok = r.Get(k) if ok { t.Fatal(i, k) } } for _, k := range a { r.Set(k, (k^x)+42) } for i, k := range a { v, ok := r.Get(k) if !ok { t.Fatal(i, k, v, ok) } if g, e := v.(int), k^x+42; g != e { t.Fatal(i, g, e) } k |= 1 _, ok = r.Get(k) if ok { t.Fatal(i, k) } } } } func TestSetGet3(t *testing.T) { r := TreeNew(cmp) set := r.Set var i int for i = 0; ; i++ { set(i, -i) if _, ok := r.r.(*x); ok { break } } for j := 0; j <= i; j++ { set(j, j) } for j := 0; j <= i; j++ { v, ok := r.Get(j) if !ok { t.Fatal(j) } if g, e := v.(int), j; g != e { t.Fatal(g, e) } } } func TestDelete0(t *testing.T) { r := TreeNew(cmp) if ok := r.Delete(0); ok { t.Fatal(ok) } if g, e := r.Len(), 0; g != e { t.Fatal(g, e) } r.Set(0, 0) if ok := r.Delete(1); ok { t.Fatal(ok) } if g, e := r.Len(), 1; g != e { t.Fatal(g, e) } if ok := r.Delete(0); !ok { t.Fatal(ok) } if g, e := r.Len(), 0; g != e { t.Fatal(g, e) } if ok := r.Delete(0); ok { t.Fatal(ok) } r.Set(0, 0) r.Set(1, 1) if ok := r.Delete(1); !ok { t.Fatal(ok) } if g, e := r.Len(), 1; g != e { t.Fatal(g, e) } if ok := r.Delete(1); ok { t.Fatal(ok) } if ok := r.Delete(0); !ok { t.Fatal(ok) } if g, e := r.Len(), 0; g != e { t.Fatal(g, e) } if ok := r.Delete(0); ok { t.Fatal(ok) } r.Set(0, 0) r.Set(1, 1) if ok := r.Delete(0); !ok { t.Fatal(ok) } if g, e := r.Len(), 1; g != e { t.Fatal(g, e) } if ok := r.Delete(0); ok { t.Fatal(ok) } if ok := r.Delete(1); !ok { t.Fatal(ok) } if g, e := r.Len(), 0; g != e { t.Fatal(g, e) } if ok := r.Delete(1); ok { t.Fatal(ok) } } func TestDelete1(t *testing.T) { const N = 130000 for _, x := range []int{0, -1, 0x555555, 0xaaaaaa, 0x333333, 0xcccccc, 0x314159} { r := TreeNew(cmp) set := r.Set a := make([]int, N) for i := range a { a[i] = (i ^ x) << 1 } for _, k := range a { set(k, 0) } for i, k := range a { ok := r.Delete(k) if !ok { t.Fatal(i, x, k) } if g, e := r.Len(), N-i-1; g != e { t.Fatal(i, g, e) } } } } func BenchmarkDelSeq1e3(b *testing.B) { benchmarkDelSeq(b, 1e3) } func BenchmarkDelSeq1e4(b *testing.B) { benchmarkDelSeq(b, 1e4) } func BenchmarkDelSeq1e5(b *testing.B) { benchmarkDelSeq(b, 1e5) } func BenchmarkDelSeq1e6(b *testing.B) { benchmarkDelSeq(b, 1e6) } func benchmarkDelSeq(b *testing.B, n int) { b.ResetTimer() for i := 0; i < b.N; i++ { b.StopTimer() r := TreeNew(cmp) for i := 0; i < n; i++ { r.Set(i, i) } debug.FreeOSMemory() b.StartTimer() for j := 0; j < n; j++ { r.Delete(j) } } b.StopTimer() } func BenchmarkDelRnd1e3(b *testing.B) { benchmarkDelRnd(b, 1e3) } func BenchmarkDelRnd1e4(b *testing.B) { benchmarkDelRnd(b, 1e4) } func BenchmarkDelRnd1e5(b *testing.B) { benchmarkDelRnd(b, 1e5) } func BenchmarkDelRnd1e6(b *testing.B) { benchmarkDelRnd(b, 1e6) } func benchmarkDelRnd(b *testing.B, n int) { rng := rng() a := make([]int, n) for i := range a { a[i] = rng.Next() } b.ResetTimer() for i := 0; i < b.N; i++ { b.StopTimer() r := TreeNew(cmp) for _, v := range a { r.Set(v, 0) } debug.FreeOSMemory() b.StartTimer() for _, v := range a { r.Delete(v) } b.StopTimer() r.Close() } b.StopTimer() } func TestDelete2(t *testing.T) { const N = 100000 for _, x := range []int{0, -1, 0x555555, 0xaaaaaa, 0x333333, 0xcccccc, 0x314159} { r := TreeNew(cmp) set := r.Set a := make([]int, N) rng := rng() for i := range a { a[i] = (rng.Next() ^ x) << 1 } for _, k := range a { set(k, 0) } for i, k := range a { ok := r.Delete(k) if !ok { t.Fatal(i, x, k) } if g, e := r.Len(), N-i-1; g != e { t.Fatal(i, g, e) } } } } func TestEnumeratorNext(t *testing.T) { // seeking within 3 keys: 10, 20, 30 table := []struct { k int hit bool keys []int }{ {5, false, []int{10, 20, 30}}, {10, true, []int{10, 20, 30}}, {15, false, []int{20, 30}}, {20, true, []int{20, 30}}, {25, false, []int{30}}, {30, true, []int{30}}, {35, false, []int{}}, } for i, test := range table { up := test.keys r := TreeNew(cmp) r.Set(10, 100) r.Set(20, 200) r.Set(30, 300) for verChange := 0; verChange < 16; verChange++ { en, hit := r.Seek(test.k) if g, e := hit, test.hit; g != e { t.Fatal(i, g, e) } j := 0 for { if verChange&(1<<uint(j)) != 0 { r.Set(20, 200) } k, v, err := en.Next() if err != nil { if err != io.EOF { t.Fatal(i, err) } break } if j >= len(up) { t.Fatal(i, j, verChange) } if g, e := k.(int), up[j]; g != e { t.Fatal(i, j, verChange, g, e) } if g, e := v.(int), 10*up[j]; g != e { t.Fatal(i, g, e) } j++ } if g, e := j, len(up); g != e { t.Fatal(i, j, g, e) } } } } func TestEnumeratorPrev(t *testing.T) { // seeking within 3 keys: 10, 20, 30 table := []struct { k int hit bool keys []int }{ {5, false, []int{10}}, {10, true, []int{10}}, {15, false, []int{20, 10}}, {20, true, []int{20, 10}}, {25, false, []int{30, 20, 10}}, {30, true, []int{30, 20, 10}}, {35, false, []int{}}, } for i, test := range table { dn := test.keys r := TreeNew(cmp) r.Set(10, 100) r.Set(20, 200) r.Set(30, 300) for verChange := 0; verChange < 16; verChange++ { en, hit := r.Seek(test.k) if g, e := hit, test.hit; g != e { t.Fatal(i, g, e) } j := 0 for { if verChange&(1<<uint(j)) != 0 { r.Set(20, 200) } k, v, err := en.Prev() if err != nil { if err != io.EOF { t.Fatal(i, err) } break } if j >= len(dn) { t.Fatal(i, j, verChange) } if g, e := k.(int), dn[j]; g != e { t.Fatal(i, j, verChange, g, e) } if g, e := v.(int), 10*dn[j]; g != e { t.Fatal(i, g, e) } j++ } if g, e := j, len(dn); g != e { t.Fatal(i, j, g, e) } } } } func BenchmarkSeekSeq1e3(b *testing.B) { benchmarkSeekSeq(b, 1e3) } func BenchmarkSeekSeq1e4(b *testing.B) { benchmarkSeekSeq(b, 1e4) } func BenchmarkSeekSeq1e5(b *testing.B) { benchmarkSeekSeq(b, 1e5) } func BenchmarkSeekSeq1e6(b *testing.B) { benchmarkSeekSeq(b, 1e6) } func benchmarkSeekSeq(b *testing.B, n int) { for i := 0; i < b.N; i++ { b.StopTimer() t := TreeNew(cmp) for j := 0; j < n; j++ { t.Set(j, 0) } debug.FreeOSMemory() b.StartTimer() for j := 0; j < n; j++ { e, _ := t.Seek(j) e.Close() } b.StopTimer() t.Close() } b.StopTimer() } func BenchmarkSeekRnd1e3(b *testing.B) { benchmarkSeekRnd(b, 1e3) } func BenchmarkSeekRnd1e4(b *testing.B) { benchmarkSeekRnd(b, 1e4) } func BenchmarkSeekRnd1e5(b *testing.B) { benchmarkSeekRnd(b, 1e5) } func BenchmarkSeekRnd1e6(b *testing.B) { benchmarkSeekRnd(b, 1e6) } func benchmarkSeekRnd(b *testing.B, n int) { r := TreeNew(cmp) rng := rng() a := make([]int, n) for i := range a { a[i] = rng.Next() } for _, v := range a { r.Set(v, 0) } debug.FreeOSMemory() b.ResetTimer() for i := 0; i < b.N; i++ { for _, v := range a { e, _ := r.Seek(v) e.Close() } } b.StopTimer() r.Close() } func BenchmarkNext1e3(b *testing.B) { benchmarkNext(b, 1e3) } func BenchmarkNext1e4(b *testing.B) { benchmarkNext(b, 1e4) } func BenchmarkNext1e5(b *testing.B) { benchmarkNext(b, 1e5) } func BenchmarkNext1e6(b *testing.B) { benchmarkNext(b, 1e6) } func benchmarkNext(b *testing.B, n int) { t := TreeNew(cmp) for i := 0; i < n; i++ { t.Set(i, 0) } debug.FreeOSMemory() b.ResetTimer() for i := 0; i < b.N; i++ { en, err := t.SeekFirst() if err != nil { b.Fatal(err) } m := 0 for { if _, _, err = en.Next(); err != nil { break } m++ } if m != n { b.Fatal(m) } } b.StopTimer() t.Close() } func BenchmarkPrev1e3(b *testing.B) { benchmarkPrev(b, 1e3) } func BenchmarkPrev1e4(b *testing.B) { benchmarkPrev(b, 1e4) } func BenchmarkPrev1e5(b *testing.B) { benchmarkPrev(b, 1e5) } func BenchmarkPrev1e6(b *testing.B) { benchmarkPrev(b, 1e6) } func benchmarkPrev(b *testing.B, n int) { t := TreeNew(cmp) for i := 0; i < n; i++ { t.Set(i, 0) } debug.FreeOSMemory() b.ResetTimer() for i := 0; i < b.N; i++ { en, err := t.SeekLast() if err != nil { b.Fatal(err) } m := 0 for { if _, _, err = en.Prev(); err != nil { break } m++ } if m != n { b.Fatal(m) } } } func TestSeekFirst0(t *testing.T) { b := TreeNew(cmp) _, err := b.SeekFirst() if g, e := err, io.EOF; g != e { t.Fatal(g, e) } } func TestSeekFirst1(t *testing.T) { b := TreeNew(cmp) b.Set(1, 10) en, err := b.SeekFirst() if err != nil { t.Fatal(err) } k, v, err := en.Next() if k != 1 || v != 10 || err != nil { t.Fatal(k, v, err) } k, v, err = en.Next() if err == nil { t.Fatal(k, v, err) } } func TestSeekFirst2(t *testing.T) { b := TreeNew(cmp) b.Set(1, 10) b.Set(2, 20) en, err := b.SeekFirst() if err != nil { t.Fatal(err) } k, v, err := en.Next() if k != 1 || v != 10 || err != nil { t.Fatal(k, v, err) } k, v, err = en.Next() if k != 2 || v != 20 || err != nil { t.Fatal(k, v, err) } k, v, err = en.Next() if err == nil { t.Fatal(k, v, err) } } func TestSeekFirst3(t *testing.T) { b := TreeNew(cmp) b.Set(2, 20) b.Set(3, 30) b.Set(1, 10) en, err := b.SeekFirst() if err != nil { t.Fatal(err) } k, v, err := en.Next() if k != 1 || v != 10 || err != nil { t.Fatal(k, v, err) } k, v, err = en.Next() if k != 2 || v != 20 || err != nil { t.Fatal(k, v, err) } k, v, err = en.Next() if k != 3 || v != 30 || err != nil { t.Fatal(k, v, err) } k, v, err = en.Next() if err == nil { t.Fatal(k, v, err) } } func TestSeekLast0(t *testing.T) { b := TreeNew(cmp) _, err := b.SeekLast() if g, e := err, io.EOF; g != e { t.Fatal(g, e) } } func TestSeekLast1(t *testing.T) { b := TreeNew(cmp) b.Set(1, 10) en, err := b.SeekLast() if err != nil { t.Fatal(err) } k, v, err := en.Prev() if k != 1 || v != 10 || err != nil { t.Fatal(k, v, err) } k, v, err = en.Prev() if err == nil { t.Fatal(k, v, err) } } func TestSeekLast2(t *testing.T) { b := TreeNew(cmp) b.Set(1, 10) b.Set(2, 20) en, err := b.SeekLast() if err != nil { t.Fatal(err) } k, v, err := en.Prev() if k != 2 || v != 20 || err != nil { t.Fatal(k, v, err) } k, v, err = en.Prev() if k != 1 || v != 10 || err != nil { t.Fatal(k, v, err) } k, v, err = en.Prev() if err == nil { t.Fatal(k, v, err) } } func TestSeekLast3(t *testing.T) { b := TreeNew(cmp) b.Set(2, 20) b.Set(3, 30) b.Set(1, 10) en, err := b.SeekLast() if err != nil { t.Fatal(err) } k, v, err := en.Prev() if k != 3 || v != 30 || err != nil { t.Fatal(k, v, err) } k, v, err = en.Prev() if k != 2 || v != 20 || err != nil { t.Fatal(k, v, err) } k, v, err = en.Prev() if k != 1 || v != 10 || err != nil { t.Fatal(k, v, err) } k, v, err = en.Prev() if err == nil { t.Fatal(k, v, err) } } func TestPut(t *testing.T) { tab := []struct { pre []int // even index: K, odd index: V newK int // Put(newK, ... oldV int // Put()->oldV exists bool // upd(exists) write bool // upd()->write post []int // even index: K, odd index: V }{ // 0 { []int{}, 1, 0, false, false, []int{}, }, { []int{}, 1, 0, false, true, []int{1, -1}, }, { []int{1, 10}, 0, 0, false, false, []int{1, 10}, }, { []int{1, 10}, 0, 0, false, true, []int{0, -1, 1, 10}, }, { []int{1, 10}, 1, 10, true, false, []int{1, 10}, }, // 5 { []int{1, 10}, 1, 10, true, true, []int{1, -1}, }, { []int{1, 10}, 2, 0, false, false, []int{1, 10}, }, { []int{1, 10}, 2, 0, false, true, []int{1, 10, 2, -1}, }, } for iTest, test := range tab { tr := TreeNew(cmp) for i := 0; i < len(test.pre); i += 2 { k, v := test.pre[i], test.pre[i+1] tr.Set(k, v) } oldV, written := tr.Put(test.newK, func(old interface{}, exists bool) (newV interface{}, write bool) { if g, e := exists, test.exists; g != e { t.Fatal(iTest, g, e) } if exists { if g, e := old.(int), test.oldV; g != e { t.Fatal(iTest, g, e) } } return -1, test.write }) if test.exists { if g, e := oldV.(int), test.oldV; g != e { t.Fatal(iTest, g, e) } } if g, e := written, test.write; g != e { t.Fatal(iTest, g, e) } n := len(test.post) en, err := tr.SeekFirst() if err != nil { if n == 0 && err == io.EOF { continue } t.Fatal(iTest, err) } for i := 0; i < len(test.post); i += 2 { k, v, err := en.Next() if err != nil { t.Fatal(iTest, err) } if g, e := k.(int), test.post[i]; g != e { t.Fatal(iTest, g, e) } if g, e := v.(int), test.post[i+1]; g != e { t.Fatal(iTest, g, e) } } _, _, err = en.Next() if g, e := err, io.EOF; g != e { t.Fatal(iTest, g, e) } } }
GrimDerp/flynn
Godeps/_workspace/src/github.com/cznic/b/all_test.go
GO
bsd-3-clause
20,505
/// Copyright (c) 2012 Ecma International. All rights reserved. /** * @path ch15/15.2/15.2.3/15.2.3.6/15.2.3.6-3-33.js * @description Object.defineProperty - 'Attributes' is a Function object which implements its own [[Get]] method to access the 'enumerable' property (8.10.5 step 3.a) */ function testcase() { var obj = {}; var accessed = false; var fun = function () { }; fun.enumerable = true; Object.defineProperty(obj, "property", fun); for (var prop in obj) { if (prop === "property") { accessed = true; } } return accessed; } runTestCase(testcase);
Oceanswave/NiL.JS
Tests/tests/sputnik/ch15/15.2/15.2.3/15.2.3.6/15.2.3.6-3-33.js
JavaScript
bsd-3-clause
675
// // UYLAppDelegate.h // Collection // // Created by Keith Harrison http://useyourloaf.com // Copyright (c) 2013 Keith Harrison. 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 Keith Harrison 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 HOLDER ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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. #import <UIKit/UIKit.h> @interface UYLAppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @end
Arul15/All_CodeExamples-master
Collection/Collection/UYLAppDelegate.h
C
bsd-3-clause
1,750
/// Copyright (c) 2012 Ecma International. All rights reserved. /** * @path ch15/15.2/15.2.3/15.2.3.3/15.2.3.3-4-173.js * @description Object.getOwnPropertyDescriptor returns data desc for functions on built-ins (SyntaxError.prototype.constructor) */ function testcase() { var desc = Object.getOwnPropertyDescriptor(SyntaxError.prototype, "constructor"); if (desc.value === SyntaxError.prototype.constructor && desc.writable === true && desc.enumerable === false && desc.configurable === true) { return true; } } runTestCase(testcase);
Oceanswave/NiL.JS
Tests/tests/sputnik/ch15/15.2/15.2.3/15.2.3.3/15.2.3.3-4-173.js
JavaScript
bsd-3-clause
572
/// Copyright (c) 2012 Ecma International. All rights reserved. /** * @path ch15/15.4/15.4.3/15.4.3.2/15.4.3.2-0-2.js * @description Array.isArray must exist as a function taking 1 parameter */ function testcase() { if (Array.isArray.length === 1) { return true; } } runTestCase(testcase);
Oceanswave/NiL.JS
Tests/tests/sputnik/ch15/15.4/15.4.3/15.4.3.2/15.4.3.2-0-2.js
JavaScript
bsd-3-clause
306
/// Copyright (c) 2012 Ecma International. All rights reserved. /** * @path ch15/15.4/15.4.4/15.4.4.19/15.4.4.19-8-c-iii-2.js * @description Array.prototype.map - value of returned array element equals to 'mappedValue' */ function testcase() { function callbackfn(val, idx, obj) { return val; } var obj = { 0: 11, 1: 9, length: 2 }; var newArr = Array.prototype.map.call(obj, callbackfn); return newArr[0] === obj[0] && newArr[1] === obj[1]; } runTestCase(testcase);
Oceanswave/NiL.JS
Tests/tests/sputnik/ch15/15.4/15.4.4/15.4.4.19/15.4.4.19-8-c-iii-2.js
JavaScript
bsd-3-clause
533
//================================================================================================= /*! // \file src/blaze/Mat3Mat3Mult.cpp // \brief Source file for the 3-dimensional matrix/matrix multiplication benchmark // // Copyright (C) 2013 Klaus Iglberger - All Rights Reserved // // This file is part of the Blaze library. You can redistribute it and/or modify it under // the terms of the New (Revised) BSD License. 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 names of the Blaze development group nor the names of its contributors // may be used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT // SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED // TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR // BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. */ //================================================================================================= //************************************************************************************************* // Includes //************************************************************************************************* #include <algorithm> #include <cstdlib> #include <iostream> #include <stdexcept> #include <string> #include <vector> #include <blaze/math/Functions.h> #include <blaze/math/Infinity.h> #include <blaze/math/StaticMatrix.h> #include <blaze/util/AlignedAllocator.h> #include <blaze/util/Random.h> #include <blaze/util/Timing.h> #include <blazemark/blaze/init/StaticMatrix.h> #include <blazemark/blaze/Mat3Mat3Mult.h> #include <blazemark/blitz/Mat3Mat3Mult.h> #include <blazemark/boost/Mat3Mat3Mult.h> #include <blazemark/eigen/Mat3Mat3Mult.h> #include <blazemark/flens/Mat3Mat3Mult.h> #include <blazemark/mtl/Mat3Mat3Mult.h> #include <blazemark/system/Blitz.h> #include <blazemark/system/Config.h> #include <blazemark/system/Eigen.h> #include <blazemark/system/FLENS.h> #include <blazemark/system/MTL.h> #include <blazemark/system/Types.h> #include <blazemark/util/Benchmarks.h> #include <blazemark/util/Parser.h> #include <blazemark/util/StaticDenseRun.h> //************************************************************************************************* // Using declarations //************************************************************************************************* using blazemark::Benchmarks; using blazemark::Parser; using blazemark::StaticDenseRun; //================================================================================================= // // TYPE DEFINITIONS // //================================================================================================= //************************************************************************************************* /*!\brief Type of a benchmark run. // // This type definition specifies the type of a single benchmark run for the 3D matrix/matrix // multiplication benchmark. */ typedef StaticDenseRun<3UL> Run; //************************************************************************************************* //================================================================================================= // // UTILITY FUNCTIONS // //================================================================================================= //************************************************************************************************* /*!\brief Estimating the necessary number of steps for each benchmark. // // \param run The parameters for the benchmark run. // \return void // // This function estimates the necessary number of steps for the given benchmark based on the // performance of the Blaze library. */ void estimateSteps( Run& run ) { using blazemark::element_t; using blaze::rowMajor; typedef blaze::StaticMatrix<element_t,3UL,3UL,rowMajor> MatrixType; typedef blaze::AlignedAllocator<MatrixType> AllocatorType; blaze::setSeed( blazemark::seed ); const size_t N( run.getNumber() ); std::vector< MatrixType, AllocatorType > A( N ), B( N ), C( N ); blaze::timing::WcTimer timer; double wct( 0.0 ); size_t steps( 1UL ); blazemark::blaze::init( A ); blazemark::blaze::init( B ); while( true ) { timer.start(); for( size_t step=0UL, i=0UL; step<steps; ++step, ++i ) { if( i == N ) i = 0UL; C[i] = A[i] * B[i]; } timer.end(); wct = timer.last(); if( wct >= 0.2 ) break; steps *= 2UL; } for( size_t i=0UL; i<N; ++i ) if( C[i](0,0) < element_t(0) ) std::cerr << " Line " << __LINE__ << ": ERROR detected!!!\n"; run.setSteps( blaze::max( 1UL, ( blazemark::runtime * steps ) / timer.last() ) ); } //************************************************************************************************* //************************************************************************************************* /*!\brief Estimating the necessary number of floating point operations. // // \param run The parameters for the benchmark run. // \return void // // This function estimates the number of floating point operations required for a single // computation of the (composite) arithmetic operation. */ void estimateFlops( Run& run ) { run.setFlops( 45UL ); } //************************************************************************************************* //================================================================================================= // // BENCHMARK FUNCTIONS // //================================================================================================= //************************************************************************************************* /*!\brief 3-dimensional matrix/matrix multiplication benchmark function. // // \param runs The specified benchmark runs. // \param benchmarks The selection of benchmarks. // \return void */ void mat3mat3mult( std::vector<Run>& runs, Benchmarks benchmarks ) { std::cout << std::left; std::sort( runs.begin(), runs.end() ); size_t slowSize( blaze::inf ); for( std::vector<Run>::iterator run=runs.begin(); run!=runs.end(); ++run ) { estimateFlops( *run ); if( run->getSteps() == 0UL ) { if( run->getSize() < slowSize ) { estimateSteps( *run ); if( run->getSteps() == 1UL ) slowSize = run->getSize(); } else run->setSteps( 1UL ); } } if( benchmarks.runBlaze ) { std::cout << " Blaze [MFlop/s]:\n"; for( std::vector<Run>::iterator run=runs.begin(); run!=runs.end(); ++run ) { const size_t N ( run->getNumber() ); const size_t steps( run->getSteps() ); run->setBlazeResult( blazemark::blaze::mat3mat3mult( N, steps ) ); const double mflops( run->getFlops() * steps / run->getBlazeResult() / 1E6 ); std::cout << " " << std::setw(12) << N << mflops << std::endl; } } if( benchmarks.runBoost ) { std::cout << " Boost uBLAS [MFlop/s]:\n"; for( std::vector<Run>::iterator run=runs.begin(); run!=runs.end(); ++run ) { const size_t N ( run->getNumber() ); const size_t steps( run->getSteps() ); run->setBoostResult( blazemark::boost::mat3mat3mult( N, steps ) ); const double mflops( run->getFlops() * steps / run->getBoostResult() / 1E6 ); std::cout << " " << std::setw(12) << N << mflops << std::endl; } } #if BLAZEMARK_BLITZ_MODE if( benchmarks.runBlitz ) { std::cout << " Blitz++ [MFlop/s]:\n"; for( std::vector<Run>::iterator run=runs.begin(); run!=runs.end(); ++run ) { const size_t N ( run->getNumber() ); const size_t steps( run->getSteps() ); run->setBlitzResult( blazemark::blitz::mat3mat3mult( N, steps ) ); const double mflops( run->getFlops() * steps / run->getBlitzResult() / 1E6 ); std::cout << " " << std::setw(12) << N << mflops << std::endl; } } #endif #if BLAZEMARK_FLENS_MODE if( benchmarks.runFLENS ) { std::cout << " FLENS [MFlop/s]:\n"; for( std::vector<Run>::iterator run=runs.begin(); run!=runs.end(); ++run ) { const size_t N ( run->getNumber() ); const size_t steps( run->getSteps() ); run->setFLENSResult( blazemark::flens::mat3mat3mult( N, steps ) ); const double mflops( run->getFlops() * steps / run->getFLENSResult() / 1E6 ); std::cout << " " << std::setw(12) << N << mflops << std::endl; } } #endif #if BLAZEMARK_MTL_MODE if( benchmarks.runMTL ) { std::cout << " MTL [MFlop/s]:\n"; for( std::vector<Run>::iterator run=runs.begin(); run!=runs.end(); ++run ) { const size_t N ( run->getNumber() ); const size_t steps( run->getSteps() ); run->setMTLResult( blazemark::mtl::mat3mat3mult( N, steps ) ); const double mflops( run->getFlops() * steps / run->getMTLResult() / 1E6 ); std::cout << " " << std::setw(12) << N << mflops << std::endl; } } #endif #if BLAZEMARK_EIGEN_MODE if( benchmarks.runEigen ) { std::cout << " Eigen [MFlop/s]:\n"; for( std::vector<Run>::iterator run=runs.begin(); run!=runs.end(); ++run ) { const size_t N ( run->getNumber() ); const size_t steps( run->getSteps() ); run->setEigenResult( blazemark::eigen::mat3mat3mult( N, steps ) ); const double mflops( run->getFlops() * steps / run->getEigenResult() / 1E6 ); std::cout << " " << std::setw(12) << N << mflops << std::endl; } } #endif for( std::vector<Run>::iterator run=runs.begin(); run!=runs.end(); ++run ) { std::cout << *run; } } //************************************************************************************************* //================================================================================================= // // MAIN FUNCTION // //================================================================================================= //************************************************************************************************* /*!\brief The main function for the 3-dimensional matrix/matrix multiplication benchmark. // // \param argc The total number of command line arguments. // \param argv The array of command line arguments. // \return void */ int main( int argc, char** argv ) { std::cout << "\n 3-Dimensional Matrix/Matrix Multiplication:\n"; Benchmarks benchmarks; try { parseCommandLineArguments( argc, argv, benchmarks ); } catch( std::exception& ex ) { std::cerr << " " << ex.what() << "\n"; return EXIT_FAILURE; } const std::string installPath( INSTALL_PATH ); const std::string parameterFile( installPath + "/params/mat3mat3mult.prm" ); Parser<Run> parser; std::vector<Run> runs; try { parser.parse( parameterFile.c_str(), runs ); } catch( std::exception& ex ) { std::cerr << " Error during parameter extraction: " << ex.what() << "\n"; return EXIT_FAILURE; } try { mat3mat3mult( runs, benchmarks ); } catch( std::exception& ex ) { std::cerr << " Error during benchmark execution: " << ex.what() << "\n"; return EXIT_FAILURE; } } //*************************************************************************************************
yzxyzh/blaze-lib
blazemark/src/main/Mat3Mat3Mult.cpp
C++
bsd-3-clause
12,502
/* Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'pastetext', 'el', { button: 'Επικόλληση ως απλό κείμενο', title: 'Επικόλληση ως απλό κείμενο' } );
aodarc/flowers_room
styleguides/static/ckeditor/ckeditor/plugins/pastetext/lang/el.js
JavaScript
mit
320
/** * Prev Rollover * (c) 2013 Bill, BunKat LLC. * * Determines if a value will cause a particualr constraint to rollover to the * previous largest time period. Used primarily when a constraint has a * variable extent. * * Later is freely distributable under the MIT license. * For all details and documentation: * http://github.com/bunkat/later */ later.date.prevRollover = function(d, val, constraint, period) { var cur = constraint.val(d); return (val >= cur || !val) ? period.start(period.prev(d, period.val(d)-1)) : period.start(d); };
nmccann/later
src/date/prevrollover.js
JavaScript
mit
574
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Phaser Source: src/pixi/renderers/canvas/utils/CanvasMaskManager.js</title> <!--[if lt IE 9]> <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <link type="text/css" rel="stylesheet" href="styles/default.css"> <link type="text/css" rel="stylesheet" href="styles/sunlight.default.css"> <link type="text/css" rel="stylesheet" href="styles/site.cerulean.css"> </head> <body> <div class="container-fluid"> <div class="navbar navbar-fixed-top navbar-inverse"> <div style="position: absolute; width: 143px; height: 31px; right: 10px; top: 10px; z-index: 1050"><a href="http://phaser.io"><img src="img/phaser.png" border="0" /></a></div> <div class="navbar-inner"> <a class="brand" href="index.html">Phaser API</a> <ul class="nav"> <li class="dropdown"> <a href="namespaces.list.html" class="dropdown-toggle" data-toggle="dropdown">Namespaces<b class="caret"></b></a> <ul class="dropdown-menu "> <li class="class-depth-0"> <a href="Phaser.html">Phaser</a> </li> <li class="class-depth-0"> <a href="PIXI.html">PIXI</a> </li> </ul> </li> <li class="dropdown"> <a href="classes.list.html" class="dropdown-toggle" data-toggle="dropdown">Classes<b class="caret"></b></a> <ul class="dropdown-menu "> <li class="class-depth-1"> <a href="Phaser.Animation.html">Animation</a> </li> <li class="class-depth-1"> <a href="Phaser.AnimationManager.html">AnimationManager</a> </li> <li class="class-depth-1"> <a href="Phaser.AnimationParser.html">AnimationParser</a> </li> <li class="class-depth-1"> <a href="Phaser.ArraySet.html">ArraySet</a> </li> <li class="class-depth-1"> <a href="Phaser.ArrayUtils.html">ArrayUtils</a> </li> <li class="class-depth-1"> <a href="Phaser.AudioSprite.html">AudioSprite</a> </li> <li class="class-depth-1"> <a href="Phaser.BitmapData.html">BitmapData</a> </li> <li class="class-depth-1"> <a href="Phaser.BitmapText.html">BitmapText</a> </li> <li class="class-depth-1"> <a href="Phaser.Button.html">Button</a> </li> <li class="class-depth-1"> <a href="Phaser.Cache.html">Cache</a> </li> <li class="class-depth-1"> <a href="Phaser.Camera.html">Camera</a> </li> <li class="class-depth-1"> <a href="Phaser.Canvas.html">Canvas</a> </li> <li class="class-depth-1"> <a href="Phaser.Circle.html">Circle</a> </li> <li class="class-depth-1"> <a href="Phaser.Color.html">Color</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.Angle.html">Angle</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.Animation.html">Animation</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.AutoCull.html">AutoCull</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.Bounds.html">Bounds</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.BringToTop.html">BringToTop</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.Core.html">Core</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.Crop.html">Crop</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.Delta.html">Delta</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.Destroy.html">Destroy</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.FixedToCamera.html">FixedToCamera</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.Health.html">Health</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.InCamera.html">InCamera</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.InputEnabled.html">InputEnabled</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.InWorld.html">InWorld</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.LifeSpan.html">LifeSpan</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.LoadTexture.html">LoadTexture</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.Overlap.html">Overlap</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.PhysicsBody.html">PhysicsBody</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.Reset.html">Reset</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.ScaleMinMax.html">ScaleMinMax</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.Smoothed.html">Smoothed</a> </li> <li class="class-depth-1"> <a href="Phaser.Create.html">Create</a> </li> <li class="class-depth-1"> <a href="Phaser.Creature.html">Creature</a> </li> <li class="class-depth-1"> <a href="Phaser.Device.html">Device</a> </li> <li class="class-depth-1"> <a href="Phaser.DeviceButton.html">DeviceButton</a> </li> <li class="class-depth-1"> <a href="Phaser.DOM.html">DOM</a> </li> <li class="class-depth-1"> <a href="Phaser.Easing.html">Easing</a> </li> <li class="class-depth-2"> <a href="Phaser.Easing.Back.html">Back</a> </li> <li class="class-depth-2"> <a href="Phaser.Easing.Bounce.html">Bounce</a> </li> <li class="class-depth-2"> <a href="Phaser.Easing.Circular.html">Circular</a> </li> <li class="class-depth-2"> <a href="Phaser.Easing.Cubic.html">Cubic</a> </li> <li class="class-depth-2"> <a href="Phaser.Easing.Elastic.html">Elastic</a> </li> <li class="class-depth-2"> <a href="Phaser.Easing.Exponential.html">Exponential</a> </li> <li class="class-depth-2"> <a href="Phaser.Easing.Linear.html">Linear</a> </li> <li class="class-depth-2"> <a href="Phaser.Easing.Quadratic.html">Quadratic</a> </li> <li class="class-depth-2"> <a href="Phaser.Easing.Quartic.html">Quartic</a> </li> <li class="class-depth-2"> <a href="Phaser.Easing.Quintic.html">Quintic</a> </li> <li class="class-depth-2"> <a href="Phaser.Easing.Sinusoidal.html">Sinusoidal</a> </li> <li class="class-depth-1"> <a href="Phaser.Ellipse.html">Ellipse</a> </li> <li class="class-depth-1"> <a href="Phaser.Events.html">Events</a> </li> <li class="class-depth-1"> <a href="Phaser.Filter.html">Filter</a> </li> <li class="class-depth-1"> <a href="Phaser.FlexGrid.html">FlexGrid</a> </li> <li class="class-depth-1"> <a href="Phaser.FlexLayer.html">FlexLayer</a> </li> <li class="class-depth-1"> <a href="Phaser.Frame.html">Frame</a> </li> <li class="class-depth-1"> <a href="Phaser.FrameData.html">FrameData</a> </li> <li class="class-depth-1"> <a href="Phaser.Game.html">Game</a> </li> <li class="class-depth-1"> <a href="Phaser.GameObjectCreator.html">GameObjectCreator</a> </li> <li class="class-depth-1"> <a href="Phaser.GameObjectFactory.html">GameObjectFactory</a> </li> <li class="class-depth-1"> <a href="Phaser.Gamepad.html">Gamepad</a> </li> <li class="class-depth-1"> <a href="Phaser.Graphics.html">Graphics</a> </li> <li class="class-depth-1"> <a href="Phaser.Group.html">Group</a> </li> <li class="class-depth-1"> <a href="Phaser.Image.html">Image</a> </li> <li class="class-depth-1"> <a href="Phaser.ImageCollection.html">ImageCollection</a> </li> <li class="class-depth-1"> <a href="Phaser.Input.html">Input</a> </li> <li class="class-depth-1"> <a href="Phaser.InputHandler.html">InputHandler</a> </li> <li class="class-depth-1"> <a href="Phaser.Key.html">Key</a> </li> <li class="class-depth-1"> <a href="Phaser.Keyboard.html">Keyboard</a> </li> <li class="class-depth-1"> <a href="Phaser.Line.html">Line</a> </li> <li class="class-depth-1"> <a href="Phaser.LinkedList.html">LinkedList</a> </li> <li class="class-depth-1"> <a href="Phaser.Loader.html">Loader</a> </li> <li class="class-depth-1"> <a href="Phaser.LoaderParser.html">LoaderParser</a> </li> <li class="class-depth-1"> <a href="Phaser.Math.html">Math</a> </li> <li class="class-depth-1"> <a href="Phaser.Matrix.html">Matrix</a> </li> <li class="class-depth-1"> <a href="Phaser.Mouse.html">Mouse</a> </li> <li class="class-depth-1"> <a href="Phaser.MSPointer.html">MSPointer</a> </li> <li class="class-depth-1"> <a href="Phaser.Net.html">Net</a> </li> <li class="class-depth-1"> <a href="Phaser.Particle.html">Particle</a> </li> <li class="class-depth-1"> <a href="Phaser.Particles.html">Particles</a> </li> <li class="class-depth-2"> <a href="Phaser.Particles.Arcade.html">Arcade</a> </li> <li class="class-depth-3"> <a href="Phaser.Particles.Arcade.Emitter.html">Emitter</a> </li> <li class="class-depth-1"> <a href="Phaser.Physics.html">Physics</a> </li> <li class="class-depth-2"> <a href="Phaser.Physics.Arcade.html">Arcade</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.Arcade.Body.html">Body</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.Arcade.html#TilemapCollision">TilemapCollision</a> </li> <li class="class-depth-2"> <a href="Phaser.Physics.Ninja.html">Ninja</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.Ninja.AABB.html">AABB</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.Ninja.Body.html">Body</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.Ninja.Circle.html">Circle</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.Ninja.Tile.html">Tile</a> </li> <li class="class-depth-2"> <a href="Phaser.Physics.P2.html">P2</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.Body.html">Body</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.BodyDebug.html">BodyDebug</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.CollisionGroup.html">CollisionGroup</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.ContactMaterial.html">ContactMaterial</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.DistanceConstraint.html">DistanceConstraint</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.FixtureList.html">FixtureList</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.GearConstraint.html">GearConstraint</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.InversePointProxy.html">InversePointProxy</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.LockConstraint.html">LockConstraint</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.Material.html">Material</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.PointProxy.html">PointProxy</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.PrismaticConstraint.html">PrismaticConstraint</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.RevoluteConstraint.html">RevoluteConstraint</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.RotationalSpring.html">RotationalSpring</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.Spring.html">Spring</a> </li> <li class="class-depth-1"> <a href="Phaser.Plugin.html">Plugin</a> </li> <li class="class-depth-1"> <a href="Phaser.PluginManager.html">PluginManager</a> </li> <li class="class-depth-1"> <a href="Phaser.Point.html">Point</a> </li> <li class="class-depth-1"> <a href="Phaser.Pointer.html">Pointer</a> </li> <li class="class-depth-1"> <a href="Phaser.Polygon.html">Polygon</a> </li> <li class="class-depth-1"> <a href="Phaser.QuadTree.html">QuadTree</a> </li> <li class="class-depth-1"> <a href="Phaser.RandomDataGenerator.html">RandomDataGenerator</a> </li> <li class="class-depth-1"> <a href="Phaser.Rectangle.html">Rectangle</a> </li> <li class="class-depth-1"> <a href="Phaser.RenderTexture.html">RenderTexture</a> </li> <li class="class-depth-1"> <a href="Phaser.RequestAnimationFrame.html">RequestAnimationFrame</a> </li> <li class="class-depth-1"> <a href="Phaser.RetroFont.html">RetroFont</a> </li> <li class="class-depth-1"> <a href="Phaser.Rope.html">Rope</a> </li> <li class="class-depth-1"> <a href="Phaser.RoundedRectangle.html">RoundedRectangle</a> </li> <li class="class-depth-1"> <a href="Phaser.ScaleManager.html">ScaleManager</a> </li> <li class="class-depth-1"> <a href="Phaser.Signal.html">Signal</a> </li> <li class="class-depth-1"> <a href="Phaser.SignalBinding.html">SignalBinding</a> </li> <li class="class-depth-1"> <a href="Phaser.SinglePad.html">SinglePad</a> </li> <li class="class-depth-1"> <a href="Phaser.Sound.html">Sound</a> </li> <li class="class-depth-1"> <a href="Phaser.SoundManager.html">SoundManager</a> </li> <li class="class-depth-1"> <a href="Phaser.Sprite.html">Sprite</a> </li> <li class="class-depth-1"> <a href="Phaser.SpriteBatch.html">SpriteBatch</a> </li> <li class="class-depth-1"> <a href="Phaser.Stage.html">Stage</a> </li> <li class="class-depth-1"> <a href="Phaser.State.html">State</a> </li> <li class="class-depth-1"> <a href="Phaser.StateManager.html">StateManager</a> </li> <li class="class-depth-1"> <a href="Phaser.Text.html">Text</a> </li> <li class="class-depth-1"> <a href="Phaser.Tile.html">Tile</a> </li> <li class="class-depth-1"> <a href="Phaser.Tilemap.html">Tilemap</a> </li> <li class="class-depth-1"> <a href="Phaser.TilemapLayer.html">TilemapLayer</a> </li> <li class="class-depth-1"> <a href="Phaser.TilemapParser.html">TilemapParser</a> </li> <li class="class-depth-1"> <a href="Phaser.Tileset.html">Tileset</a> </li> <li class="class-depth-1"> <a href="Phaser.TileSprite.html">TileSprite</a> </li> <li class="class-depth-1"> <a href="Phaser.Time.html">Time</a> </li> <li class="class-depth-1"> <a href="Phaser.Timer.html">Timer</a> </li> <li class="class-depth-1"> <a href="Phaser.TimerEvent.html">TimerEvent</a> </li> <li class="class-depth-1"> <a href="Phaser.Touch.html">Touch</a> </li> <li class="class-depth-1"> <a href="Phaser.Tween.html">Tween</a> </li> <li class="class-depth-1"> <a href="Phaser.TweenData.html">TweenData</a> </li> <li class="class-depth-1"> <a href="Phaser.TweenManager.html">TweenManager</a> </li> <li class="class-depth-1"> <a href="Phaser.Utils.html">Utils</a> </li> <li class="class-depth-2"> <a href="Phaser.Utils.Debug.html">Debug</a> </li> <li class="class-depth-1"> <a href="Phaser.Video.html">Video</a> </li> <li class="class-depth-1"> <a href="Phaser.World.html">World</a> </li> <li class="class-depth-1"> <a href="PIXI.AbstractFilter.html">AbstractFilter</a> </li> <li class="class-depth-1"> <a href="PIXI.BaseTexture.html">BaseTexture</a> </li> <li class="class-depth-1"> <a href="PIXI.CanvasBuffer.html">CanvasBuffer</a> </li> <li class="class-depth-1"> <a href="PIXI.CanvasGraphics.html">CanvasGraphics</a> </li> <li class="class-depth-1"> <a href="PIXI.CanvasMaskManager.html">CanvasMaskManager</a> </li> <li class="class-depth-1"> <a href="PIXI.CanvasRenderer.html">CanvasRenderer</a> </li> <li class="class-depth-1"> <a href="PIXI.CanvasTinter.html">CanvasTinter</a> </li> <li class="class-depth-1"> <a href="PIXI.ComplexPrimitiveShader.html">ComplexPrimitiveShader</a> </li> <li class="class-depth-1"> <a href="PIXI.DisplayObject.html">DisplayObject</a> </li> <li class="class-depth-1"> <a href="PIXI.DisplayObjectContainer.html">DisplayObjectContainer</a> </li> <li class="class-depth-1"> <a href="PIXI.Event.html">Event</a> </li> <li class="class-depth-1"> <a href="PIXI.EventTarget.html">EventTarget</a> </li> <li class="class-depth-1"> <a href="PIXI.FilterTexture.html">FilterTexture</a> </li> <li class="class-depth-1"> <a href="PIXI.Graphics.html">Graphics</a> </li> <li class="class-depth-1"> <a href="PIXI.GraphicsData.html">GraphicsData</a> </li> <li class="class-depth-1"> <a href="PIXI.PIXI.html">PIXI</a> </li> <li class="class-depth-1"> <a href="PIXI.PixiFastShader.html">PixiFastShader</a> </li> <li class="class-depth-1"> <a href="PIXI.PixiShader.html">PixiShader</a> </li> <li class="class-depth-1"> <a href="PIXI.PolyK.html">PolyK</a> </li> <li class="class-depth-1"> <a href="PIXI.PrimitiveShader.html">PrimitiveShader</a> </li> <li class="class-depth-1"> <a href="PIXI.RenderTexture.html">RenderTexture</a> </li> <li class="class-depth-1"> <a href="PIXI.Rope.html">Rope</a> </li> <li class="class-depth-1"> <a href="PIXI.Sprite.html">Sprite</a> </li> <li class="class-depth-1"> <a href="PIXI.SpriteBatch.html">SpriteBatch</a> </li> <li class="class-depth-1"> <a href="PIXI.Stage.html">Stage</a> </li> <li class="class-depth-1"> <a href="PIXI.Strip.html">Strip</a> </li> <li class="class-depth-1"> <a href="PIXI.StripShader.html">StripShader</a> </li> <li class="class-depth-1"> <a href="PIXI.Texture.html">Texture</a> </li> <li class="class-depth-1"> <a href="PIXI.TilingSprite.html">TilingSprite</a> </li> <li class="class-depth-1"> <a href="PIXI.WebGLBlendModeManager.html">WebGLBlendModeManager</a> </li> <li class="class-depth-1"> <a href="PIXI.WebGLFastSpriteBatch.html">WebGLFastSpriteBatch</a> </li> <li class="class-depth-1"> <a href="PIXI.WebGLFilterManager.html">WebGLFilterManager</a> </li> <li class="class-depth-1"> <a href="PIXI.WebGLRenderer.html">WebGLRenderer</a> </li> </ul> </li> <li class="dropdown"> <a href="global.html" class="dropdown-toggle" data-toggle="dropdown">Global<b class="caret"></b></a> <ul class="dropdown-menu "> <li class="class-depth-0"> <a href="global.html#AUTO">AUTO</a> </li> <li class="class-depth-0"> <a href="global.html#BITMAPDATA">BITMAPDATA</a> </li> <li class="class-depth-0"> <a href="global.html#BITMAPTEXT">BITMAPTEXT</a> </li> <li class="class-depth-0"> <a href="global.html#blendModes">blendModes</a> </li> <li class="class-depth-0"> <a href="global.html#BUTTON">BUTTON</a> </li> <li class="class-depth-0"> <a href="global.html#CANVAS">CANVAS</a> </li> <li class="class-depth-0"> <a href="global.html#CANVAS_FILTER">CANVAS_FILTER</a> </li> <li class="class-depth-0"> <a href="global.html#CIRCLE">CIRCLE</a> </li> <li class="class-depth-0"> <a href="global.html#CREATURE">CREATURE</a> </li> <li class="class-depth-0"> <a href="global.html#DOWN">DOWN</a> </li> <li class="class-depth-0"> <a href="global.html#ELLIPSE">ELLIPSE</a> </li> <li class="class-depth-0"> <a href="global.html#EMITTER">EMITTER</a> </li> <li class="class-depth-0"> <a href="global.html#GAMES">GAMES</a> </li> <li class="class-depth-0"> <a href="global.html#GRAPHICS">GRAPHICS</a> </li> <li class="class-depth-0"> <a href="global.html#GROUP">GROUP</a> </li> <li class="class-depth-0"> <a href="global.html#HEADLESS">HEADLESS</a> </li> <li class="class-depth-0"> <a href="global.html#IMAGE">IMAGE</a> </li> <li class="class-depth-0"> <a href="global.html#LEFT">LEFT</a> </li> <li class="class-depth-0"> <a href="global.html#LINE">LINE</a> </li> <li class="class-depth-0"> <a href="global.html#MATRIX">MATRIX</a> </li> <li class="class-depth-0"> <a href="global.html#NONE">NONE</a> </li> <li class="class-depth-0"> <a href="global.html#POINT">POINT</a> </li> <li class="class-depth-0"> <a href="global.html#POINTER">POINTER</a> </li> <li class="class-depth-0"> <a href="global.html#POLYGON">POLYGON</a> </li> <li class="class-depth-0"> <a href="global.html#RECTANGLE">RECTANGLE</a> </li> <li class="class-depth-0"> <a href="global.html#RENDERTEXTURE">RENDERTEXTURE</a> </li> <li class="class-depth-0"> <a href="global.html#RETROFONT">RETROFONT</a> </li> <li class="class-depth-0"> <a href="global.html#RIGHT">RIGHT</a> </li> <li class="class-depth-0"> <a href="global.html#ROPE">ROPE</a> </li> <li class="class-depth-0"> <a href="global.html#ROUNDEDRECTANGLE">ROUNDEDRECTANGLE</a> </li> <li class="class-depth-0"> <a href="global.html#scaleModes">scaleModes</a> </li> <li class="class-depth-0"> <a href="global.html#SPRITE">SPRITE</a> </li> <li class="class-depth-0"> <a href="global.html#SPRITEBATCH">SPRITEBATCH</a> </li> <li class="class-depth-0"> <a href="global.html#TEXT">TEXT</a> </li> <li class="class-depth-0"> <a href="global.html#TILEMAP">TILEMAP</a> </li> <li class="class-depth-0"> <a href="global.html#TILEMAPLAYER">TILEMAPLAYER</a> </li> <li class="class-depth-0"> <a href="global.html#TILESPRITE">TILESPRITE</a> </li> <li class="class-depth-0"> <a href="global.html#UP">UP</a> </li> <li class="class-depth-0"> <a href="global.html#VERSION">VERSION</a> </li> <li class="class-depth-0"> <a href="global.html#VIDEO">VIDEO</a> </li> <li class="class-depth-0"> <a href="global.html#WEBGL">WEBGL</a> </li> <li class="class-depth-0"> <a href="global.html#WEBGL_FILTER">WEBGL_FILTER</a> </li> </ul> </li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Core<b class="caret"></b></a> <ul class="dropdown-menu "> <li class="class-depth-1"><a href="Phaser.Game.html">Game</a></li> <li class="class-depth-1"><a href="Phaser.Group.html">Group</a></li> <li class="class-depth-1"><a href="Phaser.World.html">World</a></li> <li class="class-depth-1"><a href="Phaser.Loader.html">Loader</a></li> <li class="class-depth-1"><a href="Phaser.Cache.html">Cache</a></li> <li class="class-depth-1"><a href="Phaser.Time.html">Time</a></li> <li class="class-depth-1"><a href="Phaser.Camera.html">Camera</a></li> <li class="class-depth-1"><a href="Phaser.StateManager.html">State Manager</a></li> <li class="class-depth-1"><a href="Phaser.TweenManager.html">Tween Manager</a></li> <li class="class-depth-1"><a href="Phaser.SoundManager.html">Sound Manager</a></li> <li class="class-depth-1"><a href="Phaser.Input.html">Input Manager</a></li> <li class="class-depth-1"><a href="Phaser.ScaleManager.html">Scale Manager</a></li> </ul> </li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Game Objects<b class="caret"></b></a> <ul class="dropdown-menu "> <li class="class-depth-1"><a href="Phaser.GameObjectFactory.html">Factory (game.add)</a></li> <li class="class-depth-1"><a href="Phaser.GameObjectCreator.html">Creator (game.make)</a></li> <li class="class-depth-1"><a href="Phaser.Sprite.html">Sprite</a></li> <li class="class-depth-1"><a href="Phaser.Image.html">Image</a></li> <li class="class-depth-1"><a href="Phaser.Sound.html">Sound</a></li> <li class="class-depth-1"><a href="Phaser.Video.html">Video</a></li> <li class="class-depth-1"><a href="Phaser.Particles.Arcade.Emitter.html">Particle Emitter</a></li> <li class="class-depth-1"><a href="Phaser.Particle.html">Particle</a></li> <li class="class-depth-1"><a href="Phaser.Text.html">Text</a></li> <li class="class-depth-1"><a href="Phaser.Tween.html">Tween</a></li> <li class="class-depth-1"><a href="Phaser.BitmapText.html">BitmapText</a></li> <li class="class-depth-1"><a href="Phaser.Tilemap.html">Tilemap</a></li> <li class="class-depth-1"><a href="Phaser.BitmapData.html">BitmapData</a></li> <li class="class-depth-1"><a href="Phaser.RetroFont.html">RetroFont</a></li> <li class="class-depth-1"><a href="Phaser.Button.html">Button</a></li> <li class="class-depth-1"><a href="Phaser.Animation.html">Animation</a></li> <li class="class-depth-1"><a href="Phaser.Graphics.html">Graphics</a></li> <li class="class-depth-1"><a href="Phaser.RenderTexture.html">RenderTexture</a></li> <li class="class-depth-1"><a href="Phaser.TileSprite.html">TileSprite</a></li> </ul> </li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Geometry<b class="caret"></b></a> <ul class="dropdown-menu "> <li class="class-depth-1"><a href="Phaser.Circle.html">Circle</a></li> <li class="class-depth-1"><a href="Phaser.Ellipse.html">Ellipse</a></li> <li class="class-depth-1"><a href="Phaser.Line.html">Line</a></li> <li class="class-depth-1"><a href="Phaser.Matrix.html">Matrix</a></li> <li class="class-depth-1"><a href="Phaser.Point.html">Point</a></li> <li class="class-depth-1"><a href="Phaser.Polygon.html">Polygon</a></li> <li class="class-depth-1"><a href="Phaser.Rectangle.html">Rectangle</a></li> <li class="class-depth-1"><a href="Phaser.RoundedRectangle.html">Rounded Rectangle</a></li> </ul> </li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Physics<b class="caret"></b></a> <ul class="dropdown-menu "> <li class="class-depth-1"><a href="Phaser.Physics.Arcade.html">Arcade Physics</a></li> <li class="class-depth-2"><a href="Phaser.Physics.Arcade.Body.html">Body</a></li> <li class="class-depth-1"><a href="Phaser.Physics.P2.html">P2 Physics</a></li> <li class="class-depth-2"><a href="Phaser.Physics.P2.Body.html">Body</a></li> <li class="class-depth-2"><a href="Phaser.Physics.P2.Spring.html">Spring</a></li> <li class="class-depth-2"><a href="Phaser.Physics.P2.CollisionGroup.html">CollisionGroup</a></li> <li class="class-depth-2"><a href="Phaser.Physics.P2.ContactMaterial.html">ContactMaterial</a></li> <li class="class-depth-1"><a href="Phaser.Physics.Ninja.html">Ninja Physics</a></li> <li class="class-depth-2"><a href="Phaser.Physics.Body.html">Body</a></li> </ul> </li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Input<b class="caret"></b></a> <ul class="dropdown-menu "> <li class="class-depth-1"><a href="Phaser.InputHandler.html">Input Handler</a></li> <li class="class-depth-1"><a href="Phaser.Pointer.html">Pointer</a></li> <li class="class-depth-1"><a href="Phaser.DeviceButton.html">Device Button</a></li> <li class="class-depth-1"><a href="Phaser.Mouse.html">Mouse</a></li> <li class="class-depth-1"><a href="Phaser.Keyboard.html">Keyboard</a></li> <li class="class-depth-1"><a href="Phaser.Key.html">Key</a></li> <li class="class-depth-1"><a href="Phaser.Gamepad.html">Gamepad</a></li> </ul> </li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Community<b class="caret"></b></a> <ul class="dropdown-menu "> <li class="class-depth-1"><a href="http://phaser.io">Phaser Web Site</a></li> <li class="class-depth-1"><a href="https://github.com/photonstorm/phaser">Phaser Github</a></li> <li class="class-depth-1"><a href="http://phaser.io/examples">Phaser Examples</a></li> <li class="class-depth-1"><a href="https://github.com/photonstorm/phaser-plugins">Phaser Plugins</a></li> <li class="class-depth-1"><a href="http://www.html5gamedevs.com/forum/14-phaser/">Forum</a></li> <li class="class-depth-1"><a href="http://stackoverflow.com/questions/tagged/phaser-framework">Stack Overflow</a></li> <li class="class-depth-1"><a href="http://phaser.io/learn">Tutorials</a></li> <li class="class-depth-1"><a href="https://confirmsubscription.com/h/r/369DE48E3E86AF1E">Newsletter</a></li> <li class="class-depth-1"><a href="http://phaser.io/community/twitter">Twitter</a></li> <li class="class-depth-1"><a href="http://phaser.io/community/irc">IRC</a></li> <li class="class-depth-1"><a href="https://www.codeandweb.com/texturepacker/phaser">Texture Packer</a></li> </ul> </li> </ul> </div> </div> <div class="row-fluid"> <div class="span12"> <div id="main"> <h1 class="page-title">Source: src/pixi/renderers/canvas/utils/CanvasMaskManager.js</h1> <section> <article> <pre class="sunlight-highlight-javascript linenums">/** * @author Mat Groves http://matgroves.com/ @Doormat23 */ /** * A set of functions used to handle masking. * * @class CanvasMaskManager * @constructor */ PIXI.CanvasMaskManager = function() { }; PIXI.CanvasMaskManager.prototype.constructor = PIXI.CanvasMaskManager; /** * This method adds it to the current stack of masks. * * @method pushMask * @param maskData {Object} the maskData that will be pushed * @param renderSession {Object} The renderSession whose context will be used for this mask manager. */ PIXI.CanvasMaskManager.prototype.pushMask = function(maskData, renderSession) { var context = renderSession.context; context.save(); var cacheAlpha = maskData.alpha; var transform = maskData.worldTransform; var resolution = renderSession.resolution; context.setTransform(transform.a * resolution, transform.b * resolution, transform.c * resolution, transform.d * resolution, transform.tx * resolution, transform.ty * resolution); PIXI.CanvasGraphics.renderGraphicsMask(maskData, context); context.clip(); maskData.worldAlpha = cacheAlpha; }; /** * Restores the current drawing context to the state it was before the mask was applied. * * @method popMask * @param renderSession {Object} The renderSession whose context will be used for this mask manager. */ PIXI.CanvasMaskManager.prototype.popMask = function(renderSession) { renderSession.context.restore(); }; </pre> </article> </section> </div> <div class="clearfix"></div> <footer> <span class="copyright"> Phaser Copyright © 2012-2015 Photon Storm Ltd. </span> <br /> <span class="jsdoc-message"> Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.3.0-alpha10</a> on Wed Jul 29 2015 14:57:51 GMT+0100 (GMT Daylight Time) using the <a href="https://github.com/terryweiss/docstrap">DocStrap template</a>. </span> </footer> </div> <br clear="both"> </div> </div> <script src="scripts/sunlight.js"></script> <script src="scripts/sunlight.javascript.js"></script> <script src="scripts/sunlight-plugin.doclinks.js"></script> <script src="scripts/sunlight-plugin.linenumbers.js"></script> <script src="scripts/sunlight-plugin.menu.js"></script> <script src="scripts/jquery.min.js"></script> <script src="scripts/jquery.scrollTo.js"></script> <script src="scripts/jquery.localScroll.js"></script> <script src="scripts/bootstrap-dropdown.js"></script> <script src="scripts/toc.js"></script> <script> Sunlight.highlightAll({lineNumbers:true, showMenu: true, enableDoclinks :true}); </script> <script> $( function () { $( "#toc" ).toc( { anchorName : function(i, heading, prefix) { return $(heading).attr("id") || ( prefix + i ); }, selectors : "h1,h2,h3,h4", showAndHide : false, scrollTo : 60 } ); $( "#toc>ul" ).addClass( "nav nav-pills nav-stacked" ); $( "#main span[id^='toc']" ).addClass( "toc-shim" ); } ); </script> </body> </html>
erbridge/fatal-attraction
lib/phaser/docs/src_pixi_renderers_canvas_utils_CanvasMaskManager.js.html
HTML
mit
36,044
@description Simulate an update on a fixture. @function can.fixture.types.Store.update @parent can.fixture.types.Store @signature `store.update(request, callback)` @param {Object} request Parameters for the request. @param {Function} callback A function to call with the updated item and headers. @body `store.update(request, response(props,headers))` simulates a request to update an items properties on a server. todosStore.update({ url: "/todos/5" }, function(props, headers){ props.id //-> 5 headers.location // "todos/5" });
marlncpe/canjs
util/fixture/doc/update.md
Markdown
mit
568
/** * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v10.1.0 * @link http://www.ag-grid.com/ * @license MIT */ "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var component_1 = require("../widgets/component"); var componentAnnotations_1 = require("../widgets/componentAnnotations"); var context_1 = require("../context/context"); var gridOptionsWrapper_1 = require("../gridOptionsWrapper"); var utils_1 = require("../utils"); var DEFAULT_TRANSLATIONS = { equals: 'Equals', notEqual: 'Not equal', lessThan: 'Less than', greaterThan: 'Greater than', inRange: 'In range', lessThanOrEqual: 'Less than or equals', greaterThanOrEqual: 'Greater than or equals', filterOoo: 'Filter...', contains: 'Contains', notContains: 'Not contains', startsWith: 'Starts with', endsWith: 'Ends with', searchOoo: 'Search...', selectAll: 'Select All', applyFilter: 'Apply Filter', clearFilter: 'Clear Filter' }; /** * T(ype) The type of this filter. ie in DateFilter T=Date * P(arams) The params that this filter can take * M(model getModel/setModel) The object that this filter serializes to * F Floating filter params * * Contains common logic to ALL filters.. Translation, apply and clear button * get/setModel context wiring.... */ var BaseFilter = (function (_super) { __extends(BaseFilter, _super); function BaseFilter() { return _super !== null && _super.apply(this, arguments) || this; } BaseFilter.prototype.init = function (params) { this.filterParams = params; this.defaultFilter = this.filterParams.defaultOption; if (this.filterParams.filterOptions) { if (this.filterParams.filterOptions.lastIndexOf(BaseFilter.EQUALS) < 0) { this.defaultFilter = this.filterParams.filterOptions[0]; } } this.customInit(); this.filter = this.defaultFilter; this.clearActive = params.clearButton === true; //Allowing for old param property apply, even though is not advertised through the interface this.applyActive = ((params.applyButton === true) || (params.apply === true)); this.newRowsActionKeep = params.newRowsAction === 'keep'; this.setTemplate(this.generateTemplate()); utils_1._.setVisible(this.eApplyButton, this.applyActive); if (this.applyActive) { this.addDestroyableEventListener(this.eApplyButton, "click", this.filterParams.filterChangedCallback); } utils_1._.setVisible(this.eClearButton, this.clearActive); if (this.clearActive) { this.addDestroyableEventListener(this.eClearButton, "click", this.onClearButton.bind(this)); } var anyButtonVisible = this.applyActive || this.clearActive; utils_1._.setVisible(this.eButtonsPanel, anyButtonVisible); this.instantiate(this.context); this.initialiseFilterBodyUi(); this.refreshFilterBodyUi(); }; BaseFilter.prototype.onClearButton = function () { this.setModel(null); this.onFilterChanged(); }; BaseFilter.prototype.floatingFilter = function (from) { if (from !== '') { var model = this.modelFromFloatingFilter(from); this.setModel(model); } else { this.resetState(); } this.onFilterChanged(); }; BaseFilter.prototype.onNewRowsLoaded = function () { if (!this.newRowsActionKeep) { this.resetState(); } }; BaseFilter.prototype.getModel = function () { if (this.isFilterActive()) { return this.serialize(); } else { return null; } }; BaseFilter.prototype.getNullableModel = function () { return this.serialize(); }; BaseFilter.prototype.setModel = function (model) { if (model) { this.parse(model); } else { this.resetState(); } this.refreshFilterBodyUi(); }; BaseFilter.prototype.doOnFilterChanged = function (applyNow) { if (applyNow === void 0) { applyNow = false; } this.filterParams.filterModifiedCallback(); var requiresApplyAndIsApplying = this.applyActive && applyNow; var notRequiresApply = !this.applyActive; var shouldFilter = notRequiresApply || requiresApplyAndIsApplying; if (shouldFilter) { this.filterParams.filterChangedCallback(); } this.refreshFilterBodyUi(); return shouldFilter; }; BaseFilter.prototype.onFilterChanged = function () { this.doOnFilterChanged(); }; BaseFilter.prototype.onFloatingFilterChanged = function (change) { //It has to be of the type FloatingFilterWithApplyChange if it gets here var casted = change; this.setModel(casted ? casted.model : null); return this.doOnFilterChanged(casted ? casted.apply : false); }; BaseFilter.prototype.generateFilterHeader = function () { return ''; }; BaseFilter.prototype.generateTemplate = function () { var translate = this.translate.bind(this); var body = this.bodyTemplate(); return "<div>\n " + this.generateFilterHeader() + "\n " + body + "\n <div class=\"ag-filter-apply-panel\" id=\"applyPanel\">\n <button type=\"button\" id=\"clearButton\">" + translate('clearFilter') + "</button>\n <button type=\"button\" id=\"applyButton\">" + translate('applyFilter') + "</button>\n </div>\n </div>"; }; BaseFilter.prototype.translate = function (toTranslate) { var translate = this.gridOptionsWrapper.getLocaleTextFunc(); return translate(toTranslate, DEFAULT_TRANSLATIONS[toTranslate]); }; return BaseFilter; }(component_1.Component)); BaseFilter.EQUALS = 'equals'; BaseFilter.NOT_EQUAL = 'notEqual'; BaseFilter.LESS_THAN = 'lessThan'; BaseFilter.LESS_THAN_OR_EQUAL = 'lessThanOrEqual'; BaseFilter.GREATER_THAN = 'greaterThan'; BaseFilter.GREATER_THAN_OR_EQUAL = 'greaterThanOrEqual'; BaseFilter.IN_RANGE = 'inRange'; BaseFilter.CONTAINS = 'contains'; //1; BaseFilter.NOT_CONTAINS = 'notContains'; //1; BaseFilter.STARTS_WITH = 'startsWith'; //4; BaseFilter.ENDS_WITH = 'endsWith'; //5; __decorate([ componentAnnotations_1.QuerySelector('#applyPanel'), __metadata("design:type", HTMLElement) ], BaseFilter.prototype, "eButtonsPanel", void 0); __decorate([ componentAnnotations_1.QuerySelector('#applyButton'), __metadata("design:type", HTMLElement) ], BaseFilter.prototype, "eApplyButton", void 0); __decorate([ componentAnnotations_1.QuerySelector('#clearButton'), __metadata("design:type", HTMLElement) ], BaseFilter.prototype, "eClearButton", void 0); __decorate([ context_1.Autowired('context'), __metadata("design:type", context_1.Context) ], BaseFilter.prototype, "context", void 0); __decorate([ context_1.Autowired('gridOptionsWrapper'), __metadata("design:type", gridOptionsWrapper_1.GridOptionsWrapper) ], BaseFilter.prototype, "gridOptionsWrapper", void 0); exports.BaseFilter = BaseFilter; /** * Every filter with a dropdown where the user can specify a comparing type against the filter values */ var ComparableBaseFilter = (function (_super) { __extends(ComparableBaseFilter, _super); function ComparableBaseFilter() { return _super !== null && _super.apply(this, arguments) || this; } ComparableBaseFilter.prototype.init = function (params) { _super.prototype.init.call(this, params); this.addDestroyableEventListener(this.eTypeSelector, "change", this.onFilterTypeChanged.bind(this)); }; ComparableBaseFilter.prototype.customInit = function () { if (!this.defaultFilter) { this.defaultFilter = this.getDefaultType(); } }; ComparableBaseFilter.prototype.generateFilterHeader = function () { var _this = this; var defaultFilterTypes = this.getApplicableFilterTypes(); var restrictedFilterTypes = this.filterParams.filterOptions; var actualFilterTypes = restrictedFilterTypes ? restrictedFilterTypes : defaultFilterTypes; var optionsHtml = actualFilterTypes.map(function (filterType) { var localeFilterName = _this.translate(filterType); return "<option value=\"" + filterType + "\">" + localeFilterName + "</option>"; }); var readOnly = optionsHtml.length == 1 ? 'disabled' : ''; return optionsHtml.length <= 0 ? '' : "<div>\n <select class=\"ag-filter-select\" id=\"filterType\" " + readOnly + ">\n " + optionsHtml.join('') + "\n </select>\n </div>"; }; ComparableBaseFilter.prototype.initialiseFilterBodyUi = function () { this.setFilterType(this.filter); }; ComparableBaseFilter.prototype.onFilterTypeChanged = function () { this.filter = this.eTypeSelector.value; this.refreshFilterBodyUi(); this.onFilterChanged(); }; ComparableBaseFilter.prototype.isFilterActive = function () { var rawFilterValues = this.filterValues(); if (this.filter === BaseFilter.IN_RANGE) { var filterValueArray = rawFilterValues; return filterValueArray[0] != null && filterValueArray[1] != null; } else { return rawFilterValues != null; } }; ComparableBaseFilter.prototype.setFilterType = function (filterType) { this.filter = filterType; this.eTypeSelector.value = filterType; }; return ComparableBaseFilter; }(BaseFilter)); __decorate([ componentAnnotations_1.QuerySelector('#filterType'), __metadata("design:type", HTMLSelectElement) ], ComparableBaseFilter.prototype, "eTypeSelector", void 0); exports.ComparableBaseFilter = ComparableBaseFilter; /** * Comparable filter with scalar underlying values (ie numbers and dates. Strings are not scalar so have to extend * ComparableBaseFilter) */ var ScalarBaseFilter = (function (_super) { __extends(ScalarBaseFilter, _super); function ScalarBaseFilter() { return _super !== null && _super.apply(this, arguments) || this; } ScalarBaseFilter.prototype.getDefaultType = function () { return BaseFilter.EQUALS; }; ScalarBaseFilter.prototype.doesFilterPass = function (params) { var value = this.filterParams.valueGetter(params.node); var comparator = this.comparator(); var rawFilterValues = this.filterValues(); var from = Array.isArray(rawFilterValues) ? rawFilterValues[0] : rawFilterValues; if (from == null) return true; var compareResult = comparator(from, value); if (this.filter === BaseFilter.EQUALS) { return compareResult === 0; } if (this.filter === BaseFilter.GREATER_THAN) { return compareResult > 0; } if (this.filter === BaseFilter.GREATER_THAN_OR_EQUAL) { return compareResult >= 0 && (value != null); } if (this.filter === BaseFilter.LESS_THAN_OR_EQUAL) { return compareResult <= 0 && (value != null); } if (this.filter === BaseFilter.LESS_THAN) { return compareResult < 0; } if (this.filter === BaseFilter.NOT_EQUAL) { return compareResult != 0; } //From now on the type is a range and rawFilterValues must be an array! var compareToResult = comparator(rawFilterValues[1], value); if (this.filter === BaseFilter.IN_RANGE) { if (!this.filterParams.inRangeInclusive) { return compareResult > 0 && compareToResult < 0; } else { return compareResult >= 0 && compareToResult <= 0; } } throw new Error('Unexpected type of date filter!: ' + this.filter); }; return ScalarBaseFilter; }(ComparableBaseFilter)); exports.ScalarBaseFilter = ScalarBaseFilter;
BenjaminVanRyseghem/cdnjs
ajax/libs/ag-grid/10.1.0/lib/filter/baseFilter.js
JavaScript
mit
13,527
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; class AddConstraintValidatorsPass implements CompilerPassInterface { public function process(ContainerBuilder $container) { if (!$container->hasDefinition('validator.validator_factory')) { return; } $validators = array(); foreach ($container->findTaggedServiceIds('validator.constraint_validator') as $id => $attributes) { if (isset($attributes[0]['alias'])) { $validators[$attributes[0]['alias']] = $id; } $definition = $container->getDefinition($id); if (!$definition->isPublic()) { throw new InvalidArgumentException(sprintf('The service "%s" must be public as it can be lazy-loaded.', $id)); } if ($definition->isAbstract()) { throw new InvalidArgumentException(sprintf('The service "%s" must not be abstract as it can be lazy-loaded.', $id)); } $validators[$definition->getClass()] = $id; } $container->getDefinition('validator.validator_factory')->replaceArgument(1, $validators); } }
SrGio/GestorFCT
vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/AddConstraintValidatorsPass.php
PHP
mit
1,558
export function foo4() {}; export const { a: [{ foo4: foo }], b, c: { foo2: [{ foo3: foo4 }] } } = bar;
wcjohnson/babylon-lightscript
test/fixtures/es2015/modules/duplicate-named-export-destructuring13/actual.js
JavaScript
mit
104
<?php global $_MODULE; $_MODULE = array(); $_MODULE['<{graphnvd3}prestashop>graphnvd3_a9f70dff230e6fc8e878043486e6cddf'] = 'NVD3 Charts'; return $_MODULE;
victorespnt/v-eshop
prestashop/modules/graphnvd3/translations/en.php
PHP
mit
159
/** * @copyright Copyright (C) 2005 - 2019 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ .js-calendar { box-shadow: 0 0 15px 4px rgba(0,0,0,.15) !important; } .calendar-container { float: left; min-width: 160px; padding: 0; list-style: none; border-radius: 5px; background-color: #ffffff !important; z-index: 1100 !important; } .calendar-container table { table-layout: fixed; max-width: 262px; border-radius: 5px; background-color: #ffffff !important; z-index: 1100 !important; } /* The main calendar widget. DIV containing a table. */ div.calendar-container table th, .calendar-container table td { padding: 8px 0; line-height: 1.1em; text-align: center; } div.calendar-container table body td { line-height: 2em; } div.calendar-container table td.title { /* This holds the current "month, year" */ vertical-align: middle; text-align: center; } .calendar-container table thead td.headrow { /* Row <TR> containing navigation buttons */ background: #fff; color: #000; } .calendar-container table thead td.name { /* Cells <TD> containing the day names */ border-bottom: 1px solid #fff; text-align: center; color: #000; } .calendar-container table thead td.weekend { /* How a weekend day name shows in header */ color: #999; } /* The body part -- contains all the days in month. */ .calendar-container table tbody td.day { /* Cells <TD> containing month days dates */ text-align: right; } .calendar-container table tbody td.wn { background: #fff; } .calendar-container table tbody td.weekend { /* Cells showing weekend days */ color: #999; } .calendar-container table tbody td.hilite { /* Hovered cells <TD> */ background: #999999; color: #ffffff; } .calendar-container table tbody td.day { border: 0; cursor : pointer; font-size: 12px; min-width: 38px; } .calendar-container table tbody td.day.wn { text-align: center; background-color: #f4f4f4; } .calendar-container table tbody td.day.selected { /* Cell showing today date */ background: #3071a9; color: #fff; border: 0; } .calendar-container table tbody td.today { position: relative; height: 100%; width: auto; font-weight: bold; } .calendar-container table tbody td.today:after { position: absolute; bottom: 3px; left: 3px; right: 3px; content: ""; height: 3px; border-radius: 1.5px; background-color: #46a546; } .calendar-container table tbody td.today.selected:after { background-color: #fff; } .calendar-container table tbody td.day:hover { cursor: pointer; background: #3d8fd7; color: #fff; } .calendar-container table tbody td.day:hover:after { background-color: #fff; } .calendar-container table tbody .disabled { color: #999; background-color: #fafafa; } .calendar-container table tbody .emptycell { /* Empty cells (the best is to hide them) */ visibility: hidden; } .calendar-container table tbody .emptyrow { /* Empty row (some months need less than 6 rows) */ display: none; } .buttons-wrapper { padding: 5px 5px; } a.js-btn.btn.btn-exit, a.js-btn.btn.btn-today, a.js-btn.btn.btn-clear { cursor: pointer; text-decoration: none; min-width: 60px; } .calendar-container .calendar-head-row td { padding: 4px 0 !important; } .calendar-container .day-name { font-size: 0.7rem; font-weight: bold; } .calendar-container .time td { padding: 8px 0 8px 8px; } .time .time-title { background-image: url("data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAABYAAAAWCAYAAADEtGw7AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAdlJREFUeNqklUsohFEUx7/5kgWGjEcRJULJSmJhITQLr8UoFko2k2SDLGZD2SglJcXOxo6Fx0ayUt4jWXgNG2rIwsgMJZPn/+o/dRvfa8yp33zfPfecM+e795x7bYqxtIAaUA2KgA3cgn3gBcsgrMQg3eAAfJtwBYa0Atg0dAugg+/3YAUcgkvqCkAVcIIy6raBCwT0/mRdymYG5Bt8VQoYBe+0Pwdpik6mwuAVNMawbJXgmr7e6FVokzKt1XBOZnYuneB54Jn+w/LEMZXTOo65nN80yNxNmyBIF4o6Ku6AXccpmzbzJstyQbs+FT/1VC6CFyU+mePTqbIBhBwp8csGn8UqO0qIz8AhstNBk8BP4As4RGCVyk8LgUVVlFvIXFXZ+4qUuZY8gn6W1QmYBKkadklM9PfLJriTYxYyEYFXpZp3s8Yj0kv9mhi0cuCTlsVMuqRWbpL0Xuo8YpAotaQnhgoQSzEAMjhuZoywfMb0UCmyKP1HmSXzJBQxpqIn9zhxA0piCJoFdqXu/bOpmeCMBiF+ZoJJ0E7gp0/AKCF71M1xCkZ4NRWSCjAIdiQ7v9UlHAcPUdfQh1QJEd7ArOg0K1dTRHJAO2hg8zhoH2IVbYElvaPgR4ABAFM/gtHnpJfxAAAAAElFTkSuQmCC"); background-repeat: no-repeat; background-position: center; }
IOC/joomla3
media/system/css/fields/calendar.css
CSS
gpl-2.0
4,279
/* * This file is part of the coreboot project. * * Copyright (C) 2012 Advanced Micro Devices, 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; 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. */ #include "AGESA.h" #include <northbridge/amd/agesa/BiosCallOuts.h> #include "OptionsIds.h" #include <cbfs.h> #include <southbridge/amd/agesa/hudson/imc.h> #include <vendorcode/amd/agesa/f15tn/Proc/Fch/FchPlatform.h> #include <stdlib.h> static AGESA_STATUS Fch_Oem_config(UINT32 Func, UINT32 FchData, VOID *ConfigPtr); const BIOS_CALLOUT_STRUCT BiosCallouts[] = { {AGESA_DO_RESET, agesa_Reset }, {AGESA_READ_SPD, agesa_ReadSpd }, {AGESA_READ_SPD_RECOVERY, agesa_NoopUnsupported }, {AGESA_RUNFUNC_ONAP, agesa_RunFuncOnAp }, {AGESA_GET_IDS_INIT_DATA, agesa_EmptyIdsInitData }, {AGESA_HOOKBEFORE_DQS_TRAINING, agesa_NoopSuccess }, {AGESA_HOOKBEFORE_EXIT_SELF_REF, agesa_NoopSuccess }, {AGESA_FCH_OEM_CALLOUT, Fch_Oem_config }, {AGESA_GNB_GFX_GET_VBIOS_IMAGE, agesa_GfxGetVbiosImage } }; const int BiosCalloutsLen = ARRAY_SIZE(BiosCallouts); /** * AMD Parmer Platform ALC272 Verb Table */ static const CODEC_ENTRY Parmer_Alc272_VerbTbl[] = { {0x11, 0x411111F0}, {0x12, 0x411111F0}, {0x13, 0x411111F0}, {0x14, 0x411111F0}, {0x15, 0x411111F0}, {0x16, 0x411111F0}, {0x17, 0x411111F0}, {0x18, 0x01a19840}, {0x19, 0x411111F0}, {0x1a, 0x01813030}, {0x1b, 0x411111F0}, {0x1d, 0x40130605}, {0x1e, 0x01441120}, {0x21, 0x01211010}, {0xff, 0xffffffff} }; static const CODEC_TBL_LIST CodecTableList[] = { {0x10ec0272, (CODEC_ENTRY*)&Parmer_Alc272_VerbTbl[0]}, {(UINT32)0x0FFFFFFFF, (CODEC_ENTRY*)0x0FFFFFFFFUL} }; #define FAN_INPUT_INTERNAL_DIODE 0 #define FAN_INPUT_TEMP0 1 #define FAN_INPUT_TEMP1 2 #define FAN_INPUT_TEMP2 3 #define FAN_INPUT_TEMP3 4 #define FAN_INPUT_TEMP0_FILTER 5 #define FAN_INPUT_ZERO 6 #define FAN_INPUT_DISABLED 7 #define FAN_AUTOMODE (1 << 0) #define FAN_LINEARMODE (1 << 1) #define FAN_STEPMODE ~(1 << 1) #define FAN_POLARITY_HIGH (1 << 2) #define FAN_POLARITY_LOW ~(1 << 2) /* Normally, 4-wire fan runs at 25KHz and 3-wire fan runs at 100Hz */ #define FREQ_28KHZ 0x0 #define FREQ_25KHZ 0x1 #define FREQ_23KHZ 0x2 #define FREQ_21KHZ 0x3 #define FREQ_29KHZ 0x4 #define FREQ_18KHZ 0x5 #define FREQ_100HZ 0xF7 #define FREQ_87HZ 0xF8 #define FREQ_58HZ 0xF9 #define FREQ_44HZ 0xFA #define FREQ_35HZ 0xFB #define FREQ_29HZ 0xFC #define FREQ_22HZ 0xFD #define FREQ_14HZ 0xFE #define FREQ_11HZ 0xFF /* Parmer Hardware Monitor Fan Control * Hardware limitation: * HWM failed to read the input temperture vi I2C, * if other software switch the I2C switch by mistake or intention. * We recommend to using IMC to control Fans, instead of HWM. */ static void oem_fan_control(FCH_DATA_BLOCK *FchParams) { /* Enable IMC fan control. the recommand way */ #if IS_ENABLED(CONFIG_HUDSON_IMC_FWM) imc_reg_init(); /* HwMonitorEnable = TRUE && HwmFchtsiAutoOpll ==FALSE to call FchECfancontrolservice */ FchParams->Hwm.HwMonitorEnable = TRUE; FchParams->Hwm.HwmFchtsiAutoPoll = FALSE;/* 0 disable, 1 enable TSI Auto Polling */ FchParams->Imc.ImcEnable = TRUE; FchParams->Hwm.HwmControl = 1; /* 1 IMC, 0 HWM */ FchParams->Imc.ImcEnableOverWrite = 1; /* 2 disable IMC , 1 enable IMC, 0 following hw strap setting */ LibAmdMemFill(&(FchParams->Imc.EcStruct), 0, sizeof(FCH_EC), FchParams->StdHeader); /* Thermal Zone Parameter */ FchParams->Imc.EcStruct.MsgFun81Zone0MsgReg0 = 0x00; FchParams->Imc.EcStruct.MsgFun81Zone0MsgReg1 = 0x00; /* Zone */ FchParams->Imc.EcStruct.MsgFun81Zone0MsgReg2 = 0x3d; //BIT0 | BIT2 | BIT5; FchParams->Imc.EcStruct.MsgFun81Zone0MsgReg3 = 0x0e;//6 | BIT3; FchParams->Imc.EcStruct.MsgFun81Zone0MsgReg4 = 0x00; FchParams->Imc.EcStruct.MsgFun81Zone0MsgReg5 = 0x54; FchParams->Imc.EcStruct.MsgFun81Zone0MsgReg6 = 0x98; /* SMBUS Address for SMBUS based temperature sensor such as SB-TSI and ADM1032 */ FchParams->Imc.EcStruct.MsgFun81Zone0MsgReg7 = 0x02; FchParams->Imc.EcStruct.MsgFun81Zone0MsgReg8 = 0x01; /* PWM steping rate in unit of PWM level percentage */ FchParams->Imc.EcStruct.MsgFun81Zone0MsgReg9 = 0x00; /* IMC Fan Policy temperature thresholds */ FchParams->Imc.EcStruct.MsgFun83Zone0MsgReg0 = 0x00; FchParams->Imc.EcStruct.MsgFun83Zone0MsgReg1 = 0x00; /* Zone */ FchParams->Imc.EcStruct.MsgFun83Zone0MsgReg2 = 0x46;///80; /*AC0 threshold in Celsius */ FchParams->Imc.EcStruct.MsgFun83Zone0MsgReg3 = 0x3c; /*AC1 threshold in Celsius */ FchParams->Imc.EcStruct.MsgFun83Zone0MsgReg4 = 0x32; /*AC2 threshold in Celsius */ FchParams->Imc.EcStruct.MsgFun83Zone0MsgReg5 = 0xff; /*AC3 threshold in Celsius, 0xFF is not define */ FchParams->Imc.EcStruct.MsgFun83Zone0MsgReg6 = 0xff; /*AC4 threshold in Celsius, 0xFF is not define */ FchParams->Imc.EcStruct.MsgFun83Zone0MsgReg7 = 0xff; /*AC5 threshold in Celsius, 0xFF is not define */ FchParams->Imc.EcStruct.MsgFun83Zone0MsgReg8 = 0xff; /*AC6 threshold in Celsius, 0xFF is not define */ FchParams->Imc.EcStruct.MsgFun83Zone0MsgReg9 = 0xff; /*AC7 lowest threshold in Celsius, 0xFF is not define */ FchParams->Imc.EcStruct.MsgFun83Zone0MsgRegA = 0x4b; /*critical threshold* in Celsius, 0xFF is not define */ FchParams->Imc.EcStruct.MsgFun83Zone0MsgRegB = 0x00; /* IMC Fan Policy PWM Settings */ FchParams->Imc.EcStruct.MsgFun85Zone0MsgReg0 = 0x00; FchParams->Imc.EcStruct.MsgFun85Zone0MsgReg1 = 0x00; /* Zone */ FchParams->Imc.EcStruct.MsgFun85Zone0MsgReg2 = 0x5a; /* AL0 percentage */ FchParams->Imc.EcStruct.MsgFun85Zone0MsgReg3 = 0x46; /* AL1 percentage */ FchParams->Imc.EcStruct.MsgFun85Zone0MsgReg4 = 0x28; /* AL2 percentage */ FchParams->Imc.EcStruct.MsgFun85Zone0MsgReg5 = 0xff; /* AL3 percentage */ FchParams->Imc.EcStruct.MsgFun85Zone0MsgReg6 = 0xff; /* AL4 percentage */ FchParams->Imc.EcStruct.MsgFun85Zone0MsgReg7 = 0xff; /* AL5 percentage */ FchParams->Imc.EcStruct.MsgFun85Zone0MsgReg8 = 0xff; /* AL6 percentage */ FchParams->Imc.EcStruct.MsgFun85Zone0MsgReg9 = 0xff; /* AL7 percentage */ FchParams->Imc.EcStruct.IMCFUNSupportBitMap = 0x111;//BIT0 | BIT4 |BIT8; /* NOTE: * FchInitLateHwm will overwrite the EcStruct with EcDefaultMassege, * AGESA put EcDefaultMassege as global data in ROM, so we can't overwride it. * so we remove it from AGESA code. Please Seee FchInitLateHwm. */ #else /* HWM fan control, the way not recommand */ FchParams->Imc.ImcEnable = FALSE; FchParams->Hwm.HwMonitorEnable = TRUE; FchParams->Hwm.HwmFchtsiAutoPoll = TRUE;/* 1 enable, 0 disable TSI Auto Polling */ #endif /* CONFIG_HUDSON_IMC_FWM */ } /** * Fch Oem setting callback * * Configure platform specific Hudson device, * such Azalia, SATA, IMC etc. */ static AGESA_STATUS Fch_Oem_config(UINT32 Func, UINT32 FchData, VOID *ConfigPtr) { AMD_CONFIG_PARAMS *StdHeader = ConfigPtr; if (StdHeader->Func == AMD_INIT_RESET) { FCH_RESET_DATA_BLOCK *FchParams_reset = (FCH_RESET_DATA_BLOCK *)FchData; printk(BIOS_DEBUG, "Fch OEM config in INIT RESET "); //FchParams_reset->EcChannel0 = TRUE; /* logical devicd 3 */ FchParams_reset->LegacyFree = IS_ENABLED(CONFIG_HUDSON_LEGACY_FREE); FchParams_reset->FchReset.Xhci0Enable = IS_ENABLED(CONFIG_HUDSON_XHCI_ENABLE); FchParams_reset->FchReset.Xhci1Enable = FALSE; } else if (StdHeader->Func == AMD_INIT_ENV) { FCH_DATA_BLOCK *FchParams_env = (FCH_DATA_BLOCK *)FchData; printk(BIOS_DEBUG, "Fch OEM config in INIT ENV "); /* Azalia Controller OEM Codec Table Pointer */ FchParams_env->Azalia.AzaliaOemCodecTablePtr = (CODEC_TBL_LIST *)(&CodecTableList[0]); /* Azalia Controller Front Panel OEM Table Pointer */ /* Fan Control */ oem_fan_control(FchParams_env); /* XHCI configuration */ FchParams_env->Usb.Xhci0Enable = IS_ENABLED(CONFIG_HUDSON_XHCI_ENABLE); FchParams_env->Usb.Xhci1Enable = FALSE; /* sata configuration */ } printk(BIOS_DEBUG, "Done\n"); return AGESA_SUCCESS; }
BTDC/coreboot
src/mainboard/lenovo/g505s/BiosCallOuts.c
C
gpl-2.0
8,486
/** * Copyright (c) 2009--2010 Red Hat, Inc. * * This software is licensed to you under the GNU General Public License, * version 2 (GPLv2). There is NO WARRANTY for this software, express or * implied, including the implied warranties of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2 * along with this software; if not, see * http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt. * * Red Hat trademarks are not licensed under GPLv2. No permission is * granted to use or replicate Red Hat trademarks that are incorporated * in this software or its documentation. */ package com.redhat.rhn.common.hibernate; import com.redhat.rhn.common.db.DatabaseException; /** * DuplicateObjectException * @version $Rev$ */ public class DuplicateObjectException extends DatabaseException { /** * Comment for <code>serialVersionUID</code> */ private static final long serialVersionUID = -4793261552293382647L; /** * Constructor * @param message error message. */ public DuplicateObjectException(String message) { super(message); } /** * Constructor * @param message exception message * @param cause the cause (which is saved for later retrieval * by the Throwable.getCause() method). (A null value is * permitted, and indicates that the cause is nonexistent or * unknown.) */ public DuplicateObjectException(String message, Throwable cause) { super(message, cause); } }
xkollar/spacewalk
java/code/src/com/redhat/rhn/common/hibernate/DuplicateObjectException.java
Java
gpl-2.0
1,534
/* Copyright (C) 2000-2002 Joakim Axelsson <gozem@linux.nu> * Patrick Schaaf <bof@bof.de> * Martin Josefsson <gandalf@wlug.westbo.se> * Copyright (C) 2003-2013 Jozsef Kadlecsik <kadlec@blackhole.kfki.hu> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ /* Kernel module implementing an IP set type: the bitmap:ip,mac type */ #include <linux/module.h> #include <linux/ip.h> #include <linux/etherdevice.h> #include <linux/skbuff.h> #include <linux/errno.h> #include <linux/if_ether.h> #include <linux/netlink.h> #include <linux/jiffies.h> #include <linux/timer.h> #include <net/netlink.h> #include <linux/netfilter/ipset/pfxlen.h> #include <linux/netfilter/ipset/ip_set.h> #include <linux/netfilter/ipset/ip_set_bitmap.h> #define IPSET_TYPE_REV_MIN 0 /* 1 Counter support added */ /* 2 Comment support added */ #define IPSET_TYPE_REV_MAX 3 /* skbinfo support added */ MODULE_LICENSE("GPL"); MODULE_AUTHOR("Jozsef Kadlecsik <kadlec@blackhole.kfki.hu>"); IP_SET_MODULE_DESC("bitmap:ip,mac", IPSET_TYPE_REV_MIN, IPSET_TYPE_REV_MAX); MODULE_ALIAS("ip_set_bitmap:ip,mac"); #define MTYPE bitmap_ipmac #define HOST_MASK 32 #define IP_SET_BITMAP_STORED_TIMEOUT enum { MAC_UNSET, /* element is set, without MAC */ MAC_FILLED, /* element is set with MAC */ }; /* Type structure */ struct bitmap_ipmac { void *members; /* the set members */ u32 first_ip; /* host byte order, included in range */ u32 last_ip; /* host byte order, included in range */ u32 elements; /* number of max elements in the set */ size_t memsize; /* members size */ struct timer_list gc; /* garbage collector */ struct ip_set *set; /* attached to this ip_set */ unsigned char extensions[0] /* MAC + data extensions */ __aligned(__alignof__(u64)); }; /* ADT structure for generic function args */ struct bitmap_ipmac_adt_elem { unsigned char ether[ETH_ALEN] __aligned(2); u16 id; u16 add_mac; }; struct bitmap_ipmac_elem { unsigned char ether[ETH_ALEN]; unsigned char filled; } __aligned(__alignof__(u64)); static inline u32 ip_to_id(const struct bitmap_ipmac *m, u32 ip) { return ip - m->first_ip; } #define get_elem(extensions, id, dsize) \ (struct bitmap_ipmac_elem *)(extensions + (id) * (dsize)) #define get_const_elem(extensions, id, dsize) \ (const struct bitmap_ipmac_elem *)(extensions + (id) * (dsize)) /* Common functions */ static inline int bitmap_ipmac_do_test(const struct bitmap_ipmac_adt_elem *e, const struct bitmap_ipmac *map, size_t dsize) { const struct bitmap_ipmac_elem *elem; if (!test_bit(e->id, map->members)) return 0; elem = get_const_elem(map->extensions, e->id, dsize); if (e->add_mac && elem->filled == MAC_FILLED) return ether_addr_equal(e->ether, elem->ether); /* Trigger kernel to fill out the ethernet address */ return -EAGAIN; } static inline int bitmap_ipmac_gc_test(u16 id, const struct bitmap_ipmac *map, size_t dsize) { const struct bitmap_ipmac_elem *elem; if (!test_bit(id, map->members)) return 0; elem = get_const_elem(map->extensions, id, dsize); /* Timer not started for the incomplete elements */ return elem->filled == MAC_FILLED; } static inline int bitmap_ipmac_is_filled(const struct bitmap_ipmac_elem *elem) { return elem->filled == MAC_FILLED; } static inline int bitmap_ipmac_add_timeout(unsigned long *timeout, const struct bitmap_ipmac_adt_elem *e, const struct ip_set_ext *ext, struct ip_set *set, struct bitmap_ipmac *map, int mode) { u32 t = ext->timeout; if (mode == IPSET_ADD_START_STORED_TIMEOUT) { if (t == set->timeout) /* Timeout was not specified, get stored one */ t = *timeout; ip_set_timeout_set(timeout, t); } else { /* If MAC is unset yet, we store plain timeout value * because the timer is not activated yet * and we can reuse it later when MAC is filled out, * possibly by the kernel */ if (e->add_mac) ip_set_timeout_set(timeout, t); else *timeout = t; } return 0; } static inline int bitmap_ipmac_do_add(const struct bitmap_ipmac_adt_elem *e, struct bitmap_ipmac *map, u32 flags, size_t dsize) { struct bitmap_ipmac_elem *elem; elem = get_elem(map->extensions, e->id, dsize); if (test_bit(e->id, map->members)) { if (elem->filled == MAC_FILLED) { if (e->add_mac && (flags & IPSET_FLAG_EXIST) && !ether_addr_equal(e->ether, elem->ether)) { /* memcpy isn't atomic */ clear_bit(e->id, map->members); smp_mb__after_atomic(); ether_addr_copy(elem->ether, e->ether); } return IPSET_ADD_FAILED; } else if (!e->add_mac) /* Already added without ethernet address */ return IPSET_ADD_FAILED; /* Fill the MAC address and trigger the timer activation */ clear_bit(e->id, map->members); smp_mb__after_atomic(); ether_addr_copy(elem->ether, e->ether); elem->filled = MAC_FILLED; return IPSET_ADD_START_STORED_TIMEOUT; } else if (e->add_mac) { /* We can store MAC too */ ether_addr_copy(elem->ether, e->ether); elem->filled = MAC_FILLED; return 0; } elem->filled = MAC_UNSET; /* MAC is not stored yet, don't start timer */ return IPSET_ADD_STORE_PLAIN_TIMEOUT; } static inline int bitmap_ipmac_do_del(const struct bitmap_ipmac_adt_elem *e, struct bitmap_ipmac *map) { return !test_and_clear_bit(e->id, map->members); } static inline int bitmap_ipmac_do_list(struct sk_buff *skb, const struct bitmap_ipmac *map, u32 id, size_t dsize) { const struct bitmap_ipmac_elem *elem = get_const_elem(map->extensions, id, dsize); return nla_put_ipaddr4(skb, IPSET_ATTR_IP, htonl(map->first_ip + id)) || (elem->filled == MAC_FILLED && nla_put(skb, IPSET_ATTR_ETHER, ETH_ALEN, elem->ether)); } static inline int bitmap_ipmac_do_head(struct sk_buff *skb, const struct bitmap_ipmac *map) { return nla_put_ipaddr4(skb, IPSET_ATTR_IP, htonl(map->first_ip)) || nla_put_ipaddr4(skb, IPSET_ATTR_IP_TO, htonl(map->last_ip)); } static int bitmap_ipmac_kadt(struct ip_set *set, const struct sk_buff *skb, const struct xt_action_param *par, enum ipset_adt adt, struct ip_set_adt_opt *opt) { struct bitmap_ipmac *map = set->data; ipset_adtfn adtfn = set->variant->adt[adt]; struct bitmap_ipmac_adt_elem e = { .id = 0, .add_mac = 1 }; struct ip_set_ext ext = IP_SET_INIT_KEXT(skb, opt, set); u32 ip; /* MAC can be src only */ if (!(opt->flags & IPSET_DIM_TWO_SRC)) return 0; ip = ntohl(ip4addr(skb, opt->flags & IPSET_DIM_ONE_SRC)); if (ip < map->first_ip || ip > map->last_ip) return -IPSET_ERR_BITMAP_RANGE; /* Backward compatibility: we don't check the second flag */ if (skb_mac_header(skb) < skb->head || (skb_mac_header(skb) + ETH_HLEN) > skb->data) return -EINVAL; e.id = ip_to_id(map, ip); memcpy(e.ether, eth_hdr(skb)->h_source, ETH_ALEN); return adtfn(set, &e, &ext, &opt->ext, opt->cmdflags); } static int bitmap_ipmac_uadt(struct ip_set *set, struct nlattr *tb[], enum ipset_adt adt, u32 *lineno, u32 flags, bool retried) { const struct bitmap_ipmac *map = set->data; ipset_adtfn adtfn = set->variant->adt[adt]; struct bitmap_ipmac_adt_elem e = { .id = 0 }; struct ip_set_ext ext = IP_SET_INIT_UEXT(set); u32 ip = 0; int ret = 0; if (tb[IPSET_ATTR_LINENO]) *lineno = nla_get_u32(tb[IPSET_ATTR_LINENO]); if (unlikely(!tb[IPSET_ATTR_IP])) return -IPSET_ERR_PROTOCOL; ret = ip_set_get_hostipaddr4(tb[IPSET_ATTR_IP], &ip); if (ret) return ret; ret = ip_set_get_extensions(set, tb, &ext); if (ret) return ret; if (ip < map->first_ip || ip > map->last_ip) return -IPSET_ERR_BITMAP_RANGE; e.id = ip_to_id(map, ip); if (tb[IPSET_ATTR_ETHER]) { if (nla_len(tb[IPSET_ATTR_ETHER]) != ETH_ALEN) return -IPSET_ERR_PROTOCOL; memcpy(e.ether, nla_data(tb[IPSET_ATTR_ETHER]), ETH_ALEN); e.add_mac = 1; } ret = adtfn(set, &e, &ext, &ext, flags); return ip_set_eexist(ret, flags) ? 0 : ret; } static bool bitmap_ipmac_same_set(const struct ip_set *a, const struct ip_set *b) { const struct bitmap_ipmac *x = a->data; const struct bitmap_ipmac *y = b->data; return x->first_ip == y->first_ip && x->last_ip == y->last_ip && a->timeout == b->timeout && a->extensions == b->extensions; } /* Plain variant */ #include "ip_set_bitmap_gen.h" /* Create bitmap:ip,mac type of sets */ static bool init_map_ipmac(struct ip_set *set, struct bitmap_ipmac *map, u32 first_ip, u32 last_ip, u32 elements) { map->members = ip_set_alloc(map->memsize); if (!map->members) return false; map->first_ip = first_ip; map->last_ip = last_ip; map->elements = elements; set->timeout = IPSET_NO_TIMEOUT; map->set = set; set->data = map; set->family = NFPROTO_IPV4; return true; } static int bitmap_ipmac_create(struct net *net, struct ip_set *set, struct nlattr *tb[], u32 flags) { u32 first_ip = 0, last_ip = 0; u64 elements; struct bitmap_ipmac *map; int ret; if (unlikely(!tb[IPSET_ATTR_IP] || !ip_set_optattr_netorder(tb, IPSET_ATTR_TIMEOUT) || !ip_set_optattr_netorder(tb, IPSET_ATTR_CADT_FLAGS))) return -IPSET_ERR_PROTOCOL; ret = ip_set_get_hostipaddr4(tb[IPSET_ATTR_IP], &first_ip); if (ret) return ret; if (tb[IPSET_ATTR_IP_TO]) { ret = ip_set_get_hostipaddr4(tb[IPSET_ATTR_IP_TO], &last_ip); if (ret) return ret; if (first_ip > last_ip) { u32 tmp = first_ip; first_ip = last_ip; last_ip = tmp; } } else if (tb[IPSET_ATTR_CIDR]) { u8 cidr = nla_get_u8(tb[IPSET_ATTR_CIDR]); if (cidr >= HOST_MASK) return -IPSET_ERR_INVALID_CIDR; ip_set_mask_from_to(first_ip, last_ip, cidr); } else { return -IPSET_ERR_PROTOCOL; } elements = (u64)last_ip - first_ip + 1; if (elements > IPSET_BITMAP_MAX_RANGE + 1) return -IPSET_ERR_BITMAP_RANGE_SIZE; set->dsize = ip_set_elem_len(set, tb, sizeof(struct bitmap_ipmac_elem), __alignof__(struct bitmap_ipmac_elem)); map = ip_set_alloc(sizeof(*map) + elements * set->dsize); if (!map) return -ENOMEM; map->memsize = bitmap_bytes(0, elements - 1); set->variant = &bitmap_ipmac; if (!init_map_ipmac(set, map, first_ip, last_ip, elements)) { kfree(map); return -ENOMEM; } if (tb[IPSET_ATTR_TIMEOUT]) { set->timeout = ip_set_timeout_uget(tb[IPSET_ATTR_TIMEOUT]); bitmap_ipmac_gc_init(set, bitmap_ipmac_gc); } return 0; } static struct ip_set_type bitmap_ipmac_type = { .name = "bitmap:ip,mac", .protocol = IPSET_PROTOCOL, .features = IPSET_TYPE_IP | IPSET_TYPE_MAC, .dimension = IPSET_DIM_TWO, .family = NFPROTO_IPV4, .revision_min = IPSET_TYPE_REV_MIN, .revision_max = IPSET_TYPE_REV_MAX, .create = bitmap_ipmac_create, .create_policy = { [IPSET_ATTR_IP] = { .type = NLA_NESTED }, [IPSET_ATTR_IP_TO] = { .type = NLA_NESTED }, [IPSET_ATTR_CIDR] = { .type = NLA_U8 }, [IPSET_ATTR_TIMEOUT] = { .type = NLA_U32 }, [IPSET_ATTR_CADT_FLAGS] = { .type = NLA_U32 }, }, .adt_policy = { [IPSET_ATTR_IP] = { .type = NLA_NESTED }, [IPSET_ATTR_ETHER] = { .type = NLA_BINARY, .len = ETH_ALEN }, [IPSET_ATTR_TIMEOUT] = { .type = NLA_U32 }, [IPSET_ATTR_LINENO] = { .type = NLA_U32 }, [IPSET_ATTR_BYTES] = { .type = NLA_U64 }, [IPSET_ATTR_PACKETS] = { .type = NLA_U64 }, [IPSET_ATTR_COMMENT] = { .type = NLA_NUL_STRING, .len = IPSET_MAX_COMMENT_SIZE }, [IPSET_ATTR_SKBMARK] = { .type = NLA_U64 }, [IPSET_ATTR_SKBPRIO] = { .type = NLA_U32 }, [IPSET_ATTR_SKBQUEUE] = { .type = NLA_U16 }, }, .me = THIS_MODULE, }; static int __init bitmap_ipmac_init(void) { return ip_set_type_register(&bitmap_ipmac_type); } static void __exit bitmap_ipmac_fini(void) { rcu_barrier(); ip_set_type_unregister(&bitmap_ipmac_type); } module_init(bitmap_ipmac_init); module_exit(bitmap_ipmac_fini);
djbw/linux
net/netfilter/ipset/ip_set_bitmap_ipmac.c
C
gpl-2.0
11,840
require 'drb/drb' require 'rinda/tuplespace' uri = ARGV.shift DRb.start_service(uri, Rinda::TupleSpace.new) puts DRb.uri DRb.thread.join
atmark-techno/atmark-dist
user/ruby/ruby-2.1.2/sample/drb/rinda_ts.rb
Ruby
gpl-2.0
138
/* * Copyright 2009 Freescale Semicondutor, 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 * 2 of the License, or (at your option) any later version. * * provides masks and opcode images for use by code generation, emulation * and for instructions that older assemblers might not know about */ #ifndef _ASM_POWERPC_PPC_OPCODE_H #define _ASM_POWERPC_PPC_OPCODE_H #include <linux/stringify.h> #include <asm/asm-compat.h> /* sorted alphabetically */ #define PPC_INST_DCBA 0x7c0005ec #define PPC_INST_DCBA_MASK 0xfc0007fe #define PPC_INST_DCBAL 0x7c2005ec #define PPC_INST_DCBZL 0x7c2007ec #define PPC_INST_ISEL 0x7c00001e #define PPC_INST_ISEL_MASK 0xfc00003e #define PPC_INST_LSWI 0x7c0004aa #define PPC_INST_LSWX 0x7c00042a #define PPC_INST_LWSYNC 0x7c2004ac #define PPC_INST_LXVD2X 0x7c000698 #define PPC_INST_MCRXR 0x7c000400 #define PPC_INST_MCRXR_MASK 0xfc0007fe #define PPC_INST_MFSPR_PVR 0x7c1f42a6 #define PPC_INST_MFSPR_PVR_MASK 0xfc1fffff #define PPC_INST_MSGSND 0x7c00019c #define PPC_INST_NOP 0x60000000 #define PPC_INST_POPCNTB 0x7c0000f4 #define PPC_INST_POPCNTB_MASK 0xfc0007fe #define PPC_INST_RFCI 0x4c000066 #define PPC_INST_RFDI 0x4c00004e #define PPC_INST_RFMCI 0x4c00004c #define PPC_INST_STRING 0x7c00042a #define PPC_INST_STRING_MASK 0xfc0007fe #define PPC_INST_STRING_GEN_MASK 0xfc00067e #define PPC_INST_STSWI 0x7c0005aa #define PPC_INST_STSWX 0x7c00052a #define PPC_INST_STXVD2X 0x7c000798 #define PPC_INST_TLBIE 0x7c000264 #define PPC_INST_TLBILX 0x7c000024 #define PPC_INST_WAIT 0x7c00007c /* macros to insert fields into opcodes */ #define __PPC_RA(a) (((a) & 0x1f) << 16) #define __PPC_RB(b) (((b) & 0x1f) << 11) #define __PPC_RS(s) (((s) & 0x1f) << 21) #define __PPC_XS(s) ((((s) & 0x1f) << 21) | (((s) & 0x20) >> 5)) #define __PPC_T_TLB(t) (((t) & 0x3) << 21) #define __PPC_WC(w) (((w) & 0x3) << 21) /* Deal with instructions that older assemblers aren't aware of */ #define PPC_DCBAL(a, b) stringify_in_c(.long PPC_INST_DCBAL | \ __PPC_RA(a) | __PPC_RB(b)) #define PPC_DCBZL(a, b) stringify_in_c(.long PPC_INST_DCBZL | \ __PPC_RA(a) | __PPC_RB(b)) #define PPC_MSGSND(b) stringify_in_c(.long PPC_INST_MSGSND | \ __PPC_RB(b)) #define PPC_RFCI stringify_in_c(.long PPC_INST_RFCI) #define PPC_RFDI stringify_in_c(.long PPC_INST_RFDI) #define PPC_RFMCI stringify_in_c(.long PPC_INST_RFMCI) #define PPC_TLBILX(t, a, b) stringify_in_c(.long PPC_INST_TLBILX | \ __PPC_T_TLB(t) | __PPC_RA(a) | __PPC_RB(b)) #define PPC_TLBILX_ALL(a, b) PPC_TLBILX(0, a, b) #define PPC_TLBILX_PID(a, b) PPC_TLBILX(1, a, b) #define PPC_TLBILX_VA(a, b) PPC_TLBILX(3, a, b) #define PPC_WAIT(w) stringify_in_c(.long PPC_INST_WAIT | \ __PPC_WC(w)) #define PPC_TLBIE(lp,a) stringify_in_c(.long PPC_INST_TLBIE | \ __PPC_RB(a) | __PPC_RS(lp)) /* * Define what the VSX XX1 form instructions will look like, then add * the 128 bit load store instructions based on that. */ #define VSX_XX1(s, a, b) (__PPC_XS(s) | __PPC_RA(a) | __PPC_RB(b)) #define STXVD2X(s, a, b) stringify_in_c(.long PPC_INST_STXVD2X | \ VSX_XX1((s), (a), (b))) #define LXVD2X(s, a, b) stringify_in_c(.long PPC_INST_LXVD2X | \ VSX_XX1((s), (a), (b))) #endif /* _ASM_POWERPC_PPC_OPCODE_H */
stevelord/PR30
linux-2.6.31/arch/powerpc/include/asm/ppc-opcode.h
C
gpl-2.0
3,442
#!/bin/bash set -e source ./scripts/mod_helpers.sh if test "$(mod_filename mac80211)" = "mac80211.ko.gz" ; then compr=".gz" else compr="" fi for driver in $(find ${BACKPORT_DIR} -type f -name *.ko); do mod_name=${driver/${BACKPORT_DIR}/${KLIB}${KMODDIR}}${compr} echo " uninstall" $mod_name rm -f $mod_name done
tank0412/android_kernel_xiaomi_latte
uefi/cht/modules/iwlwifi/scripts/uninstall.sh
Shell
gpl-2.0
322
// SPDX-License-Identifier: GPL-2.0 /* * Intel SOC Telemetry debugfs Driver: Currently supports APL * Copyright (c) 2015, Intel Corporation. * All Rights Reserved. * * This file provides the debugfs interfaces for telemetry. * /sys/kernel/debug/telemetry/pss_info: Shows Primary Control Sub-Sys Counters * /sys/kernel/debug/telemetry/ioss_info: Shows IO Sub-System Counters * /sys/kernel/debug/telemetry/soc_states: Shows SoC State * /sys/kernel/debug/telemetry/pss_trace_verbosity: Read and Change Tracing * Verbosity via firmware * /sys/kernel/debug/telemetry/ioss_race_verbosity: Write and Change Tracing * Verbosity via firmware */ #include <linux/debugfs.h> #include <linux/device.h> #include <linux/module.h> #include <linux/pci.h> #include <linux/seq_file.h> #include <linux/suspend.h> #include <asm/cpu_device_id.h> #include <asm/intel-family.h> #include <asm/intel_pmc_ipc.h> #include <asm/intel_telemetry.h> #define DRIVER_NAME "telemetry_soc_debugfs" #define DRIVER_VERSION "1.0.0" /* ApolloLake SoC Event-IDs */ #define TELEM_APL_PSS_PSTATES_ID 0x2802 #define TELEM_APL_PSS_IDLE_ID 0x2806 #define TELEM_APL_PCS_IDLE_BLOCKED_ID 0x2C00 #define TELEM_APL_PCS_S0IX_BLOCKED_ID 0x2C01 #define TELEM_APL_PSS_WAKEUP_ID 0x2C02 #define TELEM_APL_PSS_LTR_BLOCKING_ID 0x2C03 #define TELEM_APL_S0IX_TOTAL_OCC_ID 0x4000 #define TELEM_APL_S0IX_SHLW_OCC_ID 0x4001 #define TELEM_APL_S0IX_DEEP_OCC_ID 0x4002 #define TELEM_APL_S0IX_TOTAL_RES_ID 0x4800 #define TELEM_APL_S0IX_SHLW_RES_ID 0x4801 #define TELEM_APL_S0IX_DEEP_RES_ID 0x4802 #define TELEM_APL_D0IX_ID 0x581A #define TELEM_APL_D3_ID 0x5819 #define TELEM_APL_PG_ID 0x5818 #define TELEM_INFO_SRAMEVTS_MASK 0xFF00 #define TELEM_INFO_SRAMEVTS_SHIFT 0x8 #define TELEM_SSRAM_READ_TIMEOUT 10 #define TELEM_MASK_BIT 1 #define TELEM_MASK_BYTE 0xFF #define BYTES_PER_LONG 8 #define TELEM_APL_MASK_PCS_STATE 0xF /* Max events in bitmap to check for */ #define TELEM_PSS_IDLE_EVTS 25 #define TELEM_PSS_IDLE_BLOCKED_EVTS 20 #define TELEM_PSS_S0IX_BLOCKED_EVTS 20 #define TELEM_PSS_S0IX_WAKEUP_EVTS 20 #define TELEM_PSS_LTR_BLOCKING_EVTS 20 #define TELEM_IOSS_DX_D0IX_EVTS 25 #define TELEM_IOSS_PG_EVTS 30 #define TELEM_CHECK_AND_PARSE_EVTS(EVTID, EVTNUM, BUF, EVTLOG, EVTDAT, MASK) { \ if (evtlog[index].telem_evtid == (EVTID)) { \ for (idx = 0; idx < (EVTNUM); idx++) \ (BUF)[idx] = ((EVTLOG) >> (EVTDAT)[idx].bit_pos) & \ (MASK); \ continue; \ } \ } #define TELEM_CHECK_AND_PARSE_CTRS(EVTID, CTR) { \ if (evtlog[index].telem_evtid == (EVTID)) { \ (CTR) = evtlog[index].telem_evtlog; \ continue; \ } \ } static u8 suspend_prep_ok; static u32 suspend_shlw_ctr_temp, suspend_deep_ctr_temp; static u64 suspend_shlw_res_temp, suspend_deep_res_temp; struct telemetry_susp_stats { u32 shlw_ctr; u32 deep_ctr; u64 shlw_res; u64 deep_res; }; /* Bitmap definitions for default counters in APL */ struct telem_pss_idle_stateinfo { const char *name; u32 bit_pos; }; static struct telem_pss_idle_stateinfo telem_apl_pss_idle_data[] = { {"IA_CORE0_C1E", 0}, {"IA_CORE1_C1E", 1}, {"IA_CORE2_C1E", 2}, {"IA_CORE3_C1E", 3}, {"IA_CORE0_C6", 16}, {"IA_CORE1_C6", 17}, {"IA_CORE2_C6", 18}, {"IA_CORE3_C6", 19}, {"IA_MODULE0_C7", 32}, {"IA_MODULE1_C7", 33}, {"GT_RC6", 40}, {"IUNIT_PROCESSING_IDLE", 41}, {"FAR_MEM_IDLE", 43}, {"DISPLAY_IDLE", 44}, {"IUNIT_INPUT_SYSTEM_IDLE", 45}, {"PCS_STATUS", 60}, }; struct telem_pcs_blkd_info { const char *name; u32 bit_pos; }; static struct telem_pcs_blkd_info telem_apl_pcs_idle_blkd_data[] = { {"COMPUTE", 0}, {"MISC", 8}, {"MODULE_ACTIONS_PENDING", 16}, {"LTR", 24}, {"DISPLAY_WAKE", 32}, {"ISP_WAKE", 40}, {"PSF0_ACTIVE", 48}, }; static struct telem_pcs_blkd_info telem_apl_pcs_s0ix_blkd_data[] = { {"LTR", 0}, {"IRTL", 8}, {"WAKE_DEADLINE_PENDING", 16}, {"DISPLAY", 24}, {"ISP", 32}, {"CORE", 40}, {"PMC", 48}, {"MISC", 56}, }; struct telem_pss_ltr_info { const char *name; u32 bit_pos; }; static struct telem_pss_ltr_info telem_apl_pss_ltr_data[] = { {"CORE_ACTIVE", 0}, {"MEM_UP", 8}, {"DFX", 16}, {"DFX_FORCE_LTR", 24}, {"DISPLAY", 32}, {"ISP", 40}, {"SOUTH", 48}, }; struct telem_pss_wakeup_info { const char *name; u32 bit_pos; }; static struct telem_pss_wakeup_info telem_apl_pss_wakeup[] = { {"IP_IDLE", 0}, {"DISPLAY_WAKE", 8}, {"VOLTAGE_REG_INT", 16}, {"DROWSY_TIMER (HOTPLUG)", 24}, {"CORE_WAKE", 32}, {"MISC_S0IX", 40}, {"MISC_ABORT", 56}, }; struct telem_ioss_d0ix_stateinfo { const char *name; u32 bit_pos; }; static struct telem_ioss_d0ix_stateinfo telem_apl_ioss_d0ix_data[] = { {"CSE", 0}, {"SCC2", 1}, {"GMM", 2}, {"XDCI", 3}, {"XHCI", 4}, {"ISH", 5}, {"AVS", 6}, {"PCIE0P1", 7}, {"PECI0P0", 8}, {"LPSS", 9}, {"SCC", 10}, {"PWM", 11}, {"PCIE1_P3", 12}, {"PCIE1_P2", 13}, {"PCIE1_P1", 14}, {"PCIE1_P0", 15}, {"CNV", 16}, {"SATA", 17}, {"PRTC", 18}, }; struct telem_ioss_pg_info { const char *name; u32 bit_pos; }; static struct telem_ioss_pg_info telem_apl_ioss_pg_data[] = { {"LPSS", 0}, {"SCC", 1}, {"P2SB", 2}, {"SCC2", 3}, {"GMM", 4}, {"PCIE0", 5}, {"XDCI", 6}, {"xHCI", 7}, {"CSE", 8}, {"SPI", 9}, {"AVSPGD4", 10}, {"AVSPGD3", 11}, {"AVSPGD2", 12}, {"AVSPGD1", 13}, {"ISH", 14}, {"EXI", 15}, {"NPKVRC", 16}, {"NPKVNN", 17}, {"CUNIT", 18}, {"FUSE_CTRL", 19}, {"PCIE1", 20}, {"CNV", 21}, {"LPC", 22}, {"SATA", 23}, {"SMB", 24}, {"PRTC", 25}, }; struct telemetry_debugfs_conf { struct telemetry_susp_stats suspend_stats; struct dentry *telemetry_dbg_dir; /* Bitmap Data */ struct telem_ioss_d0ix_stateinfo *ioss_d0ix_data; struct telem_pss_idle_stateinfo *pss_idle_data; struct telem_pcs_blkd_info *pcs_idle_blkd_data; struct telem_pcs_blkd_info *pcs_s0ix_blkd_data; struct telem_pss_wakeup_info *pss_wakeup; struct telem_pss_ltr_info *pss_ltr_data; struct telem_ioss_pg_info *ioss_pg_data; u8 pcs_idle_blkd_evts; u8 pcs_s0ix_blkd_evts; u8 pss_wakeup_evts; u8 pss_idle_evts; u8 pss_ltr_evts; u8 ioss_d0ix_evts; u8 ioss_pg_evts; /* IDs */ u16 pss_ltr_blocking_id; u16 pcs_idle_blkd_id; u16 pcs_s0ix_blkd_id; u16 s0ix_total_occ_id; u16 s0ix_shlw_occ_id; u16 s0ix_deep_occ_id; u16 s0ix_total_res_id; u16 s0ix_shlw_res_id; u16 s0ix_deep_res_id; u16 pss_wakeup_id; u16 ioss_d0ix_id; u16 pstates_id; u16 pss_idle_id; u16 ioss_d3_id; u16 ioss_pg_id; }; static struct telemetry_debugfs_conf *debugfs_conf; static struct telemetry_debugfs_conf telem_apl_debugfs_conf = { .pss_idle_data = telem_apl_pss_idle_data, .pcs_idle_blkd_data = telem_apl_pcs_idle_blkd_data, .pcs_s0ix_blkd_data = telem_apl_pcs_s0ix_blkd_data, .pss_ltr_data = telem_apl_pss_ltr_data, .pss_wakeup = telem_apl_pss_wakeup, .ioss_d0ix_data = telem_apl_ioss_d0ix_data, .ioss_pg_data = telem_apl_ioss_pg_data, .pss_idle_evts = ARRAY_SIZE(telem_apl_pss_idle_data), .pcs_idle_blkd_evts = ARRAY_SIZE(telem_apl_pcs_idle_blkd_data), .pcs_s0ix_blkd_evts = ARRAY_SIZE(telem_apl_pcs_s0ix_blkd_data), .pss_ltr_evts = ARRAY_SIZE(telem_apl_pss_ltr_data), .pss_wakeup_evts = ARRAY_SIZE(telem_apl_pss_wakeup), .ioss_d0ix_evts = ARRAY_SIZE(telem_apl_ioss_d0ix_data), .ioss_pg_evts = ARRAY_SIZE(telem_apl_ioss_pg_data), .pstates_id = TELEM_APL_PSS_PSTATES_ID, .pss_idle_id = TELEM_APL_PSS_IDLE_ID, .pcs_idle_blkd_id = TELEM_APL_PCS_IDLE_BLOCKED_ID, .pcs_s0ix_blkd_id = TELEM_APL_PCS_S0IX_BLOCKED_ID, .pss_wakeup_id = TELEM_APL_PSS_WAKEUP_ID, .pss_ltr_blocking_id = TELEM_APL_PSS_LTR_BLOCKING_ID, .s0ix_total_occ_id = TELEM_APL_S0IX_TOTAL_OCC_ID, .s0ix_shlw_occ_id = TELEM_APL_S0IX_SHLW_OCC_ID, .s0ix_deep_occ_id = TELEM_APL_S0IX_DEEP_OCC_ID, .s0ix_total_res_id = TELEM_APL_S0IX_TOTAL_RES_ID, .s0ix_shlw_res_id = TELEM_APL_S0IX_SHLW_RES_ID, .s0ix_deep_res_id = TELEM_APL_S0IX_DEEP_RES_ID, .ioss_d0ix_id = TELEM_APL_D0IX_ID, .ioss_d3_id = TELEM_APL_D3_ID, .ioss_pg_id = TELEM_APL_PG_ID, }; static const struct x86_cpu_id telemetry_debugfs_cpu_ids[] = { INTEL_CPU_FAM6(ATOM_GOLDMONT, telem_apl_debugfs_conf), INTEL_CPU_FAM6(ATOM_GOLDMONT_PLUS, telem_apl_debugfs_conf), {} }; MODULE_DEVICE_TABLE(x86cpu, telemetry_debugfs_cpu_ids); static int telemetry_debugfs_check_evts(void) { if ((debugfs_conf->pss_idle_evts > TELEM_PSS_IDLE_EVTS) || (debugfs_conf->pcs_idle_blkd_evts > TELEM_PSS_IDLE_BLOCKED_EVTS) || (debugfs_conf->pcs_s0ix_blkd_evts > TELEM_PSS_S0IX_BLOCKED_EVTS) || (debugfs_conf->pss_ltr_evts > TELEM_PSS_LTR_BLOCKING_EVTS) || (debugfs_conf->pss_wakeup_evts > TELEM_PSS_S0IX_WAKEUP_EVTS) || (debugfs_conf->ioss_d0ix_evts > TELEM_IOSS_DX_D0IX_EVTS) || (debugfs_conf->ioss_pg_evts > TELEM_IOSS_PG_EVTS)) return -EINVAL; return 0; } static int telem_pss_states_show(struct seq_file *s, void *unused) { struct telemetry_evtlog evtlog[TELEM_MAX_OS_ALLOCATED_EVENTS]; struct telemetry_debugfs_conf *conf = debugfs_conf; const char *name[TELEM_MAX_OS_ALLOCATED_EVENTS]; u32 pcs_idle_blkd[TELEM_PSS_IDLE_BLOCKED_EVTS], pcs_s0ix_blkd[TELEM_PSS_S0IX_BLOCKED_EVTS], pss_s0ix_wakeup[TELEM_PSS_S0IX_WAKEUP_EVTS], pss_ltr_blkd[TELEM_PSS_LTR_BLOCKING_EVTS], pss_idle[TELEM_PSS_IDLE_EVTS]; int index, idx, ret, err = 0; u64 pstates = 0; ret = telemetry_read_eventlog(TELEM_PSS, evtlog, TELEM_MAX_OS_ALLOCATED_EVENTS); if (ret < 0) return ret; err = telemetry_get_evtname(TELEM_PSS, name, TELEM_MAX_OS_ALLOCATED_EVENTS); if (err < 0) return err; seq_puts(s, "\n----------------------------------------------------\n"); seq_puts(s, "\tPSS TELEM EVENTLOG (Residency = field/19.2 us\n"); seq_puts(s, "----------------------------------------------------\n"); for (index = 0; index < ret; index++) { seq_printf(s, "%-32s %llu\n", name[index], evtlog[index].telem_evtlog); /* Fetch PSS IDLE State */ if (evtlog[index].telem_evtid == conf->pss_idle_id) { pss_idle[conf->pss_idle_evts - 1] = (evtlog[index].telem_evtlog >> conf->pss_idle_data[conf->pss_idle_evts - 1].bit_pos) & TELEM_APL_MASK_PCS_STATE; } TELEM_CHECK_AND_PARSE_EVTS(conf->pss_idle_id, conf->pss_idle_evts - 1, pss_idle, evtlog[index].telem_evtlog, conf->pss_idle_data, TELEM_MASK_BIT); TELEM_CHECK_AND_PARSE_EVTS(conf->pcs_idle_blkd_id, conf->pcs_idle_blkd_evts, pcs_idle_blkd, evtlog[index].telem_evtlog, conf->pcs_idle_blkd_data, TELEM_MASK_BYTE); TELEM_CHECK_AND_PARSE_EVTS(conf->pcs_s0ix_blkd_id, conf->pcs_s0ix_blkd_evts, pcs_s0ix_blkd, evtlog[index].telem_evtlog, conf->pcs_s0ix_blkd_data, TELEM_MASK_BYTE); TELEM_CHECK_AND_PARSE_EVTS(conf->pss_wakeup_id, conf->pss_wakeup_evts, pss_s0ix_wakeup, evtlog[index].telem_evtlog, conf->pss_wakeup, TELEM_MASK_BYTE); TELEM_CHECK_AND_PARSE_EVTS(conf->pss_ltr_blocking_id, conf->pss_ltr_evts, pss_ltr_blkd, evtlog[index].telem_evtlog, conf->pss_ltr_data, TELEM_MASK_BYTE); if (evtlog[index].telem_evtid == debugfs_conf->pstates_id) pstates = evtlog[index].telem_evtlog; } seq_puts(s, "\n--------------------------------------\n"); seq_puts(s, "PStates\n"); seq_puts(s, "--------------------------------------\n"); seq_puts(s, "Domain\t\t\t\tFreq(Mhz)\n"); seq_printf(s, " IA\t\t\t\t %llu\n GT\t\t\t\t %llu\n", (pstates & TELEM_MASK_BYTE)*100, ((pstates >> 8) & TELEM_MASK_BYTE)*50/3); seq_printf(s, " IUNIT\t\t\t\t %llu\n SA\t\t\t\t %llu\n", ((pstates >> 16) & TELEM_MASK_BYTE)*25, ((pstates >> 24) & TELEM_MASK_BYTE)*50/3); seq_puts(s, "\n--------------------------------------\n"); seq_puts(s, "PSS IDLE Status\n"); seq_puts(s, "--------------------------------------\n"); seq_puts(s, "Device\t\t\t\t\tIDLE\n"); for (index = 0; index < debugfs_conf->pss_idle_evts; index++) { seq_printf(s, "%-32s\t%u\n", debugfs_conf->pss_idle_data[index].name, pss_idle[index]); } seq_puts(s, "\n--------------------------------------\n"); seq_puts(s, "PSS Idle blkd Status (~1ms saturating bucket)\n"); seq_puts(s, "--------------------------------------\n"); seq_puts(s, "Blocker\t\t\t\t\tCount\n"); for (index = 0; index < debugfs_conf->pcs_idle_blkd_evts; index++) { seq_printf(s, "%-32s\t%u\n", debugfs_conf->pcs_idle_blkd_data[index].name, pcs_idle_blkd[index]); } seq_puts(s, "\n--------------------------------------\n"); seq_puts(s, "PSS S0ix blkd Status (~1ms saturating bucket)\n"); seq_puts(s, "--------------------------------------\n"); seq_puts(s, "Blocker\t\t\t\t\tCount\n"); for (index = 0; index < debugfs_conf->pcs_s0ix_blkd_evts; index++) { seq_printf(s, "%-32s\t%u\n", debugfs_conf->pcs_s0ix_blkd_data[index].name, pcs_s0ix_blkd[index]); } seq_puts(s, "\n--------------------------------------\n"); seq_puts(s, "LTR Blocking Status (~1ms saturating bucket)\n"); seq_puts(s, "--------------------------------------\n"); seq_puts(s, "Blocker\t\t\t\t\tCount\n"); for (index = 0; index < debugfs_conf->pss_ltr_evts; index++) { seq_printf(s, "%-32s\t%u\n", debugfs_conf->pss_ltr_data[index].name, pss_s0ix_wakeup[index]); } seq_puts(s, "\n--------------------------------------\n"); seq_puts(s, "Wakes Status (~1ms saturating bucket)\n"); seq_puts(s, "--------------------------------------\n"); seq_puts(s, "Wakes\t\t\t\t\tCount\n"); for (index = 0; index < debugfs_conf->pss_wakeup_evts; index++) { seq_printf(s, "%-32s\t%u\n", debugfs_conf->pss_wakeup[index].name, pss_ltr_blkd[index]); } return 0; } DEFINE_SHOW_ATTRIBUTE(telem_pss_states); static int telem_ioss_states_show(struct seq_file *s, void *unused) { struct telemetry_evtlog evtlog[TELEM_MAX_OS_ALLOCATED_EVENTS]; const char *name[TELEM_MAX_OS_ALLOCATED_EVENTS]; int index, ret, err; ret = telemetry_read_eventlog(TELEM_IOSS, evtlog, TELEM_MAX_OS_ALLOCATED_EVENTS); if (ret < 0) return ret; err = telemetry_get_evtname(TELEM_IOSS, name, TELEM_MAX_OS_ALLOCATED_EVENTS); if (err < 0) return err; seq_puts(s, "--------------------------------------\n"); seq_puts(s, "\tI0SS TELEMETRY EVENTLOG\n"); seq_puts(s, "--------------------------------------\n"); for (index = 0; index < ret; index++) { seq_printf(s, "%-32s 0x%llx\n", name[index], evtlog[index].telem_evtlog); } return 0; } DEFINE_SHOW_ATTRIBUTE(telem_ioss_states); static int telem_soc_states_show(struct seq_file *s, void *unused) { u32 d3_sts[TELEM_IOSS_DX_D0IX_EVTS], d0ix_sts[TELEM_IOSS_DX_D0IX_EVTS]; u32 pg_sts[TELEM_IOSS_PG_EVTS], pss_idle[TELEM_PSS_IDLE_EVTS]; struct telemetry_evtlog evtlog[TELEM_MAX_OS_ALLOCATED_EVENTS]; u32 s0ix_total_ctr = 0, s0ix_shlw_ctr = 0, s0ix_deep_ctr = 0; u64 s0ix_total_res = 0, s0ix_shlw_res = 0, s0ix_deep_res = 0; struct telemetry_debugfs_conf *conf = debugfs_conf; struct pci_dev *dev = NULL; int index, idx, ret; u32 d3_state; u16 pmcsr; ret = telemetry_read_eventlog(TELEM_IOSS, evtlog, TELEM_MAX_OS_ALLOCATED_EVENTS); if (ret < 0) return ret; for (index = 0; index < ret; index++) { TELEM_CHECK_AND_PARSE_EVTS(conf->ioss_d3_id, conf->ioss_d0ix_evts, d3_sts, evtlog[index].telem_evtlog, conf->ioss_d0ix_data, TELEM_MASK_BIT); TELEM_CHECK_AND_PARSE_EVTS(conf->ioss_pg_id, conf->ioss_pg_evts, pg_sts, evtlog[index].telem_evtlog, conf->ioss_pg_data, TELEM_MASK_BIT); TELEM_CHECK_AND_PARSE_EVTS(conf->ioss_d0ix_id, conf->ioss_d0ix_evts, d0ix_sts, evtlog[index].telem_evtlog, conf->ioss_d0ix_data, TELEM_MASK_BIT); TELEM_CHECK_AND_PARSE_CTRS(conf->s0ix_total_occ_id, s0ix_total_ctr); TELEM_CHECK_AND_PARSE_CTRS(conf->s0ix_shlw_occ_id, s0ix_shlw_ctr); TELEM_CHECK_AND_PARSE_CTRS(conf->s0ix_deep_occ_id, s0ix_deep_ctr); TELEM_CHECK_AND_PARSE_CTRS(conf->s0ix_total_res_id, s0ix_total_res); TELEM_CHECK_AND_PARSE_CTRS(conf->s0ix_shlw_res_id, s0ix_shlw_res); TELEM_CHECK_AND_PARSE_CTRS(conf->s0ix_deep_res_id, s0ix_deep_res); } seq_puts(s, "\n---------------------------------------------------\n"); seq_puts(s, "S0IX Type\t\t\t Occurrence\t\t Residency(us)\n"); seq_puts(s, "---------------------------------------------------\n"); seq_printf(s, "S0IX Shallow\t\t\t %10u\t %10llu\n", s0ix_shlw_ctr - conf->suspend_stats.shlw_ctr, (u64)((s0ix_shlw_res - conf->suspend_stats.shlw_res)*10/192)); seq_printf(s, "S0IX Deep\t\t\t %10u\t %10llu\n", s0ix_deep_ctr - conf->suspend_stats.deep_ctr, (u64)((s0ix_deep_res - conf->suspend_stats.deep_res)*10/192)); seq_printf(s, "Suspend(With S0ixShallow)\t %10u\t %10llu\n", conf->suspend_stats.shlw_ctr, (u64)(conf->suspend_stats.shlw_res*10)/192); seq_printf(s, "Suspend(With S0ixDeep)\t\t %10u\t %10llu\n", conf->suspend_stats.deep_ctr, (u64)(conf->suspend_stats.deep_res*10)/192); seq_printf(s, "TOTAL S0IX\t\t\t %10u\t %10llu\n", s0ix_total_ctr, (u64)(s0ix_total_res*10/192)); seq_puts(s, "\n-------------------------------------------------\n"); seq_puts(s, "\t\tDEVICE STATES\n"); seq_puts(s, "-------------------------------------------------\n"); for_each_pci_dev(dev) { pci_read_config_word(dev, dev->pm_cap + PCI_PM_CTRL, &pmcsr); d3_state = ((pmcsr & PCI_PM_CTRL_STATE_MASK) == (__force int)PCI_D3hot) ? 1 : 0; seq_printf(s, "pci %04x %04X %s %20.20s: ", dev->vendor, dev->device, dev_name(&dev->dev), dev_driver_string(&dev->dev)); seq_printf(s, " d3:%x\n", d3_state); } seq_puts(s, "\n--------------------------------------\n"); seq_puts(s, "D3/D0i3 Status\n"); seq_puts(s, "--------------------------------------\n"); seq_puts(s, "Block\t\t D3\t D0i3\n"); for (index = 0; index < conf->ioss_d0ix_evts; index++) { seq_printf(s, "%-10s\t %u\t %u\n", conf->ioss_d0ix_data[index].name, d3_sts[index], d0ix_sts[index]); } seq_puts(s, "\n--------------------------------------\n"); seq_puts(s, "South Complex PowerGate Status\n"); seq_puts(s, "--------------------------------------\n"); seq_puts(s, "Device\t\t PG\n"); for (index = 0; index < conf->ioss_pg_evts; index++) { seq_printf(s, "%-10s\t %u\n", conf->ioss_pg_data[index].name, pg_sts[index]); } evtlog->telem_evtid = conf->pss_idle_id; ret = telemetry_read_events(TELEM_PSS, evtlog, 1); if (ret < 0) return ret; seq_puts(s, "\n-----------------------------------------\n"); seq_puts(s, "North Idle Status\n"); seq_puts(s, "-----------------------------------------\n"); for (idx = 0; idx < conf->pss_idle_evts - 1; idx++) { pss_idle[idx] = (evtlog->telem_evtlog >> conf->pss_idle_data[idx].bit_pos) & TELEM_MASK_BIT; } pss_idle[idx] = (evtlog->telem_evtlog >> conf->pss_idle_data[idx].bit_pos) & TELEM_APL_MASK_PCS_STATE; for (index = 0; index < conf->pss_idle_evts; index++) { seq_printf(s, "%-30s %u\n", conf->pss_idle_data[index].name, pss_idle[index]); } seq_puts(s, "\nPCS_STATUS Code\n"); seq_puts(s, "0:C0 1:C1 2:C1_DN_WT_DEV 3:C2 4:C2_WT_DE_MEM_UP\n"); seq_puts(s, "5:C2_WT_DE_MEM_DOWN 6:C2_UP_WT_DEV 7:C2_DN 8:C2_VOA\n"); seq_puts(s, "9:C2_VOA_UP 10:S0IX_PRE 11:S0IX\n"); return 0; } DEFINE_SHOW_ATTRIBUTE(telem_soc_states); static int telem_s0ix_res_get(void *data, u64 *val) { u64 s0ix_total_res; int ret; ret = intel_pmc_s0ix_counter_read(&s0ix_total_res); if (ret) { pr_err("Failed to read S0ix residency"); return ret; } *val = s0ix_total_res; return 0; } DEFINE_DEBUGFS_ATTRIBUTE(telem_s0ix_fops, telem_s0ix_res_get, NULL, "%llu\n"); static int telem_pss_trc_verb_show(struct seq_file *s, void *unused) { u32 verbosity; int err; err = telemetry_get_trace_verbosity(TELEM_PSS, &verbosity); if (err) { pr_err("Get PSS Trace Verbosity Failed with Error %d\n", err); return -EFAULT; } seq_printf(s, "PSS Trace Verbosity %u\n", verbosity); return 0; } static ssize_t telem_pss_trc_verb_write(struct file *file, const char __user *userbuf, size_t count, loff_t *ppos) { u32 verbosity; int err; err = kstrtou32_from_user(userbuf, count, 0, &verbosity); if (err) return err; err = telemetry_set_trace_verbosity(TELEM_PSS, verbosity); if (err) { pr_err("Changing PSS Trace Verbosity Failed. Error %d\n", err); return err; } return count; } static int telem_pss_trc_verb_open(struct inode *inode, struct file *file) { return single_open(file, telem_pss_trc_verb_show, inode->i_private); } static const struct file_operations telem_pss_trc_verb_ops = { .open = telem_pss_trc_verb_open, .read = seq_read, .write = telem_pss_trc_verb_write, .llseek = seq_lseek, .release = single_release, }; static int telem_ioss_trc_verb_show(struct seq_file *s, void *unused) { u32 verbosity; int err; err = telemetry_get_trace_verbosity(TELEM_IOSS, &verbosity); if (err) { pr_err("Get IOSS Trace Verbosity Failed with Error %d\n", err); return -EFAULT; } seq_printf(s, "IOSS Trace Verbosity %u\n", verbosity); return 0; } static ssize_t telem_ioss_trc_verb_write(struct file *file, const char __user *userbuf, size_t count, loff_t *ppos) { u32 verbosity; int err; err = kstrtou32_from_user(userbuf, count, 0, &verbosity); if (err) return err; err = telemetry_set_trace_verbosity(TELEM_IOSS, verbosity); if (err) { pr_err("Changing IOSS Trace Verbosity Failed. Error %d\n", err); return err; } return count; } static int telem_ioss_trc_verb_open(struct inode *inode, struct file *file) { return single_open(file, telem_ioss_trc_verb_show, inode->i_private); } static const struct file_operations telem_ioss_trc_verb_ops = { .open = telem_ioss_trc_verb_open, .read = seq_read, .write = telem_ioss_trc_verb_write, .llseek = seq_lseek, .release = single_release, }; static int pm_suspend_prep_cb(void) { struct telemetry_evtlog evtlog[TELEM_MAX_OS_ALLOCATED_EVENTS]; struct telemetry_debugfs_conf *conf = debugfs_conf; int ret, index; ret = telemetry_raw_read_eventlog(TELEM_IOSS, evtlog, TELEM_MAX_OS_ALLOCATED_EVENTS); if (ret < 0) { suspend_prep_ok = 0; goto out; } for (index = 0; index < ret; index++) { TELEM_CHECK_AND_PARSE_CTRS(conf->s0ix_shlw_occ_id, suspend_shlw_ctr_temp); TELEM_CHECK_AND_PARSE_CTRS(conf->s0ix_deep_occ_id, suspend_deep_ctr_temp); TELEM_CHECK_AND_PARSE_CTRS(conf->s0ix_shlw_res_id, suspend_shlw_res_temp); TELEM_CHECK_AND_PARSE_CTRS(conf->s0ix_deep_res_id, suspend_deep_res_temp); } suspend_prep_ok = 1; out: return NOTIFY_OK; } static int pm_suspend_exit_cb(void) { struct telemetry_evtlog evtlog[TELEM_MAX_OS_ALLOCATED_EVENTS]; static u32 suspend_shlw_ctr_exit, suspend_deep_ctr_exit; static u64 suspend_shlw_res_exit, suspend_deep_res_exit; struct telemetry_debugfs_conf *conf = debugfs_conf; int ret, index; if (!suspend_prep_ok) goto out; ret = telemetry_raw_read_eventlog(TELEM_IOSS, evtlog, TELEM_MAX_OS_ALLOCATED_EVENTS); if (ret < 0) goto out; for (index = 0; index < ret; index++) { TELEM_CHECK_AND_PARSE_CTRS(conf->s0ix_shlw_occ_id, suspend_shlw_ctr_exit); TELEM_CHECK_AND_PARSE_CTRS(conf->s0ix_deep_occ_id, suspend_deep_ctr_exit); TELEM_CHECK_AND_PARSE_CTRS(conf->s0ix_shlw_res_id, suspend_shlw_res_exit); TELEM_CHECK_AND_PARSE_CTRS(conf->s0ix_deep_res_id, suspend_deep_res_exit); } if ((suspend_shlw_ctr_exit < suspend_shlw_ctr_temp) || (suspend_deep_ctr_exit < suspend_deep_ctr_temp) || (suspend_shlw_res_exit < suspend_shlw_res_temp) || (suspend_deep_res_exit < suspend_deep_res_temp)) { pr_err("Wrong s0ix counters detected\n"); goto out; } /* * Due to some design limitations in the firmware, sometimes the * counters do not get updated by the time we reach here. As a * workaround, we try to see if this was a genuine case of sleep * failure or not by cross-checking from PMC GCR registers directly. */ if (suspend_shlw_ctr_exit == suspend_shlw_ctr_temp && suspend_deep_ctr_exit == suspend_deep_ctr_temp) { ret = intel_pmc_gcr_read64(PMC_GCR_TELEM_SHLW_S0IX_REG, &suspend_shlw_res_exit); if (ret < 0) goto out; ret = intel_pmc_gcr_read64(PMC_GCR_TELEM_DEEP_S0IX_REG, &suspend_deep_res_exit); if (ret < 0) goto out; if (suspend_shlw_res_exit > suspend_shlw_res_temp) suspend_shlw_ctr_exit++; if (suspend_deep_res_exit > suspend_deep_res_temp) suspend_deep_ctr_exit++; } suspend_shlw_ctr_exit -= suspend_shlw_ctr_temp; suspend_deep_ctr_exit -= suspend_deep_ctr_temp; suspend_shlw_res_exit -= suspend_shlw_res_temp; suspend_deep_res_exit -= suspend_deep_res_temp; if (suspend_shlw_ctr_exit != 0) { conf->suspend_stats.shlw_ctr += suspend_shlw_ctr_exit; conf->suspend_stats.shlw_res += suspend_shlw_res_exit; } if (suspend_deep_ctr_exit != 0) { conf->suspend_stats.deep_ctr += suspend_deep_ctr_exit; conf->suspend_stats.deep_res += suspend_deep_res_exit; } out: suspend_prep_ok = 0; return NOTIFY_OK; } static int pm_notification(struct notifier_block *this, unsigned long event, void *ptr) { switch (event) { case PM_SUSPEND_PREPARE: return pm_suspend_prep_cb(); case PM_POST_SUSPEND: return pm_suspend_exit_cb(); } return NOTIFY_DONE; } static struct notifier_block pm_notifier = { .notifier_call = pm_notification, }; static int __init telemetry_debugfs_init(void) { const struct x86_cpu_id *id; int err; struct dentry *dir; /* Only APL supported for now */ id = x86_match_cpu(telemetry_debugfs_cpu_ids); if (!id) return -ENODEV; debugfs_conf = (struct telemetry_debugfs_conf *)id->driver_data; err = telemetry_pltconfig_valid(); if (err < 0) { pr_info("Invalid pltconfig, ensure IPC1 device is enabled in BIOS\n"); return -ENODEV; } err = telemetry_debugfs_check_evts(); if (err < 0) { pr_info("telemetry_debugfs_check_evts failed\n"); return -EINVAL; } register_pm_notifier(&pm_notifier); dir = debugfs_create_dir("telemetry", NULL); debugfs_conf->telemetry_dbg_dir = dir; debugfs_create_file("pss_info", S_IFREG | S_IRUGO, dir, NULL, &telem_pss_states_fops); debugfs_create_file("ioss_info", S_IFREG | S_IRUGO, dir, NULL, &telem_ioss_states_fops); debugfs_create_file("soc_states", S_IFREG | S_IRUGO, dir, NULL, &telem_soc_states_fops); debugfs_create_file("s0ix_residency_usec", S_IFREG | S_IRUGO, dir, NULL, &telem_s0ix_fops); debugfs_create_file("pss_trace_verbosity", S_IFREG | S_IRUGO, dir, NULL, &telem_pss_trc_verb_ops); debugfs_create_file("ioss_trace_verbosity", S_IFREG | S_IRUGO, dir, NULL, &telem_ioss_trc_verb_ops); return 0; } static void __exit telemetry_debugfs_exit(void) { debugfs_remove_recursive(debugfs_conf->telemetry_dbg_dir); debugfs_conf->telemetry_dbg_dir = NULL; unregister_pm_notifier(&pm_notifier); } late_initcall(telemetry_debugfs_init); module_exit(telemetry_debugfs_exit); MODULE_AUTHOR("Souvik Kumar Chakravarty <souvik.k.chakravarty@intel.com>"); MODULE_DESCRIPTION("Intel SoC Telemetry debugfs Interface"); MODULE_VERSION(DRIVER_VERSION); MODULE_LICENSE("GPL v2");
c0d3z3r0/linux-rockchip
drivers/platform/x86/intel_telemetry_debugfs.c
C
gpl-2.0
27,264
<?php /** Abkhazian (Аҧсшәа) * * See MessagesQqq.php for message documentation incl. usage of parameters * To improve a translation please visit http://translatewiki.net * * @ingroup Language * @file * */ $fallback = 'ru'; $namespaceNames = array( NS_MEDIA => 'Амедиа', NS_SPECIAL => 'Цастәи', NS_TALK => 'Ахцәажәара', NS_USER => 'Алахәыла', NS_USER_TALK => 'Алахәыла_ахцәажәара', NS_PROJECT_TALK => '$1_ахцәажәара', NS_FILE => 'Афаил', NS_FILE_TALK => 'Афаил_ахцәажәара', NS_MEDIAWIKI => 'Амедиавики', NS_MEDIAWIKI_TALK => 'Амедиавики_ахцәажәара', NS_TEMPLATE => 'Ашаблон', NS_TEMPLATE_TALK => 'Ашаблон_ахцәажәара', NS_HELP => 'Ацхыраара', NS_HELP_TALK => 'Ацхыраара_ахцәажәара', NS_CATEGORY => 'Акатегориа', NS_CATEGORY_TALK => 'Акатегориа_ахцәажәара', ); $namespaceAliases = array( 'Иалахә' => NS_USER, // Backward compat. Fallbacks from 'ru'. 'Медиа' => NS_MEDIA, 'Служебная' => NS_SPECIAL, 'Обсуждение' => NS_TALK, 'Участник' => NS_USER, 'Обсуждение_участника' => NS_USER_TALK, 'Обсуждение_$1' => NS_PROJECT_TALK, 'Файл' => NS_FILE, 'Обсуждение_файла' => NS_FILE_TALK, 'MediaWiki' => NS_MEDIAWIKI, 'Обсуждение_MediaWiki' => NS_MEDIAWIKI_TALK, 'Шаблон' => NS_TEMPLATE, 'Обсуждение_шаблона' => NS_TEMPLATE_TALK, 'Справка' => NS_HELP, 'Обсуждение_справки' => NS_HELP_TALK, 'Категория' => NS_CATEGORY, 'Обсуждение_категории' => NS_CATEGORY_TALK ); // Remove Russian aliases $namespaceGenderAliases = array(); $specialPageAliases = array( 'Categories' => array( 'Акатегориақәа' ), 'Mycontributions' => array( 'Архиарақәа' ), 'Mypage' => array( 'Садаҟьа' ), 'Mytalk' => array( 'Сахцәажәара' ), 'Newimages' => array( 'АфаилқәаҾыц' ), 'Newpages' => array( 'АдаҟьақәаҾыц' ), 'Randompage' => array( 'Машәырлатәи' ), 'Recentchanges' => array( 'АрҽеираҾыцқәа' ), 'Search' => array( 'Аҧшаара' ), 'Specialpages' => array( 'ЦастәиАдаҟьақәа' ), 'Upload' => array( 'Аҭагалара' ), ); $magicWords = array( 'language' => array( '0', '#АБЫЗШӘА:', '#ЯЗЫК:', '#LANGUAGE:' ), 'special' => array( '0', 'цастәи', 'служебная', 'special' ), 'index' => array( '1', '__АИНДЕКС__', '__ИНДЕКС__', '__INDEX__' ), );
shayzluf/lazoozweb
wiki/languages/messages/MessagesAb.php
PHP
gpl-2.0
3,170
<?php /** * This file is automatically @generated by {@link GeneratePhonePrefixData}. * Please don't modify it directly. */ return array ( 86159 => 'China Mobile', );
CTSATLAS/wordpress
wp-content/plugins/constant-contact-api/vendor/giggsey/libphonenumber-for-php/src/libphonenumber/carrier/data/en/86159.php
PHP
gpl-2.0
173
/* SPDX-License-Identifier: GPL-2.0 */ #ifndef _LINUX_SWAP_H #define _LINUX_SWAP_H #include <linux/spinlock.h> #include <linux/linkage.h> #include <linux/mmzone.h> #include <linux/list.h> #include <linux/memcontrol.h> #include <linux/sched.h> #include <linux/node.h> #include <linux/fs.h> #include <linux/atomic.h> #include <linux/page-flags.h> #include <asm/page.h> struct notifier_block; struct bio; struct pagevec; #define SWAP_FLAG_PREFER 0x8000 /* set if swap priority specified */ #define SWAP_FLAG_PRIO_MASK 0x7fff #define SWAP_FLAG_PRIO_SHIFT 0 #define SWAP_FLAG_DISCARD 0x10000 /* enable discard for swap */ #define SWAP_FLAG_DISCARD_ONCE 0x20000 /* discard swap area at swapon-time */ #define SWAP_FLAG_DISCARD_PAGES 0x40000 /* discard page-clusters after use */ #define SWAP_FLAGS_VALID (SWAP_FLAG_PRIO_MASK | SWAP_FLAG_PREFER | \ SWAP_FLAG_DISCARD | SWAP_FLAG_DISCARD_ONCE | \ SWAP_FLAG_DISCARD_PAGES) #define SWAP_BATCH 64 static inline int current_is_kswapd(void) { return current->flags & PF_KSWAPD; } /* * MAX_SWAPFILES defines the maximum number of swaptypes: things which can * be swapped to. The swap type and the offset into that swap type are * encoded into pte's and into pgoff_t's in the swapcache. Using five bits * for the type means that the maximum number of swapcache pages is 27 bits * on 32-bit-pgoff_t architectures. And that assumes that the architecture packs * the type/offset into the pte as 5/27 as well. */ #define MAX_SWAPFILES_SHIFT 5 /* * Use some of the swap files numbers for other purposes. This * is a convenient way to hook into the VM to trigger special * actions on faults. */ /* * Unaddressable device memory support. See include/linux/hmm.h and * Documentation/vm/hmm.rst. Short description is we need struct pages for * device memory that is unaddressable (inaccessible) by CPU, so that we can * migrate part of a process memory to device memory. * * When a page is migrated from CPU to device, we set the CPU page table entry * to a special SWP_DEVICE_* entry. */ #ifdef CONFIG_DEVICE_PRIVATE #define SWP_DEVICE_NUM 2 #define SWP_DEVICE_WRITE (MAX_SWAPFILES+SWP_HWPOISON_NUM+SWP_MIGRATION_NUM) #define SWP_DEVICE_READ (MAX_SWAPFILES+SWP_HWPOISON_NUM+SWP_MIGRATION_NUM+1) #else #define SWP_DEVICE_NUM 0 #endif /* * NUMA node memory migration support */ #ifdef CONFIG_MIGRATION #define SWP_MIGRATION_NUM 2 #define SWP_MIGRATION_READ (MAX_SWAPFILES + SWP_HWPOISON_NUM) #define SWP_MIGRATION_WRITE (MAX_SWAPFILES + SWP_HWPOISON_NUM + 1) #else #define SWP_MIGRATION_NUM 0 #endif /* * Handling of hardware poisoned pages with memory corruption. */ #ifdef CONFIG_MEMORY_FAILURE #define SWP_HWPOISON_NUM 1 #define SWP_HWPOISON MAX_SWAPFILES #else #define SWP_HWPOISON_NUM 0 #endif #define MAX_SWAPFILES \ ((1 << MAX_SWAPFILES_SHIFT) - SWP_DEVICE_NUM - \ SWP_MIGRATION_NUM - SWP_HWPOISON_NUM) /* * Magic header for a swap area. The first part of the union is * what the swap magic looks like for the old (limited to 128MB) * swap area format, the second part of the union adds - in the * old reserved area - some extra information. Note that the first * kilobyte is reserved for boot loader or disk label stuff... * * Having the magic at the end of the PAGE_SIZE makes detecting swap * areas somewhat tricky on machines that support multiple page sizes. * For 2.5 we'll probably want to move the magic to just beyond the * bootbits... */ union swap_header { struct { char reserved[PAGE_SIZE - 10]; char magic[10]; /* SWAP-SPACE or SWAPSPACE2 */ } magic; struct { char bootbits[1024]; /* Space for disklabel etc. */ __u32 version; __u32 last_page; __u32 nr_badpages; unsigned char sws_uuid[16]; unsigned char sws_volume[16]; __u32 padding[117]; __u32 badpages[1]; } info; }; /* * current->reclaim_state points to one of these when a task is running * memory reclaim */ struct reclaim_state { unsigned long reclaimed_slab; }; #ifdef __KERNEL__ struct address_space; struct sysinfo; struct writeback_control; struct zone; /* * A swap extent maps a range of a swapfile's PAGE_SIZE pages onto a range of * disk blocks. A list of swap extents maps the entire swapfile. (Where the * term `swapfile' refers to either a blockdevice or an IS_REG file. Apart * from setup, they're handled identically. * * We always assume that blocks are of size PAGE_SIZE. */ struct swap_extent { struct rb_node rb_node; pgoff_t start_page; pgoff_t nr_pages; sector_t start_block; }; /* * Max bad pages in the new format.. */ #define MAX_SWAP_BADPAGES \ ((offsetof(union swap_header, magic.magic) - \ offsetof(union swap_header, info.badpages)) / sizeof(int)) enum { SWP_USED = (1 << 0), /* is slot in swap_info[] used? */ SWP_WRITEOK = (1 << 1), /* ok to write to this swap? */ SWP_DISCARDABLE = (1 << 2), /* blkdev support discard */ SWP_DISCARDING = (1 << 3), /* now discarding a free cluster */ SWP_SOLIDSTATE = (1 << 4), /* blkdev seeks are cheap */ SWP_CONTINUED = (1 << 5), /* swap_map has count continuation */ SWP_BLKDEV = (1 << 6), /* its a block device */ SWP_ACTIVATED = (1 << 7), /* set after swap_activate success */ SWP_FS_OPS = (1 << 8), /* swapfile operations go through fs */ SWP_AREA_DISCARD = (1 << 9), /* single-time swap area discards */ SWP_PAGE_DISCARD = (1 << 10), /* freed swap page-cluster discards */ SWP_STABLE_WRITES = (1 << 11), /* no overwrite PG_writeback pages */ SWP_SYNCHRONOUS_IO = (1 << 12), /* synchronous IO is efficient */ SWP_VALID = (1 << 13), /* swap is valid to be operated on? */ /* add others here before... */ SWP_SCANNING = (1 << 14), /* refcount in scan_swap_map */ }; #define SWAP_CLUSTER_MAX 32UL #define COMPACT_CLUSTER_MAX SWAP_CLUSTER_MAX /* Bit flag in swap_map */ #define SWAP_HAS_CACHE 0x40 /* Flag page is cached, in first swap_map */ #define COUNT_CONTINUED 0x80 /* Flag swap_map continuation for full count */ /* Special value in first swap_map */ #define SWAP_MAP_MAX 0x3e /* Max count */ #define SWAP_MAP_BAD 0x3f /* Note page is bad */ #define SWAP_MAP_SHMEM 0xbf /* Owned by shmem/tmpfs */ /* Special value in each swap_map continuation */ #define SWAP_CONT_MAX 0x7f /* Max count */ /* * We use this to track usage of a cluster. A cluster is a block of swap disk * space with SWAPFILE_CLUSTER pages long and naturally aligns in disk. All * free clusters are organized into a list. We fetch an entry from the list to * get a free cluster. * * The data field stores next cluster if the cluster is free or cluster usage * counter otherwise. The flags field determines if a cluster is free. This is * protected by swap_info_struct.lock. */ struct swap_cluster_info { spinlock_t lock; /* * Protect swap_cluster_info fields * and swap_info_struct->swap_map * elements correspond to the swap * cluster */ unsigned int data:24; unsigned int flags:8; }; #define CLUSTER_FLAG_FREE 1 /* This cluster is free */ #define CLUSTER_FLAG_NEXT_NULL 2 /* This cluster has no next cluster */ #define CLUSTER_FLAG_HUGE 4 /* This cluster is backing a transparent huge page */ /* * We assign a cluster to each CPU, so each CPU can allocate swap entry from * its own cluster and swapout sequentially. The purpose is to optimize swapout * throughput. */ struct percpu_cluster { struct swap_cluster_info index; /* Current cluster index */ unsigned int next; /* Likely next allocation offset */ }; struct swap_cluster_list { struct swap_cluster_info head; struct swap_cluster_info tail; }; /* * The in-memory structure used to track swap areas. */ struct swap_info_struct { unsigned long flags; /* SWP_USED etc: see above */ signed short prio; /* swap priority of this type */ struct plist_node list; /* entry in swap_active_head */ signed char type; /* strange name for an index */ unsigned int max; /* extent of the swap_map */ unsigned char *swap_map; /* vmalloc'ed array of usage counts */ struct swap_cluster_info *cluster_info; /* cluster info. Only for SSD */ struct swap_cluster_list free_clusters; /* free clusters list */ unsigned int lowest_bit; /* index of first free in swap_map */ unsigned int highest_bit; /* index of last free in swap_map */ unsigned int pages; /* total of usable pages of swap */ unsigned int inuse_pages; /* number of those currently in use */ unsigned int cluster_next; /* likely index for next allocation */ unsigned int cluster_nr; /* countdown to next cluster search */ unsigned int __percpu *cluster_next_cpu; /*percpu index for next allocation */ struct percpu_cluster __percpu *percpu_cluster; /* per cpu's swap location */ struct rb_root swap_extent_root;/* root of the swap extent rbtree */ struct block_device *bdev; /* swap device or bdev of swap file */ struct file *swap_file; /* seldom referenced */ unsigned int old_block_size; /* seldom referenced */ #ifdef CONFIG_FRONTSWAP unsigned long *frontswap_map; /* frontswap in-use, one bit per page */ atomic_t frontswap_pages; /* frontswap pages in-use counter */ #endif spinlock_t lock; /* * protect map scan related fields like * swap_map, lowest_bit, highest_bit, * inuse_pages, cluster_next, * cluster_nr, lowest_alloc, * highest_alloc, free/discard cluster * list. other fields are only changed * at swapon/swapoff, so are protected * by swap_lock. changing flags need * hold this lock and swap_lock. If * both locks need hold, hold swap_lock * first. */ spinlock_t cont_lock; /* * protect swap count continuation page * list. */ struct work_struct discard_work; /* discard worker */ struct swap_cluster_list discard_clusters; /* discard clusters list */ struct plist_node avail_lists[]; /* * entries in swap_avail_heads, one * entry per node. * Must be last as the number of the * array is nr_node_ids, which is not * a fixed value so have to allocate * dynamically. * And it has to be an array so that * plist_for_each_* can work. */ }; #ifdef CONFIG_64BIT #define SWAP_RA_ORDER_CEILING 5 #else /* Avoid stack overflow, because we need to save part of page table */ #define SWAP_RA_ORDER_CEILING 3 #define SWAP_RA_PTE_CACHE_SIZE (1 << SWAP_RA_ORDER_CEILING) #endif struct vma_swap_readahead { unsigned short win; unsigned short offset; unsigned short nr_pte; #ifdef CONFIG_64BIT pte_t *ptes; #else pte_t ptes[SWAP_RA_PTE_CACHE_SIZE]; #endif }; /* linux/mm/workingset.c */ void workingset_age_nonresident(struct lruvec *lruvec, unsigned long nr_pages); void *workingset_eviction(struct page *page, struct mem_cgroup *target_memcg); void workingset_refault(struct page *page, void *shadow); void workingset_activation(struct page *page); /* Only track the nodes of mappings with shadow entries */ void workingset_update_node(struct xa_node *node); #define mapping_set_update(xas, mapping) do { \ if (!dax_mapping(mapping) && !shmem_mapping(mapping)) \ xas_set_update(xas, workingset_update_node); \ } while (0) /* linux/mm/page_alloc.c */ extern unsigned long totalreserve_pages; extern unsigned long nr_free_buffer_pages(void); /* Definition of global_zone_page_state not available yet */ #define nr_free_pages() global_zone_page_state(NR_FREE_PAGES) /* linux/mm/swap.c */ extern void lru_note_cost(struct lruvec *lruvec, bool file, unsigned int nr_pages); extern void lru_note_cost_page(struct page *); extern void lru_cache_add(struct page *); extern void mark_page_accessed(struct page *); extern void lru_add_drain(void); extern void lru_add_drain_cpu(int cpu); extern void lru_add_drain_cpu_zone(struct zone *zone); extern void lru_add_drain_all(void); extern void rotate_reclaimable_page(struct page *page); extern void deactivate_file_page(struct page *page); extern void deactivate_page(struct page *page); extern void mark_page_lazyfree(struct page *page); extern void swap_setup(void); extern void lru_cache_add_inactive_or_unevictable(struct page *page, struct vm_area_struct *vma); /* linux/mm/vmscan.c */ extern unsigned long zone_reclaimable_pages(struct zone *zone); extern unsigned long try_to_free_pages(struct zonelist *zonelist, int order, gfp_t gfp_mask, nodemask_t *mask); extern int __isolate_lru_page_prepare(struct page *page, isolate_mode_t mode); extern unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg, unsigned long nr_pages, gfp_t gfp_mask, bool may_swap); extern unsigned long mem_cgroup_shrink_node(struct mem_cgroup *mem, gfp_t gfp_mask, bool noswap, pg_data_t *pgdat, unsigned long *nr_scanned); extern unsigned long shrink_all_memory(unsigned long nr_pages); extern int vm_swappiness; extern int remove_mapping(struct address_space *mapping, struct page *page); extern unsigned long reclaim_pages(struct list_head *page_list); #ifdef CONFIG_NUMA extern int node_reclaim_mode; extern int sysctl_min_unmapped_ratio; extern int sysctl_min_slab_ratio; #else #define node_reclaim_mode 0 #endif extern void check_move_unevictable_pages(struct pagevec *pvec); extern int kswapd_run(int nid); extern void kswapd_stop(int nid); #ifdef CONFIG_SWAP #include <linux/blk_types.h> /* for bio_end_io_t */ /* linux/mm/page_io.c */ extern int swap_readpage(struct page *page, bool do_poll); extern int swap_writepage(struct page *page, struct writeback_control *wbc); extern void end_swap_bio_write(struct bio *bio); extern int __swap_writepage(struct page *page, struct writeback_control *wbc, bio_end_io_t end_write_func); extern int swap_set_page_dirty(struct page *page); int add_swap_extent(struct swap_info_struct *sis, unsigned long start_page, unsigned long nr_pages, sector_t start_block); int generic_swapfile_activate(struct swap_info_struct *, struct file *, sector_t *); /* linux/mm/swap_state.c */ /* One swap address space for each 64M swap space */ #define SWAP_ADDRESS_SPACE_SHIFT 14 #define SWAP_ADDRESS_SPACE_PAGES (1 << SWAP_ADDRESS_SPACE_SHIFT) extern struct address_space *swapper_spaces[]; #define swap_address_space(entry) \ (&swapper_spaces[swp_type(entry)][swp_offset(entry) \ >> SWAP_ADDRESS_SPACE_SHIFT]) extern unsigned long total_swapcache_pages(void); extern void show_swap_cache_info(void); extern int add_to_swap(struct page *page); extern void *get_shadow_from_swap_cache(swp_entry_t entry); extern int add_to_swap_cache(struct page *page, swp_entry_t entry, gfp_t gfp, void **shadowp); extern void __delete_from_swap_cache(struct page *page, swp_entry_t entry, void *shadow); extern void delete_from_swap_cache(struct page *); extern void clear_shadow_from_swap_cache(int type, unsigned long begin, unsigned long end); extern void free_page_and_swap_cache(struct page *); extern void free_pages_and_swap_cache(struct page **, int); extern struct page *lookup_swap_cache(swp_entry_t entry, struct vm_area_struct *vma, unsigned long addr); struct page *find_get_incore_page(struct address_space *mapping, pgoff_t index); extern struct page *read_swap_cache_async(swp_entry_t, gfp_t, struct vm_area_struct *vma, unsigned long addr, bool do_poll); extern struct page *__read_swap_cache_async(swp_entry_t, gfp_t, struct vm_area_struct *vma, unsigned long addr, bool *new_page_allocated); extern struct page *swap_cluster_readahead(swp_entry_t entry, gfp_t flag, struct vm_fault *vmf); extern struct page *swapin_readahead(swp_entry_t entry, gfp_t flag, struct vm_fault *vmf); /* linux/mm/swapfile.c */ extern atomic_long_t nr_swap_pages; extern long total_swap_pages; extern atomic_t nr_rotate_swap; extern bool has_usable_swap(void); /* Swap 50% full? Release swapcache more aggressively.. */ static inline bool vm_swap_full(void) { return atomic_long_read(&nr_swap_pages) * 2 < total_swap_pages; } static inline long get_nr_swap_pages(void) { return atomic_long_read(&nr_swap_pages); } extern void si_swapinfo(struct sysinfo *); extern swp_entry_t get_swap_page(struct page *page); extern void put_swap_page(struct page *page, swp_entry_t entry); extern swp_entry_t get_swap_page_of_type(int); extern int get_swap_pages(int n, swp_entry_t swp_entries[], int entry_size); extern int add_swap_count_continuation(swp_entry_t, gfp_t); extern void swap_shmem_alloc(swp_entry_t); extern int swap_duplicate(swp_entry_t); extern int swapcache_prepare(swp_entry_t); extern void swap_free(swp_entry_t); extern void swapcache_free_entries(swp_entry_t *entries, int n); extern int free_swap_and_cache(swp_entry_t); int swap_type_of(dev_t device, sector_t offset); int find_first_swap(dev_t *device); extern unsigned int count_swap_pages(int, int); extern sector_t map_swap_page(struct page *, struct block_device **); extern sector_t swapdev_block(int, pgoff_t); extern int page_swapcount(struct page *); extern int __swap_count(swp_entry_t entry); extern int __swp_swapcount(swp_entry_t entry); extern int swp_swapcount(swp_entry_t entry); extern struct swap_info_struct *page_swap_info(struct page *); extern struct swap_info_struct *swp_swap_info(swp_entry_t entry); extern bool reuse_swap_page(struct page *, int *); extern int try_to_free_swap(struct page *); struct backing_dev_info; extern int init_swap_address_space(unsigned int type, unsigned long nr_pages); extern void exit_swap_address_space(unsigned int type); extern struct swap_info_struct *get_swap_device(swp_entry_t entry); static inline void put_swap_device(struct swap_info_struct *si) { rcu_read_unlock(); } #else /* CONFIG_SWAP */ static inline int swap_readpage(struct page *page, bool do_poll) { return 0; } static inline struct swap_info_struct *swp_swap_info(swp_entry_t entry) { return NULL; } #define swap_address_space(entry) (NULL) #define get_nr_swap_pages() 0L #define total_swap_pages 0L #define total_swapcache_pages() 0UL #define vm_swap_full() 0 #define si_swapinfo(val) \ do { (val)->freeswap = (val)->totalswap = 0; } while (0) /* only sparc can not include linux/pagemap.h in this file * so leave put_page and release_pages undeclared... */ #define free_page_and_swap_cache(page) \ put_page(page) #define free_pages_and_swap_cache(pages, nr) \ release_pages((pages), (nr)); static inline void show_swap_cache_info(void) { } #define free_swap_and_cache(e) ({(is_migration_entry(e) || is_device_private_entry(e));}) #define swapcache_prepare(e) ({(is_migration_entry(e) || is_device_private_entry(e));}) static inline int add_swap_count_continuation(swp_entry_t swp, gfp_t gfp_mask) { return 0; } static inline void swap_shmem_alloc(swp_entry_t swp) { } static inline int swap_duplicate(swp_entry_t swp) { return 0; } static inline void swap_free(swp_entry_t swp) { } static inline void put_swap_page(struct page *page, swp_entry_t swp) { } static inline struct page *swap_cluster_readahead(swp_entry_t entry, gfp_t gfp_mask, struct vm_fault *vmf) { return NULL; } static inline struct page *swapin_readahead(swp_entry_t swp, gfp_t gfp_mask, struct vm_fault *vmf) { return NULL; } static inline int swap_writepage(struct page *p, struct writeback_control *wbc) { return 0; } static inline struct page *lookup_swap_cache(swp_entry_t swp, struct vm_area_struct *vma, unsigned long addr) { return NULL; } static inline struct page *find_get_incore_page(struct address_space *mapping, pgoff_t index) { return find_get_page(mapping, index); } static inline int add_to_swap(struct page *page) { return 0; } static inline void *get_shadow_from_swap_cache(swp_entry_t entry) { return NULL; } static inline int add_to_swap_cache(struct page *page, swp_entry_t entry, gfp_t gfp_mask, void **shadowp) { return -1; } static inline void __delete_from_swap_cache(struct page *page, swp_entry_t entry, void *shadow) { } static inline void delete_from_swap_cache(struct page *page) { } static inline void clear_shadow_from_swap_cache(int type, unsigned long begin, unsigned long end) { } static inline int page_swapcount(struct page *page) { return 0; } static inline int __swap_count(swp_entry_t entry) { return 0; } static inline int __swp_swapcount(swp_entry_t entry) { return 0; } static inline int swp_swapcount(swp_entry_t entry) { return 0; } #define reuse_swap_page(page, total_map_swapcount) \ (page_trans_huge_mapcount(page, total_map_swapcount) == 1) static inline int try_to_free_swap(struct page *page) { return 0; } static inline swp_entry_t get_swap_page(struct page *page) { swp_entry_t entry; entry.val = 0; return entry; } #endif /* CONFIG_SWAP */ #ifdef CONFIG_THP_SWAP extern int split_swap_cluster(swp_entry_t entry); #else static inline int split_swap_cluster(swp_entry_t entry) { return 0; } #endif #ifdef CONFIG_MEMCG static inline int mem_cgroup_swappiness(struct mem_cgroup *memcg) { /* Cgroup2 doesn't have per-cgroup swappiness */ if (cgroup_subsys_on_dfl(memory_cgrp_subsys)) return vm_swappiness; /* root ? */ if (mem_cgroup_disabled() || mem_cgroup_is_root(memcg)) return vm_swappiness; return memcg->swappiness; } #else static inline int mem_cgroup_swappiness(struct mem_cgroup *mem) { return vm_swappiness; } #endif #if defined(CONFIG_SWAP) && defined(CONFIG_MEMCG) && defined(CONFIG_BLK_CGROUP) extern void cgroup_throttle_swaprate(struct page *page, gfp_t gfp_mask); #else static inline void cgroup_throttle_swaprate(struct page *page, gfp_t gfp_mask) { } #endif #ifdef CONFIG_MEMCG_SWAP extern void mem_cgroup_swapout(struct page *page, swp_entry_t entry); extern int mem_cgroup_try_charge_swap(struct page *page, swp_entry_t entry); extern void mem_cgroup_uncharge_swap(swp_entry_t entry, unsigned int nr_pages); extern long mem_cgroup_get_nr_swap_pages(struct mem_cgroup *memcg); extern bool mem_cgroup_swap_full(struct page *page); #else static inline void mem_cgroup_swapout(struct page *page, swp_entry_t entry) { } static inline int mem_cgroup_try_charge_swap(struct page *page, swp_entry_t entry) { return 0; } static inline void mem_cgroup_uncharge_swap(swp_entry_t entry, unsigned int nr_pages) { } static inline long mem_cgroup_get_nr_swap_pages(struct mem_cgroup *memcg) { return get_nr_swap_pages(); } static inline bool mem_cgroup_swap_full(struct page *page) { return vm_swap_full(); } #endif #endif /* __KERNEL__*/ #endif /* _LINUX_SWAP_H */
GuillaumeSeren/linux
include/linux/swap.h
C
gpl-2.0
22,389
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | \\ / A nd | Copyright (C) 2013 OpenFOAM Foundation \\/ M anipulation | ------------------------------------------------------------------------------- License This file is part of OpenFOAM. OpenFOAM 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. OpenFOAM 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 OpenFOAM. If not, see <http://www.gnu.org/licenses/>. \*---------------------------------------------------------------------------*/ #include "AveragingMethod.H" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // template<class ParcelType> template<class CloudType> inline Foam::MPPICParcel<ParcelType>::TrackingData<CloudType>::TrackingData ( CloudType& cloud, trackPart part ) : ParcelType::template TrackingData<CloudType>(cloud), volumeAverage_ ( AveragingMethod<scalar>::New ( IOobject ( cloud.name() + ":volumeAverage", cloud.db().time().timeName(), cloud.mesh() ), cloud.solution().dict(), cloud.mesh() ) ), radiusAverage_ ( AveragingMethod<scalar>::New ( IOobject ( cloud.name() + ":radiusAverage", cloud.db().time().timeName(), cloud.mesh() ), cloud.solution().dict(), cloud.mesh() ) ), rhoAverage_ ( AveragingMethod<scalar>::New ( IOobject ( cloud.name() + ":rhoAverage", cloud.db().time().timeName(), cloud.mesh() ), cloud.solution().dict(), cloud.mesh() ) ), uAverage_ ( AveragingMethod<vector>::New ( IOobject ( cloud.name() + ":uAverage", cloud.db().time().timeName(), cloud.mesh() ), cloud.solution().dict(), cloud.mesh() ) ), uSqrAverage_ ( AveragingMethod<scalar>::New ( IOobject ( cloud.name() + ":uSqrAverage", cloud.db().time().timeName(), cloud.mesh() ), cloud.solution().dict(), cloud.mesh() ) ), frequencyAverage_ ( AveragingMethod<scalar>::New ( IOobject ( cloud.name() + ":frequencyAverage", cloud.db().time().timeName(), cloud.mesh() ), cloud.solution().dict(), cloud.mesh() ) ), massAverage_ ( AveragingMethod<scalar>::New ( IOobject ( cloud.name() + ":massAverage", cloud.db().time().timeName(), cloud.mesh() ), cloud.solution().dict(), cloud.mesh() ) ), part_(part) {} template<class ParcelType> template<class CloudType> inline void Foam::MPPICParcel<ParcelType>::TrackingData<CloudType>::updateAverages ( CloudType& cloud ) { // zero the sums volumeAverage_() = 0; radiusAverage_() = 0; rhoAverage_() = 0; uAverage_() = vector::zero; uSqrAverage_() = 0; frequencyAverage_() = 0; massAverage_() = 0; // temporary weights autoPtr<AveragingMethod<scalar> > weightAveragePtr ( AveragingMethod<scalar>::New ( IOobject ( cloud.name() + ":weightAverage", cloud.db().time().timeName(), cloud.mesh() ), cloud.solution().dict(), cloud.mesh() ) ); AveragingMethod<scalar>& weightAverage = weightAveragePtr(); // averaging sums forAllConstIter(typename CloudType, cloud, iter) { const typename CloudType::parcelType& p = iter(); const tetIndices tetIs(p.cell(), p.tetFace(), p.tetPt(), cloud.mesh()); const scalar m = p.nParticle()*p.mass(); volumeAverage_->add(p.position(), tetIs, p.nParticle()*p.volume()); rhoAverage_->add(p.position(), tetIs, m*p.rho()); uAverage_->add(p.position(), tetIs, m*p.U()); massAverage_->add(p.position(), tetIs, m); } volumeAverage_->average(); massAverage_->average(); rhoAverage_->average(massAverage_); uAverage_->average(massAverage_); // squared velocity deviation forAllConstIter(typename CloudType, cloud, iter) { const typename CloudType::parcelType& p = iter(); const tetIndices tetIs(p.cell(), p.tetFace(), p.tetPt(), cloud.mesh()); const vector u = uAverage_->interpolate(p.position(), tetIs); uSqrAverage_->add ( p.position(), tetIs, p.nParticle()*p.mass()*magSqr(p.U() - u) ); } uSqrAverage_->average(massAverage_); // sauter mean radius radiusAverage_() = volumeAverage_(); weightAverage = 0; forAllConstIter(typename CloudType, cloud, iter) { const typename CloudType::parcelType& p = iter(); const tetIndices tetIs(p.cell(), p.tetFace(), p.tetPt(), cloud.mesh()); weightAverage.add ( p.position(), tetIs, p.nParticle()*pow(p.volume(), 2.0/3.0) ); } weightAverage.average(); radiusAverage_->average(weightAverage); // collision frequency weightAverage = 0; forAllConstIter(typename CloudType, cloud, iter) { const typename CloudType::parcelType& p = iter(); tetIndices tetIs(p.cell(), p.tetFace(), p.tetPt(), cloud.mesh()); const scalar a = volumeAverage_->interpolate(p.position(), tetIs); const scalar r = radiusAverage_->interpolate(p.position(), tetIs); const vector u = uAverage_->interpolate(p.position(), tetIs); const scalar f = 0.75*a/pow3(r)*sqr(0.5*p.d() + r)*mag(p.U() - u); frequencyAverage_->add(p.position(), tetIs, p.nParticle()*f*f); weightAverage.add(p.position(), tetIs, p.nParticle()*f); } frequencyAverage_->average(weightAverage); } template<class ParcelType> template<class CloudType> inline typename Foam::MPPICParcel<ParcelType>::template TrackingData<CloudType>::trackPart Foam::MPPICParcel<ParcelType>::TrackingData<CloudType>::part() const { return part_; } template<class ParcelType> template<class CloudType> inline typename Foam::MPPICParcel<ParcelType>::template TrackingData<CloudType>::trackPart& Foam::MPPICParcel<ParcelType>::TrackingData<CloudType>::part() { return part_; } // ************************************************************************* //
OpenFOAM/OpenFOAM-2.3.x
src/lagrangian/intermediate/parcels/Templates/MPPICParcel/MPPICParcelTrackingDataI.H
C++
gpl-3.0
7,540
/***************************************************************************** * * PROJECT: Multi Theft Auto v1.0 * LICENSE: See LICENSE in the top level directory * FILE: sdk/game/CRenderWare.h * PURPOSE: RenderWare engine interface * * Multi Theft Auto is available from http://www.multitheftauto.com/ * *****************************************************************************/ #ifndef __CRENDERWARE #define __CRENDERWARE #include "RenderWare.h" #include <list> class CD3DDUMMY; class CClientEntityBase; class CShaderItem; typedef CShaderItem CSHADERDUMMY; // A list of custom textures to add to a model's txd struct SReplacementTextures { struct SPerTxd { std::vector < RwTexture* > usingTextures; ushort usTxdId; bool bTexturesAreCopies; }; std::vector < RwTexture* > textures; // List of textures we want to inject into TXD's std::vector < SPerTxd > perTxdList; // TXD's which have been modified std::vector < ushort > usedInTxdIds; std::vector < ushort > usedInModelIds; }; // Shader layers to render struct SShaderItemLayers { SShaderItemLayers ( void ) : pBase ( NULL ), bUsesVertexShader ( false ) {} CShaderItem* pBase; std::vector < CShaderItem* > layerList; bool bUsesVertexShader; }; enum EEntityTypeMask { TYPE_MASK_NONE = 0, TYPE_MASK_WORLD = 1, TYPE_MASK_PED = 2, TYPE_MASK_VEHICLE = 4, TYPE_MASK_OBJECT = 8, TYPE_MASK_OTHER = 16, TYPE_MASK_ALL = 127, }; typedef void (*PFN_WATCH_CALLBACK) ( CSHADERDUMMY* pContext, CD3DDUMMY* pD3DDataNew, CD3DDUMMY* pD3DDataOld ); #define MAX_ATOMICS_PER_CLUMP 128 class CRenderWare { public: virtual bool ModelInfoTXDLoadTextures ( SReplacementTextures* pReplacementTextures, const CBuffer& fileData, bool bFilteringEnabled ) = 0; virtual bool ModelInfoTXDAddTextures ( SReplacementTextures* pReplacementTextures, ushort usModelId ) = 0; virtual void ModelInfoTXDRemoveTextures ( SReplacementTextures* pReplacementTextures ) = 0; virtual void ClothesAddReplacementTxd ( char* pFileData, ushort usFileId ) = 0; virtual void ClothesRemoveReplacementTxd ( char* pFileData ) = 0; virtual bool HasClothesReplacementChanged( void ) = 0; virtual RwTexDictionary * ReadTXD ( const CBuffer& fileData ) = 0; virtual RpClump * ReadDFF ( const CBuffer& fileData, unsigned short usModelID, bool bLoadEmbeddedCollisions ) = 0; virtual CColModel * ReadCOL ( const CBuffer& fileData ) = 0; virtual void DestroyDFF ( RpClump * pClump ) = 0; virtual void DestroyTXD ( RwTexDictionary * pTXD ) = 0; virtual void DestroyTexture ( RwTexture * pTex ) = 0; virtual void ReplaceCollisions ( CColModel * pColModel, unsigned short usModelID ) = 0; virtual unsigned int LoadAtomics ( RpClump * pClump, RpAtomicContainer * pAtomics ) = 0; virtual void ReplaceAllAtomicsInModel ( RpClump * pSrc, unsigned short usModelID ) = 0; virtual void ReplaceAllAtomicsInClump ( RpClump * pDst, RpAtomicContainer * pAtomics, unsigned int uiAtomics ) = 0; virtual void ReplaceWheels ( RpClump * pClump, RpAtomicContainer * pAtomics, unsigned int uiAtomics, const char * szWheel ) = 0; virtual void RepositionAtomic ( RpClump * pDst, RpClump * pSrc, const char * szName ) = 0; virtual void AddAllAtomics ( RpClump * pDst, RpClump * pSrc ) = 0; virtual void ReplaceVehicleModel ( RpClump * pNew, unsigned short usModelID ) = 0; virtual void ReplaceWeaponModel ( RpClump * pNew, unsigned short usModelID ) = 0; virtual void ReplacePedModel ( RpClump * pNew, unsigned short usModelID ) = 0; virtual bool ReplacePartModels ( RpClump * pClump, RpAtomicContainer * pAtomics, unsigned int uiAtomics, const char * szName ) = 0; virtual void PulseWorldTextureWatch ( void ) = 0; virtual void GetModelTextureNames ( std::vector < SString >& outNameList, ushort usModelID ) = 0; virtual const char* GetTextureName ( CD3DDUMMY* pD3DData ) = 0; virtual void SetRenderingClientEntity ( CClientEntityBase* pClientEntity, ushort usModelId, int iTypeMask ) = 0; virtual SShaderItemLayers* GetAppliedShaderForD3DData ( CD3DDUMMY* pD3DData ) = 0; virtual void AppendAdditiveMatch ( CSHADERDUMMY* pShaderData, CClientEntityBase* pClientEntity, const char* strTextureNameMatch, float fShaderPriority, bool bShaderLayered, int iTypeMask, uint uiShaderCreateTime, bool bShaderUsesVertexShader, bool bAppendLayers ) = 0; virtual void AppendSubtractiveMatch ( CSHADERDUMMY* pShaderData, CClientEntityBase* pClientEntity, const char* strTextureNameMatch ) = 0; virtual void RemoveClientEntityRefs ( CClientEntityBase* pClientEntity ) = 0; virtual void RemoveShaderRefs ( CSHADERDUMMY* pShaderItem ) = 0; virtual RwFrame * GetFrameFromName ( RpClump * pRoot, SString strName ) = 0; }; #endif
BozhkoAlexander/mtasa-blue
MTA10/sdk/game/CRenderWare.h
C
gpl-3.0
5,828
//@tag dom,core //@define Ext.DomHelper //@define Ext.core.DomHelper //@require Ext.dom.AbstractElement-traversal /** * @class Ext.DomHelper * @extends Ext.dom.Helper * @alternateClassName Ext.core.DomHelper * @singleton * * The DomHelper class provides a layer of abstraction from DOM and transparently supports creating elements via DOM or * using HTML fragments. It also has the ability to create HTML fragment templates from your DOM building code. * * # DomHelper element specification object * * A specification object is used when creating elements. Attributes of this object are assumed to be element * attributes, except for 4 special attributes: * * - **tag** - The tag name of the element. * - **children** or **cn** - An array of the same kind of element definition objects to be created and appended. * These can be nested as deep as you want. * - **cls** - The class attribute of the element. This will end up being either the "class" attribute on a HTML * fragment or className for a DOM node, depending on whether DomHelper is using fragments or DOM. * - **html** - The innerHTML for the element. * * **NOTE:** For other arbitrary attributes, the value will currently **not** be automatically HTML-escaped prior to * building the element's HTML string. This means that if your attribute value contains special characters that would * not normally be allowed in a double-quoted attribute value, you **must** manually HTML-encode it beforehand (see * {@link Ext.String#htmlEncode}) or risk malformed HTML being created. This behavior may change in a future release. * * # Insertion methods * * Commonly used insertion methods: * * - **{@link #append}** * - **{@link #insertBefore}** * - **{@link #insertAfter}** * - **{@link #overwrite}** * - **{@link #createTemplate}** * - **{@link #insertHtml}** * * # Example * * This is an example, where an unordered list with 3 children items is appended to an existing element with * id 'my-div': * * var dh = Ext.DomHelper; // create shorthand alias * // specification object * var spec = { * id: 'my-ul', * tag: 'ul', * cls: 'my-list', * // append children after creating * children: [ // may also specify 'cn' instead of 'children' * {tag: 'li', id: 'item0', html: 'List Item 0'}, * {tag: 'li', id: 'item1', html: 'List Item 1'}, * {tag: 'li', id: 'item2', html: 'List Item 2'} * ] * }; * var list = dh.append( * 'my-div', // the context element 'my-div' can either be the id or the actual node * spec // the specification object * ); * * Element creation specification parameters in this class may also be passed as an Array of specification objects. This * can be used to insert multiple sibling nodes into an existing container very efficiently. For example, to add more * list items to the example above: * * dh.append('my-ul', [ * {tag: 'li', id: 'item3', html: 'List Item 3'}, * {tag: 'li', id: 'item4', html: 'List Item 4'} * ]); * * # Templating * * The real power is in the built-in templating. Instead of creating or appending any elements, {@link #createTemplate} * returns a Template object which can be used over and over to insert new elements. Revisiting the example above, we * could utilize templating this time: * * // create the node * var list = dh.append('my-div', {tag: 'ul', cls: 'my-list'}); * // get template * var tpl = dh.createTemplate({tag: 'li', id: 'item{0}', html: 'List Item {0}'}); * * for(var i = 0; i < 5, i++){ * tpl.append(list, [i]); // use template to append to the actual node * } * * An example using a template: * * var html = '<a id="{0}" href="{1}" class="nav">{2}</a>'; * * var tpl = new Ext.DomHelper.createTemplate(html); * tpl.append('blog-roll', ['link1', 'http://www.edspencer.net/', "Ed's Site"]); * tpl.append('blog-roll', ['link2', 'http://www.dustindiaz.com/', "Dustin's Site"]); * * The same example using named parameters: * * var html = '<a id="{id}" href="{url}" class="nav">{text}</a>'; * * var tpl = new Ext.DomHelper.createTemplate(html); * tpl.append('blog-roll', { * id: 'link1', * url: 'http://www.edspencer.net/', * text: "Ed's Site" * }); * tpl.append('blog-roll', { * id: 'link2', * url: 'http://www.dustindiaz.com/', * text: "Dustin's Site" * }); * * # Compiling Templates * * Templates are applied using regular expressions. The performance is great, but if you are adding a bunch of DOM * elements using the same template, you can increase performance even further by {@link Ext.Template#compile * "compiling"} the template. The way "{@link Ext.Template#compile compile()}" works is the template is parsed and * broken up at the different variable points and a dynamic function is created and eval'ed. The generated function * performs string concatenation of these parts and the passed variables instead of using regular expressions. * * var html = '<a id="{id}" href="{url}" class="nav">{text}</a>'; * * var tpl = new Ext.DomHelper.createTemplate(html); * tpl.compile(); * * //... use template like normal * * # Performance Boost * * DomHelper will transparently create HTML fragments when it can. Using HTML fragments instead of DOM can significantly * boost performance. * * Element creation specification parameters may also be strings. If {@link #useDom} is false, then the string is used * as innerHTML. If {@link #useDom} is true, a string specification results in the creation of a text node. Usage: * * Ext.DomHelper.useDom = true; // force it to use DOM; reduces performance * */ (function() { // kill repeat to save bytes var afterbegin = 'afterbegin', afterend = 'afterend', beforebegin = 'beforebegin', beforeend = 'beforeend', ts = '<table>', te = '</table>', tbs = ts+'<tbody>', tbe = '</tbody>'+te, trs = tbs + '<tr>', tre = '</tr>'+tbe, detachedDiv = document.createElement('div'), bbValues = ['BeforeBegin', 'previousSibling'], aeValues = ['AfterEnd', 'nextSibling'], bb_ae_PositionHash = { beforebegin: bbValues, afterend: aeValues }, fullPositionHash = { beforebegin: bbValues, afterend: aeValues, afterbegin: ['AfterBegin', 'firstChild'], beforeend: ['BeforeEnd', 'lastChild'] }; /** * The actual class of which {@link Ext.DomHelper} is instance of. * * Use singleton {@link Ext.DomHelper} instead. * * @private */ Ext.define('Ext.dom.Helper', { extend: 'Ext.dom.AbstractHelper', requires:['Ext.dom.AbstractElement'], tableRe: /^table|tbody|tr|td$/i, tableElRe: /td|tr|tbody/i, /** * @property {Boolean} useDom * True to force the use of DOM instead of html fragments. */ useDom : false, /** * Creates new DOM element(s) without inserting them to the document. * @param {Object/String} o The DOM object spec (and children) or raw HTML blob * @return {HTMLElement} The new uninserted node */ createDom: function(o, parentNode){ var el, doc = document, useSet, attr, val, cn, i, l; if (Ext.isArray(o)) { // Allow Arrays of siblings to be inserted el = doc.createDocumentFragment(); // in one shot using a DocumentFragment for (i = 0, l = o.length; i < l; i++) { this.createDom(o[i], el); } } else if (typeof o == 'string') { // Allow a string as a child spec. el = doc.createTextNode(o); } else { el = doc.createElement(o.tag || 'div'); useSet = !!el.setAttribute; // In IE some elements don't have setAttribute for (attr in o) { if (!this.confRe.test(attr)) { val = o[attr]; if (attr == 'cls') { el.className = val; } else { if (useSet) { el.setAttribute(attr, val); } else { el[attr] = val; } } } } Ext.DomHelper.applyStyles(el, o.style); if ((cn = o.children || o.cn)) { this.createDom(cn, el); } else if (o.html) { el.innerHTML = o.html; } } if (parentNode) { parentNode.appendChild(el); } return el; }, ieTable: function(depth, openingTags, htmlContent, closingTags){ detachedDiv.innerHTML = [openingTags, htmlContent, closingTags].join(''); var i = -1, el = detachedDiv, ns; while (++i < depth) { el = el.firstChild; } // If the result is multiple siblings, then encapsulate them into one fragment. ns = el.nextSibling; if (ns) { el = document.createDocumentFragment(); while (ns) { el.appendChild(ns); ns = ns.nextSibling; } } return el; }, /** * @private * Nasty code for IE's broken table implementation */ insertIntoTable: function(tag, where, destinationEl, html) { var node, before, bb = where == beforebegin, ab = where == afterbegin, be = where == beforeend, ae = where == afterend; if (tag == 'td' && (ab || be) || !this.tableElRe.test(tag) && (bb || ae)) { return null; } before = bb ? destinationEl : ae ? destinationEl.nextSibling : ab ? destinationEl.firstChild : null; if (bb || ae) { destinationEl = destinationEl.parentNode; } if (tag == 'td' || (tag == 'tr' && (be || ab))) { node = this.ieTable(4, trs, html, tre); } else if ((tag == 'tbody' && (be || ab)) || (tag == 'tr' && (bb || ae))) { node = this.ieTable(3, tbs, html, tbe); } else { node = this.ieTable(2, ts, html, te); } destinationEl.insertBefore(node, before); return node; }, /** * @private * Fix for IE9 createContextualFragment missing method */ createContextualFragment: function(html) { var fragment = document.createDocumentFragment(), length, childNodes; detachedDiv.innerHTML = html; childNodes = detachedDiv.childNodes; length = childNodes.length; // Move nodes into fragment, don't clone: http://jsperf.com/create-fragment while (length--) { fragment.appendChild(childNodes[0]); } return fragment; }, applyStyles: function(el, styles) { if (styles) { el = Ext.fly(el); if (typeof styles == "function") { styles = styles.call(); } if (typeof styles == "string") { styles = Ext.dom.Element.parseStyles(styles); } if (typeof styles == "object") { el.setStyle(styles); } } }, /** * Alias for {@link #markup}. * @inheritdoc Ext.dom.AbstractHelper#markup */ createHtml: function(spec) { return this.markup(spec); }, doInsert: function(el, o, returnElement, pos, sibling, append) { el = el.dom || Ext.getDom(el); var newNode; if (this.useDom) { newNode = this.createDom(o, null); if (append) { el.appendChild(newNode); } else { (sibling == 'firstChild' ? el : el.parentNode).insertBefore(newNode, el[sibling] || el); } } else { newNode = this.insertHtml(pos, el, this.markup(o)); } return returnElement ? Ext.get(newNode, true) : newNode; }, /** * Creates new DOM element(s) and overwrites the contents of el with them. * @param {String/HTMLElement/Ext.Element} el The context element * @param {Object/String} o The DOM object spec (and children) or raw HTML blob * @param {Boolean} [returnElement] true to return an Ext.Element * @return {HTMLElement/Ext.Element} The new node */ overwrite: function(el, html, returnElement) { var newNode; el = Ext.getDom(el); html = this.markup(html); // IE Inserting HTML into a table/tbody/tr requires extra processing: http://www.ericvasilik.com/2006/07/code-karma.html if (Ext.isIE && this.tableRe.test(el.tagName)) { // Clearing table elements requires removal of all elements. while (el.firstChild) { el.removeChild(el.firstChild); } if (html) { newNode = this.insertHtml('afterbegin', el, html); return returnElement ? Ext.get(newNode) : newNode; } return null; } el.innerHTML = html; return returnElement ? Ext.get(el.firstChild) : el.firstChild; }, insertHtml: function(where, el, html) { var hashVal, range, rangeEl, setStart, frag; where = where.toLowerCase(); // Has fast HTML insertion into existing DOM: http://www.w3.org/TR/html5/apis-in-html-documents.html#insertadjacenthtml if (el.insertAdjacentHTML) { // IE's incomplete table implementation: http://www.ericvasilik.com/2006/07/code-karma.html if (Ext.isIE && this.tableRe.test(el.tagName) && (frag = this.insertIntoTable(el.tagName.toLowerCase(), where, el, html))) { return frag; } if ((hashVal = fullPositionHash[where])) { el.insertAdjacentHTML(hashVal[0], html); return el[hashVal[1]]; } // if (not IE and context element is an HTMLElement) or TextNode } else { // we cannot insert anything inside a textnode so... if (el.nodeType === 3) { where = where === 'afterbegin' ? 'beforebegin' : where; where = where === 'beforeend' ? 'afterend' : where; } range = Ext.supports.CreateContextualFragment ? el.ownerDocument.createRange() : undefined; setStart = 'setStart' + (this.endRe.test(where) ? 'After' : 'Before'); if (bb_ae_PositionHash[where]) { if (range) { range[setStart](el); frag = range.createContextualFragment(html); } else { frag = this.createContextualFragment(html); } el.parentNode.insertBefore(frag, where == beforebegin ? el : el.nextSibling); return el[(where == beforebegin ? 'previous' : 'next') + 'Sibling']; } else { rangeEl = (where == afterbegin ? 'first' : 'last') + 'Child'; if (el.firstChild) { if (range) { range[setStart](el[rangeEl]); frag = range.createContextualFragment(html); } else { frag = this.createContextualFragment(html); } if (where == afterbegin) { el.insertBefore(frag, el.firstChild); } else { el.appendChild(frag); } } else { el.innerHTML = html; } return el[rangeEl]; } } //<debug> Ext.Error.raise({ sourceClass: 'Ext.DomHelper', sourceMethod: 'insertHtml', htmlToInsert: html, targetElement: el, msg: 'Illegal insertion point reached: "' + where + '"' }); //</debug> }, /** * Creates a new Ext.Template from the DOM object spec. * @param {Object} o The DOM object spec (and children) * @return {Ext.Template} The new template */ createTemplate: function(o) { var html = this.markup(o); return new Ext.Template(html); } }, function() { Ext.ns('Ext.core'); Ext.DomHelper = Ext.core.DomHelper = new this; }); }());
Webcampak/v2.0
src/www/interface/extjs/src/dom/Helper.js
JavaScript
gpl-3.0
16,761
describe("", function() { var rootEl; beforeEach(function() { rootEl = browser.rootEl; browser.get("build/docs/examples/example-select-unknown-value-required/index.html"); }); it('should show the error message when the unknown option is selected', function() { var error = element(by.className('error')); expect(error.getText()).toBe('Error: Please select a value'); element(by.cssContainingText('option', 'Option 1')).click(); expect(error.isPresent()).toBe(false); element(by.tagName('button')).click(); expect(error.getText()).toBe('Error: Please select a value'); }); });
gplv2/grbtool
public/js/angular-1.7.8/docs/ptore2e/example-select-unknown-value-required/default_test.js
JavaScript
gpl-3.0
631
<?php /* Copyright (C) 2009 Laurent Destailleur <eldy@users.sourceforge.net> * * 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/>. */ /** * \defgroup webservices Module webservices * \brief Module to enable the Dolibarr server of web services * \file htdocs/core/modules/modWebServices.class.php * \ingroup webservices * \brief File to describe webservices module */ include_once DOL_DOCUMENT_ROOT .'/core/modules/DolibarrModules.class.php'; /** * Class to describe a WebServices module */ class modWebServices extends DolibarrModules { /** * Constructor. Define names, constants, directories, boxes, permissions * * @param DoliDB $db Database handler */ function __construct($db) { $this->db = $db; $this->numero = 2600; $this->family = "technic"; // Module label (no space allowed), used if translation string 'ModuleXXXName' not found (where XXX is value of numeric property 'numero' of module) $this->name = preg_replace('/^mod/i','',get_class($this)); $this->description = "Enable the Dolibarr web services server"; $this->version = 'dolibarr'; // 'experimental' or 'dolibarr' or version // Key used in llx_const table to save module status enabled/disabled (where MYMODULE is value of property name of module in uppercase) $this->const_name = 'MAIN_MODULE_'.strtoupper($this->name); // Where to store the module in setup page (0=common,1=interface,2=others,3=very specific) $this->special = 1; // Name of image file used for this module. $this->picto='technic'; // Data directories to create when module is enabled $this->dirs = array(); // Config pages //------------- $this->config_page_url = array("index.php@webservices"); // Dependancies //------------- $this->depends = array(); $this->requiredby = array(); $this->langfiles = array("other"); // Constants //----------- $this->const = array(); // New pages on tabs // ----------------- $this->tabs = array(); // Boxes //------ $this->boxes = array(); // Permissions //------------ $this->rights = array(); $this->rights_class = 'webservices'; $r=0; } }
atm-robin/dolibarr
htdocs/core/modules/modWebServices.class.php
PHP
gpl-3.0
3,044
// META: script=websocket.sub.js var testOpen = async_test("Send binary data on a WebSocket - Blob - Connection should be opened"); var testMessage = async_test("Send binary data on a WebSocket - Blob - Message should be received"); var testClose = async_test("Send binary data on a WebSocket - Blob - Connection should be closed"); var data = ""; var datasize = 65000; var isOpenCalled = false; var wsocket = CreateWebSocket(false, false, false); wsocket.addEventListener('open', testOpen.step_func(function(evt) { wsocket.binaryType = "blob"; for (var i = 0; i < datasize; i++) data += String.fromCharCode(0); data = new Blob([data]); isOpenCalled = true; wsocket.send(data); testOpen.done(); }), true); wsocket.addEventListener('message', testMessage.step_func(function(evt) { assert_true(evt.data instanceof Blob); assert_equals(evt.data.size, datasize); wsocket.close(); testMessage.done(); }), true); wsocket.addEventListener('close', testClose.step_func(function(evt) { assert_true(isOpenCalled, "WebSocket connection should be open"); assert_true(evt.wasClean, "wasClean should be true"); testClose.done(); }), true);
pyfisch/servo
tests/wpt/web-platform-tests/websockets/Send-binary-blob.any.js
JavaScript
mpl-2.0
1,162
import unittest class StringProcessingTestBase(unittest.TestCase): # The backslash character. Needed since there are limitations when # using backslashes at the end of raw-strings in front of the # terminating " or '. bs = "\\" # Basic test strings all StringProcessing functions should test. test_strings = [ r"out1 'escaped-escape: \\ ' out2", r"out1 'escaped-quote: \' ' out2", r"out1 'escaped-anything: \X ' out2", r"out1 'two escaped escapes: \\\\ ' out2", r"out1 'escaped-quote at end: \'' out2", r"out1 'escaped-escape at end: \\' out2", r"out1 'str1' out2 'str2' out2", r"out1 \' 'str1' out2 'str2' out2", r"out1 \\\' 'str1' out2 'str2' out2", r"out1 \\ 'str1' out2 'str2' out2", r"out1 \\\\ 'str1' out2 'str2' out2", r"out1 \\'str1' out2 'str2' out2", r"out1 \\\\'str1' out2 'str2' out2", r"out1 'str1''str2''str3' out2", r"", r"out1 out2 out3", bs, 2 * bs] # Test string for multi-pattern tests (since we want to variate the # pattern, not the test string). multi_pattern_test_string = (r"abcabccba###\\13q4ujsabbc\+'**'ac" r"###.#.####-ba") # Multiple patterns for the multi-pattern tests. multi_patterns = [r"abc", r"ab", r"ab|ac", 2 * bs, r"#+", r"(a)|(b)|(#.)", r"(?:a(b)*c)+", r"1|\+"] # Test strings for the remove_empty_matches feature (alias auto-trim). auto_trim_test_pattern = r";" auto_trim_test_strings = [r";;;;;;;;;;;;;;;;", r"\\;\\\\\;\\#;\\\';;\;\\\\;+ios;;", r"1;2;3;4;5;6;", r"1;2;3;4;5;6;7", r"", r"Hello world", r"\;", r"\\;", r"abc;a;;;;;asc"] # Test strings for search-in-between functions. search_in_between_begin_pattern = r"(" search_in_between_end_pattern = r")" search_in_between_test_strings = [ r"()assk(This is a word)and((in a word) another ) one anyway.", r"bcc5(((((((((((((((((((1)2)3)))))))))))))))))", r"Let's (do (it ) more ) complicated ) ) ) () (hello.)", r"()assk\\(This\ is a word\)and((in a\\\ word\\\\\) another \)) " r"one anyway.", r"bcc5\(\(\((((((\\\(((((((((((1)2)3))\\\\\)))))))))))))\)\)", r"Let's \(do (it ) more ) \\ complicated ) ) ) () (hello.)\\z"] @staticmethod def _construct_message(func, args, kwargs): """ Constructs the error message for the call result assertions. :param func: The function that was called. :param args: The argument tuple the function was invoked with. :param kwargs: The named arguments dict the function was invoked with. :param return: The error message. """ args = [repr(x) for x in args] kwargs = [str(key) + '=' + repr(value) for key, value in kwargs.items()] return "Called {}({}).".format(func.__name__, ", ".join(args + kwargs)) def assertResultsEqual(self, func, invocation_and_results, postprocess=lambda result: result): """ Tests each given invocation against the given results with the specified function. :param func: The function to test. :param invocation_and_results: A dict containing the invocation tuple as key and the result as value. :param postprocess: A function that shall process the returned result from the tested function. The function must accept only one parameter as postprocessing input. Performs no postprocessing by default. """ for args, result in invocation_and_results.items(): self.assertEqual( postprocess(func(*args)), result, self._construct_message(func, args, {})) def assertResultsEqualEx(self, func, invocation_and_results, postprocess=lambda result: result): """ Tests each given invocation against the given results with the specified function. This is an extended version of ``assertResultsEqual()`` that supports also ``**kwargs``. :param func: The function to test. :param invocation_and_results: A dict containing the invocation tuple as key and the result as value. The tuple contains (args, kwargs). :param postprocess: A function that shall process the returned result from the tested function. The function must accept only one parameter as postprocessing input. Performs no postprocessing by default. """ for (args, kwargs), result in invocation_and_results.items(): self.assertEqual( postprocess(func(*args, **kwargs)), result, self._construct_message(func, args, kwargs))
yland/coala
tests/parsing/StringProcessing/StringProcessingTestBase.py
Python
agpl-3.0
5,848
// Copyright 2012, 2013 Canonical Ltd. // Licensed under the AGPLv3, see LICENCE file for details. // hook provides types that define the hooks known to the Uniter package hook import ( "fmt" "gopkg.in/juju/charm.v6-unstable/hooks" "gopkg.in/juju/names.v2" ) // TODO(fwereade): move these definitions to juju/charm/hooks. const ( LeaderElected hooks.Kind = "leader-elected" LeaderDeposed hooks.Kind = "leader-deposed" LeaderSettingsChanged hooks.Kind = "leader-settings-changed" ) // Info holds details required to execute a hook. Not all fields are // relevant to all Kind values. type Info struct { Kind hooks.Kind `yaml:"kind"` // RelationId identifies the relation associated with the hook. It is // only set when Kind indicates a relation hook. RelationId int `yaml:"relation-id,omitempty"` // RemoteUnit is the name of the unit that triggered the hook. It is only // set when Kind indicates a relation hook other than relation-broken. RemoteUnit string `yaml:"remote-unit,omitempty"` // ChangeVersion identifies the most recent unit settings change // associated with RemoteUnit. It is only set when RemoteUnit is set. ChangeVersion int64 `yaml:"change-version,omitempty"` // StorageId is the ID of the storage instance relevant to the hook. StorageId string `yaml:"storage-id,omitempty"` } // Validate returns an error if the info is not valid. func (hi Info) Validate() error { switch hi.Kind { case hooks.RelationJoined, hooks.RelationChanged, hooks.RelationDeparted: if hi.RemoteUnit == "" { return fmt.Errorf("%q hook requires a remote unit", hi.Kind) } fallthrough case hooks.Install, hooks.Start, hooks.ConfigChanged, hooks.UpgradeCharm, hooks.Stop, hooks.RelationBroken, hooks.CollectMetrics, hooks.MeterStatusChanged, hooks.UpdateStatus: return nil case hooks.Action: return fmt.Errorf("hooks.Kind Action is deprecated") case hooks.StorageAttached, hooks.StorageDetaching: if !names.IsValidStorage(hi.StorageId) { return fmt.Errorf("invalid storage ID %q", hi.StorageId) } return nil // TODO(fwereade): define these in charm/hooks... case LeaderElected, LeaderDeposed, LeaderSettingsChanged: return nil } return fmt.Errorf("unknown hook kind %q", hi.Kind) } // Committer is an interface that may be used to convey the fact that the // specified hook has been successfully executed, and committed. type Committer interface { CommitHook(Info) error } // Validator is an interface that may be used to validate a hook execution // request prior to executing it. type Validator interface { ValidateHook(Info) error }
marcmolla/juju
worker/uniter/hook/hook.go
GO
agpl-3.0
2,610
/* * libwebsockets - small server side websockets and web server implementation * * Copyright (C) 2010-2013 Andy Green <andy@warmcat.com> * * 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: * version 2.1 of the License. * * 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., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include "private-libwebsockets.h" /* * -04 of the protocol (actually the 80th version) has a radically different * handshake. The 04 spec gives the following idea * * The handshake from the client looks as follows: * * GET /chat HTTP/1.1 * Host: server.example.com * Upgrade: websocket * Connection: Upgrade * Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== * Sec-WebSocket-Origin: http://example.com * Sec-WebSocket-Protocol: chat, superchat * Sec-WebSocket-Version: 4 * * The handshake from the server looks as follows: * * HTTP/1.1 101 Switching Protocols * Upgrade: websocket * Connection: Upgrade * Sec-WebSocket-Accept: me89jWimTRKTWwrS3aRrL53YZSo= * Sec-WebSocket-Nonce: AQIDBAUGBwgJCgsMDQ4PEC== * Sec-WebSocket-Protocol: chat */ #ifndef min #define min(a, b) ((a) < (b) ? (a) : (b)) #endif /* * We have to take care about parsing because the headers may be split * into multiple fragments. They may contain unknown headers with arbitrary * argument lengths. So, we parse using a single-character at a time state * machine that is completely independent of packet size. */ LWS_VISIBLE int libwebsocket_read(struct libwebsocket_context *context, struct libwebsocket *wsi, unsigned char *buf, size_t len) { size_t n; int body_chunk_len; unsigned char *last_char; switch (wsi->state) { #ifdef LWS_USE_HTTP2 case WSI_STATE_HTTP2_AWAIT_CLIENT_PREFACE: case WSI_STATE_HTTP2_ESTABLISHED_PRE_SETTINGS: case WSI_STATE_HTTP2_ESTABLISHED: n = 0; while (n < len) { /* * we were accepting input but now we stopped doing so */ if (!(wsi->rxflow_change_to & LWS_RXFLOW_ALLOW)) { lws_rxflow_cache(wsi, buf, n, len); return 1; } /* account for what we're using in rxflow buffer */ if (wsi->rxflow_buffer) wsi->rxflow_pos++; if (lws_http2_parser(context, wsi, buf[n++])) goto bail; } break; #endif http_new: case WSI_STATE_HTTP: wsi->hdr_parsing_completed = 0; /* fallthru */ case WSI_STATE_HTTP_ISSUING_FILE: wsi->state = WSI_STATE_HTTP_HEADERS; wsi->u.hdr.parser_state = WSI_TOKEN_NAME_PART; wsi->u.hdr.lextable_pos = 0; /* fallthru */ case WSI_STATE_HTTP_HEADERS: lwsl_parser("issuing %d bytes to parser\n", (int)len); if (lws_handshake_client(wsi, &buf, len)) goto bail; last_char = buf; if (lws_handshake_server(context, wsi, &buf, len)) /* Handshake indicates this session is done. */ goto bail; /* It's possible that we've exhausted our data already, but * lws_handshake_server doesn't update len for us. Figure out how * much was read, so that we can proceed appropriately: */ len -= (buf - last_char); if (!wsi->hdr_parsing_completed) /* More header content on the way */ goto read_ok; switch (wsi->state) { case WSI_STATE_HTTP: case WSI_STATE_HTTP_HEADERS: goto http_complete; case WSI_STATE_HTTP_ISSUING_FILE: goto read_ok; case WSI_STATE_HTTP_BODY: wsi->u.http.content_remain = wsi->u.http.content_length; goto http_postbody; default: break; } break; case WSI_STATE_HTTP_BODY: http_postbody: while (len && wsi->u.http.content_remain) { /* Copy as much as possible, up to the limit of: * what we have in the read buffer (len) * remaining portion of the POST body (content_remain) */ body_chunk_len = min(wsi->u.http.content_remain,len); wsi->u.http.content_remain -= body_chunk_len; len -= body_chunk_len; if (wsi->protocol->callback) { n = wsi->protocol->callback( wsi->protocol->owning_server, wsi, LWS_CALLBACK_HTTP_BODY, wsi->user_space, buf, body_chunk_len); if (n) goto bail; } buf += body_chunk_len; if (!wsi->u.http.content_remain) { /* he sent the content in time */ libwebsocket_set_timeout(wsi, NO_PENDING_TIMEOUT, 0); if (wsi->protocol->callback) { n = wsi->protocol->callback( wsi->protocol->owning_server, wsi, LWS_CALLBACK_HTTP_BODY_COMPLETION, wsi->user_space, NULL, 0); if (n) goto bail; } goto http_complete; } else libwebsocket_set_timeout(wsi, PENDING_TIMEOUT_HTTP_CONTENT, AWAITING_TIMEOUT); } break; case WSI_STATE_ESTABLISHED: case WSI_STATE_AWAITING_CLOSE_ACK: if (lws_handshake_client(wsi, &buf, len)) goto bail; switch (wsi->mode) { case LWS_CONNMODE_WS_SERVING: if (libwebsocket_interpret_incoming_packet(wsi, buf, len) < 0) { lwsl_info("interpret_incoming_packet has bailed\n"); goto bail; } break; } break; default: lwsl_err("libwebsocket_read: Unhandled state\n"); break; } read_ok: /* Nothing more to do for now. */ lwsl_debug("libwebsocket_read: read_ok\n"); return 0; http_complete: lwsl_debug("libwebsocket_read: http_complete\n"); /* Did the client want to keep the HTTP connection going? */ if (wsi->u.http.connection_type == HTTP_CONNECTION_KEEP_ALIVE) { lwsl_debug("libwebsocket_read: keep-alive\n"); wsi->state = WSI_STATE_HTTP; wsi->mode = LWS_CONNMODE_HTTP_SERVING; /* He asked for it to stay alive indefinitely */ libwebsocket_set_timeout(wsi, NO_PENDING_TIMEOUT, 0); if (lws_allocate_header_table(wsi)) goto bail; /* If we're (re)starting on headers, need other implied init */ wsi->u.hdr.ues = URIES_IDLE; /* If we have more data, loop back around: */ if (len) goto http_new; return 0; } bail: lwsl_debug("closing connection at libwebsocket_read bail:\n"); libwebsocket_close_and_free_session(context, wsi, LWS_CLOSE_STATUS_NOSTATUS); return -1; }
maws/libwebsockets
lib/handshake.c
C
lgpl-2.1
6,468
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // 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. // ---------------------------------------------------------------------------------- namespace Microsoft.Azure.Commands.Compute { /// <summary> /// SQL Server extension's private settings /// </summary> public class SqlServerPrivateSettings { /// <summary> /// Azure blob store URL /// </summary> public string StorageUrl; /// <summary> /// Storage account access key /// </summary> public string StorageAccessKey; /// <summary> /// Password required for certification when encryption is enabled /// </summary> public string Password; } }
devigned/azure-powershell
src/ResourceManager/Compute/Stack/Commands.Compute/Extension/SqlServer/AzureVMSqlServerPrivateSettings.cs
C#
apache-2.0
1,337
package water.util; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; /** * Simple Timer class. **/ public class Timer { private static final DateTimeFormatter longFormat = DateTimeFormat.forPattern("dd-MMM HH:mm:ss.SSS"); private static final DateTimeFormatter shortFormat= DateTimeFormat.forPattern( "HH:mm:ss.SSS"); private static final DateTimeFormatter logFormat = DateTimeFormat.forPattern( "MM-dd HH:mm:ss.SSS"); final long _start = System.currentTimeMillis(); final long _nanos = System.nanoTime(); /**Return the difference between when the timer was created and the current time. */ public long time() { return System.currentTimeMillis() - _start; } public long nanos(){ return System.nanoTime() - _nanos; } /** Return the difference between when the timer was created and the current * time as a string along with the time of creation in date format. */ @Override public String toString() { final long now = System.currentTimeMillis(); return PrettyPrint.msecs(now - _start, false) + " (Wall: " + longFormat.print(now) + ") "; } /** return the start time of this timer.**/ String startAsString() { return longFormat.print(_start); } /** return the start time of this timer.**/ String startAsShortString() { return shortFormat.print(_start); } /** * Used by Logging (Log.java) for creating a timestamp in front of each output line. */ static String nowAsLogString() { return logFormat.print(DateTime.now()); } }
PawarPawan/h2o-v3
h2o-core/src/main/java/water/util/Timer.java
Java
apache-2.0
1,562
/* * 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. */ /*! * \file broadcast_reduce_op.cc * \brief CPU Implementation of broadcast and reduce functions. */ #include "./broadcast_reduce_op.h" namespace mxnet { namespace op { DMLC_REGISTER_PARAMETER(PickParam); MXNET_OPERATOR_REGISTER_REDUCE_AXIS(argmax) .describe(R"code(Returns indices of the maximum values along an axis. In the case of multiple occurrences of maximum values, the indices corresponding to the first occurrence are returned. Examples:: x = [[ 0., 1., 2.], [ 3., 4., 5.]] // argmax along axis 0 argmax(x, axis=0) = [ 1., 1., 1.] // argmax along axis 1 argmax(x, axis=1) = [ 2., 2.] // argmax along axis 1 keeping same dims as an input array argmax(x, axis=1, keepdims=True) = [[ 2.], [ 2.]] )code" ADD_FILELINE) .set_attr<FCompute>("FCompute<cpu>", SearchAxisCompute<cpu, mshadow::red::maximum>) .set_attr<nnvm::FGradient>("FGradient", MakeZeroGradNodes); MXNET_OPERATOR_REGISTER_REDUCE_AXIS(argmin) .describe(R"code(Returns indices of the minimum values along an axis. In the case of multiple occurrences of minimum values, the indices corresponding to the first occurrence are returned. Examples:: x = [[ 0., 1., 2.], [ 3., 4., 5.]] // argmin along axis 0 argmin(x, axis=0) = [ 0., 0., 0.] // argmin along axis 1 argmin(x, axis=1) = [ 0., 0.] // argmin along axis 1 keeping same dims as an input array argmin(x, axis=1, keepdims=True) = [[ 0.], [ 0.]] )code" ADD_FILELINE) .set_attr<FCompute>("FCompute<cpu>", SearchAxisCompute<cpu, mshadow::red::minimum>) .set_attr<nnvm::FGradient>("FGradient", MakeZeroGradNodes); // Legacy support NNVM_REGISTER_OP(argmax_channel) .describe(R"code(Returns argmax indices of each channel from the input array. The result will be an NDArray of shape (num_channel,). In case of multiple occurrences of the maximum values, the indices corresponding to the first occurrence are returned. Examples:: x = [[ 0., 1., 2.], [ 3., 4., 5.]] argmax_channel(x) = [ 2., 2.] )code" ADD_FILELINE) .set_num_inputs(1) .set_num_outputs(1) .set_attr_parser([](NodeAttrs* attrs) { ReduceAxisParam param; param.axis = 1; param.keepdims = false; attrs->parsed = param; }) .set_attr<nnvm::FInferShape>("FInferShape", ReduceAxisShape) .set_attr<nnvm::FInferType>("FInferType", ElemwiseType<1, 1>) .set_attr<FCompute>("FCompute<cpu>", SearchAxisCompute<cpu, mshadow::red::maximum>) .add_argument("data", "NDArray-or-Symbol", "The input array"); NNVM_REGISTER_OP(pick) .describe(R"code(Picks elements from an input array according to the input indices along the given axis. Given an input array of shape ``(d0, d1)`` and indices of shape ``(i0,)``, the result will be an output array of shape ``(i0,)`` with:: output[i] = input[i, indices[i]] By default, if any index mentioned is too large, it is replaced by the index that addresses the last element along an axis (the `clip` mode). This function supports n-dimensional input and (n-1)-dimensional indices arrays. Examples:: x = [[ 1., 2.], [ 3., 4.], [ 5., 6.]] // picks elements with specified indices along axis 0 pick(x, y=[0,1], 0) = [ 1., 4.] // picks elements with specified indices along axis 1 pick(x, y=[0,1,0], 1) = [ 1., 4., 5.] y = [[ 1.], [ 0.], [ 2.]] // picks elements with specified indices along axis 1 and dims are maintained pick(x,y, 1, keepdims=True) = [[ 2.], [ 3.], [ 6.]] )code" ADD_FILELINE) .set_num_inputs(2) .set_num_outputs(1) .set_attr_parser(ParamParser<PickParam>) .set_attr<nnvm::FListInputNames>("FListInputNames", [](const NodeAttrs& attrs) { return std::vector<std::string>{"data", "index"}; }) .set_attr<nnvm::FInferShape>("FInferShape", PickOpShape) .set_attr<nnvm::FInferType>("FInferType", PickOpType) .set_attr<FCompute>("FCompute<cpu>", PickOpForward<cpu>) .set_attr<nnvm::FGradient>("FGradient", [](const nnvm::NodePtr& n, const std::vector<nnvm::NodeEntry>& ograds) { auto ret = MakeNonlossGradNode("_backward_pick", n, ograds, {n->inputs[1]}, n->attrs.dict); auto p = MakeNode("zeros_like", n->attrs.name + "_index_backward", {n->inputs[1]}, nullptr, &n); ret.emplace_back(nnvm::NodeEntry{p, 0, 0}); return ret; }) .add_argument("data", "NDArray-or-Symbol", "The input array") .add_argument("index", "NDArray-or-Symbol", "The index array") .add_arguments(ReduceAxisParam::__FIELDS__()); NNVM_REGISTER_OP(_backward_pick) .set_num_inputs(2) .set_num_outputs(1) .set_attr_parser(ParamParser<PickParam>) .set_attr<nnvm::TIsBackward>("TIsBackward", true) .set_attr<FCompute>("FCompute<cpu>", PickOpBackward<cpu>); } // namespace op } // namespace mxnet
Mega-DatA-Lab/mxnet
src/operator/tensor/broadcast_reduce_op_index.cc
C++
apache-2.0
5,691
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_11) on Tue Aug 12 11:16:05 PDT 2014 --> <title>com.microsoft.windowsazure.mobileservices.table.sync.synchandler</title> <meta name="date" content="2014-08-12"> <link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../../../script.js"></script> </head> <body> <h1 class="bar"><a href="../../../../../../../com/microsoft/windowsazure/mobileservices/table/sync/synchandler/package-summary.html" target="classFrame">com.microsoft.windowsazure.mobileservices.table.sync.synchandler</a></h1> <div class="indexContainer"> <h2 title="Interfaces">Interfaces</h2> <ul title="Interfaces"> <li><a href="MobileServiceSyncHandler.html" title="interface in com.microsoft.windowsazure.mobileservices.table.sync.synchandler" target="classFrame"><span class="interfaceName">MobileServiceSyncHandler</span></a></li> </ul> <h2 title="Classes">Classes</h2> <ul title="Classes"> <li><a href="SimpleSyncHandler.html" title="class in com.microsoft.windowsazure.mobileservices.table.sync.synchandler" target="classFrame">SimpleSyncHandler</a></li> </ul> <h2 title="Exceptions">Exceptions</h2> <ul title="Exceptions"> <li><a href="MobileServiceSyncHandlerException.html" title="class in com.microsoft.windowsazure.mobileservices.table.sync.synchandler" target="classFrame">MobileServiceSyncHandlerException</a></li> </ul> </div> </body> </html>
paulbatum/azure-mobile-services
sdk/android/src/sdk/doc/com/microsoft/windowsazure/mobileservices/table/sync/synchandler/package-frame.html
HTML
apache-2.0
1,587
// run-pass #![allow(dead_code)] // pretty-expanded FIXME #23616 fn main() { if true { return } match () { () => { static MAGIC: usize = 0; } } }
aidancully/rust
src/test/ui/issues/issue-16452.rs
Rust
apache-2.0
167
package org.jetbrains.debugger; import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.Conditions; import com.intellij.ui.SimpleTextAttributes; import com.intellij.xdebugger.frame.*; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.concurrency.AsyncFunction; import org.jetbrains.concurrency.AsyncPromise; import org.jetbrains.concurrency.Promise; import org.jetbrains.debugger.values.ObjectValue; import javax.swing.*; import java.util.ArrayList; import java.util.List; public class TestCompositeNode implements XCompositeNode { private final AsyncPromise<XValueChildrenList> result = new AsyncPromise<XValueChildrenList>(); private final XValueChildrenList children = new XValueChildrenList(); private final XValueGroup valueGroup; public Content content; public TestCompositeNode() { valueGroup = null; } public TestCompositeNode(@NotNull XValueGroup group) { valueGroup = group; } @NotNull public XValueGroup getValueGroup() { return valueGroup; } @Override public void addChildren(@NotNull XValueChildrenList children, boolean last) { for (XValueGroup group : children.getTopGroups()) { this.children.addTopGroup(group); } for (int i = 0; i < children.size(); i++) { this.children.add(children.getName(i), children.getValue(i)); } for (XValueGroup group : children.getBottomGroups()) { this.children.addBottomGroup(group); } if (last) { result.setResult(this.children); } } @Override public void tooManyChildren(int remaining) { result.setResult(children); } @Override public void setAlreadySorted(boolean alreadySorted) { } @Override public void setErrorMessage(@NotNull String errorMessage) { result.setError(Promise.createError(errorMessage)); } @Override public void setErrorMessage(@NotNull String errorMessage, @Nullable XDebuggerTreeNodeHyperlink link) { setErrorMessage(errorMessage); } @Override public void setMessage(@NotNull String message, @Nullable Icon icon, @NotNull SimpleTextAttributes attributes, @Nullable XDebuggerTreeNodeHyperlink link) { } @Override public boolean isObsolete() { return false; } @NotNull public Promise<XValueChildrenList> getResult() { return result; } @NotNull public Promise<Content> loadContent(@NotNull final Condition<XValueGroup> groupContentResolveCondition, @NotNull final Condition<VariableView> valueSubContentResolveCondition) { assert content == null; content = new Content(); return result.then(new AsyncFunction<XValueChildrenList, Content>() { private void resolveGroups(@NotNull List<XValueGroup> valueGroups, @NotNull List<TestCompositeNode> resultNodes, @NotNull List<Promise<?>> promises) { for (XValueGroup group : valueGroups) { TestCompositeNode node = new TestCompositeNode(group); boolean computeChildren = groupContentResolveCondition.value(group); if (computeChildren) { group.computeChildren(node); } resultNodes.add(node); if (computeChildren) { promises.add(node.loadContent(Conditions.<XValueGroup>alwaysFalse(), valueSubContentResolveCondition)); } } } @NotNull @Override public Promise<Content> fun(XValueChildrenList list) { List<Promise<?>> promises = new ArrayList<Promise<?>>(); resolveGroups(children.getTopGroups(), content.topGroups, promises); for (int i = 0; i < children.size(); i++) { XValue value = children.getValue(i); TestValueNode node = new TestValueNode(); node.myName = children.getName(i); value.computePresentation(node, XValuePlace.TREE); content.values.add(node); promises.add(node.getResult()); // myHasChildren could be not computed yet if (value instanceof VariableView && ((VariableView)value).getValue() instanceof ObjectValue && valueSubContentResolveCondition.value((VariableView)value)) { promises.add(node.loadChildren(value)); } } resolveGroups(children.getBottomGroups(), content.bottomGroups, promises); return Promise.all(promises, content); } }); } }
akosyakov/intellij-community
platform/script-debugger/debugger-ui/testSrc/org/jetbrains/debugger/TestCompositeNode.java
Java
apache-2.0
4,343
#!/usr/bin/env bash ################################################################################ # 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. ################################################################################ python=${python:-python} if [[ "$FLINK_TESTING" = "1" ]]; then ACTUAL_FLINK_HOME=`cd $FLINK_HOME; pwd -P` FLINK_SOURCE_ROOT_DIR=`cd $ACTUAL_FLINK_HOME/../../../../; pwd` FLINK_PYTHON="${FLINK_SOURCE_ROOT_DIR}/flink-python" if [[ -f "${FLINK_PYTHON}/pyflink/fn_execution/boot.py" ]]; then # use pyflink source code to override the pyflink.zip in PYTHONPATH # to ensure loading latest code export PYTHONPATH="$FLINK_PYTHON:$PYTHONPATH" fi fi if [[ "$_PYTHON_WORKING_DIR" != "" ]]; then # set current working directory to $_PYTHON_WORKING_DIR cd "$_PYTHON_WORKING_DIR" if [[ "$python" == ${_PYTHON_WORKING_DIR}* ]]; then # The file extracted from archives may not preserve its original permission. # Set minimum execution permission to prevent from permission denied error. chmod +x "$python" fi fi log="$BOOT_LOG_DIR/flink-python-udf-boot.log" ${python} -m pyflink.fn_execution.beam.beam_boot $@ 2>&1 | tee ${log}
StephanEwen/incubator-flink
flink-python/pyflink/bin/pyflink-udf-runner.sh
Shell
apache-2.0
1,977
-- verify that resource group gucs all exist, -- in case any of them are removed by accident. -- do not care about the values / ranges / types -- start_ignore \! gpconfig -s gp_resgroup_print_operator_memory_limits; -- end_ignore \! echo $?; -- start_ignore \! gpconfig -s gp_resgroup_memory_policy_auto_fixed_mem; -- end_ignore \! echo $?; -- start_ignore \! gpconfig -s gp_resgroup_memory_policy; -- end_ignore \! echo $?; -- start_ignore \! gpconfig -s gp_resource_group_cpu_priority; -- end_ignore \! echo $?; -- start_ignore \! gpconfig -s gp_resource_group_cpu_limit; -- end_ignore \! echo $?; -- start_ignore \! gpconfig -s gp_resource_group_memory_limit; -- end_ignore \! echo $?;
50wu/gpdb
src/test/regress/sql/resource_group_gucs.sql
SQL
apache-2.0
695
/*! ****************************************************************************** * * Pentaho Data Integration * * Copyright (C) 2002-2013 by Pentaho : http://www.pentaho.com * ******************************************************************************* * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ package org.pentaho.di.ui.job.entries.pgpverify; import org.apache.commons.vfs2.FileObject; import org.apache.commons.vfs2.FileSystemException; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.ShellAdapter; import org.eclipse.swt.events.ShellEvent; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.FormLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.MessageBox; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.pentaho.di.core.Const; import org.pentaho.di.core.vfs.KettleVFS; import org.pentaho.di.i18n.BaseMessages; import org.pentaho.di.job.JobMeta; import org.pentaho.di.job.entries.pgpverify.JobEntryPGPVerify; import org.pentaho.di.job.entry.JobEntryDialogInterface; import org.pentaho.di.job.entry.JobEntryInterface; import org.pentaho.di.repository.Repository; import org.pentaho.di.ui.core.gui.WindowProperty; import org.pentaho.di.ui.core.widget.TextVar; import org.pentaho.di.ui.job.dialog.JobDialog; import org.pentaho.di.ui.job.entry.JobEntryDialog; import org.pentaho.di.ui.spoon.Spoon; import org.pentaho.di.ui.trans.step.BaseStepDialog; import org.pentaho.vfs.ui.VfsFileChooserDialog; /** * This defines a PGP verify job entry. * * @author Samatar * @since 25-02-2011 * */ public class JobEntryPGPVerifyDialog extends JobEntryDialog implements JobEntryDialogInterface { private static Class<?> PKG = JobEntryPGPVerify.class; // for i18n purposes, needed by Translator2!! private static final String[] EXTENSIONS = new String[] { "*" }; private static final String[] FILETYPES = new String[] { BaseMessages.getString( PKG, "JobPGPVerify.Filetype.All" ) }; private Label wlName; private Text wName; private FormData fdlName, fdName; private Label wlGPGLocation; private Button wbGPGLocation; private TextVar wGPGLocation; private FormData fdlGPGLocation, fdbGPGLocation, fdGPGLocation; private Label wlFilename; private Button wbFilename; private TextVar wFilename; private FormData fdlFilename, fdbFilename, fdFilename; private Label wluseDetachedSignature; private Button wuseDetachedSignature; private FormData fdluseDetachedSignature, fduseDetachedSignature; private Label wlDetachedFilename; private Button wbDetachedFilename; private TextVar wDetachedFilename; private FormData fdlDetachedFilename, fdbDetachedFilename, fdDetachedFilename; private Button wOK, wCancel; private Listener lsOK, lsCancel; private JobEntryPGPVerify jobEntry; private Shell shell; private SelectionAdapter lsDef; private boolean changed; private Group wSettings; private FormData fdSettings; public JobEntryPGPVerifyDialog( Shell parent, JobEntryInterface jobEntryInt, Repository rep, JobMeta jobMeta ) { super( parent, jobEntryInt, rep, jobMeta ); jobEntry = (JobEntryPGPVerify) jobEntryInt; if ( this.jobEntry.getName() == null ) { this.jobEntry.setName( BaseMessages.getString( PKG, "JobPGPVerify.Name.Default" ) ); } } public JobEntryInterface open() { Shell parent = getParent(); Display display = parent.getDisplay(); shell = new Shell( parent, props.getJobsDialogStyle() ); props.setLook( shell ); JobDialog.setShellImage( shell, jobEntry ); ModifyListener lsMod = new ModifyListener() { public void modifyText( ModifyEvent e ) { jobEntry.setChanged(); } }; changed = jobEntry.hasChanged(); FormLayout formLayout = new FormLayout(); formLayout.marginWidth = Const.FORM_MARGIN; formLayout.marginHeight = Const.FORM_MARGIN; shell.setLayout( formLayout ); shell.setText( BaseMessages.getString( PKG, "JobPGPVerify.Title" ) ); int middle = props.getMiddlePct(); int margin = Const.MARGIN; // GPGLocation line wlName = new Label( shell, SWT.RIGHT ); wlName.setText( BaseMessages.getString( PKG, "JobPGPVerify.Name.Label" ) ); props.setLook( wlName ); fdlName = new FormData(); fdlName.left = new FormAttachment( 0, 0 ); fdlName.right = new FormAttachment( middle, -margin ); fdlName.top = new FormAttachment( 0, margin ); wlName.setLayoutData( fdlName ); wName = new Text( shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER ); props.setLook( wName ); wName.addModifyListener( lsMod ); fdName = new FormData(); fdName.left = new FormAttachment( middle, 0 ); fdName.top = new FormAttachment( 0, margin ); fdName.right = new FormAttachment( 100, 0 ); wName.setLayoutData( fdName ); // //////////////////////// // START OF SERVER SETTINGS GROUP/// // / wSettings = new Group( shell, SWT.SHADOW_NONE ); props.setLook( wSettings ); wSettings.setText( BaseMessages.getString( PKG, "JobPGPVerify.Settings.Group.Label" ) ); FormLayout SettingsgroupLayout = new FormLayout(); SettingsgroupLayout.marginWidth = 10; SettingsgroupLayout.marginHeight = 10; wSettings.setLayout( SettingsgroupLayout ); // GPGLocation line wlGPGLocation = new Label( wSettings, SWT.RIGHT ); wlGPGLocation.setText( BaseMessages.getString( PKG, "JobPGPVerify.GPGLocation.Label" ) ); props.setLook( wlGPGLocation ); fdlGPGLocation = new FormData(); fdlGPGLocation.left = new FormAttachment( 0, 0 ); fdlGPGLocation.top = new FormAttachment( wName, margin ); fdlGPGLocation.right = new FormAttachment( middle, -margin ); wlGPGLocation.setLayoutData( fdlGPGLocation ); wbGPGLocation = new Button( wSettings, SWT.PUSH | SWT.CENTER ); props.setLook( wbGPGLocation ); wbGPGLocation.setText( BaseMessages.getString( PKG, "System.Button.Browse" ) ); fdbGPGLocation = new FormData(); fdbGPGLocation.right = new FormAttachment( 100, 0 ); fdbGPGLocation.top = new FormAttachment( wName, 0 ); wbGPGLocation.setLayoutData( fdbGPGLocation ); wGPGLocation = new TextVar( jobMeta, wSettings, SWT.SINGLE | SWT.LEFT | SWT.BORDER ); props.setLook( wGPGLocation ); wGPGLocation.addModifyListener( lsMod ); fdGPGLocation = new FormData(); fdGPGLocation.left = new FormAttachment( middle, 0 ); fdGPGLocation.top = new FormAttachment( wName, margin ); fdGPGLocation.right = new FormAttachment( wbGPGLocation, -margin ); wGPGLocation.setLayoutData( fdGPGLocation ); // Filename line wlFilename = new Label( wSettings, SWT.RIGHT ); wlFilename.setText( BaseMessages.getString( PKG, "JobPGPVerify.Filename.Label" ) ); props.setLook( wlFilename ); fdlFilename = new FormData(); fdlFilename.left = new FormAttachment( 0, 0 ); fdlFilename.top = new FormAttachment( wGPGLocation, margin ); fdlFilename.right = new FormAttachment( middle, -margin ); wlFilename.setLayoutData( fdlFilename ); wbFilename = new Button( wSettings, SWT.PUSH | SWT.CENTER ); props.setLook( wbFilename ); wbFilename.setText( BaseMessages.getString( PKG, "System.Button.Browse" ) ); fdbFilename = new FormData(); fdbFilename.right = new FormAttachment( 100, 0 ); fdbFilename.top = new FormAttachment( wGPGLocation, 0 ); wbFilename.setLayoutData( fdbFilename ); wFilename = new TextVar( jobMeta, wSettings, SWT.SINGLE | SWT.LEFT | SWT.BORDER ); props.setLook( wFilename ); wFilename.addModifyListener( lsMod ); fdFilename = new FormData(); fdFilename.left = new FormAttachment( middle, 0 ); fdFilename.top = new FormAttachment( wGPGLocation, margin ); fdFilename.right = new FormAttachment( wbFilename, -margin ); wFilename.setLayoutData( fdFilename ); wluseDetachedSignature = new Label( wSettings, SWT.RIGHT ); wluseDetachedSignature.setText( BaseMessages.getString( PKG, "JobPGPVerify.useDetachedSignature.Label" ) ); props.setLook( wluseDetachedSignature ); fdluseDetachedSignature = new FormData(); fdluseDetachedSignature.left = new FormAttachment( 0, 0 ); fdluseDetachedSignature.top = new FormAttachment( wFilename, margin ); fdluseDetachedSignature.right = new FormAttachment( middle, -margin ); wluseDetachedSignature.setLayoutData( fdluseDetachedSignature ); wuseDetachedSignature = new Button( wSettings, SWT.CHECK ); props.setLook( wuseDetachedSignature ); wuseDetachedSignature.setToolTipText( BaseMessages .getString( PKG, "JobPGPVerify.useDetachedSignature.Tooltip" ) ); fduseDetachedSignature = new FormData(); fduseDetachedSignature.left = new FormAttachment( middle, 0 ); fduseDetachedSignature.top = new FormAttachment( wFilename, margin ); fduseDetachedSignature.right = new FormAttachment( 100, -margin ); wuseDetachedSignature.setLayoutData( fduseDetachedSignature ); wuseDetachedSignature.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { enableDetachedSignature(); } } ); // DetachedFilename line wlDetachedFilename = new Label( wSettings, SWT.RIGHT ); wlDetachedFilename.setText( BaseMessages.getString( PKG, "JobPGPVerify.DetachedFilename.Label" ) ); props.setLook( wlDetachedFilename ); fdlDetachedFilename = new FormData(); fdlDetachedFilename.left = new FormAttachment( 0, 0 ); fdlDetachedFilename.top = new FormAttachment( wuseDetachedSignature, margin ); fdlDetachedFilename.right = new FormAttachment( middle, -margin ); wlDetachedFilename.setLayoutData( fdlDetachedFilename ); wbDetachedFilename = new Button( wSettings, SWT.PUSH | SWT.CENTER ); props.setLook( wbDetachedFilename ); wbDetachedFilename.setText( BaseMessages.getString( PKG, "System.Button.Browse" ) ); fdbDetachedFilename = new FormData(); fdbDetachedFilename.right = new FormAttachment( 100, 0 ); fdbDetachedFilename.top = new FormAttachment( wuseDetachedSignature, 0 ); wbDetachedFilename.setLayoutData( fdbDetachedFilename ); wDetachedFilename = new TextVar( jobMeta, wSettings, SWT.SINGLE | SWT.LEFT | SWT.BORDER ); props.setLook( wDetachedFilename ); wDetachedFilename.addModifyListener( lsMod ); fdDetachedFilename = new FormData(); fdDetachedFilename.left = new FormAttachment( middle, 0 ); fdDetachedFilename.top = new FormAttachment( wuseDetachedSignature, margin ); fdDetachedFilename.right = new FormAttachment( wbDetachedFilename, -margin ); wDetachedFilename.setLayoutData( fdDetachedFilename ); // Whenever something changes, set the tooltip to the expanded version: wDetachedFilename.addModifyListener( new ModifyListener() { public void modifyText( ModifyEvent e ) { wDetachedFilename.setToolTipText( jobMeta.environmentSubstitute( wDetachedFilename.getText() ) ); } } ); wbDetachedFilename.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { try { FileObject DetachedFilename = null; try { String curFile = wDetachedFilename.getText(); if ( curFile.trim().length() > 0 ) { DetachedFilename = KettleVFS.getInstance().getFileSystemManager().resolveFile( jobMeta.environmentSubstitute( wDetachedFilename.getText() ) ); } else { DetachedFilename = KettleVFS.getInstance().getFileSystemManager().resolveFile( Const.getUserHomeDirectory() ); } } catch ( FileSystemException ex ) { DetachedFilename = KettleVFS.getInstance().getFileSystemManager().resolveFile( Const.getUserHomeDirectory() ); } VfsFileChooserDialog vfsFileChooser = Spoon.getInstance().getVfsFileChooserDialog( DetachedFilename.getParent(), DetachedFilename ); FileObject selected = vfsFileChooser.open( shell, null, EXTENSIONS, FILETYPES, VfsFileChooserDialog.VFS_DIALOG_OPEN_FILE ); wDetachedFilename.setText( selected != null ? selected.getURL().toString() : Const.EMPTY_STRING ); } catch ( FileSystemException ex ) { ex.printStackTrace(); } } } ); // Whenever something changes, set the tooltip to the expanded version: wFilename.addModifyListener( new ModifyListener() { public void modifyText( ModifyEvent e ) { wFilename.setToolTipText( jobMeta.environmentSubstitute( wFilename.getText() ) ); } } ); wbFilename.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { try { FileObject fileName = null; try { String curFile = wFilename.getText(); if ( curFile.trim().length() > 0 ) { fileName = KettleVFS.getInstance().getFileSystemManager().resolveFile( jobMeta.environmentSubstitute( wFilename.getText() ) ); } else { fileName = KettleVFS.getInstance().getFileSystemManager().resolveFile( Const.getUserHomeDirectory() ); } } catch ( FileSystemException ex ) { fileName = KettleVFS.getInstance().getFileSystemManager().resolveFile( Const.getUserHomeDirectory() ); } VfsFileChooserDialog vfsFileChooser = Spoon.getInstance().getVfsFileChooserDialog( fileName.getParent(), fileName ); FileObject selected = vfsFileChooser.open( shell, null, EXTENSIONS, FILETYPES, VfsFileChooserDialog.VFS_DIALOG_OPEN_FILE ); wFilename.setText( selected != null ? selected.getURL().toString() : Const.EMPTY_STRING ); } catch ( FileSystemException ex ) { ex.printStackTrace(); } } } ); // Whenever something changes, set the tooltip to the expanded version: wGPGLocation.addModifyListener( new ModifyListener() { public void modifyText( ModifyEvent e ) { wGPGLocation.setToolTipText( jobMeta.environmentSubstitute( wGPGLocation.getText() ) ); } } ); wbGPGLocation.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { try { FileObject fileName = null; try { String curFile = wGPGLocation.getText(); if ( curFile.trim().length() > 0 ) { fileName = KettleVFS.getInstance().getFileSystemManager().resolveFile( jobMeta.environmentSubstitute( wGPGLocation.getText() ) ); } else { fileName = KettleVFS.getInstance().getFileSystemManager().resolveFile( Const.getUserHomeDirectory() ); } } catch ( FileSystemException ex ) { fileName = KettleVFS.getInstance().getFileSystemManager().resolveFile( Const.getUserHomeDirectory() ); } VfsFileChooserDialog vfsFileChooser = Spoon.getInstance().getVfsFileChooserDialog( fileName.getParent(), fileName ); FileObject selected = vfsFileChooser.open( shell, null, EXTENSIONS, FILETYPES, VfsFileChooserDialog.VFS_DIALOG_OPEN_FILE ); wGPGLocation.setText( selected != null ? selected.getURL().toString() : Const.EMPTY_STRING ); } catch ( FileSystemException ex ) { ex.printStackTrace(); } } } ); fdSettings = new FormData(); fdSettings.left = new FormAttachment( 0, margin ); fdSettings.top = new FormAttachment( wName, margin ); fdSettings.right = new FormAttachment( 100, -margin ); wSettings.setLayoutData( fdSettings ); // /////////////////////////////////////////////////////////// // / END OF Advanced SETTINGS GROUP // /////////////////////////////////////////////////////////// wOK = new Button( shell, SWT.PUSH ); wOK.setText( BaseMessages.getString( PKG, "System.Button.OK" ) ); FormData fd = new FormData(); fd.right = new FormAttachment( 50, -10 ); fd.bottom = new FormAttachment( 100, 0 ); fd.width = 100; wOK.setLayoutData( fd ); wCancel = new Button( shell, SWT.PUSH ); wCancel.setText( BaseMessages.getString( PKG, "System.Button.Cancel" ) ); fd = new FormData(); fd.left = new FormAttachment( 50, 10 ); fd.bottom = new FormAttachment( 100, 0 ); fd.width = 100; wCancel.setLayoutData( fd ); BaseStepDialog.positionBottomButtons( shell, new Button[] { wOK, wCancel }, margin, wSettings ); // Add listeners lsCancel = new Listener() { public void handleEvent( Event e ) { cancel(); } }; lsOK = new Listener() { public void handleEvent( Event e ) { ok(); } }; wCancel.addListener( SWT.Selection, lsCancel ); wOK.addListener( SWT.Selection, lsOK ); lsDef = new SelectionAdapter() { public void widgetDefaultSelected( SelectionEvent e ) { ok(); } }; wName.addSelectionListener( lsDef ); wGPGLocation.addSelectionListener( lsDef ); // Detect X or ALT-F4 or something that kills this window... shell.addShellListener( new ShellAdapter() { public void shellClosed( ShellEvent e ) { cancel(); } } ); getData(); enableDetachedSignature(); BaseStepDialog.setSize( shell ); shell.open(); props.setDialogSize( shell, "JobPGPVerifyDialogSize" ); while ( !shell.isDisposed() ) { if ( !display.readAndDispatch() ) { display.sleep(); } } return jobEntry; } public void dispose() { WindowProperty winprop = new WindowProperty( shell ); props.setScreen( winprop ); shell.dispose(); } /** * Copy information from the meta-data input to the dialog fields. */ public void getData() { wName.setText( Const.nullToEmpty( jobEntry.getName() ) ); if ( jobEntry.getGPGLocation() != null ) { wGPGLocation.setText( jobEntry.getGPGLocation() ); } if ( jobEntry.getFilename() != null ) { wFilename.setText( jobEntry.getFilename() ); } if ( jobEntry.getDetachedfilename() != null ) { wDetachedFilename.setText( jobEntry.getDetachedfilename() ); } wuseDetachedSignature.setSelection( jobEntry.useDetachedfilename() ); wName.selectAll(); wName.setFocus(); } private void cancel() { jobEntry.setChanged( changed ); jobEntry = null; dispose(); } private void ok() { if ( Const.isEmpty( wName.getText() ) ) { MessageBox mb = new MessageBox( shell, SWT.OK | SWT.ICON_ERROR ); mb.setText( BaseMessages.getString( PKG, "System.StepJobEntryNameMissing.Title" ) ); mb.setMessage( BaseMessages.getString( PKG, "System.JobEntryNameMissing.Msg" ) ); mb.open(); return; } jobEntry.setName( wName.getText() ); jobEntry.setGPGLocation( wGPGLocation.getText() ); jobEntry.setFilename( wFilename.getText() ); jobEntry.setDetachedfilename( wDetachedFilename.getText() ); jobEntry.setUseDetachedfilename( wuseDetachedSignature.getSelection() ); dispose(); } private void enableDetachedSignature() { wlDetachedFilename.setEnabled( wuseDetachedSignature.getSelection() ); wDetachedFilename.setEnabled( wuseDetachedSignature.getSelection() ); wbDetachedFilename.setEnabled( wuseDetachedSignature.getSelection() ); } public boolean evaluates() { return true; } public boolean isUnconditional() { return false; } }
sajeetharan/pentaho-kettle
ui/src/org/pentaho/di/ui/job/entries/pgpverify/JobEntryPGPVerifyDialog.java
Java
apache-2.0
20,639
# Development report for 22 May 2017 The tenth weekly development report. Feel free to send PRs if you want to add to these reports (or correct them). There is now a new [linuxkit/virtsock] repository that contains Go bindings and sample code for Hyper-V sockets and virtio sockets. A [SIG Security](https://github.com/linuxkit/linuxkit/blob/master/sigs/security/README.md) has been instituted and there will be a [call on 24 May 2017](https://github.com/linuxkit/linuxkit/blob/master/reports/sig-security/2017-05-24.md). ## Overview - We have mostly added a registry and hub org override so you can do `make ORG=myorg` when building packages, rather than pushing to the `linuxkit` org. - ongoing work has continued to move all builds to use the same Alpine base package. [linuxkit/linuxkit#1856] [@rneugeba] - Label support - images may now specify an `org.mobyproject.config` label which contains a JSON version of the config. Anything set in this config will be the default, but can be overridden by the yaml file. In many cases this means that the yaml is nor needed, simplifying the config a lot. [linuxkit/linuxkit#1862] [@justincormack] - Testing has been significantly improved and more tests are being added. ## PRs merged Kernel and Base: - Update Hyper-V patches for 4.11 and add Hub org override for kernel builds [linuxkit/linuxkit#1844] [@justincormack] [@rneugeba] - kernel: Add vmlinux to debug builds [linuxkit/linuxkit#1849] [@rneugeba] - Update containerd [linuxkit/linuxkit#1861] [@justincormack] Projects: - add IMA namespacing project [linuxkit/linuxkit#1857] [@guimagalhaes] [@riyazdf] [@justincormack] CLI: - Allow forcing qemu backend to use container via command line [linuxkit/linuxkit#1854] [@rneugeba] [@ijc25] - Pass `--tty` to `docker run` when running Qemu via a container [linuxkit/linuxkit#1855] [@justincormack] [@rneugeba] [@ijc25] Tests/CI: - Tidy up the tests [linuxkit/linuxkit#1830] [@talex5] [@justincormack] [@rneugeba] - Save contents of test/_results after building [linuxkit/linuxkit-ci#5] [@talex5] - Turn on vm.overcommit_memory on GCP builder [linuxkit/linuxkit-ci#7] [@rneugeba] [@talex5] Documentation: - Add a section on custom kernel builds [linuxkit/linuxkit#1838] [@justincormack] [@rneugeba] - Document the CI setup [linuxkit/linuxkit#1840] [@dave-tucker] [@talex5] [@justincormack] - update SIG agenda with IMA namespace support [linuxkit/linuxkit#1851] [@tych0] [@justincormack] - Fix Github language detection [linuxkit/linuxkit#1842] [@dave-tucker] ## PRs closed without merge - LinuxKit push and run on Azure - still being worked on [linuxkit/linuxkit#1864] [@radu-matei] ## Issues of interest - [linuxkit/linuxkit#1835] Build my own kernel was closed ([@rneugeba] [@justincormack] [@yankunsam]) - [linuxkit/linuxkit#1841] Windows moby build failed was closed ([@rneugeba] [@tippexs]) - [linuxkit/linuxkit#1845] [Question] Run service container with elevated privileges was closed ([@radu-matei]) - [linuxkit/linuxkit#1846] Can busybox in the root fs be stripped down more? was closed ([@rneugeba] [@justincormack] [@avsm]) - [linuxkit/linuxkit#1847] Selection of architecture in config by `moby` tool was closed ([@mor1]) - [linuxkit/linuxkit#1115] bios iso test was opened and closed ([@rneugeba] [@justincormack]) - [linuxkit/linuxkit#1429] DockerCon and open source planning was opened and closed ([@rneugeba]) - [linuxkit/linuxkit#1453] unify nameing of compile containers was opened and closed ([@rneugeba]) - [linuxkit/linuxkit#1616] HVSock related crash with 17.05.0-rc1 was opened and closed ([@rneugeba] [@simonferquel]) - [linuxkit/linuxkit#1661] With containerd, sometimes service containers don't get started was opened and closed ([@rneugeba]) - [linuxkit/linuxkit#1824] Set docker hub repository linuxkit as variable was opened and closed ([@rneugeba] [@pwFoo]) - [linuxkit/linuxkit#1828] Arrow keys do not work after boot with qemu running in a container was opened and closed ([@ijc25] [@rneugeba] [@mrmodolo]) - [linuxkit/linuxkit#1859] oomScoreAdj not working had 0 event () - [linuxkit/linuxkit#1863] linuxkit initial make failed on Windows had 0 event ([@justincormack]) - [linuxkit/rtf#14] Honour ordering for mixed tests/subgroups had 0 event () - [linuxkit/linuxkit#1742] Handle kernel module loading better had 1 event ([@pwFoo]) - [linuxkit/linuxkit#1767] no host networking on Linux/qemu had 1 event ([@justincormack]) - [linuxkit/linuxkit#1852] [Request] Update `sysctl.conf` and `limits.conf` defaults had 1 event ([@rneugeba] [@justincormack]) - [linuxkit/linuxkit#1376] kernel hang in fchownat? had 2 events ([@djs55] [@dsheets] [@rneugeba]) - [linuxkit/linuxkit#1377] [tracking] ARM boot status had 2 events ([@rneugeba] [@techninja1008] [@mor1]) - [linuxkit/linuxkit#1692] Proposal: example for Minio S3 as an appliance had 2 events ([@alexellis] [@rneugeba]) - [linuxkit/linuxkit#1848] Hyper-V socket crash with 4.11 kernels had 2 events ([@rneugeba] [@dcui]) - [linuxkit/linuxkit#492] preload a registry into test base image had 2 events ([@justincormack] [@rneugeba]) - [linuxkit/linuxkit#1426] replace busybox init had 3 events ([@justincormack] [@pwFoo]) - [linuxkit/linuxkit#1836] Trying to output as .vhd hangs / takes a lot of time had 3 events ([@justincormack] [@radu-matei] [@rneugeba]) - [linuxkit/rtf#13] Add ability to run a single test or a group had 3 events ([@rneugeba] [@dave-tucker]) - [linuxkit/linuxkit#1839] After halt, it will been blocked and have no response had 4 events ([@yankunsam] [@avsm] [@rneugeba] [@thebsdbox]) - [linuxkit/linuxkit#1837] `ctr exec -t` hangs had 6 events ([@FrenchBen] [@avsm] [@rneugeba] [@justincormack]) - [linuxkit/linuxkit#1421] Add build support for Azure to `moby build` had 7 events ([@justincormack] [@radu-matei]) Other reports in this series can be browsed directly in the repository at [linuxkit/linuxkit:/reports](https://github.com/linuxkit/linuxkit/tree/master/reports/). [@FrenchBen]: https://github.com/FrenchBen [@MagnusS]: https://github.com/MagnusS [@RobbKistler]: https://github.com/RobbKistler [@alexellis]: https://github.com/alexellis [@avsm]: https://github.com/avsm [@dave-tucker]: https://github.com/dave-tucker [@dcui]: https://github.com/dcui [@djs55]: https://github.com/djs55 [@dsheets]: https://github.com/dsheets [@guimagalhaes]: https://github.com/guimagalhaes [@ijc25]: https://github.com/ijc25 [@justincormack]: https://github.com/justincormack [@mor1]: https://github.com/mor1 [@mrmodolo]: https://github.com/mrmodolo [@pwFoo]: https://github.com/pwFoo [@radu-matei]: https://github.com/radu-matei [@riyazdf]: https://github.com/riyazdf [@rneugeba]: https://github.com/rneugeba [@simonferquel]: https://github.com/simonferquel [@talex5]: https://github.com/talex5 [@techninja1008]: https://github.com/techninja1008 [@thebsdbox]: https://github.com/thebsdbox [@tippexs]: https://github.com/tippexs [@tych0]: https://github.com/tych0 [@yankunsam]: https://github.com/yankunsam [linuxkit/linuxkit]: https://github.com/linuxkit/linuxkit [linuxkit/linuxkit#1115]: https://github.com/linuxkit/linuxkit/issues/1115 [linuxkit/linuxkit#1376]: https://github.com/linuxkit/linuxkit/issues/1376 [linuxkit/linuxkit#1377]: https://github.com/linuxkit/linuxkit/issues/1377 [linuxkit/linuxkit#1421]: https://github.com/linuxkit/linuxkit/issues/1421 [linuxkit/linuxkit#1426]: https://github.com/linuxkit/linuxkit/issues/1426 [linuxkit/linuxkit#1429]: https://github.com/linuxkit/linuxkit/issues/1429 [linuxkit/linuxkit#1453]: https://github.com/linuxkit/linuxkit/issues/1453 [linuxkit/linuxkit#1616]: https://github.com/linuxkit/linuxkit/issues/1616 [linuxkit/linuxkit#1661]: https://github.com/linuxkit/linuxkit/issues/1661 [linuxkit/linuxkit#1692]: https://github.com/linuxkit/linuxkit/issues/1692 [linuxkit/linuxkit#1742]: https://github.com/linuxkit/linuxkit/issues/1742 [linuxkit/linuxkit#1767]: https://github.com/linuxkit/linuxkit/issues/1767 [linuxkit/linuxkit#1783]: https://github.com/linuxkit/linuxkit/pull/1783 [linuxkit/linuxkit#1813]: https://github.com/linuxkit/linuxkit/pull/1813 [linuxkit/linuxkit#1824]: https://github.com/linuxkit/linuxkit/issues/1824 [linuxkit/linuxkit#1826]: https://github.com/linuxkit/linuxkit/pull/1826 [linuxkit/linuxkit#1827]: https://github.com/linuxkit/linuxkit/pull/1827 [linuxkit/linuxkit#1828]: https://github.com/linuxkit/linuxkit/issues/1828 [linuxkit/linuxkit#1829]: https://github.com/linuxkit/linuxkit/pull/1829 [linuxkit/linuxkit#1830]: https://github.com/linuxkit/linuxkit/pull/1830 [linuxkit/linuxkit#1831]: https://github.com/linuxkit/linuxkit/pull/1831 [linuxkit/linuxkit#1832]: https://github.com/linuxkit/linuxkit/pull/1832 [linuxkit/linuxkit#1833]: https://github.com/linuxkit/linuxkit/pull/1833 [linuxkit/linuxkit#1834]: https://github.com/linuxkit/linuxkit/pull/1834 [linuxkit/linuxkit#1835]: https://github.com/linuxkit/linuxkit/issues/1835 [linuxkit/linuxkit#1836]: https://github.com/linuxkit/linuxkit/issues/1836 [linuxkit/linuxkit#1837]: https://github.com/linuxkit/linuxkit/issues/1837 [linuxkit/linuxkit#1838]: https://github.com/linuxkit/linuxkit/pull/1838 [linuxkit/linuxkit#1839]: https://github.com/linuxkit/linuxkit/issues/1839 [linuxkit/linuxkit#1840]: https://github.com/linuxkit/linuxkit/pull/1840 [linuxkit/linuxkit#1841]: https://github.com/linuxkit/linuxkit/issues/1841 [linuxkit/linuxkit#1842]: https://github.com/linuxkit/linuxkit/pull/1842 [linuxkit/linuxkit#1843]: https://github.com/linuxkit/linuxkit/pull/1843 [linuxkit/linuxkit#1844]: https://github.com/linuxkit/linuxkit/pull/1844 [linuxkit/linuxkit#1845]: https://github.com/linuxkit/linuxkit/issues/1845 [linuxkit/linuxkit#1846]: https://github.com/linuxkit/linuxkit/issues/1846 [linuxkit/linuxkit#1847]: https://github.com/linuxkit/linuxkit/issues/1847 [linuxkit/linuxkit#1848]: https://github.com/linuxkit/linuxkit/issues/1848 [linuxkit/linuxkit#1849]: https://github.com/linuxkit/linuxkit/pull/1849 [linuxkit/linuxkit#1850]: https://github.com/linuxkit/linuxkit/pull/1850 [linuxkit/linuxkit#1851]: https://github.com/linuxkit/linuxkit/pull/1851 [linuxkit/linuxkit#1852]: https://github.com/linuxkit/linuxkit/issues/1852 [linuxkit/linuxkit#1853]: https://github.com/linuxkit/linuxkit/pull/1853 [linuxkit/linuxkit#1854]: https://github.com/linuxkit/linuxkit/pull/1854 [linuxkit/linuxkit#1855]: https://github.com/linuxkit/linuxkit/pull/1855 [linuxkit/linuxkit#1856]: https://github.com/linuxkit/linuxkit/pull/1856 [linuxkit/linuxkit#1857]: https://github.com/linuxkit/linuxkit/pull/1857 [linuxkit/linuxkit#1858]: https://github.com/linuxkit/linuxkit/pull/1858 [linuxkit/linuxkit#1859]: https://github.com/linuxkit/linuxkit/issues/1859 [linuxkit/linuxkit#1860]: https://github.com/linuxkit/linuxkit/pull/1860 [linuxkit/linuxkit#1861]: https://github.com/linuxkit/linuxkit/pull/1861 [linuxkit/linuxkit#1862]: https://github.com/linuxkit/linuxkit/pull/1862 [linuxkit/linuxkit#1863]: https://github.com/linuxkit/linuxkit/issues/1863 [linuxkit/linuxkit#1864]: https://github.com/linuxkit/linuxkit/pull/1864 [linuxkit/linuxkit#1865]: https://github.com/linuxkit/linuxkit/pull/1865 [linuxkit/linuxkit#492]: https://github.com/linuxkit/linuxkit/issues/492 [linuxkit/linuxkit-ci]: https://github.com/linuxkit/linuxkit-ci [linuxkit/linuxkit-ci#5]: https://github.com/linuxkit/linuxkit-ci/pull/5 [linuxkit/linuxkit-ci#6]: https://github.com/linuxkit/linuxkit-ci/pull/6 [linuxkit/linuxkit-ci#7]: https://github.com/linuxkit/linuxkit-ci/pull/7 [linuxkit/rtf]: https://github.com/linuxkit/rtf [linuxkit/rtf#13]: https://github.com/linuxkit/rtf/issues/13 [linuxkit/rtf#14]: https://github.com/linuxkit/rtf/issues/14 [linuxkit/rtf#15]: https://github.com/linuxkit/rtf/pull/15 [linuxkit/virtsock]: https://github.com/linuxkit/virtsock [linuxkit/virtsock#28]: https://github.com/linuxkit/virtsock/pull/28
JohnnyLeone/linuxkit
reports/2017-05-22.md
Markdown
apache-2.0
11,820
cask :v1 => 'retroarch' do version '1.0.0.2' if MacOS.release <= :snow_leopard sha256 'a3ebc3a46d674433a1bf40c1b948021e752919b4b43da853fd73fb508bf40982' url "http://buildbot.libretro.com/stable/OSX/RetroArch-OSX10.6-x86-v#{version}.zip" else sha256 '9d2232663f5dade1b4f648cc0cf0bb605c630b1c6bcbfe5ddce265ddab0d9d2a' url "http://buildbot.libretro.com/stable/OSX/RetroArch-OSX10.7-x86_64-v#{version}.zip" end name 'RetroArch' homepage 'http://www.libretro.com/' license :unknown # todo: change license and remove this comment; ':unknown' is a machine-generated placeholder app 'RetroArch.app' end
joaoponceleao/homebrew-cask
Casks/retroarch.rb
Ruby
bsd-2-clause
630
<?php /** * PHPCI - Continuous Integration for PHP * * @copyright Copyright 2014, Block 8 Limited. * @license https://github.com/Block8/PHPCI/blob/master/LICENSE.md * @link https://www.phptesting.org/ */ namespace PHPCI\Plugin; use Exception; use b8\View; use PHPCI\Builder; use PHPCI\Helper\Lang; use PHPCI\Model\Build; use PHPCI\Helper\Email as EmailHelper; use Psr\Log\LogLevel; /** * Email Plugin - Provides simple email capability to PHPCI. * @author Steve Brazier <meadsteve@gmail.com> * @package PHPCI * @subpackage Plugins */ class Email implements \PHPCI\Plugin { /** * @var \PHPCI\Builder */ protected $phpci; /** * @var \PHPCI\Model\Build */ protected $build; /** * @var array */ protected $options; /** * Set up the plugin, configure options, etc. * @param Builder $phpci * @param Build $build * @param \Swift_Mailer $mailer * @param array $options */ public function __construct( Builder $phpci, Build $build, array $options = array() ) { $this->phpci = $phpci; $this->build = $build; $this->options = $options; } /** * Send a notification mail. */ public function execute() { $addresses = $this->getEmailAddresses(); // Without some email addresses in the yml file then we // can't do anything. if (count($addresses) == 0) { return false; } $buildStatus = $this->build->isSuccessful() ? "Passing Build" : "Failing Build"; $projectName = $this->build->getProject()->getTitle(); try { $view = $this->getMailTemplate(); } catch (Exception $e) { $this->phpci->log( sprintf('Unknown mail template "%s", falling back to default.', $this->options['template']), LogLevel::WARNING ); $view = $this->getDefaultMailTemplate(); } $view->build = $this->build; $view->project = $this->build->getProject(); $layout = new View('Email/layout'); $layout->build = $this->build; $layout->project = $this->build->getProject(); $layout->content = $view->render(); $body = $layout->render(); $sendFailures = $this->sendSeparateEmails( $addresses, sprintf("PHPCI - %s - %s", $projectName, $buildStatus), $body ); // This is a success if we've not failed to send anything. $this->phpci->log(sprintf("%d emails sent", (count($addresses) - $sendFailures))); $this->phpci->log(sprintf("%d emails failed to send", $sendFailures)); return ($sendFailures === 0); } /** * @param string $toAddress Single address to send to * @param string[] $ccList * @param string $subject Email subject * @param string $body Email body * @return array Array of failed addresses */ protected function sendEmail($toAddress, $ccList, $subject, $body) { $email = new EmailHelper(); $email->setEmailTo($toAddress, $toAddress); $email->setSubject($subject); $email->setBody($body); $email->setHtml(true); if (is_array($ccList) && count($ccList)) { foreach ($ccList as $address) { $email->addCc($address, $address); } } return $email->send(); } /** * Send an email to a list of specified subjects. * * @param array $toAddresses * List of destinatary of message. * @param string $subject * Mail subject * @param string $body * Mail body * * @return int number of failed messages */ public function sendSeparateEmails(array $toAddresses, $subject, $body) { $failures = 0; $ccList = $this->getCcAddresses(); foreach ($toAddresses as $address) { if (!$this->sendEmail($address, $ccList, $subject, $body)) { $failures++; } } return $failures; } /** * Get the list of email addresses to send to. * @return array */ protected function getEmailAddresses() { $addresses = array(); $committer = $this->build->getCommitterEmail(); if (isset($this->options['committer']) && !empty($committer)) { $addresses[] = $committer; } if (isset($this->options['addresses'])) { foreach ($this->options['addresses'] as $address) { $addresses[] = $address; } } if (empty($addresses) && isset($this->options['default_mailto_address'])) { $addresses[] = $this->options['default_mailto_address']; } return array_unique($addresses); } /** * Get the list of email addresses to CC. * * @return array */ protected function getCcAddresses() { $ccAddresses = array(); if (isset($this->options['cc'])) { foreach ($this->options['cc'] as $address) { $ccAddresses[] = $address; } } return $ccAddresses; } /** * Get the mail template used to sent the mail. * * @return View */ protected function getMailTemplate() { if (isset($this->options['template'])) { return new View('Email/' . $this->options['template']); } return $this->getDefaultMailTemplate(); } /** * Get the default mail template. * * @return View */ protected function getDefaultMailTemplate() { $template = $this->build->isSuccessful() ? 'short' : 'long'; return new View('Email/' . $template); } }
nelsonyang0710/PHPCI
PHPCI/Plugin/Email.php
PHP
bsd-2-clause
5,888
/** * Utility functions for jazzing up HTMLForm elements. */ ( function ( mw, $ ) { /** * jQuery plugin to fade or snap to visible state. * * @param {boolean} instantToggle [optional] * @return {jQuery} */ $.fn.goIn = function ( instantToggle ) { if ( instantToggle === true ) { return $(this).show(); } return $(this).stop( true, true ).fadeIn(); }; /** * jQuery plugin to fade or snap to hiding state. * * @param {boolean} instantToggle [optional] * @return jQuery */ $.fn.goOut = function ( instantToggle ) { if ( instantToggle === true ) { return $(this).hide(); } return $(this).stop( true, true ).fadeOut(); }; /** * Bind a function to the jQuery object via live(), and also immediately trigger * the function on the objects with an 'instant' parameter set to true. * @param {Function} callback Takes one parameter, which is {true} when the * event is called immediately, and {jQuery.Event} when triggered from an event. */ $.fn.liveAndTestAtStart = function ( callback ){ $(this) .live( 'change', callback ) .each( function () { callback.call( this, true ); } ); }; $( function () { // Animate the SelectOrOther fields, to only show the text field when // 'other' is selected. $( '.mw-htmlform-select-or-other' ).liveAndTestAtStart( function ( instant ) { var $other = $( '#' + $(this).attr( 'id' ) + '-other' ); $other = $other.add( $other.siblings( 'br' ) ); if ( $(this).val() === 'other' ) { $other.goIn( instant ); } else { $other.goOut( instant ); } }); } ); function addMulti( $oldContainer, $container ) { var name = $oldContainer.find( 'input:first-child' ).attr( 'name' ), oldClass = ( ' ' + $oldContainer.attr( 'class' ) + ' ' ).replace( /(mw-htmlform-field-HTMLMultiSelectField|mw-chosen)/g, '' ), $select = $( '<select>' ), dataPlaceholder = mw.message( 'htmlform-chosen-placeholder' ); oldClass = $.trim( oldClass ); $select.attr( { name: name, multiple: 'multiple', 'data-placeholder': dataPlaceholder.plain(), 'class': 'htmlform-chzn-select mw-input ' + oldClass } ); $oldContainer.find( 'input' ).each( function () { var $oldInput = $(this), checked = $oldInput.prop( 'checked' ), $option = $( '<option>' ); $option.prop( 'value', $oldInput.prop( 'value' ) ); if ( checked ) { $option.prop( 'selected', true ); } $option.text( $oldInput.prop( 'value' ) ); $select.append( $option ); } ); $container.append( $select ); } function convertCheckboxesToMulti( $oldContainer, type ) { var $fieldLabel = $( '<td>' ), $td = $( '<td>' ), $fieldLabelText = $( '<label>' ), $container; if ( type === 'tr' ) { addMulti( $oldContainer, $td ); $container = $( '<tr>' ); $container.append( $td ); } else if ( type === 'div' ) { $fieldLabel = $( '<div>' ); $container = $( '<div>' ); addMulti( $oldContainer, $container ); } $fieldLabel.attr( 'class', 'mw-label' ); $fieldLabelText.text( $oldContainer.find( '.mw-label label' ).text() ); $fieldLabel.append( $fieldLabelText ); $container.prepend( $fieldLabel ); $oldContainer.replaceWith( $container ); return $container; } if ( $( '.mw-chosen' ).length ) { mw.loader.using( 'jquery.chosen', function () { $( '.mw-chosen' ).each( function () { var type = this.nodeName.toLowerCase(), $converted = convertCheckboxesToMulti( $( this ), type ); $converted.find( '.htmlform-chzn-select' ).chosen( { width: 'auto' } ); } ); } ); } $( function () { var $matrixTooltips = $( '.mw-htmlform-matrix .mw-htmlform-tooltip' ); if ( $matrixTooltips.length ) { mw.loader.using( 'jquery.tipsy', function () { $matrixTooltips.tipsy( { gravity: 's' } ); } ); } } ); }( mediaWiki, jQuery ) );
BRL-CAD/web
wiki/resources/mediawiki/mediawiki.htmlform.js
JavaScript
bsd-2-clause
3,804
{% extends "account/base.html" %} {% load url from future %} {% load i18n %} {% block head_title %}{% trans "Sign Out" %}{% endblock %} {% block content %} <h1>{% trans "Sign Out" %}</h1> <p>{% trans 'Are you sure you want to sign out?' %}</p> <form method="post" action="{% url 'account_logout' %}"> {% csrf_token %} {% if redirect_field_value %} <input type="hidden" name="{{redirect_field_name}}" value="{{redirect_field_value}}"/> {% endif %} <button class="btn btn-primary" type="submit">{% trans 'Sign Out' %}</button> </form> {% endblock %}
fpytloun/waliki
waliki_project/waliki_project/templates/allauth/account/logout.html
HTML
bsd-3-clause
565
<!DOCTYPE html> <meta charset="utf-8"> <link rel="author" href="mailto:masonf@chromium.org"> <link rel="help" href="https://crbug.com/1180286"> <meta name="assert" content="The renderer should not crash."> <span>This test passes if the renderer does not crash.</span> <div> <option></option> </div> <style> div { direction: rtl; zoom: 0.01; } option { zoom: 5; } option::before { display: table-caption; overflow: scroll; content: open-quote; padding-right: 1px; -webkit-column-width: 1px; } </style>
chromium/chromium
third_party/blink/web_tests/external/wpt/shadow-dom/event-on-pseudo-element-crash.html
HTML
bsd-3-clause
550
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <future> // class shared_future<R> // shared_future(future<R>&& rhs); #include <future> #include <cassert> int main() { { typedef int T; std::promise<T> p; std::future<T> f0 = p.get_future(); std::shared_future<T> f = std::move(f0); assert(!f0.valid()); assert(f.valid()); } { typedef int T; std::future<T> f0; std::shared_future<T> f = std::move(f0); assert(!f0.valid()); assert(!f.valid()); } { typedef int& T; std::promise<T> p; std::future<T> f0 = p.get_future(); std::shared_future<T> f = std::move(f0); assert(!f0.valid()); assert(f.valid()); } { typedef int& T; std::future<T> f0; std::shared_future<T> f = std::move(f0); assert(!f0.valid()); assert(!f.valid()); } { typedef void T; std::promise<T> p; std::future<T> f0 = p.get_future(); std::shared_future<T> f = std::move(f0); assert(!f0.valid()); assert(f.valid()); } { typedef void T; std::future<T> f0; std::shared_future<T> f = std::move(f0); assert(!f0.valid()); assert(!f.valid()); } }
mxOBS/deb-pkg_trusty_chromium-browser
third_party/libc++/trunk/test/thread/futures/futures.shared_future/ctor_future.pass.cpp
C++
bsd-3-clause
1,627
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>CSS Text Decoration Test: text-decoration-thickness respects variable font properties</title> <link rel="help" href="https://drafts.csswg.org/css-text-decor-4/#text-decoration-width-property"> <meta name="assert" content="text-decoration-thickness from-font respects MVAR table of variable fonts for variable metrics"> <link rel="author" title="Dominik Röttsches" href="mailto:drott@chromium.org"> <style> @font-face { font-family: underline-thin; src: url(../resources/UnderlineTest-Thin.ttf); } @font-face { font-family: underline-thick; src: url(../resources/UnderlineTest-Thick.ttf); } .test { text-underline-position: from-font; font-size: 64px; line-height: 1.8; } .thin_underline { text-decoration: underline; font-family: underline-thin; text-decoration-thickness: from-font; } .thick_underline { text-decoration: underline; font-family: underline-thick; text-decoration-thickness: from-font; } </style> </head> <body> <p>Test passes if the underline on the first line is thin and thick on the second line.</p> <div class="test"><span class="thin_underline">aagaa</span></div> <div class="test"><span class="thick_underline">aagaa</span></div> </body> </html>
nwjs/chromium.src
third_party/blink/web_tests/external/wpt/css/css-text-decor/reference/text-decoration-thickness-from-font-variable-ref.html
HTML
bsd-3-clause
1,245
<!DOCTYPE html> <!-- Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ --> <html> <head> <meta charset="utf-8"> <title>CSS Test: 'object-fit: scale-down' on img element, with a PNG image and with various 'object-position' values</title> <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"> <link rel="help" href="http://www.w3.org/TR/css3-images/#sizing"> <link rel="help" href="http://www.w3.org/TR/css3-images/#the-object-fit"> <link rel="help" href="http://www.w3.org/TR/css3-images/#the-object-position"> <link rel="match" href="object-fit-scale-down-png-001-ref.html"> <style type="text/css"> img { border: 1px dashed gray; padding: 1px; object-fit: scale-down; image-rendering: crisp-edges; float: left; } .bigWide { width: 48px; height: 32px; } .bigTall { width: 32px; height: 48px; } .small { width: 8px; height: 8px; } br { clear: both; } .tr { object-position: top right } .bl { object-position: bottom left } .tl { object-position: top 25% left 25% } .br { object-position: bottom 1px right 2px } .tc { object-position: top 3px left 50% } .cr { object-position: top 50% right 25% } </style> </head> <body> <!-- big/wide: --> <img src="support/colors-16x8.png" class="bigWide tr"> <img src="support/colors-16x8.png" class="bigWide bl"> <img src="support/colors-16x8.png" class="bigWide tl"> <img src="support/colors-16x8.png" class="bigWide br"> <img src="support/colors-16x8.png" class="bigWide tc"> <img src="support/colors-16x8.png" class="bigWide cr"> <img src="support/colors-16x8.png" class="bigWide"> <br> <!-- big/tall: --> <img src="support/colors-16x8.png" class="bigTall tr"> <img src="support/colors-16x8.png" class="bigTall bl"> <img src="support/colors-16x8.png" class="bigTall tl"> <img src="support/colors-16x8.png" class="bigTall br"> <img src="support/colors-16x8.png" class="bigTall tc"> <img src="support/colors-16x8.png" class="bigTall cr"> <img src="support/colors-16x8.png" class="bigTall"> <br> <!-- small: --> <img src="support/colors-16x8.png" class="small tr"> <img src="support/colors-16x8.png" class="small bl"> <img src="support/colors-16x8.png" class="small tl"> <img src="support/colors-16x8.png" class="small br"> <img src="support/colors-16x8.png" class="small tc"> <img src="support/colors-16x8.png" class="small cr"> <img src="support/colors-16x8.png" class="small"> <br> </body> </html>
scheib/chromium
third_party/blink/web_tests/external/wpt/css/css-images/object-fit-scale-down-png-001i.html
HTML
bsd-3-clause
2,752
/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * Crypto user configuration API. * * Copyright (C) 2011 secunet Security Networks AG * Copyright (C) 2011 Steffen Klassert <steffen.klassert@secunet.com> * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef _UAPI_LINUX_CRYPTOUSER_H #define _UAPI_LINUX_CRYPTOUSER_H #include <linux/types.h> /* Netlink configuration messages. */ enum { CRYPTO_MSG_BASE = 0x10, CRYPTO_MSG_NEWALG = 0x10, CRYPTO_MSG_DELALG, CRYPTO_MSG_UPDATEALG, CRYPTO_MSG_GETALG, CRYPTO_MSG_DELRNG, CRYPTO_MSG_GETSTAT, __CRYPTO_MSG_MAX }; #define CRYPTO_MSG_MAX (__CRYPTO_MSG_MAX - 1) #define CRYPTO_NR_MSGTYPES (CRYPTO_MSG_MAX + 1 - CRYPTO_MSG_BASE) #define CRYPTO_MAX_NAME 64 /* Netlink message attributes. */ enum crypto_attr_type_t { CRYPTOCFGA_UNSPEC, CRYPTOCFGA_PRIORITY_VAL, /* __u32 */ CRYPTOCFGA_REPORT_LARVAL, /* struct crypto_report_larval */ CRYPTOCFGA_REPORT_HASH, /* struct crypto_report_hash */ CRYPTOCFGA_REPORT_BLKCIPHER, /* struct crypto_report_blkcipher */ CRYPTOCFGA_REPORT_AEAD, /* struct crypto_report_aead */ CRYPTOCFGA_REPORT_COMPRESS, /* struct crypto_report_comp */ CRYPTOCFGA_REPORT_RNG, /* struct crypto_report_rng */ CRYPTOCFGA_REPORT_CIPHER, /* struct crypto_report_cipher */ CRYPTOCFGA_REPORT_AKCIPHER, /* struct crypto_report_akcipher */ CRYPTOCFGA_REPORT_KPP, /* struct crypto_report_kpp */ CRYPTOCFGA_REPORT_ACOMP, /* struct crypto_report_acomp */ CRYPTOCFGA_STAT_LARVAL, /* struct crypto_stat */ CRYPTOCFGA_STAT_HASH, /* struct crypto_stat */ CRYPTOCFGA_STAT_BLKCIPHER, /* struct crypto_stat */ CRYPTOCFGA_STAT_AEAD, /* struct crypto_stat */ CRYPTOCFGA_STAT_COMPRESS, /* struct crypto_stat */ CRYPTOCFGA_STAT_RNG, /* struct crypto_stat */ CRYPTOCFGA_STAT_CIPHER, /* struct crypto_stat */ CRYPTOCFGA_STAT_AKCIPHER, /* struct crypto_stat */ CRYPTOCFGA_STAT_KPP, /* struct crypto_stat */ CRYPTOCFGA_STAT_ACOMP, /* struct crypto_stat */ __CRYPTOCFGA_MAX #define CRYPTOCFGA_MAX (__CRYPTOCFGA_MAX - 1) }; struct crypto_user_alg { char cru_name[CRYPTO_MAX_NAME]; char cru_driver_name[CRYPTO_MAX_NAME]; char cru_module_name[CRYPTO_MAX_NAME]; __u32 cru_type; __u32 cru_mask; __u32 cru_refcnt; __u32 cru_flags; }; struct crypto_stat_aead { char type[CRYPTO_MAX_NAME]; __u64 stat_encrypt_cnt; __u64 stat_encrypt_tlen; __u64 stat_decrypt_cnt; __u64 stat_decrypt_tlen; __u64 stat_err_cnt; }; struct crypto_stat_akcipher { char type[CRYPTO_MAX_NAME]; __u64 stat_encrypt_cnt; __u64 stat_encrypt_tlen; __u64 stat_decrypt_cnt; __u64 stat_decrypt_tlen; __u64 stat_verify_cnt; __u64 stat_sign_cnt; __u64 stat_err_cnt; }; struct crypto_stat_cipher { char type[CRYPTO_MAX_NAME]; __u64 stat_encrypt_cnt; __u64 stat_encrypt_tlen; __u64 stat_decrypt_cnt; __u64 stat_decrypt_tlen; __u64 stat_err_cnt; }; struct crypto_stat_compress { char type[CRYPTO_MAX_NAME]; __u64 stat_compress_cnt; __u64 stat_compress_tlen; __u64 stat_decompress_cnt; __u64 stat_decompress_tlen; __u64 stat_err_cnt; }; struct crypto_stat_hash { char type[CRYPTO_MAX_NAME]; __u64 stat_hash_cnt; __u64 stat_hash_tlen; __u64 stat_err_cnt; }; struct crypto_stat_kpp { char type[CRYPTO_MAX_NAME]; __u64 stat_setsecret_cnt; __u64 stat_generate_public_key_cnt; __u64 stat_compute_shared_secret_cnt; __u64 stat_err_cnt; }; struct crypto_stat_rng { char type[CRYPTO_MAX_NAME]; __u64 stat_generate_cnt; __u64 stat_generate_tlen; __u64 stat_seed_cnt; __u64 stat_err_cnt; }; struct crypto_stat_larval { char type[CRYPTO_MAX_NAME]; }; struct crypto_report_larval { char type[CRYPTO_MAX_NAME]; }; struct crypto_report_hash { char type[CRYPTO_MAX_NAME]; unsigned int blocksize; unsigned int digestsize; }; struct crypto_report_cipher { char type[CRYPTO_MAX_NAME]; unsigned int blocksize; unsigned int min_keysize; unsigned int max_keysize; }; struct crypto_report_blkcipher { char type[CRYPTO_MAX_NAME]; char geniv[CRYPTO_MAX_NAME]; unsigned int blocksize; unsigned int min_keysize; unsigned int max_keysize; unsigned int ivsize; }; struct crypto_report_aead { char type[CRYPTO_MAX_NAME]; char geniv[CRYPTO_MAX_NAME]; unsigned int blocksize; unsigned int maxauthsize; unsigned int ivsize; }; struct crypto_report_comp { char type[CRYPTO_MAX_NAME]; }; struct crypto_report_rng { char type[CRYPTO_MAX_NAME]; unsigned int seedsize; }; struct crypto_report_akcipher { char type[CRYPTO_MAX_NAME]; }; struct crypto_report_kpp { char type[CRYPTO_MAX_NAME]; }; struct crypto_report_acomp { char type[CRYPTO_MAX_NAME]; }; #define CRYPTO_REPORT_MAXSIZE (sizeof(struct crypto_user_alg) + \ sizeof(struct crypto_report_blkcipher)) #endif /* _UAPI_LINUX_CRYPTOUSER_H */
CSE3320/kernel-code
linux-5.8/include/uapi/linux/cryptouser.h
C
gpl-2.0
5,336
*> \brief <b> DGGSVD computes the singular value decomposition (SVD) for OTHER matrices</b> * * =========== DOCUMENTATION =========== * * Online html documentation available at * http://www.netlib.org/lapack/explore-html/ * *> \htmlonly *> Download DGGSVD + dependencies *> <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/dggsvd.f"> *> [TGZ]</a> *> <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/dggsvd.f"> *> [ZIP]</a> *> <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/dggsvd.f"> *> [TXT]</a> *> \endhtmlonly * * Definition: * =========== * * SUBROUTINE DGGSVD( JOBU, JOBV, JOBQ, M, N, P, K, L, A, LDA, B, * LDB, ALPHA, BETA, U, LDU, V, LDV, Q, LDQ, WORK, * IWORK, INFO ) * * .. Scalar Arguments .. * CHARACTER JOBQ, JOBU, JOBV * INTEGER INFO, K, L, LDA, LDB, LDQ, LDU, LDV, M, N, P * .. * .. Array Arguments .. * INTEGER IWORK( * ) * DOUBLE PRECISION A( LDA, * ), ALPHA( * ), B( LDB, * ), * $ BETA( * ), Q( LDQ, * ), U( LDU, * ), * $ V( LDV, * ), WORK( * ) * .. * * *> \par Purpose: * ============= *> *> \verbatim *> *> DGGSVD computes the generalized singular value decomposition (GSVD) *> of an M-by-N real matrix A and P-by-N real matrix B: *> *> U**T*A*Q = D1*( 0 R ), V**T*B*Q = D2*( 0 R ) *> *> where U, V and Q are orthogonal matrices. *> Let K+L = the effective numerical rank of the matrix (A**T,B**T)**T, *> then R is a K+L-by-K+L nonsingular upper triangular matrix, D1 and *> D2 are M-by-(K+L) and P-by-(K+L) "diagonal" matrices and of the *> following structures, respectively: *> *> If M-K-L >= 0, *> *> K L *> D1 = K ( I 0 ) *> L ( 0 C ) *> M-K-L ( 0 0 ) *> *> K L *> D2 = L ( 0 S ) *> P-L ( 0 0 ) *> *> N-K-L K L *> ( 0 R ) = K ( 0 R11 R12 ) *> L ( 0 0 R22 ) *> *> where *> *> C = diag( ALPHA(K+1), ... , ALPHA(K+L) ), *> S = diag( BETA(K+1), ... , BETA(K+L) ), *> C**2 + S**2 = I. *> *> R is stored in A(1:K+L,N-K-L+1:N) on exit. *> *> If M-K-L < 0, *> *> K M-K K+L-M *> D1 = K ( I 0 0 ) *> M-K ( 0 C 0 ) *> *> K M-K K+L-M *> D2 = M-K ( 0 S 0 ) *> K+L-M ( 0 0 I ) *> P-L ( 0 0 0 ) *> *> N-K-L K M-K K+L-M *> ( 0 R ) = K ( 0 R11 R12 R13 ) *> M-K ( 0 0 R22 R23 ) *> K+L-M ( 0 0 0 R33 ) *> *> where *> *> C = diag( ALPHA(K+1), ... , ALPHA(M) ), *> S = diag( BETA(K+1), ... , BETA(M) ), *> C**2 + S**2 = I. *> *> (R11 R12 R13 ) is stored in A(1:M, N-K-L+1:N), and R33 is stored *> ( 0 R22 R23 ) *> in B(M-K+1:L,N+M-K-L+1:N) on exit. *> *> The routine computes C, S, R, and optionally the orthogonal *> transformation matrices U, V and Q. *> *> In particular, if B is an N-by-N nonsingular matrix, then the GSVD of *> A and B implicitly gives the SVD of A*inv(B): *> A*inv(B) = U*(D1*inv(D2))*V**T. *> If ( A**T,B**T)**T has orthonormal columns, then the GSVD of A and B is *> also equal to the CS decomposition of A and B. Furthermore, the GSVD *> can be used to derive the solution of the eigenvalue problem: *> A**T*A x = lambda* B**T*B x. *> In some literature, the GSVD of A and B is presented in the form *> U**T*A*X = ( 0 D1 ), V**T*B*X = ( 0 D2 ) *> where U and V are orthogonal and X is nonsingular, D1 and D2 are *> ``diagonal''. The former GSVD form can be converted to the latter *> form by taking the nonsingular matrix X as *> *> X = Q*( I 0 ) *> ( 0 inv(R) ). *> \endverbatim * * Arguments: * ========== * *> \param[in] JOBU *> \verbatim *> JOBU is CHARACTER*1 *> = 'U': Orthogonal matrix U is computed; *> = 'N': U is not computed. *> \endverbatim *> *> \param[in] JOBV *> \verbatim *> JOBV is CHARACTER*1 *> = 'V': Orthogonal matrix V is computed; *> = 'N': V is not computed. *> \endverbatim *> *> \param[in] JOBQ *> \verbatim *> JOBQ is CHARACTER*1 *> = 'Q': Orthogonal matrix Q is computed; *> = 'N': Q is not computed. *> \endverbatim *> *> \param[in] M *> \verbatim *> M is INTEGER *> The number of rows of the matrix A. M >= 0. *> \endverbatim *> *> \param[in] N *> \verbatim *> N is INTEGER *> The number of columns of the matrices A and B. N >= 0. *> \endverbatim *> *> \param[in] P *> \verbatim *> P is INTEGER *> The number of rows of the matrix B. P >= 0. *> \endverbatim *> *> \param[out] K *> \verbatim *> K is INTEGER *> \endverbatim *> *> \param[out] L *> \verbatim *> L is INTEGER *> *> On exit, K and L specify the dimension of the subblocks *> described in Purpose. *> K + L = effective numerical rank of (A**T,B**T)**T. *> \endverbatim *> *> \param[in,out] A *> \verbatim *> A is DOUBLE PRECISION array, dimension (LDA,N) *> On entry, the M-by-N matrix A. *> On exit, A contains the triangular matrix R, or part of R. *> See Purpose for details. *> \endverbatim *> *> \param[in] LDA *> \verbatim *> LDA is INTEGER *> The leading dimension of the array A. LDA >= max(1,M). *> \endverbatim *> *> \param[in,out] B *> \verbatim *> B is DOUBLE PRECISION array, dimension (LDB,N) *> On entry, the P-by-N matrix B. *> On exit, B contains the triangular matrix R if M-K-L < 0. *> See Purpose for details. *> \endverbatim *> *> \param[in] LDB *> \verbatim *> LDB is INTEGER *> The leading dimension of the array B. LDB >= max(1,P). *> \endverbatim *> *> \param[out] ALPHA *> \verbatim *> ALPHA is DOUBLE PRECISION array, dimension (N) *> \endverbatim *> *> \param[out] BETA *> \verbatim *> BETA is DOUBLE PRECISION array, dimension (N) *> *> On exit, ALPHA and BETA contain the generalized singular *> value pairs of A and B; *> ALPHA(1:K) = 1, *> BETA(1:K) = 0, *> and if M-K-L >= 0, *> ALPHA(K+1:K+L) = C, *> BETA(K+1:K+L) = S, *> or if M-K-L < 0, *> ALPHA(K+1:M)=C, ALPHA(M+1:K+L)=0 *> BETA(K+1:M) =S, BETA(M+1:K+L) =1 *> and *> ALPHA(K+L+1:N) = 0 *> BETA(K+L+1:N) = 0 *> \endverbatim *> *> \param[out] U *> \verbatim *> U is DOUBLE PRECISION array, dimension (LDU,M) *> If JOBU = 'U', U contains the M-by-M orthogonal matrix U. *> If JOBU = 'N', U is not referenced. *> \endverbatim *> *> \param[in] LDU *> \verbatim *> LDU is INTEGER *> The leading dimension of the array U. LDU >= max(1,M) if *> JOBU = 'U'; LDU >= 1 otherwise. *> \endverbatim *> *> \param[out] V *> \verbatim *> V is DOUBLE PRECISION array, dimension (LDV,P) *> If JOBV = 'V', V contains the P-by-P orthogonal matrix V. *> If JOBV = 'N', V is not referenced. *> \endverbatim *> *> \param[in] LDV *> \verbatim *> LDV is INTEGER *> The leading dimension of the array V. LDV >= max(1,P) if *> JOBV = 'V'; LDV >= 1 otherwise. *> \endverbatim *> *> \param[out] Q *> \verbatim *> Q is DOUBLE PRECISION array, dimension (LDQ,N) *> If JOBQ = 'Q', Q contains the N-by-N orthogonal matrix Q. *> If JOBQ = 'N', Q is not referenced. *> \endverbatim *> *> \param[in] LDQ *> \verbatim *> LDQ is INTEGER *> The leading dimension of the array Q. LDQ >= max(1,N) if *> JOBQ = 'Q'; LDQ >= 1 otherwise. *> \endverbatim *> *> \param[out] WORK *> \verbatim *> WORK is DOUBLE PRECISION array, *> dimension (max(3*N,M,P)+N) *> \endverbatim *> *> \param[out] IWORK *> \verbatim *> IWORK is INTEGER array, dimension (N) *> On exit, IWORK stores the sorting information. More *> precisely, the following loop will sort ALPHA *> for I = K+1, min(M,K+L) *> swap ALPHA(I) and ALPHA(IWORK(I)) *> endfor *> such that ALPHA(1) >= ALPHA(2) >= ... >= ALPHA(N). *> \endverbatim *> *> \param[out] INFO *> \verbatim *> INFO is INTEGER *> = 0: successful exit *> < 0: if INFO = -i, the i-th argument had an illegal value. *> > 0: if INFO = 1, the Jacobi-type procedure failed to *> converge. For further details, see subroutine DTGSJA. *> \endverbatim * *> \par Internal Parameters: * ========================= *> *> \verbatim *> TOLA DOUBLE PRECISION *> TOLB DOUBLE PRECISION *> TOLA and TOLB are the thresholds to determine the effective *> rank of (A',B')**T. Generally, they are set to *> TOLA = MAX(M,N)*norm(A)*MAZHEPS, *> TOLB = MAX(P,N)*norm(B)*MAZHEPS. *> The size of TOLA and TOLB may affect the size of backward *> errors of the decomposition. *> \endverbatim * * Authors: * ======== * *> \author Univ. of Tennessee *> \author Univ. of California Berkeley *> \author Univ. of Colorado Denver *> \author NAG Ltd. * *> \date November 2011 * *> \ingroup doubleOTHERsing * *> \par Contributors: * ================== *> *> Ming Gu and Huan Ren, Computer Science Division, University of *> California at Berkeley, USA *> * ===================================================================== SUBROUTINE DGGSVD( JOBU, JOBV, JOBQ, M, N, P, K, L, A, LDA, B, $ LDB, ALPHA, BETA, U, LDU, V, LDV, Q, LDQ, WORK, $ IWORK, INFO ) * * -- LAPACK driver routine (version 3.4.0) -- * -- LAPACK is a software package provided by Univ. of Tennessee, -- * -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- * November 2011 * * .. Scalar Arguments .. CHARACTER JOBQ, JOBU, JOBV INTEGER INFO, K, L, LDA, LDB, LDQ, LDU, LDV, M, N, P * .. * .. Array Arguments .. INTEGER IWORK( * ) DOUBLE PRECISION A( LDA, * ), ALPHA( * ), B( LDB, * ), $ BETA( * ), Q( LDQ, * ), U( LDU, * ), $ V( LDV, * ), WORK( * ) * .. * * ===================================================================== * * .. Local Scalars .. LOGICAL WANTQ, WANTU, WANTV INTEGER I, IBND, ISUB, J, NCYCLE DOUBLE PRECISION ANORM, BNORM, SMAX, TEMP, TOLA, TOLB, ULP, UNFL * .. * .. External Functions .. LOGICAL LSAME DOUBLE PRECISION DLAMCH, DLANGE EXTERNAL LSAME, DLAMCH, DLANGE * .. * .. External Subroutines .. EXTERNAL DCOPY, DGGSVP, DTGSJA, XERBLA * .. * .. Intrinsic Functions .. INTRINSIC MAX, MIN * .. * .. Executable Statements .. * * Test the input parameters * WANTU = LSAME( JOBU, 'U' ) WANTV = LSAME( JOBV, 'V' ) WANTQ = LSAME( JOBQ, 'Q' ) * INFO = 0 IF( .NOT.( WANTU .OR. LSAME( JOBU, 'N' ) ) ) THEN INFO = -1 ELSE IF( .NOT.( WANTV .OR. LSAME( JOBV, 'N' ) ) ) THEN INFO = -2 ELSE IF( .NOT.( WANTQ .OR. LSAME( JOBQ, 'N' ) ) ) THEN INFO = -3 ELSE IF( M.LT.0 ) THEN INFO = -4 ELSE IF( N.LT.0 ) THEN INFO = -5 ELSE IF( P.LT.0 ) THEN INFO = -6 ELSE IF( LDA.LT.MAX( 1, M ) ) THEN INFO = -10 ELSE IF( LDB.LT.MAX( 1, P ) ) THEN INFO = -12 ELSE IF( LDU.LT.1 .OR. ( WANTU .AND. LDU.LT.M ) ) THEN INFO = -16 ELSE IF( LDV.LT.1 .OR. ( WANTV .AND. LDV.LT.P ) ) THEN INFO = -18 ELSE IF( LDQ.LT.1 .OR. ( WANTQ .AND. LDQ.LT.N ) ) THEN INFO = -20 END IF IF( INFO.NE.0 ) THEN CALL XERBLA( 'DGGSVD', -INFO ) RETURN END IF * * Compute the Frobenius norm of matrices A and B * ANORM = DLANGE( '1', M, N, A, LDA, WORK ) BNORM = DLANGE( '1', P, N, B, LDB, WORK ) * * Get machine precision and set up threshold for determining * the effective numerical rank of the matrices A and B. * ULP = DLAMCH( 'Precision' ) UNFL = DLAMCH( 'Safe Minimum' ) TOLA = MAX( M, N )*MAX( ANORM, UNFL )*ULP TOLB = MAX( P, N )*MAX( BNORM, UNFL )*ULP * * Preprocessing * CALL DGGSVP( JOBU, JOBV, JOBQ, M, P, N, A, LDA, B, LDB, TOLA, $ TOLB, K, L, U, LDU, V, LDV, Q, LDQ, IWORK, WORK, $ WORK( N+1 ), INFO ) * * Compute the GSVD of two upper "triangular" matrices * CALL DTGSJA( JOBU, JOBV, JOBQ, M, P, N, K, L, A, LDA, B, LDB, $ TOLA, TOLB, ALPHA, BETA, U, LDU, V, LDV, Q, LDQ, $ WORK, NCYCLE, INFO ) * * Sort the singular values and store the pivot indices in IWORK * Copy ALPHA to WORK, then sort ALPHA in WORK * CALL DCOPY( N, ALPHA, 1, WORK, 1 ) IBND = MIN( L, M-K ) DO 20 I = 1, IBND * * Scan for largest ALPHA(K+I) * ISUB = I SMAX = WORK( K+I ) DO 10 J = I + 1, IBND TEMP = WORK( K+J ) IF( TEMP.GT.SMAX ) THEN ISUB = J SMAX = TEMP END IF 10 CONTINUE IF( ISUB.NE.I ) THEN WORK( K+ISUB ) = WORK( K+I ) WORK( K+I ) = SMAX IWORK( K+I ) = K + ISUB ELSE IWORK( K+I ) = K + I END IF 20 CONTINUE * RETURN * * End of DGGSVD * END
LighthouseHPC/lighthouse
src/Dlighthouse/media/Doxygen/lapack/dggsvd.f
FORTRAN
mit
13,994
import * as React from "react"; import { channel, ContextWithTheme, Theme, themeListener, ThemeProvider, withTheme } from "theming"; // Typings currently accept non-plain-objects while they get rejected at runtime. // There exists currently no typing for plain objects. const runtimeErrorTheme: Theme = []; const customTheme = { color: { primary: "red", secondary: "blue" } }; type CustomTheme = typeof customTheme; interface DemoBoxProps { text: string; theme: CustomTheme; } const DemoBox = ({ text, theme }: DemoBoxProps) => { return <div style={{ color: theme.color.primary }}>{text}</div>; }; const ThemedDemoBox = withTheme(DemoBox); const renderDemoBox = () => <ThemedDemoBox text="Hello, World!" />; const App = () => { return ( <ThemeProvider theme={customTheme}> <ThemedDemoBox text="Theme provided" /> </ThemeProvider> ); }; const AugmentedApp = () => { return ( <ThemeProvider theme={customTheme}> <ThemeProvider theme={outerTheme => ({ ...outerTheme, augmented: true })}> <ThemedDemoBox text="Theme provided" /> </ThemeProvider> </ThemeProvider> ); }; function customWithTheme<P>( // tslint:disable-next-line: no-unnecessary-generics Component: React.ComponentType<P & { theme: object }> ) { return class CustomWithTheme extends React.Component<P, { theme: object }> { static contextTypes = themeListener.contextTypes; context: any; setTheme = (theme: object) => this.setState({ theme }); subscription: number | undefined; constructor(props: P, context: ContextWithTheme<typeof channel>) { super(props, context); this.state = { theme: themeListener.initial(context) }; } componentDidMount() { this.subscription = themeListener.subscribe(this.context, this.setTheme); } componentWillUnmount() { const { subscription } = this; if (subscription != null) { themeListener.unsubscribe(this.context, subscription); } } render() { const { theme } = this.state; return <Component theme={theme} {...this.props} />; } }; }
borisyankov/DefinitelyTyped
types/theming/theming-tests.tsx
TypeScript
mit
2,125
module Fog module Ecloud class Model < Fog::Model attr_accessor :loaded alias_method :loaded?, :loaded def reload instance = super @loaded = true instance end def load_unless_loaded! unless @loaded reload end end end end end
aamin005/Firdowsspace
vendor/bundle/ruby/2.3.0/gems/fog-ecloud-0.3.0/lib/fog/compute/ecloud/models/model.rb
Ruby
mit
325
Meteor.methods({ getStatistics(refresh) { if (!Meteor.userId()) { throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'getStatistics' }); } if (RocketChat.authz.hasPermission(Meteor.userId(), 'view-statistics') !== true) { throw new Meteor.Error('error-not-allowed', 'Not allowed', { method: 'getStatistics' }); } if (refresh) { return RocketChat.statistics.save(); } else { return RocketChat.models.Statistics.findLast(); } } });
pitamar/Rocket.Chat
packages/rocketchat-statistics/server/methods/getStatistics.js
JavaScript
mit
480
<?php /* * This file is part of the Sonata project. * * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * */ namespace Sonata\IntlBundle\Tests\Timezone; use Sonata\IntlBundle\Timezone\LocaleBasedTimezoneDetector; /** * Tests for the LocaleBasedTimezoneDetector. * * @author Alexander <iam.asm89@gmail.com> */ class LocaleBasedTimezoneDetectorTest extends \PHPUnit_Framework_TestCase { public function testDetectsTimezoneForLocale() { $localeDetector = $this->getMock('Sonata\IntlBundle\Locale\LocaleDetectorInterface'); $localeDetector ->expects($this->any()) ->method('getLocale') ->will($this->returnValue('fr')) ; $timezoneDetector = new LocaleBasedTimezoneDetector($localeDetector, array('fr' => 'Europe/Paris')); $this->assertEquals('Europe/Paris', $timezoneDetector->getTimezone()); } public function testTimezoneNotDetected() { $localeDetector = $this->getMock('Sonata\IntlBundle\Locale\LocaleDetectorInterface'); $localeDetector ->expects($this->any()) ->method('getLocale') ->will($this->returnValue('de')) ; $timezoneDetector = new LocaleBasedTimezoneDetector($localeDetector, array('fr' => 'Europe/Paris')); $this->assertEquals(null, $timezoneDetector->getTimezone()); } }
firestorm23/gyrolab-ste
vendor/sonata-project/intl-bundle/Tests/Timezone/LocaleBasedTimezoneDetectorTest.php
PHP
mit
1,511
#include "pch.h" using namespace concurrency; using namespace Microsoft::WRL; using namespace Platform; using namespace Windows::Foundation; using namespace Windows::Devices::AllJoyn; using namespace org::alljoyn::ControlPanel; std::map<alljoyn_busobject, WeakReference*> PropertyProducer::SourceObjects; std::map<alljoyn_interfacedescription, WeakReference*> PropertyProducer::SourceInterfaces; PropertyProducer::PropertyProducer(AllJoynBusAttachment^ busAttachment) : m_busAttachment(busAttachment), m_sessionListener(nullptr), m_busObject(nullptr), m_sessionPort(0), m_sessionId(0) { m_weak = new WeakReference(this); ServiceObjectPath = ref new String(L"/Service"); m_signals = ref new PropertySignals(); m_busAttachmentStateChangedToken.Value = 0; } PropertyProducer::~PropertyProducer() { UnregisterFromBus(); delete m_weak; } void PropertyProducer::UnregisterFromBus() { if ((nullptr != m_busAttachment) && (0 != m_busAttachmentStateChangedToken.Value)) { m_busAttachment->StateChanged -= m_busAttachmentStateChangedToken; m_busAttachmentStateChangedToken.Value = 0; } if (nullptr != SessionPortListener) { alljoyn_busattachment_unbindsessionport(AllJoynHelpers::GetInternalBusAttachment(m_busAttachment), m_sessionPort); alljoyn_sessionportlistener_destroy(SessionPortListener); SessionPortListener = nullptr; } if (nullptr != BusObject) { alljoyn_busattachment_unregisterbusobject(AllJoynHelpers::GetInternalBusAttachment(m_busAttachment), BusObject); alljoyn_busobject_destroy(BusObject); BusObject = nullptr; } if (nullptr != SessionListener) { alljoyn_sessionlistener_destroy(SessionListener); SessionListener = nullptr; } } bool PropertyProducer::OnAcceptSessionJoiner(_In_ alljoyn_sessionport sessionPort, _In_ PCSTR joiner, _In_ const alljoyn_sessionopts opts) { UNREFERENCED_PARAMETER(sessionPort); UNREFERENCED_PARAMETER(joiner); UNREFERENCED_PARAMETER(opts); return true; } void PropertyProducer::OnSessionJoined(_In_ alljoyn_sessionport sessionPort, _In_ alljoyn_sessionid id, _In_ PCSTR joiner) { UNREFERENCED_PARAMETER(joiner); // We initialize the Signals object after the session has been joined, because it needs // the session id. m_signals->Initialize(BusObject, id); m_sessionPort = sessionPort; m_sessionId = id; alljoyn_sessionlistener_callbacks callbacks = { AllJoynHelpers::SessionLostHandler<PropertyProducer>, AllJoynHelpers::SessionMemberAddedHandler<PropertyProducer>, AllJoynHelpers::SessionMemberRemovedHandler<PropertyProducer> }; SessionListener = alljoyn_sessionlistener_create(&callbacks, m_weak); alljoyn_busattachment_setsessionlistener(AllJoynHelpers::GetInternalBusAttachment(m_busAttachment), id, SessionListener); } void PropertyProducer::OnSessionLost(_In_ alljoyn_sessionid sessionId, _In_ alljoyn_sessionlostreason reason) { if (sessionId == m_sessionId) { AllJoynSessionLostEventArgs^ args = ref new AllJoynSessionLostEventArgs(static_cast<AllJoynSessionLostReason>(reason)); SessionLost(this, args); } } void PropertyProducer::OnSessionMemberAdded(_In_ alljoyn_sessionid sessionId, _In_ PCSTR uniqueName) { if (sessionId == m_sessionId) { auto args = ref new AllJoynSessionMemberAddedEventArgs(AllJoynHelpers::MultibyteToPlatformString(uniqueName)); SessionMemberAdded(this, args); } } void PropertyProducer::OnSessionMemberRemoved(_In_ alljoyn_sessionid sessionId, _In_ PCSTR uniqueName) { if (sessionId == m_sessionId) { auto args = ref new AllJoynSessionMemberRemovedEventArgs(AllJoynHelpers::MultibyteToPlatformString(uniqueName)); SessionMemberRemoved(this, args); } } void PropertyProducer::BusAttachmentStateChanged(_In_ AllJoynBusAttachment^ sender, _In_ AllJoynBusAttachmentStateChangedEventArgs^ args) { if (args->State == AllJoynBusAttachmentState::Connected) { QStatus result = AllJoynHelpers::CreateProducerSession<PropertyProducer>(m_busAttachment, m_weak); if (ER_OK != result) { StopInternal(result); return; } } else if (args->State == AllJoynBusAttachmentState::Disconnected) { StopInternal(ER_BUS_STOPPING); } } void PropertyProducer::CallMetadataChangedSignalHandler(_In_ const alljoyn_interfacedescription_member* member, _In_ alljoyn_message message) { auto source = SourceInterfaces.find(member->iface); if (source == SourceInterfaces.end()) { return; } auto producer = source->second->Resolve<PropertyProducer>(); if (producer->Signals != nullptr) { auto callInfo = ref new AllJoynMessageInfo(AllJoynHelpers::MultibyteToPlatformString(alljoyn_message_getsender(message))); auto eventArgs = ref new PropertyMetadataChangedReceivedEventArgs(); eventArgs->MessageInfo = callInfo; producer->Signals->CallMetadataChangedReceived(producer->Signals, eventArgs); } } void PropertyProducer::CallValueChangedSignalHandler(_In_ const alljoyn_interfacedescription_member* member, _In_ alljoyn_message message) { auto source = SourceInterfaces.find(member->iface); if (source == SourceInterfaces.end()) { return; } auto producer = source->second->Resolve<PropertyProducer>(); if (producer->Signals != nullptr) { auto callInfo = ref new AllJoynMessageInfo(AllJoynHelpers::MultibyteToPlatformString(alljoyn_message_getsender(message))); auto eventArgs = ref new PropertyValueChangedReceivedEventArgs(); eventArgs->MessageInfo = callInfo; producer->Signals->CallValueChangedReceived(producer->Signals, eventArgs); } } QStatus PropertyProducer::AddMethodHandler(_In_ alljoyn_interfacedescription interfaceDescription, _In_ PCSTR methodName, _In_ alljoyn_messagereceiver_methodhandler_ptr handler) { alljoyn_interfacedescription_member member; if (!alljoyn_interfacedescription_getmember(interfaceDescription, methodName, &member)) { return ER_BUS_INTERFACE_NO_SUCH_MEMBER; } return alljoyn_busobject_addmethodhandler( m_busObject, member, handler, m_weak); } QStatus PropertyProducer::AddSignalHandler(_In_ alljoyn_busattachment busAttachment, _In_ alljoyn_interfacedescription interfaceDescription, _In_ PCSTR methodName, _In_ alljoyn_messagereceiver_signalhandler_ptr handler) { alljoyn_interfacedescription_member member; if (!alljoyn_interfacedescription_getmember(interfaceDescription, methodName, &member)) { return ER_BUS_INTERFACE_NO_SUCH_MEMBER; } return alljoyn_busattachment_registersignalhandler(busAttachment, handler, member, NULL); } QStatus PropertyProducer::OnPropertyGet(_In_ PCSTR interfaceName, _In_ PCSTR propertyName, _Inout_ alljoyn_msgarg value) { UNREFERENCED_PARAMETER(interfaceName); if (0 == strcmp(propertyName, "Version")) { auto task = create_task(Service->GetVersionAsync(nullptr)); auto result = task.get(); if (AllJoynStatus::Ok != result->Status) { return static_cast<QStatus>(result->Status); } return static_cast<QStatus>(TypeConversionHelpers::SetAllJoynMessageArg(value, "q", result->Version)); } if (0 == strcmp(propertyName, "States")) { auto task = create_task(Service->GetStatesAsync(nullptr)); auto result = task.get(); if (AllJoynStatus::Ok != result->Status) { return static_cast<QStatus>(result->Status); } return static_cast<QStatus>(TypeConversionHelpers::SetAllJoynMessageArg(value, "u", result->States)); } if (0 == strcmp(propertyName, "OptParams")) { auto task = create_task(Service->GetOptParamsAsync(nullptr)); auto result = task.get(); if (AllJoynStatus::Ok != result->Status) { return static_cast<QStatus>(result->Status); } return static_cast<QStatus>(TypeConversionHelpers::SetAllJoynMessageArg(value, "a{qv}", result->OptParams)); } if (0 == strcmp(propertyName, "Value")) { auto task = create_task(Service->GetValueAsync(nullptr)); auto result = task.get(); if (AllJoynStatus::Ok != result->Status) { return static_cast<QStatus>(result->Status); } return static_cast<QStatus>(TypeConversionHelpers::SetAllJoynMessageArg(value, "v", result->Value)); } return ER_BUS_NO_SUCH_PROPERTY; } QStatus PropertyProducer::OnPropertySet(_In_ PCSTR interfaceName, _In_ PCSTR propertyName, _In_ alljoyn_msgarg value) { UNREFERENCED_PARAMETER(interfaceName); if (0 == strcmp(propertyName, "Value")) { Platform::Object^ argument; TypeConversionHelpers::GetAllJoynMessageArg(value, "v", &argument); auto task = create_task(Service->SetValueAsync(nullptr, argument)); return static_cast<QStatus>(task.get()); } return ER_BUS_NO_SUCH_PROPERTY; } void PropertyProducer::Start() { if (nullptr == m_busAttachment) { StopInternal(ER_FAIL); return; } QStatus result = AllJoynHelpers::CreateInterfaces(m_busAttachment, c_PropertyIntrospectionXml); if (result != ER_OK) { StopInternal(result); return; } result = AllJoynHelpers::CreateBusObject<PropertyProducer>(m_weak); if (result != ER_OK) { StopInternal(result); return; } alljoyn_interfacedescription interfaceDescription = alljoyn_busattachment_getinterface(AllJoynHelpers::GetInternalBusAttachment(m_busAttachment), "org.alljoyn.ControlPanel.Property"); if (interfaceDescription == nullptr) { StopInternal(ER_FAIL); return; } alljoyn_busobject_addinterface_announced(BusObject, interfaceDescription); result = AddSignalHandler( AllJoynHelpers::GetInternalBusAttachment(m_busAttachment), interfaceDescription, "MetadataChanged", [](const alljoyn_interfacedescription_member* member, PCSTR srcPath, alljoyn_message message) { UNREFERENCED_PARAMETER(srcPath); CallMetadataChangedSignalHandler(member, message); }); if (result != ER_OK) { StopInternal(result); return; } result = AddSignalHandler( AllJoynHelpers::GetInternalBusAttachment(m_busAttachment), interfaceDescription, "ValueChanged", [](const alljoyn_interfacedescription_member* member, PCSTR srcPath, alljoyn_message message) { UNREFERENCED_PARAMETER(srcPath); CallValueChangedSignalHandler(member, message); }); if (result != ER_OK) { StopInternal(result); return; } SourceObjects[m_busObject] = m_weak; SourceInterfaces[interfaceDescription] = m_weak; result = alljoyn_busattachment_registerbusobject(AllJoynHelpers::GetInternalBusAttachment(m_busAttachment), BusObject); if (result != ER_OK) { StopInternal(result); return; } m_busAttachmentStateChangedToken = m_busAttachment->StateChanged += ref new TypedEventHandler<AllJoynBusAttachment^,AllJoynBusAttachmentStateChangedEventArgs^>(this, &PropertyProducer::BusAttachmentStateChanged); m_busAttachment->Connect(); } void PropertyProducer::Stop() { StopInternal(AllJoynStatus::Ok); } void PropertyProducer::StopInternal(int32 status) { UnregisterFromBus(); Stopped(this, ref new AllJoynProducerStoppedEventArgs(status)); } int32 PropertyProducer::RemoveMemberFromSession(_In_ String^ uniqueName) { return alljoyn_busattachment_removesessionmember( AllJoynHelpers::GetInternalBusAttachment(m_busAttachment), m_sessionId, AllJoynHelpers::PlatformToMultibyteString(uniqueName).data()); } PCSTR org::alljoyn::ControlPanel::c_PropertyIntrospectionXml = "<interface name=\"org.alljoyn.ControlPanel.Property\">" " <property name=\"Version\" type=\"q\" access=\"read\" />" " <property name=\"States\" type=\"u\" access=\"read\" />" " <property name=\"OptParams\" type=\"a{qv}\" access=\"read\" />" " <property name=\"Value\" type=\"v\" access=\"readwrite\" />" " <signal name=\"MetadataChanged\" />" " <signal name=\"ValueChanged\" type=\"v\" />" "</interface>" ;
tjaffri/msiot-samples
AllJoyn/Samples/MyLivingRoom/Models/org.alljoyn.ControlPanel/PropertyProducer.cpp
C++
mit
12,471
$(document).ready(() => { const config: DataTables.Settings = { // FixedColumns extension options fixedColumns: { heightMatch: 'semiauto', leftColumns: 2, rightColumns: 1 } }; });
dsebastien/DefinitelyTyped
types/datatables.net-fixedcolumns/datatables.net-fixedcolumns-tests.ts
TypeScript
mit
248
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Reflection.Runtime.General; namespace System.Reflection.Runtime.BindingFlagSupport { internal static class Shared { // // This is similar to FilterApplyMethodBase from CoreClr with some important differences: // // - Does *not* filter on Public|NonPublic|Instance|Static|FlatternHierarchy. Caller is expected to have done that. // // - ArgumentTypes cannot be null. // // Used by Type.GetMethodImpl(), Type.GetConstructorImpl(), Type.InvokeMember() and Activator.CreateInstance(). Does some // preliminary weeding out of candidate methods based on the supplied calling convention and parameter list lengths. // // Candidates must pass this screen before we involve the binder. // public static bool QualifiesBasedOnParameterCount(this MethodBase methodBase, BindingFlags bindingFlags, CallingConventions callConv, Type[] argumentTypes) { Debug.Assert(methodBase != null); Debug.Assert(argumentTypes != null); #if DEBUG bindingFlags &= ~(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly | BindingFlags.FlattenHierarchy | BindingFlags.IgnoreCase); #endif #region Check CallingConvention if ((callConv & CallingConventions.Any) == 0) { if ((callConv & CallingConventions.VarArgs) != 0 && (methodBase.CallingConvention & CallingConventions.VarArgs) == 0) return false; if ((callConv & CallingConventions.Standard) != 0 && (methodBase.CallingConvention & CallingConventions.Standard) == 0) return false; } #endregion #region ArgumentTypes ParameterInfo[] parameterInfos = methodBase.GetParametersNoCopy(); if (argumentTypes.Length != parameterInfos.Length) { #region Invoke Member, Get\Set & Create Instance specific case // If the number of supplied arguments differs than the number in the signature AND // we are not filtering for a dynamic call -- InvokeMethod or CreateInstance -- filter out the method. if ((bindingFlags & (BindingFlags.InvokeMethod | BindingFlags.CreateInstance | BindingFlags.GetProperty | BindingFlags.SetProperty)) == 0) return false; bool testForParamArray = false; bool excessSuppliedArguments = argumentTypes.Length > parameterInfos.Length; if (excessSuppliedArguments) { // more supplied arguments than parameters, additional arguments could be vararg #region Varargs // If method is not vararg, additional arguments can not be passed as vararg if ((methodBase.CallingConvention & CallingConventions.VarArgs) == 0) { testForParamArray = true; } else { // If Binding flags did not include varargs we would have filtered this vararg method. // This Invariant established during callConv check. Debug.Assert((callConv & CallingConventions.VarArgs) != 0); } #endregion } else {// fewer supplied arguments than parameters, missing arguments could be optional #region OptionalParamBinding if ((bindingFlags & BindingFlags.OptionalParamBinding) == 0) { testForParamArray = true; } else { // From our existing code, our policy here is that if a parameterInfo // is optional then all subsequent parameterInfos shall be optional. // Thus, iff the first parameterInfo is not optional then this MethodInfo is no longer a canidate. if (!parameterInfos[argumentTypes.Length].IsOptional) testForParamArray = true; } #endregion } #region ParamArray if (testForParamArray) { if (parameterInfos.Length == 0) return false; // The last argument of the signature could be a param array. bool shortByMoreThanOneSuppliedArgument = argumentTypes.Length < parameterInfos.Length - 1; if (shortByMoreThanOneSuppliedArgument) return false; ParameterInfo lastParameter = parameterInfos[parameterInfos.Length - 1]; if (!lastParameter.ParameterType.IsArray) return false; if (!lastParameter.IsDefined(typeof(ParamArrayAttribute), false)) return false; } #endregion #endregion } else { #region Exact Binding if ((bindingFlags & BindingFlags.ExactBinding) != 0) { // Legacy behavior is to ignore ExactBinding when InvokeMember is specified. // Why filter by InvokeMember? If the answer is we leave this to the binder then why not leave // all the rest of this to the binder too? Further, what other semanitc would the binder // use for BindingFlags.ExactBinding besides this one? Further, why not include CreateInstance // in this if statement? That's just InvokeMethod with a constructor, right? if ((bindingFlags & (BindingFlags.InvokeMethod)) == 0) { for (int i = 0; i < parameterInfos.Length; i++) { // a null argument type implies a null arg which is always a perfect match if ((object)argumentTypes[i] != null && !argumentTypes[i].MatchesParameterTypeExactly(parameterInfos[i])) return false; } } } #endregion } #endregion return true; } // // If member is a virtual member that implicitly overrides a member in a base class, return the overridden member. // Otherwise, return null. // // - MethodImpls ignored. (I didn't say it made sense, this is just how the desktop api we're porting behaves.) // - Implemented interfaces ignores. (I didn't say it made sense, this is just how the desktop api we're porting behaves.) // public static M GetImplicitlyOverriddenBaseClassMember<M>(this M member) where M : MemberInfo { MemberPolicies<M> policies = MemberPolicies<M>.Default; MethodAttributes visibility; bool isStatic; bool isVirtual; bool isNewSlot; policies.GetMemberAttributes(member, out visibility, out isStatic, out isVirtual, out isNewSlot); if (isNewSlot || !isVirtual) { return null; } String name = member.Name; TypeInfo typeInfo = member.DeclaringType.GetTypeInfo(); for (;;) { Type baseType = typeInfo.BaseType; if (baseType == null) { return null; } typeInfo = baseType.GetTypeInfo(); foreach (M candidate in policies.GetDeclaredMembers(typeInfo)) { if (candidate.Name != name) { continue; } MethodAttributes candidateVisibility; bool isCandidateStatic; bool isCandidateVirtual; bool isCandidateNewSlot; policies.GetMemberAttributes(member, out candidateVisibility, out isCandidateStatic, out isCandidateVirtual, out isCandidateNewSlot); if (!isCandidateVirtual) { continue; } if (!policies.ImplicitlyOverrides(candidate, member)) { continue; } return candidate; } } } } }
zenos-os/zenos
vendor/corert/src/System.Private.Reflection.Core/src/System/Reflection/Runtime/BindingFlagSupport/Shared.cs
C#
mit
9,059
/* * ioreq.h: I/O request definitions for device models * Copyright (c) 2004, Intel Corporation. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ #ifndef _IOREQ_H_ #define _IOREQ_H_ #define IOREQ_READ 1 #define IOREQ_WRITE 0 #define STATE_IOREQ_NONE 0 #define STATE_IOREQ_READY 1 #define STATE_IOREQ_INPROCESS 2 #define STATE_IORESP_READY 3 #define IOREQ_TYPE_PIO 0 /* pio */ #define IOREQ_TYPE_COPY 1 /* mmio ops */ #define IOREQ_TYPE_PCI_CONFIG 2 #define IOREQ_TYPE_TIMEOFFSET 7 #define IOREQ_TYPE_INVALIDATE 8 /* mapcache */ /* * VMExit dispatcher should cooperate with instruction decoder to * prepare this structure and notify service OS and DM by sending * virq. * * For I/O type IOREQ_TYPE_PCI_CONFIG, the physical address is formatted * as follows: * * 63....48|47..40|39..35|34..32|31........0 * SEGMENT |BUS |DEV |FN |OFFSET */ struct ioreq { uint64_t addr; /* physical address */ uint64_t data; /* data (or paddr of data) */ uint32_t count; /* for rep prefixes */ uint32_t size; /* size in bytes */ uint32_t vp_eport; /* evtchn for notifications to/from device model */ uint16_t _pad0; uint8_t state:4; uint8_t data_is_ptr:1; /* if 1, data above is the guest paddr * of the real data to use. */ uint8_t dir:1; /* 1=read, 0=write */ uint8_t df:1; uint8_t _pad1:1; uint8_t type; /* I/O type */ }; typedef struct ioreq ioreq_t; struct shared_iopage { struct ioreq vcpu_ioreq[1]; }; typedef struct shared_iopage shared_iopage_t; struct buf_ioreq { uint8_t type; /* I/O type */ uint8_t pad:1; uint8_t dir:1; /* 1=read, 0=write */ uint8_t size:2; /* 0=>1, 1=>2, 2=>4, 3=>8. If 8, use two buf_ioreqs */ uint32_t addr:20;/* physical address */ uint32_t data; /* data */ }; typedef struct buf_ioreq buf_ioreq_t; #define IOREQ_BUFFER_SLOT_NUM 511 /* 8 bytes each, plus 2 4-byte indexes */ struct buffered_iopage { #ifdef __XEN__ union bufioreq_pointers { struct { #endif uint32_t read_pointer; uint32_t write_pointer; #ifdef __XEN__ }; uint64_t full; } ptrs; #endif buf_ioreq_t buf_ioreq[IOREQ_BUFFER_SLOT_NUM]; }; /* NB. Size of this structure must be no greater than one page. */ typedef struct buffered_iopage buffered_iopage_t; /* * ACPI Control/Event register locations. Location is controlled by a * version number in HVM_PARAM_ACPI_IOPORTS_LOCATION. */ /* Version 0 (default): Traditional Xen locations. */ #define ACPI_PM1A_EVT_BLK_ADDRESS_V0 0x1f40 #define ACPI_PM1A_CNT_BLK_ADDRESS_V0 (ACPI_PM1A_EVT_BLK_ADDRESS_V0 + 0x04) #define ACPI_PM_TMR_BLK_ADDRESS_V0 (ACPI_PM1A_EVT_BLK_ADDRESS_V0 + 0x08) #define ACPI_GPE0_BLK_ADDRESS_V0 (ACPI_PM_TMR_BLK_ADDRESS_V0 + 0x20) #define ACPI_GPE0_BLK_LEN_V0 0x08 /* Version 1: Locations preferred by modern Qemu. */ #define ACPI_PM1A_EVT_BLK_ADDRESS_V1 0xb000 #define ACPI_PM1A_CNT_BLK_ADDRESS_V1 (ACPI_PM1A_EVT_BLK_ADDRESS_V1 + 0x04) #define ACPI_PM_TMR_BLK_ADDRESS_V1 (ACPI_PM1A_EVT_BLK_ADDRESS_V1 + 0x08) #define ACPI_GPE0_BLK_ADDRESS_V1 0xafe0 #define ACPI_GPE0_BLK_LEN_V1 0x04 /* Compatibility definitions for the default location (version 0). */ #define ACPI_PM1A_EVT_BLK_ADDRESS ACPI_PM1A_EVT_BLK_ADDRESS_V0 #define ACPI_PM1A_CNT_BLK_ADDRESS ACPI_PM1A_CNT_BLK_ADDRESS_V0 #define ACPI_PM_TMR_BLK_ADDRESS ACPI_PM_TMR_BLK_ADDRESS_V0 #define ACPI_GPE0_BLK_ADDRESS ACPI_GPE0_BLK_ADDRESS_V0 #define ACPI_GPE0_BLK_LEN ACPI_GPE0_BLK_LEN_V0 #endif /* _IOREQ_H_ */ /* * Local variables: * mode: C * c-file-style: "BSD" * c-basic-offset: 4 * tab-width: 4 * indent-tabs-mode: nil * End: */
SunnyRaj/evade-4.6
xen/include/public/hvm/ioreq.h
C
gpl-2.0
4,923
#include "base/arch.h" #if defined(_M_IX86) || defined(_M_X64) #include <emmintrin.h> #include "fast_matrix.h" void fast_matrix_mul_4x4_sse(float *dest, const float *a, const float *b) { int i; __m128 a_col_1 = _mm_loadu_ps(a); __m128 a_col_2 = _mm_loadu_ps(&a[4]); __m128 a_col_3 = _mm_loadu_ps(&a[8]); __m128 a_col_4 = _mm_loadu_ps(&a[12]); for (i = 0; i < 16; i += 4) { __m128 r_col = _mm_mul_ps(a_col_1, _mm_set1_ps(b[i])); r_col = _mm_add_ps(r_col, _mm_mul_ps(a_col_2, _mm_set1_ps(b[i + 1]))); r_col = _mm_add_ps(r_col, _mm_mul_ps(a_col_3, _mm_set1_ps(b[i + 2]))); r_col = _mm_add_ps(r_col, _mm_mul_ps(a_col_4, _mm_set1_ps(b[i + 3]))); _mm_storeu_ps(&dest[i], r_col); } } #endif
libretro/PSP1
native/math/fast/fast_matrix_sse.c
C
gpl-2.0
707
/* * S390 version * * Derived from "include/asm-i386/mmu_context.h" */ #ifndef __S390_MMU_CONTEXT_H #define __S390_MMU_CONTEXT_H #include <asm/pgalloc.h> #include <linux/uaccess.h> #include <linux/mm_types.h> #include <asm/tlbflush.h> #include <asm/ctl_reg.h> static inline int init_new_context(struct task_struct *tsk, struct mm_struct *mm) { spin_lock_init(&mm->context.pgtable_lock); INIT_LIST_HEAD(&mm->context.pgtable_list); spin_lock_init(&mm->context.gmap_lock); INIT_LIST_HEAD(&mm->context.gmap_list); cpumask_clear(&mm->context.cpu_attach_mask); atomic_set(&mm->context.flush_count, 0); mm->context.gmap_asce = 0; mm->context.flush_mm = 0; #ifdef CONFIG_PGSTE mm->context.alloc_pgste = page_table_allocate_pgste; mm->context.has_pgste = 0; mm->context.use_skey = 0; #endif switch (mm->context.asce_limit) { case 1UL << 42: /* * forked 3-level task, fall through to set new asce with new * mm->pgd */ case 0: /* context created by exec, set asce limit to 4TB */ mm->context.asce_limit = STACK_TOP_MAX; mm->context.asce = __pa(mm->pgd) | _ASCE_TABLE_LENGTH | _ASCE_USER_BITS | _ASCE_TYPE_REGION3; break; case 1UL << 53: /* forked 4-level task, set new asce with new mm->pgd */ mm->context.asce = __pa(mm->pgd) | _ASCE_TABLE_LENGTH | _ASCE_USER_BITS | _ASCE_TYPE_REGION2; break; case 1UL << 31: /* forked 2-level compat task, set new asce with new mm->pgd */ mm->context.asce = __pa(mm->pgd) | _ASCE_TABLE_LENGTH | _ASCE_USER_BITS | _ASCE_TYPE_SEGMENT; /* pgd_alloc() did not increase mm->nr_pmds */ mm_inc_nr_pmds(mm); } crst_table_init((unsigned long *) mm->pgd, pgd_entry_type(mm)); return 0; } #define destroy_context(mm) do { } while (0) static inline void set_user_asce(struct mm_struct *mm) { S390_lowcore.user_asce = mm->context.asce; if (current->thread.mm_segment.ar4) __ctl_load(S390_lowcore.user_asce, 7, 7); set_cpu_flag(CIF_ASCE_PRIMARY); } static inline void clear_user_asce(void) { S390_lowcore.user_asce = S390_lowcore.kernel_asce; __ctl_load(S390_lowcore.user_asce, 1, 1); __ctl_load(S390_lowcore.user_asce, 7, 7); } static inline void load_kernel_asce(void) { unsigned long asce; __ctl_store(asce, 1, 1); if (asce != S390_lowcore.kernel_asce) __ctl_load(S390_lowcore.kernel_asce, 1, 1); set_cpu_flag(CIF_ASCE_PRIMARY); } static inline void switch_mm(struct mm_struct *prev, struct mm_struct *next, struct task_struct *tsk) { int cpu = smp_processor_id(); S390_lowcore.user_asce = next->context.asce; if (prev == next) return; cpumask_set_cpu(cpu, &next->context.cpu_attach_mask); cpumask_set_cpu(cpu, mm_cpumask(next)); /* Clear old ASCE by loading the kernel ASCE. */ __ctl_load(S390_lowcore.kernel_asce, 1, 1); __ctl_load(S390_lowcore.kernel_asce, 7, 7); cpumask_clear_cpu(cpu, &prev->context.cpu_attach_mask); } #define finish_arch_post_lock_switch finish_arch_post_lock_switch static inline void finish_arch_post_lock_switch(void) { struct task_struct *tsk = current; struct mm_struct *mm = tsk->mm; load_kernel_asce(); if (mm) { preempt_disable(); while (atomic_read(&mm->context.flush_count)) cpu_relax(); if (mm->context.flush_mm) __tlb_flush_mm(mm); preempt_enable(); } set_fs(current->thread.mm_segment); } #define enter_lazy_tlb(mm,tsk) do { } while (0) #define deactivate_mm(tsk,mm) do { } while (0) static inline void activate_mm(struct mm_struct *prev, struct mm_struct *next) { switch_mm(prev, next, current); set_user_asce(next); } static inline void arch_dup_mmap(struct mm_struct *oldmm, struct mm_struct *mm) { } static inline void arch_exit_mmap(struct mm_struct *mm) { } static inline void arch_unmap(struct mm_struct *mm, struct vm_area_struct *vma, unsigned long start, unsigned long end) { } static inline void arch_bprm_mm_init(struct mm_struct *mm, struct vm_area_struct *vma) { } static inline bool arch_vma_access_permitted(struct vm_area_struct *vma, bool write, bool execute, bool foreign) { /* by default, allow everything */ return true; } static inline bool arch_pte_access_permitted(pte_t pte, bool write) { /* by default, allow everything */ return true; } #endif /* __S390_MMU_CONTEXT_H */
minipli/linux-grsec
arch/s390/include/asm/mmu_context.h
C
gpl-2.0
4,282
#include <xen/types.h> #include <xen/sched.h> #include "mcaction.h" #include "vmce.h" #include "mce.h" static struct mcinfo_recovery * mci_action_add_pageoffline(int bank, struct mc_info *mi, uint64_t mfn, uint32_t status) { struct mcinfo_recovery *rec; if (!mi) return NULL; rec = x86_mcinfo_reserve(mi, sizeof(*rec)); if (!rec) { mi->flags |= MCINFO_FLAGS_UNCOMPLETE; return NULL; } rec->common.type = MC_TYPE_RECOVERY; rec->common.size = sizeof(*rec); rec->mc_bank = bank; rec->action_types = MC_ACTION_PAGE_OFFLINE; rec->action_info.page_retire.mfn = mfn; rec->action_info.page_retire.status = status; return rec; } mce_check_addr_t mc_check_addr = NULL; void mce_register_addrcheck(mce_check_addr_t cbfunc) { mc_check_addr = cbfunc; } void mc_memerr_dhandler(struct mca_binfo *binfo, enum mce_result *result, struct cpu_user_regs *regs) { struct mcinfo_bank *bank = binfo->mib; struct mcinfo_global *global = binfo->mig; struct domain *d; unsigned long mfn, gfn; uint32_t status; int vmce_vcpuid; if (!mc_check_addr(bank->mc_status, bank->mc_misc, MC_ADDR_PHYSICAL)) { dprintk(XENLOG_WARNING, "No physical address provided for memory error\n"); return; } mfn = bank->mc_addr >> PAGE_SHIFT; if (offline_page(mfn, 1, &status)) { dprintk(XENLOG_WARNING, "Failed to offline page %lx for MCE error\n", mfn); return; } mci_action_add_pageoffline(binfo->bank, binfo->mi, mfn, status); /* This is free page */ if (status & PG_OFFLINE_OFFLINED) *result = MCER_RECOVERED; else if (status & PG_OFFLINE_AGAIN) *result = MCER_CONTINUE; else if (status & PG_OFFLINE_PENDING) { /* This page has owner */ if (status & PG_OFFLINE_OWNED) { bank->mc_domid = status >> PG_OFFLINE_OWNER_SHIFT; mce_printk(MCE_QUIET, "MCE: This error page is ownded" " by DOM %d\n", bank->mc_domid); /* XXX: Cannot handle shared pages yet * (this should identify all domains and gfn mapping to * the mfn in question) */ BUG_ON( bank->mc_domid == DOMID_COW ); if ( bank->mc_domid != DOMID_XEN ) { d = get_domain_by_id(bank->mc_domid); ASSERT(d); gfn = get_gpfn_from_mfn((bank->mc_addr) >> PAGE_SHIFT); if ( unmmap_broken_page(d, _mfn(mfn), gfn) ) { printk("Unmap broken memory %lx for DOM%d failed\n", mfn, d->domain_id); goto vmce_failed; } bank->mc_addr = gfn << PAGE_SHIFT | (bank->mc_addr & (PAGE_SIZE -1 )); if ( fill_vmsr_data(bank, d, global->mc_gstatus) == -1 ) { mce_printk(MCE_QUIET, "Fill vMCE# data for DOM%d " "failed\n", bank->mc_domid); goto vmce_failed; } if ( boot_cpu_data.x86_vendor == X86_VENDOR_INTEL ) vmce_vcpuid = VMCE_INJECT_BROADCAST; else vmce_vcpuid = global->mc_vcpuid; /* We will inject vMCE to DOMU*/ if ( inject_vmce(d, vmce_vcpuid) < 0 ) { mce_printk(MCE_QUIET, "inject vMCE to DOM%d" " failed\n", d->domain_id); goto vmce_failed; } /* Impacted domain go on with domain's recovery job * if the domain has its own MCA handler. * For xen, it has contained the error and finished * its own recovery job. */ *result = MCER_RECOVERED; put_domain(d); return; vmce_failed: put_domain(d); domain_crash(d); } } } }
flexiant/xen
xen/arch/x86/cpu/mcheck/mcaction.c
C
gpl-2.0
4,135
/********************************************************************** Audacity: A Digital Audio Editor Internat.h Markus Meyer Dominic Mazzoni (Mac OS X code) **********************************************************************/ #ifndef __AUDACITY_INTERNAT__ #define __AUDACITY_INTERNAT__ #include <wx/arrstr.h> #include <wx/string.h> #include <wx/longlong.h> class Internat { public: /** \brief Initialize internationalisation support. Call this once at * program start. */ static void Init(); /** \brief Get the decimal separator for the current locale. * * Normally, this is a decimal point ('.'), but e.g. Germany uses a * comma (',').*/ static wxChar GetDecimalSeparator(); /** \brief Convert a string to a number. * * This function will accept BOTH point and comma as a decimal separator, * regardless of the current locale. * Returns 'true' on success, and 'false' if an error occurs. */ static bool CompatibleToDouble(const wxString& stringToConvert, double* result); // Function version of above. static double CompatibleToDouble(const wxString& stringToConvert); /** \brief Convert a number to a string, always uses the dot as decimal * separator*/ static wxString ToString(double numberToConvert, int digitsAfterDecimalPoint = -1); /** \brief Convert a number to a string, uses the user's locale's decimal * separator */ static wxString ToDisplayString(double numberToConvert, int digitsAfterDecimalPoint = -1); /** \brief Convert a number to a string while formatting it in bytes, KB, * MB, GB */ static wxString FormatSize(wxLongLong size); static wxString FormatSize(double size); /** \brief Protect against Unicode to multi-byte conversion failures * on Windows */ #if defined(__WXMSW__) static char *VerifyFilename(const wxString &s, bool input = true); #endif /** \brief Check a proposed file name string for illegal characters and * remove them */ static wxString SanitiseFilename(const wxString &name, const wxString &sub); /** \brief Remove accelerator charactors from strings * * Utility function - takes a translatable string to be used as a menu item, * for example _("&Splash...\tAlt+S"), and strips all of the menu * accelerator stuff from it, to make "Splash". That way the same * translatable string can be used both when accelerators are needed and * when they aren't, saving translators effort. */ static wxString StripAccelerators(const wxString& str); private: static wxChar mDecimalSeparator; // stuff for file name sanitisation static wxString forbid; static wxArrayString exclude; static wxCharBuffer mFilename; }; #define _NoAcc(X) Internat::StripAccelerators(_(X)) // Use this macro to wrap all filenames and pathnames that get // passed directly to a system call, like opening a file, creating // a directory, checking to see that a file exists, etc... #if defined(__WXMSW__) // Note, on Windows we don't define an OSFILENAME() to prevent accidental use. // See VerifyFilename() for an explanation. #define OSINPUT(X) Internat::VerifyFilename(X, true) #define OSOUTPUT(X) Internat::VerifyFilename(X, false) #elif defined(__WXMAC__) #define OSFILENAME(X) ((char *) (const char *)(X).fn_str()) #define OSINPUT(X) OSFILENAME(X) #define OSOUTPUT(X) OSFILENAME(X) #else #define OSFILENAME(X) ((char *) (const char *)(X).mb_str()) #define OSINPUT(X) OSFILENAME(X) #define OSOUTPUT(X) OSFILENAME(X) #endif // Convert C strings to wxString #define UTF8CTOWX(X) wxString((X), wxConvUTF8) #define LAT1CTOWX(X) wxString((X), wxConvISO8859_1) #endif
Marcusz97/CILP_Facilitatore_Audacity
src/Internat.h
C
gpl-2.0
3,707
/* eggaccelerators.h * Copyright (C) 2002 Red Hat, Inc. * Developed by Havoc Pennington * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #ifndef __EGG_ACCELERATORS_H__ #define __EGG_ACCELERATORS_H__ #include <gtk/gtkaccelgroup.h> #include <gdk/gdk.h> G_BEGIN_DECLS /* Where a value is also in GdkModifierType we coincide, * otherwise we don't overlap. */ typedef enum { EGG_VIRTUAL_SHIFT_MASK = 1 << 0, EGG_VIRTUAL_LOCK_MASK = 1 << 1, EGG_VIRTUAL_CONTROL_MASK = 1 << 2, EGG_VIRTUAL_ALT_MASK = 1 << 3, /* fixed as Mod1 */ EGG_VIRTUAL_MOD2_MASK = 1 << 4, EGG_VIRTUAL_MOD3_MASK = 1 << 5, EGG_VIRTUAL_MOD4_MASK = 1 << 6, EGG_VIRTUAL_MOD5_MASK = 1 << 7, #if 0 GDK_BUTTON1_MASK = 1 << 8, GDK_BUTTON2_MASK = 1 << 9, GDK_BUTTON3_MASK = 1 << 10, GDK_BUTTON4_MASK = 1 << 11, GDK_BUTTON5_MASK = 1 << 12, /* 13, 14 are used by Xkb for the keyboard group */ #endif EGG_VIRTUAL_META_MASK = 1 << 24, EGG_VIRTUAL_SUPER_MASK = 1 << 25, EGG_VIRTUAL_HYPER_MASK = 1 << 26, EGG_VIRTUAL_MODE_SWITCH_MASK = 1 << 27, EGG_VIRTUAL_NUM_LOCK_MASK = 1 << 28, EGG_VIRTUAL_SCROLL_LOCK_MASK = 1 << 29, /* Also in GdkModifierType */ EGG_VIRTUAL_RELEASE_MASK = 1 << 30, /* 28-31 24-27 20-23 16-19 12-15 8-11 4-7 0-3 * 7 f 0 0 0 0 f f */ EGG_VIRTUAL_MODIFIER_MASK = 0x7f0000ff } EggVirtualModifierType; gboolean egg_accelerator_parse_virtual (const gchar *accelerator, guint *accelerator_key, EggVirtualModifierType *accelerator_mods); void egg_keymap_resolve_virtual_modifiers (GdkKeymap *keymap, EggVirtualModifierType virtual_mods, GdkModifierType *concrete_mods); void egg_keymap_virtualize_modifiers (GdkKeymap *keymap, GdkModifierType concrete_mods, EggVirtualModifierType *virtual_mods); gchar* egg_virtual_accelerator_name (guint accelerator_key, EggVirtualModifierType accelerator_mods); G_END_DECLS #endif /* __EGG_ACCELERATORS_H__ */
herzi/monkey-bubble
src/ui/eggaccelerators.h
C
gpl-2.0
3,086
/***************************************************************************** * * * File: sge.c * * $Revision: 1.26 $ * * $Date: 2005/06/21 18:29:48 $ * * Description: * * DMA engine. * * part of the Chelsio 10Gb Ethernet Driver. * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License, version 2, as * * published by the Free Software Foundation. * * * * 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. * * * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED * * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF * * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. * * * * http://www.chelsio.com * * * * Copyright (c) 2003 - 2005 Chelsio Communications, Inc. * * All rights reserved. * * * * Maintainers: maintainers@chelsio.com * * * * Authors: Dimitrios Michailidis <dm@chelsio.com> * * Tina Yang <tainay@chelsio.com> * * Felix Marti <felix@chelsio.com> * * Scott Bardone <sbardone@chelsio.com> * * Kurt Ottaway <kottaway@chelsio.com> * * Frank DiMambro <frank@chelsio.com> * * * * History: * * * ****************************************************************************/ #include "common.h" #include <linux/types.h> #include <linux/errno.h> #include <linux/pci.h> #include <linux/ktime.h> #include <linux/netdevice.h> #include <linux/etherdevice.h> #include <linux/if_vlan.h> #include <linux/skbuff.h> #include <linux/init.h> #include <linux/mm.h> #include <linux/tcp.h> #include <linux/ip.h> #include <linux/in.h> #include <linux/if_arp.h> #include "cpl5_cmd.h" #include "sge.h" #include "regs.h" #include "espi.h" /* This belongs in if_ether.h */ #define ETH_P_CPL5 0xf #define SGE_CMDQ_N 2 #define SGE_FREELQ_N 2 #define SGE_CMDQ0_E_N 1024 #define SGE_CMDQ1_E_N 128 #define SGE_FREEL_SIZE 4096 #define SGE_JUMBO_FREEL_SIZE 512 #define SGE_FREEL_REFILL_THRESH 16 #define SGE_RESPQ_E_N 1024 #define SGE_INTRTIMER_NRES 1000 #define SGE_RX_SM_BUF_SIZE 1536 #define SGE_TX_DESC_MAX_PLEN 16384 #define SGE_RESPQ_REPLENISH_THRES (SGE_RESPQ_E_N / 4) /* * Period of the TX buffer reclaim timer. This timer does not need to run * frequently as TX buffers are usually reclaimed by new TX packets. */ #define TX_RECLAIM_PERIOD (HZ / 4) #define M_CMD_LEN 0x7fffffff #define V_CMD_LEN(v) (v) #define G_CMD_LEN(v) ((v) & M_CMD_LEN) #define V_CMD_GEN1(v) ((v) << 31) #define V_CMD_GEN2(v) (v) #define F_CMD_DATAVALID (1 << 1) #define F_CMD_SOP (1 << 2) #define V_CMD_EOP(v) ((v) << 3) /* * Command queue, receive buffer list, and response queue descriptors. */ #if defined(__BIG_ENDIAN_BITFIELD) struct cmdQ_e { u32 addr_lo; u32 len_gen; u32 flags; u32 addr_hi; }; struct freelQ_e { u32 addr_lo; u32 len_gen; u32 gen2; u32 addr_hi; }; struct respQ_e { u32 Qsleeping : 4; u32 Cmdq1CreditReturn : 5; u32 Cmdq1DmaComplete : 5; u32 Cmdq0CreditReturn : 5; u32 Cmdq0DmaComplete : 5; u32 FreelistQid : 2; u32 CreditValid : 1; u32 DataValid : 1; u32 Offload : 1; u32 Eop : 1; u32 Sop : 1; u32 GenerationBit : 1; u32 BufferLength; }; #elif defined(__LITTLE_ENDIAN_BITFIELD) struct cmdQ_e { u32 len_gen; u32 addr_lo; u32 addr_hi; u32 flags; }; struct freelQ_e { u32 len_gen; u32 addr_lo; u32 addr_hi; u32 gen2; }; struct respQ_e { u32 BufferLength; u32 GenerationBit : 1; u32 Sop : 1; u32 Eop : 1; u32 Offload : 1; u32 DataValid : 1; u32 CreditValid : 1; u32 FreelistQid : 2; u32 Cmdq0DmaComplete : 5; u32 Cmdq0CreditReturn : 5; u32 Cmdq1DmaComplete : 5; u32 Cmdq1CreditReturn : 5; u32 Qsleeping : 4; } ; #endif /* * SW Context Command and Freelist Queue Descriptors */ struct cmdQ_ce { struct sk_buff *skb; DECLARE_PCI_UNMAP_ADDR(dma_addr); DECLARE_PCI_UNMAP_LEN(dma_len); }; struct freelQ_ce { struct sk_buff *skb; DECLARE_PCI_UNMAP_ADDR(dma_addr); DECLARE_PCI_UNMAP_LEN(dma_len); }; /* * SW command, freelist and response rings */ struct cmdQ { unsigned long status; /* HW DMA fetch status */ unsigned int in_use; /* # of in-use command descriptors */ unsigned int size; /* # of descriptors */ unsigned int processed; /* total # of descs HW has processed */ unsigned int cleaned; /* total # of descs SW has reclaimed */ unsigned int stop_thres; /* SW TX queue suspend threshold */ u16 pidx; /* producer index (SW) */ u16 cidx; /* consumer index (HW) */ u8 genbit; /* current generation (=valid) bit */ u8 sop; /* is next entry start of packet? */ struct cmdQ_e *entries; /* HW command descriptor Q */ struct cmdQ_ce *centries; /* SW command context descriptor Q */ dma_addr_t dma_addr; /* DMA addr HW command descriptor Q */ spinlock_t lock; /* Lock to protect cmdQ enqueuing */ }; struct freelQ { unsigned int credits; /* # of available RX buffers */ unsigned int size; /* free list capacity */ u16 pidx; /* producer index (SW) */ u16 cidx; /* consumer index (HW) */ u16 rx_buffer_size; /* Buffer size on this free list */ u16 dma_offset; /* DMA offset to align IP headers */ u16 recycleq_idx; /* skb recycle q to use */ u8 genbit; /* current generation (=valid) bit */ struct freelQ_e *entries; /* HW freelist descriptor Q */ struct freelQ_ce *centries; /* SW freelist context descriptor Q */ dma_addr_t dma_addr; /* DMA addr HW freelist descriptor Q */ }; struct respQ { unsigned int credits; /* credits to be returned to SGE */ unsigned int size; /* # of response Q descriptors */ u16 cidx; /* consumer index (SW) */ u8 genbit; /* current generation(=valid) bit */ struct respQ_e *entries; /* HW response descriptor Q */ dma_addr_t dma_addr; /* DMA addr HW response descriptor Q */ }; /* Bit flags for cmdQ.status */ enum { CMDQ_STAT_RUNNING = 1, /* fetch engine is running */ CMDQ_STAT_LAST_PKT_DB = 2 /* last packet rung the doorbell */ }; /* T204 TX SW scheduler */ /* Per T204 TX port */ struct sched_port { unsigned int avail; /* available bits - quota */ unsigned int drain_bits_per_1024ns; /* drain rate */ unsigned int speed; /* drain rate, mbps */ unsigned int mtu; /* mtu size */ struct sk_buff_head skbq; /* pending skbs */ }; /* Per T204 device */ struct sched { ktime_t last_updated; /* last time quotas were computed */ unsigned int max_avail; /* max bits to be sent to any port */ unsigned int port; /* port index (round robin ports) */ unsigned int num; /* num skbs in per port queues */ struct sched_port p[MAX_NPORTS]; struct tasklet_struct sched_tsk;/* tasklet used to run scheduler */ }; static void restart_sched(unsigned long); /* * Main SGE data structure * * Interrupts are handled by a single CPU and it is likely that on a MP system * the application is migrated to another CPU. In that scenario, we try to * seperate the RX(in irq context) and TX state in order to decrease memory * contention. */ struct sge { struct adapter *adapter; /* adapter backpointer */ struct net_device *netdev; /* netdevice backpointer */ struct freelQ freelQ[SGE_FREELQ_N]; /* buffer free lists */ struct respQ respQ; /* response Q */ unsigned long stopped_tx_queues; /* bitmap of suspended Tx queues */ unsigned int rx_pkt_pad; /* RX padding for L2 packets */ unsigned int jumbo_fl; /* jumbo freelist Q index */ unsigned int intrtimer_nres; /* no-resource interrupt timer */ unsigned int fixed_intrtimer;/* non-adaptive interrupt timer */ struct timer_list tx_reclaim_timer; /* reclaims TX buffers */ struct timer_list espibug_timer; unsigned long espibug_timeout; struct sk_buff *espibug_skb[MAX_NPORTS]; u32 sge_control; /* shadow value of sge control reg */ struct sge_intr_counts stats; struct sge_port_stats *port_stats[MAX_NPORTS]; struct sched *tx_sched; struct cmdQ cmdQ[SGE_CMDQ_N] ____cacheline_aligned_in_smp; }; /* * stop tasklet and free all pending skb's */ static void tx_sched_stop(struct sge *sge) { struct sched *s = sge->tx_sched; int i; tasklet_kill(&s->sched_tsk); for (i = 0; i < MAX_NPORTS; i++) __skb_queue_purge(&s->p[s->port].skbq); } /* * t1_sched_update_parms() is called when the MTU or link speed changes. It * re-computes scheduler parameters to scope with the change. */ unsigned int t1_sched_update_parms(struct sge *sge, unsigned int port, unsigned int mtu, unsigned int speed) { struct sched *s = sge->tx_sched; struct sched_port *p = &s->p[port]; unsigned int max_avail_segs; pr_debug("t1_sched_update_params mtu=%d speed=%d\n", mtu, speed); if (speed) p->speed = speed; if (mtu) p->mtu = mtu; if (speed || mtu) { unsigned long long drain = 1024ULL * p->speed * (p->mtu - 40); do_div(drain, (p->mtu + 50) * 1000); p->drain_bits_per_1024ns = (unsigned int) drain; if (p->speed < 1000) p->drain_bits_per_1024ns = 90 * p->drain_bits_per_1024ns / 100; } if (board_info(sge->adapter)->board == CHBT_BOARD_CHT204) { p->drain_bits_per_1024ns -= 16; s->max_avail = max(4096U, p->mtu + 16 + 14 + 4); max_avail_segs = max(1U, 4096 / (p->mtu - 40)); } else { s->max_avail = 16384; max_avail_segs = max(1U, 9000 / (p->mtu - 40)); } pr_debug("t1_sched_update_parms: mtu %u speed %u max_avail %u " "max_avail_segs %u drain_bits_per_1024ns %u\n", p->mtu, p->speed, s->max_avail, max_avail_segs, p->drain_bits_per_1024ns); return max_avail_segs * (p->mtu - 40); } #if 0 /* * t1_sched_max_avail_bytes() tells the scheduler the maximum amount of * data that can be pushed per port. */ void t1_sched_set_max_avail_bytes(struct sge *sge, unsigned int val) { struct sched *s = sge->tx_sched; unsigned int i; s->max_avail = val; for (i = 0; i < MAX_NPORTS; i++) t1_sched_update_parms(sge, i, 0, 0); } /* * t1_sched_set_drain_bits_per_us() tells the scheduler at which rate a port * is draining. */ void t1_sched_set_drain_bits_per_us(struct sge *sge, unsigned int port, unsigned int val) { struct sched *s = sge->tx_sched; struct sched_port *p = &s->p[port]; p->drain_bits_per_1024ns = val * 1024 / 1000; t1_sched_update_parms(sge, port, 0, 0); } #endif /* 0 */ /* * get_clock() implements a ns clock (see ktime_get) */ static inline ktime_t get_clock(void) { struct timespec ts; ktime_get_ts(&ts); return timespec_to_ktime(ts); } /* * tx_sched_init() allocates resources and does basic initialization. */ static int tx_sched_init(struct sge *sge) { struct sched *s; int i; s = kzalloc(sizeof (struct sched), GFP_KERNEL); if (!s) return -ENOMEM; pr_debug("tx_sched_init\n"); tasklet_init(&s->sched_tsk, restart_sched, (unsigned long) sge); sge->tx_sched = s; for (i = 0; i < MAX_NPORTS; i++) { skb_queue_head_init(&s->p[i].skbq); t1_sched_update_parms(sge, i, 1500, 1000); } return 0; } /* * sched_update_avail() computes the delta since the last time it was called * and updates the per port quota (number of bits that can be sent to the any * port). */ static inline int sched_update_avail(struct sge *sge) { struct sched *s = sge->tx_sched; ktime_t now = get_clock(); unsigned int i; long long delta_time_ns; delta_time_ns = ktime_to_ns(ktime_sub(now, s->last_updated)); pr_debug("sched_update_avail delta=%lld\n", delta_time_ns); if (delta_time_ns < 15000) return 0; for (i = 0; i < MAX_NPORTS; i++) { struct sched_port *p = &s->p[i]; unsigned int delta_avail; delta_avail = (p->drain_bits_per_1024ns * delta_time_ns) >> 13; p->avail = min(p->avail + delta_avail, s->max_avail); } s->last_updated = now; return 1; } /* * sched_skb() is called from two different places. In the tx path, any * packet generating load on an output port will call sched_skb() * (skb != NULL). In addition, sched_skb() is called from the irq/soft irq * context (skb == NULL). * The scheduler only returns a skb (which will then be sent) if the * length of the skb is <= the current quota of the output port. */ static struct sk_buff *sched_skb(struct sge *sge, struct sk_buff *skb, unsigned int credits) { struct sched *s = sge->tx_sched; struct sk_buff_head *skbq; unsigned int i, len, update = 1; pr_debug("sched_skb %p\n", skb); if (!skb) { if (!s->num) return NULL; } else { skbq = &s->p[skb->dev->if_port].skbq; __skb_queue_tail(skbq, skb); s->num++; skb = NULL; } if (credits < MAX_SKB_FRAGS + 1) goto out; again: for (i = 0; i < MAX_NPORTS; i++) { s->port = ++s->port & (MAX_NPORTS - 1); skbq = &s->p[s->port].skbq; skb = skb_peek(skbq); if (!skb) continue; len = skb->len; if (len <= s->p[s->port].avail) { s->p[s->port].avail -= len; s->num--; __skb_unlink(skb, skbq); goto out; } skb = NULL; } if (update-- && sched_update_avail(sge)) goto again; out: /* If there are more pending skbs, we use the hardware to schedule us * again. */ if (s->num && !skb) { struct cmdQ *q = &sge->cmdQ[0]; clear_bit(CMDQ_STAT_LAST_PKT_DB, &q->status); if (test_and_set_bit(CMDQ_STAT_RUNNING, &q->status) == 0) { set_bit(CMDQ_STAT_LAST_PKT_DB, &q->status); writel(F_CMDQ0_ENABLE, sge->adapter->regs + A_SG_DOORBELL); } } pr_debug("sched_skb ret %p\n", skb); return skb; } /* * PIO to indicate that memory mapped Q contains valid descriptor(s). */ static inline void doorbell_pio(struct adapter *adapter, u32 val) { wmb(); writel(val, adapter->regs + A_SG_DOORBELL); } /* * Frees all RX buffers on the freelist Q. The caller must make sure that * the SGE is turned off before calling this function. */ static void free_freelQ_buffers(struct pci_dev *pdev, struct freelQ *q) { unsigned int cidx = q->cidx; while (q->credits--) { struct freelQ_ce *ce = &q->centries[cidx]; pci_unmap_single(pdev, pci_unmap_addr(ce, dma_addr), pci_unmap_len(ce, dma_len), PCI_DMA_FROMDEVICE); dev_kfree_skb(ce->skb); ce->skb = NULL; if (++cidx == q->size) cidx = 0; } } /* * Free RX free list and response queue resources. */ static void free_rx_resources(struct sge *sge) { struct pci_dev *pdev = sge->adapter->pdev; unsigned int size, i; if (sge->respQ.entries) { size = sizeof(struct respQ_e) * sge->respQ.size; pci_free_consistent(pdev, size, sge->respQ.entries, sge->respQ.dma_addr); } for (i = 0; i < SGE_FREELQ_N; i++) { struct freelQ *q = &sge->freelQ[i]; if (q->centries) { free_freelQ_buffers(pdev, q); kfree(q->centries); } if (q->entries) { size = sizeof(struct freelQ_e) * q->size; pci_free_consistent(pdev, size, q->entries, q->dma_addr); } } } /* * Allocates basic RX resources, consisting of memory mapped freelist Qs and a * response queue. */ static int alloc_rx_resources(struct sge *sge, struct sge_params *p) { struct pci_dev *pdev = sge->adapter->pdev; unsigned int size, i; for (i = 0; i < SGE_FREELQ_N; i++) { struct freelQ *q = &sge->freelQ[i]; q->genbit = 1; q->size = p->freelQ_size[i]; q->dma_offset = sge->rx_pkt_pad ? 0 : NET_IP_ALIGN; size = sizeof(struct freelQ_e) * q->size; q->entries = pci_alloc_consistent(pdev, size, &q->dma_addr); if (!q->entries) goto err_no_mem; size = sizeof(struct freelQ_ce) * q->size; q->centries = kzalloc(size, GFP_KERNEL); if (!q->centries) goto err_no_mem; } /* * Calculate the buffer sizes for the two free lists. FL0 accommodates * regular sized Ethernet frames, FL1 is sized not to exceed 16K, * including all the sk_buff overhead. * * Note: For T2 FL0 and FL1 are reversed. */ sge->freelQ[!sge->jumbo_fl].rx_buffer_size = SGE_RX_SM_BUF_SIZE + sizeof(struct cpl_rx_data) + sge->freelQ[!sge->jumbo_fl].dma_offset; size = (16 * 1024) - SKB_DATA_ALIGN(sizeof(struct skb_shared_info)); sge->freelQ[sge->jumbo_fl].rx_buffer_size = size; /* * Setup which skb recycle Q should be used when recycling buffers from * each free list. */ sge->freelQ[!sge->jumbo_fl].recycleq_idx = 0; sge->freelQ[sge->jumbo_fl].recycleq_idx = 1; sge->respQ.genbit = 1; sge->respQ.size = SGE_RESPQ_E_N; sge->respQ.credits = 0; size = sizeof(struct respQ_e) * sge->respQ.size; sge->respQ.entries = pci_alloc_consistent(pdev, size, &sge->respQ.dma_addr); if (!sge->respQ.entries) goto err_no_mem; return 0; err_no_mem: free_rx_resources(sge); return -ENOMEM; } /* * Reclaims n TX descriptors and frees the buffers associated with them. */ static void free_cmdQ_buffers(struct sge *sge, struct cmdQ *q, unsigned int n) { struct cmdQ_ce *ce; struct pci_dev *pdev = sge->adapter->pdev; unsigned int cidx = q->cidx; q->in_use -= n; ce = &q->centries[cidx]; while (n--) { if (likely(pci_unmap_len(ce, dma_len))) { pci_unmap_single(pdev, pci_unmap_addr(ce, dma_addr), pci_unmap_len(ce, dma_len), PCI_DMA_TODEVICE); if (q->sop) q->sop = 0; } if (ce->skb) { dev_kfree_skb_any(ce->skb); q->sop = 1; } ce++; if (++cidx == q->size) { cidx = 0; ce = q->centries; } } q->cidx = cidx; } /* * Free TX resources. * * Assumes that SGE is stopped and all interrupts are disabled. */ static void free_tx_resources(struct sge *sge) { struct pci_dev *pdev = sge->adapter->pdev; unsigned int size, i; for (i = 0; i < SGE_CMDQ_N; i++) { struct cmdQ *q = &sge->cmdQ[i]; if (q->centries) { if (q->in_use) free_cmdQ_buffers(sge, q, q->in_use); kfree(q->centries); } if (q->entries) { size = sizeof(struct cmdQ_e) * q->size; pci_free_consistent(pdev, size, q->entries, q->dma_addr); } } } /* * Allocates basic TX resources, consisting of memory mapped command Qs. */ static int alloc_tx_resources(struct sge *sge, struct sge_params *p) { struct pci_dev *pdev = sge->adapter->pdev; unsigned int size, i; for (i = 0; i < SGE_CMDQ_N; i++) { struct cmdQ *q = &sge->cmdQ[i]; q->genbit = 1; q->sop = 1; q->size = p->cmdQ_size[i]; q->in_use = 0; q->status = 0; q->processed = q->cleaned = 0; q->stop_thres = 0; spin_lock_init(&q->lock); size = sizeof(struct cmdQ_e) * q->size; q->entries = pci_alloc_consistent(pdev, size, &q->dma_addr); if (!q->entries) goto err_no_mem; size = sizeof(struct cmdQ_ce) * q->size; q->centries = kzalloc(size, GFP_KERNEL); if (!q->centries) goto err_no_mem; } /* * CommandQ 0 handles Ethernet and TOE packets, while queue 1 is TOE * only. For queue 0 set the stop threshold so we can handle one more * packet from each port, plus reserve an additional 24 entries for * Ethernet packets only. Queue 1 never suspends nor do we reserve * space for Ethernet packets. */ sge->cmdQ[0].stop_thres = sge->adapter->params.nports * (MAX_SKB_FRAGS + 1); return 0; err_no_mem: free_tx_resources(sge); return -ENOMEM; } static inline void setup_ring_params(struct adapter *adapter, u64 addr, u32 size, int base_reg_lo, int base_reg_hi, int size_reg) { writel((u32)addr, adapter->regs + base_reg_lo); writel(addr >> 32, adapter->regs + base_reg_hi); writel(size, adapter->regs + size_reg); } /* * Enable/disable VLAN acceleration. */ void t1_set_vlan_accel(struct adapter *adapter, int on_off) { struct sge *sge = adapter->sge; sge->sge_control &= ~F_VLAN_XTRACT; if (on_off) sge->sge_control |= F_VLAN_XTRACT; if (adapter->open_device_map) { writel(sge->sge_control, adapter->regs + A_SG_CONTROL); readl(adapter->regs + A_SG_CONTROL); /* flush */ } } /* * Programs the various SGE registers. However, the engine is not yet enabled, * but sge->sge_control is setup and ready to go. */ static void configure_sge(struct sge *sge, struct sge_params *p) { struct adapter *ap = sge->adapter; writel(0, ap->regs + A_SG_CONTROL); setup_ring_params(ap, sge->cmdQ[0].dma_addr, sge->cmdQ[0].size, A_SG_CMD0BASELWR, A_SG_CMD0BASEUPR, A_SG_CMD0SIZE); setup_ring_params(ap, sge->cmdQ[1].dma_addr, sge->cmdQ[1].size, A_SG_CMD1BASELWR, A_SG_CMD1BASEUPR, A_SG_CMD1SIZE); setup_ring_params(ap, sge->freelQ[0].dma_addr, sge->freelQ[0].size, A_SG_FL0BASELWR, A_SG_FL0BASEUPR, A_SG_FL0SIZE); setup_ring_params(ap, sge->freelQ[1].dma_addr, sge->freelQ[1].size, A_SG_FL1BASELWR, A_SG_FL1BASEUPR, A_SG_FL1SIZE); /* The threshold comparison uses <. */ writel(SGE_RX_SM_BUF_SIZE + 1, ap->regs + A_SG_FLTHRESHOLD); setup_ring_params(ap, sge->respQ.dma_addr, sge->respQ.size, A_SG_RSPBASELWR, A_SG_RSPBASEUPR, A_SG_RSPSIZE); writel((u32)sge->respQ.size - 1, ap->regs + A_SG_RSPQUEUECREDIT); sge->sge_control = F_CMDQ0_ENABLE | F_CMDQ1_ENABLE | F_FL0_ENABLE | F_FL1_ENABLE | F_CPL_ENABLE | F_RESPONSE_QUEUE_ENABLE | V_CMDQ_PRIORITY(2) | F_DISABLE_CMDQ1_GTS | F_ISCSI_COALESCE | V_RX_PKT_OFFSET(sge->rx_pkt_pad); #if defined(__BIG_ENDIAN_BITFIELD) sge->sge_control |= F_ENABLE_BIG_ENDIAN; #endif /* Initialize no-resource timer */ sge->intrtimer_nres = SGE_INTRTIMER_NRES * core_ticks_per_usec(ap); t1_sge_set_coalesce_params(sge, p); } /* * Return the payload capacity of the jumbo free-list buffers. */ static inline unsigned int jumbo_payload_capacity(const struct sge *sge) { return sge->freelQ[sge->jumbo_fl].rx_buffer_size - sge->freelQ[sge->jumbo_fl].dma_offset - sizeof(struct cpl_rx_data); } /* * Frees all SGE related resources and the sge structure itself */ void t1_sge_destroy(struct sge *sge) { int i; for_each_port(sge->adapter, i) free_percpu(sge->port_stats[i]); kfree(sge->tx_sched); free_tx_resources(sge); free_rx_resources(sge); kfree(sge); } /* * Allocates new RX buffers on the freelist Q (and tracks them on the freelist * context Q) until the Q is full or alloc_skb fails. * * It is possible that the generation bits already match, indicating that the * buffer is already valid and nothing needs to be done. This happens when we * copied a received buffer into a new sk_buff during the interrupt processing. * * If the SGE doesn't automatically align packets properly (!sge->rx_pkt_pad), * we specify a RX_OFFSET in order to make sure that the IP header is 4B * aligned. */ static void refill_free_list(struct sge *sge, struct freelQ *q) { struct pci_dev *pdev = sge->adapter->pdev; struct freelQ_ce *ce = &q->centries[q->pidx]; struct freelQ_e *e = &q->entries[q->pidx]; unsigned int dma_len = q->rx_buffer_size - q->dma_offset; while (q->credits < q->size) { struct sk_buff *skb; dma_addr_t mapping; skb = alloc_skb(q->rx_buffer_size, GFP_ATOMIC); if (!skb) break; skb_reserve(skb, q->dma_offset); mapping = pci_map_single(pdev, skb->data, dma_len, PCI_DMA_FROMDEVICE); skb_reserve(skb, sge->rx_pkt_pad); ce->skb = skb; pci_unmap_addr_set(ce, dma_addr, mapping); pci_unmap_len_set(ce, dma_len, dma_len); e->addr_lo = (u32)mapping; e->addr_hi = (u64)mapping >> 32; e->len_gen = V_CMD_LEN(dma_len) | V_CMD_GEN1(q->genbit); wmb(); e->gen2 = V_CMD_GEN2(q->genbit); e++; ce++; if (++q->pidx == q->size) { q->pidx = 0; q->genbit ^= 1; ce = q->centries; e = q->entries; } q->credits++; } } /* * Calls refill_free_list for both free lists. If we cannot fill at least 1/4 * of both rings, we go into 'few interrupt mode' in order to give the system * time to free up resources. */ static void freelQs_empty(struct sge *sge) { struct adapter *adapter = sge->adapter; u32 irq_reg = readl(adapter->regs + A_SG_INT_ENABLE); u32 irqholdoff_reg; refill_free_list(sge, &sge->freelQ[0]); refill_free_list(sge, &sge->freelQ[1]); if (sge->freelQ[0].credits > (sge->freelQ[0].size >> 2) && sge->freelQ[1].credits > (sge->freelQ[1].size >> 2)) { irq_reg |= F_FL_EXHAUSTED; irqholdoff_reg = sge->fixed_intrtimer; } else { /* Clear the F_FL_EXHAUSTED interrupts for now */ irq_reg &= ~F_FL_EXHAUSTED; irqholdoff_reg = sge->intrtimer_nres; } writel(irqholdoff_reg, adapter->regs + A_SG_INTRTIMER); writel(irq_reg, adapter->regs + A_SG_INT_ENABLE); /* We reenable the Qs to force a freelist GTS interrupt later */ doorbell_pio(adapter, F_FL0_ENABLE | F_FL1_ENABLE); } #define SGE_PL_INTR_MASK (F_PL_INTR_SGE_ERR | F_PL_INTR_SGE_DATA) #define SGE_INT_FATAL (F_RESPQ_OVERFLOW | F_PACKET_TOO_BIG | F_PACKET_MISMATCH) #define SGE_INT_ENABLE (F_RESPQ_EXHAUSTED | F_RESPQ_OVERFLOW | \ F_FL_EXHAUSTED | F_PACKET_TOO_BIG | F_PACKET_MISMATCH) /* * Disable SGE Interrupts */ void t1_sge_intr_disable(struct sge *sge) { u32 val = readl(sge->adapter->regs + A_PL_ENABLE); writel(val & ~SGE_PL_INTR_MASK, sge->adapter->regs + A_PL_ENABLE); writel(0, sge->adapter->regs + A_SG_INT_ENABLE); } /* * Enable SGE interrupts. */ void t1_sge_intr_enable(struct sge *sge) { u32 en = SGE_INT_ENABLE; u32 val = readl(sge->adapter->regs + A_PL_ENABLE); if (sge->adapter->flags & TSO_CAPABLE) en &= ~F_PACKET_TOO_BIG; writel(en, sge->adapter->regs + A_SG_INT_ENABLE); writel(val | SGE_PL_INTR_MASK, sge->adapter->regs + A_PL_ENABLE); } /* * Clear SGE interrupts. */ void t1_sge_intr_clear(struct sge *sge) { writel(SGE_PL_INTR_MASK, sge->adapter->regs + A_PL_CAUSE); writel(0xffffffff, sge->adapter->regs + A_SG_INT_CAUSE); } /* * SGE 'Error' interrupt handler */ int t1_sge_intr_error_handler(struct sge *sge) { struct adapter *adapter = sge->adapter; u32 cause = readl(adapter->regs + A_SG_INT_CAUSE); if (adapter->flags & TSO_CAPABLE) cause &= ~F_PACKET_TOO_BIG; if (cause & F_RESPQ_EXHAUSTED) sge->stats.respQ_empty++; if (cause & F_RESPQ_OVERFLOW) { sge->stats.respQ_overflow++; CH_ALERT("%s: SGE response queue overflow\n", adapter->name); } if (cause & F_FL_EXHAUSTED) { sge->stats.freelistQ_empty++; freelQs_empty(sge); } if (cause & F_PACKET_TOO_BIG) { sge->stats.pkt_too_big++; CH_ALERT("%s: SGE max packet size exceeded\n", adapter->name); } if (cause & F_PACKET_MISMATCH) { sge->stats.pkt_mismatch++; CH_ALERT("%s: SGE packet mismatch\n", adapter->name); } if (cause & SGE_INT_FATAL) t1_fatal_err(adapter); writel(cause, adapter->regs + A_SG_INT_CAUSE); return 0; } const struct sge_intr_counts *t1_sge_get_intr_counts(const struct sge *sge) { return &sge->stats; } void t1_sge_get_port_stats(const struct sge *sge, int port, struct sge_port_stats *ss) { int cpu; memset(ss, 0, sizeof(*ss)); for_each_possible_cpu(cpu) { struct sge_port_stats *st = per_cpu_ptr(sge->port_stats[port], cpu); ss->rx_cso_good += st->rx_cso_good; ss->tx_cso += st->tx_cso; ss->tx_tso += st->tx_tso; ss->tx_need_hdrroom += st->tx_need_hdrroom; ss->vlan_xtract += st->vlan_xtract; ss->vlan_insert += st->vlan_insert; } } /** * recycle_fl_buf - recycle a free list buffer * @fl: the free list * @idx: index of buffer to recycle * * Recycles the specified buffer on the given free list by adding it at * the next available slot on the list. */ static void recycle_fl_buf(struct freelQ *fl, int idx) { struct freelQ_e *from = &fl->entries[idx]; struct freelQ_e *to = &fl->entries[fl->pidx]; fl->centries[fl->pidx] = fl->centries[idx]; to->addr_lo = from->addr_lo; to->addr_hi = from->addr_hi; to->len_gen = G_CMD_LEN(from->len_gen) | V_CMD_GEN1(fl->genbit); wmb(); to->gen2 = V_CMD_GEN2(fl->genbit); fl->credits++; if (++fl->pidx == fl->size) { fl->pidx = 0; fl->genbit ^= 1; } } static int copybreak __read_mostly = 256; module_param(copybreak, int, 0); MODULE_PARM_DESC(copybreak, "Receive copy threshold"); /** * get_packet - return the next ingress packet buffer * @pdev: the PCI device that received the packet * @fl: the SGE free list holding the packet * @len: the actual packet length, excluding any SGE padding * * Get the next packet from a free list and complete setup of the * sk_buff. If the packet is small we make a copy and recycle the * original buffer, otherwise we use the original buffer itself. If a * positive drop threshold is supplied packets are dropped and their * buffers recycled if (a) the number of remaining buffers is under the * threshold and the packet is too big to copy, or (b) the packet should * be copied but there is no memory for the copy. */ static inline struct sk_buff *get_packet(struct pci_dev *pdev, struct freelQ *fl, unsigned int len) { struct sk_buff *skb; const struct freelQ_ce *ce = &fl->centries[fl->cidx]; if (len < copybreak) { skb = alloc_skb(len + 2, GFP_ATOMIC); if (!skb) goto use_orig_buf; skb_reserve(skb, 2); /* align IP header */ skb_put(skb, len); pci_dma_sync_single_for_cpu(pdev, pci_unmap_addr(ce, dma_addr), pci_unmap_len(ce, dma_len), PCI_DMA_FROMDEVICE); skb_copy_from_linear_data(ce->skb, skb->data, len); pci_dma_sync_single_for_device(pdev, pci_unmap_addr(ce, dma_addr), pci_unmap_len(ce, dma_len), PCI_DMA_FROMDEVICE); recycle_fl_buf(fl, fl->cidx); return skb; } use_orig_buf: if (fl->credits < 2) { recycle_fl_buf(fl, fl->cidx); return NULL; } pci_unmap_single(pdev, pci_unmap_addr(ce, dma_addr), pci_unmap_len(ce, dma_len), PCI_DMA_FROMDEVICE); skb = ce->skb; prefetch(skb->data); skb_put(skb, len); return skb; } /** * unexpected_offload - handle an unexpected offload packet * @adapter: the adapter * @fl: the free list that received the packet * * Called when we receive an unexpected offload packet (e.g., the TOE * function is disabled or the card is a NIC). Prints a message and * recycles the buffer. */ static void unexpected_offload(struct adapter *adapter, struct freelQ *fl) { struct freelQ_ce *ce = &fl->centries[fl->cidx]; struct sk_buff *skb = ce->skb; pci_dma_sync_single_for_cpu(adapter->pdev, pci_unmap_addr(ce, dma_addr), pci_unmap_len(ce, dma_len), PCI_DMA_FROMDEVICE); CH_ERR("%s: unexpected offload packet, cmd %u\n", adapter->name, *skb->data); recycle_fl_buf(fl, fl->cidx); } /* * T1/T2 SGE limits the maximum DMA size per TX descriptor to * SGE_TX_DESC_MAX_PLEN (16KB). If the PAGE_SIZE is larger than 16KB, the * stack might send more than SGE_TX_DESC_MAX_PLEN in a contiguous manner. * Note that the *_large_page_tx_descs stuff will be optimized out when * PAGE_SIZE <= SGE_TX_DESC_MAX_PLEN. * * compute_large_page_descs() computes how many additional descriptors are * required to break down the stack's request. */ static inline unsigned int compute_large_page_tx_descs(struct sk_buff *skb) { unsigned int count = 0; if (PAGE_SIZE > SGE_TX_DESC_MAX_PLEN) { unsigned int nfrags = skb_shinfo(skb)->nr_frags; unsigned int i, len = skb->len - skb->data_len; while (len > SGE_TX_DESC_MAX_PLEN) { count++; len -= SGE_TX_DESC_MAX_PLEN; } for (i = 0; nfrags--; i++) { skb_frag_t *frag = &skb_shinfo(skb)->frags[i]; len = frag->size; while (len > SGE_TX_DESC_MAX_PLEN) { count++; len -= SGE_TX_DESC_MAX_PLEN; } } } return count; } /* * Write a cmdQ entry. * * Since this function writes the 'flags' field, it must not be used to * write the first cmdQ entry. */ static inline void write_tx_desc(struct cmdQ_e *e, dma_addr_t mapping, unsigned int len, unsigned int gen, unsigned int eop) { if (unlikely(len > SGE_TX_DESC_MAX_PLEN)) BUG(); e->addr_lo = (u32)mapping; e->addr_hi = (u64)mapping >> 32; e->len_gen = V_CMD_LEN(len) | V_CMD_GEN1(gen); e->flags = F_CMD_DATAVALID | V_CMD_EOP(eop) | V_CMD_GEN2(gen); } /* * See comment for previous function. * * write_tx_descs_large_page() writes additional SGE tx descriptors if * *desc_len exceeds HW's capability. */ static inline unsigned int write_large_page_tx_descs(unsigned int pidx, struct cmdQ_e **e, struct cmdQ_ce **ce, unsigned int *gen, dma_addr_t *desc_mapping, unsigned int *desc_len, unsigned int nfrags, struct cmdQ *q) { if (PAGE_SIZE > SGE_TX_DESC_MAX_PLEN) { struct cmdQ_e *e1 = *e; struct cmdQ_ce *ce1 = *ce; while (*desc_len > SGE_TX_DESC_MAX_PLEN) { *desc_len -= SGE_TX_DESC_MAX_PLEN; write_tx_desc(e1, *desc_mapping, SGE_TX_DESC_MAX_PLEN, *gen, nfrags == 0 && *desc_len == 0); ce1->skb = NULL; pci_unmap_len_set(ce1, dma_len, 0); *desc_mapping += SGE_TX_DESC_MAX_PLEN; if (*desc_len) { ce1++; e1++; if (++pidx == q->size) { pidx = 0; *gen ^= 1; ce1 = q->centries; e1 = q->entries; } } } *e = e1; *ce = ce1; } return pidx; } /* * Write the command descriptors to transmit the given skb starting at * descriptor pidx with the given generation. */ static inline void write_tx_descs(struct adapter *adapter, struct sk_buff *skb, unsigned int pidx, unsigned int gen, struct cmdQ *q) { dma_addr_t mapping, desc_mapping; struct cmdQ_e *e, *e1; struct cmdQ_ce *ce; unsigned int i, flags, first_desc_len, desc_len, nfrags = skb_shinfo(skb)->nr_frags; e = e1 = &q->entries[pidx]; ce = &q->centries[pidx]; mapping = pci_map_single(adapter->pdev, skb->data, skb->len - skb->data_len, PCI_DMA_TODEVICE); desc_mapping = mapping; desc_len = skb->len - skb->data_len; flags = F_CMD_DATAVALID | F_CMD_SOP | V_CMD_EOP(nfrags == 0 && desc_len <= SGE_TX_DESC_MAX_PLEN) | V_CMD_GEN2(gen); first_desc_len = (desc_len <= SGE_TX_DESC_MAX_PLEN) ? desc_len : SGE_TX_DESC_MAX_PLEN; e->addr_lo = (u32)desc_mapping; e->addr_hi = (u64)desc_mapping >> 32; e->len_gen = V_CMD_LEN(first_desc_len) | V_CMD_GEN1(gen); ce->skb = NULL; pci_unmap_len_set(ce, dma_len, 0); if (PAGE_SIZE > SGE_TX_DESC_MAX_PLEN && desc_len > SGE_TX_DESC_MAX_PLEN) { desc_mapping += first_desc_len; desc_len -= first_desc_len; e1++; ce++; if (++pidx == q->size) { pidx = 0; gen ^= 1; e1 = q->entries; ce = q->centries; } pidx = write_large_page_tx_descs(pidx, &e1, &ce, &gen, &desc_mapping, &desc_len, nfrags, q); if (likely(desc_len)) write_tx_desc(e1, desc_mapping, desc_len, gen, nfrags == 0); } ce->skb = NULL; pci_unmap_addr_set(ce, dma_addr, mapping); pci_unmap_len_set(ce, dma_len, skb->len - skb->data_len); for (i = 0; nfrags--; i++) { skb_frag_t *frag = &skb_shinfo(skb)->frags[i]; e1++; ce++; if (++pidx == q->size) { pidx = 0; gen ^= 1; e1 = q->entries; ce = q->centries; } mapping = pci_map_page(adapter->pdev, frag->page, frag->page_offset, frag->size, PCI_DMA_TODEVICE); desc_mapping = mapping; desc_len = frag->size; pidx = write_large_page_tx_descs(pidx, &e1, &ce, &gen, &desc_mapping, &desc_len, nfrags, q); if (likely(desc_len)) write_tx_desc(e1, desc_mapping, desc_len, gen, nfrags == 0); ce->skb = NULL; pci_unmap_addr_set(ce, dma_addr, mapping); pci_unmap_len_set(ce, dma_len, frag->size); } ce->skb = skb; wmb(); e->flags = flags; } /* * Clean up completed Tx buffers. */ static inline void reclaim_completed_tx(struct sge *sge, struct cmdQ *q) { unsigned int reclaim = q->processed - q->cleaned; if (reclaim) { pr_debug("reclaim_completed_tx processed:%d cleaned:%d\n", q->processed, q->cleaned); free_cmdQ_buffers(sge, q, reclaim); q->cleaned += reclaim; } } /* * Called from tasklet. Checks the scheduler for any * pending skbs that can be sent. */ static void restart_sched(unsigned long arg) { struct sge *sge = (struct sge *) arg; struct adapter *adapter = sge->adapter; struct cmdQ *q = &sge->cmdQ[0]; struct sk_buff *skb; unsigned int credits, queued_skb = 0; spin_lock(&q->lock); reclaim_completed_tx(sge, q); credits = q->size - q->in_use; pr_debug("restart_sched credits=%d\n", credits); while ((skb = sched_skb(sge, NULL, credits)) != NULL) { unsigned int genbit, pidx, count; count = 1 + skb_shinfo(skb)->nr_frags; count += compute_large_page_tx_descs(skb); q->in_use += count; genbit = q->genbit; pidx = q->pidx; q->pidx += count; if (q->pidx >= q->size) { q->pidx -= q->size; q->genbit ^= 1; } write_tx_descs(adapter, skb, pidx, genbit, q); credits = q->size - q->in_use; queued_skb = 1; } if (queued_skb) { clear_bit(CMDQ_STAT_LAST_PKT_DB, &q->status); if (test_and_set_bit(CMDQ_STAT_RUNNING, &q->status) == 0) { set_bit(CMDQ_STAT_LAST_PKT_DB, &q->status); writel(F_CMDQ0_ENABLE, adapter->regs + A_SG_DOORBELL); } } spin_unlock(&q->lock); } /** * sge_rx - process an ingress ethernet packet * @sge: the sge structure * @fl: the free list that contains the packet buffer * @len: the packet length * * Process an ingress ethernet pakcet and deliver it to the stack. */ static void sge_rx(struct sge *sge, struct freelQ *fl, unsigned int len) { struct sk_buff *skb; const struct cpl_rx_pkt *p; struct adapter *adapter = sge->adapter; struct sge_port_stats *st; skb = get_packet(adapter->pdev, fl, len - sge->rx_pkt_pad); if (unlikely(!skb)) { sge->stats.rx_drops++; return; } p = (const struct cpl_rx_pkt *) skb->data; if (p->iff >= adapter->params.nports) { kfree_skb(skb); return; } __skb_pull(skb, sizeof(*p)); st = per_cpu_ptr(sge->port_stats[p->iff], smp_processor_id()); skb->protocol = eth_type_trans(skb, adapter->port[p->iff].dev); skb->dev->last_rx = jiffies; if ((adapter->flags & RX_CSUM_ENABLED) && p->csum == 0xffff && skb->protocol == htons(ETH_P_IP) && (skb->data[9] == IPPROTO_TCP || skb->data[9] == IPPROTO_UDP)) { ++st->rx_cso_good; skb->ip_summed = CHECKSUM_UNNECESSARY; } else skb->ip_summed = CHECKSUM_NONE; if (unlikely(adapter->vlan_grp && p->vlan_valid)) { st->vlan_xtract++; vlan_hwaccel_receive_skb(skb, adapter->vlan_grp, ntohs(p->vlan)); } else netif_receive_skb(skb); } /* * Returns true if a command queue has enough available descriptors that * we can resume Tx operation after temporarily disabling its packet queue. */ static inline int enough_free_Tx_descs(const struct cmdQ *q) { unsigned int r = q->processed - q->cleaned; return q->in_use - r < (q->size >> 1); } /* * Called when sufficient space has become available in the SGE command queues * after the Tx packet schedulers have been suspended to restart the Tx path. */ static void restart_tx_queues(struct sge *sge) { struct adapter *adap = sge->adapter; int i; if (!enough_free_Tx_descs(&sge->cmdQ[0])) return; for_each_port(adap, i) { struct net_device *nd = adap->port[i].dev; if (test_and_clear_bit(nd->if_port, &sge->stopped_tx_queues) && netif_running(nd)) { sge->stats.cmdQ_restarted[2]++; netif_wake_queue(nd); } } } /* * update_tx_info is called from the interrupt handler/NAPI to return cmdQ0 * information. */ static unsigned int update_tx_info(struct adapter *adapter, unsigned int flags, unsigned int pr0) { struct sge *sge = adapter->sge; struct cmdQ *cmdq = &sge->cmdQ[0]; cmdq->processed += pr0; if (flags & (F_FL0_ENABLE | F_FL1_ENABLE)) { freelQs_empty(sge); flags &= ~(F_FL0_ENABLE | F_FL1_ENABLE); } if (flags & F_CMDQ0_ENABLE) { clear_bit(CMDQ_STAT_RUNNING, &cmdq->status); if (cmdq->cleaned + cmdq->in_use != cmdq->processed && !test_and_set_bit(CMDQ_STAT_LAST_PKT_DB, &cmdq->status)) { set_bit(CMDQ_STAT_RUNNING, &cmdq->status); writel(F_CMDQ0_ENABLE, adapter->regs + A_SG_DOORBELL); } if (sge->tx_sched) tasklet_hi_schedule(&sge->tx_sched->sched_tsk); flags &= ~F_CMDQ0_ENABLE; } if (unlikely(sge->stopped_tx_queues != 0)) restart_tx_queues(sge); return flags; } /* * Process SGE responses, up to the supplied budget. Returns the number of * responses processed. A negative budget is effectively unlimited. */ static int process_responses(struct adapter *adapter, int budget) { struct sge *sge = adapter->sge; struct respQ *q = &sge->respQ; struct respQ_e *e = &q->entries[q->cidx]; int done = 0; unsigned int flags = 0; unsigned int cmdq_processed[SGE_CMDQ_N] = {0, 0}; while (done < budget && e->GenerationBit == q->genbit) { flags |= e->Qsleeping; cmdq_processed[0] += e->Cmdq0CreditReturn; cmdq_processed[1] += e->Cmdq1CreditReturn; /* We batch updates to the TX side to avoid cacheline * ping-pong of TX state information on MP where the sender * might run on a different CPU than this function... */ if (unlikely((flags & F_CMDQ0_ENABLE) || cmdq_processed[0] > 64)) { flags = update_tx_info(adapter, flags, cmdq_processed[0]); cmdq_processed[0] = 0; } if (unlikely(cmdq_processed[1] > 16)) { sge->cmdQ[1].processed += cmdq_processed[1]; cmdq_processed[1] = 0; } if (likely(e->DataValid)) { struct freelQ *fl = &sge->freelQ[e->FreelistQid]; BUG_ON(!e->Sop || !e->Eop); if (unlikely(e->Offload)) unexpected_offload(adapter, fl); else sge_rx(sge, fl, e->BufferLength); ++done; /* * Note: this depends on each packet consuming a * single free-list buffer; cf. the BUG above. */ if (++fl->cidx == fl->size) fl->cidx = 0; prefetch(fl->centries[fl->cidx].skb); if (unlikely(--fl->credits < fl->size - SGE_FREEL_REFILL_THRESH)) refill_free_list(sge, fl); } else sge->stats.pure_rsps++; e++; if (unlikely(++q->cidx == q->size)) { q->cidx = 0; q->genbit ^= 1; e = q->entries; } prefetch(e); if (++q->credits > SGE_RESPQ_REPLENISH_THRES) { writel(q->credits, adapter->regs + A_SG_RSPQUEUECREDIT); q->credits = 0; } } flags = update_tx_info(adapter, flags, cmdq_processed[0]); sge->cmdQ[1].processed += cmdq_processed[1]; return done; } static inline int responses_pending(const struct adapter *adapter) { const struct respQ *Q = &adapter->sge->respQ; const struct respQ_e *e = &Q->entries[Q->cidx]; return (e->GenerationBit == Q->genbit); } /* * A simpler version of process_responses() that handles only pure (i.e., * non data-carrying) responses. Such respones are too light-weight to justify * calling a softirq when using NAPI, so we handle them specially in hard * interrupt context. The function is called with a pointer to a response, * which the caller must ensure is a valid pure response. Returns 1 if it * encounters a valid data-carrying response, 0 otherwise. */ static int process_pure_responses(struct adapter *adapter) { struct sge *sge = adapter->sge; struct respQ *q = &sge->respQ; struct respQ_e *e = &q->entries[q->cidx]; const struct freelQ *fl = &sge->freelQ[e->FreelistQid]; unsigned int flags = 0; unsigned int cmdq_processed[SGE_CMDQ_N] = {0, 0}; prefetch(fl->centries[fl->cidx].skb); if (e->DataValid) return 1; do { flags |= e->Qsleeping; cmdq_processed[0] += e->Cmdq0CreditReturn; cmdq_processed[1] += e->Cmdq1CreditReturn; e++; if (unlikely(++q->cidx == q->size)) { q->cidx = 0; q->genbit ^= 1; e = q->entries; } prefetch(e); if (++q->credits > SGE_RESPQ_REPLENISH_THRES) { writel(q->credits, adapter->regs + A_SG_RSPQUEUECREDIT); q->credits = 0; } sge->stats.pure_rsps++; } while (e->GenerationBit == q->genbit && !e->DataValid); flags = update_tx_info(adapter, flags, cmdq_processed[0]); sge->cmdQ[1].processed += cmdq_processed[1]; return e->GenerationBit == q->genbit; } /* * Handler for new data events when using NAPI. This does not need any locking * or protection from interrupts as data interrupts are off at this point and * other adapter interrupts do not interfere. */ int t1_poll(struct napi_struct *napi, int budget) { struct adapter *adapter = container_of(napi, struct adapter, napi); struct net_device *dev = adapter->port[0].dev; int work_done = process_responses(adapter, budget); if (likely(work_done < budget)) { netif_rx_complete(dev, napi); writel(adapter->sge->respQ.cidx, adapter->regs + A_SG_SLEEPING); } return work_done; } irqreturn_t t1_interrupt(int irq, void *data) { struct adapter *adapter = data; struct sge *sge = adapter->sge; int handled; if (likely(responses_pending(adapter))) { struct net_device *dev = sge->netdev; writel(F_PL_INTR_SGE_DATA, adapter->regs + A_PL_CAUSE); if (napi_schedule_prep(&adapter->napi)) { if (process_pure_responses(adapter)) __netif_rx_schedule(dev, &adapter->napi); else { /* no data, no NAPI needed */ writel(sge->respQ.cidx, adapter->regs + A_SG_SLEEPING); /* undo schedule_prep */ napi_enable(&adapter->napi); } } return IRQ_HANDLED; } spin_lock(&adapter->async_lock); handled = t1_slow_intr_handler(adapter); spin_unlock(&adapter->async_lock); if (!handled) sge->stats.unhandled_irqs++; return IRQ_RETVAL(handled != 0); } /* * Enqueues the sk_buff onto the cmdQ[qid] and has hardware fetch it. * * The code figures out how many entries the sk_buff will require in the * cmdQ and updates the cmdQ data structure with the state once the enqueue * has complete. Then, it doesn't access the global structure anymore, but * uses the corresponding fields on the stack. In conjuction with a spinlock * around that code, we can make the function reentrant without holding the * lock when we actually enqueue (which might be expensive, especially on * architectures with IO MMUs). * * This runs with softirqs disabled. */ static int t1_sge_tx(struct sk_buff *skb, struct adapter *adapter, unsigned int qid, struct net_device *dev) { struct sge *sge = adapter->sge; struct cmdQ *q = &sge->cmdQ[qid]; unsigned int credits, pidx, genbit, count, use_sched_skb = 0; if (!spin_trylock(&q->lock)) return NETDEV_TX_LOCKED; reclaim_completed_tx(sge, q); pidx = q->pidx; credits = q->size - q->in_use; count = 1 + skb_shinfo(skb)->nr_frags; count += compute_large_page_tx_descs(skb); /* Ethernet packet */ if (unlikely(credits < count)) { if (!netif_queue_stopped(dev)) { netif_stop_queue(dev); set_bit(dev->if_port, &sge->stopped_tx_queues); sge->stats.cmdQ_full[2]++; CH_ERR("%s: Tx ring full while queue awake!\n", adapter->name); } spin_unlock(&q->lock); return NETDEV_TX_BUSY; } if (unlikely(credits - count < q->stop_thres)) { netif_stop_queue(dev); set_bit(dev->if_port, &sge->stopped_tx_queues); sge->stats.cmdQ_full[2]++; } /* T204 cmdQ0 skbs that are destined for a certain port have to go * through the scheduler. */ if (sge->tx_sched && !qid && skb->dev) { use_sched: use_sched_skb = 1; /* Note that the scheduler might return a different skb than * the one passed in. */ skb = sched_skb(sge, skb, credits); if (!skb) { spin_unlock(&q->lock); return NETDEV_TX_OK; } pidx = q->pidx; count = 1 + skb_shinfo(skb)->nr_frags; count += compute_large_page_tx_descs(skb); } q->in_use += count; genbit = q->genbit; pidx = q->pidx; q->pidx += count; if (q->pidx >= q->size) { q->pidx -= q->size; q->genbit ^= 1; } spin_unlock(&q->lock); write_tx_descs(adapter, skb, pidx, genbit, q); /* * We always ring the doorbell for cmdQ1. For cmdQ0, we only ring * the doorbell if the Q is asleep. There is a natural race, where * the hardware is going to sleep just after we checked, however, * then the interrupt handler will detect the outstanding TX packet * and ring the doorbell for us. */ if (qid) doorbell_pio(adapter, F_CMDQ1_ENABLE); else { clear_bit(CMDQ_STAT_LAST_PKT_DB, &q->status); if (test_and_set_bit(CMDQ_STAT_RUNNING, &q->status) == 0) { set_bit(CMDQ_STAT_LAST_PKT_DB, &q->status); writel(F_CMDQ0_ENABLE, adapter->regs + A_SG_DOORBELL); } } if (use_sched_skb) { if (spin_trylock(&q->lock)) { credits = q->size - q->in_use; skb = NULL; goto use_sched; } } return NETDEV_TX_OK; } #define MK_ETH_TYPE_MSS(type, mss) (((mss) & 0x3FFF) | ((type) << 14)) /* * eth_hdr_len - return the length of an Ethernet header * @data: pointer to the start of the Ethernet header * * Returns the length of an Ethernet header, including optional VLAN tag. */ static inline int eth_hdr_len(const void *data) { const struct ethhdr *e = data; return e->h_proto == htons(ETH_P_8021Q) ? VLAN_ETH_HLEN : ETH_HLEN; } /* * Adds the CPL header to the sk_buff and passes it to t1_sge_tx. */ int t1_start_xmit(struct sk_buff *skb, struct net_device *dev) { struct adapter *adapter = dev->priv; struct sge *sge = adapter->sge; struct sge_port_stats *st = per_cpu_ptr(sge->port_stats[dev->if_port], smp_processor_id()); struct cpl_tx_pkt *cpl; struct sk_buff *orig_skb = skb; int ret; if (skb->protocol == htons(ETH_P_CPL5)) goto send; /* * We are using a non-standard hard_header_len. * Allocate more header room in the rare cases it is not big enough. */ if (unlikely(skb_headroom(skb) < dev->hard_header_len - ETH_HLEN)) { skb = skb_realloc_headroom(skb, sizeof(struct cpl_tx_pkt_lso)); ++st->tx_need_hdrroom; dev_kfree_skb_any(orig_skb); if (!skb) return NETDEV_TX_OK; } if (skb_shinfo(skb)->gso_size) { int eth_type; struct cpl_tx_pkt_lso *hdr; ++st->tx_tso; eth_type = skb_network_offset(skb) == ETH_HLEN ? CPL_ETH_II : CPL_ETH_II_VLAN; hdr = (struct cpl_tx_pkt_lso *)skb_push(skb, sizeof(*hdr)); hdr->opcode = CPL_TX_PKT_LSO; hdr->ip_csum_dis = hdr->l4_csum_dis = 0; hdr->ip_hdr_words = ip_hdr(skb)->ihl; hdr->tcp_hdr_words = tcp_hdr(skb)->doff; hdr->eth_type_mss = htons(MK_ETH_TYPE_MSS(eth_type, skb_shinfo(skb)->gso_size)); hdr->len = htonl(skb->len - sizeof(*hdr)); cpl = (struct cpl_tx_pkt *)hdr; } else { /* * Packets shorter than ETH_HLEN can break the MAC, drop them * early. Also, we may get oversized packets because some * parts of the kernel don't handle our unusual hard_header_len * right, drop those too. */ if (unlikely(skb->len < ETH_HLEN || skb->len > dev->mtu + eth_hdr_len(skb->data))) { pr_debug("%s: packet size %d hdr %d mtu%d\n", dev->name, skb->len, eth_hdr_len(skb->data), dev->mtu); dev_kfree_skb_any(skb); return NETDEV_TX_OK; } if (!(adapter->flags & UDP_CSUM_CAPABLE) && skb->ip_summed == CHECKSUM_PARTIAL && ip_hdr(skb)->protocol == IPPROTO_UDP) { if (unlikely(skb_checksum_help(skb))) { pr_debug("%s: unable to do udp checksum\n", dev->name); dev_kfree_skb_any(skb); return NETDEV_TX_OK; } } /* Hmmm, assuming to catch the gratious arp... and we'll use * it to flush out stuck espi packets... */ if ((unlikely(!adapter->sge->espibug_skb[dev->if_port]))) { if (skb->protocol == htons(ETH_P_ARP) && arp_hdr(skb)->ar_op == htons(ARPOP_REQUEST)) { adapter->sge->espibug_skb[dev->if_port] = skb; /* We want to re-use this skb later. We * simply bump the reference count and it * will not be freed... */ skb = skb_get(skb); } } cpl = (struct cpl_tx_pkt *)__skb_push(skb, sizeof(*cpl)); cpl->opcode = CPL_TX_PKT; cpl->ip_csum_dis = 1; /* SW calculates IP csum */ cpl->l4_csum_dis = skb->ip_summed == CHECKSUM_PARTIAL ? 0 : 1; /* the length field isn't used so don't bother setting it */ st->tx_cso += (skb->ip_summed == CHECKSUM_PARTIAL); } cpl->iff = dev->if_port; #if defined(CONFIG_VLAN_8021Q) || defined(CONFIG_VLAN_8021Q_MODULE) if (adapter->vlan_grp && vlan_tx_tag_present(skb)) { cpl->vlan_valid = 1; cpl->vlan = htons(vlan_tx_tag_get(skb)); st->vlan_insert++; } else #endif cpl->vlan_valid = 0; send: dev->trans_start = jiffies; ret = t1_sge_tx(skb, adapter, 0, dev); /* If transmit busy, and we reallocated skb's due to headroom limit, * then silently discard to avoid leak. */ if (unlikely(ret != NETDEV_TX_OK && skb != orig_skb)) { dev_kfree_skb_any(skb); ret = NETDEV_TX_OK; } return ret; } /* * Callback for the Tx buffer reclaim timer. Runs with softirqs disabled. */ static void sge_tx_reclaim_cb(unsigned long data) { int i; struct sge *sge = (struct sge *)data; for (i = 0; i < SGE_CMDQ_N; ++i) { struct cmdQ *q = &sge->cmdQ[i]; if (!spin_trylock(&q->lock)) continue; reclaim_completed_tx(sge, q); if (i == 0 && q->in_use) { /* flush pending credits */ writel(F_CMDQ0_ENABLE, sge->adapter->regs + A_SG_DOORBELL); } spin_unlock(&q->lock); } mod_timer(&sge->tx_reclaim_timer, jiffies + TX_RECLAIM_PERIOD); } /* * Propagate changes of the SGE coalescing parameters to the HW. */ int t1_sge_set_coalesce_params(struct sge *sge, struct sge_params *p) { sge->fixed_intrtimer = p->rx_coalesce_usecs * core_ticks_per_usec(sge->adapter); writel(sge->fixed_intrtimer, sge->adapter->regs + A_SG_INTRTIMER); return 0; } /* * Allocates both RX and TX resources and configures the SGE. However, * the hardware is not enabled yet. */ int t1_sge_configure(struct sge *sge, struct sge_params *p) { if (alloc_rx_resources(sge, p)) return -ENOMEM; if (alloc_tx_resources(sge, p)) { free_rx_resources(sge); return -ENOMEM; } configure_sge(sge, p); /* * Now that we have sized the free lists calculate the payload * capacity of the large buffers. Other parts of the driver use * this to set the max offload coalescing size so that RX packets * do not overflow our large buffers. */ p->large_buf_capacity = jumbo_payload_capacity(sge); return 0; } /* * Disables the DMA engine. */ void t1_sge_stop(struct sge *sge) { int i; writel(0, sge->adapter->regs + A_SG_CONTROL); readl(sge->adapter->regs + A_SG_CONTROL); /* flush */ if (is_T2(sge->adapter)) del_timer_sync(&sge->espibug_timer); del_timer_sync(&sge->tx_reclaim_timer); if (sge->tx_sched) tx_sched_stop(sge); for (i = 0; i < MAX_NPORTS; i++) if (sge->espibug_skb[i]) kfree_skb(sge->espibug_skb[i]); } /* * Enables the DMA engine. */ void t1_sge_start(struct sge *sge) { refill_free_list(sge, &sge->freelQ[0]); refill_free_list(sge, &sge->freelQ[1]); writel(sge->sge_control, sge->adapter->regs + A_SG_CONTROL); doorbell_pio(sge->adapter, F_FL0_ENABLE | F_FL1_ENABLE); readl(sge->adapter->regs + A_SG_CONTROL); /* flush */ mod_timer(&sge->tx_reclaim_timer, jiffies + TX_RECLAIM_PERIOD); if (is_T2(sge->adapter)) mod_timer(&sge->espibug_timer, jiffies + sge->espibug_timeout); } /* * Callback for the T2 ESPI 'stuck packet feature' workaorund */ static void espibug_workaround_t204(unsigned long data) { struct adapter *adapter = (struct adapter *)data; struct sge *sge = adapter->sge; unsigned int nports = adapter->params.nports; u32 seop[MAX_NPORTS]; if (adapter->open_device_map & PORT_MASK) { int i; if (t1_espi_get_mon_t204(adapter, &(seop[0]), 0) < 0) return; for (i = 0; i < nports; i++) { struct sk_buff *skb = sge->espibug_skb[i]; if (!netif_running(adapter->port[i].dev) || netif_queue_stopped(adapter->port[i].dev) || !seop[i] || ((seop[i] & 0xfff) != 0) || !skb) continue; if (!skb->cb[0]) { u8 ch_mac_addr[ETH_ALEN] = { 0x0, 0x7, 0x43, 0x0, 0x0, 0x0 }; skb_copy_to_linear_data_offset(skb, sizeof(struct cpl_tx_pkt), ch_mac_addr, ETH_ALEN); skb_copy_to_linear_data_offset(skb, skb->len - 10, ch_mac_addr, ETH_ALEN); skb->cb[0] = 0xff; } /* bump the reference count to avoid freeing of * the skb once the DMA has completed. */ skb = skb_get(skb); t1_sge_tx(skb, adapter, 0, adapter->port[i].dev); } } mod_timer(&sge->espibug_timer, jiffies + sge->espibug_timeout); } static void espibug_workaround(unsigned long data) { struct adapter *adapter = (struct adapter *)data; struct sge *sge = adapter->sge; if (netif_running(adapter->port[0].dev)) { struct sk_buff *skb = sge->espibug_skb[0]; u32 seop = t1_espi_get_mon(adapter, 0x930, 0); if ((seop & 0xfff0fff) == 0xfff && skb) { if (!skb->cb[0]) { u8 ch_mac_addr[ETH_ALEN] = {0x0, 0x7, 0x43, 0x0, 0x0, 0x0}; skb_copy_to_linear_data_offset(skb, sizeof(struct cpl_tx_pkt), ch_mac_addr, ETH_ALEN); skb_copy_to_linear_data_offset(skb, skb->len - 10, ch_mac_addr, ETH_ALEN); skb->cb[0] = 0xff; } /* bump the reference count to avoid freeing of the * skb once the DMA has completed. */ skb = skb_get(skb); t1_sge_tx(skb, adapter, 0, adapter->port[0].dev); } } mod_timer(&sge->espibug_timer, jiffies + sge->espibug_timeout); } /* * Creates a t1_sge structure and returns suggested resource parameters. */ struct sge * __devinit t1_sge_create(struct adapter *adapter, struct sge_params *p) { struct sge *sge = kzalloc(sizeof(*sge), GFP_KERNEL); int i; if (!sge) return NULL; sge->adapter = adapter; sge->netdev = adapter->port[0].dev; sge->rx_pkt_pad = t1_is_T1B(adapter) ? 0 : 2; sge->jumbo_fl = t1_is_T1B(adapter) ? 1 : 0; for_each_port(adapter, i) { sge->port_stats[i] = alloc_percpu(struct sge_port_stats); if (!sge->port_stats[i]) goto nomem_port; } init_timer(&sge->tx_reclaim_timer); sge->tx_reclaim_timer.data = (unsigned long)sge; sge->tx_reclaim_timer.function = sge_tx_reclaim_cb; if (is_T2(sge->adapter)) { init_timer(&sge->espibug_timer); if (adapter->params.nports > 1) { tx_sched_init(sge); sge->espibug_timer.function = espibug_workaround_t204; } else sge->espibug_timer.function = espibug_workaround; sge->espibug_timer.data = (unsigned long)sge->adapter; sge->espibug_timeout = 1; /* for T204, every 10ms */ if (adapter->params.nports > 1) sge->espibug_timeout = HZ/100; } p->cmdQ_size[0] = SGE_CMDQ0_E_N; p->cmdQ_size[1] = SGE_CMDQ1_E_N; p->freelQ_size[!sge->jumbo_fl] = SGE_FREEL_SIZE; p->freelQ_size[sge->jumbo_fl] = SGE_JUMBO_FREEL_SIZE; if (sge->tx_sched) { if (board_info(sge->adapter)->board == CHBT_BOARD_CHT204) p->rx_coalesce_usecs = 15; else p->rx_coalesce_usecs = 50; } else p->rx_coalesce_usecs = 50; p->coalesce_enable = 0; p->sample_interval_usecs = 0; return sge; nomem_port: while (i >= 0) { free_percpu(sge->port_stats[i]); --i; } kfree(sge); return NULL; }
kzlin129/tt-gpl
go12/linux-2.6.28.10/drivers/net/chelsio/sge.c
C
gpl-2.0
59,944
/* * reserved comment block * DO NOT REMOVE OR ALTER! */ /* * 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 com.sun.org.apache.xml.internal.utils; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.URL; import java.net.URLConnection; import javax.xml.transform.ErrorListener; import javax.xml.transform.SourceLocator; import javax.xml.transform.TransformerException; import com.sun.org.apache.xml.internal.res.XMLErrorResources; import com.sun.org.apache.xml.internal.res.XMLMessages; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; /** * Sample implementation of similar SAX ErrorHandler and JAXP ErrorListener. * * <p>This implementation is suitable for various use cases, and * provides some basic configuration API's as well to control * when we re-throw errors, etc.</p> * * @author shane_curcuru@us.ibm.com * @xsl.usage general */ public class ListingErrorHandler implements ErrorHandler, ErrorListener { protected PrintWriter m_pw = null; /** * Constructor ListingErrorHandler; user-supplied PrintWriter. */ public ListingErrorHandler(PrintWriter pw) { if (null == pw) throw new NullPointerException(XMLMessages.createXMLMessage(XMLErrorResources.ER_ERRORHANDLER_CREATED_WITH_NULL_PRINTWRITER, null)); // "ListingErrorHandler created with null PrintWriter!"); m_pw = pw; } /** * Constructor ListingErrorHandler; uses System.err. */ public ListingErrorHandler() { m_pw = new PrintWriter(System.err, true); } /* ======== Implement org.xml.sax.ErrorHandler ======== */ /** * Receive notification of a warning. * * <p>SAX parsers will use this method to report conditions that * are not errors or fatal errors as defined by the XML 1.0 * recommendation. The default behaviour is to take no action.</p> * * <p>The SAX parser must continue to provide normal parsing events * after invoking this method: it should still be possible for the * application to process the document through to the end.</p> * * <p>Filters may use this method to report other, non-XML warnings * as well.</p> * * @param exception The warning information encapsulated in a * SAX parse exception. * @exception org.xml.sax.SAXException Any SAX exception, possibly * wrapping another exception; only if setThrowOnWarning is true. * @see org.xml.sax.SAXParseException */ public void warning (SAXParseException exception) throws SAXException { logExceptionLocation(m_pw, exception); // Note: should we really call .toString() below, since // sometimes the message is not properly set? m_pw.println("warning: " + exception.getMessage()); m_pw.flush(); if (getThrowOnWarning()) throw exception; } /** * Receive notification of a recoverable error. * * <p>This corresponds to the definition of "error" in section 1.2 * of the W3C XML 1.0 Recommendation. For example, a validating * parser would use this callback to report the violation of a * validity constraint. The default behaviour is to take no * action.</p> * * <p>The SAX parser must continue to provide normal parsing events * after invoking this method: it should still be possible for the * application to process the document through to the end. If the * application cannot do so, then the parser should report a fatal * error even if the XML 1.0 recommendation does not require it to * do so.</p> * * <p>Filters may use this method to report other, non-XML errors * as well.</p> * * @param exception The error information encapsulated in a * SAX parse exception. * @exception org.xml.sax.SAXException Any SAX exception, possibly * wrapping another exception; only if setThrowOnErroris true. * @see org.xml.sax.SAXParseException */ public void error (SAXParseException exception) throws SAXException { logExceptionLocation(m_pw, exception); m_pw.println("error: " + exception.getMessage()); m_pw.flush(); if (getThrowOnError()) throw exception; } /** * Receive notification of a non-recoverable error. * * <p>This corresponds to the definition of "fatal error" in * section 1.2 of the W3C XML 1.0 Recommendation. For example, a * parser would use this callback to report the violation of a * well-formedness constraint.</p> * * <p>The application must assume that the document is unusable * after the parser has invoked this method, and should continue * (if at all) only for the sake of collecting addition error * messages: in fact, SAX parsers are free to stop reporting any * other events once this method has been invoked.</p> * * @param exception The error information encapsulated in a * SAX parse exception. * @exception org.xml.sax.SAXException Any SAX exception, possibly * wrapping another exception; only if setThrowOnFatalError is true. * @see org.xml.sax.SAXParseException */ public void fatalError (SAXParseException exception) throws SAXException { logExceptionLocation(m_pw, exception); m_pw.println("fatalError: " + exception.getMessage()); m_pw.flush(); if (getThrowOnFatalError()) throw exception; } /* ======== Implement javax.xml.transform.ErrorListener ======== */ /** * Receive notification of a warning. * * <p>{@link javax.xml.transform.Transformer} can use this method to report * conditions that are not errors or fatal errors. The default behaviour * is to take no action.</p> * * <p>After invoking this method, the Transformer must continue with * the transformation. It should still be possible for the * application to process the document through to the end.</p> * * @param exception The warning information encapsulated in a * transformer exception. * * @throws javax.xml.transform.TransformerException only if * setThrowOnWarning is true. * * @see javax.xml.transform.TransformerException */ public void warning(TransformerException exception) throws TransformerException { logExceptionLocation(m_pw, exception); m_pw.println("warning: " + exception.getMessage()); m_pw.flush(); if (getThrowOnWarning()) throw exception; } /** * Receive notification of a recoverable error. * * <p>The transformer must continue to try and provide normal transformation * after invoking this method. It should still be possible for the * application to process the document through to the end if no other errors * are encountered.</p> * * @param exception The error information encapsulated in a * transformer exception. * * @throws javax.xml.transform.TransformerException only if * setThrowOnError is true. * * @see javax.xml.transform.TransformerException */ public void error(TransformerException exception) throws TransformerException { logExceptionLocation(m_pw, exception); m_pw.println("error: " + exception.getMessage()); m_pw.flush(); if (getThrowOnError()) throw exception; } /** * Receive notification of a non-recoverable error. * * <p>The transformer must continue to try and provide normal transformation * after invoking this method. It should still be possible for the * application to process the document through to the end if no other errors * are encountered, but there is no guarantee that the output will be * useable.</p> * * @param exception The error information encapsulated in a * transformer exception. * * @throws javax.xml.transform.TransformerException only if * setThrowOnError is true. * * @see javax.xml.transform.TransformerException */ public void fatalError(TransformerException exception) throws TransformerException { logExceptionLocation(m_pw, exception); m_pw.println("error: " + exception.getMessage()); m_pw.flush(); if (getThrowOnError()) throw exception; } /* ======== Implement worker methods ======== */ /** * Print out location information about the exception. * * Cribbed from DefaultErrorHandler.printLocation() * @param pw PrintWriter to send output to * @param exception TransformerException or SAXParseException * to log information about */ public static void logExceptionLocation(PrintWriter pw, Throwable exception) { if (null == pw) pw = new PrintWriter(System.err, true); SourceLocator locator = null; Throwable cause = exception; // Try to find the locator closest to the cause. do { // Find the current locator, if one present if(cause instanceof SAXParseException) { // A SAXSourceLocator is a Xalan helper class // that implements both a SourceLocator and a SAX Locator //@todo check that the new locator actually has // as much or more information as the // current one already does locator = new SAXSourceLocator((SAXParseException)cause); } else if (cause instanceof TransformerException) { SourceLocator causeLocator = ((TransformerException)cause).getLocator(); if(null != causeLocator) { locator = causeLocator; } } // Then walk back down the chain of exceptions if(cause instanceof TransformerException) cause = ((TransformerException)cause).getCause(); else if(cause instanceof WrappedRuntimeException) cause = ((WrappedRuntimeException)cause).getException(); else if(cause instanceof SAXException) cause = ((SAXException)cause).getException(); else cause = null; } while(null != cause); // Formatting note: mimic javac-like errors: // path\filename:123: message-here // systemId:L=1;C=2: message-here if(null != locator) { String id = (locator.getPublicId() != locator.getPublicId()) ? locator.getPublicId() : (null != locator.getSystemId()) ? locator.getSystemId() : "SystemId-Unknown"; pw.print(id + ":Line=" + locator.getLineNumber() + ";Column=" + locator.getColumnNumber()+": "); pw.println("exception:" + exception.getMessage()); pw.println("root-cause:" + ((null != cause) ? cause.getMessage() : "null")); logSourceLine(pw, locator); } else { pw.print("SystemId-Unknown:locator-unavailable: "); pw.println("exception:" + exception.getMessage()); pw.println("root-cause:" + ((null != cause) ? cause.getMessage() : "null")); } } /** * Print out the specific source line that caused the exception, * if possible to load it. * * @param pw PrintWriter to send output to * @param locator Xalan wrapper for either a JAXP or a SAX * source location object */ public static void logSourceLine(PrintWriter pw, SourceLocator locator) { if (null == locator) return; if (null == pw) pw = new PrintWriter(System.err, true); String url = locator.getSystemId(); // Bail immediately if we get SystemId-Unknown //@todo future improvement: attempt to get resource // from a publicId if possible if (null == url) { pw.println("line: (No systemId; cannot read file)"); pw.println(); return; } //@todo attempt to get DOM backpointer or other ids try { int line = locator.getLineNumber(); int column = locator.getColumnNumber(); pw.println("line: " + getSourceLine(url, line)); StringBuffer buf = new StringBuffer("line: "); for (int i = 1; i < column; i++) { buf.append(' '); } buf.append('^'); pw.println(buf.toString()); } catch (Exception e) { pw.println("line: logSourceLine unavailable due to: " + e.getMessage()); pw.println(); } } /** * Return the specific source line that caused the exception, * if possible to load it; allow exceptions to be thrown. * * @author shane_curcuru@us.ibm.com */ protected static String getSourceLine(String sourceUrl, int lineNum) throws Exception { URL url = null; // Get a URL from the sourceUrl try { // Try to get a URL from it as-is url = new URL(sourceUrl); } catch (java.net.MalformedURLException mue) { int indexOfColon = sourceUrl.indexOf(':'); int indexOfSlash = sourceUrl.indexOf('/'); if ((indexOfColon != -1) && (indexOfSlash != -1) && (indexOfColon < indexOfSlash)) { // The url is already absolute, but we could not get // the system to form it, so bail throw mue; } else { // The url is relative, so attempt to get absolute url = new URL(SystemIDResolver.getAbsoluteURI(sourceUrl)); // If this fails, allow the exception to propagate } } String line = null; InputStream is = null; BufferedReader br = null; try { // Open the URL and read to our specified line URLConnection uc = url.openConnection(); is = uc.getInputStream(); br = new BufferedReader(new InputStreamReader(is)); // Not the most efficient way, but it works // (Feel free to patch to seek to the appropriate line) for (int i = 1; i <= lineNum; i++) { line = br.readLine(); } } // Allow exceptions to propagate from here, but ensure // streams are closed! finally { br.close(); is.close(); } // Return whatever we found return line; } /* ======== Implement settable properties ======== */ /** * User-settable behavior: when to re-throw exceptions. * * <p>This allows per-instance configuration of * ListingErrorHandlers. You can ask us to either throw * an exception when we're called for various warning / * error / fatalErrors, or simply log them and continue.</p> * * @param b if we should throw an exception on warnings */ public void setThrowOnWarning(boolean b) { throwOnWarning = b; } /** * User-settable behavior: when to re-throw exceptions. * * @return if we throw an exception on warnings */ public boolean getThrowOnWarning() { return throwOnWarning; } /** If we should throw exception on warnings; default:false. */ protected boolean throwOnWarning = false; /** * User-settable behavior: when to re-throw exceptions. * * <p>This allows per-instance configuration of * ListingErrorHandlers. You can ask us to either throw * an exception when we're called for various warning / * error / fatalErrors, or simply log them and continue.</p> * * <p>Note that the behavior of many parsers/transformers * after an error is not necessarily defined!</p> * * @param b if we should throw an exception on errors */ public void setThrowOnError(boolean b) { throwOnError = b; } /** * User-settable behavior: when to re-throw exceptions. * * @return if we throw an exception on errors */ public boolean getThrowOnError() { return throwOnError; } /** If we should throw exception on errors; default:true. */ protected boolean throwOnError = true; /** * User-settable behavior: when to re-throw exceptions. * * <p>This allows per-instance configuration of * ListingErrorHandlers. You can ask us to either throw * an exception when we're called for various warning / * error / fatalErrors, or simply log them and continue.</p> * * <p>Note that the behavior of many parsers/transformers * after a fatalError is not necessarily defined, most * products will probably barf if you continue.</p> * * @param b if we should throw an exception on fatalErrors */ public void setThrowOnFatalError(boolean b) { throwOnFatalError = b; } /** * User-settable behavior: when to re-throw exceptions. * * @return if we throw an exception on fatalErrors */ public boolean getThrowOnFatalError() { return throwOnFatalError; } /** If we should throw exception on fatalErrors; default:true. */ protected boolean throwOnFatalError = true; }
md-5/jdk10
src/java.xml/share/classes/com/sun/org/apache/xml/internal/utils/ListingErrorHandler.java
Java
gpl-2.0
18,873
/* * Copyright (C) 2011-2014 MediaTek Inc. * * This program is free software: you can redistribute it and/or modify it under the terms of the * GNU General Public License version 2 as published by the Free Software Foundation. * * 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/>. */ #ifdef BUILD_LK #include <stdio.h> #include <string.h> #else #include <linux/string.h> #include <linux/kernel.h> #endif #include "lcm_drv.h" #ifndef TRUE #define TRUE 1 #endif #ifndef FALSE #define FALSE 0 #endif #ifdef BUILD_LK #define LCM_PRINT printf #else #define LCM_PRINT pr_debug #endif // --------------------------------------------------------------------------- // Local Constants // --------------------------------------------------------------------------- #define FRAME_WIDTH (480) #define FRAME_HEIGHT (854) // --------------------------------------------------------------------------- // Local Variables // --------------------------------------------------------------------------- static LCM_UTIL_FUNCS lcm_util; static struct LCM_setting_table *para_init_table = NULL; static unsigned int para_init_size = 0; static LCM_PARAMS *para_params = NULL; static unsigned int lcm_driver_id = 0x0; static unsigned int lcm_module_id = 0x0; #define SET_RESET_PIN(v) (lcm_util.set_reset_pin((v))) #define UDELAY(n) (lcm_util.udelay(n)) #define MDELAY(n) (lcm_util.mdelay(n)) #define LCM_ID_NT35590 (0x90) // --------------------------------------------------------------------------- // Local Functions // --------------------------------------------------------------------------- #define dsi_set_cmdq_V2(cmd, count, ppara, force_update) lcm_util.dsi_set_cmdq_V2(cmd, count, ppara, force_update) #define dsi_set_cmdq(pdata, queue_size, force_update) lcm_util.dsi_set_cmdq(pdata, queue_size, force_update) #define read_reg_v2(cmd, buffer, buffer_size) lcm_util.dsi_dcs_read_lcm_reg_v2(cmd, buffer, buffer_size) static void push_table(struct LCM_setting_table *table, unsigned int count, unsigned char force_update) { unsigned int i; for(i = 0; i < count; i++) { unsigned cmd; cmd = table[i].cmd; switch (cmd) { case REGFLAG_DELAY : MDELAY(table[i].count); break; case REGFLAG_END_OF_TABLE : break; default: dsi_set_cmdq_V2(cmd, table[i].count, table[i].para_list, force_update); } } } // --------------------------------------------------------------------------- // LCM Driver Implementations // --------------------------------------------------------------------------- static void lcm_get_id(unsigned int* driver_id, unsigned int* module_id) { *driver_id = lcm_driver_id; *module_id = lcm_module_id; } static void lcm_set_util_funcs(const LCM_UTIL_FUNCS *util) { memcpy(&lcm_util, util, sizeof(LCM_UTIL_FUNCS)); } static void lcm_set_params(struct LCM_setting_table *init_table, unsigned int init_size, LCM_PARAMS *params) { para_init_table = init_table; para_init_size = init_size; para_params = params; } static void lcm_get_params(LCM_PARAMS *params) { memset(params, 0, sizeof(LCM_PARAMS)); if (para_params != NULL) { memcpy(params, para_params, sizeof(LCM_PARAMS)); } else { params->type = LCM_TYPE_DSI; params->width = FRAME_WIDTH; params->height = FRAME_HEIGHT; params->dsi.mode = CMD_MODE; params->dsi.LANE_NUM = LCM_THREE_LANE; params->dsi.data_format.format = LCM_DSI_FORMAT_RGB888; params->dsi.PS = LCM_PACKED_PS_24BIT_RGB888; params->dsi.PLL_CLOCK = 221; } } static void init_lcm_registers(void) { unsigned int data_array[16]; data_array[0]=0x00023902; data_array[1]=0x000008C2; dsi_set_cmdq(data_array, 2, 1); data_array[0]=0x00023902; data_array[1]=0x000002BA; dsi_set_cmdq(data_array, 2, 1); data_array[0]=0x00023902; data_array[1]=0x0000773A; dsi_set_cmdq(data_array, 2, 1); // ******************** EABLE DSI TE packet **************// data_array[0]=0x00351500; dsi_set_cmdq(data_array, 1, 1); data_array[0]=0x773a1500; dsi_set_cmdq(data_array, 1, 1); data_array[0]= 0x00053902; data_array[1]= 0x0100002a; data_array[2]= 0x000000df; dsi_set_cmdq(data_array, 3, 1); data_array[0]= 0x00053902; data_array[1]= 0x0300002b; data_array[2]= 0x00000055; dsi_set_cmdq(data_array, 3, 1); data_array[0] = 0x00110500; dsi_set_cmdq(data_array, 1, 1); MDELAY(120); data_array[0]= 0x00290500; dsi_set_cmdq(data_array, 1, 1); } static void lcm_init(void) { int i, j; int size; SET_RESET_PIN(1); SET_RESET_PIN(0); MDELAY(5); SET_RESET_PIN(1); MDELAY(20); if (para_init_table != NULL) { push_table(para_init_table, para_init_size, 1); } else { init_lcm_registers(); } } static void lcm_suspend(void) { unsigned int data_array[16]; data_array[0] = 0x00100500; dsi_set_cmdq(data_array, 1, 1); MDELAY(120); data_array[0] = 0x00280500; dsi_set_cmdq(data_array, 1, 1); MDELAY(10); data_array[0] = 0x014F1500; dsi_set_cmdq(data_array, 1, 1); MDELAY(40); } static void lcm_resume(void) { lcm_init(); } static void lcm_update(unsigned int x, unsigned int y, unsigned int width, unsigned int height) { unsigned int x0 = x; unsigned int y0 = y; unsigned int x1 = x0 + width - 1; unsigned int y1 = y0 + height - 1; unsigned char x0_MSB = ((x0>>8)&0xFF); unsigned char x0_LSB = (x0&0xFF); unsigned char x1_MSB = ((x1>>8)&0xFF); unsigned char x1_LSB = (x1&0xFF); unsigned char y0_MSB = ((y0>>8)&0xFF); unsigned char y0_LSB = (y0&0xFF); unsigned char y1_MSB = ((y1>>8)&0xFF); unsigned char y1_LSB = (y1&0xFF); unsigned int data_array[16]; data_array[0]= 0x00053902; data_array[1]= (x1_MSB<<24)|(x0_LSB<<16)|(x0_MSB<<8)|0x2a; data_array[2]= (x1_LSB); dsi_set_cmdq(data_array, 3, 1); data_array[0]= 0x00053902; data_array[1]= (y1_MSB<<24)|(y0_LSB<<16)|(y0_MSB<<8)|0x2b; data_array[2]= (y1_LSB); dsi_set_cmdq(data_array, 3, 1); data_array[0]= 0x002c3909; dsi_set_cmdq(data_array, 1, 0); } static void lcm_setbacklight(unsigned int level) { unsigned int data_array[16]; LCM_PRINT("lcm_setbacklight = %d\n", level); if (level > 255) level = 255; data_array[0]= 0x00023902; data_array[1] =(0x51|(level<<8)); dsi_set_cmdq(data_array, 2, 1); } static unsigned int lcm_compare_id(void) { unsigned int id=0; unsigned char buffer[2]; unsigned int array[16]; SET_RESET_PIN(1); SET_RESET_PIN(0); MDELAY(1); SET_RESET_PIN(1); MDELAY(20); array[0] = 0x00023700;// read id return two byte,version and id dsi_set_cmdq(array, 1, 1); read_reg_v2(0xF4, buffer, 2); id = buffer[0]; //we only need ID lcm_driver_id = id; // TBD lcm_module_id = 0x0; #ifdef BUILD_LK printf("%s, LK nt35590 debug: nt35590 id = 0x%08x\n", __func__, id); #else pr_debug("%s, kernel nt35590 horse debug: nt35590 id = 0x%08x\n", __func__, id); #endif if(id == LCM_ID_NT35590) return 1; else return 0; } // --------------------------------------------------------------------------- // Get LCM Driver Hooks // --------------------------------------------------------------------------- LCM_DRIVER nt35590_dsi_cmd_6571_fwvga_lcm_drv = { .name = "nt35590_dsi_cmd_6571_fwvga", .set_util_funcs = lcm_set_util_funcs, .set_params = lcm_set_params, .get_id = lcm_get_id, .get_params = lcm_get_params, .init = lcm_init, .suspend = lcm_suspend, .resume = lcm_resume, .set_backlight = lcm_setbacklight, .compare_id = lcm_compare_id, .update = lcm_update };
profglavcho/test
arch/arm/mach-mt6582/sprout/lcm/nt35590_dsi_cmd_6571_fwvga.c
C
gpl-2.0
8,397
/* * cynapses libc functions * * Copyright (c) 2008-2013 by Andreas Schneider <asn@cryptomilk.org> * * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file c_macro.h * * @brief cynapses libc macro definitions * * @defgroup cynMacroInternals cynapses libc macro definitions * @ingroup cynLibraryAPI * * @{ */ #ifndef _C_MACRO_H #define _C_MACRO_H #include <stdint.h> #include <string.h> #define INT_TO_POINTER(i) (void *) i #define POINTER_TO_INT(p) *((int *) (p)) /** Zero a structure */ #define ZERO_STRUCT(x) memset((char *)&(x), 0, sizeof(x)) /** Zero a structure given a pointer to the structure */ #define ZERO_STRUCTP(x) do { if ((x) != NULL) memset((char *)(x), 0, sizeof(*(x))); } while(0) /** Free memory and zero the pointer */ #define SAFE_FREE(x) do { if ((x) != NULL) {free((void*)x); x=NULL;} } while(0) /** Get the smaller value */ #define MIN(a,b) ((a) < (b) ? (a) : (b)) /** Get the bigger value */ #define MAX(a,b) ((a) < (b) ? (b) : (a)) /** Get the size of an array */ #define ARRAY_SIZE(a) (sizeof(a)/sizeof(a[0])) /** * This is a hack to fix warnings. The idea is to use this everywhere that we * get the "discarding const" warning by the compiler. That doesn't actually * fix the real issue, but marks the place and you can search the code for * discard_const. * * Please use this macro only when there is no other way to fix the warning. * We should use this function in only in a very few places. * * Also, please call this via the discard_const_p() macro interface, as that * makes the return type safe. */ #define discard_const(ptr) ((void *)((uintptr_t)(ptr))) /** * Type-safe version of discard_const */ #define discard_const_p(type, ptr) ((type *)discard_const(ptr)) #if (__GNUC__ >= 3) # ifndef likely # define likely(x) __builtin_expect(!!(x), 1) # endif # ifndef unlikely # define unlikely(x) __builtin_expect(!!(x), 0) # endif #else /* __GNUC__ */ # ifndef likely # define likely(x) (x) # endif # ifndef unlikely # define unlikely(x) (x) # endif #endif /* __GNUC__ */ /** * }@ */ #ifdef _WIN32 /* missing errno codes on mingw */ #ifndef ENOTBLK #define ENOTBLK 15 #endif #ifndef ETXTBSY #define ETXTBSY 26 #endif #ifndef ENOBUFS #define ENOBUFS WSAENOBUFS #endif #endif /* _WIN32 */ #endif /* _C_MACRO_H */
mnutt/owncloud-client
csync/src/std/c_macro.h
C
gpl-2.0
3,057
/* * Copyright (c) 2002, 2016, 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. */ import java.io.ByteArrayInputStream; import java.io.InputStream; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.Clip; import javax.sound.sampled.DataLine; import javax.sound.sampled.LineEvent; import javax.sound.sampled.LineListener; /** * @test * @bug 4498848 * @summary Sound causes crashes on Linux (part 1) */ public class ClipLinuxCrash { static Clip clip; public static long bytes2Ms(long bytes, AudioFormat format) { return (long) (bytes / format.getFrameRate() * 1000 / format.getFrameSize()); } static int staticLen = 1000; static boolean addLen = true; public static long start() throws Exception { AudioFormat fmt = new AudioFormat(44100, 16, 2, true, false); if (addLen) { staticLen += (int) (staticLen / 5) + 1000; } else { staticLen -= (int) (staticLen / 5) + 1000; } if (staticLen > 8 * 44100 * 4) { staticLen = 8 * 44100 * 4; addLen = !addLen; } if (staticLen < 1000) { staticLen = 1000; addLen = !addLen; } int len = staticLen; len -= (len % 4); byte[] fakedata = new byte[len]; InputStream is = new ByteArrayInputStream(fakedata); AudioFormat format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, 44100, 16, 2, 4, 44100, false); AudioInputStream ais = new AudioInputStream(is, format, fakedata.length / format.getFrameSize()); out(" preparing to play back " + len + " bytes == " + bytes2Ms(len, format) + "ms audio..."); DataLine.Info info = new DataLine.Info(Clip.class, ais.getFormat()); clip = (Clip) AudioSystem.getLine(info); clip.addLineListener(new LineListener() { public void update(LineEvent e) { if (e.getType() == LineEvent.Type.STOP) { out(" calling close() from event dispatcher thread"); ((Clip) e.getSource()).close(); } else if (e.getType() == LineEvent.Type.CLOSE) { } } }); out(" opening..."); try { clip.open(ais); } catch (Throwable t) { t.printStackTrace(); clip.close(); clip = null; } ais.close(); if (clip != null) { out(" starting..."); clip.start(); } return bytes2Ms(fakedata.length, format); } public static void main(String[] args) throws Exception { if (AudioSystem.getMixerInfo().length == 0) { System.out.println("Cannot execute test: no mixers installed!"); System.out.println("Not Failed."); return; } try { int COUNT = 10; out(); out("4498848 Sound causes crashes on Linux (testing with Clip)"); if (args.length > 0) { COUNT = Integer.parseInt(args[0]); } for (int i = 0; i < COUNT; i++) { out(" trial " + (i + 1) + "/" + COUNT); start(); int waitTime = 500 + (1000 * (i % 2)); // every second // time wait 1500, rather than 500ms. out(" waiting for " + waitTime + " ms for audio playback to stop..."); Thread.sleep(waitTime); out(" calling close() from main thread"); if (clip != null) { clip.close(); } // let the subsystem enough time to actually close the soundcard out(" waiting for 2 seconds..."); Thread.sleep(2000); out(); } out(" waiting for 1 second..."); Thread.sleep(1000); } catch (Exception e) { e.printStackTrace(); out(" waiting for 1 second"); try { Thread.sleep(1000); } catch (InterruptedException ie) { } throw e; } out("Test passed"); } static void out() { out(""); } static void out(String s) { System.out.println(s); System.out.flush(); } }
md-5/jdk10
test/jdk/javax/sound/sampled/LinuxCrash/ClipLinuxCrash.java
Java
gpl-2.0
5,675
// SPDX-License-Identifier: GPL-2.0 #include <subcmd/parse-options.h> #include "evsel.h" #include "cgroup.h" #include "evlist.h" #include "rblist.h" #include "metricgroup.h" #include "stat.h" #include <linux/zalloc.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdlib.h> #include <string.h> #include <api/fs/fs.h> #include <ftw.h> #include <regex.h> int nr_cgroups; /* used to match cgroup name with patterns */ struct cgroup_name { struct list_head list; bool used; char name[]; }; static LIST_HEAD(cgroup_list); static int open_cgroup(const char *name) { char path[PATH_MAX + 1]; char mnt[PATH_MAX + 1]; int fd; if (cgroupfs_find_mountpoint(mnt, PATH_MAX + 1, "perf_event")) return -1; scnprintf(path, PATH_MAX, "%s/%s", mnt, name); fd = open(path, O_RDONLY); if (fd == -1) fprintf(stderr, "no access to cgroup %s\n", path); return fd; } static struct cgroup *evlist__find_cgroup(struct evlist *evlist, const char *str) { struct evsel *counter; /* * check if cgrp is already defined, if so we reuse it */ evlist__for_each_entry(evlist, counter) { if (!counter->cgrp) continue; if (!strcmp(counter->cgrp->name, str)) return cgroup__get(counter->cgrp); } return NULL; } static struct cgroup *cgroup__new(const char *name, bool do_open) { struct cgroup *cgroup = zalloc(sizeof(*cgroup)); if (cgroup != NULL) { refcount_set(&cgroup->refcnt, 1); cgroup->name = strdup(name); if (!cgroup->name) goto out_err; if (do_open) { cgroup->fd = open_cgroup(name); if (cgroup->fd == -1) goto out_free_name; } else { cgroup->fd = -1; } } return cgroup; out_free_name: zfree(&cgroup->name); out_err: free(cgroup); return NULL; } struct cgroup *evlist__findnew_cgroup(struct evlist *evlist, const char *name) { struct cgroup *cgroup = evlist__find_cgroup(evlist, name); return cgroup ?: cgroup__new(name, true); } static int add_cgroup(struct evlist *evlist, const char *str) { struct evsel *counter; struct cgroup *cgrp = evlist__findnew_cgroup(evlist, str); int n; if (!cgrp) return -1; /* * find corresponding event * if add cgroup N, then need to find event N */ n = 0; evlist__for_each_entry(evlist, counter) { if (n == nr_cgroups) goto found; n++; } cgroup__put(cgrp); return -1; found: counter->cgrp = cgrp; return 0; } static void cgroup__delete(struct cgroup *cgroup) { if (cgroup->fd >= 0) close(cgroup->fd); zfree(&cgroup->name); free(cgroup); } void cgroup__put(struct cgroup *cgrp) { if (cgrp && refcount_dec_and_test(&cgrp->refcnt)) { cgroup__delete(cgrp); } } struct cgroup *cgroup__get(struct cgroup *cgroup) { if (cgroup) refcount_inc(&cgroup->refcnt); return cgroup; } static void evsel__set_default_cgroup(struct evsel *evsel, struct cgroup *cgroup) { if (evsel->cgrp == NULL) evsel->cgrp = cgroup__get(cgroup); } void evlist__set_default_cgroup(struct evlist *evlist, struct cgroup *cgroup) { struct evsel *evsel; evlist__for_each_entry(evlist, evsel) evsel__set_default_cgroup(evsel, cgroup); } /* helper function for ftw() in match_cgroups and list_cgroups */ static int add_cgroup_name(const char *fpath, const struct stat *sb __maybe_unused, int typeflag) { struct cgroup_name *cn; if (typeflag != FTW_D) return 0; cn = malloc(sizeof(*cn) + strlen(fpath) + 1); if (cn == NULL) return -1; cn->used = false; strcpy(cn->name, fpath); list_add_tail(&cn->list, &cgroup_list); return 0; } static void release_cgroup_list(void) { struct cgroup_name *cn; while (!list_empty(&cgroup_list)) { cn = list_first_entry(&cgroup_list, struct cgroup_name, list); list_del(&cn->list); free(cn); } } /* collect given cgroups only */ static int list_cgroups(const char *str) { const char *p, *e, *eos = str + strlen(str); struct cgroup_name *cn; char *s; /* use given name as is - for testing purpose */ for (;;) { p = strchr(str, ','); e = p ? p : eos; if (e - str) { int ret; s = strndup(str, e - str); if (!s) return -1; /* pretend if it's added by ftw() */ ret = add_cgroup_name(s, NULL, FTW_D); free(s); if (ret) return -1; } else { if (add_cgroup_name("", NULL, FTW_D) < 0) return -1; } if (!p) break; str = p+1; } /* these groups will be used */ list_for_each_entry(cn, &cgroup_list, list) cn->used = true; return 0; } /* collect all cgroups first and then match with the pattern */ static int match_cgroups(const char *str) { char mnt[PATH_MAX]; const char *p, *e, *eos = str + strlen(str); struct cgroup_name *cn; regex_t reg; int prefix_len; char *s; if (cgroupfs_find_mountpoint(mnt, sizeof(mnt), "perf_event")) return -1; /* cgroup_name will have a full path, skip the root directory */ prefix_len = strlen(mnt); /* collect all cgroups in the cgroup_list */ if (ftw(mnt, add_cgroup_name, 20) < 0) return -1; for (;;) { p = strchr(str, ','); e = p ? p : eos; /* allow empty cgroups, i.e., skip */ if (e - str) { /* termination added */ s = strndup(str, e - str); if (!s) return -1; if (regcomp(&reg, s, REG_NOSUB)) { free(s); return -1; } /* check cgroup name with the pattern */ list_for_each_entry(cn, &cgroup_list, list) { char *name = cn->name + prefix_len; if (name[0] == '/' && name[1]) name++; if (!regexec(&reg, name, 0, NULL, 0)) cn->used = true; } regfree(&reg); free(s); } else { /* first entry to root cgroup */ cn = list_first_entry(&cgroup_list, struct cgroup_name, list); cn->used = true; } if (!p) break; str = p+1; } return prefix_len; } int parse_cgroups(const struct option *opt, const char *str, int unset __maybe_unused) { struct evlist *evlist = *(struct evlist **)opt->value; struct evsel *counter; struct cgroup *cgrp = NULL; const char *p, *e, *eos = str + strlen(str); char *s; int ret, i; if (list_empty(&evlist->core.entries)) { fprintf(stderr, "must define events before cgroups\n"); return -1; } for (;;) { p = strchr(str, ','); e = p ? p : eos; /* allow empty cgroups, i.e., skip */ if (e - str) { /* termination added */ s = strndup(str, e - str); if (!s) return -1; ret = add_cgroup(evlist, s); free(s); if (ret) return -1; } /* nr_cgroups is increased een for empty cgroups */ nr_cgroups++; if (!p) break; str = p+1; } /* for the case one cgroup combine to multiple events */ i = 0; if (nr_cgroups == 1) { evlist__for_each_entry(evlist, counter) { if (i == 0) cgrp = counter->cgrp; else { counter->cgrp = cgrp; refcount_inc(&cgrp->refcnt); } i++; } } return 0; } static bool has_pattern_string(const char *str) { return !!strpbrk(str, "{}[]()|*+?^$"); } int evlist__expand_cgroup(struct evlist *evlist, const char *str, struct rblist *metric_events, bool open_cgroup) { struct evlist *orig_list, *tmp_list; struct evsel *pos, *evsel, *leader; struct rblist orig_metric_events; struct cgroup *cgrp = NULL; struct cgroup_name *cn; int ret = -1; int prefix_len; if (evlist->core.nr_entries == 0) { fprintf(stderr, "must define events before cgroups\n"); return -EINVAL; } orig_list = evlist__new(); tmp_list = evlist__new(); if (orig_list == NULL || tmp_list == NULL) { fprintf(stderr, "memory allocation failed\n"); return -ENOMEM; } /* save original events and init evlist */ evlist__splice_list_tail(orig_list, &evlist->core.entries); evlist->core.nr_entries = 0; if (metric_events) { orig_metric_events = *metric_events; rblist__init(metric_events); } else { rblist__init(&orig_metric_events); } if (has_pattern_string(str)) prefix_len = match_cgroups(str); else prefix_len = list_cgroups(str); if (prefix_len < 0) goto out_err; list_for_each_entry(cn, &cgroup_list, list) { char *name; if (!cn->used) continue; /* cgroup_name might have a full path, skip the prefix */ name = cn->name + prefix_len; if (name[0] == '/' && name[1]) name++; cgrp = cgroup__new(name, open_cgroup); if (cgrp == NULL) goto out_err; leader = NULL; evlist__for_each_entry(orig_list, pos) { evsel = evsel__clone(pos); if (evsel == NULL) goto out_err; cgroup__put(evsel->cgrp); evsel->cgrp = cgroup__get(cgrp); if (evsel__is_group_leader(pos)) leader = evsel; evsel->leader = leader; evlist__add(tmp_list, evsel); } /* cgroup__new() has a refcount, release it here */ cgroup__put(cgrp); nr_cgroups++; if (metric_events) { perf_stat__collect_metric_expr(tmp_list); if (metricgroup__copy_metric_events(tmp_list, cgrp, metric_events, &orig_metric_events) < 0) goto out_err; } evlist__splice_list_tail(evlist, &tmp_list->core.entries); tmp_list->core.nr_entries = 0; } if (list_empty(&evlist->core.entries)) { fprintf(stderr, "no cgroup matched: %s\n", str); goto out_err; } ret = 0; out_err: evlist__delete(orig_list); evlist__delete(tmp_list); rblist__exit(&orig_metric_events); release_cgroup_list(); return ret; } static struct cgroup *__cgroup__findnew(struct rb_root *root, uint64_t id, bool create, const char *path) { struct rb_node **p = &root->rb_node; struct rb_node *parent = NULL; struct cgroup *cgrp; while (*p != NULL) { parent = *p; cgrp = rb_entry(parent, struct cgroup, node); if (cgrp->id == id) return cgrp; if (cgrp->id < id) p = &(*p)->rb_left; else p = &(*p)->rb_right; } if (!create) return NULL; cgrp = malloc(sizeof(*cgrp)); if (cgrp == NULL) return NULL; cgrp->name = strdup(path); if (cgrp->name == NULL) { free(cgrp); return NULL; } cgrp->fd = -1; cgrp->id = id; refcount_set(&cgrp->refcnt, 1); rb_link_node(&cgrp->node, parent, p); rb_insert_color(&cgrp->node, root); return cgrp; } struct cgroup *cgroup__findnew(struct perf_env *env, uint64_t id, const char *path) { struct cgroup *cgrp; down_write(&env->cgroups.lock); cgrp = __cgroup__findnew(&env->cgroups.tree, id, true, path); up_write(&env->cgroups.lock); return cgrp; } struct cgroup *cgroup__find(struct perf_env *env, uint64_t id) { struct cgroup *cgrp; down_read(&env->cgroups.lock); cgrp = __cgroup__findnew(&env->cgroups.tree, id, false, NULL); up_read(&env->cgroups.lock); return cgrp; } void perf_env__purge_cgroups(struct perf_env *env) { struct rb_node *node; struct cgroup *cgrp; down_write(&env->cgroups.lock); while (!RB_EMPTY_ROOT(&env->cgroups.tree)) { node = rb_first(&env->cgroups.tree); cgrp = rb_entry(node, struct cgroup, node); rb_erase(node, &env->cgroups.tree); cgroup__put(cgrp); } up_write(&env->cgroups.lock); }
GuillaumeSeren/linux
tools/perf/util/cgroup.c
C
gpl-2.0
10,742
// SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause) /* Copyright (C) 2017-2018 Netronome Systems, Inc. */ #include <ctype.h> #include <errno.h> #include <getopt.h> #include <linux/bpf.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <bpf/bpf.h> #include <bpf/libbpf.h> #include "main.h" #define BATCH_LINE_LEN_MAX 65536 #define BATCH_ARG_NB_MAX 4096 const char *bin_name; static int last_argc; static char **last_argv; static int (*last_do_help)(int argc, char **argv); json_writer_t *json_wtr; bool pretty_output; bool json_output; bool show_pinned; bool block_mount; bool verifier_logs; bool relaxed_maps; struct pinned_obj_table prog_table; struct pinned_obj_table map_table; struct pinned_obj_table link_table; struct obj_refs_table refs_table; static void __noreturn clean_and_exit(int i) { if (json_output) jsonw_destroy(&json_wtr); exit(i); } void usage(void) { last_do_help(last_argc - 1, last_argv + 1); clean_and_exit(-1); } static int do_help(int argc, char **argv) { if (json_output) { jsonw_null(json_wtr); return 0; } fprintf(stderr, "Usage: %s [OPTIONS] OBJECT { COMMAND | help }\n" " %s batch file FILE\n" " %s version\n" "\n" " OBJECT := { prog | map | link | cgroup | perf | net | feature | btf | gen | struct_ops | iter }\n" " " HELP_SPEC_OPTIONS "\n" "", bin_name, bin_name, bin_name); return 0; } static int do_version(int argc, char **argv) { #ifdef HAVE_LIBBFD_SUPPORT const bool has_libbfd = true; #else const bool has_libbfd = false; #endif #ifdef BPFTOOL_WITHOUT_SKELETONS const bool has_skeletons = false; #else const bool has_skeletons = true; #endif if (json_output) { jsonw_start_object(json_wtr); /* root object */ jsonw_name(json_wtr, "version"); jsonw_printf(json_wtr, "\"%s\"", BPFTOOL_VERSION); jsonw_name(json_wtr, "features"); jsonw_start_object(json_wtr); /* features */ jsonw_bool_field(json_wtr, "libbfd", has_libbfd); jsonw_bool_field(json_wtr, "skeletons", has_skeletons); jsonw_end_object(json_wtr); /* features */ jsonw_end_object(json_wtr); /* root object */ } else { unsigned int nb_features = 0; printf("%s v%s\n", bin_name, BPFTOOL_VERSION); printf("features:"); if (has_libbfd) { printf(" libbfd"); nb_features++; } if (has_skeletons) printf("%s skeletons", nb_features++ ? "," : ""); printf("\n"); } return 0; } int cmd_select(const struct cmd *cmds, int argc, char **argv, int (*help)(int argc, char **argv)) { unsigned int i; last_argc = argc; last_argv = argv; last_do_help = help; if (argc < 1 && cmds[0].func) return cmds[0].func(argc, argv); for (i = 0; cmds[i].cmd; i++) { if (is_prefix(*argv, cmds[i].cmd)) { if (!cmds[i].func) { p_err("command '%s' is not supported in bootstrap mode", cmds[i].cmd); return -1; } return cmds[i].func(argc - 1, argv + 1); } } help(argc - 1, argv + 1); return -1; } bool is_prefix(const char *pfx, const char *str) { if (!pfx) return false; if (strlen(str) < strlen(pfx)) return false; return !memcmp(str, pfx, strlen(pfx)); } /* Last argument MUST be NULL pointer */ int detect_common_prefix(const char *arg, ...) { unsigned int count = 0; const char *ref; char msg[256]; va_list ap; snprintf(msg, sizeof(msg), "ambiguous prefix: '%s' could be '", arg); va_start(ap, arg); while ((ref = va_arg(ap, const char *))) { if (!is_prefix(arg, ref)) continue; count++; if (count > 1) strncat(msg, "' or '", sizeof(msg) - strlen(msg) - 1); strncat(msg, ref, sizeof(msg) - strlen(msg) - 1); } va_end(ap); strncat(msg, "'", sizeof(msg) - strlen(msg) - 1); if (count >= 2) { p_err("%s", msg); return -1; } return 0; } void fprint_hex(FILE *f, void *arg, unsigned int n, const char *sep) { unsigned char *data = arg; unsigned int i; for (i = 0; i < n; i++) { const char *pfx = ""; if (!i) /* nothing */; else if (!(i % 16)) fprintf(f, "\n"); else if (!(i % 8)) fprintf(f, " "); else pfx = sep; fprintf(f, "%s%02hhx", i ? pfx : "", data[i]); } } /* Split command line into argument vector. */ static int make_args(char *line, char *n_argv[], int maxargs, int cmd_nb) { static const char ws[] = " \t\r\n"; char *cp = line; int n_argc = 0; while (*cp) { /* Skip leading whitespace. */ cp += strspn(cp, ws); if (*cp == '\0') break; if (n_argc >= (maxargs - 1)) { p_err("too many arguments to command %d", cmd_nb); return -1; } /* Word begins with quote. */ if (*cp == '\'' || *cp == '"') { char quote = *cp++; n_argv[n_argc++] = cp; /* Find ending quote. */ cp = strchr(cp, quote); if (!cp) { p_err("unterminated quoted string in command %d", cmd_nb); return -1; } } else { n_argv[n_argc++] = cp; /* Find end of word. */ cp += strcspn(cp, ws); if (*cp == '\0') break; } /* Separate words. */ *cp++ = 0; } n_argv[n_argc] = NULL; return n_argc; } static int do_batch(int argc, char **argv); static const struct cmd cmds[] = { { "help", do_help }, { "batch", do_batch }, { "prog", do_prog }, { "map", do_map }, { "link", do_link }, { "cgroup", do_cgroup }, { "perf", do_perf }, { "net", do_net }, { "feature", do_feature }, { "btf", do_btf }, { "gen", do_gen }, { "struct_ops", do_struct_ops }, { "iter", do_iter }, { "version", do_version }, { 0 } }; static int do_batch(int argc, char **argv) { char buf[BATCH_LINE_LEN_MAX], contline[BATCH_LINE_LEN_MAX]; char *n_argv[BATCH_ARG_NB_MAX]; unsigned int lines = 0; int n_argc; FILE *fp; char *cp; int err; int i; if (argc < 2) { p_err("too few parameters for batch"); return -1; } else if (!is_prefix(*argv, "file")) { p_err("expected 'file', got: %s", *argv); return -1; } else if (argc > 2) { p_err("too many parameters for batch"); return -1; } NEXT_ARG(); if (!strcmp(*argv, "-")) fp = stdin; else fp = fopen(*argv, "r"); if (!fp) { p_err("Can't open file (%s): %s", *argv, strerror(errno)); return -1; } if (json_output) jsonw_start_array(json_wtr); while (fgets(buf, sizeof(buf), fp)) { cp = strchr(buf, '#'); if (cp) *cp = '\0'; if (strlen(buf) == sizeof(buf) - 1) { errno = E2BIG; break; } /* Append continuation lines if any (coming after a line ending * with '\' in the batch file). */ while ((cp = strstr(buf, "\\\n")) != NULL) { if (!fgets(contline, sizeof(contline), fp) || strlen(contline) == 0) { p_err("missing continuation line on command %d", lines); err = -1; goto err_close; } cp = strchr(contline, '#'); if (cp) *cp = '\0'; if (strlen(buf) + strlen(contline) + 1 > sizeof(buf)) { p_err("command %d is too long", lines); err = -1; goto err_close; } buf[strlen(buf) - 2] = '\0'; strcat(buf, contline); } n_argc = make_args(buf, n_argv, BATCH_ARG_NB_MAX, lines); if (!n_argc) continue; if (n_argc < 0) goto err_close; if (json_output) { jsonw_start_object(json_wtr); jsonw_name(json_wtr, "command"); jsonw_start_array(json_wtr); for (i = 0; i < n_argc; i++) jsonw_string(json_wtr, n_argv[i]); jsonw_end_array(json_wtr); jsonw_name(json_wtr, "output"); } err = cmd_select(cmds, n_argc, n_argv, do_help); if (json_output) jsonw_end_object(json_wtr); if (err) goto err_close; lines++; } if (errno && errno != ENOENT) { p_err("reading batch file failed: %s", strerror(errno)); err = -1; } else { if (!json_output) printf("processed %d commands\n", lines); err = 0; } err_close: if (fp != stdin) fclose(fp); if (json_output) jsonw_end_array(json_wtr); return err; } int main(int argc, char **argv) { static const struct option options[] = { { "json", no_argument, NULL, 'j' }, { "help", no_argument, NULL, 'h' }, { "pretty", no_argument, NULL, 'p' }, { "version", no_argument, NULL, 'V' }, { "bpffs", no_argument, NULL, 'f' }, { "mapcompat", no_argument, NULL, 'm' }, { "nomount", no_argument, NULL, 'n' }, { "debug", no_argument, NULL, 'd' }, { 0 } }; int opt, ret; last_do_help = do_help; pretty_output = false; json_output = false; show_pinned = false; block_mount = false; bin_name = argv[0]; hash_init(prog_table.table); hash_init(map_table.table); hash_init(link_table.table); opterr = 0; while ((opt = getopt_long(argc, argv, "Vhpjfmnd", options, NULL)) >= 0) { switch (opt) { case 'V': return do_version(argc, argv); case 'h': return do_help(argc, argv); case 'p': pretty_output = true; /* fall through */ case 'j': if (!json_output) { json_wtr = jsonw_new(stdout); if (!json_wtr) { p_err("failed to create JSON writer"); return -1; } json_output = true; } jsonw_pretty(json_wtr, pretty_output); break; case 'f': show_pinned = true; break; case 'm': relaxed_maps = true; break; case 'n': block_mount = true; break; case 'd': libbpf_set_print(print_all_levels); verifier_logs = true; break; default: p_err("unrecognized option '%s'", argv[optind - 1]); if (json_output) clean_and_exit(-1); else usage(); } } argc -= optind; argv += optind; if (argc < 0) usage(); ret = cmd_select(cmds, argc, argv, do_help); if (json_output) jsonw_destroy(&json_wtr); if (show_pinned) { delete_pinned_obj_table(&prog_table); delete_pinned_obj_table(&map_table); delete_pinned_obj_table(&link_table); } return ret; }
chenshuo/linux-study
tools/bpf/bpftool/main.c
C
gpl-2.0
9,549
--- layout: compress --- {% include _header.html %} <main> <div class="row"> <div class="medium-8 columns"> <a href="{{site.baseUrl}}/news.html" class="button tiny"><i class="fa fa-chevron-left"></i>&nbsp;Back</a><br/> <article class="post" itemscope itemtype="http://schema.org/BlogPosting"> <header> <h1 itemprop="headline name">{{ page.title }}</h1> <div class="meta"> <time itemprop="datePublished" content="{{ page.date | date: '%Y-%m-%d'}}">{{ page.date | date: "%Y-%m-%d"}}</time> by <span class="author" itemprop="author" itemscope itemtype="http://schema.org/Person"><span itemprop="name">{{ page.author }}</span></span> </div> </header> <div itemprop="articleBody"> {{ content }} </div> </article> </div> <div class="medium-4 columns"> </div> </div> </main> {% include _footer.html %}
SzwedzikPL/ACE3
docs/_layouts/post.html
HTML
gpl-2.0
1,067
----------------------------------------- -- Spell: Huton: San -- Deals wind damage to an enemy and lowers its resistance against ice. ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) --doNinjutsuNuke(V,M,caster,spell,target,hasMultipleTargetReduction,resistBonus) local duration = 15 + caster:getMerit(MERIT_HUTON_EFFECT) -- T1 bonus debuff duration local bonusAcc = 0; local bonusMab = caster:getMerit(MERIT_HUTON_EFFECT); -- T1 mag atk if(caster:getMerit(MERIT_HUTON_SAN) ~= 0) then -- T2 mag atk/mag acc, don't want to give a penalty to entities that can cast this without merits bonusMab = bonusMab + caster:getMerit(MERIT_HUTON_SAN) - 5; -- merit gives 5 power but no bonus with one invest, thus subtract 5 bonusAcc = bonusAcc + caster:getMerit(MERIT_HUTON_SAN) - 5; end local dmg = doNinjutsuNuke(134,1.5,caster,spell,target,false,bonusAcc,bonusMab); handleNinjutsuDebuff(caster,target,spell,30,duration,MOD_ICERES); return dmg; end;
UnknownX7/darkstar
scripts/globals/spells/huton_san.lua
Lua
gpl-3.0
1,271
# Copyright (c) 2018 Cisco and/or its affiliates. # # 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/>. # from __future__ import absolute_import import pytest from units.modules.utils import set_module_args, exit_json, fail_json, AnsibleFailJson, AnsibleExitJson from ansible.module_utils import basic from ansible.module_utils.network.ftd.common import FtdConfigurationError, FtdServerError, FtdUnexpectedResponse from ansible.module_utils.network.ftd.configuration import FtdInvalidOperationNameError, CheckModeException from ansible.module_utils.network.ftd.fdm_swagger_client import ValidationError from ansible.modules.network.ftd import ftd_configuration class TestFtdConfiguration(object): module = ftd_configuration @pytest.fixture(autouse=True) def module_mock(self, mocker): return mocker.patch.multiple(basic.AnsibleModule, exit_json=exit_json, fail_json=fail_json) @pytest.fixture(autouse=True) def connection_mock(self, mocker): connection_class_mock = mocker.patch('ansible.modules.network.ftd.ftd_configuration.Connection') return connection_class_mock.return_value @pytest.fixture def resource_mock(self, mocker): resource_class_mock = mocker.patch('ansible.modules.network.ftd.ftd_configuration.BaseConfigurationResource') resource_instance = resource_class_mock.return_value return resource_instance.execute_operation def test_module_should_fail_when_ftd_invalid_operation_name_error(self, resource_mock): operation_name = 'test name' resource_mock.side_effect = FtdInvalidOperationNameError(operation_name) result = self._run_module_with_fail_json({'operation': operation_name}) assert result['failed'] assert 'Invalid operation name provided: %s' % operation_name == result['msg'] def test_module_should_fail_when_ftd_configuration_error(self, resource_mock): operation_name = 'test name' msg = 'Foo error.' resource_mock.side_effect = FtdConfigurationError(msg) result = self._run_module_with_fail_json({'operation': operation_name}) assert result['failed'] assert 'Failed to execute %s operation because of the configuration error: %s' % (operation_name, msg) == \ result['msg'] def test_module_should_fail_when_ftd_server_error(self, resource_mock): operation_name = 'test name' code = 500 response = {'error': 'foo'} resource_mock.side_effect = FtdServerError(response, code) result = self._run_module_with_fail_json({'operation': operation_name}) assert result['failed'] assert 'Server returned an error trying to execute %s operation. Status code: %s. ' \ 'Server response: %s' % (operation_name, code, response) == \ result['msg'] def test_module_should_fail_when_validation_error(self, resource_mock): operation_name = 'test name' msg = 'Foo error.' resource_mock.side_effect = ValidationError(msg) result = self._run_module_with_fail_json({'operation': operation_name}) assert result['failed'] assert msg == result['msg'] def test_module_should_fail_when_unexpected_server_response(self, resource_mock): operation_name = 'test name' msg = 'Foo error.' resource_mock.side_effect = FtdUnexpectedResponse(msg) result = self._run_module_with_fail_json({'operation': operation_name}) assert result['failed'] assert msg == result['msg'] def test_module_should_fail_when_check_mode_exception(self, resource_mock): operation_name = 'test name' msg = 'Foo error.' resource_mock.side_effect = CheckModeException(msg) result = self._run_module({'operation': operation_name}) assert not result['changed'] def test_module_should_run_successful(self, resource_mock): operation_name = 'test name' resource_mock.return_value = 'ok' result = self._run_module({'operation': operation_name}) assert result['response'] == 'ok' def _run_module(self, module_args): set_module_args(module_args) with pytest.raises(AnsibleExitJson) as ex: self.module.main() return ex.value.args[0] def _run_module_with_fail_json(self, module_args): set_module_args(module_args) with pytest.raises(AnsibleFailJson) as exc: self.module.main() result = exc.value.args[0] return result
Jorge-Rodriguez/ansible
test/units/modules/network/ftd/test_ftd_configuration.py
Python
gpl-3.0
5,145
# -*- coding: utf-8 -*- # Copyright (C) 2006-2010 Søren Roug, European Environment Agency # # 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # Contributor(s): # __doc__="""Use OpenDocument to generate your documents.""" import zipfile, time, sys, mimetypes, copy from cStringIO import StringIO from namespaces import * import manifest, meta from office import * import element from attrconverters import make_NCName from xml.sax.xmlreader import InputSource from odfmanifest import manifestlist __version__= TOOLSVERSION _XMLPROLOGUE = u"<?xml version='1.0' encoding='UTF-8'?>\n" UNIXPERMS = 0100644 << 16L # -rw-r--r-- IS_FILENAME = 0 IS_IMAGE = 1 # We need at least Python 2.2 assert sys.version_info[0]>=2 and sys.version_info[1] >= 2 #sys.setrecursionlimit(100) #The recursion limit is set conservative so mistakes like # s=content() s.addElement(s) won't eat up too much processor time. odmimetypes = { 'application/vnd.oasis.opendocument.text': '.odt', 'application/vnd.oasis.opendocument.text-template': '.ott', 'application/vnd.oasis.opendocument.graphics': '.odg', 'application/vnd.oasis.opendocument.graphics-template': '.otg', 'application/vnd.oasis.opendocument.presentation': '.odp', 'application/vnd.oasis.opendocument.presentation-template': '.otp', 'application/vnd.oasis.opendocument.spreadsheet': '.ods', 'application/vnd.oasis.opendocument.spreadsheet-template': '.ots', 'application/vnd.oasis.opendocument.chart': '.odc', 'application/vnd.oasis.opendocument.chart-template': '.otc', 'application/vnd.oasis.opendocument.image': '.odi', 'application/vnd.oasis.opendocument.image-template': '.oti', 'application/vnd.oasis.opendocument.formula': '.odf', 'application/vnd.oasis.opendocument.formula-template': '.otf', 'application/vnd.oasis.opendocument.text-master': '.odm', 'application/vnd.oasis.opendocument.text-web': '.oth', } class OpaqueObject: def __init__(self, filename, mediatype, content=None): self.mediatype = mediatype self.filename = filename self.content = content class OpenDocument: """ A class to hold the content of an OpenDocument document Use the xml method to write the XML source to the screen or to a file d = OpenDocument(mimetype) fd.write(d.xml()) """ thumbnail = None def __init__(self, mimetype, add_generator=True): self.mimetype = mimetype self.childobjects = [] self._extra = [] self.folder = "" # Always empty for toplevel documents self.topnode = Document(mimetype=self.mimetype) self.topnode.ownerDocument = self self.clear_caches() self.Pictures = {} self.meta = Meta() self.topnode.addElement(self.meta) if add_generator: self.meta.addElement(meta.Generator(text=TOOLSVERSION)) self.scripts = Scripts() self.topnode.addElement(self.scripts) self.fontfacedecls = FontFaceDecls() self.topnode.addElement(self.fontfacedecls) self.settings = Settings() self.topnode.addElement(self.settings) self.styles = Styles() self.topnode.addElement(self.styles) self.automaticstyles = AutomaticStyles() self.topnode.addElement(self.automaticstyles) self.masterstyles = MasterStyles() self.topnode.addElement(self.masterstyles) self.body = Body() self.topnode.addElement(self.body) def rebuild_caches(self, node=None): if node is None: node = self.topnode self.build_caches(node) for e in node.childNodes: if e.nodeType == element.Node.ELEMENT_NODE: self.rebuild_caches(e) def clear_caches(self): self.element_dict = {} self._styles_dict = {} self._styles_ooo_fix = {} def build_caches(self, element): """ Called from element.py """ if not self.element_dict.has_key(element.qname): self.element_dict[element.qname] = [] self.element_dict[element.qname].append(element) if element.qname == (STYLENS, u'style'): self.__register_stylename(element) # Add to style dictionary styleref = element.getAttrNS(TEXTNS,u'style-name') if styleref is not None and self._styles_ooo_fix.has_key(styleref): element.setAttrNS(TEXTNS,u'style-name', self._styles_ooo_fix[styleref]) def __register_stylename(self, element): ''' Register a style. But there are three style dictionaries: office:styles, office:automatic-styles and office:master-styles Chapter 14 ''' name = element.getAttrNS(STYLENS, u'name') if name is None: return if element.parentNode.qname in ((OFFICENS,u'styles'), (OFFICENS,u'automatic-styles')): if self._styles_dict.has_key(name): newname = 'M'+name # Rename style self._styles_ooo_fix[name] = newname # From here on all references to the old name will refer to the new one name = newname element.setAttrNS(STYLENS, u'name', name) self._styles_dict[name] = element def toXml(self, filename=''): xml=StringIO() xml.write(_XMLPROLOGUE) self.body.toXml(0, xml) if not filename: return xml.getvalue() else: f=file(filename,'w') f.write(xml.getvalue()) f.close() def xml(self): """ Generates the full document as an XML file Always written as a bytestream in UTF-8 encoding """ self.__replaceGenerator() xml=StringIO() xml.write(_XMLPROLOGUE) self.topnode.toXml(0, xml) return xml.getvalue() def contentxml(self): """ Generates the content.xml file Always written as a bytestream in UTF-8 encoding """ xml=StringIO() xml.write(_XMLPROLOGUE) x = DocumentContent() x.write_open_tag(0, xml) if self.scripts.hasChildNodes(): self.scripts.toXml(1, xml) if self.fontfacedecls.hasChildNodes(): self.fontfacedecls.toXml(1, xml) a = AutomaticStyles() stylelist = self._used_auto_styles([self.styles, self.automaticstyles, self.body]) if len(stylelist) > 0: a.write_open_tag(1, xml) for s in stylelist: s.toXml(2, xml) a.write_close_tag(1, xml) else: a.toXml(1, xml) self.body.toXml(1, xml) x.write_close_tag(0, xml) return xml.getvalue() def __manifestxml(self): """ Generates the manifest.xml file The self.manifest isn't avaible unless the document is being saved """ xml=StringIO() xml.write(_XMLPROLOGUE) self.manifest.toXml(0,xml) return xml.getvalue() def metaxml(self): """ Generates the meta.xml file """ self.__replaceGenerator() x = DocumentMeta() x.addElement(self.meta) xml=StringIO() xml.write(_XMLPROLOGUE) x.toXml(0,xml) return xml.getvalue() def settingsxml(self): """ Generates the settings.xml file """ x = DocumentSettings() x.addElement(self.settings) xml=StringIO() xml.write(_XMLPROLOGUE) x.toXml(0,xml) return xml.getvalue() def _parseoneelement(self, top, stylenamelist): """ Finds references to style objects in master-styles and add the style name to the style list if not already there. Recursive """ for e in top.childNodes: if e.nodeType == element.Node.ELEMENT_NODE: for styleref in ( (CHARTNS,u'style-name'), (DRAWNS,u'style-name'), (DRAWNS,u'text-style-name'), (PRESENTATIONNS,u'style-name'), (STYLENS,u'data-style-name'), (STYLENS,u'list-style-name'), (STYLENS,u'page-layout-name'), (STYLENS,u'style-name'), (TABLENS,u'default-cell-style-name'), (TABLENS,u'style-name'), (TEXTNS,u'style-name') ): if e.getAttrNS(styleref[0],styleref[1]): stylename = e.getAttrNS(styleref[0],styleref[1]) if stylename not in stylenamelist: stylenamelist.append(stylename) stylenamelist = self._parseoneelement(e, stylenamelist) return stylenamelist def _used_auto_styles(self, segments): """ Loop through the masterstyles elements, and find the automatic styles that are used. These will be added to the automatic-styles element in styles.xml """ stylenamelist = [] for top in segments: stylenamelist = self._parseoneelement(top, stylenamelist) stylelist = [] for e in self.automaticstyles.childNodes: if e.getAttrNS(STYLENS,u'name') in stylenamelist: stylelist.append(e) return stylelist def stylesxml(self): """ Generates the styles.xml file """ xml=StringIO() xml.write(_XMLPROLOGUE) x = DocumentStyles() x.write_open_tag(0, xml) if self.fontfacedecls.hasChildNodes(): self.fontfacedecls.toXml(1, xml) self.styles.toXml(1, xml) a = AutomaticStyles() a.write_open_tag(1, xml) for s in self._used_auto_styles([self.masterstyles]): s.toXml(2, xml) a.write_close_tag(1, xml) if self.masterstyles.hasChildNodes(): self.masterstyles.toXml(1, xml) x.write_close_tag(0, xml) return xml.getvalue() def addPicture(self, filename, mediatype=None, content=None): """ Add a picture It uses the same convention as OOo, in that it saves the picture in the zipfile in the subdirectory 'Pictures' If passed a file ptr, mediatype must be set """ if content is None: if mediatype is None: mediatype, encoding = mimetypes.guess_type(filename) if mediatype is None: mediatype = '' try: ext = filename[filename.rindex('.'):] except: ext='' else: ext = mimetypes.guess_extension(mediatype) manifestfn = "Pictures/%0.0f%s" % ((time.time()*10000000000), ext) self.Pictures[manifestfn] = (IS_FILENAME, filename, mediatype) else: manifestfn = filename self.Pictures[manifestfn] = (IS_IMAGE, content, mediatype) return manifestfn def addPictureFromFile(self, filename, mediatype=None): """ Add a picture It uses the same convention as OOo, in that it saves the picture in the zipfile in the subdirectory 'Pictures'. If mediatype is not given, it will be guessed from the filename extension. """ if mediatype is None: mediatype, encoding = mimetypes.guess_type(filename) if mediatype is None: mediatype = '' try: ext = filename[filename.rindex('.'):] except ValueError: ext='' else: ext = mimetypes.guess_extension(mediatype) manifestfn = "Pictures/%0.0f%s" % ((time.time()*10000000000), ext) self.Pictures[manifestfn] = (IS_FILENAME, filename, mediatype) return manifestfn def addPictureFromString(self, content, mediatype): """ Add a picture It uses the same convention as OOo, in that it saves the picture in the zipfile in the subdirectory 'Pictures'. The content variable is a string that contains the binary image data. The mediatype indicates the image format. """ ext = mimetypes.guess_extension(mediatype) manifestfn = "Pictures/%0.0f%s" % ((time.time()*10000000000), ext) self.Pictures[manifestfn] = (IS_IMAGE, content, mediatype) return manifestfn def addThumbnail(self, filecontent=None): """ Add a fixed thumbnail The thumbnail in the library is big, so this is pretty useless. """ if filecontent is None: import thumbnail self.thumbnail = thumbnail.thumbnail() else: self.thumbnail = filecontent def addObject(self, document, objectname=None): """ Adds an object (subdocument). The object must be an OpenDocument class The return value will be the folder in the zipfile the object is stored in """ self.childobjects.append(document) if objectname is None: document.folder = "%s/Object %d" % (self.folder, len(self.childobjects)) else: document.folder = objectname return ".%s" % document.folder def _savePictures(self, object, folder): hasPictures = False for arcname, picturerec in object.Pictures.items(): what_it_is, fileobj, mediatype = picturerec self.manifest.addElement(manifest.FileEntry(fullpath="%s%s" % ( folder ,arcname), mediatype=mediatype)) hasPictures = True if what_it_is == IS_FILENAME: self._z.write(fileobj, arcname, zipfile.ZIP_STORED) else: zi = zipfile.ZipInfo(str(arcname), self._now) zi.compress_type = zipfile.ZIP_STORED zi.external_attr = UNIXPERMS self._z.writestr(zi, fileobj) # According to section 17.7.3 in ODF 1.1, the pictures folder should not have a manifest entry # if hasPictures: # self.manifest.addElement(manifest.FileEntry(fullpath="%sPictures/" % folder, mediatype="")) # Look in subobjects subobjectnum = 1 for subobject in object.childobjects: self._savePictures(subobject,'%sObject %d/' % (folder, subobjectnum)) subobjectnum += 1 def __replaceGenerator(self): """ Section 3.1.1: The application MUST NOT export the original identifier belonging to the application that created the document. """ for m in self.meta.childNodes[:]: if m.qname == (METANS, u'generator'): self.meta.removeChild(m) self.meta.addElement(meta.Generator(text=TOOLSVERSION)) def save(self, outputfile, addsuffix=False): """ Save the document under the filename. If the filename is '-' then save to stdout """ if outputfile == '-': outputfp = zipfile.ZipFile(sys.stdout,"w") else: if addsuffix: outputfile = outputfile + odmimetypes.get(self.mimetype,'.xxx') outputfp = zipfile.ZipFile(outputfile, "w") self.__zipwrite(outputfp) outputfp.close() def write(self, outputfp): """ User API to write the ODF file to an open file descriptor Writes the ZIP format """ zipoutputfp = zipfile.ZipFile(outputfp,"w") self.__zipwrite(zipoutputfp) def __zipwrite(self, outputfp): """ Write the document to an open file pointer This is where the real work is done """ self._z = outputfp self._now = time.localtime()[:6] self.manifest = manifest.Manifest() # Write mimetype zi = zipfile.ZipInfo('mimetype', self._now) zi.compress_type = zipfile.ZIP_STORED zi.external_attr = UNIXPERMS self._z.writestr(zi, self.mimetype) self._saveXmlObjects(self,"") # Write pictures self._savePictures(self,"") # Write the thumbnail if self.thumbnail is not None: self.manifest.addElement(manifest.FileEntry(fullpath="Thumbnails/", mediatype='')) self.manifest.addElement(manifest.FileEntry(fullpath="Thumbnails/thumbnail.png", mediatype='')) zi = zipfile.ZipInfo("Thumbnails/thumbnail.png", self._now) zi.compress_type = zipfile.ZIP_DEFLATED zi.external_attr = UNIXPERMS self._z.writestr(zi, self.thumbnail) # Write any extra files for op in self._extra: if op.filename == "META-INF/documentsignatures.xml": continue # Don't save signatures self.manifest.addElement(manifest.FileEntry(fullpath=op.filename, mediatype=op.mediatype)) zi = zipfile.ZipInfo(op.filename.encode('utf-8'), self._now) zi.compress_type = zipfile.ZIP_DEFLATED zi.external_attr = UNIXPERMS if op.content is not None: self._z.writestr(zi, op.content) # Write manifest zi = zipfile.ZipInfo("META-INF/manifest.xml", self._now) zi.compress_type = zipfile.ZIP_DEFLATED zi.external_attr = UNIXPERMS self._z.writestr(zi, self.__manifestxml() ) del self._z del self._now del self.manifest def _saveXmlObjects(self, object, folder): if self == object: self.manifest.addElement(manifest.FileEntry(fullpath="/", mediatype=object.mimetype)) else: self.manifest.addElement(manifest.FileEntry(fullpath=folder, mediatype=object.mimetype)) # Write styles self.manifest.addElement(manifest.FileEntry(fullpath="%sstyles.xml" % folder, mediatype="text/xml")) zi = zipfile.ZipInfo("%sstyles.xml" % folder, self._now) zi.compress_type = zipfile.ZIP_DEFLATED zi.external_attr = UNIXPERMS self._z.writestr(zi, object.stylesxml() ) # Write content self.manifest.addElement(manifest.FileEntry(fullpath="%scontent.xml" % folder, mediatype="text/xml")) zi = zipfile.ZipInfo("%scontent.xml" % folder, self._now) zi.compress_type = zipfile.ZIP_DEFLATED zi.external_attr = UNIXPERMS self._z.writestr(zi, object.contentxml() ) # Write settings if object.settings.hasChildNodes(): self.manifest.addElement(manifest.FileEntry(fullpath="%ssettings.xml" % folder, mediatype="text/xml")) zi = zipfile.ZipInfo("%ssettings.xml" % folder, self._now) zi.compress_type = zipfile.ZIP_DEFLATED zi.external_attr = UNIXPERMS self._z.writestr(zi, object.settingsxml() ) # Write meta if self == object: self.manifest.addElement(manifest.FileEntry(fullpath="meta.xml", mediatype="text/xml")) zi = zipfile.ZipInfo("meta.xml", self._now) zi.compress_type = zipfile.ZIP_DEFLATED zi.external_attr = UNIXPERMS self._z.writestr(zi, object.metaxml() ) # Write subobjects subobjectnum = 1 for subobject in object.childobjects: self._saveXmlObjects(subobject, '%sObject %d/' % (folder, subobjectnum)) subobjectnum += 1 # Document's DOM methods def createElement(self, element): """ Inconvenient interface to create an element, but follows XML-DOM. Does not allow attributes as argument, therefore can't check grammar. """ return element(check_grammar=False) def createTextNode(self, data): """ Method to create a text node """ return element.Text(data) def createCDATASection(self, data): """ Method to create a CDATA section """ return element.CDATASection(cdata) def getMediaType(self): """ Returns the media type """ return self.mimetype def getStyleByName(self, name): """ Finds a style object based on the name """ ncname = make_NCName(name) if self._styles_dict == {}: self.rebuild_caches() return self._styles_dict.get(ncname, None) def getElementsByType(self, element): """ Gets elements based on the type, which is function from text.py, draw.py etc. """ obj = element(check_grammar=False) if self.element_dict == {}: self.rebuild_caches() return self.element_dict.get(obj.qname, []) # Convenience functions def OpenDocumentChart(): """ Creates a chart document """ doc = OpenDocument('application/vnd.oasis.opendocument.chart') doc.chart = Chart() doc.body.addElement(doc.chart) return doc def OpenDocumentDrawing(): """ Creates a drawing document """ doc = OpenDocument('application/vnd.oasis.opendocument.graphics') doc.drawing = Drawing() doc.body.addElement(doc.drawing) return doc def OpenDocumentImage(): """ Creates an image document """ doc = OpenDocument('application/vnd.oasis.opendocument.image') doc.image = Image() doc.body.addElement(doc.image) return doc def OpenDocumentPresentation(): """ Creates a presentation document """ doc = OpenDocument('application/vnd.oasis.opendocument.presentation') doc.presentation = Presentation() doc.body.addElement(doc.presentation) return doc def OpenDocumentSpreadsheet(): """ Creates a spreadsheet document """ doc = OpenDocument('application/vnd.oasis.opendocument.spreadsheet') doc.spreadsheet = Spreadsheet() doc.body.addElement(doc.spreadsheet) return doc def OpenDocumentText(): """ Creates a text document """ doc = OpenDocument('application/vnd.oasis.opendocument.text') doc.text = Text() doc.body.addElement(doc.text) return doc def OpenDocumentTextMaster(): """ Creates a text master document """ doc = OpenDocument('application/vnd.oasis.opendocument.text-master') doc.text = Text() doc.body.addElement(doc.text) return doc def __loadxmlparts(z, manifest, doc, objectpath): from load import LoadParser from xml.sax import make_parser, handler for xmlfile in (objectpath+'settings.xml', objectpath+'meta.xml', objectpath+'content.xml', objectpath+'styles.xml'): if not manifest.has_key(xmlfile): continue try: xmlpart = z.read(xmlfile) doc._parsing = xmlfile parser = make_parser() parser.setFeature(handler.feature_namespaces, 1) parser.setContentHandler(LoadParser(doc)) parser.setErrorHandler(handler.ErrorHandler()) inpsrc = InputSource() inpsrc.setByteStream(StringIO(xmlpart)) parser.setFeature(handler.feature_external_ges, False) # Changed by Kovid to ignore external DTDs parser.parse(inpsrc) del doc._parsing except KeyError, v: pass def load(odffile): """ Load an ODF file into memory Returns a reference to the structure """ z = zipfile.ZipFile(odffile) try: mimetype = z.read('mimetype') except KeyError: # Added by Kovid to handle malformed odt files mimetype = 'application/vnd.oasis.opendocument.text' doc = OpenDocument(mimetype, add_generator=False) # Look in the manifest file to see if which of the four files there are manifestpart = z.read('META-INF/manifest.xml') manifest = manifestlist(manifestpart) __loadxmlparts(z, manifest, doc, '') for mentry,mvalue in manifest.items(): if mentry[:9] == "Pictures/" and len(mentry) > 9: doc.addPicture(mvalue['full-path'], mvalue['media-type'], z.read(mentry)) elif mentry == "Thumbnails/thumbnail.png": doc.addThumbnail(z.read(mentry)) elif mentry in ('settings.xml', 'meta.xml', 'content.xml', 'styles.xml'): pass # Load subobjects into structure elif mentry[:7] == "Object " and len(mentry) < 11 and mentry[-1] == "/": subdoc = OpenDocument(mvalue['media-type'], add_generator=False) doc.addObject(subdoc, "/" + mentry[:-1]) __loadxmlparts(z, manifest, subdoc, mentry) elif mentry[:7] == "Object ": pass # Don't load subobjects as opaque objects else: if mvalue['full-path'][-1] == '/': doc._extra.append(OpaqueObject(mvalue['full-path'], mvalue['media-type'], None)) else: doc._extra.append(OpaqueObject(mvalue['full-path'], mvalue['media-type'], z.read(mentry))) # Add the SUN junk here to the struct somewhere # It is cached data, so it can be out-of-date z.close() b = doc.getElementsByType(Body) if mimetype[:39] == 'application/vnd.oasis.opendocument.text': doc.text = b[0].firstChild elif mimetype[:43] == 'application/vnd.oasis.opendocument.graphics': doc.graphics = b[0].firstChild elif mimetype[:47] == 'application/vnd.oasis.opendocument.presentation': doc.presentation = b[0].firstChild elif mimetype[:46] == 'application/vnd.oasis.opendocument.spreadsheet': doc.spreadsheet = b[0].firstChild elif mimetype[:40] == 'application/vnd.oasis.opendocument.chart': doc.chart = b[0].firstChild elif mimetype[:40] == 'application/vnd.oasis.opendocument.image': doc.image = b[0].firstChild elif mimetype[:42] == 'application/vnd.oasis.opendocument.formula': doc.formula = b[0].firstChild return doc # vim: set expandtab sw=4 :
ashang/calibre
src/odf/opendocument.py
Python
gpl-3.0
26,274