Search is not available for this dataset
max_stars_repo_path
stringlengths
2
976
max_stars_repo_name
stringlengths
5
109
max_stars_count
float64
0
191k
id
stringlengths
1
7
content
stringlengths
1
11.6M
score
float64
-0.83
3.86
int_score
int64
0
4
Drivers/BSP/Components/hts221/HTS221_Driver.c
VictorLee1990/WSL309S_Luna
3
804
/** ****************************************************************************** * @file HTS221_Driver.c * @author HESA Application Team * @version V1.1 * @date 10-August-2016 * @brief HTS221 driver file ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT(c) 2016 STMicroelectronics</center></h2> * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics 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 "HTS221_Driver.h" #ifdef USE_FULL_ASSERT_HTS221 #include <stdio.h> #endif /** @addtogroup Environmental_Sensor * @{ */ /** @defgroup HTS221_DRIVER * @brief HTS221 DRIVER * @{ */ /** @defgroup HTS221_Imported_Function_Prototypes * @{ */ extern uint8_t Sensor_IO_Write( void *handle, uint8_t WriteAddr, uint8_t *pBuffer, uint16_t nBytesToWrite ); extern uint8_t Sensor_IO_Read( void *handle, uint8_t ReadAddr, uint8_t *pBuffer, uint16_t nBytesToRead ); /** * @} */ /** @defgroup HTS221_Private_Function_Prototypes * @{ */ /** * @} */ /** @defgroup HTS221_Private_Functions * @{ */ /** * @} */ /** @defgroup HTS221_Public_Functions * @{ */ /******************************************************************************* * Function Name : HTS221_ReadReg * Description : Generic Reading function. It must be fullfilled with either * : I2C or SPI reading functions * Input : Register Address * Output : Data Read * Return : None *******************************************************************************/ HTS221_Error_et HTS221_ReadReg( void *handle, uint8_t RegAddr, uint16_t NumByteToRead, uint8_t *Data ) { if ( NumByteToRead > 1 ) RegAddr |= 0x80; if ( Sensor_IO_Read( handle, RegAddr, Data, NumByteToRead ) ) return HTS221_ERROR; else return HTS221_OK; } /******************************************************************************* * Function Name : HTS221_WriteReg * Description : Generic Writing function. It must be fullfilled with either * : I2C or SPI writing function * Input : Register Address, Data to be written * Output : None * Return : None *******************************************************************************/ HTS221_Error_et HTS221_WriteReg( void *handle, uint8_t RegAddr, uint16_t NumByteToWrite, uint8_t *Data ) { if ( NumByteToWrite > 1 ) RegAddr |= 0x80; if ( Sensor_IO_Write( handle, RegAddr, Data, NumByteToWrite ) ) return HTS221_ERROR; else return HTS221_OK; } /** * @brief Get the version of this driver. * @param pxVersion pointer to a HTS221_DriverVersion_st structure that contains the version information. * This parameter is a pointer to @ref HTS221_DriverVersion_st. * @retval Error code [HTS221_OK, HTS221_ERROR]. */ HTS221_Error_et HTS221_Get_DriverVersion(HTS221_DriverVersion_st* version) { version->Major = HTS221_DRIVER_VERSION_MAJOR; version->Minor = HTS221_DRIVER_VERSION_MINOR; version->Point = HTS221_DRIVER_VERSION_POINT; return HTS221_OK; } /** * @brief Get device type ID. * @param *handle Device handle. * @param deviceid pointer to the returned device type ID. * @retval Error code [HTS221_OK, HTS221_ERROR]. */ HTS221_Error_et HTS221_Get_DeviceID(void *handle, uint8_t* deviceid) { if(HTS221_ReadReg(handle, HTS221_WHO_AM_I_REG, 1, deviceid)) return HTS221_ERROR; return HTS221_OK; } /** * @brief Initializes the HTS221 with the specified parameters in HTS221_Init_st struct. * @param *handle Device handle. * @param pxInit pointer to a HTS221_Init_st structure that contains the configuration. * This parameter is a pointer to @ref HTS221_Init_st. * @retval Error code [HTS221_OK, HTS221_ERROR]. */ HTS221_Error_et HTS221_Set_InitConfig(void *handle, HTS221_Init_st* pxInit) { uint8_t buffer[3]; HTS221_assert_param(IS_HTS221_AVGH(pxInit->avg_h)); HTS221_assert_param(IS_HTS221_AVGT(pxInit->avg_t)); HTS221_assert_param(IS_HTS221_ODR(pxInit->odr)); HTS221_assert_param(IS_HTS221_State(pxInit->bdu_status)); HTS221_assert_param(IS_HTS221_State(pxInit->heater_status)); HTS221_assert_param(IS_HTS221_DrdyLevelType(pxInit->irq_level)); HTS221_assert_param(IS_HTS221_OutputType(pxInit->irq_output_type)); HTS221_assert_param(IS_HTS221_State(pxInit->irq_enable)); if(HTS221_ReadReg(handle, HTS221_AV_CONF_REG, 1, buffer)) return HTS221_ERROR; buffer[0] &= ~(HTS221_AVGH_MASK | HTS221_AVGT_MASK); buffer[0] |= (uint8_t)pxInit->avg_h; buffer[0] |= (uint8_t)pxInit->avg_t; if(HTS221_WriteReg(handle, HTS221_AV_CONF_REG, 1, buffer)) return HTS221_ERROR; if(HTS221_ReadReg(handle, HTS221_CTRL_REG1, 3, buffer)) return HTS221_ERROR; buffer[0] &= ~(HTS221_BDU_MASK | HTS221_ODR_MASK); buffer[0] |= (uint8_t)pxInit->odr; buffer[0] |= ((uint8_t)pxInit->bdu_status) << HTS221_BDU_BIT; buffer[1] &= ~HTS221_HEATHER_BIT; buffer[1] |= ((uint8_t)pxInit->heater_status) << HTS221_HEATHER_BIT; buffer[2] &= ~(HTS221_DRDY_H_L_MASK | HTS221_PP_OD_MASK | HTS221_DRDY_MASK); buffer[2] |= ((uint8_t)pxInit->irq_level) << HTS221_DRDY_H_L_BIT; buffer[2] |= (uint8_t)pxInit->irq_output_type; buffer[2] |= ((uint8_t)pxInit->irq_enable) << HTS221_DRDY_BIT; if(HTS221_WriteReg(handle, HTS221_CTRL_REG1, 3, buffer)) return HTS221_ERROR; return HTS221_OK; } /** * @brief Returns a HTS221_Init_st struct with the actual configuration. * @param *handle Device handle. * @param pxInit pointer to a HTS221_Init_st structure. * This parameter is a pointer to @ref HTS221_Init_st. * @retval Error code [HTS221_OK, HTS221_ERROR]. */ HTS221_Error_et HTS221_Get_InitConfig(void *handle, HTS221_Init_st* pxInit) { uint8_t buffer[3]; if(HTS221_ReadReg(handle, HTS221_AV_CONF_REG, 1, buffer)) return HTS221_ERROR; pxInit->avg_h = (HTS221_Avgh_et)(buffer[0] & HTS221_AVGH_MASK); pxInit->avg_t = (HTS221_Avgt_et)(buffer[0] & HTS221_AVGT_MASK); if(HTS221_ReadReg(handle, HTS221_CTRL_REG1, 3, buffer)) return HTS221_ERROR; pxInit->odr = (HTS221_Odr_et)(buffer[0] & HTS221_ODR_MASK); pxInit->bdu_status = (HTS221_State_et)((buffer[0] & HTS221_BDU_MASK) >> HTS221_BDU_BIT); pxInit->heater_status = (HTS221_State_et)((buffer[1] & HTS221_HEATHER_MASK) >> HTS221_HEATHER_BIT); pxInit->irq_level = (HTS221_DrdyLevel_et)(buffer[2] & HTS221_DRDY_H_L_MASK); pxInit->irq_output_type = (HTS221_OutputType_et)(buffer[2] & HTS221_PP_OD_MASK); pxInit->irq_enable = (HTS221_State_et)((buffer[2] & HTS221_DRDY_MASK) >> HTS221_DRDY_BIT); return HTS221_OK; } /** * @brief De initialization function for HTS221. * This function put the HTS221 in power down, make a memory boot and clear the data output flags. * @param *handle Device handle. * @retval Error code [HTS221_OK, HTS221_ERROR]. */ HTS221_Error_et HTS221_DeInit(void *handle) { uint8_t buffer[4]; if(HTS221_ReadReg(handle, HTS221_CTRL_REG1, 2, buffer)) return HTS221_ERROR; /* HTS221 in power down */ buffer[0] |= 0x01 << HTS221_PD_BIT; /* Make HTS221 boot */ buffer[1] |= 0x01 << HTS221_BOOT_BIT; if(HTS221_WriteReg(handle, HTS221_CTRL_REG1, 2, buffer)) return HTS221_ERROR; /* Dump of data output */ if(HTS221_ReadReg(handle, HTS221_HR_OUT_L_REG, 4, buffer)) return HTS221_ERROR; return HTS221_OK; } /** * @brief Read HTS221 output registers, and calculate humidity and temperature. * @param *handle Device handle. * @param humidity pointer to the returned humidity value that must be divided by 10 to get the value in [%]. * @param temperature pointer to the returned temperature value that must be divided by 10 to get the value in ['C]. * @retval Error code [HTS221_OK, HTS221_ERROR]. */ HTS221_Error_et HTS221_Get_Measurement(void *handle, uint16_t* humidity, int16_t* temperature) { if ( HTS221_Get_Temperature( handle, temperature ) == HTS221_ERROR ) return HTS221_ERROR; if ( HTS221_Get_Humidity( handle, humidity ) == HTS221_ERROR ) return HTS221_ERROR; return HTS221_OK; } /** * @brief Read HTS221 output registers. Humidity and temperature. * @param *handle Device handle. * @param humidity pointer to the returned humidity raw value. * @param temperature pointer to the returned temperature raw value. * @retval Error code [HTS221_OK, HTS221_ERROR]. */ HTS221_Error_et HTS221_Get_RawMeasurement(void *handle, int16_t* humidity, int16_t* temperature) { uint8_t buffer[4]; if(HTS221_ReadReg(handle, HTS221_HR_OUT_L_REG, 4, buffer)) return HTS221_ERROR; *humidity = (int16_t)((((uint16_t)buffer[1]) << 8) | (uint16_t)buffer[0]); *temperature = (int16_t)((((uint16_t)buffer[3]) << 8) | (uint16_t)buffer[2]); return HTS221_OK; } /** * @brief Read HTS221 Humidity output registers, and calculate humidity. * @param *handle Device handle. * @param Pointer to the returned humidity value that must be divided by 10 to get the value in [%]. * @retval Error code [HTS221_OK, HTS221_ERROR]. */ HTS221_Error_et HTS221_Get_Humidity(void *handle, uint16_t* value) { int16_t H0_T0_out, H1_T0_out, H_T_out; int16_t H0_rh, H1_rh; uint8_t buffer[2]; float tmp_f; if(HTS221_ReadReg(handle, HTS221_H0_RH_X2, 2, buffer)) return HTS221_ERROR; H0_rh = buffer[0] >> 1; H1_rh = buffer[1] >> 1; if(HTS221_ReadReg(handle, HTS221_H0_T0_OUT_L, 2, buffer)) return HTS221_ERROR; H0_T0_out = (((uint16_t)buffer[1]) << 8) | (uint16_t)buffer[0]; if(HTS221_ReadReg(handle, HTS221_H1_T0_OUT_L, 2, buffer)) return HTS221_ERROR; H1_T0_out = (((uint16_t)buffer[1]) << 8) | (uint16_t)buffer[0]; if(HTS221_ReadReg(handle, HTS221_HR_OUT_L_REG, 2, buffer)) return HTS221_ERROR; H_T_out = (((uint16_t)buffer[1]) << 8) | (uint16_t)buffer[0]; tmp_f = (float)(H_T_out - H0_T0_out) * (float)(H1_rh - H0_rh) / (float)(H1_T0_out - H0_T0_out) + H0_rh; tmp_f *= 10.0f; *value = ( tmp_f > 1000.0f ) ? 1000 : ( tmp_f < 0.0f ) ? 0 : ( uint16_t )tmp_f; return HTS221_OK; } /** * @brief Read HTS221 humidity output registers. * @param *handle Device handle. * @param Pointer to the returned humidity raw value. * @retval Error code [HTS221_OK, HTS221_ERROR]. */ HTS221_Error_et HTS221_Get_HumidityRaw(void *handle, int16_t* value) { uint8_t buffer[2]; if(HTS221_ReadReg(handle, HTS221_HR_OUT_L_REG, 2, buffer)) return HTS221_ERROR; *value = (int16_t)((((uint16_t)buffer[1]) << 8) | (uint16_t)buffer[0]); return HTS221_OK; } /** * @brief Read HTS221 temperature output registers, and calculate temperature. * @param *handle Device handle. * @param Pointer to the returned temperature value that must be divided by 10 to get the value in ['C]. * @retval Error code [HTS221_OK, HTS221_ERROR]. */ HTS221_Error_et HTS221_Get_Temperature(void *handle, int16_t *value) { int16_t T0_out, T1_out, T_out, T0_degC_x8_u16, T1_degC_x8_u16; int16_t T0_degC, T1_degC; uint8_t buffer[4], tmp; float tmp_f; if(HTS221_ReadReg(handle, HTS221_T0_DEGC_X8, 2, buffer)) return HTS221_ERROR; if(HTS221_ReadReg(handle, HTS221_T0_T1_DEGC_H2, 1, &tmp)) return HTS221_ERROR; T0_degC_x8_u16 = (((uint16_t)(tmp & 0x03)) << 8) | ((uint16_t)buffer[0]); T1_degC_x8_u16 = (((uint16_t)(tmp & 0x0C)) << 6) | ((uint16_t)buffer[1]); T0_degC = T0_degC_x8_u16 >> 3; T1_degC = T1_degC_x8_u16 >> 3; if(HTS221_ReadReg(handle, HTS221_T0_OUT_L, 4, buffer)) return HTS221_ERROR; T0_out = (((uint16_t)buffer[1]) << 8) | (uint16_t)buffer[0]; T1_out = (((uint16_t)buffer[3]) << 8) | (uint16_t)buffer[2]; if(HTS221_ReadReg(handle, HTS221_TEMP_OUT_L_REG, 2, buffer)) return HTS221_ERROR; T_out = (((uint16_t)buffer[1]) << 8) | (uint16_t)buffer[0]; tmp_f = (float)(T_out - T0_out) * (float)(T1_degC - T0_degC) / (float)(T1_out - T0_out) + T0_degC; tmp_f *= 10.0f; *value = ( int16_t )tmp_f; return HTS221_OK; } /** * @brief Read HTS221 temperature output registers. * @param *handle Device handle. * @param Pointer to the returned temperature raw value. * @retval Error code [HTS221_OK, HTS221_ERROR]. */ HTS221_Error_et HTS221_Get_TemperatureRaw(void *handle, int16_t* value) { uint8_t buffer[2]; if(HTS221_ReadReg(handle, HTS221_TEMP_OUT_L_REG, 2, buffer)) return HTS221_ERROR; *value = (int16_t)((((uint16_t)buffer[1]) << 8) | (uint16_t)buffer[0]); return HTS221_OK; } /** * @brief Get the availability of new data for humidity and temperature. * @param *handle Device handle. * @param humidity pointer to the returned humidity data status [HTS221_SET/HTS221_RESET]. * @param temperature pointer to the returned temperature data status [HTS221_SET/HTS221_RESET]. * This parameter is a pointer to @ref HTS221_BitStatus_et. * @retval Error code [HTS221_OK, HTS221_ERROR]. */ HTS221_Error_et HTS221_Get_DataStatus(void *handle, HTS221_BitStatus_et* humidity, HTS221_BitStatus_et* temperature) { uint8_t tmp; if(HTS221_ReadReg(handle, HTS221_STATUS_REG, 1, &tmp)) return HTS221_ERROR; *humidity = (HTS221_BitStatus_et)((tmp & HTS221_HDA_MASK) >> HTS221_H_DA_BIT); *temperature = (HTS221_BitStatus_et)(tmp & HTS221_TDA_MASK); return HTS221_OK; } /** * @brief Exit from power down mode. * @param *handle Device handle. * @param void. * @retval Error code [HTS221_OK, HTS221_ERROR]. */ HTS221_Error_et HTS221_Activate(void *handle) { uint8_t tmp; if(HTS221_ReadReg(handle, HTS221_CTRL_REG1, 1, &tmp)) return HTS221_ERROR; tmp |= HTS221_PD_MASK; if(HTS221_WriteReg(handle, HTS221_CTRL_REG1, 1, &tmp)) return HTS221_ERROR; return HTS221_OK; } /** * @brief Put the sensor in power down mode. * @param *handle Device handle. * @retval Error code [HTS221_OK, HTS221_ERROR]. */ HTS221_Error_et HTS221_DeActivate(void *handle) { uint8_t tmp; if(HTS221_ReadReg(handle, HTS221_CTRL_REG1, 1, &tmp)) return HTS221_ERROR; tmp &= ~HTS221_PD_MASK; if(HTS221_WriteReg(handle, HTS221_CTRL_REG1, 1, &tmp)) return HTS221_ERROR; return HTS221_OK; } /** * @brief Check if the single measurement has completed. * @param *handle Device handle. * @param tmp is set to 1, when the measure is completed * @retval Status [HTS221_ERROR, HTS221_OK] */ HTS221_Error_et HTS221_IsMeasurementCompleted(void *handle, HTS221_BitStatus_et* Is_Measurement_Completed) { uint8_t tmp; if(HTS221_ReadReg(handle, HTS221_STATUS_REG, 1, &tmp)) return HTS221_ERROR; if((tmp & (uint8_t)(HTS221_HDA_MASK | HTS221_TDA_MASK)) == (uint8_t)(HTS221_HDA_MASK | HTS221_TDA_MASK)) *Is_Measurement_Completed = HTS221_SET; else *Is_Measurement_Completed = HTS221_RESET; return HTS221_OK; } /** * @brief Set_ humidity and temperature average mode. * @param *handle Device handle. * @param avgh is the average mode for humidity, this parameter is @ref HTS221_Avgh_et. * @param avgt is the average mode for temperature, this parameter is @ref HTS221_Avgt_et. * @retval Error code [HTS221_OK, HTS221_ERROR]. */ HTS221_Error_et HTS221_Set_AvgHT(void *handle, HTS221_Avgh_et avgh, HTS221_Avgt_et avgt) { uint8_t tmp; HTS221_assert_param(IS_HTS221_AVGH(avgh)); HTS221_assert_param(IS_HTS221_AVGT(avgt)); if(HTS221_ReadReg(handle, HTS221_AV_CONF_REG, 1, &tmp)) return HTS221_ERROR; tmp &= ~(HTS221_AVGH_MASK | HTS221_AVGT_MASK); tmp |= (uint8_t)avgh; tmp |= (uint8_t)avgt; if(HTS221_WriteReg(handle, HTS221_AV_CONF_REG, 1, &tmp)) return HTS221_ERROR; return HTS221_OK; } /** * @brief Set humidity average mode. * @param *handle Device handle. * @param avgh is the average mode for humidity, this parameter is @ref HTS221_Avgh_et. * @retval Error code [HTS221_OK, HTS221_ERROR]. */ HTS221_Error_et HTS221_Set_AvgH(void *handle, HTS221_Avgh_et avgh) { uint8_t tmp; HTS221_assert_param(IS_HTS221_AVGH(avgh)); if(HTS221_ReadReg(handle, HTS221_AV_CONF_REG, 1, &tmp)) return HTS221_ERROR; tmp &= ~HTS221_AVGH_MASK; tmp |= (uint8_t)avgh; if(HTS221_WriteReg(handle, HTS221_AV_CONF_REG, 1, &tmp)) return HTS221_ERROR; return HTS221_OK; } /** * @brief Set temperature average mode. * @param *handle Device handle. * @param avgt is the average mode for temperature, this parameter is @ref HTS221_Avgt_et. * @retval Error code [HTS221_OK, HTS221_ERROR]. */ HTS221_Error_et HTS221_Set_AvgT(void *handle, HTS221_Avgt_et avgt) { uint8_t tmp; HTS221_assert_param(IS_HTS221_AVGT(avgt)); if(HTS221_ReadReg(handle, HTS221_AV_CONF_REG, 1, &tmp)) return HTS221_ERROR; tmp &= ~HTS221_AVGT_MASK; tmp |= (uint8_t)avgt; if(HTS221_WriteReg(handle, HTS221_AV_CONF_REG, 1, &tmp)) return HTS221_ERROR; return HTS221_OK; } /** * @brief Get humidity and temperature average mode. * @param *handle Device handle. * @param avgh pointer to the returned value with the humidity average mode. * @param avgt pointer to the returned value with the temperature average mode. * @retval Error code [HTS221_OK, HTS221_ERROR]. */ HTS221_Error_et HTS221_Get_AvgHT(void *handle, HTS221_Avgh_et* avgh, HTS221_Avgt_et* avgt) { uint8_t tmp; if(HTS221_ReadReg(handle, HTS221_AV_CONF_REG, 1, &tmp)) return HTS221_ERROR; *avgh = (HTS221_Avgh_et)(tmp & HTS221_AVGH_MASK); *avgt = (HTS221_Avgt_et)(tmp & HTS221_AVGT_MASK); return HTS221_OK; } /** * @brief Set block data update mode. * @param *handle Device handle. * @param status can be HTS221_ENABLE: enable the block data update, output data registers are updated once both MSB and LSB are read. * @param status can be HTS221_DISABLE: output data registers are continuously updated. * This parameter is a @ref HTS221_BitStatus_et. * @retval Error code [HTS221_OK, HTS221_ERROR]. */ HTS221_Error_et HTS221_Set_BduMode(void *handle, HTS221_State_et status) { uint8_t tmp; HTS221_assert_param(IS_HTS221_State(status)); if(HTS221_ReadReg(handle, HTS221_CTRL_REG1, 1, &tmp)) return HTS221_ERROR; tmp &= ~HTS221_BDU_MASK; tmp |= ((uint8_t)status) << HTS221_BDU_BIT; if(HTS221_WriteReg(handle, HTS221_CTRL_REG1, 1, &tmp)) return HTS221_ERROR; return HTS221_OK; } /** * @brief Get block data update mode. * @param *handle Device handle. * @param Pointer to the returned value with block data update mode status. * @retval Error code [HTS221_OK, HTS221_ERROR]. */ HTS221_Error_et HTS221_Get_BduMode(void *handle, HTS221_State_et* status) { uint8_t tmp; if(HTS221_ReadReg(handle, HTS221_CTRL_REG1, 1, &tmp)) return HTS221_ERROR; *status = (HTS221_State_et)((tmp & HTS221_BDU_MASK) >> HTS221_BDU_BIT); return HTS221_OK; } /** * @brief Enter or exit from power down mode. * @param *handle Device handle. * @param status can be HTS221_SET: HTS221 in power down mode. * @param status can be HTS221_REET: HTS221 in active mode. * This parameter is a @ref HTS221_BitStatus_et. * @retval Error code [HTS221_OK, HTS221_ERROR]. */ HTS221_Error_et HTS221_Set_PowerDownMode(void *handle, HTS221_BitStatus_et status) { uint8_t tmp; HTS221_assert_param(IS_HTS221_BitStatus(status)); if(HTS221_ReadReg(handle, HTS221_CTRL_REG1, 1, &tmp)) return HTS221_ERROR; tmp &= ~HTS221_PD_MASK; tmp |= ((uint8_t)status) << HTS221_PD_BIT; if(HTS221_WriteReg(handle, HTS221_CTRL_REG1, 1, &tmp)) return HTS221_ERROR; return HTS221_OK; } /** * @brief Get if HTS221 is in active mode or in power down mode. * @param *handle Device handle. * @param Pointer to the returned value with HTS221 status. * @retval Error code [HTS221_OK, HTS221_ERROR]. */ HTS221_Error_et HTS221_Get_PowerDownMode(void *handle, HTS221_BitStatus_et* status) { uint8_t tmp; if(HTS221_ReadReg(handle, HTS221_CTRL_REG1, 1, &tmp)) return HTS221_ERROR; *status = (HTS221_BitStatus_et)((tmp & HTS221_PD_MASK) >> HTS221_PD_BIT); return HTS221_OK; } /** * @brief Set the output data rate mode. * @param *handle Device handle. * @param odr is the output data rate mode. * This parameter is a @ref HTS221_Odr_et. * @retval Error code [HTS221_OK, HTS221_ERROR]. */ HTS221_Error_et HTS221_Set_Odr(void *handle, HTS221_Odr_et odr) { uint8_t tmp; HTS221_assert_param(IS_HTS221_ODR(odr)); if(HTS221_ReadReg(handle, HTS221_CTRL_REG1, 1, &tmp)) return HTS221_ERROR; tmp &= ~HTS221_ODR_MASK; tmp |= (uint8_t)odr; if(HTS221_WriteReg(handle, HTS221_CTRL_REG1, 1, &tmp)) return HTS221_ERROR; return HTS221_OK; } /** * @brief Get the output data rate mode. * @param *handle Device handle. * @param Pointer to the returned value with output data rate mode. * @retval Error code [HTS221_OK, HTS221_ERROR]. */ HTS221_Error_et HTS221_Get_Odr(void *handle, HTS221_Odr_et* odr) { uint8_t tmp; if(HTS221_ReadReg(handle, HTS221_CTRL_REG1, 1, &tmp)) return HTS221_ERROR; tmp &= HTS221_ODR_MASK; *odr = (HTS221_Odr_et)tmp; return HTS221_OK; } /** * @brief Reboot Memory Content. * @param *handle Device handle. * @retval Error code [HTS221_OK, HTS221_ERROR]. */ HTS221_Error_et HTS221_MemoryBoot(void *handle) { uint8_t tmp; if(HTS221_ReadReg(handle, HTS221_CTRL_REG2, 1, &tmp)) return HTS221_ERROR; tmp |= HTS221_BOOT_MASK; if(HTS221_WriteReg(handle, HTS221_CTRL_REG2, 1, &tmp)) return HTS221_ERROR; return HTS221_OK; } /** * @brief Configure the internal heater. * @param *handle Device handle. * @param The status of the internal heater [HTS221_ENABLE/HTS221_DISABLE]. * This parameter is a @ref HTS221_State_et. * @retval Error code [HTS221_OK, HTS221_ERROR] */ HTS221_Error_et HTS221_Set_HeaterState(void *handle, HTS221_State_et status) { uint8_t tmp; HTS221_assert_param(IS_HTS221_State(status)); if(HTS221_ReadReg(handle, HTS221_CTRL_REG2, 1, &tmp)) return HTS221_ERROR; tmp &= ~HTS221_HEATHER_MASK; tmp |= ((uint8_t)status) << HTS221_HEATHER_BIT; if(HTS221_WriteReg(handle, HTS221_CTRL_REG2, 1, &tmp)) return HTS221_ERROR; return HTS221_OK; } /** * @brief Get the internal heater. * @param *handle Device handle. * @param Pointer to the returned status of the internal heater [HTS221_ENABLE/HTS221_DISABLE]. * @retval Error code [HTS221_OK, HTS221_ERROR]. */ HTS221_Error_et HTS221_Get_HeaterState(void *handle, HTS221_State_et* status) { uint8_t tmp; if(HTS221_ReadReg(handle, HTS221_CTRL_REG2, 1, &tmp)) return HTS221_ERROR; *status = (HTS221_State_et)((tmp & HTS221_HEATHER_MASK) >> HTS221_HEATHER_BIT); return HTS221_OK; } /** * @brief Set ONE_SHOT bit to start a new conversion (ODR mode has to be 00). * Once the measurement is done, ONE_SHOT bit is self-cleared. * @param *handle Device handle. * @retval Error code [HTS221_OK, HTS221_ERROR]. */ HTS221_Error_et HTS221_StartOneShotMeasurement(void *handle) { uint8_t tmp; if(HTS221_ReadReg(handle, HTS221_CTRL_REG2, 1, &tmp)) return HTS221_ERROR; tmp |= HTS221_ONE_SHOT_MASK; if(HTS221_WriteReg(handle, HTS221_CTRL_REG2, 1, &tmp)) return HTS221_ERROR; return HTS221_OK; } /** * @brief Set level configuration of the interrupt pin DRDY. * @param *handle Device handle. * @param status can be HTS221_LOW_LVL: active level is LOW. * @param status can be HTS221_HIGH_LVL: active level is HIGH. * This parameter is a @ref HTS221_State_et. * @retval Error code [HTS221_OK, HTS221_ERROR]. */ HTS221_Error_et HTS221_Set_IrqActiveLevel(void *handle, HTS221_DrdyLevel_et value) { uint8_t tmp; HTS221_assert_param(IS_HTS221_DrdyLevelType(value)); if(HTS221_ReadReg(handle, HTS221_CTRL_REG3, 1, &tmp)) return HTS221_ERROR; tmp &= ~HTS221_DRDY_H_L_MASK; tmp |= (uint8_t)value; if(HTS221_WriteReg(handle, HTS221_CTRL_REG3, 1, &tmp)) return HTS221_ERROR; return HTS221_OK; } /** * @brief Get level configuration of the interrupt pin DRDY. * @param *handle Device handle. * @param Pointer to the returned status of the level configuration [HTS221_ENABLE/HTS221_DISABLE]. * @retval Error code [HTS221_OK, HTS221_ERROR]. */ HTS221_Error_et HTS221_Get_IrqActiveLevel(void *handle, HTS221_DrdyLevel_et* value) { uint8_t tmp; if(HTS221_ReadReg(handle, HTS221_CTRL_REG3, 1, &tmp)) return HTS221_ERROR; *value = (HTS221_DrdyLevel_et)(tmp & HTS221_DRDY_H_L_MASK); return HTS221_OK; } /** * @brief Set Push-pull/open drain configuration for the interrupt pin DRDY. * @param *handle Device handle. * @param value is the output type configuration. * This parameter is a @ref HTS221_OutputType_et. * @retval Error code [HTS221_OK, HTS221_ERROR]. */ HTS221_Error_et HTS221_Set_IrqOutputType(void *handle, HTS221_OutputType_et value) { uint8_t tmp; HTS221_assert_param(IS_HTS221_OutputType(value)); if(HTS221_ReadReg(handle, HTS221_CTRL_REG3, 1, &tmp)) return HTS221_ERROR; tmp &= ~HTS221_PP_OD_MASK; tmp |= (uint8_t)value; if(HTS221_WriteReg(handle, HTS221_CTRL_REG3, 1, &tmp)) return HTS221_ERROR; return HTS221_OK; } /** * @brief Get the configuration for the interrupt pin DRDY. * @param *handle Device handle. * @param Pointer to the returned value with output type configuration. * @retval Error code [HTS221_OK, HTS221_ERROR]. */ HTS221_Error_et HTS221_Get_IrqOutputType(void *handle, HTS221_OutputType_et* value) { uint8_t tmp; if(HTS221_ReadReg(handle, HTS221_CTRL_REG3, 1, &tmp)) return HTS221_ERROR; *value = (HTS221_OutputType_et)(tmp & HTS221_PP_OD_MASK); return HTS221_OK; } /** * @brief Enable/disable the interrupt mode. * @param *handle Device handle. * @param status is the enable/disable for the interrupt mode. * This parameter is a @ref HTS221_State_et. * @retval Error code [HTS221_OK, HTS221_ERROR]. */ HTS221_Error_et HTS221_Set_IrqEnable(void *handle, HTS221_State_et status) { uint8_t tmp; HTS221_assert_param(IS_HTS221_State(status)); if(HTS221_ReadReg(handle, HTS221_CTRL_REG3, 1, &tmp)) return HTS221_ERROR; tmp &= ~HTS221_DRDY_MASK; tmp |= ((uint8_t)status) << HTS221_DRDY_BIT; if(HTS221_WriteReg(handle, HTS221_CTRL_REG3, 1, &tmp)) return HTS221_ERROR; return HTS221_OK; } /** * @brief Get the interrupt mode. * @param *handle Device handle. * @param Pointer to the returned status of the interrupt mode configuration [HTS221_ENABLE/HTS221_DISABLE]. * @retval Error code [HTS221_OK, HTS221_ERROR]. */ HTS221_Error_et HTS221_Get_IrqEnable(void *handle, HTS221_State_et* status) { uint8_t tmp; if(HTS221_ReadReg(handle, HTS221_CTRL_REG3, 1, &tmp)) return HTS221_ERROR; *status = (HTS221_State_et)((tmp & HTS221_DRDY_MASK) >> HTS221_DRDY_BIT); return HTS221_OK; } #ifdef USE_FULL_ASSERT_HTS221 /** * @brief Reports the name of the source file and the source line number * where the assert_param error has occurred. * @param file: pointer to the source file name * @param line: assert_param error line source number * @retval : None */ void HTS221_assert_failed(uint8_t* file, uint32_t line) { /* User can add his own implementation to report the file name and line number */ printf("Wrong parameters value: file %s on line %d\r\n", file, (int)line); /* Infinite loop */ while (1) { } } #endif /** * @} */ /** * @} */ /** * @} */ /******************* (C) COPYRIGHT 2013 STMicroelectronics *****END OF FILE****/
1.140625
1
src/resource/protocol.h
01org/murphy
10
812
/* * Copyright (c) 2012, Intel Corporation * * 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 Intel Corporation nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef __MURPHY_RESOURCE_PROTOCOL_H__ #define __MURPHY_RESOURCE_PROTOCOL_H__ #include <stdint.h> #include <stdbool.h> #include <stdlib.h> #include <murphy/common/msg.h> #define RESPROTO_DEFAULT_ADDRESS "unxs:@murphy-resource-native" #define RESPROTO_DEFAULT_ADDRVAR "MURPHY_RESOURCE_ADDRESS" #define RESPROTO_BIT(n) ((uint32_t)1 << (n)) #define RESPROTO_RSETFLAG_AUTORELEASE RESPROTO_BIT(0) #define RESPROTO_RSETFLAG_AUTOACQUIRE RESPROTO_BIT(1) #define RESPROTO_RSETFLAG_NOEVENTS RESPROTO_BIT(2) #define RESPROTO_RSETFLAG_DONTWAIT RESPROTO_BIT(3) #define RESPROTO_RESFLAG_MANDATORY RESPROTO_BIT(0) #define RESPROTO_RESFLAG_SHARED RESPROTO_BIT(1) #define RESPROTO_TAG(x) ((uint16_t)(x)) #define RESPROTO_MESSAGE_END MRP_MSG_FIELD_END #define RESPROTO_SECTION_END RESPROTO_TAG(1) #define RESPROTO_ARRAY_DIMENSION RESPROTO_TAG(2) #define RESPROTO_SEQUENCE_NO RESPROTO_TAG(3) #define RESPROTO_REQUEST_TYPE RESPROTO_TAG(4) #define RESPROTO_REQUEST_STATUS RESPROTO_TAG(5) #define RESPROTO_RESOURCE_SET_ID RESPROTO_TAG(6) #define RESPROTO_RESOURCE_STATE RESPROTO_TAG(7) #define RESPROTO_RESOURCE_GRANT RESPROTO_TAG(8) #define RESPROTO_RESOURCE_ADVICE RESPROTO_TAG(9) #define RESPROTO_RESOURCE_ID RESPROTO_TAG(10) #define RESPROTO_RESOURCE_NAME RESPROTO_TAG(11) #define RESPROTO_RESOURCE_FLAGS RESPROTO_TAG(12) #define RESPROTO_RESOURCE_PRIORITY RESPROTO_TAG(13) #define RESPROTO_CLASS_NAME RESPROTO_TAG(14) #define RESPROTO_ZONE_NAME RESPROTO_TAG(15) #define RESPROTO_ATTRIBUTE_INDEX RESPROTO_TAG(16) #define RESPROTO_ATTRIBUTE_NAME RESPROTO_TAG(17) #define RESPROTO_ATTRIBUTE_VALUE RESPROTO_TAG(18) typedef enum { RESPROTO_QUERY_RESOURCES, RESPROTO_QUERY_CLASSES, RESPROTO_QUERY_ZONES, RESPROTO_CREATE_RESOURCE_SET, RESPROTO_DESTROY_RESOURCE_SET, RESPROTO_ACQUIRE_RESOURCE_SET, RESPROTO_RELEASE_RESOURCE_SET, RESPROTO_RESOURCES_EVENT, } mrp_resproto_request_t; typedef enum { RESPROTO_RELEASE, RESPROTO_ACQUIRE, } mrp_resproto_state_t; static inline const char *mrp_resource_get_default_address(void) { const char *addr; if ((addr = getenv(RESPROTO_DEFAULT_ADDRVAR)) == NULL) return RESPROTO_DEFAULT_ADDRESS; else return addr; } #endif /* __MURPHY_RESOURCE_PROTOCOL_H__ */ /* * Local Variables: * c-basic-offset: 4 * indent-tabs-mode: nil * End: * */
1.0625
1
src/tree.c
fanchanghu/libal
1
820
/** * Copyright (c) 2015 - 2021 YIYAS * * This source code is licensed under BSD 3-Clause License (the "License"). * You may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/BSD-3-Clause */
0.734375
1
src/searching-algorithms/binary-search/main.c
codemons/codebase-c
1
828
#include <stdio.h> #include "binary-search.h" int main() { int arr[' '], arrSize, search, i; printf("Enter size of the array ::"); scanf("%d", &arrSize); printf("\nEnter elements of the array in ascending order ::\n"); for (i = 0; i < arrSize; i++) scanf("%d", &arr[i]); printf("Enter the number to be searched ::\n"); scanf("%d", &search); int c = binarySearch(arr, arrSize, search); if (c != -1){ printf("%d is present at location %d.\n", search, c + 1); } else { printf("%d is not present in array.\n", search); } return 0; }
2.71875
3
Classes/MCSinusoid.h
imegatron/MCWaves
1
836
// // MCSinusoid.h // MCWave // // Created by <NAME> on 08/25/2016. // Copyright © 2016 iMegatron's Lab. All rights reserved. // #import <UIKit/UIKit.h> typedef enum MCSinusoidType { MCSinusoidTypeNone, MCSinusoidTypeNormal, MCSinusoidTypeDecay, MCSinusoidTypeDecayTwo, } MCSinusoidType; @interface MCSinusoid : NSObject @property (nonatomic) MCSinusoidType sinusoidType; @property (nonatomic) CGFloat waveSpeed; // Sinusoid: y=Asin(ωx+φ)+k @property (nonatomic) CGFloat y; @property (nonatomic) CGFloat x; // amplitude @property (nonatomic) CGFloat A; // angular velocity @property (nonatomic) CGFloat ω; // initial phase @property (nonatomic) CGFloat φ; // setover @property (nonatomic) CGFloat k; @property (nonatomic) CFTimeInterval currTimestamp; - (void)reset; @end
0.941406
1
tests/scheme/test_let.c
FunnyLanguage/funny
0
844
/* * Funny Language - a free style programming language. * Copyright (C) 2015 by fanguangping (<EMAIL>) * test_let.c */ //http://blog.csdn.net/baisung/article/details/7650488 分类 //http://www.cnblogs.com/xiangnan/p/3387146.html #include "test_let.h" void test_let(Scheme *sc) { test_op(sc, "(let ((x 2) (y 5)) (* x y))", "10"); test_op(sc, "(let* ((x 1) (y (+ x 1))) (cons y x))", "(2 . 1)"); test_op(sc, "(letrec ((x (lambda () (+ y y))) (y 100)) (+ (x) y))", "300"); }
1.640625
2
exilib/BlockAS_i.c
manub686/atomix
3
852
/** Atomix project, BlockAS_i.c, TODO: insert summary here Copyright (c) 2015 Stanford University Released under the Apache License v2.0. See the LICENSE file for details. Author(s): <NAME> */ #include <osl/inc/swpform.h> #include "BlockAS_t.h" void BlockAS_i ( //Uint8 *mem_data_inp, //inp //Uint8 *mem_state_inp, //inp //Uint8 *mem_data_out, //out //Uint8 *mem_state_out, //out //Uint32 mem_data_lengthInBytes, //Uint32 mem_state_lengthInBytes BlockAS_tData *bInpData, BlockAS_tState *bInpState, BlockAS_tData *bOutData, BlockAS_tState *bOutState ) { int i = 0; int sum = 0; //int factor = ((Uint32 *)mem_state_inp)[0]; int factor = bInpState->factor; //for (i = 0; i < mem_data_lengthInBytes/4; i++) { for (i = 0; i < BLOCKAS_N_VALS; i++) { //((Uint32 *)mem_data_out)[i] = ((Uint32 *)mem_data_inp)[i] + factor; bOutData->val[i] = bInpData->val[i] + factor; //sum += ((Uint32 *)mem_data_out)[i]; sum += bOutData->val[i]; } factor = factor + 1; //((Uint32 *)mem_state_out)[0] = factor; bOutState->factor = factor; DEBUG( printf("AS: Buffer sum %d\n", sum); ) }
1.46875
1
src/ppl/nn/engines/riscv/impls/src/ppl/kernel/riscv/fp32/reduce/reduce_n4cx_fp32.h
Alcanderian/ppl.nn
764
860
// 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. #ifndef __ST_PPL_KERNEL_RISCV_FP32_REDUCE_REDUCE_N4CX_FP32_H_ #define __ST_PPL_KERNEL_RISCV_FP32_REDUCE_REDUCE_N4CX_FP32_H_ #include "ppl/kernel/riscv/fp32/reduce/reduce_kernel_fp32.h" #include "ppl/common/log.h" namespace ppl { namespace kernel { namespace riscv { #define C_BLK() ((int64_t)4) template <reduce_op_type_t op> void reduce_n4cx_lastdim_no_reduce_fp32(const float* src, float* dst, const int64_t dim_length, const int64_t remain_c) { const int64_t parall_d = 16; const int64_t unroll_len = parall_d * C_BLK(); const auto vl = vsetvli(C_BLK(), RVV_E32, RVV_M1); int64_t i = 0; for (; i + unroll_len < dim_length * C_BLK(); i += unroll_len) { vsev_float32xm1(dst + i + 0 * C_BLK(), reduce_vector_kernel_fp32<op>(vlev_float32xm1(src + i + 0 * C_BLK(), vl), vlev_float32xm1(dst + i + 0 * C_BLK(), vl)), vl); vsev_float32xm1(dst + i + 1 * C_BLK(), reduce_vector_kernel_fp32<op>(vlev_float32xm1(src + i + 1 * C_BLK(), vl), vlev_float32xm1(dst + i + 1 * C_BLK(), vl)), vl); vsev_float32xm1(dst + i + 2 * C_BLK(), reduce_vector_kernel_fp32<op>(vlev_float32xm1(src + i + 2 * C_BLK(), vl), vlev_float32xm1(dst + i + 2 * C_BLK(), vl)), vl); vsev_float32xm1(dst + i + 3 * C_BLK(), reduce_vector_kernel_fp32<op>(vlev_float32xm1(src + i + 3 * C_BLK(), vl), vlev_float32xm1(dst + i + 3 * C_BLK(), vl)), vl); vsev_float32xm1(dst + i + 4 * C_BLK(), reduce_vector_kernel_fp32<op>(vlev_float32xm1(src + i + 4 * C_BLK(), vl), vlev_float32xm1(dst + i + 4 * C_BLK(), vl)), vl); vsev_float32xm1(dst + i + 5 * C_BLK(), reduce_vector_kernel_fp32<op>(vlev_float32xm1(src + i + 5 * C_BLK(), vl), vlev_float32xm1(dst + i + 5 * C_BLK(), vl)), vl); vsev_float32xm1(dst + i + 6 * C_BLK(), reduce_vector_kernel_fp32<op>(vlev_float32xm1(src + i + 6 * C_BLK(), vl), vlev_float32xm1(dst + i + 6 * C_BLK(), vl)), vl); vsev_float32xm1(dst + i + 7 * C_BLK(), reduce_vector_kernel_fp32<op>(vlev_float32xm1(src + i + 7 * C_BLK(), vl), vlev_float32xm1(dst + i + 7 * C_BLK(), vl)), vl); vsev_float32xm1(dst + i + 8 * C_BLK(), reduce_vector_kernel_fp32<op>(vlev_float32xm1(src + i + 8 * C_BLK(), vl), vlev_float32xm1(dst + i + 8 * C_BLK(), vl)), vl); vsev_float32xm1(dst + i + 9 * C_BLK(), reduce_vector_kernel_fp32<op>(vlev_float32xm1(src + i + 9 * C_BLK(), vl), vlev_float32xm1(dst + i + 9 * C_BLK(), vl)), vl); vsev_float32xm1(dst + i + 10 * C_BLK(), reduce_vector_kernel_fp32<op>(vlev_float32xm1(src + i + 10 * C_BLK(), vl), vlev_float32xm1(dst + i + 10 * C_BLK(), vl)), vl); vsev_float32xm1(dst + i + 11 * C_BLK(), reduce_vector_kernel_fp32<op>(vlev_float32xm1(src + i + 11 * C_BLK(), vl), vlev_float32xm1(dst + i + 11 * C_BLK(), vl)), vl); vsev_float32xm1(dst + i + 12 * C_BLK(), reduce_vector_kernel_fp32<op>(vlev_float32xm1(src + i + 12 * C_BLK(), vl), vlev_float32xm1(dst + i + 12 * C_BLK(), vl)), vl); vsev_float32xm1(dst + i + 13 * C_BLK(), reduce_vector_kernel_fp32<op>(vlev_float32xm1(src + i + 13 * C_BLK(), vl), vlev_float32xm1(dst + i + 13 * C_BLK(), vl)), vl); vsev_float32xm1(dst + i + 14 * C_BLK(), reduce_vector_kernel_fp32<op>(vlev_float32xm1(src + i + 14 * C_BLK(), vl), vlev_float32xm1(dst + i + 14 * C_BLK(), vl)), vl); vsev_float32xm1(dst + i + 15 * C_BLK(), reduce_vector_kernel_fp32<op>(vlev_float32xm1(src + i + 15 * C_BLK(), vl), vlev_float32xm1(dst + i + 15 * C_BLK(), vl)), vl); } for (; i < dim_length * C_BLK(); i += C_BLK()) { vsev_float32xm1(dst + i, reduce_vector_kernel_fp32<op>(vlev_float32xm1(src + i, vl), vlev_float32xm1(dst + i, vl)), vl); } } template <reduce_op_type_t op> void reduce_n4cx_lastdim_reduce_w_fp32(const float* src, float* dst, const int64_t dim_length, const int64_t remain_c) { const int64_t parall_d = 1; const int64_t unroll_len = parall_d * C_BLK(); const auto vl = vsetvli(C_BLK(), RVV_E32, RVV_M1); float32xm1_t v_reduce_val = vlev_float32xm1(dst, vl); int64_t i = 0; for (; i < dim_length * C_BLK(); i += unroll_len) { v_reduce_val = reduce_vector_kernel_fp32<op>(vlev_float32xm1(src + i, vl), v_reduce_val); } vsev_float32xm1(dst, v_reduce_val, vl); } template <reduce_op_type_t op> void reduce_n4cx_lastdim_reduce_c_fp32(const float* src, float* dst, const int64_t dim_length, const int64_t remain_c) { const auto vl = vsetvli(C_BLK(), RVV_E32, RVV_M1); if (remain_c >= C_BLK()) { int64_t i = 0; for (; i < dim_length * C_BLK(); i += C_BLK()) { float reduce_val = reduce_vector_all_lanes_kernel_fp32<op>(vlev_float32xm1(src + i, vl)); dst[i] = reduce_scalar_kernel_fp32<op>(dst[i], reduce_val); } } else { // if remain_c is aligned to C_BLK(), this branch is useless -- make sure 'src_shape[1]' is aligned } } template <reduce_op_type_t op> void reduce_n4cx_lastdim_reduce_cw_fp32(const float* src, float* dst, const int64_t dim_length, const int64_t remain_c) { const auto vl = vsetvli(C_BLK(), RVV_E32, RVV_M1); if (remain_c >= C_BLK()) { float32xm1_t v_reduce_val = vfmvvf_float32xm1(reduce_init_val_fp32<op>(), vl); int64_t i = 0; for (; i < dim_length * C_BLK(); i += C_BLK()) { v_reduce_val = reduce_vector_kernel_fp32<op>(vlev_float32xm1(src + i, vl), v_reduce_val); } float reduce_val = reduce_vector_all_lanes_kernel_fp32<op>(v_reduce_val); dst[0] = reduce_scalar_kernel_fp32<op>(reduce_val, dst[0]); } else { // // if remain_c is aligned to C_BLK(), this branch is useless -- make sure 'src_shape[1]' is aligned } } template <reduce_op_type_t op> void reduce_n4cx_recursive_fp32(const float* src, float* dst, const ppl::nn::TensorShape* src_shape, const ppl::nn::TensorShape* dst_shape, const int64_t dim_idx, const int64_t* inc_src, const int64_t* inc_dst, const int64_t c_dim_idx, int64_t remain_c) { if (dim_idx == src_shape->GetDimCount() - 1) { const bool reduce_on_w = src_shape->GetDim(dim_idx) != dst_shape->GetDim(dim_idx); const bool reduce_on_c = src_shape->GetDim(c_dim_idx) != dst_shape->GetDim(c_dim_idx); const int64_t dim_length = src_shape->GetDim(dim_idx); if (!reduce_on_c && !reduce_on_w) { reduce_n4cx_lastdim_no_reduce_fp32<op>(src, dst, dim_length, remain_c); } else if (!reduce_on_c && reduce_on_w) { reduce_n4cx_lastdim_reduce_w_fp32<op>(src, dst, dim_length, remain_c); } else if (reduce_on_c && !reduce_on_w) { reduce_n4cx_lastdim_reduce_c_fp32<op>(src, dst, dim_length, remain_c); } else { reduce_n4cx_lastdim_reduce_cw_fp32<op>(src, dst, dim_length, remain_c); } } else { const int64_t len = dim_idx == c_dim_idx ? div_up(src_shape->GetDim(dim_idx), C_BLK()) : src_shape->GetDim(dim_idx); for (int64_t i = 0; i < len; i++) { if (dim_idx == c_dim_idx) { remain_c = src_shape->GetDim(c_dim_idx) - i * C_BLK(); } reduce_n4cx_recursive_fp32<op>(src + i * inc_src[dim_idx], dst + i * inc_dst[dim_idx], src_shape, dst_shape, dim_idx + 1, inc_src, inc_dst, c_dim_idx, remain_c); } } } template <reduce_op_type_t op> ppl::common::RetCode reduce_n4cx_fp32(const float* src, float* dst, const ppl::nn::TensorShape* src_shape, const ppl::nn::TensorShape* dst_shape, const int32_t* axes, const int32_t num_axes, const int64_t c_dim_idx) { if (src_shape->GetDimCount() > PPL_RISCV_TENSOR_MAX_DIMS()) { return ppl::common::RC_UNSUPPORTED; } ppl::nn::TensorShape& padded_dst_shape = *(new ppl::nn::TensorShape(*src_shape)); for (int64_t i = 0; i < num_axes; i++) { padded_dst_shape.SetDim(axes[i], 1); } padded_dst_shape.CalcPadding(); reduce_preprocess_fp32<op>(dst, padded_dst_shape.GetElementsIncludingPadding()); int64_t dim_count = padded_dst_shape.GetDimCount(); int64_t inc_src[PPL_RISCV_TENSOR_MAX_DIMS()] = {0}; int64_t inc_dst[PPL_RISCV_TENSOR_MAX_DIMS()] = {0}; int64_t stride_src = C_BLK(); int64_t stride_dst = C_BLK(); for (int64_t i = dim_count - 1; i >= 0; i--) { int64_t src_dim = src_shape->GetDim(i); int64_t dst_dim = padded_dst_shape.GetDim(i); inc_src[i] = src_dim == 1 ? 0 : stride_src; inc_dst[i] = dst_dim == 1 ? 0 : stride_dst; if (i == c_dim_idx) { src_dim = div_up(src_dim, C_BLK()); dst_dim = div_up(dst_dim, C_BLK()); } stride_src *= src_dim; stride_dst *= dst_dim; } reduce_n4cx_recursive_fp32<op>(src, dst, src_shape, &padded_dst_shape, 0, inc_src, inc_dst, c_dim_idx, src_shape->GetDim(c_dim_idx)); int64_t reduce_factor = 1; for (int64_t i = 0; i < dim_count; i++) { reduce_factor *= src_shape->GetDim(i) / padded_dst_shape.GetDim(i); } reduce_postprocess_fp32<op>(dst, padded_dst_shape.GetElementsIncludingPadding(), reduce_factor); delete &padded_dst_shape; return ppl::common::RC_SUCCESS; } }}}; // namespace ppl::kernel::riscv #endif // __ST_PPL_KERNEL_RISCV_FP32_REDUCE_REDUCE_N4CX_FP32_H_
1.273438
1
src/optimization/optimization_task.h
wfoperihnofiksnfvopjdf/k52
6
868
#ifndef OPTIMIZATION_TASK_H #define OPTIMIZATION_TASK_H #include <k52/common/disallow_copy_and_assign.h> #include <k52/parallel/i_task.h> #include <k52/optimization/params/i_parameters.h> #include <k52/optimization/i_objective_function.h> #include <k52/optimization/i_optimizer.h> #ifdef BUILD_WITH_MPI #include <k52/parallel/mpi/i_mpi_task.h> #include <k52/parallel/mpi/i_mpi_task_result.h> #endif namespace k52 { namespace optimization { class OptimizationTask : #ifdef BUILD_WITH_MPI public k52::parallel::mpi::IMpiTask #else public k52::parallel::ITask #endif { public: typedef boost::shared_ptr<OptimizationTask> shared_ptr; //TODO remove as needed only for registering OptimizationTask(); OptimizationTask(const IOptimizer* optimizer, const IParameters* initial_parameters, const IObjectiveFunction* function_to_optimize, bool maximize); #ifdef BUILD_WITH_MPI virtual k52::parallel::mpi::IMpiTaskResult::shared_ptr CreateEmptyResult() const; virtual OptimizationTask* Clone() const; virtual void Send(boost::mpi::communicator* communicator, int target) const; virtual void Receive(boost::mpi::communicator* communicator, int source); virtual k52::parallel::mpi::IMpiTaskResult* Perform() const; #else virtual k52::parallel::ITaskResult* Perform() const; #endif private: IParameters::shared_ptr initial_parameters_; IObjectiveFunction::shared_ptr function_to_optimize_; IOptimizer::shared_ptr optimizer_; bool maximize_; }; }/* namespace optimization */ }/* namespace k52 */ #endif /* OPTIMIZATION_TASK_H */
1.4375
1
Adafruit_SSD1306/Adafruit_SSD1306.h
eliaraysalem/Blinkit-Arduino-integration
0
876
/********************************************************************* This is a library for our Monochrome OLEDs based on SSD1306 drivers Pick one up today in the adafruit shop! ------> http://www.adafruit.com/category/63_98 These displays use SPI to communicate, 4 or 5 pins are required to interface Adafruit invests time and resources providing this open source code, please support Adafruit and open-source hardware by purchasing products from Adafruit! Written by <NAME>/Ladyada for Adafruit Industries. BSD license, check license.txt for more information All text above, and the splash screen must be included in any redistribution *********************************************************************/ #ifndef _Adafruit_SSD1306_H_ #define _Adafruit_SSD1306_H_ #if ARDUINO >= 100 #include "Arduino.h" #define WIRE_WRITE Wire.write #else #include "WProgram.h" #define WIRE_WRITE Wire.send #endif #if defined(__SAM3X8E__) typedef volatile RwReg PortReg; typedef uint32_t PortMask; #define HAVE_PORTREG #elif defined(ARDUINO_ARCH_SAMD) // not supported #elif defined(ESP8266) || defined(ESP32) || defined(ARDUINO_STM32_FEATHER) || defined(__arc__) typedef volatile uint32_t PortReg; typedef uint32_t PortMask; #elif defined(__AVR__) typedef volatile uint8_t PortReg; typedef uint8_t PortMask; #define HAVE_PORTREG #else // chances are its 32 bit so assume that typedef volatile uint32_t PortReg; typedef uint32_t PortMask; #endif #include <SPI.h> #include <Adafruit_GFX.h> #define BLACK 0 #define WHITE 1 #define INVERSE 2 #define SSD1306_I2C_ADDRESS 0x3C // 011110+SA0+RW - 0x3C or 0x3D // Address for 128x32 is 0x3C // Address for 128x64 is 0x3D (default) or 0x3C (if SA0 is grounded) /*========================================================================= SSD1306 Displays ----------------------------------------------------------------------- The driver is used in multiple displays (128x64, 128x32, etc.). Select the appropriate display below to create an appropriately sized framebuffer, etc. SSD1306_128_64 128x64 pixel display SSD1306_128_32 128x32 pixel display SSD1306_96_16 -----------------------------------------------------------------------*/ #define SSD1306_128_64 // #define SSD1306_128_32 // #define SSD1306_96_16 /*=========================================================================*/ #if defined SSD1306_128_64 && defined SSD1306_128_32 #error "Only one SSD1306 display can be specified at once in SSD1306.h" #endif #if !defined SSD1306_128_64 && !defined SSD1306_128_32 && !defined SSD1306_96_16 #error "At least one SSD1306 display must be specified in SSD1306.h" #endif #if defined SSD1306_128_64 #define SSD1306_LCDWIDTH 128 #define SSD1306_LCDHEIGHT 64 #endif #if defined SSD1306_128_32 #define SSD1306_LCDWIDTH 128 #define SSD1306_LCDHEIGHT 32 #endif #if defined SSD1306_96_16 #define SSD1306_LCDWIDTH 96 #define SSD1306_LCDHEIGHT 16 #endif #define SSD1306_SETCONTRAST 0x81 #define SSD1306_DISPLAYALLON_RESUME 0xA4 #define SSD1306_DISPLAYALLON 0xA5 #define SSD1306_NORMALDISPLAY 0xA6 #define SSD1306_INVERTDISPLAY 0xA7 #define SSD1306_DISPLAYOFF 0xAE #define SSD1306_DISPLAYON 0xAF #define SSD1306_SETDISPLAYOFFSET 0xD3 #define SSD1306_SETCOMPINS 0xDA #define SSD1306_SETVCOMDETECT 0xDB #define SSD1306_SETDISPLAYCLOCKDIV 0xD5 #define SSD1306_SETPRECHARGE 0xD9 #define SSD1306_SETMULTIPLEX 0xA8 #define SSD1306_SETLOWCOLUMN 0x00 #define SSD1306_SETHIGHCOLUMN 0x10 #define SSD1306_SETSTARTLINE 0x40 #define SSD1306_MEMORYMODE 0x20 #define SSD1306_COLUMNADDR 0x21 #define SSD1306_PAGEADDR 0x22 #define SSD1306_COMSCANINC 0xC0 #define SSD1306_COMSCANDEC 0xC8 #define SSD1306_SEGREMAP 0xA0 #define SSD1306_CHARGEPUMP 0x8D #define SSD1306_EXTERNALVCC 0x1 #define SSD1306_SWITCHCAPVCC 0x2 // Scrolling #defines #define SSD1306_ACTIVATE_SCROLL 0x2F #define SSD1306_DEACTIVATE_SCROLL 0x2E #define SSD1306_SET_VERTICAL_SCROLL_AREA 0xA3 #define SSD1306_RIGHT_HORIZONTAL_SCROLL 0x26 #define SSD1306_LEFT_HORIZONTAL_SCROLL 0x27 #define SSD1306_VERTICAL_AND_RIGHT_HORIZONTAL_SCROLL 0x29 #define SSD1306_VERTICAL_AND_LEFT_HORIZONTAL_SCROLL 0x2A class Adafruit_SSD1306 : public Adafruit_GFX { public: Adafruit_SSD1306(int8_t SID, int8_t SCLK, int8_t DC, int8_t RST, int8_t CS); Adafruit_SSD1306(int8_t DC, int8_t RST, int8_t CS); Adafruit_SSD1306(int8_t RST = -1); void begin(uint8_t switchvcc = SSD1306_SWITCHCAPVCC, uint8_t i2caddr = SSD1306_I2C_ADDRESS, bool reset=true); void ssd1306_command(uint8_t c); void clearDisplay(void); void invertDisplay(uint8_t i); void display(); void startscrollright(uint8_t start, uint8_t stop); void startscrollleft(uint8_t start, uint8_t stop); void startscrolldiagright(uint8_t start, uint8_t stop); void startscrolldiagleft(uint8_t start, uint8_t stop); void stopscroll(void); void dim(boolean dim); void drawPixel(int16_t x, int16_t y, uint16_t color); virtual void drawFastVLine(int16_t x, int16_t y, int16_t h, uint16_t color); virtual void drawFastHLine(int16_t x, int16_t y, int16_t w, uint16_t color); private: int8_t _i2caddr, _vccstate, sid, sclk, dc, rst, cs; void fastSPIwrite(uint8_t c); boolean hwSPI; #ifdef HAVE_PORTREG PortReg *mosiport, *clkport, *csport, *dcport; PortMask mosipinmask, clkpinmask, cspinmask, dcpinmask; #endif inline void drawFastVLineInternal(int16_t x, int16_t y, int16_t h, uint16_t color) __attribute__((always_inline)); inline void drawFastHLineInternal(int16_t x, int16_t y, int16_t w, uint16_t color) __attribute__((always_inline)); }; #endif /* _Adafruit_SSD1306_H_ */
1.671875
2
canbus_bootloader/src/can.c
Lembed/Cortex-M3-Projects
1
884
/* * bxCAN driver for STM32 family processors * * 2010 <NAME> * */ #include "platform.h" #include "stm32f10x.h" #include <string.h> #include "can.h" // TODO: add others //"1M" "800K" "500K" "250K" "125K" "100K" "50K" "20K" "10K" #define TIMINGS_NUM (sizeof(CAN_Timings)/sizeof(struct can_timing_t)) static const struct can_timing_t CAN_Timings[] = { {"1M", 0x03, 0x115 }, // 36MHz peripheral clock, sample @ 33%, SWJ = 2, TS1 = 1+1, TS2 = 5+1, BRP = 4 {"500K", 0x07, 0x115 }, // 36MHz peripheral clock, sample @ 33%, SWJ = 2, TS1 = 1+1, TS2 = 5+1, BRP = 8 {"250K", 0x0f, 0x115 }, // 36MHz peripheral clock, sample @ 33%, SWJ = 2, TS1 = 1+1, TS2 = 5+1, BRP = 16 }; #define FILTER_NUM 14 static CAN_FilterInitTypeDef CAN_Filters[FILTER_NUM] = { // Id_H, Id_L MskIdH MskIdL FIFO Filt# Mode Scale Active { 0x0000, 0x0000, 0x0000, 0x0000, 0, 0, CAN_FilterMode_IdMask, CAN_FilterScale_32bit, ENABLE }, }; struct can_timing_t *CAN_Timing; static NVIC_InitTypeDef CAN_Int; static void canHWReinit(); uint8_t canChangeBaudRate( CAN_HANDLE fd, char* baud) { (void)fd; uint8_t i; for (i = 0; i < TIMINGS_NUM; i++){ if (strcmp(CAN_Timings[i].baud, baud) == 0) { CAN_Timing = &CAN_Timings[i]; return 0; } } return 1; } void can_init(char* baud) { GPIO_InitTypeDef GPIO_InitStructure; RCC_APB1PeriphClockCmd(RCC_APB1Periph_CAN1, ENABLE); // Configure CAN pin: RX GPIO_InitStructure.GPIO_Pin = GPIO_Pin_11; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_Init(GPIOA, &GPIO_InitStructure); // Configure CAN pin: TX GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_Init(GPIOA, &GPIO_InitStructure); CAN_Int.NVIC_IRQChannelPreemptionPriority = 14; CAN_Int.NVIC_IRQChannelSubPriority = 0; CAN_Timing = &CAN_Timings[0]; canChangeBaudRate(0, baud); canHWReinit(); } static void canHWReinit() { CAN_Int.NVIC_IRQChannelCmd = DISABLE; CAN_Int.NVIC_IRQChannel = USB_HP_CAN1_TX_IRQn; NVIC_Init(&CAN_Int); CAN_Int.NVIC_IRQChannel = USB_LP_CAN1_RX0_IRQn; NVIC_Init(&CAN_Int); CAN_Int.NVIC_IRQChannel = CAN1_SCE_IRQn; NVIC_Init(&CAN_Int); // Reset CAN1 - clears the error state CAN_DeInit(CAN1); can_filter_apply(); // enable intertrupts //CAN1->IER = 0x00008F13; // enable all interrupts (except FIFOx full/overrun, sleep/wakeup) CAN1->IER = CAN_IER_TMEIE ;//| CAN_IER_FMPIE0; CAN1->IER |= CAN_IER_EWGIE | CAN_IER_EPVIE | CAN_IER_BOFIE | CAN_IER_LECIE; // CAN1->IER |= CAN_IER_ERRIE; // FIXME // enter the init mode CAN1->MCR &= ~CAN_MCR_SLEEP; CAN1->MCR |= CAN_MCR_INRQ; // wait for it ! while ((CAN1->MSR & CAN_MSR_INAK) != CAN_MSR_INAK); /* setup timing */ CAN1->BTR = (CAN_Timing->ts << 16) | CAN_Timing->brp; /* finish bxCAN setup */ CAN1->MCR |= CAN_MCR_ABOM; CAN1->MCR |= CAN_MCR_TXFP | CAN_MCR_RFLM | CAN_MCR_AWUM; // automatic wakeup, tx round-robin mode CAN1->MCR &= ~(CAN_MCR_SLEEP | 0x10000); // we don't support sleep, no debug-freeze CAN1->MCR &= ~CAN_MCR_INRQ; // leave init mode CAN_Int.NVIC_IRQChannelCmd = ENABLE; CAN_Int.NVIC_IRQChannel = USB_HP_CAN1_TX_IRQn; NVIC_Init(&CAN_Int); CAN_Int.NVIC_IRQChannel = USB_LP_CAN1_RX0_IRQn; NVIC_Init(&CAN_Int); CAN_Int.NVIC_IRQChannel = CAN1_SCE_IRQn; NVIC_Init(&CAN_Int); } void can_filter_clear() { int i; // setup can filters for (i = 0; i < FILTER_NUM; i++) { CAN_Filters[i].CAN_FilterActivation = DISABLE; } } void can_filter_apply() { int i; // setup can filters for (i = 0; i < FILTER_NUM; i++) { if (CAN_Filters[i].CAN_FilterActivation == DISABLE) break; CAN_FilterInit(&CAN_Filters[i]); } } void can_filter_addmask(uint16_t cobid, uint16_t cobid_mask, uint8_t prio) { uint8_t i = 0; for (i = 0; i < FILTER_NUM; i++) { if (CAN_Filters[i].CAN_FilterActivation == DISABLE) break; } // check limit if (i >= FILTER_NUM) return; CAN_Filters[i].CAN_FilterActivation = ENABLE; CAN_Filters[i].CAN_FilterNumber = i; CAN_Filters[i].CAN_FilterScale = CAN_FilterScale_32bit; CAN_Filters[i].CAN_FilterMode = CAN_FilterMode_IdMask; CAN_Filters[i].CAN_FilterFIFOAssignment = (prio > 0)? 1: 0; CAN_Filters[i].CAN_FilterIdHigh = cobid << 5; CAN_Filters[i].CAN_FilterIdLow = 0x0000; CAN_Filters[i].CAN_FilterMaskIdHigh = cobid_mask << 5; CAN_Filters[i].CAN_FilterMaskIdLow = 0x0004; } /* TODO: priority scheduling */ uint8_t can_send(struct can_message_t *m) { uint16_t mailbox = 4; if (CAN1->TSR & (CAN_TSR_TME0 | CAN_TSR_TME1 | CAN_TSR_TME2)) { mailbox = (CAN1->TSR & CAN_TSR_CODE) >> 24; } else { // nothing empty ? :( this should not happen ! // TODO: Error ? return 0xFF; } // clear message CAN1->sTxMailBox[mailbox].TIR &= CAN_TI0R_TXRQ; // add IDE and RTR fields CAN1->sTxMailBox[mailbox].TIR |= m->flags & CAN_MSG_RTR ? 0x02 : 0; // add msg ID (cob_id) CAN1->sTxMailBox[mailbox].TIR |= m->id << 21; // setup the DLC field (lenght) CAN1->sTxMailBox[mailbox].TDTR &= 0xFFFFFFF0; CAN1->sTxMailBox[mailbox].TDTR |= m->flags & CAN_MSG_SIZE; // Set up the data fields CAN1->sTxMailBox[mailbox].TDLR = (((uint32_t)m->data[3] << 24) | ((uint32_t)m->data[2] << 16) | ((uint32_t)m->data[1] << 8) | ((uint32_t)m->data[0])); CAN1->sTxMailBox[mailbox].TDHR = (((uint32_t)m->data[7] << 24) | ((uint32_t)m->data[6] << 16) | ((uint32_t)m->data[5] << 8) | ((uint32_t)m->data[4])); // mark message for transmission CAN1->sTxMailBox[mailbox].TIR |= CAN_TI0R_TXRQ; return 0; } /* TX interrupt */ /* TODO: error propagation */ void USB_HP_CAN1_TX_IRQHandler(void) { if (CAN1->TSR & CAN_TSR_RQCP0) { CAN1->TSR |= CAN_TSR_RQCP0; } if (CAN1->TSR & CAN_TSR_RQCP1) { CAN1->TSR |= CAN_TSR_RQCP1; } if (CAN1->TSR & CAN_TSR_RQCP2) { /* CANController_Status |= (CAN1->TSR & CAN_TSR_ALST2)?CAN_STAT_ALST:0; CANController_Status |= (CAN1->TSR & CAN_TSR_TERR2)?CAN_STAT_TERR:0; CANController_Status |= (CAN1->TSR & CAN_TSR_TXOK2)?CAN_STAT_TXOK:0;*/ CAN1->TSR |= CAN_TSR_RQCP2; } } /* TODO: make this interrupt routine again and make it call canfestival callback (or something) */ /*void USB_LP_CAN1_RX0_IRQHandler(void)*/ uint8_t can_receive(struct can_message_t *m) { uint8_t fifo = 0; if (CAN1->RF1R & 0x03) { fifo = 1; } else if (CAN1->RF0R & 0x03) { fifo = 0; } else { return 0; } if (CAN1->sFIFOMailBox[fifo].RIR & 0x04) { // extended id we do not support // release fifo CAN1->RF0R = CAN_RF0R_RFOM0; return 0; } m->flags = CAN1->sFIFOMailBox[fifo].RIR & 0x02 ? CAN_MSG_RTR : 0; m->flags |= CAN1->sFIFOMailBox[fifo].RDTR & CAN_MSG_SIZE; // standard id m->id = (uint32_t)0x000007FF & (CAN1->sFIFOMailBox[0].RIR >> 21); // copy data bytes m->data[0] = (uint8_t)0xFF & (CAN1->sFIFOMailBox[fifo].RDLR); m->data[1] = (uint8_t)0xFF & (CAN1->sFIFOMailBox[fifo].RDLR >> 8); m->data[2] = (uint8_t)0xFF & (CAN1->sFIFOMailBox[fifo].RDLR >> 16); m->data[3] = (uint8_t)0xFF & (CAN1->sFIFOMailBox[fifo].RDLR >> 24); m->data[4] = (uint8_t)0xFF & (CAN1->sFIFOMailBox[fifo].RDHR); m->data[5] = (uint8_t)0xFF & (CAN1->sFIFOMailBox[fifo].RDHR >> 8); m->data[6] = (uint8_t)0xFF & (CAN1->sFIFOMailBox[fifo].RDHR >> 16); m->data[7] = (uint8_t)0xFF & (CAN1->sFIFOMailBox[fifo].RDHR >> 24); CAN1->RF0R = CAN_RF0R_RFOM0; return fifo+1; } /* status change and error * This ISR is called periodicaly while error condition persists ! * * FIXME: This is very much broken (HW side) !!! */ uint32_t CAN_Error = 0; void CAN1_SCE_IRQHandler(void) { static uint32_t _CAN_Error = 0; static uint32_t _CAN_Error_Last = 0; static uint16_t count = 0; if (CAN1->ESR & (CAN_ESR_EWGF | CAN_ESR_EPVF | CAN_ESR_BOFF)) { // if error happened, copy the state _CAN_Error = CAN1->ESR; // abort msg transmission on Bus-Off if (CAN1->ESR & CAN_ESR_BOFF) { CAN1->TSR |= (CAN_TSR_ABRQ0 | CAN_TSR_ABRQ1 | CAN_TSR_ABRQ2); } // clean flag - not working at all :( CAN1->ESR &= ~ (CAN_ESR_EWGF | CAN_ESR_EPVF | CAN_ESR_BOFF); // clear last error code CAN1->ESR |= CAN_ESR_LEC; // clear interrupt flag CAN1->MSR &= ~CAN_MSR_ERRI; // work around the bug in HW // notify only on "new" error, otherwise reset can controller if (_CAN_Error ^ _CAN_Error_Last) { count = 0; } else { count ++; if (count > 10) { count = 0; // reinit hw canHWReinit(); // notify CAN stack - emcy event CAN_Error = 1; } } _CAN_Error_Last = _CAN_Error; } }
1.679688
2
src/coreclr/pal/src/include/pal/utf8.h
pyracanda/runtime
9,402
892
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /*++ Module Name: include/pal/utf8.h Abstract: Header file for UTF-8 conversion functions. Revision History: --*/ #ifndef _PAL_UTF8_H_ #define _PAL_UTF8_H_ #include <pal/palinternal.h> /* for WCHAR */ #ifdef __cplusplus extern "C" { #endif // __cplusplus /*++ Function : UTF8ToUnicode Convert a string from UTF-8 to UTF-16 (UCS-2) --*/ int UTF8ToUnicode(LPCSTR lpSrcStr, int cchSrc, LPWSTR lpDestStr, int cchDest, DWORD dwFlags); /*++ Function : UnicodeToUTF8 Convert a string from UTF-16 (UCS-2) to UTF-8 --*/ int UnicodeToUTF8(LPCWSTR lpSrcStr, int cchSrc, LPSTR lpDestStr, int cchDest); #ifdef __cplusplus } #endif // __cplusplus #endif /* _PAL_UTF8_H_ */
1.0625
1
av1/encoder/global_motion.h
tmatth/aomanalyzer
4
900
/* * Copyright (c) 2010 The WebM project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #ifndef AV1_ENCODER_GLOBAL_MOTION_H_ #define AV1_ENCODER_GLOBAL_MOTION_H_ #include "aom/aom_integer.h" #ifdef __cplusplus extern "C" { #endif /* Computes global motion parameters between two frames. The array "params" should be length 9, where the first 2 slots are translation parameters in (row, col) order, and the remaining slots correspond to values in the transformation matrix of the corresponding motion model. They are arranged in "params" such that values on the tx-matrix diagonal have odd numbered indices so the folowing matrix: A | B C | D would produce params = [trans row, trans col, B, A, C, D] */ int compute_global_motion_feature_based(TransformationType type, YV12_BUFFER_CONFIG *frm, YV12_BUFFER_CONFIG *ref, double *params); #ifdef __cplusplus } // extern "C" #endif #endif // AV1_ENCODER_GLOBAL_MOTION_H_
1.3125
1
Code/Query/GreaterEqualQuery.h
jungb-basf/rdkit
0
908
// // Copyright (c) 2003-2020 <NAME> and Rational Discovery LLC // // @@ All Rights Reserved @@ // This file is part of the RDKit. // The contents are covered by the terms of the BSD license // which is included in the file license.txt, found at the root // of the RDKit source tree. // #include <RDGeneral/export.h> #ifndef RD_GREATEREQUALQUERY_H #define RD_GREATEREQUALQUERY_H #include "Query.h" #include "EqualityQuery.h" namespace Queries { //! \brief a Query implementing >= using a particular //! value (and an optional tolerance) template <class MatchFuncArgType, class DataFuncArgType = MatchFuncArgType, bool needsConversion = false> class RDKIT_QUERY_EXPORT GreaterEqualQuery : public EqualityQuery<MatchFuncArgType, DataFuncArgType, needsConversion> { public: GreaterEqualQuery() { this->d_tol = 0; }; //! constructs with our target value explicit GreaterEqualQuery(DataFuncArgType what) { this->d_val = what; this->d_tol = 0; this->df_negate = false; }; //! constructs with our target value and a tolerance GreaterEqualQuery(DataFuncArgType v, DataFuncArgType t) { this->d_val = v; this->d_tol = t; this->df_negate = false; }; bool Match(const DataFuncArgType what) const { MatchFuncArgType mfArg = this->TypeConvert(what, Int2Type<needsConversion>()); if (queryCmp(this->d_val, mfArg, this->d_tol) >= 0) { if (this->getNegation()) return false; else return true; } else { if (this->getNegation()) return true; else return false; } }; Query<MatchFuncArgType, DataFuncArgType, needsConversion> *copy() const { GreaterEqualQuery<MatchFuncArgType, DataFuncArgType, needsConversion> *res = new GreaterEqualQuery<MatchFuncArgType, DataFuncArgType, needsConversion>(); res->setVal(this->d_val); res->setTol(this->d_tol); res->setNegation(this->getNegation()); res->setDataFunc(this->d_dataFunc); res->d_description = this->d_description; res->d_queryType = this->d_queryType; return res; }; std::string getFullDescription() const { std::ostringstream res; res << this->getDescription(); res << " " << this->d_val; if (this->getNegation()) res << " ! >= "; else res << " >= "; return res.str(); }; }; } // namespace Queries #endif
1.390625
1
src/enclave/tlsframedendpoint.h
olvrou/CCF
0
916
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the Apache 2.0 License. #pragma once #include "tlsendpoint.h" namespace enclave { class FramedTLSEndpoint : public TLSEndpoint { protected: uint32_t msg_size; size_t count; public: FramedTLSEndpoint( size_t session_id, ringbuffer::AbstractWriterFactory& writer_factory, std::unique_ptr<tls::Context> ctx) : TLSEndpoint(session_id, writer_factory, std::move(ctx)), msg_size(-1), count(0) {} void recv(const uint8_t* data, size_t size) { recv_buffered(data, size); while (true) { // Read framed data. if (msg_size == (uint32_t)-1) { auto len = read(4, true); if (len.size() == 0) return; const uint8_t* data = len.data(); size_t size = len.size(); msg_size = serialized::read<uint32_t>(data, size); LOG_TRACE_FMT("msg size is: {}", msg_size); } // Arbitrary limit on RPC size to stop a client from requesting // a very large allocation. if (msg_size > 1 << 21) { close(); return; } auto req = read(msg_size, true); if (req.size() == 0) return; msg_size = -1; try { if (!handle_data(req)) close(); } catch (...) { // On any exception, close the connection. close(); } } } void send(const std::vector<uint8_t>& data) { // Write framed data. if (data.size() == 0) return; std::vector<uint8_t> len(4); uint8_t* p = len.data(); size_t size = len.size(); serialized::write(p, size, (uint32_t)data.size()); send_buffered(len); send_buffered(data); flush(); } }; }
1.492188
1
CRAB/QuestText.h
arvindrajayadav/unrest
11
924
#pragma once #include "common_header.h" #include "ImageData.h" #include "ParagraphData.h" #include "quest.h" #include "button.h" namespace pyrodactyl { namespace ui { class QuestText : public ParagraphData { protected: //How much the text and bullet positions change per line Vector2i inc; //Color of the highlighted quest int col_s; //The coordinates for drawing image, which is like bullet points in the form of <Bullet> <Text> ImageData img; //The lines per page, we split the quest text into multiple pages if we have to draw more than that unsigned int lines_per_page; //Keep track of which page we are at, and total pages unsigned int current_page, total_page; //The quest entries we start and stop the drawing at int start, stop; //The buttons for cycling between pages of the menu Button prev, next; //Display "Page 1 of 3" style information for the menu HoverInfo status; public: QuestText() { col_s = 0; current_page = 0; start = 0; stop = 0; total_page = 1; lines_per_page = 10; } void Load(rapidxml::xml_node<char> *node); //Reset the value of current page void Reset() { current_page = 0; } void HandleEvents(pyrodactyl::event::Quest &q, const SDL_Event &Event); void Draw(pyrodactyl::event::Quest &q); void SetUI(); }; } }
1.460938
1
Engine/src/Core/TMemory.c
ZackShrout/Thrianta
0
932
#include "TMemory.h" #include "Core/TString.h" #include "Core/Logger.h" #include "Platform/Platform.h" // TODO: Custom string lib #include <string.h> #include <stdio.h> struct memory_stats { u64 totalAllocated; u64 taggedAllocations[MEMORY_TAG_MAX_TAGS]; }; static const char* memoryTagStrings[MEMORY_TAG_MAX_TAGS] = { "UNKNOWN ", "ARRAY ", "LINEAR_ALLC", "DARRAY ", "DICT ", "RING_QUEUE ", "BST ", "STRING ", "APPLICATION", "JOB ", "TEXTURE ", "MAT_INST ", "RENDERER ", "GAME ", "TRANSFORM ", "ENTITY ", "ENTITY_NODE", "SCENE " }; typedef struct memory_system_state { struct memory_stats stats; u64 allocCount; } memory_system_state; static memory_system_state* statePtr; void MemorySystemInitialize(u64* memoryRequirements, void* state) { *memoryRequirements = sizeof(memory_system_state); if (state == 0) return; statePtr = state; statePtr->allocCount = 0; PlatformZeroMemory(&statePtr->stats, sizeof(statePtr->stats)); } void MemorySystemShutdown(void* state) { statePtr = 0; } void* TAllocate(u64 size, memory_tag tag) { if (tag == MEMORY_TAG_UNKNOWN) { TWARN("TAllocate called using MEMORY_TAG_UNKNOWN. Re-class this allocation."); } if (statePtr) { statePtr->stats.totalAllocated += size; statePtr->stats.taggedAllocations[tag] += size; statePtr->allocCount++; } // TODO: Memory alignment void* block = PlatformAllocate(size, false); PlatformZeroMemory(block, size); return block; } void TFree(void* block, u64 size, memory_tag tag) { if (tag == MEMORY_TAG_UNKNOWN) { TWARN("TFree called using MEMORY_TAG_UNKNOWN. Re-class this allocation."); } if (statePtr) { statePtr->stats.totalAllocated -= size; statePtr->stats.taggedAllocations[tag] -= size; } // TODO: Memory alignment PlatformFree(block, false); } void* TZeroMemory(void* block, u64 size) { return PlatformZeroMemory(block, size); } void* TCopyMemory(void* dest, const void* source, u64 size) { return PlatformCopyMemory(dest, source, size); } void* TSetMemory(void* dest, s32 value, u64 size) { return PlatformSetMemory(dest, value, size); } char* GetMemoryUsageStr() { const u64 gib = 1024 * 1024 * 1024; const u64 mib = 1024 * 1024; const u64 kib = 1024; char buffer[8000] = "System memory use (tagged):\n"; u64 offset = strlen(buffer); for (u32 i = 0; i < MEMORY_TAG_MAX_TAGS; i++) { char unit[4] = "XiB"; float amount = 1.0f; if (statePtr->stats.taggedAllocations[i] >= gib) { unit[0] = 'G'; amount = statePtr->stats.taggedAllocations[i] / (float)gib; } else if (statePtr->stats.taggedAllocations[i] >= mib) { unit[0] = 'M'; amount = statePtr->stats.taggedAllocations[i] / (float)mib; } else if (statePtr->stats.taggedAllocations[i] >= kib) { unit[0] = 'K'; amount = statePtr->stats.taggedAllocations[i] / (float)kib; } else { unit[0] = 'B'; unit[1] = 0; amount = (float)statePtr->stats.taggedAllocations[i]; } s32 length = snprintf(buffer + offset, 8000, " %s: %.2f%s\n", memoryTagStrings[i], amount, unit); offset += length; } // TODO: This is a memory leak danger char* outString = StringDuplicate(buffer); return outString; } u64 GetMemoryAllocCount() { if (statePtr) { return statePtr->allocCount; } return 0; }
1.515625
2
3rdparty/aws-sdk-cpp-master/aws-cpp-sdk-datapipeline/include/aws/datapipeline/model/ReportTaskProgressRequest.h
prateek-s/mesos
2
940
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ #pragma once #include <aws/datapipeline/DataPipeline_EXPORTS.h> #include <aws/datapipeline/DataPipelineRequest.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/core/utils/memory/stl/AWSVector.h> #include <aws/datapipeline/model/Field.h> namespace Aws { namespace DataPipeline { namespace Model { /** * <p>Contains the parameters for ReportTaskProgress.</p> */ class AWS_DATAPIPELINE_API ReportTaskProgressRequest : public DataPipelineRequest { public: ReportTaskProgressRequest(); Aws::String SerializePayload() const override; Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override; /** * <p>The ID of the task assigned to the task runner. This value is provided in the * response for <a>PollForTask</a>.</p> */ inline const Aws::String& GetTaskId() const{ return m_taskId; } /** * <p>The ID of the task assigned to the task runner. This value is provided in the * response for <a>PollForTask</a>.</p> */ inline void SetTaskId(const Aws::String& value) { m_taskIdHasBeenSet = true; m_taskId = value; } /** * <p>The ID of the task assigned to the task runner. This value is provided in the * response for <a>PollForTask</a>.</p> */ inline void SetTaskId(Aws::String&& value) { m_taskIdHasBeenSet = true; m_taskId = value; } /** * <p>The ID of the task assigned to the task runner. This value is provided in the * response for <a>PollForTask</a>.</p> */ inline void SetTaskId(const char* value) { m_taskIdHasBeenSet = true; m_taskId.assign(value); } /** * <p>The ID of the task assigned to the task runner. This value is provided in the * response for <a>PollForTask</a>.</p> */ inline ReportTaskProgressRequest& WithTaskId(const Aws::String& value) { SetTaskId(value); return *this;} /** * <p>The ID of the task assigned to the task runner. This value is provided in the * response for <a>PollForTask</a>.</p> */ inline ReportTaskProgressRequest& WithTaskId(Aws::String&& value) { SetTaskId(value); return *this;} /** * <p>The ID of the task assigned to the task runner. This value is provided in the * response for <a>PollForTask</a>.</p> */ inline ReportTaskProgressRequest& WithTaskId(const char* value) { SetTaskId(value); return *this;} /** * <p>Key-value pairs that define the properties of the ReportTaskProgressInput * object.</p> */ inline const Aws::Vector<Field>& GetFields() const{ return m_fields; } /** * <p>Key-value pairs that define the properties of the ReportTaskProgressInput * object.</p> */ inline void SetFields(const Aws::Vector<Field>& value) { m_fieldsHasBeenSet = true; m_fields = value; } /** * <p>Key-value pairs that define the properties of the ReportTaskProgressInput * object.</p> */ inline void SetFields(Aws::Vector<Field>&& value) { m_fieldsHasBeenSet = true; m_fields = value; } /** * <p>Key-value pairs that define the properties of the ReportTaskProgressInput * object.</p> */ inline ReportTaskProgressRequest& WithFields(const Aws::Vector<Field>& value) { SetFields(value); return *this;} /** * <p>Key-value pairs that define the properties of the ReportTaskProgressInput * object.</p> */ inline ReportTaskProgressRequest& WithFields(Aws::Vector<Field>&& value) { SetFields(value); return *this;} /** * <p>Key-value pairs that define the properties of the ReportTaskProgressInput * object.</p> */ inline ReportTaskProgressRequest& AddFields(const Field& value) { m_fieldsHasBeenSet = true; m_fields.push_back(value); return *this; } /** * <p>Key-value pairs that define the properties of the ReportTaskProgressInput * object.</p> */ inline ReportTaskProgressRequest& AddFields(Field&& value) { m_fieldsHasBeenSet = true; m_fields.push_back(value); return *this; } private: Aws::String m_taskId; bool m_taskIdHasBeenSet; Aws::Vector<Field> m_fields; bool m_fieldsHasBeenSet; }; } // namespace Model } // namespace DataPipeline } // namespace Aws
0.996094
1
glibc-2.21/sysdeps/x86_64/fpu/multiarch/mpa-avx.c
LinuxUser404/smack-glibc
12
948
#define __add __add_avx #define __mul __mul_avx #define __sqr __sqr_avx #define __sub __sub_avx #define __dbl_mp __dbl_mp_avx #define __dvd __dvd_avx #define NO___CPY 1 #define NO___MP_DBL 1 #define NO___ACR 1 #define NO__CONST 1 #define SECTION __attribute__ ((section (".text.avx"))) #include <sysdeps/ieee754/dbl-64/mpa.c>
0.361328
0
src/torch/lib/include/ATen/CPUHalfType.h
warcraft12321/Hyperfoods
51
956
#pragma once // @generated by aten/src/ATen/gen.py #include "ATen/Type.h" #include "ATen/Context.h" #include "ATen/TensorMethods.h" #include "ATen/CheckGenerator.h" #ifdef _MSC_VER #ifdef Type #undef Type #endif #endif namespace at { struct CPUHalfType final : public Type { explicit CPUHalfType(Context* context); virtual ScalarType scalarType() const override; virtual Backend backend() const override; virtual bool is_cuda() const override; virtual bool is_sparse() const override; virtual bool is_distributed() const override; virtual std::unique_ptr<Storage> storage() const override; virtual std::unique_ptr<Storage> storage(size_t size) const override; virtual std::unique_ptr<Storage> storageFromBlob(void * data, int64_t size, const std::function<void(void*)> & deleter) const override; virtual std::unique_ptr<Storage> storageWithAllocator(int64_t size, Allocator* allocator) const override; virtual std::unique_ptr<Generator> generator() const override; virtual const char * toString() const override; virtual size_t elementSizeInBytes() const override; virtual TypeID ID() const override; static const char * typeString(); virtual std::unique_ptr<Storage> unsafeStorageFromTH(void * th_pointer, bool retain) const override; virtual Tensor unsafeTensorFromTH(void * th_pointer, bool retain) const override; // example // virtual Tensor * add(Tensor & a, Tensor & b) override; virtual Tensor & s_copy_(Tensor & self, const Tensor & src, bool non_blocking) const override; virtual Tensor & _s_copy_from(const Tensor & self, Tensor & dst, bool non_blocking) const override; virtual int64_t storage_offset(const Tensor & self) const override; virtual Tensor & resize_(Tensor & self, IntList size) const override; virtual Tensor & set_(Tensor & self, Storage & source) const override; virtual Tensor & set_(Tensor & self, Storage & source, int64_t storage_offset, IntList size, IntList stride) const override; virtual Tensor & set_(Tensor & self, const Tensor & source) const override; virtual Tensor & set_(Tensor & self) const override; virtual bool is_contiguous(const Tensor & self) const override; virtual bool is_set_to(const Tensor & self, const Tensor & tensor) const override; virtual Tensor th_clone(const Tensor & self) const override; virtual Tensor unfold(const Tensor & self, int64_t dimension, int64_t size, int64_t step) const override; virtual void* data_ptr(const Tensor & self) const override; virtual Tensor th_tensor(IntList size) const override; virtual Tensor th_tensor() const override; virtual Tensor tensor(Storage & storage, int64_t storageOffset, IntList size, IntList stride) const override; virtual Tensor tensor(IntList size, IntList stride) const override; virtual Tensor alias(const Tensor & self) const override; virtual Tensor & as_strided_out(Tensor & result, const Tensor & self, IntList size, IntList stride, int64_t storage_offset) const override; virtual Tensor as_strided(const Tensor & self, IntList size, IntList stride, int64_t storage_offset) const override; virtual Tensor & as_strided_(Tensor & self, IntList size, IntList stride, int64_t storage_offset) const override; }; } // namespace at
1.132813
1
src/ml/inc/relaxation_knn_classifier.h
Cognixion-inc/brainflow
528
964
#pragma once #include "brainflow_constants.h" #include "concentration_knn_classifier.h" class RelaxationKNNClassifier : public ConcentrationKNNClassifier { public: RelaxationKNNClassifier (struct BrainFlowModelParams params) : ConcentrationKNNClassifier (params) { } int predict (double *data, int data_len, double *output) { int res = ConcentrationKNNClassifier::predict (data, data_len, output); if (res != (int)BrainFlowExitCodes::STATUS_OK) { return res; } *output = 1.0 - (*output); return res; } };
0.890625
1
lib/pcap_reader/ip_defragmenter.h
leozz37/makani
1,178
972
/* * Copyright 2020 Makani Technologies LLC * * 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. */ #ifndef LIB_PCAP_READER_IP_DEFRAGMENTER_H_ #define LIB_PCAP_READER_IP_DEFRAGMENTER_H_ #include <netinet/ip.h> // For iphdr. #include <stdint.h> #include <sys/time.h> #include <deque> #include <list> #include <utility> #include "common/macros.h" class FragmentedPacket { public: FragmentedPacket(const timeval &ts, const iphdr &header); ~FragmentedPacket() {} // Copies the payload from the current fragmented packet into the // appropriate position in the reassembled packet. void Fill(const iphdr &header, const uint8_t *fragment_payload); // Returns true when all the fragments of the original packet have // been received. bool IsComplete() const { return holes_.empty(); } // Returns packet age in microseconds. int64_t GetAge(const timeval &now) const; const iphdr &ip_header() const { return ip_header_; } int32_t payload_size() const { return payload_size_; } const uint8_t *payload() const { return payload_; } private: // The maximum size of the payload of an IP packet is determined by // the maximum value of the iphdr.tot_len field and the size of the // IP header itself. static const int32_t kMaxPayloadSize = 65535 - sizeof(iphdr); // The packet timestamp is used to expire old fragments. timeval timestamp_; // The IP header includes an id field, which is used to identify // which fragments belong to the same packet. iphdr ip_header_; // The hole structure describes a section of the payload with an // inclusive start and exclusive end byte indices: [start, end). // The list of holes keeps track of which parts of the fragmented // packet have not been filled in. The list of holes is initialized // to a single hole that covers the largest possible packet. Holes // may be split, truncated, or removed as fragments arrive. The // list of holes is guaranteed to be non-overlapping and in // increasing order of start index. struct Hole { int32_t start, end; }; std::list<Hole> holes_; // payload_size_ is the total number of bytes of the payloads of all // the packet fragments. The total size of the payload is not known // until the last fragment packet arrives. int32_t payload_size_; uint8_t payload_[kMaxPayloadSize]; }; // Holds the state of the incomplete packets during the IP // defragmentation process. Returns full payloads when they are // complete. Discards incomplete packets once the fragmented packet // container reaches a maximum size. class IpDefragmenter { public: IpDefragmenter() : packets_(), completed_packet_(packets_.end(), false) {} ~IpDefragmenter() {} // Defragments IP packets. Once the packet has been completely // defragmented, returns the total length of the payload, and a // pointer to the payload. You can continue to use the payload // pointer until the next call to Defragment. If the packet is not // defragmented, returns -1. int32_t Defragment(const timeval &ts, const iphdr &header, const uint8_t *fragment_payload, const uint8_t **full_payload); // Returns the number of partially completed packets, which may // include the last completed packet, currently stored in the // container. int32_t Length() const { return static_cast<int32_t>(packets_.size()); } // Clear stored fragmented packets from buffer. void ClearPackets(void); private: typedef std::deque<FragmentedPacket>::iterator iterator; // The maximum number of incomplete packets allowed in the deque. // Once we reach this limit, we remove a quarter of the incomplete // packets starting at the front of the deque. static const int32_t kMaxFragmentedPackets = 100; // The maximum number of microseconds to keep a fragmented packet. static const int64_t kMaxFragmentTimeUsec = 30000000LL; // Returns an iterator to the partially filled out FragmentedPacket // that has the same ID as the packet with the given header. iterator FindPacket(const timeval &ts, const iphdr &header); // Adds a new fragmented packet to the back of the deque. void AddPacket(const timeval &ts, const iphdr &header, const uint8_t *fragment_payload); // Returns true if the container has reached the maximum allowed size. bool IsFull() const { return packets_.size() >= kMaxFragmentedPackets; } // Partially completed packets are stored in a deque. std::deque<FragmentedPacket> packets_; // Iterator to the completed packet from the last call to Defragment // and a Boolean that is true when the iterator is valid. std::pair<iterator, bool> completed_packet_; DISALLOW_COPY_AND_ASSIGN(IpDefragmenter); }; #endif // LIB_PCAP_READER_IP_DEFRAGMENTER_H_
1.367188
1
NetFarmCommune/Classes/Farm/Farm/View/ShopSelectView.h
JKrystalMH/NYN
1
980
// // ShopSelectView.h // NetFarmCommune // // Created by manager on 2017/12/19. // Copyright © 2017年 NongYiNong. All rights reserved. // #import <UIKit/UIKit.h> @protocol ShopSelectViewDelagate<NSObject> -(void)selectCellClick:(NSString * )str selectID:(NSString*)selectID selectIndex:(NSString*)selectIndex; @end @interface ShopSelectView : UIView -(void)getData:(NSArray*)array; @property(nonatomic,weak)id<ShopSelectViewDelagate>delagate; @end
0.71875
1
Interaction/Widgets/vtkSplineRepresentation.h
jasper-yeh/VtkDotNet
1
988
/*========================================================================= Program: Visualization Toolkit Module: vtkSplineRepresentation.h Copyright (c) <NAME>, <NAME>, <NAME> All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ // .NAME vtkSplineRepresentation - representation for a spline. // .SECTION Description // vtkSplineRepresentation is a vtkWidgetRepresentation for a spline. // This 3D widget defines a spline that can be interactively placed in a // scene. The spline has handles, the number of which can be changed, plus it // can be picked on the spline itself to translate or rotate it in the scene. // This is based on vtkSplineWidget. // .SECTION See Also // vtkSplineWidget, vtkSplineWidget2 #ifndef vtkSplineRepresentation_h #define vtkSplineRepresentation_h #include "vtkInteractionWidgetsModule.h" // For export macro #include "vtkCurveRepresentation.h" class vtkActor; class vtkCellPicker; class vtkDoubleArray; class vtkParametricFunctionSource; class vtkParametricSpline; class vtkPlaneSource; class vtkPoints; class vtkPolyData; class vtkProp; class vtkProperty; class vtkSphereSource; class vtkTransform; class VTKINTERACTIONWIDGETS_EXPORT vtkSplineRepresentation : public vtkCurveRepresentation { public: static vtkSplineRepresentation* New(); vtkTypeMacro(vtkSplineRepresentation, vtkCurveRepresentation); void PrintSelf(ostream& os, vtkIndent indent); // Description: // Grab the polydata (including points) that defines the spline. The // polydata consists of points and line segments numbering Resolution + 1 // and Resolution, respectively. Points are guaranteed to be up-to-date when // either the InteractionEvent or EndInteraction events are invoked. The // user provides the vtkPolyData and the points and polyline are added to it. void GetPolyData(vtkPolyData *pd); // Description: // Set the number of handles for this widget. virtual void SetNumberOfHandles(int npts); // Description: // Set/Get the number of line segments representing the spline for // this widget. void SetResolution(int resolution); vtkGetMacro(Resolution,int); // Description: // Set the parametric spline object. Through vtkParametricSpline's API, the // user can supply and configure one of two types of spline: // vtkCardinalSpline, vtkKochanekSpline. The widget controls the open // or closed configuration of the spline. // WARNING: The widget does not enforce internal consistency so that all // three are of the same type. virtual void SetParametricSpline(vtkParametricSpline*); vtkGetObjectMacro(ParametricSpline,vtkParametricSpline); // Description: // Get the position of the spline handles. vtkDoubleArray* GetHandlePositions(); // Description: // Get the approximate vs. the true arc length of the spline. Calculated as // the summed lengths of the individual straight line segments. Use // SetResolution to control the accuracy. double GetSummedLength(); // Description: // Convenience method to allocate and set the handles from a vtkPoints // instance. If the first and last points are the same, the spline sets // Closed to the on InteractionState and disregards the last point, otherwise Closed // remains unchanged. void InitializeHandles(vtkPoints* points); // Description: // These are methods that satisfy vtkWidgetRepresentation's API. Note that a // version of place widget is available where the center and handle position // are specified. virtual void BuildRepresentation(); //BTX protected: vtkSplineRepresentation(); ~vtkSplineRepresentation(); // The spline vtkParametricSpline *ParametricSpline; vtkParametricFunctionSource *ParametricFunctionSource; // The number of line segments used to represent the spline. int Resolution; // Specialized method to insert a handle on the poly line. virtual void InsertHandleOnLine(double* pos); private: vtkSplineRepresentation(const vtkSplineRepresentation&); // Not implemented. void operator=(const vtkSplineRepresentation&); // Not implemented. //ETX }; #endif
1.492188
1
src/Gulden/Common/diff_common.h
Gulden-Coin/gulden-official
0
996
// Copyright (c) 2015-2018 The Gulden developers // Authored by: <NAME> (<EMAIL>) // Distributed under the GULDEN software license, see the accompanying // file COPYING #ifndef GULDEN_DIFF_COMMON_H #define GULDEN_DIFF_COMMON_H #ifdef __JAVA__ #define fDebug false #define LogPrintf(...) #define BLOCK_TYPE Block #define BLOCK_TIME(block) block.getTimeSeconds() #define INDEX_TYPE StoredBlock #define INDEX_HEIGHT(block) block.getHeight() //fixme: (2.0.1) (Mobile) #define INDEX_TIME(block) block.getHeader().getTimeSeconds() #define INDEX_PREV(block) blockStore.get(block.getHeader().getPrevBlockHash()) #define INDEX_TARGET(block) block.getHeader().getDifficultyTarget() #define DIFF_SWITCHOVER(T, M) (Constants.TEST ? T : M) #define DIFF_ABS Math.abs #define arith_uint256(x) BigInteger.valueOf(x) #define SET_COMPACT(EXPANDED, COMPACT) EXPANDED = Utils.decodeCompactBits(COMPACT) #define GET_COMPACT(EXPANDED) Utils.encodeCompactBits(EXPANDED) #define BIGINT_MULTIPLY(x, y) x.multiply(y) #define BIGINT_DIVIDE(x, y) x.divide(y) #define BIGINT_GREATER_THAN(x, y) (x.compareTo(y) == 1) #elif defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE!=0 // it's defined, but as 0 on macOS @class BRMerkleBlock; #define BUILD_IOS #define fDebug false #define LogPrintf(...) #define BLOCK_TYPE BRMerkleBlock* #define BLOCK_TIME(block) (int64_t)block.timestamp #define INDEX_TYPE BRMerkleBlock* #define INDEX_HEIGHT(block) block.height //fixme: (2.0.1) (Mobile) #define INDEX_TIME(block) (int64_t)block.timestamp #define INDEX_PREV(block) [[BRPeerManager sharedInstance] blockForHash:(block.prevBlock)] #define INDEX_TARGET(block) block.target #ifdef GULDEN_TESTNET #define DIFF_SWITCHOVER(T, M) T #else #define DIFF_SWITCHOVER(T, M) M #endif #define DIFF_ABS llabs #define SET_COMPACT(EXPANDED, COMPACT) EXPANDED.SetCompact(COMPACT) #define GET_COMPACT(EXPANDED) EXPANDED.GetCompact() #define BIGINT_MULTIPLY(x, y) x * y #define BIGINT_DIVIDE(x, y) x / y #define BIGINT_GREATER_THAN(x, y) (x > y) #else #include <consensus/params.h> #include <arith_uint256.h> #include <chain.h> #include <sync.h> #include <util.h> #include <stdint.h> #define BLOCK_TYPE CBlockHeader* #define BLOCK_TIME(block) block->nTime #define INDEX_TYPE CBlockIndex* #define INDEX_HEIGHT(block) block->nHeight #define INDEX_TIME(block) block->GetBlockTime() #define INDEX_PREV(block) block->pprev #define INDEX_TARGET(block) block->nBits #define DIFF_SWITCHOVER(TEST, MAIN) (IsArgSet("-testnet") ? TEST : MAIN) #define DIFF_ABS std::abs #define SET_COMPACT(EXPANDED, COMPACT) EXPANDED.SetCompact(COMPACT) #define GET_COMPACT(EXPANDED) EXPANDED.GetCompact() #define BIGINT_MULTIPLY(x, y) x * y #define BIGINT_DIVIDE(x, y) x / y #define BIGINT_GREATER_THAN(x, y) (x > y) #endif #ifndef __JAVA__ #if defined __cplusplus extern "C" { #endif extern unsigned int GetNextWorkRequired(const INDEX_TYPE indexLast, const BLOCK_TYPE block, unsigned int nPowTargetSpacing, unsigned int nPowLimit); #if defined __cplusplus }; #endif #endif #endif
1.148438
1
doc/examples/ex60.cured.c
CTSRD-CHERI/ccured
5
1004
/* Generated by CIL v. 1.3.5 */ /* print_CIL_Input is false */ #define CCURED_SPLIT_ARGUMENTS // #define CCURED_ALLOW_PARTIAL_ELEMENTS_IN_SEQUENCE // #define CCURED_LOG_NON_POINTERS #define CCURED_USE_STRINGS // #define CCURED_FAIL_IS_TERSE // #define CCURED_ALWAYS_STOP_ON_ERROR // Include the definition of the checkers #define CCURED #define CCURED_POST #include "ccuredcheck.h" struct printf_arguments { int i ; double d ; char * __ROSTRING s ; long long ll ; }; struct msghdr; struct iovec; struct meta_fseqp_s_iovec { void *_e ; } ; struct fseqp_s_iovec { struct iovec * __FSEQ _p ; struct meta_fseqp_s_iovec _ms ; } ; typedef struct fseqp_s_iovec fseqp_s_iovec; struct msghdr { void *msg_name ; int msg_namelen ; fseqp_s_iovec msg_iov ; int msg_iovlen ; void *msg_control ; int msg_controllen ; int msg_flags ; }; struct iovec { char *iov_base ; int iov_len ; }; extern void __ccuredInit(void) ; extern __attribute__((__noreturn__)) void abort_deepcopy(char *errmsg ) ; struct msghdr_COMPAT; struct iovec_COMPAT; struct msghdr_COMPAT { void *msg_name ; int msg_namelen ; struct iovec_COMPAT *msg_iov ; int msg_iovlen ; void *msg_control ; int msg_controllen ; int msg_flags ; }; extern int sendmsg(int fd , struct msghdr_COMPAT *msg , int flags ) ; __inline static int /*1*/sendmsg_wrapper4(int fd , struct msghdr *msg , int flags ) ; int foo_f(int fd , struct iovec * __FSEQ array , void *array_e , int array_len ) ; int foo_f(int fd , struct iovec * __FSEQ array , void *array_e , int array_len ) { struct msghdr msg ; struct iovec *foo___0 ; int tmp ; int __retres ; struct iovec * __FSEQ __cil_tmp8 ; int __cil_tmp9 ; void *__cil_tmp8_e13 ; { foo___0 = (struct iovec *)0; msg.msg_control = (void *)0; msg.msg_iov._ms._e = (void *)0; msg.msg_iov._p = (struct iovec */* __FSEQ */)0; msg.msg_name = (void *)0; msg.msg_name = (void *)0; msg.msg_namelen = 0; __cil_tmp8 = array; __cil_tmp8_e13 = array_e; msg.msg_iov._ms._e = __cil_tmp8_e13; msg.msg_iov._p = __cil_tmp8; msg.msg_iovlen = array_len; msg.msg_control = (void *)0; msg.msg_controllen = 0; msg.msg_flags = 0; CHECK_FSEQARITH((void *)msg.msg_iov._p, sizeof(struct iovec ), (void *)(msg.msg_iov._p + 1), msg.msg_iov._ms._e, 0); CHECK_FSEQ2SAFE(msg.msg_iov._ms._e, (void *)(msg.msg_iov._p + 1), sizeof(struct iovec ), sizeof(struct iovec ), 0, 0); foo___0 = (struct iovec *)(msg.msg_iov._p + 1); __cil_tmp9 = /*1*/sendmsg_wrapper4(fd, (struct msghdr *)(& msg), 0); tmp = __cil_tmp9; __retres = tmp; return (__retres); } } extern void *malloc(int ) ; extern void free(void * ) ; struct iovec_COMPAT { char *iov_base ; int iov_len ; }; __inline static void __deepcopy_msghdr_to_compat(struct msghdr_COMPAT *compat , struct msghdr *fat ) ; __inline static void __deepcopy_iovec_to_compat(struct iovec_COMPAT *compat , struct iovec *fat ) ; __inline static void __deepcopy_iovec_to_compat(struct iovec_COMPAT *compat , struct iovec *fat ) { void *__cil_tmp3 ; { CHECK_NULL((void *)compat); CHECK_NULL((void *)fat); compat->iov_len = fat->iov_len; __cil_tmp3 = (void *)((void *)fat->iov_base); compat->iov_base = (char *)__cil_tmp3; return; } } static char __string1[45] = { 'A', 'b', 'o', 'r', 't', ' ', 'd', 'e', 'e', 'p', 'c', 'o', 'p', 'y', '_', 't', 'o', '_', 'c', 'o', 'm', 'p', 'a', 't', ' ', 'f', 'o', 'r', ' ', 'm', 's', 'g', 'h', 'd', 'r', '.', 'm', 's', 'g', '_', 'n', 'a', 'm', 'e', '\000'}; static char __string2[48] = { 'A', 'b', 'o', 'r', 't', ' ', 'd', 'e', 'e', 'p', 'c', 'o', 'p', 'y', '_', 't', 'o', '_', 'c', 'o', 'm', 'p', 'a', 't', ' ', 'f', 'o', 'r', ' ', 'm', 's', 'g', 'h', 'd', 'r', '.', 'm', 's', 'g', '_', 'c', 'o', 'n', 't', 'r', 'o', 'l', '\000'}; __inline static void __deepcopy_msghdr_to_compat(struct msghdr_COMPAT *compat , struct msghdr *fat ) ; __inline static void __deepcopy_msghdr_to_compat(struct msghdr_COMPAT *compat , struct msghdr *fat ) { int len ; int v ; struct iovec_COMPAT *iptr ; struct iovec_COMPAT *tmp ; int tmp___0 ; void *__cil_tmp8 ; int dest_mangling9 ; void *__cil_tmp10 ; int dest_mangling11 ; void *__cil_tmp12 ; void *__cil_tmp13 ; void *__cil_tmp14 ; void *__cil_tmp15 ; void *__cil_tmp16 ; void *__cil_tmp17 ; void *__cil_tmp18 ; { __cil_tmp10 = (void *)0; __cil_tmp8 = (void *)0; tmp = (struct iovec_COMPAT *)0; iptr = (struct iovec_COMPAT *)0; CHECK_NULL((void *)fat); __cil_tmp12 = (void *)fat->msg_name; __cil_tmp10 = (void *)__cil_tmp12; if ((int )(! __cil_tmp10)) { { CHECK_NULL((void *)compat); compat->msg_name = (void *)0; } } else { { dest_mangling11 = 1; if (dest_mangling11) { { __cil_tmp13 = (void *)__cil_tmp10; CHECK_NULL((void *)compat); compat->msg_name = (void *)__cil_tmp13; } } else { { abort_deepcopy((char *)(& __string1[0])); } } } } CHECK_NULL((void *)compat); CHECK_NULL((void *)fat); compat->msg_namelen = fat->msg_namelen; compat->msg_iovlen = fat->msg_iovlen; __cil_tmp14 = (void *)fat->msg_control; __cil_tmp8 = (void *)__cil_tmp14; if ((int )(! __cil_tmp8)) { { CHECK_NULL((void *)compat); compat->msg_control = (void *)0; } } else { { dest_mangling9 = 1; if (dest_mangling9) { { __cil_tmp15 = (void *)__cil_tmp8; CHECK_NULL((void *)compat); compat->msg_control = (void *)__cil_tmp15; } } else { { abort_deepcopy((char *)(& __string2[0])); } } } } CHECK_NULL((void *)compat); CHECK_NULL((void *)fat); compat->msg_controllen = fat->msg_controllen; compat->msg_flags = fat->msg_flags; tmp___0 = 1; if (tmp___0) { CHECK_NULL((void *)fat); if ((void */* __FSEQ */)fat->msg_iov._p) { CHECK_FSEQ2SAFE(fat->msg_iov._ms._e, (void *)((void */* __FSEQ */)fat->msg_iov._p), sizeof(void ), sizeof(void ), 1, 0); } __cil_tmp18 = (void */* __FSEQ */)fat->msg_iov._p; CHECK_NULL((void *)compat); compat->msg_iov = (struct iovec_COMPAT *)__cil_tmp18; } else { CHECK_NULL((void *)fat); len = fat->msg_iovlen; __cil_tmp16 = malloc((int )((unsigned int )len * sizeof(*(compat->msg_iov)))); CHECK_NULL((void *)compat); compat->msg_iov = (struct iovec_COMPAT *)__cil_tmp16; v = 0; while (v < len) { CHECK_NULL((void *)compat); __cil_tmp17 = (void *)((void *)((unsigned long )compat->msg_iov + (unsigned long )((unsigned int )v * sizeof(*(compat->msg_iov))))); tmp = (struct iovec_COMPAT *)__cil_tmp17; iptr = (struct iovec_COMPAT *)tmp; CHECK_NULL((void *)fat); CHECK_FSEQARITH((void *)fat->msg_iov._p, sizeof(struct iovec ), (void *)(fat->msg_iov._p + v), fat->msg_iov._ms._e, 0); CHECK_FSEQ2SAFE(fat->msg_iov._ms._e, (void *)(fat->msg_iov._p + v), sizeof(struct iovec ), sizeof(struct iovec ), 0, 0); __deepcopy_iovec_to_compat((struct iovec_COMPAT *)iptr, (struct iovec *)(fat->msg_iov._p + v)); v ++; } } return; } } __inline static int /*1*/sendmsg_wrapper4(int fd , struct msghdr *msg , int flags ) ; __inline static int /*1*/sendmsg_wrapper4(int fd , struct msghdr *msg , int flags ) { struct msghdr_COMPAT msg1__area ; struct msghdr *msg1__ptrof ; struct msghdr *tmp ; struct msghdr_COMPAT *msg1 ; struct msghdr_COMPAT *tmp___2 ; int tmp___4 ; int result ; int tmp___5 ; int __retres ; void *__cil_tmp16 ; void *__cil_tmp17 ; void *__cil_tmp18 ; int __cil_tmp19 ; { tmp___2 = (struct msghdr_COMPAT *)0; msg1 = (struct msghdr_COMPAT *)0; tmp = (struct msghdr *)0; msg1__ptrof = (struct msghdr *)0; msg1__area.msg_control = (void *)0; msg1__area.msg_iov = (struct iovec_COMPAT *)0; msg1__area.msg_name = (void *)0; __cil_tmp16 = (void *)((void *)msg); tmp = (struct msghdr *)__cil_tmp16; msg1__ptrof = (struct msghdr *)tmp; if ((int )msg1__ptrof) { tmp___4 = 0; if (tmp___4) { __cil_tmp18 = (void *)((void *)msg1__ptrof); tmp___2 = (struct msghdr_COMPAT *)__cil_tmp18; } else { __deepcopy_msghdr_to_compat((struct msghdr_COMPAT *)(& msg1__area), (struct msghdr *)msg1__ptrof); tmp___2 = (struct msghdr_COMPAT *)(& msg1__area); } } else { __cil_tmp17 = (void *)((void *)msg1__ptrof); tmp___2 = (struct msghdr_COMPAT *)__cil_tmp17; } msg1 = (struct msghdr_COMPAT *)tmp___2; __cil_tmp19 = sendmsg(fd, (struct msghdr_COMPAT *)msg1, flags); tmp___5 = __cil_tmp19; result = tmp___5; CHECK_NULL((void *)msg1); CHECK_NULL((void *)msg); if ((unsigned int )msg1->msg_iov != (unsigned int )msg->msg_iov._p) { free((void *)((void *)msg1->msg_iov)); } __retres = result; return (__retres); } }
1.039063
1
kernel/aos/sys/timer.c
OrdinaryMagician/aliceos-kernel
19
1012
/* timer.c : programmable timer interface. (C)2012-2013 <NAME>, UnSX Team. Part of AliceOS, the Alice Operating System. Released under the MIT License. */ #include <sys/types.h> #include <sys/regs.h> #include <sys/timer.h> #include <sys/irq_handlers.h> #include <sys/helpers.h> #include <printk.h> #include <memops.h> #include <sys/port.h> /* internal counter */ static uint32_t ticker = 0; /* length of each tick in nanoseconds */ static uint32_t tscale = 0; /* system time frequency */ static uint32_t thz = 0; /* timer list */ static timer_t timer[TIMERS_SZ]; static uint8_t timers = 0; /* get current ticks passed */ uint32_t get_ticks( void ) { return ticker; } /* get current nanoseconds/tick */ uint32_t get_timescale( void ) { return tscale; } /* get current timer frequency */ uint32_t get_hz( void ) { return thz; } /* return the equivalent in ticks for some time units */ uint32_t timer_sec( uint32_t s ) { return (s*1000000000)/tscale; } uint32_t timer_msec( uint32_t m ) { return (m*1000000)/tscale; } uint32_t timer_usec( uint32_t u ) { return (u*1000)/tscale; } /* calls a timer task if specific conditions are met */ static void timer_call( timer_t t, regs_t *regs ) { if ( !(uint32_t)t.fn ) /* no function set */ return; if ( t.oneshot ) /* one-shot tasks are handled differently */ { if ( !t.interval ) { t.fn(regs); timer_rm(t.fn); return; } t.interval--; return; } if ( !t.interval ) /* zero interval */ return; if ( ticker%t.interval ) /* not the right time */ return; /* if all is ok, call the task */ t.fn(regs); } /* function to increment ticker and call all registered tasks */ static void timer_callback( regs_t *regs ) { ticker++; uint8_t i; for ( i=0; i<timers; i++ ) timer_call(timer[i],regs); irq_eoi(PIT_IRQ); int_enable(); } /* initialize the base timer */ void init_timer( uint32_t hz ) { printk("Setting base timer to %u hz\n",hz); timers = 0; memset(&timer[0],0,sizeof(timer_t)*TIMERS_SZ); printk(" Registering base IRQ%u handler\n",PIT_IRQ); register_irq_handler(PIT_IRQ,&timer_callback); uint32_t divisor = 1193180/hz; printk(" PIT frequency divisor: %u\n",divisor); thz = (divisor*hz*hz)/1193180; int32_t error = hz-thz; tscale = 1000000000/thz; outport_b(0x43,0x36); /* repeating mode */ uint8_t l = (uint8_t)(divisor&0xFF); uint8_t h = (uint8_t)((divisor>>8)&0xFF); outport_b(0x40,l); outport_b(0x40,h); printk(" Base timer set with ~%u hz error\n",abs(error)); } /* register a timer, return 1 on error, 0 otherwise */ uint8_t timer_add( timerfn_t fn, uint32_t interval, uint8_t oneshot ) { if ( timers == TIMERS_SZ ) /* list full */ return 1; timer[timers].fn = fn; timer[timers].interval = interval; timer[timers].oneshot = oneshot; timers++; return 0; } /* rearrange the timer array, removing a specific timer in the process */ static void timer_rmid( uint8_t id ) { memmove(&timer[id],&timer[id+1], sizeof(timer_t)*(timers-id)); timers--; } /* unregister a timer, return 1 on error, 0 otherwise */ uint8_t timer_rm( timerfn_t fn ) { uint8_t i; for ( i=0; i<timers; i++ ) { if ( timer[i].fn != fn ) continue; timer_rmid(i); return 0; } return 1; }
1.554688
2
VZInspector/core/item/VZInspectorBizLogItem.h
xta0/VZInspector
58
1020
// // Copyright © 2016年 Vizlab. All rights reserved. // #import <Foundation/Foundation.h> @interface VZInspectorBizLogItem : NSObject<NSCoding ,NSCopying> @property (nonatomic, assign) float itemHeight; @property (nonatomic, assign) Class cellClass; @property (nonatomic, strong) NSIndexPath *indexPath; @end
0.578125
1
Data Structures and Algorithms/Arrays/Array ADT/Union.c
subhamb123/C-and-CPP-Projects
1
1028
#include<stdio.h> #include<stdlib.h> #include<stdbool.h> int main(){ int A[10] = {1, 2, 3, 4, 5, 6, 7, 8}; int B[10] = {3, 5, 2, 434, 1}; int C[20]; int lengthA = 8; int lengthB = 5; int lengthC = 13; for(int i = 0; i < lengthA; i++){ C[i] = A[i]; } int k = lengthA; for(int i = 0; i < lengthB; i++){ int x = 0; for(int j = 0; j < lengthA; j++){ if(A[j] == B[i]){ break; } x++; } if(x == lengthA){ C[k] = B[i]; k++; } } for(int i = 0; i < lengthC; i++){ printf("%d ", A[i]); } return 0; }
2
2
src/libre/class/utf8_Egyptian_Hieroglyphs.c
data-man/libfsm
766
1036
/* generated */ #include "class.h" static const struct range ranges[] = { { 0x13000UL, 0x1342EUL }, { 0x13430UL, 0x13438UL } }; const struct class utf8_Egyptian_Hieroglyphs = { ranges, sizeof ranges / sizeof *ranges };
0.976563
1
linux-x86/host/x86_64-linux-glibc2.11-4.8/sysroot/usr/include/linux/mman.h
HelixOS/prebuilts-gcc
1,178
1044
#ifndef _LINUX_MMAN_H #define _LINUX_MMAN_H #include <asm/mman.h> #define MREMAP_MAYMOVE 1 #define MREMAP_FIXED 2 #define OVERCOMMIT_GUESS 0 #define OVERCOMMIT_ALWAYS 1 #define OVERCOMMIT_NEVER 2 #endif /* _LINUX_MMAN_H */
0.412109
0
Libs/DICOM/Core/ctkDICOMObjectModel.h
espakm/CTK
0
1052
/*============================================================================= Library: CTK Copyright (c) Brigham and Women's Hospital (BWH) Copyright (c) University of Sheffield 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. =============================================================================*/ #ifndef __ctkDICOMObjectModel_h #define __ctkDICOMObjectModel_h // STD includes #include <string> // Qt includes #include <QMetaType> #include <QStandardItemModel> #include <QString> #include "ctkDICOMCoreExport.h" class ctkDICOMObjectModelPrivate; /// \ingroup DICOM_Core /// /// \brief Provides a Qt MVC-compatible wrapper around a ctkDICOMItem. /// class CTK_DICOM_CORE_EXPORT ctkDICOMObjectModel : public QStandardItemModel { Q_OBJECT typedef QStandardItemModel Superclass; //Q_PROPERTY(setFile); public: explicit ctkDICOMObjectModel(QObject* parent = 0); ctkDICOMObjectModel(const ctkDICOMObjectModel& other); virtual ~ctkDICOMObjectModel(); Q_INVOKABLE void setFile (const QString& fileName); protected: QScopedPointer<ctkDICOMObjectModelPrivate> d_ptr; private: Q_DECLARE_PRIVATE(ctkDICOMObjectModel); }; #endif // ctkDICOMObjectModel_h
0.917969
1
challenges/root64_and_parcour/pov_2/pov.c
pingjuiliao/cb-multios
473
1060
#include "libpov.h" int main(int cgc_argc, char *cgc_argv[]) { cgc_negotiate_type1(0x0, 0x0, 0); do { //*** writing data static unsigned char write_00000_00000[] = "\x48\x45\x4c\x4c\x4f\x0a"; static unsigned int write_00000_00000_len = 6; unsigned char *write_00000 = NULL; unsigned int write_00000_len = 0; write_00000 = cgc_append_buf(write_00000, &write_00000_len, write_00000_00000, write_00000_00000_len); if (write_00000_len > 0) { cgc_transmit_all(1, write_00000, write_00000_len); } cgc_free(write_00000); } while (0); do { unsigned char *read_00000; unsigned int read_00000_len; unsigned int read_00000_ptr = 0; //**** delimited read static unsigned char read_00000_delim[] = "\x0a"; read_00000 = NULL; read_00000_len = 0; int read_00000_res = cgc_delimited_read(0, &read_00000, &read_00000_len, read_00000_delim, 1); if (read_00000_res) {} //silence unused variable warning //**** read assign to var "token" from pcre: OK ([0-9A-F]*)\n static char read_00000_regex[] = "\x4f\x4b\x20\x28\x5b\x30\x2d\x39\x41\x2d\x46\x5d\x2a\x29\x5c\x6e"; cgc_assign_from_pcre("token", read_00000, read_00000_len - read_00000_ptr, read_00000_regex, 1); cgc_free(read_00000); if (read_00000_ptr) {} //silence unused variable warning if any } while (0); do { //*** writing data static unsigned char write_00001_00000[] = "\x41\x55\x54\x48\x20"; static unsigned int write_00001_00000_len = 5; static unsigned char write_00001_00002[] = "\x0a"; static unsigned int write_00001_00002_len = 1; unsigned char *write_00001 = NULL; unsigned int write_00001_len = 0; write_00001 = cgc_append_buf(write_00001, &write_00001_len, write_00001_00000, write_00001_00000_len); write_00001 = cgc_append_var("token", write_00001, &write_00001_len); write_00001 = cgc_append_buf(write_00001, &write_00001_len, write_00001_00002, write_00001_00002_len); if (write_00001_len > 0) { cgc_transmit_all(1, write_00001, write_00001_len); } cgc_free(write_00001); } while (0); do { unsigned char *read_00001; unsigned int read_00001_len; unsigned int read_00001_ptr = 0; //**** delimited read static unsigned char read_00001_delim[] = "\x0a"; read_00001 = NULL; read_00001_len = 0; int read_00001_res = cgc_delimited_read(0, &read_00001, &read_00001_len, read_00001_delim, 1); if (read_00001_res) {} //silence unused variable warning //**** read match data static unsigned char match_00001_00000[] = "\x4f\x4b\x0a"; read_00001_ptr += cgc_data_match(read_00001 + read_00001_ptr, read_00001_len - read_00001_ptr, match_00001_00000, 3); cgc_free(read_00001); if (read_00001_ptr) {} //silence unused variable warning if any } while (0); do { //*** writing data static unsigned char write_00002_00000[] = "\x53\x45\x54\x20\x6d\x6f\x64\x65\x20\x65\x6e\x63\x6f\x64\x65\x0a"; static unsigned int write_00002_00000_len = 16; unsigned char *write_00002 = NULL; unsigned int write_00002_len = 0; write_00002 = cgc_append_buf(write_00002, &write_00002_len, write_00002_00000, write_00002_00000_len); if (write_00002_len > 0) { cgc_transmit_all(1, write_00002, write_00002_len); } cgc_free(write_00002); } while (0); do { unsigned char *read_00002; unsigned int read_00002_len; unsigned int read_00002_ptr = 0; //**** delimited read static unsigned char read_00002_delim[] = "\x0a"; read_00002 = NULL; read_00002_len = 0; int read_00002_res = cgc_delimited_read(0, &read_00002, &read_00002_len, read_00002_delim, 1); if (read_00002_res) {} //silence unused variable warning //**** read match data static unsigned char match_00002_00000[] = "\x4f\x4b\x0a"; read_00002_ptr += cgc_data_match(read_00002 + read_00002_ptr, read_00002_len - read_00002_ptr, match_00002_00000, 3); cgc_free(read_00002); if (read_00002_ptr) {} //silence unused variable warning if any } while (0); do { //*** writing data static unsigned char write_00003_00000[] = "\x53\x45\x54\x20\x64\x61\x74\x61\x20\x61\x61\x61\x61\x61\x61\x61" "\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61" "\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61" "\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61" "\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61" "\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61" "\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61" "\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61" "\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61" "\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61" "\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61" "\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61" "\x61\x61\x61\x61\x61\x61\x61\x61\x61\x61\x0a"; static unsigned int write_00003_00000_len = 203; unsigned char *write_00003 = NULL; unsigned int write_00003_len = 0; write_00003 = cgc_append_buf(write_00003, &write_00003_len, write_00003_00000, write_00003_00000_len); if (write_00003_len > 0) { cgc_transmit_all(1, write_00003, write_00003_len); } cgc_free(write_00003); } while (0); do { unsigned char *read_00003; unsigned int read_00003_len; unsigned int read_00003_ptr = 0; //**** delimited read static unsigned char read_00003_delim[] = "\x0a"; read_00003 = NULL; read_00003_len = 0; int read_00003_res = cgc_delimited_read(0, &read_00003, &read_00003_len, read_00003_delim, 1); if (read_00003_res) {} //silence unused variable warning //**** read match data static unsigned char match_00003_00000[] = "\x4f\x4b\x0a"; read_00003_ptr += cgc_data_match(read_00003 + read_00003_ptr, read_00003_len - read_00003_ptr, match_00003_00000, 3); cgc_free(read_00003); if (read_00003_ptr) {} //silence unused variable warning if any } while (0); do { //*** writing data static unsigned char write_00004_00000[] = "\x43\x41\x4c\x4c\x20\x2f\x72\x6f\x6f\x74\x36\x34\x0a"; static unsigned int write_00004_00000_len = 13; unsigned char *write_00004 = NULL; unsigned int write_00004_len = 0; write_00004 = cgc_append_buf(write_00004, &write_00004_len, write_00004_00000, write_00004_00000_len); if (write_00004_len > 0) { cgc_transmit_all(1, write_00004, write_00004_len); } cgc_free(write_00004); } while (0); do { unsigned char *read_00004; unsigned int read_00004_len; unsigned int read_00004_ptr = 0; //**** delimited read static unsigned char read_00004_delim[] = "\x0a"; read_00004 = NULL; read_00004_len = 0; int read_00004_res = cgc_delimited_read(0, &read_00004, &read_00004_len, read_00004_delim, 1); if (read_00004_res) {} //silence unused variable warning cgc_free(read_00004); if (read_00004_ptr) {} //silence unused variable warning if any } while (0); }
0.960938
1
dlls/d3d11/utils.c
GranPC/wine
4
1068
/* * Copyright 2008 <NAME> for CodeWeavers * * 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 St, Fifth Floor, Boston, MA 02110-1301, USA * */ #include "config.h" #include "wine/port.h" #include "d3d11_private.h" WINE_DEFAULT_DEBUG_CHANNEL(d3d11); #define WINE_D3D_TO_STR(x) case x: return #x const char *debug_d3d10_primitive_topology(D3D10_PRIMITIVE_TOPOLOGY topology) { switch (topology) { WINE_D3D_TO_STR(D3D10_PRIMITIVE_TOPOLOGY_UNDEFINED); WINE_D3D_TO_STR(D3D10_PRIMITIVE_TOPOLOGY_POINTLIST); WINE_D3D_TO_STR(D3D10_PRIMITIVE_TOPOLOGY_LINELIST); WINE_D3D_TO_STR(D3D10_PRIMITIVE_TOPOLOGY_LINESTRIP); WINE_D3D_TO_STR(D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST); WINE_D3D_TO_STR(D3D10_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP); WINE_D3D_TO_STR(D3D10_PRIMITIVE_TOPOLOGY_LINELIST_ADJ); WINE_D3D_TO_STR(D3D10_PRIMITIVE_TOPOLOGY_LINESTRIP_ADJ); WINE_D3D_TO_STR(D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST_ADJ); WINE_D3D_TO_STR(D3D10_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP_ADJ); default: FIXME("Unrecognized D3D10_PRIMITIVE_TOPOLOGY %#x\n", topology); return "unrecognized"; } } const char *debug_dxgi_format(DXGI_FORMAT format) { switch(format) { WINE_D3D_TO_STR(DXGI_FORMAT_UNKNOWN); WINE_D3D_TO_STR(DXGI_FORMAT_R32G32B32A32_TYPELESS); WINE_D3D_TO_STR(DXGI_FORMAT_R32G32B32A32_FLOAT); WINE_D3D_TO_STR(DXGI_FORMAT_R32G32B32A32_UINT); WINE_D3D_TO_STR(DXGI_FORMAT_R32G32B32A32_SINT); WINE_D3D_TO_STR(DXGI_FORMAT_R32G32B32_TYPELESS); WINE_D3D_TO_STR(DXGI_FORMAT_R32G32B32_FLOAT); WINE_D3D_TO_STR(DXGI_FORMAT_R32G32B32_UINT); WINE_D3D_TO_STR(DXGI_FORMAT_R32G32B32_SINT); WINE_D3D_TO_STR(DXGI_FORMAT_R16G16B16A16_TYPELESS); WINE_D3D_TO_STR(DXGI_FORMAT_R16G16B16A16_FLOAT); WINE_D3D_TO_STR(DXGI_FORMAT_R16G16B16A16_UNORM); WINE_D3D_TO_STR(DXGI_FORMAT_R16G16B16A16_UINT); WINE_D3D_TO_STR(DXGI_FORMAT_R16G16B16A16_SNORM); WINE_D3D_TO_STR(DXGI_FORMAT_R16G16B16A16_SINT); WINE_D3D_TO_STR(DXGI_FORMAT_R32G32_TYPELESS); WINE_D3D_TO_STR(DXGI_FORMAT_R32G32_FLOAT); WINE_D3D_TO_STR(DXGI_FORMAT_R32G32_UINT); WINE_D3D_TO_STR(DXGI_FORMAT_R32G32_SINT); WINE_D3D_TO_STR(DXGI_FORMAT_R32G8X24_TYPELESS); WINE_D3D_TO_STR(DXGI_FORMAT_D32_FLOAT_S8X24_UINT); WINE_D3D_TO_STR(DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS); WINE_D3D_TO_STR(DXGI_FORMAT_X32_TYPELESS_G8X24_UINT); WINE_D3D_TO_STR(DXGI_FORMAT_R10G10B10A2_TYPELESS); WINE_D3D_TO_STR(DXGI_FORMAT_R10G10B10A2_UNORM); WINE_D3D_TO_STR(DXGI_FORMAT_R10G10B10A2_UINT); WINE_D3D_TO_STR(DXGI_FORMAT_R11G11B10_FLOAT); WINE_D3D_TO_STR(DXGI_FORMAT_R8G8B8A8_TYPELESS); WINE_D3D_TO_STR(DXGI_FORMAT_R8G8B8A8_UNORM); WINE_D3D_TO_STR(DXGI_FORMAT_R8G8B8A8_UNORM_SRGB); WINE_D3D_TO_STR(DXGI_FORMAT_R8G8B8A8_UINT); WINE_D3D_TO_STR(DXGI_FORMAT_R8G8B8A8_SNORM); WINE_D3D_TO_STR(DXGI_FORMAT_R8G8B8A8_SINT); WINE_D3D_TO_STR(DXGI_FORMAT_R16G16_TYPELESS); WINE_D3D_TO_STR(DXGI_FORMAT_R16G16_FLOAT); WINE_D3D_TO_STR(DXGI_FORMAT_R16G16_UNORM); WINE_D3D_TO_STR(DXGI_FORMAT_R16G16_UINT); WINE_D3D_TO_STR(DXGI_FORMAT_R16G16_SNORM); WINE_D3D_TO_STR(DXGI_FORMAT_R16G16_SINT); WINE_D3D_TO_STR(DXGI_FORMAT_R32_TYPELESS); WINE_D3D_TO_STR(DXGI_FORMAT_D32_FLOAT); WINE_D3D_TO_STR(DXGI_FORMAT_R32_FLOAT); WINE_D3D_TO_STR(DXGI_FORMAT_R32_UINT); WINE_D3D_TO_STR(DXGI_FORMAT_R32_SINT); WINE_D3D_TO_STR(DXGI_FORMAT_R24G8_TYPELESS); WINE_D3D_TO_STR(DXGI_FORMAT_D24_UNORM_S8_UINT); WINE_D3D_TO_STR(DXGI_FORMAT_R24_UNORM_X8_TYPELESS); WINE_D3D_TO_STR(DXGI_FORMAT_X24_TYPELESS_G8_UINT); WINE_D3D_TO_STR(DXGI_FORMAT_R8G8_TYPELESS); WINE_D3D_TO_STR(DXGI_FORMAT_R8G8_UNORM); WINE_D3D_TO_STR(DXGI_FORMAT_R8G8_UINT); WINE_D3D_TO_STR(DXGI_FORMAT_R8G8_SNORM); WINE_D3D_TO_STR(DXGI_FORMAT_R8G8_SINT); WINE_D3D_TO_STR(DXGI_FORMAT_R16_TYPELESS); WINE_D3D_TO_STR(DXGI_FORMAT_R16_FLOAT); WINE_D3D_TO_STR(DXGI_FORMAT_D16_UNORM); WINE_D3D_TO_STR(DXGI_FORMAT_R16_UNORM); WINE_D3D_TO_STR(DXGI_FORMAT_R16_UINT); WINE_D3D_TO_STR(DXGI_FORMAT_R16_SNORM); WINE_D3D_TO_STR(DXGI_FORMAT_R16_SINT); WINE_D3D_TO_STR(DXGI_FORMAT_R8_TYPELESS); WINE_D3D_TO_STR(DXGI_FORMAT_R8_UNORM); WINE_D3D_TO_STR(DXGI_FORMAT_R8_UINT); WINE_D3D_TO_STR(DXGI_FORMAT_R8_SNORM); WINE_D3D_TO_STR(DXGI_FORMAT_R8_SINT); WINE_D3D_TO_STR(DXGI_FORMAT_A8_UNORM); WINE_D3D_TO_STR(DXGI_FORMAT_R1_UNORM); WINE_D3D_TO_STR(DXGI_FORMAT_R9G9B9E5_SHAREDEXP); WINE_D3D_TO_STR(DXGI_FORMAT_R8G8_B8G8_UNORM); WINE_D3D_TO_STR(DXGI_FORMAT_G8R8_G8B8_UNORM); WINE_D3D_TO_STR(DXGI_FORMAT_BC1_TYPELESS); WINE_D3D_TO_STR(DXGI_FORMAT_BC1_UNORM); WINE_D3D_TO_STR(DXGI_FORMAT_BC1_UNORM_SRGB); WINE_D3D_TO_STR(DXGI_FORMAT_BC2_TYPELESS); WINE_D3D_TO_STR(DXGI_FORMAT_BC2_UNORM); WINE_D3D_TO_STR(DXGI_FORMAT_BC2_UNORM_SRGB); WINE_D3D_TO_STR(DXGI_FORMAT_BC3_TYPELESS); WINE_D3D_TO_STR(DXGI_FORMAT_BC3_UNORM); WINE_D3D_TO_STR(DXGI_FORMAT_BC3_UNORM_SRGB); WINE_D3D_TO_STR(DXGI_FORMAT_BC4_TYPELESS); WINE_D3D_TO_STR(DXGI_FORMAT_BC4_UNORM); WINE_D3D_TO_STR(DXGI_FORMAT_BC4_SNORM); WINE_D3D_TO_STR(DXGI_FORMAT_BC5_TYPELESS); WINE_D3D_TO_STR(DXGI_FORMAT_BC5_UNORM); WINE_D3D_TO_STR(DXGI_FORMAT_BC5_SNORM); WINE_D3D_TO_STR(DXGI_FORMAT_B5G6R5_UNORM); WINE_D3D_TO_STR(DXGI_FORMAT_B5G5R5A1_UNORM); WINE_D3D_TO_STR(DXGI_FORMAT_B8G8R8A8_UNORM); WINE_D3D_TO_STR(DXGI_FORMAT_B8G8R8X8_UNORM); WINE_D3D_TO_STR(DXGI_FORMAT_B8G8R8A8_TYPELESS); WINE_D3D_TO_STR(DXGI_FORMAT_B8G8R8A8_UNORM_SRGB); WINE_D3D_TO_STR(DXGI_FORMAT_B8G8R8X8_TYPELESS); WINE_D3D_TO_STR(DXGI_FORMAT_B8G8R8X8_UNORM_SRGB); WINE_D3D_TO_STR(DXGI_FORMAT_BC7_TYPELESS); WINE_D3D_TO_STR(DXGI_FORMAT_BC7_UNORM); WINE_D3D_TO_STR(DXGI_FORMAT_BC7_UNORM_SRGB); default: FIXME("Unrecognized DXGI_FORMAT %#x.\n", format); return "unrecognized"; } } #undef WINE_D3D_TO_STR const char *debug_float4(const float *values) { if (!values) return "(null)"; return wine_dbg_sprintf("{%.8e, %.8e, %.8e, %.8e}", values[0], values[1], values[2], values[3]); } DXGI_FORMAT dxgi_format_from_wined3dformat(enum wined3d_format_id format) { switch(format) { case WINED3DFMT_UNKNOWN: return DXGI_FORMAT_UNKNOWN; case WINED3DFMT_R32G32B32A32_TYPELESS: return DXGI_FORMAT_R32G32B32A32_TYPELESS; case WINED3DFMT_R32G32B32A32_FLOAT: return DXGI_FORMAT_R32G32B32A32_FLOAT; case WINED3DFMT_R32G32B32A32_UINT: return DXGI_FORMAT_R32G32B32A32_UINT; case WINED3DFMT_R32G32B32A32_SINT: return DXGI_FORMAT_R32G32B32A32_SINT; case WINED3DFMT_R32G32B32_TYPELESS: return DXGI_FORMAT_R32G32B32_TYPELESS; case WINED3DFMT_R32G32B32_FLOAT: return DXGI_FORMAT_R32G32B32_FLOAT; case WINED3DFMT_R32G32B32_UINT: return DXGI_FORMAT_R32G32B32_UINT; case WINED3DFMT_R32G32B32_SINT: return DXGI_FORMAT_R32G32B32_SINT; case WINED3DFMT_R16G16B16A16_TYPELESS: return DXGI_FORMAT_R16G16B16A16_TYPELESS; case WINED3DFMT_R16G16B16A16_FLOAT: return DXGI_FORMAT_R16G16B16A16_FLOAT; case WINED3DFMT_R16G16B16A16_UNORM: return DXGI_FORMAT_R16G16B16A16_UNORM; case WINED3DFMT_R16G16B16A16_UINT: return DXGI_FORMAT_R16G16B16A16_UINT; case WINED3DFMT_R16G16B16A16_SNORM: return DXGI_FORMAT_R16G16B16A16_SNORM; case WINED3DFMT_R16G16B16A16_SINT: return DXGI_FORMAT_R16G16B16A16_SINT; case WINED3DFMT_R32G32_TYPELESS: return DXGI_FORMAT_R32G32_TYPELESS; case WINED3DFMT_R32G32_FLOAT: return DXGI_FORMAT_R32G32_FLOAT; case WINED3DFMT_R32G32_UINT: return DXGI_FORMAT_R32G32_UINT; case WINED3DFMT_R32G32_SINT: return DXGI_FORMAT_R32G32_SINT; case WINED3DFMT_R32G8X24_TYPELESS: return DXGI_FORMAT_R32G8X24_TYPELESS; case WINED3DFMT_D32_FLOAT_S8X24_UINT: return DXGI_FORMAT_D32_FLOAT_S8X24_UINT; case WINED3DFMT_R32_FLOAT_X8X24_TYPELESS: return DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS; case WINED3DFMT_X32_TYPELESS_G8X24_UINT: return DXGI_FORMAT_X32_TYPELESS_G8X24_UINT; case WINED3DFMT_R10G10B10A2_TYPELESS: return DXGI_FORMAT_R10G10B10A2_TYPELESS; case WINED3DFMT_R10G10B10A2_UNORM: return DXGI_FORMAT_R10G10B10A2_UNORM; case WINED3DFMT_R10G10B10A2_UINT: return DXGI_FORMAT_R10G10B10A2_UINT; case WINED3DFMT_R11G11B10_FLOAT: return DXGI_FORMAT_R11G11B10_FLOAT; case WINED3DFMT_R8G8B8A8_TYPELESS: return DXGI_FORMAT_R8G8B8A8_TYPELESS; case WINED3DFMT_R8G8B8A8_UNORM: return DXGI_FORMAT_R8G8B8A8_UNORM; case WINED3DFMT_R8G8B8A8_UNORM_SRGB: return DXGI_FORMAT_R8G8B8A8_UNORM_SRGB; case WINED3DFMT_R8G8B8A8_UINT: return DXGI_FORMAT_R8G8B8A8_UINT; case WINED3DFMT_R8G8B8A8_SNORM: return DXGI_FORMAT_R8G8B8A8_SNORM; case WINED3DFMT_R8G8B8A8_SINT: return DXGI_FORMAT_R8G8B8A8_SINT; case WINED3DFMT_R16G16_TYPELESS: return DXGI_FORMAT_R16G16_TYPELESS; case WINED3DFMT_R16G16_FLOAT: return DXGI_FORMAT_R16G16_FLOAT; case WINED3DFMT_R16G16_UNORM: return DXGI_FORMAT_R16G16_UNORM; case WINED3DFMT_R16G16_UINT: return DXGI_FORMAT_R16G16_UINT; case WINED3DFMT_R16G16_SNORM: return DXGI_FORMAT_R16G16_SNORM; case WINED3DFMT_R16G16_SINT: return DXGI_FORMAT_R16G16_SINT; case WINED3DFMT_R32_TYPELESS: return DXGI_FORMAT_R32_TYPELESS; case WINED3DFMT_D32_FLOAT: return DXGI_FORMAT_D32_FLOAT; case WINED3DFMT_R32_FLOAT: return DXGI_FORMAT_R32_FLOAT; case WINED3DFMT_R32_UINT: return DXGI_FORMAT_R32_UINT; case WINED3DFMT_R32_SINT: return DXGI_FORMAT_R32_SINT; case WINED3DFMT_R24G8_TYPELESS: return DXGI_FORMAT_R24G8_TYPELESS; case WINED3DFMT_D24_UNORM_S8_UINT: return DXGI_FORMAT_D24_UNORM_S8_UINT; case WINED3DFMT_R24_UNORM_X8_TYPELESS: return DXGI_FORMAT_R24_UNORM_X8_TYPELESS; case WINED3DFMT_X24_TYPELESS_G8_UINT: return DXGI_FORMAT_X24_TYPELESS_G8_UINT; case WINED3DFMT_R8G8_TYPELESS: return DXGI_FORMAT_R8G8_TYPELESS; case WINED3DFMT_R8G8_UNORM: return DXGI_FORMAT_R8G8_UNORM; case WINED3DFMT_R8G8_UINT: return DXGI_FORMAT_R8G8_UINT; case WINED3DFMT_R8G8_SNORM: return DXGI_FORMAT_R8G8_SNORM; case WINED3DFMT_R8G8_SINT: return DXGI_FORMAT_R8G8_SINT; case WINED3DFMT_R16_TYPELESS: return DXGI_FORMAT_R16_TYPELESS; case WINED3DFMT_R16_FLOAT: return DXGI_FORMAT_R16_FLOAT; case WINED3DFMT_D16_UNORM: return DXGI_FORMAT_D16_UNORM; case WINED3DFMT_R16_UNORM: return DXGI_FORMAT_R16_UNORM; case WINED3DFMT_R16_UINT: return DXGI_FORMAT_R16_UINT; case WINED3DFMT_R16_SNORM: return DXGI_FORMAT_R16_SNORM; case WINED3DFMT_R16_SINT: return DXGI_FORMAT_R16_SINT; case WINED3DFMT_R8_TYPELESS: return DXGI_FORMAT_R8_TYPELESS; case WINED3DFMT_R8_UNORM: return DXGI_FORMAT_R8_UNORM; case WINED3DFMT_R8_UINT: return DXGI_FORMAT_R8_UINT; case WINED3DFMT_R8_SNORM: return DXGI_FORMAT_R8_SNORM; case WINED3DFMT_R8_SINT: return DXGI_FORMAT_R8_SINT; case WINED3DFMT_A8_UNORM: return DXGI_FORMAT_A8_UNORM; case WINED3DFMT_R1_UNORM: return DXGI_FORMAT_R1_UNORM; case WINED3DFMT_R9G9B9E5_SHAREDEXP: return DXGI_FORMAT_R9G9B9E5_SHAREDEXP; case WINED3DFMT_R8G8_B8G8_UNORM: return DXGI_FORMAT_R8G8_B8G8_UNORM; case WINED3DFMT_G8R8_G8B8_UNORM: return DXGI_FORMAT_G8R8_G8B8_UNORM; case WINED3DFMT_BC1_TYPELESS: return DXGI_FORMAT_BC1_TYPELESS; case WINED3DFMT_BC1_UNORM: return DXGI_FORMAT_BC1_UNORM; case WINED3DFMT_BC1_UNORM_SRGB: return DXGI_FORMAT_BC1_UNORM_SRGB; case WINED3DFMT_BC2_TYPELESS: return DXGI_FORMAT_BC2_TYPELESS; case WINED3DFMT_BC2_UNORM: return DXGI_FORMAT_BC2_UNORM; case WINED3DFMT_BC2_UNORM_SRGB: return DXGI_FORMAT_BC2_UNORM_SRGB; case WINED3DFMT_BC3_TYPELESS: return DXGI_FORMAT_BC3_TYPELESS; case WINED3DFMT_BC3_UNORM: return DXGI_FORMAT_BC3_UNORM; case WINED3DFMT_BC3_UNORM_SRGB: return DXGI_FORMAT_BC3_UNORM_SRGB; case WINED3DFMT_BC4_TYPELESS: return DXGI_FORMAT_BC4_TYPELESS; case WINED3DFMT_BC4_UNORM: return DXGI_FORMAT_BC4_UNORM; case WINED3DFMT_BC4_SNORM: return DXGI_FORMAT_BC4_SNORM; case WINED3DFMT_BC5_TYPELESS: return DXGI_FORMAT_BC5_TYPELESS; case WINED3DFMT_BC5_UNORM: return DXGI_FORMAT_BC5_UNORM; case WINED3DFMT_BC5_SNORM: return DXGI_FORMAT_BC5_SNORM; case WINED3DFMT_B5G6R5_UNORM: return DXGI_FORMAT_B5G6R5_UNORM; case WINED3DFMT_B5G5R5A1_UNORM: return DXGI_FORMAT_B5G5R5A1_UNORM; case WINED3DFMT_B8G8R8A8_UNORM: return DXGI_FORMAT_B8G8R8A8_UNORM; case WINED3DFMT_B8G8R8X8_UNORM: return DXGI_FORMAT_B8G8R8X8_UNORM; case WINED3DFMT_B8G8R8A8_TYPELESS: return DXGI_FORMAT_B8G8R8A8_TYPELESS; case WINED3DFMT_B8G8R8A8_UNORM_SRGB: return DXGI_FORMAT_B8G8R8A8_UNORM_SRGB; case WINED3DFMT_B8G8R8X8_TYPELESS: return DXGI_FORMAT_B8G8R8X8_TYPELESS; case WINED3DFMT_B8G8R8X8_UNORM_SRGB: return DXGI_FORMAT_B8G8R8X8_UNORM_SRGB; case WINED3DFMT_BC7_TYPELESS: return DXGI_FORMAT_BC7_TYPELESS; case WINED3DFMT_BC7_UNORM: return DXGI_FORMAT_BC7_UNORM; case WINED3DFMT_BC7_UNORM_SRGB: return DXGI_FORMAT_BC7_UNORM_SRGB; default: FIXME("Unhandled wined3d format %#x.\n", format); return DXGI_FORMAT_UNKNOWN; } } enum wined3d_format_id wined3dformat_from_dxgi_format(DXGI_FORMAT format) { switch(format) { case DXGI_FORMAT_UNKNOWN: return WINED3DFMT_UNKNOWN; case DXGI_FORMAT_R32G32B32A32_TYPELESS: return WINED3DFMT_R32G32B32A32_TYPELESS; case DXGI_FORMAT_R32G32B32A32_FLOAT: return WINED3DFMT_R32G32B32A32_FLOAT; case DXGI_FORMAT_R32G32B32A32_UINT: return WINED3DFMT_R32G32B32A32_UINT; case DXGI_FORMAT_R32G32B32A32_SINT: return WINED3DFMT_R32G32B32A32_SINT; case DXGI_FORMAT_R32G32B32_TYPELESS: return WINED3DFMT_R32G32B32_TYPELESS; case DXGI_FORMAT_R32G32B32_FLOAT: return WINED3DFMT_R32G32B32_FLOAT; case DXGI_FORMAT_R32G32B32_UINT: return WINED3DFMT_R32G32B32_UINT; case DXGI_FORMAT_R32G32B32_SINT: return WINED3DFMT_R32G32B32_SINT; case DXGI_FORMAT_R16G16B16A16_TYPELESS: return WINED3DFMT_R16G16B16A16_TYPELESS; case DXGI_FORMAT_R16G16B16A16_FLOAT: return WINED3DFMT_R16G16B16A16_FLOAT; case DXGI_FORMAT_R16G16B16A16_UNORM: return WINED3DFMT_R16G16B16A16_UNORM; case DXGI_FORMAT_R16G16B16A16_UINT: return WINED3DFMT_R16G16B16A16_UINT; case DXGI_FORMAT_R16G16B16A16_SNORM: return WINED3DFMT_R16G16B16A16_SNORM; case DXGI_FORMAT_R16G16B16A16_SINT: return WINED3DFMT_R16G16B16A16_SINT; case DXGI_FORMAT_R32G32_TYPELESS: return WINED3DFMT_R32G32_TYPELESS; case DXGI_FORMAT_R32G32_FLOAT: return WINED3DFMT_R32G32_FLOAT; case DXGI_FORMAT_R32G32_UINT: return WINED3DFMT_R32G32_UINT; case DXGI_FORMAT_R32G32_SINT: return WINED3DFMT_R32G32_SINT; case DXGI_FORMAT_R32G8X24_TYPELESS: return WINED3DFMT_R32G8X24_TYPELESS; case DXGI_FORMAT_D32_FLOAT_S8X24_UINT: return WINED3DFMT_D32_FLOAT_S8X24_UINT; case DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS: return WINED3DFMT_R32_FLOAT_X8X24_TYPELESS; case DXGI_FORMAT_X32_TYPELESS_G8X24_UINT: return WINED3DFMT_X32_TYPELESS_G8X24_UINT; case DXGI_FORMAT_R10G10B10A2_TYPELESS: return WINED3DFMT_R10G10B10A2_TYPELESS; case DXGI_FORMAT_R10G10B10A2_UNORM: return WINED3DFMT_R10G10B10A2_UNORM; case DXGI_FORMAT_R10G10B10A2_UINT: return WINED3DFMT_R10G10B10A2_UINT; case DXGI_FORMAT_R11G11B10_FLOAT: return WINED3DFMT_R11G11B10_FLOAT; case DXGI_FORMAT_R8G8B8A8_TYPELESS: return WINED3DFMT_R8G8B8A8_TYPELESS; case DXGI_FORMAT_R8G8B8A8_UNORM: return WINED3DFMT_R8G8B8A8_UNORM; case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: return WINED3DFMT_R8G8B8A8_UNORM_SRGB; case DXGI_FORMAT_R8G8B8A8_UINT: return WINED3DFMT_R8G8B8A8_UINT; case DXGI_FORMAT_R8G8B8A8_SNORM: return WINED3DFMT_R8G8B8A8_SNORM; case DXGI_FORMAT_R8G8B8A8_SINT: return WINED3DFMT_R8G8B8A8_SINT; case DXGI_FORMAT_R16G16_TYPELESS: return WINED3DFMT_R16G16_TYPELESS; case DXGI_FORMAT_R16G16_FLOAT: return WINED3DFMT_R16G16_FLOAT; case DXGI_FORMAT_R16G16_UNORM: return WINED3DFMT_R16G16_UNORM; case DXGI_FORMAT_R16G16_UINT: return WINED3DFMT_R16G16_UINT; case DXGI_FORMAT_R16G16_SNORM: return WINED3DFMT_R16G16_SNORM; case DXGI_FORMAT_R16G16_SINT: return WINED3DFMT_R16G16_SINT; case DXGI_FORMAT_R32_TYPELESS: return WINED3DFMT_R32_TYPELESS; case DXGI_FORMAT_D32_FLOAT: return WINED3DFMT_D32_FLOAT; case DXGI_FORMAT_R32_FLOAT: return WINED3DFMT_R32_FLOAT; case DXGI_FORMAT_R32_UINT: return WINED3DFMT_R32_UINT; case DXGI_FORMAT_R32_SINT: return WINED3DFMT_R32_SINT; case DXGI_FORMAT_R24G8_TYPELESS: return WINED3DFMT_R24G8_TYPELESS; case DXGI_FORMAT_D24_UNORM_S8_UINT: return WINED3DFMT_D24_UNORM_S8_UINT; case DXGI_FORMAT_R24_UNORM_X8_TYPELESS: return WINED3DFMT_R24_UNORM_X8_TYPELESS; case DXGI_FORMAT_X24_TYPELESS_G8_UINT: return WINED3DFMT_X24_TYPELESS_G8_UINT; case DXGI_FORMAT_R8G8_TYPELESS: return WINED3DFMT_R8G8_TYPELESS; case DXGI_FORMAT_R8G8_UNORM: return WINED3DFMT_R8G8_UNORM; case DXGI_FORMAT_R8G8_UINT: return WINED3DFMT_R8G8_UINT; case DXGI_FORMAT_R8G8_SNORM: return WINED3DFMT_R8G8_SNORM; case DXGI_FORMAT_R8G8_SINT: return WINED3DFMT_R8G8_SINT; case DXGI_FORMAT_R16_TYPELESS: return WINED3DFMT_R16_TYPELESS; case DXGI_FORMAT_R16_FLOAT: return WINED3DFMT_R16_FLOAT; case DXGI_FORMAT_D16_UNORM: return WINED3DFMT_D16_UNORM; case DXGI_FORMAT_R16_UNORM: return WINED3DFMT_R16_UNORM; case DXGI_FORMAT_R16_UINT: return WINED3DFMT_R16_UINT; case DXGI_FORMAT_R16_SNORM: return WINED3DFMT_R16_SNORM; case DXGI_FORMAT_R16_SINT: return WINED3DFMT_R16_SINT; case DXGI_FORMAT_R8_TYPELESS: return WINED3DFMT_R8_TYPELESS; case DXGI_FORMAT_R8_UNORM: return WINED3DFMT_R8_UNORM; case DXGI_FORMAT_R8_UINT: return WINED3DFMT_R8_UINT; case DXGI_FORMAT_R8_SNORM: return WINED3DFMT_R8_SNORM; case DXGI_FORMAT_R8_SINT: return WINED3DFMT_R8_SINT; case DXGI_FORMAT_A8_UNORM: return WINED3DFMT_A8_UNORM; case DXGI_FORMAT_R1_UNORM: return WINED3DFMT_R1_UNORM; case DXGI_FORMAT_R9G9B9E5_SHAREDEXP: return WINED3DFMT_R9G9B9E5_SHAREDEXP; case DXGI_FORMAT_R8G8_B8G8_UNORM: return WINED3DFMT_R8G8_B8G8_UNORM; case DXGI_FORMAT_G8R8_G8B8_UNORM: return WINED3DFMT_G8R8_G8B8_UNORM; case DXGI_FORMAT_BC1_TYPELESS: return WINED3DFMT_BC1_TYPELESS; case DXGI_FORMAT_BC1_UNORM: return WINED3DFMT_BC1_UNORM; case DXGI_FORMAT_BC1_UNORM_SRGB: return WINED3DFMT_BC1_UNORM_SRGB; case DXGI_FORMAT_BC2_TYPELESS: return WINED3DFMT_BC2_TYPELESS; case DXGI_FORMAT_BC2_UNORM: return WINED3DFMT_BC2_UNORM; case DXGI_FORMAT_BC2_UNORM_SRGB: return WINED3DFMT_BC2_UNORM_SRGB; case DXGI_FORMAT_BC3_TYPELESS: return WINED3DFMT_BC3_TYPELESS; case DXGI_FORMAT_BC3_UNORM: return WINED3DFMT_BC3_UNORM; case DXGI_FORMAT_BC3_UNORM_SRGB: return WINED3DFMT_BC3_UNORM_SRGB; case DXGI_FORMAT_BC4_TYPELESS: return WINED3DFMT_BC4_TYPELESS; case DXGI_FORMAT_BC4_UNORM: return WINED3DFMT_BC4_UNORM; case DXGI_FORMAT_BC4_SNORM: return WINED3DFMT_BC4_SNORM; case DXGI_FORMAT_BC5_TYPELESS: return WINED3DFMT_BC5_TYPELESS; case DXGI_FORMAT_BC5_UNORM: return WINED3DFMT_BC5_UNORM; case DXGI_FORMAT_BC5_SNORM: return WINED3DFMT_BC5_SNORM; case DXGI_FORMAT_B5G6R5_UNORM: return WINED3DFMT_B5G6R5_UNORM; case DXGI_FORMAT_B5G5R5A1_UNORM: return WINED3DFMT_B5G5R5A1_UNORM; case DXGI_FORMAT_B8G8R8A8_UNORM: return WINED3DFMT_B8G8R8A8_UNORM; case DXGI_FORMAT_B8G8R8X8_UNORM: return WINED3DFMT_B8G8R8X8_UNORM; case DXGI_FORMAT_B8G8R8A8_TYPELESS: return WINED3DFMT_B8G8R8A8_TYPELESS; case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB: return WINED3DFMT_B8G8R8A8_UNORM_SRGB; case DXGI_FORMAT_B8G8R8X8_TYPELESS: return WINED3DFMT_B8G8R8X8_TYPELESS; case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB: return WINED3DFMT_B8G8R8X8_UNORM_SRGB; case DXGI_FORMAT_BC7_TYPELESS: return WINED3DFMT_BC7_TYPELESS; case DXGI_FORMAT_BC7_UNORM: return WINED3DFMT_BC7_UNORM; case DXGI_FORMAT_BC7_UNORM_SRGB: return WINED3DFMT_BC7_UNORM_SRGB; default: FIXME("Unhandled DXGI_FORMAT %#x.\n", format); return WINED3DFMT_UNKNOWN; } } unsigned int wined3d_getdata_flags_from_d3d11_async_getdata_flags(unsigned int d3d11_flags) { if (d3d11_flags & ~D3D11_ASYNC_GETDATA_DONOTFLUSH) FIXME("Unhandled async getdata flags %#x.\n", d3d11_flags); if (d3d11_flags & D3D11_ASYNC_GETDATA_DONOTFLUSH) return 0; return WINED3DGETDATA_FLUSH; } DWORD wined3d_usage_from_d3d11(UINT bind_flags, enum D3D11_USAGE usage) { static const DWORD handled = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET | D3D11_BIND_DEPTH_STENCIL; DWORD wined3d_usage = 0; if (bind_flags & D3D11_BIND_SHADER_RESOURCE) wined3d_usage |= WINED3DUSAGE_TEXTURE; if (bind_flags & D3D11_BIND_RENDER_TARGET) wined3d_usage |= WINED3DUSAGE_RENDERTARGET; if (bind_flags & D3D11_BIND_DEPTH_STENCIL) wined3d_usage |= WINED3DUSAGE_DEPTHSTENCIL; if (bind_flags & ~handled) FIXME("Unhandled bind flags %#x.\n", usage & ~handled); if (usage == D3D11_USAGE_DYNAMIC) wined3d_usage |= WINED3DUSAGE_DYNAMIC; return wined3d_usage; } enum D3D11_USAGE d3d11_usage_from_d3d10_usage(enum D3D10_USAGE usage) { switch (usage) { case D3D10_USAGE_DEFAULT: return D3D11_USAGE_DEFAULT; case D3D10_USAGE_IMMUTABLE: return D3D11_USAGE_IMMUTABLE; case D3D10_USAGE_DYNAMIC: return D3D11_USAGE_DYNAMIC; case D3D10_USAGE_STAGING: return D3D11_USAGE_STAGING; default: FIXME("Unhandled usage %#x.\n", usage); return D3D11_USAGE_DEFAULT; } } enum D3D10_USAGE d3d10_usage_from_d3d11_usage(enum D3D11_USAGE usage) { switch (usage) { case D3D11_USAGE_DEFAULT: return D3D10_USAGE_DEFAULT; case D3D11_USAGE_IMMUTABLE: return D3D10_USAGE_IMMUTABLE; case D3D11_USAGE_DYNAMIC: return D3D10_USAGE_DYNAMIC; case D3D11_USAGE_STAGING: return D3D10_USAGE_STAGING; default: FIXME("Unhandled usage %#x.\n", usage); return D3D10_USAGE_DEFAULT; } } UINT d3d11_bind_flags_from_d3d10_bind_flags(UINT bind_flags) { static const UINT handled_flags = D3D10_BIND_VERTEX_BUFFER | D3D10_BIND_INDEX_BUFFER | D3D10_BIND_CONSTANT_BUFFER | D3D10_BIND_SHADER_RESOURCE | D3D10_BIND_STREAM_OUTPUT | D3D10_BIND_RENDER_TARGET | D3D10_BIND_DEPTH_STENCIL; UINT d3d11_bind_flags = bind_flags & handled_flags; if (bind_flags & ~handled_flags) FIXME("Unhandled bind flags %#x.\n", bind_flags & ~handled_flags); return d3d11_bind_flags; } UINT d3d10_bind_flags_from_d3d11_bind_flags(UINT bind_flags) { static const UINT handled_flags = D3D11_BIND_VERTEX_BUFFER | D3D11_BIND_INDEX_BUFFER | D3D11_BIND_CONSTANT_BUFFER | D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_STREAM_OUTPUT | D3D11_BIND_RENDER_TARGET | D3D11_BIND_DEPTH_STENCIL | D3D11_BIND_UNORDERED_ACCESS | D3D11_BIND_DECODER | D3D11_BIND_VIDEO_ENCODER; UINT d3d10_bind_flags = bind_flags & handled_flags; if (bind_flags & ~handled_flags) FIXME("Unhandled bind flags %#x.\n", bind_flags & ~handled_flags); return d3d10_bind_flags; } UINT d3d11_cpu_access_flags_from_d3d10_cpu_access_flags(UINT cpu_access_flags) { static const UINT handled_flags = D3D10_CPU_ACCESS_WRITE | D3D10_CPU_ACCESS_READ; UINT d3d11_cpu_access_flags = cpu_access_flags & handled_flags; if (cpu_access_flags & ~handled_flags) FIXME("Unhandled cpu access flags %#x.\n", cpu_access_flags & ~handled_flags); return d3d11_cpu_access_flags; } UINT d3d10_cpu_access_flags_from_d3d11_cpu_access_flags(UINT cpu_access_flags) { static const UINT handled_flags = D3D11_CPU_ACCESS_WRITE | D3D11_CPU_ACCESS_READ; UINT d3d10_cpu_access_flags = cpu_access_flags & handled_flags; if (cpu_access_flags & ~handled_flags) FIXME("Unhandled cpu access flags %#x.\n", cpu_access_flags & ~handled_flags); return d3d10_cpu_access_flags; } UINT d3d11_resource_misc_flags_from_d3d10_resource_misc_flags(UINT resource_misc_flags) { static const UINT bitwise_identical_flags = D3D10_RESOURCE_MISC_GENERATE_MIPS | D3D10_RESOURCE_MISC_SHARED | D3D10_RESOURCE_MISC_TEXTURECUBE; const UINT handled_flags = bitwise_identical_flags | D3D10_RESOURCE_MISC_SHARED_KEYEDMUTEX | D3D10_RESOURCE_MISC_GDI_COMPATIBLE; UINT d3d11_resource_misc_flags = resource_misc_flags & bitwise_identical_flags; if (resource_misc_flags & D3D10_RESOURCE_MISC_SHARED_KEYEDMUTEX) d3d11_resource_misc_flags |= D3D11_RESOURCE_MISC_SHARED_KEYEDMUTEX; if (resource_misc_flags & D3D10_RESOURCE_MISC_GDI_COMPATIBLE) d3d11_resource_misc_flags |= D3D11_RESOURCE_MISC_GDI_COMPATIBLE; if (resource_misc_flags & ~handled_flags) FIXME("Unhandled resource misc flags %#x.\n", resource_misc_flags & ~handled_flags); return d3d11_resource_misc_flags; } UINT d3d10_resource_misc_flags_from_d3d11_resource_misc_flags(UINT resource_misc_flags) { static const UINT bitwise_identical_flags = D3D11_RESOURCE_MISC_GENERATE_MIPS | D3D11_RESOURCE_MISC_SHARED | D3D11_RESOURCE_MISC_TEXTURECUBE; const UINT handled_flags = bitwise_identical_flags | D3D11_RESOURCE_MISC_DRAWINDIRECT_ARGS | D3D11_RESOURCE_MISC_BUFFER_ALLOW_RAW_VIEWS | D3D11_RESOURCE_MISC_BUFFER_STRUCTURED | D3D11_RESOURCE_MISC_SHARED_KEYEDMUTEX | D3D11_RESOURCE_MISC_GDI_COMPATIBLE | D3D11_RESOURCE_MISC_SHARED_NTHANDLE; UINT d3d10_resource_misc_flags = resource_misc_flags & bitwise_identical_flags; if (resource_misc_flags & D3D11_RESOURCE_MISC_SHARED_KEYEDMUTEX) d3d10_resource_misc_flags |= D3D10_RESOURCE_MISC_SHARED_KEYEDMUTEX; if (resource_misc_flags & D3D11_RESOURCE_MISC_GDI_COMPATIBLE) d3d10_resource_misc_flags |= D3D10_RESOURCE_MISC_GDI_COMPATIBLE; if (resource_misc_flags & ~handled_flags) FIXME("Unhandled resource misc flags #%x.\n", resource_misc_flags & ~handled_flags); return d3d10_resource_misc_flags; } struct wined3d_resource *wined3d_resource_from_d3d11_resource(ID3D11Resource *resource) { D3D11_RESOURCE_DIMENSION dimension; ID3D11Resource_GetType(resource, &dimension); switch (dimension) { case D3D11_RESOURCE_DIMENSION_BUFFER: return wined3d_buffer_get_resource(unsafe_impl_from_ID3D11Buffer( (ID3D11Buffer *)resource)->wined3d_buffer); case D3D11_RESOURCE_DIMENSION_TEXTURE2D: return wined3d_texture_get_resource(unsafe_impl_from_ID3D11Texture2D( (ID3D11Texture2D *)resource)->wined3d_texture); case D3D11_RESOURCE_DIMENSION_TEXTURE3D: return wined3d_texture_get_resource(unsafe_impl_from_ID3D11Texture3D( (ID3D11Texture3D *)resource)->wined3d_texture); default: FIXME("Unhandled resource dimension %#x.\n", dimension); return NULL; } } struct wined3d_resource *wined3d_resource_from_d3d10_resource(ID3D10Resource *resource) { D3D10_RESOURCE_DIMENSION dimension; ID3D10Resource_GetType(resource, &dimension); switch (dimension) { case D3D10_RESOURCE_DIMENSION_BUFFER: return wined3d_buffer_get_resource(unsafe_impl_from_ID3D10Buffer( (ID3D10Buffer *)resource)->wined3d_buffer); case D3D10_RESOURCE_DIMENSION_TEXTURE2D: return wined3d_texture_get_resource(unsafe_impl_from_ID3D10Texture2D( (ID3D10Texture2D *)resource)->wined3d_texture); default: FIXME("Unhandled resource dimension %#x.\n", dimension); return NULL; } } DWORD wined3d_map_flags_from_d3d11_map_type(D3D11_MAP map_type) { switch (map_type) { case D3D11_MAP_READ_WRITE: return 0; case D3D11_MAP_READ: return WINED3D_MAP_READONLY; case D3D11_MAP_WRITE_DISCARD: return WINED3D_MAP_DISCARD; case D3D11_MAP_WRITE_NO_OVERWRITE: return WINED3D_MAP_NOOVERWRITE; default: FIXME("Unhandled map_type %#x.\n", map_type); return 0; } } DWORD wined3d_clear_flags_from_d3d11_clear_flags(UINT clear_flags) { DWORD wined3d_clear_flags = 0; if (clear_flags & D3D11_CLEAR_DEPTH) wined3d_clear_flags |= WINED3DCLEAR_ZBUFFER; if (clear_flags & D3D11_CLEAR_STENCIL) wined3d_clear_flags |= WINED3DCLEAR_STENCIL; if (clear_flags & ~(D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL)) { FIXME("Unhandled clear flags %#x.\n", clear_flags & ~(D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL)); } return wined3d_clear_flags; } HRESULT d3d_get_private_data(struct wined3d_private_store *store, REFGUID guid, UINT *data_size, void *data) { const struct wined3d_private_data *stored_data; DWORD size_in; if (!data_size) return E_INVALIDARG; wined3d_mutex_lock(); if (!(stored_data = wined3d_private_store_get_private_data(store, guid))) { *data_size = 0; wined3d_mutex_unlock(); return DXGI_ERROR_NOT_FOUND; } size_in = *data_size; *data_size = stored_data->size; if (!data) { wined3d_mutex_unlock(); return S_OK; } if (size_in < stored_data->size) { wined3d_mutex_unlock(); return DXGI_ERROR_MORE_DATA; } if (stored_data->flags & WINED3DSPD_IUNKNOWN) IUnknown_AddRef(stored_data->content.object); memcpy(data, stored_data->content.data, stored_data->size); wined3d_mutex_unlock(); return S_OK; } HRESULT d3d_set_private_data(struct wined3d_private_store *store, REFGUID guid, UINT data_size, const void *data) { struct wined3d_private_data *entry; HRESULT hr; wined3d_mutex_lock(); if (!data) { if (!(entry = wined3d_private_store_get_private_data(store, guid))) { wined3d_mutex_unlock(); return S_FALSE; } wined3d_private_store_free_private_data(store, entry); wined3d_mutex_unlock(); return S_OK; } hr = wined3d_private_store_set_private_data(store, guid, data, data_size, 0); wined3d_mutex_unlock(); return hr; } HRESULT d3d_set_private_data_interface(struct wined3d_private_store *store, REFGUID guid, const IUnknown *object) { HRESULT hr; if (!object) return d3d_set_private_data(store, guid, sizeof(object), &object); wined3d_mutex_lock(); hr = wined3d_private_store_set_private_data(store, guid, object, sizeof(object), WINED3DSPD_IUNKNOWN); wined3d_mutex_unlock(); return hr; } void skip_dword_unknown(const char **ptr, unsigned int count) { unsigned int i; DWORD d; FIXME("Skipping %u unknown DWORDs:\n", count); for (i = 0; i < count; ++i) { read_dword(ptr, &d); FIXME("\t0x%08x\n", d); } } HRESULT parse_dxbc(const char *data, SIZE_T data_size, HRESULT (*chunk_handler)(const char *data, DWORD data_size, DWORD tag, void *ctx), void *ctx) { const char *ptr = data; HRESULT hr = S_OK; DWORD chunk_count; DWORD total_size; unsigned int i; DWORD tag; read_dword(&ptr, &tag); TRACE("tag: %s.\n", debugstr_an((const char *)&tag, 4)); if (tag != TAG_DXBC) { WARN("Wrong tag.\n"); return E_INVALIDARG; } /* checksum? */ skip_dword_unknown(&ptr, 4); skip_dword_unknown(&ptr, 1); read_dword(&ptr, &total_size); TRACE("total size: %#x\n", total_size); read_dword(&ptr, &chunk_count); TRACE("chunk count: %#x\n", chunk_count); for (i = 0; i < chunk_count; ++i) { DWORD chunk_tag, chunk_size; const char *chunk_ptr; DWORD chunk_offset; read_dword(&ptr, &chunk_offset); TRACE("chunk %u at offset %#x\n", i, chunk_offset); if (chunk_offset >= data_size || !require_space(chunk_offset, 2, sizeof(DWORD), data_size)) { WARN("Invalid chunk offset %#x (data size %#lx).\n", chunk_offset, data_size); return E_FAIL; } chunk_ptr = data + chunk_offset; read_dword(&chunk_ptr, &chunk_tag); read_dword(&chunk_ptr, &chunk_size); if (!require_space(chunk_ptr - data, 1, chunk_size, data_size)) { WARN("Invalid chunk size %#x (data size %#lx, chunk offset %#x).\n", chunk_size, data_size, chunk_offset); return E_FAIL; } hr = chunk_handler(chunk_ptr, chunk_size, chunk_tag, ctx); if (FAILED(hr)) break; } return hr; }
1.109375
1
ompi/mpi/c/win_allocate_shared.c
isuruf/ompi
20
1076
/* -*- Mode: C; c-basic-offset:4 ; indent-tabs-mode:nil -*- */ /* * Copyright (c) 2004-2007 The Trustees of Indiana University and Indiana * University Research and Technology * Corporation. All rights reserved. * Copyright (c) 2004-2005 The University of Tennessee and The University * of Tennessee Research Foundation. All rights * reserved. * Copyright (c) 2004-2008 High Performance Computing Center Stuttgart, * University of Stuttgart. All rights reserved. * Copyright (c) 2004-2005 The Regents of the University of California. * All rights reserved. * Copyright (c) 2006 Cisco Systems, Inc. All rights reserved. * Copyright (c) 2014 Los Alamos National Security, LLC. All rights * reserved. * Copyright (c) 2015 Research Organization for Information Science * and Technology (RIST). All rights reserved. * Copyright (c) 2017 IBM Corporation. All rights reserved. * $COPYRIGHT$ * * Additional copyrights may follow * * $HEADER$ */ #include "ompi_config.h" #include <stdio.h> #include "ompi/mpi/c/bindings.h" #include "ompi/runtime/params.h" #include "ompi/communicator/communicator.h" #include "ompi/errhandler/errhandler.h" #include "ompi/info/info.h" #include "ompi/win/win.h" #include "ompi/memchecker.h" #if OMPI_BUILD_MPI_PROFILING #if OPAL_HAVE_WEAK_SYMBOLS #pragma weak MPI_Win_allocate_shared = PMPI_Win_allocate_shared #endif #define MPI_Win_allocate_shared PMPI_Win_allocate_shared #endif static const char FUNC_NAME[] = "MPI_Win_allocate_shared"; int MPI_Win_allocate_shared(MPI_Aint size, int disp_unit, MPI_Info info, MPI_Comm comm, void *baseptr, MPI_Win *win) { int ret = MPI_SUCCESS; MEMCHECKER( memchecker_comm(comm); ); /* argument checking */ if (MPI_PARAM_CHECK) { OMPI_ERR_INIT_FINALIZE(FUNC_NAME); if (ompi_comm_invalid (comm)) { return OMPI_ERRHANDLER_INVOKE(MPI_COMM_WORLD, MPI_ERR_COMM, FUNC_NAME); } else if (NULL == info || ompi_info_is_freed(info)) { return OMPI_ERRHANDLER_INVOKE(comm, MPI_ERR_INFO, FUNC_NAME); } else if (NULL == win) { return OMPI_ERRHANDLER_INVOKE(comm, MPI_ERR_WIN, FUNC_NAME); } else if ( size < 0 ) { return OMPI_ERRHANDLER_INVOKE(comm, MPI_ERR_SIZE, FUNC_NAME); } } /* communicator must be an intracommunicator */ if (OMPI_COMM_IS_INTER(comm)) { return OMPI_ERRHANDLER_INVOKE(comm, MPI_ERR_COMM, FUNC_NAME); } OPAL_CR_ENTER_LIBRARY(); /* create window and return */ ret = ompi_win_allocate_shared((size_t)size, disp_unit, &(info->super), comm, baseptr, win); if (OMPI_SUCCESS != ret) { *win = MPI_WIN_NULL; OPAL_CR_EXIT_LIBRARY(); OMPI_ERRHANDLER_RETURN (ret, comm, ret, FUNC_NAME); } OPAL_CR_EXIT_LIBRARY(); return MPI_SUCCESS; }
1.15625
1
arch/risc-v/src/esp32c3/esp32c3_dma.c
alvin1991/incubator-nuttx
201
1084
/**************************************************************************** * arch/risc-v/src/esp32c3/esp32c3_dma.c * * 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. * ****************************************************************************/ /**************************************************************************** * Included Files ****************************************************************************/ #include <nuttx/config.h> #include <sys/types.h> #include <stdint.h> #include <string.h> #include <assert.h> #include <debug.h> #include <nuttx/arch.h> #include <nuttx/irq.h> #include <nuttx/kmalloc.h> #include <arch/irq.h> #include "riscv_arch.h" #include "esp32c3_dma.h" #include "hardware/esp32c3_dma.h" #include "hardware/esp32c3_soc.h" #include "hardware/esp32c3_system.h" /**************************************************************************** * Pre-processor Macros ****************************************************************************/ #define REG_OFF (DMA_OUT_CONF0_CH1_REG - DMA_OUT_CONF0_CH0_REG) #define SET_REG(_r, _ch, _v) putreg32((_v), (_r) + (_ch) * REG_OFF) #define GET_REG(_r, _ch) getreg32((_r) + (_ch) * REG_OFF) #define SET_BITS(_r, _ch, _b) modifyreg32((_r) + (_ch) * REG_OFF, 0, (_b)) #define CLR_BITS(_r, _ch, _b) modifyreg32((_r) + (_ch) * REG_OFF, (_b), 0) #ifndef MIN # define MIN(a, b) (((a) < (b)) ? (a) : (b)) #endif #ifndef ALIGN_UP # define ALIGN_UP(num, align) (((num) + ((align) - 1)) & ~((align) - 1)) #endif /**************************************************************************** * Private Data ****************************************************************************/ static bool g_dma_chan_used[ESP32C3_DMA_CHAN_MAX]; static sem_t g_dma_exc_sem = SEM_INITIALIZER(1); /**************************************************************************** * Public Functions ****************************************************************************/ /**************************************************************************** * Name: esp32c3_dma_request * * Description: * Request DMA channel and config it with given parameters. * * Input Parameters: * periph - Peripheral for which the DMA channel request was made * tx_prio - Interrupt priority * rx_prio - Interrupt flags * burst_en - Enable burst transmission * * Returned Value: * DMA channel number (>=0) if success or -1 if fail. * ****************************************************************************/ int32_t esp32c3_dma_request(enum esp32c3_dma_periph_e periph, uint32_t tx_prio, uint32_t rx_prio, bool burst_en) { int chan; DEBUGASSERT((periph < ESP32C3_DMA_PERIPH_NUM) && (periph != ESP32C3_DMA_PERIPH_RD0) && (periph != ESP32C3_DMA_PERIPH_RD1)); DEBUGASSERT(tx_prio <= ESP32C3_DMA_TX_PRIO_MAX); DEBUGASSERT(rx_prio <= ESP32C3_DMA_RX_PRIO_MAX); dmainfo("periph=%" PRIu32 " tx_prio=%" PRIu32 " rx_prio=%" PRIu32 "\n", (uint32_t)periph, tx_prio, rx_prio); nxsem_wait_uninterruptible(&g_dma_exc_sem); for (chan = 0; chan < ESP32C3_DMA_CHAN_MAX; chan++) { if (!g_dma_chan_used[chan]) { g_dma_chan_used[chan] = true; break; } } if (chan == ESP32C3_DMA_CHAN_MAX) { dmaerr("No available GDMA channel for allocation\n"); nxsem_post(&g_dma_exc_sem); return ERROR; } dmainfo("Allocated channel=%d\n", chan); if (periph == ESP32C3_DMA_PERIPH_MEM) { /* Enable DMA channel M2M mode */ SET_BITS(DMA_IN_CONF0_CH0_REG, chan, DMA_MEM_TRANS_EN_CH0_M); /* Just setting a valid value to the register */ SET_REG(DMA_OUT_PERI_SEL_CH0_REG, chan, 0); SET_REG(DMA_IN_PERI_SEL_CH0_REG, chan, 0); } else { /* Disable DMA channel M2M mode */ CLR_BITS(DMA_IN_CONF0_CH0_REG, chan, DMA_MEM_TRANS_EN_CH0_M); /* Connect DMA TX/RX channels to a given peripheral */ SET_REG(DMA_OUT_PERI_SEL_CH0_REG, chan, periph); SET_REG(DMA_IN_PERI_SEL_CH0_REG, chan, periph); } if (burst_en) { /* Enable DMA TX/RX channels burst sending data */ SET_BITS(DMA_OUT_CONF0_CH0_REG, chan, DMA_OUT_DATA_BURST_EN_CH0_M); SET_BITS(DMA_IN_CONF0_CH0_REG, chan, DMA_IN_DATA_BURST_EN_CH0_M); /* Enable DMA TX/RX channels burst reading descriptor link */ SET_BITS(DMA_OUT_CONF0_CH0_REG, chan, DMA_OUTDSCR_BURST_EN_CH0_M); SET_BITS(DMA_IN_CONF0_CH0_REG, chan, DMA_INDSCR_BURST_EN_CH0_M); } /* Set priority for DMA TX/RX channels */ SET_REG(DMA_OUT_PRI_CH0_REG, chan, tx_prio); SET_REG(DMA_IN_PRI_CH0_REG, chan, rx_prio); nxsem_post(&g_dma_exc_sem); return chan; } /**************************************************************************** * Name: esp32c3_dma_setup * * Description: * Set up DMA descriptor with given parameters. * * Input Parameters: * chan - DMA channel * tx - true: TX mode; false: RX mode * dmadesc - DMA descriptor pointer * num - DMA descriptor number * pbuf - Buffer pointer * len - Buffer length by byte * * Returned Value: * Bind pbuf data bytes. * ****************************************************************************/ uint32_t esp32c3_dma_setup(int chan, bool tx, struct esp32c3_dmadesc_s *dmadesc, uint32_t num, uint8_t *pbuf, uint32_t len) { int i; uint32_t regval; uint32_t bytes = len; uint8_t *pdata = pbuf; uint32_t data_len; uint32_t buf_len; DEBUGASSERT(chan >= 0); DEBUGASSERT(dmadesc != NULL); DEBUGASSERT(num > 0); DEBUGASSERT(pbuf != NULL); DEBUGASSERT(len > 0); for (i = 0; i < num; i++) { data_len = MIN(bytes, ESP32C3_DMA_BUFLEN_MAX); /* Buffer length must be rounded to next 32-bit boundary. */ buf_len = ALIGN_UP(data_len, sizeof(uintptr_t)); dmadesc[i].ctrl = (data_len << ESP32C3_DMA_CTRL_DATALEN_S) | (buf_len << ESP32C3_DMA_CTRL_BUFLEN_S) | ESP32C3_DMA_CTRL_OWN; dmadesc[i].pbuf = pdata; dmadesc[i].next = &dmadesc[i + 1]; bytes -= data_len; if (bytes == 0) { break; } pdata += data_len; } dmadesc[i].ctrl |= ESP32C3_DMA_CTRL_EOF; dmadesc[i].next = NULL; if (tx) { /* Reset DMA TX channel FSM and FIFO pointer */ SET_BITS(DMA_OUT_CONF0_CH0_REG, chan, DMA_OUT_RST_CH0_M); CLR_BITS(DMA_OUT_CONF0_CH0_REG, chan, DMA_OUT_RST_CH0_M); /* Set the descriptor link base address for TX channel */ regval = (uint32_t)dmadesc & DMA_OUTLINK_ADDR_CH0; SET_BITS(DMA_OUT_LINK_CH0_REG, chan, regval); } else { /* Reset DMA RX channel FSM and FIFO pointer */ SET_BITS(DMA_IN_CONF0_CH0_REG, chan, DMA_IN_RST_CH0_M); CLR_BITS(DMA_IN_CONF0_CH0_REG, chan, DMA_IN_RST_CH0_M); /* Set the descriptor link base address for RX channel */ regval = (uint32_t)dmadesc & DMA_INLINK_ADDR_CH0; SET_BITS(DMA_IN_LINK_CH0_REG, chan, regval); } return len - bytes; } /**************************************************************************** * Name: esp32c3_dma_enable * * Description: * Enable DMA channel transmission. * * Input Parameters: * chan - DMA channel * tx - true: TX mode; false: RX mode * * Returned Value: * None. * ****************************************************************************/ void esp32c3_dma_enable(int chan, bool tx) { if (tx) { SET_BITS(DMA_OUT_LINK_CH0_REG, chan, DMA_OUTLINK_START_CH0_M); } else { SET_BITS(DMA_IN_LINK_CH0_REG, chan, DMA_INLINK_START_CH0_M); } } /**************************************************************************** * Name: esp32c3_dma_disable * * Description: * Disable DMA channel transmission. * * Input Parameters: * chan - DMA channel * tx - true: TX mode; false: RX mode * * Returned Value: * None. * ****************************************************************************/ void esp32c3_dma_disable(int chan, bool tx) { if (tx) { SET_BITS(DMA_OUT_LINK_CH0_REG, chan, DMA_OUTLINK_STOP_CH0_M); } else { SET_BITS(DMA_IN_LINK_CH0_REG, chan, DMA_INLINK_STOP_CH0_M); } } /**************************************************************************** * Name: esp32c3_dma_wait_idle * * Description: * Wait until transmission ends. * * Input Parameters: * chan - DMA channel * tx - true: TX mode; false: RX mode * * Returned Value: * None. * ****************************************************************************/ void esp32c3_dma_wait_idle(int chan, bool tx) { uint32_t regval; uint32_t regaddr; uint32_t waitbits; if (tx) { regaddr = DMA_OUT_LINK_CH0_REG + chan * REG_OFF; waitbits = DMA_OUTLINK_PARK_CH0; } else { regaddr = DMA_IN_LINK_CH0_REG + chan * REG_OFF; waitbits = DMA_INLINK_PARK_CH0; } do { regval = getreg32(regaddr); } while ((waitbits & regval) == 0); } /**************************************************************************** * Name: esp32c3_dma_init * * Description: * Initialize DMA driver. * * Input Parameters: * None * * Returned Value: * None. * ****************************************************************************/ void esp32c3_dma_init(void) { modifyreg32(SYSTEM_PERIP_CLK_EN1_REG, 0, SYSTEM_DMA_CLK_EN_M); modifyreg32(SYSTEM_PERIP_RST_EN1_REG, SYSTEM_DMA_RST_M, 0); modifyreg32(DMA_MISC_CONF_REG, 0, DMA_CLK_EN_M); } /**************************************************************************** * Name: esp32c3_dma_main * * Description: * ESP32-C3 DMA testing example. * ****************************************************************************/ #ifdef CONFIG_ESP32C3_DMA_M2M_TEST void esp32c3_dma_main(int argc, char *argv[]) { int chan; struct esp32c3_dmadesc_s *rx_dmadesc; struct esp32c3_dmadesc_s *tx_dmadesc; uint8_t *rxbuf; uint8_t *txbuf; bool success = true; const size_t bufsize = CONFIG_ESP32C3_DMA_M2M_TEST_BUFSIZE; #if (CONFIG_ESP32C3_DMA_M2M_TEST_BUFSIZE % ESP32C3_DMA_BUFLEN_MAX) > 0 const size_t dmadesc_num = bufsize / ESP32C3_DMA_BUFLEN_MAX + 1; #else const size_t dmadesc_num = bufsize / ESP32C3_DMA_BUFLEN_MAX; #endif syslog(LOG_INFO, "----- BEGIN TEST -----\n"); rxbuf = kmm_malloc(bufsize); if (rxbuf == NULL) { syslog(LOG_ERR, "Failed to malloc RX buffer\n"); success = false; goto test_end; } txbuf = kmm_malloc(bufsize); if (txbuf == NULL) { syslog(LOG_ERR, "Failed to malloc TX buffer\n"); kmm_free(rxbuf); success = false; goto test_end; } rx_dmadesc = kmm_malloc(sizeof(struct esp32c3_dmadesc_s) * dmadesc_num); if (rx_dmadesc == NULL) { syslog(LOG_ERR, "Failed to malloc RX DMA descriptor\n"); kmm_free(txbuf); kmm_free(rxbuf); success = false; goto test_end; } tx_dmadesc = kmm_malloc(sizeof(struct esp32c3_dmadesc_s) * dmadesc_num); if (txbuf == NULL) { syslog(LOG_ERR, "Failed to malloc TX DMA descriptor\n"); kmm_free(rx_dmadesc); kmm_free(txbuf); kmm_free(rxbuf); success = false; goto test_end; } esp32c3_dma_init(); chan = esp32c3_dma_request(ESP32C3_DMA_PERIPH_MEM, 1, 1, false); if (chan < 0) { syslog(LOG_ERR, "Request DMA channel error\n"); success = false; goto test_end_cleanup; } for (int i = 1; i <= CONFIG_ESP32C3_DMA_M2M_TEST_LOOPS; ++i) { const uint8_t watermark = i & UINT8_MAX; size_t j = 0; /* Prepare buffers for DMA transfer */ memset(rxbuf, 0, bufsize); memset(txbuf, watermark, bufsize); /* Setup DMA descriptors. * Intentionally ignore the last byte for TX. */ esp32c3_dma_setup(chan, false, rx_dmadesc, dmadesc_num, rxbuf, bufsize); esp32c3_dma_setup(chan, true, tx_dmadesc, dmadesc_num, txbuf, bufsize - 1); /* Start DMA transfer */ esp32c3_dma_enable(chan, false); esp32c3_dma_enable(chan, true); /* Wait for DMA transfer to complete */ esp32c3_dma_wait_idle(chan, true); esp32c3_dma_wait_idle(chan, false); /* Verify if last byte on RX buffer is unchanged */ if (rxbuf[bufsize - 1] != 0) { success = false; goto test_end_cleanup; } /* Verify if RX buffer contains expected values */ for (j = 0; j < bufsize - 1; ++j) { if (rxbuf[j] != watermark) { syslog(LOG_ERR, "DMA-M2M-TEST loop %d fail buf[%zu]=%" PRIu8 "\n", i, j, rxbuf[j]); success = false; goto test_end_cleanup; } } syslog(LOG_INFO, "DMA-M2M-TEST loop %d OK\n", i); } test_end_cleanup: kmm_free(tx_dmadesc); kmm_free(rx_dmadesc); kmm_free(txbuf); kmm_free(rxbuf); test_end: syslog(LOG_INFO, "----- END TEST -----\n"); syslog(LOG_INFO, "\n"); syslog(LOG_INFO, "----- RESULT: %s -----\n", success ? "SUCCESS" : "FAILED"); } #endif
0.941406
1
mono/utils/mono-semaphore.c
nataren/mono
1
1092
/* * mono-semaphore.c: mono-semaphore functions * * Author: * <NAME> <<EMAIL>> * * (C) 2010 Novell, Inc. */ #include <config.h> #include <errno.h> #include "utils/mono-semaphore.h" #ifdef HAVE_SYS_TIME_H #include <sys/time.h> #endif #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #if (defined(HAVE_SEMAPHORE_H) || defined(USE_MACH_SEMA)) /* sem_* or semaphore_* functions in use */ # ifdef USE_MACH_SEMA # define TIMESPEC mach_timespec_t # define WAIT_BLOCK(a,b) semaphore_timedwait (*(a), *(b)) # elif defined(__OpenBSD__) # define TIMESPEC struct timespec # define WAIT_BLOCK(a) sem_trywait(a) # else # define TIMESPEC struct timespec # define WAIT_BLOCK(a,b) sem_timedwait (a, b) # endif #define NSEC_PER_SEC 1000000000 int mono_sem_timedwait (MonoSemType *sem, guint32 timeout_ms, gboolean alertable) { TIMESPEC ts, copy; struct timeval t; int res = 0; #if defined(__OpenBSD__) int timeout; #endif #ifndef USE_MACH_SEMA if (timeout_ms == 0) return sem_trywait (sem); #endif if (timeout_ms == (guint32) 0xFFFFFFFF) return mono_sem_wait (sem, alertable); #ifdef USE_MACH_SEMA memset (&t, 0, sizeof (TIMESPEC)); #else gettimeofday (&t, NULL); #endif ts.tv_sec = timeout_ms / 1000 + t.tv_sec; ts.tv_nsec = (timeout_ms % 1000) * 1000000 + t.tv_usec * 1000; while (ts.tv_nsec > NSEC_PER_SEC) { ts.tv_nsec -= NSEC_PER_SEC; ts.tv_sec++; } #if defined(__OpenBSD__) timeout = ts.tv_sec; while (timeout) { if ((res = WAIT_BLOCK (sem)) == 0) return res; if (alertable) return -1; usleep (ts.tv_nsec / 1000); timeout--; } #else copy = ts; while ((res = WAIT_BLOCK (sem, &ts)) == -1 && errno == EINTR) { struct timeval current; if (alertable) return -1; #ifdef USE_MACH_SEMA memset (&current, 0, sizeof (TIMESPEC)); #else gettimeofday (&current, NULL); #endif ts = copy; ts.tv_sec -= (current.tv_sec - t.tv_sec); ts.tv_nsec -= (current.tv_usec - t.tv_usec) * 1000; if (ts.tv_nsec < 0) { if (ts.tv_sec <= 0) { ts.tv_nsec = 0; } else { ts.tv_sec--; ts.tv_nsec += NSEC_PER_SEC; } } if (ts.tv_sec < 0) { ts.tv_sec = 0; ts.tv_nsec = 0; } } #endif /* OSX might return > 0 for error */ if (res != 0) res = -1; return res; } int mono_sem_wait (MonoSemType *sem, gboolean alertable) { int res; #ifndef USE_MACH_SEMA while ((res = sem_wait (sem)) == -1 && errno == EINTR) #else while ((res = semaphore_wait (*sem)) == -1 && errno == EINTR) #endif { if (alertable) return -1; } /* OSX might return > 0 for error */ if (res != 0) res = -1; return res; } int mono_sem_post (MonoSemType *sem) { int res; #ifndef USE_MACH_SEMA while ((res = sem_post (sem)) == -1 && errno == EINTR); #else while ((res = semaphore_signal (*sem)) == -1 && errno == EINTR); /* OSX might return > 0 for error */ if (res != 0) res = -1; #endif return res; } #else /* Windows or io-layer functions in use */ int mono_sem_wait (MonoSemType *sem, gboolean alertable) { return mono_sem_timedwait (sem, INFINITE, alertable); } int mono_sem_timedwait (MonoSemType *sem, guint32 timeout_ms, gboolean alertable) { gboolean res; while ((res = WaitForSingleObjectEx (*sem, timeout_ms, alertable)) == WAIT_IO_COMPLETION) { if (alertable) { errno = EINTR; return -1; } } switch (res) { case WAIT_OBJECT_0: return 0; // WAIT_TIMEOUT and WAIT_FAILED default: return -1; } } int mono_sem_post (MonoSemType *sem) { if (!ReleaseSemaphore (*sem, 1, NULL)) return -1; return 0; } #endif
1.304688
1
src/tas.c
kulp/tenyr
17
1100
#include "os_common.h" #include "asm.h" #include "asmif.h" #include "common.h" #include "parser.h" #include "parser_global.h" #include "lexer.h" #include "param.h" #include <stdlib.h> #include <stdio.h> #include <getopt.h> #include <search.h> #include <string.h> #include <strings.h> #include <stdbool.h> static const char shortopts[] = "df:o:p:qsv" "hV"; static const struct option longopts[] = { { "disassemble" , no_argument, NULL, 'd' }, { "format" , required_argument, NULL, 'f' }, { "output" , required_argument, NULL, 'o' }, { "param" , required_argument, NULL, 'p' }, { "quiet" , no_argument, NULL, 'q' }, { "verbose" , no_argument, NULL, 'v' }, { "help" , no_argument, NULL, 'h' }, { "version" , no_argument, NULL, 'V' }, { NULL, 0, NULL, 0 }, }; static const char *version(void) { return "tas version " STR(BUILD_NAME) " built " __DATE__; } static int format_has_output(const struct format *f) { return !!f->out; } static void usage(const char *me) { char format_list[256] = { 0 }; make_format_list(format_has_output, tenyr_asm_formats_count, tenyr_asm_formats, sizeof format_list, format_list, ", "); printf("Usage: %s [ OPTIONS ] file [ file ... ] \n" "Options:\n" " -d, --disassemble disassemble (default is to assemble)\n" " -f, --format=F select output format (%s)\n" " -o, --output=X write output to filename X\n" " -p, --param=X=Y set parameter X to value Y\n" " -q, --quiet disable disassembly output comments\n" " -v, --verbose disable simplified disassembly output\n" " -h, --help display this message\n" " -V, --version print a string describing the version\n" , me, format_list); } static int process_stream(struct param_state *params, const struct format *f, FILE *infile, FILE *outfile, int flags) { int rc = 0; const struct stream in_ = stream_make_from_file(infile), *in = &in_; const struct stream out_ = stream_make_from_file(outfile), *out = &out_; int disassemble = flags & ASM_DISASSEMBLE; STREAM *stream = disassemble ? in : out; void *ud = NULL; if (f->init(stream, params, &ud)) fatal(PRINT_ERRNO, "Error during initialisation for format '%s'", f->name); if (disassemble) { // This output might be consumed by a tool that needs a line at a time os_set_buffering(outfile, _IOLBF); rc = do_disassembly(in, out, f, ud, flags); } else { rc = do_assembly(in, out, f, ud); } if (!rc && f->emit) rc |= f->emit(stream, &ud); rc |= f->fini(stream, &ud); out->op.fflush(out); return rc; } static int process_file(struct param_state *params, int flags, const struct format *fmt, const char *infname, FILE *out) { int rc = 0; FILE *in = NULL; if (!strcmp(infname, "-")) { in = stdin; } else { in = os_fopen(infname, "rb"); if (!in) fatal(PRINT_ERRNO, "Failed to open input file `%s'", infname); } // Explicitly clear errors and EOF in case we run main() twice // (emscripten) clearerr(in); rc = process_stream(params, fmt, in, out, flags); fclose(in); return rc; } int main(int argc, char *argv[]) { int rc = 0; volatile int disassemble = 0; volatile int flags = 0; char * volatile outfname = NULL; FILE * volatile out = stdout; struct param_state * volatile params = NULL; param_init((struct param_state **)&params); if ((rc = setjmp(errbuf))) { if (rc & DISPLAY_USAGE) usage(argv[0]); // We may have created an output file already, but we do not try to // remove it, because doing so by filename would be a race condition. // The most important reason to remove the output file is to avoid // tricking a build system into thinking that a failed build created a // good output file; with GNU Make this can be avoided by using // .DELETE_ON_ERROR, and other build systems have similar features. rc = EXIT_FAILURE; goto cleanup; } const struct format *fmt = &tenyr_asm_formats[0]; // Explicitly reset optind for cases where main() is called more than once // (emscripten) optind = 0; int ch; while ((ch = getopt_long(argc, argv, shortopts, longopts, NULL)) != -1) { switch (ch) { case 'd': disassemble = 1; break; case 'f': if (find_format(optarg, &fmt)) { usage(argv[0]); exit(EXIT_FAILURE); } break; case 'o': outfname = optarg; break; case 'p': param_add(params, optarg); break; case 'q': flags |= ASM_QUIET; break; case 'v': flags |= ASM_VERBOSE; break; case 'V': puts(version()); rc = EXIT_SUCCESS; goto cleanup; case 'h': usage(argv[0]); rc = EXIT_SUCCESS; goto cleanup; default: usage(argv[0]); rc = EXIT_FAILURE; goto cleanup; } } if (optind >= argc) fatal(DISPLAY_USAGE, "No input files specified on the command line"); param_set(params, "assembling", &"1\0""0\0"[disassemble], 1, false, false); { int setting = 0; int clearing = 0; // Return values from param_get_int are not significant in this case, // since we have correct defaults. param_get_int(params, "tas.flags.set" , &setting ); param_get_int(params, "tas.flags.clear", &clearing); flags = (flags | setting) & ~clearing; } os_preamble(); // TODO don't open output until input has been validated if (outfname) out = os_fopen(outfname, "wb"); if (!out) fatal(PRINT_ERRNO, "Failed to open output file `%s'", outfname ? outfname : "<stdout>"); if (disassemble) flags |= ASM_DISASSEMBLE; for (int i = optind; i < argc; i++) { rc = process_file(params, flags, fmt, argv[i], out); // We may have created an output file already, but we do not try to // remove it, because doing so by filename would be a race condition. // The most important reason to remove the output file is to avoid // tricking a build system into thinking that a failed build created a // good output file; with GNU Make this can be avoided by using // .DELETE_ON_ERROR, and other build systems have similar features. } fclose(out); out = NULL; cleanup: param_destroy(params); return rc; } /* vi: set ts=4 sw=4 et: */
1.460938
1
export/ClassFactory.h
jonntd/field3d
0
1108
//----------------------------------------------------------------------------// /* * Copyright (c) 2009 Sony Pictures Imageworks Inc * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. Neither the name of Sony Pictures Imageworks nor the * names of its contributors may be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ //----------------------------------------------------------------------------// /*! \file ClassFactory.h \brief Contains the ClassFactory class for registering Field3D classes. */ //----------------------------------------------------------------------------// #ifndef _INCLUDED_Field3D_ClassFactory_H_ #define _INCLUDED_Field3D_ClassFactory_H_ #include <map> #include <vector> #include "Field.h" #include "FieldIO.h" #include "FieldMappingIO.h" //----------------------------------------------------------------------------// #include "ns.h" FIELD3D_NAMESPACE_OPEN //----------------------------------------------------------------------------// // ClassFactory //----------------------------------------------------------------------------// /*! \class ClassFactory \ingroup field_int */ //----------------------------------------------------------------------------// class ClassFactory { public: // Typedefs ------------------------------------------------------------------ typedef FieldRes::Ptr (*CreateFieldFnPtr) (); typedef FieldIO::Ptr (*CreateFieldIOFnPtr) (); typedef FieldMapping::Ptr (*CreateFieldMappingFnPtr) (); typedef FieldMappingIO::Ptr (*CreateFieldMappingIOFnPtr) (); // Ctors, dtor --------------------------------------------------------------- //! Standard constructor ClassFactory(); // Main methods -------------------------------------------------------------- //! \name Field class //! \{ //! Registers a class with the class pool. //! \param createFunc Pointer to creation function void registerField(CreateFieldFnPtr createFunc); //! Instances an object by name FieldRes::Ptr createField(const std::string &className) const; //! Registers an IO class with the class pool. //! \param createFunc Pointer to creation function void registerFieldIO(CreateFieldIOFnPtr createFunc); //! Instances an IO object by name FieldIO::Ptr createFieldIO(const std::string &className) const; //! } //! \name FieldMapping class //! \{ //! Registers a class with the class pool. //! \param createFunc Pointer to creation function void registerFieldMapping(CreateFieldMappingFnPtr createFunc); //! Instances an object by name FieldMapping::Ptr createFieldMapping(const std::string &className) const; //! Registers an IO class with the class pool. //! \param createFunc Pointer to creation function void registerFieldMappingIO(CreateFieldMappingIOFnPtr createFunc); //! Instances an IO object by name FieldMappingIO::Ptr createFieldMappingIO(const std::string &className) const; //! } //! Access point for the singleton instance. static ClassFactory& singleton(); private: // Typedefs ------------------------------------------------------------------ typedef std::vector<std::string> NameVec; typedef std::map<std::string, CreateFieldFnPtr> FieldFuncMap; typedef std::map<std::string, CreateFieldIOFnPtr> FieldIOFuncMap; typedef std::map<std::string, CreateFieldMappingFnPtr> FieldMappingFuncMap; typedef std::map<std::string, CreateFieldMappingIOFnPtr> FieldMappingIOFuncMap; // Data members -------------------------------------------------------------- //! Map of create functions for Fields. The key is the class name. FieldFuncMap m_fields; //! NameVec m_fieldNames; //! Map of create functions for FieldIO classes. The key is the class name. FieldIOFuncMap m_fieldIOs; //! NameVec m_fieldIONames; //! Map of create functions for FieldMappings. The key is the class name. FieldMappingFuncMap m_mappings; //! NameVec m_fieldMappingNames; //! Map of create functions for FieldMapping IO classes. The key is the class name. FieldMappingIOFuncMap m_mappingIOs; //! NameVec m_fieldMappingIONames; //! Pointer to static instance static ClassFactory *ms_instance; }; //----------------------------------------------------------------------------// FIELD3D_NAMESPACE_HEADER_CLOSE //----------------------------------------------------------------------------// #endif // Include guard
1.148438
1
Include/my.h
Yassineelg/MiniShell
0
1116
/* ** EPITECH PROJECT, 2019 ** my.h ** File description: ** all prototypes. */ #include <stdio.h> #include <stdarg.h> #include <unistd.h> int flag_searcher(char *flags, char c); void my_printf(char *str, ...); int my_getnbr(char const *str); void my_put_nbr(int nb); void my_putchar(char c); void my_putstr(char const *str); char *my_revstr(char *str); char *my_strcat(char *dest, char const *src); char *my_strcpy(char *dest, char const *src); int my_strlen(char const *str); char *my_strncat(char *dest, char const *src, int nb); char *my_strncpy(char *dest, char const *src, int n); void my_swap(int *a, int *b); void get_modulo_s(va_list *list, char *str, int *i); void get_modulo_c(va_list *list, char *str, int *i); void get_modulo_d(va_list *list, char *str, int *i); void get_modulo_o(va_list *list, char *str, int *i); void get_modulo_x(va_list *list, char *str, int *i); void get_modulo_u(va_list *list, char *str, int *i); void get_modulo_p(va_list *list, char *str, int *i); void get_modulo_n(va_list *list, char *str, int *i); void get_modulo_b(va_list *list, char *str, int *i); void get_modulo_gs(va_list *list, char *str, int *i); void get_modulo_gx(va_list *list, char *str, int *i); void get_modulo_modulo(va_list *list, char *str, int *i); void no_flag(va_list *list, char *str, int *i); void convert_dec_hex(unsigned int nb); void convert_dec_oct(unsigned int nb); void convert_dec_octs(unsigned int nb); void my_put_unsignedint(unsigned int nb); int my_strcmp(char *str1, char *str2); int my_strncmp(char *str1, char *str2, int nb); char **my_str_to_word_array(char *str, char c); char **my_tabcpy(char **dest, char **src);
1.148438
1
Engine/Source/ThirdParty/MCPP/mcpp-2.7.2/test-l/nest111.h
windystrife/UnrealEngine_NVIDIAGameWork
34
1124
/* nest111.h */ #include "nest112.h"
-0.214844
0
remoting/host/win/elevated_native_messaging_host.h
zealoussnow/chromium
76
1132
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef REMOTING_HOST_WIN_ELEVATED_NATIVE_MESSAGING_HOST_H_ #define REMOTING_HOST_WIN_ELEVATED_NATIVE_MESSAGING_HOST_H_ #include <cstdint> #include <memory> #include "base/files/file_path.h" #include "base/macros.h" #include "base/threading/thread_checker.h" #include "base/time/time.h" #include "base/timer/timer.h" #include "extensions/browser/api/messaging/native_message_host.h" #include "extensions/browser/api/messaging/native_messaging_channel.h" #include "remoting/host/win/launch_native_messaging_host_process.h" namespace base { class Value; } // namespace base namespace remoting { // Helper class which manages the creation and lifetime of an elevated native // messaging host process. class ElevatedNativeMessagingHost : public extensions::NativeMessagingChannel::EventHandler { public: ElevatedNativeMessagingHost(const base::FilePath& binary_path, intptr_t parent_window_handle, bool elevate_process, base::TimeDelta host_timeout, extensions::NativeMessageHost::Client* client); ElevatedNativeMessagingHost(const ElevatedNativeMessagingHost&) = delete; ElevatedNativeMessagingHost& operator=(const ElevatedNativeMessagingHost&) = delete; ~ElevatedNativeMessagingHost() override; // extensions::NativeMessagingChannel::EventHandle implementation. void OnMessage(std::unique_ptr<base::Value> message) override; void OnDisconnect() override; // Create and connect to an elevated host process if necessary. // |elevated_channel_| will contain the native messaging channel to the // elevated host if the function succeeds. ProcessLaunchResult EnsureElevatedHostCreated(); // Send |message| to the elevated host. void SendMessage(std::unique_ptr<base::Value> message); private: // Disconnect and shut down the elevated host. void DisconnectHost(); // Path to the binary to use for the elevated host process. base::FilePath host_binary_path_; // Handle of the parent window. intptr_t parent_window_handle_; // Indicates whether the launched process should be elevated when lauinched. // Note: Binaries with uiaccess run at a higher UIPI level than the launching // process so they still need to be launched and controlled by this class but // do not require traditional elevation to function. bool elevate_host_process_; // Specifies the amount of time to allow the elevated host to run. base::TimeDelta host_process_timeout_; // EventHandler of the parent process. extensions::NativeMessageHost::Client* client_; // Native messaging channel used to communicate with the elevated host. std::unique_ptr<extensions::NativeMessagingChannel> elevated_channel_; // Timer to control the lifetime of the elevated host. base::OneShotTimer elevated_host_timer_; base::ThreadChecker thread_checker_; }; } // namespace remoting #endif // REMOTING_HOST_WIN_ELEVATED_NATIVE_MESSAGING_HOST_H_
1.117188
1
System/Library/PrivateFrameworks/UIKitCore.framework/UIStatusBarLockItemView.h
lechium/iOS1351Headers
2
1140
/* * This header is generated by classdump-dyld 1.5 * on Friday, April 30, 2021 at 11:35:10 AM Mountain Standard Time * Operating System: Version 13.5.1 (Build 17F80) * Image Source: /System/Library/PrivateFrameworks/UIKitCore.framework/UIKitCore * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>. Updated by <NAME>. */ #import <UIKitCore/UIKitCore-Structs.h> #import <UIKitCore/UIStatusBarItemView.h> #import <libobjc.A.dylib/CAAnimationDelegate.h> @class UIView, _UIStatusBarLockItemPadlockView, _UIExpandingGlyphsView, NSString; @interface UIStatusBarLockItemView : UIStatusBarItemView <CAAnimationDelegate> { BOOL _alongsideViewIsBecomingVisible; int _animationCount; UIView* _viewToAnimateAlongside; _UIStatusBarLockItemPadlockView* _padlockView; UIView* _textClippingView; _UIExpandingGlyphsView* _textView; double _padlockViewCenterOffsetFromForegroundViewCenter; UIView* _timeItemSnapshot; double _timeItemSnapshotCenterOffsetFromForegroundViewCenter; double _widthNeededDuringAnimation; double _widthNeededForFinalState; /*^block*/id _animationCompletionBlock; } @property (nonatomic,retain) _UIStatusBarLockItemPadlockView * padlockView; //@synthesize padlockView=_padlockView - In the implementation block @property (nonatomic,retain) UIView * textClippingView; //@synthesize textClippingView=_textClippingView - In the implementation block @property (nonatomic,retain) _UIExpandingGlyphsView * textView; //@synthesize textView=_textView - In the implementation block @property (assign,nonatomic) double padlockViewCenterOffsetFromForegroundViewCenter; //@synthesize padlockViewCenterOffsetFromForegroundViewCenter=_padlockViewCenterOffsetFromForegroundViewCenter - In the implementation block @property (nonatomic,retain) UIView * timeItemSnapshot; //@synthesize timeItemSnapshot=_timeItemSnapshot - In the implementation block @property (assign,nonatomic) double timeItemSnapshotCenterOffsetFromForegroundViewCenter; //@synthesize timeItemSnapshotCenterOffsetFromForegroundViewCenter=_timeItemSnapshotCenterOffsetFromForegroundViewCenter - In the implementation block @property (assign,nonatomic) double widthNeededDuringAnimation; //@synthesize widthNeededDuringAnimation=_widthNeededDuringAnimation - In the implementation block @property (assign,nonatomic) double widthNeededForFinalState; //@synthesize widthNeededForFinalState=_widthNeededForFinalState - In the implementation block @property (assign,nonatomic) int animationCount; //@synthesize animationCount=_animationCount - In the implementation block @property (nonatomic,copy) id animationCompletionBlock; //@synthesize animationCompletionBlock=_animationCompletionBlock - In the implementation block @property (assign,nonatomic,__weak) UIView * viewToAnimateAlongside; //@synthesize viewToAnimateAlongside=_viewToAnimateAlongside - In the implementation block @property (assign,nonatomic) BOOL alongsideViewIsBecomingVisible; //@synthesize alongsideViewIsBecomingVisible=_alongsideViewIsBecomingVisible - In the implementation block @property (readonly) unsigned long long hash; @property (readonly) Class superclass; @property (copy,readonly) NSString * description; @property (copy,readonly) NSString * debugDescription; +(double)lockSlideAnimationDuration; -(_UIExpandingGlyphsView *)textView; -(void)setTextView:(_UIExpandingGlyphsView *)arg1 ; -(BOOL)_isAnimating; -(void)animationDidStop:(id)arg1 finished:(BOOL)arg2 ; -(id)accessibilityHUDRepresentation; -(int)animationCount; -(void)setAnimationCount:(int)arg1 ; -(BOOL)updateForNewData:(id)arg1 actions:(int)arg2 ; -(double)updateContentsAndWidth; -(void)setVisible:(BOOL)arg1 frame:(CGRect)arg2 duration:(double)arg3 ; -(void)jiggleCompletionBlock:(/*^block*/id)arg1 ; -(void)_beginAnimation; -(_UIStatusBarLockItemPadlockView *)padlockView; -(UIView *)timeItemSnapshot; -(void)setTimeItemSnapshot:(UIView *)arg1 ; -(void)_endAnimation; -(BOOL)isExclusive; -(void)animateUnlockForegroundView:(id)arg1 timeItemSnapshot:(id)arg2 completionBlock:(/*^block*/id)arg3 ; -(UIView *)viewToAnimateAlongside; -(void)setViewToAnimateAlongside:(UIView *)arg1 ; -(BOOL)alongsideViewIsBecomingVisible; -(void)setAlongsideViewIsBecomingVisible:(BOOL)arg1 ; -(void)setPadlockView:(_UIStatusBarLockItemPadlockView *)arg1 ; -(UIView *)textClippingView; -(void)setTextClippingView:(UIView *)arg1 ; -(double)padlockViewCenterOffsetFromForegroundViewCenter; -(void)setPadlockViewCenterOffsetFromForegroundViewCenter:(double)arg1 ; -(double)timeItemSnapshotCenterOffsetFromForegroundViewCenter; -(void)setTimeItemSnapshotCenterOffsetFromForegroundViewCenter:(double)arg1 ; -(double)widthNeededDuringAnimation; -(void)setWidthNeededDuringAnimation:(double)arg1 ; -(double)widthNeededForFinalState; -(void)setWidthNeededForFinalState:(double)arg1 ; -(id)animationCompletionBlock; -(void)setAnimationCompletionBlock:(id)arg1 ; @end
0.621094
1
EZMP/Utils.h
triagon-games/ezMP
0
1148
#pragma once #include "pch.h" #include <string> #include <array> #include <iostream> #include "CommonDefinitions.h" #include <WinSock2.h> #include <winerror.h> #include <ws2tcpip.h> #include <vector> #pragma comment (lib, "Ws2_32.lib") #pragma comment (lib, "Mswsock.lib") #pragma comment (lib, "AdvApi32.lib") class Utils { public: static std::string exec(const char* cmd); static sockaddr_in MakeAddress(std::string IP, uint16_t Port); static std::string ByteAddrToString(uint8_t* addr); struct PortTranslation { PortTranslation() { OutboundLocal = 0; OutboundPublic = 0; } PortTranslation(uint16_t _local, uint16_t _public) { OutboundLocal = _local; OutboundPublic = _public; } uint16_t OutboundLocal; uint16_t OutboundPublic; }; struct Endpoint { Endpoint() { IP = ""; privateKey = 0; portPair = Utils::PortTranslation(); } Endpoint(std::string addr, uint64_t key, Utils::PortTranslation pt) { IP = addr; privateKey = key; portPair = pt; } std::string IP; uint64_t privateKey; Utils::PortTranslation portPair; }; static PortTranslation getPortTranslation(uint16_t Port, std::string stunServer); static void getPublicIPAddress(std::string stunServer, uint8_t* ipAddr); static void getIPFromString(std::string ip, uint8_t* ipAddr); static std::string getStringFromIP(uint8_t* ip); static std::string stringFromBytes(uint8_t* bytes, uint32_t size); static void bytesFromString(std::string string, uint32_t* p_size, uint8_t* bytes); static std::vector<uint8_t> vectorBytesFromString(std::string string); static std::string stringFromVectorBytes(std::vector<uint8_t> bytes); };
1.242188
1
src/kits/debugger/value/type_handlers/BListTypeHandler.h
Kirishikesan/haiku
1,338
1156
/* * Copyright 2012-2018, <NAME>, <EMAIL>. * Distributed under the terms of the MIT License. */ #ifndef BLIST_TYPE_HANDLER_H #define BLIST_TYPE_HANDLER_H #include "TypeHandler.h" class BListTypeHandler : public TypeHandler { public: virtual ~BListTypeHandler(); virtual const char* Name() const; virtual float SupportsType(Type* type) const; virtual status_t CreateValueNode(ValueNodeChild* nodeChild, Type* type, ValueNode*& _node); }; #endif // BLIST_TYPE_HANDLER_H
1.03125
1
CodeBlocks1908/share/CodeBlocks/templates/wizard/arm/files/lpd-lh7a404/h/lh7a404.h
BenjaminRenz/FirmwareTY71M
9
1164
/*==================================================================== * Project: Board Support Package (BSP) * Developed using: * Function: Standard definitions for Sharp LH7A404 (ARM922T) * * Copyright HighTec EDV-Systeme GmbH 1982-2006 *====================================================================*/ #ifndef __LH7A404_H__ #define __LH7A404_H__ /* general register definition macro */ #define __REG32(x) ((volatile unsigned int *)(x)) #define __REG16(x) ((volatile unsigned short *)(x)) #define __REG8(x) ((volatile unsigned char *)(x)) /*****************/ /* Memory layout */ /*****************/ #define LH7A404_CS0_BASE (0x00000000) /* SMC CS0 */ #define LH7A404_CS1_BASE (0x10000000) /* SMC CS1 */ #define LH7A404_CS2_BASE (0x20000000) /* SMC CS2 */ #define LH7A404_CS3_BASE (0x30000000) /* SMC CS3 */ #define LH7A404_PCMCIA0_BASE (0x40000000) /* PC Card/CF Slot 0 */ #define LH7A404_PCMCIA1_BASE (0x50000000) /* PC Card/CF Slot 1 */ #define LH7A404_CS6_BASE (0x60000000) /* SMC CS6 */ #define LH7A404_CS7_BASE (0x70000000) /* SMC CS7 */ #define LH7A404_APB_BASE (0x80000000) /* Advanced Peripheral Bus (APB) */ #define LH7A404_AHB_BASE (0x80002000) /* Advanced High-Performance Bus (AHB) */ #define LH7A404_ESRAM_BASE (0xB0000000) /* Embedded SRAM */ #define LH7A404_SDCSC0_BASE (0xC0000000) /* SDRAM CS0 */ #define LH7A404_SDCSC1_BASE (0xD0000000) /* SDRAM CS1 */ #define LH7A404_SDCSC2_BASE (0xE0000000) /* SDRAM CS2 */ #define LH7A404_SDCSC3_BASE (0xF0000000) /* SDRAM CS3 */ /*************************/ /* Module base addresses */ /*************************/ #define APB_BASE LH7A404_APB_BASE #define LH7A404_AC97_BASE (APB_BASE + 0x0000) /* AC97 Controller */ #define LH7A404_MMC_BASE (APB_BASE + 0x0100) /* Multimedia Card Controller */ #define LH7A404_USB_BASE (APB_BASE + 0x0200) /* USB Client */ #define LH7A404_SCI_BASE (APB_BASE + 0x0300) /* Smart Card Interface */ #define LH7A404_CSC_BASE (APB_BASE + 0x0400) /* Clock/State Controller */ #define LH7A404_UART1_BASE (APB_BASE + 0x0600) /* UART1 Controller */ #define LH7A404_SIR_BASE (APB_BASE + 0x0600) /* IR Controller, same as UART1 */ #define LH7A404_UART2_BASE (APB_BASE + 0x0700) /* UART2 Controller */ #define LH7A404_UART3_BASE (APB_BASE + 0x0800) /* UART3 Controller */ #define LH7A404_DCDC_BASE (APB_BASE + 0x0900) /* DC to DC Controller */ #define LH7A404_ACI_BASE (APB_BASE + 0x0A00) /* Audio Codec Interface */ #define LH7A404_SSP_BASE (APB_BASE + 0x0B00) /* Synchronous Serial Port */ #define LH7A404_TIMER_BASE (APB_BASE + 0x0C00) /* Timer Controller */ #define LH7A404_RTC_BASE (APB_BASE + 0x0D00) /* Real-time Clock */ #define LH7A404_GPIO_BASE (APB_BASE + 0x0E00) /* General Purpose IO */ #define LH7A404_BMI_BASE (APB_BASE + 0x0F00) /* Battery Monitor Interface */ #define LH7A404_ALI_BASE (APB_BASE + 0x1000) /* Advanced LCD Interface */ #define LH7A404_PWM_BASE (APB_BASE + 0x1100) /* Pulse Width Modulator */ #define LH7A404_KMI_BASE (APB_BASE + 0x1200) /* Keyboard and Mouse Interface */ #define LH7A404_ADC_BASE (APB_BASE + 0x1300) /* Analog-to-Digital Converter */ #define LH7A404_WDT_BASE (APB_BASE + 0x1400) /* Watchdog Timer */ #define AHB_BASE LH7A404_AHB_BASE #define LH7A404_SMC_BASE (AHB_BASE + 0x0000) /* Static Memory Controller */ #define LH7A404_SDMC_BASE (AHB_BASE + 0x0400) /* Synchronous Dynamic Memory Controller */ #define LH7A404_DMAC_BASE (AHB_BASE + 0x0800) /* DMA Controller */ #define LH7A404_CLCDC_BASE (AHB_BASE + 0x1000) /* Color LCD Controller */ #define LH7A404_VIC1_BASE (AHB_BASE + 0x6000) /* Vectored Interrupt Controller 1 */ #define LH7A404_USBH_BASE (AHB_BASE + 0x7000) /* USB OHCI host controller */ #define LH7A404_VIC2_BASE (AHB_BASE + 0x8000) /* Vectored Interrupt Controller 2 */ /**************************************/ /* Static Memory Controller registers */ /**************************************/ #define SMC_BASE LH7A404_SMC_BASE #define SMC_BCR0 __REG32(SMC_BASE + 0x00) /* Bank 0 Configuration */ #define SMC_BCR1 __REG32(SMC_BASE + 0x04) /* Bank 1 Configuration */ #define SMC_BCR2 __REG32(SMC_BASE + 0x08) /* Bank 2 Configuration */ #define SMC_BCR3 __REG32(SMC_BASE + 0x0C) /* Bank 3 Configuration */ #define SMC_BCR6 __REG32(SMC_BASE + 0x18) /* Bank 6 Configuration */ #define SMC_BCR7 __REG32(SMC_BASE + 0x1C) /* Bank 7 Configuration */ #define SMC_PC1ATTRIB __REG32(SMC_BASE + 0x20) /* PC Card 1 Attribute Space Config. */ #define SMC_PC1COM __REG32(SMC_BASE + 0x24) /* PC Card 1 Common Memory Space Config. */ #define SMC_PC1IO __REG32(SMC_BASE + 0x28) /* PC Card 1 I/O Space Configuration */ #define SMC_PC2ATTRIB __REG32(SMC_BASE + 0x30) /* PC Card 2 Attribute Space Config. */ #define SMC_PC2COM __REG32(SMC_BASE + 0x34) /* PC Card 2 Common Memory Space Config. */ #define SMC_PC2IO __REG32(SMC_BASE + 0x38) /* PC Card 2 I/O Space Configuration */ #define SMC_PCMCIACON __REG32(SMC_BASE + 0x40) /* PCMCIA Control */ /* bitfields in BCRx */ #define BCR_IDCY_SHFT 0 #define BCR_IDCY_MSK (0x0F << 0) /* Idle Cycle */ #define BCR_WST1_SHFT 5 #define BCR_WST1_MSK (0x1F << 5) /* Wait State 1 */ #define BCR_RBLE (1 << 10) /* Read Byte Lane Enable */ #define BCR_WST2_SHFT 11 #define BCR_WST2_MSK (0x1F << 11) /* Wait State 2 */ #define BCR_WPERR (1 << 25) /* Write Protect Error */ #define BCR_WP (1 << 26) /* Write Protect */ #define BCR_PME (1 << 27) /* Page Mode Enable */ #define BCR_MW_SHFT 28 #define BCR_MW_MSK (0x03 << 28) /* Memory Width */ #define BCR_MW_8 (0x00 << 28) #define BCR_MW_16 (0x01 << 28) #define BCR_MW_32 (0x02 << 28) /* bitfields in PCxATTRIB */ #define PCATTR_PA_SHFT 0 #define PCATTR_PA_MSK (0xFF << 0) /* Pre-Charge Delay Time for Attribute Space */ #define PCATTR_HT_SHFT 8 #define PCATTR_HT_MSK (0x0F << 8) /* Hold Time */ #define PCATTR_AA_SHFT 16 #define PCATTR_AA_MSK (0xFF << 16) /* Access Time for Attribute Space */ #define PCATTR_WA_16 (1 << 31) /* Width of Attribute Address Space (16 bit) */ #define PCATTR_WA_8 (0 << 31) /* Width of Attribute Address Space (8 bit) */ /* bitfields in PCxCOM */ #define PCCOM_PC_SHFT 0 #define PCCOM_PC_MSK (0xFF << 0) /* Pre-Charge Delay Time for Common Memory Space */ #define PCCOM_HT_SHFT 8 #define PCCOM_HT_MSK (0x0F << 8) /* Hold Time */ #define PCCOM_AC_SHFT 16 #define PCCOM_AC_MSK (0xFF << 16) /* Access Time for Common Memory Space */ #define PCCOM_WC_16 (1 << 31) /* Width of Common Memory Address Space (16 bit) */ #define PCCOM_WC_8 (0 << 31) /* Width of Common Memory Address Space (8 bit) */ /* bitfields in PCxIO */ #define PCIO_PI_SHFT 0 #define PCIO_PI_MSK (0xFF << 0) /* Pre-Charge Delay Time for I/O Space */ #define PCIO_HT_SHFT 8 #define PCIO_HT_MSK (0x0F << 8) /* Hold Time */ #define PCIO_AI_SHFT 16 #define PCIO_AI_MSK (0xFF << 16) /* Access Time for I/O Space */ #define PCIO_WI_16 (1 << 31) /* Width of I/O Address Space (16 bit) */ #define PCIO_WI_8 (0 << 31) /* Width of I/O Address Space (8 bit) */ /* bits in PCMCIACON register */ #define PCMCIA_PC12EN (0x03 << 0) /* PC Card 1 and 2 Enable */ #define PCMCIA_PC1RST (1 << 2) /* PC Card 1 Reset */ #define PCMCIA_PC2RST (1 << 3) /* PC Card 2 Reset */ #define PCMCIA_WEN1 (1 << 4) /* Wait State Enable for Card 1 */ #define PCMCIA_WEN2 (1 << 5) /* Wait State Enable for Card 2 */ #define PCMCIA_MPREG (1 << 9) /* Manual Control of PCREG */ /***************************************************/ /* Synchronous Dynamic Memory Controller registers */ /***************************************************/ #define SDMC_BASE LH7A404_SDMC_BASE #define SDMC_GBLCNFG __REG32(SDMC_BASE + 0x04) /* Global Configuration */ #define SDMC_RFSHTMR __REG32(SDMC_BASE + 0x08) /* Refresh Timer */ #define SDMC_BOOTSTAT __REG32(SDMC_BASE + 0x0C) /* Boot Status */ #define SDMC_SDCSC0 __REG32(SDMC_BASE + 0x10) /* Synchr. Domain Chip Select Config. 0 */ #define SDMC_SDCSC1 __REG32(SDMC_BASE + 0x14) /* Synchr. Domain Chip Select Config. 1 */ #define SDMC_SDCSC2 __REG32(SDMC_BASE + 0x18) /* Synchr. Domain Chip Select Config. 2 */ #define SDMC_SDCSC3 __REG32(SDMC_BASE + 0x1C) /* Synchr. Domain Chip Select Config. 3 */ /* bits in GBLCNFG register */ #define GBLCNFG_INIT (1 << 0) /* Initialize */ #define GBLCNFG_MRS (1 << 1) /* Mode Register in Synchronous device */ #define GBLCNFG_SMEMBS (1 << 5) /* Synchronous Memory Busy State */ #define GBLCNFG_LCR (1 << 6) /* Load Command Register */ #define GBLCNFG_CKSD (1 << 30) /* Clock Shutdown */ #define GBLCNFG_CKE (1 << 31) /* Clock Enable */ /* bits in BOOTSTAT register */ #define BOOTSTAT_WIDTH (0x03 << 0) /* Boot Memory Width */ #define BOOTSTAT_MEDCHG (1 << 2) /* Media Change [1 = Synchr., 0 = Asynchr. ROM] */ /* bits in SDMC_SDCSCx register */ #define SDCSC_EBW (1 << 2) /* External Bus Width [1 = 16, 0 = 32 bit] */ #define SDCSC_BANKCOUNT (1 << 3) /* Bank Count [0 = 2 , 1 = 4 bank devices] */ #define SDCSC_SROM512 (1 << 4) /* SROM Page Depth 512 */ #define SDCSC_SROMLL (1 << 5) /* SROM Lookalike */ #define SDCSC_2KPAGE (1 << 6) /* 2K Page Depth */ #define SDCSC_CASLAT (0x07 << 16) /* Column Address Strobe Latency */ #define SDCSC_WBL (1 << 19) /* Write Burst Length */ #define SDCSC_RASTOCAS (0x03 << 20) /* Row Address Strobe To Column Address Strobe */ #define SDCSC_APEN (1 << 24) /* Auto Precharge Enable */ /***********************************/ /* Clock/State Controller register */ /***********************************/ #define CSC_BASE LH7A404_CSC_BASE #define CSC_PWRSR __REG32(CSC_BASE + 0x00) /* Power Reset Register */ #define CSC_PWRCNT __REG32(CSC_BASE + 0x04) /* Power Control Register */ #define CSC_HALT __REG32(CSC_BASE + 0x08) /* Read to enter Halt */ #define CSC_STBY __REG32(CSC_BASE + 0x0C) /* Read to enter Standby */ #define CSC_BLEOI __REG32(CSC_BASE + 0x10) /* Battery Low End Of Interrupt reg */ #define CSC_MCEOI __REG32(CSC_BASE + 0x14) /* Media Changed End Of Interrupt reg */ #define CSC_TEOI __REG32(CSC_BASE + 0x18) /* Tick End Of Interrupt register */ #define CSC_STFCLR __REG32(CSC_BASE + 0x1C) /* STatus Flag CLeaR register */ #define CSC_CLKSET __REG32(CSC_BASE + 0x20) /* Clock Set register */ #define CSC_SCRREG0 __REG32(CSC_BASE + 0x40) /* General purpose storage register 0 */ #define CSC_SCRREG1 __REG32(CSC_BASE + 0x44) /* General purpose storage register 1 */ #define CSC_USBDRESET __REG32(CSC_BASE + 0x4C) /* USB Device Reset register */ #define CSC_BMAR __REG32(CSC_BASE + 0x54) /* Bus Master Arbitration Register */ #define CSC_BOOTCLR __REG32(CSC_BASE + 0x58) /* Boot ROM Clear Register */ /* Bits in Power Reset Register */ #define CSC_PWRSR_RTCDIV_MSK 0x0000003F /* Real Time Clock Divisor */ #define CSC_PWRSR_MCDR (1 << 6) /* Media Change Direct Read */ #define CSC_PWRSR_DCDET (1 << 7) /* Direct Current Detect */ #define CSC_PWRSR_WUDR (1 << 8) /* Wakeup Direct */ #define CSC_PWRSR_WUON (1 << 9) /* Wake Up On */ #define CSC_PWRSR_NBFLG (1 << 10) /* New Battery Status Flag */ #define CSC_PWRSR_RSTFLG (1 << 11) /* User Reset Status Flag */ #define CSC_PWRSR_PFFLG (1 << 12) /* Power Fail Status Flag */ #define CSC_PWRSR_CLDFLG (1 << 13) /* Cold Start Status Flag */ #define CSC_PWRSR_LCKFLG (1 << 14) /* PLL2 Lock Flag */ #define CSC_PWRSR_WDTFLG (1 << 15) /* Watchdog Flag */ #define CSC_PWRSR_CHIPID_MSK (0xFF << 16) /* Chip Identification */ #define CSC_PWRSR_CHIPMAN_MSK (0xFF << 24) /* Chip Manufacturer ID [0x53 = 'S'] */ /* Bits in Power Control Register */ #define CSC_PWRCNT_WDTSEL (1 << 0) /* Watchdog Timer Reset Select */ #define CSC_PWRCNT_WAKEDIS (1 << 1) /* Wakeup Disable */ #define CSC_PWRCNT_PGMCLK_MSK (0xFF << 8) /* Program Clock Divisor */ #define CSC_PWRCNT_DMAM2PCH1 (1 << 16) /* DMA M2P Clock Enable Channel 1 */ #define CSC_PWRCNT_DMAM2PCH0 (1 << 17) /* DMA M2P Clock Enable Channel 0 */ #define CSC_PWRCNT_DMAM2PCH3 (1 << 18) /* DMA M2P Clock Enable Channel 3 */ #define CSC_PWRCNT_DMAM2PCH2 (1 << 19) /* DMA M2P Clock Enable Channel 2 */ #define CSC_PWRCNT_DMAM2PCH5 (1 << 20) /* DMA M2P Clock Enable Channel 5 */ #define CSC_PWRCNT_DMAM2PCH4 (1 << 21) /* DMA M2P Clock Enable Channel 4 */ #define CSC_PWRCNT_DMAM2PCH7 (1 << 22) /* DMA M2P Clock Enable Channel 7 */ #define CSC_PWRCNT_DMAM2PCH6 (1 << 23) /* DMA M2P Clock Enable Channel 6 */ #define CSC_PWRCNT_DMAM2PCH9 (1 << 24) /* DMA M2P Clock Enable Channel 9 */ #define CSC_PWRCNT_DMAM2PCH8 (1 << 25) /* DMA M2P Clock Enable Channel 8 */ #define CSC_PWRCNT_DMAM2MCH0 (1 << 26) /* DMA M2M Clock Enable Channel 0 */ #define CSC_PWRCNT_DMAM2MCH1 (1 << 27) /* DMA M2M Clock Enable Channel 1 */ #define CSC_PWRCNT_USHEN (1 << 28) /* USB Host Clock Enable */ #define CSC_PWRCNT_UARTBAUD (1 << 29) /* UART Baud Clock Source */ /* Bits in CLKSET Register */ #define CSC_CLKSET_HCLKDIV_SHFT 0 #define CSC_CLKSET_HCLKDIV_MSK (0x03 << 0) /* HCLK Divisor */ #define CSC_CLKSET_PREDIV_SHFT 2 #define CSC_CLKSET_PREDIV_MSK (0x1F << 2) /* Predivisor */ #define CSC_CLKSET_MAINDIV1_SHFT 7 #define CSC_CLKSET_MAINDIV1_MSK (0x0F << 7) /* Main Divisor 1 */ #define CSC_CLKSET_MAINDIV2_SHFT 11 #define CSC_CLKSET_MAINDIV2_MSK (0x1F << 11) /* Main Divisor 2 */ #define CSC_CLKSET_PCLKDIV_SHFT 16 #define CSC_CLKSET_PCLKDIV_MSK (0x03 << 16) /* PCLK Divisor */ #define CSC_CLKSET_PS_SHFT 18 #define CSC_CLKSET_PS_MSK (0x03 << 18) /* PS Divisor (2^PS) */ #define CSC_CLKSET_SMCROM (1 << 24) /* SMC Clock Disable */ /* Bits in USB Device Reset Register */ #define CSC_USBDRESET_IO (1 << 0) /* Reset USB Device I/O side */ #define CSC_USBDRESET_APB (1 << 1) /* Reset USB Device control side */ /*******************************************/ /* Vectored Interrupt Controller registers */ /*******************************************/ #define VIC1_BASE LH7A404_VIC1_BASE #define VIC1_IRQSTATUS __REG32(VIC1_BASE + 0x00) /* IRQ Status Register */ #define VIC1_FIQSTATUS __REG32(VIC1_BASE + 0x04) /* FIQ Status Register */ #define VIC1_RAWINTR __REG32(VIC1_BASE + 0x08) /* Raw Interrupt Status Register */ #define VIC1_INTSEL __REG32(VIC1_BASE + 0x0C) /* Interrupt Select Register */ #define VIC1_INTEN __REG32(VIC1_BASE + 0x10) /* Interrupt Enable Register */ #define VIC1_INTENCLR __REG32(VIC1_BASE + 0x14) /* Interrupt Enable Clear Register */ #define VIC1_SOFTINT __REG32(VIC1_BASE + 0x18) /* Software Interrupt Register */ #define VIC1_SOFTINTCLR __REG32(VIC1_BASE + 0x1C) /* Software Interrupt Clear Register */ #define VIC1_VECTADDR __REG32(VIC1_BASE + 0x30) /* Vector Address Register */ #define VIC1_NVADDR __REG32(VIC1_BASE + 0x34) /* Non-vectored Address Register */ #define VIC1_VAD0 __REG32(VIC1_BASE + 0x100) /* Vector Address 0 Register */ #define VIC1_VECTCNTL0 __REG32(VIC1_BASE + 0x200) /* Vector Control 0 Register */ #define VIC1_ITCR __REG32(VIC1_BASE + 0x300) /* Test Control Register */ #define VIC1_ITIP1 __REG32(VIC1_BASE + 0x304) /* Test Input Register 1 */ #define VIC1_ITIP2 __REG32(VIC1_BASE + 0x308) /* Test Input Register 2 */ #define VIC1_ITOP1 __REG32(VIC1_BASE + 0x30C) /* Test Output Register 1 */ #define VIC1_ITOP2 __REG32(VIC1_BASE + 0x310) /* Test Output Register 2 */ #define VIC2_BASE LH7A404_VIC2_BASE #define VIC2_IRQSTATUS __REG32(VIC2_BASE + 0x00) /* IRQ Status Register */ #define VIC2_FIQSTATUS __REG32(VIC2_BASE + 0x04) /* FIQ Status Register */ #define VIC2_RAWINTR __REG32(VIC2_BASE + 0x08) /* Raw Interrupt Status Register */ #define VIC2_INTSEL __REG32(VIC2_BASE + 0x0C) /* Interrupt Select Register */ #define VIC2_INTEN __REG32(VIC2_BASE + 0x10) /* Interrupt Enable Register */ #define VIC2_INTENCLR __REG32(VIC2_BASE + 0x14) /* Interrupt Enable Clear Register */ #define VIC2_SOFTINT __REG32(VIC2_BASE + 0x18) /* Software Interrupt Register */ #define VIC2_SOFTINTCLR __REG32(VIC2_BASE + 0x1C) /* Software Interrupt Clear Register */ #define VIC2_VECTADDR __REG32(VIC2_BASE + 0x30) /* Vector Address Register */ #define VIC2_NVADDR __REG32(VIC2_BASE + 0x34) /* Non-vectored Address Register */ #define VIC2_VAD0 __REG32(VIC2_BASE + 0x100) /* Vector Address 0 Register */ #define VIC2_VECTCNTL0 __REG32(VIC2_BASE + 0x200) /* Vector Control 0 Register */ #define VIC2_ITCR __REG32(VIC2_BASE + 0x300) /* Test Control Register */ #define VIC2_ITIP1 __REG32(VIC2_BASE + 0x304) /* Test Input Register 1 */ #define VIC2_ITIP2 __REG32(VIC2_BASE + 0x308) /* Test Input Register 2 */ #define VIC2_ITOP1 __REG32(VIC2_BASE + 0x30C) /* Test Output Register 1 */ #define VIC2_ITOP2 __REG32(VIC2_BASE + 0x310) /* Test Output Register 2 */ #define VIC_CNTL_ENABLE (0x20) /* Enable bit in VECTCNTLx register */ /*****************************************/ /* Direct Memory Access (DMA) Controller */ /*****************************************/ #define DMAC_BASE LH7A404_DMAC_BASE #define DMAC_M2PCH0_BASE (DMAC_BASE + 0x0000) /* M2P Channel 0 Registers (Tx) */ #define DMAC_M2PCH1_BASE (DMAC_BASE + 0x0040) /* M2P Channel 1 Registers (Rx) */ #define DMAC_M2PCH2_BASE (DMAC_BASE + 0x0080) /* M2P Channel 2 Registers (Tx) */ #define DMAC_M2PCH3_BASE (DMAC_BASE + 0x00C0) /* M2P Channel 3 Registers (Rx) */ #define DMAC_M2MCH0_BASE (DMAC_BASE + 0x0100) /* M2M Channel 0 Registers */ #define DMAC_M2MCH1_BASE (DMAC_BASE + 0x0140) /* M2M Channel 0 Registers */ #define DMAC_M2PCH5_BASE (DMAC_BASE + 0x0200) /* M2P Channel 5 Registers (Rx) */ #define DMAC_M2PCH4_BASE (DMAC_BASE + 0x0240) /* M2P Channel 4 Registers (Tx) */ #define DMAC_M2PCH7_BASE (DMAC_BASE + 0x0280) /* M2P Channel 7 Registers (Rx) */ #define DMAC_M2PCH6_BASE (DMAC_BASE + 0x02C0) /* M2P Channel 6 Registers (Tx) */ #define DMAC_M2PCH9_BASE (DMAC_BASE + 0x0300) /* M2P Channel 9 Registers (Rx) */ #define DMAC_M2PCH8_BASE (DMAC_BASE + 0x0340) /* M2P Channel 8 Registers (Tx) */ #define DMAC_GCA __REG32(DMAC_BASE + 0x0380) /* Global Channel Arbitration Register */ #define DMAC_GIR __REG32(DMAC_BASE + 0x03C0) /* Global Interrupt Register */ /************************/ /* Color LCD Controller */ /************************/ #define CLCDC_BASE LH7A404_CLCDC_BASE #define CLCDC_TIMING0 __REG32(CLCDC_BASE + 0x000) /* Horizontal axis panel control */ #define CLCDC_TIMING1 __REG32(CLCDC_BASE + 0x004) /* Vertical axis panel control */ #define CLCDC_TIMING2 __REG32(CLCDC_BASE + 0x008) /* Clock and signal polarity control */ #define CLCDC_UPBASE __REG32(CLCDC_BASE + 0x010) /* Upper panel frame base address */ #define CLCDC_LPBASE __REG32(CLCDC_BASE + 0x014) /* Lower panel frame base address */ #define CLCDC_INTREN __REG32(CLCDC_BASE + 0x018) /* Interrupt enable mask */ #define CLCDC_CONTROL __REG32(CLCDC_BASE + 0x01C) /* LCD panel pixel parameters */ #define CLCDC_STATUS __REG32(CLCDC_BASE + 0x020) /* Raw interrupt status */ #define CLCDC_INTERRUPT __REG32(CLCDC_BASE + 0x024) /* Final masked interrupts */ #define CLCDC_UPCURR __REG32(CLCDC_BASE + 0x028) /* LCD upper panel current address value */ #define CLCDC_LPCURR __REG32(CLCDC_BASE + 0x02C) /* LCD lower panel current address value */ #define CLCDC_OVERFLOW __REG32(CLCDC_BASE + 0x030) /* SDRAM overflow frame buffer address */ /* LCD Palette registers: 256 entries with 16 bit */ #define CLCDC_PALETTE_BASE (CLCDC_BASE + 0x300) /* Bits in CLCDC Timing Register 0 */ #define CLCDC_TIMING0_PPL_SHFT 2 #define CLCDC_TIMING0_PPL_MSK (0x3F << 2) /* Pixels Per Line */ #define CLCDC_TIMING0_HSW_SHFT 8 #define CLCDC_TIMING0_HSW_MSK (0xFF << 8) /* Horizontal Synchronization Pulse Width */ #define CLCDC_TIMING0_HFP_SHFT 16 #define CLCDC_TIMING0_HFP_MSK (0xFF << 16) /* Horizontal Front Porch */ #define CLCDC_TIMING0_HBP_SHFT 24 #define CLCDC_TIMING0_HBP_MSK (0xFF << 24) /* Horizontal Back Porch */ /* Bits in CLCDC Timing Register 1 */ #define CLCDC_TIMING1_LPP_SHFT 0 #define CLCDC_TIMING1_LPP_MSK (0x1FF << 0) /* Lines Per Panel */ #define CLCDC_TIMING1_VSW_SHFT 10 #define CLCDC_TIMING1_VSW_MSK (0x3F << 10) /* Vertical Synchronization Pulse Width */ #define CLCDC_TIMING1_VFP_SHFT 16 #define CLCDC_TIMING1_VFP_MSK (0xFF << 16) /* Vertical Front Porch */ #define CLCDC_TIMING1_VBP_SHFT 24 #define CLCDC_TIMING1_VBP_MSK (0xFF << 24) /* Vertical Back Porch */ /* Bits in CLCDC Timing Register 2 */ #define CLCDC_TIMING2_PCD_SHFT 0 #define CLCDC_TIMING2_PCD_MSK (0x1F << 0) /* Panel Clock Divisor */ #define CLCDC_TIMING2_CSEL (1 << 5) /* Clock Select */ #define CLCDC_TIMING2_ACB_SHFT 6 #define CLCDC_TIMING2_ACB_MSK (0x1F << 6) /* AC Bias Signal Frequency */ #define CLCDC_TIMING2_IVS (1 << 11) /* Invert Vertical Synchronization */ #define CLCDC_TIMING2_IHS (1 << 12) /* Invert Horizontal Synchronization */ #define CLCDC_TIMING2_IPC (1 << 13) /* Invert Panel Clock */ #define CLCDC_TIMING2_IOE (1 << 14) /* Invert Output Enable */ #define CLCDC_TIMING2_CPL_SHFT 16 #define CLCDC_TIMING2_CPL_MSK (0x3FF << 16) /* Clocks Per Line */ #define CLCDC_TIMING2_BCD (1 << 26) /* Bypass Pixel Clock Divider */ /* Bits in CLCDC Interrupt Enable Register (INTREN) */ #define CLCDC_INTREN_FUIEN (1 << 1) /* FIFO Underflow Interrupt Enable */ #define CLCDC_INTREN_BUIEN (1 << 2) /* Next Base Update Interrupt Enable */ #define CLCDC_INTREN_VCIEN (1 << 3) /* Vertical Compare Interrupt Enable */ #define CLCDC_INTREN_MBEIEN (1 << 4) /* Bus Master Error Interrupt Enable */ /* Bits in CLCDC Control Register (CONTROL) */ #define CLCDC_CONTROL_LCDEN (1 << 0) /* Color LCD Controller Enable */ #define CLCDC_CONTROL_BPP_SHFT 1 #define CLCDC_CONTROL_BPP_MSK (0x07 << 1) /* Bits Per Pixel */ #define CLCDC_CONTROL_BPP_1 (0 << 1) #define CLCDC_CONTROL_BPP_2 (1 << 1) #define CLCDC_CONTROL_BPP_4 (2 << 1) #define CLCDC_CONTROL_BPP_8 (3 << 1) #define CLCDC_CONTROL_BPP_16 (4 << 1) #define CLCDC_CONTROL_BW (1 << 4) /* Monochrome STN LCD */ #define CLCDC_CONTROL_TFT (1 << 5) /* TFT LCD */ #define CLCDC_CONTROL_MONO8L (1 << 6) /* Monochrome LCD uses 8-bit interface */ #define CLCDC_CONTROL_DUAL (1 << 7) /* Dual Panel STN LCD */ #define CLCDC_CONTROL_BGR (1 << 8) /* RGB or BGR */ #define CLCDC_CONTROL_BEBO (1 << 9) /* Big Endian Byte Ordering */ #define CLCDC_CONTROL_BEPO (1 << 10) /* Big Endian Pixel Ordering */ #define CLCDC_CONTROL_PWR (1 << 11) /* LCD Power Enable */ #define CLCDC_CONTROL_VCI_SHFT 12 #define CLCDC_CONTROL_VCI_MSK (0x3 << 12) /* LCD Vertical Compare */ #define CLCDC_CONTROL_WATERMARK (1 << 16) /* LCD DMA FIFO Watermark Level */ /* Bits in CLCDC Interrupt Status Register (STATUS) */ #define CLCDC_STATUS_FUI (1 << 1) /* FIFO Underflow */ #define CLCDC_STATUS_BUI (1 << 2) /* LCD Next Base Address Update */ #define CLCDC_STATUS_VCI (1 << 3) /* Vertical Compare */ #define CLCDC_STATUS_MBEI (1 << 4) /* AMBA AHB Master Bus Error Status */ /* Bits in CLCDC Interrupt Register (INTERRUPT) */ #define CLCDC_INTERRUPT_FUIM (1 << 1) /* Masked FIFO Underflow Interrupt */ #define CLCDC_INTERRUPT_BUIM (1 << 2) /* Masked LCD Next Base Address Update Interrupt */ #define CLCDC_INTERRUPT_VCIM (1 << 3) /* Masked Vertical Compare Interrupt */ #define CLCDC_INTERRUPT_MBEIM (1 << 4) /* Masked AMBA AHB Master Bus Error Interrupt */ /******************************************/ /* Advanced LCD Interface (ALI) registers */ /******************************************/ #define ALI_BASE LH7A404_ALI_BASE #define ALI_SETUP __REG32(ALI_BASE + 0x00) /* ALI Setup Register */ #define ALI_CONTROL __REG32(ALI_BASE + 0x04) /* ALI Control Register */ #define ALI_TIMING1 __REG32(ALI_BASE + 0x08) /* ALI Timing Register 1 */ #define ALI_TIMING2 __REG32(ALI_BASE + 0x0C) /* ALI Timing Register 2 */ /* Bits in ALI Setup Register */ #define ALI_SETUP_CR_MSK (0x03) /* Conversion Mode Select */ #define ALI_SETUP_CR_ACTIVE 0x01 /* Active Mode */ #define ALI_SETUP_CR_BYPASS 0x00 /* Bypass Mode (for STN or TFT panels) */ #define ALI_SETUP_LBR (1 << 2) /* Left Before Right */ #define ALI_SETUP_UBL (1 << 3) /* Upper Before Lower */ #define ALI_SETUP_PPL_SHIFT 4 #define ALI_SETUP_PPL_MSK (0x1FF << 4) /* Pixels Per Line */ #define ALI_SETUP_ALIEN (1 << 13) /* ALI Enable */ /* Bits in ALI Control Register */ #define ALI_CONTROL_LCDSPSEN (1 << 0) /* LCDSPS Enable (Row Reset) */ #define ALI_CONTROL_LCDCLSEN (1 << 1) /* LCDCLS Enable (Gate Driver Clock) */ /* Bits in ALI Timing Register 1 */ #define ALI_TIMING1_LPDEL_SHFT 0 #define ALI_TIMING1_LPDEL_MSK (0x0F << 0) /* LCDLP Delay */ #define ALI_TIMING1_REVDEL_SHFT 4 #define ALI_TIMING1_REVDEL_MSK (0x0F << 4) /* Polarity-Reversal Delay */ #define ALI_TIMING1_PSCLS_SHFT 8 #define ALI_TIMING1_PSCLS_MSK (0x0F << 8) /* LCDPS and LCDCLS Delay */ /* Bits in ALI Timing Register 2 */ #define ALI_TIMING2_PS2CLS2_SHFT 0 #define ALI_TIMING2_PS2CLS2_MSK (0x1FF) /* LCDSPL and LCDCLS Delay 2 */ #define ALI_TIMING2_SPLDEL_SHFT 9 #define ALI_TIMING2_SPLDEL_MSK (0x7F << 9) /* LCDSPL Delay */ /*******************************************/ /* Synchronous Serial Port (SSP) registers */ /*******************************************/ #define SSP_BASE LH7A404_SSP_BASE #define SSP_CR0 __REG32(SSP_BASE + 0x00) /* Control Register 0 */ #define SSP_CR1 __REG32(SSP_BASE + 0x04) /* Control Register 1 */ #define SSP_IIR __REG32(SSP_BASE + 0x08) /* Interrupt Identification Register (RO) */ #define SSP_ROEOI __REG32(SSP_BASE + 0x08) /* Receive Overrun End-of-Interrupt (WO) */ #define SSP_DR __REG32(SSP_BASE + 0x0C) /* Data Register */ #define SSP_CPR __REG32(SSP_BASE + 0x10) /* Clock Prescale Register */ #define SSP_SR __REG32(SSP_BASE + 0x14) /* Status Register */ /* Bits in SSP Control Register 0 */ #define SSP_CR0_DSS (0x0F << 0) /* Data Size Selection */ #define SSP_CR0_DSS_16 (0x0F << 0) /* 16 bit */ #define SSP_CR0_DSS_15 (0x0E << 0) /* 15 bit */ #define SSP_CR0_DSS_14 (0x0D << 0) /* 14 bit */ #define SSP_CR0_DSS_13 (0x0C << 0) /* 13 bit */ #define SSP_CR0_DSS_12 (0x0B << 0) /* 12 bit */ #define SSP_CR0_DSS_11 (0x0A << 0) /* 11 bit */ #define SSP_CR0_DSS_10 (0x09 << 0) /* 10 bit */ #define SSP_CR0_DSS_9 (0x08 << 0) /* 9 bit */ #define SSP_CR0_DSS_8 (0x07 << 0) /* 8 bit */ #define SSP_CR0_DSS_7 (0x06 << 0) /* 7 bit */ #define SSP_CR0_DSS_6 (0x05 << 0) /* 6 bit */ #define SSP_CR0_DSS_5 (0x04 << 0) /* 5 bit */ #define SSP_CR0_DSS_4 (0x03 << 0) /* 4 bit */ #define SSP_CR0_FRF (0x03 << 4) /* Frame Format */ #define SSP_CR0_FRF_MOT (0x00 << 4) /* Motorola SPI frame format */ #define SSP_CR0_FRF_TI (0x01 << 4) /* TI synchronous serial frame format */ #define SSP_CR0_FRF_NAT (0x02 << 4) /* National MICROWIRE frame format */ #define SSP_CR0_SSE (1 << 7) /* SSP Enable */ #define SSP_CR0_SCR (0xFF << 8) /* Serial Clock Rate */ /* Bits in SSP Control Register 1 */ #define SSP_CR1_RXSIEN (1 << 0) /* Receive FIFO Service Interrupt Enable */ #define SSP_CR1_TXSIEN (1 << 1) /* Transmit FIFO Service Interrupt Enable */ #define SSP_CR1_LBM (1 << 2) /* Loopback Mode */ #define SSP_CR1_SPO (1 << 3) /* SPI Polarity */ #define SSP_CR1_SPH (1 << 4) /* SPI Phase */ #define SSP_CR1_RXOIEN (1 << 5) /* Receive Overrun Interrupt Enable */ #define SSP_CR1_FEN (1 << 6) /* FIFO Enable */ #define SSP_CR1_TXIIEN (1 << 7) /* Transmit Idle Interrupt Enable */ /* Bits in SSP Interrupt Identification Register */ #define SSP_IIR_RXSI (1 << 0) /* Receive FIFO Service Request Interrupt */ #define SSP_IIR_TXSI (1 << 1) /* Transmit FIFO Service Request Interrupt */ #define SSP_IIR_RXOI (1 << 6) /* Receive FIFO Overrun Interrupt */ #define SSP_IIR_TXII (1 << 7) /* Transmit Idle Interrupt */ /* Bits in SSP Status Register */ #define SSP_SR_TNF (1 << 1) /* Transmit FIFO Not Full */ #define SSP_SR_RNE (1 << 2) /* Receive FIFO Not Empty */ #define SSP_SR_BSY (1 << 3) /* Busy */ #define SSP_SR_THE (1 << 4) /* Transmit FIFO Half Empty */ #define SSP_SR_RHF (1 << 5) /* Receive FIFO Half Full */ #define SSP_SR_ROR (1 << 6) /* Receive Overrun */ #define SSP_SR_TFE (1 << 7) /* Transmit FIFO Empty */ #define SSP_SR_RFF (1 << 8) /* Receive FIFO Full */ /*******************/ /* Timer registers */ /*******************/ #define TIMER_BASE LH7A404_TIMER_BASE #define TIMER_LOAD1 __REG32(TIMER_BASE + 0x00) /* Timer 1 initial value */ #define TIMER_VALUE1 __REG32(TIMER_BASE + 0x04) /* Timer 1 current value */ #define TIMER_CONTROL1 __REG32(TIMER_BASE + 0x08) /* Timer 1 control word */ #define TIMER_EOI1 __REG32(TIMER_BASE + 0x0C) /* Timer 1 interrupt clear */ #define TIMER_LOAD2 __REG32(TIMER_BASE + 0x20) /* Timer 2 initial value */ #define TIMER_VALUE2 __REG32(TIMER_BASE + 0x24) /* Timer 2 current value */ #define TIMER_CONTROL2 __REG32(TIMER_BASE + 0x28) /* Timer 2 control word */ #define TIMER_EOI2 __REG32(TIMER_BASE + 0x2C) /* Timer 2 interrupt clear */ #define TIMER_BUZZCON __REG32(TIMER_BASE + 0x40) /* Buzzer configuration */ #define TIMER_LOAD3 __REG32(TIMER_BASE + 0x80) /* Timer 3 initial value */ #define TIMER_VALUE3 __REG32(TIMER_BASE + 0x84) /* Timer 3 current value */ #define TIMER_CONTROL3 __REG32(TIMER_BASE + 0x88) /* Timer 3 control word */ #define TIMER_EOI3 __REG32(TIMER_BASE + 0x8C) /* Timer 3 interrupt clear */ #define TIMER_C_ENABLE (1 << 7) #define TIMER_C_PERIODIC (1 << 6) #define TIMER_C_FREERUNNING (0) #define TIMER_C_2KHZ (0x00) /* 1.994 kHz */ #define TIMER_C_508KHZ (0x08) /* 508.469 kHz */ /******************/ /* GPIO registers */ /******************/ /* Note: Direction of port pin has different meaning for ports Port C,D,G: 0 == output, 1 == input Port A,B,E,F,H: 0 == input, 1 == output */ #define GPIO_BASE LH7A404_GPIO_BASE #define GPIO_PAD __REG32(GPIO_BASE + 0x00) /* Port A Data register */ #define GPIO_PBD __REG32(GPIO_BASE + 0x04) /* Port B Data register */ #define GPIO_PCD __REG32(GPIO_BASE + 0x08) /* Port C Data register */ #define GPIO_PDD __REG32(GPIO_BASE + 0x0C) /* Port D Data register */ #define GPIO_PADD __REG32(GPIO_BASE + 0x10) /* Port A Data Direction register */ #define GPIO_PBDD __REG32(GPIO_BASE + 0x14) /* Port B Data Direction register */ #define GPIO_PCDD __REG32(GPIO_BASE + 0x18) /* Port C Data Direction register */ #define GPIO_PDDD __REG32(GPIO_BASE + 0x1C) /* Port D Data Direction register */ #define GPIO_PED __REG32(GPIO_BASE + 0x20) /* Port E Data register */ #define GPIO_PEDD __REG32(GPIO_BASE + 0x24) /* Port E Data Direction register */ #define GPIO_KBDCTL __REG32(GPIO_BASE + 0x28) /* Keyboard Control register */ #define GPIO_PINMUX __REG32(GPIO_BASE + 0x2C) /* Pin Multiplexing register */ #define GPIO_PFD __REG32(GPIO_BASE + 0x30) /* Port F Data register */ #define GPIO_PFDD __REG32(GPIO_BASE + 0x34) /* Port F Data Direction register */ #define GPIO_PGD __REG32(GPIO_BASE + 0x38) /* Port G Data register */ #define GPIO_PGDD __REG32(GPIO_BASE + 0x3C) /* Port G Data Direction register */ #define GPIO_PHD __REG32(GPIO_BASE + 0x40) /* Port H Data register */ #define GPIO_PHDD __REG32(GPIO_BASE + 0x44) /* Port H Data Direction register */ #define GPIO_INTTYPE1 __REG32(GPIO_BASE + 0x4C) /* IRQ edge (1) or lvl (0) */ #define GPIO_INTTYPE2 __REG32(GPIO_BASE + 0x50) /* IRQ activ hi/lo or rising/falling */ #define GPIO_GPIOFEOI __REG32(GPIO_BASE + 0x54) /* GPIOF end of IRQ */ #define GPIO_GPIOINTEN __REG32(GPIO_BASE + 0x58) /* GPIOF IRQ enable */ #define GPIO_INTSTATUS __REG32(GPIO_BASE + 0x5C) /* GPIOF IRQ latch */ #define GPIO_RAWINTSTATUS __REG32(GPIO_BASE + 0x60) /* GPIOF IRQ raw */ #define GPIO_GPIODB __REG32(GPIO_BASE + 0x64) /* GPIOF Debounce */ #define GPIO_PAPD __REG32(GPIO_BASE + 0x68) /* Port A Pin Data register */ #define GPIO_PBPD __REG32(GPIO_BASE + 0x6C) /* Port B Pin Data register */ #define GPIO_PCPD __REG32(GPIO_BASE + 0x70) /* Port C Pin Data register */ #define GPIO_PDPD __REG32(GPIO_BASE + 0x74) /* Port D Pin Data register */ #define GPIO_PEPD __REG32(GPIO_BASE + 0x78) /* Port E Pin Data register */ #define GPIO_PFPD __REG32(GPIO_BASE + 0x7C) /* Port F Pin Data register */ #define GPIO_PGPD __REG32(GPIO_BASE + 0x80) /* Port G Pin Data register */ #define GPIO_PHPD __REG32(GPIO_BASE + 0x84) /* Port H Pin Data register */ /* Bits in GPIO_PINMUX */ #define GPIO_PINMUX_PEOCON (1 << 0) /* Port E Output Control */ #define GPIO_PINMUX_PDOCON (1 << 1) /* Port D Output Control */ #define GPIO_PINMUX_CODECON (1 << 2) /* Codec Control (AC97) */ #define GPIO_PINMUX_UART3CON (1 << 3) /* UART3 Control */ /******************/ /* UART registers */ /******************/ #define UART1_BASE LH7A404_UART1_BASE #define UART1_DATA __REG32(UART1_BASE + 0x00) /* Data Register */ #define UART1_FCON __REG32(UART1_BASE + 0x04) /* FIFO Control Register */ #define UART1_BRCON __REG32(UART1_BASE + 0x08) /* Baud Rate Control Register */ #define UART1_CON __REG32(UART1_BASE + 0x0C) /* Control Register */ #define UART1_STATUS __REG32(UART1_BASE + 0x10) /* Status Register */ #define UART1_RAWISR __REG32(UART1_BASE + 0x14) /* Raw Interrupt Status Register */ #define UART1_INTEN __REG32(UART1_BASE + 0x18) /* Interrupt Mask Register */ #define UART1_MISR __REG32(UART1_BASE + 0x1C) /* Masked Interrupt Status Register */ #define UART1_RES __REG32(UART1_BASE + 0x20) /* Receive Error Status + Clear Register */ #define UART1_EIC __REG32(UART1_BASE + 0x24) /* Error Interrupt Clear Register */ #define UART1_DMACR __REG32(UART1_BASE + 0x28) /* DMA Control Register */ #define UART2_BASE LH7A404_UART2_BASE #define UART2_DATA __REG32(UART2_BASE + 0x00) /* Data Register */ #define UART2_FCON __REG32(UART2_BASE + 0x04) /* FIFO Control Register */ #define UART2_BRCON __REG32(UART2_BASE + 0x08) /* Baud Rate Control Register */ #define UART2_CON __REG32(UART2_BASE + 0x0C) /* Control Register */ #define UART2_STATUS __REG32(UART2_BASE + 0x10) /* Status Register */ #define UART2_RAWISR __REG32(UART2_BASE + 0x14) /* Raw Interrupt Status Register */ #define UART2_INTEN __REG32(UART2_BASE + 0x18) /* Interrupt Mask Register */ #define UART2_MISR __REG32(UART2_BASE + 0x1C) /* Masked Interrupt Status Register */ #define UART2_RES __REG32(UART2_BASE + 0x20) /* Receive Error Status + Clear Register */ #define UART2_EIC __REG32(UART2_BASE + 0x24) /* Error Interrupt Clear Register */ #define UART2_DMACR __REG32(UART2_BASE + 0x28) /* DMA Control Register */ #define UART3_BASE LH7A404_UART3_BASE #define UART3_DATA __REG32(UART3_BASE + 0x00) /* Data Register */ #define UART3_FCON __REG32(UART3_BASE + 0x04) /* FIFO Control Register */ #define UART3_BRCON __REG32(UART3_BASE + 0x08) /* Baud Rate Control Register */ #define UART3_CON __REG32(UART3_BASE + 0x0C) /* Control Register */ #define UART3_STATUS __REG32(UART3_BASE + 0x10) /* Status Register */ #define UART3_RAWISR __REG32(UART3_BASE + 0x14) /* Raw Interrupt Status Register */ #define UART3_INTEN __REG32(UART3_BASE + 0x18) /* Interrupt Mask Register */ #define UART3_MISR __REG32(UART3_BASE + 0x1C) /* Masked Interrupt Status Register */ #define UART3_RES __REG32(UART3_BASE + 0x20) /* Receive Error Status + Clear Register */ #define UART3_EIC __REG32(UART3_BASE + 0x24) /* Error Interrupt Clear Register */ #define UART3_DMACR __REG32(UART3_BASE + 0x28) /* DMA Control Register */ /* Bits in DATA register (error flags on RX) */ #define UART_DATA_MSK (0xFF << 0) #define UART_DATA_FE (1 << 8) /* Framing Error */ #define UART_DATA_PE (1 << 9) /* Parity Error */ #define UART_DATA_OE (1 << 10) /* Overrun Error */ #define UART_DATA_BE (1 << 11) /* Break Error */ /* Bits in FCON register */ #define UART_FCON_BRK (1 << 0) /* Break (Assert Break) */ #define UART_FCON_PEN (1 << 1) /* Parity Enable */ #define UART_FCON_EPS (1 << 2) /* Even Parity Set */ #define UART_FCON_STP2 (1 << 3) /* Stop bits (1 = 2 stop bits, 0 = 1 stop bit) */ #define UART_FCON_FEN (1 << 4) /* FIFO Enable */ #define UART_FCON_WLEN5 (0 << 5) /* Word Length: 5 bit data */ #define UART_FCON_WLEN6 (1 << 5) /* Word Length: 6 bit data */ #define UART_FCON_WLEN7 (2 << 5) /* Word Length: 7 bit data */ #define UART_FCON_WLEN8 (3 << 5) /* Word Length: 8 bit data */ /* Bits in CON register */ #define UART_CON_UARTEN (1 << 0) /* UART Enable */ #define UART_CON_SIRD (1 << 1) /* Serial Infrared disable (UART1) */ #define UART_CON_SIRLP (1 << 2) /* Serial Infrared Low Power (UART1) */ #define UART_CON_RXP (1 << 3) /* Receive Polarity */ #define UART_CON_TXP (1 << 4) /* Transmit Polarity */ #define UART_CON_MXP (1 << 5) /* Modem Transfer Polarity */ #define UART_CON_LBE (1 << 6) /* Loopback Enable */ #define UART_CON_SIRBD (1 << 7) /* Serial Infrared Blanking Disable (UART1) */ /* Bits in STATUS register */ #define UART_STATUS_CTS (1 << 0) /* Clear To Send (UART2/3) */ #define UART_STATUS_DSR (1 << 1) /* Data Set Ready (UART2/3) */ #define UART_STATUS_DCD (1 << 2) /* Data Carrier Detect (UART2/3) */ #define UART_STATUS_BUSY (1 << 3) /* UART busy */ #define UART_STATUS_RXFE (1 << 4) /* Receive FIFO empty */ #define UART_STATUS_TXFF (1 << 5) /* Transmit FIFO full */ #define UART_STATUS_RXFF (1 << 6) /* Receive FIFO full */ #define UART_STATUS_TXFE (1 << 7) /* Transmit FIFO empty */ /* Bits in RAWISR register (Read) */ #define UART_RAWISR_RI (1 << 0) /* Receive Interrupt */ #define UART_RAWISR_TI (1 << 1) /* Transmit Interrupt */ #define UART_RAWISR_MI (1 << 2) /* Modem Status Interrupt */ #define UART_RAWISR_RTI (1 << 3) /* Receive Timeout Interrupt */ #define UART_RAWISR_FEI (1 << 4) /* Frame Error Interrupt */ #define UART_RAWISR_PEI (1 << 5) /* Parity Error Interrupt */ #define UART_RAWISR_BEI (1 << 6) /* Break Error Interrupt */ #define UART_RAWISR_OEI (1 << 7) /* Overrun Error Interrupt */ /* Bits in INTEN register */ #define UART_INTEN_REN (1 << 0) /* Receive Interrupt Enable */ #define UART_INTEN_TEN (1 << 1) /* Transmit Interrupt Enable */ #define UART_INTEN_MEN (1 << 2) /* Modem Status Interrupt Enable */ #define UART_INTEN_RTEN (1 << 3) /* Receive Timeout Interrupt Enable */ #define UART_INTEN_FEEN (1 << 4) /* Frame Error Interrupt Enable */ #define UART_INTEN_PEEN (1 << 5) /* Parity Error Interrupt Enable */ #define UART_INTEN_BEEN (1 << 6) /* Break Error Interrupt Enable */ #define UART_INTEN_OEEN (1 << 7) /* Overrun Error Interrupt Enable */ /* Bits in MISR register */ #define UART_MISR_RIM (1 << 0) /* Masked Receive Interrupt */ #define UART_MISR_TIM (1 << 1) /* Masked Transmit Interrupt */ #define UART_MISR_MIM (1 << 2) /* Masked Modem Status Interrupt */ #define UART_MISR_RTIM (1 << 3) /* Masked Receive Timeout Interrupt */ #define UART_MISR_FEIM (1 << 4) /* Masked Frame Error Interrupt */ #define UART_MISR_PEIM (1 << 5) /* Masked Parity Error Interrupt */ #define UART_MISR_BEIM (1 << 6) /* Masked Break Error Interrupt */ #define UART_MISR_OEIM (1 << 7) /* Masked Overrun Error Interrupt */ /* Bits in RES register */ #define UART_RES_FE (1 << 0) /* Frame Error */ #define UART_RES_PE (1 << 1) /* Parity Error */ #define UART_RES_OE (1 << 2) /* Overrun Error */ #define UART_RES_BE (1 << 3) /* Break Error */ /* Bits in EIC register */ #define UART_EIC_FEIC (1 << 0) /* Masked Frame Error Interrupt Clear */ #define UART_EIC_PEIC (1 << 1) /* Masked Parity Error Interrupt Clear */ #define UART_EIC_OEIC (1 << 2) /* Masked Overrun Error Interrupt Clear */ #define UART_EIC_BEIC (1 << 3) /* Masked Break Error Interrupt Clear */ /* Bits in DMACR register */ #define UART_DMACR_RDE (1 << 0) /* Receive DMA Enable */ #define UART_DMACR_TDE (1 << 1) /* Transmit DMA Enable */ #define UART_DMACR_DE (1 << 2) /* DMA On Error */ /***********************************/ /* MultiMediaCard (MMC) Controller */ /***********************************/ #define MMC_BASE LH7A404_MMC_BASE #define MMC_CLKC __REG32(MMC_BASE + 0x00) /* Clock control register */ #define MMC_STATUS __REG32(MMC_BASE + 0x04) /* Controller status register */ #define MMC_RATE __REG32(MMC_BASE + 0x08) /* SD/MMC clock divider register */ #define MMC_PREDIV __REG32(MMC_BASE + 0x0C) /* SD/MMC predivide register */ #define MMC_CMDCON __REG32(MMC_BASE + 0x14) /* Command control register */ #define MMC_RES_TO __REG32(MMC_BASE + 0x18) /* Response timeout register */ #define MMC_READ_TO __REG32(MMC_BASE + 0x1C) /* Read timeout register */ #define MMC_BLK_LEN __REG32(MMC_BASE + 0x20) /* Block length register */ #define MMC_NOB __REG32(MMC_BASE + 0x24) /* Number Of Blocks register */ #define MMC_INT_STATUS __REG32(MMC_BASE + 0x28) /* Interrupt status register */ #define MMC_EOI __REG32(MMC_BASE + 0x2C) /* End Of Interrupt register */ #define MMC_INT_MASK __REG32(MMC_BASE + 0x34) /* Interrupt mask register */ #define MMC_CMD __REG32(MMC_BASE + 0x38) /* Command number register */ #define MMC_ARGUMENT __REG32(MMC_BASE + 0x3C) /* Command argument register */ #define MMC_RES_FIFO __REG32(MMC_BASE + 0x40) /* Response FIFO location */ #define MMC_DATA_FIFO __REG32(MMC_BASE + 0x48) /* FIFO data register */ /* Bits in MMC_CLKC */ #define MMC_CLKC_STOP_CLK (1 << 0) /* Stop Clock */ #define MMC_CLKC_START_CLK (1 << 1) /* Start Clock */ /* Bits in MMC_STATUS */ #define MMC_STATUS_TOREAD (1 << 0) /* Read Timeout */ #define MMC_STATUS_TORES (1 << 1) /* Response Timeout */ #define MMC_STATUS_CRCWRITE (1 << 2) /* CRC Write Error */ #define MMC_STATUS_CRCREAD (1 << 3) /* CRC Read Error */ #define MMC_STATUS_CRC (1 << 5) /* Response CRC Error */ #define MMC_STATUS_FIFO_EMPTY (1 << 6) /* FIFO Empty */ #define MMC_STATUS_FIFO_FULL (1 << 7) /* FIFO Full */ #define MMC_STATUS_CLK_DIS (1 << 8) /* Clock Disabled */ #define MMC_STATUS_TRANDONE (1 << 11) /* Data Transfer Done */ #define MMC_STATUS_DONE (1 << 12) /* Program Done */ #define MMC_STATUS_ENDRESP (1 << 13) /* End Command Response */ /* Bits in MMC_PREDIV */ #define MMC_PREDIV_MMC_PREDIV (0x0F << 0) /* SD/MMC Predivisor */ #define MMC_PREDIV_MMC_EN (1 << 4) /* SD/MMC Enable */ #define MMC_PREDIV_APB_RD_EN (1 << 5) /* APB Read Enable */ /* Bits in MMC_CMDCON */ #define MMC_CMDCON_ABORT (1 << 13) /* Abort Transaction */ #define MMC_CMDCON_SET_READ_WRITE (1 << 12) /* Set Transaction to Read (0) or Write (1) */ #define MMC_CMDCON_MULTI_BLK4_INTEN (1 << 11) /* Multiple Block Interrupt Enable */ #define MMC_CMDCON_READ_WAIT_EN (1 << 10) /* Enable Read Wait States */ #define MMC_CMDCON_SDIO_EN (1 << 9) /* Enable SD Input/Output */ #define MMC_CMDCON_BIG_ENDIAN (1 << 8) /* Enable Big Endian Mode for MMC */ #define MMC_CMDCON_WIDE (1 << 7) /* Enable Wide Mode for SD */ #define MMC_CMDCON_INITIALIZE (1 << 6) /* Enable 80-bit Initialization Sequence */ #define MMC_CMDCON_BUSY (1 << 5) /* Busy Expected */ #define MMC_CMDCON_STREAM (1 << 4) /* Stream Mode */ #define MMC_CMDCON_WRITE (1 << 3) /* Write Transfer Mode */ #define MMC_CMDCON_DATA_EN (1 << 2) /* Data Transfer Enable */ #define MMC_CMDCON_RESP_FORMAT_NONE (0 << 0) /* No Response */ #define MMC_CMDCON_RESP_FORMAT_R1 (1 << 0) /* Response Format R1 */ #define MMC_CMDCON_RESP_FORMAT_R2 (2 << 0) /* Response Format R2 */ #define MMC_CMDCON_RESP_FORMAT_R3 (3 << 0) /* Response Format R3 */ /* Bits in MMC_INT_STATUS, MMC_EOI + MMC_INT_MASK */ #define MMC_INT_SDIO_INT (1 << 5) /* SD Interrupt */ #define MMC_INT_BUS_CLOCK_STOPPED (1 << 4) /* Bus Clock Stopped Interrupt */ #define MMC_INT_BUF_READY (1 << 3) /* Buffer Ready Interrupt */ #define MMC_INT_END_CMD (1 << 2) /* End Command Response Interrupt */ #define MMC_INT_DONE (1 << 1) /* Program Done Interrupt */ #define MMC_INT_DATA_TRAN (1 << 0) /* Data Transfer Done Interrupt */ /*************************************/ /* Universal Serial Bus (USB) Device */ /*************************************/ #define USB_BASE LH7A404_USB_BASE #define USB_FAR __REG32(USB_BASE + 0x00) /* Function Address Register */ #define USB_PMR __REG32(USB_BASE + 0x04) /* Power Management Register */ #define USB_IIR __REG32(USB_BASE + 0x08) /* IN Interrupt Register Bank */ #define USB_OIR __REG32(USB_BASE + 0x10) /* OUT Interrupt Register Bank */ #define USB_UIR __REG32(USB_BASE + 0x18) /* USB Interrupt Register Bank */ #define USB_IIE __REG32(USB_BASE + 0x1C) /* IN Interrupt Enable Register Bank */ #define USB_OIE __REG32(USB_BASE + 0x24) /* OUT Interrupt Enable Register Bank */ #define USB_UIE __REG32(USB_BASE + 0x2C) /* USB Interrupt Enable Register Bank */ #define USB_FRAME1 __REG32(USB_BASE + 0x30) /* Frame Number1 Register */ #define USB_FRAME2 __REG32(USB_BASE + 0x34) /* Frame Number2 Register */ #define USB_INDEX __REG32(USB_BASE + 0x38) /* Index Register */ #define USB_INMAXP __REG32(USB_BASE + 0x40) /* IN Maximum Packet Size Register */ #define USB_INCSR1 __REG32(USB_BASE + 0x44) /* Control and Status Register (EP0,1,3) */ #define USB_INCSR2 __REG32(USB_BASE + 0x48) /* IN Control Register (EP1,EP3) */ #define USB_OUTMAXP __REG32(USB_BASE + 0x4C) /* OUT Maximum Packet Size Register */ #define USB_OUTCSR1 __REG32(USB_BASE + 0x50) /* OUT Control and Status Register */ #define USB_OUTCSR2 __REG32(USB_BASE + 0x54) /* OUT Control Register */ #define USB_COUNT1 __REG32(USB_BASE + 0x58) /* OUT FIFO Write Count1 Register */ #define USB_EP0FIFO __REG32(USB_BASE + 0x80) /* EP0 (Control, 8 Bytes) */ #define USB_EP1FIFO __REG32(USB_BASE + 0x84) /* EP1 (IN BULK, 64 Bytes) */ #define USB_EP2FIFO __REG32(USB_BASE + 0x88) /* EP2 (OUT BULK, 64 Bytes) */ #define USB_EP3FIFO __REG32(USB_BASE + 0x8C) /* EP3 (IN Interrupt, 64 Bytes) */ /* Bits in USB_FAR */ #define USB_FAR_FUNCTION_ADDR (0x7F << 0) /* Function Address field */ #define USB_FAR_ADDR_UPDATE (1 << 7) /* Address Update */ /* Bits in USB_PMR */ #define USB_PMR_ENABLE_SUSPEND (1 << 0) /* SUSPEND Enable */ #define USB_PMR_SUSPEND_MODE (1 << 1) /* SUSPEND Mode active */ #define USB_PMR_UC_RESUME (1 << 2) /* UC RESUME */ #define USB_PMR_USB_RESET (1 << 3) /* USB RESET active */ #define USB_PMR_USB_ENABLE (1 << 4) /* USB Enable */ #define USB_PMR_DCP_CTRL (1 << 5) /* DCP Pin Control (0=pulled up, 1=floating) */ /* Bits in USB_IIR */ #define USB_IIR_EP0 (1 << 0) /* End Point 0 Interrupt */ #define USB_IIR_EP1IN (1 << 1) /* End Point 1 IN Interrupt */ #define USB_IIR_EP3IN (1 << 3) /* End Point 3 IN Interrupt */ /* Bits in USB_OIR */ #define USB_OIR_EP2OUT (1 << 2) /* End Point 2 OUT Interrupt */ /* Bits in USB_UIR */ #define USB_UIR_SUSINT (1 << 0) /* SUSPEND Interrupt */ #define USB_UIR_RESINT (1 << 1) /* RESUME Interrupt */ #define USB_UIR_URINT (1 << 2) /* USB RESET Interrupt */ /* Bits in USB_IIE */ #define USB_IIE_EP0EN (1 << 0) /* End Point 0 Interrupt Enable */ #define USB_IIE_EP1INEN (1 << 1) /* End Point 1 IN Interrupt Enable */ #define USB_IIE_EP3INEN (1 << 3) /* End Point 3 IN Interrupt Enable */ /* Bits in USB_OIE */ #define USB_OIE_EP2OUTEN (1 << 2) /* End Point 2 OUT Interrupt Enable */ /* Bits in USB_UIE */ #define USB_UIE_SUSINTEN (1 << 0) /* SUSPEND Interrupt Enable (also RESUME) */ #define USB_UIE_URINTEN (1 << 2) /* USB RESET Interrupt Enable */ /* Values for USB_INDEX */ #define USB_INDEX_EP0 0 #define USB_INDEX_EP1 1 #define USB_INDEX_EP2 2 #define USB_INDEX_EP3 3 /* Values for USB_MAXP */ #define USB_MAXP_MAXP_8 1 #define USB_MAXP_MAXP_16 2 #define USB_MAXP_MAXP_24 3 #define USB_MAXP_MAXP_32 4 #define USB_MAXP_MAXP_40 5 #define USB_MAXP_MAXP_48 6 #define USB_MAXP_MAXP_56 7 #define USB_MAXP_MAXP_64 8 /* Bits in USB_INCSR1 */ #define USB_INCSR1_IN_PKT_RDY (1 << 0) /* IN Packet Ready */ #define USB_INCSR1_FIFO_NE (1 << 1) /* FIFO Not Empty */ #define USB_INCSR1_FIFO_FLUSH (1 << 3) /* FIFO Flush Request */ #define USB_INCSR1_SEND_STALL (1 << 4) /* Send Stall Handshake to USB */ #define USB_INCSR1_SENT_STALL (1 << 5) /* STALL Send Acknowledge */ #define USB_INCSR1_CLRTOG (1 << 6) /* Clear Data Toggle */ /* Bits in USB_INCSR2 */ #define USB_INCSR2_USB_DMA_EN (1 << 4) /* USB DMA Enable */ #define USB_INCSR2_AUTO_SET (1 << 7) /* Auto Set IN_PKT_RDY Bit */ /* Bits in USB_OUTCSR1 */ #define USB_OUTCSR1_OUT_PKT_RDY (1 << 0) /* OUT Packet Ready */ #define USB_OUTCSR1_FIFO_FULL (1 << 1) /* FIFO Full */ #define USB_OUTCSR1_FIFO_FLUSH (1 << 4) /* Flush OUT FIFO */ #define USB_OUTCSR1_SEND_STALL (1 << 5) /* Send Stall Handshake */ #define USB_OUTCSR1_SENT_STALL (1 << 6) /* STALL Handshake Sent */ #define USB_OUTCSR1_CL_DATATOG (1 << 7) /* Clear Data Toggle Sequence Bit */ /* Bits in USB_OUTCSR2 */ #define USB_OUTCSR2_USB_DMA_EN (1 << 4) /* USB DMA Enable */ #define USB_OUTCSR2_AUTO_CLR (1 << 7) /* Auto Clear OUT_PKT_RDY Bit */ /* Bits in EP0CSR (== USB_INCSR1 with USB_INDEX = 0) */ #define USB_EP0CSR_OUT_PKT_RDY (1 << 0) /* OUT Packet Ready (RO) */ #define USB_EP0CSR_IN_PKT_RDY (1 << 1) /* IN Packet Ready */ #define USB_EP0CSR_SENT_STALL (1 << 2) /* Sent STALL Handshake */ #define USB_EP0CSR_DATA_END (1 << 3) /* Data End */ #define USB_EP0CSR_SETUP_END (1 << 4) /* Setup Ends (RO) */ #define USB_EP0CSR_SEND_STALL (1 << 5) /* Send Stall Handshake to USB */ #define USB_EP0CSR_CLR_OUT (1 << 6) /* Clear OUT Packet Ready Bit */ #define USB_EP0CSR_CLR_SETUP_END (1 << 7) /* Clear Setup End Bit */ /***********************/ /* USB Host Controller */ /***********************/ #define USBH_BASE LH7A404_USBH_BASE #define USBH_CMDSTATUS __REG32(USBH_BASE + 0x08) /*******************/ /* AC97 Controller */ /*******************/ #define AC97_BASE LH7A404_AC97_BASE #define AC97_DR1 __REG32(AC97_BASE + 0x00) /* FIFO1 Data Register */ #define AC97_RXCR1 __REG32(AC97_BASE + 0x04) /* FIFO1 Receive Control Register */ #define AC97_TXCR1 __REG32(AC97_BASE + 0x08) /* FIFO1 Transmit Control Register */ #define AC97_SR1 __REG32(AC97_BASE + 0x0C) /* FIFO1 Status Register */ #define AC97_RISR1 __REG32(AC97_BASE + 0x10) /* FIFO1 Raw Interrupt Status Register */ #define AC97_ISR1 __REG32(AC97_BASE + 0x14) /* FIFO1 Interrupt Status Register */ #define AC97_IE1 __REG32(AC97_BASE + 0x18) /* FIFO1 Interrupt Enable Register */ #define AC97_DR2 __REG32(AC97_BASE + 0x20) /* FIFO2 Data Register */ #define AC97_RXCR2 __REG32(AC97_BASE + 0x24) /* FIFO2 Receive Control Register */ #define AC97_TXCR2 __REG32(AC97_BASE + 0x28) /* FIFO2 Transmit Control Register */ #define AC97_SR2 __REG32(AC97_BASE + 0x2C) /* FIFO2 Status Register */ #define AC97_RISR2 __REG32(AC97_BASE + 0x30) /* FIFO2 Raw Interrupt Status Register */ #define AC97_ISR2 __REG32(AC97_BASE + 0x34) /* FIFO2 Interrupt Status Register */ #define AC97_IE2 __REG32(AC97_BASE + 0x38) /* FIFO2 Interrupt Enable Register */ #define AC97_DR3 __REG32(AC97_BASE + 0x40) /* FIFO3 Data Register */ #define AC97_RXCR3 __REG32(AC97_BASE + 0x44) /* FIFO3 Receive Control Register */ #define AC97_TXCR3 __REG32(AC97_BASE + 0x48) /* FIFO3 Transmit Control Register */ #define AC97_SR3 __REG32(AC97_BASE + 0x4C) /* FIFO3 Status Register */ #define AC97_RISR3 __REG32(AC97_BASE + 0x50) /* FIFO3 Raw Interrupt Status Register */ #define AC97_ISR3 __REG32(AC97_BASE + 0x54) /* FIFO3 Interrupt Status Register */ #define AC97_IE3 __REG32(AC97_BASE + 0x58) /* FIFO3 Interrupt Enable Register */ #define AC97_DR4 __REG32(AC97_BASE + 0x60) /* FIFO4 Data Register */ #define AC97_RXCR4 __REG32(AC97_BASE + 0x64) /* FIFO4 Receive Control Register */ #define AC97_TXCR4 __REG32(AC97_BASE + 0x68) /* FIFO4 Transmit Control Register */ #define AC97_SR4 __REG32(AC97_BASE + 0x6C) /* FIFO4 Status Register */ #define AC97_RISR4 __REG32(AC97_BASE + 0x70) /* FIFO4 Raw Interrupt Status Register */ #define AC97_ISR4 __REG32(AC97_BASE + 0x74) /* FIFO4 Interrupt Status Register */ #define AC97_IE4 __REG32(AC97_BASE + 0x78) /* FIFO4 Interrupt Enable Register */ #define AC97_S1DATA __REG32(AC97_BASE + 0x80) /* Data Register on Slot 1 */ #define AC97_S2DATA __REG32(AC97_BASE + 0x84) /* Data Register on Slot 2 */ #define AC97_S12DATA __REG32(AC97_BASE + 0x88) /* Data Register on Slot 12 */ #define AC97_RGIS __REG32(AC97_BASE + 0x8C) /* Raw Global Interrupt Status */ #define AC97_GIS __REG32(AC97_BASE + 0x90) /* Global Interrupt Status */ #define AC97_GIEN __REG32(AC97_BASE + 0x94) /* Global Interrupt Enable */ #define AC97_GEOI __REG32(AC97_BASE + 0x98) /* Global Interrupt Clear */ #define AC97_GCR __REG32(AC97_BASE + 0x9C) /* Global Control Register */ #define AC97_RESET __REG32(AC97_BASE + 0xA0) /* Reset Control Register */ #define AC97_SYNC __REG32(AC97_BASE + 0xA4) /* Sync Control Register */ #define AC97_GCIS __REG32(AC97_BASE + 0xA8) /* Global Control FIFO Interrupt Status */ /*******************************/ /* Audio Codec Interface (ACI) */ /*******************************/ #define ACI_BASE LH7A404_ACI_BASE #define ACI_DATA __REG32(ACI_BASE + 0x00) /* Data Register */ #define ACI_CTL __REG32(ACI_BASE + 0x04) /* Control Register */ #define ACI_STATUS __REG32(ACI_BASE + 0x08) /* Status Register */ #define ACI_EOI __REG32(ACI_BASE + 0x0C) /* End-Of-Interrupt Register */ #define ACI_CLKDIV __REG32(ACI_BASE + 0x10) /* Clock Divider Register */ #define ACI_DATA_MASK 0xFF /* valid bits in Data Register */ /* Bits in Control Register */ #define ACI_CTL_TXEN (1 << 0) /* Transmit Enable */ #define ACI_CTL_RXEN (1 << 1) /* Receive Enable */ #define ACI_CTL_RXIE (1 << 2) /* Receive Interrupt Enable */ #define ACI_CTL_TXIE (1 << 3) /* Transmit Interrupt Enable */ #define ACI_CTL_LB (1 << 4) /* Loopback */ #define ACI_CTL_TXEPCLKEN (1 << 5) /* Transmit FIFO Empty Stop Clock Enable */ /* Bits in Status Register */ #define ACI_STATUS_RXFE (1 << 0) /* Receive FIFO Empty */ #define ACI_STATUS_TXFF (1 << 1) /* Transmit FIFO Full */ #define ACI_STATUS_RXFF (1 << 2) /* Receive FIFO Full */ #define ACI_STATUS_TXFE (1 << 3) /* Transmit FIFO Empty */ #define ACI_STATUS_RXI (1 << 4) /* Receive Interrupt */ #define ACI_STATUS_TXI (1 << 5) /* Transmit Interrupt */ #define ACI_STATUS_RXBUSY (1 << 6) /* Receive Busy */ #define ACI_STATUS_TXBUSY (1 << 7) /* Transmit Busy */ /*******************************/ /* Pulse Width Modulator (PWM) */ /*******************************/ #define PWM_BASE LH7A404_PWM_BASE #define PWM_TC2 __REG32(PWM_BASE + 0x00) /* PWM2 Terminal Count Register */ #define PWM_DC2 __REG32(PWM_BASE + 0x04) /* PWM2 Duty Cycle Register */ #define PWM_EN2 __REG32(PWM_BASE + 0x08) /* PWM2 Enable Register */ #define PWM_INV2 __REG32(PWM_BASE + 0x0C) /* PWM2 Invert Register */ #define PWM_SYNC2 __REG32(PWM_BASE + 0x10) /* PWM2 Synchronous Register */ #define PWM_TC3 __REG32(PWM_BASE + 0x20) /* PWM3 Terminal Count Register */ #define PWM_DC3 __REG32(PWM_BASE + 0x24) /* PWM3 Duty Cycle Register */ #define PWM_EN3 __REG32(PWM_BASE + 0x28) /* PWM3 Enable Register */ #define PWM_INV3 __REG32(PWM_BASE + 0x2C) /* PWM3 Invert Register */ /* Bits in PWM_ENx Register */ #define PWM_EN_ENABLE (1 << 0) /* PWM Enable */ /* Bits in PWM_INVx Register */ #define PWM_INV_INV (1 << 0) /* Invert PWM Output */ /* Bits in PWM_SYNC2 Register */ #define PWM_SYNC2_MODCE (1 << 0) /* PWM Mode Select */ #define PWM_SYNC2_SOURCE (1 << 1) /* PWM Sync Signal Source */ /*************************************/ /* Analog-to-Digital Converter (ADC) */ /*************************************/ #define ADC_BASE LH7A404_ADC_BASE #define ADC_HW __REG32(ADC_BASE + 0x00) /* High Word Register */ #define ADC_LW __REG32(ADC_BASE + 0x04) /* Low Word Register */ #define ADC_RR __REG32(ADC_BASE + 0x08) /* Results Register */ #define ADC_IM __REG32(ADC_BASE + 0x0C) /* Interrupt Mask Register */ #define ADC_PC __REG32(ADC_BASE + 0x10) /* Power Configuration Register */ #define ADC_GC __REG32(ADC_BASE + 0x14) /* General Configuration Register */ #define ADC_GS __REG32(ADC_BASE + 0x18) /* General Status Register */ #define ADC_IS __REG32(ADC_BASE + 0x1C) /* Raw Interrupt Status Register */ #define ADC_FS __REG32(ADC_BASE + 0x20) /* FIFO Status Register */ #define ADC_HWCB0 __REG32(ADC_BASE + 0x24) /* High Word Control Bank Register 0 */ #define ADC_HWCB1 __REG32(ADC_BASE + 0x28) /* High Word Control Bank Register 1 */ #define ADC_HWCB2 __REG32(ADC_BASE + 0x2C) /* High Word Control Bank Register 2 */ #define ADC_HWCB3 __REG32(ADC_BASE + 0x30) /* High Word Control Bank Register 3 */ #define ADC_HWCB4 __REG32(ADC_BASE + 0x34) /* High Word Control Bank Register 4 */ #define ADC_HWCB5 __REG32(ADC_BASE + 0x38) /* High Word Control Bank Register 5 */ #define ADC_HWCB6 __REG32(ADC_BASE + 0x3C) /* High Word Control Bank Register 6 */ #define ADC_HWCB7 __REG32(ADC_BASE + 0x40) /* High Word Control Bank Register 7 */ #define ADC_HWCB8 __REG32(ADC_BASE + 0x44) /* High Word Control Bank Register 8 */ #define ADC_HWCB9 __REG32(ADC_BASE + 0x48) /* High Word Control Bank Register 9 */ #define ADC_HWCB10 __REG32(ADC_BASE + 0x4C) /* High Word Control Bank Register 10 */ #define ADC_HWCB11 __REG32(ADC_BASE + 0x50) /* High Word Control Bank Register 11 */ #define ADC_HWCB12 __REG32(ADC_BASE + 0x54) /* High Word Control Bank Register 12 */ #define ADC_HWCB13 __REG32(ADC_BASE + 0x58) /* High Word Control Bank Register 13 */ #define ADC_HWCB14 __REG32(ADC_BASE + 0x5C) /* High Word Control Bank Register 14 */ #define ADC_HWCB15 __REG32(ADC_BASE + 0x60) /* High Word Control Bank Register 15 */ #define ADC_LWCB0 __REG32(ADC_BASE + 0x64) /* Low Word Control Bank Register 0 */ #define ADC_LWCB1 __REG32(ADC_BASE + 0x68) /* Low Word Control Bank Register 1 */ #define ADC_LWCB2 __REG32(ADC_BASE + 0x6C) /* Low Word Control Bank Register 2 */ #define ADC_LWCB3 __REG32(ADC_BASE + 0x70) /* Low Word Control Bank Register 3 */ #define ADC_LWCB4 __REG32(ADC_BASE + 0x74) /* Low Word Control Bank Register 4 */ #define ADC_LWCB5 __REG32(ADC_BASE + 0x78) /* Low Word Control Bank Register 5 */ #define ADC_LWCB6 __REG32(ADC_BASE + 0x7C) /* Low Word Control Bank Register 6 */ #define ADC_LWCB7 __REG32(ADC_BASE + 0x80) /* Low Word Control Bank Register 7 */ #define ADC_LWCB8 __REG32(ADC_BASE + 0x84) /* Low Word Control Bank Register 8 */ #define ADC_LWCB9 __REG32(ADC_BASE + 0x88) /* Low Word Control Bank Register 9 */ #define ADC_LWCB10 __REG32(ADC_BASE + 0x8C) /* Low Word Control Bank Register 10 */ #define ADC_LWCB11 __REG32(ADC_BASE + 0x90) /* Low Word Control Bank Register 11 */ #define ADC_LWCB12 __REG32(ADC_BASE + 0x94) /* Low Word Control Bank Register 12 */ #define ADC_LWCB13 __REG32(ADC_BASE + 0x98) /* Low Word Control Bank Register 13 */ #define ADC_LWCB14 __REG32(ADC_BASE + 0x9C) /* Low Word Control Bank Register 14 */ #define ADC_LWCB15 __REG32(ADC_BASE + 0xA0) /* Low Word Control Bank Register 15 */ #define ADC_IHWCTRL __REG32(ADC_BASE + 0xA4) /* Idle High Word Register */ #define ADC_ILWCTRL __REG32(ADC_BASE + 0xA8) /* Idle Low Word Register */ #define ADC_MIS __REG32(ADC_BASE + 0xAC) /* Masked Interrupt Status Register */ #define ADC_IC __REG32(ADC_BASE + 0xB0) /* Interrupt Clear Register */ /**************************************/ /* Keyboard and Mouse Interface (KMI) */ /**************************************/ #define KMI_BASE LH7A404_KMI_BASE #define KMI_CR __REG32(KMI_BASE + 0x00) /* KMI Control Register */ #define KMI_STAT __REG32(KMI_BASE + 0x04) /* KMI Status Register */ #define KMI_DATA __REG32(KMI_BASE + 0x08) /* KMI Data Register */ #define KMI_CLKDIV __REG32(KMI_BASE + 0x0C) /* KMI Clock Divider Register */ #define KMI_ISR __REG32(KMI_BASE + 0x10) /* KMI Interrupt Status Register */ /* Bits in KMI Control Register */ #define KMI_CR_FCL (1 << 0) /* Force KMI Clock LOW */ #define KMI_CR_FDL (1 << 1) /* Force KMI Data Line LOW */ #define KMI_CR_KMIEN (1 << 2) /* KMI Enable */ #define KMI_CR_TIE (1 << 3) /* Transmit Interrupt Enable */ #define KMI_CR_RIE (1 << 4) /* Receive Interrupt Enable */ #define KMI_CR_TYPE (1 << 5) /* Keyboard Type: 0 = PS2/AT (with line control bit) */ /* Bits in KMI Status Register */ #define KMI_STAT_DSTAT (1 << 0) /* Data Line Status */ #define KMI_STAT_CLKSTAT (1 << 1) /* Clock Line Status */ #define KMI_STAT_RXPARITY (1 << 2) /* Receive Parity */ #define KMI_STAT_RXBUSY (1 << 3) /* Receive Busy */ #define KMI_STAT_RXFULL (1 << 4) /* Receive Register Full */ #define KMI_STAT_TXBUSY (1 << 5) /* Transmit Busy */ #define KMI_STAT_TXEMPTY (1 << 6) /* Transmit Register Empty */ /* Bits in KMI Data Register */ #define KMI_DATA_MASK (0xFF << 0) /* KMI Data */ /* Bits in KMI Clock Divider Register */ #define KMI_CLKDIV_MASK (0x0F << 0) /* KMI Clock Divisor */ /* Bits in KMI Interrupt Status Register */ #define KMI_ISR_RXI (1 << 0) /* Receive interrupt */ #define KMI_ISR_TXI (1 << 1) /* Transmit interrupt */ #endif /* __LH7A404_H__ */
0.871094
1
code/RobotCDrivers/codatech-rfid-test2.c
trc492/Ftc2013RingItUp
0
1172
#pragma config(Sensor, S1, CTRFID, sensorI2CCustom9V) //*!!Code automatically generated by 'ROBOTC' configuration wizard !!*// /* * $Id: codatech-rfid-test2.c 127 2012-12-05 19:32:39Z xander $ */ /** * codatech-rfid.h provides an API for the Codatex RFID sensor. This program * demonstrates how to use that API to use the sensor in continuous mode. * * Changelog: * - 0.1: Initial release * - 0.2: Removed common.h include * * Credits: * - Big thanks to <NAME> for writing the initial drivers. * * License: You may use this code as you wish, provided you give credit where it's due. * * THIS CODE WILL ONLY WORK WITH ROBOTC VERSION 3.55 beta 2 AND HIGHER. * <NAME> (xander_at_botbench.com) * 20 february 2011 * version 0.2 */ #include "drivers/codatech-rfid.h" string transponderID; task main() { nNxtButtonTask = -2; nxtDisplayCenteredTextLine(0, "Codatex"); nxtDisplayCenteredBigTextLine(1, "RFID"); nxtDisplayCenteredTextLine(3, "Test 2"); nxtDisplayCenteredTextLine(5, "Connect sensor"); nxtDisplayCenteredTextLine(6, "to S1"); wait1Msec(2000); eraseDisplay(); nxtDisplayCenteredTextLine(3, "Start single"); nxtDisplayCenteredTextLine(4, "reading loop"); wait1Msec(2000); eraseDisplay(); // Set up the sensor for continuous readings. CTRFIDsetContinuous(CTRFID); // loop for transponder readings with continuous read function while(nNxtButtonPressed == kNoButton) { // read the transponder if (!CTRFIDreadTransponder(CTRFID, transponderID)) { eraseDisplay(); nxtDisplayTextLine(3, "Error reading"); nxtDisplayTextLine(4, "from sensor!"); wait10Msec(5000); StopAllTasks(); } nxtDisplayCenteredTextLine(3, "Transponder ID:"); nxtDisplayCenteredTextLine(4, "%s", transponderID); // Be sure to add about 200ms after each read // or you end up getting 0000000000 as a transponder address wait1Msec(200); } } /* * $Id: codatech-rfid-test2.c 127 2012-12-05 19:32:39Z xander $ */
1.53125
2
toolboxes/python/python_toolbox.h
roopchansinghv/gadgetron
1
1180
#pragma once #include "python_export.h" #include "log.h" #include <boost/python.hpp> namespace bp = boost::python; namespace Gadgetron { /// Initialize Python and NumPy. Called by each PythonFunction constructor EXPORTPYTHON void initialize_python(void); /// Initialize NumPy EXPORTPYTHON void initialize_numpy(void); /// Finalize Python, Called by user expclictly EXPORTPYTHON void finalize_python(void); /// Add a path to the PYTHONPATH EXPORTPYTHON void add_python_path(const std::string& path); /// Extracts the exception/traceback to build and return a std::string EXPORTPYTHON std::string pyerr_to_string(void); } // Include converters after declaring above functions namespace Gadgetron { /// Utility class for RAII handling of the Python GIL. Usage: /// /// GILLock lg; // at the top of a block /// class GILLock { public: GILLock() { gstate_ = PyGILState_Ensure(); } ~GILLock() { PyGILState_Release(gstate_); } private: // noncopyable GILLock(const GILLock &); GILLock &operator=(const GILLock &); PyGILState_STATE gstate_; }; } #include "python_converters.h" namespace Gadgetron { /// Base class for templated PythonFunction class. Do not use directly. class PythonFunctionBase { protected: PythonFunctionBase(const std::string& module, const std::string& funcname) { initialize_python(); // ensure Python and NumPy are initialized GILLock lg; // Lock the GIL, releasing at the end of constructor try { // import the module and load the function bp::object mod(bp::import(module.c_str())); fn_ = mod.attr(funcname.c_str()); } catch (const bp::error_already_set&) { std::string err = pyerr_to_string(); GERROR(err.c_str()); throw std::runtime_error(err); } } bp::object fn_; }; /// PythonFunction for multiple return types (std::tuple) template <typename... ReturnTypes> class PythonFunction : public PythonFunctionBase { public: typedef std::tuple<ReturnTypes...> TupleType; PythonFunction(const std::string& module, const std::string& funcname) : PythonFunctionBase(module, funcname) { // register the tuple return type converter register_converter<TupleType>(); } template <typename... TS> TupleType operator()(const TS&... args) { // register type converter for each parameter type register_converter<TS...>(); GILLock lg; // lock GIL and release at function exit try { bp::object res = fn_(args...); return bp::extract<TupleType>(res); } catch (bp::error_already_set const &) { std::string err = pyerr_to_string(); GERROR(err.c_str()); throw std::runtime_error(err); } } }; /// PythonFunction for a single return type template <typename RetType> class PythonFunction<RetType> : public PythonFunctionBase { public: PythonFunction(const std::string& module, const std::string& funcname) : PythonFunctionBase(module, funcname) { // register the return type converter register_converter<RetType>(); } template <typename... TS> RetType operator()(const TS&... args) { // register type converter for each parameter type register_converter<TS...>(); GILLock lg; // lock GIL and release at function exit try { bp::object res = fn_(args...); return bp::extract<RetType>(res); } catch (bp::error_already_set const &) { std::string err = pyerr_to_string(); GERROR(err.c_str()); throw std::runtime_error(err); } } }; /// PythonFunction for a single return type, special for bp::object type template <> class PythonFunction<bp::object> : public PythonFunctionBase { public: PythonFunction(const std::string& module, const std::string& funcname) : PythonFunctionBase(module, funcname) { } template <typename... TS> bp::object operator()(const TS&... args) { // register type converter for each parameter type register_converter<TS...>(); GILLock lg; // lock GIL and release at function exit try { bp::object res = fn_(args...); return res; } catch (bp::error_already_set const &) { std::string err = pyerr_to_string(); GERROR(err.c_str()); throw std::runtime_error(err); } } }; /// PythonFunction returning nothing template <> class PythonFunction<> : public PythonFunctionBase { public: PythonFunction(const std::string& module, const std::string& funcname) : PythonFunctionBase(module, funcname) {} template <typename... TS> void operator()(const TS&... args) { // register type converter for each parameter type register_converter<TS...>(); GILLock lg; // lock GIL and release at function exit try { bp::object res = fn_(args...); } catch (bp::error_already_set const &) { std::string err = pyerr_to_string(); GERROR(err.c_str()); throw std::runtime_error(err); } } }; } namespace boost { namespace python { EXPORTPYTHON bool hasattr(object o, const char* name); } }
1.609375
2
AnalyticSDWebImage/SDWebImage/SDWebImageDefine.h
ZpFate/AnalyticSDWebImage
1
1188
/* * This file is part of the SDWebImage package. * (c) <NAME> <<EMAIL>> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import "SDWebImageCompat.h" typedef void(^SDWebImageNoParamsBlock)(void); typedef NSString * SDWebImageContextOption NS_EXTENSIBLE_STRING_ENUM; typedef NSDictionary<SDWebImageContextOption, id> SDWebImageContext; typedef NSMutableDictionary<SDWebImageContextOption, id> SDWebImageMutableContext; #pragma mark - Image scale /** Return the image scale factor for the specify key, supports file name and url key. This is the built-in way to check the scale factor when we have no context about it. Because scale factor is not stored in image data (It's typically from filename). However, you can also provide custom scale factor as well, see `SDWebImageContextImageScaleFactor`. @param key The image cache key @return The scale factor for image */ FOUNDATION_EXPORT CGFloat SDImageScaleFactorForKey(NSString * _Nullable key); /** Scale the image with the scale factor for the specify key. If no need to scale, return the original image. This works for `UIImage`(UIKit) or `NSImage`(AppKit). And this function also preserve the associated value in `UIImage+Metadata.h`. @note This is actually a convenience function, which firstlly call `SDImageScaleFactorForKey` and then call `SDScaledImageForScaleFactor`, kept for backward compatibility. @param key The image cache key @param image The image @return The scaled image */ FOUNDATION_EXPORT UIImage * _Nullable SDScaledImageForKey(NSString * _Nullable key, UIImage * _Nullable image); /** Scale the image with the scale factor. If no need to scale, return the original image. This works for `UIImage`(UIKit) or `NSImage`(AppKit). And this function also preserve the associated value in `UIImage+Metadata.h`. @param scale The image scale factor @param image The image @return The scaled image */ FOUNDATION_EXPORT UIImage * _Nullable SDScaledImageForScaleFactor(CGFloat scale, UIImage * _Nullable image); #pragma mark - WebCache Options /// WebCache options typedef NS_OPTIONS(NSUInteger, SDWebImageOptions) { /** * By default, when a URL fail to be downloaded, the URL is blacklisted so the library won't keep trying. * This flag disable this blacklisting. * 如果一个url加载图片失败会加入黑名单 不在重试, 设置该选项取消黑名单限制 */ SDWebImageRetryFailed = 1 << 0, /** * By default, image downloads are started during UI interactions, this flags disable this feature, * leading to delayed download on UIScrollView deceleration for instance. * 默认情况是在UI交互的时候下载图片 * 低优先级, 设置该选项在UIScrollView滑动减速时才开始下载图片 */ SDWebImageLowPriority = 1 << 1, /** * This flag enables progressive download, the image is displayed progressively during download as a browser would do. * By default, the image is only displayed once completely downloaded. * 设置该选项 图片会逐渐展示,像浏览器一样 * 默认是图片下载完成展示 */ SDWebImageProgressiveLoad = 1 << 2, /** * Even if the image is cached, respect the HTTP response cache control, and refresh the image from remote location if needed. * The disk caching will be handled by NSURLCache instead of SDWebImage leading to slight performance degradation. * This option helps deal with images changing behind the same request URL, e.g. Facebook graph api profile pics. * If a cached image is refreshed, the completion block is called once with the cached image and again with the final image. * * Use this flag only if you can't make your URLs static with embedded cache busting parameter. * 一个图片缓存了,还是会重新请求.并且缓存侧略依据NSURLCache而不是SDWebImage.URL不变,图片会更新时使用 * 需要服务端支持cache control */ SDWebImageRefreshCached = 1 << 3, /** * In iOS 4+, continue the download of the image if the app goes to background. This is achieved by asking the system for * extra time in background to let the request finish. If the background task expires the operation will be cancelled. * 启动后台下载 */ SDWebImageContinueInBackground = 1 << 4, /** * Handles cookies stored in NSHTTPCookieStore by setting * NSMutableURLRequest.HTTPShouldHandleCookies = YES; * 可以控制存在NSHTTPCookieStore的cookies */ SDWebImageHandleCookies = 1 << 5, /** * Enable to allow untrusted SSL certificates. * Useful for testing purposes. Use with caution in production. * 允许不安全的SSL证书,在正式环境中慎用 */ SDWebImageAllowInvalidSSLCertificates = 1 << 6, /** * By default, images are loaded in the order in which they were queued. This flag moves them to * the front of the queue. * 高优先级下载 会把该任务放置到队列前面 */ SDWebImageHighPriority = 1 << 7, /** * By default, placeholder images are loaded while the image is loading. This flag will delay the loading * of the placeholder image until after the image has finished loading. * 默认情况下,占位图会在图片下载的时候显示.这个flag开启会延迟占位图显示的时间,等到图片下载完成之后才会显示占位图 */ SDWebImageDelayPlaceholder = 1 << 8, /** * We usually don't apply transform on animated images as most transformers could not manage animated images. * Use this flag to transform them anyway. * 我们通常不会对变换动图,因为大多数变缓都无法管理动图。 ?? */ SDWebImageTransformAnimatedImage = 1 << 9, /** * By default, image is added to the imageView after download. But in some cases, we want to * have the hand before setting the image (apply a filter or add it with cross-fade animation for instance) * Use this flag if you want to manually set the image in the completion when success * (默认情况下,图像在下载后添加到imageView。 * 但在某些情况下,我们希望在设置图像之前可以手动修改动画 */ SDWebImageAvoidAutoSetImage = 1 << 10, /** * By default, images are decoded respecting their original size. On iOS, this flag will scale down the * images to a size compatible with the constrained memory of devices. * This flag take no effect if `SDWebImageAvoidDecodeImage` is set. And it will be ignored if `SDWebImageProgressiveLoad` is set. * 默认情况下,图像将根据其原始大小进行解码。此标志将图像缩小到与设备的受限内存兼容的大小; * 主要用于加载大图片时避免高内存导致闪退 */ SDWebImageScaleDownLargeImages = 1 << 11, /** * By default, we do not query image data when the image is already cached in memory. This mask can force to query image data at the same time. However, this query is asynchronously unless you specify `SDWebImageQueryMemoryDataSync` * 默认情况下,当图像已经缓存在内存中时,我们不查询图像数据。 * 此掩码可以强制同时查询图像数据。除非指定“SDWebImageQueryMemoryDataSync”,否则此查询是异步的` */ SDWebImageQueryMemoryData = 1 << 12, /** * By default, when you only specify `SDWebImageQueryMemoryData`, we query the memory image data asynchronously. Combined this mask as well to query the memory image data synchronously. * @note Query data synchronously is not recommend, unless you want to ensure the image is loaded in the same runloop to avoid flashing during cell reusing. * (默认情况下,当您仅指定“SDWebImageQueryMemoryData”时,我们将异步查询内存映像数据。结合该掩模,实现了对内存图像数据的同步查询。) */ SDWebImageQueryMemoryDataSync = 1 << 13, /** * By default, when the memory cache miss, we query the disk cache asynchronously. This mask can force to query disk cache (when memory cache miss) synchronously. * @note These 3 query options can be combined together. For the full list about these masks combination, see wiki page. * @note Query data synchronously is not recommend, unless you want to ensure the image is loaded in the same runloop to avoid flashing during cell reusing. * (默认情况下,当内存缓存丢失时,我们异步查询磁盘缓存。此掩码可以强制同步查询磁盘缓存(当内存缓存丢失时)。 */ SDWebImageQueryDiskDataSync = 1 << 14, /** * By default, when the cache missed, the image is load from the loader. This flag can prevent this to load from cache only. * (默认情况下,当缓存丢失时,从加载程序加载图像。 * 此标志可设置为仅从缓存加载此文件 */ SDWebImageFromCacheOnly = 1 << 15, /** * By default, we query the cache before the image is load from the loader. This flag can prevent this to load from loader only. * 默认情况下,我们在从加载程序加载图像之前查询缓存。此标志可防止仅从加载程序加载此文件。 */ SDWebImageFromLoaderOnly = 1 << 16, /** * By default, when you use `SDWebImageTransition` to do some view transition after the image load finished, this transition is only applied for image download from the network. This mask can force to apply view transition for memory and disk cache as well. * 默认情况下,当使用“SDWebImageTransition”在映像加载完成后执行某些视图转换时,此转换仅在管理器的回调是异步的(从网络或磁盘缓存查询)时应用于映像.此掩码可以强制对任何情况应用视图转换,如内存缓存查询或同步磁盘缓存查询 */ SDWebImageForceTransition = 1 << 17, /** * By default, we will decode the image in the background during cache query and download from the network. This can help to improve performance because when rendering image on the screen, it need to be firstly decoded. But this happen on the main queue by Core Animation. * However, this process may increase the memory usage as well. If you are experiencing a issue due to excessive memory consumption, This flag can prevent decode the image. * 默认情况下,我们将在缓存查询和从网络下载期间在后台解码图像。这有助于提高性能,因为在屏幕上渲染图像时,需要首先对其进行解码。但是,这个过程也会增加内存的使用。如果由于内存消耗过多而遇到问题,此标志可能会阻止对图像进行解码。 */ SDWebImageAvoidDecodeImage = 1 << 18, /** * By default, we decode the animated image. This flag can force decode the first frame only and produece the static image. * 默认情况下,我们解码动画图像。此标志只能强制解码第一帧并生成静态图像 */ SDWebImageDecodeFirstFrameOnly = 1 << 19, /** * By default, for `SDAnimatedImage`, we decode the animated image frame during rendering to reduce memory usage. However, you can specify to preload all frames into memory to reduce CPU usage when the animated image is shared by lots of imageViews. * This will actually trigger `preloadAllAnimatedImageFrames` in the background queue(Disk Cache & Download only). * 默认情况下,对于“SDAnimatedImage”,我们在渲染期间解码动画图像帧以减少内存使用。但是,您可以指定将所有帧预加载到内存中,以在大量ImageView共享动画图像时减少CPU使用量。这实际上会触发后台队列中的“prelodallanimatedImageFrames”(仅限于磁盘缓存和下载) */ SDWebImagePreloadAllFrames = 1 << 20 }; #pragma mark - Context Options /** A String to be used as the operation key for view category to store the image load operation. This is used for view instance which supports different image loading process. If nil, will use the class name as operation key. (NSString *) */ FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextSetImageOperationKey; /** A SDWebImageManager instance to control the image download and cache process using in UIImageView+WebCache category and likes. If not provided, use the shared manager (SDWebImageManager *) */ FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextCustomManager; /** A id<SDImageTransformer> instance which conforms `SDImageTransformer` protocol. It's used for image transform after the image load finished and store the transformed image to cache. If you provide one, it will ignore the `transformer` in manager and use provided one instead. (id<SDImageTransformer>) */ FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextImageTransformer; /** A CGFloat raw value which specify the image scale factor. The number should be greater than or equal to 1.0. If not provide or the number is invalid, we will use the cache key to specify the scale factor. (NSNumber) */ FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextImageScaleFactor; /** A SDImageCacheType raw value which specify the cache type when the image has just been downloaded and will be stored to the cache. Specify `SDImageCacheTypeNone` to disable cache storage; `SDImageCacheTypeDisk` to store in disk cache only; `SDImageCacheTypeMemory` to store in memory only. And `SDImageCacheTypeAll` to store in both memory cache and disk cache. If not provide or the value is invalid, we will use `SDImageCacheTypeAll`. (NSNumber) */ FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextStoreCacheType; /** A Class object which the instance is a `UIImage/NSImage` subclass and adopt `SDAnimatedImage` protocol. We will call `initWithData:scale:options:` to create the instance (or `initWithAnimatedCoder:scale:` when using progressive download) . If the instance create failed, fallback to normal `UIImage/NSImage`. This can be used to improve animated images rendering performance (especially memory usage on big animated images) with `SDAnimatedImageView` (Class). */ FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextAnimatedImageClass; /** A id<SDWebImageDownloaderRequestModifier> instance to modify the image download request. It's used for downloader to modify the original request from URL and options. If you provide one, it will ignore the `requestModifier` in downloader and use provided one instead. (id<SDWebImageDownloaderRequestModifier>) */ FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextDownloadRequestModifier; /** A id<SDWebImageCacheKeyFilter> instance to convert an URL into a cache key. It's used when manager need cache key to use image cache. If you provide one, it will ignore the `cacheKeyFilter` in manager and use provided one instead. (id<SDWebImageCacheKeyFilter>) */ FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextCacheKeyFilter; /** A id<SDWebImageCacheSerializer> instance to convert the decoded image, the source downloaded data, to the actual data. It's used for manager to store image to the disk cache. If you provide one, it will ignore the `cacheSerializer` in manager and use provided one instead. (id<SDWebImageCacheSerializer>) */ FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextCacheSerializer;
0.980469
1
Userland/Libraries/LibWeb/SVG/AttributeParser.h
gSpera/serenity
2
1196
/* * Copyright (c) 2020, <NAME> <<EMAIL>> * Copyright (c) 2022, <NAME> <<EMAIL>> * * SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <AK/String.h> #include <AK/Vector.h> #include <LibGfx/Point.h> namespace Web::SVG { enum class PathInstructionType { Move, ClosePath, Line, HorizontalLine, VerticalLine, Curve, SmoothCurve, QuadraticBezierCurve, SmoothQuadraticBezierCurve, EllipticalArc, Invalid, }; struct PathInstruction { PathInstructionType type; bool absolute; Vector<float> data; }; class AttributeParser final { public: ~AttributeParser() = default; static Optional<float> parse_coordinate(StringView input); static Optional<float> parse_length(StringView input); static Optional<float> parse_positive_length(StringView input); static Vector<Gfx::FloatPoint> parse_points(StringView input); static Vector<PathInstruction> parse_path_data(StringView input); private: AttributeParser(StringView source); void parse_drawto(); void parse_moveto(); void parse_closepath(); void parse_lineto(); void parse_horizontal_lineto(); void parse_vertical_lineto(); void parse_curveto(); void parse_smooth_curveto(); void parse_quadratic_bezier_curveto(); void parse_smooth_quadratic_bezier_curveto(); void parse_elliptical_arc(); float parse_length(); float parse_coordinate(); Vector<float> parse_coordinate_pair(); Vector<float> parse_coordinate_sequence(); Vector<Vector<float>> parse_coordinate_pair_sequence(); Vector<float> parse_coordinate_pair_double(); Vector<float> parse_coordinate_pair_triplet(); Vector<float> parse_elliptical_arg_argument(); void parse_whitespace(bool must_match_once = false); void parse_comma_whitespace(); float parse_fractional_constant(); float parse_number(); float parse_flag(); // -1 if negative, +1 otherwise int parse_sign(); bool match_whitespace() const; bool match_comma_whitespace() const; bool match_coordinate() const; bool match_length() const; bool match(char c) const { return !done() && ch() == c; } bool done() const { return m_cursor >= m_source.length(); } char ch() const { return m_source[m_cursor]; } char consume() { return m_source[m_cursor++]; } StringView m_source; size_t m_cursor { 0 }; Vector<PathInstruction> m_instructions; }; }
1.492188
1
Source/ThunderBeast/QuakeToonProto1/linux/rw_svgalib.c
1vanK/Urho3DQuake2
7
1204
/* Copyright (C) 1997-2001 Id Software, 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. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ /* ** RW_SVGALBI.C ** ** This file contains ALL Linux specific stuff having to do with the ** software refresh. When a port is being made the following functions ** must be implemented by the port: ** ** SWimp_EndFrame ** SWimp_Init ** SWimp_InitGraphics ** SWimp_SetPalette ** SWimp_Shutdown ** SWimp_SwitchFullscreen */ #include <termios.h> #include <sys/ioctl.h> #include <sys/stat.h> #include <sys/vt.h> #include <stdarg.h> #include <stdio.h> #include <signal.h> #include <sys/mman.h> #include <asm/io.h> #include "vga.h" #include "vgakeyboard.h" #include "vgamouse.h" #include "../ref_soft/r_local.h" #include "../client/keys.h" #include "../linux/rw_linux.h" /*****************************************************************************/ int VGA_width, VGA_height, VGA_rowbytes, VGA_bufferrowbytes, VGA_planar; byte *VGA_pagebase; char *framebuffer_ptr; void VGA_UpdatePlanarScreen (void *srcbuffer); int num_modes; vga_modeinfo *modes; int current_mode; // Console variables that we need to access from this module /*****************************************************************************/ void VID_InitModes(void) { int i; // get complete information on all modes num_modes = vga_lastmodenumber()+1; modes = malloc(num_modes * sizeof(vga_modeinfo)); for (i=0 ; i<num_modes ; i++) { if (vga_hasmode(i)) memcpy(&modes[i], vga_getmodeinfo(i), sizeof (vga_modeinfo)); else modes[i].width = 0; // means not available } // filter for modes i don't support for (i=0 ; i<num_modes ; i++) { if (modes[i].bytesperpixel != 1 && modes[i].colors != 256) modes[i].width = 0; } for (i = 0; i < num_modes; i++) if (modes[i].width) ri.Con_Printf(PRINT_ALL, "mode %d: %d %d\n", modes[i].width, modes[i].height); } /* ** SWimp_Init ** ** This routine is responsible for initializing the implementation ** specific stuff in a software rendering subsystem. */ int SWimp_Init( void *hInstance, void *wndProc ) { vga_init(); VID_InitModes(); return true; } int get_mode(int width, int height) { int i; int ok, match; for (i=0 ; i<num_modes ; i++) if (modes[i].width && modes[i].width == width && modes[i].height == height) break; if (i==num_modes) return -1; // not found return i; } /* ** SWimp_InitGraphics ** ** This initializes the software refresh's implementation specific ** graphics subsystem. In the case of Windows it creates DIB or ** DDRAW surfaces. ** ** The necessary width and height parameters are grabbed from ** vid.width and vid.height. */ static qboolean SWimp_InitGraphics( qboolean fullscreen ) { int bsize, zsize, tsize; SWimp_Shutdown(); current_mode = get_mode(vid.width, vid.height); if (current_mode < 0) { ri.Con_Printf (PRINT_ALL, "Mode %d %d not found\n", vid.width, vid.height); return false; // mode not found } // let the sound and input subsystems know about the new window ri.Vid_NewWindow (vid.width, vid.height); ri.Con_Printf (PRINT_ALL, "Setting VGAMode: %d\n", current_mode ); // Cvar_SetValue ("vid_mode", (float)modenum); VGA_width = modes[current_mode].width; VGA_height = modes[current_mode].height; VGA_planar = modes[current_mode].bytesperpixel == 0; VGA_rowbytes = modes[current_mode].linewidth; vid.rowbytes = modes[current_mode].linewidth; if (VGA_planar) { VGA_bufferrowbytes = modes[current_mode].linewidth * 4; vid.rowbytes = modes[current_mode].linewidth*4; } // get goin' vga_setmode(current_mode); VGA_pagebase = framebuffer_ptr = (char *) vga_getgraphmem(); // if (vga_setlinearaddressing()>0) // framebuffer_ptr = (char *) vga_getgraphmem(); if (!framebuffer_ptr) Sys_Error("This mode isn't hapnin'\n"); vga_setpage(0); vid.buffer = malloc(vid.rowbytes * vid.height); if (!vid.buffer) Sys_Error("Unabled to alloc vid.buffer!\n"); return true; } /* ** SWimp_EndFrame ** ** This does an implementation specific copy from the backbuffer to the ** front buffer. In the Win32 case it uses BitBlt or BltFast depending ** on whether we're using DIB sections/GDI or DDRAW. */ void SWimp_EndFrame (void) { if (!vga_oktowrite()) return; // can't update screen if it's not active // if (vid_waitforrefresh.value) // vga_waitretrace(); if (VGA_planar) VGA_UpdatePlanarScreen (vid.buffer); else { int total = vid.rowbytes * vid.height; int offset; for (offset=0;offset<total;offset+=0x10000) { vga_setpage(offset/0x10000); memcpy(framebuffer_ptr, vid.buffer + offset, ((total-offset>0x10000)?0x10000:(total-offset))); } } } /* ** SWimp_SetMode */ rserr_t SWimp_SetMode( int *pwidth, int *pheight, int mode, qboolean fullscreen ) { rserr_t retval = rserr_ok; ri.Con_Printf (PRINT_ALL, "setting mode %d:", mode ); if ( !ri.Vid_GetModeInfo( pwidth, pheight, mode ) ) { ri.Con_Printf( PRINT_ALL, " invalid mode\n" ); return rserr_invalid_mode; } ri.Con_Printf( PRINT_ALL, " %d %d\n", *pwidth, *pheight); if ( !SWimp_InitGraphics( false ) ) { // failed to set a valid mode in windowed mode return rserr_invalid_mode; } R_GammaCorrectAndSetPalette( ( const unsigned char * ) d_8to24table ); return retval; } /* ** SWimp_SetPalette ** ** System specific palette setting routine. A NULL palette means ** to use the existing palette. The palette is expected to be in ** a padded 4-byte xRGB format. */ void SWimp_SetPalette( const unsigned char *palette ) { static int tmppal[256*3]; const unsigned char *pal; int *tp; int i; if ( !palette ) palette = ( const unsigned char * ) sw_state.currentpalette; if (vga_getcolors() == 256) { tp = tmppal; pal = palette; for (i=0 ; i < 256 ; i++, pal += 4, tp += 3) { tp[0] = pal[0] >> 2; tp[1] = pal[1] >> 2; tp[2] = pal[2] >> 2; } if (vga_oktowrite()) vga_setpalvec(0, 256, tmppal); } } /* ** SWimp_Shutdown ** ** System specific graphics subsystem shutdown routine. Destroys ** DIBs or DDRAW surfaces as appropriate. */ void SWimp_Shutdown( void ) { if (vid.buffer) { free(vid.buffer); vid.buffer = NULL; } vga_setmode(TEXT); } /* ** SWimp_AppActivate */ void SWimp_AppActivate( qboolean active ) { } //=============================================================================== /* ================ Sys_MakeCodeWriteable ================ */ void Sys_MakeCodeWriteable (unsigned long startaddr, unsigned long length) { int r; unsigned long addr; int psize = getpagesize(); addr = (startaddr & ~(psize-1)) - psize; // fprintf(stderr, "writable code %lx(%lx)-%lx, length=%lx\n", startaddr, // addr, startaddr+length, length); r = mprotect((char*)addr, length + startaddr - addr + psize, 7); if (r < 0) Sys_Error("Protection change failed\n"); }
1.382813
1
extras/RightTrack/rt_process_instrumentation.h
judajake/kwiver
0
1212
/*ckwg +29 * Copyright 2016 by Kitware, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither name of Kitware, Inc. nor the names of any 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 AUTHORS 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 f * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef KWIVER_EXTRAS_RT_PROCESS_INSTRUMENTATION_H #define KWIVER_EXTRAS_RT_PROCESS_INSTRUMENTATION_H #include "righttrack_plugin_export.h" #include <sprokit/pipeline/process_instrumentation.h> #include <RightTrack/BoundedEvent.h> #include <memory> namespace sprokit { // ---------------------------------------------------------------- /** * @brief Process instrumentation using RightTrack tool. * */ class RIGHTTRACK_PLUGIN_NO_EXPORT rt_process_instrumentation : public process_instrumentation { public: // -- CONSTRUCTORS -- rt_process_instrumentation(); virtual ~rt_process_instrumentation(); virtual void configure( kwiver::vital::config_block_sptr const config ); virtual kwiver::vital::config_block_sptr get_configuration() const; virtual void start_init_processing( std::string const& data ); virtual void stop_init_processing(); virtual void start_reset_processing( std::string const& data ); virtual void stop_reset_processing(); virtual void start_flush_processing( std::string const& data ); virtual void stop_flush_processing(); virtual void start_step_processing( std::string const& data ); virtual void stop_step_processing(); virtual void start_configure_processing( std::string const& data ); virtual void stop_configure_processing(); virtual void start_reconfigure_processing( std::string const& data ); virtual void stop_reconfigure_processing(); private: std::unique_ptr< RightTrack::BoundedEvent > m_init_event; std::unique_ptr< RightTrack::BoundedEvent > m_reset_event; std::unique_ptr< RightTrack::BoundedEvent > m_flush_event; std::unique_ptr< RightTrack::BoundedEvent > m_step_event; std::unique_ptr< RightTrack::BoundedEvent > m_configure_event; std::unique_ptr< RightTrack::BoundedEvent > m_reconfigure_event; }; // end class rt_process_instrumentation } // end namespace #endif // KWIVER_EXTRAS_RT_PROCESS_INSTRUMENTATION_H
1.3125
1
cpp/src/io/orc/timezone.h
isVoid/cudf
1
1220
/* * Copyright (c) 2019, NVIDIA 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. */ #pragma once #include <stdint.h> #include <string> #include <vector> namespace cudf { namespace io { /** * @brief Creates a transition table to convert ORC timestamps to UTC * * @param[out] table output table (1st entry = gmtOffset, 2 int64_t per transition, last 800 *transitions repeat forever with 400 year cycle) * @param[in] timezone_name standard timezone name (for example, "US/Pacific") * * @return true if successful, false if failed to find/parse the timezone information **/ bool BuildTimezoneTransitionTable(std::vector<int64_t> &table, const std::string &timezone_name); } // namespace io } // namespace cudf
1.453125
1
src/apps/relay/dbdrivers/dbd_pgsql.c
huzhenyu/coturn
1
1228
/* * Copyright (C) 2011, 2012, 2013 Citrix Systems * Copyright (C) 2014 <NAME>. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the project 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 PROJECT 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 PROJECT 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. */ #include "../mainrelay.h" #include "dbd_pgsql.h" #if !defined(TURN_NO_PQ) #include <libpq-fe.h> /////////////////////////////////////////////////////////////////////////////////////////////////////////// static int donot_print_connection_success = 0; static PGconn *get_pqdb_connection(void) { persistent_users_db_t *pud = get_persistent_users_db(); PGconn *pqdbconnection = (PGconn*)pthread_getspecific(connection_key); if(pqdbconnection) { ConnStatusType status = PQstatus(pqdbconnection); if(status != CONNECTION_OK) { PQfinish(pqdbconnection); pqdbconnection = NULL; (void) pthread_setspecific(connection_key, pqdbconnection); } } if(!pqdbconnection) { char *errmsg=NULL; PQconninfoOption *co = PQconninfoParse(pud->userdb, &errmsg); if(!co) { if(errmsg) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Cannot open PostgreSQL DB connection <%s>, connection string format error: %s\n",pud->userdb,errmsg); turn_free(errmsg,strlen(errmsg)+1); } else { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Cannot open PostgreSQL DB connection: <%s>, unknown connection string format error\n",pud->userdb); } } else { PQconninfoFree(co); if(errmsg) turn_free(errmsg,strlen(errmsg)+1); pqdbconnection = PQconnectdb(pud->userdb); if(!pqdbconnection) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Cannot open PostgreSQL DB connection: <%s>, runtime error\n",pud->userdb); } else { ConnStatusType status = PQstatus(pqdbconnection); if(status != CONNECTION_OK) { PQfinish(pqdbconnection); pqdbconnection = NULL; TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Cannot open PostgreSQL DB connection: <%s>, runtime error\n",pud->userdb); } else if(!donot_print_connection_success){ TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "PostgreSQL DB connection success: %s\n",pud->userdb); donot_print_connection_success = 1; } } } if(pqdbconnection) { (void) pthread_setspecific(connection_key, pqdbconnection); } } return pqdbconnection; } /////////////////////////////////////////////////////////////////////////////////////////////////////////// static int pgsql_get_auth_secrets(secrets_list_t *sl, u08bits *realm) { int ret = -1; PGconn * pqc = get_pqdb_connection(); if(pqc) { char statement[TURN_LONG_STRING_SIZE]; snprintf(statement,sizeof(statement)-1,"select value from turn_secret where realm='%s'",realm); PGresult *res = PQexec(pqc, statement); if(!res || (PQresultStatus(res) != PGRES_TUPLES_OK)) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Error retrieving PostgreSQL DB information: %s\n",PQerrorMessage(pqc)); } else { int i = 0; for(i=0;i<PQntuples(res);i++) { char *kval = PQgetvalue(res,i,0); if(kval) { add_to_secrets_list(sl,kval); } } ret = 0; } if(res) { PQclear(res); } } return ret; } static int pgsql_get_user_key(u08bits *usname, u08bits *realm, hmackey_t key) { int ret = -1; PGconn * pqc = get_pqdb_connection(); if(pqc) { char statement[TURN_LONG_STRING_SIZE]; snprintf(statement,sizeof(statement),"select hmackey from turnusers_lt where name='%s' and realm='%s'",usname,realm); PGresult *res = PQexec(pqc, statement); if(!res || (PQresultStatus(res) != PGRES_TUPLES_OK) || (PQntuples(res)!=1)) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Error retrieving PostgreSQL DB information: %s\n",PQerrorMessage(pqc)); } else { char *kval = PQgetvalue(res,0,0); int len = PQgetlength(res,0,0); if(kval) { size_t sz = get_hmackey_size(SHATYPE_DEFAULT); if(((size_t)len<sz*2)||(strlen(kval)<sz*2)) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Wrong key format: %s, user %s\n",kval,usname); } else if(convert_string_key_to_binary(kval, key, sz)<0) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Wrong key: %s, user %s\n",kval,usname); } else { ret = 0; } } else { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Wrong hmackey data for user %s: NULL\n",usname); } } if(res) PQclear(res); } return ret; } static int pgsql_get_oauth_key(const u08bits *kid, oauth_key_data_raw *key) { int ret = -1; char statement[TURN_LONG_STRING_SIZE]; snprintf(statement,sizeof(statement),"select ikm_key,timestamp,lifetime,as_rs_alg from oauth_key where kid='%s'",(const char*)kid); PGconn * pqc = get_pqdb_connection(); if(pqc) { PGresult *res = PQexec(pqc, statement); if(!res || (PQresultStatus(res) != PGRES_TUPLES_OK) || (PQntuples(res)!=1)) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Error retrieving PostgreSQL DB information: %s\n",PQerrorMessage(pqc)); } else { STRCPY(key->ikm_key,PQgetvalue(res,0,0)); key->timestamp = (u64bits)strtoll(PQgetvalue(res,0,1),NULL,10); key->lifetime = (u32bits)strtol(PQgetvalue(res,0,2),NULL,10); STRCPY(key->as_rs_alg,PQgetvalue(res,0,3)); STRCPY(key->kid,kid); ret = 0; } if(res) { PQclear(res); } } return ret; } static int pgsql_list_oauth_keys(secrets_list_t *kids,secrets_list_t *teas,secrets_list_t *tss,secrets_list_t *lts) { oauth_key_data_raw key_; oauth_key_data_raw *key=&key_; int ret = -1; char statement[TURN_LONG_STRING_SIZE]; snprintf(statement,sizeof(statement),"select ikm_key,timestamp,lifetime,as_rs_alg,kid from oauth_key order by kid"); PGconn * pqc = get_pqdb_connection(); if(pqc) { PGresult *res = PQexec(pqc, statement); if(!res || (PQresultStatus(res) != PGRES_TUPLES_OK)) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Error retrieving PostgreSQL DB information: %s\n",PQerrorMessage(pqc)); } else { int i = 0; for(i=0;i<PQntuples(res);i++) { STRCPY(key->ikm_key,PQgetvalue(res,i,0)); key->timestamp = (u64bits)strtoll(PQgetvalue(res,i,1),NULL,10); key->lifetime = (u32bits)strtol(PQgetvalue(res,i,2),NULL,10); STRCPY(key->as_rs_alg,PQgetvalue(res,i,3)); STRCPY(key->kid,PQgetvalue(res,i,4)); if(kids) { add_to_secrets_list(kids,key->kid); add_to_secrets_list(teas,key->as_rs_alg); { char ts[256]; snprintf(ts,sizeof(ts)-1,"%llu",(unsigned long long)key->timestamp); add_to_secrets_list(tss,ts); } { char lt[256]; snprintf(lt,sizeof(lt)-1,"%lu",(unsigned long)key->lifetime); add_to_secrets_list(lts,lt); } } else { printf(" kid=%s, ikm_key=%s, timestamp=%llu, lifetime=%lu, as_rs_alg=%s\n", key->kid, key->ikm_key, (unsigned long long)key->timestamp, (unsigned long)key->lifetime, key->as_rs_alg); } ret = 0; } } if(res) { PQclear(res); } } return ret; } static int pgsql_set_user_key(u08bits *usname, u08bits *realm, const char *key) { int ret = -1; char statement[TURN_LONG_STRING_SIZE]; PGconn *pqc = get_pqdb_connection(); if(pqc) { snprintf(statement,sizeof(statement),"insert into turnusers_lt (realm,name,hmackey) values('%s','%s','%s')",realm,usname,key); PGresult *res = PQexec(pqc, statement); if(!res || (PQresultStatus(res) != PGRES_COMMAND_OK)) { if(res) { PQclear(res); } snprintf(statement,sizeof(statement),"update turnusers_lt set hmackey='%s' where name='%s' and realm='%s'",key,usname,realm); res = PQexec(pqc, statement); if(!res || (PQresultStatus(res) != PGRES_COMMAND_OK)) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Error inserting/updating user information: %s\n",PQerrorMessage(pqc)); } else { ret = 0; } } if(res) { PQclear(res); } } return ret; } static int pgsql_set_oauth_key(oauth_key_data_raw *key) { int ret = -1; char statement[TURN_LONG_STRING_SIZE]; PGconn *pqc = get_pqdb_connection(); if(pqc) { snprintf(statement,sizeof(statement),"insert into oauth_key (kid,ikm_key,timestamp,lifetime,as_rs_alg) values('%s','%s',%llu,%lu,'%s')", key->kid,key->ikm_key,(unsigned long long)key->timestamp,(unsigned long)key->lifetime, key->as_rs_alg); PGresult *res = PQexec(pqc, statement); if(!res || (PQresultStatus(res) != PGRES_COMMAND_OK)) { if(res) { PQclear(res); } snprintf(statement,sizeof(statement),"update oauth_key set ikm_key='%s',timestamp=%lu,lifetime=%lu, as_rs_alg='%s' where kid='%s'",key->ikm_key,(unsigned long)key->timestamp,(unsigned long)key->lifetime, key->as_rs_alg,key->kid); res = PQexec(pqc, statement); if(!res || (PQresultStatus(res) != PGRES_COMMAND_OK)) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Error inserting/updating oauth_key information: %s\n",PQerrorMessage(pqc)); } else { ret = 0; } } else { ret = 0; } if(res) { PQclear(res); } } return ret; } static int pgsql_del_user(u08bits *usname, u08bits *realm) { int ret = -1; char statement[TURN_LONG_STRING_SIZE]; PGconn *pqc = get_pqdb_connection(); if(pqc) { snprintf(statement,sizeof(statement),"delete from turnusers_lt where name='%s' and realm='%s'",usname,realm); PGresult *res = PQexec(pqc, statement); if(res) { PQclear(res); ret = 0; } } return ret; } static int pgsql_del_oauth_key(const u08bits *kid) { int ret = -1; char statement[TURN_LONG_STRING_SIZE]; PGconn *pqc = get_pqdb_connection(); if(pqc) { snprintf(statement,sizeof(statement),"delete from oauth_key where kid = '%s'",(const char*)kid); PGresult *res = PQexec(pqc, statement); if(!res || (PQresultStatus(res) != PGRES_COMMAND_OK)) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Error deleting oauth_key information: %s\n",PQerrorMessage(pqc)); } else { ret = 0; } if(res) { PQclear(res); } } return ret; } static int pgsql_list_users(u08bits *realm, secrets_list_t *users, secrets_list_t *realms) { int ret = -1; char statement[TURN_LONG_STRING_SIZE]; u08bits realm0[STUN_MAX_REALM_SIZE+1] = "\0"; if(!realm) realm=realm0; PGconn *pqc = get_pqdb_connection(); if(pqc) { if(realm[0]) { snprintf(statement,sizeof(statement),"select name,realm from turnusers_lt where realm='%s' order by name",realm); } else { snprintf(statement,sizeof(statement),"select name,realm from turnusers_lt order by realm,name"); } PGresult *res = PQexec(pqc, statement); if(!res || (PQresultStatus(res) != PGRES_TUPLES_OK)) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Error retrieving PostgreSQL DB information: %s\n",PQerrorMessage(pqc)); } else { int i = 0; for(i=0;i<PQntuples(res);i++) { char *kval = PQgetvalue(res,i,0); if(kval) { char *rval = PQgetvalue(res,i,1); if(rval) { if(users) { add_to_secrets_list(users,kval); if(realms) { if(rval && *rval) { add_to_secrets_list(realms,rval); } else { add_to_secrets_list(realms,(char*)realm); } } } else { printf("%s[%s]\n", kval, rval); } } } } ret = 0; } if(res) { PQclear(res); } } return ret; } static int pgsql_list_secrets(u08bits *realm, secrets_list_t *secrets, secrets_list_t *realms) { int ret = -1; u08bits realm0[STUN_MAX_REALM_SIZE+1] = "\0"; if(!realm) realm=realm0; char statement[TURN_LONG_STRING_SIZE]; if (realm[0]) { snprintf(statement, sizeof(statement), "select value,realm from turn_secret where realm='%s' order by value", realm); } else { snprintf(statement, sizeof(statement), "select value,realm from turn_secret order by realm,value"); } donot_print_connection_success=1; PGconn *pqc = get_pqdb_connection(); if(pqc) { PGresult *res = PQexec(pqc, statement); if(!res || (PQresultStatus(res) != PGRES_TUPLES_OK)) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Error retrieving PostgreSQL DB information: %s\n",PQerrorMessage(pqc)); } else { int i = 0; for(i=0;i<PQntuples(res);i++) { char *kval = PQgetvalue(res,i,0); if(kval) { char* rval = PQgetvalue(res,i,1); if(secrets) { add_to_secrets_list(secrets,kval); if(realms) { if(rval && *rval) { add_to_secrets_list(realms,rval); } else { add_to_secrets_list(realms,(char*)realm); } } } else { printf("%s[%s]\n",kval,rval); } } } ret = 0; } if(res) { PQclear(res); } } return ret; } static int pgsql_del_secret(u08bits *secret, u08bits *realm) { int ret = -1; donot_print_connection_success=1; char statement[TURN_LONG_STRING_SIZE]; PGconn *pqc = get_pqdb_connection(); if (pqc) { if(!secret || (secret[0]==0)) snprintf(statement,sizeof(statement),"delete from turn_secret where realm='%s'",realm); else snprintf(statement,sizeof(statement),"delete from turn_secret where value='%s' and realm='%s'",secret,realm); PGresult *res = PQexec(pqc, statement); if (res) { PQclear(res); ret = 0; } } return ret; } static int pgsql_set_secret(u08bits *secret, u08bits *realm) { int ret = -1; donot_print_connection_success = 1; char statement[TURN_LONG_STRING_SIZE]; PGconn *pqc = get_pqdb_connection(); if (pqc) { snprintf(statement,sizeof(statement),"insert into turn_secret (realm,value) values('%s','%s')",realm,secret); PGresult *res = PQexec(pqc, statement); if (!res || (PQresultStatus(res) != PGRES_COMMAND_OK)) { TURN_LOG_FUNC( TURN_LOG_LEVEL_ERROR, "Error inserting/updating secret key information: %s\n", PQerrorMessage(pqc)); } else { ret = 0; } if (res) { PQclear(res); } } return ret; } static int pgsql_set_permission_ip(const char *kind, u08bits *realm, const char* ip, int del) { int ret = -1; u08bits realm0[STUN_MAX_REALM_SIZE+1] = "\0"; if(!realm) realm=realm0; donot_print_connection_success = 1; char statement[TURN_LONG_STRING_SIZE]; PGconn *pqc = get_pqdb_connection(); if (pqc) { if(del) { snprintf(statement, sizeof(statement), "delete from %s_peer_ip where realm = '%s' and ip_range = '%s'", kind, (char*)realm, ip); } else { snprintf(statement, sizeof(statement), "insert into %s_peer_ip (realm,ip_range) values('%s','%s')", kind, (char*)realm, ip); } PGresult *res = PQexec(pqc, statement); if (!res || (PQresultStatus(res) != PGRES_COMMAND_OK)) { TURN_LOG_FUNC( TURN_LOG_LEVEL_ERROR, "Error inserting ip permission information: %s\n", PQerrorMessage(pqc)); } else { ret = 0; } if (res) { PQclear(res); } } return ret; } static int pgsql_add_origin(u08bits *origin, u08bits *realm) { int ret = -1; char statement[TURN_LONG_STRING_SIZE]; PGconn *pqc = get_pqdb_connection(); if(pqc) { snprintf(statement,sizeof(statement),"insert into turn_origin_to_realm (origin,realm) values('%s','%s')",origin,realm); PGresult *res = PQexec(pqc, statement); if(!res || (PQresultStatus(res) != PGRES_COMMAND_OK)) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Error inserting origin information: %s\n",PQerrorMessage(pqc)); } else { ret = 0; } if(res) { PQclear(res); } } return ret; } static int pgsql_del_origin(u08bits *origin) { int ret = -1; char statement[TURN_LONG_STRING_SIZE]; PGconn *pqc = get_pqdb_connection(); if(pqc) { snprintf(statement,sizeof(statement),"delete from turn_origin_to_realm where origin='%s'",origin); PGresult *res = PQexec(pqc, statement); if(!res || (PQresultStatus(res) != PGRES_COMMAND_OK)) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Error deleting origin information: %s\n",PQerrorMessage(pqc)); } else { ret = 0; } if(res) { PQclear(res); } } return ret; } static int pgsql_list_origins(u08bits *realm, secrets_list_t *origins, secrets_list_t *realms) { int ret = -1; u08bits realm0[STUN_MAX_REALM_SIZE+1] = "\0"; if(!realm) realm=realm0; donot_print_connection_success = 1; PGconn *pqc = get_pqdb_connection(); if(pqc) { char statement[TURN_LONG_STRING_SIZE]; if(realm && realm[0]) { snprintf(statement,sizeof(statement),"select origin,realm from turn_origin_to_realm where realm='%s' order by origin",realm); } else { snprintf(statement,sizeof(statement),"select origin,realm from turn_origin_to_realm order by realm,origin"); } PGresult *res = PQexec(pqc, statement); if(!res || (PQresultStatus(res) != PGRES_TUPLES_OK)) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Error retrieving PostgreSQL DB information: %s\n",PQerrorMessage(pqc)); } else { int i = 0; for(i=0;i<PQntuples(res);i++) { char *kval = PQgetvalue(res,i,0); if(kval) { char *rval = PQgetvalue(res,i,1); if(rval) { if(origins) { add_to_secrets_list(origins,kval); if(realms) { if(rval && *rval) { add_to_secrets_list(realms,rval); } else { add_to_secrets_list(realms,(char*)realm); } } } else { printf("%s ==>> %s\n",kval,rval); } } } } ret = 0; } if(res) { PQclear(res); } } return ret; } static int pgsql_set_realm_option_one(u08bits *realm, unsigned long value, const char* opt) { int ret = -1; char statement[TURN_LONG_STRING_SIZE]; PGconn *pqc = get_pqdb_connection(); if(pqc) { { snprintf(statement,sizeof(statement),"delete from turn_realm_option where realm='%s' and opt='%s'",realm,opt); PGresult *res = PQexec(pqc, statement); if(res) { PQclear(res); } } if(value>0) { snprintf(statement,sizeof(statement),"insert into turn_realm_option (realm,opt,value) values('%s','%s','%lu')",realm,opt,(unsigned long)value); PGresult *res = PQexec(pqc, statement); if(!res || (PQresultStatus(res) != PGRES_COMMAND_OK)) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Error inserting realm option information: %s\n",PQerrorMessage(pqc)); } else { ret = 0; } if(res) { PQclear(res); } } } return ret; } static int pgsql_list_realm_options(u08bits *realm) { int ret = -1; donot_print_connection_success = 1; char statement[TURN_LONG_STRING_SIZE]; PGconn *pqc = get_pqdb_connection(); if(pqc) { if(realm && realm[0]) { snprintf(statement,sizeof(statement),"select realm,opt,value from turn_realm_option where realm='%s' order by realm,opt",realm); } else { snprintf(statement,sizeof(statement),"select realm,opt,value from turn_realm_option order by realm,opt"); } PGresult *res = PQexec(pqc, statement); if(!res || (PQresultStatus(res) != PGRES_TUPLES_OK)) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Error retrieving PostgreSQL DB information: %s\n",PQerrorMessage(pqc)); } else { int i = 0; for(i=0;i<PQntuples(res);i++) { char *rval = PQgetvalue(res,i,0); if(rval) { char *oval = PQgetvalue(res,i,1); if(oval) { char *vval = PQgetvalue(res,i,2); if(vval) { printf("%s[%s]=%s\n",oval,rval,vval); } } } } ret = 0; } if(res) { PQclear(res); } } return ret; } static void pgsql_auth_ping(void * rch) { UNUSED_ARG(rch); PGconn * pqc = get_pqdb_connection(); if(pqc) { char statement[TURN_LONG_STRING_SIZE]; STRCPY(statement,"select value from turn_secret"); PGresult *res = PQexec(pqc, statement); if(!res || (PQresultStatus(res) != PGRES_TUPLES_OK)) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Error retrieving PostgreSQL DB information: %s\n",PQerrorMessage(pqc)); } if(res) { PQclear(res); } } } static int pgsql_get_ip_list(const char *kind, ip_range_list_t * list) { int ret = -1; PGconn * pqc = get_pqdb_connection(); if (pqc) { char statement[TURN_LONG_STRING_SIZE]; snprintf(statement, sizeof(statement), "select ip_range,realm from %s_peer_ip", kind); PGresult *res = PQexec(pqc, statement); if (!res || (PQresultStatus(res) != PGRES_TUPLES_OK)) { static int wrong_table_reported = 0; if(!wrong_table_reported) { wrong_table_reported = 1; TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Error retrieving PostgreSQL DB information: %s; probably, the tables 'allowed_peer_ip' and/or 'denied_peer_ip' have to be upgraded to include the realm column.\n",PQerrorMessage(pqc)); } snprintf(statement, sizeof(statement), "select ip_range,'' from %s_peer_ip", kind); res = PQexec(pqc, statement); } if (res && (PQresultStatus(res) == PGRES_TUPLES_OK)) { int i = 0; for (i = 0; i < PQntuples(res); i++) { char *kval = PQgetvalue(res, i, 0); char *rval = PQgetvalue(res, i, 1); if (kval) { add_ip_list_range(kval, rval, list); } } ret = 0; } if (res) { PQclear(res); } } return ret; } static void pgsql_reread_realms(secrets_list_t * realms_list) { PGconn * pqc = get_pqdb_connection(); if(pqc) { char statement[TURN_LONG_STRING_SIZE]; { snprintf(statement,sizeof(statement),"select origin,realm from turn_origin_to_realm"); PGresult *res = PQexec(pqc, statement); if(res && (PQresultStatus(res) == PGRES_TUPLES_OK)) { ur_string_map *o_to_realm_new = ur_string_map_create(turn_free_simple); int i = 0; for(i=0;i<PQntuples(res);i++) { char *oval = PQgetvalue(res,i,0); if(oval) { char *rval = PQgetvalue(res,i,1); if(rval) { get_realm(rval); ur_string_map_value_type value = turn_strdup(rval); ur_string_map_put(o_to_realm_new, (const ur_string_map_key_type) oval, value); } } } update_o_to_realm(o_to_realm_new); } if(res) { PQclear(res); } } { { size_t i = 0; size_t rlsz = 0; lock_realms(); rlsz = realms_list->sz; unlock_realms(); for (i = 0; i<rlsz; ++i) { char *realm = realms_list->secrets[i]; realm_params_t* rp = get_realm(realm); lock_realms(); rp->options.perf_options.max_bps = turn_params.max_bps; unlock_realms(); lock_realms(); rp->options.perf_options.total_quota = turn_params.total_quota; unlock_realms(); lock_realms(); rp->options.perf_options.user_quota = turn_params.user_quota; unlock_realms(); } } snprintf(statement,sizeof(statement),"select realm,opt,value from turn_realm_option"); PGresult *res = PQexec(pqc, statement); if(res && (PQresultStatus(res) == PGRES_TUPLES_OK)) { int i = 0; for(i=0;i<PQntuples(res);i++) { char *rval = PQgetvalue(res,i,0); char *oval = PQgetvalue(res,i,1); char *vval = PQgetvalue(res,i,2); if(rval && oval && vval) { realm_params_t* rp = get_realm(rval); if(!strcmp(oval,"max-bps")) rp->options.perf_options.max_bps = (band_limit_t)strtoul(vval,NULL,10); else if(!strcmp(oval,"total-quota")) rp->options.perf_options.total_quota = (vint)atoi(vval); else if(!strcmp(oval,"user-quota")) rp->options.perf_options.user_quota = (vint)atoi(vval); else { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Unknown realm option: %s\n", oval); } } } } if(res) { PQclear(res); } } } } ////////////////////////////////////////////// static int pgsql_get_admin_user(const u08bits *usname, u08bits *realm, password_t pwd) { int ret = -1; realm[0]=0; pwd[0]=0; PGconn * pqc = get_pqdb_connection(); if(pqc) { char statement[TURN_LONG_STRING_SIZE]; snprintf(statement,sizeof(statement),"select realm,password from admin_user where name='%s'",usname); PGresult *res = PQexec(pqc, statement); if(!res || (PQresultStatus(res) != PGRES_TUPLES_OK) || (PQntuples(res)!=1)) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Error retrieving PostgreSQL DB information: %s\n",PQerrorMessage(pqc)); } else { const char *kval = PQgetvalue(res,0,0); if(kval) { strncpy((char*)realm,kval,STUN_MAX_REALM_SIZE); } kval = (const char*) PQgetvalue(res,0,1); if(kval) { strncpy((char*)pwd,kval,STUN_MAX_PWD_SIZE); } ret = 0; } if(res) PQclear(res); } return ret; } static int pgsql_set_admin_user(const u08bits *usname, const u08bits *realm, const password_t pwd) { int ret = -1; char statement[TURN_LONG_STRING_SIZE]; donot_print_connection_success=1; PGconn *pqc = get_pqdb_connection(); if(pqc) { snprintf(statement,sizeof(statement),"insert into admin_user (realm,name,password) values('%s','%s','%s')",realm,usname,pwd); PGresult *res = PQexec(pqc, statement); if(!res || (PQresultStatus(res) != PGRES_COMMAND_OK)) { if(res) { PQclear(res); } snprintf(statement,sizeof(statement),"update admin_user set password='%s',realm='%s' where name='%s'",pwd,realm,usname); res = PQexec(pqc, statement); if(!res || (PQresultStatus(res) != PGRES_COMMAND_OK)) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Error inserting/updating user information: %s\n",PQerrorMessage(pqc)); } else { ret = 0; } } if(res) { PQclear(res); } } return ret; } static int pgsql_del_admin_user(const u08bits *usname) { int ret = -1; char statement[TURN_LONG_STRING_SIZE]; donot_print_connection_success=1; PGconn *pqc = get_pqdb_connection(); if(pqc) { snprintf(statement,sizeof(statement),"delete from admin_user where name='%s'",usname); PGresult *res = PQexec(pqc, statement); if(res) { PQclear(res); ret = 0; } } return ret; } static int pgsql_list_admin_users(int no_print) { int ret = -1; char statement[TURN_LONG_STRING_SIZE]; donot_print_connection_success=1; PGconn *pqc = get_pqdb_connection(); if(pqc) { snprintf(statement,sizeof(statement),"select name,realm,password from admin_user order by realm,name"); } PGresult *res = PQexec(pqc, statement); if(!res || (PQresultStatus(res) != PGRES_TUPLES_OK)) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Error retrieving PostgreSQL DB information: %s\n",PQerrorMessage(pqc)); } else { int i = 0; ret = 0; for(i=0;i<PQntuples(res);i++) { char *kval = PQgetvalue(res,i,0); ++ret; if(kval && !no_print) { char *rval = PQgetvalue(res,i,1); if(rval && *rval) { printf("%s[%s]\n",kval,rval); } else { printf("%s\n",kval); } } } } if(res) { PQclear(res); } return ret; } ///////////////////////////////////////////////////////////// static const turn_dbdriver_t driver = { &pgsql_get_auth_secrets, &pgsql_get_user_key, &pgsql_set_user_key, &pgsql_del_user, &pgsql_list_users, &pgsql_list_secrets, &pgsql_del_secret, &pgsql_set_secret, &pgsql_add_origin, &pgsql_del_origin, &pgsql_list_origins, &pgsql_set_realm_option_one, &pgsql_list_realm_options, &pgsql_auth_ping, &pgsql_get_ip_list, &pgsql_set_permission_ip, &pgsql_reread_realms, &pgsql_set_oauth_key, &pgsql_get_oauth_key, &pgsql_del_oauth_key, &pgsql_list_oauth_keys, &pgsql_get_admin_user, &pgsql_set_admin_user, &pgsql_del_admin_user, &pgsql_list_admin_users }; const turn_dbdriver_t * get_pgsql_dbdriver(void) { return &driver; } /////////////////////////////////////////////////////////////////////////////////////////////////////////// #else const turn_dbdriver_t * get_pgsql_dbdriver(void) { return NULL; } #endif
1.203125
1
zettelkasten.h
jameschip/Zettelkasten
5
1236
#ifndef ZETTELKASTEN_H #define ZETTELKASTEN_H #include <ncurses.h> enum nav_states { SCREEN_EXIT, SCREEN_DISPLAY, SCREEN_LIST, SCREEN_ADD, SCREEN_CLEAR_FILTER, SCREEN_FILTER_INPUT, SCREEN_CREATE_LINK, SCREEN_LINK_CONTEXT, SCREEN_TAG_LIST, SCREEN_ADD_TAG }; extern char * filter_tag; extern int last_entry; extern int link_entry; extern int entry_to_read; WINDOW *create_newwin(int height, int width, int starty, int startx); WINDOW *create_newwin_lb(int height, int width, int starty, int startx); void print_text_underlined( WINDOW * win, int row, int col, char* text); int zk_screen_display( uint64_t e ); int zk_screen_list( const char * message ); int zk_screen_tag_filter( void ); int zk_screen_add_entry( void ); int zk_do_add_link( void ); int zk_screen_link_context( void ); int zk_screen_tag_list( uint64_t ent_num ); int zk_screen_add_tag( void ); #endif
1.015625
1
app/archive/commsdsl2old/src/ListField.h
arobenko/commsdsl
4
1244
// // Copyright 2018 - 2021 (C). <NAME>. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once #include "commsdsl/parse/ListField.h" #include "Field.h" #include "common.h" namespace commsdsl2old { class ListField final : public Field { using Base = Field; public: ListField(Generator& generator, commsdsl::parse::Field field) : Base(generator, field) {} protected: virtual bool prepareImpl() override; virtual void updateIncludesImpl(IncludesList& includes) const override; virtual void updateIncludesCommonImpl(IncludesList& includes) const override; virtual void updatePluginIncludesImpl(IncludesList& includes) const override; virtual std::size_t maxLengthImpl() const override; virtual std::string getClassDefinitionImpl( const std::string& scope, const std::string& className) const override; virtual std::string getExtraDefaultOptionsImpl(const std::string& scope) const override; virtual std::string getExtraBareMetalDefaultOptionsImpl(const std::string& base, const std::string& scope) const override; virtual std::string getExtraDataViewDefaultOptionsImpl(const std::string& base, const std::string& scope) const override; virtual std::string getBareMetalOptionStrImpl() const override; virtual std::string getCompareToValueImpl( const std::string& op, const std::string& value, const std::string& nameOverride, bool forcedVersionOptional) const override; virtual std::string getCompareToFieldImpl( const std::string& op, const Field& field, const std::string& nameOverride, bool forcedVersionOptional) const override; virtual std::string getPluginAnonNamespaceImpl( const std::string& scope, bool forcedSerialisedHidden, bool serHiddenParam) const override; virtual std::string getPluginPropertiesImpl(bool serHiddenParam) const override; virtual std::string getPrivateRefreshBodyImpl(const FieldsList& fields) const override; virtual bool hasCustomReadRefreshImpl() const override; virtual std::string getReadPreparationImpl(const FieldsList& fields) const override; virtual bool isLimitedCustomizableImpl() const override; virtual bool isVersionDependentImpl() const override; virtual std::string getCommonDefinitionImpl(const std::string& fullScope) const override; virtual std::string getExtraRefToCommonDefinitionImpl(const std::string& fullScope) const override; private: using StringsList = common::StringsList; using GetExtraOptionsFunc = std::string (Field::*)(const std::string& base, const std::string& scope) const; std::string getFieldOpts(const std::string& scope) const; std::string getElement() const; std::string getMembersDef(const std::string& scope) const; void checkFixedSizeOpt(StringsList& list) const; void checkCountPrefixOpt(StringsList& list) const; void checkLengthPrefixOpt(StringsList& list) const; void checkElemLengthPrefixOpt(StringsList& list) const; bool checkDetachedPrefixOpt(StringsList& list) const; bool isElemForcedSerialisedHiddenInPlugin() const; std::string getPrefixName() const; std::string getExtraOptions(const std::string& scope, GetExtraOptionsFunc func, const std::string& base) const; commsdsl::parse::ListField listFieldDslObj() const { return commsdsl::parse::ListField(dslObj()); } FieldPtr m_element; FieldPtr m_countPrefix; FieldPtr m_lengthPrefix; FieldPtr m_elemLengthPrefix; }; inline FieldPtr createListField(Generator& generator, commsdsl::parse::Field field) { return std::make_unique<ListField>(generator, field); } } // namespace commsdsl2old
1.039063
1
src/qt/qtwebkit/Source/WebCore/platform/graphics/texmap/coordinated/CoordinatedGraphicsLayer.h
viewdy/phantomjs
1
1252
/* Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies) 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; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef CoordinatedGraphicsLayer_h #define CoordinatedGraphicsLayer_h #include "CoordinatedGraphicsState.h" #include "CoordinatedImageBacking.h" #include "CoordinatedTile.h" #include "FloatPoint3D.h" #include "GraphicsLayer.h" #include "GraphicsLayerAnimation.h" #include "GraphicsLayerTransform.h" #include "Image.h" #include "IntSize.h" #include "RunLoop.h" #include "TiledBackingStore.h" #include "TiledBackingStoreClient.h" #include "TransformationMatrix.h" #if USE(GRAPHICS_SURFACE) #include "GraphicsSurfaceToken.h" #endif #include <wtf/text/StringHash.h> #if USE(COORDINATED_GRAPHICS) namespace WebCore { class CoordinatedGraphicsLayer; class GraphicsLayerAnimations; class ScrollableArea; class CoordinatedGraphicsLayerClient { public: virtual bool isFlushingLayerChanges() const = 0; virtual FloatRect visibleContentsRect() const = 0; virtual PassRefPtr<CoordinatedImageBacking> createImageBackingIfNeeded(Image*) = 0; virtual void detachLayer(CoordinatedGraphicsLayer*) = 0; virtual bool paintToSurface(const IntSize&, CoordinatedSurface::Flags, uint32_t& atlasID, IntPoint&, CoordinatedSurface::Client*) = 0; virtual void syncLayerState(CoordinatedLayerID, CoordinatedGraphicsLayerState&) = 0; }; class CoordinatedGraphicsLayer : public GraphicsLayer , public TiledBackingStoreClient , public CoordinatedImageBacking::Host , public CoordinatedTileClient { public: explicit CoordinatedGraphicsLayer(GraphicsLayerClient*); virtual ~CoordinatedGraphicsLayer(); // Reimplementations from GraphicsLayer.h. virtual bool setChildren(const Vector<GraphicsLayer*>&) OVERRIDE; virtual void addChild(GraphicsLayer*) OVERRIDE; virtual void addChildAtIndex(GraphicsLayer*, int) OVERRIDE; virtual void addChildAbove(GraphicsLayer*, GraphicsLayer*) OVERRIDE; virtual void addChildBelow(GraphicsLayer*, GraphicsLayer*) OVERRIDE; virtual bool replaceChild(GraphicsLayer*, GraphicsLayer*) OVERRIDE; virtual void removeFromParent() OVERRIDE; virtual void setPosition(const FloatPoint&) OVERRIDE; virtual void setAnchorPoint(const FloatPoint3D&) OVERRIDE; virtual void setSize(const FloatSize&) OVERRIDE; virtual void setTransform(const TransformationMatrix&) OVERRIDE; virtual void setChildrenTransform(const TransformationMatrix&) OVERRIDE; virtual void setPreserves3D(bool) OVERRIDE; virtual void setMasksToBounds(bool) OVERRIDE; virtual void setDrawsContent(bool) OVERRIDE; virtual void setContentsVisible(bool) OVERRIDE; virtual void setContentsOpaque(bool) OVERRIDE; virtual void setBackfaceVisibility(bool) OVERRIDE; virtual void setOpacity(float) OVERRIDE; virtual void setContentsRect(const IntRect&) OVERRIDE; virtual void setContentsTilePhase(const IntPoint&) OVERRIDE; virtual void setContentsTileSize(const IntSize&) OVERRIDE; virtual void setContentsToImage(Image*) OVERRIDE; virtual void setContentsToSolidColor(const Color&) OVERRIDE; virtual void setShowDebugBorder(bool) OVERRIDE; virtual void setShowRepaintCounter(bool) OVERRIDE; virtual bool shouldDirectlyCompositeImage(Image*) const OVERRIDE; virtual void setContentsToCanvas(PlatformLayer*) OVERRIDE; virtual void setMaskLayer(GraphicsLayer*) OVERRIDE; virtual void setReplicatedByLayer(GraphicsLayer*) OVERRIDE; virtual void setNeedsDisplay() OVERRIDE; virtual void setNeedsDisplayInRect(const FloatRect&) OVERRIDE; virtual void setContentsNeedsDisplay() OVERRIDE; virtual void deviceOrPageScaleFactorChanged() OVERRIDE; virtual void flushCompositingState(const FloatRect&) OVERRIDE; virtual void flushCompositingStateForThisLayerOnly() OVERRIDE; #if ENABLE(CSS_FILTERS) virtual bool setFilters(const FilterOperations&) OVERRIDE; #endif virtual bool addAnimation(const KeyframeValueList&, const IntSize&, const Animation*, const String&, double) OVERRIDE; virtual void pauseAnimation(const String&, double) OVERRIDE; virtual void removeAnimation(const String&) OVERRIDE; virtual void suspendAnimations(double time) OVERRIDE; virtual void resumeAnimations() OVERRIDE; virtual bool hasContentsLayer() const OVERRIDE { return m_canvasPlatformLayer || m_compositedImage; } void syncPendingStateChangesIncludingSubLayers(); void updateContentBuffersIncludingSubLayers(); FloatPoint computePositionRelativeToBase(); void computePixelAlignment(FloatPoint& position, FloatSize&, FloatPoint3D& anchorPoint, FloatSize& alignmentOffset); void setVisibleContentRectTrajectoryVector(const FloatPoint&); void setScrollableArea(ScrollableArea*); bool isScrollable() const { return !!m_scrollableArea; } void commitScrollOffset(const IntSize&); CoordinatedLayerID id() const; void setFixedToViewport(bool isFixed); IntRect coverRect() const { return m_mainBackingStore ? m_mainBackingStore->mapToContents(m_mainBackingStore->coverRect()) : IntRect(); } // TiledBackingStoreClient virtual void tiledBackingStorePaintBegin() OVERRIDE; virtual void tiledBackingStorePaint(GraphicsContext*, const IntRect&) OVERRIDE; virtual void tiledBackingStorePaintEnd(const Vector<IntRect>& paintedArea) OVERRIDE; virtual void tiledBackingStoreHasPendingTileCreation() OVERRIDE; virtual IntRect tiledBackingStoreContentsRect() OVERRIDE; virtual IntRect tiledBackingStoreVisibleRect() OVERRIDE; virtual Color tiledBackingStoreBackgroundColor() const OVERRIDE; // CoordinatedTileClient virtual void createTile(uint32_t tileID, const SurfaceUpdateInfo&, const IntRect&) OVERRIDE; virtual void updateTile(uint32_t tileID, const SurfaceUpdateInfo&, const IntRect&) OVERRIDE; virtual void removeTile(uint32_t tileID) OVERRIDE; virtual bool paintToSurface(const IntSize&, uint32_t& /* atlasID */, IntPoint&, CoordinatedSurface::Client*) OVERRIDE; void setCoordinator(CoordinatedGraphicsLayerClient*); void setNeedsVisibleRectAdjustment(); void purgeBackingStores(); bool hasPendingVisibleChanges(); static void setShouldSupportContentsTiling(bool); CoordinatedGraphicsLayer* findFirstDescendantWithContentsRecursively(); private: #if USE(GRAPHICS_SURFACE) enum PendingCanvasOperation { None = 0x00, CreateCanvas = 0x01, DestroyCanvas = 0x02, SyncCanvas = 0x04, CreateAndSyncCanvas = CreateCanvas | SyncCanvas, RecreateCanvas = CreateAndSyncCanvas | DestroyCanvas }; void syncCanvas(); void destroyCanvasIfNeeded(); void createCanvasIfNeeded(); #endif virtual void setDebugBorder(const Color&, float width) OVERRIDE; bool fixedToViewport() const { return m_fixedToViewport; } void didChangeLayerState(); void didChangeAnimations(); void didChangeGeometry(); void didChangeChildren(); #if ENABLE(CSS_FILTERS) void didChangeFilters(); #endif void didChangeImageBacking(); void resetLayerState(); void syncLayerState(); void syncAnimations(); void syncChildren(); #if ENABLE(CSS_FILTERS) void syncFilters(); #endif void syncImageBacking(); void computeTransformedVisibleRect(); void updateContentBuffers(); void createBackingStore(); void releaseImageBackingIfNeeded(); // CoordinatedImageBacking::Host virtual bool imageBackingVisible() OVERRIDE; bool shouldHaveBackingStore() const; bool selfOrAncestorHasActiveTransformAnimation() const; bool selfOrAncestorHaveNonAffineTransforms(); void adjustContentsScale(); void setShouldUpdateVisibleRect(); float effectiveContentsScale(); void animationStartedTimerFired(Timer<CoordinatedGraphicsLayer>*); CoordinatedLayerID m_id; CoordinatedGraphicsLayerState m_layerState; GraphicsLayerTransform m_layerTransform; TransformationMatrix m_cachedInverseTransform; FloatSize m_pixelAlignmentOffset; FloatSize m_adjustedSize; FloatPoint m_adjustedPosition; FloatPoint3D m_adjustedAnchorPoint; #ifndef NDEBUG bool m_isPurging; #endif bool m_shouldUpdateVisibleRect: 1; bool m_shouldSyncLayerState: 1; bool m_shouldSyncChildren: 1; bool m_shouldSyncFilters: 1; bool m_shouldSyncImageBacking: 1; bool m_shouldSyncAnimations: 1; bool m_fixedToViewport : 1; bool m_movingVisibleRect : 1; bool m_pendingContentsScaleAdjustment : 1; bool m_pendingVisibleRectAdjustment : 1; #if USE(GRAPHICS_SURFACE) bool m_isValidCanvas : 1; unsigned m_pendingCanvasOperation : 3; #endif CoordinatedGraphicsLayerClient* m_coordinator; OwnPtr<TiledBackingStore> m_mainBackingStore; OwnPtr<TiledBackingStore> m_previousBackingStore; RefPtr<Image> m_compositedImage; NativeImagePtr m_compositedNativeImagePtr; RefPtr<CoordinatedImageBacking> m_coordinatedImageBacking; PlatformLayer* m_canvasPlatformLayer; #if USE(GRAPHICS_SURFACE) IntSize m_canvasSize; GraphicsSurfaceToken m_canvasToken; #endif Timer<CoordinatedGraphicsLayer> m_animationStartedTimer; GraphicsLayerAnimations m_animations; double m_lastAnimationStartTime; ScrollableArea* m_scrollableArea; }; CoordinatedGraphicsLayer* toCoordinatedGraphicsLayer(GraphicsLayer*); } // namespace WebCore #endif // USE(COORDINATED_GRAPHICS) #endif // CoordinatedGraphicsLayer_h
1.117188
1
AzureMXChip/MXCHIPAZ3166/core/lib/netxduo/addons/azure_iot/azure-sdk-for-c/sdk/samples/iot/pnp/pnp_mqtt_message.c
Logicalis/eugenio-devices
0
1260
// Copyright (c) Microsoft Corporation. All rights reserved. // SPDX-License-Identifier: MIT #include "pnp_mqtt_message.h" #include <iot_sample_common.h> #include <stddef.h> #include <stdint.h> #include <stdlib.h> #include <azure/core/az_result.h> #include <azure/core/az_span.h> static char publish_topic_buffer[128]; static char publish_payload_buffer[512]; static uint32_t request_id_int; static char request_id_buffer[16]; az_result pnp_mqtt_message_init(pnp_mqtt_message* out_mqtt_message) { if (out_mqtt_message == NULL) { return AZ_ERROR_ARG; } out_mqtt_message->topic = publish_topic_buffer; out_mqtt_message->topic_length = sizeof(publish_topic_buffer); out_mqtt_message->out_topic_length = 0; out_mqtt_message->payload = AZ_SPAN_FROM_BUFFER(publish_payload_buffer); out_mqtt_message->out_payload = out_mqtt_message->payload; return AZ_OK; } az_span pnp_mqtt_get_request_id(void) { az_span remainder; az_span out_span = az_span_create((uint8_t*)request_id_buffer, sizeof(request_id_buffer)); // Note that if left to run for a long time, this will overflow and reset back to 0. az_result rc = az_span_u32toa(out_span, request_id_int++, &remainder); if (az_result_failed(rc)) { IOT_SAMPLE_LOG_ERROR("Failed to get request id: az_result return code 0x%08x.", rc); exit(rc); } return az_span_slice(out_span, 0, az_span_size(out_span) - az_span_size(remainder)); }
1.25
1
lib/linux-5.18-rc3-smdk/arch/powerpc/kvm/emulate_loadstore.c
OpenMPDK/SMDK
44
1268
// SPDX-License-Identifier: GPL-2.0-only /* * * Copyright IBM Corp. 2007 * Copyright 2011 Freescale Semiconductor, Inc. * * Authors: <NAME> <<EMAIL>> */ #include <linux/jiffies.h> #include <linux/hrtimer.h> #include <linux/types.h> #include <linux/string.h> #include <linux/kvm_host.h> #include <linux/clockchips.h> #include <asm/reg.h> #include <asm/time.h> #include <asm/byteorder.h> #include <asm/kvm_ppc.h> #include <asm/disassemble.h> #include <asm/ppc-opcode.h> #include <asm/sstep.h> #include "timing.h" #include "trace.h" #ifdef CONFIG_PPC_FPU static bool kvmppc_check_fp_disabled(struct kvm_vcpu *vcpu) { if (!(kvmppc_get_msr(vcpu) & MSR_FP)) { kvmppc_core_queue_fpunavail(vcpu); return true; } return false; } #endif /* CONFIG_PPC_FPU */ #ifdef CONFIG_VSX static bool kvmppc_check_vsx_disabled(struct kvm_vcpu *vcpu) { if (!(kvmppc_get_msr(vcpu) & MSR_VSX)) { kvmppc_core_queue_vsx_unavail(vcpu); return true; } return false; } #endif /* CONFIG_VSX */ #ifdef CONFIG_ALTIVEC static bool kvmppc_check_altivec_disabled(struct kvm_vcpu *vcpu) { if (!(kvmppc_get_msr(vcpu) & MSR_VEC)) { kvmppc_core_queue_vec_unavail(vcpu); return true; } return false; } #endif /* CONFIG_ALTIVEC */ /* * XXX to do: * lfiwax, lfiwzx * vector loads and stores * * Instructions that trap when used on cache-inhibited mappings * are not emulated here: multiple and string instructions, * lq/stq, and the load-reserve/store-conditional instructions. */ int kvmppc_emulate_loadstore(struct kvm_vcpu *vcpu) { u32 inst; enum emulation_result emulated = EMULATE_FAIL; struct instruction_op op; /* this default type might be overwritten by subcategories */ kvmppc_set_exit_type(vcpu, EMULATED_INST_EXITS); emulated = kvmppc_get_last_inst(vcpu, INST_GENERIC, &inst); if (emulated != EMULATE_DONE) return emulated; vcpu->arch.mmio_vsx_copy_nums = 0; vcpu->arch.mmio_vsx_offset = 0; vcpu->arch.mmio_copy_type = KVMPPC_VSX_COPY_NONE; vcpu->arch.mmio_sp64_extend = 0; vcpu->arch.mmio_sign_extend = 0; vcpu->arch.mmio_vmx_copy_nums = 0; vcpu->arch.mmio_vmx_offset = 0; vcpu->arch.mmio_host_swabbed = 0; emulated = EMULATE_FAIL; vcpu->arch.regs.msr = vcpu->arch.shared->msr; if (analyse_instr(&op, &vcpu->arch.regs, ppc_inst(inst)) == 0) { int type = op.type & INSTR_TYPE_MASK; int size = GETSIZE(op.type); vcpu->mmio_is_write = OP_IS_STORE(type); switch (type) { case LOAD: { int instr_byte_swap = op.type & BYTEREV; if (op.type & SIGNEXT) emulated = kvmppc_handle_loads(vcpu, op.reg, size, !instr_byte_swap); else emulated = kvmppc_handle_load(vcpu, op.reg, size, !instr_byte_swap); if ((op.type & UPDATE) && (emulated != EMULATE_FAIL)) kvmppc_set_gpr(vcpu, op.update_reg, op.ea); break; } #ifdef CONFIG_PPC_FPU case LOAD_FP: if (kvmppc_check_fp_disabled(vcpu)) return EMULATE_DONE; if (op.type & FPCONV) vcpu->arch.mmio_sp64_extend = 1; if (op.type & SIGNEXT) emulated = kvmppc_handle_loads(vcpu, KVM_MMIO_REG_FPR|op.reg, size, 1); else emulated = kvmppc_handle_load(vcpu, KVM_MMIO_REG_FPR|op.reg, size, 1); if ((op.type & UPDATE) && (emulated != EMULATE_FAIL)) kvmppc_set_gpr(vcpu, op.update_reg, op.ea); break; #endif #ifdef CONFIG_ALTIVEC case LOAD_VMX: if (kvmppc_check_altivec_disabled(vcpu)) return EMULATE_DONE; /* Hardware enforces alignment of VMX accesses */ vcpu->arch.vaddr_accessed &= ~((unsigned long)size - 1); vcpu->arch.paddr_accessed &= ~((unsigned long)size - 1); if (size == 16) { /* lvx */ vcpu->arch.mmio_copy_type = KVMPPC_VMX_COPY_DWORD; } else if (size == 4) { /* lvewx */ vcpu->arch.mmio_copy_type = KVMPPC_VMX_COPY_WORD; } else if (size == 2) { /* lvehx */ vcpu->arch.mmio_copy_type = KVMPPC_VMX_COPY_HWORD; } else if (size == 1) { /* lvebx */ vcpu->arch.mmio_copy_type = KVMPPC_VMX_COPY_BYTE; } else break; vcpu->arch.mmio_vmx_offset = (vcpu->arch.vaddr_accessed & 0xf)/size; if (size == 16) { vcpu->arch.mmio_vmx_copy_nums = 2; emulated = kvmppc_handle_vmx_load(vcpu, KVM_MMIO_REG_VMX|op.reg, 8, 1); } else { vcpu->arch.mmio_vmx_copy_nums = 1; emulated = kvmppc_handle_vmx_load(vcpu, KVM_MMIO_REG_VMX|op.reg, size, 1); } break; #endif #ifdef CONFIG_VSX case LOAD_VSX: { int io_size_each; if (op.vsx_flags & VSX_CHECK_VEC) { if (kvmppc_check_altivec_disabled(vcpu)) return EMULATE_DONE; } else { if (kvmppc_check_vsx_disabled(vcpu)) return EMULATE_DONE; } if (op.vsx_flags & VSX_FPCONV) vcpu->arch.mmio_sp64_extend = 1; if (op.element_size == 8) { if (op.vsx_flags & VSX_SPLAT) vcpu->arch.mmio_copy_type = KVMPPC_VSX_COPY_DWORD_LOAD_DUMP; else vcpu->arch.mmio_copy_type = KVMPPC_VSX_COPY_DWORD; } else if (op.element_size == 4) { if (op.vsx_flags & VSX_SPLAT) vcpu->arch.mmio_copy_type = KVMPPC_VSX_COPY_WORD_LOAD_DUMP; else vcpu->arch.mmio_copy_type = KVMPPC_VSX_COPY_WORD; } else break; if (size < op.element_size) { /* precision convert case: lxsspx, etc */ vcpu->arch.mmio_vsx_copy_nums = 1; io_size_each = size; } else { /* lxvw4x, lxvd2x, etc */ vcpu->arch.mmio_vsx_copy_nums = size/op.element_size; io_size_each = op.element_size; } emulated = kvmppc_handle_vsx_load(vcpu, KVM_MMIO_REG_VSX|op.reg, io_size_each, 1, op.type & SIGNEXT); break; } #endif case STORE: /* if need byte reverse, op.val has been reversed by * analyse_instr(). */ emulated = kvmppc_handle_store(vcpu, op.val, size, 1); if ((op.type & UPDATE) && (emulated != EMULATE_FAIL)) kvmppc_set_gpr(vcpu, op.update_reg, op.ea); break; #ifdef CONFIG_PPC_FPU case STORE_FP: if (kvmppc_check_fp_disabled(vcpu)) return EMULATE_DONE; /* The FP registers need to be flushed so that * kvmppc_handle_store() can read actual FP vals * from vcpu->arch. */ if (vcpu->kvm->arch.kvm_ops->giveup_ext) vcpu->kvm->arch.kvm_ops->giveup_ext(vcpu, MSR_FP); if (op.type & FPCONV) vcpu->arch.mmio_sp64_extend = 1; emulated = kvmppc_handle_store(vcpu, VCPU_FPR(vcpu, op.reg), size, 1); if ((op.type & UPDATE) && (emulated != EMULATE_FAIL)) kvmppc_set_gpr(vcpu, op.update_reg, op.ea); break; #endif #ifdef CONFIG_ALTIVEC case STORE_VMX: if (kvmppc_check_altivec_disabled(vcpu)) return EMULATE_DONE; /* Hardware enforces alignment of VMX accesses. */ vcpu->arch.vaddr_accessed &= ~((unsigned long)size - 1); vcpu->arch.paddr_accessed &= ~((unsigned long)size - 1); if (vcpu->kvm->arch.kvm_ops->giveup_ext) vcpu->kvm->arch.kvm_ops->giveup_ext(vcpu, MSR_VEC); if (size == 16) { /* stvx */ vcpu->arch.mmio_copy_type = KVMPPC_VMX_COPY_DWORD; } else if (size == 4) { /* stvewx */ vcpu->arch.mmio_copy_type = KVMPPC_VMX_COPY_WORD; } else if (size == 2) { /* stvehx */ vcpu->arch.mmio_copy_type = KVMPPC_VMX_COPY_HWORD; } else if (size == 1) { /* stvebx */ vcpu->arch.mmio_copy_type = KVMPPC_VMX_COPY_BYTE; } else break; vcpu->arch.mmio_vmx_offset = (vcpu->arch.vaddr_accessed & 0xf)/size; if (size == 16) { vcpu->arch.mmio_vmx_copy_nums = 2; emulated = kvmppc_handle_vmx_store(vcpu, op.reg, 8, 1); } else { vcpu->arch.mmio_vmx_copy_nums = 1; emulated = kvmppc_handle_vmx_store(vcpu, op.reg, size, 1); } break; #endif #ifdef CONFIG_VSX case STORE_VSX: { int io_size_each; if (op.vsx_flags & VSX_CHECK_VEC) { if (kvmppc_check_altivec_disabled(vcpu)) return EMULATE_DONE; } else { if (kvmppc_check_vsx_disabled(vcpu)) return EMULATE_DONE; } if (vcpu->kvm->arch.kvm_ops->giveup_ext) vcpu->kvm->arch.kvm_ops->giveup_ext(vcpu, MSR_VSX); if (op.vsx_flags & VSX_FPCONV) vcpu->arch.mmio_sp64_extend = 1; if (op.element_size == 8) vcpu->arch.mmio_copy_type = KVMPPC_VSX_COPY_DWORD; else if (op.element_size == 4) vcpu->arch.mmio_copy_type = KVMPPC_VSX_COPY_WORD; else break; if (size < op.element_size) { /* precise conversion case, like stxsspx */ vcpu->arch.mmio_vsx_copy_nums = 1; io_size_each = size; } else { /* stxvw4x, stxvd2x, etc */ vcpu->arch.mmio_vsx_copy_nums = size/op.element_size; io_size_each = op.element_size; } emulated = kvmppc_handle_vsx_store(vcpu, op.reg, io_size_each, 1); break; } #endif case CACHEOP: /* Do nothing. The guest is performing dcbi because * hardware DMA is not snooped by the dcache, but * emulated DMA either goes through the dcache as * normal writes, or the host kernel has handled dcache * coherence. */ emulated = EMULATE_DONE; break; default: break; } } trace_kvm_ppc_instr(inst, kvmppc_get_pc(vcpu), emulated); /* Advance past emulated instruction. */ if (emulated != EMULATE_FAIL) kvmppc_set_pc(vcpu, kvmppc_get_pc(vcpu) + 4); return emulated; }
1.359375
1
unsorted_include_todo/efx/TKechappyTest.h
projectPiki/pikmin2
33
1276
#ifndef _EFX_TKECHAPPYTEST_H #define _EFX_TKECHAPPYTEST_H /* __vt__Q23efx13TKechappyTest: .4byte 0 .4byte 0 .4byte "create__Q23efx29TSyncGroup3<Q23efx9TChaseMtx>FPQ23efx3Arg" .4byte "forceKill__Q23efx29TSyncGroup3<Q23efx9TChaseMtx>Fv" .4byte "fade__Q23efx29TSyncGroup3<Q23efx9TChaseMtx>Fv" .4byte "startDemoDrawOff__Q23efx29TSyncGroup3<Q23efx9TChaseMtx>Fv" .4byte "endDemoDrawOn__Q23efx29TSyncGroup3<Q23efx9TChaseMtx>Fv" */ namespace efx { namespace TSyncGroup3 < efx { struct TChaseMtx > { virtual void TSyncGroup3 < create(Arg*); // _00 virtual void TSyncGroup3 < forceKill(); // _04 virtual void TSyncGroup3 < fade(); // _08 virtual void TSyncGroup3 < startDemoDrawOff(); // _0C virtual void TSyncGroup3 < endDemoDrawOn(); // _10 // _00 VTBL }; } // namespace efx } // namespace efx namespace efx { struct TKechappyTest : public TChaseMtx > { virtual void TSyncGroup3 < create(Arg*); // _00 virtual void TSyncGroup3 < forceKill(); // _04 virtual void TSyncGroup3 < fade(); // _08 virtual void TSyncGroup3 < startDemoDrawOff(); // _0C virtual void TSyncGroup3 < endDemoDrawOn(); // _10 // _00 VTBL }; } // namespace efx #endif
0.949219
1
wangle/channel/HandlerContext-inl.h
G-arj/wangle
0
1284
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * 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. */ #pragma once #include <folly/Format.h> namespace wangle { class PipelineContext { public: virtual ~PipelineContext() = default; virtual void attachPipeline() = 0; virtual void detachPipeline() = 0; template <class H, class HandlerContext> void attachContext(H* handler, HandlerContext* ctx) { if (++handler->attachCount_ == 1) { handler->ctx_ = ctx; } else { handler->ctx_ = nullptr; } } template <class H, class HandlerContext> void detachContext(H* handler, HandlerContext* /*ctx*/) { if (handler->attachCount_ >= 1) { --handler->attachCount_; } handler->ctx_ = nullptr; } virtual void setNextIn(PipelineContext* ctx) = 0; virtual void setNextOut(PipelineContext* ctx) = 0; virtual HandlerDir getDirection() = 0; }; template <class In> class InboundLink { public: virtual ~InboundLink() = default; virtual void read(In msg) = 0; virtual void readEOF() = 0; virtual void readException(folly::exception_wrapper e) = 0; virtual void transportActive() = 0; virtual void transportInactive() = 0; }; template <class Out> class OutboundLink { public: virtual ~OutboundLink() = default; virtual folly::Future<folly::Unit> write(Out msg) = 0; virtual folly::Future<folly::Unit> writeException( folly::exception_wrapper e) = 0; virtual folly::Future<folly::Unit> close() = 0; }; template <class H, class Context> class ContextImplBase : public PipelineContext { public: ~ContextImplBase() override = default; H* getHandler() { return handler_.get(); } void initialize( std::weak_ptr<PipelineBase> pipeline, std::shared_ptr<H> handler) { pipelineWeak_ = pipeline; pipelineRaw_ = pipeline.lock().get(); handler_ = std::move(handler); } // PipelineContext overrides void attachPipeline() override { if (!attached_) { this->attachContext(handler_.get(), impl_); handler_->attachPipeline(impl_); attached_ = true; } } void detachPipeline() override { handler_->detachPipeline(impl_); attached_ = false; this->detachContext(handler_.get(), impl_); } void setNextIn(PipelineContext* ctx) override { if (!ctx) { nextIn_ = nullptr; return; } auto nextIn = dynamic_cast<InboundLink<typename H::rout>*>(ctx); if (nextIn) { nextIn_ = nextIn; } else { throw std::invalid_argument(folly::sformat( "inbound type mismatch after {}", folly::demangle(typeid(H)))); } } void setNextOut(PipelineContext* ctx) override { if (!ctx) { nextOut_ = nullptr; return; } auto nextOut = dynamic_cast<OutboundLink<typename H::wout>*>(ctx); if (nextOut) { nextOut_ = nextOut; } else { throw std::invalid_argument(folly::sformat( "outbound type mismatch after {}", folly::demangle(typeid(H)))); } } HandlerDir getDirection() override { return H::dir; } protected: Context* impl_; std::weak_ptr<PipelineBase> pipelineWeak_; PipelineBase* pipelineRaw_; std::shared_ptr<H> handler_; InboundLink<typename H::rout>* nextIn_{nullptr}; OutboundLink<typename H::wout>* nextOut_{nullptr}; private: bool attached_{false}; }; template <class H> class ContextImpl : public HandlerContext<typename H::rout, typename H::wout>, public InboundLink<typename H::rin>, public OutboundLink<typename H::win>, public ContextImplBase< H, HandlerContext<typename H::rout, typename H::wout>> { public: typedef typename H::rin Rin; typedef typename H::rout Rout; typedef typename H::win Win; typedef typename H::wout Wout; static const HandlerDir dir = HandlerDir::BOTH; explicit ContextImpl( std::weak_ptr<PipelineBase> pipeline, std::shared_ptr<H> handler) { this->impl_ = this; this->initialize(pipeline, std::move(handler)); } // For StaticPipeline ContextImpl() { this->impl_ = this; } ~ContextImpl() override = default; // HandlerContext overrides void fireRead(Rout msg) override { auto guard = this->pipelineWeak_.lock(); if (this->nextIn_) { this->nextIn_->read(std::forward<Rout>(msg)); } else { LOG(WARNING) << "read reached end of pipeline"; } } void fireReadEOF() override { auto guard = this->pipelineWeak_.lock(); if (this->nextIn_) { this->nextIn_->readEOF(); } else { LOG(WARNING) << "readEOF reached end of pipeline"; } } void fireReadException(folly::exception_wrapper e) override { auto guard = this->pipelineWeak_.lock(); if (this->nextIn_) { this->nextIn_->readException(std::move(e)); } else { LOG(WARNING) << "readException reached end of pipeline"; } } void fireTransportActive() override { auto guard = this->pipelineWeak_.lock(); if (this->nextIn_) { this->nextIn_->transportActive(); } } void fireTransportInactive() override { auto guard = this->pipelineWeak_.lock(); if (this->nextIn_) { this->nextIn_->transportInactive(); } } folly::Future<folly::Unit> fireWrite(Wout msg) override { auto guard = this->pipelineWeak_.lock(); if (this->nextOut_) { return this->nextOut_->write(std::forward<Wout>(msg)); } else { LOG(WARNING) << "write reached end of pipeline"; return folly::makeFuture(); } } folly::Future<folly::Unit> fireWriteException( folly::exception_wrapper e) override { auto guard = this->pipelineWeak_.lock(); if (this->nextOut_) { return this->nextOut_->writeException(std::move(e)); } else { LOG(WARNING) << "close reached end of pipeline"; return folly::makeFuture(); } } folly::Future<folly::Unit> fireClose() override { auto guard = this->pipelineWeak_.lock(); if (this->nextOut_) { return this->nextOut_->close(); } else { LOG(WARNING) << "close reached end of pipeline"; return folly::makeFuture(); } } PipelineBase* getPipeline() override { return this->pipelineRaw_; } std::shared_ptr<PipelineBase> getPipelineShared() override { return this->pipelineWeak_.lock(); } void setWriteFlags(folly::WriteFlags flags) override { this->pipelineRaw_->setWriteFlags(flags); } folly::WriteFlags getWriteFlags() override { return this->pipelineRaw_->getWriteFlags(); } void setReadBufferSettings(uint64_t minAvailable, uint64_t allocationSize) override { this->pipelineRaw_->setReadBufferSettings(minAvailable, allocationSize); } std::pair<uint64_t, uint64_t> getReadBufferSettings() override { return this->pipelineRaw_->getReadBufferSettings(); } // InboundLink overrides void read(Rin msg) override { auto guard = this->pipelineWeak_.lock(); this->handler_->read(this, std::forward<Rin>(msg)); } void readEOF() override { auto guard = this->pipelineWeak_.lock(); this->handler_->readEOF(this); } void readException(folly::exception_wrapper e) override { auto guard = this->pipelineWeak_.lock(); this->handler_->readException(this, std::move(e)); } void transportActive() override { auto guard = this->pipelineWeak_.lock(); this->handler_->transportActive(this); } void transportInactive() override { auto guard = this->pipelineWeak_.lock(); this->handler_->transportInactive(this); } // OutboundLink overrides folly::Future<folly::Unit> write(Win msg) override { auto guard = this->pipelineWeak_.lock(); return this->handler_->write(this, std::forward<Win>(msg)); } folly::Future<folly::Unit> writeException( folly::exception_wrapper e) override { auto guard = this->pipelineWeak_.lock(); return this->handler_->writeException(this, std::move(e)); } folly::Future<folly::Unit> close() override { auto guard = this->pipelineWeak_.lock(); return this->handler_->close(this); } }; template <class H> class InboundContextImpl : public InboundHandlerContext<typename H::rout>, public InboundLink<typename H::rin>, public ContextImplBase<H, InboundHandlerContext<typename H::rout>> { public: typedef typename H::rin Rin; typedef typename H::rout Rout; typedef typename H::win Win; typedef typename H::wout Wout; static const HandlerDir dir = HandlerDir::IN; explicit InboundContextImpl( std::weak_ptr<PipelineBase> pipeline, std::shared_ptr<H> handler) { this->impl_ = this; this->initialize(pipeline, std::move(handler)); } // For StaticPipeline InboundContextImpl() { this->impl_ = this; } ~InboundContextImpl() override = default; // InboundHandlerContext overrides void fireRead(Rout msg) override { auto guard = this->pipelineWeak_.lock(); if (this->nextIn_) { this->nextIn_->read(std::forward<Rout>(msg)); } else { LOG(WARNING) << "read reached end of pipeline"; } } void fireReadEOF() override { auto guard = this->pipelineWeak_.lock(); if (this->nextIn_) { this->nextIn_->readEOF(); } else { LOG(WARNING) << "readEOF reached end of pipeline"; } } void fireReadException(folly::exception_wrapper e) override { auto guard = this->pipelineWeak_.lock(); if (this->nextIn_) { this->nextIn_->readException(std::move(e)); } else { LOG(WARNING) << "readException reached end of pipeline"; } } void fireTransportActive() override { auto guard = this->pipelineWeak_.lock(); if (this->nextIn_) { this->nextIn_->transportActive(); } } void fireTransportInactive() override { auto guard = this->pipelineWeak_.lock(); if (this->nextIn_) { this->nextIn_->transportInactive(); } } PipelineBase* getPipeline() override { return this->pipelineRaw_; } std::shared_ptr<PipelineBase> getPipelineShared() override { return this->pipelineWeak_.lock(); } // InboundLink overrides void read(Rin msg) override { auto guard = this->pipelineWeak_.lock(); this->handler_->read(this, std::forward<Rin>(msg)); } void readEOF() override { auto guard = this->pipelineWeak_.lock(); this->handler_->readEOF(this); } void readException(folly::exception_wrapper e) override { auto guard = this->pipelineWeak_.lock(); this->handler_->readException(this, std::move(e)); } void transportActive() override { auto guard = this->pipelineWeak_.lock(); this->handler_->transportActive(this); } void transportInactive() override { auto guard = this->pipelineWeak_.lock(); this->handler_->transportInactive(this); } }; template <class H> class OutboundContextImpl : public OutboundHandlerContext<typename H::wout>, public OutboundLink<typename H::win>, public ContextImplBase<H, OutboundHandlerContext<typename H::wout>> { public: typedef typename H::rin Rin; typedef typename H::rout Rout; typedef typename H::win Win; typedef typename H::wout Wout; static const HandlerDir dir = HandlerDir::OUT; explicit OutboundContextImpl( std::weak_ptr<PipelineBase> pipeline, std::shared_ptr<H> handler) { this->impl_ = this; this->initialize(pipeline, std::move(handler)); } // For StaticPipeline OutboundContextImpl() { this->impl_ = this; } ~OutboundContextImpl() override = default; // OutboundHandlerContext overrides folly::Future<folly::Unit> fireWrite(Wout msg) override { auto guard = this->pipelineWeak_.lock(); if (this->nextOut_) { return this->nextOut_->write(std::forward<Wout>(msg)); } else { LOG(WARNING) << "write reached end of pipeline"; return folly::makeFuture(); } } folly::Future<folly::Unit> fireWriteException( folly::exception_wrapper e) override { auto guard = this->pipelineWeak_.lock(); if (this->nextOut_) { return this->nextOut_->writeException(std::move(e)); } else { LOG(WARNING) << "close reached end of pipeline"; return folly::makeFuture(); } } folly::Future<folly::Unit> fireClose() override { auto guard = this->pipelineWeak_.lock(); if (this->nextOut_) { return this->nextOut_->close(); } else { LOG(WARNING) << "close reached end of pipeline"; return folly::makeFuture(); } } PipelineBase* getPipeline() override { return this->pipelineRaw_; } std::shared_ptr<PipelineBase> getPipelineShared() override { return this->pipelineWeak_.lock(); } // OutboundLink overrides folly::Future<folly::Unit> write(Win msg) override { auto guard = this->pipelineWeak_.lock(); return this->handler_->write(this, std::forward<Win>(msg)); } folly::Future<folly::Unit> writeException( folly::exception_wrapper e) override { auto guard = this->pipelineWeak_.lock(); return this->handler_->writeException(this, std::move(e)); } folly::Future<folly::Unit> close() override { auto guard = this->pipelineWeak_.lock(); return this->handler_->close(this); } }; template <class Handler> struct ContextType { typedef typename std::conditional< Handler::dir == HandlerDir::BOTH, ContextImpl<Handler>, typename std::conditional< Handler::dir == HandlerDir::IN, InboundContextImpl<Handler>, OutboundContextImpl<Handler>>::type>::type type; }; } // namespace wangle
1.210938
1
Software/Azure_RTOS_USB_MSC/Core/Src/fdcan.c
Indemsys/Backup-controller_BACKPMAN-v2.0
4
1292
/** ****************************************************************************** * @file fdcan.c * @brief This file provides code for the configuration * of the FDCAN instances. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2021 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "fdcan.h" /* USER CODE BEGIN 0 */ /* USER CODE END 0 */ FDCAN_HandleTypeDef hfdcan1; /* FDCAN1 init function */ void MX_FDCAN1_Init(void) { /* USER CODE BEGIN FDCAN1_Init 0 */ /* USER CODE END FDCAN1_Init 0 */ /* USER CODE BEGIN FDCAN1_Init 1 */ /* USER CODE END FDCAN1_Init 1 */ hfdcan1.Instance = FDCAN1; hfdcan1.Init.FrameFormat = FDCAN_FRAME_CLASSIC; hfdcan1.Init.Mode = FDCAN_MODE_NORMAL; hfdcan1.Init.AutoRetransmission = DISABLE; hfdcan1.Init.TransmitPause = DISABLE; hfdcan1.Init.ProtocolException = DISABLE; hfdcan1.Init.NominalPrescaler = 1; hfdcan1.Init.NominalSyncJumpWidth = 1; hfdcan1.Init.NominalTimeSeg1 = 2; hfdcan1.Init.NominalTimeSeg2 = 2; hfdcan1.Init.DataPrescaler = 1; hfdcan1.Init.DataSyncJumpWidth = 1; hfdcan1.Init.DataTimeSeg1 = 1; hfdcan1.Init.DataTimeSeg2 = 1; hfdcan1.Init.MessageRAMOffset = 0; hfdcan1.Init.StdFiltersNbr = 0; hfdcan1.Init.ExtFiltersNbr = 0; hfdcan1.Init.RxFifo0ElmtsNbr = 0; hfdcan1.Init.RxFifo0ElmtSize = FDCAN_DATA_BYTES_8; hfdcan1.Init.RxFifo1ElmtsNbr = 0; hfdcan1.Init.RxFifo1ElmtSize = FDCAN_DATA_BYTES_8; hfdcan1.Init.RxBuffersNbr = 0; hfdcan1.Init.RxBufferSize = FDCAN_DATA_BYTES_8; hfdcan1.Init.TxEventsNbr = 0; hfdcan1.Init.TxBuffersNbr = 0; hfdcan1.Init.TxFifoQueueElmtsNbr = 0; hfdcan1.Init.TxFifoQueueMode = FDCAN_TX_FIFO_OPERATION; hfdcan1.Init.TxElmtSize = FDCAN_DATA_BYTES_8; if (HAL_FDCAN_Init(&hfdcan1) != HAL_OK) { Error_Handler(); } /* USER CODE BEGIN FDCAN1_Init 2 */ /* USER CODE END FDCAN1_Init 2 */ } void HAL_FDCAN_MspInit(FDCAN_HandleTypeDef* fdcanHandle) { GPIO_InitTypeDef GPIO_InitStruct = {0}; if(fdcanHandle->Instance==FDCAN1) { /* USER CODE BEGIN FDCAN1_MspInit 0 */ /* USER CODE END FDCAN1_MspInit 0 */ /* FDCAN1 clock enable */ __HAL_RCC_FDCAN_CLK_ENABLE(); __HAL_RCC_GPIOB_CLK_ENABLE(); __HAL_RCC_GPIOD_CLK_ENABLE(); /**FDCAN1 GPIO Configuration PB8 ------> FDCAN1_RX PD1 ------> FDCAN1_TX */ GPIO_InitStruct.Pin = CAN0_RX_Pin; GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW; GPIO_InitStruct.Alternate = GPIO_AF9_FDCAN1; HAL_GPIO_Init(CAN0_RX_GPIO_Port, &GPIO_InitStruct); GPIO_InitStruct.Pin = CAN0_TX_Pin; GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW; GPIO_InitStruct.Alternate = GPIO_AF9_FDCAN1; HAL_GPIO_Init(CAN0_TX_GPIO_Port, &GPIO_InitStruct); /* USER CODE BEGIN FDCAN1_MspInit 1 */ /* USER CODE END FDCAN1_MspInit 1 */ } } void HAL_FDCAN_MspDeInit(FDCAN_HandleTypeDef* fdcanHandle) { if(fdcanHandle->Instance==FDCAN1) { /* USER CODE BEGIN FDCAN1_MspDeInit 0 */ /* USER CODE END FDCAN1_MspDeInit 0 */ /* Peripheral clock disable */ __HAL_RCC_FDCAN_CLK_DISABLE(); /**FDCAN1 GPIO Configuration PB8 ------> FDCAN1_RX PD1 ------> FDCAN1_TX */ HAL_GPIO_DeInit(CAN0_RX_GPIO_Port, CAN0_RX_Pin); HAL_GPIO_DeInit(CAN0_TX_GPIO_Port, CAN0_TX_Pin); /* USER CODE BEGIN FDCAN1_MspDeInit 1 */ /* USER CODE END FDCAN1_MspDeInit 1 */ } } /* USER CODE BEGIN 1 */ /* USER CODE END 1 */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
0.941406
1
headers/3rdparty/CCActionFadeIn.h
Tatsh-archive/tynder
1
1300
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>. // #import "CCActionInterval.h" #import "NSCopying.h" @interface CCActionFadeIn : CCActionInterval <NSCopying> { } - (id)reverse; - (void)update:(double)arg1; @end
0.628906
1
src/video/directfb/SDL_DirectFB_dyn.c
electroduck/SDL2mod
2,967
1308
/* Simple DirectMedia Layer Copyright (C) 1997-2021 <NAME> <<EMAIL>> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #if SDL_VIDEO_DRIVER_DIRECTFB #include "SDL_DirectFB_video.h" #include "SDL_DirectFB_dyn.h" #ifdef SDL_VIDEO_DRIVER_DIRECTFB_DYNAMIC #include "SDL_name.h" #include "SDL_loadso.h" #define DFB_SYM(ret, name, args, al, func) ret (*name) args; static struct _SDL_DirectFB_Symbols { DFB_SYMS const unsigned int *directfb_major_version; const unsigned int *directfb_minor_version; const unsigned int *directfb_micro_version; } SDL_DirectFB_Symbols; #undef DFB_SYM #define DFB_SYM(ret, name, args, al, func) ret name args { func SDL_DirectFB_Symbols.name al ; } DFB_SYMS #undef DFB_SYM static void *handle = NULL; int SDL_DirectFB_LoadLibrary(void) { int retval = 0; if (handle == NULL) { handle = SDL_LoadObject(SDL_VIDEO_DRIVER_DIRECTFB_DYNAMIC); if (handle != NULL) { retval = 1; #define DFB_SYM(ret, name, args, al, func) if (!(SDL_DirectFB_Symbols.name = SDL_LoadFunction(handle, # name))) retval = 0; DFB_SYMS #undef DFB_SYM if (! (SDL_DirectFB_Symbols.directfb_major_version = SDL_LoadFunction(handle, "directfb_major_version"))) retval = 0; if (! (SDL_DirectFB_Symbols.directfb_minor_version = SDL_LoadFunction(handle, "directfb_minor_version"))) retval = 0; if (! (SDL_DirectFB_Symbols.directfb_micro_version = SDL_LoadFunction(handle, "directfb_micro_version"))) retval = 0; } } if (retval) { const char *stemp = DirectFBCheckVersion(DIRECTFB_MAJOR_VERSION, DIRECTFB_MINOR_VERSION, DIRECTFB_MICRO_VERSION); /* Version Check */ if (stemp != NULL) { fprintf(stderr, "DirectFB Lib: Version mismatch. Compiled: %d.%d.%d Library %d.%d.%d\n", DIRECTFB_MAJOR_VERSION, DIRECTFB_MINOR_VERSION, DIRECTFB_MICRO_VERSION, *SDL_DirectFB_Symbols.directfb_major_version, *SDL_DirectFB_Symbols.directfb_minor_version, *SDL_DirectFB_Symbols.directfb_micro_version); retval = 0; } } if (!retval) SDL_DirectFB_UnLoadLibrary(); return retval; } void SDL_DirectFB_UnLoadLibrary(void) { if (handle != NULL) { SDL_UnloadObject(handle); handle = NULL; } } #else int SDL_DirectFB_LoadLibrary(void) { return 1; } void SDL_DirectFB_UnLoadLibrary(void) { } #endif #endif /* SDL_VIDEO_DRIVER_DIRECTFB */
1.140625
1
QueryEngine/OmniSciTypes.h
xieqi/omniscidb
0
1316
/* * Copyright 2020 OmniSci, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <limits> #include <type_traits> /* `../` is required for UDFCompiler */ #include "../Shared/InlineNullValues.h" #include "../Shared/funcannotations.h" #define EXTENSION_INLINE extern "C" RUNTIME_EXPORT ALWAYS_INLINE DEVICE #define EXTENSION_NOINLINE extern "C" RUNTIME_EXPORT NEVER_INLINE DEVICE EXTENSION_NOINLINE int8_t* allocate_varlen_buffer(int64_t element_count, int64_t element_size); EXTENSION_NOINLINE void set_output_row_size(int64_t num_rows); template <typename T> struct Array { T* ptr; int64_t size; int8_t is_null; DEVICE Array(const int64_t size, const bool is_null = false) : size(size), is_null(is_null) { if (!is_null) { ptr = reinterpret_cast<T*>( allocate_varlen_buffer(size, static_cast<int64_t>(sizeof(T)))); } else { ptr = nullptr; } } DEVICE T operator()(const unsigned int index) const { if (index < static_cast<unsigned int>(size)) { return ptr[index]; } else { return 0; // see array_at } } DEVICE T& operator[](const unsigned int index) { return ptr[index]; } DEVICE int64_t getSize() const { return size; } DEVICE bool isNull() const { return is_null; } DEVICE constexpr inline T null_value() const { return std::is_signed<T>::value ? std::numeric_limits<T>::min() : std::numeric_limits<T>::max(); } }; struct GeoLineString { int8_t* ptr; int64_t sz; int32_t compression; int32_t input_srid; int32_t output_srid; DEVICE int64_t getSize() const { return sz; } DEVICE int32_t getCompression() const { return compression; } DEVICE int32_t getInputSrid() const { return input_srid; } DEVICE int32_t getOutputSrid() const { return output_srid; } }; struct GeoPoint { int8_t* ptr; int64_t sz; int32_t compression; int32_t input_srid; int32_t output_srid; DEVICE int64_t getSize() const { return sz; } DEVICE int32_t getCompression() const { return compression; } DEVICE int32_t getInputSrid() const { return input_srid; } DEVICE int32_t getOutputSrid() const { return output_srid; } }; struct GeoPolygon { int8_t* ptr_coords; int64_t coords_size; int32_t* ring_sizes; int64_t num_rings; int32_t compression; int32_t input_srid; int32_t output_srid; DEVICE int32_t* getRingSizes() { return ring_sizes; } DEVICE int64_t getCoordsSize() const { return coords_size; } DEVICE int64_t getNumRings() const { return num_rings; } DEVICE int32_t getCompression() const { return compression; } DEVICE int32_t getInputSrid() const { return input_srid; } DEVICE int32_t getOutputSrid() const { return output_srid; } }; struct GeoMultiPolygon { int8_t* ptr_coords; int64_t coords_size; int32_t* ring_sizes; int64_t num_rings; int32_t* poly_sizes; int64_t num_polys; int32_t compression; int32_t input_srid; int32_t output_srid; DEVICE int32_t* getRingSizes() { return ring_sizes; } DEVICE int64_t getCoordsSize() const { return coords_size; } DEVICE int64_t getNumRings() const { return num_rings; } DEVICE int32_t* getPolygonSizes() { return poly_sizes; } DEVICE int64_t getNumPolygons() const { return num_polys; } DEVICE int32_t getCompression() const { return compression; } DEVICE int32_t getInputSrid() const { return input_srid; } DEVICE int32_t getOutputSrid() const { return output_srid; } }; template <typename T> struct Column { T* ptr_; // row data int64_t size_; // row count DEVICE T& operator[](const unsigned int index) const { if (index >= size_) { #ifndef __CUDACC__ throw std::runtime_error("column buffer index is out of range"); #else static T null_value; set_null(null_value); return null_value; #endif } return ptr_[index]; } DEVICE int64_t size() const { return size_; } DEVICE bool isNull(int64_t index) const { return is_null(ptr_[index]); } DEVICE void setNull(int64_t index) { set_null(ptr_[index]); } DEVICE Column<T>& operator=(const Column<T>& other) { #ifndef __CUDACC__ if (size() == other.size()) { memcpy(ptr_, &other[0], other.size() * sizeof(T)); } else { throw std::runtime_error("cannot copy assign columns with different sizes"); } #else if (size() == other.size()) { for (unsigned int i = 0; i < size(); i++) { ptr_[i] = other[i]; } } else { // TODO: set error } #endif return *this; } #ifdef HAVE_TOSTRING std::string toString() const { return ::typeName(this) + "(ptr=" + ::toString(reinterpret_cast<void*>(ptr_)) + ", size_=" + std::to_string(size_) + ")"; } #endif }; /* ColumnList is an ordered list of Columns. */ template <typename T> struct ColumnList { int8_t** ptrs_; // ptrs to columns data int64_t num_cols_; // the length of columns list int64_t size_; // the size of columns DEVICE int64_t size() const { return size_; } DEVICE int64_t numCols() const { return num_cols_; } DEVICE Column<T> operator[](const int index) const { if (index >= 0 && index < num_cols_) return {reinterpret_cast<T*>(ptrs_[index]), size_}; else return {nullptr, -1}; } #ifdef HAVE_TOSTRING std::string toString() const { std::string result = ::typeName(this) + "(ptrs=["; for (int64_t index = 0; index < num_cols_; index++) { result += ::toString(reinterpret_cast<void*>(ptrs_[index])) + (index < num_cols_ - 1 ? ", " : ""); } result += "], num_cols=" + std::to_string(num_cols_) + ", size=" + std::to_string(size_) + ")"; return result; } #endif };
1.15625
1
s2e/source/s2e-linux-kernel/decree-cgc-cfe/fs/xfs/xfs_inode_fork.c
Albocoder/KOOBE
55
1324
/* * Copyright (c) 2000-2006 Silicon Graphics, Inc. * All Rights Reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation. * * This program is distributed in the hope that it would 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 the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <linux/log2.h> #include "xfs.h" #include "xfs_fs.h" #include "xfs_format.h" #include "xfs_log_format.h" #include "xfs_trans_resv.h" #include "xfs_inum.h" #include "xfs_sb.h" #include "xfs_ag.h" #include "xfs_mount.h" #include "xfs_inode.h" #include "xfs_trans.h" #include "xfs_inode_item.h" #include "xfs_bmap_btree.h" #include "xfs_bmap.h" #include "xfs_error.h" #include "xfs_trace.h" #include "xfs_attr_sf.h" #include "xfs_dinode.h" kmem_zone_t *xfs_ifork_zone; STATIC int xfs_iformat_local(xfs_inode_t *, xfs_dinode_t *, int, int); STATIC int xfs_iformat_extents(xfs_inode_t *, xfs_dinode_t *, int); STATIC int xfs_iformat_btree(xfs_inode_t *, xfs_dinode_t *, int); #ifdef DEBUG /* * Make sure that the extents in the given memory buffer * are valid. */ void xfs_validate_extents( xfs_ifork_t *ifp, int nrecs, xfs_exntfmt_t fmt) { xfs_bmbt_irec_t irec; xfs_bmbt_rec_host_t rec; int i; for (i = 0; i < nrecs; i++) { xfs_bmbt_rec_host_t *ep = xfs_iext_get_ext(ifp, i); rec.l0 = get_unaligned(&ep->l0); rec.l1 = get_unaligned(&ep->l1); xfs_bmbt_get_all(&rec, &irec); if (fmt == XFS_EXTFMT_NOSTATE) ASSERT(irec.br_state == XFS_EXT_NORM); } } #else /* DEBUG */ #define xfs_validate_extents(ifp, nrecs, fmt) #endif /* DEBUG */ /* * Move inode type and inode format specific information from the * on-disk inode to the in-core inode. For fifos, devs, and sockets * this means set if_rdev to the proper value. For files, directories, * and symlinks this means to bring in the in-line data or extent * pointers. For a file in B-tree format, only the root is immediately * brought in-core. The rest will be in-lined in if_extents when it * is first referenced (see xfs_iread_extents()). */ int xfs_iformat_fork( xfs_inode_t *ip, xfs_dinode_t *dip) { xfs_attr_shortform_t *atp; int size; int error = 0; xfs_fsize_t di_size; if (unlikely(be32_to_cpu(dip->di_nextents) + be16_to_cpu(dip->di_anextents) > be64_to_cpu(dip->di_nblocks))) { xfs_warn(ip->i_mount, "corrupt dinode %Lu, extent total = %d, nblocks = %Lu.", (unsigned long long)ip->i_ino, (int)(be32_to_cpu(dip->di_nextents) + be16_to_cpu(dip->di_anextents)), (unsigned long long) be64_to_cpu(dip->di_nblocks)); XFS_CORRUPTION_ERROR("xfs_iformat(1)", XFS_ERRLEVEL_LOW, ip->i_mount, dip); return XFS_ERROR(EFSCORRUPTED); } if (unlikely(dip->di_forkoff > ip->i_mount->m_sb.sb_inodesize)) { xfs_warn(ip->i_mount, "corrupt dinode %Lu, forkoff = 0x%x.", (unsigned long long)ip->i_ino, dip->di_forkoff); XFS_CORRUPTION_ERROR("xfs_iformat(2)", XFS_ERRLEVEL_LOW, ip->i_mount, dip); return XFS_ERROR(EFSCORRUPTED); } if (unlikely((ip->i_d.di_flags & XFS_DIFLAG_REALTIME) && !ip->i_mount->m_rtdev_targp)) { xfs_warn(ip->i_mount, "corrupt dinode %Lu, has realtime flag set.", ip->i_ino); XFS_CORRUPTION_ERROR("xfs_iformat(realtime)", XFS_ERRLEVEL_LOW, ip->i_mount, dip); return XFS_ERROR(EFSCORRUPTED); } switch (ip->i_d.di_mode & S_IFMT) { case S_IFIFO: case S_IFCHR: case S_IFBLK: case S_IFSOCK: if (unlikely(dip->di_format != XFS_DINODE_FMT_DEV)) { XFS_CORRUPTION_ERROR("xfs_iformat(3)", XFS_ERRLEVEL_LOW, ip->i_mount, dip); return XFS_ERROR(EFSCORRUPTED); } ip->i_d.di_size = 0; ip->i_df.if_u2.if_rdev = xfs_dinode_get_rdev(dip); break; case S_IFREG: case S_IFLNK: case S_IFDIR: switch (dip->di_format) { case XFS_DINODE_FMT_LOCAL: /* * no local regular files yet */ if (unlikely(S_ISREG(be16_to_cpu(dip->di_mode)))) { xfs_warn(ip->i_mount, "corrupt inode %Lu (local format for regular file).", (unsigned long long) ip->i_ino); XFS_CORRUPTION_ERROR("xfs_iformat(4)", XFS_ERRLEVEL_LOW, ip->i_mount, dip); return XFS_ERROR(EFSCORRUPTED); } di_size = be64_to_cpu(dip->di_size); if (unlikely(di_size < 0 || di_size > XFS_DFORK_DSIZE(dip, ip->i_mount))) { xfs_warn(ip->i_mount, "corrupt inode %Lu (bad size %Ld for local inode).", (unsigned long long) ip->i_ino, (long long) di_size); XFS_CORRUPTION_ERROR("xfs_iformat(5)", XFS_ERRLEVEL_LOW, ip->i_mount, dip); return XFS_ERROR(EFSCORRUPTED); } size = (int)di_size; error = xfs_iformat_local(ip, dip, XFS_DATA_FORK, size); break; case XFS_DINODE_FMT_EXTENTS: error = xfs_iformat_extents(ip, dip, XFS_DATA_FORK); break; case XFS_DINODE_FMT_BTREE: error = xfs_iformat_btree(ip, dip, XFS_DATA_FORK); break; default: XFS_ERROR_REPORT("xfs_iformat(6)", XFS_ERRLEVEL_LOW, ip->i_mount); return XFS_ERROR(EFSCORRUPTED); } break; default: XFS_ERROR_REPORT("xfs_iformat(7)", XFS_ERRLEVEL_LOW, ip->i_mount); return XFS_ERROR(EFSCORRUPTED); } if (error) { return error; } if (!XFS_DFORK_Q(dip)) return 0; ASSERT(ip->i_afp == NULL); ip->i_afp = kmem_zone_zalloc(xfs_ifork_zone, KM_SLEEP | KM_NOFS); switch (dip->di_aformat) { case XFS_DINODE_FMT_LOCAL: atp = (xfs_attr_shortform_t *)XFS_DFORK_APTR(dip); size = be16_to_cpu(atp->hdr.totsize); if (unlikely(size < sizeof(struct xfs_attr_sf_hdr))) { xfs_warn(ip->i_mount, "corrupt inode %Lu (bad attr fork size %Ld).", (unsigned long long) ip->i_ino, (long long) size); XFS_CORRUPTION_ERROR("xfs_iformat(8)", XFS_ERRLEVEL_LOW, ip->i_mount, dip); return XFS_ERROR(EFSCORRUPTED); } error = xfs_iformat_local(ip, dip, XFS_ATTR_FORK, size); break; case XFS_DINODE_FMT_EXTENTS: error = xfs_iformat_extents(ip, dip, XFS_ATTR_FORK); break; case XFS_DINODE_FMT_BTREE: error = xfs_iformat_btree(ip, dip, XFS_ATTR_FORK); break; default: error = XFS_ERROR(EFSCORRUPTED); break; } if (error) { kmem_zone_free(xfs_ifork_zone, ip->i_afp); ip->i_afp = NULL; xfs_idestroy_fork(ip, XFS_DATA_FORK); } return error; } /* * The file is in-lined in the on-disk inode. * If it fits into if_inline_data, then copy * it there, otherwise allocate a buffer for it * and copy the data there. Either way, set * if_data to point at the data. * If we allocate a buffer for the data, make * sure that its size is a multiple of 4 and * record the real size in i_real_bytes. */ STATIC int xfs_iformat_local( xfs_inode_t *ip, xfs_dinode_t *dip, int whichfork, int size) { xfs_ifork_t *ifp; int real_size; /* * If the size is unreasonable, then something * is wrong and we just bail out rather than crash in * kmem_alloc() or memcpy() below. */ if (unlikely(size > XFS_DFORK_SIZE(dip, ip->i_mount, whichfork))) { xfs_warn(ip->i_mount, "corrupt inode %Lu (bad size %d for local fork, size = %d).", (unsigned long long) ip->i_ino, size, XFS_DFORK_SIZE(dip, ip->i_mount, whichfork)); XFS_CORRUPTION_ERROR("xfs_iformat_local", XFS_ERRLEVEL_LOW, ip->i_mount, dip); return XFS_ERROR(EFSCORRUPTED); } ifp = XFS_IFORK_PTR(ip, whichfork); real_size = 0; if (size == 0) ifp->if_u1.if_data = NULL; else if (size <= sizeof(ifp->if_u2.if_inline_data)) ifp->if_u1.if_data = ifp->if_u2.if_inline_data; else { real_size = roundup(size, 4); ifp->if_u1.if_data = kmem_alloc(real_size, KM_SLEEP | KM_NOFS); } ifp->if_bytes = size; ifp->if_real_bytes = real_size; if (size) memcpy(ifp->if_u1.if_data, XFS_DFORK_PTR(dip, whichfork), size); ifp->if_flags &= ~XFS_IFEXTENTS; ifp->if_flags |= XFS_IFINLINE; return 0; } /* * The file consists of a set of extents all * of which fit into the on-disk inode. * If there are few enough extents to fit into * the if_inline_ext, then copy them there. * Otherwise allocate a buffer for them and copy * them into it. Either way, set if_extents * to point at the extents. */ STATIC int xfs_iformat_extents( xfs_inode_t *ip, xfs_dinode_t *dip, int whichfork) { xfs_bmbt_rec_t *dp; xfs_ifork_t *ifp; int nex; int size; int i; ifp = XFS_IFORK_PTR(ip, whichfork); nex = XFS_DFORK_NEXTENTS(dip, whichfork); size = nex * (uint)sizeof(xfs_bmbt_rec_t); /* * If the number of extents is unreasonable, then something * is wrong and we just bail out rather than crash in * kmem_alloc() or memcpy() below. */ if (unlikely(size < 0 || size > XFS_DFORK_SIZE(dip, ip->i_mount, whichfork))) { xfs_warn(ip->i_mount, "corrupt inode %Lu ((a)extents = %d).", (unsigned long long) ip->i_ino, nex); XFS_CORRUPTION_ERROR("xfs_iformat_extents(1)", XFS_ERRLEVEL_LOW, ip->i_mount, dip); return XFS_ERROR(EFSCORRUPTED); } ifp->if_real_bytes = 0; if (nex == 0) ifp->if_u1.if_extents = NULL; else if (nex <= XFS_INLINE_EXTS) ifp->if_u1.if_extents = ifp->if_u2.if_inline_ext; else xfs_iext_add(ifp, 0, nex); ifp->if_bytes = size; if (size) { dp = (xfs_bmbt_rec_t *) XFS_DFORK_PTR(dip, whichfork); xfs_validate_extents(ifp, nex, XFS_EXTFMT_INODE(ip)); for (i = 0; i < nex; i++, dp++) { xfs_bmbt_rec_host_t *ep = xfs_iext_get_ext(ifp, i); ep->l0 = get_unaligned_be64(&dp->l0); ep->l1 = get_unaligned_be64(&dp->l1); } XFS_BMAP_TRACE_EXLIST(ip, nex, whichfork); if (whichfork != XFS_DATA_FORK || XFS_EXTFMT_INODE(ip) == XFS_EXTFMT_NOSTATE) if (unlikely(xfs_check_nostate_extents( ifp, 0, nex))) { XFS_ERROR_REPORT("xfs_iformat_extents(2)", XFS_ERRLEVEL_LOW, ip->i_mount); return XFS_ERROR(EFSCORRUPTED); } } ifp->if_flags |= XFS_IFEXTENTS; return 0; } /* * The file has too many extents to fit into * the inode, so they are in B-tree format. * Allocate a buffer for the root of the B-tree * and copy the root into it. The i_extents * field will remain NULL until all of the * extents are read in (when they are needed). */ STATIC int xfs_iformat_btree( xfs_inode_t *ip, xfs_dinode_t *dip, int whichfork) { struct xfs_mount *mp = ip->i_mount; xfs_bmdr_block_t *dfp; xfs_ifork_t *ifp; /* REFERENCED */ int nrecs; int size; ifp = XFS_IFORK_PTR(ip, whichfork); dfp = (xfs_bmdr_block_t *)XFS_DFORK_PTR(dip, whichfork); size = XFS_BMAP_BROOT_SPACE(mp, dfp); nrecs = be16_to_cpu(dfp->bb_numrecs); /* * blow out if -- fork has less extents than can fit in * fork (fork shouldn't be a btree format), root btree * block has more records than can fit into the fork, * or the number of extents is greater than the number of * blocks. */ if (unlikely(XFS_IFORK_NEXTENTS(ip, whichfork) <= XFS_IFORK_MAXEXT(ip, whichfork) || XFS_BMDR_SPACE_CALC(nrecs) > XFS_DFORK_SIZE(dip, mp, whichfork) || XFS_IFORK_NEXTENTS(ip, whichfork) > ip->i_d.di_nblocks)) { xfs_warn(mp, "corrupt inode %Lu (btree).", (unsigned long long) ip->i_ino); XFS_CORRUPTION_ERROR("xfs_iformat_btree", XFS_ERRLEVEL_LOW, mp, dip); return XFS_ERROR(EFSCORRUPTED); } ifp->if_broot_bytes = size; ifp->if_broot = kmem_alloc(size, KM_SLEEP | KM_NOFS); ASSERT(ifp->if_broot != NULL); /* * Copy and convert from the on-disk structure * to the in-memory structure. */ xfs_bmdr_to_bmbt(ip, dfp, XFS_DFORK_SIZE(dip, ip->i_mount, whichfork), ifp->if_broot, size); ifp->if_flags &= ~XFS_IFEXTENTS; ifp->if_flags |= XFS_IFBROOT; return 0; } /* * Read in extents from a btree-format inode. * Allocate and fill in if_extents. Real work is done in xfs_bmap.c. */ int xfs_iread_extents( xfs_trans_t *tp, xfs_inode_t *ip, int whichfork) { int error; xfs_ifork_t *ifp; xfs_extnum_t nextents; if (unlikely(XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_BTREE)) { XFS_ERROR_REPORT("xfs_iread_extents", XFS_ERRLEVEL_LOW, ip->i_mount); return XFS_ERROR(EFSCORRUPTED); } nextents = XFS_IFORK_NEXTENTS(ip, whichfork); ifp = XFS_IFORK_PTR(ip, whichfork); /* * We know that the size is valid (it's checked in iformat_btree) */ ifp->if_bytes = ifp->if_real_bytes = 0; ifp->if_flags |= XFS_IFEXTENTS; xfs_iext_add(ifp, 0, nextents); error = xfs_bmap_read_extents(tp, ip, whichfork); if (error) { xfs_iext_destroy(ifp); ifp->if_flags &= ~XFS_IFEXTENTS; return error; } xfs_validate_extents(ifp, nextents, XFS_EXTFMT_INODE(ip)); return 0; } /* * Reallocate the space for if_broot based on the number of records * being added or deleted as indicated in rec_diff. Move the records * and pointers in if_broot to fit the new size. When shrinking this * will eliminate holes between the records and pointers created by * the caller. When growing this will create holes to be filled in * by the caller. * * The caller must not request to add more records than would fit in * the on-disk inode root. If the if_broot is currently NULL, then * if we are adding records, one will be allocated. The caller must also * not request that the number of records go below zero, although * it can go to zero. * * ip -- the inode whose if_broot area is changing * ext_diff -- the change in the number of records, positive or negative, * requested for the if_broot array. */ void xfs_iroot_realloc( xfs_inode_t *ip, int rec_diff, int whichfork) { struct xfs_mount *mp = ip->i_mount; int cur_max; xfs_ifork_t *ifp; struct xfs_btree_block *new_broot; int new_max; size_t new_size; char *np; char *op; /* * Handle the degenerate case quietly. */ if (rec_diff == 0) { return; } ifp = XFS_IFORK_PTR(ip, whichfork); if (rec_diff > 0) { /* * If there wasn't any memory allocated before, just * allocate it now and get out. */ if (ifp->if_broot_bytes == 0) { new_size = XFS_BMAP_BROOT_SPACE_CALC(mp, rec_diff); ifp->if_broot = kmem_alloc(new_size, KM_SLEEP | KM_NOFS); ifp->if_broot_bytes = (int)new_size; return; } /* * If there is already an existing if_broot, then we need * to realloc() it and shift the pointers to their new * location. The records don't change location because * they are kept butted up against the btree block header. */ cur_max = xfs_bmbt_maxrecs(mp, ifp->if_broot_bytes, 0); new_max = cur_max + rec_diff; new_size = XFS_BMAP_BROOT_SPACE_CALC(mp, new_max); ifp->if_broot = kmem_realloc(ifp->if_broot, new_size, XFS_BMAP_BROOT_SPACE_CALC(mp, cur_max), KM_SLEEP | KM_NOFS); op = (char *)XFS_BMAP_BROOT_PTR_ADDR(mp, ifp->if_broot, 1, ifp->if_broot_bytes); np = (char *)XFS_BMAP_BROOT_PTR_ADDR(mp, ifp->if_broot, 1, (int)new_size); ifp->if_broot_bytes = (int)new_size; ASSERT(XFS_BMAP_BMDR_SPACE(ifp->if_broot) <= XFS_IFORK_SIZE(ip, whichfork)); memmove(np, op, cur_max * (uint)sizeof(xfs_dfsbno_t)); return; } /* * rec_diff is less than 0. In this case, we are shrinking the * if_broot buffer. It must already exist. If we go to zero * records, just get rid of the root and clear the status bit. */ ASSERT((ifp->if_broot != NULL) && (ifp->if_broot_bytes > 0)); cur_max = xfs_bmbt_maxrecs(mp, ifp->if_broot_bytes, 0); new_max = cur_max + rec_diff; ASSERT(new_max >= 0); if (new_max > 0) new_size = XFS_BMAP_BROOT_SPACE_CALC(mp, new_max); else new_size = 0; if (new_size > 0) { new_broot = kmem_alloc(new_size, KM_SLEEP | KM_NOFS); /* * First copy over the btree block header. */ memcpy(new_broot, ifp->if_broot, XFS_BMBT_BLOCK_LEN(ip->i_mount)); } else { new_broot = NULL; ifp->if_flags &= ~XFS_IFBROOT; } /* * Only copy the records and pointers if there are any. */ if (new_max > 0) { /* * First copy the records. */ op = (char *)XFS_BMBT_REC_ADDR(mp, ifp->if_broot, 1); np = (char *)XFS_BMBT_REC_ADDR(mp, new_broot, 1); memcpy(np, op, new_max * (uint)sizeof(xfs_bmbt_rec_t)); /* * Then copy the pointers. */ op = (char *)XFS_BMAP_BROOT_PTR_ADDR(mp, ifp->if_broot, 1, ifp->if_broot_bytes); np = (char *)XFS_BMAP_BROOT_PTR_ADDR(mp, new_broot, 1, (int)new_size); memcpy(np, op, new_max * (uint)sizeof(xfs_dfsbno_t)); } kmem_free(ifp->if_broot); ifp->if_broot = new_broot; ifp->if_broot_bytes = (int)new_size; if (ifp->if_broot) ASSERT(XFS_BMAP_BMDR_SPACE(ifp->if_broot) <= XFS_IFORK_SIZE(ip, whichfork)); return; } /* * This is called when the amount of space needed for if_data * is increased or decreased. The change in size is indicated by * the number of bytes that need to be added or deleted in the * byte_diff parameter. * * If the amount of space needed has decreased below the size of the * inline buffer, then switch to using the inline buffer. Otherwise, * use kmem_realloc() or kmem_alloc() to adjust the size of the buffer * to what is needed. * * ip -- the inode whose if_data area is changing * byte_diff -- the change in the number of bytes, positive or negative, * requested for the if_data array. */ void xfs_idata_realloc( xfs_inode_t *ip, int byte_diff, int whichfork) { xfs_ifork_t *ifp; int new_size; int real_size; if (byte_diff == 0) { return; } ifp = XFS_IFORK_PTR(ip, whichfork); new_size = (int)ifp->if_bytes + byte_diff; ASSERT(new_size >= 0); if (new_size == 0) { if (ifp->if_u1.if_data != ifp->if_u2.if_inline_data) { kmem_free(ifp->if_u1.if_data); } ifp->if_u1.if_data = NULL; real_size = 0; } else if (new_size <= sizeof(ifp->if_u2.if_inline_data)) { /* * If the valid extents/data can fit in if_inline_ext/data, * copy them from the malloc'd vector and free it. */ if (ifp->if_u1.if_data == NULL) { ifp->if_u1.if_data = ifp->if_u2.if_inline_data; } else if (ifp->if_u1.if_data != ifp->if_u2.if_inline_data) { ASSERT(ifp->if_real_bytes != 0); memcpy(ifp->if_u2.if_inline_data, ifp->if_u1.if_data, new_size); kmem_free(ifp->if_u1.if_data); ifp->if_u1.if_data = ifp->if_u2.if_inline_data; } real_size = 0; } else { /* * Stuck with malloc/realloc. * For inline data, the underlying buffer must be * a multiple of 4 bytes in size so that it can be * logged and stay on word boundaries. We enforce * that here. */ real_size = roundup(new_size, 4); if (ifp->if_u1.if_data == NULL) { ASSERT(ifp->if_real_bytes == 0); ifp->if_u1.if_data = kmem_alloc(real_size, KM_SLEEP | KM_NOFS); } else if (ifp->if_u1.if_data != ifp->if_u2.if_inline_data) { /* * Only do the realloc if the underlying size * is really changing. */ if (ifp->if_real_bytes != real_size) { ifp->if_u1.if_data = kmem_realloc(ifp->if_u1.if_data, real_size, ifp->if_real_bytes, KM_SLEEP | KM_NOFS); } } else { ASSERT(ifp->if_real_bytes == 0); ifp->if_u1.if_data = kmem_alloc(real_size, KM_SLEEP | KM_NOFS); memcpy(ifp->if_u1.if_data, ifp->if_u2.if_inline_data, ifp->if_bytes); } } ifp->if_real_bytes = real_size; ifp->if_bytes = new_size; ASSERT(ifp->if_bytes <= XFS_IFORK_SIZE(ip, whichfork)); } void xfs_idestroy_fork( xfs_inode_t *ip, int whichfork) { xfs_ifork_t *ifp; ifp = XFS_IFORK_PTR(ip, whichfork); if (ifp->if_broot != NULL) { kmem_free(ifp->if_broot); ifp->if_broot = NULL; } /* * If the format is local, then we can't have an extents * array so just look for an inline data array. If we're * not local then we may or may not have an extents list, * so check and free it up if we do. */ if (XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_LOCAL) { if ((ifp->if_u1.if_data != ifp->if_u2.if_inline_data) && (ifp->if_u1.if_data != NULL)) { ASSERT(ifp->if_real_bytes != 0); kmem_free(ifp->if_u1.if_data); ifp->if_u1.if_data = NULL; ifp->if_real_bytes = 0; } } else if ((ifp->if_flags & XFS_IFEXTENTS) && ((ifp->if_flags & XFS_IFEXTIREC) || ((ifp->if_u1.if_extents != NULL) && (ifp->if_u1.if_extents != ifp->if_u2.if_inline_ext)))) { ASSERT(ifp->if_real_bytes != 0); xfs_iext_destroy(ifp); } ASSERT(ifp->if_u1.if_extents == NULL || ifp->if_u1.if_extents == ifp->if_u2.if_inline_ext); ASSERT(ifp->if_real_bytes == 0); if (whichfork == XFS_ATTR_FORK) { kmem_zone_free(xfs_ifork_zone, ip->i_afp); ip->i_afp = NULL; } } /* * xfs_iextents_copy() * * This is called to copy the REAL extents (as opposed to the delayed * allocation extents) from the inode into the given buffer. It * returns the number of bytes copied into the buffer. * * If there are no delayed allocation extents, then we can just * memcpy() the extents into the buffer. Otherwise, we need to * examine each extent in turn and skip those which are delayed. */ int xfs_iextents_copy( xfs_inode_t *ip, xfs_bmbt_rec_t *dp, int whichfork) { int copied; int i; xfs_ifork_t *ifp; int nrecs; xfs_fsblock_t start_block; ifp = XFS_IFORK_PTR(ip, whichfork); ASSERT(xfs_isilocked(ip, XFS_ILOCK_EXCL|XFS_ILOCK_SHARED)); ASSERT(ifp->if_bytes > 0); nrecs = ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t); XFS_BMAP_TRACE_EXLIST(ip, nrecs, whichfork); ASSERT(nrecs > 0); /* * There are some delayed allocation extents in the * inode, so copy the extents one at a time and skip * the delayed ones. There must be at least one * non-delayed extent. */ copied = 0; for (i = 0; i < nrecs; i++) { xfs_bmbt_rec_host_t *ep = xfs_iext_get_ext(ifp, i); start_block = xfs_bmbt_get_startblock(ep); if (isnullstartblock(start_block)) { /* * It's a delayed allocation extent, so skip it. */ continue; } /* Translate to on disk format */ put_unaligned_be64(ep->l0, &dp->l0); put_unaligned_be64(ep->l1, &dp->l1); dp++; copied++; } ASSERT(copied != 0); xfs_validate_extents(ifp, copied, XFS_EXTFMT_INODE(ip)); return (copied * (uint)sizeof(xfs_bmbt_rec_t)); } /* * Each of the following cases stores data into the same region * of the on-disk inode, so only one of them can be valid at * any given time. While it is possible to have conflicting formats * and log flags, e.g. having XFS_ILOG_?DATA set when the fork is * in EXTENTS format, this can only happen when the fork has * changed formats after being modified but before being flushed. * In these cases, the format always takes precedence, because the * format indicates the current state of the fork. */ void xfs_iflush_fork( xfs_inode_t *ip, xfs_dinode_t *dip, xfs_inode_log_item_t *iip, int whichfork, xfs_buf_t *bp) { char *cp; xfs_ifork_t *ifp; xfs_mount_t *mp; static const short brootflag[2] = { XFS_ILOG_DBROOT, XFS_ILOG_ABROOT }; static const short dataflag[2] = { XFS_ILOG_DDATA, XFS_ILOG_ADATA }; static const short extflag[2] = { XFS_ILOG_DEXT, XFS_ILOG_AEXT }; if (!iip) return; ifp = XFS_IFORK_PTR(ip, whichfork); /* * This can happen if we gave up in iformat in an error path, * for the attribute fork. */ if (!ifp) { ASSERT(whichfork == XFS_ATTR_FORK); return; } cp = XFS_DFORK_PTR(dip, whichfork); mp = ip->i_mount; switch (XFS_IFORK_FORMAT(ip, whichfork)) { case XFS_DINODE_FMT_LOCAL: if ((iip->ili_fields & dataflag[whichfork]) && (ifp->if_bytes > 0)) { ASSERT(ifp->if_u1.if_data != NULL); ASSERT(ifp->if_bytes <= XFS_IFORK_SIZE(ip, whichfork)); memcpy(cp, ifp->if_u1.if_data, ifp->if_bytes); } break; case XFS_DINODE_FMT_EXTENTS: ASSERT((ifp->if_flags & XFS_IFEXTENTS) || !(iip->ili_fields & extflag[whichfork])); if ((iip->ili_fields & extflag[whichfork]) && (ifp->if_bytes > 0)) { ASSERT(xfs_iext_get_ext(ifp, 0)); ASSERT(XFS_IFORK_NEXTENTS(ip, whichfork) > 0); (void)xfs_iextents_copy(ip, (xfs_bmbt_rec_t *)cp, whichfork); } break; case XFS_DINODE_FMT_BTREE: if ((iip->ili_fields & brootflag[whichfork]) && (ifp->if_broot_bytes > 0)) { ASSERT(ifp->if_broot != NULL); ASSERT(XFS_BMAP_BMDR_SPACE(ifp->if_broot) <= XFS_IFORK_SIZE(ip, whichfork)); xfs_bmbt_to_bmdr(mp, ifp->if_broot, ifp->if_broot_bytes, (xfs_bmdr_block_t *)cp, XFS_DFORK_SIZE(dip, mp, whichfork)); } break; case XFS_DINODE_FMT_DEV: if (iip->ili_fields & XFS_ILOG_DEV) { ASSERT(whichfork == XFS_DATA_FORK); xfs_dinode_put_rdev(dip, ip->i_df.if_u2.if_rdev); } break; case XFS_DINODE_FMT_UUID: if (iip->ili_fields & XFS_ILOG_UUID) { ASSERT(whichfork == XFS_DATA_FORK); memcpy(XFS_DFORK_DPTR(dip), &ip->i_df.if_u2.if_uuid, sizeof(uuid_t)); } break; default: ASSERT(0); break; } } /* * Return a pointer to the extent record at file index idx. */ xfs_bmbt_rec_host_t * xfs_iext_get_ext( xfs_ifork_t *ifp, /* inode fork pointer */ xfs_extnum_t idx) /* index of target extent */ { ASSERT(idx >= 0); ASSERT(idx < ifp->if_bytes / sizeof(xfs_bmbt_rec_t)); if ((ifp->if_flags & XFS_IFEXTIREC) && (idx == 0)) { return ifp->if_u1.if_ext_irec->er_extbuf; } else if (ifp->if_flags & XFS_IFEXTIREC) { xfs_ext_irec_t *erp; /* irec pointer */ int erp_idx = 0; /* irec index */ xfs_extnum_t page_idx = idx; /* ext index in target list */ erp = xfs_iext_idx_to_irec(ifp, &page_idx, &erp_idx, 0); return &erp->er_extbuf[page_idx]; } else if (ifp->if_bytes) { return &ifp->if_u1.if_extents[idx]; } else { return NULL; } } /* * Insert new item(s) into the extent records for incore inode * fork 'ifp'. 'count' new items are inserted at index 'idx'. */ void xfs_iext_insert( xfs_inode_t *ip, /* incore inode pointer */ xfs_extnum_t idx, /* starting index of new items */ xfs_extnum_t count, /* number of inserted items */ xfs_bmbt_irec_t *new, /* items to insert */ int state) /* type of extent conversion */ { xfs_ifork_t *ifp = (state & BMAP_ATTRFORK) ? ip->i_afp : &ip->i_df; xfs_extnum_t i; /* extent record index */ trace_xfs_iext_insert(ip, idx, new, state, _RET_IP_); ASSERT(ifp->if_flags & XFS_IFEXTENTS); xfs_iext_add(ifp, idx, count); for (i = idx; i < idx + count; i++, new++) xfs_bmbt_set_all(xfs_iext_get_ext(ifp, i), new); } /* * This is called when the amount of space required for incore file * extents needs to be increased. The ext_diff parameter stores the * number of new extents being added and the idx parameter contains * the extent index where the new extents will be added. If the new * extents are being appended, then we just need to (re)allocate and * initialize the space. Otherwise, if the new extents are being * inserted into the middle of the existing entries, a bit more work * is required to make room for the new extents to be inserted. The * caller is responsible for filling in the new extent entries upon * return. */ void xfs_iext_add( xfs_ifork_t *ifp, /* inode fork pointer */ xfs_extnum_t idx, /* index to begin adding exts */ int ext_diff) /* number of extents to add */ { int byte_diff; /* new bytes being added */ int new_size; /* size of extents after adding */ xfs_extnum_t nextents; /* number of extents in file */ nextents = ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t); ASSERT((idx >= 0) && (idx <= nextents)); byte_diff = ext_diff * sizeof(xfs_bmbt_rec_t); new_size = ifp->if_bytes + byte_diff; /* * If the new number of extents (nextents + ext_diff) * fits inside the inode, then continue to use the inline * extent buffer. */ if (nextents + ext_diff <= XFS_INLINE_EXTS) { if (idx < nextents) { memmove(&ifp->if_u2.if_inline_ext[idx + ext_diff], &ifp->if_u2.if_inline_ext[idx], (nextents - idx) * sizeof(xfs_bmbt_rec_t)); memset(&ifp->if_u2.if_inline_ext[idx], 0, byte_diff); } ifp->if_u1.if_extents = ifp->if_u2.if_inline_ext; ifp->if_real_bytes = 0; } /* * Otherwise use a linear (direct) extent list. * If the extents are currently inside the inode, * xfs_iext_realloc_direct will switch us from * inline to direct extent allocation mode. */ else if (nextents + ext_diff <= XFS_LINEAR_EXTS) { xfs_iext_realloc_direct(ifp, new_size); if (idx < nextents) { memmove(&ifp->if_u1.if_extents[idx + ext_diff], &ifp->if_u1.if_extents[idx], (nextents - idx) * sizeof(xfs_bmbt_rec_t)); memset(&ifp->if_u1.if_extents[idx], 0, byte_diff); } } /* Indirection array */ else { xfs_ext_irec_t *erp; int erp_idx = 0; int page_idx = idx; ASSERT(nextents + ext_diff > XFS_LINEAR_EXTS); if (ifp->if_flags & XFS_IFEXTIREC) { erp = xfs_iext_idx_to_irec(ifp, &page_idx, &erp_idx, 1); } else { xfs_iext_irec_init(ifp); ASSERT(ifp->if_flags & XFS_IFEXTIREC); erp = ifp->if_u1.if_ext_irec; } /* Extents fit in target extent page */ if (erp && erp->er_extcount + ext_diff <= XFS_LINEAR_EXTS) { if (page_idx < erp->er_extcount) { memmove(&erp->er_extbuf[page_idx + ext_diff], &erp->er_extbuf[page_idx], (erp->er_extcount - page_idx) * sizeof(xfs_bmbt_rec_t)); memset(&erp->er_extbuf[page_idx], 0, byte_diff); } erp->er_extcount += ext_diff; xfs_iext_irec_update_extoffs(ifp, erp_idx + 1, ext_diff); } /* Insert a new extent page */ else if (erp) { xfs_iext_add_indirect_multi(ifp, erp_idx, page_idx, ext_diff); } /* * If extent(s) are being appended to the last page in * the indirection array and the new extent(s) don't fit * in the page, then erp is NULL and erp_idx is set to * the next index needed in the indirection array. */ else { uint count = ext_diff; while (count) { erp = xfs_iext_irec_new(ifp, erp_idx); erp->er_extcount = min(count, XFS_LINEAR_EXTS); count -= erp->er_extcount; if (count) erp_idx++; } } } ifp->if_bytes = new_size; } /* * This is called when incore extents are being added to the indirection * array and the new extents do not fit in the target extent list. The * erp_idx parameter contains the irec index for the target extent list * in the indirection array, and the idx parameter contains the extent * index within the list. The number of extents being added is stored * in the count parameter. * * |-------| |-------| * | | | | idx - number of extents before idx * | idx | | count | * | | | | count - number of extents being inserted at idx * |-------| |-------| * | count | | nex2 | nex2 - number of extents after idx + count * |-------| |-------| */ void xfs_iext_add_indirect_multi( xfs_ifork_t *ifp, /* inode fork pointer */ int erp_idx, /* target extent irec index */ xfs_extnum_t idx, /* index within target list */ int count) /* new extents being added */ { int byte_diff; /* new bytes being added */ xfs_ext_irec_t *erp; /* pointer to irec entry */ xfs_extnum_t ext_diff; /* number of extents to add */ xfs_extnum_t ext_cnt; /* new extents still needed */ xfs_extnum_t nex2; /* extents after idx + count */ xfs_bmbt_rec_t *nex2_ep = NULL; /* temp list for nex2 extents */ int nlists; /* number of irec's (lists) */ ASSERT(ifp->if_flags & XFS_IFEXTIREC); erp = &ifp->if_u1.if_ext_irec[erp_idx]; nex2 = erp->er_extcount - idx; nlists = ifp->if_real_bytes / XFS_IEXT_BUFSZ; /* * Save second part of target extent list * (all extents past */ if (nex2) { byte_diff = nex2 * sizeof(xfs_bmbt_rec_t); nex2_ep = (xfs_bmbt_rec_t *) kmem_alloc(byte_diff, KM_NOFS); memmove(nex2_ep, &erp->er_extbuf[idx], byte_diff); erp->er_extcount -= nex2; xfs_iext_irec_update_extoffs(ifp, erp_idx + 1, -nex2); memset(&erp->er_extbuf[idx], 0, byte_diff); } /* * Add the new extents to the end of the target * list, then allocate new irec record(s) and * extent buffer(s) as needed to store the rest * of the new extents. */ ext_cnt = count; ext_diff = MIN(ext_cnt, (int)XFS_LINEAR_EXTS - erp->er_extcount); if (ext_diff) { erp->er_extcount += ext_diff; xfs_iext_irec_update_extoffs(ifp, erp_idx + 1, ext_diff); ext_cnt -= ext_diff; } while (ext_cnt) { erp_idx++; erp = xfs_iext_irec_new(ifp, erp_idx); ext_diff = MIN(ext_cnt, (int)XFS_LINEAR_EXTS); erp->er_extcount = ext_diff; xfs_iext_irec_update_extoffs(ifp, erp_idx + 1, ext_diff); ext_cnt -= ext_diff; } /* Add nex2 extents back to indirection array */ if (nex2) { xfs_extnum_t ext_avail; int i; byte_diff = nex2 * sizeof(xfs_bmbt_rec_t); ext_avail = XFS_LINEAR_EXTS - erp->er_extcount; i = 0; /* * If nex2 extents fit in the current page, append * nex2_ep after the new extents. */ if (nex2 <= ext_avail) { i = erp->er_extcount; } /* * Otherwise, check if space is available in the * next page. */ else if ((erp_idx < nlists - 1) && (nex2 <= (ext_avail = XFS_LINEAR_EXTS - ifp->if_u1.if_ext_irec[erp_idx+1].er_extcount))) { erp_idx++; erp++; /* Create a hole for nex2 extents */ memmove(&erp->er_extbuf[nex2], erp->er_extbuf, erp->er_extcount * sizeof(xfs_bmbt_rec_t)); } /* * Final choice, create a new extent page for * nex2 extents. */ else { erp_idx++; erp = xfs_iext_irec_new(ifp, erp_idx); } memmove(&erp->er_extbuf[i], nex2_ep, byte_diff); kmem_free(nex2_ep); erp->er_extcount += nex2; xfs_iext_irec_update_extoffs(ifp, erp_idx + 1, nex2); } } /* * This is called when the amount of space required for incore file * extents needs to be decreased. The ext_diff parameter stores the * number of extents to be removed and the idx parameter contains * the extent index where the extents will be removed from. * * If the amount of space needed has decreased below the linear * limit, XFS_IEXT_BUFSZ, then switch to using the contiguous * extent array. Otherwise, use kmem_realloc() to adjust the * size to what is needed. */ void xfs_iext_remove( xfs_inode_t *ip, /* incore inode pointer */ xfs_extnum_t idx, /* index to begin removing exts */ int ext_diff, /* number of extents to remove */ int state) /* type of extent conversion */ { xfs_ifork_t *ifp = (state & BMAP_ATTRFORK) ? ip->i_afp : &ip->i_df; xfs_extnum_t nextents; /* number of extents in file */ int new_size; /* size of extents after removal */ trace_xfs_iext_remove(ip, idx, state, _RET_IP_); ASSERT(ext_diff > 0); nextents = ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t); new_size = (nextents - ext_diff) * sizeof(xfs_bmbt_rec_t); if (new_size == 0) { xfs_iext_destroy(ifp); } else if (ifp->if_flags & XFS_IFEXTIREC) { xfs_iext_remove_indirect(ifp, idx, ext_diff); } else if (ifp->if_real_bytes) { xfs_iext_remove_direct(ifp, idx, ext_diff); } else { xfs_iext_remove_inline(ifp, idx, ext_diff); } ifp->if_bytes = new_size; } /* * This removes ext_diff extents from the inline buffer, beginning * at extent index idx. */ void xfs_iext_remove_inline( xfs_ifork_t *ifp, /* inode fork pointer */ xfs_extnum_t idx, /* index to begin removing exts */ int ext_diff) /* number of extents to remove */ { int nextents; /* number of extents in file */ ASSERT(!(ifp->if_flags & XFS_IFEXTIREC)); ASSERT(idx < XFS_INLINE_EXTS); nextents = ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t); ASSERT(((nextents - ext_diff) > 0) && (nextents - ext_diff) < XFS_INLINE_EXTS); if (idx + ext_diff < nextents) { memmove(&ifp->if_u2.if_inline_ext[idx], &ifp->if_u2.if_inline_ext[idx + ext_diff], (nextents - (idx + ext_diff)) * sizeof(xfs_bmbt_rec_t)); memset(&ifp->if_u2.if_inline_ext[nextents - ext_diff], 0, ext_diff * sizeof(xfs_bmbt_rec_t)); } else { memset(&ifp->if_u2.if_inline_ext[idx], 0, ext_diff * sizeof(xfs_bmbt_rec_t)); } } /* * This removes ext_diff extents from a linear (direct) extent list, * beginning at extent index idx. If the extents are being removed * from the end of the list (ie. truncate) then we just need to re- * allocate the list to remove the extra space. Otherwise, if the * extents are being removed from the middle of the existing extent * entries, then we first need to move the extent records beginning * at idx + ext_diff up in the list to overwrite the records being * removed, then remove the extra space via kmem_realloc. */ void xfs_iext_remove_direct( xfs_ifork_t *ifp, /* inode fork pointer */ xfs_extnum_t idx, /* index to begin removing exts */ int ext_diff) /* number of extents to remove */ { xfs_extnum_t nextents; /* number of extents in file */ int new_size; /* size of extents after removal */ ASSERT(!(ifp->if_flags & XFS_IFEXTIREC)); new_size = ifp->if_bytes - (ext_diff * sizeof(xfs_bmbt_rec_t)); nextents = ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t); if (new_size == 0) { xfs_iext_destroy(ifp); return; } /* Move extents up in the list (if needed) */ if (idx + ext_diff < nextents) { memmove(&ifp->if_u1.if_extents[idx], &ifp->if_u1.if_extents[idx + ext_diff], (nextents - (idx + ext_diff)) * sizeof(xfs_bmbt_rec_t)); } memset(&ifp->if_u1.if_extents[nextents - ext_diff], 0, ext_diff * sizeof(xfs_bmbt_rec_t)); /* * Reallocate the direct extent list. If the extents * will fit inside the inode then xfs_iext_realloc_direct * will switch from direct to inline extent allocation * mode for us. */ xfs_iext_realloc_direct(ifp, new_size); ifp->if_bytes = new_size; } /* * This is called when incore extents are being removed from the * indirection array and the extents being removed span multiple extent * buffers. The idx parameter contains the file extent index where we * want to begin removing extents, and the count parameter contains * how many extents need to be removed. * * |-------| |-------| * | nex1 | | | nex1 - number of extents before idx * |-------| | count | * | | | | count - number of extents being removed at idx * | count | |-------| * | | | nex2 | nex2 - number of extents after idx + count * |-------| |-------| */ void xfs_iext_remove_indirect( xfs_ifork_t *ifp, /* inode fork pointer */ xfs_extnum_t idx, /* index to begin removing extents */ int count) /* number of extents to remove */ { xfs_ext_irec_t *erp; /* indirection array pointer */ int erp_idx = 0; /* indirection array index */ xfs_extnum_t ext_cnt; /* extents left to remove */ xfs_extnum_t ext_diff; /* extents to remove in current list */ xfs_extnum_t nex1; /* number of extents before idx */ xfs_extnum_t nex2; /* extents after idx + count */ int page_idx = idx; /* index in target extent list */ ASSERT(ifp->if_flags & XFS_IFEXTIREC); erp = xfs_iext_idx_to_irec(ifp, &page_idx, &erp_idx, 0); ASSERT(erp != NULL); nex1 = page_idx; ext_cnt = count; while (ext_cnt) { nex2 = MAX((erp->er_extcount - (nex1 + ext_cnt)), 0); ext_diff = MIN(ext_cnt, (erp->er_extcount - nex1)); /* * Check for deletion of entire list; * xfs_iext_irec_remove() updates extent offsets. */ if (ext_diff == erp->er_extcount) { xfs_iext_irec_remove(ifp, erp_idx); ext_cnt -= ext_diff; nex1 = 0; if (ext_cnt) { ASSERT(erp_idx < ifp->if_real_bytes / XFS_IEXT_BUFSZ); erp = &ifp->if_u1.if_ext_irec[erp_idx]; nex1 = 0; continue; } else { break; } } /* Move extents up (if needed) */ if (nex2) { memmove(&erp->er_extbuf[nex1], &erp->er_extbuf[nex1 + ext_diff], nex2 * sizeof(xfs_bmbt_rec_t)); } /* Zero out rest of page */ memset(&erp->er_extbuf[nex1 + nex2], 0, (XFS_IEXT_BUFSZ - ((nex1 + nex2) * sizeof(xfs_bmbt_rec_t)))); /* Update remaining counters */ erp->er_extcount -= ext_diff; xfs_iext_irec_update_extoffs(ifp, erp_idx + 1, -ext_diff); ext_cnt -= ext_diff; nex1 = 0; erp_idx++; erp++; } ifp->if_bytes -= count * sizeof(xfs_bmbt_rec_t); xfs_iext_irec_compact(ifp); } /* * Create, destroy, or resize a linear (direct) block of extents. */ void xfs_iext_realloc_direct( xfs_ifork_t *ifp, /* inode fork pointer */ int new_size) /* new size of extents after adding */ { int rnew_size; /* real new size of extents */ rnew_size = new_size; ASSERT(!(ifp->if_flags & XFS_IFEXTIREC) || ((new_size >= 0) && (new_size <= XFS_IEXT_BUFSZ) && (new_size != ifp->if_real_bytes))); /* Free extent records */ if (new_size == 0) { xfs_iext_destroy(ifp); } /* Resize direct extent list and zero any new bytes */ else if (ifp->if_real_bytes) { /* Check if extents will fit inside the inode */ if (new_size <= XFS_INLINE_EXTS * sizeof(xfs_bmbt_rec_t)) { xfs_iext_direct_to_inline(ifp, new_size / (uint)sizeof(xfs_bmbt_rec_t)); ifp->if_bytes = new_size; return; } if (!is_power_of_2(new_size)){ rnew_size = roundup_pow_of_two(new_size); } if (rnew_size != ifp->if_real_bytes) { ifp->if_u1.if_extents = kmem_realloc(ifp->if_u1.if_extents, rnew_size, ifp->if_real_bytes, KM_NOFS); } if (rnew_size > ifp->if_real_bytes) { memset(&ifp->if_u1.if_extents[ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t)], 0, rnew_size - ifp->if_real_bytes); } } /* Switch from the inline extent buffer to a direct extent list */ else { if (!is_power_of_2(new_size)) { rnew_size = roundup_pow_of_two(new_size); } xfs_iext_inline_to_direct(ifp, rnew_size); } ifp->if_real_bytes = rnew_size; ifp->if_bytes = new_size; } /* * Switch from linear (direct) extent records to inline buffer. */ void xfs_iext_direct_to_inline( xfs_ifork_t *ifp, /* inode fork pointer */ xfs_extnum_t nextents) /* number of extents in file */ { ASSERT(ifp->if_flags & XFS_IFEXTENTS); ASSERT(nextents <= XFS_INLINE_EXTS); /* * The inline buffer was zeroed when we switched * from inline to direct extent allocation mode, * so we don't need to clear it here. */ memcpy(ifp->if_u2.if_inline_ext, ifp->if_u1.if_extents, nextents * sizeof(xfs_bmbt_rec_t)); kmem_free(ifp->if_u1.if_extents); ifp->if_u1.if_extents = ifp->if_u2.if_inline_ext; ifp->if_real_bytes = 0; } /* * Switch from inline buffer to linear (direct) extent records. * new_size should already be rounded up to the next power of 2 * by the caller (when appropriate), so use new_size as it is. * However, since new_size may be rounded up, we can't update * if_bytes here. It is the caller's responsibility to update * if_bytes upon return. */ void xfs_iext_inline_to_direct( xfs_ifork_t *ifp, /* inode fork pointer */ int new_size) /* number of extents in file */ { ifp->if_u1.if_extents = kmem_alloc(new_size, KM_NOFS); memset(ifp->if_u1.if_extents, 0, new_size); if (ifp->if_bytes) { memcpy(ifp->if_u1.if_extents, ifp->if_u2.if_inline_ext, ifp->if_bytes); memset(ifp->if_u2.if_inline_ext, 0, XFS_INLINE_EXTS * sizeof(xfs_bmbt_rec_t)); } ifp->if_real_bytes = new_size; } /* * Resize an extent indirection array to new_size bytes. */ STATIC void xfs_iext_realloc_indirect( xfs_ifork_t *ifp, /* inode fork pointer */ int new_size) /* new indirection array size */ { int nlists; /* number of irec's (ex lists) */ int size; /* current indirection array size */ ASSERT(ifp->if_flags & XFS_IFEXTIREC); nlists = ifp->if_real_bytes / XFS_IEXT_BUFSZ; size = nlists * sizeof(xfs_ext_irec_t); ASSERT(ifp->if_real_bytes); ASSERT((new_size >= 0) && (new_size != size)); if (new_size == 0) { xfs_iext_destroy(ifp); } else { ifp->if_u1.if_ext_irec = (xfs_ext_irec_t *) kmem_realloc(ifp->if_u1.if_ext_irec, new_size, size, KM_NOFS); } } /* * Switch from indirection array to linear (direct) extent allocations. */ STATIC void xfs_iext_indirect_to_direct( xfs_ifork_t *ifp) /* inode fork pointer */ { xfs_bmbt_rec_host_t *ep; /* extent record pointer */ xfs_extnum_t nextents; /* number of extents in file */ int size; /* size of file extents */ ASSERT(ifp->if_flags & XFS_IFEXTIREC); nextents = ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t); ASSERT(nextents <= XFS_LINEAR_EXTS); size = nextents * sizeof(xfs_bmbt_rec_t); xfs_iext_irec_compact_pages(ifp); ASSERT(ifp->if_real_bytes == XFS_IEXT_BUFSZ); ep = ifp->if_u1.if_ext_irec->er_extbuf; kmem_free(ifp->if_u1.if_ext_irec); ifp->if_flags &= ~XFS_IFEXTIREC; ifp->if_u1.if_extents = ep; ifp->if_bytes = size; if (nextents < XFS_LINEAR_EXTS) { xfs_iext_realloc_direct(ifp, size); } } /* * Free incore file extents. */ void xfs_iext_destroy( xfs_ifork_t *ifp) /* inode fork pointer */ { if (ifp->if_flags & XFS_IFEXTIREC) { int erp_idx; int nlists; nlists = ifp->if_real_bytes / XFS_IEXT_BUFSZ; for (erp_idx = nlists - 1; erp_idx >= 0 ; erp_idx--) { xfs_iext_irec_remove(ifp, erp_idx); } ifp->if_flags &= ~XFS_IFEXTIREC; } else if (ifp->if_real_bytes) { kmem_free(ifp->if_u1.if_extents); } else if (ifp->if_bytes) { memset(ifp->if_u2.if_inline_ext, 0, XFS_INLINE_EXTS * sizeof(xfs_bmbt_rec_t)); } ifp->if_u1.if_extents = NULL; ifp->if_real_bytes = 0; ifp->if_bytes = 0; } /* * Return a pointer to the extent record for file system block bno. */ xfs_bmbt_rec_host_t * /* pointer to found extent record */ xfs_iext_bno_to_ext( xfs_ifork_t *ifp, /* inode fork pointer */ xfs_fileoff_t bno, /* block number to search for */ xfs_extnum_t *idxp) /* index of target extent */ { xfs_bmbt_rec_host_t *base; /* pointer to first extent */ xfs_filblks_t blockcount = 0; /* number of blocks in extent */ xfs_bmbt_rec_host_t *ep = NULL; /* pointer to target extent */ xfs_ext_irec_t *erp = NULL; /* indirection array pointer */ int high; /* upper boundary in search */ xfs_extnum_t idx = 0; /* index of target extent */ int low; /* lower boundary in search */ xfs_extnum_t nextents; /* number of file extents */ xfs_fileoff_t startoff = 0; /* start offset of extent */ nextents = ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t); if (nextents == 0) { *idxp = 0; return NULL; } low = 0; if (ifp->if_flags & XFS_IFEXTIREC) { /* Find target extent list */ int erp_idx = 0; erp = xfs_iext_bno_to_irec(ifp, bno, &erp_idx); base = erp->er_extbuf; high = erp->er_extcount - 1; } else { base = ifp->if_u1.if_extents; high = nextents - 1; } /* Binary search extent records */ while (low <= high) { idx = (low + high) >> 1; ep = base + idx; startoff = xfs_bmbt_get_startoff(ep); blockcount = xfs_bmbt_get_blockcount(ep); if (bno < startoff) { high = idx - 1; } else if (bno >= startoff + blockcount) { low = idx + 1; } else { /* Convert back to file-based extent index */ if (ifp->if_flags & XFS_IFEXTIREC) { idx += erp->er_extoff; } *idxp = idx; return ep; } } /* Convert back to file-based extent index */ if (ifp->if_flags & XFS_IFEXTIREC) { idx += erp->er_extoff; } if (bno >= startoff + blockcount) { if (++idx == nextents) { ep = NULL; } else { ep = xfs_iext_get_ext(ifp, idx); } } *idxp = idx; return ep; } /* * Return a pointer to the indirection array entry containing the * extent record for filesystem block bno. Store the index of the * target irec in *erp_idxp. */ xfs_ext_irec_t * /* pointer to found extent record */ xfs_iext_bno_to_irec( xfs_ifork_t *ifp, /* inode fork pointer */ xfs_fileoff_t bno, /* block number to search for */ int *erp_idxp) /* irec index of target ext list */ { xfs_ext_irec_t *erp = NULL; /* indirection array pointer */ xfs_ext_irec_t *erp_next; /* next indirection array entry */ int erp_idx; /* indirection array index */ int nlists; /* number of extent irec's (lists) */ int high; /* binary search upper limit */ int low; /* binary search lower limit */ ASSERT(ifp->if_flags & XFS_IFEXTIREC); nlists = ifp->if_real_bytes / XFS_IEXT_BUFSZ; erp_idx = 0; low = 0; high = nlists - 1; while (low <= high) { erp_idx = (low + high) >> 1; erp = &ifp->if_u1.if_ext_irec[erp_idx]; erp_next = erp_idx < nlists - 1 ? erp + 1 : NULL; if (bno < xfs_bmbt_get_startoff(erp->er_extbuf)) { high = erp_idx - 1; } else if (erp_next && bno >= xfs_bmbt_get_startoff(erp_next->er_extbuf)) { low = erp_idx + 1; } else { break; } } *erp_idxp = erp_idx; return erp; } /* * Return a pointer to the indirection array entry containing the * extent record at file extent index *idxp. Store the index of the * target irec in *erp_idxp and store the page index of the target * extent record in *idxp. */ xfs_ext_irec_t * xfs_iext_idx_to_irec( xfs_ifork_t *ifp, /* inode fork pointer */ xfs_extnum_t *idxp, /* extent index (file -> page) */ int *erp_idxp, /* pointer to target irec */ int realloc) /* new bytes were just added */ { xfs_ext_irec_t *prev; /* pointer to previous irec */ xfs_ext_irec_t *erp = NULL; /* pointer to current irec */ int erp_idx; /* indirection array index */ int nlists; /* number of irec's (ex lists) */ int high; /* binary search upper limit */ int low; /* binary search lower limit */ xfs_extnum_t page_idx = *idxp; /* extent index in target list */ ASSERT(ifp->if_flags & XFS_IFEXTIREC); ASSERT(page_idx >= 0); ASSERT(page_idx <= ifp->if_bytes / sizeof(xfs_bmbt_rec_t)); ASSERT(page_idx < ifp->if_bytes / sizeof(xfs_bmbt_rec_t) || realloc); nlists = ifp->if_real_bytes / XFS_IEXT_BUFSZ; erp_idx = 0; low = 0; high = nlists - 1; /* Binary search extent irec's */ while (low <= high) { erp_idx = (low + high) >> 1; erp = &ifp->if_u1.if_ext_irec[erp_idx]; prev = erp_idx > 0 ? erp - 1 : NULL; if (page_idx < erp->er_extoff || (page_idx == erp->er_extoff && realloc && prev && prev->er_extcount < XFS_LINEAR_EXTS)) { high = erp_idx - 1; } else if (page_idx > erp->er_extoff + erp->er_extcount || (page_idx == erp->er_extoff + erp->er_extcount && !realloc)) { low = erp_idx + 1; } else if (page_idx == erp->er_extoff + erp->er_extcount && erp->er_extcount == XFS_LINEAR_EXTS) { ASSERT(realloc); page_idx = 0; erp_idx++; erp = erp_idx < nlists ? erp + 1 : NULL; break; } else { page_idx -= erp->er_extoff; break; } } *idxp = page_idx; *erp_idxp = erp_idx; return(erp); } /* * Allocate and initialize an indirection array once the space needed * for incore extents increases above XFS_IEXT_BUFSZ. */ void xfs_iext_irec_init( xfs_ifork_t *ifp) /* inode fork pointer */ { xfs_ext_irec_t *erp; /* indirection array pointer */ xfs_extnum_t nextents; /* number of extents in file */ ASSERT(!(ifp->if_flags & XFS_IFEXTIREC)); nextents = ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t); ASSERT(nextents <= XFS_LINEAR_EXTS); erp = kmem_alloc(sizeof(xfs_ext_irec_t), KM_NOFS); if (nextents == 0) { ifp->if_u1.if_extents = kmem_alloc(XFS_IEXT_BUFSZ, KM_NOFS); } else if (!ifp->if_real_bytes) { xfs_iext_inline_to_direct(ifp, XFS_IEXT_BUFSZ); } else if (ifp->if_real_bytes < XFS_IEXT_BUFSZ) { xfs_iext_realloc_direct(ifp, XFS_IEXT_BUFSZ); } erp->er_extbuf = ifp->if_u1.if_extents; erp->er_extcount = nextents; erp->er_extoff = 0; ifp->if_flags |= XFS_IFEXTIREC; ifp->if_real_bytes = XFS_IEXT_BUFSZ; ifp->if_bytes = nextents * sizeof(xfs_bmbt_rec_t); ifp->if_u1.if_ext_irec = erp; return; } /* * Allocate and initialize a new entry in the indirection array. */ xfs_ext_irec_t * xfs_iext_irec_new( xfs_ifork_t *ifp, /* inode fork pointer */ int erp_idx) /* index for new irec */ { xfs_ext_irec_t *erp; /* indirection array pointer */ int i; /* loop counter */ int nlists; /* number of irec's (ex lists) */ ASSERT(ifp->if_flags & XFS_IFEXTIREC); nlists = ifp->if_real_bytes / XFS_IEXT_BUFSZ; /* Resize indirection array */ xfs_iext_realloc_indirect(ifp, ++nlists * sizeof(xfs_ext_irec_t)); /* * Move records down in the array so the * new page can use erp_idx. */ erp = ifp->if_u1.if_ext_irec; for (i = nlists - 1; i > erp_idx; i--) { memmove(&erp[i], &erp[i-1], sizeof(xfs_ext_irec_t)); } ASSERT(i == erp_idx); /* Initialize new extent record */ erp = ifp->if_u1.if_ext_irec; erp[erp_idx].er_extbuf = kmem_alloc(XFS_IEXT_BUFSZ, KM_NOFS); ifp->if_real_bytes = nlists * XFS_IEXT_BUFSZ; memset(erp[erp_idx].er_extbuf, 0, XFS_IEXT_BUFSZ); erp[erp_idx].er_extcount = 0; erp[erp_idx].er_extoff = erp_idx > 0 ? erp[erp_idx-1].er_extoff + erp[erp_idx-1].er_extcount : 0; return (&erp[erp_idx]); } /* * Remove a record from the indirection array. */ void xfs_iext_irec_remove( xfs_ifork_t *ifp, /* inode fork pointer */ int erp_idx) /* irec index to remove */ { xfs_ext_irec_t *erp; /* indirection array pointer */ int i; /* loop counter */ int nlists; /* number of irec's (ex lists) */ ASSERT(ifp->if_flags & XFS_IFEXTIREC); nlists = ifp->if_real_bytes / XFS_IEXT_BUFSZ; erp = &ifp->if_u1.if_ext_irec[erp_idx]; if (erp->er_extbuf) { xfs_iext_irec_update_extoffs(ifp, erp_idx + 1, -erp->er_extcount); kmem_free(erp->er_extbuf); } /* Compact extent records */ erp = ifp->if_u1.if_ext_irec; for (i = erp_idx; i < nlists - 1; i++) { memmove(&erp[i], &erp[i+1], sizeof(xfs_ext_irec_t)); } /* * Manually free the last extent record from the indirection * array. A call to xfs_iext_realloc_indirect() with a size * of zero would result in a call to xfs_iext_destroy() which * would in turn call this function again, creating a nasty * infinite loop. */ if (--nlists) { xfs_iext_realloc_indirect(ifp, nlists * sizeof(xfs_ext_irec_t)); } else { kmem_free(ifp->if_u1.if_ext_irec); } ifp->if_real_bytes = nlists * XFS_IEXT_BUFSZ; } /* * This is called to clean up large amounts of unused memory allocated * by the indirection array. Before compacting anything though, verify * that the indirection array is still needed and switch back to the * linear extent list (or even the inline buffer) if possible. The * compaction policy is as follows: * * Full Compaction: Extents fit into a single page (or inline buffer) * Partial Compaction: Extents occupy less than 50% of allocated space * No Compaction: Extents occupy at least 50% of allocated space */ void xfs_iext_irec_compact( xfs_ifork_t *ifp) /* inode fork pointer */ { xfs_extnum_t nextents; /* number of extents in file */ int nlists; /* number of irec's (ex lists) */ ASSERT(ifp->if_flags & XFS_IFEXTIREC); nlists = ifp->if_real_bytes / XFS_IEXT_BUFSZ; nextents = ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t); if (nextents == 0) { xfs_iext_destroy(ifp); } else if (nextents <= XFS_INLINE_EXTS) { xfs_iext_indirect_to_direct(ifp); xfs_iext_direct_to_inline(ifp, nextents); } else if (nextents <= XFS_LINEAR_EXTS) { xfs_iext_indirect_to_direct(ifp); } else if (nextents < (nlists * XFS_LINEAR_EXTS) >> 1) { xfs_iext_irec_compact_pages(ifp); } } /* * Combine extents from neighboring extent pages. */ void xfs_iext_irec_compact_pages( xfs_ifork_t *ifp) /* inode fork pointer */ { xfs_ext_irec_t *erp, *erp_next;/* pointers to irec entries */ int erp_idx = 0; /* indirection array index */ int nlists; /* number of irec's (ex lists) */ ASSERT(ifp->if_flags & XFS_IFEXTIREC); nlists = ifp->if_real_bytes / XFS_IEXT_BUFSZ; while (erp_idx < nlists - 1) { erp = &ifp->if_u1.if_ext_irec[erp_idx]; erp_next = erp + 1; if (erp_next->er_extcount <= (XFS_LINEAR_EXTS - erp->er_extcount)) { memcpy(&erp->er_extbuf[erp->er_extcount], erp_next->er_extbuf, erp_next->er_extcount * sizeof(xfs_bmbt_rec_t)); erp->er_extcount += erp_next->er_extcount; /* * Free page before removing extent record * so er_extoffs don't get modified in * xfs_iext_irec_remove. */ kmem_free(erp_next->er_extbuf); erp_next->er_extbuf = NULL; xfs_iext_irec_remove(ifp, erp_idx + 1); nlists = ifp->if_real_bytes / XFS_IEXT_BUFSZ; } else { erp_idx++; } } } /* * This is called to update the er_extoff field in the indirection * array when extents have been added or removed from one of the * extent lists. erp_idx contains the irec index to begin updating * at and ext_diff contains the number of extents that were added * or removed. */ void xfs_iext_irec_update_extoffs( xfs_ifork_t *ifp, /* inode fork pointer */ int erp_idx, /* irec index to update */ int ext_diff) /* number of new extents */ { int i; /* loop counter */ int nlists; /* number of irec's (ex lists */ ASSERT(ifp->if_flags & XFS_IFEXTIREC); nlists = ifp->if_real_bytes / XFS_IEXT_BUFSZ; for (i = erp_idx; i < nlists; i++) { ifp->if_u1.if_ext_irec[i].er_extoff += ext_diff; } }
1.1875
1
Internetworking Distributed Project/Kernal/linux-3.6.3/drivers/media/dvb/frontends/a8293.c
supriyasingh01/github_basics
0
1332
/* * Allegro A8293 SEC driver * * Copyright (C) 2011 <NAME> <<EMAIL>> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "dvb_frontend.h" #include "a8293.h" struct a8293_priv { struct i2c_adapter *i2c; const struct a8293_config *cfg; u8 reg[2]; }; static int a8293_i2c(struct a8293_priv *priv, u8 *val, int len, bool rd) { int ret; struct i2c_msg msg[1] = { { .addr = priv->cfg->i2c_addr, .len = len, .buf = val, } }; if (rd) msg[0].flags = I2C_M_RD; else msg[0].flags = 0; ret = i2c_transfer(priv->i2c, msg, 1); if (ret == 1) { ret = 0; } else { dev_warn(&priv->i2c->dev, "%s: i2c failed=%d rd=%d\n", KBUILD_MODNAME, ret, rd); ret = -EREMOTEIO; } return ret; } static int a8293_wr(struct a8293_priv *priv, u8 *val, int len) { return a8293_i2c(priv, val, len, 0); } static int a8293_rd(struct a8293_priv *priv, u8 *val, int len) { return a8293_i2c(priv, val, len, 1); } static int a8293_set_voltage(struct dvb_frontend *fe, fe_sec_voltage_t fe_sec_voltage) { struct a8293_priv *priv = fe->sec_priv; int ret; dev_dbg(&priv->i2c->dev, "%s: fe_sec_voltage=%d\n", __func__, fe_sec_voltage); switch (fe_sec_voltage) { case SEC_VOLTAGE_OFF: /* ENB=0 */ priv->reg[0] = 0x10; break; case SEC_VOLTAGE_13: /* VSEL0=1, VSEL1=0, VSEL2=0, VSEL3=0, ENB=1*/ priv->reg[0] = 0x31; break; case SEC_VOLTAGE_18: /* VSEL0=0, VSEL1=0, VSEL2=0, VSEL3=1, ENB=1*/ priv->reg[0] = 0x38; break; default: ret = -EINVAL; goto err; }; ret = a8293_wr(priv, &priv->reg[0], 1); if (ret) goto err; return ret; err: dev_dbg(&priv->i2c->dev, "%s: failed=%d\n", __func__, ret); return ret; } static void a8293_release_sec(struct dvb_frontend *fe) { a8293_set_voltage(fe, SEC_VOLTAGE_OFF); kfree(fe->sec_priv); fe->sec_priv = NULL; } struct dvb_frontend *a8293_attach(struct dvb_frontend *fe, struct i2c_adapter *i2c, const struct a8293_config *cfg) { int ret; struct a8293_priv *priv = NULL; u8 buf[2]; /* allocate memory for the internal priv */ priv = kzalloc(sizeof(struct a8293_priv), GFP_KERNEL); if (priv == NULL) { ret = -ENOMEM; goto err; } /* setup the priv */ priv->i2c = i2c; priv->cfg = cfg; fe->sec_priv = priv; /* check if the SEC is there */ ret = a8293_rd(priv, buf, 2); if (ret) goto err; /* ENB=0 */ priv->reg[0] = 0x10; ret = a8293_wr(priv, &priv->reg[0], 1); if (ret) goto err; /* TMODE=0, TGATE=1 */ priv->reg[1] = 0x82; ret = a8293_wr(priv, &priv->reg[1], 1); if (ret) goto err; fe->ops.release_sec = a8293_release_sec; /* override frontend ops */ fe->ops.set_voltage = a8293_set_voltage; dev_info(&priv->i2c->dev, "%s: Allegro A8293 SEC attached\n", KBUILD_MODNAME); return fe; err: dev_dbg(&i2c->dev, "%s: failed=%d\n", __func__, ret); kfree(priv); return NULL; } EXPORT_SYMBOL(a8293_attach); MODULE_AUTHOR("<NAME> <<EMAIL>>"); MODULE_DESCRIPTION("Allegro A8293 SEC driver"); MODULE_LICENSE("GPL");
1.429688
1
cxx/src/iot_client/src/generate_messages.h
MoysheBenRabi/setp
1
1340
#ifndef GENERATE_MESSAGES_H #define GENERATE_MESSAGES_H /* Copyright (c) 2009-2010 Tyrell Corporation & <NAME>. The contents of this file are subject to the Mozilla Public License Version 1.1 (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.mozilla.org/MPL/ Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. The Original Code is an implementation of the Metaverse eXchange Protocol. The Initial Developer of the Original Code is <NAME> and <NAME>. All Rights Reserved. Contributor(s): <NAME> and <NAME>. Alternatively, the contents of this file may be used under the terms of the Affero General Public License (the "AGPL"), in which case the provisions of the AGPL are applicable instead of those above. If you wish to allow use of your version of this file only under the terms of the AGPL and not to allow others to use your version of this file under the MPL, indicate your decision by deleting the provisions above and replace them with the notice and other provisions required by the AGPL. If you do not delete the provisions above, a recipient may use your version of this file under either the MPL or the AGPL. */ #include <boost/smart_ptr.hpp> #include <mxp.h> void init_object_fragment(mxp::message::object_fragment & of); boost::shared_ptr<mxp::message::join_rq> generate_join_rq(); boost::shared_ptr<mxp::message::inject_rq> generate_inject_rq(); boost::shared_ptr<mxp::message::modify_rq> generate_modify_rq(); boost::shared_ptr<mxp::message::interact_rq> generate_interact_rq(); boost::shared_ptr<mxp::message::examine_rq> generate_examine_rq(); boost::shared_ptr<mxp::message::eject_rq> generate_eject_rq(); boost::shared_ptr<mxp::message::leave_rq> generate_leave_rq(); #endif
0.882813
1
Include/10.0.19041.0/cppwinrt/winrt/impl/Windows.Media.Core.2.h
sezero/windows-sdk-headers
5
1348
// C++/WinRT v2.0.190620.2 // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #ifndef WINRT_Windows_Media_Core_2_H #define WINRT_Windows_Media_Core_2_H #include "winrt/impl/Windows.ApplicationModel.AppService.2.h" #include "winrt/impl/Windows.Foundation.2.h" #include "winrt/impl/Windows.Foundation.Collections.2.h" #include "winrt/impl/Windows.Graphics.DirectX.Direct3D11.2.h" #include "winrt/impl/Windows.Graphics.Imaging.2.h" #include "winrt/impl/Windows.Media.2.h" #include "winrt/impl/Windows.Media.Capture.Frames.2.h" #include "winrt/impl/Windows.Media.Effects.2.h" #include "winrt/impl/Windows.Media.MediaProperties.2.h" #include "winrt/impl/Windows.Media.Playback.2.h" #include "winrt/impl/Windows.Media.Streaming.Adaptive.2.h" #include "winrt/impl/Windows.Networking.BackgroundTransfer.2.h" #include "winrt/impl/Windows.Storage.2.h" #include "winrt/impl/Windows.Storage.Streams.2.h" #include "winrt/impl/Windows.Media.Core.1.h" namespace winrt::Windows::Media::Core { struct MseTimeRange { Windows::Foundation::TimeSpan Start; Windows::Foundation::TimeSpan End; }; inline bool operator==(MseTimeRange const& left, MseTimeRange const& right) noexcept { return left.Start == right.Start && left.End == right.End; } inline bool operator!=(MseTimeRange const& left, MseTimeRange const& right) noexcept { return !(left == right); } struct TimedTextDouble { double Value; Windows::Media::Core::TimedTextUnit Unit; }; inline bool operator==(TimedTextDouble const& left, TimedTextDouble const& right) noexcept { return left.Value == right.Value && left.Unit == right.Unit; } inline bool operator!=(TimedTextDouble const& left, TimedTextDouble const& right) noexcept { return !(left == right); } struct TimedTextPadding { double Before; double After; double Start; double End; Windows::Media::Core::TimedTextUnit Unit; }; inline bool operator==(TimedTextPadding const& left, TimedTextPadding const& right) noexcept { return left.Before == right.Before && left.After == right.After && left.Start == right.Start && left.End == right.End && left.Unit == right.Unit; } inline bool operator!=(TimedTextPadding const& left, TimedTextPadding const& right) noexcept { return !(left == right); } struct TimedTextPoint { double X; double Y; Windows::Media::Core::TimedTextUnit Unit; }; inline bool operator==(TimedTextPoint const& left, TimedTextPoint const& right) noexcept { return left.X == right.X && left.Y == right.Y && left.Unit == right.Unit; } inline bool operator!=(TimedTextPoint const& left, TimedTextPoint const& right) noexcept { return !(left == right); } struct TimedTextSize { double Height; double Width; Windows::Media::Core::TimedTextUnit Unit; }; inline bool operator==(TimedTextSize const& left, TimedTextSize const& right) noexcept { return left.Height == right.Height && left.Width == right.Width && left.Unit == right.Unit; } inline bool operator!=(TimedTextSize const& left, TimedTextSize const& right) noexcept { return !(left == right); } struct __declspec(empty_bases) AudioStreamDescriptor : Windows::Media::Core::IAudioStreamDescriptor, impl::require<AudioStreamDescriptor, Windows::Media::Core::IAudioStreamDescriptor2, Windows::Media::Core::IMediaStreamDescriptor2, Windows::Media::Core::IAudioStreamDescriptor3> { AudioStreamDescriptor(std::nullptr_t) noexcept {} AudioStreamDescriptor(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Media::Core::IAudioStreamDescriptor(ptr, take_ownership_from_abi) {} AudioStreamDescriptor(Windows::Media::MediaProperties::AudioEncodingProperties const& encodingProperties); }; struct __declspec(empty_bases) AudioTrack : Windows::Media::Core::IMediaTrack, impl::require<AudioTrack, Windows::Media::Core::IAudioTrack> { AudioTrack(std::nullptr_t) noexcept {} AudioTrack(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Media::Core::IMediaTrack(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) AudioTrackOpenFailedEventArgs : Windows::Media::Core::IAudioTrackOpenFailedEventArgs { AudioTrackOpenFailedEventArgs(std::nullptr_t) noexcept {} AudioTrackOpenFailedEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Media::Core::IAudioTrackOpenFailedEventArgs(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) AudioTrackSupportInfo : Windows::Media::Core::IAudioTrackSupportInfo { AudioTrackSupportInfo(std::nullptr_t) noexcept {} AudioTrackSupportInfo(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Media::Core::IAudioTrackSupportInfo(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) ChapterCue : Windows::Media::Core::IChapterCue { ChapterCue(std::nullptr_t) noexcept {} ChapterCue(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Media::Core::IChapterCue(ptr, take_ownership_from_abi) {} ChapterCue(); }; struct __declspec(empty_bases) CodecInfo : Windows::Media::Core::ICodecInfo { CodecInfo(std::nullptr_t) noexcept {} CodecInfo(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Media::Core::ICodecInfo(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) CodecQuery : Windows::Media::Core::ICodecQuery { CodecQuery(std::nullptr_t) noexcept {} CodecQuery(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Media::Core::ICodecQuery(ptr, take_ownership_from_abi) {} CodecQuery(); }; struct CodecSubtypes { CodecSubtypes() = delete; [[nodiscard]] static auto VideoFormatDV25(); [[nodiscard]] static auto VideoFormatDV50(); [[nodiscard]] static auto VideoFormatDvc(); [[nodiscard]] static auto VideoFormatDvh1(); [[nodiscard]] static auto VideoFormatDvhD(); [[nodiscard]] static auto VideoFormatDvsd(); [[nodiscard]] static auto VideoFormatDvsl(); [[nodiscard]] static auto VideoFormatH263(); [[nodiscard]] static auto VideoFormatH264(); [[nodiscard]] static auto VideoFormatH265(); [[nodiscard]] static auto VideoFormatH264ES(); [[nodiscard]] static auto VideoFormatHevc(); [[nodiscard]] static auto VideoFormatHevcES(); [[nodiscard]] static auto VideoFormatM4S2(); [[nodiscard]] static auto VideoFormatMjpg(); [[nodiscard]] static auto VideoFormatMP43(); [[nodiscard]] static auto VideoFormatMP4S(); [[nodiscard]] static auto VideoFormatMP4V(); [[nodiscard]] static auto VideoFormatMpeg2(); [[nodiscard]] static auto VideoFormatVP80(); [[nodiscard]] static auto VideoFormatVP90(); [[nodiscard]] static auto VideoFormatMpg1(); [[nodiscard]] static auto VideoFormatMss1(); [[nodiscard]] static auto VideoFormatMss2(); [[nodiscard]] static auto VideoFormatWmv1(); [[nodiscard]] static auto VideoFormatWmv2(); [[nodiscard]] static auto VideoFormatWmv3(); [[nodiscard]] static auto VideoFormatWvc1(); [[nodiscard]] static auto VideoFormat420O(); [[nodiscard]] static auto AudioFormatAac(); [[nodiscard]] static auto AudioFormatAdts(); [[nodiscard]] static auto AudioFormatAlac(); [[nodiscard]] static auto AudioFormatAmrNB(); [[nodiscard]] static auto AudioFormatAmrWB(); [[nodiscard]] static auto AudioFormatAmrWP(); [[nodiscard]] static auto AudioFormatDolbyAC3(); [[nodiscard]] static auto AudioFormatDolbyAC3Spdif(); [[nodiscard]] static auto AudioFormatDolbyDDPlus(); [[nodiscard]] static auto AudioFormatDrm(); [[nodiscard]] static auto AudioFormatDts(); [[nodiscard]] static auto AudioFormatFlac(); [[nodiscard]] static auto AudioFormatFloat(); [[nodiscard]] static auto AudioFormatMP3(); [[nodiscard]] static auto AudioFormatMPeg(); [[nodiscard]] static auto AudioFormatMsp1(); [[nodiscard]] static auto AudioFormatOpus(); [[nodiscard]] static auto AudioFormatPcm(); [[nodiscard]] static auto AudioFormatWmaSpdif(); [[nodiscard]] static auto AudioFormatWMAudioLossless(); [[nodiscard]] static auto AudioFormatWMAudioV8(); [[nodiscard]] static auto AudioFormatWMAudioV9(); }; struct __declspec(empty_bases) DataCue : Windows::Media::Core::IDataCue, impl::require<DataCue, Windows::Media::Core::IDataCue2> { DataCue(std::nullptr_t) noexcept {} DataCue(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Media::Core::IDataCue(ptr, take_ownership_from_abi) {} DataCue(); }; struct __declspec(empty_bases) FaceDetectedEventArgs : Windows::Media::Core::IFaceDetectedEventArgs { FaceDetectedEventArgs(std::nullptr_t) noexcept {} FaceDetectedEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Media::Core::IFaceDetectedEventArgs(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) FaceDetectionEffect : Windows::Media::Core::IFaceDetectionEffect { FaceDetectionEffect(std::nullptr_t) noexcept {} FaceDetectionEffect(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Media::Core::IFaceDetectionEffect(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) FaceDetectionEffectDefinition : Windows::Media::Effects::IVideoEffectDefinition, impl::require<FaceDetectionEffectDefinition, Windows::Media::Core::IFaceDetectionEffectDefinition> { FaceDetectionEffectDefinition(std::nullptr_t) noexcept {} FaceDetectionEffectDefinition(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Media::Effects::IVideoEffectDefinition(ptr, take_ownership_from_abi) {} FaceDetectionEffectDefinition(); }; struct __declspec(empty_bases) FaceDetectionEffectFrame : Windows::Media::Core::IFaceDetectionEffectFrame { FaceDetectionEffectFrame(std::nullptr_t) noexcept {} FaceDetectionEffectFrame(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Media::Core::IFaceDetectionEffectFrame(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) HighDynamicRangeControl : Windows::Media::Core::IHighDynamicRangeControl { HighDynamicRangeControl(std::nullptr_t) noexcept {} HighDynamicRangeControl(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Media::Core::IHighDynamicRangeControl(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) HighDynamicRangeOutput : Windows::Media::Core::IHighDynamicRangeOutput { HighDynamicRangeOutput(std::nullptr_t) noexcept {} HighDynamicRangeOutput(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Media::Core::IHighDynamicRangeOutput(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) ImageCue : Windows::Media::Core::IImageCue { ImageCue(std::nullptr_t) noexcept {} ImageCue(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Media::Core::IImageCue(ptr, take_ownership_from_abi) {} ImageCue(); }; struct __declspec(empty_bases) InitializeMediaStreamSourceRequestedEventArgs : Windows::Media::Core::IInitializeMediaStreamSourceRequestedEventArgs { InitializeMediaStreamSourceRequestedEventArgs(std::nullptr_t) noexcept {} InitializeMediaStreamSourceRequestedEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Media::Core::IInitializeMediaStreamSourceRequestedEventArgs(ptr, take_ownership_from_abi) {} }; struct LowLightFusion { LowLightFusion() = delete; [[nodiscard]] static auto SupportedBitmapPixelFormats(); [[nodiscard]] static auto MaxSupportedFrameCount(); static auto FuseAsync(param::async_iterable<Windows::Graphics::Imaging::SoftwareBitmap> const& frameSet); }; struct __declspec(empty_bases) LowLightFusionResult : Windows::Media::Core::ILowLightFusionResult, impl::require<LowLightFusionResult, Windows::Foundation::IClosable> { LowLightFusionResult(std::nullptr_t) noexcept {} LowLightFusionResult(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Media::Core::ILowLightFusionResult(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) MediaBinder : Windows::Media::Core::IMediaBinder { MediaBinder(std::nullptr_t) noexcept {} MediaBinder(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Media::Core::IMediaBinder(ptr, take_ownership_from_abi) {} MediaBinder(); }; struct __declspec(empty_bases) MediaBindingEventArgs : Windows::Media::Core::IMediaBindingEventArgs, impl::require<MediaBindingEventArgs, Windows::Media::Core::IMediaBindingEventArgs2, Windows::Media::Core::IMediaBindingEventArgs3> { MediaBindingEventArgs(std::nullptr_t) noexcept {} MediaBindingEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Media::Core::IMediaBindingEventArgs(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) MediaCueEventArgs : Windows::Media::Core::IMediaCueEventArgs { MediaCueEventArgs(std::nullptr_t) noexcept {} MediaCueEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Media::Core::IMediaCueEventArgs(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) MediaSource : Windows::Media::Core::IMediaSource2, impl::require<MediaSource, Windows::Media::Core::IMediaSource3, Windows::Media::Core::IMediaSource4, Windows::Media::Core::IMediaSource5> { MediaSource(std::nullptr_t) noexcept {} MediaSource(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Media::Core::IMediaSource2(ptr, take_ownership_from_abi) {} static auto CreateFromAdaptiveMediaSource(Windows::Media::Streaming::Adaptive::AdaptiveMediaSource const& mediaSource); static auto CreateFromMediaStreamSource(Windows::Media::Core::MediaStreamSource const& mediaSource); static auto CreateFromMseStreamSource(Windows::Media::Core::MseStreamSource const& mediaSource); static auto CreateFromIMediaSource(Windows::Media::Core::IMediaSource const& mediaSource); static auto CreateFromStorageFile(Windows::Storage::IStorageFile const& file); static auto CreateFromStream(Windows::Storage::Streams::IRandomAccessStream const& stream, param::hstring const& contentType); static auto CreateFromStreamReference(Windows::Storage::Streams::IRandomAccessStreamReference const& stream, param::hstring const& contentType); static auto CreateFromUri(Windows::Foundation::Uri const& uri); static auto CreateFromMediaBinder(Windows::Media::Core::MediaBinder const& binder); static auto CreateFromMediaFrameSource(Windows::Media::Capture::Frames::MediaFrameSource const& frameSource); static auto CreateFromDownloadOperation(Windows::Networking::BackgroundTransfer::DownloadOperation const& downloadOperation); }; struct __declspec(empty_bases) MediaSourceAppServiceConnection : Windows::Media::Core::IMediaSourceAppServiceConnection { MediaSourceAppServiceConnection(std::nullptr_t) noexcept {} MediaSourceAppServiceConnection(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Media::Core::IMediaSourceAppServiceConnection(ptr, take_ownership_from_abi) {} MediaSourceAppServiceConnection(Windows::ApplicationModel::AppService::AppServiceConnection const& appServiceConnection); }; struct __declspec(empty_bases) MediaSourceError : Windows::Media::Core::IMediaSourceError { MediaSourceError(std::nullptr_t) noexcept {} MediaSourceError(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Media::Core::IMediaSourceError(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) MediaSourceOpenOperationCompletedEventArgs : Windows::Media::Core::IMediaSourceOpenOperationCompletedEventArgs { MediaSourceOpenOperationCompletedEventArgs(std::nullptr_t) noexcept {} MediaSourceOpenOperationCompletedEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Media::Core::IMediaSourceOpenOperationCompletedEventArgs(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) MediaSourceStateChangedEventArgs : Windows::Media::Core::IMediaSourceStateChangedEventArgs { MediaSourceStateChangedEventArgs(std::nullptr_t) noexcept {} MediaSourceStateChangedEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Media::Core::IMediaSourceStateChangedEventArgs(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) MediaStreamSample : Windows::Media::Core::IMediaStreamSample, impl::require<MediaStreamSample, Windows::Media::Core::IMediaStreamSample2> { MediaStreamSample(std::nullptr_t) noexcept {} MediaStreamSample(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Media::Core::IMediaStreamSample(ptr, take_ownership_from_abi) {} static auto CreateFromBuffer(Windows::Storage::Streams::IBuffer const& buffer, Windows::Foundation::TimeSpan const& timestamp); static auto CreateFromStreamAsync(Windows::Storage::Streams::IInputStream const& stream, uint32_t count, Windows::Foundation::TimeSpan const& timestamp); static auto CreateFromDirect3D11Surface(Windows::Graphics::DirectX::Direct3D11::IDirect3DSurface const& surface, Windows::Foundation::TimeSpan const& timestamp); }; struct __declspec(empty_bases) MediaStreamSamplePropertySet : Windows::Foundation::Collections::IMap<winrt::guid, Windows::Foundation::IInspectable> { MediaStreamSamplePropertySet(std::nullptr_t) noexcept {} MediaStreamSamplePropertySet(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::Collections::IMap<winrt::guid, Windows::Foundation::IInspectable>(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) MediaStreamSampleProtectionProperties : Windows::Media::Core::IMediaStreamSampleProtectionProperties { MediaStreamSampleProtectionProperties(std::nullptr_t) noexcept {} MediaStreamSampleProtectionProperties(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Media::Core::IMediaStreamSampleProtectionProperties(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) MediaStreamSource : Windows::Media::Core::IMediaStreamSource, impl::require<MediaStreamSource, Windows::Media::Core::IMediaStreamSource2, Windows::Media::Core::IMediaStreamSource3, Windows::Media::Core::IMediaStreamSource4> { MediaStreamSource(std::nullptr_t) noexcept {} MediaStreamSource(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Media::Core::IMediaStreamSource(ptr, take_ownership_from_abi) {} MediaStreamSource(Windows::Media::Core::IMediaStreamDescriptor const& descriptor); MediaStreamSource(Windows::Media::Core::IMediaStreamDescriptor const& descriptor, Windows::Media::Core::IMediaStreamDescriptor const& descriptor2); }; struct __declspec(empty_bases) MediaStreamSourceClosedEventArgs : Windows::Media::Core::IMediaStreamSourceClosedEventArgs { MediaStreamSourceClosedEventArgs(std::nullptr_t) noexcept {} MediaStreamSourceClosedEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Media::Core::IMediaStreamSourceClosedEventArgs(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) MediaStreamSourceClosedRequest : Windows::Media::Core::IMediaStreamSourceClosedRequest { MediaStreamSourceClosedRequest(std::nullptr_t) noexcept {} MediaStreamSourceClosedRequest(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Media::Core::IMediaStreamSourceClosedRequest(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) MediaStreamSourceSampleRenderedEventArgs : Windows::Media::Core::IMediaStreamSourceSampleRenderedEventArgs { MediaStreamSourceSampleRenderedEventArgs(std::nullptr_t) noexcept {} MediaStreamSourceSampleRenderedEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Media::Core::IMediaStreamSourceSampleRenderedEventArgs(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) MediaStreamSourceSampleRequest : Windows::Media::Core::IMediaStreamSourceSampleRequest { MediaStreamSourceSampleRequest(std::nullptr_t) noexcept {} MediaStreamSourceSampleRequest(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Media::Core::IMediaStreamSourceSampleRequest(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) MediaStreamSourceSampleRequestDeferral : Windows::Media::Core::IMediaStreamSourceSampleRequestDeferral { MediaStreamSourceSampleRequestDeferral(std::nullptr_t) noexcept {} MediaStreamSourceSampleRequestDeferral(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Media::Core::IMediaStreamSourceSampleRequestDeferral(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) MediaStreamSourceSampleRequestedEventArgs : Windows::Media::Core::IMediaStreamSourceSampleRequestedEventArgs { MediaStreamSourceSampleRequestedEventArgs(std::nullptr_t) noexcept {} MediaStreamSourceSampleRequestedEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Media::Core::IMediaStreamSourceSampleRequestedEventArgs(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) MediaStreamSourceStartingEventArgs : Windows::Media::Core::IMediaStreamSourceStartingEventArgs { MediaStreamSourceStartingEventArgs(std::nullptr_t) noexcept {} MediaStreamSourceStartingEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Media::Core::IMediaStreamSourceStartingEventArgs(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) MediaStreamSourceStartingRequest : Windows::Media::Core::IMediaStreamSourceStartingRequest { MediaStreamSourceStartingRequest(std::nullptr_t) noexcept {} MediaStreamSourceStartingRequest(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Media::Core::IMediaStreamSourceStartingRequest(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) MediaStreamSourceStartingRequestDeferral : Windows::Media::Core::IMediaStreamSourceStartingRequestDeferral { MediaStreamSourceStartingRequestDeferral(std::nullptr_t) noexcept {} MediaStreamSourceStartingRequestDeferral(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Media::Core::IMediaStreamSourceStartingRequestDeferral(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) MediaStreamSourceSwitchStreamsRequest : Windows::Media::Core::IMediaStreamSourceSwitchStreamsRequest { MediaStreamSourceSwitchStreamsRequest(std::nullptr_t) noexcept {} MediaStreamSourceSwitchStreamsRequest(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Media::Core::IMediaStreamSourceSwitchStreamsRequest(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) MediaStreamSourceSwitchStreamsRequestDeferral : Windows::Media::Core::IMediaStreamSourceSwitchStreamsRequestDeferral { MediaStreamSourceSwitchStreamsRequestDeferral(std::nullptr_t) noexcept {} MediaStreamSourceSwitchStreamsRequestDeferral(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Media::Core::IMediaStreamSourceSwitchStreamsRequestDeferral(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) MediaStreamSourceSwitchStreamsRequestedEventArgs : Windows::Media::Core::IMediaStreamSourceSwitchStreamsRequestedEventArgs { MediaStreamSourceSwitchStreamsRequestedEventArgs(std::nullptr_t) noexcept {} MediaStreamSourceSwitchStreamsRequestedEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Media::Core::IMediaStreamSourceSwitchStreamsRequestedEventArgs(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) MseSourceBuffer : Windows::Media::Core::IMseSourceBuffer { MseSourceBuffer(std::nullptr_t) noexcept {} MseSourceBuffer(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Media::Core::IMseSourceBuffer(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) MseSourceBufferList : Windows::Media::Core::IMseSourceBufferList { MseSourceBufferList(std::nullptr_t) noexcept {} MseSourceBufferList(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Media::Core::IMseSourceBufferList(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) MseStreamSource : Windows::Media::Core::IMseStreamSource, impl::require<MseStreamSource, Windows::Media::Core::IMseStreamSource2> { MseStreamSource(std::nullptr_t) noexcept {} MseStreamSource(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Media::Core::IMseStreamSource(ptr, take_ownership_from_abi) {} MseStreamSource(); static auto IsContentTypeSupported(param::hstring const& contentType); }; struct __declspec(empty_bases) SceneAnalysisEffect : Windows::Media::Core::ISceneAnalysisEffect { SceneAnalysisEffect(std::nullptr_t) noexcept {} SceneAnalysisEffect(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Media::Core::ISceneAnalysisEffect(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) SceneAnalysisEffectDefinition : Windows::Media::Effects::IVideoEffectDefinition { SceneAnalysisEffectDefinition(std::nullptr_t) noexcept {} SceneAnalysisEffectDefinition(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Media::Effects::IVideoEffectDefinition(ptr, take_ownership_from_abi) {} SceneAnalysisEffectDefinition(); }; struct __declspec(empty_bases) SceneAnalysisEffectFrame : Windows::Media::Core::ISceneAnalysisEffectFrame, impl::require<SceneAnalysisEffectFrame, Windows::Media::Core::ISceneAnalysisEffectFrame2> { SceneAnalysisEffectFrame(std::nullptr_t) noexcept {} SceneAnalysisEffectFrame(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Media::Core::ISceneAnalysisEffectFrame(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) SceneAnalyzedEventArgs : Windows::Media::Core::ISceneAnalyzedEventArgs { SceneAnalyzedEventArgs(std::nullptr_t) noexcept {} SceneAnalyzedEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Media::Core::ISceneAnalyzedEventArgs(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) SpeechCue : Windows::Media::Core::ISpeechCue { SpeechCue(std::nullptr_t) noexcept {} SpeechCue(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Media::Core::ISpeechCue(ptr, take_ownership_from_abi) {} SpeechCue(); }; struct __declspec(empty_bases) TimedMetadataStreamDescriptor : Windows::Media::Core::IMediaStreamDescriptor, impl::require<TimedMetadataStreamDescriptor, Windows::Media::Core::ITimedMetadataStreamDescriptor, Windows::Media::Core::IMediaStreamDescriptor2> { TimedMetadataStreamDescriptor(std::nullptr_t) noexcept {} TimedMetadataStreamDescriptor(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Media::Core::IMediaStreamDescriptor(ptr, take_ownership_from_abi) {} TimedMetadataStreamDescriptor(Windows::Media::MediaProperties::TimedMetadataEncodingProperties const& encodingProperties); }; struct __declspec(empty_bases) TimedMetadataTrack : Windows::Media::Core::ITimedMetadataTrack, impl::require<TimedMetadataTrack, Windows::Media::Core::ITimedMetadataTrack2> { TimedMetadataTrack(std::nullptr_t) noexcept {} TimedMetadataTrack(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Media::Core::ITimedMetadataTrack(ptr, take_ownership_from_abi) {} TimedMetadataTrack(param::hstring const& id, param::hstring const& language, Windows::Media::Core::TimedMetadataKind const& kind); }; struct __declspec(empty_bases) TimedMetadataTrackError : Windows::Media::Core::ITimedMetadataTrackError { TimedMetadataTrackError(std::nullptr_t) noexcept {} TimedMetadataTrackError(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Media::Core::ITimedMetadataTrackError(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) TimedMetadataTrackFailedEventArgs : Windows::Media::Core::ITimedMetadataTrackFailedEventArgs { TimedMetadataTrackFailedEventArgs(std::nullptr_t) noexcept {} TimedMetadataTrackFailedEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Media::Core::ITimedMetadataTrackFailedEventArgs(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) TimedTextCue : Windows::Media::Core::ITimedTextCue { TimedTextCue(std::nullptr_t) noexcept {} TimedTextCue(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Media::Core::ITimedTextCue(ptr, take_ownership_from_abi) {} TimedTextCue(); }; struct __declspec(empty_bases) TimedTextLine : Windows::Media::Core::ITimedTextLine { TimedTextLine(std::nullptr_t) noexcept {} TimedTextLine(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Media::Core::ITimedTextLine(ptr, take_ownership_from_abi) {} TimedTextLine(); }; struct __declspec(empty_bases) TimedTextRegion : Windows::Media::Core::ITimedTextRegion { TimedTextRegion(std::nullptr_t) noexcept {} TimedTextRegion(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Media::Core::ITimedTextRegion(ptr, take_ownership_from_abi) {} TimedTextRegion(); }; struct __declspec(empty_bases) TimedTextSource : Windows::Media::Core::ITimedTextSource { TimedTextSource(std::nullptr_t) noexcept {} TimedTextSource(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Media::Core::ITimedTextSource(ptr, take_ownership_from_abi) {} static auto CreateFromStream(Windows::Storage::Streams::IRandomAccessStream const& stream); static auto CreateFromUri(Windows::Foundation::Uri const& uri); static auto CreateFromStream(Windows::Storage::Streams::IRandomAccessStream const& stream, param::hstring const& defaultLanguage); static auto CreateFromUri(Windows::Foundation::Uri const& uri, param::hstring const& defaultLanguage); static auto CreateFromStreamWithIndex(Windows::Storage::Streams::IRandomAccessStream const& stream, Windows::Storage::Streams::IRandomAccessStream const& indexStream); static auto CreateFromUriWithIndex(Windows::Foundation::Uri const& uri, Windows::Foundation::Uri const& indexUri); static auto CreateFromStreamWithIndex(Windows::Storage::Streams::IRandomAccessStream const& stream, Windows::Storage::Streams::IRandomAccessStream const& indexStream, param::hstring const& defaultLanguage); static auto CreateFromUriWithIndex(Windows::Foundation::Uri const& uri, Windows::Foundation::Uri const& indexUri, param::hstring const& defaultLanguage); }; struct __declspec(empty_bases) TimedTextSourceResolveResultEventArgs : Windows::Media::Core::ITimedTextSourceResolveResultEventArgs { TimedTextSourceResolveResultEventArgs(std::nullptr_t) noexcept {} TimedTextSourceResolveResultEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Media::Core::ITimedTextSourceResolveResultEventArgs(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) TimedTextStyle : Windows::Media::Core::ITimedTextStyle, impl::require<TimedTextStyle, Windows::Media::Core::ITimedTextStyle2> { TimedTextStyle(std::nullptr_t) noexcept {} TimedTextStyle(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Media::Core::ITimedTextStyle(ptr, take_ownership_from_abi) {} TimedTextStyle(); }; struct __declspec(empty_bases) TimedTextSubformat : Windows::Media::Core::ITimedTextSubformat { TimedTextSubformat(std::nullptr_t) noexcept {} TimedTextSubformat(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Media::Core::ITimedTextSubformat(ptr, take_ownership_from_abi) {} TimedTextSubformat(); }; struct __declspec(empty_bases) VideoStabilizationEffect : Windows::Media::Core::IVideoStabilizationEffect { VideoStabilizationEffect(std::nullptr_t) noexcept {} VideoStabilizationEffect(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Media::Core::IVideoStabilizationEffect(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) VideoStabilizationEffectDefinition : Windows::Media::Effects::IVideoEffectDefinition { VideoStabilizationEffectDefinition(std::nullptr_t) noexcept {} VideoStabilizationEffectDefinition(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Media::Effects::IVideoEffectDefinition(ptr, take_ownership_from_abi) {} VideoStabilizationEffectDefinition(); }; struct __declspec(empty_bases) VideoStabilizationEffectEnabledChangedEventArgs : Windows::Media::Core::IVideoStabilizationEffectEnabledChangedEventArgs { VideoStabilizationEffectEnabledChangedEventArgs(std::nullptr_t) noexcept {} VideoStabilizationEffectEnabledChangedEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Media::Core::IVideoStabilizationEffectEnabledChangedEventArgs(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) VideoStreamDescriptor : Windows::Media::Core::IVideoStreamDescriptor, impl::require<VideoStreamDescriptor, Windows::Media::Core::IMediaStreamDescriptor2, Windows::Media::Core::IVideoStreamDescriptor2> { VideoStreamDescriptor(std::nullptr_t) noexcept {} VideoStreamDescriptor(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Media::Core::IVideoStreamDescriptor(ptr, take_ownership_from_abi) {} VideoStreamDescriptor(Windows::Media::MediaProperties::VideoEncodingProperties const& encodingProperties); }; struct __declspec(empty_bases) VideoTrack : Windows::Media::Core::IMediaTrack, impl::require<VideoTrack, Windows::Media::Core::IVideoTrack> { VideoTrack(std::nullptr_t) noexcept {} VideoTrack(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Media::Core::IMediaTrack(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) VideoTrackOpenFailedEventArgs : Windows::Media::Core::IVideoTrackOpenFailedEventArgs { VideoTrackOpenFailedEventArgs(std::nullptr_t) noexcept {} VideoTrackOpenFailedEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Media::Core::IVideoTrackOpenFailedEventArgs(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) VideoTrackSupportInfo : Windows::Media::Core::IVideoTrackSupportInfo { VideoTrackSupportInfo(std::nullptr_t) noexcept {} VideoTrackSupportInfo(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Media::Core::IVideoTrackSupportInfo(ptr, take_ownership_from_abi) {} }; } #endif
0.976563
1
sapp/shadows-sapp.c
fabiopolimeni/sokol-samples
0
1356
//------------------------------------------------------------------------------ // shadows-sapp.c // Render to an offscreen rendertarget texture, and use this texture // for rendering shadows to the screen. //------------------------------------------------------------------------------ #include "sokol_app.h" #include "sokol_gfx.h" #include "sokol_glue.h" #define HANDMADE_MATH_IMPLEMENTATION #define HANDMADE_MATH_NO_SSE #include "HandmadeMath.h" #include "dbgui/dbgui.h" #include "shadows-sapp.glsl.h" #define SCREEN_SAMPLE_COUNT (4) static struct { struct { sg_pass_action pass_action; sg_pass pass; sg_pipeline pip; sg_bindings bind; } shadows; struct { sg_pass_action pass_action; sg_pipeline pip; sg_bindings bind; } deflt; float ry; } state; void init(void) { sg_setup(&(sg_desc){ .context = sapp_sgcontext() }); __dbgui_setup(sapp_sample_count()); /* default pass action: clear to blue-ish */ state.deflt.pass_action = (sg_pass_action) { .colors[0] = { .action = SG_ACTION_CLEAR, .value = { 0.0f, 0.25f, 1.0f, 1.0f } } }; /* shadow pass action: clear to white */ state.shadows.pass_action = (sg_pass_action) { .colors[0] = { .action = SG_ACTION_CLEAR, .value = { 1.0f, 1.0f, 1.0f, 1.0f } } }; /* a render pass with one color- and one depth-attachment image */ sg_image_desc img_desc = { .render_target = true, .width = 2048, .height = 2048, .pixel_format = SG_PIXELFORMAT_RGBA8, .min_filter = SG_FILTER_LINEAR, .mag_filter = SG_FILTER_LINEAR, .sample_count = 1, .label = "shadow-map-color-image" }; sg_image color_img = sg_make_image(&img_desc); img_desc.pixel_format = SG_PIXELFORMAT_DEPTH; img_desc.label = "shadow-map-depth-image"; sg_image depth_img = sg_make_image(&img_desc); state.shadows.pass = sg_make_pass(&(sg_pass_desc){ .color_attachments[0].image = color_img, .depth_stencil_attachment.image = depth_img, .label = "shadow-map-pass" }); /* cube vertex buffer with positions & normals */ float vertices[] = { /* pos normals */ -1.0f, -1.0f, -1.0f, 0.0f, 0.0f, -1.0f, //CUBE BACK FACE 1.0f, -1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f, -1.0f, 0.0f, 0.0f, -1.0f, -1.0f, 1.0f, -1.0f, 0.0f, 0.0f, -1.0f, -1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, //CUBE FRONT FACE 1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, -1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 0.0f, 0.0f, //CUBE LEFT FACE -1.0f, 1.0f, -1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f, -1.0f, 0.0f, 0.0f, -1.0f, -1.0f, 1.0f, -1.0f, 0.0f, 0.0f, 1.0f, -1.0f, -1.0f, 1.0f, 0.0f, 0.0f, //CUBE RIGHT FACE 1.0f, 1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, -1.0f, 1.0f, 1.0f, 0.0f, 0.0f, -1.0f, -1.0f, -1.0f, 0.0f, -1.0f, 0.0f, //CUBE BOTTOM FACE -1.0f, -1.0f, 1.0f, 0.0f, -1.0f, 0.0f, 1.0f, -1.0f, 1.0f, 0.0f, -1.0f, 0.0f, 1.0f, -1.0f, -1.0f, 0.0f, -1.0f, 0.0f, -1.0f, 1.0f, -1.0f, 0.0f, 1.0f, 0.0f, //CUBE TOP FACE -1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, -1.0f, 0.0f, 1.0f, 0.0f, -1.0f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, //PLANE GEOMETRY -1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, }; sg_buffer vbuf = sg_make_buffer(&(sg_buffer_desc){ .data = SG_RANGE(vertices), .label = "cube-vertices" }); /* an index buffer for the cube */ uint16_t indices[] = { 0, 1, 2, 0, 2, 3, 6, 5, 4, 7, 6, 4, 8, 9, 10, 8, 10, 11, 14, 13, 12, 15, 14, 12, 16, 17, 18, 16, 18, 19, 22, 21, 20, 23, 22, 20, 26, 25, 24, 27, 26, 24 }; sg_buffer ibuf = sg_make_buffer(&(sg_buffer_desc){ .type = SG_BUFFERTYPE_INDEXBUFFER, .data = SG_RANGE(indices), .label = "cube-indices" }); /* pipeline-state-object for shadows-rendered cube, don't need texture coord here */ state.shadows.pip = sg_make_pipeline(&(sg_pipeline_desc){ .layout = { /* need to provide stride, because the buffer's normal vector is skipped */ .buffers[0].stride = 6 * sizeof(float), /* but don't need to provide attr offsets, because pos and normal are continuous */ .attrs = { [ATTR_shadowVS_position].format = SG_VERTEXFORMAT_FLOAT3 } }, .shader = sg_make_shader(shadow_shader_desc(sg_query_backend())), .index_type = SG_INDEXTYPE_UINT16, /* Cull front faces in the shadow map pass */ .cull_mode = SG_CULLMODE_FRONT, .sample_count = 1, .depth = { .pixel_format = SG_PIXELFORMAT_DEPTH, .compare = SG_COMPAREFUNC_LESS_EQUAL, .write_enabled = true, }, .colors[0].pixel_format = SG_PIXELFORMAT_RGBA8, .label = "shadow-map-pipeline" }); /* and another pipeline-state-object for the default pass */ state.deflt.pip = sg_make_pipeline(&(sg_pipeline_desc){ .layout = { /* don't need to provide buffer stride or attr offsets, no gaps here */ .attrs = { [ATTR_colorVS_position].format = SG_VERTEXFORMAT_FLOAT3, [ATTR_colorVS_normal].format = SG_VERTEXFORMAT_FLOAT3 } }, .shader = sg_make_shader(color_shader_desc(sg_query_backend())), .index_type = SG_INDEXTYPE_UINT16, /* Cull back faces when rendering to the screen */ .cull_mode = SG_CULLMODE_BACK, .depth = { .compare = SG_COMPAREFUNC_LESS_EQUAL, .write_enabled = true }, .label = "default-pipeline" }); /* the resource bindings for rendering the cube into the shadow map render target */ state.shadows.bind = (sg_bindings){ .vertex_buffers[0] = vbuf, .index_buffer = ibuf }; /* resource bindings to render the cube, using the shadow map render target as texture */ state.deflt.bind = (sg_bindings){ .vertex_buffers[0] = vbuf, .index_buffer = ibuf, .fs_images[SLOT_shadowMap] = color_img }; state.ry = 0.0f; } void frame(void) { const float t = (float)(sapp_frame_duration() * 60.0); state.ry += 0.2f * t; /* Calculate matrices for shadow pass */ const hmm_mat4 rym = HMM_Rotate(state.ry, HMM_Vec3(0.0f,1.0f,0.0f)); const hmm_vec4 light_dir = HMM_MultiplyMat4ByVec4(rym, HMM_Vec4(50.0f,50.0f,-50.0f,0.0f)); const hmm_mat4 light_view = HMM_LookAt(light_dir.XYZ, HMM_Vec3(0.0f, 0.0f, 0.0f), HMM_Vec3(0.0f, 1.0f, 0.0f)); /* Configure a bias matrix for converting view-space coordinates into uv coordinates */ hmm_mat4 light_proj = { { { 0.5f, 0.0f, 0.0f, 0 }, { 0.0f, 0.5f, 0.0f, 0 }, { 0.0f, 0.0f, 0.5f, 0 }, { 0.5f, 0.5f, 0.5f, 1 } } }; light_proj = HMM_MultiplyMat4(light_proj, HMM_Orthographic(-4.0f, 4.0f, -4.0f, 4.0f, 0, 200.0f)); const hmm_mat4 light_view_proj = HMM_MultiplyMat4(light_proj, light_view); /* Calculate matrices for camera pass */ const hmm_mat4 proj = HMM_Perspective(60.0f, sapp_widthf()/sapp_heightf(), 0.01f, 100.0f); const hmm_mat4 view = HMM_LookAt(HMM_Vec3(5.0f, 5.0f, 5.0f), HMM_Vec3(0.0f, 0.0f, 0.0f), HMM_Vec3(0.0f, 1.0f, 0.0f)); const hmm_mat4 view_proj = HMM_MultiplyMat4(proj, view); /* Calculate transform matrices for plane and cube */ const hmm_mat4 scale = HMM_Scale(HMM_Vec3(5,0,5)); const hmm_mat4 translate = HMM_Translate(HMM_Vec3(0,1.5f,0)); /* Initialise fragment uniforms for light shader */ const fs_light_params_t fs_light_params = { .lightDir = HMM_NormalizeVec3(light_dir.XYZ), .shadowMapSize = HMM_Vec2(2048,2048), .eyePos = HMM_Vec3(5.0f,5.0f,5.0f) }; /* the shadow map pass, render the vertices into the depth image */ sg_begin_pass(state.shadows.pass, &state.shadows.pass_action); sg_apply_pipeline(state.shadows.pip); sg_apply_bindings(&state.shadows.bind); { /* Render the cube into the shadow map */ const vs_shadow_params_t vs_shadow_params = { .mvp = HMM_MultiplyMat4(light_view_proj,translate) }; sg_apply_uniforms(SG_SHADERSTAGE_VS, SLOT_vs_shadow_params, &SG_RANGE(vs_shadow_params)); sg_draw(0, 36, 1); } sg_end_pass(); /* and the display-pass, rendering the scene, using the previously rendered shadow map as a texture */ sg_begin_default_pass(&state.deflt.pass_action, sapp_width(), sapp_height()); sg_apply_pipeline(state.deflt.pip); sg_apply_bindings(&state.deflt.bind); sg_apply_uniforms(SG_SHADERSTAGE_FS, SLOT_fs_light_params, &SG_RANGE(fs_light_params)); { /* Render the plane in the light pass */ const vs_light_params_t vs_light_params = { .mvp = HMM_MultiplyMat4(view_proj,scale), .lightMVP = HMM_MultiplyMat4(light_view_proj,scale), .model = HMM_Mat4d(1.0f), .diffColor = HMM_Vec3(0.5f,0.5f,0.5f) }; sg_apply_uniforms(SG_SHADERSTAGE_VS, SLOT_vs_light_params, &SG_RANGE(vs_light_params)); sg_draw(36, 6, 1); } { /* Render the cube in the light pass */ const vs_light_params_t vs_light_params = { .lightMVP = HMM_MultiplyMat4(light_view_proj,translate), .model = translate, .mvp = HMM_MultiplyMat4(view_proj,translate), .diffColor = HMM_Vec3(1.0f,1.0f,1.0f) }; sg_apply_uniforms(SG_SHADERSTAGE_VS, SLOT_vs_light_params, &SG_RANGE(vs_light_params)); sg_draw(0, 36, 1); } __dbgui_draw(); sg_end_pass(); sg_commit(); } void cleanup(void) { __dbgui_shutdown(); sg_shutdown(); } sapp_desc sokol_main(int argc, char* argv[]) { (void)argc; (void)argv; return (sapp_desc){ .init_cb = init, .frame_cb = frame, .cleanup_cb = cleanup, .event_cb = __dbgui_event, .width = 800, .height = 600, .sample_count = SCREEN_SAMPLE_COUNT, .window_title = "Shadow Rendering (sokol-app)", .icon.sokol_default = true, }; }
1.53125
2
coleminik45/keymaps/default/keymap.c
soahyle/qmk-related
0
1364
#include QMK_KEYBOARD_H /* * ┌────┬────┬────┬────┬────┬────┬────┬────┬────┬────┬────┬────┬────┐ * │ │ │ │ │ │ │ │ │ │ │ │ │ │ * ├────┴┬───┴┬───┴┬───┴┬───┴┬───┴┬───┴┬───┴┬───┴┬───┴┬───┴┬───┴────┤ * │ │ │ │ │ │ │ │ │ │ │ │ │ * ├─────┴─┬──┴─┬──┴─┬──┴─┬──┴─┬──┴─┬──┴─┬──┴─┬──┴─┬──┴─┬──┴─┬──────┤ * │ │ │ │ │ │ │ │ │ │ │ │ │ * ├────┬──┴──┬─┴──┬─┴────┴───┬┴────┴────┴───┬┴───┬┴───┬┴───┬┴──────┤ * │ │ │ │ │ │ │ │ │ │ * └────┴─────┴────┴──────────┴──────────────┴────┴────┴────┴───────┘ */ const uint16_t PROGMEM keymaps[][MATRIX_ROWS][MATRIX_COLS] = { /* * $Tab = LT(2, Tab) * $Enter = LT(2, Enter) * * ┌────┬────┬────┬────┬────┬────┬────┬────┬────┬────┬────┬────┬────┐ * │$TAB│ Q │ W │ E │ R │ T │ Y │ U │ I │ O │ P │DEL │ │ * ├────┴┬───┴┬───┴┬───┴┬───┴┬───┴┬───┴┬───┴┬───┴┬───┴┬───┴┬───┴────┤ * │BSpc │ A │ S │ D │ F │ G │ H │ J │ K │ L │ ; │$Enter │ * ├─────┴─┬──┴─┬──┴─┬──┴─┬──┴─┬──┴─┬──┴─┬──┴─┬──┴─┬──┴─┬──┴─┬──────┤ * │LShift │ Z │ X │ C │ V │ B │ N │ M │ , │ . │ / │RShift│ * ├────┬──┴──┬─┴──┬─┴────┴───┬┴────┴────┴───┬┴───┬┴───┬┴───┬┴──────┤ * │Ctrl│LGUI │Alt │ Space │ MO(1) │ 39 │ 3a │ 3b │ 3c │ * └────┴─────┴────┴──────────┴──────────────┴────┴────┴────┴───────┘ */ [0] = LAYOUT_45_SUCK( LT(4, KC_TAB), KC_Q, KC_W, KC_E, KC_R, KC_T, KC_Y, KC_U, KC_I, KC_O, KC_P, _______, TG(1), KC_BSPC, KC_A, KC_S, KC_D, KC_F, KC_G, KC_H, KC_J, KC_K, KC_L, KC_SCLN, LT(4, KC_ENT), KC_LSFT, KC_Z, KC_X, KC_C, KC_V, KC_B, KC_N, KC_M, KC_COMM, KC_DOT, KC_SLSH, KC_RSFT, KC_LCTL, KC_LGUI, KC_LALT, KC_SPC, MO(2), MO(3), _______, _______, _______), // GAME LAYOUT [1] = LAYOUT_45_SUCK( LT(4, KC_TAB), KC_Q, KC_W, KC_E, KC_R, KC_T, KC_Y, KC_U, KC_I, KC_O, KC_P, KC_BSPC, _______, KC_BSPC, KC_A, KC_S, KC_D, KC_F, KC_G, KC_H, KC_J, KC_K, KC_L, KC_SCLN, LT(4, KC_ENT), KC_LSFT, KC_Z, KC_X, KC_C, KC_V, KC_B, KC_N, KC_M, KC_COMM, KC_DOT, KC_SLSH, KC_RSFT, KC_LCTL, KC_LGUI, KC_LALT, KC_SPC, MO(5), MO(3), _______, _______, _______), [2] = LAYOUT_45_SUCK( KC_ESC, KC_LBRC, KC_RBRC, KC_QUOT, KC_DQUO, KC_PIPE, _______, KC_PGUP, KC_PGDN, KC_INS, KC_DEL, _______, _______, _______, KC_LPRN, KC_RPRN, KC_MINS, KC_EQL, KC_BSLS, KC_LEFT, KC_DOWN, KC_UP, KC_RGHT, KC_ESC, _______, _______, KC_LCBR, KC_RCBR, KC_UNDS, KC_PLUS, _______, _______, KC_HOME, KC_END, _______, TG(5), _______, _______, _______, _______, _______, _______, _______, _______, _______, _______), [3] = LAYOUT_45_SUCK( KC_ESC, KC_F1, KC_F2, KC_F3, KC_F4, CK_TOGG, CK_RST, KC_PERC, KC_CIRC, KC_AMPR, KC_ASTR, _______, _______, _______, KC_F5, KC_F6, KC_F7, KC_F8, _______, _______, KC_EXLM, KC_AT, KC_HASH, KC_DLR, _______, _______, KC_F9, KC_F10, KC_F11, KC_F12, CK_DOWN, KC_UP, KC_TILD, KC_GRV, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, RESET), [4] = LAYOUT_45_SUCK( _______, KC_PSCR, _______, _______, _______, _______, _______, KC_7, KC_8, KC_9, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, KC_4, KC_5, KC_6, KC_0, _______, _______, KC_MUTE, KC_VOLD, KC_VOLU, _______, _______, _______, KC_1, KC_2, KC_3, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______), // GAME LAYOUT [5] = LAYOUT_45_SUCK( KC_ESC, KC_1, KC_2, KC_3, KC_4, _______, _______, KC_PGUP, KC_PGDN, KC_INS, KC_DEL, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, KC_HOME, KC_END, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______), //[3] = LAYOUT_45_SUCK( // _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, // _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, // _______, KC_F9, KC_F10, KC_F11, KC_F12, CK_DOWN, KC_UP, _______, _______, _______, _______, _______, // _______, _______, _______, KC_BTN1, KC_BTN2, _______, _______, _______, _______) };
1.21875
1
include/llvm/ADT/Statistic.h
kpdev/llvm-tnt
1,073
1372
//===-- llvm/ADT/Statistic.h - Easy way to expose stats ---------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the 'Statistic' class, which is designed to be an easy way // to expose various metrics from passes. These statistics are printed at the // end of a run (from llvm_shutdown), when the -stats command line option is // passed on the command line. // // This is useful for reporting information like the number of instructions // simplified, optimized or removed by various transformations, like this: // // static Statistic NumInstsKilled("gcse", "Number of instructions killed"); // // Later, in the code: ++NumInstsKilled; // // NOTE: Statistics *must* be declared as global variables. // //===----------------------------------------------------------------------===// #ifndef LLVM_ADT_STATISTIC_H #define LLVM_ADT_STATISTIC_H #include "llvm/Support/Atomic.h" #include "llvm/Support/Compiler.h" #include <atomic> #include <memory> namespace llvm { class raw_ostream; class raw_fd_ostream; class Statistic { public: const char *DebugType; const char *Name; const char *Desc; std::atomic<unsigned> Value; bool Initialized; unsigned getValue() const { return Value.load(std::memory_order_relaxed); } const char *getDebugType() const { return DebugType; } const char *getName() const { return Name; } const char *getDesc() const { return Desc; } /// construct - This should only be called for non-global statistics. void construct(const char *debugtype, const char *name, const char *desc) { DebugType = debugtype; Name = name; Desc = desc; Value = 0; Initialized = false; } // Allow use of this class as the value itself. operator unsigned() const { return getValue(); } #if !defined(NDEBUG) || defined(LLVM_ENABLE_STATS) const Statistic &operator=(unsigned Val) { Value.store(Val, std::memory_order_relaxed); return init(); } const Statistic &operator++() { Value.fetch_add(1, std::memory_order_relaxed); return init(); } unsigned operator++(int) { init(); return Value.fetch_add(1, std::memory_order_relaxed); } const Statistic &operator--() { Value.fetch_sub(1, std::memory_order_relaxed); return init(); } unsigned operator--(int) { init(); return Value.fetch_sub(1, std::memory_order_relaxed); } const Statistic &operator+=(unsigned V) { if (V == 0) return *this; Value.fetch_add(V, std::memory_order_relaxed); return init(); } const Statistic &operator-=(unsigned V) { if (V == 0) return *this; Value.fetch_sub(V, std::memory_order_relaxed); return init(); } #else // Statistics are disabled in release builds. const Statistic &operator=(unsigned Val) { return *this; } const Statistic &operator++() { return *this; } unsigned operator++(int) { return 0; } const Statistic &operator--() { return *this; } unsigned operator--(int) { return 0; } const Statistic &operator+=(const unsigned &V) { return *this; } const Statistic &operator-=(const unsigned &V) { return *this; } #endif // !defined(NDEBUG) || defined(LLVM_ENABLE_STATS) protected: Statistic &init() { bool tmp = Initialized; sys::MemoryFence(); if (!tmp) RegisterStatistic(); TsanHappensAfter(this); return *this; } void RegisterStatistic(); }; // STATISTIC - A macro to make definition of statistics really simple. This // automatically passes the DEBUG_TYPE of the file into the statistic. #define STATISTIC(VARNAME, DESC) \ static llvm::Statistic VARNAME = {DEBUG_TYPE, #VARNAME, DESC, {0}, 0} /// \brief Enable the collection and printing of statistics. void EnableStatistics(); /// \brief Check if statistics are enabled. bool AreStatisticsEnabled(); /// \brief Return a file stream to print our output on. std::unique_ptr<raw_fd_ostream> CreateInfoOutputFile(); /// \brief Print statistics to the file returned by CreateInfoOutputFile(). void PrintStatistics(); /// \brief Print statistics to the given output stream. void PrintStatistics(raw_ostream &OS); /// Print statistics in JSON format. void PrintStatisticsJSON(raw_ostream &OS); } // end llvm namespace #endif // LLVM_ADT_STATISTIC_H
1.640625
2
scene/gui/split_container.h
Tosotada/godot
152
1380
/*************************************************************************/ /* split_container.h */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2018 <NAME>, <NAME>. */ /* Copyright (c) 2014-2018 Godot Engine contributors (cf. AUTHORS.md) */ /* */ /* 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 SPLIT_CONTAINER_H #define SPLIT_CONTAINER_H #include "scene/gui/container.h" class SplitContainer : public Container { GDCLASS(SplitContainer, Container) public: enum DraggerVisibility { DRAGGER_VISIBLE, DRAGGER_HIDDEN, DRAGGER_HIDDEN_COLLAPSED }; private: bool vertical; int split_offset; int middle_sep; bool dragging; int drag_from; int drag_ofs; bool collapsed; DraggerVisibility dragger_visibility; bool mouse_inside; Control *_getch(int p_idx) const; void _resort(); protected: void _gui_input(const Ref<InputEvent> &p_event); void _notification(int p_what); static void _bind_methods(); public: void set_split_offset(int p_offset); int get_split_offset() const; void set_collapsed(bool p_collapsed); bool is_collapsed() const; void set_dragger_visibility(DraggerVisibility p_visibility); DraggerVisibility get_dragger_visibility() const; virtual CursorShape get_cursor_shape(const Point2 &p_pos = Point2i()) const; virtual Size2 get_minimum_size() const; SplitContainer(bool p_vertical = false); }; VARIANT_ENUM_CAST(SplitContainer::DraggerVisibility); class HSplitContainer : public SplitContainer { GDCLASS(HSplitContainer, SplitContainer); public: HSplitContainer() : SplitContainer(false) {} }; class VSplitContainer : public SplitContainer { GDCLASS(VSplitContainer, SplitContainer); public: VSplitContainer() : SplitContainer(true) {} }; #endif // SPLIT_CONTAINER_H
1.296875
1
Source/Source/Tools/SceneEditor/KG3DTerrainHeightMap.h
uvbs/FullSource
2
1388
class KG3DTerrainHeightMap { public: KG3DTerrainHeightMap(void); virtual ~KG3DTerrainHeightMap(void); };
-0.033691
0
tensorflow-yolo-ios/dependencies/tensorflow/core/lib/io/iterator.h
initialz/tensorflow-yolo-face-ios
27
1396
version https://git-lfs.github.com/spec/v1 oid sha256:2ca62f3e14ff1da4ed61615aedbdbd58841de591485fba5e5bbb3cb9a27d4d4d size 3670
0.01709
0
ompi/mca/pml/example/pml_example_recvfrag.c
j-xiong/ompi
1,585
1404
/* * Copyright (c) 2004-2005 The University of Tennessee and The University * of Tennessee Research Foundation. All rights * reserved. * $COPYRIGHT$ * * Additional copyrights may follow * * $HEADER$ */ #include "ompi_config.h" #include "pml_example.h" #include "pml_example_recvfrag.h" bool mca_pml_example_recv_frag_match( mca_ptl_base_module_t* ptl, mca_ptl_base_recv_frag_t* frag, mca_ptl_base_match_header_t* header ) { return false; }
0.628906
1
Source/Random.h
biug/XBot
1
1412
#pragma once #include <random> namespace XBot { class Random { private: std::minstd_rand _rng; public: Random(); int index(int n); static Random & Instance(); }; }
0.443359
0
src/graphics/display/drivers/intel-i915/fake-dpcd-channel.h
Prajwal-Koirala/fuchsia
4
1420
// Copyright 2021 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef SRC_GRAPHICS_DISPLAY_DRIVERS_INTEL_I915_FAKE_DPCD_CHANNEL_H_ #define SRC_GRAPHICS_DISPLAY_DRIVERS_INTEL_I915_FAKE_DPCD_CHANNEL_H_ #include <cstdint> #include "dp-display.h" namespace i915 { namespace testing { constexpr uint8_t kDefaultLaneCount = 2; constexpr uint8_t kDefaultSinkCount = 1; constexpr size_t kMaxLinkRateTableEntries = (dpcd::DPCD_SUPPORTED_LINK_RATE_END + 1 - dpcd::DPCD_SUPPORTED_LINK_RATE_START) / 2; // FakeDpcdChannel is a utility that allows the DPCD register space to be mocked for test that need // to exercise DisplayPort functionality. class FakeDpcdChannel : public i915::DpcdChannel { public: FakeDpcdChannel() { registers.fill(0); } // Populates the bare minimum of required fields to form a valid set of capabilities. void SetDefaults(); void SetDpcdRevision(dpcd::Revision rev) { registers[dpcd::DPCD_REV] = static_cast<uint8_t>(rev); } void SetMaxLinkRate(uint8_t value) { registers[dpcd::DPCD_MAX_LINK_RATE] = value; } void SetMaxLaneCount(uint8_t value) { registers[dpcd::DPCD_MAX_LANE_COUNT] = value; } void SetSinkCount(uint8_t value) { registers[dpcd::DPCD_SINK_COUNT] = value; } void SetEdpCapable(dpcd::EdpRevision rev) { dpcd::EdpConfigCap reg; reg.set_dpcd_display_ctrl_capable(1); registers[dpcd::DPCD_EDP_CONFIG] = reg.reg_value(); registers[dpcd::DPCD_EDP_REV] = static_cast<uint8_t>(rev); } void SetEdpBacklightBrightnessCapable() { dpcd::EdpGeneralCap1 gc; gc.set_tcon_backlight_adjustment_cap(1); gc.set_backlight_aux_enable_cap(1); registers[dpcd::DPCD_EDP_GENERAL_CAP1] = gc.reg_value(); dpcd::EdpBacklightCap bc; bc.set_brightness_aux_set_cap(1); registers[dpcd::DPCD_EDP_BACKLIGHT_CAP] = bc.reg_value(); } void PopulateLinkRateTable(std::vector<uint16_t> values); // i915::DpcdChannel overrides: bool DpcdRead(uint32_t addr, uint8_t* buf, size_t size) override; bool DpcdWrite(uint32_t addr, const uint8_t* buf, size_t size) override; // The full DPCD field mapping spans addresses 0x00000-0xFFFFF however it's sufficient for us to // allocate only the subset that the driver uses. 0x800 contains all addresses up to and // including eDP-specific registers (see eDP v1.4a, 2.9.3 "DPCD Field Address Mapping"). std::array<uint8_t, 0x800> registers; }; } // namespace testing } // namespace i915 #endif // SRC_GRAPHICS_DISPLAY_DRIVERS_INTEL_I915_FAKE_DPCD_CHANNEL_H_
1.320313
1
libsrc/_DEVELOPMENT/math/float/math32/c/m32_atan2f.c
jpoikela/z88dk
0
1428
#include "m32_math.h" float m32_atan2f (float x, float y) { float v; if(m32_fabsf(y) >= m32_fabsf(x)) { v = m32_atanf(x/y); if( y < 0.0) if(x >= 0.0) v += 3.14159265358979; else v -= 3.14159265358979; return v; } v = -m32_atanf(y/x); if(y < 0.0) v -= 1.57079632679489; else v += 1.57079632679489; return v; }
1.5625
2
src/uri.h
DJAndries/libdtorr
1
1436
#ifndef URI_H #define URI_H struct parsed_uri { char* hostname; unsigned short port; char* hostname_with_port; char* schema; char* rest; }; typedef struct parsed_uri parsed_uri; parsed_uri* parse_uri(char* uri); void free_parsed_uri(parsed_uri* uri); #endif
0.964844
1
src/Generic/compound.h
MadManRises/Madgine
5
1444
#pragma once #include "type_pack.h" namespace Engine { template <typename T> using ctor_t = typename T::ctor; template <typename... Ty> struct Compound : Ty... { Compound() = default; Compound(ctor_t<Ty>... args) : Ty({ args })... { } template <typename T> static const constexpr bool holds = type_pack_contains_v<type_pack<Ty...>, T>; }; }
1.195313
1
src/keystore.h
arjundashrath/PIVX
0
1452
// Copyright (c) 2009-2010 <NAME> // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2017-2020 The PIVX developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_KEYSTORE_H #define BITCOIN_KEYSTORE_H #include "key.h" #include "pubkey.h" #include "sapling/address.h" #include "sapling/zip32.h" #include "sync.h" #include <boost/signals2/signal.hpp> class CScript; class CScriptID; /** A virtual base class for key stores */ class CKeyStore { public: // todo: Make it protected again once we are more advanced in the wallet/spkm decoupling. mutable RecursiveMutex cs_KeyStore; virtual ~CKeyStore() {} //! Add a key to the store. virtual bool AddKeyPubKey(const CKey& key, const CPubKey& pubkey) = 0; virtual bool AddKey(const CKey& key); //! Check whether a key corresponding to a given address is present in the store. virtual bool HaveKey(const CKeyID& address) const = 0; virtual bool GetKey(const CKeyID& address, CKey& keyOut) const = 0; virtual std::set<CKeyID> GetKeys() const = 0; virtual bool GetPubKey(const CKeyID& address, CPubKey& vchPubKeyOut) const = 0; //! Support for BIP 0013 : see https://github.com/bitcoin/bips/blob/master/bip-0013.mediawiki virtual bool AddCScript(const CScript& redeemScript) = 0; virtual bool HaveCScript(const CScriptID& hash) const = 0; virtual bool GetCScript(const CScriptID& hash, CScript& redeemScriptOut) const = 0; //! Support for Watch-only addresses virtual bool AddWatchOnly(const CScript& dest) = 0; virtual bool RemoveWatchOnly(const CScript& dest) = 0; virtual bool HaveWatchOnly(const CScript& dest) const = 0; virtual bool HaveWatchOnly() const = 0; //! Support for Sapling // Add a Sapling spending key to the store. virtual bool AddSaplingSpendingKey(const libzcash::SaplingExtendedSpendingKey &sk) = 0; // Check whether a Sapling spending key corresponding to a given Sapling viewing key is present in the store. virtual bool HaveSaplingSpendingKey( const libzcash::SaplingExtendedFullViewingKey &extfvk) const = 0; virtual bool GetSaplingSpendingKey( const libzcash::SaplingExtendedFullViewingKey &extfvk, libzcash::SaplingExtendedSpendingKey& skOut) const = 0; //! Support for Sapling full viewing keys virtual bool AddSaplingFullViewingKey(const libzcash::SaplingExtendedFullViewingKey &extfvk) = 0; virtual bool HaveSaplingFullViewingKey(const libzcash::SaplingIncomingViewingKey &ivk) const = 0; virtual bool GetSaplingFullViewingKey( const libzcash::SaplingIncomingViewingKey &ivk, libzcash::SaplingExtendedFullViewingKey& extfvkOut) const = 0; virtual void GetSaplingPaymentAddresses(std::set<libzcash::SaplingPaymentAddress> &setAddress) const = 0; //! Sapling incoming viewing keys virtual bool AddSaplingIncomingViewingKey( const libzcash::SaplingIncomingViewingKey &ivk, const libzcash::SaplingPaymentAddress &addr) = 0; virtual bool HaveSaplingIncomingViewingKey(const libzcash::SaplingPaymentAddress &addr) const = 0; virtual bool GetSaplingIncomingViewingKey( const libzcash::SaplingPaymentAddress &addr, libzcash::SaplingIncomingViewingKey& ivkOut) const = 0; }; typedef std::map<CKeyID, CKey> KeyMap; typedef std::map<CKeyID, CPubKey> WatchKeyMap; typedef std::map<CScriptID, CScript> ScriptMap; typedef std::set<CScript> WatchOnlySet; // Full viewing key has equivalent functionality to a transparent address // When encrypting wallet, encrypt SaplingSpendingKeyMap, while leaving SaplingFullViewingKeyMap unencrypted typedef std::map< libzcash::SaplingExtendedFullViewingKey, libzcash::SaplingExtendedSpendingKey> SaplingSpendingKeyMap; typedef std::map< libzcash::SaplingIncomingViewingKey, libzcash::SaplingExtendedFullViewingKey> SaplingFullViewingKeyMap; // Only maps from default addresses to ivk, may need to be reworked when adding diversified addresses. typedef std::map<libzcash::SaplingPaymentAddress, libzcash::SaplingIncomingViewingKey> SaplingIncomingViewingKeyMap; /** Basic key store, that keeps keys in an address->secret map */ class CBasicKeyStore : public CKeyStore { protected: KeyMap mapKeys; WatchKeyMap mapWatchKeys; ScriptMap mapScripts; WatchOnlySet setWatchOnly; public: // todo future: Move every Sapling map to the new sspkm box. SaplingSpendingKeyMap mapSaplingSpendingKeys; SaplingFullViewingKeyMap mapSaplingFullViewingKeys; SaplingIncomingViewingKeyMap mapSaplingIncomingViewingKeys; bool AddKeyPubKey(const CKey& key, const CPubKey& pubkey); bool GetPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const; bool HaveKey(const CKeyID& address) const; std::set<CKeyID> GetKeys() const; bool GetKey(const CKeyID& address, CKey& keyOut) const; virtual bool AddCScript(const CScript& redeemScript); virtual bool HaveCScript(const CScriptID& hash) const; virtual bool GetCScript(const CScriptID& hash, CScript& redeemScriptOut) const; virtual bool AddWatchOnly(const CScript& dest); virtual bool RemoveWatchOnly(const CScript& dest); virtual bool HaveWatchOnly(const CScript& dest) const; virtual bool HaveWatchOnly() const; //! Sapling bool AddSaplingSpendingKey(const libzcash::SaplingExtendedSpendingKey &sk); bool HaveSaplingSpendingKey(const libzcash::SaplingExtendedFullViewingKey &extfvk) const; bool GetSaplingSpendingKey(const libzcash::SaplingExtendedFullViewingKey &extfvk, libzcash::SaplingExtendedSpendingKey &skOut) const; virtual bool AddSaplingFullViewingKey(const libzcash::SaplingExtendedFullViewingKey &extfvk); virtual bool HaveSaplingFullViewingKey(const libzcash::SaplingIncomingViewingKey &ivk) const; virtual bool GetSaplingFullViewingKey( const libzcash::SaplingIncomingViewingKey &ivk, libzcash::SaplingExtendedFullViewingKey& extfvkOut) const; virtual bool AddSaplingIncomingViewingKey( const libzcash::SaplingIncomingViewingKey &ivk, const libzcash::SaplingPaymentAddress &addr); virtual bool HaveSaplingIncomingViewingKey(const libzcash::SaplingPaymentAddress &addr) const; virtual bool GetSaplingIncomingViewingKey( const libzcash::SaplingPaymentAddress &addr, libzcash::SaplingIncomingViewingKey& ivkOut) const; bool GetSaplingExtendedSpendingKey( const libzcash::SaplingPaymentAddress &addr, libzcash::SaplingExtendedSpendingKey &extskOut) const; void GetSaplingPaymentAddresses(std::set<libzcash::SaplingPaymentAddress> &setAddress) const; }; typedef std::vector<unsigned char, secure_allocator<unsigned char> > CKeyingMaterial; typedef std::map<CKeyID, std::pair<CPubKey, std::vector<unsigned char> > > CryptedKeyMap; //! Sapling typedef std::map<libzcash::SaplingExtendedFullViewingKey, std::vector<unsigned char> > CryptedSaplingSpendingKeyMap; #endif // BITCOIN_KEYSTORE_H
1.523438
2
ruby/lib/ruby/gems/2.0.0/gems/byebug-5.0.0/ext/byebug/byebug.h
choman7721/stukdo
1
1460
#ifndef BYEBUG #define BYEBUG #include <ruby.h> #include <ruby/debug.h> /* To prevent unused parameter warnings */ #define UNUSED(x) (void)(x) /* flags */ #define CTX_FL_DEAD (1<<1) /* this context belonged to a dead thread */ #define CTX_FL_IGNORE (1<<2) /* this context belongs to ignored thread */ #define CTX_FL_SUSPEND (1<<3) /* thread currently suspended */ #define CTX_FL_TRACING (1<<4) /* call at_tracing method */ #define CTX_FL_WAS_RUNNING (1<<5) /* thread was previously running */ #define CTX_FL_STOP_ON_RET (1<<6) /* can stop on method 'end' */ #define CTX_FL_IGNORE_STEPS (1<<7) /* doesn't countdown steps to break */ /* macro functions */ #define CTX_FL_TEST(c,f) ((c)->flags & (f)) #define CTX_FL_SET(c,f) do { (c)->flags |= (f); } while (0) #define CTX_FL_UNSET(c,f) do { (c)->flags &= ~(f); } while (0) /* types */ typedef enum { CTX_STOP_NONE, CTX_STOP_STEP, CTX_STOP_BREAKPOINT, CTX_STOP_CATCHPOINT } ctx_stop_reason; typedef struct { int calced_stack_size; int flags; ctx_stop_reason stop_reason; VALUE thread; int thnum; int dest_frame; /* next stop's frame if stopped by next */ int lines; /* # of lines in dest_frame before stopping */ int steps; /* # of steps before stopping */ int steps_out; /* # of returns before stopping */ VALUE backtrace; /* [[loc, self, klass, binding], ...] */ } debug_context_t; enum frame_component { LOCATION, SELF, CLASS, BINDING }; struct call_with_inspection_data { debug_context_t *dc; VALUE context_obj; ID id; int argc; VALUE *argv; }; typedef struct { st_table *tbl; } threads_table_t; enum bp_type { BP_POS_TYPE, BP_METHOD_TYPE }; enum hit_condition { HIT_COND_NONE, HIT_COND_GE, HIT_COND_EQ, HIT_COND_MOD }; typedef struct { int id; enum bp_type type; VALUE source; union { int line; ID mid; } pos; VALUE expr; VALUE enabled; int hit_count; int hit_value; enum hit_condition hit_condition; } breakpoint_t; /* functions from locker.c */ extern int is_in_locked(VALUE thread_id); extern void add_to_locked(VALUE thread); extern VALUE pop_from_locked(); extern void remove_from_locked(VALUE thread); /* functions from threads.c */ extern void Init_threads_table(VALUE mByebug); extern VALUE create_threads_table(void); extern void thread_context_lookup(VALUE thread, VALUE *context); extern int is_living_thread(VALUE thread); extern void acquire_lock(debug_context_t *dc); extern void release_lock(void); /* global variables */ extern VALUE threads; extern VALUE next_thread; /* functions from context.c */ extern void Init_context(VALUE mByebug); extern VALUE context_create(VALUE thread); extern VALUE context_dup(debug_context_t *context); extern void reset_stepping_stop_points(debug_context_t *context); extern VALUE call_with_debug_inspector(struct call_with_inspection_data *data); extern VALUE context_backtrace_set(const rb_debug_inspector_t *inspector, void *data); /* functions from breakpoint.c */ extern void Init_breakpoint(VALUE mByebug); extern VALUE catchpoint_hit_count(VALUE catchpoints, VALUE exception, VALUE *exception_name); extern VALUE find_breakpoint_by_pos(VALUE breakpoints, VALUE source, VALUE pos, VALUE bind); extern VALUE find_breakpoint_by_method(VALUE breakpoints, VALUE klass, VALUE mid, VALUE bind, VALUE self); #endif
1.570313
2
System/Library/PrivateFrameworks/Navigation.framework/MNClassicGuidanceManager.h
lechium/tvOS135Headers
2
1468
/* * This header is generated by classdump-dyld 1.0 * on Sunday, June 7, 2020 at 11:17:54 AM Mountain Standard Time * Operating System: Version 13.4.5 (Build 17L562) * Image Source: /System/Library/PrivateFrameworks/Navigation.framework/Navigation * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>. */ #import <Navigation/Navigation-Structs.h> #import <libobjc.A.dylib/MNGuidanceManager.h> @protocol MNGuidanceManagerDelegate; @class GEOComposedRoute, MNNavigationSession, GEOComposedWaypoint, NSString, NSData, GEOComposedRouteStep; @interface MNClassicGuidanceManager : NSObject <MNGuidanceManager> { GEOComposedRoute* _route; int _guidanceState; unsigned long long _currentStepIndex; double _distanceWhenFirstAnnouncementAllowed; double _distanceWhenInitialAnnounced; double _distanceWhenPrepareAnnounced; double _distanceWhenExecuteAnnounced; double _baselineSpeed; double _baselineDistance; double _minExecutionDistance; double _timeLastAnnouncementStarted; double _timeLastAnnouncementEnded; double _timeUntilNextAnnouncement; double _estimateOfTimeToSpeakExecutionAnnouncement; BOOL _shouldAnnounceContinueStraight; BOOL _shouldSkipInitialAnnounce; BOOL _shouldSkipPrepareAnnounce; BOOL _shouldSkipExecuteAnnounce; BOOL _didAnnounceProceedToRoute; BOOL _didAnnounceManeuverContinue; BOOL _didAnnounceManeuverInitial; BOOL _didAnnounceManeuverPreparation; BOOL _didAnnounceManeuverExecution; BOOL _didAnnounceSecondaryManeuver; BOOL _didAnnounceArrival; BOOL _didShowPrimarySign; BOOL _didShowSecondarySign; id<MNGuidanceManagerDelegate> _delegate; MNNavigationSession* _navigationSession; GEOComposedWaypoint* _destination; unsigned long long _pointIndexForCurrentRoadInfo; NSString* _currentRoadName; long long _currentShieldType; NSString* _currentShieldText; SCD_Struct_MN16 _currentInstructionOptions; BOOL _didAnnounceStartOfRoute; unsigned long long _countLocationUpdates; } @property (nonatomic,retain) NSString * currentRoadName; //@synthesize currentRoadName=_currentRoadName - In the implementation block @property (nonatomic,retain) NSString * currentShieldText; //@synthesize currentShieldText=_currentShieldText - In the implementation block @property (assign,nonatomic) SCD_Struct_MN16 currentInstructionOptions; //@synthesize currentInstructionOptions=_currentInstructionOptions - In the implementation block @property (assign,nonatomic,__weak) id<MNGuidanceManagerDelegate> delegate; //@synthesize delegate=_delegate - In the implementation block @property (nonatomic,readonly) NSData * remainingRouteZilchData; @property (nonatomic,readonly) int guidanceState; //@synthesize guidanceState=_guidanceState - In the implementation block @property (nonatomic,readonly) BOOL proceedingToRoute; @property (nonatomic,readonly) GEOComposedRouteStep * maneuverStep; @property (nonatomic,readonly) unsigned long long maneuverStepIndex; @property (nonatomic,readonly) int transportType; @property (nonatomic,readonly) GEOComposedRoute * route; //@synthesize route=_route - In the implementation block @property (readonly) unsigned long long hash; @property (readonly) Class superclass; @property (copy,readonly) NSString * description; @property (copy,readonly) NSString * debugDescription; -(void)dealloc; -(id<MNGuidanceManagerDelegate>)delegate; -(void)setDelegate:(id<MNGuidanceManagerDelegate>)arg1 ; -(void)stop; -(int)transportType; -(GEOComposedRoute *)route; -(void)setCurrentRoadName:(NSString *)arg1 ; -(NSString *)currentRoadName; -(GEOComposedRouteStep *)maneuverStep; -(void)updateDestination:(id)arg1 ; -(void)updateForReroute:(id)arg1 ; -(double)timeSinceLastAnnouncement; -(double)timeUntilNextAnnouncement; -(void)_resetStepState; -(void)_clearCurrentRoadName; -(unsigned long long)maneuverStepIndex; -(id)_getStepAtIndex:(unsigned long long)arg1 ; -(void)setCurrentShieldText:(NSString *)arg1 ; -(id)_nameInfoForContinueSign; -(id)_nameInfoForCurrentRoad; -(id)_getStepAtIndex:(unsigned long long)arg1 clampIndexToRange:(BOOL)arg2 ; -(int)guidanceState; -(unsigned long long)_maneuverStepIndex; -(id)_announcementForArrival; -(id)_announcementForStart; -(id)_updateValidateRouteMatchForLocation:(id)arg1 ; -(BOOL)_startingWrongWayForLocation:(id)arg1 navigatorState:(int)arg2 routeMatch:(id)arg3 ; -(void)_notifyAnnounceManeuverForStep:(id)arg1 withDistance:(double)arg2 withCombinedGuidance:(int)arg3 playShortPrompt:(BOOL)arg4 isRepeat:(BOOL)arg5 stage:(unsigned long long)arg6 timeLimit:(double)arg7 ; -(void)_notifyDisplayManeuverForStep:(id)arg1 withDistance:(double)arg2 allowCombinedGuidance:(BOOL)arg3 ; -(BOOL)_updateCheckIfNextStep:(id)arg1 navigatorState:(int)arg2 routeMatch:(id)arg3 ; -(BOOL)_updateGuidanceStateWithLocation:(id)arg1 withMatch:(id)arg2 withNavigatorState:(int)arg3 stepChanged:(BOOL*)arg4 ; -(unsigned long long)_currentAnnouncementStage; -(BOOL)proceedingToRoute; -(void)updateGuidanceForProceedToRouteAtLocation:(SCD_Struct_MN8)arg1 routeMatch:(id)arg2 remainingTime:(double)arg3 distanceUntilDestination:(double)arg4 ; -(void)_updatePrepareForNextStep; -(BOOL)_updateConsiderContinueAnnouncement:(id)arg1 location:(id)arg2 ; -(BOOL)_updateConsiderInitialAnnouncement:(id)arg1 passedManeuverStart:(BOOL)arg2 ; -(BOOL)_updateConsiderExecuteAnnouncement:(id)arg1 location:(id)arg2 ; -(BOOL)_updateConsiderPrepareAnnouncement:(id)arg1 withMatch:(id)arg2 ; -(double)_timeUntilNextAnnouncement:(id)arg1 location:(id)arg2 upcomingStage:(out unsigned long long*)arg3 ; -(double)_distanceForSign; -(id)_getClosestStepWithNameForProceedToRoute:(SCD_Struct_MN8)arg1 routeMatch:(id)arg2 ; -(id)_combinedGuidanceForStep:(id)arg1 withType:(int)arg2 ; -(void)_notifyAnnounceProceedToRoute:(id)arg1 withClosestStep:(id)arg2 withNamedStep:(id)arg3 andSecondaryStep:(id)arg4 isRepeat:(BOOL)arg5 ; -(void)_notifyDisplayManeuverForSecondaryStep:(id)arg1 ; -(double)_durationOfLastAnnouncement; -(double)_adjustedVehicleSpeed:(id)arg1 ; -(double)_speedFactor:(id)arg1 ; -(double)_calculateExecutionDistance:(id)arg1 withLogging:(BOOL)arg2 ; -(double)_estimateTimeToSpeakExecutionAnnouncement; -(void)_notifyAnnounceContinueAsRepeat:(BOOL)arg1 ; -(void)updateGuidanceForLocation:(id)arg1 navigatorState:(int)arg2 ; -(BOOL)repeatLastGuidanceAnnouncement:(id)arg1 ; -(void)addInjectedEvent:(id)arg1 ; -(void)updateForReturnToRoute; -(id)initWithNavigationSession:(id)arg1 proceedToRoute:(BOOL)arg2 allowMidRouteStart:(BOOL)arg3 ; -(BOOL)_hasSubsteps; -(BOOL)_hasCurrentRoadNameChangedForLocation:(id)arg1 ; -(SCD_Struct_MN8)maneuverStepCoordinate; -(BOOL)_announcementInProgress; -(NSData *)remainingRouteZilchData; -(NSString *)currentShieldText; -(SCD_Struct_MN16)currentInstructionOptions; -(void)setCurrentInstructionOptions:(SCD_Struct_MN16)arg1 ; @end
0.660156
1
processors/ARM/gdb-7.10/sim/rx/cpu.h
pavel-krivanek/opensmalltalk-vm
110
1476
/* cpu.h --- declarations for the RX core. Copyright (C) 2005-2015 Free Software Foundation, Inc. Contributed by Red Hat, Inc. This file is part of the GNU simulators. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stdint.h> #include <setjmp.h> extern int verbose; extern int trace; extern int enable_counting; typedef uint8_t QI; typedef uint16_t HI; typedef uint32_t SI; typedef uint64_t DI; extern int rx_in_gdb; extern int rx_big_endian; typedef struct { SI r[16]; SI r_psw; SI r_pc; SI r_usp; SI r_fpsw; SI r__reserved_cr_4; SI r__reserved_cr_5; SI r__reserved_cr_6; SI r__reserved_cr_7; SI r_bpsw; SI r_bpc; SI r_isp; SI r_fintv; SI r_intb; SI r__reserved_cr_13; SI r__reserved_cr_14; SI r__reserved_cr_15; SI r__reserved_cr_16; SI r__reserved_cr_17; SI r__reserved_cr_18; SI r__reserved_cr_19; SI r__reserved_cr_20; SI r__reserved_cr_21; SI r__reserved_cr_22; SI r__reserved_cr_23; SI r__reserved_cr_24; SI r__reserved_cr_25; SI r__reserved_cr_26; SI r__reserved_cr_27; SI r__reserved_cr_28; SI r__reserved_cr_29; SI r__reserved_cr_30; SI r__reserved_cr_31; SI r_temp; DI r_acc; #ifdef CYCLE_ACCURATE /* If set, RTS/RTSD take 2 fewer cycles. */ char fast_return; SI link_register; unsigned long long cycle_count; /* Bits saying what kind of memory operands the previous insn had. */ int m2m; /* Target register for load. */ int rt; #endif } regs_type; #define M2M_SRC 0x01 #define M2M_DST 0x02 #define M2M_BOTH 0x03 #define sp 0 #define psw 16 #define pc 17 #define usp 18 #define fpsw 19 #define bpsw 24 #define bpc 25 #define isp 26 #define fintv 27 #define intb 28 #define r_temp_idx 48 #define acc64 49 #define acchi 50 #define accmi 51 #define acclo 52 extern regs_type regs; #define FLAGBIT_C 0x00000001 #define FLAGBIT_Z 0x00000002 #define FLAGBIT_S 0x00000004 #define FLAGBIT_O 0x00000008 #define FLAGBIT_I 0x00010000 #define FLAGBIT_U 0x00020000 #define FLAGBIT_PM 0x00100000 #define FLAGBITS_IPL 0x0f000000 #define FLAGSHIFT_IPL 24 #define FPSWBITS_RM 0x00000003 #define FPSWBITS_CV 0x00000004 /* invalid operation */ #define FPSWBITS_CO 0x00000008 /* overflow */ #define FPSWBITS_CZ 0x00000010 /* divide-by-zero */ #define FPSWBITS_CU 0x00000020 /* underflow */ #define FPSWBITS_CX 0x00000040 /* inexact */ #define FPSWBITS_CE 0x00000080 /* unimplemented processing */ #define FPSWBITS_CMASK 0x000000fc /* all the above */ #define FPSWBITS_DN 0x00000100 #define FPSW_CESH 8 #define FPSWBITS_EV 0x00000400 #define FPSWBITS_EO 0x00000800 #define FPSWBITS_EZ 0x00001000 #define FPSWBITS_EU 0x00002000 #define FPSWBITS_EX 0x00004000 #define FPSW_EFSH 16 #define FPSW_CFSH 24 #define FPSWBITS_FV 0x04000000 #define FPSWBITS_FO 0x08000000 #define FPSWBITS_FZ 0x10000000 #define FPSWBITS_FU 0x20000000 #define FPSWBITS_FX 0x40000000 #define FPSWBITS_FSUM 0x80000000 #define FPSWBITS_FMASK 0x7c000000 #define FPSWBITS_CLEAR 0xffffff03 /* masked at start of any FP opcode */ #define FPRM_NEAREST 0 #define FPRM_ZERO 1 #define FPRM_PINF 2 #define FPRM_NINF 3 extern char *reg_names[]; extern int rx_flagmask; extern int rx_flagand; extern int rx_flagor; extern unsigned int b2mask[]; extern unsigned int b2signbit[]; extern int b2maxsigned[]; extern int b2minsigned[]; void init_regs (void); void stack_heap_stats (void); void set_pointer_width (int bytes); unsigned int get_reg (int id); unsigned long long get_reg64 (int id); void put_reg (int id, unsigned int value); void put_reg64 (int id, unsigned long long value); void set_flags (int mask, int newbits); void set_oszc (long long value, int bytes, int c); void set_szc (long long value, int bytes, int c); void set_osz (long long value, int bytes); void set_sz (long long value, int bytes); void set_zc (int z, int c); void set_c (int c); const char *bits (int v, int b); int condition_true (int cond_id); #define FLAG(f) ((regs.r_psw & f) ? 1 : 0) #define FLAG_C FLAG(FLAGBIT_C) #define FLAG_D FLAG(FLAGBIT_D) #define FLAG_Z FLAG(FLAGBIT_Z) #define FLAG_S FLAG(FLAGBIT_S) #define FLAG_B FLAG(FLAGBIT_B) #define FLAG_O FLAG(FLAGBIT_O) #define FLAG_I FLAG(FLAGBIT_I) #define FLAG_U FLAG(FLAGBIT_U) #define FLAG_PM FLAG(FLAGBIT_PM) /* Instruction step return codes. Suppose one of the decode_* functions below returns a value R: - If RX_STEPPED (R), then the single-step completed normally. - If RX_HIT_BREAK (R), then the program hit a breakpoint. - If RX_EXITED (R), then the program has done an 'exit' system call, and the exit code is RX_EXIT_STATUS (R). - If RX_STOPPED (R), then a signal (number RX_STOP_SIG (R)) was generated. For building step return codes: - RX_MAKE_STEPPED is the return code for finishing a normal step. - RX_MAKE_HIT_BREAK is the return code for hitting a breakpoint. - RX_MAKE_EXITED (C) is the return code for exiting with status C. - RX_MAKE_STOPPED (S) is the return code for stopping on signal S. */ #define RX_MAKE_STEPPED() (1) #define RX_MAKE_HIT_BREAK() (2) #define RX_MAKE_EXITED(c) (((int) (c) << 8) + 3) #define RX_MAKE_STOPPED(s) (((int) (s) << 8) + 4) #define RX_STEPPED(r) ((r) == RX_MAKE_STEPPED ()) #define RX_HIT_BREAK(r) ((r) == RX_MAKE_HIT_BREAK ()) #define RX_EXITED(r) (((r) & 0xff) == 3) #define RX_EXIT_STATUS(r) ((r) >> 8) #define RX_STOPPED(r) (((r) & 0xff) == 4) #define RX_STOP_SIG(r) ((r) >> 8) /* The step result for the current step. Global to allow communication between the stepping function and the system calls. */ extern int step_result; extern unsigned int rx_cycles; /* Used to detect heap/stack collisions. */ extern unsigned int heaptop; extern unsigned int heapbottom; extern int decode_opcode (void); extern void reset_decoder (void); extern void reset_pipeline_stats (void); extern void halt_pipeline_stats (void); extern void pipeline_stats (void); extern void trace_register_changes (); extern void generate_access_exception (void); extern jmp_buf decode_jmp_buf;
1.03125
1
src/cpp/I2Cdev.h
satosystems/mpu6050
0
1484
// I2Cdev library collection - Main I2C device class header file // Abstracts bit and byte I2C R/W functions into a convenient class // 6/9/2012 by <NAME> <<EMAIL>> // // Changelog: // 2012-06-09 - fix major issue with reading > 32 bytes at a time with Arduino Wire // - add compiler warnings when using outdated or IDE or limited I2Cdev implementation // 2011-11-01 - fix write*Bits mask calculation (thanks sasquatch @ Arduino forums) // 2011-10-03 - added automatic Arduino version detection for ease of use // 2011-10-02 - added Gene Knight's NBWire TwoWire class implementation with small modifications // 2011-08-31 - added support for Arduino 1.0 Wire library (methods are different from 0.x) // 2011-08-03 - added optional timeout parameter to read* methods to easily change from default // 2011-08-02 - added support for 16-bit registers // - fixed incorrect Doxygen comments on some methods // - added timeout value for read operations (thanks mem @ Arduino forums) // 2011-07-30 - changed read/write function structures to return success or byte counts // - made all methods static for multi-device memory savings // 2011-07-28 - initial release /* ============================================ I2Cdev device library code is placed under the MIT license Copyright (c) 2012 <NAME> 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 _I2CDEV_H_ #define _I2CDEV_H_ #ifndef TRUE #define TRUE (1==1) #define FALSE (0==1) #endif class I2Cdev { public: I2Cdev(); static int8_t readBit(uint8_t devAddr, uint8_t regAddr, uint8_t bitNum, uint8_t *data, uint16_t timeout=I2Cdev::readTimeout); static int8_t readBitW(uint8_t devAddr, uint8_t regAddr, uint8_t bitNum, uint16_t *data, uint16_t timeout=I2Cdev::readTimeout); static int8_t readBits(uint8_t devAddr, uint8_t regAddr, uint8_t bitStart, uint8_t length, uint8_t *data, uint16_t timeout=I2Cdev::readTimeout); static int8_t readBitsW(uint8_t devAddr, uint8_t regAddr, uint8_t bitStart, uint8_t length, uint16_t *data, uint16_t timeout=I2Cdev::readTimeout); static int8_t readByte(uint8_t devAddr, uint8_t regAddr, uint8_t *data, uint16_t timeout=I2Cdev::readTimeout); static int8_t readWord(uint8_t devAddr, uint8_t regAddr, uint16_t *data, uint16_t timeout=I2Cdev::readTimeout); static int8_t readBytes(uint8_t devAddr, uint8_t regAddr, uint8_t length, uint8_t *data, uint16_t timeout=I2Cdev::readTimeout); static int8_t readWords(uint8_t devAddr, uint8_t regAddr, uint8_t length, uint16_t *data, uint16_t timeout=I2Cdev::readTimeout); static bool writeBit(uint8_t devAddr, uint8_t regAddr, uint8_t bitNum, uint8_t data); static bool writeBitW(uint8_t devAddr, uint8_t regAddr, uint8_t bitNum, uint16_t data); static bool writeBits(uint8_t devAddr, uint8_t regAddr, uint8_t bitStart, uint8_t length, uint8_t data); static bool writeBitsW(uint8_t devAddr, uint8_t regAddr, uint8_t bitStart, uint8_t length, uint16_t data); static bool writeByte(uint8_t devAddr, uint8_t regAddr, uint8_t data); static bool writeWord(uint8_t devAddr, uint8_t regAddr, uint16_t data); static bool writeBytes(uint8_t devAddr, uint8_t regAddr, uint8_t length, uint8_t *data); static bool writeWords(uint8_t devAddr, uint8_t regAddr, uint8_t length, uint16_t *data); static uint16_t readTimeout; static const char* findI2C(); }; #endif /* _I2CDEV_H_ */
1.554688
2
third_party/MADDriver.Source/FileUtils.h
mickaelcala/TNTbasic
5
1492
/******************** ***********************/ // // Player PRO 5.0 - DRIVER SOURCE CODE - // // Library Version 5.0 // // To use with MAD Library for Mac: Symantec, CodeWarrior and MPW // // <NAME> // 16 Tranchees // 1206 GENEVA // SWITZERLAND // // COPYRIGHT <NAME> 1996, 1997, 1998 // // Thank you for your interest in PlayerPRO ! // // FAX: (+41 22) 346 11 97 // PHONE: (+41 79) 203 74 62 // Internet: <EMAIL> // /******************** ***********************/ #ifndef __PPC_FILEUTILS_H__ #define __PPC_FILEUTILS_H__ #ifndef __MADI__ #include "MAD.h" #endif #ifdef __cplusplus extern "C" { #endif //////////////////////////////////////////////////////////// #ifdef _MAC_H #include <CoreServices/CoreServices.h> #if defined(__LP64__) typedef FSIORefNum UNFILE; #else typedef SInt16 UNFILE; #endif #else #include <stdio.h> #include <stdlib.h> #include <string.h> typedef FILE* UNFILE; #endif EXP UNFILE iFileOpen( Ptr name); EXP void iFileCreate( Ptr name, OSType); EXP long iGetEOF( UNFILE iFileRefI); EXP OSErr iRead( long size, Ptr dest, UNFILE iFileRefI); EXP OSErr iWrite( long size, Ptr dest, UNFILE iFileRefI); EXP OSErr iSeekCur( long size, UNFILE iFileRefI); EXP void iClose( UNFILE iFileRefI); EXP char* MADstrcpy( char*, const char*) DEPRECATED_ATTRIBUTE; EXP int MADstrcmp( const char *dst, const char* src); EXP unsigned char* MYC2PStr( Ptr cStr); EXP void MYP2CStr( unsigned char *cStr); EXP OSType Ptr2OSType( Ptr str); EXP void OSType2Ptr( OSType type, Ptr str); void pStrcpy(register unsigned char *s1, register const unsigned char *s2); //////////////////////////////////////////////////////////// #ifdef NOINLINE void INT32( void *msg_buf); void INT16( void *msg_buf); void MOT32( void *msg_buf); void MOT16( void *msg_buf); #else static inline void MADByteSwap32(void *msg_buf) { UInt32 temp = *((UInt32*) msg_buf); #ifdef _MAC_H *((UInt32*) msg_buf) = Endian32_Swap(temp); #else *((UInt32*) msg_buf) = ((((temp & 0xff000000) >> 24) | \ (( temp & 0x00ff0000) >> 8) | (( temp & 0x0000ff00) << 8) | \ (temp & 0x000000ff) << 24)); #endif } static inline void MADByteSwap16(void *msg_buf) { UInt16 buf = *((UInt16*) msg_buf); #ifdef _MAC_H *((UInt16*) msg_buf) = Endian16_Swap(buf); #else *((UInt16*) msg_buf) = (((((UInt16)buf)<<8) & 0xFF00) | ((((UInt16)buf)>>8) & 0x00FF)); #endif } ///////////////////////////////// static inline void MOT32(void *msg_buf) { #ifdef __LITTLE_ENDIAN__ MADByteSwap32(msg_buf); #endif } static inline void MOT16(void *msg_buf) { #ifdef __LITTLE_ENDIAN__ MADByteSwap16(msg_buf); #endif } ///////////////////////////////// static inline void INT32(void *msg_buf) { #ifdef __BIG_ENDIAN__ MADByteSwap32(msg_buf); #endif } static inline void INT16(void *msg_buf) { #ifdef __BIG_ENDIAN__ MADByteSwap16(msg_buf); #endif } #endif #ifdef __cplusplus } #endif #endif
1.132813
1
IMU/VTK-6.2.0/Filters/Sources/vtkOutlineCornerFilter.h
timkrentz/SunTracker
4
1500
/*========================================================================= Program: Visualization Toolkit Module: vtkOutlineCornerFilter.h Copyright (c) <NAME>, <NAME>, <NAME> All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ // .NAME vtkOutlineCornerFilter - create wireframe outline corners for arbitrary data set // .SECTION Description // vtkOutlineCornerFilter is a filter that generates wireframe outline corners of any // data set. The outline consists of the eight corners of the dataset // bounding box. #ifndef vtkOutlineCornerFilter_h #define vtkOutlineCornerFilter_h #include "vtkFiltersSourcesModule.h" // For export macro #include "vtkPolyDataAlgorithm.h" class vtkOutlineCornerSource; class VTKFILTERSSOURCES_EXPORT vtkOutlineCornerFilter : public vtkPolyDataAlgorithm { public: vtkTypeMacro(vtkOutlineCornerFilter,vtkPolyDataAlgorithm); void PrintSelf(ostream& os, vtkIndent indent); // Description: // Construct outline corner filter with default corner factor = 0.2 static vtkOutlineCornerFilter *New(); // Description: // Set/Get the factor that controls the relative size of the corners // to the length of the corresponding bounds vtkSetClampMacro(CornerFactor, double, 0.001, 0.5); vtkGetMacro(CornerFactor, double); protected: vtkOutlineCornerFilter(); ~vtkOutlineCornerFilter(); vtkOutlineCornerSource *OutlineCornerSource; virtual int RequestData(vtkInformation *, vtkInformationVector **, vtkInformationVector *); virtual int FillInputPortInformation(int port, vtkInformation *info); double CornerFactor; private: vtkOutlineCornerFilter(const vtkOutlineCornerFilter&); // Not implemented. void operator=(const vtkOutlineCornerFilter&); // Not implemented. }; #endif
1.75
2
FWCore/ParameterSet/interface/ParameterDescriptionNode.h
jwill24/cmssw
0
1508
#ifndef FWCore_ParameterSet_ParameterDescriptionNode_h #define FWCore_ParameterSet_ParameterDescriptionNode_h // This is a base class for the class that describes // the parameters that are allowed or required to be // in a ParameterSet. It is also a base class for // other more complex logical structures which describe // which combinations of parameters are allowed to be // in a ParameterSet. #include "FWCore/Utilities/interface/value_ptr.h" #include <string> #include <set> #include <iosfwd> #include <memory> namespace edm { class ParameterSet; template <typename T> class ParameterDescriptionCases; class DocFormatHelper; // Originally these were defined such that the values were the // same as in the ParameterSet Entry class and the validation // depended on that. But at the moment I'm typing this comment, // the code no longer depends on the values being the same (which // is probably good because nothing enforces the correspondence, // a task for the future when someone has free time would be // to define the values in a common header, but that would involve // significant changes to ParameterSet ...) enum ParameterTypes { k_int32 = 'I', k_vint32 = 'i', k_uint32 = 'U', k_vuint32 = 'u', k_int64 = 'L', k_vint64 = 'l', k_uint64 = 'X', k_vuint64 = 'x', k_double = 'D', k_vdouble = 'd', k_bool = 'B', k_string = 'S', k_vstring = 's', k_EventID = 'E', k_VEventID = 'e', k_LuminosityBlockID = 'M', k_VLuminosityBlockID = 'm', k_InputTag = 't', k_VInputTag = 'v', k_FileInPath = 'F', k_LuminosityBlockRange = 'A', k_VLuminosityBlockRange = 'a', k_EventRange = 'R', k_VEventRange = 'r', k_PSet = 'Q', k_VPSet = 'q' }; std::string parameterTypeEnumToString(ParameterTypes iType); struct ParameterTypeToEnum { template <class T> static ParameterTypes toEnum(); }; class Comment { public: Comment(); explicit Comment(std::string const& iComment); explicit Comment(char const* iComment); std::string const& comment() const { return comment_; } private: std::string comment_; }; class ParameterDescriptionNode { public: ParameterDescriptionNode() {} explicit ParameterDescriptionNode(Comment const& iComment) : comment_(iComment.comment()) {} virtual ~ParameterDescriptionNode(); virtual ParameterDescriptionNode* clone() const = 0; std::string const& comment() const { return comment_; } void setComment(std::string const& value); void setComment(char const* value); // The validate function should do one of three things, find that the // node "exists", make the node "exist" by inserting missing parameters // or throw. The only exception to this rule occurs when the argument // named "optional" is true, which should only be possible for the // top level nodes of a ParameterSetDescription. When a parameter is // found or inserted its label is added into the list of validatedLabels. void validate(ParameterSet& pset, std::set<std::string>& validatedLabels, bool optional) const { validate_(pset, validatedLabels, optional); } // As long as it has default values, this will attempt to write // parameters associated with a node into a cfi file that is // being automatically generated. It is quite possible for // to produce a cfi that will fail validation. In some cases, // this will imply the user is required to supply certain missing // parameters that do not appear in the cfi and do not have defaults // in the description. It is also possible to create a pathological // ParameterSetDescription where the algorithm fails to write // a valid cfi, in some cases the description can be so pathological // that it is impossible to write a cfi that will pass validation. void writeCfi(std::ostream& os, bool optional, bool& startWithComma, int indentation, bool& wroteSomething) const { writeCfi_(os, optional, startWithComma, indentation, wroteSomething); } // Print out the description in human readable format void print(std::ostream& os, bool optional, bool writeToCfi, DocFormatHelper& dfh) const; bool hasNestedContent() const { return hasNestedContent_(); } void printNestedContent(std::ostream& os, bool optional, DocFormatHelper& dfh) const; // The next three functions are only called by the logical nodes // on their subnodes. When executing these functions, the // insertion of missing parameters does not occur. // Usually checks to see if a parameter exists in the configuration, but // if the node is a logical node, then it returns the value of the logical // expression. bool exists(ParameterSet const& pset) const { return exists_(pset); } // For most nodes, this simply returns the same value as the exists // function. But for AND nodes this returns true if either its subnodes // exists. Used by operator&& during validation, if either of an AND node's // subnodes exists, then both subnodes get validated. bool partiallyExists(ParameterSet const& pset) const { return partiallyExists_(pset); } // For most nodes, this simply returns the same value as the exists // function. It is different for an XOR node. It counts // XOR subnodes whose exists function returns true. And it // does this recursively into XOR nodes that are contained in // other XOR nodes. // Used by operator^ during validation: // -- if it returns more than 1, then validation will throw, // -- if it returns exactly one, then only the nonzero subnode gets validated // -- if it returns zero, then validation tries to validate the first node and // then rechecks to see what the missing parameter insertion did (there could // be side effects on the nodes that were not validated) int howManyXORSubNodesExist(ParameterSet const& pset) const { return howManyXORSubNodesExist_(pset); } /* Validation puts requirements on which parameters can and cannot exist within a ParameterSet. The evaluation of whether a ParameterSet passes or fails the rules in the ParameterSetDescription is complicated by the fact that we allow missing parameters to be injected into the ParameterSet during validation. One must worry whether injecting a missing parameter invalidates some other part of the ParameterSet that was already checked and determined to be OK. The following restrictions avoid that problem. - The same parameter labels cannot occur in different nodes of the same ParameterSetDescription. There are two exceptions to this. Nodes that are contained in the cases of a ParameterSwitch or the subnodes of an "exclusive or" are allowed to use the same labels. - If insertion is necessary to make an "exclusive or" node pass validation, then the insertion could make more than one of the possibilities evaluate true. This must be checked for after the insertions occur. The behavior is to throw a Configuration exception if this problem is encountered. (Example: (A && B) ^ (A && C) where C already exists in the ParameterSet but A and B do not. A and B get inserted by the algorithm, because it tries to make the first possibility true when all fail without insertion. Then both parts of the "exclusive or" pass, which is a validation failure). - Another potential problem is that a parameter insertion related to one ParameterDescription could match unrelated wildcards causing other validation requirements to change from being passing to failing or vice versa. This makes it almost impossible to determine if a ParameterSet passes validation. Each time you try to loop through and check, the result of validation could change. To avoid this problem, a list is maintained of the type for all wildcards. Another list is maintained for the type of all parameters. As new items are added we check for collisions. The function that builds the ParameterSetDescription, will throw if this rule is violated. At the moment, the criteria for a collision is matching types between a parameter and a wildcard. (This criteria is overrestrictive. With some additional CPU and code development the restriction could be loosened to parameters that might be injected cannot match the type, trackiness, and wildcard label pattern of any wildcard that requires a match. And further this could not apply to wildcards on different branches of a ParameterSwitch or "exclusive or".) These restrictions have the additional benefit that the things they prohibit would tend to confuse a user trying to configure a module or a module developer writing the code to extract the parameters from a ParameterSet. These rules tend to prohibit bad design. One strategy to avoid problems with wildcard parameters is to add a nested ParameterSet and put the wildcard parameters in the nested ParameterSet. The names and types in a nested ParameterSet will not interfere with names in the containing ParameterSet. */ void checkAndGetLabelsAndTypes(std::set<std::string>& usedLabels, std::set<ParameterTypes>& parameterTypes, std::set<ParameterTypes>& wildcardTypes) const { checkAndGetLabelsAndTypes_(usedLabels, parameterTypes, wildcardTypes); } static void printSpaces(std::ostream& os, int n); protected: virtual void checkAndGetLabelsAndTypes_(std::set<std::string>& usedLabels, std::set<ParameterTypes>& parameterTypes, std::set<ParameterTypes>& wildcardTypes) const = 0; virtual void validate_(ParameterSet& pset, std::set<std::string>& validatedLabels, bool optional) const = 0; virtual void writeCfi_(std::ostream& os, bool optional, bool& startWithComma, int indentation, bool& wroteSomething) const = 0; virtual void print_(std::ostream&, bool /*optional*/, bool /*writeToCfi*/, DocFormatHelper&) const {} virtual bool hasNestedContent_() const { return false; } virtual void printNestedContent_(std::ostream&, bool /*optional*/, DocFormatHelper&) const {} virtual bool exists_(ParameterSet const& pset) const = 0; virtual bool partiallyExists_(ParameterSet const& pset) const = 0; virtual int howManyXORSubNodesExist_(ParameterSet const& pset) const = 0; std::string comment_; }; template <> struct value_ptr_traits<ParameterDescriptionNode> { static ParameterDescriptionNode* clone(ParameterDescriptionNode const* p) { return p->clone(); } static void destroy(ParameterDescriptionNode* p) { delete p; } }; // operator>> --------------------------------------------- std::unique_ptr<ParameterDescriptionCases<bool> > operator>>(bool caseValue, ParameterDescriptionNode const& node); std::unique_ptr<ParameterDescriptionCases<int> > operator>>(int caseValue, ParameterDescriptionNode const& node); std::unique_ptr<ParameterDescriptionCases<std::string> > operator>>(std::string const& caseValue, ParameterDescriptionNode const& node); std::unique_ptr<ParameterDescriptionCases<std::string> > operator>>(char const* caseValue, ParameterDescriptionNode const& node); std::unique_ptr<ParameterDescriptionCases<bool> > operator>>(bool caseValue, std::unique_ptr<ParameterDescriptionNode> node); std::unique_ptr<ParameterDescriptionCases<int> > operator>>(int caseValue, std::unique_ptr<ParameterDescriptionNode> node); std::unique_ptr<ParameterDescriptionCases<std::string> > operator>>(std::string const& caseValue, std::unique_ptr<ParameterDescriptionNode> node); std::unique_ptr<ParameterDescriptionCases<std::string> > operator>>(char const* caseValue, std::unique_ptr<ParameterDescriptionNode> node); // operator&& --------------------------------------------- std::unique_ptr<ParameterDescriptionNode> operator&&(ParameterDescriptionNode const& node_left, ParameterDescriptionNode const& node_right); std::unique_ptr<ParameterDescriptionNode> operator&&(std::unique_ptr<ParameterDescriptionNode> node_left, ParameterDescriptionNode const& node_right); std::unique_ptr<ParameterDescriptionNode> operator&&(ParameterDescriptionNode const& node_left, std::unique_ptr<ParameterDescriptionNode> node_right); std::unique_ptr<ParameterDescriptionNode> operator&&(std::unique_ptr<ParameterDescriptionNode> node_left, std::unique_ptr<ParameterDescriptionNode> node_right); // operator|| --------------------------------------------- std::unique_ptr<ParameterDescriptionNode> operator||(ParameterDescriptionNode const& node_left, ParameterDescriptionNode const& node_right); std::unique_ptr<ParameterDescriptionNode> operator||(std::unique_ptr<ParameterDescriptionNode> node_left, ParameterDescriptionNode const& node_right); std::unique_ptr<ParameterDescriptionNode> operator||(ParameterDescriptionNode const& node_left, std::unique_ptr<ParameterDescriptionNode> node_right); std::unique_ptr<ParameterDescriptionNode> operator||(std::unique_ptr<ParameterDescriptionNode> node_left, std::unique_ptr<ParameterDescriptionNode> node_right); // operator^ --------------------------------------------- std::unique_ptr<ParameterDescriptionNode> operator^(ParameterDescriptionNode const& node_left, ParameterDescriptionNode const& node_right); std::unique_ptr<ParameterDescriptionNode> operator^(std::unique_ptr<ParameterDescriptionNode> node_left, ParameterDescriptionNode const& node_right); std::unique_ptr<ParameterDescriptionNode> operator^(ParameterDescriptionNode const& node_left, std::unique_ptr<ParameterDescriptionNode> node_right); std::unique_ptr<ParameterDescriptionNode> operator^(std::unique_ptr<ParameterDescriptionNode> node_left, std::unique_ptr<ParameterDescriptionNode> node_right); } // namespace edm #endif
1.21875
1
tests/verify_kernel.c
greck2908/vboot
0
1516
/* Copyright (c) 2014 The Chromium OS Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. * * Routines for verifying a kernel or disk image */ #include "2sysincludes.h" #include "2api.h" #include "2common.h" #include "2misc.h" #include "2nvstorage.h" #include "host_common.h" #include "util_misc.h" #include "vboot_api.h" #include "vboot_kernel.h" static uint8_t workbuf[VB2_KERNEL_WORKBUF_RECOMMENDED_SIZE] __attribute__((aligned(VB2_WORKBUF_ALIGN))); static struct vb2_context *ctx; static struct vb2_shared_data *sd; static uint8_t *diskbuf; static LoadKernelParams params; vb2_error_t VbExDiskRead(VbExDiskHandle_t handle, uint64_t lba_start, uint64_t lba_count, void *buffer) { if (handle != (VbExDiskHandle_t)1) return VB2_ERROR_UNKNOWN; if (lba_start >= params.streaming_lba_count) return VB2_ERROR_UNKNOWN; if (lba_start + lba_count > params.streaming_lba_count) return VB2_ERROR_UNKNOWN; memcpy(buffer, diskbuf + lba_start * 512, lba_count * 512); return VB2_SUCCESS; } vb2_error_t VbExDiskWrite(VbExDiskHandle_t handle, uint64_t lba_start, uint64_t lba_count, const void *buffer) { if (handle != (VbExDiskHandle_t)1) return VB2_ERROR_UNKNOWN; if (lba_start >= params.streaming_lba_count) return VB2_ERROR_UNKNOWN; if (lba_start + lba_count > params.streaming_lba_count) return VB2_ERROR_UNKNOWN; memcpy(diskbuf + lba_start * 512, buffer, lba_count * 512); return VB2_SUCCESS; } static void print_help(const char *progname) { printf("\nUsage: %s <disk_image> <kernel.vbpubk>\n\n", progname); } int main(int argc, char *argv[]) { struct vb2_packed_key *kernkey; uint64_t disk_bytes = 0; vb2_error_t rv; if (argc < 3) { print_help(argv[0]); return 1; } /* Load disk file */ /* TODO: is it better to mmap() in the long run? */ diskbuf = ReadFile(argv[1], &disk_bytes); if (!diskbuf) { fprintf(stderr, "Can't read disk file %s\n", argv[1]); return 1; } /* Read public key */ kernkey = vb2_read_packed_key(argv[2]); if (!kernkey) { fprintf(stderr, "Can't read key file %s\n", argv[2]); return 1; } /* Set up params */ params.disk_handle = (VbExDiskHandle_t)1; params.bytes_per_lba = 512; params.streaming_lba_count = disk_bytes / 512; params.gpt_lba_count = params.streaming_lba_count; params.kernel_buffer_size = 16 * 1024 * 1024; params.kernel_buffer = malloc(params.kernel_buffer_size); if (!params.kernel_buffer) { fprintf(stderr, "Can't allocate kernel buffer\n"); return 1; } /* TODO(chromium:441893): support dev-mode flag and external gpt flag */ params.boot_flags = 0; if (vb2api_init(&workbuf, sizeof(workbuf), &ctx)) { fprintf(stderr, "Can't initialize workbuf\n"); return 1; } sd = vb2_get_sd(ctx); /* Copy kernel subkey to workbuf */ { struct vb2_workbuf wb; struct vb2_packed_key *dst; uint32_t kernkey_size = kernkey->key_offset + kernkey->key_size; vb2_workbuf_from_ctx(ctx, &wb); dst = vb2_workbuf_alloc(&wb, kernkey_size); memcpy(dst, kernkey, kernkey_size); vb2_set_workbuf_used(ctx, vb2_offset_of(sd, wb.buf)); sd->kernel_key_offset = vb2_offset_of(sd, dst); sd->kernel_key_size = kernkey_size; } /* * LoadKernel() cares only about VBNV_DEV_BOOT_SIGNED_ONLY, and only in * dev mode. So just use defaults for nv storage. */ vb2_nv_init(ctx); /* Try loading kernel */ rv = LoadKernel(ctx, &params); if (rv != VB2_SUCCESS) { fprintf(stderr, "LoadKernel() failed with code %d\n", rv); return 1; } printf("Found a good kernel.\n"); printf("Partition number: %u\n", params.partition_number); printf("Bootloader address: 0x%" PRIx64 "\n", params.bootloader_address); /* TODO: print other things (partition GUID, shared_data) */ printf("Yaay!\n"); return 0; }
1.125
1
include/dungeon/BaseBSPGen.h
xzrunner/dungeon
0
1524
#pragma once #include <SM_Vector.h> #include <SM_Rect.h> #include <memory> #include <vector> namespace dungeon { class BaseBSPGen { public: BaseBSPGen(const sm::vec2& size, const sm::vec2& split_sz, const sm::vec2& min_sz, uint32_t seed = 0); std::vector<sm::rect> GetAllRooms() const; private: void BuildBSP(const sm::vec2& size, const sm::vec2& split_sz, const sm::vec2& min_sz); void BuildDungeon(const sm::vec2& min_sz); private: enum class SplitType { None, Hori, Vert, }; class Node { public: Node(const sm::rect& r); bool Split(const sm::vec2& split_sz, const sm::vec2& min_sz); private: std::unique_ptr<Node> m_kids[2]; sm::rect m_rect; sm::rect m_room; SplitType m_split = SplitType::None; friend class BaseBSPGen; }; // Node private: std::unique_ptr<Node> m_root = nullptr; uint32_t m_seed = 0; }; // BaseBSPGen }
1.46875
1
HackerRank Problems/Array Reversal/solution.c
Kankona-C/Coding-Questions
14
1532
main(){ int n,arr[1000],i,temp; //datatypes assigned scanf("%d",&n); //reading value for(i=0;i<n;i++){ scanf("%d ",&arr[i]); // reading values and sorring in the array "arr[]" } for(i=0;i<n/2;i++){ temp=arr[i]; //swaping array elements arr[i]=arr[n-i-1]; arr[n-i-1]=temp; } for(i=0;i<n;i++){ printf("%d ",arr[i]); //printing values } return(0); }
2.1875
2
driver/common/objects/as3935_common.c
anaren/AS3935_element_library
0
1540
/** * ---------------------------------------------------------------------------- * Copyright (c) 2016, <NAME>, Inc. * * For more information on licensing, please see Anaren Microwave, Inc's * end user software licensing agreement: EULA.txt. * * ---------------------------------------------------------------------------- * * as3935_common.c - driver interface for the ams AG AS3935 Frankling Lightning * Sensor. * * @version 1.0.0 * @date 19 Sep 2016 * @author Anaren, <EMAIL> * * assumptions * =========== * - The i2c driver provides the proper signaling sequences for read & write * operations. * - The i2c driver meets the timing requirements specified in the AS3935 * datasheet. * * file dependency * =============== * i2c.h : defines the i2c read & write interfaces. * math.h : floating point calculations. * fp_math.h : floating point calculations using fixed point math. Use when math.h not implemented. * * revision history * ================ * ver 1.0.00 : 19 September 2016 * - initial development, replace this line upon release. */ #include "as3935.h" #include "../i2c/i2c.h" #include "../gpio/gpio.h" #include "../generic/generic.h" #include "../pin_mapping.h" // ----------------------------------------------------------------------------- /** * Global data */ static int AS3935_freq = 0; static int AS3935_mode = 0; // ----------------------------------------------------------------------------- /** * Private interface */ // ----------------------------------------------------------------------------- /** * Public interface */ void AS3935_Init() { AS3935_PresetRegisterDefaults(); AS3935_CalibrateRCO(); AS3935_SetAnalogFrontEnd(AIR_AS3935_ANALOG_FRONT_END); AS3935_SetNoiseFloor((0x02<<4)|(0x02<<0)); AS3935_EnableDisturbers(); AS3935_CalibrateLCO(); } /** * Write to specified register on the AS3935. */ void AS3935_WriteReg(uint8_t addr, uint8_t data) { uint8_t writeBytes[2]; writeBytes[0] = addr; writeBytes[1] = data; AIR_I2C_Write(AS3935_I2C_ADDRESS, writeBytes, 2); } /** * Read data from specified register */ uint8_t AS3935_ReadReg(uint8_t addr) { uint8_t writeBytes[1] = {0}; uint8_t readBytes[1] = {0}; AIR_I2C_ComboRead(AS3935_I2C_ADDRESS, writeBytes, 1, readBytes, 1); return readBytes[0]; } /** * Get the estimated distance to the lightning storm in kilometers. * Also resets the contents of the Interrupt register. * Values beyond 40 are out of range. * Values less than 5 mean that the storm is overhead. */ uint8_t AS3935_GetDistanceEstimation() { uint8_t distanceEstimate = (uint8_t)AS3935_ReadReg(AS3935_DIST_ESTI_REG_ADDR); return distanceEstimate & AS3935_DISTEST_MASK; } /** * Calibrate the RC Oscillators automatically. */ void AS3935_CalibrateRCO() { AS3935_WriteReg(AS3935_CALIBR_RCO_REG_ADDR, AS3935_DIRECT_CMD_REG_VALU); } void AS3935_CalibrateLCOIRQHandler() { if (AS3935_mode == 1) { AS3935_freq++; } } /** * */ void AS3935_CalibrateLCO() { int i, n, m = 10000, r = 0; AIR_GPIO_RegisterInterrupt(AS3935_IRQ_PIN, AS3935_CalibrateLCOIRQHandler, AIR_GPIO_TRIGGER_FALLING_EDGE); for(i = 0; i < 0x10; i++) { AS3935_WriteReg(AS3935_DISP_IRQ_REG_ADDR, 0x80 | i); AIR_GENERIC_UDelay(10000); AS3935_freq = 0; AS3935_mode = 1; AIR_GENERIC_UDelay(100000); AS3935_mode = 0; n = abs(AS3935_freq - 3125); if (m > n) { r = i; } else { break; } m = n; } AIR_GPIO_UnregisterInterrupt(AS3935_IRQ_PIN); AS3935_WriteReg(AS3935_DISP_IRQ_REG_ADDR, r); } /** * Sets all registers in default mode */ void AS3935_PresetRegisterDefaults() { AS3935_WriteReg(AS3935_PRESET_DEF_REG_ADDR, AS3935_DIRECT_CMD_REG_VALU); } /* * Set the analog front end and watchdog operating mode. * Refer to as3935.h for possible operating modes. */ void AS3935_SetAnalogFrontEnd(uint8_t mode) { uint8_t newAFESetting; uint8_t currentAFESetting = AS3935_ReadReg(AS3935_PWD_AFEGB_REG_ADDR); currentAFESetting = currentAFESetting & AS3935_AFE_MASK; if (mode == AS3935_AFE_OUTDOOR) { newAFESetting = currentAFESetting & AS3935_AFE_OUTDOOR; AS3935_WriteReg(AS3935_PWD_AFEGB_REG_ADDR, newAFESetting); } if (mode == AS3935_AFE_INDOOR) { newAFESetting = currentAFESetting & AS3935_AFE_OUTDOOR; AS3935_WriteReg(AS3935_PWD_AFEGB_REG_ADDR, newAFESetting); } } /** * Retrieve the current operating mode of the AFE and watchdog. */ uint8_t AS3935_GetAnalogFrontEnd() { return ((uint8_t)AS3935_ReadReg(AS3935_PWD_AFEGB_REG_ADDR) & AS3935_AFE_MASK_2) >> 1; } /** * Disable the disturber detection feature on the AS3935. */ void AS3935_DisableDisturbers() { AS3935_WriteReg(AS3935_MASK_DIST_REG_ADDR, 1); } /** * Enable the disturber detection feature on the AS3935. */ void AS3935_EnableDisturbers() { AS3935_WriteReg(AS3935_MASK_DIST_REG_ADDR, 0); } /** * Get the defined minimum number of lightning events in the last 17 minutes that issue a lightning interrupt. */ uint8_t AS3935_GetMinimumLightnings() { return AS3935_ReadReg(AS3935_MIN_LIGHT_REG_ADDR); } /** * Set the defined minimum number of lightning events in the last 17 minutes that issue a lightning interrupt. */ uint8_t AS3935_SetMinimumLightnings(uint8_t minimumLightning) { AS3935_WriteReg(AS3935_MIN_LIGHT_REG_ADDR, minimumLightning); return AS3935_GetMinimumLightnings(); } /** * Get the defined threshold for the noise floor that triggers an interrupt. */ uint8_t AS3935_GetNoiseFloor() { return AS3935_ReadReg(AS3935_NFLV_WDTH_REG_ADDR); } /** * Set the defined threshold for the noise floor that triggers an interrupt. */ uint8_t AS3935_SetNoiseFloor(int noiseFloor) { AS3935_WriteReg(AS3935_NFLV_WDTH_REG_ADDR, noiseFloor); return AS3935_GetNoiseFloor(); } /** * Read current state of the interrupt register. * Issue a 2 millisecond delay per the datasheet recommendations. */ uint8_t AS3935_ReadInterruptRegister() { return (uint8_t)AS3935_ReadReg(AS3935_MASK_DIST_REG_ADDR); }
1.578125
2
lib/Target/PPU/PPUArgumentUsageInfo.h
chisuhua/llvm
0
1548
//==- PPUArgumentrUsageInfo.h - Function Arg Usage Info -------*- C++ -*-==// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #ifndef LLVM_LIB_TARGET_PPU_PPUARGUMENTUSAGEINFO_H #define LLVM_LIB_TARGET_PPU_PPUARGUMENTUSAGEINFO_H #include "llvm/ADT/DenseMap.h" #include "llvm/CodeGen/Register.h" #include "llvm/IR/Function.h" #include "llvm/Pass.h" namespace llvm { class Function; class raw_ostream; class PPUSubtarget; class TargetMachine; class TargetRegisterClass; class TargetRegisterInfo; struct ArgDescriptor { private: friend struct PPUFunctionArgInfo; friend class PPUArgumentUsageInfo; union { Register Reg; unsigned StackOffset; }; // Bitmask to locate argument within the register. unsigned Mask; bool IsStack : 1; bool IsSet : 1; public: ArgDescriptor(unsigned Val = 0, unsigned Mask = ~0u, bool IsStack = false, bool IsSet = false) : Reg(Val), Mask(Mask), IsStack(IsStack), IsSet(IsSet) {} static ArgDescriptor createRegister(Register Reg, unsigned Mask = ~0u) { return ArgDescriptor(Reg, Mask, false, true); } static ArgDescriptor createStack(Register Reg, unsigned Mask = ~0u) { return ArgDescriptor(Reg, Mask, true, true); } static ArgDescriptor createArg(const ArgDescriptor &Arg, unsigned Mask) { return ArgDescriptor(Arg.Reg, Mask, Arg.IsStack, Arg.IsSet); } bool isSet() const { return IsSet; } explicit operator bool() const { return isSet(); } bool isRegister() const { return !IsStack; } Register getRegister() const { assert(!IsStack); return Reg; } unsigned getStackOffset() const { assert(IsStack); return StackOffset; } unsigned getMask() const { return Mask; } bool isMasked() const { return Mask != ~0u; } void print(raw_ostream &OS, const TargetRegisterInfo *TRI = nullptr) const; }; inline raw_ostream &operator<<(raw_ostream &OS, const ArgDescriptor &Arg) { Arg.print(OS); return OS; } struct PPUFunctionArgInfo { enum PreloadedValue { // SGPRS: PRIVATE_SEGMENT_BUFFER = 0, DISPATCH_PTR = 1, QUEUE_PTR = 2, KERNARG_SEGMENT_PTR = 3, DISPATCH_ID = 4, FLAT_SCRATCH_INIT = 5, WORKGROUP_ID_X = 10, WORKGROUP_ID_Y = 11, WORKGROUP_ID_Z = 12, PRIVATE_SEGMENT_WAVE_BYTE_OFFSET = 14, IMPLICIT_BUFFER_PTR = 15, IMPLICIT_ARG_PTR = 16, // VGPRS: WORKITEM_ID_X = 17, WORKITEM_ID_Y = 18, WORKITEM_ID_Z = 19, FIRST_VGPR_VALUE = WORKITEM_ID_X }; // Kernel input registers setup for the HSA ABI in allocation order. // User SGPRs in kernels // XXX - Can these require argument spills? ArgDescriptor PrivateSegmentBuffer; ArgDescriptor DispatchPtr; ArgDescriptor QueuePtr; ArgDescriptor KernargSegmentPtr; ArgDescriptor DispatchID; ArgDescriptor FlatScratchInit; ArgDescriptor PrivateSegmentSize; // System SGPRs in kernels. ArgDescriptor WorkGroupIDX; ArgDescriptor WorkGroupIDY; ArgDescriptor WorkGroupIDZ; ArgDescriptor WorkGroupInfo; ArgDescriptor PrivateSegmentWaveByteOffset; // Pointer with offset from kernargsegmentptr to where special ABI arguments // are passed to callable functions. ArgDescriptor ImplicitArgPtr; // Input registers for non-HSA ABI ArgDescriptor ImplicitBufferPtr = 0; // VGPRs inputs. These are always v0, v1 and v2 for entry functions. ArgDescriptor WorkItemIDX; ArgDescriptor WorkItemIDY; ArgDescriptor WorkItemIDZ; std::pair<const ArgDescriptor *, const TargetRegisterClass *> getPreloadedValue(PreloadedValue Value) const; }; class PPUArgumentUsageInfo : public ImmutablePass { private: static const PPUFunctionArgInfo ExternFunctionInfo; DenseMap<const Function *, PPUFunctionArgInfo> ArgInfoMap; public: static char ID; PPUArgumentUsageInfo() : ImmutablePass(ID) { } void getAnalysisUsage(AnalysisUsage &AU) const override { AU.setPreservesAll(); } bool doInitialization(Module &M) override; bool doFinalization(Module &M) override; void print(raw_ostream &OS, const Module *M = nullptr) const override; void setFuncArgInfo(const Function &F, const PPUFunctionArgInfo &ArgInfo) { ArgInfoMap[&F] = ArgInfo; } const PPUFunctionArgInfo &lookupFuncArgInfo(const Function &F) const { auto I = ArgInfoMap.find(&F); if (I == ArgInfoMap.end()) { assert(F.isDeclaration()); return ExternFunctionInfo; } return I->second; } }; } // end namespace llvm #endif
1.601563
2
google/cloud/bigtable/internal/logging_instance_admin_client.h
VPeruS/google-cloud-cpp
4
1556
// Copyright 2020 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_BIGTABLE_INTERNAL_LOGGING_INSTANCE_ADMIN_CLIENT_H #define GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_BIGTABLE_INTERNAL_LOGGING_INSTANCE_ADMIN_CLIENT_H #include "google/cloud/bigtable/instance_admin_client.h" #include <memory> #include <string> namespace google { namespace cloud { namespace bigtable { inline namespace BIGTABLE_CLIENT_NS { namespace internal { /** * Implements a logging InstanceAdminClient. * * This class is used by the Cloud Bigtable wrappers to access Cloud Bigtable. * Multiple `bigtable::InstanceAdmin` objects may share a connection via a * single `InstanceAdminClient` object. The `InstanceAdminClient` object is * configured at construction time, this configuration includes the credentials, * access endpoints, default timeouts, and other gRPC configuration options. * This is an interface class because it is also used as a dependency injection * point in some of the tests. * * @par Cost * Applications should avoid unnecessarily creating new objects of type * `InstanceAdminClient`. Creating a new object of this type typically requires * connecting to the Cloud Bigtable servers, and performing the authentication * workflows with Google Cloud Platform. These operations can take many * milliseconds, therefore applications should try to reuse the same * `InstanceAdminClient` instances when possible. */ class LoggingInstanceAdminClient : public google::cloud::bigtable::InstanceAdminClient { public: LoggingInstanceAdminClient( std::shared_ptr<google::cloud::bigtable::InstanceAdminClient> child, google::cloud::TracingOptions options) : child_(std::move(child)), tracing_options_(std::move(options)) {} std::string const& project() const override { return child_->project(); } std::shared_ptr<grpc::Channel> Channel() override { return child_->Channel(); } void reset() override { child_->reset(); } grpc::Status ListInstances( grpc::ClientContext* context, google::bigtable::admin::v2::ListInstancesRequest const& request, google::bigtable::admin::v2::ListInstancesResponse* response) override; grpc::Status CreateInstance( grpc::ClientContext* context, google::bigtable::admin::v2::CreateInstanceRequest const& request, google::longrunning::Operation* response) override; grpc::Status UpdateInstance( grpc::ClientContext* context, google::bigtable::admin::v2::PartialUpdateInstanceRequest const& request, google::longrunning::Operation* response) override; grpc::Status GetOperation( grpc::ClientContext* context, google::longrunning::GetOperationRequest const& request, google::longrunning::Operation* response) override; grpc::Status GetInstance( grpc::ClientContext* context, google::bigtable::admin::v2::GetInstanceRequest const& request, google::bigtable::admin::v2::Instance* response) override; grpc::Status DeleteInstance( grpc::ClientContext* context, google::bigtable::admin::v2::DeleteInstanceRequest const& request, google::protobuf::Empty* response) override; grpc::Status ListClusters( grpc::ClientContext* context, google::bigtable::admin::v2::ListClustersRequest const& request, google::bigtable::admin::v2::ListClustersResponse* response) override; grpc::Status GetCluster( grpc::ClientContext* context, google::bigtable::admin::v2::GetClusterRequest const& request, google::bigtable::admin::v2::Cluster* response) override; grpc::Status DeleteCluster( grpc::ClientContext* context, google::bigtable::admin::v2::DeleteClusterRequest const& request, google::protobuf::Empty* response) override; grpc::Status CreateCluster( grpc::ClientContext* context, google::bigtable::admin::v2::CreateClusterRequest const& request, google::longrunning::Operation* response) override; grpc::Status UpdateCluster( grpc::ClientContext* context, google::bigtable::admin::v2::Cluster const& request, google::longrunning::Operation* response) override; grpc::Status CreateAppProfile( grpc::ClientContext* context, google::bigtable::admin::v2::CreateAppProfileRequest const& request, google::bigtable::admin::v2::AppProfile* response) override; grpc::Status GetAppProfile( grpc::ClientContext* context, google::bigtable::admin::v2::GetAppProfileRequest const& request, google::bigtable::admin::v2::AppProfile* response) override; grpc::Status ListAppProfiles( grpc::ClientContext* context, google::bigtable::admin::v2::ListAppProfilesRequest const& request, google::bigtable::admin::v2::ListAppProfilesResponse* response) override; grpc::Status UpdateAppProfile( grpc::ClientContext* context, google::bigtable::admin::v2::UpdateAppProfileRequest const& request, google::longrunning::Operation* response) override; grpc::Status DeleteAppProfile( grpc::ClientContext* context, google::bigtable::admin::v2::DeleteAppProfileRequest const& request, google::protobuf::Empty* response) override; grpc::Status GetIamPolicy(grpc::ClientContext* context, google::iam::v1::GetIamPolicyRequest const& request, google::iam::v1::Policy* response) override; grpc::Status SetIamPolicy(grpc::ClientContext* context, google::iam::v1::SetIamPolicyRequest const& request, google::iam::v1::Policy* response) override; grpc::Status TestIamPermissions( grpc::ClientContext* context, google::iam::v1::TestIamPermissionsRequest const& request, google::iam::v1::TestIamPermissionsResponse* response) override; std::unique_ptr<grpc::ClientAsyncResponseReaderInterface< google::bigtable::admin::v2::ListInstancesResponse>> AsyncListInstances( grpc::ClientContext* context, google::bigtable::admin::v2::ListInstancesRequest const& request, grpc::CompletionQueue* cq) override; std::unique_ptr<grpc::ClientAsyncResponseReaderInterface< google::bigtable::admin::v2::Instance>> AsyncGetInstance( grpc::ClientContext* context, google::bigtable::admin::v2::GetInstanceRequest const& request, grpc::CompletionQueue* cq) override; std::unique_ptr<grpc::ClientAsyncResponseReaderInterface< google::bigtable::admin::v2::Cluster>> AsyncGetCluster(grpc::ClientContext* context, google::bigtable::admin::v2::GetClusterRequest const& request, grpc::CompletionQueue* cq) override; std::unique_ptr< grpc::ClientAsyncResponseReaderInterface<google::protobuf::Empty>> AsyncDeleteCluster( grpc::ClientContext* context, google::bigtable::admin::v2::DeleteClusterRequest const& request, grpc::CompletionQueue* cq) override; std::unique_ptr< grpc::ClientAsyncResponseReaderInterface<google::longrunning::Operation>> AsyncCreateCluster( grpc::ClientContext* context, google::bigtable::admin::v2::CreateClusterRequest const& request, grpc::CompletionQueue* cq) override; std::unique_ptr< grpc::ClientAsyncResponseReaderInterface<google::longrunning::Operation>> AsyncCreateInstance( grpc::ClientContext* context, google::bigtable::admin::v2::CreateInstanceRequest const& request, grpc::CompletionQueue* cq) override; std::unique_ptr< grpc::ClientAsyncResponseReaderInterface<google::longrunning::Operation>> AsyncUpdateInstance( grpc::ClientContext* context, google::bigtable::admin::v2::PartialUpdateInstanceRequest const& request, grpc::CompletionQueue* cq) override; std::unique_ptr< grpc::ClientAsyncResponseReaderInterface<google::longrunning::Operation>> AsyncUpdateCluster(grpc::ClientContext* context, google::bigtable::admin::v2::Cluster const& request, grpc::CompletionQueue* cq) override; std::unique_ptr< grpc::ClientAsyncResponseReaderInterface<google::protobuf::Empty>> AsyncDeleteInstance( grpc::ClientContext* context, google::bigtable::admin::v2::DeleteInstanceRequest const& request, grpc::CompletionQueue* cq) override; std::unique_ptr<grpc::ClientAsyncResponseReaderInterface< google::bigtable::admin::v2::ListClustersResponse>> AsyncListClusters( grpc::ClientContext* context, google::bigtable::admin::v2::ListClustersRequest const& request, grpc::CompletionQueue* cq) override; std::unique_ptr<grpc::ClientAsyncResponseReaderInterface< google::bigtable::admin::v2::AppProfile>> AsyncGetAppProfile( grpc::ClientContext* context, google::bigtable::admin::v2::GetAppProfileRequest const& request, grpc::CompletionQueue* cq) override; std::unique_ptr< grpc::ClientAsyncResponseReaderInterface<google::protobuf::Empty>> AsyncDeleteAppProfile( grpc::ClientContext* context, google::bigtable::admin::v2::DeleteAppProfileRequest const& request, grpc::CompletionQueue* cq) override; std::unique_ptr<grpc::ClientAsyncResponseReaderInterface< google::bigtable::admin::v2::AppProfile>> AsyncCreateAppProfile( grpc::ClientContext* context, google::bigtable::admin::v2::CreateAppProfileRequest const& request, grpc::CompletionQueue* cq) override; std::unique_ptr< grpc::ClientAsyncResponseReaderInterface<google::longrunning::Operation>> AsyncUpdateAppProfile( grpc::ClientContext* context, google::bigtable::admin::v2::UpdateAppProfileRequest const& request, grpc::CompletionQueue* cq) override; std::unique_ptr<grpc::ClientAsyncResponseReaderInterface< google::bigtable::admin::v2::ListAppProfilesResponse>> AsyncListAppProfiles( grpc::ClientContext* context, google::bigtable::admin::v2::ListAppProfilesRequest const& request, grpc::CompletionQueue* cq) override; std::unique_ptr< grpc::ClientAsyncResponseReaderInterface<google::iam::v1::Policy>> AsyncGetIamPolicy(grpc::ClientContext* context, google::iam::v1::GetIamPolicyRequest const& request, grpc::CompletionQueue* cq) override; std::unique_ptr< grpc::ClientAsyncResponseReaderInterface<google::iam::v1::Policy>> AsyncSetIamPolicy(grpc::ClientContext* context, google::iam::v1::SetIamPolicyRequest const& request, grpc::CompletionQueue* cq) override; std::unique_ptr<grpc::ClientAsyncResponseReaderInterface< google::iam::v1::TestIamPermissionsResponse>> AsyncTestIamPermissions( grpc::ClientContext* context, google::iam::v1::TestIamPermissionsRequest const& request, grpc::CompletionQueue* cq) override; std::unique_ptr< grpc::ClientAsyncResponseReaderInterface<google::longrunning::Operation>> AsyncGetOperation(grpc::ClientContext* context, google::longrunning::GetOperationRequest const& request, grpc::CompletionQueue* cq) override; private: google::cloud::BackgroundThreadsFactory BackgroundThreadsFactory() override { return child_->BackgroundThreadsFactory(); } std::shared_ptr<google::cloud::bigtable::InstanceAdminClient> child_; google::cloud::TracingOptions tracing_options_; }; } // namespace internal } // namespace BIGTABLE_CLIENT_NS } // namespace bigtable } // namespace cloud } // namespace google #endif // GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_BIGTABLE_INTERNAL_LOGGING_INSTANCE_ADMIN_CLIENT_H
1.132813
1
TgVoip.h
Meteorite/libtgvoip
69
1564
#ifndef __TGVOIP_H #define __TGVOIP_H #include <functional> #include <vector> #include <string> #include <memory> struct TgVoipProxy { std::string host; uint16_t port = 0; std::string login; std::string password; }; enum class TgVoipEndpointType { Inet, Lan, UdpRelay, TcpRelay }; struct TgVoipEdpointHost { std::string ipv4; std::string ipv6; }; struct TgVoipEndpoint { int64_t endpointId = 0; TgVoipEdpointHost host; uint16_t port = 0; TgVoipEndpointType type = TgVoipEndpointType(); unsigned char peerTag[16] = { 0 }; }; enum class TgVoipNetworkType { Unknown, Gprs, Edge, ThirdGeneration, Hspa, Lte, WiFi, Ethernet, OtherHighSpeed, OtherLowSpeed, OtherMobile, Dialup }; enum class TgVoipDataSaving { Never, Mobile, Always }; struct TgVoipPersistentState { std::vector<uint8_t> value; }; #ifdef TGVOIP_USE_CUSTOM_CRYPTO struct TgVoipCrypto { void (*rand_bytes)(uint8_t* buffer, size_t length) = nullptr; void (*sha1)(uint8_t* msg, size_t length, uint8_t* output) = nullptr; void (*sha256)(uint8_t* msg, size_t length, uint8_t* output) = nullptr; void (*aes_ige_encrypt)(uint8_t* in, uint8_t* out, size_t length, uint8_t* key, uint8_t* iv) = nullptr; void (*aes_ige_decrypt)(uint8_t* in, uint8_t* out, size_t length, uint8_t* key, uint8_t* iv) = nullptr; void (*aes_ctr_encrypt)(uint8_t* inout, size_t length, uint8_t* key, uint8_t* iv, uint8_t* ecount, uint32_t* num) = nullptr; void (*aes_cbc_encrypt)(uint8_t* in, uint8_t* out, size_t length, uint8_t* key, uint8_t* iv) = nullptr; void (*aes_cbc_decrypt)(uint8_t* in, uint8_t* out, size_t length, uint8_t* key, uint8_t* iv) = nullptr; }; #endif struct TgVoipConfig { double initializationTimeout = 0.; double receiveTimeout = 0.; TgVoipDataSaving dataSaving = TgVoipDataSaving(); bool enableP2P = false; bool enableAEC = false; bool enableNS = false; bool enableAGC = false; bool enableVolumeControl = false; bool enableCallUpgrade = false; #ifndef _WIN32 std::string logPath; #else std::wstring logPath; #endif int maxApiLayer = 0; }; struct TgVoipEncryptionKey { std::vector<uint8_t> value; bool isOutgoing = false; }; enum class TgVoipState { WaitInit, WaitInitAck, Established, Failed, Reconnecting }; struct TgVoipTrafficStats { uint64_t bytesSentWifi = 0; uint64_t bytesReceivedWifi = 0; uint64_t bytesSentMobile = 0; uint64_t bytesReceivedMobile = 0; }; struct TgVoipFinalState { TgVoipPersistentState persistentState; std::string debugLog; TgVoipTrafficStats trafficStats; bool isRatingSuggested = false; }; struct TgVoipAudioDataCallbacks { std::function<void(int16_t*, size_t)> input; std::function<void(int16_t*, size_t)> output; std::function<void(int16_t*, size_t)> preprocessed; }; class TgVoip { protected: TgVoip() = default; public: static void setLoggingFunction(std::function<void(std::string const &)> loggingFunction); static void setGlobalServerConfig(std::string const &serverConfig); static int getConnectionMaxLayer(); static std::string getVersion(); static std::unique_ptr<TgVoip> makeInstance( TgVoipConfig const &config, TgVoipPersistentState const &persistentState, std::vector<TgVoipEndpoint> const &endpoints, TgVoipProxy const *proxy, TgVoipNetworkType initialNetworkType, TgVoipEncryptionKey const &encryptionKey #ifdef TGVOIP_USE_CUSTOM_CRYPTO , TgVoipCrypto const &crypto #endif #ifdef TGVOIP_USE_CALLBACK_AUDIO_IO , TgVoipAudioDataCallbacks const &audioDataCallbacks #endif ); virtual ~TgVoip(); virtual void setNetworkType(TgVoipNetworkType networkType) = 0; virtual void setMuteMicrophone(bool muteMicrophone) = 0; virtual void setAudioOutputGainControlEnabled(bool enabled) = 0; virtual void setEchoCancellationStrength(int strength) = 0; virtual void setAudioInputDevice(std::string id) = 0; virtual void setAudioOutputDevice(std::string id) = 0; virtual void setInputVolume(float level) = 0; virtual void setOutputVolume(float level) = 0; virtual void setAudioOutputDuckingEnabled(bool enabled) = 0; virtual std::string getLastError() = 0; virtual std::string getDebugInfo() = 0; virtual int64_t getPreferredRelayId() = 0; virtual TgVoipTrafficStats getTrafficStats() = 0; virtual TgVoipPersistentState getPersistentState() = 0; virtual void setOnStateUpdated(std::function<void(TgVoipState)> onStateUpdated) = 0; virtual void setOnSignalBarsUpdated(std::function<void(int)> onSignalBarsUpdated) = 0; virtual TgVoipFinalState stop() = 0; }; #endif
1.453125
1
src/ucp/tag/tag_recv.c
yqin/ucx
1
1572
/** * Copyright (C) Mellanox Technologies Ltd. 2001-2015. ALL RIGHTS RESERVED. * * See file LICENSE for terms. */ #include "eager.h" #include "rndv.h" #include "tag_match.inl" #include "offload.h" #include <ucp/core/ucp_worker.h> #include <ucp/core/ucp_request.inl> #include <ucs/datastruct/mpool.inl> #include <ucs/datastruct/queue.h> static UCS_F_ALWAYS_INLINE void ucp_tag_recv_request_completed(ucp_request_t *req, ucs_status_t status, ucp_tag_recv_info_t *info, const char *function) { ucs_trace_req("%s returning completed request %p (%p) stag 0x%"PRIx64" len %zu, %s", function, req, req + 1, info->sender_tag, info->length, ucs_status_string(status)); req->status = status; if ((req->flags |= UCP_REQUEST_FLAG_COMPLETED) & UCP_REQUEST_FLAG_RELEASED) { ucp_request_put(req); } UCS_PROFILE_REQUEST_EVENT(req, "complete_recv", 0); } static UCS_F_ALWAYS_INLINE void ucp_tag_recv_common(ucp_worker_h worker, void *buffer, size_t count, uintptr_t datatype, ucp_tag_t tag, ucp_tag_t tag_mask, ucp_request_t *req, uint32_t req_flags, ucp_tag_recv_callback_t cb, ucp_recv_desc_t *rdesc, const char *debug_name) { unsigned common_flags = UCP_REQUEST_FLAG_RECV | UCP_REQUEST_FLAG_EXPECTED; ucp_eager_first_hdr_t *eagerf_hdr; ucp_request_queue_t *req_queue; uct_memory_type_t mem_type; size_t hdr_len, recv_len; ucs_status_t status; uint64_t msg_id; ucp_trace_req(req, "%s buffer %p dt 0x%lx count %zu tag %"PRIx64"/%"PRIx64, debug_name, buffer, datatype, count, tag, tag_mask); /* First, check the fast path case - single fragment * in this case avoid initializing most of request fields * */ if (ucs_likely((rdesc != NULL) && (rdesc->flags & UCP_RECV_DESC_FLAG_EAGER_ONLY))) { UCS_PROFILE_REQUEST_EVENT(req, "eager_only_match", 0); UCP_WORKER_STAT_EAGER_MSG(worker, rdesc->flags); UCP_WORKER_STAT_EAGER_CHUNK(worker, UNEXP); if (ucs_unlikely(rdesc->flags & UCP_RECV_DESC_FLAG_EAGER_SYNC)) { ucp_tag_eager_sync_send_ack(worker, rdesc + 1, rdesc->flags); } req->flags = UCP_REQUEST_FLAG_RECV | req_flags; hdr_len = rdesc->payload_offset; recv_len = rdesc->length - hdr_len; req->recv.tag.info.sender_tag = ucp_rdesc_get_tag(rdesc); req->recv.tag.info.length = recv_len; ucp_memory_type_detect_mds(worker->context, buffer, recv_len, &mem_type); status = ucp_dt_unpack_only(worker, buffer, count, datatype, mem_type, (void*)(rdesc + 1) + hdr_len, recv_len, 1); ucp_recv_desc_release(rdesc); if (req_flags & UCP_REQUEST_FLAG_CALLBACK) { cb(req + 1, status, &req->recv.tag.info); } ucp_tag_recv_request_completed(req, status, &req->recv.tag.info, debug_name); return; } /* Initialize receive request */ req->status = UCS_OK; req->recv.worker = worker; req->recv.buffer = buffer; req->recv.datatype = datatype; ucp_dt_recv_state_init(&req->recv.state, buffer, datatype, count); if (!UCP_DT_IS_CONTIG(datatype)) { common_flags |= UCP_REQUEST_FLAG_BLOCK_OFFLOAD; } req->flags = common_flags | req_flags; req->recv.length = ucp_dt_length(datatype, count, buffer, &req->recv.state); ucp_memory_type_detect_mds(worker->context, buffer, req->recv.length, &mem_type); req->recv.mem_type = mem_type; req->recv.tag.tag = tag; req->recv.tag.tag_mask = tag_mask; req->recv.tag.cb = cb; if (ucs_log_is_enabled(UCS_LOG_LEVEL_TRACE_REQ)) { req->recv.tag.info.sender_tag = 0; } if (ucs_unlikely(rdesc == NULL)) { /* If not found on unexpected, wait until it arrives. * If was found but need this receive request for later completion, save it */ req_queue = ucp_tag_exp_get_queue(&worker->tm, tag, tag_mask); /* If offload supported, post this tag to transport as well. * TODO: need to distinguish the cases when posting is not needed. */ ucp_tag_offload_try_post(worker, req, req_queue); ucp_tag_exp_push(&worker->tm, req_queue, req); ucs_trace_req("%s returning expected request %p (%p)", debug_name, req, req + 1); return; } /* Check rendezvous case */ if (ucs_unlikely(rdesc->flags & UCP_RECV_DESC_FLAG_RNDV)) { ucp_rndv_matched(worker, req, (void*)(rdesc + 1)); UCP_WORKER_STAT_RNDV(worker, UNEXP); ucp_recv_desc_release(rdesc); return; } if (ucs_unlikely(rdesc->flags & UCP_RECV_DESC_FLAG_EAGER_SYNC)) { ucp_tag_eager_sync_send_ack(worker, rdesc + 1, rdesc->flags); } UCP_WORKER_STAT_EAGER_MSG(worker, rdesc->flags); ucs_assert(rdesc->flags & UCP_RECV_DESC_FLAG_EAGER); eagerf_hdr = (void*)(rdesc + 1); req->recv.tag.info.sender_tag = ucp_rdesc_get_tag(rdesc); req->recv.tag.info.length = req->recv.tag.remaining = eagerf_hdr->total_len; /* process first fragment */ UCP_WORKER_STAT_EAGER_CHUNK(worker, UNEXP); msg_id = eagerf_hdr->msg_id; status = ucp_tag_recv_request_process_rdesc(req, rdesc, 0); ucs_assert(status == UCS_INPROGRESS); /* process additional fragments */ ucp_tag_frag_list_process_queue(&worker->tm, req, msg_id UCS_STATS_ARG(UCP_WORKER_STAT_TAG_RX_EAGER_CHUNK_UNEXP)); } UCS_PROFILE_FUNC(ucs_status_t, ucp_tag_recv_nbr, (worker, buffer, count, datatype, tag, tag_mask, request), ucp_worker_h worker, void *buffer, size_t count, uintptr_t datatype, ucp_tag_t tag, ucp_tag_t tag_mask, void *request) { ucp_request_t *req = (ucp_request_t *)request - 1; ucp_recv_desc_t *rdesc; UCP_CONTEXT_CHECK_FEATURE_FLAGS(worker->context, UCP_FEATURE_TAG, return UCS_ERR_INVALID_PARAM); UCP_WORKER_THREAD_CS_ENTER_CONDITIONAL(worker); rdesc = ucp_tag_unexp_search(&worker->tm, tag, tag_mask, 1, "recv_nbr"); ucp_tag_recv_common(worker, buffer, count, datatype, tag, tag_mask, req, UCP_REQUEST_DEBUG_FLAG_EXTERNAL, NULL, rdesc, "recv_nbr"); UCP_WORKER_THREAD_CS_EXIT_CONDITIONAL(worker); return UCS_OK; } UCS_PROFILE_FUNC(ucs_status_ptr_t, ucp_tag_recv_nb, (worker, buffer, count, datatype, tag, tag_mask, cb), ucp_worker_h worker, void *buffer, size_t count, uintptr_t datatype, ucp_tag_t tag, ucp_tag_t tag_mask, ucp_tag_recv_callback_t cb) { ucp_recv_desc_t *rdesc; ucs_status_ptr_t ret; ucp_request_t *req; UCP_CONTEXT_CHECK_FEATURE_FLAGS(worker->context, UCP_FEATURE_TAG, return UCS_STATUS_PTR(UCS_ERR_INVALID_PARAM)); UCP_WORKER_THREAD_CS_ENTER_CONDITIONAL(worker); req = ucp_request_get(worker); if (ucs_likely(req != NULL)) { rdesc = ucp_tag_unexp_search(&worker->tm, tag, tag_mask, 1, "recv_nb"); ucp_tag_recv_common(worker, buffer, count, datatype, tag, tag_mask, req, UCP_REQUEST_FLAG_CALLBACK, cb, rdesc,"recv_nb"); ret = req + 1; } else { ret = UCS_STATUS_PTR(UCS_ERR_NO_MEMORY); } UCP_WORKER_THREAD_CS_EXIT_CONDITIONAL(worker); return ret; } UCS_PROFILE_FUNC(ucs_status_ptr_t, ucp_tag_msg_recv_nb, (worker, buffer, count, datatype, message, cb), ucp_worker_h worker, void *buffer, size_t count, uintptr_t datatype, ucp_tag_message_h message, ucp_tag_recv_callback_t cb) { ucp_recv_desc_t *rdesc = message; ucs_status_ptr_t ret; ucp_request_t *req; UCP_CONTEXT_CHECK_FEATURE_FLAGS(worker->context, UCP_FEATURE_TAG, return UCS_STATUS_PTR(UCS_ERR_INVALID_PARAM)); UCP_WORKER_THREAD_CS_ENTER_CONDITIONAL(worker); req = ucp_request_get(worker); if (ucs_likely(req != NULL)) { ucp_tag_recv_common(worker, buffer, count, datatype, ucp_rdesc_get_tag(rdesc), UCP_TAG_MASK_FULL, req, UCP_REQUEST_FLAG_CALLBACK, cb, rdesc, "msg_recv_nb"); ret = req + 1; } else { ret = UCS_STATUS_PTR(UCS_ERR_NO_MEMORY); } UCP_WORKER_THREAD_CS_EXIT_CONDITIONAL(worker); return ret; }
1.195313
1
external/mysql_connector/unittest/libmysql/logs.c
wangsun1983/Obotcha
27
1580
/* Copyright (C) 2008 Sun Microsystems, 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "my_test.h" static int enable_general_log(MYSQL *mysql, int truncate) { int rc; rc= mysql_query(mysql, "set @save_global_general_log=@@global.general_log"); check_mysql_rc(rc, mysql); rc= mysql_query(mysql, "set @@global.general_log=on"); check_mysql_rc(rc, mysql); if (truncate) { rc= mysql_query(mysql, "truncate mysql.general_log"); check_mysql_rc(rc, mysql); } return OK; } static int restore_general_log(MYSQL *mysql) { int rc; rc= mysql_query(mysql, "set @@global.general_log=@save_global_general_log"); check_mysql_rc(rc, mysql); return OK; } /* Test update/binary logs */ static int test_logs(MYSQL *mysql) { MYSQL_STMT *stmt; MYSQL_BIND my_bind[2]; char data[255]; ulong length; int rc; short id; rc= mysql_query(mysql, "DROP TABLE IF EXISTS test_logs"); check_mysql_rc(rc, mysql); rc= mysql_query(mysql, "CREATE TABLE test_logs(id smallint, name varchar(20))"); check_mysql_rc(rc, mysql); strcpy((char *)data, "INSERT INTO test_logs VALUES(?, ?)"); stmt= mysql_stmt_init(mysql); FAIL_IF(!stmt, mysql_error(mysql)); rc= mysql_stmt_prepare(stmt, data, strlen(data)); check_stmt_rc(rc, stmt); memset(my_bind, '\0', sizeof(my_bind)); my_bind[0].buffer_type= MYSQL_TYPE_SHORT; my_bind[0].buffer= (void *)&id; my_bind[1].buffer_type= MYSQL_TYPE_STRING; my_bind[1].buffer= (void *)&data; my_bind[1].buffer_length= 255; my_bind[1].length= &length; id= 9876; strcpy((char *)data, "MySQL - Open Source Database"); length= strlen(data); rc= mysql_stmt_bind_param(stmt, my_bind); check_stmt_rc(rc, stmt); rc= mysql_stmt_execute(stmt); check_stmt_rc(rc, stmt); strcpy((char *)data, "'"); length= 1; rc= mysql_stmt_execute(stmt); check_stmt_rc(rc, stmt); strcpy((char *)data, "\""); length= 1; rc= mysql_stmt_execute(stmt); check_stmt_rc(rc, stmt); strcpy((char *)data, "my\'sql\'"); length= strlen(data); rc= mysql_stmt_execute(stmt); check_stmt_rc(rc, stmt); strcpy((char *)data, "my\"sql\""); length= strlen(data); rc= mysql_stmt_execute(stmt); check_stmt_rc(rc, stmt); mysql_stmt_close(stmt); strcpy((char *)data, "INSERT INTO test_logs VALUES(20, 'mysql')"); stmt= mysql_stmt_init(mysql); FAIL_IF(!stmt, mysql_error(mysql)); rc= mysql_stmt_prepare(stmt, data, strlen(data)); check_stmt_rc(rc, stmt); rc= mysql_stmt_execute(stmt); check_stmt_rc(rc, stmt); rc= mysql_stmt_execute(stmt); check_stmt_rc(rc, stmt); mysql_stmt_close(stmt); strcpy((char *)data, "SELECT * FROM test_logs WHERE id=?"); stmt= mysql_stmt_init(mysql); FAIL_IF(!stmt, mysql_error(mysql)); rc= mysql_stmt_prepare(stmt, data, strlen(data)); check_stmt_rc(rc, stmt); rc= mysql_stmt_bind_param(stmt, my_bind); check_stmt_rc(rc, stmt); rc= mysql_stmt_execute(stmt); check_stmt_rc(rc, stmt); my_bind[1].buffer_length= 255; rc= mysql_stmt_bind_result(stmt, my_bind); check_stmt_rc(rc, stmt); rc= mysql_stmt_fetch(stmt); check_stmt_rc(rc, stmt); FAIL_UNLESS(id == 9876, "id != 9876"); FAIL_UNLESS(length == 19 || length == 20, "Invalid Length"); /* Due to VARCHAR(20) */ FAIL_UNLESS(strncmp(data, "MySQL - Open Source", 19) == 0, "data != 'MySQL - Open Source'"); rc= mysql_stmt_fetch(stmt); check_stmt_rc(rc, stmt); FAIL_UNLESS(length == 1, "length != 1"); FAIL_UNLESS(strcmp(data, "'") == 0, "data != '''"); rc= mysql_stmt_fetch(stmt); check_stmt_rc(rc, stmt); FAIL_UNLESS(length == 1, "length != 1"); FAIL_UNLESS(strcmp(data, "\"") == 0, "data != '\"'"); rc= mysql_stmt_fetch(stmt); check_stmt_rc(rc, stmt); FAIL_UNLESS(length == 7, "length != 7"); FAIL_UNLESS(strcmp(data, "my\'sql\'") == 0, "data != my'sql'"); rc= mysql_stmt_fetch(stmt); check_stmt_rc(rc, stmt); FAIL_UNLESS(length == 7, "length != 7"); rc= mysql_stmt_fetch(stmt); FAIL_UNLESS(rc == MYSQL_NO_DATA, "rc != MYSQL_NO_DATA"); mysql_stmt_close(stmt); rc= mysql_query(mysql, "DROP TABLE test_logs"); check_mysql_rc(rc, mysql); return OK; } struct my_tests_st my_tests[] = { {"test_logs", test_logs, TEST_CONNECTION_DEFAULT, 0, NULL , NULL}, {NULL, NULL, 0, 0, NULL, NULL} }; int main(int argc, char **argv) { if (argc > 1) get_options(&argc, &argv); get_envvars(); run_tests(my_tests); return(exit_status()); }
1.320313
1
SnakeGame/Food.h
yebeman/SnakeGame
0
1588
#ifndef FOOD_H #define FOOD_H #include "SDL.h" #include <string> #include <vector> class Snake; class Powerup; class BodyPart; class Food { private: SDL_Surface* texture; int lifeTime; Snake* snake1; bool PositionFree( Powerup* powerup1 ); public: Food( Snake* _snake1 ); ~Food(); int X; int Y; void NewPosition( Powerup* powerup1 ); void Update( Powerup* powerup1 ); void Render( SDL_Surface* destSurface ); }; #endif
1.140625
1
ToolKit/include/efi110/efiDebugPort.h
kontais/EFI-MIPS
11
1596
/*++ Copyright (c) 1999 - 2002 Intel Corporation. All rights reserved This software and associated documentation (if any) is furnished under a license and may only be used or copied in accordance with the terms of the license. Except as permitted by such license, no part of this software or documentation may be reproduced, stored in a retrieval system, or transmitted in any form or by any means without the express written consent of Intel Corporation. Module Name: DebugPort.h Abstract: --*/ #ifndef _DEBUG_PORT_H_ #define _DEBUG_PORT_H_ //#include "EfiApi.h" // // DebugPortIo protocol {EBA4E8D2-3858-41EC-A281-2647BA9660D0} // #define EFI_DEBUGPORT_PROTOCOL_GUID \ { 0xEBA4E8D2, 0x3858, 0x41EC, 0xA2, 0x81, 0x26, 0x47, 0xBA, 0x96, 0x60, 0xD0 } extern EFI_GUID DebugPortProtocol; EFI_FORWARD_DECLARATION (EFI_DEBUGPORT_PROTOCOL); // // DebugPort member functions // typedef EFI_STATUS (EFIAPI *EFI_DEBUGPORT_RESET) ( IN EFI_DEBUGPORT_PROTOCOL *This ); typedef EFI_STATUS (EFIAPI *EFI_DEBUGPORT_WRITE) ( IN EFI_DEBUGPORT_PROTOCOL *This, IN UINT32 Timeout, IN OUT UINTN *BufferSize, IN VOID *Buffer ); typedef EFI_STATUS (EFIAPI *EFI_DEBUGPORT_READ) ( IN EFI_DEBUGPORT_PROTOCOL *This, IN UINT32 Timeout, IN OUT UINTN *BufferSize, OUT VOID *Buffer ); typedef EFI_STATUS (EFIAPI *EFI_DEBUGPORT_POLL) ( IN EFI_DEBUGPORT_PROTOCOL *This ); // // DebugPort protocol definition // struct _EFI_DEBUGPORT_PROTOCOL { EFI_DEBUGPORT_RESET Reset; EFI_DEBUGPORT_WRITE Write; EFI_DEBUGPORT_READ Read; EFI_DEBUGPORT_POLL Poll; } ; // // DEBUGPORT variable definitions... // #define EFI_DEBUGPORT_VARIABLE_NAME L"DEBUGPORT" #define EFI_DEBUGPORT_VARIABLE_GUID EFI_DEBUGPORT_PROTOCOL_GUID #define gEfiDebugPortVariableGuid DebugPortProtocol // // DebugPort device path definitions... // #define DEVICE_PATH_MESSAGING_DEBUGPORT EFI_DEBUGPORT_PROTOCOL_GUID #define gEfiDebugPortDevicePathGuid DebugPortProtocol typedef struct { EFI_DEVICE_PATH_PROTOCOL Header; EFI_GUID Guid; } DEBUGPORT_DEVICE_PATH; #endif /* _DEBUG_PORT_H_ */
1
1